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/utils/network.py
natural_ipv4_netmask
python
def natural_ipv4_netmask(ip, fmt='prefixlen'): ''' Returns the "natural" mask of an IPv4 address ''' bits = _ipv4_to_bits(ip) if bits.startswith('11'): mask = '24' elif bits.startswith('1'): mask = '16' else: mask = '8' if fmt == 'netmask': return cidr_to_ipv4_netmask(mask) else: return '/' + mask
Returns the "natural" mask of an IPv4 address
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/network.py#L576-L592
[ "def _ipv4_to_bits(ipaddr):\n '''\n Accepts an IPv4 dotted quad and returns a string representing its binary\n counterpart\n '''\n return ''.join([bin(int(x))[2:].rjust(8, '0') for x in ipaddr.split('.')])\n", "def cidr_to_ipv4_netmask(cidr_bits):\n '''\n Returns an IPv4 netmask\n '''\n try:\n cidr_bits = int(cidr_bits)\n if not 1 <= cidr_bits <= 32:\n return ''\n except ValueError:\n return ''\n\n netmask = ''\n for idx in range(4):\n if idx:\n netmask += '.'\n if cidr_bits >= 8:\n netmask += '255'\n cidr_bits -= 8\n else:\n netmask += '{0:d}'.format(256 - (2 ** (8 - cidr_bits)))\n cidr_bits = 0\n return netmask\n" ]
# -*- coding: utf-8 -*- ''' Define some generic socket functions for network modules ''' # Import python libs from __future__ import absolute_import, unicode_literals, print_function import itertools import os import re import types import socket import logging import platform import random import subprocess from string import ascii_letters, digits # Import 3rd-party libs from salt.ext import six from salt.ext.six.moves import range # pylint: disable=import-error,redefined-builtin # Attempt to import wmi try: import wmi import salt.utils.winapi except ImportError: pass # Import salt libs import salt.utils.args import salt.utils.files import salt.utils.path import salt.utils.platform import salt.utils.stringutils import salt.utils.zeromq from salt._compat import ipaddress from salt.exceptions import SaltClientError, SaltSystemExit from salt.utils.decorators.jinja import jinja_filter from salt.utils.versions import LooseVersion # inet_pton does not exist in Windows, this is a workaround if salt.utils.platform.is_windows(): from salt.ext import win_inet_pton # pylint: disable=unused-import log = logging.getLogger(__name__) try: import ctypes import ctypes.util libc = ctypes.cdll.LoadLibrary(ctypes.util.find_library("c")) res_init = libc.__res_init except (ImportError, OSError, AttributeError, TypeError): pass # pylint: disable=C0103 def sanitize_host(host): ''' Sanitize host string. https://tools.ietf.org/html/rfc1123#section-2.1 ''' RFC952_characters = ascii_letters + digits + ".-" return "".join([c for c in host[0:255] if c in RFC952_characters]) def isportopen(host, port): ''' Return status of a port ''' if not 1 <= int(port) <= 65535: return False sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) out = sock.connect_ex((sanitize_host(host), int(port))) return out def host_to_ips(host): ''' Returns a list of IP addresses of a given hostname or None if not found. ''' ips = [] try: for family, socktype, proto, canonname, sockaddr in socket.getaddrinfo( host, 0, socket.AF_UNSPEC, socket.SOCK_STREAM): if family == socket.AF_INET: ip, port = sockaddr elif family == socket.AF_INET6: ip, port, flow_info, scope_id = sockaddr ips.append(ip) if not ips: ips = None except Exception: ips = None return ips def _generate_minion_id(): ''' Get list of possible host names and convention names. :return: ''' # There are three types of hostnames: # 1. Network names. How host is accessed from the network. # 2. Host aliases. They might be not available in all the network or only locally (/etc/hosts) # 3. Convention names, an internal nodename. class DistinctList(list): ''' List, which allows one to append only distinct objects. Needs to work on Python 2.6, because of collections.OrderedDict only since 2.7 version. Override 'filter()' for custom filtering. ''' localhost_matchers = [r'localhost.*', r'ip6-.*', r'127[.]\d', r'0\.0\.0\.0', r'::1.*', r'ipv6-.*', r'fe00::.*', r'fe02::.*', r'1.0.0.*.ip6.arpa'] def append(self, p_object): if p_object and p_object not in self and not self.filter(p_object): super(DistinctList, self).append(p_object) return self def extend(self, iterable): for obj in iterable: self.append(obj) return self def filter(self, element): 'Returns True if element needs to be filtered' for rgx in self.localhost_matchers: if re.match(rgx, element): return True def first(self): return self and self[0] or None hostname = socket.gethostname() hosts = DistinctList().append( salt.utils.stringutils.to_unicode(socket.getfqdn(salt.utils.stringutils.to_bytes(hostname))) ).append(platform.node()).append(hostname) if not hosts: try: for a_nfo in socket.getaddrinfo(hosts.first() or 'localhost', None, socket.AF_INET, socket.SOCK_RAW, socket.IPPROTO_IP, socket.AI_CANONNAME): if len(a_nfo) > 3: hosts.append(a_nfo[3]) except socket.gaierror: log.warning('Cannot resolve address %s info via socket: %s', hosts.first() or 'localhost (N/A)', socket.gaierror) # Universal method for everywhere (Linux, Slowlaris, Windows etc) for f_name in ('/etc/hostname', '/etc/nodename', '/etc/hosts', r'{win}\system32\drivers\etc\hosts'.format(win=os.getenv('WINDIR'))): try: with salt.utils.files.fopen(f_name) as f_hdl: for line in f_hdl: line = salt.utils.stringutils.to_unicode(line) hst = line.strip().split('#')[0].strip().split() if hst: if hst[0][:4] in ('127.', '::1') or len(hst) == 1: hosts.extend(hst) except IOError: pass # include public and private ipaddresses return hosts.extend([addr for addr in ip_addrs() if not ipaddress.ip_address(addr).is_loopback]) def generate_minion_id(): ''' Return only first element of the hostname from all possible list. :return: ''' try: ret = salt.utils.stringutils.to_unicode(_generate_minion_id().first()) except TypeError: ret = None return ret or 'localhost' def get_socket(addr, type=socket.SOCK_STREAM, proto=0): ''' Return a socket object for the addr IP-version agnostic ''' version = ipaddress.ip_address(addr).version if version == 4: family = socket.AF_INET elif version == 6: family = socket.AF_INET6 return socket.socket(family, type, proto) def get_fqhostname(): ''' Returns the fully qualified hostname ''' # try getaddrinfo() fqdn = None try: addrinfo = socket.getaddrinfo( socket.gethostname(), 0, socket.AF_UNSPEC, socket.SOCK_STREAM, socket.SOL_TCP, socket.AI_CANONNAME ) for info in addrinfo: # info struct [family, socktype, proto, canonname, sockaddr] # On Windows `canonname` can be an empty string # This can cause the function to return `None` if len(info) > 3 and info[3]: fqdn = info[3] break except socket.gaierror: pass # NOTE: this used to log.error() but it was later disabled except socket.error as err: log.debug('socket.getaddrinfo() failure while finding fqdn: %s', err) if fqdn is None: fqdn = socket.getfqdn() return fqdn def ip_to_host(ip): ''' Returns the hostname of a given IP ''' try: hostname, aliaslist, ipaddrlist = socket.gethostbyaddr(ip) except Exception as exc: log.debug('salt.utils.network.ip_to_host(%r) failed: %s', ip, exc) hostname = None return hostname # pylint: enable=C0103 def is_reachable_host(entity_name): ''' Returns a bool telling if the entity name is a reachable host (IPv4/IPv6/FQDN/etc). :param hostname: :return: ''' try: assert type(socket.getaddrinfo(entity_name, 0, 0, 0, 0)) == list ret = True except socket.gaierror: ret = False return ret def is_ip(ip): ''' Returns a bool telling if the passed IP is a valid IPv4 or IPv6 address. ''' return is_ipv4(ip) or is_ipv6(ip) def is_ipv4(ip): ''' Returns a bool telling if the value passed to it was a valid IPv4 address ''' try: return ipaddress.ip_address(ip).version == 4 except ValueError: return False def is_ipv6(ip): ''' Returns a bool telling if the value passed to it was a valid IPv6 address ''' try: return ipaddress.ip_address(ip).version == 6 except ValueError: return False def is_subnet(cidr): ''' Returns a bool telling if the passed string is an IPv4 or IPv6 subnet ''' return is_ipv4_subnet(cidr) or is_ipv6_subnet(cidr) def is_ipv4_subnet(cidr): ''' Returns a bool telling if the passed string is an IPv4 subnet ''' try: return '/' in cidr and bool(ipaddress.IPv4Network(cidr)) except Exception: return False def is_ipv6_subnet(cidr): ''' Returns a bool telling if the passed string is an IPv6 subnet ''' try: return '/' in cidr and bool(ipaddress.IPv6Network(cidr)) except Exception: return False @jinja_filter('is_ip') def is_ip_filter(ip, options=None): ''' Returns a bool telling if the passed IP is a valid IPv4 or IPv6 address. ''' return is_ipv4_filter(ip, options=options) or is_ipv6_filter(ip, options=options) def _ip_options_global(ip_obj, version): return not ip_obj.is_private def _ip_options_multicast(ip_obj, version): return ip_obj.is_multicast def _ip_options_loopback(ip_obj, version): return ip_obj.is_loopback def _ip_options_link_local(ip_obj, version): return ip_obj.is_link_local def _ip_options_private(ip_obj, version): return ip_obj.is_private def _ip_options_reserved(ip_obj, version): return ip_obj.is_reserved def _ip_options_site_local(ip_obj, version): if version == 6: return ip_obj.is_site_local return False def _ip_options_unspecified(ip_obj, version): return ip_obj.is_unspecified def _ip_options(ip_obj, version, options=None): # will process and IP options options_fun_map = { 'global': _ip_options_global, 'link-local': _ip_options_link_local, 'linklocal': _ip_options_link_local, 'll': _ip_options_link_local, 'link_local': _ip_options_link_local, 'loopback': _ip_options_loopback, 'lo': _ip_options_loopback, 'multicast': _ip_options_multicast, 'private': _ip_options_private, 'public': _ip_options_global, 'reserved': _ip_options_reserved, 'site-local': _ip_options_site_local, 'sl': _ip_options_site_local, 'site_local': _ip_options_site_local, 'unspecified': _ip_options_unspecified } if not options: return six.text_type(ip_obj) # IP version already checked options_list = [option.strip() for option in options.split(',')] for option, fun in options_fun_map.items(): if option in options_list: fun_res = fun(ip_obj, version) if not fun_res: return None # stop at first failed test # else continue return six.text_type(ip_obj) def _is_ipv(ip, version, options=None): if not version: version = 4 if version not in (4, 6): return None try: ip_obj = ipaddress.ip_address(ip) except ValueError: # maybe it is an IP network try: ip_obj = ipaddress.ip_interface(ip) except ValueError: # nope, still not :( return None if not ip_obj.version == version: return None # has the right version, let's move on return _ip_options(ip_obj, version, options=options) @jinja_filter('is_ipv4') def is_ipv4_filter(ip, options=None): ''' Returns a bool telling if the value passed to it was a valid IPv4 address. ip The IP address. net: False Consider IP addresses followed by netmask. options CSV of options regarding the nature of the IP address. E.g.: loopback, multicast, private etc. ''' _is_ipv4 = _is_ipv(ip, 4, options=options) return isinstance(_is_ipv4, six.string_types) @jinja_filter('is_ipv6') def is_ipv6_filter(ip, options=None): ''' Returns a bool telling if the value passed to it was a valid IPv6 address. ip The IP address. net: False Consider IP addresses followed by netmask. options CSV of options regarding the nature of the IP address. E.g.: loopback, multicast, private etc. ''' _is_ipv6 = _is_ipv(ip, 6, options=options) return isinstance(_is_ipv6, six.string_types) def _ipv_filter(value, version, options=None): if version not in (4, 6): return if isinstance(value, (six.string_types, six.text_type, six.binary_type)): return _is_ipv(value, version, options=options) # calls is_ipv4 or is_ipv6 for `value` elif isinstance(value, (list, tuple, types.GeneratorType)): # calls is_ipv4 or is_ipv6 for each element in the list # os it filters and returns only those elements having the desired IP version return [ _is_ipv(addr, version, options=options) for addr in value if _is_ipv(addr, version, options=options) is not None ] return None @jinja_filter('ipv4') def ipv4(value, options=None): ''' Filters a list and returns IPv4 values only. ''' return _ipv_filter(value, 4, options=options) @jinja_filter('ipv6') def ipv6(value, options=None): ''' Filters a list and returns IPv6 values only. ''' return _ipv_filter(value, 6, options=options) @jinja_filter('ipaddr') def ipaddr(value, options=None): ''' Filters and returns only valid IP objects. ''' ipv4_obj = ipv4(value, options=options) ipv6_obj = ipv6(value, options=options) if ipv4_obj is None or ipv6_obj is None: # an IP address can be either IPv4 either IPv6 # therefofe if the value passed as arg is not a list, at least one of the calls above will return None # if one of them is none, means that we should return only one of them return ipv4_obj or ipv6_obj # one of them else: return ipv4_obj + ipv6_obj # extend lists def _filter_ipaddr(value, options, version=None): ipaddr_filter_out = None if version: if version == 4: ipaddr_filter_out = ipv4(value, options) elif version == 6: ipaddr_filter_out = ipv6(value, options) else: ipaddr_filter_out = ipaddr(value, options) if not ipaddr_filter_out: return if not isinstance(ipaddr_filter_out, (list, tuple, types.GeneratorType)): ipaddr_filter_out = [ipaddr_filter_out] return ipaddr_filter_out @jinja_filter('ip_host') def ip_host(value, options=None, version=None): ''' Returns the interfaces IP address, e.g.: 192.168.0.1/28. ''' ipaddr_filter_out = _filter_ipaddr(value, options=options, version=version) if not ipaddr_filter_out: return if not isinstance(value, (list, tuple, types.GeneratorType)): return six.text_type(ipaddress.ip_interface(ipaddr_filter_out[0])) return [six.text_type(ipaddress.ip_interface(ip_a)) for ip_a in ipaddr_filter_out] def _network_hosts(ip_addr_entry): return [ six.text_type(host) for host in ipaddress.ip_network(ip_addr_entry, strict=False).hosts() ] @jinja_filter('network_hosts') def network_hosts(value, options=None, version=None): ''' Return the list of hosts within a network. .. note:: When running this command with a large IPv6 network, the command will take a long time to gather all of the hosts. ''' ipaddr_filter_out = _filter_ipaddr(value, options=options, version=version) if not ipaddr_filter_out: return if not isinstance(value, (list, tuple, types.GeneratorType)): return _network_hosts(ipaddr_filter_out[0]) return [ _network_hosts(ip_a) for ip_a in ipaddr_filter_out ] def _network_size(ip_addr_entry): return ipaddress.ip_network(ip_addr_entry, strict=False).num_addresses @jinja_filter('network_size') def network_size(value, options=None, version=None): ''' Get the size of a network. ''' ipaddr_filter_out = _filter_ipaddr(value, options=options, version=version) if not ipaddr_filter_out: return if not isinstance(value, (list, tuple, types.GeneratorType)): return _network_size(ipaddr_filter_out[0]) return [ _network_size(ip_a) for ip_a in ipaddr_filter_out ] def rpad_ipv4_network(ip): ''' Returns an IP network address padded with zeros. Ex: '192.168.3' -> '192.168.3.0' '10.209' -> '10.209.0.0' ''' return '.'.join(itertools.islice(itertools.chain(ip.split('.'), '0000'), 0, 4)) def cidr_to_ipv4_netmask(cidr_bits): ''' Returns an IPv4 netmask ''' try: cidr_bits = int(cidr_bits) if not 1 <= cidr_bits <= 32: return '' except ValueError: return '' netmask = '' for idx in range(4): if idx: netmask += '.' if cidr_bits >= 8: netmask += '255' cidr_bits -= 8 else: netmask += '{0:d}'.format(256 - (2 ** (8 - cidr_bits))) cidr_bits = 0 return netmask def _number_of_set_bits_to_ipv4_netmask(set_bits): # pylint: disable=C0103 ''' Returns an IPv4 netmask from the integer representation of that mask. Ex. 0xffffff00 -> '255.255.255.0' ''' return cidr_to_ipv4_netmask(_number_of_set_bits(set_bits)) # pylint: disable=C0103 def _number_of_set_bits(x): ''' Returns the number of bits that are set in a 32bit int ''' # Taken from http://stackoverflow.com/a/4912729. Many thanks! x -= (x >> 1) & 0x55555555 x = ((x >> 2) & 0x33333333) + (x & 0x33333333) x = ((x >> 4) + x) & 0x0f0f0f0f x += x >> 8 x += x >> 16 return x & 0x0000003f # pylint: enable=C0103 def _interfaces_ip(out): ''' Uses ip to return a dictionary of interfaces with various information about each (up/down state, ip address, netmask, and hwaddr) ''' ret = dict() def parse_network(value, cols): ''' Return a tuple of ip, netmask, broadcast based on the current set of cols ''' brd = None scope = None if '/' in value: # we have a CIDR in this address ip, cidr = value.split('/') # pylint: disable=C0103 else: ip = value # pylint: disable=C0103 cidr = 32 if type_ == 'inet': mask = cidr_to_ipv4_netmask(int(cidr)) if 'brd' in cols: brd = cols[cols.index('brd') + 1] elif type_ == 'inet6': mask = cidr if 'scope' in cols: scope = cols[cols.index('scope') + 1] return (ip, mask, brd, scope) groups = re.compile('\r?\n\\d').split(out) for group in groups: iface = None data = dict() for line in group.splitlines(): if ' ' not in line: continue match = re.match(r'^\d*:\s+([\w.\-]+)(?:@)?([\w.\-]+)?:\s+<(.+)>', line) if match: iface, parent, attrs = match.groups() if 'UP' in attrs.split(','): data['up'] = True else: data['up'] = False if parent: data['parent'] = parent continue cols = line.split() if len(cols) >= 2: type_, value = tuple(cols[0:2]) iflabel = cols[-1:][0] if type_ in ('inet', 'inet6'): if 'secondary' not in cols: ipaddr, netmask, broadcast, scope = parse_network(value, cols) if type_ == 'inet': if 'inet' not in data: data['inet'] = list() addr_obj = dict() addr_obj['address'] = ipaddr addr_obj['netmask'] = netmask addr_obj['broadcast'] = broadcast addr_obj['label'] = iflabel data['inet'].append(addr_obj) elif type_ == 'inet6': if 'inet6' not in data: data['inet6'] = list() addr_obj = dict() addr_obj['address'] = ipaddr addr_obj['prefixlen'] = netmask addr_obj['scope'] = scope data['inet6'].append(addr_obj) else: if 'secondary' not in data: data['secondary'] = list() ip_, mask, brd, scp = parse_network(value, cols) data['secondary'].append({ 'type': type_, 'address': ip_, 'netmask': mask, 'broadcast': brd, 'label': iflabel, }) del ip_, mask, brd, scp elif type_.startswith('link'): data['hwaddr'] = value if iface: ret[iface] = data del iface, data return ret def _interfaces_ifconfig(out): ''' Uses ifconfig to return a dictionary of interfaces with various information about each (up/down state, ip address, netmask, and hwaddr) ''' ret = dict() piface = re.compile(r'^([^\s:]+)') pmac = re.compile('.*?(?:HWaddr|ether|address:|lladdr) ([0-9a-fA-F:]+)') if salt.utils.platform.is_sunos(): pip = re.compile(r'.*?(?:inet\s+)([0-9]+\.[0-9]+\.[0-9]+\.[0-9]+)(.*)') pip6 = re.compile('.*?(?:inet6 )([0-9a-fA-F:]+)') pmask6 = re.compile(r'.*?(?:inet6 [0-9a-fA-F:]+/(\d+)).*') else: pip = re.compile(r'.*?(?:inet addr:|inet [^\d]*)(.*?)\s') pip6 = re.compile('.*?(?:inet6 addr: (.*?)/|inet6 )([0-9a-fA-F:]+)') pmask6 = re.compile(r'.*?(?:inet6 addr: [0-9a-fA-F:]+/(\d+)|prefixlen (\d+))(?: Scope:([a-zA-Z]+)| scopeid (0x[0-9a-fA-F]))?') pmask = re.compile(r'.*?(?:Mask:|netmask )(?:((?:0x)?[0-9a-fA-F]{8})|([\d\.]+))') pupdown = re.compile('UP') pbcast = re.compile(r'.*?(?:Bcast:|broadcast )([\d\.]+)') groups = re.compile('\r?\n(?=\\S)').split(out) for group in groups: data = dict() iface = '' updown = False for line in group.splitlines(): miface = piface.match(line) mmac = pmac.match(line) mip = pip.match(line) mip6 = pip6.match(line) mupdown = pupdown.search(line) if miface: iface = miface.group(1) if mmac: data['hwaddr'] = mmac.group(1) if salt.utils.platform.is_sunos(): expand_mac = [] for chunk in data['hwaddr'].split(':'): expand_mac.append('0{0}'.format(chunk) if len(chunk) < 2 else '{0}'.format(chunk)) data['hwaddr'] = ':'.join(expand_mac) if mip: if 'inet' not in data: data['inet'] = list() addr_obj = dict() addr_obj['address'] = mip.group(1) mmask = pmask.match(line) if mmask: if mmask.group(1): mmask = _number_of_set_bits_to_ipv4_netmask( int(mmask.group(1), 16)) else: mmask = mmask.group(2) addr_obj['netmask'] = mmask mbcast = pbcast.match(line) if mbcast: addr_obj['broadcast'] = mbcast.group(1) data['inet'].append(addr_obj) if mupdown: updown = True if mip6: if 'inet6' not in data: data['inet6'] = list() addr_obj = dict() addr_obj['address'] = mip6.group(1) or mip6.group(2) mmask6 = pmask6.match(line) if mmask6: addr_obj['prefixlen'] = mmask6.group(1) or mmask6.group(2) if not salt.utils.platform.is_sunos(): ipv6scope = mmask6.group(3) or mmask6.group(4) addr_obj['scope'] = ipv6scope.lower() if ipv6scope is not None else ipv6scope # SunOS sometimes has ::/0 as inet6 addr when using addrconf if not salt.utils.platform.is_sunos() \ or addr_obj['address'] != '::' \ and addr_obj['prefixlen'] != 0: data['inet6'].append(addr_obj) data['up'] = updown if iface in ret: # SunOS optimization, where interfaces occur twice in 'ifconfig -a' # output with the same name: for ipv4 and then for ipv6 addr family. # Every instance has it's own 'UP' status and we assume that ipv4 # status determines global interface status. # # merge items with higher priority for older values # after that merge the inet and inet6 sub items for both ret[iface] = dict(list(data.items()) + list(ret[iface].items())) if 'inet' in data: ret[iface]['inet'].extend(x for x in data['inet'] if x not in ret[iface]['inet']) if 'inet6' in data: ret[iface]['inet6'].extend(x for x in data['inet6'] if x not in ret[iface]['inet6']) else: ret[iface] = data del data return ret def linux_interfaces(): ''' Obtain interface information for *NIX/BSD variants ''' ifaces = dict() ip_path = salt.utils.path.which('ip') ifconfig_path = None if ip_path else salt.utils.path.which('ifconfig') if ip_path: cmd1 = subprocess.Popen( '{0} link show'.format(ip_path), shell=True, close_fds=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT).communicate()[0] cmd2 = subprocess.Popen( '{0} addr show'.format(ip_path), shell=True, close_fds=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT).communicate()[0] ifaces = _interfaces_ip("{0}\n{1}".format( salt.utils.stringutils.to_str(cmd1), salt.utils.stringutils.to_str(cmd2))) elif ifconfig_path: cmd = subprocess.Popen( '{0} -a'.format(ifconfig_path), shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT).communicate()[0] ifaces = _interfaces_ifconfig(salt.utils.stringutils.to_str(cmd)) return ifaces def _netbsd_interfaces_ifconfig(out): ''' Uses ifconfig to return a dictionary of interfaces with various information about each (up/down state, ip address, netmask, and hwaddr) ''' ret = dict() piface = re.compile(r'^([^\s:]+)') pmac = re.compile('.*?address: ([0-9a-f:]+)') pip = re.compile(r'.*?inet [^\d]*(.*?)/([\d]*)\s') pip6 = re.compile(r'.*?inet6 ([0-9a-f:]+)%([a-zA-Z0-9]*)/([\d]*)\s') pupdown = re.compile('UP') pbcast = re.compile(r'.*?broadcast ([\d\.]+)') groups = re.compile('\r?\n(?=\\S)').split(out) for group in groups: data = dict() iface = '' updown = False for line in group.splitlines(): miface = piface.match(line) mmac = pmac.match(line) mip = pip.match(line) mip6 = pip6.match(line) mupdown = pupdown.search(line) if miface: iface = miface.group(1) if mmac: data['hwaddr'] = mmac.group(1) if mip: if 'inet' not in data: data['inet'] = list() addr_obj = dict() addr_obj['address'] = mip.group(1) mmask = mip.group(2) if mip.group(2): addr_obj['netmask'] = cidr_to_ipv4_netmask(mip.group(2)) mbcast = pbcast.match(line) if mbcast: addr_obj['broadcast'] = mbcast.group(1) data['inet'].append(addr_obj) if mupdown: updown = True if mip6: if 'inet6' not in data: data['inet6'] = list() addr_obj = dict() addr_obj['address'] = mip6.group(1) mmask6 = mip6.group(3) addr_obj['scope'] = mip6.group(2) addr_obj['prefixlen'] = mip6.group(3) data['inet6'].append(addr_obj) data['up'] = updown ret[iface] = data del data return ret def netbsd_interfaces(): ''' Obtain interface information for NetBSD >= 8 where the ifconfig output diverged from other BSD variants (Netmask is now part of the address) ''' # NetBSD versions prior to 8.0 can still use linux_interfaces() if LooseVersion(os.uname()[2]) < LooseVersion('8.0'): return linux_interfaces() ifconfig_path = salt.utils.path.which('ifconfig') cmd = subprocess.Popen( '{0} -a'.format(ifconfig_path), shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT).communicate()[0] return _netbsd_interfaces_ifconfig(salt.utils.stringutils.to_str(cmd)) def _interfaces_ipconfig(out): ''' Returns a dictionary of interfaces with various information about each (up/down state, ip address, netmask, and hwaddr) NOTE: This is not used by any function and may be able to be removed in the future. ''' ifaces = dict() iface = None adapter_iface_regex = re.compile(r'adapter (\S.+):$') for line in out.splitlines(): if not line: continue # TODO what does Windows call Infiniband and 10/40gige adapters if line.startswith('Ethernet'): iface = ifaces[adapter_iface_regex.search(line).group(1)] iface['up'] = True addr = None continue if iface: key, val = line.split(',', 1) key = key.strip(' .') val = val.strip() if addr and key == 'Subnet Mask': addr['netmask'] = val elif key in ('IP Address', 'IPv4 Address'): if 'inet' not in iface: iface['inet'] = list() addr = {'address': val.rstrip('(Preferred)'), 'netmask': None, 'broadcast': None} # TODO find the broadcast iface['inet'].append(addr) elif 'IPv6 Address' in key: if 'inet6' not in iface: iface['inet'] = list() # XXX What is the prefixlen!? addr = {'address': val.rstrip('(Preferred)'), 'prefixlen': None} iface['inet6'].append(addr) elif key == 'Physical Address': iface['hwaddr'] = val elif key == 'Media State': # XXX seen used for tunnel adaptors # might be useful iface['up'] = (val != 'Media disconnected') def win_interfaces(): ''' Obtain interface information for Windows systems ''' with salt.utils.winapi.Com(): c = wmi.WMI() ifaces = {} for iface in c.Win32_NetworkAdapterConfiguration(IPEnabled=1): ifaces[iface.Description] = dict() if iface.MACAddress: ifaces[iface.Description]['hwaddr'] = iface.MACAddress if iface.IPEnabled: ifaces[iface.Description]['up'] = True for ip in iface.IPAddress: if '.' in ip: if 'inet' not in ifaces[iface.Description]: ifaces[iface.Description]['inet'] = [] item = {'address': ip, 'label': iface.Description} if iface.DefaultIPGateway: broadcast = next((i for i in iface.DefaultIPGateway if '.' in i), '') if broadcast: item['broadcast'] = broadcast if iface.IPSubnet: netmask = next((i for i in iface.IPSubnet if '.' in i), '') if netmask: item['netmask'] = netmask ifaces[iface.Description]['inet'].append(item) if ':' in ip: if 'inet6' not in ifaces[iface.Description]: ifaces[iface.Description]['inet6'] = [] item = {'address': ip} if iface.DefaultIPGateway: broadcast = next((i for i in iface.DefaultIPGateway if ':' in i), '') if broadcast: item['broadcast'] = broadcast if iface.IPSubnet: netmask = next((i for i in iface.IPSubnet if ':' in i), '') if netmask: item['netmask'] = netmask ifaces[iface.Description]['inet6'].append(item) else: ifaces[iface.Description]['up'] = False return ifaces def interfaces(): ''' Return a dictionary of information about all the interfaces on the minion ''' if salt.utils.platform.is_windows(): return win_interfaces() elif salt.utils.platform.is_netbsd(): return netbsd_interfaces() else: return linux_interfaces() def get_net_start(ipaddr, netmask): ''' Return the address of the network ''' net = ipaddress.ip_network('{0}/{1}'.format(ipaddr, netmask), strict=False) return six.text_type(net.network_address) def get_net_size(mask): ''' Turns an IPv4 netmask into it's corresponding prefix length (255.255.255.0 -> 24 as in 192.168.1.10/24). ''' binary_str = '' for octet in mask.split('.'): binary_str += bin(int(octet))[2:].zfill(8) return len(binary_str.rstrip('0')) def calc_net(ipaddr, netmask=None): ''' Takes IP (CIDR notation supported) and optionally netmask and returns the network in CIDR-notation. (The IP can be any IP inside the subnet) ''' if netmask is not None: ipaddr = '{0}/{1}'.format(ipaddr, netmask) return six.text_type(ipaddress.ip_network(ipaddr, strict=False)) def _ipv4_to_bits(ipaddr): ''' Accepts an IPv4 dotted quad and returns a string representing its binary counterpart ''' return ''.join([bin(int(x))[2:].rjust(8, '0') for x in ipaddr.split('.')]) def _get_iface_info(iface): ''' If `iface` is available, return interface info and no error, otherwise return no info and log and return an error ''' iface_info = interfaces() if iface in iface_info.keys(): return iface_info, False else: error_msg = ('Interface "{0}" not in available interfaces: "{1}"' ''.format(iface, '", "'.join(iface_info.keys()))) log.error(error_msg) return None, error_msg def _hw_addr_aix(iface): ''' Return the hardware address (a.k.a. MAC address) for a given interface on AIX MAC address not available in through interfaces ''' cmd = subprocess.Popen( 'entstat -d {0} | grep \'Hardware Address\''.format(iface), shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT).communicate()[0] if cmd: comps = cmd.split(' ') if len(comps) == 3: mac_addr = comps[2].strip('\'').strip() return mac_addr error_msg = ('Interface "{0}" either not available or does not contain a hardware address'.format(iface)) log.error(error_msg) return error_msg def hw_addr(iface): ''' Return the hardware address (a.k.a. MAC address) for a given interface .. versionchanged:: 2016.11.4 Added support for AIX ''' if salt.utils.platform.is_aix(): return _hw_addr_aix iface_info, error = _get_iface_info(iface) if error is False: return iface_info.get(iface, {}).get('hwaddr', '') else: return error def interface(iface): ''' Return the details of `iface` or an error if it does not exist ''' iface_info, error = _get_iface_info(iface) if error is False: return iface_info.get(iface, {}).get('inet', '') else: return error def interface_ip(iface): ''' Return `iface` IPv4 addr or an error if `iface` does not exist ''' iface_info, error = _get_iface_info(iface) if error is False: inet = iface_info.get(iface, {}).get('inet', None) return inet[0].get('address', '') if inet else '' else: return error def _subnets(proto='inet', interfaces_=None): ''' Returns a list of subnets to which the host belongs ''' if interfaces_ is None: ifaces = interfaces() elif isinstance(interfaces_, list): ifaces = {} for key, value in six.iteritems(interfaces()): if key in interfaces_: ifaces[key] = value else: ifaces = {interfaces_: interfaces().get(interfaces_, {})} ret = set() if proto == 'inet': subnet = 'netmask' dflt_cidr = 32 elif proto == 'inet6': subnet = 'prefixlen' dflt_cidr = 128 else: log.error('Invalid proto %s calling subnets()', proto) return for ip_info in six.itervalues(ifaces): addrs = ip_info.get(proto, []) addrs.extend([addr for addr in ip_info.get('secondary', []) if addr.get('type') == proto]) for intf in addrs: if subnet in intf: intf = ipaddress.ip_interface('{0}/{1}'.format(intf['address'], intf[subnet])) else: intf = ipaddress.ip_interface('{0}/{1}'.format(intf['address'], dflt_cidr)) if not intf.is_loopback: ret.add(intf.network) return [six.text_type(net) for net in sorted(ret)] def subnets(interfaces=None): ''' Returns a list of IPv4 subnets to which the host belongs ''' return _subnets('inet', interfaces_=interfaces) def subnets6(): ''' Returns a list of IPv6 subnets to which the host belongs ''' return _subnets('inet6') def in_subnet(cidr, addr=None): ''' Returns True if host or (any of) addrs is within specified subnet, otherwise False ''' try: cidr = ipaddress.ip_network(cidr) except ValueError: log.error('Invalid CIDR \'%s\'', cidr) return False if addr is None: addr = ip_addrs() addr.extend(ip_addrs6()) elif not isinstance(addr, (list, tuple)): addr = (addr,) return any(ipaddress.ip_address(item) in cidr for item in addr) def _ip_addrs(interface=None, include_loopback=False, interface_data=None, proto='inet'): ''' Return the full list of IP adresses matching the criteria proto = inet|inet6 ''' ret = set() ifaces = interface_data \ if isinstance(interface_data, dict) \ else interfaces() if interface is None: target_ifaces = ifaces else: target_ifaces = dict([(k, v) for k, v in six.iteritems(ifaces) if k == interface]) if not target_ifaces: log.error('Interface %s not found.', interface) for ip_info in six.itervalues(target_ifaces): addrs = ip_info.get(proto, []) addrs.extend([addr for addr in ip_info.get('secondary', []) if addr.get('type') == proto]) for addr in addrs: addr = ipaddress.ip_address(addr.get('address')) if not addr.is_loopback or include_loopback: ret.add(addr) return [six.text_type(addr) for addr in sorted(ret)] def ip_addrs(interface=None, include_loopback=False, interface_data=None): ''' Returns a list of IPv4 addresses assigned to the host. 127.0.0.1 is ignored, unless 'include_loopback=True' is indicated. If 'interface' is provided, then only IP addresses from that interface will be returned. ''' return _ip_addrs(interface, include_loopback, interface_data, 'inet') def ip_addrs6(interface=None, include_loopback=False, interface_data=None): ''' Returns a list of IPv6 addresses assigned to the host. ::1 is ignored, unless 'include_loopback=True' is indicated. If 'interface' is provided, then only IP addresses from that interface will be returned. ''' return _ip_addrs(interface, include_loopback, interface_data, 'inet6') def hex2ip(hex_ip, invert=False): ''' Convert a hex string to an ip, if a failure occurs the original hex is returned. If 'invert=True' assume that ip from /proc/net/<proto> ''' if len(hex_ip) == 32: # ipv6 ip = [] for i in range(0, 32, 8): ip_part = hex_ip[i:i + 8] ip_part = [ip_part[x:x + 2] for x in range(0, 8, 2)] if invert: ip.append("{0[3]}{0[2]}:{0[1]}{0[0]}".format(ip_part)) else: ip.append("{0[0]}{0[1]}:{0[2]}{0[3]}".format(ip_part)) try: address = ipaddress.IPv6Address(":".join(ip)) if address.ipv4_mapped: return str(address.ipv4_mapped) else: return address.compressed except ipaddress.AddressValueError as ex: log.error('hex2ip - ipv6 address error: %s', ex) return hex_ip try: hip = int(hex_ip, 16) except ValueError: return hex_ip if invert: return '{3}.{2}.{1}.{0}'.format(hip >> 24 & 255, hip >> 16 & 255, hip >> 8 & 255, hip & 255) return '{0}.{1}.{2}.{3}'.format(hip >> 24 & 255, hip >> 16 & 255, hip >> 8 & 255, hip & 255) def mac2eui64(mac, prefix=None): ''' Convert a MAC address to a EUI64 identifier or, with prefix provided, a full IPv6 address ''' # http://tools.ietf.org/html/rfc4291#section-2.5.1 eui64 = re.sub(r'[.:-]', '', mac).lower() eui64 = eui64[0:6] + 'fffe' + eui64[6:] eui64 = hex(int(eui64[0:2], 16) | 2)[2:].zfill(2) + eui64[2:] if prefix is None: return ':'.join(re.findall(r'.{4}', eui64)) else: try: net = ipaddress.ip_network(prefix, strict=False) euil = int('0x{0}'.format(eui64), 16) return '{0}/{1}'.format(net[euil], net.prefixlen) except Exception: return def active_tcp(): ''' Return a dict describing all active tcp connections as quickly as possible ''' ret = {} for statf in ['/proc/net/tcp', '/proc/net/tcp6']: if os.path.isfile(statf): with salt.utils.files.fopen(statf, 'rb') as fp_: for line in fp_: line = salt.utils.stringutils.to_unicode(line) if line.strip().startswith('sl'): continue iret = _parse_tcp_line(line) sl = next(iter(iret)) if iret[sl]['state'] == 1: # 1 is ESTABLISHED del iret[sl]['state'] ret[len(ret)] = iret[sl] return ret def local_port_tcp(port): ''' Return a set of remote ip addrs attached to the specified local port ''' ret = _remotes_on(port, 'local_port') return ret def remote_port_tcp(port): ''' Return a set of ip addrs the current host is connected to on given port ''' ret = _remotes_on(port, 'remote_port') return ret def _remotes_on(port, which_end): ''' Return a set of ip addrs active tcp connections ''' port = int(port) ret = _netlink_tool_remote_on(port, which_end) if ret is not None: return ret ret = set() proc_available = False for statf in ['/proc/net/tcp', '/proc/net/tcp6']: if os.path.isfile(statf): proc_available = True with salt.utils.files.fopen(statf, 'r') as fp_: for line in fp_: line = salt.utils.stringutils.to_unicode(line) if line.strip().startswith('sl'): continue iret = _parse_tcp_line(line) sl = next(iter(iret)) if iret[sl][which_end] == port and iret[sl]['state'] == 1: # 1 is ESTABLISHED ret.add(iret[sl]['remote_addr']) if not proc_available: # Fallback to use OS specific tools if salt.utils.platform.is_sunos(): return _sunos_remotes_on(port, which_end) if salt.utils.platform.is_freebsd(): return _freebsd_remotes_on(port, which_end) if salt.utils.platform.is_netbsd(): return _netbsd_remotes_on(port, which_end) if salt.utils.platform.is_openbsd(): return _openbsd_remotes_on(port, which_end) if salt.utils.platform.is_windows(): return _windows_remotes_on(port, which_end) if salt.utils.platform.is_aix(): return _aix_remotes_on(port, which_end) return _linux_remotes_on(port, which_end) return ret def _parse_tcp_line(line): ''' Parse a single line from the contents of /proc/net/tcp or /proc/net/tcp6 ''' ret = {} comps = line.strip().split() sl = comps[0].rstrip(':') ret[sl] = {} l_addr, l_port = comps[1].split(':') r_addr, r_port = comps[2].split(':') ret[sl]['local_addr'] = hex2ip(l_addr, True) ret[sl]['local_port'] = int(l_port, 16) ret[sl]['remote_addr'] = hex2ip(r_addr, True) ret[sl]['remote_port'] = int(r_port, 16) ret[sl]['state'] = int(comps[3], 16) return ret def _netlink_tool_remote_on(port, which_end): ''' Returns set of ipv4 host addresses of remote established connections on local or remote tcp port. Parses output of shell 'ss' to get connections [root@salt-master ~]# ss -ant State Recv-Q Send-Q Local Address:Port Peer Address:Port LISTEN 0 511 *:80 *:* LISTEN 0 128 *:22 *:* ESTAB 0 0 127.0.0.1:56726 127.0.0.1:4505 ''' remotes = set() valid = False try: data = subprocess.check_output(['ss', '-ant']) # pylint: disable=minimum-python-version except subprocess.CalledProcessError: log.error('Failed ss') raise except OSError: # not command "No such file or directory" return None lines = salt.utils.stringutils.to_str(data).split('\n') for line in lines: if 'Address:Port' in line: # ss tools may not be valid valid = True continue elif 'ESTAB' not in line: continue chunks = line.split() local_host, local_port = chunks[3].split(':', 1) remote_host, remote_port = chunks[4].split(':', 1) if which_end == 'remote_port' and int(remote_port) != port: continue if which_end == 'local_port' and int(local_port) != port: continue remotes.add(remote_host) if valid is False: remotes = None return remotes def _sunos_remotes_on(port, which_end): ''' SunOS specific helper function. Returns set of ipv4 host addresses of remote established connections on local or remote tcp port. Parses output of shell 'netstat' to get connections [root@salt-master ~]# netstat -f inet -n TCP: IPv4 Local Address Remote Address Swind Send-Q Rwind Recv-Q State -------------------- -------------------- ----- ------ ----- ------ ----------- 10.0.0.101.4505 10.0.0.1.45329 1064800 0 1055864 0 ESTABLISHED 10.0.0.101.4505 10.0.0.100.50798 1064800 0 1055864 0 ESTABLISHED ''' remotes = set() try: data = subprocess.check_output(['netstat', '-f', 'inet', '-n']) # pylint: disable=minimum-python-version except subprocess.CalledProcessError: log.error('Failed netstat') raise lines = salt.utils.stringutils.to_str(data).split('\n') for line in lines: if 'ESTABLISHED' not in line: continue chunks = line.split() local_host, local_port = chunks[0].rsplit('.', 1) remote_host, remote_port = chunks[1].rsplit('.', 1) if which_end == 'remote_port' and int(remote_port) != port: continue if which_end == 'local_port' and int(local_port) != port: continue remotes.add(remote_host) return remotes def _freebsd_remotes_on(port, which_end): ''' Returns set of ipv4 host addresses of remote established connections on local tcp port port. Parses output of shell 'sockstat' (FreeBSD) to get connections $ sudo sockstat -4 USER COMMAND PID FD PROTO LOCAL ADDRESS FOREIGN ADDRESS root python2.7 1456 29 tcp4 *:4505 *:* root python2.7 1445 17 tcp4 *:4506 *:* root python2.7 1294 14 tcp4 127.0.0.1:11813 127.0.0.1:4505 root python2.7 1294 41 tcp4 127.0.0.1:61115 127.0.0.1:4506 $ sudo sockstat -4 -c -p 4506 USER COMMAND PID FD PROTO LOCAL ADDRESS FOREIGN ADDRESS root python2.7 1294 41 tcp4 127.0.0.1:61115 127.0.0.1:4506 ''' port = int(port) remotes = set() try: cmd = salt.utils.args.shlex_split('sockstat -4 -c -p {0}'.format(port)) data = subprocess.check_output(cmd) # pylint: disable=minimum-python-version except subprocess.CalledProcessError as ex: log.error('Failed "sockstat" with returncode = %s', ex.returncode) raise lines = salt.utils.stringutils.to_str(data).split('\n') for line in lines: chunks = line.split() if not chunks: continue # ['root', 'python2.7', '1456', '37', 'tcp4', # '127.0.0.1:4505-', '127.0.0.1:55703'] # print chunks if 'COMMAND' in chunks[1]: continue # ignore header if len(chunks) < 2: continue # sockstat -4 -c -p 4506 does this with high PIDs: # USER COMMAND PID FD PROTO LOCAL ADDRESS FOREIGN ADDRESS # salt-master python2.781106 35 tcp4 192.168.12.34:4506 192.168.12.45:60143 local = chunks[-2] remote = chunks[-1] lhost, lport = local.split(':') rhost, rport = remote.split(':') if which_end == 'local' and int(lport) != port: # ignore if local port not port continue if which_end == 'remote' and int(rport) != port: # ignore if remote port not port continue remotes.add(rhost) return remotes def _netbsd_remotes_on(port, which_end): ''' Returns set of ipv4 host addresses of remote established connections on local tcp port port. Parses output of shell 'sockstat' (NetBSD) to get connections $ sudo sockstat -4 -n USER COMMAND PID FD PROTO LOCAL ADDRESS FOREIGN ADDRESS root python2.7 1456 29 tcp *.4505 *.* root python2.7 1445 17 tcp *.4506 *.* root python2.7 1294 14 tcp 127.0.0.1.11813 127.0.0.1.4505 root python2.7 1294 41 tcp 127.0.0.1.61115 127.0.0.1.4506 $ sudo sockstat -4 -c -n -p 4506 USER COMMAND PID FD PROTO LOCAL ADDRESS FOREIGN ADDRESS root python2.7 1294 41 tcp 127.0.0.1.61115 127.0.0.1.4506 ''' port = int(port) remotes = set() try: cmd = salt.utils.args.shlex_split('sockstat -4 -c -n -p {0}'.format(port)) data = subprocess.check_output(cmd) # pylint: disable=minimum-python-version except subprocess.CalledProcessError as ex: log.error('Failed "sockstat" with returncode = %s', ex.returncode) raise lines = salt.utils.stringutils.to_str(data).split('\n') for line in lines: chunks = line.split() if not chunks: continue # ['root', 'python2.7', '1456', '37', 'tcp', # '127.0.0.1.4505-', '127.0.0.1.55703'] # print chunks if 'COMMAND' in chunks[1]: continue # ignore header if len(chunks) < 2: continue local = chunks[5].split('.') lport = local.pop() lhost = '.'.join(local) remote = chunks[6].split('.') rport = remote.pop() rhost = '.'.join(remote) if which_end == 'local' and int(lport) != port: # ignore if local port not port continue if which_end == 'remote' and int(rport) != port: # ignore if remote port not port continue remotes.add(rhost) return remotes def _openbsd_remotes_on(port, which_end): ''' OpenBSD specific helper function. Returns set of ipv4 host addresses of remote established connections on local or remote tcp port. Parses output of shell 'netstat' to get connections $ netstat -nf inet Active Internet connections Proto Recv-Q Send-Q Local Address Foreign Address (state) tcp 0 0 10.0.0.101.4505 10.0.0.1.45329 ESTABLISHED tcp 0 0 10.0.0.101.4505 10.0.0.100.50798 ESTABLISHED ''' remotes = set() try: data = subprocess.check_output(['netstat', '-nf', 'inet']) # pylint: disable=minimum-python-version except subprocess.CalledProcessError: log.error('Failed netstat') raise lines = data.split('\n') for line in lines: if 'ESTABLISHED' not in line: continue chunks = line.split() local_host, local_port = chunks[3].rsplit('.', 1) remote_host, remote_port = chunks[4].rsplit('.', 1) if which_end == 'remote_port' and int(remote_port) != port: continue if which_end == 'local_port' and int(local_port) != port: continue remotes.add(remote_host) return remotes def _windows_remotes_on(port, which_end): r''' Windows specific helper function. Returns set of ipv4 host addresses of remote established connections on local or remote tcp port. Parses output of shell 'netstat' to get connections C:\>netstat -n Active Connections Proto Local Address Foreign Address State TCP 10.2.33.17:3007 130.164.12.233:10123 ESTABLISHED TCP 10.2.33.17:3389 130.164.30.5:10378 ESTABLISHED ''' remotes = set() try: data = subprocess.check_output(['netstat', '-n']) # pylint: disable=minimum-python-version except subprocess.CalledProcessError: log.error('Failed netstat') raise lines = salt.utils.stringutils.to_str(data).split('\n') for line in lines: if 'ESTABLISHED' not in line: continue chunks = line.split() local_host, local_port = chunks[1].rsplit(':', 1) remote_host, remote_port = chunks[2].rsplit(':', 1) if which_end == 'remote_port' and int(remote_port) != port: continue if which_end == 'local_port' and int(local_port) != port: continue remotes.add(remote_host) return remotes def _linux_remotes_on(port, which_end): ''' Linux specific helper function. Returns set of ip host addresses of remote established connections on local tcp port port. Parses output of shell 'lsof' to get connections $ sudo lsof -iTCP:4505 -n COMMAND PID USER FD TYPE DEVICE SIZE/OFF NODE NAME Python 9971 root 35u IPv4 0x18a8464a29ca329d 0t0 TCP *:4505 (LISTEN) Python 9971 root 37u IPv4 0x18a8464a29b2b29d 0t0 TCP 127.0.0.1:4505->127.0.0.1:55703 (ESTABLISHED) Python 10152 root 22u IPv4 0x18a8464a29c8cab5 0t0 TCP 127.0.0.1:55703->127.0.0.1:4505 (ESTABLISHED) Python 10153 root 22u IPv4 0x18a8464a29c8cab5 0t0 TCP [fe80::249a]:4505->[fe80::150]:59367 (ESTABLISHED) ''' remotes = set() try: data = subprocess.check_output( ['lsof', '-iTCP:{0:d}'.format(port), '-n', '-P'] # pylint: disable=minimum-python-version ) except subprocess.CalledProcessError as ex: if ex.returncode == 1: # Lsof return 1 if any error was detected, including the failure # to locate Internet addresses, and it is not an error in this case. log.warning('"lsof" returncode = 1, likely no active TCP sessions.') return remotes log.error('Failed "lsof" with returncode = %s', ex.returncode) raise lines = salt.utils.stringutils.to_str(data).split('\n') for line in lines: chunks = line.split() if not chunks: continue # ['Python', '9971', 'root', '37u', 'IPv4', '0x18a8464a29b2b29d', '0t0', # 'TCP', '127.0.0.1:4505->127.0.0.1:55703', '(ESTABLISHED)'] # print chunks if 'COMMAND' in chunks[0]: continue # ignore header if 'ESTABLISHED' not in chunks[-1]: continue # ignore if not ESTABLISHED # '127.0.0.1:4505->127.0.0.1:55703' local, remote = chunks[8].split('->') _, lport = local.rsplit(':', 1) rhost, rport = remote.rsplit(':', 1) if which_end == 'remote_port' and int(rport) != port: continue if which_end == 'local_port' and int(lport) != port: continue remotes.add(rhost.strip("[]")) return remotes def _aix_remotes_on(port, which_end): ''' AIX specific helper function. Returns set of ipv4 host addresses of remote established connections on local or remote tcp port. Parses output of shell 'netstat' to get connections root@la68pp002_pub:/opt/salt/lib/python2.7/site-packages/salt/modules# netstat -f inet -n Active Internet connections Proto Recv-Q Send-Q Local Address Foreign Address (state) tcp4 0 0 172.29.149.95.50093 209.41.78.13.4505 ESTABLISHED tcp4 0 0 127.0.0.1.9514 *.* LISTEN tcp4 0 0 127.0.0.1.9515 *.* LISTEN tcp4 0 0 127.0.0.1.199 127.0.0.1.32779 ESTABLISHED tcp4 0 0 127.0.0.1.32779 127.0.0.1.199 ESTABLISHED tcp4 0 40 172.29.149.95.22 172.29.96.83.41022 ESTABLISHED tcp4 0 0 172.29.149.95.22 172.29.96.83.41032 ESTABLISHED tcp4 0 0 127.0.0.1.32771 127.0.0.1.32775 ESTABLISHED tcp 0 0 127.0.0.1.32775 127.0.0.1.32771 ESTABLISHED tcp4 0 0 127.0.0.1.32771 127.0.0.1.32776 ESTABLISHED tcp 0 0 127.0.0.1.32776 127.0.0.1.32771 ESTABLISHED tcp4 0 0 127.0.0.1.32771 127.0.0.1.32777 ESTABLISHED tcp 0 0 127.0.0.1.32777 127.0.0.1.32771 ESTABLISHED tcp4 0 0 127.0.0.1.32771 127.0.0.1.32778 ESTABLISHED tcp 0 0 127.0.0.1.32778 127.0.0.1.32771 ESTABLISHED ''' remotes = set() try: data = subprocess.check_output(['netstat', '-f', 'inet', '-n']) # pylint: disable=minimum-python-version except subprocess.CalledProcessError: log.error('Failed netstat') raise lines = salt.utils.stringutils.to_str(data).split('\n') for line in lines: if 'ESTABLISHED' not in line: continue chunks = line.split() local_host, local_port = chunks[3].rsplit('.', 1) remote_host, remote_port = chunks[4].rsplit('.', 1) if which_end == 'remote_port' and int(remote_port) != port: continue if which_end == 'local_port' and int(local_port) != port: continue remotes.add(remote_host) return remotes @jinja_filter('gen_mac') def gen_mac(prefix='AC:DE:48'): ''' Generates a MAC address with the defined OUI prefix. Common prefixes: - ``00:16:3E`` -- Xen - ``00:18:51`` -- OpenVZ - ``00:50:56`` -- VMware (manually generated) - ``52:54:00`` -- QEMU/KVM - ``AC:DE:48`` -- PRIVATE References: - http://standards.ieee.org/develop/regauth/oui/oui.txt - https://www.wireshark.org/tools/oui-lookup.html - https://en.wikipedia.org/wiki/MAC_address ''' return '{0}:{1:02X}:{2:02X}:{3:02X}'.format(prefix, random.randint(0, 0xff), random.randint(0, 0xff), random.randint(0, 0xff)) @jinja_filter('mac_str_to_bytes') def mac_str_to_bytes(mac_str): ''' Convert a MAC address string into bytes. Works with or without separators: b1 = mac_str_to_bytes('08:00:27:13:69:77') b2 = mac_str_to_bytes('080027136977') assert b1 == b2 assert isinstance(b1, bytes) ''' if len(mac_str) == 12: pass elif len(mac_str) == 17: sep = mac_str[2] mac_str = mac_str.replace(sep, '') else: raise ValueError('Invalid MAC address') chars = (int(mac_str[s:s+2], 16) for s in range(0, 12, 2)) return bytes(chars) if six.PY3 else b''.join(chr(x) for x in chars) def refresh_dns(): ''' issue #21397: force glibc to re-read resolv.conf ''' try: res_init() except NameError: # Exception raised loading the library, thus res_init is not defined pass @jinja_filter('connection_check') def connection_check(addr, port=80, safe=False, ipv6=None): ''' Provides a convenient alias for the dns_check filter. ''' return dns_check(addr, port, safe, ipv6) @jinja_filter('dns_check') def dns_check(addr, port=80, safe=False, ipv6=None, attempt_connect=True): ''' Return the ip resolved by dns, but do not exit on failure, only raise an exception. Obeys system preference for IPv4/6 address resolution - this can be overridden by the ipv6 flag. Tries to connect to the address before considering it useful. If no address can be reached, the first one resolved is used as a fallback. ''' error = False lookup = addr seen_ipv6 = False family = socket.AF_INET6 if ipv6 else socket.AF_INET if ipv6 is False else socket.AF_UNSPEC hostnames = [] try: refresh_dns() hostnames = socket.getaddrinfo(addr, port, family, socket.SOCK_STREAM) except TypeError: err = ('Attempt to resolve address \'{0}\' failed. Invalid or unresolveable address').format(lookup) raise SaltSystemExit(code=42, msg=err) except socket.error: error = True # If ipv6 is set to True, attempt another lookup using the IPv4 family, # just in case we're attempting to lookup an IPv4 IP # as an IPv6 hostname. if error and ipv6: try: refresh_dns() hostnames = socket.getaddrinfo(addr, port, socket.AF_INET, socket.SOCK_STREAM) except TypeError: err = ('Attempt to resolve address \'{0}\' failed. Invalid or unresolveable address').format(lookup) raise SaltSystemExit(code=42, msg=err) except socket.error: error = True try: if not hostnames: error = True else: resolved = False candidates = [] for h in hostnames: # Input is IP address, passed through unchanged, just return it if h[4][0] == addr: resolved = salt.utils.zeromq.ip_bracket(addr) break candidate_addr = salt.utils.zeromq.ip_bracket(h[4][0]) # sometimes /etc/hosts contains ::1 localhost if not ipv6 and candidate_addr == '[::1]': continue candidates.append(candidate_addr) if attempt_connect: try: s = socket.socket(h[0], socket.SOCK_STREAM) s.settimeout(2) s.connect((candidate_addr.strip('[]'), h[4][1])) s.close() resolved = candidate_addr break except socket.error: pass if not resolved: if candidates: resolved = candidates[0] else: error = True except TypeError: err = ('Attempt to resolve address \'{0}\' failed. Invalid or unresolveable address').format(lookup) raise SaltSystemExit(code=42, msg=err) except socket.error: error = True if error: err = ('DNS lookup or connection check of \'{0}\' failed.').format(addr) if safe: if salt.log.is_console_configured(): # If logging is not configured it also means that either # the master or minion instance calling this hasn't even # started running log.error(err) raise SaltClientError() raise SaltSystemExit(code=42, msg=err) return resolved def parse_host_port(host_port): """ Takes a string argument specifying host or host:port. Returns a (hostname, port) or (ip_address, port) tuple. If no port is given, the second (port) element of the returned tuple will be None. host:port argument, for example, is accepted in the forms of: - hostname - hostname:1234 - hostname.domain.tld - hostname.domain.tld:5678 - [1234::5]:5678 - 1234::5 - 10.11.12.13:4567 - 10.11.12.13 """ host, port = None, None # default _s_ = host_port[:] if _s_[0] == "[": if "]" in host_port: host, _s_ = _s_.lstrip("[").rsplit("]", 1) host = ipaddress.IPv6Address(host).compressed if _s_[0] == ":": port = int(_s_.lstrip(":")) else: if len(_s_) > 1: raise ValueError('found ambiguous "{}" port in "{}"'.format(_s_, host_port)) else: if _s_.count(":") == 1: host, _hostport_separator_, port = _s_.partition(":") try: port = int(port) except ValueError as _e_: log.error('host_port "%s" port value "%s" is not an integer.', host_port, port) raise _e_ else: host = _s_ try: if not isinstance(host, ipaddress._BaseAddress): host_ip = ipaddress.ip_address(host).compressed host = host_ip except ValueError: log.debug('"%s" Not an IP address? Assuming it is a hostname.', host) if host != sanitize_host(host): log.error('bad hostname: "%s"', host) raise ValueError('bad hostname: "{}"'.format(host)) return host, port def is_fqdn(hostname): """ Verify if hostname conforms to be a FQDN. :param hostname: text string with the name of the host :return: bool, True if hostname is correct FQDN, False otherwise """ compliant = re.compile(r"(?!-)[A-Z\d\-\_]{1,63}(?<!-)$", re.IGNORECASE) return "." in hostname and len(hostname) < 0xff and all(compliant.match(x) for x in hostname.rstrip(".").split("."))
saltstack/salt
salt/utils/network.py
cidr_to_ipv4_netmask
python
def cidr_to_ipv4_netmask(cidr_bits): ''' Returns an IPv4 netmask ''' try: cidr_bits = int(cidr_bits) if not 1 <= cidr_bits <= 32: return '' except ValueError: return '' netmask = '' for idx in range(4): if idx: netmask += '.' if cidr_bits >= 8: netmask += '255' cidr_bits -= 8 else: netmask += '{0:d}'.format(256 - (2 ** (8 - cidr_bits))) cidr_bits = 0 return netmask
Returns an IPv4 netmask
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/network.py#L606-L627
null
# -*- coding: utf-8 -*- ''' Define some generic socket functions for network modules ''' # Import python libs from __future__ import absolute_import, unicode_literals, print_function import itertools import os import re import types import socket import logging import platform import random import subprocess from string import ascii_letters, digits # Import 3rd-party libs from salt.ext import six from salt.ext.six.moves import range # pylint: disable=import-error,redefined-builtin # Attempt to import wmi try: import wmi import salt.utils.winapi except ImportError: pass # Import salt libs import salt.utils.args import salt.utils.files import salt.utils.path import salt.utils.platform import salt.utils.stringutils import salt.utils.zeromq from salt._compat import ipaddress from salt.exceptions import SaltClientError, SaltSystemExit from salt.utils.decorators.jinja import jinja_filter from salt.utils.versions import LooseVersion # inet_pton does not exist in Windows, this is a workaround if salt.utils.platform.is_windows(): from salt.ext import win_inet_pton # pylint: disable=unused-import log = logging.getLogger(__name__) try: import ctypes import ctypes.util libc = ctypes.cdll.LoadLibrary(ctypes.util.find_library("c")) res_init = libc.__res_init except (ImportError, OSError, AttributeError, TypeError): pass # pylint: disable=C0103 def sanitize_host(host): ''' Sanitize host string. https://tools.ietf.org/html/rfc1123#section-2.1 ''' RFC952_characters = ascii_letters + digits + ".-" return "".join([c for c in host[0:255] if c in RFC952_characters]) def isportopen(host, port): ''' Return status of a port ''' if not 1 <= int(port) <= 65535: return False sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) out = sock.connect_ex((sanitize_host(host), int(port))) return out def host_to_ips(host): ''' Returns a list of IP addresses of a given hostname or None if not found. ''' ips = [] try: for family, socktype, proto, canonname, sockaddr in socket.getaddrinfo( host, 0, socket.AF_UNSPEC, socket.SOCK_STREAM): if family == socket.AF_INET: ip, port = sockaddr elif family == socket.AF_INET6: ip, port, flow_info, scope_id = sockaddr ips.append(ip) if not ips: ips = None except Exception: ips = None return ips def _generate_minion_id(): ''' Get list of possible host names and convention names. :return: ''' # There are three types of hostnames: # 1. Network names. How host is accessed from the network. # 2. Host aliases. They might be not available in all the network or only locally (/etc/hosts) # 3. Convention names, an internal nodename. class DistinctList(list): ''' List, which allows one to append only distinct objects. Needs to work on Python 2.6, because of collections.OrderedDict only since 2.7 version. Override 'filter()' for custom filtering. ''' localhost_matchers = [r'localhost.*', r'ip6-.*', r'127[.]\d', r'0\.0\.0\.0', r'::1.*', r'ipv6-.*', r'fe00::.*', r'fe02::.*', r'1.0.0.*.ip6.arpa'] def append(self, p_object): if p_object and p_object not in self and not self.filter(p_object): super(DistinctList, self).append(p_object) return self def extend(self, iterable): for obj in iterable: self.append(obj) return self def filter(self, element): 'Returns True if element needs to be filtered' for rgx in self.localhost_matchers: if re.match(rgx, element): return True def first(self): return self and self[0] or None hostname = socket.gethostname() hosts = DistinctList().append( salt.utils.stringutils.to_unicode(socket.getfqdn(salt.utils.stringutils.to_bytes(hostname))) ).append(platform.node()).append(hostname) if not hosts: try: for a_nfo in socket.getaddrinfo(hosts.first() or 'localhost', None, socket.AF_INET, socket.SOCK_RAW, socket.IPPROTO_IP, socket.AI_CANONNAME): if len(a_nfo) > 3: hosts.append(a_nfo[3]) except socket.gaierror: log.warning('Cannot resolve address %s info via socket: %s', hosts.first() or 'localhost (N/A)', socket.gaierror) # Universal method for everywhere (Linux, Slowlaris, Windows etc) for f_name in ('/etc/hostname', '/etc/nodename', '/etc/hosts', r'{win}\system32\drivers\etc\hosts'.format(win=os.getenv('WINDIR'))): try: with salt.utils.files.fopen(f_name) as f_hdl: for line in f_hdl: line = salt.utils.stringutils.to_unicode(line) hst = line.strip().split('#')[0].strip().split() if hst: if hst[0][:4] in ('127.', '::1') or len(hst) == 1: hosts.extend(hst) except IOError: pass # include public and private ipaddresses return hosts.extend([addr for addr in ip_addrs() if not ipaddress.ip_address(addr).is_loopback]) def generate_minion_id(): ''' Return only first element of the hostname from all possible list. :return: ''' try: ret = salt.utils.stringutils.to_unicode(_generate_minion_id().first()) except TypeError: ret = None return ret or 'localhost' def get_socket(addr, type=socket.SOCK_STREAM, proto=0): ''' Return a socket object for the addr IP-version agnostic ''' version = ipaddress.ip_address(addr).version if version == 4: family = socket.AF_INET elif version == 6: family = socket.AF_INET6 return socket.socket(family, type, proto) def get_fqhostname(): ''' Returns the fully qualified hostname ''' # try getaddrinfo() fqdn = None try: addrinfo = socket.getaddrinfo( socket.gethostname(), 0, socket.AF_UNSPEC, socket.SOCK_STREAM, socket.SOL_TCP, socket.AI_CANONNAME ) for info in addrinfo: # info struct [family, socktype, proto, canonname, sockaddr] # On Windows `canonname` can be an empty string # This can cause the function to return `None` if len(info) > 3 and info[3]: fqdn = info[3] break except socket.gaierror: pass # NOTE: this used to log.error() but it was later disabled except socket.error as err: log.debug('socket.getaddrinfo() failure while finding fqdn: %s', err) if fqdn is None: fqdn = socket.getfqdn() return fqdn def ip_to_host(ip): ''' Returns the hostname of a given IP ''' try: hostname, aliaslist, ipaddrlist = socket.gethostbyaddr(ip) except Exception as exc: log.debug('salt.utils.network.ip_to_host(%r) failed: %s', ip, exc) hostname = None return hostname # pylint: enable=C0103 def is_reachable_host(entity_name): ''' Returns a bool telling if the entity name is a reachable host (IPv4/IPv6/FQDN/etc). :param hostname: :return: ''' try: assert type(socket.getaddrinfo(entity_name, 0, 0, 0, 0)) == list ret = True except socket.gaierror: ret = False return ret def is_ip(ip): ''' Returns a bool telling if the passed IP is a valid IPv4 or IPv6 address. ''' return is_ipv4(ip) or is_ipv6(ip) def is_ipv4(ip): ''' Returns a bool telling if the value passed to it was a valid IPv4 address ''' try: return ipaddress.ip_address(ip).version == 4 except ValueError: return False def is_ipv6(ip): ''' Returns a bool telling if the value passed to it was a valid IPv6 address ''' try: return ipaddress.ip_address(ip).version == 6 except ValueError: return False def is_subnet(cidr): ''' Returns a bool telling if the passed string is an IPv4 or IPv6 subnet ''' return is_ipv4_subnet(cidr) or is_ipv6_subnet(cidr) def is_ipv4_subnet(cidr): ''' Returns a bool telling if the passed string is an IPv4 subnet ''' try: return '/' in cidr and bool(ipaddress.IPv4Network(cidr)) except Exception: return False def is_ipv6_subnet(cidr): ''' Returns a bool telling if the passed string is an IPv6 subnet ''' try: return '/' in cidr and bool(ipaddress.IPv6Network(cidr)) except Exception: return False @jinja_filter('is_ip') def is_ip_filter(ip, options=None): ''' Returns a bool telling if the passed IP is a valid IPv4 or IPv6 address. ''' return is_ipv4_filter(ip, options=options) or is_ipv6_filter(ip, options=options) def _ip_options_global(ip_obj, version): return not ip_obj.is_private def _ip_options_multicast(ip_obj, version): return ip_obj.is_multicast def _ip_options_loopback(ip_obj, version): return ip_obj.is_loopback def _ip_options_link_local(ip_obj, version): return ip_obj.is_link_local def _ip_options_private(ip_obj, version): return ip_obj.is_private def _ip_options_reserved(ip_obj, version): return ip_obj.is_reserved def _ip_options_site_local(ip_obj, version): if version == 6: return ip_obj.is_site_local return False def _ip_options_unspecified(ip_obj, version): return ip_obj.is_unspecified def _ip_options(ip_obj, version, options=None): # will process and IP options options_fun_map = { 'global': _ip_options_global, 'link-local': _ip_options_link_local, 'linklocal': _ip_options_link_local, 'll': _ip_options_link_local, 'link_local': _ip_options_link_local, 'loopback': _ip_options_loopback, 'lo': _ip_options_loopback, 'multicast': _ip_options_multicast, 'private': _ip_options_private, 'public': _ip_options_global, 'reserved': _ip_options_reserved, 'site-local': _ip_options_site_local, 'sl': _ip_options_site_local, 'site_local': _ip_options_site_local, 'unspecified': _ip_options_unspecified } if not options: return six.text_type(ip_obj) # IP version already checked options_list = [option.strip() for option in options.split(',')] for option, fun in options_fun_map.items(): if option in options_list: fun_res = fun(ip_obj, version) if not fun_res: return None # stop at first failed test # else continue return six.text_type(ip_obj) def _is_ipv(ip, version, options=None): if not version: version = 4 if version not in (4, 6): return None try: ip_obj = ipaddress.ip_address(ip) except ValueError: # maybe it is an IP network try: ip_obj = ipaddress.ip_interface(ip) except ValueError: # nope, still not :( return None if not ip_obj.version == version: return None # has the right version, let's move on return _ip_options(ip_obj, version, options=options) @jinja_filter('is_ipv4') def is_ipv4_filter(ip, options=None): ''' Returns a bool telling if the value passed to it was a valid IPv4 address. ip The IP address. net: False Consider IP addresses followed by netmask. options CSV of options regarding the nature of the IP address. E.g.: loopback, multicast, private etc. ''' _is_ipv4 = _is_ipv(ip, 4, options=options) return isinstance(_is_ipv4, six.string_types) @jinja_filter('is_ipv6') def is_ipv6_filter(ip, options=None): ''' Returns a bool telling if the value passed to it was a valid IPv6 address. ip The IP address. net: False Consider IP addresses followed by netmask. options CSV of options regarding the nature of the IP address. E.g.: loopback, multicast, private etc. ''' _is_ipv6 = _is_ipv(ip, 6, options=options) return isinstance(_is_ipv6, six.string_types) def _ipv_filter(value, version, options=None): if version not in (4, 6): return if isinstance(value, (six.string_types, six.text_type, six.binary_type)): return _is_ipv(value, version, options=options) # calls is_ipv4 or is_ipv6 for `value` elif isinstance(value, (list, tuple, types.GeneratorType)): # calls is_ipv4 or is_ipv6 for each element in the list # os it filters and returns only those elements having the desired IP version return [ _is_ipv(addr, version, options=options) for addr in value if _is_ipv(addr, version, options=options) is not None ] return None @jinja_filter('ipv4') def ipv4(value, options=None): ''' Filters a list and returns IPv4 values only. ''' return _ipv_filter(value, 4, options=options) @jinja_filter('ipv6') def ipv6(value, options=None): ''' Filters a list and returns IPv6 values only. ''' return _ipv_filter(value, 6, options=options) @jinja_filter('ipaddr') def ipaddr(value, options=None): ''' Filters and returns only valid IP objects. ''' ipv4_obj = ipv4(value, options=options) ipv6_obj = ipv6(value, options=options) if ipv4_obj is None or ipv6_obj is None: # an IP address can be either IPv4 either IPv6 # therefofe if the value passed as arg is not a list, at least one of the calls above will return None # if one of them is none, means that we should return only one of them return ipv4_obj or ipv6_obj # one of them else: return ipv4_obj + ipv6_obj # extend lists def _filter_ipaddr(value, options, version=None): ipaddr_filter_out = None if version: if version == 4: ipaddr_filter_out = ipv4(value, options) elif version == 6: ipaddr_filter_out = ipv6(value, options) else: ipaddr_filter_out = ipaddr(value, options) if not ipaddr_filter_out: return if not isinstance(ipaddr_filter_out, (list, tuple, types.GeneratorType)): ipaddr_filter_out = [ipaddr_filter_out] return ipaddr_filter_out @jinja_filter('ip_host') def ip_host(value, options=None, version=None): ''' Returns the interfaces IP address, e.g.: 192.168.0.1/28. ''' ipaddr_filter_out = _filter_ipaddr(value, options=options, version=version) if not ipaddr_filter_out: return if not isinstance(value, (list, tuple, types.GeneratorType)): return six.text_type(ipaddress.ip_interface(ipaddr_filter_out[0])) return [six.text_type(ipaddress.ip_interface(ip_a)) for ip_a in ipaddr_filter_out] def _network_hosts(ip_addr_entry): return [ six.text_type(host) for host in ipaddress.ip_network(ip_addr_entry, strict=False).hosts() ] @jinja_filter('network_hosts') def network_hosts(value, options=None, version=None): ''' Return the list of hosts within a network. .. note:: When running this command with a large IPv6 network, the command will take a long time to gather all of the hosts. ''' ipaddr_filter_out = _filter_ipaddr(value, options=options, version=version) if not ipaddr_filter_out: return if not isinstance(value, (list, tuple, types.GeneratorType)): return _network_hosts(ipaddr_filter_out[0]) return [ _network_hosts(ip_a) for ip_a in ipaddr_filter_out ] def _network_size(ip_addr_entry): return ipaddress.ip_network(ip_addr_entry, strict=False).num_addresses @jinja_filter('network_size') def network_size(value, options=None, version=None): ''' Get the size of a network. ''' ipaddr_filter_out = _filter_ipaddr(value, options=options, version=version) if not ipaddr_filter_out: return if not isinstance(value, (list, tuple, types.GeneratorType)): return _network_size(ipaddr_filter_out[0]) return [ _network_size(ip_a) for ip_a in ipaddr_filter_out ] def natural_ipv4_netmask(ip, fmt='prefixlen'): ''' Returns the "natural" mask of an IPv4 address ''' bits = _ipv4_to_bits(ip) if bits.startswith('11'): mask = '24' elif bits.startswith('1'): mask = '16' else: mask = '8' if fmt == 'netmask': return cidr_to_ipv4_netmask(mask) else: return '/' + mask def rpad_ipv4_network(ip): ''' Returns an IP network address padded with zeros. Ex: '192.168.3' -> '192.168.3.0' '10.209' -> '10.209.0.0' ''' return '.'.join(itertools.islice(itertools.chain(ip.split('.'), '0000'), 0, 4)) def _number_of_set_bits_to_ipv4_netmask(set_bits): # pylint: disable=C0103 ''' Returns an IPv4 netmask from the integer representation of that mask. Ex. 0xffffff00 -> '255.255.255.0' ''' return cidr_to_ipv4_netmask(_number_of_set_bits(set_bits)) # pylint: disable=C0103 def _number_of_set_bits(x): ''' Returns the number of bits that are set in a 32bit int ''' # Taken from http://stackoverflow.com/a/4912729. Many thanks! x -= (x >> 1) & 0x55555555 x = ((x >> 2) & 0x33333333) + (x & 0x33333333) x = ((x >> 4) + x) & 0x0f0f0f0f x += x >> 8 x += x >> 16 return x & 0x0000003f # pylint: enable=C0103 def _interfaces_ip(out): ''' Uses ip to return a dictionary of interfaces with various information about each (up/down state, ip address, netmask, and hwaddr) ''' ret = dict() def parse_network(value, cols): ''' Return a tuple of ip, netmask, broadcast based on the current set of cols ''' brd = None scope = None if '/' in value: # we have a CIDR in this address ip, cidr = value.split('/') # pylint: disable=C0103 else: ip = value # pylint: disable=C0103 cidr = 32 if type_ == 'inet': mask = cidr_to_ipv4_netmask(int(cidr)) if 'brd' in cols: brd = cols[cols.index('brd') + 1] elif type_ == 'inet6': mask = cidr if 'scope' in cols: scope = cols[cols.index('scope') + 1] return (ip, mask, brd, scope) groups = re.compile('\r?\n\\d').split(out) for group in groups: iface = None data = dict() for line in group.splitlines(): if ' ' not in line: continue match = re.match(r'^\d*:\s+([\w.\-]+)(?:@)?([\w.\-]+)?:\s+<(.+)>', line) if match: iface, parent, attrs = match.groups() if 'UP' in attrs.split(','): data['up'] = True else: data['up'] = False if parent: data['parent'] = parent continue cols = line.split() if len(cols) >= 2: type_, value = tuple(cols[0:2]) iflabel = cols[-1:][0] if type_ in ('inet', 'inet6'): if 'secondary' not in cols: ipaddr, netmask, broadcast, scope = parse_network(value, cols) if type_ == 'inet': if 'inet' not in data: data['inet'] = list() addr_obj = dict() addr_obj['address'] = ipaddr addr_obj['netmask'] = netmask addr_obj['broadcast'] = broadcast addr_obj['label'] = iflabel data['inet'].append(addr_obj) elif type_ == 'inet6': if 'inet6' not in data: data['inet6'] = list() addr_obj = dict() addr_obj['address'] = ipaddr addr_obj['prefixlen'] = netmask addr_obj['scope'] = scope data['inet6'].append(addr_obj) else: if 'secondary' not in data: data['secondary'] = list() ip_, mask, brd, scp = parse_network(value, cols) data['secondary'].append({ 'type': type_, 'address': ip_, 'netmask': mask, 'broadcast': brd, 'label': iflabel, }) del ip_, mask, brd, scp elif type_.startswith('link'): data['hwaddr'] = value if iface: ret[iface] = data del iface, data return ret def _interfaces_ifconfig(out): ''' Uses ifconfig to return a dictionary of interfaces with various information about each (up/down state, ip address, netmask, and hwaddr) ''' ret = dict() piface = re.compile(r'^([^\s:]+)') pmac = re.compile('.*?(?:HWaddr|ether|address:|lladdr) ([0-9a-fA-F:]+)') if salt.utils.platform.is_sunos(): pip = re.compile(r'.*?(?:inet\s+)([0-9]+\.[0-9]+\.[0-9]+\.[0-9]+)(.*)') pip6 = re.compile('.*?(?:inet6 )([0-9a-fA-F:]+)') pmask6 = re.compile(r'.*?(?:inet6 [0-9a-fA-F:]+/(\d+)).*') else: pip = re.compile(r'.*?(?:inet addr:|inet [^\d]*)(.*?)\s') pip6 = re.compile('.*?(?:inet6 addr: (.*?)/|inet6 )([0-9a-fA-F:]+)') pmask6 = re.compile(r'.*?(?:inet6 addr: [0-9a-fA-F:]+/(\d+)|prefixlen (\d+))(?: Scope:([a-zA-Z]+)| scopeid (0x[0-9a-fA-F]))?') pmask = re.compile(r'.*?(?:Mask:|netmask )(?:((?:0x)?[0-9a-fA-F]{8})|([\d\.]+))') pupdown = re.compile('UP') pbcast = re.compile(r'.*?(?:Bcast:|broadcast )([\d\.]+)') groups = re.compile('\r?\n(?=\\S)').split(out) for group in groups: data = dict() iface = '' updown = False for line in group.splitlines(): miface = piface.match(line) mmac = pmac.match(line) mip = pip.match(line) mip6 = pip6.match(line) mupdown = pupdown.search(line) if miface: iface = miface.group(1) if mmac: data['hwaddr'] = mmac.group(1) if salt.utils.platform.is_sunos(): expand_mac = [] for chunk in data['hwaddr'].split(':'): expand_mac.append('0{0}'.format(chunk) if len(chunk) < 2 else '{0}'.format(chunk)) data['hwaddr'] = ':'.join(expand_mac) if mip: if 'inet' not in data: data['inet'] = list() addr_obj = dict() addr_obj['address'] = mip.group(1) mmask = pmask.match(line) if mmask: if mmask.group(1): mmask = _number_of_set_bits_to_ipv4_netmask( int(mmask.group(1), 16)) else: mmask = mmask.group(2) addr_obj['netmask'] = mmask mbcast = pbcast.match(line) if mbcast: addr_obj['broadcast'] = mbcast.group(1) data['inet'].append(addr_obj) if mupdown: updown = True if mip6: if 'inet6' not in data: data['inet6'] = list() addr_obj = dict() addr_obj['address'] = mip6.group(1) or mip6.group(2) mmask6 = pmask6.match(line) if mmask6: addr_obj['prefixlen'] = mmask6.group(1) or mmask6.group(2) if not salt.utils.platform.is_sunos(): ipv6scope = mmask6.group(3) or mmask6.group(4) addr_obj['scope'] = ipv6scope.lower() if ipv6scope is not None else ipv6scope # SunOS sometimes has ::/0 as inet6 addr when using addrconf if not salt.utils.platform.is_sunos() \ or addr_obj['address'] != '::' \ and addr_obj['prefixlen'] != 0: data['inet6'].append(addr_obj) data['up'] = updown if iface in ret: # SunOS optimization, where interfaces occur twice in 'ifconfig -a' # output with the same name: for ipv4 and then for ipv6 addr family. # Every instance has it's own 'UP' status and we assume that ipv4 # status determines global interface status. # # merge items with higher priority for older values # after that merge the inet and inet6 sub items for both ret[iface] = dict(list(data.items()) + list(ret[iface].items())) if 'inet' in data: ret[iface]['inet'].extend(x for x in data['inet'] if x not in ret[iface]['inet']) if 'inet6' in data: ret[iface]['inet6'].extend(x for x in data['inet6'] if x not in ret[iface]['inet6']) else: ret[iface] = data del data return ret def linux_interfaces(): ''' Obtain interface information for *NIX/BSD variants ''' ifaces = dict() ip_path = salt.utils.path.which('ip') ifconfig_path = None if ip_path else salt.utils.path.which('ifconfig') if ip_path: cmd1 = subprocess.Popen( '{0} link show'.format(ip_path), shell=True, close_fds=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT).communicate()[0] cmd2 = subprocess.Popen( '{0} addr show'.format(ip_path), shell=True, close_fds=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT).communicate()[0] ifaces = _interfaces_ip("{0}\n{1}".format( salt.utils.stringutils.to_str(cmd1), salt.utils.stringutils.to_str(cmd2))) elif ifconfig_path: cmd = subprocess.Popen( '{0} -a'.format(ifconfig_path), shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT).communicate()[0] ifaces = _interfaces_ifconfig(salt.utils.stringutils.to_str(cmd)) return ifaces def _netbsd_interfaces_ifconfig(out): ''' Uses ifconfig to return a dictionary of interfaces with various information about each (up/down state, ip address, netmask, and hwaddr) ''' ret = dict() piface = re.compile(r'^([^\s:]+)') pmac = re.compile('.*?address: ([0-9a-f:]+)') pip = re.compile(r'.*?inet [^\d]*(.*?)/([\d]*)\s') pip6 = re.compile(r'.*?inet6 ([0-9a-f:]+)%([a-zA-Z0-9]*)/([\d]*)\s') pupdown = re.compile('UP') pbcast = re.compile(r'.*?broadcast ([\d\.]+)') groups = re.compile('\r?\n(?=\\S)').split(out) for group in groups: data = dict() iface = '' updown = False for line in group.splitlines(): miface = piface.match(line) mmac = pmac.match(line) mip = pip.match(line) mip6 = pip6.match(line) mupdown = pupdown.search(line) if miface: iface = miface.group(1) if mmac: data['hwaddr'] = mmac.group(1) if mip: if 'inet' not in data: data['inet'] = list() addr_obj = dict() addr_obj['address'] = mip.group(1) mmask = mip.group(2) if mip.group(2): addr_obj['netmask'] = cidr_to_ipv4_netmask(mip.group(2)) mbcast = pbcast.match(line) if mbcast: addr_obj['broadcast'] = mbcast.group(1) data['inet'].append(addr_obj) if mupdown: updown = True if mip6: if 'inet6' not in data: data['inet6'] = list() addr_obj = dict() addr_obj['address'] = mip6.group(1) mmask6 = mip6.group(3) addr_obj['scope'] = mip6.group(2) addr_obj['prefixlen'] = mip6.group(3) data['inet6'].append(addr_obj) data['up'] = updown ret[iface] = data del data return ret def netbsd_interfaces(): ''' Obtain interface information for NetBSD >= 8 where the ifconfig output diverged from other BSD variants (Netmask is now part of the address) ''' # NetBSD versions prior to 8.0 can still use linux_interfaces() if LooseVersion(os.uname()[2]) < LooseVersion('8.0'): return linux_interfaces() ifconfig_path = salt.utils.path.which('ifconfig') cmd = subprocess.Popen( '{0} -a'.format(ifconfig_path), shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT).communicate()[0] return _netbsd_interfaces_ifconfig(salt.utils.stringutils.to_str(cmd)) def _interfaces_ipconfig(out): ''' Returns a dictionary of interfaces with various information about each (up/down state, ip address, netmask, and hwaddr) NOTE: This is not used by any function and may be able to be removed in the future. ''' ifaces = dict() iface = None adapter_iface_regex = re.compile(r'adapter (\S.+):$') for line in out.splitlines(): if not line: continue # TODO what does Windows call Infiniband and 10/40gige adapters if line.startswith('Ethernet'): iface = ifaces[adapter_iface_regex.search(line).group(1)] iface['up'] = True addr = None continue if iface: key, val = line.split(',', 1) key = key.strip(' .') val = val.strip() if addr and key == 'Subnet Mask': addr['netmask'] = val elif key in ('IP Address', 'IPv4 Address'): if 'inet' not in iface: iface['inet'] = list() addr = {'address': val.rstrip('(Preferred)'), 'netmask': None, 'broadcast': None} # TODO find the broadcast iface['inet'].append(addr) elif 'IPv6 Address' in key: if 'inet6' not in iface: iface['inet'] = list() # XXX What is the prefixlen!? addr = {'address': val.rstrip('(Preferred)'), 'prefixlen': None} iface['inet6'].append(addr) elif key == 'Physical Address': iface['hwaddr'] = val elif key == 'Media State': # XXX seen used for tunnel adaptors # might be useful iface['up'] = (val != 'Media disconnected') def win_interfaces(): ''' Obtain interface information for Windows systems ''' with salt.utils.winapi.Com(): c = wmi.WMI() ifaces = {} for iface in c.Win32_NetworkAdapterConfiguration(IPEnabled=1): ifaces[iface.Description] = dict() if iface.MACAddress: ifaces[iface.Description]['hwaddr'] = iface.MACAddress if iface.IPEnabled: ifaces[iface.Description]['up'] = True for ip in iface.IPAddress: if '.' in ip: if 'inet' not in ifaces[iface.Description]: ifaces[iface.Description]['inet'] = [] item = {'address': ip, 'label': iface.Description} if iface.DefaultIPGateway: broadcast = next((i for i in iface.DefaultIPGateway if '.' in i), '') if broadcast: item['broadcast'] = broadcast if iface.IPSubnet: netmask = next((i for i in iface.IPSubnet if '.' in i), '') if netmask: item['netmask'] = netmask ifaces[iface.Description]['inet'].append(item) if ':' in ip: if 'inet6' not in ifaces[iface.Description]: ifaces[iface.Description]['inet6'] = [] item = {'address': ip} if iface.DefaultIPGateway: broadcast = next((i for i in iface.DefaultIPGateway if ':' in i), '') if broadcast: item['broadcast'] = broadcast if iface.IPSubnet: netmask = next((i for i in iface.IPSubnet if ':' in i), '') if netmask: item['netmask'] = netmask ifaces[iface.Description]['inet6'].append(item) else: ifaces[iface.Description]['up'] = False return ifaces def interfaces(): ''' Return a dictionary of information about all the interfaces on the minion ''' if salt.utils.platform.is_windows(): return win_interfaces() elif salt.utils.platform.is_netbsd(): return netbsd_interfaces() else: return linux_interfaces() def get_net_start(ipaddr, netmask): ''' Return the address of the network ''' net = ipaddress.ip_network('{0}/{1}'.format(ipaddr, netmask), strict=False) return six.text_type(net.network_address) def get_net_size(mask): ''' Turns an IPv4 netmask into it's corresponding prefix length (255.255.255.0 -> 24 as in 192.168.1.10/24). ''' binary_str = '' for octet in mask.split('.'): binary_str += bin(int(octet))[2:].zfill(8) return len(binary_str.rstrip('0')) def calc_net(ipaddr, netmask=None): ''' Takes IP (CIDR notation supported) and optionally netmask and returns the network in CIDR-notation. (The IP can be any IP inside the subnet) ''' if netmask is not None: ipaddr = '{0}/{1}'.format(ipaddr, netmask) return six.text_type(ipaddress.ip_network(ipaddr, strict=False)) def _ipv4_to_bits(ipaddr): ''' Accepts an IPv4 dotted quad and returns a string representing its binary counterpart ''' return ''.join([bin(int(x))[2:].rjust(8, '0') for x in ipaddr.split('.')]) def _get_iface_info(iface): ''' If `iface` is available, return interface info and no error, otherwise return no info and log and return an error ''' iface_info = interfaces() if iface in iface_info.keys(): return iface_info, False else: error_msg = ('Interface "{0}" not in available interfaces: "{1}"' ''.format(iface, '", "'.join(iface_info.keys()))) log.error(error_msg) return None, error_msg def _hw_addr_aix(iface): ''' Return the hardware address (a.k.a. MAC address) for a given interface on AIX MAC address not available in through interfaces ''' cmd = subprocess.Popen( 'entstat -d {0} | grep \'Hardware Address\''.format(iface), shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT).communicate()[0] if cmd: comps = cmd.split(' ') if len(comps) == 3: mac_addr = comps[2].strip('\'').strip() return mac_addr error_msg = ('Interface "{0}" either not available or does not contain a hardware address'.format(iface)) log.error(error_msg) return error_msg def hw_addr(iface): ''' Return the hardware address (a.k.a. MAC address) for a given interface .. versionchanged:: 2016.11.4 Added support for AIX ''' if salt.utils.platform.is_aix(): return _hw_addr_aix iface_info, error = _get_iface_info(iface) if error is False: return iface_info.get(iface, {}).get('hwaddr', '') else: return error def interface(iface): ''' Return the details of `iface` or an error if it does not exist ''' iface_info, error = _get_iface_info(iface) if error is False: return iface_info.get(iface, {}).get('inet', '') else: return error def interface_ip(iface): ''' Return `iface` IPv4 addr or an error if `iface` does not exist ''' iface_info, error = _get_iface_info(iface) if error is False: inet = iface_info.get(iface, {}).get('inet', None) return inet[0].get('address', '') if inet else '' else: return error def _subnets(proto='inet', interfaces_=None): ''' Returns a list of subnets to which the host belongs ''' if interfaces_ is None: ifaces = interfaces() elif isinstance(interfaces_, list): ifaces = {} for key, value in six.iteritems(interfaces()): if key in interfaces_: ifaces[key] = value else: ifaces = {interfaces_: interfaces().get(interfaces_, {})} ret = set() if proto == 'inet': subnet = 'netmask' dflt_cidr = 32 elif proto == 'inet6': subnet = 'prefixlen' dflt_cidr = 128 else: log.error('Invalid proto %s calling subnets()', proto) return for ip_info in six.itervalues(ifaces): addrs = ip_info.get(proto, []) addrs.extend([addr for addr in ip_info.get('secondary', []) if addr.get('type') == proto]) for intf in addrs: if subnet in intf: intf = ipaddress.ip_interface('{0}/{1}'.format(intf['address'], intf[subnet])) else: intf = ipaddress.ip_interface('{0}/{1}'.format(intf['address'], dflt_cidr)) if not intf.is_loopback: ret.add(intf.network) return [six.text_type(net) for net in sorted(ret)] def subnets(interfaces=None): ''' Returns a list of IPv4 subnets to which the host belongs ''' return _subnets('inet', interfaces_=interfaces) def subnets6(): ''' Returns a list of IPv6 subnets to which the host belongs ''' return _subnets('inet6') def in_subnet(cidr, addr=None): ''' Returns True if host or (any of) addrs is within specified subnet, otherwise False ''' try: cidr = ipaddress.ip_network(cidr) except ValueError: log.error('Invalid CIDR \'%s\'', cidr) return False if addr is None: addr = ip_addrs() addr.extend(ip_addrs6()) elif not isinstance(addr, (list, tuple)): addr = (addr,) return any(ipaddress.ip_address(item) in cidr for item in addr) def _ip_addrs(interface=None, include_loopback=False, interface_data=None, proto='inet'): ''' Return the full list of IP adresses matching the criteria proto = inet|inet6 ''' ret = set() ifaces = interface_data \ if isinstance(interface_data, dict) \ else interfaces() if interface is None: target_ifaces = ifaces else: target_ifaces = dict([(k, v) for k, v in six.iteritems(ifaces) if k == interface]) if not target_ifaces: log.error('Interface %s not found.', interface) for ip_info in six.itervalues(target_ifaces): addrs = ip_info.get(proto, []) addrs.extend([addr for addr in ip_info.get('secondary', []) if addr.get('type') == proto]) for addr in addrs: addr = ipaddress.ip_address(addr.get('address')) if not addr.is_loopback or include_loopback: ret.add(addr) return [six.text_type(addr) for addr in sorted(ret)] def ip_addrs(interface=None, include_loopback=False, interface_data=None): ''' Returns a list of IPv4 addresses assigned to the host. 127.0.0.1 is ignored, unless 'include_loopback=True' is indicated. If 'interface' is provided, then only IP addresses from that interface will be returned. ''' return _ip_addrs(interface, include_loopback, interface_data, 'inet') def ip_addrs6(interface=None, include_loopback=False, interface_data=None): ''' Returns a list of IPv6 addresses assigned to the host. ::1 is ignored, unless 'include_loopback=True' is indicated. If 'interface' is provided, then only IP addresses from that interface will be returned. ''' return _ip_addrs(interface, include_loopback, interface_data, 'inet6') def hex2ip(hex_ip, invert=False): ''' Convert a hex string to an ip, if a failure occurs the original hex is returned. If 'invert=True' assume that ip from /proc/net/<proto> ''' if len(hex_ip) == 32: # ipv6 ip = [] for i in range(0, 32, 8): ip_part = hex_ip[i:i + 8] ip_part = [ip_part[x:x + 2] for x in range(0, 8, 2)] if invert: ip.append("{0[3]}{0[2]}:{0[1]}{0[0]}".format(ip_part)) else: ip.append("{0[0]}{0[1]}:{0[2]}{0[3]}".format(ip_part)) try: address = ipaddress.IPv6Address(":".join(ip)) if address.ipv4_mapped: return str(address.ipv4_mapped) else: return address.compressed except ipaddress.AddressValueError as ex: log.error('hex2ip - ipv6 address error: %s', ex) return hex_ip try: hip = int(hex_ip, 16) except ValueError: return hex_ip if invert: return '{3}.{2}.{1}.{0}'.format(hip >> 24 & 255, hip >> 16 & 255, hip >> 8 & 255, hip & 255) return '{0}.{1}.{2}.{3}'.format(hip >> 24 & 255, hip >> 16 & 255, hip >> 8 & 255, hip & 255) def mac2eui64(mac, prefix=None): ''' Convert a MAC address to a EUI64 identifier or, with prefix provided, a full IPv6 address ''' # http://tools.ietf.org/html/rfc4291#section-2.5.1 eui64 = re.sub(r'[.:-]', '', mac).lower() eui64 = eui64[0:6] + 'fffe' + eui64[6:] eui64 = hex(int(eui64[0:2], 16) | 2)[2:].zfill(2) + eui64[2:] if prefix is None: return ':'.join(re.findall(r'.{4}', eui64)) else: try: net = ipaddress.ip_network(prefix, strict=False) euil = int('0x{0}'.format(eui64), 16) return '{0}/{1}'.format(net[euil], net.prefixlen) except Exception: return def active_tcp(): ''' Return a dict describing all active tcp connections as quickly as possible ''' ret = {} for statf in ['/proc/net/tcp', '/proc/net/tcp6']: if os.path.isfile(statf): with salt.utils.files.fopen(statf, 'rb') as fp_: for line in fp_: line = salt.utils.stringutils.to_unicode(line) if line.strip().startswith('sl'): continue iret = _parse_tcp_line(line) sl = next(iter(iret)) if iret[sl]['state'] == 1: # 1 is ESTABLISHED del iret[sl]['state'] ret[len(ret)] = iret[sl] return ret def local_port_tcp(port): ''' Return a set of remote ip addrs attached to the specified local port ''' ret = _remotes_on(port, 'local_port') return ret def remote_port_tcp(port): ''' Return a set of ip addrs the current host is connected to on given port ''' ret = _remotes_on(port, 'remote_port') return ret def _remotes_on(port, which_end): ''' Return a set of ip addrs active tcp connections ''' port = int(port) ret = _netlink_tool_remote_on(port, which_end) if ret is not None: return ret ret = set() proc_available = False for statf in ['/proc/net/tcp', '/proc/net/tcp6']: if os.path.isfile(statf): proc_available = True with salt.utils.files.fopen(statf, 'r') as fp_: for line in fp_: line = salt.utils.stringutils.to_unicode(line) if line.strip().startswith('sl'): continue iret = _parse_tcp_line(line) sl = next(iter(iret)) if iret[sl][which_end] == port and iret[sl]['state'] == 1: # 1 is ESTABLISHED ret.add(iret[sl]['remote_addr']) if not proc_available: # Fallback to use OS specific tools if salt.utils.platform.is_sunos(): return _sunos_remotes_on(port, which_end) if salt.utils.platform.is_freebsd(): return _freebsd_remotes_on(port, which_end) if salt.utils.platform.is_netbsd(): return _netbsd_remotes_on(port, which_end) if salt.utils.platform.is_openbsd(): return _openbsd_remotes_on(port, which_end) if salt.utils.platform.is_windows(): return _windows_remotes_on(port, which_end) if salt.utils.platform.is_aix(): return _aix_remotes_on(port, which_end) return _linux_remotes_on(port, which_end) return ret def _parse_tcp_line(line): ''' Parse a single line from the contents of /proc/net/tcp or /proc/net/tcp6 ''' ret = {} comps = line.strip().split() sl = comps[0].rstrip(':') ret[sl] = {} l_addr, l_port = comps[1].split(':') r_addr, r_port = comps[2].split(':') ret[sl]['local_addr'] = hex2ip(l_addr, True) ret[sl]['local_port'] = int(l_port, 16) ret[sl]['remote_addr'] = hex2ip(r_addr, True) ret[sl]['remote_port'] = int(r_port, 16) ret[sl]['state'] = int(comps[3], 16) return ret def _netlink_tool_remote_on(port, which_end): ''' Returns set of ipv4 host addresses of remote established connections on local or remote tcp port. Parses output of shell 'ss' to get connections [root@salt-master ~]# ss -ant State Recv-Q Send-Q Local Address:Port Peer Address:Port LISTEN 0 511 *:80 *:* LISTEN 0 128 *:22 *:* ESTAB 0 0 127.0.0.1:56726 127.0.0.1:4505 ''' remotes = set() valid = False try: data = subprocess.check_output(['ss', '-ant']) # pylint: disable=minimum-python-version except subprocess.CalledProcessError: log.error('Failed ss') raise except OSError: # not command "No such file or directory" return None lines = salt.utils.stringutils.to_str(data).split('\n') for line in lines: if 'Address:Port' in line: # ss tools may not be valid valid = True continue elif 'ESTAB' not in line: continue chunks = line.split() local_host, local_port = chunks[3].split(':', 1) remote_host, remote_port = chunks[4].split(':', 1) if which_end == 'remote_port' and int(remote_port) != port: continue if which_end == 'local_port' and int(local_port) != port: continue remotes.add(remote_host) if valid is False: remotes = None return remotes def _sunos_remotes_on(port, which_end): ''' SunOS specific helper function. Returns set of ipv4 host addresses of remote established connections on local or remote tcp port. Parses output of shell 'netstat' to get connections [root@salt-master ~]# netstat -f inet -n TCP: IPv4 Local Address Remote Address Swind Send-Q Rwind Recv-Q State -------------------- -------------------- ----- ------ ----- ------ ----------- 10.0.0.101.4505 10.0.0.1.45329 1064800 0 1055864 0 ESTABLISHED 10.0.0.101.4505 10.0.0.100.50798 1064800 0 1055864 0 ESTABLISHED ''' remotes = set() try: data = subprocess.check_output(['netstat', '-f', 'inet', '-n']) # pylint: disable=minimum-python-version except subprocess.CalledProcessError: log.error('Failed netstat') raise lines = salt.utils.stringutils.to_str(data).split('\n') for line in lines: if 'ESTABLISHED' not in line: continue chunks = line.split() local_host, local_port = chunks[0].rsplit('.', 1) remote_host, remote_port = chunks[1].rsplit('.', 1) if which_end == 'remote_port' and int(remote_port) != port: continue if which_end == 'local_port' and int(local_port) != port: continue remotes.add(remote_host) return remotes def _freebsd_remotes_on(port, which_end): ''' Returns set of ipv4 host addresses of remote established connections on local tcp port port. Parses output of shell 'sockstat' (FreeBSD) to get connections $ sudo sockstat -4 USER COMMAND PID FD PROTO LOCAL ADDRESS FOREIGN ADDRESS root python2.7 1456 29 tcp4 *:4505 *:* root python2.7 1445 17 tcp4 *:4506 *:* root python2.7 1294 14 tcp4 127.0.0.1:11813 127.0.0.1:4505 root python2.7 1294 41 tcp4 127.0.0.1:61115 127.0.0.1:4506 $ sudo sockstat -4 -c -p 4506 USER COMMAND PID FD PROTO LOCAL ADDRESS FOREIGN ADDRESS root python2.7 1294 41 tcp4 127.0.0.1:61115 127.0.0.1:4506 ''' port = int(port) remotes = set() try: cmd = salt.utils.args.shlex_split('sockstat -4 -c -p {0}'.format(port)) data = subprocess.check_output(cmd) # pylint: disable=minimum-python-version except subprocess.CalledProcessError as ex: log.error('Failed "sockstat" with returncode = %s', ex.returncode) raise lines = salt.utils.stringutils.to_str(data).split('\n') for line in lines: chunks = line.split() if not chunks: continue # ['root', 'python2.7', '1456', '37', 'tcp4', # '127.0.0.1:4505-', '127.0.0.1:55703'] # print chunks if 'COMMAND' in chunks[1]: continue # ignore header if len(chunks) < 2: continue # sockstat -4 -c -p 4506 does this with high PIDs: # USER COMMAND PID FD PROTO LOCAL ADDRESS FOREIGN ADDRESS # salt-master python2.781106 35 tcp4 192.168.12.34:4506 192.168.12.45:60143 local = chunks[-2] remote = chunks[-1] lhost, lport = local.split(':') rhost, rport = remote.split(':') if which_end == 'local' and int(lport) != port: # ignore if local port not port continue if which_end == 'remote' and int(rport) != port: # ignore if remote port not port continue remotes.add(rhost) return remotes def _netbsd_remotes_on(port, which_end): ''' Returns set of ipv4 host addresses of remote established connections on local tcp port port. Parses output of shell 'sockstat' (NetBSD) to get connections $ sudo sockstat -4 -n USER COMMAND PID FD PROTO LOCAL ADDRESS FOREIGN ADDRESS root python2.7 1456 29 tcp *.4505 *.* root python2.7 1445 17 tcp *.4506 *.* root python2.7 1294 14 tcp 127.0.0.1.11813 127.0.0.1.4505 root python2.7 1294 41 tcp 127.0.0.1.61115 127.0.0.1.4506 $ sudo sockstat -4 -c -n -p 4506 USER COMMAND PID FD PROTO LOCAL ADDRESS FOREIGN ADDRESS root python2.7 1294 41 tcp 127.0.0.1.61115 127.0.0.1.4506 ''' port = int(port) remotes = set() try: cmd = salt.utils.args.shlex_split('sockstat -4 -c -n -p {0}'.format(port)) data = subprocess.check_output(cmd) # pylint: disable=minimum-python-version except subprocess.CalledProcessError as ex: log.error('Failed "sockstat" with returncode = %s', ex.returncode) raise lines = salt.utils.stringutils.to_str(data).split('\n') for line in lines: chunks = line.split() if not chunks: continue # ['root', 'python2.7', '1456', '37', 'tcp', # '127.0.0.1.4505-', '127.0.0.1.55703'] # print chunks if 'COMMAND' in chunks[1]: continue # ignore header if len(chunks) < 2: continue local = chunks[5].split('.') lport = local.pop() lhost = '.'.join(local) remote = chunks[6].split('.') rport = remote.pop() rhost = '.'.join(remote) if which_end == 'local' and int(lport) != port: # ignore if local port not port continue if which_end == 'remote' and int(rport) != port: # ignore if remote port not port continue remotes.add(rhost) return remotes def _openbsd_remotes_on(port, which_end): ''' OpenBSD specific helper function. Returns set of ipv4 host addresses of remote established connections on local or remote tcp port. Parses output of shell 'netstat' to get connections $ netstat -nf inet Active Internet connections Proto Recv-Q Send-Q Local Address Foreign Address (state) tcp 0 0 10.0.0.101.4505 10.0.0.1.45329 ESTABLISHED tcp 0 0 10.0.0.101.4505 10.0.0.100.50798 ESTABLISHED ''' remotes = set() try: data = subprocess.check_output(['netstat', '-nf', 'inet']) # pylint: disable=minimum-python-version except subprocess.CalledProcessError: log.error('Failed netstat') raise lines = data.split('\n') for line in lines: if 'ESTABLISHED' not in line: continue chunks = line.split() local_host, local_port = chunks[3].rsplit('.', 1) remote_host, remote_port = chunks[4].rsplit('.', 1) if which_end == 'remote_port' and int(remote_port) != port: continue if which_end == 'local_port' and int(local_port) != port: continue remotes.add(remote_host) return remotes def _windows_remotes_on(port, which_end): r''' Windows specific helper function. Returns set of ipv4 host addresses of remote established connections on local or remote tcp port. Parses output of shell 'netstat' to get connections C:\>netstat -n Active Connections Proto Local Address Foreign Address State TCP 10.2.33.17:3007 130.164.12.233:10123 ESTABLISHED TCP 10.2.33.17:3389 130.164.30.5:10378 ESTABLISHED ''' remotes = set() try: data = subprocess.check_output(['netstat', '-n']) # pylint: disable=minimum-python-version except subprocess.CalledProcessError: log.error('Failed netstat') raise lines = salt.utils.stringutils.to_str(data).split('\n') for line in lines: if 'ESTABLISHED' not in line: continue chunks = line.split() local_host, local_port = chunks[1].rsplit(':', 1) remote_host, remote_port = chunks[2].rsplit(':', 1) if which_end == 'remote_port' and int(remote_port) != port: continue if which_end == 'local_port' and int(local_port) != port: continue remotes.add(remote_host) return remotes def _linux_remotes_on(port, which_end): ''' Linux specific helper function. Returns set of ip host addresses of remote established connections on local tcp port port. Parses output of shell 'lsof' to get connections $ sudo lsof -iTCP:4505 -n COMMAND PID USER FD TYPE DEVICE SIZE/OFF NODE NAME Python 9971 root 35u IPv4 0x18a8464a29ca329d 0t0 TCP *:4505 (LISTEN) Python 9971 root 37u IPv4 0x18a8464a29b2b29d 0t0 TCP 127.0.0.1:4505->127.0.0.1:55703 (ESTABLISHED) Python 10152 root 22u IPv4 0x18a8464a29c8cab5 0t0 TCP 127.0.0.1:55703->127.0.0.1:4505 (ESTABLISHED) Python 10153 root 22u IPv4 0x18a8464a29c8cab5 0t0 TCP [fe80::249a]:4505->[fe80::150]:59367 (ESTABLISHED) ''' remotes = set() try: data = subprocess.check_output( ['lsof', '-iTCP:{0:d}'.format(port), '-n', '-P'] # pylint: disable=minimum-python-version ) except subprocess.CalledProcessError as ex: if ex.returncode == 1: # Lsof return 1 if any error was detected, including the failure # to locate Internet addresses, and it is not an error in this case. log.warning('"lsof" returncode = 1, likely no active TCP sessions.') return remotes log.error('Failed "lsof" with returncode = %s', ex.returncode) raise lines = salt.utils.stringutils.to_str(data).split('\n') for line in lines: chunks = line.split() if not chunks: continue # ['Python', '9971', 'root', '37u', 'IPv4', '0x18a8464a29b2b29d', '0t0', # 'TCP', '127.0.0.1:4505->127.0.0.1:55703', '(ESTABLISHED)'] # print chunks if 'COMMAND' in chunks[0]: continue # ignore header if 'ESTABLISHED' not in chunks[-1]: continue # ignore if not ESTABLISHED # '127.0.0.1:4505->127.0.0.1:55703' local, remote = chunks[8].split('->') _, lport = local.rsplit(':', 1) rhost, rport = remote.rsplit(':', 1) if which_end == 'remote_port' and int(rport) != port: continue if which_end == 'local_port' and int(lport) != port: continue remotes.add(rhost.strip("[]")) return remotes def _aix_remotes_on(port, which_end): ''' AIX specific helper function. Returns set of ipv4 host addresses of remote established connections on local or remote tcp port. Parses output of shell 'netstat' to get connections root@la68pp002_pub:/opt/salt/lib/python2.7/site-packages/salt/modules# netstat -f inet -n Active Internet connections Proto Recv-Q Send-Q Local Address Foreign Address (state) tcp4 0 0 172.29.149.95.50093 209.41.78.13.4505 ESTABLISHED tcp4 0 0 127.0.0.1.9514 *.* LISTEN tcp4 0 0 127.0.0.1.9515 *.* LISTEN tcp4 0 0 127.0.0.1.199 127.0.0.1.32779 ESTABLISHED tcp4 0 0 127.0.0.1.32779 127.0.0.1.199 ESTABLISHED tcp4 0 40 172.29.149.95.22 172.29.96.83.41022 ESTABLISHED tcp4 0 0 172.29.149.95.22 172.29.96.83.41032 ESTABLISHED tcp4 0 0 127.0.0.1.32771 127.0.0.1.32775 ESTABLISHED tcp 0 0 127.0.0.1.32775 127.0.0.1.32771 ESTABLISHED tcp4 0 0 127.0.0.1.32771 127.0.0.1.32776 ESTABLISHED tcp 0 0 127.0.0.1.32776 127.0.0.1.32771 ESTABLISHED tcp4 0 0 127.0.0.1.32771 127.0.0.1.32777 ESTABLISHED tcp 0 0 127.0.0.1.32777 127.0.0.1.32771 ESTABLISHED tcp4 0 0 127.0.0.1.32771 127.0.0.1.32778 ESTABLISHED tcp 0 0 127.0.0.1.32778 127.0.0.1.32771 ESTABLISHED ''' remotes = set() try: data = subprocess.check_output(['netstat', '-f', 'inet', '-n']) # pylint: disable=minimum-python-version except subprocess.CalledProcessError: log.error('Failed netstat') raise lines = salt.utils.stringutils.to_str(data).split('\n') for line in lines: if 'ESTABLISHED' not in line: continue chunks = line.split() local_host, local_port = chunks[3].rsplit('.', 1) remote_host, remote_port = chunks[4].rsplit('.', 1) if which_end == 'remote_port' and int(remote_port) != port: continue if which_end == 'local_port' and int(local_port) != port: continue remotes.add(remote_host) return remotes @jinja_filter('gen_mac') def gen_mac(prefix='AC:DE:48'): ''' Generates a MAC address with the defined OUI prefix. Common prefixes: - ``00:16:3E`` -- Xen - ``00:18:51`` -- OpenVZ - ``00:50:56`` -- VMware (manually generated) - ``52:54:00`` -- QEMU/KVM - ``AC:DE:48`` -- PRIVATE References: - http://standards.ieee.org/develop/regauth/oui/oui.txt - https://www.wireshark.org/tools/oui-lookup.html - https://en.wikipedia.org/wiki/MAC_address ''' return '{0}:{1:02X}:{2:02X}:{3:02X}'.format(prefix, random.randint(0, 0xff), random.randint(0, 0xff), random.randint(0, 0xff)) @jinja_filter('mac_str_to_bytes') def mac_str_to_bytes(mac_str): ''' Convert a MAC address string into bytes. Works with or without separators: b1 = mac_str_to_bytes('08:00:27:13:69:77') b2 = mac_str_to_bytes('080027136977') assert b1 == b2 assert isinstance(b1, bytes) ''' if len(mac_str) == 12: pass elif len(mac_str) == 17: sep = mac_str[2] mac_str = mac_str.replace(sep, '') else: raise ValueError('Invalid MAC address') chars = (int(mac_str[s:s+2], 16) for s in range(0, 12, 2)) return bytes(chars) if six.PY3 else b''.join(chr(x) for x in chars) def refresh_dns(): ''' issue #21397: force glibc to re-read resolv.conf ''' try: res_init() except NameError: # Exception raised loading the library, thus res_init is not defined pass @jinja_filter('connection_check') def connection_check(addr, port=80, safe=False, ipv6=None): ''' Provides a convenient alias for the dns_check filter. ''' return dns_check(addr, port, safe, ipv6) @jinja_filter('dns_check') def dns_check(addr, port=80, safe=False, ipv6=None, attempt_connect=True): ''' Return the ip resolved by dns, but do not exit on failure, only raise an exception. Obeys system preference for IPv4/6 address resolution - this can be overridden by the ipv6 flag. Tries to connect to the address before considering it useful. If no address can be reached, the first one resolved is used as a fallback. ''' error = False lookup = addr seen_ipv6 = False family = socket.AF_INET6 if ipv6 else socket.AF_INET if ipv6 is False else socket.AF_UNSPEC hostnames = [] try: refresh_dns() hostnames = socket.getaddrinfo(addr, port, family, socket.SOCK_STREAM) except TypeError: err = ('Attempt to resolve address \'{0}\' failed. Invalid or unresolveable address').format(lookup) raise SaltSystemExit(code=42, msg=err) except socket.error: error = True # If ipv6 is set to True, attempt another lookup using the IPv4 family, # just in case we're attempting to lookup an IPv4 IP # as an IPv6 hostname. if error and ipv6: try: refresh_dns() hostnames = socket.getaddrinfo(addr, port, socket.AF_INET, socket.SOCK_STREAM) except TypeError: err = ('Attempt to resolve address \'{0}\' failed. Invalid or unresolveable address').format(lookup) raise SaltSystemExit(code=42, msg=err) except socket.error: error = True try: if not hostnames: error = True else: resolved = False candidates = [] for h in hostnames: # Input is IP address, passed through unchanged, just return it if h[4][0] == addr: resolved = salt.utils.zeromq.ip_bracket(addr) break candidate_addr = salt.utils.zeromq.ip_bracket(h[4][0]) # sometimes /etc/hosts contains ::1 localhost if not ipv6 and candidate_addr == '[::1]': continue candidates.append(candidate_addr) if attempt_connect: try: s = socket.socket(h[0], socket.SOCK_STREAM) s.settimeout(2) s.connect((candidate_addr.strip('[]'), h[4][1])) s.close() resolved = candidate_addr break except socket.error: pass if not resolved: if candidates: resolved = candidates[0] else: error = True except TypeError: err = ('Attempt to resolve address \'{0}\' failed. Invalid or unresolveable address').format(lookup) raise SaltSystemExit(code=42, msg=err) except socket.error: error = True if error: err = ('DNS lookup or connection check of \'{0}\' failed.').format(addr) if safe: if salt.log.is_console_configured(): # If logging is not configured it also means that either # the master or minion instance calling this hasn't even # started running log.error(err) raise SaltClientError() raise SaltSystemExit(code=42, msg=err) return resolved def parse_host_port(host_port): """ Takes a string argument specifying host or host:port. Returns a (hostname, port) or (ip_address, port) tuple. If no port is given, the second (port) element of the returned tuple will be None. host:port argument, for example, is accepted in the forms of: - hostname - hostname:1234 - hostname.domain.tld - hostname.domain.tld:5678 - [1234::5]:5678 - 1234::5 - 10.11.12.13:4567 - 10.11.12.13 """ host, port = None, None # default _s_ = host_port[:] if _s_[0] == "[": if "]" in host_port: host, _s_ = _s_.lstrip("[").rsplit("]", 1) host = ipaddress.IPv6Address(host).compressed if _s_[0] == ":": port = int(_s_.lstrip(":")) else: if len(_s_) > 1: raise ValueError('found ambiguous "{}" port in "{}"'.format(_s_, host_port)) else: if _s_.count(":") == 1: host, _hostport_separator_, port = _s_.partition(":") try: port = int(port) except ValueError as _e_: log.error('host_port "%s" port value "%s" is not an integer.', host_port, port) raise _e_ else: host = _s_ try: if not isinstance(host, ipaddress._BaseAddress): host_ip = ipaddress.ip_address(host).compressed host = host_ip except ValueError: log.debug('"%s" Not an IP address? Assuming it is a hostname.', host) if host != sanitize_host(host): log.error('bad hostname: "%s"', host) raise ValueError('bad hostname: "{}"'.format(host)) return host, port def is_fqdn(hostname): """ Verify if hostname conforms to be a FQDN. :param hostname: text string with the name of the host :return: bool, True if hostname is correct FQDN, False otherwise """ compliant = re.compile(r"(?!-)[A-Z\d\-\_]{1,63}(?<!-)$", re.IGNORECASE) return "." in hostname and len(hostname) < 0xff and all(compliant.match(x) for x in hostname.rstrip(".").split("."))
saltstack/salt
salt/utils/network.py
_number_of_set_bits
python
def _number_of_set_bits(x): ''' Returns the number of bits that are set in a 32bit int ''' # Taken from http://stackoverflow.com/a/4912729. Many thanks! x -= (x >> 1) & 0x55555555 x = ((x >> 2) & 0x33333333) + (x & 0x33333333) x = ((x >> 4) + x) & 0x0f0f0f0f x += x >> 8 x += x >> 16 return x & 0x0000003f
Returns the number of bits that are set in a 32bit int
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/network.py#L640-L650
null
# -*- coding: utf-8 -*- ''' Define some generic socket functions for network modules ''' # Import python libs from __future__ import absolute_import, unicode_literals, print_function import itertools import os import re import types import socket import logging import platform import random import subprocess from string import ascii_letters, digits # Import 3rd-party libs from salt.ext import six from salt.ext.six.moves import range # pylint: disable=import-error,redefined-builtin # Attempt to import wmi try: import wmi import salt.utils.winapi except ImportError: pass # Import salt libs import salt.utils.args import salt.utils.files import salt.utils.path import salt.utils.platform import salt.utils.stringutils import salt.utils.zeromq from salt._compat import ipaddress from salt.exceptions import SaltClientError, SaltSystemExit from salt.utils.decorators.jinja import jinja_filter from salt.utils.versions import LooseVersion # inet_pton does not exist in Windows, this is a workaround if salt.utils.platform.is_windows(): from salt.ext import win_inet_pton # pylint: disable=unused-import log = logging.getLogger(__name__) try: import ctypes import ctypes.util libc = ctypes.cdll.LoadLibrary(ctypes.util.find_library("c")) res_init = libc.__res_init except (ImportError, OSError, AttributeError, TypeError): pass # pylint: disable=C0103 def sanitize_host(host): ''' Sanitize host string. https://tools.ietf.org/html/rfc1123#section-2.1 ''' RFC952_characters = ascii_letters + digits + ".-" return "".join([c for c in host[0:255] if c in RFC952_characters]) def isportopen(host, port): ''' Return status of a port ''' if not 1 <= int(port) <= 65535: return False sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) out = sock.connect_ex((sanitize_host(host), int(port))) return out def host_to_ips(host): ''' Returns a list of IP addresses of a given hostname or None if not found. ''' ips = [] try: for family, socktype, proto, canonname, sockaddr in socket.getaddrinfo( host, 0, socket.AF_UNSPEC, socket.SOCK_STREAM): if family == socket.AF_INET: ip, port = sockaddr elif family == socket.AF_INET6: ip, port, flow_info, scope_id = sockaddr ips.append(ip) if not ips: ips = None except Exception: ips = None return ips def _generate_minion_id(): ''' Get list of possible host names and convention names. :return: ''' # There are three types of hostnames: # 1. Network names. How host is accessed from the network. # 2. Host aliases. They might be not available in all the network or only locally (/etc/hosts) # 3. Convention names, an internal nodename. class DistinctList(list): ''' List, which allows one to append only distinct objects. Needs to work on Python 2.6, because of collections.OrderedDict only since 2.7 version. Override 'filter()' for custom filtering. ''' localhost_matchers = [r'localhost.*', r'ip6-.*', r'127[.]\d', r'0\.0\.0\.0', r'::1.*', r'ipv6-.*', r'fe00::.*', r'fe02::.*', r'1.0.0.*.ip6.arpa'] def append(self, p_object): if p_object and p_object not in self and not self.filter(p_object): super(DistinctList, self).append(p_object) return self def extend(self, iterable): for obj in iterable: self.append(obj) return self def filter(self, element): 'Returns True if element needs to be filtered' for rgx in self.localhost_matchers: if re.match(rgx, element): return True def first(self): return self and self[0] or None hostname = socket.gethostname() hosts = DistinctList().append( salt.utils.stringutils.to_unicode(socket.getfqdn(salt.utils.stringutils.to_bytes(hostname))) ).append(platform.node()).append(hostname) if not hosts: try: for a_nfo in socket.getaddrinfo(hosts.first() or 'localhost', None, socket.AF_INET, socket.SOCK_RAW, socket.IPPROTO_IP, socket.AI_CANONNAME): if len(a_nfo) > 3: hosts.append(a_nfo[3]) except socket.gaierror: log.warning('Cannot resolve address %s info via socket: %s', hosts.first() or 'localhost (N/A)', socket.gaierror) # Universal method for everywhere (Linux, Slowlaris, Windows etc) for f_name in ('/etc/hostname', '/etc/nodename', '/etc/hosts', r'{win}\system32\drivers\etc\hosts'.format(win=os.getenv('WINDIR'))): try: with salt.utils.files.fopen(f_name) as f_hdl: for line in f_hdl: line = salt.utils.stringutils.to_unicode(line) hst = line.strip().split('#')[0].strip().split() if hst: if hst[0][:4] in ('127.', '::1') or len(hst) == 1: hosts.extend(hst) except IOError: pass # include public and private ipaddresses return hosts.extend([addr for addr in ip_addrs() if not ipaddress.ip_address(addr).is_loopback]) def generate_minion_id(): ''' Return only first element of the hostname from all possible list. :return: ''' try: ret = salt.utils.stringutils.to_unicode(_generate_minion_id().first()) except TypeError: ret = None return ret or 'localhost' def get_socket(addr, type=socket.SOCK_STREAM, proto=0): ''' Return a socket object for the addr IP-version agnostic ''' version = ipaddress.ip_address(addr).version if version == 4: family = socket.AF_INET elif version == 6: family = socket.AF_INET6 return socket.socket(family, type, proto) def get_fqhostname(): ''' Returns the fully qualified hostname ''' # try getaddrinfo() fqdn = None try: addrinfo = socket.getaddrinfo( socket.gethostname(), 0, socket.AF_UNSPEC, socket.SOCK_STREAM, socket.SOL_TCP, socket.AI_CANONNAME ) for info in addrinfo: # info struct [family, socktype, proto, canonname, sockaddr] # On Windows `canonname` can be an empty string # This can cause the function to return `None` if len(info) > 3 and info[3]: fqdn = info[3] break except socket.gaierror: pass # NOTE: this used to log.error() but it was later disabled except socket.error as err: log.debug('socket.getaddrinfo() failure while finding fqdn: %s', err) if fqdn is None: fqdn = socket.getfqdn() return fqdn def ip_to_host(ip): ''' Returns the hostname of a given IP ''' try: hostname, aliaslist, ipaddrlist = socket.gethostbyaddr(ip) except Exception as exc: log.debug('salt.utils.network.ip_to_host(%r) failed: %s', ip, exc) hostname = None return hostname # pylint: enable=C0103 def is_reachable_host(entity_name): ''' Returns a bool telling if the entity name is a reachable host (IPv4/IPv6/FQDN/etc). :param hostname: :return: ''' try: assert type(socket.getaddrinfo(entity_name, 0, 0, 0, 0)) == list ret = True except socket.gaierror: ret = False return ret def is_ip(ip): ''' Returns a bool telling if the passed IP is a valid IPv4 or IPv6 address. ''' return is_ipv4(ip) or is_ipv6(ip) def is_ipv4(ip): ''' Returns a bool telling if the value passed to it was a valid IPv4 address ''' try: return ipaddress.ip_address(ip).version == 4 except ValueError: return False def is_ipv6(ip): ''' Returns a bool telling if the value passed to it was a valid IPv6 address ''' try: return ipaddress.ip_address(ip).version == 6 except ValueError: return False def is_subnet(cidr): ''' Returns a bool telling if the passed string is an IPv4 or IPv6 subnet ''' return is_ipv4_subnet(cidr) or is_ipv6_subnet(cidr) def is_ipv4_subnet(cidr): ''' Returns a bool telling if the passed string is an IPv4 subnet ''' try: return '/' in cidr and bool(ipaddress.IPv4Network(cidr)) except Exception: return False def is_ipv6_subnet(cidr): ''' Returns a bool telling if the passed string is an IPv6 subnet ''' try: return '/' in cidr and bool(ipaddress.IPv6Network(cidr)) except Exception: return False @jinja_filter('is_ip') def is_ip_filter(ip, options=None): ''' Returns a bool telling if the passed IP is a valid IPv4 or IPv6 address. ''' return is_ipv4_filter(ip, options=options) or is_ipv6_filter(ip, options=options) def _ip_options_global(ip_obj, version): return not ip_obj.is_private def _ip_options_multicast(ip_obj, version): return ip_obj.is_multicast def _ip_options_loopback(ip_obj, version): return ip_obj.is_loopback def _ip_options_link_local(ip_obj, version): return ip_obj.is_link_local def _ip_options_private(ip_obj, version): return ip_obj.is_private def _ip_options_reserved(ip_obj, version): return ip_obj.is_reserved def _ip_options_site_local(ip_obj, version): if version == 6: return ip_obj.is_site_local return False def _ip_options_unspecified(ip_obj, version): return ip_obj.is_unspecified def _ip_options(ip_obj, version, options=None): # will process and IP options options_fun_map = { 'global': _ip_options_global, 'link-local': _ip_options_link_local, 'linklocal': _ip_options_link_local, 'll': _ip_options_link_local, 'link_local': _ip_options_link_local, 'loopback': _ip_options_loopback, 'lo': _ip_options_loopback, 'multicast': _ip_options_multicast, 'private': _ip_options_private, 'public': _ip_options_global, 'reserved': _ip_options_reserved, 'site-local': _ip_options_site_local, 'sl': _ip_options_site_local, 'site_local': _ip_options_site_local, 'unspecified': _ip_options_unspecified } if not options: return six.text_type(ip_obj) # IP version already checked options_list = [option.strip() for option in options.split(',')] for option, fun in options_fun_map.items(): if option in options_list: fun_res = fun(ip_obj, version) if not fun_res: return None # stop at first failed test # else continue return six.text_type(ip_obj) def _is_ipv(ip, version, options=None): if not version: version = 4 if version not in (4, 6): return None try: ip_obj = ipaddress.ip_address(ip) except ValueError: # maybe it is an IP network try: ip_obj = ipaddress.ip_interface(ip) except ValueError: # nope, still not :( return None if not ip_obj.version == version: return None # has the right version, let's move on return _ip_options(ip_obj, version, options=options) @jinja_filter('is_ipv4') def is_ipv4_filter(ip, options=None): ''' Returns a bool telling if the value passed to it was a valid IPv4 address. ip The IP address. net: False Consider IP addresses followed by netmask. options CSV of options regarding the nature of the IP address. E.g.: loopback, multicast, private etc. ''' _is_ipv4 = _is_ipv(ip, 4, options=options) return isinstance(_is_ipv4, six.string_types) @jinja_filter('is_ipv6') def is_ipv6_filter(ip, options=None): ''' Returns a bool telling if the value passed to it was a valid IPv6 address. ip The IP address. net: False Consider IP addresses followed by netmask. options CSV of options regarding the nature of the IP address. E.g.: loopback, multicast, private etc. ''' _is_ipv6 = _is_ipv(ip, 6, options=options) return isinstance(_is_ipv6, six.string_types) def _ipv_filter(value, version, options=None): if version not in (4, 6): return if isinstance(value, (six.string_types, six.text_type, six.binary_type)): return _is_ipv(value, version, options=options) # calls is_ipv4 or is_ipv6 for `value` elif isinstance(value, (list, tuple, types.GeneratorType)): # calls is_ipv4 or is_ipv6 for each element in the list # os it filters and returns only those elements having the desired IP version return [ _is_ipv(addr, version, options=options) for addr in value if _is_ipv(addr, version, options=options) is not None ] return None @jinja_filter('ipv4') def ipv4(value, options=None): ''' Filters a list and returns IPv4 values only. ''' return _ipv_filter(value, 4, options=options) @jinja_filter('ipv6') def ipv6(value, options=None): ''' Filters a list and returns IPv6 values only. ''' return _ipv_filter(value, 6, options=options) @jinja_filter('ipaddr') def ipaddr(value, options=None): ''' Filters and returns only valid IP objects. ''' ipv4_obj = ipv4(value, options=options) ipv6_obj = ipv6(value, options=options) if ipv4_obj is None or ipv6_obj is None: # an IP address can be either IPv4 either IPv6 # therefofe if the value passed as arg is not a list, at least one of the calls above will return None # if one of them is none, means that we should return only one of them return ipv4_obj or ipv6_obj # one of them else: return ipv4_obj + ipv6_obj # extend lists def _filter_ipaddr(value, options, version=None): ipaddr_filter_out = None if version: if version == 4: ipaddr_filter_out = ipv4(value, options) elif version == 6: ipaddr_filter_out = ipv6(value, options) else: ipaddr_filter_out = ipaddr(value, options) if not ipaddr_filter_out: return if not isinstance(ipaddr_filter_out, (list, tuple, types.GeneratorType)): ipaddr_filter_out = [ipaddr_filter_out] return ipaddr_filter_out @jinja_filter('ip_host') def ip_host(value, options=None, version=None): ''' Returns the interfaces IP address, e.g.: 192.168.0.1/28. ''' ipaddr_filter_out = _filter_ipaddr(value, options=options, version=version) if not ipaddr_filter_out: return if not isinstance(value, (list, tuple, types.GeneratorType)): return six.text_type(ipaddress.ip_interface(ipaddr_filter_out[0])) return [six.text_type(ipaddress.ip_interface(ip_a)) for ip_a in ipaddr_filter_out] def _network_hosts(ip_addr_entry): return [ six.text_type(host) for host in ipaddress.ip_network(ip_addr_entry, strict=False).hosts() ] @jinja_filter('network_hosts') def network_hosts(value, options=None, version=None): ''' Return the list of hosts within a network. .. note:: When running this command with a large IPv6 network, the command will take a long time to gather all of the hosts. ''' ipaddr_filter_out = _filter_ipaddr(value, options=options, version=version) if not ipaddr_filter_out: return if not isinstance(value, (list, tuple, types.GeneratorType)): return _network_hosts(ipaddr_filter_out[0]) return [ _network_hosts(ip_a) for ip_a in ipaddr_filter_out ] def _network_size(ip_addr_entry): return ipaddress.ip_network(ip_addr_entry, strict=False).num_addresses @jinja_filter('network_size') def network_size(value, options=None, version=None): ''' Get the size of a network. ''' ipaddr_filter_out = _filter_ipaddr(value, options=options, version=version) if not ipaddr_filter_out: return if not isinstance(value, (list, tuple, types.GeneratorType)): return _network_size(ipaddr_filter_out[0]) return [ _network_size(ip_a) for ip_a in ipaddr_filter_out ] def natural_ipv4_netmask(ip, fmt='prefixlen'): ''' Returns the "natural" mask of an IPv4 address ''' bits = _ipv4_to_bits(ip) if bits.startswith('11'): mask = '24' elif bits.startswith('1'): mask = '16' else: mask = '8' if fmt == 'netmask': return cidr_to_ipv4_netmask(mask) else: return '/' + mask def rpad_ipv4_network(ip): ''' Returns an IP network address padded with zeros. Ex: '192.168.3' -> '192.168.3.0' '10.209' -> '10.209.0.0' ''' return '.'.join(itertools.islice(itertools.chain(ip.split('.'), '0000'), 0, 4)) def cidr_to_ipv4_netmask(cidr_bits): ''' Returns an IPv4 netmask ''' try: cidr_bits = int(cidr_bits) if not 1 <= cidr_bits <= 32: return '' except ValueError: return '' netmask = '' for idx in range(4): if idx: netmask += '.' if cidr_bits >= 8: netmask += '255' cidr_bits -= 8 else: netmask += '{0:d}'.format(256 - (2 ** (8 - cidr_bits))) cidr_bits = 0 return netmask def _number_of_set_bits_to_ipv4_netmask(set_bits): # pylint: disable=C0103 ''' Returns an IPv4 netmask from the integer representation of that mask. Ex. 0xffffff00 -> '255.255.255.0' ''' return cidr_to_ipv4_netmask(_number_of_set_bits(set_bits)) # pylint: disable=C0103 # pylint: enable=C0103 def _interfaces_ip(out): ''' Uses ip to return a dictionary of interfaces with various information about each (up/down state, ip address, netmask, and hwaddr) ''' ret = dict() def parse_network(value, cols): ''' Return a tuple of ip, netmask, broadcast based on the current set of cols ''' brd = None scope = None if '/' in value: # we have a CIDR in this address ip, cidr = value.split('/') # pylint: disable=C0103 else: ip = value # pylint: disable=C0103 cidr = 32 if type_ == 'inet': mask = cidr_to_ipv4_netmask(int(cidr)) if 'brd' in cols: brd = cols[cols.index('brd') + 1] elif type_ == 'inet6': mask = cidr if 'scope' in cols: scope = cols[cols.index('scope') + 1] return (ip, mask, brd, scope) groups = re.compile('\r?\n\\d').split(out) for group in groups: iface = None data = dict() for line in group.splitlines(): if ' ' not in line: continue match = re.match(r'^\d*:\s+([\w.\-]+)(?:@)?([\w.\-]+)?:\s+<(.+)>', line) if match: iface, parent, attrs = match.groups() if 'UP' in attrs.split(','): data['up'] = True else: data['up'] = False if parent: data['parent'] = parent continue cols = line.split() if len(cols) >= 2: type_, value = tuple(cols[0:2]) iflabel = cols[-1:][0] if type_ in ('inet', 'inet6'): if 'secondary' not in cols: ipaddr, netmask, broadcast, scope = parse_network(value, cols) if type_ == 'inet': if 'inet' not in data: data['inet'] = list() addr_obj = dict() addr_obj['address'] = ipaddr addr_obj['netmask'] = netmask addr_obj['broadcast'] = broadcast addr_obj['label'] = iflabel data['inet'].append(addr_obj) elif type_ == 'inet6': if 'inet6' not in data: data['inet6'] = list() addr_obj = dict() addr_obj['address'] = ipaddr addr_obj['prefixlen'] = netmask addr_obj['scope'] = scope data['inet6'].append(addr_obj) else: if 'secondary' not in data: data['secondary'] = list() ip_, mask, brd, scp = parse_network(value, cols) data['secondary'].append({ 'type': type_, 'address': ip_, 'netmask': mask, 'broadcast': brd, 'label': iflabel, }) del ip_, mask, brd, scp elif type_.startswith('link'): data['hwaddr'] = value if iface: ret[iface] = data del iface, data return ret def _interfaces_ifconfig(out): ''' Uses ifconfig to return a dictionary of interfaces with various information about each (up/down state, ip address, netmask, and hwaddr) ''' ret = dict() piface = re.compile(r'^([^\s:]+)') pmac = re.compile('.*?(?:HWaddr|ether|address:|lladdr) ([0-9a-fA-F:]+)') if salt.utils.platform.is_sunos(): pip = re.compile(r'.*?(?:inet\s+)([0-9]+\.[0-9]+\.[0-9]+\.[0-9]+)(.*)') pip6 = re.compile('.*?(?:inet6 )([0-9a-fA-F:]+)') pmask6 = re.compile(r'.*?(?:inet6 [0-9a-fA-F:]+/(\d+)).*') else: pip = re.compile(r'.*?(?:inet addr:|inet [^\d]*)(.*?)\s') pip6 = re.compile('.*?(?:inet6 addr: (.*?)/|inet6 )([0-9a-fA-F:]+)') pmask6 = re.compile(r'.*?(?:inet6 addr: [0-9a-fA-F:]+/(\d+)|prefixlen (\d+))(?: Scope:([a-zA-Z]+)| scopeid (0x[0-9a-fA-F]))?') pmask = re.compile(r'.*?(?:Mask:|netmask )(?:((?:0x)?[0-9a-fA-F]{8})|([\d\.]+))') pupdown = re.compile('UP') pbcast = re.compile(r'.*?(?:Bcast:|broadcast )([\d\.]+)') groups = re.compile('\r?\n(?=\\S)').split(out) for group in groups: data = dict() iface = '' updown = False for line in group.splitlines(): miface = piface.match(line) mmac = pmac.match(line) mip = pip.match(line) mip6 = pip6.match(line) mupdown = pupdown.search(line) if miface: iface = miface.group(1) if mmac: data['hwaddr'] = mmac.group(1) if salt.utils.platform.is_sunos(): expand_mac = [] for chunk in data['hwaddr'].split(':'): expand_mac.append('0{0}'.format(chunk) if len(chunk) < 2 else '{0}'.format(chunk)) data['hwaddr'] = ':'.join(expand_mac) if mip: if 'inet' not in data: data['inet'] = list() addr_obj = dict() addr_obj['address'] = mip.group(1) mmask = pmask.match(line) if mmask: if mmask.group(1): mmask = _number_of_set_bits_to_ipv4_netmask( int(mmask.group(1), 16)) else: mmask = mmask.group(2) addr_obj['netmask'] = mmask mbcast = pbcast.match(line) if mbcast: addr_obj['broadcast'] = mbcast.group(1) data['inet'].append(addr_obj) if mupdown: updown = True if mip6: if 'inet6' not in data: data['inet6'] = list() addr_obj = dict() addr_obj['address'] = mip6.group(1) or mip6.group(2) mmask6 = pmask6.match(line) if mmask6: addr_obj['prefixlen'] = mmask6.group(1) or mmask6.group(2) if not salt.utils.platform.is_sunos(): ipv6scope = mmask6.group(3) or mmask6.group(4) addr_obj['scope'] = ipv6scope.lower() if ipv6scope is not None else ipv6scope # SunOS sometimes has ::/0 as inet6 addr when using addrconf if not salt.utils.platform.is_sunos() \ or addr_obj['address'] != '::' \ and addr_obj['prefixlen'] != 0: data['inet6'].append(addr_obj) data['up'] = updown if iface in ret: # SunOS optimization, where interfaces occur twice in 'ifconfig -a' # output with the same name: for ipv4 and then for ipv6 addr family. # Every instance has it's own 'UP' status and we assume that ipv4 # status determines global interface status. # # merge items with higher priority for older values # after that merge the inet and inet6 sub items for both ret[iface] = dict(list(data.items()) + list(ret[iface].items())) if 'inet' in data: ret[iface]['inet'].extend(x for x in data['inet'] if x not in ret[iface]['inet']) if 'inet6' in data: ret[iface]['inet6'].extend(x for x in data['inet6'] if x not in ret[iface]['inet6']) else: ret[iface] = data del data return ret def linux_interfaces(): ''' Obtain interface information for *NIX/BSD variants ''' ifaces = dict() ip_path = salt.utils.path.which('ip') ifconfig_path = None if ip_path else salt.utils.path.which('ifconfig') if ip_path: cmd1 = subprocess.Popen( '{0} link show'.format(ip_path), shell=True, close_fds=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT).communicate()[0] cmd2 = subprocess.Popen( '{0} addr show'.format(ip_path), shell=True, close_fds=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT).communicate()[0] ifaces = _interfaces_ip("{0}\n{1}".format( salt.utils.stringutils.to_str(cmd1), salt.utils.stringutils.to_str(cmd2))) elif ifconfig_path: cmd = subprocess.Popen( '{0} -a'.format(ifconfig_path), shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT).communicate()[0] ifaces = _interfaces_ifconfig(salt.utils.stringutils.to_str(cmd)) return ifaces def _netbsd_interfaces_ifconfig(out): ''' Uses ifconfig to return a dictionary of interfaces with various information about each (up/down state, ip address, netmask, and hwaddr) ''' ret = dict() piface = re.compile(r'^([^\s:]+)') pmac = re.compile('.*?address: ([0-9a-f:]+)') pip = re.compile(r'.*?inet [^\d]*(.*?)/([\d]*)\s') pip6 = re.compile(r'.*?inet6 ([0-9a-f:]+)%([a-zA-Z0-9]*)/([\d]*)\s') pupdown = re.compile('UP') pbcast = re.compile(r'.*?broadcast ([\d\.]+)') groups = re.compile('\r?\n(?=\\S)').split(out) for group in groups: data = dict() iface = '' updown = False for line in group.splitlines(): miface = piface.match(line) mmac = pmac.match(line) mip = pip.match(line) mip6 = pip6.match(line) mupdown = pupdown.search(line) if miface: iface = miface.group(1) if mmac: data['hwaddr'] = mmac.group(1) if mip: if 'inet' not in data: data['inet'] = list() addr_obj = dict() addr_obj['address'] = mip.group(1) mmask = mip.group(2) if mip.group(2): addr_obj['netmask'] = cidr_to_ipv4_netmask(mip.group(2)) mbcast = pbcast.match(line) if mbcast: addr_obj['broadcast'] = mbcast.group(1) data['inet'].append(addr_obj) if mupdown: updown = True if mip6: if 'inet6' not in data: data['inet6'] = list() addr_obj = dict() addr_obj['address'] = mip6.group(1) mmask6 = mip6.group(3) addr_obj['scope'] = mip6.group(2) addr_obj['prefixlen'] = mip6.group(3) data['inet6'].append(addr_obj) data['up'] = updown ret[iface] = data del data return ret def netbsd_interfaces(): ''' Obtain interface information for NetBSD >= 8 where the ifconfig output diverged from other BSD variants (Netmask is now part of the address) ''' # NetBSD versions prior to 8.0 can still use linux_interfaces() if LooseVersion(os.uname()[2]) < LooseVersion('8.0'): return linux_interfaces() ifconfig_path = salt.utils.path.which('ifconfig') cmd = subprocess.Popen( '{0} -a'.format(ifconfig_path), shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT).communicate()[0] return _netbsd_interfaces_ifconfig(salt.utils.stringutils.to_str(cmd)) def _interfaces_ipconfig(out): ''' Returns a dictionary of interfaces with various information about each (up/down state, ip address, netmask, and hwaddr) NOTE: This is not used by any function and may be able to be removed in the future. ''' ifaces = dict() iface = None adapter_iface_regex = re.compile(r'adapter (\S.+):$') for line in out.splitlines(): if not line: continue # TODO what does Windows call Infiniband and 10/40gige adapters if line.startswith('Ethernet'): iface = ifaces[adapter_iface_regex.search(line).group(1)] iface['up'] = True addr = None continue if iface: key, val = line.split(',', 1) key = key.strip(' .') val = val.strip() if addr and key == 'Subnet Mask': addr['netmask'] = val elif key in ('IP Address', 'IPv4 Address'): if 'inet' not in iface: iface['inet'] = list() addr = {'address': val.rstrip('(Preferred)'), 'netmask': None, 'broadcast': None} # TODO find the broadcast iface['inet'].append(addr) elif 'IPv6 Address' in key: if 'inet6' not in iface: iface['inet'] = list() # XXX What is the prefixlen!? addr = {'address': val.rstrip('(Preferred)'), 'prefixlen': None} iface['inet6'].append(addr) elif key == 'Physical Address': iface['hwaddr'] = val elif key == 'Media State': # XXX seen used for tunnel adaptors # might be useful iface['up'] = (val != 'Media disconnected') def win_interfaces(): ''' Obtain interface information for Windows systems ''' with salt.utils.winapi.Com(): c = wmi.WMI() ifaces = {} for iface in c.Win32_NetworkAdapterConfiguration(IPEnabled=1): ifaces[iface.Description] = dict() if iface.MACAddress: ifaces[iface.Description]['hwaddr'] = iface.MACAddress if iface.IPEnabled: ifaces[iface.Description]['up'] = True for ip in iface.IPAddress: if '.' in ip: if 'inet' not in ifaces[iface.Description]: ifaces[iface.Description]['inet'] = [] item = {'address': ip, 'label': iface.Description} if iface.DefaultIPGateway: broadcast = next((i for i in iface.DefaultIPGateway if '.' in i), '') if broadcast: item['broadcast'] = broadcast if iface.IPSubnet: netmask = next((i for i in iface.IPSubnet if '.' in i), '') if netmask: item['netmask'] = netmask ifaces[iface.Description]['inet'].append(item) if ':' in ip: if 'inet6' not in ifaces[iface.Description]: ifaces[iface.Description]['inet6'] = [] item = {'address': ip} if iface.DefaultIPGateway: broadcast = next((i for i in iface.DefaultIPGateway if ':' in i), '') if broadcast: item['broadcast'] = broadcast if iface.IPSubnet: netmask = next((i for i in iface.IPSubnet if ':' in i), '') if netmask: item['netmask'] = netmask ifaces[iface.Description]['inet6'].append(item) else: ifaces[iface.Description]['up'] = False return ifaces def interfaces(): ''' Return a dictionary of information about all the interfaces on the minion ''' if salt.utils.platform.is_windows(): return win_interfaces() elif salt.utils.platform.is_netbsd(): return netbsd_interfaces() else: return linux_interfaces() def get_net_start(ipaddr, netmask): ''' Return the address of the network ''' net = ipaddress.ip_network('{0}/{1}'.format(ipaddr, netmask), strict=False) return six.text_type(net.network_address) def get_net_size(mask): ''' Turns an IPv4 netmask into it's corresponding prefix length (255.255.255.0 -> 24 as in 192.168.1.10/24). ''' binary_str = '' for octet in mask.split('.'): binary_str += bin(int(octet))[2:].zfill(8) return len(binary_str.rstrip('0')) def calc_net(ipaddr, netmask=None): ''' Takes IP (CIDR notation supported) and optionally netmask and returns the network in CIDR-notation. (The IP can be any IP inside the subnet) ''' if netmask is not None: ipaddr = '{0}/{1}'.format(ipaddr, netmask) return six.text_type(ipaddress.ip_network(ipaddr, strict=False)) def _ipv4_to_bits(ipaddr): ''' Accepts an IPv4 dotted quad and returns a string representing its binary counterpart ''' return ''.join([bin(int(x))[2:].rjust(8, '0') for x in ipaddr.split('.')]) def _get_iface_info(iface): ''' If `iface` is available, return interface info and no error, otherwise return no info and log and return an error ''' iface_info = interfaces() if iface in iface_info.keys(): return iface_info, False else: error_msg = ('Interface "{0}" not in available interfaces: "{1}"' ''.format(iface, '", "'.join(iface_info.keys()))) log.error(error_msg) return None, error_msg def _hw_addr_aix(iface): ''' Return the hardware address (a.k.a. MAC address) for a given interface on AIX MAC address not available in through interfaces ''' cmd = subprocess.Popen( 'entstat -d {0} | grep \'Hardware Address\''.format(iface), shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT).communicate()[0] if cmd: comps = cmd.split(' ') if len(comps) == 3: mac_addr = comps[2].strip('\'').strip() return mac_addr error_msg = ('Interface "{0}" either not available or does not contain a hardware address'.format(iface)) log.error(error_msg) return error_msg def hw_addr(iface): ''' Return the hardware address (a.k.a. MAC address) for a given interface .. versionchanged:: 2016.11.4 Added support for AIX ''' if salt.utils.platform.is_aix(): return _hw_addr_aix iface_info, error = _get_iface_info(iface) if error is False: return iface_info.get(iface, {}).get('hwaddr', '') else: return error def interface(iface): ''' Return the details of `iface` or an error if it does not exist ''' iface_info, error = _get_iface_info(iface) if error is False: return iface_info.get(iface, {}).get('inet', '') else: return error def interface_ip(iface): ''' Return `iface` IPv4 addr or an error if `iface` does not exist ''' iface_info, error = _get_iface_info(iface) if error is False: inet = iface_info.get(iface, {}).get('inet', None) return inet[0].get('address', '') if inet else '' else: return error def _subnets(proto='inet', interfaces_=None): ''' Returns a list of subnets to which the host belongs ''' if interfaces_ is None: ifaces = interfaces() elif isinstance(interfaces_, list): ifaces = {} for key, value in six.iteritems(interfaces()): if key in interfaces_: ifaces[key] = value else: ifaces = {interfaces_: interfaces().get(interfaces_, {})} ret = set() if proto == 'inet': subnet = 'netmask' dflt_cidr = 32 elif proto == 'inet6': subnet = 'prefixlen' dflt_cidr = 128 else: log.error('Invalid proto %s calling subnets()', proto) return for ip_info in six.itervalues(ifaces): addrs = ip_info.get(proto, []) addrs.extend([addr for addr in ip_info.get('secondary', []) if addr.get('type') == proto]) for intf in addrs: if subnet in intf: intf = ipaddress.ip_interface('{0}/{1}'.format(intf['address'], intf[subnet])) else: intf = ipaddress.ip_interface('{0}/{1}'.format(intf['address'], dflt_cidr)) if not intf.is_loopback: ret.add(intf.network) return [six.text_type(net) for net in sorted(ret)] def subnets(interfaces=None): ''' Returns a list of IPv4 subnets to which the host belongs ''' return _subnets('inet', interfaces_=interfaces) def subnets6(): ''' Returns a list of IPv6 subnets to which the host belongs ''' return _subnets('inet6') def in_subnet(cidr, addr=None): ''' Returns True if host or (any of) addrs is within specified subnet, otherwise False ''' try: cidr = ipaddress.ip_network(cidr) except ValueError: log.error('Invalid CIDR \'%s\'', cidr) return False if addr is None: addr = ip_addrs() addr.extend(ip_addrs6()) elif not isinstance(addr, (list, tuple)): addr = (addr,) return any(ipaddress.ip_address(item) in cidr for item in addr) def _ip_addrs(interface=None, include_loopback=False, interface_data=None, proto='inet'): ''' Return the full list of IP adresses matching the criteria proto = inet|inet6 ''' ret = set() ifaces = interface_data \ if isinstance(interface_data, dict) \ else interfaces() if interface is None: target_ifaces = ifaces else: target_ifaces = dict([(k, v) for k, v in six.iteritems(ifaces) if k == interface]) if not target_ifaces: log.error('Interface %s not found.', interface) for ip_info in six.itervalues(target_ifaces): addrs = ip_info.get(proto, []) addrs.extend([addr for addr in ip_info.get('secondary', []) if addr.get('type') == proto]) for addr in addrs: addr = ipaddress.ip_address(addr.get('address')) if not addr.is_loopback or include_loopback: ret.add(addr) return [six.text_type(addr) for addr in sorted(ret)] def ip_addrs(interface=None, include_loopback=False, interface_data=None): ''' Returns a list of IPv4 addresses assigned to the host. 127.0.0.1 is ignored, unless 'include_loopback=True' is indicated. If 'interface' is provided, then only IP addresses from that interface will be returned. ''' return _ip_addrs(interface, include_loopback, interface_data, 'inet') def ip_addrs6(interface=None, include_loopback=False, interface_data=None): ''' Returns a list of IPv6 addresses assigned to the host. ::1 is ignored, unless 'include_loopback=True' is indicated. If 'interface' is provided, then only IP addresses from that interface will be returned. ''' return _ip_addrs(interface, include_loopback, interface_data, 'inet6') def hex2ip(hex_ip, invert=False): ''' Convert a hex string to an ip, if a failure occurs the original hex is returned. If 'invert=True' assume that ip from /proc/net/<proto> ''' if len(hex_ip) == 32: # ipv6 ip = [] for i in range(0, 32, 8): ip_part = hex_ip[i:i + 8] ip_part = [ip_part[x:x + 2] for x in range(0, 8, 2)] if invert: ip.append("{0[3]}{0[2]}:{0[1]}{0[0]}".format(ip_part)) else: ip.append("{0[0]}{0[1]}:{0[2]}{0[3]}".format(ip_part)) try: address = ipaddress.IPv6Address(":".join(ip)) if address.ipv4_mapped: return str(address.ipv4_mapped) else: return address.compressed except ipaddress.AddressValueError as ex: log.error('hex2ip - ipv6 address error: %s', ex) return hex_ip try: hip = int(hex_ip, 16) except ValueError: return hex_ip if invert: return '{3}.{2}.{1}.{0}'.format(hip >> 24 & 255, hip >> 16 & 255, hip >> 8 & 255, hip & 255) return '{0}.{1}.{2}.{3}'.format(hip >> 24 & 255, hip >> 16 & 255, hip >> 8 & 255, hip & 255) def mac2eui64(mac, prefix=None): ''' Convert a MAC address to a EUI64 identifier or, with prefix provided, a full IPv6 address ''' # http://tools.ietf.org/html/rfc4291#section-2.5.1 eui64 = re.sub(r'[.:-]', '', mac).lower() eui64 = eui64[0:6] + 'fffe' + eui64[6:] eui64 = hex(int(eui64[0:2], 16) | 2)[2:].zfill(2) + eui64[2:] if prefix is None: return ':'.join(re.findall(r'.{4}', eui64)) else: try: net = ipaddress.ip_network(prefix, strict=False) euil = int('0x{0}'.format(eui64), 16) return '{0}/{1}'.format(net[euil], net.prefixlen) except Exception: return def active_tcp(): ''' Return a dict describing all active tcp connections as quickly as possible ''' ret = {} for statf in ['/proc/net/tcp', '/proc/net/tcp6']: if os.path.isfile(statf): with salt.utils.files.fopen(statf, 'rb') as fp_: for line in fp_: line = salt.utils.stringutils.to_unicode(line) if line.strip().startswith('sl'): continue iret = _parse_tcp_line(line) sl = next(iter(iret)) if iret[sl]['state'] == 1: # 1 is ESTABLISHED del iret[sl]['state'] ret[len(ret)] = iret[sl] return ret def local_port_tcp(port): ''' Return a set of remote ip addrs attached to the specified local port ''' ret = _remotes_on(port, 'local_port') return ret def remote_port_tcp(port): ''' Return a set of ip addrs the current host is connected to on given port ''' ret = _remotes_on(port, 'remote_port') return ret def _remotes_on(port, which_end): ''' Return a set of ip addrs active tcp connections ''' port = int(port) ret = _netlink_tool_remote_on(port, which_end) if ret is not None: return ret ret = set() proc_available = False for statf in ['/proc/net/tcp', '/proc/net/tcp6']: if os.path.isfile(statf): proc_available = True with salt.utils.files.fopen(statf, 'r') as fp_: for line in fp_: line = salt.utils.stringutils.to_unicode(line) if line.strip().startswith('sl'): continue iret = _parse_tcp_line(line) sl = next(iter(iret)) if iret[sl][which_end] == port and iret[sl]['state'] == 1: # 1 is ESTABLISHED ret.add(iret[sl]['remote_addr']) if not proc_available: # Fallback to use OS specific tools if salt.utils.platform.is_sunos(): return _sunos_remotes_on(port, which_end) if salt.utils.platform.is_freebsd(): return _freebsd_remotes_on(port, which_end) if salt.utils.platform.is_netbsd(): return _netbsd_remotes_on(port, which_end) if salt.utils.platform.is_openbsd(): return _openbsd_remotes_on(port, which_end) if salt.utils.platform.is_windows(): return _windows_remotes_on(port, which_end) if salt.utils.platform.is_aix(): return _aix_remotes_on(port, which_end) return _linux_remotes_on(port, which_end) return ret def _parse_tcp_line(line): ''' Parse a single line from the contents of /proc/net/tcp or /proc/net/tcp6 ''' ret = {} comps = line.strip().split() sl = comps[0].rstrip(':') ret[sl] = {} l_addr, l_port = comps[1].split(':') r_addr, r_port = comps[2].split(':') ret[sl]['local_addr'] = hex2ip(l_addr, True) ret[sl]['local_port'] = int(l_port, 16) ret[sl]['remote_addr'] = hex2ip(r_addr, True) ret[sl]['remote_port'] = int(r_port, 16) ret[sl]['state'] = int(comps[3], 16) return ret def _netlink_tool_remote_on(port, which_end): ''' Returns set of ipv4 host addresses of remote established connections on local or remote tcp port. Parses output of shell 'ss' to get connections [root@salt-master ~]# ss -ant State Recv-Q Send-Q Local Address:Port Peer Address:Port LISTEN 0 511 *:80 *:* LISTEN 0 128 *:22 *:* ESTAB 0 0 127.0.0.1:56726 127.0.0.1:4505 ''' remotes = set() valid = False try: data = subprocess.check_output(['ss', '-ant']) # pylint: disable=minimum-python-version except subprocess.CalledProcessError: log.error('Failed ss') raise except OSError: # not command "No such file or directory" return None lines = salt.utils.stringutils.to_str(data).split('\n') for line in lines: if 'Address:Port' in line: # ss tools may not be valid valid = True continue elif 'ESTAB' not in line: continue chunks = line.split() local_host, local_port = chunks[3].split(':', 1) remote_host, remote_port = chunks[4].split(':', 1) if which_end == 'remote_port' and int(remote_port) != port: continue if which_end == 'local_port' and int(local_port) != port: continue remotes.add(remote_host) if valid is False: remotes = None return remotes def _sunos_remotes_on(port, which_end): ''' SunOS specific helper function. Returns set of ipv4 host addresses of remote established connections on local or remote tcp port. Parses output of shell 'netstat' to get connections [root@salt-master ~]# netstat -f inet -n TCP: IPv4 Local Address Remote Address Swind Send-Q Rwind Recv-Q State -------------------- -------------------- ----- ------ ----- ------ ----------- 10.0.0.101.4505 10.0.0.1.45329 1064800 0 1055864 0 ESTABLISHED 10.0.0.101.4505 10.0.0.100.50798 1064800 0 1055864 0 ESTABLISHED ''' remotes = set() try: data = subprocess.check_output(['netstat', '-f', 'inet', '-n']) # pylint: disable=minimum-python-version except subprocess.CalledProcessError: log.error('Failed netstat') raise lines = salt.utils.stringutils.to_str(data).split('\n') for line in lines: if 'ESTABLISHED' not in line: continue chunks = line.split() local_host, local_port = chunks[0].rsplit('.', 1) remote_host, remote_port = chunks[1].rsplit('.', 1) if which_end == 'remote_port' and int(remote_port) != port: continue if which_end == 'local_port' and int(local_port) != port: continue remotes.add(remote_host) return remotes def _freebsd_remotes_on(port, which_end): ''' Returns set of ipv4 host addresses of remote established connections on local tcp port port. Parses output of shell 'sockstat' (FreeBSD) to get connections $ sudo sockstat -4 USER COMMAND PID FD PROTO LOCAL ADDRESS FOREIGN ADDRESS root python2.7 1456 29 tcp4 *:4505 *:* root python2.7 1445 17 tcp4 *:4506 *:* root python2.7 1294 14 tcp4 127.0.0.1:11813 127.0.0.1:4505 root python2.7 1294 41 tcp4 127.0.0.1:61115 127.0.0.1:4506 $ sudo sockstat -4 -c -p 4506 USER COMMAND PID FD PROTO LOCAL ADDRESS FOREIGN ADDRESS root python2.7 1294 41 tcp4 127.0.0.1:61115 127.0.0.1:4506 ''' port = int(port) remotes = set() try: cmd = salt.utils.args.shlex_split('sockstat -4 -c -p {0}'.format(port)) data = subprocess.check_output(cmd) # pylint: disable=minimum-python-version except subprocess.CalledProcessError as ex: log.error('Failed "sockstat" with returncode = %s', ex.returncode) raise lines = salt.utils.stringutils.to_str(data).split('\n') for line in lines: chunks = line.split() if not chunks: continue # ['root', 'python2.7', '1456', '37', 'tcp4', # '127.0.0.1:4505-', '127.0.0.1:55703'] # print chunks if 'COMMAND' in chunks[1]: continue # ignore header if len(chunks) < 2: continue # sockstat -4 -c -p 4506 does this with high PIDs: # USER COMMAND PID FD PROTO LOCAL ADDRESS FOREIGN ADDRESS # salt-master python2.781106 35 tcp4 192.168.12.34:4506 192.168.12.45:60143 local = chunks[-2] remote = chunks[-1] lhost, lport = local.split(':') rhost, rport = remote.split(':') if which_end == 'local' and int(lport) != port: # ignore if local port not port continue if which_end == 'remote' and int(rport) != port: # ignore if remote port not port continue remotes.add(rhost) return remotes def _netbsd_remotes_on(port, which_end): ''' Returns set of ipv4 host addresses of remote established connections on local tcp port port. Parses output of shell 'sockstat' (NetBSD) to get connections $ sudo sockstat -4 -n USER COMMAND PID FD PROTO LOCAL ADDRESS FOREIGN ADDRESS root python2.7 1456 29 tcp *.4505 *.* root python2.7 1445 17 tcp *.4506 *.* root python2.7 1294 14 tcp 127.0.0.1.11813 127.0.0.1.4505 root python2.7 1294 41 tcp 127.0.0.1.61115 127.0.0.1.4506 $ sudo sockstat -4 -c -n -p 4506 USER COMMAND PID FD PROTO LOCAL ADDRESS FOREIGN ADDRESS root python2.7 1294 41 tcp 127.0.0.1.61115 127.0.0.1.4506 ''' port = int(port) remotes = set() try: cmd = salt.utils.args.shlex_split('sockstat -4 -c -n -p {0}'.format(port)) data = subprocess.check_output(cmd) # pylint: disable=minimum-python-version except subprocess.CalledProcessError as ex: log.error('Failed "sockstat" with returncode = %s', ex.returncode) raise lines = salt.utils.stringutils.to_str(data).split('\n') for line in lines: chunks = line.split() if not chunks: continue # ['root', 'python2.7', '1456', '37', 'tcp', # '127.0.0.1.4505-', '127.0.0.1.55703'] # print chunks if 'COMMAND' in chunks[1]: continue # ignore header if len(chunks) < 2: continue local = chunks[5].split('.') lport = local.pop() lhost = '.'.join(local) remote = chunks[6].split('.') rport = remote.pop() rhost = '.'.join(remote) if which_end == 'local' and int(lport) != port: # ignore if local port not port continue if which_end == 'remote' and int(rport) != port: # ignore if remote port not port continue remotes.add(rhost) return remotes def _openbsd_remotes_on(port, which_end): ''' OpenBSD specific helper function. Returns set of ipv4 host addresses of remote established connections on local or remote tcp port. Parses output of shell 'netstat' to get connections $ netstat -nf inet Active Internet connections Proto Recv-Q Send-Q Local Address Foreign Address (state) tcp 0 0 10.0.0.101.4505 10.0.0.1.45329 ESTABLISHED tcp 0 0 10.0.0.101.4505 10.0.0.100.50798 ESTABLISHED ''' remotes = set() try: data = subprocess.check_output(['netstat', '-nf', 'inet']) # pylint: disable=minimum-python-version except subprocess.CalledProcessError: log.error('Failed netstat') raise lines = data.split('\n') for line in lines: if 'ESTABLISHED' not in line: continue chunks = line.split() local_host, local_port = chunks[3].rsplit('.', 1) remote_host, remote_port = chunks[4].rsplit('.', 1) if which_end == 'remote_port' and int(remote_port) != port: continue if which_end == 'local_port' and int(local_port) != port: continue remotes.add(remote_host) return remotes def _windows_remotes_on(port, which_end): r''' Windows specific helper function. Returns set of ipv4 host addresses of remote established connections on local or remote tcp port. Parses output of shell 'netstat' to get connections C:\>netstat -n Active Connections Proto Local Address Foreign Address State TCP 10.2.33.17:3007 130.164.12.233:10123 ESTABLISHED TCP 10.2.33.17:3389 130.164.30.5:10378 ESTABLISHED ''' remotes = set() try: data = subprocess.check_output(['netstat', '-n']) # pylint: disable=minimum-python-version except subprocess.CalledProcessError: log.error('Failed netstat') raise lines = salt.utils.stringutils.to_str(data).split('\n') for line in lines: if 'ESTABLISHED' not in line: continue chunks = line.split() local_host, local_port = chunks[1].rsplit(':', 1) remote_host, remote_port = chunks[2].rsplit(':', 1) if which_end == 'remote_port' and int(remote_port) != port: continue if which_end == 'local_port' and int(local_port) != port: continue remotes.add(remote_host) return remotes def _linux_remotes_on(port, which_end): ''' Linux specific helper function. Returns set of ip host addresses of remote established connections on local tcp port port. Parses output of shell 'lsof' to get connections $ sudo lsof -iTCP:4505 -n COMMAND PID USER FD TYPE DEVICE SIZE/OFF NODE NAME Python 9971 root 35u IPv4 0x18a8464a29ca329d 0t0 TCP *:4505 (LISTEN) Python 9971 root 37u IPv4 0x18a8464a29b2b29d 0t0 TCP 127.0.0.1:4505->127.0.0.1:55703 (ESTABLISHED) Python 10152 root 22u IPv4 0x18a8464a29c8cab5 0t0 TCP 127.0.0.1:55703->127.0.0.1:4505 (ESTABLISHED) Python 10153 root 22u IPv4 0x18a8464a29c8cab5 0t0 TCP [fe80::249a]:4505->[fe80::150]:59367 (ESTABLISHED) ''' remotes = set() try: data = subprocess.check_output( ['lsof', '-iTCP:{0:d}'.format(port), '-n', '-P'] # pylint: disable=minimum-python-version ) except subprocess.CalledProcessError as ex: if ex.returncode == 1: # Lsof return 1 if any error was detected, including the failure # to locate Internet addresses, and it is not an error in this case. log.warning('"lsof" returncode = 1, likely no active TCP sessions.') return remotes log.error('Failed "lsof" with returncode = %s', ex.returncode) raise lines = salt.utils.stringutils.to_str(data).split('\n') for line in lines: chunks = line.split() if not chunks: continue # ['Python', '9971', 'root', '37u', 'IPv4', '0x18a8464a29b2b29d', '0t0', # 'TCP', '127.0.0.1:4505->127.0.0.1:55703', '(ESTABLISHED)'] # print chunks if 'COMMAND' in chunks[0]: continue # ignore header if 'ESTABLISHED' not in chunks[-1]: continue # ignore if not ESTABLISHED # '127.0.0.1:4505->127.0.0.1:55703' local, remote = chunks[8].split('->') _, lport = local.rsplit(':', 1) rhost, rport = remote.rsplit(':', 1) if which_end == 'remote_port' and int(rport) != port: continue if which_end == 'local_port' and int(lport) != port: continue remotes.add(rhost.strip("[]")) return remotes def _aix_remotes_on(port, which_end): ''' AIX specific helper function. Returns set of ipv4 host addresses of remote established connections on local or remote tcp port. Parses output of shell 'netstat' to get connections root@la68pp002_pub:/opt/salt/lib/python2.7/site-packages/salt/modules# netstat -f inet -n Active Internet connections Proto Recv-Q Send-Q Local Address Foreign Address (state) tcp4 0 0 172.29.149.95.50093 209.41.78.13.4505 ESTABLISHED tcp4 0 0 127.0.0.1.9514 *.* LISTEN tcp4 0 0 127.0.0.1.9515 *.* LISTEN tcp4 0 0 127.0.0.1.199 127.0.0.1.32779 ESTABLISHED tcp4 0 0 127.0.0.1.32779 127.0.0.1.199 ESTABLISHED tcp4 0 40 172.29.149.95.22 172.29.96.83.41022 ESTABLISHED tcp4 0 0 172.29.149.95.22 172.29.96.83.41032 ESTABLISHED tcp4 0 0 127.0.0.1.32771 127.0.0.1.32775 ESTABLISHED tcp 0 0 127.0.0.1.32775 127.0.0.1.32771 ESTABLISHED tcp4 0 0 127.0.0.1.32771 127.0.0.1.32776 ESTABLISHED tcp 0 0 127.0.0.1.32776 127.0.0.1.32771 ESTABLISHED tcp4 0 0 127.0.0.1.32771 127.0.0.1.32777 ESTABLISHED tcp 0 0 127.0.0.1.32777 127.0.0.1.32771 ESTABLISHED tcp4 0 0 127.0.0.1.32771 127.0.0.1.32778 ESTABLISHED tcp 0 0 127.0.0.1.32778 127.0.0.1.32771 ESTABLISHED ''' remotes = set() try: data = subprocess.check_output(['netstat', '-f', 'inet', '-n']) # pylint: disable=minimum-python-version except subprocess.CalledProcessError: log.error('Failed netstat') raise lines = salt.utils.stringutils.to_str(data).split('\n') for line in lines: if 'ESTABLISHED' not in line: continue chunks = line.split() local_host, local_port = chunks[3].rsplit('.', 1) remote_host, remote_port = chunks[4].rsplit('.', 1) if which_end == 'remote_port' and int(remote_port) != port: continue if which_end == 'local_port' and int(local_port) != port: continue remotes.add(remote_host) return remotes @jinja_filter('gen_mac') def gen_mac(prefix='AC:DE:48'): ''' Generates a MAC address with the defined OUI prefix. Common prefixes: - ``00:16:3E`` -- Xen - ``00:18:51`` -- OpenVZ - ``00:50:56`` -- VMware (manually generated) - ``52:54:00`` -- QEMU/KVM - ``AC:DE:48`` -- PRIVATE References: - http://standards.ieee.org/develop/regauth/oui/oui.txt - https://www.wireshark.org/tools/oui-lookup.html - https://en.wikipedia.org/wiki/MAC_address ''' return '{0}:{1:02X}:{2:02X}:{3:02X}'.format(prefix, random.randint(0, 0xff), random.randint(0, 0xff), random.randint(0, 0xff)) @jinja_filter('mac_str_to_bytes') def mac_str_to_bytes(mac_str): ''' Convert a MAC address string into bytes. Works with or without separators: b1 = mac_str_to_bytes('08:00:27:13:69:77') b2 = mac_str_to_bytes('080027136977') assert b1 == b2 assert isinstance(b1, bytes) ''' if len(mac_str) == 12: pass elif len(mac_str) == 17: sep = mac_str[2] mac_str = mac_str.replace(sep, '') else: raise ValueError('Invalid MAC address') chars = (int(mac_str[s:s+2], 16) for s in range(0, 12, 2)) return bytes(chars) if six.PY3 else b''.join(chr(x) for x in chars) def refresh_dns(): ''' issue #21397: force glibc to re-read resolv.conf ''' try: res_init() except NameError: # Exception raised loading the library, thus res_init is not defined pass @jinja_filter('connection_check') def connection_check(addr, port=80, safe=False, ipv6=None): ''' Provides a convenient alias for the dns_check filter. ''' return dns_check(addr, port, safe, ipv6) @jinja_filter('dns_check') def dns_check(addr, port=80, safe=False, ipv6=None, attempt_connect=True): ''' Return the ip resolved by dns, but do not exit on failure, only raise an exception. Obeys system preference for IPv4/6 address resolution - this can be overridden by the ipv6 flag. Tries to connect to the address before considering it useful. If no address can be reached, the first one resolved is used as a fallback. ''' error = False lookup = addr seen_ipv6 = False family = socket.AF_INET6 if ipv6 else socket.AF_INET if ipv6 is False else socket.AF_UNSPEC hostnames = [] try: refresh_dns() hostnames = socket.getaddrinfo(addr, port, family, socket.SOCK_STREAM) except TypeError: err = ('Attempt to resolve address \'{0}\' failed. Invalid or unresolveable address').format(lookup) raise SaltSystemExit(code=42, msg=err) except socket.error: error = True # If ipv6 is set to True, attempt another lookup using the IPv4 family, # just in case we're attempting to lookup an IPv4 IP # as an IPv6 hostname. if error and ipv6: try: refresh_dns() hostnames = socket.getaddrinfo(addr, port, socket.AF_INET, socket.SOCK_STREAM) except TypeError: err = ('Attempt to resolve address \'{0}\' failed. Invalid or unresolveable address').format(lookup) raise SaltSystemExit(code=42, msg=err) except socket.error: error = True try: if not hostnames: error = True else: resolved = False candidates = [] for h in hostnames: # Input is IP address, passed through unchanged, just return it if h[4][0] == addr: resolved = salt.utils.zeromq.ip_bracket(addr) break candidate_addr = salt.utils.zeromq.ip_bracket(h[4][0]) # sometimes /etc/hosts contains ::1 localhost if not ipv6 and candidate_addr == '[::1]': continue candidates.append(candidate_addr) if attempt_connect: try: s = socket.socket(h[0], socket.SOCK_STREAM) s.settimeout(2) s.connect((candidate_addr.strip('[]'), h[4][1])) s.close() resolved = candidate_addr break except socket.error: pass if not resolved: if candidates: resolved = candidates[0] else: error = True except TypeError: err = ('Attempt to resolve address \'{0}\' failed. Invalid or unresolveable address').format(lookup) raise SaltSystemExit(code=42, msg=err) except socket.error: error = True if error: err = ('DNS lookup or connection check of \'{0}\' failed.').format(addr) if safe: if salt.log.is_console_configured(): # If logging is not configured it also means that either # the master or minion instance calling this hasn't even # started running log.error(err) raise SaltClientError() raise SaltSystemExit(code=42, msg=err) return resolved def parse_host_port(host_port): """ Takes a string argument specifying host or host:port. Returns a (hostname, port) or (ip_address, port) tuple. If no port is given, the second (port) element of the returned tuple will be None. host:port argument, for example, is accepted in the forms of: - hostname - hostname:1234 - hostname.domain.tld - hostname.domain.tld:5678 - [1234::5]:5678 - 1234::5 - 10.11.12.13:4567 - 10.11.12.13 """ host, port = None, None # default _s_ = host_port[:] if _s_[0] == "[": if "]" in host_port: host, _s_ = _s_.lstrip("[").rsplit("]", 1) host = ipaddress.IPv6Address(host).compressed if _s_[0] == ":": port = int(_s_.lstrip(":")) else: if len(_s_) > 1: raise ValueError('found ambiguous "{}" port in "{}"'.format(_s_, host_port)) else: if _s_.count(":") == 1: host, _hostport_separator_, port = _s_.partition(":") try: port = int(port) except ValueError as _e_: log.error('host_port "%s" port value "%s" is not an integer.', host_port, port) raise _e_ else: host = _s_ try: if not isinstance(host, ipaddress._BaseAddress): host_ip = ipaddress.ip_address(host).compressed host = host_ip except ValueError: log.debug('"%s" Not an IP address? Assuming it is a hostname.', host) if host != sanitize_host(host): log.error('bad hostname: "%s"', host) raise ValueError('bad hostname: "{}"'.format(host)) return host, port def is_fqdn(hostname): """ Verify if hostname conforms to be a FQDN. :param hostname: text string with the name of the host :return: bool, True if hostname is correct FQDN, False otherwise """ compliant = re.compile(r"(?!-)[A-Z\d\-\_]{1,63}(?<!-)$", re.IGNORECASE) return "." in hostname and len(hostname) < 0xff and all(compliant.match(x) for x in hostname.rstrip(".").split("."))
saltstack/salt
salt/utils/network.py
_interfaces_ifconfig
python
def _interfaces_ifconfig(out): ''' Uses ifconfig to return a dictionary of interfaces with various information about each (up/down state, ip address, netmask, and hwaddr) ''' ret = dict() piface = re.compile(r'^([^\s:]+)') pmac = re.compile('.*?(?:HWaddr|ether|address:|lladdr) ([0-9a-fA-F:]+)') if salt.utils.platform.is_sunos(): pip = re.compile(r'.*?(?:inet\s+)([0-9]+\.[0-9]+\.[0-9]+\.[0-9]+)(.*)') pip6 = re.compile('.*?(?:inet6 )([0-9a-fA-F:]+)') pmask6 = re.compile(r'.*?(?:inet6 [0-9a-fA-F:]+/(\d+)).*') else: pip = re.compile(r'.*?(?:inet addr:|inet [^\d]*)(.*?)\s') pip6 = re.compile('.*?(?:inet6 addr: (.*?)/|inet6 )([0-9a-fA-F:]+)') pmask6 = re.compile(r'.*?(?:inet6 addr: [0-9a-fA-F:]+/(\d+)|prefixlen (\d+))(?: Scope:([a-zA-Z]+)| scopeid (0x[0-9a-fA-F]))?') pmask = re.compile(r'.*?(?:Mask:|netmask )(?:((?:0x)?[0-9a-fA-F]{8})|([\d\.]+))') pupdown = re.compile('UP') pbcast = re.compile(r'.*?(?:Bcast:|broadcast )([\d\.]+)') groups = re.compile('\r?\n(?=\\S)').split(out) for group in groups: data = dict() iface = '' updown = False for line in group.splitlines(): miface = piface.match(line) mmac = pmac.match(line) mip = pip.match(line) mip6 = pip6.match(line) mupdown = pupdown.search(line) if miface: iface = miface.group(1) if mmac: data['hwaddr'] = mmac.group(1) if salt.utils.platform.is_sunos(): expand_mac = [] for chunk in data['hwaddr'].split(':'): expand_mac.append('0{0}'.format(chunk) if len(chunk) < 2 else '{0}'.format(chunk)) data['hwaddr'] = ':'.join(expand_mac) if mip: if 'inet' not in data: data['inet'] = list() addr_obj = dict() addr_obj['address'] = mip.group(1) mmask = pmask.match(line) if mmask: if mmask.group(1): mmask = _number_of_set_bits_to_ipv4_netmask( int(mmask.group(1), 16)) else: mmask = mmask.group(2) addr_obj['netmask'] = mmask mbcast = pbcast.match(line) if mbcast: addr_obj['broadcast'] = mbcast.group(1) data['inet'].append(addr_obj) if mupdown: updown = True if mip6: if 'inet6' not in data: data['inet6'] = list() addr_obj = dict() addr_obj['address'] = mip6.group(1) or mip6.group(2) mmask6 = pmask6.match(line) if mmask6: addr_obj['prefixlen'] = mmask6.group(1) or mmask6.group(2) if not salt.utils.platform.is_sunos(): ipv6scope = mmask6.group(3) or mmask6.group(4) addr_obj['scope'] = ipv6scope.lower() if ipv6scope is not None else ipv6scope # SunOS sometimes has ::/0 as inet6 addr when using addrconf if not salt.utils.platform.is_sunos() \ or addr_obj['address'] != '::' \ and addr_obj['prefixlen'] != 0: data['inet6'].append(addr_obj) data['up'] = updown if iface in ret: # SunOS optimization, where interfaces occur twice in 'ifconfig -a' # output with the same name: for ipv4 and then for ipv6 addr family. # Every instance has it's own 'UP' status and we assume that ipv4 # status determines global interface status. # # merge items with higher priority for older values # after that merge the inet and inet6 sub items for both ret[iface] = dict(list(data.items()) + list(ret[iface].items())) if 'inet' in data: ret[iface]['inet'].extend(x for x in data['inet'] if x not in ret[iface]['inet']) if 'inet6' in data: ret[iface]['inet6'].extend(x for x in data['inet6'] if x not in ret[iface]['inet6']) else: ret[iface] = data del data return ret
Uses ifconfig to return a dictionary of interfaces with various information about each (up/down state, ip address, netmask, and hwaddr)
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/network.py#L748-L841
[ "def _number_of_set_bits_to_ipv4_netmask(set_bits): # pylint: disable=C0103\n '''\n Returns an IPv4 netmask from the integer representation of that mask.\n\n Ex. 0xffffff00 -> '255.255.255.0'\n '''\n return cidr_to_ipv4_netmask(_number_of_set_bits(set_bits))\n" ]
# -*- coding: utf-8 -*- ''' Define some generic socket functions for network modules ''' # Import python libs from __future__ import absolute_import, unicode_literals, print_function import itertools import os import re import types import socket import logging import platform import random import subprocess from string import ascii_letters, digits # Import 3rd-party libs from salt.ext import six from salt.ext.six.moves import range # pylint: disable=import-error,redefined-builtin # Attempt to import wmi try: import wmi import salt.utils.winapi except ImportError: pass # Import salt libs import salt.utils.args import salt.utils.files import salt.utils.path import salt.utils.platform import salt.utils.stringutils import salt.utils.zeromq from salt._compat import ipaddress from salt.exceptions import SaltClientError, SaltSystemExit from salt.utils.decorators.jinja import jinja_filter from salt.utils.versions import LooseVersion # inet_pton does not exist in Windows, this is a workaround if salt.utils.platform.is_windows(): from salt.ext import win_inet_pton # pylint: disable=unused-import log = logging.getLogger(__name__) try: import ctypes import ctypes.util libc = ctypes.cdll.LoadLibrary(ctypes.util.find_library("c")) res_init = libc.__res_init except (ImportError, OSError, AttributeError, TypeError): pass # pylint: disable=C0103 def sanitize_host(host): ''' Sanitize host string. https://tools.ietf.org/html/rfc1123#section-2.1 ''' RFC952_characters = ascii_letters + digits + ".-" return "".join([c for c in host[0:255] if c in RFC952_characters]) def isportopen(host, port): ''' Return status of a port ''' if not 1 <= int(port) <= 65535: return False sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) out = sock.connect_ex((sanitize_host(host), int(port))) return out def host_to_ips(host): ''' Returns a list of IP addresses of a given hostname or None if not found. ''' ips = [] try: for family, socktype, proto, canonname, sockaddr in socket.getaddrinfo( host, 0, socket.AF_UNSPEC, socket.SOCK_STREAM): if family == socket.AF_INET: ip, port = sockaddr elif family == socket.AF_INET6: ip, port, flow_info, scope_id = sockaddr ips.append(ip) if not ips: ips = None except Exception: ips = None return ips def _generate_minion_id(): ''' Get list of possible host names and convention names. :return: ''' # There are three types of hostnames: # 1. Network names. How host is accessed from the network. # 2. Host aliases. They might be not available in all the network or only locally (/etc/hosts) # 3. Convention names, an internal nodename. class DistinctList(list): ''' List, which allows one to append only distinct objects. Needs to work on Python 2.6, because of collections.OrderedDict only since 2.7 version. Override 'filter()' for custom filtering. ''' localhost_matchers = [r'localhost.*', r'ip6-.*', r'127[.]\d', r'0\.0\.0\.0', r'::1.*', r'ipv6-.*', r'fe00::.*', r'fe02::.*', r'1.0.0.*.ip6.arpa'] def append(self, p_object): if p_object and p_object not in self and not self.filter(p_object): super(DistinctList, self).append(p_object) return self def extend(self, iterable): for obj in iterable: self.append(obj) return self def filter(self, element): 'Returns True if element needs to be filtered' for rgx in self.localhost_matchers: if re.match(rgx, element): return True def first(self): return self and self[0] or None hostname = socket.gethostname() hosts = DistinctList().append( salt.utils.stringutils.to_unicode(socket.getfqdn(salt.utils.stringutils.to_bytes(hostname))) ).append(platform.node()).append(hostname) if not hosts: try: for a_nfo in socket.getaddrinfo(hosts.first() or 'localhost', None, socket.AF_INET, socket.SOCK_RAW, socket.IPPROTO_IP, socket.AI_CANONNAME): if len(a_nfo) > 3: hosts.append(a_nfo[3]) except socket.gaierror: log.warning('Cannot resolve address %s info via socket: %s', hosts.first() or 'localhost (N/A)', socket.gaierror) # Universal method for everywhere (Linux, Slowlaris, Windows etc) for f_name in ('/etc/hostname', '/etc/nodename', '/etc/hosts', r'{win}\system32\drivers\etc\hosts'.format(win=os.getenv('WINDIR'))): try: with salt.utils.files.fopen(f_name) as f_hdl: for line in f_hdl: line = salt.utils.stringutils.to_unicode(line) hst = line.strip().split('#')[0].strip().split() if hst: if hst[0][:4] in ('127.', '::1') or len(hst) == 1: hosts.extend(hst) except IOError: pass # include public and private ipaddresses return hosts.extend([addr for addr in ip_addrs() if not ipaddress.ip_address(addr).is_loopback]) def generate_minion_id(): ''' Return only first element of the hostname from all possible list. :return: ''' try: ret = salt.utils.stringutils.to_unicode(_generate_minion_id().first()) except TypeError: ret = None return ret or 'localhost' def get_socket(addr, type=socket.SOCK_STREAM, proto=0): ''' Return a socket object for the addr IP-version agnostic ''' version = ipaddress.ip_address(addr).version if version == 4: family = socket.AF_INET elif version == 6: family = socket.AF_INET6 return socket.socket(family, type, proto) def get_fqhostname(): ''' Returns the fully qualified hostname ''' # try getaddrinfo() fqdn = None try: addrinfo = socket.getaddrinfo( socket.gethostname(), 0, socket.AF_UNSPEC, socket.SOCK_STREAM, socket.SOL_TCP, socket.AI_CANONNAME ) for info in addrinfo: # info struct [family, socktype, proto, canonname, sockaddr] # On Windows `canonname` can be an empty string # This can cause the function to return `None` if len(info) > 3 and info[3]: fqdn = info[3] break except socket.gaierror: pass # NOTE: this used to log.error() but it was later disabled except socket.error as err: log.debug('socket.getaddrinfo() failure while finding fqdn: %s', err) if fqdn is None: fqdn = socket.getfqdn() return fqdn def ip_to_host(ip): ''' Returns the hostname of a given IP ''' try: hostname, aliaslist, ipaddrlist = socket.gethostbyaddr(ip) except Exception as exc: log.debug('salt.utils.network.ip_to_host(%r) failed: %s', ip, exc) hostname = None return hostname # pylint: enable=C0103 def is_reachable_host(entity_name): ''' Returns a bool telling if the entity name is a reachable host (IPv4/IPv6/FQDN/etc). :param hostname: :return: ''' try: assert type(socket.getaddrinfo(entity_name, 0, 0, 0, 0)) == list ret = True except socket.gaierror: ret = False return ret def is_ip(ip): ''' Returns a bool telling if the passed IP is a valid IPv4 or IPv6 address. ''' return is_ipv4(ip) or is_ipv6(ip) def is_ipv4(ip): ''' Returns a bool telling if the value passed to it was a valid IPv4 address ''' try: return ipaddress.ip_address(ip).version == 4 except ValueError: return False def is_ipv6(ip): ''' Returns a bool telling if the value passed to it was a valid IPv6 address ''' try: return ipaddress.ip_address(ip).version == 6 except ValueError: return False def is_subnet(cidr): ''' Returns a bool telling if the passed string is an IPv4 or IPv6 subnet ''' return is_ipv4_subnet(cidr) or is_ipv6_subnet(cidr) def is_ipv4_subnet(cidr): ''' Returns a bool telling if the passed string is an IPv4 subnet ''' try: return '/' in cidr and bool(ipaddress.IPv4Network(cidr)) except Exception: return False def is_ipv6_subnet(cidr): ''' Returns a bool telling if the passed string is an IPv6 subnet ''' try: return '/' in cidr and bool(ipaddress.IPv6Network(cidr)) except Exception: return False @jinja_filter('is_ip') def is_ip_filter(ip, options=None): ''' Returns a bool telling if the passed IP is a valid IPv4 or IPv6 address. ''' return is_ipv4_filter(ip, options=options) or is_ipv6_filter(ip, options=options) def _ip_options_global(ip_obj, version): return not ip_obj.is_private def _ip_options_multicast(ip_obj, version): return ip_obj.is_multicast def _ip_options_loopback(ip_obj, version): return ip_obj.is_loopback def _ip_options_link_local(ip_obj, version): return ip_obj.is_link_local def _ip_options_private(ip_obj, version): return ip_obj.is_private def _ip_options_reserved(ip_obj, version): return ip_obj.is_reserved def _ip_options_site_local(ip_obj, version): if version == 6: return ip_obj.is_site_local return False def _ip_options_unspecified(ip_obj, version): return ip_obj.is_unspecified def _ip_options(ip_obj, version, options=None): # will process and IP options options_fun_map = { 'global': _ip_options_global, 'link-local': _ip_options_link_local, 'linklocal': _ip_options_link_local, 'll': _ip_options_link_local, 'link_local': _ip_options_link_local, 'loopback': _ip_options_loopback, 'lo': _ip_options_loopback, 'multicast': _ip_options_multicast, 'private': _ip_options_private, 'public': _ip_options_global, 'reserved': _ip_options_reserved, 'site-local': _ip_options_site_local, 'sl': _ip_options_site_local, 'site_local': _ip_options_site_local, 'unspecified': _ip_options_unspecified } if not options: return six.text_type(ip_obj) # IP version already checked options_list = [option.strip() for option in options.split(',')] for option, fun in options_fun_map.items(): if option in options_list: fun_res = fun(ip_obj, version) if not fun_res: return None # stop at first failed test # else continue return six.text_type(ip_obj) def _is_ipv(ip, version, options=None): if not version: version = 4 if version not in (4, 6): return None try: ip_obj = ipaddress.ip_address(ip) except ValueError: # maybe it is an IP network try: ip_obj = ipaddress.ip_interface(ip) except ValueError: # nope, still not :( return None if not ip_obj.version == version: return None # has the right version, let's move on return _ip_options(ip_obj, version, options=options) @jinja_filter('is_ipv4') def is_ipv4_filter(ip, options=None): ''' Returns a bool telling if the value passed to it was a valid IPv4 address. ip The IP address. net: False Consider IP addresses followed by netmask. options CSV of options regarding the nature of the IP address. E.g.: loopback, multicast, private etc. ''' _is_ipv4 = _is_ipv(ip, 4, options=options) return isinstance(_is_ipv4, six.string_types) @jinja_filter('is_ipv6') def is_ipv6_filter(ip, options=None): ''' Returns a bool telling if the value passed to it was a valid IPv6 address. ip The IP address. net: False Consider IP addresses followed by netmask. options CSV of options regarding the nature of the IP address. E.g.: loopback, multicast, private etc. ''' _is_ipv6 = _is_ipv(ip, 6, options=options) return isinstance(_is_ipv6, six.string_types) def _ipv_filter(value, version, options=None): if version not in (4, 6): return if isinstance(value, (six.string_types, six.text_type, six.binary_type)): return _is_ipv(value, version, options=options) # calls is_ipv4 or is_ipv6 for `value` elif isinstance(value, (list, tuple, types.GeneratorType)): # calls is_ipv4 or is_ipv6 for each element in the list # os it filters and returns only those elements having the desired IP version return [ _is_ipv(addr, version, options=options) for addr in value if _is_ipv(addr, version, options=options) is not None ] return None @jinja_filter('ipv4') def ipv4(value, options=None): ''' Filters a list and returns IPv4 values only. ''' return _ipv_filter(value, 4, options=options) @jinja_filter('ipv6') def ipv6(value, options=None): ''' Filters a list and returns IPv6 values only. ''' return _ipv_filter(value, 6, options=options) @jinja_filter('ipaddr') def ipaddr(value, options=None): ''' Filters and returns only valid IP objects. ''' ipv4_obj = ipv4(value, options=options) ipv6_obj = ipv6(value, options=options) if ipv4_obj is None or ipv6_obj is None: # an IP address can be either IPv4 either IPv6 # therefofe if the value passed as arg is not a list, at least one of the calls above will return None # if one of them is none, means that we should return only one of them return ipv4_obj or ipv6_obj # one of them else: return ipv4_obj + ipv6_obj # extend lists def _filter_ipaddr(value, options, version=None): ipaddr_filter_out = None if version: if version == 4: ipaddr_filter_out = ipv4(value, options) elif version == 6: ipaddr_filter_out = ipv6(value, options) else: ipaddr_filter_out = ipaddr(value, options) if not ipaddr_filter_out: return if not isinstance(ipaddr_filter_out, (list, tuple, types.GeneratorType)): ipaddr_filter_out = [ipaddr_filter_out] return ipaddr_filter_out @jinja_filter('ip_host') def ip_host(value, options=None, version=None): ''' Returns the interfaces IP address, e.g.: 192.168.0.1/28. ''' ipaddr_filter_out = _filter_ipaddr(value, options=options, version=version) if not ipaddr_filter_out: return if not isinstance(value, (list, tuple, types.GeneratorType)): return six.text_type(ipaddress.ip_interface(ipaddr_filter_out[0])) return [six.text_type(ipaddress.ip_interface(ip_a)) for ip_a in ipaddr_filter_out] def _network_hosts(ip_addr_entry): return [ six.text_type(host) for host in ipaddress.ip_network(ip_addr_entry, strict=False).hosts() ] @jinja_filter('network_hosts') def network_hosts(value, options=None, version=None): ''' Return the list of hosts within a network. .. note:: When running this command with a large IPv6 network, the command will take a long time to gather all of the hosts. ''' ipaddr_filter_out = _filter_ipaddr(value, options=options, version=version) if not ipaddr_filter_out: return if not isinstance(value, (list, tuple, types.GeneratorType)): return _network_hosts(ipaddr_filter_out[0]) return [ _network_hosts(ip_a) for ip_a in ipaddr_filter_out ] def _network_size(ip_addr_entry): return ipaddress.ip_network(ip_addr_entry, strict=False).num_addresses @jinja_filter('network_size') def network_size(value, options=None, version=None): ''' Get the size of a network. ''' ipaddr_filter_out = _filter_ipaddr(value, options=options, version=version) if not ipaddr_filter_out: return if not isinstance(value, (list, tuple, types.GeneratorType)): return _network_size(ipaddr_filter_out[0]) return [ _network_size(ip_a) for ip_a in ipaddr_filter_out ] def natural_ipv4_netmask(ip, fmt='prefixlen'): ''' Returns the "natural" mask of an IPv4 address ''' bits = _ipv4_to_bits(ip) if bits.startswith('11'): mask = '24' elif bits.startswith('1'): mask = '16' else: mask = '8' if fmt == 'netmask': return cidr_to_ipv4_netmask(mask) else: return '/' + mask def rpad_ipv4_network(ip): ''' Returns an IP network address padded with zeros. Ex: '192.168.3' -> '192.168.3.0' '10.209' -> '10.209.0.0' ''' return '.'.join(itertools.islice(itertools.chain(ip.split('.'), '0000'), 0, 4)) def cidr_to_ipv4_netmask(cidr_bits): ''' Returns an IPv4 netmask ''' try: cidr_bits = int(cidr_bits) if not 1 <= cidr_bits <= 32: return '' except ValueError: return '' netmask = '' for idx in range(4): if idx: netmask += '.' if cidr_bits >= 8: netmask += '255' cidr_bits -= 8 else: netmask += '{0:d}'.format(256 - (2 ** (8 - cidr_bits))) cidr_bits = 0 return netmask def _number_of_set_bits_to_ipv4_netmask(set_bits): # pylint: disable=C0103 ''' Returns an IPv4 netmask from the integer representation of that mask. Ex. 0xffffff00 -> '255.255.255.0' ''' return cidr_to_ipv4_netmask(_number_of_set_bits(set_bits)) # pylint: disable=C0103 def _number_of_set_bits(x): ''' Returns the number of bits that are set in a 32bit int ''' # Taken from http://stackoverflow.com/a/4912729. Many thanks! x -= (x >> 1) & 0x55555555 x = ((x >> 2) & 0x33333333) + (x & 0x33333333) x = ((x >> 4) + x) & 0x0f0f0f0f x += x >> 8 x += x >> 16 return x & 0x0000003f # pylint: enable=C0103 def _interfaces_ip(out): ''' Uses ip to return a dictionary of interfaces with various information about each (up/down state, ip address, netmask, and hwaddr) ''' ret = dict() def parse_network(value, cols): ''' Return a tuple of ip, netmask, broadcast based on the current set of cols ''' brd = None scope = None if '/' in value: # we have a CIDR in this address ip, cidr = value.split('/') # pylint: disable=C0103 else: ip = value # pylint: disable=C0103 cidr = 32 if type_ == 'inet': mask = cidr_to_ipv4_netmask(int(cidr)) if 'brd' in cols: brd = cols[cols.index('brd') + 1] elif type_ == 'inet6': mask = cidr if 'scope' in cols: scope = cols[cols.index('scope') + 1] return (ip, mask, brd, scope) groups = re.compile('\r?\n\\d').split(out) for group in groups: iface = None data = dict() for line in group.splitlines(): if ' ' not in line: continue match = re.match(r'^\d*:\s+([\w.\-]+)(?:@)?([\w.\-]+)?:\s+<(.+)>', line) if match: iface, parent, attrs = match.groups() if 'UP' in attrs.split(','): data['up'] = True else: data['up'] = False if parent: data['parent'] = parent continue cols = line.split() if len(cols) >= 2: type_, value = tuple(cols[0:2]) iflabel = cols[-1:][0] if type_ in ('inet', 'inet6'): if 'secondary' not in cols: ipaddr, netmask, broadcast, scope = parse_network(value, cols) if type_ == 'inet': if 'inet' not in data: data['inet'] = list() addr_obj = dict() addr_obj['address'] = ipaddr addr_obj['netmask'] = netmask addr_obj['broadcast'] = broadcast addr_obj['label'] = iflabel data['inet'].append(addr_obj) elif type_ == 'inet6': if 'inet6' not in data: data['inet6'] = list() addr_obj = dict() addr_obj['address'] = ipaddr addr_obj['prefixlen'] = netmask addr_obj['scope'] = scope data['inet6'].append(addr_obj) else: if 'secondary' not in data: data['secondary'] = list() ip_, mask, brd, scp = parse_network(value, cols) data['secondary'].append({ 'type': type_, 'address': ip_, 'netmask': mask, 'broadcast': brd, 'label': iflabel, }) del ip_, mask, brd, scp elif type_.startswith('link'): data['hwaddr'] = value if iface: ret[iface] = data del iface, data return ret def linux_interfaces(): ''' Obtain interface information for *NIX/BSD variants ''' ifaces = dict() ip_path = salt.utils.path.which('ip') ifconfig_path = None if ip_path else salt.utils.path.which('ifconfig') if ip_path: cmd1 = subprocess.Popen( '{0} link show'.format(ip_path), shell=True, close_fds=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT).communicate()[0] cmd2 = subprocess.Popen( '{0} addr show'.format(ip_path), shell=True, close_fds=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT).communicate()[0] ifaces = _interfaces_ip("{0}\n{1}".format( salt.utils.stringutils.to_str(cmd1), salt.utils.stringutils.to_str(cmd2))) elif ifconfig_path: cmd = subprocess.Popen( '{0} -a'.format(ifconfig_path), shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT).communicate()[0] ifaces = _interfaces_ifconfig(salt.utils.stringutils.to_str(cmd)) return ifaces def _netbsd_interfaces_ifconfig(out): ''' Uses ifconfig to return a dictionary of interfaces with various information about each (up/down state, ip address, netmask, and hwaddr) ''' ret = dict() piface = re.compile(r'^([^\s:]+)') pmac = re.compile('.*?address: ([0-9a-f:]+)') pip = re.compile(r'.*?inet [^\d]*(.*?)/([\d]*)\s') pip6 = re.compile(r'.*?inet6 ([0-9a-f:]+)%([a-zA-Z0-9]*)/([\d]*)\s') pupdown = re.compile('UP') pbcast = re.compile(r'.*?broadcast ([\d\.]+)') groups = re.compile('\r?\n(?=\\S)').split(out) for group in groups: data = dict() iface = '' updown = False for line in group.splitlines(): miface = piface.match(line) mmac = pmac.match(line) mip = pip.match(line) mip6 = pip6.match(line) mupdown = pupdown.search(line) if miface: iface = miface.group(1) if mmac: data['hwaddr'] = mmac.group(1) if mip: if 'inet' not in data: data['inet'] = list() addr_obj = dict() addr_obj['address'] = mip.group(1) mmask = mip.group(2) if mip.group(2): addr_obj['netmask'] = cidr_to_ipv4_netmask(mip.group(2)) mbcast = pbcast.match(line) if mbcast: addr_obj['broadcast'] = mbcast.group(1) data['inet'].append(addr_obj) if mupdown: updown = True if mip6: if 'inet6' not in data: data['inet6'] = list() addr_obj = dict() addr_obj['address'] = mip6.group(1) mmask6 = mip6.group(3) addr_obj['scope'] = mip6.group(2) addr_obj['prefixlen'] = mip6.group(3) data['inet6'].append(addr_obj) data['up'] = updown ret[iface] = data del data return ret def netbsd_interfaces(): ''' Obtain interface information for NetBSD >= 8 where the ifconfig output diverged from other BSD variants (Netmask is now part of the address) ''' # NetBSD versions prior to 8.0 can still use linux_interfaces() if LooseVersion(os.uname()[2]) < LooseVersion('8.0'): return linux_interfaces() ifconfig_path = salt.utils.path.which('ifconfig') cmd = subprocess.Popen( '{0} -a'.format(ifconfig_path), shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT).communicate()[0] return _netbsd_interfaces_ifconfig(salt.utils.stringutils.to_str(cmd)) def _interfaces_ipconfig(out): ''' Returns a dictionary of interfaces with various information about each (up/down state, ip address, netmask, and hwaddr) NOTE: This is not used by any function and may be able to be removed in the future. ''' ifaces = dict() iface = None adapter_iface_regex = re.compile(r'adapter (\S.+):$') for line in out.splitlines(): if not line: continue # TODO what does Windows call Infiniband and 10/40gige adapters if line.startswith('Ethernet'): iface = ifaces[adapter_iface_regex.search(line).group(1)] iface['up'] = True addr = None continue if iface: key, val = line.split(',', 1) key = key.strip(' .') val = val.strip() if addr and key == 'Subnet Mask': addr['netmask'] = val elif key in ('IP Address', 'IPv4 Address'): if 'inet' not in iface: iface['inet'] = list() addr = {'address': val.rstrip('(Preferred)'), 'netmask': None, 'broadcast': None} # TODO find the broadcast iface['inet'].append(addr) elif 'IPv6 Address' in key: if 'inet6' not in iface: iface['inet'] = list() # XXX What is the prefixlen!? addr = {'address': val.rstrip('(Preferred)'), 'prefixlen': None} iface['inet6'].append(addr) elif key == 'Physical Address': iface['hwaddr'] = val elif key == 'Media State': # XXX seen used for tunnel adaptors # might be useful iface['up'] = (val != 'Media disconnected') def win_interfaces(): ''' Obtain interface information for Windows systems ''' with salt.utils.winapi.Com(): c = wmi.WMI() ifaces = {} for iface in c.Win32_NetworkAdapterConfiguration(IPEnabled=1): ifaces[iface.Description] = dict() if iface.MACAddress: ifaces[iface.Description]['hwaddr'] = iface.MACAddress if iface.IPEnabled: ifaces[iface.Description]['up'] = True for ip in iface.IPAddress: if '.' in ip: if 'inet' not in ifaces[iface.Description]: ifaces[iface.Description]['inet'] = [] item = {'address': ip, 'label': iface.Description} if iface.DefaultIPGateway: broadcast = next((i for i in iface.DefaultIPGateway if '.' in i), '') if broadcast: item['broadcast'] = broadcast if iface.IPSubnet: netmask = next((i for i in iface.IPSubnet if '.' in i), '') if netmask: item['netmask'] = netmask ifaces[iface.Description]['inet'].append(item) if ':' in ip: if 'inet6' not in ifaces[iface.Description]: ifaces[iface.Description]['inet6'] = [] item = {'address': ip} if iface.DefaultIPGateway: broadcast = next((i for i in iface.DefaultIPGateway if ':' in i), '') if broadcast: item['broadcast'] = broadcast if iface.IPSubnet: netmask = next((i for i in iface.IPSubnet if ':' in i), '') if netmask: item['netmask'] = netmask ifaces[iface.Description]['inet6'].append(item) else: ifaces[iface.Description]['up'] = False return ifaces def interfaces(): ''' Return a dictionary of information about all the interfaces on the minion ''' if salt.utils.platform.is_windows(): return win_interfaces() elif salt.utils.platform.is_netbsd(): return netbsd_interfaces() else: return linux_interfaces() def get_net_start(ipaddr, netmask): ''' Return the address of the network ''' net = ipaddress.ip_network('{0}/{1}'.format(ipaddr, netmask), strict=False) return six.text_type(net.network_address) def get_net_size(mask): ''' Turns an IPv4 netmask into it's corresponding prefix length (255.255.255.0 -> 24 as in 192.168.1.10/24). ''' binary_str = '' for octet in mask.split('.'): binary_str += bin(int(octet))[2:].zfill(8) return len(binary_str.rstrip('0')) def calc_net(ipaddr, netmask=None): ''' Takes IP (CIDR notation supported) and optionally netmask and returns the network in CIDR-notation. (The IP can be any IP inside the subnet) ''' if netmask is not None: ipaddr = '{0}/{1}'.format(ipaddr, netmask) return six.text_type(ipaddress.ip_network(ipaddr, strict=False)) def _ipv4_to_bits(ipaddr): ''' Accepts an IPv4 dotted quad and returns a string representing its binary counterpart ''' return ''.join([bin(int(x))[2:].rjust(8, '0') for x in ipaddr.split('.')]) def _get_iface_info(iface): ''' If `iface` is available, return interface info and no error, otherwise return no info and log and return an error ''' iface_info = interfaces() if iface in iface_info.keys(): return iface_info, False else: error_msg = ('Interface "{0}" not in available interfaces: "{1}"' ''.format(iface, '", "'.join(iface_info.keys()))) log.error(error_msg) return None, error_msg def _hw_addr_aix(iface): ''' Return the hardware address (a.k.a. MAC address) for a given interface on AIX MAC address not available in through interfaces ''' cmd = subprocess.Popen( 'entstat -d {0} | grep \'Hardware Address\''.format(iface), shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT).communicate()[0] if cmd: comps = cmd.split(' ') if len(comps) == 3: mac_addr = comps[2].strip('\'').strip() return mac_addr error_msg = ('Interface "{0}" either not available or does not contain a hardware address'.format(iface)) log.error(error_msg) return error_msg def hw_addr(iface): ''' Return the hardware address (a.k.a. MAC address) for a given interface .. versionchanged:: 2016.11.4 Added support for AIX ''' if salt.utils.platform.is_aix(): return _hw_addr_aix iface_info, error = _get_iface_info(iface) if error is False: return iface_info.get(iface, {}).get('hwaddr', '') else: return error def interface(iface): ''' Return the details of `iface` or an error if it does not exist ''' iface_info, error = _get_iface_info(iface) if error is False: return iface_info.get(iface, {}).get('inet', '') else: return error def interface_ip(iface): ''' Return `iface` IPv4 addr or an error if `iface` does not exist ''' iface_info, error = _get_iface_info(iface) if error is False: inet = iface_info.get(iface, {}).get('inet', None) return inet[0].get('address', '') if inet else '' else: return error def _subnets(proto='inet', interfaces_=None): ''' Returns a list of subnets to which the host belongs ''' if interfaces_ is None: ifaces = interfaces() elif isinstance(interfaces_, list): ifaces = {} for key, value in six.iteritems(interfaces()): if key in interfaces_: ifaces[key] = value else: ifaces = {interfaces_: interfaces().get(interfaces_, {})} ret = set() if proto == 'inet': subnet = 'netmask' dflt_cidr = 32 elif proto == 'inet6': subnet = 'prefixlen' dflt_cidr = 128 else: log.error('Invalid proto %s calling subnets()', proto) return for ip_info in six.itervalues(ifaces): addrs = ip_info.get(proto, []) addrs.extend([addr for addr in ip_info.get('secondary', []) if addr.get('type') == proto]) for intf in addrs: if subnet in intf: intf = ipaddress.ip_interface('{0}/{1}'.format(intf['address'], intf[subnet])) else: intf = ipaddress.ip_interface('{0}/{1}'.format(intf['address'], dflt_cidr)) if not intf.is_loopback: ret.add(intf.network) return [six.text_type(net) for net in sorted(ret)] def subnets(interfaces=None): ''' Returns a list of IPv4 subnets to which the host belongs ''' return _subnets('inet', interfaces_=interfaces) def subnets6(): ''' Returns a list of IPv6 subnets to which the host belongs ''' return _subnets('inet6') def in_subnet(cidr, addr=None): ''' Returns True if host or (any of) addrs is within specified subnet, otherwise False ''' try: cidr = ipaddress.ip_network(cidr) except ValueError: log.error('Invalid CIDR \'%s\'', cidr) return False if addr is None: addr = ip_addrs() addr.extend(ip_addrs6()) elif not isinstance(addr, (list, tuple)): addr = (addr,) return any(ipaddress.ip_address(item) in cidr for item in addr) def _ip_addrs(interface=None, include_loopback=False, interface_data=None, proto='inet'): ''' Return the full list of IP adresses matching the criteria proto = inet|inet6 ''' ret = set() ifaces = interface_data \ if isinstance(interface_data, dict) \ else interfaces() if interface is None: target_ifaces = ifaces else: target_ifaces = dict([(k, v) for k, v in six.iteritems(ifaces) if k == interface]) if not target_ifaces: log.error('Interface %s not found.', interface) for ip_info in six.itervalues(target_ifaces): addrs = ip_info.get(proto, []) addrs.extend([addr for addr in ip_info.get('secondary', []) if addr.get('type') == proto]) for addr in addrs: addr = ipaddress.ip_address(addr.get('address')) if not addr.is_loopback or include_loopback: ret.add(addr) return [six.text_type(addr) for addr in sorted(ret)] def ip_addrs(interface=None, include_loopback=False, interface_data=None): ''' Returns a list of IPv4 addresses assigned to the host. 127.0.0.1 is ignored, unless 'include_loopback=True' is indicated. If 'interface' is provided, then only IP addresses from that interface will be returned. ''' return _ip_addrs(interface, include_loopback, interface_data, 'inet') def ip_addrs6(interface=None, include_loopback=False, interface_data=None): ''' Returns a list of IPv6 addresses assigned to the host. ::1 is ignored, unless 'include_loopback=True' is indicated. If 'interface' is provided, then only IP addresses from that interface will be returned. ''' return _ip_addrs(interface, include_loopback, interface_data, 'inet6') def hex2ip(hex_ip, invert=False): ''' Convert a hex string to an ip, if a failure occurs the original hex is returned. If 'invert=True' assume that ip from /proc/net/<proto> ''' if len(hex_ip) == 32: # ipv6 ip = [] for i in range(0, 32, 8): ip_part = hex_ip[i:i + 8] ip_part = [ip_part[x:x + 2] for x in range(0, 8, 2)] if invert: ip.append("{0[3]}{0[2]}:{0[1]}{0[0]}".format(ip_part)) else: ip.append("{0[0]}{0[1]}:{0[2]}{0[3]}".format(ip_part)) try: address = ipaddress.IPv6Address(":".join(ip)) if address.ipv4_mapped: return str(address.ipv4_mapped) else: return address.compressed except ipaddress.AddressValueError as ex: log.error('hex2ip - ipv6 address error: %s', ex) return hex_ip try: hip = int(hex_ip, 16) except ValueError: return hex_ip if invert: return '{3}.{2}.{1}.{0}'.format(hip >> 24 & 255, hip >> 16 & 255, hip >> 8 & 255, hip & 255) return '{0}.{1}.{2}.{3}'.format(hip >> 24 & 255, hip >> 16 & 255, hip >> 8 & 255, hip & 255) def mac2eui64(mac, prefix=None): ''' Convert a MAC address to a EUI64 identifier or, with prefix provided, a full IPv6 address ''' # http://tools.ietf.org/html/rfc4291#section-2.5.1 eui64 = re.sub(r'[.:-]', '', mac).lower() eui64 = eui64[0:6] + 'fffe' + eui64[6:] eui64 = hex(int(eui64[0:2], 16) | 2)[2:].zfill(2) + eui64[2:] if prefix is None: return ':'.join(re.findall(r'.{4}', eui64)) else: try: net = ipaddress.ip_network(prefix, strict=False) euil = int('0x{0}'.format(eui64), 16) return '{0}/{1}'.format(net[euil], net.prefixlen) except Exception: return def active_tcp(): ''' Return a dict describing all active tcp connections as quickly as possible ''' ret = {} for statf in ['/proc/net/tcp', '/proc/net/tcp6']: if os.path.isfile(statf): with salt.utils.files.fopen(statf, 'rb') as fp_: for line in fp_: line = salt.utils.stringutils.to_unicode(line) if line.strip().startswith('sl'): continue iret = _parse_tcp_line(line) sl = next(iter(iret)) if iret[sl]['state'] == 1: # 1 is ESTABLISHED del iret[sl]['state'] ret[len(ret)] = iret[sl] return ret def local_port_tcp(port): ''' Return a set of remote ip addrs attached to the specified local port ''' ret = _remotes_on(port, 'local_port') return ret def remote_port_tcp(port): ''' Return a set of ip addrs the current host is connected to on given port ''' ret = _remotes_on(port, 'remote_port') return ret def _remotes_on(port, which_end): ''' Return a set of ip addrs active tcp connections ''' port = int(port) ret = _netlink_tool_remote_on(port, which_end) if ret is not None: return ret ret = set() proc_available = False for statf in ['/proc/net/tcp', '/proc/net/tcp6']: if os.path.isfile(statf): proc_available = True with salt.utils.files.fopen(statf, 'r') as fp_: for line in fp_: line = salt.utils.stringutils.to_unicode(line) if line.strip().startswith('sl'): continue iret = _parse_tcp_line(line) sl = next(iter(iret)) if iret[sl][which_end] == port and iret[sl]['state'] == 1: # 1 is ESTABLISHED ret.add(iret[sl]['remote_addr']) if not proc_available: # Fallback to use OS specific tools if salt.utils.platform.is_sunos(): return _sunos_remotes_on(port, which_end) if salt.utils.platform.is_freebsd(): return _freebsd_remotes_on(port, which_end) if salt.utils.platform.is_netbsd(): return _netbsd_remotes_on(port, which_end) if salt.utils.platform.is_openbsd(): return _openbsd_remotes_on(port, which_end) if salt.utils.platform.is_windows(): return _windows_remotes_on(port, which_end) if salt.utils.platform.is_aix(): return _aix_remotes_on(port, which_end) return _linux_remotes_on(port, which_end) return ret def _parse_tcp_line(line): ''' Parse a single line from the contents of /proc/net/tcp or /proc/net/tcp6 ''' ret = {} comps = line.strip().split() sl = comps[0].rstrip(':') ret[sl] = {} l_addr, l_port = comps[1].split(':') r_addr, r_port = comps[2].split(':') ret[sl]['local_addr'] = hex2ip(l_addr, True) ret[sl]['local_port'] = int(l_port, 16) ret[sl]['remote_addr'] = hex2ip(r_addr, True) ret[sl]['remote_port'] = int(r_port, 16) ret[sl]['state'] = int(comps[3], 16) return ret def _netlink_tool_remote_on(port, which_end): ''' Returns set of ipv4 host addresses of remote established connections on local or remote tcp port. Parses output of shell 'ss' to get connections [root@salt-master ~]# ss -ant State Recv-Q Send-Q Local Address:Port Peer Address:Port LISTEN 0 511 *:80 *:* LISTEN 0 128 *:22 *:* ESTAB 0 0 127.0.0.1:56726 127.0.0.1:4505 ''' remotes = set() valid = False try: data = subprocess.check_output(['ss', '-ant']) # pylint: disable=minimum-python-version except subprocess.CalledProcessError: log.error('Failed ss') raise except OSError: # not command "No such file or directory" return None lines = salt.utils.stringutils.to_str(data).split('\n') for line in lines: if 'Address:Port' in line: # ss tools may not be valid valid = True continue elif 'ESTAB' not in line: continue chunks = line.split() local_host, local_port = chunks[3].split(':', 1) remote_host, remote_port = chunks[4].split(':', 1) if which_end == 'remote_port' and int(remote_port) != port: continue if which_end == 'local_port' and int(local_port) != port: continue remotes.add(remote_host) if valid is False: remotes = None return remotes def _sunos_remotes_on(port, which_end): ''' SunOS specific helper function. Returns set of ipv4 host addresses of remote established connections on local or remote tcp port. Parses output of shell 'netstat' to get connections [root@salt-master ~]# netstat -f inet -n TCP: IPv4 Local Address Remote Address Swind Send-Q Rwind Recv-Q State -------------------- -------------------- ----- ------ ----- ------ ----------- 10.0.0.101.4505 10.0.0.1.45329 1064800 0 1055864 0 ESTABLISHED 10.0.0.101.4505 10.0.0.100.50798 1064800 0 1055864 0 ESTABLISHED ''' remotes = set() try: data = subprocess.check_output(['netstat', '-f', 'inet', '-n']) # pylint: disable=minimum-python-version except subprocess.CalledProcessError: log.error('Failed netstat') raise lines = salt.utils.stringutils.to_str(data).split('\n') for line in lines: if 'ESTABLISHED' not in line: continue chunks = line.split() local_host, local_port = chunks[0].rsplit('.', 1) remote_host, remote_port = chunks[1].rsplit('.', 1) if which_end == 'remote_port' and int(remote_port) != port: continue if which_end == 'local_port' and int(local_port) != port: continue remotes.add(remote_host) return remotes def _freebsd_remotes_on(port, which_end): ''' Returns set of ipv4 host addresses of remote established connections on local tcp port port. Parses output of shell 'sockstat' (FreeBSD) to get connections $ sudo sockstat -4 USER COMMAND PID FD PROTO LOCAL ADDRESS FOREIGN ADDRESS root python2.7 1456 29 tcp4 *:4505 *:* root python2.7 1445 17 tcp4 *:4506 *:* root python2.7 1294 14 tcp4 127.0.0.1:11813 127.0.0.1:4505 root python2.7 1294 41 tcp4 127.0.0.1:61115 127.0.0.1:4506 $ sudo sockstat -4 -c -p 4506 USER COMMAND PID FD PROTO LOCAL ADDRESS FOREIGN ADDRESS root python2.7 1294 41 tcp4 127.0.0.1:61115 127.0.0.1:4506 ''' port = int(port) remotes = set() try: cmd = salt.utils.args.shlex_split('sockstat -4 -c -p {0}'.format(port)) data = subprocess.check_output(cmd) # pylint: disable=minimum-python-version except subprocess.CalledProcessError as ex: log.error('Failed "sockstat" with returncode = %s', ex.returncode) raise lines = salt.utils.stringutils.to_str(data).split('\n') for line in lines: chunks = line.split() if not chunks: continue # ['root', 'python2.7', '1456', '37', 'tcp4', # '127.0.0.1:4505-', '127.0.0.1:55703'] # print chunks if 'COMMAND' in chunks[1]: continue # ignore header if len(chunks) < 2: continue # sockstat -4 -c -p 4506 does this with high PIDs: # USER COMMAND PID FD PROTO LOCAL ADDRESS FOREIGN ADDRESS # salt-master python2.781106 35 tcp4 192.168.12.34:4506 192.168.12.45:60143 local = chunks[-2] remote = chunks[-1] lhost, lport = local.split(':') rhost, rport = remote.split(':') if which_end == 'local' and int(lport) != port: # ignore if local port not port continue if which_end == 'remote' and int(rport) != port: # ignore if remote port not port continue remotes.add(rhost) return remotes def _netbsd_remotes_on(port, which_end): ''' Returns set of ipv4 host addresses of remote established connections on local tcp port port. Parses output of shell 'sockstat' (NetBSD) to get connections $ sudo sockstat -4 -n USER COMMAND PID FD PROTO LOCAL ADDRESS FOREIGN ADDRESS root python2.7 1456 29 tcp *.4505 *.* root python2.7 1445 17 tcp *.4506 *.* root python2.7 1294 14 tcp 127.0.0.1.11813 127.0.0.1.4505 root python2.7 1294 41 tcp 127.0.0.1.61115 127.0.0.1.4506 $ sudo sockstat -4 -c -n -p 4506 USER COMMAND PID FD PROTO LOCAL ADDRESS FOREIGN ADDRESS root python2.7 1294 41 tcp 127.0.0.1.61115 127.0.0.1.4506 ''' port = int(port) remotes = set() try: cmd = salt.utils.args.shlex_split('sockstat -4 -c -n -p {0}'.format(port)) data = subprocess.check_output(cmd) # pylint: disable=minimum-python-version except subprocess.CalledProcessError as ex: log.error('Failed "sockstat" with returncode = %s', ex.returncode) raise lines = salt.utils.stringutils.to_str(data).split('\n') for line in lines: chunks = line.split() if not chunks: continue # ['root', 'python2.7', '1456', '37', 'tcp', # '127.0.0.1.4505-', '127.0.0.1.55703'] # print chunks if 'COMMAND' in chunks[1]: continue # ignore header if len(chunks) < 2: continue local = chunks[5].split('.') lport = local.pop() lhost = '.'.join(local) remote = chunks[6].split('.') rport = remote.pop() rhost = '.'.join(remote) if which_end == 'local' and int(lport) != port: # ignore if local port not port continue if which_end == 'remote' and int(rport) != port: # ignore if remote port not port continue remotes.add(rhost) return remotes def _openbsd_remotes_on(port, which_end): ''' OpenBSD specific helper function. Returns set of ipv4 host addresses of remote established connections on local or remote tcp port. Parses output of shell 'netstat' to get connections $ netstat -nf inet Active Internet connections Proto Recv-Q Send-Q Local Address Foreign Address (state) tcp 0 0 10.0.0.101.4505 10.0.0.1.45329 ESTABLISHED tcp 0 0 10.0.0.101.4505 10.0.0.100.50798 ESTABLISHED ''' remotes = set() try: data = subprocess.check_output(['netstat', '-nf', 'inet']) # pylint: disable=minimum-python-version except subprocess.CalledProcessError: log.error('Failed netstat') raise lines = data.split('\n') for line in lines: if 'ESTABLISHED' not in line: continue chunks = line.split() local_host, local_port = chunks[3].rsplit('.', 1) remote_host, remote_port = chunks[4].rsplit('.', 1) if which_end == 'remote_port' and int(remote_port) != port: continue if which_end == 'local_port' and int(local_port) != port: continue remotes.add(remote_host) return remotes def _windows_remotes_on(port, which_end): r''' Windows specific helper function. Returns set of ipv4 host addresses of remote established connections on local or remote tcp port. Parses output of shell 'netstat' to get connections C:\>netstat -n Active Connections Proto Local Address Foreign Address State TCP 10.2.33.17:3007 130.164.12.233:10123 ESTABLISHED TCP 10.2.33.17:3389 130.164.30.5:10378 ESTABLISHED ''' remotes = set() try: data = subprocess.check_output(['netstat', '-n']) # pylint: disable=minimum-python-version except subprocess.CalledProcessError: log.error('Failed netstat') raise lines = salt.utils.stringutils.to_str(data).split('\n') for line in lines: if 'ESTABLISHED' not in line: continue chunks = line.split() local_host, local_port = chunks[1].rsplit(':', 1) remote_host, remote_port = chunks[2].rsplit(':', 1) if which_end == 'remote_port' and int(remote_port) != port: continue if which_end == 'local_port' and int(local_port) != port: continue remotes.add(remote_host) return remotes def _linux_remotes_on(port, which_end): ''' Linux specific helper function. Returns set of ip host addresses of remote established connections on local tcp port port. Parses output of shell 'lsof' to get connections $ sudo lsof -iTCP:4505 -n COMMAND PID USER FD TYPE DEVICE SIZE/OFF NODE NAME Python 9971 root 35u IPv4 0x18a8464a29ca329d 0t0 TCP *:4505 (LISTEN) Python 9971 root 37u IPv4 0x18a8464a29b2b29d 0t0 TCP 127.0.0.1:4505->127.0.0.1:55703 (ESTABLISHED) Python 10152 root 22u IPv4 0x18a8464a29c8cab5 0t0 TCP 127.0.0.1:55703->127.0.0.1:4505 (ESTABLISHED) Python 10153 root 22u IPv4 0x18a8464a29c8cab5 0t0 TCP [fe80::249a]:4505->[fe80::150]:59367 (ESTABLISHED) ''' remotes = set() try: data = subprocess.check_output( ['lsof', '-iTCP:{0:d}'.format(port), '-n', '-P'] # pylint: disable=minimum-python-version ) except subprocess.CalledProcessError as ex: if ex.returncode == 1: # Lsof return 1 if any error was detected, including the failure # to locate Internet addresses, and it is not an error in this case. log.warning('"lsof" returncode = 1, likely no active TCP sessions.') return remotes log.error('Failed "lsof" with returncode = %s', ex.returncode) raise lines = salt.utils.stringutils.to_str(data).split('\n') for line in lines: chunks = line.split() if not chunks: continue # ['Python', '9971', 'root', '37u', 'IPv4', '0x18a8464a29b2b29d', '0t0', # 'TCP', '127.0.0.1:4505->127.0.0.1:55703', '(ESTABLISHED)'] # print chunks if 'COMMAND' in chunks[0]: continue # ignore header if 'ESTABLISHED' not in chunks[-1]: continue # ignore if not ESTABLISHED # '127.0.0.1:4505->127.0.0.1:55703' local, remote = chunks[8].split('->') _, lport = local.rsplit(':', 1) rhost, rport = remote.rsplit(':', 1) if which_end == 'remote_port' and int(rport) != port: continue if which_end == 'local_port' and int(lport) != port: continue remotes.add(rhost.strip("[]")) return remotes def _aix_remotes_on(port, which_end): ''' AIX specific helper function. Returns set of ipv4 host addresses of remote established connections on local or remote tcp port. Parses output of shell 'netstat' to get connections root@la68pp002_pub:/opt/salt/lib/python2.7/site-packages/salt/modules# netstat -f inet -n Active Internet connections Proto Recv-Q Send-Q Local Address Foreign Address (state) tcp4 0 0 172.29.149.95.50093 209.41.78.13.4505 ESTABLISHED tcp4 0 0 127.0.0.1.9514 *.* LISTEN tcp4 0 0 127.0.0.1.9515 *.* LISTEN tcp4 0 0 127.0.0.1.199 127.0.0.1.32779 ESTABLISHED tcp4 0 0 127.0.0.1.32779 127.0.0.1.199 ESTABLISHED tcp4 0 40 172.29.149.95.22 172.29.96.83.41022 ESTABLISHED tcp4 0 0 172.29.149.95.22 172.29.96.83.41032 ESTABLISHED tcp4 0 0 127.0.0.1.32771 127.0.0.1.32775 ESTABLISHED tcp 0 0 127.0.0.1.32775 127.0.0.1.32771 ESTABLISHED tcp4 0 0 127.0.0.1.32771 127.0.0.1.32776 ESTABLISHED tcp 0 0 127.0.0.1.32776 127.0.0.1.32771 ESTABLISHED tcp4 0 0 127.0.0.1.32771 127.0.0.1.32777 ESTABLISHED tcp 0 0 127.0.0.1.32777 127.0.0.1.32771 ESTABLISHED tcp4 0 0 127.0.0.1.32771 127.0.0.1.32778 ESTABLISHED tcp 0 0 127.0.0.1.32778 127.0.0.1.32771 ESTABLISHED ''' remotes = set() try: data = subprocess.check_output(['netstat', '-f', 'inet', '-n']) # pylint: disable=minimum-python-version except subprocess.CalledProcessError: log.error('Failed netstat') raise lines = salt.utils.stringutils.to_str(data).split('\n') for line in lines: if 'ESTABLISHED' not in line: continue chunks = line.split() local_host, local_port = chunks[3].rsplit('.', 1) remote_host, remote_port = chunks[4].rsplit('.', 1) if which_end == 'remote_port' and int(remote_port) != port: continue if which_end == 'local_port' and int(local_port) != port: continue remotes.add(remote_host) return remotes @jinja_filter('gen_mac') def gen_mac(prefix='AC:DE:48'): ''' Generates a MAC address with the defined OUI prefix. Common prefixes: - ``00:16:3E`` -- Xen - ``00:18:51`` -- OpenVZ - ``00:50:56`` -- VMware (manually generated) - ``52:54:00`` -- QEMU/KVM - ``AC:DE:48`` -- PRIVATE References: - http://standards.ieee.org/develop/regauth/oui/oui.txt - https://www.wireshark.org/tools/oui-lookup.html - https://en.wikipedia.org/wiki/MAC_address ''' return '{0}:{1:02X}:{2:02X}:{3:02X}'.format(prefix, random.randint(0, 0xff), random.randint(0, 0xff), random.randint(0, 0xff)) @jinja_filter('mac_str_to_bytes') def mac_str_to_bytes(mac_str): ''' Convert a MAC address string into bytes. Works with or without separators: b1 = mac_str_to_bytes('08:00:27:13:69:77') b2 = mac_str_to_bytes('080027136977') assert b1 == b2 assert isinstance(b1, bytes) ''' if len(mac_str) == 12: pass elif len(mac_str) == 17: sep = mac_str[2] mac_str = mac_str.replace(sep, '') else: raise ValueError('Invalid MAC address') chars = (int(mac_str[s:s+2], 16) for s in range(0, 12, 2)) return bytes(chars) if six.PY3 else b''.join(chr(x) for x in chars) def refresh_dns(): ''' issue #21397: force glibc to re-read resolv.conf ''' try: res_init() except NameError: # Exception raised loading the library, thus res_init is not defined pass @jinja_filter('connection_check') def connection_check(addr, port=80, safe=False, ipv6=None): ''' Provides a convenient alias for the dns_check filter. ''' return dns_check(addr, port, safe, ipv6) @jinja_filter('dns_check') def dns_check(addr, port=80, safe=False, ipv6=None, attempt_connect=True): ''' Return the ip resolved by dns, but do not exit on failure, only raise an exception. Obeys system preference for IPv4/6 address resolution - this can be overridden by the ipv6 flag. Tries to connect to the address before considering it useful. If no address can be reached, the first one resolved is used as a fallback. ''' error = False lookup = addr seen_ipv6 = False family = socket.AF_INET6 if ipv6 else socket.AF_INET if ipv6 is False else socket.AF_UNSPEC hostnames = [] try: refresh_dns() hostnames = socket.getaddrinfo(addr, port, family, socket.SOCK_STREAM) except TypeError: err = ('Attempt to resolve address \'{0}\' failed. Invalid or unresolveable address').format(lookup) raise SaltSystemExit(code=42, msg=err) except socket.error: error = True # If ipv6 is set to True, attempt another lookup using the IPv4 family, # just in case we're attempting to lookup an IPv4 IP # as an IPv6 hostname. if error and ipv6: try: refresh_dns() hostnames = socket.getaddrinfo(addr, port, socket.AF_INET, socket.SOCK_STREAM) except TypeError: err = ('Attempt to resolve address \'{0}\' failed. Invalid or unresolveable address').format(lookup) raise SaltSystemExit(code=42, msg=err) except socket.error: error = True try: if not hostnames: error = True else: resolved = False candidates = [] for h in hostnames: # Input is IP address, passed through unchanged, just return it if h[4][0] == addr: resolved = salt.utils.zeromq.ip_bracket(addr) break candidate_addr = salt.utils.zeromq.ip_bracket(h[4][0]) # sometimes /etc/hosts contains ::1 localhost if not ipv6 and candidate_addr == '[::1]': continue candidates.append(candidate_addr) if attempt_connect: try: s = socket.socket(h[0], socket.SOCK_STREAM) s.settimeout(2) s.connect((candidate_addr.strip('[]'), h[4][1])) s.close() resolved = candidate_addr break except socket.error: pass if not resolved: if candidates: resolved = candidates[0] else: error = True except TypeError: err = ('Attempt to resolve address \'{0}\' failed. Invalid or unresolveable address').format(lookup) raise SaltSystemExit(code=42, msg=err) except socket.error: error = True if error: err = ('DNS lookup or connection check of \'{0}\' failed.').format(addr) if safe: if salt.log.is_console_configured(): # If logging is not configured it also means that either # the master or minion instance calling this hasn't even # started running log.error(err) raise SaltClientError() raise SaltSystemExit(code=42, msg=err) return resolved def parse_host_port(host_port): """ Takes a string argument specifying host or host:port. Returns a (hostname, port) or (ip_address, port) tuple. If no port is given, the second (port) element of the returned tuple will be None. host:port argument, for example, is accepted in the forms of: - hostname - hostname:1234 - hostname.domain.tld - hostname.domain.tld:5678 - [1234::5]:5678 - 1234::5 - 10.11.12.13:4567 - 10.11.12.13 """ host, port = None, None # default _s_ = host_port[:] if _s_[0] == "[": if "]" in host_port: host, _s_ = _s_.lstrip("[").rsplit("]", 1) host = ipaddress.IPv6Address(host).compressed if _s_[0] == ":": port = int(_s_.lstrip(":")) else: if len(_s_) > 1: raise ValueError('found ambiguous "{}" port in "{}"'.format(_s_, host_port)) else: if _s_.count(":") == 1: host, _hostport_separator_, port = _s_.partition(":") try: port = int(port) except ValueError as _e_: log.error('host_port "%s" port value "%s" is not an integer.', host_port, port) raise _e_ else: host = _s_ try: if not isinstance(host, ipaddress._BaseAddress): host_ip = ipaddress.ip_address(host).compressed host = host_ip except ValueError: log.debug('"%s" Not an IP address? Assuming it is a hostname.', host) if host != sanitize_host(host): log.error('bad hostname: "%s"', host) raise ValueError('bad hostname: "{}"'.format(host)) return host, port def is_fqdn(hostname): """ Verify if hostname conforms to be a FQDN. :param hostname: text string with the name of the host :return: bool, True if hostname is correct FQDN, False otherwise """ compliant = re.compile(r"(?!-)[A-Z\d\-\_]{1,63}(?<!-)$", re.IGNORECASE) return "." in hostname and len(hostname) < 0xff and all(compliant.match(x) for x in hostname.rstrip(".").split("."))
saltstack/salt
salt/utils/network.py
linux_interfaces
python
def linux_interfaces(): ''' Obtain interface information for *NIX/BSD variants ''' ifaces = dict() ip_path = salt.utils.path.which('ip') ifconfig_path = None if ip_path else salt.utils.path.which('ifconfig') if ip_path: cmd1 = subprocess.Popen( '{0} link show'.format(ip_path), shell=True, close_fds=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT).communicate()[0] cmd2 = subprocess.Popen( '{0} addr show'.format(ip_path), shell=True, close_fds=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT).communicate()[0] ifaces = _interfaces_ip("{0}\n{1}".format( salt.utils.stringutils.to_str(cmd1), salt.utils.stringutils.to_str(cmd2))) elif ifconfig_path: cmd = subprocess.Popen( '{0} -a'.format(ifconfig_path), shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT).communicate()[0] ifaces = _interfaces_ifconfig(salt.utils.stringutils.to_str(cmd)) return ifaces
Obtain interface information for *NIX/BSD variants
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/network.py#L844-L874
[ "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 _interfaces_ip(out):\n '''\n Uses ip to return a dictionary of interfaces with various information about\n each (up/down state, ip address, netmask, and hwaddr)\n '''\n ret = dict()\n\n def parse_network(value, cols):\n '''\n Return a tuple of ip, netmask, broadcast\n based on the current set of cols\n '''\n brd = None\n scope = None\n if '/' in value: # we have a CIDR in this address\n ip, cidr = value.split('/') # pylint: disable=C0103\n else:\n ip = value # pylint: disable=C0103\n cidr = 32\n\n if type_ == 'inet':\n mask = cidr_to_ipv4_netmask(int(cidr))\n if 'brd' in cols:\n brd = cols[cols.index('brd') + 1]\n elif type_ == 'inet6':\n mask = cidr\n if 'scope' in cols:\n scope = cols[cols.index('scope') + 1]\n return (ip, mask, brd, scope)\n\n groups = re.compile('\\r?\\n\\\\d').split(out)\n for group in groups:\n iface = None\n data = dict()\n\n for line in group.splitlines():\n if ' ' not in line:\n continue\n match = re.match(r'^\\d*:\\s+([\\w.\\-]+)(?:@)?([\\w.\\-]+)?:\\s+<(.+)>', line)\n if match:\n iface, parent, attrs = match.groups()\n if 'UP' in attrs.split(','):\n data['up'] = True\n else:\n data['up'] = False\n if parent:\n data['parent'] = parent\n continue\n\n cols = line.split()\n if len(cols) >= 2:\n type_, value = tuple(cols[0:2])\n iflabel = cols[-1:][0]\n if type_ in ('inet', 'inet6'):\n if 'secondary' not in cols:\n ipaddr, netmask, broadcast, scope = parse_network(value, cols)\n if type_ == 'inet':\n if 'inet' not in data:\n data['inet'] = list()\n addr_obj = dict()\n addr_obj['address'] = ipaddr\n addr_obj['netmask'] = netmask\n addr_obj['broadcast'] = broadcast\n addr_obj['label'] = iflabel\n data['inet'].append(addr_obj)\n elif type_ == 'inet6':\n if 'inet6' not in data:\n data['inet6'] = list()\n addr_obj = dict()\n addr_obj['address'] = ipaddr\n addr_obj['prefixlen'] = netmask\n addr_obj['scope'] = scope\n data['inet6'].append(addr_obj)\n else:\n if 'secondary' not in data:\n data['secondary'] = list()\n ip_, mask, brd, scp = parse_network(value, cols)\n data['secondary'].append({\n 'type': type_,\n 'address': ip_,\n 'netmask': mask,\n 'broadcast': brd,\n 'label': iflabel,\n })\n del ip_, mask, brd, scp\n elif type_.startswith('link'):\n data['hwaddr'] = value\n if iface:\n ret[iface] = data\n del iface, data\n return ret\n", "def _interfaces_ifconfig(out):\n '''\n Uses ifconfig to return a dictionary of interfaces with various information\n about each (up/down state, ip address, netmask, and hwaddr)\n '''\n ret = dict()\n\n piface = re.compile(r'^([^\\s:]+)')\n pmac = re.compile('.*?(?:HWaddr|ether|address:|lladdr) ([0-9a-fA-F:]+)')\n if salt.utils.platform.is_sunos():\n pip = re.compile(r'.*?(?:inet\\s+)([0-9]+\\.[0-9]+\\.[0-9]+\\.[0-9]+)(.*)')\n pip6 = re.compile('.*?(?:inet6 )([0-9a-fA-F:]+)')\n pmask6 = re.compile(r'.*?(?:inet6 [0-9a-fA-F:]+/(\\d+)).*')\n else:\n pip = re.compile(r'.*?(?:inet addr:|inet [^\\d]*)(.*?)\\s')\n pip6 = re.compile('.*?(?:inet6 addr: (.*?)/|inet6 )([0-9a-fA-F:]+)')\n pmask6 = re.compile(r'.*?(?:inet6 addr: [0-9a-fA-F:]+/(\\d+)|prefixlen (\\d+))(?: Scope:([a-zA-Z]+)| scopeid (0x[0-9a-fA-F]))?')\n pmask = re.compile(r'.*?(?:Mask:|netmask )(?:((?:0x)?[0-9a-fA-F]{8})|([\\d\\.]+))')\n pupdown = re.compile('UP')\n pbcast = re.compile(r'.*?(?:Bcast:|broadcast )([\\d\\.]+)')\n\n groups = re.compile('\\r?\\n(?=\\\\S)').split(out)\n for group in groups:\n data = dict()\n iface = ''\n updown = False\n for line in group.splitlines():\n miface = piface.match(line)\n mmac = pmac.match(line)\n mip = pip.match(line)\n mip6 = pip6.match(line)\n mupdown = pupdown.search(line)\n if miface:\n iface = miface.group(1)\n if mmac:\n data['hwaddr'] = mmac.group(1)\n if salt.utils.platform.is_sunos():\n expand_mac = []\n for chunk in data['hwaddr'].split(':'):\n expand_mac.append('0{0}'.format(chunk) if len(chunk) < 2 else '{0}'.format(chunk))\n data['hwaddr'] = ':'.join(expand_mac)\n if mip:\n if 'inet' not in data:\n data['inet'] = list()\n addr_obj = dict()\n addr_obj['address'] = mip.group(1)\n mmask = pmask.match(line)\n if mmask:\n if mmask.group(1):\n mmask = _number_of_set_bits_to_ipv4_netmask(\n int(mmask.group(1), 16))\n else:\n mmask = mmask.group(2)\n addr_obj['netmask'] = mmask\n mbcast = pbcast.match(line)\n if mbcast:\n addr_obj['broadcast'] = mbcast.group(1)\n data['inet'].append(addr_obj)\n if mupdown:\n updown = True\n if mip6:\n if 'inet6' not in data:\n data['inet6'] = list()\n addr_obj = dict()\n addr_obj['address'] = mip6.group(1) or mip6.group(2)\n mmask6 = pmask6.match(line)\n if mmask6:\n addr_obj['prefixlen'] = mmask6.group(1) or mmask6.group(2)\n if not salt.utils.platform.is_sunos():\n ipv6scope = mmask6.group(3) or mmask6.group(4)\n addr_obj['scope'] = ipv6scope.lower() if ipv6scope is not None else ipv6scope\n # SunOS sometimes has ::/0 as inet6 addr when using addrconf\n if not salt.utils.platform.is_sunos() \\\n or addr_obj['address'] != '::' \\\n and addr_obj['prefixlen'] != 0:\n data['inet6'].append(addr_obj)\n data['up'] = updown\n if iface in ret:\n # SunOS optimization, where interfaces occur twice in 'ifconfig -a'\n # output with the same name: for ipv4 and then for ipv6 addr family.\n # Every instance has it's own 'UP' status and we assume that ipv4\n # status determines global interface status.\n #\n # merge items with higher priority for older values\n # after that merge the inet and inet6 sub items for both\n ret[iface] = dict(list(data.items()) + list(ret[iface].items()))\n if 'inet' in data:\n ret[iface]['inet'].extend(x for x in data['inet'] if x not in ret[iface]['inet'])\n if 'inet6' in data:\n ret[iface]['inet6'].extend(x for x in data['inet6'] if x not in ret[iface]['inet6'])\n else:\n ret[iface] = data\n del data\n return ret\n" ]
# -*- coding: utf-8 -*- ''' Define some generic socket functions for network modules ''' # Import python libs from __future__ import absolute_import, unicode_literals, print_function import itertools import os import re import types import socket import logging import platform import random import subprocess from string import ascii_letters, digits # Import 3rd-party libs from salt.ext import six from salt.ext.six.moves import range # pylint: disable=import-error,redefined-builtin # Attempt to import wmi try: import wmi import salt.utils.winapi except ImportError: pass # Import salt libs import salt.utils.args import salt.utils.files import salt.utils.path import salt.utils.platform import salt.utils.stringutils import salt.utils.zeromq from salt._compat import ipaddress from salt.exceptions import SaltClientError, SaltSystemExit from salt.utils.decorators.jinja import jinja_filter from salt.utils.versions import LooseVersion # inet_pton does not exist in Windows, this is a workaround if salt.utils.platform.is_windows(): from salt.ext import win_inet_pton # pylint: disable=unused-import log = logging.getLogger(__name__) try: import ctypes import ctypes.util libc = ctypes.cdll.LoadLibrary(ctypes.util.find_library("c")) res_init = libc.__res_init except (ImportError, OSError, AttributeError, TypeError): pass # pylint: disable=C0103 def sanitize_host(host): ''' Sanitize host string. https://tools.ietf.org/html/rfc1123#section-2.1 ''' RFC952_characters = ascii_letters + digits + ".-" return "".join([c for c in host[0:255] if c in RFC952_characters]) def isportopen(host, port): ''' Return status of a port ''' if not 1 <= int(port) <= 65535: return False sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) out = sock.connect_ex((sanitize_host(host), int(port))) return out def host_to_ips(host): ''' Returns a list of IP addresses of a given hostname or None if not found. ''' ips = [] try: for family, socktype, proto, canonname, sockaddr in socket.getaddrinfo( host, 0, socket.AF_UNSPEC, socket.SOCK_STREAM): if family == socket.AF_INET: ip, port = sockaddr elif family == socket.AF_INET6: ip, port, flow_info, scope_id = sockaddr ips.append(ip) if not ips: ips = None except Exception: ips = None return ips def _generate_minion_id(): ''' Get list of possible host names and convention names. :return: ''' # There are three types of hostnames: # 1. Network names. How host is accessed from the network. # 2. Host aliases. They might be not available in all the network or only locally (/etc/hosts) # 3. Convention names, an internal nodename. class DistinctList(list): ''' List, which allows one to append only distinct objects. Needs to work on Python 2.6, because of collections.OrderedDict only since 2.7 version. Override 'filter()' for custom filtering. ''' localhost_matchers = [r'localhost.*', r'ip6-.*', r'127[.]\d', r'0\.0\.0\.0', r'::1.*', r'ipv6-.*', r'fe00::.*', r'fe02::.*', r'1.0.0.*.ip6.arpa'] def append(self, p_object): if p_object and p_object not in self and not self.filter(p_object): super(DistinctList, self).append(p_object) return self def extend(self, iterable): for obj in iterable: self.append(obj) return self def filter(self, element): 'Returns True if element needs to be filtered' for rgx in self.localhost_matchers: if re.match(rgx, element): return True def first(self): return self and self[0] or None hostname = socket.gethostname() hosts = DistinctList().append( salt.utils.stringutils.to_unicode(socket.getfqdn(salt.utils.stringutils.to_bytes(hostname))) ).append(platform.node()).append(hostname) if not hosts: try: for a_nfo in socket.getaddrinfo(hosts.first() or 'localhost', None, socket.AF_INET, socket.SOCK_RAW, socket.IPPROTO_IP, socket.AI_CANONNAME): if len(a_nfo) > 3: hosts.append(a_nfo[3]) except socket.gaierror: log.warning('Cannot resolve address %s info via socket: %s', hosts.first() or 'localhost (N/A)', socket.gaierror) # Universal method for everywhere (Linux, Slowlaris, Windows etc) for f_name in ('/etc/hostname', '/etc/nodename', '/etc/hosts', r'{win}\system32\drivers\etc\hosts'.format(win=os.getenv('WINDIR'))): try: with salt.utils.files.fopen(f_name) as f_hdl: for line in f_hdl: line = salt.utils.stringutils.to_unicode(line) hst = line.strip().split('#')[0].strip().split() if hst: if hst[0][:4] in ('127.', '::1') or len(hst) == 1: hosts.extend(hst) except IOError: pass # include public and private ipaddresses return hosts.extend([addr for addr in ip_addrs() if not ipaddress.ip_address(addr).is_loopback]) def generate_minion_id(): ''' Return only first element of the hostname from all possible list. :return: ''' try: ret = salt.utils.stringutils.to_unicode(_generate_minion_id().first()) except TypeError: ret = None return ret or 'localhost' def get_socket(addr, type=socket.SOCK_STREAM, proto=0): ''' Return a socket object for the addr IP-version agnostic ''' version = ipaddress.ip_address(addr).version if version == 4: family = socket.AF_INET elif version == 6: family = socket.AF_INET6 return socket.socket(family, type, proto) def get_fqhostname(): ''' Returns the fully qualified hostname ''' # try getaddrinfo() fqdn = None try: addrinfo = socket.getaddrinfo( socket.gethostname(), 0, socket.AF_UNSPEC, socket.SOCK_STREAM, socket.SOL_TCP, socket.AI_CANONNAME ) for info in addrinfo: # info struct [family, socktype, proto, canonname, sockaddr] # On Windows `canonname` can be an empty string # This can cause the function to return `None` if len(info) > 3 and info[3]: fqdn = info[3] break except socket.gaierror: pass # NOTE: this used to log.error() but it was later disabled except socket.error as err: log.debug('socket.getaddrinfo() failure while finding fqdn: %s', err) if fqdn is None: fqdn = socket.getfqdn() return fqdn def ip_to_host(ip): ''' Returns the hostname of a given IP ''' try: hostname, aliaslist, ipaddrlist = socket.gethostbyaddr(ip) except Exception as exc: log.debug('salt.utils.network.ip_to_host(%r) failed: %s', ip, exc) hostname = None return hostname # pylint: enable=C0103 def is_reachable_host(entity_name): ''' Returns a bool telling if the entity name is a reachable host (IPv4/IPv6/FQDN/etc). :param hostname: :return: ''' try: assert type(socket.getaddrinfo(entity_name, 0, 0, 0, 0)) == list ret = True except socket.gaierror: ret = False return ret def is_ip(ip): ''' Returns a bool telling if the passed IP is a valid IPv4 or IPv6 address. ''' return is_ipv4(ip) or is_ipv6(ip) def is_ipv4(ip): ''' Returns a bool telling if the value passed to it was a valid IPv4 address ''' try: return ipaddress.ip_address(ip).version == 4 except ValueError: return False def is_ipv6(ip): ''' Returns a bool telling if the value passed to it was a valid IPv6 address ''' try: return ipaddress.ip_address(ip).version == 6 except ValueError: return False def is_subnet(cidr): ''' Returns a bool telling if the passed string is an IPv4 or IPv6 subnet ''' return is_ipv4_subnet(cidr) or is_ipv6_subnet(cidr) def is_ipv4_subnet(cidr): ''' Returns a bool telling if the passed string is an IPv4 subnet ''' try: return '/' in cidr and bool(ipaddress.IPv4Network(cidr)) except Exception: return False def is_ipv6_subnet(cidr): ''' Returns a bool telling if the passed string is an IPv6 subnet ''' try: return '/' in cidr and bool(ipaddress.IPv6Network(cidr)) except Exception: return False @jinja_filter('is_ip') def is_ip_filter(ip, options=None): ''' Returns a bool telling if the passed IP is a valid IPv4 or IPv6 address. ''' return is_ipv4_filter(ip, options=options) or is_ipv6_filter(ip, options=options) def _ip_options_global(ip_obj, version): return not ip_obj.is_private def _ip_options_multicast(ip_obj, version): return ip_obj.is_multicast def _ip_options_loopback(ip_obj, version): return ip_obj.is_loopback def _ip_options_link_local(ip_obj, version): return ip_obj.is_link_local def _ip_options_private(ip_obj, version): return ip_obj.is_private def _ip_options_reserved(ip_obj, version): return ip_obj.is_reserved def _ip_options_site_local(ip_obj, version): if version == 6: return ip_obj.is_site_local return False def _ip_options_unspecified(ip_obj, version): return ip_obj.is_unspecified def _ip_options(ip_obj, version, options=None): # will process and IP options options_fun_map = { 'global': _ip_options_global, 'link-local': _ip_options_link_local, 'linklocal': _ip_options_link_local, 'll': _ip_options_link_local, 'link_local': _ip_options_link_local, 'loopback': _ip_options_loopback, 'lo': _ip_options_loopback, 'multicast': _ip_options_multicast, 'private': _ip_options_private, 'public': _ip_options_global, 'reserved': _ip_options_reserved, 'site-local': _ip_options_site_local, 'sl': _ip_options_site_local, 'site_local': _ip_options_site_local, 'unspecified': _ip_options_unspecified } if not options: return six.text_type(ip_obj) # IP version already checked options_list = [option.strip() for option in options.split(',')] for option, fun in options_fun_map.items(): if option in options_list: fun_res = fun(ip_obj, version) if not fun_res: return None # stop at first failed test # else continue return six.text_type(ip_obj) def _is_ipv(ip, version, options=None): if not version: version = 4 if version not in (4, 6): return None try: ip_obj = ipaddress.ip_address(ip) except ValueError: # maybe it is an IP network try: ip_obj = ipaddress.ip_interface(ip) except ValueError: # nope, still not :( return None if not ip_obj.version == version: return None # has the right version, let's move on return _ip_options(ip_obj, version, options=options) @jinja_filter('is_ipv4') def is_ipv4_filter(ip, options=None): ''' Returns a bool telling if the value passed to it was a valid IPv4 address. ip The IP address. net: False Consider IP addresses followed by netmask. options CSV of options regarding the nature of the IP address. E.g.: loopback, multicast, private etc. ''' _is_ipv4 = _is_ipv(ip, 4, options=options) return isinstance(_is_ipv4, six.string_types) @jinja_filter('is_ipv6') def is_ipv6_filter(ip, options=None): ''' Returns a bool telling if the value passed to it was a valid IPv6 address. ip The IP address. net: False Consider IP addresses followed by netmask. options CSV of options regarding the nature of the IP address. E.g.: loopback, multicast, private etc. ''' _is_ipv6 = _is_ipv(ip, 6, options=options) return isinstance(_is_ipv6, six.string_types) def _ipv_filter(value, version, options=None): if version not in (4, 6): return if isinstance(value, (six.string_types, six.text_type, six.binary_type)): return _is_ipv(value, version, options=options) # calls is_ipv4 or is_ipv6 for `value` elif isinstance(value, (list, tuple, types.GeneratorType)): # calls is_ipv4 or is_ipv6 for each element in the list # os it filters and returns only those elements having the desired IP version return [ _is_ipv(addr, version, options=options) for addr in value if _is_ipv(addr, version, options=options) is not None ] return None @jinja_filter('ipv4') def ipv4(value, options=None): ''' Filters a list and returns IPv4 values only. ''' return _ipv_filter(value, 4, options=options) @jinja_filter('ipv6') def ipv6(value, options=None): ''' Filters a list and returns IPv6 values only. ''' return _ipv_filter(value, 6, options=options) @jinja_filter('ipaddr') def ipaddr(value, options=None): ''' Filters and returns only valid IP objects. ''' ipv4_obj = ipv4(value, options=options) ipv6_obj = ipv6(value, options=options) if ipv4_obj is None or ipv6_obj is None: # an IP address can be either IPv4 either IPv6 # therefofe if the value passed as arg is not a list, at least one of the calls above will return None # if one of them is none, means that we should return only one of them return ipv4_obj or ipv6_obj # one of them else: return ipv4_obj + ipv6_obj # extend lists def _filter_ipaddr(value, options, version=None): ipaddr_filter_out = None if version: if version == 4: ipaddr_filter_out = ipv4(value, options) elif version == 6: ipaddr_filter_out = ipv6(value, options) else: ipaddr_filter_out = ipaddr(value, options) if not ipaddr_filter_out: return if not isinstance(ipaddr_filter_out, (list, tuple, types.GeneratorType)): ipaddr_filter_out = [ipaddr_filter_out] return ipaddr_filter_out @jinja_filter('ip_host') def ip_host(value, options=None, version=None): ''' Returns the interfaces IP address, e.g.: 192.168.0.1/28. ''' ipaddr_filter_out = _filter_ipaddr(value, options=options, version=version) if not ipaddr_filter_out: return if not isinstance(value, (list, tuple, types.GeneratorType)): return six.text_type(ipaddress.ip_interface(ipaddr_filter_out[0])) return [six.text_type(ipaddress.ip_interface(ip_a)) for ip_a in ipaddr_filter_out] def _network_hosts(ip_addr_entry): return [ six.text_type(host) for host in ipaddress.ip_network(ip_addr_entry, strict=False).hosts() ] @jinja_filter('network_hosts') def network_hosts(value, options=None, version=None): ''' Return the list of hosts within a network. .. note:: When running this command with a large IPv6 network, the command will take a long time to gather all of the hosts. ''' ipaddr_filter_out = _filter_ipaddr(value, options=options, version=version) if not ipaddr_filter_out: return if not isinstance(value, (list, tuple, types.GeneratorType)): return _network_hosts(ipaddr_filter_out[0]) return [ _network_hosts(ip_a) for ip_a in ipaddr_filter_out ] def _network_size(ip_addr_entry): return ipaddress.ip_network(ip_addr_entry, strict=False).num_addresses @jinja_filter('network_size') def network_size(value, options=None, version=None): ''' Get the size of a network. ''' ipaddr_filter_out = _filter_ipaddr(value, options=options, version=version) if not ipaddr_filter_out: return if not isinstance(value, (list, tuple, types.GeneratorType)): return _network_size(ipaddr_filter_out[0]) return [ _network_size(ip_a) for ip_a in ipaddr_filter_out ] def natural_ipv4_netmask(ip, fmt='prefixlen'): ''' Returns the "natural" mask of an IPv4 address ''' bits = _ipv4_to_bits(ip) if bits.startswith('11'): mask = '24' elif bits.startswith('1'): mask = '16' else: mask = '8' if fmt == 'netmask': return cidr_to_ipv4_netmask(mask) else: return '/' + mask def rpad_ipv4_network(ip): ''' Returns an IP network address padded with zeros. Ex: '192.168.3' -> '192.168.3.0' '10.209' -> '10.209.0.0' ''' return '.'.join(itertools.islice(itertools.chain(ip.split('.'), '0000'), 0, 4)) def cidr_to_ipv4_netmask(cidr_bits): ''' Returns an IPv4 netmask ''' try: cidr_bits = int(cidr_bits) if not 1 <= cidr_bits <= 32: return '' except ValueError: return '' netmask = '' for idx in range(4): if idx: netmask += '.' if cidr_bits >= 8: netmask += '255' cidr_bits -= 8 else: netmask += '{0:d}'.format(256 - (2 ** (8 - cidr_bits))) cidr_bits = 0 return netmask def _number_of_set_bits_to_ipv4_netmask(set_bits): # pylint: disable=C0103 ''' Returns an IPv4 netmask from the integer representation of that mask. Ex. 0xffffff00 -> '255.255.255.0' ''' return cidr_to_ipv4_netmask(_number_of_set_bits(set_bits)) # pylint: disable=C0103 def _number_of_set_bits(x): ''' Returns the number of bits that are set in a 32bit int ''' # Taken from http://stackoverflow.com/a/4912729. Many thanks! x -= (x >> 1) & 0x55555555 x = ((x >> 2) & 0x33333333) + (x & 0x33333333) x = ((x >> 4) + x) & 0x0f0f0f0f x += x >> 8 x += x >> 16 return x & 0x0000003f # pylint: enable=C0103 def _interfaces_ip(out): ''' Uses ip to return a dictionary of interfaces with various information about each (up/down state, ip address, netmask, and hwaddr) ''' ret = dict() def parse_network(value, cols): ''' Return a tuple of ip, netmask, broadcast based on the current set of cols ''' brd = None scope = None if '/' in value: # we have a CIDR in this address ip, cidr = value.split('/') # pylint: disable=C0103 else: ip = value # pylint: disable=C0103 cidr = 32 if type_ == 'inet': mask = cidr_to_ipv4_netmask(int(cidr)) if 'brd' in cols: brd = cols[cols.index('brd') + 1] elif type_ == 'inet6': mask = cidr if 'scope' in cols: scope = cols[cols.index('scope') + 1] return (ip, mask, brd, scope) groups = re.compile('\r?\n\\d').split(out) for group in groups: iface = None data = dict() for line in group.splitlines(): if ' ' not in line: continue match = re.match(r'^\d*:\s+([\w.\-]+)(?:@)?([\w.\-]+)?:\s+<(.+)>', line) if match: iface, parent, attrs = match.groups() if 'UP' in attrs.split(','): data['up'] = True else: data['up'] = False if parent: data['parent'] = parent continue cols = line.split() if len(cols) >= 2: type_, value = tuple(cols[0:2]) iflabel = cols[-1:][0] if type_ in ('inet', 'inet6'): if 'secondary' not in cols: ipaddr, netmask, broadcast, scope = parse_network(value, cols) if type_ == 'inet': if 'inet' not in data: data['inet'] = list() addr_obj = dict() addr_obj['address'] = ipaddr addr_obj['netmask'] = netmask addr_obj['broadcast'] = broadcast addr_obj['label'] = iflabel data['inet'].append(addr_obj) elif type_ == 'inet6': if 'inet6' not in data: data['inet6'] = list() addr_obj = dict() addr_obj['address'] = ipaddr addr_obj['prefixlen'] = netmask addr_obj['scope'] = scope data['inet6'].append(addr_obj) else: if 'secondary' not in data: data['secondary'] = list() ip_, mask, brd, scp = parse_network(value, cols) data['secondary'].append({ 'type': type_, 'address': ip_, 'netmask': mask, 'broadcast': brd, 'label': iflabel, }) del ip_, mask, brd, scp elif type_.startswith('link'): data['hwaddr'] = value if iface: ret[iface] = data del iface, data return ret def _interfaces_ifconfig(out): ''' Uses ifconfig to return a dictionary of interfaces with various information about each (up/down state, ip address, netmask, and hwaddr) ''' ret = dict() piface = re.compile(r'^([^\s:]+)') pmac = re.compile('.*?(?:HWaddr|ether|address:|lladdr) ([0-9a-fA-F:]+)') if salt.utils.platform.is_sunos(): pip = re.compile(r'.*?(?:inet\s+)([0-9]+\.[0-9]+\.[0-9]+\.[0-9]+)(.*)') pip6 = re.compile('.*?(?:inet6 )([0-9a-fA-F:]+)') pmask6 = re.compile(r'.*?(?:inet6 [0-9a-fA-F:]+/(\d+)).*') else: pip = re.compile(r'.*?(?:inet addr:|inet [^\d]*)(.*?)\s') pip6 = re.compile('.*?(?:inet6 addr: (.*?)/|inet6 )([0-9a-fA-F:]+)') pmask6 = re.compile(r'.*?(?:inet6 addr: [0-9a-fA-F:]+/(\d+)|prefixlen (\d+))(?: Scope:([a-zA-Z]+)| scopeid (0x[0-9a-fA-F]))?') pmask = re.compile(r'.*?(?:Mask:|netmask )(?:((?:0x)?[0-9a-fA-F]{8})|([\d\.]+))') pupdown = re.compile('UP') pbcast = re.compile(r'.*?(?:Bcast:|broadcast )([\d\.]+)') groups = re.compile('\r?\n(?=\\S)').split(out) for group in groups: data = dict() iface = '' updown = False for line in group.splitlines(): miface = piface.match(line) mmac = pmac.match(line) mip = pip.match(line) mip6 = pip6.match(line) mupdown = pupdown.search(line) if miface: iface = miface.group(1) if mmac: data['hwaddr'] = mmac.group(1) if salt.utils.platform.is_sunos(): expand_mac = [] for chunk in data['hwaddr'].split(':'): expand_mac.append('0{0}'.format(chunk) if len(chunk) < 2 else '{0}'.format(chunk)) data['hwaddr'] = ':'.join(expand_mac) if mip: if 'inet' not in data: data['inet'] = list() addr_obj = dict() addr_obj['address'] = mip.group(1) mmask = pmask.match(line) if mmask: if mmask.group(1): mmask = _number_of_set_bits_to_ipv4_netmask( int(mmask.group(1), 16)) else: mmask = mmask.group(2) addr_obj['netmask'] = mmask mbcast = pbcast.match(line) if mbcast: addr_obj['broadcast'] = mbcast.group(1) data['inet'].append(addr_obj) if mupdown: updown = True if mip6: if 'inet6' not in data: data['inet6'] = list() addr_obj = dict() addr_obj['address'] = mip6.group(1) or mip6.group(2) mmask6 = pmask6.match(line) if mmask6: addr_obj['prefixlen'] = mmask6.group(1) or mmask6.group(2) if not salt.utils.platform.is_sunos(): ipv6scope = mmask6.group(3) or mmask6.group(4) addr_obj['scope'] = ipv6scope.lower() if ipv6scope is not None else ipv6scope # SunOS sometimes has ::/0 as inet6 addr when using addrconf if not salt.utils.platform.is_sunos() \ or addr_obj['address'] != '::' \ and addr_obj['prefixlen'] != 0: data['inet6'].append(addr_obj) data['up'] = updown if iface in ret: # SunOS optimization, where interfaces occur twice in 'ifconfig -a' # output with the same name: for ipv4 and then for ipv6 addr family. # Every instance has it's own 'UP' status and we assume that ipv4 # status determines global interface status. # # merge items with higher priority for older values # after that merge the inet and inet6 sub items for both ret[iface] = dict(list(data.items()) + list(ret[iface].items())) if 'inet' in data: ret[iface]['inet'].extend(x for x in data['inet'] if x not in ret[iface]['inet']) if 'inet6' in data: ret[iface]['inet6'].extend(x for x in data['inet6'] if x not in ret[iface]['inet6']) else: ret[iface] = data del data return ret def _netbsd_interfaces_ifconfig(out): ''' Uses ifconfig to return a dictionary of interfaces with various information about each (up/down state, ip address, netmask, and hwaddr) ''' ret = dict() piface = re.compile(r'^([^\s:]+)') pmac = re.compile('.*?address: ([0-9a-f:]+)') pip = re.compile(r'.*?inet [^\d]*(.*?)/([\d]*)\s') pip6 = re.compile(r'.*?inet6 ([0-9a-f:]+)%([a-zA-Z0-9]*)/([\d]*)\s') pupdown = re.compile('UP') pbcast = re.compile(r'.*?broadcast ([\d\.]+)') groups = re.compile('\r?\n(?=\\S)').split(out) for group in groups: data = dict() iface = '' updown = False for line in group.splitlines(): miface = piface.match(line) mmac = pmac.match(line) mip = pip.match(line) mip6 = pip6.match(line) mupdown = pupdown.search(line) if miface: iface = miface.group(1) if mmac: data['hwaddr'] = mmac.group(1) if mip: if 'inet' not in data: data['inet'] = list() addr_obj = dict() addr_obj['address'] = mip.group(1) mmask = mip.group(2) if mip.group(2): addr_obj['netmask'] = cidr_to_ipv4_netmask(mip.group(2)) mbcast = pbcast.match(line) if mbcast: addr_obj['broadcast'] = mbcast.group(1) data['inet'].append(addr_obj) if mupdown: updown = True if mip6: if 'inet6' not in data: data['inet6'] = list() addr_obj = dict() addr_obj['address'] = mip6.group(1) mmask6 = mip6.group(3) addr_obj['scope'] = mip6.group(2) addr_obj['prefixlen'] = mip6.group(3) data['inet6'].append(addr_obj) data['up'] = updown ret[iface] = data del data return ret def netbsd_interfaces(): ''' Obtain interface information for NetBSD >= 8 where the ifconfig output diverged from other BSD variants (Netmask is now part of the address) ''' # NetBSD versions prior to 8.0 can still use linux_interfaces() if LooseVersion(os.uname()[2]) < LooseVersion('8.0'): return linux_interfaces() ifconfig_path = salt.utils.path.which('ifconfig') cmd = subprocess.Popen( '{0} -a'.format(ifconfig_path), shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT).communicate()[0] return _netbsd_interfaces_ifconfig(salt.utils.stringutils.to_str(cmd)) def _interfaces_ipconfig(out): ''' Returns a dictionary of interfaces with various information about each (up/down state, ip address, netmask, and hwaddr) NOTE: This is not used by any function and may be able to be removed in the future. ''' ifaces = dict() iface = None adapter_iface_regex = re.compile(r'adapter (\S.+):$') for line in out.splitlines(): if not line: continue # TODO what does Windows call Infiniband and 10/40gige adapters if line.startswith('Ethernet'): iface = ifaces[adapter_iface_regex.search(line).group(1)] iface['up'] = True addr = None continue if iface: key, val = line.split(',', 1) key = key.strip(' .') val = val.strip() if addr and key == 'Subnet Mask': addr['netmask'] = val elif key in ('IP Address', 'IPv4 Address'): if 'inet' not in iface: iface['inet'] = list() addr = {'address': val.rstrip('(Preferred)'), 'netmask': None, 'broadcast': None} # TODO find the broadcast iface['inet'].append(addr) elif 'IPv6 Address' in key: if 'inet6' not in iface: iface['inet'] = list() # XXX What is the prefixlen!? addr = {'address': val.rstrip('(Preferred)'), 'prefixlen': None} iface['inet6'].append(addr) elif key == 'Physical Address': iface['hwaddr'] = val elif key == 'Media State': # XXX seen used for tunnel adaptors # might be useful iface['up'] = (val != 'Media disconnected') def win_interfaces(): ''' Obtain interface information for Windows systems ''' with salt.utils.winapi.Com(): c = wmi.WMI() ifaces = {} for iface in c.Win32_NetworkAdapterConfiguration(IPEnabled=1): ifaces[iface.Description] = dict() if iface.MACAddress: ifaces[iface.Description]['hwaddr'] = iface.MACAddress if iface.IPEnabled: ifaces[iface.Description]['up'] = True for ip in iface.IPAddress: if '.' in ip: if 'inet' not in ifaces[iface.Description]: ifaces[iface.Description]['inet'] = [] item = {'address': ip, 'label': iface.Description} if iface.DefaultIPGateway: broadcast = next((i for i in iface.DefaultIPGateway if '.' in i), '') if broadcast: item['broadcast'] = broadcast if iface.IPSubnet: netmask = next((i for i in iface.IPSubnet if '.' in i), '') if netmask: item['netmask'] = netmask ifaces[iface.Description]['inet'].append(item) if ':' in ip: if 'inet6' not in ifaces[iface.Description]: ifaces[iface.Description]['inet6'] = [] item = {'address': ip} if iface.DefaultIPGateway: broadcast = next((i for i in iface.DefaultIPGateway if ':' in i), '') if broadcast: item['broadcast'] = broadcast if iface.IPSubnet: netmask = next((i for i in iface.IPSubnet if ':' in i), '') if netmask: item['netmask'] = netmask ifaces[iface.Description]['inet6'].append(item) else: ifaces[iface.Description]['up'] = False return ifaces def interfaces(): ''' Return a dictionary of information about all the interfaces on the minion ''' if salt.utils.platform.is_windows(): return win_interfaces() elif salt.utils.platform.is_netbsd(): return netbsd_interfaces() else: return linux_interfaces() def get_net_start(ipaddr, netmask): ''' Return the address of the network ''' net = ipaddress.ip_network('{0}/{1}'.format(ipaddr, netmask), strict=False) return six.text_type(net.network_address) def get_net_size(mask): ''' Turns an IPv4 netmask into it's corresponding prefix length (255.255.255.0 -> 24 as in 192.168.1.10/24). ''' binary_str = '' for octet in mask.split('.'): binary_str += bin(int(octet))[2:].zfill(8) return len(binary_str.rstrip('0')) def calc_net(ipaddr, netmask=None): ''' Takes IP (CIDR notation supported) and optionally netmask and returns the network in CIDR-notation. (The IP can be any IP inside the subnet) ''' if netmask is not None: ipaddr = '{0}/{1}'.format(ipaddr, netmask) return six.text_type(ipaddress.ip_network(ipaddr, strict=False)) def _ipv4_to_bits(ipaddr): ''' Accepts an IPv4 dotted quad and returns a string representing its binary counterpart ''' return ''.join([bin(int(x))[2:].rjust(8, '0') for x in ipaddr.split('.')]) def _get_iface_info(iface): ''' If `iface` is available, return interface info and no error, otherwise return no info and log and return an error ''' iface_info = interfaces() if iface in iface_info.keys(): return iface_info, False else: error_msg = ('Interface "{0}" not in available interfaces: "{1}"' ''.format(iface, '", "'.join(iface_info.keys()))) log.error(error_msg) return None, error_msg def _hw_addr_aix(iface): ''' Return the hardware address (a.k.a. MAC address) for a given interface on AIX MAC address not available in through interfaces ''' cmd = subprocess.Popen( 'entstat -d {0} | grep \'Hardware Address\''.format(iface), shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT).communicate()[0] if cmd: comps = cmd.split(' ') if len(comps) == 3: mac_addr = comps[2].strip('\'').strip() return mac_addr error_msg = ('Interface "{0}" either not available or does not contain a hardware address'.format(iface)) log.error(error_msg) return error_msg def hw_addr(iface): ''' Return the hardware address (a.k.a. MAC address) for a given interface .. versionchanged:: 2016.11.4 Added support for AIX ''' if salt.utils.platform.is_aix(): return _hw_addr_aix iface_info, error = _get_iface_info(iface) if error is False: return iface_info.get(iface, {}).get('hwaddr', '') else: return error def interface(iface): ''' Return the details of `iface` or an error if it does not exist ''' iface_info, error = _get_iface_info(iface) if error is False: return iface_info.get(iface, {}).get('inet', '') else: return error def interface_ip(iface): ''' Return `iface` IPv4 addr or an error if `iface` does not exist ''' iface_info, error = _get_iface_info(iface) if error is False: inet = iface_info.get(iface, {}).get('inet', None) return inet[0].get('address', '') if inet else '' else: return error def _subnets(proto='inet', interfaces_=None): ''' Returns a list of subnets to which the host belongs ''' if interfaces_ is None: ifaces = interfaces() elif isinstance(interfaces_, list): ifaces = {} for key, value in six.iteritems(interfaces()): if key in interfaces_: ifaces[key] = value else: ifaces = {interfaces_: interfaces().get(interfaces_, {})} ret = set() if proto == 'inet': subnet = 'netmask' dflt_cidr = 32 elif proto == 'inet6': subnet = 'prefixlen' dflt_cidr = 128 else: log.error('Invalid proto %s calling subnets()', proto) return for ip_info in six.itervalues(ifaces): addrs = ip_info.get(proto, []) addrs.extend([addr for addr in ip_info.get('secondary', []) if addr.get('type') == proto]) for intf in addrs: if subnet in intf: intf = ipaddress.ip_interface('{0}/{1}'.format(intf['address'], intf[subnet])) else: intf = ipaddress.ip_interface('{0}/{1}'.format(intf['address'], dflt_cidr)) if not intf.is_loopback: ret.add(intf.network) return [six.text_type(net) for net in sorted(ret)] def subnets(interfaces=None): ''' Returns a list of IPv4 subnets to which the host belongs ''' return _subnets('inet', interfaces_=interfaces) def subnets6(): ''' Returns a list of IPv6 subnets to which the host belongs ''' return _subnets('inet6') def in_subnet(cidr, addr=None): ''' Returns True if host or (any of) addrs is within specified subnet, otherwise False ''' try: cidr = ipaddress.ip_network(cidr) except ValueError: log.error('Invalid CIDR \'%s\'', cidr) return False if addr is None: addr = ip_addrs() addr.extend(ip_addrs6()) elif not isinstance(addr, (list, tuple)): addr = (addr,) return any(ipaddress.ip_address(item) in cidr for item in addr) def _ip_addrs(interface=None, include_loopback=False, interface_data=None, proto='inet'): ''' Return the full list of IP adresses matching the criteria proto = inet|inet6 ''' ret = set() ifaces = interface_data \ if isinstance(interface_data, dict) \ else interfaces() if interface is None: target_ifaces = ifaces else: target_ifaces = dict([(k, v) for k, v in six.iteritems(ifaces) if k == interface]) if not target_ifaces: log.error('Interface %s not found.', interface) for ip_info in six.itervalues(target_ifaces): addrs = ip_info.get(proto, []) addrs.extend([addr for addr in ip_info.get('secondary', []) if addr.get('type') == proto]) for addr in addrs: addr = ipaddress.ip_address(addr.get('address')) if not addr.is_loopback or include_loopback: ret.add(addr) return [six.text_type(addr) for addr in sorted(ret)] def ip_addrs(interface=None, include_loopback=False, interface_data=None): ''' Returns a list of IPv4 addresses assigned to the host. 127.0.0.1 is ignored, unless 'include_loopback=True' is indicated. If 'interface' is provided, then only IP addresses from that interface will be returned. ''' return _ip_addrs(interface, include_loopback, interface_data, 'inet') def ip_addrs6(interface=None, include_loopback=False, interface_data=None): ''' Returns a list of IPv6 addresses assigned to the host. ::1 is ignored, unless 'include_loopback=True' is indicated. If 'interface' is provided, then only IP addresses from that interface will be returned. ''' return _ip_addrs(interface, include_loopback, interface_data, 'inet6') def hex2ip(hex_ip, invert=False): ''' Convert a hex string to an ip, if a failure occurs the original hex is returned. If 'invert=True' assume that ip from /proc/net/<proto> ''' if len(hex_ip) == 32: # ipv6 ip = [] for i in range(0, 32, 8): ip_part = hex_ip[i:i + 8] ip_part = [ip_part[x:x + 2] for x in range(0, 8, 2)] if invert: ip.append("{0[3]}{0[2]}:{0[1]}{0[0]}".format(ip_part)) else: ip.append("{0[0]}{0[1]}:{0[2]}{0[3]}".format(ip_part)) try: address = ipaddress.IPv6Address(":".join(ip)) if address.ipv4_mapped: return str(address.ipv4_mapped) else: return address.compressed except ipaddress.AddressValueError as ex: log.error('hex2ip - ipv6 address error: %s', ex) return hex_ip try: hip = int(hex_ip, 16) except ValueError: return hex_ip if invert: return '{3}.{2}.{1}.{0}'.format(hip >> 24 & 255, hip >> 16 & 255, hip >> 8 & 255, hip & 255) return '{0}.{1}.{2}.{3}'.format(hip >> 24 & 255, hip >> 16 & 255, hip >> 8 & 255, hip & 255) def mac2eui64(mac, prefix=None): ''' Convert a MAC address to a EUI64 identifier or, with prefix provided, a full IPv6 address ''' # http://tools.ietf.org/html/rfc4291#section-2.5.1 eui64 = re.sub(r'[.:-]', '', mac).lower() eui64 = eui64[0:6] + 'fffe' + eui64[6:] eui64 = hex(int(eui64[0:2], 16) | 2)[2:].zfill(2) + eui64[2:] if prefix is None: return ':'.join(re.findall(r'.{4}', eui64)) else: try: net = ipaddress.ip_network(prefix, strict=False) euil = int('0x{0}'.format(eui64), 16) return '{0}/{1}'.format(net[euil], net.prefixlen) except Exception: return def active_tcp(): ''' Return a dict describing all active tcp connections as quickly as possible ''' ret = {} for statf in ['/proc/net/tcp', '/proc/net/tcp6']: if os.path.isfile(statf): with salt.utils.files.fopen(statf, 'rb') as fp_: for line in fp_: line = salt.utils.stringutils.to_unicode(line) if line.strip().startswith('sl'): continue iret = _parse_tcp_line(line) sl = next(iter(iret)) if iret[sl]['state'] == 1: # 1 is ESTABLISHED del iret[sl]['state'] ret[len(ret)] = iret[sl] return ret def local_port_tcp(port): ''' Return a set of remote ip addrs attached to the specified local port ''' ret = _remotes_on(port, 'local_port') return ret def remote_port_tcp(port): ''' Return a set of ip addrs the current host is connected to on given port ''' ret = _remotes_on(port, 'remote_port') return ret def _remotes_on(port, which_end): ''' Return a set of ip addrs active tcp connections ''' port = int(port) ret = _netlink_tool_remote_on(port, which_end) if ret is not None: return ret ret = set() proc_available = False for statf in ['/proc/net/tcp', '/proc/net/tcp6']: if os.path.isfile(statf): proc_available = True with salt.utils.files.fopen(statf, 'r') as fp_: for line in fp_: line = salt.utils.stringutils.to_unicode(line) if line.strip().startswith('sl'): continue iret = _parse_tcp_line(line) sl = next(iter(iret)) if iret[sl][which_end] == port and iret[sl]['state'] == 1: # 1 is ESTABLISHED ret.add(iret[sl]['remote_addr']) if not proc_available: # Fallback to use OS specific tools if salt.utils.platform.is_sunos(): return _sunos_remotes_on(port, which_end) if salt.utils.platform.is_freebsd(): return _freebsd_remotes_on(port, which_end) if salt.utils.platform.is_netbsd(): return _netbsd_remotes_on(port, which_end) if salt.utils.platform.is_openbsd(): return _openbsd_remotes_on(port, which_end) if salt.utils.platform.is_windows(): return _windows_remotes_on(port, which_end) if salt.utils.platform.is_aix(): return _aix_remotes_on(port, which_end) return _linux_remotes_on(port, which_end) return ret def _parse_tcp_line(line): ''' Parse a single line from the contents of /proc/net/tcp or /proc/net/tcp6 ''' ret = {} comps = line.strip().split() sl = comps[0].rstrip(':') ret[sl] = {} l_addr, l_port = comps[1].split(':') r_addr, r_port = comps[2].split(':') ret[sl]['local_addr'] = hex2ip(l_addr, True) ret[sl]['local_port'] = int(l_port, 16) ret[sl]['remote_addr'] = hex2ip(r_addr, True) ret[sl]['remote_port'] = int(r_port, 16) ret[sl]['state'] = int(comps[3], 16) return ret def _netlink_tool_remote_on(port, which_end): ''' Returns set of ipv4 host addresses of remote established connections on local or remote tcp port. Parses output of shell 'ss' to get connections [root@salt-master ~]# ss -ant State Recv-Q Send-Q Local Address:Port Peer Address:Port LISTEN 0 511 *:80 *:* LISTEN 0 128 *:22 *:* ESTAB 0 0 127.0.0.1:56726 127.0.0.1:4505 ''' remotes = set() valid = False try: data = subprocess.check_output(['ss', '-ant']) # pylint: disable=minimum-python-version except subprocess.CalledProcessError: log.error('Failed ss') raise except OSError: # not command "No such file or directory" return None lines = salt.utils.stringutils.to_str(data).split('\n') for line in lines: if 'Address:Port' in line: # ss tools may not be valid valid = True continue elif 'ESTAB' not in line: continue chunks = line.split() local_host, local_port = chunks[3].split(':', 1) remote_host, remote_port = chunks[4].split(':', 1) if which_end == 'remote_port' and int(remote_port) != port: continue if which_end == 'local_port' and int(local_port) != port: continue remotes.add(remote_host) if valid is False: remotes = None return remotes def _sunos_remotes_on(port, which_end): ''' SunOS specific helper function. Returns set of ipv4 host addresses of remote established connections on local or remote tcp port. Parses output of shell 'netstat' to get connections [root@salt-master ~]# netstat -f inet -n TCP: IPv4 Local Address Remote Address Swind Send-Q Rwind Recv-Q State -------------------- -------------------- ----- ------ ----- ------ ----------- 10.0.0.101.4505 10.0.0.1.45329 1064800 0 1055864 0 ESTABLISHED 10.0.0.101.4505 10.0.0.100.50798 1064800 0 1055864 0 ESTABLISHED ''' remotes = set() try: data = subprocess.check_output(['netstat', '-f', 'inet', '-n']) # pylint: disable=minimum-python-version except subprocess.CalledProcessError: log.error('Failed netstat') raise lines = salt.utils.stringutils.to_str(data).split('\n') for line in lines: if 'ESTABLISHED' not in line: continue chunks = line.split() local_host, local_port = chunks[0].rsplit('.', 1) remote_host, remote_port = chunks[1].rsplit('.', 1) if which_end == 'remote_port' and int(remote_port) != port: continue if which_end == 'local_port' and int(local_port) != port: continue remotes.add(remote_host) return remotes def _freebsd_remotes_on(port, which_end): ''' Returns set of ipv4 host addresses of remote established connections on local tcp port port. Parses output of shell 'sockstat' (FreeBSD) to get connections $ sudo sockstat -4 USER COMMAND PID FD PROTO LOCAL ADDRESS FOREIGN ADDRESS root python2.7 1456 29 tcp4 *:4505 *:* root python2.7 1445 17 tcp4 *:4506 *:* root python2.7 1294 14 tcp4 127.0.0.1:11813 127.0.0.1:4505 root python2.7 1294 41 tcp4 127.0.0.1:61115 127.0.0.1:4506 $ sudo sockstat -4 -c -p 4506 USER COMMAND PID FD PROTO LOCAL ADDRESS FOREIGN ADDRESS root python2.7 1294 41 tcp4 127.0.0.1:61115 127.0.0.1:4506 ''' port = int(port) remotes = set() try: cmd = salt.utils.args.shlex_split('sockstat -4 -c -p {0}'.format(port)) data = subprocess.check_output(cmd) # pylint: disable=minimum-python-version except subprocess.CalledProcessError as ex: log.error('Failed "sockstat" with returncode = %s', ex.returncode) raise lines = salt.utils.stringutils.to_str(data).split('\n') for line in lines: chunks = line.split() if not chunks: continue # ['root', 'python2.7', '1456', '37', 'tcp4', # '127.0.0.1:4505-', '127.0.0.1:55703'] # print chunks if 'COMMAND' in chunks[1]: continue # ignore header if len(chunks) < 2: continue # sockstat -4 -c -p 4506 does this with high PIDs: # USER COMMAND PID FD PROTO LOCAL ADDRESS FOREIGN ADDRESS # salt-master python2.781106 35 tcp4 192.168.12.34:4506 192.168.12.45:60143 local = chunks[-2] remote = chunks[-1] lhost, lport = local.split(':') rhost, rport = remote.split(':') if which_end == 'local' and int(lport) != port: # ignore if local port not port continue if which_end == 'remote' and int(rport) != port: # ignore if remote port not port continue remotes.add(rhost) return remotes def _netbsd_remotes_on(port, which_end): ''' Returns set of ipv4 host addresses of remote established connections on local tcp port port. Parses output of shell 'sockstat' (NetBSD) to get connections $ sudo sockstat -4 -n USER COMMAND PID FD PROTO LOCAL ADDRESS FOREIGN ADDRESS root python2.7 1456 29 tcp *.4505 *.* root python2.7 1445 17 tcp *.4506 *.* root python2.7 1294 14 tcp 127.0.0.1.11813 127.0.0.1.4505 root python2.7 1294 41 tcp 127.0.0.1.61115 127.0.0.1.4506 $ sudo sockstat -4 -c -n -p 4506 USER COMMAND PID FD PROTO LOCAL ADDRESS FOREIGN ADDRESS root python2.7 1294 41 tcp 127.0.0.1.61115 127.0.0.1.4506 ''' port = int(port) remotes = set() try: cmd = salt.utils.args.shlex_split('sockstat -4 -c -n -p {0}'.format(port)) data = subprocess.check_output(cmd) # pylint: disable=minimum-python-version except subprocess.CalledProcessError as ex: log.error('Failed "sockstat" with returncode = %s', ex.returncode) raise lines = salt.utils.stringutils.to_str(data).split('\n') for line in lines: chunks = line.split() if not chunks: continue # ['root', 'python2.7', '1456', '37', 'tcp', # '127.0.0.1.4505-', '127.0.0.1.55703'] # print chunks if 'COMMAND' in chunks[1]: continue # ignore header if len(chunks) < 2: continue local = chunks[5].split('.') lport = local.pop() lhost = '.'.join(local) remote = chunks[6].split('.') rport = remote.pop() rhost = '.'.join(remote) if which_end == 'local' and int(lport) != port: # ignore if local port not port continue if which_end == 'remote' and int(rport) != port: # ignore if remote port not port continue remotes.add(rhost) return remotes def _openbsd_remotes_on(port, which_end): ''' OpenBSD specific helper function. Returns set of ipv4 host addresses of remote established connections on local or remote tcp port. Parses output of shell 'netstat' to get connections $ netstat -nf inet Active Internet connections Proto Recv-Q Send-Q Local Address Foreign Address (state) tcp 0 0 10.0.0.101.4505 10.0.0.1.45329 ESTABLISHED tcp 0 0 10.0.0.101.4505 10.0.0.100.50798 ESTABLISHED ''' remotes = set() try: data = subprocess.check_output(['netstat', '-nf', 'inet']) # pylint: disable=minimum-python-version except subprocess.CalledProcessError: log.error('Failed netstat') raise lines = data.split('\n') for line in lines: if 'ESTABLISHED' not in line: continue chunks = line.split() local_host, local_port = chunks[3].rsplit('.', 1) remote_host, remote_port = chunks[4].rsplit('.', 1) if which_end == 'remote_port' and int(remote_port) != port: continue if which_end == 'local_port' and int(local_port) != port: continue remotes.add(remote_host) return remotes def _windows_remotes_on(port, which_end): r''' Windows specific helper function. Returns set of ipv4 host addresses of remote established connections on local or remote tcp port. Parses output of shell 'netstat' to get connections C:\>netstat -n Active Connections Proto Local Address Foreign Address State TCP 10.2.33.17:3007 130.164.12.233:10123 ESTABLISHED TCP 10.2.33.17:3389 130.164.30.5:10378 ESTABLISHED ''' remotes = set() try: data = subprocess.check_output(['netstat', '-n']) # pylint: disable=minimum-python-version except subprocess.CalledProcessError: log.error('Failed netstat') raise lines = salt.utils.stringutils.to_str(data).split('\n') for line in lines: if 'ESTABLISHED' not in line: continue chunks = line.split() local_host, local_port = chunks[1].rsplit(':', 1) remote_host, remote_port = chunks[2].rsplit(':', 1) if which_end == 'remote_port' and int(remote_port) != port: continue if which_end == 'local_port' and int(local_port) != port: continue remotes.add(remote_host) return remotes def _linux_remotes_on(port, which_end): ''' Linux specific helper function. Returns set of ip host addresses of remote established connections on local tcp port port. Parses output of shell 'lsof' to get connections $ sudo lsof -iTCP:4505 -n COMMAND PID USER FD TYPE DEVICE SIZE/OFF NODE NAME Python 9971 root 35u IPv4 0x18a8464a29ca329d 0t0 TCP *:4505 (LISTEN) Python 9971 root 37u IPv4 0x18a8464a29b2b29d 0t0 TCP 127.0.0.1:4505->127.0.0.1:55703 (ESTABLISHED) Python 10152 root 22u IPv4 0x18a8464a29c8cab5 0t0 TCP 127.0.0.1:55703->127.0.0.1:4505 (ESTABLISHED) Python 10153 root 22u IPv4 0x18a8464a29c8cab5 0t0 TCP [fe80::249a]:4505->[fe80::150]:59367 (ESTABLISHED) ''' remotes = set() try: data = subprocess.check_output( ['lsof', '-iTCP:{0:d}'.format(port), '-n', '-P'] # pylint: disable=minimum-python-version ) except subprocess.CalledProcessError as ex: if ex.returncode == 1: # Lsof return 1 if any error was detected, including the failure # to locate Internet addresses, and it is not an error in this case. log.warning('"lsof" returncode = 1, likely no active TCP sessions.') return remotes log.error('Failed "lsof" with returncode = %s', ex.returncode) raise lines = salt.utils.stringutils.to_str(data).split('\n') for line in lines: chunks = line.split() if not chunks: continue # ['Python', '9971', 'root', '37u', 'IPv4', '0x18a8464a29b2b29d', '0t0', # 'TCP', '127.0.0.1:4505->127.0.0.1:55703', '(ESTABLISHED)'] # print chunks if 'COMMAND' in chunks[0]: continue # ignore header if 'ESTABLISHED' not in chunks[-1]: continue # ignore if not ESTABLISHED # '127.0.0.1:4505->127.0.0.1:55703' local, remote = chunks[8].split('->') _, lport = local.rsplit(':', 1) rhost, rport = remote.rsplit(':', 1) if which_end == 'remote_port' and int(rport) != port: continue if which_end == 'local_port' and int(lport) != port: continue remotes.add(rhost.strip("[]")) return remotes def _aix_remotes_on(port, which_end): ''' AIX specific helper function. Returns set of ipv4 host addresses of remote established connections on local or remote tcp port. Parses output of shell 'netstat' to get connections root@la68pp002_pub:/opt/salt/lib/python2.7/site-packages/salt/modules# netstat -f inet -n Active Internet connections Proto Recv-Q Send-Q Local Address Foreign Address (state) tcp4 0 0 172.29.149.95.50093 209.41.78.13.4505 ESTABLISHED tcp4 0 0 127.0.0.1.9514 *.* LISTEN tcp4 0 0 127.0.0.1.9515 *.* LISTEN tcp4 0 0 127.0.0.1.199 127.0.0.1.32779 ESTABLISHED tcp4 0 0 127.0.0.1.32779 127.0.0.1.199 ESTABLISHED tcp4 0 40 172.29.149.95.22 172.29.96.83.41022 ESTABLISHED tcp4 0 0 172.29.149.95.22 172.29.96.83.41032 ESTABLISHED tcp4 0 0 127.0.0.1.32771 127.0.0.1.32775 ESTABLISHED tcp 0 0 127.0.0.1.32775 127.0.0.1.32771 ESTABLISHED tcp4 0 0 127.0.0.1.32771 127.0.0.1.32776 ESTABLISHED tcp 0 0 127.0.0.1.32776 127.0.0.1.32771 ESTABLISHED tcp4 0 0 127.0.0.1.32771 127.0.0.1.32777 ESTABLISHED tcp 0 0 127.0.0.1.32777 127.0.0.1.32771 ESTABLISHED tcp4 0 0 127.0.0.1.32771 127.0.0.1.32778 ESTABLISHED tcp 0 0 127.0.0.1.32778 127.0.0.1.32771 ESTABLISHED ''' remotes = set() try: data = subprocess.check_output(['netstat', '-f', 'inet', '-n']) # pylint: disable=minimum-python-version except subprocess.CalledProcessError: log.error('Failed netstat') raise lines = salt.utils.stringutils.to_str(data).split('\n') for line in lines: if 'ESTABLISHED' not in line: continue chunks = line.split() local_host, local_port = chunks[3].rsplit('.', 1) remote_host, remote_port = chunks[4].rsplit('.', 1) if which_end == 'remote_port' and int(remote_port) != port: continue if which_end == 'local_port' and int(local_port) != port: continue remotes.add(remote_host) return remotes @jinja_filter('gen_mac') def gen_mac(prefix='AC:DE:48'): ''' Generates a MAC address with the defined OUI prefix. Common prefixes: - ``00:16:3E`` -- Xen - ``00:18:51`` -- OpenVZ - ``00:50:56`` -- VMware (manually generated) - ``52:54:00`` -- QEMU/KVM - ``AC:DE:48`` -- PRIVATE References: - http://standards.ieee.org/develop/regauth/oui/oui.txt - https://www.wireshark.org/tools/oui-lookup.html - https://en.wikipedia.org/wiki/MAC_address ''' return '{0}:{1:02X}:{2:02X}:{3:02X}'.format(prefix, random.randint(0, 0xff), random.randint(0, 0xff), random.randint(0, 0xff)) @jinja_filter('mac_str_to_bytes') def mac_str_to_bytes(mac_str): ''' Convert a MAC address string into bytes. Works with or without separators: b1 = mac_str_to_bytes('08:00:27:13:69:77') b2 = mac_str_to_bytes('080027136977') assert b1 == b2 assert isinstance(b1, bytes) ''' if len(mac_str) == 12: pass elif len(mac_str) == 17: sep = mac_str[2] mac_str = mac_str.replace(sep, '') else: raise ValueError('Invalid MAC address') chars = (int(mac_str[s:s+2], 16) for s in range(0, 12, 2)) return bytes(chars) if six.PY3 else b''.join(chr(x) for x in chars) def refresh_dns(): ''' issue #21397: force glibc to re-read resolv.conf ''' try: res_init() except NameError: # Exception raised loading the library, thus res_init is not defined pass @jinja_filter('connection_check') def connection_check(addr, port=80, safe=False, ipv6=None): ''' Provides a convenient alias for the dns_check filter. ''' return dns_check(addr, port, safe, ipv6) @jinja_filter('dns_check') def dns_check(addr, port=80, safe=False, ipv6=None, attempt_connect=True): ''' Return the ip resolved by dns, but do not exit on failure, only raise an exception. Obeys system preference for IPv4/6 address resolution - this can be overridden by the ipv6 flag. Tries to connect to the address before considering it useful. If no address can be reached, the first one resolved is used as a fallback. ''' error = False lookup = addr seen_ipv6 = False family = socket.AF_INET6 if ipv6 else socket.AF_INET if ipv6 is False else socket.AF_UNSPEC hostnames = [] try: refresh_dns() hostnames = socket.getaddrinfo(addr, port, family, socket.SOCK_STREAM) except TypeError: err = ('Attempt to resolve address \'{0}\' failed. Invalid or unresolveable address').format(lookup) raise SaltSystemExit(code=42, msg=err) except socket.error: error = True # If ipv6 is set to True, attempt another lookup using the IPv4 family, # just in case we're attempting to lookup an IPv4 IP # as an IPv6 hostname. if error and ipv6: try: refresh_dns() hostnames = socket.getaddrinfo(addr, port, socket.AF_INET, socket.SOCK_STREAM) except TypeError: err = ('Attempt to resolve address \'{0}\' failed. Invalid or unresolveable address').format(lookup) raise SaltSystemExit(code=42, msg=err) except socket.error: error = True try: if not hostnames: error = True else: resolved = False candidates = [] for h in hostnames: # Input is IP address, passed through unchanged, just return it if h[4][0] == addr: resolved = salt.utils.zeromq.ip_bracket(addr) break candidate_addr = salt.utils.zeromq.ip_bracket(h[4][0]) # sometimes /etc/hosts contains ::1 localhost if not ipv6 and candidate_addr == '[::1]': continue candidates.append(candidate_addr) if attempt_connect: try: s = socket.socket(h[0], socket.SOCK_STREAM) s.settimeout(2) s.connect((candidate_addr.strip('[]'), h[4][1])) s.close() resolved = candidate_addr break except socket.error: pass if not resolved: if candidates: resolved = candidates[0] else: error = True except TypeError: err = ('Attempt to resolve address \'{0}\' failed. Invalid or unresolveable address').format(lookup) raise SaltSystemExit(code=42, msg=err) except socket.error: error = True if error: err = ('DNS lookup or connection check of \'{0}\' failed.').format(addr) if safe: if salt.log.is_console_configured(): # If logging is not configured it also means that either # the master or minion instance calling this hasn't even # started running log.error(err) raise SaltClientError() raise SaltSystemExit(code=42, msg=err) return resolved def parse_host_port(host_port): """ Takes a string argument specifying host or host:port. Returns a (hostname, port) or (ip_address, port) tuple. If no port is given, the second (port) element of the returned tuple will be None. host:port argument, for example, is accepted in the forms of: - hostname - hostname:1234 - hostname.domain.tld - hostname.domain.tld:5678 - [1234::5]:5678 - 1234::5 - 10.11.12.13:4567 - 10.11.12.13 """ host, port = None, None # default _s_ = host_port[:] if _s_[0] == "[": if "]" in host_port: host, _s_ = _s_.lstrip("[").rsplit("]", 1) host = ipaddress.IPv6Address(host).compressed if _s_[0] == ":": port = int(_s_.lstrip(":")) else: if len(_s_) > 1: raise ValueError('found ambiguous "{}" port in "{}"'.format(_s_, host_port)) else: if _s_.count(":") == 1: host, _hostport_separator_, port = _s_.partition(":") try: port = int(port) except ValueError as _e_: log.error('host_port "%s" port value "%s" is not an integer.', host_port, port) raise _e_ else: host = _s_ try: if not isinstance(host, ipaddress._BaseAddress): host_ip = ipaddress.ip_address(host).compressed host = host_ip except ValueError: log.debug('"%s" Not an IP address? Assuming it is a hostname.', host) if host != sanitize_host(host): log.error('bad hostname: "%s"', host) raise ValueError('bad hostname: "{}"'.format(host)) return host, port def is_fqdn(hostname): """ Verify if hostname conforms to be a FQDN. :param hostname: text string with the name of the host :return: bool, True if hostname is correct FQDN, False otherwise """ compliant = re.compile(r"(?!-)[A-Z\d\-\_]{1,63}(?<!-)$", re.IGNORECASE) return "." in hostname and len(hostname) < 0xff and all(compliant.match(x) for x in hostname.rstrip(".").split("."))
saltstack/salt
salt/utils/network.py
_netbsd_interfaces_ifconfig
python
def _netbsd_interfaces_ifconfig(out): ''' Uses ifconfig to return a dictionary of interfaces with various information about each (up/down state, ip address, netmask, and hwaddr) ''' ret = dict() piface = re.compile(r'^([^\s:]+)') pmac = re.compile('.*?address: ([0-9a-f:]+)') pip = re.compile(r'.*?inet [^\d]*(.*?)/([\d]*)\s') pip6 = re.compile(r'.*?inet6 ([0-9a-f:]+)%([a-zA-Z0-9]*)/([\d]*)\s') pupdown = re.compile('UP') pbcast = re.compile(r'.*?broadcast ([\d\.]+)') groups = re.compile('\r?\n(?=\\S)').split(out) for group in groups: data = dict() iface = '' updown = False for line in group.splitlines(): miface = piface.match(line) mmac = pmac.match(line) mip = pip.match(line) mip6 = pip6.match(line) mupdown = pupdown.search(line) if miface: iface = miface.group(1) if mmac: data['hwaddr'] = mmac.group(1) if mip: if 'inet' not in data: data['inet'] = list() addr_obj = dict() addr_obj['address'] = mip.group(1) mmask = mip.group(2) if mip.group(2): addr_obj['netmask'] = cidr_to_ipv4_netmask(mip.group(2)) mbcast = pbcast.match(line) if mbcast: addr_obj['broadcast'] = mbcast.group(1) data['inet'].append(addr_obj) if mupdown: updown = True if mip6: if 'inet6' not in data: data['inet6'] = list() addr_obj = dict() addr_obj['address'] = mip6.group(1) mmask6 = mip6.group(3) addr_obj['scope'] = mip6.group(2) addr_obj['prefixlen'] = mip6.group(3) data['inet6'].append(addr_obj) data['up'] = updown ret[iface] = data del data return ret
Uses ifconfig to return a dictionary of interfaces with various information about each (up/down state, ip address, netmask, and hwaddr)
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/network.py#L877-L934
[ "def cidr_to_ipv4_netmask(cidr_bits):\n '''\n Returns an IPv4 netmask\n '''\n try:\n cidr_bits = int(cidr_bits)\n if not 1 <= cidr_bits <= 32:\n return ''\n except ValueError:\n return ''\n\n netmask = ''\n for idx in range(4):\n if idx:\n netmask += '.'\n if cidr_bits >= 8:\n netmask += '255'\n cidr_bits -= 8\n else:\n netmask += '{0:d}'.format(256 - (2 ** (8 - cidr_bits)))\n cidr_bits = 0\n return netmask\n" ]
# -*- coding: utf-8 -*- ''' Define some generic socket functions for network modules ''' # Import python libs from __future__ import absolute_import, unicode_literals, print_function import itertools import os import re import types import socket import logging import platform import random import subprocess from string import ascii_letters, digits # Import 3rd-party libs from salt.ext import six from salt.ext.six.moves import range # pylint: disable=import-error,redefined-builtin # Attempt to import wmi try: import wmi import salt.utils.winapi except ImportError: pass # Import salt libs import salt.utils.args import salt.utils.files import salt.utils.path import salt.utils.platform import salt.utils.stringutils import salt.utils.zeromq from salt._compat import ipaddress from salt.exceptions import SaltClientError, SaltSystemExit from salt.utils.decorators.jinja import jinja_filter from salt.utils.versions import LooseVersion # inet_pton does not exist in Windows, this is a workaround if salt.utils.platform.is_windows(): from salt.ext import win_inet_pton # pylint: disable=unused-import log = logging.getLogger(__name__) try: import ctypes import ctypes.util libc = ctypes.cdll.LoadLibrary(ctypes.util.find_library("c")) res_init = libc.__res_init except (ImportError, OSError, AttributeError, TypeError): pass # pylint: disable=C0103 def sanitize_host(host): ''' Sanitize host string. https://tools.ietf.org/html/rfc1123#section-2.1 ''' RFC952_characters = ascii_letters + digits + ".-" return "".join([c for c in host[0:255] if c in RFC952_characters]) def isportopen(host, port): ''' Return status of a port ''' if not 1 <= int(port) <= 65535: return False sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) out = sock.connect_ex((sanitize_host(host), int(port))) return out def host_to_ips(host): ''' Returns a list of IP addresses of a given hostname or None if not found. ''' ips = [] try: for family, socktype, proto, canonname, sockaddr in socket.getaddrinfo( host, 0, socket.AF_UNSPEC, socket.SOCK_STREAM): if family == socket.AF_INET: ip, port = sockaddr elif family == socket.AF_INET6: ip, port, flow_info, scope_id = sockaddr ips.append(ip) if not ips: ips = None except Exception: ips = None return ips def _generate_minion_id(): ''' Get list of possible host names and convention names. :return: ''' # There are three types of hostnames: # 1. Network names. How host is accessed from the network. # 2. Host aliases. They might be not available in all the network or only locally (/etc/hosts) # 3. Convention names, an internal nodename. class DistinctList(list): ''' List, which allows one to append only distinct objects. Needs to work on Python 2.6, because of collections.OrderedDict only since 2.7 version. Override 'filter()' for custom filtering. ''' localhost_matchers = [r'localhost.*', r'ip6-.*', r'127[.]\d', r'0\.0\.0\.0', r'::1.*', r'ipv6-.*', r'fe00::.*', r'fe02::.*', r'1.0.0.*.ip6.arpa'] def append(self, p_object): if p_object and p_object not in self and not self.filter(p_object): super(DistinctList, self).append(p_object) return self def extend(self, iterable): for obj in iterable: self.append(obj) return self def filter(self, element): 'Returns True if element needs to be filtered' for rgx in self.localhost_matchers: if re.match(rgx, element): return True def first(self): return self and self[0] or None hostname = socket.gethostname() hosts = DistinctList().append( salt.utils.stringutils.to_unicode(socket.getfqdn(salt.utils.stringutils.to_bytes(hostname))) ).append(platform.node()).append(hostname) if not hosts: try: for a_nfo in socket.getaddrinfo(hosts.first() or 'localhost', None, socket.AF_INET, socket.SOCK_RAW, socket.IPPROTO_IP, socket.AI_CANONNAME): if len(a_nfo) > 3: hosts.append(a_nfo[3]) except socket.gaierror: log.warning('Cannot resolve address %s info via socket: %s', hosts.first() or 'localhost (N/A)', socket.gaierror) # Universal method for everywhere (Linux, Slowlaris, Windows etc) for f_name in ('/etc/hostname', '/etc/nodename', '/etc/hosts', r'{win}\system32\drivers\etc\hosts'.format(win=os.getenv('WINDIR'))): try: with salt.utils.files.fopen(f_name) as f_hdl: for line in f_hdl: line = salt.utils.stringutils.to_unicode(line) hst = line.strip().split('#')[0].strip().split() if hst: if hst[0][:4] in ('127.', '::1') or len(hst) == 1: hosts.extend(hst) except IOError: pass # include public and private ipaddresses return hosts.extend([addr for addr in ip_addrs() if not ipaddress.ip_address(addr).is_loopback]) def generate_minion_id(): ''' Return only first element of the hostname from all possible list. :return: ''' try: ret = salt.utils.stringutils.to_unicode(_generate_minion_id().first()) except TypeError: ret = None return ret or 'localhost' def get_socket(addr, type=socket.SOCK_STREAM, proto=0): ''' Return a socket object for the addr IP-version agnostic ''' version = ipaddress.ip_address(addr).version if version == 4: family = socket.AF_INET elif version == 6: family = socket.AF_INET6 return socket.socket(family, type, proto) def get_fqhostname(): ''' Returns the fully qualified hostname ''' # try getaddrinfo() fqdn = None try: addrinfo = socket.getaddrinfo( socket.gethostname(), 0, socket.AF_UNSPEC, socket.SOCK_STREAM, socket.SOL_TCP, socket.AI_CANONNAME ) for info in addrinfo: # info struct [family, socktype, proto, canonname, sockaddr] # On Windows `canonname` can be an empty string # This can cause the function to return `None` if len(info) > 3 and info[3]: fqdn = info[3] break except socket.gaierror: pass # NOTE: this used to log.error() but it was later disabled except socket.error as err: log.debug('socket.getaddrinfo() failure while finding fqdn: %s', err) if fqdn is None: fqdn = socket.getfqdn() return fqdn def ip_to_host(ip): ''' Returns the hostname of a given IP ''' try: hostname, aliaslist, ipaddrlist = socket.gethostbyaddr(ip) except Exception as exc: log.debug('salt.utils.network.ip_to_host(%r) failed: %s', ip, exc) hostname = None return hostname # pylint: enable=C0103 def is_reachable_host(entity_name): ''' Returns a bool telling if the entity name is a reachable host (IPv4/IPv6/FQDN/etc). :param hostname: :return: ''' try: assert type(socket.getaddrinfo(entity_name, 0, 0, 0, 0)) == list ret = True except socket.gaierror: ret = False return ret def is_ip(ip): ''' Returns a bool telling if the passed IP is a valid IPv4 or IPv6 address. ''' return is_ipv4(ip) or is_ipv6(ip) def is_ipv4(ip): ''' Returns a bool telling if the value passed to it was a valid IPv4 address ''' try: return ipaddress.ip_address(ip).version == 4 except ValueError: return False def is_ipv6(ip): ''' Returns a bool telling if the value passed to it was a valid IPv6 address ''' try: return ipaddress.ip_address(ip).version == 6 except ValueError: return False def is_subnet(cidr): ''' Returns a bool telling if the passed string is an IPv4 or IPv6 subnet ''' return is_ipv4_subnet(cidr) or is_ipv6_subnet(cidr) def is_ipv4_subnet(cidr): ''' Returns a bool telling if the passed string is an IPv4 subnet ''' try: return '/' in cidr and bool(ipaddress.IPv4Network(cidr)) except Exception: return False def is_ipv6_subnet(cidr): ''' Returns a bool telling if the passed string is an IPv6 subnet ''' try: return '/' in cidr and bool(ipaddress.IPv6Network(cidr)) except Exception: return False @jinja_filter('is_ip') def is_ip_filter(ip, options=None): ''' Returns a bool telling if the passed IP is a valid IPv4 or IPv6 address. ''' return is_ipv4_filter(ip, options=options) or is_ipv6_filter(ip, options=options) def _ip_options_global(ip_obj, version): return not ip_obj.is_private def _ip_options_multicast(ip_obj, version): return ip_obj.is_multicast def _ip_options_loopback(ip_obj, version): return ip_obj.is_loopback def _ip_options_link_local(ip_obj, version): return ip_obj.is_link_local def _ip_options_private(ip_obj, version): return ip_obj.is_private def _ip_options_reserved(ip_obj, version): return ip_obj.is_reserved def _ip_options_site_local(ip_obj, version): if version == 6: return ip_obj.is_site_local return False def _ip_options_unspecified(ip_obj, version): return ip_obj.is_unspecified def _ip_options(ip_obj, version, options=None): # will process and IP options options_fun_map = { 'global': _ip_options_global, 'link-local': _ip_options_link_local, 'linklocal': _ip_options_link_local, 'll': _ip_options_link_local, 'link_local': _ip_options_link_local, 'loopback': _ip_options_loopback, 'lo': _ip_options_loopback, 'multicast': _ip_options_multicast, 'private': _ip_options_private, 'public': _ip_options_global, 'reserved': _ip_options_reserved, 'site-local': _ip_options_site_local, 'sl': _ip_options_site_local, 'site_local': _ip_options_site_local, 'unspecified': _ip_options_unspecified } if not options: return six.text_type(ip_obj) # IP version already checked options_list = [option.strip() for option in options.split(',')] for option, fun in options_fun_map.items(): if option in options_list: fun_res = fun(ip_obj, version) if not fun_res: return None # stop at first failed test # else continue return six.text_type(ip_obj) def _is_ipv(ip, version, options=None): if not version: version = 4 if version not in (4, 6): return None try: ip_obj = ipaddress.ip_address(ip) except ValueError: # maybe it is an IP network try: ip_obj = ipaddress.ip_interface(ip) except ValueError: # nope, still not :( return None if not ip_obj.version == version: return None # has the right version, let's move on return _ip_options(ip_obj, version, options=options) @jinja_filter('is_ipv4') def is_ipv4_filter(ip, options=None): ''' Returns a bool telling if the value passed to it was a valid IPv4 address. ip The IP address. net: False Consider IP addresses followed by netmask. options CSV of options regarding the nature of the IP address. E.g.: loopback, multicast, private etc. ''' _is_ipv4 = _is_ipv(ip, 4, options=options) return isinstance(_is_ipv4, six.string_types) @jinja_filter('is_ipv6') def is_ipv6_filter(ip, options=None): ''' Returns a bool telling if the value passed to it was a valid IPv6 address. ip The IP address. net: False Consider IP addresses followed by netmask. options CSV of options regarding the nature of the IP address. E.g.: loopback, multicast, private etc. ''' _is_ipv6 = _is_ipv(ip, 6, options=options) return isinstance(_is_ipv6, six.string_types) def _ipv_filter(value, version, options=None): if version not in (4, 6): return if isinstance(value, (six.string_types, six.text_type, six.binary_type)): return _is_ipv(value, version, options=options) # calls is_ipv4 or is_ipv6 for `value` elif isinstance(value, (list, tuple, types.GeneratorType)): # calls is_ipv4 or is_ipv6 for each element in the list # os it filters and returns only those elements having the desired IP version return [ _is_ipv(addr, version, options=options) for addr in value if _is_ipv(addr, version, options=options) is not None ] return None @jinja_filter('ipv4') def ipv4(value, options=None): ''' Filters a list and returns IPv4 values only. ''' return _ipv_filter(value, 4, options=options) @jinja_filter('ipv6') def ipv6(value, options=None): ''' Filters a list and returns IPv6 values only. ''' return _ipv_filter(value, 6, options=options) @jinja_filter('ipaddr') def ipaddr(value, options=None): ''' Filters and returns only valid IP objects. ''' ipv4_obj = ipv4(value, options=options) ipv6_obj = ipv6(value, options=options) if ipv4_obj is None or ipv6_obj is None: # an IP address can be either IPv4 either IPv6 # therefofe if the value passed as arg is not a list, at least one of the calls above will return None # if one of them is none, means that we should return only one of them return ipv4_obj or ipv6_obj # one of them else: return ipv4_obj + ipv6_obj # extend lists def _filter_ipaddr(value, options, version=None): ipaddr_filter_out = None if version: if version == 4: ipaddr_filter_out = ipv4(value, options) elif version == 6: ipaddr_filter_out = ipv6(value, options) else: ipaddr_filter_out = ipaddr(value, options) if not ipaddr_filter_out: return if not isinstance(ipaddr_filter_out, (list, tuple, types.GeneratorType)): ipaddr_filter_out = [ipaddr_filter_out] return ipaddr_filter_out @jinja_filter('ip_host') def ip_host(value, options=None, version=None): ''' Returns the interfaces IP address, e.g.: 192.168.0.1/28. ''' ipaddr_filter_out = _filter_ipaddr(value, options=options, version=version) if not ipaddr_filter_out: return if not isinstance(value, (list, tuple, types.GeneratorType)): return six.text_type(ipaddress.ip_interface(ipaddr_filter_out[0])) return [six.text_type(ipaddress.ip_interface(ip_a)) for ip_a in ipaddr_filter_out] def _network_hosts(ip_addr_entry): return [ six.text_type(host) for host in ipaddress.ip_network(ip_addr_entry, strict=False).hosts() ] @jinja_filter('network_hosts') def network_hosts(value, options=None, version=None): ''' Return the list of hosts within a network. .. note:: When running this command with a large IPv6 network, the command will take a long time to gather all of the hosts. ''' ipaddr_filter_out = _filter_ipaddr(value, options=options, version=version) if not ipaddr_filter_out: return if not isinstance(value, (list, tuple, types.GeneratorType)): return _network_hosts(ipaddr_filter_out[0]) return [ _network_hosts(ip_a) for ip_a in ipaddr_filter_out ] def _network_size(ip_addr_entry): return ipaddress.ip_network(ip_addr_entry, strict=False).num_addresses @jinja_filter('network_size') def network_size(value, options=None, version=None): ''' Get the size of a network. ''' ipaddr_filter_out = _filter_ipaddr(value, options=options, version=version) if not ipaddr_filter_out: return if not isinstance(value, (list, tuple, types.GeneratorType)): return _network_size(ipaddr_filter_out[0]) return [ _network_size(ip_a) for ip_a in ipaddr_filter_out ] def natural_ipv4_netmask(ip, fmt='prefixlen'): ''' Returns the "natural" mask of an IPv4 address ''' bits = _ipv4_to_bits(ip) if bits.startswith('11'): mask = '24' elif bits.startswith('1'): mask = '16' else: mask = '8' if fmt == 'netmask': return cidr_to_ipv4_netmask(mask) else: return '/' + mask def rpad_ipv4_network(ip): ''' Returns an IP network address padded with zeros. Ex: '192.168.3' -> '192.168.3.0' '10.209' -> '10.209.0.0' ''' return '.'.join(itertools.islice(itertools.chain(ip.split('.'), '0000'), 0, 4)) def cidr_to_ipv4_netmask(cidr_bits): ''' Returns an IPv4 netmask ''' try: cidr_bits = int(cidr_bits) if not 1 <= cidr_bits <= 32: return '' except ValueError: return '' netmask = '' for idx in range(4): if idx: netmask += '.' if cidr_bits >= 8: netmask += '255' cidr_bits -= 8 else: netmask += '{0:d}'.format(256 - (2 ** (8 - cidr_bits))) cidr_bits = 0 return netmask def _number_of_set_bits_to_ipv4_netmask(set_bits): # pylint: disable=C0103 ''' Returns an IPv4 netmask from the integer representation of that mask. Ex. 0xffffff00 -> '255.255.255.0' ''' return cidr_to_ipv4_netmask(_number_of_set_bits(set_bits)) # pylint: disable=C0103 def _number_of_set_bits(x): ''' Returns the number of bits that are set in a 32bit int ''' # Taken from http://stackoverflow.com/a/4912729. Many thanks! x -= (x >> 1) & 0x55555555 x = ((x >> 2) & 0x33333333) + (x & 0x33333333) x = ((x >> 4) + x) & 0x0f0f0f0f x += x >> 8 x += x >> 16 return x & 0x0000003f # pylint: enable=C0103 def _interfaces_ip(out): ''' Uses ip to return a dictionary of interfaces with various information about each (up/down state, ip address, netmask, and hwaddr) ''' ret = dict() def parse_network(value, cols): ''' Return a tuple of ip, netmask, broadcast based on the current set of cols ''' brd = None scope = None if '/' in value: # we have a CIDR in this address ip, cidr = value.split('/') # pylint: disable=C0103 else: ip = value # pylint: disable=C0103 cidr = 32 if type_ == 'inet': mask = cidr_to_ipv4_netmask(int(cidr)) if 'brd' in cols: brd = cols[cols.index('brd') + 1] elif type_ == 'inet6': mask = cidr if 'scope' in cols: scope = cols[cols.index('scope') + 1] return (ip, mask, brd, scope) groups = re.compile('\r?\n\\d').split(out) for group in groups: iface = None data = dict() for line in group.splitlines(): if ' ' not in line: continue match = re.match(r'^\d*:\s+([\w.\-]+)(?:@)?([\w.\-]+)?:\s+<(.+)>', line) if match: iface, parent, attrs = match.groups() if 'UP' in attrs.split(','): data['up'] = True else: data['up'] = False if parent: data['parent'] = parent continue cols = line.split() if len(cols) >= 2: type_, value = tuple(cols[0:2]) iflabel = cols[-1:][0] if type_ in ('inet', 'inet6'): if 'secondary' not in cols: ipaddr, netmask, broadcast, scope = parse_network(value, cols) if type_ == 'inet': if 'inet' not in data: data['inet'] = list() addr_obj = dict() addr_obj['address'] = ipaddr addr_obj['netmask'] = netmask addr_obj['broadcast'] = broadcast addr_obj['label'] = iflabel data['inet'].append(addr_obj) elif type_ == 'inet6': if 'inet6' not in data: data['inet6'] = list() addr_obj = dict() addr_obj['address'] = ipaddr addr_obj['prefixlen'] = netmask addr_obj['scope'] = scope data['inet6'].append(addr_obj) else: if 'secondary' not in data: data['secondary'] = list() ip_, mask, brd, scp = parse_network(value, cols) data['secondary'].append({ 'type': type_, 'address': ip_, 'netmask': mask, 'broadcast': brd, 'label': iflabel, }) del ip_, mask, brd, scp elif type_.startswith('link'): data['hwaddr'] = value if iface: ret[iface] = data del iface, data return ret def _interfaces_ifconfig(out): ''' Uses ifconfig to return a dictionary of interfaces with various information about each (up/down state, ip address, netmask, and hwaddr) ''' ret = dict() piface = re.compile(r'^([^\s:]+)') pmac = re.compile('.*?(?:HWaddr|ether|address:|lladdr) ([0-9a-fA-F:]+)') if salt.utils.platform.is_sunos(): pip = re.compile(r'.*?(?:inet\s+)([0-9]+\.[0-9]+\.[0-9]+\.[0-9]+)(.*)') pip6 = re.compile('.*?(?:inet6 )([0-9a-fA-F:]+)') pmask6 = re.compile(r'.*?(?:inet6 [0-9a-fA-F:]+/(\d+)).*') else: pip = re.compile(r'.*?(?:inet addr:|inet [^\d]*)(.*?)\s') pip6 = re.compile('.*?(?:inet6 addr: (.*?)/|inet6 )([0-9a-fA-F:]+)') pmask6 = re.compile(r'.*?(?:inet6 addr: [0-9a-fA-F:]+/(\d+)|prefixlen (\d+))(?: Scope:([a-zA-Z]+)| scopeid (0x[0-9a-fA-F]))?') pmask = re.compile(r'.*?(?:Mask:|netmask )(?:((?:0x)?[0-9a-fA-F]{8})|([\d\.]+))') pupdown = re.compile('UP') pbcast = re.compile(r'.*?(?:Bcast:|broadcast )([\d\.]+)') groups = re.compile('\r?\n(?=\\S)').split(out) for group in groups: data = dict() iface = '' updown = False for line in group.splitlines(): miface = piface.match(line) mmac = pmac.match(line) mip = pip.match(line) mip6 = pip6.match(line) mupdown = pupdown.search(line) if miface: iface = miface.group(1) if mmac: data['hwaddr'] = mmac.group(1) if salt.utils.platform.is_sunos(): expand_mac = [] for chunk in data['hwaddr'].split(':'): expand_mac.append('0{0}'.format(chunk) if len(chunk) < 2 else '{0}'.format(chunk)) data['hwaddr'] = ':'.join(expand_mac) if mip: if 'inet' not in data: data['inet'] = list() addr_obj = dict() addr_obj['address'] = mip.group(1) mmask = pmask.match(line) if mmask: if mmask.group(1): mmask = _number_of_set_bits_to_ipv4_netmask( int(mmask.group(1), 16)) else: mmask = mmask.group(2) addr_obj['netmask'] = mmask mbcast = pbcast.match(line) if mbcast: addr_obj['broadcast'] = mbcast.group(1) data['inet'].append(addr_obj) if mupdown: updown = True if mip6: if 'inet6' not in data: data['inet6'] = list() addr_obj = dict() addr_obj['address'] = mip6.group(1) or mip6.group(2) mmask6 = pmask6.match(line) if mmask6: addr_obj['prefixlen'] = mmask6.group(1) or mmask6.group(2) if not salt.utils.platform.is_sunos(): ipv6scope = mmask6.group(3) or mmask6.group(4) addr_obj['scope'] = ipv6scope.lower() if ipv6scope is not None else ipv6scope # SunOS sometimes has ::/0 as inet6 addr when using addrconf if not salt.utils.platform.is_sunos() \ or addr_obj['address'] != '::' \ and addr_obj['prefixlen'] != 0: data['inet6'].append(addr_obj) data['up'] = updown if iface in ret: # SunOS optimization, where interfaces occur twice in 'ifconfig -a' # output with the same name: for ipv4 and then for ipv6 addr family. # Every instance has it's own 'UP' status and we assume that ipv4 # status determines global interface status. # # merge items with higher priority for older values # after that merge the inet and inet6 sub items for both ret[iface] = dict(list(data.items()) + list(ret[iface].items())) if 'inet' in data: ret[iface]['inet'].extend(x for x in data['inet'] if x not in ret[iface]['inet']) if 'inet6' in data: ret[iface]['inet6'].extend(x for x in data['inet6'] if x not in ret[iface]['inet6']) else: ret[iface] = data del data return ret def linux_interfaces(): ''' Obtain interface information for *NIX/BSD variants ''' ifaces = dict() ip_path = salt.utils.path.which('ip') ifconfig_path = None if ip_path else salt.utils.path.which('ifconfig') if ip_path: cmd1 = subprocess.Popen( '{0} link show'.format(ip_path), shell=True, close_fds=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT).communicate()[0] cmd2 = subprocess.Popen( '{0} addr show'.format(ip_path), shell=True, close_fds=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT).communicate()[0] ifaces = _interfaces_ip("{0}\n{1}".format( salt.utils.stringutils.to_str(cmd1), salt.utils.stringutils.to_str(cmd2))) elif ifconfig_path: cmd = subprocess.Popen( '{0} -a'.format(ifconfig_path), shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT).communicate()[0] ifaces = _interfaces_ifconfig(salt.utils.stringutils.to_str(cmd)) return ifaces def netbsd_interfaces(): ''' Obtain interface information for NetBSD >= 8 where the ifconfig output diverged from other BSD variants (Netmask is now part of the address) ''' # NetBSD versions prior to 8.0 can still use linux_interfaces() if LooseVersion(os.uname()[2]) < LooseVersion('8.0'): return linux_interfaces() ifconfig_path = salt.utils.path.which('ifconfig') cmd = subprocess.Popen( '{0} -a'.format(ifconfig_path), shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT).communicate()[0] return _netbsd_interfaces_ifconfig(salt.utils.stringutils.to_str(cmd)) def _interfaces_ipconfig(out): ''' Returns a dictionary of interfaces with various information about each (up/down state, ip address, netmask, and hwaddr) NOTE: This is not used by any function and may be able to be removed in the future. ''' ifaces = dict() iface = None adapter_iface_regex = re.compile(r'adapter (\S.+):$') for line in out.splitlines(): if not line: continue # TODO what does Windows call Infiniband and 10/40gige adapters if line.startswith('Ethernet'): iface = ifaces[adapter_iface_regex.search(line).group(1)] iface['up'] = True addr = None continue if iface: key, val = line.split(',', 1) key = key.strip(' .') val = val.strip() if addr and key == 'Subnet Mask': addr['netmask'] = val elif key in ('IP Address', 'IPv4 Address'): if 'inet' not in iface: iface['inet'] = list() addr = {'address': val.rstrip('(Preferred)'), 'netmask': None, 'broadcast': None} # TODO find the broadcast iface['inet'].append(addr) elif 'IPv6 Address' in key: if 'inet6' not in iface: iface['inet'] = list() # XXX What is the prefixlen!? addr = {'address': val.rstrip('(Preferred)'), 'prefixlen': None} iface['inet6'].append(addr) elif key == 'Physical Address': iface['hwaddr'] = val elif key == 'Media State': # XXX seen used for tunnel adaptors # might be useful iface['up'] = (val != 'Media disconnected') def win_interfaces(): ''' Obtain interface information for Windows systems ''' with salt.utils.winapi.Com(): c = wmi.WMI() ifaces = {} for iface in c.Win32_NetworkAdapterConfiguration(IPEnabled=1): ifaces[iface.Description] = dict() if iface.MACAddress: ifaces[iface.Description]['hwaddr'] = iface.MACAddress if iface.IPEnabled: ifaces[iface.Description]['up'] = True for ip in iface.IPAddress: if '.' in ip: if 'inet' not in ifaces[iface.Description]: ifaces[iface.Description]['inet'] = [] item = {'address': ip, 'label': iface.Description} if iface.DefaultIPGateway: broadcast = next((i for i in iface.DefaultIPGateway if '.' in i), '') if broadcast: item['broadcast'] = broadcast if iface.IPSubnet: netmask = next((i for i in iface.IPSubnet if '.' in i), '') if netmask: item['netmask'] = netmask ifaces[iface.Description]['inet'].append(item) if ':' in ip: if 'inet6' not in ifaces[iface.Description]: ifaces[iface.Description]['inet6'] = [] item = {'address': ip} if iface.DefaultIPGateway: broadcast = next((i for i in iface.DefaultIPGateway if ':' in i), '') if broadcast: item['broadcast'] = broadcast if iface.IPSubnet: netmask = next((i for i in iface.IPSubnet if ':' in i), '') if netmask: item['netmask'] = netmask ifaces[iface.Description]['inet6'].append(item) else: ifaces[iface.Description]['up'] = False return ifaces def interfaces(): ''' Return a dictionary of information about all the interfaces on the minion ''' if salt.utils.platform.is_windows(): return win_interfaces() elif salt.utils.platform.is_netbsd(): return netbsd_interfaces() else: return linux_interfaces() def get_net_start(ipaddr, netmask): ''' Return the address of the network ''' net = ipaddress.ip_network('{0}/{1}'.format(ipaddr, netmask), strict=False) return six.text_type(net.network_address) def get_net_size(mask): ''' Turns an IPv4 netmask into it's corresponding prefix length (255.255.255.0 -> 24 as in 192.168.1.10/24). ''' binary_str = '' for octet in mask.split('.'): binary_str += bin(int(octet))[2:].zfill(8) return len(binary_str.rstrip('0')) def calc_net(ipaddr, netmask=None): ''' Takes IP (CIDR notation supported) and optionally netmask and returns the network in CIDR-notation. (The IP can be any IP inside the subnet) ''' if netmask is not None: ipaddr = '{0}/{1}'.format(ipaddr, netmask) return six.text_type(ipaddress.ip_network(ipaddr, strict=False)) def _ipv4_to_bits(ipaddr): ''' Accepts an IPv4 dotted quad and returns a string representing its binary counterpart ''' return ''.join([bin(int(x))[2:].rjust(8, '0') for x in ipaddr.split('.')]) def _get_iface_info(iface): ''' If `iface` is available, return interface info and no error, otherwise return no info and log and return an error ''' iface_info = interfaces() if iface in iface_info.keys(): return iface_info, False else: error_msg = ('Interface "{0}" not in available interfaces: "{1}"' ''.format(iface, '", "'.join(iface_info.keys()))) log.error(error_msg) return None, error_msg def _hw_addr_aix(iface): ''' Return the hardware address (a.k.a. MAC address) for a given interface on AIX MAC address not available in through interfaces ''' cmd = subprocess.Popen( 'entstat -d {0} | grep \'Hardware Address\''.format(iface), shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT).communicate()[0] if cmd: comps = cmd.split(' ') if len(comps) == 3: mac_addr = comps[2].strip('\'').strip() return mac_addr error_msg = ('Interface "{0}" either not available or does not contain a hardware address'.format(iface)) log.error(error_msg) return error_msg def hw_addr(iface): ''' Return the hardware address (a.k.a. MAC address) for a given interface .. versionchanged:: 2016.11.4 Added support for AIX ''' if salt.utils.platform.is_aix(): return _hw_addr_aix iface_info, error = _get_iface_info(iface) if error is False: return iface_info.get(iface, {}).get('hwaddr', '') else: return error def interface(iface): ''' Return the details of `iface` or an error if it does not exist ''' iface_info, error = _get_iface_info(iface) if error is False: return iface_info.get(iface, {}).get('inet', '') else: return error def interface_ip(iface): ''' Return `iface` IPv4 addr or an error if `iface` does not exist ''' iface_info, error = _get_iface_info(iface) if error is False: inet = iface_info.get(iface, {}).get('inet', None) return inet[0].get('address', '') if inet else '' else: return error def _subnets(proto='inet', interfaces_=None): ''' Returns a list of subnets to which the host belongs ''' if interfaces_ is None: ifaces = interfaces() elif isinstance(interfaces_, list): ifaces = {} for key, value in six.iteritems(interfaces()): if key in interfaces_: ifaces[key] = value else: ifaces = {interfaces_: interfaces().get(interfaces_, {})} ret = set() if proto == 'inet': subnet = 'netmask' dflt_cidr = 32 elif proto == 'inet6': subnet = 'prefixlen' dflt_cidr = 128 else: log.error('Invalid proto %s calling subnets()', proto) return for ip_info in six.itervalues(ifaces): addrs = ip_info.get(proto, []) addrs.extend([addr for addr in ip_info.get('secondary', []) if addr.get('type') == proto]) for intf in addrs: if subnet in intf: intf = ipaddress.ip_interface('{0}/{1}'.format(intf['address'], intf[subnet])) else: intf = ipaddress.ip_interface('{0}/{1}'.format(intf['address'], dflt_cidr)) if not intf.is_loopback: ret.add(intf.network) return [six.text_type(net) for net in sorted(ret)] def subnets(interfaces=None): ''' Returns a list of IPv4 subnets to which the host belongs ''' return _subnets('inet', interfaces_=interfaces) def subnets6(): ''' Returns a list of IPv6 subnets to which the host belongs ''' return _subnets('inet6') def in_subnet(cidr, addr=None): ''' Returns True if host or (any of) addrs is within specified subnet, otherwise False ''' try: cidr = ipaddress.ip_network(cidr) except ValueError: log.error('Invalid CIDR \'%s\'', cidr) return False if addr is None: addr = ip_addrs() addr.extend(ip_addrs6()) elif not isinstance(addr, (list, tuple)): addr = (addr,) return any(ipaddress.ip_address(item) in cidr for item in addr) def _ip_addrs(interface=None, include_loopback=False, interface_data=None, proto='inet'): ''' Return the full list of IP adresses matching the criteria proto = inet|inet6 ''' ret = set() ifaces = interface_data \ if isinstance(interface_data, dict) \ else interfaces() if interface is None: target_ifaces = ifaces else: target_ifaces = dict([(k, v) for k, v in six.iteritems(ifaces) if k == interface]) if not target_ifaces: log.error('Interface %s not found.', interface) for ip_info in six.itervalues(target_ifaces): addrs = ip_info.get(proto, []) addrs.extend([addr for addr in ip_info.get('secondary', []) if addr.get('type') == proto]) for addr in addrs: addr = ipaddress.ip_address(addr.get('address')) if not addr.is_loopback or include_loopback: ret.add(addr) return [six.text_type(addr) for addr in sorted(ret)] def ip_addrs(interface=None, include_loopback=False, interface_data=None): ''' Returns a list of IPv4 addresses assigned to the host. 127.0.0.1 is ignored, unless 'include_loopback=True' is indicated. If 'interface' is provided, then only IP addresses from that interface will be returned. ''' return _ip_addrs(interface, include_loopback, interface_data, 'inet') def ip_addrs6(interface=None, include_loopback=False, interface_data=None): ''' Returns a list of IPv6 addresses assigned to the host. ::1 is ignored, unless 'include_loopback=True' is indicated. If 'interface' is provided, then only IP addresses from that interface will be returned. ''' return _ip_addrs(interface, include_loopback, interface_data, 'inet6') def hex2ip(hex_ip, invert=False): ''' Convert a hex string to an ip, if a failure occurs the original hex is returned. If 'invert=True' assume that ip from /proc/net/<proto> ''' if len(hex_ip) == 32: # ipv6 ip = [] for i in range(0, 32, 8): ip_part = hex_ip[i:i + 8] ip_part = [ip_part[x:x + 2] for x in range(0, 8, 2)] if invert: ip.append("{0[3]}{0[2]}:{0[1]}{0[0]}".format(ip_part)) else: ip.append("{0[0]}{0[1]}:{0[2]}{0[3]}".format(ip_part)) try: address = ipaddress.IPv6Address(":".join(ip)) if address.ipv4_mapped: return str(address.ipv4_mapped) else: return address.compressed except ipaddress.AddressValueError as ex: log.error('hex2ip - ipv6 address error: %s', ex) return hex_ip try: hip = int(hex_ip, 16) except ValueError: return hex_ip if invert: return '{3}.{2}.{1}.{0}'.format(hip >> 24 & 255, hip >> 16 & 255, hip >> 8 & 255, hip & 255) return '{0}.{1}.{2}.{3}'.format(hip >> 24 & 255, hip >> 16 & 255, hip >> 8 & 255, hip & 255) def mac2eui64(mac, prefix=None): ''' Convert a MAC address to a EUI64 identifier or, with prefix provided, a full IPv6 address ''' # http://tools.ietf.org/html/rfc4291#section-2.5.1 eui64 = re.sub(r'[.:-]', '', mac).lower() eui64 = eui64[0:6] + 'fffe' + eui64[6:] eui64 = hex(int(eui64[0:2], 16) | 2)[2:].zfill(2) + eui64[2:] if prefix is None: return ':'.join(re.findall(r'.{4}', eui64)) else: try: net = ipaddress.ip_network(prefix, strict=False) euil = int('0x{0}'.format(eui64), 16) return '{0}/{1}'.format(net[euil], net.prefixlen) except Exception: return def active_tcp(): ''' Return a dict describing all active tcp connections as quickly as possible ''' ret = {} for statf in ['/proc/net/tcp', '/proc/net/tcp6']: if os.path.isfile(statf): with salt.utils.files.fopen(statf, 'rb') as fp_: for line in fp_: line = salt.utils.stringutils.to_unicode(line) if line.strip().startswith('sl'): continue iret = _parse_tcp_line(line) sl = next(iter(iret)) if iret[sl]['state'] == 1: # 1 is ESTABLISHED del iret[sl]['state'] ret[len(ret)] = iret[sl] return ret def local_port_tcp(port): ''' Return a set of remote ip addrs attached to the specified local port ''' ret = _remotes_on(port, 'local_port') return ret def remote_port_tcp(port): ''' Return a set of ip addrs the current host is connected to on given port ''' ret = _remotes_on(port, 'remote_port') return ret def _remotes_on(port, which_end): ''' Return a set of ip addrs active tcp connections ''' port = int(port) ret = _netlink_tool_remote_on(port, which_end) if ret is not None: return ret ret = set() proc_available = False for statf in ['/proc/net/tcp', '/proc/net/tcp6']: if os.path.isfile(statf): proc_available = True with salt.utils.files.fopen(statf, 'r') as fp_: for line in fp_: line = salt.utils.stringutils.to_unicode(line) if line.strip().startswith('sl'): continue iret = _parse_tcp_line(line) sl = next(iter(iret)) if iret[sl][which_end] == port and iret[sl]['state'] == 1: # 1 is ESTABLISHED ret.add(iret[sl]['remote_addr']) if not proc_available: # Fallback to use OS specific tools if salt.utils.platform.is_sunos(): return _sunos_remotes_on(port, which_end) if salt.utils.platform.is_freebsd(): return _freebsd_remotes_on(port, which_end) if salt.utils.platform.is_netbsd(): return _netbsd_remotes_on(port, which_end) if salt.utils.platform.is_openbsd(): return _openbsd_remotes_on(port, which_end) if salt.utils.platform.is_windows(): return _windows_remotes_on(port, which_end) if salt.utils.platform.is_aix(): return _aix_remotes_on(port, which_end) return _linux_remotes_on(port, which_end) return ret def _parse_tcp_line(line): ''' Parse a single line from the contents of /proc/net/tcp or /proc/net/tcp6 ''' ret = {} comps = line.strip().split() sl = comps[0].rstrip(':') ret[sl] = {} l_addr, l_port = comps[1].split(':') r_addr, r_port = comps[2].split(':') ret[sl]['local_addr'] = hex2ip(l_addr, True) ret[sl]['local_port'] = int(l_port, 16) ret[sl]['remote_addr'] = hex2ip(r_addr, True) ret[sl]['remote_port'] = int(r_port, 16) ret[sl]['state'] = int(comps[3], 16) return ret def _netlink_tool_remote_on(port, which_end): ''' Returns set of ipv4 host addresses of remote established connections on local or remote tcp port. Parses output of shell 'ss' to get connections [root@salt-master ~]# ss -ant State Recv-Q Send-Q Local Address:Port Peer Address:Port LISTEN 0 511 *:80 *:* LISTEN 0 128 *:22 *:* ESTAB 0 0 127.0.0.1:56726 127.0.0.1:4505 ''' remotes = set() valid = False try: data = subprocess.check_output(['ss', '-ant']) # pylint: disable=minimum-python-version except subprocess.CalledProcessError: log.error('Failed ss') raise except OSError: # not command "No such file or directory" return None lines = salt.utils.stringutils.to_str(data).split('\n') for line in lines: if 'Address:Port' in line: # ss tools may not be valid valid = True continue elif 'ESTAB' not in line: continue chunks = line.split() local_host, local_port = chunks[3].split(':', 1) remote_host, remote_port = chunks[4].split(':', 1) if which_end == 'remote_port' and int(remote_port) != port: continue if which_end == 'local_port' and int(local_port) != port: continue remotes.add(remote_host) if valid is False: remotes = None return remotes def _sunos_remotes_on(port, which_end): ''' SunOS specific helper function. Returns set of ipv4 host addresses of remote established connections on local or remote tcp port. Parses output of shell 'netstat' to get connections [root@salt-master ~]# netstat -f inet -n TCP: IPv4 Local Address Remote Address Swind Send-Q Rwind Recv-Q State -------------------- -------------------- ----- ------ ----- ------ ----------- 10.0.0.101.4505 10.0.0.1.45329 1064800 0 1055864 0 ESTABLISHED 10.0.0.101.4505 10.0.0.100.50798 1064800 0 1055864 0 ESTABLISHED ''' remotes = set() try: data = subprocess.check_output(['netstat', '-f', 'inet', '-n']) # pylint: disable=minimum-python-version except subprocess.CalledProcessError: log.error('Failed netstat') raise lines = salt.utils.stringutils.to_str(data).split('\n') for line in lines: if 'ESTABLISHED' not in line: continue chunks = line.split() local_host, local_port = chunks[0].rsplit('.', 1) remote_host, remote_port = chunks[1].rsplit('.', 1) if which_end == 'remote_port' and int(remote_port) != port: continue if which_end == 'local_port' and int(local_port) != port: continue remotes.add(remote_host) return remotes def _freebsd_remotes_on(port, which_end): ''' Returns set of ipv4 host addresses of remote established connections on local tcp port port. Parses output of shell 'sockstat' (FreeBSD) to get connections $ sudo sockstat -4 USER COMMAND PID FD PROTO LOCAL ADDRESS FOREIGN ADDRESS root python2.7 1456 29 tcp4 *:4505 *:* root python2.7 1445 17 tcp4 *:4506 *:* root python2.7 1294 14 tcp4 127.0.0.1:11813 127.0.0.1:4505 root python2.7 1294 41 tcp4 127.0.0.1:61115 127.0.0.1:4506 $ sudo sockstat -4 -c -p 4506 USER COMMAND PID FD PROTO LOCAL ADDRESS FOREIGN ADDRESS root python2.7 1294 41 tcp4 127.0.0.1:61115 127.0.0.1:4506 ''' port = int(port) remotes = set() try: cmd = salt.utils.args.shlex_split('sockstat -4 -c -p {0}'.format(port)) data = subprocess.check_output(cmd) # pylint: disable=minimum-python-version except subprocess.CalledProcessError as ex: log.error('Failed "sockstat" with returncode = %s', ex.returncode) raise lines = salt.utils.stringutils.to_str(data).split('\n') for line in lines: chunks = line.split() if not chunks: continue # ['root', 'python2.7', '1456', '37', 'tcp4', # '127.0.0.1:4505-', '127.0.0.1:55703'] # print chunks if 'COMMAND' in chunks[1]: continue # ignore header if len(chunks) < 2: continue # sockstat -4 -c -p 4506 does this with high PIDs: # USER COMMAND PID FD PROTO LOCAL ADDRESS FOREIGN ADDRESS # salt-master python2.781106 35 tcp4 192.168.12.34:4506 192.168.12.45:60143 local = chunks[-2] remote = chunks[-1] lhost, lport = local.split(':') rhost, rport = remote.split(':') if which_end == 'local' and int(lport) != port: # ignore if local port not port continue if which_end == 'remote' and int(rport) != port: # ignore if remote port not port continue remotes.add(rhost) return remotes def _netbsd_remotes_on(port, which_end): ''' Returns set of ipv4 host addresses of remote established connections on local tcp port port. Parses output of shell 'sockstat' (NetBSD) to get connections $ sudo sockstat -4 -n USER COMMAND PID FD PROTO LOCAL ADDRESS FOREIGN ADDRESS root python2.7 1456 29 tcp *.4505 *.* root python2.7 1445 17 tcp *.4506 *.* root python2.7 1294 14 tcp 127.0.0.1.11813 127.0.0.1.4505 root python2.7 1294 41 tcp 127.0.0.1.61115 127.0.0.1.4506 $ sudo sockstat -4 -c -n -p 4506 USER COMMAND PID FD PROTO LOCAL ADDRESS FOREIGN ADDRESS root python2.7 1294 41 tcp 127.0.0.1.61115 127.0.0.1.4506 ''' port = int(port) remotes = set() try: cmd = salt.utils.args.shlex_split('sockstat -4 -c -n -p {0}'.format(port)) data = subprocess.check_output(cmd) # pylint: disable=minimum-python-version except subprocess.CalledProcessError as ex: log.error('Failed "sockstat" with returncode = %s', ex.returncode) raise lines = salt.utils.stringutils.to_str(data).split('\n') for line in lines: chunks = line.split() if not chunks: continue # ['root', 'python2.7', '1456', '37', 'tcp', # '127.0.0.1.4505-', '127.0.0.1.55703'] # print chunks if 'COMMAND' in chunks[1]: continue # ignore header if len(chunks) < 2: continue local = chunks[5].split('.') lport = local.pop() lhost = '.'.join(local) remote = chunks[6].split('.') rport = remote.pop() rhost = '.'.join(remote) if which_end == 'local' and int(lport) != port: # ignore if local port not port continue if which_end == 'remote' and int(rport) != port: # ignore if remote port not port continue remotes.add(rhost) return remotes def _openbsd_remotes_on(port, which_end): ''' OpenBSD specific helper function. Returns set of ipv4 host addresses of remote established connections on local or remote tcp port. Parses output of shell 'netstat' to get connections $ netstat -nf inet Active Internet connections Proto Recv-Q Send-Q Local Address Foreign Address (state) tcp 0 0 10.0.0.101.4505 10.0.0.1.45329 ESTABLISHED tcp 0 0 10.0.0.101.4505 10.0.0.100.50798 ESTABLISHED ''' remotes = set() try: data = subprocess.check_output(['netstat', '-nf', 'inet']) # pylint: disable=minimum-python-version except subprocess.CalledProcessError: log.error('Failed netstat') raise lines = data.split('\n') for line in lines: if 'ESTABLISHED' not in line: continue chunks = line.split() local_host, local_port = chunks[3].rsplit('.', 1) remote_host, remote_port = chunks[4].rsplit('.', 1) if which_end == 'remote_port' and int(remote_port) != port: continue if which_end == 'local_port' and int(local_port) != port: continue remotes.add(remote_host) return remotes def _windows_remotes_on(port, which_end): r''' Windows specific helper function. Returns set of ipv4 host addresses of remote established connections on local or remote tcp port. Parses output of shell 'netstat' to get connections C:\>netstat -n Active Connections Proto Local Address Foreign Address State TCP 10.2.33.17:3007 130.164.12.233:10123 ESTABLISHED TCP 10.2.33.17:3389 130.164.30.5:10378 ESTABLISHED ''' remotes = set() try: data = subprocess.check_output(['netstat', '-n']) # pylint: disable=minimum-python-version except subprocess.CalledProcessError: log.error('Failed netstat') raise lines = salt.utils.stringutils.to_str(data).split('\n') for line in lines: if 'ESTABLISHED' not in line: continue chunks = line.split() local_host, local_port = chunks[1].rsplit(':', 1) remote_host, remote_port = chunks[2].rsplit(':', 1) if which_end == 'remote_port' and int(remote_port) != port: continue if which_end == 'local_port' and int(local_port) != port: continue remotes.add(remote_host) return remotes def _linux_remotes_on(port, which_end): ''' Linux specific helper function. Returns set of ip host addresses of remote established connections on local tcp port port. Parses output of shell 'lsof' to get connections $ sudo lsof -iTCP:4505 -n COMMAND PID USER FD TYPE DEVICE SIZE/OFF NODE NAME Python 9971 root 35u IPv4 0x18a8464a29ca329d 0t0 TCP *:4505 (LISTEN) Python 9971 root 37u IPv4 0x18a8464a29b2b29d 0t0 TCP 127.0.0.1:4505->127.0.0.1:55703 (ESTABLISHED) Python 10152 root 22u IPv4 0x18a8464a29c8cab5 0t0 TCP 127.0.0.1:55703->127.0.0.1:4505 (ESTABLISHED) Python 10153 root 22u IPv4 0x18a8464a29c8cab5 0t0 TCP [fe80::249a]:4505->[fe80::150]:59367 (ESTABLISHED) ''' remotes = set() try: data = subprocess.check_output( ['lsof', '-iTCP:{0:d}'.format(port), '-n', '-P'] # pylint: disable=minimum-python-version ) except subprocess.CalledProcessError as ex: if ex.returncode == 1: # Lsof return 1 if any error was detected, including the failure # to locate Internet addresses, and it is not an error in this case. log.warning('"lsof" returncode = 1, likely no active TCP sessions.') return remotes log.error('Failed "lsof" with returncode = %s', ex.returncode) raise lines = salt.utils.stringutils.to_str(data).split('\n') for line in lines: chunks = line.split() if not chunks: continue # ['Python', '9971', 'root', '37u', 'IPv4', '0x18a8464a29b2b29d', '0t0', # 'TCP', '127.0.0.1:4505->127.0.0.1:55703', '(ESTABLISHED)'] # print chunks if 'COMMAND' in chunks[0]: continue # ignore header if 'ESTABLISHED' not in chunks[-1]: continue # ignore if not ESTABLISHED # '127.0.0.1:4505->127.0.0.1:55703' local, remote = chunks[8].split('->') _, lport = local.rsplit(':', 1) rhost, rport = remote.rsplit(':', 1) if which_end == 'remote_port' and int(rport) != port: continue if which_end == 'local_port' and int(lport) != port: continue remotes.add(rhost.strip("[]")) return remotes def _aix_remotes_on(port, which_end): ''' AIX specific helper function. Returns set of ipv4 host addresses of remote established connections on local or remote tcp port. Parses output of shell 'netstat' to get connections root@la68pp002_pub:/opt/salt/lib/python2.7/site-packages/salt/modules# netstat -f inet -n Active Internet connections Proto Recv-Q Send-Q Local Address Foreign Address (state) tcp4 0 0 172.29.149.95.50093 209.41.78.13.4505 ESTABLISHED tcp4 0 0 127.0.0.1.9514 *.* LISTEN tcp4 0 0 127.0.0.1.9515 *.* LISTEN tcp4 0 0 127.0.0.1.199 127.0.0.1.32779 ESTABLISHED tcp4 0 0 127.0.0.1.32779 127.0.0.1.199 ESTABLISHED tcp4 0 40 172.29.149.95.22 172.29.96.83.41022 ESTABLISHED tcp4 0 0 172.29.149.95.22 172.29.96.83.41032 ESTABLISHED tcp4 0 0 127.0.0.1.32771 127.0.0.1.32775 ESTABLISHED tcp 0 0 127.0.0.1.32775 127.0.0.1.32771 ESTABLISHED tcp4 0 0 127.0.0.1.32771 127.0.0.1.32776 ESTABLISHED tcp 0 0 127.0.0.1.32776 127.0.0.1.32771 ESTABLISHED tcp4 0 0 127.0.0.1.32771 127.0.0.1.32777 ESTABLISHED tcp 0 0 127.0.0.1.32777 127.0.0.1.32771 ESTABLISHED tcp4 0 0 127.0.0.1.32771 127.0.0.1.32778 ESTABLISHED tcp 0 0 127.0.0.1.32778 127.0.0.1.32771 ESTABLISHED ''' remotes = set() try: data = subprocess.check_output(['netstat', '-f', 'inet', '-n']) # pylint: disable=minimum-python-version except subprocess.CalledProcessError: log.error('Failed netstat') raise lines = salt.utils.stringutils.to_str(data).split('\n') for line in lines: if 'ESTABLISHED' not in line: continue chunks = line.split() local_host, local_port = chunks[3].rsplit('.', 1) remote_host, remote_port = chunks[4].rsplit('.', 1) if which_end == 'remote_port' and int(remote_port) != port: continue if which_end == 'local_port' and int(local_port) != port: continue remotes.add(remote_host) return remotes @jinja_filter('gen_mac') def gen_mac(prefix='AC:DE:48'): ''' Generates a MAC address with the defined OUI prefix. Common prefixes: - ``00:16:3E`` -- Xen - ``00:18:51`` -- OpenVZ - ``00:50:56`` -- VMware (manually generated) - ``52:54:00`` -- QEMU/KVM - ``AC:DE:48`` -- PRIVATE References: - http://standards.ieee.org/develop/regauth/oui/oui.txt - https://www.wireshark.org/tools/oui-lookup.html - https://en.wikipedia.org/wiki/MAC_address ''' return '{0}:{1:02X}:{2:02X}:{3:02X}'.format(prefix, random.randint(0, 0xff), random.randint(0, 0xff), random.randint(0, 0xff)) @jinja_filter('mac_str_to_bytes') def mac_str_to_bytes(mac_str): ''' Convert a MAC address string into bytes. Works with or without separators: b1 = mac_str_to_bytes('08:00:27:13:69:77') b2 = mac_str_to_bytes('080027136977') assert b1 == b2 assert isinstance(b1, bytes) ''' if len(mac_str) == 12: pass elif len(mac_str) == 17: sep = mac_str[2] mac_str = mac_str.replace(sep, '') else: raise ValueError('Invalid MAC address') chars = (int(mac_str[s:s+2], 16) for s in range(0, 12, 2)) return bytes(chars) if six.PY3 else b''.join(chr(x) for x in chars) def refresh_dns(): ''' issue #21397: force glibc to re-read resolv.conf ''' try: res_init() except NameError: # Exception raised loading the library, thus res_init is not defined pass @jinja_filter('connection_check') def connection_check(addr, port=80, safe=False, ipv6=None): ''' Provides a convenient alias for the dns_check filter. ''' return dns_check(addr, port, safe, ipv6) @jinja_filter('dns_check') def dns_check(addr, port=80, safe=False, ipv6=None, attempt_connect=True): ''' Return the ip resolved by dns, but do not exit on failure, only raise an exception. Obeys system preference for IPv4/6 address resolution - this can be overridden by the ipv6 flag. Tries to connect to the address before considering it useful. If no address can be reached, the first one resolved is used as a fallback. ''' error = False lookup = addr seen_ipv6 = False family = socket.AF_INET6 if ipv6 else socket.AF_INET if ipv6 is False else socket.AF_UNSPEC hostnames = [] try: refresh_dns() hostnames = socket.getaddrinfo(addr, port, family, socket.SOCK_STREAM) except TypeError: err = ('Attempt to resolve address \'{0}\' failed. Invalid or unresolveable address').format(lookup) raise SaltSystemExit(code=42, msg=err) except socket.error: error = True # If ipv6 is set to True, attempt another lookup using the IPv4 family, # just in case we're attempting to lookup an IPv4 IP # as an IPv6 hostname. if error and ipv6: try: refresh_dns() hostnames = socket.getaddrinfo(addr, port, socket.AF_INET, socket.SOCK_STREAM) except TypeError: err = ('Attempt to resolve address \'{0}\' failed. Invalid or unresolveable address').format(lookup) raise SaltSystemExit(code=42, msg=err) except socket.error: error = True try: if not hostnames: error = True else: resolved = False candidates = [] for h in hostnames: # Input is IP address, passed through unchanged, just return it if h[4][0] == addr: resolved = salt.utils.zeromq.ip_bracket(addr) break candidate_addr = salt.utils.zeromq.ip_bracket(h[4][0]) # sometimes /etc/hosts contains ::1 localhost if not ipv6 and candidate_addr == '[::1]': continue candidates.append(candidate_addr) if attempt_connect: try: s = socket.socket(h[0], socket.SOCK_STREAM) s.settimeout(2) s.connect((candidate_addr.strip('[]'), h[4][1])) s.close() resolved = candidate_addr break except socket.error: pass if not resolved: if candidates: resolved = candidates[0] else: error = True except TypeError: err = ('Attempt to resolve address \'{0}\' failed. Invalid or unresolveable address').format(lookup) raise SaltSystemExit(code=42, msg=err) except socket.error: error = True if error: err = ('DNS lookup or connection check of \'{0}\' failed.').format(addr) if safe: if salt.log.is_console_configured(): # If logging is not configured it also means that either # the master or minion instance calling this hasn't even # started running log.error(err) raise SaltClientError() raise SaltSystemExit(code=42, msg=err) return resolved def parse_host_port(host_port): """ Takes a string argument specifying host or host:port. Returns a (hostname, port) or (ip_address, port) tuple. If no port is given, the second (port) element of the returned tuple will be None. host:port argument, for example, is accepted in the forms of: - hostname - hostname:1234 - hostname.domain.tld - hostname.domain.tld:5678 - [1234::5]:5678 - 1234::5 - 10.11.12.13:4567 - 10.11.12.13 """ host, port = None, None # default _s_ = host_port[:] if _s_[0] == "[": if "]" in host_port: host, _s_ = _s_.lstrip("[").rsplit("]", 1) host = ipaddress.IPv6Address(host).compressed if _s_[0] == ":": port = int(_s_.lstrip(":")) else: if len(_s_) > 1: raise ValueError('found ambiguous "{}" port in "{}"'.format(_s_, host_port)) else: if _s_.count(":") == 1: host, _hostport_separator_, port = _s_.partition(":") try: port = int(port) except ValueError as _e_: log.error('host_port "%s" port value "%s" is not an integer.', host_port, port) raise _e_ else: host = _s_ try: if not isinstance(host, ipaddress._BaseAddress): host_ip = ipaddress.ip_address(host).compressed host = host_ip except ValueError: log.debug('"%s" Not an IP address? Assuming it is a hostname.', host) if host != sanitize_host(host): log.error('bad hostname: "%s"', host) raise ValueError('bad hostname: "{}"'.format(host)) return host, port def is_fqdn(hostname): """ Verify if hostname conforms to be a FQDN. :param hostname: text string with the name of the host :return: bool, True if hostname is correct FQDN, False otherwise """ compliant = re.compile(r"(?!-)[A-Z\d\-\_]{1,63}(?<!-)$", re.IGNORECASE) return "." in hostname and len(hostname) < 0xff and all(compliant.match(x) for x in hostname.rstrip(".").split("."))
saltstack/salt
salt/utils/network.py
netbsd_interfaces
python
def netbsd_interfaces(): ''' Obtain interface information for NetBSD >= 8 where the ifconfig output diverged from other BSD variants (Netmask is now part of the address) ''' # NetBSD versions prior to 8.0 can still use linux_interfaces() if LooseVersion(os.uname()[2]) < LooseVersion('8.0'): return linux_interfaces() ifconfig_path = salt.utils.path.which('ifconfig') cmd = subprocess.Popen( '{0} -a'.format(ifconfig_path), shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT).communicate()[0] return _netbsd_interfaces_ifconfig(salt.utils.stringutils.to_str(cmd))
Obtain interface information for NetBSD >= 8 where the ifconfig output diverged from other BSD variants (Netmask is now part of the address)
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/network.py#L937-L953
null
# -*- coding: utf-8 -*- ''' Define some generic socket functions for network modules ''' # Import python libs from __future__ import absolute_import, unicode_literals, print_function import itertools import os import re import types import socket import logging import platform import random import subprocess from string import ascii_letters, digits # Import 3rd-party libs from salt.ext import six from salt.ext.six.moves import range # pylint: disable=import-error,redefined-builtin # Attempt to import wmi try: import wmi import salt.utils.winapi except ImportError: pass # Import salt libs import salt.utils.args import salt.utils.files import salt.utils.path import salt.utils.platform import salt.utils.stringutils import salt.utils.zeromq from salt._compat import ipaddress from salt.exceptions import SaltClientError, SaltSystemExit from salt.utils.decorators.jinja import jinja_filter from salt.utils.versions import LooseVersion # inet_pton does not exist in Windows, this is a workaround if salt.utils.platform.is_windows(): from salt.ext import win_inet_pton # pylint: disable=unused-import log = logging.getLogger(__name__) try: import ctypes import ctypes.util libc = ctypes.cdll.LoadLibrary(ctypes.util.find_library("c")) res_init = libc.__res_init except (ImportError, OSError, AttributeError, TypeError): pass # pylint: disable=C0103 def sanitize_host(host): ''' Sanitize host string. https://tools.ietf.org/html/rfc1123#section-2.1 ''' RFC952_characters = ascii_letters + digits + ".-" return "".join([c for c in host[0:255] if c in RFC952_characters]) def isportopen(host, port): ''' Return status of a port ''' if not 1 <= int(port) <= 65535: return False sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) out = sock.connect_ex((sanitize_host(host), int(port))) return out def host_to_ips(host): ''' Returns a list of IP addresses of a given hostname or None if not found. ''' ips = [] try: for family, socktype, proto, canonname, sockaddr in socket.getaddrinfo( host, 0, socket.AF_UNSPEC, socket.SOCK_STREAM): if family == socket.AF_INET: ip, port = sockaddr elif family == socket.AF_INET6: ip, port, flow_info, scope_id = sockaddr ips.append(ip) if not ips: ips = None except Exception: ips = None return ips def _generate_minion_id(): ''' Get list of possible host names and convention names. :return: ''' # There are three types of hostnames: # 1. Network names. How host is accessed from the network. # 2. Host aliases. They might be not available in all the network or only locally (/etc/hosts) # 3. Convention names, an internal nodename. class DistinctList(list): ''' List, which allows one to append only distinct objects. Needs to work on Python 2.6, because of collections.OrderedDict only since 2.7 version. Override 'filter()' for custom filtering. ''' localhost_matchers = [r'localhost.*', r'ip6-.*', r'127[.]\d', r'0\.0\.0\.0', r'::1.*', r'ipv6-.*', r'fe00::.*', r'fe02::.*', r'1.0.0.*.ip6.arpa'] def append(self, p_object): if p_object and p_object not in self and not self.filter(p_object): super(DistinctList, self).append(p_object) return self def extend(self, iterable): for obj in iterable: self.append(obj) return self def filter(self, element): 'Returns True if element needs to be filtered' for rgx in self.localhost_matchers: if re.match(rgx, element): return True def first(self): return self and self[0] or None hostname = socket.gethostname() hosts = DistinctList().append( salt.utils.stringutils.to_unicode(socket.getfqdn(salt.utils.stringutils.to_bytes(hostname))) ).append(platform.node()).append(hostname) if not hosts: try: for a_nfo in socket.getaddrinfo(hosts.first() or 'localhost', None, socket.AF_INET, socket.SOCK_RAW, socket.IPPROTO_IP, socket.AI_CANONNAME): if len(a_nfo) > 3: hosts.append(a_nfo[3]) except socket.gaierror: log.warning('Cannot resolve address %s info via socket: %s', hosts.first() or 'localhost (N/A)', socket.gaierror) # Universal method for everywhere (Linux, Slowlaris, Windows etc) for f_name in ('/etc/hostname', '/etc/nodename', '/etc/hosts', r'{win}\system32\drivers\etc\hosts'.format(win=os.getenv('WINDIR'))): try: with salt.utils.files.fopen(f_name) as f_hdl: for line in f_hdl: line = salt.utils.stringutils.to_unicode(line) hst = line.strip().split('#')[0].strip().split() if hst: if hst[0][:4] in ('127.', '::1') or len(hst) == 1: hosts.extend(hst) except IOError: pass # include public and private ipaddresses return hosts.extend([addr for addr in ip_addrs() if not ipaddress.ip_address(addr).is_loopback]) def generate_minion_id(): ''' Return only first element of the hostname from all possible list. :return: ''' try: ret = salt.utils.stringutils.to_unicode(_generate_minion_id().first()) except TypeError: ret = None return ret or 'localhost' def get_socket(addr, type=socket.SOCK_STREAM, proto=0): ''' Return a socket object for the addr IP-version agnostic ''' version = ipaddress.ip_address(addr).version if version == 4: family = socket.AF_INET elif version == 6: family = socket.AF_INET6 return socket.socket(family, type, proto) def get_fqhostname(): ''' Returns the fully qualified hostname ''' # try getaddrinfo() fqdn = None try: addrinfo = socket.getaddrinfo( socket.gethostname(), 0, socket.AF_UNSPEC, socket.SOCK_STREAM, socket.SOL_TCP, socket.AI_CANONNAME ) for info in addrinfo: # info struct [family, socktype, proto, canonname, sockaddr] # On Windows `canonname` can be an empty string # This can cause the function to return `None` if len(info) > 3 and info[3]: fqdn = info[3] break except socket.gaierror: pass # NOTE: this used to log.error() but it was later disabled except socket.error as err: log.debug('socket.getaddrinfo() failure while finding fqdn: %s', err) if fqdn is None: fqdn = socket.getfqdn() return fqdn def ip_to_host(ip): ''' Returns the hostname of a given IP ''' try: hostname, aliaslist, ipaddrlist = socket.gethostbyaddr(ip) except Exception as exc: log.debug('salt.utils.network.ip_to_host(%r) failed: %s', ip, exc) hostname = None return hostname # pylint: enable=C0103 def is_reachable_host(entity_name): ''' Returns a bool telling if the entity name is a reachable host (IPv4/IPv6/FQDN/etc). :param hostname: :return: ''' try: assert type(socket.getaddrinfo(entity_name, 0, 0, 0, 0)) == list ret = True except socket.gaierror: ret = False return ret def is_ip(ip): ''' Returns a bool telling if the passed IP is a valid IPv4 or IPv6 address. ''' return is_ipv4(ip) or is_ipv6(ip) def is_ipv4(ip): ''' Returns a bool telling if the value passed to it was a valid IPv4 address ''' try: return ipaddress.ip_address(ip).version == 4 except ValueError: return False def is_ipv6(ip): ''' Returns a bool telling if the value passed to it was a valid IPv6 address ''' try: return ipaddress.ip_address(ip).version == 6 except ValueError: return False def is_subnet(cidr): ''' Returns a bool telling if the passed string is an IPv4 or IPv6 subnet ''' return is_ipv4_subnet(cidr) or is_ipv6_subnet(cidr) def is_ipv4_subnet(cidr): ''' Returns a bool telling if the passed string is an IPv4 subnet ''' try: return '/' in cidr and bool(ipaddress.IPv4Network(cidr)) except Exception: return False def is_ipv6_subnet(cidr): ''' Returns a bool telling if the passed string is an IPv6 subnet ''' try: return '/' in cidr and bool(ipaddress.IPv6Network(cidr)) except Exception: return False @jinja_filter('is_ip') def is_ip_filter(ip, options=None): ''' Returns a bool telling if the passed IP is a valid IPv4 or IPv6 address. ''' return is_ipv4_filter(ip, options=options) or is_ipv6_filter(ip, options=options) def _ip_options_global(ip_obj, version): return not ip_obj.is_private def _ip_options_multicast(ip_obj, version): return ip_obj.is_multicast def _ip_options_loopback(ip_obj, version): return ip_obj.is_loopback def _ip_options_link_local(ip_obj, version): return ip_obj.is_link_local def _ip_options_private(ip_obj, version): return ip_obj.is_private def _ip_options_reserved(ip_obj, version): return ip_obj.is_reserved def _ip_options_site_local(ip_obj, version): if version == 6: return ip_obj.is_site_local return False def _ip_options_unspecified(ip_obj, version): return ip_obj.is_unspecified def _ip_options(ip_obj, version, options=None): # will process and IP options options_fun_map = { 'global': _ip_options_global, 'link-local': _ip_options_link_local, 'linklocal': _ip_options_link_local, 'll': _ip_options_link_local, 'link_local': _ip_options_link_local, 'loopback': _ip_options_loopback, 'lo': _ip_options_loopback, 'multicast': _ip_options_multicast, 'private': _ip_options_private, 'public': _ip_options_global, 'reserved': _ip_options_reserved, 'site-local': _ip_options_site_local, 'sl': _ip_options_site_local, 'site_local': _ip_options_site_local, 'unspecified': _ip_options_unspecified } if not options: return six.text_type(ip_obj) # IP version already checked options_list = [option.strip() for option in options.split(',')] for option, fun in options_fun_map.items(): if option in options_list: fun_res = fun(ip_obj, version) if not fun_res: return None # stop at first failed test # else continue return six.text_type(ip_obj) def _is_ipv(ip, version, options=None): if not version: version = 4 if version not in (4, 6): return None try: ip_obj = ipaddress.ip_address(ip) except ValueError: # maybe it is an IP network try: ip_obj = ipaddress.ip_interface(ip) except ValueError: # nope, still not :( return None if not ip_obj.version == version: return None # has the right version, let's move on return _ip_options(ip_obj, version, options=options) @jinja_filter('is_ipv4') def is_ipv4_filter(ip, options=None): ''' Returns a bool telling if the value passed to it was a valid IPv4 address. ip The IP address. net: False Consider IP addresses followed by netmask. options CSV of options regarding the nature of the IP address. E.g.: loopback, multicast, private etc. ''' _is_ipv4 = _is_ipv(ip, 4, options=options) return isinstance(_is_ipv4, six.string_types) @jinja_filter('is_ipv6') def is_ipv6_filter(ip, options=None): ''' Returns a bool telling if the value passed to it was a valid IPv6 address. ip The IP address. net: False Consider IP addresses followed by netmask. options CSV of options regarding the nature of the IP address. E.g.: loopback, multicast, private etc. ''' _is_ipv6 = _is_ipv(ip, 6, options=options) return isinstance(_is_ipv6, six.string_types) def _ipv_filter(value, version, options=None): if version not in (4, 6): return if isinstance(value, (six.string_types, six.text_type, six.binary_type)): return _is_ipv(value, version, options=options) # calls is_ipv4 or is_ipv6 for `value` elif isinstance(value, (list, tuple, types.GeneratorType)): # calls is_ipv4 or is_ipv6 for each element in the list # os it filters and returns only those elements having the desired IP version return [ _is_ipv(addr, version, options=options) for addr in value if _is_ipv(addr, version, options=options) is not None ] return None @jinja_filter('ipv4') def ipv4(value, options=None): ''' Filters a list and returns IPv4 values only. ''' return _ipv_filter(value, 4, options=options) @jinja_filter('ipv6') def ipv6(value, options=None): ''' Filters a list and returns IPv6 values only. ''' return _ipv_filter(value, 6, options=options) @jinja_filter('ipaddr') def ipaddr(value, options=None): ''' Filters and returns only valid IP objects. ''' ipv4_obj = ipv4(value, options=options) ipv6_obj = ipv6(value, options=options) if ipv4_obj is None or ipv6_obj is None: # an IP address can be either IPv4 either IPv6 # therefofe if the value passed as arg is not a list, at least one of the calls above will return None # if one of them is none, means that we should return only one of them return ipv4_obj or ipv6_obj # one of them else: return ipv4_obj + ipv6_obj # extend lists def _filter_ipaddr(value, options, version=None): ipaddr_filter_out = None if version: if version == 4: ipaddr_filter_out = ipv4(value, options) elif version == 6: ipaddr_filter_out = ipv6(value, options) else: ipaddr_filter_out = ipaddr(value, options) if not ipaddr_filter_out: return if not isinstance(ipaddr_filter_out, (list, tuple, types.GeneratorType)): ipaddr_filter_out = [ipaddr_filter_out] return ipaddr_filter_out @jinja_filter('ip_host') def ip_host(value, options=None, version=None): ''' Returns the interfaces IP address, e.g.: 192.168.0.1/28. ''' ipaddr_filter_out = _filter_ipaddr(value, options=options, version=version) if not ipaddr_filter_out: return if not isinstance(value, (list, tuple, types.GeneratorType)): return six.text_type(ipaddress.ip_interface(ipaddr_filter_out[0])) return [six.text_type(ipaddress.ip_interface(ip_a)) for ip_a in ipaddr_filter_out] def _network_hosts(ip_addr_entry): return [ six.text_type(host) for host in ipaddress.ip_network(ip_addr_entry, strict=False).hosts() ] @jinja_filter('network_hosts') def network_hosts(value, options=None, version=None): ''' Return the list of hosts within a network. .. note:: When running this command with a large IPv6 network, the command will take a long time to gather all of the hosts. ''' ipaddr_filter_out = _filter_ipaddr(value, options=options, version=version) if not ipaddr_filter_out: return if not isinstance(value, (list, tuple, types.GeneratorType)): return _network_hosts(ipaddr_filter_out[0]) return [ _network_hosts(ip_a) for ip_a in ipaddr_filter_out ] def _network_size(ip_addr_entry): return ipaddress.ip_network(ip_addr_entry, strict=False).num_addresses @jinja_filter('network_size') def network_size(value, options=None, version=None): ''' Get the size of a network. ''' ipaddr_filter_out = _filter_ipaddr(value, options=options, version=version) if not ipaddr_filter_out: return if not isinstance(value, (list, tuple, types.GeneratorType)): return _network_size(ipaddr_filter_out[0]) return [ _network_size(ip_a) for ip_a in ipaddr_filter_out ] def natural_ipv4_netmask(ip, fmt='prefixlen'): ''' Returns the "natural" mask of an IPv4 address ''' bits = _ipv4_to_bits(ip) if bits.startswith('11'): mask = '24' elif bits.startswith('1'): mask = '16' else: mask = '8' if fmt == 'netmask': return cidr_to_ipv4_netmask(mask) else: return '/' + mask def rpad_ipv4_network(ip): ''' Returns an IP network address padded with zeros. Ex: '192.168.3' -> '192.168.3.0' '10.209' -> '10.209.0.0' ''' return '.'.join(itertools.islice(itertools.chain(ip.split('.'), '0000'), 0, 4)) def cidr_to_ipv4_netmask(cidr_bits): ''' Returns an IPv4 netmask ''' try: cidr_bits = int(cidr_bits) if not 1 <= cidr_bits <= 32: return '' except ValueError: return '' netmask = '' for idx in range(4): if idx: netmask += '.' if cidr_bits >= 8: netmask += '255' cidr_bits -= 8 else: netmask += '{0:d}'.format(256 - (2 ** (8 - cidr_bits))) cidr_bits = 0 return netmask def _number_of_set_bits_to_ipv4_netmask(set_bits): # pylint: disable=C0103 ''' Returns an IPv4 netmask from the integer representation of that mask. Ex. 0xffffff00 -> '255.255.255.0' ''' return cidr_to_ipv4_netmask(_number_of_set_bits(set_bits)) # pylint: disable=C0103 def _number_of_set_bits(x): ''' Returns the number of bits that are set in a 32bit int ''' # Taken from http://stackoverflow.com/a/4912729. Many thanks! x -= (x >> 1) & 0x55555555 x = ((x >> 2) & 0x33333333) + (x & 0x33333333) x = ((x >> 4) + x) & 0x0f0f0f0f x += x >> 8 x += x >> 16 return x & 0x0000003f # pylint: enable=C0103 def _interfaces_ip(out): ''' Uses ip to return a dictionary of interfaces with various information about each (up/down state, ip address, netmask, and hwaddr) ''' ret = dict() def parse_network(value, cols): ''' Return a tuple of ip, netmask, broadcast based on the current set of cols ''' brd = None scope = None if '/' in value: # we have a CIDR in this address ip, cidr = value.split('/') # pylint: disable=C0103 else: ip = value # pylint: disable=C0103 cidr = 32 if type_ == 'inet': mask = cidr_to_ipv4_netmask(int(cidr)) if 'brd' in cols: brd = cols[cols.index('brd') + 1] elif type_ == 'inet6': mask = cidr if 'scope' in cols: scope = cols[cols.index('scope') + 1] return (ip, mask, brd, scope) groups = re.compile('\r?\n\\d').split(out) for group in groups: iface = None data = dict() for line in group.splitlines(): if ' ' not in line: continue match = re.match(r'^\d*:\s+([\w.\-]+)(?:@)?([\w.\-]+)?:\s+<(.+)>', line) if match: iface, parent, attrs = match.groups() if 'UP' in attrs.split(','): data['up'] = True else: data['up'] = False if parent: data['parent'] = parent continue cols = line.split() if len(cols) >= 2: type_, value = tuple(cols[0:2]) iflabel = cols[-1:][0] if type_ in ('inet', 'inet6'): if 'secondary' not in cols: ipaddr, netmask, broadcast, scope = parse_network(value, cols) if type_ == 'inet': if 'inet' not in data: data['inet'] = list() addr_obj = dict() addr_obj['address'] = ipaddr addr_obj['netmask'] = netmask addr_obj['broadcast'] = broadcast addr_obj['label'] = iflabel data['inet'].append(addr_obj) elif type_ == 'inet6': if 'inet6' not in data: data['inet6'] = list() addr_obj = dict() addr_obj['address'] = ipaddr addr_obj['prefixlen'] = netmask addr_obj['scope'] = scope data['inet6'].append(addr_obj) else: if 'secondary' not in data: data['secondary'] = list() ip_, mask, brd, scp = parse_network(value, cols) data['secondary'].append({ 'type': type_, 'address': ip_, 'netmask': mask, 'broadcast': brd, 'label': iflabel, }) del ip_, mask, brd, scp elif type_.startswith('link'): data['hwaddr'] = value if iface: ret[iface] = data del iface, data return ret def _interfaces_ifconfig(out): ''' Uses ifconfig to return a dictionary of interfaces with various information about each (up/down state, ip address, netmask, and hwaddr) ''' ret = dict() piface = re.compile(r'^([^\s:]+)') pmac = re.compile('.*?(?:HWaddr|ether|address:|lladdr) ([0-9a-fA-F:]+)') if salt.utils.platform.is_sunos(): pip = re.compile(r'.*?(?:inet\s+)([0-9]+\.[0-9]+\.[0-9]+\.[0-9]+)(.*)') pip6 = re.compile('.*?(?:inet6 )([0-9a-fA-F:]+)') pmask6 = re.compile(r'.*?(?:inet6 [0-9a-fA-F:]+/(\d+)).*') else: pip = re.compile(r'.*?(?:inet addr:|inet [^\d]*)(.*?)\s') pip6 = re.compile('.*?(?:inet6 addr: (.*?)/|inet6 )([0-9a-fA-F:]+)') pmask6 = re.compile(r'.*?(?:inet6 addr: [0-9a-fA-F:]+/(\d+)|prefixlen (\d+))(?: Scope:([a-zA-Z]+)| scopeid (0x[0-9a-fA-F]))?') pmask = re.compile(r'.*?(?:Mask:|netmask )(?:((?:0x)?[0-9a-fA-F]{8})|([\d\.]+))') pupdown = re.compile('UP') pbcast = re.compile(r'.*?(?:Bcast:|broadcast )([\d\.]+)') groups = re.compile('\r?\n(?=\\S)').split(out) for group in groups: data = dict() iface = '' updown = False for line in group.splitlines(): miface = piface.match(line) mmac = pmac.match(line) mip = pip.match(line) mip6 = pip6.match(line) mupdown = pupdown.search(line) if miface: iface = miface.group(1) if mmac: data['hwaddr'] = mmac.group(1) if salt.utils.platform.is_sunos(): expand_mac = [] for chunk in data['hwaddr'].split(':'): expand_mac.append('0{0}'.format(chunk) if len(chunk) < 2 else '{0}'.format(chunk)) data['hwaddr'] = ':'.join(expand_mac) if mip: if 'inet' not in data: data['inet'] = list() addr_obj = dict() addr_obj['address'] = mip.group(1) mmask = pmask.match(line) if mmask: if mmask.group(1): mmask = _number_of_set_bits_to_ipv4_netmask( int(mmask.group(1), 16)) else: mmask = mmask.group(2) addr_obj['netmask'] = mmask mbcast = pbcast.match(line) if mbcast: addr_obj['broadcast'] = mbcast.group(1) data['inet'].append(addr_obj) if mupdown: updown = True if mip6: if 'inet6' not in data: data['inet6'] = list() addr_obj = dict() addr_obj['address'] = mip6.group(1) or mip6.group(2) mmask6 = pmask6.match(line) if mmask6: addr_obj['prefixlen'] = mmask6.group(1) or mmask6.group(2) if not salt.utils.platform.is_sunos(): ipv6scope = mmask6.group(3) or mmask6.group(4) addr_obj['scope'] = ipv6scope.lower() if ipv6scope is not None else ipv6scope # SunOS sometimes has ::/0 as inet6 addr when using addrconf if not salt.utils.platform.is_sunos() \ or addr_obj['address'] != '::' \ and addr_obj['prefixlen'] != 0: data['inet6'].append(addr_obj) data['up'] = updown if iface in ret: # SunOS optimization, where interfaces occur twice in 'ifconfig -a' # output with the same name: for ipv4 and then for ipv6 addr family. # Every instance has it's own 'UP' status and we assume that ipv4 # status determines global interface status. # # merge items with higher priority for older values # after that merge the inet and inet6 sub items for both ret[iface] = dict(list(data.items()) + list(ret[iface].items())) if 'inet' in data: ret[iface]['inet'].extend(x for x in data['inet'] if x not in ret[iface]['inet']) if 'inet6' in data: ret[iface]['inet6'].extend(x for x in data['inet6'] if x not in ret[iface]['inet6']) else: ret[iface] = data del data return ret def linux_interfaces(): ''' Obtain interface information for *NIX/BSD variants ''' ifaces = dict() ip_path = salt.utils.path.which('ip') ifconfig_path = None if ip_path else salt.utils.path.which('ifconfig') if ip_path: cmd1 = subprocess.Popen( '{0} link show'.format(ip_path), shell=True, close_fds=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT).communicate()[0] cmd2 = subprocess.Popen( '{0} addr show'.format(ip_path), shell=True, close_fds=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT).communicate()[0] ifaces = _interfaces_ip("{0}\n{1}".format( salt.utils.stringutils.to_str(cmd1), salt.utils.stringutils.to_str(cmd2))) elif ifconfig_path: cmd = subprocess.Popen( '{0} -a'.format(ifconfig_path), shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT).communicate()[0] ifaces = _interfaces_ifconfig(salt.utils.stringutils.to_str(cmd)) return ifaces def _netbsd_interfaces_ifconfig(out): ''' Uses ifconfig to return a dictionary of interfaces with various information about each (up/down state, ip address, netmask, and hwaddr) ''' ret = dict() piface = re.compile(r'^([^\s:]+)') pmac = re.compile('.*?address: ([0-9a-f:]+)') pip = re.compile(r'.*?inet [^\d]*(.*?)/([\d]*)\s') pip6 = re.compile(r'.*?inet6 ([0-9a-f:]+)%([a-zA-Z0-9]*)/([\d]*)\s') pupdown = re.compile('UP') pbcast = re.compile(r'.*?broadcast ([\d\.]+)') groups = re.compile('\r?\n(?=\\S)').split(out) for group in groups: data = dict() iface = '' updown = False for line in group.splitlines(): miface = piface.match(line) mmac = pmac.match(line) mip = pip.match(line) mip6 = pip6.match(line) mupdown = pupdown.search(line) if miface: iface = miface.group(1) if mmac: data['hwaddr'] = mmac.group(1) if mip: if 'inet' not in data: data['inet'] = list() addr_obj = dict() addr_obj['address'] = mip.group(1) mmask = mip.group(2) if mip.group(2): addr_obj['netmask'] = cidr_to_ipv4_netmask(mip.group(2)) mbcast = pbcast.match(line) if mbcast: addr_obj['broadcast'] = mbcast.group(1) data['inet'].append(addr_obj) if mupdown: updown = True if mip6: if 'inet6' not in data: data['inet6'] = list() addr_obj = dict() addr_obj['address'] = mip6.group(1) mmask6 = mip6.group(3) addr_obj['scope'] = mip6.group(2) addr_obj['prefixlen'] = mip6.group(3) data['inet6'].append(addr_obj) data['up'] = updown ret[iface] = data del data return ret def _interfaces_ipconfig(out): ''' Returns a dictionary of interfaces with various information about each (up/down state, ip address, netmask, and hwaddr) NOTE: This is not used by any function and may be able to be removed in the future. ''' ifaces = dict() iface = None adapter_iface_regex = re.compile(r'adapter (\S.+):$') for line in out.splitlines(): if not line: continue # TODO what does Windows call Infiniband and 10/40gige adapters if line.startswith('Ethernet'): iface = ifaces[adapter_iface_regex.search(line).group(1)] iface['up'] = True addr = None continue if iface: key, val = line.split(',', 1) key = key.strip(' .') val = val.strip() if addr and key == 'Subnet Mask': addr['netmask'] = val elif key in ('IP Address', 'IPv4 Address'): if 'inet' not in iface: iface['inet'] = list() addr = {'address': val.rstrip('(Preferred)'), 'netmask': None, 'broadcast': None} # TODO find the broadcast iface['inet'].append(addr) elif 'IPv6 Address' in key: if 'inet6' not in iface: iface['inet'] = list() # XXX What is the prefixlen!? addr = {'address': val.rstrip('(Preferred)'), 'prefixlen': None} iface['inet6'].append(addr) elif key == 'Physical Address': iface['hwaddr'] = val elif key == 'Media State': # XXX seen used for tunnel adaptors # might be useful iface['up'] = (val != 'Media disconnected') def win_interfaces(): ''' Obtain interface information for Windows systems ''' with salt.utils.winapi.Com(): c = wmi.WMI() ifaces = {} for iface in c.Win32_NetworkAdapterConfiguration(IPEnabled=1): ifaces[iface.Description] = dict() if iface.MACAddress: ifaces[iface.Description]['hwaddr'] = iface.MACAddress if iface.IPEnabled: ifaces[iface.Description]['up'] = True for ip in iface.IPAddress: if '.' in ip: if 'inet' not in ifaces[iface.Description]: ifaces[iface.Description]['inet'] = [] item = {'address': ip, 'label': iface.Description} if iface.DefaultIPGateway: broadcast = next((i for i in iface.DefaultIPGateway if '.' in i), '') if broadcast: item['broadcast'] = broadcast if iface.IPSubnet: netmask = next((i for i in iface.IPSubnet if '.' in i), '') if netmask: item['netmask'] = netmask ifaces[iface.Description]['inet'].append(item) if ':' in ip: if 'inet6' not in ifaces[iface.Description]: ifaces[iface.Description]['inet6'] = [] item = {'address': ip} if iface.DefaultIPGateway: broadcast = next((i for i in iface.DefaultIPGateway if ':' in i), '') if broadcast: item['broadcast'] = broadcast if iface.IPSubnet: netmask = next((i for i in iface.IPSubnet if ':' in i), '') if netmask: item['netmask'] = netmask ifaces[iface.Description]['inet6'].append(item) else: ifaces[iface.Description]['up'] = False return ifaces def interfaces(): ''' Return a dictionary of information about all the interfaces on the minion ''' if salt.utils.platform.is_windows(): return win_interfaces() elif salt.utils.platform.is_netbsd(): return netbsd_interfaces() else: return linux_interfaces() def get_net_start(ipaddr, netmask): ''' Return the address of the network ''' net = ipaddress.ip_network('{0}/{1}'.format(ipaddr, netmask), strict=False) return six.text_type(net.network_address) def get_net_size(mask): ''' Turns an IPv4 netmask into it's corresponding prefix length (255.255.255.0 -> 24 as in 192.168.1.10/24). ''' binary_str = '' for octet in mask.split('.'): binary_str += bin(int(octet))[2:].zfill(8) return len(binary_str.rstrip('0')) def calc_net(ipaddr, netmask=None): ''' Takes IP (CIDR notation supported) and optionally netmask and returns the network in CIDR-notation. (The IP can be any IP inside the subnet) ''' if netmask is not None: ipaddr = '{0}/{1}'.format(ipaddr, netmask) return six.text_type(ipaddress.ip_network(ipaddr, strict=False)) def _ipv4_to_bits(ipaddr): ''' Accepts an IPv4 dotted quad and returns a string representing its binary counterpart ''' return ''.join([bin(int(x))[2:].rjust(8, '0') for x in ipaddr.split('.')]) def _get_iface_info(iface): ''' If `iface` is available, return interface info and no error, otherwise return no info and log and return an error ''' iface_info = interfaces() if iface in iface_info.keys(): return iface_info, False else: error_msg = ('Interface "{0}" not in available interfaces: "{1}"' ''.format(iface, '", "'.join(iface_info.keys()))) log.error(error_msg) return None, error_msg def _hw_addr_aix(iface): ''' Return the hardware address (a.k.a. MAC address) for a given interface on AIX MAC address not available in through interfaces ''' cmd = subprocess.Popen( 'entstat -d {0} | grep \'Hardware Address\''.format(iface), shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT).communicate()[0] if cmd: comps = cmd.split(' ') if len(comps) == 3: mac_addr = comps[2].strip('\'').strip() return mac_addr error_msg = ('Interface "{0}" either not available or does not contain a hardware address'.format(iface)) log.error(error_msg) return error_msg def hw_addr(iface): ''' Return the hardware address (a.k.a. MAC address) for a given interface .. versionchanged:: 2016.11.4 Added support for AIX ''' if salt.utils.platform.is_aix(): return _hw_addr_aix iface_info, error = _get_iface_info(iface) if error is False: return iface_info.get(iface, {}).get('hwaddr', '') else: return error def interface(iface): ''' Return the details of `iface` or an error if it does not exist ''' iface_info, error = _get_iface_info(iface) if error is False: return iface_info.get(iface, {}).get('inet', '') else: return error def interface_ip(iface): ''' Return `iface` IPv4 addr or an error if `iface` does not exist ''' iface_info, error = _get_iface_info(iface) if error is False: inet = iface_info.get(iface, {}).get('inet', None) return inet[0].get('address', '') if inet else '' else: return error def _subnets(proto='inet', interfaces_=None): ''' Returns a list of subnets to which the host belongs ''' if interfaces_ is None: ifaces = interfaces() elif isinstance(interfaces_, list): ifaces = {} for key, value in six.iteritems(interfaces()): if key in interfaces_: ifaces[key] = value else: ifaces = {interfaces_: interfaces().get(interfaces_, {})} ret = set() if proto == 'inet': subnet = 'netmask' dflt_cidr = 32 elif proto == 'inet6': subnet = 'prefixlen' dflt_cidr = 128 else: log.error('Invalid proto %s calling subnets()', proto) return for ip_info in six.itervalues(ifaces): addrs = ip_info.get(proto, []) addrs.extend([addr for addr in ip_info.get('secondary', []) if addr.get('type') == proto]) for intf in addrs: if subnet in intf: intf = ipaddress.ip_interface('{0}/{1}'.format(intf['address'], intf[subnet])) else: intf = ipaddress.ip_interface('{0}/{1}'.format(intf['address'], dflt_cidr)) if not intf.is_loopback: ret.add(intf.network) return [six.text_type(net) for net in sorted(ret)] def subnets(interfaces=None): ''' Returns a list of IPv4 subnets to which the host belongs ''' return _subnets('inet', interfaces_=interfaces) def subnets6(): ''' Returns a list of IPv6 subnets to which the host belongs ''' return _subnets('inet6') def in_subnet(cidr, addr=None): ''' Returns True if host or (any of) addrs is within specified subnet, otherwise False ''' try: cidr = ipaddress.ip_network(cidr) except ValueError: log.error('Invalid CIDR \'%s\'', cidr) return False if addr is None: addr = ip_addrs() addr.extend(ip_addrs6()) elif not isinstance(addr, (list, tuple)): addr = (addr,) return any(ipaddress.ip_address(item) in cidr for item in addr) def _ip_addrs(interface=None, include_loopback=False, interface_data=None, proto='inet'): ''' Return the full list of IP adresses matching the criteria proto = inet|inet6 ''' ret = set() ifaces = interface_data \ if isinstance(interface_data, dict) \ else interfaces() if interface is None: target_ifaces = ifaces else: target_ifaces = dict([(k, v) for k, v in six.iteritems(ifaces) if k == interface]) if not target_ifaces: log.error('Interface %s not found.', interface) for ip_info in six.itervalues(target_ifaces): addrs = ip_info.get(proto, []) addrs.extend([addr for addr in ip_info.get('secondary', []) if addr.get('type') == proto]) for addr in addrs: addr = ipaddress.ip_address(addr.get('address')) if not addr.is_loopback or include_loopback: ret.add(addr) return [six.text_type(addr) for addr in sorted(ret)] def ip_addrs(interface=None, include_loopback=False, interface_data=None): ''' Returns a list of IPv4 addresses assigned to the host. 127.0.0.1 is ignored, unless 'include_loopback=True' is indicated. If 'interface' is provided, then only IP addresses from that interface will be returned. ''' return _ip_addrs(interface, include_loopback, interface_data, 'inet') def ip_addrs6(interface=None, include_loopback=False, interface_data=None): ''' Returns a list of IPv6 addresses assigned to the host. ::1 is ignored, unless 'include_loopback=True' is indicated. If 'interface' is provided, then only IP addresses from that interface will be returned. ''' return _ip_addrs(interface, include_loopback, interface_data, 'inet6') def hex2ip(hex_ip, invert=False): ''' Convert a hex string to an ip, if a failure occurs the original hex is returned. If 'invert=True' assume that ip from /proc/net/<proto> ''' if len(hex_ip) == 32: # ipv6 ip = [] for i in range(0, 32, 8): ip_part = hex_ip[i:i + 8] ip_part = [ip_part[x:x + 2] for x in range(0, 8, 2)] if invert: ip.append("{0[3]}{0[2]}:{0[1]}{0[0]}".format(ip_part)) else: ip.append("{0[0]}{0[1]}:{0[2]}{0[3]}".format(ip_part)) try: address = ipaddress.IPv6Address(":".join(ip)) if address.ipv4_mapped: return str(address.ipv4_mapped) else: return address.compressed except ipaddress.AddressValueError as ex: log.error('hex2ip - ipv6 address error: %s', ex) return hex_ip try: hip = int(hex_ip, 16) except ValueError: return hex_ip if invert: return '{3}.{2}.{1}.{0}'.format(hip >> 24 & 255, hip >> 16 & 255, hip >> 8 & 255, hip & 255) return '{0}.{1}.{2}.{3}'.format(hip >> 24 & 255, hip >> 16 & 255, hip >> 8 & 255, hip & 255) def mac2eui64(mac, prefix=None): ''' Convert a MAC address to a EUI64 identifier or, with prefix provided, a full IPv6 address ''' # http://tools.ietf.org/html/rfc4291#section-2.5.1 eui64 = re.sub(r'[.:-]', '', mac).lower() eui64 = eui64[0:6] + 'fffe' + eui64[6:] eui64 = hex(int(eui64[0:2], 16) | 2)[2:].zfill(2) + eui64[2:] if prefix is None: return ':'.join(re.findall(r'.{4}', eui64)) else: try: net = ipaddress.ip_network(prefix, strict=False) euil = int('0x{0}'.format(eui64), 16) return '{0}/{1}'.format(net[euil], net.prefixlen) except Exception: return def active_tcp(): ''' Return a dict describing all active tcp connections as quickly as possible ''' ret = {} for statf in ['/proc/net/tcp', '/proc/net/tcp6']: if os.path.isfile(statf): with salt.utils.files.fopen(statf, 'rb') as fp_: for line in fp_: line = salt.utils.stringutils.to_unicode(line) if line.strip().startswith('sl'): continue iret = _parse_tcp_line(line) sl = next(iter(iret)) if iret[sl]['state'] == 1: # 1 is ESTABLISHED del iret[sl]['state'] ret[len(ret)] = iret[sl] return ret def local_port_tcp(port): ''' Return a set of remote ip addrs attached to the specified local port ''' ret = _remotes_on(port, 'local_port') return ret def remote_port_tcp(port): ''' Return a set of ip addrs the current host is connected to on given port ''' ret = _remotes_on(port, 'remote_port') return ret def _remotes_on(port, which_end): ''' Return a set of ip addrs active tcp connections ''' port = int(port) ret = _netlink_tool_remote_on(port, which_end) if ret is not None: return ret ret = set() proc_available = False for statf in ['/proc/net/tcp', '/proc/net/tcp6']: if os.path.isfile(statf): proc_available = True with salt.utils.files.fopen(statf, 'r') as fp_: for line in fp_: line = salt.utils.stringutils.to_unicode(line) if line.strip().startswith('sl'): continue iret = _parse_tcp_line(line) sl = next(iter(iret)) if iret[sl][which_end] == port and iret[sl]['state'] == 1: # 1 is ESTABLISHED ret.add(iret[sl]['remote_addr']) if not proc_available: # Fallback to use OS specific tools if salt.utils.platform.is_sunos(): return _sunos_remotes_on(port, which_end) if salt.utils.platform.is_freebsd(): return _freebsd_remotes_on(port, which_end) if salt.utils.platform.is_netbsd(): return _netbsd_remotes_on(port, which_end) if salt.utils.platform.is_openbsd(): return _openbsd_remotes_on(port, which_end) if salt.utils.platform.is_windows(): return _windows_remotes_on(port, which_end) if salt.utils.platform.is_aix(): return _aix_remotes_on(port, which_end) return _linux_remotes_on(port, which_end) return ret def _parse_tcp_line(line): ''' Parse a single line from the contents of /proc/net/tcp or /proc/net/tcp6 ''' ret = {} comps = line.strip().split() sl = comps[0].rstrip(':') ret[sl] = {} l_addr, l_port = comps[1].split(':') r_addr, r_port = comps[2].split(':') ret[sl]['local_addr'] = hex2ip(l_addr, True) ret[sl]['local_port'] = int(l_port, 16) ret[sl]['remote_addr'] = hex2ip(r_addr, True) ret[sl]['remote_port'] = int(r_port, 16) ret[sl]['state'] = int(comps[3], 16) return ret def _netlink_tool_remote_on(port, which_end): ''' Returns set of ipv4 host addresses of remote established connections on local or remote tcp port. Parses output of shell 'ss' to get connections [root@salt-master ~]# ss -ant State Recv-Q Send-Q Local Address:Port Peer Address:Port LISTEN 0 511 *:80 *:* LISTEN 0 128 *:22 *:* ESTAB 0 0 127.0.0.1:56726 127.0.0.1:4505 ''' remotes = set() valid = False try: data = subprocess.check_output(['ss', '-ant']) # pylint: disable=minimum-python-version except subprocess.CalledProcessError: log.error('Failed ss') raise except OSError: # not command "No such file or directory" return None lines = salt.utils.stringutils.to_str(data).split('\n') for line in lines: if 'Address:Port' in line: # ss tools may not be valid valid = True continue elif 'ESTAB' not in line: continue chunks = line.split() local_host, local_port = chunks[3].split(':', 1) remote_host, remote_port = chunks[4].split(':', 1) if which_end == 'remote_port' and int(remote_port) != port: continue if which_end == 'local_port' and int(local_port) != port: continue remotes.add(remote_host) if valid is False: remotes = None return remotes def _sunos_remotes_on(port, which_end): ''' SunOS specific helper function. Returns set of ipv4 host addresses of remote established connections on local or remote tcp port. Parses output of shell 'netstat' to get connections [root@salt-master ~]# netstat -f inet -n TCP: IPv4 Local Address Remote Address Swind Send-Q Rwind Recv-Q State -------------------- -------------------- ----- ------ ----- ------ ----------- 10.0.0.101.4505 10.0.0.1.45329 1064800 0 1055864 0 ESTABLISHED 10.0.0.101.4505 10.0.0.100.50798 1064800 0 1055864 0 ESTABLISHED ''' remotes = set() try: data = subprocess.check_output(['netstat', '-f', 'inet', '-n']) # pylint: disable=minimum-python-version except subprocess.CalledProcessError: log.error('Failed netstat') raise lines = salt.utils.stringutils.to_str(data).split('\n') for line in lines: if 'ESTABLISHED' not in line: continue chunks = line.split() local_host, local_port = chunks[0].rsplit('.', 1) remote_host, remote_port = chunks[1].rsplit('.', 1) if which_end == 'remote_port' and int(remote_port) != port: continue if which_end == 'local_port' and int(local_port) != port: continue remotes.add(remote_host) return remotes def _freebsd_remotes_on(port, which_end): ''' Returns set of ipv4 host addresses of remote established connections on local tcp port port. Parses output of shell 'sockstat' (FreeBSD) to get connections $ sudo sockstat -4 USER COMMAND PID FD PROTO LOCAL ADDRESS FOREIGN ADDRESS root python2.7 1456 29 tcp4 *:4505 *:* root python2.7 1445 17 tcp4 *:4506 *:* root python2.7 1294 14 tcp4 127.0.0.1:11813 127.0.0.1:4505 root python2.7 1294 41 tcp4 127.0.0.1:61115 127.0.0.1:4506 $ sudo sockstat -4 -c -p 4506 USER COMMAND PID FD PROTO LOCAL ADDRESS FOREIGN ADDRESS root python2.7 1294 41 tcp4 127.0.0.1:61115 127.0.0.1:4506 ''' port = int(port) remotes = set() try: cmd = salt.utils.args.shlex_split('sockstat -4 -c -p {0}'.format(port)) data = subprocess.check_output(cmd) # pylint: disable=minimum-python-version except subprocess.CalledProcessError as ex: log.error('Failed "sockstat" with returncode = %s', ex.returncode) raise lines = salt.utils.stringutils.to_str(data).split('\n') for line in lines: chunks = line.split() if not chunks: continue # ['root', 'python2.7', '1456', '37', 'tcp4', # '127.0.0.1:4505-', '127.0.0.1:55703'] # print chunks if 'COMMAND' in chunks[1]: continue # ignore header if len(chunks) < 2: continue # sockstat -4 -c -p 4506 does this with high PIDs: # USER COMMAND PID FD PROTO LOCAL ADDRESS FOREIGN ADDRESS # salt-master python2.781106 35 tcp4 192.168.12.34:4506 192.168.12.45:60143 local = chunks[-2] remote = chunks[-1] lhost, lport = local.split(':') rhost, rport = remote.split(':') if which_end == 'local' and int(lport) != port: # ignore if local port not port continue if which_end == 'remote' and int(rport) != port: # ignore if remote port not port continue remotes.add(rhost) return remotes def _netbsd_remotes_on(port, which_end): ''' Returns set of ipv4 host addresses of remote established connections on local tcp port port. Parses output of shell 'sockstat' (NetBSD) to get connections $ sudo sockstat -4 -n USER COMMAND PID FD PROTO LOCAL ADDRESS FOREIGN ADDRESS root python2.7 1456 29 tcp *.4505 *.* root python2.7 1445 17 tcp *.4506 *.* root python2.7 1294 14 tcp 127.0.0.1.11813 127.0.0.1.4505 root python2.7 1294 41 tcp 127.0.0.1.61115 127.0.0.1.4506 $ sudo sockstat -4 -c -n -p 4506 USER COMMAND PID FD PROTO LOCAL ADDRESS FOREIGN ADDRESS root python2.7 1294 41 tcp 127.0.0.1.61115 127.0.0.1.4506 ''' port = int(port) remotes = set() try: cmd = salt.utils.args.shlex_split('sockstat -4 -c -n -p {0}'.format(port)) data = subprocess.check_output(cmd) # pylint: disable=minimum-python-version except subprocess.CalledProcessError as ex: log.error('Failed "sockstat" with returncode = %s', ex.returncode) raise lines = salt.utils.stringutils.to_str(data).split('\n') for line in lines: chunks = line.split() if not chunks: continue # ['root', 'python2.7', '1456', '37', 'tcp', # '127.0.0.1.4505-', '127.0.0.1.55703'] # print chunks if 'COMMAND' in chunks[1]: continue # ignore header if len(chunks) < 2: continue local = chunks[5].split('.') lport = local.pop() lhost = '.'.join(local) remote = chunks[6].split('.') rport = remote.pop() rhost = '.'.join(remote) if which_end == 'local' and int(lport) != port: # ignore if local port not port continue if which_end == 'remote' and int(rport) != port: # ignore if remote port not port continue remotes.add(rhost) return remotes def _openbsd_remotes_on(port, which_end): ''' OpenBSD specific helper function. Returns set of ipv4 host addresses of remote established connections on local or remote tcp port. Parses output of shell 'netstat' to get connections $ netstat -nf inet Active Internet connections Proto Recv-Q Send-Q Local Address Foreign Address (state) tcp 0 0 10.0.0.101.4505 10.0.0.1.45329 ESTABLISHED tcp 0 0 10.0.0.101.4505 10.0.0.100.50798 ESTABLISHED ''' remotes = set() try: data = subprocess.check_output(['netstat', '-nf', 'inet']) # pylint: disable=minimum-python-version except subprocess.CalledProcessError: log.error('Failed netstat') raise lines = data.split('\n') for line in lines: if 'ESTABLISHED' not in line: continue chunks = line.split() local_host, local_port = chunks[3].rsplit('.', 1) remote_host, remote_port = chunks[4].rsplit('.', 1) if which_end == 'remote_port' and int(remote_port) != port: continue if which_end == 'local_port' and int(local_port) != port: continue remotes.add(remote_host) return remotes def _windows_remotes_on(port, which_end): r''' Windows specific helper function. Returns set of ipv4 host addresses of remote established connections on local or remote tcp port. Parses output of shell 'netstat' to get connections C:\>netstat -n Active Connections Proto Local Address Foreign Address State TCP 10.2.33.17:3007 130.164.12.233:10123 ESTABLISHED TCP 10.2.33.17:3389 130.164.30.5:10378 ESTABLISHED ''' remotes = set() try: data = subprocess.check_output(['netstat', '-n']) # pylint: disable=minimum-python-version except subprocess.CalledProcessError: log.error('Failed netstat') raise lines = salt.utils.stringutils.to_str(data).split('\n') for line in lines: if 'ESTABLISHED' not in line: continue chunks = line.split() local_host, local_port = chunks[1].rsplit(':', 1) remote_host, remote_port = chunks[2].rsplit(':', 1) if which_end == 'remote_port' and int(remote_port) != port: continue if which_end == 'local_port' and int(local_port) != port: continue remotes.add(remote_host) return remotes def _linux_remotes_on(port, which_end): ''' Linux specific helper function. Returns set of ip host addresses of remote established connections on local tcp port port. Parses output of shell 'lsof' to get connections $ sudo lsof -iTCP:4505 -n COMMAND PID USER FD TYPE DEVICE SIZE/OFF NODE NAME Python 9971 root 35u IPv4 0x18a8464a29ca329d 0t0 TCP *:4505 (LISTEN) Python 9971 root 37u IPv4 0x18a8464a29b2b29d 0t0 TCP 127.0.0.1:4505->127.0.0.1:55703 (ESTABLISHED) Python 10152 root 22u IPv4 0x18a8464a29c8cab5 0t0 TCP 127.0.0.1:55703->127.0.0.1:4505 (ESTABLISHED) Python 10153 root 22u IPv4 0x18a8464a29c8cab5 0t0 TCP [fe80::249a]:4505->[fe80::150]:59367 (ESTABLISHED) ''' remotes = set() try: data = subprocess.check_output( ['lsof', '-iTCP:{0:d}'.format(port), '-n', '-P'] # pylint: disable=minimum-python-version ) except subprocess.CalledProcessError as ex: if ex.returncode == 1: # Lsof return 1 if any error was detected, including the failure # to locate Internet addresses, and it is not an error in this case. log.warning('"lsof" returncode = 1, likely no active TCP sessions.') return remotes log.error('Failed "lsof" with returncode = %s', ex.returncode) raise lines = salt.utils.stringutils.to_str(data).split('\n') for line in lines: chunks = line.split() if not chunks: continue # ['Python', '9971', 'root', '37u', 'IPv4', '0x18a8464a29b2b29d', '0t0', # 'TCP', '127.0.0.1:4505->127.0.0.1:55703', '(ESTABLISHED)'] # print chunks if 'COMMAND' in chunks[0]: continue # ignore header if 'ESTABLISHED' not in chunks[-1]: continue # ignore if not ESTABLISHED # '127.0.0.1:4505->127.0.0.1:55703' local, remote = chunks[8].split('->') _, lport = local.rsplit(':', 1) rhost, rport = remote.rsplit(':', 1) if which_end == 'remote_port' and int(rport) != port: continue if which_end == 'local_port' and int(lport) != port: continue remotes.add(rhost.strip("[]")) return remotes def _aix_remotes_on(port, which_end): ''' AIX specific helper function. Returns set of ipv4 host addresses of remote established connections on local or remote tcp port. Parses output of shell 'netstat' to get connections root@la68pp002_pub:/opt/salt/lib/python2.7/site-packages/salt/modules# netstat -f inet -n Active Internet connections Proto Recv-Q Send-Q Local Address Foreign Address (state) tcp4 0 0 172.29.149.95.50093 209.41.78.13.4505 ESTABLISHED tcp4 0 0 127.0.0.1.9514 *.* LISTEN tcp4 0 0 127.0.0.1.9515 *.* LISTEN tcp4 0 0 127.0.0.1.199 127.0.0.1.32779 ESTABLISHED tcp4 0 0 127.0.0.1.32779 127.0.0.1.199 ESTABLISHED tcp4 0 40 172.29.149.95.22 172.29.96.83.41022 ESTABLISHED tcp4 0 0 172.29.149.95.22 172.29.96.83.41032 ESTABLISHED tcp4 0 0 127.0.0.1.32771 127.0.0.1.32775 ESTABLISHED tcp 0 0 127.0.0.1.32775 127.0.0.1.32771 ESTABLISHED tcp4 0 0 127.0.0.1.32771 127.0.0.1.32776 ESTABLISHED tcp 0 0 127.0.0.1.32776 127.0.0.1.32771 ESTABLISHED tcp4 0 0 127.0.0.1.32771 127.0.0.1.32777 ESTABLISHED tcp 0 0 127.0.0.1.32777 127.0.0.1.32771 ESTABLISHED tcp4 0 0 127.0.0.1.32771 127.0.0.1.32778 ESTABLISHED tcp 0 0 127.0.0.1.32778 127.0.0.1.32771 ESTABLISHED ''' remotes = set() try: data = subprocess.check_output(['netstat', '-f', 'inet', '-n']) # pylint: disable=minimum-python-version except subprocess.CalledProcessError: log.error('Failed netstat') raise lines = salt.utils.stringutils.to_str(data).split('\n') for line in lines: if 'ESTABLISHED' not in line: continue chunks = line.split() local_host, local_port = chunks[3].rsplit('.', 1) remote_host, remote_port = chunks[4].rsplit('.', 1) if which_end == 'remote_port' and int(remote_port) != port: continue if which_end == 'local_port' and int(local_port) != port: continue remotes.add(remote_host) return remotes @jinja_filter('gen_mac') def gen_mac(prefix='AC:DE:48'): ''' Generates a MAC address with the defined OUI prefix. Common prefixes: - ``00:16:3E`` -- Xen - ``00:18:51`` -- OpenVZ - ``00:50:56`` -- VMware (manually generated) - ``52:54:00`` -- QEMU/KVM - ``AC:DE:48`` -- PRIVATE References: - http://standards.ieee.org/develop/regauth/oui/oui.txt - https://www.wireshark.org/tools/oui-lookup.html - https://en.wikipedia.org/wiki/MAC_address ''' return '{0}:{1:02X}:{2:02X}:{3:02X}'.format(prefix, random.randint(0, 0xff), random.randint(0, 0xff), random.randint(0, 0xff)) @jinja_filter('mac_str_to_bytes') def mac_str_to_bytes(mac_str): ''' Convert a MAC address string into bytes. Works with or without separators: b1 = mac_str_to_bytes('08:00:27:13:69:77') b2 = mac_str_to_bytes('080027136977') assert b1 == b2 assert isinstance(b1, bytes) ''' if len(mac_str) == 12: pass elif len(mac_str) == 17: sep = mac_str[2] mac_str = mac_str.replace(sep, '') else: raise ValueError('Invalid MAC address') chars = (int(mac_str[s:s+2], 16) for s in range(0, 12, 2)) return bytes(chars) if six.PY3 else b''.join(chr(x) for x in chars) def refresh_dns(): ''' issue #21397: force glibc to re-read resolv.conf ''' try: res_init() except NameError: # Exception raised loading the library, thus res_init is not defined pass @jinja_filter('connection_check') def connection_check(addr, port=80, safe=False, ipv6=None): ''' Provides a convenient alias for the dns_check filter. ''' return dns_check(addr, port, safe, ipv6) @jinja_filter('dns_check') def dns_check(addr, port=80, safe=False, ipv6=None, attempt_connect=True): ''' Return the ip resolved by dns, but do not exit on failure, only raise an exception. Obeys system preference for IPv4/6 address resolution - this can be overridden by the ipv6 flag. Tries to connect to the address before considering it useful. If no address can be reached, the first one resolved is used as a fallback. ''' error = False lookup = addr seen_ipv6 = False family = socket.AF_INET6 if ipv6 else socket.AF_INET if ipv6 is False else socket.AF_UNSPEC hostnames = [] try: refresh_dns() hostnames = socket.getaddrinfo(addr, port, family, socket.SOCK_STREAM) except TypeError: err = ('Attempt to resolve address \'{0}\' failed. Invalid or unresolveable address').format(lookup) raise SaltSystemExit(code=42, msg=err) except socket.error: error = True # If ipv6 is set to True, attempt another lookup using the IPv4 family, # just in case we're attempting to lookup an IPv4 IP # as an IPv6 hostname. if error and ipv6: try: refresh_dns() hostnames = socket.getaddrinfo(addr, port, socket.AF_INET, socket.SOCK_STREAM) except TypeError: err = ('Attempt to resolve address \'{0}\' failed. Invalid or unresolveable address').format(lookup) raise SaltSystemExit(code=42, msg=err) except socket.error: error = True try: if not hostnames: error = True else: resolved = False candidates = [] for h in hostnames: # Input is IP address, passed through unchanged, just return it if h[4][0] == addr: resolved = salt.utils.zeromq.ip_bracket(addr) break candidate_addr = salt.utils.zeromq.ip_bracket(h[4][0]) # sometimes /etc/hosts contains ::1 localhost if not ipv6 and candidate_addr == '[::1]': continue candidates.append(candidate_addr) if attempt_connect: try: s = socket.socket(h[0], socket.SOCK_STREAM) s.settimeout(2) s.connect((candidate_addr.strip('[]'), h[4][1])) s.close() resolved = candidate_addr break except socket.error: pass if not resolved: if candidates: resolved = candidates[0] else: error = True except TypeError: err = ('Attempt to resolve address \'{0}\' failed. Invalid or unresolveable address').format(lookup) raise SaltSystemExit(code=42, msg=err) except socket.error: error = True if error: err = ('DNS lookup or connection check of \'{0}\' failed.').format(addr) if safe: if salt.log.is_console_configured(): # If logging is not configured it also means that either # the master or minion instance calling this hasn't even # started running log.error(err) raise SaltClientError() raise SaltSystemExit(code=42, msg=err) return resolved def parse_host_port(host_port): """ Takes a string argument specifying host or host:port. Returns a (hostname, port) or (ip_address, port) tuple. If no port is given, the second (port) element of the returned tuple will be None. host:port argument, for example, is accepted in the forms of: - hostname - hostname:1234 - hostname.domain.tld - hostname.domain.tld:5678 - [1234::5]:5678 - 1234::5 - 10.11.12.13:4567 - 10.11.12.13 """ host, port = None, None # default _s_ = host_port[:] if _s_[0] == "[": if "]" in host_port: host, _s_ = _s_.lstrip("[").rsplit("]", 1) host = ipaddress.IPv6Address(host).compressed if _s_[0] == ":": port = int(_s_.lstrip(":")) else: if len(_s_) > 1: raise ValueError('found ambiguous "{}" port in "{}"'.format(_s_, host_port)) else: if _s_.count(":") == 1: host, _hostport_separator_, port = _s_.partition(":") try: port = int(port) except ValueError as _e_: log.error('host_port "%s" port value "%s" is not an integer.', host_port, port) raise _e_ else: host = _s_ try: if not isinstance(host, ipaddress._BaseAddress): host_ip = ipaddress.ip_address(host).compressed host = host_ip except ValueError: log.debug('"%s" Not an IP address? Assuming it is a hostname.', host) if host != sanitize_host(host): log.error('bad hostname: "%s"', host) raise ValueError('bad hostname: "{}"'.format(host)) return host, port def is_fqdn(hostname): """ Verify if hostname conforms to be a FQDN. :param hostname: text string with the name of the host :return: bool, True if hostname is correct FQDN, False otherwise """ compliant = re.compile(r"(?!-)[A-Z\d\-\_]{1,63}(?<!-)$", re.IGNORECASE) return "." in hostname and len(hostname) < 0xff and all(compliant.match(x) for x in hostname.rstrip(".").split("."))
saltstack/salt
salt/utils/network.py
_interfaces_ipconfig
python
def _interfaces_ipconfig(out): ''' Returns a dictionary of interfaces with various information about each (up/down state, ip address, netmask, and hwaddr) NOTE: This is not used by any function and may be able to be removed in the future. ''' ifaces = dict() iface = None adapter_iface_regex = re.compile(r'adapter (\S.+):$') for line in out.splitlines(): if not line: continue # TODO what does Windows call Infiniband and 10/40gige adapters if line.startswith('Ethernet'): iface = ifaces[adapter_iface_regex.search(line).group(1)] iface['up'] = True addr = None continue if iface: key, val = line.split(',', 1) key = key.strip(' .') val = val.strip() if addr and key == 'Subnet Mask': addr['netmask'] = val elif key in ('IP Address', 'IPv4 Address'): if 'inet' not in iface: iface['inet'] = list() addr = {'address': val.rstrip('(Preferred)'), 'netmask': None, 'broadcast': None} # TODO find the broadcast iface['inet'].append(addr) elif 'IPv6 Address' in key: if 'inet6' not in iface: iface['inet'] = list() # XXX What is the prefixlen!? addr = {'address': val.rstrip('(Preferred)'), 'prefixlen': None} iface['inet6'].append(addr) elif key == 'Physical Address': iface['hwaddr'] = val elif key == 'Media State': # XXX seen used for tunnel adaptors # might be useful iface['up'] = (val != 'Media disconnected')
Returns a dictionary of interfaces with various information about each (up/down state, ip address, netmask, and hwaddr) NOTE: This is not used by any function and may be able to be removed in the future.
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/network.py#L956-L1002
null
# -*- coding: utf-8 -*- ''' Define some generic socket functions for network modules ''' # Import python libs from __future__ import absolute_import, unicode_literals, print_function import itertools import os import re import types import socket import logging import platform import random import subprocess from string import ascii_letters, digits # Import 3rd-party libs from salt.ext import six from salt.ext.six.moves import range # pylint: disable=import-error,redefined-builtin # Attempt to import wmi try: import wmi import salt.utils.winapi except ImportError: pass # Import salt libs import salt.utils.args import salt.utils.files import salt.utils.path import salt.utils.platform import salt.utils.stringutils import salt.utils.zeromq from salt._compat import ipaddress from salt.exceptions import SaltClientError, SaltSystemExit from salt.utils.decorators.jinja import jinja_filter from salt.utils.versions import LooseVersion # inet_pton does not exist in Windows, this is a workaround if salt.utils.platform.is_windows(): from salt.ext import win_inet_pton # pylint: disable=unused-import log = logging.getLogger(__name__) try: import ctypes import ctypes.util libc = ctypes.cdll.LoadLibrary(ctypes.util.find_library("c")) res_init = libc.__res_init except (ImportError, OSError, AttributeError, TypeError): pass # pylint: disable=C0103 def sanitize_host(host): ''' Sanitize host string. https://tools.ietf.org/html/rfc1123#section-2.1 ''' RFC952_characters = ascii_letters + digits + ".-" return "".join([c for c in host[0:255] if c in RFC952_characters]) def isportopen(host, port): ''' Return status of a port ''' if not 1 <= int(port) <= 65535: return False sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) out = sock.connect_ex((sanitize_host(host), int(port))) return out def host_to_ips(host): ''' Returns a list of IP addresses of a given hostname or None if not found. ''' ips = [] try: for family, socktype, proto, canonname, sockaddr in socket.getaddrinfo( host, 0, socket.AF_UNSPEC, socket.SOCK_STREAM): if family == socket.AF_INET: ip, port = sockaddr elif family == socket.AF_INET6: ip, port, flow_info, scope_id = sockaddr ips.append(ip) if not ips: ips = None except Exception: ips = None return ips def _generate_minion_id(): ''' Get list of possible host names and convention names. :return: ''' # There are three types of hostnames: # 1. Network names. How host is accessed from the network. # 2. Host aliases. They might be not available in all the network or only locally (/etc/hosts) # 3. Convention names, an internal nodename. class DistinctList(list): ''' List, which allows one to append only distinct objects. Needs to work on Python 2.6, because of collections.OrderedDict only since 2.7 version. Override 'filter()' for custom filtering. ''' localhost_matchers = [r'localhost.*', r'ip6-.*', r'127[.]\d', r'0\.0\.0\.0', r'::1.*', r'ipv6-.*', r'fe00::.*', r'fe02::.*', r'1.0.0.*.ip6.arpa'] def append(self, p_object): if p_object and p_object not in self and not self.filter(p_object): super(DistinctList, self).append(p_object) return self def extend(self, iterable): for obj in iterable: self.append(obj) return self def filter(self, element): 'Returns True if element needs to be filtered' for rgx in self.localhost_matchers: if re.match(rgx, element): return True def first(self): return self and self[0] or None hostname = socket.gethostname() hosts = DistinctList().append( salt.utils.stringutils.to_unicode(socket.getfqdn(salt.utils.stringutils.to_bytes(hostname))) ).append(platform.node()).append(hostname) if not hosts: try: for a_nfo in socket.getaddrinfo(hosts.first() or 'localhost', None, socket.AF_INET, socket.SOCK_RAW, socket.IPPROTO_IP, socket.AI_CANONNAME): if len(a_nfo) > 3: hosts.append(a_nfo[3]) except socket.gaierror: log.warning('Cannot resolve address %s info via socket: %s', hosts.first() or 'localhost (N/A)', socket.gaierror) # Universal method for everywhere (Linux, Slowlaris, Windows etc) for f_name in ('/etc/hostname', '/etc/nodename', '/etc/hosts', r'{win}\system32\drivers\etc\hosts'.format(win=os.getenv('WINDIR'))): try: with salt.utils.files.fopen(f_name) as f_hdl: for line in f_hdl: line = salt.utils.stringutils.to_unicode(line) hst = line.strip().split('#')[0].strip().split() if hst: if hst[0][:4] in ('127.', '::1') or len(hst) == 1: hosts.extend(hst) except IOError: pass # include public and private ipaddresses return hosts.extend([addr for addr in ip_addrs() if not ipaddress.ip_address(addr).is_loopback]) def generate_minion_id(): ''' Return only first element of the hostname from all possible list. :return: ''' try: ret = salt.utils.stringutils.to_unicode(_generate_minion_id().first()) except TypeError: ret = None return ret or 'localhost' def get_socket(addr, type=socket.SOCK_STREAM, proto=0): ''' Return a socket object for the addr IP-version agnostic ''' version = ipaddress.ip_address(addr).version if version == 4: family = socket.AF_INET elif version == 6: family = socket.AF_INET6 return socket.socket(family, type, proto) def get_fqhostname(): ''' Returns the fully qualified hostname ''' # try getaddrinfo() fqdn = None try: addrinfo = socket.getaddrinfo( socket.gethostname(), 0, socket.AF_UNSPEC, socket.SOCK_STREAM, socket.SOL_TCP, socket.AI_CANONNAME ) for info in addrinfo: # info struct [family, socktype, proto, canonname, sockaddr] # On Windows `canonname` can be an empty string # This can cause the function to return `None` if len(info) > 3 and info[3]: fqdn = info[3] break except socket.gaierror: pass # NOTE: this used to log.error() but it was later disabled except socket.error as err: log.debug('socket.getaddrinfo() failure while finding fqdn: %s', err) if fqdn is None: fqdn = socket.getfqdn() return fqdn def ip_to_host(ip): ''' Returns the hostname of a given IP ''' try: hostname, aliaslist, ipaddrlist = socket.gethostbyaddr(ip) except Exception as exc: log.debug('salt.utils.network.ip_to_host(%r) failed: %s', ip, exc) hostname = None return hostname # pylint: enable=C0103 def is_reachable_host(entity_name): ''' Returns a bool telling if the entity name is a reachable host (IPv4/IPv6/FQDN/etc). :param hostname: :return: ''' try: assert type(socket.getaddrinfo(entity_name, 0, 0, 0, 0)) == list ret = True except socket.gaierror: ret = False return ret def is_ip(ip): ''' Returns a bool telling if the passed IP is a valid IPv4 or IPv6 address. ''' return is_ipv4(ip) or is_ipv6(ip) def is_ipv4(ip): ''' Returns a bool telling if the value passed to it was a valid IPv4 address ''' try: return ipaddress.ip_address(ip).version == 4 except ValueError: return False def is_ipv6(ip): ''' Returns a bool telling if the value passed to it was a valid IPv6 address ''' try: return ipaddress.ip_address(ip).version == 6 except ValueError: return False def is_subnet(cidr): ''' Returns a bool telling if the passed string is an IPv4 or IPv6 subnet ''' return is_ipv4_subnet(cidr) or is_ipv6_subnet(cidr) def is_ipv4_subnet(cidr): ''' Returns a bool telling if the passed string is an IPv4 subnet ''' try: return '/' in cidr and bool(ipaddress.IPv4Network(cidr)) except Exception: return False def is_ipv6_subnet(cidr): ''' Returns a bool telling if the passed string is an IPv6 subnet ''' try: return '/' in cidr and bool(ipaddress.IPv6Network(cidr)) except Exception: return False @jinja_filter('is_ip') def is_ip_filter(ip, options=None): ''' Returns a bool telling if the passed IP is a valid IPv4 or IPv6 address. ''' return is_ipv4_filter(ip, options=options) or is_ipv6_filter(ip, options=options) def _ip_options_global(ip_obj, version): return not ip_obj.is_private def _ip_options_multicast(ip_obj, version): return ip_obj.is_multicast def _ip_options_loopback(ip_obj, version): return ip_obj.is_loopback def _ip_options_link_local(ip_obj, version): return ip_obj.is_link_local def _ip_options_private(ip_obj, version): return ip_obj.is_private def _ip_options_reserved(ip_obj, version): return ip_obj.is_reserved def _ip_options_site_local(ip_obj, version): if version == 6: return ip_obj.is_site_local return False def _ip_options_unspecified(ip_obj, version): return ip_obj.is_unspecified def _ip_options(ip_obj, version, options=None): # will process and IP options options_fun_map = { 'global': _ip_options_global, 'link-local': _ip_options_link_local, 'linklocal': _ip_options_link_local, 'll': _ip_options_link_local, 'link_local': _ip_options_link_local, 'loopback': _ip_options_loopback, 'lo': _ip_options_loopback, 'multicast': _ip_options_multicast, 'private': _ip_options_private, 'public': _ip_options_global, 'reserved': _ip_options_reserved, 'site-local': _ip_options_site_local, 'sl': _ip_options_site_local, 'site_local': _ip_options_site_local, 'unspecified': _ip_options_unspecified } if not options: return six.text_type(ip_obj) # IP version already checked options_list = [option.strip() for option in options.split(',')] for option, fun in options_fun_map.items(): if option in options_list: fun_res = fun(ip_obj, version) if not fun_res: return None # stop at first failed test # else continue return six.text_type(ip_obj) def _is_ipv(ip, version, options=None): if not version: version = 4 if version not in (4, 6): return None try: ip_obj = ipaddress.ip_address(ip) except ValueError: # maybe it is an IP network try: ip_obj = ipaddress.ip_interface(ip) except ValueError: # nope, still not :( return None if not ip_obj.version == version: return None # has the right version, let's move on return _ip_options(ip_obj, version, options=options) @jinja_filter('is_ipv4') def is_ipv4_filter(ip, options=None): ''' Returns a bool telling if the value passed to it was a valid IPv4 address. ip The IP address. net: False Consider IP addresses followed by netmask. options CSV of options regarding the nature of the IP address. E.g.: loopback, multicast, private etc. ''' _is_ipv4 = _is_ipv(ip, 4, options=options) return isinstance(_is_ipv4, six.string_types) @jinja_filter('is_ipv6') def is_ipv6_filter(ip, options=None): ''' Returns a bool telling if the value passed to it was a valid IPv6 address. ip The IP address. net: False Consider IP addresses followed by netmask. options CSV of options regarding the nature of the IP address. E.g.: loopback, multicast, private etc. ''' _is_ipv6 = _is_ipv(ip, 6, options=options) return isinstance(_is_ipv6, six.string_types) def _ipv_filter(value, version, options=None): if version not in (4, 6): return if isinstance(value, (six.string_types, six.text_type, six.binary_type)): return _is_ipv(value, version, options=options) # calls is_ipv4 or is_ipv6 for `value` elif isinstance(value, (list, tuple, types.GeneratorType)): # calls is_ipv4 or is_ipv6 for each element in the list # os it filters and returns only those elements having the desired IP version return [ _is_ipv(addr, version, options=options) for addr in value if _is_ipv(addr, version, options=options) is not None ] return None @jinja_filter('ipv4') def ipv4(value, options=None): ''' Filters a list and returns IPv4 values only. ''' return _ipv_filter(value, 4, options=options) @jinja_filter('ipv6') def ipv6(value, options=None): ''' Filters a list and returns IPv6 values only. ''' return _ipv_filter(value, 6, options=options) @jinja_filter('ipaddr') def ipaddr(value, options=None): ''' Filters and returns only valid IP objects. ''' ipv4_obj = ipv4(value, options=options) ipv6_obj = ipv6(value, options=options) if ipv4_obj is None or ipv6_obj is None: # an IP address can be either IPv4 either IPv6 # therefofe if the value passed as arg is not a list, at least one of the calls above will return None # if one of them is none, means that we should return only one of them return ipv4_obj or ipv6_obj # one of them else: return ipv4_obj + ipv6_obj # extend lists def _filter_ipaddr(value, options, version=None): ipaddr_filter_out = None if version: if version == 4: ipaddr_filter_out = ipv4(value, options) elif version == 6: ipaddr_filter_out = ipv6(value, options) else: ipaddr_filter_out = ipaddr(value, options) if not ipaddr_filter_out: return if not isinstance(ipaddr_filter_out, (list, tuple, types.GeneratorType)): ipaddr_filter_out = [ipaddr_filter_out] return ipaddr_filter_out @jinja_filter('ip_host') def ip_host(value, options=None, version=None): ''' Returns the interfaces IP address, e.g.: 192.168.0.1/28. ''' ipaddr_filter_out = _filter_ipaddr(value, options=options, version=version) if not ipaddr_filter_out: return if not isinstance(value, (list, tuple, types.GeneratorType)): return six.text_type(ipaddress.ip_interface(ipaddr_filter_out[0])) return [six.text_type(ipaddress.ip_interface(ip_a)) for ip_a in ipaddr_filter_out] def _network_hosts(ip_addr_entry): return [ six.text_type(host) for host in ipaddress.ip_network(ip_addr_entry, strict=False).hosts() ] @jinja_filter('network_hosts') def network_hosts(value, options=None, version=None): ''' Return the list of hosts within a network. .. note:: When running this command with a large IPv6 network, the command will take a long time to gather all of the hosts. ''' ipaddr_filter_out = _filter_ipaddr(value, options=options, version=version) if not ipaddr_filter_out: return if not isinstance(value, (list, tuple, types.GeneratorType)): return _network_hosts(ipaddr_filter_out[0]) return [ _network_hosts(ip_a) for ip_a in ipaddr_filter_out ] def _network_size(ip_addr_entry): return ipaddress.ip_network(ip_addr_entry, strict=False).num_addresses @jinja_filter('network_size') def network_size(value, options=None, version=None): ''' Get the size of a network. ''' ipaddr_filter_out = _filter_ipaddr(value, options=options, version=version) if not ipaddr_filter_out: return if not isinstance(value, (list, tuple, types.GeneratorType)): return _network_size(ipaddr_filter_out[0]) return [ _network_size(ip_a) for ip_a in ipaddr_filter_out ] def natural_ipv4_netmask(ip, fmt='prefixlen'): ''' Returns the "natural" mask of an IPv4 address ''' bits = _ipv4_to_bits(ip) if bits.startswith('11'): mask = '24' elif bits.startswith('1'): mask = '16' else: mask = '8' if fmt == 'netmask': return cidr_to_ipv4_netmask(mask) else: return '/' + mask def rpad_ipv4_network(ip): ''' Returns an IP network address padded with zeros. Ex: '192.168.3' -> '192.168.3.0' '10.209' -> '10.209.0.0' ''' return '.'.join(itertools.islice(itertools.chain(ip.split('.'), '0000'), 0, 4)) def cidr_to_ipv4_netmask(cidr_bits): ''' Returns an IPv4 netmask ''' try: cidr_bits = int(cidr_bits) if not 1 <= cidr_bits <= 32: return '' except ValueError: return '' netmask = '' for idx in range(4): if idx: netmask += '.' if cidr_bits >= 8: netmask += '255' cidr_bits -= 8 else: netmask += '{0:d}'.format(256 - (2 ** (8 - cidr_bits))) cidr_bits = 0 return netmask def _number_of_set_bits_to_ipv4_netmask(set_bits): # pylint: disable=C0103 ''' Returns an IPv4 netmask from the integer representation of that mask. Ex. 0xffffff00 -> '255.255.255.0' ''' return cidr_to_ipv4_netmask(_number_of_set_bits(set_bits)) # pylint: disable=C0103 def _number_of_set_bits(x): ''' Returns the number of bits that are set in a 32bit int ''' # Taken from http://stackoverflow.com/a/4912729. Many thanks! x -= (x >> 1) & 0x55555555 x = ((x >> 2) & 0x33333333) + (x & 0x33333333) x = ((x >> 4) + x) & 0x0f0f0f0f x += x >> 8 x += x >> 16 return x & 0x0000003f # pylint: enable=C0103 def _interfaces_ip(out): ''' Uses ip to return a dictionary of interfaces with various information about each (up/down state, ip address, netmask, and hwaddr) ''' ret = dict() def parse_network(value, cols): ''' Return a tuple of ip, netmask, broadcast based on the current set of cols ''' brd = None scope = None if '/' in value: # we have a CIDR in this address ip, cidr = value.split('/') # pylint: disable=C0103 else: ip = value # pylint: disable=C0103 cidr = 32 if type_ == 'inet': mask = cidr_to_ipv4_netmask(int(cidr)) if 'brd' in cols: brd = cols[cols.index('brd') + 1] elif type_ == 'inet6': mask = cidr if 'scope' in cols: scope = cols[cols.index('scope') + 1] return (ip, mask, brd, scope) groups = re.compile('\r?\n\\d').split(out) for group in groups: iface = None data = dict() for line in group.splitlines(): if ' ' not in line: continue match = re.match(r'^\d*:\s+([\w.\-]+)(?:@)?([\w.\-]+)?:\s+<(.+)>', line) if match: iface, parent, attrs = match.groups() if 'UP' in attrs.split(','): data['up'] = True else: data['up'] = False if parent: data['parent'] = parent continue cols = line.split() if len(cols) >= 2: type_, value = tuple(cols[0:2]) iflabel = cols[-1:][0] if type_ in ('inet', 'inet6'): if 'secondary' not in cols: ipaddr, netmask, broadcast, scope = parse_network(value, cols) if type_ == 'inet': if 'inet' not in data: data['inet'] = list() addr_obj = dict() addr_obj['address'] = ipaddr addr_obj['netmask'] = netmask addr_obj['broadcast'] = broadcast addr_obj['label'] = iflabel data['inet'].append(addr_obj) elif type_ == 'inet6': if 'inet6' not in data: data['inet6'] = list() addr_obj = dict() addr_obj['address'] = ipaddr addr_obj['prefixlen'] = netmask addr_obj['scope'] = scope data['inet6'].append(addr_obj) else: if 'secondary' not in data: data['secondary'] = list() ip_, mask, brd, scp = parse_network(value, cols) data['secondary'].append({ 'type': type_, 'address': ip_, 'netmask': mask, 'broadcast': brd, 'label': iflabel, }) del ip_, mask, brd, scp elif type_.startswith('link'): data['hwaddr'] = value if iface: ret[iface] = data del iface, data return ret def _interfaces_ifconfig(out): ''' Uses ifconfig to return a dictionary of interfaces with various information about each (up/down state, ip address, netmask, and hwaddr) ''' ret = dict() piface = re.compile(r'^([^\s:]+)') pmac = re.compile('.*?(?:HWaddr|ether|address:|lladdr) ([0-9a-fA-F:]+)') if salt.utils.platform.is_sunos(): pip = re.compile(r'.*?(?:inet\s+)([0-9]+\.[0-9]+\.[0-9]+\.[0-9]+)(.*)') pip6 = re.compile('.*?(?:inet6 )([0-9a-fA-F:]+)') pmask6 = re.compile(r'.*?(?:inet6 [0-9a-fA-F:]+/(\d+)).*') else: pip = re.compile(r'.*?(?:inet addr:|inet [^\d]*)(.*?)\s') pip6 = re.compile('.*?(?:inet6 addr: (.*?)/|inet6 )([0-9a-fA-F:]+)') pmask6 = re.compile(r'.*?(?:inet6 addr: [0-9a-fA-F:]+/(\d+)|prefixlen (\d+))(?: Scope:([a-zA-Z]+)| scopeid (0x[0-9a-fA-F]))?') pmask = re.compile(r'.*?(?:Mask:|netmask )(?:((?:0x)?[0-9a-fA-F]{8})|([\d\.]+))') pupdown = re.compile('UP') pbcast = re.compile(r'.*?(?:Bcast:|broadcast )([\d\.]+)') groups = re.compile('\r?\n(?=\\S)').split(out) for group in groups: data = dict() iface = '' updown = False for line in group.splitlines(): miface = piface.match(line) mmac = pmac.match(line) mip = pip.match(line) mip6 = pip6.match(line) mupdown = pupdown.search(line) if miface: iface = miface.group(1) if mmac: data['hwaddr'] = mmac.group(1) if salt.utils.platform.is_sunos(): expand_mac = [] for chunk in data['hwaddr'].split(':'): expand_mac.append('0{0}'.format(chunk) if len(chunk) < 2 else '{0}'.format(chunk)) data['hwaddr'] = ':'.join(expand_mac) if mip: if 'inet' not in data: data['inet'] = list() addr_obj = dict() addr_obj['address'] = mip.group(1) mmask = pmask.match(line) if mmask: if mmask.group(1): mmask = _number_of_set_bits_to_ipv4_netmask( int(mmask.group(1), 16)) else: mmask = mmask.group(2) addr_obj['netmask'] = mmask mbcast = pbcast.match(line) if mbcast: addr_obj['broadcast'] = mbcast.group(1) data['inet'].append(addr_obj) if mupdown: updown = True if mip6: if 'inet6' not in data: data['inet6'] = list() addr_obj = dict() addr_obj['address'] = mip6.group(1) or mip6.group(2) mmask6 = pmask6.match(line) if mmask6: addr_obj['prefixlen'] = mmask6.group(1) or mmask6.group(2) if not salt.utils.platform.is_sunos(): ipv6scope = mmask6.group(3) or mmask6.group(4) addr_obj['scope'] = ipv6scope.lower() if ipv6scope is not None else ipv6scope # SunOS sometimes has ::/0 as inet6 addr when using addrconf if not salt.utils.platform.is_sunos() \ or addr_obj['address'] != '::' \ and addr_obj['prefixlen'] != 0: data['inet6'].append(addr_obj) data['up'] = updown if iface in ret: # SunOS optimization, where interfaces occur twice in 'ifconfig -a' # output with the same name: for ipv4 and then for ipv6 addr family. # Every instance has it's own 'UP' status and we assume that ipv4 # status determines global interface status. # # merge items with higher priority for older values # after that merge the inet and inet6 sub items for both ret[iface] = dict(list(data.items()) + list(ret[iface].items())) if 'inet' in data: ret[iface]['inet'].extend(x for x in data['inet'] if x not in ret[iface]['inet']) if 'inet6' in data: ret[iface]['inet6'].extend(x for x in data['inet6'] if x not in ret[iface]['inet6']) else: ret[iface] = data del data return ret def linux_interfaces(): ''' Obtain interface information for *NIX/BSD variants ''' ifaces = dict() ip_path = salt.utils.path.which('ip') ifconfig_path = None if ip_path else salt.utils.path.which('ifconfig') if ip_path: cmd1 = subprocess.Popen( '{0} link show'.format(ip_path), shell=True, close_fds=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT).communicate()[0] cmd2 = subprocess.Popen( '{0} addr show'.format(ip_path), shell=True, close_fds=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT).communicate()[0] ifaces = _interfaces_ip("{0}\n{1}".format( salt.utils.stringutils.to_str(cmd1), salt.utils.stringutils.to_str(cmd2))) elif ifconfig_path: cmd = subprocess.Popen( '{0} -a'.format(ifconfig_path), shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT).communicate()[0] ifaces = _interfaces_ifconfig(salt.utils.stringutils.to_str(cmd)) return ifaces def _netbsd_interfaces_ifconfig(out): ''' Uses ifconfig to return a dictionary of interfaces with various information about each (up/down state, ip address, netmask, and hwaddr) ''' ret = dict() piface = re.compile(r'^([^\s:]+)') pmac = re.compile('.*?address: ([0-9a-f:]+)') pip = re.compile(r'.*?inet [^\d]*(.*?)/([\d]*)\s') pip6 = re.compile(r'.*?inet6 ([0-9a-f:]+)%([a-zA-Z0-9]*)/([\d]*)\s') pupdown = re.compile('UP') pbcast = re.compile(r'.*?broadcast ([\d\.]+)') groups = re.compile('\r?\n(?=\\S)').split(out) for group in groups: data = dict() iface = '' updown = False for line in group.splitlines(): miface = piface.match(line) mmac = pmac.match(line) mip = pip.match(line) mip6 = pip6.match(line) mupdown = pupdown.search(line) if miface: iface = miface.group(1) if mmac: data['hwaddr'] = mmac.group(1) if mip: if 'inet' not in data: data['inet'] = list() addr_obj = dict() addr_obj['address'] = mip.group(1) mmask = mip.group(2) if mip.group(2): addr_obj['netmask'] = cidr_to_ipv4_netmask(mip.group(2)) mbcast = pbcast.match(line) if mbcast: addr_obj['broadcast'] = mbcast.group(1) data['inet'].append(addr_obj) if mupdown: updown = True if mip6: if 'inet6' not in data: data['inet6'] = list() addr_obj = dict() addr_obj['address'] = mip6.group(1) mmask6 = mip6.group(3) addr_obj['scope'] = mip6.group(2) addr_obj['prefixlen'] = mip6.group(3) data['inet6'].append(addr_obj) data['up'] = updown ret[iface] = data del data return ret def netbsd_interfaces(): ''' Obtain interface information for NetBSD >= 8 where the ifconfig output diverged from other BSD variants (Netmask is now part of the address) ''' # NetBSD versions prior to 8.0 can still use linux_interfaces() if LooseVersion(os.uname()[2]) < LooseVersion('8.0'): return linux_interfaces() ifconfig_path = salt.utils.path.which('ifconfig') cmd = subprocess.Popen( '{0} -a'.format(ifconfig_path), shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT).communicate()[0] return _netbsd_interfaces_ifconfig(salt.utils.stringutils.to_str(cmd)) def win_interfaces(): ''' Obtain interface information for Windows systems ''' with salt.utils.winapi.Com(): c = wmi.WMI() ifaces = {} for iface in c.Win32_NetworkAdapterConfiguration(IPEnabled=1): ifaces[iface.Description] = dict() if iface.MACAddress: ifaces[iface.Description]['hwaddr'] = iface.MACAddress if iface.IPEnabled: ifaces[iface.Description]['up'] = True for ip in iface.IPAddress: if '.' in ip: if 'inet' not in ifaces[iface.Description]: ifaces[iface.Description]['inet'] = [] item = {'address': ip, 'label': iface.Description} if iface.DefaultIPGateway: broadcast = next((i for i in iface.DefaultIPGateway if '.' in i), '') if broadcast: item['broadcast'] = broadcast if iface.IPSubnet: netmask = next((i for i in iface.IPSubnet if '.' in i), '') if netmask: item['netmask'] = netmask ifaces[iface.Description]['inet'].append(item) if ':' in ip: if 'inet6' not in ifaces[iface.Description]: ifaces[iface.Description]['inet6'] = [] item = {'address': ip} if iface.DefaultIPGateway: broadcast = next((i for i in iface.DefaultIPGateway if ':' in i), '') if broadcast: item['broadcast'] = broadcast if iface.IPSubnet: netmask = next((i for i in iface.IPSubnet if ':' in i), '') if netmask: item['netmask'] = netmask ifaces[iface.Description]['inet6'].append(item) else: ifaces[iface.Description]['up'] = False return ifaces def interfaces(): ''' Return a dictionary of information about all the interfaces on the minion ''' if salt.utils.platform.is_windows(): return win_interfaces() elif salt.utils.platform.is_netbsd(): return netbsd_interfaces() else: return linux_interfaces() def get_net_start(ipaddr, netmask): ''' Return the address of the network ''' net = ipaddress.ip_network('{0}/{1}'.format(ipaddr, netmask), strict=False) return six.text_type(net.network_address) def get_net_size(mask): ''' Turns an IPv4 netmask into it's corresponding prefix length (255.255.255.0 -> 24 as in 192.168.1.10/24). ''' binary_str = '' for octet in mask.split('.'): binary_str += bin(int(octet))[2:].zfill(8) return len(binary_str.rstrip('0')) def calc_net(ipaddr, netmask=None): ''' Takes IP (CIDR notation supported) and optionally netmask and returns the network in CIDR-notation. (The IP can be any IP inside the subnet) ''' if netmask is not None: ipaddr = '{0}/{1}'.format(ipaddr, netmask) return six.text_type(ipaddress.ip_network(ipaddr, strict=False)) def _ipv4_to_bits(ipaddr): ''' Accepts an IPv4 dotted quad and returns a string representing its binary counterpart ''' return ''.join([bin(int(x))[2:].rjust(8, '0') for x in ipaddr.split('.')]) def _get_iface_info(iface): ''' If `iface` is available, return interface info and no error, otherwise return no info and log and return an error ''' iface_info = interfaces() if iface in iface_info.keys(): return iface_info, False else: error_msg = ('Interface "{0}" not in available interfaces: "{1}"' ''.format(iface, '", "'.join(iface_info.keys()))) log.error(error_msg) return None, error_msg def _hw_addr_aix(iface): ''' Return the hardware address (a.k.a. MAC address) for a given interface on AIX MAC address not available in through interfaces ''' cmd = subprocess.Popen( 'entstat -d {0} | grep \'Hardware Address\''.format(iface), shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT).communicate()[0] if cmd: comps = cmd.split(' ') if len(comps) == 3: mac_addr = comps[2].strip('\'').strip() return mac_addr error_msg = ('Interface "{0}" either not available or does not contain a hardware address'.format(iface)) log.error(error_msg) return error_msg def hw_addr(iface): ''' Return the hardware address (a.k.a. MAC address) for a given interface .. versionchanged:: 2016.11.4 Added support for AIX ''' if salt.utils.platform.is_aix(): return _hw_addr_aix iface_info, error = _get_iface_info(iface) if error is False: return iface_info.get(iface, {}).get('hwaddr', '') else: return error def interface(iface): ''' Return the details of `iface` or an error if it does not exist ''' iface_info, error = _get_iface_info(iface) if error is False: return iface_info.get(iface, {}).get('inet', '') else: return error def interface_ip(iface): ''' Return `iface` IPv4 addr or an error if `iface` does not exist ''' iface_info, error = _get_iface_info(iface) if error is False: inet = iface_info.get(iface, {}).get('inet', None) return inet[0].get('address', '') if inet else '' else: return error def _subnets(proto='inet', interfaces_=None): ''' Returns a list of subnets to which the host belongs ''' if interfaces_ is None: ifaces = interfaces() elif isinstance(interfaces_, list): ifaces = {} for key, value in six.iteritems(interfaces()): if key in interfaces_: ifaces[key] = value else: ifaces = {interfaces_: interfaces().get(interfaces_, {})} ret = set() if proto == 'inet': subnet = 'netmask' dflt_cidr = 32 elif proto == 'inet6': subnet = 'prefixlen' dflt_cidr = 128 else: log.error('Invalid proto %s calling subnets()', proto) return for ip_info in six.itervalues(ifaces): addrs = ip_info.get(proto, []) addrs.extend([addr for addr in ip_info.get('secondary', []) if addr.get('type') == proto]) for intf in addrs: if subnet in intf: intf = ipaddress.ip_interface('{0}/{1}'.format(intf['address'], intf[subnet])) else: intf = ipaddress.ip_interface('{0}/{1}'.format(intf['address'], dflt_cidr)) if not intf.is_loopback: ret.add(intf.network) return [six.text_type(net) for net in sorted(ret)] def subnets(interfaces=None): ''' Returns a list of IPv4 subnets to which the host belongs ''' return _subnets('inet', interfaces_=interfaces) def subnets6(): ''' Returns a list of IPv6 subnets to which the host belongs ''' return _subnets('inet6') def in_subnet(cidr, addr=None): ''' Returns True if host or (any of) addrs is within specified subnet, otherwise False ''' try: cidr = ipaddress.ip_network(cidr) except ValueError: log.error('Invalid CIDR \'%s\'', cidr) return False if addr is None: addr = ip_addrs() addr.extend(ip_addrs6()) elif not isinstance(addr, (list, tuple)): addr = (addr,) return any(ipaddress.ip_address(item) in cidr for item in addr) def _ip_addrs(interface=None, include_loopback=False, interface_data=None, proto='inet'): ''' Return the full list of IP adresses matching the criteria proto = inet|inet6 ''' ret = set() ifaces = interface_data \ if isinstance(interface_data, dict) \ else interfaces() if interface is None: target_ifaces = ifaces else: target_ifaces = dict([(k, v) for k, v in six.iteritems(ifaces) if k == interface]) if not target_ifaces: log.error('Interface %s not found.', interface) for ip_info in six.itervalues(target_ifaces): addrs = ip_info.get(proto, []) addrs.extend([addr for addr in ip_info.get('secondary', []) if addr.get('type') == proto]) for addr in addrs: addr = ipaddress.ip_address(addr.get('address')) if not addr.is_loopback or include_loopback: ret.add(addr) return [six.text_type(addr) for addr in sorted(ret)] def ip_addrs(interface=None, include_loopback=False, interface_data=None): ''' Returns a list of IPv4 addresses assigned to the host. 127.0.0.1 is ignored, unless 'include_loopback=True' is indicated. If 'interface' is provided, then only IP addresses from that interface will be returned. ''' return _ip_addrs(interface, include_loopback, interface_data, 'inet') def ip_addrs6(interface=None, include_loopback=False, interface_data=None): ''' Returns a list of IPv6 addresses assigned to the host. ::1 is ignored, unless 'include_loopback=True' is indicated. If 'interface' is provided, then only IP addresses from that interface will be returned. ''' return _ip_addrs(interface, include_loopback, interface_data, 'inet6') def hex2ip(hex_ip, invert=False): ''' Convert a hex string to an ip, if a failure occurs the original hex is returned. If 'invert=True' assume that ip from /proc/net/<proto> ''' if len(hex_ip) == 32: # ipv6 ip = [] for i in range(0, 32, 8): ip_part = hex_ip[i:i + 8] ip_part = [ip_part[x:x + 2] for x in range(0, 8, 2)] if invert: ip.append("{0[3]}{0[2]}:{0[1]}{0[0]}".format(ip_part)) else: ip.append("{0[0]}{0[1]}:{0[2]}{0[3]}".format(ip_part)) try: address = ipaddress.IPv6Address(":".join(ip)) if address.ipv4_mapped: return str(address.ipv4_mapped) else: return address.compressed except ipaddress.AddressValueError as ex: log.error('hex2ip - ipv6 address error: %s', ex) return hex_ip try: hip = int(hex_ip, 16) except ValueError: return hex_ip if invert: return '{3}.{2}.{1}.{0}'.format(hip >> 24 & 255, hip >> 16 & 255, hip >> 8 & 255, hip & 255) return '{0}.{1}.{2}.{3}'.format(hip >> 24 & 255, hip >> 16 & 255, hip >> 8 & 255, hip & 255) def mac2eui64(mac, prefix=None): ''' Convert a MAC address to a EUI64 identifier or, with prefix provided, a full IPv6 address ''' # http://tools.ietf.org/html/rfc4291#section-2.5.1 eui64 = re.sub(r'[.:-]', '', mac).lower() eui64 = eui64[0:6] + 'fffe' + eui64[6:] eui64 = hex(int(eui64[0:2], 16) | 2)[2:].zfill(2) + eui64[2:] if prefix is None: return ':'.join(re.findall(r'.{4}', eui64)) else: try: net = ipaddress.ip_network(prefix, strict=False) euil = int('0x{0}'.format(eui64), 16) return '{0}/{1}'.format(net[euil], net.prefixlen) except Exception: return def active_tcp(): ''' Return a dict describing all active tcp connections as quickly as possible ''' ret = {} for statf in ['/proc/net/tcp', '/proc/net/tcp6']: if os.path.isfile(statf): with salt.utils.files.fopen(statf, 'rb') as fp_: for line in fp_: line = salt.utils.stringutils.to_unicode(line) if line.strip().startswith('sl'): continue iret = _parse_tcp_line(line) sl = next(iter(iret)) if iret[sl]['state'] == 1: # 1 is ESTABLISHED del iret[sl]['state'] ret[len(ret)] = iret[sl] return ret def local_port_tcp(port): ''' Return a set of remote ip addrs attached to the specified local port ''' ret = _remotes_on(port, 'local_port') return ret def remote_port_tcp(port): ''' Return a set of ip addrs the current host is connected to on given port ''' ret = _remotes_on(port, 'remote_port') return ret def _remotes_on(port, which_end): ''' Return a set of ip addrs active tcp connections ''' port = int(port) ret = _netlink_tool_remote_on(port, which_end) if ret is not None: return ret ret = set() proc_available = False for statf in ['/proc/net/tcp', '/proc/net/tcp6']: if os.path.isfile(statf): proc_available = True with salt.utils.files.fopen(statf, 'r') as fp_: for line in fp_: line = salt.utils.stringutils.to_unicode(line) if line.strip().startswith('sl'): continue iret = _parse_tcp_line(line) sl = next(iter(iret)) if iret[sl][which_end] == port and iret[sl]['state'] == 1: # 1 is ESTABLISHED ret.add(iret[sl]['remote_addr']) if not proc_available: # Fallback to use OS specific tools if salt.utils.platform.is_sunos(): return _sunos_remotes_on(port, which_end) if salt.utils.platform.is_freebsd(): return _freebsd_remotes_on(port, which_end) if salt.utils.platform.is_netbsd(): return _netbsd_remotes_on(port, which_end) if salt.utils.platform.is_openbsd(): return _openbsd_remotes_on(port, which_end) if salt.utils.platform.is_windows(): return _windows_remotes_on(port, which_end) if salt.utils.platform.is_aix(): return _aix_remotes_on(port, which_end) return _linux_remotes_on(port, which_end) return ret def _parse_tcp_line(line): ''' Parse a single line from the contents of /proc/net/tcp or /proc/net/tcp6 ''' ret = {} comps = line.strip().split() sl = comps[0].rstrip(':') ret[sl] = {} l_addr, l_port = comps[1].split(':') r_addr, r_port = comps[2].split(':') ret[sl]['local_addr'] = hex2ip(l_addr, True) ret[sl]['local_port'] = int(l_port, 16) ret[sl]['remote_addr'] = hex2ip(r_addr, True) ret[sl]['remote_port'] = int(r_port, 16) ret[sl]['state'] = int(comps[3], 16) return ret def _netlink_tool_remote_on(port, which_end): ''' Returns set of ipv4 host addresses of remote established connections on local or remote tcp port. Parses output of shell 'ss' to get connections [root@salt-master ~]# ss -ant State Recv-Q Send-Q Local Address:Port Peer Address:Port LISTEN 0 511 *:80 *:* LISTEN 0 128 *:22 *:* ESTAB 0 0 127.0.0.1:56726 127.0.0.1:4505 ''' remotes = set() valid = False try: data = subprocess.check_output(['ss', '-ant']) # pylint: disable=minimum-python-version except subprocess.CalledProcessError: log.error('Failed ss') raise except OSError: # not command "No such file or directory" return None lines = salt.utils.stringutils.to_str(data).split('\n') for line in lines: if 'Address:Port' in line: # ss tools may not be valid valid = True continue elif 'ESTAB' not in line: continue chunks = line.split() local_host, local_port = chunks[3].split(':', 1) remote_host, remote_port = chunks[4].split(':', 1) if which_end == 'remote_port' and int(remote_port) != port: continue if which_end == 'local_port' and int(local_port) != port: continue remotes.add(remote_host) if valid is False: remotes = None return remotes def _sunos_remotes_on(port, which_end): ''' SunOS specific helper function. Returns set of ipv4 host addresses of remote established connections on local or remote tcp port. Parses output of shell 'netstat' to get connections [root@salt-master ~]# netstat -f inet -n TCP: IPv4 Local Address Remote Address Swind Send-Q Rwind Recv-Q State -------------------- -------------------- ----- ------ ----- ------ ----------- 10.0.0.101.4505 10.0.0.1.45329 1064800 0 1055864 0 ESTABLISHED 10.0.0.101.4505 10.0.0.100.50798 1064800 0 1055864 0 ESTABLISHED ''' remotes = set() try: data = subprocess.check_output(['netstat', '-f', 'inet', '-n']) # pylint: disable=minimum-python-version except subprocess.CalledProcessError: log.error('Failed netstat') raise lines = salt.utils.stringutils.to_str(data).split('\n') for line in lines: if 'ESTABLISHED' not in line: continue chunks = line.split() local_host, local_port = chunks[0].rsplit('.', 1) remote_host, remote_port = chunks[1].rsplit('.', 1) if which_end == 'remote_port' and int(remote_port) != port: continue if which_end == 'local_port' and int(local_port) != port: continue remotes.add(remote_host) return remotes def _freebsd_remotes_on(port, which_end): ''' Returns set of ipv4 host addresses of remote established connections on local tcp port port. Parses output of shell 'sockstat' (FreeBSD) to get connections $ sudo sockstat -4 USER COMMAND PID FD PROTO LOCAL ADDRESS FOREIGN ADDRESS root python2.7 1456 29 tcp4 *:4505 *:* root python2.7 1445 17 tcp4 *:4506 *:* root python2.7 1294 14 tcp4 127.0.0.1:11813 127.0.0.1:4505 root python2.7 1294 41 tcp4 127.0.0.1:61115 127.0.0.1:4506 $ sudo sockstat -4 -c -p 4506 USER COMMAND PID FD PROTO LOCAL ADDRESS FOREIGN ADDRESS root python2.7 1294 41 tcp4 127.0.0.1:61115 127.0.0.1:4506 ''' port = int(port) remotes = set() try: cmd = salt.utils.args.shlex_split('sockstat -4 -c -p {0}'.format(port)) data = subprocess.check_output(cmd) # pylint: disable=minimum-python-version except subprocess.CalledProcessError as ex: log.error('Failed "sockstat" with returncode = %s', ex.returncode) raise lines = salt.utils.stringutils.to_str(data).split('\n') for line in lines: chunks = line.split() if not chunks: continue # ['root', 'python2.7', '1456', '37', 'tcp4', # '127.0.0.1:4505-', '127.0.0.1:55703'] # print chunks if 'COMMAND' in chunks[1]: continue # ignore header if len(chunks) < 2: continue # sockstat -4 -c -p 4506 does this with high PIDs: # USER COMMAND PID FD PROTO LOCAL ADDRESS FOREIGN ADDRESS # salt-master python2.781106 35 tcp4 192.168.12.34:4506 192.168.12.45:60143 local = chunks[-2] remote = chunks[-1] lhost, lport = local.split(':') rhost, rport = remote.split(':') if which_end == 'local' and int(lport) != port: # ignore if local port not port continue if which_end == 'remote' and int(rport) != port: # ignore if remote port not port continue remotes.add(rhost) return remotes def _netbsd_remotes_on(port, which_end): ''' Returns set of ipv4 host addresses of remote established connections on local tcp port port. Parses output of shell 'sockstat' (NetBSD) to get connections $ sudo sockstat -4 -n USER COMMAND PID FD PROTO LOCAL ADDRESS FOREIGN ADDRESS root python2.7 1456 29 tcp *.4505 *.* root python2.7 1445 17 tcp *.4506 *.* root python2.7 1294 14 tcp 127.0.0.1.11813 127.0.0.1.4505 root python2.7 1294 41 tcp 127.0.0.1.61115 127.0.0.1.4506 $ sudo sockstat -4 -c -n -p 4506 USER COMMAND PID FD PROTO LOCAL ADDRESS FOREIGN ADDRESS root python2.7 1294 41 tcp 127.0.0.1.61115 127.0.0.1.4506 ''' port = int(port) remotes = set() try: cmd = salt.utils.args.shlex_split('sockstat -4 -c -n -p {0}'.format(port)) data = subprocess.check_output(cmd) # pylint: disable=minimum-python-version except subprocess.CalledProcessError as ex: log.error('Failed "sockstat" with returncode = %s', ex.returncode) raise lines = salt.utils.stringutils.to_str(data).split('\n') for line in lines: chunks = line.split() if not chunks: continue # ['root', 'python2.7', '1456', '37', 'tcp', # '127.0.0.1.4505-', '127.0.0.1.55703'] # print chunks if 'COMMAND' in chunks[1]: continue # ignore header if len(chunks) < 2: continue local = chunks[5].split('.') lport = local.pop() lhost = '.'.join(local) remote = chunks[6].split('.') rport = remote.pop() rhost = '.'.join(remote) if which_end == 'local' and int(lport) != port: # ignore if local port not port continue if which_end == 'remote' and int(rport) != port: # ignore if remote port not port continue remotes.add(rhost) return remotes def _openbsd_remotes_on(port, which_end): ''' OpenBSD specific helper function. Returns set of ipv4 host addresses of remote established connections on local or remote tcp port. Parses output of shell 'netstat' to get connections $ netstat -nf inet Active Internet connections Proto Recv-Q Send-Q Local Address Foreign Address (state) tcp 0 0 10.0.0.101.4505 10.0.0.1.45329 ESTABLISHED tcp 0 0 10.0.0.101.4505 10.0.0.100.50798 ESTABLISHED ''' remotes = set() try: data = subprocess.check_output(['netstat', '-nf', 'inet']) # pylint: disable=minimum-python-version except subprocess.CalledProcessError: log.error('Failed netstat') raise lines = data.split('\n') for line in lines: if 'ESTABLISHED' not in line: continue chunks = line.split() local_host, local_port = chunks[3].rsplit('.', 1) remote_host, remote_port = chunks[4].rsplit('.', 1) if which_end == 'remote_port' and int(remote_port) != port: continue if which_end == 'local_port' and int(local_port) != port: continue remotes.add(remote_host) return remotes def _windows_remotes_on(port, which_end): r''' Windows specific helper function. Returns set of ipv4 host addresses of remote established connections on local or remote tcp port. Parses output of shell 'netstat' to get connections C:\>netstat -n Active Connections Proto Local Address Foreign Address State TCP 10.2.33.17:3007 130.164.12.233:10123 ESTABLISHED TCP 10.2.33.17:3389 130.164.30.5:10378 ESTABLISHED ''' remotes = set() try: data = subprocess.check_output(['netstat', '-n']) # pylint: disable=minimum-python-version except subprocess.CalledProcessError: log.error('Failed netstat') raise lines = salt.utils.stringutils.to_str(data).split('\n') for line in lines: if 'ESTABLISHED' not in line: continue chunks = line.split() local_host, local_port = chunks[1].rsplit(':', 1) remote_host, remote_port = chunks[2].rsplit(':', 1) if which_end == 'remote_port' and int(remote_port) != port: continue if which_end == 'local_port' and int(local_port) != port: continue remotes.add(remote_host) return remotes def _linux_remotes_on(port, which_end): ''' Linux specific helper function. Returns set of ip host addresses of remote established connections on local tcp port port. Parses output of shell 'lsof' to get connections $ sudo lsof -iTCP:4505 -n COMMAND PID USER FD TYPE DEVICE SIZE/OFF NODE NAME Python 9971 root 35u IPv4 0x18a8464a29ca329d 0t0 TCP *:4505 (LISTEN) Python 9971 root 37u IPv4 0x18a8464a29b2b29d 0t0 TCP 127.0.0.1:4505->127.0.0.1:55703 (ESTABLISHED) Python 10152 root 22u IPv4 0x18a8464a29c8cab5 0t0 TCP 127.0.0.1:55703->127.0.0.1:4505 (ESTABLISHED) Python 10153 root 22u IPv4 0x18a8464a29c8cab5 0t0 TCP [fe80::249a]:4505->[fe80::150]:59367 (ESTABLISHED) ''' remotes = set() try: data = subprocess.check_output( ['lsof', '-iTCP:{0:d}'.format(port), '-n', '-P'] # pylint: disable=minimum-python-version ) except subprocess.CalledProcessError as ex: if ex.returncode == 1: # Lsof return 1 if any error was detected, including the failure # to locate Internet addresses, and it is not an error in this case. log.warning('"lsof" returncode = 1, likely no active TCP sessions.') return remotes log.error('Failed "lsof" with returncode = %s', ex.returncode) raise lines = salt.utils.stringutils.to_str(data).split('\n') for line in lines: chunks = line.split() if not chunks: continue # ['Python', '9971', 'root', '37u', 'IPv4', '0x18a8464a29b2b29d', '0t0', # 'TCP', '127.0.0.1:4505->127.0.0.1:55703', '(ESTABLISHED)'] # print chunks if 'COMMAND' in chunks[0]: continue # ignore header if 'ESTABLISHED' not in chunks[-1]: continue # ignore if not ESTABLISHED # '127.0.0.1:4505->127.0.0.1:55703' local, remote = chunks[8].split('->') _, lport = local.rsplit(':', 1) rhost, rport = remote.rsplit(':', 1) if which_end == 'remote_port' and int(rport) != port: continue if which_end == 'local_port' and int(lport) != port: continue remotes.add(rhost.strip("[]")) return remotes def _aix_remotes_on(port, which_end): ''' AIX specific helper function. Returns set of ipv4 host addresses of remote established connections on local or remote tcp port. Parses output of shell 'netstat' to get connections root@la68pp002_pub:/opt/salt/lib/python2.7/site-packages/salt/modules# netstat -f inet -n Active Internet connections Proto Recv-Q Send-Q Local Address Foreign Address (state) tcp4 0 0 172.29.149.95.50093 209.41.78.13.4505 ESTABLISHED tcp4 0 0 127.0.0.1.9514 *.* LISTEN tcp4 0 0 127.0.0.1.9515 *.* LISTEN tcp4 0 0 127.0.0.1.199 127.0.0.1.32779 ESTABLISHED tcp4 0 0 127.0.0.1.32779 127.0.0.1.199 ESTABLISHED tcp4 0 40 172.29.149.95.22 172.29.96.83.41022 ESTABLISHED tcp4 0 0 172.29.149.95.22 172.29.96.83.41032 ESTABLISHED tcp4 0 0 127.0.0.1.32771 127.0.0.1.32775 ESTABLISHED tcp 0 0 127.0.0.1.32775 127.0.0.1.32771 ESTABLISHED tcp4 0 0 127.0.0.1.32771 127.0.0.1.32776 ESTABLISHED tcp 0 0 127.0.0.1.32776 127.0.0.1.32771 ESTABLISHED tcp4 0 0 127.0.0.1.32771 127.0.0.1.32777 ESTABLISHED tcp 0 0 127.0.0.1.32777 127.0.0.1.32771 ESTABLISHED tcp4 0 0 127.0.0.1.32771 127.0.0.1.32778 ESTABLISHED tcp 0 0 127.0.0.1.32778 127.0.0.1.32771 ESTABLISHED ''' remotes = set() try: data = subprocess.check_output(['netstat', '-f', 'inet', '-n']) # pylint: disable=minimum-python-version except subprocess.CalledProcessError: log.error('Failed netstat') raise lines = salt.utils.stringutils.to_str(data).split('\n') for line in lines: if 'ESTABLISHED' not in line: continue chunks = line.split() local_host, local_port = chunks[3].rsplit('.', 1) remote_host, remote_port = chunks[4].rsplit('.', 1) if which_end == 'remote_port' and int(remote_port) != port: continue if which_end == 'local_port' and int(local_port) != port: continue remotes.add(remote_host) return remotes @jinja_filter('gen_mac') def gen_mac(prefix='AC:DE:48'): ''' Generates a MAC address with the defined OUI prefix. Common prefixes: - ``00:16:3E`` -- Xen - ``00:18:51`` -- OpenVZ - ``00:50:56`` -- VMware (manually generated) - ``52:54:00`` -- QEMU/KVM - ``AC:DE:48`` -- PRIVATE References: - http://standards.ieee.org/develop/regauth/oui/oui.txt - https://www.wireshark.org/tools/oui-lookup.html - https://en.wikipedia.org/wiki/MAC_address ''' return '{0}:{1:02X}:{2:02X}:{3:02X}'.format(prefix, random.randint(0, 0xff), random.randint(0, 0xff), random.randint(0, 0xff)) @jinja_filter('mac_str_to_bytes') def mac_str_to_bytes(mac_str): ''' Convert a MAC address string into bytes. Works with or without separators: b1 = mac_str_to_bytes('08:00:27:13:69:77') b2 = mac_str_to_bytes('080027136977') assert b1 == b2 assert isinstance(b1, bytes) ''' if len(mac_str) == 12: pass elif len(mac_str) == 17: sep = mac_str[2] mac_str = mac_str.replace(sep, '') else: raise ValueError('Invalid MAC address') chars = (int(mac_str[s:s+2], 16) for s in range(0, 12, 2)) return bytes(chars) if six.PY3 else b''.join(chr(x) for x in chars) def refresh_dns(): ''' issue #21397: force glibc to re-read resolv.conf ''' try: res_init() except NameError: # Exception raised loading the library, thus res_init is not defined pass @jinja_filter('connection_check') def connection_check(addr, port=80, safe=False, ipv6=None): ''' Provides a convenient alias for the dns_check filter. ''' return dns_check(addr, port, safe, ipv6) @jinja_filter('dns_check') def dns_check(addr, port=80, safe=False, ipv6=None, attempt_connect=True): ''' Return the ip resolved by dns, but do not exit on failure, only raise an exception. Obeys system preference for IPv4/6 address resolution - this can be overridden by the ipv6 flag. Tries to connect to the address before considering it useful. If no address can be reached, the first one resolved is used as a fallback. ''' error = False lookup = addr seen_ipv6 = False family = socket.AF_INET6 if ipv6 else socket.AF_INET if ipv6 is False else socket.AF_UNSPEC hostnames = [] try: refresh_dns() hostnames = socket.getaddrinfo(addr, port, family, socket.SOCK_STREAM) except TypeError: err = ('Attempt to resolve address \'{0}\' failed. Invalid or unresolveable address').format(lookup) raise SaltSystemExit(code=42, msg=err) except socket.error: error = True # If ipv6 is set to True, attempt another lookup using the IPv4 family, # just in case we're attempting to lookup an IPv4 IP # as an IPv6 hostname. if error and ipv6: try: refresh_dns() hostnames = socket.getaddrinfo(addr, port, socket.AF_INET, socket.SOCK_STREAM) except TypeError: err = ('Attempt to resolve address \'{0}\' failed. Invalid or unresolveable address').format(lookup) raise SaltSystemExit(code=42, msg=err) except socket.error: error = True try: if not hostnames: error = True else: resolved = False candidates = [] for h in hostnames: # Input is IP address, passed through unchanged, just return it if h[4][0] == addr: resolved = salt.utils.zeromq.ip_bracket(addr) break candidate_addr = salt.utils.zeromq.ip_bracket(h[4][0]) # sometimes /etc/hosts contains ::1 localhost if not ipv6 and candidate_addr == '[::1]': continue candidates.append(candidate_addr) if attempt_connect: try: s = socket.socket(h[0], socket.SOCK_STREAM) s.settimeout(2) s.connect((candidate_addr.strip('[]'), h[4][1])) s.close() resolved = candidate_addr break except socket.error: pass if not resolved: if candidates: resolved = candidates[0] else: error = True except TypeError: err = ('Attempt to resolve address \'{0}\' failed. Invalid or unresolveable address').format(lookup) raise SaltSystemExit(code=42, msg=err) except socket.error: error = True if error: err = ('DNS lookup or connection check of \'{0}\' failed.').format(addr) if safe: if salt.log.is_console_configured(): # If logging is not configured it also means that either # the master or minion instance calling this hasn't even # started running log.error(err) raise SaltClientError() raise SaltSystemExit(code=42, msg=err) return resolved def parse_host_port(host_port): """ Takes a string argument specifying host or host:port. Returns a (hostname, port) or (ip_address, port) tuple. If no port is given, the second (port) element of the returned tuple will be None. host:port argument, for example, is accepted in the forms of: - hostname - hostname:1234 - hostname.domain.tld - hostname.domain.tld:5678 - [1234::5]:5678 - 1234::5 - 10.11.12.13:4567 - 10.11.12.13 """ host, port = None, None # default _s_ = host_port[:] if _s_[0] == "[": if "]" in host_port: host, _s_ = _s_.lstrip("[").rsplit("]", 1) host = ipaddress.IPv6Address(host).compressed if _s_[0] == ":": port = int(_s_.lstrip(":")) else: if len(_s_) > 1: raise ValueError('found ambiguous "{}" port in "{}"'.format(_s_, host_port)) else: if _s_.count(":") == 1: host, _hostport_separator_, port = _s_.partition(":") try: port = int(port) except ValueError as _e_: log.error('host_port "%s" port value "%s" is not an integer.', host_port, port) raise _e_ else: host = _s_ try: if not isinstance(host, ipaddress._BaseAddress): host_ip = ipaddress.ip_address(host).compressed host = host_ip except ValueError: log.debug('"%s" Not an IP address? Assuming it is a hostname.', host) if host != sanitize_host(host): log.error('bad hostname: "%s"', host) raise ValueError('bad hostname: "{}"'.format(host)) return host, port def is_fqdn(hostname): """ Verify if hostname conforms to be a FQDN. :param hostname: text string with the name of the host :return: bool, True if hostname is correct FQDN, False otherwise """ compliant = re.compile(r"(?!-)[A-Z\d\-\_]{1,63}(?<!-)$", re.IGNORECASE) return "." in hostname and len(hostname) < 0xff and all(compliant.match(x) for x in hostname.rstrip(".").split("."))
saltstack/salt
salt/utils/network.py
win_interfaces
python
def win_interfaces(): ''' Obtain interface information for Windows systems ''' with salt.utils.winapi.Com(): c = wmi.WMI() ifaces = {} for iface in c.Win32_NetworkAdapterConfiguration(IPEnabled=1): ifaces[iface.Description] = dict() if iface.MACAddress: ifaces[iface.Description]['hwaddr'] = iface.MACAddress if iface.IPEnabled: ifaces[iface.Description]['up'] = True for ip in iface.IPAddress: if '.' in ip: if 'inet' not in ifaces[iface.Description]: ifaces[iface.Description]['inet'] = [] item = {'address': ip, 'label': iface.Description} if iface.DefaultIPGateway: broadcast = next((i for i in iface.DefaultIPGateway if '.' in i), '') if broadcast: item['broadcast'] = broadcast if iface.IPSubnet: netmask = next((i for i in iface.IPSubnet if '.' in i), '') if netmask: item['netmask'] = netmask ifaces[iface.Description]['inet'].append(item) if ':' in ip: if 'inet6' not in ifaces[iface.Description]: ifaces[iface.Description]['inet6'] = [] item = {'address': ip} if iface.DefaultIPGateway: broadcast = next((i for i in iface.DefaultIPGateway if ':' in i), '') if broadcast: item['broadcast'] = broadcast if iface.IPSubnet: netmask = next((i for i in iface.IPSubnet if ':' in i), '') if netmask: item['netmask'] = netmask ifaces[iface.Description]['inet6'].append(item) else: ifaces[iface.Description]['up'] = False return ifaces
Obtain interface information for Windows systems
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/network.py#L1005-L1048
null
# -*- coding: utf-8 -*- ''' Define some generic socket functions for network modules ''' # Import python libs from __future__ import absolute_import, unicode_literals, print_function import itertools import os import re import types import socket import logging import platform import random import subprocess from string import ascii_letters, digits # Import 3rd-party libs from salt.ext import six from salt.ext.six.moves import range # pylint: disable=import-error,redefined-builtin # Attempt to import wmi try: import wmi import salt.utils.winapi except ImportError: pass # Import salt libs import salt.utils.args import salt.utils.files import salt.utils.path import salt.utils.platform import salt.utils.stringutils import salt.utils.zeromq from salt._compat import ipaddress from salt.exceptions import SaltClientError, SaltSystemExit from salt.utils.decorators.jinja import jinja_filter from salt.utils.versions import LooseVersion # inet_pton does not exist in Windows, this is a workaround if salt.utils.platform.is_windows(): from salt.ext import win_inet_pton # pylint: disable=unused-import log = logging.getLogger(__name__) try: import ctypes import ctypes.util libc = ctypes.cdll.LoadLibrary(ctypes.util.find_library("c")) res_init = libc.__res_init except (ImportError, OSError, AttributeError, TypeError): pass # pylint: disable=C0103 def sanitize_host(host): ''' Sanitize host string. https://tools.ietf.org/html/rfc1123#section-2.1 ''' RFC952_characters = ascii_letters + digits + ".-" return "".join([c for c in host[0:255] if c in RFC952_characters]) def isportopen(host, port): ''' Return status of a port ''' if not 1 <= int(port) <= 65535: return False sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) out = sock.connect_ex((sanitize_host(host), int(port))) return out def host_to_ips(host): ''' Returns a list of IP addresses of a given hostname or None if not found. ''' ips = [] try: for family, socktype, proto, canonname, sockaddr in socket.getaddrinfo( host, 0, socket.AF_UNSPEC, socket.SOCK_STREAM): if family == socket.AF_INET: ip, port = sockaddr elif family == socket.AF_INET6: ip, port, flow_info, scope_id = sockaddr ips.append(ip) if not ips: ips = None except Exception: ips = None return ips def _generate_minion_id(): ''' Get list of possible host names and convention names. :return: ''' # There are three types of hostnames: # 1. Network names. How host is accessed from the network. # 2. Host aliases. They might be not available in all the network or only locally (/etc/hosts) # 3. Convention names, an internal nodename. class DistinctList(list): ''' List, which allows one to append only distinct objects. Needs to work on Python 2.6, because of collections.OrderedDict only since 2.7 version. Override 'filter()' for custom filtering. ''' localhost_matchers = [r'localhost.*', r'ip6-.*', r'127[.]\d', r'0\.0\.0\.0', r'::1.*', r'ipv6-.*', r'fe00::.*', r'fe02::.*', r'1.0.0.*.ip6.arpa'] def append(self, p_object): if p_object and p_object not in self and not self.filter(p_object): super(DistinctList, self).append(p_object) return self def extend(self, iterable): for obj in iterable: self.append(obj) return self def filter(self, element): 'Returns True if element needs to be filtered' for rgx in self.localhost_matchers: if re.match(rgx, element): return True def first(self): return self and self[0] or None hostname = socket.gethostname() hosts = DistinctList().append( salt.utils.stringutils.to_unicode(socket.getfqdn(salt.utils.stringutils.to_bytes(hostname))) ).append(platform.node()).append(hostname) if not hosts: try: for a_nfo in socket.getaddrinfo(hosts.first() or 'localhost', None, socket.AF_INET, socket.SOCK_RAW, socket.IPPROTO_IP, socket.AI_CANONNAME): if len(a_nfo) > 3: hosts.append(a_nfo[3]) except socket.gaierror: log.warning('Cannot resolve address %s info via socket: %s', hosts.first() or 'localhost (N/A)', socket.gaierror) # Universal method for everywhere (Linux, Slowlaris, Windows etc) for f_name in ('/etc/hostname', '/etc/nodename', '/etc/hosts', r'{win}\system32\drivers\etc\hosts'.format(win=os.getenv('WINDIR'))): try: with salt.utils.files.fopen(f_name) as f_hdl: for line in f_hdl: line = salt.utils.stringutils.to_unicode(line) hst = line.strip().split('#')[0].strip().split() if hst: if hst[0][:4] in ('127.', '::1') or len(hst) == 1: hosts.extend(hst) except IOError: pass # include public and private ipaddresses return hosts.extend([addr for addr in ip_addrs() if not ipaddress.ip_address(addr).is_loopback]) def generate_minion_id(): ''' Return only first element of the hostname from all possible list. :return: ''' try: ret = salt.utils.stringutils.to_unicode(_generate_minion_id().first()) except TypeError: ret = None return ret or 'localhost' def get_socket(addr, type=socket.SOCK_STREAM, proto=0): ''' Return a socket object for the addr IP-version agnostic ''' version = ipaddress.ip_address(addr).version if version == 4: family = socket.AF_INET elif version == 6: family = socket.AF_INET6 return socket.socket(family, type, proto) def get_fqhostname(): ''' Returns the fully qualified hostname ''' # try getaddrinfo() fqdn = None try: addrinfo = socket.getaddrinfo( socket.gethostname(), 0, socket.AF_UNSPEC, socket.SOCK_STREAM, socket.SOL_TCP, socket.AI_CANONNAME ) for info in addrinfo: # info struct [family, socktype, proto, canonname, sockaddr] # On Windows `canonname` can be an empty string # This can cause the function to return `None` if len(info) > 3 and info[3]: fqdn = info[3] break except socket.gaierror: pass # NOTE: this used to log.error() but it was later disabled except socket.error as err: log.debug('socket.getaddrinfo() failure while finding fqdn: %s', err) if fqdn is None: fqdn = socket.getfqdn() return fqdn def ip_to_host(ip): ''' Returns the hostname of a given IP ''' try: hostname, aliaslist, ipaddrlist = socket.gethostbyaddr(ip) except Exception as exc: log.debug('salt.utils.network.ip_to_host(%r) failed: %s', ip, exc) hostname = None return hostname # pylint: enable=C0103 def is_reachable_host(entity_name): ''' Returns a bool telling if the entity name is a reachable host (IPv4/IPv6/FQDN/etc). :param hostname: :return: ''' try: assert type(socket.getaddrinfo(entity_name, 0, 0, 0, 0)) == list ret = True except socket.gaierror: ret = False return ret def is_ip(ip): ''' Returns a bool telling if the passed IP is a valid IPv4 or IPv6 address. ''' return is_ipv4(ip) or is_ipv6(ip) def is_ipv4(ip): ''' Returns a bool telling if the value passed to it was a valid IPv4 address ''' try: return ipaddress.ip_address(ip).version == 4 except ValueError: return False def is_ipv6(ip): ''' Returns a bool telling if the value passed to it was a valid IPv6 address ''' try: return ipaddress.ip_address(ip).version == 6 except ValueError: return False def is_subnet(cidr): ''' Returns a bool telling if the passed string is an IPv4 or IPv6 subnet ''' return is_ipv4_subnet(cidr) or is_ipv6_subnet(cidr) def is_ipv4_subnet(cidr): ''' Returns a bool telling if the passed string is an IPv4 subnet ''' try: return '/' in cidr and bool(ipaddress.IPv4Network(cidr)) except Exception: return False def is_ipv6_subnet(cidr): ''' Returns a bool telling if the passed string is an IPv6 subnet ''' try: return '/' in cidr and bool(ipaddress.IPv6Network(cidr)) except Exception: return False @jinja_filter('is_ip') def is_ip_filter(ip, options=None): ''' Returns a bool telling if the passed IP is a valid IPv4 or IPv6 address. ''' return is_ipv4_filter(ip, options=options) or is_ipv6_filter(ip, options=options) def _ip_options_global(ip_obj, version): return not ip_obj.is_private def _ip_options_multicast(ip_obj, version): return ip_obj.is_multicast def _ip_options_loopback(ip_obj, version): return ip_obj.is_loopback def _ip_options_link_local(ip_obj, version): return ip_obj.is_link_local def _ip_options_private(ip_obj, version): return ip_obj.is_private def _ip_options_reserved(ip_obj, version): return ip_obj.is_reserved def _ip_options_site_local(ip_obj, version): if version == 6: return ip_obj.is_site_local return False def _ip_options_unspecified(ip_obj, version): return ip_obj.is_unspecified def _ip_options(ip_obj, version, options=None): # will process and IP options options_fun_map = { 'global': _ip_options_global, 'link-local': _ip_options_link_local, 'linklocal': _ip_options_link_local, 'll': _ip_options_link_local, 'link_local': _ip_options_link_local, 'loopback': _ip_options_loopback, 'lo': _ip_options_loopback, 'multicast': _ip_options_multicast, 'private': _ip_options_private, 'public': _ip_options_global, 'reserved': _ip_options_reserved, 'site-local': _ip_options_site_local, 'sl': _ip_options_site_local, 'site_local': _ip_options_site_local, 'unspecified': _ip_options_unspecified } if not options: return six.text_type(ip_obj) # IP version already checked options_list = [option.strip() for option in options.split(',')] for option, fun in options_fun_map.items(): if option in options_list: fun_res = fun(ip_obj, version) if not fun_res: return None # stop at first failed test # else continue return six.text_type(ip_obj) def _is_ipv(ip, version, options=None): if not version: version = 4 if version not in (4, 6): return None try: ip_obj = ipaddress.ip_address(ip) except ValueError: # maybe it is an IP network try: ip_obj = ipaddress.ip_interface(ip) except ValueError: # nope, still not :( return None if not ip_obj.version == version: return None # has the right version, let's move on return _ip_options(ip_obj, version, options=options) @jinja_filter('is_ipv4') def is_ipv4_filter(ip, options=None): ''' Returns a bool telling if the value passed to it was a valid IPv4 address. ip The IP address. net: False Consider IP addresses followed by netmask. options CSV of options regarding the nature of the IP address. E.g.: loopback, multicast, private etc. ''' _is_ipv4 = _is_ipv(ip, 4, options=options) return isinstance(_is_ipv4, six.string_types) @jinja_filter('is_ipv6') def is_ipv6_filter(ip, options=None): ''' Returns a bool telling if the value passed to it was a valid IPv6 address. ip The IP address. net: False Consider IP addresses followed by netmask. options CSV of options regarding the nature of the IP address. E.g.: loopback, multicast, private etc. ''' _is_ipv6 = _is_ipv(ip, 6, options=options) return isinstance(_is_ipv6, six.string_types) def _ipv_filter(value, version, options=None): if version not in (4, 6): return if isinstance(value, (six.string_types, six.text_type, six.binary_type)): return _is_ipv(value, version, options=options) # calls is_ipv4 or is_ipv6 for `value` elif isinstance(value, (list, tuple, types.GeneratorType)): # calls is_ipv4 or is_ipv6 for each element in the list # os it filters and returns only those elements having the desired IP version return [ _is_ipv(addr, version, options=options) for addr in value if _is_ipv(addr, version, options=options) is not None ] return None @jinja_filter('ipv4') def ipv4(value, options=None): ''' Filters a list and returns IPv4 values only. ''' return _ipv_filter(value, 4, options=options) @jinja_filter('ipv6') def ipv6(value, options=None): ''' Filters a list and returns IPv6 values only. ''' return _ipv_filter(value, 6, options=options) @jinja_filter('ipaddr') def ipaddr(value, options=None): ''' Filters and returns only valid IP objects. ''' ipv4_obj = ipv4(value, options=options) ipv6_obj = ipv6(value, options=options) if ipv4_obj is None or ipv6_obj is None: # an IP address can be either IPv4 either IPv6 # therefofe if the value passed as arg is not a list, at least one of the calls above will return None # if one of them is none, means that we should return only one of them return ipv4_obj or ipv6_obj # one of them else: return ipv4_obj + ipv6_obj # extend lists def _filter_ipaddr(value, options, version=None): ipaddr_filter_out = None if version: if version == 4: ipaddr_filter_out = ipv4(value, options) elif version == 6: ipaddr_filter_out = ipv6(value, options) else: ipaddr_filter_out = ipaddr(value, options) if not ipaddr_filter_out: return if not isinstance(ipaddr_filter_out, (list, tuple, types.GeneratorType)): ipaddr_filter_out = [ipaddr_filter_out] return ipaddr_filter_out @jinja_filter('ip_host') def ip_host(value, options=None, version=None): ''' Returns the interfaces IP address, e.g.: 192.168.0.1/28. ''' ipaddr_filter_out = _filter_ipaddr(value, options=options, version=version) if not ipaddr_filter_out: return if not isinstance(value, (list, tuple, types.GeneratorType)): return six.text_type(ipaddress.ip_interface(ipaddr_filter_out[0])) return [six.text_type(ipaddress.ip_interface(ip_a)) for ip_a in ipaddr_filter_out] def _network_hosts(ip_addr_entry): return [ six.text_type(host) for host in ipaddress.ip_network(ip_addr_entry, strict=False).hosts() ] @jinja_filter('network_hosts') def network_hosts(value, options=None, version=None): ''' Return the list of hosts within a network. .. note:: When running this command with a large IPv6 network, the command will take a long time to gather all of the hosts. ''' ipaddr_filter_out = _filter_ipaddr(value, options=options, version=version) if not ipaddr_filter_out: return if not isinstance(value, (list, tuple, types.GeneratorType)): return _network_hosts(ipaddr_filter_out[0]) return [ _network_hosts(ip_a) for ip_a in ipaddr_filter_out ] def _network_size(ip_addr_entry): return ipaddress.ip_network(ip_addr_entry, strict=False).num_addresses @jinja_filter('network_size') def network_size(value, options=None, version=None): ''' Get the size of a network. ''' ipaddr_filter_out = _filter_ipaddr(value, options=options, version=version) if not ipaddr_filter_out: return if not isinstance(value, (list, tuple, types.GeneratorType)): return _network_size(ipaddr_filter_out[0]) return [ _network_size(ip_a) for ip_a in ipaddr_filter_out ] def natural_ipv4_netmask(ip, fmt='prefixlen'): ''' Returns the "natural" mask of an IPv4 address ''' bits = _ipv4_to_bits(ip) if bits.startswith('11'): mask = '24' elif bits.startswith('1'): mask = '16' else: mask = '8' if fmt == 'netmask': return cidr_to_ipv4_netmask(mask) else: return '/' + mask def rpad_ipv4_network(ip): ''' Returns an IP network address padded with zeros. Ex: '192.168.3' -> '192.168.3.0' '10.209' -> '10.209.0.0' ''' return '.'.join(itertools.islice(itertools.chain(ip.split('.'), '0000'), 0, 4)) def cidr_to_ipv4_netmask(cidr_bits): ''' Returns an IPv4 netmask ''' try: cidr_bits = int(cidr_bits) if not 1 <= cidr_bits <= 32: return '' except ValueError: return '' netmask = '' for idx in range(4): if idx: netmask += '.' if cidr_bits >= 8: netmask += '255' cidr_bits -= 8 else: netmask += '{0:d}'.format(256 - (2 ** (8 - cidr_bits))) cidr_bits = 0 return netmask def _number_of_set_bits_to_ipv4_netmask(set_bits): # pylint: disable=C0103 ''' Returns an IPv4 netmask from the integer representation of that mask. Ex. 0xffffff00 -> '255.255.255.0' ''' return cidr_to_ipv4_netmask(_number_of_set_bits(set_bits)) # pylint: disable=C0103 def _number_of_set_bits(x): ''' Returns the number of bits that are set in a 32bit int ''' # Taken from http://stackoverflow.com/a/4912729. Many thanks! x -= (x >> 1) & 0x55555555 x = ((x >> 2) & 0x33333333) + (x & 0x33333333) x = ((x >> 4) + x) & 0x0f0f0f0f x += x >> 8 x += x >> 16 return x & 0x0000003f # pylint: enable=C0103 def _interfaces_ip(out): ''' Uses ip to return a dictionary of interfaces with various information about each (up/down state, ip address, netmask, and hwaddr) ''' ret = dict() def parse_network(value, cols): ''' Return a tuple of ip, netmask, broadcast based on the current set of cols ''' brd = None scope = None if '/' in value: # we have a CIDR in this address ip, cidr = value.split('/') # pylint: disable=C0103 else: ip = value # pylint: disable=C0103 cidr = 32 if type_ == 'inet': mask = cidr_to_ipv4_netmask(int(cidr)) if 'brd' in cols: brd = cols[cols.index('brd') + 1] elif type_ == 'inet6': mask = cidr if 'scope' in cols: scope = cols[cols.index('scope') + 1] return (ip, mask, brd, scope) groups = re.compile('\r?\n\\d').split(out) for group in groups: iface = None data = dict() for line in group.splitlines(): if ' ' not in line: continue match = re.match(r'^\d*:\s+([\w.\-]+)(?:@)?([\w.\-]+)?:\s+<(.+)>', line) if match: iface, parent, attrs = match.groups() if 'UP' in attrs.split(','): data['up'] = True else: data['up'] = False if parent: data['parent'] = parent continue cols = line.split() if len(cols) >= 2: type_, value = tuple(cols[0:2]) iflabel = cols[-1:][0] if type_ in ('inet', 'inet6'): if 'secondary' not in cols: ipaddr, netmask, broadcast, scope = parse_network(value, cols) if type_ == 'inet': if 'inet' not in data: data['inet'] = list() addr_obj = dict() addr_obj['address'] = ipaddr addr_obj['netmask'] = netmask addr_obj['broadcast'] = broadcast addr_obj['label'] = iflabel data['inet'].append(addr_obj) elif type_ == 'inet6': if 'inet6' not in data: data['inet6'] = list() addr_obj = dict() addr_obj['address'] = ipaddr addr_obj['prefixlen'] = netmask addr_obj['scope'] = scope data['inet6'].append(addr_obj) else: if 'secondary' not in data: data['secondary'] = list() ip_, mask, brd, scp = parse_network(value, cols) data['secondary'].append({ 'type': type_, 'address': ip_, 'netmask': mask, 'broadcast': brd, 'label': iflabel, }) del ip_, mask, brd, scp elif type_.startswith('link'): data['hwaddr'] = value if iface: ret[iface] = data del iface, data return ret def _interfaces_ifconfig(out): ''' Uses ifconfig to return a dictionary of interfaces with various information about each (up/down state, ip address, netmask, and hwaddr) ''' ret = dict() piface = re.compile(r'^([^\s:]+)') pmac = re.compile('.*?(?:HWaddr|ether|address:|lladdr) ([0-9a-fA-F:]+)') if salt.utils.platform.is_sunos(): pip = re.compile(r'.*?(?:inet\s+)([0-9]+\.[0-9]+\.[0-9]+\.[0-9]+)(.*)') pip6 = re.compile('.*?(?:inet6 )([0-9a-fA-F:]+)') pmask6 = re.compile(r'.*?(?:inet6 [0-9a-fA-F:]+/(\d+)).*') else: pip = re.compile(r'.*?(?:inet addr:|inet [^\d]*)(.*?)\s') pip6 = re.compile('.*?(?:inet6 addr: (.*?)/|inet6 )([0-9a-fA-F:]+)') pmask6 = re.compile(r'.*?(?:inet6 addr: [0-9a-fA-F:]+/(\d+)|prefixlen (\d+))(?: Scope:([a-zA-Z]+)| scopeid (0x[0-9a-fA-F]))?') pmask = re.compile(r'.*?(?:Mask:|netmask )(?:((?:0x)?[0-9a-fA-F]{8})|([\d\.]+))') pupdown = re.compile('UP') pbcast = re.compile(r'.*?(?:Bcast:|broadcast )([\d\.]+)') groups = re.compile('\r?\n(?=\\S)').split(out) for group in groups: data = dict() iface = '' updown = False for line in group.splitlines(): miface = piface.match(line) mmac = pmac.match(line) mip = pip.match(line) mip6 = pip6.match(line) mupdown = pupdown.search(line) if miface: iface = miface.group(1) if mmac: data['hwaddr'] = mmac.group(1) if salt.utils.platform.is_sunos(): expand_mac = [] for chunk in data['hwaddr'].split(':'): expand_mac.append('0{0}'.format(chunk) if len(chunk) < 2 else '{0}'.format(chunk)) data['hwaddr'] = ':'.join(expand_mac) if mip: if 'inet' not in data: data['inet'] = list() addr_obj = dict() addr_obj['address'] = mip.group(1) mmask = pmask.match(line) if mmask: if mmask.group(1): mmask = _number_of_set_bits_to_ipv4_netmask( int(mmask.group(1), 16)) else: mmask = mmask.group(2) addr_obj['netmask'] = mmask mbcast = pbcast.match(line) if mbcast: addr_obj['broadcast'] = mbcast.group(1) data['inet'].append(addr_obj) if mupdown: updown = True if mip6: if 'inet6' not in data: data['inet6'] = list() addr_obj = dict() addr_obj['address'] = mip6.group(1) or mip6.group(2) mmask6 = pmask6.match(line) if mmask6: addr_obj['prefixlen'] = mmask6.group(1) or mmask6.group(2) if not salt.utils.platform.is_sunos(): ipv6scope = mmask6.group(3) or mmask6.group(4) addr_obj['scope'] = ipv6scope.lower() if ipv6scope is not None else ipv6scope # SunOS sometimes has ::/0 as inet6 addr when using addrconf if not salt.utils.platform.is_sunos() \ or addr_obj['address'] != '::' \ and addr_obj['prefixlen'] != 0: data['inet6'].append(addr_obj) data['up'] = updown if iface in ret: # SunOS optimization, where interfaces occur twice in 'ifconfig -a' # output with the same name: for ipv4 and then for ipv6 addr family. # Every instance has it's own 'UP' status and we assume that ipv4 # status determines global interface status. # # merge items with higher priority for older values # after that merge the inet and inet6 sub items for both ret[iface] = dict(list(data.items()) + list(ret[iface].items())) if 'inet' in data: ret[iface]['inet'].extend(x for x in data['inet'] if x not in ret[iface]['inet']) if 'inet6' in data: ret[iface]['inet6'].extend(x for x in data['inet6'] if x not in ret[iface]['inet6']) else: ret[iface] = data del data return ret def linux_interfaces(): ''' Obtain interface information for *NIX/BSD variants ''' ifaces = dict() ip_path = salt.utils.path.which('ip') ifconfig_path = None if ip_path else salt.utils.path.which('ifconfig') if ip_path: cmd1 = subprocess.Popen( '{0} link show'.format(ip_path), shell=True, close_fds=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT).communicate()[0] cmd2 = subprocess.Popen( '{0} addr show'.format(ip_path), shell=True, close_fds=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT).communicate()[0] ifaces = _interfaces_ip("{0}\n{1}".format( salt.utils.stringutils.to_str(cmd1), salt.utils.stringutils.to_str(cmd2))) elif ifconfig_path: cmd = subprocess.Popen( '{0} -a'.format(ifconfig_path), shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT).communicate()[0] ifaces = _interfaces_ifconfig(salt.utils.stringutils.to_str(cmd)) return ifaces def _netbsd_interfaces_ifconfig(out): ''' Uses ifconfig to return a dictionary of interfaces with various information about each (up/down state, ip address, netmask, and hwaddr) ''' ret = dict() piface = re.compile(r'^([^\s:]+)') pmac = re.compile('.*?address: ([0-9a-f:]+)') pip = re.compile(r'.*?inet [^\d]*(.*?)/([\d]*)\s') pip6 = re.compile(r'.*?inet6 ([0-9a-f:]+)%([a-zA-Z0-9]*)/([\d]*)\s') pupdown = re.compile('UP') pbcast = re.compile(r'.*?broadcast ([\d\.]+)') groups = re.compile('\r?\n(?=\\S)').split(out) for group in groups: data = dict() iface = '' updown = False for line in group.splitlines(): miface = piface.match(line) mmac = pmac.match(line) mip = pip.match(line) mip6 = pip6.match(line) mupdown = pupdown.search(line) if miface: iface = miface.group(1) if mmac: data['hwaddr'] = mmac.group(1) if mip: if 'inet' not in data: data['inet'] = list() addr_obj = dict() addr_obj['address'] = mip.group(1) mmask = mip.group(2) if mip.group(2): addr_obj['netmask'] = cidr_to_ipv4_netmask(mip.group(2)) mbcast = pbcast.match(line) if mbcast: addr_obj['broadcast'] = mbcast.group(1) data['inet'].append(addr_obj) if mupdown: updown = True if mip6: if 'inet6' not in data: data['inet6'] = list() addr_obj = dict() addr_obj['address'] = mip6.group(1) mmask6 = mip6.group(3) addr_obj['scope'] = mip6.group(2) addr_obj['prefixlen'] = mip6.group(3) data['inet6'].append(addr_obj) data['up'] = updown ret[iface] = data del data return ret def netbsd_interfaces(): ''' Obtain interface information for NetBSD >= 8 where the ifconfig output diverged from other BSD variants (Netmask is now part of the address) ''' # NetBSD versions prior to 8.0 can still use linux_interfaces() if LooseVersion(os.uname()[2]) < LooseVersion('8.0'): return linux_interfaces() ifconfig_path = salt.utils.path.which('ifconfig') cmd = subprocess.Popen( '{0} -a'.format(ifconfig_path), shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT).communicate()[0] return _netbsd_interfaces_ifconfig(salt.utils.stringutils.to_str(cmd)) def _interfaces_ipconfig(out): ''' Returns a dictionary of interfaces with various information about each (up/down state, ip address, netmask, and hwaddr) NOTE: This is not used by any function and may be able to be removed in the future. ''' ifaces = dict() iface = None adapter_iface_regex = re.compile(r'adapter (\S.+):$') for line in out.splitlines(): if not line: continue # TODO what does Windows call Infiniband and 10/40gige adapters if line.startswith('Ethernet'): iface = ifaces[adapter_iface_regex.search(line).group(1)] iface['up'] = True addr = None continue if iface: key, val = line.split(',', 1) key = key.strip(' .') val = val.strip() if addr and key == 'Subnet Mask': addr['netmask'] = val elif key in ('IP Address', 'IPv4 Address'): if 'inet' not in iface: iface['inet'] = list() addr = {'address': val.rstrip('(Preferred)'), 'netmask': None, 'broadcast': None} # TODO find the broadcast iface['inet'].append(addr) elif 'IPv6 Address' in key: if 'inet6' not in iface: iface['inet'] = list() # XXX What is the prefixlen!? addr = {'address': val.rstrip('(Preferred)'), 'prefixlen': None} iface['inet6'].append(addr) elif key == 'Physical Address': iface['hwaddr'] = val elif key == 'Media State': # XXX seen used for tunnel adaptors # might be useful iface['up'] = (val != 'Media disconnected') def interfaces(): ''' Return a dictionary of information about all the interfaces on the minion ''' if salt.utils.platform.is_windows(): return win_interfaces() elif salt.utils.platform.is_netbsd(): return netbsd_interfaces() else: return linux_interfaces() def get_net_start(ipaddr, netmask): ''' Return the address of the network ''' net = ipaddress.ip_network('{0}/{1}'.format(ipaddr, netmask), strict=False) return six.text_type(net.network_address) def get_net_size(mask): ''' Turns an IPv4 netmask into it's corresponding prefix length (255.255.255.0 -> 24 as in 192.168.1.10/24). ''' binary_str = '' for octet in mask.split('.'): binary_str += bin(int(octet))[2:].zfill(8) return len(binary_str.rstrip('0')) def calc_net(ipaddr, netmask=None): ''' Takes IP (CIDR notation supported) and optionally netmask and returns the network in CIDR-notation. (The IP can be any IP inside the subnet) ''' if netmask is not None: ipaddr = '{0}/{1}'.format(ipaddr, netmask) return six.text_type(ipaddress.ip_network(ipaddr, strict=False)) def _ipv4_to_bits(ipaddr): ''' Accepts an IPv4 dotted quad and returns a string representing its binary counterpart ''' return ''.join([bin(int(x))[2:].rjust(8, '0') for x in ipaddr.split('.')]) def _get_iface_info(iface): ''' If `iface` is available, return interface info and no error, otherwise return no info and log and return an error ''' iface_info = interfaces() if iface in iface_info.keys(): return iface_info, False else: error_msg = ('Interface "{0}" not in available interfaces: "{1}"' ''.format(iface, '", "'.join(iface_info.keys()))) log.error(error_msg) return None, error_msg def _hw_addr_aix(iface): ''' Return the hardware address (a.k.a. MAC address) for a given interface on AIX MAC address not available in through interfaces ''' cmd = subprocess.Popen( 'entstat -d {0} | grep \'Hardware Address\''.format(iface), shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT).communicate()[0] if cmd: comps = cmd.split(' ') if len(comps) == 3: mac_addr = comps[2].strip('\'').strip() return mac_addr error_msg = ('Interface "{0}" either not available or does not contain a hardware address'.format(iface)) log.error(error_msg) return error_msg def hw_addr(iface): ''' Return the hardware address (a.k.a. MAC address) for a given interface .. versionchanged:: 2016.11.4 Added support for AIX ''' if salt.utils.platform.is_aix(): return _hw_addr_aix iface_info, error = _get_iface_info(iface) if error is False: return iface_info.get(iface, {}).get('hwaddr', '') else: return error def interface(iface): ''' Return the details of `iface` or an error if it does not exist ''' iface_info, error = _get_iface_info(iface) if error is False: return iface_info.get(iface, {}).get('inet', '') else: return error def interface_ip(iface): ''' Return `iface` IPv4 addr or an error if `iface` does not exist ''' iface_info, error = _get_iface_info(iface) if error is False: inet = iface_info.get(iface, {}).get('inet', None) return inet[0].get('address', '') if inet else '' else: return error def _subnets(proto='inet', interfaces_=None): ''' Returns a list of subnets to which the host belongs ''' if interfaces_ is None: ifaces = interfaces() elif isinstance(interfaces_, list): ifaces = {} for key, value in six.iteritems(interfaces()): if key in interfaces_: ifaces[key] = value else: ifaces = {interfaces_: interfaces().get(interfaces_, {})} ret = set() if proto == 'inet': subnet = 'netmask' dflt_cidr = 32 elif proto == 'inet6': subnet = 'prefixlen' dflt_cidr = 128 else: log.error('Invalid proto %s calling subnets()', proto) return for ip_info in six.itervalues(ifaces): addrs = ip_info.get(proto, []) addrs.extend([addr for addr in ip_info.get('secondary', []) if addr.get('type') == proto]) for intf in addrs: if subnet in intf: intf = ipaddress.ip_interface('{0}/{1}'.format(intf['address'], intf[subnet])) else: intf = ipaddress.ip_interface('{0}/{1}'.format(intf['address'], dflt_cidr)) if not intf.is_loopback: ret.add(intf.network) return [six.text_type(net) for net in sorted(ret)] def subnets(interfaces=None): ''' Returns a list of IPv4 subnets to which the host belongs ''' return _subnets('inet', interfaces_=interfaces) def subnets6(): ''' Returns a list of IPv6 subnets to which the host belongs ''' return _subnets('inet6') def in_subnet(cidr, addr=None): ''' Returns True if host or (any of) addrs is within specified subnet, otherwise False ''' try: cidr = ipaddress.ip_network(cidr) except ValueError: log.error('Invalid CIDR \'%s\'', cidr) return False if addr is None: addr = ip_addrs() addr.extend(ip_addrs6()) elif not isinstance(addr, (list, tuple)): addr = (addr,) return any(ipaddress.ip_address(item) in cidr for item in addr) def _ip_addrs(interface=None, include_loopback=False, interface_data=None, proto='inet'): ''' Return the full list of IP adresses matching the criteria proto = inet|inet6 ''' ret = set() ifaces = interface_data \ if isinstance(interface_data, dict) \ else interfaces() if interface is None: target_ifaces = ifaces else: target_ifaces = dict([(k, v) for k, v in six.iteritems(ifaces) if k == interface]) if not target_ifaces: log.error('Interface %s not found.', interface) for ip_info in six.itervalues(target_ifaces): addrs = ip_info.get(proto, []) addrs.extend([addr for addr in ip_info.get('secondary', []) if addr.get('type') == proto]) for addr in addrs: addr = ipaddress.ip_address(addr.get('address')) if not addr.is_loopback or include_loopback: ret.add(addr) return [six.text_type(addr) for addr in sorted(ret)] def ip_addrs(interface=None, include_loopback=False, interface_data=None): ''' Returns a list of IPv4 addresses assigned to the host. 127.0.0.1 is ignored, unless 'include_loopback=True' is indicated. If 'interface' is provided, then only IP addresses from that interface will be returned. ''' return _ip_addrs(interface, include_loopback, interface_data, 'inet') def ip_addrs6(interface=None, include_loopback=False, interface_data=None): ''' Returns a list of IPv6 addresses assigned to the host. ::1 is ignored, unless 'include_loopback=True' is indicated. If 'interface' is provided, then only IP addresses from that interface will be returned. ''' return _ip_addrs(interface, include_loopback, interface_data, 'inet6') def hex2ip(hex_ip, invert=False): ''' Convert a hex string to an ip, if a failure occurs the original hex is returned. If 'invert=True' assume that ip from /proc/net/<proto> ''' if len(hex_ip) == 32: # ipv6 ip = [] for i in range(0, 32, 8): ip_part = hex_ip[i:i + 8] ip_part = [ip_part[x:x + 2] for x in range(0, 8, 2)] if invert: ip.append("{0[3]}{0[2]}:{0[1]}{0[0]}".format(ip_part)) else: ip.append("{0[0]}{0[1]}:{0[2]}{0[3]}".format(ip_part)) try: address = ipaddress.IPv6Address(":".join(ip)) if address.ipv4_mapped: return str(address.ipv4_mapped) else: return address.compressed except ipaddress.AddressValueError as ex: log.error('hex2ip - ipv6 address error: %s', ex) return hex_ip try: hip = int(hex_ip, 16) except ValueError: return hex_ip if invert: return '{3}.{2}.{1}.{0}'.format(hip >> 24 & 255, hip >> 16 & 255, hip >> 8 & 255, hip & 255) return '{0}.{1}.{2}.{3}'.format(hip >> 24 & 255, hip >> 16 & 255, hip >> 8 & 255, hip & 255) def mac2eui64(mac, prefix=None): ''' Convert a MAC address to a EUI64 identifier or, with prefix provided, a full IPv6 address ''' # http://tools.ietf.org/html/rfc4291#section-2.5.1 eui64 = re.sub(r'[.:-]', '', mac).lower() eui64 = eui64[0:6] + 'fffe' + eui64[6:] eui64 = hex(int(eui64[0:2], 16) | 2)[2:].zfill(2) + eui64[2:] if prefix is None: return ':'.join(re.findall(r'.{4}', eui64)) else: try: net = ipaddress.ip_network(prefix, strict=False) euil = int('0x{0}'.format(eui64), 16) return '{0}/{1}'.format(net[euil], net.prefixlen) except Exception: return def active_tcp(): ''' Return a dict describing all active tcp connections as quickly as possible ''' ret = {} for statf in ['/proc/net/tcp', '/proc/net/tcp6']: if os.path.isfile(statf): with salt.utils.files.fopen(statf, 'rb') as fp_: for line in fp_: line = salt.utils.stringutils.to_unicode(line) if line.strip().startswith('sl'): continue iret = _parse_tcp_line(line) sl = next(iter(iret)) if iret[sl]['state'] == 1: # 1 is ESTABLISHED del iret[sl]['state'] ret[len(ret)] = iret[sl] return ret def local_port_tcp(port): ''' Return a set of remote ip addrs attached to the specified local port ''' ret = _remotes_on(port, 'local_port') return ret def remote_port_tcp(port): ''' Return a set of ip addrs the current host is connected to on given port ''' ret = _remotes_on(port, 'remote_port') return ret def _remotes_on(port, which_end): ''' Return a set of ip addrs active tcp connections ''' port = int(port) ret = _netlink_tool_remote_on(port, which_end) if ret is not None: return ret ret = set() proc_available = False for statf in ['/proc/net/tcp', '/proc/net/tcp6']: if os.path.isfile(statf): proc_available = True with salt.utils.files.fopen(statf, 'r') as fp_: for line in fp_: line = salt.utils.stringutils.to_unicode(line) if line.strip().startswith('sl'): continue iret = _parse_tcp_line(line) sl = next(iter(iret)) if iret[sl][which_end] == port and iret[sl]['state'] == 1: # 1 is ESTABLISHED ret.add(iret[sl]['remote_addr']) if not proc_available: # Fallback to use OS specific tools if salt.utils.platform.is_sunos(): return _sunos_remotes_on(port, which_end) if salt.utils.platform.is_freebsd(): return _freebsd_remotes_on(port, which_end) if salt.utils.platform.is_netbsd(): return _netbsd_remotes_on(port, which_end) if salt.utils.platform.is_openbsd(): return _openbsd_remotes_on(port, which_end) if salt.utils.platform.is_windows(): return _windows_remotes_on(port, which_end) if salt.utils.platform.is_aix(): return _aix_remotes_on(port, which_end) return _linux_remotes_on(port, which_end) return ret def _parse_tcp_line(line): ''' Parse a single line from the contents of /proc/net/tcp or /proc/net/tcp6 ''' ret = {} comps = line.strip().split() sl = comps[0].rstrip(':') ret[sl] = {} l_addr, l_port = comps[1].split(':') r_addr, r_port = comps[2].split(':') ret[sl]['local_addr'] = hex2ip(l_addr, True) ret[sl]['local_port'] = int(l_port, 16) ret[sl]['remote_addr'] = hex2ip(r_addr, True) ret[sl]['remote_port'] = int(r_port, 16) ret[sl]['state'] = int(comps[3], 16) return ret def _netlink_tool_remote_on(port, which_end): ''' Returns set of ipv4 host addresses of remote established connections on local or remote tcp port. Parses output of shell 'ss' to get connections [root@salt-master ~]# ss -ant State Recv-Q Send-Q Local Address:Port Peer Address:Port LISTEN 0 511 *:80 *:* LISTEN 0 128 *:22 *:* ESTAB 0 0 127.0.0.1:56726 127.0.0.1:4505 ''' remotes = set() valid = False try: data = subprocess.check_output(['ss', '-ant']) # pylint: disable=minimum-python-version except subprocess.CalledProcessError: log.error('Failed ss') raise except OSError: # not command "No such file or directory" return None lines = salt.utils.stringutils.to_str(data).split('\n') for line in lines: if 'Address:Port' in line: # ss tools may not be valid valid = True continue elif 'ESTAB' not in line: continue chunks = line.split() local_host, local_port = chunks[3].split(':', 1) remote_host, remote_port = chunks[4].split(':', 1) if which_end == 'remote_port' and int(remote_port) != port: continue if which_end == 'local_port' and int(local_port) != port: continue remotes.add(remote_host) if valid is False: remotes = None return remotes def _sunos_remotes_on(port, which_end): ''' SunOS specific helper function. Returns set of ipv4 host addresses of remote established connections on local or remote tcp port. Parses output of shell 'netstat' to get connections [root@salt-master ~]# netstat -f inet -n TCP: IPv4 Local Address Remote Address Swind Send-Q Rwind Recv-Q State -------------------- -------------------- ----- ------ ----- ------ ----------- 10.0.0.101.4505 10.0.0.1.45329 1064800 0 1055864 0 ESTABLISHED 10.0.0.101.4505 10.0.0.100.50798 1064800 0 1055864 0 ESTABLISHED ''' remotes = set() try: data = subprocess.check_output(['netstat', '-f', 'inet', '-n']) # pylint: disable=minimum-python-version except subprocess.CalledProcessError: log.error('Failed netstat') raise lines = salt.utils.stringutils.to_str(data).split('\n') for line in lines: if 'ESTABLISHED' not in line: continue chunks = line.split() local_host, local_port = chunks[0].rsplit('.', 1) remote_host, remote_port = chunks[1].rsplit('.', 1) if which_end == 'remote_port' and int(remote_port) != port: continue if which_end == 'local_port' and int(local_port) != port: continue remotes.add(remote_host) return remotes def _freebsd_remotes_on(port, which_end): ''' Returns set of ipv4 host addresses of remote established connections on local tcp port port. Parses output of shell 'sockstat' (FreeBSD) to get connections $ sudo sockstat -4 USER COMMAND PID FD PROTO LOCAL ADDRESS FOREIGN ADDRESS root python2.7 1456 29 tcp4 *:4505 *:* root python2.7 1445 17 tcp4 *:4506 *:* root python2.7 1294 14 tcp4 127.0.0.1:11813 127.0.0.1:4505 root python2.7 1294 41 tcp4 127.0.0.1:61115 127.0.0.1:4506 $ sudo sockstat -4 -c -p 4506 USER COMMAND PID FD PROTO LOCAL ADDRESS FOREIGN ADDRESS root python2.7 1294 41 tcp4 127.0.0.1:61115 127.0.0.1:4506 ''' port = int(port) remotes = set() try: cmd = salt.utils.args.shlex_split('sockstat -4 -c -p {0}'.format(port)) data = subprocess.check_output(cmd) # pylint: disable=minimum-python-version except subprocess.CalledProcessError as ex: log.error('Failed "sockstat" with returncode = %s', ex.returncode) raise lines = salt.utils.stringutils.to_str(data).split('\n') for line in lines: chunks = line.split() if not chunks: continue # ['root', 'python2.7', '1456', '37', 'tcp4', # '127.0.0.1:4505-', '127.0.0.1:55703'] # print chunks if 'COMMAND' in chunks[1]: continue # ignore header if len(chunks) < 2: continue # sockstat -4 -c -p 4506 does this with high PIDs: # USER COMMAND PID FD PROTO LOCAL ADDRESS FOREIGN ADDRESS # salt-master python2.781106 35 tcp4 192.168.12.34:4506 192.168.12.45:60143 local = chunks[-2] remote = chunks[-1] lhost, lport = local.split(':') rhost, rport = remote.split(':') if which_end == 'local' and int(lport) != port: # ignore if local port not port continue if which_end == 'remote' and int(rport) != port: # ignore if remote port not port continue remotes.add(rhost) return remotes def _netbsd_remotes_on(port, which_end): ''' Returns set of ipv4 host addresses of remote established connections on local tcp port port. Parses output of shell 'sockstat' (NetBSD) to get connections $ sudo sockstat -4 -n USER COMMAND PID FD PROTO LOCAL ADDRESS FOREIGN ADDRESS root python2.7 1456 29 tcp *.4505 *.* root python2.7 1445 17 tcp *.4506 *.* root python2.7 1294 14 tcp 127.0.0.1.11813 127.0.0.1.4505 root python2.7 1294 41 tcp 127.0.0.1.61115 127.0.0.1.4506 $ sudo sockstat -4 -c -n -p 4506 USER COMMAND PID FD PROTO LOCAL ADDRESS FOREIGN ADDRESS root python2.7 1294 41 tcp 127.0.0.1.61115 127.0.0.1.4506 ''' port = int(port) remotes = set() try: cmd = salt.utils.args.shlex_split('sockstat -4 -c -n -p {0}'.format(port)) data = subprocess.check_output(cmd) # pylint: disable=minimum-python-version except subprocess.CalledProcessError as ex: log.error('Failed "sockstat" with returncode = %s', ex.returncode) raise lines = salt.utils.stringutils.to_str(data).split('\n') for line in lines: chunks = line.split() if not chunks: continue # ['root', 'python2.7', '1456', '37', 'tcp', # '127.0.0.1.4505-', '127.0.0.1.55703'] # print chunks if 'COMMAND' in chunks[1]: continue # ignore header if len(chunks) < 2: continue local = chunks[5].split('.') lport = local.pop() lhost = '.'.join(local) remote = chunks[6].split('.') rport = remote.pop() rhost = '.'.join(remote) if which_end == 'local' and int(lport) != port: # ignore if local port not port continue if which_end == 'remote' and int(rport) != port: # ignore if remote port not port continue remotes.add(rhost) return remotes def _openbsd_remotes_on(port, which_end): ''' OpenBSD specific helper function. Returns set of ipv4 host addresses of remote established connections on local or remote tcp port. Parses output of shell 'netstat' to get connections $ netstat -nf inet Active Internet connections Proto Recv-Q Send-Q Local Address Foreign Address (state) tcp 0 0 10.0.0.101.4505 10.0.0.1.45329 ESTABLISHED tcp 0 0 10.0.0.101.4505 10.0.0.100.50798 ESTABLISHED ''' remotes = set() try: data = subprocess.check_output(['netstat', '-nf', 'inet']) # pylint: disable=minimum-python-version except subprocess.CalledProcessError: log.error('Failed netstat') raise lines = data.split('\n') for line in lines: if 'ESTABLISHED' not in line: continue chunks = line.split() local_host, local_port = chunks[3].rsplit('.', 1) remote_host, remote_port = chunks[4].rsplit('.', 1) if which_end == 'remote_port' and int(remote_port) != port: continue if which_end == 'local_port' and int(local_port) != port: continue remotes.add(remote_host) return remotes def _windows_remotes_on(port, which_end): r''' Windows specific helper function. Returns set of ipv4 host addresses of remote established connections on local or remote tcp port. Parses output of shell 'netstat' to get connections C:\>netstat -n Active Connections Proto Local Address Foreign Address State TCP 10.2.33.17:3007 130.164.12.233:10123 ESTABLISHED TCP 10.2.33.17:3389 130.164.30.5:10378 ESTABLISHED ''' remotes = set() try: data = subprocess.check_output(['netstat', '-n']) # pylint: disable=minimum-python-version except subprocess.CalledProcessError: log.error('Failed netstat') raise lines = salt.utils.stringutils.to_str(data).split('\n') for line in lines: if 'ESTABLISHED' not in line: continue chunks = line.split() local_host, local_port = chunks[1].rsplit(':', 1) remote_host, remote_port = chunks[2].rsplit(':', 1) if which_end == 'remote_port' and int(remote_port) != port: continue if which_end == 'local_port' and int(local_port) != port: continue remotes.add(remote_host) return remotes def _linux_remotes_on(port, which_end): ''' Linux specific helper function. Returns set of ip host addresses of remote established connections on local tcp port port. Parses output of shell 'lsof' to get connections $ sudo lsof -iTCP:4505 -n COMMAND PID USER FD TYPE DEVICE SIZE/OFF NODE NAME Python 9971 root 35u IPv4 0x18a8464a29ca329d 0t0 TCP *:4505 (LISTEN) Python 9971 root 37u IPv4 0x18a8464a29b2b29d 0t0 TCP 127.0.0.1:4505->127.0.0.1:55703 (ESTABLISHED) Python 10152 root 22u IPv4 0x18a8464a29c8cab5 0t0 TCP 127.0.0.1:55703->127.0.0.1:4505 (ESTABLISHED) Python 10153 root 22u IPv4 0x18a8464a29c8cab5 0t0 TCP [fe80::249a]:4505->[fe80::150]:59367 (ESTABLISHED) ''' remotes = set() try: data = subprocess.check_output( ['lsof', '-iTCP:{0:d}'.format(port), '-n', '-P'] # pylint: disable=minimum-python-version ) except subprocess.CalledProcessError as ex: if ex.returncode == 1: # Lsof return 1 if any error was detected, including the failure # to locate Internet addresses, and it is not an error in this case. log.warning('"lsof" returncode = 1, likely no active TCP sessions.') return remotes log.error('Failed "lsof" with returncode = %s', ex.returncode) raise lines = salt.utils.stringutils.to_str(data).split('\n') for line in lines: chunks = line.split() if not chunks: continue # ['Python', '9971', 'root', '37u', 'IPv4', '0x18a8464a29b2b29d', '0t0', # 'TCP', '127.0.0.1:4505->127.0.0.1:55703', '(ESTABLISHED)'] # print chunks if 'COMMAND' in chunks[0]: continue # ignore header if 'ESTABLISHED' not in chunks[-1]: continue # ignore if not ESTABLISHED # '127.0.0.1:4505->127.0.0.1:55703' local, remote = chunks[8].split('->') _, lport = local.rsplit(':', 1) rhost, rport = remote.rsplit(':', 1) if which_end == 'remote_port' and int(rport) != port: continue if which_end == 'local_port' and int(lport) != port: continue remotes.add(rhost.strip("[]")) return remotes def _aix_remotes_on(port, which_end): ''' AIX specific helper function. Returns set of ipv4 host addresses of remote established connections on local or remote tcp port. Parses output of shell 'netstat' to get connections root@la68pp002_pub:/opt/salt/lib/python2.7/site-packages/salt/modules# netstat -f inet -n Active Internet connections Proto Recv-Q Send-Q Local Address Foreign Address (state) tcp4 0 0 172.29.149.95.50093 209.41.78.13.4505 ESTABLISHED tcp4 0 0 127.0.0.1.9514 *.* LISTEN tcp4 0 0 127.0.0.1.9515 *.* LISTEN tcp4 0 0 127.0.0.1.199 127.0.0.1.32779 ESTABLISHED tcp4 0 0 127.0.0.1.32779 127.0.0.1.199 ESTABLISHED tcp4 0 40 172.29.149.95.22 172.29.96.83.41022 ESTABLISHED tcp4 0 0 172.29.149.95.22 172.29.96.83.41032 ESTABLISHED tcp4 0 0 127.0.0.1.32771 127.0.0.1.32775 ESTABLISHED tcp 0 0 127.0.0.1.32775 127.0.0.1.32771 ESTABLISHED tcp4 0 0 127.0.0.1.32771 127.0.0.1.32776 ESTABLISHED tcp 0 0 127.0.0.1.32776 127.0.0.1.32771 ESTABLISHED tcp4 0 0 127.0.0.1.32771 127.0.0.1.32777 ESTABLISHED tcp 0 0 127.0.0.1.32777 127.0.0.1.32771 ESTABLISHED tcp4 0 0 127.0.0.1.32771 127.0.0.1.32778 ESTABLISHED tcp 0 0 127.0.0.1.32778 127.0.0.1.32771 ESTABLISHED ''' remotes = set() try: data = subprocess.check_output(['netstat', '-f', 'inet', '-n']) # pylint: disable=minimum-python-version except subprocess.CalledProcessError: log.error('Failed netstat') raise lines = salt.utils.stringutils.to_str(data).split('\n') for line in lines: if 'ESTABLISHED' not in line: continue chunks = line.split() local_host, local_port = chunks[3].rsplit('.', 1) remote_host, remote_port = chunks[4].rsplit('.', 1) if which_end == 'remote_port' and int(remote_port) != port: continue if which_end == 'local_port' and int(local_port) != port: continue remotes.add(remote_host) return remotes @jinja_filter('gen_mac') def gen_mac(prefix='AC:DE:48'): ''' Generates a MAC address with the defined OUI prefix. Common prefixes: - ``00:16:3E`` -- Xen - ``00:18:51`` -- OpenVZ - ``00:50:56`` -- VMware (manually generated) - ``52:54:00`` -- QEMU/KVM - ``AC:DE:48`` -- PRIVATE References: - http://standards.ieee.org/develop/regauth/oui/oui.txt - https://www.wireshark.org/tools/oui-lookup.html - https://en.wikipedia.org/wiki/MAC_address ''' return '{0}:{1:02X}:{2:02X}:{3:02X}'.format(prefix, random.randint(0, 0xff), random.randint(0, 0xff), random.randint(0, 0xff)) @jinja_filter('mac_str_to_bytes') def mac_str_to_bytes(mac_str): ''' Convert a MAC address string into bytes. Works with or without separators: b1 = mac_str_to_bytes('08:00:27:13:69:77') b2 = mac_str_to_bytes('080027136977') assert b1 == b2 assert isinstance(b1, bytes) ''' if len(mac_str) == 12: pass elif len(mac_str) == 17: sep = mac_str[2] mac_str = mac_str.replace(sep, '') else: raise ValueError('Invalid MAC address') chars = (int(mac_str[s:s+2], 16) for s in range(0, 12, 2)) return bytes(chars) if six.PY3 else b''.join(chr(x) for x in chars) def refresh_dns(): ''' issue #21397: force glibc to re-read resolv.conf ''' try: res_init() except NameError: # Exception raised loading the library, thus res_init is not defined pass @jinja_filter('connection_check') def connection_check(addr, port=80, safe=False, ipv6=None): ''' Provides a convenient alias for the dns_check filter. ''' return dns_check(addr, port, safe, ipv6) @jinja_filter('dns_check') def dns_check(addr, port=80, safe=False, ipv6=None, attempt_connect=True): ''' Return the ip resolved by dns, but do not exit on failure, only raise an exception. Obeys system preference for IPv4/6 address resolution - this can be overridden by the ipv6 flag. Tries to connect to the address before considering it useful. If no address can be reached, the first one resolved is used as a fallback. ''' error = False lookup = addr seen_ipv6 = False family = socket.AF_INET6 if ipv6 else socket.AF_INET if ipv6 is False else socket.AF_UNSPEC hostnames = [] try: refresh_dns() hostnames = socket.getaddrinfo(addr, port, family, socket.SOCK_STREAM) except TypeError: err = ('Attempt to resolve address \'{0}\' failed. Invalid or unresolveable address').format(lookup) raise SaltSystemExit(code=42, msg=err) except socket.error: error = True # If ipv6 is set to True, attempt another lookup using the IPv4 family, # just in case we're attempting to lookup an IPv4 IP # as an IPv6 hostname. if error and ipv6: try: refresh_dns() hostnames = socket.getaddrinfo(addr, port, socket.AF_INET, socket.SOCK_STREAM) except TypeError: err = ('Attempt to resolve address \'{0}\' failed. Invalid or unresolveable address').format(lookup) raise SaltSystemExit(code=42, msg=err) except socket.error: error = True try: if not hostnames: error = True else: resolved = False candidates = [] for h in hostnames: # Input is IP address, passed through unchanged, just return it if h[4][0] == addr: resolved = salt.utils.zeromq.ip_bracket(addr) break candidate_addr = salt.utils.zeromq.ip_bracket(h[4][0]) # sometimes /etc/hosts contains ::1 localhost if not ipv6 and candidate_addr == '[::1]': continue candidates.append(candidate_addr) if attempt_connect: try: s = socket.socket(h[0], socket.SOCK_STREAM) s.settimeout(2) s.connect((candidate_addr.strip('[]'), h[4][1])) s.close() resolved = candidate_addr break except socket.error: pass if not resolved: if candidates: resolved = candidates[0] else: error = True except TypeError: err = ('Attempt to resolve address \'{0}\' failed. Invalid or unresolveable address').format(lookup) raise SaltSystemExit(code=42, msg=err) except socket.error: error = True if error: err = ('DNS lookup or connection check of \'{0}\' failed.').format(addr) if safe: if salt.log.is_console_configured(): # If logging is not configured it also means that either # the master or minion instance calling this hasn't even # started running log.error(err) raise SaltClientError() raise SaltSystemExit(code=42, msg=err) return resolved def parse_host_port(host_port): """ Takes a string argument specifying host or host:port. Returns a (hostname, port) or (ip_address, port) tuple. If no port is given, the second (port) element of the returned tuple will be None. host:port argument, for example, is accepted in the forms of: - hostname - hostname:1234 - hostname.domain.tld - hostname.domain.tld:5678 - [1234::5]:5678 - 1234::5 - 10.11.12.13:4567 - 10.11.12.13 """ host, port = None, None # default _s_ = host_port[:] if _s_[0] == "[": if "]" in host_port: host, _s_ = _s_.lstrip("[").rsplit("]", 1) host = ipaddress.IPv6Address(host).compressed if _s_[0] == ":": port = int(_s_.lstrip(":")) else: if len(_s_) > 1: raise ValueError('found ambiguous "{}" port in "{}"'.format(_s_, host_port)) else: if _s_.count(":") == 1: host, _hostport_separator_, port = _s_.partition(":") try: port = int(port) except ValueError as _e_: log.error('host_port "%s" port value "%s" is not an integer.', host_port, port) raise _e_ else: host = _s_ try: if not isinstance(host, ipaddress._BaseAddress): host_ip = ipaddress.ip_address(host).compressed host = host_ip except ValueError: log.debug('"%s" Not an IP address? Assuming it is a hostname.', host) if host != sanitize_host(host): log.error('bad hostname: "%s"', host) raise ValueError('bad hostname: "{}"'.format(host)) return host, port def is_fqdn(hostname): """ Verify if hostname conforms to be a FQDN. :param hostname: text string with the name of the host :return: bool, True if hostname is correct FQDN, False otherwise """ compliant = re.compile(r"(?!-)[A-Z\d\-\_]{1,63}(?<!-)$", re.IGNORECASE) return "." in hostname and len(hostname) < 0xff and all(compliant.match(x) for x in hostname.rstrip(".").split("."))
saltstack/salt
salt/utils/network.py
interfaces
python
def interfaces(): ''' Return a dictionary of information about all the interfaces on the minion ''' if salt.utils.platform.is_windows(): return win_interfaces() elif salt.utils.platform.is_netbsd(): return netbsd_interfaces() else: return linux_interfaces()
Return a dictionary of information about all the interfaces on the minion
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/network.py#L1051-L1060
[ "def win_interfaces():\n '''\n Obtain interface information for Windows systems\n '''\n with salt.utils.winapi.Com():\n c = wmi.WMI()\n ifaces = {}\n for iface in c.Win32_NetworkAdapterConfiguration(IPEnabled=1):\n ifaces[iface.Description] = dict()\n if iface.MACAddress:\n ifaces[iface.Description]['hwaddr'] = iface.MACAddress\n if iface.IPEnabled:\n ifaces[iface.Description]['up'] = True\n for ip in iface.IPAddress:\n if '.' in ip:\n if 'inet' not in ifaces[iface.Description]:\n ifaces[iface.Description]['inet'] = []\n item = {'address': ip,\n 'label': iface.Description}\n if iface.DefaultIPGateway:\n broadcast = next((i for i in iface.DefaultIPGateway if '.' in i), '')\n if broadcast:\n item['broadcast'] = broadcast\n if iface.IPSubnet:\n netmask = next((i for i in iface.IPSubnet if '.' in i), '')\n if netmask:\n item['netmask'] = netmask\n ifaces[iface.Description]['inet'].append(item)\n if ':' in ip:\n if 'inet6' not in ifaces[iface.Description]:\n ifaces[iface.Description]['inet6'] = []\n item = {'address': ip}\n if iface.DefaultIPGateway:\n broadcast = next((i for i in iface.DefaultIPGateway if ':' in i), '')\n if broadcast:\n item['broadcast'] = broadcast\n if iface.IPSubnet:\n netmask = next((i for i in iface.IPSubnet if ':' in i), '')\n if netmask:\n item['netmask'] = netmask\n ifaces[iface.Description]['inet6'].append(item)\n else:\n ifaces[iface.Description]['up'] = False\n return ifaces\n" ]
# -*- coding: utf-8 -*- ''' Define some generic socket functions for network modules ''' # Import python libs from __future__ import absolute_import, unicode_literals, print_function import itertools import os import re import types import socket import logging import platform import random import subprocess from string import ascii_letters, digits # Import 3rd-party libs from salt.ext import six from salt.ext.six.moves import range # pylint: disable=import-error,redefined-builtin # Attempt to import wmi try: import wmi import salt.utils.winapi except ImportError: pass # Import salt libs import salt.utils.args import salt.utils.files import salt.utils.path import salt.utils.platform import salt.utils.stringutils import salt.utils.zeromq from salt._compat import ipaddress from salt.exceptions import SaltClientError, SaltSystemExit from salt.utils.decorators.jinja import jinja_filter from salt.utils.versions import LooseVersion # inet_pton does not exist in Windows, this is a workaround if salt.utils.platform.is_windows(): from salt.ext import win_inet_pton # pylint: disable=unused-import log = logging.getLogger(__name__) try: import ctypes import ctypes.util libc = ctypes.cdll.LoadLibrary(ctypes.util.find_library("c")) res_init = libc.__res_init except (ImportError, OSError, AttributeError, TypeError): pass # pylint: disable=C0103 def sanitize_host(host): ''' Sanitize host string. https://tools.ietf.org/html/rfc1123#section-2.1 ''' RFC952_characters = ascii_letters + digits + ".-" return "".join([c for c in host[0:255] if c in RFC952_characters]) def isportopen(host, port): ''' Return status of a port ''' if not 1 <= int(port) <= 65535: return False sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) out = sock.connect_ex((sanitize_host(host), int(port))) return out def host_to_ips(host): ''' Returns a list of IP addresses of a given hostname or None if not found. ''' ips = [] try: for family, socktype, proto, canonname, sockaddr in socket.getaddrinfo( host, 0, socket.AF_UNSPEC, socket.SOCK_STREAM): if family == socket.AF_INET: ip, port = sockaddr elif family == socket.AF_INET6: ip, port, flow_info, scope_id = sockaddr ips.append(ip) if not ips: ips = None except Exception: ips = None return ips def _generate_minion_id(): ''' Get list of possible host names and convention names. :return: ''' # There are three types of hostnames: # 1. Network names. How host is accessed from the network. # 2. Host aliases. They might be not available in all the network or only locally (/etc/hosts) # 3. Convention names, an internal nodename. class DistinctList(list): ''' List, which allows one to append only distinct objects. Needs to work on Python 2.6, because of collections.OrderedDict only since 2.7 version. Override 'filter()' for custom filtering. ''' localhost_matchers = [r'localhost.*', r'ip6-.*', r'127[.]\d', r'0\.0\.0\.0', r'::1.*', r'ipv6-.*', r'fe00::.*', r'fe02::.*', r'1.0.0.*.ip6.arpa'] def append(self, p_object): if p_object and p_object not in self and not self.filter(p_object): super(DistinctList, self).append(p_object) return self def extend(self, iterable): for obj in iterable: self.append(obj) return self def filter(self, element): 'Returns True if element needs to be filtered' for rgx in self.localhost_matchers: if re.match(rgx, element): return True def first(self): return self and self[0] or None hostname = socket.gethostname() hosts = DistinctList().append( salt.utils.stringutils.to_unicode(socket.getfqdn(salt.utils.stringutils.to_bytes(hostname))) ).append(platform.node()).append(hostname) if not hosts: try: for a_nfo in socket.getaddrinfo(hosts.first() or 'localhost', None, socket.AF_INET, socket.SOCK_RAW, socket.IPPROTO_IP, socket.AI_CANONNAME): if len(a_nfo) > 3: hosts.append(a_nfo[3]) except socket.gaierror: log.warning('Cannot resolve address %s info via socket: %s', hosts.first() or 'localhost (N/A)', socket.gaierror) # Universal method for everywhere (Linux, Slowlaris, Windows etc) for f_name in ('/etc/hostname', '/etc/nodename', '/etc/hosts', r'{win}\system32\drivers\etc\hosts'.format(win=os.getenv('WINDIR'))): try: with salt.utils.files.fopen(f_name) as f_hdl: for line in f_hdl: line = salt.utils.stringutils.to_unicode(line) hst = line.strip().split('#')[0].strip().split() if hst: if hst[0][:4] in ('127.', '::1') or len(hst) == 1: hosts.extend(hst) except IOError: pass # include public and private ipaddresses return hosts.extend([addr for addr in ip_addrs() if not ipaddress.ip_address(addr).is_loopback]) def generate_minion_id(): ''' Return only first element of the hostname from all possible list. :return: ''' try: ret = salt.utils.stringutils.to_unicode(_generate_minion_id().first()) except TypeError: ret = None return ret or 'localhost' def get_socket(addr, type=socket.SOCK_STREAM, proto=0): ''' Return a socket object for the addr IP-version agnostic ''' version = ipaddress.ip_address(addr).version if version == 4: family = socket.AF_INET elif version == 6: family = socket.AF_INET6 return socket.socket(family, type, proto) def get_fqhostname(): ''' Returns the fully qualified hostname ''' # try getaddrinfo() fqdn = None try: addrinfo = socket.getaddrinfo( socket.gethostname(), 0, socket.AF_UNSPEC, socket.SOCK_STREAM, socket.SOL_TCP, socket.AI_CANONNAME ) for info in addrinfo: # info struct [family, socktype, proto, canonname, sockaddr] # On Windows `canonname` can be an empty string # This can cause the function to return `None` if len(info) > 3 and info[3]: fqdn = info[3] break except socket.gaierror: pass # NOTE: this used to log.error() but it was later disabled except socket.error as err: log.debug('socket.getaddrinfo() failure while finding fqdn: %s', err) if fqdn is None: fqdn = socket.getfqdn() return fqdn def ip_to_host(ip): ''' Returns the hostname of a given IP ''' try: hostname, aliaslist, ipaddrlist = socket.gethostbyaddr(ip) except Exception as exc: log.debug('salt.utils.network.ip_to_host(%r) failed: %s', ip, exc) hostname = None return hostname # pylint: enable=C0103 def is_reachable_host(entity_name): ''' Returns a bool telling if the entity name is a reachable host (IPv4/IPv6/FQDN/etc). :param hostname: :return: ''' try: assert type(socket.getaddrinfo(entity_name, 0, 0, 0, 0)) == list ret = True except socket.gaierror: ret = False return ret def is_ip(ip): ''' Returns a bool telling if the passed IP is a valid IPv4 or IPv6 address. ''' return is_ipv4(ip) or is_ipv6(ip) def is_ipv4(ip): ''' Returns a bool telling if the value passed to it was a valid IPv4 address ''' try: return ipaddress.ip_address(ip).version == 4 except ValueError: return False def is_ipv6(ip): ''' Returns a bool telling if the value passed to it was a valid IPv6 address ''' try: return ipaddress.ip_address(ip).version == 6 except ValueError: return False def is_subnet(cidr): ''' Returns a bool telling if the passed string is an IPv4 or IPv6 subnet ''' return is_ipv4_subnet(cidr) or is_ipv6_subnet(cidr) def is_ipv4_subnet(cidr): ''' Returns a bool telling if the passed string is an IPv4 subnet ''' try: return '/' in cidr and bool(ipaddress.IPv4Network(cidr)) except Exception: return False def is_ipv6_subnet(cidr): ''' Returns a bool telling if the passed string is an IPv6 subnet ''' try: return '/' in cidr and bool(ipaddress.IPv6Network(cidr)) except Exception: return False @jinja_filter('is_ip') def is_ip_filter(ip, options=None): ''' Returns a bool telling if the passed IP is a valid IPv4 or IPv6 address. ''' return is_ipv4_filter(ip, options=options) or is_ipv6_filter(ip, options=options) def _ip_options_global(ip_obj, version): return not ip_obj.is_private def _ip_options_multicast(ip_obj, version): return ip_obj.is_multicast def _ip_options_loopback(ip_obj, version): return ip_obj.is_loopback def _ip_options_link_local(ip_obj, version): return ip_obj.is_link_local def _ip_options_private(ip_obj, version): return ip_obj.is_private def _ip_options_reserved(ip_obj, version): return ip_obj.is_reserved def _ip_options_site_local(ip_obj, version): if version == 6: return ip_obj.is_site_local return False def _ip_options_unspecified(ip_obj, version): return ip_obj.is_unspecified def _ip_options(ip_obj, version, options=None): # will process and IP options options_fun_map = { 'global': _ip_options_global, 'link-local': _ip_options_link_local, 'linklocal': _ip_options_link_local, 'll': _ip_options_link_local, 'link_local': _ip_options_link_local, 'loopback': _ip_options_loopback, 'lo': _ip_options_loopback, 'multicast': _ip_options_multicast, 'private': _ip_options_private, 'public': _ip_options_global, 'reserved': _ip_options_reserved, 'site-local': _ip_options_site_local, 'sl': _ip_options_site_local, 'site_local': _ip_options_site_local, 'unspecified': _ip_options_unspecified } if not options: return six.text_type(ip_obj) # IP version already checked options_list = [option.strip() for option in options.split(',')] for option, fun in options_fun_map.items(): if option in options_list: fun_res = fun(ip_obj, version) if not fun_res: return None # stop at first failed test # else continue return six.text_type(ip_obj) def _is_ipv(ip, version, options=None): if not version: version = 4 if version not in (4, 6): return None try: ip_obj = ipaddress.ip_address(ip) except ValueError: # maybe it is an IP network try: ip_obj = ipaddress.ip_interface(ip) except ValueError: # nope, still not :( return None if not ip_obj.version == version: return None # has the right version, let's move on return _ip_options(ip_obj, version, options=options) @jinja_filter('is_ipv4') def is_ipv4_filter(ip, options=None): ''' Returns a bool telling if the value passed to it was a valid IPv4 address. ip The IP address. net: False Consider IP addresses followed by netmask. options CSV of options regarding the nature of the IP address. E.g.: loopback, multicast, private etc. ''' _is_ipv4 = _is_ipv(ip, 4, options=options) return isinstance(_is_ipv4, six.string_types) @jinja_filter('is_ipv6') def is_ipv6_filter(ip, options=None): ''' Returns a bool telling if the value passed to it was a valid IPv6 address. ip The IP address. net: False Consider IP addresses followed by netmask. options CSV of options regarding the nature of the IP address. E.g.: loopback, multicast, private etc. ''' _is_ipv6 = _is_ipv(ip, 6, options=options) return isinstance(_is_ipv6, six.string_types) def _ipv_filter(value, version, options=None): if version not in (4, 6): return if isinstance(value, (six.string_types, six.text_type, six.binary_type)): return _is_ipv(value, version, options=options) # calls is_ipv4 or is_ipv6 for `value` elif isinstance(value, (list, tuple, types.GeneratorType)): # calls is_ipv4 or is_ipv6 for each element in the list # os it filters and returns only those elements having the desired IP version return [ _is_ipv(addr, version, options=options) for addr in value if _is_ipv(addr, version, options=options) is not None ] return None @jinja_filter('ipv4') def ipv4(value, options=None): ''' Filters a list and returns IPv4 values only. ''' return _ipv_filter(value, 4, options=options) @jinja_filter('ipv6') def ipv6(value, options=None): ''' Filters a list and returns IPv6 values only. ''' return _ipv_filter(value, 6, options=options) @jinja_filter('ipaddr') def ipaddr(value, options=None): ''' Filters and returns only valid IP objects. ''' ipv4_obj = ipv4(value, options=options) ipv6_obj = ipv6(value, options=options) if ipv4_obj is None or ipv6_obj is None: # an IP address can be either IPv4 either IPv6 # therefofe if the value passed as arg is not a list, at least one of the calls above will return None # if one of them is none, means that we should return only one of them return ipv4_obj or ipv6_obj # one of them else: return ipv4_obj + ipv6_obj # extend lists def _filter_ipaddr(value, options, version=None): ipaddr_filter_out = None if version: if version == 4: ipaddr_filter_out = ipv4(value, options) elif version == 6: ipaddr_filter_out = ipv6(value, options) else: ipaddr_filter_out = ipaddr(value, options) if not ipaddr_filter_out: return if not isinstance(ipaddr_filter_out, (list, tuple, types.GeneratorType)): ipaddr_filter_out = [ipaddr_filter_out] return ipaddr_filter_out @jinja_filter('ip_host') def ip_host(value, options=None, version=None): ''' Returns the interfaces IP address, e.g.: 192.168.0.1/28. ''' ipaddr_filter_out = _filter_ipaddr(value, options=options, version=version) if not ipaddr_filter_out: return if not isinstance(value, (list, tuple, types.GeneratorType)): return six.text_type(ipaddress.ip_interface(ipaddr_filter_out[0])) return [six.text_type(ipaddress.ip_interface(ip_a)) for ip_a in ipaddr_filter_out] def _network_hosts(ip_addr_entry): return [ six.text_type(host) for host in ipaddress.ip_network(ip_addr_entry, strict=False).hosts() ] @jinja_filter('network_hosts') def network_hosts(value, options=None, version=None): ''' Return the list of hosts within a network. .. note:: When running this command with a large IPv6 network, the command will take a long time to gather all of the hosts. ''' ipaddr_filter_out = _filter_ipaddr(value, options=options, version=version) if not ipaddr_filter_out: return if not isinstance(value, (list, tuple, types.GeneratorType)): return _network_hosts(ipaddr_filter_out[0]) return [ _network_hosts(ip_a) for ip_a in ipaddr_filter_out ] def _network_size(ip_addr_entry): return ipaddress.ip_network(ip_addr_entry, strict=False).num_addresses @jinja_filter('network_size') def network_size(value, options=None, version=None): ''' Get the size of a network. ''' ipaddr_filter_out = _filter_ipaddr(value, options=options, version=version) if not ipaddr_filter_out: return if not isinstance(value, (list, tuple, types.GeneratorType)): return _network_size(ipaddr_filter_out[0]) return [ _network_size(ip_a) for ip_a in ipaddr_filter_out ] def natural_ipv4_netmask(ip, fmt='prefixlen'): ''' Returns the "natural" mask of an IPv4 address ''' bits = _ipv4_to_bits(ip) if bits.startswith('11'): mask = '24' elif bits.startswith('1'): mask = '16' else: mask = '8' if fmt == 'netmask': return cidr_to_ipv4_netmask(mask) else: return '/' + mask def rpad_ipv4_network(ip): ''' Returns an IP network address padded with zeros. Ex: '192.168.3' -> '192.168.3.0' '10.209' -> '10.209.0.0' ''' return '.'.join(itertools.islice(itertools.chain(ip.split('.'), '0000'), 0, 4)) def cidr_to_ipv4_netmask(cidr_bits): ''' Returns an IPv4 netmask ''' try: cidr_bits = int(cidr_bits) if not 1 <= cidr_bits <= 32: return '' except ValueError: return '' netmask = '' for idx in range(4): if idx: netmask += '.' if cidr_bits >= 8: netmask += '255' cidr_bits -= 8 else: netmask += '{0:d}'.format(256 - (2 ** (8 - cidr_bits))) cidr_bits = 0 return netmask def _number_of_set_bits_to_ipv4_netmask(set_bits): # pylint: disable=C0103 ''' Returns an IPv4 netmask from the integer representation of that mask. Ex. 0xffffff00 -> '255.255.255.0' ''' return cidr_to_ipv4_netmask(_number_of_set_bits(set_bits)) # pylint: disable=C0103 def _number_of_set_bits(x): ''' Returns the number of bits that are set in a 32bit int ''' # Taken from http://stackoverflow.com/a/4912729. Many thanks! x -= (x >> 1) & 0x55555555 x = ((x >> 2) & 0x33333333) + (x & 0x33333333) x = ((x >> 4) + x) & 0x0f0f0f0f x += x >> 8 x += x >> 16 return x & 0x0000003f # pylint: enable=C0103 def _interfaces_ip(out): ''' Uses ip to return a dictionary of interfaces with various information about each (up/down state, ip address, netmask, and hwaddr) ''' ret = dict() def parse_network(value, cols): ''' Return a tuple of ip, netmask, broadcast based on the current set of cols ''' brd = None scope = None if '/' in value: # we have a CIDR in this address ip, cidr = value.split('/') # pylint: disable=C0103 else: ip = value # pylint: disable=C0103 cidr = 32 if type_ == 'inet': mask = cidr_to_ipv4_netmask(int(cidr)) if 'brd' in cols: brd = cols[cols.index('brd') + 1] elif type_ == 'inet6': mask = cidr if 'scope' in cols: scope = cols[cols.index('scope') + 1] return (ip, mask, brd, scope) groups = re.compile('\r?\n\\d').split(out) for group in groups: iface = None data = dict() for line in group.splitlines(): if ' ' not in line: continue match = re.match(r'^\d*:\s+([\w.\-]+)(?:@)?([\w.\-]+)?:\s+<(.+)>', line) if match: iface, parent, attrs = match.groups() if 'UP' in attrs.split(','): data['up'] = True else: data['up'] = False if parent: data['parent'] = parent continue cols = line.split() if len(cols) >= 2: type_, value = tuple(cols[0:2]) iflabel = cols[-1:][0] if type_ in ('inet', 'inet6'): if 'secondary' not in cols: ipaddr, netmask, broadcast, scope = parse_network(value, cols) if type_ == 'inet': if 'inet' not in data: data['inet'] = list() addr_obj = dict() addr_obj['address'] = ipaddr addr_obj['netmask'] = netmask addr_obj['broadcast'] = broadcast addr_obj['label'] = iflabel data['inet'].append(addr_obj) elif type_ == 'inet6': if 'inet6' not in data: data['inet6'] = list() addr_obj = dict() addr_obj['address'] = ipaddr addr_obj['prefixlen'] = netmask addr_obj['scope'] = scope data['inet6'].append(addr_obj) else: if 'secondary' not in data: data['secondary'] = list() ip_, mask, brd, scp = parse_network(value, cols) data['secondary'].append({ 'type': type_, 'address': ip_, 'netmask': mask, 'broadcast': brd, 'label': iflabel, }) del ip_, mask, brd, scp elif type_.startswith('link'): data['hwaddr'] = value if iface: ret[iface] = data del iface, data return ret def _interfaces_ifconfig(out): ''' Uses ifconfig to return a dictionary of interfaces with various information about each (up/down state, ip address, netmask, and hwaddr) ''' ret = dict() piface = re.compile(r'^([^\s:]+)') pmac = re.compile('.*?(?:HWaddr|ether|address:|lladdr) ([0-9a-fA-F:]+)') if salt.utils.platform.is_sunos(): pip = re.compile(r'.*?(?:inet\s+)([0-9]+\.[0-9]+\.[0-9]+\.[0-9]+)(.*)') pip6 = re.compile('.*?(?:inet6 )([0-9a-fA-F:]+)') pmask6 = re.compile(r'.*?(?:inet6 [0-9a-fA-F:]+/(\d+)).*') else: pip = re.compile(r'.*?(?:inet addr:|inet [^\d]*)(.*?)\s') pip6 = re.compile('.*?(?:inet6 addr: (.*?)/|inet6 )([0-9a-fA-F:]+)') pmask6 = re.compile(r'.*?(?:inet6 addr: [0-9a-fA-F:]+/(\d+)|prefixlen (\d+))(?: Scope:([a-zA-Z]+)| scopeid (0x[0-9a-fA-F]))?') pmask = re.compile(r'.*?(?:Mask:|netmask )(?:((?:0x)?[0-9a-fA-F]{8})|([\d\.]+))') pupdown = re.compile('UP') pbcast = re.compile(r'.*?(?:Bcast:|broadcast )([\d\.]+)') groups = re.compile('\r?\n(?=\\S)').split(out) for group in groups: data = dict() iface = '' updown = False for line in group.splitlines(): miface = piface.match(line) mmac = pmac.match(line) mip = pip.match(line) mip6 = pip6.match(line) mupdown = pupdown.search(line) if miface: iface = miface.group(1) if mmac: data['hwaddr'] = mmac.group(1) if salt.utils.platform.is_sunos(): expand_mac = [] for chunk in data['hwaddr'].split(':'): expand_mac.append('0{0}'.format(chunk) if len(chunk) < 2 else '{0}'.format(chunk)) data['hwaddr'] = ':'.join(expand_mac) if mip: if 'inet' not in data: data['inet'] = list() addr_obj = dict() addr_obj['address'] = mip.group(1) mmask = pmask.match(line) if mmask: if mmask.group(1): mmask = _number_of_set_bits_to_ipv4_netmask( int(mmask.group(1), 16)) else: mmask = mmask.group(2) addr_obj['netmask'] = mmask mbcast = pbcast.match(line) if mbcast: addr_obj['broadcast'] = mbcast.group(1) data['inet'].append(addr_obj) if mupdown: updown = True if mip6: if 'inet6' not in data: data['inet6'] = list() addr_obj = dict() addr_obj['address'] = mip6.group(1) or mip6.group(2) mmask6 = pmask6.match(line) if mmask6: addr_obj['prefixlen'] = mmask6.group(1) or mmask6.group(2) if not salt.utils.platform.is_sunos(): ipv6scope = mmask6.group(3) or mmask6.group(4) addr_obj['scope'] = ipv6scope.lower() if ipv6scope is not None else ipv6scope # SunOS sometimes has ::/0 as inet6 addr when using addrconf if not salt.utils.platform.is_sunos() \ or addr_obj['address'] != '::' \ and addr_obj['prefixlen'] != 0: data['inet6'].append(addr_obj) data['up'] = updown if iface in ret: # SunOS optimization, where interfaces occur twice in 'ifconfig -a' # output with the same name: for ipv4 and then for ipv6 addr family. # Every instance has it's own 'UP' status and we assume that ipv4 # status determines global interface status. # # merge items with higher priority for older values # after that merge the inet and inet6 sub items for both ret[iface] = dict(list(data.items()) + list(ret[iface].items())) if 'inet' in data: ret[iface]['inet'].extend(x for x in data['inet'] if x not in ret[iface]['inet']) if 'inet6' in data: ret[iface]['inet6'].extend(x for x in data['inet6'] if x not in ret[iface]['inet6']) else: ret[iface] = data del data return ret def linux_interfaces(): ''' Obtain interface information for *NIX/BSD variants ''' ifaces = dict() ip_path = salt.utils.path.which('ip') ifconfig_path = None if ip_path else salt.utils.path.which('ifconfig') if ip_path: cmd1 = subprocess.Popen( '{0} link show'.format(ip_path), shell=True, close_fds=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT).communicate()[0] cmd2 = subprocess.Popen( '{0} addr show'.format(ip_path), shell=True, close_fds=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT).communicate()[0] ifaces = _interfaces_ip("{0}\n{1}".format( salt.utils.stringutils.to_str(cmd1), salt.utils.stringutils.to_str(cmd2))) elif ifconfig_path: cmd = subprocess.Popen( '{0} -a'.format(ifconfig_path), shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT).communicate()[0] ifaces = _interfaces_ifconfig(salt.utils.stringutils.to_str(cmd)) return ifaces def _netbsd_interfaces_ifconfig(out): ''' Uses ifconfig to return a dictionary of interfaces with various information about each (up/down state, ip address, netmask, and hwaddr) ''' ret = dict() piface = re.compile(r'^([^\s:]+)') pmac = re.compile('.*?address: ([0-9a-f:]+)') pip = re.compile(r'.*?inet [^\d]*(.*?)/([\d]*)\s') pip6 = re.compile(r'.*?inet6 ([0-9a-f:]+)%([a-zA-Z0-9]*)/([\d]*)\s') pupdown = re.compile('UP') pbcast = re.compile(r'.*?broadcast ([\d\.]+)') groups = re.compile('\r?\n(?=\\S)').split(out) for group in groups: data = dict() iface = '' updown = False for line in group.splitlines(): miface = piface.match(line) mmac = pmac.match(line) mip = pip.match(line) mip6 = pip6.match(line) mupdown = pupdown.search(line) if miface: iface = miface.group(1) if mmac: data['hwaddr'] = mmac.group(1) if mip: if 'inet' not in data: data['inet'] = list() addr_obj = dict() addr_obj['address'] = mip.group(1) mmask = mip.group(2) if mip.group(2): addr_obj['netmask'] = cidr_to_ipv4_netmask(mip.group(2)) mbcast = pbcast.match(line) if mbcast: addr_obj['broadcast'] = mbcast.group(1) data['inet'].append(addr_obj) if mupdown: updown = True if mip6: if 'inet6' not in data: data['inet6'] = list() addr_obj = dict() addr_obj['address'] = mip6.group(1) mmask6 = mip6.group(3) addr_obj['scope'] = mip6.group(2) addr_obj['prefixlen'] = mip6.group(3) data['inet6'].append(addr_obj) data['up'] = updown ret[iface] = data del data return ret def netbsd_interfaces(): ''' Obtain interface information for NetBSD >= 8 where the ifconfig output diverged from other BSD variants (Netmask is now part of the address) ''' # NetBSD versions prior to 8.0 can still use linux_interfaces() if LooseVersion(os.uname()[2]) < LooseVersion('8.0'): return linux_interfaces() ifconfig_path = salt.utils.path.which('ifconfig') cmd = subprocess.Popen( '{0} -a'.format(ifconfig_path), shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT).communicate()[0] return _netbsd_interfaces_ifconfig(salt.utils.stringutils.to_str(cmd)) def _interfaces_ipconfig(out): ''' Returns a dictionary of interfaces with various information about each (up/down state, ip address, netmask, and hwaddr) NOTE: This is not used by any function and may be able to be removed in the future. ''' ifaces = dict() iface = None adapter_iface_regex = re.compile(r'adapter (\S.+):$') for line in out.splitlines(): if not line: continue # TODO what does Windows call Infiniband and 10/40gige adapters if line.startswith('Ethernet'): iface = ifaces[adapter_iface_regex.search(line).group(1)] iface['up'] = True addr = None continue if iface: key, val = line.split(',', 1) key = key.strip(' .') val = val.strip() if addr and key == 'Subnet Mask': addr['netmask'] = val elif key in ('IP Address', 'IPv4 Address'): if 'inet' not in iface: iface['inet'] = list() addr = {'address': val.rstrip('(Preferred)'), 'netmask': None, 'broadcast': None} # TODO find the broadcast iface['inet'].append(addr) elif 'IPv6 Address' in key: if 'inet6' not in iface: iface['inet'] = list() # XXX What is the prefixlen!? addr = {'address': val.rstrip('(Preferred)'), 'prefixlen': None} iface['inet6'].append(addr) elif key == 'Physical Address': iface['hwaddr'] = val elif key == 'Media State': # XXX seen used for tunnel adaptors # might be useful iface['up'] = (val != 'Media disconnected') def win_interfaces(): ''' Obtain interface information for Windows systems ''' with salt.utils.winapi.Com(): c = wmi.WMI() ifaces = {} for iface in c.Win32_NetworkAdapterConfiguration(IPEnabled=1): ifaces[iface.Description] = dict() if iface.MACAddress: ifaces[iface.Description]['hwaddr'] = iface.MACAddress if iface.IPEnabled: ifaces[iface.Description]['up'] = True for ip in iface.IPAddress: if '.' in ip: if 'inet' not in ifaces[iface.Description]: ifaces[iface.Description]['inet'] = [] item = {'address': ip, 'label': iface.Description} if iface.DefaultIPGateway: broadcast = next((i for i in iface.DefaultIPGateway if '.' in i), '') if broadcast: item['broadcast'] = broadcast if iface.IPSubnet: netmask = next((i for i in iface.IPSubnet if '.' in i), '') if netmask: item['netmask'] = netmask ifaces[iface.Description]['inet'].append(item) if ':' in ip: if 'inet6' not in ifaces[iface.Description]: ifaces[iface.Description]['inet6'] = [] item = {'address': ip} if iface.DefaultIPGateway: broadcast = next((i for i in iface.DefaultIPGateway if ':' in i), '') if broadcast: item['broadcast'] = broadcast if iface.IPSubnet: netmask = next((i for i in iface.IPSubnet if ':' in i), '') if netmask: item['netmask'] = netmask ifaces[iface.Description]['inet6'].append(item) else: ifaces[iface.Description]['up'] = False return ifaces def get_net_start(ipaddr, netmask): ''' Return the address of the network ''' net = ipaddress.ip_network('{0}/{1}'.format(ipaddr, netmask), strict=False) return six.text_type(net.network_address) def get_net_size(mask): ''' Turns an IPv4 netmask into it's corresponding prefix length (255.255.255.0 -> 24 as in 192.168.1.10/24). ''' binary_str = '' for octet in mask.split('.'): binary_str += bin(int(octet))[2:].zfill(8) return len(binary_str.rstrip('0')) def calc_net(ipaddr, netmask=None): ''' Takes IP (CIDR notation supported) and optionally netmask and returns the network in CIDR-notation. (The IP can be any IP inside the subnet) ''' if netmask is not None: ipaddr = '{0}/{1}'.format(ipaddr, netmask) return six.text_type(ipaddress.ip_network(ipaddr, strict=False)) def _ipv4_to_bits(ipaddr): ''' Accepts an IPv4 dotted quad and returns a string representing its binary counterpart ''' return ''.join([bin(int(x))[2:].rjust(8, '0') for x in ipaddr.split('.')]) def _get_iface_info(iface): ''' If `iface` is available, return interface info and no error, otherwise return no info and log and return an error ''' iface_info = interfaces() if iface in iface_info.keys(): return iface_info, False else: error_msg = ('Interface "{0}" not in available interfaces: "{1}"' ''.format(iface, '", "'.join(iface_info.keys()))) log.error(error_msg) return None, error_msg def _hw_addr_aix(iface): ''' Return the hardware address (a.k.a. MAC address) for a given interface on AIX MAC address not available in through interfaces ''' cmd = subprocess.Popen( 'entstat -d {0} | grep \'Hardware Address\''.format(iface), shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT).communicate()[0] if cmd: comps = cmd.split(' ') if len(comps) == 3: mac_addr = comps[2].strip('\'').strip() return mac_addr error_msg = ('Interface "{0}" either not available or does not contain a hardware address'.format(iface)) log.error(error_msg) return error_msg def hw_addr(iface): ''' Return the hardware address (a.k.a. MAC address) for a given interface .. versionchanged:: 2016.11.4 Added support for AIX ''' if salt.utils.platform.is_aix(): return _hw_addr_aix iface_info, error = _get_iface_info(iface) if error is False: return iface_info.get(iface, {}).get('hwaddr', '') else: return error def interface(iface): ''' Return the details of `iface` or an error if it does not exist ''' iface_info, error = _get_iface_info(iface) if error is False: return iface_info.get(iface, {}).get('inet', '') else: return error def interface_ip(iface): ''' Return `iface` IPv4 addr or an error if `iface` does not exist ''' iface_info, error = _get_iface_info(iface) if error is False: inet = iface_info.get(iface, {}).get('inet', None) return inet[0].get('address', '') if inet else '' else: return error def _subnets(proto='inet', interfaces_=None): ''' Returns a list of subnets to which the host belongs ''' if interfaces_ is None: ifaces = interfaces() elif isinstance(interfaces_, list): ifaces = {} for key, value in six.iteritems(interfaces()): if key in interfaces_: ifaces[key] = value else: ifaces = {interfaces_: interfaces().get(interfaces_, {})} ret = set() if proto == 'inet': subnet = 'netmask' dflt_cidr = 32 elif proto == 'inet6': subnet = 'prefixlen' dflt_cidr = 128 else: log.error('Invalid proto %s calling subnets()', proto) return for ip_info in six.itervalues(ifaces): addrs = ip_info.get(proto, []) addrs.extend([addr for addr in ip_info.get('secondary', []) if addr.get('type') == proto]) for intf in addrs: if subnet in intf: intf = ipaddress.ip_interface('{0}/{1}'.format(intf['address'], intf[subnet])) else: intf = ipaddress.ip_interface('{0}/{1}'.format(intf['address'], dflt_cidr)) if not intf.is_loopback: ret.add(intf.network) return [six.text_type(net) for net in sorted(ret)] def subnets(interfaces=None): ''' Returns a list of IPv4 subnets to which the host belongs ''' return _subnets('inet', interfaces_=interfaces) def subnets6(): ''' Returns a list of IPv6 subnets to which the host belongs ''' return _subnets('inet6') def in_subnet(cidr, addr=None): ''' Returns True if host or (any of) addrs is within specified subnet, otherwise False ''' try: cidr = ipaddress.ip_network(cidr) except ValueError: log.error('Invalid CIDR \'%s\'', cidr) return False if addr is None: addr = ip_addrs() addr.extend(ip_addrs6()) elif not isinstance(addr, (list, tuple)): addr = (addr,) return any(ipaddress.ip_address(item) in cidr for item in addr) def _ip_addrs(interface=None, include_loopback=False, interface_data=None, proto='inet'): ''' Return the full list of IP adresses matching the criteria proto = inet|inet6 ''' ret = set() ifaces = interface_data \ if isinstance(interface_data, dict) \ else interfaces() if interface is None: target_ifaces = ifaces else: target_ifaces = dict([(k, v) for k, v in six.iteritems(ifaces) if k == interface]) if not target_ifaces: log.error('Interface %s not found.', interface) for ip_info in six.itervalues(target_ifaces): addrs = ip_info.get(proto, []) addrs.extend([addr for addr in ip_info.get('secondary', []) if addr.get('type') == proto]) for addr in addrs: addr = ipaddress.ip_address(addr.get('address')) if not addr.is_loopback or include_loopback: ret.add(addr) return [six.text_type(addr) for addr in sorted(ret)] def ip_addrs(interface=None, include_loopback=False, interface_data=None): ''' Returns a list of IPv4 addresses assigned to the host. 127.0.0.1 is ignored, unless 'include_loopback=True' is indicated. If 'interface' is provided, then only IP addresses from that interface will be returned. ''' return _ip_addrs(interface, include_loopback, interface_data, 'inet') def ip_addrs6(interface=None, include_loopback=False, interface_data=None): ''' Returns a list of IPv6 addresses assigned to the host. ::1 is ignored, unless 'include_loopback=True' is indicated. If 'interface' is provided, then only IP addresses from that interface will be returned. ''' return _ip_addrs(interface, include_loopback, interface_data, 'inet6') def hex2ip(hex_ip, invert=False): ''' Convert a hex string to an ip, if a failure occurs the original hex is returned. If 'invert=True' assume that ip from /proc/net/<proto> ''' if len(hex_ip) == 32: # ipv6 ip = [] for i in range(0, 32, 8): ip_part = hex_ip[i:i + 8] ip_part = [ip_part[x:x + 2] for x in range(0, 8, 2)] if invert: ip.append("{0[3]}{0[2]}:{0[1]}{0[0]}".format(ip_part)) else: ip.append("{0[0]}{0[1]}:{0[2]}{0[3]}".format(ip_part)) try: address = ipaddress.IPv6Address(":".join(ip)) if address.ipv4_mapped: return str(address.ipv4_mapped) else: return address.compressed except ipaddress.AddressValueError as ex: log.error('hex2ip - ipv6 address error: %s', ex) return hex_ip try: hip = int(hex_ip, 16) except ValueError: return hex_ip if invert: return '{3}.{2}.{1}.{0}'.format(hip >> 24 & 255, hip >> 16 & 255, hip >> 8 & 255, hip & 255) return '{0}.{1}.{2}.{3}'.format(hip >> 24 & 255, hip >> 16 & 255, hip >> 8 & 255, hip & 255) def mac2eui64(mac, prefix=None): ''' Convert a MAC address to a EUI64 identifier or, with prefix provided, a full IPv6 address ''' # http://tools.ietf.org/html/rfc4291#section-2.5.1 eui64 = re.sub(r'[.:-]', '', mac).lower() eui64 = eui64[0:6] + 'fffe' + eui64[6:] eui64 = hex(int(eui64[0:2], 16) | 2)[2:].zfill(2) + eui64[2:] if prefix is None: return ':'.join(re.findall(r'.{4}', eui64)) else: try: net = ipaddress.ip_network(prefix, strict=False) euil = int('0x{0}'.format(eui64), 16) return '{0}/{1}'.format(net[euil], net.prefixlen) except Exception: return def active_tcp(): ''' Return a dict describing all active tcp connections as quickly as possible ''' ret = {} for statf in ['/proc/net/tcp', '/proc/net/tcp6']: if os.path.isfile(statf): with salt.utils.files.fopen(statf, 'rb') as fp_: for line in fp_: line = salt.utils.stringutils.to_unicode(line) if line.strip().startswith('sl'): continue iret = _parse_tcp_line(line) sl = next(iter(iret)) if iret[sl]['state'] == 1: # 1 is ESTABLISHED del iret[sl]['state'] ret[len(ret)] = iret[sl] return ret def local_port_tcp(port): ''' Return a set of remote ip addrs attached to the specified local port ''' ret = _remotes_on(port, 'local_port') return ret def remote_port_tcp(port): ''' Return a set of ip addrs the current host is connected to on given port ''' ret = _remotes_on(port, 'remote_port') return ret def _remotes_on(port, which_end): ''' Return a set of ip addrs active tcp connections ''' port = int(port) ret = _netlink_tool_remote_on(port, which_end) if ret is not None: return ret ret = set() proc_available = False for statf in ['/proc/net/tcp', '/proc/net/tcp6']: if os.path.isfile(statf): proc_available = True with salt.utils.files.fopen(statf, 'r') as fp_: for line in fp_: line = salt.utils.stringutils.to_unicode(line) if line.strip().startswith('sl'): continue iret = _parse_tcp_line(line) sl = next(iter(iret)) if iret[sl][which_end] == port and iret[sl]['state'] == 1: # 1 is ESTABLISHED ret.add(iret[sl]['remote_addr']) if not proc_available: # Fallback to use OS specific tools if salt.utils.platform.is_sunos(): return _sunos_remotes_on(port, which_end) if salt.utils.platform.is_freebsd(): return _freebsd_remotes_on(port, which_end) if salt.utils.platform.is_netbsd(): return _netbsd_remotes_on(port, which_end) if salt.utils.platform.is_openbsd(): return _openbsd_remotes_on(port, which_end) if salt.utils.platform.is_windows(): return _windows_remotes_on(port, which_end) if salt.utils.platform.is_aix(): return _aix_remotes_on(port, which_end) return _linux_remotes_on(port, which_end) return ret def _parse_tcp_line(line): ''' Parse a single line from the contents of /proc/net/tcp or /proc/net/tcp6 ''' ret = {} comps = line.strip().split() sl = comps[0].rstrip(':') ret[sl] = {} l_addr, l_port = comps[1].split(':') r_addr, r_port = comps[2].split(':') ret[sl]['local_addr'] = hex2ip(l_addr, True) ret[sl]['local_port'] = int(l_port, 16) ret[sl]['remote_addr'] = hex2ip(r_addr, True) ret[sl]['remote_port'] = int(r_port, 16) ret[sl]['state'] = int(comps[3], 16) return ret def _netlink_tool_remote_on(port, which_end): ''' Returns set of ipv4 host addresses of remote established connections on local or remote tcp port. Parses output of shell 'ss' to get connections [root@salt-master ~]# ss -ant State Recv-Q Send-Q Local Address:Port Peer Address:Port LISTEN 0 511 *:80 *:* LISTEN 0 128 *:22 *:* ESTAB 0 0 127.0.0.1:56726 127.0.0.1:4505 ''' remotes = set() valid = False try: data = subprocess.check_output(['ss', '-ant']) # pylint: disable=minimum-python-version except subprocess.CalledProcessError: log.error('Failed ss') raise except OSError: # not command "No such file or directory" return None lines = salt.utils.stringutils.to_str(data).split('\n') for line in lines: if 'Address:Port' in line: # ss tools may not be valid valid = True continue elif 'ESTAB' not in line: continue chunks = line.split() local_host, local_port = chunks[3].split(':', 1) remote_host, remote_port = chunks[4].split(':', 1) if which_end == 'remote_port' and int(remote_port) != port: continue if which_end == 'local_port' and int(local_port) != port: continue remotes.add(remote_host) if valid is False: remotes = None return remotes def _sunos_remotes_on(port, which_end): ''' SunOS specific helper function. Returns set of ipv4 host addresses of remote established connections on local or remote tcp port. Parses output of shell 'netstat' to get connections [root@salt-master ~]# netstat -f inet -n TCP: IPv4 Local Address Remote Address Swind Send-Q Rwind Recv-Q State -------------------- -------------------- ----- ------ ----- ------ ----------- 10.0.0.101.4505 10.0.0.1.45329 1064800 0 1055864 0 ESTABLISHED 10.0.0.101.4505 10.0.0.100.50798 1064800 0 1055864 0 ESTABLISHED ''' remotes = set() try: data = subprocess.check_output(['netstat', '-f', 'inet', '-n']) # pylint: disable=minimum-python-version except subprocess.CalledProcessError: log.error('Failed netstat') raise lines = salt.utils.stringutils.to_str(data).split('\n') for line in lines: if 'ESTABLISHED' not in line: continue chunks = line.split() local_host, local_port = chunks[0].rsplit('.', 1) remote_host, remote_port = chunks[1].rsplit('.', 1) if which_end == 'remote_port' and int(remote_port) != port: continue if which_end == 'local_port' and int(local_port) != port: continue remotes.add(remote_host) return remotes def _freebsd_remotes_on(port, which_end): ''' Returns set of ipv4 host addresses of remote established connections on local tcp port port. Parses output of shell 'sockstat' (FreeBSD) to get connections $ sudo sockstat -4 USER COMMAND PID FD PROTO LOCAL ADDRESS FOREIGN ADDRESS root python2.7 1456 29 tcp4 *:4505 *:* root python2.7 1445 17 tcp4 *:4506 *:* root python2.7 1294 14 tcp4 127.0.0.1:11813 127.0.0.1:4505 root python2.7 1294 41 tcp4 127.0.0.1:61115 127.0.0.1:4506 $ sudo sockstat -4 -c -p 4506 USER COMMAND PID FD PROTO LOCAL ADDRESS FOREIGN ADDRESS root python2.7 1294 41 tcp4 127.0.0.1:61115 127.0.0.1:4506 ''' port = int(port) remotes = set() try: cmd = salt.utils.args.shlex_split('sockstat -4 -c -p {0}'.format(port)) data = subprocess.check_output(cmd) # pylint: disable=minimum-python-version except subprocess.CalledProcessError as ex: log.error('Failed "sockstat" with returncode = %s', ex.returncode) raise lines = salt.utils.stringutils.to_str(data).split('\n') for line in lines: chunks = line.split() if not chunks: continue # ['root', 'python2.7', '1456', '37', 'tcp4', # '127.0.0.1:4505-', '127.0.0.1:55703'] # print chunks if 'COMMAND' in chunks[1]: continue # ignore header if len(chunks) < 2: continue # sockstat -4 -c -p 4506 does this with high PIDs: # USER COMMAND PID FD PROTO LOCAL ADDRESS FOREIGN ADDRESS # salt-master python2.781106 35 tcp4 192.168.12.34:4506 192.168.12.45:60143 local = chunks[-2] remote = chunks[-1] lhost, lport = local.split(':') rhost, rport = remote.split(':') if which_end == 'local' and int(lport) != port: # ignore if local port not port continue if which_end == 'remote' and int(rport) != port: # ignore if remote port not port continue remotes.add(rhost) return remotes def _netbsd_remotes_on(port, which_end): ''' Returns set of ipv4 host addresses of remote established connections on local tcp port port. Parses output of shell 'sockstat' (NetBSD) to get connections $ sudo sockstat -4 -n USER COMMAND PID FD PROTO LOCAL ADDRESS FOREIGN ADDRESS root python2.7 1456 29 tcp *.4505 *.* root python2.7 1445 17 tcp *.4506 *.* root python2.7 1294 14 tcp 127.0.0.1.11813 127.0.0.1.4505 root python2.7 1294 41 tcp 127.0.0.1.61115 127.0.0.1.4506 $ sudo sockstat -4 -c -n -p 4506 USER COMMAND PID FD PROTO LOCAL ADDRESS FOREIGN ADDRESS root python2.7 1294 41 tcp 127.0.0.1.61115 127.0.0.1.4506 ''' port = int(port) remotes = set() try: cmd = salt.utils.args.shlex_split('sockstat -4 -c -n -p {0}'.format(port)) data = subprocess.check_output(cmd) # pylint: disable=minimum-python-version except subprocess.CalledProcessError as ex: log.error('Failed "sockstat" with returncode = %s', ex.returncode) raise lines = salt.utils.stringutils.to_str(data).split('\n') for line in lines: chunks = line.split() if not chunks: continue # ['root', 'python2.7', '1456', '37', 'tcp', # '127.0.0.1.4505-', '127.0.0.1.55703'] # print chunks if 'COMMAND' in chunks[1]: continue # ignore header if len(chunks) < 2: continue local = chunks[5].split('.') lport = local.pop() lhost = '.'.join(local) remote = chunks[6].split('.') rport = remote.pop() rhost = '.'.join(remote) if which_end == 'local' and int(lport) != port: # ignore if local port not port continue if which_end == 'remote' and int(rport) != port: # ignore if remote port not port continue remotes.add(rhost) return remotes def _openbsd_remotes_on(port, which_end): ''' OpenBSD specific helper function. Returns set of ipv4 host addresses of remote established connections on local or remote tcp port. Parses output of shell 'netstat' to get connections $ netstat -nf inet Active Internet connections Proto Recv-Q Send-Q Local Address Foreign Address (state) tcp 0 0 10.0.0.101.4505 10.0.0.1.45329 ESTABLISHED tcp 0 0 10.0.0.101.4505 10.0.0.100.50798 ESTABLISHED ''' remotes = set() try: data = subprocess.check_output(['netstat', '-nf', 'inet']) # pylint: disable=minimum-python-version except subprocess.CalledProcessError: log.error('Failed netstat') raise lines = data.split('\n') for line in lines: if 'ESTABLISHED' not in line: continue chunks = line.split() local_host, local_port = chunks[3].rsplit('.', 1) remote_host, remote_port = chunks[4].rsplit('.', 1) if which_end == 'remote_port' and int(remote_port) != port: continue if which_end == 'local_port' and int(local_port) != port: continue remotes.add(remote_host) return remotes def _windows_remotes_on(port, which_end): r''' Windows specific helper function. Returns set of ipv4 host addresses of remote established connections on local or remote tcp port. Parses output of shell 'netstat' to get connections C:\>netstat -n Active Connections Proto Local Address Foreign Address State TCP 10.2.33.17:3007 130.164.12.233:10123 ESTABLISHED TCP 10.2.33.17:3389 130.164.30.5:10378 ESTABLISHED ''' remotes = set() try: data = subprocess.check_output(['netstat', '-n']) # pylint: disable=minimum-python-version except subprocess.CalledProcessError: log.error('Failed netstat') raise lines = salt.utils.stringutils.to_str(data).split('\n') for line in lines: if 'ESTABLISHED' not in line: continue chunks = line.split() local_host, local_port = chunks[1].rsplit(':', 1) remote_host, remote_port = chunks[2].rsplit(':', 1) if which_end == 'remote_port' and int(remote_port) != port: continue if which_end == 'local_port' and int(local_port) != port: continue remotes.add(remote_host) return remotes def _linux_remotes_on(port, which_end): ''' Linux specific helper function. Returns set of ip host addresses of remote established connections on local tcp port port. Parses output of shell 'lsof' to get connections $ sudo lsof -iTCP:4505 -n COMMAND PID USER FD TYPE DEVICE SIZE/OFF NODE NAME Python 9971 root 35u IPv4 0x18a8464a29ca329d 0t0 TCP *:4505 (LISTEN) Python 9971 root 37u IPv4 0x18a8464a29b2b29d 0t0 TCP 127.0.0.1:4505->127.0.0.1:55703 (ESTABLISHED) Python 10152 root 22u IPv4 0x18a8464a29c8cab5 0t0 TCP 127.0.0.1:55703->127.0.0.1:4505 (ESTABLISHED) Python 10153 root 22u IPv4 0x18a8464a29c8cab5 0t0 TCP [fe80::249a]:4505->[fe80::150]:59367 (ESTABLISHED) ''' remotes = set() try: data = subprocess.check_output( ['lsof', '-iTCP:{0:d}'.format(port), '-n', '-P'] # pylint: disable=minimum-python-version ) except subprocess.CalledProcessError as ex: if ex.returncode == 1: # Lsof return 1 if any error was detected, including the failure # to locate Internet addresses, and it is not an error in this case. log.warning('"lsof" returncode = 1, likely no active TCP sessions.') return remotes log.error('Failed "lsof" with returncode = %s', ex.returncode) raise lines = salt.utils.stringutils.to_str(data).split('\n') for line in lines: chunks = line.split() if not chunks: continue # ['Python', '9971', 'root', '37u', 'IPv4', '0x18a8464a29b2b29d', '0t0', # 'TCP', '127.0.0.1:4505->127.0.0.1:55703', '(ESTABLISHED)'] # print chunks if 'COMMAND' in chunks[0]: continue # ignore header if 'ESTABLISHED' not in chunks[-1]: continue # ignore if not ESTABLISHED # '127.0.0.1:4505->127.0.0.1:55703' local, remote = chunks[8].split('->') _, lport = local.rsplit(':', 1) rhost, rport = remote.rsplit(':', 1) if which_end == 'remote_port' and int(rport) != port: continue if which_end == 'local_port' and int(lport) != port: continue remotes.add(rhost.strip("[]")) return remotes def _aix_remotes_on(port, which_end): ''' AIX specific helper function. Returns set of ipv4 host addresses of remote established connections on local or remote tcp port. Parses output of shell 'netstat' to get connections root@la68pp002_pub:/opt/salt/lib/python2.7/site-packages/salt/modules# netstat -f inet -n Active Internet connections Proto Recv-Q Send-Q Local Address Foreign Address (state) tcp4 0 0 172.29.149.95.50093 209.41.78.13.4505 ESTABLISHED tcp4 0 0 127.0.0.1.9514 *.* LISTEN tcp4 0 0 127.0.0.1.9515 *.* LISTEN tcp4 0 0 127.0.0.1.199 127.0.0.1.32779 ESTABLISHED tcp4 0 0 127.0.0.1.32779 127.0.0.1.199 ESTABLISHED tcp4 0 40 172.29.149.95.22 172.29.96.83.41022 ESTABLISHED tcp4 0 0 172.29.149.95.22 172.29.96.83.41032 ESTABLISHED tcp4 0 0 127.0.0.1.32771 127.0.0.1.32775 ESTABLISHED tcp 0 0 127.0.0.1.32775 127.0.0.1.32771 ESTABLISHED tcp4 0 0 127.0.0.1.32771 127.0.0.1.32776 ESTABLISHED tcp 0 0 127.0.0.1.32776 127.0.0.1.32771 ESTABLISHED tcp4 0 0 127.0.0.1.32771 127.0.0.1.32777 ESTABLISHED tcp 0 0 127.0.0.1.32777 127.0.0.1.32771 ESTABLISHED tcp4 0 0 127.0.0.1.32771 127.0.0.1.32778 ESTABLISHED tcp 0 0 127.0.0.1.32778 127.0.0.1.32771 ESTABLISHED ''' remotes = set() try: data = subprocess.check_output(['netstat', '-f', 'inet', '-n']) # pylint: disable=minimum-python-version except subprocess.CalledProcessError: log.error('Failed netstat') raise lines = salt.utils.stringutils.to_str(data).split('\n') for line in lines: if 'ESTABLISHED' not in line: continue chunks = line.split() local_host, local_port = chunks[3].rsplit('.', 1) remote_host, remote_port = chunks[4].rsplit('.', 1) if which_end == 'remote_port' and int(remote_port) != port: continue if which_end == 'local_port' and int(local_port) != port: continue remotes.add(remote_host) return remotes @jinja_filter('gen_mac') def gen_mac(prefix='AC:DE:48'): ''' Generates a MAC address with the defined OUI prefix. Common prefixes: - ``00:16:3E`` -- Xen - ``00:18:51`` -- OpenVZ - ``00:50:56`` -- VMware (manually generated) - ``52:54:00`` -- QEMU/KVM - ``AC:DE:48`` -- PRIVATE References: - http://standards.ieee.org/develop/regauth/oui/oui.txt - https://www.wireshark.org/tools/oui-lookup.html - https://en.wikipedia.org/wiki/MAC_address ''' return '{0}:{1:02X}:{2:02X}:{3:02X}'.format(prefix, random.randint(0, 0xff), random.randint(0, 0xff), random.randint(0, 0xff)) @jinja_filter('mac_str_to_bytes') def mac_str_to_bytes(mac_str): ''' Convert a MAC address string into bytes. Works with or without separators: b1 = mac_str_to_bytes('08:00:27:13:69:77') b2 = mac_str_to_bytes('080027136977') assert b1 == b2 assert isinstance(b1, bytes) ''' if len(mac_str) == 12: pass elif len(mac_str) == 17: sep = mac_str[2] mac_str = mac_str.replace(sep, '') else: raise ValueError('Invalid MAC address') chars = (int(mac_str[s:s+2], 16) for s in range(0, 12, 2)) return bytes(chars) if six.PY3 else b''.join(chr(x) for x in chars) def refresh_dns(): ''' issue #21397: force glibc to re-read resolv.conf ''' try: res_init() except NameError: # Exception raised loading the library, thus res_init is not defined pass @jinja_filter('connection_check') def connection_check(addr, port=80, safe=False, ipv6=None): ''' Provides a convenient alias for the dns_check filter. ''' return dns_check(addr, port, safe, ipv6) @jinja_filter('dns_check') def dns_check(addr, port=80, safe=False, ipv6=None, attempt_connect=True): ''' Return the ip resolved by dns, but do not exit on failure, only raise an exception. Obeys system preference for IPv4/6 address resolution - this can be overridden by the ipv6 flag. Tries to connect to the address before considering it useful. If no address can be reached, the first one resolved is used as a fallback. ''' error = False lookup = addr seen_ipv6 = False family = socket.AF_INET6 if ipv6 else socket.AF_INET if ipv6 is False else socket.AF_UNSPEC hostnames = [] try: refresh_dns() hostnames = socket.getaddrinfo(addr, port, family, socket.SOCK_STREAM) except TypeError: err = ('Attempt to resolve address \'{0}\' failed. Invalid or unresolveable address').format(lookup) raise SaltSystemExit(code=42, msg=err) except socket.error: error = True # If ipv6 is set to True, attempt another lookup using the IPv4 family, # just in case we're attempting to lookup an IPv4 IP # as an IPv6 hostname. if error and ipv6: try: refresh_dns() hostnames = socket.getaddrinfo(addr, port, socket.AF_INET, socket.SOCK_STREAM) except TypeError: err = ('Attempt to resolve address \'{0}\' failed. Invalid or unresolveable address').format(lookup) raise SaltSystemExit(code=42, msg=err) except socket.error: error = True try: if not hostnames: error = True else: resolved = False candidates = [] for h in hostnames: # Input is IP address, passed through unchanged, just return it if h[4][0] == addr: resolved = salt.utils.zeromq.ip_bracket(addr) break candidate_addr = salt.utils.zeromq.ip_bracket(h[4][0]) # sometimes /etc/hosts contains ::1 localhost if not ipv6 and candidate_addr == '[::1]': continue candidates.append(candidate_addr) if attempt_connect: try: s = socket.socket(h[0], socket.SOCK_STREAM) s.settimeout(2) s.connect((candidate_addr.strip('[]'), h[4][1])) s.close() resolved = candidate_addr break except socket.error: pass if not resolved: if candidates: resolved = candidates[0] else: error = True except TypeError: err = ('Attempt to resolve address \'{0}\' failed. Invalid or unresolveable address').format(lookup) raise SaltSystemExit(code=42, msg=err) except socket.error: error = True if error: err = ('DNS lookup or connection check of \'{0}\' failed.').format(addr) if safe: if salt.log.is_console_configured(): # If logging is not configured it also means that either # the master or minion instance calling this hasn't even # started running log.error(err) raise SaltClientError() raise SaltSystemExit(code=42, msg=err) return resolved def parse_host_port(host_port): """ Takes a string argument specifying host or host:port. Returns a (hostname, port) or (ip_address, port) tuple. If no port is given, the second (port) element of the returned tuple will be None. host:port argument, for example, is accepted in the forms of: - hostname - hostname:1234 - hostname.domain.tld - hostname.domain.tld:5678 - [1234::5]:5678 - 1234::5 - 10.11.12.13:4567 - 10.11.12.13 """ host, port = None, None # default _s_ = host_port[:] if _s_[0] == "[": if "]" in host_port: host, _s_ = _s_.lstrip("[").rsplit("]", 1) host = ipaddress.IPv6Address(host).compressed if _s_[0] == ":": port = int(_s_.lstrip(":")) else: if len(_s_) > 1: raise ValueError('found ambiguous "{}" port in "{}"'.format(_s_, host_port)) else: if _s_.count(":") == 1: host, _hostport_separator_, port = _s_.partition(":") try: port = int(port) except ValueError as _e_: log.error('host_port "%s" port value "%s" is not an integer.', host_port, port) raise _e_ else: host = _s_ try: if not isinstance(host, ipaddress._BaseAddress): host_ip = ipaddress.ip_address(host).compressed host = host_ip except ValueError: log.debug('"%s" Not an IP address? Assuming it is a hostname.', host) if host != sanitize_host(host): log.error('bad hostname: "%s"', host) raise ValueError('bad hostname: "{}"'.format(host)) return host, port def is_fqdn(hostname): """ Verify if hostname conforms to be a FQDN. :param hostname: text string with the name of the host :return: bool, True if hostname is correct FQDN, False otherwise """ compliant = re.compile(r"(?!-)[A-Z\d\-\_]{1,63}(?<!-)$", re.IGNORECASE) return "." in hostname and len(hostname) < 0xff and all(compliant.match(x) for x in hostname.rstrip(".").split("."))
saltstack/salt
salt/utils/network.py
get_net_start
python
def get_net_start(ipaddr, netmask): ''' Return the address of the network ''' net = ipaddress.ip_network('{0}/{1}'.format(ipaddr, netmask), strict=False) return six.text_type(net.network_address)
Return the address of the network
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/network.py#L1063-L1068
null
# -*- coding: utf-8 -*- ''' Define some generic socket functions for network modules ''' # Import python libs from __future__ import absolute_import, unicode_literals, print_function import itertools import os import re import types import socket import logging import platform import random import subprocess from string import ascii_letters, digits # Import 3rd-party libs from salt.ext import six from salt.ext.six.moves import range # pylint: disable=import-error,redefined-builtin # Attempt to import wmi try: import wmi import salt.utils.winapi except ImportError: pass # Import salt libs import salt.utils.args import salt.utils.files import salt.utils.path import salt.utils.platform import salt.utils.stringutils import salt.utils.zeromq from salt._compat import ipaddress from salt.exceptions import SaltClientError, SaltSystemExit from salt.utils.decorators.jinja import jinja_filter from salt.utils.versions import LooseVersion # inet_pton does not exist in Windows, this is a workaround if salt.utils.platform.is_windows(): from salt.ext import win_inet_pton # pylint: disable=unused-import log = logging.getLogger(__name__) try: import ctypes import ctypes.util libc = ctypes.cdll.LoadLibrary(ctypes.util.find_library("c")) res_init = libc.__res_init except (ImportError, OSError, AttributeError, TypeError): pass # pylint: disable=C0103 def sanitize_host(host): ''' Sanitize host string. https://tools.ietf.org/html/rfc1123#section-2.1 ''' RFC952_characters = ascii_letters + digits + ".-" return "".join([c for c in host[0:255] if c in RFC952_characters]) def isportopen(host, port): ''' Return status of a port ''' if not 1 <= int(port) <= 65535: return False sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) out = sock.connect_ex((sanitize_host(host), int(port))) return out def host_to_ips(host): ''' Returns a list of IP addresses of a given hostname or None if not found. ''' ips = [] try: for family, socktype, proto, canonname, sockaddr in socket.getaddrinfo( host, 0, socket.AF_UNSPEC, socket.SOCK_STREAM): if family == socket.AF_INET: ip, port = sockaddr elif family == socket.AF_INET6: ip, port, flow_info, scope_id = sockaddr ips.append(ip) if not ips: ips = None except Exception: ips = None return ips def _generate_minion_id(): ''' Get list of possible host names and convention names. :return: ''' # There are three types of hostnames: # 1. Network names. How host is accessed from the network. # 2. Host aliases. They might be not available in all the network or only locally (/etc/hosts) # 3. Convention names, an internal nodename. class DistinctList(list): ''' List, which allows one to append only distinct objects. Needs to work on Python 2.6, because of collections.OrderedDict only since 2.7 version. Override 'filter()' for custom filtering. ''' localhost_matchers = [r'localhost.*', r'ip6-.*', r'127[.]\d', r'0\.0\.0\.0', r'::1.*', r'ipv6-.*', r'fe00::.*', r'fe02::.*', r'1.0.0.*.ip6.arpa'] def append(self, p_object): if p_object and p_object not in self and not self.filter(p_object): super(DistinctList, self).append(p_object) return self def extend(self, iterable): for obj in iterable: self.append(obj) return self def filter(self, element): 'Returns True if element needs to be filtered' for rgx in self.localhost_matchers: if re.match(rgx, element): return True def first(self): return self and self[0] or None hostname = socket.gethostname() hosts = DistinctList().append( salt.utils.stringutils.to_unicode(socket.getfqdn(salt.utils.stringutils.to_bytes(hostname))) ).append(platform.node()).append(hostname) if not hosts: try: for a_nfo in socket.getaddrinfo(hosts.first() or 'localhost', None, socket.AF_INET, socket.SOCK_RAW, socket.IPPROTO_IP, socket.AI_CANONNAME): if len(a_nfo) > 3: hosts.append(a_nfo[3]) except socket.gaierror: log.warning('Cannot resolve address %s info via socket: %s', hosts.first() or 'localhost (N/A)', socket.gaierror) # Universal method for everywhere (Linux, Slowlaris, Windows etc) for f_name in ('/etc/hostname', '/etc/nodename', '/etc/hosts', r'{win}\system32\drivers\etc\hosts'.format(win=os.getenv('WINDIR'))): try: with salt.utils.files.fopen(f_name) as f_hdl: for line in f_hdl: line = salt.utils.stringutils.to_unicode(line) hst = line.strip().split('#')[0].strip().split() if hst: if hst[0][:4] in ('127.', '::1') or len(hst) == 1: hosts.extend(hst) except IOError: pass # include public and private ipaddresses return hosts.extend([addr for addr in ip_addrs() if not ipaddress.ip_address(addr).is_loopback]) def generate_minion_id(): ''' Return only first element of the hostname from all possible list. :return: ''' try: ret = salt.utils.stringutils.to_unicode(_generate_minion_id().first()) except TypeError: ret = None return ret or 'localhost' def get_socket(addr, type=socket.SOCK_STREAM, proto=0): ''' Return a socket object for the addr IP-version agnostic ''' version = ipaddress.ip_address(addr).version if version == 4: family = socket.AF_INET elif version == 6: family = socket.AF_INET6 return socket.socket(family, type, proto) def get_fqhostname(): ''' Returns the fully qualified hostname ''' # try getaddrinfo() fqdn = None try: addrinfo = socket.getaddrinfo( socket.gethostname(), 0, socket.AF_UNSPEC, socket.SOCK_STREAM, socket.SOL_TCP, socket.AI_CANONNAME ) for info in addrinfo: # info struct [family, socktype, proto, canonname, sockaddr] # On Windows `canonname` can be an empty string # This can cause the function to return `None` if len(info) > 3 and info[3]: fqdn = info[3] break except socket.gaierror: pass # NOTE: this used to log.error() but it was later disabled except socket.error as err: log.debug('socket.getaddrinfo() failure while finding fqdn: %s', err) if fqdn is None: fqdn = socket.getfqdn() return fqdn def ip_to_host(ip): ''' Returns the hostname of a given IP ''' try: hostname, aliaslist, ipaddrlist = socket.gethostbyaddr(ip) except Exception as exc: log.debug('salt.utils.network.ip_to_host(%r) failed: %s', ip, exc) hostname = None return hostname # pylint: enable=C0103 def is_reachable_host(entity_name): ''' Returns a bool telling if the entity name is a reachable host (IPv4/IPv6/FQDN/etc). :param hostname: :return: ''' try: assert type(socket.getaddrinfo(entity_name, 0, 0, 0, 0)) == list ret = True except socket.gaierror: ret = False return ret def is_ip(ip): ''' Returns a bool telling if the passed IP is a valid IPv4 or IPv6 address. ''' return is_ipv4(ip) or is_ipv6(ip) def is_ipv4(ip): ''' Returns a bool telling if the value passed to it was a valid IPv4 address ''' try: return ipaddress.ip_address(ip).version == 4 except ValueError: return False def is_ipv6(ip): ''' Returns a bool telling if the value passed to it was a valid IPv6 address ''' try: return ipaddress.ip_address(ip).version == 6 except ValueError: return False def is_subnet(cidr): ''' Returns a bool telling if the passed string is an IPv4 or IPv6 subnet ''' return is_ipv4_subnet(cidr) or is_ipv6_subnet(cidr) def is_ipv4_subnet(cidr): ''' Returns a bool telling if the passed string is an IPv4 subnet ''' try: return '/' in cidr and bool(ipaddress.IPv4Network(cidr)) except Exception: return False def is_ipv6_subnet(cidr): ''' Returns a bool telling if the passed string is an IPv6 subnet ''' try: return '/' in cidr and bool(ipaddress.IPv6Network(cidr)) except Exception: return False @jinja_filter('is_ip') def is_ip_filter(ip, options=None): ''' Returns a bool telling if the passed IP is a valid IPv4 or IPv6 address. ''' return is_ipv4_filter(ip, options=options) or is_ipv6_filter(ip, options=options) def _ip_options_global(ip_obj, version): return not ip_obj.is_private def _ip_options_multicast(ip_obj, version): return ip_obj.is_multicast def _ip_options_loopback(ip_obj, version): return ip_obj.is_loopback def _ip_options_link_local(ip_obj, version): return ip_obj.is_link_local def _ip_options_private(ip_obj, version): return ip_obj.is_private def _ip_options_reserved(ip_obj, version): return ip_obj.is_reserved def _ip_options_site_local(ip_obj, version): if version == 6: return ip_obj.is_site_local return False def _ip_options_unspecified(ip_obj, version): return ip_obj.is_unspecified def _ip_options(ip_obj, version, options=None): # will process and IP options options_fun_map = { 'global': _ip_options_global, 'link-local': _ip_options_link_local, 'linklocal': _ip_options_link_local, 'll': _ip_options_link_local, 'link_local': _ip_options_link_local, 'loopback': _ip_options_loopback, 'lo': _ip_options_loopback, 'multicast': _ip_options_multicast, 'private': _ip_options_private, 'public': _ip_options_global, 'reserved': _ip_options_reserved, 'site-local': _ip_options_site_local, 'sl': _ip_options_site_local, 'site_local': _ip_options_site_local, 'unspecified': _ip_options_unspecified } if not options: return six.text_type(ip_obj) # IP version already checked options_list = [option.strip() for option in options.split(',')] for option, fun in options_fun_map.items(): if option in options_list: fun_res = fun(ip_obj, version) if not fun_res: return None # stop at first failed test # else continue return six.text_type(ip_obj) def _is_ipv(ip, version, options=None): if not version: version = 4 if version not in (4, 6): return None try: ip_obj = ipaddress.ip_address(ip) except ValueError: # maybe it is an IP network try: ip_obj = ipaddress.ip_interface(ip) except ValueError: # nope, still not :( return None if not ip_obj.version == version: return None # has the right version, let's move on return _ip_options(ip_obj, version, options=options) @jinja_filter('is_ipv4') def is_ipv4_filter(ip, options=None): ''' Returns a bool telling if the value passed to it was a valid IPv4 address. ip The IP address. net: False Consider IP addresses followed by netmask. options CSV of options regarding the nature of the IP address. E.g.: loopback, multicast, private etc. ''' _is_ipv4 = _is_ipv(ip, 4, options=options) return isinstance(_is_ipv4, six.string_types) @jinja_filter('is_ipv6') def is_ipv6_filter(ip, options=None): ''' Returns a bool telling if the value passed to it was a valid IPv6 address. ip The IP address. net: False Consider IP addresses followed by netmask. options CSV of options regarding the nature of the IP address. E.g.: loopback, multicast, private etc. ''' _is_ipv6 = _is_ipv(ip, 6, options=options) return isinstance(_is_ipv6, six.string_types) def _ipv_filter(value, version, options=None): if version not in (4, 6): return if isinstance(value, (six.string_types, six.text_type, six.binary_type)): return _is_ipv(value, version, options=options) # calls is_ipv4 or is_ipv6 for `value` elif isinstance(value, (list, tuple, types.GeneratorType)): # calls is_ipv4 or is_ipv6 for each element in the list # os it filters and returns only those elements having the desired IP version return [ _is_ipv(addr, version, options=options) for addr in value if _is_ipv(addr, version, options=options) is not None ] return None @jinja_filter('ipv4') def ipv4(value, options=None): ''' Filters a list and returns IPv4 values only. ''' return _ipv_filter(value, 4, options=options) @jinja_filter('ipv6') def ipv6(value, options=None): ''' Filters a list and returns IPv6 values only. ''' return _ipv_filter(value, 6, options=options) @jinja_filter('ipaddr') def ipaddr(value, options=None): ''' Filters and returns only valid IP objects. ''' ipv4_obj = ipv4(value, options=options) ipv6_obj = ipv6(value, options=options) if ipv4_obj is None or ipv6_obj is None: # an IP address can be either IPv4 either IPv6 # therefofe if the value passed as arg is not a list, at least one of the calls above will return None # if one of them is none, means that we should return only one of them return ipv4_obj or ipv6_obj # one of them else: return ipv4_obj + ipv6_obj # extend lists def _filter_ipaddr(value, options, version=None): ipaddr_filter_out = None if version: if version == 4: ipaddr_filter_out = ipv4(value, options) elif version == 6: ipaddr_filter_out = ipv6(value, options) else: ipaddr_filter_out = ipaddr(value, options) if not ipaddr_filter_out: return if not isinstance(ipaddr_filter_out, (list, tuple, types.GeneratorType)): ipaddr_filter_out = [ipaddr_filter_out] return ipaddr_filter_out @jinja_filter('ip_host') def ip_host(value, options=None, version=None): ''' Returns the interfaces IP address, e.g.: 192.168.0.1/28. ''' ipaddr_filter_out = _filter_ipaddr(value, options=options, version=version) if not ipaddr_filter_out: return if not isinstance(value, (list, tuple, types.GeneratorType)): return six.text_type(ipaddress.ip_interface(ipaddr_filter_out[0])) return [six.text_type(ipaddress.ip_interface(ip_a)) for ip_a in ipaddr_filter_out] def _network_hosts(ip_addr_entry): return [ six.text_type(host) for host in ipaddress.ip_network(ip_addr_entry, strict=False).hosts() ] @jinja_filter('network_hosts') def network_hosts(value, options=None, version=None): ''' Return the list of hosts within a network. .. note:: When running this command with a large IPv6 network, the command will take a long time to gather all of the hosts. ''' ipaddr_filter_out = _filter_ipaddr(value, options=options, version=version) if not ipaddr_filter_out: return if not isinstance(value, (list, tuple, types.GeneratorType)): return _network_hosts(ipaddr_filter_out[0]) return [ _network_hosts(ip_a) for ip_a in ipaddr_filter_out ] def _network_size(ip_addr_entry): return ipaddress.ip_network(ip_addr_entry, strict=False).num_addresses @jinja_filter('network_size') def network_size(value, options=None, version=None): ''' Get the size of a network. ''' ipaddr_filter_out = _filter_ipaddr(value, options=options, version=version) if not ipaddr_filter_out: return if not isinstance(value, (list, tuple, types.GeneratorType)): return _network_size(ipaddr_filter_out[0]) return [ _network_size(ip_a) for ip_a in ipaddr_filter_out ] def natural_ipv4_netmask(ip, fmt='prefixlen'): ''' Returns the "natural" mask of an IPv4 address ''' bits = _ipv4_to_bits(ip) if bits.startswith('11'): mask = '24' elif bits.startswith('1'): mask = '16' else: mask = '8' if fmt == 'netmask': return cidr_to_ipv4_netmask(mask) else: return '/' + mask def rpad_ipv4_network(ip): ''' Returns an IP network address padded with zeros. Ex: '192.168.3' -> '192.168.3.0' '10.209' -> '10.209.0.0' ''' return '.'.join(itertools.islice(itertools.chain(ip.split('.'), '0000'), 0, 4)) def cidr_to_ipv4_netmask(cidr_bits): ''' Returns an IPv4 netmask ''' try: cidr_bits = int(cidr_bits) if not 1 <= cidr_bits <= 32: return '' except ValueError: return '' netmask = '' for idx in range(4): if idx: netmask += '.' if cidr_bits >= 8: netmask += '255' cidr_bits -= 8 else: netmask += '{0:d}'.format(256 - (2 ** (8 - cidr_bits))) cidr_bits = 0 return netmask def _number_of_set_bits_to_ipv4_netmask(set_bits): # pylint: disable=C0103 ''' Returns an IPv4 netmask from the integer representation of that mask. Ex. 0xffffff00 -> '255.255.255.0' ''' return cidr_to_ipv4_netmask(_number_of_set_bits(set_bits)) # pylint: disable=C0103 def _number_of_set_bits(x): ''' Returns the number of bits that are set in a 32bit int ''' # Taken from http://stackoverflow.com/a/4912729. Many thanks! x -= (x >> 1) & 0x55555555 x = ((x >> 2) & 0x33333333) + (x & 0x33333333) x = ((x >> 4) + x) & 0x0f0f0f0f x += x >> 8 x += x >> 16 return x & 0x0000003f # pylint: enable=C0103 def _interfaces_ip(out): ''' Uses ip to return a dictionary of interfaces with various information about each (up/down state, ip address, netmask, and hwaddr) ''' ret = dict() def parse_network(value, cols): ''' Return a tuple of ip, netmask, broadcast based on the current set of cols ''' brd = None scope = None if '/' in value: # we have a CIDR in this address ip, cidr = value.split('/') # pylint: disable=C0103 else: ip = value # pylint: disable=C0103 cidr = 32 if type_ == 'inet': mask = cidr_to_ipv4_netmask(int(cidr)) if 'brd' in cols: brd = cols[cols.index('brd') + 1] elif type_ == 'inet6': mask = cidr if 'scope' in cols: scope = cols[cols.index('scope') + 1] return (ip, mask, brd, scope) groups = re.compile('\r?\n\\d').split(out) for group in groups: iface = None data = dict() for line in group.splitlines(): if ' ' not in line: continue match = re.match(r'^\d*:\s+([\w.\-]+)(?:@)?([\w.\-]+)?:\s+<(.+)>', line) if match: iface, parent, attrs = match.groups() if 'UP' in attrs.split(','): data['up'] = True else: data['up'] = False if parent: data['parent'] = parent continue cols = line.split() if len(cols) >= 2: type_, value = tuple(cols[0:2]) iflabel = cols[-1:][0] if type_ in ('inet', 'inet6'): if 'secondary' not in cols: ipaddr, netmask, broadcast, scope = parse_network(value, cols) if type_ == 'inet': if 'inet' not in data: data['inet'] = list() addr_obj = dict() addr_obj['address'] = ipaddr addr_obj['netmask'] = netmask addr_obj['broadcast'] = broadcast addr_obj['label'] = iflabel data['inet'].append(addr_obj) elif type_ == 'inet6': if 'inet6' not in data: data['inet6'] = list() addr_obj = dict() addr_obj['address'] = ipaddr addr_obj['prefixlen'] = netmask addr_obj['scope'] = scope data['inet6'].append(addr_obj) else: if 'secondary' not in data: data['secondary'] = list() ip_, mask, brd, scp = parse_network(value, cols) data['secondary'].append({ 'type': type_, 'address': ip_, 'netmask': mask, 'broadcast': brd, 'label': iflabel, }) del ip_, mask, brd, scp elif type_.startswith('link'): data['hwaddr'] = value if iface: ret[iface] = data del iface, data return ret def _interfaces_ifconfig(out): ''' Uses ifconfig to return a dictionary of interfaces with various information about each (up/down state, ip address, netmask, and hwaddr) ''' ret = dict() piface = re.compile(r'^([^\s:]+)') pmac = re.compile('.*?(?:HWaddr|ether|address:|lladdr) ([0-9a-fA-F:]+)') if salt.utils.platform.is_sunos(): pip = re.compile(r'.*?(?:inet\s+)([0-9]+\.[0-9]+\.[0-9]+\.[0-9]+)(.*)') pip6 = re.compile('.*?(?:inet6 )([0-9a-fA-F:]+)') pmask6 = re.compile(r'.*?(?:inet6 [0-9a-fA-F:]+/(\d+)).*') else: pip = re.compile(r'.*?(?:inet addr:|inet [^\d]*)(.*?)\s') pip6 = re.compile('.*?(?:inet6 addr: (.*?)/|inet6 )([0-9a-fA-F:]+)') pmask6 = re.compile(r'.*?(?:inet6 addr: [0-9a-fA-F:]+/(\d+)|prefixlen (\d+))(?: Scope:([a-zA-Z]+)| scopeid (0x[0-9a-fA-F]))?') pmask = re.compile(r'.*?(?:Mask:|netmask )(?:((?:0x)?[0-9a-fA-F]{8})|([\d\.]+))') pupdown = re.compile('UP') pbcast = re.compile(r'.*?(?:Bcast:|broadcast )([\d\.]+)') groups = re.compile('\r?\n(?=\\S)').split(out) for group in groups: data = dict() iface = '' updown = False for line in group.splitlines(): miface = piface.match(line) mmac = pmac.match(line) mip = pip.match(line) mip6 = pip6.match(line) mupdown = pupdown.search(line) if miface: iface = miface.group(1) if mmac: data['hwaddr'] = mmac.group(1) if salt.utils.platform.is_sunos(): expand_mac = [] for chunk in data['hwaddr'].split(':'): expand_mac.append('0{0}'.format(chunk) if len(chunk) < 2 else '{0}'.format(chunk)) data['hwaddr'] = ':'.join(expand_mac) if mip: if 'inet' not in data: data['inet'] = list() addr_obj = dict() addr_obj['address'] = mip.group(1) mmask = pmask.match(line) if mmask: if mmask.group(1): mmask = _number_of_set_bits_to_ipv4_netmask( int(mmask.group(1), 16)) else: mmask = mmask.group(2) addr_obj['netmask'] = mmask mbcast = pbcast.match(line) if mbcast: addr_obj['broadcast'] = mbcast.group(1) data['inet'].append(addr_obj) if mupdown: updown = True if mip6: if 'inet6' not in data: data['inet6'] = list() addr_obj = dict() addr_obj['address'] = mip6.group(1) or mip6.group(2) mmask6 = pmask6.match(line) if mmask6: addr_obj['prefixlen'] = mmask6.group(1) or mmask6.group(2) if not salt.utils.platform.is_sunos(): ipv6scope = mmask6.group(3) or mmask6.group(4) addr_obj['scope'] = ipv6scope.lower() if ipv6scope is not None else ipv6scope # SunOS sometimes has ::/0 as inet6 addr when using addrconf if not salt.utils.platform.is_sunos() \ or addr_obj['address'] != '::' \ and addr_obj['prefixlen'] != 0: data['inet6'].append(addr_obj) data['up'] = updown if iface in ret: # SunOS optimization, where interfaces occur twice in 'ifconfig -a' # output with the same name: for ipv4 and then for ipv6 addr family. # Every instance has it's own 'UP' status and we assume that ipv4 # status determines global interface status. # # merge items with higher priority for older values # after that merge the inet and inet6 sub items for both ret[iface] = dict(list(data.items()) + list(ret[iface].items())) if 'inet' in data: ret[iface]['inet'].extend(x for x in data['inet'] if x not in ret[iface]['inet']) if 'inet6' in data: ret[iface]['inet6'].extend(x for x in data['inet6'] if x not in ret[iface]['inet6']) else: ret[iface] = data del data return ret def linux_interfaces(): ''' Obtain interface information for *NIX/BSD variants ''' ifaces = dict() ip_path = salt.utils.path.which('ip') ifconfig_path = None if ip_path else salt.utils.path.which('ifconfig') if ip_path: cmd1 = subprocess.Popen( '{0} link show'.format(ip_path), shell=True, close_fds=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT).communicate()[0] cmd2 = subprocess.Popen( '{0} addr show'.format(ip_path), shell=True, close_fds=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT).communicate()[0] ifaces = _interfaces_ip("{0}\n{1}".format( salt.utils.stringutils.to_str(cmd1), salt.utils.stringutils.to_str(cmd2))) elif ifconfig_path: cmd = subprocess.Popen( '{0} -a'.format(ifconfig_path), shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT).communicate()[0] ifaces = _interfaces_ifconfig(salt.utils.stringutils.to_str(cmd)) return ifaces def _netbsd_interfaces_ifconfig(out): ''' Uses ifconfig to return a dictionary of interfaces with various information about each (up/down state, ip address, netmask, and hwaddr) ''' ret = dict() piface = re.compile(r'^([^\s:]+)') pmac = re.compile('.*?address: ([0-9a-f:]+)') pip = re.compile(r'.*?inet [^\d]*(.*?)/([\d]*)\s') pip6 = re.compile(r'.*?inet6 ([0-9a-f:]+)%([a-zA-Z0-9]*)/([\d]*)\s') pupdown = re.compile('UP') pbcast = re.compile(r'.*?broadcast ([\d\.]+)') groups = re.compile('\r?\n(?=\\S)').split(out) for group in groups: data = dict() iface = '' updown = False for line in group.splitlines(): miface = piface.match(line) mmac = pmac.match(line) mip = pip.match(line) mip6 = pip6.match(line) mupdown = pupdown.search(line) if miface: iface = miface.group(1) if mmac: data['hwaddr'] = mmac.group(1) if mip: if 'inet' not in data: data['inet'] = list() addr_obj = dict() addr_obj['address'] = mip.group(1) mmask = mip.group(2) if mip.group(2): addr_obj['netmask'] = cidr_to_ipv4_netmask(mip.group(2)) mbcast = pbcast.match(line) if mbcast: addr_obj['broadcast'] = mbcast.group(1) data['inet'].append(addr_obj) if mupdown: updown = True if mip6: if 'inet6' not in data: data['inet6'] = list() addr_obj = dict() addr_obj['address'] = mip6.group(1) mmask6 = mip6.group(3) addr_obj['scope'] = mip6.group(2) addr_obj['prefixlen'] = mip6.group(3) data['inet6'].append(addr_obj) data['up'] = updown ret[iface] = data del data return ret def netbsd_interfaces(): ''' Obtain interface information for NetBSD >= 8 where the ifconfig output diverged from other BSD variants (Netmask is now part of the address) ''' # NetBSD versions prior to 8.0 can still use linux_interfaces() if LooseVersion(os.uname()[2]) < LooseVersion('8.0'): return linux_interfaces() ifconfig_path = salt.utils.path.which('ifconfig') cmd = subprocess.Popen( '{0} -a'.format(ifconfig_path), shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT).communicate()[0] return _netbsd_interfaces_ifconfig(salt.utils.stringutils.to_str(cmd)) def _interfaces_ipconfig(out): ''' Returns a dictionary of interfaces with various information about each (up/down state, ip address, netmask, and hwaddr) NOTE: This is not used by any function and may be able to be removed in the future. ''' ifaces = dict() iface = None adapter_iface_regex = re.compile(r'adapter (\S.+):$') for line in out.splitlines(): if not line: continue # TODO what does Windows call Infiniband and 10/40gige adapters if line.startswith('Ethernet'): iface = ifaces[adapter_iface_regex.search(line).group(1)] iface['up'] = True addr = None continue if iface: key, val = line.split(',', 1) key = key.strip(' .') val = val.strip() if addr and key == 'Subnet Mask': addr['netmask'] = val elif key in ('IP Address', 'IPv4 Address'): if 'inet' not in iface: iface['inet'] = list() addr = {'address': val.rstrip('(Preferred)'), 'netmask': None, 'broadcast': None} # TODO find the broadcast iface['inet'].append(addr) elif 'IPv6 Address' in key: if 'inet6' not in iface: iface['inet'] = list() # XXX What is the prefixlen!? addr = {'address': val.rstrip('(Preferred)'), 'prefixlen': None} iface['inet6'].append(addr) elif key == 'Physical Address': iface['hwaddr'] = val elif key == 'Media State': # XXX seen used for tunnel adaptors # might be useful iface['up'] = (val != 'Media disconnected') def win_interfaces(): ''' Obtain interface information for Windows systems ''' with salt.utils.winapi.Com(): c = wmi.WMI() ifaces = {} for iface in c.Win32_NetworkAdapterConfiguration(IPEnabled=1): ifaces[iface.Description] = dict() if iface.MACAddress: ifaces[iface.Description]['hwaddr'] = iface.MACAddress if iface.IPEnabled: ifaces[iface.Description]['up'] = True for ip in iface.IPAddress: if '.' in ip: if 'inet' not in ifaces[iface.Description]: ifaces[iface.Description]['inet'] = [] item = {'address': ip, 'label': iface.Description} if iface.DefaultIPGateway: broadcast = next((i for i in iface.DefaultIPGateway if '.' in i), '') if broadcast: item['broadcast'] = broadcast if iface.IPSubnet: netmask = next((i for i in iface.IPSubnet if '.' in i), '') if netmask: item['netmask'] = netmask ifaces[iface.Description]['inet'].append(item) if ':' in ip: if 'inet6' not in ifaces[iface.Description]: ifaces[iface.Description]['inet6'] = [] item = {'address': ip} if iface.DefaultIPGateway: broadcast = next((i for i in iface.DefaultIPGateway if ':' in i), '') if broadcast: item['broadcast'] = broadcast if iface.IPSubnet: netmask = next((i for i in iface.IPSubnet if ':' in i), '') if netmask: item['netmask'] = netmask ifaces[iface.Description]['inet6'].append(item) else: ifaces[iface.Description]['up'] = False return ifaces def interfaces(): ''' Return a dictionary of information about all the interfaces on the minion ''' if salt.utils.platform.is_windows(): return win_interfaces() elif salt.utils.platform.is_netbsd(): return netbsd_interfaces() else: return linux_interfaces() def get_net_size(mask): ''' Turns an IPv4 netmask into it's corresponding prefix length (255.255.255.0 -> 24 as in 192.168.1.10/24). ''' binary_str = '' for octet in mask.split('.'): binary_str += bin(int(octet))[2:].zfill(8) return len(binary_str.rstrip('0')) def calc_net(ipaddr, netmask=None): ''' Takes IP (CIDR notation supported) and optionally netmask and returns the network in CIDR-notation. (The IP can be any IP inside the subnet) ''' if netmask is not None: ipaddr = '{0}/{1}'.format(ipaddr, netmask) return six.text_type(ipaddress.ip_network(ipaddr, strict=False)) def _ipv4_to_bits(ipaddr): ''' Accepts an IPv4 dotted quad and returns a string representing its binary counterpart ''' return ''.join([bin(int(x))[2:].rjust(8, '0') for x in ipaddr.split('.')]) def _get_iface_info(iface): ''' If `iface` is available, return interface info and no error, otherwise return no info and log and return an error ''' iface_info = interfaces() if iface in iface_info.keys(): return iface_info, False else: error_msg = ('Interface "{0}" not in available interfaces: "{1}"' ''.format(iface, '", "'.join(iface_info.keys()))) log.error(error_msg) return None, error_msg def _hw_addr_aix(iface): ''' Return the hardware address (a.k.a. MAC address) for a given interface on AIX MAC address not available in through interfaces ''' cmd = subprocess.Popen( 'entstat -d {0} | grep \'Hardware Address\''.format(iface), shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT).communicate()[0] if cmd: comps = cmd.split(' ') if len(comps) == 3: mac_addr = comps[2].strip('\'').strip() return mac_addr error_msg = ('Interface "{0}" either not available or does not contain a hardware address'.format(iface)) log.error(error_msg) return error_msg def hw_addr(iface): ''' Return the hardware address (a.k.a. MAC address) for a given interface .. versionchanged:: 2016.11.4 Added support for AIX ''' if salt.utils.platform.is_aix(): return _hw_addr_aix iface_info, error = _get_iface_info(iface) if error is False: return iface_info.get(iface, {}).get('hwaddr', '') else: return error def interface(iface): ''' Return the details of `iface` or an error if it does not exist ''' iface_info, error = _get_iface_info(iface) if error is False: return iface_info.get(iface, {}).get('inet', '') else: return error def interface_ip(iface): ''' Return `iface` IPv4 addr or an error if `iface` does not exist ''' iface_info, error = _get_iface_info(iface) if error is False: inet = iface_info.get(iface, {}).get('inet', None) return inet[0].get('address', '') if inet else '' else: return error def _subnets(proto='inet', interfaces_=None): ''' Returns a list of subnets to which the host belongs ''' if interfaces_ is None: ifaces = interfaces() elif isinstance(interfaces_, list): ifaces = {} for key, value in six.iteritems(interfaces()): if key in interfaces_: ifaces[key] = value else: ifaces = {interfaces_: interfaces().get(interfaces_, {})} ret = set() if proto == 'inet': subnet = 'netmask' dflt_cidr = 32 elif proto == 'inet6': subnet = 'prefixlen' dflt_cidr = 128 else: log.error('Invalid proto %s calling subnets()', proto) return for ip_info in six.itervalues(ifaces): addrs = ip_info.get(proto, []) addrs.extend([addr for addr in ip_info.get('secondary', []) if addr.get('type') == proto]) for intf in addrs: if subnet in intf: intf = ipaddress.ip_interface('{0}/{1}'.format(intf['address'], intf[subnet])) else: intf = ipaddress.ip_interface('{0}/{1}'.format(intf['address'], dflt_cidr)) if not intf.is_loopback: ret.add(intf.network) return [six.text_type(net) for net in sorted(ret)] def subnets(interfaces=None): ''' Returns a list of IPv4 subnets to which the host belongs ''' return _subnets('inet', interfaces_=interfaces) def subnets6(): ''' Returns a list of IPv6 subnets to which the host belongs ''' return _subnets('inet6') def in_subnet(cidr, addr=None): ''' Returns True if host or (any of) addrs is within specified subnet, otherwise False ''' try: cidr = ipaddress.ip_network(cidr) except ValueError: log.error('Invalid CIDR \'%s\'', cidr) return False if addr is None: addr = ip_addrs() addr.extend(ip_addrs6()) elif not isinstance(addr, (list, tuple)): addr = (addr,) return any(ipaddress.ip_address(item) in cidr for item in addr) def _ip_addrs(interface=None, include_loopback=False, interface_data=None, proto='inet'): ''' Return the full list of IP adresses matching the criteria proto = inet|inet6 ''' ret = set() ifaces = interface_data \ if isinstance(interface_data, dict) \ else interfaces() if interface is None: target_ifaces = ifaces else: target_ifaces = dict([(k, v) for k, v in six.iteritems(ifaces) if k == interface]) if not target_ifaces: log.error('Interface %s not found.', interface) for ip_info in six.itervalues(target_ifaces): addrs = ip_info.get(proto, []) addrs.extend([addr for addr in ip_info.get('secondary', []) if addr.get('type') == proto]) for addr in addrs: addr = ipaddress.ip_address(addr.get('address')) if not addr.is_loopback or include_loopback: ret.add(addr) return [six.text_type(addr) for addr in sorted(ret)] def ip_addrs(interface=None, include_loopback=False, interface_data=None): ''' Returns a list of IPv4 addresses assigned to the host. 127.0.0.1 is ignored, unless 'include_loopback=True' is indicated. If 'interface' is provided, then only IP addresses from that interface will be returned. ''' return _ip_addrs(interface, include_loopback, interface_data, 'inet') def ip_addrs6(interface=None, include_loopback=False, interface_data=None): ''' Returns a list of IPv6 addresses assigned to the host. ::1 is ignored, unless 'include_loopback=True' is indicated. If 'interface' is provided, then only IP addresses from that interface will be returned. ''' return _ip_addrs(interface, include_loopback, interface_data, 'inet6') def hex2ip(hex_ip, invert=False): ''' Convert a hex string to an ip, if a failure occurs the original hex is returned. If 'invert=True' assume that ip from /proc/net/<proto> ''' if len(hex_ip) == 32: # ipv6 ip = [] for i in range(0, 32, 8): ip_part = hex_ip[i:i + 8] ip_part = [ip_part[x:x + 2] for x in range(0, 8, 2)] if invert: ip.append("{0[3]}{0[2]}:{0[1]}{0[0]}".format(ip_part)) else: ip.append("{0[0]}{0[1]}:{0[2]}{0[3]}".format(ip_part)) try: address = ipaddress.IPv6Address(":".join(ip)) if address.ipv4_mapped: return str(address.ipv4_mapped) else: return address.compressed except ipaddress.AddressValueError as ex: log.error('hex2ip - ipv6 address error: %s', ex) return hex_ip try: hip = int(hex_ip, 16) except ValueError: return hex_ip if invert: return '{3}.{2}.{1}.{0}'.format(hip >> 24 & 255, hip >> 16 & 255, hip >> 8 & 255, hip & 255) return '{0}.{1}.{2}.{3}'.format(hip >> 24 & 255, hip >> 16 & 255, hip >> 8 & 255, hip & 255) def mac2eui64(mac, prefix=None): ''' Convert a MAC address to a EUI64 identifier or, with prefix provided, a full IPv6 address ''' # http://tools.ietf.org/html/rfc4291#section-2.5.1 eui64 = re.sub(r'[.:-]', '', mac).lower() eui64 = eui64[0:6] + 'fffe' + eui64[6:] eui64 = hex(int(eui64[0:2], 16) | 2)[2:].zfill(2) + eui64[2:] if prefix is None: return ':'.join(re.findall(r'.{4}', eui64)) else: try: net = ipaddress.ip_network(prefix, strict=False) euil = int('0x{0}'.format(eui64), 16) return '{0}/{1}'.format(net[euil], net.prefixlen) except Exception: return def active_tcp(): ''' Return a dict describing all active tcp connections as quickly as possible ''' ret = {} for statf in ['/proc/net/tcp', '/proc/net/tcp6']: if os.path.isfile(statf): with salt.utils.files.fopen(statf, 'rb') as fp_: for line in fp_: line = salt.utils.stringutils.to_unicode(line) if line.strip().startswith('sl'): continue iret = _parse_tcp_line(line) sl = next(iter(iret)) if iret[sl]['state'] == 1: # 1 is ESTABLISHED del iret[sl]['state'] ret[len(ret)] = iret[sl] return ret def local_port_tcp(port): ''' Return a set of remote ip addrs attached to the specified local port ''' ret = _remotes_on(port, 'local_port') return ret def remote_port_tcp(port): ''' Return a set of ip addrs the current host is connected to on given port ''' ret = _remotes_on(port, 'remote_port') return ret def _remotes_on(port, which_end): ''' Return a set of ip addrs active tcp connections ''' port = int(port) ret = _netlink_tool_remote_on(port, which_end) if ret is not None: return ret ret = set() proc_available = False for statf in ['/proc/net/tcp', '/proc/net/tcp6']: if os.path.isfile(statf): proc_available = True with salt.utils.files.fopen(statf, 'r') as fp_: for line in fp_: line = salt.utils.stringutils.to_unicode(line) if line.strip().startswith('sl'): continue iret = _parse_tcp_line(line) sl = next(iter(iret)) if iret[sl][which_end] == port and iret[sl]['state'] == 1: # 1 is ESTABLISHED ret.add(iret[sl]['remote_addr']) if not proc_available: # Fallback to use OS specific tools if salt.utils.platform.is_sunos(): return _sunos_remotes_on(port, which_end) if salt.utils.platform.is_freebsd(): return _freebsd_remotes_on(port, which_end) if salt.utils.platform.is_netbsd(): return _netbsd_remotes_on(port, which_end) if salt.utils.platform.is_openbsd(): return _openbsd_remotes_on(port, which_end) if salt.utils.platform.is_windows(): return _windows_remotes_on(port, which_end) if salt.utils.platform.is_aix(): return _aix_remotes_on(port, which_end) return _linux_remotes_on(port, which_end) return ret def _parse_tcp_line(line): ''' Parse a single line from the contents of /proc/net/tcp or /proc/net/tcp6 ''' ret = {} comps = line.strip().split() sl = comps[0].rstrip(':') ret[sl] = {} l_addr, l_port = comps[1].split(':') r_addr, r_port = comps[2].split(':') ret[sl]['local_addr'] = hex2ip(l_addr, True) ret[sl]['local_port'] = int(l_port, 16) ret[sl]['remote_addr'] = hex2ip(r_addr, True) ret[sl]['remote_port'] = int(r_port, 16) ret[sl]['state'] = int(comps[3], 16) return ret def _netlink_tool_remote_on(port, which_end): ''' Returns set of ipv4 host addresses of remote established connections on local or remote tcp port. Parses output of shell 'ss' to get connections [root@salt-master ~]# ss -ant State Recv-Q Send-Q Local Address:Port Peer Address:Port LISTEN 0 511 *:80 *:* LISTEN 0 128 *:22 *:* ESTAB 0 0 127.0.0.1:56726 127.0.0.1:4505 ''' remotes = set() valid = False try: data = subprocess.check_output(['ss', '-ant']) # pylint: disable=minimum-python-version except subprocess.CalledProcessError: log.error('Failed ss') raise except OSError: # not command "No such file or directory" return None lines = salt.utils.stringutils.to_str(data).split('\n') for line in lines: if 'Address:Port' in line: # ss tools may not be valid valid = True continue elif 'ESTAB' not in line: continue chunks = line.split() local_host, local_port = chunks[3].split(':', 1) remote_host, remote_port = chunks[4].split(':', 1) if which_end == 'remote_port' and int(remote_port) != port: continue if which_end == 'local_port' and int(local_port) != port: continue remotes.add(remote_host) if valid is False: remotes = None return remotes def _sunos_remotes_on(port, which_end): ''' SunOS specific helper function. Returns set of ipv4 host addresses of remote established connections on local or remote tcp port. Parses output of shell 'netstat' to get connections [root@salt-master ~]# netstat -f inet -n TCP: IPv4 Local Address Remote Address Swind Send-Q Rwind Recv-Q State -------------------- -------------------- ----- ------ ----- ------ ----------- 10.0.0.101.4505 10.0.0.1.45329 1064800 0 1055864 0 ESTABLISHED 10.0.0.101.4505 10.0.0.100.50798 1064800 0 1055864 0 ESTABLISHED ''' remotes = set() try: data = subprocess.check_output(['netstat', '-f', 'inet', '-n']) # pylint: disable=minimum-python-version except subprocess.CalledProcessError: log.error('Failed netstat') raise lines = salt.utils.stringutils.to_str(data).split('\n') for line in lines: if 'ESTABLISHED' not in line: continue chunks = line.split() local_host, local_port = chunks[0].rsplit('.', 1) remote_host, remote_port = chunks[1].rsplit('.', 1) if which_end == 'remote_port' and int(remote_port) != port: continue if which_end == 'local_port' and int(local_port) != port: continue remotes.add(remote_host) return remotes def _freebsd_remotes_on(port, which_end): ''' Returns set of ipv4 host addresses of remote established connections on local tcp port port. Parses output of shell 'sockstat' (FreeBSD) to get connections $ sudo sockstat -4 USER COMMAND PID FD PROTO LOCAL ADDRESS FOREIGN ADDRESS root python2.7 1456 29 tcp4 *:4505 *:* root python2.7 1445 17 tcp4 *:4506 *:* root python2.7 1294 14 tcp4 127.0.0.1:11813 127.0.0.1:4505 root python2.7 1294 41 tcp4 127.0.0.1:61115 127.0.0.1:4506 $ sudo sockstat -4 -c -p 4506 USER COMMAND PID FD PROTO LOCAL ADDRESS FOREIGN ADDRESS root python2.7 1294 41 tcp4 127.0.0.1:61115 127.0.0.1:4506 ''' port = int(port) remotes = set() try: cmd = salt.utils.args.shlex_split('sockstat -4 -c -p {0}'.format(port)) data = subprocess.check_output(cmd) # pylint: disable=minimum-python-version except subprocess.CalledProcessError as ex: log.error('Failed "sockstat" with returncode = %s', ex.returncode) raise lines = salt.utils.stringutils.to_str(data).split('\n') for line in lines: chunks = line.split() if not chunks: continue # ['root', 'python2.7', '1456', '37', 'tcp4', # '127.0.0.1:4505-', '127.0.0.1:55703'] # print chunks if 'COMMAND' in chunks[1]: continue # ignore header if len(chunks) < 2: continue # sockstat -4 -c -p 4506 does this with high PIDs: # USER COMMAND PID FD PROTO LOCAL ADDRESS FOREIGN ADDRESS # salt-master python2.781106 35 tcp4 192.168.12.34:4506 192.168.12.45:60143 local = chunks[-2] remote = chunks[-1] lhost, lport = local.split(':') rhost, rport = remote.split(':') if which_end == 'local' and int(lport) != port: # ignore if local port not port continue if which_end == 'remote' and int(rport) != port: # ignore if remote port not port continue remotes.add(rhost) return remotes def _netbsd_remotes_on(port, which_end): ''' Returns set of ipv4 host addresses of remote established connections on local tcp port port. Parses output of shell 'sockstat' (NetBSD) to get connections $ sudo sockstat -4 -n USER COMMAND PID FD PROTO LOCAL ADDRESS FOREIGN ADDRESS root python2.7 1456 29 tcp *.4505 *.* root python2.7 1445 17 tcp *.4506 *.* root python2.7 1294 14 tcp 127.0.0.1.11813 127.0.0.1.4505 root python2.7 1294 41 tcp 127.0.0.1.61115 127.0.0.1.4506 $ sudo sockstat -4 -c -n -p 4506 USER COMMAND PID FD PROTO LOCAL ADDRESS FOREIGN ADDRESS root python2.7 1294 41 tcp 127.0.0.1.61115 127.0.0.1.4506 ''' port = int(port) remotes = set() try: cmd = salt.utils.args.shlex_split('sockstat -4 -c -n -p {0}'.format(port)) data = subprocess.check_output(cmd) # pylint: disable=minimum-python-version except subprocess.CalledProcessError as ex: log.error('Failed "sockstat" with returncode = %s', ex.returncode) raise lines = salt.utils.stringutils.to_str(data).split('\n') for line in lines: chunks = line.split() if not chunks: continue # ['root', 'python2.7', '1456', '37', 'tcp', # '127.0.0.1.4505-', '127.0.0.1.55703'] # print chunks if 'COMMAND' in chunks[1]: continue # ignore header if len(chunks) < 2: continue local = chunks[5].split('.') lport = local.pop() lhost = '.'.join(local) remote = chunks[6].split('.') rport = remote.pop() rhost = '.'.join(remote) if which_end == 'local' and int(lport) != port: # ignore if local port not port continue if which_end == 'remote' and int(rport) != port: # ignore if remote port not port continue remotes.add(rhost) return remotes def _openbsd_remotes_on(port, which_end): ''' OpenBSD specific helper function. Returns set of ipv4 host addresses of remote established connections on local or remote tcp port. Parses output of shell 'netstat' to get connections $ netstat -nf inet Active Internet connections Proto Recv-Q Send-Q Local Address Foreign Address (state) tcp 0 0 10.0.0.101.4505 10.0.0.1.45329 ESTABLISHED tcp 0 0 10.0.0.101.4505 10.0.0.100.50798 ESTABLISHED ''' remotes = set() try: data = subprocess.check_output(['netstat', '-nf', 'inet']) # pylint: disable=minimum-python-version except subprocess.CalledProcessError: log.error('Failed netstat') raise lines = data.split('\n') for line in lines: if 'ESTABLISHED' not in line: continue chunks = line.split() local_host, local_port = chunks[3].rsplit('.', 1) remote_host, remote_port = chunks[4].rsplit('.', 1) if which_end == 'remote_port' and int(remote_port) != port: continue if which_end == 'local_port' and int(local_port) != port: continue remotes.add(remote_host) return remotes def _windows_remotes_on(port, which_end): r''' Windows specific helper function. Returns set of ipv4 host addresses of remote established connections on local or remote tcp port. Parses output of shell 'netstat' to get connections C:\>netstat -n Active Connections Proto Local Address Foreign Address State TCP 10.2.33.17:3007 130.164.12.233:10123 ESTABLISHED TCP 10.2.33.17:3389 130.164.30.5:10378 ESTABLISHED ''' remotes = set() try: data = subprocess.check_output(['netstat', '-n']) # pylint: disable=minimum-python-version except subprocess.CalledProcessError: log.error('Failed netstat') raise lines = salt.utils.stringutils.to_str(data).split('\n') for line in lines: if 'ESTABLISHED' not in line: continue chunks = line.split() local_host, local_port = chunks[1].rsplit(':', 1) remote_host, remote_port = chunks[2].rsplit(':', 1) if which_end == 'remote_port' and int(remote_port) != port: continue if which_end == 'local_port' and int(local_port) != port: continue remotes.add(remote_host) return remotes def _linux_remotes_on(port, which_end): ''' Linux specific helper function. Returns set of ip host addresses of remote established connections on local tcp port port. Parses output of shell 'lsof' to get connections $ sudo lsof -iTCP:4505 -n COMMAND PID USER FD TYPE DEVICE SIZE/OFF NODE NAME Python 9971 root 35u IPv4 0x18a8464a29ca329d 0t0 TCP *:4505 (LISTEN) Python 9971 root 37u IPv4 0x18a8464a29b2b29d 0t0 TCP 127.0.0.1:4505->127.0.0.1:55703 (ESTABLISHED) Python 10152 root 22u IPv4 0x18a8464a29c8cab5 0t0 TCP 127.0.0.1:55703->127.0.0.1:4505 (ESTABLISHED) Python 10153 root 22u IPv4 0x18a8464a29c8cab5 0t0 TCP [fe80::249a]:4505->[fe80::150]:59367 (ESTABLISHED) ''' remotes = set() try: data = subprocess.check_output( ['lsof', '-iTCP:{0:d}'.format(port), '-n', '-P'] # pylint: disable=minimum-python-version ) except subprocess.CalledProcessError as ex: if ex.returncode == 1: # Lsof return 1 if any error was detected, including the failure # to locate Internet addresses, and it is not an error in this case. log.warning('"lsof" returncode = 1, likely no active TCP sessions.') return remotes log.error('Failed "lsof" with returncode = %s', ex.returncode) raise lines = salt.utils.stringutils.to_str(data).split('\n') for line in lines: chunks = line.split() if not chunks: continue # ['Python', '9971', 'root', '37u', 'IPv4', '0x18a8464a29b2b29d', '0t0', # 'TCP', '127.0.0.1:4505->127.0.0.1:55703', '(ESTABLISHED)'] # print chunks if 'COMMAND' in chunks[0]: continue # ignore header if 'ESTABLISHED' not in chunks[-1]: continue # ignore if not ESTABLISHED # '127.0.0.1:4505->127.0.0.1:55703' local, remote = chunks[8].split('->') _, lport = local.rsplit(':', 1) rhost, rport = remote.rsplit(':', 1) if which_end == 'remote_port' and int(rport) != port: continue if which_end == 'local_port' and int(lport) != port: continue remotes.add(rhost.strip("[]")) return remotes def _aix_remotes_on(port, which_end): ''' AIX specific helper function. Returns set of ipv4 host addresses of remote established connections on local or remote tcp port. Parses output of shell 'netstat' to get connections root@la68pp002_pub:/opt/salt/lib/python2.7/site-packages/salt/modules# netstat -f inet -n Active Internet connections Proto Recv-Q Send-Q Local Address Foreign Address (state) tcp4 0 0 172.29.149.95.50093 209.41.78.13.4505 ESTABLISHED tcp4 0 0 127.0.0.1.9514 *.* LISTEN tcp4 0 0 127.0.0.1.9515 *.* LISTEN tcp4 0 0 127.0.0.1.199 127.0.0.1.32779 ESTABLISHED tcp4 0 0 127.0.0.1.32779 127.0.0.1.199 ESTABLISHED tcp4 0 40 172.29.149.95.22 172.29.96.83.41022 ESTABLISHED tcp4 0 0 172.29.149.95.22 172.29.96.83.41032 ESTABLISHED tcp4 0 0 127.0.0.1.32771 127.0.0.1.32775 ESTABLISHED tcp 0 0 127.0.0.1.32775 127.0.0.1.32771 ESTABLISHED tcp4 0 0 127.0.0.1.32771 127.0.0.1.32776 ESTABLISHED tcp 0 0 127.0.0.1.32776 127.0.0.1.32771 ESTABLISHED tcp4 0 0 127.0.0.1.32771 127.0.0.1.32777 ESTABLISHED tcp 0 0 127.0.0.1.32777 127.0.0.1.32771 ESTABLISHED tcp4 0 0 127.0.0.1.32771 127.0.0.1.32778 ESTABLISHED tcp 0 0 127.0.0.1.32778 127.0.0.1.32771 ESTABLISHED ''' remotes = set() try: data = subprocess.check_output(['netstat', '-f', 'inet', '-n']) # pylint: disable=minimum-python-version except subprocess.CalledProcessError: log.error('Failed netstat') raise lines = salt.utils.stringutils.to_str(data).split('\n') for line in lines: if 'ESTABLISHED' not in line: continue chunks = line.split() local_host, local_port = chunks[3].rsplit('.', 1) remote_host, remote_port = chunks[4].rsplit('.', 1) if which_end == 'remote_port' and int(remote_port) != port: continue if which_end == 'local_port' and int(local_port) != port: continue remotes.add(remote_host) return remotes @jinja_filter('gen_mac') def gen_mac(prefix='AC:DE:48'): ''' Generates a MAC address with the defined OUI prefix. Common prefixes: - ``00:16:3E`` -- Xen - ``00:18:51`` -- OpenVZ - ``00:50:56`` -- VMware (manually generated) - ``52:54:00`` -- QEMU/KVM - ``AC:DE:48`` -- PRIVATE References: - http://standards.ieee.org/develop/regauth/oui/oui.txt - https://www.wireshark.org/tools/oui-lookup.html - https://en.wikipedia.org/wiki/MAC_address ''' return '{0}:{1:02X}:{2:02X}:{3:02X}'.format(prefix, random.randint(0, 0xff), random.randint(0, 0xff), random.randint(0, 0xff)) @jinja_filter('mac_str_to_bytes') def mac_str_to_bytes(mac_str): ''' Convert a MAC address string into bytes. Works with or without separators: b1 = mac_str_to_bytes('08:00:27:13:69:77') b2 = mac_str_to_bytes('080027136977') assert b1 == b2 assert isinstance(b1, bytes) ''' if len(mac_str) == 12: pass elif len(mac_str) == 17: sep = mac_str[2] mac_str = mac_str.replace(sep, '') else: raise ValueError('Invalid MAC address') chars = (int(mac_str[s:s+2], 16) for s in range(0, 12, 2)) return bytes(chars) if six.PY3 else b''.join(chr(x) for x in chars) def refresh_dns(): ''' issue #21397: force glibc to re-read resolv.conf ''' try: res_init() except NameError: # Exception raised loading the library, thus res_init is not defined pass @jinja_filter('connection_check') def connection_check(addr, port=80, safe=False, ipv6=None): ''' Provides a convenient alias for the dns_check filter. ''' return dns_check(addr, port, safe, ipv6) @jinja_filter('dns_check') def dns_check(addr, port=80, safe=False, ipv6=None, attempt_connect=True): ''' Return the ip resolved by dns, but do not exit on failure, only raise an exception. Obeys system preference for IPv4/6 address resolution - this can be overridden by the ipv6 flag. Tries to connect to the address before considering it useful. If no address can be reached, the first one resolved is used as a fallback. ''' error = False lookup = addr seen_ipv6 = False family = socket.AF_INET6 if ipv6 else socket.AF_INET if ipv6 is False else socket.AF_UNSPEC hostnames = [] try: refresh_dns() hostnames = socket.getaddrinfo(addr, port, family, socket.SOCK_STREAM) except TypeError: err = ('Attempt to resolve address \'{0}\' failed. Invalid or unresolveable address').format(lookup) raise SaltSystemExit(code=42, msg=err) except socket.error: error = True # If ipv6 is set to True, attempt another lookup using the IPv4 family, # just in case we're attempting to lookup an IPv4 IP # as an IPv6 hostname. if error and ipv6: try: refresh_dns() hostnames = socket.getaddrinfo(addr, port, socket.AF_INET, socket.SOCK_STREAM) except TypeError: err = ('Attempt to resolve address \'{0}\' failed. Invalid or unresolveable address').format(lookup) raise SaltSystemExit(code=42, msg=err) except socket.error: error = True try: if not hostnames: error = True else: resolved = False candidates = [] for h in hostnames: # Input is IP address, passed through unchanged, just return it if h[4][0] == addr: resolved = salt.utils.zeromq.ip_bracket(addr) break candidate_addr = salt.utils.zeromq.ip_bracket(h[4][0]) # sometimes /etc/hosts contains ::1 localhost if not ipv6 and candidate_addr == '[::1]': continue candidates.append(candidate_addr) if attempt_connect: try: s = socket.socket(h[0], socket.SOCK_STREAM) s.settimeout(2) s.connect((candidate_addr.strip('[]'), h[4][1])) s.close() resolved = candidate_addr break except socket.error: pass if not resolved: if candidates: resolved = candidates[0] else: error = True except TypeError: err = ('Attempt to resolve address \'{0}\' failed. Invalid or unresolveable address').format(lookup) raise SaltSystemExit(code=42, msg=err) except socket.error: error = True if error: err = ('DNS lookup or connection check of \'{0}\' failed.').format(addr) if safe: if salt.log.is_console_configured(): # If logging is not configured it also means that either # the master or minion instance calling this hasn't even # started running log.error(err) raise SaltClientError() raise SaltSystemExit(code=42, msg=err) return resolved def parse_host_port(host_port): """ Takes a string argument specifying host or host:port. Returns a (hostname, port) or (ip_address, port) tuple. If no port is given, the second (port) element of the returned tuple will be None. host:port argument, for example, is accepted in the forms of: - hostname - hostname:1234 - hostname.domain.tld - hostname.domain.tld:5678 - [1234::5]:5678 - 1234::5 - 10.11.12.13:4567 - 10.11.12.13 """ host, port = None, None # default _s_ = host_port[:] if _s_[0] == "[": if "]" in host_port: host, _s_ = _s_.lstrip("[").rsplit("]", 1) host = ipaddress.IPv6Address(host).compressed if _s_[0] == ":": port = int(_s_.lstrip(":")) else: if len(_s_) > 1: raise ValueError('found ambiguous "{}" port in "{}"'.format(_s_, host_port)) else: if _s_.count(":") == 1: host, _hostport_separator_, port = _s_.partition(":") try: port = int(port) except ValueError as _e_: log.error('host_port "%s" port value "%s" is not an integer.', host_port, port) raise _e_ else: host = _s_ try: if not isinstance(host, ipaddress._BaseAddress): host_ip = ipaddress.ip_address(host).compressed host = host_ip except ValueError: log.debug('"%s" Not an IP address? Assuming it is a hostname.', host) if host != sanitize_host(host): log.error('bad hostname: "%s"', host) raise ValueError('bad hostname: "{}"'.format(host)) return host, port def is_fqdn(hostname): """ Verify if hostname conforms to be a FQDN. :param hostname: text string with the name of the host :return: bool, True if hostname is correct FQDN, False otherwise """ compliant = re.compile(r"(?!-)[A-Z\d\-\_]{1,63}(?<!-)$", re.IGNORECASE) return "." in hostname and len(hostname) < 0xff and all(compliant.match(x) for x in hostname.rstrip(".").split("."))
saltstack/salt
salt/utils/network.py
get_net_size
python
def get_net_size(mask): ''' Turns an IPv4 netmask into it's corresponding prefix length (255.255.255.0 -> 24 as in 192.168.1.10/24). ''' binary_str = '' for octet in mask.split('.'): binary_str += bin(int(octet))[2:].zfill(8) return len(binary_str.rstrip('0'))
Turns an IPv4 netmask into it's corresponding prefix length (255.255.255.0 -> 24 as in 192.168.1.10/24).
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/network.py#L1071-L1079
null
# -*- coding: utf-8 -*- ''' Define some generic socket functions for network modules ''' # Import python libs from __future__ import absolute_import, unicode_literals, print_function import itertools import os import re import types import socket import logging import platform import random import subprocess from string import ascii_letters, digits # Import 3rd-party libs from salt.ext import six from salt.ext.six.moves import range # pylint: disable=import-error,redefined-builtin # Attempt to import wmi try: import wmi import salt.utils.winapi except ImportError: pass # Import salt libs import salt.utils.args import salt.utils.files import salt.utils.path import salt.utils.platform import salt.utils.stringutils import salt.utils.zeromq from salt._compat import ipaddress from salt.exceptions import SaltClientError, SaltSystemExit from salt.utils.decorators.jinja import jinja_filter from salt.utils.versions import LooseVersion # inet_pton does not exist in Windows, this is a workaround if salt.utils.platform.is_windows(): from salt.ext import win_inet_pton # pylint: disable=unused-import log = logging.getLogger(__name__) try: import ctypes import ctypes.util libc = ctypes.cdll.LoadLibrary(ctypes.util.find_library("c")) res_init = libc.__res_init except (ImportError, OSError, AttributeError, TypeError): pass # pylint: disable=C0103 def sanitize_host(host): ''' Sanitize host string. https://tools.ietf.org/html/rfc1123#section-2.1 ''' RFC952_characters = ascii_letters + digits + ".-" return "".join([c for c in host[0:255] if c in RFC952_characters]) def isportopen(host, port): ''' Return status of a port ''' if not 1 <= int(port) <= 65535: return False sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) out = sock.connect_ex((sanitize_host(host), int(port))) return out def host_to_ips(host): ''' Returns a list of IP addresses of a given hostname or None if not found. ''' ips = [] try: for family, socktype, proto, canonname, sockaddr in socket.getaddrinfo( host, 0, socket.AF_UNSPEC, socket.SOCK_STREAM): if family == socket.AF_INET: ip, port = sockaddr elif family == socket.AF_INET6: ip, port, flow_info, scope_id = sockaddr ips.append(ip) if not ips: ips = None except Exception: ips = None return ips def _generate_minion_id(): ''' Get list of possible host names and convention names. :return: ''' # There are three types of hostnames: # 1. Network names. How host is accessed from the network. # 2. Host aliases. They might be not available in all the network or only locally (/etc/hosts) # 3. Convention names, an internal nodename. class DistinctList(list): ''' List, which allows one to append only distinct objects. Needs to work on Python 2.6, because of collections.OrderedDict only since 2.7 version. Override 'filter()' for custom filtering. ''' localhost_matchers = [r'localhost.*', r'ip6-.*', r'127[.]\d', r'0\.0\.0\.0', r'::1.*', r'ipv6-.*', r'fe00::.*', r'fe02::.*', r'1.0.0.*.ip6.arpa'] def append(self, p_object): if p_object and p_object not in self and not self.filter(p_object): super(DistinctList, self).append(p_object) return self def extend(self, iterable): for obj in iterable: self.append(obj) return self def filter(self, element): 'Returns True if element needs to be filtered' for rgx in self.localhost_matchers: if re.match(rgx, element): return True def first(self): return self and self[0] or None hostname = socket.gethostname() hosts = DistinctList().append( salt.utils.stringutils.to_unicode(socket.getfqdn(salt.utils.stringutils.to_bytes(hostname))) ).append(platform.node()).append(hostname) if not hosts: try: for a_nfo in socket.getaddrinfo(hosts.first() or 'localhost', None, socket.AF_INET, socket.SOCK_RAW, socket.IPPROTO_IP, socket.AI_CANONNAME): if len(a_nfo) > 3: hosts.append(a_nfo[3]) except socket.gaierror: log.warning('Cannot resolve address %s info via socket: %s', hosts.first() or 'localhost (N/A)', socket.gaierror) # Universal method for everywhere (Linux, Slowlaris, Windows etc) for f_name in ('/etc/hostname', '/etc/nodename', '/etc/hosts', r'{win}\system32\drivers\etc\hosts'.format(win=os.getenv('WINDIR'))): try: with salt.utils.files.fopen(f_name) as f_hdl: for line in f_hdl: line = salt.utils.stringutils.to_unicode(line) hst = line.strip().split('#')[0].strip().split() if hst: if hst[0][:4] in ('127.', '::1') or len(hst) == 1: hosts.extend(hst) except IOError: pass # include public and private ipaddresses return hosts.extend([addr for addr in ip_addrs() if not ipaddress.ip_address(addr).is_loopback]) def generate_minion_id(): ''' Return only first element of the hostname from all possible list. :return: ''' try: ret = salt.utils.stringutils.to_unicode(_generate_minion_id().first()) except TypeError: ret = None return ret or 'localhost' def get_socket(addr, type=socket.SOCK_STREAM, proto=0): ''' Return a socket object for the addr IP-version agnostic ''' version = ipaddress.ip_address(addr).version if version == 4: family = socket.AF_INET elif version == 6: family = socket.AF_INET6 return socket.socket(family, type, proto) def get_fqhostname(): ''' Returns the fully qualified hostname ''' # try getaddrinfo() fqdn = None try: addrinfo = socket.getaddrinfo( socket.gethostname(), 0, socket.AF_UNSPEC, socket.SOCK_STREAM, socket.SOL_TCP, socket.AI_CANONNAME ) for info in addrinfo: # info struct [family, socktype, proto, canonname, sockaddr] # On Windows `canonname` can be an empty string # This can cause the function to return `None` if len(info) > 3 and info[3]: fqdn = info[3] break except socket.gaierror: pass # NOTE: this used to log.error() but it was later disabled except socket.error as err: log.debug('socket.getaddrinfo() failure while finding fqdn: %s', err) if fqdn is None: fqdn = socket.getfqdn() return fqdn def ip_to_host(ip): ''' Returns the hostname of a given IP ''' try: hostname, aliaslist, ipaddrlist = socket.gethostbyaddr(ip) except Exception as exc: log.debug('salt.utils.network.ip_to_host(%r) failed: %s', ip, exc) hostname = None return hostname # pylint: enable=C0103 def is_reachable_host(entity_name): ''' Returns a bool telling if the entity name is a reachable host (IPv4/IPv6/FQDN/etc). :param hostname: :return: ''' try: assert type(socket.getaddrinfo(entity_name, 0, 0, 0, 0)) == list ret = True except socket.gaierror: ret = False return ret def is_ip(ip): ''' Returns a bool telling if the passed IP is a valid IPv4 or IPv6 address. ''' return is_ipv4(ip) or is_ipv6(ip) def is_ipv4(ip): ''' Returns a bool telling if the value passed to it was a valid IPv4 address ''' try: return ipaddress.ip_address(ip).version == 4 except ValueError: return False def is_ipv6(ip): ''' Returns a bool telling if the value passed to it was a valid IPv6 address ''' try: return ipaddress.ip_address(ip).version == 6 except ValueError: return False def is_subnet(cidr): ''' Returns a bool telling if the passed string is an IPv4 or IPv6 subnet ''' return is_ipv4_subnet(cidr) or is_ipv6_subnet(cidr) def is_ipv4_subnet(cidr): ''' Returns a bool telling if the passed string is an IPv4 subnet ''' try: return '/' in cidr and bool(ipaddress.IPv4Network(cidr)) except Exception: return False def is_ipv6_subnet(cidr): ''' Returns a bool telling if the passed string is an IPv6 subnet ''' try: return '/' in cidr and bool(ipaddress.IPv6Network(cidr)) except Exception: return False @jinja_filter('is_ip') def is_ip_filter(ip, options=None): ''' Returns a bool telling if the passed IP is a valid IPv4 or IPv6 address. ''' return is_ipv4_filter(ip, options=options) or is_ipv6_filter(ip, options=options) def _ip_options_global(ip_obj, version): return not ip_obj.is_private def _ip_options_multicast(ip_obj, version): return ip_obj.is_multicast def _ip_options_loopback(ip_obj, version): return ip_obj.is_loopback def _ip_options_link_local(ip_obj, version): return ip_obj.is_link_local def _ip_options_private(ip_obj, version): return ip_obj.is_private def _ip_options_reserved(ip_obj, version): return ip_obj.is_reserved def _ip_options_site_local(ip_obj, version): if version == 6: return ip_obj.is_site_local return False def _ip_options_unspecified(ip_obj, version): return ip_obj.is_unspecified def _ip_options(ip_obj, version, options=None): # will process and IP options options_fun_map = { 'global': _ip_options_global, 'link-local': _ip_options_link_local, 'linklocal': _ip_options_link_local, 'll': _ip_options_link_local, 'link_local': _ip_options_link_local, 'loopback': _ip_options_loopback, 'lo': _ip_options_loopback, 'multicast': _ip_options_multicast, 'private': _ip_options_private, 'public': _ip_options_global, 'reserved': _ip_options_reserved, 'site-local': _ip_options_site_local, 'sl': _ip_options_site_local, 'site_local': _ip_options_site_local, 'unspecified': _ip_options_unspecified } if not options: return six.text_type(ip_obj) # IP version already checked options_list = [option.strip() for option in options.split(',')] for option, fun in options_fun_map.items(): if option in options_list: fun_res = fun(ip_obj, version) if not fun_res: return None # stop at first failed test # else continue return six.text_type(ip_obj) def _is_ipv(ip, version, options=None): if not version: version = 4 if version not in (4, 6): return None try: ip_obj = ipaddress.ip_address(ip) except ValueError: # maybe it is an IP network try: ip_obj = ipaddress.ip_interface(ip) except ValueError: # nope, still not :( return None if not ip_obj.version == version: return None # has the right version, let's move on return _ip_options(ip_obj, version, options=options) @jinja_filter('is_ipv4') def is_ipv4_filter(ip, options=None): ''' Returns a bool telling if the value passed to it was a valid IPv4 address. ip The IP address. net: False Consider IP addresses followed by netmask. options CSV of options regarding the nature of the IP address. E.g.: loopback, multicast, private etc. ''' _is_ipv4 = _is_ipv(ip, 4, options=options) return isinstance(_is_ipv4, six.string_types) @jinja_filter('is_ipv6') def is_ipv6_filter(ip, options=None): ''' Returns a bool telling if the value passed to it was a valid IPv6 address. ip The IP address. net: False Consider IP addresses followed by netmask. options CSV of options regarding the nature of the IP address. E.g.: loopback, multicast, private etc. ''' _is_ipv6 = _is_ipv(ip, 6, options=options) return isinstance(_is_ipv6, six.string_types) def _ipv_filter(value, version, options=None): if version not in (4, 6): return if isinstance(value, (six.string_types, six.text_type, six.binary_type)): return _is_ipv(value, version, options=options) # calls is_ipv4 or is_ipv6 for `value` elif isinstance(value, (list, tuple, types.GeneratorType)): # calls is_ipv4 or is_ipv6 for each element in the list # os it filters and returns only those elements having the desired IP version return [ _is_ipv(addr, version, options=options) for addr in value if _is_ipv(addr, version, options=options) is not None ] return None @jinja_filter('ipv4') def ipv4(value, options=None): ''' Filters a list and returns IPv4 values only. ''' return _ipv_filter(value, 4, options=options) @jinja_filter('ipv6') def ipv6(value, options=None): ''' Filters a list and returns IPv6 values only. ''' return _ipv_filter(value, 6, options=options) @jinja_filter('ipaddr') def ipaddr(value, options=None): ''' Filters and returns only valid IP objects. ''' ipv4_obj = ipv4(value, options=options) ipv6_obj = ipv6(value, options=options) if ipv4_obj is None or ipv6_obj is None: # an IP address can be either IPv4 either IPv6 # therefofe if the value passed as arg is not a list, at least one of the calls above will return None # if one of them is none, means that we should return only one of them return ipv4_obj or ipv6_obj # one of them else: return ipv4_obj + ipv6_obj # extend lists def _filter_ipaddr(value, options, version=None): ipaddr_filter_out = None if version: if version == 4: ipaddr_filter_out = ipv4(value, options) elif version == 6: ipaddr_filter_out = ipv6(value, options) else: ipaddr_filter_out = ipaddr(value, options) if not ipaddr_filter_out: return if not isinstance(ipaddr_filter_out, (list, tuple, types.GeneratorType)): ipaddr_filter_out = [ipaddr_filter_out] return ipaddr_filter_out @jinja_filter('ip_host') def ip_host(value, options=None, version=None): ''' Returns the interfaces IP address, e.g.: 192.168.0.1/28. ''' ipaddr_filter_out = _filter_ipaddr(value, options=options, version=version) if not ipaddr_filter_out: return if not isinstance(value, (list, tuple, types.GeneratorType)): return six.text_type(ipaddress.ip_interface(ipaddr_filter_out[0])) return [six.text_type(ipaddress.ip_interface(ip_a)) for ip_a in ipaddr_filter_out] def _network_hosts(ip_addr_entry): return [ six.text_type(host) for host in ipaddress.ip_network(ip_addr_entry, strict=False).hosts() ] @jinja_filter('network_hosts') def network_hosts(value, options=None, version=None): ''' Return the list of hosts within a network. .. note:: When running this command with a large IPv6 network, the command will take a long time to gather all of the hosts. ''' ipaddr_filter_out = _filter_ipaddr(value, options=options, version=version) if not ipaddr_filter_out: return if not isinstance(value, (list, tuple, types.GeneratorType)): return _network_hosts(ipaddr_filter_out[0]) return [ _network_hosts(ip_a) for ip_a in ipaddr_filter_out ] def _network_size(ip_addr_entry): return ipaddress.ip_network(ip_addr_entry, strict=False).num_addresses @jinja_filter('network_size') def network_size(value, options=None, version=None): ''' Get the size of a network. ''' ipaddr_filter_out = _filter_ipaddr(value, options=options, version=version) if not ipaddr_filter_out: return if not isinstance(value, (list, tuple, types.GeneratorType)): return _network_size(ipaddr_filter_out[0]) return [ _network_size(ip_a) for ip_a in ipaddr_filter_out ] def natural_ipv4_netmask(ip, fmt='prefixlen'): ''' Returns the "natural" mask of an IPv4 address ''' bits = _ipv4_to_bits(ip) if bits.startswith('11'): mask = '24' elif bits.startswith('1'): mask = '16' else: mask = '8' if fmt == 'netmask': return cidr_to_ipv4_netmask(mask) else: return '/' + mask def rpad_ipv4_network(ip): ''' Returns an IP network address padded with zeros. Ex: '192.168.3' -> '192.168.3.0' '10.209' -> '10.209.0.0' ''' return '.'.join(itertools.islice(itertools.chain(ip.split('.'), '0000'), 0, 4)) def cidr_to_ipv4_netmask(cidr_bits): ''' Returns an IPv4 netmask ''' try: cidr_bits = int(cidr_bits) if not 1 <= cidr_bits <= 32: return '' except ValueError: return '' netmask = '' for idx in range(4): if idx: netmask += '.' if cidr_bits >= 8: netmask += '255' cidr_bits -= 8 else: netmask += '{0:d}'.format(256 - (2 ** (8 - cidr_bits))) cidr_bits = 0 return netmask def _number_of_set_bits_to_ipv4_netmask(set_bits): # pylint: disable=C0103 ''' Returns an IPv4 netmask from the integer representation of that mask. Ex. 0xffffff00 -> '255.255.255.0' ''' return cidr_to_ipv4_netmask(_number_of_set_bits(set_bits)) # pylint: disable=C0103 def _number_of_set_bits(x): ''' Returns the number of bits that are set in a 32bit int ''' # Taken from http://stackoverflow.com/a/4912729. Many thanks! x -= (x >> 1) & 0x55555555 x = ((x >> 2) & 0x33333333) + (x & 0x33333333) x = ((x >> 4) + x) & 0x0f0f0f0f x += x >> 8 x += x >> 16 return x & 0x0000003f # pylint: enable=C0103 def _interfaces_ip(out): ''' Uses ip to return a dictionary of interfaces with various information about each (up/down state, ip address, netmask, and hwaddr) ''' ret = dict() def parse_network(value, cols): ''' Return a tuple of ip, netmask, broadcast based on the current set of cols ''' brd = None scope = None if '/' in value: # we have a CIDR in this address ip, cidr = value.split('/') # pylint: disable=C0103 else: ip = value # pylint: disable=C0103 cidr = 32 if type_ == 'inet': mask = cidr_to_ipv4_netmask(int(cidr)) if 'brd' in cols: brd = cols[cols.index('brd') + 1] elif type_ == 'inet6': mask = cidr if 'scope' in cols: scope = cols[cols.index('scope') + 1] return (ip, mask, brd, scope) groups = re.compile('\r?\n\\d').split(out) for group in groups: iface = None data = dict() for line in group.splitlines(): if ' ' not in line: continue match = re.match(r'^\d*:\s+([\w.\-]+)(?:@)?([\w.\-]+)?:\s+<(.+)>', line) if match: iface, parent, attrs = match.groups() if 'UP' in attrs.split(','): data['up'] = True else: data['up'] = False if parent: data['parent'] = parent continue cols = line.split() if len(cols) >= 2: type_, value = tuple(cols[0:2]) iflabel = cols[-1:][0] if type_ in ('inet', 'inet6'): if 'secondary' not in cols: ipaddr, netmask, broadcast, scope = parse_network(value, cols) if type_ == 'inet': if 'inet' not in data: data['inet'] = list() addr_obj = dict() addr_obj['address'] = ipaddr addr_obj['netmask'] = netmask addr_obj['broadcast'] = broadcast addr_obj['label'] = iflabel data['inet'].append(addr_obj) elif type_ == 'inet6': if 'inet6' not in data: data['inet6'] = list() addr_obj = dict() addr_obj['address'] = ipaddr addr_obj['prefixlen'] = netmask addr_obj['scope'] = scope data['inet6'].append(addr_obj) else: if 'secondary' not in data: data['secondary'] = list() ip_, mask, brd, scp = parse_network(value, cols) data['secondary'].append({ 'type': type_, 'address': ip_, 'netmask': mask, 'broadcast': brd, 'label': iflabel, }) del ip_, mask, brd, scp elif type_.startswith('link'): data['hwaddr'] = value if iface: ret[iface] = data del iface, data return ret def _interfaces_ifconfig(out): ''' Uses ifconfig to return a dictionary of interfaces with various information about each (up/down state, ip address, netmask, and hwaddr) ''' ret = dict() piface = re.compile(r'^([^\s:]+)') pmac = re.compile('.*?(?:HWaddr|ether|address:|lladdr) ([0-9a-fA-F:]+)') if salt.utils.platform.is_sunos(): pip = re.compile(r'.*?(?:inet\s+)([0-9]+\.[0-9]+\.[0-9]+\.[0-9]+)(.*)') pip6 = re.compile('.*?(?:inet6 )([0-9a-fA-F:]+)') pmask6 = re.compile(r'.*?(?:inet6 [0-9a-fA-F:]+/(\d+)).*') else: pip = re.compile(r'.*?(?:inet addr:|inet [^\d]*)(.*?)\s') pip6 = re.compile('.*?(?:inet6 addr: (.*?)/|inet6 )([0-9a-fA-F:]+)') pmask6 = re.compile(r'.*?(?:inet6 addr: [0-9a-fA-F:]+/(\d+)|prefixlen (\d+))(?: Scope:([a-zA-Z]+)| scopeid (0x[0-9a-fA-F]))?') pmask = re.compile(r'.*?(?:Mask:|netmask )(?:((?:0x)?[0-9a-fA-F]{8})|([\d\.]+))') pupdown = re.compile('UP') pbcast = re.compile(r'.*?(?:Bcast:|broadcast )([\d\.]+)') groups = re.compile('\r?\n(?=\\S)').split(out) for group in groups: data = dict() iface = '' updown = False for line in group.splitlines(): miface = piface.match(line) mmac = pmac.match(line) mip = pip.match(line) mip6 = pip6.match(line) mupdown = pupdown.search(line) if miface: iface = miface.group(1) if mmac: data['hwaddr'] = mmac.group(1) if salt.utils.platform.is_sunos(): expand_mac = [] for chunk in data['hwaddr'].split(':'): expand_mac.append('0{0}'.format(chunk) if len(chunk) < 2 else '{0}'.format(chunk)) data['hwaddr'] = ':'.join(expand_mac) if mip: if 'inet' not in data: data['inet'] = list() addr_obj = dict() addr_obj['address'] = mip.group(1) mmask = pmask.match(line) if mmask: if mmask.group(1): mmask = _number_of_set_bits_to_ipv4_netmask( int(mmask.group(1), 16)) else: mmask = mmask.group(2) addr_obj['netmask'] = mmask mbcast = pbcast.match(line) if mbcast: addr_obj['broadcast'] = mbcast.group(1) data['inet'].append(addr_obj) if mupdown: updown = True if mip6: if 'inet6' not in data: data['inet6'] = list() addr_obj = dict() addr_obj['address'] = mip6.group(1) or mip6.group(2) mmask6 = pmask6.match(line) if mmask6: addr_obj['prefixlen'] = mmask6.group(1) or mmask6.group(2) if not salt.utils.platform.is_sunos(): ipv6scope = mmask6.group(3) or mmask6.group(4) addr_obj['scope'] = ipv6scope.lower() if ipv6scope is not None else ipv6scope # SunOS sometimes has ::/0 as inet6 addr when using addrconf if not salt.utils.platform.is_sunos() \ or addr_obj['address'] != '::' \ and addr_obj['prefixlen'] != 0: data['inet6'].append(addr_obj) data['up'] = updown if iface in ret: # SunOS optimization, where interfaces occur twice in 'ifconfig -a' # output with the same name: for ipv4 and then for ipv6 addr family. # Every instance has it's own 'UP' status and we assume that ipv4 # status determines global interface status. # # merge items with higher priority for older values # after that merge the inet and inet6 sub items for both ret[iface] = dict(list(data.items()) + list(ret[iface].items())) if 'inet' in data: ret[iface]['inet'].extend(x for x in data['inet'] if x not in ret[iface]['inet']) if 'inet6' in data: ret[iface]['inet6'].extend(x for x in data['inet6'] if x not in ret[iface]['inet6']) else: ret[iface] = data del data return ret def linux_interfaces(): ''' Obtain interface information for *NIX/BSD variants ''' ifaces = dict() ip_path = salt.utils.path.which('ip') ifconfig_path = None if ip_path else salt.utils.path.which('ifconfig') if ip_path: cmd1 = subprocess.Popen( '{0} link show'.format(ip_path), shell=True, close_fds=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT).communicate()[0] cmd2 = subprocess.Popen( '{0} addr show'.format(ip_path), shell=True, close_fds=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT).communicate()[0] ifaces = _interfaces_ip("{0}\n{1}".format( salt.utils.stringutils.to_str(cmd1), salt.utils.stringutils.to_str(cmd2))) elif ifconfig_path: cmd = subprocess.Popen( '{0} -a'.format(ifconfig_path), shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT).communicate()[0] ifaces = _interfaces_ifconfig(salt.utils.stringutils.to_str(cmd)) return ifaces def _netbsd_interfaces_ifconfig(out): ''' Uses ifconfig to return a dictionary of interfaces with various information about each (up/down state, ip address, netmask, and hwaddr) ''' ret = dict() piface = re.compile(r'^([^\s:]+)') pmac = re.compile('.*?address: ([0-9a-f:]+)') pip = re.compile(r'.*?inet [^\d]*(.*?)/([\d]*)\s') pip6 = re.compile(r'.*?inet6 ([0-9a-f:]+)%([a-zA-Z0-9]*)/([\d]*)\s') pupdown = re.compile('UP') pbcast = re.compile(r'.*?broadcast ([\d\.]+)') groups = re.compile('\r?\n(?=\\S)').split(out) for group in groups: data = dict() iface = '' updown = False for line in group.splitlines(): miface = piface.match(line) mmac = pmac.match(line) mip = pip.match(line) mip6 = pip6.match(line) mupdown = pupdown.search(line) if miface: iface = miface.group(1) if mmac: data['hwaddr'] = mmac.group(1) if mip: if 'inet' not in data: data['inet'] = list() addr_obj = dict() addr_obj['address'] = mip.group(1) mmask = mip.group(2) if mip.group(2): addr_obj['netmask'] = cidr_to_ipv4_netmask(mip.group(2)) mbcast = pbcast.match(line) if mbcast: addr_obj['broadcast'] = mbcast.group(1) data['inet'].append(addr_obj) if mupdown: updown = True if mip6: if 'inet6' not in data: data['inet6'] = list() addr_obj = dict() addr_obj['address'] = mip6.group(1) mmask6 = mip6.group(3) addr_obj['scope'] = mip6.group(2) addr_obj['prefixlen'] = mip6.group(3) data['inet6'].append(addr_obj) data['up'] = updown ret[iface] = data del data return ret def netbsd_interfaces(): ''' Obtain interface information for NetBSD >= 8 where the ifconfig output diverged from other BSD variants (Netmask is now part of the address) ''' # NetBSD versions prior to 8.0 can still use linux_interfaces() if LooseVersion(os.uname()[2]) < LooseVersion('8.0'): return linux_interfaces() ifconfig_path = salt.utils.path.which('ifconfig') cmd = subprocess.Popen( '{0} -a'.format(ifconfig_path), shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT).communicate()[0] return _netbsd_interfaces_ifconfig(salt.utils.stringutils.to_str(cmd)) def _interfaces_ipconfig(out): ''' Returns a dictionary of interfaces with various information about each (up/down state, ip address, netmask, and hwaddr) NOTE: This is not used by any function and may be able to be removed in the future. ''' ifaces = dict() iface = None adapter_iface_regex = re.compile(r'adapter (\S.+):$') for line in out.splitlines(): if not line: continue # TODO what does Windows call Infiniband and 10/40gige adapters if line.startswith('Ethernet'): iface = ifaces[adapter_iface_regex.search(line).group(1)] iface['up'] = True addr = None continue if iface: key, val = line.split(',', 1) key = key.strip(' .') val = val.strip() if addr and key == 'Subnet Mask': addr['netmask'] = val elif key in ('IP Address', 'IPv4 Address'): if 'inet' not in iface: iface['inet'] = list() addr = {'address': val.rstrip('(Preferred)'), 'netmask': None, 'broadcast': None} # TODO find the broadcast iface['inet'].append(addr) elif 'IPv6 Address' in key: if 'inet6' not in iface: iface['inet'] = list() # XXX What is the prefixlen!? addr = {'address': val.rstrip('(Preferred)'), 'prefixlen': None} iface['inet6'].append(addr) elif key == 'Physical Address': iface['hwaddr'] = val elif key == 'Media State': # XXX seen used for tunnel adaptors # might be useful iface['up'] = (val != 'Media disconnected') def win_interfaces(): ''' Obtain interface information for Windows systems ''' with salt.utils.winapi.Com(): c = wmi.WMI() ifaces = {} for iface in c.Win32_NetworkAdapterConfiguration(IPEnabled=1): ifaces[iface.Description] = dict() if iface.MACAddress: ifaces[iface.Description]['hwaddr'] = iface.MACAddress if iface.IPEnabled: ifaces[iface.Description]['up'] = True for ip in iface.IPAddress: if '.' in ip: if 'inet' not in ifaces[iface.Description]: ifaces[iface.Description]['inet'] = [] item = {'address': ip, 'label': iface.Description} if iface.DefaultIPGateway: broadcast = next((i for i in iface.DefaultIPGateway if '.' in i), '') if broadcast: item['broadcast'] = broadcast if iface.IPSubnet: netmask = next((i for i in iface.IPSubnet if '.' in i), '') if netmask: item['netmask'] = netmask ifaces[iface.Description]['inet'].append(item) if ':' in ip: if 'inet6' not in ifaces[iface.Description]: ifaces[iface.Description]['inet6'] = [] item = {'address': ip} if iface.DefaultIPGateway: broadcast = next((i for i in iface.DefaultIPGateway if ':' in i), '') if broadcast: item['broadcast'] = broadcast if iface.IPSubnet: netmask = next((i for i in iface.IPSubnet if ':' in i), '') if netmask: item['netmask'] = netmask ifaces[iface.Description]['inet6'].append(item) else: ifaces[iface.Description]['up'] = False return ifaces def interfaces(): ''' Return a dictionary of information about all the interfaces on the minion ''' if salt.utils.platform.is_windows(): return win_interfaces() elif salt.utils.platform.is_netbsd(): return netbsd_interfaces() else: return linux_interfaces() def get_net_start(ipaddr, netmask): ''' Return the address of the network ''' net = ipaddress.ip_network('{0}/{1}'.format(ipaddr, netmask), strict=False) return six.text_type(net.network_address) def calc_net(ipaddr, netmask=None): ''' Takes IP (CIDR notation supported) and optionally netmask and returns the network in CIDR-notation. (The IP can be any IP inside the subnet) ''' if netmask is not None: ipaddr = '{0}/{1}'.format(ipaddr, netmask) return six.text_type(ipaddress.ip_network(ipaddr, strict=False)) def _ipv4_to_bits(ipaddr): ''' Accepts an IPv4 dotted quad and returns a string representing its binary counterpart ''' return ''.join([bin(int(x))[2:].rjust(8, '0') for x in ipaddr.split('.')]) def _get_iface_info(iface): ''' If `iface` is available, return interface info and no error, otherwise return no info and log and return an error ''' iface_info = interfaces() if iface in iface_info.keys(): return iface_info, False else: error_msg = ('Interface "{0}" not in available interfaces: "{1}"' ''.format(iface, '", "'.join(iface_info.keys()))) log.error(error_msg) return None, error_msg def _hw_addr_aix(iface): ''' Return the hardware address (a.k.a. MAC address) for a given interface on AIX MAC address not available in through interfaces ''' cmd = subprocess.Popen( 'entstat -d {0} | grep \'Hardware Address\''.format(iface), shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT).communicate()[0] if cmd: comps = cmd.split(' ') if len(comps) == 3: mac_addr = comps[2].strip('\'').strip() return mac_addr error_msg = ('Interface "{0}" either not available or does not contain a hardware address'.format(iface)) log.error(error_msg) return error_msg def hw_addr(iface): ''' Return the hardware address (a.k.a. MAC address) for a given interface .. versionchanged:: 2016.11.4 Added support for AIX ''' if salt.utils.platform.is_aix(): return _hw_addr_aix iface_info, error = _get_iface_info(iface) if error is False: return iface_info.get(iface, {}).get('hwaddr', '') else: return error def interface(iface): ''' Return the details of `iface` or an error if it does not exist ''' iface_info, error = _get_iface_info(iface) if error is False: return iface_info.get(iface, {}).get('inet', '') else: return error def interface_ip(iface): ''' Return `iface` IPv4 addr or an error if `iface` does not exist ''' iface_info, error = _get_iface_info(iface) if error is False: inet = iface_info.get(iface, {}).get('inet', None) return inet[0].get('address', '') if inet else '' else: return error def _subnets(proto='inet', interfaces_=None): ''' Returns a list of subnets to which the host belongs ''' if interfaces_ is None: ifaces = interfaces() elif isinstance(interfaces_, list): ifaces = {} for key, value in six.iteritems(interfaces()): if key in interfaces_: ifaces[key] = value else: ifaces = {interfaces_: interfaces().get(interfaces_, {})} ret = set() if proto == 'inet': subnet = 'netmask' dflt_cidr = 32 elif proto == 'inet6': subnet = 'prefixlen' dflt_cidr = 128 else: log.error('Invalid proto %s calling subnets()', proto) return for ip_info in six.itervalues(ifaces): addrs = ip_info.get(proto, []) addrs.extend([addr for addr in ip_info.get('secondary', []) if addr.get('type') == proto]) for intf in addrs: if subnet in intf: intf = ipaddress.ip_interface('{0}/{1}'.format(intf['address'], intf[subnet])) else: intf = ipaddress.ip_interface('{0}/{1}'.format(intf['address'], dflt_cidr)) if not intf.is_loopback: ret.add(intf.network) return [six.text_type(net) for net in sorted(ret)] def subnets(interfaces=None): ''' Returns a list of IPv4 subnets to which the host belongs ''' return _subnets('inet', interfaces_=interfaces) def subnets6(): ''' Returns a list of IPv6 subnets to which the host belongs ''' return _subnets('inet6') def in_subnet(cidr, addr=None): ''' Returns True if host or (any of) addrs is within specified subnet, otherwise False ''' try: cidr = ipaddress.ip_network(cidr) except ValueError: log.error('Invalid CIDR \'%s\'', cidr) return False if addr is None: addr = ip_addrs() addr.extend(ip_addrs6()) elif not isinstance(addr, (list, tuple)): addr = (addr,) return any(ipaddress.ip_address(item) in cidr for item in addr) def _ip_addrs(interface=None, include_loopback=False, interface_data=None, proto='inet'): ''' Return the full list of IP adresses matching the criteria proto = inet|inet6 ''' ret = set() ifaces = interface_data \ if isinstance(interface_data, dict) \ else interfaces() if interface is None: target_ifaces = ifaces else: target_ifaces = dict([(k, v) for k, v in six.iteritems(ifaces) if k == interface]) if not target_ifaces: log.error('Interface %s not found.', interface) for ip_info in six.itervalues(target_ifaces): addrs = ip_info.get(proto, []) addrs.extend([addr for addr in ip_info.get('secondary', []) if addr.get('type') == proto]) for addr in addrs: addr = ipaddress.ip_address(addr.get('address')) if not addr.is_loopback or include_loopback: ret.add(addr) return [six.text_type(addr) for addr in sorted(ret)] def ip_addrs(interface=None, include_loopback=False, interface_data=None): ''' Returns a list of IPv4 addresses assigned to the host. 127.0.0.1 is ignored, unless 'include_loopback=True' is indicated. If 'interface' is provided, then only IP addresses from that interface will be returned. ''' return _ip_addrs(interface, include_loopback, interface_data, 'inet') def ip_addrs6(interface=None, include_loopback=False, interface_data=None): ''' Returns a list of IPv6 addresses assigned to the host. ::1 is ignored, unless 'include_loopback=True' is indicated. If 'interface' is provided, then only IP addresses from that interface will be returned. ''' return _ip_addrs(interface, include_loopback, interface_data, 'inet6') def hex2ip(hex_ip, invert=False): ''' Convert a hex string to an ip, if a failure occurs the original hex is returned. If 'invert=True' assume that ip from /proc/net/<proto> ''' if len(hex_ip) == 32: # ipv6 ip = [] for i in range(0, 32, 8): ip_part = hex_ip[i:i + 8] ip_part = [ip_part[x:x + 2] for x in range(0, 8, 2)] if invert: ip.append("{0[3]}{0[2]}:{0[1]}{0[0]}".format(ip_part)) else: ip.append("{0[0]}{0[1]}:{0[2]}{0[3]}".format(ip_part)) try: address = ipaddress.IPv6Address(":".join(ip)) if address.ipv4_mapped: return str(address.ipv4_mapped) else: return address.compressed except ipaddress.AddressValueError as ex: log.error('hex2ip - ipv6 address error: %s', ex) return hex_ip try: hip = int(hex_ip, 16) except ValueError: return hex_ip if invert: return '{3}.{2}.{1}.{0}'.format(hip >> 24 & 255, hip >> 16 & 255, hip >> 8 & 255, hip & 255) return '{0}.{1}.{2}.{3}'.format(hip >> 24 & 255, hip >> 16 & 255, hip >> 8 & 255, hip & 255) def mac2eui64(mac, prefix=None): ''' Convert a MAC address to a EUI64 identifier or, with prefix provided, a full IPv6 address ''' # http://tools.ietf.org/html/rfc4291#section-2.5.1 eui64 = re.sub(r'[.:-]', '', mac).lower() eui64 = eui64[0:6] + 'fffe' + eui64[6:] eui64 = hex(int(eui64[0:2], 16) | 2)[2:].zfill(2) + eui64[2:] if prefix is None: return ':'.join(re.findall(r'.{4}', eui64)) else: try: net = ipaddress.ip_network(prefix, strict=False) euil = int('0x{0}'.format(eui64), 16) return '{0}/{1}'.format(net[euil], net.prefixlen) except Exception: return def active_tcp(): ''' Return a dict describing all active tcp connections as quickly as possible ''' ret = {} for statf in ['/proc/net/tcp', '/proc/net/tcp6']: if os.path.isfile(statf): with salt.utils.files.fopen(statf, 'rb') as fp_: for line in fp_: line = salt.utils.stringutils.to_unicode(line) if line.strip().startswith('sl'): continue iret = _parse_tcp_line(line) sl = next(iter(iret)) if iret[sl]['state'] == 1: # 1 is ESTABLISHED del iret[sl]['state'] ret[len(ret)] = iret[sl] return ret def local_port_tcp(port): ''' Return a set of remote ip addrs attached to the specified local port ''' ret = _remotes_on(port, 'local_port') return ret def remote_port_tcp(port): ''' Return a set of ip addrs the current host is connected to on given port ''' ret = _remotes_on(port, 'remote_port') return ret def _remotes_on(port, which_end): ''' Return a set of ip addrs active tcp connections ''' port = int(port) ret = _netlink_tool_remote_on(port, which_end) if ret is not None: return ret ret = set() proc_available = False for statf in ['/proc/net/tcp', '/proc/net/tcp6']: if os.path.isfile(statf): proc_available = True with salt.utils.files.fopen(statf, 'r') as fp_: for line in fp_: line = salt.utils.stringutils.to_unicode(line) if line.strip().startswith('sl'): continue iret = _parse_tcp_line(line) sl = next(iter(iret)) if iret[sl][which_end] == port and iret[sl]['state'] == 1: # 1 is ESTABLISHED ret.add(iret[sl]['remote_addr']) if not proc_available: # Fallback to use OS specific tools if salt.utils.platform.is_sunos(): return _sunos_remotes_on(port, which_end) if salt.utils.platform.is_freebsd(): return _freebsd_remotes_on(port, which_end) if salt.utils.platform.is_netbsd(): return _netbsd_remotes_on(port, which_end) if salt.utils.platform.is_openbsd(): return _openbsd_remotes_on(port, which_end) if salt.utils.platform.is_windows(): return _windows_remotes_on(port, which_end) if salt.utils.platform.is_aix(): return _aix_remotes_on(port, which_end) return _linux_remotes_on(port, which_end) return ret def _parse_tcp_line(line): ''' Parse a single line from the contents of /proc/net/tcp or /proc/net/tcp6 ''' ret = {} comps = line.strip().split() sl = comps[0].rstrip(':') ret[sl] = {} l_addr, l_port = comps[1].split(':') r_addr, r_port = comps[2].split(':') ret[sl]['local_addr'] = hex2ip(l_addr, True) ret[sl]['local_port'] = int(l_port, 16) ret[sl]['remote_addr'] = hex2ip(r_addr, True) ret[sl]['remote_port'] = int(r_port, 16) ret[sl]['state'] = int(comps[3], 16) return ret def _netlink_tool_remote_on(port, which_end): ''' Returns set of ipv4 host addresses of remote established connections on local or remote tcp port. Parses output of shell 'ss' to get connections [root@salt-master ~]# ss -ant State Recv-Q Send-Q Local Address:Port Peer Address:Port LISTEN 0 511 *:80 *:* LISTEN 0 128 *:22 *:* ESTAB 0 0 127.0.0.1:56726 127.0.0.1:4505 ''' remotes = set() valid = False try: data = subprocess.check_output(['ss', '-ant']) # pylint: disable=minimum-python-version except subprocess.CalledProcessError: log.error('Failed ss') raise except OSError: # not command "No such file or directory" return None lines = salt.utils.stringutils.to_str(data).split('\n') for line in lines: if 'Address:Port' in line: # ss tools may not be valid valid = True continue elif 'ESTAB' not in line: continue chunks = line.split() local_host, local_port = chunks[3].split(':', 1) remote_host, remote_port = chunks[4].split(':', 1) if which_end == 'remote_port' and int(remote_port) != port: continue if which_end == 'local_port' and int(local_port) != port: continue remotes.add(remote_host) if valid is False: remotes = None return remotes def _sunos_remotes_on(port, which_end): ''' SunOS specific helper function. Returns set of ipv4 host addresses of remote established connections on local or remote tcp port. Parses output of shell 'netstat' to get connections [root@salt-master ~]# netstat -f inet -n TCP: IPv4 Local Address Remote Address Swind Send-Q Rwind Recv-Q State -------------------- -------------------- ----- ------ ----- ------ ----------- 10.0.0.101.4505 10.0.0.1.45329 1064800 0 1055864 0 ESTABLISHED 10.0.0.101.4505 10.0.0.100.50798 1064800 0 1055864 0 ESTABLISHED ''' remotes = set() try: data = subprocess.check_output(['netstat', '-f', 'inet', '-n']) # pylint: disable=minimum-python-version except subprocess.CalledProcessError: log.error('Failed netstat') raise lines = salt.utils.stringutils.to_str(data).split('\n') for line in lines: if 'ESTABLISHED' not in line: continue chunks = line.split() local_host, local_port = chunks[0].rsplit('.', 1) remote_host, remote_port = chunks[1].rsplit('.', 1) if which_end == 'remote_port' and int(remote_port) != port: continue if which_end == 'local_port' and int(local_port) != port: continue remotes.add(remote_host) return remotes def _freebsd_remotes_on(port, which_end): ''' Returns set of ipv4 host addresses of remote established connections on local tcp port port. Parses output of shell 'sockstat' (FreeBSD) to get connections $ sudo sockstat -4 USER COMMAND PID FD PROTO LOCAL ADDRESS FOREIGN ADDRESS root python2.7 1456 29 tcp4 *:4505 *:* root python2.7 1445 17 tcp4 *:4506 *:* root python2.7 1294 14 tcp4 127.0.0.1:11813 127.0.0.1:4505 root python2.7 1294 41 tcp4 127.0.0.1:61115 127.0.0.1:4506 $ sudo sockstat -4 -c -p 4506 USER COMMAND PID FD PROTO LOCAL ADDRESS FOREIGN ADDRESS root python2.7 1294 41 tcp4 127.0.0.1:61115 127.0.0.1:4506 ''' port = int(port) remotes = set() try: cmd = salt.utils.args.shlex_split('sockstat -4 -c -p {0}'.format(port)) data = subprocess.check_output(cmd) # pylint: disable=minimum-python-version except subprocess.CalledProcessError as ex: log.error('Failed "sockstat" with returncode = %s', ex.returncode) raise lines = salt.utils.stringutils.to_str(data).split('\n') for line in lines: chunks = line.split() if not chunks: continue # ['root', 'python2.7', '1456', '37', 'tcp4', # '127.0.0.1:4505-', '127.0.0.1:55703'] # print chunks if 'COMMAND' in chunks[1]: continue # ignore header if len(chunks) < 2: continue # sockstat -4 -c -p 4506 does this with high PIDs: # USER COMMAND PID FD PROTO LOCAL ADDRESS FOREIGN ADDRESS # salt-master python2.781106 35 tcp4 192.168.12.34:4506 192.168.12.45:60143 local = chunks[-2] remote = chunks[-1] lhost, lport = local.split(':') rhost, rport = remote.split(':') if which_end == 'local' and int(lport) != port: # ignore if local port not port continue if which_end == 'remote' and int(rport) != port: # ignore if remote port not port continue remotes.add(rhost) return remotes def _netbsd_remotes_on(port, which_end): ''' Returns set of ipv4 host addresses of remote established connections on local tcp port port. Parses output of shell 'sockstat' (NetBSD) to get connections $ sudo sockstat -4 -n USER COMMAND PID FD PROTO LOCAL ADDRESS FOREIGN ADDRESS root python2.7 1456 29 tcp *.4505 *.* root python2.7 1445 17 tcp *.4506 *.* root python2.7 1294 14 tcp 127.0.0.1.11813 127.0.0.1.4505 root python2.7 1294 41 tcp 127.0.0.1.61115 127.0.0.1.4506 $ sudo sockstat -4 -c -n -p 4506 USER COMMAND PID FD PROTO LOCAL ADDRESS FOREIGN ADDRESS root python2.7 1294 41 tcp 127.0.0.1.61115 127.0.0.1.4506 ''' port = int(port) remotes = set() try: cmd = salt.utils.args.shlex_split('sockstat -4 -c -n -p {0}'.format(port)) data = subprocess.check_output(cmd) # pylint: disable=minimum-python-version except subprocess.CalledProcessError as ex: log.error('Failed "sockstat" with returncode = %s', ex.returncode) raise lines = salt.utils.stringutils.to_str(data).split('\n') for line in lines: chunks = line.split() if not chunks: continue # ['root', 'python2.7', '1456', '37', 'tcp', # '127.0.0.1.4505-', '127.0.0.1.55703'] # print chunks if 'COMMAND' in chunks[1]: continue # ignore header if len(chunks) < 2: continue local = chunks[5].split('.') lport = local.pop() lhost = '.'.join(local) remote = chunks[6].split('.') rport = remote.pop() rhost = '.'.join(remote) if which_end == 'local' and int(lport) != port: # ignore if local port not port continue if which_end == 'remote' and int(rport) != port: # ignore if remote port not port continue remotes.add(rhost) return remotes def _openbsd_remotes_on(port, which_end): ''' OpenBSD specific helper function. Returns set of ipv4 host addresses of remote established connections on local or remote tcp port. Parses output of shell 'netstat' to get connections $ netstat -nf inet Active Internet connections Proto Recv-Q Send-Q Local Address Foreign Address (state) tcp 0 0 10.0.0.101.4505 10.0.0.1.45329 ESTABLISHED tcp 0 0 10.0.0.101.4505 10.0.0.100.50798 ESTABLISHED ''' remotes = set() try: data = subprocess.check_output(['netstat', '-nf', 'inet']) # pylint: disable=minimum-python-version except subprocess.CalledProcessError: log.error('Failed netstat') raise lines = data.split('\n') for line in lines: if 'ESTABLISHED' not in line: continue chunks = line.split() local_host, local_port = chunks[3].rsplit('.', 1) remote_host, remote_port = chunks[4].rsplit('.', 1) if which_end == 'remote_port' and int(remote_port) != port: continue if which_end == 'local_port' and int(local_port) != port: continue remotes.add(remote_host) return remotes def _windows_remotes_on(port, which_end): r''' Windows specific helper function. Returns set of ipv4 host addresses of remote established connections on local or remote tcp port. Parses output of shell 'netstat' to get connections C:\>netstat -n Active Connections Proto Local Address Foreign Address State TCP 10.2.33.17:3007 130.164.12.233:10123 ESTABLISHED TCP 10.2.33.17:3389 130.164.30.5:10378 ESTABLISHED ''' remotes = set() try: data = subprocess.check_output(['netstat', '-n']) # pylint: disable=minimum-python-version except subprocess.CalledProcessError: log.error('Failed netstat') raise lines = salt.utils.stringutils.to_str(data).split('\n') for line in lines: if 'ESTABLISHED' not in line: continue chunks = line.split() local_host, local_port = chunks[1].rsplit(':', 1) remote_host, remote_port = chunks[2].rsplit(':', 1) if which_end == 'remote_port' and int(remote_port) != port: continue if which_end == 'local_port' and int(local_port) != port: continue remotes.add(remote_host) return remotes def _linux_remotes_on(port, which_end): ''' Linux specific helper function. Returns set of ip host addresses of remote established connections on local tcp port port. Parses output of shell 'lsof' to get connections $ sudo lsof -iTCP:4505 -n COMMAND PID USER FD TYPE DEVICE SIZE/OFF NODE NAME Python 9971 root 35u IPv4 0x18a8464a29ca329d 0t0 TCP *:4505 (LISTEN) Python 9971 root 37u IPv4 0x18a8464a29b2b29d 0t0 TCP 127.0.0.1:4505->127.0.0.1:55703 (ESTABLISHED) Python 10152 root 22u IPv4 0x18a8464a29c8cab5 0t0 TCP 127.0.0.1:55703->127.0.0.1:4505 (ESTABLISHED) Python 10153 root 22u IPv4 0x18a8464a29c8cab5 0t0 TCP [fe80::249a]:4505->[fe80::150]:59367 (ESTABLISHED) ''' remotes = set() try: data = subprocess.check_output( ['lsof', '-iTCP:{0:d}'.format(port), '-n', '-P'] # pylint: disable=minimum-python-version ) except subprocess.CalledProcessError as ex: if ex.returncode == 1: # Lsof return 1 if any error was detected, including the failure # to locate Internet addresses, and it is not an error in this case. log.warning('"lsof" returncode = 1, likely no active TCP sessions.') return remotes log.error('Failed "lsof" with returncode = %s', ex.returncode) raise lines = salt.utils.stringutils.to_str(data).split('\n') for line in lines: chunks = line.split() if not chunks: continue # ['Python', '9971', 'root', '37u', 'IPv4', '0x18a8464a29b2b29d', '0t0', # 'TCP', '127.0.0.1:4505->127.0.0.1:55703', '(ESTABLISHED)'] # print chunks if 'COMMAND' in chunks[0]: continue # ignore header if 'ESTABLISHED' not in chunks[-1]: continue # ignore if not ESTABLISHED # '127.0.0.1:4505->127.0.0.1:55703' local, remote = chunks[8].split('->') _, lport = local.rsplit(':', 1) rhost, rport = remote.rsplit(':', 1) if which_end == 'remote_port' and int(rport) != port: continue if which_end == 'local_port' and int(lport) != port: continue remotes.add(rhost.strip("[]")) return remotes def _aix_remotes_on(port, which_end): ''' AIX specific helper function. Returns set of ipv4 host addresses of remote established connections on local or remote tcp port. Parses output of shell 'netstat' to get connections root@la68pp002_pub:/opt/salt/lib/python2.7/site-packages/salt/modules# netstat -f inet -n Active Internet connections Proto Recv-Q Send-Q Local Address Foreign Address (state) tcp4 0 0 172.29.149.95.50093 209.41.78.13.4505 ESTABLISHED tcp4 0 0 127.0.0.1.9514 *.* LISTEN tcp4 0 0 127.0.0.1.9515 *.* LISTEN tcp4 0 0 127.0.0.1.199 127.0.0.1.32779 ESTABLISHED tcp4 0 0 127.0.0.1.32779 127.0.0.1.199 ESTABLISHED tcp4 0 40 172.29.149.95.22 172.29.96.83.41022 ESTABLISHED tcp4 0 0 172.29.149.95.22 172.29.96.83.41032 ESTABLISHED tcp4 0 0 127.0.0.1.32771 127.0.0.1.32775 ESTABLISHED tcp 0 0 127.0.0.1.32775 127.0.0.1.32771 ESTABLISHED tcp4 0 0 127.0.0.1.32771 127.0.0.1.32776 ESTABLISHED tcp 0 0 127.0.0.1.32776 127.0.0.1.32771 ESTABLISHED tcp4 0 0 127.0.0.1.32771 127.0.0.1.32777 ESTABLISHED tcp 0 0 127.0.0.1.32777 127.0.0.1.32771 ESTABLISHED tcp4 0 0 127.0.0.1.32771 127.0.0.1.32778 ESTABLISHED tcp 0 0 127.0.0.1.32778 127.0.0.1.32771 ESTABLISHED ''' remotes = set() try: data = subprocess.check_output(['netstat', '-f', 'inet', '-n']) # pylint: disable=minimum-python-version except subprocess.CalledProcessError: log.error('Failed netstat') raise lines = salt.utils.stringutils.to_str(data).split('\n') for line in lines: if 'ESTABLISHED' not in line: continue chunks = line.split() local_host, local_port = chunks[3].rsplit('.', 1) remote_host, remote_port = chunks[4].rsplit('.', 1) if which_end == 'remote_port' and int(remote_port) != port: continue if which_end == 'local_port' and int(local_port) != port: continue remotes.add(remote_host) return remotes @jinja_filter('gen_mac') def gen_mac(prefix='AC:DE:48'): ''' Generates a MAC address with the defined OUI prefix. Common prefixes: - ``00:16:3E`` -- Xen - ``00:18:51`` -- OpenVZ - ``00:50:56`` -- VMware (manually generated) - ``52:54:00`` -- QEMU/KVM - ``AC:DE:48`` -- PRIVATE References: - http://standards.ieee.org/develop/regauth/oui/oui.txt - https://www.wireshark.org/tools/oui-lookup.html - https://en.wikipedia.org/wiki/MAC_address ''' return '{0}:{1:02X}:{2:02X}:{3:02X}'.format(prefix, random.randint(0, 0xff), random.randint(0, 0xff), random.randint(0, 0xff)) @jinja_filter('mac_str_to_bytes') def mac_str_to_bytes(mac_str): ''' Convert a MAC address string into bytes. Works with or without separators: b1 = mac_str_to_bytes('08:00:27:13:69:77') b2 = mac_str_to_bytes('080027136977') assert b1 == b2 assert isinstance(b1, bytes) ''' if len(mac_str) == 12: pass elif len(mac_str) == 17: sep = mac_str[2] mac_str = mac_str.replace(sep, '') else: raise ValueError('Invalid MAC address') chars = (int(mac_str[s:s+2], 16) for s in range(0, 12, 2)) return bytes(chars) if six.PY3 else b''.join(chr(x) for x in chars) def refresh_dns(): ''' issue #21397: force glibc to re-read resolv.conf ''' try: res_init() except NameError: # Exception raised loading the library, thus res_init is not defined pass @jinja_filter('connection_check') def connection_check(addr, port=80, safe=False, ipv6=None): ''' Provides a convenient alias for the dns_check filter. ''' return dns_check(addr, port, safe, ipv6) @jinja_filter('dns_check') def dns_check(addr, port=80, safe=False, ipv6=None, attempt_connect=True): ''' Return the ip resolved by dns, but do not exit on failure, only raise an exception. Obeys system preference for IPv4/6 address resolution - this can be overridden by the ipv6 flag. Tries to connect to the address before considering it useful. If no address can be reached, the first one resolved is used as a fallback. ''' error = False lookup = addr seen_ipv6 = False family = socket.AF_INET6 if ipv6 else socket.AF_INET if ipv6 is False else socket.AF_UNSPEC hostnames = [] try: refresh_dns() hostnames = socket.getaddrinfo(addr, port, family, socket.SOCK_STREAM) except TypeError: err = ('Attempt to resolve address \'{0}\' failed. Invalid or unresolveable address').format(lookup) raise SaltSystemExit(code=42, msg=err) except socket.error: error = True # If ipv6 is set to True, attempt another lookup using the IPv4 family, # just in case we're attempting to lookup an IPv4 IP # as an IPv6 hostname. if error and ipv6: try: refresh_dns() hostnames = socket.getaddrinfo(addr, port, socket.AF_INET, socket.SOCK_STREAM) except TypeError: err = ('Attempt to resolve address \'{0}\' failed. Invalid or unresolveable address').format(lookup) raise SaltSystemExit(code=42, msg=err) except socket.error: error = True try: if not hostnames: error = True else: resolved = False candidates = [] for h in hostnames: # Input is IP address, passed through unchanged, just return it if h[4][0] == addr: resolved = salt.utils.zeromq.ip_bracket(addr) break candidate_addr = salt.utils.zeromq.ip_bracket(h[4][0]) # sometimes /etc/hosts contains ::1 localhost if not ipv6 and candidate_addr == '[::1]': continue candidates.append(candidate_addr) if attempt_connect: try: s = socket.socket(h[0], socket.SOCK_STREAM) s.settimeout(2) s.connect((candidate_addr.strip('[]'), h[4][1])) s.close() resolved = candidate_addr break except socket.error: pass if not resolved: if candidates: resolved = candidates[0] else: error = True except TypeError: err = ('Attempt to resolve address \'{0}\' failed. Invalid or unresolveable address').format(lookup) raise SaltSystemExit(code=42, msg=err) except socket.error: error = True if error: err = ('DNS lookup or connection check of \'{0}\' failed.').format(addr) if safe: if salt.log.is_console_configured(): # If logging is not configured it also means that either # the master or minion instance calling this hasn't even # started running log.error(err) raise SaltClientError() raise SaltSystemExit(code=42, msg=err) return resolved def parse_host_port(host_port): """ Takes a string argument specifying host or host:port. Returns a (hostname, port) or (ip_address, port) tuple. If no port is given, the second (port) element of the returned tuple will be None. host:port argument, for example, is accepted in the forms of: - hostname - hostname:1234 - hostname.domain.tld - hostname.domain.tld:5678 - [1234::5]:5678 - 1234::5 - 10.11.12.13:4567 - 10.11.12.13 """ host, port = None, None # default _s_ = host_port[:] if _s_[0] == "[": if "]" in host_port: host, _s_ = _s_.lstrip("[").rsplit("]", 1) host = ipaddress.IPv6Address(host).compressed if _s_[0] == ":": port = int(_s_.lstrip(":")) else: if len(_s_) > 1: raise ValueError('found ambiguous "{}" port in "{}"'.format(_s_, host_port)) else: if _s_.count(":") == 1: host, _hostport_separator_, port = _s_.partition(":") try: port = int(port) except ValueError as _e_: log.error('host_port "%s" port value "%s" is not an integer.', host_port, port) raise _e_ else: host = _s_ try: if not isinstance(host, ipaddress._BaseAddress): host_ip = ipaddress.ip_address(host).compressed host = host_ip except ValueError: log.debug('"%s" Not an IP address? Assuming it is a hostname.', host) if host != sanitize_host(host): log.error('bad hostname: "%s"', host) raise ValueError('bad hostname: "{}"'.format(host)) return host, port def is_fqdn(hostname): """ Verify if hostname conforms to be a FQDN. :param hostname: text string with the name of the host :return: bool, True if hostname is correct FQDN, False otherwise """ compliant = re.compile(r"(?!-)[A-Z\d\-\_]{1,63}(?<!-)$", re.IGNORECASE) return "." in hostname and len(hostname) < 0xff and all(compliant.match(x) for x in hostname.rstrip(".").split("."))
saltstack/salt
salt/utils/network.py
calc_net
python
def calc_net(ipaddr, netmask=None): ''' Takes IP (CIDR notation supported) and optionally netmask and returns the network in CIDR-notation. (The IP can be any IP inside the subnet) ''' if netmask is not None: ipaddr = '{0}/{1}'.format(ipaddr, netmask) return six.text_type(ipaddress.ip_network(ipaddr, strict=False))
Takes IP (CIDR notation supported) and optionally netmask and returns the network in CIDR-notation. (The IP can be any IP inside the subnet)
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/network.py#L1082-L1091
null
# -*- coding: utf-8 -*- ''' Define some generic socket functions for network modules ''' # Import python libs from __future__ import absolute_import, unicode_literals, print_function import itertools import os import re import types import socket import logging import platform import random import subprocess from string import ascii_letters, digits # Import 3rd-party libs from salt.ext import six from salt.ext.six.moves import range # pylint: disable=import-error,redefined-builtin # Attempt to import wmi try: import wmi import salt.utils.winapi except ImportError: pass # Import salt libs import salt.utils.args import salt.utils.files import salt.utils.path import salt.utils.platform import salt.utils.stringutils import salt.utils.zeromq from salt._compat import ipaddress from salt.exceptions import SaltClientError, SaltSystemExit from salt.utils.decorators.jinja import jinja_filter from salt.utils.versions import LooseVersion # inet_pton does not exist in Windows, this is a workaround if salt.utils.platform.is_windows(): from salt.ext import win_inet_pton # pylint: disable=unused-import log = logging.getLogger(__name__) try: import ctypes import ctypes.util libc = ctypes.cdll.LoadLibrary(ctypes.util.find_library("c")) res_init = libc.__res_init except (ImportError, OSError, AttributeError, TypeError): pass # pylint: disable=C0103 def sanitize_host(host): ''' Sanitize host string. https://tools.ietf.org/html/rfc1123#section-2.1 ''' RFC952_characters = ascii_letters + digits + ".-" return "".join([c for c in host[0:255] if c in RFC952_characters]) def isportopen(host, port): ''' Return status of a port ''' if not 1 <= int(port) <= 65535: return False sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) out = sock.connect_ex((sanitize_host(host), int(port))) return out def host_to_ips(host): ''' Returns a list of IP addresses of a given hostname or None if not found. ''' ips = [] try: for family, socktype, proto, canonname, sockaddr in socket.getaddrinfo( host, 0, socket.AF_UNSPEC, socket.SOCK_STREAM): if family == socket.AF_INET: ip, port = sockaddr elif family == socket.AF_INET6: ip, port, flow_info, scope_id = sockaddr ips.append(ip) if not ips: ips = None except Exception: ips = None return ips def _generate_minion_id(): ''' Get list of possible host names and convention names. :return: ''' # There are three types of hostnames: # 1. Network names. How host is accessed from the network. # 2. Host aliases. They might be not available in all the network or only locally (/etc/hosts) # 3. Convention names, an internal nodename. class DistinctList(list): ''' List, which allows one to append only distinct objects. Needs to work on Python 2.6, because of collections.OrderedDict only since 2.7 version. Override 'filter()' for custom filtering. ''' localhost_matchers = [r'localhost.*', r'ip6-.*', r'127[.]\d', r'0\.0\.0\.0', r'::1.*', r'ipv6-.*', r'fe00::.*', r'fe02::.*', r'1.0.0.*.ip6.arpa'] def append(self, p_object): if p_object and p_object not in self and not self.filter(p_object): super(DistinctList, self).append(p_object) return self def extend(self, iterable): for obj in iterable: self.append(obj) return self def filter(self, element): 'Returns True if element needs to be filtered' for rgx in self.localhost_matchers: if re.match(rgx, element): return True def first(self): return self and self[0] or None hostname = socket.gethostname() hosts = DistinctList().append( salt.utils.stringutils.to_unicode(socket.getfqdn(salt.utils.stringutils.to_bytes(hostname))) ).append(platform.node()).append(hostname) if not hosts: try: for a_nfo in socket.getaddrinfo(hosts.first() or 'localhost', None, socket.AF_INET, socket.SOCK_RAW, socket.IPPROTO_IP, socket.AI_CANONNAME): if len(a_nfo) > 3: hosts.append(a_nfo[3]) except socket.gaierror: log.warning('Cannot resolve address %s info via socket: %s', hosts.first() or 'localhost (N/A)', socket.gaierror) # Universal method for everywhere (Linux, Slowlaris, Windows etc) for f_name in ('/etc/hostname', '/etc/nodename', '/etc/hosts', r'{win}\system32\drivers\etc\hosts'.format(win=os.getenv('WINDIR'))): try: with salt.utils.files.fopen(f_name) as f_hdl: for line in f_hdl: line = salt.utils.stringutils.to_unicode(line) hst = line.strip().split('#')[0].strip().split() if hst: if hst[0][:4] in ('127.', '::1') or len(hst) == 1: hosts.extend(hst) except IOError: pass # include public and private ipaddresses return hosts.extend([addr for addr in ip_addrs() if not ipaddress.ip_address(addr).is_loopback]) def generate_minion_id(): ''' Return only first element of the hostname from all possible list. :return: ''' try: ret = salt.utils.stringutils.to_unicode(_generate_minion_id().first()) except TypeError: ret = None return ret or 'localhost' def get_socket(addr, type=socket.SOCK_STREAM, proto=0): ''' Return a socket object for the addr IP-version agnostic ''' version = ipaddress.ip_address(addr).version if version == 4: family = socket.AF_INET elif version == 6: family = socket.AF_INET6 return socket.socket(family, type, proto) def get_fqhostname(): ''' Returns the fully qualified hostname ''' # try getaddrinfo() fqdn = None try: addrinfo = socket.getaddrinfo( socket.gethostname(), 0, socket.AF_UNSPEC, socket.SOCK_STREAM, socket.SOL_TCP, socket.AI_CANONNAME ) for info in addrinfo: # info struct [family, socktype, proto, canonname, sockaddr] # On Windows `canonname` can be an empty string # This can cause the function to return `None` if len(info) > 3 and info[3]: fqdn = info[3] break except socket.gaierror: pass # NOTE: this used to log.error() but it was later disabled except socket.error as err: log.debug('socket.getaddrinfo() failure while finding fqdn: %s', err) if fqdn is None: fqdn = socket.getfqdn() return fqdn def ip_to_host(ip): ''' Returns the hostname of a given IP ''' try: hostname, aliaslist, ipaddrlist = socket.gethostbyaddr(ip) except Exception as exc: log.debug('salt.utils.network.ip_to_host(%r) failed: %s', ip, exc) hostname = None return hostname # pylint: enable=C0103 def is_reachable_host(entity_name): ''' Returns a bool telling if the entity name is a reachable host (IPv4/IPv6/FQDN/etc). :param hostname: :return: ''' try: assert type(socket.getaddrinfo(entity_name, 0, 0, 0, 0)) == list ret = True except socket.gaierror: ret = False return ret def is_ip(ip): ''' Returns a bool telling if the passed IP is a valid IPv4 or IPv6 address. ''' return is_ipv4(ip) or is_ipv6(ip) def is_ipv4(ip): ''' Returns a bool telling if the value passed to it was a valid IPv4 address ''' try: return ipaddress.ip_address(ip).version == 4 except ValueError: return False def is_ipv6(ip): ''' Returns a bool telling if the value passed to it was a valid IPv6 address ''' try: return ipaddress.ip_address(ip).version == 6 except ValueError: return False def is_subnet(cidr): ''' Returns a bool telling if the passed string is an IPv4 or IPv6 subnet ''' return is_ipv4_subnet(cidr) or is_ipv6_subnet(cidr) def is_ipv4_subnet(cidr): ''' Returns a bool telling if the passed string is an IPv4 subnet ''' try: return '/' in cidr and bool(ipaddress.IPv4Network(cidr)) except Exception: return False def is_ipv6_subnet(cidr): ''' Returns a bool telling if the passed string is an IPv6 subnet ''' try: return '/' in cidr and bool(ipaddress.IPv6Network(cidr)) except Exception: return False @jinja_filter('is_ip') def is_ip_filter(ip, options=None): ''' Returns a bool telling if the passed IP is a valid IPv4 or IPv6 address. ''' return is_ipv4_filter(ip, options=options) or is_ipv6_filter(ip, options=options) def _ip_options_global(ip_obj, version): return not ip_obj.is_private def _ip_options_multicast(ip_obj, version): return ip_obj.is_multicast def _ip_options_loopback(ip_obj, version): return ip_obj.is_loopback def _ip_options_link_local(ip_obj, version): return ip_obj.is_link_local def _ip_options_private(ip_obj, version): return ip_obj.is_private def _ip_options_reserved(ip_obj, version): return ip_obj.is_reserved def _ip_options_site_local(ip_obj, version): if version == 6: return ip_obj.is_site_local return False def _ip_options_unspecified(ip_obj, version): return ip_obj.is_unspecified def _ip_options(ip_obj, version, options=None): # will process and IP options options_fun_map = { 'global': _ip_options_global, 'link-local': _ip_options_link_local, 'linklocal': _ip_options_link_local, 'll': _ip_options_link_local, 'link_local': _ip_options_link_local, 'loopback': _ip_options_loopback, 'lo': _ip_options_loopback, 'multicast': _ip_options_multicast, 'private': _ip_options_private, 'public': _ip_options_global, 'reserved': _ip_options_reserved, 'site-local': _ip_options_site_local, 'sl': _ip_options_site_local, 'site_local': _ip_options_site_local, 'unspecified': _ip_options_unspecified } if not options: return six.text_type(ip_obj) # IP version already checked options_list = [option.strip() for option in options.split(',')] for option, fun in options_fun_map.items(): if option in options_list: fun_res = fun(ip_obj, version) if not fun_res: return None # stop at first failed test # else continue return six.text_type(ip_obj) def _is_ipv(ip, version, options=None): if not version: version = 4 if version not in (4, 6): return None try: ip_obj = ipaddress.ip_address(ip) except ValueError: # maybe it is an IP network try: ip_obj = ipaddress.ip_interface(ip) except ValueError: # nope, still not :( return None if not ip_obj.version == version: return None # has the right version, let's move on return _ip_options(ip_obj, version, options=options) @jinja_filter('is_ipv4') def is_ipv4_filter(ip, options=None): ''' Returns a bool telling if the value passed to it was a valid IPv4 address. ip The IP address. net: False Consider IP addresses followed by netmask. options CSV of options regarding the nature of the IP address. E.g.: loopback, multicast, private etc. ''' _is_ipv4 = _is_ipv(ip, 4, options=options) return isinstance(_is_ipv4, six.string_types) @jinja_filter('is_ipv6') def is_ipv6_filter(ip, options=None): ''' Returns a bool telling if the value passed to it was a valid IPv6 address. ip The IP address. net: False Consider IP addresses followed by netmask. options CSV of options regarding the nature of the IP address. E.g.: loopback, multicast, private etc. ''' _is_ipv6 = _is_ipv(ip, 6, options=options) return isinstance(_is_ipv6, six.string_types) def _ipv_filter(value, version, options=None): if version not in (4, 6): return if isinstance(value, (six.string_types, six.text_type, six.binary_type)): return _is_ipv(value, version, options=options) # calls is_ipv4 or is_ipv6 for `value` elif isinstance(value, (list, tuple, types.GeneratorType)): # calls is_ipv4 or is_ipv6 for each element in the list # os it filters and returns only those elements having the desired IP version return [ _is_ipv(addr, version, options=options) for addr in value if _is_ipv(addr, version, options=options) is not None ] return None @jinja_filter('ipv4') def ipv4(value, options=None): ''' Filters a list and returns IPv4 values only. ''' return _ipv_filter(value, 4, options=options) @jinja_filter('ipv6') def ipv6(value, options=None): ''' Filters a list and returns IPv6 values only. ''' return _ipv_filter(value, 6, options=options) @jinja_filter('ipaddr') def ipaddr(value, options=None): ''' Filters and returns only valid IP objects. ''' ipv4_obj = ipv4(value, options=options) ipv6_obj = ipv6(value, options=options) if ipv4_obj is None or ipv6_obj is None: # an IP address can be either IPv4 either IPv6 # therefofe if the value passed as arg is not a list, at least one of the calls above will return None # if one of them is none, means that we should return only one of them return ipv4_obj or ipv6_obj # one of them else: return ipv4_obj + ipv6_obj # extend lists def _filter_ipaddr(value, options, version=None): ipaddr_filter_out = None if version: if version == 4: ipaddr_filter_out = ipv4(value, options) elif version == 6: ipaddr_filter_out = ipv6(value, options) else: ipaddr_filter_out = ipaddr(value, options) if not ipaddr_filter_out: return if not isinstance(ipaddr_filter_out, (list, tuple, types.GeneratorType)): ipaddr_filter_out = [ipaddr_filter_out] return ipaddr_filter_out @jinja_filter('ip_host') def ip_host(value, options=None, version=None): ''' Returns the interfaces IP address, e.g.: 192.168.0.1/28. ''' ipaddr_filter_out = _filter_ipaddr(value, options=options, version=version) if not ipaddr_filter_out: return if not isinstance(value, (list, tuple, types.GeneratorType)): return six.text_type(ipaddress.ip_interface(ipaddr_filter_out[0])) return [six.text_type(ipaddress.ip_interface(ip_a)) for ip_a in ipaddr_filter_out] def _network_hosts(ip_addr_entry): return [ six.text_type(host) for host in ipaddress.ip_network(ip_addr_entry, strict=False).hosts() ] @jinja_filter('network_hosts') def network_hosts(value, options=None, version=None): ''' Return the list of hosts within a network. .. note:: When running this command with a large IPv6 network, the command will take a long time to gather all of the hosts. ''' ipaddr_filter_out = _filter_ipaddr(value, options=options, version=version) if not ipaddr_filter_out: return if not isinstance(value, (list, tuple, types.GeneratorType)): return _network_hosts(ipaddr_filter_out[0]) return [ _network_hosts(ip_a) for ip_a in ipaddr_filter_out ] def _network_size(ip_addr_entry): return ipaddress.ip_network(ip_addr_entry, strict=False).num_addresses @jinja_filter('network_size') def network_size(value, options=None, version=None): ''' Get the size of a network. ''' ipaddr_filter_out = _filter_ipaddr(value, options=options, version=version) if not ipaddr_filter_out: return if not isinstance(value, (list, tuple, types.GeneratorType)): return _network_size(ipaddr_filter_out[0]) return [ _network_size(ip_a) for ip_a in ipaddr_filter_out ] def natural_ipv4_netmask(ip, fmt='prefixlen'): ''' Returns the "natural" mask of an IPv4 address ''' bits = _ipv4_to_bits(ip) if bits.startswith('11'): mask = '24' elif bits.startswith('1'): mask = '16' else: mask = '8' if fmt == 'netmask': return cidr_to_ipv4_netmask(mask) else: return '/' + mask def rpad_ipv4_network(ip): ''' Returns an IP network address padded with zeros. Ex: '192.168.3' -> '192.168.3.0' '10.209' -> '10.209.0.0' ''' return '.'.join(itertools.islice(itertools.chain(ip.split('.'), '0000'), 0, 4)) def cidr_to_ipv4_netmask(cidr_bits): ''' Returns an IPv4 netmask ''' try: cidr_bits = int(cidr_bits) if not 1 <= cidr_bits <= 32: return '' except ValueError: return '' netmask = '' for idx in range(4): if idx: netmask += '.' if cidr_bits >= 8: netmask += '255' cidr_bits -= 8 else: netmask += '{0:d}'.format(256 - (2 ** (8 - cidr_bits))) cidr_bits = 0 return netmask def _number_of_set_bits_to_ipv4_netmask(set_bits): # pylint: disable=C0103 ''' Returns an IPv4 netmask from the integer representation of that mask. Ex. 0xffffff00 -> '255.255.255.0' ''' return cidr_to_ipv4_netmask(_number_of_set_bits(set_bits)) # pylint: disable=C0103 def _number_of_set_bits(x): ''' Returns the number of bits that are set in a 32bit int ''' # Taken from http://stackoverflow.com/a/4912729. Many thanks! x -= (x >> 1) & 0x55555555 x = ((x >> 2) & 0x33333333) + (x & 0x33333333) x = ((x >> 4) + x) & 0x0f0f0f0f x += x >> 8 x += x >> 16 return x & 0x0000003f # pylint: enable=C0103 def _interfaces_ip(out): ''' Uses ip to return a dictionary of interfaces with various information about each (up/down state, ip address, netmask, and hwaddr) ''' ret = dict() def parse_network(value, cols): ''' Return a tuple of ip, netmask, broadcast based on the current set of cols ''' brd = None scope = None if '/' in value: # we have a CIDR in this address ip, cidr = value.split('/') # pylint: disable=C0103 else: ip = value # pylint: disable=C0103 cidr = 32 if type_ == 'inet': mask = cidr_to_ipv4_netmask(int(cidr)) if 'brd' in cols: brd = cols[cols.index('brd') + 1] elif type_ == 'inet6': mask = cidr if 'scope' in cols: scope = cols[cols.index('scope') + 1] return (ip, mask, brd, scope) groups = re.compile('\r?\n\\d').split(out) for group in groups: iface = None data = dict() for line in group.splitlines(): if ' ' not in line: continue match = re.match(r'^\d*:\s+([\w.\-]+)(?:@)?([\w.\-]+)?:\s+<(.+)>', line) if match: iface, parent, attrs = match.groups() if 'UP' in attrs.split(','): data['up'] = True else: data['up'] = False if parent: data['parent'] = parent continue cols = line.split() if len(cols) >= 2: type_, value = tuple(cols[0:2]) iflabel = cols[-1:][0] if type_ in ('inet', 'inet6'): if 'secondary' not in cols: ipaddr, netmask, broadcast, scope = parse_network(value, cols) if type_ == 'inet': if 'inet' not in data: data['inet'] = list() addr_obj = dict() addr_obj['address'] = ipaddr addr_obj['netmask'] = netmask addr_obj['broadcast'] = broadcast addr_obj['label'] = iflabel data['inet'].append(addr_obj) elif type_ == 'inet6': if 'inet6' not in data: data['inet6'] = list() addr_obj = dict() addr_obj['address'] = ipaddr addr_obj['prefixlen'] = netmask addr_obj['scope'] = scope data['inet6'].append(addr_obj) else: if 'secondary' not in data: data['secondary'] = list() ip_, mask, brd, scp = parse_network(value, cols) data['secondary'].append({ 'type': type_, 'address': ip_, 'netmask': mask, 'broadcast': brd, 'label': iflabel, }) del ip_, mask, brd, scp elif type_.startswith('link'): data['hwaddr'] = value if iface: ret[iface] = data del iface, data return ret def _interfaces_ifconfig(out): ''' Uses ifconfig to return a dictionary of interfaces with various information about each (up/down state, ip address, netmask, and hwaddr) ''' ret = dict() piface = re.compile(r'^([^\s:]+)') pmac = re.compile('.*?(?:HWaddr|ether|address:|lladdr) ([0-9a-fA-F:]+)') if salt.utils.platform.is_sunos(): pip = re.compile(r'.*?(?:inet\s+)([0-9]+\.[0-9]+\.[0-9]+\.[0-9]+)(.*)') pip6 = re.compile('.*?(?:inet6 )([0-9a-fA-F:]+)') pmask6 = re.compile(r'.*?(?:inet6 [0-9a-fA-F:]+/(\d+)).*') else: pip = re.compile(r'.*?(?:inet addr:|inet [^\d]*)(.*?)\s') pip6 = re.compile('.*?(?:inet6 addr: (.*?)/|inet6 )([0-9a-fA-F:]+)') pmask6 = re.compile(r'.*?(?:inet6 addr: [0-9a-fA-F:]+/(\d+)|prefixlen (\d+))(?: Scope:([a-zA-Z]+)| scopeid (0x[0-9a-fA-F]))?') pmask = re.compile(r'.*?(?:Mask:|netmask )(?:((?:0x)?[0-9a-fA-F]{8})|([\d\.]+))') pupdown = re.compile('UP') pbcast = re.compile(r'.*?(?:Bcast:|broadcast )([\d\.]+)') groups = re.compile('\r?\n(?=\\S)').split(out) for group in groups: data = dict() iface = '' updown = False for line in group.splitlines(): miface = piface.match(line) mmac = pmac.match(line) mip = pip.match(line) mip6 = pip6.match(line) mupdown = pupdown.search(line) if miface: iface = miface.group(1) if mmac: data['hwaddr'] = mmac.group(1) if salt.utils.platform.is_sunos(): expand_mac = [] for chunk in data['hwaddr'].split(':'): expand_mac.append('0{0}'.format(chunk) if len(chunk) < 2 else '{0}'.format(chunk)) data['hwaddr'] = ':'.join(expand_mac) if mip: if 'inet' not in data: data['inet'] = list() addr_obj = dict() addr_obj['address'] = mip.group(1) mmask = pmask.match(line) if mmask: if mmask.group(1): mmask = _number_of_set_bits_to_ipv4_netmask( int(mmask.group(1), 16)) else: mmask = mmask.group(2) addr_obj['netmask'] = mmask mbcast = pbcast.match(line) if mbcast: addr_obj['broadcast'] = mbcast.group(1) data['inet'].append(addr_obj) if mupdown: updown = True if mip6: if 'inet6' not in data: data['inet6'] = list() addr_obj = dict() addr_obj['address'] = mip6.group(1) or mip6.group(2) mmask6 = pmask6.match(line) if mmask6: addr_obj['prefixlen'] = mmask6.group(1) or mmask6.group(2) if not salt.utils.platform.is_sunos(): ipv6scope = mmask6.group(3) or mmask6.group(4) addr_obj['scope'] = ipv6scope.lower() if ipv6scope is not None else ipv6scope # SunOS sometimes has ::/0 as inet6 addr when using addrconf if not salt.utils.platform.is_sunos() \ or addr_obj['address'] != '::' \ and addr_obj['prefixlen'] != 0: data['inet6'].append(addr_obj) data['up'] = updown if iface in ret: # SunOS optimization, where interfaces occur twice in 'ifconfig -a' # output with the same name: for ipv4 and then for ipv6 addr family. # Every instance has it's own 'UP' status and we assume that ipv4 # status determines global interface status. # # merge items with higher priority for older values # after that merge the inet and inet6 sub items for both ret[iface] = dict(list(data.items()) + list(ret[iface].items())) if 'inet' in data: ret[iface]['inet'].extend(x for x in data['inet'] if x not in ret[iface]['inet']) if 'inet6' in data: ret[iface]['inet6'].extend(x for x in data['inet6'] if x not in ret[iface]['inet6']) else: ret[iface] = data del data return ret def linux_interfaces(): ''' Obtain interface information for *NIX/BSD variants ''' ifaces = dict() ip_path = salt.utils.path.which('ip') ifconfig_path = None if ip_path else salt.utils.path.which('ifconfig') if ip_path: cmd1 = subprocess.Popen( '{0} link show'.format(ip_path), shell=True, close_fds=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT).communicate()[0] cmd2 = subprocess.Popen( '{0} addr show'.format(ip_path), shell=True, close_fds=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT).communicate()[0] ifaces = _interfaces_ip("{0}\n{1}".format( salt.utils.stringutils.to_str(cmd1), salt.utils.stringutils.to_str(cmd2))) elif ifconfig_path: cmd = subprocess.Popen( '{0} -a'.format(ifconfig_path), shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT).communicate()[0] ifaces = _interfaces_ifconfig(salt.utils.stringutils.to_str(cmd)) return ifaces def _netbsd_interfaces_ifconfig(out): ''' Uses ifconfig to return a dictionary of interfaces with various information about each (up/down state, ip address, netmask, and hwaddr) ''' ret = dict() piface = re.compile(r'^([^\s:]+)') pmac = re.compile('.*?address: ([0-9a-f:]+)') pip = re.compile(r'.*?inet [^\d]*(.*?)/([\d]*)\s') pip6 = re.compile(r'.*?inet6 ([0-9a-f:]+)%([a-zA-Z0-9]*)/([\d]*)\s') pupdown = re.compile('UP') pbcast = re.compile(r'.*?broadcast ([\d\.]+)') groups = re.compile('\r?\n(?=\\S)').split(out) for group in groups: data = dict() iface = '' updown = False for line in group.splitlines(): miface = piface.match(line) mmac = pmac.match(line) mip = pip.match(line) mip6 = pip6.match(line) mupdown = pupdown.search(line) if miface: iface = miface.group(1) if mmac: data['hwaddr'] = mmac.group(1) if mip: if 'inet' not in data: data['inet'] = list() addr_obj = dict() addr_obj['address'] = mip.group(1) mmask = mip.group(2) if mip.group(2): addr_obj['netmask'] = cidr_to_ipv4_netmask(mip.group(2)) mbcast = pbcast.match(line) if mbcast: addr_obj['broadcast'] = mbcast.group(1) data['inet'].append(addr_obj) if mupdown: updown = True if mip6: if 'inet6' not in data: data['inet6'] = list() addr_obj = dict() addr_obj['address'] = mip6.group(1) mmask6 = mip6.group(3) addr_obj['scope'] = mip6.group(2) addr_obj['prefixlen'] = mip6.group(3) data['inet6'].append(addr_obj) data['up'] = updown ret[iface] = data del data return ret def netbsd_interfaces(): ''' Obtain interface information for NetBSD >= 8 where the ifconfig output diverged from other BSD variants (Netmask is now part of the address) ''' # NetBSD versions prior to 8.0 can still use linux_interfaces() if LooseVersion(os.uname()[2]) < LooseVersion('8.0'): return linux_interfaces() ifconfig_path = salt.utils.path.which('ifconfig') cmd = subprocess.Popen( '{0} -a'.format(ifconfig_path), shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT).communicate()[0] return _netbsd_interfaces_ifconfig(salt.utils.stringutils.to_str(cmd)) def _interfaces_ipconfig(out): ''' Returns a dictionary of interfaces with various information about each (up/down state, ip address, netmask, and hwaddr) NOTE: This is not used by any function and may be able to be removed in the future. ''' ifaces = dict() iface = None adapter_iface_regex = re.compile(r'adapter (\S.+):$') for line in out.splitlines(): if not line: continue # TODO what does Windows call Infiniband and 10/40gige adapters if line.startswith('Ethernet'): iface = ifaces[adapter_iface_regex.search(line).group(1)] iface['up'] = True addr = None continue if iface: key, val = line.split(',', 1) key = key.strip(' .') val = val.strip() if addr and key == 'Subnet Mask': addr['netmask'] = val elif key in ('IP Address', 'IPv4 Address'): if 'inet' not in iface: iface['inet'] = list() addr = {'address': val.rstrip('(Preferred)'), 'netmask': None, 'broadcast': None} # TODO find the broadcast iface['inet'].append(addr) elif 'IPv6 Address' in key: if 'inet6' not in iface: iface['inet'] = list() # XXX What is the prefixlen!? addr = {'address': val.rstrip('(Preferred)'), 'prefixlen': None} iface['inet6'].append(addr) elif key == 'Physical Address': iface['hwaddr'] = val elif key == 'Media State': # XXX seen used for tunnel adaptors # might be useful iface['up'] = (val != 'Media disconnected') def win_interfaces(): ''' Obtain interface information for Windows systems ''' with salt.utils.winapi.Com(): c = wmi.WMI() ifaces = {} for iface in c.Win32_NetworkAdapterConfiguration(IPEnabled=1): ifaces[iface.Description] = dict() if iface.MACAddress: ifaces[iface.Description]['hwaddr'] = iface.MACAddress if iface.IPEnabled: ifaces[iface.Description]['up'] = True for ip in iface.IPAddress: if '.' in ip: if 'inet' not in ifaces[iface.Description]: ifaces[iface.Description]['inet'] = [] item = {'address': ip, 'label': iface.Description} if iface.DefaultIPGateway: broadcast = next((i for i in iface.DefaultIPGateway if '.' in i), '') if broadcast: item['broadcast'] = broadcast if iface.IPSubnet: netmask = next((i for i in iface.IPSubnet if '.' in i), '') if netmask: item['netmask'] = netmask ifaces[iface.Description]['inet'].append(item) if ':' in ip: if 'inet6' not in ifaces[iface.Description]: ifaces[iface.Description]['inet6'] = [] item = {'address': ip} if iface.DefaultIPGateway: broadcast = next((i for i in iface.DefaultIPGateway if ':' in i), '') if broadcast: item['broadcast'] = broadcast if iface.IPSubnet: netmask = next((i for i in iface.IPSubnet if ':' in i), '') if netmask: item['netmask'] = netmask ifaces[iface.Description]['inet6'].append(item) else: ifaces[iface.Description]['up'] = False return ifaces def interfaces(): ''' Return a dictionary of information about all the interfaces on the minion ''' if salt.utils.platform.is_windows(): return win_interfaces() elif salt.utils.platform.is_netbsd(): return netbsd_interfaces() else: return linux_interfaces() def get_net_start(ipaddr, netmask): ''' Return the address of the network ''' net = ipaddress.ip_network('{0}/{1}'.format(ipaddr, netmask), strict=False) return six.text_type(net.network_address) def get_net_size(mask): ''' Turns an IPv4 netmask into it's corresponding prefix length (255.255.255.0 -> 24 as in 192.168.1.10/24). ''' binary_str = '' for octet in mask.split('.'): binary_str += bin(int(octet))[2:].zfill(8) return len(binary_str.rstrip('0')) def _ipv4_to_bits(ipaddr): ''' Accepts an IPv4 dotted quad and returns a string representing its binary counterpart ''' return ''.join([bin(int(x))[2:].rjust(8, '0') for x in ipaddr.split('.')]) def _get_iface_info(iface): ''' If `iface` is available, return interface info and no error, otherwise return no info and log and return an error ''' iface_info = interfaces() if iface in iface_info.keys(): return iface_info, False else: error_msg = ('Interface "{0}" not in available interfaces: "{1}"' ''.format(iface, '", "'.join(iface_info.keys()))) log.error(error_msg) return None, error_msg def _hw_addr_aix(iface): ''' Return the hardware address (a.k.a. MAC address) for a given interface on AIX MAC address not available in through interfaces ''' cmd = subprocess.Popen( 'entstat -d {0} | grep \'Hardware Address\''.format(iface), shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT).communicate()[0] if cmd: comps = cmd.split(' ') if len(comps) == 3: mac_addr = comps[2].strip('\'').strip() return mac_addr error_msg = ('Interface "{0}" either not available or does not contain a hardware address'.format(iface)) log.error(error_msg) return error_msg def hw_addr(iface): ''' Return the hardware address (a.k.a. MAC address) for a given interface .. versionchanged:: 2016.11.4 Added support for AIX ''' if salt.utils.platform.is_aix(): return _hw_addr_aix iface_info, error = _get_iface_info(iface) if error is False: return iface_info.get(iface, {}).get('hwaddr', '') else: return error def interface(iface): ''' Return the details of `iface` or an error if it does not exist ''' iface_info, error = _get_iface_info(iface) if error is False: return iface_info.get(iface, {}).get('inet', '') else: return error def interface_ip(iface): ''' Return `iface` IPv4 addr or an error if `iface` does not exist ''' iface_info, error = _get_iface_info(iface) if error is False: inet = iface_info.get(iface, {}).get('inet', None) return inet[0].get('address', '') if inet else '' else: return error def _subnets(proto='inet', interfaces_=None): ''' Returns a list of subnets to which the host belongs ''' if interfaces_ is None: ifaces = interfaces() elif isinstance(interfaces_, list): ifaces = {} for key, value in six.iteritems(interfaces()): if key in interfaces_: ifaces[key] = value else: ifaces = {interfaces_: interfaces().get(interfaces_, {})} ret = set() if proto == 'inet': subnet = 'netmask' dflt_cidr = 32 elif proto == 'inet6': subnet = 'prefixlen' dflt_cidr = 128 else: log.error('Invalid proto %s calling subnets()', proto) return for ip_info in six.itervalues(ifaces): addrs = ip_info.get(proto, []) addrs.extend([addr for addr in ip_info.get('secondary', []) if addr.get('type') == proto]) for intf in addrs: if subnet in intf: intf = ipaddress.ip_interface('{0}/{1}'.format(intf['address'], intf[subnet])) else: intf = ipaddress.ip_interface('{0}/{1}'.format(intf['address'], dflt_cidr)) if not intf.is_loopback: ret.add(intf.network) return [six.text_type(net) for net in sorted(ret)] def subnets(interfaces=None): ''' Returns a list of IPv4 subnets to which the host belongs ''' return _subnets('inet', interfaces_=interfaces) def subnets6(): ''' Returns a list of IPv6 subnets to which the host belongs ''' return _subnets('inet6') def in_subnet(cidr, addr=None): ''' Returns True if host or (any of) addrs is within specified subnet, otherwise False ''' try: cidr = ipaddress.ip_network(cidr) except ValueError: log.error('Invalid CIDR \'%s\'', cidr) return False if addr is None: addr = ip_addrs() addr.extend(ip_addrs6()) elif not isinstance(addr, (list, tuple)): addr = (addr,) return any(ipaddress.ip_address(item) in cidr for item in addr) def _ip_addrs(interface=None, include_loopback=False, interface_data=None, proto='inet'): ''' Return the full list of IP adresses matching the criteria proto = inet|inet6 ''' ret = set() ifaces = interface_data \ if isinstance(interface_data, dict) \ else interfaces() if interface is None: target_ifaces = ifaces else: target_ifaces = dict([(k, v) for k, v in six.iteritems(ifaces) if k == interface]) if not target_ifaces: log.error('Interface %s not found.', interface) for ip_info in six.itervalues(target_ifaces): addrs = ip_info.get(proto, []) addrs.extend([addr for addr in ip_info.get('secondary', []) if addr.get('type') == proto]) for addr in addrs: addr = ipaddress.ip_address(addr.get('address')) if not addr.is_loopback or include_loopback: ret.add(addr) return [six.text_type(addr) for addr in sorted(ret)] def ip_addrs(interface=None, include_loopback=False, interface_data=None): ''' Returns a list of IPv4 addresses assigned to the host. 127.0.0.1 is ignored, unless 'include_loopback=True' is indicated. If 'interface' is provided, then only IP addresses from that interface will be returned. ''' return _ip_addrs(interface, include_loopback, interface_data, 'inet') def ip_addrs6(interface=None, include_loopback=False, interface_data=None): ''' Returns a list of IPv6 addresses assigned to the host. ::1 is ignored, unless 'include_loopback=True' is indicated. If 'interface' is provided, then only IP addresses from that interface will be returned. ''' return _ip_addrs(interface, include_loopback, interface_data, 'inet6') def hex2ip(hex_ip, invert=False): ''' Convert a hex string to an ip, if a failure occurs the original hex is returned. If 'invert=True' assume that ip from /proc/net/<proto> ''' if len(hex_ip) == 32: # ipv6 ip = [] for i in range(0, 32, 8): ip_part = hex_ip[i:i + 8] ip_part = [ip_part[x:x + 2] for x in range(0, 8, 2)] if invert: ip.append("{0[3]}{0[2]}:{0[1]}{0[0]}".format(ip_part)) else: ip.append("{0[0]}{0[1]}:{0[2]}{0[3]}".format(ip_part)) try: address = ipaddress.IPv6Address(":".join(ip)) if address.ipv4_mapped: return str(address.ipv4_mapped) else: return address.compressed except ipaddress.AddressValueError as ex: log.error('hex2ip - ipv6 address error: %s', ex) return hex_ip try: hip = int(hex_ip, 16) except ValueError: return hex_ip if invert: return '{3}.{2}.{1}.{0}'.format(hip >> 24 & 255, hip >> 16 & 255, hip >> 8 & 255, hip & 255) return '{0}.{1}.{2}.{3}'.format(hip >> 24 & 255, hip >> 16 & 255, hip >> 8 & 255, hip & 255) def mac2eui64(mac, prefix=None): ''' Convert a MAC address to a EUI64 identifier or, with prefix provided, a full IPv6 address ''' # http://tools.ietf.org/html/rfc4291#section-2.5.1 eui64 = re.sub(r'[.:-]', '', mac).lower() eui64 = eui64[0:6] + 'fffe' + eui64[6:] eui64 = hex(int(eui64[0:2], 16) | 2)[2:].zfill(2) + eui64[2:] if prefix is None: return ':'.join(re.findall(r'.{4}', eui64)) else: try: net = ipaddress.ip_network(prefix, strict=False) euil = int('0x{0}'.format(eui64), 16) return '{0}/{1}'.format(net[euil], net.prefixlen) except Exception: return def active_tcp(): ''' Return a dict describing all active tcp connections as quickly as possible ''' ret = {} for statf in ['/proc/net/tcp', '/proc/net/tcp6']: if os.path.isfile(statf): with salt.utils.files.fopen(statf, 'rb') as fp_: for line in fp_: line = salt.utils.stringutils.to_unicode(line) if line.strip().startswith('sl'): continue iret = _parse_tcp_line(line) sl = next(iter(iret)) if iret[sl]['state'] == 1: # 1 is ESTABLISHED del iret[sl]['state'] ret[len(ret)] = iret[sl] return ret def local_port_tcp(port): ''' Return a set of remote ip addrs attached to the specified local port ''' ret = _remotes_on(port, 'local_port') return ret def remote_port_tcp(port): ''' Return a set of ip addrs the current host is connected to on given port ''' ret = _remotes_on(port, 'remote_port') return ret def _remotes_on(port, which_end): ''' Return a set of ip addrs active tcp connections ''' port = int(port) ret = _netlink_tool_remote_on(port, which_end) if ret is not None: return ret ret = set() proc_available = False for statf in ['/proc/net/tcp', '/proc/net/tcp6']: if os.path.isfile(statf): proc_available = True with salt.utils.files.fopen(statf, 'r') as fp_: for line in fp_: line = salt.utils.stringutils.to_unicode(line) if line.strip().startswith('sl'): continue iret = _parse_tcp_line(line) sl = next(iter(iret)) if iret[sl][which_end] == port and iret[sl]['state'] == 1: # 1 is ESTABLISHED ret.add(iret[sl]['remote_addr']) if not proc_available: # Fallback to use OS specific tools if salt.utils.platform.is_sunos(): return _sunos_remotes_on(port, which_end) if salt.utils.platform.is_freebsd(): return _freebsd_remotes_on(port, which_end) if salt.utils.platform.is_netbsd(): return _netbsd_remotes_on(port, which_end) if salt.utils.platform.is_openbsd(): return _openbsd_remotes_on(port, which_end) if salt.utils.platform.is_windows(): return _windows_remotes_on(port, which_end) if salt.utils.platform.is_aix(): return _aix_remotes_on(port, which_end) return _linux_remotes_on(port, which_end) return ret def _parse_tcp_line(line): ''' Parse a single line from the contents of /proc/net/tcp or /proc/net/tcp6 ''' ret = {} comps = line.strip().split() sl = comps[0].rstrip(':') ret[sl] = {} l_addr, l_port = comps[1].split(':') r_addr, r_port = comps[2].split(':') ret[sl]['local_addr'] = hex2ip(l_addr, True) ret[sl]['local_port'] = int(l_port, 16) ret[sl]['remote_addr'] = hex2ip(r_addr, True) ret[sl]['remote_port'] = int(r_port, 16) ret[sl]['state'] = int(comps[3], 16) return ret def _netlink_tool_remote_on(port, which_end): ''' Returns set of ipv4 host addresses of remote established connections on local or remote tcp port. Parses output of shell 'ss' to get connections [root@salt-master ~]# ss -ant State Recv-Q Send-Q Local Address:Port Peer Address:Port LISTEN 0 511 *:80 *:* LISTEN 0 128 *:22 *:* ESTAB 0 0 127.0.0.1:56726 127.0.0.1:4505 ''' remotes = set() valid = False try: data = subprocess.check_output(['ss', '-ant']) # pylint: disable=minimum-python-version except subprocess.CalledProcessError: log.error('Failed ss') raise except OSError: # not command "No such file or directory" return None lines = salt.utils.stringutils.to_str(data).split('\n') for line in lines: if 'Address:Port' in line: # ss tools may not be valid valid = True continue elif 'ESTAB' not in line: continue chunks = line.split() local_host, local_port = chunks[3].split(':', 1) remote_host, remote_port = chunks[4].split(':', 1) if which_end == 'remote_port' and int(remote_port) != port: continue if which_end == 'local_port' and int(local_port) != port: continue remotes.add(remote_host) if valid is False: remotes = None return remotes def _sunos_remotes_on(port, which_end): ''' SunOS specific helper function. Returns set of ipv4 host addresses of remote established connections on local or remote tcp port. Parses output of shell 'netstat' to get connections [root@salt-master ~]# netstat -f inet -n TCP: IPv4 Local Address Remote Address Swind Send-Q Rwind Recv-Q State -------------------- -------------------- ----- ------ ----- ------ ----------- 10.0.0.101.4505 10.0.0.1.45329 1064800 0 1055864 0 ESTABLISHED 10.0.0.101.4505 10.0.0.100.50798 1064800 0 1055864 0 ESTABLISHED ''' remotes = set() try: data = subprocess.check_output(['netstat', '-f', 'inet', '-n']) # pylint: disable=minimum-python-version except subprocess.CalledProcessError: log.error('Failed netstat') raise lines = salt.utils.stringutils.to_str(data).split('\n') for line in lines: if 'ESTABLISHED' not in line: continue chunks = line.split() local_host, local_port = chunks[0].rsplit('.', 1) remote_host, remote_port = chunks[1].rsplit('.', 1) if which_end == 'remote_port' and int(remote_port) != port: continue if which_end == 'local_port' and int(local_port) != port: continue remotes.add(remote_host) return remotes def _freebsd_remotes_on(port, which_end): ''' Returns set of ipv4 host addresses of remote established connections on local tcp port port. Parses output of shell 'sockstat' (FreeBSD) to get connections $ sudo sockstat -4 USER COMMAND PID FD PROTO LOCAL ADDRESS FOREIGN ADDRESS root python2.7 1456 29 tcp4 *:4505 *:* root python2.7 1445 17 tcp4 *:4506 *:* root python2.7 1294 14 tcp4 127.0.0.1:11813 127.0.0.1:4505 root python2.7 1294 41 tcp4 127.0.0.1:61115 127.0.0.1:4506 $ sudo sockstat -4 -c -p 4506 USER COMMAND PID FD PROTO LOCAL ADDRESS FOREIGN ADDRESS root python2.7 1294 41 tcp4 127.0.0.1:61115 127.0.0.1:4506 ''' port = int(port) remotes = set() try: cmd = salt.utils.args.shlex_split('sockstat -4 -c -p {0}'.format(port)) data = subprocess.check_output(cmd) # pylint: disable=minimum-python-version except subprocess.CalledProcessError as ex: log.error('Failed "sockstat" with returncode = %s', ex.returncode) raise lines = salt.utils.stringutils.to_str(data).split('\n') for line in lines: chunks = line.split() if not chunks: continue # ['root', 'python2.7', '1456', '37', 'tcp4', # '127.0.0.1:4505-', '127.0.0.1:55703'] # print chunks if 'COMMAND' in chunks[1]: continue # ignore header if len(chunks) < 2: continue # sockstat -4 -c -p 4506 does this with high PIDs: # USER COMMAND PID FD PROTO LOCAL ADDRESS FOREIGN ADDRESS # salt-master python2.781106 35 tcp4 192.168.12.34:4506 192.168.12.45:60143 local = chunks[-2] remote = chunks[-1] lhost, lport = local.split(':') rhost, rport = remote.split(':') if which_end == 'local' and int(lport) != port: # ignore if local port not port continue if which_end == 'remote' and int(rport) != port: # ignore if remote port not port continue remotes.add(rhost) return remotes def _netbsd_remotes_on(port, which_end): ''' Returns set of ipv4 host addresses of remote established connections on local tcp port port. Parses output of shell 'sockstat' (NetBSD) to get connections $ sudo sockstat -4 -n USER COMMAND PID FD PROTO LOCAL ADDRESS FOREIGN ADDRESS root python2.7 1456 29 tcp *.4505 *.* root python2.7 1445 17 tcp *.4506 *.* root python2.7 1294 14 tcp 127.0.0.1.11813 127.0.0.1.4505 root python2.7 1294 41 tcp 127.0.0.1.61115 127.0.0.1.4506 $ sudo sockstat -4 -c -n -p 4506 USER COMMAND PID FD PROTO LOCAL ADDRESS FOREIGN ADDRESS root python2.7 1294 41 tcp 127.0.0.1.61115 127.0.0.1.4506 ''' port = int(port) remotes = set() try: cmd = salt.utils.args.shlex_split('sockstat -4 -c -n -p {0}'.format(port)) data = subprocess.check_output(cmd) # pylint: disable=minimum-python-version except subprocess.CalledProcessError as ex: log.error('Failed "sockstat" with returncode = %s', ex.returncode) raise lines = salt.utils.stringutils.to_str(data).split('\n') for line in lines: chunks = line.split() if not chunks: continue # ['root', 'python2.7', '1456', '37', 'tcp', # '127.0.0.1.4505-', '127.0.0.1.55703'] # print chunks if 'COMMAND' in chunks[1]: continue # ignore header if len(chunks) < 2: continue local = chunks[5].split('.') lport = local.pop() lhost = '.'.join(local) remote = chunks[6].split('.') rport = remote.pop() rhost = '.'.join(remote) if which_end == 'local' and int(lport) != port: # ignore if local port not port continue if which_end == 'remote' and int(rport) != port: # ignore if remote port not port continue remotes.add(rhost) return remotes def _openbsd_remotes_on(port, which_end): ''' OpenBSD specific helper function. Returns set of ipv4 host addresses of remote established connections on local or remote tcp port. Parses output of shell 'netstat' to get connections $ netstat -nf inet Active Internet connections Proto Recv-Q Send-Q Local Address Foreign Address (state) tcp 0 0 10.0.0.101.4505 10.0.0.1.45329 ESTABLISHED tcp 0 0 10.0.0.101.4505 10.0.0.100.50798 ESTABLISHED ''' remotes = set() try: data = subprocess.check_output(['netstat', '-nf', 'inet']) # pylint: disable=minimum-python-version except subprocess.CalledProcessError: log.error('Failed netstat') raise lines = data.split('\n') for line in lines: if 'ESTABLISHED' not in line: continue chunks = line.split() local_host, local_port = chunks[3].rsplit('.', 1) remote_host, remote_port = chunks[4].rsplit('.', 1) if which_end == 'remote_port' and int(remote_port) != port: continue if which_end == 'local_port' and int(local_port) != port: continue remotes.add(remote_host) return remotes def _windows_remotes_on(port, which_end): r''' Windows specific helper function. Returns set of ipv4 host addresses of remote established connections on local or remote tcp port. Parses output of shell 'netstat' to get connections C:\>netstat -n Active Connections Proto Local Address Foreign Address State TCP 10.2.33.17:3007 130.164.12.233:10123 ESTABLISHED TCP 10.2.33.17:3389 130.164.30.5:10378 ESTABLISHED ''' remotes = set() try: data = subprocess.check_output(['netstat', '-n']) # pylint: disable=minimum-python-version except subprocess.CalledProcessError: log.error('Failed netstat') raise lines = salt.utils.stringutils.to_str(data).split('\n') for line in lines: if 'ESTABLISHED' not in line: continue chunks = line.split() local_host, local_port = chunks[1].rsplit(':', 1) remote_host, remote_port = chunks[2].rsplit(':', 1) if which_end == 'remote_port' and int(remote_port) != port: continue if which_end == 'local_port' and int(local_port) != port: continue remotes.add(remote_host) return remotes def _linux_remotes_on(port, which_end): ''' Linux specific helper function. Returns set of ip host addresses of remote established connections on local tcp port port. Parses output of shell 'lsof' to get connections $ sudo lsof -iTCP:4505 -n COMMAND PID USER FD TYPE DEVICE SIZE/OFF NODE NAME Python 9971 root 35u IPv4 0x18a8464a29ca329d 0t0 TCP *:4505 (LISTEN) Python 9971 root 37u IPv4 0x18a8464a29b2b29d 0t0 TCP 127.0.0.1:4505->127.0.0.1:55703 (ESTABLISHED) Python 10152 root 22u IPv4 0x18a8464a29c8cab5 0t0 TCP 127.0.0.1:55703->127.0.0.1:4505 (ESTABLISHED) Python 10153 root 22u IPv4 0x18a8464a29c8cab5 0t0 TCP [fe80::249a]:4505->[fe80::150]:59367 (ESTABLISHED) ''' remotes = set() try: data = subprocess.check_output( ['lsof', '-iTCP:{0:d}'.format(port), '-n', '-P'] # pylint: disable=minimum-python-version ) except subprocess.CalledProcessError as ex: if ex.returncode == 1: # Lsof return 1 if any error was detected, including the failure # to locate Internet addresses, and it is not an error in this case. log.warning('"lsof" returncode = 1, likely no active TCP sessions.') return remotes log.error('Failed "lsof" with returncode = %s', ex.returncode) raise lines = salt.utils.stringutils.to_str(data).split('\n') for line in lines: chunks = line.split() if not chunks: continue # ['Python', '9971', 'root', '37u', 'IPv4', '0x18a8464a29b2b29d', '0t0', # 'TCP', '127.0.0.1:4505->127.0.0.1:55703', '(ESTABLISHED)'] # print chunks if 'COMMAND' in chunks[0]: continue # ignore header if 'ESTABLISHED' not in chunks[-1]: continue # ignore if not ESTABLISHED # '127.0.0.1:4505->127.0.0.1:55703' local, remote = chunks[8].split('->') _, lport = local.rsplit(':', 1) rhost, rport = remote.rsplit(':', 1) if which_end == 'remote_port' and int(rport) != port: continue if which_end == 'local_port' and int(lport) != port: continue remotes.add(rhost.strip("[]")) return remotes def _aix_remotes_on(port, which_end): ''' AIX specific helper function. Returns set of ipv4 host addresses of remote established connections on local or remote tcp port. Parses output of shell 'netstat' to get connections root@la68pp002_pub:/opt/salt/lib/python2.7/site-packages/salt/modules# netstat -f inet -n Active Internet connections Proto Recv-Q Send-Q Local Address Foreign Address (state) tcp4 0 0 172.29.149.95.50093 209.41.78.13.4505 ESTABLISHED tcp4 0 0 127.0.0.1.9514 *.* LISTEN tcp4 0 0 127.0.0.1.9515 *.* LISTEN tcp4 0 0 127.0.0.1.199 127.0.0.1.32779 ESTABLISHED tcp4 0 0 127.0.0.1.32779 127.0.0.1.199 ESTABLISHED tcp4 0 40 172.29.149.95.22 172.29.96.83.41022 ESTABLISHED tcp4 0 0 172.29.149.95.22 172.29.96.83.41032 ESTABLISHED tcp4 0 0 127.0.0.1.32771 127.0.0.1.32775 ESTABLISHED tcp 0 0 127.0.0.1.32775 127.0.0.1.32771 ESTABLISHED tcp4 0 0 127.0.0.1.32771 127.0.0.1.32776 ESTABLISHED tcp 0 0 127.0.0.1.32776 127.0.0.1.32771 ESTABLISHED tcp4 0 0 127.0.0.1.32771 127.0.0.1.32777 ESTABLISHED tcp 0 0 127.0.0.1.32777 127.0.0.1.32771 ESTABLISHED tcp4 0 0 127.0.0.1.32771 127.0.0.1.32778 ESTABLISHED tcp 0 0 127.0.0.1.32778 127.0.0.1.32771 ESTABLISHED ''' remotes = set() try: data = subprocess.check_output(['netstat', '-f', 'inet', '-n']) # pylint: disable=minimum-python-version except subprocess.CalledProcessError: log.error('Failed netstat') raise lines = salt.utils.stringutils.to_str(data).split('\n') for line in lines: if 'ESTABLISHED' not in line: continue chunks = line.split() local_host, local_port = chunks[3].rsplit('.', 1) remote_host, remote_port = chunks[4].rsplit('.', 1) if which_end == 'remote_port' and int(remote_port) != port: continue if which_end == 'local_port' and int(local_port) != port: continue remotes.add(remote_host) return remotes @jinja_filter('gen_mac') def gen_mac(prefix='AC:DE:48'): ''' Generates a MAC address with the defined OUI prefix. Common prefixes: - ``00:16:3E`` -- Xen - ``00:18:51`` -- OpenVZ - ``00:50:56`` -- VMware (manually generated) - ``52:54:00`` -- QEMU/KVM - ``AC:DE:48`` -- PRIVATE References: - http://standards.ieee.org/develop/regauth/oui/oui.txt - https://www.wireshark.org/tools/oui-lookup.html - https://en.wikipedia.org/wiki/MAC_address ''' return '{0}:{1:02X}:{2:02X}:{3:02X}'.format(prefix, random.randint(0, 0xff), random.randint(0, 0xff), random.randint(0, 0xff)) @jinja_filter('mac_str_to_bytes') def mac_str_to_bytes(mac_str): ''' Convert a MAC address string into bytes. Works with or without separators: b1 = mac_str_to_bytes('08:00:27:13:69:77') b2 = mac_str_to_bytes('080027136977') assert b1 == b2 assert isinstance(b1, bytes) ''' if len(mac_str) == 12: pass elif len(mac_str) == 17: sep = mac_str[2] mac_str = mac_str.replace(sep, '') else: raise ValueError('Invalid MAC address') chars = (int(mac_str[s:s+2], 16) for s in range(0, 12, 2)) return bytes(chars) if six.PY3 else b''.join(chr(x) for x in chars) def refresh_dns(): ''' issue #21397: force glibc to re-read resolv.conf ''' try: res_init() except NameError: # Exception raised loading the library, thus res_init is not defined pass @jinja_filter('connection_check') def connection_check(addr, port=80, safe=False, ipv6=None): ''' Provides a convenient alias for the dns_check filter. ''' return dns_check(addr, port, safe, ipv6) @jinja_filter('dns_check') def dns_check(addr, port=80, safe=False, ipv6=None, attempt_connect=True): ''' Return the ip resolved by dns, but do not exit on failure, only raise an exception. Obeys system preference for IPv4/6 address resolution - this can be overridden by the ipv6 flag. Tries to connect to the address before considering it useful. If no address can be reached, the first one resolved is used as a fallback. ''' error = False lookup = addr seen_ipv6 = False family = socket.AF_INET6 if ipv6 else socket.AF_INET if ipv6 is False else socket.AF_UNSPEC hostnames = [] try: refresh_dns() hostnames = socket.getaddrinfo(addr, port, family, socket.SOCK_STREAM) except TypeError: err = ('Attempt to resolve address \'{0}\' failed. Invalid or unresolveable address').format(lookup) raise SaltSystemExit(code=42, msg=err) except socket.error: error = True # If ipv6 is set to True, attempt another lookup using the IPv4 family, # just in case we're attempting to lookup an IPv4 IP # as an IPv6 hostname. if error and ipv6: try: refresh_dns() hostnames = socket.getaddrinfo(addr, port, socket.AF_INET, socket.SOCK_STREAM) except TypeError: err = ('Attempt to resolve address \'{0}\' failed. Invalid or unresolveable address').format(lookup) raise SaltSystemExit(code=42, msg=err) except socket.error: error = True try: if not hostnames: error = True else: resolved = False candidates = [] for h in hostnames: # Input is IP address, passed through unchanged, just return it if h[4][0] == addr: resolved = salt.utils.zeromq.ip_bracket(addr) break candidate_addr = salt.utils.zeromq.ip_bracket(h[4][0]) # sometimes /etc/hosts contains ::1 localhost if not ipv6 and candidate_addr == '[::1]': continue candidates.append(candidate_addr) if attempt_connect: try: s = socket.socket(h[0], socket.SOCK_STREAM) s.settimeout(2) s.connect((candidate_addr.strip('[]'), h[4][1])) s.close() resolved = candidate_addr break except socket.error: pass if not resolved: if candidates: resolved = candidates[0] else: error = True except TypeError: err = ('Attempt to resolve address \'{0}\' failed. Invalid or unresolveable address').format(lookup) raise SaltSystemExit(code=42, msg=err) except socket.error: error = True if error: err = ('DNS lookup or connection check of \'{0}\' failed.').format(addr) if safe: if salt.log.is_console_configured(): # If logging is not configured it also means that either # the master or minion instance calling this hasn't even # started running log.error(err) raise SaltClientError() raise SaltSystemExit(code=42, msg=err) return resolved def parse_host_port(host_port): """ Takes a string argument specifying host or host:port. Returns a (hostname, port) or (ip_address, port) tuple. If no port is given, the second (port) element of the returned tuple will be None. host:port argument, for example, is accepted in the forms of: - hostname - hostname:1234 - hostname.domain.tld - hostname.domain.tld:5678 - [1234::5]:5678 - 1234::5 - 10.11.12.13:4567 - 10.11.12.13 """ host, port = None, None # default _s_ = host_port[:] if _s_[0] == "[": if "]" in host_port: host, _s_ = _s_.lstrip("[").rsplit("]", 1) host = ipaddress.IPv6Address(host).compressed if _s_[0] == ":": port = int(_s_.lstrip(":")) else: if len(_s_) > 1: raise ValueError('found ambiguous "{}" port in "{}"'.format(_s_, host_port)) else: if _s_.count(":") == 1: host, _hostport_separator_, port = _s_.partition(":") try: port = int(port) except ValueError as _e_: log.error('host_port "%s" port value "%s" is not an integer.', host_port, port) raise _e_ else: host = _s_ try: if not isinstance(host, ipaddress._BaseAddress): host_ip = ipaddress.ip_address(host).compressed host = host_ip except ValueError: log.debug('"%s" Not an IP address? Assuming it is a hostname.', host) if host != sanitize_host(host): log.error('bad hostname: "%s"', host) raise ValueError('bad hostname: "{}"'.format(host)) return host, port def is_fqdn(hostname): """ Verify if hostname conforms to be a FQDN. :param hostname: text string with the name of the host :return: bool, True if hostname is correct FQDN, False otherwise """ compliant = re.compile(r"(?!-)[A-Z\d\-\_]{1,63}(?<!-)$", re.IGNORECASE) return "." in hostname and len(hostname) < 0xff and all(compliant.match(x) for x in hostname.rstrip(".").split("."))
saltstack/salt
salt/utils/network.py
_ipv4_to_bits
python
def _ipv4_to_bits(ipaddr): ''' Accepts an IPv4 dotted quad and returns a string representing its binary counterpart ''' return ''.join([bin(int(x))[2:].rjust(8, '0') for x in ipaddr.split('.')])
Accepts an IPv4 dotted quad and returns a string representing its binary counterpart
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/network.py#L1094-L1099
null
# -*- coding: utf-8 -*- ''' Define some generic socket functions for network modules ''' # Import python libs from __future__ import absolute_import, unicode_literals, print_function import itertools import os import re import types import socket import logging import platform import random import subprocess from string import ascii_letters, digits # Import 3rd-party libs from salt.ext import six from salt.ext.six.moves import range # pylint: disable=import-error,redefined-builtin # Attempt to import wmi try: import wmi import salt.utils.winapi except ImportError: pass # Import salt libs import salt.utils.args import salt.utils.files import salt.utils.path import salt.utils.platform import salt.utils.stringutils import salt.utils.zeromq from salt._compat import ipaddress from salt.exceptions import SaltClientError, SaltSystemExit from salt.utils.decorators.jinja import jinja_filter from salt.utils.versions import LooseVersion # inet_pton does not exist in Windows, this is a workaround if salt.utils.platform.is_windows(): from salt.ext import win_inet_pton # pylint: disable=unused-import log = logging.getLogger(__name__) try: import ctypes import ctypes.util libc = ctypes.cdll.LoadLibrary(ctypes.util.find_library("c")) res_init = libc.__res_init except (ImportError, OSError, AttributeError, TypeError): pass # pylint: disable=C0103 def sanitize_host(host): ''' Sanitize host string. https://tools.ietf.org/html/rfc1123#section-2.1 ''' RFC952_characters = ascii_letters + digits + ".-" return "".join([c for c in host[0:255] if c in RFC952_characters]) def isportopen(host, port): ''' Return status of a port ''' if not 1 <= int(port) <= 65535: return False sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) out = sock.connect_ex((sanitize_host(host), int(port))) return out def host_to_ips(host): ''' Returns a list of IP addresses of a given hostname or None if not found. ''' ips = [] try: for family, socktype, proto, canonname, sockaddr in socket.getaddrinfo( host, 0, socket.AF_UNSPEC, socket.SOCK_STREAM): if family == socket.AF_INET: ip, port = sockaddr elif family == socket.AF_INET6: ip, port, flow_info, scope_id = sockaddr ips.append(ip) if not ips: ips = None except Exception: ips = None return ips def _generate_minion_id(): ''' Get list of possible host names and convention names. :return: ''' # There are three types of hostnames: # 1. Network names. How host is accessed from the network. # 2. Host aliases. They might be not available in all the network or only locally (/etc/hosts) # 3. Convention names, an internal nodename. class DistinctList(list): ''' List, which allows one to append only distinct objects. Needs to work on Python 2.6, because of collections.OrderedDict only since 2.7 version. Override 'filter()' for custom filtering. ''' localhost_matchers = [r'localhost.*', r'ip6-.*', r'127[.]\d', r'0\.0\.0\.0', r'::1.*', r'ipv6-.*', r'fe00::.*', r'fe02::.*', r'1.0.0.*.ip6.arpa'] def append(self, p_object): if p_object and p_object not in self and not self.filter(p_object): super(DistinctList, self).append(p_object) return self def extend(self, iterable): for obj in iterable: self.append(obj) return self def filter(self, element): 'Returns True if element needs to be filtered' for rgx in self.localhost_matchers: if re.match(rgx, element): return True def first(self): return self and self[0] or None hostname = socket.gethostname() hosts = DistinctList().append( salt.utils.stringutils.to_unicode(socket.getfqdn(salt.utils.stringutils.to_bytes(hostname))) ).append(platform.node()).append(hostname) if not hosts: try: for a_nfo in socket.getaddrinfo(hosts.first() or 'localhost', None, socket.AF_INET, socket.SOCK_RAW, socket.IPPROTO_IP, socket.AI_CANONNAME): if len(a_nfo) > 3: hosts.append(a_nfo[3]) except socket.gaierror: log.warning('Cannot resolve address %s info via socket: %s', hosts.first() or 'localhost (N/A)', socket.gaierror) # Universal method for everywhere (Linux, Slowlaris, Windows etc) for f_name in ('/etc/hostname', '/etc/nodename', '/etc/hosts', r'{win}\system32\drivers\etc\hosts'.format(win=os.getenv('WINDIR'))): try: with salt.utils.files.fopen(f_name) as f_hdl: for line in f_hdl: line = salt.utils.stringutils.to_unicode(line) hst = line.strip().split('#')[0].strip().split() if hst: if hst[0][:4] in ('127.', '::1') or len(hst) == 1: hosts.extend(hst) except IOError: pass # include public and private ipaddresses return hosts.extend([addr for addr in ip_addrs() if not ipaddress.ip_address(addr).is_loopback]) def generate_minion_id(): ''' Return only first element of the hostname from all possible list. :return: ''' try: ret = salt.utils.stringutils.to_unicode(_generate_minion_id().first()) except TypeError: ret = None return ret or 'localhost' def get_socket(addr, type=socket.SOCK_STREAM, proto=0): ''' Return a socket object for the addr IP-version agnostic ''' version = ipaddress.ip_address(addr).version if version == 4: family = socket.AF_INET elif version == 6: family = socket.AF_INET6 return socket.socket(family, type, proto) def get_fqhostname(): ''' Returns the fully qualified hostname ''' # try getaddrinfo() fqdn = None try: addrinfo = socket.getaddrinfo( socket.gethostname(), 0, socket.AF_UNSPEC, socket.SOCK_STREAM, socket.SOL_TCP, socket.AI_CANONNAME ) for info in addrinfo: # info struct [family, socktype, proto, canonname, sockaddr] # On Windows `canonname` can be an empty string # This can cause the function to return `None` if len(info) > 3 and info[3]: fqdn = info[3] break except socket.gaierror: pass # NOTE: this used to log.error() but it was later disabled except socket.error as err: log.debug('socket.getaddrinfo() failure while finding fqdn: %s', err) if fqdn is None: fqdn = socket.getfqdn() return fqdn def ip_to_host(ip): ''' Returns the hostname of a given IP ''' try: hostname, aliaslist, ipaddrlist = socket.gethostbyaddr(ip) except Exception as exc: log.debug('salt.utils.network.ip_to_host(%r) failed: %s', ip, exc) hostname = None return hostname # pylint: enable=C0103 def is_reachable_host(entity_name): ''' Returns a bool telling if the entity name is a reachable host (IPv4/IPv6/FQDN/etc). :param hostname: :return: ''' try: assert type(socket.getaddrinfo(entity_name, 0, 0, 0, 0)) == list ret = True except socket.gaierror: ret = False return ret def is_ip(ip): ''' Returns a bool telling if the passed IP is a valid IPv4 or IPv6 address. ''' return is_ipv4(ip) or is_ipv6(ip) def is_ipv4(ip): ''' Returns a bool telling if the value passed to it was a valid IPv4 address ''' try: return ipaddress.ip_address(ip).version == 4 except ValueError: return False def is_ipv6(ip): ''' Returns a bool telling if the value passed to it was a valid IPv6 address ''' try: return ipaddress.ip_address(ip).version == 6 except ValueError: return False def is_subnet(cidr): ''' Returns a bool telling if the passed string is an IPv4 or IPv6 subnet ''' return is_ipv4_subnet(cidr) or is_ipv6_subnet(cidr) def is_ipv4_subnet(cidr): ''' Returns a bool telling if the passed string is an IPv4 subnet ''' try: return '/' in cidr and bool(ipaddress.IPv4Network(cidr)) except Exception: return False def is_ipv6_subnet(cidr): ''' Returns a bool telling if the passed string is an IPv6 subnet ''' try: return '/' in cidr and bool(ipaddress.IPv6Network(cidr)) except Exception: return False @jinja_filter('is_ip') def is_ip_filter(ip, options=None): ''' Returns a bool telling if the passed IP is a valid IPv4 or IPv6 address. ''' return is_ipv4_filter(ip, options=options) or is_ipv6_filter(ip, options=options) def _ip_options_global(ip_obj, version): return not ip_obj.is_private def _ip_options_multicast(ip_obj, version): return ip_obj.is_multicast def _ip_options_loopback(ip_obj, version): return ip_obj.is_loopback def _ip_options_link_local(ip_obj, version): return ip_obj.is_link_local def _ip_options_private(ip_obj, version): return ip_obj.is_private def _ip_options_reserved(ip_obj, version): return ip_obj.is_reserved def _ip_options_site_local(ip_obj, version): if version == 6: return ip_obj.is_site_local return False def _ip_options_unspecified(ip_obj, version): return ip_obj.is_unspecified def _ip_options(ip_obj, version, options=None): # will process and IP options options_fun_map = { 'global': _ip_options_global, 'link-local': _ip_options_link_local, 'linklocal': _ip_options_link_local, 'll': _ip_options_link_local, 'link_local': _ip_options_link_local, 'loopback': _ip_options_loopback, 'lo': _ip_options_loopback, 'multicast': _ip_options_multicast, 'private': _ip_options_private, 'public': _ip_options_global, 'reserved': _ip_options_reserved, 'site-local': _ip_options_site_local, 'sl': _ip_options_site_local, 'site_local': _ip_options_site_local, 'unspecified': _ip_options_unspecified } if not options: return six.text_type(ip_obj) # IP version already checked options_list = [option.strip() for option in options.split(',')] for option, fun in options_fun_map.items(): if option in options_list: fun_res = fun(ip_obj, version) if not fun_res: return None # stop at first failed test # else continue return six.text_type(ip_obj) def _is_ipv(ip, version, options=None): if not version: version = 4 if version not in (4, 6): return None try: ip_obj = ipaddress.ip_address(ip) except ValueError: # maybe it is an IP network try: ip_obj = ipaddress.ip_interface(ip) except ValueError: # nope, still not :( return None if not ip_obj.version == version: return None # has the right version, let's move on return _ip_options(ip_obj, version, options=options) @jinja_filter('is_ipv4') def is_ipv4_filter(ip, options=None): ''' Returns a bool telling if the value passed to it was a valid IPv4 address. ip The IP address. net: False Consider IP addresses followed by netmask. options CSV of options regarding the nature of the IP address. E.g.: loopback, multicast, private etc. ''' _is_ipv4 = _is_ipv(ip, 4, options=options) return isinstance(_is_ipv4, six.string_types) @jinja_filter('is_ipv6') def is_ipv6_filter(ip, options=None): ''' Returns a bool telling if the value passed to it was a valid IPv6 address. ip The IP address. net: False Consider IP addresses followed by netmask. options CSV of options regarding the nature of the IP address. E.g.: loopback, multicast, private etc. ''' _is_ipv6 = _is_ipv(ip, 6, options=options) return isinstance(_is_ipv6, six.string_types) def _ipv_filter(value, version, options=None): if version not in (4, 6): return if isinstance(value, (six.string_types, six.text_type, six.binary_type)): return _is_ipv(value, version, options=options) # calls is_ipv4 or is_ipv6 for `value` elif isinstance(value, (list, tuple, types.GeneratorType)): # calls is_ipv4 or is_ipv6 for each element in the list # os it filters and returns only those elements having the desired IP version return [ _is_ipv(addr, version, options=options) for addr in value if _is_ipv(addr, version, options=options) is not None ] return None @jinja_filter('ipv4') def ipv4(value, options=None): ''' Filters a list and returns IPv4 values only. ''' return _ipv_filter(value, 4, options=options) @jinja_filter('ipv6') def ipv6(value, options=None): ''' Filters a list and returns IPv6 values only. ''' return _ipv_filter(value, 6, options=options) @jinja_filter('ipaddr') def ipaddr(value, options=None): ''' Filters and returns only valid IP objects. ''' ipv4_obj = ipv4(value, options=options) ipv6_obj = ipv6(value, options=options) if ipv4_obj is None or ipv6_obj is None: # an IP address can be either IPv4 either IPv6 # therefofe if the value passed as arg is not a list, at least one of the calls above will return None # if one of them is none, means that we should return only one of them return ipv4_obj or ipv6_obj # one of them else: return ipv4_obj + ipv6_obj # extend lists def _filter_ipaddr(value, options, version=None): ipaddr_filter_out = None if version: if version == 4: ipaddr_filter_out = ipv4(value, options) elif version == 6: ipaddr_filter_out = ipv6(value, options) else: ipaddr_filter_out = ipaddr(value, options) if not ipaddr_filter_out: return if not isinstance(ipaddr_filter_out, (list, tuple, types.GeneratorType)): ipaddr_filter_out = [ipaddr_filter_out] return ipaddr_filter_out @jinja_filter('ip_host') def ip_host(value, options=None, version=None): ''' Returns the interfaces IP address, e.g.: 192.168.0.1/28. ''' ipaddr_filter_out = _filter_ipaddr(value, options=options, version=version) if not ipaddr_filter_out: return if not isinstance(value, (list, tuple, types.GeneratorType)): return six.text_type(ipaddress.ip_interface(ipaddr_filter_out[0])) return [six.text_type(ipaddress.ip_interface(ip_a)) for ip_a in ipaddr_filter_out] def _network_hosts(ip_addr_entry): return [ six.text_type(host) for host in ipaddress.ip_network(ip_addr_entry, strict=False).hosts() ] @jinja_filter('network_hosts') def network_hosts(value, options=None, version=None): ''' Return the list of hosts within a network. .. note:: When running this command with a large IPv6 network, the command will take a long time to gather all of the hosts. ''' ipaddr_filter_out = _filter_ipaddr(value, options=options, version=version) if not ipaddr_filter_out: return if not isinstance(value, (list, tuple, types.GeneratorType)): return _network_hosts(ipaddr_filter_out[0]) return [ _network_hosts(ip_a) for ip_a in ipaddr_filter_out ] def _network_size(ip_addr_entry): return ipaddress.ip_network(ip_addr_entry, strict=False).num_addresses @jinja_filter('network_size') def network_size(value, options=None, version=None): ''' Get the size of a network. ''' ipaddr_filter_out = _filter_ipaddr(value, options=options, version=version) if not ipaddr_filter_out: return if not isinstance(value, (list, tuple, types.GeneratorType)): return _network_size(ipaddr_filter_out[0]) return [ _network_size(ip_a) for ip_a in ipaddr_filter_out ] def natural_ipv4_netmask(ip, fmt='prefixlen'): ''' Returns the "natural" mask of an IPv4 address ''' bits = _ipv4_to_bits(ip) if bits.startswith('11'): mask = '24' elif bits.startswith('1'): mask = '16' else: mask = '8' if fmt == 'netmask': return cidr_to_ipv4_netmask(mask) else: return '/' + mask def rpad_ipv4_network(ip): ''' Returns an IP network address padded with zeros. Ex: '192.168.3' -> '192.168.3.0' '10.209' -> '10.209.0.0' ''' return '.'.join(itertools.islice(itertools.chain(ip.split('.'), '0000'), 0, 4)) def cidr_to_ipv4_netmask(cidr_bits): ''' Returns an IPv4 netmask ''' try: cidr_bits = int(cidr_bits) if not 1 <= cidr_bits <= 32: return '' except ValueError: return '' netmask = '' for idx in range(4): if idx: netmask += '.' if cidr_bits >= 8: netmask += '255' cidr_bits -= 8 else: netmask += '{0:d}'.format(256 - (2 ** (8 - cidr_bits))) cidr_bits = 0 return netmask def _number_of_set_bits_to_ipv4_netmask(set_bits): # pylint: disable=C0103 ''' Returns an IPv4 netmask from the integer representation of that mask. Ex. 0xffffff00 -> '255.255.255.0' ''' return cidr_to_ipv4_netmask(_number_of_set_bits(set_bits)) # pylint: disable=C0103 def _number_of_set_bits(x): ''' Returns the number of bits that are set in a 32bit int ''' # Taken from http://stackoverflow.com/a/4912729. Many thanks! x -= (x >> 1) & 0x55555555 x = ((x >> 2) & 0x33333333) + (x & 0x33333333) x = ((x >> 4) + x) & 0x0f0f0f0f x += x >> 8 x += x >> 16 return x & 0x0000003f # pylint: enable=C0103 def _interfaces_ip(out): ''' Uses ip to return a dictionary of interfaces with various information about each (up/down state, ip address, netmask, and hwaddr) ''' ret = dict() def parse_network(value, cols): ''' Return a tuple of ip, netmask, broadcast based on the current set of cols ''' brd = None scope = None if '/' in value: # we have a CIDR in this address ip, cidr = value.split('/') # pylint: disable=C0103 else: ip = value # pylint: disable=C0103 cidr = 32 if type_ == 'inet': mask = cidr_to_ipv4_netmask(int(cidr)) if 'brd' in cols: brd = cols[cols.index('brd') + 1] elif type_ == 'inet6': mask = cidr if 'scope' in cols: scope = cols[cols.index('scope') + 1] return (ip, mask, brd, scope) groups = re.compile('\r?\n\\d').split(out) for group in groups: iface = None data = dict() for line in group.splitlines(): if ' ' not in line: continue match = re.match(r'^\d*:\s+([\w.\-]+)(?:@)?([\w.\-]+)?:\s+<(.+)>', line) if match: iface, parent, attrs = match.groups() if 'UP' in attrs.split(','): data['up'] = True else: data['up'] = False if parent: data['parent'] = parent continue cols = line.split() if len(cols) >= 2: type_, value = tuple(cols[0:2]) iflabel = cols[-1:][0] if type_ in ('inet', 'inet6'): if 'secondary' not in cols: ipaddr, netmask, broadcast, scope = parse_network(value, cols) if type_ == 'inet': if 'inet' not in data: data['inet'] = list() addr_obj = dict() addr_obj['address'] = ipaddr addr_obj['netmask'] = netmask addr_obj['broadcast'] = broadcast addr_obj['label'] = iflabel data['inet'].append(addr_obj) elif type_ == 'inet6': if 'inet6' not in data: data['inet6'] = list() addr_obj = dict() addr_obj['address'] = ipaddr addr_obj['prefixlen'] = netmask addr_obj['scope'] = scope data['inet6'].append(addr_obj) else: if 'secondary' not in data: data['secondary'] = list() ip_, mask, brd, scp = parse_network(value, cols) data['secondary'].append({ 'type': type_, 'address': ip_, 'netmask': mask, 'broadcast': brd, 'label': iflabel, }) del ip_, mask, brd, scp elif type_.startswith('link'): data['hwaddr'] = value if iface: ret[iface] = data del iface, data return ret def _interfaces_ifconfig(out): ''' Uses ifconfig to return a dictionary of interfaces with various information about each (up/down state, ip address, netmask, and hwaddr) ''' ret = dict() piface = re.compile(r'^([^\s:]+)') pmac = re.compile('.*?(?:HWaddr|ether|address:|lladdr) ([0-9a-fA-F:]+)') if salt.utils.platform.is_sunos(): pip = re.compile(r'.*?(?:inet\s+)([0-9]+\.[0-9]+\.[0-9]+\.[0-9]+)(.*)') pip6 = re.compile('.*?(?:inet6 )([0-9a-fA-F:]+)') pmask6 = re.compile(r'.*?(?:inet6 [0-9a-fA-F:]+/(\d+)).*') else: pip = re.compile(r'.*?(?:inet addr:|inet [^\d]*)(.*?)\s') pip6 = re.compile('.*?(?:inet6 addr: (.*?)/|inet6 )([0-9a-fA-F:]+)') pmask6 = re.compile(r'.*?(?:inet6 addr: [0-9a-fA-F:]+/(\d+)|prefixlen (\d+))(?: Scope:([a-zA-Z]+)| scopeid (0x[0-9a-fA-F]))?') pmask = re.compile(r'.*?(?:Mask:|netmask )(?:((?:0x)?[0-9a-fA-F]{8})|([\d\.]+))') pupdown = re.compile('UP') pbcast = re.compile(r'.*?(?:Bcast:|broadcast )([\d\.]+)') groups = re.compile('\r?\n(?=\\S)').split(out) for group in groups: data = dict() iface = '' updown = False for line in group.splitlines(): miface = piface.match(line) mmac = pmac.match(line) mip = pip.match(line) mip6 = pip6.match(line) mupdown = pupdown.search(line) if miface: iface = miface.group(1) if mmac: data['hwaddr'] = mmac.group(1) if salt.utils.platform.is_sunos(): expand_mac = [] for chunk in data['hwaddr'].split(':'): expand_mac.append('0{0}'.format(chunk) if len(chunk) < 2 else '{0}'.format(chunk)) data['hwaddr'] = ':'.join(expand_mac) if mip: if 'inet' not in data: data['inet'] = list() addr_obj = dict() addr_obj['address'] = mip.group(1) mmask = pmask.match(line) if mmask: if mmask.group(1): mmask = _number_of_set_bits_to_ipv4_netmask( int(mmask.group(1), 16)) else: mmask = mmask.group(2) addr_obj['netmask'] = mmask mbcast = pbcast.match(line) if mbcast: addr_obj['broadcast'] = mbcast.group(1) data['inet'].append(addr_obj) if mupdown: updown = True if mip6: if 'inet6' not in data: data['inet6'] = list() addr_obj = dict() addr_obj['address'] = mip6.group(1) or mip6.group(2) mmask6 = pmask6.match(line) if mmask6: addr_obj['prefixlen'] = mmask6.group(1) or mmask6.group(2) if not salt.utils.platform.is_sunos(): ipv6scope = mmask6.group(3) or mmask6.group(4) addr_obj['scope'] = ipv6scope.lower() if ipv6scope is not None else ipv6scope # SunOS sometimes has ::/0 as inet6 addr when using addrconf if not salt.utils.platform.is_sunos() \ or addr_obj['address'] != '::' \ and addr_obj['prefixlen'] != 0: data['inet6'].append(addr_obj) data['up'] = updown if iface in ret: # SunOS optimization, where interfaces occur twice in 'ifconfig -a' # output with the same name: for ipv4 and then for ipv6 addr family. # Every instance has it's own 'UP' status and we assume that ipv4 # status determines global interface status. # # merge items with higher priority for older values # after that merge the inet and inet6 sub items for both ret[iface] = dict(list(data.items()) + list(ret[iface].items())) if 'inet' in data: ret[iface]['inet'].extend(x for x in data['inet'] if x not in ret[iface]['inet']) if 'inet6' in data: ret[iface]['inet6'].extend(x for x in data['inet6'] if x not in ret[iface]['inet6']) else: ret[iface] = data del data return ret def linux_interfaces(): ''' Obtain interface information for *NIX/BSD variants ''' ifaces = dict() ip_path = salt.utils.path.which('ip') ifconfig_path = None if ip_path else salt.utils.path.which('ifconfig') if ip_path: cmd1 = subprocess.Popen( '{0} link show'.format(ip_path), shell=True, close_fds=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT).communicate()[0] cmd2 = subprocess.Popen( '{0} addr show'.format(ip_path), shell=True, close_fds=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT).communicate()[0] ifaces = _interfaces_ip("{0}\n{1}".format( salt.utils.stringutils.to_str(cmd1), salt.utils.stringutils.to_str(cmd2))) elif ifconfig_path: cmd = subprocess.Popen( '{0} -a'.format(ifconfig_path), shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT).communicate()[0] ifaces = _interfaces_ifconfig(salt.utils.stringutils.to_str(cmd)) return ifaces def _netbsd_interfaces_ifconfig(out): ''' Uses ifconfig to return a dictionary of interfaces with various information about each (up/down state, ip address, netmask, and hwaddr) ''' ret = dict() piface = re.compile(r'^([^\s:]+)') pmac = re.compile('.*?address: ([0-9a-f:]+)') pip = re.compile(r'.*?inet [^\d]*(.*?)/([\d]*)\s') pip6 = re.compile(r'.*?inet6 ([0-9a-f:]+)%([a-zA-Z0-9]*)/([\d]*)\s') pupdown = re.compile('UP') pbcast = re.compile(r'.*?broadcast ([\d\.]+)') groups = re.compile('\r?\n(?=\\S)').split(out) for group in groups: data = dict() iface = '' updown = False for line in group.splitlines(): miface = piface.match(line) mmac = pmac.match(line) mip = pip.match(line) mip6 = pip6.match(line) mupdown = pupdown.search(line) if miface: iface = miface.group(1) if mmac: data['hwaddr'] = mmac.group(1) if mip: if 'inet' not in data: data['inet'] = list() addr_obj = dict() addr_obj['address'] = mip.group(1) mmask = mip.group(2) if mip.group(2): addr_obj['netmask'] = cidr_to_ipv4_netmask(mip.group(2)) mbcast = pbcast.match(line) if mbcast: addr_obj['broadcast'] = mbcast.group(1) data['inet'].append(addr_obj) if mupdown: updown = True if mip6: if 'inet6' not in data: data['inet6'] = list() addr_obj = dict() addr_obj['address'] = mip6.group(1) mmask6 = mip6.group(3) addr_obj['scope'] = mip6.group(2) addr_obj['prefixlen'] = mip6.group(3) data['inet6'].append(addr_obj) data['up'] = updown ret[iface] = data del data return ret def netbsd_interfaces(): ''' Obtain interface information for NetBSD >= 8 where the ifconfig output diverged from other BSD variants (Netmask is now part of the address) ''' # NetBSD versions prior to 8.0 can still use linux_interfaces() if LooseVersion(os.uname()[2]) < LooseVersion('8.0'): return linux_interfaces() ifconfig_path = salt.utils.path.which('ifconfig') cmd = subprocess.Popen( '{0} -a'.format(ifconfig_path), shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT).communicate()[0] return _netbsd_interfaces_ifconfig(salt.utils.stringutils.to_str(cmd)) def _interfaces_ipconfig(out): ''' Returns a dictionary of interfaces with various information about each (up/down state, ip address, netmask, and hwaddr) NOTE: This is not used by any function and may be able to be removed in the future. ''' ifaces = dict() iface = None adapter_iface_regex = re.compile(r'adapter (\S.+):$') for line in out.splitlines(): if not line: continue # TODO what does Windows call Infiniband and 10/40gige adapters if line.startswith('Ethernet'): iface = ifaces[adapter_iface_regex.search(line).group(1)] iface['up'] = True addr = None continue if iface: key, val = line.split(',', 1) key = key.strip(' .') val = val.strip() if addr and key == 'Subnet Mask': addr['netmask'] = val elif key in ('IP Address', 'IPv4 Address'): if 'inet' not in iface: iface['inet'] = list() addr = {'address': val.rstrip('(Preferred)'), 'netmask': None, 'broadcast': None} # TODO find the broadcast iface['inet'].append(addr) elif 'IPv6 Address' in key: if 'inet6' not in iface: iface['inet'] = list() # XXX What is the prefixlen!? addr = {'address': val.rstrip('(Preferred)'), 'prefixlen': None} iface['inet6'].append(addr) elif key == 'Physical Address': iface['hwaddr'] = val elif key == 'Media State': # XXX seen used for tunnel adaptors # might be useful iface['up'] = (val != 'Media disconnected') def win_interfaces(): ''' Obtain interface information for Windows systems ''' with salt.utils.winapi.Com(): c = wmi.WMI() ifaces = {} for iface in c.Win32_NetworkAdapterConfiguration(IPEnabled=1): ifaces[iface.Description] = dict() if iface.MACAddress: ifaces[iface.Description]['hwaddr'] = iface.MACAddress if iface.IPEnabled: ifaces[iface.Description]['up'] = True for ip in iface.IPAddress: if '.' in ip: if 'inet' not in ifaces[iface.Description]: ifaces[iface.Description]['inet'] = [] item = {'address': ip, 'label': iface.Description} if iface.DefaultIPGateway: broadcast = next((i for i in iface.DefaultIPGateway if '.' in i), '') if broadcast: item['broadcast'] = broadcast if iface.IPSubnet: netmask = next((i for i in iface.IPSubnet if '.' in i), '') if netmask: item['netmask'] = netmask ifaces[iface.Description]['inet'].append(item) if ':' in ip: if 'inet6' not in ifaces[iface.Description]: ifaces[iface.Description]['inet6'] = [] item = {'address': ip} if iface.DefaultIPGateway: broadcast = next((i for i in iface.DefaultIPGateway if ':' in i), '') if broadcast: item['broadcast'] = broadcast if iface.IPSubnet: netmask = next((i for i in iface.IPSubnet if ':' in i), '') if netmask: item['netmask'] = netmask ifaces[iface.Description]['inet6'].append(item) else: ifaces[iface.Description]['up'] = False return ifaces def interfaces(): ''' Return a dictionary of information about all the interfaces on the minion ''' if salt.utils.platform.is_windows(): return win_interfaces() elif salt.utils.platform.is_netbsd(): return netbsd_interfaces() else: return linux_interfaces() def get_net_start(ipaddr, netmask): ''' Return the address of the network ''' net = ipaddress.ip_network('{0}/{1}'.format(ipaddr, netmask), strict=False) return six.text_type(net.network_address) def get_net_size(mask): ''' Turns an IPv4 netmask into it's corresponding prefix length (255.255.255.0 -> 24 as in 192.168.1.10/24). ''' binary_str = '' for octet in mask.split('.'): binary_str += bin(int(octet))[2:].zfill(8) return len(binary_str.rstrip('0')) def calc_net(ipaddr, netmask=None): ''' Takes IP (CIDR notation supported) and optionally netmask and returns the network in CIDR-notation. (The IP can be any IP inside the subnet) ''' if netmask is not None: ipaddr = '{0}/{1}'.format(ipaddr, netmask) return six.text_type(ipaddress.ip_network(ipaddr, strict=False)) def _get_iface_info(iface): ''' If `iface` is available, return interface info and no error, otherwise return no info and log and return an error ''' iface_info = interfaces() if iface in iface_info.keys(): return iface_info, False else: error_msg = ('Interface "{0}" not in available interfaces: "{1}"' ''.format(iface, '", "'.join(iface_info.keys()))) log.error(error_msg) return None, error_msg def _hw_addr_aix(iface): ''' Return the hardware address (a.k.a. MAC address) for a given interface on AIX MAC address not available in through interfaces ''' cmd = subprocess.Popen( 'entstat -d {0} | grep \'Hardware Address\''.format(iface), shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT).communicate()[0] if cmd: comps = cmd.split(' ') if len(comps) == 3: mac_addr = comps[2].strip('\'').strip() return mac_addr error_msg = ('Interface "{0}" either not available or does not contain a hardware address'.format(iface)) log.error(error_msg) return error_msg def hw_addr(iface): ''' Return the hardware address (a.k.a. MAC address) for a given interface .. versionchanged:: 2016.11.4 Added support for AIX ''' if salt.utils.platform.is_aix(): return _hw_addr_aix iface_info, error = _get_iface_info(iface) if error is False: return iface_info.get(iface, {}).get('hwaddr', '') else: return error def interface(iface): ''' Return the details of `iface` or an error if it does not exist ''' iface_info, error = _get_iface_info(iface) if error is False: return iface_info.get(iface, {}).get('inet', '') else: return error def interface_ip(iface): ''' Return `iface` IPv4 addr or an error if `iface` does not exist ''' iface_info, error = _get_iface_info(iface) if error is False: inet = iface_info.get(iface, {}).get('inet', None) return inet[0].get('address', '') if inet else '' else: return error def _subnets(proto='inet', interfaces_=None): ''' Returns a list of subnets to which the host belongs ''' if interfaces_ is None: ifaces = interfaces() elif isinstance(interfaces_, list): ifaces = {} for key, value in six.iteritems(interfaces()): if key in interfaces_: ifaces[key] = value else: ifaces = {interfaces_: interfaces().get(interfaces_, {})} ret = set() if proto == 'inet': subnet = 'netmask' dflt_cidr = 32 elif proto == 'inet6': subnet = 'prefixlen' dflt_cidr = 128 else: log.error('Invalid proto %s calling subnets()', proto) return for ip_info in six.itervalues(ifaces): addrs = ip_info.get(proto, []) addrs.extend([addr for addr in ip_info.get('secondary', []) if addr.get('type') == proto]) for intf in addrs: if subnet in intf: intf = ipaddress.ip_interface('{0}/{1}'.format(intf['address'], intf[subnet])) else: intf = ipaddress.ip_interface('{0}/{1}'.format(intf['address'], dflt_cidr)) if not intf.is_loopback: ret.add(intf.network) return [six.text_type(net) for net in sorted(ret)] def subnets(interfaces=None): ''' Returns a list of IPv4 subnets to which the host belongs ''' return _subnets('inet', interfaces_=interfaces) def subnets6(): ''' Returns a list of IPv6 subnets to which the host belongs ''' return _subnets('inet6') def in_subnet(cidr, addr=None): ''' Returns True if host or (any of) addrs is within specified subnet, otherwise False ''' try: cidr = ipaddress.ip_network(cidr) except ValueError: log.error('Invalid CIDR \'%s\'', cidr) return False if addr is None: addr = ip_addrs() addr.extend(ip_addrs6()) elif not isinstance(addr, (list, tuple)): addr = (addr,) return any(ipaddress.ip_address(item) in cidr for item in addr) def _ip_addrs(interface=None, include_loopback=False, interface_data=None, proto='inet'): ''' Return the full list of IP adresses matching the criteria proto = inet|inet6 ''' ret = set() ifaces = interface_data \ if isinstance(interface_data, dict) \ else interfaces() if interface is None: target_ifaces = ifaces else: target_ifaces = dict([(k, v) for k, v in six.iteritems(ifaces) if k == interface]) if not target_ifaces: log.error('Interface %s not found.', interface) for ip_info in six.itervalues(target_ifaces): addrs = ip_info.get(proto, []) addrs.extend([addr for addr in ip_info.get('secondary', []) if addr.get('type') == proto]) for addr in addrs: addr = ipaddress.ip_address(addr.get('address')) if not addr.is_loopback or include_loopback: ret.add(addr) return [six.text_type(addr) for addr in sorted(ret)] def ip_addrs(interface=None, include_loopback=False, interface_data=None): ''' Returns a list of IPv4 addresses assigned to the host. 127.0.0.1 is ignored, unless 'include_loopback=True' is indicated. If 'interface' is provided, then only IP addresses from that interface will be returned. ''' return _ip_addrs(interface, include_loopback, interface_data, 'inet') def ip_addrs6(interface=None, include_loopback=False, interface_data=None): ''' Returns a list of IPv6 addresses assigned to the host. ::1 is ignored, unless 'include_loopback=True' is indicated. If 'interface' is provided, then only IP addresses from that interface will be returned. ''' return _ip_addrs(interface, include_loopback, interface_data, 'inet6') def hex2ip(hex_ip, invert=False): ''' Convert a hex string to an ip, if a failure occurs the original hex is returned. If 'invert=True' assume that ip from /proc/net/<proto> ''' if len(hex_ip) == 32: # ipv6 ip = [] for i in range(0, 32, 8): ip_part = hex_ip[i:i + 8] ip_part = [ip_part[x:x + 2] for x in range(0, 8, 2)] if invert: ip.append("{0[3]}{0[2]}:{0[1]}{0[0]}".format(ip_part)) else: ip.append("{0[0]}{0[1]}:{0[2]}{0[3]}".format(ip_part)) try: address = ipaddress.IPv6Address(":".join(ip)) if address.ipv4_mapped: return str(address.ipv4_mapped) else: return address.compressed except ipaddress.AddressValueError as ex: log.error('hex2ip - ipv6 address error: %s', ex) return hex_ip try: hip = int(hex_ip, 16) except ValueError: return hex_ip if invert: return '{3}.{2}.{1}.{0}'.format(hip >> 24 & 255, hip >> 16 & 255, hip >> 8 & 255, hip & 255) return '{0}.{1}.{2}.{3}'.format(hip >> 24 & 255, hip >> 16 & 255, hip >> 8 & 255, hip & 255) def mac2eui64(mac, prefix=None): ''' Convert a MAC address to a EUI64 identifier or, with prefix provided, a full IPv6 address ''' # http://tools.ietf.org/html/rfc4291#section-2.5.1 eui64 = re.sub(r'[.:-]', '', mac).lower() eui64 = eui64[0:6] + 'fffe' + eui64[6:] eui64 = hex(int(eui64[0:2], 16) | 2)[2:].zfill(2) + eui64[2:] if prefix is None: return ':'.join(re.findall(r'.{4}', eui64)) else: try: net = ipaddress.ip_network(prefix, strict=False) euil = int('0x{0}'.format(eui64), 16) return '{0}/{1}'.format(net[euil], net.prefixlen) except Exception: return def active_tcp(): ''' Return a dict describing all active tcp connections as quickly as possible ''' ret = {} for statf in ['/proc/net/tcp', '/proc/net/tcp6']: if os.path.isfile(statf): with salt.utils.files.fopen(statf, 'rb') as fp_: for line in fp_: line = salt.utils.stringutils.to_unicode(line) if line.strip().startswith('sl'): continue iret = _parse_tcp_line(line) sl = next(iter(iret)) if iret[sl]['state'] == 1: # 1 is ESTABLISHED del iret[sl]['state'] ret[len(ret)] = iret[sl] return ret def local_port_tcp(port): ''' Return a set of remote ip addrs attached to the specified local port ''' ret = _remotes_on(port, 'local_port') return ret def remote_port_tcp(port): ''' Return a set of ip addrs the current host is connected to on given port ''' ret = _remotes_on(port, 'remote_port') return ret def _remotes_on(port, which_end): ''' Return a set of ip addrs active tcp connections ''' port = int(port) ret = _netlink_tool_remote_on(port, which_end) if ret is not None: return ret ret = set() proc_available = False for statf in ['/proc/net/tcp', '/proc/net/tcp6']: if os.path.isfile(statf): proc_available = True with salt.utils.files.fopen(statf, 'r') as fp_: for line in fp_: line = salt.utils.stringutils.to_unicode(line) if line.strip().startswith('sl'): continue iret = _parse_tcp_line(line) sl = next(iter(iret)) if iret[sl][which_end] == port and iret[sl]['state'] == 1: # 1 is ESTABLISHED ret.add(iret[sl]['remote_addr']) if not proc_available: # Fallback to use OS specific tools if salt.utils.platform.is_sunos(): return _sunos_remotes_on(port, which_end) if salt.utils.platform.is_freebsd(): return _freebsd_remotes_on(port, which_end) if salt.utils.platform.is_netbsd(): return _netbsd_remotes_on(port, which_end) if salt.utils.platform.is_openbsd(): return _openbsd_remotes_on(port, which_end) if salt.utils.platform.is_windows(): return _windows_remotes_on(port, which_end) if salt.utils.platform.is_aix(): return _aix_remotes_on(port, which_end) return _linux_remotes_on(port, which_end) return ret def _parse_tcp_line(line): ''' Parse a single line from the contents of /proc/net/tcp or /proc/net/tcp6 ''' ret = {} comps = line.strip().split() sl = comps[0].rstrip(':') ret[sl] = {} l_addr, l_port = comps[1].split(':') r_addr, r_port = comps[2].split(':') ret[sl]['local_addr'] = hex2ip(l_addr, True) ret[sl]['local_port'] = int(l_port, 16) ret[sl]['remote_addr'] = hex2ip(r_addr, True) ret[sl]['remote_port'] = int(r_port, 16) ret[sl]['state'] = int(comps[3], 16) return ret def _netlink_tool_remote_on(port, which_end): ''' Returns set of ipv4 host addresses of remote established connections on local or remote tcp port. Parses output of shell 'ss' to get connections [root@salt-master ~]# ss -ant State Recv-Q Send-Q Local Address:Port Peer Address:Port LISTEN 0 511 *:80 *:* LISTEN 0 128 *:22 *:* ESTAB 0 0 127.0.0.1:56726 127.0.0.1:4505 ''' remotes = set() valid = False try: data = subprocess.check_output(['ss', '-ant']) # pylint: disable=minimum-python-version except subprocess.CalledProcessError: log.error('Failed ss') raise except OSError: # not command "No such file or directory" return None lines = salt.utils.stringutils.to_str(data).split('\n') for line in lines: if 'Address:Port' in line: # ss tools may not be valid valid = True continue elif 'ESTAB' not in line: continue chunks = line.split() local_host, local_port = chunks[3].split(':', 1) remote_host, remote_port = chunks[4].split(':', 1) if which_end == 'remote_port' and int(remote_port) != port: continue if which_end == 'local_port' and int(local_port) != port: continue remotes.add(remote_host) if valid is False: remotes = None return remotes def _sunos_remotes_on(port, which_end): ''' SunOS specific helper function. Returns set of ipv4 host addresses of remote established connections on local or remote tcp port. Parses output of shell 'netstat' to get connections [root@salt-master ~]# netstat -f inet -n TCP: IPv4 Local Address Remote Address Swind Send-Q Rwind Recv-Q State -------------------- -------------------- ----- ------ ----- ------ ----------- 10.0.0.101.4505 10.0.0.1.45329 1064800 0 1055864 0 ESTABLISHED 10.0.0.101.4505 10.0.0.100.50798 1064800 0 1055864 0 ESTABLISHED ''' remotes = set() try: data = subprocess.check_output(['netstat', '-f', 'inet', '-n']) # pylint: disable=minimum-python-version except subprocess.CalledProcessError: log.error('Failed netstat') raise lines = salt.utils.stringutils.to_str(data).split('\n') for line in lines: if 'ESTABLISHED' not in line: continue chunks = line.split() local_host, local_port = chunks[0].rsplit('.', 1) remote_host, remote_port = chunks[1].rsplit('.', 1) if which_end == 'remote_port' and int(remote_port) != port: continue if which_end == 'local_port' and int(local_port) != port: continue remotes.add(remote_host) return remotes def _freebsd_remotes_on(port, which_end): ''' Returns set of ipv4 host addresses of remote established connections on local tcp port port. Parses output of shell 'sockstat' (FreeBSD) to get connections $ sudo sockstat -4 USER COMMAND PID FD PROTO LOCAL ADDRESS FOREIGN ADDRESS root python2.7 1456 29 tcp4 *:4505 *:* root python2.7 1445 17 tcp4 *:4506 *:* root python2.7 1294 14 tcp4 127.0.0.1:11813 127.0.0.1:4505 root python2.7 1294 41 tcp4 127.0.0.1:61115 127.0.0.1:4506 $ sudo sockstat -4 -c -p 4506 USER COMMAND PID FD PROTO LOCAL ADDRESS FOREIGN ADDRESS root python2.7 1294 41 tcp4 127.0.0.1:61115 127.0.0.1:4506 ''' port = int(port) remotes = set() try: cmd = salt.utils.args.shlex_split('sockstat -4 -c -p {0}'.format(port)) data = subprocess.check_output(cmd) # pylint: disable=minimum-python-version except subprocess.CalledProcessError as ex: log.error('Failed "sockstat" with returncode = %s', ex.returncode) raise lines = salt.utils.stringutils.to_str(data).split('\n') for line in lines: chunks = line.split() if not chunks: continue # ['root', 'python2.7', '1456', '37', 'tcp4', # '127.0.0.1:4505-', '127.0.0.1:55703'] # print chunks if 'COMMAND' in chunks[1]: continue # ignore header if len(chunks) < 2: continue # sockstat -4 -c -p 4506 does this with high PIDs: # USER COMMAND PID FD PROTO LOCAL ADDRESS FOREIGN ADDRESS # salt-master python2.781106 35 tcp4 192.168.12.34:4506 192.168.12.45:60143 local = chunks[-2] remote = chunks[-1] lhost, lport = local.split(':') rhost, rport = remote.split(':') if which_end == 'local' and int(lport) != port: # ignore if local port not port continue if which_end == 'remote' and int(rport) != port: # ignore if remote port not port continue remotes.add(rhost) return remotes def _netbsd_remotes_on(port, which_end): ''' Returns set of ipv4 host addresses of remote established connections on local tcp port port. Parses output of shell 'sockstat' (NetBSD) to get connections $ sudo sockstat -4 -n USER COMMAND PID FD PROTO LOCAL ADDRESS FOREIGN ADDRESS root python2.7 1456 29 tcp *.4505 *.* root python2.7 1445 17 tcp *.4506 *.* root python2.7 1294 14 tcp 127.0.0.1.11813 127.0.0.1.4505 root python2.7 1294 41 tcp 127.0.0.1.61115 127.0.0.1.4506 $ sudo sockstat -4 -c -n -p 4506 USER COMMAND PID FD PROTO LOCAL ADDRESS FOREIGN ADDRESS root python2.7 1294 41 tcp 127.0.0.1.61115 127.0.0.1.4506 ''' port = int(port) remotes = set() try: cmd = salt.utils.args.shlex_split('sockstat -4 -c -n -p {0}'.format(port)) data = subprocess.check_output(cmd) # pylint: disable=minimum-python-version except subprocess.CalledProcessError as ex: log.error('Failed "sockstat" with returncode = %s', ex.returncode) raise lines = salt.utils.stringutils.to_str(data).split('\n') for line in lines: chunks = line.split() if not chunks: continue # ['root', 'python2.7', '1456', '37', 'tcp', # '127.0.0.1.4505-', '127.0.0.1.55703'] # print chunks if 'COMMAND' in chunks[1]: continue # ignore header if len(chunks) < 2: continue local = chunks[5].split('.') lport = local.pop() lhost = '.'.join(local) remote = chunks[6].split('.') rport = remote.pop() rhost = '.'.join(remote) if which_end == 'local' and int(lport) != port: # ignore if local port not port continue if which_end == 'remote' and int(rport) != port: # ignore if remote port not port continue remotes.add(rhost) return remotes def _openbsd_remotes_on(port, which_end): ''' OpenBSD specific helper function. Returns set of ipv4 host addresses of remote established connections on local or remote tcp port. Parses output of shell 'netstat' to get connections $ netstat -nf inet Active Internet connections Proto Recv-Q Send-Q Local Address Foreign Address (state) tcp 0 0 10.0.0.101.4505 10.0.0.1.45329 ESTABLISHED tcp 0 0 10.0.0.101.4505 10.0.0.100.50798 ESTABLISHED ''' remotes = set() try: data = subprocess.check_output(['netstat', '-nf', 'inet']) # pylint: disable=minimum-python-version except subprocess.CalledProcessError: log.error('Failed netstat') raise lines = data.split('\n') for line in lines: if 'ESTABLISHED' not in line: continue chunks = line.split() local_host, local_port = chunks[3].rsplit('.', 1) remote_host, remote_port = chunks[4].rsplit('.', 1) if which_end == 'remote_port' and int(remote_port) != port: continue if which_end == 'local_port' and int(local_port) != port: continue remotes.add(remote_host) return remotes def _windows_remotes_on(port, which_end): r''' Windows specific helper function. Returns set of ipv4 host addresses of remote established connections on local or remote tcp port. Parses output of shell 'netstat' to get connections C:\>netstat -n Active Connections Proto Local Address Foreign Address State TCP 10.2.33.17:3007 130.164.12.233:10123 ESTABLISHED TCP 10.2.33.17:3389 130.164.30.5:10378 ESTABLISHED ''' remotes = set() try: data = subprocess.check_output(['netstat', '-n']) # pylint: disable=minimum-python-version except subprocess.CalledProcessError: log.error('Failed netstat') raise lines = salt.utils.stringutils.to_str(data).split('\n') for line in lines: if 'ESTABLISHED' not in line: continue chunks = line.split() local_host, local_port = chunks[1].rsplit(':', 1) remote_host, remote_port = chunks[2].rsplit(':', 1) if which_end == 'remote_port' and int(remote_port) != port: continue if which_end == 'local_port' and int(local_port) != port: continue remotes.add(remote_host) return remotes def _linux_remotes_on(port, which_end): ''' Linux specific helper function. Returns set of ip host addresses of remote established connections on local tcp port port. Parses output of shell 'lsof' to get connections $ sudo lsof -iTCP:4505 -n COMMAND PID USER FD TYPE DEVICE SIZE/OFF NODE NAME Python 9971 root 35u IPv4 0x18a8464a29ca329d 0t0 TCP *:4505 (LISTEN) Python 9971 root 37u IPv4 0x18a8464a29b2b29d 0t0 TCP 127.0.0.1:4505->127.0.0.1:55703 (ESTABLISHED) Python 10152 root 22u IPv4 0x18a8464a29c8cab5 0t0 TCP 127.0.0.1:55703->127.0.0.1:4505 (ESTABLISHED) Python 10153 root 22u IPv4 0x18a8464a29c8cab5 0t0 TCP [fe80::249a]:4505->[fe80::150]:59367 (ESTABLISHED) ''' remotes = set() try: data = subprocess.check_output( ['lsof', '-iTCP:{0:d}'.format(port), '-n', '-P'] # pylint: disable=minimum-python-version ) except subprocess.CalledProcessError as ex: if ex.returncode == 1: # Lsof return 1 if any error was detected, including the failure # to locate Internet addresses, and it is not an error in this case. log.warning('"lsof" returncode = 1, likely no active TCP sessions.') return remotes log.error('Failed "lsof" with returncode = %s', ex.returncode) raise lines = salt.utils.stringutils.to_str(data).split('\n') for line in lines: chunks = line.split() if not chunks: continue # ['Python', '9971', 'root', '37u', 'IPv4', '0x18a8464a29b2b29d', '0t0', # 'TCP', '127.0.0.1:4505->127.0.0.1:55703', '(ESTABLISHED)'] # print chunks if 'COMMAND' in chunks[0]: continue # ignore header if 'ESTABLISHED' not in chunks[-1]: continue # ignore if not ESTABLISHED # '127.0.0.1:4505->127.0.0.1:55703' local, remote = chunks[8].split('->') _, lport = local.rsplit(':', 1) rhost, rport = remote.rsplit(':', 1) if which_end == 'remote_port' and int(rport) != port: continue if which_end == 'local_port' and int(lport) != port: continue remotes.add(rhost.strip("[]")) return remotes def _aix_remotes_on(port, which_end): ''' AIX specific helper function. Returns set of ipv4 host addresses of remote established connections on local or remote tcp port. Parses output of shell 'netstat' to get connections root@la68pp002_pub:/opt/salt/lib/python2.7/site-packages/salt/modules# netstat -f inet -n Active Internet connections Proto Recv-Q Send-Q Local Address Foreign Address (state) tcp4 0 0 172.29.149.95.50093 209.41.78.13.4505 ESTABLISHED tcp4 0 0 127.0.0.1.9514 *.* LISTEN tcp4 0 0 127.0.0.1.9515 *.* LISTEN tcp4 0 0 127.0.0.1.199 127.0.0.1.32779 ESTABLISHED tcp4 0 0 127.0.0.1.32779 127.0.0.1.199 ESTABLISHED tcp4 0 40 172.29.149.95.22 172.29.96.83.41022 ESTABLISHED tcp4 0 0 172.29.149.95.22 172.29.96.83.41032 ESTABLISHED tcp4 0 0 127.0.0.1.32771 127.0.0.1.32775 ESTABLISHED tcp 0 0 127.0.0.1.32775 127.0.0.1.32771 ESTABLISHED tcp4 0 0 127.0.0.1.32771 127.0.0.1.32776 ESTABLISHED tcp 0 0 127.0.0.1.32776 127.0.0.1.32771 ESTABLISHED tcp4 0 0 127.0.0.1.32771 127.0.0.1.32777 ESTABLISHED tcp 0 0 127.0.0.1.32777 127.0.0.1.32771 ESTABLISHED tcp4 0 0 127.0.0.1.32771 127.0.0.1.32778 ESTABLISHED tcp 0 0 127.0.0.1.32778 127.0.0.1.32771 ESTABLISHED ''' remotes = set() try: data = subprocess.check_output(['netstat', '-f', 'inet', '-n']) # pylint: disable=minimum-python-version except subprocess.CalledProcessError: log.error('Failed netstat') raise lines = salt.utils.stringutils.to_str(data).split('\n') for line in lines: if 'ESTABLISHED' not in line: continue chunks = line.split() local_host, local_port = chunks[3].rsplit('.', 1) remote_host, remote_port = chunks[4].rsplit('.', 1) if which_end == 'remote_port' and int(remote_port) != port: continue if which_end == 'local_port' and int(local_port) != port: continue remotes.add(remote_host) return remotes @jinja_filter('gen_mac') def gen_mac(prefix='AC:DE:48'): ''' Generates a MAC address with the defined OUI prefix. Common prefixes: - ``00:16:3E`` -- Xen - ``00:18:51`` -- OpenVZ - ``00:50:56`` -- VMware (manually generated) - ``52:54:00`` -- QEMU/KVM - ``AC:DE:48`` -- PRIVATE References: - http://standards.ieee.org/develop/regauth/oui/oui.txt - https://www.wireshark.org/tools/oui-lookup.html - https://en.wikipedia.org/wiki/MAC_address ''' return '{0}:{1:02X}:{2:02X}:{3:02X}'.format(prefix, random.randint(0, 0xff), random.randint(0, 0xff), random.randint(0, 0xff)) @jinja_filter('mac_str_to_bytes') def mac_str_to_bytes(mac_str): ''' Convert a MAC address string into bytes. Works with or without separators: b1 = mac_str_to_bytes('08:00:27:13:69:77') b2 = mac_str_to_bytes('080027136977') assert b1 == b2 assert isinstance(b1, bytes) ''' if len(mac_str) == 12: pass elif len(mac_str) == 17: sep = mac_str[2] mac_str = mac_str.replace(sep, '') else: raise ValueError('Invalid MAC address') chars = (int(mac_str[s:s+2], 16) for s in range(0, 12, 2)) return bytes(chars) if six.PY3 else b''.join(chr(x) for x in chars) def refresh_dns(): ''' issue #21397: force glibc to re-read resolv.conf ''' try: res_init() except NameError: # Exception raised loading the library, thus res_init is not defined pass @jinja_filter('connection_check') def connection_check(addr, port=80, safe=False, ipv6=None): ''' Provides a convenient alias for the dns_check filter. ''' return dns_check(addr, port, safe, ipv6) @jinja_filter('dns_check') def dns_check(addr, port=80, safe=False, ipv6=None, attempt_connect=True): ''' Return the ip resolved by dns, but do not exit on failure, only raise an exception. Obeys system preference for IPv4/6 address resolution - this can be overridden by the ipv6 flag. Tries to connect to the address before considering it useful. If no address can be reached, the first one resolved is used as a fallback. ''' error = False lookup = addr seen_ipv6 = False family = socket.AF_INET6 if ipv6 else socket.AF_INET if ipv6 is False else socket.AF_UNSPEC hostnames = [] try: refresh_dns() hostnames = socket.getaddrinfo(addr, port, family, socket.SOCK_STREAM) except TypeError: err = ('Attempt to resolve address \'{0}\' failed. Invalid or unresolveable address').format(lookup) raise SaltSystemExit(code=42, msg=err) except socket.error: error = True # If ipv6 is set to True, attempt another lookup using the IPv4 family, # just in case we're attempting to lookup an IPv4 IP # as an IPv6 hostname. if error and ipv6: try: refresh_dns() hostnames = socket.getaddrinfo(addr, port, socket.AF_INET, socket.SOCK_STREAM) except TypeError: err = ('Attempt to resolve address \'{0}\' failed. Invalid or unresolveable address').format(lookup) raise SaltSystemExit(code=42, msg=err) except socket.error: error = True try: if not hostnames: error = True else: resolved = False candidates = [] for h in hostnames: # Input is IP address, passed through unchanged, just return it if h[4][0] == addr: resolved = salt.utils.zeromq.ip_bracket(addr) break candidate_addr = salt.utils.zeromq.ip_bracket(h[4][0]) # sometimes /etc/hosts contains ::1 localhost if not ipv6 and candidate_addr == '[::1]': continue candidates.append(candidate_addr) if attempt_connect: try: s = socket.socket(h[0], socket.SOCK_STREAM) s.settimeout(2) s.connect((candidate_addr.strip('[]'), h[4][1])) s.close() resolved = candidate_addr break except socket.error: pass if not resolved: if candidates: resolved = candidates[0] else: error = True except TypeError: err = ('Attempt to resolve address \'{0}\' failed. Invalid or unresolveable address').format(lookup) raise SaltSystemExit(code=42, msg=err) except socket.error: error = True if error: err = ('DNS lookup or connection check of \'{0}\' failed.').format(addr) if safe: if salt.log.is_console_configured(): # If logging is not configured it also means that either # the master or minion instance calling this hasn't even # started running log.error(err) raise SaltClientError() raise SaltSystemExit(code=42, msg=err) return resolved def parse_host_port(host_port): """ Takes a string argument specifying host or host:port. Returns a (hostname, port) or (ip_address, port) tuple. If no port is given, the second (port) element of the returned tuple will be None. host:port argument, for example, is accepted in the forms of: - hostname - hostname:1234 - hostname.domain.tld - hostname.domain.tld:5678 - [1234::5]:5678 - 1234::5 - 10.11.12.13:4567 - 10.11.12.13 """ host, port = None, None # default _s_ = host_port[:] if _s_[0] == "[": if "]" in host_port: host, _s_ = _s_.lstrip("[").rsplit("]", 1) host = ipaddress.IPv6Address(host).compressed if _s_[0] == ":": port = int(_s_.lstrip(":")) else: if len(_s_) > 1: raise ValueError('found ambiguous "{}" port in "{}"'.format(_s_, host_port)) else: if _s_.count(":") == 1: host, _hostport_separator_, port = _s_.partition(":") try: port = int(port) except ValueError as _e_: log.error('host_port "%s" port value "%s" is not an integer.', host_port, port) raise _e_ else: host = _s_ try: if not isinstance(host, ipaddress._BaseAddress): host_ip = ipaddress.ip_address(host).compressed host = host_ip except ValueError: log.debug('"%s" Not an IP address? Assuming it is a hostname.', host) if host != sanitize_host(host): log.error('bad hostname: "%s"', host) raise ValueError('bad hostname: "{}"'.format(host)) return host, port def is_fqdn(hostname): """ Verify if hostname conforms to be a FQDN. :param hostname: text string with the name of the host :return: bool, True if hostname is correct FQDN, False otherwise """ compliant = re.compile(r"(?!-)[A-Z\d\-\_]{1,63}(?<!-)$", re.IGNORECASE) return "." in hostname and len(hostname) < 0xff and all(compliant.match(x) for x in hostname.rstrip(".").split("."))
saltstack/salt
salt/utils/network.py
_get_iface_info
python
def _get_iface_info(iface): ''' If `iface` is available, return interface info and no error, otherwise return no info and log and return an error ''' iface_info = interfaces() if iface in iface_info.keys(): return iface_info, False else: error_msg = ('Interface "{0}" not in available interfaces: "{1}"' ''.format(iface, '", "'.join(iface_info.keys()))) log.error(error_msg) return None, error_msg
If `iface` is available, return interface info and no error, otherwise return no info and log and return an error
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/network.py#L1102-L1115
[ "def interfaces():\n '''\n Return a dictionary of information about all the interfaces on the minion\n '''\n if salt.utils.platform.is_windows():\n return win_interfaces()\n elif salt.utils.platform.is_netbsd():\n return netbsd_interfaces()\n else:\n return linux_interfaces()\n" ]
# -*- coding: utf-8 -*- ''' Define some generic socket functions for network modules ''' # Import python libs from __future__ import absolute_import, unicode_literals, print_function import itertools import os import re import types import socket import logging import platform import random import subprocess from string import ascii_letters, digits # Import 3rd-party libs from salt.ext import six from salt.ext.six.moves import range # pylint: disable=import-error,redefined-builtin # Attempt to import wmi try: import wmi import salt.utils.winapi except ImportError: pass # Import salt libs import salt.utils.args import salt.utils.files import salt.utils.path import salt.utils.platform import salt.utils.stringutils import salt.utils.zeromq from salt._compat import ipaddress from salt.exceptions import SaltClientError, SaltSystemExit from salt.utils.decorators.jinja import jinja_filter from salt.utils.versions import LooseVersion # inet_pton does not exist in Windows, this is a workaround if salt.utils.platform.is_windows(): from salt.ext import win_inet_pton # pylint: disable=unused-import log = logging.getLogger(__name__) try: import ctypes import ctypes.util libc = ctypes.cdll.LoadLibrary(ctypes.util.find_library("c")) res_init = libc.__res_init except (ImportError, OSError, AttributeError, TypeError): pass # pylint: disable=C0103 def sanitize_host(host): ''' Sanitize host string. https://tools.ietf.org/html/rfc1123#section-2.1 ''' RFC952_characters = ascii_letters + digits + ".-" return "".join([c for c in host[0:255] if c in RFC952_characters]) def isportopen(host, port): ''' Return status of a port ''' if not 1 <= int(port) <= 65535: return False sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) out = sock.connect_ex((sanitize_host(host), int(port))) return out def host_to_ips(host): ''' Returns a list of IP addresses of a given hostname or None if not found. ''' ips = [] try: for family, socktype, proto, canonname, sockaddr in socket.getaddrinfo( host, 0, socket.AF_UNSPEC, socket.SOCK_STREAM): if family == socket.AF_INET: ip, port = sockaddr elif family == socket.AF_INET6: ip, port, flow_info, scope_id = sockaddr ips.append(ip) if not ips: ips = None except Exception: ips = None return ips def _generate_minion_id(): ''' Get list of possible host names and convention names. :return: ''' # There are three types of hostnames: # 1. Network names. How host is accessed from the network. # 2. Host aliases. They might be not available in all the network or only locally (/etc/hosts) # 3. Convention names, an internal nodename. class DistinctList(list): ''' List, which allows one to append only distinct objects. Needs to work on Python 2.6, because of collections.OrderedDict only since 2.7 version. Override 'filter()' for custom filtering. ''' localhost_matchers = [r'localhost.*', r'ip6-.*', r'127[.]\d', r'0\.0\.0\.0', r'::1.*', r'ipv6-.*', r'fe00::.*', r'fe02::.*', r'1.0.0.*.ip6.arpa'] def append(self, p_object): if p_object and p_object not in self and not self.filter(p_object): super(DistinctList, self).append(p_object) return self def extend(self, iterable): for obj in iterable: self.append(obj) return self def filter(self, element): 'Returns True if element needs to be filtered' for rgx in self.localhost_matchers: if re.match(rgx, element): return True def first(self): return self and self[0] or None hostname = socket.gethostname() hosts = DistinctList().append( salt.utils.stringutils.to_unicode(socket.getfqdn(salt.utils.stringutils.to_bytes(hostname))) ).append(platform.node()).append(hostname) if not hosts: try: for a_nfo in socket.getaddrinfo(hosts.first() or 'localhost', None, socket.AF_INET, socket.SOCK_RAW, socket.IPPROTO_IP, socket.AI_CANONNAME): if len(a_nfo) > 3: hosts.append(a_nfo[3]) except socket.gaierror: log.warning('Cannot resolve address %s info via socket: %s', hosts.first() or 'localhost (N/A)', socket.gaierror) # Universal method for everywhere (Linux, Slowlaris, Windows etc) for f_name in ('/etc/hostname', '/etc/nodename', '/etc/hosts', r'{win}\system32\drivers\etc\hosts'.format(win=os.getenv('WINDIR'))): try: with salt.utils.files.fopen(f_name) as f_hdl: for line in f_hdl: line = salt.utils.stringutils.to_unicode(line) hst = line.strip().split('#')[0].strip().split() if hst: if hst[0][:4] in ('127.', '::1') or len(hst) == 1: hosts.extend(hst) except IOError: pass # include public and private ipaddresses return hosts.extend([addr for addr in ip_addrs() if not ipaddress.ip_address(addr).is_loopback]) def generate_minion_id(): ''' Return only first element of the hostname from all possible list. :return: ''' try: ret = salt.utils.stringutils.to_unicode(_generate_minion_id().first()) except TypeError: ret = None return ret or 'localhost' def get_socket(addr, type=socket.SOCK_STREAM, proto=0): ''' Return a socket object for the addr IP-version agnostic ''' version = ipaddress.ip_address(addr).version if version == 4: family = socket.AF_INET elif version == 6: family = socket.AF_INET6 return socket.socket(family, type, proto) def get_fqhostname(): ''' Returns the fully qualified hostname ''' # try getaddrinfo() fqdn = None try: addrinfo = socket.getaddrinfo( socket.gethostname(), 0, socket.AF_UNSPEC, socket.SOCK_STREAM, socket.SOL_TCP, socket.AI_CANONNAME ) for info in addrinfo: # info struct [family, socktype, proto, canonname, sockaddr] # On Windows `canonname` can be an empty string # This can cause the function to return `None` if len(info) > 3 and info[3]: fqdn = info[3] break except socket.gaierror: pass # NOTE: this used to log.error() but it was later disabled except socket.error as err: log.debug('socket.getaddrinfo() failure while finding fqdn: %s', err) if fqdn is None: fqdn = socket.getfqdn() return fqdn def ip_to_host(ip): ''' Returns the hostname of a given IP ''' try: hostname, aliaslist, ipaddrlist = socket.gethostbyaddr(ip) except Exception as exc: log.debug('salt.utils.network.ip_to_host(%r) failed: %s', ip, exc) hostname = None return hostname # pylint: enable=C0103 def is_reachable_host(entity_name): ''' Returns a bool telling if the entity name is a reachable host (IPv4/IPv6/FQDN/etc). :param hostname: :return: ''' try: assert type(socket.getaddrinfo(entity_name, 0, 0, 0, 0)) == list ret = True except socket.gaierror: ret = False return ret def is_ip(ip): ''' Returns a bool telling if the passed IP is a valid IPv4 or IPv6 address. ''' return is_ipv4(ip) or is_ipv6(ip) def is_ipv4(ip): ''' Returns a bool telling if the value passed to it was a valid IPv4 address ''' try: return ipaddress.ip_address(ip).version == 4 except ValueError: return False def is_ipv6(ip): ''' Returns a bool telling if the value passed to it was a valid IPv6 address ''' try: return ipaddress.ip_address(ip).version == 6 except ValueError: return False def is_subnet(cidr): ''' Returns a bool telling if the passed string is an IPv4 or IPv6 subnet ''' return is_ipv4_subnet(cidr) or is_ipv6_subnet(cidr) def is_ipv4_subnet(cidr): ''' Returns a bool telling if the passed string is an IPv4 subnet ''' try: return '/' in cidr and bool(ipaddress.IPv4Network(cidr)) except Exception: return False def is_ipv6_subnet(cidr): ''' Returns a bool telling if the passed string is an IPv6 subnet ''' try: return '/' in cidr and bool(ipaddress.IPv6Network(cidr)) except Exception: return False @jinja_filter('is_ip') def is_ip_filter(ip, options=None): ''' Returns a bool telling if the passed IP is a valid IPv4 or IPv6 address. ''' return is_ipv4_filter(ip, options=options) or is_ipv6_filter(ip, options=options) def _ip_options_global(ip_obj, version): return not ip_obj.is_private def _ip_options_multicast(ip_obj, version): return ip_obj.is_multicast def _ip_options_loopback(ip_obj, version): return ip_obj.is_loopback def _ip_options_link_local(ip_obj, version): return ip_obj.is_link_local def _ip_options_private(ip_obj, version): return ip_obj.is_private def _ip_options_reserved(ip_obj, version): return ip_obj.is_reserved def _ip_options_site_local(ip_obj, version): if version == 6: return ip_obj.is_site_local return False def _ip_options_unspecified(ip_obj, version): return ip_obj.is_unspecified def _ip_options(ip_obj, version, options=None): # will process and IP options options_fun_map = { 'global': _ip_options_global, 'link-local': _ip_options_link_local, 'linklocal': _ip_options_link_local, 'll': _ip_options_link_local, 'link_local': _ip_options_link_local, 'loopback': _ip_options_loopback, 'lo': _ip_options_loopback, 'multicast': _ip_options_multicast, 'private': _ip_options_private, 'public': _ip_options_global, 'reserved': _ip_options_reserved, 'site-local': _ip_options_site_local, 'sl': _ip_options_site_local, 'site_local': _ip_options_site_local, 'unspecified': _ip_options_unspecified } if not options: return six.text_type(ip_obj) # IP version already checked options_list = [option.strip() for option in options.split(',')] for option, fun in options_fun_map.items(): if option in options_list: fun_res = fun(ip_obj, version) if not fun_res: return None # stop at first failed test # else continue return six.text_type(ip_obj) def _is_ipv(ip, version, options=None): if not version: version = 4 if version not in (4, 6): return None try: ip_obj = ipaddress.ip_address(ip) except ValueError: # maybe it is an IP network try: ip_obj = ipaddress.ip_interface(ip) except ValueError: # nope, still not :( return None if not ip_obj.version == version: return None # has the right version, let's move on return _ip_options(ip_obj, version, options=options) @jinja_filter('is_ipv4') def is_ipv4_filter(ip, options=None): ''' Returns a bool telling if the value passed to it was a valid IPv4 address. ip The IP address. net: False Consider IP addresses followed by netmask. options CSV of options regarding the nature of the IP address. E.g.: loopback, multicast, private etc. ''' _is_ipv4 = _is_ipv(ip, 4, options=options) return isinstance(_is_ipv4, six.string_types) @jinja_filter('is_ipv6') def is_ipv6_filter(ip, options=None): ''' Returns a bool telling if the value passed to it was a valid IPv6 address. ip The IP address. net: False Consider IP addresses followed by netmask. options CSV of options regarding the nature of the IP address. E.g.: loopback, multicast, private etc. ''' _is_ipv6 = _is_ipv(ip, 6, options=options) return isinstance(_is_ipv6, six.string_types) def _ipv_filter(value, version, options=None): if version not in (4, 6): return if isinstance(value, (six.string_types, six.text_type, six.binary_type)): return _is_ipv(value, version, options=options) # calls is_ipv4 or is_ipv6 for `value` elif isinstance(value, (list, tuple, types.GeneratorType)): # calls is_ipv4 or is_ipv6 for each element in the list # os it filters and returns only those elements having the desired IP version return [ _is_ipv(addr, version, options=options) for addr in value if _is_ipv(addr, version, options=options) is not None ] return None @jinja_filter('ipv4') def ipv4(value, options=None): ''' Filters a list and returns IPv4 values only. ''' return _ipv_filter(value, 4, options=options) @jinja_filter('ipv6') def ipv6(value, options=None): ''' Filters a list and returns IPv6 values only. ''' return _ipv_filter(value, 6, options=options) @jinja_filter('ipaddr') def ipaddr(value, options=None): ''' Filters and returns only valid IP objects. ''' ipv4_obj = ipv4(value, options=options) ipv6_obj = ipv6(value, options=options) if ipv4_obj is None or ipv6_obj is None: # an IP address can be either IPv4 either IPv6 # therefofe if the value passed as arg is not a list, at least one of the calls above will return None # if one of them is none, means that we should return only one of them return ipv4_obj or ipv6_obj # one of them else: return ipv4_obj + ipv6_obj # extend lists def _filter_ipaddr(value, options, version=None): ipaddr_filter_out = None if version: if version == 4: ipaddr_filter_out = ipv4(value, options) elif version == 6: ipaddr_filter_out = ipv6(value, options) else: ipaddr_filter_out = ipaddr(value, options) if not ipaddr_filter_out: return if not isinstance(ipaddr_filter_out, (list, tuple, types.GeneratorType)): ipaddr_filter_out = [ipaddr_filter_out] return ipaddr_filter_out @jinja_filter('ip_host') def ip_host(value, options=None, version=None): ''' Returns the interfaces IP address, e.g.: 192.168.0.1/28. ''' ipaddr_filter_out = _filter_ipaddr(value, options=options, version=version) if not ipaddr_filter_out: return if not isinstance(value, (list, tuple, types.GeneratorType)): return six.text_type(ipaddress.ip_interface(ipaddr_filter_out[0])) return [six.text_type(ipaddress.ip_interface(ip_a)) for ip_a in ipaddr_filter_out] def _network_hosts(ip_addr_entry): return [ six.text_type(host) for host in ipaddress.ip_network(ip_addr_entry, strict=False).hosts() ] @jinja_filter('network_hosts') def network_hosts(value, options=None, version=None): ''' Return the list of hosts within a network. .. note:: When running this command with a large IPv6 network, the command will take a long time to gather all of the hosts. ''' ipaddr_filter_out = _filter_ipaddr(value, options=options, version=version) if not ipaddr_filter_out: return if not isinstance(value, (list, tuple, types.GeneratorType)): return _network_hosts(ipaddr_filter_out[0]) return [ _network_hosts(ip_a) for ip_a in ipaddr_filter_out ] def _network_size(ip_addr_entry): return ipaddress.ip_network(ip_addr_entry, strict=False).num_addresses @jinja_filter('network_size') def network_size(value, options=None, version=None): ''' Get the size of a network. ''' ipaddr_filter_out = _filter_ipaddr(value, options=options, version=version) if not ipaddr_filter_out: return if not isinstance(value, (list, tuple, types.GeneratorType)): return _network_size(ipaddr_filter_out[0]) return [ _network_size(ip_a) for ip_a in ipaddr_filter_out ] def natural_ipv4_netmask(ip, fmt='prefixlen'): ''' Returns the "natural" mask of an IPv4 address ''' bits = _ipv4_to_bits(ip) if bits.startswith('11'): mask = '24' elif bits.startswith('1'): mask = '16' else: mask = '8' if fmt == 'netmask': return cidr_to_ipv4_netmask(mask) else: return '/' + mask def rpad_ipv4_network(ip): ''' Returns an IP network address padded with zeros. Ex: '192.168.3' -> '192.168.3.0' '10.209' -> '10.209.0.0' ''' return '.'.join(itertools.islice(itertools.chain(ip.split('.'), '0000'), 0, 4)) def cidr_to_ipv4_netmask(cidr_bits): ''' Returns an IPv4 netmask ''' try: cidr_bits = int(cidr_bits) if not 1 <= cidr_bits <= 32: return '' except ValueError: return '' netmask = '' for idx in range(4): if idx: netmask += '.' if cidr_bits >= 8: netmask += '255' cidr_bits -= 8 else: netmask += '{0:d}'.format(256 - (2 ** (8 - cidr_bits))) cidr_bits = 0 return netmask def _number_of_set_bits_to_ipv4_netmask(set_bits): # pylint: disable=C0103 ''' Returns an IPv4 netmask from the integer representation of that mask. Ex. 0xffffff00 -> '255.255.255.0' ''' return cidr_to_ipv4_netmask(_number_of_set_bits(set_bits)) # pylint: disable=C0103 def _number_of_set_bits(x): ''' Returns the number of bits that are set in a 32bit int ''' # Taken from http://stackoverflow.com/a/4912729. Many thanks! x -= (x >> 1) & 0x55555555 x = ((x >> 2) & 0x33333333) + (x & 0x33333333) x = ((x >> 4) + x) & 0x0f0f0f0f x += x >> 8 x += x >> 16 return x & 0x0000003f # pylint: enable=C0103 def _interfaces_ip(out): ''' Uses ip to return a dictionary of interfaces with various information about each (up/down state, ip address, netmask, and hwaddr) ''' ret = dict() def parse_network(value, cols): ''' Return a tuple of ip, netmask, broadcast based on the current set of cols ''' brd = None scope = None if '/' in value: # we have a CIDR in this address ip, cidr = value.split('/') # pylint: disable=C0103 else: ip = value # pylint: disable=C0103 cidr = 32 if type_ == 'inet': mask = cidr_to_ipv4_netmask(int(cidr)) if 'brd' in cols: brd = cols[cols.index('brd') + 1] elif type_ == 'inet6': mask = cidr if 'scope' in cols: scope = cols[cols.index('scope') + 1] return (ip, mask, brd, scope) groups = re.compile('\r?\n\\d').split(out) for group in groups: iface = None data = dict() for line in group.splitlines(): if ' ' not in line: continue match = re.match(r'^\d*:\s+([\w.\-]+)(?:@)?([\w.\-]+)?:\s+<(.+)>', line) if match: iface, parent, attrs = match.groups() if 'UP' in attrs.split(','): data['up'] = True else: data['up'] = False if parent: data['parent'] = parent continue cols = line.split() if len(cols) >= 2: type_, value = tuple(cols[0:2]) iflabel = cols[-1:][0] if type_ in ('inet', 'inet6'): if 'secondary' not in cols: ipaddr, netmask, broadcast, scope = parse_network(value, cols) if type_ == 'inet': if 'inet' not in data: data['inet'] = list() addr_obj = dict() addr_obj['address'] = ipaddr addr_obj['netmask'] = netmask addr_obj['broadcast'] = broadcast addr_obj['label'] = iflabel data['inet'].append(addr_obj) elif type_ == 'inet6': if 'inet6' not in data: data['inet6'] = list() addr_obj = dict() addr_obj['address'] = ipaddr addr_obj['prefixlen'] = netmask addr_obj['scope'] = scope data['inet6'].append(addr_obj) else: if 'secondary' not in data: data['secondary'] = list() ip_, mask, brd, scp = parse_network(value, cols) data['secondary'].append({ 'type': type_, 'address': ip_, 'netmask': mask, 'broadcast': brd, 'label': iflabel, }) del ip_, mask, brd, scp elif type_.startswith('link'): data['hwaddr'] = value if iface: ret[iface] = data del iface, data return ret def _interfaces_ifconfig(out): ''' Uses ifconfig to return a dictionary of interfaces with various information about each (up/down state, ip address, netmask, and hwaddr) ''' ret = dict() piface = re.compile(r'^([^\s:]+)') pmac = re.compile('.*?(?:HWaddr|ether|address:|lladdr) ([0-9a-fA-F:]+)') if salt.utils.platform.is_sunos(): pip = re.compile(r'.*?(?:inet\s+)([0-9]+\.[0-9]+\.[0-9]+\.[0-9]+)(.*)') pip6 = re.compile('.*?(?:inet6 )([0-9a-fA-F:]+)') pmask6 = re.compile(r'.*?(?:inet6 [0-9a-fA-F:]+/(\d+)).*') else: pip = re.compile(r'.*?(?:inet addr:|inet [^\d]*)(.*?)\s') pip6 = re.compile('.*?(?:inet6 addr: (.*?)/|inet6 )([0-9a-fA-F:]+)') pmask6 = re.compile(r'.*?(?:inet6 addr: [0-9a-fA-F:]+/(\d+)|prefixlen (\d+))(?: Scope:([a-zA-Z]+)| scopeid (0x[0-9a-fA-F]))?') pmask = re.compile(r'.*?(?:Mask:|netmask )(?:((?:0x)?[0-9a-fA-F]{8})|([\d\.]+))') pupdown = re.compile('UP') pbcast = re.compile(r'.*?(?:Bcast:|broadcast )([\d\.]+)') groups = re.compile('\r?\n(?=\\S)').split(out) for group in groups: data = dict() iface = '' updown = False for line in group.splitlines(): miface = piface.match(line) mmac = pmac.match(line) mip = pip.match(line) mip6 = pip6.match(line) mupdown = pupdown.search(line) if miface: iface = miface.group(1) if mmac: data['hwaddr'] = mmac.group(1) if salt.utils.platform.is_sunos(): expand_mac = [] for chunk in data['hwaddr'].split(':'): expand_mac.append('0{0}'.format(chunk) if len(chunk) < 2 else '{0}'.format(chunk)) data['hwaddr'] = ':'.join(expand_mac) if mip: if 'inet' not in data: data['inet'] = list() addr_obj = dict() addr_obj['address'] = mip.group(1) mmask = pmask.match(line) if mmask: if mmask.group(1): mmask = _number_of_set_bits_to_ipv4_netmask( int(mmask.group(1), 16)) else: mmask = mmask.group(2) addr_obj['netmask'] = mmask mbcast = pbcast.match(line) if mbcast: addr_obj['broadcast'] = mbcast.group(1) data['inet'].append(addr_obj) if mupdown: updown = True if mip6: if 'inet6' not in data: data['inet6'] = list() addr_obj = dict() addr_obj['address'] = mip6.group(1) or mip6.group(2) mmask6 = pmask6.match(line) if mmask6: addr_obj['prefixlen'] = mmask6.group(1) or mmask6.group(2) if not salt.utils.platform.is_sunos(): ipv6scope = mmask6.group(3) or mmask6.group(4) addr_obj['scope'] = ipv6scope.lower() if ipv6scope is not None else ipv6scope # SunOS sometimes has ::/0 as inet6 addr when using addrconf if not salt.utils.platform.is_sunos() \ or addr_obj['address'] != '::' \ and addr_obj['prefixlen'] != 0: data['inet6'].append(addr_obj) data['up'] = updown if iface in ret: # SunOS optimization, where interfaces occur twice in 'ifconfig -a' # output with the same name: for ipv4 and then for ipv6 addr family. # Every instance has it's own 'UP' status and we assume that ipv4 # status determines global interface status. # # merge items with higher priority for older values # after that merge the inet and inet6 sub items for both ret[iface] = dict(list(data.items()) + list(ret[iface].items())) if 'inet' in data: ret[iface]['inet'].extend(x for x in data['inet'] if x not in ret[iface]['inet']) if 'inet6' in data: ret[iface]['inet6'].extend(x for x in data['inet6'] if x not in ret[iface]['inet6']) else: ret[iface] = data del data return ret def linux_interfaces(): ''' Obtain interface information for *NIX/BSD variants ''' ifaces = dict() ip_path = salt.utils.path.which('ip') ifconfig_path = None if ip_path else salt.utils.path.which('ifconfig') if ip_path: cmd1 = subprocess.Popen( '{0} link show'.format(ip_path), shell=True, close_fds=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT).communicate()[0] cmd2 = subprocess.Popen( '{0} addr show'.format(ip_path), shell=True, close_fds=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT).communicate()[0] ifaces = _interfaces_ip("{0}\n{1}".format( salt.utils.stringutils.to_str(cmd1), salt.utils.stringutils.to_str(cmd2))) elif ifconfig_path: cmd = subprocess.Popen( '{0} -a'.format(ifconfig_path), shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT).communicate()[0] ifaces = _interfaces_ifconfig(salt.utils.stringutils.to_str(cmd)) return ifaces def _netbsd_interfaces_ifconfig(out): ''' Uses ifconfig to return a dictionary of interfaces with various information about each (up/down state, ip address, netmask, and hwaddr) ''' ret = dict() piface = re.compile(r'^([^\s:]+)') pmac = re.compile('.*?address: ([0-9a-f:]+)') pip = re.compile(r'.*?inet [^\d]*(.*?)/([\d]*)\s') pip6 = re.compile(r'.*?inet6 ([0-9a-f:]+)%([a-zA-Z0-9]*)/([\d]*)\s') pupdown = re.compile('UP') pbcast = re.compile(r'.*?broadcast ([\d\.]+)') groups = re.compile('\r?\n(?=\\S)').split(out) for group in groups: data = dict() iface = '' updown = False for line in group.splitlines(): miface = piface.match(line) mmac = pmac.match(line) mip = pip.match(line) mip6 = pip6.match(line) mupdown = pupdown.search(line) if miface: iface = miface.group(1) if mmac: data['hwaddr'] = mmac.group(1) if mip: if 'inet' not in data: data['inet'] = list() addr_obj = dict() addr_obj['address'] = mip.group(1) mmask = mip.group(2) if mip.group(2): addr_obj['netmask'] = cidr_to_ipv4_netmask(mip.group(2)) mbcast = pbcast.match(line) if mbcast: addr_obj['broadcast'] = mbcast.group(1) data['inet'].append(addr_obj) if mupdown: updown = True if mip6: if 'inet6' not in data: data['inet6'] = list() addr_obj = dict() addr_obj['address'] = mip6.group(1) mmask6 = mip6.group(3) addr_obj['scope'] = mip6.group(2) addr_obj['prefixlen'] = mip6.group(3) data['inet6'].append(addr_obj) data['up'] = updown ret[iface] = data del data return ret def netbsd_interfaces(): ''' Obtain interface information for NetBSD >= 8 where the ifconfig output diverged from other BSD variants (Netmask is now part of the address) ''' # NetBSD versions prior to 8.0 can still use linux_interfaces() if LooseVersion(os.uname()[2]) < LooseVersion('8.0'): return linux_interfaces() ifconfig_path = salt.utils.path.which('ifconfig') cmd = subprocess.Popen( '{0} -a'.format(ifconfig_path), shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT).communicate()[0] return _netbsd_interfaces_ifconfig(salt.utils.stringutils.to_str(cmd)) def _interfaces_ipconfig(out): ''' Returns a dictionary of interfaces with various information about each (up/down state, ip address, netmask, and hwaddr) NOTE: This is not used by any function and may be able to be removed in the future. ''' ifaces = dict() iface = None adapter_iface_regex = re.compile(r'adapter (\S.+):$') for line in out.splitlines(): if not line: continue # TODO what does Windows call Infiniband and 10/40gige adapters if line.startswith('Ethernet'): iface = ifaces[adapter_iface_regex.search(line).group(1)] iface['up'] = True addr = None continue if iface: key, val = line.split(',', 1) key = key.strip(' .') val = val.strip() if addr and key == 'Subnet Mask': addr['netmask'] = val elif key in ('IP Address', 'IPv4 Address'): if 'inet' not in iface: iface['inet'] = list() addr = {'address': val.rstrip('(Preferred)'), 'netmask': None, 'broadcast': None} # TODO find the broadcast iface['inet'].append(addr) elif 'IPv6 Address' in key: if 'inet6' not in iface: iface['inet'] = list() # XXX What is the prefixlen!? addr = {'address': val.rstrip('(Preferred)'), 'prefixlen': None} iface['inet6'].append(addr) elif key == 'Physical Address': iface['hwaddr'] = val elif key == 'Media State': # XXX seen used for tunnel adaptors # might be useful iface['up'] = (val != 'Media disconnected') def win_interfaces(): ''' Obtain interface information for Windows systems ''' with salt.utils.winapi.Com(): c = wmi.WMI() ifaces = {} for iface in c.Win32_NetworkAdapterConfiguration(IPEnabled=1): ifaces[iface.Description] = dict() if iface.MACAddress: ifaces[iface.Description]['hwaddr'] = iface.MACAddress if iface.IPEnabled: ifaces[iface.Description]['up'] = True for ip in iface.IPAddress: if '.' in ip: if 'inet' not in ifaces[iface.Description]: ifaces[iface.Description]['inet'] = [] item = {'address': ip, 'label': iface.Description} if iface.DefaultIPGateway: broadcast = next((i for i in iface.DefaultIPGateway if '.' in i), '') if broadcast: item['broadcast'] = broadcast if iface.IPSubnet: netmask = next((i for i in iface.IPSubnet if '.' in i), '') if netmask: item['netmask'] = netmask ifaces[iface.Description]['inet'].append(item) if ':' in ip: if 'inet6' not in ifaces[iface.Description]: ifaces[iface.Description]['inet6'] = [] item = {'address': ip} if iface.DefaultIPGateway: broadcast = next((i for i in iface.DefaultIPGateway if ':' in i), '') if broadcast: item['broadcast'] = broadcast if iface.IPSubnet: netmask = next((i for i in iface.IPSubnet if ':' in i), '') if netmask: item['netmask'] = netmask ifaces[iface.Description]['inet6'].append(item) else: ifaces[iface.Description]['up'] = False return ifaces def interfaces(): ''' Return a dictionary of information about all the interfaces on the minion ''' if salt.utils.platform.is_windows(): return win_interfaces() elif salt.utils.platform.is_netbsd(): return netbsd_interfaces() else: return linux_interfaces() def get_net_start(ipaddr, netmask): ''' Return the address of the network ''' net = ipaddress.ip_network('{0}/{1}'.format(ipaddr, netmask), strict=False) return six.text_type(net.network_address) def get_net_size(mask): ''' Turns an IPv4 netmask into it's corresponding prefix length (255.255.255.0 -> 24 as in 192.168.1.10/24). ''' binary_str = '' for octet in mask.split('.'): binary_str += bin(int(octet))[2:].zfill(8) return len(binary_str.rstrip('0')) def calc_net(ipaddr, netmask=None): ''' Takes IP (CIDR notation supported) and optionally netmask and returns the network in CIDR-notation. (The IP can be any IP inside the subnet) ''' if netmask is not None: ipaddr = '{0}/{1}'.format(ipaddr, netmask) return six.text_type(ipaddress.ip_network(ipaddr, strict=False)) def _ipv4_to_bits(ipaddr): ''' Accepts an IPv4 dotted quad and returns a string representing its binary counterpart ''' return ''.join([bin(int(x))[2:].rjust(8, '0') for x in ipaddr.split('.')]) def _hw_addr_aix(iface): ''' Return the hardware address (a.k.a. MAC address) for a given interface on AIX MAC address not available in through interfaces ''' cmd = subprocess.Popen( 'entstat -d {0} | grep \'Hardware Address\''.format(iface), shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT).communicate()[0] if cmd: comps = cmd.split(' ') if len(comps) == 3: mac_addr = comps[2].strip('\'').strip() return mac_addr error_msg = ('Interface "{0}" either not available or does not contain a hardware address'.format(iface)) log.error(error_msg) return error_msg def hw_addr(iface): ''' Return the hardware address (a.k.a. MAC address) for a given interface .. versionchanged:: 2016.11.4 Added support for AIX ''' if salt.utils.platform.is_aix(): return _hw_addr_aix iface_info, error = _get_iface_info(iface) if error is False: return iface_info.get(iface, {}).get('hwaddr', '') else: return error def interface(iface): ''' Return the details of `iface` or an error if it does not exist ''' iface_info, error = _get_iface_info(iface) if error is False: return iface_info.get(iface, {}).get('inet', '') else: return error def interface_ip(iface): ''' Return `iface` IPv4 addr or an error if `iface` does not exist ''' iface_info, error = _get_iface_info(iface) if error is False: inet = iface_info.get(iface, {}).get('inet', None) return inet[0].get('address', '') if inet else '' else: return error def _subnets(proto='inet', interfaces_=None): ''' Returns a list of subnets to which the host belongs ''' if interfaces_ is None: ifaces = interfaces() elif isinstance(interfaces_, list): ifaces = {} for key, value in six.iteritems(interfaces()): if key in interfaces_: ifaces[key] = value else: ifaces = {interfaces_: interfaces().get(interfaces_, {})} ret = set() if proto == 'inet': subnet = 'netmask' dflt_cidr = 32 elif proto == 'inet6': subnet = 'prefixlen' dflt_cidr = 128 else: log.error('Invalid proto %s calling subnets()', proto) return for ip_info in six.itervalues(ifaces): addrs = ip_info.get(proto, []) addrs.extend([addr for addr in ip_info.get('secondary', []) if addr.get('type') == proto]) for intf in addrs: if subnet in intf: intf = ipaddress.ip_interface('{0}/{1}'.format(intf['address'], intf[subnet])) else: intf = ipaddress.ip_interface('{0}/{1}'.format(intf['address'], dflt_cidr)) if not intf.is_loopback: ret.add(intf.network) return [six.text_type(net) for net in sorted(ret)] def subnets(interfaces=None): ''' Returns a list of IPv4 subnets to which the host belongs ''' return _subnets('inet', interfaces_=interfaces) def subnets6(): ''' Returns a list of IPv6 subnets to which the host belongs ''' return _subnets('inet6') def in_subnet(cidr, addr=None): ''' Returns True if host or (any of) addrs is within specified subnet, otherwise False ''' try: cidr = ipaddress.ip_network(cidr) except ValueError: log.error('Invalid CIDR \'%s\'', cidr) return False if addr is None: addr = ip_addrs() addr.extend(ip_addrs6()) elif not isinstance(addr, (list, tuple)): addr = (addr,) return any(ipaddress.ip_address(item) in cidr for item in addr) def _ip_addrs(interface=None, include_loopback=False, interface_data=None, proto='inet'): ''' Return the full list of IP adresses matching the criteria proto = inet|inet6 ''' ret = set() ifaces = interface_data \ if isinstance(interface_data, dict) \ else interfaces() if interface is None: target_ifaces = ifaces else: target_ifaces = dict([(k, v) for k, v in six.iteritems(ifaces) if k == interface]) if not target_ifaces: log.error('Interface %s not found.', interface) for ip_info in six.itervalues(target_ifaces): addrs = ip_info.get(proto, []) addrs.extend([addr for addr in ip_info.get('secondary', []) if addr.get('type') == proto]) for addr in addrs: addr = ipaddress.ip_address(addr.get('address')) if not addr.is_loopback or include_loopback: ret.add(addr) return [six.text_type(addr) for addr in sorted(ret)] def ip_addrs(interface=None, include_loopback=False, interface_data=None): ''' Returns a list of IPv4 addresses assigned to the host. 127.0.0.1 is ignored, unless 'include_loopback=True' is indicated. If 'interface' is provided, then only IP addresses from that interface will be returned. ''' return _ip_addrs(interface, include_loopback, interface_data, 'inet') def ip_addrs6(interface=None, include_loopback=False, interface_data=None): ''' Returns a list of IPv6 addresses assigned to the host. ::1 is ignored, unless 'include_loopback=True' is indicated. If 'interface' is provided, then only IP addresses from that interface will be returned. ''' return _ip_addrs(interface, include_loopback, interface_data, 'inet6') def hex2ip(hex_ip, invert=False): ''' Convert a hex string to an ip, if a failure occurs the original hex is returned. If 'invert=True' assume that ip from /proc/net/<proto> ''' if len(hex_ip) == 32: # ipv6 ip = [] for i in range(0, 32, 8): ip_part = hex_ip[i:i + 8] ip_part = [ip_part[x:x + 2] for x in range(0, 8, 2)] if invert: ip.append("{0[3]}{0[2]}:{0[1]}{0[0]}".format(ip_part)) else: ip.append("{0[0]}{0[1]}:{0[2]}{0[3]}".format(ip_part)) try: address = ipaddress.IPv6Address(":".join(ip)) if address.ipv4_mapped: return str(address.ipv4_mapped) else: return address.compressed except ipaddress.AddressValueError as ex: log.error('hex2ip - ipv6 address error: %s', ex) return hex_ip try: hip = int(hex_ip, 16) except ValueError: return hex_ip if invert: return '{3}.{2}.{1}.{0}'.format(hip >> 24 & 255, hip >> 16 & 255, hip >> 8 & 255, hip & 255) return '{0}.{1}.{2}.{3}'.format(hip >> 24 & 255, hip >> 16 & 255, hip >> 8 & 255, hip & 255) def mac2eui64(mac, prefix=None): ''' Convert a MAC address to a EUI64 identifier or, with prefix provided, a full IPv6 address ''' # http://tools.ietf.org/html/rfc4291#section-2.5.1 eui64 = re.sub(r'[.:-]', '', mac).lower() eui64 = eui64[0:6] + 'fffe' + eui64[6:] eui64 = hex(int(eui64[0:2], 16) | 2)[2:].zfill(2) + eui64[2:] if prefix is None: return ':'.join(re.findall(r'.{4}', eui64)) else: try: net = ipaddress.ip_network(prefix, strict=False) euil = int('0x{0}'.format(eui64), 16) return '{0}/{1}'.format(net[euil], net.prefixlen) except Exception: return def active_tcp(): ''' Return a dict describing all active tcp connections as quickly as possible ''' ret = {} for statf in ['/proc/net/tcp', '/proc/net/tcp6']: if os.path.isfile(statf): with salt.utils.files.fopen(statf, 'rb') as fp_: for line in fp_: line = salt.utils.stringutils.to_unicode(line) if line.strip().startswith('sl'): continue iret = _parse_tcp_line(line) sl = next(iter(iret)) if iret[sl]['state'] == 1: # 1 is ESTABLISHED del iret[sl]['state'] ret[len(ret)] = iret[sl] return ret def local_port_tcp(port): ''' Return a set of remote ip addrs attached to the specified local port ''' ret = _remotes_on(port, 'local_port') return ret def remote_port_tcp(port): ''' Return a set of ip addrs the current host is connected to on given port ''' ret = _remotes_on(port, 'remote_port') return ret def _remotes_on(port, which_end): ''' Return a set of ip addrs active tcp connections ''' port = int(port) ret = _netlink_tool_remote_on(port, which_end) if ret is not None: return ret ret = set() proc_available = False for statf in ['/proc/net/tcp', '/proc/net/tcp6']: if os.path.isfile(statf): proc_available = True with salt.utils.files.fopen(statf, 'r') as fp_: for line in fp_: line = salt.utils.stringutils.to_unicode(line) if line.strip().startswith('sl'): continue iret = _parse_tcp_line(line) sl = next(iter(iret)) if iret[sl][which_end] == port and iret[sl]['state'] == 1: # 1 is ESTABLISHED ret.add(iret[sl]['remote_addr']) if not proc_available: # Fallback to use OS specific tools if salt.utils.platform.is_sunos(): return _sunos_remotes_on(port, which_end) if salt.utils.platform.is_freebsd(): return _freebsd_remotes_on(port, which_end) if salt.utils.platform.is_netbsd(): return _netbsd_remotes_on(port, which_end) if salt.utils.platform.is_openbsd(): return _openbsd_remotes_on(port, which_end) if salt.utils.platform.is_windows(): return _windows_remotes_on(port, which_end) if salt.utils.platform.is_aix(): return _aix_remotes_on(port, which_end) return _linux_remotes_on(port, which_end) return ret def _parse_tcp_line(line): ''' Parse a single line from the contents of /proc/net/tcp or /proc/net/tcp6 ''' ret = {} comps = line.strip().split() sl = comps[0].rstrip(':') ret[sl] = {} l_addr, l_port = comps[1].split(':') r_addr, r_port = comps[2].split(':') ret[sl]['local_addr'] = hex2ip(l_addr, True) ret[sl]['local_port'] = int(l_port, 16) ret[sl]['remote_addr'] = hex2ip(r_addr, True) ret[sl]['remote_port'] = int(r_port, 16) ret[sl]['state'] = int(comps[3], 16) return ret def _netlink_tool_remote_on(port, which_end): ''' Returns set of ipv4 host addresses of remote established connections on local or remote tcp port. Parses output of shell 'ss' to get connections [root@salt-master ~]# ss -ant State Recv-Q Send-Q Local Address:Port Peer Address:Port LISTEN 0 511 *:80 *:* LISTEN 0 128 *:22 *:* ESTAB 0 0 127.0.0.1:56726 127.0.0.1:4505 ''' remotes = set() valid = False try: data = subprocess.check_output(['ss', '-ant']) # pylint: disable=minimum-python-version except subprocess.CalledProcessError: log.error('Failed ss') raise except OSError: # not command "No such file or directory" return None lines = salt.utils.stringutils.to_str(data).split('\n') for line in lines: if 'Address:Port' in line: # ss tools may not be valid valid = True continue elif 'ESTAB' not in line: continue chunks = line.split() local_host, local_port = chunks[3].split(':', 1) remote_host, remote_port = chunks[4].split(':', 1) if which_end == 'remote_port' and int(remote_port) != port: continue if which_end == 'local_port' and int(local_port) != port: continue remotes.add(remote_host) if valid is False: remotes = None return remotes def _sunos_remotes_on(port, which_end): ''' SunOS specific helper function. Returns set of ipv4 host addresses of remote established connections on local or remote tcp port. Parses output of shell 'netstat' to get connections [root@salt-master ~]# netstat -f inet -n TCP: IPv4 Local Address Remote Address Swind Send-Q Rwind Recv-Q State -------------------- -------------------- ----- ------ ----- ------ ----------- 10.0.0.101.4505 10.0.0.1.45329 1064800 0 1055864 0 ESTABLISHED 10.0.0.101.4505 10.0.0.100.50798 1064800 0 1055864 0 ESTABLISHED ''' remotes = set() try: data = subprocess.check_output(['netstat', '-f', 'inet', '-n']) # pylint: disable=minimum-python-version except subprocess.CalledProcessError: log.error('Failed netstat') raise lines = salt.utils.stringutils.to_str(data).split('\n') for line in lines: if 'ESTABLISHED' not in line: continue chunks = line.split() local_host, local_port = chunks[0].rsplit('.', 1) remote_host, remote_port = chunks[1].rsplit('.', 1) if which_end == 'remote_port' and int(remote_port) != port: continue if which_end == 'local_port' and int(local_port) != port: continue remotes.add(remote_host) return remotes def _freebsd_remotes_on(port, which_end): ''' Returns set of ipv4 host addresses of remote established connections on local tcp port port. Parses output of shell 'sockstat' (FreeBSD) to get connections $ sudo sockstat -4 USER COMMAND PID FD PROTO LOCAL ADDRESS FOREIGN ADDRESS root python2.7 1456 29 tcp4 *:4505 *:* root python2.7 1445 17 tcp4 *:4506 *:* root python2.7 1294 14 tcp4 127.0.0.1:11813 127.0.0.1:4505 root python2.7 1294 41 tcp4 127.0.0.1:61115 127.0.0.1:4506 $ sudo sockstat -4 -c -p 4506 USER COMMAND PID FD PROTO LOCAL ADDRESS FOREIGN ADDRESS root python2.7 1294 41 tcp4 127.0.0.1:61115 127.0.0.1:4506 ''' port = int(port) remotes = set() try: cmd = salt.utils.args.shlex_split('sockstat -4 -c -p {0}'.format(port)) data = subprocess.check_output(cmd) # pylint: disable=minimum-python-version except subprocess.CalledProcessError as ex: log.error('Failed "sockstat" with returncode = %s', ex.returncode) raise lines = salt.utils.stringutils.to_str(data).split('\n') for line in lines: chunks = line.split() if not chunks: continue # ['root', 'python2.7', '1456', '37', 'tcp4', # '127.0.0.1:4505-', '127.0.0.1:55703'] # print chunks if 'COMMAND' in chunks[1]: continue # ignore header if len(chunks) < 2: continue # sockstat -4 -c -p 4506 does this with high PIDs: # USER COMMAND PID FD PROTO LOCAL ADDRESS FOREIGN ADDRESS # salt-master python2.781106 35 tcp4 192.168.12.34:4506 192.168.12.45:60143 local = chunks[-2] remote = chunks[-1] lhost, lport = local.split(':') rhost, rport = remote.split(':') if which_end == 'local' and int(lport) != port: # ignore if local port not port continue if which_end == 'remote' and int(rport) != port: # ignore if remote port not port continue remotes.add(rhost) return remotes def _netbsd_remotes_on(port, which_end): ''' Returns set of ipv4 host addresses of remote established connections on local tcp port port. Parses output of shell 'sockstat' (NetBSD) to get connections $ sudo sockstat -4 -n USER COMMAND PID FD PROTO LOCAL ADDRESS FOREIGN ADDRESS root python2.7 1456 29 tcp *.4505 *.* root python2.7 1445 17 tcp *.4506 *.* root python2.7 1294 14 tcp 127.0.0.1.11813 127.0.0.1.4505 root python2.7 1294 41 tcp 127.0.0.1.61115 127.0.0.1.4506 $ sudo sockstat -4 -c -n -p 4506 USER COMMAND PID FD PROTO LOCAL ADDRESS FOREIGN ADDRESS root python2.7 1294 41 tcp 127.0.0.1.61115 127.0.0.1.4506 ''' port = int(port) remotes = set() try: cmd = salt.utils.args.shlex_split('sockstat -4 -c -n -p {0}'.format(port)) data = subprocess.check_output(cmd) # pylint: disable=minimum-python-version except subprocess.CalledProcessError as ex: log.error('Failed "sockstat" with returncode = %s', ex.returncode) raise lines = salt.utils.stringutils.to_str(data).split('\n') for line in lines: chunks = line.split() if not chunks: continue # ['root', 'python2.7', '1456', '37', 'tcp', # '127.0.0.1.4505-', '127.0.0.1.55703'] # print chunks if 'COMMAND' in chunks[1]: continue # ignore header if len(chunks) < 2: continue local = chunks[5].split('.') lport = local.pop() lhost = '.'.join(local) remote = chunks[6].split('.') rport = remote.pop() rhost = '.'.join(remote) if which_end == 'local' and int(lport) != port: # ignore if local port not port continue if which_end == 'remote' and int(rport) != port: # ignore if remote port not port continue remotes.add(rhost) return remotes def _openbsd_remotes_on(port, which_end): ''' OpenBSD specific helper function. Returns set of ipv4 host addresses of remote established connections on local or remote tcp port. Parses output of shell 'netstat' to get connections $ netstat -nf inet Active Internet connections Proto Recv-Q Send-Q Local Address Foreign Address (state) tcp 0 0 10.0.0.101.4505 10.0.0.1.45329 ESTABLISHED tcp 0 0 10.0.0.101.4505 10.0.0.100.50798 ESTABLISHED ''' remotes = set() try: data = subprocess.check_output(['netstat', '-nf', 'inet']) # pylint: disable=minimum-python-version except subprocess.CalledProcessError: log.error('Failed netstat') raise lines = data.split('\n') for line in lines: if 'ESTABLISHED' not in line: continue chunks = line.split() local_host, local_port = chunks[3].rsplit('.', 1) remote_host, remote_port = chunks[4].rsplit('.', 1) if which_end == 'remote_port' and int(remote_port) != port: continue if which_end == 'local_port' and int(local_port) != port: continue remotes.add(remote_host) return remotes def _windows_remotes_on(port, which_end): r''' Windows specific helper function. Returns set of ipv4 host addresses of remote established connections on local or remote tcp port. Parses output of shell 'netstat' to get connections C:\>netstat -n Active Connections Proto Local Address Foreign Address State TCP 10.2.33.17:3007 130.164.12.233:10123 ESTABLISHED TCP 10.2.33.17:3389 130.164.30.5:10378 ESTABLISHED ''' remotes = set() try: data = subprocess.check_output(['netstat', '-n']) # pylint: disable=minimum-python-version except subprocess.CalledProcessError: log.error('Failed netstat') raise lines = salt.utils.stringutils.to_str(data).split('\n') for line in lines: if 'ESTABLISHED' not in line: continue chunks = line.split() local_host, local_port = chunks[1].rsplit(':', 1) remote_host, remote_port = chunks[2].rsplit(':', 1) if which_end == 'remote_port' and int(remote_port) != port: continue if which_end == 'local_port' and int(local_port) != port: continue remotes.add(remote_host) return remotes def _linux_remotes_on(port, which_end): ''' Linux specific helper function. Returns set of ip host addresses of remote established connections on local tcp port port. Parses output of shell 'lsof' to get connections $ sudo lsof -iTCP:4505 -n COMMAND PID USER FD TYPE DEVICE SIZE/OFF NODE NAME Python 9971 root 35u IPv4 0x18a8464a29ca329d 0t0 TCP *:4505 (LISTEN) Python 9971 root 37u IPv4 0x18a8464a29b2b29d 0t0 TCP 127.0.0.1:4505->127.0.0.1:55703 (ESTABLISHED) Python 10152 root 22u IPv4 0x18a8464a29c8cab5 0t0 TCP 127.0.0.1:55703->127.0.0.1:4505 (ESTABLISHED) Python 10153 root 22u IPv4 0x18a8464a29c8cab5 0t0 TCP [fe80::249a]:4505->[fe80::150]:59367 (ESTABLISHED) ''' remotes = set() try: data = subprocess.check_output( ['lsof', '-iTCP:{0:d}'.format(port), '-n', '-P'] # pylint: disable=minimum-python-version ) except subprocess.CalledProcessError as ex: if ex.returncode == 1: # Lsof return 1 if any error was detected, including the failure # to locate Internet addresses, and it is not an error in this case. log.warning('"lsof" returncode = 1, likely no active TCP sessions.') return remotes log.error('Failed "lsof" with returncode = %s', ex.returncode) raise lines = salt.utils.stringutils.to_str(data).split('\n') for line in lines: chunks = line.split() if not chunks: continue # ['Python', '9971', 'root', '37u', 'IPv4', '0x18a8464a29b2b29d', '0t0', # 'TCP', '127.0.0.1:4505->127.0.0.1:55703', '(ESTABLISHED)'] # print chunks if 'COMMAND' in chunks[0]: continue # ignore header if 'ESTABLISHED' not in chunks[-1]: continue # ignore if not ESTABLISHED # '127.0.0.1:4505->127.0.0.1:55703' local, remote = chunks[8].split('->') _, lport = local.rsplit(':', 1) rhost, rport = remote.rsplit(':', 1) if which_end == 'remote_port' and int(rport) != port: continue if which_end == 'local_port' and int(lport) != port: continue remotes.add(rhost.strip("[]")) return remotes def _aix_remotes_on(port, which_end): ''' AIX specific helper function. Returns set of ipv4 host addresses of remote established connections on local or remote tcp port. Parses output of shell 'netstat' to get connections root@la68pp002_pub:/opt/salt/lib/python2.7/site-packages/salt/modules# netstat -f inet -n Active Internet connections Proto Recv-Q Send-Q Local Address Foreign Address (state) tcp4 0 0 172.29.149.95.50093 209.41.78.13.4505 ESTABLISHED tcp4 0 0 127.0.0.1.9514 *.* LISTEN tcp4 0 0 127.0.0.1.9515 *.* LISTEN tcp4 0 0 127.0.0.1.199 127.0.0.1.32779 ESTABLISHED tcp4 0 0 127.0.0.1.32779 127.0.0.1.199 ESTABLISHED tcp4 0 40 172.29.149.95.22 172.29.96.83.41022 ESTABLISHED tcp4 0 0 172.29.149.95.22 172.29.96.83.41032 ESTABLISHED tcp4 0 0 127.0.0.1.32771 127.0.0.1.32775 ESTABLISHED tcp 0 0 127.0.0.1.32775 127.0.0.1.32771 ESTABLISHED tcp4 0 0 127.0.0.1.32771 127.0.0.1.32776 ESTABLISHED tcp 0 0 127.0.0.1.32776 127.0.0.1.32771 ESTABLISHED tcp4 0 0 127.0.0.1.32771 127.0.0.1.32777 ESTABLISHED tcp 0 0 127.0.0.1.32777 127.0.0.1.32771 ESTABLISHED tcp4 0 0 127.0.0.1.32771 127.0.0.1.32778 ESTABLISHED tcp 0 0 127.0.0.1.32778 127.0.0.1.32771 ESTABLISHED ''' remotes = set() try: data = subprocess.check_output(['netstat', '-f', 'inet', '-n']) # pylint: disable=minimum-python-version except subprocess.CalledProcessError: log.error('Failed netstat') raise lines = salt.utils.stringutils.to_str(data).split('\n') for line in lines: if 'ESTABLISHED' not in line: continue chunks = line.split() local_host, local_port = chunks[3].rsplit('.', 1) remote_host, remote_port = chunks[4].rsplit('.', 1) if which_end == 'remote_port' and int(remote_port) != port: continue if which_end == 'local_port' and int(local_port) != port: continue remotes.add(remote_host) return remotes @jinja_filter('gen_mac') def gen_mac(prefix='AC:DE:48'): ''' Generates a MAC address with the defined OUI prefix. Common prefixes: - ``00:16:3E`` -- Xen - ``00:18:51`` -- OpenVZ - ``00:50:56`` -- VMware (manually generated) - ``52:54:00`` -- QEMU/KVM - ``AC:DE:48`` -- PRIVATE References: - http://standards.ieee.org/develop/regauth/oui/oui.txt - https://www.wireshark.org/tools/oui-lookup.html - https://en.wikipedia.org/wiki/MAC_address ''' return '{0}:{1:02X}:{2:02X}:{3:02X}'.format(prefix, random.randint(0, 0xff), random.randint(0, 0xff), random.randint(0, 0xff)) @jinja_filter('mac_str_to_bytes') def mac_str_to_bytes(mac_str): ''' Convert a MAC address string into bytes. Works with or without separators: b1 = mac_str_to_bytes('08:00:27:13:69:77') b2 = mac_str_to_bytes('080027136977') assert b1 == b2 assert isinstance(b1, bytes) ''' if len(mac_str) == 12: pass elif len(mac_str) == 17: sep = mac_str[2] mac_str = mac_str.replace(sep, '') else: raise ValueError('Invalid MAC address') chars = (int(mac_str[s:s+2], 16) for s in range(0, 12, 2)) return bytes(chars) if six.PY3 else b''.join(chr(x) for x in chars) def refresh_dns(): ''' issue #21397: force glibc to re-read resolv.conf ''' try: res_init() except NameError: # Exception raised loading the library, thus res_init is not defined pass @jinja_filter('connection_check') def connection_check(addr, port=80, safe=False, ipv6=None): ''' Provides a convenient alias for the dns_check filter. ''' return dns_check(addr, port, safe, ipv6) @jinja_filter('dns_check') def dns_check(addr, port=80, safe=False, ipv6=None, attempt_connect=True): ''' Return the ip resolved by dns, but do not exit on failure, only raise an exception. Obeys system preference for IPv4/6 address resolution - this can be overridden by the ipv6 flag. Tries to connect to the address before considering it useful. If no address can be reached, the first one resolved is used as a fallback. ''' error = False lookup = addr seen_ipv6 = False family = socket.AF_INET6 if ipv6 else socket.AF_INET if ipv6 is False else socket.AF_UNSPEC hostnames = [] try: refresh_dns() hostnames = socket.getaddrinfo(addr, port, family, socket.SOCK_STREAM) except TypeError: err = ('Attempt to resolve address \'{0}\' failed. Invalid or unresolveable address').format(lookup) raise SaltSystemExit(code=42, msg=err) except socket.error: error = True # If ipv6 is set to True, attempt another lookup using the IPv4 family, # just in case we're attempting to lookup an IPv4 IP # as an IPv6 hostname. if error and ipv6: try: refresh_dns() hostnames = socket.getaddrinfo(addr, port, socket.AF_INET, socket.SOCK_STREAM) except TypeError: err = ('Attempt to resolve address \'{0}\' failed. Invalid or unresolveable address').format(lookup) raise SaltSystemExit(code=42, msg=err) except socket.error: error = True try: if not hostnames: error = True else: resolved = False candidates = [] for h in hostnames: # Input is IP address, passed through unchanged, just return it if h[4][0] == addr: resolved = salt.utils.zeromq.ip_bracket(addr) break candidate_addr = salt.utils.zeromq.ip_bracket(h[4][0]) # sometimes /etc/hosts contains ::1 localhost if not ipv6 and candidate_addr == '[::1]': continue candidates.append(candidate_addr) if attempt_connect: try: s = socket.socket(h[0], socket.SOCK_STREAM) s.settimeout(2) s.connect((candidate_addr.strip('[]'), h[4][1])) s.close() resolved = candidate_addr break except socket.error: pass if not resolved: if candidates: resolved = candidates[0] else: error = True except TypeError: err = ('Attempt to resolve address \'{0}\' failed. Invalid or unresolveable address').format(lookup) raise SaltSystemExit(code=42, msg=err) except socket.error: error = True if error: err = ('DNS lookup or connection check of \'{0}\' failed.').format(addr) if safe: if salt.log.is_console_configured(): # If logging is not configured it also means that either # the master or minion instance calling this hasn't even # started running log.error(err) raise SaltClientError() raise SaltSystemExit(code=42, msg=err) return resolved def parse_host_port(host_port): """ Takes a string argument specifying host or host:port. Returns a (hostname, port) or (ip_address, port) tuple. If no port is given, the second (port) element of the returned tuple will be None. host:port argument, for example, is accepted in the forms of: - hostname - hostname:1234 - hostname.domain.tld - hostname.domain.tld:5678 - [1234::5]:5678 - 1234::5 - 10.11.12.13:4567 - 10.11.12.13 """ host, port = None, None # default _s_ = host_port[:] if _s_[0] == "[": if "]" in host_port: host, _s_ = _s_.lstrip("[").rsplit("]", 1) host = ipaddress.IPv6Address(host).compressed if _s_[0] == ":": port = int(_s_.lstrip(":")) else: if len(_s_) > 1: raise ValueError('found ambiguous "{}" port in "{}"'.format(_s_, host_port)) else: if _s_.count(":") == 1: host, _hostport_separator_, port = _s_.partition(":") try: port = int(port) except ValueError as _e_: log.error('host_port "%s" port value "%s" is not an integer.', host_port, port) raise _e_ else: host = _s_ try: if not isinstance(host, ipaddress._BaseAddress): host_ip = ipaddress.ip_address(host).compressed host = host_ip except ValueError: log.debug('"%s" Not an IP address? Assuming it is a hostname.', host) if host != sanitize_host(host): log.error('bad hostname: "%s"', host) raise ValueError('bad hostname: "{}"'.format(host)) return host, port def is_fqdn(hostname): """ Verify if hostname conforms to be a FQDN. :param hostname: text string with the name of the host :return: bool, True if hostname is correct FQDN, False otherwise """ compliant = re.compile(r"(?!-)[A-Z\d\-\_]{1,63}(?<!-)$", re.IGNORECASE) return "." in hostname and len(hostname) < 0xff and all(compliant.match(x) for x in hostname.rstrip(".").split("."))
saltstack/salt
salt/utils/network.py
_hw_addr_aix
python
def _hw_addr_aix(iface): ''' Return the hardware address (a.k.a. MAC address) for a given interface on AIX MAC address not available in through interfaces ''' cmd = subprocess.Popen( 'entstat -d {0} | grep \'Hardware Address\''.format(iface), shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT).communicate()[0] if cmd: comps = cmd.split(' ') if len(comps) == 3: mac_addr = comps[2].strip('\'').strip() return mac_addr error_msg = ('Interface "{0}" either not available or does not contain a hardware address'.format(iface)) log.error(error_msg) return error_msg
Return the hardware address (a.k.a. MAC address) for a given interface on AIX MAC address not available in through interfaces
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/network.py#L1118-L1137
null
# -*- coding: utf-8 -*- ''' Define some generic socket functions for network modules ''' # Import python libs from __future__ import absolute_import, unicode_literals, print_function import itertools import os import re import types import socket import logging import platform import random import subprocess from string import ascii_letters, digits # Import 3rd-party libs from salt.ext import six from salt.ext.six.moves import range # pylint: disable=import-error,redefined-builtin # Attempt to import wmi try: import wmi import salt.utils.winapi except ImportError: pass # Import salt libs import salt.utils.args import salt.utils.files import salt.utils.path import salt.utils.platform import salt.utils.stringutils import salt.utils.zeromq from salt._compat import ipaddress from salt.exceptions import SaltClientError, SaltSystemExit from salt.utils.decorators.jinja import jinja_filter from salt.utils.versions import LooseVersion # inet_pton does not exist in Windows, this is a workaround if salt.utils.platform.is_windows(): from salt.ext import win_inet_pton # pylint: disable=unused-import log = logging.getLogger(__name__) try: import ctypes import ctypes.util libc = ctypes.cdll.LoadLibrary(ctypes.util.find_library("c")) res_init = libc.__res_init except (ImportError, OSError, AttributeError, TypeError): pass # pylint: disable=C0103 def sanitize_host(host): ''' Sanitize host string. https://tools.ietf.org/html/rfc1123#section-2.1 ''' RFC952_characters = ascii_letters + digits + ".-" return "".join([c for c in host[0:255] if c in RFC952_characters]) def isportopen(host, port): ''' Return status of a port ''' if not 1 <= int(port) <= 65535: return False sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) out = sock.connect_ex((sanitize_host(host), int(port))) return out def host_to_ips(host): ''' Returns a list of IP addresses of a given hostname or None if not found. ''' ips = [] try: for family, socktype, proto, canonname, sockaddr in socket.getaddrinfo( host, 0, socket.AF_UNSPEC, socket.SOCK_STREAM): if family == socket.AF_INET: ip, port = sockaddr elif family == socket.AF_INET6: ip, port, flow_info, scope_id = sockaddr ips.append(ip) if not ips: ips = None except Exception: ips = None return ips def _generate_minion_id(): ''' Get list of possible host names and convention names. :return: ''' # There are three types of hostnames: # 1. Network names. How host is accessed from the network. # 2. Host aliases. They might be not available in all the network or only locally (/etc/hosts) # 3. Convention names, an internal nodename. class DistinctList(list): ''' List, which allows one to append only distinct objects. Needs to work on Python 2.6, because of collections.OrderedDict only since 2.7 version. Override 'filter()' for custom filtering. ''' localhost_matchers = [r'localhost.*', r'ip6-.*', r'127[.]\d', r'0\.0\.0\.0', r'::1.*', r'ipv6-.*', r'fe00::.*', r'fe02::.*', r'1.0.0.*.ip6.arpa'] def append(self, p_object): if p_object and p_object not in self and not self.filter(p_object): super(DistinctList, self).append(p_object) return self def extend(self, iterable): for obj in iterable: self.append(obj) return self def filter(self, element): 'Returns True if element needs to be filtered' for rgx in self.localhost_matchers: if re.match(rgx, element): return True def first(self): return self and self[0] or None hostname = socket.gethostname() hosts = DistinctList().append( salt.utils.stringutils.to_unicode(socket.getfqdn(salt.utils.stringutils.to_bytes(hostname))) ).append(platform.node()).append(hostname) if not hosts: try: for a_nfo in socket.getaddrinfo(hosts.first() or 'localhost', None, socket.AF_INET, socket.SOCK_RAW, socket.IPPROTO_IP, socket.AI_CANONNAME): if len(a_nfo) > 3: hosts.append(a_nfo[3]) except socket.gaierror: log.warning('Cannot resolve address %s info via socket: %s', hosts.first() or 'localhost (N/A)', socket.gaierror) # Universal method for everywhere (Linux, Slowlaris, Windows etc) for f_name in ('/etc/hostname', '/etc/nodename', '/etc/hosts', r'{win}\system32\drivers\etc\hosts'.format(win=os.getenv('WINDIR'))): try: with salt.utils.files.fopen(f_name) as f_hdl: for line in f_hdl: line = salt.utils.stringutils.to_unicode(line) hst = line.strip().split('#')[0].strip().split() if hst: if hst[0][:4] in ('127.', '::1') or len(hst) == 1: hosts.extend(hst) except IOError: pass # include public and private ipaddresses return hosts.extend([addr for addr in ip_addrs() if not ipaddress.ip_address(addr).is_loopback]) def generate_minion_id(): ''' Return only first element of the hostname from all possible list. :return: ''' try: ret = salt.utils.stringutils.to_unicode(_generate_minion_id().first()) except TypeError: ret = None return ret or 'localhost' def get_socket(addr, type=socket.SOCK_STREAM, proto=0): ''' Return a socket object for the addr IP-version agnostic ''' version = ipaddress.ip_address(addr).version if version == 4: family = socket.AF_INET elif version == 6: family = socket.AF_INET6 return socket.socket(family, type, proto) def get_fqhostname(): ''' Returns the fully qualified hostname ''' # try getaddrinfo() fqdn = None try: addrinfo = socket.getaddrinfo( socket.gethostname(), 0, socket.AF_UNSPEC, socket.SOCK_STREAM, socket.SOL_TCP, socket.AI_CANONNAME ) for info in addrinfo: # info struct [family, socktype, proto, canonname, sockaddr] # On Windows `canonname` can be an empty string # This can cause the function to return `None` if len(info) > 3 and info[3]: fqdn = info[3] break except socket.gaierror: pass # NOTE: this used to log.error() but it was later disabled except socket.error as err: log.debug('socket.getaddrinfo() failure while finding fqdn: %s', err) if fqdn is None: fqdn = socket.getfqdn() return fqdn def ip_to_host(ip): ''' Returns the hostname of a given IP ''' try: hostname, aliaslist, ipaddrlist = socket.gethostbyaddr(ip) except Exception as exc: log.debug('salt.utils.network.ip_to_host(%r) failed: %s', ip, exc) hostname = None return hostname # pylint: enable=C0103 def is_reachable_host(entity_name): ''' Returns a bool telling if the entity name is a reachable host (IPv4/IPv6/FQDN/etc). :param hostname: :return: ''' try: assert type(socket.getaddrinfo(entity_name, 0, 0, 0, 0)) == list ret = True except socket.gaierror: ret = False return ret def is_ip(ip): ''' Returns a bool telling if the passed IP is a valid IPv4 or IPv6 address. ''' return is_ipv4(ip) or is_ipv6(ip) def is_ipv4(ip): ''' Returns a bool telling if the value passed to it was a valid IPv4 address ''' try: return ipaddress.ip_address(ip).version == 4 except ValueError: return False def is_ipv6(ip): ''' Returns a bool telling if the value passed to it was a valid IPv6 address ''' try: return ipaddress.ip_address(ip).version == 6 except ValueError: return False def is_subnet(cidr): ''' Returns a bool telling if the passed string is an IPv4 or IPv6 subnet ''' return is_ipv4_subnet(cidr) or is_ipv6_subnet(cidr) def is_ipv4_subnet(cidr): ''' Returns a bool telling if the passed string is an IPv4 subnet ''' try: return '/' in cidr and bool(ipaddress.IPv4Network(cidr)) except Exception: return False def is_ipv6_subnet(cidr): ''' Returns a bool telling if the passed string is an IPv6 subnet ''' try: return '/' in cidr and bool(ipaddress.IPv6Network(cidr)) except Exception: return False @jinja_filter('is_ip') def is_ip_filter(ip, options=None): ''' Returns a bool telling if the passed IP is a valid IPv4 or IPv6 address. ''' return is_ipv4_filter(ip, options=options) or is_ipv6_filter(ip, options=options) def _ip_options_global(ip_obj, version): return not ip_obj.is_private def _ip_options_multicast(ip_obj, version): return ip_obj.is_multicast def _ip_options_loopback(ip_obj, version): return ip_obj.is_loopback def _ip_options_link_local(ip_obj, version): return ip_obj.is_link_local def _ip_options_private(ip_obj, version): return ip_obj.is_private def _ip_options_reserved(ip_obj, version): return ip_obj.is_reserved def _ip_options_site_local(ip_obj, version): if version == 6: return ip_obj.is_site_local return False def _ip_options_unspecified(ip_obj, version): return ip_obj.is_unspecified def _ip_options(ip_obj, version, options=None): # will process and IP options options_fun_map = { 'global': _ip_options_global, 'link-local': _ip_options_link_local, 'linklocal': _ip_options_link_local, 'll': _ip_options_link_local, 'link_local': _ip_options_link_local, 'loopback': _ip_options_loopback, 'lo': _ip_options_loopback, 'multicast': _ip_options_multicast, 'private': _ip_options_private, 'public': _ip_options_global, 'reserved': _ip_options_reserved, 'site-local': _ip_options_site_local, 'sl': _ip_options_site_local, 'site_local': _ip_options_site_local, 'unspecified': _ip_options_unspecified } if not options: return six.text_type(ip_obj) # IP version already checked options_list = [option.strip() for option in options.split(',')] for option, fun in options_fun_map.items(): if option in options_list: fun_res = fun(ip_obj, version) if not fun_res: return None # stop at first failed test # else continue return six.text_type(ip_obj) def _is_ipv(ip, version, options=None): if not version: version = 4 if version not in (4, 6): return None try: ip_obj = ipaddress.ip_address(ip) except ValueError: # maybe it is an IP network try: ip_obj = ipaddress.ip_interface(ip) except ValueError: # nope, still not :( return None if not ip_obj.version == version: return None # has the right version, let's move on return _ip_options(ip_obj, version, options=options) @jinja_filter('is_ipv4') def is_ipv4_filter(ip, options=None): ''' Returns a bool telling if the value passed to it was a valid IPv4 address. ip The IP address. net: False Consider IP addresses followed by netmask. options CSV of options regarding the nature of the IP address. E.g.: loopback, multicast, private etc. ''' _is_ipv4 = _is_ipv(ip, 4, options=options) return isinstance(_is_ipv4, six.string_types) @jinja_filter('is_ipv6') def is_ipv6_filter(ip, options=None): ''' Returns a bool telling if the value passed to it was a valid IPv6 address. ip The IP address. net: False Consider IP addresses followed by netmask. options CSV of options regarding the nature of the IP address. E.g.: loopback, multicast, private etc. ''' _is_ipv6 = _is_ipv(ip, 6, options=options) return isinstance(_is_ipv6, six.string_types) def _ipv_filter(value, version, options=None): if version not in (4, 6): return if isinstance(value, (six.string_types, six.text_type, six.binary_type)): return _is_ipv(value, version, options=options) # calls is_ipv4 or is_ipv6 for `value` elif isinstance(value, (list, tuple, types.GeneratorType)): # calls is_ipv4 or is_ipv6 for each element in the list # os it filters and returns only those elements having the desired IP version return [ _is_ipv(addr, version, options=options) for addr in value if _is_ipv(addr, version, options=options) is not None ] return None @jinja_filter('ipv4') def ipv4(value, options=None): ''' Filters a list and returns IPv4 values only. ''' return _ipv_filter(value, 4, options=options) @jinja_filter('ipv6') def ipv6(value, options=None): ''' Filters a list and returns IPv6 values only. ''' return _ipv_filter(value, 6, options=options) @jinja_filter('ipaddr') def ipaddr(value, options=None): ''' Filters and returns only valid IP objects. ''' ipv4_obj = ipv4(value, options=options) ipv6_obj = ipv6(value, options=options) if ipv4_obj is None or ipv6_obj is None: # an IP address can be either IPv4 either IPv6 # therefofe if the value passed as arg is not a list, at least one of the calls above will return None # if one of them is none, means that we should return only one of them return ipv4_obj or ipv6_obj # one of them else: return ipv4_obj + ipv6_obj # extend lists def _filter_ipaddr(value, options, version=None): ipaddr_filter_out = None if version: if version == 4: ipaddr_filter_out = ipv4(value, options) elif version == 6: ipaddr_filter_out = ipv6(value, options) else: ipaddr_filter_out = ipaddr(value, options) if not ipaddr_filter_out: return if not isinstance(ipaddr_filter_out, (list, tuple, types.GeneratorType)): ipaddr_filter_out = [ipaddr_filter_out] return ipaddr_filter_out @jinja_filter('ip_host') def ip_host(value, options=None, version=None): ''' Returns the interfaces IP address, e.g.: 192.168.0.1/28. ''' ipaddr_filter_out = _filter_ipaddr(value, options=options, version=version) if not ipaddr_filter_out: return if not isinstance(value, (list, tuple, types.GeneratorType)): return six.text_type(ipaddress.ip_interface(ipaddr_filter_out[0])) return [six.text_type(ipaddress.ip_interface(ip_a)) for ip_a in ipaddr_filter_out] def _network_hosts(ip_addr_entry): return [ six.text_type(host) for host in ipaddress.ip_network(ip_addr_entry, strict=False).hosts() ] @jinja_filter('network_hosts') def network_hosts(value, options=None, version=None): ''' Return the list of hosts within a network. .. note:: When running this command with a large IPv6 network, the command will take a long time to gather all of the hosts. ''' ipaddr_filter_out = _filter_ipaddr(value, options=options, version=version) if not ipaddr_filter_out: return if not isinstance(value, (list, tuple, types.GeneratorType)): return _network_hosts(ipaddr_filter_out[0]) return [ _network_hosts(ip_a) for ip_a in ipaddr_filter_out ] def _network_size(ip_addr_entry): return ipaddress.ip_network(ip_addr_entry, strict=False).num_addresses @jinja_filter('network_size') def network_size(value, options=None, version=None): ''' Get the size of a network. ''' ipaddr_filter_out = _filter_ipaddr(value, options=options, version=version) if not ipaddr_filter_out: return if not isinstance(value, (list, tuple, types.GeneratorType)): return _network_size(ipaddr_filter_out[0]) return [ _network_size(ip_a) for ip_a in ipaddr_filter_out ] def natural_ipv4_netmask(ip, fmt='prefixlen'): ''' Returns the "natural" mask of an IPv4 address ''' bits = _ipv4_to_bits(ip) if bits.startswith('11'): mask = '24' elif bits.startswith('1'): mask = '16' else: mask = '8' if fmt == 'netmask': return cidr_to_ipv4_netmask(mask) else: return '/' + mask def rpad_ipv4_network(ip): ''' Returns an IP network address padded with zeros. Ex: '192.168.3' -> '192.168.3.0' '10.209' -> '10.209.0.0' ''' return '.'.join(itertools.islice(itertools.chain(ip.split('.'), '0000'), 0, 4)) def cidr_to_ipv4_netmask(cidr_bits): ''' Returns an IPv4 netmask ''' try: cidr_bits = int(cidr_bits) if not 1 <= cidr_bits <= 32: return '' except ValueError: return '' netmask = '' for idx in range(4): if idx: netmask += '.' if cidr_bits >= 8: netmask += '255' cidr_bits -= 8 else: netmask += '{0:d}'.format(256 - (2 ** (8 - cidr_bits))) cidr_bits = 0 return netmask def _number_of_set_bits_to_ipv4_netmask(set_bits): # pylint: disable=C0103 ''' Returns an IPv4 netmask from the integer representation of that mask. Ex. 0xffffff00 -> '255.255.255.0' ''' return cidr_to_ipv4_netmask(_number_of_set_bits(set_bits)) # pylint: disable=C0103 def _number_of_set_bits(x): ''' Returns the number of bits that are set in a 32bit int ''' # Taken from http://stackoverflow.com/a/4912729. Many thanks! x -= (x >> 1) & 0x55555555 x = ((x >> 2) & 0x33333333) + (x & 0x33333333) x = ((x >> 4) + x) & 0x0f0f0f0f x += x >> 8 x += x >> 16 return x & 0x0000003f # pylint: enable=C0103 def _interfaces_ip(out): ''' Uses ip to return a dictionary of interfaces with various information about each (up/down state, ip address, netmask, and hwaddr) ''' ret = dict() def parse_network(value, cols): ''' Return a tuple of ip, netmask, broadcast based on the current set of cols ''' brd = None scope = None if '/' in value: # we have a CIDR in this address ip, cidr = value.split('/') # pylint: disable=C0103 else: ip = value # pylint: disable=C0103 cidr = 32 if type_ == 'inet': mask = cidr_to_ipv4_netmask(int(cidr)) if 'brd' in cols: brd = cols[cols.index('brd') + 1] elif type_ == 'inet6': mask = cidr if 'scope' in cols: scope = cols[cols.index('scope') + 1] return (ip, mask, brd, scope) groups = re.compile('\r?\n\\d').split(out) for group in groups: iface = None data = dict() for line in group.splitlines(): if ' ' not in line: continue match = re.match(r'^\d*:\s+([\w.\-]+)(?:@)?([\w.\-]+)?:\s+<(.+)>', line) if match: iface, parent, attrs = match.groups() if 'UP' in attrs.split(','): data['up'] = True else: data['up'] = False if parent: data['parent'] = parent continue cols = line.split() if len(cols) >= 2: type_, value = tuple(cols[0:2]) iflabel = cols[-1:][0] if type_ in ('inet', 'inet6'): if 'secondary' not in cols: ipaddr, netmask, broadcast, scope = parse_network(value, cols) if type_ == 'inet': if 'inet' not in data: data['inet'] = list() addr_obj = dict() addr_obj['address'] = ipaddr addr_obj['netmask'] = netmask addr_obj['broadcast'] = broadcast addr_obj['label'] = iflabel data['inet'].append(addr_obj) elif type_ == 'inet6': if 'inet6' not in data: data['inet6'] = list() addr_obj = dict() addr_obj['address'] = ipaddr addr_obj['prefixlen'] = netmask addr_obj['scope'] = scope data['inet6'].append(addr_obj) else: if 'secondary' not in data: data['secondary'] = list() ip_, mask, brd, scp = parse_network(value, cols) data['secondary'].append({ 'type': type_, 'address': ip_, 'netmask': mask, 'broadcast': brd, 'label': iflabel, }) del ip_, mask, brd, scp elif type_.startswith('link'): data['hwaddr'] = value if iface: ret[iface] = data del iface, data return ret def _interfaces_ifconfig(out): ''' Uses ifconfig to return a dictionary of interfaces with various information about each (up/down state, ip address, netmask, and hwaddr) ''' ret = dict() piface = re.compile(r'^([^\s:]+)') pmac = re.compile('.*?(?:HWaddr|ether|address:|lladdr) ([0-9a-fA-F:]+)') if salt.utils.platform.is_sunos(): pip = re.compile(r'.*?(?:inet\s+)([0-9]+\.[0-9]+\.[0-9]+\.[0-9]+)(.*)') pip6 = re.compile('.*?(?:inet6 )([0-9a-fA-F:]+)') pmask6 = re.compile(r'.*?(?:inet6 [0-9a-fA-F:]+/(\d+)).*') else: pip = re.compile(r'.*?(?:inet addr:|inet [^\d]*)(.*?)\s') pip6 = re.compile('.*?(?:inet6 addr: (.*?)/|inet6 )([0-9a-fA-F:]+)') pmask6 = re.compile(r'.*?(?:inet6 addr: [0-9a-fA-F:]+/(\d+)|prefixlen (\d+))(?: Scope:([a-zA-Z]+)| scopeid (0x[0-9a-fA-F]))?') pmask = re.compile(r'.*?(?:Mask:|netmask )(?:((?:0x)?[0-9a-fA-F]{8})|([\d\.]+))') pupdown = re.compile('UP') pbcast = re.compile(r'.*?(?:Bcast:|broadcast )([\d\.]+)') groups = re.compile('\r?\n(?=\\S)').split(out) for group in groups: data = dict() iface = '' updown = False for line in group.splitlines(): miface = piface.match(line) mmac = pmac.match(line) mip = pip.match(line) mip6 = pip6.match(line) mupdown = pupdown.search(line) if miface: iface = miface.group(1) if mmac: data['hwaddr'] = mmac.group(1) if salt.utils.platform.is_sunos(): expand_mac = [] for chunk in data['hwaddr'].split(':'): expand_mac.append('0{0}'.format(chunk) if len(chunk) < 2 else '{0}'.format(chunk)) data['hwaddr'] = ':'.join(expand_mac) if mip: if 'inet' not in data: data['inet'] = list() addr_obj = dict() addr_obj['address'] = mip.group(1) mmask = pmask.match(line) if mmask: if mmask.group(1): mmask = _number_of_set_bits_to_ipv4_netmask( int(mmask.group(1), 16)) else: mmask = mmask.group(2) addr_obj['netmask'] = mmask mbcast = pbcast.match(line) if mbcast: addr_obj['broadcast'] = mbcast.group(1) data['inet'].append(addr_obj) if mupdown: updown = True if mip6: if 'inet6' not in data: data['inet6'] = list() addr_obj = dict() addr_obj['address'] = mip6.group(1) or mip6.group(2) mmask6 = pmask6.match(line) if mmask6: addr_obj['prefixlen'] = mmask6.group(1) or mmask6.group(2) if not salt.utils.platform.is_sunos(): ipv6scope = mmask6.group(3) or mmask6.group(4) addr_obj['scope'] = ipv6scope.lower() if ipv6scope is not None else ipv6scope # SunOS sometimes has ::/0 as inet6 addr when using addrconf if not salt.utils.platform.is_sunos() \ or addr_obj['address'] != '::' \ and addr_obj['prefixlen'] != 0: data['inet6'].append(addr_obj) data['up'] = updown if iface in ret: # SunOS optimization, where interfaces occur twice in 'ifconfig -a' # output with the same name: for ipv4 and then for ipv6 addr family. # Every instance has it's own 'UP' status and we assume that ipv4 # status determines global interface status. # # merge items with higher priority for older values # after that merge the inet and inet6 sub items for both ret[iface] = dict(list(data.items()) + list(ret[iface].items())) if 'inet' in data: ret[iface]['inet'].extend(x for x in data['inet'] if x not in ret[iface]['inet']) if 'inet6' in data: ret[iface]['inet6'].extend(x for x in data['inet6'] if x not in ret[iface]['inet6']) else: ret[iface] = data del data return ret def linux_interfaces(): ''' Obtain interface information for *NIX/BSD variants ''' ifaces = dict() ip_path = salt.utils.path.which('ip') ifconfig_path = None if ip_path else salt.utils.path.which('ifconfig') if ip_path: cmd1 = subprocess.Popen( '{0} link show'.format(ip_path), shell=True, close_fds=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT).communicate()[0] cmd2 = subprocess.Popen( '{0} addr show'.format(ip_path), shell=True, close_fds=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT).communicate()[0] ifaces = _interfaces_ip("{0}\n{1}".format( salt.utils.stringutils.to_str(cmd1), salt.utils.stringutils.to_str(cmd2))) elif ifconfig_path: cmd = subprocess.Popen( '{0} -a'.format(ifconfig_path), shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT).communicate()[0] ifaces = _interfaces_ifconfig(salt.utils.stringutils.to_str(cmd)) return ifaces def _netbsd_interfaces_ifconfig(out): ''' Uses ifconfig to return a dictionary of interfaces with various information about each (up/down state, ip address, netmask, and hwaddr) ''' ret = dict() piface = re.compile(r'^([^\s:]+)') pmac = re.compile('.*?address: ([0-9a-f:]+)') pip = re.compile(r'.*?inet [^\d]*(.*?)/([\d]*)\s') pip6 = re.compile(r'.*?inet6 ([0-9a-f:]+)%([a-zA-Z0-9]*)/([\d]*)\s') pupdown = re.compile('UP') pbcast = re.compile(r'.*?broadcast ([\d\.]+)') groups = re.compile('\r?\n(?=\\S)').split(out) for group in groups: data = dict() iface = '' updown = False for line in group.splitlines(): miface = piface.match(line) mmac = pmac.match(line) mip = pip.match(line) mip6 = pip6.match(line) mupdown = pupdown.search(line) if miface: iface = miface.group(1) if mmac: data['hwaddr'] = mmac.group(1) if mip: if 'inet' not in data: data['inet'] = list() addr_obj = dict() addr_obj['address'] = mip.group(1) mmask = mip.group(2) if mip.group(2): addr_obj['netmask'] = cidr_to_ipv4_netmask(mip.group(2)) mbcast = pbcast.match(line) if mbcast: addr_obj['broadcast'] = mbcast.group(1) data['inet'].append(addr_obj) if mupdown: updown = True if mip6: if 'inet6' not in data: data['inet6'] = list() addr_obj = dict() addr_obj['address'] = mip6.group(1) mmask6 = mip6.group(3) addr_obj['scope'] = mip6.group(2) addr_obj['prefixlen'] = mip6.group(3) data['inet6'].append(addr_obj) data['up'] = updown ret[iface] = data del data return ret def netbsd_interfaces(): ''' Obtain interface information for NetBSD >= 8 where the ifconfig output diverged from other BSD variants (Netmask is now part of the address) ''' # NetBSD versions prior to 8.0 can still use linux_interfaces() if LooseVersion(os.uname()[2]) < LooseVersion('8.0'): return linux_interfaces() ifconfig_path = salt.utils.path.which('ifconfig') cmd = subprocess.Popen( '{0} -a'.format(ifconfig_path), shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT).communicate()[0] return _netbsd_interfaces_ifconfig(salt.utils.stringutils.to_str(cmd)) def _interfaces_ipconfig(out): ''' Returns a dictionary of interfaces with various information about each (up/down state, ip address, netmask, and hwaddr) NOTE: This is not used by any function and may be able to be removed in the future. ''' ifaces = dict() iface = None adapter_iface_regex = re.compile(r'adapter (\S.+):$') for line in out.splitlines(): if not line: continue # TODO what does Windows call Infiniband and 10/40gige adapters if line.startswith('Ethernet'): iface = ifaces[adapter_iface_regex.search(line).group(1)] iface['up'] = True addr = None continue if iface: key, val = line.split(',', 1) key = key.strip(' .') val = val.strip() if addr and key == 'Subnet Mask': addr['netmask'] = val elif key in ('IP Address', 'IPv4 Address'): if 'inet' not in iface: iface['inet'] = list() addr = {'address': val.rstrip('(Preferred)'), 'netmask': None, 'broadcast': None} # TODO find the broadcast iface['inet'].append(addr) elif 'IPv6 Address' in key: if 'inet6' not in iface: iface['inet'] = list() # XXX What is the prefixlen!? addr = {'address': val.rstrip('(Preferred)'), 'prefixlen': None} iface['inet6'].append(addr) elif key == 'Physical Address': iface['hwaddr'] = val elif key == 'Media State': # XXX seen used for tunnel adaptors # might be useful iface['up'] = (val != 'Media disconnected') def win_interfaces(): ''' Obtain interface information for Windows systems ''' with salt.utils.winapi.Com(): c = wmi.WMI() ifaces = {} for iface in c.Win32_NetworkAdapterConfiguration(IPEnabled=1): ifaces[iface.Description] = dict() if iface.MACAddress: ifaces[iface.Description]['hwaddr'] = iface.MACAddress if iface.IPEnabled: ifaces[iface.Description]['up'] = True for ip in iface.IPAddress: if '.' in ip: if 'inet' not in ifaces[iface.Description]: ifaces[iface.Description]['inet'] = [] item = {'address': ip, 'label': iface.Description} if iface.DefaultIPGateway: broadcast = next((i for i in iface.DefaultIPGateway if '.' in i), '') if broadcast: item['broadcast'] = broadcast if iface.IPSubnet: netmask = next((i for i in iface.IPSubnet if '.' in i), '') if netmask: item['netmask'] = netmask ifaces[iface.Description]['inet'].append(item) if ':' in ip: if 'inet6' not in ifaces[iface.Description]: ifaces[iface.Description]['inet6'] = [] item = {'address': ip} if iface.DefaultIPGateway: broadcast = next((i for i in iface.DefaultIPGateway if ':' in i), '') if broadcast: item['broadcast'] = broadcast if iface.IPSubnet: netmask = next((i for i in iface.IPSubnet if ':' in i), '') if netmask: item['netmask'] = netmask ifaces[iface.Description]['inet6'].append(item) else: ifaces[iface.Description]['up'] = False return ifaces def interfaces(): ''' Return a dictionary of information about all the interfaces on the minion ''' if salt.utils.platform.is_windows(): return win_interfaces() elif salt.utils.platform.is_netbsd(): return netbsd_interfaces() else: return linux_interfaces() def get_net_start(ipaddr, netmask): ''' Return the address of the network ''' net = ipaddress.ip_network('{0}/{1}'.format(ipaddr, netmask), strict=False) return six.text_type(net.network_address) def get_net_size(mask): ''' Turns an IPv4 netmask into it's corresponding prefix length (255.255.255.0 -> 24 as in 192.168.1.10/24). ''' binary_str = '' for octet in mask.split('.'): binary_str += bin(int(octet))[2:].zfill(8) return len(binary_str.rstrip('0')) def calc_net(ipaddr, netmask=None): ''' Takes IP (CIDR notation supported) and optionally netmask and returns the network in CIDR-notation. (The IP can be any IP inside the subnet) ''' if netmask is not None: ipaddr = '{0}/{1}'.format(ipaddr, netmask) return six.text_type(ipaddress.ip_network(ipaddr, strict=False)) def _ipv4_to_bits(ipaddr): ''' Accepts an IPv4 dotted quad and returns a string representing its binary counterpart ''' return ''.join([bin(int(x))[2:].rjust(8, '0') for x in ipaddr.split('.')]) def _get_iface_info(iface): ''' If `iface` is available, return interface info and no error, otherwise return no info and log and return an error ''' iface_info = interfaces() if iface in iface_info.keys(): return iface_info, False else: error_msg = ('Interface "{0}" not in available interfaces: "{1}"' ''.format(iface, '", "'.join(iface_info.keys()))) log.error(error_msg) return None, error_msg def hw_addr(iface): ''' Return the hardware address (a.k.a. MAC address) for a given interface .. versionchanged:: 2016.11.4 Added support for AIX ''' if salt.utils.platform.is_aix(): return _hw_addr_aix iface_info, error = _get_iface_info(iface) if error is False: return iface_info.get(iface, {}).get('hwaddr', '') else: return error def interface(iface): ''' Return the details of `iface` or an error if it does not exist ''' iface_info, error = _get_iface_info(iface) if error is False: return iface_info.get(iface, {}).get('inet', '') else: return error def interface_ip(iface): ''' Return `iface` IPv4 addr or an error if `iface` does not exist ''' iface_info, error = _get_iface_info(iface) if error is False: inet = iface_info.get(iface, {}).get('inet', None) return inet[0].get('address', '') if inet else '' else: return error def _subnets(proto='inet', interfaces_=None): ''' Returns a list of subnets to which the host belongs ''' if interfaces_ is None: ifaces = interfaces() elif isinstance(interfaces_, list): ifaces = {} for key, value in six.iteritems(interfaces()): if key in interfaces_: ifaces[key] = value else: ifaces = {interfaces_: interfaces().get(interfaces_, {})} ret = set() if proto == 'inet': subnet = 'netmask' dflt_cidr = 32 elif proto == 'inet6': subnet = 'prefixlen' dflt_cidr = 128 else: log.error('Invalid proto %s calling subnets()', proto) return for ip_info in six.itervalues(ifaces): addrs = ip_info.get(proto, []) addrs.extend([addr for addr in ip_info.get('secondary', []) if addr.get('type') == proto]) for intf in addrs: if subnet in intf: intf = ipaddress.ip_interface('{0}/{1}'.format(intf['address'], intf[subnet])) else: intf = ipaddress.ip_interface('{0}/{1}'.format(intf['address'], dflt_cidr)) if not intf.is_loopback: ret.add(intf.network) return [six.text_type(net) for net in sorted(ret)] def subnets(interfaces=None): ''' Returns a list of IPv4 subnets to which the host belongs ''' return _subnets('inet', interfaces_=interfaces) def subnets6(): ''' Returns a list of IPv6 subnets to which the host belongs ''' return _subnets('inet6') def in_subnet(cidr, addr=None): ''' Returns True if host or (any of) addrs is within specified subnet, otherwise False ''' try: cidr = ipaddress.ip_network(cidr) except ValueError: log.error('Invalid CIDR \'%s\'', cidr) return False if addr is None: addr = ip_addrs() addr.extend(ip_addrs6()) elif not isinstance(addr, (list, tuple)): addr = (addr,) return any(ipaddress.ip_address(item) in cidr for item in addr) def _ip_addrs(interface=None, include_loopback=False, interface_data=None, proto='inet'): ''' Return the full list of IP adresses matching the criteria proto = inet|inet6 ''' ret = set() ifaces = interface_data \ if isinstance(interface_data, dict) \ else interfaces() if interface is None: target_ifaces = ifaces else: target_ifaces = dict([(k, v) for k, v in six.iteritems(ifaces) if k == interface]) if not target_ifaces: log.error('Interface %s not found.', interface) for ip_info in six.itervalues(target_ifaces): addrs = ip_info.get(proto, []) addrs.extend([addr for addr in ip_info.get('secondary', []) if addr.get('type') == proto]) for addr in addrs: addr = ipaddress.ip_address(addr.get('address')) if not addr.is_loopback or include_loopback: ret.add(addr) return [six.text_type(addr) for addr in sorted(ret)] def ip_addrs(interface=None, include_loopback=False, interface_data=None): ''' Returns a list of IPv4 addresses assigned to the host. 127.0.0.1 is ignored, unless 'include_loopback=True' is indicated. If 'interface' is provided, then only IP addresses from that interface will be returned. ''' return _ip_addrs(interface, include_loopback, interface_data, 'inet') def ip_addrs6(interface=None, include_loopback=False, interface_data=None): ''' Returns a list of IPv6 addresses assigned to the host. ::1 is ignored, unless 'include_loopback=True' is indicated. If 'interface' is provided, then only IP addresses from that interface will be returned. ''' return _ip_addrs(interface, include_loopback, interface_data, 'inet6') def hex2ip(hex_ip, invert=False): ''' Convert a hex string to an ip, if a failure occurs the original hex is returned. If 'invert=True' assume that ip from /proc/net/<proto> ''' if len(hex_ip) == 32: # ipv6 ip = [] for i in range(0, 32, 8): ip_part = hex_ip[i:i + 8] ip_part = [ip_part[x:x + 2] for x in range(0, 8, 2)] if invert: ip.append("{0[3]}{0[2]}:{0[1]}{0[0]}".format(ip_part)) else: ip.append("{0[0]}{0[1]}:{0[2]}{0[3]}".format(ip_part)) try: address = ipaddress.IPv6Address(":".join(ip)) if address.ipv4_mapped: return str(address.ipv4_mapped) else: return address.compressed except ipaddress.AddressValueError as ex: log.error('hex2ip - ipv6 address error: %s', ex) return hex_ip try: hip = int(hex_ip, 16) except ValueError: return hex_ip if invert: return '{3}.{2}.{1}.{0}'.format(hip >> 24 & 255, hip >> 16 & 255, hip >> 8 & 255, hip & 255) return '{0}.{1}.{2}.{3}'.format(hip >> 24 & 255, hip >> 16 & 255, hip >> 8 & 255, hip & 255) def mac2eui64(mac, prefix=None): ''' Convert a MAC address to a EUI64 identifier or, with prefix provided, a full IPv6 address ''' # http://tools.ietf.org/html/rfc4291#section-2.5.1 eui64 = re.sub(r'[.:-]', '', mac).lower() eui64 = eui64[0:6] + 'fffe' + eui64[6:] eui64 = hex(int(eui64[0:2], 16) | 2)[2:].zfill(2) + eui64[2:] if prefix is None: return ':'.join(re.findall(r'.{4}', eui64)) else: try: net = ipaddress.ip_network(prefix, strict=False) euil = int('0x{0}'.format(eui64), 16) return '{0}/{1}'.format(net[euil], net.prefixlen) except Exception: return def active_tcp(): ''' Return a dict describing all active tcp connections as quickly as possible ''' ret = {} for statf in ['/proc/net/tcp', '/proc/net/tcp6']: if os.path.isfile(statf): with salt.utils.files.fopen(statf, 'rb') as fp_: for line in fp_: line = salt.utils.stringutils.to_unicode(line) if line.strip().startswith('sl'): continue iret = _parse_tcp_line(line) sl = next(iter(iret)) if iret[sl]['state'] == 1: # 1 is ESTABLISHED del iret[sl]['state'] ret[len(ret)] = iret[sl] return ret def local_port_tcp(port): ''' Return a set of remote ip addrs attached to the specified local port ''' ret = _remotes_on(port, 'local_port') return ret def remote_port_tcp(port): ''' Return a set of ip addrs the current host is connected to on given port ''' ret = _remotes_on(port, 'remote_port') return ret def _remotes_on(port, which_end): ''' Return a set of ip addrs active tcp connections ''' port = int(port) ret = _netlink_tool_remote_on(port, which_end) if ret is not None: return ret ret = set() proc_available = False for statf in ['/proc/net/tcp', '/proc/net/tcp6']: if os.path.isfile(statf): proc_available = True with salt.utils.files.fopen(statf, 'r') as fp_: for line in fp_: line = salt.utils.stringutils.to_unicode(line) if line.strip().startswith('sl'): continue iret = _parse_tcp_line(line) sl = next(iter(iret)) if iret[sl][which_end] == port and iret[sl]['state'] == 1: # 1 is ESTABLISHED ret.add(iret[sl]['remote_addr']) if not proc_available: # Fallback to use OS specific tools if salt.utils.platform.is_sunos(): return _sunos_remotes_on(port, which_end) if salt.utils.platform.is_freebsd(): return _freebsd_remotes_on(port, which_end) if salt.utils.platform.is_netbsd(): return _netbsd_remotes_on(port, which_end) if salt.utils.platform.is_openbsd(): return _openbsd_remotes_on(port, which_end) if salt.utils.platform.is_windows(): return _windows_remotes_on(port, which_end) if salt.utils.platform.is_aix(): return _aix_remotes_on(port, which_end) return _linux_remotes_on(port, which_end) return ret def _parse_tcp_line(line): ''' Parse a single line from the contents of /proc/net/tcp or /proc/net/tcp6 ''' ret = {} comps = line.strip().split() sl = comps[0].rstrip(':') ret[sl] = {} l_addr, l_port = comps[1].split(':') r_addr, r_port = comps[2].split(':') ret[sl]['local_addr'] = hex2ip(l_addr, True) ret[sl]['local_port'] = int(l_port, 16) ret[sl]['remote_addr'] = hex2ip(r_addr, True) ret[sl]['remote_port'] = int(r_port, 16) ret[sl]['state'] = int(comps[3], 16) return ret def _netlink_tool_remote_on(port, which_end): ''' Returns set of ipv4 host addresses of remote established connections on local or remote tcp port. Parses output of shell 'ss' to get connections [root@salt-master ~]# ss -ant State Recv-Q Send-Q Local Address:Port Peer Address:Port LISTEN 0 511 *:80 *:* LISTEN 0 128 *:22 *:* ESTAB 0 0 127.0.0.1:56726 127.0.0.1:4505 ''' remotes = set() valid = False try: data = subprocess.check_output(['ss', '-ant']) # pylint: disable=minimum-python-version except subprocess.CalledProcessError: log.error('Failed ss') raise except OSError: # not command "No such file or directory" return None lines = salt.utils.stringutils.to_str(data).split('\n') for line in lines: if 'Address:Port' in line: # ss tools may not be valid valid = True continue elif 'ESTAB' not in line: continue chunks = line.split() local_host, local_port = chunks[3].split(':', 1) remote_host, remote_port = chunks[4].split(':', 1) if which_end == 'remote_port' and int(remote_port) != port: continue if which_end == 'local_port' and int(local_port) != port: continue remotes.add(remote_host) if valid is False: remotes = None return remotes def _sunos_remotes_on(port, which_end): ''' SunOS specific helper function. Returns set of ipv4 host addresses of remote established connections on local or remote tcp port. Parses output of shell 'netstat' to get connections [root@salt-master ~]# netstat -f inet -n TCP: IPv4 Local Address Remote Address Swind Send-Q Rwind Recv-Q State -------------------- -------------------- ----- ------ ----- ------ ----------- 10.0.0.101.4505 10.0.0.1.45329 1064800 0 1055864 0 ESTABLISHED 10.0.0.101.4505 10.0.0.100.50798 1064800 0 1055864 0 ESTABLISHED ''' remotes = set() try: data = subprocess.check_output(['netstat', '-f', 'inet', '-n']) # pylint: disable=minimum-python-version except subprocess.CalledProcessError: log.error('Failed netstat') raise lines = salt.utils.stringutils.to_str(data).split('\n') for line in lines: if 'ESTABLISHED' not in line: continue chunks = line.split() local_host, local_port = chunks[0].rsplit('.', 1) remote_host, remote_port = chunks[1].rsplit('.', 1) if which_end == 'remote_port' and int(remote_port) != port: continue if which_end == 'local_port' and int(local_port) != port: continue remotes.add(remote_host) return remotes def _freebsd_remotes_on(port, which_end): ''' Returns set of ipv4 host addresses of remote established connections on local tcp port port. Parses output of shell 'sockstat' (FreeBSD) to get connections $ sudo sockstat -4 USER COMMAND PID FD PROTO LOCAL ADDRESS FOREIGN ADDRESS root python2.7 1456 29 tcp4 *:4505 *:* root python2.7 1445 17 tcp4 *:4506 *:* root python2.7 1294 14 tcp4 127.0.0.1:11813 127.0.0.1:4505 root python2.7 1294 41 tcp4 127.0.0.1:61115 127.0.0.1:4506 $ sudo sockstat -4 -c -p 4506 USER COMMAND PID FD PROTO LOCAL ADDRESS FOREIGN ADDRESS root python2.7 1294 41 tcp4 127.0.0.1:61115 127.0.0.1:4506 ''' port = int(port) remotes = set() try: cmd = salt.utils.args.shlex_split('sockstat -4 -c -p {0}'.format(port)) data = subprocess.check_output(cmd) # pylint: disable=minimum-python-version except subprocess.CalledProcessError as ex: log.error('Failed "sockstat" with returncode = %s', ex.returncode) raise lines = salt.utils.stringutils.to_str(data).split('\n') for line in lines: chunks = line.split() if not chunks: continue # ['root', 'python2.7', '1456', '37', 'tcp4', # '127.0.0.1:4505-', '127.0.0.1:55703'] # print chunks if 'COMMAND' in chunks[1]: continue # ignore header if len(chunks) < 2: continue # sockstat -4 -c -p 4506 does this with high PIDs: # USER COMMAND PID FD PROTO LOCAL ADDRESS FOREIGN ADDRESS # salt-master python2.781106 35 tcp4 192.168.12.34:4506 192.168.12.45:60143 local = chunks[-2] remote = chunks[-1] lhost, lport = local.split(':') rhost, rport = remote.split(':') if which_end == 'local' and int(lport) != port: # ignore if local port not port continue if which_end == 'remote' and int(rport) != port: # ignore if remote port not port continue remotes.add(rhost) return remotes def _netbsd_remotes_on(port, which_end): ''' Returns set of ipv4 host addresses of remote established connections on local tcp port port. Parses output of shell 'sockstat' (NetBSD) to get connections $ sudo sockstat -4 -n USER COMMAND PID FD PROTO LOCAL ADDRESS FOREIGN ADDRESS root python2.7 1456 29 tcp *.4505 *.* root python2.7 1445 17 tcp *.4506 *.* root python2.7 1294 14 tcp 127.0.0.1.11813 127.0.0.1.4505 root python2.7 1294 41 tcp 127.0.0.1.61115 127.0.0.1.4506 $ sudo sockstat -4 -c -n -p 4506 USER COMMAND PID FD PROTO LOCAL ADDRESS FOREIGN ADDRESS root python2.7 1294 41 tcp 127.0.0.1.61115 127.0.0.1.4506 ''' port = int(port) remotes = set() try: cmd = salt.utils.args.shlex_split('sockstat -4 -c -n -p {0}'.format(port)) data = subprocess.check_output(cmd) # pylint: disable=minimum-python-version except subprocess.CalledProcessError as ex: log.error('Failed "sockstat" with returncode = %s', ex.returncode) raise lines = salt.utils.stringutils.to_str(data).split('\n') for line in lines: chunks = line.split() if not chunks: continue # ['root', 'python2.7', '1456', '37', 'tcp', # '127.0.0.1.4505-', '127.0.0.1.55703'] # print chunks if 'COMMAND' in chunks[1]: continue # ignore header if len(chunks) < 2: continue local = chunks[5].split('.') lport = local.pop() lhost = '.'.join(local) remote = chunks[6].split('.') rport = remote.pop() rhost = '.'.join(remote) if which_end == 'local' and int(lport) != port: # ignore if local port not port continue if which_end == 'remote' and int(rport) != port: # ignore if remote port not port continue remotes.add(rhost) return remotes def _openbsd_remotes_on(port, which_end): ''' OpenBSD specific helper function. Returns set of ipv4 host addresses of remote established connections on local or remote tcp port. Parses output of shell 'netstat' to get connections $ netstat -nf inet Active Internet connections Proto Recv-Q Send-Q Local Address Foreign Address (state) tcp 0 0 10.0.0.101.4505 10.0.0.1.45329 ESTABLISHED tcp 0 0 10.0.0.101.4505 10.0.0.100.50798 ESTABLISHED ''' remotes = set() try: data = subprocess.check_output(['netstat', '-nf', 'inet']) # pylint: disable=minimum-python-version except subprocess.CalledProcessError: log.error('Failed netstat') raise lines = data.split('\n') for line in lines: if 'ESTABLISHED' not in line: continue chunks = line.split() local_host, local_port = chunks[3].rsplit('.', 1) remote_host, remote_port = chunks[4].rsplit('.', 1) if which_end == 'remote_port' and int(remote_port) != port: continue if which_end == 'local_port' and int(local_port) != port: continue remotes.add(remote_host) return remotes def _windows_remotes_on(port, which_end): r''' Windows specific helper function. Returns set of ipv4 host addresses of remote established connections on local or remote tcp port. Parses output of shell 'netstat' to get connections C:\>netstat -n Active Connections Proto Local Address Foreign Address State TCP 10.2.33.17:3007 130.164.12.233:10123 ESTABLISHED TCP 10.2.33.17:3389 130.164.30.5:10378 ESTABLISHED ''' remotes = set() try: data = subprocess.check_output(['netstat', '-n']) # pylint: disable=minimum-python-version except subprocess.CalledProcessError: log.error('Failed netstat') raise lines = salt.utils.stringutils.to_str(data).split('\n') for line in lines: if 'ESTABLISHED' not in line: continue chunks = line.split() local_host, local_port = chunks[1].rsplit(':', 1) remote_host, remote_port = chunks[2].rsplit(':', 1) if which_end == 'remote_port' and int(remote_port) != port: continue if which_end == 'local_port' and int(local_port) != port: continue remotes.add(remote_host) return remotes def _linux_remotes_on(port, which_end): ''' Linux specific helper function. Returns set of ip host addresses of remote established connections on local tcp port port. Parses output of shell 'lsof' to get connections $ sudo lsof -iTCP:4505 -n COMMAND PID USER FD TYPE DEVICE SIZE/OFF NODE NAME Python 9971 root 35u IPv4 0x18a8464a29ca329d 0t0 TCP *:4505 (LISTEN) Python 9971 root 37u IPv4 0x18a8464a29b2b29d 0t0 TCP 127.0.0.1:4505->127.0.0.1:55703 (ESTABLISHED) Python 10152 root 22u IPv4 0x18a8464a29c8cab5 0t0 TCP 127.0.0.1:55703->127.0.0.1:4505 (ESTABLISHED) Python 10153 root 22u IPv4 0x18a8464a29c8cab5 0t0 TCP [fe80::249a]:4505->[fe80::150]:59367 (ESTABLISHED) ''' remotes = set() try: data = subprocess.check_output( ['lsof', '-iTCP:{0:d}'.format(port), '-n', '-P'] # pylint: disable=minimum-python-version ) except subprocess.CalledProcessError as ex: if ex.returncode == 1: # Lsof return 1 if any error was detected, including the failure # to locate Internet addresses, and it is not an error in this case. log.warning('"lsof" returncode = 1, likely no active TCP sessions.') return remotes log.error('Failed "lsof" with returncode = %s', ex.returncode) raise lines = salt.utils.stringutils.to_str(data).split('\n') for line in lines: chunks = line.split() if not chunks: continue # ['Python', '9971', 'root', '37u', 'IPv4', '0x18a8464a29b2b29d', '0t0', # 'TCP', '127.0.0.1:4505->127.0.0.1:55703', '(ESTABLISHED)'] # print chunks if 'COMMAND' in chunks[0]: continue # ignore header if 'ESTABLISHED' not in chunks[-1]: continue # ignore if not ESTABLISHED # '127.0.0.1:4505->127.0.0.1:55703' local, remote = chunks[8].split('->') _, lport = local.rsplit(':', 1) rhost, rport = remote.rsplit(':', 1) if which_end == 'remote_port' and int(rport) != port: continue if which_end == 'local_port' and int(lport) != port: continue remotes.add(rhost.strip("[]")) return remotes def _aix_remotes_on(port, which_end): ''' AIX specific helper function. Returns set of ipv4 host addresses of remote established connections on local or remote tcp port. Parses output of shell 'netstat' to get connections root@la68pp002_pub:/opt/salt/lib/python2.7/site-packages/salt/modules# netstat -f inet -n Active Internet connections Proto Recv-Q Send-Q Local Address Foreign Address (state) tcp4 0 0 172.29.149.95.50093 209.41.78.13.4505 ESTABLISHED tcp4 0 0 127.0.0.1.9514 *.* LISTEN tcp4 0 0 127.0.0.1.9515 *.* LISTEN tcp4 0 0 127.0.0.1.199 127.0.0.1.32779 ESTABLISHED tcp4 0 0 127.0.0.1.32779 127.0.0.1.199 ESTABLISHED tcp4 0 40 172.29.149.95.22 172.29.96.83.41022 ESTABLISHED tcp4 0 0 172.29.149.95.22 172.29.96.83.41032 ESTABLISHED tcp4 0 0 127.0.0.1.32771 127.0.0.1.32775 ESTABLISHED tcp 0 0 127.0.0.1.32775 127.0.0.1.32771 ESTABLISHED tcp4 0 0 127.0.0.1.32771 127.0.0.1.32776 ESTABLISHED tcp 0 0 127.0.0.1.32776 127.0.0.1.32771 ESTABLISHED tcp4 0 0 127.0.0.1.32771 127.0.0.1.32777 ESTABLISHED tcp 0 0 127.0.0.1.32777 127.0.0.1.32771 ESTABLISHED tcp4 0 0 127.0.0.1.32771 127.0.0.1.32778 ESTABLISHED tcp 0 0 127.0.0.1.32778 127.0.0.1.32771 ESTABLISHED ''' remotes = set() try: data = subprocess.check_output(['netstat', '-f', 'inet', '-n']) # pylint: disable=minimum-python-version except subprocess.CalledProcessError: log.error('Failed netstat') raise lines = salt.utils.stringutils.to_str(data).split('\n') for line in lines: if 'ESTABLISHED' not in line: continue chunks = line.split() local_host, local_port = chunks[3].rsplit('.', 1) remote_host, remote_port = chunks[4].rsplit('.', 1) if which_end == 'remote_port' and int(remote_port) != port: continue if which_end == 'local_port' and int(local_port) != port: continue remotes.add(remote_host) return remotes @jinja_filter('gen_mac') def gen_mac(prefix='AC:DE:48'): ''' Generates a MAC address with the defined OUI prefix. Common prefixes: - ``00:16:3E`` -- Xen - ``00:18:51`` -- OpenVZ - ``00:50:56`` -- VMware (manually generated) - ``52:54:00`` -- QEMU/KVM - ``AC:DE:48`` -- PRIVATE References: - http://standards.ieee.org/develop/regauth/oui/oui.txt - https://www.wireshark.org/tools/oui-lookup.html - https://en.wikipedia.org/wiki/MAC_address ''' return '{0}:{1:02X}:{2:02X}:{3:02X}'.format(prefix, random.randint(0, 0xff), random.randint(0, 0xff), random.randint(0, 0xff)) @jinja_filter('mac_str_to_bytes') def mac_str_to_bytes(mac_str): ''' Convert a MAC address string into bytes. Works with or without separators: b1 = mac_str_to_bytes('08:00:27:13:69:77') b2 = mac_str_to_bytes('080027136977') assert b1 == b2 assert isinstance(b1, bytes) ''' if len(mac_str) == 12: pass elif len(mac_str) == 17: sep = mac_str[2] mac_str = mac_str.replace(sep, '') else: raise ValueError('Invalid MAC address') chars = (int(mac_str[s:s+2], 16) for s in range(0, 12, 2)) return bytes(chars) if six.PY3 else b''.join(chr(x) for x in chars) def refresh_dns(): ''' issue #21397: force glibc to re-read resolv.conf ''' try: res_init() except NameError: # Exception raised loading the library, thus res_init is not defined pass @jinja_filter('connection_check') def connection_check(addr, port=80, safe=False, ipv6=None): ''' Provides a convenient alias for the dns_check filter. ''' return dns_check(addr, port, safe, ipv6) @jinja_filter('dns_check') def dns_check(addr, port=80, safe=False, ipv6=None, attempt_connect=True): ''' Return the ip resolved by dns, but do not exit on failure, only raise an exception. Obeys system preference for IPv4/6 address resolution - this can be overridden by the ipv6 flag. Tries to connect to the address before considering it useful. If no address can be reached, the first one resolved is used as a fallback. ''' error = False lookup = addr seen_ipv6 = False family = socket.AF_INET6 if ipv6 else socket.AF_INET if ipv6 is False else socket.AF_UNSPEC hostnames = [] try: refresh_dns() hostnames = socket.getaddrinfo(addr, port, family, socket.SOCK_STREAM) except TypeError: err = ('Attempt to resolve address \'{0}\' failed. Invalid or unresolveable address').format(lookup) raise SaltSystemExit(code=42, msg=err) except socket.error: error = True # If ipv6 is set to True, attempt another lookup using the IPv4 family, # just in case we're attempting to lookup an IPv4 IP # as an IPv6 hostname. if error and ipv6: try: refresh_dns() hostnames = socket.getaddrinfo(addr, port, socket.AF_INET, socket.SOCK_STREAM) except TypeError: err = ('Attempt to resolve address \'{0}\' failed. Invalid or unresolveable address').format(lookup) raise SaltSystemExit(code=42, msg=err) except socket.error: error = True try: if not hostnames: error = True else: resolved = False candidates = [] for h in hostnames: # Input is IP address, passed through unchanged, just return it if h[4][0] == addr: resolved = salt.utils.zeromq.ip_bracket(addr) break candidate_addr = salt.utils.zeromq.ip_bracket(h[4][0]) # sometimes /etc/hosts contains ::1 localhost if not ipv6 and candidate_addr == '[::1]': continue candidates.append(candidate_addr) if attempt_connect: try: s = socket.socket(h[0], socket.SOCK_STREAM) s.settimeout(2) s.connect((candidate_addr.strip('[]'), h[4][1])) s.close() resolved = candidate_addr break except socket.error: pass if not resolved: if candidates: resolved = candidates[0] else: error = True except TypeError: err = ('Attempt to resolve address \'{0}\' failed. Invalid or unresolveable address').format(lookup) raise SaltSystemExit(code=42, msg=err) except socket.error: error = True if error: err = ('DNS lookup or connection check of \'{0}\' failed.').format(addr) if safe: if salt.log.is_console_configured(): # If logging is not configured it also means that either # the master or minion instance calling this hasn't even # started running log.error(err) raise SaltClientError() raise SaltSystemExit(code=42, msg=err) return resolved def parse_host_port(host_port): """ Takes a string argument specifying host or host:port. Returns a (hostname, port) or (ip_address, port) tuple. If no port is given, the second (port) element of the returned tuple will be None. host:port argument, for example, is accepted in the forms of: - hostname - hostname:1234 - hostname.domain.tld - hostname.domain.tld:5678 - [1234::5]:5678 - 1234::5 - 10.11.12.13:4567 - 10.11.12.13 """ host, port = None, None # default _s_ = host_port[:] if _s_[0] == "[": if "]" in host_port: host, _s_ = _s_.lstrip("[").rsplit("]", 1) host = ipaddress.IPv6Address(host).compressed if _s_[0] == ":": port = int(_s_.lstrip(":")) else: if len(_s_) > 1: raise ValueError('found ambiguous "{}" port in "{}"'.format(_s_, host_port)) else: if _s_.count(":") == 1: host, _hostport_separator_, port = _s_.partition(":") try: port = int(port) except ValueError as _e_: log.error('host_port "%s" port value "%s" is not an integer.', host_port, port) raise _e_ else: host = _s_ try: if not isinstance(host, ipaddress._BaseAddress): host_ip = ipaddress.ip_address(host).compressed host = host_ip except ValueError: log.debug('"%s" Not an IP address? Assuming it is a hostname.', host) if host != sanitize_host(host): log.error('bad hostname: "%s"', host) raise ValueError('bad hostname: "{}"'.format(host)) return host, port def is_fqdn(hostname): """ Verify if hostname conforms to be a FQDN. :param hostname: text string with the name of the host :return: bool, True if hostname is correct FQDN, False otherwise """ compliant = re.compile(r"(?!-)[A-Z\d\-\_]{1,63}(?<!-)$", re.IGNORECASE) return "." in hostname and len(hostname) < 0xff and all(compliant.match(x) for x in hostname.rstrip(".").split("."))
saltstack/salt
salt/utils/network.py
hw_addr
python
def hw_addr(iface): ''' Return the hardware address (a.k.a. MAC address) for a given interface .. versionchanged:: 2016.11.4 Added support for AIX ''' if salt.utils.platform.is_aix(): return _hw_addr_aix iface_info, error = _get_iface_info(iface) if error is False: return iface_info.get(iface, {}).get('hwaddr', '') else: return error
Return the hardware address (a.k.a. MAC address) for a given interface .. versionchanged:: 2016.11.4 Added support for AIX
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/network.py#L1140-L1156
[ "def _get_iface_info(iface):\n '''\n If `iface` is available, return interface info and no error, otherwise\n return no info and log and return an error\n '''\n iface_info = interfaces()\n\n if iface in iface_info.keys():\n return iface_info, False\n else:\n error_msg = ('Interface \"{0}\" not in available interfaces: \"{1}\"'\n ''.format(iface, '\", \"'.join(iface_info.keys())))\n log.error(error_msg)\n return None, error_msg\n" ]
# -*- coding: utf-8 -*- ''' Define some generic socket functions for network modules ''' # Import python libs from __future__ import absolute_import, unicode_literals, print_function import itertools import os import re import types import socket import logging import platform import random import subprocess from string import ascii_letters, digits # Import 3rd-party libs from salt.ext import six from salt.ext.six.moves import range # pylint: disable=import-error,redefined-builtin # Attempt to import wmi try: import wmi import salt.utils.winapi except ImportError: pass # Import salt libs import salt.utils.args import salt.utils.files import salt.utils.path import salt.utils.platform import salt.utils.stringutils import salt.utils.zeromq from salt._compat import ipaddress from salt.exceptions import SaltClientError, SaltSystemExit from salt.utils.decorators.jinja import jinja_filter from salt.utils.versions import LooseVersion # inet_pton does not exist in Windows, this is a workaround if salt.utils.platform.is_windows(): from salt.ext import win_inet_pton # pylint: disable=unused-import log = logging.getLogger(__name__) try: import ctypes import ctypes.util libc = ctypes.cdll.LoadLibrary(ctypes.util.find_library("c")) res_init = libc.__res_init except (ImportError, OSError, AttributeError, TypeError): pass # pylint: disable=C0103 def sanitize_host(host): ''' Sanitize host string. https://tools.ietf.org/html/rfc1123#section-2.1 ''' RFC952_characters = ascii_letters + digits + ".-" return "".join([c for c in host[0:255] if c in RFC952_characters]) def isportopen(host, port): ''' Return status of a port ''' if not 1 <= int(port) <= 65535: return False sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) out = sock.connect_ex((sanitize_host(host), int(port))) return out def host_to_ips(host): ''' Returns a list of IP addresses of a given hostname or None if not found. ''' ips = [] try: for family, socktype, proto, canonname, sockaddr in socket.getaddrinfo( host, 0, socket.AF_UNSPEC, socket.SOCK_STREAM): if family == socket.AF_INET: ip, port = sockaddr elif family == socket.AF_INET6: ip, port, flow_info, scope_id = sockaddr ips.append(ip) if not ips: ips = None except Exception: ips = None return ips def _generate_minion_id(): ''' Get list of possible host names and convention names. :return: ''' # There are three types of hostnames: # 1. Network names. How host is accessed from the network. # 2. Host aliases. They might be not available in all the network or only locally (/etc/hosts) # 3. Convention names, an internal nodename. class DistinctList(list): ''' List, which allows one to append only distinct objects. Needs to work on Python 2.6, because of collections.OrderedDict only since 2.7 version. Override 'filter()' for custom filtering. ''' localhost_matchers = [r'localhost.*', r'ip6-.*', r'127[.]\d', r'0\.0\.0\.0', r'::1.*', r'ipv6-.*', r'fe00::.*', r'fe02::.*', r'1.0.0.*.ip6.arpa'] def append(self, p_object): if p_object and p_object not in self and not self.filter(p_object): super(DistinctList, self).append(p_object) return self def extend(self, iterable): for obj in iterable: self.append(obj) return self def filter(self, element): 'Returns True if element needs to be filtered' for rgx in self.localhost_matchers: if re.match(rgx, element): return True def first(self): return self and self[0] or None hostname = socket.gethostname() hosts = DistinctList().append( salt.utils.stringutils.to_unicode(socket.getfqdn(salt.utils.stringutils.to_bytes(hostname))) ).append(platform.node()).append(hostname) if not hosts: try: for a_nfo in socket.getaddrinfo(hosts.first() or 'localhost', None, socket.AF_INET, socket.SOCK_RAW, socket.IPPROTO_IP, socket.AI_CANONNAME): if len(a_nfo) > 3: hosts.append(a_nfo[3]) except socket.gaierror: log.warning('Cannot resolve address %s info via socket: %s', hosts.first() or 'localhost (N/A)', socket.gaierror) # Universal method for everywhere (Linux, Slowlaris, Windows etc) for f_name in ('/etc/hostname', '/etc/nodename', '/etc/hosts', r'{win}\system32\drivers\etc\hosts'.format(win=os.getenv('WINDIR'))): try: with salt.utils.files.fopen(f_name) as f_hdl: for line in f_hdl: line = salt.utils.stringutils.to_unicode(line) hst = line.strip().split('#')[0].strip().split() if hst: if hst[0][:4] in ('127.', '::1') or len(hst) == 1: hosts.extend(hst) except IOError: pass # include public and private ipaddresses return hosts.extend([addr for addr in ip_addrs() if not ipaddress.ip_address(addr).is_loopback]) def generate_minion_id(): ''' Return only first element of the hostname from all possible list. :return: ''' try: ret = salt.utils.stringutils.to_unicode(_generate_minion_id().first()) except TypeError: ret = None return ret or 'localhost' def get_socket(addr, type=socket.SOCK_STREAM, proto=0): ''' Return a socket object for the addr IP-version agnostic ''' version = ipaddress.ip_address(addr).version if version == 4: family = socket.AF_INET elif version == 6: family = socket.AF_INET6 return socket.socket(family, type, proto) def get_fqhostname(): ''' Returns the fully qualified hostname ''' # try getaddrinfo() fqdn = None try: addrinfo = socket.getaddrinfo( socket.gethostname(), 0, socket.AF_UNSPEC, socket.SOCK_STREAM, socket.SOL_TCP, socket.AI_CANONNAME ) for info in addrinfo: # info struct [family, socktype, proto, canonname, sockaddr] # On Windows `canonname` can be an empty string # This can cause the function to return `None` if len(info) > 3 and info[3]: fqdn = info[3] break except socket.gaierror: pass # NOTE: this used to log.error() but it was later disabled except socket.error as err: log.debug('socket.getaddrinfo() failure while finding fqdn: %s', err) if fqdn is None: fqdn = socket.getfqdn() return fqdn def ip_to_host(ip): ''' Returns the hostname of a given IP ''' try: hostname, aliaslist, ipaddrlist = socket.gethostbyaddr(ip) except Exception as exc: log.debug('salt.utils.network.ip_to_host(%r) failed: %s', ip, exc) hostname = None return hostname # pylint: enable=C0103 def is_reachable_host(entity_name): ''' Returns a bool telling if the entity name is a reachable host (IPv4/IPv6/FQDN/etc). :param hostname: :return: ''' try: assert type(socket.getaddrinfo(entity_name, 0, 0, 0, 0)) == list ret = True except socket.gaierror: ret = False return ret def is_ip(ip): ''' Returns a bool telling if the passed IP is a valid IPv4 or IPv6 address. ''' return is_ipv4(ip) or is_ipv6(ip) def is_ipv4(ip): ''' Returns a bool telling if the value passed to it was a valid IPv4 address ''' try: return ipaddress.ip_address(ip).version == 4 except ValueError: return False def is_ipv6(ip): ''' Returns a bool telling if the value passed to it was a valid IPv6 address ''' try: return ipaddress.ip_address(ip).version == 6 except ValueError: return False def is_subnet(cidr): ''' Returns a bool telling if the passed string is an IPv4 or IPv6 subnet ''' return is_ipv4_subnet(cidr) or is_ipv6_subnet(cidr) def is_ipv4_subnet(cidr): ''' Returns a bool telling if the passed string is an IPv4 subnet ''' try: return '/' in cidr and bool(ipaddress.IPv4Network(cidr)) except Exception: return False def is_ipv6_subnet(cidr): ''' Returns a bool telling if the passed string is an IPv6 subnet ''' try: return '/' in cidr and bool(ipaddress.IPv6Network(cidr)) except Exception: return False @jinja_filter('is_ip') def is_ip_filter(ip, options=None): ''' Returns a bool telling if the passed IP is a valid IPv4 or IPv6 address. ''' return is_ipv4_filter(ip, options=options) or is_ipv6_filter(ip, options=options) def _ip_options_global(ip_obj, version): return not ip_obj.is_private def _ip_options_multicast(ip_obj, version): return ip_obj.is_multicast def _ip_options_loopback(ip_obj, version): return ip_obj.is_loopback def _ip_options_link_local(ip_obj, version): return ip_obj.is_link_local def _ip_options_private(ip_obj, version): return ip_obj.is_private def _ip_options_reserved(ip_obj, version): return ip_obj.is_reserved def _ip_options_site_local(ip_obj, version): if version == 6: return ip_obj.is_site_local return False def _ip_options_unspecified(ip_obj, version): return ip_obj.is_unspecified def _ip_options(ip_obj, version, options=None): # will process and IP options options_fun_map = { 'global': _ip_options_global, 'link-local': _ip_options_link_local, 'linklocal': _ip_options_link_local, 'll': _ip_options_link_local, 'link_local': _ip_options_link_local, 'loopback': _ip_options_loopback, 'lo': _ip_options_loopback, 'multicast': _ip_options_multicast, 'private': _ip_options_private, 'public': _ip_options_global, 'reserved': _ip_options_reserved, 'site-local': _ip_options_site_local, 'sl': _ip_options_site_local, 'site_local': _ip_options_site_local, 'unspecified': _ip_options_unspecified } if not options: return six.text_type(ip_obj) # IP version already checked options_list = [option.strip() for option in options.split(',')] for option, fun in options_fun_map.items(): if option in options_list: fun_res = fun(ip_obj, version) if not fun_res: return None # stop at first failed test # else continue return six.text_type(ip_obj) def _is_ipv(ip, version, options=None): if not version: version = 4 if version not in (4, 6): return None try: ip_obj = ipaddress.ip_address(ip) except ValueError: # maybe it is an IP network try: ip_obj = ipaddress.ip_interface(ip) except ValueError: # nope, still not :( return None if not ip_obj.version == version: return None # has the right version, let's move on return _ip_options(ip_obj, version, options=options) @jinja_filter('is_ipv4') def is_ipv4_filter(ip, options=None): ''' Returns a bool telling if the value passed to it was a valid IPv4 address. ip The IP address. net: False Consider IP addresses followed by netmask. options CSV of options regarding the nature of the IP address. E.g.: loopback, multicast, private etc. ''' _is_ipv4 = _is_ipv(ip, 4, options=options) return isinstance(_is_ipv4, six.string_types) @jinja_filter('is_ipv6') def is_ipv6_filter(ip, options=None): ''' Returns a bool telling if the value passed to it was a valid IPv6 address. ip The IP address. net: False Consider IP addresses followed by netmask. options CSV of options regarding the nature of the IP address. E.g.: loopback, multicast, private etc. ''' _is_ipv6 = _is_ipv(ip, 6, options=options) return isinstance(_is_ipv6, six.string_types) def _ipv_filter(value, version, options=None): if version not in (4, 6): return if isinstance(value, (six.string_types, six.text_type, six.binary_type)): return _is_ipv(value, version, options=options) # calls is_ipv4 or is_ipv6 for `value` elif isinstance(value, (list, tuple, types.GeneratorType)): # calls is_ipv4 or is_ipv6 for each element in the list # os it filters and returns only those elements having the desired IP version return [ _is_ipv(addr, version, options=options) for addr in value if _is_ipv(addr, version, options=options) is not None ] return None @jinja_filter('ipv4') def ipv4(value, options=None): ''' Filters a list and returns IPv4 values only. ''' return _ipv_filter(value, 4, options=options) @jinja_filter('ipv6') def ipv6(value, options=None): ''' Filters a list and returns IPv6 values only. ''' return _ipv_filter(value, 6, options=options) @jinja_filter('ipaddr') def ipaddr(value, options=None): ''' Filters and returns only valid IP objects. ''' ipv4_obj = ipv4(value, options=options) ipv6_obj = ipv6(value, options=options) if ipv4_obj is None or ipv6_obj is None: # an IP address can be either IPv4 either IPv6 # therefofe if the value passed as arg is not a list, at least one of the calls above will return None # if one of them is none, means that we should return only one of them return ipv4_obj or ipv6_obj # one of them else: return ipv4_obj + ipv6_obj # extend lists def _filter_ipaddr(value, options, version=None): ipaddr_filter_out = None if version: if version == 4: ipaddr_filter_out = ipv4(value, options) elif version == 6: ipaddr_filter_out = ipv6(value, options) else: ipaddr_filter_out = ipaddr(value, options) if not ipaddr_filter_out: return if not isinstance(ipaddr_filter_out, (list, tuple, types.GeneratorType)): ipaddr_filter_out = [ipaddr_filter_out] return ipaddr_filter_out @jinja_filter('ip_host') def ip_host(value, options=None, version=None): ''' Returns the interfaces IP address, e.g.: 192.168.0.1/28. ''' ipaddr_filter_out = _filter_ipaddr(value, options=options, version=version) if not ipaddr_filter_out: return if not isinstance(value, (list, tuple, types.GeneratorType)): return six.text_type(ipaddress.ip_interface(ipaddr_filter_out[0])) return [six.text_type(ipaddress.ip_interface(ip_a)) for ip_a in ipaddr_filter_out] def _network_hosts(ip_addr_entry): return [ six.text_type(host) for host in ipaddress.ip_network(ip_addr_entry, strict=False).hosts() ] @jinja_filter('network_hosts') def network_hosts(value, options=None, version=None): ''' Return the list of hosts within a network. .. note:: When running this command with a large IPv6 network, the command will take a long time to gather all of the hosts. ''' ipaddr_filter_out = _filter_ipaddr(value, options=options, version=version) if not ipaddr_filter_out: return if not isinstance(value, (list, tuple, types.GeneratorType)): return _network_hosts(ipaddr_filter_out[0]) return [ _network_hosts(ip_a) for ip_a in ipaddr_filter_out ] def _network_size(ip_addr_entry): return ipaddress.ip_network(ip_addr_entry, strict=False).num_addresses @jinja_filter('network_size') def network_size(value, options=None, version=None): ''' Get the size of a network. ''' ipaddr_filter_out = _filter_ipaddr(value, options=options, version=version) if not ipaddr_filter_out: return if not isinstance(value, (list, tuple, types.GeneratorType)): return _network_size(ipaddr_filter_out[0]) return [ _network_size(ip_a) for ip_a in ipaddr_filter_out ] def natural_ipv4_netmask(ip, fmt='prefixlen'): ''' Returns the "natural" mask of an IPv4 address ''' bits = _ipv4_to_bits(ip) if bits.startswith('11'): mask = '24' elif bits.startswith('1'): mask = '16' else: mask = '8' if fmt == 'netmask': return cidr_to_ipv4_netmask(mask) else: return '/' + mask def rpad_ipv4_network(ip): ''' Returns an IP network address padded with zeros. Ex: '192.168.3' -> '192.168.3.0' '10.209' -> '10.209.0.0' ''' return '.'.join(itertools.islice(itertools.chain(ip.split('.'), '0000'), 0, 4)) def cidr_to_ipv4_netmask(cidr_bits): ''' Returns an IPv4 netmask ''' try: cidr_bits = int(cidr_bits) if not 1 <= cidr_bits <= 32: return '' except ValueError: return '' netmask = '' for idx in range(4): if idx: netmask += '.' if cidr_bits >= 8: netmask += '255' cidr_bits -= 8 else: netmask += '{0:d}'.format(256 - (2 ** (8 - cidr_bits))) cidr_bits = 0 return netmask def _number_of_set_bits_to_ipv4_netmask(set_bits): # pylint: disable=C0103 ''' Returns an IPv4 netmask from the integer representation of that mask. Ex. 0xffffff00 -> '255.255.255.0' ''' return cidr_to_ipv4_netmask(_number_of_set_bits(set_bits)) # pylint: disable=C0103 def _number_of_set_bits(x): ''' Returns the number of bits that are set in a 32bit int ''' # Taken from http://stackoverflow.com/a/4912729. Many thanks! x -= (x >> 1) & 0x55555555 x = ((x >> 2) & 0x33333333) + (x & 0x33333333) x = ((x >> 4) + x) & 0x0f0f0f0f x += x >> 8 x += x >> 16 return x & 0x0000003f # pylint: enable=C0103 def _interfaces_ip(out): ''' Uses ip to return a dictionary of interfaces with various information about each (up/down state, ip address, netmask, and hwaddr) ''' ret = dict() def parse_network(value, cols): ''' Return a tuple of ip, netmask, broadcast based on the current set of cols ''' brd = None scope = None if '/' in value: # we have a CIDR in this address ip, cidr = value.split('/') # pylint: disable=C0103 else: ip = value # pylint: disable=C0103 cidr = 32 if type_ == 'inet': mask = cidr_to_ipv4_netmask(int(cidr)) if 'brd' in cols: brd = cols[cols.index('brd') + 1] elif type_ == 'inet6': mask = cidr if 'scope' in cols: scope = cols[cols.index('scope') + 1] return (ip, mask, brd, scope) groups = re.compile('\r?\n\\d').split(out) for group in groups: iface = None data = dict() for line in group.splitlines(): if ' ' not in line: continue match = re.match(r'^\d*:\s+([\w.\-]+)(?:@)?([\w.\-]+)?:\s+<(.+)>', line) if match: iface, parent, attrs = match.groups() if 'UP' in attrs.split(','): data['up'] = True else: data['up'] = False if parent: data['parent'] = parent continue cols = line.split() if len(cols) >= 2: type_, value = tuple(cols[0:2]) iflabel = cols[-1:][0] if type_ in ('inet', 'inet6'): if 'secondary' not in cols: ipaddr, netmask, broadcast, scope = parse_network(value, cols) if type_ == 'inet': if 'inet' not in data: data['inet'] = list() addr_obj = dict() addr_obj['address'] = ipaddr addr_obj['netmask'] = netmask addr_obj['broadcast'] = broadcast addr_obj['label'] = iflabel data['inet'].append(addr_obj) elif type_ == 'inet6': if 'inet6' not in data: data['inet6'] = list() addr_obj = dict() addr_obj['address'] = ipaddr addr_obj['prefixlen'] = netmask addr_obj['scope'] = scope data['inet6'].append(addr_obj) else: if 'secondary' not in data: data['secondary'] = list() ip_, mask, brd, scp = parse_network(value, cols) data['secondary'].append({ 'type': type_, 'address': ip_, 'netmask': mask, 'broadcast': brd, 'label': iflabel, }) del ip_, mask, brd, scp elif type_.startswith('link'): data['hwaddr'] = value if iface: ret[iface] = data del iface, data return ret def _interfaces_ifconfig(out): ''' Uses ifconfig to return a dictionary of interfaces with various information about each (up/down state, ip address, netmask, and hwaddr) ''' ret = dict() piface = re.compile(r'^([^\s:]+)') pmac = re.compile('.*?(?:HWaddr|ether|address:|lladdr) ([0-9a-fA-F:]+)') if salt.utils.platform.is_sunos(): pip = re.compile(r'.*?(?:inet\s+)([0-9]+\.[0-9]+\.[0-9]+\.[0-9]+)(.*)') pip6 = re.compile('.*?(?:inet6 )([0-9a-fA-F:]+)') pmask6 = re.compile(r'.*?(?:inet6 [0-9a-fA-F:]+/(\d+)).*') else: pip = re.compile(r'.*?(?:inet addr:|inet [^\d]*)(.*?)\s') pip6 = re.compile('.*?(?:inet6 addr: (.*?)/|inet6 )([0-9a-fA-F:]+)') pmask6 = re.compile(r'.*?(?:inet6 addr: [0-9a-fA-F:]+/(\d+)|prefixlen (\d+))(?: Scope:([a-zA-Z]+)| scopeid (0x[0-9a-fA-F]))?') pmask = re.compile(r'.*?(?:Mask:|netmask )(?:((?:0x)?[0-9a-fA-F]{8})|([\d\.]+))') pupdown = re.compile('UP') pbcast = re.compile(r'.*?(?:Bcast:|broadcast )([\d\.]+)') groups = re.compile('\r?\n(?=\\S)').split(out) for group in groups: data = dict() iface = '' updown = False for line in group.splitlines(): miface = piface.match(line) mmac = pmac.match(line) mip = pip.match(line) mip6 = pip6.match(line) mupdown = pupdown.search(line) if miface: iface = miface.group(1) if mmac: data['hwaddr'] = mmac.group(1) if salt.utils.platform.is_sunos(): expand_mac = [] for chunk in data['hwaddr'].split(':'): expand_mac.append('0{0}'.format(chunk) if len(chunk) < 2 else '{0}'.format(chunk)) data['hwaddr'] = ':'.join(expand_mac) if mip: if 'inet' not in data: data['inet'] = list() addr_obj = dict() addr_obj['address'] = mip.group(1) mmask = pmask.match(line) if mmask: if mmask.group(1): mmask = _number_of_set_bits_to_ipv4_netmask( int(mmask.group(1), 16)) else: mmask = mmask.group(2) addr_obj['netmask'] = mmask mbcast = pbcast.match(line) if mbcast: addr_obj['broadcast'] = mbcast.group(1) data['inet'].append(addr_obj) if mupdown: updown = True if mip6: if 'inet6' not in data: data['inet6'] = list() addr_obj = dict() addr_obj['address'] = mip6.group(1) or mip6.group(2) mmask6 = pmask6.match(line) if mmask6: addr_obj['prefixlen'] = mmask6.group(1) or mmask6.group(2) if not salt.utils.platform.is_sunos(): ipv6scope = mmask6.group(3) or mmask6.group(4) addr_obj['scope'] = ipv6scope.lower() if ipv6scope is not None else ipv6scope # SunOS sometimes has ::/0 as inet6 addr when using addrconf if not salt.utils.platform.is_sunos() \ or addr_obj['address'] != '::' \ and addr_obj['prefixlen'] != 0: data['inet6'].append(addr_obj) data['up'] = updown if iface in ret: # SunOS optimization, where interfaces occur twice in 'ifconfig -a' # output with the same name: for ipv4 and then for ipv6 addr family. # Every instance has it's own 'UP' status and we assume that ipv4 # status determines global interface status. # # merge items with higher priority for older values # after that merge the inet and inet6 sub items for both ret[iface] = dict(list(data.items()) + list(ret[iface].items())) if 'inet' in data: ret[iface]['inet'].extend(x for x in data['inet'] if x not in ret[iface]['inet']) if 'inet6' in data: ret[iface]['inet6'].extend(x for x in data['inet6'] if x not in ret[iface]['inet6']) else: ret[iface] = data del data return ret def linux_interfaces(): ''' Obtain interface information for *NIX/BSD variants ''' ifaces = dict() ip_path = salt.utils.path.which('ip') ifconfig_path = None if ip_path else salt.utils.path.which('ifconfig') if ip_path: cmd1 = subprocess.Popen( '{0} link show'.format(ip_path), shell=True, close_fds=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT).communicate()[0] cmd2 = subprocess.Popen( '{0} addr show'.format(ip_path), shell=True, close_fds=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT).communicate()[0] ifaces = _interfaces_ip("{0}\n{1}".format( salt.utils.stringutils.to_str(cmd1), salt.utils.stringutils.to_str(cmd2))) elif ifconfig_path: cmd = subprocess.Popen( '{0} -a'.format(ifconfig_path), shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT).communicate()[0] ifaces = _interfaces_ifconfig(salt.utils.stringutils.to_str(cmd)) return ifaces def _netbsd_interfaces_ifconfig(out): ''' Uses ifconfig to return a dictionary of interfaces with various information about each (up/down state, ip address, netmask, and hwaddr) ''' ret = dict() piface = re.compile(r'^([^\s:]+)') pmac = re.compile('.*?address: ([0-9a-f:]+)') pip = re.compile(r'.*?inet [^\d]*(.*?)/([\d]*)\s') pip6 = re.compile(r'.*?inet6 ([0-9a-f:]+)%([a-zA-Z0-9]*)/([\d]*)\s') pupdown = re.compile('UP') pbcast = re.compile(r'.*?broadcast ([\d\.]+)') groups = re.compile('\r?\n(?=\\S)').split(out) for group in groups: data = dict() iface = '' updown = False for line in group.splitlines(): miface = piface.match(line) mmac = pmac.match(line) mip = pip.match(line) mip6 = pip6.match(line) mupdown = pupdown.search(line) if miface: iface = miface.group(1) if mmac: data['hwaddr'] = mmac.group(1) if mip: if 'inet' not in data: data['inet'] = list() addr_obj = dict() addr_obj['address'] = mip.group(1) mmask = mip.group(2) if mip.group(2): addr_obj['netmask'] = cidr_to_ipv4_netmask(mip.group(2)) mbcast = pbcast.match(line) if mbcast: addr_obj['broadcast'] = mbcast.group(1) data['inet'].append(addr_obj) if mupdown: updown = True if mip6: if 'inet6' not in data: data['inet6'] = list() addr_obj = dict() addr_obj['address'] = mip6.group(1) mmask6 = mip6.group(3) addr_obj['scope'] = mip6.group(2) addr_obj['prefixlen'] = mip6.group(3) data['inet6'].append(addr_obj) data['up'] = updown ret[iface] = data del data return ret def netbsd_interfaces(): ''' Obtain interface information for NetBSD >= 8 where the ifconfig output diverged from other BSD variants (Netmask is now part of the address) ''' # NetBSD versions prior to 8.0 can still use linux_interfaces() if LooseVersion(os.uname()[2]) < LooseVersion('8.0'): return linux_interfaces() ifconfig_path = salt.utils.path.which('ifconfig') cmd = subprocess.Popen( '{0} -a'.format(ifconfig_path), shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT).communicate()[0] return _netbsd_interfaces_ifconfig(salt.utils.stringutils.to_str(cmd)) def _interfaces_ipconfig(out): ''' Returns a dictionary of interfaces with various information about each (up/down state, ip address, netmask, and hwaddr) NOTE: This is not used by any function and may be able to be removed in the future. ''' ifaces = dict() iface = None adapter_iface_regex = re.compile(r'adapter (\S.+):$') for line in out.splitlines(): if not line: continue # TODO what does Windows call Infiniband and 10/40gige adapters if line.startswith('Ethernet'): iface = ifaces[adapter_iface_regex.search(line).group(1)] iface['up'] = True addr = None continue if iface: key, val = line.split(',', 1) key = key.strip(' .') val = val.strip() if addr and key == 'Subnet Mask': addr['netmask'] = val elif key in ('IP Address', 'IPv4 Address'): if 'inet' not in iface: iface['inet'] = list() addr = {'address': val.rstrip('(Preferred)'), 'netmask': None, 'broadcast': None} # TODO find the broadcast iface['inet'].append(addr) elif 'IPv6 Address' in key: if 'inet6' not in iface: iface['inet'] = list() # XXX What is the prefixlen!? addr = {'address': val.rstrip('(Preferred)'), 'prefixlen': None} iface['inet6'].append(addr) elif key == 'Physical Address': iface['hwaddr'] = val elif key == 'Media State': # XXX seen used for tunnel adaptors # might be useful iface['up'] = (val != 'Media disconnected') def win_interfaces(): ''' Obtain interface information for Windows systems ''' with salt.utils.winapi.Com(): c = wmi.WMI() ifaces = {} for iface in c.Win32_NetworkAdapterConfiguration(IPEnabled=1): ifaces[iface.Description] = dict() if iface.MACAddress: ifaces[iface.Description]['hwaddr'] = iface.MACAddress if iface.IPEnabled: ifaces[iface.Description]['up'] = True for ip in iface.IPAddress: if '.' in ip: if 'inet' not in ifaces[iface.Description]: ifaces[iface.Description]['inet'] = [] item = {'address': ip, 'label': iface.Description} if iface.DefaultIPGateway: broadcast = next((i for i in iface.DefaultIPGateway if '.' in i), '') if broadcast: item['broadcast'] = broadcast if iface.IPSubnet: netmask = next((i for i in iface.IPSubnet if '.' in i), '') if netmask: item['netmask'] = netmask ifaces[iface.Description]['inet'].append(item) if ':' in ip: if 'inet6' not in ifaces[iface.Description]: ifaces[iface.Description]['inet6'] = [] item = {'address': ip} if iface.DefaultIPGateway: broadcast = next((i for i in iface.DefaultIPGateway if ':' in i), '') if broadcast: item['broadcast'] = broadcast if iface.IPSubnet: netmask = next((i for i in iface.IPSubnet if ':' in i), '') if netmask: item['netmask'] = netmask ifaces[iface.Description]['inet6'].append(item) else: ifaces[iface.Description]['up'] = False return ifaces def interfaces(): ''' Return a dictionary of information about all the interfaces on the minion ''' if salt.utils.platform.is_windows(): return win_interfaces() elif salt.utils.platform.is_netbsd(): return netbsd_interfaces() else: return linux_interfaces() def get_net_start(ipaddr, netmask): ''' Return the address of the network ''' net = ipaddress.ip_network('{0}/{1}'.format(ipaddr, netmask), strict=False) return six.text_type(net.network_address) def get_net_size(mask): ''' Turns an IPv4 netmask into it's corresponding prefix length (255.255.255.0 -> 24 as in 192.168.1.10/24). ''' binary_str = '' for octet in mask.split('.'): binary_str += bin(int(octet))[2:].zfill(8) return len(binary_str.rstrip('0')) def calc_net(ipaddr, netmask=None): ''' Takes IP (CIDR notation supported) and optionally netmask and returns the network in CIDR-notation. (The IP can be any IP inside the subnet) ''' if netmask is not None: ipaddr = '{0}/{1}'.format(ipaddr, netmask) return six.text_type(ipaddress.ip_network(ipaddr, strict=False)) def _ipv4_to_bits(ipaddr): ''' Accepts an IPv4 dotted quad and returns a string representing its binary counterpart ''' return ''.join([bin(int(x))[2:].rjust(8, '0') for x in ipaddr.split('.')]) def _get_iface_info(iface): ''' If `iface` is available, return interface info and no error, otherwise return no info and log and return an error ''' iface_info = interfaces() if iface in iface_info.keys(): return iface_info, False else: error_msg = ('Interface "{0}" not in available interfaces: "{1}"' ''.format(iface, '", "'.join(iface_info.keys()))) log.error(error_msg) return None, error_msg def _hw_addr_aix(iface): ''' Return the hardware address (a.k.a. MAC address) for a given interface on AIX MAC address not available in through interfaces ''' cmd = subprocess.Popen( 'entstat -d {0} | grep \'Hardware Address\''.format(iface), shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT).communicate()[0] if cmd: comps = cmd.split(' ') if len(comps) == 3: mac_addr = comps[2].strip('\'').strip() return mac_addr error_msg = ('Interface "{0}" either not available or does not contain a hardware address'.format(iface)) log.error(error_msg) return error_msg def interface(iface): ''' Return the details of `iface` or an error if it does not exist ''' iface_info, error = _get_iface_info(iface) if error is False: return iface_info.get(iface, {}).get('inet', '') else: return error def interface_ip(iface): ''' Return `iface` IPv4 addr or an error if `iface` does not exist ''' iface_info, error = _get_iface_info(iface) if error is False: inet = iface_info.get(iface, {}).get('inet', None) return inet[0].get('address', '') if inet else '' else: return error def _subnets(proto='inet', interfaces_=None): ''' Returns a list of subnets to which the host belongs ''' if interfaces_ is None: ifaces = interfaces() elif isinstance(interfaces_, list): ifaces = {} for key, value in six.iteritems(interfaces()): if key in interfaces_: ifaces[key] = value else: ifaces = {interfaces_: interfaces().get(interfaces_, {})} ret = set() if proto == 'inet': subnet = 'netmask' dflt_cidr = 32 elif proto == 'inet6': subnet = 'prefixlen' dflt_cidr = 128 else: log.error('Invalid proto %s calling subnets()', proto) return for ip_info in six.itervalues(ifaces): addrs = ip_info.get(proto, []) addrs.extend([addr for addr in ip_info.get('secondary', []) if addr.get('type') == proto]) for intf in addrs: if subnet in intf: intf = ipaddress.ip_interface('{0}/{1}'.format(intf['address'], intf[subnet])) else: intf = ipaddress.ip_interface('{0}/{1}'.format(intf['address'], dflt_cidr)) if not intf.is_loopback: ret.add(intf.network) return [six.text_type(net) for net in sorted(ret)] def subnets(interfaces=None): ''' Returns a list of IPv4 subnets to which the host belongs ''' return _subnets('inet', interfaces_=interfaces) def subnets6(): ''' Returns a list of IPv6 subnets to which the host belongs ''' return _subnets('inet6') def in_subnet(cidr, addr=None): ''' Returns True if host or (any of) addrs is within specified subnet, otherwise False ''' try: cidr = ipaddress.ip_network(cidr) except ValueError: log.error('Invalid CIDR \'%s\'', cidr) return False if addr is None: addr = ip_addrs() addr.extend(ip_addrs6()) elif not isinstance(addr, (list, tuple)): addr = (addr,) return any(ipaddress.ip_address(item) in cidr for item in addr) def _ip_addrs(interface=None, include_loopback=False, interface_data=None, proto='inet'): ''' Return the full list of IP adresses matching the criteria proto = inet|inet6 ''' ret = set() ifaces = interface_data \ if isinstance(interface_data, dict) \ else interfaces() if interface is None: target_ifaces = ifaces else: target_ifaces = dict([(k, v) for k, v in six.iteritems(ifaces) if k == interface]) if not target_ifaces: log.error('Interface %s not found.', interface) for ip_info in six.itervalues(target_ifaces): addrs = ip_info.get(proto, []) addrs.extend([addr for addr in ip_info.get('secondary', []) if addr.get('type') == proto]) for addr in addrs: addr = ipaddress.ip_address(addr.get('address')) if not addr.is_loopback or include_loopback: ret.add(addr) return [six.text_type(addr) for addr in sorted(ret)] def ip_addrs(interface=None, include_loopback=False, interface_data=None): ''' Returns a list of IPv4 addresses assigned to the host. 127.0.0.1 is ignored, unless 'include_loopback=True' is indicated. If 'interface' is provided, then only IP addresses from that interface will be returned. ''' return _ip_addrs(interface, include_loopback, interface_data, 'inet') def ip_addrs6(interface=None, include_loopback=False, interface_data=None): ''' Returns a list of IPv6 addresses assigned to the host. ::1 is ignored, unless 'include_loopback=True' is indicated. If 'interface' is provided, then only IP addresses from that interface will be returned. ''' return _ip_addrs(interface, include_loopback, interface_data, 'inet6') def hex2ip(hex_ip, invert=False): ''' Convert a hex string to an ip, if a failure occurs the original hex is returned. If 'invert=True' assume that ip from /proc/net/<proto> ''' if len(hex_ip) == 32: # ipv6 ip = [] for i in range(0, 32, 8): ip_part = hex_ip[i:i + 8] ip_part = [ip_part[x:x + 2] for x in range(0, 8, 2)] if invert: ip.append("{0[3]}{0[2]}:{0[1]}{0[0]}".format(ip_part)) else: ip.append("{0[0]}{0[1]}:{0[2]}{0[3]}".format(ip_part)) try: address = ipaddress.IPv6Address(":".join(ip)) if address.ipv4_mapped: return str(address.ipv4_mapped) else: return address.compressed except ipaddress.AddressValueError as ex: log.error('hex2ip - ipv6 address error: %s', ex) return hex_ip try: hip = int(hex_ip, 16) except ValueError: return hex_ip if invert: return '{3}.{2}.{1}.{0}'.format(hip >> 24 & 255, hip >> 16 & 255, hip >> 8 & 255, hip & 255) return '{0}.{1}.{2}.{3}'.format(hip >> 24 & 255, hip >> 16 & 255, hip >> 8 & 255, hip & 255) def mac2eui64(mac, prefix=None): ''' Convert a MAC address to a EUI64 identifier or, with prefix provided, a full IPv6 address ''' # http://tools.ietf.org/html/rfc4291#section-2.5.1 eui64 = re.sub(r'[.:-]', '', mac).lower() eui64 = eui64[0:6] + 'fffe' + eui64[6:] eui64 = hex(int(eui64[0:2], 16) | 2)[2:].zfill(2) + eui64[2:] if prefix is None: return ':'.join(re.findall(r'.{4}', eui64)) else: try: net = ipaddress.ip_network(prefix, strict=False) euil = int('0x{0}'.format(eui64), 16) return '{0}/{1}'.format(net[euil], net.prefixlen) except Exception: return def active_tcp(): ''' Return a dict describing all active tcp connections as quickly as possible ''' ret = {} for statf in ['/proc/net/tcp', '/proc/net/tcp6']: if os.path.isfile(statf): with salt.utils.files.fopen(statf, 'rb') as fp_: for line in fp_: line = salt.utils.stringutils.to_unicode(line) if line.strip().startswith('sl'): continue iret = _parse_tcp_line(line) sl = next(iter(iret)) if iret[sl]['state'] == 1: # 1 is ESTABLISHED del iret[sl]['state'] ret[len(ret)] = iret[sl] return ret def local_port_tcp(port): ''' Return a set of remote ip addrs attached to the specified local port ''' ret = _remotes_on(port, 'local_port') return ret def remote_port_tcp(port): ''' Return a set of ip addrs the current host is connected to on given port ''' ret = _remotes_on(port, 'remote_port') return ret def _remotes_on(port, which_end): ''' Return a set of ip addrs active tcp connections ''' port = int(port) ret = _netlink_tool_remote_on(port, which_end) if ret is not None: return ret ret = set() proc_available = False for statf in ['/proc/net/tcp', '/proc/net/tcp6']: if os.path.isfile(statf): proc_available = True with salt.utils.files.fopen(statf, 'r') as fp_: for line in fp_: line = salt.utils.stringutils.to_unicode(line) if line.strip().startswith('sl'): continue iret = _parse_tcp_line(line) sl = next(iter(iret)) if iret[sl][which_end] == port and iret[sl]['state'] == 1: # 1 is ESTABLISHED ret.add(iret[sl]['remote_addr']) if not proc_available: # Fallback to use OS specific tools if salt.utils.platform.is_sunos(): return _sunos_remotes_on(port, which_end) if salt.utils.platform.is_freebsd(): return _freebsd_remotes_on(port, which_end) if salt.utils.platform.is_netbsd(): return _netbsd_remotes_on(port, which_end) if salt.utils.platform.is_openbsd(): return _openbsd_remotes_on(port, which_end) if salt.utils.platform.is_windows(): return _windows_remotes_on(port, which_end) if salt.utils.platform.is_aix(): return _aix_remotes_on(port, which_end) return _linux_remotes_on(port, which_end) return ret def _parse_tcp_line(line): ''' Parse a single line from the contents of /proc/net/tcp or /proc/net/tcp6 ''' ret = {} comps = line.strip().split() sl = comps[0].rstrip(':') ret[sl] = {} l_addr, l_port = comps[1].split(':') r_addr, r_port = comps[2].split(':') ret[sl]['local_addr'] = hex2ip(l_addr, True) ret[sl]['local_port'] = int(l_port, 16) ret[sl]['remote_addr'] = hex2ip(r_addr, True) ret[sl]['remote_port'] = int(r_port, 16) ret[sl]['state'] = int(comps[3], 16) return ret def _netlink_tool_remote_on(port, which_end): ''' Returns set of ipv4 host addresses of remote established connections on local or remote tcp port. Parses output of shell 'ss' to get connections [root@salt-master ~]# ss -ant State Recv-Q Send-Q Local Address:Port Peer Address:Port LISTEN 0 511 *:80 *:* LISTEN 0 128 *:22 *:* ESTAB 0 0 127.0.0.1:56726 127.0.0.1:4505 ''' remotes = set() valid = False try: data = subprocess.check_output(['ss', '-ant']) # pylint: disable=minimum-python-version except subprocess.CalledProcessError: log.error('Failed ss') raise except OSError: # not command "No such file or directory" return None lines = salt.utils.stringutils.to_str(data).split('\n') for line in lines: if 'Address:Port' in line: # ss tools may not be valid valid = True continue elif 'ESTAB' not in line: continue chunks = line.split() local_host, local_port = chunks[3].split(':', 1) remote_host, remote_port = chunks[4].split(':', 1) if which_end == 'remote_port' and int(remote_port) != port: continue if which_end == 'local_port' and int(local_port) != port: continue remotes.add(remote_host) if valid is False: remotes = None return remotes def _sunos_remotes_on(port, which_end): ''' SunOS specific helper function. Returns set of ipv4 host addresses of remote established connections on local or remote tcp port. Parses output of shell 'netstat' to get connections [root@salt-master ~]# netstat -f inet -n TCP: IPv4 Local Address Remote Address Swind Send-Q Rwind Recv-Q State -------------------- -------------------- ----- ------ ----- ------ ----------- 10.0.0.101.4505 10.0.0.1.45329 1064800 0 1055864 0 ESTABLISHED 10.0.0.101.4505 10.0.0.100.50798 1064800 0 1055864 0 ESTABLISHED ''' remotes = set() try: data = subprocess.check_output(['netstat', '-f', 'inet', '-n']) # pylint: disable=minimum-python-version except subprocess.CalledProcessError: log.error('Failed netstat') raise lines = salt.utils.stringutils.to_str(data).split('\n') for line in lines: if 'ESTABLISHED' not in line: continue chunks = line.split() local_host, local_port = chunks[0].rsplit('.', 1) remote_host, remote_port = chunks[1].rsplit('.', 1) if which_end == 'remote_port' and int(remote_port) != port: continue if which_end == 'local_port' and int(local_port) != port: continue remotes.add(remote_host) return remotes def _freebsd_remotes_on(port, which_end): ''' Returns set of ipv4 host addresses of remote established connections on local tcp port port. Parses output of shell 'sockstat' (FreeBSD) to get connections $ sudo sockstat -4 USER COMMAND PID FD PROTO LOCAL ADDRESS FOREIGN ADDRESS root python2.7 1456 29 tcp4 *:4505 *:* root python2.7 1445 17 tcp4 *:4506 *:* root python2.7 1294 14 tcp4 127.0.0.1:11813 127.0.0.1:4505 root python2.7 1294 41 tcp4 127.0.0.1:61115 127.0.0.1:4506 $ sudo sockstat -4 -c -p 4506 USER COMMAND PID FD PROTO LOCAL ADDRESS FOREIGN ADDRESS root python2.7 1294 41 tcp4 127.0.0.1:61115 127.0.0.1:4506 ''' port = int(port) remotes = set() try: cmd = salt.utils.args.shlex_split('sockstat -4 -c -p {0}'.format(port)) data = subprocess.check_output(cmd) # pylint: disable=minimum-python-version except subprocess.CalledProcessError as ex: log.error('Failed "sockstat" with returncode = %s', ex.returncode) raise lines = salt.utils.stringutils.to_str(data).split('\n') for line in lines: chunks = line.split() if not chunks: continue # ['root', 'python2.7', '1456', '37', 'tcp4', # '127.0.0.1:4505-', '127.0.0.1:55703'] # print chunks if 'COMMAND' in chunks[1]: continue # ignore header if len(chunks) < 2: continue # sockstat -4 -c -p 4506 does this with high PIDs: # USER COMMAND PID FD PROTO LOCAL ADDRESS FOREIGN ADDRESS # salt-master python2.781106 35 tcp4 192.168.12.34:4506 192.168.12.45:60143 local = chunks[-2] remote = chunks[-1] lhost, lport = local.split(':') rhost, rport = remote.split(':') if which_end == 'local' and int(lport) != port: # ignore if local port not port continue if which_end == 'remote' and int(rport) != port: # ignore if remote port not port continue remotes.add(rhost) return remotes def _netbsd_remotes_on(port, which_end): ''' Returns set of ipv4 host addresses of remote established connections on local tcp port port. Parses output of shell 'sockstat' (NetBSD) to get connections $ sudo sockstat -4 -n USER COMMAND PID FD PROTO LOCAL ADDRESS FOREIGN ADDRESS root python2.7 1456 29 tcp *.4505 *.* root python2.7 1445 17 tcp *.4506 *.* root python2.7 1294 14 tcp 127.0.0.1.11813 127.0.0.1.4505 root python2.7 1294 41 tcp 127.0.0.1.61115 127.0.0.1.4506 $ sudo sockstat -4 -c -n -p 4506 USER COMMAND PID FD PROTO LOCAL ADDRESS FOREIGN ADDRESS root python2.7 1294 41 tcp 127.0.0.1.61115 127.0.0.1.4506 ''' port = int(port) remotes = set() try: cmd = salt.utils.args.shlex_split('sockstat -4 -c -n -p {0}'.format(port)) data = subprocess.check_output(cmd) # pylint: disable=minimum-python-version except subprocess.CalledProcessError as ex: log.error('Failed "sockstat" with returncode = %s', ex.returncode) raise lines = salt.utils.stringutils.to_str(data).split('\n') for line in lines: chunks = line.split() if not chunks: continue # ['root', 'python2.7', '1456', '37', 'tcp', # '127.0.0.1.4505-', '127.0.0.1.55703'] # print chunks if 'COMMAND' in chunks[1]: continue # ignore header if len(chunks) < 2: continue local = chunks[5].split('.') lport = local.pop() lhost = '.'.join(local) remote = chunks[6].split('.') rport = remote.pop() rhost = '.'.join(remote) if which_end == 'local' and int(lport) != port: # ignore if local port not port continue if which_end == 'remote' and int(rport) != port: # ignore if remote port not port continue remotes.add(rhost) return remotes def _openbsd_remotes_on(port, which_end): ''' OpenBSD specific helper function. Returns set of ipv4 host addresses of remote established connections on local or remote tcp port. Parses output of shell 'netstat' to get connections $ netstat -nf inet Active Internet connections Proto Recv-Q Send-Q Local Address Foreign Address (state) tcp 0 0 10.0.0.101.4505 10.0.0.1.45329 ESTABLISHED tcp 0 0 10.0.0.101.4505 10.0.0.100.50798 ESTABLISHED ''' remotes = set() try: data = subprocess.check_output(['netstat', '-nf', 'inet']) # pylint: disable=minimum-python-version except subprocess.CalledProcessError: log.error('Failed netstat') raise lines = data.split('\n') for line in lines: if 'ESTABLISHED' not in line: continue chunks = line.split() local_host, local_port = chunks[3].rsplit('.', 1) remote_host, remote_port = chunks[4].rsplit('.', 1) if which_end == 'remote_port' and int(remote_port) != port: continue if which_end == 'local_port' and int(local_port) != port: continue remotes.add(remote_host) return remotes def _windows_remotes_on(port, which_end): r''' Windows specific helper function. Returns set of ipv4 host addresses of remote established connections on local or remote tcp port. Parses output of shell 'netstat' to get connections C:\>netstat -n Active Connections Proto Local Address Foreign Address State TCP 10.2.33.17:3007 130.164.12.233:10123 ESTABLISHED TCP 10.2.33.17:3389 130.164.30.5:10378 ESTABLISHED ''' remotes = set() try: data = subprocess.check_output(['netstat', '-n']) # pylint: disable=minimum-python-version except subprocess.CalledProcessError: log.error('Failed netstat') raise lines = salt.utils.stringutils.to_str(data).split('\n') for line in lines: if 'ESTABLISHED' not in line: continue chunks = line.split() local_host, local_port = chunks[1].rsplit(':', 1) remote_host, remote_port = chunks[2].rsplit(':', 1) if which_end == 'remote_port' and int(remote_port) != port: continue if which_end == 'local_port' and int(local_port) != port: continue remotes.add(remote_host) return remotes def _linux_remotes_on(port, which_end): ''' Linux specific helper function. Returns set of ip host addresses of remote established connections on local tcp port port. Parses output of shell 'lsof' to get connections $ sudo lsof -iTCP:4505 -n COMMAND PID USER FD TYPE DEVICE SIZE/OFF NODE NAME Python 9971 root 35u IPv4 0x18a8464a29ca329d 0t0 TCP *:4505 (LISTEN) Python 9971 root 37u IPv4 0x18a8464a29b2b29d 0t0 TCP 127.0.0.1:4505->127.0.0.1:55703 (ESTABLISHED) Python 10152 root 22u IPv4 0x18a8464a29c8cab5 0t0 TCP 127.0.0.1:55703->127.0.0.1:4505 (ESTABLISHED) Python 10153 root 22u IPv4 0x18a8464a29c8cab5 0t0 TCP [fe80::249a]:4505->[fe80::150]:59367 (ESTABLISHED) ''' remotes = set() try: data = subprocess.check_output( ['lsof', '-iTCP:{0:d}'.format(port), '-n', '-P'] # pylint: disable=minimum-python-version ) except subprocess.CalledProcessError as ex: if ex.returncode == 1: # Lsof return 1 if any error was detected, including the failure # to locate Internet addresses, and it is not an error in this case. log.warning('"lsof" returncode = 1, likely no active TCP sessions.') return remotes log.error('Failed "lsof" with returncode = %s', ex.returncode) raise lines = salt.utils.stringutils.to_str(data).split('\n') for line in lines: chunks = line.split() if not chunks: continue # ['Python', '9971', 'root', '37u', 'IPv4', '0x18a8464a29b2b29d', '0t0', # 'TCP', '127.0.0.1:4505->127.0.0.1:55703', '(ESTABLISHED)'] # print chunks if 'COMMAND' in chunks[0]: continue # ignore header if 'ESTABLISHED' not in chunks[-1]: continue # ignore if not ESTABLISHED # '127.0.0.1:4505->127.0.0.1:55703' local, remote = chunks[8].split('->') _, lport = local.rsplit(':', 1) rhost, rport = remote.rsplit(':', 1) if which_end == 'remote_port' and int(rport) != port: continue if which_end == 'local_port' and int(lport) != port: continue remotes.add(rhost.strip("[]")) return remotes def _aix_remotes_on(port, which_end): ''' AIX specific helper function. Returns set of ipv4 host addresses of remote established connections on local or remote tcp port. Parses output of shell 'netstat' to get connections root@la68pp002_pub:/opt/salt/lib/python2.7/site-packages/salt/modules# netstat -f inet -n Active Internet connections Proto Recv-Q Send-Q Local Address Foreign Address (state) tcp4 0 0 172.29.149.95.50093 209.41.78.13.4505 ESTABLISHED tcp4 0 0 127.0.0.1.9514 *.* LISTEN tcp4 0 0 127.0.0.1.9515 *.* LISTEN tcp4 0 0 127.0.0.1.199 127.0.0.1.32779 ESTABLISHED tcp4 0 0 127.0.0.1.32779 127.0.0.1.199 ESTABLISHED tcp4 0 40 172.29.149.95.22 172.29.96.83.41022 ESTABLISHED tcp4 0 0 172.29.149.95.22 172.29.96.83.41032 ESTABLISHED tcp4 0 0 127.0.0.1.32771 127.0.0.1.32775 ESTABLISHED tcp 0 0 127.0.0.1.32775 127.0.0.1.32771 ESTABLISHED tcp4 0 0 127.0.0.1.32771 127.0.0.1.32776 ESTABLISHED tcp 0 0 127.0.0.1.32776 127.0.0.1.32771 ESTABLISHED tcp4 0 0 127.0.0.1.32771 127.0.0.1.32777 ESTABLISHED tcp 0 0 127.0.0.1.32777 127.0.0.1.32771 ESTABLISHED tcp4 0 0 127.0.0.1.32771 127.0.0.1.32778 ESTABLISHED tcp 0 0 127.0.0.1.32778 127.0.0.1.32771 ESTABLISHED ''' remotes = set() try: data = subprocess.check_output(['netstat', '-f', 'inet', '-n']) # pylint: disable=minimum-python-version except subprocess.CalledProcessError: log.error('Failed netstat') raise lines = salt.utils.stringutils.to_str(data).split('\n') for line in lines: if 'ESTABLISHED' not in line: continue chunks = line.split() local_host, local_port = chunks[3].rsplit('.', 1) remote_host, remote_port = chunks[4].rsplit('.', 1) if which_end == 'remote_port' and int(remote_port) != port: continue if which_end == 'local_port' and int(local_port) != port: continue remotes.add(remote_host) return remotes @jinja_filter('gen_mac') def gen_mac(prefix='AC:DE:48'): ''' Generates a MAC address with the defined OUI prefix. Common prefixes: - ``00:16:3E`` -- Xen - ``00:18:51`` -- OpenVZ - ``00:50:56`` -- VMware (manually generated) - ``52:54:00`` -- QEMU/KVM - ``AC:DE:48`` -- PRIVATE References: - http://standards.ieee.org/develop/regauth/oui/oui.txt - https://www.wireshark.org/tools/oui-lookup.html - https://en.wikipedia.org/wiki/MAC_address ''' return '{0}:{1:02X}:{2:02X}:{3:02X}'.format(prefix, random.randint(0, 0xff), random.randint(0, 0xff), random.randint(0, 0xff)) @jinja_filter('mac_str_to_bytes') def mac_str_to_bytes(mac_str): ''' Convert a MAC address string into bytes. Works with or without separators: b1 = mac_str_to_bytes('08:00:27:13:69:77') b2 = mac_str_to_bytes('080027136977') assert b1 == b2 assert isinstance(b1, bytes) ''' if len(mac_str) == 12: pass elif len(mac_str) == 17: sep = mac_str[2] mac_str = mac_str.replace(sep, '') else: raise ValueError('Invalid MAC address') chars = (int(mac_str[s:s+2], 16) for s in range(0, 12, 2)) return bytes(chars) if six.PY3 else b''.join(chr(x) for x in chars) def refresh_dns(): ''' issue #21397: force glibc to re-read resolv.conf ''' try: res_init() except NameError: # Exception raised loading the library, thus res_init is not defined pass @jinja_filter('connection_check') def connection_check(addr, port=80, safe=False, ipv6=None): ''' Provides a convenient alias for the dns_check filter. ''' return dns_check(addr, port, safe, ipv6) @jinja_filter('dns_check') def dns_check(addr, port=80, safe=False, ipv6=None, attempt_connect=True): ''' Return the ip resolved by dns, but do not exit on failure, only raise an exception. Obeys system preference for IPv4/6 address resolution - this can be overridden by the ipv6 flag. Tries to connect to the address before considering it useful. If no address can be reached, the first one resolved is used as a fallback. ''' error = False lookup = addr seen_ipv6 = False family = socket.AF_INET6 if ipv6 else socket.AF_INET if ipv6 is False else socket.AF_UNSPEC hostnames = [] try: refresh_dns() hostnames = socket.getaddrinfo(addr, port, family, socket.SOCK_STREAM) except TypeError: err = ('Attempt to resolve address \'{0}\' failed. Invalid or unresolveable address').format(lookup) raise SaltSystemExit(code=42, msg=err) except socket.error: error = True # If ipv6 is set to True, attempt another lookup using the IPv4 family, # just in case we're attempting to lookup an IPv4 IP # as an IPv6 hostname. if error and ipv6: try: refresh_dns() hostnames = socket.getaddrinfo(addr, port, socket.AF_INET, socket.SOCK_STREAM) except TypeError: err = ('Attempt to resolve address \'{0}\' failed. Invalid or unresolveable address').format(lookup) raise SaltSystemExit(code=42, msg=err) except socket.error: error = True try: if not hostnames: error = True else: resolved = False candidates = [] for h in hostnames: # Input is IP address, passed through unchanged, just return it if h[4][0] == addr: resolved = salt.utils.zeromq.ip_bracket(addr) break candidate_addr = salt.utils.zeromq.ip_bracket(h[4][0]) # sometimes /etc/hosts contains ::1 localhost if not ipv6 and candidate_addr == '[::1]': continue candidates.append(candidate_addr) if attempt_connect: try: s = socket.socket(h[0], socket.SOCK_STREAM) s.settimeout(2) s.connect((candidate_addr.strip('[]'), h[4][1])) s.close() resolved = candidate_addr break except socket.error: pass if not resolved: if candidates: resolved = candidates[0] else: error = True except TypeError: err = ('Attempt to resolve address \'{0}\' failed. Invalid or unresolveable address').format(lookup) raise SaltSystemExit(code=42, msg=err) except socket.error: error = True if error: err = ('DNS lookup or connection check of \'{0}\' failed.').format(addr) if safe: if salt.log.is_console_configured(): # If logging is not configured it also means that either # the master or minion instance calling this hasn't even # started running log.error(err) raise SaltClientError() raise SaltSystemExit(code=42, msg=err) return resolved def parse_host_port(host_port): """ Takes a string argument specifying host or host:port. Returns a (hostname, port) or (ip_address, port) tuple. If no port is given, the second (port) element of the returned tuple will be None. host:port argument, for example, is accepted in the forms of: - hostname - hostname:1234 - hostname.domain.tld - hostname.domain.tld:5678 - [1234::5]:5678 - 1234::5 - 10.11.12.13:4567 - 10.11.12.13 """ host, port = None, None # default _s_ = host_port[:] if _s_[0] == "[": if "]" in host_port: host, _s_ = _s_.lstrip("[").rsplit("]", 1) host = ipaddress.IPv6Address(host).compressed if _s_[0] == ":": port = int(_s_.lstrip(":")) else: if len(_s_) > 1: raise ValueError('found ambiguous "{}" port in "{}"'.format(_s_, host_port)) else: if _s_.count(":") == 1: host, _hostport_separator_, port = _s_.partition(":") try: port = int(port) except ValueError as _e_: log.error('host_port "%s" port value "%s" is not an integer.', host_port, port) raise _e_ else: host = _s_ try: if not isinstance(host, ipaddress._BaseAddress): host_ip = ipaddress.ip_address(host).compressed host = host_ip except ValueError: log.debug('"%s" Not an IP address? Assuming it is a hostname.', host) if host != sanitize_host(host): log.error('bad hostname: "%s"', host) raise ValueError('bad hostname: "{}"'.format(host)) return host, port def is_fqdn(hostname): """ Verify if hostname conforms to be a FQDN. :param hostname: text string with the name of the host :return: bool, True if hostname is correct FQDN, False otherwise """ compliant = re.compile(r"(?!-)[A-Z\d\-\_]{1,63}(?<!-)$", re.IGNORECASE) return "." in hostname and len(hostname) < 0xff and all(compliant.match(x) for x in hostname.rstrip(".").split("."))
saltstack/salt
salt/utils/network.py
interface
python
def interface(iface): ''' Return the details of `iface` or an error if it does not exist ''' iface_info, error = _get_iface_info(iface) if error is False: return iface_info.get(iface, {}).get('inet', '') else: return error
Return the details of `iface` or an error if it does not exist
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/network.py#L1159-L1168
[ "def _get_iface_info(iface):\n '''\n If `iface` is available, return interface info and no error, otherwise\n return no info and log and return an error\n '''\n iface_info = interfaces()\n\n if iface in iface_info.keys():\n return iface_info, False\n else:\n error_msg = ('Interface \"{0}\" not in available interfaces: \"{1}\"'\n ''.format(iface, '\", \"'.join(iface_info.keys())))\n log.error(error_msg)\n return None, error_msg\n" ]
# -*- coding: utf-8 -*- ''' Define some generic socket functions for network modules ''' # Import python libs from __future__ import absolute_import, unicode_literals, print_function import itertools import os import re import types import socket import logging import platform import random import subprocess from string import ascii_letters, digits # Import 3rd-party libs from salt.ext import six from salt.ext.six.moves import range # pylint: disable=import-error,redefined-builtin # Attempt to import wmi try: import wmi import salt.utils.winapi except ImportError: pass # Import salt libs import salt.utils.args import salt.utils.files import salt.utils.path import salt.utils.platform import salt.utils.stringutils import salt.utils.zeromq from salt._compat import ipaddress from salt.exceptions import SaltClientError, SaltSystemExit from salt.utils.decorators.jinja import jinja_filter from salt.utils.versions import LooseVersion # inet_pton does not exist in Windows, this is a workaround if salt.utils.platform.is_windows(): from salt.ext import win_inet_pton # pylint: disable=unused-import log = logging.getLogger(__name__) try: import ctypes import ctypes.util libc = ctypes.cdll.LoadLibrary(ctypes.util.find_library("c")) res_init = libc.__res_init except (ImportError, OSError, AttributeError, TypeError): pass # pylint: disable=C0103 def sanitize_host(host): ''' Sanitize host string. https://tools.ietf.org/html/rfc1123#section-2.1 ''' RFC952_characters = ascii_letters + digits + ".-" return "".join([c for c in host[0:255] if c in RFC952_characters]) def isportopen(host, port): ''' Return status of a port ''' if not 1 <= int(port) <= 65535: return False sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) out = sock.connect_ex((sanitize_host(host), int(port))) return out def host_to_ips(host): ''' Returns a list of IP addresses of a given hostname or None if not found. ''' ips = [] try: for family, socktype, proto, canonname, sockaddr in socket.getaddrinfo( host, 0, socket.AF_UNSPEC, socket.SOCK_STREAM): if family == socket.AF_INET: ip, port = sockaddr elif family == socket.AF_INET6: ip, port, flow_info, scope_id = sockaddr ips.append(ip) if not ips: ips = None except Exception: ips = None return ips def _generate_minion_id(): ''' Get list of possible host names and convention names. :return: ''' # There are three types of hostnames: # 1. Network names. How host is accessed from the network. # 2. Host aliases. They might be not available in all the network or only locally (/etc/hosts) # 3. Convention names, an internal nodename. class DistinctList(list): ''' List, which allows one to append only distinct objects. Needs to work on Python 2.6, because of collections.OrderedDict only since 2.7 version. Override 'filter()' for custom filtering. ''' localhost_matchers = [r'localhost.*', r'ip6-.*', r'127[.]\d', r'0\.0\.0\.0', r'::1.*', r'ipv6-.*', r'fe00::.*', r'fe02::.*', r'1.0.0.*.ip6.arpa'] def append(self, p_object): if p_object and p_object not in self and not self.filter(p_object): super(DistinctList, self).append(p_object) return self def extend(self, iterable): for obj in iterable: self.append(obj) return self def filter(self, element): 'Returns True if element needs to be filtered' for rgx in self.localhost_matchers: if re.match(rgx, element): return True def first(self): return self and self[0] or None hostname = socket.gethostname() hosts = DistinctList().append( salt.utils.stringutils.to_unicode(socket.getfqdn(salt.utils.stringutils.to_bytes(hostname))) ).append(platform.node()).append(hostname) if not hosts: try: for a_nfo in socket.getaddrinfo(hosts.first() or 'localhost', None, socket.AF_INET, socket.SOCK_RAW, socket.IPPROTO_IP, socket.AI_CANONNAME): if len(a_nfo) > 3: hosts.append(a_nfo[3]) except socket.gaierror: log.warning('Cannot resolve address %s info via socket: %s', hosts.first() or 'localhost (N/A)', socket.gaierror) # Universal method for everywhere (Linux, Slowlaris, Windows etc) for f_name in ('/etc/hostname', '/etc/nodename', '/etc/hosts', r'{win}\system32\drivers\etc\hosts'.format(win=os.getenv('WINDIR'))): try: with salt.utils.files.fopen(f_name) as f_hdl: for line in f_hdl: line = salt.utils.stringutils.to_unicode(line) hst = line.strip().split('#')[0].strip().split() if hst: if hst[0][:4] in ('127.', '::1') or len(hst) == 1: hosts.extend(hst) except IOError: pass # include public and private ipaddresses return hosts.extend([addr for addr in ip_addrs() if not ipaddress.ip_address(addr).is_loopback]) def generate_minion_id(): ''' Return only first element of the hostname from all possible list. :return: ''' try: ret = salt.utils.stringutils.to_unicode(_generate_minion_id().first()) except TypeError: ret = None return ret or 'localhost' def get_socket(addr, type=socket.SOCK_STREAM, proto=0): ''' Return a socket object for the addr IP-version agnostic ''' version = ipaddress.ip_address(addr).version if version == 4: family = socket.AF_INET elif version == 6: family = socket.AF_INET6 return socket.socket(family, type, proto) def get_fqhostname(): ''' Returns the fully qualified hostname ''' # try getaddrinfo() fqdn = None try: addrinfo = socket.getaddrinfo( socket.gethostname(), 0, socket.AF_UNSPEC, socket.SOCK_STREAM, socket.SOL_TCP, socket.AI_CANONNAME ) for info in addrinfo: # info struct [family, socktype, proto, canonname, sockaddr] # On Windows `canonname` can be an empty string # This can cause the function to return `None` if len(info) > 3 and info[3]: fqdn = info[3] break except socket.gaierror: pass # NOTE: this used to log.error() but it was later disabled except socket.error as err: log.debug('socket.getaddrinfo() failure while finding fqdn: %s', err) if fqdn is None: fqdn = socket.getfqdn() return fqdn def ip_to_host(ip): ''' Returns the hostname of a given IP ''' try: hostname, aliaslist, ipaddrlist = socket.gethostbyaddr(ip) except Exception as exc: log.debug('salt.utils.network.ip_to_host(%r) failed: %s', ip, exc) hostname = None return hostname # pylint: enable=C0103 def is_reachable_host(entity_name): ''' Returns a bool telling if the entity name is a reachable host (IPv4/IPv6/FQDN/etc). :param hostname: :return: ''' try: assert type(socket.getaddrinfo(entity_name, 0, 0, 0, 0)) == list ret = True except socket.gaierror: ret = False return ret def is_ip(ip): ''' Returns a bool telling if the passed IP is a valid IPv4 or IPv6 address. ''' return is_ipv4(ip) or is_ipv6(ip) def is_ipv4(ip): ''' Returns a bool telling if the value passed to it was a valid IPv4 address ''' try: return ipaddress.ip_address(ip).version == 4 except ValueError: return False def is_ipv6(ip): ''' Returns a bool telling if the value passed to it was a valid IPv6 address ''' try: return ipaddress.ip_address(ip).version == 6 except ValueError: return False def is_subnet(cidr): ''' Returns a bool telling if the passed string is an IPv4 or IPv6 subnet ''' return is_ipv4_subnet(cidr) or is_ipv6_subnet(cidr) def is_ipv4_subnet(cidr): ''' Returns a bool telling if the passed string is an IPv4 subnet ''' try: return '/' in cidr and bool(ipaddress.IPv4Network(cidr)) except Exception: return False def is_ipv6_subnet(cidr): ''' Returns a bool telling if the passed string is an IPv6 subnet ''' try: return '/' in cidr and bool(ipaddress.IPv6Network(cidr)) except Exception: return False @jinja_filter('is_ip') def is_ip_filter(ip, options=None): ''' Returns a bool telling if the passed IP is a valid IPv4 or IPv6 address. ''' return is_ipv4_filter(ip, options=options) or is_ipv6_filter(ip, options=options) def _ip_options_global(ip_obj, version): return not ip_obj.is_private def _ip_options_multicast(ip_obj, version): return ip_obj.is_multicast def _ip_options_loopback(ip_obj, version): return ip_obj.is_loopback def _ip_options_link_local(ip_obj, version): return ip_obj.is_link_local def _ip_options_private(ip_obj, version): return ip_obj.is_private def _ip_options_reserved(ip_obj, version): return ip_obj.is_reserved def _ip_options_site_local(ip_obj, version): if version == 6: return ip_obj.is_site_local return False def _ip_options_unspecified(ip_obj, version): return ip_obj.is_unspecified def _ip_options(ip_obj, version, options=None): # will process and IP options options_fun_map = { 'global': _ip_options_global, 'link-local': _ip_options_link_local, 'linklocal': _ip_options_link_local, 'll': _ip_options_link_local, 'link_local': _ip_options_link_local, 'loopback': _ip_options_loopback, 'lo': _ip_options_loopback, 'multicast': _ip_options_multicast, 'private': _ip_options_private, 'public': _ip_options_global, 'reserved': _ip_options_reserved, 'site-local': _ip_options_site_local, 'sl': _ip_options_site_local, 'site_local': _ip_options_site_local, 'unspecified': _ip_options_unspecified } if not options: return six.text_type(ip_obj) # IP version already checked options_list = [option.strip() for option in options.split(',')] for option, fun in options_fun_map.items(): if option in options_list: fun_res = fun(ip_obj, version) if not fun_res: return None # stop at first failed test # else continue return six.text_type(ip_obj) def _is_ipv(ip, version, options=None): if not version: version = 4 if version not in (4, 6): return None try: ip_obj = ipaddress.ip_address(ip) except ValueError: # maybe it is an IP network try: ip_obj = ipaddress.ip_interface(ip) except ValueError: # nope, still not :( return None if not ip_obj.version == version: return None # has the right version, let's move on return _ip_options(ip_obj, version, options=options) @jinja_filter('is_ipv4') def is_ipv4_filter(ip, options=None): ''' Returns a bool telling if the value passed to it was a valid IPv4 address. ip The IP address. net: False Consider IP addresses followed by netmask. options CSV of options regarding the nature of the IP address. E.g.: loopback, multicast, private etc. ''' _is_ipv4 = _is_ipv(ip, 4, options=options) return isinstance(_is_ipv4, six.string_types) @jinja_filter('is_ipv6') def is_ipv6_filter(ip, options=None): ''' Returns a bool telling if the value passed to it was a valid IPv6 address. ip The IP address. net: False Consider IP addresses followed by netmask. options CSV of options regarding the nature of the IP address. E.g.: loopback, multicast, private etc. ''' _is_ipv6 = _is_ipv(ip, 6, options=options) return isinstance(_is_ipv6, six.string_types) def _ipv_filter(value, version, options=None): if version not in (4, 6): return if isinstance(value, (six.string_types, six.text_type, six.binary_type)): return _is_ipv(value, version, options=options) # calls is_ipv4 or is_ipv6 for `value` elif isinstance(value, (list, tuple, types.GeneratorType)): # calls is_ipv4 or is_ipv6 for each element in the list # os it filters and returns only those elements having the desired IP version return [ _is_ipv(addr, version, options=options) for addr in value if _is_ipv(addr, version, options=options) is not None ] return None @jinja_filter('ipv4') def ipv4(value, options=None): ''' Filters a list and returns IPv4 values only. ''' return _ipv_filter(value, 4, options=options) @jinja_filter('ipv6') def ipv6(value, options=None): ''' Filters a list and returns IPv6 values only. ''' return _ipv_filter(value, 6, options=options) @jinja_filter('ipaddr') def ipaddr(value, options=None): ''' Filters and returns only valid IP objects. ''' ipv4_obj = ipv4(value, options=options) ipv6_obj = ipv6(value, options=options) if ipv4_obj is None or ipv6_obj is None: # an IP address can be either IPv4 either IPv6 # therefofe if the value passed as arg is not a list, at least one of the calls above will return None # if one of them is none, means that we should return only one of them return ipv4_obj or ipv6_obj # one of them else: return ipv4_obj + ipv6_obj # extend lists def _filter_ipaddr(value, options, version=None): ipaddr_filter_out = None if version: if version == 4: ipaddr_filter_out = ipv4(value, options) elif version == 6: ipaddr_filter_out = ipv6(value, options) else: ipaddr_filter_out = ipaddr(value, options) if not ipaddr_filter_out: return if not isinstance(ipaddr_filter_out, (list, tuple, types.GeneratorType)): ipaddr_filter_out = [ipaddr_filter_out] return ipaddr_filter_out @jinja_filter('ip_host') def ip_host(value, options=None, version=None): ''' Returns the interfaces IP address, e.g.: 192.168.0.1/28. ''' ipaddr_filter_out = _filter_ipaddr(value, options=options, version=version) if not ipaddr_filter_out: return if not isinstance(value, (list, tuple, types.GeneratorType)): return six.text_type(ipaddress.ip_interface(ipaddr_filter_out[0])) return [six.text_type(ipaddress.ip_interface(ip_a)) for ip_a in ipaddr_filter_out] def _network_hosts(ip_addr_entry): return [ six.text_type(host) for host in ipaddress.ip_network(ip_addr_entry, strict=False).hosts() ] @jinja_filter('network_hosts') def network_hosts(value, options=None, version=None): ''' Return the list of hosts within a network. .. note:: When running this command with a large IPv6 network, the command will take a long time to gather all of the hosts. ''' ipaddr_filter_out = _filter_ipaddr(value, options=options, version=version) if not ipaddr_filter_out: return if not isinstance(value, (list, tuple, types.GeneratorType)): return _network_hosts(ipaddr_filter_out[0]) return [ _network_hosts(ip_a) for ip_a in ipaddr_filter_out ] def _network_size(ip_addr_entry): return ipaddress.ip_network(ip_addr_entry, strict=False).num_addresses @jinja_filter('network_size') def network_size(value, options=None, version=None): ''' Get the size of a network. ''' ipaddr_filter_out = _filter_ipaddr(value, options=options, version=version) if not ipaddr_filter_out: return if not isinstance(value, (list, tuple, types.GeneratorType)): return _network_size(ipaddr_filter_out[0]) return [ _network_size(ip_a) for ip_a in ipaddr_filter_out ] def natural_ipv4_netmask(ip, fmt='prefixlen'): ''' Returns the "natural" mask of an IPv4 address ''' bits = _ipv4_to_bits(ip) if bits.startswith('11'): mask = '24' elif bits.startswith('1'): mask = '16' else: mask = '8' if fmt == 'netmask': return cidr_to_ipv4_netmask(mask) else: return '/' + mask def rpad_ipv4_network(ip): ''' Returns an IP network address padded with zeros. Ex: '192.168.3' -> '192.168.3.0' '10.209' -> '10.209.0.0' ''' return '.'.join(itertools.islice(itertools.chain(ip.split('.'), '0000'), 0, 4)) def cidr_to_ipv4_netmask(cidr_bits): ''' Returns an IPv4 netmask ''' try: cidr_bits = int(cidr_bits) if not 1 <= cidr_bits <= 32: return '' except ValueError: return '' netmask = '' for idx in range(4): if idx: netmask += '.' if cidr_bits >= 8: netmask += '255' cidr_bits -= 8 else: netmask += '{0:d}'.format(256 - (2 ** (8 - cidr_bits))) cidr_bits = 0 return netmask def _number_of_set_bits_to_ipv4_netmask(set_bits): # pylint: disable=C0103 ''' Returns an IPv4 netmask from the integer representation of that mask. Ex. 0xffffff00 -> '255.255.255.0' ''' return cidr_to_ipv4_netmask(_number_of_set_bits(set_bits)) # pylint: disable=C0103 def _number_of_set_bits(x): ''' Returns the number of bits that are set in a 32bit int ''' # Taken from http://stackoverflow.com/a/4912729. Many thanks! x -= (x >> 1) & 0x55555555 x = ((x >> 2) & 0x33333333) + (x & 0x33333333) x = ((x >> 4) + x) & 0x0f0f0f0f x += x >> 8 x += x >> 16 return x & 0x0000003f # pylint: enable=C0103 def _interfaces_ip(out): ''' Uses ip to return a dictionary of interfaces with various information about each (up/down state, ip address, netmask, and hwaddr) ''' ret = dict() def parse_network(value, cols): ''' Return a tuple of ip, netmask, broadcast based on the current set of cols ''' brd = None scope = None if '/' in value: # we have a CIDR in this address ip, cidr = value.split('/') # pylint: disable=C0103 else: ip = value # pylint: disable=C0103 cidr = 32 if type_ == 'inet': mask = cidr_to_ipv4_netmask(int(cidr)) if 'brd' in cols: brd = cols[cols.index('brd') + 1] elif type_ == 'inet6': mask = cidr if 'scope' in cols: scope = cols[cols.index('scope') + 1] return (ip, mask, brd, scope) groups = re.compile('\r?\n\\d').split(out) for group in groups: iface = None data = dict() for line in group.splitlines(): if ' ' not in line: continue match = re.match(r'^\d*:\s+([\w.\-]+)(?:@)?([\w.\-]+)?:\s+<(.+)>', line) if match: iface, parent, attrs = match.groups() if 'UP' in attrs.split(','): data['up'] = True else: data['up'] = False if parent: data['parent'] = parent continue cols = line.split() if len(cols) >= 2: type_, value = tuple(cols[0:2]) iflabel = cols[-1:][0] if type_ in ('inet', 'inet6'): if 'secondary' not in cols: ipaddr, netmask, broadcast, scope = parse_network(value, cols) if type_ == 'inet': if 'inet' not in data: data['inet'] = list() addr_obj = dict() addr_obj['address'] = ipaddr addr_obj['netmask'] = netmask addr_obj['broadcast'] = broadcast addr_obj['label'] = iflabel data['inet'].append(addr_obj) elif type_ == 'inet6': if 'inet6' not in data: data['inet6'] = list() addr_obj = dict() addr_obj['address'] = ipaddr addr_obj['prefixlen'] = netmask addr_obj['scope'] = scope data['inet6'].append(addr_obj) else: if 'secondary' not in data: data['secondary'] = list() ip_, mask, brd, scp = parse_network(value, cols) data['secondary'].append({ 'type': type_, 'address': ip_, 'netmask': mask, 'broadcast': brd, 'label': iflabel, }) del ip_, mask, brd, scp elif type_.startswith('link'): data['hwaddr'] = value if iface: ret[iface] = data del iface, data return ret def _interfaces_ifconfig(out): ''' Uses ifconfig to return a dictionary of interfaces with various information about each (up/down state, ip address, netmask, and hwaddr) ''' ret = dict() piface = re.compile(r'^([^\s:]+)') pmac = re.compile('.*?(?:HWaddr|ether|address:|lladdr) ([0-9a-fA-F:]+)') if salt.utils.platform.is_sunos(): pip = re.compile(r'.*?(?:inet\s+)([0-9]+\.[0-9]+\.[0-9]+\.[0-9]+)(.*)') pip6 = re.compile('.*?(?:inet6 )([0-9a-fA-F:]+)') pmask6 = re.compile(r'.*?(?:inet6 [0-9a-fA-F:]+/(\d+)).*') else: pip = re.compile(r'.*?(?:inet addr:|inet [^\d]*)(.*?)\s') pip6 = re.compile('.*?(?:inet6 addr: (.*?)/|inet6 )([0-9a-fA-F:]+)') pmask6 = re.compile(r'.*?(?:inet6 addr: [0-9a-fA-F:]+/(\d+)|prefixlen (\d+))(?: Scope:([a-zA-Z]+)| scopeid (0x[0-9a-fA-F]))?') pmask = re.compile(r'.*?(?:Mask:|netmask )(?:((?:0x)?[0-9a-fA-F]{8})|([\d\.]+))') pupdown = re.compile('UP') pbcast = re.compile(r'.*?(?:Bcast:|broadcast )([\d\.]+)') groups = re.compile('\r?\n(?=\\S)').split(out) for group in groups: data = dict() iface = '' updown = False for line in group.splitlines(): miface = piface.match(line) mmac = pmac.match(line) mip = pip.match(line) mip6 = pip6.match(line) mupdown = pupdown.search(line) if miface: iface = miface.group(1) if mmac: data['hwaddr'] = mmac.group(1) if salt.utils.platform.is_sunos(): expand_mac = [] for chunk in data['hwaddr'].split(':'): expand_mac.append('0{0}'.format(chunk) if len(chunk) < 2 else '{0}'.format(chunk)) data['hwaddr'] = ':'.join(expand_mac) if mip: if 'inet' not in data: data['inet'] = list() addr_obj = dict() addr_obj['address'] = mip.group(1) mmask = pmask.match(line) if mmask: if mmask.group(1): mmask = _number_of_set_bits_to_ipv4_netmask( int(mmask.group(1), 16)) else: mmask = mmask.group(2) addr_obj['netmask'] = mmask mbcast = pbcast.match(line) if mbcast: addr_obj['broadcast'] = mbcast.group(1) data['inet'].append(addr_obj) if mupdown: updown = True if mip6: if 'inet6' not in data: data['inet6'] = list() addr_obj = dict() addr_obj['address'] = mip6.group(1) or mip6.group(2) mmask6 = pmask6.match(line) if mmask6: addr_obj['prefixlen'] = mmask6.group(1) or mmask6.group(2) if not salt.utils.platform.is_sunos(): ipv6scope = mmask6.group(3) or mmask6.group(4) addr_obj['scope'] = ipv6scope.lower() if ipv6scope is not None else ipv6scope # SunOS sometimes has ::/0 as inet6 addr when using addrconf if not salt.utils.platform.is_sunos() \ or addr_obj['address'] != '::' \ and addr_obj['prefixlen'] != 0: data['inet6'].append(addr_obj) data['up'] = updown if iface in ret: # SunOS optimization, where interfaces occur twice in 'ifconfig -a' # output with the same name: for ipv4 and then for ipv6 addr family. # Every instance has it's own 'UP' status and we assume that ipv4 # status determines global interface status. # # merge items with higher priority for older values # after that merge the inet and inet6 sub items for both ret[iface] = dict(list(data.items()) + list(ret[iface].items())) if 'inet' in data: ret[iface]['inet'].extend(x for x in data['inet'] if x not in ret[iface]['inet']) if 'inet6' in data: ret[iface]['inet6'].extend(x for x in data['inet6'] if x not in ret[iface]['inet6']) else: ret[iface] = data del data return ret def linux_interfaces(): ''' Obtain interface information for *NIX/BSD variants ''' ifaces = dict() ip_path = salt.utils.path.which('ip') ifconfig_path = None if ip_path else salt.utils.path.which('ifconfig') if ip_path: cmd1 = subprocess.Popen( '{0} link show'.format(ip_path), shell=True, close_fds=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT).communicate()[0] cmd2 = subprocess.Popen( '{0} addr show'.format(ip_path), shell=True, close_fds=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT).communicate()[0] ifaces = _interfaces_ip("{0}\n{1}".format( salt.utils.stringutils.to_str(cmd1), salt.utils.stringutils.to_str(cmd2))) elif ifconfig_path: cmd = subprocess.Popen( '{0} -a'.format(ifconfig_path), shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT).communicate()[0] ifaces = _interfaces_ifconfig(salt.utils.stringutils.to_str(cmd)) return ifaces def _netbsd_interfaces_ifconfig(out): ''' Uses ifconfig to return a dictionary of interfaces with various information about each (up/down state, ip address, netmask, and hwaddr) ''' ret = dict() piface = re.compile(r'^([^\s:]+)') pmac = re.compile('.*?address: ([0-9a-f:]+)') pip = re.compile(r'.*?inet [^\d]*(.*?)/([\d]*)\s') pip6 = re.compile(r'.*?inet6 ([0-9a-f:]+)%([a-zA-Z0-9]*)/([\d]*)\s') pupdown = re.compile('UP') pbcast = re.compile(r'.*?broadcast ([\d\.]+)') groups = re.compile('\r?\n(?=\\S)').split(out) for group in groups: data = dict() iface = '' updown = False for line in group.splitlines(): miface = piface.match(line) mmac = pmac.match(line) mip = pip.match(line) mip6 = pip6.match(line) mupdown = pupdown.search(line) if miface: iface = miface.group(1) if mmac: data['hwaddr'] = mmac.group(1) if mip: if 'inet' not in data: data['inet'] = list() addr_obj = dict() addr_obj['address'] = mip.group(1) mmask = mip.group(2) if mip.group(2): addr_obj['netmask'] = cidr_to_ipv4_netmask(mip.group(2)) mbcast = pbcast.match(line) if mbcast: addr_obj['broadcast'] = mbcast.group(1) data['inet'].append(addr_obj) if mupdown: updown = True if mip6: if 'inet6' not in data: data['inet6'] = list() addr_obj = dict() addr_obj['address'] = mip6.group(1) mmask6 = mip6.group(3) addr_obj['scope'] = mip6.group(2) addr_obj['prefixlen'] = mip6.group(3) data['inet6'].append(addr_obj) data['up'] = updown ret[iface] = data del data return ret def netbsd_interfaces(): ''' Obtain interface information for NetBSD >= 8 where the ifconfig output diverged from other BSD variants (Netmask is now part of the address) ''' # NetBSD versions prior to 8.0 can still use linux_interfaces() if LooseVersion(os.uname()[2]) < LooseVersion('8.0'): return linux_interfaces() ifconfig_path = salt.utils.path.which('ifconfig') cmd = subprocess.Popen( '{0} -a'.format(ifconfig_path), shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT).communicate()[0] return _netbsd_interfaces_ifconfig(salt.utils.stringutils.to_str(cmd)) def _interfaces_ipconfig(out): ''' Returns a dictionary of interfaces with various information about each (up/down state, ip address, netmask, and hwaddr) NOTE: This is not used by any function and may be able to be removed in the future. ''' ifaces = dict() iface = None adapter_iface_regex = re.compile(r'adapter (\S.+):$') for line in out.splitlines(): if not line: continue # TODO what does Windows call Infiniband and 10/40gige adapters if line.startswith('Ethernet'): iface = ifaces[adapter_iface_regex.search(line).group(1)] iface['up'] = True addr = None continue if iface: key, val = line.split(',', 1) key = key.strip(' .') val = val.strip() if addr and key == 'Subnet Mask': addr['netmask'] = val elif key in ('IP Address', 'IPv4 Address'): if 'inet' not in iface: iface['inet'] = list() addr = {'address': val.rstrip('(Preferred)'), 'netmask': None, 'broadcast': None} # TODO find the broadcast iface['inet'].append(addr) elif 'IPv6 Address' in key: if 'inet6' not in iface: iface['inet'] = list() # XXX What is the prefixlen!? addr = {'address': val.rstrip('(Preferred)'), 'prefixlen': None} iface['inet6'].append(addr) elif key == 'Physical Address': iface['hwaddr'] = val elif key == 'Media State': # XXX seen used for tunnel adaptors # might be useful iface['up'] = (val != 'Media disconnected') def win_interfaces(): ''' Obtain interface information for Windows systems ''' with salt.utils.winapi.Com(): c = wmi.WMI() ifaces = {} for iface in c.Win32_NetworkAdapterConfiguration(IPEnabled=1): ifaces[iface.Description] = dict() if iface.MACAddress: ifaces[iface.Description]['hwaddr'] = iface.MACAddress if iface.IPEnabled: ifaces[iface.Description]['up'] = True for ip in iface.IPAddress: if '.' in ip: if 'inet' not in ifaces[iface.Description]: ifaces[iface.Description]['inet'] = [] item = {'address': ip, 'label': iface.Description} if iface.DefaultIPGateway: broadcast = next((i for i in iface.DefaultIPGateway if '.' in i), '') if broadcast: item['broadcast'] = broadcast if iface.IPSubnet: netmask = next((i for i in iface.IPSubnet if '.' in i), '') if netmask: item['netmask'] = netmask ifaces[iface.Description]['inet'].append(item) if ':' in ip: if 'inet6' not in ifaces[iface.Description]: ifaces[iface.Description]['inet6'] = [] item = {'address': ip} if iface.DefaultIPGateway: broadcast = next((i for i in iface.DefaultIPGateway if ':' in i), '') if broadcast: item['broadcast'] = broadcast if iface.IPSubnet: netmask = next((i for i in iface.IPSubnet if ':' in i), '') if netmask: item['netmask'] = netmask ifaces[iface.Description]['inet6'].append(item) else: ifaces[iface.Description]['up'] = False return ifaces def interfaces(): ''' Return a dictionary of information about all the interfaces on the minion ''' if salt.utils.platform.is_windows(): return win_interfaces() elif salt.utils.platform.is_netbsd(): return netbsd_interfaces() else: return linux_interfaces() def get_net_start(ipaddr, netmask): ''' Return the address of the network ''' net = ipaddress.ip_network('{0}/{1}'.format(ipaddr, netmask), strict=False) return six.text_type(net.network_address) def get_net_size(mask): ''' Turns an IPv4 netmask into it's corresponding prefix length (255.255.255.0 -> 24 as in 192.168.1.10/24). ''' binary_str = '' for octet in mask.split('.'): binary_str += bin(int(octet))[2:].zfill(8) return len(binary_str.rstrip('0')) def calc_net(ipaddr, netmask=None): ''' Takes IP (CIDR notation supported) and optionally netmask and returns the network in CIDR-notation. (The IP can be any IP inside the subnet) ''' if netmask is not None: ipaddr = '{0}/{1}'.format(ipaddr, netmask) return six.text_type(ipaddress.ip_network(ipaddr, strict=False)) def _ipv4_to_bits(ipaddr): ''' Accepts an IPv4 dotted quad and returns a string representing its binary counterpart ''' return ''.join([bin(int(x))[2:].rjust(8, '0') for x in ipaddr.split('.')]) def _get_iface_info(iface): ''' If `iface` is available, return interface info and no error, otherwise return no info and log and return an error ''' iface_info = interfaces() if iface in iface_info.keys(): return iface_info, False else: error_msg = ('Interface "{0}" not in available interfaces: "{1}"' ''.format(iface, '", "'.join(iface_info.keys()))) log.error(error_msg) return None, error_msg def _hw_addr_aix(iface): ''' Return the hardware address (a.k.a. MAC address) for a given interface on AIX MAC address not available in through interfaces ''' cmd = subprocess.Popen( 'entstat -d {0} | grep \'Hardware Address\''.format(iface), shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT).communicate()[0] if cmd: comps = cmd.split(' ') if len(comps) == 3: mac_addr = comps[2].strip('\'').strip() return mac_addr error_msg = ('Interface "{0}" either not available or does not contain a hardware address'.format(iface)) log.error(error_msg) return error_msg def hw_addr(iface): ''' Return the hardware address (a.k.a. MAC address) for a given interface .. versionchanged:: 2016.11.4 Added support for AIX ''' if salt.utils.platform.is_aix(): return _hw_addr_aix iface_info, error = _get_iface_info(iface) if error is False: return iface_info.get(iface, {}).get('hwaddr', '') else: return error def interface_ip(iface): ''' Return `iface` IPv4 addr or an error if `iface` does not exist ''' iface_info, error = _get_iface_info(iface) if error is False: inet = iface_info.get(iface, {}).get('inet', None) return inet[0].get('address', '') if inet else '' else: return error def _subnets(proto='inet', interfaces_=None): ''' Returns a list of subnets to which the host belongs ''' if interfaces_ is None: ifaces = interfaces() elif isinstance(interfaces_, list): ifaces = {} for key, value in six.iteritems(interfaces()): if key in interfaces_: ifaces[key] = value else: ifaces = {interfaces_: interfaces().get(interfaces_, {})} ret = set() if proto == 'inet': subnet = 'netmask' dflt_cidr = 32 elif proto == 'inet6': subnet = 'prefixlen' dflt_cidr = 128 else: log.error('Invalid proto %s calling subnets()', proto) return for ip_info in six.itervalues(ifaces): addrs = ip_info.get(proto, []) addrs.extend([addr for addr in ip_info.get('secondary', []) if addr.get('type') == proto]) for intf in addrs: if subnet in intf: intf = ipaddress.ip_interface('{0}/{1}'.format(intf['address'], intf[subnet])) else: intf = ipaddress.ip_interface('{0}/{1}'.format(intf['address'], dflt_cidr)) if not intf.is_loopback: ret.add(intf.network) return [six.text_type(net) for net in sorted(ret)] def subnets(interfaces=None): ''' Returns a list of IPv4 subnets to which the host belongs ''' return _subnets('inet', interfaces_=interfaces) def subnets6(): ''' Returns a list of IPv6 subnets to which the host belongs ''' return _subnets('inet6') def in_subnet(cidr, addr=None): ''' Returns True if host or (any of) addrs is within specified subnet, otherwise False ''' try: cidr = ipaddress.ip_network(cidr) except ValueError: log.error('Invalid CIDR \'%s\'', cidr) return False if addr is None: addr = ip_addrs() addr.extend(ip_addrs6()) elif not isinstance(addr, (list, tuple)): addr = (addr,) return any(ipaddress.ip_address(item) in cidr for item in addr) def _ip_addrs(interface=None, include_loopback=False, interface_data=None, proto='inet'): ''' Return the full list of IP adresses matching the criteria proto = inet|inet6 ''' ret = set() ifaces = interface_data \ if isinstance(interface_data, dict) \ else interfaces() if interface is None: target_ifaces = ifaces else: target_ifaces = dict([(k, v) for k, v in six.iteritems(ifaces) if k == interface]) if not target_ifaces: log.error('Interface %s not found.', interface) for ip_info in six.itervalues(target_ifaces): addrs = ip_info.get(proto, []) addrs.extend([addr for addr in ip_info.get('secondary', []) if addr.get('type') == proto]) for addr in addrs: addr = ipaddress.ip_address(addr.get('address')) if not addr.is_loopback or include_loopback: ret.add(addr) return [six.text_type(addr) for addr in sorted(ret)] def ip_addrs(interface=None, include_loopback=False, interface_data=None): ''' Returns a list of IPv4 addresses assigned to the host. 127.0.0.1 is ignored, unless 'include_loopback=True' is indicated. If 'interface' is provided, then only IP addresses from that interface will be returned. ''' return _ip_addrs(interface, include_loopback, interface_data, 'inet') def ip_addrs6(interface=None, include_loopback=False, interface_data=None): ''' Returns a list of IPv6 addresses assigned to the host. ::1 is ignored, unless 'include_loopback=True' is indicated. If 'interface' is provided, then only IP addresses from that interface will be returned. ''' return _ip_addrs(interface, include_loopback, interface_data, 'inet6') def hex2ip(hex_ip, invert=False): ''' Convert a hex string to an ip, if a failure occurs the original hex is returned. If 'invert=True' assume that ip from /proc/net/<proto> ''' if len(hex_ip) == 32: # ipv6 ip = [] for i in range(0, 32, 8): ip_part = hex_ip[i:i + 8] ip_part = [ip_part[x:x + 2] for x in range(0, 8, 2)] if invert: ip.append("{0[3]}{0[2]}:{0[1]}{0[0]}".format(ip_part)) else: ip.append("{0[0]}{0[1]}:{0[2]}{0[3]}".format(ip_part)) try: address = ipaddress.IPv6Address(":".join(ip)) if address.ipv4_mapped: return str(address.ipv4_mapped) else: return address.compressed except ipaddress.AddressValueError as ex: log.error('hex2ip - ipv6 address error: %s', ex) return hex_ip try: hip = int(hex_ip, 16) except ValueError: return hex_ip if invert: return '{3}.{2}.{1}.{0}'.format(hip >> 24 & 255, hip >> 16 & 255, hip >> 8 & 255, hip & 255) return '{0}.{1}.{2}.{3}'.format(hip >> 24 & 255, hip >> 16 & 255, hip >> 8 & 255, hip & 255) def mac2eui64(mac, prefix=None): ''' Convert a MAC address to a EUI64 identifier or, with prefix provided, a full IPv6 address ''' # http://tools.ietf.org/html/rfc4291#section-2.5.1 eui64 = re.sub(r'[.:-]', '', mac).lower() eui64 = eui64[0:6] + 'fffe' + eui64[6:] eui64 = hex(int(eui64[0:2], 16) | 2)[2:].zfill(2) + eui64[2:] if prefix is None: return ':'.join(re.findall(r'.{4}', eui64)) else: try: net = ipaddress.ip_network(prefix, strict=False) euil = int('0x{0}'.format(eui64), 16) return '{0}/{1}'.format(net[euil], net.prefixlen) except Exception: return def active_tcp(): ''' Return a dict describing all active tcp connections as quickly as possible ''' ret = {} for statf in ['/proc/net/tcp', '/proc/net/tcp6']: if os.path.isfile(statf): with salt.utils.files.fopen(statf, 'rb') as fp_: for line in fp_: line = salt.utils.stringutils.to_unicode(line) if line.strip().startswith('sl'): continue iret = _parse_tcp_line(line) sl = next(iter(iret)) if iret[sl]['state'] == 1: # 1 is ESTABLISHED del iret[sl]['state'] ret[len(ret)] = iret[sl] return ret def local_port_tcp(port): ''' Return a set of remote ip addrs attached to the specified local port ''' ret = _remotes_on(port, 'local_port') return ret def remote_port_tcp(port): ''' Return a set of ip addrs the current host is connected to on given port ''' ret = _remotes_on(port, 'remote_port') return ret def _remotes_on(port, which_end): ''' Return a set of ip addrs active tcp connections ''' port = int(port) ret = _netlink_tool_remote_on(port, which_end) if ret is not None: return ret ret = set() proc_available = False for statf in ['/proc/net/tcp', '/proc/net/tcp6']: if os.path.isfile(statf): proc_available = True with salt.utils.files.fopen(statf, 'r') as fp_: for line in fp_: line = salt.utils.stringutils.to_unicode(line) if line.strip().startswith('sl'): continue iret = _parse_tcp_line(line) sl = next(iter(iret)) if iret[sl][which_end] == port and iret[sl]['state'] == 1: # 1 is ESTABLISHED ret.add(iret[sl]['remote_addr']) if not proc_available: # Fallback to use OS specific tools if salt.utils.platform.is_sunos(): return _sunos_remotes_on(port, which_end) if salt.utils.platform.is_freebsd(): return _freebsd_remotes_on(port, which_end) if salt.utils.platform.is_netbsd(): return _netbsd_remotes_on(port, which_end) if salt.utils.platform.is_openbsd(): return _openbsd_remotes_on(port, which_end) if salt.utils.platform.is_windows(): return _windows_remotes_on(port, which_end) if salt.utils.platform.is_aix(): return _aix_remotes_on(port, which_end) return _linux_remotes_on(port, which_end) return ret def _parse_tcp_line(line): ''' Parse a single line from the contents of /proc/net/tcp or /proc/net/tcp6 ''' ret = {} comps = line.strip().split() sl = comps[0].rstrip(':') ret[sl] = {} l_addr, l_port = comps[1].split(':') r_addr, r_port = comps[2].split(':') ret[sl]['local_addr'] = hex2ip(l_addr, True) ret[sl]['local_port'] = int(l_port, 16) ret[sl]['remote_addr'] = hex2ip(r_addr, True) ret[sl]['remote_port'] = int(r_port, 16) ret[sl]['state'] = int(comps[3], 16) return ret def _netlink_tool_remote_on(port, which_end): ''' Returns set of ipv4 host addresses of remote established connections on local or remote tcp port. Parses output of shell 'ss' to get connections [root@salt-master ~]# ss -ant State Recv-Q Send-Q Local Address:Port Peer Address:Port LISTEN 0 511 *:80 *:* LISTEN 0 128 *:22 *:* ESTAB 0 0 127.0.0.1:56726 127.0.0.1:4505 ''' remotes = set() valid = False try: data = subprocess.check_output(['ss', '-ant']) # pylint: disable=minimum-python-version except subprocess.CalledProcessError: log.error('Failed ss') raise except OSError: # not command "No such file or directory" return None lines = salt.utils.stringutils.to_str(data).split('\n') for line in lines: if 'Address:Port' in line: # ss tools may not be valid valid = True continue elif 'ESTAB' not in line: continue chunks = line.split() local_host, local_port = chunks[3].split(':', 1) remote_host, remote_port = chunks[4].split(':', 1) if which_end == 'remote_port' and int(remote_port) != port: continue if which_end == 'local_port' and int(local_port) != port: continue remotes.add(remote_host) if valid is False: remotes = None return remotes def _sunos_remotes_on(port, which_end): ''' SunOS specific helper function. Returns set of ipv4 host addresses of remote established connections on local or remote tcp port. Parses output of shell 'netstat' to get connections [root@salt-master ~]# netstat -f inet -n TCP: IPv4 Local Address Remote Address Swind Send-Q Rwind Recv-Q State -------------------- -------------------- ----- ------ ----- ------ ----------- 10.0.0.101.4505 10.0.0.1.45329 1064800 0 1055864 0 ESTABLISHED 10.0.0.101.4505 10.0.0.100.50798 1064800 0 1055864 0 ESTABLISHED ''' remotes = set() try: data = subprocess.check_output(['netstat', '-f', 'inet', '-n']) # pylint: disable=minimum-python-version except subprocess.CalledProcessError: log.error('Failed netstat') raise lines = salt.utils.stringutils.to_str(data).split('\n') for line in lines: if 'ESTABLISHED' not in line: continue chunks = line.split() local_host, local_port = chunks[0].rsplit('.', 1) remote_host, remote_port = chunks[1].rsplit('.', 1) if which_end == 'remote_port' and int(remote_port) != port: continue if which_end == 'local_port' and int(local_port) != port: continue remotes.add(remote_host) return remotes def _freebsd_remotes_on(port, which_end): ''' Returns set of ipv4 host addresses of remote established connections on local tcp port port. Parses output of shell 'sockstat' (FreeBSD) to get connections $ sudo sockstat -4 USER COMMAND PID FD PROTO LOCAL ADDRESS FOREIGN ADDRESS root python2.7 1456 29 tcp4 *:4505 *:* root python2.7 1445 17 tcp4 *:4506 *:* root python2.7 1294 14 tcp4 127.0.0.1:11813 127.0.0.1:4505 root python2.7 1294 41 tcp4 127.0.0.1:61115 127.0.0.1:4506 $ sudo sockstat -4 -c -p 4506 USER COMMAND PID FD PROTO LOCAL ADDRESS FOREIGN ADDRESS root python2.7 1294 41 tcp4 127.0.0.1:61115 127.0.0.1:4506 ''' port = int(port) remotes = set() try: cmd = salt.utils.args.shlex_split('sockstat -4 -c -p {0}'.format(port)) data = subprocess.check_output(cmd) # pylint: disable=minimum-python-version except subprocess.CalledProcessError as ex: log.error('Failed "sockstat" with returncode = %s', ex.returncode) raise lines = salt.utils.stringutils.to_str(data).split('\n') for line in lines: chunks = line.split() if not chunks: continue # ['root', 'python2.7', '1456', '37', 'tcp4', # '127.0.0.1:4505-', '127.0.0.1:55703'] # print chunks if 'COMMAND' in chunks[1]: continue # ignore header if len(chunks) < 2: continue # sockstat -4 -c -p 4506 does this with high PIDs: # USER COMMAND PID FD PROTO LOCAL ADDRESS FOREIGN ADDRESS # salt-master python2.781106 35 tcp4 192.168.12.34:4506 192.168.12.45:60143 local = chunks[-2] remote = chunks[-1] lhost, lport = local.split(':') rhost, rport = remote.split(':') if which_end == 'local' and int(lport) != port: # ignore if local port not port continue if which_end == 'remote' and int(rport) != port: # ignore if remote port not port continue remotes.add(rhost) return remotes def _netbsd_remotes_on(port, which_end): ''' Returns set of ipv4 host addresses of remote established connections on local tcp port port. Parses output of shell 'sockstat' (NetBSD) to get connections $ sudo sockstat -4 -n USER COMMAND PID FD PROTO LOCAL ADDRESS FOREIGN ADDRESS root python2.7 1456 29 tcp *.4505 *.* root python2.7 1445 17 tcp *.4506 *.* root python2.7 1294 14 tcp 127.0.0.1.11813 127.0.0.1.4505 root python2.7 1294 41 tcp 127.0.0.1.61115 127.0.0.1.4506 $ sudo sockstat -4 -c -n -p 4506 USER COMMAND PID FD PROTO LOCAL ADDRESS FOREIGN ADDRESS root python2.7 1294 41 tcp 127.0.0.1.61115 127.0.0.1.4506 ''' port = int(port) remotes = set() try: cmd = salt.utils.args.shlex_split('sockstat -4 -c -n -p {0}'.format(port)) data = subprocess.check_output(cmd) # pylint: disable=minimum-python-version except subprocess.CalledProcessError as ex: log.error('Failed "sockstat" with returncode = %s', ex.returncode) raise lines = salt.utils.stringutils.to_str(data).split('\n') for line in lines: chunks = line.split() if not chunks: continue # ['root', 'python2.7', '1456', '37', 'tcp', # '127.0.0.1.4505-', '127.0.0.1.55703'] # print chunks if 'COMMAND' in chunks[1]: continue # ignore header if len(chunks) < 2: continue local = chunks[5].split('.') lport = local.pop() lhost = '.'.join(local) remote = chunks[6].split('.') rport = remote.pop() rhost = '.'.join(remote) if which_end == 'local' and int(lport) != port: # ignore if local port not port continue if which_end == 'remote' and int(rport) != port: # ignore if remote port not port continue remotes.add(rhost) return remotes def _openbsd_remotes_on(port, which_end): ''' OpenBSD specific helper function. Returns set of ipv4 host addresses of remote established connections on local or remote tcp port. Parses output of shell 'netstat' to get connections $ netstat -nf inet Active Internet connections Proto Recv-Q Send-Q Local Address Foreign Address (state) tcp 0 0 10.0.0.101.4505 10.0.0.1.45329 ESTABLISHED tcp 0 0 10.0.0.101.4505 10.0.0.100.50798 ESTABLISHED ''' remotes = set() try: data = subprocess.check_output(['netstat', '-nf', 'inet']) # pylint: disable=minimum-python-version except subprocess.CalledProcessError: log.error('Failed netstat') raise lines = data.split('\n') for line in lines: if 'ESTABLISHED' not in line: continue chunks = line.split() local_host, local_port = chunks[3].rsplit('.', 1) remote_host, remote_port = chunks[4].rsplit('.', 1) if which_end == 'remote_port' and int(remote_port) != port: continue if which_end == 'local_port' and int(local_port) != port: continue remotes.add(remote_host) return remotes def _windows_remotes_on(port, which_end): r''' Windows specific helper function. Returns set of ipv4 host addresses of remote established connections on local or remote tcp port. Parses output of shell 'netstat' to get connections C:\>netstat -n Active Connections Proto Local Address Foreign Address State TCP 10.2.33.17:3007 130.164.12.233:10123 ESTABLISHED TCP 10.2.33.17:3389 130.164.30.5:10378 ESTABLISHED ''' remotes = set() try: data = subprocess.check_output(['netstat', '-n']) # pylint: disable=minimum-python-version except subprocess.CalledProcessError: log.error('Failed netstat') raise lines = salt.utils.stringutils.to_str(data).split('\n') for line in lines: if 'ESTABLISHED' not in line: continue chunks = line.split() local_host, local_port = chunks[1].rsplit(':', 1) remote_host, remote_port = chunks[2].rsplit(':', 1) if which_end == 'remote_port' and int(remote_port) != port: continue if which_end == 'local_port' and int(local_port) != port: continue remotes.add(remote_host) return remotes def _linux_remotes_on(port, which_end): ''' Linux specific helper function. Returns set of ip host addresses of remote established connections on local tcp port port. Parses output of shell 'lsof' to get connections $ sudo lsof -iTCP:4505 -n COMMAND PID USER FD TYPE DEVICE SIZE/OFF NODE NAME Python 9971 root 35u IPv4 0x18a8464a29ca329d 0t0 TCP *:4505 (LISTEN) Python 9971 root 37u IPv4 0x18a8464a29b2b29d 0t0 TCP 127.0.0.1:4505->127.0.0.1:55703 (ESTABLISHED) Python 10152 root 22u IPv4 0x18a8464a29c8cab5 0t0 TCP 127.0.0.1:55703->127.0.0.1:4505 (ESTABLISHED) Python 10153 root 22u IPv4 0x18a8464a29c8cab5 0t0 TCP [fe80::249a]:4505->[fe80::150]:59367 (ESTABLISHED) ''' remotes = set() try: data = subprocess.check_output( ['lsof', '-iTCP:{0:d}'.format(port), '-n', '-P'] # pylint: disable=minimum-python-version ) except subprocess.CalledProcessError as ex: if ex.returncode == 1: # Lsof return 1 if any error was detected, including the failure # to locate Internet addresses, and it is not an error in this case. log.warning('"lsof" returncode = 1, likely no active TCP sessions.') return remotes log.error('Failed "lsof" with returncode = %s', ex.returncode) raise lines = salt.utils.stringutils.to_str(data).split('\n') for line in lines: chunks = line.split() if not chunks: continue # ['Python', '9971', 'root', '37u', 'IPv4', '0x18a8464a29b2b29d', '0t0', # 'TCP', '127.0.0.1:4505->127.0.0.1:55703', '(ESTABLISHED)'] # print chunks if 'COMMAND' in chunks[0]: continue # ignore header if 'ESTABLISHED' not in chunks[-1]: continue # ignore if not ESTABLISHED # '127.0.0.1:4505->127.0.0.1:55703' local, remote = chunks[8].split('->') _, lport = local.rsplit(':', 1) rhost, rport = remote.rsplit(':', 1) if which_end == 'remote_port' and int(rport) != port: continue if which_end == 'local_port' and int(lport) != port: continue remotes.add(rhost.strip("[]")) return remotes def _aix_remotes_on(port, which_end): ''' AIX specific helper function. Returns set of ipv4 host addresses of remote established connections on local or remote tcp port. Parses output of shell 'netstat' to get connections root@la68pp002_pub:/opt/salt/lib/python2.7/site-packages/salt/modules# netstat -f inet -n Active Internet connections Proto Recv-Q Send-Q Local Address Foreign Address (state) tcp4 0 0 172.29.149.95.50093 209.41.78.13.4505 ESTABLISHED tcp4 0 0 127.0.0.1.9514 *.* LISTEN tcp4 0 0 127.0.0.1.9515 *.* LISTEN tcp4 0 0 127.0.0.1.199 127.0.0.1.32779 ESTABLISHED tcp4 0 0 127.0.0.1.32779 127.0.0.1.199 ESTABLISHED tcp4 0 40 172.29.149.95.22 172.29.96.83.41022 ESTABLISHED tcp4 0 0 172.29.149.95.22 172.29.96.83.41032 ESTABLISHED tcp4 0 0 127.0.0.1.32771 127.0.0.1.32775 ESTABLISHED tcp 0 0 127.0.0.1.32775 127.0.0.1.32771 ESTABLISHED tcp4 0 0 127.0.0.1.32771 127.0.0.1.32776 ESTABLISHED tcp 0 0 127.0.0.1.32776 127.0.0.1.32771 ESTABLISHED tcp4 0 0 127.0.0.1.32771 127.0.0.1.32777 ESTABLISHED tcp 0 0 127.0.0.1.32777 127.0.0.1.32771 ESTABLISHED tcp4 0 0 127.0.0.1.32771 127.0.0.1.32778 ESTABLISHED tcp 0 0 127.0.0.1.32778 127.0.0.1.32771 ESTABLISHED ''' remotes = set() try: data = subprocess.check_output(['netstat', '-f', 'inet', '-n']) # pylint: disable=minimum-python-version except subprocess.CalledProcessError: log.error('Failed netstat') raise lines = salt.utils.stringutils.to_str(data).split('\n') for line in lines: if 'ESTABLISHED' not in line: continue chunks = line.split() local_host, local_port = chunks[3].rsplit('.', 1) remote_host, remote_port = chunks[4].rsplit('.', 1) if which_end == 'remote_port' and int(remote_port) != port: continue if which_end == 'local_port' and int(local_port) != port: continue remotes.add(remote_host) return remotes @jinja_filter('gen_mac') def gen_mac(prefix='AC:DE:48'): ''' Generates a MAC address with the defined OUI prefix. Common prefixes: - ``00:16:3E`` -- Xen - ``00:18:51`` -- OpenVZ - ``00:50:56`` -- VMware (manually generated) - ``52:54:00`` -- QEMU/KVM - ``AC:DE:48`` -- PRIVATE References: - http://standards.ieee.org/develop/regauth/oui/oui.txt - https://www.wireshark.org/tools/oui-lookup.html - https://en.wikipedia.org/wiki/MAC_address ''' return '{0}:{1:02X}:{2:02X}:{3:02X}'.format(prefix, random.randint(0, 0xff), random.randint(0, 0xff), random.randint(0, 0xff)) @jinja_filter('mac_str_to_bytes') def mac_str_to_bytes(mac_str): ''' Convert a MAC address string into bytes. Works with or without separators: b1 = mac_str_to_bytes('08:00:27:13:69:77') b2 = mac_str_to_bytes('080027136977') assert b1 == b2 assert isinstance(b1, bytes) ''' if len(mac_str) == 12: pass elif len(mac_str) == 17: sep = mac_str[2] mac_str = mac_str.replace(sep, '') else: raise ValueError('Invalid MAC address') chars = (int(mac_str[s:s+2], 16) for s in range(0, 12, 2)) return bytes(chars) if six.PY3 else b''.join(chr(x) for x in chars) def refresh_dns(): ''' issue #21397: force glibc to re-read resolv.conf ''' try: res_init() except NameError: # Exception raised loading the library, thus res_init is not defined pass @jinja_filter('connection_check') def connection_check(addr, port=80, safe=False, ipv6=None): ''' Provides a convenient alias for the dns_check filter. ''' return dns_check(addr, port, safe, ipv6) @jinja_filter('dns_check') def dns_check(addr, port=80, safe=False, ipv6=None, attempt_connect=True): ''' Return the ip resolved by dns, but do not exit on failure, only raise an exception. Obeys system preference for IPv4/6 address resolution - this can be overridden by the ipv6 flag. Tries to connect to the address before considering it useful. If no address can be reached, the first one resolved is used as a fallback. ''' error = False lookup = addr seen_ipv6 = False family = socket.AF_INET6 if ipv6 else socket.AF_INET if ipv6 is False else socket.AF_UNSPEC hostnames = [] try: refresh_dns() hostnames = socket.getaddrinfo(addr, port, family, socket.SOCK_STREAM) except TypeError: err = ('Attempt to resolve address \'{0}\' failed. Invalid or unresolveable address').format(lookup) raise SaltSystemExit(code=42, msg=err) except socket.error: error = True # If ipv6 is set to True, attempt another lookup using the IPv4 family, # just in case we're attempting to lookup an IPv4 IP # as an IPv6 hostname. if error and ipv6: try: refresh_dns() hostnames = socket.getaddrinfo(addr, port, socket.AF_INET, socket.SOCK_STREAM) except TypeError: err = ('Attempt to resolve address \'{0}\' failed. Invalid or unresolveable address').format(lookup) raise SaltSystemExit(code=42, msg=err) except socket.error: error = True try: if not hostnames: error = True else: resolved = False candidates = [] for h in hostnames: # Input is IP address, passed through unchanged, just return it if h[4][0] == addr: resolved = salt.utils.zeromq.ip_bracket(addr) break candidate_addr = salt.utils.zeromq.ip_bracket(h[4][0]) # sometimes /etc/hosts contains ::1 localhost if not ipv6 and candidate_addr == '[::1]': continue candidates.append(candidate_addr) if attempt_connect: try: s = socket.socket(h[0], socket.SOCK_STREAM) s.settimeout(2) s.connect((candidate_addr.strip('[]'), h[4][1])) s.close() resolved = candidate_addr break except socket.error: pass if not resolved: if candidates: resolved = candidates[0] else: error = True except TypeError: err = ('Attempt to resolve address \'{0}\' failed. Invalid or unresolveable address').format(lookup) raise SaltSystemExit(code=42, msg=err) except socket.error: error = True if error: err = ('DNS lookup or connection check of \'{0}\' failed.').format(addr) if safe: if salt.log.is_console_configured(): # If logging is not configured it also means that either # the master or minion instance calling this hasn't even # started running log.error(err) raise SaltClientError() raise SaltSystemExit(code=42, msg=err) return resolved def parse_host_port(host_port): """ Takes a string argument specifying host or host:port. Returns a (hostname, port) or (ip_address, port) tuple. If no port is given, the second (port) element of the returned tuple will be None. host:port argument, for example, is accepted in the forms of: - hostname - hostname:1234 - hostname.domain.tld - hostname.domain.tld:5678 - [1234::5]:5678 - 1234::5 - 10.11.12.13:4567 - 10.11.12.13 """ host, port = None, None # default _s_ = host_port[:] if _s_[0] == "[": if "]" in host_port: host, _s_ = _s_.lstrip("[").rsplit("]", 1) host = ipaddress.IPv6Address(host).compressed if _s_[0] == ":": port = int(_s_.lstrip(":")) else: if len(_s_) > 1: raise ValueError('found ambiguous "{}" port in "{}"'.format(_s_, host_port)) else: if _s_.count(":") == 1: host, _hostport_separator_, port = _s_.partition(":") try: port = int(port) except ValueError as _e_: log.error('host_port "%s" port value "%s" is not an integer.', host_port, port) raise _e_ else: host = _s_ try: if not isinstance(host, ipaddress._BaseAddress): host_ip = ipaddress.ip_address(host).compressed host = host_ip except ValueError: log.debug('"%s" Not an IP address? Assuming it is a hostname.', host) if host != sanitize_host(host): log.error('bad hostname: "%s"', host) raise ValueError('bad hostname: "{}"'.format(host)) return host, port def is_fqdn(hostname): """ Verify if hostname conforms to be a FQDN. :param hostname: text string with the name of the host :return: bool, True if hostname is correct FQDN, False otherwise """ compliant = re.compile(r"(?!-)[A-Z\d\-\_]{1,63}(?<!-)$", re.IGNORECASE) return "." in hostname and len(hostname) < 0xff and all(compliant.match(x) for x in hostname.rstrip(".").split("."))
saltstack/salt
salt/utils/network.py
interface_ip
python
def interface_ip(iface): ''' Return `iface` IPv4 addr or an error if `iface` does not exist ''' iface_info, error = _get_iface_info(iface) if error is False: inet = iface_info.get(iface, {}).get('inet', None) return inet[0].get('address', '') if inet else '' else: return error
Return `iface` IPv4 addr or an error if `iface` does not exist
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/network.py#L1171-L1181
[ "def _get_iface_info(iface):\n '''\n If `iface` is available, return interface info and no error, otherwise\n return no info and log and return an error\n '''\n iface_info = interfaces()\n\n if iface in iface_info.keys():\n return iface_info, False\n else:\n error_msg = ('Interface \"{0}\" not in available interfaces: \"{1}\"'\n ''.format(iface, '\", \"'.join(iface_info.keys())))\n log.error(error_msg)\n return None, error_msg\n" ]
# -*- coding: utf-8 -*- ''' Define some generic socket functions for network modules ''' # Import python libs from __future__ import absolute_import, unicode_literals, print_function import itertools import os import re import types import socket import logging import platform import random import subprocess from string import ascii_letters, digits # Import 3rd-party libs from salt.ext import six from salt.ext.six.moves import range # pylint: disable=import-error,redefined-builtin # Attempt to import wmi try: import wmi import salt.utils.winapi except ImportError: pass # Import salt libs import salt.utils.args import salt.utils.files import salt.utils.path import salt.utils.platform import salt.utils.stringutils import salt.utils.zeromq from salt._compat import ipaddress from salt.exceptions import SaltClientError, SaltSystemExit from salt.utils.decorators.jinja import jinja_filter from salt.utils.versions import LooseVersion # inet_pton does not exist in Windows, this is a workaround if salt.utils.platform.is_windows(): from salt.ext import win_inet_pton # pylint: disable=unused-import log = logging.getLogger(__name__) try: import ctypes import ctypes.util libc = ctypes.cdll.LoadLibrary(ctypes.util.find_library("c")) res_init = libc.__res_init except (ImportError, OSError, AttributeError, TypeError): pass # pylint: disable=C0103 def sanitize_host(host): ''' Sanitize host string. https://tools.ietf.org/html/rfc1123#section-2.1 ''' RFC952_characters = ascii_letters + digits + ".-" return "".join([c for c in host[0:255] if c in RFC952_characters]) def isportopen(host, port): ''' Return status of a port ''' if not 1 <= int(port) <= 65535: return False sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) out = sock.connect_ex((sanitize_host(host), int(port))) return out def host_to_ips(host): ''' Returns a list of IP addresses of a given hostname or None if not found. ''' ips = [] try: for family, socktype, proto, canonname, sockaddr in socket.getaddrinfo( host, 0, socket.AF_UNSPEC, socket.SOCK_STREAM): if family == socket.AF_INET: ip, port = sockaddr elif family == socket.AF_INET6: ip, port, flow_info, scope_id = sockaddr ips.append(ip) if not ips: ips = None except Exception: ips = None return ips def _generate_minion_id(): ''' Get list of possible host names and convention names. :return: ''' # There are three types of hostnames: # 1. Network names. How host is accessed from the network. # 2. Host aliases. They might be not available in all the network or only locally (/etc/hosts) # 3. Convention names, an internal nodename. class DistinctList(list): ''' List, which allows one to append only distinct objects. Needs to work on Python 2.6, because of collections.OrderedDict only since 2.7 version. Override 'filter()' for custom filtering. ''' localhost_matchers = [r'localhost.*', r'ip6-.*', r'127[.]\d', r'0\.0\.0\.0', r'::1.*', r'ipv6-.*', r'fe00::.*', r'fe02::.*', r'1.0.0.*.ip6.arpa'] def append(self, p_object): if p_object and p_object not in self and not self.filter(p_object): super(DistinctList, self).append(p_object) return self def extend(self, iterable): for obj in iterable: self.append(obj) return self def filter(self, element): 'Returns True if element needs to be filtered' for rgx in self.localhost_matchers: if re.match(rgx, element): return True def first(self): return self and self[0] or None hostname = socket.gethostname() hosts = DistinctList().append( salt.utils.stringutils.to_unicode(socket.getfqdn(salt.utils.stringutils.to_bytes(hostname))) ).append(platform.node()).append(hostname) if not hosts: try: for a_nfo in socket.getaddrinfo(hosts.first() or 'localhost', None, socket.AF_INET, socket.SOCK_RAW, socket.IPPROTO_IP, socket.AI_CANONNAME): if len(a_nfo) > 3: hosts.append(a_nfo[3]) except socket.gaierror: log.warning('Cannot resolve address %s info via socket: %s', hosts.first() or 'localhost (N/A)', socket.gaierror) # Universal method for everywhere (Linux, Slowlaris, Windows etc) for f_name in ('/etc/hostname', '/etc/nodename', '/etc/hosts', r'{win}\system32\drivers\etc\hosts'.format(win=os.getenv('WINDIR'))): try: with salt.utils.files.fopen(f_name) as f_hdl: for line in f_hdl: line = salt.utils.stringutils.to_unicode(line) hst = line.strip().split('#')[0].strip().split() if hst: if hst[0][:4] in ('127.', '::1') or len(hst) == 1: hosts.extend(hst) except IOError: pass # include public and private ipaddresses return hosts.extend([addr for addr in ip_addrs() if not ipaddress.ip_address(addr).is_loopback]) def generate_minion_id(): ''' Return only first element of the hostname from all possible list. :return: ''' try: ret = salt.utils.stringutils.to_unicode(_generate_minion_id().first()) except TypeError: ret = None return ret or 'localhost' def get_socket(addr, type=socket.SOCK_STREAM, proto=0): ''' Return a socket object for the addr IP-version agnostic ''' version = ipaddress.ip_address(addr).version if version == 4: family = socket.AF_INET elif version == 6: family = socket.AF_INET6 return socket.socket(family, type, proto) def get_fqhostname(): ''' Returns the fully qualified hostname ''' # try getaddrinfo() fqdn = None try: addrinfo = socket.getaddrinfo( socket.gethostname(), 0, socket.AF_UNSPEC, socket.SOCK_STREAM, socket.SOL_TCP, socket.AI_CANONNAME ) for info in addrinfo: # info struct [family, socktype, proto, canonname, sockaddr] # On Windows `canonname` can be an empty string # This can cause the function to return `None` if len(info) > 3 and info[3]: fqdn = info[3] break except socket.gaierror: pass # NOTE: this used to log.error() but it was later disabled except socket.error as err: log.debug('socket.getaddrinfo() failure while finding fqdn: %s', err) if fqdn is None: fqdn = socket.getfqdn() return fqdn def ip_to_host(ip): ''' Returns the hostname of a given IP ''' try: hostname, aliaslist, ipaddrlist = socket.gethostbyaddr(ip) except Exception as exc: log.debug('salt.utils.network.ip_to_host(%r) failed: %s', ip, exc) hostname = None return hostname # pylint: enable=C0103 def is_reachable_host(entity_name): ''' Returns a bool telling if the entity name is a reachable host (IPv4/IPv6/FQDN/etc). :param hostname: :return: ''' try: assert type(socket.getaddrinfo(entity_name, 0, 0, 0, 0)) == list ret = True except socket.gaierror: ret = False return ret def is_ip(ip): ''' Returns a bool telling if the passed IP is a valid IPv4 or IPv6 address. ''' return is_ipv4(ip) or is_ipv6(ip) def is_ipv4(ip): ''' Returns a bool telling if the value passed to it was a valid IPv4 address ''' try: return ipaddress.ip_address(ip).version == 4 except ValueError: return False def is_ipv6(ip): ''' Returns a bool telling if the value passed to it was a valid IPv6 address ''' try: return ipaddress.ip_address(ip).version == 6 except ValueError: return False def is_subnet(cidr): ''' Returns a bool telling if the passed string is an IPv4 or IPv6 subnet ''' return is_ipv4_subnet(cidr) or is_ipv6_subnet(cidr) def is_ipv4_subnet(cidr): ''' Returns a bool telling if the passed string is an IPv4 subnet ''' try: return '/' in cidr and bool(ipaddress.IPv4Network(cidr)) except Exception: return False def is_ipv6_subnet(cidr): ''' Returns a bool telling if the passed string is an IPv6 subnet ''' try: return '/' in cidr and bool(ipaddress.IPv6Network(cidr)) except Exception: return False @jinja_filter('is_ip') def is_ip_filter(ip, options=None): ''' Returns a bool telling if the passed IP is a valid IPv4 or IPv6 address. ''' return is_ipv4_filter(ip, options=options) or is_ipv6_filter(ip, options=options) def _ip_options_global(ip_obj, version): return not ip_obj.is_private def _ip_options_multicast(ip_obj, version): return ip_obj.is_multicast def _ip_options_loopback(ip_obj, version): return ip_obj.is_loopback def _ip_options_link_local(ip_obj, version): return ip_obj.is_link_local def _ip_options_private(ip_obj, version): return ip_obj.is_private def _ip_options_reserved(ip_obj, version): return ip_obj.is_reserved def _ip_options_site_local(ip_obj, version): if version == 6: return ip_obj.is_site_local return False def _ip_options_unspecified(ip_obj, version): return ip_obj.is_unspecified def _ip_options(ip_obj, version, options=None): # will process and IP options options_fun_map = { 'global': _ip_options_global, 'link-local': _ip_options_link_local, 'linklocal': _ip_options_link_local, 'll': _ip_options_link_local, 'link_local': _ip_options_link_local, 'loopback': _ip_options_loopback, 'lo': _ip_options_loopback, 'multicast': _ip_options_multicast, 'private': _ip_options_private, 'public': _ip_options_global, 'reserved': _ip_options_reserved, 'site-local': _ip_options_site_local, 'sl': _ip_options_site_local, 'site_local': _ip_options_site_local, 'unspecified': _ip_options_unspecified } if not options: return six.text_type(ip_obj) # IP version already checked options_list = [option.strip() for option in options.split(',')] for option, fun in options_fun_map.items(): if option in options_list: fun_res = fun(ip_obj, version) if not fun_res: return None # stop at first failed test # else continue return six.text_type(ip_obj) def _is_ipv(ip, version, options=None): if not version: version = 4 if version not in (4, 6): return None try: ip_obj = ipaddress.ip_address(ip) except ValueError: # maybe it is an IP network try: ip_obj = ipaddress.ip_interface(ip) except ValueError: # nope, still not :( return None if not ip_obj.version == version: return None # has the right version, let's move on return _ip_options(ip_obj, version, options=options) @jinja_filter('is_ipv4') def is_ipv4_filter(ip, options=None): ''' Returns a bool telling if the value passed to it was a valid IPv4 address. ip The IP address. net: False Consider IP addresses followed by netmask. options CSV of options regarding the nature of the IP address. E.g.: loopback, multicast, private etc. ''' _is_ipv4 = _is_ipv(ip, 4, options=options) return isinstance(_is_ipv4, six.string_types) @jinja_filter('is_ipv6') def is_ipv6_filter(ip, options=None): ''' Returns a bool telling if the value passed to it was a valid IPv6 address. ip The IP address. net: False Consider IP addresses followed by netmask. options CSV of options regarding the nature of the IP address. E.g.: loopback, multicast, private etc. ''' _is_ipv6 = _is_ipv(ip, 6, options=options) return isinstance(_is_ipv6, six.string_types) def _ipv_filter(value, version, options=None): if version not in (4, 6): return if isinstance(value, (six.string_types, six.text_type, six.binary_type)): return _is_ipv(value, version, options=options) # calls is_ipv4 or is_ipv6 for `value` elif isinstance(value, (list, tuple, types.GeneratorType)): # calls is_ipv4 or is_ipv6 for each element in the list # os it filters and returns only those elements having the desired IP version return [ _is_ipv(addr, version, options=options) for addr in value if _is_ipv(addr, version, options=options) is not None ] return None @jinja_filter('ipv4') def ipv4(value, options=None): ''' Filters a list and returns IPv4 values only. ''' return _ipv_filter(value, 4, options=options) @jinja_filter('ipv6') def ipv6(value, options=None): ''' Filters a list and returns IPv6 values only. ''' return _ipv_filter(value, 6, options=options) @jinja_filter('ipaddr') def ipaddr(value, options=None): ''' Filters and returns only valid IP objects. ''' ipv4_obj = ipv4(value, options=options) ipv6_obj = ipv6(value, options=options) if ipv4_obj is None or ipv6_obj is None: # an IP address can be either IPv4 either IPv6 # therefofe if the value passed as arg is not a list, at least one of the calls above will return None # if one of them is none, means that we should return only one of them return ipv4_obj or ipv6_obj # one of them else: return ipv4_obj + ipv6_obj # extend lists def _filter_ipaddr(value, options, version=None): ipaddr_filter_out = None if version: if version == 4: ipaddr_filter_out = ipv4(value, options) elif version == 6: ipaddr_filter_out = ipv6(value, options) else: ipaddr_filter_out = ipaddr(value, options) if not ipaddr_filter_out: return if not isinstance(ipaddr_filter_out, (list, tuple, types.GeneratorType)): ipaddr_filter_out = [ipaddr_filter_out] return ipaddr_filter_out @jinja_filter('ip_host') def ip_host(value, options=None, version=None): ''' Returns the interfaces IP address, e.g.: 192.168.0.1/28. ''' ipaddr_filter_out = _filter_ipaddr(value, options=options, version=version) if not ipaddr_filter_out: return if not isinstance(value, (list, tuple, types.GeneratorType)): return six.text_type(ipaddress.ip_interface(ipaddr_filter_out[0])) return [six.text_type(ipaddress.ip_interface(ip_a)) for ip_a in ipaddr_filter_out] def _network_hosts(ip_addr_entry): return [ six.text_type(host) for host in ipaddress.ip_network(ip_addr_entry, strict=False).hosts() ] @jinja_filter('network_hosts') def network_hosts(value, options=None, version=None): ''' Return the list of hosts within a network. .. note:: When running this command with a large IPv6 network, the command will take a long time to gather all of the hosts. ''' ipaddr_filter_out = _filter_ipaddr(value, options=options, version=version) if not ipaddr_filter_out: return if not isinstance(value, (list, tuple, types.GeneratorType)): return _network_hosts(ipaddr_filter_out[0]) return [ _network_hosts(ip_a) for ip_a in ipaddr_filter_out ] def _network_size(ip_addr_entry): return ipaddress.ip_network(ip_addr_entry, strict=False).num_addresses @jinja_filter('network_size') def network_size(value, options=None, version=None): ''' Get the size of a network. ''' ipaddr_filter_out = _filter_ipaddr(value, options=options, version=version) if not ipaddr_filter_out: return if not isinstance(value, (list, tuple, types.GeneratorType)): return _network_size(ipaddr_filter_out[0]) return [ _network_size(ip_a) for ip_a in ipaddr_filter_out ] def natural_ipv4_netmask(ip, fmt='prefixlen'): ''' Returns the "natural" mask of an IPv4 address ''' bits = _ipv4_to_bits(ip) if bits.startswith('11'): mask = '24' elif bits.startswith('1'): mask = '16' else: mask = '8' if fmt == 'netmask': return cidr_to_ipv4_netmask(mask) else: return '/' + mask def rpad_ipv4_network(ip): ''' Returns an IP network address padded with zeros. Ex: '192.168.3' -> '192.168.3.0' '10.209' -> '10.209.0.0' ''' return '.'.join(itertools.islice(itertools.chain(ip.split('.'), '0000'), 0, 4)) def cidr_to_ipv4_netmask(cidr_bits): ''' Returns an IPv4 netmask ''' try: cidr_bits = int(cidr_bits) if not 1 <= cidr_bits <= 32: return '' except ValueError: return '' netmask = '' for idx in range(4): if idx: netmask += '.' if cidr_bits >= 8: netmask += '255' cidr_bits -= 8 else: netmask += '{0:d}'.format(256 - (2 ** (8 - cidr_bits))) cidr_bits = 0 return netmask def _number_of_set_bits_to_ipv4_netmask(set_bits): # pylint: disable=C0103 ''' Returns an IPv4 netmask from the integer representation of that mask. Ex. 0xffffff00 -> '255.255.255.0' ''' return cidr_to_ipv4_netmask(_number_of_set_bits(set_bits)) # pylint: disable=C0103 def _number_of_set_bits(x): ''' Returns the number of bits that are set in a 32bit int ''' # Taken from http://stackoverflow.com/a/4912729. Many thanks! x -= (x >> 1) & 0x55555555 x = ((x >> 2) & 0x33333333) + (x & 0x33333333) x = ((x >> 4) + x) & 0x0f0f0f0f x += x >> 8 x += x >> 16 return x & 0x0000003f # pylint: enable=C0103 def _interfaces_ip(out): ''' Uses ip to return a dictionary of interfaces with various information about each (up/down state, ip address, netmask, and hwaddr) ''' ret = dict() def parse_network(value, cols): ''' Return a tuple of ip, netmask, broadcast based on the current set of cols ''' brd = None scope = None if '/' in value: # we have a CIDR in this address ip, cidr = value.split('/') # pylint: disable=C0103 else: ip = value # pylint: disable=C0103 cidr = 32 if type_ == 'inet': mask = cidr_to_ipv4_netmask(int(cidr)) if 'brd' in cols: brd = cols[cols.index('brd') + 1] elif type_ == 'inet6': mask = cidr if 'scope' in cols: scope = cols[cols.index('scope') + 1] return (ip, mask, brd, scope) groups = re.compile('\r?\n\\d').split(out) for group in groups: iface = None data = dict() for line in group.splitlines(): if ' ' not in line: continue match = re.match(r'^\d*:\s+([\w.\-]+)(?:@)?([\w.\-]+)?:\s+<(.+)>', line) if match: iface, parent, attrs = match.groups() if 'UP' in attrs.split(','): data['up'] = True else: data['up'] = False if parent: data['parent'] = parent continue cols = line.split() if len(cols) >= 2: type_, value = tuple(cols[0:2]) iflabel = cols[-1:][0] if type_ in ('inet', 'inet6'): if 'secondary' not in cols: ipaddr, netmask, broadcast, scope = parse_network(value, cols) if type_ == 'inet': if 'inet' not in data: data['inet'] = list() addr_obj = dict() addr_obj['address'] = ipaddr addr_obj['netmask'] = netmask addr_obj['broadcast'] = broadcast addr_obj['label'] = iflabel data['inet'].append(addr_obj) elif type_ == 'inet6': if 'inet6' not in data: data['inet6'] = list() addr_obj = dict() addr_obj['address'] = ipaddr addr_obj['prefixlen'] = netmask addr_obj['scope'] = scope data['inet6'].append(addr_obj) else: if 'secondary' not in data: data['secondary'] = list() ip_, mask, brd, scp = parse_network(value, cols) data['secondary'].append({ 'type': type_, 'address': ip_, 'netmask': mask, 'broadcast': brd, 'label': iflabel, }) del ip_, mask, brd, scp elif type_.startswith('link'): data['hwaddr'] = value if iface: ret[iface] = data del iface, data return ret def _interfaces_ifconfig(out): ''' Uses ifconfig to return a dictionary of interfaces with various information about each (up/down state, ip address, netmask, and hwaddr) ''' ret = dict() piface = re.compile(r'^([^\s:]+)') pmac = re.compile('.*?(?:HWaddr|ether|address:|lladdr) ([0-9a-fA-F:]+)') if salt.utils.platform.is_sunos(): pip = re.compile(r'.*?(?:inet\s+)([0-9]+\.[0-9]+\.[0-9]+\.[0-9]+)(.*)') pip6 = re.compile('.*?(?:inet6 )([0-9a-fA-F:]+)') pmask6 = re.compile(r'.*?(?:inet6 [0-9a-fA-F:]+/(\d+)).*') else: pip = re.compile(r'.*?(?:inet addr:|inet [^\d]*)(.*?)\s') pip6 = re.compile('.*?(?:inet6 addr: (.*?)/|inet6 )([0-9a-fA-F:]+)') pmask6 = re.compile(r'.*?(?:inet6 addr: [0-9a-fA-F:]+/(\d+)|prefixlen (\d+))(?: Scope:([a-zA-Z]+)| scopeid (0x[0-9a-fA-F]))?') pmask = re.compile(r'.*?(?:Mask:|netmask )(?:((?:0x)?[0-9a-fA-F]{8})|([\d\.]+))') pupdown = re.compile('UP') pbcast = re.compile(r'.*?(?:Bcast:|broadcast )([\d\.]+)') groups = re.compile('\r?\n(?=\\S)').split(out) for group in groups: data = dict() iface = '' updown = False for line in group.splitlines(): miface = piface.match(line) mmac = pmac.match(line) mip = pip.match(line) mip6 = pip6.match(line) mupdown = pupdown.search(line) if miface: iface = miface.group(1) if mmac: data['hwaddr'] = mmac.group(1) if salt.utils.platform.is_sunos(): expand_mac = [] for chunk in data['hwaddr'].split(':'): expand_mac.append('0{0}'.format(chunk) if len(chunk) < 2 else '{0}'.format(chunk)) data['hwaddr'] = ':'.join(expand_mac) if mip: if 'inet' not in data: data['inet'] = list() addr_obj = dict() addr_obj['address'] = mip.group(1) mmask = pmask.match(line) if mmask: if mmask.group(1): mmask = _number_of_set_bits_to_ipv4_netmask( int(mmask.group(1), 16)) else: mmask = mmask.group(2) addr_obj['netmask'] = mmask mbcast = pbcast.match(line) if mbcast: addr_obj['broadcast'] = mbcast.group(1) data['inet'].append(addr_obj) if mupdown: updown = True if mip6: if 'inet6' not in data: data['inet6'] = list() addr_obj = dict() addr_obj['address'] = mip6.group(1) or mip6.group(2) mmask6 = pmask6.match(line) if mmask6: addr_obj['prefixlen'] = mmask6.group(1) or mmask6.group(2) if not salt.utils.platform.is_sunos(): ipv6scope = mmask6.group(3) or mmask6.group(4) addr_obj['scope'] = ipv6scope.lower() if ipv6scope is not None else ipv6scope # SunOS sometimes has ::/0 as inet6 addr when using addrconf if not salt.utils.platform.is_sunos() \ or addr_obj['address'] != '::' \ and addr_obj['prefixlen'] != 0: data['inet6'].append(addr_obj) data['up'] = updown if iface in ret: # SunOS optimization, where interfaces occur twice in 'ifconfig -a' # output with the same name: for ipv4 and then for ipv6 addr family. # Every instance has it's own 'UP' status and we assume that ipv4 # status determines global interface status. # # merge items with higher priority for older values # after that merge the inet and inet6 sub items for both ret[iface] = dict(list(data.items()) + list(ret[iface].items())) if 'inet' in data: ret[iface]['inet'].extend(x for x in data['inet'] if x not in ret[iface]['inet']) if 'inet6' in data: ret[iface]['inet6'].extend(x for x in data['inet6'] if x not in ret[iface]['inet6']) else: ret[iface] = data del data return ret def linux_interfaces(): ''' Obtain interface information for *NIX/BSD variants ''' ifaces = dict() ip_path = salt.utils.path.which('ip') ifconfig_path = None if ip_path else salt.utils.path.which('ifconfig') if ip_path: cmd1 = subprocess.Popen( '{0} link show'.format(ip_path), shell=True, close_fds=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT).communicate()[0] cmd2 = subprocess.Popen( '{0} addr show'.format(ip_path), shell=True, close_fds=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT).communicate()[0] ifaces = _interfaces_ip("{0}\n{1}".format( salt.utils.stringutils.to_str(cmd1), salt.utils.stringutils.to_str(cmd2))) elif ifconfig_path: cmd = subprocess.Popen( '{0} -a'.format(ifconfig_path), shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT).communicate()[0] ifaces = _interfaces_ifconfig(salt.utils.stringutils.to_str(cmd)) return ifaces def _netbsd_interfaces_ifconfig(out): ''' Uses ifconfig to return a dictionary of interfaces with various information about each (up/down state, ip address, netmask, and hwaddr) ''' ret = dict() piface = re.compile(r'^([^\s:]+)') pmac = re.compile('.*?address: ([0-9a-f:]+)') pip = re.compile(r'.*?inet [^\d]*(.*?)/([\d]*)\s') pip6 = re.compile(r'.*?inet6 ([0-9a-f:]+)%([a-zA-Z0-9]*)/([\d]*)\s') pupdown = re.compile('UP') pbcast = re.compile(r'.*?broadcast ([\d\.]+)') groups = re.compile('\r?\n(?=\\S)').split(out) for group in groups: data = dict() iface = '' updown = False for line in group.splitlines(): miface = piface.match(line) mmac = pmac.match(line) mip = pip.match(line) mip6 = pip6.match(line) mupdown = pupdown.search(line) if miface: iface = miface.group(1) if mmac: data['hwaddr'] = mmac.group(1) if mip: if 'inet' not in data: data['inet'] = list() addr_obj = dict() addr_obj['address'] = mip.group(1) mmask = mip.group(2) if mip.group(2): addr_obj['netmask'] = cidr_to_ipv4_netmask(mip.group(2)) mbcast = pbcast.match(line) if mbcast: addr_obj['broadcast'] = mbcast.group(1) data['inet'].append(addr_obj) if mupdown: updown = True if mip6: if 'inet6' not in data: data['inet6'] = list() addr_obj = dict() addr_obj['address'] = mip6.group(1) mmask6 = mip6.group(3) addr_obj['scope'] = mip6.group(2) addr_obj['prefixlen'] = mip6.group(3) data['inet6'].append(addr_obj) data['up'] = updown ret[iface] = data del data return ret def netbsd_interfaces(): ''' Obtain interface information for NetBSD >= 8 where the ifconfig output diverged from other BSD variants (Netmask is now part of the address) ''' # NetBSD versions prior to 8.0 can still use linux_interfaces() if LooseVersion(os.uname()[2]) < LooseVersion('8.0'): return linux_interfaces() ifconfig_path = salt.utils.path.which('ifconfig') cmd = subprocess.Popen( '{0} -a'.format(ifconfig_path), shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT).communicate()[0] return _netbsd_interfaces_ifconfig(salt.utils.stringutils.to_str(cmd)) def _interfaces_ipconfig(out): ''' Returns a dictionary of interfaces with various information about each (up/down state, ip address, netmask, and hwaddr) NOTE: This is not used by any function and may be able to be removed in the future. ''' ifaces = dict() iface = None adapter_iface_regex = re.compile(r'adapter (\S.+):$') for line in out.splitlines(): if not line: continue # TODO what does Windows call Infiniband and 10/40gige adapters if line.startswith('Ethernet'): iface = ifaces[adapter_iface_regex.search(line).group(1)] iface['up'] = True addr = None continue if iface: key, val = line.split(',', 1) key = key.strip(' .') val = val.strip() if addr and key == 'Subnet Mask': addr['netmask'] = val elif key in ('IP Address', 'IPv4 Address'): if 'inet' not in iface: iface['inet'] = list() addr = {'address': val.rstrip('(Preferred)'), 'netmask': None, 'broadcast': None} # TODO find the broadcast iface['inet'].append(addr) elif 'IPv6 Address' in key: if 'inet6' not in iface: iface['inet'] = list() # XXX What is the prefixlen!? addr = {'address': val.rstrip('(Preferred)'), 'prefixlen': None} iface['inet6'].append(addr) elif key == 'Physical Address': iface['hwaddr'] = val elif key == 'Media State': # XXX seen used for tunnel adaptors # might be useful iface['up'] = (val != 'Media disconnected') def win_interfaces(): ''' Obtain interface information for Windows systems ''' with salt.utils.winapi.Com(): c = wmi.WMI() ifaces = {} for iface in c.Win32_NetworkAdapterConfiguration(IPEnabled=1): ifaces[iface.Description] = dict() if iface.MACAddress: ifaces[iface.Description]['hwaddr'] = iface.MACAddress if iface.IPEnabled: ifaces[iface.Description]['up'] = True for ip in iface.IPAddress: if '.' in ip: if 'inet' not in ifaces[iface.Description]: ifaces[iface.Description]['inet'] = [] item = {'address': ip, 'label': iface.Description} if iface.DefaultIPGateway: broadcast = next((i for i in iface.DefaultIPGateway if '.' in i), '') if broadcast: item['broadcast'] = broadcast if iface.IPSubnet: netmask = next((i for i in iface.IPSubnet if '.' in i), '') if netmask: item['netmask'] = netmask ifaces[iface.Description]['inet'].append(item) if ':' in ip: if 'inet6' not in ifaces[iface.Description]: ifaces[iface.Description]['inet6'] = [] item = {'address': ip} if iface.DefaultIPGateway: broadcast = next((i for i in iface.DefaultIPGateway if ':' in i), '') if broadcast: item['broadcast'] = broadcast if iface.IPSubnet: netmask = next((i for i in iface.IPSubnet if ':' in i), '') if netmask: item['netmask'] = netmask ifaces[iface.Description]['inet6'].append(item) else: ifaces[iface.Description]['up'] = False return ifaces def interfaces(): ''' Return a dictionary of information about all the interfaces on the minion ''' if salt.utils.platform.is_windows(): return win_interfaces() elif salt.utils.platform.is_netbsd(): return netbsd_interfaces() else: return linux_interfaces() def get_net_start(ipaddr, netmask): ''' Return the address of the network ''' net = ipaddress.ip_network('{0}/{1}'.format(ipaddr, netmask), strict=False) return six.text_type(net.network_address) def get_net_size(mask): ''' Turns an IPv4 netmask into it's corresponding prefix length (255.255.255.0 -> 24 as in 192.168.1.10/24). ''' binary_str = '' for octet in mask.split('.'): binary_str += bin(int(octet))[2:].zfill(8) return len(binary_str.rstrip('0')) def calc_net(ipaddr, netmask=None): ''' Takes IP (CIDR notation supported) and optionally netmask and returns the network in CIDR-notation. (The IP can be any IP inside the subnet) ''' if netmask is not None: ipaddr = '{0}/{1}'.format(ipaddr, netmask) return six.text_type(ipaddress.ip_network(ipaddr, strict=False)) def _ipv4_to_bits(ipaddr): ''' Accepts an IPv4 dotted quad and returns a string representing its binary counterpart ''' return ''.join([bin(int(x))[2:].rjust(8, '0') for x in ipaddr.split('.')]) def _get_iface_info(iface): ''' If `iface` is available, return interface info and no error, otherwise return no info and log and return an error ''' iface_info = interfaces() if iface in iface_info.keys(): return iface_info, False else: error_msg = ('Interface "{0}" not in available interfaces: "{1}"' ''.format(iface, '", "'.join(iface_info.keys()))) log.error(error_msg) return None, error_msg def _hw_addr_aix(iface): ''' Return the hardware address (a.k.a. MAC address) for a given interface on AIX MAC address not available in through interfaces ''' cmd = subprocess.Popen( 'entstat -d {0} | grep \'Hardware Address\''.format(iface), shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT).communicate()[0] if cmd: comps = cmd.split(' ') if len(comps) == 3: mac_addr = comps[2].strip('\'').strip() return mac_addr error_msg = ('Interface "{0}" either not available or does not contain a hardware address'.format(iface)) log.error(error_msg) return error_msg def hw_addr(iface): ''' Return the hardware address (a.k.a. MAC address) for a given interface .. versionchanged:: 2016.11.4 Added support for AIX ''' if salt.utils.platform.is_aix(): return _hw_addr_aix iface_info, error = _get_iface_info(iface) if error is False: return iface_info.get(iface, {}).get('hwaddr', '') else: return error def interface(iface): ''' Return the details of `iface` or an error if it does not exist ''' iface_info, error = _get_iface_info(iface) if error is False: return iface_info.get(iface, {}).get('inet', '') else: return error def _subnets(proto='inet', interfaces_=None): ''' Returns a list of subnets to which the host belongs ''' if interfaces_ is None: ifaces = interfaces() elif isinstance(interfaces_, list): ifaces = {} for key, value in six.iteritems(interfaces()): if key in interfaces_: ifaces[key] = value else: ifaces = {interfaces_: interfaces().get(interfaces_, {})} ret = set() if proto == 'inet': subnet = 'netmask' dflt_cidr = 32 elif proto == 'inet6': subnet = 'prefixlen' dflt_cidr = 128 else: log.error('Invalid proto %s calling subnets()', proto) return for ip_info in six.itervalues(ifaces): addrs = ip_info.get(proto, []) addrs.extend([addr for addr in ip_info.get('secondary', []) if addr.get('type') == proto]) for intf in addrs: if subnet in intf: intf = ipaddress.ip_interface('{0}/{1}'.format(intf['address'], intf[subnet])) else: intf = ipaddress.ip_interface('{0}/{1}'.format(intf['address'], dflt_cidr)) if not intf.is_loopback: ret.add(intf.network) return [six.text_type(net) for net in sorted(ret)] def subnets(interfaces=None): ''' Returns a list of IPv4 subnets to which the host belongs ''' return _subnets('inet', interfaces_=interfaces) def subnets6(): ''' Returns a list of IPv6 subnets to which the host belongs ''' return _subnets('inet6') def in_subnet(cidr, addr=None): ''' Returns True if host or (any of) addrs is within specified subnet, otherwise False ''' try: cidr = ipaddress.ip_network(cidr) except ValueError: log.error('Invalid CIDR \'%s\'', cidr) return False if addr is None: addr = ip_addrs() addr.extend(ip_addrs6()) elif not isinstance(addr, (list, tuple)): addr = (addr,) return any(ipaddress.ip_address(item) in cidr for item in addr) def _ip_addrs(interface=None, include_loopback=False, interface_data=None, proto='inet'): ''' Return the full list of IP adresses matching the criteria proto = inet|inet6 ''' ret = set() ifaces = interface_data \ if isinstance(interface_data, dict) \ else interfaces() if interface is None: target_ifaces = ifaces else: target_ifaces = dict([(k, v) for k, v in six.iteritems(ifaces) if k == interface]) if not target_ifaces: log.error('Interface %s not found.', interface) for ip_info in six.itervalues(target_ifaces): addrs = ip_info.get(proto, []) addrs.extend([addr for addr in ip_info.get('secondary', []) if addr.get('type') == proto]) for addr in addrs: addr = ipaddress.ip_address(addr.get('address')) if not addr.is_loopback or include_loopback: ret.add(addr) return [six.text_type(addr) for addr in sorted(ret)] def ip_addrs(interface=None, include_loopback=False, interface_data=None): ''' Returns a list of IPv4 addresses assigned to the host. 127.0.0.1 is ignored, unless 'include_loopback=True' is indicated. If 'interface' is provided, then only IP addresses from that interface will be returned. ''' return _ip_addrs(interface, include_loopback, interface_data, 'inet') def ip_addrs6(interface=None, include_loopback=False, interface_data=None): ''' Returns a list of IPv6 addresses assigned to the host. ::1 is ignored, unless 'include_loopback=True' is indicated. If 'interface' is provided, then only IP addresses from that interface will be returned. ''' return _ip_addrs(interface, include_loopback, interface_data, 'inet6') def hex2ip(hex_ip, invert=False): ''' Convert a hex string to an ip, if a failure occurs the original hex is returned. If 'invert=True' assume that ip from /proc/net/<proto> ''' if len(hex_ip) == 32: # ipv6 ip = [] for i in range(0, 32, 8): ip_part = hex_ip[i:i + 8] ip_part = [ip_part[x:x + 2] for x in range(0, 8, 2)] if invert: ip.append("{0[3]}{0[2]}:{0[1]}{0[0]}".format(ip_part)) else: ip.append("{0[0]}{0[1]}:{0[2]}{0[3]}".format(ip_part)) try: address = ipaddress.IPv6Address(":".join(ip)) if address.ipv4_mapped: return str(address.ipv4_mapped) else: return address.compressed except ipaddress.AddressValueError as ex: log.error('hex2ip - ipv6 address error: %s', ex) return hex_ip try: hip = int(hex_ip, 16) except ValueError: return hex_ip if invert: return '{3}.{2}.{1}.{0}'.format(hip >> 24 & 255, hip >> 16 & 255, hip >> 8 & 255, hip & 255) return '{0}.{1}.{2}.{3}'.format(hip >> 24 & 255, hip >> 16 & 255, hip >> 8 & 255, hip & 255) def mac2eui64(mac, prefix=None): ''' Convert a MAC address to a EUI64 identifier or, with prefix provided, a full IPv6 address ''' # http://tools.ietf.org/html/rfc4291#section-2.5.1 eui64 = re.sub(r'[.:-]', '', mac).lower() eui64 = eui64[0:6] + 'fffe' + eui64[6:] eui64 = hex(int(eui64[0:2], 16) | 2)[2:].zfill(2) + eui64[2:] if prefix is None: return ':'.join(re.findall(r'.{4}', eui64)) else: try: net = ipaddress.ip_network(prefix, strict=False) euil = int('0x{0}'.format(eui64), 16) return '{0}/{1}'.format(net[euil], net.prefixlen) except Exception: return def active_tcp(): ''' Return a dict describing all active tcp connections as quickly as possible ''' ret = {} for statf in ['/proc/net/tcp', '/proc/net/tcp6']: if os.path.isfile(statf): with salt.utils.files.fopen(statf, 'rb') as fp_: for line in fp_: line = salt.utils.stringutils.to_unicode(line) if line.strip().startswith('sl'): continue iret = _parse_tcp_line(line) sl = next(iter(iret)) if iret[sl]['state'] == 1: # 1 is ESTABLISHED del iret[sl]['state'] ret[len(ret)] = iret[sl] return ret def local_port_tcp(port): ''' Return a set of remote ip addrs attached to the specified local port ''' ret = _remotes_on(port, 'local_port') return ret def remote_port_tcp(port): ''' Return a set of ip addrs the current host is connected to on given port ''' ret = _remotes_on(port, 'remote_port') return ret def _remotes_on(port, which_end): ''' Return a set of ip addrs active tcp connections ''' port = int(port) ret = _netlink_tool_remote_on(port, which_end) if ret is not None: return ret ret = set() proc_available = False for statf in ['/proc/net/tcp', '/proc/net/tcp6']: if os.path.isfile(statf): proc_available = True with salt.utils.files.fopen(statf, 'r') as fp_: for line in fp_: line = salt.utils.stringutils.to_unicode(line) if line.strip().startswith('sl'): continue iret = _parse_tcp_line(line) sl = next(iter(iret)) if iret[sl][which_end] == port and iret[sl]['state'] == 1: # 1 is ESTABLISHED ret.add(iret[sl]['remote_addr']) if not proc_available: # Fallback to use OS specific tools if salt.utils.platform.is_sunos(): return _sunos_remotes_on(port, which_end) if salt.utils.platform.is_freebsd(): return _freebsd_remotes_on(port, which_end) if salt.utils.platform.is_netbsd(): return _netbsd_remotes_on(port, which_end) if salt.utils.platform.is_openbsd(): return _openbsd_remotes_on(port, which_end) if salt.utils.platform.is_windows(): return _windows_remotes_on(port, which_end) if salt.utils.platform.is_aix(): return _aix_remotes_on(port, which_end) return _linux_remotes_on(port, which_end) return ret def _parse_tcp_line(line): ''' Parse a single line from the contents of /proc/net/tcp or /proc/net/tcp6 ''' ret = {} comps = line.strip().split() sl = comps[0].rstrip(':') ret[sl] = {} l_addr, l_port = comps[1].split(':') r_addr, r_port = comps[2].split(':') ret[sl]['local_addr'] = hex2ip(l_addr, True) ret[sl]['local_port'] = int(l_port, 16) ret[sl]['remote_addr'] = hex2ip(r_addr, True) ret[sl]['remote_port'] = int(r_port, 16) ret[sl]['state'] = int(comps[3], 16) return ret def _netlink_tool_remote_on(port, which_end): ''' Returns set of ipv4 host addresses of remote established connections on local or remote tcp port. Parses output of shell 'ss' to get connections [root@salt-master ~]# ss -ant State Recv-Q Send-Q Local Address:Port Peer Address:Port LISTEN 0 511 *:80 *:* LISTEN 0 128 *:22 *:* ESTAB 0 0 127.0.0.1:56726 127.0.0.1:4505 ''' remotes = set() valid = False try: data = subprocess.check_output(['ss', '-ant']) # pylint: disable=minimum-python-version except subprocess.CalledProcessError: log.error('Failed ss') raise except OSError: # not command "No such file or directory" return None lines = salt.utils.stringutils.to_str(data).split('\n') for line in lines: if 'Address:Port' in line: # ss tools may not be valid valid = True continue elif 'ESTAB' not in line: continue chunks = line.split() local_host, local_port = chunks[3].split(':', 1) remote_host, remote_port = chunks[4].split(':', 1) if which_end == 'remote_port' and int(remote_port) != port: continue if which_end == 'local_port' and int(local_port) != port: continue remotes.add(remote_host) if valid is False: remotes = None return remotes def _sunos_remotes_on(port, which_end): ''' SunOS specific helper function. Returns set of ipv4 host addresses of remote established connections on local or remote tcp port. Parses output of shell 'netstat' to get connections [root@salt-master ~]# netstat -f inet -n TCP: IPv4 Local Address Remote Address Swind Send-Q Rwind Recv-Q State -------------------- -------------------- ----- ------ ----- ------ ----------- 10.0.0.101.4505 10.0.0.1.45329 1064800 0 1055864 0 ESTABLISHED 10.0.0.101.4505 10.0.0.100.50798 1064800 0 1055864 0 ESTABLISHED ''' remotes = set() try: data = subprocess.check_output(['netstat', '-f', 'inet', '-n']) # pylint: disable=minimum-python-version except subprocess.CalledProcessError: log.error('Failed netstat') raise lines = salt.utils.stringutils.to_str(data).split('\n') for line in lines: if 'ESTABLISHED' not in line: continue chunks = line.split() local_host, local_port = chunks[0].rsplit('.', 1) remote_host, remote_port = chunks[1].rsplit('.', 1) if which_end == 'remote_port' and int(remote_port) != port: continue if which_end == 'local_port' and int(local_port) != port: continue remotes.add(remote_host) return remotes def _freebsd_remotes_on(port, which_end): ''' Returns set of ipv4 host addresses of remote established connections on local tcp port port. Parses output of shell 'sockstat' (FreeBSD) to get connections $ sudo sockstat -4 USER COMMAND PID FD PROTO LOCAL ADDRESS FOREIGN ADDRESS root python2.7 1456 29 tcp4 *:4505 *:* root python2.7 1445 17 tcp4 *:4506 *:* root python2.7 1294 14 tcp4 127.0.0.1:11813 127.0.0.1:4505 root python2.7 1294 41 tcp4 127.0.0.1:61115 127.0.0.1:4506 $ sudo sockstat -4 -c -p 4506 USER COMMAND PID FD PROTO LOCAL ADDRESS FOREIGN ADDRESS root python2.7 1294 41 tcp4 127.0.0.1:61115 127.0.0.1:4506 ''' port = int(port) remotes = set() try: cmd = salt.utils.args.shlex_split('sockstat -4 -c -p {0}'.format(port)) data = subprocess.check_output(cmd) # pylint: disable=minimum-python-version except subprocess.CalledProcessError as ex: log.error('Failed "sockstat" with returncode = %s', ex.returncode) raise lines = salt.utils.stringutils.to_str(data).split('\n') for line in lines: chunks = line.split() if not chunks: continue # ['root', 'python2.7', '1456', '37', 'tcp4', # '127.0.0.1:4505-', '127.0.0.1:55703'] # print chunks if 'COMMAND' in chunks[1]: continue # ignore header if len(chunks) < 2: continue # sockstat -4 -c -p 4506 does this with high PIDs: # USER COMMAND PID FD PROTO LOCAL ADDRESS FOREIGN ADDRESS # salt-master python2.781106 35 tcp4 192.168.12.34:4506 192.168.12.45:60143 local = chunks[-2] remote = chunks[-1] lhost, lport = local.split(':') rhost, rport = remote.split(':') if which_end == 'local' and int(lport) != port: # ignore if local port not port continue if which_end == 'remote' and int(rport) != port: # ignore if remote port not port continue remotes.add(rhost) return remotes def _netbsd_remotes_on(port, which_end): ''' Returns set of ipv4 host addresses of remote established connections on local tcp port port. Parses output of shell 'sockstat' (NetBSD) to get connections $ sudo sockstat -4 -n USER COMMAND PID FD PROTO LOCAL ADDRESS FOREIGN ADDRESS root python2.7 1456 29 tcp *.4505 *.* root python2.7 1445 17 tcp *.4506 *.* root python2.7 1294 14 tcp 127.0.0.1.11813 127.0.0.1.4505 root python2.7 1294 41 tcp 127.0.0.1.61115 127.0.0.1.4506 $ sudo sockstat -4 -c -n -p 4506 USER COMMAND PID FD PROTO LOCAL ADDRESS FOREIGN ADDRESS root python2.7 1294 41 tcp 127.0.0.1.61115 127.0.0.1.4506 ''' port = int(port) remotes = set() try: cmd = salt.utils.args.shlex_split('sockstat -4 -c -n -p {0}'.format(port)) data = subprocess.check_output(cmd) # pylint: disable=minimum-python-version except subprocess.CalledProcessError as ex: log.error('Failed "sockstat" with returncode = %s', ex.returncode) raise lines = salt.utils.stringutils.to_str(data).split('\n') for line in lines: chunks = line.split() if not chunks: continue # ['root', 'python2.7', '1456', '37', 'tcp', # '127.0.0.1.4505-', '127.0.0.1.55703'] # print chunks if 'COMMAND' in chunks[1]: continue # ignore header if len(chunks) < 2: continue local = chunks[5].split('.') lport = local.pop() lhost = '.'.join(local) remote = chunks[6].split('.') rport = remote.pop() rhost = '.'.join(remote) if which_end == 'local' and int(lport) != port: # ignore if local port not port continue if which_end == 'remote' and int(rport) != port: # ignore if remote port not port continue remotes.add(rhost) return remotes def _openbsd_remotes_on(port, which_end): ''' OpenBSD specific helper function. Returns set of ipv4 host addresses of remote established connections on local or remote tcp port. Parses output of shell 'netstat' to get connections $ netstat -nf inet Active Internet connections Proto Recv-Q Send-Q Local Address Foreign Address (state) tcp 0 0 10.0.0.101.4505 10.0.0.1.45329 ESTABLISHED tcp 0 0 10.0.0.101.4505 10.0.0.100.50798 ESTABLISHED ''' remotes = set() try: data = subprocess.check_output(['netstat', '-nf', 'inet']) # pylint: disable=minimum-python-version except subprocess.CalledProcessError: log.error('Failed netstat') raise lines = data.split('\n') for line in lines: if 'ESTABLISHED' not in line: continue chunks = line.split() local_host, local_port = chunks[3].rsplit('.', 1) remote_host, remote_port = chunks[4].rsplit('.', 1) if which_end == 'remote_port' and int(remote_port) != port: continue if which_end == 'local_port' and int(local_port) != port: continue remotes.add(remote_host) return remotes def _windows_remotes_on(port, which_end): r''' Windows specific helper function. Returns set of ipv4 host addresses of remote established connections on local or remote tcp port. Parses output of shell 'netstat' to get connections C:\>netstat -n Active Connections Proto Local Address Foreign Address State TCP 10.2.33.17:3007 130.164.12.233:10123 ESTABLISHED TCP 10.2.33.17:3389 130.164.30.5:10378 ESTABLISHED ''' remotes = set() try: data = subprocess.check_output(['netstat', '-n']) # pylint: disable=minimum-python-version except subprocess.CalledProcessError: log.error('Failed netstat') raise lines = salt.utils.stringutils.to_str(data).split('\n') for line in lines: if 'ESTABLISHED' not in line: continue chunks = line.split() local_host, local_port = chunks[1].rsplit(':', 1) remote_host, remote_port = chunks[2].rsplit(':', 1) if which_end == 'remote_port' and int(remote_port) != port: continue if which_end == 'local_port' and int(local_port) != port: continue remotes.add(remote_host) return remotes def _linux_remotes_on(port, which_end): ''' Linux specific helper function. Returns set of ip host addresses of remote established connections on local tcp port port. Parses output of shell 'lsof' to get connections $ sudo lsof -iTCP:4505 -n COMMAND PID USER FD TYPE DEVICE SIZE/OFF NODE NAME Python 9971 root 35u IPv4 0x18a8464a29ca329d 0t0 TCP *:4505 (LISTEN) Python 9971 root 37u IPv4 0x18a8464a29b2b29d 0t0 TCP 127.0.0.1:4505->127.0.0.1:55703 (ESTABLISHED) Python 10152 root 22u IPv4 0x18a8464a29c8cab5 0t0 TCP 127.0.0.1:55703->127.0.0.1:4505 (ESTABLISHED) Python 10153 root 22u IPv4 0x18a8464a29c8cab5 0t0 TCP [fe80::249a]:4505->[fe80::150]:59367 (ESTABLISHED) ''' remotes = set() try: data = subprocess.check_output( ['lsof', '-iTCP:{0:d}'.format(port), '-n', '-P'] # pylint: disable=minimum-python-version ) except subprocess.CalledProcessError as ex: if ex.returncode == 1: # Lsof return 1 if any error was detected, including the failure # to locate Internet addresses, and it is not an error in this case. log.warning('"lsof" returncode = 1, likely no active TCP sessions.') return remotes log.error('Failed "lsof" with returncode = %s', ex.returncode) raise lines = salt.utils.stringutils.to_str(data).split('\n') for line in lines: chunks = line.split() if not chunks: continue # ['Python', '9971', 'root', '37u', 'IPv4', '0x18a8464a29b2b29d', '0t0', # 'TCP', '127.0.0.1:4505->127.0.0.1:55703', '(ESTABLISHED)'] # print chunks if 'COMMAND' in chunks[0]: continue # ignore header if 'ESTABLISHED' not in chunks[-1]: continue # ignore if not ESTABLISHED # '127.0.0.1:4505->127.0.0.1:55703' local, remote = chunks[8].split('->') _, lport = local.rsplit(':', 1) rhost, rport = remote.rsplit(':', 1) if which_end == 'remote_port' and int(rport) != port: continue if which_end == 'local_port' and int(lport) != port: continue remotes.add(rhost.strip("[]")) return remotes def _aix_remotes_on(port, which_end): ''' AIX specific helper function. Returns set of ipv4 host addresses of remote established connections on local or remote tcp port. Parses output of shell 'netstat' to get connections root@la68pp002_pub:/opt/salt/lib/python2.7/site-packages/salt/modules# netstat -f inet -n Active Internet connections Proto Recv-Q Send-Q Local Address Foreign Address (state) tcp4 0 0 172.29.149.95.50093 209.41.78.13.4505 ESTABLISHED tcp4 0 0 127.0.0.1.9514 *.* LISTEN tcp4 0 0 127.0.0.1.9515 *.* LISTEN tcp4 0 0 127.0.0.1.199 127.0.0.1.32779 ESTABLISHED tcp4 0 0 127.0.0.1.32779 127.0.0.1.199 ESTABLISHED tcp4 0 40 172.29.149.95.22 172.29.96.83.41022 ESTABLISHED tcp4 0 0 172.29.149.95.22 172.29.96.83.41032 ESTABLISHED tcp4 0 0 127.0.0.1.32771 127.0.0.1.32775 ESTABLISHED tcp 0 0 127.0.0.1.32775 127.0.0.1.32771 ESTABLISHED tcp4 0 0 127.0.0.1.32771 127.0.0.1.32776 ESTABLISHED tcp 0 0 127.0.0.1.32776 127.0.0.1.32771 ESTABLISHED tcp4 0 0 127.0.0.1.32771 127.0.0.1.32777 ESTABLISHED tcp 0 0 127.0.0.1.32777 127.0.0.1.32771 ESTABLISHED tcp4 0 0 127.0.0.1.32771 127.0.0.1.32778 ESTABLISHED tcp 0 0 127.0.0.1.32778 127.0.0.1.32771 ESTABLISHED ''' remotes = set() try: data = subprocess.check_output(['netstat', '-f', 'inet', '-n']) # pylint: disable=minimum-python-version except subprocess.CalledProcessError: log.error('Failed netstat') raise lines = salt.utils.stringutils.to_str(data).split('\n') for line in lines: if 'ESTABLISHED' not in line: continue chunks = line.split() local_host, local_port = chunks[3].rsplit('.', 1) remote_host, remote_port = chunks[4].rsplit('.', 1) if which_end == 'remote_port' and int(remote_port) != port: continue if which_end == 'local_port' and int(local_port) != port: continue remotes.add(remote_host) return remotes @jinja_filter('gen_mac') def gen_mac(prefix='AC:DE:48'): ''' Generates a MAC address with the defined OUI prefix. Common prefixes: - ``00:16:3E`` -- Xen - ``00:18:51`` -- OpenVZ - ``00:50:56`` -- VMware (manually generated) - ``52:54:00`` -- QEMU/KVM - ``AC:DE:48`` -- PRIVATE References: - http://standards.ieee.org/develop/regauth/oui/oui.txt - https://www.wireshark.org/tools/oui-lookup.html - https://en.wikipedia.org/wiki/MAC_address ''' return '{0}:{1:02X}:{2:02X}:{3:02X}'.format(prefix, random.randint(0, 0xff), random.randint(0, 0xff), random.randint(0, 0xff)) @jinja_filter('mac_str_to_bytes') def mac_str_to_bytes(mac_str): ''' Convert a MAC address string into bytes. Works with or without separators: b1 = mac_str_to_bytes('08:00:27:13:69:77') b2 = mac_str_to_bytes('080027136977') assert b1 == b2 assert isinstance(b1, bytes) ''' if len(mac_str) == 12: pass elif len(mac_str) == 17: sep = mac_str[2] mac_str = mac_str.replace(sep, '') else: raise ValueError('Invalid MAC address') chars = (int(mac_str[s:s+2], 16) for s in range(0, 12, 2)) return bytes(chars) if six.PY3 else b''.join(chr(x) for x in chars) def refresh_dns(): ''' issue #21397: force glibc to re-read resolv.conf ''' try: res_init() except NameError: # Exception raised loading the library, thus res_init is not defined pass @jinja_filter('connection_check') def connection_check(addr, port=80, safe=False, ipv6=None): ''' Provides a convenient alias for the dns_check filter. ''' return dns_check(addr, port, safe, ipv6) @jinja_filter('dns_check') def dns_check(addr, port=80, safe=False, ipv6=None, attempt_connect=True): ''' Return the ip resolved by dns, but do not exit on failure, only raise an exception. Obeys system preference for IPv4/6 address resolution - this can be overridden by the ipv6 flag. Tries to connect to the address before considering it useful. If no address can be reached, the first one resolved is used as a fallback. ''' error = False lookup = addr seen_ipv6 = False family = socket.AF_INET6 if ipv6 else socket.AF_INET if ipv6 is False else socket.AF_UNSPEC hostnames = [] try: refresh_dns() hostnames = socket.getaddrinfo(addr, port, family, socket.SOCK_STREAM) except TypeError: err = ('Attempt to resolve address \'{0}\' failed. Invalid or unresolveable address').format(lookup) raise SaltSystemExit(code=42, msg=err) except socket.error: error = True # If ipv6 is set to True, attempt another lookup using the IPv4 family, # just in case we're attempting to lookup an IPv4 IP # as an IPv6 hostname. if error and ipv6: try: refresh_dns() hostnames = socket.getaddrinfo(addr, port, socket.AF_INET, socket.SOCK_STREAM) except TypeError: err = ('Attempt to resolve address \'{0}\' failed. Invalid or unresolveable address').format(lookup) raise SaltSystemExit(code=42, msg=err) except socket.error: error = True try: if not hostnames: error = True else: resolved = False candidates = [] for h in hostnames: # Input is IP address, passed through unchanged, just return it if h[4][0] == addr: resolved = salt.utils.zeromq.ip_bracket(addr) break candidate_addr = salt.utils.zeromq.ip_bracket(h[4][0]) # sometimes /etc/hosts contains ::1 localhost if not ipv6 and candidate_addr == '[::1]': continue candidates.append(candidate_addr) if attempt_connect: try: s = socket.socket(h[0], socket.SOCK_STREAM) s.settimeout(2) s.connect((candidate_addr.strip('[]'), h[4][1])) s.close() resolved = candidate_addr break except socket.error: pass if not resolved: if candidates: resolved = candidates[0] else: error = True except TypeError: err = ('Attempt to resolve address \'{0}\' failed. Invalid or unresolveable address').format(lookup) raise SaltSystemExit(code=42, msg=err) except socket.error: error = True if error: err = ('DNS lookup or connection check of \'{0}\' failed.').format(addr) if safe: if salt.log.is_console_configured(): # If logging is not configured it also means that either # the master or minion instance calling this hasn't even # started running log.error(err) raise SaltClientError() raise SaltSystemExit(code=42, msg=err) return resolved def parse_host_port(host_port): """ Takes a string argument specifying host or host:port. Returns a (hostname, port) or (ip_address, port) tuple. If no port is given, the second (port) element of the returned tuple will be None. host:port argument, for example, is accepted in the forms of: - hostname - hostname:1234 - hostname.domain.tld - hostname.domain.tld:5678 - [1234::5]:5678 - 1234::5 - 10.11.12.13:4567 - 10.11.12.13 """ host, port = None, None # default _s_ = host_port[:] if _s_[0] == "[": if "]" in host_port: host, _s_ = _s_.lstrip("[").rsplit("]", 1) host = ipaddress.IPv6Address(host).compressed if _s_[0] == ":": port = int(_s_.lstrip(":")) else: if len(_s_) > 1: raise ValueError('found ambiguous "{}" port in "{}"'.format(_s_, host_port)) else: if _s_.count(":") == 1: host, _hostport_separator_, port = _s_.partition(":") try: port = int(port) except ValueError as _e_: log.error('host_port "%s" port value "%s" is not an integer.', host_port, port) raise _e_ else: host = _s_ try: if not isinstance(host, ipaddress._BaseAddress): host_ip = ipaddress.ip_address(host).compressed host = host_ip except ValueError: log.debug('"%s" Not an IP address? Assuming it is a hostname.', host) if host != sanitize_host(host): log.error('bad hostname: "%s"', host) raise ValueError('bad hostname: "{}"'.format(host)) return host, port def is_fqdn(hostname): """ Verify if hostname conforms to be a FQDN. :param hostname: text string with the name of the host :return: bool, True if hostname is correct FQDN, False otherwise """ compliant = re.compile(r"(?!-)[A-Z\d\-\_]{1,63}(?<!-)$", re.IGNORECASE) return "." in hostname and len(hostname) < 0xff and all(compliant.match(x) for x in hostname.rstrip(".").split("."))
saltstack/salt
salt/utils/network.py
_subnets
python
def _subnets(proto='inet', interfaces_=None): ''' Returns a list of subnets to which the host belongs ''' if interfaces_ is None: ifaces = interfaces() elif isinstance(interfaces_, list): ifaces = {} for key, value in six.iteritems(interfaces()): if key in interfaces_: ifaces[key] = value else: ifaces = {interfaces_: interfaces().get(interfaces_, {})} ret = set() if proto == 'inet': subnet = 'netmask' dflt_cidr = 32 elif proto == 'inet6': subnet = 'prefixlen' dflt_cidr = 128 else: log.error('Invalid proto %s calling subnets()', proto) return for ip_info in six.itervalues(ifaces): addrs = ip_info.get(proto, []) addrs.extend([addr for addr in ip_info.get('secondary', []) if addr.get('type') == proto]) for intf in addrs: if subnet in intf: intf = ipaddress.ip_interface('{0}/{1}'.format(intf['address'], intf[subnet])) else: intf = ipaddress.ip_interface('{0}/{1}'.format(intf['address'], dflt_cidr)) if not intf.is_loopback: ret.add(intf.network) return [six.text_type(net) for net in sorted(ret)]
Returns a list of subnets to which the host belongs
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/network.py#L1184-L1221
[ "def iteritems(d, **kw):\n return d.iteritems(**kw)\n", "def itervalues(d, **kw):\n return d.itervalues(**kw)\n", "def interfaces():\n '''\n Return a dictionary of information about all the interfaces on the minion\n '''\n if salt.utils.platform.is_windows():\n return win_interfaces()\n elif salt.utils.platform.is_netbsd():\n return netbsd_interfaces()\n else:\n return linux_interfaces()\n" ]
# -*- coding: utf-8 -*- ''' Define some generic socket functions for network modules ''' # Import python libs from __future__ import absolute_import, unicode_literals, print_function import itertools import os import re import types import socket import logging import platform import random import subprocess from string import ascii_letters, digits # Import 3rd-party libs from salt.ext import six from salt.ext.six.moves import range # pylint: disable=import-error,redefined-builtin # Attempt to import wmi try: import wmi import salt.utils.winapi except ImportError: pass # Import salt libs import salt.utils.args import salt.utils.files import salt.utils.path import salt.utils.platform import salt.utils.stringutils import salt.utils.zeromq from salt._compat import ipaddress from salt.exceptions import SaltClientError, SaltSystemExit from salt.utils.decorators.jinja import jinja_filter from salt.utils.versions import LooseVersion # inet_pton does not exist in Windows, this is a workaround if salt.utils.platform.is_windows(): from salt.ext import win_inet_pton # pylint: disable=unused-import log = logging.getLogger(__name__) try: import ctypes import ctypes.util libc = ctypes.cdll.LoadLibrary(ctypes.util.find_library("c")) res_init = libc.__res_init except (ImportError, OSError, AttributeError, TypeError): pass # pylint: disable=C0103 def sanitize_host(host): ''' Sanitize host string. https://tools.ietf.org/html/rfc1123#section-2.1 ''' RFC952_characters = ascii_letters + digits + ".-" return "".join([c for c in host[0:255] if c in RFC952_characters]) def isportopen(host, port): ''' Return status of a port ''' if not 1 <= int(port) <= 65535: return False sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) out = sock.connect_ex((sanitize_host(host), int(port))) return out def host_to_ips(host): ''' Returns a list of IP addresses of a given hostname or None if not found. ''' ips = [] try: for family, socktype, proto, canonname, sockaddr in socket.getaddrinfo( host, 0, socket.AF_UNSPEC, socket.SOCK_STREAM): if family == socket.AF_INET: ip, port = sockaddr elif family == socket.AF_INET6: ip, port, flow_info, scope_id = sockaddr ips.append(ip) if not ips: ips = None except Exception: ips = None return ips def _generate_minion_id(): ''' Get list of possible host names and convention names. :return: ''' # There are three types of hostnames: # 1. Network names. How host is accessed from the network. # 2. Host aliases. They might be not available in all the network or only locally (/etc/hosts) # 3. Convention names, an internal nodename. class DistinctList(list): ''' List, which allows one to append only distinct objects. Needs to work on Python 2.6, because of collections.OrderedDict only since 2.7 version. Override 'filter()' for custom filtering. ''' localhost_matchers = [r'localhost.*', r'ip6-.*', r'127[.]\d', r'0\.0\.0\.0', r'::1.*', r'ipv6-.*', r'fe00::.*', r'fe02::.*', r'1.0.0.*.ip6.arpa'] def append(self, p_object): if p_object and p_object not in self and not self.filter(p_object): super(DistinctList, self).append(p_object) return self def extend(self, iterable): for obj in iterable: self.append(obj) return self def filter(self, element): 'Returns True if element needs to be filtered' for rgx in self.localhost_matchers: if re.match(rgx, element): return True def first(self): return self and self[0] or None hostname = socket.gethostname() hosts = DistinctList().append( salt.utils.stringutils.to_unicode(socket.getfqdn(salt.utils.stringutils.to_bytes(hostname))) ).append(platform.node()).append(hostname) if not hosts: try: for a_nfo in socket.getaddrinfo(hosts.first() or 'localhost', None, socket.AF_INET, socket.SOCK_RAW, socket.IPPROTO_IP, socket.AI_CANONNAME): if len(a_nfo) > 3: hosts.append(a_nfo[3]) except socket.gaierror: log.warning('Cannot resolve address %s info via socket: %s', hosts.first() or 'localhost (N/A)', socket.gaierror) # Universal method for everywhere (Linux, Slowlaris, Windows etc) for f_name in ('/etc/hostname', '/etc/nodename', '/etc/hosts', r'{win}\system32\drivers\etc\hosts'.format(win=os.getenv('WINDIR'))): try: with salt.utils.files.fopen(f_name) as f_hdl: for line in f_hdl: line = salt.utils.stringutils.to_unicode(line) hst = line.strip().split('#')[0].strip().split() if hst: if hst[0][:4] in ('127.', '::1') or len(hst) == 1: hosts.extend(hst) except IOError: pass # include public and private ipaddresses return hosts.extend([addr for addr in ip_addrs() if not ipaddress.ip_address(addr).is_loopback]) def generate_minion_id(): ''' Return only first element of the hostname from all possible list. :return: ''' try: ret = salt.utils.stringutils.to_unicode(_generate_minion_id().first()) except TypeError: ret = None return ret or 'localhost' def get_socket(addr, type=socket.SOCK_STREAM, proto=0): ''' Return a socket object for the addr IP-version agnostic ''' version = ipaddress.ip_address(addr).version if version == 4: family = socket.AF_INET elif version == 6: family = socket.AF_INET6 return socket.socket(family, type, proto) def get_fqhostname(): ''' Returns the fully qualified hostname ''' # try getaddrinfo() fqdn = None try: addrinfo = socket.getaddrinfo( socket.gethostname(), 0, socket.AF_UNSPEC, socket.SOCK_STREAM, socket.SOL_TCP, socket.AI_CANONNAME ) for info in addrinfo: # info struct [family, socktype, proto, canonname, sockaddr] # On Windows `canonname` can be an empty string # This can cause the function to return `None` if len(info) > 3 and info[3]: fqdn = info[3] break except socket.gaierror: pass # NOTE: this used to log.error() but it was later disabled except socket.error as err: log.debug('socket.getaddrinfo() failure while finding fqdn: %s', err) if fqdn is None: fqdn = socket.getfqdn() return fqdn def ip_to_host(ip): ''' Returns the hostname of a given IP ''' try: hostname, aliaslist, ipaddrlist = socket.gethostbyaddr(ip) except Exception as exc: log.debug('salt.utils.network.ip_to_host(%r) failed: %s', ip, exc) hostname = None return hostname # pylint: enable=C0103 def is_reachable_host(entity_name): ''' Returns a bool telling if the entity name is a reachable host (IPv4/IPv6/FQDN/etc). :param hostname: :return: ''' try: assert type(socket.getaddrinfo(entity_name, 0, 0, 0, 0)) == list ret = True except socket.gaierror: ret = False return ret def is_ip(ip): ''' Returns a bool telling if the passed IP is a valid IPv4 or IPv6 address. ''' return is_ipv4(ip) or is_ipv6(ip) def is_ipv4(ip): ''' Returns a bool telling if the value passed to it was a valid IPv4 address ''' try: return ipaddress.ip_address(ip).version == 4 except ValueError: return False def is_ipv6(ip): ''' Returns a bool telling if the value passed to it was a valid IPv6 address ''' try: return ipaddress.ip_address(ip).version == 6 except ValueError: return False def is_subnet(cidr): ''' Returns a bool telling if the passed string is an IPv4 or IPv6 subnet ''' return is_ipv4_subnet(cidr) or is_ipv6_subnet(cidr) def is_ipv4_subnet(cidr): ''' Returns a bool telling if the passed string is an IPv4 subnet ''' try: return '/' in cidr and bool(ipaddress.IPv4Network(cidr)) except Exception: return False def is_ipv6_subnet(cidr): ''' Returns a bool telling if the passed string is an IPv6 subnet ''' try: return '/' in cidr and bool(ipaddress.IPv6Network(cidr)) except Exception: return False @jinja_filter('is_ip') def is_ip_filter(ip, options=None): ''' Returns a bool telling if the passed IP is a valid IPv4 or IPv6 address. ''' return is_ipv4_filter(ip, options=options) or is_ipv6_filter(ip, options=options) def _ip_options_global(ip_obj, version): return not ip_obj.is_private def _ip_options_multicast(ip_obj, version): return ip_obj.is_multicast def _ip_options_loopback(ip_obj, version): return ip_obj.is_loopback def _ip_options_link_local(ip_obj, version): return ip_obj.is_link_local def _ip_options_private(ip_obj, version): return ip_obj.is_private def _ip_options_reserved(ip_obj, version): return ip_obj.is_reserved def _ip_options_site_local(ip_obj, version): if version == 6: return ip_obj.is_site_local return False def _ip_options_unspecified(ip_obj, version): return ip_obj.is_unspecified def _ip_options(ip_obj, version, options=None): # will process and IP options options_fun_map = { 'global': _ip_options_global, 'link-local': _ip_options_link_local, 'linklocal': _ip_options_link_local, 'll': _ip_options_link_local, 'link_local': _ip_options_link_local, 'loopback': _ip_options_loopback, 'lo': _ip_options_loopback, 'multicast': _ip_options_multicast, 'private': _ip_options_private, 'public': _ip_options_global, 'reserved': _ip_options_reserved, 'site-local': _ip_options_site_local, 'sl': _ip_options_site_local, 'site_local': _ip_options_site_local, 'unspecified': _ip_options_unspecified } if not options: return six.text_type(ip_obj) # IP version already checked options_list = [option.strip() for option in options.split(',')] for option, fun in options_fun_map.items(): if option in options_list: fun_res = fun(ip_obj, version) if not fun_res: return None # stop at first failed test # else continue return six.text_type(ip_obj) def _is_ipv(ip, version, options=None): if not version: version = 4 if version not in (4, 6): return None try: ip_obj = ipaddress.ip_address(ip) except ValueError: # maybe it is an IP network try: ip_obj = ipaddress.ip_interface(ip) except ValueError: # nope, still not :( return None if not ip_obj.version == version: return None # has the right version, let's move on return _ip_options(ip_obj, version, options=options) @jinja_filter('is_ipv4') def is_ipv4_filter(ip, options=None): ''' Returns a bool telling if the value passed to it was a valid IPv4 address. ip The IP address. net: False Consider IP addresses followed by netmask. options CSV of options regarding the nature of the IP address. E.g.: loopback, multicast, private etc. ''' _is_ipv4 = _is_ipv(ip, 4, options=options) return isinstance(_is_ipv4, six.string_types) @jinja_filter('is_ipv6') def is_ipv6_filter(ip, options=None): ''' Returns a bool telling if the value passed to it was a valid IPv6 address. ip The IP address. net: False Consider IP addresses followed by netmask. options CSV of options regarding the nature of the IP address. E.g.: loopback, multicast, private etc. ''' _is_ipv6 = _is_ipv(ip, 6, options=options) return isinstance(_is_ipv6, six.string_types) def _ipv_filter(value, version, options=None): if version not in (4, 6): return if isinstance(value, (six.string_types, six.text_type, six.binary_type)): return _is_ipv(value, version, options=options) # calls is_ipv4 or is_ipv6 for `value` elif isinstance(value, (list, tuple, types.GeneratorType)): # calls is_ipv4 or is_ipv6 for each element in the list # os it filters and returns only those elements having the desired IP version return [ _is_ipv(addr, version, options=options) for addr in value if _is_ipv(addr, version, options=options) is not None ] return None @jinja_filter('ipv4') def ipv4(value, options=None): ''' Filters a list and returns IPv4 values only. ''' return _ipv_filter(value, 4, options=options) @jinja_filter('ipv6') def ipv6(value, options=None): ''' Filters a list and returns IPv6 values only. ''' return _ipv_filter(value, 6, options=options) @jinja_filter('ipaddr') def ipaddr(value, options=None): ''' Filters and returns only valid IP objects. ''' ipv4_obj = ipv4(value, options=options) ipv6_obj = ipv6(value, options=options) if ipv4_obj is None or ipv6_obj is None: # an IP address can be either IPv4 either IPv6 # therefofe if the value passed as arg is not a list, at least one of the calls above will return None # if one of them is none, means that we should return only one of them return ipv4_obj or ipv6_obj # one of them else: return ipv4_obj + ipv6_obj # extend lists def _filter_ipaddr(value, options, version=None): ipaddr_filter_out = None if version: if version == 4: ipaddr_filter_out = ipv4(value, options) elif version == 6: ipaddr_filter_out = ipv6(value, options) else: ipaddr_filter_out = ipaddr(value, options) if not ipaddr_filter_out: return if not isinstance(ipaddr_filter_out, (list, tuple, types.GeneratorType)): ipaddr_filter_out = [ipaddr_filter_out] return ipaddr_filter_out @jinja_filter('ip_host') def ip_host(value, options=None, version=None): ''' Returns the interfaces IP address, e.g.: 192.168.0.1/28. ''' ipaddr_filter_out = _filter_ipaddr(value, options=options, version=version) if not ipaddr_filter_out: return if not isinstance(value, (list, tuple, types.GeneratorType)): return six.text_type(ipaddress.ip_interface(ipaddr_filter_out[0])) return [six.text_type(ipaddress.ip_interface(ip_a)) for ip_a in ipaddr_filter_out] def _network_hosts(ip_addr_entry): return [ six.text_type(host) for host in ipaddress.ip_network(ip_addr_entry, strict=False).hosts() ] @jinja_filter('network_hosts') def network_hosts(value, options=None, version=None): ''' Return the list of hosts within a network. .. note:: When running this command with a large IPv6 network, the command will take a long time to gather all of the hosts. ''' ipaddr_filter_out = _filter_ipaddr(value, options=options, version=version) if not ipaddr_filter_out: return if not isinstance(value, (list, tuple, types.GeneratorType)): return _network_hosts(ipaddr_filter_out[0]) return [ _network_hosts(ip_a) for ip_a in ipaddr_filter_out ] def _network_size(ip_addr_entry): return ipaddress.ip_network(ip_addr_entry, strict=False).num_addresses @jinja_filter('network_size') def network_size(value, options=None, version=None): ''' Get the size of a network. ''' ipaddr_filter_out = _filter_ipaddr(value, options=options, version=version) if not ipaddr_filter_out: return if not isinstance(value, (list, tuple, types.GeneratorType)): return _network_size(ipaddr_filter_out[0]) return [ _network_size(ip_a) for ip_a in ipaddr_filter_out ] def natural_ipv4_netmask(ip, fmt='prefixlen'): ''' Returns the "natural" mask of an IPv4 address ''' bits = _ipv4_to_bits(ip) if bits.startswith('11'): mask = '24' elif bits.startswith('1'): mask = '16' else: mask = '8' if fmt == 'netmask': return cidr_to_ipv4_netmask(mask) else: return '/' + mask def rpad_ipv4_network(ip): ''' Returns an IP network address padded with zeros. Ex: '192.168.3' -> '192.168.3.0' '10.209' -> '10.209.0.0' ''' return '.'.join(itertools.islice(itertools.chain(ip.split('.'), '0000'), 0, 4)) def cidr_to_ipv4_netmask(cidr_bits): ''' Returns an IPv4 netmask ''' try: cidr_bits = int(cidr_bits) if not 1 <= cidr_bits <= 32: return '' except ValueError: return '' netmask = '' for idx in range(4): if idx: netmask += '.' if cidr_bits >= 8: netmask += '255' cidr_bits -= 8 else: netmask += '{0:d}'.format(256 - (2 ** (8 - cidr_bits))) cidr_bits = 0 return netmask def _number_of_set_bits_to_ipv4_netmask(set_bits): # pylint: disable=C0103 ''' Returns an IPv4 netmask from the integer representation of that mask. Ex. 0xffffff00 -> '255.255.255.0' ''' return cidr_to_ipv4_netmask(_number_of_set_bits(set_bits)) # pylint: disable=C0103 def _number_of_set_bits(x): ''' Returns the number of bits that are set in a 32bit int ''' # Taken from http://stackoverflow.com/a/4912729. Many thanks! x -= (x >> 1) & 0x55555555 x = ((x >> 2) & 0x33333333) + (x & 0x33333333) x = ((x >> 4) + x) & 0x0f0f0f0f x += x >> 8 x += x >> 16 return x & 0x0000003f # pylint: enable=C0103 def _interfaces_ip(out): ''' Uses ip to return a dictionary of interfaces with various information about each (up/down state, ip address, netmask, and hwaddr) ''' ret = dict() def parse_network(value, cols): ''' Return a tuple of ip, netmask, broadcast based on the current set of cols ''' brd = None scope = None if '/' in value: # we have a CIDR in this address ip, cidr = value.split('/') # pylint: disable=C0103 else: ip = value # pylint: disable=C0103 cidr = 32 if type_ == 'inet': mask = cidr_to_ipv4_netmask(int(cidr)) if 'brd' in cols: brd = cols[cols.index('brd') + 1] elif type_ == 'inet6': mask = cidr if 'scope' in cols: scope = cols[cols.index('scope') + 1] return (ip, mask, brd, scope) groups = re.compile('\r?\n\\d').split(out) for group in groups: iface = None data = dict() for line in group.splitlines(): if ' ' not in line: continue match = re.match(r'^\d*:\s+([\w.\-]+)(?:@)?([\w.\-]+)?:\s+<(.+)>', line) if match: iface, parent, attrs = match.groups() if 'UP' in attrs.split(','): data['up'] = True else: data['up'] = False if parent: data['parent'] = parent continue cols = line.split() if len(cols) >= 2: type_, value = tuple(cols[0:2]) iflabel = cols[-1:][0] if type_ in ('inet', 'inet6'): if 'secondary' not in cols: ipaddr, netmask, broadcast, scope = parse_network(value, cols) if type_ == 'inet': if 'inet' not in data: data['inet'] = list() addr_obj = dict() addr_obj['address'] = ipaddr addr_obj['netmask'] = netmask addr_obj['broadcast'] = broadcast addr_obj['label'] = iflabel data['inet'].append(addr_obj) elif type_ == 'inet6': if 'inet6' not in data: data['inet6'] = list() addr_obj = dict() addr_obj['address'] = ipaddr addr_obj['prefixlen'] = netmask addr_obj['scope'] = scope data['inet6'].append(addr_obj) else: if 'secondary' not in data: data['secondary'] = list() ip_, mask, brd, scp = parse_network(value, cols) data['secondary'].append({ 'type': type_, 'address': ip_, 'netmask': mask, 'broadcast': brd, 'label': iflabel, }) del ip_, mask, brd, scp elif type_.startswith('link'): data['hwaddr'] = value if iface: ret[iface] = data del iface, data return ret def _interfaces_ifconfig(out): ''' Uses ifconfig to return a dictionary of interfaces with various information about each (up/down state, ip address, netmask, and hwaddr) ''' ret = dict() piface = re.compile(r'^([^\s:]+)') pmac = re.compile('.*?(?:HWaddr|ether|address:|lladdr) ([0-9a-fA-F:]+)') if salt.utils.platform.is_sunos(): pip = re.compile(r'.*?(?:inet\s+)([0-9]+\.[0-9]+\.[0-9]+\.[0-9]+)(.*)') pip6 = re.compile('.*?(?:inet6 )([0-9a-fA-F:]+)') pmask6 = re.compile(r'.*?(?:inet6 [0-9a-fA-F:]+/(\d+)).*') else: pip = re.compile(r'.*?(?:inet addr:|inet [^\d]*)(.*?)\s') pip6 = re.compile('.*?(?:inet6 addr: (.*?)/|inet6 )([0-9a-fA-F:]+)') pmask6 = re.compile(r'.*?(?:inet6 addr: [0-9a-fA-F:]+/(\d+)|prefixlen (\d+))(?: Scope:([a-zA-Z]+)| scopeid (0x[0-9a-fA-F]))?') pmask = re.compile(r'.*?(?:Mask:|netmask )(?:((?:0x)?[0-9a-fA-F]{8})|([\d\.]+))') pupdown = re.compile('UP') pbcast = re.compile(r'.*?(?:Bcast:|broadcast )([\d\.]+)') groups = re.compile('\r?\n(?=\\S)').split(out) for group in groups: data = dict() iface = '' updown = False for line in group.splitlines(): miface = piface.match(line) mmac = pmac.match(line) mip = pip.match(line) mip6 = pip6.match(line) mupdown = pupdown.search(line) if miface: iface = miface.group(1) if mmac: data['hwaddr'] = mmac.group(1) if salt.utils.platform.is_sunos(): expand_mac = [] for chunk in data['hwaddr'].split(':'): expand_mac.append('0{0}'.format(chunk) if len(chunk) < 2 else '{0}'.format(chunk)) data['hwaddr'] = ':'.join(expand_mac) if mip: if 'inet' not in data: data['inet'] = list() addr_obj = dict() addr_obj['address'] = mip.group(1) mmask = pmask.match(line) if mmask: if mmask.group(1): mmask = _number_of_set_bits_to_ipv4_netmask( int(mmask.group(1), 16)) else: mmask = mmask.group(2) addr_obj['netmask'] = mmask mbcast = pbcast.match(line) if mbcast: addr_obj['broadcast'] = mbcast.group(1) data['inet'].append(addr_obj) if mupdown: updown = True if mip6: if 'inet6' not in data: data['inet6'] = list() addr_obj = dict() addr_obj['address'] = mip6.group(1) or mip6.group(2) mmask6 = pmask6.match(line) if mmask6: addr_obj['prefixlen'] = mmask6.group(1) or mmask6.group(2) if not salt.utils.platform.is_sunos(): ipv6scope = mmask6.group(3) or mmask6.group(4) addr_obj['scope'] = ipv6scope.lower() if ipv6scope is not None else ipv6scope # SunOS sometimes has ::/0 as inet6 addr when using addrconf if not salt.utils.platform.is_sunos() \ or addr_obj['address'] != '::' \ and addr_obj['prefixlen'] != 0: data['inet6'].append(addr_obj) data['up'] = updown if iface in ret: # SunOS optimization, where interfaces occur twice in 'ifconfig -a' # output with the same name: for ipv4 and then for ipv6 addr family. # Every instance has it's own 'UP' status and we assume that ipv4 # status determines global interface status. # # merge items with higher priority for older values # after that merge the inet and inet6 sub items for both ret[iface] = dict(list(data.items()) + list(ret[iface].items())) if 'inet' in data: ret[iface]['inet'].extend(x for x in data['inet'] if x not in ret[iface]['inet']) if 'inet6' in data: ret[iface]['inet6'].extend(x for x in data['inet6'] if x not in ret[iface]['inet6']) else: ret[iface] = data del data return ret def linux_interfaces(): ''' Obtain interface information for *NIX/BSD variants ''' ifaces = dict() ip_path = salt.utils.path.which('ip') ifconfig_path = None if ip_path else salt.utils.path.which('ifconfig') if ip_path: cmd1 = subprocess.Popen( '{0} link show'.format(ip_path), shell=True, close_fds=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT).communicate()[0] cmd2 = subprocess.Popen( '{0} addr show'.format(ip_path), shell=True, close_fds=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT).communicate()[0] ifaces = _interfaces_ip("{0}\n{1}".format( salt.utils.stringutils.to_str(cmd1), salt.utils.stringutils.to_str(cmd2))) elif ifconfig_path: cmd = subprocess.Popen( '{0} -a'.format(ifconfig_path), shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT).communicate()[0] ifaces = _interfaces_ifconfig(salt.utils.stringutils.to_str(cmd)) return ifaces def _netbsd_interfaces_ifconfig(out): ''' Uses ifconfig to return a dictionary of interfaces with various information about each (up/down state, ip address, netmask, and hwaddr) ''' ret = dict() piface = re.compile(r'^([^\s:]+)') pmac = re.compile('.*?address: ([0-9a-f:]+)') pip = re.compile(r'.*?inet [^\d]*(.*?)/([\d]*)\s') pip6 = re.compile(r'.*?inet6 ([0-9a-f:]+)%([a-zA-Z0-9]*)/([\d]*)\s') pupdown = re.compile('UP') pbcast = re.compile(r'.*?broadcast ([\d\.]+)') groups = re.compile('\r?\n(?=\\S)').split(out) for group in groups: data = dict() iface = '' updown = False for line in group.splitlines(): miface = piface.match(line) mmac = pmac.match(line) mip = pip.match(line) mip6 = pip6.match(line) mupdown = pupdown.search(line) if miface: iface = miface.group(1) if mmac: data['hwaddr'] = mmac.group(1) if mip: if 'inet' not in data: data['inet'] = list() addr_obj = dict() addr_obj['address'] = mip.group(1) mmask = mip.group(2) if mip.group(2): addr_obj['netmask'] = cidr_to_ipv4_netmask(mip.group(2)) mbcast = pbcast.match(line) if mbcast: addr_obj['broadcast'] = mbcast.group(1) data['inet'].append(addr_obj) if mupdown: updown = True if mip6: if 'inet6' not in data: data['inet6'] = list() addr_obj = dict() addr_obj['address'] = mip6.group(1) mmask6 = mip6.group(3) addr_obj['scope'] = mip6.group(2) addr_obj['prefixlen'] = mip6.group(3) data['inet6'].append(addr_obj) data['up'] = updown ret[iface] = data del data return ret def netbsd_interfaces(): ''' Obtain interface information for NetBSD >= 8 where the ifconfig output diverged from other BSD variants (Netmask is now part of the address) ''' # NetBSD versions prior to 8.0 can still use linux_interfaces() if LooseVersion(os.uname()[2]) < LooseVersion('8.0'): return linux_interfaces() ifconfig_path = salt.utils.path.which('ifconfig') cmd = subprocess.Popen( '{0} -a'.format(ifconfig_path), shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT).communicate()[0] return _netbsd_interfaces_ifconfig(salt.utils.stringutils.to_str(cmd)) def _interfaces_ipconfig(out): ''' Returns a dictionary of interfaces with various information about each (up/down state, ip address, netmask, and hwaddr) NOTE: This is not used by any function and may be able to be removed in the future. ''' ifaces = dict() iface = None adapter_iface_regex = re.compile(r'adapter (\S.+):$') for line in out.splitlines(): if not line: continue # TODO what does Windows call Infiniband and 10/40gige adapters if line.startswith('Ethernet'): iface = ifaces[adapter_iface_regex.search(line).group(1)] iface['up'] = True addr = None continue if iface: key, val = line.split(',', 1) key = key.strip(' .') val = val.strip() if addr and key == 'Subnet Mask': addr['netmask'] = val elif key in ('IP Address', 'IPv4 Address'): if 'inet' not in iface: iface['inet'] = list() addr = {'address': val.rstrip('(Preferred)'), 'netmask': None, 'broadcast': None} # TODO find the broadcast iface['inet'].append(addr) elif 'IPv6 Address' in key: if 'inet6' not in iface: iface['inet'] = list() # XXX What is the prefixlen!? addr = {'address': val.rstrip('(Preferred)'), 'prefixlen': None} iface['inet6'].append(addr) elif key == 'Physical Address': iface['hwaddr'] = val elif key == 'Media State': # XXX seen used for tunnel adaptors # might be useful iface['up'] = (val != 'Media disconnected') def win_interfaces(): ''' Obtain interface information for Windows systems ''' with salt.utils.winapi.Com(): c = wmi.WMI() ifaces = {} for iface in c.Win32_NetworkAdapterConfiguration(IPEnabled=1): ifaces[iface.Description] = dict() if iface.MACAddress: ifaces[iface.Description]['hwaddr'] = iface.MACAddress if iface.IPEnabled: ifaces[iface.Description]['up'] = True for ip in iface.IPAddress: if '.' in ip: if 'inet' not in ifaces[iface.Description]: ifaces[iface.Description]['inet'] = [] item = {'address': ip, 'label': iface.Description} if iface.DefaultIPGateway: broadcast = next((i for i in iface.DefaultIPGateway if '.' in i), '') if broadcast: item['broadcast'] = broadcast if iface.IPSubnet: netmask = next((i for i in iface.IPSubnet if '.' in i), '') if netmask: item['netmask'] = netmask ifaces[iface.Description]['inet'].append(item) if ':' in ip: if 'inet6' not in ifaces[iface.Description]: ifaces[iface.Description]['inet6'] = [] item = {'address': ip} if iface.DefaultIPGateway: broadcast = next((i for i in iface.DefaultIPGateway if ':' in i), '') if broadcast: item['broadcast'] = broadcast if iface.IPSubnet: netmask = next((i for i in iface.IPSubnet if ':' in i), '') if netmask: item['netmask'] = netmask ifaces[iface.Description]['inet6'].append(item) else: ifaces[iface.Description]['up'] = False return ifaces def interfaces(): ''' Return a dictionary of information about all the interfaces on the minion ''' if salt.utils.platform.is_windows(): return win_interfaces() elif salt.utils.platform.is_netbsd(): return netbsd_interfaces() else: return linux_interfaces() def get_net_start(ipaddr, netmask): ''' Return the address of the network ''' net = ipaddress.ip_network('{0}/{1}'.format(ipaddr, netmask), strict=False) return six.text_type(net.network_address) def get_net_size(mask): ''' Turns an IPv4 netmask into it's corresponding prefix length (255.255.255.0 -> 24 as in 192.168.1.10/24). ''' binary_str = '' for octet in mask.split('.'): binary_str += bin(int(octet))[2:].zfill(8) return len(binary_str.rstrip('0')) def calc_net(ipaddr, netmask=None): ''' Takes IP (CIDR notation supported) and optionally netmask and returns the network in CIDR-notation. (The IP can be any IP inside the subnet) ''' if netmask is not None: ipaddr = '{0}/{1}'.format(ipaddr, netmask) return six.text_type(ipaddress.ip_network(ipaddr, strict=False)) def _ipv4_to_bits(ipaddr): ''' Accepts an IPv4 dotted quad and returns a string representing its binary counterpart ''' return ''.join([bin(int(x))[2:].rjust(8, '0') for x in ipaddr.split('.')]) def _get_iface_info(iface): ''' If `iface` is available, return interface info and no error, otherwise return no info and log and return an error ''' iface_info = interfaces() if iface in iface_info.keys(): return iface_info, False else: error_msg = ('Interface "{0}" not in available interfaces: "{1}"' ''.format(iface, '", "'.join(iface_info.keys()))) log.error(error_msg) return None, error_msg def _hw_addr_aix(iface): ''' Return the hardware address (a.k.a. MAC address) for a given interface on AIX MAC address not available in through interfaces ''' cmd = subprocess.Popen( 'entstat -d {0} | grep \'Hardware Address\''.format(iface), shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT).communicate()[0] if cmd: comps = cmd.split(' ') if len(comps) == 3: mac_addr = comps[2].strip('\'').strip() return mac_addr error_msg = ('Interface "{0}" either not available or does not contain a hardware address'.format(iface)) log.error(error_msg) return error_msg def hw_addr(iface): ''' Return the hardware address (a.k.a. MAC address) for a given interface .. versionchanged:: 2016.11.4 Added support for AIX ''' if salt.utils.platform.is_aix(): return _hw_addr_aix iface_info, error = _get_iface_info(iface) if error is False: return iface_info.get(iface, {}).get('hwaddr', '') else: return error def interface(iface): ''' Return the details of `iface` or an error if it does not exist ''' iface_info, error = _get_iface_info(iface) if error is False: return iface_info.get(iface, {}).get('inet', '') else: return error def interface_ip(iface): ''' Return `iface` IPv4 addr or an error if `iface` does not exist ''' iface_info, error = _get_iface_info(iface) if error is False: inet = iface_info.get(iface, {}).get('inet', None) return inet[0].get('address', '') if inet else '' else: return error def subnets(interfaces=None): ''' Returns a list of IPv4 subnets to which the host belongs ''' return _subnets('inet', interfaces_=interfaces) def subnets6(): ''' Returns a list of IPv6 subnets to which the host belongs ''' return _subnets('inet6') def in_subnet(cidr, addr=None): ''' Returns True if host or (any of) addrs is within specified subnet, otherwise False ''' try: cidr = ipaddress.ip_network(cidr) except ValueError: log.error('Invalid CIDR \'%s\'', cidr) return False if addr is None: addr = ip_addrs() addr.extend(ip_addrs6()) elif not isinstance(addr, (list, tuple)): addr = (addr,) return any(ipaddress.ip_address(item) in cidr for item in addr) def _ip_addrs(interface=None, include_loopback=False, interface_data=None, proto='inet'): ''' Return the full list of IP adresses matching the criteria proto = inet|inet6 ''' ret = set() ifaces = interface_data \ if isinstance(interface_data, dict) \ else interfaces() if interface is None: target_ifaces = ifaces else: target_ifaces = dict([(k, v) for k, v in six.iteritems(ifaces) if k == interface]) if not target_ifaces: log.error('Interface %s not found.', interface) for ip_info in six.itervalues(target_ifaces): addrs = ip_info.get(proto, []) addrs.extend([addr for addr in ip_info.get('secondary', []) if addr.get('type') == proto]) for addr in addrs: addr = ipaddress.ip_address(addr.get('address')) if not addr.is_loopback or include_loopback: ret.add(addr) return [six.text_type(addr) for addr in sorted(ret)] def ip_addrs(interface=None, include_loopback=False, interface_data=None): ''' Returns a list of IPv4 addresses assigned to the host. 127.0.0.1 is ignored, unless 'include_loopback=True' is indicated. If 'interface' is provided, then only IP addresses from that interface will be returned. ''' return _ip_addrs(interface, include_loopback, interface_data, 'inet') def ip_addrs6(interface=None, include_loopback=False, interface_data=None): ''' Returns a list of IPv6 addresses assigned to the host. ::1 is ignored, unless 'include_loopback=True' is indicated. If 'interface' is provided, then only IP addresses from that interface will be returned. ''' return _ip_addrs(interface, include_loopback, interface_data, 'inet6') def hex2ip(hex_ip, invert=False): ''' Convert a hex string to an ip, if a failure occurs the original hex is returned. If 'invert=True' assume that ip from /proc/net/<proto> ''' if len(hex_ip) == 32: # ipv6 ip = [] for i in range(0, 32, 8): ip_part = hex_ip[i:i + 8] ip_part = [ip_part[x:x + 2] for x in range(0, 8, 2)] if invert: ip.append("{0[3]}{0[2]}:{0[1]}{0[0]}".format(ip_part)) else: ip.append("{0[0]}{0[1]}:{0[2]}{0[3]}".format(ip_part)) try: address = ipaddress.IPv6Address(":".join(ip)) if address.ipv4_mapped: return str(address.ipv4_mapped) else: return address.compressed except ipaddress.AddressValueError as ex: log.error('hex2ip - ipv6 address error: %s', ex) return hex_ip try: hip = int(hex_ip, 16) except ValueError: return hex_ip if invert: return '{3}.{2}.{1}.{0}'.format(hip >> 24 & 255, hip >> 16 & 255, hip >> 8 & 255, hip & 255) return '{0}.{1}.{2}.{3}'.format(hip >> 24 & 255, hip >> 16 & 255, hip >> 8 & 255, hip & 255) def mac2eui64(mac, prefix=None): ''' Convert a MAC address to a EUI64 identifier or, with prefix provided, a full IPv6 address ''' # http://tools.ietf.org/html/rfc4291#section-2.5.1 eui64 = re.sub(r'[.:-]', '', mac).lower() eui64 = eui64[0:6] + 'fffe' + eui64[6:] eui64 = hex(int(eui64[0:2], 16) | 2)[2:].zfill(2) + eui64[2:] if prefix is None: return ':'.join(re.findall(r'.{4}', eui64)) else: try: net = ipaddress.ip_network(prefix, strict=False) euil = int('0x{0}'.format(eui64), 16) return '{0}/{1}'.format(net[euil], net.prefixlen) except Exception: return def active_tcp(): ''' Return a dict describing all active tcp connections as quickly as possible ''' ret = {} for statf in ['/proc/net/tcp', '/proc/net/tcp6']: if os.path.isfile(statf): with salt.utils.files.fopen(statf, 'rb') as fp_: for line in fp_: line = salt.utils.stringutils.to_unicode(line) if line.strip().startswith('sl'): continue iret = _parse_tcp_line(line) sl = next(iter(iret)) if iret[sl]['state'] == 1: # 1 is ESTABLISHED del iret[sl]['state'] ret[len(ret)] = iret[sl] return ret def local_port_tcp(port): ''' Return a set of remote ip addrs attached to the specified local port ''' ret = _remotes_on(port, 'local_port') return ret def remote_port_tcp(port): ''' Return a set of ip addrs the current host is connected to on given port ''' ret = _remotes_on(port, 'remote_port') return ret def _remotes_on(port, which_end): ''' Return a set of ip addrs active tcp connections ''' port = int(port) ret = _netlink_tool_remote_on(port, which_end) if ret is not None: return ret ret = set() proc_available = False for statf in ['/proc/net/tcp', '/proc/net/tcp6']: if os.path.isfile(statf): proc_available = True with salt.utils.files.fopen(statf, 'r') as fp_: for line in fp_: line = salt.utils.stringutils.to_unicode(line) if line.strip().startswith('sl'): continue iret = _parse_tcp_line(line) sl = next(iter(iret)) if iret[sl][which_end] == port and iret[sl]['state'] == 1: # 1 is ESTABLISHED ret.add(iret[sl]['remote_addr']) if not proc_available: # Fallback to use OS specific tools if salt.utils.platform.is_sunos(): return _sunos_remotes_on(port, which_end) if salt.utils.platform.is_freebsd(): return _freebsd_remotes_on(port, which_end) if salt.utils.platform.is_netbsd(): return _netbsd_remotes_on(port, which_end) if salt.utils.platform.is_openbsd(): return _openbsd_remotes_on(port, which_end) if salt.utils.platform.is_windows(): return _windows_remotes_on(port, which_end) if salt.utils.platform.is_aix(): return _aix_remotes_on(port, which_end) return _linux_remotes_on(port, which_end) return ret def _parse_tcp_line(line): ''' Parse a single line from the contents of /proc/net/tcp or /proc/net/tcp6 ''' ret = {} comps = line.strip().split() sl = comps[0].rstrip(':') ret[sl] = {} l_addr, l_port = comps[1].split(':') r_addr, r_port = comps[2].split(':') ret[sl]['local_addr'] = hex2ip(l_addr, True) ret[sl]['local_port'] = int(l_port, 16) ret[sl]['remote_addr'] = hex2ip(r_addr, True) ret[sl]['remote_port'] = int(r_port, 16) ret[sl]['state'] = int(comps[3], 16) return ret def _netlink_tool_remote_on(port, which_end): ''' Returns set of ipv4 host addresses of remote established connections on local or remote tcp port. Parses output of shell 'ss' to get connections [root@salt-master ~]# ss -ant State Recv-Q Send-Q Local Address:Port Peer Address:Port LISTEN 0 511 *:80 *:* LISTEN 0 128 *:22 *:* ESTAB 0 0 127.0.0.1:56726 127.0.0.1:4505 ''' remotes = set() valid = False try: data = subprocess.check_output(['ss', '-ant']) # pylint: disable=minimum-python-version except subprocess.CalledProcessError: log.error('Failed ss') raise except OSError: # not command "No such file or directory" return None lines = salt.utils.stringutils.to_str(data).split('\n') for line in lines: if 'Address:Port' in line: # ss tools may not be valid valid = True continue elif 'ESTAB' not in line: continue chunks = line.split() local_host, local_port = chunks[3].split(':', 1) remote_host, remote_port = chunks[4].split(':', 1) if which_end == 'remote_port' and int(remote_port) != port: continue if which_end == 'local_port' and int(local_port) != port: continue remotes.add(remote_host) if valid is False: remotes = None return remotes def _sunos_remotes_on(port, which_end): ''' SunOS specific helper function. Returns set of ipv4 host addresses of remote established connections on local or remote tcp port. Parses output of shell 'netstat' to get connections [root@salt-master ~]# netstat -f inet -n TCP: IPv4 Local Address Remote Address Swind Send-Q Rwind Recv-Q State -------------------- -------------------- ----- ------ ----- ------ ----------- 10.0.0.101.4505 10.0.0.1.45329 1064800 0 1055864 0 ESTABLISHED 10.0.0.101.4505 10.0.0.100.50798 1064800 0 1055864 0 ESTABLISHED ''' remotes = set() try: data = subprocess.check_output(['netstat', '-f', 'inet', '-n']) # pylint: disable=minimum-python-version except subprocess.CalledProcessError: log.error('Failed netstat') raise lines = salt.utils.stringutils.to_str(data).split('\n') for line in lines: if 'ESTABLISHED' not in line: continue chunks = line.split() local_host, local_port = chunks[0].rsplit('.', 1) remote_host, remote_port = chunks[1].rsplit('.', 1) if which_end == 'remote_port' and int(remote_port) != port: continue if which_end == 'local_port' and int(local_port) != port: continue remotes.add(remote_host) return remotes def _freebsd_remotes_on(port, which_end): ''' Returns set of ipv4 host addresses of remote established connections on local tcp port port. Parses output of shell 'sockstat' (FreeBSD) to get connections $ sudo sockstat -4 USER COMMAND PID FD PROTO LOCAL ADDRESS FOREIGN ADDRESS root python2.7 1456 29 tcp4 *:4505 *:* root python2.7 1445 17 tcp4 *:4506 *:* root python2.7 1294 14 tcp4 127.0.0.1:11813 127.0.0.1:4505 root python2.7 1294 41 tcp4 127.0.0.1:61115 127.0.0.1:4506 $ sudo sockstat -4 -c -p 4506 USER COMMAND PID FD PROTO LOCAL ADDRESS FOREIGN ADDRESS root python2.7 1294 41 tcp4 127.0.0.1:61115 127.0.0.1:4506 ''' port = int(port) remotes = set() try: cmd = salt.utils.args.shlex_split('sockstat -4 -c -p {0}'.format(port)) data = subprocess.check_output(cmd) # pylint: disable=minimum-python-version except subprocess.CalledProcessError as ex: log.error('Failed "sockstat" with returncode = %s', ex.returncode) raise lines = salt.utils.stringutils.to_str(data).split('\n') for line in lines: chunks = line.split() if not chunks: continue # ['root', 'python2.7', '1456', '37', 'tcp4', # '127.0.0.1:4505-', '127.0.0.1:55703'] # print chunks if 'COMMAND' in chunks[1]: continue # ignore header if len(chunks) < 2: continue # sockstat -4 -c -p 4506 does this with high PIDs: # USER COMMAND PID FD PROTO LOCAL ADDRESS FOREIGN ADDRESS # salt-master python2.781106 35 tcp4 192.168.12.34:4506 192.168.12.45:60143 local = chunks[-2] remote = chunks[-1] lhost, lport = local.split(':') rhost, rport = remote.split(':') if which_end == 'local' and int(lport) != port: # ignore if local port not port continue if which_end == 'remote' and int(rport) != port: # ignore if remote port not port continue remotes.add(rhost) return remotes def _netbsd_remotes_on(port, which_end): ''' Returns set of ipv4 host addresses of remote established connections on local tcp port port. Parses output of shell 'sockstat' (NetBSD) to get connections $ sudo sockstat -4 -n USER COMMAND PID FD PROTO LOCAL ADDRESS FOREIGN ADDRESS root python2.7 1456 29 tcp *.4505 *.* root python2.7 1445 17 tcp *.4506 *.* root python2.7 1294 14 tcp 127.0.0.1.11813 127.0.0.1.4505 root python2.7 1294 41 tcp 127.0.0.1.61115 127.0.0.1.4506 $ sudo sockstat -4 -c -n -p 4506 USER COMMAND PID FD PROTO LOCAL ADDRESS FOREIGN ADDRESS root python2.7 1294 41 tcp 127.0.0.1.61115 127.0.0.1.4506 ''' port = int(port) remotes = set() try: cmd = salt.utils.args.shlex_split('sockstat -4 -c -n -p {0}'.format(port)) data = subprocess.check_output(cmd) # pylint: disable=minimum-python-version except subprocess.CalledProcessError as ex: log.error('Failed "sockstat" with returncode = %s', ex.returncode) raise lines = salt.utils.stringutils.to_str(data).split('\n') for line in lines: chunks = line.split() if not chunks: continue # ['root', 'python2.7', '1456', '37', 'tcp', # '127.0.0.1.4505-', '127.0.0.1.55703'] # print chunks if 'COMMAND' in chunks[1]: continue # ignore header if len(chunks) < 2: continue local = chunks[5].split('.') lport = local.pop() lhost = '.'.join(local) remote = chunks[6].split('.') rport = remote.pop() rhost = '.'.join(remote) if which_end == 'local' and int(lport) != port: # ignore if local port not port continue if which_end == 'remote' and int(rport) != port: # ignore if remote port not port continue remotes.add(rhost) return remotes def _openbsd_remotes_on(port, which_end): ''' OpenBSD specific helper function. Returns set of ipv4 host addresses of remote established connections on local or remote tcp port. Parses output of shell 'netstat' to get connections $ netstat -nf inet Active Internet connections Proto Recv-Q Send-Q Local Address Foreign Address (state) tcp 0 0 10.0.0.101.4505 10.0.0.1.45329 ESTABLISHED tcp 0 0 10.0.0.101.4505 10.0.0.100.50798 ESTABLISHED ''' remotes = set() try: data = subprocess.check_output(['netstat', '-nf', 'inet']) # pylint: disable=minimum-python-version except subprocess.CalledProcessError: log.error('Failed netstat') raise lines = data.split('\n') for line in lines: if 'ESTABLISHED' not in line: continue chunks = line.split() local_host, local_port = chunks[3].rsplit('.', 1) remote_host, remote_port = chunks[4].rsplit('.', 1) if which_end == 'remote_port' and int(remote_port) != port: continue if which_end == 'local_port' and int(local_port) != port: continue remotes.add(remote_host) return remotes def _windows_remotes_on(port, which_end): r''' Windows specific helper function. Returns set of ipv4 host addresses of remote established connections on local or remote tcp port. Parses output of shell 'netstat' to get connections C:\>netstat -n Active Connections Proto Local Address Foreign Address State TCP 10.2.33.17:3007 130.164.12.233:10123 ESTABLISHED TCP 10.2.33.17:3389 130.164.30.5:10378 ESTABLISHED ''' remotes = set() try: data = subprocess.check_output(['netstat', '-n']) # pylint: disable=minimum-python-version except subprocess.CalledProcessError: log.error('Failed netstat') raise lines = salt.utils.stringutils.to_str(data).split('\n') for line in lines: if 'ESTABLISHED' not in line: continue chunks = line.split() local_host, local_port = chunks[1].rsplit(':', 1) remote_host, remote_port = chunks[2].rsplit(':', 1) if which_end == 'remote_port' and int(remote_port) != port: continue if which_end == 'local_port' and int(local_port) != port: continue remotes.add(remote_host) return remotes def _linux_remotes_on(port, which_end): ''' Linux specific helper function. Returns set of ip host addresses of remote established connections on local tcp port port. Parses output of shell 'lsof' to get connections $ sudo lsof -iTCP:4505 -n COMMAND PID USER FD TYPE DEVICE SIZE/OFF NODE NAME Python 9971 root 35u IPv4 0x18a8464a29ca329d 0t0 TCP *:4505 (LISTEN) Python 9971 root 37u IPv4 0x18a8464a29b2b29d 0t0 TCP 127.0.0.1:4505->127.0.0.1:55703 (ESTABLISHED) Python 10152 root 22u IPv4 0x18a8464a29c8cab5 0t0 TCP 127.0.0.1:55703->127.0.0.1:4505 (ESTABLISHED) Python 10153 root 22u IPv4 0x18a8464a29c8cab5 0t0 TCP [fe80::249a]:4505->[fe80::150]:59367 (ESTABLISHED) ''' remotes = set() try: data = subprocess.check_output( ['lsof', '-iTCP:{0:d}'.format(port), '-n', '-P'] # pylint: disable=minimum-python-version ) except subprocess.CalledProcessError as ex: if ex.returncode == 1: # Lsof return 1 if any error was detected, including the failure # to locate Internet addresses, and it is not an error in this case. log.warning('"lsof" returncode = 1, likely no active TCP sessions.') return remotes log.error('Failed "lsof" with returncode = %s', ex.returncode) raise lines = salt.utils.stringutils.to_str(data).split('\n') for line in lines: chunks = line.split() if not chunks: continue # ['Python', '9971', 'root', '37u', 'IPv4', '0x18a8464a29b2b29d', '0t0', # 'TCP', '127.0.0.1:4505->127.0.0.1:55703', '(ESTABLISHED)'] # print chunks if 'COMMAND' in chunks[0]: continue # ignore header if 'ESTABLISHED' not in chunks[-1]: continue # ignore if not ESTABLISHED # '127.0.0.1:4505->127.0.0.1:55703' local, remote = chunks[8].split('->') _, lport = local.rsplit(':', 1) rhost, rport = remote.rsplit(':', 1) if which_end == 'remote_port' and int(rport) != port: continue if which_end == 'local_port' and int(lport) != port: continue remotes.add(rhost.strip("[]")) return remotes def _aix_remotes_on(port, which_end): ''' AIX specific helper function. Returns set of ipv4 host addresses of remote established connections on local or remote tcp port. Parses output of shell 'netstat' to get connections root@la68pp002_pub:/opt/salt/lib/python2.7/site-packages/salt/modules# netstat -f inet -n Active Internet connections Proto Recv-Q Send-Q Local Address Foreign Address (state) tcp4 0 0 172.29.149.95.50093 209.41.78.13.4505 ESTABLISHED tcp4 0 0 127.0.0.1.9514 *.* LISTEN tcp4 0 0 127.0.0.1.9515 *.* LISTEN tcp4 0 0 127.0.0.1.199 127.0.0.1.32779 ESTABLISHED tcp4 0 0 127.0.0.1.32779 127.0.0.1.199 ESTABLISHED tcp4 0 40 172.29.149.95.22 172.29.96.83.41022 ESTABLISHED tcp4 0 0 172.29.149.95.22 172.29.96.83.41032 ESTABLISHED tcp4 0 0 127.0.0.1.32771 127.0.0.1.32775 ESTABLISHED tcp 0 0 127.0.0.1.32775 127.0.0.1.32771 ESTABLISHED tcp4 0 0 127.0.0.1.32771 127.0.0.1.32776 ESTABLISHED tcp 0 0 127.0.0.1.32776 127.0.0.1.32771 ESTABLISHED tcp4 0 0 127.0.0.1.32771 127.0.0.1.32777 ESTABLISHED tcp 0 0 127.0.0.1.32777 127.0.0.1.32771 ESTABLISHED tcp4 0 0 127.0.0.1.32771 127.0.0.1.32778 ESTABLISHED tcp 0 0 127.0.0.1.32778 127.0.0.1.32771 ESTABLISHED ''' remotes = set() try: data = subprocess.check_output(['netstat', '-f', 'inet', '-n']) # pylint: disable=minimum-python-version except subprocess.CalledProcessError: log.error('Failed netstat') raise lines = salt.utils.stringutils.to_str(data).split('\n') for line in lines: if 'ESTABLISHED' not in line: continue chunks = line.split() local_host, local_port = chunks[3].rsplit('.', 1) remote_host, remote_port = chunks[4].rsplit('.', 1) if which_end == 'remote_port' and int(remote_port) != port: continue if which_end == 'local_port' and int(local_port) != port: continue remotes.add(remote_host) return remotes @jinja_filter('gen_mac') def gen_mac(prefix='AC:DE:48'): ''' Generates a MAC address with the defined OUI prefix. Common prefixes: - ``00:16:3E`` -- Xen - ``00:18:51`` -- OpenVZ - ``00:50:56`` -- VMware (manually generated) - ``52:54:00`` -- QEMU/KVM - ``AC:DE:48`` -- PRIVATE References: - http://standards.ieee.org/develop/regauth/oui/oui.txt - https://www.wireshark.org/tools/oui-lookup.html - https://en.wikipedia.org/wiki/MAC_address ''' return '{0}:{1:02X}:{2:02X}:{3:02X}'.format(prefix, random.randint(0, 0xff), random.randint(0, 0xff), random.randint(0, 0xff)) @jinja_filter('mac_str_to_bytes') def mac_str_to_bytes(mac_str): ''' Convert a MAC address string into bytes. Works with or without separators: b1 = mac_str_to_bytes('08:00:27:13:69:77') b2 = mac_str_to_bytes('080027136977') assert b1 == b2 assert isinstance(b1, bytes) ''' if len(mac_str) == 12: pass elif len(mac_str) == 17: sep = mac_str[2] mac_str = mac_str.replace(sep, '') else: raise ValueError('Invalid MAC address') chars = (int(mac_str[s:s+2], 16) for s in range(0, 12, 2)) return bytes(chars) if six.PY3 else b''.join(chr(x) for x in chars) def refresh_dns(): ''' issue #21397: force glibc to re-read resolv.conf ''' try: res_init() except NameError: # Exception raised loading the library, thus res_init is not defined pass @jinja_filter('connection_check') def connection_check(addr, port=80, safe=False, ipv6=None): ''' Provides a convenient alias for the dns_check filter. ''' return dns_check(addr, port, safe, ipv6) @jinja_filter('dns_check') def dns_check(addr, port=80, safe=False, ipv6=None, attempt_connect=True): ''' Return the ip resolved by dns, but do not exit on failure, only raise an exception. Obeys system preference for IPv4/6 address resolution - this can be overridden by the ipv6 flag. Tries to connect to the address before considering it useful. If no address can be reached, the first one resolved is used as a fallback. ''' error = False lookup = addr seen_ipv6 = False family = socket.AF_INET6 if ipv6 else socket.AF_INET if ipv6 is False else socket.AF_UNSPEC hostnames = [] try: refresh_dns() hostnames = socket.getaddrinfo(addr, port, family, socket.SOCK_STREAM) except TypeError: err = ('Attempt to resolve address \'{0}\' failed. Invalid or unresolveable address').format(lookup) raise SaltSystemExit(code=42, msg=err) except socket.error: error = True # If ipv6 is set to True, attempt another lookup using the IPv4 family, # just in case we're attempting to lookup an IPv4 IP # as an IPv6 hostname. if error and ipv6: try: refresh_dns() hostnames = socket.getaddrinfo(addr, port, socket.AF_INET, socket.SOCK_STREAM) except TypeError: err = ('Attempt to resolve address \'{0}\' failed. Invalid or unresolveable address').format(lookup) raise SaltSystemExit(code=42, msg=err) except socket.error: error = True try: if not hostnames: error = True else: resolved = False candidates = [] for h in hostnames: # Input is IP address, passed through unchanged, just return it if h[4][0] == addr: resolved = salt.utils.zeromq.ip_bracket(addr) break candidate_addr = salt.utils.zeromq.ip_bracket(h[4][0]) # sometimes /etc/hosts contains ::1 localhost if not ipv6 and candidate_addr == '[::1]': continue candidates.append(candidate_addr) if attempt_connect: try: s = socket.socket(h[0], socket.SOCK_STREAM) s.settimeout(2) s.connect((candidate_addr.strip('[]'), h[4][1])) s.close() resolved = candidate_addr break except socket.error: pass if not resolved: if candidates: resolved = candidates[0] else: error = True except TypeError: err = ('Attempt to resolve address \'{0}\' failed. Invalid or unresolveable address').format(lookup) raise SaltSystemExit(code=42, msg=err) except socket.error: error = True if error: err = ('DNS lookup or connection check of \'{0}\' failed.').format(addr) if safe: if salt.log.is_console_configured(): # If logging is not configured it also means that either # the master or minion instance calling this hasn't even # started running log.error(err) raise SaltClientError() raise SaltSystemExit(code=42, msg=err) return resolved def parse_host_port(host_port): """ Takes a string argument specifying host or host:port. Returns a (hostname, port) or (ip_address, port) tuple. If no port is given, the second (port) element of the returned tuple will be None. host:port argument, for example, is accepted in the forms of: - hostname - hostname:1234 - hostname.domain.tld - hostname.domain.tld:5678 - [1234::5]:5678 - 1234::5 - 10.11.12.13:4567 - 10.11.12.13 """ host, port = None, None # default _s_ = host_port[:] if _s_[0] == "[": if "]" in host_port: host, _s_ = _s_.lstrip("[").rsplit("]", 1) host = ipaddress.IPv6Address(host).compressed if _s_[0] == ":": port = int(_s_.lstrip(":")) else: if len(_s_) > 1: raise ValueError('found ambiguous "{}" port in "{}"'.format(_s_, host_port)) else: if _s_.count(":") == 1: host, _hostport_separator_, port = _s_.partition(":") try: port = int(port) except ValueError as _e_: log.error('host_port "%s" port value "%s" is not an integer.', host_port, port) raise _e_ else: host = _s_ try: if not isinstance(host, ipaddress._BaseAddress): host_ip = ipaddress.ip_address(host).compressed host = host_ip except ValueError: log.debug('"%s" Not an IP address? Assuming it is a hostname.', host) if host != sanitize_host(host): log.error('bad hostname: "%s"', host) raise ValueError('bad hostname: "{}"'.format(host)) return host, port def is_fqdn(hostname): """ Verify if hostname conforms to be a FQDN. :param hostname: text string with the name of the host :return: bool, True if hostname is correct FQDN, False otherwise """ compliant = re.compile(r"(?!-)[A-Z\d\-\_]{1,63}(?<!-)$", re.IGNORECASE) return "." in hostname and len(hostname) < 0xff and all(compliant.match(x) for x in hostname.rstrip(".").split("."))
saltstack/salt
salt/utils/network.py
in_subnet
python
def in_subnet(cidr, addr=None): ''' Returns True if host or (any of) addrs is within specified subnet, otherwise False ''' try: cidr = ipaddress.ip_network(cidr) except ValueError: log.error('Invalid CIDR \'%s\'', cidr) return False if addr is None: addr = ip_addrs() addr.extend(ip_addrs6()) elif not isinstance(addr, (list, tuple)): addr = (addr,) return any(ipaddress.ip_address(item) in cidr for item in addr)
Returns True if host or (any of) addrs is within specified subnet, otherwise False
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/network.py#L1238-L1254
[ "def ip_addrs(interface=None, include_loopback=False, interface_data=None):\n '''\n Returns a list of IPv4 addresses assigned to the host. 127.0.0.1 is\n ignored, unless 'include_loopback=True' is indicated. If 'interface' is\n provided, then only IP addresses from that interface will be returned.\n '''\n return _ip_addrs(interface, include_loopback, interface_data, 'inet')\n", "def ip_addrs6(interface=None, include_loopback=False, interface_data=None):\n '''\n Returns a list of IPv6 addresses assigned to the host. ::1 is ignored,\n unless 'include_loopback=True' is indicated. If 'interface' is provided,\n then only IP addresses from that interface will be returned.\n '''\n return _ip_addrs(interface, include_loopback, interface_data, 'inet6')\n" ]
# -*- coding: utf-8 -*- ''' Define some generic socket functions for network modules ''' # Import python libs from __future__ import absolute_import, unicode_literals, print_function import itertools import os import re import types import socket import logging import platform import random import subprocess from string import ascii_letters, digits # Import 3rd-party libs from salt.ext import six from salt.ext.six.moves import range # pylint: disable=import-error,redefined-builtin # Attempt to import wmi try: import wmi import salt.utils.winapi except ImportError: pass # Import salt libs import salt.utils.args import salt.utils.files import salt.utils.path import salt.utils.platform import salt.utils.stringutils import salt.utils.zeromq from salt._compat import ipaddress from salt.exceptions import SaltClientError, SaltSystemExit from salt.utils.decorators.jinja import jinja_filter from salt.utils.versions import LooseVersion # inet_pton does not exist in Windows, this is a workaround if salt.utils.platform.is_windows(): from salt.ext import win_inet_pton # pylint: disable=unused-import log = logging.getLogger(__name__) try: import ctypes import ctypes.util libc = ctypes.cdll.LoadLibrary(ctypes.util.find_library("c")) res_init = libc.__res_init except (ImportError, OSError, AttributeError, TypeError): pass # pylint: disable=C0103 def sanitize_host(host): ''' Sanitize host string. https://tools.ietf.org/html/rfc1123#section-2.1 ''' RFC952_characters = ascii_letters + digits + ".-" return "".join([c for c in host[0:255] if c in RFC952_characters]) def isportopen(host, port): ''' Return status of a port ''' if not 1 <= int(port) <= 65535: return False sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) out = sock.connect_ex((sanitize_host(host), int(port))) return out def host_to_ips(host): ''' Returns a list of IP addresses of a given hostname or None if not found. ''' ips = [] try: for family, socktype, proto, canonname, sockaddr in socket.getaddrinfo( host, 0, socket.AF_UNSPEC, socket.SOCK_STREAM): if family == socket.AF_INET: ip, port = sockaddr elif family == socket.AF_INET6: ip, port, flow_info, scope_id = sockaddr ips.append(ip) if not ips: ips = None except Exception: ips = None return ips def _generate_minion_id(): ''' Get list of possible host names and convention names. :return: ''' # There are three types of hostnames: # 1. Network names. How host is accessed from the network. # 2. Host aliases. They might be not available in all the network or only locally (/etc/hosts) # 3. Convention names, an internal nodename. class DistinctList(list): ''' List, which allows one to append only distinct objects. Needs to work on Python 2.6, because of collections.OrderedDict only since 2.7 version. Override 'filter()' for custom filtering. ''' localhost_matchers = [r'localhost.*', r'ip6-.*', r'127[.]\d', r'0\.0\.0\.0', r'::1.*', r'ipv6-.*', r'fe00::.*', r'fe02::.*', r'1.0.0.*.ip6.arpa'] def append(self, p_object): if p_object and p_object not in self and not self.filter(p_object): super(DistinctList, self).append(p_object) return self def extend(self, iterable): for obj in iterable: self.append(obj) return self def filter(self, element): 'Returns True if element needs to be filtered' for rgx in self.localhost_matchers: if re.match(rgx, element): return True def first(self): return self and self[0] or None hostname = socket.gethostname() hosts = DistinctList().append( salt.utils.stringutils.to_unicode(socket.getfqdn(salt.utils.stringutils.to_bytes(hostname))) ).append(platform.node()).append(hostname) if not hosts: try: for a_nfo in socket.getaddrinfo(hosts.first() or 'localhost', None, socket.AF_INET, socket.SOCK_RAW, socket.IPPROTO_IP, socket.AI_CANONNAME): if len(a_nfo) > 3: hosts.append(a_nfo[3]) except socket.gaierror: log.warning('Cannot resolve address %s info via socket: %s', hosts.first() or 'localhost (N/A)', socket.gaierror) # Universal method for everywhere (Linux, Slowlaris, Windows etc) for f_name in ('/etc/hostname', '/etc/nodename', '/etc/hosts', r'{win}\system32\drivers\etc\hosts'.format(win=os.getenv('WINDIR'))): try: with salt.utils.files.fopen(f_name) as f_hdl: for line in f_hdl: line = salt.utils.stringutils.to_unicode(line) hst = line.strip().split('#')[0].strip().split() if hst: if hst[0][:4] in ('127.', '::1') or len(hst) == 1: hosts.extend(hst) except IOError: pass # include public and private ipaddresses return hosts.extend([addr for addr in ip_addrs() if not ipaddress.ip_address(addr).is_loopback]) def generate_minion_id(): ''' Return only first element of the hostname from all possible list. :return: ''' try: ret = salt.utils.stringutils.to_unicode(_generate_minion_id().first()) except TypeError: ret = None return ret or 'localhost' def get_socket(addr, type=socket.SOCK_STREAM, proto=0): ''' Return a socket object for the addr IP-version agnostic ''' version = ipaddress.ip_address(addr).version if version == 4: family = socket.AF_INET elif version == 6: family = socket.AF_INET6 return socket.socket(family, type, proto) def get_fqhostname(): ''' Returns the fully qualified hostname ''' # try getaddrinfo() fqdn = None try: addrinfo = socket.getaddrinfo( socket.gethostname(), 0, socket.AF_UNSPEC, socket.SOCK_STREAM, socket.SOL_TCP, socket.AI_CANONNAME ) for info in addrinfo: # info struct [family, socktype, proto, canonname, sockaddr] # On Windows `canonname` can be an empty string # This can cause the function to return `None` if len(info) > 3 and info[3]: fqdn = info[3] break except socket.gaierror: pass # NOTE: this used to log.error() but it was later disabled except socket.error as err: log.debug('socket.getaddrinfo() failure while finding fqdn: %s', err) if fqdn is None: fqdn = socket.getfqdn() return fqdn def ip_to_host(ip): ''' Returns the hostname of a given IP ''' try: hostname, aliaslist, ipaddrlist = socket.gethostbyaddr(ip) except Exception as exc: log.debug('salt.utils.network.ip_to_host(%r) failed: %s', ip, exc) hostname = None return hostname # pylint: enable=C0103 def is_reachable_host(entity_name): ''' Returns a bool telling if the entity name is a reachable host (IPv4/IPv6/FQDN/etc). :param hostname: :return: ''' try: assert type(socket.getaddrinfo(entity_name, 0, 0, 0, 0)) == list ret = True except socket.gaierror: ret = False return ret def is_ip(ip): ''' Returns a bool telling if the passed IP is a valid IPv4 or IPv6 address. ''' return is_ipv4(ip) or is_ipv6(ip) def is_ipv4(ip): ''' Returns a bool telling if the value passed to it was a valid IPv4 address ''' try: return ipaddress.ip_address(ip).version == 4 except ValueError: return False def is_ipv6(ip): ''' Returns a bool telling if the value passed to it was a valid IPv6 address ''' try: return ipaddress.ip_address(ip).version == 6 except ValueError: return False def is_subnet(cidr): ''' Returns a bool telling if the passed string is an IPv4 or IPv6 subnet ''' return is_ipv4_subnet(cidr) or is_ipv6_subnet(cidr) def is_ipv4_subnet(cidr): ''' Returns a bool telling if the passed string is an IPv4 subnet ''' try: return '/' in cidr and bool(ipaddress.IPv4Network(cidr)) except Exception: return False def is_ipv6_subnet(cidr): ''' Returns a bool telling if the passed string is an IPv6 subnet ''' try: return '/' in cidr and bool(ipaddress.IPv6Network(cidr)) except Exception: return False @jinja_filter('is_ip') def is_ip_filter(ip, options=None): ''' Returns a bool telling if the passed IP is a valid IPv4 or IPv6 address. ''' return is_ipv4_filter(ip, options=options) or is_ipv6_filter(ip, options=options) def _ip_options_global(ip_obj, version): return not ip_obj.is_private def _ip_options_multicast(ip_obj, version): return ip_obj.is_multicast def _ip_options_loopback(ip_obj, version): return ip_obj.is_loopback def _ip_options_link_local(ip_obj, version): return ip_obj.is_link_local def _ip_options_private(ip_obj, version): return ip_obj.is_private def _ip_options_reserved(ip_obj, version): return ip_obj.is_reserved def _ip_options_site_local(ip_obj, version): if version == 6: return ip_obj.is_site_local return False def _ip_options_unspecified(ip_obj, version): return ip_obj.is_unspecified def _ip_options(ip_obj, version, options=None): # will process and IP options options_fun_map = { 'global': _ip_options_global, 'link-local': _ip_options_link_local, 'linklocal': _ip_options_link_local, 'll': _ip_options_link_local, 'link_local': _ip_options_link_local, 'loopback': _ip_options_loopback, 'lo': _ip_options_loopback, 'multicast': _ip_options_multicast, 'private': _ip_options_private, 'public': _ip_options_global, 'reserved': _ip_options_reserved, 'site-local': _ip_options_site_local, 'sl': _ip_options_site_local, 'site_local': _ip_options_site_local, 'unspecified': _ip_options_unspecified } if not options: return six.text_type(ip_obj) # IP version already checked options_list = [option.strip() for option in options.split(',')] for option, fun in options_fun_map.items(): if option in options_list: fun_res = fun(ip_obj, version) if not fun_res: return None # stop at first failed test # else continue return six.text_type(ip_obj) def _is_ipv(ip, version, options=None): if not version: version = 4 if version not in (4, 6): return None try: ip_obj = ipaddress.ip_address(ip) except ValueError: # maybe it is an IP network try: ip_obj = ipaddress.ip_interface(ip) except ValueError: # nope, still not :( return None if not ip_obj.version == version: return None # has the right version, let's move on return _ip_options(ip_obj, version, options=options) @jinja_filter('is_ipv4') def is_ipv4_filter(ip, options=None): ''' Returns a bool telling if the value passed to it was a valid IPv4 address. ip The IP address. net: False Consider IP addresses followed by netmask. options CSV of options regarding the nature of the IP address. E.g.: loopback, multicast, private etc. ''' _is_ipv4 = _is_ipv(ip, 4, options=options) return isinstance(_is_ipv4, six.string_types) @jinja_filter('is_ipv6') def is_ipv6_filter(ip, options=None): ''' Returns a bool telling if the value passed to it was a valid IPv6 address. ip The IP address. net: False Consider IP addresses followed by netmask. options CSV of options regarding the nature of the IP address. E.g.: loopback, multicast, private etc. ''' _is_ipv6 = _is_ipv(ip, 6, options=options) return isinstance(_is_ipv6, six.string_types) def _ipv_filter(value, version, options=None): if version not in (4, 6): return if isinstance(value, (six.string_types, six.text_type, six.binary_type)): return _is_ipv(value, version, options=options) # calls is_ipv4 or is_ipv6 for `value` elif isinstance(value, (list, tuple, types.GeneratorType)): # calls is_ipv4 or is_ipv6 for each element in the list # os it filters and returns only those elements having the desired IP version return [ _is_ipv(addr, version, options=options) for addr in value if _is_ipv(addr, version, options=options) is not None ] return None @jinja_filter('ipv4') def ipv4(value, options=None): ''' Filters a list and returns IPv4 values only. ''' return _ipv_filter(value, 4, options=options) @jinja_filter('ipv6') def ipv6(value, options=None): ''' Filters a list and returns IPv6 values only. ''' return _ipv_filter(value, 6, options=options) @jinja_filter('ipaddr') def ipaddr(value, options=None): ''' Filters and returns only valid IP objects. ''' ipv4_obj = ipv4(value, options=options) ipv6_obj = ipv6(value, options=options) if ipv4_obj is None or ipv6_obj is None: # an IP address can be either IPv4 either IPv6 # therefofe if the value passed as arg is not a list, at least one of the calls above will return None # if one of them is none, means that we should return only one of them return ipv4_obj or ipv6_obj # one of them else: return ipv4_obj + ipv6_obj # extend lists def _filter_ipaddr(value, options, version=None): ipaddr_filter_out = None if version: if version == 4: ipaddr_filter_out = ipv4(value, options) elif version == 6: ipaddr_filter_out = ipv6(value, options) else: ipaddr_filter_out = ipaddr(value, options) if not ipaddr_filter_out: return if not isinstance(ipaddr_filter_out, (list, tuple, types.GeneratorType)): ipaddr_filter_out = [ipaddr_filter_out] return ipaddr_filter_out @jinja_filter('ip_host') def ip_host(value, options=None, version=None): ''' Returns the interfaces IP address, e.g.: 192.168.0.1/28. ''' ipaddr_filter_out = _filter_ipaddr(value, options=options, version=version) if not ipaddr_filter_out: return if not isinstance(value, (list, tuple, types.GeneratorType)): return six.text_type(ipaddress.ip_interface(ipaddr_filter_out[0])) return [six.text_type(ipaddress.ip_interface(ip_a)) for ip_a in ipaddr_filter_out] def _network_hosts(ip_addr_entry): return [ six.text_type(host) for host in ipaddress.ip_network(ip_addr_entry, strict=False).hosts() ] @jinja_filter('network_hosts') def network_hosts(value, options=None, version=None): ''' Return the list of hosts within a network. .. note:: When running this command with a large IPv6 network, the command will take a long time to gather all of the hosts. ''' ipaddr_filter_out = _filter_ipaddr(value, options=options, version=version) if not ipaddr_filter_out: return if not isinstance(value, (list, tuple, types.GeneratorType)): return _network_hosts(ipaddr_filter_out[0]) return [ _network_hosts(ip_a) for ip_a in ipaddr_filter_out ] def _network_size(ip_addr_entry): return ipaddress.ip_network(ip_addr_entry, strict=False).num_addresses @jinja_filter('network_size') def network_size(value, options=None, version=None): ''' Get the size of a network. ''' ipaddr_filter_out = _filter_ipaddr(value, options=options, version=version) if not ipaddr_filter_out: return if not isinstance(value, (list, tuple, types.GeneratorType)): return _network_size(ipaddr_filter_out[0]) return [ _network_size(ip_a) for ip_a in ipaddr_filter_out ] def natural_ipv4_netmask(ip, fmt='prefixlen'): ''' Returns the "natural" mask of an IPv4 address ''' bits = _ipv4_to_bits(ip) if bits.startswith('11'): mask = '24' elif bits.startswith('1'): mask = '16' else: mask = '8' if fmt == 'netmask': return cidr_to_ipv4_netmask(mask) else: return '/' + mask def rpad_ipv4_network(ip): ''' Returns an IP network address padded with zeros. Ex: '192.168.3' -> '192.168.3.0' '10.209' -> '10.209.0.0' ''' return '.'.join(itertools.islice(itertools.chain(ip.split('.'), '0000'), 0, 4)) def cidr_to_ipv4_netmask(cidr_bits): ''' Returns an IPv4 netmask ''' try: cidr_bits = int(cidr_bits) if not 1 <= cidr_bits <= 32: return '' except ValueError: return '' netmask = '' for idx in range(4): if idx: netmask += '.' if cidr_bits >= 8: netmask += '255' cidr_bits -= 8 else: netmask += '{0:d}'.format(256 - (2 ** (8 - cidr_bits))) cidr_bits = 0 return netmask def _number_of_set_bits_to_ipv4_netmask(set_bits): # pylint: disable=C0103 ''' Returns an IPv4 netmask from the integer representation of that mask. Ex. 0xffffff00 -> '255.255.255.0' ''' return cidr_to_ipv4_netmask(_number_of_set_bits(set_bits)) # pylint: disable=C0103 def _number_of_set_bits(x): ''' Returns the number of bits that are set in a 32bit int ''' # Taken from http://stackoverflow.com/a/4912729. Many thanks! x -= (x >> 1) & 0x55555555 x = ((x >> 2) & 0x33333333) + (x & 0x33333333) x = ((x >> 4) + x) & 0x0f0f0f0f x += x >> 8 x += x >> 16 return x & 0x0000003f # pylint: enable=C0103 def _interfaces_ip(out): ''' Uses ip to return a dictionary of interfaces with various information about each (up/down state, ip address, netmask, and hwaddr) ''' ret = dict() def parse_network(value, cols): ''' Return a tuple of ip, netmask, broadcast based on the current set of cols ''' brd = None scope = None if '/' in value: # we have a CIDR in this address ip, cidr = value.split('/') # pylint: disable=C0103 else: ip = value # pylint: disable=C0103 cidr = 32 if type_ == 'inet': mask = cidr_to_ipv4_netmask(int(cidr)) if 'brd' in cols: brd = cols[cols.index('brd') + 1] elif type_ == 'inet6': mask = cidr if 'scope' in cols: scope = cols[cols.index('scope') + 1] return (ip, mask, brd, scope) groups = re.compile('\r?\n\\d').split(out) for group in groups: iface = None data = dict() for line in group.splitlines(): if ' ' not in line: continue match = re.match(r'^\d*:\s+([\w.\-]+)(?:@)?([\w.\-]+)?:\s+<(.+)>', line) if match: iface, parent, attrs = match.groups() if 'UP' in attrs.split(','): data['up'] = True else: data['up'] = False if parent: data['parent'] = parent continue cols = line.split() if len(cols) >= 2: type_, value = tuple(cols[0:2]) iflabel = cols[-1:][0] if type_ in ('inet', 'inet6'): if 'secondary' not in cols: ipaddr, netmask, broadcast, scope = parse_network(value, cols) if type_ == 'inet': if 'inet' not in data: data['inet'] = list() addr_obj = dict() addr_obj['address'] = ipaddr addr_obj['netmask'] = netmask addr_obj['broadcast'] = broadcast addr_obj['label'] = iflabel data['inet'].append(addr_obj) elif type_ == 'inet6': if 'inet6' not in data: data['inet6'] = list() addr_obj = dict() addr_obj['address'] = ipaddr addr_obj['prefixlen'] = netmask addr_obj['scope'] = scope data['inet6'].append(addr_obj) else: if 'secondary' not in data: data['secondary'] = list() ip_, mask, brd, scp = parse_network(value, cols) data['secondary'].append({ 'type': type_, 'address': ip_, 'netmask': mask, 'broadcast': brd, 'label': iflabel, }) del ip_, mask, brd, scp elif type_.startswith('link'): data['hwaddr'] = value if iface: ret[iface] = data del iface, data return ret def _interfaces_ifconfig(out): ''' Uses ifconfig to return a dictionary of interfaces with various information about each (up/down state, ip address, netmask, and hwaddr) ''' ret = dict() piface = re.compile(r'^([^\s:]+)') pmac = re.compile('.*?(?:HWaddr|ether|address:|lladdr) ([0-9a-fA-F:]+)') if salt.utils.platform.is_sunos(): pip = re.compile(r'.*?(?:inet\s+)([0-9]+\.[0-9]+\.[0-9]+\.[0-9]+)(.*)') pip6 = re.compile('.*?(?:inet6 )([0-9a-fA-F:]+)') pmask6 = re.compile(r'.*?(?:inet6 [0-9a-fA-F:]+/(\d+)).*') else: pip = re.compile(r'.*?(?:inet addr:|inet [^\d]*)(.*?)\s') pip6 = re.compile('.*?(?:inet6 addr: (.*?)/|inet6 )([0-9a-fA-F:]+)') pmask6 = re.compile(r'.*?(?:inet6 addr: [0-9a-fA-F:]+/(\d+)|prefixlen (\d+))(?: Scope:([a-zA-Z]+)| scopeid (0x[0-9a-fA-F]))?') pmask = re.compile(r'.*?(?:Mask:|netmask )(?:((?:0x)?[0-9a-fA-F]{8})|([\d\.]+))') pupdown = re.compile('UP') pbcast = re.compile(r'.*?(?:Bcast:|broadcast )([\d\.]+)') groups = re.compile('\r?\n(?=\\S)').split(out) for group in groups: data = dict() iface = '' updown = False for line in group.splitlines(): miface = piface.match(line) mmac = pmac.match(line) mip = pip.match(line) mip6 = pip6.match(line) mupdown = pupdown.search(line) if miface: iface = miface.group(1) if mmac: data['hwaddr'] = mmac.group(1) if salt.utils.platform.is_sunos(): expand_mac = [] for chunk in data['hwaddr'].split(':'): expand_mac.append('0{0}'.format(chunk) if len(chunk) < 2 else '{0}'.format(chunk)) data['hwaddr'] = ':'.join(expand_mac) if mip: if 'inet' not in data: data['inet'] = list() addr_obj = dict() addr_obj['address'] = mip.group(1) mmask = pmask.match(line) if mmask: if mmask.group(1): mmask = _number_of_set_bits_to_ipv4_netmask( int(mmask.group(1), 16)) else: mmask = mmask.group(2) addr_obj['netmask'] = mmask mbcast = pbcast.match(line) if mbcast: addr_obj['broadcast'] = mbcast.group(1) data['inet'].append(addr_obj) if mupdown: updown = True if mip6: if 'inet6' not in data: data['inet6'] = list() addr_obj = dict() addr_obj['address'] = mip6.group(1) or mip6.group(2) mmask6 = pmask6.match(line) if mmask6: addr_obj['prefixlen'] = mmask6.group(1) or mmask6.group(2) if not salt.utils.platform.is_sunos(): ipv6scope = mmask6.group(3) or mmask6.group(4) addr_obj['scope'] = ipv6scope.lower() if ipv6scope is not None else ipv6scope # SunOS sometimes has ::/0 as inet6 addr when using addrconf if not salt.utils.platform.is_sunos() \ or addr_obj['address'] != '::' \ and addr_obj['prefixlen'] != 0: data['inet6'].append(addr_obj) data['up'] = updown if iface in ret: # SunOS optimization, where interfaces occur twice in 'ifconfig -a' # output with the same name: for ipv4 and then for ipv6 addr family. # Every instance has it's own 'UP' status and we assume that ipv4 # status determines global interface status. # # merge items with higher priority for older values # after that merge the inet and inet6 sub items for both ret[iface] = dict(list(data.items()) + list(ret[iface].items())) if 'inet' in data: ret[iface]['inet'].extend(x for x in data['inet'] if x not in ret[iface]['inet']) if 'inet6' in data: ret[iface]['inet6'].extend(x for x in data['inet6'] if x not in ret[iface]['inet6']) else: ret[iface] = data del data return ret def linux_interfaces(): ''' Obtain interface information for *NIX/BSD variants ''' ifaces = dict() ip_path = salt.utils.path.which('ip') ifconfig_path = None if ip_path else salt.utils.path.which('ifconfig') if ip_path: cmd1 = subprocess.Popen( '{0} link show'.format(ip_path), shell=True, close_fds=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT).communicate()[0] cmd2 = subprocess.Popen( '{0} addr show'.format(ip_path), shell=True, close_fds=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT).communicate()[0] ifaces = _interfaces_ip("{0}\n{1}".format( salt.utils.stringutils.to_str(cmd1), salt.utils.stringutils.to_str(cmd2))) elif ifconfig_path: cmd = subprocess.Popen( '{0} -a'.format(ifconfig_path), shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT).communicate()[0] ifaces = _interfaces_ifconfig(salt.utils.stringutils.to_str(cmd)) return ifaces def _netbsd_interfaces_ifconfig(out): ''' Uses ifconfig to return a dictionary of interfaces with various information about each (up/down state, ip address, netmask, and hwaddr) ''' ret = dict() piface = re.compile(r'^([^\s:]+)') pmac = re.compile('.*?address: ([0-9a-f:]+)') pip = re.compile(r'.*?inet [^\d]*(.*?)/([\d]*)\s') pip6 = re.compile(r'.*?inet6 ([0-9a-f:]+)%([a-zA-Z0-9]*)/([\d]*)\s') pupdown = re.compile('UP') pbcast = re.compile(r'.*?broadcast ([\d\.]+)') groups = re.compile('\r?\n(?=\\S)').split(out) for group in groups: data = dict() iface = '' updown = False for line in group.splitlines(): miface = piface.match(line) mmac = pmac.match(line) mip = pip.match(line) mip6 = pip6.match(line) mupdown = pupdown.search(line) if miface: iface = miface.group(1) if mmac: data['hwaddr'] = mmac.group(1) if mip: if 'inet' not in data: data['inet'] = list() addr_obj = dict() addr_obj['address'] = mip.group(1) mmask = mip.group(2) if mip.group(2): addr_obj['netmask'] = cidr_to_ipv4_netmask(mip.group(2)) mbcast = pbcast.match(line) if mbcast: addr_obj['broadcast'] = mbcast.group(1) data['inet'].append(addr_obj) if mupdown: updown = True if mip6: if 'inet6' not in data: data['inet6'] = list() addr_obj = dict() addr_obj['address'] = mip6.group(1) mmask6 = mip6.group(3) addr_obj['scope'] = mip6.group(2) addr_obj['prefixlen'] = mip6.group(3) data['inet6'].append(addr_obj) data['up'] = updown ret[iface] = data del data return ret def netbsd_interfaces(): ''' Obtain interface information for NetBSD >= 8 where the ifconfig output diverged from other BSD variants (Netmask is now part of the address) ''' # NetBSD versions prior to 8.0 can still use linux_interfaces() if LooseVersion(os.uname()[2]) < LooseVersion('8.0'): return linux_interfaces() ifconfig_path = salt.utils.path.which('ifconfig') cmd = subprocess.Popen( '{0} -a'.format(ifconfig_path), shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT).communicate()[0] return _netbsd_interfaces_ifconfig(salt.utils.stringutils.to_str(cmd)) def _interfaces_ipconfig(out): ''' Returns a dictionary of interfaces with various information about each (up/down state, ip address, netmask, and hwaddr) NOTE: This is not used by any function and may be able to be removed in the future. ''' ifaces = dict() iface = None adapter_iface_regex = re.compile(r'adapter (\S.+):$') for line in out.splitlines(): if not line: continue # TODO what does Windows call Infiniband and 10/40gige adapters if line.startswith('Ethernet'): iface = ifaces[adapter_iface_regex.search(line).group(1)] iface['up'] = True addr = None continue if iface: key, val = line.split(',', 1) key = key.strip(' .') val = val.strip() if addr and key == 'Subnet Mask': addr['netmask'] = val elif key in ('IP Address', 'IPv4 Address'): if 'inet' not in iface: iface['inet'] = list() addr = {'address': val.rstrip('(Preferred)'), 'netmask': None, 'broadcast': None} # TODO find the broadcast iface['inet'].append(addr) elif 'IPv6 Address' in key: if 'inet6' not in iface: iface['inet'] = list() # XXX What is the prefixlen!? addr = {'address': val.rstrip('(Preferred)'), 'prefixlen': None} iface['inet6'].append(addr) elif key == 'Physical Address': iface['hwaddr'] = val elif key == 'Media State': # XXX seen used for tunnel adaptors # might be useful iface['up'] = (val != 'Media disconnected') def win_interfaces(): ''' Obtain interface information for Windows systems ''' with salt.utils.winapi.Com(): c = wmi.WMI() ifaces = {} for iface in c.Win32_NetworkAdapterConfiguration(IPEnabled=1): ifaces[iface.Description] = dict() if iface.MACAddress: ifaces[iface.Description]['hwaddr'] = iface.MACAddress if iface.IPEnabled: ifaces[iface.Description]['up'] = True for ip in iface.IPAddress: if '.' in ip: if 'inet' not in ifaces[iface.Description]: ifaces[iface.Description]['inet'] = [] item = {'address': ip, 'label': iface.Description} if iface.DefaultIPGateway: broadcast = next((i for i in iface.DefaultIPGateway if '.' in i), '') if broadcast: item['broadcast'] = broadcast if iface.IPSubnet: netmask = next((i for i in iface.IPSubnet if '.' in i), '') if netmask: item['netmask'] = netmask ifaces[iface.Description]['inet'].append(item) if ':' in ip: if 'inet6' not in ifaces[iface.Description]: ifaces[iface.Description]['inet6'] = [] item = {'address': ip} if iface.DefaultIPGateway: broadcast = next((i for i in iface.DefaultIPGateway if ':' in i), '') if broadcast: item['broadcast'] = broadcast if iface.IPSubnet: netmask = next((i for i in iface.IPSubnet if ':' in i), '') if netmask: item['netmask'] = netmask ifaces[iface.Description]['inet6'].append(item) else: ifaces[iface.Description]['up'] = False return ifaces def interfaces(): ''' Return a dictionary of information about all the interfaces on the minion ''' if salt.utils.platform.is_windows(): return win_interfaces() elif salt.utils.platform.is_netbsd(): return netbsd_interfaces() else: return linux_interfaces() def get_net_start(ipaddr, netmask): ''' Return the address of the network ''' net = ipaddress.ip_network('{0}/{1}'.format(ipaddr, netmask), strict=False) return six.text_type(net.network_address) def get_net_size(mask): ''' Turns an IPv4 netmask into it's corresponding prefix length (255.255.255.0 -> 24 as in 192.168.1.10/24). ''' binary_str = '' for octet in mask.split('.'): binary_str += bin(int(octet))[2:].zfill(8) return len(binary_str.rstrip('0')) def calc_net(ipaddr, netmask=None): ''' Takes IP (CIDR notation supported) and optionally netmask and returns the network in CIDR-notation. (The IP can be any IP inside the subnet) ''' if netmask is not None: ipaddr = '{0}/{1}'.format(ipaddr, netmask) return six.text_type(ipaddress.ip_network(ipaddr, strict=False)) def _ipv4_to_bits(ipaddr): ''' Accepts an IPv4 dotted quad and returns a string representing its binary counterpart ''' return ''.join([bin(int(x))[2:].rjust(8, '0') for x in ipaddr.split('.')]) def _get_iface_info(iface): ''' If `iface` is available, return interface info and no error, otherwise return no info and log and return an error ''' iface_info = interfaces() if iface in iface_info.keys(): return iface_info, False else: error_msg = ('Interface "{0}" not in available interfaces: "{1}"' ''.format(iface, '", "'.join(iface_info.keys()))) log.error(error_msg) return None, error_msg def _hw_addr_aix(iface): ''' Return the hardware address (a.k.a. MAC address) for a given interface on AIX MAC address not available in through interfaces ''' cmd = subprocess.Popen( 'entstat -d {0} | grep \'Hardware Address\''.format(iface), shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT).communicate()[0] if cmd: comps = cmd.split(' ') if len(comps) == 3: mac_addr = comps[2].strip('\'').strip() return mac_addr error_msg = ('Interface "{0}" either not available or does not contain a hardware address'.format(iface)) log.error(error_msg) return error_msg def hw_addr(iface): ''' Return the hardware address (a.k.a. MAC address) for a given interface .. versionchanged:: 2016.11.4 Added support for AIX ''' if salt.utils.platform.is_aix(): return _hw_addr_aix iface_info, error = _get_iface_info(iface) if error is False: return iface_info.get(iface, {}).get('hwaddr', '') else: return error def interface(iface): ''' Return the details of `iface` or an error if it does not exist ''' iface_info, error = _get_iface_info(iface) if error is False: return iface_info.get(iface, {}).get('inet', '') else: return error def interface_ip(iface): ''' Return `iface` IPv4 addr or an error if `iface` does not exist ''' iface_info, error = _get_iface_info(iface) if error is False: inet = iface_info.get(iface, {}).get('inet', None) return inet[0].get('address', '') if inet else '' else: return error def _subnets(proto='inet', interfaces_=None): ''' Returns a list of subnets to which the host belongs ''' if interfaces_ is None: ifaces = interfaces() elif isinstance(interfaces_, list): ifaces = {} for key, value in six.iteritems(interfaces()): if key in interfaces_: ifaces[key] = value else: ifaces = {interfaces_: interfaces().get(interfaces_, {})} ret = set() if proto == 'inet': subnet = 'netmask' dflt_cidr = 32 elif proto == 'inet6': subnet = 'prefixlen' dflt_cidr = 128 else: log.error('Invalid proto %s calling subnets()', proto) return for ip_info in six.itervalues(ifaces): addrs = ip_info.get(proto, []) addrs.extend([addr for addr in ip_info.get('secondary', []) if addr.get('type') == proto]) for intf in addrs: if subnet in intf: intf = ipaddress.ip_interface('{0}/{1}'.format(intf['address'], intf[subnet])) else: intf = ipaddress.ip_interface('{0}/{1}'.format(intf['address'], dflt_cidr)) if not intf.is_loopback: ret.add(intf.network) return [six.text_type(net) for net in sorted(ret)] def subnets(interfaces=None): ''' Returns a list of IPv4 subnets to which the host belongs ''' return _subnets('inet', interfaces_=interfaces) def subnets6(): ''' Returns a list of IPv6 subnets to which the host belongs ''' return _subnets('inet6') def _ip_addrs(interface=None, include_loopback=False, interface_data=None, proto='inet'): ''' Return the full list of IP adresses matching the criteria proto = inet|inet6 ''' ret = set() ifaces = interface_data \ if isinstance(interface_data, dict) \ else interfaces() if interface is None: target_ifaces = ifaces else: target_ifaces = dict([(k, v) for k, v in six.iteritems(ifaces) if k == interface]) if not target_ifaces: log.error('Interface %s not found.', interface) for ip_info in six.itervalues(target_ifaces): addrs = ip_info.get(proto, []) addrs.extend([addr for addr in ip_info.get('secondary', []) if addr.get('type') == proto]) for addr in addrs: addr = ipaddress.ip_address(addr.get('address')) if not addr.is_loopback or include_loopback: ret.add(addr) return [six.text_type(addr) for addr in sorted(ret)] def ip_addrs(interface=None, include_loopback=False, interface_data=None): ''' Returns a list of IPv4 addresses assigned to the host. 127.0.0.1 is ignored, unless 'include_loopback=True' is indicated. If 'interface' is provided, then only IP addresses from that interface will be returned. ''' return _ip_addrs(interface, include_loopback, interface_data, 'inet') def ip_addrs6(interface=None, include_loopback=False, interface_data=None): ''' Returns a list of IPv6 addresses assigned to the host. ::1 is ignored, unless 'include_loopback=True' is indicated. If 'interface' is provided, then only IP addresses from that interface will be returned. ''' return _ip_addrs(interface, include_loopback, interface_data, 'inet6') def hex2ip(hex_ip, invert=False): ''' Convert a hex string to an ip, if a failure occurs the original hex is returned. If 'invert=True' assume that ip from /proc/net/<proto> ''' if len(hex_ip) == 32: # ipv6 ip = [] for i in range(0, 32, 8): ip_part = hex_ip[i:i + 8] ip_part = [ip_part[x:x + 2] for x in range(0, 8, 2)] if invert: ip.append("{0[3]}{0[2]}:{0[1]}{0[0]}".format(ip_part)) else: ip.append("{0[0]}{0[1]}:{0[2]}{0[3]}".format(ip_part)) try: address = ipaddress.IPv6Address(":".join(ip)) if address.ipv4_mapped: return str(address.ipv4_mapped) else: return address.compressed except ipaddress.AddressValueError as ex: log.error('hex2ip - ipv6 address error: %s', ex) return hex_ip try: hip = int(hex_ip, 16) except ValueError: return hex_ip if invert: return '{3}.{2}.{1}.{0}'.format(hip >> 24 & 255, hip >> 16 & 255, hip >> 8 & 255, hip & 255) return '{0}.{1}.{2}.{3}'.format(hip >> 24 & 255, hip >> 16 & 255, hip >> 8 & 255, hip & 255) def mac2eui64(mac, prefix=None): ''' Convert a MAC address to a EUI64 identifier or, with prefix provided, a full IPv6 address ''' # http://tools.ietf.org/html/rfc4291#section-2.5.1 eui64 = re.sub(r'[.:-]', '', mac).lower() eui64 = eui64[0:6] + 'fffe' + eui64[6:] eui64 = hex(int(eui64[0:2], 16) | 2)[2:].zfill(2) + eui64[2:] if prefix is None: return ':'.join(re.findall(r'.{4}', eui64)) else: try: net = ipaddress.ip_network(prefix, strict=False) euil = int('0x{0}'.format(eui64), 16) return '{0}/{1}'.format(net[euil], net.prefixlen) except Exception: return def active_tcp(): ''' Return a dict describing all active tcp connections as quickly as possible ''' ret = {} for statf in ['/proc/net/tcp', '/proc/net/tcp6']: if os.path.isfile(statf): with salt.utils.files.fopen(statf, 'rb') as fp_: for line in fp_: line = salt.utils.stringutils.to_unicode(line) if line.strip().startswith('sl'): continue iret = _parse_tcp_line(line) sl = next(iter(iret)) if iret[sl]['state'] == 1: # 1 is ESTABLISHED del iret[sl]['state'] ret[len(ret)] = iret[sl] return ret def local_port_tcp(port): ''' Return a set of remote ip addrs attached to the specified local port ''' ret = _remotes_on(port, 'local_port') return ret def remote_port_tcp(port): ''' Return a set of ip addrs the current host is connected to on given port ''' ret = _remotes_on(port, 'remote_port') return ret def _remotes_on(port, which_end): ''' Return a set of ip addrs active tcp connections ''' port = int(port) ret = _netlink_tool_remote_on(port, which_end) if ret is not None: return ret ret = set() proc_available = False for statf in ['/proc/net/tcp', '/proc/net/tcp6']: if os.path.isfile(statf): proc_available = True with salt.utils.files.fopen(statf, 'r') as fp_: for line in fp_: line = salt.utils.stringutils.to_unicode(line) if line.strip().startswith('sl'): continue iret = _parse_tcp_line(line) sl = next(iter(iret)) if iret[sl][which_end] == port and iret[sl]['state'] == 1: # 1 is ESTABLISHED ret.add(iret[sl]['remote_addr']) if not proc_available: # Fallback to use OS specific tools if salt.utils.platform.is_sunos(): return _sunos_remotes_on(port, which_end) if salt.utils.platform.is_freebsd(): return _freebsd_remotes_on(port, which_end) if salt.utils.platform.is_netbsd(): return _netbsd_remotes_on(port, which_end) if salt.utils.platform.is_openbsd(): return _openbsd_remotes_on(port, which_end) if salt.utils.platform.is_windows(): return _windows_remotes_on(port, which_end) if salt.utils.platform.is_aix(): return _aix_remotes_on(port, which_end) return _linux_remotes_on(port, which_end) return ret def _parse_tcp_line(line): ''' Parse a single line from the contents of /proc/net/tcp or /proc/net/tcp6 ''' ret = {} comps = line.strip().split() sl = comps[0].rstrip(':') ret[sl] = {} l_addr, l_port = comps[1].split(':') r_addr, r_port = comps[2].split(':') ret[sl]['local_addr'] = hex2ip(l_addr, True) ret[sl]['local_port'] = int(l_port, 16) ret[sl]['remote_addr'] = hex2ip(r_addr, True) ret[sl]['remote_port'] = int(r_port, 16) ret[sl]['state'] = int(comps[3], 16) return ret def _netlink_tool_remote_on(port, which_end): ''' Returns set of ipv4 host addresses of remote established connections on local or remote tcp port. Parses output of shell 'ss' to get connections [root@salt-master ~]# ss -ant State Recv-Q Send-Q Local Address:Port Peer Address:Port LISTEN 0 511 *:80 *:* LISTEN 0 128 *:22 *:* ESTAB 0 0 127.0.0.1:56726 127.0.0.1:4505 ''' remotes = set() valid = False try: data = subprocess.check_output(['ss', '-ant']) # pylint: disable=minimum-python-version except subprocess.CalledProcessError: log.error('Failed ss') raise except OSError: # not command "No such file or directory" return None lines = salt.utils.stringutils.to_str(data).split('\n') for line in lines: if 'Address:Port' in line: # ss tools may not be valid valid = True continue elif 'ESTAB' not in line: continue chunks = line.split() local_host, local_port = chunks[3].split(':', 1) remote_host, remote_port = chunks[4].split(':', 1) if which_end == 'remote_port' and int(remote_port) != port: continue if which_end == 'local_port' and int(local_port) != port: continue remotes.add(remote_host) if valid is False: remotes = None return remotes def _sunos_remotes_on(port, which_end): ''' SunOS specific helper function. Returns set of ipv4 host addresses of remote established connections on local or remote tcp port. Parses output of shell 'netstat' to get connections [root@salt-master ~]# netstat -f inet -n TCP: IPv4 Local Address Remote Address Swind Send-Q Rwind Recv-Q State -------------------- -------------------- ----- ------ ----- ------ ----------- 10.0.0.101.4505 10.0.0.1.45329 1064800 0 1055864 0 ESTABLISHED 10.0.0.101.4505 10.0.0.100.50798 1064800 0 1055864 0 ESTABLISHED ''' remotes = set() try: data = subprocess.check_output(['netstat', '-f', 'inet', '-n']) # pylint: disable=minimum-python-version except subprocess.CalledProcessError: log.error('Failed netstat') raise lines = salt.utils.stringutils.to_str(data).split('\n') for line in lines: if 'ESTABLISHED' not in line: continue chunks = line.split() local_host, local_port = chunks[0].rsplit('.', 1) remote_host, remote_port = chunks[1].rsplit('.', 1) if which_end == 'remote_port' and int(remote_port) != port: continue if which_end == 'local_port' and int(local_port) != port: continue remotes.add(remote_host) return remotes def _freebsd_remotes_on(port, which_end): ''' Returns set of ipv4 host addresses of remote established connections on local tcp port port. Parses output of shell 'sockstat' (FreeBSD) to get connections $ sudo sockstat -4 USER COMMAND PID FD PROTO LOCAL ADDRESS FOREIGN ADDRESS root python2.7 1456 29 tcp4 *:4505 *:* root python2.7 1445 17 tcp4 *:4506 *:* root python2.7 1294 14 tcp4 127.0.0.1:11813 127.0.0.1:4505 root python2.7 1294 41 tcp4 127.0.0.1:61115 127.0.0.1:4506 $ sudo sockstat -4 -c -p 4506 USER COMMAND PID FD PROTO LOCAL ADDRESS FOREIGN ADDRESS root python2.7 1294 41 tcp4 127.0.0.1:61115 127.0.0.1:4506 ''' port = int(port) remotes = set() try: cmd = salt.utils.args.shlex_split('sockstat -4 -c -p {0}'.format(port)) data = subprocess.check_output(cmd) # pylint: disable=minimum-python-version except subprocess.CalledProcessError as ex: log.error('Failed "sockstat" with returncode = %s', ex.returncode) raise lines = salt.utils.stringutils.to_str(data).split('\n') for line in lines: chunks = line.split() if not chunks: continue # ['root', 'python2.7', '1456', '37', 'tcp4', # '127.0.0.1:4505-', '127.0.0.1:55703'] # print chunks if 'COMMAND' in chunks[1]: continue # ignore header if len(chunks) < 2: continue # sockstat -4 -c -p 4506 does this with high PIDs: # USER COMMAND PID FD PROTO LOCAL ADDRESS FOREIGN ADDRESS # salt-master python2.781106 35 tcp4 192.168.12.34:4506 192.168.12.45:60143 local = chunks[-2] remote = chunks[-1] lhost, lport = local.split(':') rhost, rport = remote.split(':') if which_end == 'local' and int(lport) != port: # ignore if local port not port continue if which_end == 'remote' and int(rport) != port: # ignore if remote port not port continue remotes.add(rhost) return remotes def _netbsd_remotes_on(port, which_end): ''' Returns set of ipv4 host addresses of remote established connections on local tcp port port. Parses output of shell 'sockstat' (NetBSD) to get connections $ sudo sockstat -4 -n USER COMMAND PID FD PROTO LOCAL ADDRESS FOREIGN ADDRESS root python2.7 1456 29 tcp *.4505 *.* root python2.7 1445 17 tcp *.4506 *.* root python2.7 1294 14 tcp 127.0.0.1.11813 127.0.0.1.4505 root python2.7 1294 41 tcp 127.0.0.1.61115 127.0.0.1.4506 $ sudo sockstat -4 -c -n -p 4506 USER COMMAND PID FD PROTO LOCAL ADDRESS FOREIGN ADDRESS root python2.7 1294 41 tcp 127.0.0.1.61115 127.0.0.1.4506 ''' port = int(port) remotes = set() try: cmd = salt.utils.args.shlex_split('sockstat -4 -c -n -p {0}'.format(port)) data = subprocess.check_output(cmd) # pylint: disable=minimum-python-version except subprocess.CalledProcessError as ex: log.error('Failed "sockstat" with returncode = %s', ex.returncode) raise lines = salt.utils.stringutils.to_str(data).split('\n') for line in lines: chunks = line.split() if not chunks: continue # ['root', 'python2.7', '1456', '37', 'tcp', # '127.0.0.1.4505-', '127.0.0.1.55703'] # print chunks if 'COMMAND' in chunks[1]: continue # ignore header if len(chunks) < 2: continue local = chunks[5].split('.') lport = local.pop() lhost = '.'.join(local) remote = chunks[6].split('.') rport = remote.pop() rhost = '.'.join(remote) if which_end == 'local' and int(lport) != port: # ignore if local port not port continue if which_end == 'remote' and int(rport) != port: # ignore if remote port not port continue remotes.add(rhost) return remotes def _openbsd_remotes_on(port, which_end): ''' OpenBSD specific helper function. Returns set of ipv4 host addresses of remote established connections on local or remote tcp port. Parses output of shell 'netstat' to get connections $ netstat -nf inet Active Internet connections Proto Recv-Q Send-Q Local Address Foreign Address (state) tcp 0 0 10.0.0.101.4505 10.0.0.1.45329 ESTABLISHED tcp 0 0 10.0.0.101.4505 10.0.0.100.50798 ESTABLISHED ''' remotes = set() try: data = subprocess.check_output(['netstat', '-nf', 'inet']) # pylint: disable=minimum-python-version except subprocess.CalledProcessError: log.error('Failed netstat') raise lines = data.split('\n') for line in lines: if 'ESTABLISHED' not in line: continue chunks = line.split() local_host, local_port = chunks[3].rsplit('.', 1) remote_host, remote_port = chunks[4].rsplit('.', 1) if which_end == 'remote_port' and int(remote_port) != port: continue if which_end == 'local_port' and int(local_port) != port: continue remotes.add(remote_host) return remotes def _windows_remotes_on(port, which_end): r''' Windows specific helper function. Returns set of ipv4 host addresses of remote established connections on local or remote tcp port. Parses output of shell 'netstat' to get connections C:\>netstat -n Active Connections Proto Local Address Foreign Address State TCP 10.2.33.17:3007 130.164.12.233:10123 ESTABLISHED TCP 10.2.33.17:3389 130.164.30.5:10378 ESTABLISHED ''' remotes = set() try: data = subprocess.check_output(['netstat', '-n']) # pylint: disable=minimum-python-version except subprocess.CalledProcessError: log.error('Failed netstat') raise lines = salt.utils.stringutils.to_str(data).split('\n') for line in lines: if 'ESTABLISHED' not in line: continue chunks = line.split() local_host, local_port = chunks[1].rsplit(':', 1) remote_host, remote_port = chunks[2].rsplit(':', 1) if which_end == 'remote_port' and int(remote_port) != port: continue if which_end == 'local_port' and int(local_port) != port: continue remotes.add(remote_host) return remotes def _linux_remotes_on(port, which_end): ''' Linux specific helper function. Returns set of ip host addresses of remote established connections on local tcp port port. Parses output of shell 'lsof' to get connections $ sudo lsof -iTCP:4505 -n COMMAND PID USER FD TYPE DEVICE SIZE/OFF NODE NAME Python 9971 root 35u IPv4 0x18a8464a29ca329d 0t0 TCP *:4505 (LISTEN) Python 9971 root 37u IPv4 0x18a8464a29b2b29d 0t0 TCP 127.0.0.1:4505->127.0.0.1:55703 (ESTABLISHED) Python 10152 root 22u IPv4 0x18a8464a29c8cab5 0t0 TCP 127.0.0.1:55703->127.0.0.1:4505 (ESTABLISHED) Python 10153 root 22u IPv4 0x18a8464a29c8cab5 0t0 TCP [fe80::249a]:4505->[fe80::150]:59367 (ESTABLISHED) ''' remotes = set() try: data = subprocess.check_output( ['lsof', '-iTCP:{0:d}'.format(port), '-n', '-P'] # pylint: disable=minimum-python-version ) except subprocess.CalledProcessError as ex: if ex.returncode == 1: # Lsof return 1 if any error was detected, including the failure # to locate Internet addresses, and it is not an error in this case. log.warning('"lsof" returncode = 1, likely no active TCP sessions.') return remotes log.error('Failed "lsof" with returncode = %s', ex.returncode) raise lines = salt.utils.stringutils.to_str(data).split('\n') for line in lines: chunks = line.split() if not chunks: continue # ['Python', '9971', 'root', '37u', 'IPv4', '0x18a8464a29b2b29d', '0t0', # 'TCP', '127.0.0.1:4505->127.0.0.1:55703', '(ESTABLISHED)'] # print chunks if 'COMMAND' in chunks[0]: continue # ignore header if 'ESTABLISHED' not in chunks[-1]: continue # ignore if not ESTABLISHED # '127.0.0.1:4505->127.0.0.1:55703' local, remote = chunks[8].split('->') _, lport = local.rsplit(':', 1) rhost, rport = remote.rsplit(':', 1) if which_end == 'remote_port' and int(rport) != port: continue if which_end == 'local_port' and int(lport) != port: continue remotes.add(rhost.strip("[]")) return remotes def _aix_remotes_on(port, which_end): ''' AIX specific helper function. Returns set of ipv4 host addresses of remote established connections on local or remote tcp port. Parses output of shell 'netstat' to get connections root@la68pp002_pub:/opt/salt/lib/python2.7/site-packages/salt/modules# netstat -f inet -n Active Internet connections Proto Recv-Q Send-Q Local Address Foreign Address (state) tcp4 0 0 172.29.149.95.50093 209.41.78.13.4505 ESTABLISHED tcp4 0 0 127.0.0.1.9514 *.* LISTEN tcp4 0 0 127.0.0.1.9515 *.* LISTEN tcp4 0 0 127.0.0.1.199 127.0.0.1.32779 ESTABLISHED tcp4 0 0 127.0.0.1.32779 127.0.0.1.199 ESTABLISHED tcp4 0 40 172.29.149.95.22 172.29.96.83.41022 ESTABLISHED tcp4 0 0 172.29.149.95.22 172.29.96.83.41032 ESTABLISHED tcp4 0 0 127.0.0.1.32771 127.0.0.1.32775 ESTABLISHED tcp 0 0 127.0.0.1.32775 127.0.0.1.32771 ESTABLISHED tcp4 0 0 127.0.0.1.32771 127.0.0.1.32776 ESTABLISHED tcp 0 0 127.0.0.1.32776 127.0.0.1.32771 ESTABLISHED tcp4 0 0 127.0.0.1.32771 127.0.0.1.32777 ESTABLISHED tcp 0 0 127.0.0.1.32777 127.0.0.1.32771 ESTABLISHED tcp4 0 0 127.0.0.1.32771 127.0.0.1.32778 ESTABLISHED tcp 0 0 127.0.0.1.32778 127.0.0.1.32771 ESTABLISHED ''' remotes = set() try: data = subprocess.check_output(['netstat', '-f', 'inet', '-n']) # pylint: disable=minimum-python-version except subprocess.CalledProcessError: log.error('Failed netstat') raise lines = salt.utils.stringutils.to_str(data).split('\n') for line in lines: if 'ESTABLISHED' not in line: continue chunks = line.split() local_host, local_port = chunks[3].rsplit('.', 1) remote_host, remote_port = chunks[4].rsplit('.', 1) if which_end == 'remote_port' and int(remote_port) != port: continue if which_end == 'local_port' and int(local_port) != port: continue remotes.add(remote_host) return remotes @jinja_filter('gen_mac') def gen_mac(prefix='AC:DE:48'): ''' Generates a MAC address with the defined OUI prefix. Common prefixes: - ``00:16:3E`` -- Xen - ``00:18:51`` -- OpenVZ - ``00:50:56`` -- VMware (manually generated) - ``52:54:00`` -- QEMU/KVM - ``AC:DE:48`` -- PRIVATE References: - http://standards.ieee.org/develop/regauth/oui/oui.txt - https://www.wireshark.org/tools/oui-lookup.html - https://en.wikipedia.org/wiki/MAC_address ''' return '{0}:{1:02X}:{2:02X}:{3:02X}'.format(prefix, random.randint(0, 0xff), random.randint(0, 0xff), random.randint(0, 0xff)) @jinja_filter('mac_str_to_bytes') def mac_str_to_bytes(mac_str): ''' Convert a MAC address string into bytes. Works with or without separators: b1 = mac_str_to_bytes('08:00:27:13:69:77') b2 = mac_str_to_bytes('080027136977') assert b1 == b2 assert isinstance(b1, bytes) ''' if len(mac_str) == 12: pass elif len(mac_str) == 17: sep = mac_str[2] mac_str = mac_str.replace(sep, '') else: raise ValueError('Invalid MAC address') chars = (int(mac_str[s:s+2], 16) for s in range(0, 12, 2)) return bytes(chars) if six.PY3 else b''.join(chr(x) for x in chars) def refresh_dns(): ''' issue #21397: force glibc to re-read resolv.conf ''' try: res_init() except NameError: # Exception raised loading the library, thus res_init is not defined pass @jinja_filter('connection_check') def connection_check(addr, port=80, safe=False, ipv6=None): ''' Provides a convenient alias for the dns_check filter. ''' return dns_check(addr, port, safe, ipv6) @jinja_filter('dns_check') def dns_check(addr, port=80, safe=False, ipv6=None, attempt_connect=True): ''' Return the ip resolved by dns, but do not exit on failure, only raise an exception. Obeys system preference for IPv4/6 address resolution - this can be overridden by the ipv6 flag. Tries to connect to the address before considering it useful. If no address can be reached, the first one resolved is used as a fallback. ''' error = False lookup = addr seen_ipv6 = False family = socket.AF_INET6 if ipv6 else socket.AF_INET if ipv6 is False else socket.AF_UNSPEC hostnames = [] try: refresh_dns() hostnames = socket.getaddrinfo(addr, port, family, socket.SOCK_STREAM) except TypeError: err = ('Attempt to resolve address \'{0}\' failed. Invalid or unresolveable address').format(lookup) raise SaltSystemExit(code=42, msg=err) except socket.error: error = True # If ipv6 is set to True, attempt another lookup using the IPv4 family, # just in case we're attempting to lookup an IPv4 IP # as an IPv6 hostname. if error and ipv6: try: refresh_dns() hostnames = socket.getaddrinfo(addr, port, socket.AF_INET, socket.SOCK_STREAM) except TypeError: err = ('Attempt to resolve address \'{0}\' failed. Invalid or unresolveable address').format(lookup) raise SaltSystemExit(code=42, msg=err) except socket.error: error = True try: if not hostnames: error = True else: resolved = False candidates = [] for h in hostnames: # Input is IP address, passed through unchanged, just return it if h[4][0] == addr: resolved = salt.utils.zeromq.ip_bracket(addr) break candidate_addr = salt.utils.zeromq.ip_bracket(h[4][0]) # sometimes /etc/hosts contains ::1 localhost if not ipv6 and candidate_addr == '[::1]': continue candidates.append(candidate_addr) if attempt_connect: try: s = socket.socket(h[0], socket.SOCK_STREAM) s.settimeout(2) s.connect((candidate_addr.strip('[]'), h[4][1])) s.close() resolved = candidate_addr break except socket.error: pass if not resolved: if candidates: resolved = candidates[0] else: error = True except TypeError: err = ('Attempt to resolve address \'{0}\' failed. Invalid or unresolveable address').format(lookup) raise SaltSystemExit(code=42, msg=err) except socket.error: error = True if error: err = ('DNS lookup or connection check of \'{0}\' failed.').format(addr) if safe: if salt.log.is_console_configured(): # If logging is not configured it also means that either # the master or minion instance calling this hasn't even # started running log.error(err) raise SaltClientError() raise SaltSystemExit(code=42, msg=err) return resolved def parse_host_port(host_port): """ Takes a string argument specifying host or host:port. Returns a (hostname, port) or (ip_address, port) tuple. If no port is given, the second (port) element of the returned tuple will be None. host:port argument, for example, is accepted in the forms of: - hostname - hostname:1234 - hostname.domain.tld - hostname.domain.tld:5678 - [1234::5]:5678 - 1234::5 - 10.11.12.13:4567 - 10.11.12.13 """ host, port = None, None # default _s_ = host_port[:] if _s_[0] == "[": if "]" in host_port: host, _s_ = _s_.lstrip("[").rsplit("]", 1) host = ipaddress.IPv6Address(host).compressed if _s_[0] == ":": port = int(_s_.lstrip(":")) else: if len(_s_) > 1: raise ValueError('found ambiguous "{}" port in "{}"'.format(_s_, host_port)) else: if _s_.count(":") == 1: host, _hostport_separator_, port = _s_.partition(":") try: port = int(port) except ValueError as _e_: log.error('host_port "%s" port value "%s" is not an integer.', host_port, port) raise _e_ else: host = _s_ try: if not isinstance(host, ipaddress._BaseAddress): host_ip = ipaddress.ip_address(host).compressed host = host_ip except ValueError: log.debug('"%s" Not an IP address? Assuming it is a hostname.', host) if host != sanitize_host(host): log.error('bad hostname: "%s"', host) raise ValueError('bad hostname: "{}"'.format(host)) return host, port def is_fqdn(hostname): """ Verify if hostname conforms to be a FQDN. :param hostname: text string with the name of the host :return: bool, True if hostname is correct FQDN, False otherwise """ compliant = re.compile(r"(?!-)[A-Z\d\-\_]{1,63}(?<!-)$", re.IGNORECASE) return "." in hostname and len(hostname) < 0xff and all(compliant.match(x) for x in hostname.rstrip(".").split("."))
saltstack/salt
salt/utils/network.py
_ip_addrs
python
def _ip_addrs(interface=None, include_loopback=False, interface_data=None, proto='inet'): ''' Return the full list of IP adresses matching the criteria proto = inet|inet6 ''' ret = set() ifaces = interface_data \ if isinstance(interface_data, dict) \ else interfaces() if interface is None: target_ifaces = ifaces else: target_ifaces = dict([(k, v) for k, v in six.iteritems(ifaces) if k == interface]) if not target_ifaces: log.error('Interface %s not found.', interface) for ip_info in six.itervalues(target_ifaces): addrs = ip_info.get(proto, []) addrs.extend([addr for addr in ip_info.get('secondary', []) if addr.get('type') == proto]) for addr in addrs: addr = ipaddress.ip_address(addr.get('address')) if not addr.is_loopback or include_loopback: ret.add(addr) return [six.text_type(addr) for addr in sorted(ret)]
Return the full list of IP adresses matching the criteria proto = inet|inet6
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/network.py#L1257-L1283
[ "def iteritems(d, **kw):\n return d.iteritems(**kw)\n", "def itervalues(d, **kw):\n return d.itervalues(**kw)\n", "def interfaces():\n '''\n Return a dictionary of information about all the interfaces on the minion\n '''\n if salt.utils.platform.is_windows():\n return win_interfaces()\n elif salt.utils.platform.is_netbsd():\n return netbsd_interfaces()\n else:\n return linux_interfaces()\n" ]
# -*- coding: utf-8 -*- ''' Define some generic socket functions for network modules ''' # Import python libs from __future__ import absolute_import, unicode_literals, print_function import itertools import os import re import types import socket import logging import platform import random import subprocess from string import ascii_letters, digits # Import 3rd-party libs from salt.ext import six from salt.ext.six.moves import range # pylint: disable=import-error,redefined-builtin # Attempt to import wmi try: import wmi import salt.utils.winapi except ImportError: pass # Import salt libs import salt.utils.args import salt.utils.files import salt.utils.path import salt.utils.platform import salt.utils.stringutils import salt.utils.zeromq from salt._compat import ipaddress from salt.exceptions import SaltClientError, SaltSystemExit from salt.utils.decorators.jinja import jinja_filter from salt.utils.versions import LooseVersion # inet_pton does not exist in Windows, this is a workaround if salt.utils.platform.is_windows(): from salt.ext import win_inet_pton # pylint: disable=unused-import log = logging.getLogger(__name__) try: import ctypes import ctypes.util libc = ctypes.cdll.LoadLibrary(ctypes.util.find_library("c")) res_init = libc.__res_init except (ImportError, OSError, AttributeError, TypeError): pass # pylint: disable=C0103 def sanitize_host(host): ''' Sanitize host string. https://tools.ietf.org/html/rfc1123#section-2.1 ''' RFC952_characters = ascii_letters + digits + ".-" return "".join([c for c in host[0:255] if c in RFC952_characters]) def isportopen(host, port): ''' Return status of a port ''' if not 1 <= int(port) <= 65535: return False sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) out = sock.connect_ex((sanitize_host(host), int(port))) return out def host_to_ips(host): ''' Returns a list of IP addresses of a given hostname or None if not found. ''' ips = [] try: for family, socktype, proto, canonname, sockaddr in socket.getaddrinfo( host, 0, socket.AF_UNSPEC, socket.SOCK_STREAM): if family == socket.AF_INET: ip, port = sockaddr elif family == socket.AF_INET6: ip, port, flow_info, scope_id = sockaddr ips.append(ip) if not ips: ips = None except Exception: ips = None return ips def _generate_minion_id(): ''' Get list of possible host names and convention names. :return: ''' # There are three types of hostnames: # 1. Network names. How host is accessed from the network. # 2. Host aliases. They might be not available in all the network or only locally (/etc/hosts) # 3. Convention names, an internal nodename. class DistinctList(list): ''' List, which allows one to append only distinct objects. Needs to work on Python 2.6, because of collections.OrderedDict only since 2.7 version. Override 'filter()' for custom filtering. ''' localhost_matchers = [r'localhost.*', r'ip6-.*', r'127[.]\d', r'0\.0\.0\.0', r'::1.*', r'ipv6-.*', r'fe00::.*', r'fe02::.*', r'1.0.0.*.ip6.arpa'] def append(self, p_object): if p_object and p_object not in self and not self.filter(p_object): super(DistinctList, self).append(p_object) return self def extend(self, iterable): for obj in iterable: self.append(obj) return self def filter(self, element): 'Returns True if element needs to be filtered' for rgx in self.localhost_matchers: if re.match(rgx, element): return True def first(self): return self and self[0] or None hostname = socket.gethostname() hosts = DistinctList().append( salt.utils.stringutils.to_unicode(socket.getfqdn(salt.utils.stringutils.to_bytes(hostname))) ).append(platform.node()).append(hostname) if not hosts: try: for a_nfo in socket.getaddrinfo(hosts.first() or 'localhost', None, socket.AF_INET, socket.SOCK_RAW, socket.IPPROTO_IP, socket.AI_CANONNAME): if len(a_nfo) > 3: hosts.append(a_nfo[3]) except socket.gaierror: log.warning('Cannot resolve address %s info via socket: %s', hosts.first() or 'localhost (N/A)', socket.gaierror) # Universal method for everywhere (Linux, Slowlaris, Windows etc) for f_name in ('/etc/hostname', '/etc/nodename', '/etc/hosts', r'{win}\system32\drivers\etc\hosts'.format(win=os.getenv('WINDIR'))): try: with salt.utils.files.fopen(f_name) as f_hdl: for line in f_hdl: line = salt.utils.stringutils.to_unicode(line) hst = line.strip().split('#')[0].strip().split() if hst: if hst[0][:4] in ('127.', '::1') or len(hst) == 1: hosts.extend(hst) except IOError: pass # include public and private ipaddresses return hosts.extend([addr for addr in ip_addrs() if not ipaddress.ip_address(addr).is_loopback]) def generate_minion_id(): ''' Return only first element of the hostname from all possible list. :return: ''' try: ret = salt.utils.stringutils.to_unicode(_generate_minion_id().first()) except TypeError: ret = None return ret or 'localhost' def get_socket(addr, type=socket.SOCK_STREAM, proto=0): ''' Return a socket object for the addr IP-version agnostic ''' version = ipaddress.ip_address(addr).version if version == 4: family = socket.AF_INET elif version == 6: family = socket.AF_INET6 return socket.socket(family, type, proto) def get_fqhostname(): ''' Returns the fully qualified hostname ''' # try getaddrinfo() fqdn = None try: addrinfo = socket.getaddrinfo( socket.gethostname(), 0, socket.AF_UNSPEC, socket.SOCK_STREAM, socket.SOL_TCP, socket.AI_CANONNAME ) for info in addrinfo: # info struct [family, socktype, proto, canonname, sockaddr] # On Windows `canonname` can be an empty string # This can cause the function to return `None` if len(info) > 3 and info[3]: fqdn = info[3] break except socket.gaierror: pass # NOTE: this used to log.error() but it was later disabled except socket.error as err: log.debug('socket.getaddrinfo() failure while finding fqdn: %s', err) if fqdn is None: fqdn = socket.getfqdn() return fqdn def ip_to_host(ip): ''' Returns the hostname of a given IP ''' try: hostname, aliaslist, ipaddrlist = socket.gethostbyaddr(ip) except Exception as exc: log.debug('salt.utils.network.ip_to_host(%r) failed: %s', ip, exc) hostname = None return hostname # pylint: enable=C0103 def is_reachable_host(entity_name): ''' Returns a bool telling if the entity name is a reachable host (IPv4/IPv6/FQDN/etc). :param hostname: :return: ''' try: assert type(socket.getaddrinfo(entity_name, 0, 0, 0, 0)) == list ret = True except socket.gaierror: ret = False return ret def is_ip(ip): ''' Returns a bool telling if the passed IP is a valid IPv4 or IPv6 address. ''' return is_ipv4(ip) or is_ipv6(ip) def is_ipv4(ip): ''' Returns a bool telling if the value passed to it was a valid IPv4 address ''' try: return ipaddress.ip_address(ip).version == 4 except ValueError: return False def is_ipv6(ip): ''' Returns a bool telling if the value passed to it was a valid IPv6 address ''' try: return ipaddress.ip_address(ip).version == 6 except ValueError: return False def is_subnet(cidr): ''' Returns a bool telling if the passed string is an IPv4 or IPv6 subnet ''' return is_ipv4_subnet(cidr) or is_ipv6_subnet(cidr) def is_ipv4_subnet(cidr): ''' Returns a bool telling if the passed string is an IPv4 subnet ''' try: return '/' in cidr and bool(ipaddress.IPv4Network(cidr)) except Exception: return False def is_ipv6_subnet(cidr): ''' Returns a bool telling if the passed string is an IPv6 subnet ''' try: return '/' in cidr and bool(ipaddress.IPv6Network(cidr)) except Exception: return False @jinja_filter('is_ip') def is_ip_filter(ip, options=None): ''' Returns a bool telling if the passed IP is a valid IPv4 or IPv6 address. ''' return is_ipv4_filter(ip, options=options) or is_ipv6_filter(ip, options=options) def _ip_options_global(ip_obj, version): return not ip_obj.is_private def _ip_options_multicast(ip_obj, version): return ip_obj.is_multicast def _ip_options_loopback(ip_obj, version): return ip_obj.is_loopback def _ip_options_link_local(ip_obj, version): return ip_obj.is_link_local def _ip_options_private(ip_obj, version): return ip_obj.is_private def _ip_options_reserved(ip_obj, version): return ip_obj.is_reserved def _ip_options_site_local(ip_obj, version): if version == 6: return ip_obj.is_site_local return False def _ip_options_unspecified(ip_obj, version): return ip_obj.is_unspecified def _ip_options(ip_obj, version, options=None): # will process and IP options options_fun_map = { 'global': _ip_options_global, 'link-local': _ip_options_link_local, 'linklocal': _ip_options_link_local, 'll': _ip_options_link_local, 'link_local': _ip_options_link_local, 'loopback': _ip_options_loopback, 'lo': _ip_options_loopback, 'multicast': _ip_options_multicast, 'private': _ip_options_private, 'public': _ip_options_global, 'reserved': _ip_options_reserved, 'site-local': _ip_options_site_local, 'sl': _ip_options_site_local, 'site_local': _ip_options_site_local, 'unspecified': _ip_options_unspecified } if not options: return six.text_type(ip_obj) # IP version already checked options_list = [option.strip() for option in options.split(',')] for option, fun in options_fun_map.items(): if option in options_list: fun_res = fun(ip_obj, version) if not fun_res: return None # stop at first failed test # else continue return six.text_type(ip_obj) def _is_ipv(ip, version, options=None): if not version: version = 4 if version not in (4, 6): return None try: ip_obj = ipaddress.ip_address(ip) except ValueError: # maybe it is an IP network try: ip_obj = ipaddress.ip_interface(ip) except ValueError: # nope, still not :( return None if not ip_obj.version == version: return None # has the right version, let's move on return _ip_options(ip_obj, version, options=options) @jinja_filter('is_ipv4') def is_ipv4_filter(ip, options=None): ''' Returns a bool telling if the value passed to it was a valid IPv4 address. ip The IP address. net: False Consider IP addresses followed by netmask. options CSV of options regarding the nature of the IP address. E.g.: loopback, multicast, private etc. ''' _is_ipv4 = _is_ipv(ip, 4, options=options) return isinstance(_is_ipv4, six.string_types) @jinja_filter('is_ipv6') def is_ipv6_filter(ip, options=None): ''' Returns a bool telling if the value passed to it was a valid IPv6 address. ip The IP address. net: False Consider IP addresses followed by netmask. options CSV of options regarding the nature of the IP address. E.g.: loopback, multicast, private etc. ''' _is_ipv6 = _is_ipv(ip, 6, options=options) return isinstance(_is_ipv6, six.string_types) def _ipv_filter(value, version, options=None): if version not in (4, 6): return if isinstance(value, (six.string_types, six.text_type, six.binary_type)): return _is_ipv(value, version, options=options) # calls is_ipv4 or is_ipv6 for `value` elif isinstance(value, (list, tuple, types.GeneratorType)): # calls is_ipv4 or is_ipv6 for each element in the list # os it filters and returns only those elements having the desired IP version return [ _is_ipv(addr, version, options=options) for addr in value if _is_ipv(addr, version, options=options) is not None ] return None @jinja_filter('ipv4') def ipv4(value, options=None): ''' Filters a list and returns IPv4 values only. ''' return _ipv_filter(value, 4, options=options) @jinja_filter('ipv6') def ipv6(value, options=None): ''' Filters a list and returns IPv6 values only. ''' return _ipv_filter(value, 6, options=options) @jinja_filter('ipaddr') def ipaddr(value, options=None): ''' Filters and returns only valid IP objects. ''' ipv4_obj = ipv4(value, options=options) ipv6_obj = ipv6(value, options=options) if ipv4_obj is None or ipv6_obj is None: # an IP address can be either IPv4 either IPv6 # therefofe if the value passed as arg is not a list, at least one of the calls above will return None # if one of them is none, means that we should return only one of them return ipv4_obj or ipv6_obj # one of them else: return ipv4_obj + ipv6_obj # extend lists def _filter_ipaddr(value, options, version=None): ipaddr_filter_out = None if version: if version == 4: ipaddr_filter_out = ipv4(value, options) elif version == 6: ipaddr_filter_out = ipv6(value, options) else: ipaddr_filter_out = ipaddr(value, options) if not ipaddr_filter_out: return if not isinstance(ipaddr_filter_out, (list, tuple, types.GeneratorType)): ipaddr_filter_out = [ipaddr_filter_out] return ipaddr_filter_out @jinja_filter('ip_host') def ip_host(value, options=None, version=None): ''' Returns the interfaces IP address, e.g.: 192.168.0.1/28. ''' ipaddr_filter_out = _filter_ipaddr(value, options=options, version=version) if not ipaddr_filter_out: return if not isinstance(value, (list, tuple, types.GeneratorType)): return six.text_type(ipaddress.ip_interface(ipaddr_filter_out[0])) return [six.text_type(ipaddress.ip_interface(ip_a)) for ip_a in ipaddr_filter_out] def _network_hosts(ip_addr_entry): return [ six.text_type(host) for host in ipaddress.ip_network(ip_addr_entry, strict=False).hosts() ] @jinja_filter('network_hosts') def network_hosts(value, options=None, version=None): ''' Return the list of hosts within a network. .. note:: When running this command with a large IPv6 network, the command will take a long time to gather all of the hosts. ''' ipaddr_filter_out = _filter_ipaddr(value, options=options, version=version) if not ipaddr_filter_out: return if not isinstance(value, (list, tuple, types.GeneratorType)): return _network_hosts(ipaddr_filter_out[0]) return [ _network_hosts(ip_a) for ip_a in ipaddr_filter_out ] def _network_size(ip_addr_entry): return ipaddress.ip_network(ip_addr_entry, strict=False).num_addresses @jinja_filter('network_size') def network_size(value, options=None, version=None): ''' Get the size of a network. ''' ipaddr_filter_out = _filter_ipaddr(value, options=options, version=version) if not ipaddr_filter_out: return if not isinstance(value, (list, tuple, types.GeneratorType)): return _network_size(ipaddr_filter_out[0]) return [ _network_size(ip_a) for ip_a in ipaddr_filter_out ] def natural_ipv4_netmask(ip, fmt='prefixlen'): ''' Returns the "natural" mask of an IPv4 address ''' bits = _ipv4_to_bits(ip) if bits.startswith('11'): mask = '24' elif bits.startswith('1'): mask = '16' else: mask = '8' if fmt == 'netmask': return cidr_to_ipv4_netmask(mask) else: return '/' + mask def rpad_ipv4_network(ip): ''' Returns an IP network address padded with zeros. Ex: '192.168.3' -> '192.168.3.0' '10.209' -> '10.209.0.0' ''' return '.'.join(itertools.islice(itertools.chain(ip.split('.'), '0000'), 0, 4)) def cidr_to_ipv4_netmask(cidr_bits): ''' Returns an IPv4 netmask ''' try: cidr_bits = int(cidr_bits) if not 1 <= cidr_bits <= 32: return '' except ValueError: return '' netmask = '' for idx in range(4): if idx: netmask += '.' if cidr_bits >= 8: netmask += '255' cidr_bits -= 8 else: netmask += '{0:d}'.format(256 - (2 ** (8 - cidr_bits))) cidr_bits = 0 return netmask def _number_of_set_bits_to_ipv4_netmask(set_bits): # pylint: disable=C0103 ''' Returns an IPv4 netmask from the integer representation of that mask. Ex. 0xffffff00 -> '255.255.255.0' ''' return cidr_to_ipv4_netmask(_number_of_set_bits(set_bits)) # pylint: disable=C0103 def _number_of_set_bits(x): ''' Returns the number of bits that are set in a 32bit int ''' # Taken from http://stackoverflow.com/a/4912729. Many thanks! x -= (x >> 1) & 0x55555555 x = ((x >> 2) & 0x33333333) + (x & 0x33333333) x = ((x >> 4) + x) & 0x0f0f0f0f x += x >> 8 x += x >> 16 return x & 0x0000003f # pylint: enable=C0103 def _interfaces_ip(out): ''' Uses ip to return a dictionary of interfaces with various information about each (up/down state, ip address, netmask, and hwaddr) ''' ret = dict() def parse_network(value, cols): ''' Return a tuple of ip, netmask, broadcast based on the current set of cols ''' brd = None scope = None if '/' in value: # we have a CIDR in this address ip, cidr = value.split('/') # pylint: disable=C0103 else: ip = value # pylint: disable=C0103 cidr = 32 if type_ == 'inet': mask = cidr_to_ipv4_netmask(int(cidr)) if 'brd' in cols: brd = cols[cols.index('brd') + 1] elif type_ == 'inet6': mask = cidr if 'scope' in cols: scope = cols[cols.index('scope') + 1] return (ip, mask, brd, scope) groups = re.compile('\r?\n\\d').split(out) for group in groups: iface = None data = dict() for line in group.splitlines(): if ' ' not in line: continue match = re.match(r'^\d*:\s+([\w.\-]+)(?:@)?([\w.\-]+)?:\s+<(.+)>', line) if match: iface, parent, attrs = match.groups() if 'UP' in attrs.split(','): data['up'] = True else: data['up'] = False if parent: data['parent'] = parent continue cols = line.split() if len(cols) >= 2: type_, value = tuple(cols[0:2]) iflabel = cols[-1:][0] if type_ in ('inet', 'inet6'): if 'secondary' not in cols: ipaddr, netmask, broadcast, scope = parse_network(value, cols) if type_ == 'inet': if 'inet' not in data: data['inet'] = list() addr_obj = dict() addr_obj['address'] = ipaddr addr_obj['netmask'] = netmask addr_obj['broadcast'] = broadcast addr_obj['label'] = iflabel data['inet'].append(addr_obj) elif type_ == 'inet6': if 'inet6' not in data: data['inet6'] = list() addr_obj = dict() addr_obj['address'] = ipaddr addr_obj['prefixlen'] = netmask addr_obj['scope'] = scope data['inet6'].append(addr_obj) else: if 'secondary' not in data: data['secondary'] = list() ip_, mask, brd, scp = parse_network(value, cols) data['secondary'].append({ 'type': type_, 'address': ip_, 'netmask': mask, 'broadcast': brd, 'label': iflabel, }) del ip_, mask, brd, scp elif type_.startswith('link'): data['hwaddr'] = value if iface: ret[iface] = data del iface, data return ret def _interfaces_ifconfig(out): ''' Uses ifconfig to return a dictionary of interfaces with various information about each (up/down state, ip address, netmask, and hwaddr) ''' ret = dict() piface = re.compile(r'^([^\s:]+)') pmac = re.compile('.*?(?:HWaddr|ether|address:|lladdr) ([0-9a-fA-F:]+)') if salt.utils.platform.is_sunos(): pip = re.compile(r'.*?(?:inet\s+)([0-9]+\.[0-9]+\.[0-9]+\.[0-9]+)(.*)') pip6 = re.compile('.*?(?:inet6 )([0-9a-fA-F:]+)') pmask6 = re.compile(r'.*?(?:inet6 [0-9a-fA-F:]+/(\d+)).*') else: pip = re.compile(r'.*?(?:inet addr:|inet [^\d]*)(.*?)\s') pip6 = re.compile('.*?(?:inet6 addr: (.*?)/|inet6 )([0-9a-fA-F:]+)') pmask6 = re.compile(r'.*?(?:inet6 addr: [0-9a-fA-F:]+/(\d+)|prefixlen (\d+))(?: Scope:([a-zA-Z]+)| scopeid (0x[0-9a-fA-F]))?') pmask = re.compile(r'.*?(?:Mask:|netmask )(?:((?:0x)?[0-9a-fA-F]{8})|([\d\.]+))') pupdown = re.compile('UP') pbcast = re.compile(r'.*?(?:Bcast:|broadcast )([\d\.]+)') groups = re.compile('\r?\n(?=\\S)').split(out) for group in groups: data = dict() iface = '' updown = False for line in group.splitlines(): miface = piface.match(line) mmac = pmac.match(line) mip = pip.match(line) mip6 = pip6.match(line) mupdown = pupdown.search(line) if miface: iface = miface.group(1) if mmac: data['hwaddr'] = mmac.group(1) if salt.utils.platform.is_sunos(): expand_mac = [] for chunk in data['hwaddr'].split(':'): expand_mac.append('0{0}'.format(chunk) if len(chunk) < 2 else '{0}'.format(chunk)) data['hwaddr'] = ':'.join(expand_mac) if mip: if 'inet' not in data: data['inet'] = list() addr_obj = dict() addr_obj['address'] = mip.group(1) mmask = pmask.match(line) if mmask: if mmask.group(1): mmask = _number_of_set_bits_to_ipv4_netmask( int(mmask.group(1), 16)) else: mmask = mmask.group(2) addr_obj['netmask'] = mmask mbcast = pbcast.match(line) if mbcast: addr_obj['broadcast'] = mbcast.group(1) data['inet'].append(addr_obj) if mupdown: updown = True if mip6: if 'inet6' not in data: data['inet6'] = list() addr_obj = dict() addr_obj['address'] = mip6.group(1) or mip6.group(2) mmask6 = pmask6.match(line) if mmask6: addr_obj['prefixlen'] = mmask6.group(1) or mmask6.group(2) if not salt.utils.platform.is_sunos(): ipv6scope = mmask6.group(3) or mmask6.group(4) addr_obj['scope'] = ipv6scope.lower() if ipv6scope is not None else ipv6scope # SunOS sometimes has ::/0 as inet6 addr when using addrconf if not salt.utils.platform.is_sunos() \ or addr_obj['address'] != '::' \ and addr_obj['prefixlen'] != 0: data['inet6'].append(addr_obj) data['up'] = updown if iface in ret: # SunOS optimization, where interfaces occur twice in 'ifconfig -a' # output with the same name: for ipv4 and then for ipv6 addr family. # Every instance has it's own 'UP' status and we assume that ipv4 # status determines global interface status. # # merge items with higher priority for older values # after that merge the inet and inet6 sub items for both ret[iface] = dict(list(data.items()) + list(ret[iface].items())) if 'inet' in data: ret[iface]['inet'].extend(x for x in data['inet'] if x not in ret[iface]['inet']) if 'inet6' in data: ret[iface]['inet6'].extend(x for x in data['inet6'] if x not in ret[iface]['inet6']) else: ret[iface] = data del data return ret def linux_interfaces(): ''' Obtain interface information for *NIX/BSD variants ''' ifaces = dict() ip_path = salt.utils.path.which('ip') ifconfig_path = None if ip_path else salt.utils.path.which('ifconfig') if ip_path: cmd1 = subprocess.Popen( '{0} link show'.format(ip_path), shell=True, close_fds=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT).communicate()[0] cmd2 = subprocess.Popen( '{0} addr show'.format(ip_path), shell=True, close_fds=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT).communicate()[0] ifaces = _interfaces_ip("{0}\n{1}".format( salt.utils.stringutils.to_str(cmd1), salt.utils.stringutils.to_str(cmd2))) elif ifconfig_path: cmd = subprocess.Popen( '{0} -a'.format(ifconfig_path), shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT).communicate()[0] ifaces = _interfaces_ifconfig(salt.utils.stringutils.to_str(cmd)) return ifaces def _netbsd_interfaces_ifconfig(out): ''' Uses ifconfig to return a dictionary of interfaces with various information about each (up/down state, ip address, netmask, and hwaddr) ''' ret = dict() piface = re.compile(r'^([^\s:]+)') pmac = re.compile('.*?address: ([0-9a-f:]+)') pip = re.compile(r'.*?inet [^\d]*(.*?)/([\d]*)\s') pip6 = re.compile(r'.*?inet6 ([0-9a-f:]+)%([a-zA-Z0-9]*)/([\d]*)\s') pupdown = re.compile('UP') pbcast = re.compile(r'.*?broadcast ([\d\.]+)') groups = re.compile('\r?\n(?=\\S)').split(out) for group in groups: data = dict() iface = '' updown = False for line in group.splitlines(): miface = piface.match(line) mmac = pmac.match(line) mip = pip.match(line) mip6 = pip6.match(line) mupdown = pupdown.search(line) if miface: iface = miface.group(1) if mmac: data['hwaddr'] = mmac.group(1) if mip: if 'inet' not in data: data['inet'] = list() addr_obj = dict() addr_obj['address'] = mip.group(1) mmask = mip.group(2) if mip.group(2): addr_obj['netmask'] = cidr_to_ipv4_netmask(mip.group(2)) mbcast = pbcast.match(line) if mbcast: addr_obj['broadcast'] = mbcast.group(1) data['inet'].append(addr_obj) if mupdown: updown = True if mip6: if 'inet6' not in data: data['inet6'] = list() addr_obj = dict() addr_obj['address'] = mip6.group(1) mmask6 = mip6.group(3) addr_obj['scope'] = mip6.group(2) addr_obj['prefixlen'] = mip6.group(3) data['inet6'].append(addr_obj) data['up'] = updown ret[iface] = data del data return ret def netbsd_interfaces(): ''' Obtain interface information for NetBSD >= 8 where the ifconfig output diverged from other BSD variants (Netmask is now part of the address) ''' # NetBSD versions prior to 8.0 can still use linux_interfaces() if LooseVersion(os.uname()[2]) < LooseVersion('8.0'): return linux_interfaces() ifconfig_path = salt.utils.path.which('ifconfig') cmd = subprocess.Popen( '{0} -a'.format(ifconfig_path), shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT).communicate()[0] return _netbsd_interfaces_ifconfig(salt.utils.stringutils.to_str(cmd)) def _interfaces_ipconfig(out): ''' Returns a dictionary of interfaces with various information about each (up/down state, ip address, netmask, and hwaddr) NOTE: This is not used by any function and may be able to be removed in the future. ''' ifaces = dict() iface = None adapter_iface_regex = re.compile(r'adapter (\S.+):$') for line in out.splitlines(): if not line: continue # TODO what does Windows call Infiniband and 10/40gige adapters if line.startswith('Ethernet'): iface = ifaces[adapter_iface_regex.search(line).group(1)] iface['up'] = True addr = None continue if iface: key, val = line.split(',', 1) key = key.strip(' .') val = val.strip() if addr and key == 'Subnet Mask': addr['netmask'] = val elif key in ('IP Address', 'IPv4 Address'): if 'inet' not in iface: iface['inet'] = list() addr = {'address': val.rstrip('(Preferred)'), 'netmask': None, 'broadcast': None} # TODO find the broadcast iface['inet'].append(addr) elif 'IPv6 Address' in key: if 'inet6' not in iface: iface['inet'] = list() # XXX What is the prefixlen!? addr = {'address': val.rstrip('(Preferred)'), 'prefixlen': None} iface['inet6'].append(addr) elif key == 'Physical Address': iface['hwaddr'] = val elif key == 'Media State': # XXX seen used for tunnel adaptors # might be useful iface['up'] = (val != 'Media disconnected') def win_interfaces(): ''' Obtain interface information for Windows systems ''' with salt.utils.winapi.Com(): c = wmi.WMI() ifaces = {} for iface in c.Win32_NetworkAdapterConfiguration(IPEnabled=1): ifaces[iface.Description] = dict() if iface.MACAddress: ifaces[iface.Description]['hwaddr'] = iface.MACAddress if iface.IPEnabled: ifaces[iface.Description]['up'] = True for ip in iface.IPAddress: if '.' in ip: if 'inet' not in ifaces[iface.Description]: ifaces[iface.Description]['inet'] = [] item = {'address': ip, 'label': iface.Description} if iface.DefaultIPGateway: broadcast = next((i for i in iface.DefaultIPGateway if '.' in i), '') if broadcast: item['broadcast'] = broadcast if iface.IPSubnet: netmask = next((i for i in iface.IPSubnet if '.' in i), '') if netmask: item['netmask'] = netmask ifaces[iface.Description]['inet'].append(item) if ':' in ip: if 'inet6' not in ifaces[iface.Description]: ifaces[iface.Description]['inet6'] = [] item = {'address': ip} if iface.DefaultIPGateway: broadcast = next((i for i in iface.DefaultIPGateway if ':' in i), '') if broadcast: item['broadcast'] = broadcast if iface.IPSubnet: netmask = next((i for i in iface.IPSubnet if ':' in i), '') if netmask: item['netmask'] = netmask ifaces[iface.Description]['inet6'].append(item) else: ifaces[iface.Description]['up'] = False return ifaces def interfaces(): ''' Return a dictionary of information about all the interfaces on the minion ''' if salt.utils.platform.is_windows(): return win_interfaces() elif salt.utils.platform.is_netbsd(): return netbsd_interfaces() else: return linux_interfaces() def get_net_start(ipaddr, netmask): ''' Return the address of the network ''' net = ipaddress.ip_network('{0}/{1}'.format(ipaddr, netmask), strict=False) return six.text_type(net.network_address) def get_net_size(mask): ''' Turns an IPv4 netmask into it's corresponding prefix length (255.255.255.0 -> 24 as in 192.168.1.10/24). ''' binary_str = '' for octet in mask.split('.'): binary_str += bin(int(octet))[2:].zfill(8) return len(binary_str.rstrip('0')) def calc_net(ipaddr, netmask=None): ''' Takes IP (CIDR notation supported) and optionally netmask and returns the network in CIDR-notation. (The IP can be any IP inside the subnet) ''' if netmask is not None: ipaddr = '{0}/{1}'.format(ipaddr, netmask) return six.text_type(ipaddress.ip_network(ipaddr, strict=False)) def _ipv4_to_bits(ipaddr): ''' Accepts an IPv4 dotted quad and returns a string representing its binary counterpart ''' return ''.join([bin(int(x))[2:].rjust(8, '0') for x in ipaddr.split('.')]) def _get_iface_info(iface): ''' If `iface` is available, return interface info and no error, otherwise return no info and log and return an error ''' iface_info = interfaces() if iface in iface_info.keys(): return iface_info, False else: error_msg = ('Interface "{0}" not in available interfaces: "{1}"' ''.format(iface, '", "'.join(iface_info.keys()))) log.error(error_msg) return None, error_msg def _hw_addr_aix(iface): ''' Return the hardware address (a.k.a. MAC address) for a given interface on AIX MAC address not available in through interfaces ''' cmd = subprocess.Popen( 'entstat -d {0} | grep \'Hardware Address\''.format(iface), shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT).communicate()[0] if cmd: comps = cmd.split(' ') if len(comps) == 3: mac_addr = comps[2].strip('\'').strip() return mac_addr error_msg = ('Interface "{0}" either not available or does not contain a hardware address'.format(iface)) log.error(error_msg) return error_msg def hw_addr(iface): ''' Return the hardware address (a.k.a. MAC address) for a given interface .. versionchanged:: 2016.11.4 Added support for AIX ''' if salt.utils.platform.is_aix(): return _hw_addr_aix iface_info, error = _get_iface_info(iface) if error is False: return iface_info.get(iface, {}).get('hwaddr', '') else: return error def interface(iface): ''' Return the details of `iface` or an error if it does not exist ''' iface_info, error = _get_iface_info(iface) if error is False: return iface_info.get(iface, {}).get('inet', '') else: return error def interface_ip(iface): ''' Return `iface` IPv4 addr or an error if `iface` does not exist ''' iface_info, error = _get_iface_info(iface) if error is False: inet = iface_info.get(iface, {}).get('inet', None) return inet[0].get('address', '') if inet else '' else: return error def _subnets(proto='inet', interfaces_=None): ''' Returns a list of subnets to which the host belongs ''' if interfaces_ is None: ifaces = interfaces() elif isinstance(interfaces_, list): ifaces = {} for key, value in six.iteritems(interfaces()): if key in interfaces_: ifaces[key] = value else: ifaces = {interfaces_: interfaces().get(interfaces_, {})} ret = set() if proto == 'inet': subnet = 'netmask' dflt_cidr = 32 elif proto == 'inet6': subnet = 'prefixlen' dflt_cidr = 128 else: log.error('Invalid proto %s calling subnets()', proto) return for ip_info in six.itervalues(ifaces): addrs = ip_info.get(proto, []) addrs.extend([addr for addr in ip_info.get('secondary', []) if addr.get('type') == proto]) for intf in addrs: if subnet in intf: intf = ipaddress.ip_interface('{0}/{1}'.format(intf['address'], intf[subnet])) else: intf = ipaddress.ip_interface('{0}/{1}'.format(intf['address'], dflt_cidr)) if not intf.is_loopback: ret.add(intf.network) return [six.text_type(net) for net in sorted(ret)] def subnets(interfaces=None): ''' Returns a list of IPv4 subnets to which the host belongs ''' return _subnets('inet', interfaces_=interfaces) def subnets6(): ''' Returns a list of IPv6 subnets to which the host belongs ''' return _subnets('inet6') def in_subnet(cidr, addr=None): ''' Returns True if host or (any of) addrs is within specified subnet, otherwise False ''' try: cidr = ipaddress.ip_network(cidr) except ValueError: log.error('Invalid CIDR \'%s\'', cidr) return False if addr is None: addr = ip_addrs() addr.extend(ip_addrs6()) elif not isinstance(addr, (list, tuple)): addr = (addr,) return any(ipaddress.ip_address(item) in cidr for item in addr) def ip_addrs(interface=None, include_loopback=False, interface_data=None): ''' Returns a list of IPv4 addresses assigned to the host. 127.0.0.1 is ignored, unless 'include_loopback=True' is indicated. If 'interface' is provided, then only IP addresses from that interface will be returned. ''' return _ip_addrs(interface, include_loopback, interface_data, 'inet') def ip_addrs6(interface=None, include_loopback=False, interface_data=None): ''' Returns a list of IPv6 addresses assigned to the host. ::1 is ignored, unless 'include_loopback=True' is indicated. If 'interface' is provided, then only IP addresses from that interface will be returned. ''' return _ip_addrs(interface, include_loopback, interface_data, 'inet6') def hex2ip(hex_ip, invert=False): ''' Convert a hex string to an ip, if a failure occurs the original hex is returned. If 'invert=True' assume that ip from /proc/net/<proto> ''' if len(hex_ip) == 32: # ipv6 ip = [] for i in range(0, 32, 8): ip_part = hex_ip[i:i + 8] ip_part = [ip_part[x:x + 2] for x in range(0, 8, 2)] if invert: ip.append("{0[3]}{0[2]}:{0[1]}{0[0]}".format(ip_part)) else: ip.append("{0[0]}{0[1]}:{0[2]}{0[3]}".format(ip_part)) try: address = ipaddress.IPv6Address(":".join(ip)) if address.ipv4_mapped: return str(address.ipv4_mapped) else: return address.compressed except ipaddress.AddressValueError as ex: log.error('hex2ip - ipv6 address error: %s', ex) return hex_ip try: hip = int(hex_ip, 16) except ValueError: return hex_ip if invert: return '{3}.{2}.{1}.{0}'.format(hip >> 24 & 255, hip >> 16 & 255, hip >> 8 & 255, hip & 255) return '{0}.{1}.{2}.{3}'.format(hip >> 24 & 255, hip >> 16 & 255, hip >> 8 & 255, hip & 255) def mac2eui64(mac, prefix=None): ''' Convert a MAC address to a EUI64 identifier or, with prefix provided, a full IPv6 address ''' # http://tools.ietf.org/html/rfc4291#section-2.5.1 eui64 = re.sub(r'[.:-]', '', mac).lower() eui64 = eui64[0:6] + 'fffe' + eui64[6:] eui64 = hex(int(eui64[0:2], 16) | 2)[2:].zfill(2) + eui64[2:] if prefix is None: return ':'.join(re.findall(r'.{4}', eui64)) else: try: net = ipaddress.ip_network(prefix, strict=False) euil = int('0x{0}'.format(eui64), 16) return '{0}/{1}'.format(net[euil], net.prefixlen) except Exception: return def active_tcp(): ''' Return a dict describing all active tcp connections as quickly as possible ''' ret = {} for statf in ['/proc/net/tcp', '/proc/net/tcp6']: if os.path.isfile(statf): with salt.utils.files.fopen(statf, 'rb') as fp_: for line in fp_: line = salt.utils.stringutils.to_unicode(line) if line.strip().startswith('sl'): continue iret = _parse_tcp_line(line) sl = next(iter(iret)) if iret[sl]['state'] == 1: # 1 is ESTABLISHED del iret[sl]['state'] ret[len(ret)] = iret[sl] return ret def local_port_tcp(port): ''' Return a set of remote ip addrs attached to the specified local port ''' ret = _remotes_on(port, 'local_port') return ret def remote_port_tcp(port): ''' Return a set of ip addrs the current host is connected to on given port ''' ret = _remotes_on(port, 'remote_port') return ret def _remotes_on(port, which_end): ''' Return a set of ip addrs active tcp connections ''' port = int(port) ret = _netlink_tool_remote_on(port, which_end) if ret is not None: return ret ret = set() proc_available = False for statf in ['/proc/net/tcp', '/proc/net/tcp6']: if os.path.isfile(statf): proc_available = True with salt.utils.files.fopen(statf, 'r') as fp_: for line in fp_: line = salt.utils.stringutils.to_unicode(line) if line.strip().startswith('sl'): continue iret = _parse_tcp_line(line) sl = next(iter(iret)) if iret[sl][which_end] == port and iret[sl]['state'] == 1: # 1 is ESTABLISHED ret.add(iret[sl]['remote_addr']) if not proc_available: # Fallback to use OS specific tools if salt.utils.platform.is_sunos(): return _sunos_remotes_on(port, which_end) if salt.utils.platform.is_freebsd(): return _freebsd_remotes_on(port, which_end) if salt.utils.platform.is_netbsd(): return _netbsd_remotes_on(port, which_end) if salt.utils.platform.is_openbsd(): return _openbsd_remotes_on(port, which_end) if salt.utils.platform.is_windows(): return _windows_remotes_on(port, which_end) if salt.utils.platform.is_aix(): return _aix_remotes_on(port, which_end) return _linux_remotes_on(port, which_end) return ret def _parse_tcp_line(line): ''' Parse a single line from the contents of /proc/net/tcp or /proc/net/tcp6 ''' ret = {} comps = line.strip().split() sl = comps[0].rstrip(':') ret[sl] = {} l_addr, l_port = comps[1].split(':') r_addr, r_port = comps[2].split(':') ret[sl]['local_addr'] = hex2ip(l_addr, True) ret[sl]['local_port'] = int(l_port, 16) ret[sl]['remote_addr'] = hex2ip(r_addr, True) ret[sl]['remote_port'] = int(r_port, 16) ret[sl]['state'] = int(comps[3], 16) return ret def _netlink_tool_remote_on(port, which_end): ''' Returns set of ipv4 host addresses of remote established connections on local or remote tcp port. Parses output of shell 'ss' to get connections [root@salt-master ~]# ss -ant State Recv-Q Send-Q Local Address:Port Peer Address:Port LISTEN 0 511 *:80 *:* LISTEN 0 128 *:22 *:* ESTAB 0 0 127.0.0.1:56726 127.0.0.1:4505 ''' remotes = set() valid = False try: data = subprocess.check_output(['ss', '-ant']) # pylint: disable=minimum-python-version except subprocess.CalledProcessError: log.error('Failed ss') raise except OSError: # not command "No such file or directory" return None lines = salt.utils.stringutils.to_str(data).split('\n') for line in lines: if 'Address:Port' in line: # ss tools may not be valid valid = True continue elif 'ESTAB' not in line: continue chunks = line.split() local_host, local_port = chunks[3].split(':', 1) remote_host, remote_port = chunks[4].split(':', 1) if which_end == 'remote_port' and int(remote_port) != port: continue if which_end == 'local_port' and int(local_port) != port: continue remotes.add(remote_host) if valid is False: remotes = None return remotes def _sunos_remotes_on(port, which_end): ''' SunOS specific helper function. Returns set of ipv4 host addresses of remote established connections on local or remote tcp port. Parses output of shell 'netstat' to get connections [root@salt-master ~]# netstat -f inet -n TCP: IPv4 Local Address Remote Address Swind Send-Q Rwind Recv-Q State -------------------- -------------------- ----- ------ ----- ------ ----------- 10.0.0.101.4505 10.0.0.1.45329 1064800 0 1055864 0 ESTABLISHED 10.0.0.101.4505 10.0.0.100.50798 1064800 0 1055864 0 ESTABLISHED ''' remotes = set() try: data = subprocess.check_output(['netstat', '-f', 'inet', '-n']) # pylint: disable=minimum-python-version except subprocess.CalledProcessError: log.error('Failed netstat') raise lines = salt.utils.stringutils.to_str(data).split('\n') for line in lines: if 'ESTABLISHED' not in line: continue chunks = line.split() local_host, local_port = chunks[0].rsplit('.', 1) remote_host, remote_port = chunks[1].rsplit('.', 1) if which_end == 'remote_port' and int(remote_port) != port: continue if which_end == 'local_port' and int(local_port) != port: continue remotes.add(remote_host) return remotes def _freebsd_remotes_on(port, which_end): ''' Returns set of ipv4 host addresses of remote established connections on local tcp port port. Parses output of shell 'sockstat' (FreeBSD) to get connections $ sudo sockstat -4 USER COMMAND PID FD PROTO LOCAL ADDRESS FOREIGN ADDRESS root python2.7 1456 29 tcp4 *:4505 *:* root python2.7 1445 17 tcp4 *:4506 *:* root python2.7 1294 14 tcp4 127.0.0.1:11813 127.0.0.1:4505 root python2.7 1294 41 tcp4 127.0.0.1:61115 127.0.0.1:4506 $ sudo sockstat -4 -c -p 4506 USER COMMAND PID FD PROTO LOCAL ADDRESS FOREIGN ADDRESS root python2.7 1294 41 tcp4 127.0.0.1:61115 127.0.0.1:4506 ''' port = int(port) remotes = set() try: cmd = salt.utils.args.shlex_split('sockstat -4 -c -p {0}'.format(port)) data = subprocess.check_output(cmd) # pylint: disable=minimum-python-version except subprocess.CalledProcessError as ex: log.error('Failed "sockstat" with returncode = %s', ex.returncode) raise lines = salt.utils.stringutils.to_str(data).split('\n') for line in lines: chunks = line.split() if not chunks: continue # ['root', 'python2.7', '1456', '37', 'tcp4', # '127.0.0.1:4505-', '127.0.0.1:55703'] # print chunks if 'COMMAND' in chunks[1]: continue # ignore header if len(chunks) < 2: continue # sockstat -4 -c -p 4506 does this with high PIDs: # USER COMMAND PID FD PROTO LOCAL ADDRESS FOREIGN ADDRESS # salt-master python2.781106 35 tcp4 192.168.12.34:4506 192.168.12.45:60143 local = chunks[-2] remote = chunks[-1] lhost, lport = local.split(':') rhost, rport = remote.split(':') if which_end == 'local' and int(lport) != port: # ignore if local port not port continue if which_end == 'remote' and int(rport) != port: # ignore if remote port not port continue remotes.add(rhost) return remotes def _netbsd_remotes_on(port, which_end): ''' Returns set of ipv4 host addresses of remote established connections on local tcp port port. Parses output of shell 'sockstat' (NetBSD) to get connections $ sudo sockstat -4 -n USER COMMAND PID FD PROTO LOCAL ADDRESS FOREIGN ADDRESS root python2.7 1456 29 tcp *.4505 *.* root python2.7 1445 17 tcp *.4506 *.* root python2.7 1294 14 tcp 127.0.0.1.11813 127.0.0.1.4505 root python2.7 1294 41 tcp 127.0.0.1.61115 127.0.0.1.4506 $ sudo sockstat -4 -c -n -p 4506 USER COMMAND PID FD PROTO LOCAL ADDRESS FOREIGN ADDRESS root python2.7 1294 41 tcp 127.0.0.1.61115 127.0.0.1.4506 ''' port = int(port) remotes = set() try: cmd = salt.utils.args.shlex_split('sockstat -4 -c -n -p {0}'.format(port)) data = subprocess.check_output(cmd) # pylint: disable=minimum-python-version except subprocess.CalledProcessError as ex: log.error('Failed "sockstat" with returncode = %s', ex.returncode) raise lines = salt.utils.stringutils.to_str(data).split('\n') for line in lines: chunks = line.split() if not chunks: continue # ['root', 'python2.7', '1456', '37', 'tcp', # '127.0.0.1.4505-', '127.0.0.1.55703'] # print chunks if 'COMMAND' in chunks[1]: continue # ignore header if len(chunks) < 2: continue local = chunks[5].split('.') lport = local.pop() lhost = '.'.join(local) remote = chunks[6].split('.') rport = remote.pop() rhost = '.'.join(remote) if which_end == 'local' and int(lport) != port: # ignore if local port not port continue if which_end == 'remote' and int(rport) != port: # ignore if remote port not port continue remotes.add(rhost) return remotes def _openbsd_remotes_on(port, which_end): ''' OpenBSD specific helper function. Returns set of ipv4 host addresses of remote established connections on local or remote tcp port. Parses output of shell 'netstat' to get connections $ netstat -nf inet Active Internet connections Proto Recv-Q Send-Q Local Address Foreign Address (state) tcp 0 0 10.0.0.101.4505 10.0.0.1.45329 ESTABLISHED tcp 0 0 10.0.0.101.4505 10.0.0.100.50798 ESTABLISHED ''' remotes = set() try: data = subprocess.check_output(['netstat', '-nf', 'inet']) # pylint: disable=minimum-python-version except subprocess.CalledProcessError: log.error('Failed netstat') raise lines = data.split('\n') for line in lines: if 'ESTABLISHED' not in line: continue chunks = line.split() local_host, local_port = chunks[3].rsplit('.', 1) remote_host, remote_port = chunks[4].rsplit('.', 1) if which_end == 'remote_port' and int(remote_port) != port: continue if which_end == 'local_port' and int(local_port) != port: continue remotes.add(remote_host) return remotes def _windows_remotes_on(port, which_end): r''' Windows specific helper function. Returns set of ipv4 host addresses of remote established connections on local or remote tcp port. Parses output of shell 'netstat' to get connections C:\>netstat -n Active Connections Proto Local Address Foreign Address State TCP 10.2.33.17:3007 130.164.12.233:10123 ESTABLISHED TCP 10.2.33.17:3389 130.164.30.5:10378 ESTABLISHED ''' remotes = set() try: data = subprocess.check_output(['netstat', '-n']) # pylint: disable=minimum-python-version except subprocess.CalledProcessError: log.error('Failed netstat') raise lines = salt.utils.stringutils.to_str(data).split('\n') for line in lines: if 'ESTABLISHED' not in line: continue chunks = line.split() local_host, local_port = chunks[1].rsplit(':', 1) remote_host, remote_port = chunks[2].rsplit(':', 1) if which_end == 'remote_port' and int(remote_port) != port: continue if which_end == 'local_port' and int(local_port) != port: continue remotes.add(remote_host) return remotes def _linux_remotes_on(port, which_end): ''' Linux specific helper function. Returns set of ip host addresses of remote established connections on local tcp port port. Parses output of shell 'lsof' to get connections $ sudo lsof -iTCP:4505 -n COMMAND PID USER FD TYPE DEVICE SIZE/OFF NODE NAME Python 9971 root 35u IPv4 0x18a8464a29ca329d 0t0 TCP *:4505 (LISTEN) Python 9971 root 37u IPv4 0x18a8464a29b2b29d 0t0 TCP 127.0.0.1:4505->127.0.0.1:55703 (ESTABLISHED) Python 10152 root 22u IPv4 0x18a8464a29c8cab5 0t0 TCP 127.0.0.1:55703->127.0.0.1:4505 (ESTABLISHED) Python 10153 root 22u IPv4 0x18a8464a29c8cab5 0t0 TCP [fe80::249a]:4505->[fe80::150]:59367 (ESTABLISHED) ''' remotes = set() try: data = subprocess.check_output( ['lsof', '-iTCP:{0:d}'.format(port), '-n', '-P'] # pylint: disable=minimum-python-version ) except subprocess.CalledProcessError as ex: if ex.returncode == 1: # Lsof return 1 if any error was detected, including the failure # to locate Internet addresses, and it is not an error in this case. log.warning('"lsof" returncode = 1, likely no active TCP sessions.') return remotes log.error('Failed "lsof" with returncode = %s', ex.returncode) raise lines = salt.utils.stringutils.to_str(data).split('\n') for line in lines: chunks = line.split() if not chunks: continue # ['Python', '9971', 'root', '37u', 'IPv4', '0x18a8464a29b2b29d', '0t0', # 'TCP', '127.0.0.1:4505->127.0.0.1:55703', '(ESTABLISHED)'] # print chunks if 'COMMAND' in chunks[0]: continue # ignore header if 'ESTABLISHED' not in chunks[-1]: continue # ignore if not ESTABLISHED # '127.0.0.1:4505->127.0.0.1:55703' local, remote = chunks[8].split('->') _, lport = local.rsplit(':', 1) rhost, rport = remote.rsplit(':', 1) if which_end == 'remote_port' and int(rport) != port: continue if which_end == 'local_port' and int(lport) != port: continue remotes.add(rhost.strip("[]")) return remotes def _aix_remotes_on(port, which_end): ''' AIX specific helper function. Returns set of ipv4 host addresses of remote established connections on local or remote tcp port. Parses output of shell 'netstat' to get connections root@la68pp002_pub:/opt/salt/lib/python2.7/site-packages/salt/modules# netstat -f inet -n Active Internet connections Proto Recv-Q Send-Q Local Address Foreign Address (state) tcp4 0 0 172.29.149.95.50093 209.41.78.13.4505 ESTABLISHED tcp4 0 0 127.0.0.1.9514 *.* LISTEN tcp4 0 0 127.0.0.1.9515 *.* LISTEN tcp4 0 0 127.0.0.1.199 127.0.0.1.32779 ESTABLISHED tcp4 0 0 127.0.0.1.32779 127.0.0.1.199 ESTABLISHED tcp4 0 40 172.29.149.95.22 172.29.96.83.41022 ESTABLISHED tcp4 0 0 172.29.149.95.22 172.29.96.83.41032 ESTABLISHED tcp4 0 0 127.0.0.1.32771 127.0.0.1.32775 ESTABLISHED tcp 0 0 127.0.0.1.32775 127.0.0.1.32771 ESTABLISHED tcp4 0 0 127.0.0.1.32771 127.0.0.1.32776 ESTABLISHED tcp 0 0 127.0.0.1.32776 127.0.0.1.32771 ESTABLISHED tcp4 0 0 127.0.0.1.32771 127.0.0.1.32777 ESTABLISHED tcp 0 0 127.0.0.1.32777 127.0.0.1.32771 ESTABLISHED tcp4 0 0 127.0.0.1.32771 127.0.0.1.32778 ESTABLISHED tcp 0 0 127.0.0.1.32778 127.0.0.1.32771 ESTABLISHED ''' remotes = set() try: data = subprocess.check_output(['netstat', '-f', 'inet', '-n']) # pylint: disable=minimum-python-version except subprocess.CalledProcessError: log.error('Failed netstat') raise lines = salt.utils.stringutils.to_str(data).split('\n') for line in lines: if 'ESTABLISHED' not in line: continue chunks = line.split() local_host, local_port = chunks[3].rsplit('.', 1) remote_host, remote_port = chunks[4].rsplit('.', 1) if which_end == 'remote_port' and int(remote_port) != port: continue if which_end == 'local_port' and int(local_port) != port: continue remotes.add(remote_host) return remotes @jinja_filter('gen_mac') def gen_mac(prefix='AC:DE:48'): ''' Generates a MAC address with the defined OUI prefix. Common prefixes: - ``00:16:3E`` -- Xen - ``00:18:51`` -- OpenVZ - ``00:50:56`` -- VMware (manually generated) - ``52:54:00`` -- QEMU/KVM - ``AC:DE:48`` -- PRIVATE References: - http://standards.ieee.org/develop/regauth/oui/oui.txt - https://www.wireshark.org/tools/oui-lookup.html - https://en.wikipedia.org/wiki/MAC_address ''' return '{0}:{1:02X}:{2:02X}:{3:02X}'.format(prefix, random.randint(0, 0xff), random.randint(0, 0xff), random.randint(0, 0xff)) @jinja_filter('mac_str_to_bytes') def mac_str_to_bytes(mac_str): ''' Convert a MAC address string into bytes. Works with or without separators: b1 = mac_str_to_bytes('08:00:27:13:69:77') b2 = mac_str_to_bytes('080027136977') assert b1 == b2 assert isinstance(b1, bytes) ''' if len(mac_str) == 12: pass elif len(mac_str) == 17: sep = mac_str[2] mac_str = mac_str.replace(sep, '') else: raise ValueError('Invalid MAC address') chars = (int(mac_str[s:s+2], 16) for s in range(0, 12, 2)) return bytes(chars) if six.PY3 else b''.join(chr(x) for x in chars) def refresh_dns(): ''' issue #21397: force glibc to re-read resolv.conf ''' try: res_init() except NameError: # Exception raised loading the library, thus res_init is not defined pass @jinja_filter('connection_check') def connection_check(addr, port=80, safe=False, ipv6=None): ''' Provides a convenient alias for the dns_check filter. ''' return dns_check(addr, port, safe, ipv6) @jinja_filter('dns_check') def dns_check(addr, port=80, safe=False, ipv6=None, attempt_connect=True): ''' Return the ip resolved by dns, but do not exit on failure, only raise an exception. Obeys system preference for IPv4/6 address resolution - this can be overridden by the ipv6 flag. Tries to connect to the address before considering it useful. If no address can be reached, the first one resolved is used as a fallback. ''' error = False lookup = addr seen_ipv6 = False family = socket.AF_INET6 if ipv6 else socket.AF_INET if ipv6 is False else socket.AF_UNSPEC hostnames = [] try: refresh_dns() hostnames = socket.getaddrinfo(addr, port, family, socket.SOCK_STREAM) except TypeError: err = ('Attempt to resolve address \'{0}\' failed. Invalid or unresolveable address').format(lookup) raise SaltSystemExit(code=42, msg=err) except socket.error: error = True # If ipv6 is set to True, attempt another lookup using the IPv4 family, # just in case we're attempting to lookup an IPv4 IP # as an IPv6 hostname. if error and ipv6: try: refresh_dns() hostnames = socket.getaddrinfo(addr, port, socket.AF_INET, socket.SOCK_STREAM) except TypeError: err = ('Attempt to resolve address \'{0}\' failed. Invalid or unresolveable address').format(lookup) raise SaltSystemExit(code=42, msg=err) except socket.error: error = True try: if not hostnames: error = True else: resolved = False candidates = [] for h in hostnames: # Input is IP address, passed through unchanged, just return it if h[4][0] == addr: resolved = salt.utils.zeromq.ip_bracket(addr) break candidate_addr = salt.utils.zeromq.ip_bracket(h[4][0]) # sometimes /etc/hosts contains ::1 localhost if not ipv6 and candidate_addr == '[::1]': continue candidates.append(candidate_addr) if attempt_connect: try: s = socket.socket(h[0], socket.SOCK_STREAM) s.settimeout(2) s.connect((candidate_addr.strip('[]'), h[4][1])) s.close() resolved = candidate_addr break except socket.error: pass if not resolved: if candidates: resolved = candidates[0] else: error = True except TypeError: err = ('Attempt to resolve address \'{0}\' failed. Invalid or unresolveable address').format(lookup) raise SaltSystemExit(code=42, msg=err) except socket.error: error = True if error: err = ('DNS lookup or connection check of \'{0}\' failed.').format(addr) if safe: if salt.log.is_console_configured(): # If logging is not configured it also means that either # the master or minion instance calling this hasn't even # started running log.error(err) raise SaltClientError() raise SaltSystemExit(code=42, msg=err) return resolved def parse_host_port(host_port): """ Takes a string argument specifying host or host:port. Returns a (hostname, port) or (ip_address, port) tuple. If no port is given, the second (port) element of the returned tuple will be None. host:port argument, for example, is accepted in the forms of: - hostname - hostname:1234 - hostname.domain.tld - hostname.domain.tld:5678 - [1234::5]:5678 - 1234::5 - 10.11.12.13:4567 - 10.11.12.13 """ host, port = None, None # default _s_ = host_port[:] if _s_[0] == "[": if "]" in host_port: host, _s_ = _s_.lstrip("[").rsplit("]", 1) host = ipaddress.IPv6Address(host).compressed if _s_[0] == ":": port = int(_s_.lstrip(":")) else: if len(_s_) > 1: raise ValueError('found ambiguous "{}" port in "{}"'.format(_s_, host_port)) else: if _s_.count(":") == 1: host, _hostport_separator_, port = _s_.partition(":") try: port = int(port) except ValueError as _e_: log.error('host_port "%s" port value "%s" is not an integer.', host_port, port) raise _e_ else: host = _s_ try: if not isinstance(host, ipaddress._BaseAddress): host_ip = ipaddress.ip_address(host).compressed host = host_ip except ValueError: log.debug('"%s" Not an IP address? Assuming it is a hostname.', host) if host != sanitize_host(host): log.error('bad hostname: "%s"', host) raise ValueError('bad hostname: "{}"'.format(host)) return host, port def is_fqdn(hostname): """ Verify if hostname conforms to be a FQDN. :param hostname: text string with the name of the host :return: bool, True if hostname is correct FQDN, False otherwise """ compliant = re.compile(r"(?!-)[A-Z\d\-\_]{1,63}(?<!-)$", re.IGNORECASE) return "." in hostname and len(hostname) < 0xff and all(compliant.match(x) for x in hostname.rstrip(".").split("."))
saltstack/salt
salt/utils/network.py
hex2ip
python
def hex2ip(hex_ip, invert=False): ''' Convert a hex string to an ip, if a failure occurs the original hex is returned. If 'invert=True' assume that ip from /proc/net/<proto> ''' if len(hex_ip) == 32: # ipv6 ip = [] for i in range(0, 32, 8): ip_part = hex_ip[i:i + 8] ip_part = [ip_part[x:x + 2] for x in range(0, 8, 2)] if invert: ip.append("{0[3]}{0[2]}:{0[1]}{0[0]}".format(ip_part)) else: ip.append("{0[0]}{0[1]}:{0[2]}{0[3]}".format(ip_part)) try: address = ipaddress.IPv6Address(":".join(ip)) if address.ipv4_mapped: return str(address.ipv4_mapped) else: return address.compressed except ipaddress.AddressValueError as ex: log.error('hex2ip - ipv6 address error: %s', ex) return hex_ip try: hip = int(hex_ip, 16) except ValueError: return hex_ip if invert: return '{3}.{2}.{1}.{0}'.format(hip >> 24 & 255, hip >> 16 & 255, hip >> 8 & 255, hip & 255) return '{0}.{1}.{2}.{3}'.format(hip >> 24 & 255, hip >> 16 & 255, hip >> 8 & 255, hip & 255)
Convert a hex string to an ip, if a failure occurs the original hex is returned. If 'invert=True' assume that ip from /proc/net/<proto>
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/network.py#L1304-L1340
null
# -*- coding: utf-8 -*- ''' Define some generic socket functions for network modules ''' # Import python libs from __future__ import absolute_import, unicode_literals, print_function import itertools import os import re import types import socket import logging import platform import random import subprocess from string import ascii_letters, digits # Import 3rd-party libs from salt.ext import six from salt.ext.six.moves import range # pylint: disable=import-error,redefined-builtin # Attempt to import wmi try: import wmi import salt.utils.winapi except ImportError: pass # Import salt libs import salt.utils.args import salt.utils.files import salt.utils.path import salt.utils.platform import salt.utils.stringutils import salt.utils.zeromq from salt._compat import ipaddress from salt.exceptions import SaltClientError, SaltSystemExit from salt.utils.decorators.jinja import jinja_filter from salt.utils.versions import LooseVersion # inet_pton does not exist in Windows, this is a workaround if salt.utils.platform.is_windows(): from salt.ext import win_inet_pton # pylint: disable=unused-import log = logging.getLogger(__name__) try: import ctypes import ctypes.util libc = ctypes.cdll.LoadLibrary(ctypes.util.find_library("c")) res_init = libc.__res_init except (ImportError, OSError, AttributeError, TypeError): pass # pylint: disable=C0103 def sanitize_host(host): ''' Sanitize host string. https://tools.ietf.org/html/rfc1123#section-2.1 ''' RFC952_characters = ascii_letters + digits + ".-" return "".join([c for c in host[0:255] if c in RFC952_characters]) def isportopen(host, port): ''' Return status of a port ''' if not 1 <= int(port) <= 65535: return False sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) out = sock.connect_ex((sanitize_host(host), int(port))) return out def host_to_ips(host): ''' Returns a list of IP addresses of a given hostname or None if not found. ''' ips = [] try: for family, socktype, proto, canonname, sockaddr in socket.getaddrinfo( host, 0, socket.AF_UNSPEC, socket.SOCK_STREAM): if family == socket.AF_INET: ip, port = sockaddr elif family == socket.AF_INET6: ip, port, flow_info, scope_id = sockaddr ips.append(ip) if not ips: ips = None except Exception: ips = None return ips def _generate_minion_id(): ''' Get list of possible host names and convention names. :return: ''' # There are three types of hostnames: # 1. Network names. How host is accessed from the network. # 2. Host aliases. They might be not available in all the network or only locally (/etc/hosts) # 3. Convention names, an internal nodename. class DistinctList(list): ''' List, which allows one to append only distinct objects. Needs to work on Python 2.6, because of collections.OrderedDict only since 2.7 version. Override 'filter()' for custom filtering. ''' localhost_matchers = [r'localhost.*', r'ip6-.*', r'127[.]\d', r'0\.0\.0\.0', r'::1.*', r'ipv6-.*', r'fe00::.*', r'fe02::.*', r'1.0.0.*.ip6.arpa'] def append(self, p_object): if p_object and p_object not in self and not self.filter(p_object): super(DistinctList, self).append(p_object) return self def extend(self, iterable): for obj in iterable: self.append(obj) return self def filter(self, element): 'Returns True if element needs to be filtered' for rgx in self.localhost_matchers: if re.match(rgx, element): return True def first(self): return self and self[0] or None hostname = socket.gethostname() hosts = DistinctList().append( salt.utils.stringutils.to_unicode(socket.getfqdn(salt.utils.stringutils.to_bytes(hostname))) ).append(platform.node()).append(hostname) if not hosts: try: for a_nfo in socket.getaddrinfo(hosts.first() or 'localhost', None, socket.AF_INET, socket.SOCK_RAW, socket.IPPROTO_IP, socket.AI_CANONNAME): if len(a_nfo) > 3: hosts.append(a_nfo[3]) except socket.gaierror: log.warning('Cannot resolve address %s info via socket: %s', hosts.first() or 'localhost (N/A)', socket.gaierror) # Universal method for everywhere (Linux, Slowlaris, Windows etc) for f_name in ('/etc/hostname', '/etc/nodename', '/etc/hosts', r'{win}\system32\drivers\etc\hosts'.format(win=os.getenv('WINDIR'))): try: with salt.utils.files.fopen(f_name) as f_hdl: for line in f_hdl: line = salt.utils.stringutils.to_unicode(line) hst = line.strip().split('#')[0].strip().split() if hst: if hst[0][:4] in ('127.', '::1') or len(hst) == 1: hosts.extend(hst) except IOError: pass # include public and private ipaddresses return hosts.extend([addr for addr in ip_addrs() if not ipaddress.ip_address(addr).is_loopback]) def generate_minion_id(): ''' Return only first element of the hostname from all possible list. :return: ''' try: ret = salt.utils.stringutils.to_unicode(_generate_minion_id().first()) except TypeError: ret = None return ret or 'localhost' def get_socket(addr, type=socket.SOCK_STREAM, proto=0): ''' Return a socket object for the addr IP-version agnostic ''' version = ipaddress.ip_address(addr).version if version == 4: family = socket.AF_INET elif version == 6: family = socket.AF_INET6 return socket.socket(family, type, proto) def get_fqhostname(): ''' Returns the fully qualified hostname ''' # try getaddrinfo() fqdn = None try: addrinfo = socket.getaddrinfo( socket.gethostname(), 0, socket.AF_UNSPEC, socket.SOCK_STREAM, socket.SOL_TCP, socket.AI_CANONNAME ) for info in addrinfo: # info struct [family, socktype, proto, canonname, sockaddr] # On Windows `canonname` can be an empty string # This can cause the function to return `None` if len(info) > 3 and info[3]: fqdn = info[3] break except socket.gaierror: pass # NOTE: this used to log.error() but it was later disabled except socket.error as err: log.debug('socket.getaddrinfo() failure while finding fqdn: %s', err) if fqdn is None: fqdn = socket.getfqdn() return fqdn def ip_to_host(ip): ''' Returns the hostname of a given IP ''' try: hostname, aliaslist, ipaddrlist = socket.gethostbyaddr(ip) except Exception as exc: log.debug('salt.utils.network.ip_to_host(%r) failed: %s', ip, exc) hostname = None return hostname # pylint: enable=C0103 def is_reachable_host(entity_name): ''' Returns a bool telling if the entity name is a reachable host (IPv4/IPv6/FQDN/etc). :param hostname: :return: ''' try: assert type(socket.getaddrinfo(entity_name, 0, 0, 0, 0)) == list ret = True except socket.gaierror: ret = False return ret def is_ip(ip): ''' Returns a bool telling if the passed IP is a valid IPv4 or IPv6 address. ''' return is_ipv4(ip) or is_ipv6(ip) def is_ipv4(ip): ''' Returns a bool telling if the value passed to it was a valid IPv4 address ''' try: return ipaddress.ip_address(ip).version == 4 except ValueError: return False def is_ipv6(ip): ''' Returns a bool telling if the value passed to it was a valid IPv6 address ''' try: return ipaddress.ip_address(ip).version == 6 except ValueError: return False def is_subnet(cidr): ''' Returns a bool telling if the passed string is an IPv4 or IPv6 subnet ''' return is_ipv4_subnet(cidr) or is_ipv6_subnet(cidr) def is_ipv4_subnet(cidr): ''' Returns a bool telling if the passed string is an IPv4 subnet ''' try: return '/' in cidr and bool(ipaddress.IPv4Network(cidr)) except Exception: return False def is_ipv6_subnet(cidr): ''' Returns a bool telling if the passed string is an IPv6 subnet ''' try: return '/' in cidr and bool(ipaddress.IPv6Network(cidr)) except Exception: return False @jinja_filter('is_ip') def is_ip_filter(ip, options=None): ''' Returns a bool telling if the passed IP is a valid IPv4 or IPv6 address. ''' return is_ipv4_filter(ip, options=options) or is_ipv6_filter(ip, options=options) def _ip_options_global(ip_obj, version): return not ip_obj.is_private def _ip_options_multicast(ip_obj, version): return ip_obj.is_multicast def _ip_options_loopback(ip_obj, version): return ip_obj.is_loopback def _ip_options_link_local(ip_obj, version): return ip_obj.is_link_local def _ip_options_private(ip_obj, version): return ip_obj.is_private def _ip_options_reserved(ip_obj, version): return ip_obj.is_reserved def _ip_options_site_local(ip_obj, version): if version == 6: return ip_obj.is_site_local return False def _ip_options_unspecified(ip_obj, version): return ip_obj.is_unspecified def _ip_options(ip_obj, version, options=None): # will process and IP options options_fun_map = { 'global': _ip_options_global, 'link-local': _ip_options_link_local, 'linklocal': _ip_options_link_local, 'll': _ip_options_link_local, 'link_local': _ip_options_link_local, 'loopback': _ip_options_loopback, 'lo': _ip_options_loopback, 'multicast': _ip_options_multicast, 'private': _ip_options_private, 'public': _ip_options_global, 'reserved': _ip_options_reserved, 'site-local': _ip_options_site_local, 'sl': _ip_options_site_local, 'site_local': _ip_options_site_local, 'unspecified': _ip_options_unspecified } if not options: return six.text_type(ip_obj) # IP version already checked options_list = [option.strip() for option in options.split(',')] for option, fun in options_fun_map.items(): if option in options_list: fun_res = fun(ip_obj, version) if not fun_res: return None # stop at first failed test # else continue return six.text_type(ip_obj) def _is_ipv(ip, version, options=None): if not version: version = 4 if version not in (4, 6): return None try: ip_obj = ipaddress.ip_address(ip) except ValueError: # maybe it is an IP network try: ip_obj = ipaddress.ip_interface(ip) except ValueError: # nope, still not :( return None if not ip_obj.version == version: return None # has the right version, let's move on return _ip_options(ip_obj, version, options=options) @jinja_filter('is_ipv4') def is_ipv4_filter(ip, options=None): ''' Returns a bool telling if the value passed to it was a valid IPv4 address. ip The IP address. net: False Consider IP addresses followed by netmask. options CSV of options regarding the nature of the IP address. E.g.: loopback, multicast, private etc. ''' _is_ipv4 = _is_ipv(ip, 4, options=options) return isinstance(_is_ipv4, six.string_types) @jinja_filter('is_ipv6') def is_ipv6_filter(ip, options=None): ''' Returns a bool telling if the value passed to it was a valid IPv6 address. ip The IP address. net: False Consider IP addresses followed by netmask. options CSV of options regarding the nature of the IP address. E.g.: loopback, multicast, private etc. ''' _is_ipv6 = _is_ipv(ip, 6, options=options) return isinstance(_is_ipv6, six.string_types) def _ipv_filter(value, version, options=None): if version not in (4, 6): return if isinstance(value, (six.string_types, six.text_type, six.binary_type)): return _is_ipv(value, version, options=options) # calls is_ipv4 or is_ipv6 for `value` elif isinstance(value, (list, tuple, types.GeneratorType)): # calls is_ipv4 or is_ipv6 for each element in the list # os it filters and returns only those elements having the desired IP version return [ _is_ipv(addr, version, options=options) for addr in value if _is_ipv(addr, version, options=options) is not None ] return None @jinja_filter('ipv4') def ipv4(value, options=None): ''' Filters a list and returns IPv4 values only. ''' return _ipv_filter(value, 4, options=options) @jinja_filter('ipv6') def ipv6(value, options=None): ''' Filters a list and returns IPv6 values only. ''' return _ipv_filter(value, 6, options=options) @jinja_filter('ipaddr') def ipaddr(value, options=None): ''' Filters and returns only valid IP objects. ''' ipv4_obj = ipv4(value, options=options) ipv6_obj = ipv6(value, options=options) if ipv4_obj is None or ipv6_obj is None: # an IP address can be either IPv4 either IPv6 # therefofe if the value passed as arg is not a list, at least one of the calls above will return None # if one of them is none, means that we should return only one of them return ipv4_obj or ipv6_obj # one of them else: return ipv4_obj + ipv6_obj # extend lists def _filter_ipaddr(value, options, version=None): ipaddr_filter_out = None if version: if version == 4: ipaddr_filter_out = ipv4(value, options) elif version == 6: ipaddr_filter_out = ipv6(value, options) else: ipaddr_filter_out = ipaddr(value, options) if not ipaddr_filter_out: return if not isinstance(ipaddr_filter_out, (list, tuple, types.GeneratorType)): ipaddr_filter_out = [ipaddr_filter_out] return ipaddr_filter_out @jinja_filter('ip_host') def ip_host(value, options=None, version=None): ''' Returns the interfaces IP address, e.g.: 192.168.0.1/28. ''' ipaddr_filter_out = _filter_ipaddr(value, options=options, version=version) if not ipaddr_filter_out: return if not isinstance(value, (list, tuple, types.GeneratorType)): return six.text_type(ipaddress.ip_interface(ipaddr_filter_out[0])) return [six.text_type(ipaddress.ip_interface(ip_a)) for ip_a in ipaddr_filter_out] def _network_hosts(ip_addr_entry): return [ six.text_type(host) for host in ipaddress.ip_network(ip_addr_entry, strict=False).hosts() ] @jinja_filter('network_hosts') def network_hosts(value, options=None, version=None): ''' Return the list of hosts within a network. .. note:: When running this command with a large IPv6 network, the command will take a long time to gather all of the hosts. ''' ipaddr_filter_out = _filter_ipaddr(value, options=options, version=version) if not ipaddr_filter_out: return if not isinstance(value, (list, tuple, types.GeneratorType)): return _network_hosts(ipaddr_filter_out[0]) return [ _network_hosts(ip_a) for ip_a in ipaddr_filter_out ] def _network_size(ip_addr_entry): return ipaddress.ip_network(ip_addr_entry, strict=False).num_addresses @jinja_filter('network_size') def network_size(value, options=None, version=None): ''' Get the size of a network. ''' ipaddr_filter_out = _filter_ipaddr(value, options=options, version=version) if not ipaddr_filter_out: return if not isinstance(value, (list, tuple, types.GeneratorType)): return _network_size(ipaddr_filter_out[0]) return [ _network_size(ip_a) for ip_a in ipaddr_filter_out ] def natural_ipv4_netmask(ip, fmt='prefixlen'): ''' Returns the "natural" mask of an IPv4 address ''' bits = _ipv4_to_bits(ip) if bits.startswith('11'): mask = '24' elif bits.startswith('1'): mask = '16' else: mask = '8' if fmt == 'netmask': return cidr_to_ipv4_netmask(mask) else: return '/' + mask def rpad_ipv4_network(ip): ''' Returns an IP network address padded with zeros. Ex: '192.168.3' -> '192.168.3.0' '10.209' -> '10.209.0.0' ''' return '.'.join(itertools.islice(itertools.chain(ip.split('.'), '0000'), 0, 4)) def cidr_to_ipv4_netmask(cidr_bits): ''' Returns an IPv4 netmask ''' try: cidr_bits = int(cidr_bits) if not 1 <= cidr_bits <= 32: return '' except ValueError: return '' netmask = '' for idx in range(4): if idx: netmask += '.' if cidr_bits >= 8: netmask += '255' cidr_bits -= 8 else: netmask += '{0:d}'.format(256 - (2 ** (8 - cidr_bits))) cidr_bits = 0 return netmask def _number_of_set_bits_to_ipv4_netmask(set_bits): # pylint: disable=C0103 ''' Returns an IPv4 netmask from the integer representation of that mask. Ex. 0xffffff00 -> '255.255.255.0' ''' return cidr_to_ipv4_netmask(_number_of_set_bits(set_bits)) # pylint: disable=C0103 def _number_of_set_bits(x): ''' Returns the number of bits that are set in a 32bit int ''' # Taken from http://stackoverflow.com/a/4912729. Many thanks! x -= (x >> 1) & 0x55555555 x = ((x >> 2) & 0x33333333) + (x & 0x33333333) x = ((x >> 4) + x) & 0x0f0f0f0f x += x >> 8 x += x >> 16 return x & 0x0000003f # pylint: enable=C0103 def _interfaces_ip(out): ''' Uses ip to return a dictionary of interfaces with various information about each (up/down state, ip address, netmask, and hwaddr) ''' ret = dict() def parse_network(value, cols): ''' Return a tuple of ip, netmask, broadcast based on the current set of cols ''' brd = None scope = None if '/' in value: # we have a CIDR in this address ip, cidr = value.split('/') # pylint: disable=C0103 else: ip = value # pylint: disable=C0103 cidr = 32 if type_ == 'inet': mask = cidr_to_ipv4_netmask(int(cidr)) if 'brd' in cols: brd = cols[cols.index('brd') + 1] elif type_ == 'inet6': mask = cidr if 'scope' in cols: scope = cols[cols.index('scope') + 1] return (ip, mask, brd, scope) groups = re.compile('\r?\n\\d').split(out) for group in groups: iface = None data = dict() for line in group.splitlines(): if ' ' not in line: continue match = re.match(r'^\d*:\s+([\w.\-]+)(?:@)?([\w.\-]+)?:\s+<(.+)>', line) if match: iface, parent, attrs = match.groups() if 'UP' in attrs.split(','): data['up'] = True else: data['up'] = False if parent: data['parent'] = parent continue cols = line.split() if len(cols) >= 2: type_, value = tuple(cols[0:2]) iflabel = cols[-1:][0] if type_ in ('inet', 'inet6'): if 'secondary' not in cols: ipaddr, netmask, broadcast, scope = parse_network(value, cols) if type_ == 'inet': if 'inet' not in data: data['inet'] = list() addr_obj = dict() addr_obj['address'] = ipaddr addr_obj['netmask'] = netmask addr_obj['broadcast'] = broadcast addr_obj['label'] = iflabel data['inet'].append(addr_obj) elif type_ == 'inet6': if 'inet6' not in data: data['inet6'] = list() addr_obj = dict() addr_obj['address'] = ipaddr addr_obj['prefixlen'] = netmask addr_obj['scope'] = scope data['inet6'].append(addr_obj) else: if 'secondary' not in data: data['secondary'] = list() ip_, mask, brd, scp = parse_network(value, cols) data['secondary'].append({ 'type': type_, 'address': ip_, 'netmask': mask, 'broadcast': brd, 'label': iflabel, }) del ip_, mask, brd, scp elif type_.startswith('link'): data['hwaddr'] = value if iface: ret[iface] = data del iface, data return ret def _interfaces_ifconfig(out): ''' Uses ifconfig to return a dictionary of interfaces with various information about each (up/down state, ip address, netmask, and hwaddr) ''' ret = dict() piface = re.compile(r'^([^\s:]+)') pmac = re.compile('.*?(?:HWaddr|ether|address:|lladdr) ([0-9a-fA-F:]+)') if salt.utils.platform.is_sunos(): pip = re.compile(r'.*?(?:inet\s+)([0-9]+\.[0-9]+\.[0-9]+\.[0-9]+)(.*)') pip6 = re.compile('.*?(?:inet6 )([0-9a-fA-F:]+)') pmask6 = re.compile(r'.*?(?:inet6 [0-9a-fA-F:]+/(\d+)).*') else: pip = re.compile(r'.*?(?:inet addr:|inet [^\d]*)(.*?)\s') pip6 = re.compile('.*?(?:inet6 addr: (.*?)/|inet6 )([0-9a-fA-F:]+)') pmask6 = re.compile(r'.*?(?:inet6 addr: [0-9a-fA-F:]+/(\d+)|prefixlen (\d+))(?: Scope:([a-zA-Z]+)| scopeid (0x[0-9a-fA-F]))?') pmask = re.compile(r'.*?(?:Mask:|netmask )(?:((?:0x)?[0-9a-fA-F]{8})|([\d\.]+))') pupdown = re.compile('UP') pbcast = re.compile(r'.*?(?:Bcast:|broadcast )([\d\.]+)') groups = re.compile('\r?\n(?=\\S)').split(out) for group in groups: data = dict() iface = '' updown = False for line in group.splitlines(): miface = piface.match(line) mmac = pmac.match(line) mip = pip.match(line) mip6 = pip6.match(line) mupdown = pupdown.search(line) if miface: iface = miface.group(1) if mmac: data['hwaddr'] = mmac.group(1) if salt.utils.platform.is_sunos(): expand_mac = [] for chunk in data['hwaddr'].split(':'): expand_mac.append('0{0}'.format(chunk) if len(chunk) < 2 else '{0}'.format(chunk)) data['hwaddr'] = ':'.join(expand_mac) if mip: if 'inet' not in data: data['inet'] = list() addr_obj = dict() addr_obj['address'] = mip.group(1) mmask = pmask.match(line) if mmask: if mmask.group(1): mmask = _number_of_set_bits_to_ipv4_netmask( int(mmask.group(1), 16)) else: mmask = mmask.group(2) addr_obj['netmask'] = mmask mbcast = pbcast.match(line) if mbcast: addr_obj['broadcast'] = mbcast.group(1) data['inet'].append(addr_obj) if mupdown: updown = True if mip6: if 'inet6' not in data: data['inet6'] = list() addr_obj = dict() addr_obj['address'] = mip6.group(1) or mip6.group(2) mmask6 = pmask6.match(line) if mmask6: addr_obj['prefixlen'] = mmask6.group(1) or mmask6.group(2) if not salt.utils.platform.is_sunos(): ipv6scope = mmask6.group(3) or mmask6.group(4) addr_obj['scope'] = ipv6scope.lower() if ipv6scope is not None else ipv6scope # SunOS sometimes has ::/0 as inet6 addr when using addrconf if not salt.utils.platform.is_sunos() \ or addr_obj['address'] != '::' \ and addr_obj['prefixlen'] != 0: data['inet6'].append(addr_obj) data['up'] = updown if iface in ret: # SunOS optimization, where interfaces occur twice in 'ifconfig -a' # output with the same name: for ipv4 and then for ipv6 addr family. # Every instance has it's own 'UP' status and we assume that ipv4 # status determines global interface status. # # merge items with higher priority for older values # after that merge the inet and inet6 sub items for both ret[iface] = dict(list(data.items()) + list(ret[iface].items())) if 'inet' in data: ret[iface]['inet'].extend(x for x in data['inet'] if x not in ret[iface]['inet']) if 'inet6' in data: ret[iface]['inet6'].extend(x for x in data['inet6'] if x not in ret[iface]['inet6']) else: ret[iface] = data del data return ret def linux_interfaces(): ''' Obtain interface information for *NIX/BSD variants ''' ifaces = dict() ip_path = salt.utils.path.which('ip') ifconfig_path = None if ip_path else salt.utils.path.which('ifconfig') if ip_path: cmd1 = subprocess.Popen( '{0} link show'.format(ip_path), shell=True, close_fds=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT).communicate()[0] cmd2 = subprocess.Popen( '{0} addr show'.format(ip_path), shell=True, close_fds=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT).communicate()[0] ifaces = _interfaces_ip("{0}\n{1}".format( salt.utils.stringutils.to_str(cmd1), salt.utils.stringutils.to_str(cmd2))) elif ifconfig_path: cmd = subprocess.Popen( '{0} -a'.format(ifconfig_path), shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT).communicate()[0] ifaces = _interfaces_ifconfig(salt.utils.stringutils.to_str(cmd)) return ifaces def _netbsd_interfaces_ifconfig(out): ''' Uses ifconfig to return a dictionary of interfaces with various information about each (up/down state, ip address, netmask, and hwaddr) ''' ret = dict() piface = re.compile(r'^([^\s:]+)') pmac = re.compile('.*?address: ([0-9a-f:]+)') pip = re.compile(r'.*?inet [^\d]*(.*?)/([\d]*)\s') pip6 = re.compile(r'.*?inet6 ([0-9a-f:]+)%([a-zA-Z0-9]*)/([\d]*)\s') pupdown = re.compile('UP') pbcast = re.compile(r'.*?broadcast ([\d\.]+)') groups = re.compile('\r?\n(?=\\S)').split(out) for group in groups: data = dict() iface = '' updown = False for line in group.splitlines(): miface = piface.match(line) mmac = pmac.match(line) mip = pip.match(line) mip6 = pip6.match(line) mupdown = pupdown.search(line) if miface: iface = miface.group(1) if mmac: data['hwaddr'] = mmac.group(1) if mip: if 'inet' not in data: data['inet'] = list() addr_obj = dict() addr_obj['address'] = mip.group(1) mmask = mip.group(2) if mip.group(2): addr_obj['netmask'] = cidr_to_ipv4_netmask(mip.group(2)) mbcast = pbcast.match(line) if mbcast: addr_obj['broadcast'] = mbcast.group(1) data['inet'].append(addr_obj) if mupdown: updown = True if mip6: if 'inet6' not in data: data['inet6'] = list() addr_obj = dict() addr_obj['address'] = mip6.group(1) mmask6 = mip6.group(3) addr_obj['scope'] = mip6.group(2) addr_obj['prefixlen'] = mip6.group(3) data['inet6'].append(addr_obj) data['up'] = updown ret[iface] = data del data return ret def netbsd_interfaces(): ''' Obtain interface information for NetBSD >= 8 where the ifconfig output diverged from other BSD variants (Netmask is now part of the address) ''' # NetBSD versions prior to 8.0 can still use linux_interfaces() if LooseVersion(os.uname()[2]) < LooseVersion('8.0'): return linux_interfaces() ifconfig_path = salt.utils.path.which('ifconfig') cmd = subprocess.Popen( '{0} -a'.format(ifconfig_path), shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT).communicate()[0] return _netbsd_interfaces_ifconfig(salt.utils.stringutils.to_str(cmd)) def _interfaces_ipconfig(out): ''' Returns a dictionary of interfaces with various information about each (up/down state, ip address, netmask, and hwaddr) NOTE: This is not used by any function and may be able to be removed in the future. ''' ifaces = dict() iface = None adapter_iface_regex = re.compile(r'adapter (\S.+):$') for line in out.splitlines(): if not line: continue # TODO what does Windows call Infiniband and 10/40gige adapters if line.startswith('Ethernet'): iface = ifaces[adapter_iface_regex.search(line).group(1)] iface['up'] = True addr = None continue if iface: key, val = line.split(',', 1) key = key.strip(' .') val = val.strip() if addr and key == 'Subnet Mask': addr['netmask'] = val elif key in ('IP Address', 'IPv4 Address'): if 'inet' not in iface: iface['inet'] = list() addr = {'address': val.rstrip('(Preferred)'), 'netmask': None, 'broadcast': None} # TODO find the broadcast iface['inet'].append(addr) elif 'IPv6 Address' in key: if 'inet6' not in iface: iface['inet'] = list() # XXX What is the prefixlen!? addr = {'address': val.rstrip('(Preferred)'), 'prefixlen': None} iface['inet6'].append(addr) elif key == 'Physical Address': iface['hwaddr'] = val elif key == 'Media State': # XXX seen used for tunnel adaptors # might be useful iface['up'] = (val != 'Media disconnected') def win_interfaces(): ''' Obtain interface information for Windows systems ''' with salt.utils.winapi.Com(): c = wmi.WMI() ifaces = {} for iface in c.Win32_NetworkAdapterConfiguration(IPEnabled=1): ifaces[iface.Description] = dict() if iface.MACAddress: ifaces[iface.Description]['hwaddr'] = iface.MACAddress if iface.IPEnabled: ifaces[iface.Description]['up'] = True for ip in iface.IPAddress: if '.' in ip: if 'inet' not in ifaces[iface.Description]: ifaces[iface.Description]['inet'] = [] item = {'address': ip, 'label': iface.Description} if iface.DefaultIPGateway: broadcast = next((i for i in iface.DefaultIPGateway if '.' in i), '') if broadcast: item['broadcast'] = broadcast if iface.IPSubnet: netmask = next((i for i in iface.IPSubnet if '.' in i), '') if netmask: item['netmask'] = netmask ifaces[iface.Description]['inet'].append(item) if ':' in ip: if 'inet6' not in ifaces[iface.Description]: ifaces[iface.Description]['inet6'] = [] item = {'address': ip} if iface.DefaultIPGateway: broadcast = next((i for i in iface.DefaultIPGateway if ':' in i), '') if broadcast: item['broadcast'] = broadcast if iface.IPSubnet: netmask = next((i for i in iface.IPSubnet if ':' in i), '') if netmask: item['netmask'] = netmask ifaces[iface.Description]['inet6'].append(item) else: ifaces[iface.Description]['up'] = False return ifaces def interfaces(): ''' Return a dictionary of information about all the interfaces on the minion ''' if salt.utils.platform.is_windows(): return win_interfaces() elif salt.utils.platform.is_netbsd(): return netbsd_interfaces() else: return linux_interfaces() def get_net_start(ipaddr, netmask): ''' Return the address of the network ''' net = ipaddress.ip_network('{0}/{1}'.format(ipaddr, netmask), strict=False) return six.text_type(net.network_address) def get_net_size(mask): ''' Turns an IPv4 netmask into it's corresponding prefix length (255.255.255.0 -> 24 as in 192.168.1.10/24). ''' binary_str = '' for octet in mask.split('.'): binary_str += bin(int(octet))[2:].zfill(8) return len(binary_str.rstrip('0')) def calc_net(ipaddr, netmask=None): ''' Takes IP (CIDR notation supported) and optionally netmask and returns the network in CIDR-notation. (The IP can be any IP inside the subnet) ''' if netmask is not None: ipaddr = '{0}/{1}'.format(ipaddr, netmask) return six.text_type(ipaddress.ip_network(ipaddr, strict=False)) def _ipv4_to_bits(ipaddr): ''' Accepts an IPv4 dotted quad and returns a string representing its binary counterpart ''' return ''.join([bin(int(x))[2:].rjust(8, '0') for x in ipaddr.split('.')]) def _get_iface_info(iface): ''' If `iface` is available, return interface info and no error, otherwise return no info and log and return an error ''' iface_info = interfaces() if iface in iface_info.keys(): return iface_info, False else: error_msg = ('Interface "{0}" not in available interfaces: "{1}"' ''.format(iface, '", "'.join(iface_info.keys()))) log.error(error_msg) return None, error_msg def _hw_addr_aix(iface): ''' Return the hardware address (a.k.a. MAC address) for a given interface on AIX MAC address not available in through interfaces ''' cmd = subprocess.Popen( 'entstat -d {0} | grep \'Hardware Address\''.format(iface), shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT).communicate()[0] if cmd: comps = cmd.split(' ') if len(comps) == 3: mac_addr = comps[2].strip('\'').strip() return mac_addr error_msg = ('Interface "{0}" either not available or does not contain a hardware address'.format(iface)) log.error(error_msg) return error_msg def hw_addr(iface): ''' Return the hardware address (a.k.a. MAC address) for a given interface .. versionchanged:: 2016.11.4 Added support for AIX ''' if salt.utils.platform.is_aix(): return _hw_addr_aix iface_info, error = _get_iface_info(iface) if error is False: return iface_info.get(iface, {}).get('hwaddr', '') else: return error def interface(iface): ''' Return the details of `iface` or an error if it does not exist ''' iface_info, error = _get_iface_info(iface) if error is False: return iface_info.get(iface, {}).get('inet', '') else: return error def interface_ip(iface): ''' Return `iface` IPv4 addr or an error if `iface` does not exist ''' iface_info, error = _get_iface_info(iface) if error is False: inet = iface_info.get(iface, {}).get('inet', None) return inet[0].get('address', '') if inet else '' else: return error def _subnets(proto='inet', interfaces_=None): ''' Returns a list of subnets to which the host belongs ''' if interfaces_ is None: ifaces = interfaces() elif isinstance(interfaces_, list): ifaces = {} for key, value in six.iteritems(interfaces()): if key in interfaces_: ifaces[key] = value else: ifaces = {interfaces_: interfaces().get(interfaces_, {})} ret = set() if proto == 'inet': subnet = 'netmask' dflt_cidr = 32 elif proto == 'inet6': subnet = 'prefixlen' dflt_cidr = 128 else: log.error('Invalid proto %s calling subnets()', proto) return for ip_info in six.itervalues(ifaces): addrs = ip_info.get(proto, []) addrs.extend([addr for addr in ip_info.get('secondary', []) if addr.get('type') == proto]) for intf in addrs: if subnet in intf: intf = ipaddress.ip_interface('{0}/{1}'.format(intf['address'], intf[subnet])) else: intf = ipaddress.ip_interface('{0}/{1}'.format(intf['address'], dflt_cidr)) if not intf.is_loopback: ret.add(intf.network) return [six.text_type(net) for net in sorted(ret)] def subnets(interfaces=None): ''' Returns a list of IPv4 subnets to which the host belongs ''' return _subnets('inet', interfaces_=interfaces) def subnets6(): ''' Returns a list of IPv6 subnets to which the host belongs ''' return _subnets('inet6') def in_subnet(cidr, addr=None): ''' Returns True if host or (any of) addrs is within specified subnet, otherwise False ''' try: cidr = ipaddress.ip_network(cidr) except ValueError: log.error('Invalid CIDR \'%s\'', cidr) return False if addr is None: addr = ip_addrs() addr.extend(ip_addrs6()) elif not isinstance(addr, (list, tuple)): addr = (addr,) return any(ipaddress.ip_address(item) in cidr for item in addr) def _ip_addrs(interface=None, include_loopback=False, interface_data=None, proto='inet'): ''' Return the full list of IP adresses matching the criteria proto = inet|inet6 ''' ret = set() ifaces = interface_data \ if isinstance(interface_data, dict) \ else interfaces() if interface is None: target_ifaces = ifaces else: target_ifaces = dict([(k, v) for k, v in six.iteritems(ifaces) if k == interface]) if not target_ifaces: log.error('Interface %s not found.', interface) for ip_info in six.itervalues(target_ifaces): addrs = ip_info.get(proto, []) addrs.extend([addr for addr in ip_info.get('secondary', []) if addr.get('type') == proto]) for addr in addrs: addr = ipaddress.ip_address(addr.get('address')) if not addr.is_loopback or include_loopback: ret.add(addr) return [six.text_type(addr) for addr in sorted(ret)] def ip_addrs(interface=None, include_loopback=False, interface_data=None): ''' Returns a list of IPv4 addresses assigned to the host. 127.0.0.1 is ignored, unless 'include_loopback=True' is indicated. If 'interface' is provided, then only IP addresses from that interface will be returned. ''' return _ip_addrs(interface, include_loopback, interface_data, 'inet') def ip_addrs6(interface=None, include_loopback=False, interface_data=None): ''' Returns a list of IPv6 addresses assigned to the host. ::1 is ignored, unless 'include_loopback=True' is indicated. If 'interface' is provided, then only IP addresses from that interface will be returned. ''' return _ip_addrs(interface, include_loopback, interface_data, 'inet6') def mac2eui64(mac, prefix=None): ''' Convert a MAC address to a EUI64 identifier or, with prefix provided, a full IPv6 address ''' # http://tools.ietf.org/html/rfc4291#section-2.5.1 eui64 = re.sub(r'[.:-]', '', mac).lower() eui64 = eui64[0:6] + 'fffe' + eui64[6:] eui64 = hex(int(eui64[0:2], 16) | 2)[2:].zfill(2) + eui64[2:] if prefix is None: return ':'.join(re.findall(r'.{4}', eui64)) else: try: net = ipaddress.ip_network(prefix, strict=False) euil = int('0x{0}'.format(eui64), 16) return '{0}/{1}'.format(net[euil], net.prefixlen) except Exception: return def active_tcp(): ''' Return a dict describing all active tcp connections as quickly as possible ''' ret = {} for statf in ['/proc/net/tcp', '/proc/net/tcp6']: if os.path.isfile(statf): with salt.utils.files.fopen(statf, 'rb') as fp_: for line in fp_: line = salt.utils.stringutils.to_unicode(line) if line.strip().startswith('sl'): continue iret = _parse_tcp_line(line) sl = next(iter(iret)) if iret[sl]['state'] == 1: # 1 is ESTABLISHED del iret[sl]['state'] ret[len(ret)] = iret[sl] return ret def local_port_tcp(port): ''' Return a set of remote ip addrs attached to the specified local port ''' ret = _remotes_on(port, 'local_port') return ret def remote_port_tcp(port): ''' Return a set of ip addrs the current host is connected to on given port ''' ret = _remotes_on(port, 'remote_port') return ret def _remotes_on(port, which_end): ''' Return a set of ip addrs active tcp connections ''' port = int(port) ret = _netlink_tool_remote_on(port, which_end) if ret is not None: return ret ret = set() proc_available = False for statf in ['/proc/net/tcp', '/proc/net/tcp6']: if os.path.isfile(statf): proc_available = True with salt.utils.files.fopen(statf, 'r') as fp_: for line in fp_: line = salt.utils.stringutils.to_unicode(line) if line.strip().startswith('sl'): continue iret = _parse_tcp_line(line) sl = next(iter(iret)) if iret[sl][which_end] == port and iret[sl]['state'] == 1: # 1 is ESTABLISHED ret.add(iret[sl]['remote_addr']) if not proc_available: # Fallback to use OS specific tools if salt.utils.platform.is_sunos(): return _sunos_remotes_on(port, which_end) if salt.utils.platform.is_freebsd(): return _freebsd_remotes_on(port, which_end) if salt.utils.platform.is_netbsd(): return _netbsd_remotes_on(port, which_end) if salt.utils.platform.is_openbsd(): return _openbsd_remotes_on(port, which_end) if salt.utils.platform.is_windows(): return _windows_remotes_on(port, which_end) if salt.utils.platform.is_aix(): return _aix_remotes_on(port, which_end) return _linux_remotes_on(port, which_end) return ret def _parse_tcp_line(line): ''' Parse a single line from the contents of /proc/net/tcp or /proc/net/tcp6 ''' ret = {} comps = line.strip().split() sl = comps[0].rstrip(':') ret[sl] = {} l_addr, l_port = comps[1].split(':') r_addr, r_port = comps[2].split(':') ret[sl]['local_addr'] = hex2ip(l_addr, True) ret[sl]['local_port'] = int(l_port, 16) ret[sl]['remote_addr'] = hex2ip(r_addr, True) ret[sl]['remote_port'] = int(r_port, 16) ret[sl]['state'] = int(comps[3], 16) return ret def _netlink_tool_remote_on(port, which_end): ''' Returns set of ipv4 host addresses of remote established connections on local or remote tcp port. Parses output of shell 'ss' to get connections [root@salt-master ~]# ss -ant State Recv-Q Send-Q Local Address:Port Peer Address:Port LISTEN 0 511 *:80 *:* LISTEN 0 128 *:22 *:* ESTAB 0 0 127.0.0.1:56726 127.0.0.1:4505 ''' remotes = set() valid = False try: data = subprocess.check_output(['ss', '-ant']) # pylint: disable=minimum-python-version except subprocess.CalledProcessError: log.error('Failed ss') raise except OSError: # not command "No such file or directory" return None lines = salt.utils.stringutils.to_str(data).split('\n') for line in lines: if 'Address:Port' in line: # ss tools may not be valid valid = True continue elif 'ESTAB' not in line: continue chunks = line.split() local_host, local_port = chunks[3].split(':', 1) remote_host, remote_port = chunks[4].split(':', 1) if which_end == 'remote_port' and int(remote_port) != port: continue if which_end == 'local_port' and int(local_port) != port: continue remotes.add(remote_host) if valid is False: remotes = None return remotes def _sunos_remotes_on(port, which_end): ''' SunOS specific helper function. Returns set of ipv4 host addresses of remote established connections on local or remote tcp port. Parses output of shell 'netstat' to get connections [root@salt-master ~]# netstat -f inet -n TCP: IPv4 Local Address Remote Address Swind Send-Q Rwind Recv-Q State -------------------- -------------------- ----- ------ ----- ------ ----------- 10.0.0.101.4505 10.0.0.1.45329 1064800 0 1055864 0 ESTABLISHED 10.0.0.101.4505 10.0.0.100.50798 1064800 0 1055864 0 ESTABLISHED ''' remotes = set() try: data = subprocess.check_output(['netstat', '-f', 'inet', '-n']) # pylint: disable=minimum-python-version except subprocess.CalledProcessError: log.error('Failed netstat') raise lines = salt.utils.stringutils.to_str(data).split('\n') for line in lines: if 'ESTABLISHED' not in line: continue chunks = line.split() local_host, local_port = chunks[0].rsplit('.', 1) remote_host, remote_port = chunks[1].rsplit('.', 1) if which_end == 'remote_port' and int(remote_port) != port: continue if which_end == 'local_port' and int(local_port) != port: continue remotes.add(remote_host) return remotes def _freebsd_remotes_on(port, which_end): ''' Returns set of ipv4 host addresses of remote established connections on local tcp port port. Parses output of shell 'sockstat' (FreeBSD) to get connections $ sudo sockstat -4 USER COMMAND PID FD PROTO LOCAL ADDRESS FOREIGN ADDRESS root python2.7 1456 29 tcp4 *:4505 *:* root python2.7 1445 17 tcp4 *:4506 *:* root python2.7 1294 14 tcp4 127.0.0.1:11813 127.0.0.1:4505 root python2.7 1294 41 tcp4 127.0.0.1:61115 127.0.0.1:4506 $ sudo sockstat -4 -c -p 4506 USER COMMAND PID FD PROTO LOCAL ADDRESS FOREIGN ADDRESS root python2.7 1294 41 tcp4 127.0.0.1:61115 127.0.0.1:4506 ''' port = int(port) remotes = set() try: cmd = salt.utils.args.shlex_split('sockstat -4 -c -p {0}'.format(port)) data = subprocess.check_output(cmd) # pylint: disable=minimum-python-version except subprocess.CalledProcessError as ex: log.error('Failed "sockstat" with returncode = %s', ex.returncode) raise lines = salt.utils.stringutils.to_str(data).split('\n') for line in lines: chunks = line.split() if not chunks: continue # ['root', 'python2.7', '1456', '37', 'tcp4', # '127.0.0.1:4505-', '127.0.0.1:55703'] # print chunks if 'COMMAND' in chunks[1]: continue # ignore header if len(chunks) < 2: continue # sockstat -4 -c -p 4506 does this with high PIDs: # USER COMMAND PID FD PROTO LOCAL ADDRESS FOREIGN ADDRESS # salt-master python2.781106 35 tcp4 192.168.12.34:4506 192.168.12.45:60143 local = chunks[-2] remote = chunks[-1] lhost, lport = local.split(':') rhost, rport = remote.split(':') if which_end == 'local' and int(lport) != port: # ignore if local port not port continue if which_end == 'remote' and int(rport) != port: # ignore if remote port not port continue remotes.add(rhost) return remotes def _netbsd_remotes_on(port, which_end): ''' Returns set of ipv4 host addresses of remote established connections on local tcp port port. Parses output of shell 'sockstat' (NetBSD) to get connections $ sudo sockstat -4 -n USER COMMAND PID FD PROTO LOCAL ADDRESS FOREIGN ADDRESS root python2.7 1456 29 tcp *.4505 *.* root python2.7 1445 17 tcp *.4506 *.* root python2.7 1294 14 tcp 127.0.0.1.11813 127.0.0.1.4505 root python2.7 1294 41 tcp 127.0.0.1.61115 127.0.0.1.4506 $ sudo sockstat -4 -c -n -p 4506 USER COMMAND PID FD PROTO LOCAL ADDRESS FOREIGN ADDRESS root python2.7 1294 41 tcp 127.0.0.1.61115 127.0.0.1.4506 ''' port = int(port) remotes = set() try: cmd = salt.utils.args.shlex_split('sockstat -4 -c -n -p {0}'.format(port)) data = subprocess.check_output(cmd) # pylint: disable=minimum-python-version except subprocess.CalledProcessError as ex: log.error('Failed "sockstat" with returncode = %s', ex.returncode) raise lines = salt.utils.stringutils.to_str(data).split('\n') for line in lines: chunks = line.split() if not chunks: continue # ['root', 'python2.7', '1456', '37', 'tcp', # '127.0.0.1.4505-', '127.0.0.1.55703'] # print chunks if 'COMMAND' in chunks[1]: continue # ignore header if len(chunks) < 2: continue local = chunks[5].split('.') lport = local.pop() lhost = '.'.join(local) remote = chunks[6].split('.') rport = remote.pop() rhost = '.'.join(remote) if which_end == 'local' and int(lport) != port: # ignore if local port not port continue if which_end == 'remote' and int(rport) != port: # ignore if remote port not port continue remotes.add(rhost) return remotes def _openbsd_remotes_on(port, which_end): ''' OpenBSD specific helper function. Returns set of ipv4 host addresses of remote established connections on local or remote tcp port. Parses output of shell 'netstat' to get connections $ netstat -nf inet Active Internet connections Proto Recv-Q Send-Q Local Address Foreign Address (state) tcp 0 0 10.0.0.101.4505 10.0.0.1.45329 ESTABLISHED tcp 0 0 10.0.0.101.4505 10.0.0.100.50798 ESTABLISHED ''' remotes = set() try: data = subprocess.check_output(['netstat', '-nf', 'inet']) # pylint: disable=minimum-python-version except subprocess.CalledProcessError: log.error('Failed netstat') raise lines = data.split('\n') for line in lines: if 'ESTABLISHED' not in line: continue chunks = line.split() local_host, local_port = chunks[3].rsplit('.', 1) remote_host, remote_port = chunks[4].rsplit('.', 1) if which_end == 'remote_port' and int(remote_port) != port: continue if which_end == 'local_port' and int(local_port) != port: continue remotes.add(remote_host) return remotes def _windows_remotes_on(port, which_end): r''' Windows specific helper function. Returns set of ipv4 host addresses of remote established connections on local or remote tcp port. Parses output of shell 'netstat' to get connections C:\>netstat -n Active Connections Proto Local Address Foreign Address State TCP 10.2.33.17:3007 130.164.12.233:10123 ESTABLISHED TCP 10.2.33.17:3389 130.164.30.5:10378 ESTABLISHED ''' remotes = set() try: data = subprocess.check_output(['netstat', '-n']) # pylint: disable=minimum-python-version except subprocess.CalledProcessError: log.error('Failed netstat') raise lines = salt.utils.stringutils.to_str(data).split('\n') for line in lines: if 'ESTABLISHED' not in line: continue chunks = line.split() local_host, local_port = chunks[1].rsplit(':', 1) remote_host, remote_port = chunks[2].rsplit(':', 1) if which_end == 'remote_port' and int(remote_port) != port: continue if which_end == 'local_port' and int(local_port) != port: continue remotes.add(remote_host) return remotes def _linux_remotes_on(port, which_end): ''' Linux specific helper function. Returns set of ip host addresses of remote established connections on local tcp port port. Parses output of shell 'lsof' to get connections $ sudo lsof -iTCP:4505 -n COMMAND PID USER FD TYPE DEVICE SIZE/OFF NODE NAME Python 9971 root 35u IPv4 0x18a8464a29ca329d 0t0 TCP *:4505 (LISTEN) Python 9971 root 37u IPv4 0x18a8464a29b2b29d 0t0 TCP 127.0.0.1:4505->127.0.0.1:55703 (ESTABLISHED) Python 10152 root 22u IPv4 0x18a8464a29c8cab5 0t0 TCP 127.0.0.1:55703->127.0.0.1:4505 (ESTABLISHED) Python 10153 root 22u IPv4 0x18a8464a29c8cab5 0t0 TCP [fe80::249a]:4505->[fe80::150]:59367 (ESTABLISHED) ''' remotes = set() try: data = subprocess.check_output( ['lsof', '-iTCP:{0:d}'.format(port), '-n', '-P'] # pylint: disable=minimum-python-version ) except subprocess.CalledProcessError as ex: if ex.returncode == 1: # Lsof return 1 if any error was detected, including the failure # to locate Internet addresses, and it is not an error in this case. log.warning('"lsof" returncode = 1, likely no active TCP sessions.') return remotes log.error('Failed "lsof" with returncode = %s', ex.returncode) raise lines = salt.utils.stringutils.to_str(data).split('\n') for line in lines: chunks = line.split() if not chunks: continue # ['Python', '9971', 'root', '37u', 'IPv4', '0x18a8464a29b2b29d', '0t0', # 'TCP', '127.0.0.1:4505->127.0.0.1:55703', '(ESTABLISHED)'] # print chunks if 'COMMAND' in chunks[0]: continue # ignore header if 'ESTABLISHED' not in chunks[-1]: continue # ignore if not ESTABLISHED # '127.0.0.1:4505->127.0.0.1:55703' local, remote = chunks[8].split('->') _, lport = local.rsplit(':', 1) rhost, rport = remote.rsplit(':', 1) if which_end == 'remote_port' and int(rport) != port: continue if which_end == 'local_port' and int(lport) != port: continue remotes.add(rhost.strip("[]")) return remotes def _aix_remotes_on(port, which_end): ''' AIX specific helper function. Returns set of ipv4 host addresses of remote established connections on local or remote tcp port. Parses output of shell 'netstat' to get connections root@la68pp002_pub:/opt/salt/lib/python2.7/site-packages/salt/modules# netstat -f inet -n Active Internet connections Proto Recv-Q Send-Q Local Address Foreign Address (state) tcp4 0 0 172.29.149.95.50093 209.41.78.13.4505 ESTABLISHED tcp4 0 0 127.0.0.1.9514 *.* LISTEN tcp4 0 0 127.0.0.1.9515 *.* LISTEN tcp4 0 0 127.0.0.1.199 127.0.0.1.32779 ESTABLISHED tcp4 0 0 127.0.0.1.32779 127.0.0.1.199 ESTABLISHED tcp4 0 40 172.29.149.95.22 172.29.96.83.41022 ESTABLISHED tcp4 0 0 172.29.149.95.22 172.29.96.83.41032 ESTABLISHED tcp4 0 0 127.0.0.1.32771 127.0.0.1.32775 ESTABLISHED tcp 0 0 127.0.0.1.32775 127.0.0.1.32771 ESTABLISHED tcp4 0 0 127.0.0.1.32771 127.0.0.1.32776 ESTABLISHED tcp 0 0 127.0.0.1.32776 127.0.0.1.32771 ESTABLISHED tcp4 0 0 127.0.0.1.32771 127.0.0.1.32777 ESTABLISHED tcp 0 0 127.0.0.1.32777 127.0.0.1.32771 ESTABLISHED tcp4 0 0 127.0.0.1.32771 127.0.0.1.32778 ESTABLISHED tcp 0 0 127.0.0.1.32778 127.0.0.1.32771 ESTABLISHED ''' remotes = set() try: data = subprocess.check_output(['netstat', '-f', 'inet', '-n']) # pylint: disable=minimum-python-version except subprocess.CalledProcessError: log.error('Failed netstat') raise lines = salt.utils.stringutils.to_str(data).split('\n') for line in lines: if 'ESTABLISHED' not in line: continue chunks = line.split() local_host, local_port = chunks[3].rsplit('.', 1) remote_host, remote_port = chunks[4].rsplit('.', 1) if which_end == 'remote_port' and int(remote_port) != port: continue if which_end == 'local_port' and int(local_port) != port: continue remotes.add(remote_host) return remotes @jinja_filter('gen_mac') def gen_mac(prefix='AC:DE:48'): ''' Generates a MAC address with the defined OUI prefix. Common prefixes: - ``00:16:3E`` -- Xen - ``00:18:51`` -- OpenVZ - ``00:50:56`` -- VMware (manually generated) - ``52:54:00`` -- QEMU/KVM - ``AC:DE:48`` -- PRIVATE References: - http://standards.ieee.org/develop/regauth/oui/oui.txt - https://www.wireshark.org/tools/oui-lookup.html - https://en.wikipedia.org/wiki/MAC_address ''' return '{0}:{1:02X}:{2:02X}:{3:02X}'.format(prefix, random.randint(0, 0xff), random.randint(0, 0xff), random.randint(0, 0xff)) @jinja_filter('mac_str_to_bytes') def mac_str_to_bytes(mac_str): ''' Convert a MAC address string into bytes. Works with or without separators: b1 = mac_str_to_bytes('08:00:27:13:69:77') b2 = mac_str_to_bytes('080027136977') assert b1 == b2 assert isinstance(b1, bytes) ''' if len(mac_str) == 12: pass elif len(mac_str) == 17: sep = mac_str[2] mac_str = mac_str.replace(sep, '') else: raise ValueError('Invalid MAC address') chars = (int(mac_str[s:s+2], 16) for s in range(0, 12, 2)) return bytes(chars) if six.PY3 else b''.join(chr(x) for x in chars) def refresh_dns(): ''' issue #21397: force glibc to re-read resolv.conf ''' try: res_init() except NameError: # Exception raised loading the library, thus res_init is not defined pass @jinja_filter('connection_check') def connection_check(addr, port=80, safe=False, ipv6=None): ''' Provides a convenient alias for the dns_check filter. ''' return dns_check(addr, port, safe, ipv6) @jinja_filter('dns_check') def dns_check(addr, port=80, safe=False, ipv6=None, attempt_connect=True): ''' Return the ip resolved by dns, but do not exit on failure, only raise an exception. Obeys system preference for IPv4/6 address resolution - this can be overridden by the ipv6 flag. Tries to connect to the address before considering it useful. If no address can be reached, the first one resolved is used as a fallback. ''' error = False lookup = addr seen_ipv6 = False family = socket.AF_INET6 if ipv6 else socket.AF_INET if ipv6 is False else socket.AF_UNSPEC hostnames = [] try: refresh_dns() hostnames = socket.getaddrinfo(addr, port, family, socket.SOCK_STREAM) except TypeError: err = ('Attempt to resolve address \'{0}\' failed. Invalid or unresolveable address').format(lookup) raise SaltSystemExit(code=42, msg=err) except socket.error: error = True # If ipv6 is set to True, attempt another lookup using the IPv4 family, # just in case we're attempting to lookup an IPv4 IP # as an IPv6 hostname. if error and ipv6: try: refresh_dns() hostnames = socket.getaddrinfo(addr, port, socket.AF_INET, socket.SOCK_STREAM) except TypeError: err = ('Attempt to resolve address \'{0}\' failed. Invalid or unresolveable address').format(lookup) raise SaltSystemExit(code=42, msg=err) except socket.error: error = True try: if not hostnames: error = True else: resolved = False candidates = [] for h in hostnames: # Input is IP address, passed through unchanged, just return it if h[4][0] == addr: resolved = salt.utils.zeromq.ip_bracket(addr) break candidate_addr = salt.utils.zeromq.ip_bracket(h[4][0]) # sometimes /etc/hosts contains ::1 localhost if not ipv6 and candidate_addr == '[::1]': continue candidates.append(candidate_addr) if attempt_connect: try: s = socket.socket(h[0], socket.SOCK_STREAM) s.settimeout(2) s.connect((candidate_addr.strip('[]'), h[4][1])) s.close() resolved = candidate_addr break except socket.error: pass if not resolved: if candidates: resolved = candidates[0] else: error = True except TypeError: err = ('Attempt to resolve address \'{0}\' failed. Invalid or unresolveable address').format(lookup) raise SaltSystemExit(code=42, msg=err) except socket.error: error = True if error: err = ('DNS lookup or connection check of \'{0}\' failed.').format(addr) if safe: if salt.log.is_console_configured(): # If logging is not configured it also means that either # the master or minion instance calling this hasn't even # started running log.error(err) raise SaltClientError() raise SaltSystemExit(code=42, msg=err) return resolved def parse_host_port(host_port): """ Takes a string argument specifying host or host:port. Returns a (hostname, port) or (ip_address, port) tuple. If no port is given, the second (port) element of the returned tuple will be None. host:port argument, for example, is accepted in the forms of: - hostname - hostname:1234 - hostname.domain.tld - hostname.domain.tld:5678 - [1234::5]:5678 - 1234::5 - 10.11.12.13:4567 - 10.11.12.13 """ host, port = None, None # default _s_ = host_port[:] if _s_[0] == "[": if "]" in host_port: host, _s_ = _s_.lstrip("[").rsplit("]", 1) host = ipaddress.IPv6Address(host).compressed if _s_[0] == ":": port = int(_s_.lstrip(":")) else: if len(_s_) > 1: raise ValueError('found ambiguous "{}" port in "{}"'.format(_s_, host_port)) else: if _s_.count(":") == 1: host, _hostport_separator_, port = _s_.partition(":") try: port = int(port) except ValueError as _e_: log.error('host_port "%s" port value "%s" is not an integer.', host_port, port) raise _e_ else: host = _s_ try: if not isinstance(host, ipaddress._BaseAddress): host_ip = ipaddress.ip_address(host).compressed host = host_ip except ValueError: log.debug('"%s" Not an IP address? Assuming it is a hostname.', host) if host != sanitize_host(host): log.error('bad hostname: "%s"', host) raise ValueError('bad hostname: "{}"'.format(host)) return host, port def is_fqdn(hostname): """ Verify if hostname conforms to be a FQDN. :param hostname: text string with the name of the host :return: bool, True if hostname is correct FQDN, False otherwise """ compliant = re.compile(r"(?!-)[A-Z\d\-\_]{1,63}(?<!-)$", re.IGNORECASE) return "." in hostname and len(hostname) < 0xff and all(compliant.match(x) for x in hostname.rstrip(".").split("."))
saltstack/salt
salt/utils/network.py
mac2eui64
python
def mac2eui64(mac, prefix=None): ''' Convert a MAC address to a EUI64 identifier or, with prefix provided, a full IPv6 address ''' # http://tools.ietf.org/html/rfc4291#section-2.5.1 eui64 = re.sub(r'[.:-]', '', mac).lower() eui64 = eui64[0:6] + 'fffe' + eui64[6:] eui64 = hex(int(eui64[0:2], 16) | 2)[2:].zfill(2) + eui64[2:] if prefix is None: return ':'.join(re.findall(r'.{4}', eui64)) else: try: net = ipaddress.ip_network(prefix, strict=False) euil = int('0x{0}'.format(eui64), 16) return '{0}/{1}'.format(net[euil], net.prefixlen) except Exception: return
Convert a MAC address to a EUI64 identifier or, with prefix provided, a full IPv6 address
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/network.py#L1343-L1361
null
# -*- coding: utf-8 -*- ''' Define some generic socket functions for network modules ''' # Import python libs from __future__ import absolute_import, unicode_literals, print_function import itertools import os import re import types import socket import logging import platform import random import subprocess from string import ascii_letters, digits # Import 3rd-party libs from salt.ext import six from salt.ext.six.moves import range # pylint: disable=import-error,redefined-builtin # Attempt to import wmi try: import wmi import salt.utils.winapi except ImportError: pass # Import salt libs import salt.utils.args import salt.utils.files import salt.utils.path import salt.utils.platform import salt.utils.stringutils import salt.utils.zeromq from salt._compat import ipaddress from salt.exceptions import SaltClientError, SaltSystemExit from salt.utils.decorators.jinja import jinja_filter from salt.utils.versions import LooseVersion # inet_pton does not exist in Windows, this is a workaround if salt.utils.platform.is_windows(): from salt.ext import win_inet_pton # pylint: disable=unused-import log = logging.getLogger(__name__) try: import ctypes import ctypes.util libc = ctypes.cdll.LoadLibrary(ctypes.util.find_library("c")) res_init = libc.__res_init except (ImportError, OSError, AttributeError, TypeError): pass # pylint: disable=C0103 def sanitize_host(host): ''' Sanitize host string. https://tools.ietf.org/html/rfc1123#section-2.1 ''' RFC952_characters = ascii_letters + digits + ".-" return "".join([c for c in host[0:255] if c in RFC952_characters]) def isportopen(host, port): ''' Return status of a port ''' if not 1 <= int(port) <= 65535: return False sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) out = sock.connect_ex((sanitize_host(host), int(port))) return out def host_to_ips(host): ''' Returns a list of IP addresses of a given hostname or None if not found. ''' ips = [] try: for family, socktype, proto, canonname, sockaddr in socket.getaddrinfo( host, 0, socket.AF_UNSPEC, socket.SOCK_STREAM): if family == socket.AF_INET: ip, port = sockaddr elif family == socket.AF_INET6: ip, port, flow_info, scope_id = sockaddr ips.append(ip) if not ips: ips = None except Exception: ips = None return ips def _generate_minion_id(): ''' Get list of possible host names and convention names. :return: ''' # There are three types of hostnames: # 1. Network names. How host is accessed from the network. # 2. Host aliases. They might be not available in all the network or only locally (/etc/hosts) # 3. Convention names, an internal nodename. class DistinctList(list): ''' List, which allows one to append only distinct objects. Needs to work on Python 2.6, because of collections.OrderedDict only since 2.7 version. Override 'filter()' for custom filtering. ''' localhost_matchers = [r'localhost.*', r'ip6-.*', r'127[.]\d', r'0\.0\.0\.0', r'::1.*', r'ipv6-.*', r'fe00::.*', r'fe02::.*', r'1.0.0.*.ip6.arpa'] def append(self, p_object): if p_object and p_object not in self and not self.filter(p_object): super(DistinctList, self).append(p_object) return self def extend(self, iterable): for obj in iterable: self.append(obj) return self def filter(self, element): 'Returns True if element needs to be filtered' for rgx in self.localhost_matchers: if re.match(rgx, element): return True def first(self): return self and self[0] or None hostname = socket.gethostname() hosts = DistinctList().append( salt.utils.stringutils.to_unicode(socket.getfqdn(salt.utils.stringutils.to_bytes(hostname))) ).append(platform.node()).append(hostname) if not hosts: try: for a_nfo in socket.getaddrinfo(hosts.first() or 'localhost', None, socket.AF_INET, socket.SOCK_RAW, socket.IPPROTO_IP, socket.AI_CANONNAME): if len(a_nfo) > 3: hosts.append(a_nfo[3]) except socket.gaierror: log.warning('Cannot resolve address %s info via socket: %s', hosts.first() or 'localhost (N/A)', socket.gaierror) # Universal method for everywhere (Linux, Slowlaris, Windows etc) for f_name in ('/etc/hostname', '/etc/nodename', '/etc/hosts', r'{win}\system32\drivers\etc\hosts'.format(win=os.getenv('WINDIR'))): try: with salt.utils.files.fopen(f_name) as f_hdl: for line in f_hdl: line = salt.utils.stringutils.to_unicode(line) hst = line.strip().split('#')[0].strip().split() if hst: if hst[0][:4] in ('127.', '::1') or len(hst) == 1: hosts.extend(hst) except IOError: pass # include public and private ipaddresses return hosts.extend([addr for addr in ip_addrs() if not ipaddress.ip_address(addr).is_loopback]) def generate_minion_id(): ''' Return only first element of the hostname from all possible list. :return: ''' try: ret = salt.utils.stringutils.to_unicode(_generate_minion_id().first()) except TypeError: ret = None return ret or 'localhost' def get_socket(addr, type=socket.SOCK_STREAM, proto=0): ''' Return a socket object for the addr IP-version agnostic ''' version = ipaddress.ip_address(addr).version if version == 4: family = socket.AF_INET elif version == 6: family = socket.AF_INET6 return socket.socket(family, type, proto) def get_fqhostname(): ''' Returns the fully qualified hostname ''' # try getaddrinfo() fqdn = None try: addrinfo = socket.getaddrinfo( socket.gethostname(), 0, socket.AF_UNSPEC, socket.SOCK_STREAM, socket.SOL_TCP, socket.AI_CANONNAME ) for info in addrinfo: # info struct [family, socktype, proto, canonname, sockaddr] # On Windows `canonname` can be an empty string # This can cause the function to return `None` if len(info) > 3 and info[3]: fqdn = info[3] break except socket.gaierror: pass # NOTE: this used to log.error() but it was later disabled except socket.error as err: log.debug('socket.getaddrinfo() failure while finding fqdn: %s', err) if fqdn is None: fqdn = socket.getfqdn() return fqdn def ip_to_host(ip): ''' Returns the hostname of a given IP ''' try: hostname, aliaslist, ipaddrlist = socket.gethostbyaddr(ip) except Exception as exc: log.debug('salt.utils.network.ip_to_host(%r) failed: %s', ip, exc) hostname = None return hostname # pylint: enable=C0103 def is_reachable_host(entity_name): ''' Returns a bool telling if the entity name is a reachable host (IPv4/IPv6/FQDN/etc). :param hostname: :return: ''' try: assert type(socket.getaddrinfo(entity_name, 0, 0, 0, 0)) == list ret = True except socket.gaierror: ret = False return ret def is_ip(ip): ''' Returns a bool telling if the passed IP is a valid IPv4 or IPv6 address. ''' return is_ipv4(ip) or is_ipv6(ip) def is_ipv4(ip): ''' Returns a bool telling if the value passed to it was a valid IPv4 address ''' try: return ipaddress.ip_address(ip).version == 4 except ValueError: return False def is_ipv6(ip): ''' Returns a bool telling if the value passed to it was a valid IPv6 address ''' try: return ipaddress.ip_address(ip).version == 6 except ValueError: return False def is_subnet(cidr): ''' Returns a bool telling if the passed string is an IPv4 or IPv6 subnet ''' return is_ipv4_subnet(cidr) or is_ipv6_subnet(cidr) def is_ipv4_subnet(cidr): ''' Returns a bool telling if the passed string is an IPv4 subnet ''' try: return '/' in cidr and bool(ipaddress.IPv4Network(cidr)) except Exception: return False def is_ipv6_subnet(cidr): ''' Returns a bool telling if the passed string is an IPv6 subnet ''' try: return '/' in cidr and bool(ipaddress.IPv6Network(cidr)) except Exception: return False @jinja_filter('is_ip') def is_ip_filter(ip, options=None): ''' Returns a bool telling if the passed IP is a valid IPv4 or IPv6 address. ''' return is_ipv4_filter(ip, options=options) or is_ipv6_filter(ip, options=options) def _ip_options_global(ip_obj, version): return not ip_obj.is_private def _ip_options_multicast(ip_obj, version): return ip_obj.is_multicast def _ip_options_loopback(ip_obj, version): return ip_obj.is_loopback def _ip_options_link_local(ip_obj, version): return ip_obj.is_link_local def _ip_options_private(ip_obj, version): return ip_obj.is_private def _ip_options_reserved(ip_obj, version): return ip_obj.is_reserved def _ip_options_site_local(ip_obj, version): if version == 6: return ip_obj.is_site_local return False def _ip_options_unspecified(ip_obj, version): return ip_obj.is_unspecified def _ip_options(ip_obj, version, options=None): # will process and IP options options_fun_map = { 'global': _ip_options_global, 'link-local': _ip_options_link_local, 'linklocal': _ip_options_link_local, 'll': _ip_options_link_local, 'link_local': _ip_options_link_local, 'loopback': _ip_options_loopback, 'lo': _ip_options_loopback, 'multicast': _ip_options_multicast, 'private': _ip_options_private, 'public': _ip_options_global, 'reserved': _ip_options_reserved, 'site-local': _ip_options_site_local, 'sl': _ip_options_site_local, 'site_local': _ip_options_site_local, 'unspecified': _ip_options_unspecified } if not options: return six.text_type(ip_obj) # IP version already checked options_list = [option.strip() for option in options.split(',')] for option, fun in options_fun_map.items(): if option in options_list: fun_res = fun(ip_obj, version) if not fun_res: return None # stop at first failed test # else continue return six.text_type(ip_obj) def _is_ipv(ip, version, options=None): if not version: version = 4 if version not in (4, 6): return None try: ip_obj = ipaddress.ip_address(ip) except ValueError: # maybe it is an IP network try: ip_obj = ipaddress.ip_interface(ip) except ValueError: # nope, still not :( return None if not ip_obj.version == version: return None # has the right version, let's move on return _ip_options(ip_obj, version, options=options) @jinja_filter('is_ipv4') def is_ipv4_filter(ip, options=None): ''' Returns a bool telling if the value passed to it was a valid IPv4 address. ip The IP address. net: False Consider IP addresses followed by netmask. options CSV of options regarding the nature of the IP address. E.g.: loopback, multicast, private etc. ''' _is_ipv4 = _is_ipv(ip, 4, options=options) return isinstance(_is_ipv4, six.string_types) @jinja_filter('is_ipv6') def is_ipv6_filter(ip, options=None): ''' Returns a bool telling if the value passed to it was a valid IPv6 address. ip The IP address. net: False Consider IP addresses followed by netmask. options CSV of options regarding the nature of the IP address. E.g.: loopback, multicast, private etc. ''' _is_ipv6 = _is_ipv(ip, 6, options=options) return isinstance(_is_ipv6, six.string_types) def _ipv_filter(value, version, options=None): if version not in (4, 6): return if isinstance(value, (six.string_types, six.text_type, six.binary_type)): return _is_ipv(value, version, options=options) # calls is_ipv4 or is_ipv6 for `value` elif isinstance(value, (list, tuple, types.GeneratorType)): # calls is_ipv4 or is_ipv6 for each element in the list # os it filters and returns only those elements having the desired IP version return [ _is_ipv(addr, version, options=options) for addr in value if _is_ipv(addr, version, options=options) is not None ] return None @jinja_filter('ipv4') def ipv4(value, options=None): ''' Filters a list and returns IPv4 values only. ''' return _ipv_filter(value, 4, options=options) @jinja_filter('ipv6') def ipv6(value, options=None): ''' Filters a list and returns IPv6 values only. ''' return _ipv_filter(value, 6, options=options) @jinja_filter('ipaddr') def ipaddr(value, options=None): ''' Filters and returns only valid IP objects. ''' ipv4_obj = ipv4(value, options=options) ipv6_obj = ipv6(value, options=options) if ipv4_obj is None or ipv6_obj is None: # an IP address can be either IPv4 either IPv6 # therefofe if the value passed as arg is not a list, at least one of the calls above will return None # if one of them is none, means that we should return only one of them return ipv4_obj or ipv6_obj # one of them else: return ipv4_obj + ipv6_obj # extend lists def _filter_ipaddr(value, options, version=None): ipaddr_filter_out = None if version: if version == 4: ipaddr_filter_out = ipv4(value, options) elif version == 6: ipaddr_filter_out = ipv6(value, options) else: ipaddr_filter_out = ipaddr(value, options) if not ipaddr_filter_out: return if not isinstance(ipaddr_filter_out, (list, tuple, types.GeneratorType)): ipaddr_filter_out = [ipaddr_filter_out] return ipaddr_filter_out @jinja_filter('ip_host') def ip_host(value, options=None, version=None): ''' Returns the interfaces IP address, e.g.: 192.168.0.1/28. ''' ipaddr_filter_out = _filter_ipaddr(value, options=options, version=version) if not ipaddr_filter_out: return if not isinstance(value, (list, tuple, types.GeneratorType)): return six.text_type(ipaddress.ip_interface(ipaddr_filter_out[0])) return [six.text_type(ipaddress.ip_interface(ip_a)) for ip_a in ipaddr_filter_out] def _network_hosts(ip_addr_entry): return [ six.text_type(host) for host in ipaddress.ip_network(ip_addr_entry, strict=False).hosts() ] @jinja_filter('network_hosts') def network_hosts(value, options=None, version=None): ''' Return the list of hosts within a network. .. note:: When running this command with a large IPv6 network, the command will take a long time to gather all of the hosts. ''' ipaddr_filter_out = _filter_ipaddr(value, options=options, version=version) if not ipaddr_filter_out: return if not isinstance(value, (list, tuple, types.GeneratorType)): return _network_hosts(ipaddr_filter_out[0]) return [ _network_hosts(ip_a) for ip_a in ipaddr_filter_out ] def _network_size(ip_addr_entry): return ipaddress.ip_network(ip_addr_entry, strict=False).num_addresses @jinja_filter('network_size') def network_size(value, options=None, version=None): ''' Get the size of a network. ''' ipaddr_filter_out = _filter_ipaddr(value, options=options, version=version) if not ipaddr_filter_out: return if not isinstance(value, (list, tuple, types.GeneratorType)): return _network_size(ipaddr_filter_out[0]) return [ _network_size(ip_a) for ip_a in ipaddr_filter_out ] def natural_ipv4_netmask(ip, fmt='prefixlen'): ''' Returns the "natural" mask of an IPv4 address ''' bits = _ipv4_to_bits(ip) if bits.startswith('11'): mask = '24' elif bits.startswith('1'): mask = '16' else: mask = '8' if fmt == 'netmask': return cidr_to_ipv4_netmask(mask) else: return '/' + mask def rpad_ipv4_network(ip): ''' Returns an IP network address padded with zeros. Ex: '192.168.3' -> '192.168.3.0' '10.209' -> '10.209.0.0' ''' return '.'.join(itertools.islice(itertools.chain(ip.split('.'), '0000'), 0, 4)) def cidr_to_ipv4_netmask(cidr_bits): ''' Returns an IPv4 netmask ''' try: cidr_bits = int(cidr_bits) if not 1 <= cidr_bits <= 32: return '' except ValueError: return '' netmask = '' for idx in range(4): if idx: netmask += '.' if cidr_bits >= 8: netmask += '255' cidr_bits -= 8 else: netmask += '{0:d}'.format(256 - (2 ** (8 - cidr_bits))) cidr_bits = 0 return netmask def _number_of_set_bits_to_ipv4_netmask(set_bits): # pylint: disable=C0103 ''' Returns an IPv4 netmask from the integer representation of that mask. Ex. 0xffffff00 -> '255.255.255.0' ''' return cidr_to_ipv4_netmask(_number_of_set_bits(set_bits)) # pylint: disable=C0103 def _number_of_set_bits(x): ''' Returns the number of bits that are set in a 32bit int ''' # Taken from http://stackoverflow.com/a/4912729. Many thanks! x -= (x >> 1) & 0x55555555 x = ((x >> 2) & 0x33333333) + (x & 0x33333333) x = ((x >> 4) + x) & 0x0f0f0f0f x += x >> 8 x += x >> 16 return x & 0x0000003f # pylint: enable=C0103 def _interfaces_ip(out): ''' Uses ip to return a dictionary of interfaces with various information about each (up/down state, ip address, netmask, and hwaddr) ''' ret = dict() def parse_network(value, cols): ''' Return a tuple of ip, netmask, broadcast based on the current set of cols ''' brd = None scope = None if '/' in value: # we have a CIDR in this address ip, cidr = value.split('/') # pylint: disable=C0103 else: ip = value # pylint: disable=C0103 cidr = 32 if type_ == 'inet': mask = cidr_to_ipv4_netmask(int(cidr)) if 'brd' in cols: brd = cols[cols.index('brd') + 1] elif type_ == 'inet6': mask = cidr if 'scope' in cols: scope = cols[cols.index('scope') + 1] return (ip, mask, brd, scope) groups = re.compile('\r?\n\\d').split(out) for group in groups: iface = None data = dict() for line in group.splitlines(): if ' ' not in line: continue match = re.match(r'^\d*:\s+([\w.\-]+)(?:@)?([\w.\-]+)?:\s+<(.+)>', line) if match: iface, parent, attrs = match.groups() if 'UP' in attrs.split(','): data['up'] = True else: data['up'] = False if parent: data['parent'] = parent continue cols = line.split() if len(cols) >= 2: type_, value = tuple(cols[0:2]) iflabel = cols[-1:][0] if type_ in ('inet', 'inet6'): if 'secondary' not in cols: ipaddr, netmask, broadcast, scope = parse_network(value, cols) if type_ == 'inet': if 'inet' not in data: data['inet'] = list() addr_obj = dict() addr_obj['address'] = ipaddr addr_obj['netmask'] = netmask addr_obj['broadcast'] = broadcast addr_obj['label'] = iflabel data['inet'].append(addr_obj) elif type_ == 'inet6': if 'inet6' not in data: data['inet6'] = list() addr_obj = dict() addr_obj['address'] = ipaddr addr_obj['prefixlen'] = netmask addr_obj['scope'] = scope data['inet6'].append(addr_obj) else: if 'secondary' not in data: data['secondary'] = list() ip_, mask, brd, scp = parse_network(value, cols) data['secondary'].append({ 'type': type_, 'address': ip_, 'netmask': mask, 'broadcast': brd, 'label': iflabel, }) del ip_, mask, brd, scp elif type_.startswith('link'): data['hwaddr'] = value if iface: ret[iface] = data del iface, data return ret def _interfaces_ifconfig(out): ''' Uses ifconfig to return a dictionary of interfaces with various information about each (up/down state, ip address, netmask, and hwaddr) ''' ret = dict() piface = re.compile(r'^([^\s:]+)') pmac = re.compile('.*?(?:HWaddr|ether|address:|lladdr) ([0-9a-fA-F:]+)') if salt.utils.platform.is_sunos(): pip = re.compile(r'.*?(?:inet\s+)([0-9]+\.[0-9]+\.[0-9]+\.[0-9]+)(.*)') pip6 = re.compile('.*?(?:inet6 )([0-9a-fA-F:]+)') pmask6 = re.compile(r'.*?(?:inet6 [0-9a-fA-F:]+/(\d+)).*') else: pip = re.compile(r'.*?(?:inet addr:|inet [^\d]*)(.*?)\s') pip6 = re.compile('.*?(?:inet6 addr: (.*?)/|inet6 )([0-9a-fA-F:]+)') pmask6 = re.compile(r'.*?(?:inet6 addr: [0-9a-fA-F:]+/(\d+)|prefixlen (\d+))(?: Scope:([a-zA-Z]+)| scopeid (0x[0-9a-fA-F]))?') pmask = re.compile(r'.*?(?:Mask:|netmask )(?:((?:0x)?[0-9a-fA-F]{8})|([\d\.]+))') pupdown = re.compile('UP') pbcast = re.compile(r'.*?(?:Bcast:|broadcast )([\d\.]+)') groups = re.compile('\r?\n(?=\\S)').split(out) for group in groups: data = dict() iface = '' updown = False for line in group.splitlines(): miface = piface.match(line) mmac = pmac.match(line) mip = pip.match(line) mip6 = pip6.match(line) mupdown = pupdown.search(line) if miface: iface = miface.group(1) if mmac: data['hwaddr'] = mmac.group(1) if salt.utils.platform.is_sunos(): expand_mac = [] for chunk in data['hwaddr'].split(':'): expand_mac.append('0{0}'.format(chunk) if len(chunk) < 2 else '{0}'.format(chunk)) data['hwaddr'] = ':'.join(expand_mac) if mip: if 'inet' not in data: data['inet'] = list() addr_obj = dict() addr_obj['address'] = mip.group(1) mmask = pmask.match(line) if mmask: if mmask.group(1): mmask = _number_of_set_bits_to_ipv4_netmask( int(mmask.group(1), 16)) else: mmask = mmask.group(2) addr_obj['netmask'] = mmask mbcast = pbcast.match(line) if mbcast: addr_obj['broadcast'] = mbcast.group(1) data['inet'].append(addr_obj) if mupdown: updown = True if mip6: if 'inet6' not in data: data['inet6'] = list() addr_obj = dict() addr_obj['address'] = mip6.group(1) or mip6.group(2) mmask6 = pmask6.match(line) if mmask6: addr_obj['prefixlen'] = mmask6.group(1) or mmask6.group(2) if not salt.utils.platform.is_sunos(): ipv6scope = mmask6.group(3) or mmask6.group(4) addr_obj['scope'] = ipv6scope.lower() if ipv6scope is not None else ipv6scope # SunOS sometimes has ::/0 as inet6 addr when using addrconf if not salt.utils.platform.is_sunos() \ or addr_obj['address'] != '::' \ and addr_obj['prefixlen'] != 0: data['inet6'].append(addr_obj) data['up'] = updown if iface in ret: # SunOS optimization, where interfaces occur twice in 'ifconfig -a' # output with the same name: for ipv4 and then for ipv6 addr family. # Every instance has it's own 'UP' status and we assume that ipv4 # status determines global interface status. # # merge items with higher priority for older values # after that merge the inet and inet6 sub items for both ret[iface] = dict(list(data.items()) + list(ret[iface].items())) if 'inet' in data: ret[iface]['inet'].extend(x for x in data['inet'] if x not in ret[iface]['inet']) if 'inet6' in data: ret[iface]['inet6'].extend(x for x in data['inet6'] if x not in ret[iface]['inet6']) else: ret[iface] = data del data return ret def linux_interfaces(): ''' Obtain interface information for *NIX/BSD variants ''' ifaces = dict() ip_path = salt.utils.path.which('ip') ifconfig_path = None if ip_path else salt.utils.path.which('ifconfig') if ip_path: cmd1 = subprocess.Popen( '{0} link show'.format(ip_path), shell=True, close_fds=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT).communicate()[0] cmd2 = subprocess.Popen( '{0} addr show'.format(ip_path), shell=True, close_fds=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT).communicate()[0] ifaces = _interfaces_ip("{0}\n{1}".format( salt.utils.stringutils.to_str(cmd1), salt.utils.stringutils.to_str(cmd2))) elif ifconfig_path: cmd = subprocess.Popen( '{0} -a'.format(ifconfig_path), shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT).communicate()[0] ifaces = _interfaces_ifconfig(salt.utils.stringutils.to_str(cmd)) return ifaces def _netbsd_interfaces_ifconfig(out): ''' Uses ifconfig to return a dictionary of interfaces with various information about each (up/down state, ip address, netmask, and hwaddr) ''' ret = dict() piface = re.compile(r'^([^\s:]+)') pmac = re.compile('.*?address: ([0-9a-f:]+)') pip = re.compile(r'.*?inet [^\d]*(.*?)/([\d]*)\s') pip6 = re.compile(r'.*?inet6 ([0-9a-f:]+)%([a-zA-Z0-9]*)/([\d]*)\s') pupdown = re.compile('UP') pbcast = re.compile(r'.*?broadcast ([\d\.]+)') groups = re.compile('\r?\n(?=\\S)').split(out) for group in groups: data = dict() iface = '' updown = False for line in group.splitlines(): miface = piface.match(line) mmac = pmac.match(line) mip = pip.match(line) mip6 = pip6.match(line) mupdown = pupdown.search(line) if miface: iface = miface.group(1) if mmac: data['hwaddr'] = mmac.group(1) if mip: if 'inet' not in data: data['inet'] = list() addr_obj = dict() addr_obj['address'] = mip.group(1) mmask = mip.group(2) if mip.group(2): addr_obj['netmask'] = cidr_to_ipv4_netmask(mip.group(2)) mbcast = pbcast.match(line) if mbcast: addr_obj['broadcast'] = mbcast.group(1) data['inet'].append(addr_obj) if mupdown: updown = True if mip6: if 'inet6' not in data: data['inet6'] = list() addr_obj = dict() addr_obj['address'] = mip6.group(1) mmask6 = mip6.group(3) addr_obj['scope'] = mip6.group(2) addr_obj['prefixlen'] = mip6.group(3) data['inet6'].append(addr_obj) data['up'] = updown ret[iface] = data del data return ret def netbsd_interfaces(): ''' Obtain interface information for NetBSD >= 8 where the ifconfig output diverged from other BSD variants (Netmask is now part of the address) ''' # NetBSD versions prior to 8.0 can still use linux_interfaces() if LooseVersion(os.uname()[2]) < LooseVersion('8.0'): return linux_interfaces() ifconfig_path = salt.utils.path.which('ifconfig') cmd = subprocess.Popen( '{0} -a'.format(ifconfig_path), shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT).communicate()[0] return _netbsd_interfaces_ifconfig(salt.utils.stringutils.to_str(cmd)) def _interfaces_ipconfig(out): ''' Returns a dictionary of interfaces with various information about each (up/down state, ip address, netmask, and hwaddr) NOTE: This is not used by any function and may be able to be removed in the future. ''' ifaces = dict() iface = None adapter_iface_regex = re.compile(r'adapter (\S.+):$') for line in out.splitlines(): if not line: continue # TODO what does Windows call Infiniband and 10/40gige adapters if line.startswith('Ethernet'): iface = ifaces[adapter_iface_regex.search(line).group(1)] iface['up'] = True addr = None continue if iface: key, val = line.split(',', 1) key = key.strip(' .') val = val.strip() if addr and key == 'Subnet Mask': addr['netmask'] = val elif key in ('IP Address', 'IPv4 Address'): if 'inet' not in iface: iface['inet'] = list() addr = {'address': val.rstrip('(Preferred)'), 'netmask': None, 'broadcast': None} # TODO find the broadcast iface['inet'].append(addr) elif 'IPv6 Address' in key: if 'inet6' not in iface: iface['inet'] = list() # XXX What is the prefixlen!? addr = {'address': val.rstrip('(Preferred)'), 'prefixlen': None} iface['inet6'].append(addr) elif key == 'Physical Address': iface['hwaddr'] = val elif key == 'Media State': # XXX seen used for tunnel adaptors # might be useful iface['up'] = (val != 'Media disconnected') def win_interfaces(): ''' Obtain interface information for Windows systems ''' with salt.utils.winapi.Com(): c = wmi.WMI() ifaces = {} for iface in c.Win32_NetworkAdapterConfiguration(IPEnabled=1): ifaces[iface.Description] = dict() if iface.MACAddress: ifaces[iface.Description]['hwaddr'] = iface.MACAddress if iface.IPEnabled: ifaces[iface.Description]['up'] = True for ip in iface.IPAddress: if '.' in ip: if 'inet' not in ifaces[iface.Description]: ifaces[iface.Description]['inet'] = [] item = {'address': ip, 'label': iface.Description} if iface.DefaultIPGateway: broadcast = next((i for i in iface.DefaultIPGateway if '.' in i), '') if broadcast: item['broadcast'] = broadcast if iface.IPSubnet: netmask = next((i for i in iface.IPSubnet if '.' in i), '') if netmask: item['netmask'] = netmask ifaces[iface.Description]['inet'].append(item) if ':' in ip: if 'inet6' not in ifaces[iface.Description]: ifaces[iface.Description]['inet6'] = [] item = {'address': ip} if iface.DefaultIPGateway: broadcast = next((i for i in iface.DefaultIPGateway if ':' in i), '') if broadcast: item['broadcast'] = broadcast if iface.IPSubnet: netmask = next((i for i in iface.IPSubnet if ':' in i), '') if netmask: item['netmask'] = netmask ifaces[iface.Description]['inet6'].append(item) else: ifaces[iface.Description]['up'] = False return ifaces def interfaces(): ''' Return a dictionary of information about all the interfaces on the minion ''' if salt.utils.platform.is_windows(): return win_interfaces() elif salt.utils.platform.is_netbsd(): return netbsd_interfaces() else: return linux_interfaces() def get_net_start(ipaddr, netmask): ''' Return the address of the network ''' net = ipaddress.ip_network('{0}/{1}'.format(ipaddr, netmask), strict=False) return six.text_type(net.network_address) def get_net_size(mask): ''' Turns an IPv4 netmask into it's corresponding prefix length (255.255.255.0 -> 24 as in 192.168.1.10/24). ''' binary_str = '' for octet in mask.split('.'): binary_str += bin(int(octet))[2:].zfill(8) return len(binary_str.rstrip('0')) def calc_net(ipaddr, netmask=None): ''' Takes IP (CIDR notation supported) and optionally netmask and returns the network in CIDR-notation. (The IP can be any IP inside the subnet) ''' if netmask is not None: ipaddr = '{0}/{1}'.format(ipaddr, netmask) return six.text_type(ipaddress.ip_network(ipaddr, strict=False)) def _ipv4_to_bits(ipaddr): ''' Accepts an IPv4 dotted quad and returns a string representing its binary counterpart ''' return ''.join([bin(int(x))[2:].rjust(8, '0') for x in ipaddr.split('.')]) def _get_iface_info(iface): ''' If `iface` is available, return interface info and no error, otherwise return no info and log and return an error ''' iface_info = interfaces() if iface in iface_info.keys(): return iface_info, False else: error_msg = ('Interface "{0}" not in available interfaces: "{1}"' ''.format(iface, '", "'.join(iface_info.keys()))) log.error(error_msg) return None, error_msg def _hw_addr_aix(iface): ''' Return the hardware address (a.k.a. MAC address) for a given interface on AIX MAC address not available in through interfaces ''' cmd = subprocess.Popen( 'entstat -d {0} | grep \'Hardware Address\''.format(iface), shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT).communicate()[0] if cmd: comps = cmd.split(' ') if len(comps) == 3: mac_addr = comps[2].strip('\'').strip() return mac_addr error_msg = ('Interface "{0}" either not available or does not contain a hardware address'.format(iface)) log.error(error_msg) return error_msg def hw_addr(iface): ''' Return the hardware address (a.k.a. MAC address) for a given interface .. versionchanged:: 2016.11.4 Added support for AIX ''' if salt.utils.platform.is_aix(): return _hw_addr_aix iface_info, error = _get_iface_info(iface) if error is False: return iface_info.get(iface, {}).get('hwaddr', '') else: return error def interface(iface): ''' Return the details of `iface` or an error if it does not exist ''' iface_info, error = _get_iface_info(iface) if error is False: return iface_info.get(iface, {}).get('inet', '') else: return error def interface_ip(iface): ''' Return `iface` IPv4 addr or an error if `iface` does not exist ''' iface_info, error = _get_iface_info(iface) if error is False: inet = iface_info.get(iface, {}).get('inet', None) return inet[0].get('address', '') if inet else '' else: return error def _subnets(proto='inet', interfaces_=None): ''' Returns a list of subnets to which the host belongs ''' if interfaces_ is None: ifaces = interfaces() elif isinstance(interfaces_, list): ifaces = {} for key, value in six.iteritems(interfaces()): if key in interfaces_: ifaces[key] = value else: ifaces = {interfaces_: interfaces().get(interfaces_, {})} ret = set() if proto == 'inet': subnet = 'netmask' dflt_cidr = 32 elif proto == 'inet6': subnet = 'prefixlen' dflt_cidr = 128 else: log.error('Invalid proto %s calling subnets()', proto) return for ip_info in six.itervalues(ifaces): addrs = ip_info.get(proto, []) addrs.extend([addr for addr in ip_info.get('secondary', []) if addr.get('type') == proto]) for intf in addrs: if subnet in intf: intf = ipaddress.ip_interface('{0}/{1}'.format(intf['address'], intf[subnet])) else: intf = ipaddress.ip_interface('{0}/{1}'.format(intf['address'], dflt_cidr)) if not intf.is_loopback: ret.add(intf.network) return [six.text_type(net) for net in sorted(ret)] def subnets(interfaces=None): ''' Returns a list of IPv4 subnets to which the host belongs ''' return _subnets('inet', interfaces_=interfaces) def subnets6(): ''' Returns a list of IPv6 subnets to which the host belongs ''' return _subnets('inet6') def in_subnet(cidr, addr=None): ''' Returns True if host or (any of) addrs is within specified subnet, otherwise False ''' try: cidr = ipaddress.ip_network(cidr) except ValueError: log.error('Invalid CIDR \'%s\'', cidr) return False if addr is None: addr = ip_addrs() addr.extend(ip_addrs6()) elif not isinstance(addr, (list, tuple)): addr = (addr,) return any(ipaddress.ip_address(item) in cidr for item in addr) def _ip_addrs(interface=None, include_loopback=False, interface_data=None, proto='inet'): ''' Return the full list of IP adresses matching the criteria proto = inet|inet6 ''' ret = set() ifaces = interface_data \ if isinstance(interface_data, dict) \ else interfaces() if interface is None: target_ifaces = ifaces else: target_ifaces = dict([(k, v) for k, v in six.iteritems(ifaces) if k == interface]) if not target_ifaces: log.error('Interface %s not found.', interface) for ip_info in six.itervalues(target_ifaces): addrs = ip_info.get(proto, []) addrs.extend([addr for addr in ip_info.get('secondary', []) if addr.get('type') == proto]) for addr in addrs: addr = ipaddress.ip_address(addr.get('address')) if not addr.is_loopback or include_loopback: ret.add(addr) return [six.text_type(addr) for addr in sorted(ret)] def ip_addrs(interface=None, include_loopback=False, interface_data=None): ''' Returns a list of IPv4 addresses assigned to the host. 127.0.0.1 is ignored, unless 'include_loopback=True' is indicated. If 'interface' is provided, then only IP addresses from that interface will be returned. ''' return _ip_addrs(interface, include_loopback, interface_data, 'inet') def ip_addrs6(interface=None, include_loopback=False, interface_data=None): ''' Returns a list of IPv6 addresses assigned to the host. ::1 is ignored, unless 'include_loopback=True' is indicated. If 'interface' is provided, then only IP addresses from that interface will be returned. ''' return _ip_addrs(interface, include_loopback, interface_data, 'inet6') def hex2ip(hex_ip, invert=False): ''' Convert a hex string to an ip, if a failure occurs the original hex is returned. If 'invert=True' assume that ip from /proc/net/<proto> ''' if len(hex_ip) == 32: # ipv6 ip = [] for i in range(0, 32, 8): ip_part = hex_ip[i:i + 8] ip_part = [ip_part[x:x + 2] for x in range(0, 8, 2)] if invert: ip.append("{0[3]}{0[2]}:{0[1]}{0[0]}".format(ip_part)) else: ip.append("{0[0]}{0[1]}:{0[2]}{0[3]}".format(ip_part)) try: address = ipaddress.IPv6Address(":".join(ip)) if address.ipv4_mapped: return str(address.ipv4_mapped) else: return address.compressed except ipaddress.AddressValueError as ex: log.error('hex2ip - ipv6 address error: %s', ex) return hex_ip try: hip = int(hex_ip, 16) except ValueError: return hex_ip if invert: return '{3}.{2}.{1}.{0}'.format(hip >> 24 & 255, hip >> 16 & 255, hip >> 8 & 255, hip & 255) return '{0}.{1}.{2}.{3}'.format(hip >> 24 & 255, hip >> 16 & 255, hip >> 8 & 255, hip & 255) def active_tcp(): ''' Return a dict describing all active tcp connections as quickly as possible ''' ret = {} for statf in ['/proc/net/tcp', '/proc/net/tcp6']: if os.path.isfile(statf): with salt.utils.files.fopen(statf, 'rb') as fp_: for line in fp_: line = salt.utils.stringutils.to_unicode(line) if line.strip().startswith('sl'): continue iret = _parse_tcp_line(line) sl = next(iter(iret)) if iret[sl]['state'] == 1: # 1 is ESTABLISHED del iret[sl]['state'] ret[len(ret)] = iret[sl] return ret def local_port_tcp(port): ''' Return a set of remote ip addrs attached to the specified local port ''' ret = _remotes_on(port, 'local_port') return ret def remote_port_tcp(port): ''' Return a set of ip addrs the current host is connected to on given port ''' ret = _remotes_on(port, 'remote_port') return ret def _remotes_on(port, which_end): ''' Return a set of ip addrs active tcp connections ''' port = int(port) ret = _netlink_tool_remote_on(port, which_end) if ret is not None: return ret ret = set() proc_available = False for statf in ['/proc/net/tcp', '/proc/net/tcp6']: if os.path.isfile(statf): proc_available = True with salt.utils.files.fopen(statf, 'r') as fp_: for line in fp_: line = salt.utils.stringutils.to_unicode(line) if line.strip().startswith('sl'): continue iret = _parse_tcp_line(line) sl = next(iter(iret)) if iret[sl][which_end] == port and iret[sl]['state'] == 1: # 1 is ESTABLISHED ret.add(iret[sl]['remote_addr']) if not proc_available: # Fallback to use OS specific tools if salt.utils.platform.is_sunos(): return _sunos_remotes_on(port, which_end) if salt.utils.platform.is_freebsd(): return _freebsd_remotes_on(port, which_end) if salt.utils.platform.is_netbsd(): return _netbsd_remotes_on(port, which_end) if salt.utils.platform.is_openbsd(): return _openbsd_remotes_on(port, which_end) if salt.utils.platform.is_windows(): return _windows_remotes_on(port, which_end) if salt.utils.platform.is_aix(): return _aix_remotes_on(port, which_end) return _linux_remotes_on(port, which_end) return ret def _parse_tcp_line(line): ''' Parse a single line from the contents of /proc/net/tcp or /proc/net/tcp6 ''' ret = {} comps = line.strip().split() sl = comps[0].rstrip(':') ret[sl] = {} l_addr, l_port = comps[1].split(':') r_addr, r_port = comps[2].split(':') ret[sl]['local_addr'] = hex2ip(l_addr, True) ret[sl]['local_port'] = int(l_port, 16) ret[sl]['remote_addr'] = hex2ip(r_addr, True) ret[sl]['remote_port'] = int(r_port, 16) ret[sl]['state'] = int(comps[3], 16) return ret def _netlink_tool_remote_on(port, which_end): ''' Returns set of ipv4 host addresses of remote established connections on local or remote tcp port. Parses output of shell 'ss' to get connections [root@salt-master ~]# ss -ant State Recv-Q Send-Q Local Address:Port Peer Address:Port LISTEN 0 511 *:80 *:* LISTEN 0 128 *:22 *:* ESTAB 0 0 127.0.0.1:56726 127.0.0.1:4505 ''' remotes = set() valid = False try: data = subprocess.check_output(['ss', '-ant']) # pylint: disable=minimum-python-version except subprocess.CalledProcessError: log.error('Failed ss') raise except OSError: # not command "No such file or directory" return None lines = salt.utils.stringutils.to_str(data).split('\n') for line in lines: if 'Address:Port' in line: # ss tools may not be valid valid = True continue elif 'ESTAB' not in line: continue chunks = line.split() local_host, local_port = chunks[3].split(':', 1) remote_host, remote_port = chunks[4].split(':', 1) if which_end == 'remote_port' and int(remote_port) != port: continue if which_end == 'local_port' and int(local_port) != port: continue remotes.add(remote_host) if valid is False: remotes = None return remotes def _sunos_remotes_on(port, which_end): ''' SunOS specific helper function. Returns set of ipv4 host addresses of remote established connections on local or remote tcp port. Parses output of shell 'netstat' to get connections [root@salt-master ~]# netstat -f inet -n TCP: IPv4 Local Address Remote Address Swind Send-Q Rwind Recv-Q State -------------------- -------------------- ----- ------ ----- ------ ----------- 10.0.0.101.4505 10.0.0.1.45329 1064800 0 1055864 0 ESTABLISHED 10.0.0.101.4505 10.0.0.100.50798 1064800 0 1055864 0 ESTABLISHED ''' remotes = set() try: data = subprocess.check_output(['netstat', '-f', 'inet', '-n']) # pylint: disable=minimum-python-version except subprocess.CalledProcessError: log.error('Failed netstat') raise lines = salt.utils.stringutils.to_str(data).split('\n') for line in lines: if 'ESTABLISHED' not in line: continue chunks = line.split() local_host, local_port = chunks[0].rsplit('.', 1) remote_host, remote_port = chunks[1].rsplit('.', 1) if which_end == 'remote_port' and int(remote_port) != port: continue if which_end == 'local_port' and int(local_port) != port: continue remotes.add(remote_host) return remotes def _freebsd_remotes_on(port, which_end): ''' Returns set of ipv4 host addresses of remote established connections on local tcp port port. Parses output of shell 'sockstat' (FreeBSD) to get connections $ sudo sockstat -4 USER COMMAND PID FD PROTO LOCAL ADDRESS FOREIGN ADDRESS root python2.7 1456 29 tcp4 *:4505 *:* root python2.7 1445 17 tcp4 *:4506 *:* root python2.7 1294 14 tcp4 127.0.0.1:11813 127.0.0.1:4505 root python2.7 1294 41 tcp4 127.0.0.1:61115 127.0.0.1:4506 $ sudo sockstat -4 -c -p 4506 USER COMMAND PID FD PROTO LOCAL ADDRESS FOREIGN ADDRESS root python2.7 1294 41 tcp4 127.0.0.1:61115 127.0.0.1:4506 ''' port = int(port) remotes = set() try: cmd = salt.utils.args.shlex_split('sockstat -4 -c -p {0}'.format(port)) data = subprocess.check_output(cmd) # pylint: disable=minimum-python-version except subprocess.CalledProcessError as ex: log.error('Failed "sockstat" with returncode = %s', ex.returncode) raise lines = salt.utils.stringutils.to_str(data).split('\n') for line in lines: chunks = line.split() if not chunks: continue # ['root', 'python2.7', '1456', '37', 'tcp4', # '127.0.0.1:4505-', '127.0.0.1:55703'] # print chunks if 'COMMAND' in chunks[1]: continue # ignore header if len(chunks) < 2: continue # sockstat -4 -c -p 4506 does this with high PIDs: # USER COMMAND PID FD PROTO LOCAL ADDRESS FOREIGN ADDRESS # salt-master python2.781106 35 tcp4 192.168.12.34:4506 192.168.12.45:60143 local = chunks[-2] remote = chunks[-1] lhost, lport = local.split(':') rhost, rport = remote.split(':') if which_end == 'local' and int(lport) != port: # ignore if local port not port continue if which_end == 'remote' and int(rport) != port: # ignore if remote port not port continue remotes.add(rhost) return remotes def _netbsd_remotes_on(port, which_end): ''' Returns set of ipv4 host addresses of remote established connections on local tcp port port. Parses output of shell 'sockstat' (NetBSD) to get connections $ sudo sockstat -4 -n USER COMMAND PID FD PROTO LOCAL ADDRESS FOREIGN ADDRESS root python2.7 1456 29 tcp *.4505 *.* root python2.7 1445 17 tcp *.4506 *.* root python2.7 1294 14 tcp 127.0.0.1.11813 127.0.0.1.4505 root python2.7 1294 41 tcp 127.0.0.1.61115 127.0.0.1.4506 $ sudo sockstat -4 -c -n -p 4506 USER COMMAND PID FD PROTO LOCAL ADDRESS FOREIGN ADDRESS root python2.7 1294 41 tcp 127.0.0.1.61115 127.0.0.1.4506 ''' port = int(port) remotes = set() try: cmd = salt.utils.args.shlex_split('sockstat -4 -c -n -p {0}'.format(port)) data = subprocess.check_output(cmd) # pylint: disable=minimum-python-version except subprocess.CalledProcessError as ex: log.error('Failed "sockstat" with returncode = %s', ex.returncode) raise lines = salt.utils.stringutils.to_str(data).split('\n') for line in lines: chunks = line.split() if not chunks: continue # ['root', 'python2.7', '1456', '37', 'tcp', # '127.0.0.1.4505-', '127.0.0.1.55703'] # print chunks if 'COMMAND' in chunks[1]: continue # ignore header if len(chunks) < 2: continue local = chunks[5].split('.') lport = local.pop() lhost = '.'.join(local) remote = chunks[6].split('.') rport = remote.pop() rhost = '.'.join(remote) if which_end == 'local' and int(lport) != port: # ignore if local port not port continue if which_end == 'remote' and int(rport) != port: # ignore if remote port not port continue remotes.add(rhost) return remotes def _openbsd_remotes_on(port, which_end): ''' OpenBSD specific helper function. Returns set of ipv4 host addresses of remote established connections on local or remote tcp port. Parses output of shell 'netstat' to get connections $ netstat -nf inet Active Internet connections Proto Recv-Q Send-Q Local Address Foreign Address (state) tcp 0 0 10.0.0.101.4505 10.0.0.1.45329 ESTABLISHED tcp 0 0 10.0.0.101.4505 10.0.0.100.50798 ESTABLISHED ''' remotes = set() try: data = subprocess.check_output(['netstat', '-nf', 'inet']) # pylint: disable=minimum-python-version except subprocess.CalledProcessError: log.error('Failed netstat') raise lines = data.split('\n') for line in lines: if 'ESTABLISHED' not in line: continue chunks = line.split() local_host, local_port = chunks[3].rsplit('.', 1) remote_host, remote_port = chunks[4].rsplit('.', 1) if which_end == 'remote_port' and int(remote_port) != port: continue if which_end == 'local_port' and int(local_port) != port: continue remotes.add(remote_host) return remotes def _windows_remotes_on(port, which_end): r''' Windows specific helper function. Returns set of ipv4 host addresses of remote established connections on local or remote tcp port. Parses output of shell 'netstat' to get connections C:\>netstat -n Active Connections Proto Local Address Foreign Address State TCP 10.2.33.17:3007 130.164.12.233:10123 ESTABLISHED TCP 10.2.33.17:3389 130.164.30.5:10378 ESTABLISHED ''' remotes = set() try: data = subprocess.check_output(['netstat', '-n']) # pylint: disable=minimum-python-version except subprocess.CalledProcessError: log.error('Failed netstat') raise lines = salt.utils.stringutils.to_str(data).split('\n') for line in lines: if 'ESTABLISHED' not in line: continue chunks = line.split() local_host, local_port = chunks[1].rsplit(':', 1) remote_host, remote_port = chunks[2].rsplit(':', 1) if which_end == 'remote_port' and int(remote_port) != port: continue if which_end == 'local_port' and int(local_port) != port: continue remotes.add(remote_host) return remotes def _linux_remotes_on(port, which_end): ''' Linux specific helper function. Returns set of ip host addresses of remote established connections on local tcp port port. Parses output of shell 'lsof' to get connections $ sudo lsof -iTCP:4505 -n COMMAND PID USER FD TYPE DEVICE SIZE/OFF NODE NAME Python 9971 root 35u IPv4 0x18a8464a29ca329d 0t0 TCP *:4505 (LISTEN) Python 9971 root 37u IPv4 0x18a8464a29b2b29d 0t0 TCP 127.0.0.1:4505->127.0.0.1:55703 (ESTABLISHED) Python 10152 root 22u IPv4 0x18a8464a29c8cab5 0t0 TCP 127.0.0.1:55703->127.0.0.1:4505 (ESTABLISHED) Python 10153 root 22u IPv4 0x18a8464a29c8cab5 0t0 TCP [fe80::249a]:4505->[fe80::150]:59367 (ESTABLISHED) ''' remotes = set() try: data = subprocess.check_output( ['lsof', '-iTCP:{0:d}'.format(port), '-n', '-P'] # pylint: disable=minimum-python-version ) except subprocess.CalledProcessError as ex: if ex.returncode == 1: # Lsof return 1 if any error was detected, including the failure # to locate Internet addresses, and it is not an error in this case. log.warning('"lsof" returncode = 1, likely no active TCP sessions.') return remotes log.error('Failed "lsof" with returncode = %s', ex.returncode) raise lines = salt.utils.stringutils.to_str(data).split('\n') for line in lines: chunks = line.split() if not chunks: continue # ['Python', '9971', 'root', '37u', 'IPv4', '0x18a8464a29b2b29d', '0t0', # 'TCP', '127.0.0.1:4505->127.0.0.1:55703', '(ESTABLISHED)'] # print chunks if 'COMMAND' in chunks[0]: continue # ignore header if 'ESTABLISHED' not in chunks[-1]: continue # ignore if not ESTABLISHED # '127.0.0.1:4505->127.0.0.1:55703' local, remote = chunks[8].split('->') _, lport = local.rsplit(':', 1) rhost, rport = remote.rsplit(':', 1) if which_end == 'remote_port' and int(rport) != port: continue if which_end == 'local_port' and int(lport) != port: continue remotes.add(rhost.strip("[]")) return remotes def _aix_remotes_on(port, which_end): ''' AIX specific helper function. Returns set of ipv4 host addresses of remote established connections on local or remote tcp port. Parses output of shell 'netstat' to get connections root@la68pp002_pub:/opt/salt/lib/python2.7/site-packages/salt/modules# netstat -f inet -n Active Internet connections Proto Recv-Q Send-Q Local Address Foreign Address (state) tcp4 0 0 172.29.149.95.50093 209.41.78.13.4505 ESTABLISHED tcp4 0 0 127.0.0.1.9514 *.* LISTEN tcp4 0 0 127.0.0.1.9515 *.* LISTEN tcp4 0 0 127.0.0.1.199 127.0.0.1.32779 ESTABLISHED tcp4 0 0 127.0.0.1.32779 127.0.0.1.199 ESTABLISHED tcp4 0 40 172.29.149.95.22 172.29.96.83.41022 ESTABLISHED tcp4 0 0 172.29.149.95.22 172.29.96.83.41032 ESTABLISHED tcp4 0 0 127.0.0.1.32771 127.0.0.1.32775 ESTABLISHED tcp 0 0 127.0.0.1.32775 127.0.0.1.32771 ESTABLISHED tcp4 0 0 127.0.0.1.32771 127.0.0.1.32776 ESTABLISHED tcp 0 0 127.0.0.1.32776 127.0.0.1.32771 ESTABLISHED tcp4 0 0 127.0.0.1.32771 127.0.0.1.32777 ESTABLISHED tcp 0 0 127.0.0.1.32777 127.0.0.1.32771 ESTABLISHED tcp4 0 0 127.0.0.1.32771 127.0.0.1.32778 ESTABLISHED tcp 0 0 127.0.0.1.32778 127.0.0.1.32771 ESTABLISHED ''' remotes = set() try: data = subprocess.check_output(['netstat', '-f', 'inet', '-n']) # pylint: disable=minimum-python-version except subprocess.CalledProcessError: log.error('Failed netstat') raise lines = salt.utils.stringutils.to_str(data).split('\n') for line in lines: if 'ESTABLISHED' not in line: continue chunks = line.split() local_host, local_port = chunks[3].rsplit('.', 1) remote_host, remote_port = chunks[4].rsplit('.', 1) if which_end == 'remote_port' and int(remote_port) != port: continue if which_end == 'local_port' and int(local_port) != port: continue remotes.add(remote_host) return remotes @jinja_filter('gen_mac') def gen_mac(prefix='AC:DE:48'): ''' Generates a MAC address with the defined OUI prefix. Common prefixes: - ``00:16:3E`` -- Xen - ``00:18:51`` -- OpenVZ - ``00:50:56`` -- VMware (manually generated) - ``52:54:00`` -- QEMU/KVM - ``AC:DE:48`` -- PRIVATE References: - http://standards.ieee.org/develop/regauth/oui/oui.txt - https://www.wireshark.org/tools/oui-lookup.html - https://en.wikipedia.org/wiki/MAC_address ''' return '{0}:{1:02X}:{2:02X}:{3:02X}'.format(prefix, random.randint(0, 0xff), random.randint(0, 0xff), random.randint(0, 0xff)) @jinja_filter('mac_str_to_bytes') def mac_str_to_bytes(mac_str): ''' Convert a MAC address string into bytes. Works with or without separators: b1 = mac_str_to_bytes('08:00:27:13:69:77') b2 = mac_str_to_bytes('080027136977') assert b1 == b2 assert isinstance(b1, bytes) ''' if len(mac_str) == 12: pass elif len(mac_str) == 17: sep = mac_str[2] mac_str = mac_str.replace(sep, '') else: raise ValueError('Invalid MAC address') chars = (int(mac_str[s:s+2], 16) for s in range(0, 12, 2)) return bytes(chars) if six.PY3 else b''.join(chr(x) for x in chars) def refresh_dns(): ''' issue #21397: force glibc to re-read resolv.conf ''' try: res_init() except NameError: # Exception raised loading the library, thus res_init is not defined pass @jinja_filter('connection_check') def connection_check(addr, port=80, safe=False, ipv6=None): ''' Provides a convenient alias for the dns_check filter. ''' return dns_check(addr, port, safe, ipv6) @jinja_filter('dns_check') def dns_check(addr, port=80, safe=False, ipv6=None, attempt_connect=True): ''' Return the ip resolved by dns, but do not exit on failure, only raise an exception. Obeys system preference for IPv4/6 address resolution - this can be overridden by the ipv6 flag. Tries to connect to the address before considering it useful. If no address can be reached, the first one resolved is used as a fallback. ''' error = False lookup = addr seen_ipv6 = False family = socket.AF_INET6 if ipv6 else socket.AF_INET if ipv6 is False else socket.AF_UNSPEC hostnames = [] try: refresh_dns() hostnames = socket.getaddrinfo(addr, port, family, socket.SOCK_STREAM) except TypeError: err = ('Attempt to resolve address \'{0}\' failed. Invalid or unresolveable address').format(lookup) raise SaltSystemExit(code=42, msg=err) except socket.error: error = True # If ipv6 is set to True, attempt another lookup using the IPv4 family, # just in case we're attempting to lookup an IPv4 IP # as an IPv6 hostname. if error and ipv6: try: refresh_dns() hostnames = socket.getaddrinfo(addr, port, socket.AF_INET, socket.SOCK_STREAM) except TypeError: err = ('Attempt to resolve address \'{0}\' failed. Invalid or unresolveable address').format(lookup) raise SaltSystemExit(code=42, msg=err) except socket.error: error = True try: if not hostnames: error = True else: resolved = False candidates = [] for h in hostnames: # Input is IP address, passed through unchanged, just return it if h[4][0] == addr: resolved = salt.utils.zeromq.ip_bracket(addr) break candidate_addr = salt.utils.zeromq.ip_bracket(h[4][0]) # sometimes /etc/hosts contains ::1 localhost if not ipv6 and candidate_addr == '[::1]': continue candidates.append(candidate_addr) if attempt_connect: try: s = socket.socket(h[0], socket.SOCK_STREAM) s.settimeout(2) s.connect((candidate_addr.strip('[]'), h[4][1])) s.close() resolved = candidate_addr break except socket.error: pass if not resolved: if candidates: resolved = candidates[0] else: error = True except TypeError: err = ('Attempt to resolve address \'{0}\' failed. Invalid or unresolveable address').format(lookup) raise SaltSystemExit(code=42, msg=err) except socket.error: error = True if error: err = ('DNS lookup or connection check of \'{0}\' failed.').format(addr) if safe: if salt.log.is_console_configured(): # If logging is not configured it also means that either # the master or minion instance calling this hasn't even # started running log.error(err) raise SaltClientError() raise SaltSystemExit(code=42, msg=err) return resolved def parse_host_port(host_port): """ Takes a string argument specifying host or host:port. Returns a (hostname, port) or (ip_address, port) tuple. If no port is given, the second (port) element of the returned tuple will be None. host:port argument, for example, is accepted in the forms of: - hostname - hostname:1234 - hostname.domain.tld - hostname.domain.tld:5678 - [1234::5]:5678 - 1234::5 - 10.11.12.13:4567 - 10.11.12.13 """ host, port = None, None # default _s_ = host_port[:] if _s_[0] == "[": if "]" in host_port: host, _s_ = _s_.lstrip("[").rsplit("]", 1) host = ipaddress.IPv6Address(host).compressed if _s_[0] == ":": port = int(_s_.lstrip(":")) else: if len(_s_) > 1: raise ValueError('found ambiguous "{}" port in "{}"'.format(_s_, host_port)) else: if _s_.count(":") == 1: host, _hostport_separator_, port = _s_.partition(":") try: port = int(port) except ValueError as _e_: log.error('host_port "%s" port value "%s" is not an integer.', host_port, port) raise _e_ else: host = _s_ try: if not isinstance(host, ipaddress._BaseAddress): host_ip = ipaddress.ip_address(host).compressed host = host_ip except ValueError: log.debug('"%s" Not an IP address? Assuming it is a hostname.', host) if host != sanitize_host(host): log.error('bad hostname: "%s"', host) raise ValueError('bad hostname: "{}"'.format(host)) return host, port def is_fqdn(hostname): """ Verify if hostname conforms to be a FQDN. :param hostname: text string with the name of the host :return: bool, True if hostname is correct FQDN, False otherwise """ compliant = re.compile(r"(?!-)[A-Z\d\-\_]{1,63}(?<!-)$", re.IGNORECASE) return "." in hostname and len(hostname) < 0xff and all(compliant.match(x) for x in hostname.rstrip(".").split("."))
saltstack/salt
salt/utils/network.py
active_tcp
python
def active_tcp(): ''' Return a dict describing all active tcp connections as quickly as possible ''' ret = {} for statf in ['/proc/net/tcp', '/proc/net/tcp6']: if os.path.isfile(statf): with salt.utils.files.fopen(statf, 'rb') as fp_: for line in fp_: line = salt.utils.stringutils.to_unicode(line) if line.strip().startswith('sl'): continue iret = _parse_tcp_line(line) sl = next(iter(iret)) if iret[sl]['state'] == 1: # 1 is ESTABLISHED del iret[sl]['state'] ret[len(ret)] = iret[sl] return ret
Return a dict describing all active tcp connections as quickly as possible
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/network.py#L1364-L1381
[ "def fopen(*args, **kwargs):\n '''\n Wrapper around open() built-in to set CLOEXEC on the fd.\n\n This flag specifies that the file descriptor should be closed when an exec\n function is invoked;\n\n When a file descriptor is allocated (as with open or dup), this bit is\n initially cleared on the new file descriptor, meaning that descriptor will\n survive into the new program after exec.\n\n NB! We still have small race condition between open and fcntl.\n '''\n if six.PY3:\n try:\n # Don't permit stdin/stdout/stderr to be opened. The boolean False\n # and True are treated by Python 3's open() as file descriptors 0\n # and 1, respectively.\n if args[0] in (0, 1, 2):\n raise TypeError(\n '{0} is not a permitted file descriptor'.format(args[0])\n )\n except IndexError:\n pass\n binary = None\n # ensure 'binary' mode is always used on Windows in Python 2\n if ((six.PY2 and salt.utils.platform.is_windows() and 'binary' not in kwargs) or\n kwargs.pop('binary', False)):\n if len(args) > 1:\n args = list(args)\n if 'b' not in args[1]:\n args[1] = args[1].replace('t', 'b')\n if 'b' not in args[1]:\n args[1] += 'b'\n elif kwargs.get('mode'):\n if 'b' not in kwargs['mode']:\n kwargs['mode'] = kwargs['mode'].replace('t', 'b')\n if 'b' not in kwargs['mode']:\n kwargs['mode'] += 'b'\n else:\n # the default is to read\n kwargs['mode'] = 'rb'\n elif six.PY3 and 'encoding' not in kwargs:\n # In Python 3, if text mode is used and the encoding\n # is not specified, set the encoding to 'utf-8'.\n binary = False\n if len(args) > 1:\n args = list(args)\n if 'b' in args[1]:\n binary = True\n if kwargs.get('mode', None):\n if 'b' in kwargs['mode']:\n binary = True\n if not binary:\n kwargs['encoding'] = __salt_system_encoding__\n\n if six.PY3 and not binary and not kwargs.get('newline', None):\n kwargs['newline'] = ''\n\n f_handle = open(*args, **kwargs) # pylint: disable=resource-leakage\n\n if is_fcntl_available():\n # modify the file descriptor on systems with fcntl\n # unix and unix-like systems only\n try:\n FD_CLOEXEC = fcntl.FD_CLOEXEC # pylint: disable=C0103\n except AttributeError:\n FD_CLOEXEC = 1 # pylint: disable=C0103\n old_flags = fcntl.fcntl(f_handle.fileno(), fcntl.F_GETFD)\n fcntl.fcntl(f_handle.fileno(), fcntl.F_SETFD, old_flags | FD_CLOEXEC)\n\n return f_handle\n", "def to_unicode(s, encoding=None, errors='strict', normalize=False):\n '''\n Given str or unicode, return unicode (str for python 3)\n '''\n def _normalize(s):\n return unicodedata.normalize('NFC', s) if normalize else s\n\n if encoding is None:\n # Try utf-8 first, and fall back to detected encoding\n encoding = ('utf-8', __salt_system_encoding__)\n if not isinstance(encoding, (tuple, list)):\n encoding = (encoding,)\n\n if not encoding:\n raise ValueError('encoding cannot be empty')\n\n exc = None\n if six.PY3:\n if isinstance(s, str):\n return _normalize(s)\n elif isinstance(s, (bytes, bytearray)):\n return _normalize(to_str(s, encoding, errors))\n raise TypeError('expected str, bytes, or bytearray')\n else:\n # This needs to be str and not six.string_types, since if the string is\n # already a unicode type, it does not need to be decoded (and doing so\n # will raise an exception).\n if isinstance(s, unicode): # pylint: disable=incompatible-py3-code,undefined-variable\n return _normalize(s)\n elif isinstance(s, (str, bytearray)):\n for enc in encoding:\n try:\n return _normalize(s.decode(enc, errors))\n except UnicodeDecodeError as err:\n exc = err\n continue\n # The only way we get this far is if a UnicodeDecodeError was\n # raised, otherwise we would have already returned (or raised some\n # other exception).\n raise exc # pylint: disable=raising-bad-type\n raise TypeError('expected str or bytearray')\n", "def _parse_tcp_line(line):\n '''\n Parse a single line from the contents of /proc/net/tcp or /proc/net/tcp6\n '''\n ret = {}\n comps = line.strip().split()\n sl = comps[0].rstrip(':')\n ret[sl] = {}\n l_addr, l_port = comps[1].split(':')\n r_addr, r_port = comps[2].split(':')\n ret[sl]['local_addr'] = hex2ip(l_addr, True)\n ret[sl]['local_port'] = int(l_port, 16)\n ret[sl]['remote_addr'] = hex2ip(r_addr, True)\n ret[sl]['remote_port'] = int(r_port, 16)\n ret[sl]['state'] = int(comps[3], 16)\n return ret\n" ]
# -*- coding: utf-8 -*- ''' Define some generic socket functions for network modules ''' # Import python libs from __future__ import absolute_import, unicode_literals, print_function import itertools import os import re import types import socket import logging import platform import random import subprocess from string import ascii_letters, digits # Import 3rd-party libs from salt.ext import six from salt.ext.six.moves import range # pylint: disable=import-error,redefined-builtin # Attempt to import wmi try: import wmi import salt.utils.winapi except ImportError: pass # Import salt libs import salt.utils.args import salt.utils.files import salt.utils.path import salt.utils.platform import salt.utils.stringutils import salt.utils.zeromq from salt._compat import ipaddress from salt.exceptions import SaltClientError, SaltSystemExit from salt.utils.decorators.jinja import jinja_filter from salt.utils.versions import LooseVersion # inet_pton does not exist in Windows, this is a workaround if salt.utils.platform.is_windows(): from salt.ext import win_inet_pton # pylint: disable=unused-import log = logging.getLogger(__name__) try: import ctypes import ctypes.util libc = ctypes.cdll.LoadLibrary(ctypes.util.find_library("c")) res_init = libc.__res_init except (ImportError, OSError, AttributeError, TypeError): pass # pylint: disable=C0103 def sanitize_host(host): ''' Sanitize host string. https://tools.ietf.org/html/rfc1123#section-2.1 ''' RFC952_characters = ascii_letters + digits + ".-" return "".join([c for c in host[0:255] if c in RFC952_characters]) def isportopen(host, port): ''' Return status of a port ''' if not 1 <= int(port) <= 65535: return False sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) out = sock.connect_ex((sanitize_host(host), int(port))) return out def host_to_ips(host): ''' Returns a list of IP addresses of a given hostname or None if not found. ''' ips = [] try: for family, socktype, proto, canonname, sockaddr in socket.getaddrinfo( host, 0, socket.AF_UNSPEC, socket.SOCK_STREAM): if family == socket.AF_INET: ip, port = sockaddr elif family == socket.AF_INET6: ip, port, flow_info, scope_id = sockaddr ips.append(ip) if not ips: ips = None except Exception: ips = None return ips def _generate_minion_id(): ''' Get list of possible host names and convention names. :return: ''' # There are three types of hostnames: # 1. Network names. How host is accessed from the network. # 2. Host aliases. They might be not available in all the network or only locally (/etc/hosts) # 3. Convention names, an internal nodename. class DistinctList(list): ''' List, which allows one to append only distinct objects. Needs to work on Python 2.6, because of collections.OrderedDict only since 2.7 version. Override 'filter()' for custom filtering. ''' localhost_matchers = [r'localhost.*', r'ip6-.*', r'127[.]\d', r'0\.0\.0\.0', r'::1.*', r'ipv6-.*', r'fe00::.*', r'fe02::.*', r'1.0.0.*.ip6.arpa'] def append(self, p_object): if p_object and p_object not in self and not self.filter(p_object): super(DistinctList, self).append(p_object) return self def extend(self, iterable): for obj in iterable: self.append(obj) return self def filter(self, element): 'Returns True if element needs to be filtered' for rgx in self.localhost_matchers: if re.match(rgx, element): return True def first(self): return self and self[0] or None hostname = socket.gethostname() hosts = DistinctList().append( salt.utils.stringutils.to_unicode(socket.getfqdn(salt.utils.stringutils.to_bytes(hostname))) ).append(platform.node()).append(hostname) if not hosts: try: for a_nfo in socket.getaddrinfo(hosts.first() or 'localhost', None, socket.AF_INET, socket.SOCK_RAW, socket.IPPROTO_IP, socket.AI_CANONNAME): if len(a_nfo) > 3: hosts.append(a_nfo[3]) except socket.gaierror: log.warning('Cannot resolve address %s info via socket: %s', hosts.first() or 'localhost (N/A)', socket.gaierror) # Universal method for everywhere (Linux, Slowlaris, Windows etc) for f_name in ('/etc/hostname', '/etc/nodename', '/etc/hosts', r'{win}\system32\drivers\etc\hosts'.format(win=os.getenv('WINDIR'))): try: with salt.utils.files.fopen(f_name) as f_hdl: for line in f_hdl: line = salt.utils.stringutils.to_unicode(line) hst = line.strip().split('#')[0].strip().split() if hst: if hst[0][:4] in ('127.', '::1') or len(hst) == 1: hosts.extend(hst) except IOError: pass # include public and private ipaddresses return hosts.extend([addr for addr in ip_addrs() if not ipaddress.ip_address(addr).is_loopback]) def generate_minion_id(): ''' Return only first element of the hostname from all possible list. :return: ''' try: ret = salt.utils.stringutils.to_unicode(_generate_minion_id().first()) except TypeError: ret = None return ret or 'localhost' def get_socket(addr, type=socket.SOCK_STREAM, proto=0): ''' Return a socket object for the addr IP-version agnostic ''' version = ipaddress.ip_address(addr).version if version == 4: family = socket.AF_INET elif version == 6: family = socket.AF_INET6 return socket.socket(family, type, proto) def get_fqhostname(): ''' Returns the fully qualified hostname ''' # try getaddrinfo() fqdn = None try: addrinfo = socket.getaddrinfo( socket.gethostname(), 0, socket.AF_UNSPEC, socket.SOCK_STREAM, socket.SOL_TCP, socket.AI_CANONNAME ) for info in addrinfo: # info struct [family, socktype, proto, canonname, sockaddr] # On Windows `canonname` can be an empty string # This can cause the function to return `None` if len(info) > 3 and info[3]: fqdn = info[3] break except socket.gaierror: pass # NOTE: this used to log.error() but it was later disabled except socket.error as err: log.debug('socket.getaddrinfo() failure while finding fqdn: %s', err) if fqdn is None: fqdn = socket.getfqdn() return fqdn def ip_to_host(ip): ''' Returns the hostname of a given IP ''' try: hostname, aliaslist, ipaddrlist = socket.gethostbyaddr(ip) except Exception as exc: log.debug('salt.utils.network.ip_to_host(%r) failed: %s', ip, exc) hostname = None return hostname # pylint: enable=C0103 def is_reachable_host(entity_name): ''' Returns a bool telling if the entity name is a reachable host (IPv4/IPv6/FQDN/etc). :param hostname: :return: ''' try: assert type(socket.getaddrinfo(entity_name, 0, 0, 0, 0)) == list ret = True except socket.gaierror: ret = False return ret def is_ip(ip): ''' Returns a bool telling if the passed IP is a valid IPv4 or IPv6 address. ''' return is_ipv4(ip) or is_ipv6(ip) def is_ipv4(ip): ''' Returns a bool telling if the value passed to it was a valid IPv4 address ''' try: return ipaddress.ip_address(ip).version == 4 except ValueError: return False def is_ipv6(ip): ''' Returns a bool telling if the value passed to it was a valid IPv6 address ''' try: return ipaddress.ip_address(ip).version == 6 except ValueError: return False def is_subnet(cidr): ''' Returns a bool telling if the passed string is an IPv4 or IPv6 subnet ''' return is_ipv4_subnet(cidr) or is_ipv6_subnet(cidr) def is_ipv4_subnet(cidr): ''' Returns a bool telling if the passed string is an IPv4 subnet ''' try: return '/' in cidr and bool(ipaddress.IPv4Network(cidr)) except Exception: return False def is_ipv6_subnet(cidr): ''' Returns a bool telling if the passed string is an IPv6 subnet ''' try: return '/' in cidr and bool(ipaddress.IPv6Network(cidr)) except Exception: return False @jinja_filter('is_ip') def is_ip_filter(ip, options=None): ''' Returns a bool telling if the passed IP is a valid IPv4 or IPv6 address. ''' return is_ipv4_filter(ip, options=options) or is_ipv6_filter(ip, options=options) def _ip_options_global(ip_obj, version): return not ip_obj.is_private def _ip_options_multicast(ip_obj, version): return ip_obj.is_multicast def _ip_options_loopback(ip_obj, version): return ip_obj.is_loopback def _ip_options_link_local(ip_obj, version): return ip_obj.is_link_local def _ip_options_private(ip_obj, version): return ip_obj.is_private def _ip_options_reserved(ip_obj, version): return ip_obj.is_reserved def _ip_options_site_local(ip_obj, version): if version == 6: return ip_obj.is_site_local return False def _ip_options_unspecified(ip_obj, version): return ip_obj.is_unspecified def _ip_options(ip_obj, version, options=None): # will process and IP options options_fun_map = { 'global': _ip_options_global, 'link-local': _ip_options_link_local, 'linklocal': _ip_options_link_local, 'll': _ip_options_link_local, 'link_local': _ip_options_link_local, 'loopback': _ip_options_loopback, 'lo': _ip_options_loopback, 'multicast': _ip_options_multicast, 'private': _ip_options_private, 'public': _ip_options_global, 'reserved': _ip_options_reserved, 'site-local': _ip_options_site_local, 'sl': _ip_options_site_local, 'site_local': _ip_options_site_local, 'unspecified': _ip_options_unspecified } if not options: return six.text_type(ip_obj) # IP version already checked options_list = [option.strip() for option in options.split(',')] for option, fun in options_fun_map.items(): if option in options_list: fun_res = fun(ip_obj, version) if not fun_res: return None # stop at first failed test # else continue return six.text_type(ip_obj) def _is_ipv(ip, version, options=None): if not version: version = 4 if version not in (4, 6): return None try: ip_obj = ipaddress.ip_address(ip) except ValueError: # maybe it is an IP network try: ip_obj = ipaddress.ip_interface(ip) except ValueError: # nope, still not :( return None if not ip_obj.version == version: return None # has the right version, let's move on return _ip_options(ip_obj, version, options=options) @jinja_filter('is_ipv4') def is_ipv4_filter(ip, options=None): ''' Returns a bool telling if the value passed to it was a valid IPv4 address. ip The IP address. net: False Consider IP addresses followed by netmask. options CSV of options regarding the nature of the IP address. E.g.: loopback, multicast, private etc. ''' _is_ipv4 = _is_ipv(ip, 4, options=options) return isinstance(_is_ipv4, six.string_types) @jinja_filter('is_ipv6') def is_ipv6_filter(ip, options=None): ''' Returns a bool telling if the value passed to it was a valid IPv6 address. ip The IP address. net: False Consider IP addresses followed by netmask. options CSV of options regarding the nature of the IP address. E.g.: loopback, multicast, private etc. ''' _is_ipv6 = _is_ipv(ip, 6, options=options) return isinstance(_is_ipv6, six.string_types) def _ipv_filter(value, version, options=None): if version not in (4, 6): return if isinstance(value, (six.string_types, six.text_type, six.binary_type)): return _is_ipv(value, version, options=options) # calls is_ipv4 or is_ipv6 for `value` elif isinstance(value, (list, tuple, types.GeneratorType)): # calls is_ipv4 or is_ipv6 for each element in the list # os it filters and returns only those elements having the desired IP version return [ _is_ipv(addr, version, options=options) for addr in value if _is_ipv(addr, version, options=options) is not None ] return None @jinja_filter('ipv4') def ipv4(value, options=None): ''' Filters a list and returns IPv4 values only. ''' return _ipv_filter(value, 4, options=options) @jinja_filter('ipv6') def ipv6(value, options=None): ''' Filters a list and returns IPv6 values only. ''' return _ipv_filter(value, 6, options=options) @jinja_filter('ipaddr') def ipaddr(value, options=None): ''' Filters and returns only valid IP objects. ''' ipv4_obj = ipv4(value, options=options) ipv6_obj = ipv6(value, options=options) if ipv4_obj is None or ipv6_obj is None: # an IP address can be either IPv4 either IPv6 # therefofe if the value passed as arg is not a list, at least one of the calls above will return None # if one of them is none, means that we should return only one of them return ipv4_obj or ipv6_obj # one of them else: return ipv4_obj + ipv6_obj # extend lists def _filter_ipaddr(value, options, version=None): ipaddr_filter_out = None if version: if version == 4: ipaddr_filter_out = ipv4(value, options) elif version == 6: ipaddr_filter_out = ipv6(value, options) else: ipaddr_filter_out = ipaddr(value, options) if not ipaddr_filter_out: return if not isinstance(ipaddr_filter_out, (list, tuple, types.GeneratorType)): ipaddr_filter_out = [ipaddr_filter_out] return ipaddr_filter_out @jinja_filter('ip_host') def ip_host(value, options=None, version=None): ''' Returns the interfaces IP address, e.g.: 192.168.0.1/28. ''' ipaddr_filter_out = _filter_ipaddr(value, options=options, version=version) if not ipaddr_filter_out: return if not isinstance(value, (list, tuple, types.GeneratorType)): return six.text_type(ipaddress.ip_interface(ipaddr_filter_out[0])) return [six.text_type(ipaddress.ip_interface(ip_a)) for ip_a in ipaddr_filter_out] def _network_hosts(ip_addr_entry): return [ six.text_type(host) for host in ipaddress.ip_network(ip_addr_entry, strict=False).hosts() ] @jinja_filter('network_hosts') def network_hosts(value, options=None, version=None): ''' Return the list of hosts within a network. .. note:: When running this command with a large IPv6 network, the command will take a long time to gather all of the hosts. ''' ipaddr_filter_out = _filter_ipaddr(value, options=options, version=version) if not ipaddr_filter_out: return if not isinstance(value, (list, tuple, types.GeneratorType)): return _network_hosts(ipaddr_filter_out[0]) return [ _network_hosts(ip_a) for ip_a in ipaddr_filter_out ] def _network_size(ip_addr_entry): return ipaddress.ip_network(ip_addr_entry, strict=False).num_addresses @jinja_filter('network_size') def network_size(value, options=None, version=None): ''' Get the size of a network. ''' ipaddr_filter_out = _filter_ipaddr(value, options=options, version=version) if not ipaddr_filter_out: return if not isinstance(value, (list, tuple, types.GeneratorType)): return _network_size(ipaddr_filter_out[0]) return [ _network_size(ip_a) for ip_a in ipaddr_filter_out ] def natural_ipv4_netmask(ip, fmt='prefixlen'): ''' Returns the "natural" mask of an IPv4 address ''' bits = _ipv4_to_bits(ip) if bits.startswith('11'): mask = '24' elif bits.startswith('1'): mask = '16' else: mask = '8' if fmt == 'netmask': return cidr_to_ipv4_netmask(mask) else: return '/' + mask def rpad_ipv4_network(ip): ''' Returns an IP network address padded with zeros. Ex: '192.168.3' -> '192.168.3.0' '10.209' -> '10.209.0.0' ''' return '.'.join(itertools.islice(itertools.chain(ip.split('.'), '0000'), 0, 4)) def cidr_to_ipv4_netmask(cidr_bits): ''' Returns an IPv4 netmask ''' try: cidr_bits = int(cidr_bits) if not 1 <= cidr_bits <= 32: return '' except ValueError: return '' netmask = '' for idx in range(4): if idx: netmask += '.' if cidr_bits >= 8: netmask += '255' cidr_bits -= 8 else: netmask += '{0:d}'.format(256 - (2 ** (8 - cidr_bits))) cidr_bits = 0 return netmask def _number_of_set_bits_to_ipv4_netmask(set_bits): # pylint: disable=C0103 ''' Returns an IPv4 netmask from the integer representation of that mask. Ex. 0xffffff00 -> '255.255.255.0' ''' return cidr_to_ipv4_netmask(_number_of_set_bits(set_bits)) # pylint: disable=C0103 def _number_of_set_bits(x): ''' Returns the number of bits that are set in a 32bit int ''' # Taken from http://stackoverflow.com/a/4912729. Many thanks! x -= (x >> 1) & 0x55555555 x = ((x >> 2) & 0x33333333) + (x & 0x33333333) x = ((x >> 4) + x) & 0x0f0f0f0f x += x >> 8 x += x >> 16 return x & 0x0000003f # pylint: enable=C0103 def _interfaces_ip(out): ''' Uses ip to return a dictionary of interfaces with various information about each (up/down state, ip address, netmask, and hwaddr) ''' ret = dict() def parse_network(value, cols): ''' Return a tuple of ip, netmask, broadcast based on the current set of cols ''' brd = None scope = None if '/' in value: # we have a CIDR in this address ip, cidr = value.split('/') # pylint: disable=C0103 else: ip = value # pylint: disable=C0103 cidr = 32 if type_ == 'inet': mask = cidr_to_ipv4_netmask(int(cidr)) if 'brd' in cols: brd = cols[cols.index('brd') + 1] elif type_ == 'inet6': mask = cidr if 'scope' in cols: scope = cols[cols.index('scope') + 1] return (ip, mask, brd, scope) groups = re.compile('\r?\n\\d').split(out) for group in groups: iface = None data = dict() for line in group.splitlines(): if ' ' not in line: continue match = re.match(r'^\d*:\s+([\w.\-]+)(?:@)?([\w.\-]+)?:\s+<(.+)>', line) if match: iface, parent, attrs = match.groups() if 'UP' in attrs.split(','): data['up'] = True else: data['up'] = False if parent: data['parent'] = parent continue cols = line.split() if len(cols) >= 2: type_, value = tuple(cols[0:2]) iflabel = cols[-1:][0] if type_ in ('inet', 'inet6'): if 'secondary' not in cols: ipaddr, netmask, broadcast, scope = parse_network(value, cols) if type_ == 'inet': if 'inet' not in data: data['inet'] = list() addr_obj = dict() addr_obj['address'] = ipaddr addr_obj['netmask'] = netmask addr_obj['broadcast'] = broadcast addr_obj['label'] = iflabel data['inet'].append(addr_obj) elif type_ == 'inet6': if 'inet6' not in data: data['inet6'] = list() addr_obj = dict() addr_obj['address'] = ipaddr addr_obj['prefixlen'] = netmask addr_obj['scope'] = scope data['inet6'].append(addr_obj) else: if 'secondary' not in data: data['secondary'] = list() ip_, mask, brd, scp = parse_network(value, cols) data['secondary'].append({ 'type': type_, 'address': ip_, 'netmask': mask, 'broadcast': brd, 'label': iflabel, }) del ip_, mask, brd, scp elif type_.startswith('link'): data['hwaddr'] = value if iface: ret[iface] = data del iface, data return ret def _interfaces_ifconfig(out): ''' Uses ifconfig to return a dictionary of interfaces with various information about each (up/down state, ip address, netmask, and hwaddr) ''' ret = dict() piface = re.compile(r'^([^\s:]+)') pmac = re.compile('.*?(?:HWaddr|ether|address:|lladdr) ([0-9a-fA-F:]+)') if salt.utils.platform.is_sunos(): pip = re.compile(r'.*?(?:inet\s+)([0-9]+\.[0-9]+\.[0-9]+\.[0-9]+)(.*)') pip6 = re.compile('.*?(?:inet6 )([0-9a-fA-F:]+)') pmask6 = re.compile(r'.*?(?:inet6 [0-9a-fA-F:]+/(\d+)).*') else: pip = re.compile(r'.*?(?:inet addr:|inet [^\d]*)(.*?)\s') pip6 = re.compile('.*?(?:inet6 addr: (.*?)/|inet6 )([0-9a-fA-F:]+)') pmask6 = re.compile(r'.*?(?:inet6 addr: [0-9a-fA-F:]+/(\d+)|prefixlen (\d+))(?: Scope:([a-zA-Z]+)| scopeid (0x[0-9a-fA-F]))?') pmask = re.compile(r'.*?(?:Mask:|netmask )(?:((?:0x)?[0-9a-fA-F]{8})|([\d\.]+))') pupdown = re.compile('UP') pbcast = re.compile(r'.*?(?:Bcast:|broadcast )([\d\.]+)') groups = re.compile('\r?\n(?=\\S)').split(out) for group in groups: data = dict() iface = '' updown = False for line in group.splitlines(): miface = piface.match(line) mmac = pmac.match(line) mip = pip.match(line) mip6 = pip6.match(line) mupdown = pupdown.search(line) if miface: iface = miface.group(1) if mmac: data['hwaddr'] = mmac.group(1) if salt.utils.platform.is_sunos(): expand_mac = [] for chunk in data['hwaddr'].split(':'): expand_mac.append('0{0}'.format(chunk) if len(chunk) < 2 else '{0}'.format(chunk)) data['hwaddr'] = ':'.join(expand_mac) if mip: if 'inet' not in data: data['inet'] = list() addr_obj = dict() addr_obj['address'] = mip.group(1) mmask = pmask.match(line) if mmask: if mmask.group(1): mmask = _number_of_set_bits_to_ipv4_netmask( int(mmask.group(1), 16)) else: mmask = mmask.group(2) addr_obj['netmask'] = mmask mbcast = pbcast.match(line) if mbcast: addr_obj['broadcast'] = mbcast.group(1) data['inet'].append(addr_obj) if mupdown: updown = True if mip6: if 'inet6' not in data: data['inet6'] = list() addr_obj = dict() addr_obj['address'] = mip6.group(1) or mip6.group(2) mmask6 = pmask6.match(line) if mmask6: addr_obj['prefixlen'] = mmask6.group(1) or mmask6.group(2) if not salt.utils.platform.is_sunos(): ipv6scope = mmask6.group(3) or mmask6.group(4) addr_obj['scope'] = ipv6scope.lower() if ipv6scope is not None else ipv6scope # SunOS sometimes has ::/0 as inet6 addr when using addrconf if not salt.utils.platform.is_sunos() \ or addr_obj['address'] != '::' \ and addr_obj['prefixlen'] != 0: data['inet6'].append(addr_obj) data['up'] = updown if iface in ret: # SunOS optimization, where interfaces occur twice in 'ifconfig -a' # output with the same name: for ipv4 and then for ipv6 addr family. # Every instance has it's own 'UP' status and we assume that ipv4 # status determines global interface status. # # merge items with higher priority for older values # after that merge the inet and inet6 sub items for both ret[iface] = dict(list(data.items()) + list(ret[iface].items())) if 'inet' in data: ret[iface]['inet'].extend(x for x in data['inet'] if x not in ret[iface]['inet']) if 'inet6' in data: ret[iface]['inet6'].extend(x for x in data['inet6'] if x not in ret[iface]['inet6']) else: ret[iface] = data del data return ret def linux_interfaces(): ''' Obtain interface information for *NIX/BSD variants ''' ifaces = dict() ip_path = salt.utils.path.which('ip') ifconfig_path = None if ip_path else salt.utils.path.which('ifconfig') if ip_path: cmd1 = subprocess.Popen( '{0} link show'.format(ip_path), shell=True, close_fds=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT).communicate()[0] cmd2 = subprocess.Popen( '{0} addr show'.format(ip_path), shell=True, close_fds=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT).communicate()[0] ifaces = _interfaces_ip("{0}\n{1}".format( salt.utils.stringutils.to_str(cmd1), salt.utils.stringutils.to_str(cmd2))) elif ifconfig_path: cmd = subprocess.Popen( '{0} -a'.format(ifconfig_path), shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT).communicate()[0] ifaces = _interfaces_ifconfig(salt.utils.stringutils.to_str(cmd)) return ifaces def _netbsd_interfaces_ifconfig(out): ''' Uses ifconfig to return a dictionary of interfaces with various information about each (up/down state, ip address, netmask, and hwaddr) ''' ret = dict() piface = re.compile(r'^([^\s:]+)') pmac = re.compile('.*?address: ([0-9a-f:]+)') pip = re.compile(r'.*?inet [^\d]*(.*?)/([\d]*)\s') pip6 = re.compile(r'.*?inet6 ([0-9a-f:]+)%([a-zA-Z0-9]*)/([\d]*)\s') pupdown = re.compile('UP') pbcast = re.compile(r'.*?broadcast ([\d\.]+)') groups = re.compile('\r?\n(?=\\S)').split(out) for group in groups: data = dict() iface = '' updown = False for line in group.splitlines(): miface = piface.match(line) mmac = pmac.match(line) mip = pip.match(line) mip6 = pip6.match(line) mupdown = pupdown.search(line) if miface: iface = miface.group(1) if mmac: data['hwaddr'] = mmac.group(1) if mip: if 'inet' not in data: data['inet'] = list() addr_obj = dict() addr_obj['address'] = mip.group(1) mmask = mip.group(2) if mip.group(2): addr_obj['netmask'] = cidr_to_ipv4_netmask(mip.group(2)) mbcast = pbcast.match(line) if mbcast: addr_obj['broadcast'] = mbcast.group(1) data['inet'].append(addr_obj) if mupdown: updown = True if mip6: if 'inet6' not in data: data['inet6'] = list() addr_obj = dict() addr_obj['address'] = mip6.group(1) mmask6 = mip6.group(3) addr_obj['scope'] = mip6.group(2) addr_obj['prefixlen'] = mip6.group(3) data['inet6'].append(addr_obj) data['up'] = updown ret[iface] = data del data return ret def netbsd_interfaces(): ''' Obtain interface information for NetBSD >= 8 where the ifconfig output diverged from other BSD variants (Netmask is now part of the address) ''' # NetBSD versions prior to 8.0 can still use linux_interfaces() if LooseVersion(os.uname()[2]) < LooseVersion('8.0'): return linux_interfaces() ifconfig_path = salt.utils.path.which('ifconfig') cmd = subprocess.Popen( '{0} -a'.format(ifconfig_path), shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT).communicate()[0] return _netbsd_interfaces_ifconfig(salt.utils.stringutils.to_str(cmd)) def _interfaces_ipconfig(out): ''' Returns a dictionary of interfaces with various information about each (up/down state, ip address, netmask, and hwaddr) NOTE: This is not used by any function and may be able to be removed in the future. ''' ifaces = dict() iface = None adapter_iface_regex = re.compile(r'adapter (\S.+):$') for line in out.splitlines(): if not line: continue # TODO what does Windows call Infiniband and 10/40gige adapters if line.startswith('Ethernet'): iface = ifaces[adapter_iface_regex.search(line).group(1)] iface['up'] = True addr = None continue if iface: key, val = line.split(',', 1) key = key.strip(' .') val = val.strip() if addr and key == 'Subnet Mask': addr['netmask'] = val elif key in ('IP Address', 'IPv4 Address'): if 'inet' not in iface: iface['inet'] = list() addr = {'address': val.rstrip('(Preferred)'), 'netmask': None, 'broadcast': None} # TODO find the broadcast iface['inet'].append(addr) elif 'IPv6 Address' in key: if 'inet6' not in iface: iface['inet'] = list() # XXX What is the prefixlen!? addr = {'address': val.rstrip('(Preferred)'), 'prefixlen': None} iface['inet6'].append(addr) elif key == 'Physical Address': iface['hwaddr'] = val elif key == 'Media State': # XXX seen used for tunnel adaptors # might be useful iface['up'] = (val != 'Media disconnected') def win_interfaces(): ''' Obtain interface information for Windows systems ''' with salt.utils.winapi.Com(): c = wmi.WMI() ifaces = {} for iface in c.Win32_NetworkAdapterConfiguration(IPEnabled=1): ifaces[iface.Description] = dict() if iface.MACAddress: ifaces[iface.Description]['hwaddr'] = iface.MACAddress if iface.IPEnabled: ifaces[iface.Description]['up'] = True for ip in iface.IPAddress: if '.' in ip: if 'inet' not in ifaces[iface.Description]: ifaces[iface.Description]['inet'] = [] item = {'address': ip, 'label': iface.Description} if iface.DefaultIPGateway: broadcast = next((i for i in iface.DefaultIPGateway if '.' in i), '') if broadcast: item['broadcast'] = broadcast if iface.IPSubnet: netmask = next((i for i in iface.IPSubnet if '.' in i), '') if netmask: item['netmask'] = netmask ifaces[iface.Description]['inet'].append(item) if ':' in ip: if 'inet6' not in ifaces[iface.Description]: ifaces[iface.Description]['inet6'] = [] item = {'address': ip} if iface.DefaultIPGateway: broadcast = next((i for i in iface.DefaultIPGateway if ':' in i), '') if broadcast: item['broadcast'] = broadcast if iface.IPSubnet: netmask = next((i for i in iface.IPSubnet if ':' in i), '') if netmask: item['netmask'] = netmask ifaces[iface.Description]['inet6'].append(item) else: ifaces[iface.Description]['up'] = False return ifaces def interfaces(): ''' Return a dictionary of information about all the interfaces on the minion ''' if salt.utils.platform.is_windows(): return win_interfaces() elif salt.utils.platform.is_netbsd(): return netbsd_interfaces() else: return linux_interfaces() def get_net_start(ipaddr, netmask): ''' Return the address of the network ''' net = ipaddress.ip_network('{0}/{1}'.format(ipaddr, netmask), strict=False) return six.text_type(net.network_address) def get_net_size(mask): ''' Turns an IPv4 netmask into it's corresponding prefix length (255.255.255.0 -> 24 as in 192.168.1.10/24). ''' binary_str = '' for octet in mask.split('.'): binary_str += bin(int(octet))[2:].zfill(8) return len(binary_str.rstrip('0')) def calc_net(ipaddr, netmask=None): ''' Takes IP (CIDR notation supported) and optionally netmask and returns the network in CIDR-notation. (The IP can be any IP inside the subnet) ''' if netmask is not None: ipaddr = '{0}/{1}'.format(ipaddr, netmask) return six.text_type(ipaddress.ip_network(ipaddr, strict=False)) def _ipv4_to_bits(ipaddr): ''' Accepts an IPv4 dotted quad and returns a string representing its binary counterpart ''' return ''.join([bin(int(x))[2:].rjust(8, '0') for x in ipaddr.split('.')]) def _get_iface_info(iface): ''' If `iface` is available, return interface info and no error, otherwise return no info and log and return an error ''' iface_info = interfaces() if iface in iface_info.keys(): return iface_info, False else: error_msg = ('Interface "{0}" not in available interfaces: "{1}"' ''.format(iface, '", "'.join(iface_info.keys()))) log.error(error_msg) return None, error_msg def _hw_addr_aix(iface): ''' Return the hardware address (a.k.a. MAC address) for a given interface on AIX MAC address not available in through interfaces ''' cmd = subprocess.Popen( 'entstat -d {0} | grep \'Hardware Address\''.format(iface), shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT).communicate()[0] if cmd: comps = cmd.split(' ') if len(comps) == 3: mac_addr = comps[2].strip('\'').strip() return mac_addr error_msg = ('Interface "{0}" either not available or does not contain a hardware address'.format(iface)) log.error(error_msg) return error_msg def hw_addr(iface): ''' Return the hardware address (a.k.a. MAC address) for a given interface .. versionchanged:: 2016.11.4 Added support for AIX ''' if salt.utils.platform.is_aix(): return _hw_addr_aix iface_info, error = _get_iface_info(iface) if error is False: return iface_info.get(iface, {}).get('hwaddr', '') else: return error def interface(iface): ''' Return the details of `iface` or an error if it does not exist ''' iface_info, error = _get_iface_info(iface) if error is False: return iface_info.get(iface, {}).get('inet', '') else: return error def interface_ip(iface): ''' Return `iface` IPv4 addr or an error if `iface` does not exist ''' iface_info, error = _get_iface_info(iface) if error is False: inet = iface_info.get(iface, {}).get('inet', None) return inet[0].get('address', '') if inet else '' else: return error def _subnets(proto='inet', interfaces_=None): ''' Returns a list of subnets to which the host belongs ''' if interfaces_ is None: ifaces = interfaces() elif isinstance(interfaces_, list): ifaces = {} for key, value in six.iteritems(interfaces()): if key in interfaces_: ifaces[key] = value else: ifaces = {interfaces_: interfaces().get(interfaces_, {})} ret = set() if proto == 'inet': subnet = 'netmask' dflt_cidr = 32 elif proto == 'inet6': subnet = 'prefixlen' dflt_cidr = 128 else: log.error('Invalid proto %s calling subnets()', proto) return for ip_info in six.itervalues(ifaces): addrs = ip_info.get(proto, []) addrs.extend([addr for addr in ip_info.get('secondary', []) if addr.get('type') == proto]) for intf in addrs: if subnet in intf: intf = ipaddress.ip_interface('{0}/{1}'.format(intf['address'], intf[subnet])) else: intf = ipaddress.ip_interface('{0}/{1}'.format(intf['address'], dflt_cidr)) if not intf.is_loopback: ret.add(intf.network) return [six.text_type(net) for net in sorted(ret)] def subnets(interfaces=None): ''' Returns a list of IPv4 subnets to which the host belongs ''' return _subnets('inet', interfaces_=interfaces) def subnets6(): ''' Returns a list of IPv6 subnets to which the host belongs ''' return _subnets('inet6') def in_subnet(cidr, addr=None): ''' Returns True if host or (any of) addrs is within specified subnet, otherwise False ''' try: cidr = ipaddress.ip_network(cidr) except ValueError: log.error('Invalid CIDR \'%s\'', cidr) return False if addr is None: addr = ip_addrs() addr.extend(ip_addrs6()) elif not isinstance(addr, (list, tuple)): addr = (addr,) return any(ipaddress.ip_address(item) in cidr for item in addr) def _ip_addrs(interface=None, include_loopback=False, interface_data=None, proto='inet'): ''' Return the full list of IP adresses matching the criteria proto = inet|inet6 ''' ret = set() ifaces = interface_data \ if isinstance(interface_data, dict) \ else interfaces() if interface is None: target_ifaces = ifaces else: target_ifaces = dict([(k, v) for k, v in six.iteritems(ifaces) if k == interface]) if not target_ifaces: log.error('Interface %s not found.', interface) for ip_info in six.itervalues(target_ifaces): addrs = ip_info.get(proto, []) addrs.extend([addr for addr in ip_info.get('secondary', []) if addr.get('type') == proto]) for addr in addrs: addr = ipaddress.ip_address(addr.get('address')) if not addr.is_loopback or include_loopback: ret.add(addr) return [six.text_type(addr) for addr in sorted(ret)] def ip_addrs(interface=None, include_loopback=False, interface_data=None): ''' Returns a list of IPv4 addresses assigned to the host. 127.0.0.1 is ignored, unless 'include_loopback=True' is indicated. If 'interface' is provided, then only IP addresses from that interface will be returned. ''' return _ip_addrs(interface, include_loopback, interface_data, 'inet') def ip_addrs6(interface=None, include_loopback=False, interface_data=None): ''' Returns a list of IPv6 addresses assigned to the host. ::1 is ignored, unless 'include_loopback=True' is indicated. If 'interface' is provided, then only IP addresses from that interface will be returned. ''' return _ip_addrs(interface, include_loopback, interface_data, 'inet6') def hex2ip(hex_ip, invert=False): ''' Convert a hex string to an ip, if a failure occurs the original hex is returned. If 'invert=True' assume that ip from /proc/net/<proto> ''' if len(hex_ip) == 32: # ipv6 ip = [] for i in range(0, 32, 8): ip_part = hex_ip[i:i + 8] ip_part = [ip_part[x:x + 2] for x in range(0, 8, 2)] if invert: ip.append("{0[3]}{0[2]}:{0[1]}{0[0]}".format(ip_part)) else: ip.append("{0[0]}{0[1]}:{0[2]}{0[3]}".format(ip_part)) try: address = ipaddress.IPv6Address(":".join(ip)) if address.ipv4_mapped: return str(address.ipv4_mapped) else: return address.compressed except ipaddress.AddressValueError as ex: log.error('hex2ip - ipv6 address error: %s', ex) return hex_ip try: hip = int(hex_ip, 16) except ValueError: return hex_ip if invert: return '{3}.{2}.{1}.{0}'.format(hip >> 24 & 255, hip >> 16 & 255, hip >> 8 & 255, hip & 255) return '{0}.{1}.{2}.{3}'.format(hip >> 24 & 255, hip >> 16 & 255, hip >> 8 & 255, hip & 255) def mac2eui64(mac, prefix=None): ''' Convert a MAC address to a EUI64 identifier or, with prefix provided, a full IPv6 address ''' # http://tools.ietf.org/html/rfc4291#section-2.5.1 eui64 = re.sub(r'[.:-]', '', mac).lower() eui64 = eui64[0:6] + 'fffe' + eui64[6:] eui64 = hex(int(eui64[0:2], 16) | 2)[2:].zfill(2) + eui64[2:] if prefix is None: return ':'.join(re.findall(r'.{4}', eui64)) else: try: net = ipaddress.ip_network(prefix, strict=False) euil = int('0x{0}'.format(eui64), 16) return '{0}/{1}'.format(net[euil], net.prefixlen) except Exception: return def local_port_tcp(port): ''' Return a set of remote ip addrs attached to the specified local port ''' ret = _remotes_on(port, 'local_port') return ret def remote_port_tcp(port): ''' Return a set of ip addrs the current host is connected to on given port ''' ret = _remotes_on(port, 'remote_port') return ret def _remotes_on(port, which_end): ''' Return a set of ip addrs active tcp connections ''' port = int(port) ret = _netlink_tool_remote_on(port, which_end) if ret is not None: return ret ret = set() proc_available = False for statf in ['/proc/net/tcp', '/proc/net/tcp6']: if os.path.isfile(statf): proc_available = True with salt.utils.files.fopen(statf, 'r') as fp_: for line in fp_: line = salt.utils.stringutils.to_unicode(line) if line.strip().startswith('sl'): continue iret = _parse_tcp_line(line) sl = next(iter(iret)) if iret[sl][which_end] == port and iret[sl]['state'] == 1: # 1 is ESTABLISHED ret.add(iret[sl]['remote_addr']) if not proc_available: # Fallback to use OS specific tools if salt.utils.platform.is_sunos(): return _sunos_remotes_on(port, which_end) if salt.utils.platform.is_freebsd(): return _freebsd_remotes_on(port, which_end) if salt.utils.platform.is_netbsd(): return _netbsd_remotes_on(port, which_end) if salt.utils.platform.is_openbsd(): return _openbsd_remotes_on(port, which_end) if salt.utils.platform.is_windows(): return _windows_remotes_on(port, which_end) if salt.utils.platform.is_aix(): return _aix_remotes_on(port, which_end) return _linux_remotes_on(port, which_end) return ret def _parse_tcp_line(line): ''' Parse a single line from the contents of /proc/net/tcp or /proc/net/tcp6 ''' ret = {} comps = line.strip().split() sl = comps[0].rstrip(':') ret[sl] = {} l_addr, l_port = comps[1].split(':') r_addr, r_port = comps[2].split(':') ret[sl]['local_addr'] = hex2ip(l_addr, True) ret[sl]['local_port'] = int(l_port, 16) ret[sl]['remote_addr'] = hex2ip(r_addr, True) ret[sl]['remote_port'] = int(r_port, 16) ret[sl]['state'] = int(comps[3], 16) return ret def _netlink_tool_remote_on(port, which_end): ''' Returns set of ipv4 host addresses of remote established connections on local or remote tcp port. Parses output of shell 'ss' to get connections [root@salt-master ~]# ss -ant State Recv-Q Send-Q Local Address:Port Peer Address:Port LISTEN 0 511 *:80 *:* LISTEN 0 128 *:22 *:* ESTAB 0 0 127.0.0.1:56726 127.0.0.1:4505 ''' remotes = set() valid = False try: data = subprocess.check_output(['ss', '-ant']) # pylint: disable=minimum-python-version except subprocess.CalledProcessError: log.error('Failed ss') raise except OSError: # not command "No such file or directory" return None lines = salt.utils.stringutils.to_str(data).split('\n') for line in lines: if 'Address:Port' in line: # ss tools may not be valid valid = True continue elif 'ESTAB' not in line: continue chunks = line.split() local_host, local_port = chunks[3].split(':', 1) remote_host, remote_port = chunks[4].split(':', 1) if which_end == 'remote_port' and int(remote_port) != port: continue if which_end == 'local_port' and int(local_port) != port: continue remotes.add(remote_host) if valid is False: remotes = None return remotes def _sunos_remotes_on(port, which_end): ''' SunOS specific helper function. Returns set of ipv4 host addresses of remote established connections on local or remote tcp port. Parses output of shell 'netstat' to get connections [root@salt-master ~]# netstat -f inet -n TCP: IPv4 Local Address Remote Address Swind Send-Q Rwind Recv-Q State -------------------- -------------------- ----- ------ ----- ------ ----------- 10.0.0.101.4505 10.0.0.1.45329 1064800 0 1055864 0 ESTABLISHED 10.0.0.101.4505 10.0.0.100.50798 1064800 0 1055864 0 ESTABLISHED ''' remotes = set() try: data = subprocess.check_output(['netstat', '-f', 'inet', '-n']) # pylint: disable=minimum-python-version except subprocess.CalledProcessError: log.error('Failed netstat') raise lines = salt.utils.stringutils.to_str(data).split('\n') for line in lines: if 'ESTABLISHED' not in line: continue chunks = line.split() local_host, local_port = chunks[0].rsplit('.', 1) remote_host, remote_port = chunks[1].rsplit('.', 1) if which_end == 'remote_port' and int(remote_port) != port: continue if which_end == 'local_port' and int(local_port) != port: continue remotes.add(remote_host) return remotes def _freebsd_remotes_on(port, which_end): ''' Returns set of ipv4 host addresses of remote established connections on local tcp port port. Parses output of shell 'sockstat' (FreeBSD) to get connections $ sudo sockstat -4 USER COMMAND PID FD PROTO LOCAL ADDRESS FOREIGN ADDRESS root python2.7 1456 29 tcp4 *:4505 *:* root python2.7 1445 17 tcp4 *:4506 *:* root python2.7 1294 14 tcp4 127.0.0.1:11813 127.0.0.1:4505 root python2.7 1294 41 tcp4 127.0.0.1:61115 127.0.0.1:4506 $ sudo sockstat -4 -c -p 4506 USER COMMAND PID FD PROTO LOCAL ADDRESS FOREIGN ADDRESS root python2.7 1294 41 tcp4 127.0.0.1:61115 127.0.0.1:4506 ''' port = int(port) remotes = set() try: cmd = salt.utils.args.shlex_split('sockstat -4 -c -p {0}'.format(port)) data = subprocess.check_output(cmd) # pylint: disable=minimum-python-version except subprocess.CalledProcessError as ex: log.error('Failed "sockstat" with returncode = %s', ex.returncode) raise lines = salt.utils.stringutils.to_str(data).split('\n') for line in lines: chunks = line.split() if not chunks: continue # ['root', 'python2.7', '1456', '37', 'tcp4', # '127.0.0.1:4505-', '127.0.0.1:55703'] # print chunks if 'COMMAND' in chunks[1]: continue # ignore header if len(chunks) < 2: continue # sockstat -4 -c -p 4506 does this with high PIDs: # USER COMMAND PID FD PROTO LOCAL ADDRESS FOREIGN ADDRESS # salt-master python2.781106 35 tcp4 192.168.12.34:4506 192.168.12.45:60143 local = chunks[-2] remote = chunks[-1] lhost, lport = local.split(':') rhost, rport = remote.split(':') if which_end == 'local' and int(lport) != port: # ignore if local port not port continue if which_end == 'remote' and int(rport) != port: # ignore if remote port not port continue remotes.add(rhost) return remotes def _netbsd_remotes_on(port, which_end): ''' Returns set of ipv4 host addresses of remote established connections on local tcp port port. Parses output of shell 'sockstat' (NetBSD) to get connections $ sudo sockstat -4 -n USER COMMAND PID FD PROTO LOCAL ADDRESS FOREIGN ADDRESS root python2.7 1456 29 tcp *.4505 *.* root python2.7 1445 17 tcp *.4506 *.* root python2.7 1294 14 tcp 127.0.0.1.11813 127.0.0.1.4505 root python2.7 1294 41 tcp 127.0.0.1.61115 127.0.0.1.4506 $ sudo sockstat -4 -c -n -p 4506 USER COMMAND PID FD PROTO LOCAL ADDRESS FOREIGN ADDRESS root python2.7 1294 41 tcp 127.0.0.1.61115 127.0.0.1.4506 ''' port = int(port) remotes = set() try: cmd = salt.utils.args.shlex_split('sockstat -4 -c -n -p {0}'.format(port)) data = subprocess.check_output(cmd) # pylint: disable=minimum-python-version except subprocess.CalledProcessError as ex: log.error('Failed "sockstat" with returncode = %s', ex.returncode) raise lines = salt.utils.stringutils.to_str(data).split('\n') for line in lines: chunks = line.split() if not chunks: continue # ['root', 'python2.7', '1456', '37', 'tcp', # '127.0.0.1.4505-', '127.0.0.1.55703'] # print chunks if 'COMMAND' in chunks[1]: continue # ignore header if len(chunks) < 2: continue local = chunks[5].split('.') lport = local.pop() lhost = '.'.join(local) remote = chunks[6].split('.') rport = remote.pop() rhost = '.'.join(remote) if which_end == 'local' and int(lport) != port: # ignore if local port not port continue if which_end == 'remote' and int(rport) != port: # ignore if remote port not port continue remotes.add(rhost) return remotes def _openbsd_remotes_on(port, which_end): ''' OpenBSD specific helper function. Returns set of ipv4 host addresses of remote established connections on local or remote tcp port. Parses output of shell 'netstat' to get connections $ netstat -nf inet Active Internet connections Proto Recv-Q Send-Q Local Address Foreign Address (state) tcp 0 0 10.0.0.101.4505 10.0.0.1.45329 ESTABLISHED tcp 0 0 10.0.0.101.4505 10.0.0.100.50798 ESTABLISHED ''' remotes = set() try: data = subprocess.check_output(['netstat', '-nf', 'inet']) # pylint: disable=minimum-python-version except subprocess.CalledProcessError: log.error('Failed netstat') raise lines = data.split('\n') for line in lines: if 'ESTABLISHED' not in line: continue chunks = line.split() local_host, local_port = chunks[3].rsplit('.', 1) remote_host, remote_port = chunks[4].rsplit('.', 1) if which_end == 'remote_port' and int(remote_port) != port: continue if which_end == 'local_port' and int(local_port) != port: continue remotes.add(remote_host) return remotes def _windows_remotes_on(port, which_end): r''' Windows specific helper function. Returns set of ipv4 host addresses of remote established connections on local or remote tcp port. Parses output of shell 'netstat' to get connections C:\>netstat -n Active Connections Proto Local Address Foreign Address State TCP 10.2.33.17:3007 130.164.12.233:10123 ESTABLISHED TCP 10.2.33.17:3389 130.164.30.5:10378 ESTABLISHED ''' remotes = set() try: data = subprocess.check_output(['netstat', '-n']) # pylint: disable=minimum-python-version except subprocess.CalledProcessError: log.error('Failed netstat') raise lines = salt.utils.stringutils.to_str(data).split('\n') for line in lines: if 'ESTABLISHED' not in line: continue chunks = line.split() local_host, local_port = chunks[1].rsplit(':', 1) remote_host, remote_port = chunks[2].rsplit(':', 1) if which_end == 'remote_port' and int(remote_port) != port: continue if which_end == 'local_port' and int(local_port) != port: continue remotes.add(remote_host) return remotes def _linux_remotes_on(port, which_end): ''' Linux specific helper function. Returns set of ip host addresses of remote established connections on local tcp port port. Parses output of shell 'lsof' to get connections $ sudo lsof -iTCP:4505 -n COMMAND PID USER FD TYPE DEVICE SIZE/OFF NODE NAME Python 9971 root 35u IPv4 0x18a8464a29ca329d 0t0 TCP *:4505 (LISTEN) Python 9971 root 37u IPv4 0x18a8464a29b2b29d 0t0 TCP 127.0.0.1:4505->127.0.0.1:55703 (ESTABLISHED) Python 10152 root 22u IPv4 0x18a8464a29c8cab5 0t0 TCP 127.0.0.1:55703->127.0.0.1:4505 (ESTABLISHED) Python 10153 root 22u IPv4 0x18a8464a29c8cab5 0t0 TCP [fe80::249a]:4505->[fe80::150]:59367 (ESTABLISHED) ''' remotes = set() try: data = subprocess.check_output( ['lsof', '-iTCP:{0:d}'.format(port), '-n', '-P'] # pylint: disable=minimum-python-version ) except subprocess.CalledProcessError as ex: if ex.returncode == 1: # Lsof return 1 if any error was detected, including the failure # to locate Internet addresses, and it is not an error in this case. log.warning('"lsof" returncode = 1, likely no active TCP sessions.') return remotes log.error('Failed "lsof" with returncode = %s', ex.returncode) raise lines = salt.utils.stringutils.to_str(data).split('\n') for line in lines: chunks = line.split() if not chunks: continue # ['Python', '9971', 'root', '37u', 'IPv4', '0x18a8464a29b2b29d', '0t0', # 'TCP', '127.0.0.1:4505->127.0.0.1:55703', '(ESTABLISHED)'] # print chunks if 'COMMAND' in chunks[0]: continue # ignore header if 'ESTABLISHED' not in chunks[-1]: continue # ignore if not ESTABLISHED # '127.0.0.1:4505->127.0.0.1:55703' local, remote = chunks[8].split('->') _, lport = local.rsplit(':', 1) rhost, rport = remote.rsplit(':', 1) if which_end == 'remote_port' and int(rport) != port: continue if which_end == 'local_port' and int(lport) != port: continue remotes.add(rhost.strip("[]")) return remotes def _aix_remotes_on(port, which_end): ''' AIX specific helper function. Returns set of ipv4 host addresses of remote established connections on local or remote tcp port. Parses output of shell 'netstat' to get connections root@la68pp002_pub:/opt/salt/lib/python2.7/site-packages/salt/modules# netstat -f inet -n Active Internet connections Proto Recv-Q Send-Q Local Address Foreign Address (state) tcp4 0 0 172.29.149.95.50093 209.41.78.13.4505 ESTABLISHED tcp4 0 0 127.0.0.1.9514 *.* LISTEN tcp4 0 0 127.0.0.1.9515 *.* LISTEN tcp4 0 0 127.0.0.1.199 127.0.0.1.32779 ESTABLISHED tcp4 0 0 127.0.0.1.32779 127.0.0.1.199 ESTABLISHED tcp4 0 40 172.29.149.95.22 172.29.96.83.41022 ESTABLISHED tcp4 0 0 172.29.149.95.22 172.29.96.83.41032 ESTABLISHED tcp4 0 0 127.0.0.1.32771 127.0.0.1.32775 ESTABLISHED tcp 0 0 127.0.0.1.32775 127.0.0.1.32771 ESTABLISHED tcp4 0 0 127.0.0.1.32771 127.0.0.1.32776 ESTABLISHED tcp 0 0 127.0.0.1.32776 127.0.0.1.32771 ESTABLISHED tcp4 0 0 127.0.0.1.32771 127.0.0.1.32777 ESTABLISHED tcp 0 0 127.0.0.1.32777 127.0.0.1.32771 ESTABLISHED tcp4 0 0 127.0.0.1.32771 127.0.0.1.32778 ESTABLISHED tcp 0 0 127.0.0.1.32778 127.0.0.1.32771 ESTABLISHED ''' remotes = set() try: data = subprocess.check_output(['netstat', '-f', 'inet', '-n']) # pylint: disable=minimum-python-version except subprocess.CalledProcessError: log.error('Failed netstat') raise lines = salt.utils.stringutils.to_str(data).split('\n') for line in lines: if 'ESTABLISHED' not in line: continue chunks = line.split() local_host, local_port = chunks[3].rsplit('.', 1) remote_host, remote_port = chunks[4].rsplit('.', 1) if which_end == 'remote_port' and int(remote_port) != port: continue if which_end == 'local_port' and int(local_port) != port: continue remotes.add(remote_host) return remotes @jinja_filter('gen_mac') def gen_mac(prefix='AC:DE:48'): ''' Generates a MAC address with the defined OUI prefix. Common prefixes: - ``00:16:3E`` -- Xen - ``00:18:51`` -- OpenVZ - ``00:50:56`` -- VMware (manually generated) - ``52:54:00`` -- QEMU/KVM - ``AC:DE:48`` -- PRIVATE References: - http://standards.ieee.org/develop/regauth/oui/oui.txt - https://www.wireshark.org/tools/oui-lookup.html - https://en.wikipedia.org/wiki/MAC_address ''' return '{0}:{1:02X}:{2:02X}:{3:02X}'.format(prefix, random.randint(0, 0xff), random.randint(0, 0xff), random.randint(0, 0xff)) @jinja_filter('mac_str_to_bytes') def mac_str_to_bytes(mac_str): ''' Convert a MAC address string into bytes. Works with or without separators: b1 = mac_str_to_bytes('08:00:27:13:69:77') b2 = mac_str_to_bytes('080027136977') assert b1 == b2 assert isinstance(b1, bytes) ''' if len(mac_str) == 12: pass elif len(mac_str) == 17: sep = mac_str[2] mac_str = mac_str.replace(sep, '') else: raise ValueError('Invalid MAC address') chars = (int(mac_str[s:s+2], 16) for s in range(0, 12, 2)) return bytes(chars) if six.PY3 else b''.join(chr(x) for x in chars) def refresh_dns(): ''' issue #21397: force glibc to re-read resolv.conf ''' try: res_init() except NameError: # Exception raised loading the library, thus res_init is not defined pass @jinja_filter('connection_check') def connection_check(addr, port=80, safe=False, ipv6=None): ''' Provides a convenient alias for the dns_check filter. ''' return dns_check(addr, port, safe, ipv6) @jinja_filter('dns_check') def dns_check(addr, port=80, safe=False, ipv6=None, attempt_connect=True): ''' Return the ip resolved by dns, but do not exit on failure, only raise an exception. Obeys system preference for IPv4/6 address resolution - this can be overridden by the ipv6 flag. Tries to connect to the address before considering it useful. If no address can be reached, the first one resolved is used as a fallback. ''' error = False lookup = addr seen_ipv6 = False family = socket.AF_INET6 if ipv6 else socket.AF_INET if ipv6 is False else socket.AF_UNSPEC hostnames = [] try: refresh_dns() hostnames = socket.getaddrinfo(addr, port, family, socket.SOCK_STREAM) except TypeError: err = ('Attempt to resolve address \'{0}\' failed. Invalid or unresolveable address').format(lookup) raise SaltSystemExit(code=42, msg=err) except socket.error: error = True # If ipv6 is set to True, attempt another lookup using the IPv4 family, # just in case we're attempting to lookup an IPv4 IP # as an IPv6 hostname. if error and ipv6: try: refresh_dns() hostnames = socket.getaddrinfo(addr, port, socket.AF_INET, socket.SOCK_STREAM) except TypeError: err = ('Attempt to resolve address \'{0}\' failed. Invalid or unresolveable address').format(lookup) raise SaltSystemExit(code=42, msg=err) except socket.error: error = True try: if not hostnames: error = True else: resolved = False candidates = [] for h in hostnames: # Input is IP address, passed through unchanged, just return it if h[4][0] == addr: resolved = salt.utils.zeromq.ip_bracket(addr) break candidate_addr = salt.utils.zeromq.ip_bracket(h[4][0]) # sometimes /etc/hosts contains ::1 localhost if not ipv6 and candidate_addr == '[::1]': continue candidates.append(candidate_addr) if attempt_connect: try: s = socket.socket(h[0], socket.SOCK_STREAM) s.settimeout(2) s.connect((candidate_addr.strip('[]'), h[4][1])) s.close() resolved = candidate_addr break except socket.error: pass if not resolved: if candidates: resolved = candidates[0] else: error = True except TypeError: err = ('Attempt to resolve address \'{0}\' failed. Invalid or unresolveable address').format(lookup) raise SaltSystemExit(code=42, msg=err) except socket.error: error = True if error: err = ('DNS lookup or connection check of \'{0}\' failed.').format(addr) if safe: if salt.log.is_console_configured(): # If logging is not configured it also means that either # the master or minion instance calling this hasn't even # started running log.error(err) raise SaltClientError() raise SaltSystemExit(code=42, msg=err) return resolved def parse_host_port(host_port): """ Takes a string argument specifying host or host:port. Returns a (hostname, port) or (ip_address, port) tuple. If no port is given, the second (port) element of the returned tuple will be None. host:port argument, for example, is accepted in the forms of: - hostname - hostname:1234 - hostname.domain.tld - hostname.domain.tld:5678 - [1234::5]:5678 - 1234::5 - 10.11.12.13:4567 - 10.11.12.13 """ host, port = None, None # default _s_ = host_port[:] if _s_[0] == "[": if "]" in host_port: host, _s_ = _s_.lstrip("[").rsplit("]", 1) host = ipaddress.IPv6Address(host).compressed if _s_[0] == ":": port = int(_s_.lstrip(":")) else: if len(_s_) > 1: raise ValueError('found ambiguous "{}" port in "{}"'.format(_s_, host_port)) else: if _s_.count(":") == 1: host, _hostport_separator_, port = _s_.partition(":") try: port = int(port) except ValueError as _e_: log.error('host_port "%s" port value "%s" is not an integer.', host_port, port) raise _e_ else: host = _s_ try: if not isinstance(host, ipaddress._BaseAddress): host_ip = ipaddress.ip_address(host).compressed host = host_ip except ValueError: log.debug('"%s" Not an IP address? Assuming it is a hostname.', host) if host != sanitize_host(host): log.error('bad hostname: "%s"', host) raise ValueError('bad hostname: "{}"'.format(host)) return host, port def is_fqdn(hostname): """ Verify if hostname conforms to be a FQDN. :param hostname: text string with the name of the host :return: bool, True if hostname is correct FQDN, False otherwise """ compliant = re.compile(r"(?!-)[A-Z\d\-\_]{1,63}(?<!-)$", re.IGNORECASE) return "." in hostname and len(hostname) < 0xff and all(compliant.match(x) for x in hostname.rstrip(".").split("."))
saltstack/salt
salt/utils/network.py
_remotes_on
python
def _remotes_on(port, which_end): ''' Return a set of ip addrs active tcp connections ''' port = int(port) ret = _netlink_tool_remote_on(port, which_end) if ret is not None: return ret ret = set() proc_available = False for statf in ['/proc/net/tcp', '/proc/net/tcp6']: if os.path.isfile(statf): proc_available = True with salt.utils.files.fopen(statf, 'r') as fp_: for line in fp_: line = salt.utils.stringutils.to_unicode(line) if line.strip().startswith('sl'): continue iret = _parse_tcp_line(line) sl = next(iter(iret)) if iret[sl][which_end] == port and iret[sl]['state'] == 1: # 1 is ESTABLISHED ret.add(iret[sl]['remote_addr']) if not proc_available: # Fallback to use OS specific tools if salt.utils.platform.is_sunos(): return _sunos_remotes_on(port, which_end) if salt.utils.platform.is_freebsd(): return _freebsd_remotes_on(port, which_end) if salt.utils.platform.is_netbsd(): return _netbsd_remotes_on(port, which_end) if salt.utils.platform.is_openbsd(): return _openbsd_remotes_on(port, which_end) if salt.utils.platform.is_windows(): return _windows_remotes_on(port, which_end) if salt.utils.platform.is_aix(): return _aix_remotes_on(port, which_end) return _linux_remotes_on(port, which_end) return ret
Return a set of ip addrs active tcp connections
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/network.py#L1400-L1441
[ "def fopen(*args, **kwargs):\n '''\n Wrapper around open() built-in to set CLOEXEC on the fd.\n\n This flag specifies that the file descriptor should be closed when an exec\n function is invoked;\n\n When a file descriptor is allocated (as with open or dup), this bit is\n initially cleared on the new file descriptor, meaning that descriptor will\n survive into the new program after exec.\n\n NB! We still have small race condition between open and fcntl.\n '''\n if six.PY3:\n try:\n # Don't permit stdin/stdout/stderr to be opened. The boolean False\n # and True are treated by Python 3's open() as file descriptors 0\n # and 1, respectively.\n if args[0] in (0, 1, 2):\n raise TypeError(\n '{0} is not a permitted file descriptor'.format(args[0])\n )\n except IndexError:\n pass\n binary = None\n # ensure 'binary' mode is always used on Windows in Python 2\n if ((six.PY2 and salt.utils.platform.is_windows() and 'binary' not in kwargs) or\n kwargs.pop('binary', False)):\n if len(args) > 1:\n args = list(args)\n if 'b' not in args[1]:\n args[1] = args[1].replace('t', 'b')\n if 'b' not in args[1]:\n args[1] += 'b'\n elif kwargs.get('mode'):\n if 'b' not in kwargs['mode']:\n kwargs['mode'] = kwargs['mode'].replace('t', 'b')\n if 'b' not in kwargs['mode']:\n kwargs['mode'] += 'b'\n else:\n # the default is to read\n kwargs['mode'] = 'rb'\n elif six.PY3 and 'encoding' not in kwargs:\n # In Python 3, if text mode is used and the encoding\n # is not specified, set the encoding to 'utf-8'.\n binary = False\n if len(args) > 1:\n args = list(args)\n if 'b' in args[1]:\n binary = True\n if kwargs.get('mode', None):\n if 'b' in kwargs['mode']:\n binary = True\n if not binary:\n kwargs['encoding'] = __salt_system_encoding__\n\n if six.PY3 and not binary and not kwargs.get('newline', None):\n kwargs['newline'] = ''\n\n f_handle = open(*args, **kwargs) # pylint: disable=resource-leakage\n\n if is_fcntl_available():\n # modify the file descriptor on systems with fcntl\n # unix and unix-like systems only\n try:\n FD_CLOEXEC = fcntl.FD_CLOEXEC # pylint: disable=C0103\n except AttributeError:\n FD_CLOEXEC = 1 # pylint: disable=C0103\n old_flags = fcntl.fcntl(f_handle.fileno(), fcntl.F_GETFD)\n fcntl.fcntl(f_handle.fileno(), fcntl.F_SETFD, old_flags | FD_CLOEXEC)\n\n return f_handle\n", "def to_unicode(s, encoding=None, errors='strict', normalize=False):\n '''\n Given str or unicode, return unicode (str for python 3)\n '''\n def _normalize(s):\n return unicodedata.normalize('NFC', s) if normalize else s\n\n if encoding is None:\n # Try utf-8 first, and fall back to detected encoding\n encoding = ('utf-8', __salt_system_encoding__)\n if not isinstance(encoding, (tuple, list)):\n encoding = (encoding,)\n\n if not encoding:\n raise ValueError('encoding cannot be empty')\n\n exc = None\n if six.PY3:\n if isinstance(s, str):\n return _normalize(s)\n elif isinstance(s, (bytes, bytearray)):\n return _normalize(to_str(s, encoding, errors))\n raise TypeError('expected str, bytes, or bytearray')\n else:\n # This needs to be str and not six.string_types, since if the string is\n # already a unicode type, it does not need to be decoded (and doing so\n # will raise an exception).\n if isinstance(s, unicode): # pylint: disable=incompatible-py3-code,undefined-variable\n return _normalize(s)\n elif isinstance(s, (str, bytearray)):\n for enc in encoding:\n try:\n return _normalize(s.decode(enc, errors))\n except UnicodeDecodeError as err:\n exc = err\n continue\n # The only way we get this far is if a UnicodeDecodeError was\n # raised, otherwise we would have already returned (or raised some\n # other exception).\n raise exc # pylint: disable=raising-bad-type\n raise TypeError('expected str or bytearray')\n", "def _parse_tcp_line(line):\n '''\n Parse a single line from the contents of /proc/net/tcp or /proc/net/tcp6\n '''\n ret = {}\n comps = line.strip().split()\n sl = comps[0].rstrip(':')\n ret[sl] = {}\n l_addr, l_port = comps[1].split(':')\n r_addr, r_port = comps[2].split(':')\n ret[sl]['local_addr'] = hex2ip(l_addr, True)\n ret[sl]['local_port'] = int(l_port, 16)\n ret[sl]['remote_addr'] = hex2ip(r_addr, True)\n ret[sl]['remote_port'] = int(r_port, 16)\n ret[sl]['state'] = int(comps[3], 16)\n return ret\n", "def _netlink_tool_remote_on(port, which_end):\n '''\n Returns set of ipv4 host addresses of remote established connections\n on local or remote tcp port.\n\n Parses output of shell 'ss' to get connections\n\n [root@salt-master ~]# ss -ant\n State Recv-Q Send-Q Local Address:Port Peer Address:Port\n LISTEN 0 511 *:80 *:*\n LISTEN 0 128 *:22 *:*\n ESTAB 0 0 127.0.0.1:56726 127.0.0.1:4505\n '''\n remotes = set()\n valid = False\n try:\n data = subprocess.check_output(['ss', '-ant']) # pylint: disable=minimum-python-version\n except subprocess.CalledProcessError:\n log.error('Failed ss')\n raise\n except OSError: # not command \"No such file or directory\"\n return None\n\n lines = salt.utils.stringutils.to_str(data).split('\\n')\n for line in lines:\n if 'Address:Port' in line: # ss tools may not be valid\n valid = True\n continue\n elif 'ESTAB' not in line:\n continue\n chunks = line.split()\n local_host, local_port = chunks[3].split(':', 1)\n remote_host, remote_port = chunks[4].split(':', 1)\n\n if which_end == 'remote_port' and int(remote_port) != port:\n continue\n if which_end == 'local_port' and int(local_port) != port:\n continue\n remotes.add(remote_host)\n\n if valid is False:\n remotes = None\n return remotes\n", "def _sunos_remotes_on(port, which_end):\n '''\n SunOS specific helper function.\n Returns set of ipv4 host addresses of remote established connections\n on local or remote tcp port.\n\n Parses output of shell 'netstat' to get connections\n\n [root@salt-master ~]# netstat -f inet -n\n TCP: IPv4\n Local Address Remote Address Swind Send-Q Rwind Recv-Q State\n -------------------- -------------------- ----- ------ ----- ------ -----------\n 10.0.0.101.4505 10.0.0.1.45329 1064800 0 1055864 0 ESTABLISHED\n 10.0.0.101.4505 10.0.0.100.50798 1064800 0 1055864 0 ESTABLISHED\n '''\n remotes = set()\n try:\n data = subprocess.check_output(['netstat', '-f', 'inet', '-n']) # pylint: disable=minimum-python-version\n except subprocess.CalledProcessError:\n log.error('Failed netstat')\n raise\n\n lines = salt.utils.stringutils.to_str(data).split('\\n')\n for line in lines:\n if 'ESTABLISHED' not in line:\n continue\n chunks = line.split()\n local_host, local_port = chunks[0].rsplit('.', 1)\n remote_host, remote_port = chunks[1].rsplit('.', 1)\n\n if which_end == 'remote_port' and int(remote_port) != port:\n continue\n if which_end == 'local_port' and int(local_port) != port:\n continue\n remotes.add(remote_host)\n return remotes\n" ]
# -*- coding: utf-8 -*- ''' Define some generic socket functions for network modules ''' # Import python libs from __future__ import absolute_import, unicode_literals, print_function import itertools import os import re import types import socket import logging import platform import random import subprocess from string import ascii_letters, digits # Import 3rd-party libs from salt.ext import six from salt.ext.six.moves import range # pylint: disable=import-error,redefined-builtin # Attempt to import wmi try: import wmi import salt.utils.winapi except ImportError: pass # Import salt libs import salt.utils.args import salt.utils.files import salt.utils.path import salt.utils.platform import salt.utils.stringutils import salt.utils.zeromq from salt._compat import ipaddress from salt.exceptions import SaltClientError, SaltSystemExit from salt.utils.decorators.jinja import jinja_filter from salt.utils.versions import LooseVersion # inet_pton does not exist in Windows, this is a workaround if salt.utils.platform.is_windows(): from salt.ext import win_inet_pton # pylint: disable=unused-import log = logging.getLogger(__name__) try: import ctypes import ctypes.util libc = ctypes.cdll.LoadLibrary(ctypes.util.find_library("c")) res_init = libc.__res_init except (ImportError, OSError, AttributeError, TypeError): pass # pylint: disable=C0103 def sanitize_host(host): ''' Sanitize host string. https://tools.ietf.org/html/rfc1123#section-2.1 ''' RFC952_characters = ascii_letters + digits + ".-" return "".join([c for c in host[0:255] if c in RFC952_characters]) def isportopen(host, port): ''' Return status of a port ''' if not 1 <= int(port) <= 65535: return False sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) out = sock.connect_ex((sanitize_host(host), int(port))) return out def host_to_ips(host): ''' Returns a list of IP addresses of a given hostname or None if not found. ''' ips = [] try: for family, socktype, proto, canonname, sockaddr in socket.getaddrinfo( host, 0, socket.AF_UNSPEC, socket.SOCK_STREAM): if family == socket.AF_INET: ip, port = sockaddr elif family == socket.AF_INET6: ip, port, flow_info, scope_id = sockaddr ips.append(ip) if not ips: ips = None except Exception: ips = None return ips def _generate_minion_id(): ''' Get list of possible host names and convention names. :return: ''' # There are three types of hostnames: # 1. Network names. How host is accessed from the network. # 2. Host aliases. They might be not available in all the network or only locally (/etc/hosts) # 3. Convention names, an internal nodename. class DistinctList(list): ''' List, which allows one to append only distinct objects. Needs to work on Python 2.6, because of collections.OrderedDict only since 2.7 version. Override 'filter()' for custom filtering. ''' localhost_matchers = [r'localhost.*', r'ip6-.*', r'127[.]\d', r'0\.0\.0\.0', r'::1.*', r'ipv6-.*', r'fe00::.*', r'fe02::.*', r'1.0.0.*.ip6.arpa'] def append(self, p_object): if p_object and p_object not in self and not self.filter(p_object): super(DistinctList, self).append(p_object) return self def extend(self, iterable): for obj in iterable: self.append(obj) return self def filter(self, element): 'Returns True if element needs to be filtered' for rgx in self.localhost_matchers: if re.match(rgx, element): return True def first(self): return self and self[0] or None hostname = socket.gethostname() hosts = DistinctList().append( salt.utils.stringutils.to_unicode(socket.getfqdn(salt.utils.stringutils.to_bytes(hostname))) ).append(platform.node()).append(hostname) if not hosts: try: for a_nfo in socket.getaddrinfo(hosts.first() or 'localhost', None, socket.AF_INET, socket.SOCK_RAW, socket.IPPROTO_IP, socket.AI_CANONNAME): if len(a_nfo) > 3: hosts.append(a_nfo[3]) except socket.gaierror: log.warning('Cannot resolve address %s info via socket: %s', hosts.first() or 'localhost (N/A)', socket.gaierror) # Universal method for everywhere (Linux, Slowlaris, Windows etc) for f_name in ('/etc/hostname', '/etc/nodename', '/etc/hosts', r'{win}\system32\drivers\etc\hosts'.format(win=os.getenv('WINDIR'))): try: with salt.utils.files.fopen(f_name) as f_hdl: for line in f_hdl: line = salt.utils.stringutils.to_unicode(line) hst = line.strip().split('#')[0].strip().split() if hst: if hst[0][:4] in ('127.', '::1') or len(hst) == 1: hosts.extend(hst) except IOError: pass # include public and private ipaddresses return hosts.extend([addr for addr in ip_addrs() if not ipaddress.ip_address(addr).is_loopback]) def generate_minion_id(): ''' Return only first element of the hostname from all possible list. :return: ''' try: ret = salt.utils.stringutils.to_unicode(_generate_minion_id().first()) except TypeError: ret = None return ret or 'localhost' def get_socket(addr, type=socket.SOCK_STREAM, proto=0): ''' Return a socket object for the addr IP-version agnostic ''' version = ipaddress.ip_address(addr).version if version == 4: family = socket.AF_INET elif version == 6: family = socket.AF_INET6 return socket.socket(family, type, proto) def get_fqhostname(): ''' Returns the fully qualified hostname ''' # try getaddrinfo() fqdn = None try: addrinfo = socket.getaddrinfo( socket.gethostname(), 0, socket.AF_UNSPEC, socket.SOCK_STREAM, socket.SOL_TCP, socket.AI_CANONNAME ) for info in addrinfo: # info struct [family, socktype, proto, canonname, sockaddr] # On Windows `canonname` can be an empty string # This can cause the function to return `None` if len(info) > 3 and info[3]: fqdn = info[3] break except socket.gaierror: pass # NOTE: this used to log.error() but it was later disabled except socket.error as err: log.debug('socket.getaddrinfo() failure while finding fqdn: %s', err) if fqdn is None: fqdn = socket.getfqdn() return fqdn def ip_to_host(ip): ''' Returns the hostname of a given IP ''' try: hostname, aliaslist, ipaddrlist = socket.gethostbyaddr(ip) except Exception as exc: log.debug('salt.utils.network.ip_to_host(%r) failed: %s', ip, exc) hostname = None return hostname # pylint: enable=C0103 def is_reachable_host(entity_name): ''' Returns a bool telling if the entity name is a reachable host (IPv4/IPv6/FQDN/etc). :param hostname: :return: ''' try: assert type(socket.getaddrinfo(entity_name, 0, 0, 0, 0)) == list ret = True except socket.gaierror: ret = False return ret def is_ip(ip): ''' Returns a bool telling if the passed IP is a valid IPv4 or IPv6 address. ''' return is_ipv4(ip) or is_ipv6(ip) def is_ipv4(ip): ''' Returns a bool telling if the value passed to it was a valid IPv4 address ''' try: return ipaddress.ip_address(ip).version == 4 except ValueError: return False def is_ipv6(ip): ''' Returns a bool telling if the value passed to it was a valid IPv6 address ''' try: return ipaddress.ip_address(ip).version == 6 except ValueError: return False def is_subnet(cidr): ''' Returns a bool telling if the passed string is an IPv4 or IPv6 subnet ''' return is_ipv4_subnet(cidr) or is_ipv6_subnet(cidr) def is_ipv4_subnet(cidr): ''' Returns a bool telling if the passed string is an IPv4 subnet ''' try: return '/' in cidr and bool(ipaddress.IPv4Network(cidr)) except Exception: return False def is_ipv6_subnet(cidr): ''' Returns a bool telling if the passed string is an IPv6 subnet ''' try: return '/' in cidr and bool(ipaddress.IPv6Network(cidr)) except Exception: return False @jinja_filter('is_ip') def is_ip_filter(ip, options=None): ''' Returns a bool telling if the passed IP is a valid IPv4 or IPv6 address. ''' return is_ipv4_filter(ip, options=options) or is_ipv6_filter(ip, options=options) def _ip_options_global(ip_obj, version): return not ip_obj.is_private def _ip_options_multicast(ip_obj, version): return ip_obj.is_multicast def _ip_options_loopback(ip_obj, version): return ip_obj.is_loopback def _ip_options_link_local(ip_obj, version): return ip_obj.is_link_local def _ip_options_private(ip_obj, version): return ip_obj.is_private def _ip_options_reserved(ip_obj, version): return ip_obj.is_reserved def _ip_options_site_local(ip_obj, version): if version == 6: return ip_obj.is_site_local return False def _ip_options_unspecified(ip_obj, version): return ip_obj.is_unspecified def _ip_options(ip_obj, version, options=None): # will process and IP options options_fun_map = { 'global': _ip_options_global, 'link-local': _ip_options_link_local, 'linklocal': _ip_options_link_local, 'll': _ip_options_link_local, 'link_local': _ip_options_link_local, 'loopback': _ip_options_loopback, 'lo': _ip_options_loopback, 'multicast': _ip_options_multicast, 'private': _ip_options_private, 'public': _ip_options_global, 'reserved': _ip_options_reserved, 'site-local': _ip_options_site_local, 'sl': _ip_options_site_local, 'site_local': _ip_options_site_local, 'unspecified': _ip_options_unspecified } if not options: return six.text_type(ip_obj) # IP version already checked options_list = [option.strip() for option in options.split(',')] for option, fun in options_fun_map.items(): if option in options_list: fun_res = fun(ip_obj, version) if not fun_res: return None # stop at first failed test # else continue return six.text_type(ip_obj) def _is_ipv(ip, version, options=None): if not version: version = 4 if version not in (4, 6): return None try: ip_obj = ipaddress.ip_address(ip) except ValueError: # maybe it is an IP network try: ip_obj = ipaddress.ip_interface(ip) except ValueError: # nope, still not :( return None if not ip_obj.version == version: return None # has the right version, let's move on return _ip_options(ip_obj, version, options=options) @jinja_filter('is_ipv4') def is_ipv4_filter(ip, options=None): ''' Returns a bool telling if the value passed to it was a valid IPv4 address. ip The IP address. net: False Consider IP addresses followed by netmask. options CSV of options regarding the nature of the IP address. E.g.: loopback, multicast, private etc. ''' _is_ipv4 = _is_ipv(ip, 4, options=options) return isinstance(_is_ipv4, six.string_types) @jinja_filter('is_ipv6') def is_ipv6_filter(ip, options=None): ''' Returns a bool telling if the value passed to it was a valid IPv6 address. ip The IP address. net: False Consider IP addresses followed by netmask. options CSV of options regarding the nature of the IP address. E.g.: loopback, multicast, private etc. ''' _is_ipv6 = _is_ipv(ip, 6, options=options) return isinstance(_is_ipv6, six.string_types) def _ipv_filter(value, version, options=None): if version not in (4, 6): return if isinstance(value, (six.string_types, six.text_type, six.binary_type)): return _is_ipv(value, version, options=options) # calls is_ipv4 or is_ipv6 for `value` elif isinstance(value, (list, tuple, types.GeneratorType)): # calls is_ipv4 or is_ipv6 for each element in the list # os it filters and returns only those elements having the desired IP version return [ _is_ipv(addr, version, options=options) for addr in value if _is_ipv(addr, version, options=options) is not None ] return None @jinja_filter('ipv4') def ipv4(value, options=None): ''' Filters a list and returns IPv4 values only. ''' return _ipv_filter(value, 4, options=options) @jinja_filter('ipv6') def ipv6(value, options=None): ''' Filters a list and returns IPv6 values only. ''' return _ipv_filter(value, 6, options=options) @jinja_filter('ipaddr') def ipaddr(value, options=None): ''' Filters and returns only valid IP objects. ''' ipv4_obj = ipv4(value, options=options) ipv6_obj = ipv6(value, options=options) if ipv4_obj is None or ipv6_obj is None: # an IP address can be either IPv4 either IPv6 # therefofe if the value passed as arg is not a list, at least one of the calls above will return None # if one of them is none, means that we should return only one of them return ipv4_obj or ipv6_obj # one of them else: return ipv4_obj + ipv6_obj # extend lists def _filter_ipaddr(value, options, version=None): ipaddr_filter_out = None if version: if version == 4: ipaddr_filter_out = ipv4(value, options) elif version == 6: ipaddr_filter_out = ipv6(value, options) else: ipaddr_filter_out = ipaddr(value, options) if not ipaddr_filter_out: return if not isinstance(ipaddr_filter_out, (list, tuple, types.GeneratorType)): ipaddr_filter_out = [ipaddr_filter_out] return ipaddr_filter_out @jinja_filter('ip_host') def ip_host(value, options=None, version=None): ''' Returns the interfaces IP address, e.g.: 192.168.0.1/28. ''' ipaddr_filter_out = _filter_ipaddr(value, options=options, version=version) if not ipaddr_filter_out: return if not isinstance(value, (list, tuple, types.GeneratorType)): return six.text_type(ipaddress.ip_interface(ipaddr_filter_out[0])) return [six.text_type(ipaddress.ip_interface(ip_a)) for ip_a in ipaddr_filter_out] def _network_hosts(ip_addr_entry): return [ six.text_type(host) for host in ipaddress.ip_network(ip_addr_entry, strict=False).hosts() ] @jinja_filter('network_hosts') def network_hosts(value, options=None, version=None): ''' Return the list of hosts within a network. .. note:: When running this command with a large IPv6 network, the command will take a long time to gather all of the hosts. ''' ipaddr_filter_out = _filter_ipaddr(value, options=options, version=version) if not ipaddr_filter_out: return if not isinstance(value, (list, tuple, types.GeneratorType)): return _network_hosts(ipaddr_filter_out[0]) return [ _network_hosts(ip_a) for ip_a in ipaddr_filter_out ] def _network_size(ip_addr_entry): return ipaddress.ip_network(ip_addr_entry, strict=False).num_addresses @jinja_filter('network_size') def network_size(value, options=None, version=None): ''' Get the size of a network. ''' ipaddr_filter_out = _filter_ipaddr(value, options=options, version=version) if not ipaddr_filter_out: return if not isinstance(value, (list, tuple, types.GeneratorType)): return _network_size(ipaddr_filter_out[0]) return [ _network_size(ip_a) for ip_a in ipaddr_filter_out ] def natural_ipv4_netmask(ip, fmt='prefixlen'): ''' Returns the "natural" mask of an IPv4 address ''' bits = _ipv4_to_bits(ip) if bits.startswith('11'): mask = '24' elif bits.startswith('1'): mask = '16' else: mask = '8' if fmt == 'netmask': return cidr_to_ipv4_netmask(mask) else: return '/' + mask def rpad_ipv4_network(ip): ''' Returns an IP network address padded with zeros. Ex: '192.168.3' -> '192.168.3.0' '10.209' -> '10.209.0.0' ''' return '.'.join(itertools.islice(itertools.chain(ip.split('.'), '0000'), 0, 4)) def cidr_to_ipv4_netmask(cidr_bits): ''' Returns an IPv4 netmask ''' try: cidr_bits = int(cidr_bits) if not 1 <= cidr_bits <= 32: return '' except ValueError: return '' netmask = '' for idx in range(4): if idx: netmask += '.' if cidr_bits >= 8: netmask += '255' cidr_bits -= 8 else: netmask += '{0:d}'.format(256 - (2 ** (8 - cidr_bits))) cidr_bits = 0 return netmask def _number_of_set_bits_to_ipv4_netmask(set_bits): # pylint: disable=C0103 ''' Returns an IPv4 netmask from the integer representation of that mask. Ex. 0xffffff00 -> '255.255.255.0' ''' return cidr_to_ipv4_netmask(_number_of_set_bits(set_bits)) # pylint: disable=C0103 def _number_of_set_bits(x): ''' Returns the number of bits that are set in a 32bit int ''' # Taken from http://stackoverflow.com/a/4912729. Many thanks! x -= (x >> 1) & 0x55555555 x = ((x >> 2) & 0x33333333) + (x & 0x33333333) x = ((x >> 4) + x) & 0x0f0f0f0f x += x >> 8 x += x >> 16 return x & 0x0000003f # pylint: enable=C0103 def _interfaces_ip(out): ''' Uses ip to return a dictionary of interfaces with various information about each (up/down state, ip address, netmask, and hwaddr) ''' ret = dict() def parse_network(value, cols): ''' Return a tuple of ip, netmask, broadcast based on the current set of cols ''' brd = None scope = None if '/' in value: # we have a CIDR in this address ip, cidr = value.split('/') # pylint: disable=C0103 else: ip = value # pylint: disable=C0103 cidr = 32 if type_ == 'inet': mask = cidr_to_ipv4_netmask(int(cidr)) if 'brd' in cols: brd = cols[cols.index('brd') + 1] elif type_ == 'inet6': mask = cidr if 'scope' in cols: scope = cols[cols.index('scope') + 1] return (ip, mask, brd, scope) groups = re.compile('\r?\n\\d').split(out) for group in groups: iface = None data = dict() for line in group.splitlines(): if ' ' not in line: continue match = re.match(r'^\d*:\s+([\w.\-]+)(?:@)?([\w.\-]+)?:\s+<(.+)>', line) if match: iface, parent, attrs = match.groups() if 'UP' in attrs.split(','): data['up'] = True else: data['up'] = False if parent: data['parent'] = parent continue cols = line.split() if len(cols) >= 2: type_, value = tuple(cols[0:2]) iflabel = cols[-1:][0] if type_ in ('inet', 'inet6'): if 'secondary' not in cols: ipaddr, netmask, broadcast, scope = parse_network(value, cols) if type_ == 'inet': if 'inet' not in data: data['inet'] = list() addr_obj = dict() addr_obj['address'] = ipaddr addr_obj['netmask'] = netmask addr_obj['broadcast'] = broadcast addr_obj['label'] = iflabel data['inet'].append(addr_obj) elif type_ == 'inet6': if 'inet6' not in data: data['inet6'] = list() addr_obj = dict() addr_obj['address'] = ipaddr addr_obj['prefixlen'] = netmask addr_obj['scope'] = scope data['inet6'].append(addr_obj) else: if 'secondary' not in data: data['secondary'] = list() ip_, mask, brd, scp = parse_network(value, cols) data['secondary'].append({ 'type': type_, 'address': ip_, 'netmask': mask, 'broadcast': brd, 'label': iflabel, }) del ip_, mask, brd, scp elif type_.startswith('link'): data['hwaddr'] = value if iface: ret[iface] = data del iface, data return ret def _interfaces_ifconfig(out): ''' Uses ifconfig to return a dictionary of interfaces with various information about each (up/down state, ip address, netmask, and hwaddr) ''' ret = dict() piface = re.compile(r'^([^\s:]+)') pmac = re.compile('.*?(?:HWaddr|ether|address:|lladdr) ([0-9a-fA-F:]+)') if salt.utils.platform.is_sunos(): pip = re.compile(r'.*?(?:inet\s+)([0-9]+\.[0-9]+\.[0-9]+\.[0-9]+)(.*)') pip6 = re.compile('.*?(?:inet6 )([0-9a-fA-F:]+)') pmask6 = re.compile(r'.*?(?:inet6 [0-9a-fA-F:]+/(\d+)).*') else: pip = re.compile(r'.*?(?:inet addr:|inet [^\d]*)(.*?)\s') pip6 = re.compile('.*?(?:inet6 addr: (.*?)/|inet6 )([0-9a-fA-F:]+)') pmask6 = re.compile(r'.*?(?:inet6 addr: [0-9a-fA-F:]+/(\d+)|prefixlen (\d+))(?: Scope:([a-zA-Z]+)| scopeid (0x[0-9a-fA-F]))?') pmask = re.compile(r'.*?(?:Mask:|netmask )(?:((?:0x)?[0-9a-fA-F]{8})|([\d\.]+))') pupdown = re.compile('UP') pbcast = re.compile(r'.*?(?:Bcast:|broadcast )([\d\.]+)') groups = re.compile('\r?\n(?=\\S)').split(out) for group in groups: data = dict() iface = '' updown = False for line in group.splitlines(): miface = piface.match(line) mmac = pmac.match(line) mip = pip.match(line) mip6 = pip6.match(line) mupdown = pupdown.search(line) if miface: iface = miface.group(1) if mmac: data['hwaddr'] = mmac.group(1) if salt.utils.platform.is_sunos(): expand_mac = [] for chunk in data['hwaddr'].split(':'): expand_mac.append('0{0}'.format(chunk) if len(chunk) < 2 else '{0}'.format(chunk)) data['hwaddr'] = ':'.join(expand_mac) if mip: if 'inet' not in data: data['inet'] = list() addr_obj = dict() addr_obj['address'] = mip.group(1) mmask = pmask.match(line) if mmask: if mmask.group(1): mmask = _number_of_set_bits_to_ipv4_netmask( int(mmask.group(1), 16)) else: mmask = mmask.group(2) addr_obj['netmask'] = mmask mbcast = pbcast.match(line) if mbcast: addr_obj['broadcast'] = mbcast.group(1) data['inet'].append(addr_obj) if mupdown: updown = True if mip6: if 'inet6' not in data: data['inet6'] = list() addr_obj = dict() addr_obj['address'] = mip6.group(1) or mip6.group(2) mmask6 = pmask6.match(line) if mmask6: addr_obj['prefixlen'] = mmask6.group(1) or mmask6.group(2) if not salt.utils.platform.is_sunos(): ipv6scope = mmask6.group(3) or mmask6.group(4) addr_obj['scope'] = ipv6scope.lower() if ipv6scope is not None else ipv6scope # SunOS sometimes has ::/0 as inet6 addr when using addrconf if not salt.utils.platform.is_sunos() \ or addr_obj['address'] != '::' \ and addr_obj['prefixlen'] != 0: data['inet6'].append(addr_obj) data['up'] = updown if iface in ret: # SunOS optimization, where interfaces occur twice in 'ifconfig -a' # output with the same name: for ipv4 and then for ipv6 addr family. # Every instance has it's own 'UP' status and we assume that ipv4 # status determines global interface status. # # merge items with higher priority for older values # after that merge the inet and inet6 sub items for both ret[iface] = dict(list(data.items()) + list(ret[iface].items())) if 'inet' in data: ret[iface]['inet'].extend(x for x in data['inet'] if x not in ret[iface]['inet']) if 'inet6' in data: ret[iface]['inet6'].extend(x for x in data['inet6'] if x not in ret[iface]['inet6']) else: ret[iface] = data del data return ret def linux_interfaces(): ''' Obtain interface information for *NIX/BSD variants ''' ifaces = dict() ip_path = salt.utils.path.which('ip') ifconfig_path = None if ip_path else salt.utils.path.which('ifconfig') if ip_path: cmd1 = subprocess.Popen( '{0} link show'.format(ip_path), shell=True, close_fds=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT).communicate()[0] cmd2 = subprocess.Popen( '{0} addr show'.format(ip_path), shell=True, close_fds=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT).communicate()[0] ifaces = _interfaces_ip("{0}\n{1}".format( salt.utils.stringutils.to_str(cmd1), salt.utils.stringutils.to_str(cmd2))) elif ifconfig_path: cmd = subprocess.Popen( '{0} -a'.format(ifconfig_path), shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT).communicate()[0] ifaces = _interfaces_ifconfig(salt.utils.stringutils.to_str(cmd)) return ifaces def _netbsd_interfaces_ifconfig(out): ''' Uses ifconfig to return a dictionary of interfaces with various information about each (up/down state, ip address, netmask, and hwaddr) ''' ret = dict() piface = re.compile(r'^([^\s:]+)') pmac = re.compile('.*?address: ([0-9a-f:]+)') pip = re.compile(r'.*?inet [^\d]*(.*?)/([\d]*)\s') pip6 = re.compile(r'.*?inet6 ([0-9a-f:]+)%([a-zA-Z0-9]*)/([\d]*)\s') pupdown = re.compile('UP') pbcast = re.compile(r'.*?broadcast ([\d\.]+)') groups = re.compile('\r?\n(?=\\S)').split(out) for group in groups: data = dict() iface = '' updown = False for line in group.splitlines(): miface = piface.match(line) mmac = pmac.match(line) mip = pip.match(line) mip6 = pip6.match(line) mupdown = pupdown.search(line) if miface: iface = miface.group(1) if mmac: data['hwaddr'] = mmac.group(1) if mip: if 'inet' not in data: data['inet'] = list() addr_obj = dict() addr_obj['address'] = mip.group(1) mmask = mip.group(2) if mip.group(2): addr_obj['netmask'] = cidr_to_ipv4_netmask(mip.group(2)) mbcast = pbcast.match(line) if mbcast: addr_obj['broadcast'] = mbcast.group(1) data['inet'].append(addr_obj) if mupdown: updown = True if mip6: if 'inet6' not in data: data['inet6'] = list() addr_obj = dict() addr_obj['address'] = mip6.group(1) mmask6 = mip6.group(3) addr_obj['scope'] = mip6.group(2) addr_obj['prefixlen'] = mip6.group(3) data['inet6'].append(addr_obj) data['up'] = updown ret[iface] = data del data return ret def netbsd_interfaces(): ''' Obtain interface information for NetBSD >= 8 where the ifconfig output diverged from other BSD variants (Netmask is now part of the address) ''' # NetBSD versions prior to 8.0 can still use linux_interfaces() if LooseVersion(os.uname()[2]) < LooseVersion('8.0'): return linux_interfaces() ifconfig_path = salt.utils.path.which('ifconfig') cmd = subprocess.Popen( '{0} -a'.format(ifconfig_path), shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT).communicate()[0] return _netbsd_interfaces_ifconfig(salt.utils.stringutils.to_str(cmd)) def _interfaces_ipconfig(out): ''' Returns a dictionary of interfaces with various information about each (up/down state, ip address, netmask, and hwaddr) NOTE: This is not used by any function and may be able to be removed in the future. ''' ifaces = dict() iface = None adapter_iface_regex = re.compile(r'adapter (\S.+):$') for line in out.splitlines(): if not line: continue # TODO what does Windows call Infiniband and 10/40gige adapters if line.startswith('Ethernet'): iface = ifaces[adapter_iface_regex.search(line).group(1)] iface['up'] = True addr = None continue if iface: key, val = line.split(',', 1) key = key.strip(' .') val = val.strip() if addr and key == 'Subnet Mask': addr['netmask'] = val elif key in ('IP Address', 'IPv4 Address'): if 'inet' not in iface: iface['inet'] = list() addr = {'address': val.rstrip('(Preferred)'), 'netmask': None, 'broadcast': None} # TODO find the broadcast iface['inet'].append(addr) elif 'IPv6 Address' in key: if 'inet6' not in iface: iface['inet'] = list() # XXX What is the prefixlen!? addr = {'address': val.rstrip('(Preferred)'), 'prefixlen': None} iface['inet6'].append(addr) elif key == 'Physical Address': iface['hwaddr'] = val elif key == 'Media State': # XXX seen used for tunnel adaptors # might be useful iface['up'] = (val != 'Media disconnected') def win_interfaces(): ''' Obtain interface information for Windows systems ''' with salt.utils.winapi.Com(): c = wmi.WMI() ifaces = {} for iface in c.Win32_NetworkAdapterConfiguration(IPEnabled=1): ifaces[iface.Description] = dict() if iface.MACAddress: ifaces[iface.Description]['hwaddr'] = iface.MACAddress if iface.IPEnabled: ifaces[iface.Description]['up'] = True for ip in iface.IPAddress: if '.' in ip: if 'inet' not in ifaces[iface.Description]: ifaces[iface.Description]['inet'] = [] item = {'address': ip, 'label': iface.Description} if iface.DefaultIPGateway: broadcast = next((i for i in iface.DefaultIPGateway if '.' in i), '') if broadcast: item['broadcast'] = broadcast if iface.IPSubnet: netmask = next((i for i in iface.IPSubnet if '.' in i), '') if netmask: item['netmask'] = netmask ifaces[iface.Description]['inet'].append(item) if ':' in ip: if 'inet6' not in ifaces[iface.Description]: ifaces[iface.Description]['inet6'] = [] item = {'address': ip} if iface.DefaultIPGateway: broadcast = next((i for i in iface.DefaultIPGateway if ':' in i), '') if broadcast: item['broadcast'] = broadcast if iface.IPSubnet: netmask = next((i for i in iface.IPSubnet if ':' in i), '') if netmask: item['netmask'] = netmask ifaces[iface.Description]['inet6'].append(item) else: ifaces[iface.Description]['up'] = False return ifaces def interfaces(): ''' Return a dictionary of information about all the interfaces on the minion ''' if salt.utils.platform.is_windows(): return win_interfaces() elif salt.utils.platform.is_netbsd(): return netbsd_interfaces() else: return linux_interfaces() def get_net_start(ipaddr, netmask): ''' Return the address of the network ''' net = ipaddress.ip_network('{0}/{1}'.format(ipaddr, netmask), strict=False) return six.text_type(net.network_address) def get_net_size(mask): ''' Turns an IPv4 netmask into it's corresponding prefix length (255.255.255.0 -> 24 as in 192.168.1.10/24). ''' binary_str = '' for octet in mask.split('.'): binary_str += bin(int(octet))[2:].zfill(8) return len(binary_str.rstrip('0')) def calc_net(ipaddr, netmask=None): ''' Takes IP (CIDR notation supported) and optionally netmask and returns the network in CIDR-notation. (The IP can be any IP inside the subnet) ''' if netmask is not None: ipaddr = '{0}/{1}'.format(ipaddr, netmask) return six.text_type(ipaddress.ip_network(ipaddr, strict=False)) def _ipv4_to_bits(ipaddr): ''' Accepts an IPv4 dotted quad and returns a string representing its binary counterpart ''' return ''.join([bin(int(x))[2:].rjust(8, '0') for x in ipaddr.split('.')]) def _get_iface_info(iface): ''' If `iface` is available, return interface info and no error, otherwise return no info and log and return an error ''' iface_info = interfaces() if iface in iface_info.keys(): return iface_info, False else: error_msg = ('Interface "{0}" not in available interfaces: "{1}"' ''.format(iface, '", "'.join(iface_info.keys()))) log.error(error_msg) return None, error_msg def _hw_addr_aix(iface): ''' Return the hardware address (a.k.a. MAC address) for a given interface on AIX MAC address not available in through interfaces ''' cmd = subprocess.Popen( 'entstat -d {0} | grep \'Hardware Address\''.format(iface), shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT).communicate()[0] if cmd: comps = cmd.split(' ') if len(comps) == 3: mac_addr = comps[2].strip('\'').strip() return mac_addr error_msg = ('Interface "{0}" either not available or does not contain a hardware address'.format(iface)) log.error(error_msg) return error_msg def hw_addr(iface): ''' Return the hardware address (a.k.a. MAC address) for a given interface .. versionchanged:: 2016.11.4 Added support for AIX ''' if salt.utils.platform.is_aix(): return _hw_addr_aix iface_info, error = _get_iface_info(iface) if error is False: return iface_info.get(iface, {}).get('hwaddr', '') else: return error def interface(iface): ''' Return the details of `iface` or an error if it does not exist ''' iface_info, error = _get_iface_info(iface) if error is False: return iface_info.get(iface, {}).get('inet', '') else: return error def interface_ip(iface): ''' Return `iface` IPv4 addr or an error if `iface` does not exist ''' iface_info, error = _get_iface_info(iface) if error is False: inet = iface_info.get(iface, {}).get('inet', None) return inet[0].get('address', '') if inet else '' else: return error def _subnets(proto='inet', interfaces_=None): ''' Returns a list of subnets to which the host belongs ''' if interfaces_ is None: ifaces = interfaces() elif isinstance(interfaces_, list): ifaces = {} for key, value in six.iteritems(interfaces()): if key in interfaces_: ifaces[key] = value else: ifaces = {interfaces_: interfaces().get(interfaces_, {})} ret = set() if proto == 'inet': subnet = 'netmask' dflt_cidr = 32 elif proto == 'inet6': subnet = 'prefixlen' dflt_cidr = 128 else: log.error('Invalid proto %s calling subnets()', proto) return for ip_info in six.itervalues(ifaces): addrs = ip_info.get(proto, []) addrs.extend([addr for addr in ip_info.get('secondary', []) if addr.get('type') == proto]) for intf in addrs: if subnet in intf: intf = ipaddress.ip_interface('{0}/{1}'.format(intf['address'], intf[subnet])) else: intf = ipaddress.ip_interface('{0}/{1}'.format(intf['address'], dflt_cidr)) if not intf.is_loopback: ret.add(intf.network) return [six.text_type(net) for net in sorted(ret)] def subnets(interfaces=None): ''' Returns a list of IPv4 subnets to which the host belongs ''' return _subnets('inet', interfaces_=interfaces) def subnets6(): ''' Returns a list of IPv6 subnets to which the host belongs ''' return _subnets('inet6') def in_subnet(cidr, addr=None): ''' Returns True if host or (any of) addrs is within specified subnet, otherwise False ''' try: cidr = ipaddress.ip_network(cidr) except ValueError: log.error('Invalid CIDR \'%s\'', cidr) return False if addr is None: addr = ip_addrs() addr.extend(ip_addrs6()) elif not isinstance(addr, (list, tuple)): addr = (addr,) return any(ipaddress.ip_address(item) in cidr for item in addr) def _ip_addrs(interface=None, include_loopback=False, interface_data=None, proto='inet'): ''' Return the full list of IP adresses matching the criteria proto = inet|inet6 ''' ret = set() ifaces = interface_data \ if isinstance(interface_data, dict) \ else interfaces() if interface is None: target_ifaces = ifaces else: target_ifaces = dict([(k, v) for k, v in six.iteritems(ifaces) if k == interface]) if not target_ifaces: log.error('Interface %s not found.', interface) for ip_info in six.itervalues(target_ifaces): addrs = ip_info.get(proto, []) addrs.extend([addr for addr in ip_info.get('secondary', []) if addr.get('type') == proto]) for addr in addrs: addr = ipaddress.ip_address(addr.get('address')) if not addr.is_loopback or include_loopback: ret.add(addr) return [six.text_type(addr) for addr in sorted(ret)] def ip_addrs(interface=None, include_loopback=False, interface_data=None): ''' Returns a list of IPv4 addresses assigned to the host. 127.0.0.1 is ignored, unless 'include_loopback=True' is indicated. If 'interface' is provided, then only IP addresses from that interface will be returned. ''' return _ip_addrs(interface, include_loopback, interface_data, 'inet') def ip_addrs6(interface=None, include_loopback=False, interface_data=None): ''' Returns a list of IPv6 addresses assigned to the host. ::1 is ignored, unless 'include_loopback=True' is indicated. If 'interface' is provided, then only IP addresses from that interface will be returned. ''' return _ip_addrs(interface, include_loopback, interface_data, 'inet6') def hex2ip(hex_ip, invert=False): ''' Convert a hex string to an ip, if a failure occurs the original hex is returned. If 'invert=True' assume that ip from /proc/net/<proto> ''' if len(hex_ip) == 32: # ipv6 ip = [] for i in range(0, 32, 8): ip_part = hex_ip[i:i + 8] ip_part = [ip_part[x:x + 2] for x in range(0, 8, 2)] if invert: ip.append("{0[3]}{0[2]}:{0[1]}{0[0]}".format(ip_part)) else: ip.append("{0[0]}{0[1]}:{0[2]}{0[3]}".format(ip_part)) try: address = ipaddress.IPv6Address(":".join(ip)) if address.ipv4_mapped: return str(address.ipv4_mapped) else: return address.compressed except ipaddress.AddressValueError as ex: log.error('hex2ip - ipv6 address error: %s', ex) return hex_ip try: hip = int(hex_ip, 16) except ValueError: return hex_ip if invert: return '{3}.{2}.{1}.{0}'.format(hip >> 24 & 255, hip >> 16 & 255, hip >> 8 & 255, hip & 255) return '{0}.{1}.{2}.{3}'.format(hip >> 24 & 255, hip >> 16 & 255, hip >> 8 & 255, hip & 255) def mac2eui64(mac, prefix=None): ''' Convert a MAC address to a EUI64 identifier or, with prefix provided, a full IPv6 address ''' # http://tools.ietf.org/html/rfc4291#section-2.5.1 eui64 = re.sub(r'[.:-]', '', mac).lower() eui64 = eui64[0:6] + 'fffe' + eui64[6:] eui64 = hex(int(eui64[0:2], 16) | 2)[2:].zfill(2) + eui64[2:] if prefix is None: return ':'.join(re.findall(r'.{4}', eui64)) else: try: net = ipaddress.ip_network(prefix, strict=False) euil = int('0x{0}'.format(eui64), 16) return '{0}/{1}'.format(net[euil], net.prefixlen) except Exception: return def active_tcp(): ''' Return a dict describing all active tcp connections as quickly as possible ''' ret = {} for statf in ['/proc/net/tcp', '/proc/net/tcp6']: if os.path.isfile(statf): with salt.utils.files.fopen(statf, 'rb') as fp_: for line in fp_: line = salt.utils.stringutils.to_unicode(line) if line.strip().startswith('sl'): continue iret = _parse_tcp_line(line) sl = next(iter(iret)) if iret[sl]['state'] == 1: # 1 is ESTABLISHED del iret[sl]['state'] ret[len(ret)] = iret[sl] return ret def local_port_tcp(port): ''' Return a set of remote ip addrs attached to the specified local port ''' ret = _remotes_on(port, 'local_port') return ret def remote_port_tcp(port): ''' Return a set of ip addrs the current host is connected to on given port ''' ret = _remotes_on(port, 'remote_port') return ret def _parse_tcp_line(line): ''' Parse a single line from the contents of /proc/net/tcp or /proc/net/tcp6 ''' ret = {} comps = line.strip().split() sl = comps[0].rstrip(':') ret[sl] = {} l_addr, l_port = comps[1].split(':') r_addr, r_port = comps[2].split(':') ret[sl]['local_addr'] = hex2ip(l_addr, True) ret[sl]['local_port'] = int(l_port, 16) ret[sl]['remote_addr'] = hex2ip(r_addr, True) ret[sl]['remote_port'] = int(r_port, 16) ret[sl]['state'] = int(comps[3], 16) return ret def _netlink_tool_remote_on(port, which_end): ''' Returns set of ipv4 host addresses of remote established connections on local or remote tcp port. Parses output of shell 'ss' to get connections [root@salt-master ~]# ss -ant State Recv-Q Send-Q Local Address:Port Peer Address:Port LISTEN 0 511 *:80 *:* LISTEN 0 128 *:22 *:* ESTAB 0 0 127.0.0.1:56726 127.0.0.1:4505 ''' remotes = set() valid = False try: data = subprocess.check_output(['ss', '-ant']) # pylint: disable=minimum-python-version except subprocess.CalledProcessError: log.error('Failed ss') raise except OSError: # not command "No such file or directory" return None lines = salt.utils.stringutils.to_str(data).split('\n') for line in lines: if 'Address:Port' in line: # ss tools may not be valid valid = True continue elif 'ESTAB' not in line: continue chunks = line.split() local_host, local_port = chunks[3].split(':', 1) remote_host, remote_port = chunks[4].split(':', 1) if which_end == 'remote_port' and int(remote_port) != port: continue if which_end == 'local_port' and int(local_port) != port: continue remotes.add(remote_host) if valid is False: remotes = None return remotes def _sunos_remotes_on(port, which_end): ''' SunOS specific helper function. Returns set of ipv4 host addresses of remote established connections on local or remote tcp port. Parses output of shell 'netstat' to get connections [root@salt-master ~]# netstat -f inet -n TCP: IPv4 Local Address Remote Address Swind Send-Q Rwind Recv-Q State -------------------- -------------------- ----- ------ ----- ------ ----------- 10.0.0.101.4505 10.0.0.1.45329 1064800 0 1055864 0 ESTABLISHED 10.0.0.101.4505 10.0.0.100.50798 1064800 0 1055864 0 ESTABLISHED ''' remotes = set() try: data = subprocess.check_output(['netstat', '-f', 'inet', '-n']) # pylint: disable=minimum-python-version except subprocess.CalledProcessError: log.error('Failed netstat') raise lines = salt.utils.stringutils.to_str(data).split('\n') for line in lines: if 'ESTABLISHED' not in line: continue chunks = line.split() local_host, local_port = chunks[0].rsplit('.', 1) remote_host, remote_port = chunks[1].rsplit('.', 1) if which_end == 'remote_port' and int(remote_port) != port: continue if which_end == 'local_port' and int(local_port) != port: continue remotes.add(remote_host) return remotes def _freebsd_remotes_on(port, which_end): ''' Returns set of ipv4 host addresses of remote established connections on local tcp port port. Parses output of shell 'sockstat' (FreeBSD) to get connections $ sudo sockstat -4 USER COMMAND PID FD PROTO LOCAL ADDRESS FOREIGN ADDRESS root python2.7 1456 29 tcp4 *:4505 *:* root python2.7 1445 17 tcp4 *:4506 *:* root python2.7 1294 14 tcp4 127.0.0.1:11813 127.0.0.1:4505 root python2.7 1294 41 tcp4 127.0.0.1:61115 127.0.0.1:4506 $ sudo sockstat -4 -c -p 4506 USER COMMAND PID FD PROTO LOCAL ADDRESS FOREIGN ADDRESS root python2.7 1294 41 tcp4 127.0.0.1:61115 127.0.0.1:4506 ''' port = int(port) remotes = set() try: cmd = salt.utils.args.shlex_split('sockstat -4 -c -p {0}'.format(port)) data = subprocess.check_output(cmd) # pylint: disable=minimum-python-version except subprocess.CalledProcessError as ex: log.error('Failed "sockstat" with returncode = %s', ex.returncode) raise lines = salt.utils.stringutils.to_str(data).split('\n') for line in lines: chunks = line.split() if not chunks: continue # ['root', 'python2.7', '1456', '37', 'tcp4', # '127.0.0.1:4505-', '127.0.0.1:55703'] # print chunks if 'COMMAND' in chunks[1]: continue # ignore header if len(chunks) < 2: continue # sockstat -4 -c -p 4506 does this with high PIDs: # USER COMMAND PID FD PROTO LOCAL ADDRESS FOREIGN ADDRESS # salt-master python2.781106 35 tcp4 192.168.12.34:4506 192.168.12.45:60143 local = chunks[-2] remote = chunks[-1] lhost, lport = local.split(':') rhost, rport = remote.split(':') if which_end == 'local' and int(lport) != port: # ignore if local port not port continue if which_end == 'remote' and int(rport) != port: # ignore if remote port not port continue remotes.add(rhost) return remotes def _netbsd_remotes_on(port, which_end): ''' Returns set of ipv4 host addresses of remote established connections on local tcp port port. Parses output of shell 'sockstat' (NetBSD) to get connections $ sudo sockstat -4 -n USER COMMAND PID FD PROTO LOCAL ADDRESS FOREIGN ADDRESS root python2.7 1456 29 tcp *.4505 *.* root python2.7 1445 17 tcp *.4506 *.* root python2.7 1294 14 tcp 127.0.0.1.11813 127.0.0.1.4505 root python2.7 1294 41 tcp 127.0.0.1.61115 127.0.0.1.4506 $ sudo sockstat -4 -c -n -p 4506 USER COMMAND PID FD PROTO LOCAL ADDRESS FOREIGN ADDRESS root python2.7 1294 41 tcp 127.0.0.1.61115 127.0.0.1.4506 ''' port = int(port) remotes = set() try: cmd = salt.utils.args.shlex_split('sockstat -4 -c -n -p {0}'.format(port)) data = subprocess.check_output(cmd) # pylint: disable=minimum-python-version except subprocess.CalledProcessError as ex: log.error('Failed "sockstat" with returncode = %s', ex.returncode) raise lines = salt.utils.stringutils.to_str(data).split('\n') for line in lines: chunks = line.split() if not chunks: continue # ['root', 'python2.7', '1456', '37', 'tcp', # '127.0.0.1.4505-', '127.0.0.1.55703'] # print chunks if 'COMMAND' in chunks[1]: continue # ignore header if len(chunks) < 2: continue local = chunks[5].split('.') lport = local.pop() lhost = '.'.join(local) remote = chunks[6].split('.') rport = remote.pop() rhost = '.'.join(remote) if which_end == 'local' and int(lport) != port: # ignore if local port not port continue if which_end == 'remote' and int(rport) != port: # ignore if remote port not port continue remotes.add(rhost) return remotes def _openbsd_remotes_on(port, which_end): ''' OpenBSD specific helper function. Returns set of ipv4 host addresses of remote established connections on local or remote tcp port. Parses output of shell 'netstat' to get connections $ netstat -nf inet Active Internet connections Proto Recv-Q Send-Q Local Address Foreign Address (state) tcp 0 0 10.0.0.101.4505 10.0.0.1.45329 ESTABLISHED tcp 0 0 10.0.0.101.4505 10.0.0.100.50798 ESTABLISHED ''' remotes = set() try: data = subprocess.check_output(['netstat', '-nf', 'inet']) # pylint: disable=minimum-python-version except subprocess.CalledProcessError: log.error('Failed netstat') raise lines = data.split('\n') for line in lines: if 'ESTABLISHED' not in line: continue chunks = line.split() local_host, local_port = chunks[3].rsplit('.', 1) remote_host, remote_port = chunks[4].rsplit('.', 1) if which_end == 'remote_port' and int(remote_port) != port: continue if which_end == 'local_port' and int(local_port) != port: continue remotes.add(remote_host) return remotes def _windows_remotes_on(port, which_end): r''' Windows specific helper function. Returns set of ipv4 host addresses of remote established connections on local or remote tcp port. Parses output of shell 'netstat' to get connections C:\>netstat -n Active Connections Proto Local Address Foreign Address State TCP 10.2.33.17:3007 130.164.12.233:10123 ESTABLISHED TCP 10.2.33.17:3389 130.164.30.5:10378 ESTABLISHED ''' remotes = set() try: data = subprocess.check_output(['netstat', '-n']) # pylint: disable=minimum-python-version except subprocess.CalledProcessError: log.error('Failed netstat') raise lines = salt.utils.stringutils.to_str(data).split('\n') for line in lines: if 'ESTABLISHED' not in line: continue chunks = line.split() local_host, local_port = chunks[1].rsplit(':', 1) remote_host, remote_port = chunks[2].rsplit(':', 1) if which_end == 'remote_port' and int(remote_port) != port: continue if which_end == 'local_port' and int(local_port) != port: continue remotes.add(remote_host) return remotes def _linux_remotes_on(port, which_end): ''' Linux specific helper function. Returns set of ip host addresses of remote established connections on local tcp port port. Parses output of shell 'lsof' to get connections $ sudo lsof -iTCP:4505 -n COMMAND PID USER FD TYPE DEVICE SIZE/OFF NODE NAME Python 9971 root 35u IPv4 0x18a8464a29ca329d 0t0 TCP *:4505 (LISTEN) Python 9971 root 37u IPv4 0x18a8464a29b2b29d 0t0 TCP 127.0.0.1:4505->127.0.0.1:55703 (ESTABLISHED) Python 10152 root 22u IPv4 0x18a8464a29c8cab5 0t0 TCP 127.0.0.1:55703->127.0.0.1:4505 (ESTABLISHED) Python 10153 root 22u IPv4 0x18a8464a29c8cab5 0t0 TCP [fe80::249a]:4505->[fe80::150]:59367 (ESTABLISHED) ''' remotes = set() try: data = subprocess.check_output( ['lsof', '-iTCP:{0:d}'.format(port), '-n', '-P'] # pylint: disable=minimum-python-version ) except subprocess.CalledProcessError as ex: if ex.returncode == 1: # Lsof return 1 if any error was detected, including the failure # to locate Internet addresses, and it is not an error in this case. log.warning('"lsof" returncode = 1, likely no active TCP sessions.') return remotes log.error('Failed "lsof" with returncode = %s', ex.returncode) raise lines = salt.utils.stringutils.to_str(data).split('\n') for line in lines: chunks = line.split() if not chunks: continue # ['Python', '9971', 'root', '37u', 'IPv4', '0x18a8464a29b2b29d', '0t0', # 'TCP', '127.0.0.1:4505->127.0.0.1:55703', '(ESTABLISHED)'] # print chunks if 'COMMAND' in chunks[0]: continue # ignore header if 'ESTABLISHED' not in chunks[-1]: continue # ignore if not ESTABLISHED # '127.0.0.1:4505->127.0.0.1:55703' local, remote = chunks[8].split('->') _, lport = local.rsplit(':', 1) rhost, rport = remote.rsplit(':', 1) if which_end == 'remote_port' and int(rport) != port: continue if which_end == 'local_port' and int(lport) != port: continue remotes.add(rhost.strip("[]")) return remotes def _aix_remotes_on(port, which_end): ''' AIX specific helper function. Returns set of ipv4 host addresses of remote established connections on local or remote tcp port. Parses output of shell 'netstat' to get connections root@la68pp002_pub:/opt/salt/lib/python2.7/site-packages/salt/modules# netstat -f inet -n Active Internet connections Proto Recv-Q Send-Q Local Address Foreign Address (state) tcp4 0 0 172.29.149.95.50093 209.41.78.13.4505 ESTABLISHED tcp4 0 0 127.0.0.1.9514 *.* LISTEN tcp4 0 0 127.0.0.1.9515 *.* LISTEN tcp4 0 0 127.0.0.1.199 127.0.0.1.32779 ESTABLISHED tcp4 0 0 127.0.0.1.32779 127.0.0.1.199 ESTABLISHED tcp4 0 40 172.29.149.95.22 172.29.96.83.41022 ESTABLISHED tcp4 0 0 172.29.149.95.22 172.29.96.83.41032 ESTABLISHED tcp4 0 0 127.0.0.1.32771 127.0.0.1.32775 ESTABLISHED tcp 0 0 127.0.0.1.32775 127.0.0.1.32771 ESTABLISHED tcp4 0 0 127.0.0.1.32771 127.0.0.1.32776 ESTABLISHED tcp 0 0 127.0.0.1.32776 127.0.0.1.32771 ESTABLISHED tcp4 0 0 127.0.0.1.32771 127.0.0.1.32777 ESTABLISHED tcp 0 0 127.0.0.1.32777 127.0.0.1.32771 ESTABLISHED tcp4 0 0 127.0.0.1.32771 127.0.0.1.32778 ESTABLISHED tcp 0 0 127.0.0.1.32778 127.0.0.1.32771 ESTABLISHED ''' remotes = set() try: data = subprocess.check_output(['netstat', '-f', 'inet', '-n']) # pylint: disable=minimum-python-version except subprocess.CalledProcessError: log.error('Failed netstat') raise lines = salt.utils.stringutils.to_str(data).split('\n') for line in lines: if 'ESTABLISHED' not in line: continue chunks = line.split() local_host, local_port = chunks[3].rsplit('.', 1) remote_host, remote_port = chunks[4].rsplit('.', 1) if which_end == 'remote_port' and int(remote_port) != port: continue if which_end == 'local_port' and int(local_port) != port: continue remotes.add(remote_host) return remotes @jinja_filter('gen_mac') def gen_mac(prefix='AC:DE:48'): ''' Generates a MAC address with the defined OUI prefix. Common prefixes: - ``00:16:3E`` -- Xen - ``00:18:51`` -- OpenVZ - ``00:50:56`` -- VMware (manually generated) - ``52:54:00`` -- QEMU/KVM - ``AC:DE:48`` -- PRIVATE References: - http://standards.ieee.org/develop/regauth/oui/oui.txt - https://www.wireshark.org/tools/oui-lookup.html - https://en.wikipedia.org/wiki/MAC_address ''' return '{0}:{1:02X}:{2:02X}:{3:02X}'.format(prefix, random.randint(0, 0xff), random.randint(0, 0xff), random.randint(0, 0xff)) @jinja_filter('mac_str_to_bytes') def mac_str_to_bytes(mac_str): ''' Convert a MAC address string into bytes. Works with or without separators: b1 = mac_str_to_bytes('08:00:27:13:69:77') b2 = mac_str_to_bytes('080027136977') assert b1 == b2 assert isinstance(b1, bytes) ''' if len(mac_str) == 12: pass elif len(mac_str) == 17: sep = mac_str[2] mac_str = mac_str.replace(sep, '') else: raise ValueError('Invalid MAC address') chars = (int(mac_str[s:s+2], 16) for s in range(0, 12, 2)) return bytes(chars) if six.PY3 else b''.join(chr(x) for x in chars) def refresh_dns(): ''' issue #21397: force glibc to re-read resolv.conf ''' try: res_init() except NameError: # Exception raised loading the library, thus res_init is not defined pass @jinja_filter('connection_check') def connection_check(addr, port=80, safe=False, ipv6=None): ''' Provides a convenient alias for the dns_check filter. ''' return dns_check(addr, port, safe, ipv6) @jinja_filter('dns_check') def dns_check(addr, port=80, safe=False, ipv6=None, attempt_connect=True): ''' Return the ip resolved by dns, but do not exit on failure, only raise an exception. Obeys system preference for IPv4/6 address resolution - this can be overridden by the ipv6 flag. Tries to connect to the address before considering it useful. If no address can be reached, the first one resolved is used as a fallback. ''' error = False lookup = addr seen_ipv6 = False family = socket.AF_INET6 if ipv6 else socket.AF_INET if ipv6 is False else socket.AF_UNSPEC hostnames = [] try: refresh_dns() hostnames = socket.getaddrinfo(addr, port, family, socket.SOCK_STREAM) except TypeError: err = ('Attempt to resolve address \'{0}\' failed. Invalid or unresolveable address').format(lookup) raise SaltSystemExit(code=42, msg=err) except socket.error: error = True # If ipv6 is set to True, attempt another lookup using the IPv4 family, # just in case we're attempting to lookup an IPv4 IP # as an IPv6 hostname. if error and ipv6: try: refresh_dns() hostnames = socket.getaddrinfo(addr, port, socket.AF_INET, socket.SOCK_STREAM) except TypeError: err = ('Attempt to resolve address \'{0}\' failed. Invalid or unresolveable address').format(lookup) raise SaltSystemExit(code=42, msg=err) except socket.error: error = True try: if not hostnames: error = True else: resolved = False candidates = [] for h in hostnames: # Input is IP address, passed through unchanged, just return it if h[4][0] == addr: resolved = salt.utils.zeromq.ip_bracket(addr) break candidate_addr = salt.utils.zeromq.ip_bracket(h[4][0]) # sometimes /etc/hosts contains ::1 localhost if not ipv6 and candidate_addr == '[::1]': continue candidates.append(candidate_addr) if attempt_connect: try: s = socket.socket(h[0], socket.SOCK_STREAM) s.settimeout(2) s.connect((candidate_addr.strip('[]'), h[4][1])) s.close() resolved = candidate_addr break except socket.error: pass if not resolved: if candidates: resolved = candidates[0] else: error = True except TypeError: err = ('Attempt to resolve address \'{0}\' failed. Invalid or unresolveable address').format(lookup) raise SaltSystemExit(code=42, msg=err) except socket.error: error = True if error: err = ('DNS lookup or connection check of \'{0}\' failed.').format(addr) if safe: if salt.log.is_console_configured(): # If logging is not configured it also means that either # the master or minion instance calling this hasn't even # started running log.error(err) raise SaltClientError() raise SaltSystemExit(code=42, msg=err) return resolved def parse_host_port(host_port): """ Takes a string argument specifying host or host:port. Returns a (hostname, port) or (ip_address, port) tuple. If no port is given, the second (port) element of the returned tuple will be None. host:port argument, for example, is accepted in the forms of: - hostname - hostname:1234 - hostname.domain.tld - hostname.domain.tld:5678 - [1234::5]:5678 - 1234::5 - 10.11.12.13:4567 - 10.11.12.13 """ host, port = None, None # default _s_ = host_port[:] if _s_[0] == "[": if "]" in host_port: host, _s_ = _s_.lstrip("[").rsplit("]", 1) host = ipaddress.IPv6Address(host).compressed if _s_[0] == ":": port = int(_s_.lstrip(":")) else: if len(_s_) > 1: raise ValueError('found ambiguous "{}" port in "{}"'.format(_s_, host_port)) else: if _s_.count(":") == 1: host, _hostport_separator_, port = _s_.partition(":") try: port = int(port) except ValueError as _e_: log.error('host_port "%s" port value "%s" is not an integer.', host_port, port) raise _e_ else: host = _s_ try: if not isinstance(host, ipaddress._BaseAddress): host_ip = ipaddress.ip_address(host).compressed host = host_ip except ValueError: log.debug('"%s" Not an IP address? Assuming it is a hostname.', host) if host != sanitize_host(host): log.error('bad hostname: "%s"', host) raise ValueError('bad hostname: "{}"'.format(host)) return host, port def is_fqdn(hostname): """ Verify if hostname conforms to be a FQDN. :param hostname: text string with the name of the host :return: bool, True if hostname is correct FQDN, False otherwise """ compliant = re.compile(r"(?!-)[A-Z\d\-\_]{1,63}(?<!-)$", re.IGNORECASE) return "." in hostname and len(hostname) < 0xff and all(compliant.match(x) for x in hostname.rstrip(".").split("."))
saltstack/salt
salt/utils/network.py
_parse_tcp_line
python
def _parse_tcp_line(line): ''' Parse a single line from the contents of /proc/net/tcp or /proc/net/tcp6 ''' ret = {} comps = line.strip().split() sl = comps[0].rstrip(':') ret[sl] = {} l_addr, l_port = comps[1].split(':') r_addr, r_port = comps[2].split(':') ret[sl]['local_addr'] = hex2ip(l_addr, True) ret[sl]['local_port'] = int(l_port, 16) ret[sl]['remote_addr'] = hex2ip(r_addr, True) ret[sl]['remote_port'] = int(r_port, 16) ret[sl]['state'] = int(comps[3], 16) return ret
Parse a single line from the contents of /proc/net/tcp or /proc/net/tcp6
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/network.py#L1444-L1459
null
# -*- coding: utf-8 -*- ''' Define some generic socket functions for network modules ''' # Import python libs from __future__ import absolute_import, unicode_literals, print_function import itertools import os import re import types import socket import logging import platform import random import subprocess from string import ascii_letters, digits # Import 3rd-party libs from salt.ext import six from salt.ext.six.moves import range # pylint: disable=import-error,redefined-builtin # Attempt to import wmi try: import wmi import salt.utils.winapi except ImportError: pass # Import salt libs import salt.utils.args import salt.utils.files import salt.utils.path import salt.utils.platform import salt.utils.stringutils import salt.utils.zeromq from salt._compat import ipaddress from salt.exceptions import SaltClientError, SaltSystemExit from salt.utils.decorators.jinja import jinja_filter from salt.utils.versions import LooseVersion # inet_pton does not exist in Windows, this is a workaround if salt.utils.platform.is_windows(): from salt.ext import win_inet_pton # pylint: disable=unused-import log = logging.getLogger(__name__) try: import ctypes import ctypes.util libc = ctypes.cdll.LoadLibrary(ctypes.util.find_library("c")) res_init = libc.__res_init except (ImportError, OSError, AttributeError, TypeError): pass # pylint: disable=C0103 def sanitize_host(host): ''' Sanitize host string. https://tools.ietf.org/html/rfc1123#section-2.1 ''' RFC952_characters = ascii_letters + digits + ".-" return "".join([c for c in host[0:255] if c in RFC952_characters]) def isportopen(host, port): ''' Return status of a port ''' if not 1 <= int(port) <= 65535: return False sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) out = sock.connect_ex((sanitize_host(host), int(port))) return out def host_to_ips(host): ''' Returns a list of IP addresses of a given hostname or None if not found. ''' ips = [] try: for family, socktype, proto, canonname, sockaddr in socket.getaddrinfo( host, 0, socket.AF_UNSPEC, socket.SOCK_STREAM): if family == socket.AF_INET: ip, port = sockaddr elif family == socket.AF_INET6: ip, port, flow_info, scope_id = sockaddr ips.append(ip) if not ips: ips = None except Exception: ips = None return ips def _generate_minion_id(): ''' Get list of possible host names and convention names. :return: ''' # There are three types of hostnames: # 1. Network names. How host is accessed from the network. # 2. Host aliases. They might be not available in all the network or only locally (/etc/hosts) # 3. Convention names, an internal nodename. class DistinctList(list): ''' List, which allows one to append only distinct objects. Needs to work on Python 2.6, because of collections.OrderedDict only since 2.7 version. Override 'filter()' for custom filtering. ''' localhost_matchers = [r'localhost.*', r'ip6-.*', r'127[.]\d', r'0\.0\.0\.0', r'::1.*', r'ipv6-.*', r'fe00::.*', r'fe02::.*', r'1.0.0.*.ip6.arpa'] def append(self, p_object): if p_object and p_object not in self and not self.filter(p_object): super(DistinctList, self).append(p_object) return self def extend(self, iterable): for obj in iterable: self.append(obj) return self def filter(self, element): 'Returns True if element needs to be filtered' for rgx in self.localhost_matchers: if re.match(rgx, element): return True def first(self): return self and self[0] or None hostname = socket.gethostname() hosts = DistinctList().append( salt.utils.stringutils.to_unicode(socket.getfqdn(salt.utils.stringutils.to_bytes(hostname))) ).append(platform.node()).append(hostname) if not hosts: try: for a_nfo in socket.getaddrinfo(hosts.first() or 'localhost', None, socket.AF_INET, socket.SOCK_RAW, socket.IPPROTO_IP, socket.AI_CANONNAME): if len(a_nfo) > 3: hosts.append(a_nfo[3]) except socket.gaierror: log.warning('Cannot resolve address %s info via socket: %s', hosts.first() or 'localhost (N/A)', socket.gaierror) # Universal method for everywhere (Linux, Slowlaris, Windows etc) for f_name in ('/etc/hostname', '/etc/nodename', '/etc/hosts', r'{win}\system32\drivers\etc\hosts'.format(win=os.getenv('WINDIR'))): try: with salt.utils.files.fopen(f_name) as f_hdl: for line in f_hdl: line = salt.utils.stringutils.to_unicode(line) hst = line.strip().split('#')[0].strip().split() if hst: if hst[0][:4] in ('127.', '::1') or len(hst) == 1: hosts.extend(hst) except IOError: pass # include public and private ipaddresses return hosts.extend([addr for addr in ip_addrs() if not ipaddress.ip_address(addr).is_loopback]) def generate_minion_id(): ''' Return only first element of the hostname from all possible list. :return: ''' try: ret = salt.utils.stringutils.to_unicode(_generate_minion_id().first()) except TypeError: ret = None return ret or 'localhost' def get_socket(addr, type=socket.SOCK_STREAM, proto=0): ''' Return a socket object for the addr IP-version agnostic ''' version = ipaddress.ip_address(addr).version if version == 4: family = socket.AF_INET elif version == 6: family = socket.AF_INET6 return socket.socket(family, type, proto) def get_fqhostname(): ''' Returns the fully qualified hostname ''' # try getaddrinfo() fqdn = None try: addrinfo = socket.getaddrinfo( socket.gethostname(), 0, socket.AF_UNSPEC, socket.SOCK_STREAM, socket.SOL_TCP, socket.AI_CANONNAME ) for info in addrinfo: # info struct [family, socktype, proto, canonname, sockaddr] # On Windows `canonname` can be an empty string # This can cause the function to return `None` if len(info) > 3 and info[3]: fqdn = info[3] break except socket.gaierror: pass # NOTE: this used to log.error() but it was later disabled except socket.error as err: log.debug('socket.getaddrinfo() failure while finding fqdn: %s', err) if fqdn is None: fqdn = socket.getfqdn() return fqdn def ip_to_host(ip): ''' Returns the hostname of a given IP ''' try: hostname, aliaslist, ipaddrlist = socket.gethostbyaddr(ip) except Exception as exc: log.debug('salt.utils.network.ip_to_host(%r) failed: %s', ip, exc) hostname = None return hostname # pylint: enable=C0103 def is_reachable_host(entity_name): ''' Returns a bool telling if the entity name is a reachable host (IPv4/IPv6/FQDN/etc). :param hostname: :return: ''' try: assert type(socket.getaddrinfo(entity_name, 0, 0, 0, 0)) == list ret = True except socket.gaierror: ret = False return ret def is_ip(ip): ''' Returns a bool telling if the passed IP is a valid IPv4 or IPv6 address. ''' return is_ipv4(ip) or is_ipv6(ip) def is_ipv4(ip): ''' Returns a bool telling if the value passed to it was a valid IPv4 address ''' try: return ipaddress.ip_address(ip).version == 4 except ValueError: return False def is_ipv6(ip): ''' Returns a bool telling if the value passed to it was a valid IPv6 address ''' try: return ipaddress.ip_address(ip).version == 6 except ValueError: return False def is_subnet(cidr): ''' Returns a bool telling if the passed string is an IPv4 or IPv6 subnet ''' return is_ipv4_subnet(cidr) or is_ipv6_subnet(cidr) def is_ipv4_subnet(cidr): ''' Returns a bool telling if the passed string is an IPv4 subnet ''' try: return '/' in cidr and bool(ipaddress.IPv4Network(cidr)) except Exception: return False def is_ipv6_subnet(cidr): ''' Returns a bool telling if the passed string is an IPv6 subnet ''' try: return '/' in cidr and bool(ipaddress.IPv6Network(cidr)) except Exception: return False @jinja_filter('is_ip') def is_ip_filter(ip, options=None): ''' Returns a bool telling if the passed IP is a valid IPv4 or IPv6 address. ''' return is_ipv4_filter(ip, options=options) or is_ipv6_filter(ip, options=options) def _ip_options_global(ip_obj, version): return not ip_obj.is_private def _ip_options_multicast(ip_obj, version): return ip_obj.is_multicast def _ip_options_loopback(ip_obj, version): return ip_obj.is_loopback def _ip_options_link_local(ip_obj, version): return ip_obj.is_link_local def _ip_options_private(ip_obj, version): return ip_obj.is_private def _ip_options_reserved(ip_obj, version): return ip_obj.is_reserved def _ip_options_site_local(ip_obj, version): if version == 6: return ip_obj.is_site_local return False def _ip_options_unspecified(ip_obj, version): return ip_obj.is_unspecified def _ip_options(ip_obj, version, options=None): # will process and IP options options_fun_map = { 'global': _ip_options_global, 'link-local': _ip_options_link_local, 'linklocal': _ip_options_link_local, 'll': _ip_options_link_local, 'link_local': _ip_options_link_local, 'loopback': _ip_options_loopback, 'lo': _ip_options_loopback, 'multicast': _ip_options_multicast, 'private': _ip_options_private, 'public': _ip_options_global, 'reserved': _ip_options_reserved, 'site-local': _ip_options_site_local, 'sl': _ip_options_site_local, 'site_local': _ip_options_site_local, 'unspecified': _ip_options_unspecified } if not options: return six.text_type(ip_obj) # IP version already checked options_list = [option.strip() for option in options.split(',')] for option, fun in options_fun_map.items(): if option in options_list: fun_res = fun(ip_obj, version) if not fun_res: return None # stop at first failed test # else continue return six.text_type(ip_obj) def _is_ipv(ip, version, options=None): if not version: version = 4 if version not in (4, 6): return None try: ip_obj = ipaddress.ip_address(ip) except ValueError: # maybe it is an IP network try: ip_obj = ipaddress.ip_interface(ip) except ValueError: # nope, still not :( return None if not ip_obj.version == version: return None # has the right version, let's move on return _ip_options(ip_obj, version, options=options) @jinja_filter('is_ipv4') def is_ipv4_filter(ip, options=None): ''' Returns a bool telling if the value passed to it was a valid IPv4 address. ip The IP address. net: False Consider IP addresses followed by netmask. options CSV of options regarding the nature of the IP address. E.g.: loopback, multicast, private etc. ''' _is_ipv4 = _is_ipv(ip, 4, options=options) return isinstance(_is_ipv4, six.string_types) @jinja_filter('is_ipv6') def is_ipv6_filter(ip, options=None): ''' Returns a bool telling if the value passed to it was a valid IPv6 address. ip The IP address. net: False Consider IP addresses followed by netmask. options CSV of options regarding the nature of the IP address. E.g.: loopback, multicast, private etc. ''' _is_ipv6 = _is_ipv(ip, 6, options=options) return isinstance(_is_ipv6, six.string_types) def _ipv_filter(value, version, options=None): if version not in (4, 6): return if isinstance(value, (six.string_types, six.text_type, six.binary_type)): return _is_ipv(value, version, options=options) # calls is_ipv4 or is_ipv6 for `value` elif isinstance(value, (list, tuple, types.GeneratorType)): # calls is_ipv4 or is_ipv6 for each element in the list # os it filters and returns only those elements having the desired IP version return [ _is_ipv(addr, version, options=options) for addr in value if _is_ipv(addr, version, options=options) is not None ] return None @jinja_filter('ipv4') def ipv4(value, options=None): ''' Filters a list and returns IPv4 values only. ''' return _ipv_filter(value, 4, options=options) @jinja_filter('ipv6') def ipv6(value, options=None): ''' Filters a list and returns IPv6 values only. ''' return _ipv_filter(value, 6, options=options) @jinja_filter('ipaddr') def ipaddr(value, options=None): ''' Filters and returns only valid IP objects. ''' ipv4_obj = ipv4(value, options=options) ipv6_obj = ipv6(value, options=options) if ipv4_obj is None or ipv6_obj is None: # an IP address can be either IPv4 either IPv6 # therefofe if the value passed as arg is not a list, at least one of the calls above will return None # if one of them is none, means that we should return only one of them return ipv4_obj or ipv6_obj # one of them else: return ipv4_obj + ipv6_obj # extend lists def _filter_ipaddr(value, options, version=None): ipaddr_filter_out = None if version: if version == 4: ipaddr_filter_out = ipv4(value, options) elif version == 6: ipaddr_filter_out = ipv6(value, options) else: ipaddr_filter_out = ipaddr(value, options) if not ipaddr_filter_out: return if not isinstance(ipaddr_filter_out, (list, tuple, types.GeneratorType)): ipaddr_filter_out = [ipaddr_filter_out] return ipaddr_filter_out @jinja_filter('ip_host') def ip_host(value, options=None, version=None): ''' Returns the interfaces IP address, e.g.: 192.168.0.1/28. ''' ipaddr_filter_out = _filter_ipaddr(value, options=options, version=version) if not ipaddr_filter_out: return if not isinstance(value, (list, tuple, types.GeneratorType)): return six.text_type(ipaddress.ip_interface(ipaddr_filter_out[0])) return [six.text_type(ipaddress.ip_interface(ip_a)) for ip_a in ipaddr_filter_out] def _network_hosts(ip_addr_entry): return [ six.text_type(host) for host in ipaddress.ip_network(ip_addr_entry, strict=False).hosts() ] @jinja_filter('network_hosts') def network_hosts(value, options=None, version=None): ''' Return the list of hosts within a network. .. note:: When running this command with a large IPv6 network, the command will take a long time to gather all of the hosts. ''' ipaddr_filter_out = _filter_ipaddr(value, options=options, version=version) if not ipaddr_filter_out: return if not isinstance(value, (list, tuple, types.GeneratorType)): return _network_hosts(ipaddr_filter_out[0]) return [ _network_hosts(ip_a) for ip_a in ipaddr_filter_out ] def _network_size(ip_addr_entry): return ipaddress.ip_network(ip_addr_entry, strict=False).num_addresses @jinja_filter('network_size') def network_size(value, options=None, version=None): ''' Get the size of a network. ''' ipaddr_filter_out = _filter_ipaddr(value, options=options, version=version) if not ipaddr_filter_out: return if not isinstance(value, (list, tuple, types.GeneratorType)): return _network_size(ipaddr_filter_out[0]) return [ _network_size(ip_a) for ip_a in ipaddr_filter_out ] def natural_ipv4_netmask(ip, fmt='prefixlen'): ''' Returns the "natural" mask of an IPv4 address ''' bits = _ipv4_to_bits(ip) if bits.startswith('11'): mask = '24' elif bits.startswith('1'): mask = '16' else: mask = '8' if fmt == 'netmask': return cidr_to_ipv4_netmask(mask) else: return '/' + mask def rpad_ipv4_network(ip): ''' Returns an IP network address padded with zeros. Ex: '192.168.3' -> '192.168.3.0' '10.209' -> '10.209.0.0' ''' return '.'.join(itertools.islice(itertools.chain(ip.split('.'), '0000'), 0, 4)) def cidr_to_ipv4_netmask(cidr_bits): ''' Returns an IPv4 netmask ''' try: cidr_bits = int(cidr_bits) if not 1 <= cidr_bits <= 32: return '' except ValueError: return '' netmask = '' for idx in range(4): if idx: netmask += '.' if cidr_bits >= 8: netmask += '255' cidr_bits -= 8 else: netmask += '{0:d}'.format(256 - (2 ** (8 - cidr_bits))) cidr_bits = 0 return netmask def _number_of_set_bits_to_ipv4_netmask(set_bits): # pylint: disable=C0103 ''' Returns an IPv4 netmask from the integer representation of that mask. Ex. 0xffffff00 -> '255.255.255.0' ''' return cidr_to_ipv4_netmask(_number_of_set_bits(set_bits)) # pylint: disable=C0103 def _number_of_set_bits(x): ''' Returns the number of bits that are set in a 32bit int ''' # Taken from http://stackoverflow.com/a/4912729. Many thanks! x -= (x >> 1) & 0x55555555 x = ((x >> 2) & 0x33333333) + (x & 0x33333333) x = ((x >> 4) + x) & 0x0f0f0f0f x += x >> 8 x += x >> 16 return x & 0x0000003f # pylint: enable=C0103 def _interfaces_ip(out): ''' Uses ip to return a dictionary of interfaces with various information about each (up/down state, ip address, netmask, and hwaddr) ''' ret = dict() def parse_network(value, cols): ''' Return a tuple of ip, netmask, broadcast based on the current set of cols ''' brd = None scope = None if '/' in value: # we have a CIDR in this address ip, cidr = value.split('/') # pylint: disable=C0103 else: ip = value # pylint: disable=C0103 cidr = 32 if type_ == 'inet': mask = cidr_to_ipv4_netmask(int(cidr)) if 'brd' in cols: brd = cols[cols.index('brd') + 1] elif type_ == 'inet6': mask = cidr if 'scope' in cols: scope = cols[cols.index('scope') + 1] return (ip, mask, brd, scope) groups = re.compile('\r?\n\\d').split(out) for group in groups: iface = None data = dict() for line in group.splitlines(): if ' ' not in line: continue match = re.match(r'^\d*:\s+([\w.\-]+)(?:@)?([\w.\-]+)?:\s+<(.+)>', line) if match: iface, parent, attrs = match.groups() if 'UP' in attrs.split(','): data['up'] = True else: data['up'] = False if parent: data['parent'] = parent continue cols = line.split() if len(cols) >= 2: type_, value = tuple(cols[0:2]) iflabel = cols[-1:][0] if type_ in ('inet', 'inet6'): if 'secondary' not in cols: ipaddr, netmask, broadcast, scope = parse_network(value, cols) if type_ == 'inet': if 'inet' not in data: data['inet'] = list() addr_obj = dict() addr_obj['address'] = ipaddr addr_obj['netmask'] = netmask addr_obj['broadcast'] = broadcast addr_obj['label'] = iflabel data['inet'].append(addr_obj) elif type_ == 'inet6': if 'inet6' not in data: data['inet6'] = list() addr_obj = dict() addr_obj['address'] = ipaddr addr_obj['prefixlen'] = netmask addr_obj['scope'] = scope data['inet6'].append(addr_obj) else: if 'secondary' not in data: data['secondary'] = list() ip_, mask, brd, scp = parse_network(value, cols) data['secondary'].append({ 'type': type_, 'address': ip_, 'netmask': mask, 'broadcast': brd, 'label': iflabel, }) del ip_, mask, brd, scp elif type_.startswith('link'): data['hwaddr'] = value if iface: ret[iface] = data del iface, data return ret def _interfaces_ifconfig(out): ''' Uses ifconfig to return a dictionary of interfaces with various information about each (up/down state, ip address, netmask, and hwaddr) ''' ret = dict() piface = re.compile(r'^([^\s:]+)') pmac = re.compile('.*?(?:HWaddr|ether|address:|lladdr) ([0-9a-fA-F:]+)') if salt.utils.platform.is_sunos(): pip = re.compile(r'.*?(?:inet\s+)([0-9]+\.[0-9]+\.[0-9]+\.[0-9]+)(.*)') pip6 = re.compile('.*?(?:inet6 )([0-9a-fA-F:]+)') pmask6 = re.compile(r'.*?(?:inet6 [0-9a-fA-F:]+/(\d+)).*') else: pip = re.compile(r'.*?(?:inet addr:|inet [^\d]*)(.*?)\s') pip6 = re.compile('.*?(?:inet6 addr: (.*?)/|inet6 )([0-9a-fA-F:]+)') pmask6 = re.compile(r'.*?(?:inet6 addr: [0-9a-fA-F:]+/(\d+)|prefixlen (\d+))(?: Scope:([a-zA-Z]+)| scopeid (0x[0-9a-fA-F]))?') pmask = re.compile(r'.*?(?:Mask:|netmask )(?:((?:0x)?[0-9a-fA-F]{8})|([\d\.]+))') pupdown = re.compile('UP') pbcast = re.compile(r'.*?(?:Bcast:|broadcast )([\d\.]+)') groups = re.compile('\r?\n(?=\\S)').split(out) for group in groups: data = dict() iface = '' updown = False for line in group.splitlines(): miface = piface.match(line) mmac = pmac.match(line) mip = pip.match(line) mip6 = pip6.match(line) mupdown = pupdown.search(line) if miface: iface = miface.group(1) if mmac: data['hwaddr'] = mmac.group(1) if salt.utils.platform.is_sunos(): expand_mac = [] for chunk in data['hwaddr'].split(':'): expand_mac.append('0{0}'.format(chunk) if len(chunk) < 2 else '{0}'.format(chunk)) data['hwaddr'] = ':'.join(expand_mac) if mip: if 'inet' not in data: data['inet'] = list() addr_obj = dict() addr_obj['address'] = mip.group(1) mmask = pmask.match(line) if mmask: if mmask.group(1): mmask = _number_of_set_bits_to_ipv4_netmask( int(mmask.group(1), 16)) else: mmask = mmask.group(2) addr_obj['netmask'] = mmask mbcast = pbcast.match(line) if mbcast: addr_obj['broadcast'] = mbcast.group(1) data['inet'].append(addr_obj) if mupdown: updown = True if mip6: if 'inet6' not in data: data['inet6'] = list() addr_obj = dict() addr_obj['address'] = mip6.group(1) or mip6.group(2) mmask6 = pmask6.match(line) if mmask6: addr_obj['prefixlen'] = mmask6.group(1) or mmask6.group(2) if not salt.utils.platform.is_sunos(): ipv6scope = mmask6.group(3) or mmask6.group(4) addr_obj['scope'] = ipv6scope.lower() if ipv6scope is not None else ipv6scope # SunOS sometimes has ::/0 as inet6 addr when using addrconf if not salt.utils.platform.is_sunos() \ or addr_obj['address'] != '::' \ and addr_obj['prefixlen'] != 0: data['inet6'].append(addr_obj) data['up'] = updown if iface in ret: # SunOS optimization, where interfaces occur twice in 'ifconfig -a' # output with the same name: for ipv4 and then for ipv6 addr family. # Every instance has it's own 'UP' status and we assume that ipv4 # status determines global interface status. # # merge items with higher priority for older values # after that merge the inet and inet6 sub items for both ret[iface] = dict(list(data.items()) + list(ret[iface].items())) if 'inet' in data: ret[iface]['inet'].extend(x for x in data['inet'] if x not in ret[iface]['inet']) if 'inet6' in data: ret[iface]['inet6'].extend(x for x in data['inet6'] if x not in ret[iface]['inet6']) else: ret[iface] = data del data return ret def linux_interfaces(): ''' Obtain interface information for *NIX/BSD variants ''' ifaces = dict() ip_path = salt.utils.path.which('ip') ifconfig_path = None if ip_path else salt.utils.path.which('ifconfig') if ip_path: cmd1 = subprocess.Popen( '{0} link show'.format(ip_path), shell=True, close_fds=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT).communicate()[0] cmd2 = subprocess.Popen( '{0} addr show'.format(ip_path), shell=True, close_fds=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT).communicate()[0] ifaces = _interfaces_ip("{0}\n{1}".format( salt.utils.stringutils.to_str(cmd1), salt.utils.stringutils.to_str(cmd2))) elif ifconfig_path: cmd = subprocess.Popen( '{0} -a'.format(ifconfig_path), shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT).communicate()[0] ifaces = _interfaces_ifconfig(salt.utils.stringutils.to_str(cmd)) return ifaces def _netbsd_interfaces_ifconfig(out): ''' Uses ifconfig to return a dictionary of interfaces with various information about each (up/down state, ip address, netmask, and hwaddr) ''' ret = dict() piface = re.compile(r'^([^\s:]+)') pmac = re.compile('.*?address: ([0-9a-f:]+)') pip = re.compile(r'.*?inet [^\d]*(.*?)/([\d]*)\s') pip6 = re.compile(r'.*?inet6 ([0-9a-f:]+)%([a-zA-Z0-9]*)/([\d]*)\s') pupdown = re.compile('UP') pbcast = re.compile(r'.*?broadcast ([\d\.]+)') groups = re.compile('\r?\n(?=\\S)').split(out) for group in groups: data = dict() iface = '' updown = False for line in group.splitlines(): miface = piface.match(line) mmac = pmac.match(line) mip = pip.match(line) mip6 = pip6.match(line) mupdown = pupdown.search(line) if miface: iface = miface.group(1) if mmac: data['hwaddr'] = mmac.group(1) if mip: if 'inet' not in data: data['inet'] = list() addr_obj = dict() addr_obj['address'] = mip.group(1) mmask = mip.group(2) if mip.group(2): addr_obj['netmask'] = cidr_to_ipv4_netmask(mip.group(2)) mbcast = pbcast.match(line) if mbcast: addr_obj['broadcast'] = mbcast.group(1) data['inet'].append(addr_obj) if mupdown: updown = True if mip6: if 'inet6' not in data: data['inet6'] = list() addr_obj = dict() addr_obj['address'] = mip6.group(1) mmask6 = mip6.group(3) addr_obj['scope'] = mip6.group(2) addr_obj['prefixlen'] = mip6.group(3) data['inet6'].append(addr_obj) data['up'] = updown ret[iface] = data del data return ret def netbsd_interfaces(): ''' Obtain interface information for NetBSD >= 8 where the ifconfig output diverged from other BSD variants (Netmask is now part of the address) ''' # NetBSD versions prior to 8.0 can still use linux_interfaces() if LooseVersion(os.uname()[2]) < LooseVersion('8.0'): return linux_interfaces() ifconfig_path = salt.utils.path.which('ifconfig') cmd = subprocess.Popen( '{0} -a'.format(ifconfig_path), shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT).communicate()[0] return _netbsd_interfaces_ifconfig(salt.utils.stringutils.to_str(cmd)) def _interfaces_ipconfig(out): ''' Returns a dictionary of interfaces with various information about each (up/down state, ip address, netmask, and hwaddr) NOTE: This is not used by any function and may be able to be removed in the future. ''' ifaces = dict() iface = None adapter_iface_regex = re.compile(r'adapter (\S.+):$') for line in out.splitlines(): if not line: continue # TODO what does Windows call Infiniband and 10/40gige adapters if line.startswith('Ethernet'): iface = ifaces[adapter_iface_regex.search(line).group(1)] iface['up'] = True addr = None continue if iface: key, val = line.split(',', 1) key = key.strip(' .') val = val.strip() if addr and key == 'Subnet Mask': addr['netmask'] = val elif key in ('IP Address', 'IPv4 Address'): if 'inet' not in iface: iface['inet'] = list() addr = {'address': val.rstrip('(Preferred)'), 'netmask': None, 'broadcast': None} # TODO find the broadcast iface['inet'].append(addr) elif 'IPv6 Address' in key: if 'inet6' not in iface: iface['inet'] = list() # XXX What is the prefixlen!? addr = {'address': val.rstrip('(Preferred)'), 'prefixlen': None} iface['inet6'].append(addr) elif key == 'Physical Address': iface['hwaddr'] = val elif key == 'Media State': # XXX seen used for tunnel adaptors # might be useful iface['up'] = (val != 'Media disconnected') def win_interfaces(): ''' Obtain interface information for Windows systems ''' with salt.utils.winapi.Com(): c = wmi.WMI() ifaces = {} for iface in c.Win32_NetworkAdapterConfiguration(IPEnabled=1): ifaces[iface.Description] = dict() if iface.MACAddress: ifaces[iface.Description]['hwaddr'] = iface.MACAddress if iface.IPEnabled: ifaces[iface.Description]['up'] = True for ip in iface.IPAddress: if '.' in ip: if 'inet' not in ifaces[iface.Description]: ifaces[iface.Description]['inet'] = [] item = {'address': ip, 'label': iface.Description} if iface.DefaultIPGateway: broadcast = next((i for i in iface.DefaultIPGateway if '.' in i), '') if broadcast: item['broadcast'] = broadcast if iface.IPSubnet: netmask = next((i for i in iface.IPSubnet if '.' in i), '') if netmask: item['netmask'] = netmask ifaces[iface.Description]['inet'].append(item) if ':' in ip: if 'inet6' not in ifaces[iface.Description]: ifaces[iface.Description]['inet6'] = [] item = {'address': ip} if iface.DefaultIPGateway: broadcast = next((i for i in iface.DefaultIPGateway if ':' in i), '') if broadcast: item['broadcast'] = broadcast if iface.IPSubnet: netmask = next((i for i in iface.IPSubnet if ':' in i), '') if netmask: item['netmask'] = netmask ifaces[iface.Description]['inet6'].append(item) else: ifaces[iface.Description]['up'] = False return ifaces def interfaces(): ''' Return a dictionary of information about all the interfaces on the minion ''' if salt.utils.platform.is_windows(): return win_interfaces() elif salt.utils.platform.is_netbsd(): return netbsd_interfaces() else: return linux_interfaces() def get_net_start(ipaddr, netmask): ''' Return the address of the network ''' net = ipaddress.ip_network('{0}/{1}'.format(ipaddr, netmask), strict=False) return six.text_type(net.network_address) def get_net_size(mask): ''' Turns an IPv4 netmask into it's corresponding prefix length (255.255.255.0 -> 24 as in 192.168.1.10/24). ''' binary_str = '' for octet in mask.split('.'): binary_str += bin(int(octet))[2:].zfill(8) return len(binary_str.rstrip('0')) def calc_net(ipaddr, netmask=None): ''' Takes IP (CIDR notation supported) and optionally netmask and returns the network in CIDR-notation. (The IP can be any IP inside the subnet) ''' if netmask is not None: ipaddr = '{0}/{1}'.format(ipaddr, netmask) return six.text_type(ipaddress.ip_network(ipaddr, strict=False)) def _ipv4_to_bits(ipaddr): ''' Accepts an IPv4 dotted quad and returns a string representing its binary counterpart ''' return ''.join([bin(int(x))[2:].rjust(8, '0') for x in ipaddr.split('.')]) def _get_iface_info(iface): ''' If `iface` is available, return interface info and no error, otherwise return no info and log and return an error ''' iface_info = interfaces() if iface in iface_info.keys(): return iface_info, False else: error_msg = ('Interface "{0}" not in available interfaces: "{1}"' ''.format(iface, '", "'.join(iface_info.keys()))) log.error(error_msg) return None, error_msg def _hw_addr_aix(iface): ''' Return the hardware address (a.k.a. MAC address) for a given interface on AIX MAC address not available in through interfaces ''' cmd = subprocess.Popen( 'entstat -d {0} | grep \'Hardware Address\''.format(iface), shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT).communicate()[0] if cmd: comps = cmd.split(' ') if len(comps) == 3: mac_addr = comps[2].strip('\'').strip() return mac_addr error_msg = ('Interface "{0}" either not available or does not contain a hardware address'.format(iface)) log.error(error_msg) return error_msg def hw_addr(iface): ''' Return the hardware address (a.k.a. MAC address) for a given interface .. versionchanged:: 2016.11.4 Added support for AIX ''' if salt.utils.platform.is_aix(): return _hw_addr_aix iface_info, error = _get_iface_info(iface) if error is False: return iface_info.get(iface, {}).get('hwaddr', '') else: return error def interface(iface): ''' Return the details of `iface` or an error if it does not exist ''' iface_info, error = _get_iface_info(iface) if error is False: return iface_info.get(iface, {}).get('inet', '') else: return error def interface_ip(iface): ''' Return `iface` IPv4 addr or an error if `iface` does not exist ''' iface_info, error = _get_iface_info(iface) if error is False: inet = iface_info.get(iface, {}).get('inet', None) return inet[0].get('address', '') if inet else '' else: return error def _subnets(proto='inet', interfaces_=None): ''' Returns a list of subnets to which the host belongs ''' if interfaces_ is None: ifaces = interfaces() elif isinstance(interfaces_, list): ifaces = {} for key, value in six.iteritems(interfaces()): if key in interfaces_: ifaces[key] = value else: ifaces = {interfaces_: interfaces().get(interfaces_, {})} ret = set() if proto == 'inet': subnet = 'netmask' dflt_cidr = 32 elif proto == 'inet6': subnet = 'prefixlen' dflt_cidr = 128 else: log.error('Invalid proto %s calling subnets()', proto) return for ip_info in six.itervalues(ifaces): addrs = ip_info.get(proto, []) addrs.extend([addr for addr in ip_info.get('secondary', []) if addr.get('type') == proto]) for intf in addrs: if subnet in intf: intf = ipaddress.ip_interface('{0}/{1}'.format(intf['address'], intf[subnet])) else: intf = ipaddress.ip_interface('{0}/{1}'.format(intf['address'], dflt_cidr)) if not intf.is_loopback: ret.add(intf.network) return [six.text_type(net) for net in sorted(ret)] def subnets(interfaces=None): ''' Returns a list of IPv4 subnets to which the host belongs ''' return _subnets('inet', interfaces_=interfaces) def subnets6(): ''' Returns a list of IPv6 subnets to which the host belongs ''' return _subnets('inet6') def in_subnet(cidr, addr=None): ''' Returns True if host or (any of) addrs is within specified subnet, otherwise False ''' try: cidr = ipaddress.ip_network(cidr) except ValueError: log.error('Invalid CIDR \'%s\'', cidr) return False if addr is None: addr = ip_addrs() addr.extend(ip_addrs6()) elif not isinstance(addr, (list, tuple)): addr = (addr,) return any(ipaddress.ip_address(item) in cidr for item in addr) def _ip_addrs(interface=None, include_loopback=False, interface_data=None, proto='inet'): ''' Return the full list of IP adresses matching the criteria proto = inet|inet6 ''' ret = set() ifaces = interface_data \ if isinstance(interface_data, dict) \ else interfaces() if interface is None: target_ifaces = ifaces else: target_ifaces = dict([(k, v) for k, v in six.iteritems(ifaces) if k == interface]) if not target_ifaces: log.error('Interface %s not found.', interface) for ip_info in six.itervalues(target_ifaces): addrs = ip_info.get(proto, []) addrs.extend([addr for addr in ip_info.get('secondary', []) if addr.get('type') == proto]) for addr in addrs: addr = ipaddress.ip_address(addr.get('address')) if not addr.is_loopback or include_loopback: ret.add(addr) return [six.text_type(addr) for addr in sorted(ret)] def ip_addrs(interface=None, include_loopback=False, interface_data=None): ''' Returns a list of IPv4 addresses assigned to the host. 127.0.0.1 is ignored, unless 'include_loopback=True' is indicated. If 'interface' is provided, then only IP addresses from that interface will be returned. ''' return _ip_addrs(interface, include_loopback, interface_data, 'inet') def ip_addrs6(interface=None, include_loopback=False, interface_data=None): ''' Returns a list of IPv6 addresses assigned to the host. ::1 is ignored, unless 'include_loopback=True' is indicated. If 'interface' is provided, then only IP addresses from that interface will be returned. ''' return _ip_addrs(interface, include_loopback, interface_data, 'inet6') def hex2ip(hex_ip, invert=False): ''' Convert a hex string to an ip, if a failure occurs the original hex is returned. If 'invert=True' assume that ip from /proc/net/<proto> ''' if len(hex_ip) == 32: # ipv6 ip = [] for i in range(0, 32, 8): ip_part = hex_ip[i:i + 8] ip_part = [ip_part[x:x + 2] for x in range(0, 8, 2)] if invert: ip.append("{0[3]}{0[2]}:{0[1]}{0[0]}".format(ip_part)) else: ip.append("{0[0]}{0[1]}:{0[2]}{0[3]}".format(ip_part)) try: address = ipaddress.IPv6Address(":".join(ip)) if address.ipv4_mapped: return str(address.ipv4_mapped) else: return address.compressed except ipaddress.AddressValueError as ex: log.error('hex2ip - ipv6 address error: %s', ex) return hex_ip try: hip = int(hex_ip, 16) except ValueError: return hex_ip if invert: return '{3}.{2}.{1}.{0}'.format(hip >> 24 & 255, hip >> 16 & 255, hip >> 8 & 255, hip & 255) return '{0}.{1}.{2}.{3}'.format(hip >> 24 & 255, hip >> 16 & 255, hip >> 8 & 255, hip & 255) def mac2eui64(mac, prefix=None): ''' Convert a MAC address to a EUI64 identifier or, with prefix provided, a full IPv6 address ''' # http://tools.ietf.org/html/rfc4291#section-2.5.1 eui64 = re.sub(r'[.:-]', '', mac).lower() eui64 = eui64[0:6] + 'fffe' + eui64[6:] eui64 = hex(int(eui64[0:2], 16) | 2)[2:].zfill(2) + eui64[2:] if prefix is None: return ':'.join(re.findall(r'.{4}', eui64)) else: try: net = ipaddress.ip_network(prefix, strict=False) euil = int('0x{0}'.format(eui64), 16) return '{0}/{1}'.format(net[euil], net.prefixlen) except Exception: return def active_tcp(): ''' Return a dict describing all active tcp connections as quickly as possible ''' ret = {} for statf in ['/proc/net/tcp', '/proc/net/tcp6']: if os.path.isfile(statf): with salt.utils.files.fopen(statf, 'rb') as fp_: for line in fp_: line = salt.utils.stringutils.to_unicode(line) if line.strip().startswith('sl'): continue iret = _parse_tcp_line(line) sl = next(iter(iret)) if iret[sl]['state'] == 1: # 1 is ESTABLISHED del iret[sl]['state'] ret[len(ret)] = iret[sl] return ret def local_port_tcp(port): ''' Return a set of remote ip addrs attached to the specified local port ''' ret = _remotes_on(port, 'local_port') return ret def remote_port_tcp(port): ''' Return a set of ip addrs the current host is connected to on given port ''' ret = _remotes_on(port, 'remote_port') return ret def _remotes_on(port, which_end): ''' Return a set of ip addrs active tcp connections ''' port = int(port) ret = _netlink_tool_remote_on(port, which_end) if ret is not None: return ret ret = set() proc_available = False for statf in ['/proc/net/tcp', '/proc/net/tcp6']: if os.path.isfile(statf): proc_available = True with salt.utils.files.fopen(statf, 'r') as fp_: for line in fp_: line = salt.utils.stringutils.to_unicode(line) if line.strip().startswith('sl'): continue iret = _parse_tcp_line(line) sl = next(iter(iret)) if iret[sl][which_end] == port and iret[sl]['state'] == 1: # 1 is ESTABLISHED ret.add(iret[sl]['remote_addr']) if not proc_available: # Fallback to use OS specific tools if salt.utils.platform.is_sunos(): return _sunos_remotes_on(port, which_end) if salt.utils.platform.is_freebsd(): return _freebsd_remotes_on(port, which_end) if salt.utils.platform.is_netbsd(): return _netbsd_remotes_on(port, which_end) if salt.utils.platform.is_openbsd(): return _openbsd_remotes_on(port, which_end) if salt.utils.platform.is_windows(): return _windows_remotes_on(port, which_end) if salt.utils.platform.is_aix(): return _aix_remotes_on(port, which_end) return _linux_remotes_on(port, which_end) return ret def _netlink_tool_remote_on(port, which_end): ''' Returns set of ipv4 host addresses of remote established connections on local or remote tcp port. Parses output of shell 'ss' to get connections [root@salt-master ~]# ss -ant State Recv-Q Send-Q Local Address:Port Peer Address:Port LISTEN 0 511 *:80 *:* LISTEN 0 128 *:22 *:* ESTAB 0 0 127.0.0.1:56726 127.0.0.1:4505 ''' remotes = set() valid = False try: data = subprocess.check_output(['ss', '-ant']) # pylint: disable=minimum-python-version except subprocess.CalledProcessError: log.error('Failed ss') raise except OSError: # not command "No such file or directory" return None lines = salt.utils.stringutils.to_str(data).split('\n') for line in lines: if 'Address:Port' in line: # ss tools may not be valid valid = True continue elif 'ESTAB' not in line: continue chunks = line.split() local_host, local_port = chunks[3].split(':', 1) remote_host, remote_port = chunks[4].split(':', 1) if which_end == 'remote_port' and int(remote_port) != port: continue if which_end == 'local_port' and int(local_port) != port: continue remotes.add(remote_host) if valid is False: remotes = None return remotes def _sunos_remotes_on(port, which_end): ''' SunOS specific helper function. Returns set of ipv4 host addresses of remote established connections on local or remote tcp port. Parses output of shell 'netstat' to get connections [root@salt-master ~]# netstat -f inet -n TCP: IPv4 Local Address Remote Address Swind Send-Q Rwind Recv-Q State -------------------- -------------------- ----- ------ ----- ------ ----------- 10.0.0.101.4505 10.0.0.1.45329 1064800 0 1055864 0 ESTABLISHED 10.0.0.101.4505 10.0.0.100.50798 1064800 0 1055864 0 ESTABLISHED ''' remotes = set() try: data = subprocess.check_output(['netstat', '-f', 'inet', '-n']) # pylint: disable=minimum-python-version except subprocess.CalledProcessError: log.error('Failed netstat') raise lines = salt.utils.stringutils.to_str(data).split('\n') for line in lines: if 'ESTABLISHED' not in line: continue chunks = line.split() local_host, local_port = chunks[0].rsplit('.', 1) remote_host, remote_port = chunks[1].rsplit('.', 1) if which_end == 'remote_port' and int(remote_port) != port: continue if which_end == 'local_port' and int(local_port) != port: continue remotes.add(remote_host) return remotes def _freebsd_remotes_on(port, which_end): ''' Returns set of ipv4 host addresses of remote established connections on local tcp port port. Parses output of shell 'sockstat' (FreeBSD) to get connections $ sudo sockstat -4 USER COMMAND PID FD PROTO LOCAL ADDRESS FOREIGN ADDRESS root python2.7 1456 29 tcp4 *:4505 *:* root python2.7 1445 17 tcp4 *:4506 *:* root python2.7 1294 14 tcp4 127.0.0.1:11813 127.0.0.1:4505 root python2.7 1294 41 tcp4 127.0.0.1:61115 127.0.0.1:4506 $ sudo sockstat -4 -c -p 4506 USER COMMAND PID FD PROTO LOCAL ADDRESS FOREIGN ADDRESS root python2.7 1294 41 tcp4 127.0.0.1:61115 127.0.0.1:4506 ''' port = int(port) remotes = set() try: cmd = salt.utils.args.shlex_split('sockstat -4 -c -p {0}'.format(port)) data = subprocess.check_output(cmd) # pylint: disable=minimum-python-version except subprocess.CalledProcessError as ex: log.error('Failed "sockstat" with returncode = %s', ex.returncode) raise lines = salt.utils.stringutils.to_str(data).split('\n') for line in lines: chunks = line.split() if not chunks: continue # ['root', 'python2.7', '1456', '37', 'tcp4', # '127.0.0.1:4505-', '127.0.0.1:55703'] # print chunks if 'COMMAND' in chunks[1]: continue # ignore header if len(chunks) < 2: continue # sockstat -4 -c -p 4506 does this with high PIDs: # USER COMMAND PID FD PROTO LOCAL ADDRESS FOREIGN ADDRESS # salt-master python2.781106 35 tcp4 192.168.12.34:4506 192.168.12.45:60143 local = chunks[-2] remote = chunks[-1] lhost, lport = local.split(':') rhost, rport = remote.split(':') if which_end == 'local' and int(lport) != port: # ignore if local port not port continue if which_end == 'remote' and int(rport) != port: # ignore if remote port not port continue remotes.add(rhost) return remotes def _netbsd_remotes_on(port, which_end): ''' Returns set of ipv4 host addresses of remote established connections on local tcp port port. Parses output of shell 'sockstat' (NetBSD) to get connections $ sudo sockstat -4 -n USER COMMAND PID FD PROTO LOCAL ADDRESS FOREIGN ADDRESS root python2.7 1456 29 tcp *.4505 *.* root python2.7 1445 17 tcp *.4506 *.* root python2.7 1294 14 tcp 127.0.0.1.11813 127.0.0.1.4505 root python2.7 1294 41 tcp 127.0.0.1.61115 127.0.0.1.4506 $ sudo sockstat -4 -c -n -p 4506 USER COMMAND PID FD PROTO LOCAL ADDRESS FOREIGN ADDRESS root python2.7 1294 41 tcp 127.0.0.1.61115 127.0.0.1.4506 ''' port = int(port) remotes = set() try: cmd = salt.utils.args.shlex_split('sockstat -4 -c -n -p {0}'.format(port)) data = subprocess.check_output(cmd) # pylint: disable=minimum-python-version except subprocess.CalledProcessError as ex: log.error('Failed "sockstat" with returncode = %s', ex.returncode) raise lines = salt.utils.stringutils.to_str(data).split('\n') for line in lines: chunks = line.split() if not chunks: continue # ['root', 'python2.7', '1456', '37', 'tcp', # '127.0.0.1.4505-', '127.0.0.1.55703'] # print chunks if 'COMMAND' in chunks[1]: continue # ignore header if len(chunks) < 2: continue local = chunks[5].split('.') lport = local.pop() lhost = '.'.join(local) remote = chunks[6].split('.') rport = remote.pop() rhost = '.'.join(remote) if which_end == 'local' and int(lport) != port: # ignore if local port not port continue if which_end == 'remote' and int(rport) != port: # ignore if remote port not port continue remotes.add(rhost) return remotes def _openbsd_remotes_on(port, which_end): ''' OpenBSD specific helper function. Returns set of ipv4 host addresses of remote established connections on local or remote tcp port. Parses output of shell 'netstat' to get connections $ netstat -nf inet Active Internet connections Proto Recv-Q Send-Q Local Address Foreign Address (state) tcp 0 0 10.0.0.101.4505 10.0.0.1.45329 ESTABLISHED tcp 0 0 10.0.0.101.4505 10.0.0.100.50798 ESTABLISHED ''' remotes = set() try: data = subprocess.check_output(['netstat', '-nf', 'inet']) # pylint: disable=minimum-python-version except subprocess.CalledProcessError: log.error('Failed netstat') raise lines = data.split('\n') for line in lines: if 'ESTABLISHED' not in line: continue chunks = line.split() local_host, local_port = chunks[3].rsplit('.', 1) remote_host, remote_port = chunks[4].rsplit('.', 1) if which_end == 'remote_port' and int(remote_port) != port: continue if which_end == 'local_port' and int(local_port) != port: continue remotes.add(remote_host) return remotes def _windows_remotes_on(port, which_end): r''' Windows specific helper function. Returns set of ipv4 host addresses of remote established connections on local or remote tcp port. Parses output of shell 'netstat' to get connections C:\>netstat -n Active Connections Proto Local Address Foreign Address State TCP 10.2.33.17:3007 130.164.12.233:10123 ESTABLISHED TCP 10.2.33.17:3389 130.164.30.5:10378 ESTABLISHED ''' remotes = set() try: data = subprocess.check_output(['netstat', '-n']) # pylint: disable=minimum-python-version except subprocess.CalledProcessError: log.error('Failed netstat') raise lines = salt.utils.stringutils.to_str(data).split('\n') for line in lines: if 'ESTABLISHED' not in line: continue chunks = line.split() local_host, local_port = chunks[1].rsplit(':', 1) remote_host, remote_port = chunks[2].rsplit(':', 1) if which_end == 'remote_port' and int(remote_port) != port: continue if which_end == 'local_port' and int(local_port) != port: continue remotes.add(remote_host) return remotes def _linux_remotes_on(port, which_end): ''' Linux specific helper function. Returns set of ip host addresses of remote established connections on local tcp port port. Parses output of shell 'lsof' to get connections $ sudo lsof -iTCP:4505 -n COMMAND PID USER FD TYPE DEVICE SIZE/OFF NODE NAME Python 9971 root 35u IPv4 0x18a8464a29ca329d 0t0 TCP *:4505 (LISTEN) Python 9971 root 37u IPv4 0x18a8464a29b2b29d 0t0 TCP 127.0.0.1:4505->127.0.0.1:55703 (ESTABLISHED) Python 10152 root 22u IPv4 0x18a8464a29c8cab5 0t0 TCP 127.0.0.1:55703->127.0.0.1:4505 (ESTABLISHED) Python 10153 root 22u IPv4 0x18a8464a29c8cab5 0t0 TCP [fe80::249a]:4505->[fe80::150]:59367 (ESTABLISHED) ''' remotes = set() try: data = subprocess.check_output( ['lsof', '-iTCP:{0:d}'.format(port), '-n', '-P'] # pylint: disable=minimum-python-version ) except subprocess.CalledProcessError as ex: if ex.returncode == 1: # Lsof return 1 if any error was detected, including the failure # to locate Internet addresses, and it is not an error in this case. log.warning('"lsof" returncode = 1, likely no active TCP sessions.') return remotes log.error('Failed "lsof" with returncode = %s', ex.returncode) raise lines = salt.utils.stringutils.to_str(data).split('\n') for line in lines: chunks = line.split() if not chunks: continue # ['Python', '9971', 'root', '37u', 'IPv4', '0x18a8464a29b2b29d', '0t0', # 'TCP', '127.0.0.1:4505->127.0.0.1:55703', '(ESTABLISHED)'] # print chunks if 'COMMAND' in chunks[0]: continue # ignore header if 'ESTABLISHED' not in chunks[-1]: continue # ignore if not ESTABLISHED # '127.0.0.1:4505->127.0.0.1:55703' local, remote = chunks[8].split('->') _, lport = local.rsplit(':', 1) rhost, rport = remote.rsplit(':', 1) if which_end == 'remote_port' and int(rport) != port: continue if which_end == 'local_port' and int(lport) != port: continue remotes.add(rhost.strip("[]")) return remotes def _aix_remotes_on(port, which_end): ''' AIX specific helper function. Returns set of ipv4 host addresses of remote established connections on local or remote tcp port. Parses output of shell 'netstat' to get connections root@la68pp002_pub:/opt/salt/lib/python2.7/site-packages/salt/modules# netstat -f inet -n Active Internet connections Proto Recv-Q Send-Q Local Address Foreign Address (state) tcp4 0 0 172.29.149.95.50093 209.41.78.13.4505 ESTABLISHED tcp4 0 0 127.0.0.1.9514 *.* LISTEN tcp4 0 0 127.0.0.1.9515 *.* LISTEN tcp4 0 0 127.0.0.1.199 127.0.0.1.32779 ESTABLISHED tcp4 0 0 127.0.0.1.32779 127.0.0.1.199 ESTABLISHED tcp4 0 40 172.29.149.95.22 172.29.96.83.41022 ESTABLISHED tcp4 0 0 172.29.149.95.22 172.29.96.83.41032 ESTABLISHED tcp4 0 0 127.0.0.1.32771 127.0.0.1.32775 ESTABLISHED tcp 0 0 127.0.0.1.32775 127.0.0.1.32771 ESTABLISHED tcp4 0 0 127.0.0.1.32771 127.0.0.1.32776 ESTABLISHED tcp 0 0 127.0.0.1.32776 127.0.0.1.32771 ESTABLISHED tcp4 0 0 127.0.0.1.32771 127.0.0.1.32777 ESTABLISHED tcp 0 0 127.0.0.1.32777 127.0.0.1.32771 ESTABLISHED tcp4 0 0 127.0.0.1.32771 127.0.0.1.32778 ESTABLISHED tcp 0 0 127.0.0.1.32778 127.0.0.1.32771 ESTABLISHED ''' remotes = set() try: data = subprocess.check_output(['netstat', '-f', 'inet', '-n']) # pylint: disable=minimum-python-version except subprocess.CalledProcessError: log.error('Failed netstat') raise lines = salt.utils.stringutils.to_str(data).split('\n') for line in lines: if 'ESTABLISHED' not in line: continue chunks = line.split() local_host, local_port = chunks[3].rsplit('.', 1) remote_host, remote_port = chunks[4].rsplit('.', 1) if which_end == 'remote_port' and int(remote_port) != port: continue if which_end == 'local_port' and int(local_port) != port: continue remotes.add(remote_host) return remotes @jinja_filter('gen_mac') def gen_mac(prefix='AC:DE:48'): ''' Generates a MAC address with the defined OUI prefix. Common prefixes: - ``00:16:3E`` -- Xen - ``00:18:51`` -- OpenVZ - ``00:50:56`` -- VMware (manually generated) - ``52:54:00`` -- QEMU/KVM - ``AC:DE:48`` -- PRIVATE References: - http://standards.ieee.org/develop/regauth/oui/oui.txt - https://www.wireshark.org/tools/oui-lookup.html - https://en.wikipedia.org/wiki/MAC_address ''' return '{0}:{1:02X}:{2:02X}:{3:02X}'.format(prefix, random.randint(0, 0xff), random.randint(0, 0xff), random.randint(0, 0xff)) @jinja_filter('mac_str_to_bytes') def mac_str_to_bytes(mac_str): ''' Convert a MAC address string into bytes. Works with or without separators: b1 = mac_str_to_bytes('08:00:27:13:69:77') b2 = mac_str_to_bytes('080027136977') assert b1 == b2 assert isinstance(b1, bytes) ''' if len(mac_str) == 12: pass elif len(mac_str) == 17: sep = mac_str[2] mac_str = mac_str.replace(sep, '') else: raise ValueError('Invalid MAC address') chars = (int(mac_str[s:s+2], 16) for s in range(0, 12, 2)) return bytes(chars) if six.PY3 else b''.join(chr(x) for x in chars) def refresh_dns(): ''' issue #21397: force glibc to re-read resolv.conf ''' try: res_init() except NameError: # Exception raised loading the library, thus res_init is not defined pass @jinja_filter('connection_check') def connection_check(addr, port=80, safe=False, ipv6=None): ''' Provides a convenient alias for the dns_check filter. ''' return dns_check(addr, port, safe, ipv6) @jinja_filter('dns_check') def dns_check(addr, port=80, safe=False, ipv6=None, attempt_connect=True): ''' Return the ip resolved by dns, but do not exit on failure, only raise an exception. Obeys system preference for IPv4/6 address resolution - this can be overridden by the ipv6 flag. Tries to connect to the address before considering it useful. If no address can be reached, the first one resolved is used as a fallback. ''' error = False lookup = addr seen_ipv6 = False family = socket.AF_INET6 if ipv6 else socket.AF_INET if ipv6 is False else socket.AF_UNSPEC hostnames = [] try: refresh_dns() hostnames = socket.getaddrinfo(addr, port, family, socket.SOCK_STREAM) except TypeError: err = ('Attempt to resolve address \'{0}\' failed. Invalid or unresolveable address').format(lookup) raise SaltSystemExit(code=42, msg=err) except socket.error: error = True # If ipv6 is set to True, attempt another lookup using the IPv4 family, # just in case we're attempting to lookup an IPv4 IP # as an IPv6 hostname. if error and ipv6: try: refresh_dns() hostnames = socket.getaddrinfo(addr, port, socket.AF_INET, socket.SOCK_STREAM) except TypeError: err = ('Attempt to resolve address \'{0}\' failed. Invalid or unresolveable address').format(lookup) raise SaltSystemExit(code=42, msg=err) except socket.error: error = True try: if not hostnames: error = True else: resolved = False candidates = [] for h in hostnames: # Input is IP address, passed through unchanged, just return it if h[4][0] == addr: resolved = salt.utils.zeromq.ip_bracket(addr) break candidate_addr = salt.utils.zeromq.ip_bracket(h[4][0]) # sometimes /etc/hosts contains ::1 localhost if not ipv6 and candidate_addr == '[::1]': continue candidates.append(candidate_addr) if attempt_connect: try: s = socket.socket(h[0], socket.SOCK_STREAM) s.settimeout(2) s.connect((candidate_addr.strip('[]'), h[4][1])) s.close() resolved = candidate_addr break except socket.error: pass if not resolved: if candidates: resolved = candidates[0] else: error = True except TypeError: err = ('Attempt to resolve address \'{0}\' failed. Invalid or unresolveable address').format(lookup) raise SaltSystemExit(code=42, msg=err) except socket.error: error = True if error: err = ('DNS lookup or connection check of \'{0}\' failed.').format(addr) if safe: if salt.log.is_console_configured(): # If logging is not configured it also means that either # the master or minion instance calling this hasn't even # started running log.error(err) raise SaltClientError() raise SaltSystemExit(code=42, msg=err) return resolved def parse_host_port(host_port): """ Takes a string argument specifying host or host:port. Returns a (hostname, port) or (ip_address, port) tuple. If no port is given, the second (port) element of the returned tuple will be None. host:port argument, for example, is accepted in the forms of: - hostname - hostname:1234 - hostname.domain.tld - hostname.domain.tld:5678 - [1234::5]:5678 - 1234::5 - 10.11.12.13:4567 - 10.11.12.13 """ host, port = None, None # default _s_ = host_port[:] if _s_[0] == "[": if "]" in host_port: host, _s_ = _s_.lstrip("[").rsplit("]", 1) host = ipaddress.IPv6Address(host).compressed if _s_[0] == ":": port = int(_s_.lstrip(":")) else: if len(_s_) > 1: raise ValueError('found ambiguous "{}" port in "{}"'.format(_s_, host_port)) else: if _s_.count(":") == 1: host, _hostport_separator_, port = _s_.partition(":") try: port = int(port) except ValueError as _e_: log.error('host_port "%s" port value "%s" is not an integer.', host_port, port) raise _e_ else: host = _s_ try: if not isinstance(host, ipaddress._BaseAddress): host_ip = ipaddress.ip_address(host).compressed host = host_ip except ValueError: log.debug('"%s" Not an IP address? Assuming it is a hostname.', host) if host != sanitize_host(host): log.error('bad hostname: "%s"', host) raise ValueError('bad hostname: "{}"'.format(host)) return host, port def is_fqdn(hostname): """ Verify if hostname conforms to be a FQDN. :param hostname: text string with the name of the host :return: bool, True if hostname is correct FQDN, False otherwise """ compliant = re.compile(r"(?!-)[A-Z\d\-\_]{1,63}(?<!-)$", re.IGNORECASE) return "." in hostname and len(hostname) < 0xff and all(compliant.match(x) for x in hostname.rstrip(".").split("."))
saltstack/salt
salt/utils/network.py
_netlink_tool_remote_on
python
def _netlink_tool_remote_on(port, which_end): ''' Returns set of ipv4 host addresses of remote established connections on local or remote tcp port. Parses output of shell 'ss' to get connections [root@salt-master ~]# ss -ant State Recv-Q Send-Q Local Address:Port Peer Address:Port LISTEN 0 511 *:80 *:* LISTEN 0 128 *:22 *:* ESTAB 0 0 127.0.0.1:56726 127.0.0.1:4505 ''' remotes = set() valid = False try: data = subprocess.check_output(['ss', '-ant']) # pylint: disable=minimum-python-version except subprocess.CalledProcessError: log.error('Failed ss') raise except OSError: # not command "No such file or directory" return None lines = salt.utils.stringutils.to_str(data).split('\n') for line in lines: if 'Address:Port' in line: # ss tools may not be valid valid = True continue elif 'ESTAB' not in line: continue chunks = line.split() local_host, local_port = chunks[3].split(':', 1) remote_host, remote_port = chunks[4].split(':', 1) if which_end == 'remote_port' and int(remote_port) != port: continue if which_end == 'local_port' and int(local_port) != port: continue remotes.add(remote_host) if valid is False: remotes = None return remotes
Returns set of ipv4 host addresses of remote established connections on local or remote tcp port. Parses output of shell 'ss' to get connections [root@salt-master ~]# ss -ant State Recv-Q Send-Q Local Address:Port Peer Address:Port LISTEN 0 511 *:80 *:* LISTEN 0 128 *:22 *:* ESTAB 0 0 127.0.0.1:56726 127.0.0.1:4505
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/network.py#L1462-L1504
null
# -*- coding: utf-8 -*- ''' Define some generic socket functions for network modules ''' # Import python libs from __future__ import absolute_import, unicode_literals, print_function import itertools import os import re import types import socket import logging import platform import random import subprocess from string import ascii_letters, digits # Import 3rd-party libs from salt.ext import six from salt.ext.six.moves import range # pylint: disable=import-error,redefined-builtin # Attempt to import wmi try: import wmi import salt.utils.winapi except ImportError: pass # Import salt libs import salt.utils.args import salt.utils.files import salt.utils.path import salt.utils.platform import salt.utils.stringutils import salt.utils.zeromq from salt._compat import ipaddress from salt.exceptions import SaltClientError, SaltSystemExit from salt.utils.decorators.jinja import jinja_filter from salt.utils.versions import LooseVersion # inet_pton does not exist in Windows, this is a workaround if salt.utils.platform.is_windows(): from salt.ext import win_inet_pton # pylint: disable=unused-import log = logging.getLogger(__name__) try: import ctypes import ctypes.util libc = ctypes.cdll.LoadLibrary(ctypes.util.find_library("c")) res_init = libc.__res_init except (ImportError, OSError, AttributeError, TypeError): pass # pylint: disable=C0103 def sanitize_host(host): ''' Sanitize host string. https://tools.ietf.org/html/rfc1123#section-2.1 ''' RFC952_characters = ascii_letters + digits + ".-" return "".join([c for c in host[0:255] if c in RFC952_characters]) def isportopen(host, port): ''' Return status of a port ''' if not 1 <= int(port) <= 65535: return False sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) out = sock.connect_ex((sanitize_host(host), int(port))) return out def host_to_ips(host): ''' Returns a list of IP addresses of a given hostname or None if not found. ''' ips = [] try: for family, socktype, proto, canonname, sockaddr in socket.getaddrinfo( host, 0, socket.AF_UNSPEC, socket.SOCK_STREAM): if family == socket.AF_INET: ip, port = sockaddr elif family == socket.AF_INET6: ip, port, flow_info, scope_id = sockaddr ips.append(ip) if not ips: ips = None except Exception: ips = None return ips def _generate_minion_id(): ''' Get list of possible host names and convention names. :return: ''' # There are three types of hostnames: # 1. Network names. How host is accessed from the network. # 2. Host aliases. They might be not available in all the network or only locally (/etc/hosts) # 3. Convention names, an internal nodename. class DistinctList(list): ''' List, which allows one to append only distinct objects. Needs to work on Python 2.6, because of collections.OrderedDict only since 2.7 version. Override 'filter()' for custom filtering. ''' localhost_matchers = [r'localhost.*', r'ip6-.*', r'127[.]\d', r'0\.0\.0\.0', r'::1.*', r'ipv6-.*', r'fe00::.*', r'fe02::.*', r'1.0.0.*.ip6.arpa'] def append(self, p_object): if p_object and p_object not in self and not self.filter(p_object): super(DistinctList, self).append(p_object) return self def extend(self, iterable): for obj in iterable: self.append(obj) return self def filter(self, element): 'Returns True if element needs to be filtered' for rgx in self.localhost_matchers: if re.match(rgx, element): return True def first(self): return self and self[0] or None hostname = socket.gethostname() hosts = DistinctList().append( salt.utils.stringutils.to_unicode(socket.getfqdn(salt.utils.stringutils.to_bytes(hostname))) ).append(platform.node()).append(hostname) if not hosts: try: for a_nfo in socket.getaddrinfo(hosts.first() or 'localhost', None, socket.AF_INET, socket.SOCK_RAW, socket.IPPROTO_IP, socket.AI_CANONNAME): if len(a_nfo) > 3: hosts.append(a_nfo[3]) except socket.gaierror: log.warning('Cannot resolve address %s info via socket: %s', hosts.first() or 'localhost (N/A)', socket.gaierror) # Universal method for everywhere (Linux, Slowlaris, Windows etc) for f_name in ('/etc/hostname', '/etc/nodename', '/etc/hosts', r'{win}\system32\drivers\etc\hosts'.format(win=os.getenv('WINDIR'))): try: with salt.utils.files.fopen(f_name) as f_hdl: for line in f_hdl: line = salt.utils.stringutils.to_unicode(line) hst = line.strip().split('#')[0].strip().split() if hst: if hst[0][:4] in ('127.', '::1') or len(hst) == 1: hosts.extend(hst) except IOError: pass # include public and private ipaddresses return hosts.extend([addr for addr in ip_addrs() if not ipaddress.ip_address(addr).is_loopback]) def generate_minion_id(): ''' Return only first element of the hostname from all possible list. :return: ''' try: ret = salt.utils.stringutils.to_unicode(_generate_minion_id().first()) except TypeError: ret = None return ret or 'localhost' def get_socket(addr, type=socket.SOCK_STREAM, proto=0): ''' Return a socket object for the addr IP-version agnostic ''' version = ipaddress.ip_address(addr).version if version == 4: family = socket.AF_INET elif version == 6: family = socket.AF_INET6 return socket.socket(family, type, proto) def get_fqhostname(): ''' Returns the fully qualified hostname ''' # try getaddrinfo() fqdn = None try: addrinfo = socket.getaddrinfo( socket.gethostname(), 0, socket.AF_UNSPEC, socket.SOCK_STREAM, socket.SOL_TCP, socket.AI_CANONNAME ) for info in addrinfo: # info struct [family, socktype, proto, canonname, sockaddr] # On Windows `canonname` can be an empty string # This can cause the function to return `None` if len(info) > 3 and info[3]: fqdn = info[3] break except socket.gaierror: pass # NOTE: this used to log.error() but it was later disabled except socket.error as err: log.debug('socket.getaddrinfo() failure while finding fqdn: %s', err) if fqdn is None: fqdn = socket.getfqdn() return fqdn def ip_to_host(ip): ''' Returns the hostname of a given IP ''' try: hostname, aliaslist, ipaddrlist = socket.gethostbyaddr(ip) except Exception as exc: log.debug('salt.utils.network.ip_to_host(%r) failed: %s', ip, exc) hostname = None return hostname # pylint: enable=C0103 def is_reachable_host(entity_name): ''' Returns a bool telling if the entity name is a reachable host (IPv4/IPv6/FQDN/etc). :param hostname: :return: ''' try: assert type(socket.getaddrinfo(entity_name, 0, 0, 0, 0)) == list ret = True except socket.gaierror: ret = False return ret def is_ip(ip): ''' Returns a bool telling if the passed IP is a valid IPv4 or IPv6 address. ''' return is_ipv4(ip) or is_ipv6(ip) def is_ipv4(ip): ''' Returns a bool telling if the value passed to it was a valid IPv4 address ''' try: return ipaddress.ip_address(ip).version == 4 except ValueError: return False def is_ipv6(ip): ''' Returns a bool telling if the value passed to it was a valid IPv6 address ''' try: return ipaddress.ip_address(ip).version == 6 except ValueError: return False def is_subnet(cidr): ''' Returns a bool telling if the passed string is an IPv4 or IPv6 subnet ''' return is_ipv4_subnet(cidr) or is_ipv6_subnet(cidr) def is_ipv4_subnet(cidr): ''' Returns a bool telling if the passed string is an IPv4 subnet ''' try: return '/' in cidr and bool(ipaddress.IPv4Network(cidr)) except Exception: return False def is_ipv6_subnet(cidr): ''' Returns a bool telling if the passed string is an IPv6 subnet ''' try: return '/' in cidr and bool(ipaddress.IPv6Network(cidr)) except Exception: return False @jinja_filter('is_ip') def is_ip_filter(ip, options=None): ''' Returns a bool telling if the passed IP is a valid IPv4 or IPv6 address. ''' return is_ipv4_filter(ip, options=options) or is_ipv6_filter(ip, options=options) def _ip_options_global(ip_obj, version): return not ip_obj.is_private def _ip_options_multicast(ip_obj, version): return ip_obj.is_multicast def _ip_options_loopback(ip_obj, version): return ip_obj.is_loopback def _ip_options_link_local(ip_obj, version): return ip_obj.is_link_local def _ip_options_private(ip_obj, version): return ip_obj.is_private def _ip_options_reserved(ip_obj, version): return ip_obj.is_reserved def _ip_options_site_local(ip_obj, version): if version == 6: return ip_obj.is_site_local return False def _ip_options_unspecified(ip_obj, version): return ip_obj.is_unspecified def _ip_options(ip_obj, version, options=None): # will process and IP options options_fun_map = { 'global': _ip_options_global, 'link-local': _ip_options_link_local, 'linklocal': _ip_options_link_local, 'll': _ip_options_link_local, 'link_local': _ip_options_link_local, 'loopback': _ip_options_loopback, 'lo': _ip_options_loopback, 'multicast': _ip_options_multicast, 'private': _ip_options_private, 'public': _ip_options_global, 'reserved': _ip_options_reserved, 'site-local': _ip_options_site_local, 'sl': _ip_options_site_local, 'site_local': _ip_options_site_local, 'unspecified': _ip_options_unspecified } if not options: return six.text_type(ip_obj) # IP version already checked options_list = [option.strip() for option in options.split(',')] for option, fun in options_fun_map.items(): if option in options_list: fun_res = fun(ip_obj, version) if not fun_res: return None # stop at first failed test # else continue return six.text_type(ip_obj) def _is_ipv(ip, version, options=None): if not version: version = 4 if version not in (4, 6): return None try: ip_obj = ipaddress.ip_address(ip) except ValueError: # maybe it is an IP network try: ip_obj = ipaddress.ip_interface(ip) except ValueError: # nope, still not :( return None if not ip_obj.version == version: return None # has the right version, let's move on return _ip_options(ip_obj, version, options=options) @jinja_filter('is_ipv4') def is_ipv4_filter(ip, options=None): ''' Returns a bool telling if the value passed to it was a valid IPv4 address. ip The IP address. net: False Consider IP addresses followed by netmask. options CSV of options regarding the nature of the IP address. E.g.: loopback, multicast, private etc. ''' _is_ipv4 = _is_ipv(ip, 4, options=options) return isinstance(_is_ipv4, six.string_types) @jinja_filter('is_ipv6') def is_ipv6_filter(ip, options=None): ''' Returns a bool telling if the value passed to it was a valid IPv6 address. ip The IP address. net: False Consider IP addresses followed by netmask. options CSV of options regarding the nature of the IP address. E.g.: loopback, multicast, private etc. ''' _is_ipv6 = _is_ipv(ip, 6, options=options) return isinstance(_is_ipv6, six.string_types) def _ipv_filter(value, version, options=None): if version not in (4, 6): return if isinstance(value, (six.string_types, six.text_type, six.binary_type)): return _is_ipv(value, version, options=options) # calls is_ipv4 or is_ipv6 for `value` elif isinstance(value, (list, tuple, types.GeneratorType)): # calls is_ipv4 or is_ipv6 for each element in the list # os it filters and returns only those elements having the desired IP version return [ _is_ipv(addr, version, options=options) for addr in value if _is_ipv(addr, version, options=options) is not None ] return None @jinja_filter('ipv4') def ipv4(value, options=None): ''' Filters a list and returns IPv4 values only. ''' return _ipv_filter(value, 4, options=options) @jinja_filter('ipv6') def ipv6(value, options=None): ''' Filters a list and returns IPv6 values only. ''' return _ipv_filter(value, 6, options=options) @jinja_filter('ipaddr') def ipaddr(value, options=None): ''' Filters and returns only valid IP objects. ''' ipv4_obj = ipv4(value, options=options) ipv6_obj = ipv6(value, options=options) if ipv4_obj is None or ipv6_obj is None: # an IP address can be either IPv4 either IPv6 # therefofe if the value passed as arg is not a list, at least one of the calls above will return None # if one of them is none, means that we should return only one of them return ipv4_obj or ipv6_obj # one of them else: return ipv4_obj + ipv6_obj # extend lists def _filter_ipaddr(value, options, version=None): ipaddr_filter_out = None if version: if version == 4: ipaddr_filter_out = ipv4(value, options) elif version == 6: ipaddr_filter_out = ipv6(value, options) else: ipaddr_filter_out = ipaddr(value, options) if not ipaddr_filter_out: return if not isinstance(ipaddr_filter_out, (list, tuple, types.GeneratorType)): ipaddr_filter_out = [ipaddr_filter_out] return ipaddr_filter_out @jinja_filter('ip_host') def ip_host(value, options=None, version=None): ''' Returns the interfaces IP address, e.g.: 192.168.0.1/28. ''' ipaddr_filter_out = _filter_ipaddr(value, options=options, version=version) if not ipaddr_filter_out: return if not isinstance(value, (list, tuple, types.GeneratorType)): return six.text_type(ipaddress.ip_interface(ipaddr_filter_out[0])) return [six.text_type(ipaddress.ip_interface(ip_a)) for ip_a in ipaddr_filter_out] def _network_hosts(ip_addr_entry): return [ six.text_type(host) for host in ipaddress.ip_network(ip_addr_entry, strict=False).hosts() ] @jinja_filter('network_hosts') def network_hosts(value, options=None, version=None): ''' Return the list of hosts within a network. .. note:: When running this command with a large IPv6 network, the command will take a long time to gather all of the hosts. ''' ipaddr_filter_out = _filter_ipaddr(value, options=options, version=version) if not ipaddr_filter_out: return if not isinstance(value, (list, tuple, types.GeneratorType)): return _network_hosts(ipaddr_filter_out[0]) return [ _network_hosts(ip_a) for ip_a in ipaddr_filter_out ] def _network_size(ip_addr_entry): return ipaddress.ip_network(ip_addr_entry, strict=False).num_addresses @jinja_filter('network_size') def network_size(value, options=None, version=None): ''' Get the size of a network. ''' ipaddr_filter_out = _filter_ipaddr(value, options=options, version=version) if not ipaddr_filter_out: return if not isinstance(value, (list, tuple, types.GeneratorType)): return _network_size(ipaddr_filter_out[0]) return [ _network_size(ip_a) for ip_a in ipaddr_filter_out ] def natural_ipv4_netmask(ip, fmt='prefixlen'): ''' Returns the "natural" mask of an IPv4 address ''' bits = _ipv4_to_bits(ip) if bits.startswith('11'): mask = '24' elif bits.startswith('1'): mask = '16' else: mask = '8' if fmt == 'netmask': return cidr_to_ipv4_netmask(mask) else: return '/' + mask def rpad_ipv4_network(ip): ''' Returns an IP network address padded with zeros. Ex: '192.168.3' -> '192.168.3.0' '10.209' -> '10.209.0.0' ''' return '.'.join(itertools.islice(itertools.chain(ip.split('.'), '0000'), 0, 4)) def cidr_to_ipv4_netmask(cidr_bits): ''' Returns an IPv4 netmask ''' try: cidr_bits = int(cidr_bits) if not 1 <= cidr_bits <= 32: return '' except ValueError: return '' netmask = '' for idx in range(4): if idx: netmask += '.' if cidr_bits >= 8: netmask += '255' cidr_bits -= 8 else: netmask += '{0:d}'.format(256 - (2 ** (8 - cidr_bits))) cidr_bits = 0 return netmask def _number_of_set_bits_to_ipv4_netmask(set_bits): # pylint: disable=C0103 ''' Returns an IPv4 netmask from the integer representation of that mask. Ex. 0xffffff00 -> '255.255.255.0' ''' return cidr_to_ipv4_netmask(_number_of_set_bits(set_bits)) # pylint: disable=C0103 def _number_of_set_bits(x): ''' Returns the number of bits that are set in a 32bit int ''' # Taken from http://stackoverflow.com/a/4912729. Many thanks! x -= (x >> 1) & 0x55555555 x = ((x >> 2) & 0x33333333) + (x & 0x33333333) x = ((x >> 4) + x) & 0x0f0f0f0f x += x >> 8 x += x >> 16 return x & 0x0000003f # pylint: enable=C0103 def _interfaces_ip(out): ''' Uses ip to return a dictionary of interfaces with various information about each (up/down state, ip address, netmask, and hwaddr) ''' ret = dict() def parse_network(value, cols): ''' Return a tuple of ip, netmask, broadcast based on the current set of cols ''' brd = None scope = None if '/' in value: # we have a CIDR in this address ip, cidr = value.split('/') # pylint: disable=C0103 else: ip = value # pylint: disable=C0103 cidr = 32 if type_ == 'inet': mask = cidr_to_ipv4_netmask(int(cidr)) if 'brd' in cols: brd = cols[cols.index('brd') + 1] elif type_ == 'inet6': mask = cidr if 'scope' in cols: scope = cols[cols.index('scope') + 1] return (ip, mask, brd, scope) groups = re.compile('\r?\n\\d').split(out) for group in groups: iface = None data = dict() for line in group.splitlines(): if ' ' not in line: continue match = re.match(r'^\d*:\s+([\w.\-]+)(?:@)?([\w.\-]+)?:\s+<(.+)>', line) if match: iface, parent, attrs = match.groups() if 'UP' in attrs.split(','): data['up'] = True else: data['up'] = False if parent: data['parent'] = parent continue cols = line.split() if len(cols) >= 2: type_, value = tuple(cols[0:2]) iflabel = cols[-1:][0] if type_ in ('inet', 'inet6'): if 'secondary' not in cols: ipaddr, netmask, broadcast, scope = parse_network(value, cols) if type_ == 'inet': if 'inet' not in data: data['inet'] = list() addr_obj = dict() addr_obj['address'] = ipaddr addr_obj['netmask'] = netmask addr_obj['broadcast'] = broadcast addr_obj['label'] = iflabel data['inet'].append(addr_obj) elif type_ == 'inet6': if 'inet6' not in data: data['inet6'] = list() addr_obj = dict() addr_obj['address'] = ipaddr addr_obj['prefixlen'] = netmask addr_obj['scope'] = scope data['inet6'].append(addr_obj) else: if 'secondary' not in data: data['secondary'] = list() ip_, mask, brd, scp = parse_network(value, cols) data['secondary'].append({ 'type': type_, 'address': ip_, 'netmask': mask, 'broadcast': brd, 'label': iflabel, }) del ip_, mask, brd, scp elif type_.startswith('link'): data['hwaddr'] = value if iface: ret[iface] = data del iface, data return ret def _interfaces_ifconfig(out): ''' Uses ifconfig to return a dictionary of interfaces with various information about each (up/down state, ip address, netmask, and hwaddr) ''' ret = dict() piface = re.compile(r'^([^\s:]+)') pmac = re.compile('.*?(?:HWaddr|ether|address:|lladdr) ([0-9a-fA-F:]+)') if salt.utils.platform.is_sunos(): pip = re.compile(r'.*?(?:inet\s+)([0-9]+\.[0-9]+\.[0-9]+\.[0-9]+)(.*)') pip6 = re.compile('.*?(?:inet6 )([0-9a-fA-F:]+)') pmask6 = re.compile(r'.*?(?:inet6 [0-9a-fA-F:]+/(\d+)).*') else: pip = re.compile(r'.*?(?:inet addr:|inet [^\d]*)(.*?)\s') pip6 = re.compile('.*?(?:inet6 addr: (.*?)/|inet6 )([0-9a-fA-F:]+)') pmask6 = re.compile(r'.*?(?:inet6 addr: [0-9a-fA-F:]+/(\d+)|prefixlen (\d+))(?: Scope:([a-zA-Z]+)| scopeid (0x[0-9a-fA-F]))?') pmask = re.compile(r'.*?(?:Mask:|netmask )(?:((?:0x)?[0-9a-fA-F]{8})|([\d\.]+))') pupdown = re.compile('UP') pbcast = re.compile(r'.*?(?:Bcast:|broadcast )([\d\.]+)') groups = re.compile('\r?\n(?=\\S)').split(out) for group in groups: data = dict() iface = '' updown = False for line in group.splitlines(): miface = piface.match(line) mmac = pmac.match(line) mip = pip.match(line) mip6 = pip6.match(line) mupdown = pupdown.search(line) if miface: iface = miface.group(1) if mmac: data['hwaddr'] = mmac.group(1) if salt.utils.platform.is_sunos(): expand_mac = [] for chunk in data['hwaddr'].split(':'): expand_mac.append('0{0}'.format(chunk) if len(chunk) < 2 else '{0}'.format(chunk)) data['hwaddr'] = ':'.join(expand_mac) if mip: if 'inet' not in data: data['inet'] = list() addr_obj = dict() addr_obj['address'] = mip.group(1) mmask = pmask.match(line) if mmask: if mmask.group(1): mmask = _number_of_set_bits_to_ipv4_netmask( int(mmask.group(1), 16)) else: mmask = mmask.group(2) addr_obj['netmask'] = mmask mbcast = pbcast.match(line) if mbcast: addr_obj['broadcast'] = mbcast.group(1) data['inet'].append(addr_obj) if mupdown: updown = True if mip6: if 'inet6' not in data: data['inet6'] = list() addr_obj = dict() addr_obj['address'] = mip6.group(1) or mip6.group(2) mmask6 = pmask6.match(line) if mmask6: addr_obj['prefixlen'] = mmask6.group(1) or mmask6.group(2) if not salt.utils.platform.is_sunos(): ipv6scope = mmask6.group(3) or mmask6.group(4) addr_obj['scope'] = ipv6scope.lower() if ipv6scope is not None else ipv6scope # SunOS sometimes has ::/0 as inet6 addr when using addrconf if not salt.utils.platform.is_sunos() \ or addr_obj['address'] != '::' \ and addr_obj['prefixlen'] != 0: data['inet6'].append(addr_obj) data['up'] = updown if iface in ret: # SunOS optimization, where interfaces occur twice in 'ifconfig -a' # output with the same name: for ipv4 and then for ipv6 addr family. # Every instance has it's own 'UP' status and we assume that ipv4 # status determines global interface status. # # merge items with higher priority for older values # after that merge the inet and inet6 sub items for both ret[iface] = dict(list(data.items()) + list(ret[iface].items())) if 'inet' in data: ret[iface]['inet'].extend(x for x in data['inet'] if x not in ret[iface]['inet']) if 'inet6' in data: ret[iface]['inet6'].extend(x for x in data['inet6'] if x not in ret[iface]['inet6']) else: ret[iface] = data del data return ret def linux_interfaces(): ''' Obtain interface information for *NIX/BSD variants ''' ifaces = dict() ip_path = salt.utils.path.which('ip') ifconfig_path = None if ip_path else salt.utils.path.which('ifconfig') if ip_path: cmd1 = subprocess.Popen( '{0} link show'.format(ip_path), shell=True, close_fds=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT).communicate()[0] cmd2 = subprocess.Popen( '{0} addr show'.format(ip_path), shell=True, close_fds=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT).communicate()[0] ifaces = _interfaces_ip("{0}\n{1}".format( salt.utils.stringutils.to_str(cmd1), salt.utils.stringutils.to_str(cmd2))) elif ifconfig_path: cmd = subprocess.Popen( '{0} -a'.format(ifconfig_path), shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT).communicate()[0] ifaces = _interfaces_ifconfig(salt.utils.stringutils.to_str(cmd)) return ifaces def _netbsd_interfaces_ifconfig(out): ''' Uses ifconfig to return a dictionary of interfaces with various information about each (up/down state, ip address, netmask, and hwaddr) ''' ret = dict() piface = re.compile(r'^([^\s:]+)') pmac = re.compile('.*?address: ([0-9a-f:]+)') pip = re.compile(r'.*?inet [^\d]*(.*?)/([\d]*)\s') pip6 = re.compile(r'.*?inet6 ([0-9a-f:]+)%([a-zA-Z0-9]*)/([\d]*)\s') pupdown = re.compile('UP') pbcast = re.compile(r'.*?broadcast ([\d\.]+)') groups = re.compile('\r?\n(?=\\S)').split(out) for group in groups: data = dict() iface = '' updown = False for line in group.splitlines(): miface = piface.match(line) mmac = pmac.match(line) mip = pip.match(line) mip6 = pip6.match(line) mupdown = pupdown.search(line) if miface: iface = miface.group(1) if mmac: data['hwaddr'] = mmac.group(1) if mip: if 'inet' not in data: data['inet'] = list() addr_obj = dict() addr_obj['address'] = mip.group(1) mmask = mip.group(2) if mip.group(2): addr_obj['netmask'] = cidr_to_ipv4_netmask(mip.group(2)) mbcast = pbcast.match(line) if mbcast: addr_obj['broadcast'] = mbcast.group(1) data['inet'].append(addr_obj) if mupdown: updown = True if mip6: if 'inet6' not in data: data['inet6'] = list() addr_obj = dict() addr_obj['address'] = mip6.group(1) mmask6 = mip6.group(3) addr_obj['scope'] = mip6.group(2) addr_obj['prefixlen'] = mip6.group(3) data['inet6'].append(addr_obj) data['up'] = updown ret[iface] = data del data return ret def netbsd_interfaces(): ''' Obtain interface information for NetBSD >= 8 where the ifconfig output diverged from other BSD variants (Netmask is now part of the address) ''' # NetBSD versions prior to 8.0 can still use linux_interfaces() if LooseVersion(os.uname()[2]) < LooseVersion('8.0'): return linux_interfaces() ifconfig_path = salt.utils.path.which('ifconfig') cmd = subprocess.Popen( '{0} -a'.format(ifconfig_path), shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT).communicate()[0] return _netbsd_interfaces_ifconfig(salt.utils.stringutils.to_str(cmd)) def _interfaces_ipconfig(out): ''' Returns a dictionary of interfaces with various information about each (up/down state, ip address, netmask, and hwaddr) NOTE: This is not used by any function and may be able to be removed in the future. ''' ifaces = dict() iface = None adapter_iface_regex = re.compile(r'adapter (\S.+):$') for line in out.splitlines(): if not line: continue # TODO what does Windows call Infiniband and 10/40gige adapters if line.startswith('Ethernet'): iface = ifaces[adapter_iface_regex.search(line).group(1)] iface['up'] = True addr = None continue if iface: key, val = line.split(',', 1) key = key.strip(' .') val = val.strip() if addr and key == 'Subnet Mask': addr['netmask'] = val elif key in ('IP Address', 'IPv4 Address'): if 'inet' not in iface: iface['inet'] = list() addr = {'address': val.rstrip('(Preferred)'), 'netmask': None, 'broadcast': None} # TODO find the broadcast iface['inet'].append(addr) elif 'IPv6 Address' in key: if 'inet6' not in iface: iface['inet'] = list() # XXX What is the prefixlen!? addr = {'address': val.rstrip('(Preferred)'), 'prefixlen': None} iface['inet6'].append(addr) elif key == 'Physical Address': iface['hwaddr'] = val elif key == 'Media State': # XXX seen used for tunnel adaptors # might be useful iface['up'] = (val != 'Media disconnected') def win_interfaces(): ''' Obtain interface information for Windows systems ''' with salt.utils.winapi.Com(): c = wmi.WMI() ifaces = {} for iface in c.Win32_NetworkAdapterConfiguration(IPEnabled=1): ifaces[iface.Description] = dict() if iface.MACAddress: ifaces[iface.Description]['hwaddr'] = iface.MACAddress if iface.IPEnabled: ifaces[iface.Description]['up'] = True for ip in iface.IPAddress: if '.' in ip: if 'inet' not in ifaces[iface.Description]: ifaces[iface.Description]['inet'] = [] item = {'address': ip, 'label': iface.Description} if iface.DefaultIPGateway: broadcast = next((i for i in iface.DefaultIPGateway if '.' in i), '') if broadcast: item['broadcast'] = broadcast if iface.IPSubnet: netmask = next((i for i in iface.IPSubnet if '.' in i), '') if netmask: item['netmask'] = netmask ifaces[iface.Description]['inet'].append(item) if ':' in ip: if 'inet6' not in ifaces[iface.Description]: ifaces[iface.Description]['inet6'] = [] item = {'address': ip} if iface.DefaultIPGateway: broadcast = next((i for i in iface.DefaultIPGateway if ':' in i), '') if broadcast: item['broadcast'] = broadcast if iface.IPSubnet: netmask = next((i for i in iface.IPSubnet if ':' in i), '') if netmask: item['netmask'] = netmask ifaces[iface.Description]['inet6'].append(item) else: ifaces[iface.Description]['up'] = False return ifaces def interfaces(): ''' Return a dictionary of information about all the interfaces on the minion ''' if salt.utils.platform.is_windows(): return win_interfaces() elif salt.utils.platform.is_netbsd(): return netbsd_interfaces() else: return linux_interfaces() def get_net_start(ipaddr, netmask): ''' Return the address of the network ''' net = ipaddress.ip_network('{0}/{1}'.format(ipaddr, netmask), strict=False) return six.text_type(net.network_address) def get_net_size(mask): ''' Turns an IPv4 netmask into it's corresponding prefix length (255.255.255.0 -> 24 as in 192.168.1.10/24). ''' binary_str = '' for octet in mask.split('.'): binary_str += bin(int(octet))[2:].zfill(8) return len(binary_str.rstrip('0')) def calc_net(ipaddr, netmask=None): ''' Takes IP (CIDR notation supported) and optionally netmask and returns the network in CIDR-notation. (The IP can be any IP inside the subnet) ''' if netmask is not None: ipaddr = '{0}/{1}'.format(ipaddr, netmask) return six.text_type(ipaddress.ip_network(ipaddr, strict=False)) def _ipv4_to_bits(ipaddr): ''' Accepts an IPv4 dotted quad and returns a string representing its binary counterpart ''' return ''.join([bin(int(x))[2:].rjust(8, '0') for x in ipaddr.split('.')]) def _get_iface_info(iface): ''' If `iface` is available, return interface info and no error, otherwise return no info and log and return an error ''' iface_info = interfaces() if iface in iface_info.keys(): return iface_info, False else: error_msg = ('Interface "{0}" not in available interfaces: "{1}"' ''.format(iface, '", "'.join(iface_info.keys()))) log.error(error_msg) return None, error_msg def _hw_addr_aix(iface): ''' Return the hardware address (a.k.a. MAC address) for a given interface on AIX MAC address not available in through interfaces ''' cmd = subprocess.Popen( 'entstat -d {0} | grep \'Hardware Address\''.format(iface), shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT).communicate()[0] if cmd: comps = cmd.split(' ') if len(comps) == 3: mac_addr = comps[2].strip('\'').strip() return mac_addr error_msg = ('Interface "{0}" either not available or does not contain a hardware address'.format(iface)) log.error(error_msg) return error_msg def hw_addr(iface): ''' Return the hardware address (a.k.a. MAC address) for a given interface .. versionchanged:: 2016.11.4 Added support for AIX ''' if salt.utils.platform.is_aix(): return _hw_addr_aix iface_info, error = _get_iface_info(iface) if error is False: return iface_info.get(iface, {}).get('hwaddr', '') else: return error def interface(iface): ''' Return the details of `iface` or an error if it does not exist ''' iface_info, error = _get_iface_info(iface) if error is False: return iface_info.get(iface, {}).get('inet', '') else: return error def interface_ip(iface): ''' Return `iface` IPv4 addr or an error if `iface` does not exist ''' iface_info, error = _get_iface_info(iface) if error is False: inet = iface_info.get(iface, {}).get('inet', None) return inet[0].get('address', '') if inet else '' else: return error def _subnets(proto='inet', interfaces_=None): ''' Returns a list of subnets to which the host belongs ''' if interfaces_ is None: ifaces = interfaces() elif isinstance(interfaces_, list): ifaces = {} for key, value in six.iteritems(interfaces()): if key in interfaces_: ifaces[key] = value else: ifaces = {interfaces_: interfaces().get(interfaces_, {})} ret = set() if proto == 'inet': subnet = 'netmask' dflt_cidr = 32 elif proto == 'inet6': subnet = 'prefixlen' dflt_cidr = 128 else: log.error('Invalid proto %s calling subnets()', proto) return for ip_info in six.itervalues(ifaces): addrs = ip_info.get(proto, []) addrs.extend([addr for addr in ip_info.get('secondary', []) if addr.get('type') == proto]) for intf in addrs: if subnet in intf: intf = ipaddress.ip_interface('{0}/{1}'.format(intf['address'], intf[subnet])) else: intf = ipaddress.ip_interface('{0}/{1}'.format(intf['address'], dflt_cidr)) if not intf.is_loopback: ret.add(intf.network) return [six.text_type(net) for net in sorted(ret)] def subnets(interfaces=None): ''' Returns a list of IPv4 subnets to which the host belongs ''' return _subnets('inet', interfaces_=interfaces) def subnets6(): ''' Returns a list of IPv6 subnets to which the host belongs ''' return _subnets('inet6') def in_subnet(cidr, addr=None): ''' Returns True if host or (any of) addrs is within specified subnet, otherwise False ''' try: cidr = ipaddress.ip_network(cidr) except ValueError: log.error('Invalid CIDR \'%s\'', cidr) return False if addr is None: addr = ip_addrs() addr.extend(ip_addrs6()) elif not isinstance(addr, (list, tuple)): addr = (addr,) return any(ipaddress.ip_address(item) in cidr for item in addr) def _ip_addrs(interface=None, include_loopback=False, interface_data=None, proto='inet'): ''' Return the full list of IP adresses matching the criteria proto = inet|inet6 ''' ret = set() ifaces = interface_data \ if isinstance(interface_data, dict) \ else interfaces() if interface is None: target_ifaces = ifaces else: target_ifaces = dict([(k, v) for k, v in six.iteritems(ifaces) if k == interface]) if not target_ifaces: log.error('Interface %s not found.', interface) for ip_info in six.itervalues(target_ifaces): addrs = ip_info.get(proto, []) addrs.extend([addr for addr in ip_info.get('secondary', []) if addr.get('type') == proto]) for addr in addrs: addr = ipaddress.ip_address(addr.get('address')) if not addr.is_loopback or include_loopback: ret.add(addr) return [six.text_type(addr) for addr in sorted(ret)] def ip_addrs(interface=None, include_loopback=False, interface_data=None): ''' Returns a list of IPv4 addresses assigned to the host. 127.0.0.1 is ignored, unless 'include_loopback=True' is indicated. If 'interface' is provided, then only IP addresses from that interface will be returned. ''' return _ip_addrs(interface, include_loopback, interface_data, 'inet') def ip_addrs6(interface=None, include_loopback=False, interface_data=None): ''' Returns a list of IPv6 addresses assigned to the host. ::1 is ignored, unless 'include_loopback=True' is indicated. If 'interface' is provided, then only IP addresses from that interface will be returned. ''' return _ip_addrs(interface, include_loopback, interface_data, 'inet6') def hex2ip(hex_ip, invert=False): ''' Convert a hex string to an ip, if a failure occurs the original hex is returned. If 'invert=True' assume that ip from /proc/net/<proto> ''' if len(hex_ip) == 32: # ipv6 ip = [] for i in range(0, 32, 8): ip_part = hex_ip[i:i + 8] ip_part = [ip_part[x:x + 2] for x in range(0, 8, 2)] if invert: ip.append("{0[3]}{0[2]}:{0[1]}{0[0]}".format(ip_part)) else: ip.append("{0[0]}{0[1]}:{0[2]}{0[3]}".format(ip_part)) try: address = ipaddress.IPv6Address(":".join(ip)) if address.ipv4_mapped: return str(address.ipv4_mapped) else: return address.compressed except ipaddress.AddressValueError as ex: log.error('hex2ip - ipv6 address error: %s', ex) return hex_ip try: hip = int(hex_ip, 16) except ValueError: return hex_ip if invert: return '{3}.{2}.{1}.{0}'.format(hip >> 24 & 255, hip >> 16 & 255, hip >> 8 & 255, hip & 255) return '{0}.{1}.{2}.{3}'.format(hip >> 24 & 255, hip >> 16 & 255, hip >> 8 & 255, hip & 255) def mac2eui64(mac, prefix=None): ''' Convert a MAC address to a EUI64 identifier or, with prefix provided, a full IPv6 address ''' # http://tools.ietf.org/html/rfc4291#section-2.5.1 eui64 = re.sub(r'[.:-]', '', mac).lower() eui64 = eui64[0:6] + 'fffe' + eui64[6:] eui64 = hex(int(eui64[0:2], 16) | 2)[2:].zfill(2) + eui64[2:] if prefix is None: return ':'.join(re.findall(r'.{4}', eui64)) else: try: net = ipaddress.ip_network(prefix, strict=False) euil = int('0x{0}'.format(eui64), 16) return '{0}/{1}'.format(net[euil], net.prefixlen) except Exception: return def active_tcp(): ''' Return a dict describing all active tcp connections as quickly as possible ''' ret = {} for statf in ['/proc/net/tcp', '/proc/net/tcp6']: if os.path.isfile(statf): with salt.utils.files.fopen(statf, 'rb') as fp_: for line in fp_: line = salt.utils.stringutils.to_unicode(line) if line.strip().startswith('sl'): continue iret = _parse_tcp_line(line) sl = next(iter(iret)) if iret[sl]['state'] == 1: # 1 is ESTABLISHED del iret[sl]['state'] ret[len(ret)] = iret[sl] return ret def local_port_tcp(port): ''' Return a set of remote ip addrs attached to the specified local port ''' ret = _remotes_on(port, 'local_port') return ret def remote_port_tcp(port): ''' Return a set of ip addrs the current host is connected to on given port ''' ret = _remotes_on(port, 'remote_port') return ret def _remotes_on(port, which_end): ''' Return a set of ip addrs active tcp connections ''' port = int(port) ret = _netlink_tool_remote_on(port, which_end) if ret is not None: return ret ret = set() proc_available = False for statf in ['/proc/net/tcp', '/proc/net/tcp6']: if os.path.isfile(statf): proc_available = True with salt.utils.files.fopen(statf, 'r') as fp_: for line in fp_: line = salt.utils.stringutils.to_unicode(line) if line.strip().startswith('sl'): continue iret = _parse_tcp_line(line) sl = next(iter(iret)) if iret[sl][which_end] == port and iret[sl]['state'] == 1: # 1 is ESTABLISHED ret.add(iret[sl]['remote_addr']) if not proc_available: # Fallback to use OS specific tools if salt.utils.platform.is_sunos(): return _sunos_remotes_on(port, which_end) if salt.utils.platform.is_freebsd(): return _freebsd_remotes_on(port, which_end) if salt.utils.platform.is_netbsd(): return _netbsd_remotes_on(port, which_end) if salt.utils.platform.is_openbsd(): return _openbsd_remotes_on(port, which_end) if salt.utils.platform.is_windows(): return _windows_remotes_on(port, which_end) if salt.utils.platform.is_aix(): return _aix_remotes_on(port, which_end) return _linux_remotes_on(port, which_end) return ret def _parse_tcp_line(line): ''' Parse a single line from the contents of /proc/net/tcp or /proc/net/tcp6 ''' ret = {} comps = line.strip().split() sl = comps[0].rstrip(':') ret[sl] = {} l_addr, l_port = comps[1].split(':') r_addr, r_port = comps[2].split(':') ret[sl]['local_addr'] = hex2ip(l_addr, True) ret[sl]['local_port'] = int(l_port, 16) ret[sl]['remote_addr'] = hex2ip(r_addr, True) ret[sl]['remote_port'] = int(r_port, 16) ret[sl]['state'] = int(comps[3], 16) return ret def _sunos_remotes_on(port, which_end): ''' SunOS specific helper function. Returns set of ipv4 host addresses of remote established connections on local or remote tcp port. Parses output of shell 'netstat' to get connections [root@salt-master ~]# netstat -f inet -n TCP: IPv4 Local Address Remote Address Swind Send-Q Rwind Recv-Q State -------------------- -------------------- ----- ------ ----- ------ ----------- 10.0.0.101.4505 10.0.0.1.45329 1064800 0 1055864 0 ESTABLISHED 10.0.0.101.4505 10.0.0.100.50798 1064800 0 1055864 0 ESTABLISHED ''' remotes = set() try: data = subprocess.check_output(['netstat', '-f', 'inet', '-n']) # pylint: disable=minimum-python-version except subprocess.CalledProcessError: log.error('Failed netstat') raise lines = salt.utils.stringutils.to_str(data).split('\n') for line in lines: if 'ESTABLISHED' not in line: continue chunks = line.split() local_host, local_port = chunks[0].rsplit('.', 1) remote_host, remote_port = chunks[1].rsplit('.', 1) if which_end == 'remote_port' and int(remote_port) != port: continue if which_end == 'local_port' and int(local_port) != port: continue remotes.add(remote_host) return remotes def _freebsd_remotes_on(port, which_end): ''' Returns set of ipv4 host addresses of remote established connections on local tcp port port. Parses output of shell 'sockstat' (FreeBSD) to get connections $ sudo sockstat -4 USER COMMAND PID FD PROTO LOCAL ADDRESS FOREIGN ADDRESS root python2.7 1456 29 tcp4 *:4505 *:* root python2.7 1445 17 tcp4 *:4506 *:* root python2.7 1294 14 tcp4 127.0.0.1:11813 127.0.0.1:4505 root python2.7 1294 41 tcp4 127.0.0.1:61115 127.0.0.1:4506 $ sudo sockstat -4 -c -p 4506 USER COMMAND PID FD PROTO LOCAL ADDRESS FOREIGN ADDRESS root python2.7 1294 41 tcp4 127.0.0.1:61115 127.0.0.1:4506 ''' port = int(port) remotes = set() try: cmd = salt.utils.args.shlex_split('sockstat -4 -c -p {0}'.format(port)) data = subprocess.check_output(cmd) # pylint: disable=minimum-python-version except subprocess.CalledProcessError as ex: log.error('Failed "sockstat" with returncode = %s', ex.returncode) raise lines = salt.utils.stringutils.to_str(data).split('\n') for line in lines: chunks = line.split() if not chunks: continue # ['root', 'python2.7', '1456', '37', 'tcp4', # '127.0.0.1:4505-', '127.0.0.1:55703'] # print chunks if 'COMMAND' in chunks[1]: continue # ignore header if len(chunks) < 2: continue # sockstat -4 -c -p 4506 does this with high PIDs: # USER COMMAND PID FD PROTO LOCAL ADDRESS FOREIGN ADDRESS # salt-master python2.781106 35 tcp4 192.168.12.34:4506 192.168.12.45:60143 local = chunks[-2] remote = chunks[-1] lhost, lport = local.split(':') rhost, rport = remote.split(':') if which_end == 'local' and int(lport) != port: # ignore if local port not port continue if which_end == 'remote' and int(rport) != port: # ignore if remote port not port continue remotes.add(rhost) return remotes def _netbsd_remotes_on(port, which_end): ''' Returns set of ipv4 host addresses of remote established connections on local tcp port port. Parses output of shell 'sockstat' (NetBSD) to get connections $ sudo sockstat -4 -n USER COMMAND PID FD PROTO LOCAL ADDRESS FOREIGN ADDRESS root python2.7 1456 29 tcp *.4505 *.* root python2.7 1445 17 tcp *.4506 *.* root python2.7 1294 14 tcp 127.0.0.1.11813 127.0.0.1.4505 root python2.7 1294 41 tcp 127.0.0.1.61115 127.0.0.1.4506 $ sudo sockstat -4 -c -n -p 4506 USER COMMAND PID FD PROTO LOCAL ADDRESS FOREIGN ADDRESS root python2.7 1294 41 tcp 127.0.0.1.61115 127.0.0.1.4506 ''' port = int(port) remotes = set() try: cmd = salt.utils.args.shlex_split('sockstat -4 -c -n -p {0}'.format(port)) data = subprocess.check_output(cmd) # pylint: disable=minimum-python-version except subprocess.CalledProcessError as ex: log.error('Failed "sockstat" with returncode = %s', ex.returncode) raise lines = salt.utils.stringutils.to_str(data).split('\n') for line in lines: chunks = line.split() if not chunks: continue # ['root', 'python2.7', '1456', '37', 'tcp', # '127.0.0.1.4505-', '127.0.0.1.55703'] # print chunks if 'COMMAND' in chunks[1]: continue # ignore header if len(chunks) < 2: continue local = chunks[5].split('.') lport = local.pop() lhost = '.'.join(local) remote = chunks[6].split('.') rport = remote.pop() rhost = '.'.join(remote) if which_end == 'local' and int(lport) != port: # ignore if local port not port continue if which_end == 'remote' and int(rport) != port: # ignore if remote port not port continue remotes.add(rhost) return remotes def _openbsd_remotes_on(port, which_end): ''' OpenBSD specific helper function. Returns set of ipv4 host addresses of remote established connections on local or remote tcp port. Parses output of shell 'netstat' to get connections $ netstat -nf inet Active Internet connections Proto Recv-Q Send-Q Local Address Foreign Address (state) tcp 0 0 10.0.0.101.4505 10.0.0.1.45329 ESTABLISHED tcp 0 0 10.0.0.101.4505 10.0.0.100.50798 ESTABLISHED ''' remotes = set() try: data = subprocess.check_output(['netstat', '-nf', 'inet']) # pylint: disable=minimum-python-version except subprocess.CalledProcessError: log.error('Failed netstat') raise lines = data.split('\n') for line in lines: if 'ESTABLISHED' not in line: continue chunks = line.split() local_host, local_port = chunks[3].rsplit('.', 1) remote_host, remote_port = chunks[4].rsplit('.', 1) if which_end == 'remote_port' and int(remote_port) != port: continue if which_end == 'local_port' and int(local_port) != port: continue remotes.add(remote_host) return remotes def _windows_remotes_on(port, which_end): r''' Windows specific helper function. Returns set of ipv4 host addresses of remote established connections on local or remote tcp port. Parses output of shell 'netstat' to get connections C:\>netstat -n Active Connections Proto Local Address Foreign Address State TCP 10.2.33.17:3007 130.164.12.233:10123 ESTABLISHED TCP 10.2.33.17:3389 130.164.30.5:10378 ESTABLISHED ''' remotes = set() try: data = subprocess.check_output(['netstat', '-n']) # pylint: disable=minimum-python-version except subprocess.CalledProcessError: log.error('Failed netstat') raise lines = salt.utils.stringutils.to_str(data).split('\n') for line in lines: if 'ESTABLISHED' not in line: continue chunks = line.split() local_host, local_port = chunks[1].rsplit(':', 1) remote_host, remote_port = chunks[2].rsplit(':', 1) if which_end == 'remote_port' and int(remote_port) != port: continue if which_end == 'local_port' and int(local_port) != port: continue remotes.add(remote_host) return remotes def _linux_remotes_on(port, which_end): ''' Linux specific helper function. Returns set of ip host addresses of remote established connections on local tcp port port. Parses output of shell 'lsof' to get connections $ sudo lsof -iTCP:4505 -n COMMAND PID USER FD TYPE DEVICE SIZE/OFF NODE NAME Python 9971 root 35u IPv4 0x18a8464a29ca329d 0t0 TCP *:4505 (LISTEN) Python 9971 root 37u IPv4 0x18a8464a29b2b29d 0t0 TCP 127.0.0.1:4505->127.0.0.1:55703 (ESTABLISHED) Python 10152 root 22u IPv4 0x18a8464a29c8cab5 0t0 TCP 127.0.0.1:55703->127.0.0.1:4505 (ESTABLISHED) Python 10153 root 22u IPv4 0x18a8464a29c8cab5 0t0 TCP [fe80::249a]:4505->[fe80::150]:59367 (ESTABLISHED) ''' remotes = set() try: data = subprocess.check_output( ['lsof', '-iTCP:{0:d}'.format(port), '-n', '-P'] # pylint: disable=minimum-python-version ) except subprocess.CalledProcessError as ex: if ex.returncode == 1: # Lsof return 1 if any error was detected, including the failure # to locate Internet addresses, and it is not an error in this case. log.warning('"lsof" returncode = 1, likely no active TCP sessions.') return remotes log.error('Failed "lsof" with returncode = %s', ex.returncode) raise lines = salt.utils.stringutils.to_str(data).split('\n') for line in lines: chunks = line.split() if not chunks: continue # ['Python', '9971', 'root', '37u', 'IPv4', '0x18a8464a29b2b29d', '0t0', # 'TCP', '127.0.0.1:4505->127.0.0.1:55703', '(ESTABLISHED)'] # print chunks if 'COMMAND' in chunks[0]: continue # ignore header if 'ESTABLISHED' not in chunks[-1]: continue # ignore if not ESTABLISHED # '127.0.0.1:4505->127.0.0.1:55703' local, remote = chunks[8].split('->') _, lport = local.rsplit(':', 1) rhost, rport = remote.rsplit(':', 1) if which_end == 'remote_port' and int(rport) != port: continue if which_end == 'local_port' and int(lport) != port: continue remotes.add(rhost.strip("[]")) return remotes def _aix_remotes_on(port, which_end): ''' AIX specific helper function. Returns set of ipv4 host addresses of remote established connections on local or remote tcp port. Parses output of shell 'netstat' to get connections root@la68pp002_pub:/opt/salt/lib/python2.7/site-packages/salt/modules# netstat -f inet -n Active Internet connections Proto Recv-Q Send-Q Local Address Foreign Address (state) tcp4 0 0 172.29.149.95.50093 209.41.78.13.4505 ESTABLISHED tcp4 0 0 127.0.0.1.9514 *.* LISTEN tcp4 0 0 127.0.0.1.9515 *.* LISTEN tcp4 0 0 127.0.0.1.199 127.0.0.1.32779 ESTABLISHED tcp4 0 0 127.0.0.1.32779 127.0.0.1.199 ESTABLISHED tcp4 0 40 172.29.149.95.22 172.29.96.83.41022 ESTABLISHED tcp4 0 0 172.29.149.95.22 172.29.96.83.41032 ESTABLISHED tcp4 0 0 127.0.0.1.32771 127.0.0.1.32775 ESTABLISHED tcp 0 0 127.0.0.1.32775 127.0.0.1.32771 ESTABLISHED tcp4 0 0 127.0.0.1.32771 127.0.0.1.32776 ESTABLISHED tcp 0 0 127.0.0.1.32776 127.0.0.1.32771 ESTABLISHED tcp4 0 0 127.0.0.1.32771 127.0.0.1.32777 ESTABLISHED tcp 0 0 127.0.0.1.32777 127.0.0.1.32771 ESTABLISHED tcp4 0 0 127.0.0.1.32771 127.0.0.1.32778 ESTABLISHED tcp 0 0 127.0.0.1.32778 127.0.0.1.32771 ESTABLISHED ''' remotes = set() try: data = subprocess.check_output(['netstat', '-f', 'inet', '-n']) # pylint: disable=minimum-python-version except subprocess.CalledProcessError: log.error('Failed netstat') raise lines = salt.utils.stringutils.to_str(data).split('\n') for line in lines: if 'ESTABLISHED' not in line: continue chunks = line.split() local_host, local_port = chunks[3].rsplit('.', 1) remote_host, remote_port = chunks[4].rsplit('.', 1) if which_end == 'remote_port' and int(remote_port) != port: continue if which_end == 'local_port' and int(local_port) != port: continue remotes.add(remote_host) return remotes @jinja_filter('gen_mac') def gen_mac(prefix='AC:DE:48'): ''' Generates a MAC address with the defined OUI prefix. Common prefixes: - ``00:16:3E`` -- Xen - ``00:18:51`` -- OpenVZ - ``00:50:56`` -- VMware (manually generated) - ``52:54:00`` -- QEMU/KVM - ``AC:DE:48`` -- PRIVATE References: - http://standards.ieee.org/develop/regauth/oui/oui.txt - https://www.wireshark.org/tools/oui-lookup.html - https://en.wikipedia.org/wiki/MAC_address ''' return '{0}:{1:02X}:{2:02X}:{3:02X}'.format(prefix, random.randint(0, 0xff), random.randint(0, 0xff), random.randint(0, 0xff)) @jinja_filter('mac_str_to_bytes') def mac_str_to_bytes(mac_str): ''' Convert a MAC address string into bytes. Works with or without separators: b1 = mac_str_to_bytes('08:00:27:13:69:77') b2 = mac_str_to_bytes('080027136977') assert b1 == b2 assert isinstance(b1, bytes) ''' if len(mac_str) == 12: pass elif len(mac_str) == 17: sep = mac_str[2] mac_str = mac_str.replace(sep, '') else: raise ValueError('Invalid MAC address') chars = (int(mac_str[s:s+2], 16) for s in range(0, 12, 2)) return bytes(chars) if six.PY3 else b''.join(chr(x) for x in chars) def refresh_dns(): ''' issue #21397: force glibc to re-read resolv.conf ''' try: res_init() except NameError: # Exception raised loading the library, thus res_init is not defined pass @jinja_filter('connection_check') def connection_check(addr, port=80, safe=False, ipv6=None): ''' Provides a convenient alias for the dns_check filter. ''' return dns_check(addr, port, safe, ipv6) @jinja_filter('dns_check') def dns_check(addr, port=80, safe=False, ipv6=None, attempt_connect=True): ''' Return the ip resolved by dns, but do not exit on failure, only raise an exception. Obeys system preference for IPv4/6 address resolution - this can be overridden by the ipv6 flag. Tries to connect to the address before considering it useful. If no address can be reached, the first one resolved is used as a fallback. ''' error = False lookup = addr seen_ipv6 = False family = socket.AF_INET6 if ipv6 else socket.AF_INET if ipv6 is False else socket.AF_UNSPEC hostnames = [] try: refresh_dns() hostnames = socket.getaddrinfo(addr, port, family, socket.SOCK_STREAM) except TypeError: err = ('Attempt to resolve address \'{0}\' failed. Invalid or unresolveable address').format(lookup) raise SaltSystemExit(code=42, msg=err) except socket.error: error = True # If ipv6 is set to True, attempt another lookup using the IPv4 family, # just in case we're attempting to lookup an IPv4 IP # as an IPv6 hostname. if error and ipv6: try: refresh_dns() hostnames = socket.getaddrinfo(addr, port, socket.AF_INET, socket.SOCK_STREAM) except TypeError: err = ('Attempt to resolve address \'{0}\' failed. Invalid or unresolveable address').format(lookup) raise SaltSystemExit(code=42, msg=err) except socket.error: error = True try: if not hostnames: error = True else: resolved = False candidates = [] for h in hostnames: # Input is IP address, passed through unchanged, just return it if h[4][0] == addr: resolved = salt.utils.zeromq.ip_bracket(addr) break candidate_addr = salt.utils.zeromq.ip_bracket(h[4][0]) # sometimes /etc/hosts contains ::1 localhost if not ipv6 and candidate_addr == '[::1]': continue candidates.append(candidate_addr) if attempt_connect: try: s = socket.socket(h[0], socket.SOCK_STREAM) s.settimeout(2) s.connect((candidate_addr.strip('[]'), h[4][1])) s.close() resolved = candidate_addr break except socket.error: pass if not resolved: if candidates: resolved = candidates[0] else: error = True except TypeError: err = ('Attempt to resolve address \'{0}\' failed. Invalid or unresolveable address').format(lookup) raise SaltSystemExit(code=42, msg=err) except socket.error: error = True if error: err = ('DNS lookup or connection check of \'{0}\' failed.').format(addr) if safe: if salt.log.is_console_configured(): # If logging is not configured it also means that either # the master or minion instance calling this hasn't even # started running log.error(err) raise SaltClientError() raise SaltSystemExit(code=42, msg=err) return resolved def parse_host_port(host_port): """ Takes a string argument specifying host or host:port. Returns a (hostname, port) or (ip_address, port) tuple. If no port is given, the second (port) element of the returned tuple will be None. host:port argument, for example, is accepted in the forms of: - hostname - hostname:1234 - hostname.domain.tld - hostname.domain.tld:5678 - [1234::5]:5678 - 1234::5 - 10.11.12.13:4567 - 10.11.12.13 """ host, port = None, None # default _s_ = host_port[:] if _s_[0] == "[": if "]" in host_port: host, _s_ = _s_.lstrip("[").rsplit("]", 1) host = ipaddress.IPv6Address(host).compressed if _s_[0] == ":": port = int(_s_.lstrip(":")) else: if len(_s_) > 1: raise ValueError('found ambiguous "{}" port in "{}"'.format(_s_, host_port)) else: if _s_.count(":") == 1: host, _hostport_separator_, port = _s_.partition(":") try: port = int(port) except ValueError as _e_: log.error('host_port "%s" port value "%s" is not an integer.', host_port, port) raise _e_ else: host = _s_ try: if not isinstance(host, ipaddress._BaseAddress): host_ip = ipaddress.ip_address(host).compressed host = host_ip except ValueError: log.debug('"%s" Not an IP address? Assuming it is a hostname.', host) if host != sanitize_host(host): log.error('bad hostname: "%s"', host) raise ValueError('bad hostname: "{}"'.format(host)) return host, port def is_fqdn(hostname): """ Verify if hostname conforms to be a FQDN. :param hostname: text string with the name of the host :return: bool, True if hostname is correct FQDN, False otherwise """ compliant = re.compile(r"(?!-)[A-Z\d\-\_]{1,63}(?<!-)$", re.IGNORECASE) return "." in hostname and len(hostname) < 0xff and all(compliant.match(x) for x in hostname.rstrip(".").split("."))
saltstack/salt
salt/utils/network.py
_netbsd_remotes_on
python
def _netbsd_remotes_on(port, which_end): ''' Returns set of ipv4 host addresses of remote established connections on local tcp port port. Parses output of shell 'sockstat' (NetBSD) to get connections $ sudo sockstat -4 -n USER COMMAND PID FD PROTO LOCAL ADDRESS FOREIGN ADDRESS root python2.7 1456 29 tcp *.4505 *.* root python2.7 1445 17 tcp *.4506 *.* root python2.7 1294 14 tcp 127.0.0.1.11813 127.0.0.1.4505 root python2.7 1294 41 tcp 127.0.0.1.61115 127.0.0.1.4506 $ sudo sockstat -4 -c -n -p 4506 USER COMMAND PID FD PROTO LOCAL ADDRESS FOREIGN ADDRESS root python2.7 1294 41 tcp 127.0.0.1.61115 127.0.0.1.4506 ''' port = int(port) remotes = set() try: cmd = salt.utils.args.shlex_split('sockstat -4 -c -n -p {0}'.format(port)) data = subprocess.check_output(cmd) # pylint: disable=minimum-python-version except subprocess.CalledProcessError as ex: log.error('Failed "sockstat" with returncode = %s', ex.returncode) raise lines = salt.utils.stringutils.to_str(data).split('\n') for line in lines: chunks = line.split() if not chunks: continue # ['root', 'python2.7', '1456', '37', 'tcp', # '127.0.0.1.4505-', '127.0.0.1.55703'] # print chunks if 'COMMAND' in chunks[1]: continue # ignore header if len(chunks) < 2: continue local = chunks[5].split('.') lport = local.pop() lhost = '.'.join(local) remote = chunks[6].split('.') rport = remote.pop() rhost = '.'.join(remote) if which_end == 'local' and int(lport) != port: # ignore if local port not port continue if which_end == 'remote' and int(rport) != port: # ignore if remote port not port continue remotes.add(rhost) return remotes
Returns set of ipv4 host addresses of remote established connections on local tcp port port. Parses output of shell 'sockstat' (NetBSD) to get connections $ sudo sockstat -4 -n USER COMMAND PID FD PROTO LOCAL ADDRESS FOREIGN ADDRESS root python2.7 1456 29 tcp *.4505 *.* root python2.7 1445 17 tcp *.4506 *.* root python2.7 1294 14 tcp 127.0.0.1.11813 127.0.0.1.4505 root python2.7 1294 41 tcp 127.0.0.1.61115 127.0.0.1.4506 $ sudo sockstat -4 -c -n -p 4506 USER COMMAND PID FD PROTO LOCAL ADDRESS FOREIGN ADDRESS root python2.7 1294 41 tcp 127.0.0.1.61115 127.0.0.1.4506
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/network.py#L1605-L1661
null
# -*- coding: utf-8 -*- ''' Define some generic socket functions for network modules ''' # Import python libs from __future__ import absolute_import, unicode_literals, print_function import itertools import os import re import types import socket import logging import platform import random import subprocess from string import ascii_letters, digits # Import 3rd-party libs from salt.ext import six from salt.ext.six.moves import range # pylint: disable=import-error,redefined-builtin # Attempt to import wmi try: import wmi import salt.utils.winapi except ImportError: pass # Import salt libs import salt.utils.args import salt.utils.files import salt.utils.path import salt.utils.platform import salt.utils.stringutils import salt.utils.zeromq from salt._compat import ipaddress from salt.exceptions import SaltClientError, SaltSystemExit from salt.utils.decorators.jinja import jinja_filter from salt.utils.versions import LooseVersion # inet_pton does not exist in Windows, this is a workaround if salt.utils.platform.is_windows(): from salt.ext import win_inet_pton # pylint: disable=unused-import log = logging.getLogger(__name__) try: import ctypes import ctypes.util libc = ctypes.cdll.LoadLibrary(ctypes.util.find_library("c")) res_init = libc.__res_init except (ImportError, OSError, AttributeError, TypeError): pass # pylint: disable=C0103 def sanitize_host(host): ''' Sanitize host string. https://tools.ietf.org/html/rfc1123#section-2.1 ''' RFC952_characters = ascii_letters + digits + ".-" return "".join([c for c in host[0:255] if c in RFC952_characters]) def isportopen(host, port): ''' Return status of a port ''' if not 1 <= int(port) <= 65535: return False sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) out = sock.connect_ex((sanitize_host(host), int(port))) return out def host_to_ips(host): ''' Returns a list of IP addresses of a given hostname or None if not found. ''' ips = [] try: for family, socktype, proto, canonname, sockaddr in socket.getaddrinfo( host, 0, socket.AF_UNSPEC, socket.SOCK_STREAM): if family == socket.AF_INET: ip, port = sockaddr elif family == socket.AF_INET6: ip, port, flow_info, scope_id = sockaddr ips.append(ip) if not ips: ips = None except Exception: ips = None return ips def _generate_minion_id(): ''' Get list of possible host names and convention names. :return: ''' # There are three types of hostnames: # 1. Network names. How host is accessed from the network. # 2. Host aliases. They might be not available in all the network or only locally (/etc/hosts) # 3. Convention names, an internal nodename. class DistinctList(list): ''' List, which allows one to append only distinct objects. Needs to work on Python 2.6, because of collections.OrderedDict only since 2.7 version. Override 'filter()' for custom filtering. ''' localhost_matchers = [r'localhost.*', r'ip6-.*', r'127[.]\d', r'0\.0\.0\.0', r'::1.*', r'ipv6-.*', r'fe00::.*', r'fe02::.*', r'1.0.0.*.ip6.arpa'] def append(self, p_object): if p_object and p_object not in self and not self.filter(p_object): super(DistinctList, self).append(p_object) return self def extend(self, iterable): for obj in iterable: self.append(obj) return self def filter(self, element): 'Returns True if element needs to be filtered' for rgx in self.localhost_matchers: if re.match(rgx, element): return True def first(self): return self and self[0] or None hostname = socket.gethostname() hosts = DistinctList().append( salt.utils.stringutils.to_unicode(socket.getfqdn(salt.utils.stringutils.to_bytes(hostname))) ).append(platform.node()).append(hostname) if not hosts: try: for a_nfo in socket.getaddrinfo(hosts.first() or 'localhost', None, socket.AF_INET, socket.SOCK_RAW, socket.IPPROTO_IP, socket.AI_CANONNAME): if len(a_nfo) > 3: hosts.append(a_nfo[3]) except socket.gaierror: log.warning('Cannot resolve address %s info via socket: %s', hosts.first() or 'localhost (N/A)', socket.gaierror) # Universal method for everywhere (Linux, Slowlaris, Windows etc) for f_name in ('/etc/hostname', '/etc/nodename', '/etc/hosts', r'{win}\system32\drivers\etc\hosts'.format(win=os.getenv('WINDIR'))): try: with salt.utils.files.fopen(f_name) as f_hdl: for line in f_hdl: line = salt.utils.stringutils.to_unicode(line) hst = line.strip().split('#')[0].strip().split() if hst: if hst[0][:4] in ('127.', '::1') or len(hst) == 1: hosts.extend(hst) except IOError: pass # include public and private ipaddresses return hosts.extend([addr for addr in ip_addrs() if not ipaddress.ip_address(addr).is_loopback]) def generate_minion_id(): ''' Return only first element of the hostname from all possible list. :return: ''' try: ret = salt.utils.stringutils.to_unicode(_generate_minion_id().first()) except TypeError: ret = None return ret or 'localhost' def get_socket(addr, type=socket.SOCK_STREAM, proto=0): ''' Return a socket object for the addr IP-version agnostic ''' version = ipaddress.ip_address(addr).version if version == 4: family = socket.AF_INET elif version == 6: family = socket.AF_INET6 return socket.socket(family, type, proto) def get_fqhostname(): ''' Returns the fully qualified hostname ''' # try getaddrinfo() fqdn = None try: addrinfo = socket.getaddrinfo( socket.gethostname(), 0, socket.AF_UNSPEC, socket.SOCK_STREAM, socket.SOL_TCP, socket.AI_CANONNAME ) for info in addrinfo: # info struct [family, socktype, proto, canonname, sockaddr] # On Windows `canonname` can be an empty string # This can cause the function to return `None` if len(info) > 3 and info[3]: fqdn = info[3] break except socket.gaierror: pass # NOTE: this used to log.error() but it was later disabled except socket.error as err: log.debug('socket.getaddrinfo() failure while finding fqdn: %s', err) if fqdn is None: fqdn = socket.getfqdn() return fqdn def ip_to_host(ip): ''' Returns the hostname of a given IP ''' try: hostname, aliaslist, ipaddrlist = socket.gethostbyaddr(ip) except Exception as exc: log.debug('salt.utils.network.ip_to_host(%r) failed: %s', ip, exc) hostname = None return hostname # pylint: enable=C0103 def is_reachable_host(entity_name): ''' Returns a bool telling if the entity name is a reachable host (IPv4/IPv6/FQDN/etc). :param hostname: :return: ''' try: assert type(socket.getaddrinfo(entity_name, 0, 0, 0, 0)) == list ret = True except socket.gaierror: ret = False return ret def is_ip(ip): ''' Returns a bool telling if the passed IP is a valid IPv4 or IPv6 address. ''' return is_ipv4(ip) or is_ipv6(ip) def is_ipv4(ip): ''' Returns a bool telling if the value passed to it was a valid IPv4 address ''' try: return ipaddress.ip_address(ip).version == 4 except ValueError: return False def is_ipv6(ip): ''' Returns a bool telling if the value passed to it was a valid IPv6 address ''' try: return ipaddress.ip_address(ip).version == 6 except ValueError: return False def is_subnet(cidr): ''' Returns a bool telling if the passed string is an IPv4 or IPv6 subnet ''' return is_ipv4_subnet(cidr) or is_ipv6_subnet(cidr) def is_ipv4_subnet(cidr): ''' Returns a bool telling if the passed string is an IPv4 subnet ''' try: return '/' in cidr and bool(ipaddress.IPv4Network(cidr)) except Exception: return False def is_ipv6_subnet(cidr): ''' Returns a bool telling if the passed string is an IPv6 subnet ''' try: return '/' in cidr and bool(ipaddress.IPv6Network(cidr)) except Exception: return False @jinja_filter('is_ip') def is_ip_filter(ip, options=None): ''' Returns a bool telling if the passed IP is a valid IPv4 or IPv6 address. ''' return is_ipv4_filter(ip, options=options) or is_ipv6_filter(ip, options=options) def _ip_options_global(ip_obj, version): return not ip_obj.is_private def _ip_options_multicast(ip_obj, version): return ip_obj.is_multicast def _ip_options_loopback(ip_obj, version): return ip_obj.is_loopback def _ip_options_link_local(ip_obj, version): return ip_obj.is_link_local def _ip_options_private(ip_obj, version): return ip_obj.is_private def _ip_options_reserved(ip_obj, version): return ip_obj.is_reserved def _ip_options_site_local(ip_obj, version): if version == 6: return ip_obj.is_site_local return False def _ip_options_unspecified(ip_obj, version): return ip_obj.is_unspecified def _ip_options(ip_obj, version, options=None): # will process and IP options options_fun_map = { 'global': _ip_options_global, 'link-local': _ip_options_link_local, 'linklocal': _ip_options_link_local, 'll': _ip_options_link_local, 'link_local': _ip_options_link_local, 'loopback': _ip_options_loopback, 'lo': _ip_options_loopback, 'multicast': _ip_options_multicast, 'private': _ip_options_private, 'public': _ip_options_global, 'reserved': _ip_options_reserved, 'site-local': _ip_options_site_local, 'sl': _ip_options_site_local, 'site_local': _ip_options_site_local, 'unspecified': _ip_options_unspecified } if not options: return six.text_type(ip_obj) # IP version already checked options_list = [option.strip() for option in options.split(',')] for option, fun in options_fun_map.items(): if option in options_list: fun_res = fun(ip_obj, version) if not fun_res: return None # stop at first failed test # else continue return six.text_type(ip_obj) def _is_ipv(ip, version, options=None): if not version: version = 4 if version not in (4, 6): return None try: ip_obj = ipaddress.ip_address(ip) except ValueError: # maybe it is an IP network try: ip_obj = ipaddress.ip_interface(ip) except ValueError: # nope, still not :( return None if not ip_obj.version == version: return None # has the right version, let's move on return _ip_options(ip_obj, version, options=options) @jinja_filter('is_ipv4') def is_ipv4_filter(ip, options=None): ''' Returns a bool telling if the value passed to it was a valid IPv4 address. ip The IP address. net: False Consider IP addresses followed by netmask. options CSV of options regarding the nature of the IP address. E.g.: loopback, multicast, private etc. ''' _is_ipv4 = _is_ipv(ip, 4, options=options) return isinstance(_is_ipv4, six.string_types) @jinja_filter('is_ipv6') def is_ipv6_filter(ip, options=None): ''' Returns a bool telling if the value passed to it was a valid IPv6 address. ip The IP address. net: False Consider IP addresses followed by netmask. options CSV of options regarding the nature of the IP address. E.g.: loopback, multicast, private etc. ''' _is_ipv6 = _is_ipv(ip, 6, options=options) return isinstance(_is_ipv6, six.string_types) def _ipv_filter(value, version, options=None): if version not in (4, 6): return if isinstance(value, (six.string_types, six.text_type, six.binary_type)): return _is_ipv(value, version, options=options) # calls is_ipv4 or is_ipv6 for `value` elif isinstance(value, (list, tuple, types.GeneratorType)): # calls is_ipv4 or is_ipv6 for each element in the list # os it filters and returns only those elements having the desired IP version return [ _is_ipv(addr, version, options=options) for addr in value if _is_ipv(addr, version, options=options) is not None ] return None @jinja_filter('ipv4') def ipv4(value, options=None): ''' Filters a list and returns IPv4 values only. ''' return _ipv_filter(value, 4, options=options) @jinja_filter('ipv6') def ipv6(value, options=None): ''' Filters a list and returns IPv6 values only. ''' return _ipv_filter(value, 6, options=options) @jinja_filter('ipaddr') def ipaddr(value, options=None): ''' Filters and returns only valid IP objects. ''' ipv4_obj = ipv4(value, options=options) ipv6_obj = ipv6(value, options=options) if ipv4_obj is None or ipv6_obj is None: # an IP address can be either IPv4 either IPv6 # therefofe if the value passed as arg is not a list, at least one of the calls above will return None # if one of them is none, means that we should return only one of them return ipv4_obj or ipv6_obj # one of them else: return ipv4_obj + ipv6_obj # extend lists def _filter_ipaddr(value, options, version=None): ipaddr_filter_out = None if version: if version == 4: ipaddr_filter_out = ipv4(value, options) elif version == 6: ipaddr_filter_out = ipv6(value, options) else: ipaddr_filter_out = ipaddr(value, options) if not ipaddr_filter_out: return if not isinstance(ipaddr_filter_out, (list, tuple, types.GeneratorType)): ipaddr_filter_out = [ipaddr_filter_out] return ipaddr_filter_out @jinja_filter('ip_host') def ip_host(value, options=None, version=None): ''' Returns the interfaces IP address, e.g.: 192.168.0.1/28. ''' ipaddr_filter_out = _filter_ipaddr(value, options=options, version=version) if not ipaddr_filter_out: return if not isinstance(value, (list, tuple, types.GeneratorType)): return six.text_type(ipaddress.ip_interface(ipaddr_filter_out[0])) return [six.text_type(ipaddress.ip_interface(ip_a)) for ip_a in ipaddr_filter_out] def _network_hosts(ip_addr_entry): return [ six.text_type(host) for host in ipaddress.ip_network(ip_addr_entry, strict=False).hosts() ] @jinja_filter('network_hosts') def network_hosts(value, options=None, version=None): ''' Return the list of hosts within a network. .. note:: When running this command with a large IPv6 network, the command will take a long time to gather all of the hosts. ''' ipaddr_filter_out = _filter_ipaddr(value, options=options, version=version) if not ipaddr_filter_out: return if not isinstance(value, (list, tuple, types.GeneratorType)): return _network_hosts(ipaddr_filter_out[0]) return [ _network_hosts(ip_a) for ip_a in ipaddr_filter_out ] def _network_size(ip_addr_entry): return ipaddress.ip_network(ip_addr_entry, strict=False).num_addresses @jinja_filter('network_size') def network_size(value, options=None, version=None): ''' Get the size of a network. ''' ipaddr_filter_out = _filter_ipaddr(value, options=options, version=version) if not ipaddr_filter_out: return if not isinstance(value, (list, tuple, types.GeneratorType)): return _network_size(ipaddr_filter_out[0]) return [ _network_size(ip_a) for ip_a in ipaddr_filter_out ] def natural_ipv4_netmask(ip, fmt='prefixlen'): ''' Returns the "natural" mask of an IPv4 address ''' bits = _ipv4_to_bits(ip) if bits.startswith('11'): mask = '24' elif bits.startswith('1'): mask = '16' else: mask = '8' if fmt == 'netmask': return cidr_to_ipv4_netmask(mask) else: return '/' + mask def rpad_ipv4_network(ip): ''' Returns an IP network address padded with zeros. Ex: '192.168.3' -> '192.168.3.0' '10.209' -> '10.209.0.0' ''' return '.'.join(itertools.islice(itertools.chain(ip.split('.'), '0000'), 0, 4)) def cidr_to_ipv4_netmask(cidr_bits): ''' Returns an IPv4 netmask ''' try: cidr_bits = int(cidr_bits) if not 1 <= cidr_bits <= 32: return '' except ValueError: return '' netmask = '' for idx in range(4): if idx: netmask += '.' if cidr_bits >= 8: netmask += '255' cidr_bits -= 8 else: netmask += '{0:d}'.format(256 - (2 ** (8 - cidr_bits))) cidr_bits = 0 return netmask def _number_of_set_bits_to_ipv4_netmask(set_bits): # pylint: disable=C0103 ''' Returns an IPv4 netmask from the integer representation of that mask. Ex. 0xffffff00 -> '255.255.255.0' ''' return cidr_to_ipv4_netmask(_number_of_set_bits(set_bits)) # pylint: disable=C0103 def _number_of_set_bits(x): ''' Returns the number of bits that are set in a 32bit int ''' # Taken from http://stackoverflow.com/a/4912729. Many thanks! x -= (x >> 1) & 0x55555555 x = ((x >> 2) & 0x33333333) + (x & 0x33333333) x = ((x >> 4) + x) & 0x0f0f0f0f x += x >> 8 x += x >> 16 return x & 0x0000003f # pylint: enable=C0103 def _interfaces_ip(out): ''' Uses ip to return a dictionary of interfaces with various information about each (up/down state, ip address, netmask, and hwaddr) ''' ret = dict() def parse_network(value, cols): ''' Return a tuple of ip, netmask, broadcast based on the current set of cols ''' brd = None scope = None if '/' in value: # we have a CIDR in this address ip, cidr = value.split('/') # pylint: disable=C0103 else: ip = value # pylint: disable=C0103 cidr = 32 if type_ == 'inet': mask = cidr_to_ipv4_netmask(int(cidr)) if 'brd' in cols: brd = cols[cols.index('brd') + 1] elif type_ == 'inet6': mask = cidr if 'scope' in cols: scope = cols[cols.index('scope') + 1] return (ip, mask, brd, scope) groups = re.compile('\r?\n\\d').split(out) for group in groups: iface = None data = dict() for line in group.splitlines(): if ' ' not in line: continue match = re.match(r'^\d*:\s+([\w.\-]+)(?:@)?([\w.\-]+)?:\s+<(.+)>', line) if match: iface, parent, attrs = match.groups() if 'UP' in attrs.split(','): data['up'] = True else: data['up'] = False if parent: data['parent'] = parent continue cols = line.split() if len(cols) >= 2: type_, value = tuple(cols[0:2]) iflabel = cols[-1:][0] if type_ in ('inet', 'inet6'): if 'secondary' not in cols: ipaddr, netmask, broadcast, scope = parse_network(value, cols) if type_ == 'inet': if 'inet' not in data: data['inet'] = list() addr_obj = dict() addr_obj['address'] = ipaddr addr_obj['netmask'] = netmask addr_obj['broadcast'] = broadcast addr_obj['label'] = iflabel data['inet'].append(addr_obj) elif type_ == 'inet6': if 'inet6' not in data: data['inet6'] = list() addr_obj = dict() addr_obj['address'] = ipaddr addr_obj['prefixlen'] = netmask addr_obj['scope'] = scope data['inet6'].append(addr_obj) else: if 'secondary' not in data: data['secondary'] = list() ip_, mask, brd, scp = parse_network(value, cols) data['secondary'].append({ 'type': type_, 'address': ip_, 'netmask': mask, 'broadcast': brd, 'label': iflabel, }) del ip_, mask, brd, scp elif type_.startswith('link'): data['hwaddr'] = value if iface: ret[iface] = data del iface, data return ret def _interfaces_ifconfig(out): ''' Uses ifconfig to return a dictionary of interfaces with various information about each (up/down state, ip address, netmask, and hwaddr) ''' ret = dict() piface = re.compile(r'^([^\s:]+)') pmac = re.compile('.*?(?:HWaddr|ether|address:|lladdr) ([0-9a-fA-F:]+)') if salt.utils.platform.is_sunos(): pip = re.compile(r'.*?(?:inet\s+)([0-9]+\.[0-9]+\.[0-9]+\.[0-9]+)(.*)') pip6 = re.compile('.*?(?:inet6 )([0-9a-fA-F:]+)') pmask6 = re.compile(r'.*?(?:inet6 [0-9a-fA-F:]+/(\d+)).*') else: pip = re.compile(r'.*?(?:inet addr:|inet [^\d]*)(.*?)\s') pip6 = re.compile('.*?(?:inet6 addr: (.*?)/|inet6 )([0-9a-fA-F:]+)') pmask6 = re.compile(r'.*?(?:inet6 addr: [0-9a-fA-F:]+/(\d+)|prefixlen (\d+))(?: Scope:([a-zA-Z]+)| scopeid (0x[0-9a-fA-F]))?') pmask = re.compile(r'.*?(?:Mask:|netmask )(?:((?:0x)?[0-9a-fA-F]{8})|([\d\.]+))') pupdown = re.compile('UP') pbcast = re.compile(r'.*?(?:Bcast:|broadcast )([\d\.]+)') groups = re.compile('\r?\n(?=\\S)').split(out) for group in groups: data = dict() iface = '' updown = False for line in group.splitlines(): miface = piface.match(line) mmac = pmac.match(line) mip = pip.match(line) mip6 = pip6.match(line) mupdown = pupdown.search(line) if miface: iface = miface.group(1) if mmac: data['hwaddr'] = mmac.group(1) if salt.utils.platform.is_sunos(): expand_mac = [] for chunk in data['hwaddr'].split(':'): expand_mac.append('0{0}'.format(chunk) if len(chunk) < 2 else '{0}'.format(chunk)) data['hwaddr'] = ':'.join(expand_mac) if mip: if 'inet' not in data: data['inet'] = list() addr_obj = dict() addr_obj['address'] = mip.group(1) mmask = pmask.match(line) if mmask: if mmask.group(1): mmask = _number_of_set_bits_to_ipv4_netmask( int(mmask.group(1), 16)) else: mmask = mmask.group(2) addr_obj['netmask'] = mmask mbcast = pbcast.match(line) if mbcast: addr_obj['broadcast'] = mbcast.group(1) data['inet'].append(addr_obj) if mupdown: updown = True if mip6: if 'inet6' not in data: data['inet6'] = list() addr_obj = dict() addr_obj['address'] = mip6.group(1) or mip6.group(2) mmask6 = pmask6.match(line) if mmask6: addr_obj['prefixlen'] = mmask6.group(1) or mmask6.group(2) if not salt.utils.platform.is_sunos(): ipv6scope = mmask6.group(3) or mmask6.group(4) addr_obj['scope'] = ipv6scope.lower() if ipv6scope is not None else ipv6scope # SunOS sometimes has ::/0 as inet6 addr when using addrconf if not salt.utils.platform.is_sunos() \ or addr_obj['address'] != '::' \ and addr_obj['prefixlen'] != 0: data['inet6'].append(addr_obj) data['up'] = updown if iface in ret: # SunOS optimization, where interfaces occur twice in 'ifconfig -a' # output with the same name: for ipv4 and then for ipv6 addr family. # Every instance has it's own 'UP' status and we assume that ipv4 # status determines global interface status. # # merge items with higher priority for older values # after that merge the inet and inet6 sub items for both ret[iface] = dict(list(data.items()) + list(ret[iface].items())) if 'inet' in data: ret[iface]['inet'].extend(x for x in data['inet'] if x not in ret[iface]['inet']) if 'inet6' in data: ret[iface]['inet6'].extend(x for x in data['inet6'] if x not in ret[iface]['inet6']) else: ret[iface] = data del data return ret def linux_interfaces(): ''' Obtain interface information for *NIX/BSD variants ''' ifaces = dict() ip_path = salt.utils.path.which('ip') ifconfig_path = None if ip_path else salt.utils.path.which('ifconfig') if ip_path: cmd1 = subprocess.Popen( '{0} link show'.format(ip_path), shell=True, close_fds=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT).communicate()[0] cmd2 = subprocess.Popen( '{0} addr show'.format(ip_path), shell=True, close_fds=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT).communicate()[0] ifaces = _interfaces_ip("{0}\n{1}".format( salt.utils.stringutils.to_str(cmd1), salt.utils.stringutils.to_str(cmd2))) elif ifconfig_path: cmd = subprocess.Popen( '{0} -a'.format(ifconfig_path), shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT).communicate()[0] ifaces = _interfaces_ifconfig(salt.utils.stringutils.to_str(cmd)) return ifaces def _netbsd_interfaces_ifconfig(out): ''' Uses ifconfig to return a dictionary of interfaces with various information about each (up/down state, ip address, netmask, and hwaddr) ''' ret = dict() piface = re.compile(r'^([^\s:]+)') pmac = re.compile('.*?address: ([0-9a-f:]+)') pip = re.compile(r'.*?inet [^\d]*(.*?)/([\d]*)\s') pip6 = re.compile(r'.*?inet6 ([0-9a-f:]+)%([a-zA-Z0-9]*)/([\d]*)\s') pupdown = re.compile('UP') pbcast = re.compile(r'.*?broadcast ([\d\.]+)') groups = re.compile('\r?\n(?=\\S)').split(out) for group in groups: data = dict() iface = '' updown = False for line in group.splitlines(): miface = piface.match(line) mmac = pmac.match(line) mip = pip.match(line) mip6 = pip6.match(line) mupdown = pupdown.search(line) if miface: iface = miface.group(1) if mmac: data['hwaddr'] = mmac.group(1) if mip: if 'inet' not in data: data['inet'] = list() addr_obj = dict() addr_obj['address'] = mip.group(1) mmask = mip.group(2) if mip.group(2): addr_obj['netmask'] = cidr_to_ipv4_netmask(mip.group(2)) mbcast = pbcast.match(line) if mbcast: addr_obj['broadcast'] = mbcast.group(1) data['inet'].append(addr_obj) if mupdown: updown = True if mip6: if 'inet6' not in data: data['inet6'] = list() addr_obj = dict() addr_obj['address'] = mip6.group(1) mmask6 = mip6.group(3) addr_obj['scope'] = mip6.group(2) addr_obj['prefixlen'] = mip6.group(3) data['inet6'].append(addr_obj) data['up'] = updown ret[iface] = data del data return ret def netbsd_interfaces(): ''' Obtain interface information for NetBSD >= 8 where the ifconfig output diverged from other BSD variants (Netmask is now part of the address) ''' # NetBSD versions prior to 8.0 can still use linux_interfaces() if LooseVersion(os.uname()[2]) < LooseVersion('8.0'): return linux_interfaces() ifconfig_path = salt.utils.path.which('ifconfig') cmd = subprocess.Popen( '{0} -a'.format(ifconfig_path), shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT).communicate()[0] return _netbsd_interfaces_ifconfig(salt.utils.stringutils.to_str(cmd)) def _interfaces_ipconfig(out): ''' Returns a dictionary of interfaces with various information about each (up/down state, ip address, netmask, and hwaddr) NOTE: This is not used by any function and may be able to be removed in the future. ''' ifaces = dict() iface = None adapter_iface_regex = re.compile(r'adapter (\S.+):$') for line in out.splitlines(): if not line: continue # TODO what does Windows call Infiniband and 10/40gige adapters if line.startswith('Ethernet'): iface = ifaces[adapter_iface_regex.search(line).group(1)] iface['up'] = True addr = None continue if iface: key, val = line.split(',', 1) key = key.strip(' .') val = val.strip() if addr and key == 'Subnet Mask': addr['netmask'] = val elif key in ('IP Address', 'IPv4 Address'): if 'inet' not in iface: iface['inet'] = list() addr = {'address': val.rstrip('(Preferred)'), 'netmask': None, 'broadcast': None} # TODO find the broadcast iface['inet'].append(addr) elif 'IPv6 Address' in key: if 'inet6' not in iface: iface['inet'] = list() # XXX What is the prefixlen!? addr = {'address': val.rstrip('(Preferred)'), 'prefixlen': None} iface['inet6'].append(addr) elif key == 'Physical Address': iface['hwaddr'] = val elif key == 'Media State': # XXX seen used for tunnel adaptors # might be useful iface['up'] = (val != 'Media disconnected') def win_interfaces(): ''' Obtain interface information for Windows systems ''' with salt.utils.winapi.Com(): c = wmi.WMI() ifaces = {} for iface in c.Win32_NetworkAdapterConfiguration(IPEnabled=1): ifaces[iface.Description] = dict() if iface.MACAddress: ifaces[iface.Description]['hwaddr'] = iface.MACAddress if iface.IPEnabled: ifaces[iface.Description]['up'] = True for ip in iface.IPAddress: if '.' in ip: if 'inet' not in ifaces[iface.Description]: ifaces[iface.Description]['inet'] = [] item = {'address': ip, 'label': iface.Description} if iface.DefaultIPGateway: broadcast = next((i for i in iface.DefaultIPGateway if '.' in i), '') if broadcast: item['broadcast'] = broadcast if iface.IPSubnet: netmask = next((i for i in iface.IPSubnet if '.' in i), '') if netmask: item['netmask'] = netmask ifaces[iface.Description]['inet'].append(item) if ':' in ip: if 'inet6' not in ifaces[iface.Description]: ifaces[iface.Description]['inet6'] = [] item = {'address': ip} if iface.DefaultIPGateway: broadcast = next((i for i in iface.DefaultIPGateway if ':' in i), '') if broadcast: item['broadcast'] = broadcast if iface.IPSubnet: netmask = next((i for i in iface.IPSubnet if ':' in i), '') if netmask: item['netmask'] = netmask ifaces[iface.Description]['inet6'].append(item) else: ifaces[iface.Description]['up'] = False return ifaces def interfaces(): ''' Return a dictionary of information about all the interfaces on the minion ''' if salt.utils.platform.is_windows(): return win_interfaces() elif salt.utils.platform.is_netbsd(): return netbsd_interfaces() else: return linux_interfaces() def get_net_start(ipaddr, netmask): ''' Return the address of the network ''' net = ipaddress.ip_network('{0}/{1}'.format(ipaddr, netmask), strict=False) return six.text_type(net.network_address) def get_net_size(mask): ''' Turns an IPv4 netmask into it's corresponding prefix length (255.255.255.0 -> 24 as in 192.168.1.10/24). ''' binary_str = '' for octet in mask.split('.'): binary_str += bin(int(octet))[2:].zfill(8) return len(binary_str.rstrip('0')) def calc_net(ipaddr, netmask=None): ''' Takes IP (CIDR notation supported) and optionally netmask and returns the network in CIDR-notation. (The IP can be any IP inside the subnet) ''' if netmask is not None: ipaddr = '{0}/{1}'.format(ipaddr, netmask) return six.text_type(ipaddress.ip_network(ipaddr, strict=False)) def _ipv4_to_bits(ipaddr): ''' Accepts an IPv4 dotted quad and returns a string representing its binary counterpart ''' return ''.join([bin(int(x))[2:].rjust(8, '0') for x in ipaddr.split('.')]) def _get_iface_info(iface): ''' If `iface` is available, return interface info and no error, otherwise return no info and log and return an error ''' iface_info = interfaces() if iface in iface_info.keys(): return iface_info, False else: error_msg = ('Interface "{0}" not in available interfaces: "{1}"' ''.format(iface, '", "'.join(iface_info.keys()))) log.error(error_msg) return None, error_msg def _hw_addr_aix(iface): ''' Return the hardware address (a.k.a. MAC address) for a given interface on AIX MAC address not available in through interfaces ''' cmd = subprocess.Popen( 'entstat -d {0} | grep \'Hardware Address\''.format(iface), shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT).communicate()[0] if cmd: comps = cmd.split(' ') if len(comps) == 3: mac_addr = comps[2].strip('\'').strip() return mac_addr error_msg = ('Interface "{0}" either not available or does not contain a hardware address'.format(iface)) log.error(error_msg) return error_msg def hw_addr(iface): ''' Return the hardware address (a.k.a. MAC address) for a given interface .. versionchanged:: 2016.11.4 Added support for AIX ''' if salt.utils.platform.is_aix(): return _hw_addr_aix iface_info, error = _get_iface_info(iface) if error is False: return iface_info.get(iface, {}).get('hwaddr', '') else: return error def interface(iface): ''' Return the details of `iface` or an error if it does not exist ''' iface_info, error = _get_iface_info(iface) if error is False: return iface_info.get(iface, {}).get('inet', '') else: return error def interface_ip(iface): ''' Return `iface` IPv4 addr or an error if `iface` does not exist ''' iface_info, error = _get_iface_info(iface) if error is False: inet = iface_info.get(iface, {}).get('inet', None) return inet[0].get('address', '') if inet else '' else: return error def _subnets(proto='inet', interfaces_=None): ''' Returns a list of subnets to which the host belongs ''' if interfaces_ is None: ifaces = interfaces() elif isinstance(interfaces_, list): ifaces = {} for key, value in six.iteritems(interfaces()): if key in interfaces_: ifaces[key] = value else: ifaces = {interfaces_: interfaces().get(interfaces_, {})} ret = set() if proto == 'inet': subnet = 'netmask' dflt_cidr = 32 elif proto == 'inet6': subnet = 'prefixlen' dflt_cidr = 128 else: log.error('Invalid proto %s calling subnets()', proto) return for ip_info in six.itervalues(ifaces): addrs = ip_info.get(proto, []) addrs.extend([addr for addr in ip_info.get('secondary', []) if addr.get('type') == proto]) for intf in addrs: if subnet in intf: intf = ipaddress.ip_interface('{0}/{1}'.format(intf['address'], intf[subnet])) else: intf = ipaddress.ip_interface('{0}/{1}'.format(intf['address'], dflt_cidr)) if not intf.is_loopback: ret.add(intf.network) return [six.text_type(net) for net in sorted(ret)] def subnets(interfaces=None): ''' Returns a list of IPv4 subnets to which the host belongs ''' return _subnets('inet', interfaces_=interfaces) def subnets6(): ''' Returns a list of IPv6 subnets to which the host belongs ''' return _subnets('inet6') def in_subnet(cidr, addr=None): ''' Returns True if host or (any of) addrs is within specified subnet, otherwise False ''' try: cidr = ipaddress.ip_network(cidr) except ValueError: log.error('Invalid CIDR \'%s\'', cidr) return False if addr is None: addr = ip_addrs() addr.extend(ip_addrs6()) elif not isinstance(addr, (list, tuple)): addr = (addr,) return any(ipaddress.ip_address(item) in cidr for item in addr) def _ip_addrs(interface=None, include_loopback=False, interface_data=None, proto='inet'): ''' Return the full list of IP adresses matching the criteria proto = inet|inet6 ''' ret = set() ifaces = interface_data \ if isinstance(interface_data, dict) \ else interfaces() if interface is None: target_ifaces = ifaces else: target_ifaces = dict([(k, v) for k, v in six.iteritems(ifaces) if k == interface]) if not target_ifaces: log.error('Interface %s not found.', interface) for ip_info in six.itervalues(target_ifaces): addrs = ip_info.get(proto, []) addrs.extend([addr for addr in ip_info.get('secondary', []) if addr.get('type') == proto]) for addr in addrs: addr = ipaddress.ip_address(addr.get('address')) if not addr.is_loopback or include_loopback: ret.add(addr) return [six.text_type(addr) for addr in sorted(ret)] def ip_addrs(interface=None, include_loopback=False, interface_data=None): ''' Returns a list of IPv4 addresses assigned to the host. 127.0.0.1 is ignored, unless 'include_loopback=True' is indicated. If 'interface' is provided, then only IP addresses from that interface will be returned. ''' return _ip_addrs(interface, include_loopback, interface_data, 'inet') def ip_addrs6(interface=None, include_loopback=False, interface_data=None): ''' Returns a list of IPv6 addresses assigned to the host. ::1 is ignored, unless 'include_loopback=True' is indicated. If 'interface' is provided, then only IP addresses from that interface will be returned. ''' return _ip_addrs(interface, include_loopback, interface_data, 'inet6') def hex2ip(hex_ip, invert=False): ''' Convert a hex string to an ip, if a failure occurs the original hex is returned. If 'invert=True' assume that ip from /proc/net/<proto> ''' if len(hex_ip) == 32: # ipv6 ip = [] for i in range(0, 32, 8): ip_part = hex_ip[i:i + 8] ip_part = [ip_part[x:x + 2] for x in range(0, 8, 2)] if invert: ip.append("{0[3]}{0[2]}:{0[1]}{0[0]}".format(ip_part)) else: ip.append("{0[0]}{0[1]}:{0[2]}{0[3]}".format(ip_part)) try: address = ipaddress.IPv6Address(":".join(ip)) if address.ipv4_mapped: return str(address.ipv4_mapped) else: return address.compressed except ipaddress.AddressValueError as ex: log.error('hex2ip - ipv6 address error: %s', ex) return hex_ip try: hip = int(hex_ip, 16) except ValueError: return hex_ip if invert: return '{3}.{2}.{1}.{0}'.format(hip >> 24 & 255, hip >> 16 & 255, hip >> 8 & 255, hip & 255) return '{0}.{1}.{2}.{3}'.format(hip >> 24 & 255, hip >> 16 & 255, hip >> 8 & 255, hip & 255) def mac2eui64(mac, prefix=None): ''' Convert a MAC address to a EUI64 identifier or, with prefix provided, a full IPv6 address ''' # http://tools.ietf.org/html/rfc4291#section-2.5.1 eui64 = re.sub(r'[.:-]', '', mac).lower() eui64 = eui64[0:6] + 'fffe' + eui64[6:] eui64 = hex(int(eui64[0:2], 16) | 2)[2:].zfill(2) + eui64[2:] if prefix is None: return ':'.join(re.findall(r'.{4}', eui64)) else: try: net = ipaddress.ip_network(prefix, strict=False) euil = int('0x{0}'.format(eui64), 16) return '{0}/{1}'.format(net[euil], net.prefixlen) except Exception: return def active_tcp(): ''' Return a dict describing all active tcp connections as quickly as possible ''' ret = {} for statf in ['/proc/net/tcp', '/proc/net/tcp6']: if os.path.isfile(statf): with salt.utils.files.fopen(statf, 'rb') as fp_: for line in fp_: line = salt.utils.stringutils.to_unicode(line) if line.strip().startswith('sl'): continue iret = _parse_tcp_line(line) sl = next(iter(iret)) if iret[sl]['state'] == 1: # 1 is ESTABLISHED del iret[sl]['state'] ret[len(ret)] = iret[sl] return ret def local_port_tcp(port): ''' Return a set of remote ip addrs attached to the specified local port ''' ret = _remotes_on(port, 'local_port') return ret def remote_port_tcp(port): ''' Return a set of ip addrs the current host is connected to on given port ''' ret = _remotes_on(port, 'remote_port') return ret def _remotes_on(port, which_end): ''' Return a set of ip addrs active tcp connections ''' port = int(port) ret = _netlink_tool_remote_on(port, which_end) if ret is not None: return ret ret = set() proc_available = False for statf in ['/proc/net/tcp', '/proc/net/tcp6']: if os.path.isfile(statf): proc_available = True with salt.utils.files.fopen(statf, 'r') as fp_: for line in fp_: line = salt.utils.stringutils.to_unicode(line) if line.strip().startswith('sl'): continue iret = _parse_tcp_line(line) sl = next(iter(iret)) if iret[sl][which_end] == port and iret[sl]['state'] == 1: # 1 is ESTABLISHED ret.add(iret[sl]['remote_addr']) if not proc_available: # Fallback to use OS specific tools if salt.utils.platform.is_sunos(): return _sunos_remotes_on(port, which_end) if salt.utils.platform.is_freebsd(): return _freebsd_remotes_on(port, which_end) if salt.utils.platform.is_netbsd(): return _netbsd_remotes_on(port, which_end) if salt.utils.platform.is_openbsd(): return _openbsd_remotes_on(port, which_end) if salt.utils.platform.is_windows(): return _windows_remotes_on(port, which_end) if salt.utils.platform.is_aix(): return _aix_remotes_on(port, which_end) return _linux_remotes_on(port, which_end) return ret def _parse_tcp_line(line): ''' Parse a single line from the contents of /proc/net/tcp or /proc/net/tcp6 ''' ret = {} comps = line.strip().split() sl = comps[0].rstrip(':') ret[sl] = {} l_addr, l_port = comps[1].split(':') r_addr, r_port = comps[2].split(':') ret[sl]['local_addr'] = hex2ip(l_addr, True) ret[sl]['local_port'] = int(l_port, 16) ret[sl]['remote_addr'] = hex2ip(r_addr, True) ret[sl]['remote_port'] = int(r_port, 16) ret[sl]['state'] = int(comps[3], 16) return ret def _netlink_tool_remote_on(port, which_end): ''' Returns set of ipv4 host addresses of remote established connections on local or remote tcp port. Parses output of shell 'ss' to get connections [root@salt-master ~]# ss -ant State Recv-Q Send-Q Local Address:Port Peer Address:Port LISTEN 0 511 *:80 *:* LISTEN 0 128 *:22 *:* ESTAB 0 0 127.0.0.1:56726 127.0.0.1:4505 ''' remotes = set() valid = False try: data = subprocess.check_output(['ss', '-ant']) # pylint: disable=minimum-python-version except subprocess.CalledProcessError: log.error('Failed ss') raise except OSError: # not command "No such file or directory" return None lines = salt.utils.stringutils.to_str(data).split('\n') for line in lines: if 'Address:Port' in line: # ss tools may not be valid valid = True continue elif 'ESTAB' not in line: continue chunks = line.split() local_host, local_port = chunks[3].split(':', 1) remote_host, remote_port = chunks[4].split(':', 1) if which_end == 'remote_port' and int(remote_port) != port: continue if which_end == 'local_port' and int(local_port) != port: continue remotes.add(remote_host) if valid is False: remotes = None return remotes def _sunos_remotes_on(port, which_end): ''' SunOS specific helper function. Returns set of ipv4 host addresses of remote established connections on local or remote tcp port. Parses output of shell 'netstat' to get connections [root@salt-master ~]# netstat -f inet -n TCP: IPv4 Local Address Remote Address Swind Send-Q Rwind Recv-Q State -------------------- -------------------- ----- ------ ----- ------ ----------- 10.0.0.101.4505 10.0.0.1.45329 1064800 0 1055864 0 ESTABLISHED 10.0.0.101.4505 10.0.0.100.50798 1064800 0 1055864 0 ESTABLISHED ''' remotes = set() try: data = subprocess.check_output(['netstat', '-f', 'inet', '-n']) # pylint: disable=minimum-python-version except subprocess.CalledProcessError: log.error('Failed netstat') raise lines = salt.utils.stringutils.to_str(data).split('\n') for line in lines: if 'ESTABLISHED' not in line: continue chunks = line.split() local_host, local_port = chunks[0].rsplit('.', 1) remote_host, remote_port = chunks[1].rsplit('.', 1) if which_end == 'remote_port' and int(remote_port) != port: continue if which_end == 'local_port' and int(local_port) != port: continue remotes.add(remote_host) return remotes def _freebsd_remotes_on(port, which_end): ''' Returns set of ipv4 host addresses of remote established connections on local tcp port port. Parses output of shell 'sockstat' (FreeBSD) to get connections $ sudo sockstat -4 USER COMMAND PID FD PROTO LOCAL ADDRESS FOREIGN ADDRESS root python2.7 1456 29 tcp4 *:4505 *:* root python2.7 1445 17 tcp4 *:4506 *:* root python2.7 1294 14 tcp4 127.0.0.1:11813 127.0.0.1:4505 root python2.7 1294 41 tcp4 127.0.0.1:61115 127.0.0.1:4506 $ sudo sockstat -4 -c -p 4506 USER COMMAND PID FD PROTO LOCAL ADDRESS FOREIGN ADDRESS root python2.7 1294 41 tcp4 127.0.0.1:61115 127.0.0.1:4506 ''' port = int(port) remotes = set() try: cmd = salt.utils.args.shlex_split('sockstat -4 -c -p {0}'.format(port)) data = subprocess.check_output(cmd) # pylint: disable=minimum-python-version except subprocess.CalledProcessError as ex: log.error('Failed "sockstat" with returncode = %s', ex.returncode) raise lines = salt.utils.stringutils.to_str(data).split('\n') for line in lines: chunks = line.split() if not chunks: continue # ['root', 'python2.7', '1456', '37', 'tcp4', # '127.0.0.1:4505-', '127.0.0.1:55703'] # print chunks if 'COMMAND' in chunks[1]: continue # ignore header if len(chunks) < 2: continue # sockstat -4 -c -p 4506 does this with high PIDs: # USER COMMAND PID FD PROTO LOCAL ADDRESS FOREIGN ADDRESS # salt-master python2.781106 35 tcp4 192.168.12.34:4506 192.168.12.45:60143 local = chunks[-2] remote = chunks[-1] lhost, lport = local.split(':') rhost, rport = remote.split(':') if which_end == 'local' and int(lport) != port: # ignore if local port not port continue if which_end == 'remote' and int(rport) != port: # ignore if remote port not port continue remotes.add(rhost) return remotes def _openbsd_remotes_on(port, which_end): ''' OpenBSD specific helper function. Returns set of ipv4 host addresses of remote established connections on local or remote tcp port. Parses output of shell 'netstat' to get connections $ netstat -nf inet Active Internet connections Proto Recv-Q Send-Q Local Address Foreign Address (state) tcp 0 0 10.0.0.101.4505 10.0.0.1.45329 ESTABLISHED tcp 0 0 10.0.0.101.4505 10.0.0.100.50798 ESTABLISHED ''' remotes = set() try: data = subprocess.check_output(['netstat', '-nf', 'inet']) # pylint: disable=minimum-python-version except subprocess.CalledProcessError: log.error('Failed netstat') raise lines = data.split('\n') for line in lines: if 'ESTABLISHED' not in line: continue chunks = line.split() local_host, local_port = chunks[3].rsplit('.', 1) remote_host, remote_port = chunks[4].rsplit('.', 1) if which_end == 'remote_port' and int(remote_port) != port: continue if which_end == 'local_port' and int(local_port) != port: continue remotes.add(remote_host) return remotes def _windows_remotes_on(port, which_end): r''' Windows specific helper function. Returns set of ipv4 host addresses of remote established connections on local or remote tcp port. Parses output of shell 'netstat' to get connections C:\>netstat -n Active Connections Proto Local Address Foreign Address State TCP 10.2.33.17:3007 130.164.12.233:10123 ESTABLISHED TCP 10.2.33.17:3389 130.164.30.5:10378 ESTABLISHED ''' remotes = set() try: data = subprocess.check_output(['netstat', '-n']) # pylint: disable=minimum-python-version except subprocess.CalledProcessError: log.error('Failed netstat') raise lines = salt.utils.stringutils.to_str(data).split('\n') for line in lines: if 'ESTABLISHED' not in line: continue chunks = line.split() local_host, local_port = chunks[1].rsplit(':', 1) remote_host, remote_port = chunks[2].rsplit(':', 1) if which_end == 'remote_port' and int(remote_port) != port: continue if which_end == 'local_port' and int(local_port) != port: continue remotes.add(remote_host) return remotes def _linux_remotes_on(port, which_end): ''' Linux specific helper function. Returns set of ip host addresses of remote established connections on local tcp port port. Parses output of shell 'lsof' to get connections $ sudo lsof -iTCP:4505 -n COMMAND PID USER FD TYPE DEVICE SIZE/OFF NODE NAME Python 9971 root 35u IPv4 0x18a8464a29ca329d 0t0 TCP *:4505 (LISTEN) Python 9971 root 37u IPv4 0x18a8464a29b2b29d 0t0 TCP 127.0.0.1:4505->127.0.0.1:55703 (ESTABLISHED) Python 10152 root 22u IPv4 0x18a8464a29c8cab5 0t0 TCP 127.0.0.1:55703->127.0.0.1:4505 (ESTABLISHED) Python 10153 root 22u IPv4 0x18a8464a29c8cab5 0t0 TCP [fe80::249a]:4505->[fe80::150]:59367 (ESTABLISHED) ''' remotes = set() try: data = subprocess.check_output( ['lsof', '-iTCP:{0:d}'.format(port), '-n', '-P'] # pylint: disable=minimum-python-version ) except subprocess.CalledProcessError as ex: if ex.returncode == 1: # Lsof return 1 if any error was detected, including the failure # to locate Internet addresses, and it is not an error in this case. log.warning('"lsof" returncode = 1, likely no active TCP sessions.') return remotes log.error('Failed "lsof" with returncode = %s', ex.returncode) raise lines = salt.utils.stringutils.to_str(data).split('\n') for line in lines: chunks = line.split() if not chunks: continue # ['Python', '9971', 'root', '37u', 'IPv4', '0x18a8464a29b2b29d', '0t0', # 'TCP', '127.0.0.1:4505->127.0.0.1:55703', '(ESTABLISHED)'] # print chunks if 'COMMAND' in chunks[0]: continue # ignore header if 'ESTABLISHED' not in chunks[-1]: continue # ignore if not ESTABLISHED # '127.0.0.1:4505->127.0.0.1:55703' local, remote = chunks[8].split('->') _, lport = local.rsplit(':', 1) rhost, rport = remote.rsplit(':', 1) if which_end == 'remote_port' and int(rport) != port: continue if which_end == 'local_port' and int(lport) != port: continue remotes.add(rhost.strip("[]")) return remotes def _aix_remotes_on(port, which_end): ''' AIX specific helper function. Returns set of ipv4 host addresses of remote established connections on local or remote tcp port. Parses output of shell 'netstat' to get connections root@la68pp002_pub:/opt/salt/lib/python2.7/site-packages/salt/modules# netstat -f inet -n Active Internet connections Proto Recv-Q Send-Q Local Address Foreign Address (state) tcp4 0 0 172.29.149.95.50093 209.41.78.13.4505 ESTABLISHED tcp4 0 0 127.0.0.1.9514 *.* LISTEN tcp4 0 0 127.0.0.1.9515 *.* LISTEN tcp4 0 0 127.0.0.1.199 127.0.0.1.32779 ESTABLISHED tcp4 0 0 127.0.0.1.32779 127.0.0.1.199 ESTABLISHED tcp4 0 40 172.29.149.95.22 172.29.96.83.41022 ESTABLISHED tcp4 0 0 172.29.149.95.22 172.29.96.83.41032 ESTABLISHED tcp4 0 0 127.0.0.1.32771 127.0.0.1.32775 ESTABLISHED tcp 0 0 127.0.0.1.32775 127.0.0.1.32771 ESTABLISHED tcp4 0 0 127.0.0.1.32771 127.0.0.1.32776 ESTABLISHED tcp 0 0 127.0.0.1.32776 127.0.0.1.32771 ESTABLISHED tcp4 0 0 127.0.0.1.32771 127.0.0.1.32777 ESTABLISHED tcp 0 0 127.0.0.1.32777 127.0.0.1.32771 ESTABLISHED tcp4 0 0 127.0.0.1.32771 127.0.0.1.32778 ESTABLISHED tcp 0 0 127.0.0.1.32778 127.0.0.1.32771 ESTABLISHED ''' remotes = set() try: data = subprocess.check_output(['netstat', '-f', 'inet', '-n']) # pylint: disable=minimum-python-version except subprocess.CalledProcessError: log.error('Failed netstat') raise lines = salt.utils.stringutils.to_str(data).split('\n') for line in lines: if 'ESTABLISHED' not in line: continue chunks = line.split() local_host, local_port = chunks[3].rsplit('.', 1) remote_host, remote_port = chunks[4].rsplit('.', 1) if which_end == 'remote_port' and int(remote_port) != port: continue if which_end == 'local_port' and int(local_port) != port: continue remotes.add(remote_host) return remotes @jinja_filter('gen_mac') def gen_mac(prefix='AC:DE:48'): ''' Generates a MAC address with the defined OUI prefix. Common prefixes: - ``00:16:3E`` -- Xen - ``00:18:51`` -- OpenVZ - ``00:50:56`` -- VMware (manually generated) - ``52:54:00`` -- QEMU/KVM - ``AC:DE:48`` -- PRIVATE References: - http://standards.ieee.org/develop/regauth/oui/oui.txt - https://www.wireshark.org/tools/oui-lookup.html - https://en.wikipedia.org/wiki/MAC_address ''' return '{0}:{1:02X}:{2:02X}:{3:02X}'.format(prefix, random.randint(0, 0xff), random.randint(0, 0xff), random.randint(0, 0xff)) @jinja_filter('mac_str_to_bytes') def mac_str_to_bytes(mac_str): ''' Convert a MAC address string into bytes. Works with or without separators: b1 = mac_str_to_bytes('08:00:27:13:69:77') b2 = mac_str_to_bytes('080027136977') assert b1 == b2 assert isinstance(b1, bytes) ''' if len(mac_str) == 12: pass elif len(mac_str) == 17: sep = mac_str[2] mac_str = mac_str.replace(sep, '') else: raise ValueError('Invalid MAC address') chars = (int(mac_str[s:s+2], 16) for s in range(0, 12, 2)) return bytes(chars) if six.PY3 else b''.join(chr(x) for x in chars) def refresh_dns(): ''' issue #21397: force glibc to re-read resolv.conf ''' try: res_init() except NameError: # Exception raised loading the library, thus res_init is not defined pass @jinja_filter('connection_check') def connection_check(addr, port=80, safe=False, ipv6=None): ''' Provides a convenient alias for the dns_check filter. ''' return dns_check(addr, port, safe, ipv6) @jinja_filter('dns_check') def dns_check(addr, port=80, safe=False, ipv6=None, attempt_connect=True): ''' Return the ip resolved by dns, but do not exit on failure, only raise an exception. Obeys system preference for IPv4/6 address resolution - this can be overridden by the ipv6 flag. Tries to connect to the address before considering it useful. If no address can be reached, the first one resolved is used as a fallback. ''' error = False lookup = addr seen_ipv6 = False family = socket.AF_INET6 if ipv6 else socket.AF_INET if ipv6 is False else socket.AF_UNSPEC hostnames = [] try: refresh_dns() hostnames = socket.getaddrinfo(addr, port, family, socket.SOCK_STREAM) except TypeError: err = ('Attempt to resolve address \'{0}\' failed. Invalid or unresolveable address').format(lookup) raise SaltSystemExit(code=42, msg=err) except socket.error: error = True # If ipv6 is set to True, attempt another lookup using the IPv4 family, # just in case we're attempting to lookup an IPv4 IP # as an IPv6 hostname. if error and ipv6: try: refresh_dns() hostnames = socket.getaddrinfo(addr, port, socket.AF_INET, socket.SOCK_STREAM) except TypeError: err = ('Attempt to resolve address \'{0}\' failed. Invalid or unresolveable address').format(lookup) raise SaltSystemExit(code=42, msg=err) except socket.error: error = True try: if not hostnames: error = True else: resolved = False candidates = [] for h in hostnames: # Input is IP address, passed through unchanged, just return it if h[4][0] == addr: resolved = salt.utils.zeromq.ip_bracket(addr) break candidate_addr = salt.utils.zeromq.ip_bracket(h[4][0]) # sometimes /etc/hosts contains ::1 localhost if not ipv6 and candidate_addr == '[::1]': continue candidates.append(candidate_addr) if attempt_connect: try: s = socket.socket(h[0], socket.SOCK_STREAM) s.settimeout(2) s.connect((candidate_addr.strip('[]'), h[4][1])) s.close() resolved = candidate_addr break except socket.error: pass if not resolved: if candidates: resolved = candidates[0] else: error = True except TypeError: err = ('Attempt to resolve address \'{0}\' failed. Invalid or unresolveable address').format(lookup) raise SaltSystemExit(code=42, msg=err) except socket.error: error = True if error: err = ('DNS lookup or connection check of \'{0}\' failed.').format(addr) if safe: if salt.log.is_console_configured(): # If logging is not configured it also means that either # the master or minion instance calling this hasn't even # started running log.error(err) raise SaltClientError() raise SaltSystemExit(code=42, msg=err) return resolved def parse_host_port(host_port): """ Takes a string argument specifying host or host:port. Returns a (hostname, port) or (ip_address, port) tuple. If no port is given, the second (port) element of the returned tuple will be None. host:port argument, for example, is accepted in the forms of: - hostname - hostname:1234 - hostname.domain.tld - hostname.domain.tld:5678 - [1234::5]:5678 - 1234::5 - 10.11.12.13:4567 - 10.11.12.13 """ host, port = None, None # default _s_ = host_port[:] if _s_[0] == "[": if "]" in host_port: host, _s_ = _s_.lstrip("[").rsplit("]", 1) host = ipaddress.IPv6Address(host).compressed if _s_[0] == ":": port = int(_s_.lstrip(":")) else: if len(_s_) > 1: raise ValueError('found ambiguous "{}" port in "{}"'.format(_s_, host_port)) else: if _s_.count(":") == 1: host, _hostport_separator_, port = _s_.partition(":") try: port = int(port) except ValueError as _e_: log.error('host_port "%s" port value "%s" is not an integer.', host_port, port) raise _e_ else: host = _s_ try: if not isinstance(host, ipaddress._BaseAddress): host_ip = ipaddress.ip_address(host).compressed host = host_ip except ValueError: log.debug('"%s" Not an IP address? Assuming it is a hostname.', host) if host != sanitize_host(host): log.error('bad hostname: "%s"', host) raise ValueError('bad hostname: "{}"'.format(host)) return host, port def is_fqdn(hostname): """ Verify if hostname conforms to be a FQDN. :param hostname: text string with the name of the host :return: bool, True if hostname is correct FQDN, False otherwise """ compliant = re.compile(r"(?!-)[A-Z\d\-\_]{1,63}(?<!-)$", re.IGNORECASE) return "." in hostname and len(hostname) < 0xff and all(compliant.match(x) for x in hostname.rstrip(".").split("."))
saltstack/salt
salt/utils/network.py
_openbsd_remotes_on
python
def _openbsd_remotes_on(port, which_end): ''' OpenBSD specific helper function. Returns set of ipv4 host addresses of remote established connections on local or remote tcp port. Parses output of shell 'netstat' to get connections $ netstat -nf inet Active Internet connections Proto Recv-Q Send-Q Local Address Foreign Address (state) tcp 0 0 10.0.0.101.4505 10.0.0.1.45329 ESTABLISHED tcp 0 0 10.0.0.101.4505 10.0.0.100.50798 ESTABLISHED ''' remotes = set() try: data = subprocess.check_output(['netstat', '-nf', 'inet']) # pylint: disable=minimum-python-version except subprocess.CalledProcessError: log.error('Failed netstat') raise lines = data.split('\n') for line in lines: if 'ESTABLISHED' not in line: continue chunks = line.split() local_host, local_port = chunks[3].rsplit('.', 1) remote_host, remote_port = chunks[4].rsplit('.', 1) if which_end == 'remote_port' and int(remote_port) != port: continue if which_end == 'local_port' and int(local_port) != port: continue remotes.add(remote_host) return remotes
OpenBSD specific helper function. Returns set of ipv4 host addresses of remote established connections on local or remote tcp port. Parses output of shell 'netstat' to get connections $ netstat -nf inet Active Internet connections Proto Recv-Q Send-Q Local Address Foreign Address (state) tcp 0 0 10.0.0.101.4505 10.0.0.1.45329 ESTABLISHED tcp 0 0 10.0.0.101.4505 10.0.0.100.50798 ESTABLISHED
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/network.py#L1664-L1698
null
# -*- coding: utf-8 -*- ''' Define some generic socket functions for network modules ''' # Import python libs from __future__ import absolute_import, unicode_literals, print_function import itertools import os import re import types import socket import logging import platform import random import subprocess from string import ascii_letters, digits # Import 3rd-party libs from salt.ext import six from salt.ext.six.moves import range # pylint: disable=import-error,redefined-builtin # Attempt to import wmi try: import wmi import salt.utils.winapi except ImportError: pass # Import salt libs import salt.utils.args import salt.utils.files import salt.utils.path import salt.utils.platform import salt.utils.stringutils import salt.utils.zeromq from salt._compat import ipaddress from salt.exceptions import SaltClientError, SaltSystemExit from salt.utils.decorators.jinja import jinja_filter from salt.utils.versions import LooseVersion # inet_pton does not exist in Windows, this is a workaround if salt.utils.platform.is_windows(): from salt.ext import win_inet_pton # pylint: disable=unused-import log = logging.getLogger(__name__) try: import ctypes import ctypes.util libc = ctypes.cdll.LoadLibrary(ctypes.util.find_library("c")) res_init = libc.__res_init except (ImportError, OSError, AttributeError, TypeError): pass # pylint: disable=C0103 def sanitize_host(host): ''' Sanitize host string. https://tools.ietf.org/html/rfc1123#section-2.1 ''' RFC952_characters = ascii_letters + digits + ".-" return "".join([c for c in host[0:255] if c in RFC952_characters]) def isportopen(host, port): ''' Return status of a port ''' if not 1 <= int(port) <= 65535: return False sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) out = sock.connect_ex((sanitize_host(host), int(port))) return out def host_to_ips(host): ''' Returns a list of IP addresses of a given hostname or None if not found. ''' ips = [] try: for family, socktype, proto, canonname, sockaddr in socket.getaddrinfo( host, 0, socket.AF_UNSPEC, socket.SOCK_STREAM): if family == socket.AF_INET: ip, port = sockaddr elif family == socket.AF_INET6: ip, port, flow_info, scope_id = sockaddr ips.append(ip) if not ips: ips = None except Exception: ips = None return ips def _generate_minion_id(): ''' Get list of possible host names and convention names. :return: ''' # There are three types of hostnames: # 1. Network names. How host is accessed from the network. # 2. Host aliases. They might be not available in all the network or only locally (/etc/hosts) # 3. Convention names, an internal nodename. class DistinctList(list): ''' List, which allows one to append only distinct objects. Needs to work on Python 2.6, because of collections.OrderedDict only since 2.7 version. Override 'filter()' for custom filtering. ''' localhost_matchers = [r'localhost.*', r'ip6-.*', r'127[.]\d', r'0\.0\.0\.0', r'::1.*', r'ipv6-.*', r'fe00::.*', r'fe02::.*', r'1.0.0.*.ip6.arpa'] def append(self, p_object): if p_object and p_object not in self and not self.filter(p_object): super(DistinctList, self).append(p_object) return self def extend(self, iterable): for obj in iterable: self.append(obj) return self def filter(self, element): 'Returns True if element needs to be filtered' for rgx in self.localhost_matchers: if re.match(rgx, element): return True def first(self): return self and self[0] or None hostname = socket.gethostname() hosts = DistinctList().append( salt.utils.stringutils.to_unicode(socket.getfqdn(salt.utils.stringutils.to_bytes(hostname))) ).append(platform.node()).append(hostname) if not hosts: try: for a_nfo in socket.getaddrinfo(hosts.first() or 'localhost', None, socket.AF_INET, socket.SOCK_RAW, socket.IPPROTO_IP, socket.AI_CANONNAME): if len(a_nfo) > 3: hosts.append(a_nfo[3]) except socket.gaierror: log.warning('Cannot resolve address %s info via socket: %s', hosts.first() or 'localhost (N/A)', socket.gaierror) # Universal method for everywhere (Linux, Slowlaris, Windows etc) for f_name in ('/etc/hostname', '/etc/nodename', '/etc/hosts', r'{win}\system32\drivers\etc\hosts'.format(win=os.getenv('WINDIR'))): try: with salt.utils.files.fopen(f_name) as f_hdl: for line in f_hdl: line = salt.utils.stringutils.to_unicode(line) hst = line.strip().split('#')[0].strip().split() if hst: if hst[0][:4] in ('127.', '::1') or len(hst) == 1: hosts.extend(hst) except IOError: pass # include public and private ipaddresses return hosts.extend([addr for addr in ip_addrs() if not ipaddress.ip_address(addr).is_loopback]) def generate_minion_id(): ''' Return only first element of the hostname from all possible list. :return: ''' try: ret = salt.utils.stringutils.to_unicode(_generate_minion_id().first()) except TypeError: ret = None return ret or 'localhost' def get_socket(addr, type=socket.SOCK_STREAM, proto=0): ''' Return a socket object for the addr IP-version agnostic ''' version = ipaddress.ip_address(addr).version if version == 4: family = socket.AF_INET elif version == 6: family = socket.AF_INET6 return socket.socket(family, type, proto) def get_fqhostname(): ''' Returns the fully qualified hostname ''' # try getaddrinfo() fqdn = None try: addrinfo = socket.getaddrinfo( socket.gethostname(), 0, socket.AF_UNSPEC, socket.SOCK_STREAM, socket.SOL_TCP, socket.AI_CANONNAME ) for info in addrinfo: # info struct [family, socktype, proto, canonname, sockaddr] # On Windows `canonname` can be an empty string # This can cause the function to return `None` if len(info) > 3 and info[3]: fqdn = info[3] break except socket.gaierror: pass # NOTE: this used to log.error() but it was later disabled except socket.error as err: log.debug('socket.getaddrinfo() failure while finding fqdn: %s', err) if fqdn is None: fqdn = socket.getfqdn() return fqdn def ip_to_host(ip): ''' Returns the hostname of a given IP ''' try: hostname, aliaslist, ipaddrlist = socket.gethostbyaddr(ip) except Exception as exc: log.debug('salt.utils.network.ip_to_host(%r) failed: %s', ip, exc) hostname = None return hostname # pylint: enable=C0103 def is_reachable_host(entity_name): ''' Returns a bool telling if the entity name is a reachable host (IPv4/IPv6/FQDN/etc). :param hostname: :return: ''' try: assert type(socket.getaddrinfo(entity_name, 0, 0, 0, 0)) == list ret = True except socket.gaierror: ret = False return ret def is_ip(ip): ''' Returns a bool telling if the passed IP is a valid IPv4 or IPv6 address. ''' return is_ipv4(ip) or is_ipv6(ip) def is_ipv4(ip): ''' Returns a bool telling if the value passed to it was a valid IPv4 address ''' try: return ipaddress.ip_address(ip).version == 4 except ValueError: return False def is_ipv6(ip): ''' Returns a bool telling if the value passed to it was a valid IPv6 address ''' try: return ipaddress.ip_address(ip).version == 6 except ValueError: return False def is_subnet(cidr): ''' Returns a bool telling if the passed string is an IPv4 or IPv6 subnet ''' return is_ipv4_subnet(cidr) or is_ipv6_subnet(cidr) def is_ipv4_subnet(cidr): ''' Returns a bool telling if the passed string is an IPv4 subnet ''' try: return '/' in cidr and bool(ipaddress.IPv4Network(cidr)) except Exception: return False def is_ipv6_subnet(cidr): ''' Returns a bool telling if the passed string is an IPv6 subnet ''' try: return '/' in cidr and bool(ipaddress.IPv6Network(cidr)) except Exception: return False @jinja_filter('is_ip') def is_ip_filter(ip, options=None): ''' Returns a bool telling if the passed IP is a valid IPv4 or IPv6 address. ''' return is_ipv4_filter(ip, options=options) or is_ipv6_filter(ip, options=options) def _ip_options_global(ip_obj, version): return not ip_obj.is_private def _ip_options_multicast(ip_obj, version): return ip_obj.is_multicast def _ip_options_loopback(ip_obj, version): return ip_obj.is_loopback def _ip_options_link_local(ip_obj, version): return ip_obj.is_link_local def _ip_options_private(ip_obj, version): return ip_obj.is_private def _ip_options_reserved(ip_obj, version): return ip_obj.is_reserved def _ip_options_site_local(ip_obj, version): if version == 6: return ip_obj.is_site_local return False def _ip_options_unspecified(ip_obj, version): return ip_obj.is_unspecified def _ip_options(ip_obj, version, options=None): # will process and IP options options_fun_map = { 'global': _ip_options_global, 'link-local': _ip_options_link_local, 'linklocal': _ip_options_link_local, 'll': _ip_options_link_local, 'link_local': _ip_options_link_local, 'loopback': _ip_options_loopback, 'lo': _ip_options_loopback, 'multicast': _ip_options_multicast, 'private': _ip_options_private, 'public': _ip_options_global, 'reserved': _ip_options_reserved, 'site-local': _ip_options_site_local, 'sl': _ip_options_site_local, 'site_local': _ip_options_site_local, 'unspecified': _ip_options_unspecified } if not options: return six.text_type(ip_obj) # IP version already checked options_list = [option.strip() for option in options.split(',')] for option, fun in options_fun_map.items(): if option in options_list: fun_res = fun(ip_obj, version) if not fun_res: return None # stop at first failed test # else continue return six.text_type(ip_obj) def _is_ipv(ip, version, options=None): if not version: version = 4 if version not in (4, 6): return None try: ip_obj = ipaddress.ip_address(ip) except ValueError: # maybe it is an IP network try: ip_obj = ipaddress.ip_interface(ip) except ValueError: # nope, still not :( return None if not ip_obj.version == version: return None # has the right version, let's move on return _ip_options(ip_obj, version, options=options) @jinja_filter('is_ipv4') def is_ipv4_filter(ip, options=None): ''' Returns a bool telling if the value passed to it was a valid IPv4 address. ip The IP address. net: False Consider IP addresses followed by netmask. options CSV of options regarding the nature of the IP address. E.g.: loopback, multicast, private etc. ''' _is_ipv4 = _is_ipv(ip, 4, options=options) return isinstance(_is_ipv4, six.string_types) @jinja_filter('is_ipv6') def is_ipv6_filter(ip, options=None): ''' Returns a bool telling if the value passed to it was a valid IPv6 address. ip The IP address. net: False Consider IP addresses followed by netmask. options CSV of options regarding the nature of the IP address. E.g.: loopback, multicast, private etc. ''' _is_ipv6 = _is_ipv(ip, 6, options=options) return isinstance(_is_ipv6, six.string_types) def _ipv_filter(value, version, options=None): if version not in (4, 6): return if isinstance(value, (six.string_types, six.text_type, six.binary_type)): return _is_ipv(value, version, options=options) # calls is_ipv4 or is_ipv6 for `value` elif isinstance(value, (list, tuple, types.GeneratorType)): # calls is_ipv4 or is_ipv6 for each element in the list # os it filters and returns only those elements having the desired IP version return [ _is_ipv(addr, version, options=options) for addr in value if _is_ipv(addr, version, options=options) is not None ] return None @jinja_filter('ipv4') def ipv4(value, options=None): ''' Filters a list and returns IPv4 values only. ''' return _ipv_filter(value, 4, options=options) @jinja_filter('ipv6') def ipv6(value, options=None): ''' Filters a list and returns IPv6 values only. ''' return _ipv_filter(value, 6, options=options) @jinja_filter('ipaddr') def ipaddr(value, options=None): ''' Filters and returns only valid IP objects. ''' ipv4_obj = ipv4(value, options=options) ipv6_obj = ipv6(value, options=options) if ipv4_obj is None or ipv6_obj is None: # an IP address can be either IPv4 either IPv6 # therefofe if the value passed as arg is not a list, at least one of the calls above will return None # if one of them is none, means that we should return only one of them return ipv4_obj or ipv6_obj # one of them else: return ipv4_obj + ipv6_obj # extend lists def _filter_ipaddr(value, options, version=None): ipaddr_filter_out = None if version: if version == 4: ipaddr_filter_out = ipv4(value, options) elif version == 6: ipaddr_filter_out = ipv6(value, options) else: ipaddr_filter_out = ipaddr(value, options) if not ipaddr_filter_out: return if not isinstance(ipaddr_filter_out, (list, tuple, types.GeneratorType)): ipaddr_filter_out = [ipaddr_filter_out] return ipaddr_filter_out @jinja_filter('ip_host') def ip_host(value, options=None, version=None): ''' Returns the interfaces IP address, e.g.: 192.168.0.1/28. ''' ipaddr_filter_out = _filter_ipaddr(value, options=options, version=version) if not ipaddr_filter_out: return if not isinstance(value, (list, tuple, types.GeneratorType)): return six.text_type(ipaddress.ip_interface(ipaddr_filter_out[0])) return [six.text_type(ipaddress.ip_interface(ip_a)) for ip_a in ipaddr_filter_out] def _network_hosts(ip_addr_entry): return [ six.text_type(host) for host in ipaddress.ip_network(ip_addr_entry, strict=False).hosts() ] @jinja_filter('network_hosts') def network_hosts(value, options=None, version=None): ''' Return the list of hosts within a network. .. note:: When running this command with a large IPv6 network, the command will take a long time to gather all of the hosts. ''' ipaddr_filter_out = _filter_ipaddr(value, options=options, version=version) if not ipaddr_filter_out: return if not isinstance(value, (list, tuple, types.GeneratorType)): return _network_hosts(ipaddr_filter_out[0]) return [ _network_hosts(ip_a) for ip_a in ipaddr_filter_out ] def _network_size(ip_addr_entry): return ipaddress.ip_network(ip_addr_entry, strict=False).num_addresses @jinja_filter('network_size') def network_size(value, options=None, version=None): ''' Get the size of a network. ''' ipaddr_filter_out = _filter_ipaddr(value, options=options, version=version) if not ipaddr_filter_out: return if not isinstance(value, (list, tuple, types.GeneratorType)): return _network_size(ipaddr_filter_out[0]) return [ _network_size(ip_a) for ip_a in ipaddr_filter_out ] def natural_ipv4_netmask(ip, fmt='prefixlen'): ''' Returns the "natural" mask of an IPv4 address ''' bits = _ipv4_to_bits(ip) if bits.startswith('11'): mask = '24' elif bits.startswith('1'): mask = '16' else: mask = '8' if fmt == 'netmask': return cidr_to_ipv4_netmask(mask) else: return '/' + mask def rpad_ipv4_network(ip): ''' Returns an IP network address padded with zeros. Ex: '192.168.3' -> '192.168.3.0' '10.209' -> '10.209.0.0' ''' return '.'.join(itertools.islice(itertools.chain(ip.split('.'), '0000'), 0, 4)) def cidr_to_ipv4_netmask(cidr_bits): ''' Returns an IPv4 netmask ''' try: cidr_bits = int(cidr_bits) if not 1 <= cidr_bits <= 32: return '' except ValueError: return '' netmask = '' for idx in range(4): if idx: netmask += '.' if cidr_bits >= 8: netmask += '255' cidr_bits -= 8 else: netmask += '{0:d}'.format(256 - (2 ** (8 - cidr_bits))) cidr_bits = 0 return netmask def _number_of_set_bits_to_ipv4_netmask(set_bits): # pylint: disable=C0103 ''' Returns an IPv4 netmask from the integer representation of that mask. Ex. 0xffffff00 -> '255.255.255.0' ''' return cidr_to_ipv4_netmask(_number_of_set_bits(set_bits)) # pylint: disable=C0103 def _number_of_set_bits(x): ''' Returns the number of bits that are set in a 32bit int ''' # Taken from http://stackoverflow.com/a/4912729. Many thanks! x -= (x >> 1) & 0x55555555 x = ((x >> 2) & 0x33333333) + (x & 0x33333333) x = ((x >> 4) + x) & 0x0f0f0f0f x += x >> 8 x += x >> 16 return x & 0x0000003f # pylint: enable=C0103 def _interfaces_ip(out): ''' Uses ip to return a dictionary of interfaces with various information about each (up/down state, ip address, netmask, and hwaddr) ''' ret = dict() def parse_network(value, cols): ''' Return a tuple of ip, netmask, broadcast based on the current set of cols ''' brd = None scope = None if '/' in value: # we have a CIDR in this address ip, cidr = value.split('/') # pylint: disable=C0103 else: ip = value # pylint: disable=C0103 cidr = 32 if type_ == 'inet': mask = cidr_to_ipv4_netmask(int(cidr)) if 'brd' in cols: brd = cols[cols.index('brd') + 1] elif type_ == 'inet6': mask = cidr if 'scope' in cols: scope = cols[cols.index('scope') + 1] return (ip, mask, brd, scope) groups = re.compile('\r?\n\\d').split(out) for group in groups: iface = None data = dict() for line in group.splitlines(): if ' ' not in line: continue match = re.match(r'^\d*:\s+([\w.\-]+)(?:@)?([\w.\-]+)?:\s+<(.+)>', line) if match: iface, parent, attrs = match.groups() if 'UP' in attrs.split(','): data['up'] = True else: data['up'] = False if parent: data['parent'] = parent continue cols = line.split() if len(cols) >= 2: type_, value = tuple(cols[0:2]) iflabel = cols[-1:][0] if type_ in ('inet', 'inet6'): if 'secondary' not in cols: ipaddr, netmask, broadcast, scope = parse_network(value, cols) if type_ == 'inet': if 'inet' not in data: data['inet'] = list() addr_obj = dict() addr_obj['address'] = ipaddr addr_obj['netmask'] = netmask addr_obj['broadcast'] = broadcast addr_obj['label'] = iflabel data['inet'].append(addr_obj) elif type_ == 'inet6': if 'inet6' not in data: data['inet6'] = list() addr_obj = dict() addr_obj['address'] = ipaddr addr_obj['prefixlen'] = netmask addr_obj['scope'] = scope data['inet6'].append(addr_obj) else: if 'secondary' not in data: data['secondary'] = list() ip_, mask, brd, scp = parse_network(value, cols) data['secondary'].append({ 'type': type_, 'address': ip_, 'netmask': mask, 'broadcast': brd, 'label': iflabel, }) del ip_, mask, brd, scp elif type_.startswith('link'): data['hwaddr'] = value if iface: ret[iface] = data del iface, data return ret def _interfaces_ifconfig(out): ''' Uses ifconfig to return a dictionary of interfaces with various information about each (up/down state, ip address, netmask, and hwaddr) ''' ret = dict() piface = re.compile(r'^([^\s:]+)') pmac = re.compile('.*?(?:HWaddr|ether|address:|lladdr) ([0-9a-fA-F:]+)') if salt.utils.platform.is_sunos(): pip = re.compile(r'.*?(?:inet\s+)([0-9]+\.[0-9]+\.[0-9]+\.[0-9]+)(.*)') pip6 = re.compile('.*?(?:inet6 )([0-9a-fA-F:]+)') pmask6 = re.compile(r'.*?(?:inet6 [0-9a-fA-F:]+/(\d+)).*') else: pip = re.compile(r'.*?(?:inet addr:|inet [^\d]*)(.*?)\s') pip6 = re.compile('.*?(?:inet6 addr: (.*?)/|inet6 )([0-9a-fA-F:]+)') pmask6 = re.compile(r'.*?(?:inet6 addr: [0-9a-fA-F:]+/(\d+)|prefixlen (\d+))(?: Scope:([a-zA-Z]+)| scopeid (0x[0-9a-fA-F]))?') pmask = re.compile(r'.*?(?:Mask:|netmask )(?:((?:0x)?[0-9a-fA-F]{8})|([\d\.]+))') pupdown = re.compile('UP') pbcast = re.compile(r'.*?(?:Bcast:|broadcast )([\d\.]+)') groups = re.compile('\r?\n(?=\\S)').split(out) for group in groups: data = dict() iface = '' updown = False for line in group.splitlines(): miface = piface.match(line) mmac = pmac.match(line) mip = pip.match(line) mip6 = pip6.match(line) mupdown = pupdown.search(line) if miface: iface = miface.group(1) if mmac: data['hwaddr'] = mmac.group(1) if salt.utils.platform.is_sunos(): expand_mac = [] for chunk in data['hwaddr'].split(':'): expand_mac.append('0{0}'.format(chunk) if len(chunk) < 2 else '{0}'.format(chunk)) data['hwaddr'] = ':'.join(expand_mac) if mip: if 'inet' not in data: data['inet'] = list() addr_obj = dict() addr_obj['address'] = mip.group(1) mmask = pmask.match(line) if mmask: if mmask.group(1): mmask = _number_of_set_bits_to_ipv4_netmask( int(mmask.group(1), 16)) else: mmask = mmask.group(2) addr_obj['netmask'] = mmask mbcast = pbcast.match(line) if mbcast: addr_obj['broadcast'] = mbcast.group(1) data['inet'].append(addr_obj) if mupdown: updown = True if mip6: if 'inet6' not in data: data['inet6'] = list() addr_obj = dict() addr_obj['address'] = mip6.group(1) or mip6.group(2) mmask6 = pmask6.match(line) if mmask6: addr_obj['prefixlen'] = mmask6.group(1) or mmask6.group(2) if not salt.utils.platform.is_sunos(): ipv6scope = mmask6.group(3) or mmask6.group(4) addr_obj['scope'] = ipv6scope.lower() if ipv6scope is not None else ipv6scope # SunOS sometimes has ::/0 as inet6 addr when using addrconf if not salt.utils.platform.is_sunos() \ or addr_obj['address'] != '::' \ and addr_obj['prefixlen'] != 0: data['inet6'].append(addr_obj) data['up'] = updown if iface in ret: # SunOS optimization, where interfaces occur twice in 'ifconfig -a' # output with the same name: for ipv4 and then for ipv6 addr family. # Every instance has it's own 'UP' status and we assume that ipv4 # status determines global interface status. # # merge items with higher priority for older values # after that merge the inet and inet6 sub items for both ret[iface] = dict(list(data.items()) + list(ret[iface].items())) if 'inet' in data: ret[iface]['inet'].extend(x for x in data['inet'] if x not in ret[iface]['inet']) if 'inet6' in data: ret[iface]['inet6'].extend(x for x in data['inet6'] if x not in ret[iface]['inet6']) else: ret[iface] = data del data return ret def linux_interfaces(): ''' Obtain interface information for *NIX/BSD variants ''' ifaces = dict() ip_path = salt.utils.path.which('ip') ifconfig_path = None if ip_path else salt.utils.path.which('ifconfig') if ip_path: cmd1 = subprocess.Popen( '{0} link show'.format(ip_path), shell=True, close_fds=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT).communicate()[0] cmd2 = subprocess.Popen( '{0} addr show'.format(ip_path), shell=True, close_fds=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT).communicate()[0] ifaces = _interfaces_ip("{0}\n{1}".format( salt.utils.stringutils.to_str(cmd1), salt.utils.stringutils.to_str(cmd2))) elif ifconfig_path: cmd = subprocess.Popen( '{0} -a'.format(ifconfig_path), shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT).communicate()[0] ifaces = _interfaces_ifconfig(salt.utils.stringutils.to_str(cmd)) return ifaces def _netbsd_interfaces_ifconfig(out): ''' Uses ifconfig to return a dictionary of interfaces with various information about each (up/down state, ip address, netmask, and hwaddr) ''' ret = dict() piface = re.compile(r'^([^\s:]+)') pmac = re.compile('.*?address: ([0-9a-f:]+)') pip = re.compile(r'.*?inet [^\d]*(.*?)/([\d]*)\s') pip6 = re.compile(r'.*?inet6 ([0-9a-f:]+)%([a-zA-Z0-9]*)/([\d]*)\s') pupdown = re.compile('UP') pbcast = re.compile(r'.*?broadcast ([\d\.]+)') groups = re.compile('\r?\n(?=\\S)').split(out) for group in groups: data = dict() iface = '' updown = False for line in group.splitlines(): miface = piface.match(line) mmac = pmac.match(line) mip = pip.match(line) mip6 = pip6.match(line) mupdown = pupdown.search(line) if miface: iface = miface.group(1) if mmac: data['hwaddr'] = mmac.group(1) if mip: if 'inet' not in data: data['inet'] = list() addr_obj = dict() addr_obj['address'] = mip.group(1) mmask = mip.group(2) if mip.group(2): addr_obj['netmask'] = cidr_to_ipv4_netmask(mip.group(2)) mbcast = pbcast.match(line) if mbcast: addr_obj['broadcast'] = mbcast.group(1) data['inet'].append(addr_obj) if mupdown: updown = True if mip6: if 'inet6' not in data: data['inet6'] = list() addr_obj = dict() addr_obj['address'] = mip6.group(1) mmask6 = mip6.group(3) addr_obj['scope'] = mip6.group(2) addr_obj['prefixlen'] = mip6.group(3) data['inet6'].append(addr_obj) data['up'] = updown ret[iface] = data del data return ret def netbsd_interfaces(): ''' Obtain interface information for NetBSD >= 8 where the ifconfig output diverged from other BSD variants (Netmask is now part of the address) ''' # NetBSD versions prior to 8.0 can still use linux_interfaces() if LooseVersion(os.uname()[2]) < LooseVersion('8.0'): return linux_interfaces() ifconfig_path = salt.utils.path.which('ifconfig') cmd = subprocess.Popen( '{0} -a'.format(ifconfig_path), shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT).communicate()[0] return _netbsd_interfaces_ifconfig(salt.utils.stringutils.to_str(cmd)) def _interfaces_ipconfig(out): ''' Returns a dictionary of interfaces with various information about each (up/down state, ip address, netmask, and hwaddr) NOTE: This is not used by any function and may be able to be removed in the future. ''' ifaces = dict() iface = None adapter_iface_regex = re.compile(r'adapter (\S.+):$') for line in out.splitlines(): if not line: continue # TODO what does Windows call Infiniband and 10/40gige adapters if line.startswith('Ethernet'): iface = ifaces[adapter_iface_regex.search(line).group(1)] iface['up'] = True addr = None continue if iface: key, val = line.split(',', 1) key = key.strip(' .') val = val.strip() if addr and key == 'Subnet Mask': addr['netmask'] = val elif key in ('IP Address', 'IPv4 Address'): if 'inet' not in iface: iface['inet'] = list() addr = {'address': val.rstrip('(Preferred)'), 'netmask': None, 'broadcast': None} # TODO find the broadcast iface['inet'].append(addr) elif 'IPv6 Address' in key: if 'inet6' not in iface: iface['inet'] = list() # XXX What is the prefixlen!? addr = {'address': val.rstrip('(Preferred)'), 'prefixlen': None} iface['inet6'].append(addr) elif key == 'Physical Address': iface['hwaddr'] = val elif key == 'Media State': # XXX seen used for tunnel adaptors # might be useful iface['up'] = (val != 'Media disconnected') def win_interfaces(): ''' Obtain interface information for Windows systems ''' with salt.utils.winapi.Com(): c = wmi.WMI() ifaces = {} for iface in c.Win32_NetworkAdapterConfiguration(IPEnabled=1): ifaces[iface.Description] = dict() if iface.MACAddress: ifaces[iface.Description]['hwaddr'] = iface.MACAddress if iface.IPEnabled: ifaces[iface.Description]['up'] = True for ip in iface.IPAddress: if '.' in ip: if 'inet' not in ifaces[iface.Description]: ifaces[iface.Description]['inet'] = [] item = {'address': ip, 'label': iface.Description} if iface.DefaultIPGateway: broadcast = next((i for i in iface.DefaultIPGateway if '.' in i), '') if broadcast: item['broadcast'] = broadcast if iface.IPSubnet: netmask = next((i for i in iface.IPSubnet if '.' in i), '') if netmask: item['netmask'] = netmask ifaces[iface.Description]['inet'].append(item) if ':' in ip: if 'inet6' not in ifaces[iface.Description]: ifaces[iface.Description]['inet6'] = [] item = {'address': ip} if iface.DefaultIPGateway: broadcast = next((i for i in iface.DefaultIPGateway if ':' in i), '') if broadcast: item['broadcast'] = broadcast if iface.IPSubnet: netmask = next((i for i in iface.IPSubnet if ':' in i), '') if netmask: item['netmask'] = netmask ifaces[iface.Description]['inet6'].append(item) else: ifaces[iface.Description]['up'] = False return ifaces def interfaces(): ''' Return a dictionary of information about all the interfaces on the minion ''' if salt.utils.platform.is_windows(): return win_interfaces() elif salt.utils.platform.is_netbsd(): return netbsd_interfaces() else: return linux_interfaces() def get_net_start(ipaddr, netmask): ''' Return the address of the network ''' net = ipaddress.ip_network('{0}/{1}'.format(ipaddr, netmask), strict=False) return six.text_type(net.network_address) def get_net_size(mask): ''' Turns an IPv4 netmask into it's corresponding prefix length (255.255.255.0 -> 24 as in 192.168.1.10/24). ''' binary_str = '' for octet in mask.split('.'): binary_str += bin(int(octet))[2:].zfill(8) return len(binary_str.rstrip('0')) def calc_net(ipaddr, netmask=None): ''' Takes IP (CIDR notation supported) and optionally netmask and returns the network in CIDR-notation. (The IP can be any IP inside the subnet) ''' if netmask is not None: ipaddr = '{0}/{1}'.format(ipaddr, netmask) return six.text_type(ipaddress.ip_network(ipaddr, strict=False)) def _ipv4_to_bits(ipaddr): ''' Accepts an IPv4 dotted quad and returns a string representing its binary counterpart ''' return ''.join([bin(int(x))[2:].rjust(8, '0') for x in ipaddr.split('.')]) def _get_iface_info(iface): ''' If `iface` is available, return interface info and no error, otherwise return no info and log and return an error ''' iface_info = interfaces() if iface in iface_info.keys(): return iface_info, False else: error_msg = ('Interface "{0}" not in available interfaces: "{1}"' ''.format(iface, '", "'.join(iface_info.keys()))) log.error(error_msg) return None, error_msg def _hw_addr_aix(iface): ''' Return the hardware address (a.k.a. MAC address) for a given interface on AIX MAC address not available in through interfaces ''' cmd = subprocess.Popen( 'entstat -d {0} | grep \'Hardware Address\''.format(iface), shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT).communicate()[0] if cmd: comps = cmd.split(' ') if len(comps) == 3: mac_addr = comps[2].strip('\'').strip() return mac_addr error_msg = ('Interface "{0}" either not available or does not contain a hardware address'.format(iface)) log.error(error_msg) return error_msg def hw_addr(iface): ''' Return the hardware address (a.k.a. MAC address) for a given interface .. versionchanged:: 2016.11.4 Added support for AIX ''' if salt.utils.platform.is_aix(): return _hw_addr_aix iface_info, error = _get_iface_info(iface) if error is False: return iface_info.get(iface, {}).get('hwaddr', '') else: return error def interface(iface): ''' Return the details of `iface` or an error if it does not exist ''' iface_info, error = _get_iface_info(iface) if error is False: return iface_info.get(iface, {}).get('inet', '') else: return error def interface_ip(iface): ''' Return `iface` IPv4 addr or an error if `iface` does not exist ''' iface_info, error = _get_iface_info(iface) if error is False: inet = iface_info.get(iface, {}).get('inet', None) return inet[0].get('address', '') if inet else '' else: return error def _subnets(proto='inet', interfaces_=None): ''' Returns a list of subnets to which the host belongs ''' if interfaces_ is None: ifaces = interfaces() elif isinstance(interfaces_, list): ifaces = {} for key, value in six.iteritems(interfaces()): if key in interfaces_: ifaces[key] = value else: ifaces = {interfaces_: interfaces().get(interfaces_, {})} ret = set() if proto == 'inet': subnet = 'netmask' dflt_cidr = 32 elif proto == 'inet6': subnet = 'prefixlen' dflt_cidr = 128 else: log.error('Invalid proto %s calling subnets()', proto) return for ip_info in six.itervalues(ifaces): addrs = ip_info.get(proto, []) addrs.extend([addr for addr in ip_info.get('secondary', []) if addr.get('type') == proto]) for intf in addrs: if subnet in intf: intf = ipaddress.ip_interface('{0}/{1}'.format(intf['address'], intf[subnet])) else: intf = ipaddress.ip_interface('{0}/{1}'.format(intf['address'], dflt_cidr)) if not intf.is_loopback: ret.add(intf.network) return [six.text_type(net) for net in sorted(ret)] def subnets(interfaces=None): ''' Returns a list of IPv4 subnets to which the host belongs ''' return _subnets('inet', interfaces_=interfaces) def subnets6(): ''' Returns a list of IPv6 subnets to which the host belongs ''' return _subnets('inet6') def in_subnet(cidr, addr=None): ''' Returns True if host or (any of) addrs is within specified subnet, otherwise False ''' try: cidr = ipaddress.ip_network(cidr) except ValueError: log.error('Invalid CIDR \'%s\'', cidr) return False if addr is None: addr = ip_addrs() addr.extend(ip_addrs6()) elif not isinstance(addr, (list, tuple)): addr = (addr,) return any(ipaddress.ip_address(item) in cidr for item in addr) def _ip_addrs(interface=None, include_loopback=False, interface_data=None, proto='inet'): ''' Return the full list of IP adresses matching the criteria proto = inet|inet6 ''' ret = set() ifaces = interface_data \ if isinstance(interface_data, dict) \ else interfaces() if interface is None: target_ifaces = ifaces else: target_ifaces = dict([(k, v) for k, v in six.iteritems(ifaces) if k == interface]) if not target_ifaces: log.error('Interface %s not found.', interface) for ip_info in six.itervalues(target_ifaces): addrs = ip_info.get(proto, []) addrs.extend([addr for addr in ip_info.get('secondary', []) if addr.get('type') == proto]) for addr in addrs: addr = ipaddress.ip_address(addr.get('address')) if not addr.is_loopback or include_loopback: ret.add(addr) return [six.text_type(addr) for addr in sorted(ret)] def ip_addrs(interface=None, include_loopback=False, interface_data=None): ''' Returns a list of IPv4 addresses assigned to the host. 127.0.0.1 is ignored, unless 'include_loopback=True' is indicated. If 'interface' is provided, then only IP addresses from that interface will be returned. ''' return _ip_addrs(interface, include_loopback, interface_data, 'inet') def ip_addrs6(interface=None, include_loopback=False, interface_data=None): ''' Returns a list of IPv6 addresses assigned to the host. ::1 is ignored, unless 'include_loopback=True' is indicated. If 'interface' is provided, then only IP addresses from that interface will be returned. ''' return _ip_addrs(interface, include_loopback, interface_data, 'inet6') def hex2ip(hex_ip, invert=False): ''' Convert a hex string to an ip, if a failure occurs the original hex is returned. If 'invert=True' assume that ip from /proc/net/<proto> ''' if len(hex_ip) == 32: # ipv6 ip = [] for i in range(0, 32, 8): ip_part = hex_ip[i:i + 8] ip_part = [ip_part[x:x + 2] for x in range(0, 8, 2)] if invert: ip.append("{0[3]}{0[2]}:{0[1]}{0[0]}".format(ip_part)) else: ip.append("{0[0]}{0[1]}:{0[2]}{0[3]}".format(ip_part)) try: address = ipaddress.IPv6Address(":".join(ip)) if address.ipv4_mapped: return str(address.ipv4_mapped) else: return address.compressed except ipaddress.AddressValueError as ex: log.error('hex2ip - ipv6 address error: %s', ex) return hex_ip try: hip = int(hex_ip, 16) except ValueError: return hex_ip if invert: return '{3}.{2}.{1}.{0}'.format(hip >> 24 & 255, hip >> 16 & 255, hip >> 8 & 255, hip & 255) return '{0}.{1}.{2}.{3}'.format(hip >> 24 & 255, hip >> 16 & 255, hip >> 8 & 255, hip & 255) def mac2eui64(mac, prefix=None): ''' Convert a MAC address to a EUI64 identifier or, with prefix provided, a full IPv6 address ''' # http://tools.ietf.org/html/rfc4291#section-2.5.1 eui64 = re.sub(r'[.:-]', '', mac).lower() eui64 = eui64[0:6] + 'fffe' + eui64[6:] eui64 = hex(int(eui64[0:2], 16) | 2)[2:].zfill(2) + eui64[2:] if prefix is None: return ':'.join(re.findall(r'.{4}', eui64)) else: try: net = ipaddress.ip_network(prefix, strict=False) euil = int('0x{0}'.format(eui64), 16) return '{0}/{1}'.format(net[euil], net.prefixlen) except Exception: return def active_tcp(): ''' Return a dict describing all active tcp connections as quickly as possible ''' ret = {} for statf in ['/proc/net/tcp', '/proc/net/tcp6']: if os.path.isfile(statf): with salt.utils.files.fopen(statf, 'rb') as fp_: for line in fp_: line = salt.utils.stringutils.to_unicode(line) if line.strip().startswith('sl'): continue iret = _parse_tcp_line(line) sl = next(iter(iret)) if iret[sl]['state'] == 1: # 1 is ESTABLISHED del iret[sl]['state'] ret[len(ret)] = iret[sl] return ret def local_port_tcp(port): ''' Return a set of remote ip addrs attached to the specified local port ''' ret = _remotes_on(port, 'local_port') return ret def remote_port_tcp(port): ''' Return a set of ip addrs the current host is connected to on given port ''' ret = _remotes_on(port, 'remote_port') return ret def _remotes_on(port, which_end): ''' Return a set of ip addrs active tcp connections ''' port = int(port) ret = _netlink_tool_remote_on(port, which_end) if ret is not None: return ret ret = set() proc_available = False for statf in ['/proc/net/tcp', '/proc/net/tcp6']: if os.path.isfile(statf): proc_available = True with salt.utils.files.fopen(statf, 'r') as fp_: for line in fp_: line = salt.utils.stringutils.to_unicode(line) if line.strip().startswith('sl'): continue iret = _parse_tcp_line(line) sl = next(iter(iret)) if iret[sl][which_end] == port and iret[sl]['state'] == 1: # 1 is ESTABLISHED ret.add(iret[sl]['remote_addr']) if not proc_available: # Fallback to use OS specific tools if salt.utils.platform.is_sunos(): return _sunos_remotes_on(port, which_end) if salt.utils.platform.is_freebsd(): return _freebsd_remotes_on(port, which_end) if salt.utils.platform.is_netbsd(): return _netbsd_remotes_on(port, which_end) if salt.utils.platform.is_openbsd(): return _openbsd_remotes_on(port, which_end) if salt.utils.platform.is_windows(): return _windows_remotes_on(port, which_end) if salt.utils.platform.is_aix(): return _aix_remotes_on(port, which_end) return _linux_remotes_on(port, which_end) return ret def _parse_tcp_line(line): ''' Parse a single line from the contents of /proc/net/tcp or /proc/net/tcp6 ''' ret = {} comps = line.strip().split() sl = comps[0].rstrip(':') ret[sl] = {} l_addr, l_port = comps[1].split(':') r_addr, r_port = comps[2].split(':') ret[sl]['local_addr'] = hex2ip(l_addr, True) ret[sl]['local_port'] = int(l_port, 16) ret[sl]['remote_addr'] = hex2ip(r_addr, True) ret[sl]['remote_port'] = int(r_port, 16) ret[sl]['state'] = int(comps[3], 16) return ret def _netlink_tool_remote_on(port, which_end): ''' Returns set of ipv4 host addresses of remote established connections on local or remote tcp port. Parses output of shell 'ss' to get connections [root@salt-master ~]# ss -ant State Recv-Q Send-Q Local Address:Port Peer Address:Port LISTEN 0 511 *:80 *:* LISTEN 0 128 *:22 *:* ESTAB 0 0 127.0.0.1:56726 127.0.0.1:4505 ''' remotes = set() valid = False try: data = subprocess.check_output(['ss', '-ant']) # pylint: disable=minimum-python-version except subprocess.CalledProcessError: log.error('Failed ss') raise except OSError: # not command "No such file or directory" return None lines = salt.utils.stringutils.to_str(data).split('\n') for line in lines: if 'Address:Port' in line: # ss tools may not be valid valid = True continue elif 'ESTAB' not in line: continue chunks = line.split() local_host, local_port = chunks[3].split(':', 1) remote_host, remote_port = chunks[4].split(':', 1) if which_end == 'remote_port' and int(remote_port) != port: continue if which_end == 'local_port' and int(local_port) != port: continue remotes.add(remote_host) if valid is False: remotes = None return remotes def _sunos_remotes_on(port, which_end): ''' SunOS specific helper function. Returns set of ipv4 host addresses of remote established connections on local or remote tcp port. Parses output of shell 'netstat' to get connections [root@salt-master ~]# netstat -f inet -n TCP: IPv4 Local Address Remote Address Swind Send-Q Rwind Recv-Q State -------------------- -------------------- ----- ------ ----- ------ ----------- 10.0.0.101.4505 10.0.0.1.45329 1064800 0 1055864 0 ESTABLISHED 10.0.0.101.4505 10.0.0.100.50798 1064800 0 1055864 0 ESTABLISHED ''' remotes = set() try: data = subprocess.check_output(['netstat', '-f', 'inet', '-n']) # pylint: disable=minimum-python-version except subprocess.CalledProcessError: log.error('Failed netstat') raise lines = salt.utils.stringutils.to_str(data).split('\n') for line in lines: if 'ESTABLISHED' not in line: continue chunks = line.split() local_host, local_port = chunks[0].rsplit('.', 1) remote_host, remote_port = chunks[1].rsplit('.', 1) if which_end == 'remote_port' and int(remote_port) != port: continue if which_end == 'local_port' and int(local_port) != port: continue remotes.add(remote_host) return remotes def _freebsd_remotes_on(port, which_end): ''' Returns set of ipv4 host addresses of remote established connections on local tcp port port. Parses output of shell 'sockstat' (FreeBSD) to get connections $ sudo sockstat -4 USER COMMAND PID FD PROTO LOCAL ADDRESS FOREIGN ADDRESS root python2.7 1456 29 tcp4 *:4505 *:* root python2.7 1445 17 tcp4 *:4506 *:* root python2.7 1294 14 tcp4 127.0.0.1:11813 127.0.0.1:4505 root python2.7 1294 41 tcp4 127.0.0.1:61115 127.0.0.1:4506 $ sudo sockstat -4 -c -p 4506 USER COMMAND PID FD PROTO LOCAL ADDRESS FOREIGN ADDRESS root python2.7 1294 41 tcp4 127.0.0.1:61115 127.0.0.1:4506 ''' port = int(port) remotes = set() try: cmd = salt.utils.args.shlex_split('sockstat -4 -c -p {0}'.format(port)) data = subprocess.check_output(cmd) # pylint: disable=minimum-python-version except subprocess.CalledProcessError as ex: log.error('Failed "sockstat" with returncode = %s', ex.returncode) raise lines = salt.utils.stringutils.to_str(data).split('\n') for line in lines: chunks = line.split() if not chunks: continue # ['root', 'python2.7', '1456', '37', 'tcp4', # '127.0.0.1:4505-', '127.0.0.1:55703'] # print chunks if 'COMMAND' in chunks[1]: continue # ignore header if len(chunks) < 2: continue # sockstat -4 -c -p 4506 does this with high PIDs: # USER COMMAND PID FD PROTO LOCAL ADDRESS FOREIGN ADDRESS # salt-master python2.781106 35 tcp4 192.168.12.34:4506 192.168.12.45:60143 local = chunks[-2] remote = chunks[-1] lhost, lport = local.split(':') rhost, rport = remote.split(':') if which_end == 'local' and int(lport) != port: # ignore if local port not port continue if which_end == 'remote' and int(rport) != port: # ignore if remote port not port continue remotes.add(rhost) return remotes def _netbsd_remotes_on(port, which_end): ''' Returns set of ipv4 host addresses of remote established connections on local tcp port port. Parses output of shell 'sockstat' (NetBSD) to get connections $ sudo sockstat -4 -n USER COMMAND PID FD PROTO LOCAL ADDRESS FOREIGN ADDRESS root python2.7 1456 29 tcp *.4505 *.* root python2.7 1445 17 tcp *.4506 *.* root python2.7 1294 14 tcp 127.0.0.1.11813 127.0.0.1.4505 root python2.7 1294 41 tcp 127.0.0.1.61115 127.0.0.1.4506 $ sudo sockstat -4 -c -n -p 4506 USER COMMAND PID FD PROTO LOCAL ADDRESS FOREIGN ADDRESS root python2.7 1294 41 tcp 127.0.0.1.61115 127.0.0.1.4506 ''' port = int(port) remotes = set() try: cmd = salt.utils.args.shlex_split('sockstat -4 -c -n -p {0}'.format(port)) data = subprocess.check_output(cmd) # pylint: disable=minimum-python-version except subprocess.CalledProcessError as ex: log.error('Failed "sockstat" with returncode = %s', ex.returncode) raise lines = salt.utils.stringutils.to_str(data).split('\n') for line in lines: chunks = line.split() if not chunks: continue # ['root', 'python2.7', '1456', '37', 'tcp', # '127.0.0.1.4505-', '127.0.0.1.55703'] # print chunks if 'COMMAND' in chunks[1]: continue # ignore header if len(chunks) < 2: continue local = chunks[5].split('.') lport = local.pop() lhost = '.'.join(local) remote = chunks[6].split('.') rport = remote.pop() rhost = '.'.join(remote) if which_end == 'local' and int(lport) != port: # ignore if local port not port continue if which_end == 'remote' and int(rport) != port: # ignore if remote port not port continue remotes.add(rhost) return remotes def _windows_remotes_on(port, which_end): r''' Windows specific helper function. Returns set of ipv4 host addresses of remote established connections on local or remote tcp port. Parses output of shell 'netstat' to get connections C:\>netstat -n Active Connections Proto Local Address Foreign Address State TCP 10.2.33.17:3007 130.164.12.233:10123 ESTABLISHED TCP 10.2.33.17:3389 130.164.30.5:10378 ESTABLISHED ''' remotes = set() try: data = subprocess.check_output(['netstat', '-n']) # pylint: disable=minimum-python-version except subprocess.CalledProcessError: log.error('Failed netstat') raise lines = salt.utils.stringutils.to_str(data).split('\n') for line in lines: if 'ESTABLISHED' not in line: continue chunks = line.split() local_host, local_port = chunks[1].rsplit(':', 1) remote_host, remote_port = chunks[2].rsplit(':', 1) if which_end == 'remote_port' and int(remote_port) != port: continue if which_end == 'local_port' and int(local_port) != port: continue remotes.add(remote_host) return remotes def _linux_remotes_on(port, which_end): ''' Linux specific helper function. Returns set of ip host addresses of remote established connections on local tcp port port. Parses output of shell 'lsof' to get connections $ sudo lsof -iTCP:4505 -n COMMAND PID USER FD TYPE DEVICE SIZE/OFF NODE NAME Python 9971 root 35u IPv4 0x18a8464a29ca329d 0t0 TCP *:4505 (LISTEN) Python 9971 root 37u IPv4 0x18a8464a29b2b29d 0t0 TCP 127.0.0.1:4505->127.0.0.1:55703 (ESTABLISHED) Python 10152 root 22u IPv4 0x18a8464a29c8cab5 0t0 TCP 127.0.0.1:55703->127.0.0.1:4505 (ESTABLISHED) Python 10153 root 22u IPv4 0x18a8464a29c8cab5 0t0 TCP [fe80::249a]:4505->[fe80::150]:59367 (ESTABLISHED) ''' remotes = set() try: data = subprocess.check_output( ['lsof', '-iTCP:{0:d}'.format(port), '-n', '-P'] # pylint: disable=minimum-python-version ) except subprocess.CalledProcessError as ex: if ex.returncode == 1: # Lsof return 1 if any error was detected, including the failure # to locate Internet addresses, and it is not an error in this case. log.warning('"lsof" returncode = 1, likely no active TCP sessions.') return remotes log.error('Failed "lsof" with returncode = %s', ex.returncode) raise lines = salt.utils.stringutils.to_str(data).split('\n') for line in lines: chunks = line.split() if not chunks: continue # ['Python', '9971', 'root', '37u', 'IPv4', '0x18a8464a29b2b29d', '0t0', # 'TCP', '127.0.0.1:4505->127.0.0.1:55703', '(ESTABLISHED)'] # print chunks if 'COMMAND' in chunks[0]: continue # ignore header if 'ESTABLISHED' not in chunks[-1]: continue # ignore if not ESTABLISHED # '127.0.0.1:4505->127.0.0.1:55703' local, remote = chunks[8].split('->') _, lport = local.rsplit(':', 1) rhost, rport = remote.rsplit(':', 1) if which_end == 'remote_port' and int(rport) != port: continue if which_end == 'local_port' and int(lport) != port: continue remotes.add(rhost.strip("[]")) return remotes def _aix_remotes_on(port, which_end): ''' AIX specific helper function. Returns set of ipv4 host addresses of remote established connections on local or remote tcp port. Parses output of shell 'netstat' to get connections root@la68pp002_pub:/opt/salt/lib/python2.7/site-packages/salt/modules# netstat -f inet -n Active Internet connections Proto Recv-Q Send-Q Local Address Foreign Address (state) tcp4 0 0 172.29.149.95.50093 209.41.78.13.4505 ESTABLISHED tcp4 0 0 127.0.0.1.9514 *.* LISTEN tcp4 0 0 127.0.0.1.9515 *.* LISTEN tcp4 0 0 127.0.0.1.199 127.0.0.1.32779 ESTABLISHED tcp4 0 0 127.0.0.1.32779 127.0.0.1.199 ESTABLISHED tcp4 0 40 172.29.149.95.22 172.29.96.83.41022 ESTABLISHED tcp4 0 0 172.29.149.95.22 172.29.96.83.41032 ESTABLISHED tcp4 0 0 127.0.0.1.32771 127.0.0.1.32775 ESTABLISHED tcp 0 0 127.0.0.1.32775 127.0.0.1.32771 ESTABLISHED tcp4 0 0 127.0.0.1.32771 127.0.0.1.32776 ESTABLISHED tcp 0 0 127.0.0.1.32776 127.0.0.1.32771 ESTABLISHED tcp4 0 0 127.0.0.1.32771 127.0.0.1.32777 ESTABLISHED tcp 0 0 127.0.0.1.32777 127.0.0.1.32771 ESTABLISHED tcp4 0 0 127.0.0.1.32771 127.0.0.1.32778 ESTABLISHED tcp 0 0 127.0.0.1.32778 127.0.0.1.32771 ESTABLISHED ''' remotes = set() try: data = subprocess.check_output(['netstat', '-f', 'inet', '-n']) # pylint: disable=minimum-python-version except subprocess.CalledProcessError: log.error('Failed netstat') raise lines = salt.utils.stringutils.to_str(data).split('\n') for line in lines: if 'ESTABLISHED' not in line: continue chunks = line.split() local_host, local_port = chunks[3].rsplit('.', 1) remote_host, remote_port = chunks[4].rsplit('.', 1) if which_end == 'remote_port' and int(remote_port) != port: continue if which_end == 'local_port' and int(local_port) != port: continue remotes.add(remote_host) return remotes @jinja_filter('gen_mac') def gen_mac(prefix='AC:DE:48'): ''' Generates a MAC address with the defined OUI prefix. Common prefixes: - ``00:16:3E`` -- Xen - ``00:18:51`` -- OpenVZ - ``00:50:56`` -- VMware (manually generated) - ``52:54:00`` -- QEMU/KVM - ``AC:DE:48`` -- PRIVATE References: - http://standards.ieee.org/develop/regauth/oui/oui.txt - https://www.wireshark.org/tools/oui-lookup.html - https://en.wikipedia.org/wiki/MAC_address ''' return '{0}:{1:02X}:{2:02X}:{3:02X}'.format(prefix, random.randint(0, 0xff), random.randint(0, 0xff), random.randint(0, 0xff)) @jinja_filter('mac_str_to_bytes') def mac_str_to_bytes(mac_str): ''' Convert a MAC address string into bytes. Works with or without separators: b1 = mac_str_to_bytes('08:00:27:13:69:77') b2 = mac_str_to_bytes('080027136977') assert b1 == b2 assert isinstance(b1, bytes) ''' if len(mac_str) == 12: pass elif len(mac_str) == 17: sep = mac_str[2] mac_str = mac_str.replace(sep, '') else: raise ValueError('Invalid MAC address') chars = (int(mac_str[s:s+2], 16) for s in range(0, 12, 2)) return bytes(chars) if six.PY3 else b''.join(chr(x) for x in chars) def refresh_dns(): ''' issue #21397: force glibc to re-read resolv.conf ''' try: res_init() except NameError: # Exception raised loading the library, thus res_init is not defined pass @jinja_filter('connection_check') def connection_check(addr, port=80, safe=False, ipv6=None): ''' Provides a convenient alias for the dns_check filter. ''' return dns_check(addr, port, safe, ipv6) @jinja_filter('dns_check') def dns_check(addr, port=80, safe=False, ipv6=None, attempt_connect=True): ''' Return the ip resolved by dns, but do not exit on failure, only raise an exception. Obeys system preference for IPv4/6 address resolution - this can be overridden by the ipv6 flag. Tries to connect to the address before considering it useful. If no address can be reached, the first one resolved is used as a fallback. ''' error = False lookup = addr seen_ipv6 = False family = socket.AF_INET6 if ipv6 else socket.AF_INET if ipv6 is False else socket.AF_UNSPEC hostnames = [] try: refresh_dns() hostnames = socket.getaddrinfo(addr, port, family, socket.SOCK_STREAM) except TypeError: err = ('Attempt to resolve address \'{0}\' failed. Invalid or unresolveable address').format(lookup) raise SaltSystemExit(code=42, msg=err) except socket.error: error = True # If ipv6 is set to True, attempt another lookup using the IPv4 family, # just in case we're attempting to lookup an IPv4 IP # as an IPv6 hostname. if error and ipv6: try: refresh_dns() hostnames = socket.getaddrinfo(addr, port, socket.AF_INET, socket.SOCK_STREAM) except TypeError: err = ('Attempt to resolve address \'{0}\' failed. Invalid or unresolveable address').format(lookup) raise SaltSystemExit(code=42, msg=err) except socket.error: error = True try: if not hostnames: error = True else: resolved = False candidates = [] for h in hostnames: # Input is IP address, passed through unchanged, just return it if h[4][0] == addr: resolved = salt.utils.zeromq.ip_bracket(addr) break candidate_addr = salt.utils.zeromq.ip_bracket(h[4][0]) # sometimes /etc/hosts contains ::1 localhost if not ipv6 and candidate_addr == '[::1]': continue candidates.append(candidate_addr) if attempt_connect: try: s = socket.socket(h[0], socket.SOCK_STREAM) s.settimeout(2) s.connect((candidate_addr.strip('[]'), h[4][1])) s.close() resolved = candidate_addr break except socket.error: pass if not resolved: if candidates: resolved = candidates[0] else: error = True except TypeError: err = ('Attempt to resolve address \'{0}\' failed. Invalid or unresolveable address').format(lookup) raise SaltSystemExit(code=42, msg=err) except socket.error: error = True if error: err = ('DNS lookup or connection check of \'{0}\' failed.').format(addr) if safe: if salt.log.is_console_configured(): # If logging is not configured it also means that either # the master or minion instance calling this hasn't even # started running log.error(err) raise SaltClientError() raise SaltSystemExit(code=42, msg=err) return resolved def parse_host_port(host_port): """ Takes a string argument specifying host or host:port. Returns a (hostname, port) or (ip_address, port) tuple. If no port is given, the second (port) element of the returned tuple will be None. host:port argument, for example, is accepted in the forms of: - hostname - hostname:1234 - hostname.domain.tld - hostname.domain.tld:5678 - [1234::5]:5678 - 1234::5 - 10.11.12.13:4567 - 10.11.12.13 """ host, port = None, None # default _s_ = host_port[:] if _s_[0] == "[": if "]" in host_port: host, _s_ = _s_.lstrip("[").rsplit("]", 1) host = ipaddress.IPv6Address(host).compressed if _s_[0] == ":": port = int(_s_.lstrip(":")) else: if len(_s_) > 1: raise ValueError('found ambiguous "{}" port in "{}"'.format(_s_, host_port)) else: if _s_.count(":") == 1: host, _hostport_separator_, port = _s_.partition(":") try: port = int(port) except ValueError as _e_: log.error('host_port "%s" port value "%s" is not an integer.', host_port, port) raise _e_ else: host = _s_ try: if not isinstance(host, ipaddress._BaseAddress): host_ip = ipaddress.ip_address(host).compressed host = host_ip except ValueError: log.debug('"%s" Not an IP address? Assuming it is a hostname.', host) if host != sanitize_host(host): log.error('bad hostname: "%s"', host) raise ValueError('bad hostname: "{}"'.format(host)) return host, port def is_fqdn(hostname): """ Verify if hostname conforms to be a FQDN. :param hostname: text string with the name of the host :return: bool, True if hostname is correct FQDN, False otherwise """ compliant = re.compile(r"(?!-)[A-Z\d\-\_]{1,63}(?<!-)$", re.IGNORECASE) return "." in hostname and len(hostname) < 0xff and all(compliant.match(x) for x in hostname.rstrip(".").split("."))
saltstack/salt
salt/utils/network.py
_windows_remotes_on
python
def _windows_remotes_on(port, which_end): r''' Windows specific helper function. Returns set of ipv4 host addresses of remote established connections on local or remote tcp port. Parses output of shell 'netstat' to get connections C:\>netstat -n Active Connections Proto Local Address Foreign Address State TCP 10.2.33.17:3007 130.164.12.233:10123 ESTABLISHED TCP 10.2.33.17:3389 130.164.30.5:10378 ESTABLISHED ''' remotes = set() try: data = subprocess.check_output(['netstat', '-n']) # pylint: disable=minimum-python-version except subprocess.CalledProcessError: log.error('Failed netstat') raise lines = salt.utils.stringutils.to_str(data).split('\n') for line in lines: if 'ESTABLISHED' not in line: continue chunks = line.split() local_host, local_port = chunks[1].rsplit(':', 1) remote_host, remote_port = chunks[2].rsplit(':', 1) if which_end == 'remote_port' and int(remote_port) != port: continue if which_end == 'local_port' and int(local_port) != port: continue remotes.add(remote_host) return remotes
r''' Windows specific helper function. Returns set of ipv4 host addresses of remote established connections on local or remote tcp port. Parses output of shell 'netstat' to get connections C:\>netstat -n Active Connections Proto Local Address Foreign Address State TCP 10.2.33.17:3007 130.164.12.233:10123 ESTABLISHED TCP 10.2.33.17:3389 130.164.30.5:10378 ESTABLISHED
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/network.py#L1701-L1736
null
# -*- coding: utf-8 -*- ''' Define some generic socket functions for network modules ''' # Import python libs from __future__ import absolute_import, unicode_literals, print_function import itertools import os import re import types import socket import logging import platform import random import subprocess from string import ascii_letters, digits # Import 3rd-party libs from salt.ext import six from salt.ext.six.moves import range # pylint: disable=import-error,redefined-builtin # Attempt to import wmi try: import wmi import salt.utils.winapi except ImportError: pass # Import salt libs import salt.utils.args import salt.utils.files import salt.utils.path import salt.utils.platform import salt.utils.stringutils import salt.utils.zeromq from salt._compat import ipaddress from salt.exceptions import SaltClientError, SaltSystemExit from salt.utils.decorators.jinja import jinja_filter from salt.utils.versions import LooseVersion # inet_pton does not exist in Windows, this is a workaround if salt.utils.platform.is_windows(): from salt.ext import win_inet_pton # pylint: disable=unused-import log = logging.getLogger(__name__) try: import ctypes import ctypes.util libc = ctypes.cdll.LoadLibrary(ctypes.util.find_library("c")) res_init = libc.__res_init except (ImportError, OSError, AttributeError, TypeError): pass # pylint: disable=C0103 def sanitize_host(host): ''' Sanitize host string. https://tools.ietf.org/html/rfc1123#section-2.1 ''' RFC952_characters = ascii_letters + digits + ".-" return "".join([c for c in host[0:255] if c in RFC952_characters]) def isportopen(host, port): ''' Return status of a port ''' if not 1 <= int(port) <= 65535: return False sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) out = sock.connect_ex((sanitize_host(host), int(port))) return out def host_to_ips(host): ''' Returns a list of IP addresses of a given hostname or None if not found. ''' ips = [] try: for family, socktype, proto, canonname, sockaddr in socket.getaddrinfo( host, 0, socket.AF_UNSPEC, socket.SOCK_STREAM): if family == socket.AF_INET: ip, port = sockaddr elif family == socket.AF_INET6: ip, port, flow_info, scope_id = sockaddr ips.append(ip) if not ips: ips = None except Exception: ips = None return ips def _generate_minion_id(): ''' Get list of possible host names and convention names. :return: ''' # There are three types of hostnames: # 1. Network names. How host is accessed from the network. # 2. Host aliases. They might be not available in all the network or only locally (/etc/hosts) # 3. Convention names, an internal nodename. class DistinctList(list): ''' List, which allows one to append only distinct objects. Needs to work on Python 2.6, because of collections.OrderedDict only since 2.7 version. Override 'filter()' for custom filtering. ''' localhost_matchers = [r'localhost.*', r'ip6-.*', r'127[.]\d', r'0\.0\.0\.0', r'::1.*', r'ipv6-.*', r'fe00::.*', r'fe02::.*', r'1.0.0.*.ip6.arpa'] def append(self, p_object): if p_object and p_object not in self and not self.filter(p_object): super(DistinctList, self).append(p_object) return self def extend(self, iterable): for obj in iterable: self.append(obj) return self def filter(self, element): 'Returns True if element needs to be filtered' for rgx in self.localhost_matchers: if re.match(rgx, element): return True def first(self): return self and self[0] or None hostname = socket.gethostname() hosts = DistinctList().append( salt.utils.stringutils.to_unicode(socket.getfqdn(salt.utils.stringutils.to_bytes(hostname))) ).append(platform.node()).append(hostname) if not hosts: try: for a_nfo in socket.getaddrinfo(hosts.first() or 'localhost', None, socket.AF_INET, socket.SOCK_RAW, socket.IPPROTO_IP, socket.AI_CANONNAME): if len(a_nfo) > 3: hosts.append(a_nfo[3]) except socket.gaierror: log.warning('Cannot resolve address %s info via socket: %s', hosts.first() or 'localhost (N/A)', socket.gaierror) # Universal method for everywhere (Linux, Slowlaris, Windows etc) for f_name in ('/etc/hostname', '/etc/nodename', '/etc/hosts', r'{win}\system32\drivers\etc\hosts'.format(win=os.getenv('WINDIR'))): try: with salt.utils.files.fopen(f_name) as f_hdl: for line in f_hdl: line = salt.utils.stringutils.to_unicode(line) hst = line.strip().split('#')[0].strip().split() if hst: if hst[0][:4] in ('127.', '::1') or len(hst) == 1: hosts.extend(hst) except IOError: pass # include public and private ipaddresses return hosts.extend([addr for addr in ip_addrs() if not ipaddress.ip_address(addr).is_loopback]) def generate_minion_id(): ''' Return only first element of the hostname from all possible list. :return: ''' try: ret = salt.utils.stringutils.to_unicode(_generate_minion_id().first()) except TypeError: ret = None return ret or 'localhost' def get_socket(addr, type=socket.SOCK_STREAM, proto=0): ''' Return a socket object for the addr IP-version agnostic ''' version = ipaddress.ip_address(addr).version if version == 4: family = socket.AF_INET elif version == 6: family = socket.AF_INET6 return socket.socket(family, type, proto) def get_fqhostname(): ''' Returns the fully qualified hostname ''' # try getaddrinfo() fqdn = None try: addrinfo = socket.getaddrinfo( socket.gethostname(), 0, socket.AF_UNSPEC, socket.SOCK_STREAM, socket.SOL_TCP, socket.AI_CANONNAME ) for info in addrinfo: # info struct [family, socktype, proto, canonname, sockaddr] # On Windows `canonname` can be an empty string # This can cause the function to return `None` if len(info) > 3 and info[3]: fqdn = info[3] break except socket.gaierror: pass # NOTE: this used to log.error() but it was later disabled except socket.error as err: log.debug('socket.getaddrinfo() failure while finding fqdn: %s', err) if fqdn is None: fqdn = socket.getfqdn() return fqdn def ip_to_host(ip): ''' Returns the hostname of a given IP ''' try: hostname, aliaslist, ipaddrlist = socket.gethostbyaddr(ip) except Exception as exc: log.debug('salt.utils.network.ip_to_host(%r) failed: %s', ip, exc) hostname = None return hostname # pylint: enable=C0103 def is_reachable_host(entity_name): ''' Returns a bool telling if the entity name is a reachable host (IPv4/IPv6/FQDN/etc). :param hostname: :return: ''' try: assert type(socket.getaddrinfo(entity_name, 0, 0, 0, 0)) == list ret = True except socket.gaierror: ret = False return ret def is_ip(ip): ''' Returns a bool telling if the passed IP is a valid IPv4 or IPv6 address. ''' return is_ipv4(ip) or is_ipv6(ip) def is_ipv4(ip): ''' Returns a bool telling if the value passed to it was a valid IPv4 address ''' try: return ipaddress.ip_address(ip).version == 4 except ValueError: return False def is_ipv6(ip): ''' Returns a bool telling if the value passed to it was a valid IPv6 address ''' try: return ipaddress.ip_address(ip).version == 6 except ValueError: return False def is_subnet(cidr): ''' Returns a bool telling if the passed string is an IPv4 or IPv6 subnet ''' return is_ipv4_subnet(cidr) or is_ipv6_subnet(cidr) def is_ipv4_subnet(cidr): ''' Returns a bool telling if the passed string is an IPv4 subnet ''' try: return '/' in cidr and bool(ipaddress.IPv4Network(cidr)) except Exception: return False def is_ipv6_subnet(cidr): ''' Returns a bool telling if the passed string is an IPv6 subnet ''' try: return '/' in cidr and bool(ipaddress.IPv6Network(cidr)) except Exception: return False @jinja_filter('is_ip') def is_ip_filter(ip, options=None): ''' Returns a bool telling if the passed IP is a valid IPv4 or IPv6 address. ''' return is_ipv4_filter(ip, options=options) or is_ipv6_filter(ip, options=options) def _ip_options_global(ip_obj, version): return not ip_obj.is_private def _ip_options_multicast(ip_obj, version): return ip_obj.is_multicast def _ip_options_loopback(ip_obj, version): return ip_obj.is_loopback def _ip_options_link_local(ip_obj, version): return ip_obj.is_link_local def _ip_options_private(ip_obj, version): return ip_obj.is_private def _ip_options_reserved(ip_obj, version): return ip_obj.is_reserved def _ip_options_site_local(ip_obj, version): if version == 6: return ip_obj.is_site_local return False def _ip_options_unspecified(ip_obj, version): return ip_obj.is_unspecified def _ip_options(ip_obj, version, options=None): # will process and IP options options_fun_map = { 'global': _ip_options_global, 'link-local': _ip_options_link_local, 'linklocal': _ip_options_link_local, 'll': _ip_options_link_local, 'link_local': _ip_options_link_local, 'loopback': _ip_options_loopback, 'lo': _ip_options_loopback, 'multicast': _ip_options_multicast, 'private': _ip_options_private, 'public': _ip_options_global, 'reserved': _ip_options_reserved, 'site-local': _ip_options_site_local, 'sl': _ip_options_site_local, 'site_local': _ip_options_site_local, 'unspecified': _ip_options_unspecified } if not options: return six.text_type(ip_obj) # IP version already checked options_list = [option.strip() for option in options.split(',')] for option, fun in options_fun_map.items(): if option in options_list: fun_res = fun(ip_obj, version) if not fun_res: return None # stop at first failed test # else continue return six.text_type(ip_obj) def _is_ipv(ip, version, options=None): if not version: version = 4 if version not in (4, 6): return None try: ip_obj = ipaddress.ip_address(ip) except ValueError: # maybe it is an IP network try: ip_obj = ipaddress.ip_interface(ip) except ValueError: # nope, still not :( return None if not ip_obj.version == version: return None # has the right version, let's move on return _ip_options(ip_obj, version, options=options) @jinja_filter('is_ipv4') def is_ipv4_filter(ip, options=None): ''' Returns a bool telling if the value passed to it was a valid IPv4 address. ip The IP address. net: False Consider IP addresses followed by netmask. options CSV of options regarding the nature of the IP address. E.g.: loopback, multicast, private etc. ''' _is_ipv4 = _is_ipv(ip, 4, options=options) return isinstance(_is_ipv4, six.string_types) @jinja_filter('is_ipv6') def is_ipv6_filter(ip, options=None): ''' Returns a bool telling if the value passed to it was a valid IPv6 address. ip The IP address. net: False Consider IP addresses followed by netmask. options CSV of options regarding the nature of the IP address. E.g.: loopback, multicast, private etc. ''' _is_ipv6 = _is_ipv(ip, 6, options=options) return isinstance(_is_ipv6, six.string_types) def _ipv_filter(value, version, options=None): if version not in (4, 6): return if isinstance(value, (six.string_types, six.text_type, six.binary_type)): return _is_ipv(value, version, options=options) # calls is_ipv4 or is_ipv6 for `value` elif isinstance(value, (list, tuple, types.GeneratorType)): # calls is_ipv4 or is_ipv6 for each element in the list # os it filters and returns only those elements having the desired IP version return [ _is_ipv(addr, version, options=options) for addr in value if _is_ipv(addr, version, options=options) is not None ] return None @jinja_filter('ipv4') def ipv4(value, options=None): ''' Filters a list and returns IPv4 values only. ''' return _ipv_filter(value, 4, options=options) @jinja_filter('ipv6') def ipv6(value, options=None): ''' Filters a list and returns IPv6 values only. ''' return _ipv_filter(value, 6, options=options) @jinja_filter('ipaddr') def ipaddr(value, options=None): ''' Filters and returns only valid IP objects. ''' ipv4_obj = ipv4(value, options=options) ipv6_obj = ipv6(value, options=options) if ipv4_obj is None or ipv6_obj is None: # an IP address can be either IPv4 either IPv6 # therefofe if the value passed as arg is not a list, at least one of the calls above will return None # if one of them is none, means that we should return only one of them return ipv4_obj or ipv6_obj # one of them else: return ipv4_obj + ipv6_obj # extend lists def _filter_ipaddr(value, options, version=None): ipaddr_filter_out = None if version: if version == 4: ipaddr_filter_out = ipv4(value, options) elif version == 6: ipaddr_filter_out = ipv6(value, options) else: ipaddr_filter_out = ipaddr(value, options) if not ipaddr_filter_out: return if not isinstance(ipaddr_filter_out, (list, tuple, types.GeneratorType)): ipaddr_filter_out = [ipaddr_filter_out] return ipaddr_filter_out @jinja_filter('ip_host') def ip_host(value, options=None, version=None): ''' Returns the interfaces IP address, e.g.: 192.168.0.1/28. ''' ipaddr_filter_out = _filter_ipaddr(value, options=options, version=version) if not ipaddr_filter_out: return if not isinstance(value, (list, tuple, types.GeneratorType)): return six.text_type(ipaddress.ip_interface(ipaddr_filter_out[0])) return [six.text_type(ipaddress.ip_interface(ip_a)) for ip_a in ipaddr_filter_out] def _network_hosts(ip_addr_entry): return [ six.text_type(host) for host in ipaddress.ip_network(ip_addr_entry, strict=False).hosts() ] @jinja_filter('network_hosts') def network_hosts(value, options=None, version=None): ''' Return the list of hosts within a network. .. note:: When running this command with a large IPv6 network, the command will take a long time to gather all of the hosts. ''' ipaddr_filter_out = _filter_ipaddr(value, options=options, version=version) if not ipaddr_filter_out: return if not isinstance(value, (list, tuple, types.GeneratorType)): return _network_hosts(ipaddr_filter_out[0]) return [ _network_hosts(ip_a) for ip_a in ipaddr_filter_out ] def _network_size(ip_addr_entry): return ipaddress.ip_network(ip_addr_entry, strict=False).num_addresses @jinja_filter('network_size') def network_size(value, options=None, version=None): ''' Get the size of a network. ''' ipaddr_filter_out = _filter_ipaddr(value, options=options, version=version) if not ipaddr_filter_out: return if not isinstance(value, (list, tuple, types.GeneratorType)): return _network_size(ipaddr_filter_out[0]) return [ _network_size(ip_a) for ip_a in ipaddr_filter_out ] def natural_ipv4_netmask(ip, fmt='prefixlen'): ''' Returns the "natural" mask of an IPv4 address ''' bits = _ipv4_to_bits(ip) if bits.startswith('11'): mask = '24' elif bits.startswith('1'): mask = '16' else: mask = '8' if fmt == 'netmask': return cidr_to_ipv4_netmask(mask) else: return '/' + mask def rpad_ipv4_network(ip): ''' Returns an IP network address padded with zeros. Ex: '192.168.3' -> '192.168.3.0' '10.209' -> '10.209.0.0' ''' return '.'.join(itertools.islice(itertools.chain(ip.split('.'), '0000'), 0, 4)) def cidr_to_ipv4_netmask(cidr_bits): ''' Returns an IPv4 netmask ''' try: cidr_bits = int(cidr_bits) if not 1 <= cidr_bits <= 32: return '' except ValueError: return '' netmask = '' for idx in range(4): if idx: netmask += '.' if cidr_bits >= 8: netmask += '255' cidr_bits -= 8 else: netmask += '{0:d}'.format(256 - (2 ** (8 - cidr_bits))) cidr_bits = 0 return netmask def _number_of_set_bits_to_ipv4_netmask(set_bits): # pylint: disable=C0103 ''' Returns an IPv4 netmask from the integer representation of that mask. Ex. 0xffffff00 -> '255.255.255.0' ''' return cidr_to_ipv4_netmask(_number_of_set_bits(set_bits)) # pylint: disable=C0103 def _number_of_set_bits(x): ''' Returns the number of bits that are set in a 32bit int ''' # Taken from http://stackoverflow.com/a/4912729. Many thanks! x -= (x >> 1) & 0x55555555 x = ((x >> 2) & 0x33333333) + (x & 0x33333333) x = ((x >> 4) + x) & 0x0f0f0f0f x += x >> 8 x += x >> 16 return x & 0x0000003f # pylint: enable=C0103 def _interfaces_ip(out): ''' Uses ip to return a dictionary of interfaces with various information about each (up/down state, ip address, netmask, and hwaddr) ''' ret = dict() def parse_network(value, cols): ''' Return a tuple of ip, netmask, broadcast based on the current set of cols ''' brd = None scope = None if '/' in value: # we have a CIDR in this address ip, cidr = value.split('/') # pylint: disable=C0103 else: ip = value # pylint: disable=C0103 cidr = 32 if type_ == 'inet': mask = cidr_to_ipv4_netmask(int(cidr)) if 'brd' in cols: brd = cols[cols.index('brd') + 1] elif type_ == 'inet6': mask = cidr if 'scope' in cols: scope = cols[cols.index('scope') + 1] return (ip, mask, brd, scope) groups = re.compile('\r?\n\\d').split(out) for group in groups: iface = None data = dict() for line in group.splitlines(): if ' ' not in line: continue match = re.match(r'^\d*:\s+([\w.\-]+)(?:@)?([\w.\-]+)?:\s+<(.+)>', line) if match: iface, parent, attrs = match.groups() if 'UP' in attrs.split(','): data['up'] = True else: data['up'] = False if parent: data['parent'] = parent continue cols = line.split() if len(cols) >= 2: type_, value = tuple(cols[0:2]) iflabel = cols[-1:][0] if type_ in ('inet', 'inet6'): if 'secondary' not in cols: ipaddr, netmask, broadcast, scope = parse_network(value, cols) if type_ == 'inet': if 'inet' not in data: data['inet'] = list() addr_obj = dict() addr_obj['address'] = ipaddr addr_obj['netmask'] = netmask addr_obj['broadcast'] = broadcast addr_obj['label'] = iflabel data['inet'].append(addr_obj) elif type_ == 'inet6': if 'inet6' not in data: data['inet6'] = list() addr_obj = dict() addr_obj['address'] = ipaddr addr_obj['prefixlen'] = netmask addr_obj['scope'] = scope data['inet6'].append(addr_obj) else: if 'secondary' not in data: data['secondary'] = list() ip_, mask, brd, scp = parse_network(value, cols) data['secondary'].append({ 'type': type_, 'address': ip_, 'netmask': mask, 'broadcast': brd, 'label': iflabel, }) del ip_, mask, brd, scp elif type_.startswith('link'): data['hwaddr'] = value if iface: ret[iface] = data del iface, data return ret def _interfaces_ifconfig(out): ''' Uses ifconfig to return a dictionary of interfaces with various information about each (up/down state, ip address, netmask, and hwaddr) ''' ret = dict() piface = re.compile(r'^([^\s:]+)') pmac = re.compile('.*?(?:HWaddr|ether|address:|lladdr) ([0-9a-fA-F:]+)') if salt.utils.platform.is_sunos(): pip = re.compile(r'.*?(?:inet\s+)([0-9]+\.[0-9]+\.[0-9]+\.[0-9]+)(.*)') pip6 = re.compile('.*?(?:inet6 )([0-9a-fA-F:]+)') pmask6 = re.compile(r'.*?(?:inet6 [0-9a-fA-F:]+/(\d+)).*') else: pip = re.compile(r'.*?(?:inet addr:|inet [^\d]*)(.*?)\s') pip6 = re.compile('.*?(?:inet6 addr: (.*?)/|inet6 )([0-9a-fA-F:]+)') pmask6 = re.compile(r'.*?(?:inet6 addr: [0-9a-fA-F:]+/(\d+)|prefixlen (\d+))(?: Scope:([a-zA-Z]+)| scopeid (0x[0-9a-fA-F]))?') pmask = re.compile(r'.*?(?:Mask:|netmask )(?:((?:0x)?[0-9a-fA-F]{8})|([\d\.]+))') pupdown = re.compile('UP') pbcast = re.compile(r'.*?(?:Bcast:|broadcast )([\d\.]+)') groups = re.compile('\r?\n(?=\\S)').split(out) for group in groups: data = dict() iface = '' updown = False for line in group.splitlines(): miface = piface.match(line) mmac = pmac.match(line) mip = pip.match(line) mip6 = pip6.match(line) mupdown = pupdown.search(line) if miface: iface = miface.group(1) if mmac: data['hwaddr'] = mmac.group(1) if salt.utils.platform.is_sunos(): expand_mac = [] for chunk in data['hwaddr'].split(':'): expand_mac.append('0{0}'.format(chunk) if len(chunk) < 2 else '{0}'.format(chunk)) data['hwaddr'] = ':'.join(expand_mac) if mip: if 'inet' not in data: data['inet'] = list() addr_obj = dict() addr_obj['address'] = mip.group(1) mmask = pmask.match(line) if mmask: if mmask.group(1): mmask = _number_of_set_bits_to_ipv4_netmask( int(mmask.group(1), 16)) else: mmask = mmask.group(2) addr_obj['netmask'] = mmask mbcast = pbcast.match(line) if mbcast: addr_obj['broadcast'] = mbcast.group(1) data['inet'].append(addr_obj) if mupdown: updown = True if mip6: if 'inet6' not in data: data['inet6'] = list() addr_obj = dict() addr_obj['address'] = mip6.group(1) or mip6.group(2) mmask6 = pmask6.match(line) if mmask6: addr_obj['prefixlen'] = mmask6.group(1) or mmask6.group(2) if not salt.utils.platform.is_sunos(): ipv6scope = mmask6.group(3) or mmask6.group(4) addr_obj['scope'] = ipv6scope.lower() if ipv6scope is not None else ipv6scope # SunOS sometimes has ::/0 as inet6 addr when using addrconf if not salt.utils.platform.is_sunos() \ or addr_obj['address'] != '::' \ and addr_obj['prefixlen'] != 0: data['inet6'].append(addr_obj) data['up'] = updown if iface in ret: # SunOS optimization, where interfaces occur twice in 'ifconfig -a' # output with the same name: for ipv4 and then for ipv6 addr family. # Every instance has it's own 'UP' status and we assume that ipv4 # status determines global interface status. # # merge items with higher priority for older values # after that merge the inet and inet6 sub items for both ret[iface] = dict(list(data.items()) + list(ret[iface].items())) if 'inet' in data: ret[iface]['inet'].extend(x for x in data['inet'] if x not in ret[iface]['inet']) if 'inet6' in data: ret[iface]['inet6'].extend(x for x in data['inet6'] if x not in ret[iface]['inet6']) else: ret[iface] = data del data return ret def linux_interfaces(): ''' Obtain interface information for *NIX/BSD variants ''' ifaces = dict() ip_path = salt.utils.path.which('ip') ifconfig_path = None if ip_path else salt.utils.path.which('ifconfig') if ip_path: cmd1 = subprocess.Popen( '{0} link show'.format(ip_path), shell=True, close_fds=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT).communicate()[0] cmd2 = subprocess.Popen( '{0} addr show'.format(ip_path), shell=True, close_fds=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT).communicate()[0] ifaces = _interfaces_ip("{0}\n{1}".format( salt.utils.stringutils.to_str(cmd1), salt.utils.stringutils.to_str(cmd2))) elif ifconfig_path: cmd = subprocess.Popen( '{0} -a'.format(ifconfig_path), shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT).communicate()[0] ifaces = _interfaces_ifconfig(salt.utils.stringutils.to_str(cmd)) return ifaces def _netbsd_interfaces_ifconfig(out): ''' Uses ifconfig to return a dictionary of interfaces with various information about each (up/down state, ip address, netmask, and hwaddr) ''' ret = dict() piface = re.compile(r'^([^\s:]+)') pmac = re.compile('.*?address: ([0-9a-f:]+)') pip = re.compile(r'.*?inet [^\d]*(.*?)/([\d]*)\s') pip6 = re.compile(r'.*?inet6 ([0-9a-f:]+)%([a-zA-Z0-9]*)/([\d]*)\s') pupdown = re.compile('UP') pbcast = re.compile(r'.*?broadcast ([\d\.]+)') groups = re.compile('\r?\n(?=\\S)').split(out) for group in groups: data = dict() iface = '' updown = False for line in group.splitlines(): miface = piface.match(line) mmac = pmac.match(line) mip = pip.match(line) mip6 = pip6.match(line) mupdown = pupdown.search(line) if miface: iface = miface.group(1) if mmac: data['hwaddr'] = mmac.group(1) if mip: if 'inet' not in data: data['inet'] = list() addr_obj = dict() addr_obj['address'] = mip.group(1) mmask = mip.group(2) if mip.group(2): addr_obj['netmask'] = cidr_to_ipv4_netmask(mip.group(2)) mbcast = pbcast.match(line) if mbcast: addr_obj['broadcast'] = mbcast.group(1) data['inet'].append(addr_obj) if mupdown: updown = True if mip6: if 'inet6' not in data: data['inet6'] = list() addr_obj = dict() addr_obj['address'] = mip6.group(1) mmask6 = mip6.group(3) addr_obj['scope'] = mip6.group(2) addr_obj['prefixlen'] = mip6.group(3) data['inet6'].append(addr_obj) data['up'] = updown ret[iface] = data del data return ret def netbsd_interfaces(): ''' Obtain interface information for NetBSD >= 8 where the ifconfig output diverged from other BSD variants (Netmask is now part of the address) ''' # NetBSD versions prior to 8.0 can still use linux_interfaces() if LooseVersion(os.uname()[2]) < LooseVersion('8.0'): return linux_interfaces() ifconfig_path = salt.utils.path.which('ifconfig') cmd = subprocess.Popen( '{0} -a'.format(ifconfig_path), shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT).communicate()[0] return _netbsd_interfaces_ifconfig(salt.utils.stringutils.to_str(cmd)) def _interfaces_ipconfig(out): ''' Returns a dictionary of interfaces with various information about each (up/down state, ip address, netmask, and hwaddr) NOTE: This is not used by any function and may be able to be removed in the future. ''' ifaces = dict() iface = None adapter_iface_regex = re.compile(r'adapter (\S.+):$') for line in out.splitlines(): if not line: continue # TODO what does Windows call Infiniband and 10/40gige adapters if line.startswith('Ethernet'): iface = ifaces[adapter_iface_regex.search(line).group(1)] iface['up'] = True addr = None continue if iface: key, val = line.split(',', 1) key = key.strip(' .') val = val.strip() if addr and key == 'Subnet Mask': addr['netmask'] = val elif key in ('IP Address', 'IPv4 Address'): if 'inet' not in iface: iface['inet'] = list() addr = {'address': val.rstrip('(Preferred)'), 'netmask': None, 'broadcast': None} # TODO find the broadcast iface['inet'].append(addr) elif 'IPv6 Address' in key: if 'inet6' not in iface: iface['inet'] = list() # XXX What is the prefixlen!? addr = {'address': val.rstrip('(Preferred)'), 'prefixlen': None} iface['inet6'].append(addr) elif key == 'Physical Address': iface['hwaddr'] = val elif key == 'Media State': # XXX seen used for tunnel adaptors # might be useful iface['up'] = (val != 'Media disconnected') def win_interfaces(): ''' Obtain interface information for Windows systems ''' with salt.utils.winapi.Com(): c = wmi.WMI() ifaces = {} for iface in c.Win32_NetworkAdapterConfiguration(IPEnabled=1): ifaces[iface.Description] = dict() if iface.MACAddress: ifaces[iface.Description]['hwaddr'] = iface.MACAddress if iface.IPEnabled: ifaces[iface.Description]['up'] = True for ip in iface.IPAddress: if '.' in ip: if 'inet' not in ifaces[iface.Description]: ifaces[iface.Description]['inet'] = [] item = {'address': ip, 'label': iface.Description} if iface.DefaultIPGateway: broadcast = next((i for i in iface.DefaultIPGateway if '.' in i), '') if broadcast: item['broadcast'] = broadcast if iface.IPSubnet: netmask = next((i for i in iface.IPSubnet if '.' in i), '') if netmask: item['netmask'] = netmask ifaces[iface.Description]['inet'].append(item) if ':' in ip: if 'inet6' not in ifaces[iface.Description]: ifaces[iface.Description]['inet6'] = [] item = {'address': ip} if iface.DefaultIPGateway: broadcast = next((i for i in iface.DefaultIPGateway if ':' in i), '') if broadcast: item['broadcast'] = broadcast if iface.IPSubnet: netmask = next((i for i in iface.IPSubnet if ':' in i), '') if netmask: item['netmask'] = netmask ifaces[iface.Description]['inet6'].append(item) else: ifaces[iface.Description]['up'] = False return ifaces def interfaces(): ''' Return a dictionary of information about all the interfaces on the minion ''' if salt.utils.platform.is_windows(): return win_interfaces() elif salt.utils.platform.is_netbsd(): return netbsd_interfaces() else: return linux_interfaces() def get_net_start(ipaddr, netmask): ''' Return the address of the network ''' net = ipaddress.ip_network('{0}/{1}'.format(ipaddr, netmask), strict=False) return six.text_type(net.network_address) def get_net_size(mask): ''' Turns an IPv4 netmask into it's corresponding prefix length (255.255.255.0 -> 24 as in 192.168.1.10/24). ''' binary_str = '' for octet in mask.split('.'): binary_str += bin(int(octet))[2:].zfill(8) return len(binary_str.rstrip('0')) def calc_net(ipaddr, netmask=None): ''' Takes IP (CIDR notation supported) and optionally netmask and returns the network in CIDR-notation. (The IP can be any IP inside the subnet) ''' if netmask is not None: ipaddr = '{0}/{1}'.format(ipaddr, netmask) return six.text_type(ipaddress.ip_network(ipaddr, strict=False)) def _ipv4_to_bits(ipaddr): ''' Accepts an IPv4 dotted quad and returns a string representing its binary counterpart ''' return ''.join([bin(int(x))[2:].rjust(8, '0') for x in ipaddr.split('.')]) def _get_iface_info(iface): ''' If `iface` is available, return interface info and no error, otherwise return no info and log and return an error ''' iface_info = interfaces() if iface in iface_info.keys(): return iface_info, False else: error_msg = ('Interface "{0}" not in available interfaces: "{1}"' ''.format(iface, '", "'.join(iface_info.keys()))) log.error(error_msg) return None, error_msg def _hw_addr_aix(iface): ''' Return the hardware address (a.k.a. MAC address) for a given interface on AIX MAC address not available in through interfaces ''' cmd = subprocess.Popen( 'entstat -d {0} | grep \'Hardware Address\''.format(iface), shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT).communicate()[0] if cmd: comps = cmd.split(' ') if len(comps) == 3: mac_addr = comps[2].strip('\'').strip() return mac_addr error_msg = ('Interface "{0}" either not available or does not contain a hardware address'.format(iface)) log.error(error_msg) return error_msg def hw_addr(iface): ''' Return the hardware address (a.k.a. MAC address) for a given interface .. versionchanged:: 2016.11.4 Added support for AIX ''' if salt.utils.platform.is_aix(): return _hw_addr_aix iface_info, error = _get_iface_info(iface) if error is False: return iface_info.get(iface, {}).get('hwaddr', '') else: return error def interface(iface): ''' Return the details of `iface` or an error if it does not exist ''' iface_info, error = _get_iface_info(iface) if error is False: return iface_info.get(iface, {}).get('inet', '') else: return error def interface_ip(iface): ''' Return `iface` IPv4 addr or an error if `iface` does not exist ''' iface_info, error = _get_iface_info(iface) if error is False: inet = iface_info.get(iface, {}).get('inet', None) return inet[0].get('address', '') if inet else '' else: return error def _subnets(proto='inet', interfaces_=None): ''' Returns a list of subnets to which the host belongs ''' if interfaces_ is None: ifaces = interfaces() elif isinstance(interfaces_, list): ifaces = {} for key, value in six.iteritems(interfaces()): if key in interfaces_: ifaces[key] = value else: ifaces = {interfaces_: interfaces().get(interfaces_, {})} ret = set() if proto == 'inet': subnet = 'netmask' dflt_cidr = 32 elif proto == 'inet6': subnet = 'prefixlen' dflt_cidr = 128 else: log.error('Invalid proto %s calling subnets()', proto) return for ip_info in six.itervalues(ifaces): addrs = ip_info.get(proto, []) addrs.extend([addr for addr in ip_info.get('secondary', []) if addr.get('type') == proto]) for intf in addrs: if subnet in intf: intf = ipaddress.ip_interface('{0}/{1}'.format(intf['address'], intf[subnet])) else: intf = ipaddress.ip_interface('{0}/{1}'.format(intf['address'], dflt_cidr)) if not intf.is_loopback: ret.add(intf.network) return [six.text_type(net) for net in sorted(ret)] def subnets(interfaces=None): ''' Returns a list of IPv4 subnets to which the host belongs ''' return _subnets('inet', interfaces_=interfaces) def subnets6(): ''' Returns a list of IPv6 subnets to which the host belongs ''' return _subnets('inet6') def in_subnet(cidr, addr=None): ''' Returns True if host or (any of) addrs is within specified subnet, otherwise False ''' try: cidr = ipaddress.ip_network(cidr) except ValueError: log.error('Invalid CIDR \'%s\'', cidr) return False if addr is None: addr = ip_addrs() addr.extend(ip_addrs6()) elif not isinstance(addr, (list, tuple)): addr = (addr,) return any(ipaddress.ip_address(item) in cidr for item in addr) def _ip_addrs(interface=None, include_loopback=False, interface_data=None, proto='inet'): ''' Return the full list of IP adresses matching the criteria proto = inet|inet6 ''' ret = set() ifaces = interface_data \ if isinstance(interface_data, dict) \ else interfaces() if interface is None: target_ifaces = ifaces else: target_ifaces = dict([(k, v) for k, v in six.iteritems(ifaces) if k == interface]) if not target_ifaces: log.error('Interface %s not found.', interface) for ip_info in six.itervalues(target_ifaces): addrs = ip_info.get(proto, []) addrs.extend([addr for addr in ip_info.get('secondary', []) if addr.get('type') == proto]) for addr in addrs: addr = ipaddress.ip_address(addr.get('address')) if not addr.is_loopback or include_loopback: ret.add(addr) return [six.text_type(addr) for addr in sorted(ret)] def ip_addrs(interface=None, include_loopback=False, interface_data=None): ''' Returns a list of IPv4 addresses assigned to the host. 127.0.0.1 is ignored, unless 'include_loopback=True' is indicated. If 'interface' is provided, then only IP addresses from that interface will be returned. ''' return _ip_addrs(interface, include_loopback, interface_data, 'inet') def ip_addrs6(interface=None, include_loopback=False, interface_data=None): ''' Returns a list of IPv6 addresses assigned to the host. ::1 is ignored, unless 'include_loopback=True' is indicated. If 'interface' is provided, then only IP addresses from that interface will be returned. ''' return _ip_addrs(interface, include_loopback, interface_data, 'inet6') def hex2ip(hex_ip, invert=False): ''' Convert a hex string to an ip, if a failure occurs the original hex is returned. If 'invert=True' assume that ip from /proc/net/<proto> ''' if len(hex_ip) == 32: # ipv6 ip = [] for i in range(0, 32, 8): ip_part = hex_ip[i:i + 8] ip_part = [ip_part[x:x + 2] for x in range(0, 8, 2)] if invert: ip.append("{0[3]}{0[2]}:{0[1]}{0[0]}".format(ip_part)) else: ip.append("{0[0]}{0[1]}:{0[2]}{0[3]}".format(ip_part)) try: address = ipaddress.IPv6Address(":".join(ip)) if address.ipv4_mapped: return str(address.ipv4_mapped) else: return address.compressed except ipaddress.AddressValueError as ex: log.error('hex2ip - ipv6 address error: %s', ex) return hex_ip try: hip = int(hex_ip, 16) except ValueError: return hex_ip if invert: return '{3}.{2}.{1}.{0}'.format(hip >> 24 & 255, hip >> 16 & 255, hip >> 8 & 255, hip & 255) return '{0}.{1}.{2}.{3}'.format(hip >> 24 & 255, hip >> 16 & 255, hip >> 8 & 255, hip & 255) def mac2eui64(mac, prefix=None): ''' Convert a MAC address to a EUI64 identifier or, with prefix provided, a full IPv6 address ''' # http://tools.ietf.org/html/rfc4291#section-2.5.1 eui64 = re.sub(r'[.:-]', '', mac).lower() eui64 = eui64[0:6] + 'fffe' + eui64[6:] eui64 = hex(int(eui64[0:2], 16) | 2)[2:].zfill(2) + eui64[2:] if prefix is None: return ':'.join(re.findall(r'.{4}', eui64)) else: try: net = ipaddress.ip_network(prefix, strict=False) euil = int('0x{0}'.format(eui64), 16) return '{0}/{1}'.format(net[euil], net.prefixlen) except Exception: return def active_tcp(): ''' Return a dict describing all active tcp connections as quickly as possible ''' ret = {} for statf in ['/proc/net/tcp', '/proc/net/tcp6']: if os.path.isfile(statf): with salt.utils.files.fopen(statf, 'rb') as fp_: for line in fp_: line = salt.utils.stringutils.to_unicode(line) if line.strip().startswith('sl'): continue iret = _parse_tcp_line(line) sl = next(iter(iret)) if iret[sl]['state'] == 1: # 1 is ESTABLISHED del iret[sl]['state'] ret[len(ret)] = iret[sl] return ret def local_port_tcp(port): ''' Return a set of remote ip addrs attached to the specified local port ''' ret = _remotes_on(port, 'local_port') return ret def remote_port_tcp(port): ''' Return a set of ip addrs the current host is connected to on given port ''' ret = _remotes_on(port, 'remote_port') return ret def _remotes_on(port, which_end): ''' Return a set of ip addrs active tcp connections ''' port = int(port) ret = _netlink_tool_remote_on(port, which_end) if ret is not None: return ret ret = set() proc_available = False for statf in ['/proc/net/tcp', '/proc/net/tcp6']: if os.path.isfile(statf): proc_available = True with salt.utils.files.fopen(statf, 'r') as fp_: for line in fp_: line = salt.utils.stringutils.to_unicode(line) if line.strip().startswith('sl'): continue iret = _parse_tcp_line(line) sl = next(iter(iret)) if iret[sl][which_end] == port and iret[sl]['state'] == 1: # 1 is ESTABLISHED ret.add(iret[sl]['remote_addr']) if not proc_available: # Fallback to use OS specific tools if salt.utils.platform.is_sunos(): return _sunos_remotes_on(port, which_end) if salt.utils.platform.is_freebsd(): return _freebsd_remotes_on(port, which_end) if salt.utils.platform.is_netbsd(): return _netbsd_remotes_on(port, which_end) if salt.utils.platform.is_openbsd(): return _openbsd_remotes_on(port, which_end) if salt.utils.platform.is_windows(): return _windows_remotes_on(port, which_end) if salt.utils.platform.is_aix(): return _aix_remotes_on(port, which_end) return _linux_remotes_on(port, which_end) return ret def _parse_tcp_line(line): ''' Parse a single line from the contents of /proc/net/tcp or /proc/net/tcp6 ''' ret = {} comps = line.strip().split() sl = comps[0].rstrip(':') ret[sl] = {} l_addr, l_port = comps[1].split(':') r_addr, r_port = comps[2].split(':') ret[sl]['local_addr'] = hex2ip(l_addr, True) ret[sl]['local_port'] = int(l_port, 16) ret[sl]['remote_addr'] = hex2ip(r_addr, True) ret[sl]['remote_port'] = int(r_port, 16) ret[sl]['state'] = int(comps[3], 16) return ret def _netlink_tool_remote_on(port, which_end): ''' Returns set of ipv4 host addresses of remote established connections on local or remote tcp port. Parses output of shell 'ss' to get connections [root@salt-master ~]# ss -ant State Recv-Q Send-Q Local Address:Port Peer Address:Port LISTEN 0 511 *:80 *:* LISTEN 0 128 *:22 *:* ESTAB 0 0 127.0.0.1:56726 127.0.0.1:4505 ''' remotes = set() valid = False try: data = subprocess.check_output(['ss', '-ant']) # pylint: disable=minimum-python-version except subprocess.CalledProcessError: log.error('Failed ss') raise except OSError: # not command "No such file or directory" return None lines = salt.utils.stringutils.to_str(data).split('\n') for line in lines: if 'Address:Port' in line: # ss tools may not be valid valid = True continue elif 'ESTAB' not in line: continue chunks = line.split() local_host, local_port = chunks[3].split(':', 1) remote_host, remote_port = chunks[4].split(':', 1) if which_end == 'remote_port' and int(remote_port) != port: continue if which_end == 'local_port' and int(local_port) != port: continue remotes.add(remote_host) if valid is False: remotes = None return remotes def _sunos_remotes_on(port, which_end): ''' SunOS specific helper function. Returns set of ipv4 host addresses of remote established connections on local or remote tcp port. Parses output of shell 'netstat' to get connections [root@salt-master ~]# netstat -f inet -n TCP: IPv4 Local Address Remote Address Swind Send-Q Rwind Recv-Q State -------------------- -------------------- ----- ------ ----- ------ ----------- 10.0.0.101.4505 10.0.0.1.45329 1064800 0 1055864 0 ESTABLISHED 10.0.0.101.4505 10.0.0.100.50798 1064800 0 1055864 0 ESTABLISHED ''' remotes = set() try: data = subprocess.check_output(['netstat', '-f', 'inet', '-n']) # pylint: disable=minimum-python-version except subprocess.CalledProcessError: log.error('Failed netstat') raise lines = salt.utils.stringutils.to_str(data).split('\n') for line in lines: if 'ESTABLISHED' not in line: continue chunks = line.split() local_host, local_port = chunks[0].rsplit('.', 1) remote_host, remote_port = chunks[1].rsplit('.', 1) if which_end == 'remote_port' and int(remote_port) != port: continue if which_end == 'local_port' and int(local_port) != port: continue remotes.add(remote_host) return remotes def _freebsd_remotes_on(port, which_end): ''' Returns set of ipv4 host addresses of remote established connections on local tcp port port. Parses output of shell 'sockstat' (FreeBSD) to get connections $ sudo sockstat -4 USER COMMAND PID FD PROTO LOCAL ADDRESS FOREIGN ADDRESS root python2.7 1456 29 tcp4 *:4505 *:* root python2.7 1445 17 tcp4 *:4506 *:* root python2.7 1294 14 tcp4 127.0.0.1:11813 127.0.0.1:4505 root python2.7 1294 41 tcp4 127.0.0.1:61115 127.0.0.1:4506 $ sudo sockstat -4 -c -p 4506 USER COMMAND PID FD PROTO LOCAL ADDRESS FOREIGN ADDRESS root python2.7 1294 41 tcp4 127.0.0.1:61115 127.0.0.1:4506 ''' port = int(port) remotes = set() try: cmd = salt.utils.args.shlex_split('sockstat -4 -c -p {0}'.format(port)) data = subprocess.check_output(cmd) # pylint: disable=minimum-python-version except subprocess.CalledProcessError as ex: log.error('Failed "sockstat" with returncode = %s', ex.returncode) raise lines = salt.utils.stringutils.to_str(data).split('\n') for line in lines: chunks = line.split() if not chunks: continue # ['root', 'python2.7', '1456', '37', 'tcp4', # '127.0.0.1:4505-', '127.0.0.1:55703'] # print chunks if 'COMMAND' in chunks[1]: continue # ignore header if len(chunks) < 2: continue # sockstat -4 -c -p 4506 does this with high PIDs: # USER COMMAND PID FD PROTO LOCAL ADDRESS FOREIGN ADDRESS # salt-master python2.781106 35 tcp4 192.168.12.34:4506 192.168.12.45:60143 local = chunks[-2] remote = chunks[-1] lhost, lport = local.split(':') rhost, rport = remote.split(':') if which_end == 'local' and int(lport) != port: # ignore if local port not port continue if which_end == 'remote' and int(rport) != port: # ignore if remote port not port continue remotes.add(rhost) return remotes def _netbsd_remotes_on(port, which_end): ''' Returns set of ipv4 host addresses of remote established connections on local tcp port port. Parses output of shell 'sockstat' (NetBSD) to get connections $ sudo sockstat -4 -n USER COMMAND PID FD PROTO LOCAL ADDRESS FOREIGN ADDRESS root python2.7 1456 29 tcp *.4505 *.* root python2.7 1445 17 tcp *.4506 *.* root python2.7 1294 14 tcp 127.0.0.1.11813 127.0.0.1.4505 root python2.7 1294 41 tcp 127.0.0.1.61115 127.0.0.1.4506 $ sudo sockstat -4 -c -n -p 4506 USER COMMAND PID FD PROTO LOCAL ADDRESS FOREIGN ADDRESS root python2.7 1294 41 tcp 127.0.0.1.61115 127.0.0.1.4506 ''' port = int(port) remotes = set() try: cmd = salt.utils.args.shlex_split('sockstat -4 -c -n -p {0}'.format(port)) data = subprocess.check_output(cmd) # pylint: disable=minimum-python-version except subprocess.CalledProcessError as ex: log.error('Failed "sockstat" with returncode = %s', ex.returncode) raise lines = salt.utils.stringutils.to_str(data).split('\n') for line in lines: chunks = line.split() if not chunks: continue # ['root', 'python2.7', '1456', '37', 'tcp', # '127.0.0.1.4505-', '127.0.0.1.55703'] # print chunks if 'COMMAND' in chunks[1]: continue # ignore header if len(chunks) < 2: continue local = chunks[5].split('.') lport = local.pop() lhost = '.'.join(local) remote = chunks[6].split('.') rport = remote.pop() rhost = '.'.join(remote) if which_end == 'local' and int(lport) != port: # ignore if local port not port continue if which_end == 'remote' and int(rport) != port: # ignore if remote port not port continue remotes.add(rhost) return remotes def _openbsd_remotes_on(port, which_end): ''' OpenBSD specific helper function. Returns set of ipv4 host addresses of remote established connections on local or remote tcp port. Parses output of shell 'netstat' to get connections $ netstat -nf inet Active Internet connections Proto Recv-Q Send-Q Local Address Foreign Address (state) tcp 0 0 10.0.0.101.4505 10.0.0.1.45329 ESTABLISHED tcp 0 0 10.0.0.101.4505 10.0.0.100.50798 ESTABLISHED ''' remotes = set() try: data = subprocess.check_output(['netstat', '-nf', 'inet']) # pylint: disable=minimum-python-version except subprocess.CalledProcessError: log.error('Failed netstat') raise lines = data.split('\n') for line in lines: if 'ESTABLISHED' not in line: continue chunks = line.split() local_host, local_port = chunks[3].rsplit('.', 1) remote_host, remote_port = chunks[4].rsplit('.', 1) if which_end == 'remote_port' and int(remote_port) != port: continue if which_end == 'local_port' and int(local_port) != port: continue remotes.add(remote_host) return remotes def _linux_remotes_on(port, which_end): ''' Linux specific helper function. Returns set of ip host addresses of remote established connections on local tcp port port. Parses output of shell 'lsof' to get connections $ sudo lsof -iTCP:4505 -n COMMAND PID USER FD TYPE DEVICE SIZE/OFF NODE NAME Python 9971 root 35u IPv4 0x18a8464a29ca329d 0t0 TCP *:4505 (LISTEN) Python 9971 root 37u IPv4 0x18a8464a29b2b29d 0t0 TCP 127.0.0.1:4505->127.0.0.1:55703 (ESTABLISHED) Python 10152 root 22u IPv4 0x18a8464a29c8cab5 0t0 TCP 127.0.0.1:55703->127.0.0.1:4505 (ESTABLISHED) Python 10153 root 22u IPv4 0x18a8464a29c8cab5 0t0 TCP [fe80::249a]:4505->[fe80::150]:59367 (ESTABLISHED) ''' remotes = set() try: data = subprocess.check_output( ['lsof', '-iTCP:{0:d}'.format(port), '-n', '-P'] # pylint: disable=minimum-python-version ) except subprocess.CalledProcessError as ex: if ex.returncode == 1: # Lsof return 1 if any error was detected, including the failure # to locate Internet addresses, and it is not an error in this case. log.warning('"lsof" returncode = 1, likely no active TCP sessions.') return remotes log.error('Failed "lsof" with returncode = %s', ex.returncode) raise lines = salt.utils.stringutils.to_str(data).split('\n') for line in lines: chunks = line.split() if not chunks: continue # ['Python', '9971', 'root', '37u', 'IPv4', '0x18a8464a29b2b29d', '0t0', # 'TCP', '127.0.0.1:4505->127.0.0.1:55703', '(ESTABLISHED)'] # print chunks if 'COMMAND' in chunks[0]: continue # ignore header if 'ESTABLISHED' not in chunks[-1]: continue # ignore if not ESTABLISHED # '127.0.0.1:4505->127.0.0.1:55703' local, remote = chunks[8].split('->') _, lport = local.rsplit(':', 1) rhost, rport = remote.rsplit(':', 1) if which_end == 'remote_port' and int(rport) != port: continue if which_end == 'local_port' and int(lport) != port: continue remotes.add(rhost.strip("[]")) return remotes def _aix_remotes_on(port, which_end): ''' AIX specific helper function. Returns set of ipv4 host addresses of remote established connections on local or remote tcp port. Parses output of shell 'netstat' to get connections root@la68pp002_pub:/opt/salt/lib/python2.7/site-packages/salt/modules# netstat -f inet -n Active Internet connections Proto Recv-Q Send-Q Local Address Foreign Address (state) tcp4 0 0 172.29.149.95.50093 209.41.78.13.4505 ESTABLISHED tcp4 0 0 127.0.0.1.9514 *.* LISTEN tcp4 0 0 127.0.0.1.9515 *.* LISTEN tcp4 0 0 127.0.0.1.199 127.0.0.1.32779 ESTABLISHED tcp4 0 0 127.0.0.1.32779 127.0.0.1.199 ESTABLISHED tcp4 0 40 172.29.149.95.22 172.29.96.83.41022 ESTABLISHED tcp4 0 0 172.29.149.95.22 172.29.96.83.41032 ESTABLISHED tcp4 0 0 127.0.0.1.32771 127.0.0.1.32775 ESTABLISHED tcp 0 0 127.0.0.1.32775 127.0.0.1.32771 ESTABLISHED tcp4 0 0 127.0.0.1.32771 127.0.0.1.32776 ESTABLISHED tcp 0 0 127.0.0.1.32776 127.0.0.1.32771 ESTABLISHED tcp4 0 0 127.0.0.1.32771 127.0.0.1.32777 ESTABLISHED tcp 0 0 127.0.0.1.32777 127.0.0.1.32771 ESTABLISHED tcp4 0 0 127.0.0.1.32771 127.0.0.1.32778 ESTABLISHED tcp 0 0 127.0.0.1.32778 127.0.0.1.32771 ESTABLISHED ''' remotes = set() try: data = subprocess.check_output(['netstat', '-f', 'inet', '-n']) # pylint: disable=minimum-python-version except subprocess.CalledProcessError: log.error('Failed netstat') raise lines = salt.utils.stringutils.to_str(data).split('\n') for line in lines: if 'ESTABLISHED' not in line: continue chunks = line.split() local_host, local_port = chunks[3].rsplit('.', 1) remote_host, remote_port = chunks[4].rsplit('.', 1) if which_end == 'remote_port' and int(remote_port) != port: continue if which_end == 'local_port' and int(local_port) != port: continue remotes.add(remote_host) return remotes @jinja_filter('gen_mac') def gen_mac(prefix='AC:DE:48'): ''' Generates a MAC address with the defined OUI prefix. Common prefixes: - ``00:16:3E`` -- Xen - ``00:18:51`` -- OpenVZ - ``00:50:56`` -- VMware (manually generated) - ``52:54:00`` -- QEMU/KVM - ``AC:DE:48`` -- PRIVATE References: - http://standards.ieee.org/develop/regauth/oui/oui.txt - https://www.wireshark.org/tools/oui-lookup.html - https://en.wikipedia.org/wiki/MAC_address ''' return '{0}:{1:02X}:{2:02X}:{3:02X}'.format(prefix, random.randint(0, 0xff), random.randint(0, 0xff), random.randint(0, 0xff)) @jinja_filter('mac_str_to_bytes') def mac_str_to_bytes(mac_str): ''' Convert a MAC address string into bytes. Works with or without separators: b1 = mac_str_to_bytes('08:00:27:13:69:77') b2 = mac_str_to_bytes('080027136977') assert b1 == b2 assert isinstance(b1, bytes) ''' if len(mac_str) == 12: pass elif len(mac_str) == 17: sep = mac_str[2] mac_str = mac_str.replace(sep, '') else: raise ValueError('Invalid MAC address') chars = (int(mac_str[s:s+2], 16) for s in range(0, 12, 2)) return bytes(chars) if six.PY3 else b''.join(chr(x) for x in chars) def refresh_dns(): ''' issue #21397: force glibc to re-read resolv.conf ''' try: res_init() except NameError: # Exception raised loading the library, thus res_init is not defined pass @jinja_filter('connection_check') def connection_check(addr, port=80, safe=False, ipv6=None): ''' Provides a convenient alias for the dns_check filter. ''' return dns_check(addr, port, safe, ipv6) @jinja_filter('dns_check') def dns_check(addr, port=80, safe=False, ipv6=None, attempt_connect=True): ''' Return the ip resolved by dns, but do not exit on failure, only raise an exception. Obeys system preference for IPv4/6 address resolution - this can be overridden by the ipv6 flag. Tries to connect to the address before considering it useful. If no address can be reached, the first one resolved is used as a fallback. ''' error = False lookup = addr seen_ipv6 = False family = socket.AF_INET6 if ipv6 else socket.AF_INET if ipv6 is False else socket.AF_UNSPEC hostnames = [] try: refresh_dns() hostnames = socket.getaddrinfo(addr, port, family, socket.SOCK_STREAM) except TypeError: err = ('Attempt to resolve address \'{0}\' failed. Invalid or unresolveable address').format(lookup) raise SaltSystemExit(code=42, msg=err) except socket.error: error = True # If ipv6 is set to True, attempt another lookup using the IPv4 family, # just in case we're attempting to lookup an IPv4 IP # as an IPv6 hostname. if error and ipv6: try: refresh_dns() hostnames = socket.getaddrinfo(addr, port, socket.AF_INET, socket.SOCK_STREAM) except TypeError: err = ('Attempt to resolve address \'{0}\' failed. Invalid or unresolveable address').format(lookup) raise SaltSystemExit(code=42, msg=err) except socket.error: error = True try: if not hostnames: error = True else: resolved = False candidates = [] for h in hostnames: # Input is IP address, passed through unchanged, just return it if h[4][0] == addr: resolved = salt.utils.zeromq.ip_bracket(addr) break candidate_addr = salt.utils.zeromq.ip_bracket(h[4][0]) # sometimes /etc/hosts contains ::1 localhost if not ipv6 and candidate_addr == '[::1]': continue candidates.append(candidate_addr) if attempt_connect: try: s = socket.socket(h[0], socket.SOCK_STREAM) s.settimeout(2) s.connect((candidate_addr.strip('[]'), h[4][1])) s.close() resolved = candidate_addr break except socket.error: pass if not resolved: if candidates: resolved = candidates[0] else: error = True except TypeError: err = ('Attempt to resolve address \'{0}\' failed. Invalid or unresolveable address').format(lookup) raise SaltSystemExit(code=42, msg=err) except socket.error: error = True if error: err = ('DNS lookup or connection check of \'{0}\' failed.').format(addr) if safe: if salt.log.is_console_configured(): # If logging is not configured it also means that either # the master or minion instance calling this hasn't even # started running log.error(err) raise SaltClientError() raise SaltSystemExit(code=42, msg=err) return resolved def parse_host_port(host_port): """ Takes a string argument specifying host or host:port. Returns a (hostname, port) or (ip_address, port) tuple. If no port is given, the second (port) element of the returned tuple will be None. host:port argument, for example, is accepted in the forms of: - hostname - hostname:1234 - hostname.domain.tld - hostname.domain.tld:5678 - [1234::5]:5678 - 1234::5 - 10.11.12.13:4567 - 10.11.12.13 """ host, port = None, None # default _s_ = host_port[:] if _s_[0] == "[": if "]" in host_port: host, _s_ = _s_.lstrip("[").rsplit("]", 1) host = ipaddress.IPv6Address(host).compressed if _s_[0] == ":": port = int(_s_.lstrip(":")) else: if len(_s_) > 1: raise ValueError('found ambiguous "{}" port in "{}"'.format(_s_, host_port)) else: if _s_.count(":") == 1: host, _hostport_separator_, port = _s_.partition(":") try: port = int(port) except ValueError as _e_: log.error('host_port "%s" port value "%s" is not an integer.', host_port, port) raise _e_ else: host = _s_ try: if not isinstance(host, ipaddress._BaseAddress): host_ip = ipaddress.ip_address(host).compressed host = host_ip except ValueError: log.debug('"%s" Not an IP address? Assuming it is a hostname.', host) if host != sanitize_host(host): log.error('bad hostname: "%s"', host) raise ValueError('bad hostname: "{}"'.format(host)) return host, port def is_fqdn(hostname): """ Verify if hostname conforms to be a FQDN. :param hostname: text string with the name of the host :return: bool, True if hostname is correct FQDN, False otherwise """ compliant = re.compile(r"(?!-)[A-Z\d\-\_]{1,63}(?<!-)$", re.IGNORECASE) return "." in hostname and len(hostname) < 0xff and all(compliant.match(x) for x in hostname.rstrip(".").split("."))
saltstack/salt
salt/utils/network.py
_linux_remotes_on
python
def _linux_remotes_on(port, which_end): ''' Linux specific helper function. Returns set of ip host addresses of remote established connections on local tcp port port. Parses output of shell 'lsof' to get connections $ sudo lsof -iTCP:4505 -n COMMAND PID USER FD TYPE DEVICE SIZE/OFF NODE NAME Python 9971 root 35u IPv4 0x18a8464a29ca329d 0t0 TCP *:4505 (LISTEN) Python 9971 root 37u IPv4 0x18a8464a29b2b29d 0t0 TCP 127.0.0.1:4505->127.0.0.1:55703 (ESTABLISHED) Python 10152 root 22u IPv4 0x18a8464a29c8cab5 0t0 TCP 127.0.0.1:55703->127.0.0.1:4505 (ESTABLISHED) Python 10153 root 22u IPv4 0x18a8464a29c8cab5 0t0 TCP [fe80::249a]:4505->[fe80::150]:59367 (ESTABLISHED) ''' remotes = set() try: data = subprocess.check_output( ['lsof', '-iTCP:{0:d}'.format(port), '-n', '-P'] # pylint: disable=minimum-python-version ) except subprocess.CalledProcessError as ex: if ex.returncode == 1: # Lsof return 1 if any error was detected, including the failure # to locate Internet addresses, and it is not an error in this case. log.warning('"lsof" returncode = 1, likely no active TCP sessions.') return remotes log.error('Failed "lsof" with returncode = %s', ex.returncode) raise lines = salt.utils.stringutils.to_str(data).split('\n') for line in lines: chunks = line.split() if not chunks: continue # ['Python', '9971', 'root', '37u', 'IPv4', '0x18a8464a29b2b29d', '0t0', # 'TCP', '127.0.0.1:4505->127.0.0.1:55703', '(ESTABLISHED)'] # print chunks if 'COMMAND' in chunks[0]: continue # ignore header if 'ESTABLISHED' not in chunks[-1]: continue # ignore if not ESTABLISHED # '127.0.0.1:4505->127.0.0.1:55703' local, remote = chunks[8].split('->') _, lport = local.rsplit(':', 1) rhost, rport = remote.rsplit(':', 1) if which_end == 'remote_port' and int(rport) != port: continue if which_end == 'local_port' and int(lport) != port: continue remotes.add(rhost.strip("[]")) return remotes
Linux specific helper function. Returns set of ip host addresses of remote established connections on local tcp port port. Parses output of shell 'lsof' to get connections $ sudo lsof -iTCP:4505 -n COMMAND PID USER FD TYPE DEVICE SIZE/OFF NODE NAME Python 9971 root 35u IPv4 0x18a8464a29ca329d 0t0 TCP *:4505 (LISTEN) Python 9971 root 37u IPv4 0x18a8464a29b2b29d 0t0 TCP 127.0.0.1:4505->127.0.0.1:55703 (ESTABLISHED) Python 10152 root 22u IPv4 0x18a8464a29c8cab5 0t0 TCP 127.0.0.1:55703->127.0.0.1:4505 (ESTABLISHED) Python 10153 root 22u IPv4 0x18a8464a29c8cab5 0t0 TCP [fe80::249a]:4505->[fe80::150]:59367 (ESTABLISHED)
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/network.py#L1739-L1793
null
# -*- coding: utf-8 -*- ''' Define some generic socket functions for network modules ''' # Import python libs from __future__ import absolute_import, unicode_literals, print_function import itertools import os import re import types import socket import logging import platform import random import subprocess from string import ascii_letters, digits # Import 3rd-party libs from salt.ext import six from salt.ext.six.moves import range # pylint: disable=import-error,redefined-builtin # Attempt to import wmi try: import wmi import salt.utils.winapi except ImportError: pass # Import salt libs import salt.utils.args import salt.utils.files import salt.utils.path import salt.utils.platform import salt.utils.stringutils import salt.utils.zeromq from salt._compat import ipaddress from salt.exceptions import SaltClientError, SaltSystemExit from salt.utils.decorators.jinja import jinja_filter from salt.utils.versions import LooseVersion # inet_pton does not exist in Windows, this is a workaround if salt.utils.platform.is_windows(): from salt.ext import win_inet_pton # pylint: disable=unused-import log = logging.getLogger(__name__) try: import ctypes import ctypes.util libc = ctypes.cdll.LoadLibrary(ctypes.util.find_library("c")) res_init = libc.__res_init except (ImportError, OSError, AttributeError, TypeError): pass # pylint: disable=C0103 def sanitize_host(host): ''' Sanitize host string. https://tools.ietf.org/html/rfc1123#section-2.1 ''' RFC952_characters = ascii_letters + digits + ".-" return "".join([c for c in host[0:255] if c in RFC952_characters]) def isportopen(host, port): ''' Return status of a port ''' if not 1 <= int(port) <= 65535: return False sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) out = sock.connect_ex((sanitize_host(host), int(port))) return out def host_to_ips(host): ''' Returns a list of IP addresses of a given hostname or None if not found. ''' ips = [] try: for family, socktype, proto, canonname, sockaddr in socket.getaddrinfo( host, 0, socket.AF_UNSPEC, socket.SOCK_STREAM): if family == socket.AF_INET: ip, port = sockaddr elif family == socket.AF_INET6: ip, port, flow_info, scope_id = sockaddr ips.append(ip) if not ips: ips = None except Exception: ips = None return ips def _generate_minion_id(): ''' Get list of possible host names and convention names. :return: ''' # There are three types of hostnames: # 1. Network names. How host is accessed from the network. # 2. Host aliases. They might be not available in all the network or only locally (/etc/hosts) # 3. Convention names, an internal nodename. class DistinctList(list): ''' List, which allows one to append only distinct objects. Needs to work on Python 2.6, because of collections.OrderedDict only since 2.7 version. Override 'filter()' for custom filtering. ''' localhost_matchers = [r'localhost.*', r'ip6-.*', r'127[.]\d', r'0\.0\.0\.0', r'::1.*', r'ipv6-.*', r'fe00::.*', r'fe02::.*', r'1.0.0.*.ip6.arpa'] def append(self, p_object): if p_object and p_object not in self and not self.filter(p_object): super(DistinctList, self).append(p_object) return self def extend(self, iterable): for obj in iterable: self.append(obj) return self def filter(self, element): 'Returns True if element needs to be filtered' for rgx in self.localhost_matchers: if re.match(rgx, element): return True def first(self): return self and self[0] or None hostname = socket.gethostname() hosts = DistinctList().append( salt.utils.stringutils.to_unicode(socket.getfqdn(salt.utils.stringutils.to_bytes(hostname))) ).append(platform.node()).append(hostname) if not hosts: try: for a_nfo in socket.getaddrinfo(hosts.first() or 'localhost', None, socket.AF_INET, socket.SOCK_RAW, socket.IPPROTO_IP, socket.AI_CANONNAME): if len(a_nfo) > 3: hosts.append(a_nfo[3]) except socket.gaierror: log.warning('Cannot resolve address %s info via socket: %s', hosts.first() or 'localhost (N/A)', socket.gaierror) # Universal method for everywhere (Linux, Slowlaris, Windows etc) for f_name in ('/etc/hostname', '/etc/nodename', '/etc/hosts', r'{win}\system32\drivers\etc\hosts'.format(win=os.getenv('WINDIR'))): try: with salt.utils.files.fopen(f_name) as f_hdl: for line in f_hdl: line = salt.utils.stringutils.to_unicode(line) hst = line.strip().split('#')[0].strip().split() if hst: if hst[0][:4] in ('127.', '::1') or len(hst) == 1: hosts.extend(hst) except IOError: pass # include public and private ipaddresses return hosts.extend([addr for addr in ip_addrs() if not ipaddress.ip_address(addr).is_loopback]) def generate_minion_id(): ''' Return only first element of the hostname from all possible list. :return: ''' try: ret = salt.utils.stringutils.to_unicode(_generate_minion_id().first()) except TypeError: ret = None return ret or 'localhost' def get_socket(addr, type=socket.SOCK_STREAM, proto=0): ''' Return a socket object for the addr IP-version agnostic ''' version = ipaddress.ip_address(addr).version if version == 4: family = socket.AF_INET elif version == 6: family = socket.AF_INET6 return socket.socket(family, type, proto) def get_fqhostname(): ''' Returns the fully qualified hostname ''' # try getaddrinfo() fqdn = None try: addrinfo = socket.getaddrinfo( socket.gethostname(), 0, socket.AF_UNSPEC, socket.SOCK_STREAM, socket.SOL_TCP, socket.AI_CANONNAME ) for info in addrinfo: # info struct [family, socktype, proto, canonname, sockaddr] # On Windows `canonname` can be an empty string # This can cause the function to return `None` if len(info) > 3 and info[3]: fqdn = info[3] break except socket.gaierror: pass # NOTE: this used to log.error() but it was later disabled except socket.error as err: log.debug('socket.getaddrinfo() failure while finding fqdn: %s', err) if fqdn is None: fqdn = socket.getfqdn() return fqdn def ip_to_host(ip): ''' Returns the hostname of a given IP ''' try: hostname, aliaslist, ipaddrlist = socket.gethostbyaddr(ip) except Exception as exc: log.debug('salt.utils.network.ip_to_host(%r) failed: %s', ip, exc) hostname = None return hostname # pylint: enable=C0103 def is_reachable_host(entity_name): ''' Returns a bool telling if the entity name is a reachable host (IPv4/IPv6/FQDN/etc). :param hostname: :return: ''' try: assert type(socket.getaddrinfo(entity_name, 0, 0, 0, 0)) == list ret = True except socket.gaierror: ret = False return ret def is_ip(ip): ''' Returns a bool telling if the passed IP is a valid IPv4 or IPv6 address. ''' return is_ipv4(ip) or is_ipv6(ip) def is_ipv4(ip): ''' Returns a bool telling if the value passed to it was a valid IPv4 address ''' try: return ipaddress.ip_address(ip).version == 4 except ValueError: return False def is_ipv6(ip): ''' Returns a bool telling if the value passed to it was a valid IPv6 address ''' try: return ipaddress.ip_address(ip).version == 6 except ValueError: return False def is_subnet(cidr): ''' Returns a bool telling if the passed string is an IPv4 or IPv6 subnet ''' return is_ipv4_subnet(cidr) or is_ipv6_subnet(cidr) def is_ipv4_subnet(cidr): ''' Returns a bool telling if the passed string is an IPv4 subnet ''' try: return '/' in cidr and bool(ipaddress.IPv4Network(cidr)) except Exception: return False def is_ipv6_subnet(cidr): ''' Returns a bool telling if the passed string is an IPv6 subnet ''' try: return '/' in cidr and bool(ipaddress.IPv6Network(cidr)) except Exception: return False @jinja_filter('is_ip') def is_ip_filter(ip, options=None): ''' Returns a bool telling if the passed IP is a valid IPv4 or IPv6 address. ''' return is_ipv4_filter(ip, options=options) or is_ipv6_filter(ip, options=options) def _ip_options_global(ip_obj, version): return not ip_obj.is_private def _ip_options_multicast(ip_obj, version): return ip_obj.is_multicast def _ip_options_loopback(ip_obj, version): return ip_obj.is_loopback def _ip_options_link_local(ip_obj, version): return ip_obj.is_link_local def _ip_options_private(ip_obj, version): return ip_obj.is_private def _ip_options_reserved(ip_obj, version): return ip_obj.is_reserved def _ip_options_site_local(ip_obj, version): if version == 6: return ip_obj.is_site_local return False def _ip_options_unspecified(ip_obj, version): return ip_obj.is_unspecified def _ip_options(ip_obj, version, options=None): # will process and IP options options_fun_map = { 'global': _ip_options_global, 'link-local': _ip_options_link_local, 'linklocal': _ip_options_link_local, 'll': _ip_options_link_local, 'link_local': _ip_options_link_local, 'loopback': _ip_options_loopback, 'lo': _ip_options_loopback, 'multicast': _ip_options_multicast, 'private': _ip_options_private, 'public': _ip_options_global, 'reserved': _ip_options_reserved, 'site-local': _ip_options_site_local, 'sl': _ip_options_site_local, 'site_local': _ip_options_site_local, 'unspecified': _ip_options_unspecified } if not options: return six.text_type(ip_obj) # IP version already checked options_list = [option.strip() for option in options.split(',')] for option, fun in options_fun_map.items(): if option in options_list: fun_res = fun(ip_obj, version) if not fun_res: return None # stop at first failed test # else continue return six.text_type(ip_obj) def _is_ipv(ip, version, options=None): if not version: version = 4 if version not in (4, 6): return None try: ip_obj = ipaddress.ip_address(ip) except ValueError: # maybe it is an IP network try: ip_obj = ipaddress.ip_interface(ip) except ValueError: # nope, still not :( return None if not ip_obj.version == version: return None # has the right version, let's move on return _ip_options(ip_obj, version, options=options) @jinja_filter('is_ipv4') def is_ipv4_filter(ip, options=None): ''' Returns a bool telling if the value passed to it was a valid IPv4 address. ip The IP address. net: False Consider IP addresses followed by netmask. options CSV of options regarding the nature of the IP address. E.g.: loopback, multicast, private etc. ''' _is_ipv4 = _is_ipv(ip, 4, options=options) return isinstance(_is_ipv4, six.string_types) @jinja_filter('is_ipv6') def is_ipv6_filter(ip, options=None): ''' Returns a bool telling if the value passed to it was a valid IPv6 address. ip The IP address. net: False Consider IP addresses followed by netmask. options CSV of options regarding the nature of the IP address. E.g.: loopback, multicast, private etc. ''' _is_ipv6 = _is_ipv(ip, 6, options=options) return isinstance(_is_ipv6, six.string_types) def _ipv_filter(value, version, options=None): if version not in (4, 6): return if isinstance(value, (six.string_types, six.text_type, six.binary_type)): return _is_ipv(value, version, options=options) # calls is_ipv4 or is_ipv6 for `value` elif isinstance(value, (list, tuple, types.GeneratorType)): # calls is_ipv4 or is_ipv6 for each element in the list # os it filters and returns only those elements having the desired IP version return [ _is_ipv(addr, version, options=options) for addr in value if _is_ipv(addr, version, options=options) is not None ] return None @jinja_filter('ipv4') def ipv4(value, options=None): ''' Filters a list and returns IPv4 values only. ''' return _ipv_filter(value, 4, options=options) @jinja_filter('ipv6') def ipv6(value, options=None): ''' Filters a list and returns IPv6 values only. ''' return _ipv_filter(value, 6, options=options) @jinja_filter('ipaddr') def ipaddr(value, options=None): ''' Filters and returns only valid IP objects. ''' ipv4_obj = ipv4(value, options=options) ipv6_obj = ipv6(value, options=options) if ipv4_obj is None or ipv6_obj is None: # an IP address can be either IPv4 either IPv6 # therefofe if the value passed as arg is not a list, at least one of the calls above will return None # if one of them is none, means that we should return only one of them return ipv4_obj or ipv6_obj # one of them else: return ipv4_obj + ipv6_obj # extend lists def _filter_ipaddr(value, options, version=None): ipaddr_filter_out = None if version: if version == 4: ipaddr_filter_out = ipv4(value, options) elif version == 6: ipaddr_filter_out = ipv6(value, options) else: ipaddr_filter_out = ipaddr(value, options) if not ipaddr_filter_out: return if not isinstance(ipaddr_filter_out, (list, tuple, types.GeneratorType)): ipaddr_filter_out = [ipaddr_filter_out] return ipaddr_filter_out @jinja_filter('ip_host') def ip_host(value, options=None, version=None): ''' Returns the interfaces IP address, e.g.: 192.168.0.1/28. ''' ipaddr_filter_out = _filter_ipaddr(value, options=options, version=version) if not ipaddr_filter_out: return if not isinstance(value, (list, tuple, types.GeneratorType)): return six.text_type(ipaddress.ip_interface(ipaddr_filter_out[0])) return [six.text_type(ipaddress.ip_interface(ip_a)) for ip_a in ipaddr_filter_out] def _network_hosts(ip_addr_entry): return [ six.text_type(host) for host in ipaddress.ip_network(ip_addr_entry, strict=False).hosts() ] @jinja_filter('network_hosts') def network_hosts(value, options=None, version=None): ''' Return the list of hosts within a network. .. note:: When running this command with a large IPv6 network, the command will take a long time to gather all of the hosts. ''' ipaddr_filter_out = _filter_ipaddr(value, options=options, version=version) if not ipaddr_filter_out: return if not isinstance(value, (list, tuple, types.GeneratorType)): return _network_hosts(ipaddr_filter_out[0]) return [ _network_hosts(ip_a) for ip_a in ipaddr_filter_out ] def _network_size(ip_addr_entry): return ipaddress.ip_network(ip_addr_entry, strict=False).num_addresses @jinja_filter('network_size') def network_size(value, options=None, version=None): ''' Get the size of a network. ''' ipaddr_filter_out = _filter_ipaddr(value, options=options, version=version) if not ipaddr_filter_out: return if not isinstance(value, (list, tuple, types.GeneratorType)): return _network_size(ipaddr_filter_out[0]) return [ _network_size(ip_a) for ip_a in ipaddr_filter_out ] def natural_ipv4_netmask(ip, fmt='prefixlen'): ''' Returns the "natural" mask of an IPv4 address ''' bits = _ipv4_to_bits(ip) if bits.startswith('11'): mask = '24' elif bits.startswith('1'): mask = '16' else: mask = '8' if fmt == 'netmask': return cidr_to_ipv4_netmask(mask) else: return '/' + mask def rpad_ipv4_network(ip): ''' Returns an IP network address padded with zeros. Ex: '192.168.3' -> '192.168.3.0' '10.209' -> '10.209.0.0' ''' return '.'.join(itertools.islice(itertools.chain(ip.split('.'), '0000'), 0, 4)) def cidr_to_ipv4_netmask(cidr_bits): ''' Returns an IPv4 netmask ''' try: cidr_bits = int(cidr_bits) if not 1 <= cidr_bits <= 32: return '' except ValueError: return '' netmask = '' for idx in range(4): if idx: netmask += '.' if cidr_bits >= 8: netmask += '255' cidr_bits -= 8 else: netmask += '{0:d}'.format(256 - (2 ** (8 - cidr_bits))) cidr_bits = 0 return netmask def _number_of_set_bits_to_ipv4_netmask(set_bits): # pylint: disable=C0103 ''' Returns an IPv4 netmask from the integer representation of that mask. Ex. 0xffffff00 -> '255.255.255.0' ''' return cidr_to_ipv4_netmask(_number_of_set_bits(set_bits)) # pylint: disable=C0103 def _number_of_set_bits(x): ''' Returns the number of bits that are set in a 32bit int ''' # Taken from http://stackoverflow.com/a/4912729. Many thanks! x -= (x >> 1) & 0x55555555 x = ((x >> 2) & 0x33333333) + (x & 0x33333333) x = ((x >> 4) + x) & 0x0f0f0f0f x += x >> 8 x += x >> 16 return x & 0x0000003f # pylint: enable=C0103 def _interfaces_ip(out): ''' Uses ip to return a dictionary of interfaces with various information about each (up/down state, ip address, netmask, and hwaddr) ''' ret = dict() def parse_network(value, cols): ''' Return a tuple of ip, netmask, broadcast based on the current set of cols ''' brd = None scope = None if '/' in value: # we have a CIDR in this address ip, cidr = value.split('/') # pylint: disable=C0103 else: ip = value # pylint: disable=C0103 cidr = 32 if type_ == 'inet': mask = cidr_to_ipv4_netmask(int(cidr)) if 'brd' in cols: brd = cols[cols.index('brd') + 1] elif type_ == 'inet6': mask = cidr if 'scope' in cols: scope = cols[cols.index('scope') + 1] return (ip, mask, brd, scope) groups = re.compile('\r?\n\\d').split(out) for group in groups: iface = None data = dict() for line in group.splitlines(): if ' ' not in line: continue match = re.match(r'^\d*:\s+([\w.\-]+)(?:@)?([\w.\-]+)?:\s+<(.+)>', line) if match: iface, parent, attrs = match.groups() if 'UP' in attrs.split(','): data['up'] = True else: data['up'] = False if parent: data['parent'] = parent continue cols = line.split() if len(cols) >= 2: type_, value = tuple(cols[0:2]) iflabel = cols[-1:][0] if type_ in ('inet', 'inet6'): if 'secondary' not in cols: ipaddr, netmask, broadcast, scope = parse_network(value, cols) if type_ == 'inet': if 'inet' not in data: data['inet'] = list() addr_obj = dict() addr_obj['address'] = ipaddr addr_obj['netmask'] = netmask addr_obj['broadcast'] = broadcast addr_obj['label'] = iflabel data['inet'].append(addr_obj) elif type_ == 'inet6': if 'inet6' not in data: data['inet6'] = list() addr_obj = dict() addr_obj['address'] = ipaddr addr_obj['prefixlen'] = netmask addr_obj['scope'] = scope data['inet6'].append(addr_obj) else: if 'secondary' not in data: data['secondary'] = list() ip_, mask, brd, scp = parse_network(value, cols) data['secondary'].append({ 'type': type_, 'address': ip_, 'netmask': mask, 'broadcast': brd, 'label': iflabel, }) del ip_, mask, brd, scp elif type_.startswith('link'): data['hwaddr'] = value if iface: ret[iface] = data del iface, data return ret def _interfaces_ifconfig(out): ''' Uses ifconfig to return a dictionary of interfaces with various information about each (up/down state, ip address, netmask, and hwaddr) ''' ret = dict() piface = re.compile(r'^([^\s:]+)') pmac = re.compile('.*?(?:HWaddr|ether|address:|lladdr) ([0-9a-fA-F:]+)') if salt.utils.platform.is_sunos(): pip = re.compile(r'.*?(?:inet\s+)([0-9]+\.[0-9]+\.[0-9]+\.[0-9]+)(.*)') pip6 = re.compile('.*?(?:inet6 )([0-9a-fA-F:]+)') pmask6 = re.compile(r'.*?(?:inet6 [0-9a-fA-F:]+/(\d+)).*') else: pip = re.compile(r'.*?(?:inet addr:|inet [^\d]*)(.*?)\s') pip6 = re.compile('.*?(?:inet6 addr: (.*?)/|inet6 )([0-9a-fA-F:]+)') pmask6 = re.compile(r'.*?(?:inet6 addr: [0-9a-fA-F:]+/(\d+)|prefixlen (\d+))(?: Scope:([a-zA-Z]+)| scopeid (0x[0-9a-fA-F]))?') pmask = re.compile(r'.*?(?:Mask:|netmask )(?:((?:0x)?[0-9a-fA-F]{8})|([\d\.]+))') pupdown = re.compile('UP') pbcast = re.compile(r'.*?(?:Bcast:|broadcast )([\d\.]+)') groups = re.compile('\r?\n(?=\\S)').split(out) for group in groups: data = dict() iface = '' updown = False for line in group.splitlines(): miface = piface.match(line) mmac = pmac.match(line) mip = pip.match(line) mip6 = pip6.match(line) mupdown = pupdown.search(line) if miface: iface = miface.group(1) if mmac: data['hwaddr'] = mmac.group(1) if salt.utils.platform.is_sunos(): expand_mac = [] for chunk in data['hwaddr'].split(':'): expand_mac.append('0{0}'.format(chunk) if len(chunk) < 2 else '{0}'.format(chunk)) data['hwaddr'] = ':'.join(expand_mac) if mip: if 'inet' not in data: data['inet'] = list() addr_obj = dict() addr_obj['address'] = mip.group(1) mmask = pmask.match(line) if mmask: if mmask.group(1): mmask = _number_of_set_bits_to_ipv4_netmask( int(mmask.group(1), 16)) else: mmask = mmask.group(2) addr_obj['netmask'] = mmask mbcast = pbcast.match(line) if mbcast: addr_obj['broadcast'] = mbcast.group(1) data['inet'].append(addr_obj) if mupdown: updown = True if mip6: if 'inet6' not in data: data['inet6'] = list() addr_obj = dict() addr_obj['address'] = mip6.group(1) or mip6.group(2) mmask6 = pmask6.match(line) if mmask6: addr_obj['prefixlen'] = mmask6.group(1) or mmask6.group(2) if not salt.utils.platform.is_sunos(): ipv6scope = mmask6.group(3) or mmask6.group(4) addr_obj['scope'] = ipv6scope.lower() if ipv6scope is not None else ipv6scope # SunOS sometimes has ::/0 as inet6 addr when using addrconf if not salt.utils.platform.is_sunos() \ or addr_obj['address'] != '::' \ and addr_obj['prefixlen'] != 0: data['inet6'].append(addr_obj) data['up'] = updown if iface in ret: # SunOS optimization, where interfaces occur twice in 'ifconfig -a' # output with the same name: for ipv4 and then for ipv6 addr family. # Every instance has it's own 'UP' status and we assume that ipv4 # status determines global interface status. # # merge items with higher priority for older values # after that merge the inet and inet6 sub items for both ret[iface] = dict(list(data.items()) + list(ret[iface].items())) if 'inet' in data: ret[iface]['inet'].extend(x for x in data['inet'] if x not in ret[iface]['inet']) if 'inet6' in data: ret[iface]['inet6'].extend(x for x in data['inet6'] if x not in ret[iface]['inet6']) else: ret[iface] = data del data return ret def linux_interfaces(): ''' Obtain interface information for *NIX/BSD variants ''' ifaces = dict() ip_path = salt.utils.path.which('ip') ifconfig_path = None if ip_path else salt.utils.path.which('ifconfig') if ip_path: cmd1 = subprocess.Popen( '{0} link show'.format(ip_path), shell=True, close_fds=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT).communicate()[0] cmd2 = subprocess.Popen( '{0} addr show'.format(ip_path), shell=True, close_fds=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT).communicate()[0] ifaces = _interfaces_ip("{0}\n{1}".format( salt.utils.stringutils.to_str(cmd1), salt.utils.stringutils.to_str(cmd2))) elif ifconfig_path: cmd = subprocess.Popen( '{0} -a'.format(ifconfig_path), shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT).communicate()[0] ifaces = _interfaces_ifconfig(salt.utils.stringutils.to_str(cmd)) return ifaces def _netbsd_interfaces_ifconfig(out): ''' Uses ifconfig to return a dictionary of interfaces with various information about each (up/down state, ip address, netmask, and hwaddr) ''' ret = dict() piface = re.compile(r'^([^\s:]+)') pmac = re.compile('.*?address: ([0-9a-f:]+)') pip = re.compile(r'.*?inet [^\d]*(.*?)/([\d]*)\s') pip6 = re.compile(r'.*?inet6 ([0-9a-f:]+)%([a-zA-Z0-9]*)/([\d]*)\s') pupdown = re.compile('UP') pbcast = re.compile(r'.*?broadcast ([\d\.]+)') groups = re.compile('\r?\n(?=\\S)').split(out) for group in groups: data = dict() iface = '' updown = False for line in group.splitlines(): miface = piface.match(line) mmac = pmac.match(line) mip = pip.match(line) mip6 = pip6.match(line) mupdown = pupdown.search(line) if miface: iface = miface.group(1) if mmac: data['hwaddr'] = mmac.group(1) if mip: if 'inet' not in data: data['inet'] = list() addr_obj = dict() addr_obj['address'] = mip.group(1) mmask = mip.group(2) if mip.group(2): addr_obj['netmask'] = cidr_to_ipv4_netmask(mip.group(2)) mbcast = pbcast.match(line) if mbcast: addr_obj['broadcast'] = mbcast.group(1) data['inet'].append(addr_obj) if mupdown: updown = True if mip6: if 'inet6' not in data: data['inet6'] = list() addr_obj = dict() addr_obj['address'] = mip6.group(1) mmask6 = mip6.group(3) addr_obj['scope'] = mip6.group(2) addr_obj['prefixlen'] = mip6.group(3) data['inet6'].append(addr_obj) data['up'] = updown ret[iface] = data del data return ret def netbsd_interfaces(): ''' Obtain interface information for NetBSD >= 8 where the ifconfig output diverged from other BSD variants (Netmask is now part of the address) ''' # NetBSD versions prior to 8.0 can still use linux_interfaces() if LooseVersion(os.uname()[2]) < LooseVersion('8.0'): return linux_interfaces() ifconfig_path = salt.utils.path.which('ifconfig') cmd = subprocess.Popen( '{0} -a'.format(ifconfig_path), shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT).communicate()[0] return _netbsd_interfaces_ifconfig(salt.utils.stringutils.to_str(cmd)) def _interfaces_ipconfig(out): ''' Returns a dictionary of interfaces with various information about each (up/down state, ip address, netmask, and hwaddr) NOTE: This is not used by any function and may be able to be removed in the future. ''' ifaces = dict() iface = None adapter_iface_regex = re.compile(r'adapter (\S.+):$') for line in out.splitlines(): if not line: continue # TODO what does Windows call Infiniband and 10/40gige adapters if line.startswith('Ethernet'): iface = ifaces[adapter_iface_regex.search(line).group(1)] iface['up'] = True addr = None continue if iface: key, val = line.split(',', 1) key = key.strip(' .') val = val.strip() if addr and key == 'Subnet Mask': addr['netmask'] = val elif key in ('IP Address', 'IPv4 Address'): if 'inet' not in iface: iface['inet'] = list() addr = {'address': val.rstrip('(Preferred)'), 'netmask': None, 'broadcast': None} # TODO find the broadcast iface['inet'].append(addr) elif 'IPv6 Address' in key: if 'inet6' not in iface: iface['inet'] = list() # XXX What is the prefixlen!? addr = {'address': val.rstrip('(Preferred)'), 'prefixlen': None} iface['inet6'].append(addr) elif key == 'Physical Address': iface['hwaddr'] = val elif key == 'Media State': # XXX seen used for tunnel adaptors # might be useful iface['up'] = (val != 'Media disconnected') def win_interfaces(): ''' Obtain interface information for Windows systems ''' with salt.utils.winapi.Com(): c = wmi.WMI() ifaces = {} for iface in c.Win32_NetworkAdapterConfiguration(IPEnabled=1): ifaces[iface.Description] = dict() if iface.MACAddress: ifaces[iface.Description]['hwaddr'] = iface.MACAddress if iface.IPEnabled: ifaces[iface.Description]['up'] = True for ip in iface.IPAddress: if '.' in ip: if 'inet' not in ifaces[iface.Description]: ifaces[iface.Description]['inet'] = [] item = {'address': ip, 'label': iface.Description} if iface.DefaultIPGateway: broadcast = next((i for i in iface.DefaultIPGateway if '.' in i), '') if broadcast: item['broadcast'] = broadcast if iface.IPSubnet: netmask = next((i for i in iface.IPSubnet if '.' in i), '') if netmask: item['netmask'] = netmask ifaces[iface.Description]['inet'].append(item) if ':' in ip: if 'inet6' not in ifaces[iface.Description]: ifaces[iface.Description]['inet6'] = [] item = {'address': ip} if iface.DefaultIPGateway: broadcast = next((i for i in iface.DefaultIPGateway if ':' in i), '') if broadcast: item['broadcast'] = broadcast if iface.IPSubnet: netmask = next((i for i in iface.IPSubnet if ':' in i), '') if netmask: item['netmask'] = netmask ifaces[iface.Description]['inet6'].append(item) else: ifaces[iface.Description]['up'] = False return ifaces def interfaces(): ''' Return a dictionary of information about all the interfaces on the minion ''' if salt.utils.platform.is_windows(): return win_interfaces() elif salt.utils.platform.is_netbsd(): return netbsd_interfaces() else: return linux_interfaces() def get_net_start(ipaddr, netmask): ''' Return the address of the network ''' net = ipaddress.ip_network('{0}/{1}'.format(ipaddr, netmask), strict=False) return six.text_type(net.network_address) def get_net_size(mask): ''' Turns an IPv4 netmask into it's corresponding prefix length (255.255.255.0 -> 24 as in 192.168.1.10/24). ''' binary_str = '' for octet in mask.split('.'): binary_str += bin(int(octet))[2:].zfill(8) return len(binary_str.rstrip('0')) def calc_net(ipaddr, netmask=None): ''' Takes IP (CIDR notation supported) and optionally netmask and returns the network in CIDR-notation. (The IP can be any IP inside the subnet) ''' if netmask is not None: ipaddr = '{0}/{1}'.format(ipaddr, netmask) return six.text_type(ipaddress.ip_network(ipaddr, strict=False)) def _ipv4_to_bits(ipaddr): ''' Accepts an IPv4 dotted quad and returns a string representing its binary counterpart ''' return ''.join([bin(int(x))[2:].rjust(8, '0') for x in ipaddr.split('.')]) def _get_iface_info(iface): ''' If `iface` is available, return interface info and no error, otherwise return no info and log and return an error ''' iface_info = interfaces() if iface in iface_info.keys(): return iface_info, False else: error_msg = ('Interface "{0}" not in available interfaces: "{1}"' ''.format(iface, '", "'.join(iface_info.keys()))) log.error(error_msg) return None, error_msg def _hw_addr_aix(iface): ''' Return the hardware address (a.k.a. MAC address) for a given interface on AIX MAC address not available in through interfaces ''' cmd = subprocess.Popen( 'entstat -d {0} | grep \'Hardware Address\''.format(iface), shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT).communicate()[0] if cmd: comps = cmd.split(' ') if len(comps) == 3: mac_addr = comps[2].strip('\'').strip() return mac_addr error_msg = ('Interface "{0}" either not available or does not contain a hardware address'.format(iface)) log.error(error_msg) return error_msg def hw_addr(iface): ''' Return the hardware address (a.k.a. MAC address) for a given interface .. versionchanged:: 2016.11.4 Added support for AIX ''' if salt.utils.platform.is_aix(): return _hw_addr_aix iface_info, error = _get_iface_info(iface) if error is False: return iface_info.get(iface, {}).get('hwaddr', '') else: return error def interface(iface): ''' Return the details of `iface` or an error if it does not exist ''' iface_info, error = _get_iface_info(iface) if error is False: return iface_info.get(iface, {}).get('inet', '') else: return error def interface_ip(iface): ''' Return `iface` IPv4 addr or an error if `iface` does not exist ''' iface_info, error = _get_iface_info(iface) if error is False: inet = iface_info.get(iface, {}).get('inet', None) return inet[0].get('address', '') if inet else '' else: return error def _subnets(proto='inet', interfaces_=None): ''' Returns a list of subnets to which the host belongs ''' if interfaces_ is None: ifaces = interfaces() elif isinstance(interfaces_, list): ifaces = {} for key, value in six.iteritems(interfaces()): if key in interfaces_: ifaces[key] = value else: ifaces = {interfaces_: interfaces().get(interfaces_, {})} ret = set() if proto == 'inet': subnet = 'netmask' dflt_cidr = 32 elif proto == 'inet6': subnet = 'prefixlen' dflt_cidr = 128 else: log.error('Invalid proto %s calling subnets()', proto) return for ip_info in six.itervalues(ifaces): addrs = ip_info.get(proto, []) addrs.extend([addr for addr in ip_info.get('secondary', []) if addr.get('type') == proto]) for intf in addrs: if subnet in intf: intf = ipaddress.ip_interface('{0}/{1}'.format(intf['address'], intf[subnet])) else: intf = ipaddress.ip_interface('{0}/{1}'.format(intf['address'], dflt_cidr)) if not intf.is_loopback: ret.add(intf.network) return [six.text_type(net) for net in sorted(ret)] def subnets(interfaces=None): ''' Returns a list of IPv4 subnets to which the host belongs ''' return _subnets('inet', interfaces_=interfaces) def subnets6(): ''' Returns a list of IPv6 subnets to which the host belongs ''' return _subnets('inet6') def in_subnet(cidr, addr=None): ''' Returns True if host or (any of) addrs is within specified subnet, otherwise False ''' try: cidr = ipaddress.ip_network(cidr) except ValueError: log.error('Invalid CIDR \'%s\'', cidr) return False if addr is None: addr = ip_addrs() addr.extend(ip_addrs6()) elif not isinstance(addr, (list, tuple)): addr = (addr,) return any(ipaddress.ip_address(item) in cidr for item in addr) def _ip_addrs(interface=None, include_loopback=False, interface_data=None, proto='inet'): ''' Return the full list of IP adresses matching the criteria proto = inet|inet6 ''' ret = set() ifaces = interface_data \ if isinstance(interface_data, dict) \ else interfaces() if interface is None: target_ifaces = ifaces else: target_ifaces = dict([(k, v) for k, v in six.iteritems(ifaces) if k == interface]) if not target_ifaces: log.error('Interface %s not found.', interface) for ip_info in six.itervalues(target_ifaces): addrs = ip_info.get(proto, []) addrs.extend([addr for addr in ip_info.get('secondary', []) if addr.get('type') == proto]) for addr in addrs: addr = ipaddress.ip_address(addr.get('address')) if not addr.is_loopback or include_loopback: ret.add(addr) return [six.text_type(addr) for addr in sorted(ret)] def ip_addrs(interface=None, include_loopback=False, interface_data=None): ''' Returns a list of IPv4 addresses assigned to the host. 127.0.0.1 is ignored, unless 'include_loopback=True' is indicated. If 'interface' is provided, then only IP addresses from that interface will be returned. ''' return _ip_addrs(interface, include_loopback, interface_data, 'inet') def ip_addrs6(interface=None, include_loopback=False, interface_data=None): ''' Returns a list of IPv6 addresses assigned to the host. ::1 is ignored, unless 'include_loopback=True' is indicated. If 'interface' is provided, then only IP addresses from that interface will be returned. ''' return _ip_addrs(interface, include_loopback, interface_data, 'inet6') def hex2ip(hex_ip, invert=False): ''' Convert a hex string to an ip, if a failure occurs the original hex is returned. If 'invert=True' assume that ip from /proc/net/<proto> ''' if len(hex_ip) == 32: # ipv6 ip = [] for i in range(0, 32, 8): ip_part = hex_ip[i:i + 8] ip_part = [ip_part[x:x + 2] for x in range(0, 8, 2)] if invert: ip.append("{0[3]}{0[2]}:{0[1]}{0[0]}".format(ip_part)) else: ip.append("{0[0]}{0[1]}:{0[2]}{0[3]}".format(ip_part)) try: address = ipaddress.IPv6Address(":".join(ip)) if address.ipv4_mapped: return str(address.ipv4_mapped) else: return address.compressed except ipaddress.AddressValueError as ex: log.error('hex2ip - ipv6 address error: %s', ex) return hex_ip try: hip = int(hex_ip, 16) except ValueError: return hex_ip if invert: return '{3}.{2}.{1}.{0}'.format(hip >> 24 & 255, hip >> 16 & 255, hip >> 8 & 255, hip & 255) return '{0}.{1}.{2}.{3}'.format(hip >> 24 & 255, hip >> 16 & 255, hip >> 8 & 255, hip & 255) def mac2eui64(mac, prefix=None): ''' Convert a MAC address to a EUI64 identifier or, with prefix provided, a full IPv6 address ''' # http://tools.ietf.org/html/rfc4291#section-2.5.1 eui64 = re.sub(r'[.:-]', '', mac).lower() eui64 = eui64[0:6] + 'fffe' + eui64[6:] eui64 = hex(int(eui64[0:2], 16) | 2)[2:].zfill(2) + eui64[2:] if prefix is None: return ':'.join(re.findall(r'.{4}', eui64)) else: try: net = ipaddress.ip_network(prefix, strict=False) euil = int('0x{0}'.format(eui64), 16) return '{0}/{1}'.format(net[euil], net.prefixlen) except Exception: return def active_tcp(): ''' Return a dict describing all active tcp connections as quickly as possible ''' ret = {} for statf in ['/proc/net/tcp', '/proc/net/tcp6']: if os.path.isfile(statf): with salt.utils.files.fopen(statf, 'rb') as fp_: for line in fp_: line = salt.utils.stringutils.to_unicode(line) if line.strip().startswith('sl'): continue iret = _parse_tcp_line(line) sl = next(iter(iret)) if iret[sl]['state'] == 1: # 1 is ESTABLISHED del iret[sl]['state'] ret[len(ret)] = iret[sl] return ret def local_port_tcp(port): ''' Return a set of remote ip addrs attached to the specified local port ''' ret = _remotes_on(port, 'local_port') return ret def remote_port_tcp(port): ''' Return a set of ip addrs the current host is connected to on given port ''' ret = _remotes_on(port, 'remote_port') return ret def _remotes_on(port, which_end): ''' Return a set of ip addrs active tcp connections ''' port = int(port) ret = _netlink_tool_remote_on(port, which_end) if ret is not None: return ret ret = set() proc_available = False for statf in ['/proc/net/tcp', '/proc/net/tcp6']: if os.path.isfile(statf): proc_available = True with salt.utils.files.fopen(statf, 'r') as fp_: for line in fp_: line = salt.utils.stringutils.to_unicode(line) if line.strip().startswith('sl'): continue iret = _parse_tcp_line(line) sl = next(iter(iret)) if iret[sl][which_end] == port and iret[sl]['state'] == 1: # 1 is ESTABLISHED ret.add(iret[sl]['remote_addr']) if not proc_available: # Fallback to use OS specific tools if salt.utils.platform.is_sunos(): return _sunos_remotes_on(port, which_end) if salt.utils.platform.is_freebsd(): return _freebsd_remotes_on(port, which_end) if salt.utils.platform.is_netbsd(): return _netbsd_remotes_on(port, which_end) if salt.utils.platform.is_openbsd(): return _openbsd_remotes_on(port, which_end) if salt.utils.platform.is_windows(): return _windows_remotes_on(port, which_end) if salt.utils.platform.is_aix(): return _aix_remotes_on(port, which_end) return _linux_remotes_on(port, which_end) return ret def _parse_tcp_line(line): ''' Parse a single line from the contents of /proc/net/tcp or /proc/net/tcp6 ''' ret = {} comps = line.strip().split() sl = comps[0].rstrip(':') ret[sl] = {} l_addr, l_port = comps[1].split(':') r_addr, r_port = comps[2].split(':') ret[sl]['local_addr'] = hex2ip(l_addr, True) ret[sl]['local_port'] = int(l_port, 16) ret[sl]['remote_addr'] = hex2ip(r_addr, True) ret[sl]['remote_port'] = int(r_port, 16) ret[sl]['state'] = int(comps[3], 16) return ret def _netlink_tool_remote_on(port, which_end): ''' Returns set of ipv4 host addresses of remote established connections on local or remote tcp port. Parses output of shell 'ss' to get connections [root@salt-master ~]# ss -ant State Recv-Q Send-Q Local Address:Port Peer Address:Port LISTEN 0 511 *:80 *:* LISTEN 0 128 *:22 *:* ESTAB 0 0 127.0.0.1:56726 127.0.0.1:4505 ''' remotes = set() valid = False try: data = subprocess.check_output(['ss', '-ant']) # pylint: disable=minimum-python-version except subprocess.CalledProcessError: log.error('Failed ss') raise except OSError: # not command "No such file or directory" return None lines = salt.utils.stringutils.to_str(data).split('\n') for line in lines: if 'Address:Port' in line: # ss tools may not be valid valid = True continue elif 'ESTAB' not in line: continue chunks = line.split() local_host, local_port = chunks[3].split(':', 1) remote_host, remote_port = chunks[4].split(':', 1) if which_end == 'remote_port' and int(remote_port) != port: continue if which_end == 'local_port' and int(local_port) != port: continue remotes.add(remote_host) if valid is False: remotes = None return remotes def _sunos_remotes_on(port, which_end): ''' SunOS specific helper function. Returns set of ipv4 host addresses of remote established connections on local or remote tcp port. Parses output of shell 'netstat' to get connections [root@salt-master ~]# netstat -f inet -n TCP: IPv4 Local Address Remote Address Swind Send-Q Rwind Recv-Q State -------------------- -------------------- ----- ------ ----- ------ ----------- 10.0.0.101.4505 10.0.0.1.45329 1064800 0 1055864 0 ESTABLISHED 10.0.0.101.4505 10.0.0.100.50798 1064800 0 1055864 0 ESTABLISHED ''' remotes = set() try: data = subprocess.check_output(['netstat', '-f', 'inet', '-n']) # pylint: disable=minimum-python-version except subprocess.CalledProcessError: log.error('Failed netstat') raise lines = salt.utils.stringutils.to_str(data).split('\n') for line in lines: if 'ESTABLISHED' not in line: continue chunks = line.split() local_host, local_port = chunks[0].rsplit('.', 1) remote_host, remote_port = chunks[1].rsplit('.', 1) if which_end == 'remote_port' and int(remote_port) != port: continue if which_end == 'local_port' and int(local_port) != port: continue remotes.add(remote_host) return remotes def _freebsd_remotes_on(port, which_end): ''' Returns set of ipv4 host addresses of remote established connections on local tcp port port. Parses output of shell 'sockstat' (FreeBSD) to get connections $ sudo sockstat -4 USER COMMAND PID FD PROTO LOCAL ADDRESS FOREIGN ADDRESS root python2.7 1456 29 tcp4 *:4505 *:* root python2.7 1445 17 tcp4 *:4506 *:* root python2.7 1294 14 tcp4 127.0.0.1:11813 127.0.0.1:4505 root python2.7 1294 41 tcp4 127.0.0.1:61115 127.0.0.1:4506 $ sudo sockstat -4 -c -p 4506 USER COMMAND PID FD PROTO LOCAL ADDRESS FOREIGN ADDRESS root python2.7 1294 41 tcp4 127.0.0.1:61115 127.0.0.1:4506 ''' port = int(port) remotes = set() try: cmd = salt.utils.args.shlex_split('sockstat -4 -c -p {0}'.format(port)) data = subprocess.check_output(cmd) # pylint: disable=minimum-python-version except subprocess.CalledProcessError as ex: log.error('Failed "sockstat" with returncode = %s', ex.returncode) raise lines = salt.utils.stringutils.to_str(data).split('\n') for line in lines: chunks = line.split() if not chunks: continue # ['root', 'python2.7', '1456', '37', 'tcp4', # '127.0.0.1:4505-', '127.0.0.1:55703'] # print chunks if 'COMMAND' in chunks[1]: continue # ignore header if len(chunks) < 2: continue # sockstat -4 -c -p 4506 does this with high PIDs: # USER COMMAND PID FD PROTO LOCAL ADDRESS FOREIGN ADDRESS # salt-master python2.781106 35 tcp4 192.168.12.34:4506 192.168.12.45:60143 local = chunks[-2] remote = chunks[-1] lhost, lport = local.split(':') rhost, rport = remote.split(':') if which_end == 'local' and int(lport) != port: # ignore if local port not port continue if which_end == 'remote' and int(rport) != port: # ignore if remote port not port continue remotes.add(rhost) return remotes def _netbsd_remotes_on(port, which_end): ''' Returns set of ipv4 host addresses of remote established connections on local tcp port port. Parses output of shell 'sockstat' (NetBSD) to get connections $ sudo sockstat -4 -n USER COMMAND PID FD PROTO LOCAL ADDRESS FOREIGN ADDRESS root python2.7 1456 29 tcp *.4505 *.* root python2.7 1445 17 tcp *.4506 *.* root python2.7 1294 14 tcp 127.0.0.1.11813 127.0.0.1.4505 root python2.7 1294 41 tcp 127.0.0.1.61115 127.0.0.1.4506 $ sudo sockstat -4 -c -n -p 4506 USER COMMAND PID FD PROTO LOCAL ADDRESS FOREIGN ADDRESS root python2.7 1294 41 tcp 127.0.0.1.61115 127.0.0.1.4506 ''' port = int(port) remotes = set() try: cmd = salt.utils.args.shlex_split('sockstat -4 -c -n -p {0}'.format(port)) data = subprocess.check_output(cmd) # pylint: disable=minimum-python-version except subprocess.CalledProcessError as ex: log.error('Failed "sockstat" with returncode = %s', ex.returncode) raise lines = salt.utils.stringutils.to_str(data).split('\n') for line in lines: chunks = line.split() if not chunks: continue # ['root', 'python2.7', '1456', '37', 'tcp', # '127.0.0.1.4505-', '127.0.0.1.55703'] # print chunks if 'COMMAND' in chunks[1]: continue # ignore header if len(chunks) < 2: continue local = chunks[5].split('.') lport = local.pop() lhost = '.'.join(local) remote = chunks[6].split('.') rport = remote.pop() rhost = '.'.join(remote) if which_end == 'local' and int(lport) != port: # ignore if local port not port continue if which_end == 'remote' and int(rport) != port: # ignore if remote port not port continue remotes.add(rhost) return remotes def _openbsd_remotes_on(port, which_end): ''' OpenBSD specific helper function. Returns set of ipv4 host addresses of remote established connections on local or remote tcp port. Parses output of shell 'netstat' to get connections $ netstat -nf inet Active Internet connections Proto Recv-Q Send-Q Local Address Foreign Address (state) tcp 0 0 10.0.0.101.4505 10.0.0.1.45329 ESTABLISHED tcp 0 0 10.0.0.101.4505 10.0.0.100.50798 ESTABLISHED ''' remotes = set() try: data = subprocess.check_output(['netstat', '-nf', 'inet']) # pylint: disable=minimum-python-version except subprocess.CalledProcessError: log.error('Failed netstat') raise lines = data.split('\n') for line in lines: if 'ESTABLISHED' not in line: continue chunks = line.split() local_host, local_port = chunks[3].rsplit('.', 1) remote_host, remote_port = chunks[4].rsplit('.', 1) if which_end == 'remote_port' and int(remote_port) != port: continue if which_end == 'local_port' and int(local_port) != port: continue remotes.add(remote_host) return remotes def _windows_remotes_on(port, which_end): r''' Windows specific helper function. Returns set of ipv4 host addresses of remote established connections on local or remote tcp port. Parses output of shell 'netstat' to get connections C:\>netstat -n Active Connections Proto Local Address Foreign Address State TCP 10.2.33.17:3007 130.164.12.233:10123 ESTABLISHED TCP 10.2.33.17:3389 130.164.30.5:10378 ESTABLISHED ''' remotes = set() try: data = subprocess.check_output(['netstat', '-n']) # pylint: disable=minimum-python-version except subprocess.CalledProcessError: log.error('Failed netstat') raise lines = salt.utils.stringutils.to_str(data).split('\n') for line in lines: if 'ESTABLISHED' not in line: continue chunks = line.split() local_host, local_port = chunks[1].rsplit(':', 1) remote_host, remote_port = chunks[2].rsplit(':', 1) if which_end == 'remote_port' and int(remote_port) != port: continue if which_end == 'local_port' and int(local_port) != port: continue remotes.add(remote_host) return remotes def _aix_remotes_on(port, which_end): ''' AIX specific helper function. Returns set of ipv4 host addresses of remote established connections on local or remote tcp port. Parses output of shell 'netstat' to get connections root@la68pp002_pub:/opt/salt/lib/python2.7/site-packages/salt/modules# netstat -f inet -n Active Internet connections Proto Recv-Q Send-Q Local Address Foreign Address (state) tcp4 0 0 172.29.149.95.50093 209.41.78.13.4505 ESTABLISHED tcp4 0 0 127.0.0.1.9514 *.* LISTEN tcp4 0 0 127.0.0.1.9515 *.* LISTEN tcp4 0 0 127.0.0.1.199 127.0.0.1.32779 ESTABLISHED tcp4 0 0 127.0.0.1.32779 127.0.0.1.199 ESTABLISHED tcp4 0 40 172.29.149.95.22 172.29.96.83.41022 ESTABLISHED tcp4 0 0 172.29.149.95.22 172.29.96.83.41032 ESTABLISHED tcp4 0 0 127.0.0.1.32771 127.0.0.1.32775 ESTABLISHED tcp 0 0 127.0.0.1.32775 127.0.0.1.32771 ESTABLISHED tcp4 0 0 127.0.0.1.32771 127.0.0.1.32776 ESTABLISHED tcp 0 0 127.0.0.1.32776 127.0.0.1.32771 ESTABLISHED tcp4 0 0 127.0.0.1.32771 127.0.0.1.32777 ESTABLISHED tcp 0 0 127.0.0.1.32777 127.0.0.1.32771 ESTABLISHED tcp4 0 0 127.0.0.1.32771 127.0.0.1.32778 ESTABLISHED tcp 0 0 127.0.0.1.32778 127.0.0.1.32771 ESTABLISHED ''' remotes = set() try: data = subprocess.check_output(['netstat', '-f', 'inet', '-n']) # pylint: disable=minimum-python-version except subprocess.CalledProcessError: log.error('Failed netstat') raise lines = salt.utils.stringutils.to_str(data).split('\n') for line in lines: if 'ESTABLISHED' not in line: continue chunks = line.split() local_host, local_port = chunks[3].rsplit('.', 1) remote_host, remote_port = chunks[4].rsplit('.', 1) if which_end == 'remote_port' and int(remote_port) != port: continue if which_end == 'local_port' and int(local_port) != port: continue remotes.add(remote_host) return remotes @jinja_filter('gen_mac') def gen_mac(prefix='AC:DE:48'): ''' Generates a MAC address with the defined OUI prefix. Common prefixes: - ``00:16:3E`` -- Xen - ``00:18:51`` -- OpenVZ - ``00:50:56`` -- VMware (manually generated) - ``52:54:00`` -- QEMU/KVM - ``AC:DE:48`` -- PRIVATE References: - http://standards.ieee.org/develop/regauth/oui/oui.txt - https://www.wireshark.org/tools/oui-lookup.html - https://en.wikipedia.org/wiki/MAC_address ''' return '{0}:{1:02X}:{2:02X}:{3:02X}'.format(prefix, random.randint(0, 0xff), random.randint(0, 0xff), random.randint(0, 0xff)) @jinja_filter('mac_str_to_bytes') def mac_str_to_bytes(mac_str): ''' Convert a MAC address string into bytes. Works with or without separators: b1 = mac_str_to_bytes('08:00:27:13:69:77') b2 = mac_str_to_bytes('080027136977') assert b1 == b2 assert isinstance(b1, bytes) ''' if len(mac_str) == 12: pass elif len(mac_str) == 17: sep = mac_str[2] mac_str = mac_str.replace(sep, '') else: raise ValueError('Invalid MAC address') chars = (int(mac_str[s:s+2], 16) for s in range(0, 12, 2)) return bytes(chars) if six.PY3 else b''.join(chr(x) for x in chars) def refresh_dns(): ''' issue #21397: force glibc to re-read resolv.conf ''' try: res_init() except NameError: # Exception raised loading the library, thus res_init is not defined pass @jinja_filter('connection_check') def connection_check(addr, port=80, safe=False, ipv6=None): ''' Provides a convenient alias for the dns_check filter. ''' return dns_check(addr, port, safe, ipv6) @jinja_filter('dns_check') def dns_check(addr, port=80, safe=False, ipv6=None, attempt_connect=True): ''' Return the ip resolved by dns, but do not exit on failure, only raise an exception. Obeys system preference for IPv4/6 address resolution - this can be overridden by the ipv6 flag. Tries to connect to the address before considering it useful. If no address can be reached, the first one resolved is used as a fallback. ''' error = False lookup = addr seen_ipv6 = False family = socket.AF_INET6 if ipv6 else socket.AF_INET if ipv6 is False else socket.AF_UNSPEC hostnames = [] try: refresh_dns() hostnames = socket.getaddrinfo(addr, port, family, socket.SOCK_STREAM) except TypeError: err = ('Attempt to resolve address \'{0}\' failed. Invalid or unresolveable address').format(lookup) raise SaltSystemExit(code=42, msg=err) except socket.error: error = True # If ipv6 is set to True, attempt another lookup using the IPv4 family, # just in case we're attempting to lookup an IPv4 IP # as an IPv6 hostname. if error and ipv6: try: refresh_dns() hostnames = socket.getaddrinfo(addr, port, socket.AF_INET, socket.SOCK_STREAM) except TypeError: err = ('Attempt to resolve address \'{0}\' failed. Invalid or unresolveable address').format(lookup) raise SaltSystemExit(code=42, msg=err) except socket.error: error = True try: if not hostnames: error = True else: resolved = False candidates = [] for h in hostnames: # Input is IP address, passed through unchanged, just return it if h[4][0] == addr: resolved = salt.utils.zeromq.ip_bracket(addr) break candidate_addr = salt.utils.zeromq.ip_bracket(h[4][0]) # sometimes /etc/hosts contains ::1 localhost if not ipv6 and candidate_addr == '[::1]': continue candidates.append(candidate_addr) if attempt_connect: try: s = socket.socket(h[0], socket.SOCK_STREAM) s.settimeout(2) s.connect((candidate_addr.strip('[]'), h[4][1])) s.close() resolved = candidate_addr break except socket.error: pass if not resolved: if candidates: resolved = candidates[0] else: error = True except TypeError: err = ('Attempt to resolve address \'{0}\' failed. Invalid or unresolveable address').format(lookup) raise SaltSystemExit(code=42, msg=err) except socket.error: error = True if error: err = ('DNS lookup or connection check of \'{0}\' failed.').format(addr) if safe: if salt.log.is_console_configured(): # If logging is not configured it also means that either # the master or minion instance calling this hasn't even # started running log.error(err) raise SaltClientError() raise SaltSystemExit(code=42, msg=err) return resolved def parse_host_port(host_port): """ Takes a string argument specifying host or host:port. Returns a (hostname, port) or (ip_address, port) tuple. If no port is given, the second (port) element of the returned tuple will be None. host:port argument, for example, is accepted in the forms of: - hostname - hostname:1234 - hostname.domain.tld - hostname.domain.tld:5678 - [1234::5]:5678 - 1234::5 - 10.11.12.13:4567 - 10.11.12.13 """ host, port = None, None # default _s_ = host_port[:] if _s_[0] == "[": if "]" in host_port: host, _s_ = _s_.lstrip("[").rsplit("]", 1) host = ipaddress.IPv6Address(host).compressed if _s_[0] == ":": port = int(_s_.lstrip(":")) else: if len(_s_) > 1: raise ValueError('found ambiguous "{}" port in "{}"'.format(_s_, host_port)) else: if _s_.count(":") == 1: host, _hostport_separator_, port = _s_.partition(":") try: port = int(port) except ValueError as _e_: log.error('host_port "%s" port value "%s" is not an integer.', host_port, port) raise _e_ else: host = _s_ try: if not isinstance(host, ipaddress._BaseAddress): host_ip = ipaddress.ip_address(host).compressed host = host_ip except ValueError: log.debug('"%s" Not an IP address? Assuming it is a hostname.', host) if host != sanitize_host(host): log.error('bad hostname: "%s"', host) raise ValueError('bad hostname: "{}"'.format(host)) return host, port def is_fqdn(hostname): """ Verify if hostname conforms to be a FQDN. :param hostname: text string with the name of the host :return: bool, True if hostname is correct FQDN, False otherwise """ compliant = re.compile(r"(?!-)[A-Z\d\-\_]{1,63}(?<!-)$", re.IGNORECASE) return "." in hostname and len(hostname) < 0xff and all(compliant.match(x) for x in hostname.rstrip(".").split("."))
saltstack/salt
salt/utils/network.py
gen_mac
python
def gen_mac(prefix='AC:DE:48'): ''' Generates a MAC address with the defined OUI prefix. Common prefixes: - ``00:16:3E`` -- Xen - ``00:18:51`` -- OpenVZ - ``00:50:56`` -- VMware (manually generated) - ``52:54:00`` -- QEMU/KVM - ``AC:DE:48`` -- PRIVATE References: - http://standards.ieee.org/develop/regauth/oui/oui.txt - https://www.wireshark.org/tools/oui-lookup.html - https://en.wikipedia.org/wiki/MAC_address ''' return '{0}:{1:02X}:{2:02X}:{3:02X}'.format(prefix, random.randint(0, 0xff), random.randint(0, 0xff), random.randint(0, 0xff))
Generates a MAC address with the defined OUI prefix. Common prefixes: - ``00:16:3E`` -- Xen - ``00:18:51`` -- OpenVZ - ``00:50:56`` -- VMware (manually generated) - ``52:54:00`` -- QEMU/KVM - ``AC:DE:48`` -- PRIVATE References: - http://standards.ieee.org/develop/regauth/oui/oui.txt - https://www.wireshark.org/tools/oui-lookup.html - https://en.wikipedia.org/wiki/MAC_address
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/network.py#L1847-L1868
null
# -*- coding: utf-8 -*- ''' Define some generic socket functions for network modules ''' # Import python libs from __future__ import absolute_import, unicode_literals, print_function import itertools import os import re import types import socket import logging import platform import random import subprocess from string import ascii_letters, digits # Import 3rd-party libs from salt.ext import six from salt.ext.six.moves import range # pylint: disable=import-error,redefined-builtin # Attempt to import wmi try: import wmi import salt.utils.winapi except ImportError: pass # Import salt libs import salt.utils.args import salt.utils.files import salt.utils.path import salt.utils.platform import salt.utils.stringutils import salt.utils.zeromq from salt._compat import ipaddress from salt.exceptions import SaltClientError, SaltSystemExit from salt.utils.decorators.jinja import jinja_filter from salt.utils.versions import LooseVersion # inet_pton does not exist in Windows, this is a workaround if salt.utils.platform.is_windows(): from salt.ext import win_inet_pton # pylint: disable=unused-import log = logging.getLogger(__name__) try: import ctypes import ctypes.util libc = ctypes.cdll.LoadLibrary(ctypes.util.find_library("c")) res_init = libc.__res_init except (ImportError, OSError, AttributeError, TypeError): pass # pylint: disable=C0103 def sanitize_host(host): ''' Sanitize host string. https://tools.ietf.org/html/rfc1123#section-2.1 ''' RFC952_characters = ascii_letters + digits + ".-" return "".join([c for c in host[0:255] if c in RFC952_characters]) def isportopen(host, port): ''' Return status of a port ''' if not 1 <= int(port) <= 65535: return False sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) out = sock.connect_ex((sanitize_host(host), int(port))) return out def host_to_ips(host): ''' Returns a list of IP addresses of a given hostname or None if not found. ''' ips = [] try: for family, socktype, proto, canonname, sockaddr in socket.getaddrinfo( host, 0, socket.AF_UNSPEC, socket.SOCK_STREAM): if family == socket.AF_INET: ip, port = sockaddr elif family == socket.AF_INET6: ip, port, flow_info, scope_id = sockaddr ips.append(ip) if not ips: ips = None except Exception: ips = None return ips def _generate_minion_id(): ''' Get list of possible host names and convention names. :return: ''' # There are three types of hostnames: # 1. Network names. How host is accessed from the network. # 2. Host aliases. They might be not available in all the network or only locally (/etc/hosts) # 3. Convention names, an internal nodename. class DistinctList(list): ''' List, which allows one to append only distinct objects. Needs to work on Python 2.6, because of collections.OrderedDict only since 2.7 version. Override 'filter()' for custom filtering. ''' localhost_matchers = [r'localhost.*', r'ip6-.*', r'127[.]\d', r'0\.0\.0\.0', r'::1.*', r'ipv6-.*', r'fe00::.*', r'fe02::.*', r'1.0.0.*.ip6.arpa'] def append(self, p_object): if p_object and p_object not in self and not self.filter(p_object): super(DistinctList, self).append(p_object) return self def extend(self, iterable): for obj in iterable: self.append(obj) return self def filter(self, element): 'Returns True if element needs to be filtered' for rgx in self.localhost_matchers: if re.match(rgx, element): return True def first(self): return self and self[0] or None hostname = socket.gethostname() hosts = DistinctList().append( salt.utils.stringutils.to_unicode(socket.getfqdn(salt.utils.stringutils.to_bytes(hostname))) ).append(platform.node()).append(hostname) if not hosts: try: for a_nfo in socket.getaddrinfo(hosts.first() or 'localhost', None, socket.AF_INET, socket.SOCK_RAW, socket.IPPROTO_IP, socket.AI_CANONNAME): if len(a_nfo) > 3: hosts.append(a_nfo[3]) except socket.gaierror: log.warning('Cannot resolve address %s info via socket: %s', hosts.first() or 'localhost (N/A)', socket.gaierror) # Universal method for everywhere (Linux, Slowlaris, Windows etc) for f_name in ('/etc/hostname', '/etc/nodename', '/etc/hosts', r'{win}\system32\drivers\etc\hosts'.format(win=os.getenv('WINDIR'))): try: with salt.utils.files.fopen(f_name) as f_hdl: for line in f_hdl: line = salt.utils.stringutils.to_unicode(line) hst = line.strip().split('#')[0].strip().split() if hst: if hst[0][:4] in ('127.', '::1') or len(hst) == 1: hosts.extend(hst) except IOError: pass # include public and private ipaddresses return hosts.extend([addr for addr in ip_addrs() if not ipaddress.ip_address(addr).is_loopback]) def generate_minion_id(): ''' Return only first element of the hostname from all possible list. :return: ''' try: ret = salt.utils.stringutils.to_unicode(_generate_minion_id().first()) except TypeError: ret = None return ret or 'localhost' def get_socket(addr, type=socket.SOCK_STREAM, proto=0): ''' Return a socket object for the addr IP-version agnostic ''' version = ipaddress.ip_address(addr).version if version == 4: family = socket.AF_INET elif version == 6: family = socket.AF_INET6 return socket.socket(family, type, proto) def get_fqhostname(): ''' Returns the fully qualified hostname ''' # try getaddrinfo() fqdn = None try: addrinfo = socket.getaddrinfo( socket.gethostname(), 0, socket.AF_UNSPEC, socket.SOCK_STREAM, socket.SOL_TCP, socket.AI_CANONNAME ) for info in addrinfo: # info struct [family, socktype, proto, canonname, sockaddr] # On Windows `canonname` can be an empty string # This can cause the function to return `None` if len(info) > 3 and info[3]: fqdn = info[3] break except socket.gaierror: pass # NOTE: this used to log.error() but it was later disabled except socket.error as err: log.debug('socket.getaddrinfo() failure while finding fqdn: %s', err) if fqdn is None: fqdn = socket.getfqdn() return fqdn def ip_to_host(ip): ''' Returns the hostname of a given IP ''' try: hostname, aliaslist, ipaddrlist = socket.gethostbyaddr(ip) except Exception as exc: log.debug('salt.utils.network.ip_to_host(%r) failed: %s', ip, exc) hostname = None return hostname # pylint: enable=C0103 def is_reachable_host(entity_name): ''' Returns a bool telling if the entity name is a reachable host (IPv4/IPv6/FQDN/etc). :param hostname: :return: ''' try: assert type(socket.getaddrinfo(entity_name, 0, 0, 0, 0)) == list ret = True except socket.gaierror: ret = False return ret def is_ip(ip): ''' Returns a bool telling if the passed IP is a valid IPv4 or IPv6 address. ''' return is_ipv4(ip) or is_ipv6(ip) def is_ipv4(ip): ''' Returns a bool telling if the value passed to it was a valid IPv4 address ''' try: return ipaddress.ip_address(ip).version == 4 except ValueError: return False def is_ipv6(ip): ''' Returns a bool telling if the value passed to it was a valid IPv6 address ''' try: return ipaddress.ip_address(ip).version == 6 except ValueError: return False def is_subnet(cidr): ''' Returns a bool telling if the passed string is an IPv4 or IPv6 subnet ''' return is_ipv4_subnet(cidr) or is_ipv6_subnet(cidr) def is_ipv4_subnet(cidr): ''' Returns a bool telling if the passed string is an IPv4 subnet ''' try: return '/' in cidr and bool(ipaddress.IPv4Network(cidr)) except Exception: return False def is_ipv6_subnet(cidr): ''' Returns a bool telling if the passed string is an IPv6 subnet ''' try: return '/' in cidr and bool(ipaddress.IPv6Network(cidr)) except Exception: return False @jinja_filter('is_ip') def is_ip_filter(ip, options=None): ''' Returns a bool telling if the passed IP is a valid IPv4 or IPv6 address. ''' return is_ipv4_filter(ip, options=options) or is_ipv6_filter(ip, options=options) def _ip_options_global(ip_obj, version): return not ip_obj.is_private def _ip_options_multicast(ip_obj, version): return ip_obj.is_multicast def _ip_options_loopback(ip_obj, version): return ip_obj.is_loopback def _ip_options_link_local(ip_obj, version): return ip_obj.is_link_local def _ip_options_private(ip_obj, version): return ip_obj.is_private def _ip_options_reserved(ip_obj, version): return ip_obj.is_reserved def _ip_options_site_local(ip_obj, version): if version == 6: return ip_obj.is_site_local return False def _ip_options_unspecified(ip_obj, version): return ip_obj.is_unspecified def _ip_options(ip_obj, version, options=None): # will process and IP options options_fun_map = { 'global': _ip_options_global, 'link-local': _ip_options_link_local, 'linklocal': _ip_options_link_local, 'll': _ip_options_link_local, 'link_local': _ip_options_link_local, 'loopback': _ip_options_loopback, 'lo': _ip_options_loopback, 'multicast': _ip_options_multicast, 'private': _ip_options_private, 'public': _ip_options_global, 'reserved': _ip_options_reserved, 'site-local': _ip_options_site_local, 'sl': _ip_options_site_local, 'site_local': _ip_options_site_local, 'unspecified': _ip_options_unspecified } if not options: return six.text_type(ip_obj) # IP version already checked options_list = [option.strip() for option in options.split(',')] for option, fun in options_fun_map.items(): if option in options_list: fun_res = fun(ip_obj, version) if not fun_res: return None # stop at first failed test # else continue return six.text_type(ip_obj) def _is_ipv(ip, version, options=None): if not version: version = 4 if version not in (4, 6): return None try: ip_obj = ipaddress.ip_address(ip) except ValueError: # maybe it is an IP network try: ip_obj = ipaddress.ip_interface(ip) except ValueError: # nope, still not :( return None if not ip_obj.version == version: return None # has the right version, let's move on return _ip_options(ip_obj, version, options=options) @jinja_filter('is_ipv4') def is_ipv4_filter(ip, options=None): ''' Returns a bool telling if the value passed to it was a valid IPv4 address. ip The IP address. net: False Consider IP addresses followed by netmask. options CSV of options regarding the nature of the IP address. E.g.: loopback, multicast, private etc. ''' _is_ipv4 = _is_ipv(ip, 4, options=options) return isinstance(_is_ipv4, six.string_types) @jinja_filter('is_ipv6') def is_ipv6_filter(ip, options=None): ''' Returns a bool telling if the value passed to it was a valid IPv6 address. ip The IP address. net: False Consider IP addresses followed by netmask. options CSV of options regarding the nature of the IP address. E.g.: loopback, multicast, private etc. ''' _is_ipv6 = _is_ipv(ip, 6, options=options) return isinstance(_is_ipv6, six.string_types) def _ipv_filter(value, version, options=None): if version not in (4, 6): return if isinstance(value, (six.string_types, six.text_type, six.binary_type)): return _is_ipv(value, version, options=options) # calls is_ipv4 or is_ipv6 for `value` elif isinstance(value, (list, tuple, types.GeneratorType)): # calls is_ipv4 or is_ipv6 for each element in the list # os it filters and returns only those elements having the desired IP version return [ _is_ipv(addr, version, options=options) for addr in value if _is_ipv(addr, version, options=options) is not None ] return None @jinja_filter('ipv4') def ipv4(value, options=None): ''' Filters a list and returns IPv4 values only. ''' return _ipv_filter(value, 4, options=options) @jinja_filter('ipv6') def ipv6(value, options=None): ''' Filters a list and returns IPv6 values only. ''' return _ipv_filter(value, 6, options=options) @jinja_filter('ipaddr') def ipaddr(value, options=None): ''' Filters and returns only valid IP objects. ''' ipv4_obj = ipv4(value, options=options) ipv6_obj = ipv6(value, options=options) if ipv4_obj is None or ipv6_obj is None: # an IP address can be either IPv4 either IPv6 # therefofe if the value passed as arg is not a list, at least one of the calls above will return None # if one of them is none, means that we should return only one of them return ipv4_obj or ipv6_obj # one of them else: return ipv4_obj + ipv6_obj # extend lists def _filter_ipaddr(value, options, version=None): ipaddr_filter_out = None if version: if version == 4: ipaddr_filter_out = ipv4(value, options) elif version == 6: ipaddr_filter_out = ipv6(value, options) else: ipaddr_filter_out = ipaddr(value, options) if not ipaddr_filter_out: return if not isinstance(ipaddr_filter_out, (list, tuple, types.GeneratorType)): ipaddr_filter_out = [ipaddr_filter_out] return ipaddr_filter_out @jinja_filter('ip_host') def ip_host(value, options=None, version=None): ''' Returns the interfaces IP address, e.g.: 192.168.0.1/28. ''' ipaddr_filter_out = _filter_ipaddr(value, options=options, version=version) if not ipaddr_filter_out: return if not isinstance(value, (list, tuple, types.GeneratorType)): return six.text_type(ipaddress.ip_interface(ipaddr_filter_out[0])) return [six.text_type(ipaddress.ip_interface(ip_a)) for ip_a in ipaddr_filter_out] def _network_hosts(ip_addr_entry): return [ six.text_type(host) for host in ipaddress.ip_network(ip_addr_entry, strict=False).hosts() ] @jinja_filter('network_hosts') def network_hosts(value, options=None, version=None): ''' Return the list of hosts within a network. .. note:: When running this command with a large IPv6 network, the command will take a long time to gather all of the hosts. ''' ipaddr_filter_out = _filter_ipaddr(value, options=options, version=version) if not ipaddr_filter_out: return if not isinstance(value, (list, tuple, types.GeneratorType)): return _network_hosts(ipaddr_filter_out[0]) return [ _network_hosts(ip_a) for ip_a in ipaddr_filter_out ] def _network_size(ip_addr_entry): return ipaddress.ip_network(ip_addr_entry, strict=False).num_addresses @jinja_filter('network_size') def network_size(value, options=None, version=None): ''' Get the size of a network. ''' ipaddr_filter_out = _filter_ipaddr(value, options=options, version=version) if not ipaddr_filter_out: return if not isinstance(value, (list, tuple, types.GeneratorType)): return _network_size(ipaddr_filter_out[0]) return [ _network_size(ip_a) for ip_a in ipaddr_filter_out ] def natural_ipv4_netmask(ip, fmt='prefixlen'): ''' Returns the "natural" mask of an IPv4 address ''' bits = _ipv4_to_bits(ip) if bits.startswith('11'): mask = '24' elif bits.startswith('1'): mask = '16' else: mask = '8' if fmt == 'netmask': return cidr_to_ipv4_netmask(mask) else: return '/' + mask def rpad_ipv4_network(ip): ''' Returns an IP network address padded with zeros. Ex: '192.168.3' -> '192.168.3.0' '10.209' -> '10.209.0.0' ''' return '.'.join(itertools.islice(itertools.chain(ip.split('.'), '0000'), 0, 4)) def cidr_to_ipv4_netmask(cidr_bits): ''' Returns an IPv4 netmask ''' try: cidr_bits = int(cidr_bits) if not 1 <= cidr_bits <= 32: return '' except ValueError: return '' netmask = '' for idx in range(4): if idx: netmask += '.' if cidr_bits >= 8: netmask += '255' cidr_bits -= 8 else: netmask += '{0:d}'.format(256 - (2 ** (8 - cidr_bits))) cidr_bits = 0 return netmask def _number_of_set_bits_to_ipv4_netmask(set_bits): # pylint: disable=C0103 ''' Returns an IPv4 netmask from the integer representation of that mask. Ex. 0xffffff00 -> '255.255.255.0' ''' return cidr_to_ipv4_netmask(_number_of_set_bits(set_bits)) # pylint: disable=C0103 def _number_of_set_bits(x): ''' Returns the number of bits that are set in a 32bit int ''' # Taken from http://stackoverflow.com/a/4912729. Many thanks! x -= (x >> 1) & 0x55555555 x = ((x >> 2) & 0x33333333) + (x & 0x33333333) x = ((x >> 4) + x) & 0x0f0f0f0f x += x >> 8 x += x >> 16 return x & 0x0000003f # pylint: enable=C0103 def _interfaces_ip(out): ''' Uses ip to return a dictionary of interfaces with various information about each (up/down state, ip address, netmask, and hwaddr) ''' ret = dict() def parse_network(value, cols): ''' Return a tuple of ip, netmask, broadcast based on the current set of cols ''' brd = None scope = None if '/' in value: # we have a CIDR in this address ip, cidr = value.split('/') # pylint: disable=C0103 else: ip = value # pylint: disable=C0103 cidr = 32 if type_ == 'inet': mask = cidr_to_ipv4_netmask(int(cidr)) if 'brd' in cols: brd = cols[cols.index('brd') + 1] elif type_ == 'inet6': mask = cidr if 'scope' in cols: scope = cols[cols.index('scope') + 1] return (ip, mask, brd, scope) groups = re.compile('\r?\n\\d').split(out) for group in groups: iface = None data = dict() for line in group.splitlines(): if ' ' not in line: continue match = re.match(r'^\d*:\s+([\w.\-]+)(?:@)?([\w.\-]+)?:\s+<(.+)>', line) if match: iface, parent, attrs = match.groups() if 'UP' in attrs.split(','): data['up'] = True else: data['up'] = False if parent: data['parent'] = parent continue cols = line.split() if len(cols) >= 2: type_, value = tuple(cols[0:2]) iflabel = cols[-1:][0] if type_ in ('inet', 'inet6'): if 'secondary' not in cols: ipaddr, netmask, broadcast, scope = parse_network(value, cols) if type_ == 'inet': if 'inet' not in data: data['inet'] = list() addr_obj = dict() addr_obj['address'] = ipaddr addr_obj['netmask'] = netmask addr_obj['broadcast'] = broadcast addr_obj['label'] = iflabel data['inet'].append(addr_obj) elif type_ == 'inet6': if 'inet6' not in data: data['inet6'] = list() addr_obj = dict() addr_obj['address'] = ipaddr addr_obj['prefixlen'] = netmask addr_obj['scope'] = scope data['inet6'].append(addr_obj) else: if 'secondary' not in data: data['secondary'] = list() ip_, mask, brd, scp = parse_network(value, cols) data['secondary'].append({ 'type': type_, 'address': ip_, 'netmask': mask, 'broadcast': brd, 'label': iflabel, }) del ip_, mask, brd, scp elif type_.startswith('link'): data['hwaddr'] = value if iface: ret[iface] = data del iface, data return ret def _interfaces_ifconfig(out): ''' Uses ifconfig to return a dictionary of interfaces with various information about each (up/down state, ip address, netmask, and hwaddr) ''' ret = dict() piface = re.compile(r'^([^\s:]+)') pmac = re.compile('.*?(?:HWaddr|ether|address:|lladdr) ([0-9a-fA-F:]+)') if salt.utils.platform.is_sunos(): pip = re.compile(r'.*?(?:inet\s+)([0-9]+\.[0-9]+\.[0-9]+\.[0-9]+)(.*)') pip6 = re.compile('.*?(?:inet6 )([0-9a-fA-F:]+)') pmask6 = re.compile(r'.*?(?:inet6 [0-9a-fA-F:]+/(\d+)).*') else: pip = re.compile(r'.*?(?:inet addr:|inet [^\d]*)(.*?)\s') pip6 = re.compile('.*?(?:inet6 addr: (.*?)/|inet6 )([0-9a-fA-F:]+)') pmask6 = re.compile(r'.*?(?:inet6 addr: [0-9a-fA-F:]+/(\d+)|prefixlen (\d+))(?: Scope:([a-zA-Z]+)| scopeid (0x[0-9a-fA-F]))?') pmask = re.compile(r'.*?(?:Mask:|netmask )(?:((?:0x)?[0-9a-fA-F]{8})|([\d\.]+))') pupdown = re.compile('UP') pbcast = re.compile(r'.*?(?:Bcast:|broadcast )([\d\.]+)') groups = re.compile('\r?\n(?=\\S)').split(out) for group in groups: data = dict() iface = '' updown = False for line in group.splitlines(): miface = piface.match(line) mmac = pmac.match(line) mip = pip.match(line) mip6 = pip6.match(line) mupdown = pupdown.search(line) if miface: iface = miface.group(1) if mmac: data['hwaddr'] = mmac.group(1) if salt.utils.platform.is_sunos(): expand_mac = [] for chunk in data['hwaddr'].split(':'): expand_mac.append('0{0}'.format(chunk) if len(chunk) < 2 else '{0}'.format(chunk)) data['hwaddr'] = ':'.join(expand_mac) if mip: if 'inet' not in data: data['inet'] = list() addr_obj = dict() addr_obj['address'] = mip.group(1) mmask = pmask.match(line) if mmask: if mmask.group(1): mmask = _number_of_set_bits_to_ipv4_netmask( int(mmask.group(1), 16)) else: mmask = mmask.group(2) addr_obj['netmask'] = mmask mbcast = pbcast.match(line) if mbcast: addr_obj['broadcast'] = mbcast.group(1) data['inet'].append(addr_obj) if mupdown: updown = True if mip6: if 'inet6' not in data: data['inet6'] = list() addr_obj = dict() addr_obj['address'] = mip6.group(1) or mip6.group(2) mmask6 = pmask6.match(line) if mmask6: addr_obj['prefixlen'] = mmask6.group(1) or mmask6.group(2) if not salt.utils.platform.is_sunos(): ipv6scope = mmask6.group(3) or mmask6.group(4) addr_obj['scope'] = ipv6scope.lower() if ipv6scope is not None else ipv6scope # SunOS sometimes has ::/0 as inet6 addr when using addrconf if not salt.utils.platform.is_sunos() \ or addr_obj['address'] != '::' \ and addr_obj['prefixlen'] != 0: data['inet6'].append(addr_obj) data['up'] = updown if iface in ret: # SunOS optimization, where interfaces occur twice in 'ifconfig -a' # output with the same name: for ipv4 and then for ipv6 addr family. # Every instance has it's own 'UP' status and we assume that ipv4 # status determines global interface status. # # merge items with higher priority for older values # after that merge the inet and inet6 sub items for both ret[iface] = dict(list(data.items()) + list(ret[iface].items())) if 'inet' in data: ret[iface]['inet'].extend(x for x in data['inet'] if x not in ret[iface]['inet']) if 'inet6' in data: ret[iface]['inet6'].extend(x for x in data['inet6'] if x not in ret[iface]['inet6']) else: ret[iface] = data del data return ret def linux_interfaces(): ''' Obtain interface information for *NIX/BSD variants ''' ifaces = dict() ip_path = salt.utils.path.which('ip') ifconfig_path = None if ip_path else salt.utils.path.which('ifconfig') if ip_path: cmd1 = subprocess.Popen( '{0} link show'.format(ip_path), shell=True, close_fds=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT).communicate()[0] cmd2 = subprocess.Popen( '{0} addr show'.format(ip_path), shell=True, close_fds=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT).communicate()[0] ifaces = _interfaces_ip("{0}\n{1}".format( salt.utils.stringutils.to_str(cmd1), salt.utils.stringutils.to_str(cmd2))) elif ifconfig_path: cmd = subprocess.Popen( '{0} -a'.format(ifconfig_path), shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT).communicate()[0] ifaces = _interfaces_ifconfig(salt.utils.stringutils.to_str(cmd)) return ifaces def _netbsd_interfaces_ifconfig(out): ''' Uses ifconfig to return a dictionary of interfaces with various information about each (up/down state, ip address, netmask, and hwaddr) ''' ret = dict() piface = re.compile(r'^([^\s:]+)') pmac = re.compile('.*?address: ([0-9a-f:]+)') pip = re.compile(r'.*?inet [^\d]*(.*?)/([\d]*)\s') pip6 = re.compile(r'.*?inet6 ([0-9a-f:]+)%([a-zA-Z0-9]*)/([\d]*)\s') pupdown = re.compile('UP') pbcast = re.compile(r'.*?broadcast ([\d\.]+)') groups = re.compile('\r?\n(?=\\S)').split(out) for group in groups: data = dict() iface = '' updown = False for line in group.splitlines(): miface = piface.match(line) mmac = pmac.match(line) mip = pip.match(line) mip6 = pip6.match(line) mupdown = pupdown.search(line) if miface: iface = miface.group(1) if mmac: data['hwaddr'] = mmac.group(1) if mip: if 'inet' not in data: data['inet'] = list() addr_obj = dict() addr_obj['address'] = mip.group(1) mmask = mip.group(2) if mip.group(2): addr_obj['netmask'] = cidr_to_ipv4_netmask(mip.group(2)) mbcast = pbcast.match(line) if mbcast: addr_obj['broadcast'] = mbcast.group(1) data['inet'].append(addr_obj) if mupdown: updown = True if mip6: if 'inet6' not in data: data['inet6'] = list() addr_obj = dict() addr_obj['address'] = mip6.group(1) mmask6 = mip6.group(3) addr_obj['scope'] = mip6.group(2) addr_obj['prefixlen'] = mip6.group(3) data['inet6'].append(addr_obj) data['up'] = updown ret[iface] = data del data return ret def netbsd_interfaces(): ''' Obtain interface information for NetBSD >= 8 where the ifconfig output diverged from other BSD variants (Netmask is now part of the address) ''' # NetBSD versions prior to 8.0 can still use linux_interfaces() if LooseVersion(os.uname()[2]) < LooseVersion('8.0'): return linux_interfaces() ifconfig_path = salt.utils.path.which('ifconfig') cmd = subprocess.Popen( '{0} -a'.format(ifconfig_path), shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT).communicate()[0] return _netbsd_interfaces_ifconfig(salt.utils.stringutils.to_str(cmd)) def _interfaces_ipconfig(out): ''' Returns a dictionary of interfaces with various information about each (up/down state, ip address, netmask, and hwaddr) NOTE: This is not used by any function and may be able to be removed in the future. ''' ifaces = dict() iface = None adapter_iface_regex = re.compile(r'adapter (\S.+):$') for line in out.splitlines(): if not line: continue # TODO what does Windows call Infiniband and 10/40gige adapters if line.startswith('Ethernet'): iface = ifaces[adapter_iface_regex.search(line).group(1)] iface['up'] = True addr = None continue if iface: key, val = line.split(',', 1) key = key.strip(' .') val = val.strip() if addr and key == 'Subnet Mask': addr['netmask'] = val elif key in ('IP Address', 'IPv4 Address'): if 'inet' not in iface: iface['inet'] = list() addr = {'address': val.rstrip('(Preferred)'), 'netmask': None, 'broadcast': None} # TODO find the broadcast iface['inet'].append(addr) elif 'IPv6 Address' in key: if 'inet6' not in iface: iface['inet'] = list() # XXX What is the prefixlen!? addr = {'address': val.rstrip('(Preferred)'), 'prefixlen': None} iface['inet6'].append(addr) elif key == 'Physical Address': iface['hwaddr'] = val elif key == 'Media State': # XXX seen used for tunnel adaptors # might be useful iface['up'] = (val != 'Media disconnected') def win_interfaces(): ''' Obtain interface information for Windows systems ''' with salt.utils.winapi.Com(): c = wmi.WMI() ifaces = {} for iface in c.Win32_NetworkAdapterConfiguration(IPEnabled=1): ifaces[iface.Description] = dict() if iface.MACAddress: ifaces[iface.Description]['hwaddr'] = iface.MACAddress if iface.IPEnabled: ifaces[iface.Description]['up'] = True for ip in iface.IPAddress: if '.' in ip: if 'inet' not in ifaces[iface.Description]: ifaces[iface.Description]['inet'] = [] item = {'address': ip, 'label': iface.Description} if iface.DefaultIPGateway: broadcast = next((i for i in iface.DefaultIPGateway if '.' in i), '') if broadcast: item['broadcast'] = broadcast if iface.IPSubnet: netmask = next((i for i in iface.IPSubnet if '.' in i), '') if netmask: item['netmask'] = netmask ifaces[iface.Description]['inet'].append(item) if ':' in ip: if 'inet6' not in ifaces[iface.Description]: ifaces[iface.Description]['inet6'] = [] item = {'address': ip} if iface.DefaultIPGateway: broadcast = next((i for i in iface.DefaultIPGateway if ':' in i), '') if broadcast: item['broadcast'] = broadcast if iface.IPSubnet: netmask = next((i for i in iface.IPSubnet if ':' in i), '') if netmask: item['netmask'] = netmask ifaces[iface.Description]['inet6'].append(item) else: ifaces[iface.Description]['up'] = False return ifaces def interfaces(): ''' Return a dictionary of information about all the interfaces on the minion ''' if salt.utils.platform.is_windows(): return win_interfaces() elif salt.utils.platform.is_netbsd(): return netbsd_interfaces() else: return linux_interfaces() def get_net_start(ipaddr, netmask): ''' Return the address of the network ''' net = ipaddress.ip_network('{0}/{1}'.format(ipaddr, netmask), strict=False) return six.text_type(net.network_address) def get_net_size(mask): ''' Turns an IPv4 netmask into it's corresponding prefix length (255.255.255.0 -> 24 as in 192.168.1.10/24). ''' binary_str = '' for octet in mask.split('.'): binary_str += bin(int(octet))[2:].zfill(8) return len(binary_str.rstrip('0')) def calc_net(ipaddr, netmask=None): ''' Takes IP (CIDR notation supported) and optionally netmask and returns the network in CIDR-notation. (The IP can be any IP inside the subnet) ''' if netmask is not None: ipaddr = '{0}/{1}'.format(ipaddr, netmask) return six.text_type(ipaddress.ip_network(ipaddr, strict=False)) def _ipv4_to_bits(ipaddr): ''' Accepts an IPv4 dotted quad and returns a string representing its binary counterpart ''' return ''.join([bin(int(x))[2:].rjust(8, '0') for x in ipaddr.split('.')]) def _get_iface_info(iface): ''' If `iface` is available, return interface info and no error, otherwise return no info and log and return an error ''' iface_info = interfaces() if iface in iface_info.keys(): return iface_info, False else: error_msg = ('Interface "{0}" not in available interfaces: "{1}"' ''.format(iface, '", "'.join(iface_info.keys()))) log.error(error_msg) return None, error_msg def _hw_addr_aix(iface): ''' Return the hardware address (a.k.a. MAC address) for a given interface on AIX MAC address not available in through interfaces ''' cmd = subprocess.Popen( 'entstat -d {0} | grep \'Hardware Address\''.format(iface), shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT).communicate()[0] if cmd: comps = cmd.split(' ') if len(comps) == 3: mac_addr = comps[2].strip('\'').strip() return mac_addr error_msg = ('Interface "{0}" either not available or does not contain a hardware address'.format(iface)) log.error(error_msg) return error_msg def hw_addr(iface): ''' Return the hardware address (a.k.a. MAC address) for a given interface .. versionchanged:: 2016.11.4 Added support for AIX ''' if salt.utils.platform.is_aix(): return _hw_addr_aix iface_info, error = _get_iface_info(iface) if error is False: return iface_info.get(iface, {}).get('hwaddr', '') else: return error def interface(iface): ''' Return the details of `iface` or an error if it does not exist ''' iface_info, error = _get_iface_info(iface) if error is False: return iface_info.get(iface, {}).get('inet', '') else: return error def interface_ip(iface): ''' Return `iface` IPv4 addr or an error if `iface` does not exist ''' iface_info, error = _get_iface_info(iface) if error is False: inet = iface_info.get(iface, {}).get('inet', None) return inet[0].get('address', '') if inet else '' else: return error def _subnets(proto='inet', interfaces_=None): ''' Returns a list of subnets to which the host belongs ''' if interfaces_ is None: ifaces = interfaces() elif isinstance(interfaces_, list): ifaces = {} for key, value in six.iteritems(interfaces()): if key in interfaces_: ifaces[key] = value else: ifaces = {interfaces_: interfaces().get(interfaces_, {})} ret = set() if proto == 'inet': subnet = 'netmask' dflt_cidr = 32 elif proto == 'inet6': subnet = 'prefixlen' dflt_cidr = 128 else: log.error('Invalid proto %s calling subnets()', proto) return for ip_info in six.itervalues(ifaces): addrs = ip_info.get(proto, []) addrs.extend([addr for addr in ip_info.get('secondary', []) if addr.get('type') == proto]) for intf in addrs: if subnet in intf: intf = ipaddress.ip_interface('{0}/{1}'.format(intf['address'], intf[subnet])) else: intf = ipaddress.ip_interface('{0}/{1}'.format(intf['address'], dflt_cidr)) if not intf.is_loopback: ret.add(intf.network) return [six.text_type(net) for net in sorted(ret)] def subnets(interfaces=None): ''' Returns a list of IPv4 subnets to which the host belongs ''' return _subnets('inet', interfaces_=interfaces) def subnets6(): ''' Returns a list of IPv6 subnets to which the host belongs ''' return _subnets('inet6') def in_subnet(cidr, addr=None): ''' Returns True if host or (any of) addrs is within specified subnet, otherwise False ''' try: cidr = ipaddress.ip_network(cidr) except ValueError: log.error('Invalid CIDR \'%s\'', cidr) return False if addr is None: addr = ip_addrs() addr.extend(ip_addrs6()) elif not isinstance(addr, (list, tuple)): addr = (addr,) return any(ipaddress.ip_address(item) in cidr for item in addr) def _ip_addrs(interface=None, include_loopback=False, interface_data=None, proto='inet'): ''' Return the full list of IP adresses matching the criteria proto = inet|inet6 ''' ret = set() ifaces = interface_data \ if isinstance(interface_data, dict) \ else interfaces() if interface is None: target_ifaces = ifaces else: target_ifaces = dict([(k, v) for k, v in six.iteritems(ifaces) if k == interface]) if not target_ifaces: log.error('Interface %s not found.', interface) for ip_info in six.itervalues(target_ifaces): addrs = ip_info.get(proto, []) addrs.extend([addr for addr in ip_info.get('secondary', []) if addr.get('type') == proto]) for addr in addrs: addr = ipaddress.ip_address(addr.get('address')) if not addr.is_loopback or include_loopback: ret.add(addr) return [six.text_type(addr) for addr in sorted(ret)] def ip_addrs(interface=None, include_loopback=False, interface_data=None): ''' Returns a list of IPv4 addresses assigned to the host. 127.0.0.1 is ignored, unless 'include_loopback=True' is indicated. If 'interface' is provided, then only IP addresses from that interface will be returned. ''' return _ip_addrs(interface, include_loopback, interface_data, 'inet') def ip_addrs6(interface=None, include_loopback=False, interface_data=None): ''' Returns a list of IPv6 addresses assigned to the host. ::1 is ignored, unless 'include_loopback=True' is indicated. If 'interface' is provided, then only IP addresses from that interface will be returned. ''' return _ip_addrs(interface, include_loopback, interface_data, 'inet6') def hex2ip(hex_ip, invert=False): ''' Convert a hex string to an ip, if a failure occurs the original hex is returned. If 'invert=True' assume that ip from /proc/net/<proto> ''' if len(hex_ip) == 32: # ipv6 ip = [] for i in range(0, 32, 8): ip_part = hex_ip[i:i + 8] ip_part = [ip_part[x:x + 2] for x in range(0, 8, 2)] if invert: ip.append("{0[3]}{0[2]}:{0[1]}{0[0]}".format(ip_part)) else: ip.append("{0[0]}{0[1]}:{0[2]}{0[3]}".format(ip_part)) try: address = ipaddress.IPv6Address(":".join(ip)) if address.ipv4_mapped: return str(address.ipv4_mapped) else: return address.compressed except ipaddress.AddressValueError as ex: log.error('hex2ip - ipv6 address error: %s', ex) return hex_ip try: hip = int(hex_ip, 16) except ValueError: return hex_ip if invert: return '{3}.{2}.{1}.{0}'.format(hip >> 24 & 255, hip >> 16 & 255, hip >> 8 & 255, hip & 255) return '{0}.{1}.{2}.{3}'.format(hip >> 24 & 255, hip >> 16 & 255, hip >> 8 & 255, hip & 255) def mac2eui64(mac, prefix=None): ''' Convert a MAC address to a EUI64 identifier or, with prefix provided, a full IPv6 address ''' # http://tools.ietf.org/html/rfc4291#section-2.5.1 eui64 = re.sub(r'[.:-]', '', mac).lower() eui64 = eui64[0:6] + 'fffe' + eui64[6:] eui64 = hex(int(eui64[0:2], 16) | 2)[2:].zfill(2) + eui64[2:] if prefix is None: return ':'.join(re.findall(r'.{4}', eui64)) else: try: net = ipaddress.ip_network(prefix, strict=False) euil = int('0x{0}'.format(eui64), 16) return '{0}/{1}'.format(net[euil], net.prefixlen) except Exception: return def active_tcp(): ''' Return a dict describing all active tcp connections as quickly as possible ''' ret = {} for statf in ['/proc/net/tcp', '/proc/net/tcp6']: if os.path.isfile(statf): with salt.utils.files.fopen(statf, 'rb') as fp_: for line in fp_: line = salt.utils.stringutils.to_unicode(line) if line.strip().startswith('sl'): continue iret = _parse_tcp_line(line) sl = next(iter(iret)) if iret[sl]['state'] == 1: # 1 is ESTABLISHED del iret[sl]['state'] ret[len(ret)] = iret[sl] return ret def local_port_tcp(port): ''' Return a set of remote ip addrs attached to the specified local port ''' ret = _remotes_on(port, 'local_port') return ret def remote_port_tcp(port): ''' Return a set of ip addrs the current host is connected to on given port ''' ret = _remotes_on(port, 'remote_port') return ret def _remotes_on(port, which_end): ''' Return a set of ip addrs active tcp connections ''' port = int(port) ret = _netlink_tool_remote_on(port, which_end) if ret is not None: return ret ret = set() proc_available = False for statf in ['/proc/net/tcp', '/proc/net/tcp6']: if os.path.isfile(statf): proc_available = True with salt.utils.files.fopen(statf, 'r') as fp_: for line in fp_: line = salt.utils.stringutils.to_unicode(line) if line.strip().startswith('sl'): continue iret = _parse_tcp_line(line) sl = next(iter(iret)) if iret[sl][which_end] == port and iret[sl]['state'] == 1: # 1 is ESTABLISHED ret.add(iret[sl]['remote_addr']) if not proc_available: # Fallback to use OS specific tools if salt.utils.platform.is_sunos(): return _sunos_remotes_on(port, which_end) if salt.utils.platform.is_freebsd(): return _freebsd_remotes_on(port, which_end) if salt.utils.platform.is_netbsd(): return _netbsd_remotes_on(port, which_end) if salt.utils.platform.is_openbsd(): return _openbsd_remotes_on(port, which_end) if salt.utils.platform.is_windows(): return _windows_remotes_on(port, which_end) if salt.utils.platform.is_aix(): return _aix_remotes_on(port, which_end) return _linux_remotes_on(port, which_end) return ret def _parse_tcp_line(line): ''' Parse a single line from the contents of /proc/net/tcp or /proc/net/tcp6 ''' ret = {} comps = line.strip().split() sl = comps[0].rstrip(':') ret[sl] = {} l_addr, l_port = comps[1].split(':') r_addr, r_port = comps[2].split(':') ret[sl]['local_addr'] = hex2ip(l_addr, True) ret[sl]['local_port'] = int(l_port, 16) ret[sl]['remote_addr'] = hex2ip(r_addr, True) ret[sl]['remote_port'] = int(r_port, 16) ret[sl]['state'] = int(comps[3], 16) return ret def _netlink_tool_remote_on(port, which_end): ''' Returns set of ipv4 host addresses of remote established connections on local or remote tcp port. Parses output of shell 'ss' to get connections [root@salt-master ~]# ss -ant State Recv-Q Send-Q Local Address:Port Peer Address:Port LISTEN 0 511 *:80 *:* LISTEN 0 128 *:22 *:* ESTAB 0 0 127.0.0.1:56726 127.0.0.1:4505 ''' remotes = set() valid = False try: data = subprocess.check_output(['ss', '-ant']) # pylint: disable=minimum-python-version except subprocess.CalledProcessError: log.error('Failed ss') raise except OSError: # not command "No such file or directory" return None lines = salt.utils.stringutils.to_str(data).split('\n') for line in lines: if 'Address:Port' in line: # ss tools may not be valid valid = True continue elif 'ESTAB' not in line: continue chunks = line.split() local_host, local_port = chunks[3].split(':', 1) remote_host, remote_port = chunks[4].split(':', 1) if which_end == 'remote_port' and int(remote_port) != port: continue if which_end == 'local_port' and int(local_port) != port: continue remotes.add(remote_host) if valid is False: remotes = None return remotes def _sunos_remotes_on(port, which_end): ''' SunOS specific helper function. Returns set of ipv4 host addresses of remote established connections on local or remote tcp port. Parses output of shell 'netstat' to get connections [root@salt-master ~]# netstat -f inet -n TCP: IPv4 Local Address Remote Address Swind Send-Q Rwind Recv-Q State -------------------- -------------------- ----- ------ ----- ------ ----------- 10.0.0.101.4505 10.0.0.1.45329 1064800 0 1055864 0 ESTABLISHED 10.0.0.101.4505 10.0.0.100.50798 1064800 0 1055864 0 ESTABLISHED ''' remotes = set() try: data = subprocess.check_output(['netstat', '-f', 'inet', '-n']) # pylint: disable=minimum-python-version except subprocess.CalledProcessError: log.error('Failed netstat') raise lines = salt.utils.stringutils.to_str(data).split('\n') for line in lines: if 'ESTABLISHED' not in line: continue chunks = line.split() local_host, local_port = chunks[0].rsplit('.', 1) remote_host, remote_port = chunks[1].rsplit('.', 1) if which_end == 'remote_port' and int(remote_port) != port: continue if which_end == 'local_port' and int(local_port) != port: continue remotes.add(remote_host) return remotes def _freebsd_remotes_on(port, which_end): ''' Returns set of ipv4 host addresses of remote established connections on local tcp port port. Parses output of shell 'sockstat' (FreeBSD) to get connections $ sudo sockstat -4 USER COMMAND PID FD PROTO LOCAL ADDRESS FOREIGN ADDRESS root python2.7 1456 29 tcp4 *:4505 *:* root python2.7 1445 17 tcp4 *:4506 *:* root python2.7 1294 14 tcp4 127.0.0.1:11813 127.0.0.1:4505 root python2.7 1294 41 tcp4 127.0.0.1:61115 127.0.0.1:4506 $ sudo sockstat -4 -c -p 4506 USER COMMAND PID FD PROTO LOCAL ADDRESS FOREIGN ADDRESS root python2.7 1294 41 tcp4 127.0.0.1:61115 127.0.0.1:4506 ''' port = int(port) remotes = set() try: cmd = salt.utils.args.shlex_split('sockstat -4 -c -p {0}'.format(port)) data = subprocess.check_output(cmd) # pylint: disable=minimum-python-version except subprocess.CalledProcessError as ex: log.error('Failed "sockstat" with returncode = %s', ex.returncode) raise lines = salt.utils.stringutils.to_str(data).split('\n') for line in lines: chunks = line.split() if not chunks: continue # ['root', 'python2.7', '1456', '37', 'tcp4', # '127.0.0.1:4505-', '127.0.0.1:55703'] # print chunks if 'COMMAND' in chunks[1]: continue # ignore header if len(chunks) < 2: continue # sockstat -4 -c -p 4506 does this with high PIDs: # USER COMMAND PID FD PROTO LOCAL ADDRESS FOREIGN ADDRESS # salt-master python2.781106 35 tcp4 192.168.12.34:4506 192.168.12.45:60143 local = chunks[-2] remote = chunks[-1] lhost, lport = local.split(':') rhost, rport = remote.split(':') if which_end == 'local' and int(lport) != port: # ignore if local port not port continue if which_end == 'remote' and int(rport) != port: # ignore if remote port not port continue remotes.add(rhost) return remotes def _netbsd_remotes_on(port, which_end): ''' Returns set of ipv4 host addresses of remote established connections on local tcp port port. Parses output of shell 'sockstat' (NetBSD) to get connections $ sudo sockstat -4 -n USER COMMAND PID FD PROTO LOCAL ADDRESS FOREIGN ADDRESS root python2.7 1456 29 tcp *.4505 *.* root python2.7 1445 17 tcp *.4506 *.* root python2.7 1294 14 tcp 127.0.0.1.11813 127.0.0.1.4505 root python2.7 1294 41 tcp 127.0.0.1.61115 127.0.0.1.4506 $ sudo sockstat -4 -c -n -p 4506 USER COMMAND PID FD PROTO LOCAL ADDRESS FOREIGN ADDRESS root python2.7 1294 41 tcp 127.0.0.1.61115 127.0.0.1.4506 ''' port = int(port) remotes = set() try: cmd = salt.utils.args.shlex_split('sockstat -4 -c -n -p {0}'.format(port)) data = subprocess.check_output(cmd) # pylint: disable=minimum-python-version except subprocess.CalledProcessError as ex: log.error('Failed "sockstat" with returncode = %s', ex.returncode) raise lines = salt.utils.stringutils.to_str(data).split('\n') for line in lines: chunks = line.split() if not chunks: continue # ['root', 'python2.7', '1456', '37', 'tcp', # '127.0.0.1.4505-', '127.0.0.1.55703'] # print chunks if 'COMMAND' in chunks[1]: continue # ignore header if len(chunks) < 2: continue local = chunks[5].split('.') lport = local.pop() lhost = '.'.join(local) remote = chunks[6].split('.') rport = remote.pop() rhost = '.'.join(remote) if which_end == 'local' and int(lport) != port: # ignore if local port not port continue if which_end == 'remote' and int(rport) != port: # ignore if remote port not port continue remotes.add(rhost) return remotes def _openbsd_remotes_on(port, which_end): ''' OpenBSD specific helper function. Returns set of ipv4 host addresses of remote established connections on local or remote tcp port. Parses output of shell 'netstat' to get connections $ netstat -nf inet Active Internet connections Proto Recv-Q Send-Q Local Address Foreign Address (state) tcp 0 0 10.0.0.101.4505 10.0.0.1.45329 ESTABLISHED tcp 0 0 10.0.0.101.4505 10.0.0.100.50798 ESTABLISHED ''' remotes = set() try: data = subprocess.check_output(['netstat', '-nf', 'inet']) # pylint: disable=minimum-python-version except subprocess.CalledProcessError: log.error('Failed netstat') raise lines = data.split('\n') for line in lines: if 'ESTABLISHED' not in line: continue chunks = line.split() local_host, local_port = chunks[3].rsplit('.', 1) remote_host, remote_port = chunks[4].rsplit('.', 1) if which_end == 'remote_port' and int(remote_port) != port: continue if which_end == 'local_port' and int(local_port) != port: continue remotes.add(remote_host) return remotes def _windows_remotes_on(port, which_end): r''' Windows specific helper function. Returns set of ipv4 host addresses of remote established connections on local or remote tcp port. Parses output of shell 'netstat' to get connections C:\>netstat -n Active Connections Proto Local Address Foreign Address State TCP 10.2.33.17:3007 130.164.12.233:10123 ESTABLISHED TCP 10.2.33.17:3389 130.164.30.5:10378 ESTABLISHED ''' remotes = set() try: data = subprocess.check_output(['netstat', '-n']) # pylint: disable=minimum-python-version except subprocess.CalledProcessError: log.error('Failed netstat') raise lines = salt.utils.stringutils.to_str(data).split('\n') for line in lines: if 'ESTABLISHED' not in line: continue chunks = line.split() local_host, local_port = chunks[1].rsplit(':', 1) remote_host, remote_port = chunks[2].rsplit(':', 1) if which_end == 'remote_port' and int(remote_port) != port: continue if which_end == 'local_port' and int(local_port) != port: continue remotes.add(remote_host) return remotes def _linux_remotes_on(port, which_end): ''' Linux specific helper function. Returns set of ip host addresses of remote established connections on local tcp port port. Parses output of shell 'lsof' to get connections $ sudo lsof -iTCP:4505 -n COMMAND PID USER FD TYPE DEVICE SIZE/OFF NODE NAME Python 9971 root 35u IPv4 0x18a8464a29ca329d 0t0 TCP *:4505 (LISTEN) Python 9971 root 37u IPv4 0x18a8464a29b2b29d 0t0 TCP 127.0.0.1:4505->127.0.0.1:55703 (ESTABLISHED) Python 10152 root 22u IPv4 0x18a8464a29c8cab5 0t0 TCP 127.0.0.1:55703->127.0.0.1:4505 (ESTABLISHED) Python 10153 root 22u IPv4 0x18a8464a29c8cab5 0t0 TCP [fe80::249a]:4505->[fe80::150]:59367 (ESTABLISHED) ''' remotes = set() try: data = subprocess.check_output( ['lsof', '-iTCP:{0:d}'.format(port), '-n', '-P'] # pylint: disable=minimum-python-version ) except subprocess.CalledProcessError as ex: if ex.returncode == 1: # Lsof return 1 if any error was detected, including the failure # to locate Internet addresses, and it is not an error in this case. log.warning('"lsof" returncode = 1, likely no active TCP sessions.') return remotes log.error('Failed "lsof" with returncode = %s', ex.returncode) raise lines = salt.utils.stringutils.to_str(data).split('\n') for line in lines: chunks = line.split() if not chunks: continue # ['Python', '9971', 'root', '37u', 'IPv4', '0x18a8464a29b2b29d', '0t0', # 'TCP', '127.0.0.1:4505->127.0.0.1:55703', '(ESTABLISHED)'] # print chunks if 'COMMAND' in chunks[0]: continue # ignore header if 'ESTABLISHED' not in chunks[-1]: continue # ignore if not ESTABLISHED # '127.0.0.1:4505->127.0.0.1:55703' local, remote = chunks[8].split('->') _, lport = local.rsplit(':', 1) rhost, rport = remote.rsplit(':', 1) if which_end == 'remote_port' and int(rport) != port: continue if which_end == 'local_port' and int(lport) != port: continue remotes.add(rhost.strip("[]")) return remotes def _aix_remotes_on(port, which_end): ''' AIX specific helper function. Returns set of ipv4 host addresses of remote established connections on local or remote tcp port. Parses output of shell 'netstat' to get connections root@la68pp002_pub:/opt/salt/lib/python2.7/site-packages/salt/modules# netstat -f inet -n Active Internet connections Proto Recv-Q Send-Q Local Address Foreign Address (state) tcp4 0 0 172.29.149.95.50093 209.41.78.13.4505 ESTABLISHED tcp4 0 0 127.0.0.1.9514 *.* LISTEN tcp4 0 0 127.0.0.1.9515 *.* LISTEN tcp4 0 0 127.0.0.1.199 127.0.0.1.32779 ESTABLISHED tcp4 0 0 127.0.0.1.32779 127.0.0.1.199 ESTABLISHED tcp4 0 40 172.29.149.95.22 172.29.96.83.41022 ESTABLISHED tcp4 0 0 172.29.149.95.22 172.29.96.83.41032 ESTABLISHED tcp4 0 0 127.0.0.1.32771 127.0.0.1.32775 ESTABLISHED tcp 0 0 127.0.0.1.32775 127.0.0.1.32771 ESTABLISHED tcp4 0 0 127.0.0.1.32771 127.0.0.1.32776 ESTABLISHED tcp 0 0 127.0.0.1.32776 127.0.0.1.32771 ESTABLISHED tcp4 0 0 127.0.0.1.32771 127.0.0.1.32777 ESTABLISHED tcp 0 0 127.0.0.1.32777 127.0.0.1.32771 ESTABLISHED tcp4 0 0 127.0.0.1.32771 127.0.0.1.32778 ESTABLISHED tcp 0 0 127.0.0.1.32778 127.0.0.1.32771 ESTABLISHED ''' remotes = set() try: data = subprocess.check_output(['netstat', '-f', 'inet', '-n']) # pylint: disable=minimum-python-version except subprocess.CalledProcessError: log.error('Failed netstat') raise lines = salt.utils.stringutils.to_str(data).split('\n') for line in lines: if 'ESTABLISHED' not in line: continue chunks = line.split() local_host, local_port = chunks[3].rsplit('.', 1) remote_host, remote_port = chunks[4].rsplit('.', 1) if which_end == 'remote_port' and int(remote_port) != port: continue if which_end == 'local_port' and int(local_port) != port: continue remotes.add(remote_host) return remotes @jinja_filter('gen_mac') @jinja_filter('mac_str_to_bytes') def mac_str_to_bytes(mac_str): ''' Convert a MAC address string into bytes. Works with or without separators: b1 = mac_str_to_bytes('08:00:27:13:69:77') b2 = mac_str_to_bytes('080027136977') assert b1 == b2 assert isinstance(b1, bytes) ''' if len(mac_str) == 12: pass elif len(mac_str) == 17: sep = mac_str[2] mac_str = mac_str.replace(sep, '') else: raise ValueError('Invalid MAC address') chars = (int(mac_str[s:s+2], 16) for s in range(0, 12, 2)) return bytes(chars) if six.PY3 else b''.join(chr(x) for x in chars) def refresh_dns(): ''' issue #21397: force glibc to re-read resolv.conf ''' try: res_init() except NameError: # Exception raised loading the library, thus res_init is not defined pass @jinja_filter('connection_check') def connection_check(addr, port=80, safe=False, ipv6=None): ''' Provides a convenient alias for the dns_check filter. ''' return dns_check(addr, port, safe, ipv6) @jinja_filter('dns_check') def dns_check(addr, port=80, safe=False, ipv6=None, attempt_connect=True): ''' Return the ip resolved by dns, but do not exit on failure, only raise an exception. Obeys system preference for IPv4/6 address resolution - this can be overridden by the ipv6 flag. Tries to connect to the address before considering it useful. If no address can be reached, the first one resolved is used as a fallback. ''' error = False lookup = addr seen_ipv6 = False family = socket.AF_INET6 if ipv6 else socket.AF_INET if ipv6 is False else socket.AF_UNSPEC hostnames = [] try: refresh_dns() hostnames = socket.getaddrinfo(addr, port, family, socket.SOCK_STREAM) except TypeError: err = ('Attempt to resolve address \'{0}\' failed. Invalid or unresolveable address').format(lookup) raise SaltSystemExit(code=42, msg=err) except socket.error: error = True # If ipv6 is set to True, attempt another lookup using the IPv4 family, # just in case we're attempting to lookup an IPv4 IP # as an IPv6 hostname. if error and ipv6: try: refresh_dns() hostnames = socket.getaddrinfo(addr, port, socket.AF_INET, socket.SOCK_STREAM) except TypeError: err = ('Attempt to resolve address \'{0}\' failed. Invalid or unresolveable address').format(lookup) raise SaltSystemExit(code=42, msg=err) except socket.error: error = True try: if not hostnames: error = True else: resolved = False candidates = [] for h in hostnames: # Input is IP address, passed through unchanged, just return it if h[4][0] == addr: resolved = salt.utils.zeromq.ip_bracket(addr) break candidate_addr = salt.utils.zeromq.ip_bracket(h[4][0]) # sometimes /etc/hosts contains ::1 localhost if not ipv6 and candidate_addr == '[::1]': continue candidates.append(candidate_addr) if attempt_connect: try: s = socket.socket(h[0], socket.SOCK_STREAM) s.settimeout(2) s.connect((candidate_addr.strip('[]'), h[4][1])) s.close() resolved = candidate_addr break except socket.error: pass if not resolved: if candidates: resolved = candidates[0] else: error = True except TypeError: err = ('Attempt to resolve address \'{0}\' failed. Invalid or unresolveable address').format(lookup) raise SaltSystemExit(code=42, msg=err) except socket.error: error = True if error: err = ('DNS lookup or connection check of \'{0}\' failed.').format(addr) if safe: if salt.log.is_console_configured(): # If logging is not configured it also means that either # the master or minion instance calling this hasn't even # started running log.error(err) raise SaltClientError() raise SaltSystemExit(code=42, msg=err) return resolved def parse_host_port(host_port): """ Takes a string argument specifying host or host:port. Returns a (hostname, port) or (ip_address, port) tuple. If no port is given, the second (port) element of the returned tuple will be None. host:port argument, for example, is accepted in the forms of: - hostname - hostname:1234 - hostname.domain.tld - hostname.domain.tld:5678 - [1234::5]:5678 - 1234::5 - 10.11.12.13:4567 - 10.11.12.13 """ host, port = None, None # default _s_ = host_port[:] if _s_[0] == "[": if "]" in host_port: host, _s_ = _s_.lstrip("[").rsplit("]", 1) host = ipaddress.IPv6Address(host).compressed if _s_[0] == ":": port = int(_s_.lstrip(":")) else: if len(_s_) > 1: raise ValueError('found ambiguous "{}" port in "{}"'.format(_s_, host_port)) else: if _s_.count(":") == 1: host, _hostport_separator_, port = _s_.partition(":") try: port = int(port) except ValueError as _e_: log.error('host_port "%s" port value "%s" is not an integer.', host_port, port) raise _e_ else: host = _s_ try: if not isinstance(host, ipaddress._BaseAddress): host_ip = ipaddress.ip_address(host).compressed host = host_ip except ValueError: log.debug('"%s" Not an IP address? Assuming it is a hostname.', host) if host != sanitize_host(host): log.error('bad hostname: "%s"', host) raise ValueError('bad hostname: "{}"'.format(host)) return host, port def is_fqdn(hostname): """ Verify if hostname conforms to be a FQDN. :param hostname: text string with the name of the host :return: bool, True if hostname is correct FQDN, False otherwise """ compliant = re.compile(r"(?!-)[A-Z\d\-\_]{1,63}(?<!-)$", re.IGNORECASE) return "." in hostname and len(hostname) < 0xff and all(compliant.match(x) for x in hostname.rstrip(".").split("."))
saltstack/salt
salt/utils/network.py
mac_str_to_bytes
python
def mac_str_to_bytes(mac_str): ''' Convert a MAC address string into bytes. Works with or without separators: b1 = mac_str_to_bytes('08:00:27:13:69:77') b2 = mac_str_to_bytes('080027136977') assert b1 == b2 assert isinstance(b1, bytes) ''' if len(mac_str) == 12: pass elif len(mac_str) == 17: sep = mac_str[2] mac_str = mac_str.replace(sep, '') else: raise ValueError('Invalid MAC address') chars = (int(mac_str[s:s+2], 16) for s in range(0, 12, 2)) return bytes(chars) if six.PY3 else b''.join(chr(x) for x in chars)
Convert a MAC address string into bytes. Works with or without separators: b1 = mac_str_to_bytes('08:00:27:13:69:77') b2 = mac_str_to_bytes('080027136977') assert b1 == b2 assert isinstance(b1, bytes)
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/network.py#L1872-L1889
null
# -*- coding: utf-8 -*- ''' Define some generic socket functions for network modules ''' # Import python libs from __future__ import absolute_import, unicode_literals, print_function import itertools import os import re import types import socket import logging import platform import random import subprocess from string import ascii_letters, digits # Import 3rd-party libs from salt.ext import six from salt.ext.six.moves import range # pylint: disable=import-error,redefined-builtin # Attempt to import wmi try: import wmi import salt.utils.winapi except ImportError: pass # Import salt libs import salt.utils.args import salt.utils.files import salt.utils.path import salt.utils.platform import salt.utils.stringutils import salt.utils.zeromq from salt._compat import ipaddress from salt.exceptions import SaltClientError, SaltSystemExit from salt.utils.decorators.jinja import jinja_filter from salt.utils.versions import LooseVersion # inet_pton does not exist in Windows, this is a workaround if salt.utils.platform.is_windows(): from salt.ext import win_inet_pton # pylint: disable=unused-import log = logging.getLogger(__name__) try: import ctypes import ctypes.util libc = ctypes.cdll.LoadLibrary(ctypes.util.find_library("c")) res_init = libc.__res_init except (ImportError, OSError, AttributeError, TypeError): pass # pylint: disable=C0103 def sanitize_host(host): ''' Sanitize host string. https://tools.ietf.org/html/rfc1123#section-2.1 ''' RFC952_characters = ascii_letters + digits + ".-" return "".join([c for c in host[0:255] if c in RFC952_characters]) def isportopen(host, port): ''' Return status of a port ''' if not 1 <= int(port) <= 65535: return False sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) out = sock.connect_ex((sanitize_host(host), int(port))) return out def host_to_ips(host): ''' Returns a list of IP addresses of a given hostname or None if not found. ''' ips = [] try: for family, socktype, proto, canonname, sockaddr in socket.getaddrinfo( host, 0, socket.AF_UNSPEC, socket.SOCK_STREAM): if family == socket.AF_INET: ip, port = sockaddr elif family == socket.AF_INET6: ip, port, flow_info, scope_id = sockaddr ips.append(ip) if not ips: ips = None except Exception: ips = None return ips def _generate_minion_id(): ''' Get list of possible host names and convention names. :return: ''' # There are three types of hostnames: # 1. Network names. How host is accessed from the network. # 2. Host aliases. They might be not available in all the network or only locally (/etc/hosts) # 3. Convention names, an internal nodename. class DistinctList(list): ''' List, which allows one to append only distinct objects. Needs to work on Python 2.6, because of collections.OrderedDict only since 2.7 version. Override 'filter()' for custom filtering. ''' localhost_matchers = [r'localhost.*', r'ip6-.*', r'127[.]\d', r'0\.0\.0\.0', r'::1.*', r'ipv6-.*', r'fe00::.*', r'fe02::.*', r'1.0.0.*.ip6.arpa'] def append(self, p_object): if p_object and p_object not in self and not self.filter(p_object): super(DistinctList, self).append(p_object) return self def extend(self, iterable): for obj in iterable: self.append(obj) return self def filter(self, element): 'Returns True if element needs to be filtered' for rgx in self.localhost_matchers: if re.match(rgx, element): return True def first(self): return self and self[0] or None hostname = socket.gethostname() hosts = DistinctList().append( salt.utils.stringutils.to_unicode(socket.getfqdn(salt.utils.stringutils.to_bytes(hostname))) ).append(platform.node()).append(hostname) if not hosts: try: for a_nfo in socket.getaddrinfo(hosts.first() or 'localhost', None, socket.AF_INET, socket.SOCK_RAW, socket.IPPROTO_IP, socket.AI_CANONNAME): if len(a_nfo) > 3: hosts.append(a_nfo[3]) except socket.gaierror: log.warning('Cannot resolve address %s info via socket: %s', hosts.first() or 'localhost (N/A)', socket.gaierror) # Universal method for everywhere (Linux, Slowlaris, Windows etc) for f_name in ('/etc/hostname', '/etc/nodename', '/etc/hosts', r'{win}\system32\drivers\etc\hosts'.format(win=os.getenv('WINDIR'))): try: with salt.utils.files.fopen(f_name) as f_hdl: for line in f_hdl: line = salt.utils.stringutils.to_unicode(line) hst = line.strip().split('#')[0].strip().split() if hst: if hst[0][:4] in ('127.', '::1') or len(hst) == 1: hosts.extend(hst) except IOError: pass # include public and private ipaddresses return hosts.extend([addr for addr in ip_addrs() if not ipaddress.ip_address(addr).is_loopback]) def generate_minion_id(): ''' Return only first element of the hostname from all possible list. :return: ''' try: ret = salt.utils.stringutils.to_unicode(_generate_minion_id().first()) except TypeError: ret = None return ret or 'localhost' def get_socket(addr, type=socket.SOCK_STREAM, proto=0): ''' Return a socket object for the addr IP-version agnostic ''' version = ipaddress.ip_address(addr).version if version == 4: family = socket.AF_INET elif version == 6: family = socket.AF_INET6 return socket.socket(family, type, proto) def get_fqhostname(): ''' Returns the fully qualified hostname ''' # try getaddrinfo() fqdn = None try: addrinfo = socket.getaddrinfo( socket.gethostname(), 0, socket.AF_UNSPEC, socket.SOCK_STREAM, socket.SOL_TCP, socket.AI_CANONNAME ) for info in addrinfo: # info struct [family, socktype, proto, canonname, sockaddr] # On Windows `canonname` can be an empty string # This can cause the function to return `None` if len(info) > 3 and info[3]: fqdn = info[3] break except socket.gaierror: pass # NOTE: this used to log.error() but it was later disabled except socket.error as err: log.debug('socket.getaddrinfo() failure while finding fqdn: %s', err) if fqdn is None: fqdn = socket.getfqdn() return fqdn def ip_to_host(ip): ''' Returns the hostname of a given IP ''' try: hostname, aliaslist, ipaddrlist = socket.gethostbyaddr(ip) except Exception as exc: log.debug('salt.utils.network.ip_to_host(%r) failed: %s', ip, exc) hostname = None return hostname # pylint: enable=C0103 def is_reachable_host(entity_name): ''' Returns a bool telling if the entity name is a reachable host (IPv4/IPv6/FQDN/etc). :param hostname: :return: ''' try: assert type(socket.getaddrinfo(entity_name, 0, 0, 0, 0)) == list ret = True except socket.gaierror: ret = False return ret def is_ip(ip): ''' Returns a bool telling if the passed IP is a valid IPv4 or IPv6 address. ''' return is_ipv4(ip) or is_ipv6(ip) def is_ipv4(ip): ''' Returns a bool telling if the value passed to it was a valid IPv4 address ''' try: return ipaddress.ip_address(ip).version == 4 except ValueError: return False def is_ipv6(ip): ''' Returns a bool telling if the value passed to it was a valid IPv6 address ''' try: return ipaddress.ip_address(ip).version == 6 except ValueError: return False def is_subnet(cidr): ''' Returns a bool telling if the passed string is an IPv4 or IPv6 subnet ''' return is_ipv4_subnet(cidr) or is_ipv6_subnet(cidr) def is_ipv4_subnet(cidr): ''' Returns a bool telling if the passed string is an IPv4 subnet ''' try: return '/' in cidr and bool(ipaddress.IPv4Network(cidr)) except Exception: return False def is_ipv6_subnet(cidr): ''' Returns a bool telling if the passed string is an IPv6 subnet ''' try: return '/' in cidr and bool(ipaddress.IPv6Network(cidr)) except Exception: return False @jinja_filter('is_ip') def is_ip_filter(ip, options=None): ''' Returns a bool telling if the passed IP is a valid IPv4 or IPv6 address. ''' return is_ipv4_filter(ip, options=options) or is_ipv6_filter(ip, options=options) def _ip_options_global(ip_obj, version): return not ip_obj.is_private def _ip_options_multicast(ip_obj, version): return ip_obj.is_multicast def _ip_options_loopback(ip_obj, version): return ip_obj.is_loopback def _ip_options_link_local(ip_obj, version): return ip_obj.is_link_local def _ip_options_private(ip_obj, version): return ip_obj.is_private def _ip_options_reserved(ip_obj, version): return ip_obj.is_reserved def _ip_options_site_local(ip_obj, version): if version == 6: return ip_obj.is_site_local return False def _ip_options_unspecified(ip_obj, version): return ip_obj.is_unspecified def _ip_options(ip_obj, version, options=None): # will process and IP options options_fun_map = { 'global': _ip_options_global, 'link-local': _ip_options_link_local, 'linklocal': _ip_options_link_local, 'll': _ip_options_link_local, 'link_local': _ip_options_link_local, 'loopback': _ip_options_loopback, 'lo': _ip_options_loopback, 'multicast': _ip_options_multicast, 'private': _ip_options_private, 'public': _ip_options_global, 'reserved': _ip_options_reserved, 'site-local': _ip_options_site_local, 'sl': _ip_options_site_local, 'site_local': _ip_options_site_local, 'unspecified': _ip_options_unspecified } if not options: return six.text_type(ip_obj) # IP version already checked options_list = [option.strip() for option in options.split(',')] for option, fun in options_fun_map.items(): if option in options_list: fun_res = fun(ip_obj, version) if not fun_res: return None # stop at first failed test # else continue return six.text_type(ip_obj) def _is_ipv(ip, version, options=None): if not version: version = 4 if version not in (4, 6): return None try: ip_obj = ipaddress.ip_address(ip) except ValueError: # maybe it is an IP network try: ip_obj = ipaddress.ip_interface(ip) except ValueError: # nope, still not :( return None if not ip_obj.version == version: return None # has the right version, let's move on return _ip_options(ip_obj, version, options=options) @jinja_filter('is_ipv4') def is_ipv4_filter(ip, options=None): ''' Returns a bool telling if the value passed to it was a valid IPv4 address. ip The IP address. net: False Consider IP addresses followed by netmask. options CSV of options regarding the nature of the IP address. E.g.: loopback, multicast, private etc. ''' _is_ipv4 = _is_ipv(ip, 4, options=options) return isinstance(_is_ipv4, six.string_types) @jinja_filter('is_ipv6') def is_ipv6_filter(ip, options=None): ''' Returns a bool telling if the value passed to it was a valid IPv6 address. ip The IP address. net: False Consider IP addresses followed by netmask. options CSV of options regarding the nature of the IP address. E.g.: loopback, multicast, private etc. ''' _is_ipv6 = _is_ipv(ip, 6, options=options) return isinstance(_is_ipv6, six.string_types) def _ipv_filter(value, version, options=None): if version not in (4, 6): return if isinstance(value, (six.string_types, six.text_type, six.binary_type)): return _is_ipv(value, version, options=options) # calls is_ipv4 or is_ipv6 for `value` elif isinstance(value, (list, tuple, types.GeneratorType)): # calls is_ipv4 or is_ipv6 for each element in the list # os it filters and returns only those elements having the desired IP version return [ _is_ipv(addr, version, options=options) for addr in value if _is_ipv(addr, version, options=options) is not None ] return None @jinja_filter('ipv4') def ipv4(value, options=None): ''' Filters a list and returns IPv4 values only. ''' return _ipv_filter(value, 4, options=options) @jinja_filter('ipv6') def ipv6(value, options=None): ''' Filters a list and returns IPv6 values only. ''' return _ipv_filter(value, 6, options=options) @jinja_filter('ipaddr') def ipaddr(value, options=None): ''' Filters and returns only valid IP objects. ''' ipv4_obj = ipv4(value, options=options) ipv6_obj = ipv6(value, options=options) if ipv4_obj is None or ipv6_obj is None: # an IP address can be either IPv4 either IPv6 # therefofe if the value passed as arg is not a list, at least one of the calls above will return None # if one of them is none, means that we should return only one of them return ipv4_obj or ipv6_obj # one of them else: return ipv4_obj + ipv6_obj # extend lists def _filter_ipaddr(value, options, version=None): ipaddr_filter_out = None if version: if version == 4: ipaddr_filter_out = ipv4(value, options) elif version == 6: ipaddr_filter_out = ipv6(value, options) else: ipaddr_filter_out = ipaddr(value, options) if not ipaddr_filter_out: return if not isinstance(ipaddr_filter_out, (list, tuple, types.GeneratorType)): ipaddr_filter_out = [ipaddr_filter_out] return ipaddr_filter_out @jinja_filter('ip_host') def ip_host(value, options=None, version=None): ''' Returns the interfaces IP address, e.g.: 192.168.0.1/28. ''' ipaddr_filter_out = _filter_ipaddr(value, options=options, version=version) if not ipaddr_filter_out: return if not isinstance(value, (list, tuple, types.GeneratorType)): return six.text_type(ipaddress.ip_interface(ipaddr_filter_out[0])) return [six.text_type(ipaddress.ip_interface(ip_a)) for ip_a in ipaddr_filter_out] def _network_hosts(ip_addr_entry): return [ six.text_type(host) for host in ipaddress.ip_network(ip_addr_entry, strict=False).hosts() ] @jinja_filter('network_hosts') def network_hosts(value, options=None, version=None): ''' Return the list of hosts within a network. .. note:: When running this command with a large IPv6 network, the command will take a long time to gather all of the hosts. ''' ipaddr_filter_out = _filter_ipaddr(value, options=options, version=version) if not ipaddr_filter_out: return if not isinstance(value, (list, tuple, types.GeneratorType)): return _network_hosts(ipaddr_filter_out[0]) return [ _network_hosts(ip_a) for ip_a in ipaddr_filter_out ] def _network_size(ip_addr_entry): return ipaddress.ip_network(ip_addr_entry, strict=False).num_addresses @jinja_filter('network_size') def network_size(value, options=None, version=None): ''' Get the size of a network. ''' ipaddr_filter_out = _filter_ipaddr(value, options=options, version=version) if not ipaddr_filter_out: return if not isinstance(value, (list, tuple, types.GeneratorType)): return _network_size(ipaddr_filter_out[0]) return [ _network_size(ip_a) for ip_a in ipaddr_filter_out ] def natural_ipv4_netmask(ip, fmt='prefixlen'): ''' Returns the "natural" mask of an IPv4 address ''' bits = _ipv4_to_bits(ip) if bits.startswith('11'): mask = '24' elif bits.startswith('1'): mask = '16' else: mask = '8' if fmt == 'netmask': return cidr_to_ipv4_netmask(mask) else: return '/' + mask def rpad_ipv4_network(ip): ''' Returns an IP network address padded with zeros. Ex: '192.168.3' -> '192.168.3.0' '10.209' -> '10.209.0.0' ''' return '.'.join(itertools.islice(itertools.chain(ip.split('.'), '0000'), 0, 4)) def cidr_to_ipv4_netmask(cidr_bits): ''' Returns an IPv4 netmask ''' try: cidr_bits = int(cidr_bits) if not 1 <= cidr_bits <= 32: return '' except ValueError: return '' netmask = '' for idx in range(4): if idx: netmask += '.' if cidr_bits >= 8: netmask += '255' cidr_bits -= 8 else: netmask += '{0:d}'.format(256 - (2 ** (8 - cidr_bits))) cidr_bits = 0 return netmask def _number_of_set_bits_to_ipv4_netmask(set_bits): # pylint: disable=C0103 ''' Returns an IPv4 netmask from the integer representation of that mask. Ex. 0xffffff00 -> '255.255.255.0' ''' return cidr_to_ipv4_netmask(_number_of_set_bits(set_bits)) # pylint: disable=C0103 def _number_of_set_bits(x): ''' Returns the number of bits that are set in a 32bit int ''' # Taken from http://stackoverflow.com/a/4912729. Many thanks! x -= (x >> 1) & 0x55555555 x = ((x >> 2) & 0x33333333) + (x & 0x33333333) x = ((x >> 4) + x) & 0x0f0f0f0f x += x >> 8 x += x >> 16 return x & 0x0000003f # pylint: enable=C0103 def _interfaces_ip(out): ''' Uses ip to return a dictionary of interfaces with various information about each (up/down state, ip address, netmask, and hwaddr) ''' ret = dict() def parse_network(value, cols): ''' Return a tuple of ip, netmask, broadcast based on the current set of cols ''' brd = None scope = None if '/' in value: # we have a CIDR in this address ip, cidr = value.split('/') # pylint: disable=C0103 else: ip = value # pylint: disable=C0103 cidr = 32 if type_ == 'inet': mask = cidr_to_ipv4_netmask(int(cidr)) if 'brd' in cols: brd = cols[cols.index('brd') + 1] elif type_ == 'inet6': mask = cidr if 'scope' in cols: scope = cols[cols.index('scope') + 1] return (ip, mask, brd, scope) groups = re.compile('\r?\n\\d').split(out) for group in groups: iface = None data = dict() for line in group.splitlines(): if ' ' not in line: continue match = re.match(r'^\d*:\s+([\w.\-]+)(?:@)?([\w.\-]+)?:\s+<(.+)>', line) if match: iface, parent, attrs = match.groups() if 'UP' in attrs.split(','): data['up'] = True else: data['up'] = False if parent: data['parent'] = parent continue cols = line.split() if len(cols) >= 2: type_, value = tuple(cols[0:2]) iflabel = cols[-1:][0] if type_ in ('inet', 'inet6'): if 'secondary' not in cols: ipaddr, netmask, broadcast, scope = parse_network(value, cols) if type_ == 'inet': if 'inet' not in data: data['inet'] = list() addr_obj = dict() addr_obj['address'] = ipaddr addr_obj['netmask'] = netmask addr_obj['broadcast'] = broadcast addr_obj['label'] = iflabel data['inet'].append(addr_obj) elif type_ == 'inet6': if 'inet6' not in data: data['inet6'] = list() addr_obj = dict() addr_obj['address'] = ipaddr addr_obj['prefixlen'] = netmask addr_obj['scope'] = scope data['inet6'].append(addr_obj) else: if 'secondary' not in data: data['secondary'] = list() ip_, mask, brd, scp = parse_network(value, cols) data['secondary'].append({ 'type': type_, 'address': ip_, 'netmask': mask, 'broadcast': brd, 'label': iflabel, }) del ip_, mask, brd, scp elif type_.startswith('link'): data['hwaddr'] = value if iface: ret[iface] = data del iface, data return ret def _interfaces_ifconfig(out): ''' Uses ifconfig to return a dictionary of interfaces with various information about each (up/down state, ip address, netmask, and hwaddr) ''' ret = dict() piface = re.compile(r'^([^\s:]+)') pmac = re.compile('.*?(?:HWaddr|ether|address:|lladdr) ([0-9a-fA-F:]+)') if salt.utils.platform.is_sunos(): pip = re.compile(r'.*?(?:inet\s+)([0-9]+\.[0-9]+\.[0-9]+\.[0-9]+)(.*)') pip6 = re.compile('.*?(?:inet6 )([0-9a-fA-F:]+)') pmask6 = re.compile(r'.*?(?:inet6 [0-9a-fA-F:]+/(\d+)).*') else: pip = re.compile(r'.*?(?:inet addr:|inet [^\d]*)(.*?)\s') pip6 = re.compile('.*?(?:inet6 addr: (.*?)/|inet6 )([0-9a-fA-F:]+)') pmask6 = re.compile(r'.*?(?:inet6 addr: [0-9a-fA-F:]+/(\d+)|prefixlen (\d+))(?: Scope:([a-zA-Z]+)| scopeid (0x[0-9a-fA-F]))?') pmask = re.compile(r'.*?(?:Mask:|netmask )(?:((?:0x)?[0-9a-fA-F]{8})|([\d\.]+))') pupdown = re.compile('UP') pbcast = re.compile(r'.*?(?:Bcast:|broadcast )([\d\.]+)') groups = re.compile('\r?\n(?=\\S)').split(out) for group in groups: data = dict() iface = '' updown = False for line in group.splitlines(): miface = piface.match(line) mmac = pmac.match(line) mip = pip.match(line) mip6 = pip6.match(line) mupdown = pupdown.search(line) if miface: iface = miface.group(1) if mmac: data['hwaddr'] = mmac.group(1) if salt.utils.platform.is_sunos(): expand_mac = [] for chunk in data['hwaddr'].split(':'): expand_mac.append('0{0}'.format(chunk) if len(chunk) < 2 else '{0}'.format(chunk)) data['hwaddr'] = ':'.join(expand_mac) if mip: if 'inet' not in data: data['inet'] = list() addr_obj = dict() addr_obj['address'] = mip.group(1) mmask = pmask.match(line) if mmask: if mmask.group(1): mmask = _number_of_set_bits_to_ipv4_netmask( int(mmask.group(1), 16)) else: mmask = mmask.group(2) addr_obj['netmask'] = mmask mbcast = pbcast.match(line) if mbcast: addr_obj['broadcast'] = mbcast.group(1) data['inet'].append(addr_obj) if mupdown: updown = True if mip6: if 'inet6' not in data: data['inet6'] = list() addr_obj = dict() addr_obj['address'] = mip6.group(1) or mip6.group(2) mmask6 = pmask6.match(line) if mmask6: addr_obj['prefixlen'] = mmask6.group(1) or mmask6.group(2) if not salt.utils.platform.is_sunos(): ipv6scope = mmask6.group(3) or mmask6.group(4) addr_obj['scope'] = ipv6scope.lower() if ipv6scope is not None else ipv6scope # SunOS sometimes has ::/0 as inet6 addr when using addrconf if not salt.utils.platform.is_sunos() \ or addr_obj['address'] != '::' \ and addr_obj['prefixlen'] != 0: data['inet6'].append(addr_obj) data['up'] = updown if iface in ret: # SunOS optimization, where interfaces occur twice in 'ifconfig -a' # output with the same name: for ipv4 and then for ipv6 addr family. # Every instance has it's own 'UP' status and we assume that ipv4 # status determines global interface status. # # merge items with higher priority for older values # after that merge the inet and inet6 sub items for both ret[iface] = dict(list(data.items()) + list(ret[iface].items())) if 'inet' in data: ret[iface]['inet'].extend(x for x in data['inet'] if x not in ret[iface]['inet']) if 'inet6' in data: ret[iface]['inet6'].extend(x for x in data['inet6'] if x not in ret[iface]['inet6']) else: ret[iface] = data del data return ret def linux_interfaces(): ''' Obtain interface information for *NIX/BSD variants ''' ifaces = dict() ip_path = salt.utils.path.which('ip') ifconfig_path = None if ip_path else salt.utils.path.which('ifconfig') if ip_path: cmd1 = subprocess.Popen( '{0} link show'.format(ip_path), shell=True, close_fds=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT).communicate()[0] cmd2 = subprocess.Popen( '{0} addr show'.format(ip_path), shell=True, close_fds=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT).communicate()[0] ifaces = _interfaces_ip("{0}\n{1}".format( salt.utils.stringutils.to_str(cmd1), salt.utils.stringutils.to_str(cmd2))) elif ifconfig_path: cmd = subprocess.Popen( '{0} -a'.format(ifconfig_path), shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT).communicate()[0] ifaces = _interfaces_ifconfig(salt.utils.stringutils.to_str(cmd)) return ifaces def _netbsd_interfaces_ifconfig(out): ''' Uses ifconfig to return a dictionary of interfaces with various information about each (up/down state, ip address, netmask, and hwaddr) ''' ret = dict() piface = re.compile(r'^([^\s:]+)') pmac = re.compile('.*?address: ([0-9a-f:]+)') pip = re.compile(r'.*?inet [^\d]*(.*?)/([\d]*)\s') pip6 = re.compile(r'.*?inet6 ([0-9a-f:]+)%([a-zA-Z0-9]*)/([\d]*)\s') pupdown = re.compile('UP') pbcast = re.compile(r'.*?broadcast ([\d\.]+)') groups = re.compile('\r?\n(?=\\S)').split(out) for group in groups: data = dict() iface = '' updown = False for line in group.splitlines(): miface = piface.match(line) mmac = pmac.match(line) mip = pip.match(line) mip6 = pip6.match(line) mupdown = pupdown.search(line) if miface: iface = miface.group(1) if mmac: data['hwaddr'] = mmac.group(1) if mip: if 'inet' not in data: data['inet'] = list() addr_obj = dict() addr_obj['address'] = mip.group(1) mmask = mip.group(2) if mip.group(2): addr_obj['netmask'] = cidr_to_ipv4_netmask(mip.group(2)) mbcast = pbcast.match(line) if mbcast: addr_obj['broadcast'] = mbcast.group(1) data['inet'].append(addr_obj) if mupdown: updown = True if mip6: if 'inet6' not in data: data['inet6'] = list() addr_obj = dict() addr_obj['address'] = mip6.group(1) mmask6 = mip6.group(3) addr_obj['scope'] = mip6.group(2) addr_obj['prefixlen'] = mip6.group(3) data['inet6'].append(addr_obj) data['up'] = updown ret[iface] = data del data return ret def netbsd_interfaces(): ''' Obtain interface information for NetBSD >= 8 where the ifconfig output diverged from other BSD variants (Netmask is now part of the address) ''' # NetBSD versions prior to 8.0 can still use linux_interfaces() if LooseVersion(os.uname()[2]) < LooseVersion('8.0'): return linux_interfaces() ifconfig_path = salt.utils.path.which('ifconfig') cmd = subprocess.Popen( '{0} -a'.format(ifconfig_path), shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT).communicate()[0] return _netbsd_interfaces_ifconfig(salt.utils.stringutils.to_str(cmd)) def _interfaces_ipconfig(out): ''' Returns a dictionary of interfaces with various information about each (up/down state, ip address, netmask, and hwaddr) NOTE: This is not used by any function and may be able to be removed in the future. ''' ifaces = dict() iface = None adapter_iface_regex = re.compile(r'adapter (\S.+):$') for line in out.splitlines(): if not line: continue # TODO what does Windows call Infiniband and 10/40gige adapters if line.startswith('Ethernet'): iface = ifaces[adapter_iface_regex.search(line).group(1)] iface['up'] = True addr = None continue if iface: key, val = line.split(',', 1) key = key.strip(' .') val = val.strip() if addr and key == 'Subnet Mask': addr['netmask'] = val elif key in ('IP Address', 'IPv4 Address'): if 'inet' not in iface: iface['inet'] = list() addr = {'address': val.rstrip('(Preferred)'), 'netmask': None, 'broadcast': None} # TODO find the broadcast iface['inet'].append(addr) elif 'IPv6 Address' in key: if 'inet6' not in iface: iface['inet'] = list() # XXX What is the prefixlen!? addr = {'address': val.rstrip('(Preferred)'), 'prefixlen': None} iface['inet6'].append(addr) elif key == 'Physical Address': iface['hwaddr'] = val elif key == 'Media State': # XXX seen used for tunnel adaptors # might be useful iface['up'] = (val != 'Media disconnected') def win_interfaces(): ''' Obtain interface information for Windows systems ''' with salt.utils.winapi.Com(): c = wmi.WMI() ifaces = {} for iface in c.Win32_NetworkAdapterConfiguration(IPEnabled=1): ifaces[iface.Description] = dict() if iface.MACAddress: ifaces[iface.Description]['hwaddr'] = iface.MACAddress if iface.IPEnabled: ifaces[iface.Description]['up'] = True for ip in iface.IPAddress: if '.' in ip: if 'inet' not in ifaces[iface.Description]: ifaces[iface.Description]['inet'] = [] item = {'address': ip, 'label': iface.Description} if iface.DefaultIPGateway: broadcast = next((i for i in iface.DefaultIPGateway if '.' in i), '') if broadcast: item['broadcast'] = broadcast if iface.IPSubnet: netmask = next((i for i in iface.IPSubnet if '.' in i), '') if netmask: item['netmask'] = netmask ifaces[iface.Description]['inet'].append(item) if ':' in ip: if 'inet6' not in ifaces[iface.Description]: ifaces[iface.Description]['inet6'] = [] item = {'address': ip} if iface.DefaultIPGateway: broadcast = next((i for i in iface.DefaultIPGateway if ':' in i), '') if broadcast: item['broadcast'] = broadcast if iface.IPSubnet: netmask = next((i for i in iface.IPSubnet if ':' in i), '') if netmask: item['netmask'] = netmask ifaces[iface.Description]['inet6'].append(item) else: ifaces[iface.Description]['up'] = False return ifaces def interfaces(): ''' Return a dictionary of information about all the interfaces on the minion ''' if salt.utils.platform.is_windows(): return win_interfaces() elif salt.utils.platform.is_netbsd(): return netbsd_interfaces() else: return linux_interfaces() def get_net_start(ipaddr, netmask): ''' Return the address of the network ''' net = ipaddress.ip_network('{0}/{1}'.format(ipaddr, netmask), strict=False) return six.text_type(net.network_address) def get_net_size(mask): ''' Turns an IPv4 netmask into it's corresponding prefix length (255.255.255.0 -> 24 as in 192.168.1.10/24). ''' binary_str = '' for octet in mask.split('.'): binary_str += bin(int(octet))[2:].zfill(8) return len(binary_str.rstrip('0')) def calc_net(ipaddr, netmask=None): ''' Takes IP (CIDR notation supported) and optionally netmask and returns the network in CIDR-notation. (The IP can be any IP inside the subnet) ''' if netmask is not None: ipaddr = '{0}/{1}'.format(ipaddr, netmask) return six.text_type(ipaddress.ip_network(ipaddr, strict=False)) def _ipv4_to_bits(ipaddr): ''' Accepts an IPv4 dotted quad and returns a string representing its binary counterpart ''' return ''.join([bin(int(x))[2:].rjust(8, '0') for x in ipaddr.split('.')]) def _get_iface_info(iface): ''' If `iface` is available, return interface info and no error, otherwise return no info and log and return an error ''' iface_info = interfaces() if iface in iface_info.keys(): return iface_info, False else: error_msg = ('Interface "{0}" not in available interfaces: "{1}"' ''.format(iface, '", "'.join(iface_info.keys()))) log.error(error_msg) return None, error_msg def _hw_addr_aix(iface): ''' Return the hardware address (a.k.a. MAC address) for a given interface on AIX MAC address not available in through interfaces ''' cmd = subprocess.Popen( 'entstat -d {0} | grep \'Hardware Address\''.format(iface), shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT).communicate()[0] if cmd: comps = cmd.split(' ') if len(comps) == 3: mac_addr = comps[2].strip('\'').strip() return mac_addr error_msg = ('Interface "{0}" either not available or does not contain a hardware address'.format(iface)) log.error(error_msg) return error_msg def hw_addr(iface): ''' Return the hardware address (a.k.a. MAC address) for a given interface .. versionchanged:: 2016.11.4 Added support for AIX ''' if salt.utils.platform.is_aix(): return _hw_addr_aix iface_info, error = _get_iface_info(iface) if error is False: return iface_info.get(iface, {}).get('hwaddr', '') else: return error def interface(iface): ''' Return the details of `iface` or an error if it does not exist ''' iface_info, error = _get_iface_info(iface) if error is False: return iface_info.get(iface, {}).get('inet', '') else: return error def interface_ip(iface): ''' Return `iface` IPv4 addr or an error if `iface` does not exist ''' iface_info, error = _get_iface_info(iface) if error is False: inet = iface_info.get(iface, {}).get('inet', None) return inet[0].get('address', '') if inet else '' else: return error def _subnets(proto='inet', interfaces_=None): ''' Returns a list of subnets to which the host belongs ''' if interfaces_ is None: ifaces = interfaces() elif isinstance(interfaces_, list): ifaces = {} for key, value in six.iteritems(interfaces()): if key in interfaces_: ifaces[key] = value else: ifaces = {interfaces_: interfaces().get(interfaces_, {})} ret = set() if proto == 'inet': subnet = 'netmask' dflt_cidr = 32 elif proto == 'inet6': subnet = 'prefixlen' dflt_cidr = 128 else: log.error('Invalid proto %s calling subnets()', proto) return for ip_info in six.itervalues(ifaces): addrs = ip_info.get(proto, []) addrs.extend([addr for addr in ip_info.get('secondary', []) if addr.get('type') == proto]) for intf in addrs: if subnet in intf: intf = ipaddress.ip_interface('{0}/{1}'.format(intf['address'], intf[subnet])) else: intf = ipaddress.ip_interface('{0}/{1}'.format(intf['address'], dflt_cidr)) if not intf.is_loopback: ret.add(intf.network) return [six.text_type(net) for net in sorted(ret)] def subnets(interfaces=None): ''' Returns a list of IPv4 subnets to which the host belongs ''' return _subnets('inet', interfaces_=interfaces) def subnets6(): ''' Returns a list of IPv6 subnets to which the host belongs ''' return _subnets('inet6') def in_subnet(cidr, addr=None): ''' Returns True if host or (any of) addrs is within specified subnet, otherwise False ''' try: cidr = ipaddress.ip_network(cidr) except ValueError: log.error('Invalid CIDR \'%s\'', cidr) return False if addr is None: addr = ip_addrs() addr.extend(ip_addrs6()) elif not isinstance(addr, (list, tuple)): addr = (addr,) return any(ipaddress.ip_address(item) in cidr for item in addr) def _ip_addrs(interface=None, include_loopback=False, interface_data=None, proto='inet'): ''' Return the full list of IP adresses matching the criteria proto = inet|inet6 ''' ret = set() ifaces = interface_data \ if isinstance(interface_data, dict) \ else interfaces() if interface is None: target_ifaces = ifaces else: target_ifaces = dict([(k, v) for k, v in six.iteritems(ifaces) if k == interface]) if not target_ifaces: log.error('Interface %s not found.', interface) for ip_info in six.itervalues(target_ifaces): addrs = ip_info.get(proto, []) addrs.extend([addr for addr in ip_info.get('secondary', []) if addr.get('type') == proto]) for addr in addrs: addr = ipaddress.ip_address(addr.get('address')) if not addr.is_loopback or include_loopback: ret.add(addr) return [six.text_type(addr) for addr in sorted(ret)] def ip_addrs(interface=None, include_loopback=False, interface_data=None): ''' Returns a list of IPv4 addresses assigned to the host. 127.0.0.1 is ignored, unless 'include_loopback=True' is indicated. If 'interface' is provided, then only IP addresses from that interface will be returned. ''' return _ip_addrs(interface, include_loopback, interface_data, 'inet') def ip_addrs6(interface=None, include_loopback=False, interface_data=None): ''' Returns a list of IPv6 addresses assigned to the host. ::1 is ignored, unless 'include_loopback=True' is indicated. If 'interface' is provided, then only IP addresses from that interface will be returned. ''' return _ip_addrs(interface, include_loopback, interface_data, 'inet6') def hex2ip(hex_ip, invert=False): ''' Convert a hex string to an ip, if a failure occurs the original hex is returned. If 'invert=True' assume that ip from /proc/net/<proto> ''' if len(hex_ip) == 32: # ipv6 ip = [] for i in range(0, 32, 8): ip_part = hex_ip[i:i + 8] ip_part = [ip_part[x:x + 2] for x in range(0, 8, 2)] if invert: ip.append("{0[3]}{0[2]}:{0[1]}{0[0]}".format(ip_part)) else: ip.append("{0[0]}{0[1]}:{0[2]}{0[3]}".format(ip_part)) try: address = ipaddress.IPv6Address(":".join(ip)) if address.ipv4_mapped: return str(address.ipv4_mapped) else: return address.compressed except ipaddress.AddressValueError as ex: log.error('hex2ip - ipv6 address error: %s', ex) return hex_ip try: hip = int(hex_ip, 16) except ValueError: return hex_ip if invert: return '{3}.{2}.{1}.{0}'.format(hip >> 24 & 255, hip >> 16 & 255, hip >> 8 & 255, hip & 255) return '{0}.{1}.{2}.{3}'.format(hip >> 24 & 255, hip >> 16 & 255, hip >> 8 & 255, hip & 255) def mac2eui64(mac, prefix=None): ''' Convert a MAC address to a EUI64 identifier or, with prefix provided, a full IPv6 address ''' # http://tools.ietf.org/html/rfc4291#section-2.5.1 eui64 = re.sub(r'[.:-]', '', mac).lower() eui64 = eui64[0:6] + 'fffe' + eui64[6:] eui64 = hex(int(eui64[0:2], 16) | 2)[2:].zfill(2) + eui64[2:] if prefix is None: return ':'.join(re.findall(r'.{4}', eui64)) else: try: net = ipaddress.ip_network(prefix, strict=False) euil = int('0x{0}'.format(eui64), 16) return '{0}/{1}'.format(net[euil], net.prefixlen) except Exception: return def active_tcp(): ''' Return a dict describing all active tcp connections as quickly as possible ''' ret = {} for statf in ['/proc/net/tcp', '/proc/net/tcp6']: if os.path.isfile(statf): with salt.utils.files.fopen(statf, 'rb') as fp_: for line in fp_: line = salt.utils.stringutils.to_unicode(line) if line.strip().startswith('sl'): continue iret = _parse_tcp_line(line) sl = next(iter(iret)) if iret[sl]['state'] == 1: # 1 is ESTABLISHED del iret[sl]['state'] ret[len(ret)] = iret[sl] return ret def local_port_tcp(port): ''' Return a set of remote ip addrs attached to the specified local port ''' ret = _remotes_on(port, 'local_port') return ret def remote_port_tcp(port): ''' Return a set of ip addrs the current host is connected to on given port ''' ret = _remotes_on(port, 'remote_port') return ret def _remotes_on(port, which_end): ''' Return a set of ip addrs active tcp connections ''' port = int(port) ret = _netlink_tool_remote_on(port, which_end) if ret is not None: return ret ret = set() proc_available = False for statf in ['/proc/net/tcp', '/proc/net/tcp6']: if os.path.isfile(statf): proc_available = True with salt.utils.files.fopen(statf, 'r') as fp_: for line in fp_: line = salt.utils.stringutils.to_unicode(line) if line.strip().startswith('sl'): continue iret = _parse_tcp_line(line) sl = next(iter(iret)) if iret[sl][which_end] == port and iret[sl]['state'] == 1: # 1 is ESTABLISHED ret.add(iret[sl]['remote_addr']) if not proc_available: # Fallback to use OS specific tools if salt.utils.platform.is_sunos(): return _sunos_remotes_on(port, which_end) if salt.utils.platform.is_freebsd(): return _freebsd_remotes_on(port, which_end) if salt.utils.platform.is_netbsd(): return _netbsd_remotes_on(port, which_end) if salt.utils.platform.is_openbsd(): return _openbsd_remotes_on(port, which_end) if salt.utils.platform.is_windows(): return _windows_remotes_on(port, which_end) if salt.utils.platform.is_aix(): return _aix_remotes_on(port, which_end) return _linux_remotes_on(port, which_end) return ret def _parse_tcp_line(line): ''' Parse a single line from the contents of /proc/net/tcp or /proc/net/tcp6 ''' ret = {} comps = line.strip().split() sl = comps[0].rstrip(':') ret[sl] = {} l_addr, l_port = comps[1].split(':') r_addr, r_port = comps[2].split(':') ret[sl]['local_addr'] = hex2ip(l_addr, True) ret[sl]['local_port'] = int(l_port, 16) ret[sl]['remote_addr'] = hex2ip(r_addr, True) ret[sl]['remote_port'] = int(r_port, 16) ret[sl]['state'] = int(comps[3], 16) return ret def _netlink_tool_remote_on(port, which_end): ''' Returns set of ipv4 host addresses of remote established connections on local or remote tcp port. Parses output of shell 'ss' to get connections [root@salt-master ~]# ss -ant State Recv-Q Send-Q Local Address:Port Peer Address:Port LISTEN 0 511 *:80 *:* LISTEN 0 128 *:22 *:* ESTAB 0 0 127.0.0.1:56726 127.0.0.1:4505 ''' remotes = set() valid = False try: data = subprocess.check_output(['ss', '-ant']) # pylint: disable=minimum-python-version except subprocess.CalledProcessError: log.error('Failed ss') raise except OSError: # not command "No such file or directory" return None lines = salt.utils.stringutils.to_str(data).split('\n') for line in lines: if 'Address:Port' in line: # ss tools may not be valid valid = True continue elif 'ESTAB' not in line: continue chunks = line.split() local_host, local_port = chunks[3].split(':', 1) remote_host, remote_port = chunks[4].split(':', 1) if which_end == 'remote_port' and int(remote_port) != port: continue if which_end == 'local_port' and int(local_port) != port: continue remotes.add(remote_host) if valid is False: remotes = None return remotes def _sunos_remotes_on(port, which_end): ''' SunOS specific helper function. Returns set of ipv4 host addresses of remote established connections on local or remote tcp port. Parses output of shell 'netstat' to get connections [root@salt-master ~]# netstat -f inet -n TCP: IPv4 Local Address Remote Address Swind Send-Q Rwind Recv-Q State -------------------- -------------------- ----- ------ ----- ------ ----------- 10.0.0.101.4505 10.0.0.1.45329 1064800 0 1055864 0 ESTABLISHED 10.0.0.101.4505 10.0.0.100.50798 1064800 0 1055864 0 ESTABLISHED ''' remotes = set() try: data = subprocess.check_output(['netstat', '-f', 'inet', '-n']) # pylint: disable=minimum-python-version except subprocess.CalledProcessError: log.error('Failed netstat') raise lines = salt.utils.stringutils.to_str(data).split('\n') for line in lines: if 'ESTABLISHED' not in line: continue chunks = line.split() local_host, local_port = chunks[0].rsplit('.', 1) remote_host, remote_port = chunks[1].rsplit('.', 1) if which_end == 'remote_port' and int(remote_port) != port: continue if which_end == 'local_port' and int(local_port) != port: continue remotes.add(remote_host) return remotes def _freebsd_remotes_on(port, which_end): ''' Returns set of ipv4 host addresses of remote established connections on local tcp port port. Parses output of shell 'sockstat' (FreeBSD) to get connections $ sudo sockstat -4 USER COMMAND PID FD PROTO LOCAL ADDRESS FOREIGN ADDRESS root python2.7 1456 29 tcp4 *:4505 *:* root python2.7 1445 17 tcp4 *:4506 *:* root python2.7 1294 14 tcp4 127.0.0.1:11813 127.0.0.1:4505 root python2.7 1294 41 tcp4 127.0.0.1:61115 127.0.0.1:4506 $ sudo sockstat -4 -c -p 4506 USER COMMAND PID FD PROTO LOCAL ADDRESS FOREIGN ADDRESS root python2.7 1294 41 tcp4 127.0.0.1:61115 127.0.0.1:4506 ''' port = int(port) remotes = set() try: cmd = salt.utils.args.shlex_split('sockstat -4 -c -p {0}'.format(port)) data = subprocess.check_output(cmd) # pylint: disable=minimum-python-version except subprocess.CalledProcessError as ex: log.error('Failed "sockstat" with returncode = %s', ex.returncode) raise lines = salt.utils.stringutils.to_str(data).split('\n') for line in lines: chunks = line.split() if not chunks: continue # ['root', 'python2.7', '1456', '37', 'tcp4', # '127.0.0.1:4505-', '127.0.0.1:55703'] # print chunks if 'COMMAND' in chunks[1]: continue # ignore header if len(chunks) < 2: continue # sockstat -4 -c -p 4506 does this with high PIDs: # USER COMMAND PID FD PROTO LOCAL ADDRESS FOREIGN ADDRESS # salt-master python2.781106 35 tcp4 192.168.12.34:4506 192.168.12.45:60143 local = chunks[-2] remote = chunks[-1] lhost, lport = local.split(':') rhost, rport = remote.split(':') if which_end == 'local' and int(lport) != port: # ignore if local port not port continue if which_end == 'remote' and int(rport) != port: # ignore if remote port not port continue remotes.add(rhost) return remotes def _netbsd_remotes_on(port, which_end): ''' Returns set of ipv4 host addresses of remote established connections on local tcp port port. Parses output of shell 'sockstat' (NetBSD) to get connections $ sudo sockstat -4 -n USER COMMAND PID FD PROTO LOCAL ADDRESS FOREIGN ADDRESS root python2.7 1456 29 tcp *.4505 *.* root python2.7 1445 17 tcp *.4506 *.* root python2.7 1294 14 tcp 127.0.0.1.11813 127.0.0.1.4505 root python2.7 1294 41 tcp 127.0.0.1.61115 127.0.0.1.4506 $ sudo sockstat -4 -c -n -p 4506 USER COMMAND PID FD PROTO LOCAL ADDRESS FOREIGN ADDRESS root python2.7 1294 41 tcp 127.0.0.1.61115 127.0.0.1.4506 ''' port = int(port) remotes = set() try: cmd = salt.utils.args.shlex_split('sockstat -4 -c -n -p {0}'.format(port)) data = subprocess.check_output(cmd) # pylint: disable=minimum-python-version except subprocess.CalledProcessError as ex: log.error('Failed "sockstat" with returncode = %s', ex.returncode) raise lines = salt.utils.stringutils.to_str(data).split('\n') for line in lines: chunks = line.split() if not chunks: continue # ['root', 'python2.7', '1456', '37', 'tcp', # '127.0.0.1.4505-', '127.0.0.1.55703'] # print chunks if 'COMMAND' in chunks[1]: continue # ignore header if len(chunks) < 2: continue local = chunks[5].split('.') lport = local.pop() lhost = '.'.join(local) remote = chunks[6].split('.') rport = remote.pop() rhost = '.'.join(remote) if which_end == 'local' and int(lport) != port: # ignore if local port not port continue if which_end == 'remote' and int(rport) != port: # ignore if remote port not port continue remotes.add(rhost) return remotes def _openbsd_remotes_on(port, which_end): ''' OpenBSD specific helper function. Returns set of ipv4 host addresses of remote established connections on local or remote tcp port. Parses output of shell 'netstat' to get connections $ netstat -nf inet Active Internet connections Proto Recv-Q Send-Q Local Address Foreign Address (state) tcp 0 0 10.0.0.101.4505 10.0.0.1.45329 ESTABLISHED tcp 0 0 10.0.0.101.4505 10.0.0.100.50798 ESTABLISHED ''' remotes = set() try: data = subprocess.check_output(['netstat', '-nf', 'inet']) # pylint: disable=minimum-python-version except subprocess.CalledProcessError: log.error('Failed netstat') raise lines = data.split('\n') for line in lines: if 'ESTABLISHED' not in line: continue chunks = line.split() local_host, local_port = chunks[3].rsplit('.', 1) remote_host, remote_port = chunks[4].rsplit('.', 1) if which_end == 'remote_port' and int(remote_port) != port: continue if which_end == 'local_port' and int(local_port) != port: continue remotes.add(remote_host) return remotes def _windows_remotes_on(port, which_end): r''' Windows specific helper function. Returns set of ipv4 host addresses of remote established connections on local or remote tcp port. Parses output of shell 'netstat' to get connections C:\>netstat -n Active Connections Proto Local Address Foreign Address State TCP 10.2.33.17:3007 130.164.12.233:10123 ESTABLISHED TCP 10.2.33.17:3389 130.164.30.5:10378 ESTABLISHED ''' remotes = set() try: data = subprocess.check_output(['netstat', '-n']) # pylint: disable=minimum-python-version except subprocess.CalledProcessError: log.error('Failed netstat') raise lines = salt.utils.stringutils.to_str(data).split('\n') for line in lines: if 'ESTABLISHED' not in line: continue chunks = line.split() local_host, local_port = chunks[1].rsplit(':', 1) remote_host, remote_port = chunks[2].rsplit(':', 1) if which_end == 'remote_port' and int(remote_port) != port: continue if which_end == 'local_port' and int(local_port) != port: continue remotes.add(remote_host) return remotes def _linux_remotes_on(port, which_end): ''' Linux specific helper function. Returns set of ip host addresses of remote established connections on local tcp port port. Parses output of shell 'lsof' to get connections $ sudo lsof -iTCP:4505 -n COMMAND PID USER FD TYPE DEVICE SIZE/OFF NODE NAME Python 9971 root 35u IPv4 0x18a8464a29ca329d 0t0 TCP *:4505 (LISTEN) Python 9971 root 37u IPv4 0x18a8464a29b2b29d 0t0 TCP 127.0.0.1:4505->127.0.0.1:55703 (ESTABLISHED) Python 10152 root 22u IPv4 0x18a8464a29c8cab5 0t0 TCP 127.0.0.1:55703->127.0.0.1:4505 (ESTABLISHED) Python 10153 root 22u IPv4 0x18a8464a29c8cab5 0t0 TCP [fe80::249a]:4505->[fe80::150]:59367 (ESTABLISHED) ''' remotes = set() try: data = subprocess.check_output( ['lsof', '-iTCP:{0:d}'.format(port), '-n', '-P'] # pylint: disable=minimum-python-version ) except subprocess.CalledProcessError as ex: if ex.returncode == 1: # Lsof return 1 if any error was detected, including the failure # to locate Internet addresses, and it is not an error in this case. log.warning('"lsof" returncode = 1, likely no active TCP sessions.') return remotes log.error('Failed "lsof" with returncode = %s', ex.returncode) raise lines = salt.utils.stringutils.to_str(data).split('\n') for line in lines: chunks = line.split() if not chunks: continue # ['Python', '9971', 'root', '37u', 'IPv4', '0x18a8464a29b2b29d', '0t0', # 'TCP', '127.0.0.1:4505->127.0.0.1:55703', '(ESTABLISHED)'] # print chunks if 'COMMAND' in chunks[0]: continue # ignore header if 'ESTABLISHED' not in chunks[-1]: continue # ignore if not ESTABLISHED # '127.0.0.1:4505->127.0.0.1:55703' local, remote = chunks[8].split('->') _, lport = local.rsplit(':', 1) rhost, rport = remote.rsplit(':', 1) if which_end == 'remote_port' and int(rport) != port: continue if which_end == 'local_port' and int(lport) != port: continue remotes.add(rhost.strip("[]")) return remotes def _aix_remotes_on(port, which_end): ''' AIX specific helper function. Returns set of ipv4 host addresses of remote established connections on local or remote tcp port. Parses output of shell 'netstat' to get connections root@la68pp002_pub:/opt/salt/lib/python2.7/site-packages/salt/modules# netstat -f inet -n Active Internet connections Proto Recv-Q Send-Q Local Address Foreign Address (state) tcp4 0 0 172.29.149.95.50093 209.41.78.13.4505 ESTABLISHED tcp4 0 0 127.0.0.1.9514 *.* LISTEN tcp4 0 0 127.0.0.1.9515 *.* LISTEN tcp4 0 0 127.0.0.1.199 127.0.0.1.32779 ESTABLISHED tcp4 0 0 127.0.0.1.32779 127.0.0.1.199 ESTABLISHED tcp4 0 40 172.29.149.95.22 172.29.96.83.41022 ESTABLISHED tcp4 0 0 172.29.149.95.22 172.29.96.83.41032 ESTABLISHED tcp4 0 0 127.0.0.1.32771 127.0.0.1.32775 ESTABLISHED tcp 0 0 127.0.0.1.32775 127.0.0.1.32771 ESTABLISHED tcp4 0 0 127.0.0.1.32771 127.0.0.1.32776 ESTABLISHED tcp 0 0 127.0.0.1.32776 127.0.0.1.32771 ESTABLISHED tcp4 0 0 127.0.0.1.32771 127.0.0.1.32777 ESTABLISHED tcp 0 0 127.0.0.1.32777 127.0.0.1.32771 ESTABLISHED tcp4 0 0 127.0.0.1.32771 127.0.0.1.32778 ESTABLISHED tcp 0 0 127.0.0.1.32778 127.0.0.1.32771 ESTABLISHED ''' remotes = set() try: data = subprocess.check_output(['netstat', '-f', 'inet', '-n']) # pylint: disable=minimum-python-version except subprocess.CalledProcessError: log.error('Failed netstat') raise lines = salt.utils.stringutils.to_str(data).split('\n') for line in lines: if 'ESTABLISHED' not in line: continue chunks = line.split() local_host, local_port = chunks[3].rsplit('.', 1) remote_host, remote_port = chunks[4].rsplit('.', 1) if which_end == 'remote_port' and int(remote_port) != port: continue if which_end == 'local_port' and int(local_port) != port: continue remotes.add(remote_host) return remotes @jinja_filter('gen_mac') def gen_mac(prefix='AC:DE:48'): ''' Generates a MAC address with the defined OUI prefix. Common prefixes: - ``00:16:3E`` -- Xen - ``00:18:51`` -- OpenVZ - ``00:50:56`` -- VMware (manually generated) - ``52:54:00`` -- QEMU/KVM - ``AC:DE:48`` -- PRIVATE References: - http://standards.ieee.org/develop/regauth/oui/oui.txt - https://www.wireshark.org/tools/oui-lookup.html - https://en.wikipedia.org/wiki/MAC_address ''' return '{0}:{1:02X}:{2:02X}:{3:02X}'.format(prefix, random.randint(0, 0xff), random.randint(0, 0xff), random.randint(0, 0xff)) @jinja_filter('mac_str_to_bytes') def refresh_dns(): ''' issue #21397: force glibc to re-read resolv.conf ''' try: res_init() except NameError: # Exception raised loading the library, thus res_init is not defined pass @jinja_filter('connection_check') def connection_check(addr, port=80, safe=False, ipv6=None): ''' Provides a convenient alias for the dns_check filter. ''' return dns_check(addr, port, safe, ipv6) @jinja_filter('dns_check') def dns_check(addr, port=80, safe=False, ipv6=None, attempt_connect=True): ''' Return the ip resolved by dns, but do not exit on failure, only raise an exception. Obeys system preference for IPv4/6 address resolution - this can be overridden by the ipv6 flag. Tries to connect to the address before considering it useful. If no address can be reached, the first one resolved is used as a fallback. ''' error = False lookup = addr seen_ipv6 = False family = socket.AF_INET6 if ipv6 else socket.AF_INET if ipv6 is False else socket.AF_UNSPEC hostnames = [] try: refresh_dns() hostnames = socket.getaddrinfo(addr, port, family, socket.SOCK_STREAM) except TypeError: err = ('Attempt to resolve address \'{0}\' failed. Invalid or unresolveable address').format(lookup) raise SaltSystemExit(code=42, msg=err) except socket.error: error = True # If ipv6 is set to True, attempt another lookup using the IPv4 family, # just in case we're attempting to lookup an IPv4 IP # as an IPv6 hostname. if error and ipv6: try: refresh_dns() hostnames = socket.getaddrinfo(addr, port, socket.AF_INET, socket.SOCK_STREAM) except TypeError: err = ('Attempt to resolve address \'{0}\' failed. Invalid or unresolveable address').format(lookup) raise SaltSystemExit(code=42, msg=err) except socket.error: error = True try: if not hostnames: error = True else: resolved = False candidates = [] for h in hostnames: # Input is IP address, passed through unchanged, just return it if h[4][0] == addr: resolved = salt.utils.zeromq.ip_bracket(addr) break candidate_addr = salt.utils.zeromq.ip_bracket(h[4][0]) # sometimes /etc/hosts contains ::1 localhost if not ipv6 and candidate_addr == '[::1]': continue candidates.append(candidate_addr) if attempt_connect: try: s = socket.socket(h[0], socket.SOCK_STREAM) s.settimeout(2) s.connect((candidate_addr.strip('[]'), h[4][1])) s.close() resolved = candidate_addr break except socket.error: pass if not resolved: if candidates: resolved = candidates[0] else: error = True except TypeError: err = ('Attempt to resolve address \'{0}\' failed. Invalid or unresolveable address').format(lookup) raise SaltSystemExit(code=42, msg=err) except socket.error: error = True if error: err = ('DNS lookup or connection check of \'{0}\' failed.').format(addr) if safe: if salt.log.is_console_configured(): # If logging is not configured it also means that either # the master or minion instance calling this hasn't even # started running log.error(err) raise SaltClientError() raise SaltSystemExit(code=42, msg=err) return resolved def parse_host_port(host_port): """ Takes a string argument specifying host or host:port. Returns a (hostname, port) or (ip_address, port) tuple. If no port is given, the second (port) element of the returned tuple will be None. host:port argument, for example, is accepted in the forms of: - hostname - hostname:1234 - hostname.domain.tld - hostname.domain.tld:5678 - [1234::5]:5678 - 1234::5 - 10.11.12.13:4567 - 10.11.12.13 """ host, port = None, None # default _s_ = host_port[:] if _s_[0] == "[": if "]" in host_port: host, _s_ = _s_.lstrip("[").rsplit("]", 1) host = ipaddress.IPv6Address(host).compressed if _s_[0] == ":": port = int(_s_.lstrip(":")) else: if len(_s_) > 1: raise ValueError('found ambiguous "{}" port in "{}"'.format(_s_, host_port)) else: if _s_.count(":") == 1: host, _hostport_separator_, port = _s_.partition(":") try: port = int(port) except ValueError as _e_: log.error('host_port "%s" port value "%s" is not an integer.', host_port, port) raise _e_ else: host = _s_ try: if not isinstance(host, ipaddress._BaseAddress): host_ip = ipaddress.ip_address(host).compressed host = host_ip except ValueError: log.debug('"%s" Not an IP address? Assuming it is a hostname.', host) if host != sanitize_host(host): log.error('bad hostname: "%s"', host) raise ValueError('bad hostname: "{}"'.format(host)) return host, port def is_fqdn(hostname): """ Verify if hostname conforms to be a FQDN. :param hostname: text string with the name of the host :return: bool, True if hostname is correct FQDN, False otherwise """ compliant = re.compile(r"(?!-)[A-Z\d\-\_]{1,63}(?<!-)$", re.IGNORECASE) return "." in hostname and len(hostname) < 0xff and all(compliant.match(x) for x in hostname.rstrip(".").split("."))
saltstack/salt
salt/utils/network.py
connection_check
python
def connection_check(addr, port=80, safe=False, ipv6=None): ''' Provides a convenient alias for the dns_check filter. ''' return dns_check(addr, port, safe, ipv6)
Provides a convenient alias for the dns_check filter.
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/network.py#L1904-L1908
null
# -*- coding: utf-8 -*- ''' Define some generic socket functions for network modules ''' # Import python libs from __future__ import absolute_import, unicode_literals, print_function import itertools import os import re import types import socket import logging import platform import random import subprocess from string import ascii_letters, digits # Import 3rd-party libs from salt.ext import six from salt.ext.six.moves import range # pylint: disable=import-error,redefined-builtin # Attempt to import wmi try: import wmi import salt.utils.winapi except ImportError: pass # Import salt libs import salt.utils.args import salt.utils.files import salt.utils.path import salt.utils.platform import salt.utils.stringutils import salt.utils.zeromq from salt._compat import ipaddress from salt.exceptions import SaltClientError, SaltSystemExit from salt.utils.decorators.jinja import jinja_filter from salt.utils.versions import LooseVersion # inet_pton does not exist in Windows, this is a workaround if salt.utils.platform.is_windows(): from salt.ext import win_inet_pton # pylint: disable=unused-import log = logging.getLogger(__name__) try: import ctypes import ctypes.util libc = ctypes.cdll.LoadLibrary(ctypes.util.find_library("c")) res_init = libc.__res_init except (ImportError, OSError, AttributeError, TypeError): pass # pylint: disable=C0103 def sanitize_host(host): ''' Sanitize host string. https://tools.ietf.org/html/rfc1123#section-2.1 ''' RFC952_characters = ascii_letters + digits + ".-" return "".join([c for c in host[0:255] if c in RFC952_characters]) def isportopen(host, port): ''' Return status of a port ''' if not 1 <= int(port) <= 65535: return False sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) out = sock.connect_ex((sanitize_host(host), int(port))) return out def host_to_ips(host): ''' Returns a list of IP addresses of a given hostname or None if not found. ''' ips = [] try: for family, socktype, proto, canonname, sockaddr in socket.getaddrinfo( host, 0, socket.AF_UNSPEC, socket.SOCK_STREAM): if family == socket.AF_INET: ip, port = sockaddr elif family == socket.AF_INET6: ip, port, flow_info, scope_id = sockaddr ips.append(ip) if not ips: ips = None except Exception: ips = None return ips def _generate_minion_id(): ''' Get list of possible host names and convention names. :return: ''' # There are three types of hostnames: # 1. Network names. How host is accessed from the network. # 2. Host aliases. They might be not available in all the network or only locally (/etc/hosts) # 3. Convention names, an internal nodename. class DistinctList(list): ''' List, which allows one to append only distinct objects. Needs to work on Python 2.6, because of collections.OrderedDict only since 2.7 version. Override 'filter()' for custom filtering. ''' localhost_matchers = [r'localhost.*', r'ip6-.*', r'127[.]\d', r'0\.0\.0\.0', r'::1.*', r'ipv6-.*', r'fe00::.*', r'fe02::.*', r'1.0.0.*.ip6.arpa'] def append(self, p_object): if p_object and p_object not in self and not self.filter(p_object): super(DistinctList, self).append(p_object) return self def extend(self, iterable): for obj in iterable: self.append(obj) return self def filter(self, element): 'Returns True if element needs to be filtered' for rgx in self.localhost_matchers: if re.match(rgx, element): return True def first(self): return self and self[0] or None hostname = socket.gethostname() hosts = DistinctList().append( salt.utils.stringutils.to_unicode(socket.getfqdn(salt.utils.stringutils.to_bytes(hostname))) ).append(platform.node()).append(hostname) if not hosts: try: for a_nfo in socket.getaddrinfo(hosts.first() or 'localhost', None, socket.AF_INET, socket.SOCK_RAW, socket.IPPROTO_IP, socket.AI_CANONNAME): if len(a_nfo) > 3: hosts.append(a_nfo[3]) except socket.gaierror: log.warning('Cannot resolve address %s info via socket: %s', hosts.first() or 'localhost (N/A)', socket.gaierror) # Universal method for everywhere (Linux, Slowlaris, Windows etc) for f_name in ('/etc/hostname', '/etc/nodename', '/etc/hosts', r'{win}\system32\drivers\etc\hosts'.format(win=os.getenv('WINDIR'))): try: with salt.utils.files.fopen(f_name) as f_hdl: for line in f_hdl: line = salt.utils.stringutils.to_unicode(line) hst = line.strip().split('#')[0].strip().split() if hst: if hst[0][:4] in ('127.', '::1') or len(hst) == 1: hosts.extend(hst) except IOError: pass # include public and private ipaddresses return hosts.extend([addr for addr in ip_addrs() if not ipaddress.ip_address(addr).is_loopback]) def generate_minion_id(): ''' Return only first element of the hostname from all possible list. :return: ''' try: ret = salt.utils.stringutils.to_unicode(_generate_minion_id().first()) except TypeError: ret = None return ret or 'localhost' def get_socket(addr, type=socket.SOCK_STREAM, proto=0): ''' Return a socket object for the addr IP-version agnostic ''' version = ipaddress.ip_address(addr).version if version == 4: family = socket.AF_INET elif version == 6: family = socket.AF_INET6 return socket.socket(family, type, proto) def get_fqhostname(): ''' Returns the fully qualified hostname ''' # try getaddrinfo() fqdn = None try: addrinfo = socket.getaddrinfo( socket.gethostname(), 0, socket.AF_UNSPEC, socket.SOCK_STREAM, socket.SOL_TCP, socket.AI_CANONNAME ) for info in addrinfo: # info struct [family, socktype, proto, canonname, sockaddr] # On Windows `canonname` can be an empty string # This can cause the function to return `None` if len(info) > 3 and info[3]: fqdn = info[3] break except socket.gaierror: pass # NOTE: this used to log.error() but it was later disabled except socket.error as err: log.debug('socket.getaddrinfo() failure while finding fqdn: %s', err) if fqdn is None: fqdn = socket.getfqdn() return fqdn def ip_to_host(ip): ''' Returns the hostname of a given IP ''' try: hostname, aliaslist, ipaddrlist = socket.gethostbyaddr(ip) except Exception as exc: log.debug('salt.utils.network.ip_to_host(%r) failed: %s', ip, exc) hostname = None return hostname # pylint: enable=C0103 def is_reachable_host(entity_name): ''' Returns a bool telling if the entity name is a reachable host (IPv4/IPv6/FQDN/etc). :param hostname: :return: ''' try: assert type(socket.getaddrinfo(entity_name, 0, 0, 0, 0)) == list ret = True except socket.gaierror: ret = False return ret def is_ip(ip): ''' Returns a bool telling if the passed IP is a valid IPv4 or IPv6 address. ''' return is_ipv4(ip) or is_ipv6(ip) def is_ipv4(ip): ''' Returns a bool telling if the value passed to it was a valid IPv4 address ''' try: return ipaddress.ip_address(ip).version == 4 except ValueError: return False def is_ipv6(ip): ''' Returns a bool telling if the value passed to it was a valid IPv6 address ''' try: return ipaddress.ip_address(ip).version == 6 except ValueError: return False def is_subnet(cidr): ''' Returns a bool telling if the passed string is an IPv4 or IPv6 subnet ''' return is_ipv4_subnet(cidr) or is_ipv6_subnet(cidr) def is_ipv4_subnet(cidr): ''' Returns a bool telling if the passed string is an IPv4 subnet ''' try: return '/' in cidr and bool(ipaddress.IPv4Network(cidr)) except Exception: return False def is_ipv6_subnet(cidr): ''' Returns a bool telling if the passed string is an IPv6 subnet ''' try: return '/' in cidr and bool(ipaddress.IPv6Network(cidr)) except Exception: return False @jinja_filter('is_ip') def is_ip_filter(ip, options=None): ''' Returns a bool telling if the passed IP is a valid IPv4 or IPv6 address. ''' return is_ipv4_filter(ip, options=options) or is_ipv6_filter(ip, options=options) def _ip_options_global(ip_obj, version): return not ip_obj.is_private def _ip_options_multicast(ip_obj, version): return ip_obj.is_multicast def _ip_options_loopback(ip_obj, version): return ip_obj.is_loopback def _ip_options_link_local(ip_obj, version): return ip_obj.is_link_local def _ip_options_private(ip_obj, version): return ip_obj.is_private def _ip_options_reserved(ip_obj, version): return ip_obj.is_reserved def _ip_options_site_local(ip_obj, version): if version == 6: return ip_obj.is_site_local return False def _ip_options_unspecified(ip_obj, version): return ip_obj.is_unspecified def _ip_options(ip_obj, version, options=None): # will process and IP options options_fun_map = { 'global': _ip_options_global, 'link-local': _ip_options_link_local, 'linklocal': _ip_options_link_local, 'll': _ip_options_link_local, 'link_local': _ip_options_link_local, 'loopback': _ip_options_loopback, 'lo': _ip_options_loopback, 'multicast': _ip_options_multicast, 'private': _ip_options_private, 'public': _ip_options_global, 'reserved': _ip_options_reserved, 'site-local': _ip_options_site_local, 'sl': _ip_options_site_local, 'site_local': _ip_options_site_local, 'unspecified': _ip_options_unspecified } if not options: return six.text_type(ip_obj) # IP version already checked options_list = [option.strip() for option in options.split(',')] for option, fun in options_fun_map.items(): if option in options_list: fun_res = fun(ip_obj, version) if not fun_res: return None # stop at first failed test # else continue return six.text_type(ip_obj) def _is_ipv(ip, version, options=None): if not version: version = 4 if version not in (4, 6): return None try: ip_obj = ipaddress.ip_address(ip) except ValueError: # maybe it is an IP network try: ip_obj = ipaddress.ip_interface(ip) except ValueError: # nope, still not :( return None if not ip_obj.version == version: return None # has the right version, let's move on return _ip_options(ip_obj, version, options=options) @jinja_filter('is_ipv4') def is_ipv4_filter(ip, options=None): ''' Returns a bool telling if the value passed to it was a valid IPv4 address. ip The IP address. net: False Consider IP addresses followed by netmask. options CSV of options regarding the nature of the IP address. E.g.: loopback, multicast, private etc. ''' _is_ipv4 = _is_ipv(ip, 4, options=options) return isinstance(_is_ipv4, six.string_types) @jinja_filter('is_ipv6') def is_ipv6_filter(ip, options=None): ''' Returns a bool telling if the value passed to it was a valid IPv6 address. ip The IP address. net: False Consider IP addresses followed by netmask. options CSV of options regarding the nature of the IP address. E.g.: loopback, multicast, private etc. ''' _is_ipv6 = _is_ipv(ip, 6, options=options) return isinstance(_is_ipv6, six.string_types) def _ipv_filter(value, version, options=None): if version not in (4, 6): return if isinstance(value, (six.string_types, six.text_type, six.binary_type)): return _is_ipv(value, version, options=options) # calls is_ipv4 or is_ipv6 for `value` elif isinstance(value, (list, tuple, types.GeneratorType)): # calls is_ipv4 or is_ipv6 for each element in the list # os it filters and returns only those elements having the desired IP version return [ _is_ipv(addr, version, options=options) for addr in value if _is_ipv(addr, version, options=options) is not None ] return None @jinja_filter('ipv4') def ipv4(value, options=None): ''' Filters a list and returns IPv4 values only. ''' return _ipv_filter(value, 4, options=options) @jinja_filter('ipv6') def ipv6(value, options=None): ''' Filters a list and returns IPv6 values only. ''' return _ipv_filter(value, 6, options=options) @jinja_filter('ipaddr') def ipaddr(value, options=None): ''' Filters and returns only valid IP objects. ''' ipv4_obj = ipv4(value, options=options) ipv6_obj = ipv6(value, options=options) if ipv4_obj is None or ipv6_obj is None: # an IP address can be either IPv4 either IPv6 # therefofe if the value passed as arg is not a list, at least one of the calls above will return None # if one of them is none, means that we should return only one of them return ipv4_obj or ipv6_obj # one of them else: return ipv4_obj + ipv6_obj # extend lists def _filter_ipaddr(value, options, version=None): ipaddr_filter_out = None if version: if version == 4: ipaddr_filter_out = ipv4(value, options) elif version == 6: ipaddr_filter_out = ipv6(value, options) else: ipaddr_filter_out = ipaddr(value, options) if not ipaddr_filter_out: return if not isinstance(ipaddr_filter_out, (list, tuple, types.GeneratorType)): ipaddr_filter_out = [ipaddr_filter_out] return ipaddr_filter_out @jinja_filter('ip_host') def ip_host(value, options=None, version=None): ''' Returns the interfaces IP address, e.g.: 192.168.0.1/28. ''' ipaddr_filter_out = _filter_ipaddr(value, options=options, version=version) if not ipaddr_filter_out: return if not isinstance(value, (list, tuple, types.GeneratorType)): return six.text_type(ipaddress.ip_interface(ipaddr_filter_out[0])) return [six.text_type(ipaddress.ip_interface(ip_a)) for ip_a in ipaddr_filter_out] def _network_hosts(ip_addr_entry): return [ six.text_type(host) for host in ipaddress.ip_network(ip_addr_entry, strict=False).hosts() ] @jinja_filter('network_hosts') def network_hosts(value, options=None, version=None): ''' Return the list of hosts within a network. .. note:: When running this command with a large IPv6 network, the command will take a long time to gather all of the hosts. ''' ipaddr_filter_out = _filter_ipaddr(value, options=options, version=version) if not ipaddr_filter_out: return if not isinstance(value, (list, tuple, types.GeneratorType)): return _network_hosts(ipaddr_filter_out[0]) return [ _network_hosts(ip_a) for ip_a in ipaddr_filter_out ] def _network_size(ip_addr_entry): return ipaddress.ip_network(ip_addr_entry, strict=False).num_addresses @jinja_filter('network_size') def network_size(value, options=None, version=None): ''' Get the size of a network. ''' ipaddr_filter_out = _filter_ipaddr(value, options=options, version=version) if not ipaddr_filter_out: return if not isinstance(value, (list, tuple, types.GeneratorType)): return _network_size(ipaddr_filter_out[0]) return [ _network_size(ip_a) for ip_a in ipaddr_filter_out ] def natural_ipv4_netmask(ip, fmt='prefixlen'): ''' Returns the "natural" mask of an IPv4 address ''' bits = _ipv4_to_bits(ip) if bits.startswith('11'): mask = '24' elif bits.startswith('1'): mask = '16' else: mask = '8' if fmt == 'netmask': return cidr_to_ipv4_netmask(mask) else: return '/' + mask def rpad_ipv4_network(ip): ''' Returns an IP network address padded with zeros. Ex: '192.168.3' -> '192.168.3.0' '10.209' -> '10.209.0.0' ''' return '.'.join(itertools.islice(itertools.chain(ip.split('.'), '0000'), 0, 4)) def cidr_to_ipv4_netmask(cidr_bits): ''' Returns an IPv4 netmask ''' try: cidr_bits = int(cidr_bits) if not 1 <= cidr_bits <= 32: return '' except ValueError: return '' netmask = '' for idx in range(4): if idx: netmask += '.' if cidr_bits >= 8: netmask += '255' cidr_bits -= 8 else: netmask += '{0:d}'.format(256 - (2 ** (8 - cidr_bits))) cidr_bits = 0 return netmask def _number_of_set_bits_to_ipv4_netmask(set_bits): # pylint: disable=C0103 ''' Returns an IPv4 netmask from the integer representation of that mask. Ex. 0xffffff00 -> '255.255.255.0' ''' return cidr_to_ipv4_netmask(_number_of_set_bits(set_bits)) # pylint: disable=C0103 def _number_of_set_bits(x): ''' Returns the number of bits that are set in a 32bit int ''' # Taken from http://stackoverflow.com/a/4912729. Many thanks! x -= (x >> 1) & 0x55555555 x = ((x >> 2) & 0x33333333) + (x & 0x33333333) x = ((x >> 4) + x) & 0x0f0f0f0f x += x >> 8 x += x >> 16 return x & 0x0000003f # pylint: enable=C0103 def _interfaces_ip(out): ''' Uses ip to return a dictionary of interfaces with various information about each (up/down state, ip address, netmask, and hwaddr) ''' ret = dict() def parse_network(value, cols): ''' Return a tuple of ip, netmask, broadcast based on the current set of cols ''' brd = None scope = None if '/' in value: # we have a CIDR in this address ip, cidr = value.split('/') # pylint: disable=C0103 else: ip = value # pylint: disable=C0103 cidr = 32 if type_ == 'inet': mask = cidr_to_ipv4_netmask(int(cidr)) if 'brd' in cols: brd = cols[cols.index('brd') + 1] elif type_ == 'inet6': mask = cidr if 'scope' in cols: scope = cols[cols.index('scope') + 1] return (ip, mask, brd, scope) groups = re.compile('\r?\n\\d').split(out) for group in groups: iface = None data = dict() for line in group.splitlines(): if ' ' not in line: continue match = re.match(r'^\d*:\s+([\w.\-]+)(?:@)?([\w.\-]+)?:\s+<(.+)>', line) if match: iface, parent, attrs = match.groups() if 'UP' in attrs.split(','): data['up'] = True else: data['up'] = False if parent: data['parent'] = parent continue cols = line.split() if len(cols) >= 2: type_, value = tuple(cols[0:2]) iflabel = cols[-1:][0] if type_ in ('inet', 'inet6'): if 'secondary' not in cols: ipaddr, netmask, broadcast, scope = parse_network(value, cols) if type_ == 'inet': if 'inet' not in data: data['inet'] = list() addr_obj = dict() addr_obj['address'] = ipaddr addr_obj['netmask'] = netmask addr_obj['broadcast'] = broadcast addr_obj['label'] = iflabel data['inet'].append(addr_obj) elif type_ == 'inet6': if 'inet6' not in data: data['inet6'] = list() addr_obj = dict() addr_obj['address'] = ipaddr addr_obj['prefixlen'] = netmask addr_obj['scope'] = scope data['inet6'].append(addr_obj) else: if 'secondary' not in data: data['secondary'] = list() ip_, mask, brd, scp = parse_network(value, cols) data['secondary'].append({ 'type': type_, 'address': ip_, 'netmask': mask, 'broadcast': brd, 'label': iflabel, }) del ip_, mask, brd, scp elif type_.startswith('link'): data['hwaddr'] = value if iface: ret[iface] = data del iface, data return ret def _interfaces_ifconfig(out): ''' Uses ifconfig to return a dictionary of interfaces with various information about each (up/down state, ip address, netmask, and hwaddr) ''' ret = dict() piface = re.compile(r'^([^\s:]+)') pmac = re.compile('.*?(?:HWaddr|ether|address:|lladdr) ([0-9a-fA-F:]+)') if salt.utils.platform.is_sunos(): pip = re.compile(r'.*?(?:inet\s+)([0-9]+\.[0-9]+\.[0-9]+\.[0-9]+)(.*)') pip6 = re.compile('.*?(?:inet6 )([0-9a-fA-F:]+)') pmask6 = re.compile(r'.*?(?:inet6 [0-9a-fA-F:]+/(\d+)).*') else: pip = re.compile(r'.*?(?:inet addr:|inet [^\d]*)(.*?)\s') pip6 = re.compile('.*?(?:inet6 addr: (.*?)/|inet6 )([0-9a-fA-F:]+)') pmask6 = re.compile(r'.*?(?:inet6 addr: [0-9a-fA-F:]+/(\d+)|prefixlen (\d+))(?: Scope:([a-zA-Z]+)| scopeid (0x[0-9a-fA-F]))?') pmask = re.compile(r'.*?(?:Mask:|netmask )(?:((?:0x)?[0-9a-fA-F]{8})|([\d\.]+))') pupdown = re.compile('UP') pbcast = re.compile(r'.*?(?:Bcast:|broadcast )([\d\.]+)') groups = re.compile('\r?\n(?=\\S)').split(out) for group in groups: data = dict() iface = '' updown = False for line in group.splitlines(): miface = piface.match(line) mmac = pmac.match(line) mip = pip.match(line) mip6 = pip6.match(line) mupdown = pupdown.search(line) if miface: iface = miface.group(1) if mmac: data['hwaddr'] = mmac.group(1) if salt.utils.platform.is_sunos(): expand_mac = [] for chunk in data['hwaddr'].split(':'): expand_mac.append('0{0}'.format(chunk) if len(chunk) < 2 else '{0}'.format(chunk)) data['hwaddr'] = ':'.join(expand_mac) if mip: if 'inet' not in data: data['inet'] = list() addr_obj = dict() addr_obj['address'] = mip.group(1) mmask = pmask.match(line) if mmask: if mmask.group(1): mmask = _number_of_set_bits_to_ipv4_netmask( int(mmask.group(1), 16)) else: mmask = mmask.group(2) addr_obj['netmask'] = mmask mbcast = pbcast.match(line) if mbcast: addr_obj['broadcast'] = mbcast.group(1) data['inet'].append(addr_obj) if mupdown: updown = True if mip6: if 'inet6' not in data: data['inet6'] = list() addr_obj = dict() addr_obj['address'] = mip6.group(1) or mip6.group(2) mmask6 = pmask6.match(line) if mmask6: addr_obj['prefixlen'] = mmask6.group(1) or mmask6.group(2) if not salt.utils.platform.is_sunos(): ipv6scope = mmask6.group(3) or mmask6.group(4) addr_obj['scope'] = ipv6scope.lower() if ipv6scope is not None else ipv6scope # SunOS sometimes has ::/0 as inet6 addr when using addrconf if not salt.utils.platform.is_sunos() \ or addr_obj['address'] != '::' \ and addr_obj['prefixlen'] != 0: data['inet6'].append(addr_obj) data['up'] = updown if iface in ret: # SunOS optimization, where interfaces occur twice in 'ifconfig -a' # output with the same name: for ipv4 and then for ipv6 addr family. # Every instance has it's own 'UP' status and we assume that ipv4 # status determines global interface status. # # merge items with higher priority for older values # after that merge the inet and inet6 sub items for both ret[iface] = dict(list(data.items()) + list(ret[iface].items())) if 'inet' in data: ret[iface]['inet'].extend(x for x in data['inet'] if x not in ret[iface]['inet']) if 'inet6' in data: ret[iface]['inet6'].extend(x for x in data['inet6'] if x not in ret[iface]['inet6']) else: ret[iface] = data del data return ret def linux_interfaces(): ''' Obtain interface information for *NIX/BSD variants ''' ifaces = dict() ip_path = salt.utils.path.which('ip') ifconfig_path = None if ip_path else salt.utils.path.which('ifconfig') if ip_path: cmd1 = subprocess.Popen( '{0} link show'.format(ip_path), shell=True, close_fds=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT).communicate()[0] cmd2 = subprocess.Popen( '{0} addr show'.format(ip_path), shell=True, close_fds=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT).communicate()[0] ifaces = _interfaces_ip("{0}\n{1}".format( salt.utils.stringutils.to_str(cmd1), salt.utils.stringutils.to_str(cmd2))) elif ifconfig_path: cmd = subprocess.Popen( '{0} -a'.format(ifconfig_path), shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT).communicate()[0] ifaces = _interfaces_ifconfig(salt.utils.stringutils.to_str(cmd)) return ifaces def _netbsd_interfaces_ifconfig(out): ''' Uses ifconfig to return a dictionary of interfaces with various information about each (up/down state, ip address, netmask, and hwaddr) ''' ret = dict() piface = re.compile(r'^([^\s:]+)') pmac = re.compile('.*?address: ([0-9a-f:]+)') pip = re.compile(r'.*?inet [^\d]*(.*?)/([\d]*)\s') pip6 = re.compile(r'.*?inet6 ([0-9a-f:]+)%([a-zA-Z0-9]*)/([\d]*)\s') pupdown = re.compile('UP') pbcast = re.compile(r'.*?broadcast ([\d\.]+)') groups = re.compile('\r?\n(?=\\S)').split(out) for group in groups: data = dict() iface = '' updown = False for line in group.splitlines(): miface = piface.match(line) mmac = pmac.match(line) mip = pip.match(line) mip6 = pip6.match(line) mupdown = pupdown.search(line) if miface: iface = miface.group(1) if mmac: data['hwaddr'] = mmac.group(1) if mip: if 'inet' not in data: data['inet'] = list() addr_obj = dict() addr_obj['address'] = mip.group(1) mmask = mip.group(2) if mip.group(2): addr_obj['netmask'] = cidr_to_ipv4_netmask(mip.group(2)) mbcast = pbcast.match(line) if mbcast: addr_obj['broadcast'] = mbcast.group(1) data['inet'].append(addr_obj) if mupdown: updown = True if mip6: if 'inet6' not in data: data['inet6'] = list() addr_obj = dict() addr_obj['address'] = mip6.group(1) mmask6 = mip6.group(3) addr_obj['scope'] = mip6.group(2) addr_obj['prefixlen'] = mip6.group(3) data['inet6'].append(addr_obj) data['up'] = updown ret[iface] = data del data return ret def netbsd_interfaces(): ''' Obtain interface information for NetBSD >= 8 where the ifconfig output diverged from other BSD variants (Netmask is now part of the address) ''' # NetBSD versions prior to 8.0 can still use linux_interfaces() if LooseVersion(os.uname()[2]) < LooseVersion('8.0'): return linux_interfaces() ifconfig_path = salt.utils.path.which('ifconfig') cmd = subprocess.Popen( '{0} -a'.format(ifconfig_path), shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT).communicate()[0] return _netbsd_interfaces_ifconfig(salt.utils.stringutils.to_str(cmd)) def _interfaces_ipconfig(out): ''' Returns a dictionary of interfaces with various information about each (up/down state, ip address, netmask, and hwaddr) NOTE: This is not used by any function and may be able to be removed in the future. ''' ifaces = dict() iface = None adapter_iface_regex = re.compile(r'adapter (\S.+):$') for line in out.splitlines(): if not line: continue # TODO what does Windows call Infiniband and 10/40gige adapters if line.startswith('Ethernet'): iface = ifaces[adapter_iface_regex.search(line).group(1)] iface['up'] = True addr = None continue if iface: key, val = line.split(',', 1) key = key.strip(' .') val = val.strip() if addr and key == 'Subnet Mask': addr['netmask'] = val elif key in ('IP Address', 'IPv4 Address'): if 'inet' not in iface: iface['inet'] = list() addr = {'address': val.rstrip('(Preferred)'), 'netmask': None, 'broadcast': None} # TODO find the broadcast iface['inet'].append(addr) elif 'IPv6 Address' in key: if 'inet6' not in iface: iface['inet'] = list() # XXX What is the prefixlen!? addr = {'address': val.rstrip('(Preferred)'), 'prefixlen': None} iface['inet6'].append(addr) elif key == 'Physical Address': iface['hwaddr'] = val elif key == 'Media State': # XXX seen used for tunnel adaptors # might be useful iface['up'] = (val != 'Media disconnected') def win_interfaces(): ''' Obtain interface information for Windows systems ''' with salt.utils.winapi.Com(): c = wmi.WMI() ifaces = {} for iface in c.Win32_NetworkAdapterConfiguration(IPEnabled=1): ifaces[iface.Description] = dict() if iface.MACAddress: ifaces[iface.Description]['hwaddr'] = iface.MACAddress if iface.IPEnabled: ifaces[iface.Description]['up'] = True for ip in iface.IPAddress: if '.' in ip: if 'inet' not in ifaces[iface.Description]: ifaces[iface.Description]['inet'] = [] item = {'address': ip, 'label': iface.Description} if iface.DefaultIPGateway: broadcast = next((i for i in iface.DefaultIPGateway if '.' in i), '') if broadcast: item['broadcast'] = broadcast if iface.IPSubnet: netmask = next((i for i in iface.IPSubnet if '.' in i), '') if netmask: item['netmask'] = netmask ifaces[iface.Description]['inet'].append(item) if ':' in ip: if 'inet6' not in ifaces[iface.Description]: ifaces[iface.Description]['inet6'] = [] item = {'address': ip} if iface.DefaultIPGateway: broadcast = next((i for i in iface.DefaultIPGateway if ':' in i), '') if broadcast: item['broadcast'] = broadcast if iface.IPSubnet: netmask = next((i for i in iface.IPSubnet if ':' in i), '') if netmask: item['netmask'] = netmask ifaces[iface.Description]['inet6'].append(item) else: ifaces[iface.Description]['up'] = False return ifaces def interfaces(): ''' Return a dictionary of information about all the interfaces on the minion ''' if salt.utils.platform.is_windows(): return win_interfaces() elif salt.utils.platform.is_netbsd(): return netbsd_interfaces() else: return linux_interfaces() def get_net_start(ipaddr, netmask): ''' Return the address of the network ''' net = ipaddress.ip_network('{0}/{1}'.format(ipaddr, netmask), strict=False) return six.text_type(net.network_address) def get_net_size(mask): ''' Turns an IPv4 netmask into it's corresponding prefix length (255.255.255.0 -> 24 as in 192.168.1.10/24). ''' binary_str = '' for octet in mask.split('.'): binary_str += bin(int(octet))[2:].zfill(8) return len(binary_str.rstrip('0')) def calc_net(ipaddr, netmask=None): ''' Takes IP (CIDR notation supported) and optionally netmask and returns the network in CIDR-notation. (The IP can be any IP inside the subnet) ''' if netmask is not None: ipaddr = '{0}/{1}'.format(ipaddr, netmask) return six.text_type(ipaddress.ip_network(ipaddr, strict=False)) def _ipv4_to_bits(ipaddr): ''' Accepts an IPv4 dotted quad and returns a string representing its binary counterpart ''' return ''.join([bin(int(x))[2:].rjust(8, '0') for x in ipaddr.split('.')]) def _get_iface_info(iface): ''' If `iface` is available, return interface info and no error, otherwise return no info and log and return an error ''' iface_info = interfaces() if iface in iface_info.keys(): return iface_info, False else: error_msg = ('Interface "{0}" not in available interfaces: "{1}"' ''.format(iface, '", "'.join(iface_info.keys()))) log.error(error_msg) return None, error_msg def _hw_addr_aix(iface): ''' Return the hardware address (a.k.a. MAC address) for a given interface on AIX MAC address not available in through interfaces ''' cmd = subprocess.Popen( 'entstat -d {0} | grep \'Hardware Address\''.format(iface), shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT).communicate()[0] if cmd: comps = cmd.split(' ') if len(comps) == 3: mac_addr = comps[2].strip('\'').strip() return mac_addr error_msg = ('Interface "{0}" either not available or does not contain a hardware address'.format(iface)) log.error(error_msg) return error_msg def hw_addr(iface): ''' Return the hardware address (a.k.a. MAC address) for a given interface .. versionchanged:: 2016.11.4 Added support for AIX ''' if salt.utils.platform.is_aix(): return _hw_addr_aix iface_info, error = _get_iface_info(iface) if error is False: return iface_info.get(iface, {}).get('hwaddr', '') else: return error def interface(iface): ''' Return the details of `iface` or an error if it does not exist ''' iface_info, error = _get_iface_info(iface) if error is False: return iface_info.get(iface, {}).get('inet', '') else: return error def interface_ip(iface): ''' Return `iface` IPv4 addr or an error if `iface` does not exist ''' iface_info, error = _get_iface_info(iface) if error is False: inet = iface_info.get(iface, {}).get('inet', None) return inet[0].get('address', '') if inet else '' else: return error def _subnets(proto='inet', interfaces_=None): ''' Returns a list of subnets to which the host belongs ''' if interfaces_ is None: ifaces = interfaces() elif isinstance(interfaces_, list): ifaces = {} for key, value in six.iteritems(interfaces()): if key in interfaces_: ifaces[key] = value else: ifaces = {interfaces_: interfaces().get(interfaces_, {})} ret = set() if proto == 'inet': subnet = 'netmask' dflt_cidr = 32 elif proto == 'inet6': subnet = 'prefixlen' dflt_cidr = 128 else: log.error('Invalid proto %s calling subnets()', proto) return for ip_info in six.itervalues(ifaces): addrs = ip_info.get(proto, []) addrs.extend([addr for addr in ip_info.get('secondary', []) if addr.get('type') == proto]) for intf in addrs: if subnet in intf: intf = ipaddress.ip_interface('{0}/{1}'.format(intf['address'], intf[subnet])) else: intf = ipaddress.ip_interface('{0}/{1}'.format(intf['address'], dflt_cidr)) if not intf.is_loopback: ret.add(intf.network) return [six.text_type(net) for net in sorted(ret)] def subnets(interfaces=None): ''' Returns a list of IPv4 subnets to which the host belongs ''' return _subnets('inet', interfaces_=interfaces) def subnets6(): ''' Returns a list of IPv6 subnets to which the host belongs ''' return _subnets('inet6') def in_subnet(cidr, addr=None): ''' Returns True if host or (any of) addrs is within specified subnet, otherwise False ''' try: cidr = ipaddress.ip_network(cidr) except ValueError: log.error('Invalid CIDR \'%s\'', cidr) return False if addr is None: addr = ip_addrs() addr.extend(ip_addrs6()) elif not isinstance(addr, (list, tuple)): addr = (addr,) return any(ipaddress.ip_address(item) in cidr for item in addr) def _ip_addrs(interface=None, include_loopback=False, interface_data=None, proto='inet'): ''' Return the full list of IP adresses matching the criteria proto = inet|inet6 ''' ret = set() ifaces = interface_data \ if isinstance(interface_data, dict) \ else interfaces() if interface is None: target_ifaces = ifaces else: target_ifaces = dict([(k, v) for k, v in six.iteritems(ifaces) if k == interface]) if not target_ifaces: log.error('Interface %s not found.', interface) for ip_info in six.itervalues(target_ifaces): addrs = ip_info.get(proto, []) addrs.extend([addr for addr in ip_info.get('secondary', []) if addr.get('type') == proto]) for addr in addrs: addr = ipaddress.ip_address(addr.get('address')) if not addr.is_loopback or include_loopback: ret.add(addr) return [six.text_type(addr) for addr in sorted(ret)] def ip_addrs(interface=None, include_loopback=False, interface_data=None): ''' Returns a list of IPv4 addresses assigned to the host. 127.0.0.1 is ignored, unless 'include_loopback=True' is indicated. If 'interface' is provided, then only IP addresses from that interface will be returned. ''' return _ip_addrs(interface, include_loopback, interface_data, 'inet') def ip_addrs6(interface=None, include_loopback=False, interface_data=None): ''' Returns a list of IPv6 addresses assigned to the host. ::1 is ignored, unless 'include_loopback=True' is indicated. If 'interface' is provided, then only IP addresses from that interface will be returned. ''' return _ip_addrs(interface, include_loopback, interface_data, 'inet6') def hex2ip(hex_ip, invert=False): ''' Convert a hex string to an ip, if a failure occurs the original hex is returned. If 'invert=True' assume that ip from /proc/net/<proto> ''' if len(hex_ip) == 32: # ipv6 ip = [] for i in range(0, 32, 8): ip_part = hex_ip[i:i + 8] ip_part = [ip_part[x:x + 2] for x in range(0, 8, 2)] if invert: ip.append("{0[3]}{0[2]}:{0[1]}{0[0]}".format(ip_part)) else: ip.append("{0[0]}{0[1]}:{0[2]}{0[3]}".format(ip_part)) try: address = ipaddress.IPv6Address(":".join(ip)) if address.ipv4_mapped: return str(address.ipv4_mapped) else: return address.compressed except ipaddress.AddressValueError as ex: log.error('hex2ip - ipv6 address error: %s', ex) return hex_ip try: hip = int(hex_ip, 16) except ValueError: return hex_ip if invert: return '{3}.{2}.{1}.{0}'.format(hip >> 24 & 255, hip >> 16 & 255, hip >> 8 & 255, hip & 255) return '{0}.{1}.{2}.{3}'.format(hip >> 24 & 255, hip >> 16 & 255, hip >> 8 & 255, hip & 255) def mac2eui64(mac, prefix=None): ''' Convert a MAC address to a EUI64 identifier or, with prefix provided, a full IPv6 address ''' # http://tools.ietf.org/html/rfc4291#section-2.5.1 eui64 = re.sub(r'[.:-]', '', mac).lower() eui64 = eui64[0:6] + 'fffe' + eui64[6:] eui64 = hex(int(eui64[0:2], 16) | 2)[2:].zfill(2) + eui64[2:] if prefix is None: return ':'.join(re.findall(r'.{4}', eui64)) else: try: net = ipaddress.ip_network(prefix, strict=False) euil = int('0x{0}'.format(eui64), 16) return '{0}/{1}'.format(net[euil], net.prefixlen) except Exception: return def active_tcp(): ''' Return a dict describing all active tcp connections as quickly as possible ''' ret = {} for statf in ['/proc/net/tcp', '/proc/net/tcp6']: if os.path.isfile(statf): with salt.utils.files.fopen(statf, 'rb') as fp_: for line in fp_: line = salt.utils.stringutils.to_unicode(line) if line.strip().startswith('sl'): continue iret = _parse_tcp_line(line) sl = next(iter(iret)) if iret[sl]['state'] == 1: # 1 is ESTABLISHED del iret[sl]['state'] ret[len(ret)] = iret[sl] return ret def local_port_tcp(port): ''' Return a set of remote ip addrs attached to the specified local port ''' ret = _remotes_on(port, 'local_port') return ret def remote_port_tcp(port): ''' Return a set of ip addrs the current host is connected to on given port ''' ret = _remotes_on(port, 'remote_port') return ret def _remotes_on(port, which_end): ''' Return a set of ip addrs active tcp connections ''' port = int(port) ret = _netlink_tool_remote_on(port, which_end) if ret is not None: return ret ret = set() proc_available = False for statf in ['/proc/net/tcp', '/proc/net/tcp6']: if os.path.isfile(statf): proc_available = True with salt.utils.files.fopen(statf, 'r') as fp_: for line in fp_: line = salt.utils.stringutils.to_unicode(line) if line.strip().startswith('sl'): continue iret = _parse_tcp_line(line) sl = next(iter(iret)) if iret[sl][which_end] == port and iret[sl]['state'] == 1: # 1 is ESTABLISHED ret.add(iret[sl]['remote_addr']) if not proc_available: # Fallback to use OS specific tools if salt.utils.platform.is_sunos(): return _sunos_remotes_on(port, which_end) if salt.utils.platform.is_freebsd(): return _freebsd_remotes_on(port, which_end) if salt.utils.platform.is_netbsd(): return _netbsd_remotes_on(port, which_end) if salt.utils.platform.is_openbsd(): return _openbsd_remotes_on(port, which_end) if salt.utils.platform.is_windows(): return _windows_remotes_on(port, which_end) if salt.utils.platform.is_aix(): return _aix_remotes_on(port, which_end) return _linux_remotes_on(port, which_end) return ret def _parse_tcp_line(line): ''' Parse a single line from the contents of /proc/net/tcp or /proc/net/tcp6 ''' ret = {} comps = line.strip().split() sl = comps[0].rstrip(':') ret[sl] = {} l_addr, l_port = comps[1].split(':') r_addr, r_port = comps[2].split(':') ret[sl]['local_addr'] = hex2ip(l_addr, True) ret[sl]['local_port'] = int(l_port, 16) ret[sl]['remote_addr'] = hex2ip(r_addr, True) ret[sl]['remote_port'] = int(r_port, 16) ret[sl]['state'] = int(comps[3], 16) return ret def _netlink_tool_remote_on(port, which_end): ''' Returns set of ipv4 host addresses of remote established connections on local or remote tcp port. Parses output of shell 'ss' to get connections [root@salt-master ~]# ss -ant State Recv-Q Send-Q Local Address:Port Peer Address:Port LISTEN 0 511 *:80 *:* LISTEN 0 128 *:22 *:* ESTAB 0 0 127.0.0.1:56726 127.0.0.1:4505 ''' remotes = set() valid = False try: data = subprocess.check_output(['ss', '-ant']) # pylint: disable=minimum-python-version except subprocess.CalledProcessError: log.error('Failed ss') raise except OSError: # not command "No such file or directory" return None lines = salt.utils.stringutils.to_str(data).split('\n') for line in lines: if 'Address:Port' in line: # ss tools may not be valid valid = True continue elif 'ESTAB' not in line: continue chunks = line.split() local_host, local_port = chunks[3].split(':', 1) remote_host, remote_port = chunks[4].split(':', 1) if which_end == 'remote_port' and int(remote_port) != port: continue if which_end == 'local_port' and int(local_port) != port: continue remotes.add(remote_host) if valid is False: remotes = None return remotes def _sunos_remotes_on(port, which_end): ''' SunOS specific helper function. Returns set of ipv4 host addresses of remote established connections on local or remote tcp port. Parses output of shell 'netstat' to get connections [root@salt-master ~]# netstat -f inet -n TCP: IPv4 Local Address Remote Address Swind Send-Q Rwind Recv-Q State -------------------- -------------------- ----- ------ ----- ------ ----------- 10.0.0.101.4505 10.0.0.1.45329 1064800 0 1055864 0 ESTABLISHED 10.0.0.101.4505 10.0.0.100.50798 1064800 0 1055864 0 ESTABLISHED ''' remotes = set() try: data = subprocess.check_output(['netstat', '-f', 'inet', '-n']) # pylint: disable=minimum-python-version except subprocess.CalledProcessError: log.error('Failed netstat') raise lines = salt.utils.stringutils.to_str(data).split('\n') for line in lines: if 'ESTABLISHED' not in line: continue chunks = line.split() local_host, local_port = chunks[0].rsplit('.', 1) remote_host, remote_port = chunks[1].rsplit('.', 1) if which_end == 'remote_port' and int(remote_port) != port: continue if which_end == 'local_port' and int(local_port) != port: continue remotes.add(remote_host) return remotes def _freebsd_remotes_on(port, which_end): ''' Returns set of ipv4 host addresses of remote established connections on local tcp port port. Parses output of shell 'sockstat' (FreeBSD) to get connections $ sudo sockstat -4 USER COMMAND PID FD PROTO LOCAL ADDRESS FOREIGN ADDRESS root python2.7 1456 29 tcp4 *:4505 *:* root python2.7 1445 17 tcp4 *:4506 *:* root python2.7 1294 14 tcp4 127.0.0.1:11813 127.0.0.1:4505 root python2.7 1294 41 tcp4 127.0.0.1:61115 127.0.0.1:4506 $ sudo sockstat -4 -c -p 4506 USER COMMAND PID FD PROTO LOCAL ADDRESS FOREIGN ADDRESS root python2.7 1294 41 tcp4 127.0.0.1:61115 127.0.0.1:4506 ''' port = int(port) remotes = set() try: cmd = salt.utils.args.shlex_split('sockstat -4 -c -p {0}'.format(port)) data = subprocess.check_output(cmd) # pylint: disable=minimum-python-version except subprocess.CalledProcessError as ex: log.error('Failed "sockstat" with returncode = %s', ex.returncode) raise lines = salt.utils.stringutils.to_str(data).split('\n') for line in lines: chunks = line.split() if not chunks: continue # ['root', 'python2.7', '1456', '37', 'tcp4', # '127.0.0.1:4505-', '127.0.0.1:55703'] # print chunks if 'COMMAND' in chunks[1]: continue # ignore header if len(chunks) < 2: continue # sockstat -4 -c -p 4506 does this with high PIDs: # USER COMMAND PID FD PROTO LOCAL ADDRESS FOREIGN ADDRESS # salt-master python2.781106 35 tcp4 192.168.12.34:4506 192.168.12.45:60143 local = chunks[-2] remote = chunks[-1] lhost, lport = local.split(':') rhost, rport = remote.split(':') if which_end == 'local' and int(lport) != port: # ignore if local port not port continue if which_end == 'remote' and int(rport) != port: # ignore if remote port not port continue remotes.add(rhost) return remotes def _netbsd_remotes_on(port, which_end): ''' Returns set of ipv4 host addresses of remote established connections on local tcp port port. Parses output of shell 'sockstat' (NetBSD) to get connections $ sudo sockstat -4 -n USER COMMAND PID FD PROTO LOCAL ADDRESS FOREIGN ADDRESS root python2.7 1456 29 tcp *.4505 *.* root python2.7 1445 17 tcp *.4506 *.* root python2.7 1294 14 tcp 127.0.0.1.11813 127.0.0.1.4505 root python2.7 1294 41 tcp 127.0.0.1.61115 127.0.0.1.4506 $ sudo sockstat -4 -c -n -p 4506 USER COMMAND PID FD PROTO LOCAL ADDRESS FOREIGN ADDRESS root python2.7 1294 41 tcp 127.0.0.1.61115 127.0.0.1.4506 ''' port = int(port) remotes = set() try: cmd = salt.utils.args.shlex_split('sockstat -4 -c -n -p {0}'.format(port)) data = subprocess.check_output(cmd) # pylint: disable=minimum-python-version except subprocess.CalledProcessError as ex: log.error('Failed "sockstat" with returncode = %s', ex.returncode) raise lines = salt.utils.stringutils.to_str(data).split('\n') for line in lines: chunks = line.split() if not chunks: continue # ['root', 'python2.7', '1456', '37', 'tcp', # '127.0.0.1.4505-', '127.0.0.1.55703'] # print chunks if 'COMMAND' in chunks[1]: continue # ignore header if len(chunks) < 2: continue local = chunks[5].split('.') lport = local.pop() lhost = '.'.join(local) remote = chunks[6].split('.') rport = remote.pop() rhost = '.'.join(remote) if which_end == 'local' and int(lport) != port: # ignore if local port not port continue if which_end == 'remote' and int(rport) != port: # ignore if remote port not port continue remotes.add(rhost) return remotes def _openbsd_remotes_on(port, which_end): ''' OpenBSD specific helper function. Returns set of ipv4 host addresses of remote established connections on local or remote tcp port. Parses output of shell 'netstat' to get connections $ netstat -nf inet Active Internet connections Proto Recv-Q Send-Q Local Address Foreign Address (state) tcp 0 0 10.0.0.101.4505 10.0.0.1.45329 ESTABLISHED tcp 0 0 10.0.0.101.4505 10.0.0.100.50798 ESTABLISHED ''' remotes = set() try: data = subprocess.check_output(['netstat', '-nf', 'inet']) # pylint: disable=minimum-python-version except subprocess.CalledProcessError: log.error('Failed netstat') raise lines = data.split('\n') for line in lines: if 'ESTABLISHED' not in line: continue chunks = line.split() local_host, local_port = chunks[3].rsplit('.', 1) remote_host, remote_port = chunks[4].rsplit('.', 1) if which_end == 'remote_port' and int(remote_port) != port: continue if which_end == 'local_port' and int(local_port) != port: continue remotes.add(remote_host) return remotes def _windows_remotes_on(port, which_end): r''' Windows specific helper function. Returns set of ipv4 host addresses of remote established connections on local or remote tcp port. Parses output of shell 'netstat' to get connections C:\>netstat -n Active Connections Proto Local Address Foreign Address State TCP 10.2.33.17:3007 130.164.12.233:10123 ESTABLISHED TCP 10.2.33.17:3389 130.164.30.5:10378 ESTABLISHED ''' remotes = set() try: data = subprocess.check_output(['netstat', '-n']) # pylint: disable=minimum-python-version except subprocess.CalledProcessError: log.error('Failed netstat') raise lines = salt.utils.stringutils.to_str(data).split('\n') for line in lines: if 'ESTABLISHED' not in line: continue chunks = line.split() local_host, local_port = chunks[1].rsplit(':', 1) remote_host, remote_port = chunks[2].rsplit(':', 1) if which_end == 'remote_port' and int(remote_port) != port: continue if which_end == 'local_port' and int(local_port) != port: continue remotes.add(remote_host) return remotes def _linux_remotes_on(port, which_end): ''' Linux specific helper function. Returns set of ip host addresses of remote established connections on local tcp port port. Parses output of shell 'lsof' to get connections $ sudo lsof -iTCP:4505 -n COMMAND PID USER FD TYPE DEVICE SIZE/OFF NODE NAME Python 9971 root 35u IPv4 0x18a8464a29ca329d 0t0 TCP *:4505 (LISTEN) Python 9971 root 37u IPv4 0x18a8464a29b2b29d 0t0 TCP 127.0.0.1:4505->127.0.0.1:55703 (ESTABLISHED) Python 10152 root 22u IPv4 0x18a8464a29c8cab5 0t0 TCP 127.0.0.1:55703->127.0.0.1:4505 (ESTABLISHED) Python 10153 root 22u IPv4 0x18a8464a29c8cab5 0t0 TCP [fe80::249a]:4505->[fe80::150]:59367 (ESTABLISHED) ''' remotes = set() try: data = subprocess.check_output( ['lsof', '-iTCP:{0:d}'.format(port), '-n', '-P'] # pylint: disable=minimum-python-version ) except subprocess.CalledProcessError as ex: if ex.returncode == 1: # Lsof return 1 if any error was detected, including the failure # to locate Internet addresses, and it is not an error in this case. log.warning('"lsof" returncode = 1, likely no active TCP sessions.') return remotes log.error('Failed "lsof" with returncode = %s', ex.returncode) raise lines = salt.utils.stringutils.to_str(data).split('\n') for line in lines: chunks = line.split() if not chunks: continue # ['Python', '9971', 'root', '37u', 'IPv4', '0x18a8464a29b2b29d', '0t0', # 'TCP', '127.0.0.1:4505->127.0.0.1:55703', '(ESTABLISHED)'] # print chunks if 'COMMAND' in chunks[0]: continue # ignore header if 'ESTABLISHED' not in chunks[-1]: continue # ignore if not ESTABLISHED # '127.0.0.1:4505->127.0.0.1:55703' local, remote = chunks[8].split('->') _, lport = local.rsplit(':', 1) rhost, rport = remote.rsplit(':', 1) if which_end == 'remote_port' and int(rport) != port: continue if which_end == 'local_port' and int(lport) != port: continue remotes.add(rhost.strip("[]")) return remotes def _aix_remotes_on(port, which_end): ''' AIX specific helper function. Returns set of ipv4 host addresses of remote established connections on local or remote tcp port. Parses output of shell 'netstat' to get connections root@la68pp002_pub:/opt/salt/lib/python2.7/site-packages/salt/modules# netstat -f inet -n Active Internet connections Proto Recv-Q Send-Q Local Address Foreign Address (state) tcp4 0 0 172.29.149.95.50093 209.41.78.13.4505 ESTABLISHED tcp4 0 0 127.0.0.1.9514 *.* LISTEN tcp4 0 0 127.0.0.1.9515 *.* LISTEN tcp4 0 0 127.0.0.1.199 127.0.0.1.32779 ESTABLISHED tcp4 0 0 127.0.0.1.32779 127.0.0.1.199 ESTABLISHED tcp4 0 40 172.29.149.95.22 172.29.96.83.41022 ESTABLISHED tcp4 0 0 172.29.149.95.22 172.29.96.83.41032 ESTABLISHED tcp4 0 0 127.0.0.1.32771 127.0.0.1.32775 ESTABLISHED tcp 0 0 127.0.0.1.32775 127.0.0.1.32771 ESTABLISHED tcp4 0 0 127.0.0.1.32771 127.0.0.1.32776 ESTABLISHED tcp 0 0 127.0.0.1.32776 127.0.0.1.32771 ESTABLISHED tcp4 0 0 127.0.0.1.32771 127.0.0.1.32777 ESTABLISHED tcp 0 0 127.0.0.1.32777 127.0.0.1.32771 ESTABLISHED tcp4 0 0 127.0.0.1.32771 127.0.0.1.32778 ESTABLISHED tcp 0 0 127.0.0.1.32778 127.0.0.1.32771 ESTABLISHED ''' remotes = set() try: data = subprocess.check_output(['netstat', '-f', 'inet', '-n']) # pylint: disable=minimum-python-version except subprocess.CalledProcessError: log.error('Failed netstat') raise lines = salt.utils.stringutils.to_str(data).split('\n') for line in lines: if 'ESTABLISHED' not in line: continue chunks = line.split() local_host, local_port = chunks[3].rsplit('.', 1) remote_host, remote_port = chunks[4].rsplit('.', 1) if which_end == 'remote_port' and int(remote_port) != port: continue if which_end == 'local_port' and int(local_port) != port: continue remotes.add(remote_host) return remotes @jinja_filter('gen_mac') def gen_mac(prefix='AC:DE:48'): ''' Generates a MAC address with the defined OUI prefix. Common prefixes: - ``00:16:3E`` -- Xen - ``00:18:51`` -- OpenVZ - ``00:50:56`` -- VMware (manually generated) - ``52:54:00`` -- QEMU/KVM - ``AC:DE:48`` -- PRIVATE References: - http://standards.ieee.org/develop/regauth/oui/oui.txt - https://www.wireshark.org/tools/oui-lookup.html - https://en.wikipedia.org/wiki/MAC_address ''' return '{0}:{1:02X}:{2:02X}:{3:02X}'.format(prefix, random.randint(0, 0xff), random.randint(0, 0xff), random.randint(0, 0xff)) @jinja_filter('mac_str_to_bytes') def mac_str_to_bytes(mac_str): ''' Convert a MAC address string into bytes. Works with or without separators: b1 = mac_str_to_bytes('08:00:27:13:69:77') b2 = mac_str_to_bytes('080027136977') assert b1 == b2 assert isinstance(b1, bytes) ''' if len(mac_str) == 12: pass elif len(mac_str) == 17: sep = mac_str[2] mac_str = mac_str.replace(sep, '') else: raise ValueError('Invalid MAC address') chars = (int(mac_str[s:s+2], 16) for s in range(0, 12, 2)) return bytes(chars) if six.PY3 else b''.join(chr(x) for x in chars) def refresh_dns(): ''' issue #21397: force glibc to re-read resolv.conf ''' try: res_init() except NameError: # Exception raised loading the library, thus res_init is not defined pass @jinja_filter('connection_check') @jinja_filter('dns_check') def dns_check(addr, port=80, safe=False, ipv6=None, attempt_connect=True): ''' Return the ip resolved by dns, but do not exit on failure, only raise an exception. Obeys system preference for IPv4/6 address resolution - this can be overridden by the ipv6 flag. Tries to connect to the address before considering it useful. If no address can be reached, the first one resolved is used as a fallback. ''' error = False lookup = addr seen_ipv6 = False family = socket.AF_INET6 if ipv6 else socket.AF_INET if ipv6 is False else socket.AF_UNSPEC hostnames = [] try: refresh_dns() hostnames = socket.getaddrinfo(addr, port, family, socket.SOCK_STREAM) except TypeError: err = ('Attempt to resolve address \'{0}\' failed. Invalid or unresolveable address').format(lookup) raise SaltSystemExit(code=42, msg=err) except socket.error: error = True # If ipv6 is set to True, attempt another lookup using the IPv4 family, # just in case we're attempting to lookup an IPv4 IP # as an IPv6 hostname. if error and ipv6: try: refresh_dns() hostnames = socket.getaddrinfo(addr, port, socket.AF_INET, socket.SOCK_STREAM) except TypeError: err = ('Attempt to resolve address \'{0}\' failed. Invalid or unresolveable address').format(lookup) raise SaltSystemExit(code=42, msg=err) except socket.error: error = True try: if not hostnames: error = True else: resolved = False candidates = [] for h in hostnames: # Input is IP address, passed through unchanged, just return it if h[4][0] == addr: resolved = salt.utils.zeromq.ip_bracket(addr) break candidate_addr = salt.utils.zeromq.ip_bracket(h[4][0]) # sometimes /etc/hosts contains ::1 localhost if not ipv6 and candidate_addr == '[::1]': continue candidates.append(candidate_addr) if attempt_connect: try: s = socket.socket(h[0], socket.SOCK_STREAM) s.settimeout(2) s.connect((candidate_addr.strip('[]'), h[4][1])) s.close() resolved = candidate_addr break except socket.error: pass if not resolved: if candidates: resolved = candidates[0] else: error = True except TypeError: err = ('Attempt to resolve address \'{0}\' failed. Invalid or unresolveable address').format(lookup) raise SaltSystemExit(code=42, msg=err) except socket.error: error = True if error: err = ('DNS lookup or connection check of \'{0}\' failed.').format(addr) if safe: if salt.log.is_console_configured(): # If logging is not configured it also means that either # the master or minion instance calling this hasn't even # started running log.error(err) raise SaltClientError() raise SaltSystemExit(code=42, msg=err) return resolved def parse_host_port(host_port): """ Takes a string argument specifying host or host:port. Returns a (hostname, port) or (ip_address, port) tuple. If no port is given, the second (port) element of the returned tuple will be None. host:port argument, for example, is accepted in the forms of: - hostname - hostname:1234 - hostname.domain.tld - hostname.domain.tld:5678 - [1234::5]:5678 - 1234::5 - 10.11.12.13:4567 - 10.11.12.13 """ host, port = None, None # default _s_ = host_port[:] if _s_[0] == "[": if "]" in host_port: host, _s_ = _s_.lstrip("[").rsplit("]", 1) host = ipaddress.IPv6Address(host).compressed if _s_[0] == ":": port = int(_s_.lstrip(":")) else: if len(_s_) > 1: raise ValueError('found ambiguous "{}" port in "{}"'.format(_s_, host_port)) else: if _s_.count(":") == 1: host, _hostport_separator_, port = _s_.partition(":") try: port = int(port) except ValueError as _e_: log.error('host_port "%s" port value "%s" is not an integer.', host_port, port) raise _e_ else: host = _s_ try: if not isinstance(host, ipaddress._BaseAddress): host_ip = ipaddress.ip_address(host).compressed host = host_ip except ValueError: log.debug('"%s" Not an IP address? Assuming it is a hostname.', host) if host != sanitize_host(host): log.error('bad hostname: "%s"', host) raise ValueError('bad hostname: "{}"'.format(host)) return host, port def is_fqdn(hostname): """ Verify if hostname conforms to be a FQDN. :param hostname: text string with the name of the host :return: bool, True if hostname is correct FQDN, False otherwise """ compliant = re.compile(r"(?!-)[A-Z\d\-\_]{1,63}(?<!-)$", re.IGNORECASE) return "." in hostname and len(hostname) < 0xff and all(compliant.match(x) for x in hostname.rstrip(".").split("."))
saltstack/salt
salt/utils/network.py
dns_check
python
def dns_check(addr, port=80, safe=False, ipv6=None, attempt_connect=True): ''' Return the ip resolved by dns, but do not exit on failure, only raise an exception. Obeys system preference for IPv4/6 address resolution - this can be overridden by the ipv6 flag. Tries to connect to the address before considering it useful. If no address can be reached, the first one resolved is used as a fallback. ''' error = False lookup = addr seen_ipv6 = False family = socket.AF_INET6 if ipv6 else socket.AF_INET if ipv6 is False else socket.AF_UNSPEC hostnames = [] try: refresh_dns() hostnames = socket.getaddrinfo(addr, port, family, socket.SOCK_STREAM) except TypeError: err = ('Attempt to resolve address \'{0}\' failed. Invalid or unresolveable address').format(lookup) raise SaltSystemExit(code=42, msg=err) except socket.error: error = True # If ipv6 is set to True, attempt another lookup using the IPv4 family, # just in case we're attempting to lookup an IPv4 IP # as an IPv6 hostname. if error and ipv6: try: refresh_dns() hostnames = socket.getaddrinfo(addr, port, socket.AF_INET, socket.SOCK_STREAM) except TypeError: err = ('Attempt to resolve address \'{0}\' failed. Invalid or unresolveable address').format(lookup) raise SaltSystemExit(code=42, msg=err) except socket.error: error = True try: if not hostnames: error = True else: resolved = False candidates = [] for h in hostnames: # Input is IP address, passed through unchanged, just return it if h[4][0] == addr: resolved = salt.utils.zeromq.ip_bracket(addr) break candidate_addr = salt.utils.zeromq.ip_bracket(h[4][0]) # sometimes /etc/hosts contains ::1 localhost if not ipv6 and candidate_addr == '[::1]': continue candidates.append(candidate_addr) if attempt_connect: try: s = socket.socket(h[0], socket.SOCK_STREAM) s.settimeout(2) s.connect((candidate_addr.strip('[]'), h[4][1])) s.close() resolved = candidate_addr break except socket.error: pass if not resolved: if candidates: resolved = candidates[0] else: error = True except TypeError: err = ('Attempt to resolve address \'{0}\' failed. Invalid or unresolveable address').format(lookup) raise SaltSystemExit(code=42, msg=err) except socket.error: error = True if error: err = ('DNS lookup or connection check of \'{0}\' failed.').format(addr) if safe: if salt.log.is_console_configured(): # If logging is not configured it also means that either # the master or minion instance calling this hasn't even # started running log.error(err) raise SaltClientError() raise SaltSystemExit(code=42, msg=err) return resolved
Return the ip resolved by dns, but do not exit on failure, only raise an exception. Obeys system preference for IPv4/6 address resolution - this can be overridden by the ipv6 flag. Tries to connect to the address before considering it useful. If no address can be reached, the first one resolved is used as a fallback.
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/network.py#L1912-L2002
[ "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 is_console_configured():\n return __CONSOLE_CONFIGURED\n", "def refresh_dns():\n '''\n issue #21397: force glibc to re-read resolv.conf\n '''\n try:\n res_init()\n except NameError:\n # Exception raised loading the library, thus res_init is not defined\n pass\n" ]
# -*- coding: utf-8 -*- ''' Define some generic socket functions for network modules ''' # Import python libs from __future__ import absolute_import, unicode_literals, print_function import itertools import os import re import types import socket import logging import platform import random import subprocess from string import ascii_letters, digits # Import 3rd-party libs from salt.ext import six from salt.ext.six.moves import range # pylint: disable=import-error,redefined-builtin # Attempt to import wmi try: import wmi import salt.utils.winapi except ImportError: pass # Import salt libs import salt.utils.args import salt.utils.files import salt.utils.path import salt.utils.platform import salt.utils.stringutils import salt.utils.zeromq from salt._compat import ipaddress from salt.exceptions import SaltClientError, SaltSystemExit from salt.utils.decorators.jinja import jinja_filter from salt.utils.versions import LooseVersion # inet_pton does not exist in Windows, this is a workaround if salt.utils.platform.is_windows(): from salt.ext import win_inet_pton # pylint: disable=unused-import log = logging.getLogger(__name__) try: import ctypes import ctypes.util libc = ctypes.cdll.LoadLibrary(ctypes.util.find_library("c")) res_init = libc.__res_init except (ImportError, OSError, AttributeError, TypeError): pass # pylint: disable=C0103 def sanitize_host(host): ''' Sanitize host string. https://tools.ietf.org/html/rfc1123#section-2.1 ''' RFC952_characters = ascii_letters + digits + ".-" return "".join([c for c in host[0:255] if c in RFC952_characters]) def isportopen(host, port): ''' Return status of a port ''' if not 1 <= int(port) <= 65535: return False sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) out = sock.connect_ex((sanitize_host(host), int(port))) return out def host_to_ips(host): ''' Returns a list of IP addresses of a given hostname or None if not found. ''' ips = [] try: for family, socktype, proto, canonname, sockaddr in socket.getaddrinfo( host, 0, socket.AF_UNSPEC, socket.SOCK_STREAM): if family == socket.AF_INET: ip, port = sockaddr elif family == socket.AF_INET6: ip, port, flow_info, scope_id = sockaddr ips.append(ip) if not ips: ips = None except Exception: ips = None return ips def _generate_minion_id(): ''' Get list of possible host names and convention names. :return: ''' # There are three types of hostnames: # 1. Network names. How host is accessed from the network. # 2. Host aliases. They might be not available in all the network or only locally (/etc/hosts) # 3. Convention names, an internal nodename. class DistinctList(list): ''' List, which allows one to append only distinct objects. Needs to work on Python 2.6, because of collections.OrderedDict only since 2.7 version. Override 'filter()' for custom filtering. ''' localhost_matchers = [r'localhost.*', r'ip6-.*', r'127[.]\d', r'0\.0\.0\.0', r'::1.*', r'ipv6-.*', r'fe00::.*', r'fe02::.*', r'1.0.0.*.ip6.arpa'] def append(self, p_object): if p_object and p_object not in self and not self.filter(p_object): super(DistinctList, self).append(p_object) return self def extend(self, iterable): for obj in iterable: self.append(obj) return self def filter(self, element): 'Returns True if element needs to be filtered' for rgx in self.localhost_matchers: if re.match(rgx, element): return True def first(self): return self and self[0] or None hostname = socket.gethostname() hosts = DistinctList().append( salt.utils.stringutils.to_unicode(socket.getfqdn(salt.utils.stringutils.to_bytes(hostname))) ).append(platform.node()).append(hostname) if not hosts: try: for a_nfo in socket.getaddrinfo(hosts.first() or 'localhost', None, socket.AF_INET, socket.SOCK_RAW, socket.IPPROTO_IP, socket.AI_CANONNAME): if len(a_nfo) > 3: hosts.append(a_nfo[3]) except socket.gaierror: log.warning('Cannot resolve address %s info via socket: %s', hosts.first() or 'localhost (N/A)', socket.gaierror) # Universal method for everywhere (Linux, Slowlaris, Windows etc) for f_name in ('/etc/hostname', '/etc/nodename', '/etc/hosts', r'{win}\system32\drivers\etc\hosts'.format(win=os.getenv('WINDIR'))): try: with salt.utils.files.fopen(f_name) as f_hdl: for line in f_hdl: line = salt.utils.stringutils.to_unicode(line) hst = line.strip().split('#')[0].strip().split() if hst: if hst[0][:4] in ('127.', '::1') or len(hst) == 1: hosts.extend(hst) except IOError: pass # include public and private ipaddresses return hosts.extend([addr for addr in ip_addrs() if not ipaddress.ip_address(addr).is_loopback]) def generate_minion_id(): ''' Return only first element of the hostname from all possible list. :return: ''' try: ret = salt.utils.stringutils.to_unicode(_generate_minion_id().first()) except TypeError: ret = None return ret or 'localhost' def get_socket(addr, type=socket.SOCK_STREAM, proto=0): ''' Return a socket object for the addr IP-version agnostic ''' version = ipaddress.ip_address(addr).version if version == 4: family = socket.AF_INET elif version == 6: family = socket.AF_INET6 return socket.socket(family, type, proto) def get_fqhostname(): ''' Returns the fully qualified hostname ''' # try getaddrinfo() fqdn = None try: addrinfo = socket.getaddrinfo( socket.gethostname(), 0, socket.AF_UNSPEC, socket.SOCK_STREAM, socket.SOL_TCP, socket.AI_CANONNAME ) for info in addrinfo: # info struct [family, socktype, proto, canonname, sockaddr] # On Windows `canonname` can be an empty string # This can cause the function to return `None` if len(info) > 3 and info[3]: fqdn = info[3] break except socket.gaierror: pass # NOTE: this used to log.error() but it was later disabled except socket.error as err: log.debug('socket.getaddrinfo() failure while finding fqdn: %s', err) if fqdn is None: fqdn = socket.getfqdn() return fqdn def ip_to_host(ip): ''' Returns the hostname of a given IP ''' try: hostname, aliaslist, ipaddrlist = socket.gethostbyaddr(ip) except Exception as exc: log.debug('salt.utils.network.ip_to_host(%r) failed: %s', ip, exc) hostname = None return hostname # pylint: enable=C0103 def is_reachable_host(entity_name): ''' Returns a bool telling if the entity name is a reachable host (IPv4/IPv6/FQDN/etc). :param hostname: :return: ''' try: assert type(socket.getaddrinfo(entity_name, 0, 0, 0, 0)) == list ret = True except socket.gaierror: ret = False return ret def is_ip(ip): ''' Returns a bool telling if the passed IP is a valid IPv4 or IPv6 address. ''' return is_ipv4(ip) or is_ipv6(ip) def is_ipv4(ip): ''' Returns a bool telling if the value passed to it was a valid IPv4 address ''' try: return ipaddress.ip_address(ip).version == 4 except ValueError: return False def is_ipv6(ip): ''' Returns a bool telling if the value passed to it was a valid IPv6 address ''' try: return ipaddress.ip_address(ip).version == 6 except ValueError: return False def is_subnet(cidr): ''' Returns a bool telling if the passed string is an IPv4 or IPv6 subnet ''' return is_ipv4_subnet(cidr) or is_ipv6_subnet(cidr) def is_ipv4_subnet(cidr): ''' Returns a bool telling if the passed string is an IPv4 subnet ''' try: return '/' in cidr and bool(ipaddress.IPv4Network(cidr)) except Exception: return False def is_ipv6_subnet(cidr): ''' Returns a bool telling if the passed string is an IPv6 subnet ''' try: return '/' in cidr and bool(ipaddress.IPv6Network(cidr)) except Exception: return False @jinja_filter('is_ip') def is_ip_filter(ip, options=None): ''' Returns a bool telling if the passed IP is a valid IPv4 or IPv6 address. ''' return is_ipv4_filter(ip, options=options) or is_ipv6_filter(ip, options=options) def _ip_options_global(ip_obj, version): return not ip_obj.is_private def _ip_options_multicast(ip_obj, version): return ip_obj.is_multicast def _ip_options_loopback(ip_obj, version): return ip_obj.is_loopback def _ip_options_link_local(ip_obj, version): return ip_obj.is_link_local def _ip_options_private(ip_obj, version): return ip_obj.is_private def _ip_options_reserved(ip_obj, version): return ip_obj.is_reserved def _ip_options_site_local(ip_obj, version): if version == 6: return ip_obj.is_site_local return False def _ip_options_unspecified(ip_obj, version): return ip_obj.is_unspecified def _ip_options(ip_obj, version, options=None): # will process and IP options options_fun_map = { 'global': _ip_options_global, 'link-local': _ip_options_link_local, 'linklocal': _ip_options_link_local, 'll': _ip_options_link_local, 'link_local': _ip_options_link_local, 'loopback': _ip_options_loopback, 'lo': _ip_options_loopback, 'multicast': _ip_options_multicast, 'private': _ip_options_private, 'public': _ip_options_global, 'reserved': _ip_options_reserved, 'site-local': _ip_options_site_local, 'sl': _ip_options_site_local, 'site_local': _ip_options_site_local, 'unspecified': _ip_options_unspecified } if not options: return six.text_type(ip_obj) # IP version already checked options_list = [option.strip() for option in options.split(',')] for option, fun in options_fun_map.items(): if option in options_list: fun_res = fun(ip_obj, version) if not fun_res: return None # stop at first failed test # else continue return six.text_type(ip_obj) def _is_ipv(ip, version, options=None): if not version: version = 4 if version not in (4, 6): return None try: ip_obj = ipaddress.ip_address(ip) except ValueError: # maybe it is an IP network try: ip_obj = ipaddress.ip_interface(ip) except ValueError: # nope, still not :( return None if not ip_obj.version == version: return None # has the right version, let's move on return _ip_options(ip_obj, version, options=options) @jinja_filter('is_ipv4') def is_ipv4_filter(ip, options=None): ''' Returns a bool telling if the value passed to it was a valid IPv4 address. ip The IP address. net: False Consider IP addresses followed by netmask. options CSV of options regarding the nature of the IP address. E.g.: loopback, multicast, private etc. ''' _is_ipv4 = _is_ipv(ip, 4, options=options) return isinstance(_is_ipv4, six.string_types) @jinja_filter('is_ipv6') def is_ipv6_filter(ip, options=None): ''' Returns a bool telling if the value passed to it was a valid IPv6 address. ip The IP address. net: False Consider IP addresses followed by netmask. options CSV of options regarding the nature of the IP address. E.g.: loopback, multicast, private etc. ''' _is_ipv6 = _is_ipv(ip, 6, options=options) return isinstance(_is_ipv6, six.string_types) def _ipv_filter(value, version, options=None): if version not in (4, 6): return if isinstance(value, (six.string_types, six.text_type, six.binary_type)): return _is_ipv(value, version, options=options) # calls is_ipv4 or is_ipv6 for `value` elif isinstance(value, (list, tuple, types.GeneratorType)): # calls is_ipv4 or is_ipv6 for each element in the list # os it filters and returns only those elements having the desired IP version return [ _is_ipv(addr, version, options=options) for addr in value if _is_ipv(addr, version, options=options) is not None ] return None @jinja_filter('ipv4') def ipv4(value, options=None): ''' Filters a list and returns IPv4 values only. ''' return _ipv_filter(value, 4, options=options) @jinja_filter('ipv6') def ipv6(value, options=None): ''' Filters a list and returns IPv6 values only. ''' return _ipv_filter(value, 6, options=options) @jinja_filter('ipaddr') def ipaddr(value, options=None): ''' Filters and returns only valid IP objects. ''' ipv4_obj = ipv4(value, options=options) ipv6_obj = ipv6(value, options=options) if ipv4_obj is None or ipv6_obj is None: # an IP address can be either IPv4 either IPv6 # therefofe if the value passed as arg is not a list, at least one of the calls above will return None # if one of them is none, means that we should return only one of them return ipv4_obj or ipv6_obj # one of them else: return ipv4_obj + ipv6_obj # extend lists def _filter_ipaddr(value, options, version=None): ipaddr_filter_out = None if version: if version == 4: ipaddr_filter_out = ipv4(value, options) elif version == 6: ipaddr_filter_out = ipv6(value, options) else: ipaddr_filter_out = ipaddr(value, options) if not ipaddr_filter_out: return if not isinstance(ipaddr_filter_out, (list, tuple, types.GeneratorType)): ipaddr_filter_out = [ipaddr_filter_out] return ipaddr_filter_out @jinja_filter('ip_host') def ip_host(value, options=None, version=None): ''' Returns the interfaces IP address, e.g.: 192.168.0.1/28. ''' ipaddr_filter_out = _filter_ipaddr(value, options=options, version=version) if not ipaddr_filter_out: return if not isinstance(value, (list, tuple, types.GeneratorType)): return six.text_type(ipaddress.ip_interface(ipaddr_filter_out[0])) return [six.text_type(ipaddress.ip_interface(ip_a)) for ip_a in ipaddr_filter_out] def _network_hosts(ip_addr_entry): return [ six.text_type(host) for host in ipaddress.ip_network(ip_addr_entry, strict=False).hosts() ] @jinja_filter('network_hosts') def network_hosts(value, options=None, version=None): ''' Return the list of hosts within a network. .. note:: When running this command with a large IPv6 network, the command will take a long time to gather all of the hosts. ''' ipaddr_filter_out = _filter_ipaddr(value, options=options, version=version) if not ipaddr_filter_out: return if not isinstance(value, (list, tuple, types.GeneratorType)): return _network_hosts(ipaddr_filter_out[0]) return [ _network_hosts(ip_a) for ip_a in ipaddr_filter_out ] def _network_size(ip_addr_entry): return ipaddress.ip_network(ip_addr_entry, strict=False).num_addresses @jinja_filter('network_size') def network_size(value, options=None, version=None): ''' Get the size of a network. ''' ipaddr_filter_out = _filter_ipaddr(value, options=options, version=version) if not ipaddr_filter_out: return if not isinstance(value, (list, tuple, types.GeneratorType)): return _network_size(ipaddr_filter_out[0]) return [ _network_size(ip_a) for ip_a in ipaddr_filter_out ] def natural_ipv4_netmask(ip, fmt='prefixlen'): ''' Returns the "natural" mask of an IPv4 address ''' bits = _ipv4_to_bits(ip) if bits.startswith('11'): mask = '24' elif bits.startswith('1'): mask = '16' else: mask = '8' if fmt == 'netmask': return cidr_to_ipv4_netmask(mask) else: return '/' + mask def rpad_ipv4_network(ip): ''' Returns an IP network address padded with zeros. Ex: '192.168.3' -> '192.168.3.0' '10.209' -> '10.209.0.0' ''' return '.'.join(itertools.islice(itertools.chain(ip.split('.'), '0000'), 0, 4)) def cidr_to_ipv4_netmask(cidr_bits): ''' Returns an IPv4 netmask ''' try: cidr_bits = int(cidr_bits) if not 1 <= cidr_bits <= 32: return '' except ValueError: return '' netmask = '' for idx in range(4): if idx: netmask += '.' if cidr_bits >= 8: netmask += '255' cidr_bits -= 8 else: netmask += '{0:d}'.format(256 - (2 ** (8 - cidr_bits))) cidr_bits = 0 return netmask def _number_of_set_bits_to_ipv4_netmask(set_bits): # pylint: disable=C0103 ''' Returns an IPv4 netmask from the integer representation of that mask. Ex. 0xffffff00 -> '255.255.255.0' ''' return cidr_to_ipv4_netmask(_number_of_set_bits(set_bits)) # pylint: disable=C0103 def _number_of_set_bits(x): ''' Returns the number of bits that are set in a 32bit int ''' # Taken from http://stackoverflow.com/a/4912729. Many thanks! x -= (x >> 1) & 0x55555555 x = ((x >> 2) & 0x33333333) + (x & 0x33333333) x = ((x >> 4) + x) & 0x0f0f0f0f x += x >> 8 x += x >> 16 return x & 0x0000003f # pylint: enable=C0103 def _interfaces_ip(out): ''' Uses ip to return a dictionary of interfaces with various information about each (up/down state, ip address, netmask, and hwaddr) ''' ret = dict() def parse_network(value, cols): ''' Return a tuple of ip, netmask, broadcast based on the current set of cols ''' brd = None scope = None if '/' in value: # we have a CIDR in this address ip, cidr = value.split('/') # pylint: disable=C0103 else: ip = value # pylint: disable=C0103 cidr = 32 if type_ == 'inet': mask = cidr_to_ipv4_netmask(int(cidr)) if 'brd' in cols: brd = cols[cols.index('brd') + 1] elif type_ == 'inet6': mask = cidr if 'scope' in cols: scope = cols[cols.index('scope') + 1] return (ip, mask, brd, scope) groups = re.compile('\r?\n\\d').split(out) for group in groups: iface = None data = dict() for line in group.splitlines(): if ' ' not in line: continue match = re.match(r'^\d*:\s+([\w.\-]+)(?:@)?([\w.\-]+)?:\s+<(.+)>', line) if match: iface, parent, attrs = match.groups() if 'UP' in attrs.split(','): data['up'] = True else: data['up'] = False if parent: data['parent'] = parent continue cols = line.split() if len(cols) >= 2: type_, value = tuple(cols[0:2]) iflabel = cols[-1:][0] if type_ in ('inet', 'inet6'): if 'secondary' not in cols: ipaddr, netmask, broadcast, scope = parse_network(value, cols) if type_ == 'inet': if 'inet' not in data: data['inet'] = list() addr_obj = dict() addr_obj['address'] = ipaddr addr_obj['netmask'] = netmask addr_obj['broadcast'] = broadcast addr_obj['label'] = iflabel data['inet'].append(addr_obj) elif type_ == 'inet6': if 'inet6' not in data: data['inet6'] = list() addr_obj = dict() addr_obj['address'] = ipaddr addr_obj['prefixlen'] = netmask addr_obj['scope'] = scope data['inet6'].append(addr_obj) else: if 'secondary' not in data: data['secondary'] = list() ip_, mask, brd, scp = parse_network(value, cols) data['secondary'].append({ 'type': type_, 'address': ip_, 'netmask': mask, 'broadcast': brd, 'label': iflabel, }) del ip_, mask, brd, scp elif type_.startswith('link'): data['hwaddr'] = value if iface: ret[iface] = data del iface, data return ret def _interfaces_ifconfig(out): ''' Uses ifconfig to return a dictionary of interfaces with various information about each (up/down state, ip address, netmask, and hwaddr) ''' ret = dict() piface = re.compile(r'^([^\s:]+)') pmac = re.compile('.*?(?:HWaddr|ether|address:|lladdr) ([0-9a-fA-F:]+)') if salt.utils.platform.is_sunos(): pip = re.compile(r'.*?(?:inet\s+)([0-9]+\.[0-9]+\.[0-9]+\.[0-9]+)(.*)') pip6 = re.compile('.*?(?:inet6 )([0-9a-fA-F:]+)') pmask6 = re.compile(r'.*?(?:inet6 [0-9a-fA-F:]+/(\d+)).*') else: pip = re.compile(r'.*?(?:inet addr:|inet [^\d]*)(.*?)\s') pip6 = re.compile('.*?(?:inet6 addr: (.*?)/|inet6 )([0-9a-fA-F:]+)') pmask6 = re.compile(r'.*?(?:inet6 addr: [0-9a-fA-F:]+/(\d+)|prefixlen (\d+))(?: Scope:([a-zA-Z]+)| scopeid (0x[0-9a-fA-F]))?') pmask = re.compile(r'.*?(?:Mask:|netmask )(?:((?:0x)?[0-9a-fA-F]{8})|([\d\.]+))') pupdown = re.compile('UP') pbcast = re.compile(r'.*?(?:Bcast:|broadcast )([\d\.]+)') groups = re.compile('\r?\n(?=\\S)').split(out) for group in groups: data = dict() iface = '' updown = False for line in group.splitlines(): miface = piface.match(line) mmac = pmac.match(line) mip = pip.match(line) mip6 = pip6.match(line) mupdown = pupdown.search(line) if miface: iface = miface.group(1) if mmac: data['hwaddr'] = mmac.group(1) if salt.utils.platform.is_sunos(): expand_mac = [] for chunk in data['hwaddr'].split(':'): expand_mac.append('0{0}'.format(chunk) if len(chunk) < 2 else '{0}'.format(chunk)) data['hwaddr'] = ':'.join(expand_mac) if mip: if 'inet' not in data: data['inet'] = list() addr_obj = dict() addr_obj['address'] = mip.group(1) mmask = pmask.match(line) if mmask: if mmask.group(1): mmask = _number_of_set_bits_to_ipv4_netmask( int(mmask.group(1), 16)) else: mmask = mmask.group(2) addr_obj['netmask'] = mmask mbcast = pbcast.match(line) if mbcast: addr_obj['broadcast'] = mbcast.group(1) data['inet'].append(addr_obj) if mupdown: updown = True if mip6: if 'inet6' not in data: data['inet6'] = list() addr_obj = dict() addr_obj['address'] = mip6.group(1) or mip6.group(2) mmask6 = pmask6.match(line) if mmask6: addr_obj['prefixlen'] = mmask6.group(1) or mmask6.group(2) if not salt.utils.platform.is_sunos(): ipv6scope = mmask6.group(3) or mmask6.group(4) addr_obj['scope'] = ipv6scope.lower() if ipv6scope is not None else ipv6scope # SunOS sometimes has ::/0 as inet6 addr when using addrconf if not salt.utils.platform.is_sunos() \ or addr_obj['address'] != '::' \ and addr_obj['prefixlen'] != 0: data['inet6'].append(addr_obj) data['up'] = updown if iface in ret: # SunOS optimization, where interfaces occur twice in 'ifconfig -a' # output with the same name: for ipv4 and then for ipv6 addr family. # Every instance has it's own 'UP' status and we assume that ipv4 # status determines global interface status. # # merge items with higher priority for older values # after that merge the inet and inet6 sub items for both ret[iface] = dict(list(data.items()) + list(ret[iface].items())) if 'inet' in data: ret[iface]['inet'].extend(x for x in data['inet'] if x not in ret[iface]['inet']) if 'inet6' in data: ret[iface]['inet6'].extend(x for x in data['inet6'] if x not in ret[iface]['inet6']) else: ret[iface] = data del data return ret def linux_interfaces(): ''' Obtain interface information for *NIX/BSD variants ''' ifaces = dict() ip_path = salt.utils.path.which('ip') ifconfig_path = None if ip_path else salt.utils.path.which('ifconfig') if ip_path: cmd1 = subprocess.Popen( '{0} link show'.format(ip_path), shell=True, close_fds=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT).communicate()[0] cmd2 = subprocess.Popen( '{0} addr show'.format(ip_path), shell=True, close_fds=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT).communicate()[0] ifaces = _interfaces_ip("{0}\n{1}".format( salt.utils.stringutils.to_str(cmd1), salt.utils.stringutils.to_str(cmd2))) elif ifconfig_path: cmd = subprocess.Popen( '{0} -a'.format(ifconfig_path), shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT).communicate()[0] ifaces = _interfaces_ifconfig(salt.utils.stringutils.to_str(cmd)) return ifaces def _netbsd_interfaces_ifconfig(out): ''' Uses ifconfig to return a dictionary of interfaces with various information about each (up/down state, ip address, netmask, and hwaddr) ''' ret = dict() piface = re.compile(r'^([^\s:]+)') pmac = re.compile('.*?address: ([0-9a-f:]+)') pip = re.compile(r'.*?inet [^\d]*(.*?)/([\d]*)\s') pip6 = re.compile(r'.*?inet6 ([0-9a-f:]+)%([a-zA-Z0-9]*)/([\d]*)\s') pupdown = re.compile('UP') pbcast = re.compile(r'.*?broadcast ([\d\.]+)') groups = re.compile('\r?\n(?=\\S)').split(out) for group in groups: data = dict() iface = '' updown = False for line in group.splitlines(): miface = piface.match(line) mmac = pmac.match(line) mip = pip.match(line) mip6 = pip6.match(line) mupdown = pupdown.search(line) if miface: iface = miface.group(1) if mmac: data['hwaddr'] = mmac.group(1) if mip: if 'inet' not in data: data['inet'] = list() addr_obj = dict() addr_obj['address'] = mip.group(1) mmask = mip.group(2) if mip.group(2): addr_obj['netmask'] = cidr_to_ipv4_netmask(mip.group(2)) mbcast = pbcast.match(line) if mbcast: addr_obj['broadcast'] = mbcast.group(1) data['inet'].append(addr_obj) if mupdown: updown = True if mip6: if 'inet6' not in data: data['inet6'] = list() addr_obj = dict() addr_obj['address'] = mip6.group(1) mmask6 = mip6.group(3) addr_obj['scope'] = mip6.group(2) addr_obj['prefixlen'] = mip6.group(3) data['inet6'].append(addr_obj) data['up'] = updown ret[iface] = data del data return ret def netbsd_interfaces(): ''' Obtain interface information for NetBSD >= 8 where the ifconfig output diverged from other BSD variants (Netmask is now part of the address) ''' # NetBSD versions prior to 8.0 can still use linux_interfaces() if LooseVersion(os.uname()[2]) < LooseVersion('8.0'): return linux_interfaces() ifconfig_path = salt.utils.path.which('ifconfig') cmd = subprocess.Popen( '{0} -a'.format(ifconfig_path), shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT).communicate()[0] return _netbsd_interfaces_ifconfig(salt.utils.stringutils.to_str(cmd)) def _interfaces_ipconfig(out): ''' Returns a dictionary of interfaces with various information about each (up/down state, ip address, netmask, and hwaddr) NOTE: This is not used by any function and may be able to be removed in the future. ''' ifaces = dict() iface = None adapter_iface_regex = re.compile(r'adapter (\S.+):$') for line in out.splitlines(): if not line: continue # TODO what does Windows call Infiniband and 10/40gige adapters if line.startswith('Ethernet'): iface = ifaces[adapter_iface_regex.search(line).group(1)] iface['up'] = True addr = None continue if iface: key, val = line.split(',', 1) key = key.strip(' .') val = val.strip() if addr and key == 'Subnet Mask': addr['netmask'] = val elif key in ('IP Address', 'IPv4 Address'): if 'inet' not in iface: iface['inet'] = list() addr = {'address': val.rstrip('(Preferred)'), 'netmask': None, 'broadcast': None} # TODO find the broadcast iface['inet'].append(addr) elif 'IPv6 Address' in key: if 'inet6' not in iface: iface['inet'] = list() # XXX What is the prefixlen!? addr = {'address': val.rstrip('(Preferred)'), 'prefixlen': None} iface['inet6'].append(addr) elif key == 'Physical Address': iface['hwaddr'] = val elif key == 'Media State': # XXX seen used for tunnel adaptors # might be useful iface['up'] = (val != 'Media disconnected') def win_interfaces(): ''' Obtain interface information for Windows systems ''' with salt.utils.winapi.Com(): c = wmi.WMI() ifaces = {} for iface in c.Win32_NetworkAdapterConfiguration(IPEnabled=1): ifaces[iface.Description] = dict() if iface.MACAddress: ifaces[iface.Description]['hwaddr'] = iface.MACAddress if iface.IPEnabled: ifaces[iface.Description]['up'] = True for ip in iface.IPAddress: if '.' in ip: if 'inet' not in ifaces[iface.Description]: ifaces[iface.Description]['inet'] = [] item = {'address': ip, 'label': iface.Description} if iface.DefaultIPGateway: broadcast = next((i for i in iface.DefaultIPGateway if '.' in i), '') if broadcast: item['broadcast'] = broadcast if iface.IPSubnet: netmask = next((i for i in iface.IPSubnet if '.' in i), '') if netmask: item['netmask'] = netmask ifaces[iface.Description]['inet'].append(item) if ':' in ip: if 'inet6' not in ifaces[iface.Description]: ifaces[iface.Description]['inet6'] = [] item = {'address': ip} if iface.DefaultIPGateway: broadcast = next((i for i in iface.DefaultIPGateway if ':' in i), '') if broadcast: item['broadcast'] = broadcast if iface.IPSubnet: netmask = next((i for i in iface.IPSubnet if ':' in i), '') if netmask: item['netmask'] = netmask ifaces[iface.Description]['inet6'].append(item) else: ifaces[iface.Description]['up'] = False return ifaces def interfaces(): ''' Return a dictionary of information about all the interfaces on the minion ''' if salt.utils.platform.is_windows(): return win_interfaces() elif salt.utils.platform.is_netbsd(): return netbsd_interfaces() else: return linux_interfaces() def get_net_start(ipaddr, netmask): ''' Return the address of the network ''' net = ipaddress.ip_network('{0}/{1}'.format(ipaddr, netmask), strict=False) return six.text_type(net.network_address) def get_net_size(mask): ''' Turns an IPv4 netmask into it's corresponding prefix length (255.255.255.0 -> 24 as in 192.168.1.10/24). ''' binary_str = '' for octet in mask.split('.'): binary_str += bin(int(octet))[2:].zfill(8) return len(binary_str.rstrip('0')) def calc_net(ipaddr, netmask=None): ''' Takes IP (CIDR notation supported) and optionally netmask and returns the network in CIDR-notation. (The IP can be any IP inside the subnet) ''' if netmask is not None: ipaddr = '{0}/{1}'.format(ipaddr, netmask) return six.text_type(ipaddress.ip_network(ipaddr, strict=False)) def _ipv4_to_bits(ipaddr): ''' Accepts an IPv4 dotted quad and returns a string representing its binary counterpart ''' return ''.join([bin(int(x))[2:].rjust(8, '0') for x in ipaddr.split('.')]) def _get_iface_info(iface): ''' If `iface` is available, return interface info and no error, otherwise return no info and log and return an error ''' iface_info = interfaces() if iface in iface_info.keys(): return iface_info, False else: error_msg = ('Interface "{0}" not in available interfaces: "{1}"' ''.format(iface, '", "'.join(iface_info.keys()))) log.error(error_msg) return None, error_msg def _hw_addr_aix(iface): ''' Return the hardware address (a.k.a. MAC address) for a given interface on AIX MAC address not available in through interfaces ''' cmd = subprocess.Popen( 'entstat -d {0} | grep \'Hardware Address\''.format(iface), shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT).communicate()[0] if cmd: comps = cmd.split(' ') if len(comps) == 3: mac_addr = comps[2].strip('\'').strip() return mac_addr error_msg = ('Interface "{0}" either not available or does not contain a hardware address'.format(iface)) log.error(error_msg) return error_msg def hw_addr(iface): ''' Return the hardware address (a.k.a. MAC address) for a given interface .. versionchanged:: 2016.11.4 Added support for AIX ''' if salt.utils.platform.is_aix(): return _hw_addr_aix iface_info, error = _get_iface_info(iface) if error is False: return iface_info.get(iface, {}).get('hwaddr', '') else: return error def interface(iface): ''' Return the details of `iface` or an error if it does not exist ''' iface_info, error = _get_iface_info(iface) if error is False: return iface_info.get(iface, {}).get('inet', '') else: return error def interface_ip(iface): ''' Return `iface` IPv4 addr or an error if `iface` does not exist ''' iface_info, error = _get_iface_info(iface) if error is False: inet = iface_info.get(iface, {}).get('inet', None) return inet[0].get('address', '') if inet else '' else: return error def _subnets(proto='inet', interfaces_=None): ''' Returns a list of subnets to which the host belongs ''' if interfaces_ is None: ifaces = interfaces() elif isinstance(interfaces_, list): ifaces = {} for key, value in six.iteritems(interfaces()): if key in interfaces_: ifaces[key] = value else: ifaces = {interfaces_: interfaces().get(interfaces_, {})} ret = set() if proto == 'inet': subnet = 'netmask' dflt_cidr = 32 elif proto == 'inet6': subnet = 'prefixlen' dflt_cidr = 128 else: log.error('Invalid proto %s calling subnets()', proto) return for ip_info in six.itervalues(ifaces): addrs = ip_info.get(proto, []) addrs.extend([addr for addr in ip_info.get('secondary', []) if addr.get('type') == proto]) for intf in addrs: if subnet in intf: intf = ipaddress.ip_interface('{0}/{1}'.format(intf['address'], intf[subnet])) else: intf = ipaddress.ip_interface('{0}/{1}'.format(intf['address'], dflt_cidr)) if not intf.is_loopback: ret.add(intf.network) return [six.text_type(net) for net in sorted(ret)] def subnets(interfaces=None): ''' Returns a list of IPv4 subnets to which the host belongs ''' return _subnets('inet', interfaces_=interfaces) def subnets6(): ''' Returns a list of IPv6 subnets to which the host belongs ''' return _subnets('inet6') def in_subnet(cidr, addr=None): ''' Returns True if host or (any of) addrs is within specified subnet, otherwise False ''' try: cidr = ipaddress.ip_network(cidr) except ValueError: log.error('Invalid CIDR \'%s\'', cidr) return False if addr is None: addr = ip_addrs() addr.extend(ip_addrs6()) elif not isinstance(addr, (list, tuple)): addr = (addr,) return any(ipaddress.ip_address(item) in cidr for item in addr) def _ip_addrs(interface=None, include_loopback=False, interface_data=None, proto='inet'): ''' Return the full list of IP adresses matching the criteria proto = inet|inet6 ''' ret = set() ifaces = interface_data \ if isinstance(interface_data, dict) \ else interfaces() if interface is None: target_ifaces = ifaces else: target_ifaces = dict([(k, v) for k, v in six.iteritems(ifaces) if k == interface]) if not target_ifaces: log.error('Interface %s not found.', interface) for ip_info in six.itervalues(target_ifaces): addrs = ip_info.get(proto, []) addrs.extend([addr for addr in ip_info.get('secondary', []) if addr.get('type') == proto]) for addr in addrs: addr = ipaddress.ip_address(addr.get('address')) if not addr.is_loopback or include_loopback: ret.add(addr) return [six.text_type(addr) for addr in sorted(ret)] def ip_addrs(interface=None, include_loopback=False, interface_data=None): ''' Returns a list of IPv4 addresses assigned to the host. 127.0.0.1 is ignored, unless 'include_loopback=True' is indicated. If 'interface' is provided, then only IP addresses from that interface will be returned. ''' return _ip_addrs(interface, include_loopback, interface_data, 'inet') def ip_addrs6(interface=None, include_loopback=False, interface_data=None): ''' Returns a list of IPv6 addresses assigned to the host. ::1 is ignored, unless 'include_loopback=True' is indicated. If 'interface' is provided, then only IP addresses from that interface will be returned. ''' return _ip_addrs(interface, include_loopback, interface_data, 'inet6') def hex2ip(hex_ip, invert=False): ''' Convert a hex string to an ip, if a failure occurs the original hex is returned. If 'invert=True' assume that ip from /proc/net/<proto> ''' if len(hex_ip) == 32: # ipv6 ip = [] for i in range(0, 32, 8): ip_part = hex_ip[i:i + 8] ip_part = [ip_part[x:x + 2] for x in range(0, 8, 2)] if invert: ip.append("{0[3]}{0[2]}:{0[1]}{0[0]}".format(ip_part)) else: ip.append("{0[0]}{0[1]}:{0[2]}{0[3]}".format(ip_part)) try: address = ipaddress.IPv6Address(":".join(ip)) if address.ipv4_mapped: return str(address.ipv4_mapped) else: return address.compressed except ipaddress.AddressValueError as ex: log.error('hex2ip - ipv6 address error: %s', ex) return hex_ip try: hip = int(hex_ip, 16) except ValueError: return hex_ip if invert: return '{3}.{2}.{1}.{0}'.format(hip >> 24 & 255, hip >> 16 & 255, hip >> 8 & 255, hip & 255) return '{0}.{1}.{2}.{3}'.format(hip >> 24 & 255, hip >> 16 & 255, hip >> 8 & 255, hip & 255) def mac2eui64(mac, prefix=None): ''' Convert a MAC address to a EUI64 identifier or, with prefix provided, a full IPv6 address ''' # http://tools.ietf.org/html/rfc4291#section-2.5.1 eui64 = re.sub(r'[.:-]', '', mac).lower() eui64 = eui64[0:6] + 'fffe' + eui64[6:] eui64 = hex(int(eui64[0:2], 16) | 2)[2:].zfill(2) + eui64[2:] if prefix is None: return ':'.join(re.findall(r'.{4}', eui64)) else: try: net = ipaddress.ip_network(prefix, strict=False) euil = int('0x{0}'.format(eui64), 16) return '{0}/{1}'.format(net[euil], net.prefixlen) except Exception: return def active_tcp(): ''' Return a dict describing all active tcp connections as quickly as possible ''' ret = {} for statf in ['/proc/net/tcp', '/proc/net/tcp6']: if os.path.isfile(statf): with salt.utils.files.fopen(statf, 'rb') as fp_: for line in fp_: line = salt.utils.stringutils.to_unicode(line) if line.strip().startswith('sl'): continue iret = _parse_tcp_line(line) sl = next(iter(iret)) if iret[sl]['state'] == 1: # 1 is ESTABLISHED del iret[sl]['state'] ret[len(ret)] = iret[sl] return ret def local_port_tcp(port): ''' Return a set of remote ip addrs attached to the specified local port ''' ret = _remotes_on(port, 'local_port') return ret def remote_port_tcp(port): ''' Return a set of ip addrs the current host is connected to on given port ''' ret = _remotes_on(port, 'remote_port') return ret def _remotes_on(port, which_end): ''' Return a set of ip addrs active tcp connections ''' port = int(port) ret = _netlink_tool_remote_on(port, which_end) if ret is not None: return ret ret = set() proc_available = False for statf in ['/proc/net/tcp', '/proc/net/tcp6']: if os.path.isfile(statf): proc_available = True with salt.utils.files.fopen(statf, 'r') as fp_: for line in fp_: line = salt.utils.stringutils.to_unicode(line) if line.strip().startswith('sl'): continue iret = _parse_tcp_line(line) sl = next(iter(iret)) if iret[sl][which_end] == port and iret[sl]['state'] == 1: # 1 is ESTABLISHED ret.add(iret[sl]['remote_addr']) if not proc_available: # Fallback to use OS specific tools if salt.utils.platform.is_sunos(): return _sunos_remotes_on(port, which_end) if salt.utils.platform.is_freebsd(): return _freebsd_remotes_on(port, which_end) if salt.utils.platform.is_netbsd(): return _netbsd_remotes_on(port, which_end) if salt.utils.platform.is_openbsd(): return _openbsd_remotes_on(port, which_end) if salt.utils.platform.is_windows(): return _windows_remotes_on(port, which_end) if salt.utils.platform.is_aix(): return _aix_remotes_on(port, which_end) return _linux_remotes_on(port, which_end) return ret def _parse_tcp_line(line): ''' Parse a single line from the contents of /proc/net/tcp or /proc/net/tcp6 ''' ret = {} comps = line.strip().split() sl = comps[0].rstrip(':') ret[sl] = {} l_addr, l_port = comps[1].split(':') r_addr, r_port = comps[2].split(':') ret[sl]['local_addr'] = hex2ip(l_addr, True) ret[sl]['local_port'] = int(l_port, 16) ret[sl]['remote_addr'] = hex2ip(r_addr, True) ret[sl]['remote_port'] = int(r_port, 16) ret[sl]['state'] = int(comps[3], 16) return ret def _netlink_tool_remote_on(port, which_end): ''' Returns set of ipv4 host addresses of remote established connections on local or remote tcp port. Parses output of shell 'ss' to get connections [root@salt-master ~]# ss -ant State Recv-Q Send-Q Local Address:Port Peer Address:Port LISTEN 0 511 *:80 *:* LISTEN 0 128 *:22 *:* ESTAB 0 0 127.0.0.1:56726 127.0.0.1:4505 ''' remotes = set() valid = False try: data = subprocess.check_output(['ss', '-ant']) # pylint: disable=minimum-python-version except subprocess.CalledProcessError: log.error('Failed ss') raise except OSError: # not command "No such file or directory" return None lines = salt.utils.stringutils.to_str(data).split('\n') for line in lines: if 'Address:Port' in line: # ss tools may not be valid valid = True continue elif 'ESTAB' not in line: continue chunks = line.split() local_host, local_port = chunks[3].split(':', 1) remote_host, remote_port = chunks[4].split(':', 1) if which_end == 'remote_port' and int(remote_port) != port: continue if which_end == 'local_port' and int(local_port) != port: continue remotes.add(remote_host) if valid is False: remotes = None return remotes def _sunos_remotes_on(port, which_end): ''' SunOS specific helper function. Returns set of ipv4 host addresses of remote established connections on local or remote tcp port. Parses output of shell 'netstat' to get connections [root@salt-master ~]# netstat -f inet -n TCP: IPv4 Local Address Remote Address Swind Send-Q Rwind Recv-Q State -------------------- -------------------- ----- ------ ----- ------ ----------- 10.0.0.101.4505 10.0.0.1.45329 1064800 0 1055864 0 ESTABLISHED 10.0.0.101.4505 10.0.0.100.50798 1064800 0 1055864 0 ESTABLISHED ''' remotes = set() try: data = subprocess.check_output(['netstat', '-f', 'inet', '-n']) # pylint: disable=minimum-python-version except subprocess.CalledProcessError: log.error('Failed netstat') raise lines = salt.utils.stringutils.to_str(data).split('\n') for line in lines: if 'ESTABLISHED' not in line: continue chunks = line.split() local_host, local_port = chunks[0].rsplit('.', 1) remote_host, remote_port = chunks[1].rsplit('.', 1) if which_end == 'remote_port' and int(remote_port) != port: continue if which_end == 'local_port' and int(local_port) != port: continue remotes.add(remote_host) return remotes def _freebsd_remotes_on(port, which_end): ''' Returns set of ipv4 host addresses of remote established connections on local tcp port port. Parses output of shell 'sockstat' (FreeBSD) to get connections $ sudo sockstat -4 USER COMMAND PID FD PROTO LOCAL ADDRESS FOREIGN ADDRESS root python2.7 1456 29 tcp4 *:4505 *:* root python2.7 1445 17 tcp4 *:4506 *:* root python2.7 1294 14 tcp4 127.0.0.1:11813 127.0.0.1:4505 root python2.7 1294 41 tcp4 127.0.0.1:61115 127.0.0.1:4506 $ sudo sockstat -4 -c -p 4506 USER COMMAND PID FD PROTO LOCAL ADDRESS FOREIGN ADDRESS root python2.7 1294 41 tcp4 127.0.0.1:61115 127.0.0.1:4506 ''' port = int(port) remotes = set() try: cmd = salt.utils.args.shlex_split('sockstat -4 -c -p {0}'.format(port)) data = subprocess.check_output(cmd) # pylint: disable=minimum-python-version except subprocess.CalledProcessError as ex: log.error('Failed "sockstat" with returncode = %s', ex.returncode) raise lines = salt.utils.stringutils.to_str(data).split('\n') for line in lines: chunks = line.split() if not chunks: continue # ['root', 'python2.7', '1456', '37', 'tcp4', # '127.0.0.1:4505-', '127.0.0.1:55703'] # print chunks if 'COMMAND' in chunks[1]: continue # ignore header if len(chunks) < 2: continue # sockstat -4 -c -p 4506 does this with high PIDs: # USER COMMAND PID FD PROTO LOCAL ADDRESS FOREIGN ADDRESS # salt-master python2.781106 35 tcp4 192.168.12.34:4506 192.168.12.45:60143 local = chunks[-2] remote = chunks[-1] lhost, lport = local.split(':') rhost, rport = remote.split(':') if which_end == 'local' and int(lport) != port: # ignore if local port not port continue if which_end == 'remote' and int(rport) != port: # ignore if remote port not port continue remotes.add(rhost) return remotes def _netbsd_remotes_on(port, which_end): ''' Returns set of ipv4 host addresses of remote established connections on local tcp port port. Parses output of shell 'sockstat' (NetBSD) to get connections $ sudo sockstat -4 -n USER COMMAND PID FD PROTO LOCAL ADDRESS FOREIGN ADDRESS root python2.7 1456 29 tcp *.4505 *.* root python2.7 1445 17 tcp *.4506 *.* root python2.7 1294 14 tcp 127.0.0.1.11813 127.0.0.1.4505 root python2.7 1294 41 tcp 127.0.0.1.61115 127.0.0.1.4506 $ sudo sockstat -4 -c -n -p 4506 USER COMMAND PID FD PROTO LOCAL ADDRESS FOREIGN ADDRESS root python2.7 1294 41 tcp 127.0.0.1.61115 127.0.0.1.4506 ''' port = int(port) remotes = set() try: cmd = salt.utils.args.shlex_split('sockstat -4 -c -n -p {0}'.format(port)) data = subprocess.check_output(cmd) # pylint: disable=minimum-python-version except subprocess.CalledProcessError as ex: log.error('Failed "sockstat" with returncode = %s', ex.returncode) raise lines = salt.utils.stringutils.to_str(data).split('\n') for line in lines: chunks = line.split() if not chunks: continue # ['root', 'python2.7', '1456', '37', 'tcp', # '127.0.0.1.4505-', '127.0.0.1.55703'] # print chunks if 'COMMAND' in chunks[1]: continue # ignore header if len(chunks) < 2: continue local = chunks[5].split('.') lport = local.pop() lhost = '.'.join(local) remote = chunks[6].split('.') rport = remote.pop() rhost = '.'.join(remote) if which_end == 'local' and int(lport) != port: # ignore if local port not port continue if which_end == 'remote' and int(rport) != port: # ignore if remote port not port continue remotes.add(rhost) return remotes def _openbsd_remotes_on(port, which_end): ''' OpenBSD specific helper function. Returns set of ipv4 host addresses of remote established connections on local or remote tcp port. Parses output of shell 'netstat' to get connections $ netstat -nf inet Active Internet connections Proto Recv-Q Send-Q Local Address Foreign Address (state) tcp 0 0 10.0.0.101.4505 10.0.0.1.45329 ESTABLISHED tcp 0 0 10.0.0.101.4505 10.0.0.100.50798 ESTABLISHED ''' remotes = set() try: data = subprocess.check_output(['netstat', '-nf', 'inet']) # pylint: disable=minimum-python-version except subprocess.CalledProcessError: log.error('Failed netstat') raise lines = data.split('\n') for line in lines: if 'ESTABLISHED' not in line: continue chunks = line.split() local_host, local_port = chunks[3].rsplit('.', 1) remote_host, remote_port = chunks[4].rsplit('.', 1) if which_end == 'remote_port' and int(remote_port) != port: continue if which_end == 'local_port' and int(local_port) != port: continue remotes.add(remote_host) return remotes def _windows_remotes_on(port, which_end): r''' Windows specific helper function. Returns set of ipv4 host addresses of remote established connections on local or remote tcp port. Parses output of shell 'netstat' to get connections C:\>netstat -n Active Connections Proto Local Address Foreign Address State TCP 10.2.33.17:3007 130.164.12.233:10123 ESTABLISHED TCP 10.2.33.17:3389 130.164.30.5:10378 ESTABLISHED ''' remotes = set() try: data = subprocess.check_output(['netstat', '-n']) # pylint: disable=minimum-python-version except subprocess.CalledProcessError: log.error('Failed netstat') raise lines = salt.utils.stringutils.to_str(data).split('\n') for line in lines: if 'ESTABLISHED' not in line: continue chunks = line.split() local_host, local_port = chunks[1].rsplit(':', 1) remote_host, remote_port = chunks[2].rsplit(':', 1) if which_end == 'remote_port' and int(remote_port) != port: continue if which_end == 'local_port' and int(local_port) != port: continue remotes.add(remote_host) return remotes def _linux_remotes_on(port, which_end): ''' Linux specific helper function. Returns set of ip host addresses of remote established connections on local tcp port port. Parses output of shell 'lsof' to get connections $ sudo lsof -iTCP:4505 -n COMMAND PID USER FD TYPE DEVICE SIZE/OFF NODE NAME Python 9971 root 35u IPv4 0x18a8464a29ca329d 0t0 TCP *:4505 (LISTEN) Python 9971 root 37u IPv4 0x18a8464a29b2b29d 0t0 TCP 127.0.0.1:4505->127.0.0.1:55703 (ESTABLISHED) Python 10152 root 22u IPv4 0x18a8464a29c8cab5 0t0 TCP 127.0.0.1:55703->127.0.0.1:4505 (ESTABLISHED) Python 10153 root 22u IPv4 0x18a8464a29c8cab5 0t0 TCP [fe80::249a]:4505->[fe80::150]:59367 (ESTABLISHED) ''' remotes = set() try: data = subprocess.check_output( ['lsof', '-iTCP:{0:d}'.format(port), '-n', '-P'] # pylint: disable=minimum-python-version ) except subprocess.CalledProcessError as ex: if ex.returncode == 1: # Lsof return 1 if any error was detected, including the failure # to locate Internet addresses, and it is not an error in this case. log.warning('"lsof" returncode = 1, likely no active TCP sessions.') return remotes log.error('Failed "lsof" with returncode = %s', ex.returncode) raise lines = salt.utils.stringutils.to_str(data).split('\n') for line in lines: chunks = line.split() if not chunks: continue # ['Python', '9971', 'root', '37u', 'IPv4', '0x18a8464a29b2b29d', '0t0', # 'TCP', '127.0.0.1:4505->127.0.0.1:55703', '(ESTABLISHED)'] # print chunks if 'COMMAND' in chunks[0]: continue # ignore header if 'ESTABLISHED' not in chunks[-1]: continue # ignore if not ESTABLISHED # '127.0.0.1:4505->127.0.0.1:55703' local, remote = chunks[8].split('->') _, lport = local.rsplit(':', 1) rhost, rport = remote.rsplit(':', 1) if which_end == 'remote_port' and int(rport) != port: continue if which_end == 'local_port' and int(lport) != port: continue remotes.add(rhost.strip("[]")) return remotes def _aix_remotes_on(port, which_end): ''' AIX specific helper function. Returns set of ipv4 host addresses of remote established connections on local or remote tcp port. Parses output of shell 'netstat' to get connections root@la68pp002_pub:/opt/salt/lib/python2.7/site-packages/salt/modules# netstat -f inet -n Active Internet connections Proto Recv-Q Send-Q Local Address Foreign Address (state) tcp4 0 0 172.29.149.95.50093 209.41.78.13.4505 ESTABLISHED tcp4 0 0 127.0.0.1.9514 *.* LISTEN tcp4 0 0 127.0.0.1.9515 *.* LISTEN tcp4 0 0 127.0.0.1.199 127.0.0.1.32779 ESTABLISHED tcp4 0 0 127.0.0.1.32779 127.0.0.1.199 ESTABLISHED tcp4 0 40 172.29.149.95.22 172.29.96.83.41022 ESTABLISHED tcp4 0 0 172.29.149.95.22 172.29.96.83.41032 ESTABLISHED tcp4 0 0 127.0.0.1.32771 127.0.0.1.32775 ESTABLISHED tcp 0 0 127.0.0.1.32775 127.0.0.1.32771 ESTABLISHED tcp4 0 0 127.0.0.1.32771 127.0.0.1.32776 ESTABLISHED tcp 0 0 127.0.0.1.32776 127.0.0.1.32771 ESTABLISHED tcp4 0 0 127.0.0.1.32771 127.0.0.1.32777 ESTABLISHED tcp 0 0 127.0.0.1.32777 127.0.0.1.32771 ESTABLISHED tcp4 0 0 127.0.0.1.32771 127.0.0.1.32778 ESTABLISHED tcp 0 0 127.0.0.1.32778 127.0.0.1.32771 ESTABLISHED ''' remotes = set() try: data = subprocess.check_output(['netstat', '-f', 'inet', '-n']) # pylint: disable=minimum-python-version except subprocess.CalledProcessError: log.error('Failed netstat') raise lines = salt.utils.stringutils.to_str(data).split('\n') for line in lines: if 'ESTABLISHED' not in line: continue chunks = line.split() local_host, local_port = chunks[3].rsplit('.', 1) remote_host, remote_port = chunks[4].rsplit('.', 1) if which_end == 'remote_port' and int(remote_port) != port: continue if which_end == 'local_port' and int(local_port) != port: continue remotes.add(remote_host) return remotes @jinja_filter('gen_mac') def gen_mac(prefix='AC:DE:48'): ''' Generates a MAC address with the defined OUI prefix. Common prefixes: - ``00:16:3E`` -- Xen - ``00:18:51`` -- OpenVZ - ``00:50:56`` -- VMware (manually generated) - ``52:54:00`` -- QEMU/KVM - ``AC:DE:48`` -- PRIVATE References: - http://standards.ieee.org/develop/regauth/oui/oui.txt - https://www.wireshark.org/tools/oui-lookup.html - https://en.wikipedia.org/wiki/MAC_address ''' return '{0}:{1:02X}:{2:02X}:{3:02X}'.format(prefix, random.randint(0, 0xff), random.randint(0, 0xff), random.randint(0, 0xff)) @jinja_filter('mac_str_to_bytes') def mac_str_to_bytes(mac_str): ''' Convert a MAC address string into bytes. Works with or without separators: b1 = mac_str_to_bytes('08:00:27:13:69:77') b2 = mac_str_to_bytes('080027136977') assert b1 == b2 assert isinstance(b1, bytes) ''' if len(mac_str) == 12: pass elif len(mac_str) == 17: sep = mac_str[2] mac_str = mac_str.replace(sep, '') else: raise ValueError('Invalid MAC address') chars = (int(mac_str[s:s+2], 16) for s in range(0, 12, 2)) return bytes(chars) if six.PY3 else b''.join(chr(x) for x in chars) def refresh_dns(): ''' issue #21397: force glibc to re-read resolv.conf ''' try: res_init() except NameError: # Exception raised loading the library, thus res_init is not defined pass @jinja_filter('connection_check') def connection_check(addr, port=80, safe=False, ipv6=None): ''' Provides a convenient alias for the dns_check filter. ''' return dns_check(addr, port, safe, ipv6) @jinja_filter('dns_check') def parse_host_port(host_port): """ Takes a string argument specifying host or host:port. Returns a (hostname, port) or (ip_address, port) tuple. If no port is given, the second (port) element of the returned tuple will be None. host:port argument, for example, is accepted in the forms of: - hostname - hostname:1234 - hostname.domain.tld - hostname.domain.tld:5678 - [1234::5]:5678 - 1234::5 - 10.11.12.13:4567 - 10.11.12.13 """ host, port = None, None # default _s_ = host_port[:] if _s_[0] == "[": if "]" in host_port: host, _s_ = _s_.lstrip("[").rsplit("]", 1) host = ipaddress.IPv6Address(host).compressed if _s_[0] == ":": port = int(_s_.lstrip(":")) else: if len(_s_) > 1: raise ValueError('found ambiguous "{}" port in "{}"'.format(_s_, host_port)) else: if _s_.count(":") == 1: host, _hostport_separator_, port = _s_.partition(":") try: port = int(port) except ValueError as _e_: log.error('host_port "%s" port value "%s" is not an integer.', host_port, port) raise _e_ else: host = _s_ try: if not isinstance(host, ipaddress._BaseAddress): host_ip = ipaddress.ip_address(host).compressed host = host_ip except ValueError: log.debug('"%s" Not an IP address? Assuming it is a hostname.', host) if host != sanitize_host(host): log.error('bad hostname: "%s"', host) raise ValueError('bad hostname: "{}"'.format(host)) return host, port def is_fqdn(hostname): """ Verify if hostname conforms to be a FQDN. :param hostname: text string with the name of the host :return: bool, True if hostname is correct FQDN, False otherwise """ compliant = re.compile(r"(?!-)[A-Z\d\-\_]{1,63}(?<!-)$", re.IGNORECASE) return "." in hostname and len(hostname) < 0xff and all(compliant.match(x) for x in hostname.rstrip(".").split("."))
saltstack/salt
salt/utils/network.py
parse_host_port
python
def parse_host_port(host_port): host, port = None, None # default _s_ = host_port[:] if _s_[0] == "[": if "]" in host_port: host, _s_ = _s_.lstrip("[").rsplit("]", 1) host = ipaddress.IPv6Address(host).compressed if _s_[0] == ":": port = int(_s_.lstrip(":")) else: if len(_s_) > 1: raise ValueError('found ambiguous "{}" port in "{}"'.format(_s_, host_port)) else: if _s_.count(":") == 1: host, _hostport_separator_, port = _s_.partition(":") try: port = int(port) except ValueError as _e_: log.error('host_port "%s" port value "%s" is not an integer.', host_port, port) raise _e_ else: host = _s_ try: if not isinstance(host, ipaddress._BaseAddress): host_ip = ipaddress.ip_address(host).compressed host = host_ip except ValueError: log.debug('"%s" Not an IP address? Assuming it is a hostname.', host) if host != sanitize_host(host): log.error('bad hostname: "%s"', host) raise ValueError('bad hostname: "{}"'.format(host)) return host, port
Takes a string argument specifying host or host:port. Returns a (hostname, port) or (ip_address, port) tuple. If no port is given, the second (port) element of the returned tuple will be None. host:port argument, for example, is accepted in the forms of: - hostname - hostname:1234 - hostname.domain.tld - hostname.domain.tld:5678 - [1234::5]:5678 - 1234::5 - 10.11.12.13:4567 - 10.11.12.13
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/network.py#L2005-L2054
[ "def sanitize_host(host):\n '''\n Sanitize host string.\n https://tools.ietf.org/html/rfc1123#section-2.1\n '''\n RFC952_characters = ascii_letters + digits + \".-\"\n return \"\".join([c for c in host[0:255] if c in RFC952_characters])\n" ]
# -*- coding: utf-8 -*- ''' Define some generic socket functions for network modules ''' # Import python libs from __future__ import absolute_import, unicode_literals, print_function import itertools import os import re import types import socket import logging import platform import random import subprocess from string import ascii_letters, digits # Import 3rd-party libs from salt.ext import six from salt.ext.six.moves import range # pylint: disable=import-error,redefined-builtin # Attempt to import wmi try: import wmi import salt.utils.winapi except ImportError: pass # Import salt libs import salt.utils.args import salt.utils.files import salt.utils.path import salt.utils.platform import salt.utils.stringutils import salt.utils.zeromq from salt._compat import ipaddress from salt.exceptions import SaltClientError, SaltSystemExit from salt.utils.decorators.jinja import jinja_filter from salt.utils.versions import LooseVersion # inet_pton does not exist in Windows, this is a workaround if salt.utils.platform.is_windows(): from salt.ext import win_inet_pton # pylint: disable=unused-import log = logging.getLogger(__name__) try: import ctypes import ctypes.util libc = ctypes.cdll.LoadLibrary(ctypes.util.find_library("c")) res_init = libc.__res_init except (ImportError, OSError, AttributeError, TypeError): pass # pylint: disable=C0103 def sanitize_host(host): ''' Sanitize host string. https://tools.ietf.org/html/rfc1123#section-2.1 ''' RFC952_characters = ascii_letters + digits + ".-" return "".join([c for c in host[0:255] if c in RFC952_characters]) def isportopen(host, port): ''' Return status of a port ''' if not 1 <= int(port) <= 65535: return False sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) out = sock.connect_ex((sanitize_host(host), int(port))) return out def host_to_ips(host): ''' Returns a list of IP addresses of a given hostname or None if not found. ''' ips = [] try: for family, socktype, proto, canonname, sockaddr in socket.getaddrinfo( host, 0, socket.AF_UNSPEC, socket.SOCK_STREAM): if family == socket.AF_INET: ip, port = sockaddr elif family == socket.AF_INET6: ip, port, flow_info, scope_id = sockaddr ips.append(ip) if not ips: ips = None except Exception: ips = None return ips def _generate_minion_id(): ''' Get list of possible host names and convention names. :return: ''' # There are three types of hostnames: # 1. Network names. How host is accessed from the network. # 2. Host aliases. They might be not available in all the network or only locally (/etc/hosts) # 3. Convention names, an internal nodename. class DistinctList(list): ''' List, which allows one to append only distinct objects. Needs to work on Python 2.6, because of collections.OrderedDict only since 2.7 version. Override 'filter()' for custom filtering. ''' localhost_matchers = [r'localhost.*', r'ip6-.*', r'127[.]\d', r'0\.0\.0\.0', r'::1.*', r'ipv6-.*', r'fe00::.*', r'fe02::.*', r'1.0.0.*.ip6.arpa'] def append(self, p_object): if p_object and p_object not in self and not self.filter(p_object): super(DistinctList, self).append(p_object) return self def extend(self, iterable): for obj in iterable: self.append(obj) return self def filter(self, element): 'Returns True if element needs to be filtered' for rgx in self.localhost_matchers: if re.match(rgx, element): return True def first(self): return self and self[0] or None hostname = socket.gethostname() hosts = DistinctList().append( salt.utils.stringutils.to_unicode(socket.getfqdn(salt.utils.stringutils.to_bytes(hostname))) ).append(platform.node()).append(hostname) if not hosts: try: for a_nfo in socket.getaddrinfo(hosts.first() or 'localhost', None, socket.AF_INET, socket.SOCK_RAW, socket.IPPROTO_IP, socket.AI_CANONNAME): if len(a_nfo) > 3: hosts.append(a_nfo[3]) except socket.gaierror: log.warning('Cannot resolve address %s info via socket: %s', hosts.first() or 'localhost (N/A)', socket.gaierror) # Universal method for everywhere (Linux, Slowlaris, Windows etc) for f_name in ('/etc/hostname', '/etc/nodename', '/etc/hosts', r'{win}\system32\drivers\etc\hosts'.format(win=os.getenv('WINDIR'))): try: with salt.utils.files.fopen(f_name) as f_hdl: for line in f_hdl: line = salt.utils.stringutils.to_unicode(line) hst = line.strip().split('#')[0].strip().split() if hst: if hst[0][:4] in ('127.', '::1') or len(hst) == 1: hosts.extend(hst) except IOError: pass # include public and private ipaddresses return hosts.extend([addr for addr in ip_addrs() if not ipaddress.ip_address(addr).is_loopback]) def generate_minion_id(): ''' Return only first element of the hostname from all possible list. :return: ''' try: ret = salt.utils.stringutils.to_unicode(_generate_minion_id().first()) except TypeError: ret = None return ret or 'localhost' def get_socket(addr, type=socket.SOCK_STREAM, proto=0): ''' Return a socket object for the addr IP-version agnostic ''' version = ipaddress.ip_address(addr).version if version == 4: family = socket.AF_INET elif version == 6: family = socket.AF_INET6 return socket.socket(family, type, proto) def get_fqhostname(): ''' Returns the fully qualified hostname ''' # try getaddrinfo() fqdn = None try: addrinfo = socket.getaddrinfo( socket.gethostname(), 0, socket.AF_UNSPEC, socket.SOCK_STREAM, socket.SOL_TCP, socket.AI_CANONNAME ) for info in addrinfo: # info struct [family, socktype, proto, canonname, sockaddr] # On Windows `canonname` can be an empty string # This can cause the function to return `None` if len(info) > 3 and info[3]: fqdn = info[3] break except socket.gaierror: pass # NOTE: this used to log.error() but it was later disabled except socket.error as err: log.debug('socket.getaddrinfo() failure while finding fqdn: %s', err) if fqdn is None: fqdn = socket.getfqdn() return fqdn def ip_to_host(ip): ''' Returns the hostname of a given IP ''' try: hostname, aliaslist, ipaddrlist = socket.gethostbyaddr(ip) except Exception as exc: log.debug('salt.utils.network.ip_to_host(%r) failed: %s', ip, exc) hostname = None return hostname # pylint: enable=C0103 def is_reachable_host(entity_name): ''' Returns a bool telling if the entity name is a reachable host (IPv4/IPv6/FQDN/etc). :param hostname: :return: ''' try: assert type(socket.getaddrinfo(entity_name, 0, 0, 0, 0)) == list ret = True except socket.gaierror: ret = False return ret def is_ip(ip): ''' Returns a bool telling if the passed IP is a valid IPv4 or IPv6 address. ''' return is_ipv4(ip) or is_ipv6(ip) def is_ipv4(ip): ''' Returns a bool telling if the value passed to it was a valid IPv4 address ''' try: return ipaddress.ip_address(ip).version == 4 except ValueError: return False def is_ipv6(ip): ''' Returns a bool telling if the value passed to it was a valid IPv6 address ''' try: return ipaddress.ip_address(ip).version == 6 except ValueError: return False def is_subnet(cidr): ''' Returns a bool telling if the passed string is an IPv4 or IPv6 subnet ''' return is_ipv4_subnet(cidr) or is_ipv6_subnet(cidr) def is_ipv4_subnet(cidr): ''' Returns a bool telling if the passed string is an IPv4 subnet ''' try: return '/' in cidr and bool(ipaddress.IPv4Network(cidr)) except Exception: return False def is_ipv6_subnet(cidr): ''' Returns a bool telling if the passed string is an IPv6 subnet ''' try: return '/' in cidr and bool(ipaddress.IPv6Network(cidr)) except Exception: return False @jinja_filter('is_ip') def is_ip_filter(ip, options=None): ''' Returns a bool telling if the passed IP is a valid IPv4 or IPv6 address. ''' return is_ipv4_filter(ip, options=options) or is_ipv6_filter(ip, options=options) def _ip_options_global(ip_obj, version): return not ip_obj.is_private def _ip_options_multicast(ip_obj, version): return ip_obj.is_multicast def _ip_options_loopback(ip_obj, version): return ip_obj.is_loopback def _ip_options_link_local(ip_obj, version): return ip_obj.is_link_local def _ip_options_private(ip_obj, version): return ip_obj.is_private def _ip_options_reserved(ip_obj, version): return ip_obj.is_reserved def _ip_options_site_local(ip_obj, version): if version == 6: return ip_obj.is_site_local return False def _ip_options_unspecified(ip_obj, version): return ip_obj.is_unspecified def _ip_options(ip_obj, version, options=None): # will process and IP options options_fun_map = { 'global': _ip_options_global, 'link-local': _ip_options_link_local, 'linklocal': _ip_options_link_local, 'll': _ip_options_link_local, 'link_local': _ip_options_link_local, 'loopback': _ip_options_loopback, 'lo': _ip_options_loopback, 'multicast': _ip_options_multicast, 'private': _ip_options_private, 'public': _ip_options_global, 'reserved': _ip_options_reserved, 'site-local': _ip_options_site_local, 'sl': _ip_options_site_local, 'site_local': _ip_options_site_local, 'unspecified': _ip_options_unspecified } if not options: return six.text_type(ip_obj) # IP version already checked options_list = [option.strip() for option in options.split(',')] for option, fun in options_fun_map.items(): if option in options_list: fun_res = fun(ip_obj, version) if not fun_res: return None # stop at first failed test # else continue return six.text_type(ip_obj) def _is_ipv(ip, version, options=None): if not version: version = 4 if version not in (4, 6): return None try: ip_obj = ipaddress.ip_address(ip) except ValueError: # maybe it is an IP network try: ip_obj = ipaddress.ip_interface(ip) except ValueError: # nope, still not :( return None if not ip_obj.version == version: return None # has the right version, let's move on return _ip_options(ip_obj, version, options=options) @jinja_filter('is_ipv4') def is_ipv4_filter(ip, options=None): ''' Returns a bool telling if the value passed to it was a valid IPv4 address. ip The IP address. net: False Consider IP addresses followed by netmask. options CSV of options regarding the nature of the IP address. E.g.: loopback, multicast, private etc. ''' _is_ipv4 = _is_ipv(ip, 4, options=options) return isinstance(_is_ipv4, six.string_types) @jinja_filter('is_ipv6') def is_ipv6_filter(ip, options=None): ''' Returns a bool telling if the value passed to it was a valid IPv6 address. ip The IP address. net: False Consider IP addresses followed by netmask. options CSV of options regarding the nature of the IP address. E.g.: loopback, multicast, private etc. ''' _is_ipv6 = _is_ipv(ip, 6, options=options) return isinstance(_is_ipv6, six.string_types) def _ipv_filter(value, version, options=None): if version not in (4, 6): return if isinstance(value, (six.string_types, six.text_type, six.binary_type)): return _is_ipv(value, version, options=options) # calls is_ipv4 or is_ipv6 for `value` elif isinstance(value, (list, tuple, types.GeneratorType)): # calls is_ipv4 or is_ipv6 for each element in the list # os it filters and returns only those elements having the desired IP version return [ _is_ipv(addr, version, options=options) for addr in value if _is_ipv(addr, version, options=options) is not None ] return None @jinja_filter('ipv4') def ipv4(value, options=None): ''' Filters a list and returns IPv4 values only. ''' return _ipv_filter(value, 4, options=options) @jinja_filter('ipv6') def ipv6(value, options=None): ''' Filters a list and returns IPv6 values only. ''' return _ipv_filter(value, 6, options=options) @jinja_filter('ipaddr') def ipaddr(value, options=None): ''' Filters and returns only valid IP objects. ''' ipv4_obj = ipv4(value, options=options) ipv6_obj = ipv6(value, options=options) if ipv4_obj is None or ipv6_obj is None: # an IP address can be either IPv4 either IPv6 # therefofe if the value passed as arg is not a list, at least one of the calls above will return None # if one of them is none, means that we should return only one of them return ipv4_obj or ipv6_obj # one of them else: return ipv4_obj + ipv6_obj # extend lists def _filter_ipaddr(value, options, version=None): ipaddr_filter_out = None if version: if version == 4: ipaddr_filter_out = ipv4(value, options) elif version == 6: ipaddr_filter_out = ipv6(value, options) else: ipaddr_filter_out = ipaddr(value, options) if not ipaddr_filter_out: return if not isinstance(ipaddr_filter_out, (list, tuple, types.GeneratorType)): ipaddr_filter_out = [ipaddr_filter_out] return ipaddr_filter_out @jinja_filter('ip_host') def ip_host(value, options=None, version=None): ''' Returns the interfaces IP address, e.g.: 192.168.0.1/28. ''' ipaddr_filter_out = _filter_ipaddr(value, options=options, version=version) if not ipaddr_filter_out: return if not isinstance(value, (list, tuple, types.GeneratorType)): return six.text_type(ipaddress.ip_interface(ipaddr_filter_out[0])) return [six.text_type(ipaddress.ip_interface(ip_a)) for ip_a in ipaddr_filter_out] def _network_hosts(ip_addr_entry): return [ six.text_type(host) for host in ipaddress.ip_network(ip_addr_entry, strict=False).hosts() ] @jinja_filter('network_hosts') def network_hosts(value, options=None, version=None): ''' Return the list of hosts within a network. .. note:: When running this command with a large IPv6 network, the command will take a long time to gather all of the hosts. ''' ipaddr_filter_out = _filter_ipaddr(value, options=options, version=version) if not ipaddr_filter_out: return if not isinstance(value, (list, tuple, types.GeneratorType)): return _network_hosts(ipaddr_filter_out[0]) return [ _network_hosts(ip_a) for ip_a in ipaddr_filter_out ] def _network_size(ip_addr_entry): return ipaddress.ip_network(ip_addr_entry, strict=False).num_addresses @jinja_filter('network_size') def network_size(value, options=None, version=None): ''' Get the size of a network. ''' ipaddr_filter_out = _filter_ipaddr(value, options=options, version=version) if not ipaddr_filter_out: return if not isinstance(value, (list, tuple, types.GeneratorType)): return _network_size(ipaddr_filter_out[0]) return [ _network_size(ip_a) for ip_a in ipaddr_filter_out ] def natural_ipv4_netmask(ip, fmt='prefixlen'): ''' Returns the "natural" mask of an IPv4 address ''' bits = _ipv4_to_bits(ip) if bits.startswith('11'): mask = '24' elif bits.startswith('1'): mask = '16' else: mask = '8' if fmt == 'netmask': return cidr_to_ipv4_netmask(mask) else: return '/' + mask def rpad_ipv4_network(ip): ''' Returns an IP network address padded with zeros. Ex: '192.168.3' -> '192.168.3.0' '10.209' -> '10.209.0.0' ''' return '.'.join(itertools.islice(itertools.chain(ip.split('.'), '0000'), 0, 4)) def cidr_to_ipv4_netmask(cidr_bits): ''' Returns an IPv4 netmask ''' try: cidr_bits = int(cidr_bits) if not 1 <= cidr_bits <= 32: return '' except ValueError: return '' netmask = '' for idx in range(4): if idx: netmask += '.' if cidr_bits >= 8: netmask += '255' cidr_bits -= 8 else: netmask += '{0:d}'.format(256 - (2 ** (8 - cidr_bits))) cidr_bits = 0 return netmask def _number_of_set_bits_to_ipv4_netmask(set_bits): # pylint: disable=C0103 ''' Returns an IPv4 netmask from the integer representation of that mask. Ex. 0xffffff00 -> '255.255.255.0' ''' return cidr_to_ipv4_netmask(_number_of_set_bits(set_bits)) # pylint: disable=C0103 def _number_of_set_bits(x): ''' Returns the number of bits that are set in a 32bit int ''' # Taken from http://stackoverflow.com/a/4912729. Many thanks! x -= (x >> 1) & 0x55555555 x = ((x >> 2) & 0x33333333) + (x & 0x33333333) x = ((x >> 4) + x) & 0x0f0f0f0f x += x >> 8 x += x >> 16 return x & 0x0000003f # pylint: enable=C0103 def _interfaces_ip(out): ''' Uses ip to return a dictionary of interfaces with various information about each (up/down state, ip address, netmask, and hwaddr) ''' ret = dict() def parse_network(value, cols): ''' Return a tuple of ip, netmask, broadcast based on the current set of cols ''' brd = None scope = None if '/' in value: # we have a CIDR in this address ip, cidr = value.split('/') # pylint: disable=C0103 else: ip = value # pylint: disable=C0103 cidr = 32 if type_ == 'inet': mask = cidr_to_ipv4_netmask(int(cidr)) if 'brd' in cols: brd = cols[cols.index('brd') + 1] elif type_ == 'inet6': mask = cidr if 'scope' in cols: scope = cols[cols.index('scope') + 1] return (ip, mask, brd, scope) groups = re.compile('\r?\n\\d').split(out) for group in groups: iface = None data = dict() for line in group.splitlines(): if ' ' not in line: continue match = re.match(r'^\d*:\s+([\w.\-]+)(?:@)?([\w.\-]+)?:\s+<(.+)>', line) if match: iface, parent, attrs = match.groups() if 'UP' in attrs.split(','): data['up'] = True else: data['up'] = False if parent: data['parent'] = parent continue cols = line.split() if len(cols) >= 2: type_, value = tuple(cols[0:2]) iflabel = cols[-1:][0] if type_ in ('inet', 'inet6'): if 'secondary' not in cols: ipaddr, netmask, broadcast, scope = parse_network(value, cols) if type_ == 'inet': if 'inet' not in data: data['inet'] = list() addr_obj = dict() addr_obj['address'] = ipaddr addr_obj['netmask'] = netmask addr_obj['broadcast'] = broadcast addr_obj['label'] = iflabel data['inet'].append(addr_obj) elif type_ == 'inet6': if 'inet6' not in data: data['inet6'] = list() addr_obj = dict() addr_obj['address'] = ipaddr addr_obj['prefixlen'] = netmask addr_obj['scope'] = scope data['inet6'].append(addr_obj) else: if 'secondary' not in data: data['secondary'] = list() ip_, mask, brd, scp = parse_network(value, cols) data['secondary'].append({ 'type': type_, 'address': ip_, 'netmask': mask, 'broadcast': brd, 'label': iflabel, }) del ip_, mask, brd, scp elif type_.startswith('link'): data['hwaddr'] = value if iface: ret[iface] = data del iface, data return ret def _interfaces_ifconfig(out): ''' Uses ifconfig to return a dictionary of interfaces with various information about each (up/down state, ip address, netmask, and hwaddr) ''' ret = dict() piface = re.compile(r'^([^\s:]+)') pmac = re.compile('.*?(?:HWaddr|ether|address:|lladdr) ([0-9a-fA-F:]+)') if salt.utils.platform.is_sunos(): pip = re.compile(r'.*?(?:inet\s+)([0-9]+\.[0-9]+\.[0-9]+\.[0-9]+)(.*)') pip6 = re.compile('.*?(?:inet6 )([0-9a-fA-F:]+)') pmask6 = re.compile(r'.*?(?:inet6 [0-9a-fA-F:]+/(\d+)).*') else: pip = re.compile(r'.*?(?:inet addr:|inet [^\d]*)(.*?)\s') pip6 = re.compile('.*?(?:inet6 addr: (.*?)/|inet6 )([0-9a-fA-F:]+)') pmask6 = re.compile(r'.*?(?:inet6 addr: [0-9a-fA-F:]+/(\d+)|prefixlen (\d+))(?: Scope:([a-zA-Z]+)| scopeid (0x[0-9a-fA-F]))?') pmask = re.compile(r'.*?(?:Mask:|netmask )(?:((?:0x)?[0-9a-fA-F]{8})|([\d\.]+))') pupdown = re.compile('UP') pbcast = re.compile(r'.*?(?:Bcast:|broadcast )([\d\.]+)') groups = re.compile('\r?\n(?=\\S)').split(out) for group in groups: data = dict() iface = '' updown = False for line in group.splitlines(): miface = piface.match(line) mmac = pmac.match(line) mip = pip.match(line) mip6 = pip6.match(line) mupdown = pupdown.search(line) if miface: iface = miface.group(1) if mmac: data['hwaddr'] = mmac.group(1) if salt.utils.platform.is_sunos(): expand_mac = [] for chunk in data['hwaddr'].split(':'): expand_mac.append('0{0}'.format(chunk) if len(chunk) < 2 else '{0}'.format(chunk)) data['hwaddr'] = ':'.join(expand_mac) if mip: if 'inet' not in data: data['inet'] = list() addr_obj = dict() addr_obj['address'] = mip.group(1) mmask = pmask.match(line) if mmask: if mmask.group(1): mmask = _number_of_set_bits_to_ipv4_netmask( int(mmask.group(1), 16)) else: mmask = mmask.group(2) addr_obj['netmask'] = mmask mbcast = pbcast.match(line) if mbcast: addr_obj['broadcast'] = mbcast.group(1) data['inet'].append(addr_obj) if mupdown: updown = True if mip6: if 'inet6' not in data: data['inet6'] = list() addr_obj = dict() addr_obj['address'] = mip6.group(1) or mip6.group(2) mmask6 = pmask6.match(line) if mmask6: addr_obj['prefixlen'] = mmask6.group(1) or mmask6.group(2) if not salt.utils.platform.is_sunos(): ipv6scope = mmask6.group(3) or mmask6.group(4) addr_obj['scope'] = ipv6scope.lower() if ipv6scope is not None else ipv6scope # SunOS sometimes has ::/0 as inet6 addr when using addrconf if not salt.utils.platform.is_sunos() \ or addr_obj['address'] != '::' \ and addr_obj['prefixlen'] != 0: data['inet6'].append(addr_obj) data['up'] = updown if iface in ret: # SunOS optimization, where interfaces occur twice in 'ifconfig -a' # output with the same name: for ipv4 and then for ipv6 addr family. # Every instance has it's own 'UP' status and we assume that ipv4 # status determines global interface status. # # merge items with higher priority for older values # after that merge the inet and inet6 sub items for both ret[iface] = dict(list(data.items()) + list(ret[iface].items())) if 'inet' in data: ret[iface]['inet'].extend(x for x in data['inet'] if x not in ret[iface]['inet']) if 'inet6' in data: ret[iface]['inet6'].extend(x for x in data['inet6'] if x not in ret[iface]['inet6']) else: ret[iface] = data del data return ret def linux_interfaces(): ''' Obtain interface information for *NIX/BSD variants ''' ifaces = dict() ip_path = salt.utils.path.which('ip') ifconfig_path = None if ip_path else salt.utils.path.which('ifconfig') if ip_path: cmd1 = subprocess.Popen( '{0} link show'.format(ip_path), shell=True, close_fds=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT).communicate()[0] cmd2 = subprocess.Popen( '{0} addr show'.format(ip_path), shell=True, close_fds=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT).communicate()[0] ifaces = _interfaces_ip("{0}\n{1}".format( salt.utils.stringutils.to_str(cmd1), salt.utils.stringutils.to_str(cmd2))) elif ifconfig_path: cmd = subprocess.Popen( '{0} -a'.format(ifconfig_path), shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT).communicate()[0] ifaces = _interfaces_ifconfig(salt.utils.stringutils.to_str(cmd)) return ifaces def _netbsd_interfaces_ifconfig(out): ''' Uses ifconfig to return a dictionary of interfaces with various information about each (up/down state, ip address, netmask, and hwaddr) ''' ret = dict() piface = re.compile(r'^([^\s:]+)') pmac = re.compile('.*?address: ([0-9a-f:]+)') pip = re.compile(r'.*?inet [^\d]*(.*?)/([\d]*)\s') pip6 = re.compile(r'.*?inet6 ([0-9a-f:]+)%([a-zA-Z0-9]*)/([\d]*)\s') pupdown = re.compile('UP') pbcast = re.compile(r'.*?broadcast ([\d\.]+)') groups = re.compile('\r?\n(?=\\S)').split(out) for group in groups: data = dict() iface = '' updown = False for line in group.splitlines(): miface = piface.match(line) mmac = pmac.match(line) mip = pip.match(line) mip6 = pip6.match(line) mupdown = pupdown.search(line) if miface: iface = miface.group(1) if mmac: data['hwaddr'] = mmac.group(1) if mip: if 'inet' not in data: data['inet'] = list() addr_obj = dict() addr_obj['address'] = mip.group(1) mmask = mip.group(2) if mip.group(2): addr_obj['netmask'] = cidr_to_ipv4_netmask(mip.group(2)) mbcast = pbcast.match(line) if mbcast: addr_obj['broadcast'] = mbcast.group(1) data['inet'].append(addr_obj) if mupdown: updown = True if mip6: if 'inet6' not in data: data['inet6'] = list() addr_obj = dict() addr_obj['address'] = mip6.group(1) mmask6 = mip6.group(3) addr_obj['scope'] = mip6.group(2) addr_obj['prefixlen'] = mip6.group(3) data['inet6'].append(addr_obj) data['up'] = updown ret[iface] = data del data return ret def netbsd_interfaces(): ''' Obtain interface information for NetBSD >= 8 where the ifconfig output diverged from other BSD variants (Netmask is now part of the address) ''' # NetBSD versions prior to 8.0 can still use linux_interfaces() if LooseVersion(os.uname()[2]) < LooseVersion('8.0'): return linux_interfaces() ifconfig_path = salt.utils.path.which('ifconfig') cmd = subprocess.Popen( '{0} -a'.format(ifconfig_path), shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT).communicate()[0] return _netbsd_interfaces_ifconfig(salt.utils.stringutils.to_str(cmd)) def _interfaces_ipconfig(out): ''' Returns a dictionary of interfaces with various information about each (up/down state, ip address, netmask, and hwaddr) NOTE: This is not used by any function and may be able to be removed in the future. ''' ifaces = dict() iface = None adapter_iface_regex = re.compile(r'adapter (\S.+):$') for line in out.splitlines(): if not line: continue # TODO what does Windows call Infiniband and 10/40gige adapters if line.startswith('Ethernet'): iface = ifaces[adapter_iface_regex.search(line).group(1)] iface['up'] = True addr = None continue if iface: key, val = line.split(',', 1) key = key.strip(' .') val = val.strip() if addr and key == 'Subnet Mask': addr['netmask'] = val elif key in ('IP Address', 'IPv4 Address'): if 'inet' not in iface: iface['inet'] = list() addr = {'address': val.rstrip('(Preferred)'), 'netmask': None, 'broadcast': None} # TODO find the broadcast iface['inet'].append(addr) elif 'IPv6 Address' in key: if 'inet6' not in iface: iface['inet'] = list() # XXX What is the prefixlen!? addr = {'address': val.rstrip('(Preferred)'), 'prefixlen': None} iface['inet6'].append(addr) elif key == 'Physical Address': iface['hwaddr'] = val elif key == 'Media State': # XXX seen used for tunnel adaptors # might be useful iface['up'] = (val != 'Media disconnected') def win_interfaces(): ''' Obtain interface information for Windows systems ''' with salt.utils.winapi.Com(): c = wmi.WMI() ifaces = {} for iface in c.Win32_NetworkAdapterConfiguration(IPEnabled=1): ifaces[iface.Description] = dict() if iface.MACAddress: ifaces[iface.Description]['hwaddr'] = iface.MACAddress if iface.IPEnabled: ifaces[iface.Description]['up'] = True for ip in iface.IPAddress: if '.' in ip: if 'inet' not in ifaces[iface.Description]: ifaces[iface.Description]['inet'] = [] item = {'address': ip, 'label': iface.Description} if iface.DefaultIPGateway: broadcast = next((i for i in iface.DefaultIPGateway if '.' in i), '') if broadcast: item['broadcast'] = broadcast if iface.IPSubnet: netmask = next((i for i in iface.IPSubnet if '.' in i), '') if netmask: item['netmask'] = netmask ifaces[iface.Description]['inet'].append(item) if ':' in ip: if 'inet6' not in ifaces[iface.Description]: ifaces[iface.Description]['inet6'] = [] item = {'address': ip} if iface.DefaultIPGateway: broadcast = next((i for i in iface.DefaultIPGateway if ':' in i), '') if broadcast: item['broadcast'] = broadcast if iface.IPSubnet: netmask = next((i for i in iface.IPSubnet if ':' in i), '') if netmask: item['netmask'] = netmask ifaces[iface.Description]['inet6'].append(item) else: ifaces[iface.Description]['up'] = False return ifaces def interfaces(): ''' Return a dictionary of information about all the interfaces on the minion ''' if salt.utils.platform.is_windows(): return win_interfaces() elif salt.utils.platform.is_netbsd(): return netbsd_interfaces() else: return linux_interfaces() def get_net_start(ipaddr, netmask): ''' Return the address of the network ''' net = ipaddress.ip_network('{0}/{1}'.format(ipaddr, netmask), strict=False) return six.text_type(net.network_address) def get_net_size(mask): ''' Turns an IPv4 netmask into it's corresponding prefix length (255.255.255.0 -> 24 as in 192.168.1.10/24). ''' binary_str = '' for octet in mask.split('.'): binary_str += bin(int(octet))[2:].zfill(8) return len(binary_str.rstrip('0')) def calc_net(ipaddr, netmask=None): ''' Takes IP (CIDR notation supported) and optionally netmask and returns the network in CIDR-notation. (The IP can be any IP inside the subnet) ''' if netmask is not None: ipaddr = '{0}/{1}'.format(ipaddr, netmask) return six.text_type(ipaddress.ip_network(ipaddr, strict=False)) def _ipv4_to_bits(ipaddr): ''' Accepts an IPv4 dotted quad and returns a string representing its binary counterpart ''' return ''.join([bin(int(x))[2:].rjust(8, '0') for x in ipaddr.split('.')]) def _get_iface_info(iface): ''' If `iface` is available, return interface info and no error, otherwise return no info and log and return an error ''' iface_info = interfaces() if iface in iface_info.keys(): return iface_info, False else: error_msg = ('Interface "{0}" not in available interfaces: "{1}"' ''.format(iface, '", "'.join(iface_info.keys()))) log.error(error_msg) return None, error_msg def _hw_addr_aix(iface): ''' Return the hardware address (a.k.a. MAC address) for a given interface on AIX MAC address not available in through interfaces ''' cmd = subprocess.Popen( 'entstat -d {0} | grep \'Hardware Address\''.format(iface), shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT).communicate()[0] if cmd: comps = cmd.split(' ') if len(comps) == 3: mac_addr = comps[2].strip('\'').strip() return mac_addr error_msg = ('Interface "{0}" either not available or does not contain a hardware address'.format(iface)) log.error(error_msg) return error_msg def hw_addr(iface): ''' Return the hardware address (a.k.a. MAC address) for a given interface .. versionchanged:: 2016.11.4 Added support for AIX ''' if salt.utils.platform.is_aix(): return _hw_addr_aix iface_info, error = _get_iface_info(iface) if error is False: return iface_info.get(iface, {}).get('hwaddr', '') else: return error def interface(iface): ''' Return the details of `iface` or an error if it does not exist ''' iface_info, error = _get_iface_info(iface) if error is False: return iface_info.get(iface, {}).get('inet', '') else: return error def interface_ip(iface): ''' Return `iface` IPv4 addr or an error if `iface` does not exist ''' iface_info, error = _get_iface_info(iface) if error is False: inet = iface_info.get(iface, {}).get('inet', None) return inet[0].get('address', '') if inet else '' else: return error def _subnets(proto='inet', interfaces_=None): ''' Returns a list of subnets to which the host belongs ''' if interfaces_ is None: ifaces = interfaces() elif isinstance(interfaces_, list): ifaces = {} for key, value in six.iteritems(interfaces()): if key in interfaces_: ifaces[key] = value else: ifaces = {interfaces_: interfaces().get(interfaces_, {})} ret = set() if proto == 'inet': subnet = 'netmask' dflt_cidr = 32 elif proto == 'inet6': subnet = 'prefixlen' dflt_cidr = 128 else: log.error('Invalid proto %s calling subnets()', proto) return for ip_info in six.itervalues(ifaces): addrs = ip_info.get(proto, []) addrs.extend([addr for addr in ip_info.get('secondary', []) if addr.get('type') == proto]) for intf in addrs: if subnet in intf: intf = ipaddress.ip_interface('{0}/{1}'.format(intf['address'], intf[subnet])) else: intf = ipaddress.ip_interface('{0}/{1}'.format(intf['address'], dflt_cidr)) if not intf.is_loopback: ret.add(intf.network) return [six.text_type(net) for net in sorted(ret)] def subnets(interfaces=None): ''' Returns a list of IPv4 subnets to which the host belongs ''' return _subnets('inet', interfaces_=interfaces) def subnets6(): ''' Returns a list of IPv6 subnets to which the host belongs ''' return _subnets('inet6') def in_subnet(cidr, addr=None): ''' Returns True if host or (any of) addrs is within specified subnet, otherwise False ''' try: cidr = ipaddress.ip_network(cidr) except ValueError: log.error('Invalid CIDR \'%s\'', cidr) return False if addr is None: addr = ip_addrs() addr.extend(ip_addrs6()) elif not isinstance(addr, (list, tuple)): addr = (addr,) return any(ipaddress.ip_address(item) in cidr for item in addr) def _ip_addrs(interface=None, include_loopback=False, interface_data=None, proto='inet'): ''' Return the full list of IP adresses matching the criteria proto = inet|inet6 ''' ret = set() ifaces = interface_data \ if isinstance(interface_data, dict) \ else interfaces() if interface is None: target_ifaces = ifaces else: target_ifaces = dict([(k, v) for k, v in six.iteritems(ifaces) if k == interface]) if not target_ifaces: log.error('Interface %s not found.', interface) for ip_info in six.itervalues(target_ifaces): addrs = ip_info.get(proto, []) addrs.extend([addr for addr in ip_info.get('secondary', []) if addr.get('type') == proto]) for addr in addrs: addr = ipaddress.ip_address(addr.get('address')) if not addr.is_loopback or include_loopback: ret.add(addr) return [six.text_type(addr) for addr in sorted(ret)] def ip_addrs(interface=None, include_loopback=False, interface_data=None): ''' Returns a list of IPv4 addresses assigned to the host. 127.0.0.1 is ignored, unless 'include_loopback=True' is indicated. If 'interface' is provided, then only IP addresses from that interface will be returned. ''' return _ip_addrs(interface, include_loopback, interface_data, 'inet') def ip_addrs6(interface=None, include_loopback=False, interface_data=None): ''' Returns a list of IPv6 addresses assigned to the host. ::1 is ignored, unless 'include_loopback=True' is indicated. If 'interface' is provided, then only IP addresses from that interface will be returned. ''' return _ip_addrs(interface, include_loopback, interface_data, 'inet6') def hex2ip(hex_ip, invert=False): ''' Convert a hex string to an ip, if a failure occurs the original hex is returned. If 'invert=True' assume that ip from /proc/net/<proto> ''' if len(hex_ip) == 32: # ipv6 ip = [] for i in range(0, 32, 8): ip_part = hex_ip[i:i + 8] ip_part = [ip_part[x:x + 2] for x in range(0, 8, 2)] if invert: ip.append("{0[3]}{0[2]}:{0[1]}{0[0]}".format(ip_part)) else: ip.append("{0[0]}{0[1]}:{0[2]}{0[3]}".format(ip_part)) try: address = ipaddress.IPv6Address(":".join(ip)) if address.ipv4_mapped: return str(address.ipv4_mapped) else: return address.compressed except ipaddress.AddressValueError as ex: log.error('hex2ip - ipv6 address error: %s', ex) return hex_ip try: hip = int(hex_ip, 16) except ValueError: return hex_ip if invert: return '{3}.{2}.{1}.{0}'.format(hip >> 24 & 255, hip >> 16 & 255, hip >> 8 & 255, hip & 255) return '{0}.{1}.{2}.{3}'.format(hip >> 24 & 255, hip >> 16 & 255, hip >> 8 & 255, hip & 255) def mac2eui64(mac, prefix=None): ''' Convert a MAC address to a EUI64 identifier or, with prefix provided, a full IPv6 address ''' # http://tools.ietf.org/html/rfc4291#section-2.5.1 eui64 = re.sub(r'[.:-]', '', mac).lower() eui64 = eui64[0:6] + 'fffe' + eui64[6:] eui64 = hex(int(eui64[0:2], 16) | 2)[2:].zfill(2) + eui64[2:] if prefix is None: return ':'.join(re.findall(r'.{4}', eui64)) else: try: net = ipaddress.ip_network(prefix, strict=False) euil = int('0x{0}'.format(eui64), 16) return '{0}/{1}'.format(net[euil], net.prefixlen) except Exception: return def active_tcp(): ''' Return a dict describing all active tcp connections as quickly as possible ''' ret = {} for statf in ['/proc/net/tcp', '/proc/net/tcp6']: if os.path.isfile(statf): with salt.utils.files.fopen(statf, 'rb') as fp_: for line in fp_: line = salt.utils.stringutils.to_unicode(line) if line.strip().startswith('sl'): continue iret = _parse_tcp_line(line) sl = next(iter(iret)) if iret[sl]['state'] == 1: # 1 is ESTABLISHED del iret[sl]['state'] ret[len(ret)] = iret[sl] return ret def local_port_tcp(port): ''' Return a set of remote ip addrs attached to the specified local port ''' ret = _remotes_on(port, 'local_port') return ret def remote_port_tcp(port): ''' Return a set of ip addrs the current host is connected to on given port ''' ret = _remotes_on(port, 'remote_port') return ret def _remotes_on(port, which_end): ''' Return a set of ip addrs active tcp connections ''' port = int(port) ret = _netlink_tool_remote_on(port, which_end) if ret is not None: return ret ret = set() proc_available = False for statf in ['/proc/net/tcp', '/proc/net/tcp6']: if os.path.isfile(statf): proc_available = True with salt.utils.files.fopen(statf, 'r') as fp_: for line in fp_: line = salt.utils.stringutils.to_unicode(line) if line.strip().startswith('sl'): continue iret = _parse_tcp_line(line) sl = next(iter(iret)) if iret[sl][which_end] == port and iret[sl]['state'] == 1: # 1 is ESTABLISHED ret.add(iret[sl]['remote_addr']) if not proc_available: # Fallback to use OS specific tools if salt.utils.platform.is_sunos(): return _sunos_remotes_on(port, which_end) if salt.utils.platform.is_freebsd(): return _freebsd_remotes_on(port, which_end) if salt.utils.platform.is_netbsd(): return _netbsd_remotes_on(port, which_end) if salt.utils.platform.is_openbsd(): return _openbsd_remotes_on(port, which_end) if salt.utils.platform.is_windows(): return _windows_remotes_on(port, which_end) if salt.utils.platform.is_aix(): return _aix_remotes_on(port, which_end) return _linux_remotes_on(port, which_end) return ret def _parse_tcp_line(line): ''' Parse a single line from the contents of /proc/net/tcp or /proc/net/tcp6 ''' ret = {} comps = line.strip().split() sl = comps[0].rstrip(':') ret[sl] = {} l_addr, l_port = comps[1].split(':') r_addr, r_port = comps[2].split(':') ret[sl]['local_addr'] = hex2ip(l_addr, True) ret[sl]['local_port'] = int(l_port, 16) ret[sl]['remote_addr'] = hex2ip(r_addr, True) ret[sl]['remote_port'] = int(r_port, 16) ret[sl]['state'] = int(comps[3], 16) return ret def _netlink_tool_remote_on(port, which_end): ''' Returns set of ipv4 host addresses of remote established connections on local or remote tcp port. Parses output of shell 'ss' to get connections [root@salt-master ~]# ss -ant State Recv-Q Send-Q Local Address:Port Peer Address:Port LISTEN 0 511 *:80 *:* LISTEN 0 128 *:22 *:* ESTAB 0 0 127.0.0.1:56726 127.0.0.1:4505 ''' remotes = set() valid = False try: data = subprocess.check_output(['ss', '-ant']) # pylint: disable=minimum-python-version except subprocess.CalledProcessError: log.error('Failed ss') raise except OSError: # not command "No such file or directory" return None lines = salt.utils.stringutils.to_str(data).split('\n') for line in lines: if 'Address:Port' in line: # ss tools may not be valid valid = True continue elif 'ESTAB' not in line: continue chunks = line.split() local_host, local_port = chunks[3].split(':', 1) remote_host, remote_port = chunks[4].split(':', 1) if which_end == 'remote_port' and int(remote_port) != port: continue if which_end == 'local_port' and int(local_port) != port: continue remotes.add(remote_host) if valid is False: remotes = None return remotes def _sunos_remotes_on(port, which_end): ''' SunOS specific helper function. Returns set of ipv4 host addresses of remote established connections on local or remote tcp port. Parses output of shell 'netstat' to get connections [root@salt-master ~]# netstat -f inet -n TCP: IPv4 Local Address Remote Address Swind Send-Q Rwind Recv-Q State -------------------- -------------------- ----- ------ ----- ------ ----------- 10.0.0.101.4505 10.0.0.1.45329 1064800 0 1055864 0 ESTABLISHED 10.0.0.101.4505 10.0.0.100.50798 1064800 0 1055864 0 ESTABLISHED ''' remotes = set() try: data = subprocess.check_output(['netstat', '-f', 'inet', '-n']) # pylint: disable=minimum-python-version except subprocess.CalledProcessError: log.error('Failed netstat') raise lines = salt.utils.stringutils.to_str(data).split('\n') for line in lines: if 'ESTABLISHED' not in line: continue chunks = line.split() local_host, local_port = chunks[0].rsplit('.', 1) remote_host, remote_port = chunks[1].rsplit('.', 1) if which_end == 'remote_port' and int(remote_port) != port: continue if which_end == 'local_port' and int(local_port) != port: continue remotes.add(remote_host) return remotes def _freebsd_remotes_on(port, which_end): ''' Returns set of ipv4 host addresses of remote established connections on local tcp port port. Parses output of shell 'sockstat' (FreeBSD) to get connections $ sudo sockstat -4 USER COMMAND PID FD PROTO LOCAL ADDRESS FOREIGN ADDRESS root python2.7 1456 29 tcp4 *:4505 *:* root python2.7 1445 17 tcp4 *:4506 *:* root python2.7 1294 14 tcp4 127.0.0.1:11813 127.0.0.1:4505 root python2.7 1294 41 tcp4 127.0.0.1:61115 127.0.0.1:4506 $ sudo sockstat -4 -c -p 4506 USER COMMAND PID FD PROTO LOCAL ADDRESS FOREIGN ADDRESS root python2.7 1294 41 tcp4 127.0.0.1:61115 127.0.0.1:4506 ''' port = int(port) remotes = set() try: cmd = salt.utils.args.shlex_split('sockstat -4 -c -p {0}'.format(port)) data = subprocess.check_output(cmd) # pylint: disable=minimum-python-version except subprocess.CalledProcessError as ex: log.error('Failed "sockstat" with returncode = %s', ex.returncode) raise lines = salt.utils.stringutils.to_str(data).split('\n') for line in lines: chunks = line.split() if not chunks: continue # ['root', 'python2.7', '1456', '37', 'tcp4', # '127.0.0.1:4505-', '127.0.0.1:55703'] # print chunks if 'COMMAND' in chunks[1]: continue # ignore header if len(chunks) < 2: continue # sockstat -4 -c -p 4506 does this with high PIDs: # USER COMMAND PID FD PROTO LOCAL ADDRESS FOREIGN ADDRESS # salt-master python2.781106 35 tcp4 192.168.12.34:4506 192.168.12.45:60143 local = chunks[-2] remote = chunks[-1] lhost, lport = local.split(':') rhost, rport = remote.split(':') if which_end == 'local' and int(lport) != port: # ignore if local port not port continue if which_end == 'remote' and int(rport) != port: # ignore if remote port not port continue remotes.add(rhost) return remotes def _netbsd_remotes_on(port, which_end): ''' Returns set of ipv4 host addresses of remote established connections on local tcp port port. Parses output of shell 'sockstat' (NetBSD) to get connections $ sudo sockstat -4 -n USER COMMAND PID FD PROTO LOCAL ADDRESS FOREIGN ADDRESS root python2.7 1456 29 tcp *.4505 *.* root python2.7 1445 17 tcp *.4506 *.* root python2.7 1294 14 tcp 127.0.0.1.11813 127.0.0.1.4505 root python2.7 1294 41 tcp 127.0.0.1.61115 127.0.0.1.4506 $ sudo sockstat -4 -c -n -p 4506 USER COMMAND PID FD PROTO LOCAL ADDRESS FOREIGN ADDRESS root python2.7 1294 41 tcp 127.0.0.1.61115 127.0.0.1.4506 ''' port = int(port) remotes = set() try: cmd = salt.utils.args.shlex_split('sockstat -4 -c -n -p {0}'.format(port)) data = subprocess.check_output(cmd) # pylint: disable=minimum-python-version except subprocess.CalledProcessError as ex: log.error('Failed "sockstat" with returncode = %s', ex.returncode) raise lines = salt.utils.stringutils.to_str(data).split('\n') for line in lines: chunks = line.split() if not chunks: continue # ['root', 'python2.7', '1456', '37', 'tcp', # '127.0.0.1.4505-', '127.0.0.1.55703'] # print chunks if 'COMMAND' in chunks[1]: continue # ignore header if len(chunks) < 2: continue local = chunks[5].split('.') lport = local.pop() lhost = '.'.join(local) remote = chunks[6].split('.') rport = remote.pop() rhost = '.'.join(remote) if which_end == 'local' and int(lport) != port: # ignore if local port not port continue if which_end == 'remote' and int(rport) != port: # ignore if remote port not port continue remotes.add(rhost) return remotes def _openbsd_remotes_on(port, which_end): ''' OpenBSD specific helper function. Returns set of ipv4 host addresses of remote established connections on local or remote tcp port. Parses output of shell 'netstat' to get connections $ netstat -nf inet Active Internet connections Proto Recv-Q Send-Q Local Address Foreign Address (state) tcp 0 0 10.0.0.101.4505 10.0.0.1.45329 ESTABLISHED tcp 0 0 10.0.0.101.4505 10.0.0.100.50798 ESTABLISHED ''' remotes = set() try: data = subprocess.check_output(['netstat', '-nf', 'inet']) # pylint: disable=minimum-python-version except subprocess.CalledProcessError: log.error('Failed netstat') raise lines = data.split('\n') for line in lines: if 'ESTABLISHED' not in line: continue chunks = line.split() local_host, local_port = chunks[3].rsplit('.', 1) remote_host, remote_port = chunks[4].rsplit('.', 1) if which_end == 'remote_port' and int(remote_port) != port: continue if which_end == 'local_port' and int(local_port) != port: continue remotes.add(remote_host) return remotes def _windows_remotes_on(port, which_end): r''' Windows specific helper function. Returns set of ipv4 host addresses of remote established connections on local or remote tcp port. Parses output of shell 'netstat' to get connections C:\>netstat -n Active Connections Proto Local Address Foreign Address State TCP 10.2.33.17:3007 130.164.12.233:10123 ESTABLISHED TCP 10.2.33.17:3389 130.164.30.5:10378 ESTABLISHED ''' remotes = set() try: data = subprocess.check_output(['netstat', '-n']) # pylint: disable=minimum-python-version except subprocess.CalledProcessError: log.error('Failed netstat') raise lines = salt.utils.stringutils.to_str(data).split('\n') for line in lines: if 'ESTABLISHED' not in line: continue chunks = line.split() local_host, local_port = chunks[1].rsplit(':', 1) remote_host, remote_port = chunks[2].rsplit(':', 1) if which_end == 'remote_port' and int(remote_port) != port: continue if which_end == 'local_port' and int(local_port) != port: continue remotes.add(remote_host) return remotes def _linux_remotes_on(port, which_end): ''' Linux specific helper function. Returns set of ip host addresses of remote established connections on local tcp port port. Parses output of shell 'lsof' to get connections $ sudo lsof -iTCP:4505 -n COMMAND PID USER FD TYPE DEVICE SIZE/OFF NODE NAME Python 9971 root 35u IPv4 0x18a8464a29ca329d 0t0 TCP *:4505 (LISTEN) Python 9971 root 37u IPv4 0x18a8464a29b2b29d 0t0 TCP 127.0.0.1:4505->127.0.0.1:55703 (ESTABLISHED) Python 10152 root 22u IPv4 0x18a8464a29c8cab5 0t0 TCP 127.0.0.1:55703->127.0.0.1:4505 (ESTABLISHED) Python 10153 root 22u IPv4 0x18a8464a29c8cab5 0t0 TCP [fe80::249a]:4505->[fe80::150]:59367 (ESTABLISHED) ''' remotes = set() try: data = subprocess.check_output( ['lsof', '-iTCP:{0:d}'.format(port), '-n', '-P'] # pylint: disable=minimum-python-version ) except subprocess.CalledProcessError as ex: if ex.returncode == 1: # Lsof return 1 if any error was detected, including the failure # to locate Internet addresses, and it is not an error in this case. log.warning('"lsof" returncode = 1, likely no active TCP sessions.') return remotes log.error('Failed "lsof" with returncode = %s', ex.returncode) raise lines = salt.utils.stringutils.to_str(data).split('\n') for line in lines: chunks = line.split() if not chunks: continue # ['Python', '9971', 'root', '37u', 'IPv4', '0x18a8464a29b2b29d', '0t0', # 'TCP', '127.0.0.1:4505->127.0.0.1:55703', '(ESTABLISHED)'] # print chunks if 'COMMAND' in chunks[0]: continue # ignore header if 'ESTABLISHED' not in chunks[-1]: continue # ignore if not ESTABLISHED # '127.0.0.1:4505->127.0.0.1:55703' local, remote = chunks[8].split('->') _, lport = local.rsplit(':', 1) rhost, rport = remote.rsplit(':', 1) if which_end == 'remote_port' and int(rport) != port: continue if which_end == 'local_port' and int(lport) != port: continue remotes.add(rhost.strip("[]")) return remotes def _aix_remotes_on(port, which_end): ''' AIX specific helper function. Returns set of ipv4 host addresses of remote established connections on local or remote tcp port. Parses output of shell 'netstat' to get connections root@la68pp002_pub:/opt/salt/lib/python2.7/site-packages/salt/modules# netstat -f inet -n Active Internet connections Proto Recv-Q Send-Q Local Address Foreign Address (state) tcp4 0 0 172.29.149.95.50093 209.41.78.13.4505 ESTABLISHED tcp4 0 0 127.0.0.1.9514 *.* LISTEN tcp4 0 0 127.0.0.1.9515 *.* LISTEN tcp4 0 0 127.0.0.1.199 127.0.0.1.32779 ESTABLISHED tcp4 0 0 127.0.0.1.32779 127.0.0.1.199 ESTABLISHED tcp4 0 40 172.29.149.95.22 172.29.96.83.41022 ESTABLISHED tcp4 0 0 172.29.149.95.22 172.29.96.83.41032 ESTABLISHED tcp4 0 0 127.0.0.1.32771 127.0.0.1.32775 ESTABLISHED tcp 0 0 127.0.0.1.32775 127.0.0.1.32771 ESTABLISHED tcp4 0 0 127.0.0.1.32771 127.0.0.1.32776 ESTABLISHED tcp 0 0 127.0.0.1.32776 127.0.0.1.32771 ESTABLISHED tcp4 0 0 127.0.0.1.32771 127.0.0.1.32777 ESTABLISHED tcp 0 0 127.0.0.1.32777 127.0.0.1.32771 ESTABLISHED tcp4 0 0 127.0.0.1.32771 127.0.0.1.32778 ESTABLISHED tcp 0 0 127.0.0.1.32778 127.0.0.1.32771 ESTABLISHED ''' remotes = set() try: data = subprocess.check_output(['netstat', '-f', 'inet', '-n']) # pylint: disable=minimum-python-version except subprocess.CalledProcessError: log.error('Failed netstat') raise lines = salt.utils.stringutils.to_str(data).split('\n') for line in lines: if 'ESTABLISHED' not in line: continue chunks = line.split() local_host, local_port = chunks[3].rsplit('.', 1) remote_host, remote_port = chunks[4].rsplit('.', 1) if which_end == 'remote_port' and int(remote_port) != port: continue if which_end == 'local_port' and int(local_port) != port: continue remotes.add(remote_host) return remotes @jinja_filter('gen_mac') def gen_mac(prefix='AC:DE:48'): ''' Generates a MAC address with the defined OUI prefix. Common prefixes: - ``00:16:3E`` -- Xen - ``00:18:51`` -- OpenVZ - ``00:50:56`` -- VMware (manually generated) - ``52:54:00`` -- QEMU/KVM - ``AC:DE:48`` -- PRIVATE References: - http://standards.ieee.org/develop/regauth/oui/oui.txt - https://www.wireshark.org/tools/oui-lookup.html - https://en.wikipedia.org/wiki/MAC_address ''' return '{0}:{1:02X}:{2:02X}:{3:02X}'.format(prefix, random.randint(0, 0xff), random.randint(0, 0xff), random.randint(0, 0xff)) @jinja_filter('mac_str_to_bytes') def mac_str_to_bytes(mac_str): ''' Convert a MAC address string into bytes. Works with or without separators: b1 = mac_str_to_bytes('08:00:27:13:69:77') b2 = mac_str_to_bytes('080027136977') assert b1 == b2 assert isinstance(b1, bytes) ''' if len(mac_str) == 12: pass elif len(mac_str) == 17: sep = mac_str[2] mac_str = mac_str.replace(sep, '') else: raise ValueError('Invalid MAC address') chars = (int(mac_str[s:s+2], 16) for s in range(0, 12, 2)) return bytes(chars) if six.PY3 else b''.join(chr(x) for x in chars) def refresh_dns(): ''' issue #21397: force glibc to re-read resolv.conf ''' try: res_init() except NameError: # Exception raised loading the library, thus res_init is not defined pass @jinja_filter('connection_check') def connection_check(addr, port=80, safe=False, ipv6=None): ''' Provides a convenient alias for the dns_check filter. ''' return dns_check(addr, port, safe, ipv6) @jinja_filter('dns_check') def dns_check(addr, port=80, safe=False, ipv6=None, attempt_connect=True): ''' Return the ip resolved by dns, but do not exit on failure, only raise an exception. Obeys system preference for IPv4/6 address resolution - this can be overridden by the ipv6 flag. Tries to connect to the address before considering it useful. If no address can be reached, the first one resolved is used as a fallback. ''' error = False lookup = addr seen_ipv6 = False family = socket.AF_INET6 if ipv6 else socket.AF_INET if ipv6 is False else socket.AF_UNSPEC hostnames = [] try: refresh_dns() hostnames = socket.getaddrinfo(addr, port, family, socket.SOCK_STREAM) except TypeError: err = ('Attempt to resolve address \'{0}\' failed. Invalid or unresolveable address').format(lookup) raise SaltSystemExit(code=42, msg=err) except socket.error: error = True # If ipv6 is set to True, attempt another lookup using the IPv4 family, # just in case we're attempting to lookup an IPv4 IP # as an IPv6 hostname. if error and ipv6: try: refresh_dns() hostnames = socket.getaddrinfo(addr, port, socket.AF_INET, socket.SOCK_STREAM) except TypeError: err = ('Attempt to resolve address \'{0}\' failed. Invalid or unresolveable address').format(lookup) raise SaltSystemExit(code=42, msg=err) except socket.error: error = True try: if not hostnames: error = True else: resolved = False candidates = [] for h in hostnames: # Input is IP address, passed through unchanged, just return it if h[4][0] == addr: resolved = salt.utils.zeromq.ip_bracket(addr) break candidate_addr = salt.utils.zeromq.ip_bracket(h[4][0]) # sometimes /etc/hosts contains ::1 localhost if not ipv6 and candidate_addr == '[::1]': continue candidates.append(candidate_addr) if attempt_connect: try: s = socket.socket(h[0], socket.SOCK_STREAM) s.settimeout(2) s.connect((candidate_addr.strip('[]'), h[4][1])) s.close() resolved = candidate_addr break except socket.error: pass if not resolved: if candidates: resolved = candidates[0] else: error = True except TypeError: err = ('Attempt to resolve address \'{0}\' failed. Invalid or unresolveable address').format(lookup) raise SaltSystemExit(code=42, msg=err) except socket.error: error = True if error: err = ('DNS lookup or connection check of \'{0}\' failed.').format(addr) if safe: if salt.log.is_console_configured(): # If logging is not configured it also means that either # the master or minion instance calling this hasn't even # started running log.error(err) raise SaltClientError() raise SaltSystemExit(code=42, msg=err) return resolved def is_fqdn(hostname): """ Verify if hostname conforms to be a FQDN. :param hostname: text string with the name of the host :return: bool, True if hostname is correct FQDN, False otherwise """ compliant = re.compile(r"(?!-)[A-Z\d\-\_]{1,63}(?<!-)$", re.IGNORECASE) return "." in hostname and len(hostname) < 0xff and all(compliant.match(x) for x in hostname.rstrip(".").split("."))
saltstack/salt
salt/utils/network.py
is_fqdn
python
def is_fqdn(hostname): compliant = re.compile(r"(?!-)[A-Z\d\-\_]{1,63}(?<!-)$", re.IGNORECASE) return "." in hostname and len(hostname) < 0xff and all(compliant.match(x) for x in hostname.rstrip(".").split("."))
Verify if hostname conforms to be a FQDN. :param hostname: text string with the name of the host :return: bool, True if hostname is correct FQDN, False otherwise
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/network.py#L2057-L2066
null
# -*- coding: utf-8 -*- ''' Define some generic socket functions for network modules ''' # Import python libs from __future__ import absolute_import, unicode_literals, print_function import itertools import os import re import types import socket import logging import platform import random import subprocess from string import ascii_letters, digits # Import 3rd-party libs from salt.ext import six from salt.ext.six.moves import range # pylint: disable=import-error,redefined-builtin # Attempt to import wmi try: import wmi import salt.utils.winapi except ImportError: pass # Import salt libs import salt.utils.args import salt.utils.files import salt.utils.path import salt.utils.platform import salt.utils.stringutils import salt.utils.zeromq from salt._compat import ipaddress from salt.exceptions import SaltClientError, SaltSystemExit from salt.utils.decorators.jinja import jinja_filter from salt.utils.versions import LooseVersion # inet_pton does not exist in Windows, this is a workaround if salt.utils.platform.is_windows(): from salt.ext import win_inet_pton # pylint: disable=unused-import log = logging.getLogger(__name__) try: import ctypes import ctypes.util libc = ctypes.cdll.LoadLibrary(ctypes.util.find_library("c")) res_init = libc.__res_init except (ImportError, OSError, AttributeError, TypeError): pass # pylint: disable=C0103 def sanitize_host(host): ''' Sanitize host string. https://tools.ietf.org/html/rfc1123#section-2.1 ''' RFC952_characters = ascii_letters + digits + ".-" return "".join([c for c in host[0:255] if c in RFC952_characters]) def isportopen(host, port): ''' Return status of a port ''' if not 1 <= int(port) <= 65535: return False sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) out = sock.connect_ex((sanitize_host(host), int(port))) return out def host_to_ips(host): ''' Returns a list of IP addresses of a given hostname or None if not found. ''' ips = [] try: for family, socktype, proto, canonname, sockaddr in socket.getaddrinfo( host, 0, socket.AF_UNSPEC, socket.SOCK_STREAM): if family == socket.AF_INET: ip, port = sockaddr elif family == socket.AF_INET6: ip, port, flow_info, scope_id = sockaddr ips.append(ip) if not ips: ips = None except Exception: ips = None return ips def _generate_minion_id(): ''' Get list of possible host names and convention names. :return: ''' # There are three types of hostnames: # 1. Network names. How host is accessed from the network. # 2. Host aliases. They might be not available in all the network or only locally (/etc/hosts) # 3. Convention names, an internal nodename. class DistinctList(list): ''' List, which allows one to append only distinct objects. Needs to work on Python 2.6, because of collections.OrderedDict only since 2.7 version. Override 'filter()' for custom filtering. ''' localhost_matchers = [r'localhost.*', r'ip6-.*', r'127[.]\d', r'0\.0\.0\.0', r'::1.*', r'ipv6-.*', r'fe00::.*', r'fe02::.*', r'1.0.0.*.ip6.arpa'] def append(self, p_object): if p_object and p_object not in self and not self.filter(p_object): super(DistinctList, self).append(p_object) return self def extend(self, iterable): for obj in iterable: self.append(obj) return self def filter(self, element): 'Returns True if element needs to be filtered' for rgx in self.localhost_matchers: if re.match(rgx, element): return True def first(self): return self and self[0] or None hostname = socket.gethostname() hosts = DistinctList().append( salt.utils.stringutils.to_unicode(socket.getfqdn(salt.utils.stringutils.to_bytes(hostname))) ).append(platform.node()).append(hostname) if not hosts: try: for a_nfo in socket.getaddrinfo(hosts.first() or 'localhost', None, socket.AF_INET, socket.SOCK_RAW, socket.IPPROTO_IP, socket.AI_CANONNAME): if len(a_nfo) > 3: hosts.append(a_nfo[3]) except socket.gaierror: log.warning('Cannot resolve address %s info via socket: %s', hosts.first() or 'localhost (N/A)', socket.gaierror) # Universal method for everywhere (Linux, Slowlaris, Windows etc) for f_name in ('/etc/hostname', '/etc/nodename', '/etc/hosts', r'{win}\system32\drivers\etc\hosts'.format(win=os.getenv('WINDIR'))): try: with salt.utils.files.fopen(f_name) as f_hdl: for line in f_hdl: line = salt.utils.stringutils.to_unicode(line) hst = line.strip().split('#')[0].strip().split() if hst: if hst[0][:4] in ('127.', '::1') or len(hst) == 1: hosts.extend(hst) except IOError: pass # include public and private ipaddresses return hosts.extend([addr for addr in ip_addrs() if not ipaddress.ip_address(addr).is_loopback]) def generate_minion_id(): ''' Return only first element of the hostname from all possible list. :return: ''' try: ret = salt.utils.stringutils.to_unicode(_generate_minion_id().first()) except TypeError: ret = None return ret or 'localhost' def get_socket(addr, type=socket.SOCK_STREAM, proto=0): ''' Return a socket object for the addr IP-version agnostic ''' version = ipaddress.ip_address(addr).version if version == 4: family = socket.AF_INET elif version == 6: family = socket.AF_INET6 return socket.socket(family, type, proto) def get_fqhostname(): ''' Returns the fully qualified hostname ''' # try getaddrinfo() fqdn = None try: addrinfo = socket.getaddrinfo( socket.gethostname(), 0, socket.AF_UNSPEC, socket.SOCK_STREAM, socket.SOL_TCP, socket.AI_CANONNAME ) for info in addrinfo: # info struct [family, socktype, proto, canonname, sockaddr] # On Windows `canonname` can be an empty string # This can cause the function to return `None` if len(info) > 3 and info[3]: fqdn = info[3] break except socket.gaierror: pass # NOTE: this used to log.error() but it was later disabled except socket.error as err: log.debug('socket.getaddrinfo() failure while finding fqdn: %s', err) if fqdn is None: fqdn = socket.getfqdn() return fqdn def ip_to_host(ip): ''' Returns the hostname of a given IP ''' try: hostname, aliaslist, ipaddrlist = socket.gethostbyaddr(ip) except Exception as exc: log.debug('salt.utils.network.ip_to_host(%r) failed: %s', ip, exc) hostname = None return hostname # pylint: enable=C0103 def is_reachable_host(entity_name): ''' Returns a bool telling if the entity name is a reachable host (IPv4/IPv6/FQDN/etc). :param hostname: :return: ''' try: assert type(socket.getaddrinfo(entity_name, 0, 0, 0, 0)) == list ret = True except socket.gaierror: ret = False return ret def is_ip(ip): ''' Returns a bool telling if the passed IP is a valid IPv4 or IPv6 address. ''' return is_ipv4(ip) or is_ipv6(ip) def is_ipv4(ip): ''' Returns a bool telling if the value passed to it was a valid IPv4 address ''' try: return ipaddress.ip_address(ip).version == 4 except ValueError: return False def is_ipv6(ip): ''' Returns a bool telling if the value passed to it was a valid IPv6 address ''' try: return ipaddress.ip_address(ip).version == 6 except ValueError: return False def is_subnet(cidr): ''' Returns a bool telling if the passed string is an IPv4 or IPv6 subnet ''' return is_ipv4_subnet(cidr) or is_ipv6_subnet(cidr) def is_ipv4_subnet(cidr): ''' Returns a bool telling if the passed string is an IPv4 subnet ''' try: return '/' in cidr and bool(ipaddress.IPv4Network(cidr)) except Exception: return False def is_ipv6_subnet(cidr): ''' Returns a bool telling if the passed string is an IPv6 subnet ''' try: return '/' in cidr and bool(ipaddress.IPv6Network(cidr)) except Exception: return False @jinja_filter('is_ip') def is_ip_filter(ip, options=None): ''' Returns a bool telling if the passed IP is a valid IPv4 or IPv6 address. ''' return is_ipv4_filter(ip, options=options) or is_ipv6_filter(ip, options=options) def _ip_options_global(ip_obj, version): return not ip_obj.is_private def _ip_options_multicast(ip_obj, version): return ip_obj.is_multicast def _ip_options_loopback(ip_obj, version): return ip_obj.is_loopback def _ip_options_link_local(ip_obj, version): return ip_obj.is_link_local def _ip_options_private(ip_obj, version): return ip_obj.is_private def _ip_options_reserved(ip_obj, version): return ip_obj.is_reserved def _ip_options_site_local(ip_obj, version): if version == 6: return ip_obj.is_site_local return False def _ip_options_unspecified(ip_obj, version): return ip_obj.is_unspecified def _ip_options(ip_obj, version, options=None): # will process and IP options options_fun_map = { 'global': _ip_options_global, 'link-local': _ip_options_link_local, 'linklocal': _ip_options_link_local, 'll': _ip_options_link_local, 'link_local': _ip_options_link_local, 'loopback': _ip_options_loopback, 'lo': _ip_options_loopback, 'multicast': _ip_options_multicast, 'private': _ip_options_private, 'public': _ip_options_global, 'reserved': _ip_options_reserved, 'site-local': _ip_options_site_local, 'sl': _ip_options_site_local, 'site_local': _ip_options_site_local, 'unspecified': _ip_options_unspecified } if not options: return six.text_type(ip_obj) # IP version already checked options_list = [option.strip() for option in options.split(',')] for option, fun in options_fun_map.items(): if option in options_list: fun_res = fun(ip_obj, version) if not fun_res: return None # stop at first failed test # else continue return six.text_type(ip_obj) def _is_ipv(ip, version, options=None): if not version: version = 4 if version not in (4, 6): return None try: ip_obj = ipaddress.ip_address(ip) except ValueError: # maybe it is an IP network try: ip_obj = ipaddress.ip_interface(ip) except ValueError: # nope, still not :( return None if not ip_obj.version == version: return None # has the right version, let's move on return _ip_options(ip_obj, version, options=options) @jinja_filter('is_ipv4') def is_ipv4_filter(ip, options=None): ''' Returns a bool telling if the value passed to it was a valid IPv4 address. ip The IP address. net: False Consider IP addresses followed by netmask. options CSV of options regarding the nature of the IP address. E.g.: loopback, multicast, private etc. ''' _is_ipv4 = _is_ipv(ip, 4, options=options) return isinstance(_is_ipv4, six.string_types) @jinja_filter('is_ipv6') def is_ipv6_filter(ip, options=None): ''' Returns a bool telling if the value passed to it was a valid IPv6 address. ip The IP address. net: False Consider IP addresses followed by netmask. options CSV of options regarding the nature of the IP address. E.g.: loopback, multicast, private etc. ''' _is_ipv6 = _is_ipv(ip, 6, options=options) return isinstance(_is_ipv6, six.string_types) def _ipv_filter(value, version, options=None): if version not in (4, 6): return if isinstance(value, (six.string_types, six.text_type, six.binary_type)): return _is_ipv(value, version, options=options) # calls is_ipv4 or is_ipv6 for `value` elif isinstance(value, (list, tuple, types.GeneratorType)): # calls is_ipv4 or is_ipv6 for each element in the list # os it filters and returns only those elements having the desired IP version return [ _is_ipv(addr, version, options=options) for addr in value if _is_ipv(addr, version, options=options) is not None ] return None @jinja_filter('ipv4') def ipv4(value, options=None): ''' Filters a list and returns IPv4 values only. ''' return _ipv_filter(value, 4, options=options) @jinja_filter('ipv6') def ipv6(value, options=None): ''' Filters a list and returns IPv6 values only. ''' return _ipv_filter(value, 6, options=options) @jinja_filter('ipaddr') def ipaddr(value, options=None): ''' Filters and returns only valid IP objects. ''' ipv4_obj = ipv4(value, options=options) ipv6_obj = ipv6(value, options=options) if ipv4_obj is None or ipv6_obj is None: # an IP address can be either IPv4 either IPv6 # therefofe if the value passed as arg is not a list, at least one of the calls above will return None # if one of them is none, means that we should return only one of them return ipv4_obj or ipv6_obj # one of them else: return ipv4_obj + ipv6_obj # extend lists def _filter_ipaddr(value, options, version=None): ipaddr_filter_out = None if version: if version == 4: ipaddr_filter_out = ipv4(value, options) elif version == 6: ipaddr_filter_out = ipv6(value, options) else: ipaddr_filter_out = ipaddr(value, options) if not ipaddr_filter_out: return if not isinstance(ipaddr_filter_out, (list, tuple, types.GeneratorType)): ipaddr_filter_out = [ipaddr_filter_out] return ipaddr_filter_out @jinja_filter('ip_host') def ip_host(value, options=None, version=None): ''' Returns the interfaces IP address, e.g.: 192.168.0.1/28. ''' ipaddr_filter_out = _filter_ipaddr(value, options=options, version=version) if not ipaddr_filter_out: return if not isinstance(value, (list, tuple, types.GeneratorType)): return six.text_type(ipaddress.ip_interface(ipaddr_filter_out[0])) return [six.text_type(ipaddress.ip_interface(ip_a)) for ip_a in ipaddr_filter_out] def _network_hosts(ip_addr_entry): return [ six.text_type(host) for host in ipaddress.ip_network(ip_addr_entry, strict=False).hosts() ] @jinja_filter('network_hosts') def network_hosts(value, options=None, version=None): ''' Return the list of hosts within a network. .. note:: When running this command with a large IPv6 network, the command will take a long time to gather all of the hosts. ''' ipaddr_filter_out = _filter_ipaddr(value, options=options, version=version) if not ipaddr_filter_out: return if not isinstance(value, (list, tuple, types.GeneratorType)): return _network_hosts(ipaddr_filter_out[0]) return [ _network_hosts(ip_a) for ip_a in ipaddr_filter_out ] def _network_size(ip_addr_entry): return ipaddress.ip_network(ip_addr_entry, strict=False).num_addresses @jinja_filter('network_size') def network_size(value, options=None, version=None): ''' Get the size of a network. ''' ipaddr_filter_out = _filter_ipaddr(value, options=options, version=version) if not ipaddr_filter_out: return if not isinstance(value, (list, tuple, types.GeneratorType)): return _network_size(ipaddr_filter_out[0]) return [ _network_size(ip_a) for ip_a in ipaddr_filter_out ] def natural_ipv4_netmask(ip, fmt='prefixlen'): ''' Returns the "natural" mask of an IPv4 address ''' bits = _ipv4_to_bits(ip) if bits.startswith('11'): mask = '24' elif bits.startswith('1'): mask = '16' else: mask = '8' if fmt == 'netmask': return cidr_to_ipv4_netmask(mask) else: return '/' + mask def rpad_ipv4_network(ip): ''' Returns an IP network address padded with zeros. Ex: '192.168.3' -> '192.168.3.0' '10.209' -> '10.209.0.0' ''' return '.'.join(itertools.islice(itertools.chain(ip.split('.'), '0000'), 0, 4)) def cidr_to_ipv4_netmask(cidr_bits): ''' Returns an IPv4 netmask ''' try: cidr_bits = int(cidr_bits) if not 1 <= cidr_bits <= 32: return '' except ValueError: return '' netmask = '' for idx in range(4): if idx: netmask += '.' if cidr_bits >= 8: netmask += '255' cidr_bits -= 8 else: netmask += '{0:d}'.format(256 - (2 ** (8 - cidr_bits))) cidr_bits = 0 return netmask def _number_of_set_bits_to_ipv4_netmask(set_bits): # pylint: disable=C0103 ''' Returns an IPv4 netmask from the integer representation of that mask. Ex. 0xffffff00 -> '255.255.255.0' ''' return cidr_to_ipv4_netmask(_number_of_set_bits(set_bits)) # pylint: disable=C0103 def _number_of_set_bits(x): ''' Returns the number of bits that are set in a 32bit int ''' # Taken from http://stackoverflow.com/a/4912729. Many thanks! x -= (x >> 1) & 0x55555555 x = ((x >> 2) & 0x33333333) + (x & 0x33333333) x = ((x >> 4) + x) & 0x0f0f0f0f x += x >> 8 x += x >> 16 return x & 0x0000003f # pylint: enable=C0103 def _interfaces_ip(out): ''' Uses ip to return a dictionary of interfaces with various information about each (up/down state, ip address, netmask, and hwaddr) ''' ret = dict() def parse_network(value, cols): ''' Return a tuple of ip, netmask, broadcast based on the current set of cols ''' brd = None scope = None if '/' in value: # we have a CIDR in this address ip, cidr = value.split('/') # pylint: disable=C0103 else: ip = value # pylint: disable=C0103 cidr = 32 if type_ == 'inet': mask = cidr_to_ipv4_netmask(int(cidr)) if 'brd' in cols: brd = cols[cols.index('brd') + 1] elif type_ == 'inet6': mask = cidr if 'scope' in cols: scope = cols[cols.index('scope') + 1] return (ip, mask, brd, scope) groups = re.compile('\r?\n\\d').split(out) for group in groups: iface = None data = dict() for line in group.splitlines(): if ' ' not in line: continue match = re.match(r'^\d*:\s+([\w.\-]+)(?:@)?([\w.\-]+)?:\s+<(.+)>', line) if match: iface, parent, attrs = match.groups() if 'UP' in attrs.split(','): data['up'] = True else: data['up'] = False if parent: data['parent'] = parent continue cols = line.split() if len(cols) >= 2: type_, value = tuple(cols[0:2]) iflabel = cols[-1:][0] if type_ in ('inet', 'inet6'): if 'secondary' not in cols: ipaddr, netmask, broadcast, scope = parse_network(value, cols) if type_ == 'inet': if 'inet' not in data: data['inet'] = list() addr_obj = dict() addr_obj['address'] = ipaddr addr_obj['netmask'] = netmask addr_obj['broadcast'] = broadcast addr_obj['label'] = iflabel data['inet'].append(addr_obj) elif type_ == 'inet6': if 'inet6' not in data: data['inet6'] = list() addr_obj = dict() addr_obj['address'] = ipaddr addr_obj['prefixlen'] = netmask addr_obj['scope'] = scope data['inet6'].append(addr_obj) else: if 'secondary' not in data: data['secondary'] = list() ip_, mask, brd, scp = parse_network(value, cols) data['secondary'].append({ 'type': type_, 'address': ip_, 'netmask': mask, 'broadcast': brd, 'label': iflabel, }) del ip_, mask, brd, scp elif type_.startswith('link'): data['hwaddr'] = value if iface: ret[iface] = data del iface, data return ret def _interfaces_ifconfig(out): ''' Uses ifconfig to return a dictionary of interfaces with various information about each (up/down state, ip address, netmask, and hwaddr) ''' ret = dict() piface = re.compile(r'^([^\s:]+)') pmac = re.compile('.*?(?:HWaddr|ether|address:|lladdr) ([0-9a-fA-F:]+)') if salt.utils.platform.is_sunos(): pip = re.compile(r'.*?(?:inet\s+)([0-9]+\.[0-9]+\.[0-9]+\.[0-9]+)(.*)') pip6 = re.compile('.*?(?:inet6 )([0-9a-fA-F:]+)') pmask6 = re.compile(r'.*?(?:inet6 [0-9a-fA-F:]+/(\d+)).*') else: pip = re.compile(r'.*?(?:inet addr:|inet [^\d]*)(.*?)\s') pip6 = re.compile('.*?(?:inet6 addr: (.*?)/|inet6 )([0-9a-fA-F:]+)') pmask6 = re.compile(r'.*?(?:inet6 addr: [0-9a-fA-F:]+/(\d+)|prefixlen (\d+))(?: Scope:([a-zA-Z]+)| scopeid (0x[0-9a-fA-F]))?') pmask = re.compile(r'.*?(?:Mask:|netmask )(?:((?:0x)?[0-9a-fA-F]{8})|([\d\.]+))') pupdown = re.compile('UP') pbcast = re.compile(r'.*?(?:Bcast:|broadcast )([\d\.]+)') groups = re.compile('\r?\n(?=\\S)').split(out) for group in groups: data = dict() iface = '' updown = False for line in group.splitlines(): miface = piface.match(line) mmac = pmac.match(line) mip = pip.match(line) mip6 = pip6.match(line) mupdown = pupdown.search(line) if miface: iface = miface.group(1) if mmac: data['hwaddr'] = mmac.group(1) if salt.utils.platform.is_sunos(): expand_mac = [] for chunk in data['hwaddr'].split(':'): expand_mac.append('0{0}'.format(chunk) if len(chunk) < 2 else '{0}'.format(chunk)) data['hwaddr'] = ':'.join(expand_mac) if mip: if 'inet' not in data: data['inet'] = list() addr_obj = dict() addr_obj['address'] = mip.group(1) mmask = pmask.match(line) if mmask: if mmask.group(1): mmask = _number_of_set_bits_to_ipv4_netmask( int(mmask.group(1), 16)) else: mmask = mmask.group(2) addr_obj['netmask'] = mmask mbcast = pbcast.match(line) if mbcast: addr_obj['broadcast'] = mbcast.group(1) data['inet'].append(addr_obj) if mupdown: updown = True if mip6: if 'inet6' not in data: data['inet6'] = list() addr_obj = dict() addr_obj['address'] = mip6.group(1) or mip6.group(2) mmask6 = pmask6.match(line) if mmask6: addr_obj['prefixlen'] = mmask6.group(1) or mmask6.group(2) if not salt.utils.platform.is_sunos(): ipv6scope = mmask6.group(3) or mmask6.group(4) addr_obj['scope'] = ipv6scope.lower() if ipv6scope is not None else ipv6scope # SunOS sometimes has ::/0 as inet6 addr when using addrconf if not salt.utils.platform.is_sunos() \ or addr_obj['address'] != '::' \ and addr_obj['prefixlen'] != 0: data['inet6'].append(addr_obj) data['up'] = updown if iface in ret: # SunOS optimization, where interfaces occur twice in 'ifconfig -a' # output with the same name: for ipv4 and then for ipv6 addr family. # Every instance has it's own 'UP' status and we assume that ipv4 # status determines global interface status. # # merge items with higher priority for older values # after that merge the inet and inet6 sub items for both ret[iface] = dict(list(data.items()) + list(ret[iface].items())) if 'inet' in data: ret[iface]['inet'].extend(x for x in data['inet'] if x not in ret[iface]['inet']) if 'inet6' in data: ret[iface]['inet6'].extend(x for x in data['inet6'] if x not in ret[iface]['inet6']) else: ret[iface] = data del data return ret def linux_interfaces(): ''' Obtain interface information for *NIX/BSD variants ''' ifaces = dict() ip_path = salt.utils.path.which('ip') ifconfig_path = None if ip_path else salt.utils.path.which('ifconfig') if ip_path: cmd1 = subprocess.Popen( '{0} link show'.format(ip_path), shell=True, close_fds=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT).communicate()[0] cmd2 = subprocess.Popen( '{0} addr show'.format(ip_path), shell=True, close_fds=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT).communicate()[0] ifaces = _interfaces_ip("{0}\n{1}".format( salt.utils.stringutils.to_str(cmd1), salt.utils.stringutils.to_str(cmd2))) elif ifconfig_path: cmd = subprocess.Popen( '{0} -a'.format(ifconfig_path), shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT).communicate()[0] ifaces = _interfaces_ifconfig(salt.utils.stringutils.to_str(cmd)) return ifaces def _netbsd_interfaces_ifconfig(out): ''' Uses ifconfig to return a dictionary of interfaces with various information about each (up/down state, ip address, netmask, and hwaddr) ''' ret = dict() piface = re.compile(r'^([^\s:]+)') pmac = re.compile('.*?address: ([0-9a-f:]+)') pip = re.compile(r'.*?inet [^\d]*(.*?)/([\d]*)\s') pip6 = re.compile(r'.*?inet6 ([0-9a-f:]+)%([a-zA-Z0-9]*)/([\d]*)\s') pupdown = re.compile('UP') pbcast = re.compile(r'.*?broadcast ([\d\.]+)') groups = re.compile('\r?\n(?=\\S)').split(out) for group in groups: data = dict() iface = '' updown = False for line in group.splitlines(): miface = piface.match(line) mmac = pmac.match(line) mip = pip.match(line) mip6 = pip6.match(line) mupdown = pupdown.search(line) if miface: iface = miface.group(1) if mmac: data['hwaddr'] = mmac.group(1) if mip: if 'inet' not in data: data['inet'] = list() addr_obj = dict() addr_obj['address'] = mip.group(1) mmask = mip.group(2) if mip.group(2): addr_obj['netmask'] = cidr_to_ipv4_netmask(mip.group(2)) mbcast = pbcast.match(line) if mbcast: addr_obj['broadcast'] = mbcast.group(1) data['inet'].append(addr_obj) if mupdown: updown = True if mip6: if 'inet6' not in data: data['inet6'] = list() addr_obj = dict() addr_obj['address'] = mip6.group(1) mmask6 = mip6.group(3) addr_obj['scope'] = mip6.group(2) addr_obj['prefixlen'] = mip6.group(3) data['inet6'].append(addr_obj) data['up'] = updown ret[iface] = data del data return ret def netbsd_interfaces(): ''' Obtain interface information for NetBSD >= 8 where the ifconfig output diverged from other BSD variants (Netmask is now part of the address) ''' # NetBSD versions prior to 8.0 can still use linux_interfaces() if LooseVersion(os.uname()[2]) < LooseVersion('8.0'): return linux_interfaces() ifconfig_path = salt.utils.path.which('ifconfig') cmd = subprocess.Popen( '{0} -a'.format(ifconfig_path), shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT).communicate()[0] return _netbsd_interfaces_ifconfig(salt.utils.stringutils.to_str(cmd)) def _interfaces_ipconfig(out): ''' Returns a dictionary of interfaces with various information about each (up/down state, ip address, netmask, and hwaddr) NOTE: This is not used by any function and may be able to be removed in the future. ''' ifaces = dict() iface = None adapter_iface_regex = re.compile(r'adapter (\S.+):$') for line in out.splitlines(): if not line: continue # TODO what does Windows call Infiniband and 10/40gige adapters if line.startswith('Ethernet'): iface = ifaces[adapter_iface_regex.search(line).group(1)] iface['up'] = True addr = None continue if iface: key, val = line.split(',', 1) key = key.strip(' .') val = val.strip() if addr and key == 'Subnet Mask': addr['netmask'] = val elif key in ('IP Address', 'IPv4 Address'): if 'inet' not in iface: iface['inet'] = list() addr = {'address': val.rstrip('(Preferred)'), 'netmask': None, 'broadcast': None} # TODO find the broadcast iface['inet'].append(addr) elif 'IPv6 Address' in key: if 'inet6' not in iface: iface['inet'] = list() # XXX What is the prefixlen!? addr = {'address': val.rstrip('(Preferred)'), 'prefixlen': None} iface['inet6'].append(addr) elif key == 'Physical Address': iface['hwaddr'] = val elif key == 'Media State': # XXX seen used for tunnel adaptors # might be useful iface['up'] = (val != 'Media disconnected') def win_interfaces(): ''' Obtain interface information for Windows systems ''' with salt.utils.winapi.Com(): c = wmi.WMI() ifaces = {} for iface in c.Win32_NetworkAdapterConfiguration(IPEnabled=1): ifaces[iface.Description] = dict() if iface.MACAddress: ifaces[iface.Description]['hwaddr'] = iface.MACAddress if iface.IPEnabled: ifaces[iface.Description]['up'] = True for ip in iface.IPAddress: if '.' in ip: if 'inet' not in ifaces[iface.Description]: ifaces[iface.Description]['inet'] = [] item = {'address': ip, 'label': iface.Description} if iface.DefaultIPGateway: broadcast = next((i for i in iface.DefaultIPGateway if '.' in i), '') if broadcast: item['broadcast'] = broadcast if iface.IPSubnet: netmask = next((i for i in iface.IPSubnet if '.' in i), '') if netmask: item['netmask'] = netmask ifaces[iface.Description]['inet'].append(item) if ':' in ip: if 'inet6' not in ifaces[iface.Description]: ifaces[iface.Description]['inet6'] = [] item = {'address': ip} if iface.DefaultIPGateway: broadcast = next((i for i in iface.DefaultIPGateway if ':' in i), '') if broadcast: item['broadcast'] = broadcast if iface.IPSubnet: netmask = next((i for i in iface.IPSubnet if ':' in i), '') if netmask: item['netmask'] = netmask ifaces[iface.Description]['inet6'].append(item) else: ifaces[iface.Description]['up'] = False return ifaces def interfaces(): ''' Return a dictionary of information about all the interfaces on the minion ''' if salt.utils.platform.is_windows(): return win_interfaces() elif salt.utils.platform.is_netbsd(): return netbsd_interfaces() else: return linux_interfaces() def get_net_start(ipaddr, netmask): ''' Return the address of the network ''' net = ipaddress.ip_network('{0}/{1}'.format(ipaddr, netmask), strict=False) return six.text_type(net.network_address) def get_net_size(mask): ''' Turns an IPv4 netmask into it's corresponding prefix length (255.255.255.0 -> 24 as in 192.168.1.10/24). ''' binary_str = '' for octet in mask.split('.'): binary_str += bin(int(octet))[2:].zfill(8) return len(binary_str.rstrip('0')) def calc_net(ipaddr, netmask=None): ''' Takes IP (CIDR notation supported) and optionally netmask and returns the network in CIDR-notation. (The IP can be any IP inside the subnet) ''' if netmask is not None: ipaddr = '{0}/{1}'.format(ipaddr, netmask) return six.text_type(ipaddress.ip_network(ipaddr, strict=False)) def _ipv4_to_bits(ipaddr): ''' Accepts an IPv4 dotted quad and returns a string representing its binary counterpart ''' return ''.join([bin(int(x))[2:].rjust(8, '0') for x in ipaddr.split('.')]) def _get_iface_info(iface): ''' If `iface` is available, return interface info and no error, otherwise return no info and log and return an error ''' iface_info = interfaces() if iface in iface_info.keys(): return iface_info, False else: error_msg = ('Interface "{0}" not in available interfaces: "{1}"' ''.format(iface, '", "'.join(iface_info.keys()))) log.error(error_msg) return None, error_msg def _hw_addr_aix(iface): ''' Return the hardware address (a.k.a. MAC address) for a given interface on AIX MAC address not available in through interfaces ''' cmd = subprocess.Popen( 'entstat -d {0} | grep \'Hardware Address\''.format(iface), shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT).communicate()[0] if cmd: comps = cmd.split(' ') if len(comps) == 3: mac_addr = comps[2].strip('\'').strip() return mac_addr error_msg = ('Interface "{0}" either not available or does not contain a hardware address'.format(iface)) log.error(error_msg) return error_msg def hw_addr(iface): ''' Return the hardware address (a.k.a. MAC address) for a given interface .. versionchanged:: 2016.11.4 Added support for AIX ''' if salt.utils.platform.is_aix(): return _hw_addr_aix iface_info, error = _get_iface_info(iface) if error is False: return iface_info.get(iface, {}).get('hwaddr', '') else: return error def interface(iface): ''' Return the details of `iface` or an error if it does not exist ''' iface_info, error = _get_iface_info(iface) if error is False: return iface_info.get(iface, {}).get('inet', '') else: return error def interface_ip(iface): ''' Return `iface` IPv4 addr or an error if `iface` does not exist ''' iface_info, error = _get_iface_info(iface) if error is False: inet = iface_info.get(iface, {}).get('inet', None) return inet[0].get('address', '') if inet else '' else: return error def _subnets(proto='inet', interfaces_=None): ''' Returns a list of subnets to which the host belongs ''' if interfaces_ is None: ifaces = interfaces() elif isinstance(interfaces_, list): ifaces = {} for key, value in six.iteritems(interfaces()): if key in interfaces_: ifaces[key] = value else: ifaces = {interfaces_: interfaces().get(interfaces_, {})} ret = set() if proto == 'inet': subnet = 'netmask' dflt_cidr = 32 elif proto == 'inet6': subnet = 'prefixlen' dflt_cidr = 128 else: log.error('Invalid proto %s calling subnets()', proto) return for ip_info in six.itervalues(ifaces): addrs = ip_info.get(proto, []) addrs.extend([addr for addr in ip_info.get('secondary', []) if addr.get('type') == proto]) for intf in addrs: if subnet in intf: intf = ipaddress.ip_interface('{0}/{1}'.format(intf['address'], intf[subnet])) else: intf = ipaddress.ip_interface('{0}/{1}'.format(intf['address'], dflt_cidr)) if not intf.is_loopback: ret.add(intf.network) return [six.text_type(net) for net in sorted(ret)] def subnets(interfaces=None): ''' Returns a list of IPv4 subnets to which the host belongs ''' return _subnets('inet', interfaces_=interfaces) def subnets6(): ''' Returns a list of IPv6 subnets to which the host belongs ''' return _subnets('inet6') def in_subnet(cidr, addr=None): ''' Returns True if host or (any of) addrs is within specified subnet, otherwise False ''' try: cidr = ipaddress.ip_network(cidr) except ValueError: log.error('Invalid CIDR \'%s\'', cidr) return False if addr is None: addr = ip_addrs() addr.extend(ip_addrs6()) elif not isinstance(addr, (list, tuple)): addr = (addr,) return any(ipaddress.ip_address(item) in cidr for item in addr) def _ip_addrs(interface=None, include_loopback=False, interface_data=None, proto='inet'): ''' Return the full list of IP adresses matching the criteria proto = inet|inet6 ''' ret = set() ifaces = interface_data \ if isinstance(interface_data, dict) \ else interfaces() if interface is None: target_ifaces = ifaces else: target_ifaces = dict([(k, v) for k, v in six.iteritems(ifaces) if k == interface]) if not target_ifaces: log.error('Interface %s not found.', interface) for ip_info in six.itervalues(target_ifaces): addrs = ip_info.get(proto, []) addrs.extend([addr for addr in ip_info.get('secondary', []) if addr.get('type') == proto]) for addr in addrs: addr = ipaddress.ip_address(addr.get('address')) if not addr.is_loopback or include_loopback: ret.add(addr) return [six.text_type(addr) for addr in sorted(ret)] def ip_addrs(interface=None, include_loopback=False, interface_data=None): ''' Returns a list of IPv4 addresses assigned to the host. 127.0.0.1 is ignored, unless 'include_loopback=True' is indicated. If 'interface' is provided, then only IP addresses from that interface will be returned. ''' return _ip_addrs(interface, include_loopback, interface_data, 'inet') def ip_addrs6(interface=None, include_loopback=False, interface_data=None): ''' Returns a list of IPv6 addresses assigned to the host. ::1 is ignored, unless 'include_loopback=True' is indicated. If 'interface' is provided, then only IP addresses from that interface will be returned. ''' return _ip_addrs(interface, include_loopback, interface_data, 'inet6') def hex2ip(hex_ip, invert=False): ''' Convert a hex string to an ip, if a failure occurs the original hex is returned. If 'invert=True' assume that ip from /proc/net/<proto> ''' if len(hex_ip) == 32: # ipv6 ip = [] for i in range(0, 32, 8): ip_part = hex_ip[i:i + 8] ip_part = [ip_part[x:x + 2] for x in range(0, 8, 2)] if invert: ip.append("{0[3]}{0[2]}:{0[1]}{0[0]}".format(ip_part)) else: ip.append("{0[0]}{0[1]}:{0[2]}{0[3]}".format(ip_part)) try: address = ipaddress.IPv6Address(":".join(ip)) if address.ipv4_mapped: return str(address.ipv4_mapped) else: return address.compressed except ipaddress.AddressValueError as ex: log.error('hex2ip - ipv6 address error: %s', ex) return hex_ip try: hip = int(hex_ip, 16) except ValueError: return hex_ip if invert: return '{3}.{2}.{1}.{0}'.format(hip >> 24 & 255, hip >> 16 & 255, hip >> 8 & 255, hip & 255) return '{0}.{1}.{2}.{3}'.format(hip >> 24 & 255, hip >> 16 & 255, hip >> 8 & 255, hip & 255) def mac2eui64(mac, prefix=None): ''' Convert a MAC address to a EUI64 identifier or, with prefix provided, a full IPv6 address ''' # http://tools.ietf.org/html/rfc4291#section-2.5.1 eui64 = re.sub(r'[.:-]', '', mac).lower() eui64 = eui64[0:6] + 'fffe' + eui64[6:] eui64 = hex(int(eui64[0:2], 16) | 2)[2:].zfill(2) + eui64[2:] if prefix is None: return ':'.join(re.findall(r'.{4}', eui64)) else: try: net = ipaddress.ip_network(prefix, strict=False) euil = int('0x{0}'.format(eui64), 16) return '{0}/{1}'.format(net[euil], net.prefixlen) except Exception: return def active_tcp(): ''' Return a dict describing all active tcp connections as quickly as possible ''' ret = {} for statf in ['/proc/net/tcp', '/proc/net/tcp6']: if os.path.isfile(statf): with salt.utils.files.fopen(statf, 'rb') as fp_: for line in fp_: line = salt.utils.stringutils.to_unicode(line) if line.strip().startswith('sl'): continue iret = _parse_tcp_line(line) sl = next(iter(iret)) if iret[sl]['state'] == 1: # 1 is ESTABLISHED del iret[sl]['state'] ret[len(ret)] = iret[sl] return ret def local_port_tcp(port): ''' Return a set of remote ip addrs attached to the specified local port ''' ret = _remotes_on(port, 'local_port') return ret def remote_port_tcp(port): ''' Return a set of ip addrs the current host is connected to on given port ''' ret = _remotes_on(port, 'remote_port') return ret def _remotes_on(port, which_end): ''' Return a set of ip addrs active tcp connections ''' port = int(port) ret = _netlink_tool_remote_on(port, which_end) if ret is not None: return ret ret = set() proc_available = False for statf in ['/proc/net/tcp', '/proc/net/tcp6']: if os.path.isfile(statf): proc_available = True with salt.utils.files.fopen(statf, 'r') as fp_: for line in fp_: line = salt.utils.stringutils.to_unicode(line) if line.strip().startswith('sl'): continue iret = _parse_tcp_line(line) sl = next(iter(iret)) if iret[sl][which_end] == port and iret[sl]['state'] == 1: # 1 is ESTABLISHED ret.add(iret[sl]['remote_addr']) if not proc_available: # Fallback to use OS specific tools if salt.utils.platform.is_sunos(): return _sunos_remotes_on(port, which_end) if salt.utils.platform.is_freebsd(): return _freebsd_remotes_on(port, which_end) if salt.utils.platform.is_netbsd(): return _netbsd_remotes_on(port, which_end) if salt.utils.platform.is_openbsd(): return _openbsd_remotes_on(port, which_end) if salt.utils.platform.is_windows(): return _windows_remotes_on(port, which_end) if salt.utils.platform.is_aix(): return _aix_remotes_on(port, which_end) return _linux_remotes_on(port, which_end) return ret def _parse_tcp_line(line): ''' Parse a single line from the contents of /proc/net/tcp or /proc/net/tcp6 ''' ret = {} comps = line.strip().split() sl = comps[0].rstrip(':') ret[sl] = {} l_addr, l_port = comps[1].split(':') r_addr, r_port = comps[2].split(':') ret[sl]['local_addr'] = hex2ip(l_addr, True) ret[sl]['local_port'] = int(l_port, 16) ret[sl]['remote_addr'] = hex2ip(r_addr, True) ret[sl]['remote_port'] = int(r_port, 16) ret[sl]['state'] = int(comps[3], 16) return ret def _netlink_tool_remote_on(port, which_end): ''' Returns set of ipv4 host addresses of remote established connections on local or remote tcp port. Parses output of shell 'ss' to get connections [root@salt-master ~]# ss -ant State Recv-Q Send-Q Local Address:Port Peer Address:Port LISTEN 0 511 *:80 *:* LISTEN 0 128 *:22 *:* ESTAB 0 0 127.0.0.1:56726 127.0.0.1:4505 ''' remotes = set() valid = False try: data = subprocess.check_output(['ss', '-ant']) # pylint: disable=minimum-python-version except subprocess.CalledProcessError: log.error('Failed ss') raise except OSError: # not command "No such file or directory" return None lines = salt.utils.stringutils.to_str(data).split('\n') for line in lines: if 'Address:Port' in line: # ss tools may not be valid valid = True continue elif 'ESTAB' not in line: continue chunks = line.split() local_host, local_port = chunks[3].split(':', 1) remote_host, remote_port = chunks[4].split(':', 1) if which_end == 'remote_port' and int(remote_port) != port: continue if which_end == 'local_port' and int(local_port) != port: continue remotes.add(remote_host) if valid is False: remotes = None return remotes def _sunos_remotes_on(port, which_end): ''' SunOS specific helper function. Returns set of ipv4 host addresses of remote established connections on local or remote tcp port. Parses output of shell 'netstat' to get connections [root@salt-master ~]# netstat -f inet -n TCP: IPv4 Local Address Remote Address Swind Send-Q Rwind Recv-Q State -------------------- -------------------- ----- ------ ----- ------ ----------- 10.0.0.101.4505 10.0.0.1.45329 1064800 0 1055864 0 ESTABLISHED 10.0.0.101.4505 10.0.0.100.50798 1064800 0 1055864 0 ESTABLISHED ''' remotes = set() try: data = subprocess.check_output(['netstat', '-f', 'inet', '-n']) # pylint: disable=minimum-python-version except subprocess.CalledProcessError: log.error('Failed netstat') raise lines = salt.utils.stringutils.to_str(data).split('\n') for line in lines: if 'ESTABLISHED' not in line: continue chunks = line.split() local_host, local_port = chunks[0].rsplit('.', 1) remote_host, remote_port = chunks[1].rsplit('.', 1) if which_end == 'remote_port' and int(remote_port) != port: continue if which_end == 'local_port' and int(local_port) != port: continue remotes.add(remote_host) return remotes def _freebsd_remotes_on(port, which_end): ''' Returns set of ipv4 host addresses of remote established connections on local tcp port port. Parses output of shell 'sockstat' (FreeBSD) to get connections $ sudo sockstat -4 USER COMMAND PID FD PROTO LOCAL ADDRESS FOREIGN ADDRESS root python2.7 1456 29 tcp4 *:4505 *:* root python2.7 1445 17 tcp4 *:4506 *:* root python2.7 1294 14 tcp4 127.0.0.1:11813 127.0.0.1:4505 root python2.7 1294 41 tcp4 127.0.0.1:61115 127.0.0.1:4506 $ sudo sockstat -4 -c -p 4506 USER COMMAND PID FD PROTO LOCAL ADDRESS FOREIGN ADDRESS root python2.7 1294 41 tcp4 127.0.0.1:61115 127.0.0.1:4506 ''' port = int(port) remotes = set() try: cmd = salt.utils.args.shlex_split('sockstat -4 -c -p {0}'.format(port)) data = subprocess.check_output(cmd) # pylint: disable=minimum-python-version except subprocess.CalledProcessError as ex: log.error('Failed "sockstat" with returncode = %s', ex.returncode) raise lines = salt.utils.stringutils.to_str(data).split('\n') for line in lines: chunks = line.split() if not chunks: continue # ['root', 'python2.7', '1456', '37', 'tcp4', # '127.0.0.1:4505-', '127.0.0.1:55703'] # print chunks if 'COMMAND' in chunks[1]: continue # ignore header if len(chunks) < 2: continue # sockstat -4 -c -p 4506 does this with high PIDs: # USER COMMAND PID FD PROTO LOCAL ADDRESS FOREIGN ADDRESS # salt-master python2.781106 35 tcp4 192.168.12.34:4506 192.168.12.45:60143 local = chunks[-2] remote = chunks[-1] lhost, lport = local.split(':') rhost, rport = remote.split(':') if which_end == 'local' and int(lport) != port: # ignore if local port not port continue if which_end == 'remote' and int(rport) != port: # ignore if remote port not port continue remotes.add(rhost) return remotes def _netbsd_remotes_on(port, which_end): ''' Returns set of ipv4 host addresses of remote established connections on local tcp port port. Parses output of shell 'sockstat' (NetBSD) to get connections $ sudo sockstat -4 -n USER COMMAND PID FD PROTO LOCAL ADDRESS FOREIGN ADDRESS root python2.7 1456 29 tcp *.4505 *.* root python2.7 1445 17 tcp *.4506 *.* root python2.7 1294 14 tcp 127.0.0.1.11813 127.0.0.1.4505 root python2.7 1294 41 tcp 127.0.0.1.61115 127.0.0.1.4506 $ sudo sockstat -4 -c -n -p 4506 USER COMMAND PID FD PROTO LOCAL ADDRESS FOREIGN ADDRESS root python2.7 1294 41 tcp 127.0.0.1.61115 127.0.0.1.4506 ''' port = int(port) remotes = set() try: cmd = salt.utils.args.shlex_split('sockstat -4 -c -n -p {0}'.format(port)) data = subprocess.check_output(cmd) # pylint: disable=minimum-python-version except subprocess.CalledProcessError as ex: log.error('Failed "sockstat" with returncode = %s', ex.returncode) raise lines = salt.utils.stringutils.to_str(data).split('\n') for line in lines: chunks = line.split() if not chunks: continue # ['root', 'python2.7', '1456', '37', 'tcp', # '127.0.0.1.4505-', '127.0.0.1.55703'] # print chunks if 'COMMAND' in chunks[1]: continue # ignore header if len(chunks) < 2: continue local = chunks[5].split('.') lport = local.pop() lhost = '.'.join(local) remote = chunks[6].split('.') rport = remote.pop() rhost = '.'.join(remote) if which_end == 'local' and int(lport) != port: # ignore if local port not port continue if which_end == 'remote' and int(rport) != port: # ignore if remote port not port continue remotes.add(rhost) return remotes def _openbsd_remotes_on(port, which_end): ''' OpenBSD specific helper function. Returns set of ipv4 host addresses of remote established connections on local or remote tcp port. Parses output of shell 'netstat' to get connections $ netstat -nf inet Active Internet connections Proto Recv-Q Send-Q Local Address Foreign Address (state) tcp 0 0 10.0.0.101.4505 10.0.0.1.45329 ESTABLISHED tcp 0 0 10.0.0.101.4505 10.0.0.100.50798 ESTABLISHED ''' remotes = set() try: data = subprocess.check_output(['netstat', '-nf', 'inet']) # pylint: disable=minimum-python-version except subprocess.CalledProcessError: log.error('Failed netstat') raise lines = data.split('\n') for line in lines: if 'ESTABLISHED' not in line: continue chunks = line.split() local_host, local_port = chunks[3].rsplit('.', 1) remote_host, remote_port = chunks[4].rsplit('.', 1) if which_end == 'remote_port' and int(remote_port) != port: continue if which_end == 'local_port' and int(local_port) != port: continue remotes.add(remote_host) return remotes def _windows_remotes_on(port, which_end): r''' Windows specific helper function. Returns set of ipv4 host addresses of remote established connections on local or remote tcp port. Parses output of shell 'netstat' to get connections C:\>netstat -n Active Connections Proto Local Address Foreign Address State TCP 10.2.33.17:3007 130.164.12.233:10123 ESTABLISHED TCP 10.2.33.17:3389 130.164.30.5:10378 ESTABLISHED ''' remotes = set() try: data = subprocess.check_output(['netstat', '-n']) # pylint: disable=minimum-python-version except subprocess.CalledProcessError: log.error('Failed netstat') raise lines = salt.utils.stringutils.to_str(data).split('\n') for line in lines: if 'ESTABLISHED' not in line: continue chunks = line.split() local_host, local_port = chunks[1].rsplit(':', 1) remote_host, remote_port = chunks[2].rsplit(':', 1) if which_end == 'remote_port' and int(remote_port) != port: continue if which_end == 'local_port' and int(local_port) != port: continue remotes.add(remote_host) return remotes def _linux_remotes_on(port, which_end): ''' Linux specific helper function. Returns set of ip host addresses of remote established connections on local tcp port port. Parses output of shell 'lsof' to get connections $ sudo lsof -iTCP:4505 -n COMMAND PID USER FD TYPE DEVICE SIZE/OFF NODE NAME Python 9971 root 35u IPv4 0x18a8464a29ca329d 0t0 TCP *:4505 (LISTEN) Python 9971 root 37u IPv4 0x18a8464a29b2b29d 0t0 TCP 127.0.0.1:4505->127.0.0.1:55703 (ESTABLISHED) Python 10152 root 22u IPv4 0x18a8464a29c8cab5 0t0 TCP 127.0.0.1:55703->127.0.0.1:4505 (ESTABLISHED) Python 10153 root 22u IPv4 0x18a8464a29c8cab5 0t0 TCP [fe80::249a]:4505->[fe80::150]:59367 (ESTABLISHED) ''' remotes = set() try: data = subprocess.check_output( ['lsof', '-iTCP:{0:d}'.format(port), '-n', '-P'] # pylint: disable=minimum-python-version ) except subprocess.CalledProcessError as ex: if ex.returncode == 1: # Lsof return 1 if any error was detected, including the failure # to locate Internet addresses, and it is not an error in this case. log.warning('"lsof" returncode = 1, likely no active TCP sessions.') return remotes log.error('Failed "lsof" with returncode = %s', ex.returncode) raise lines = salt.utils.stringutils.to_str(data).split('\n') for line in lines: chunks = line.split() if not chunks: continue # ['Python', '9971', 'root', '37u', 'IPv4', '0x18a8464a29b2b29d', '0t0', # 'TCP', '127.0.0.1:4505->127.0.0.1:55703', '(ESTABLISHED)'] # print chunks if 'COMMAND' in chunks[0]: continue # ignore header if 'ESTABLISHED' not in chunks[-1]: continue # ignore if not ESTABLISHED # '127.0.0.1:4505->127.0.0.1:55703' local, remote = chunks[8].split('->') _, lport = local.rsplit(':', 1) rhost, rport = remote.rsplit(':', 1) if which_end == 'remote_port' and int(rport) != port: continue if which_end == 'local_port' and int(lport) != port: continue remotes.add(rhost.strip("[]")) return remotes def _aix_remotes_on(port, which_end): ''' AIX specific helper function. Returns set of ipv4 host addresses of remote established connections on local or remote tcp port. Parses output of shell 'netstat' to get connections root@la68pp002_pub:/opt/salt/lib/python2.7/site-packages/salt/modules# netstat -f inet -n Active Internet connections Proto Recv-Q Send-Q Local Address Foreign Address (state) tcp4 0 0 172.29.149.95.50093 209.41.78.13.4505 ESTABLISHED tcp4 0 0 127.0.0.1.9514 *.* LISTEN tcp4 0 0 127.0.0.1.9515 *.* LISTEN tcp4 0 0 127.0.0.1.199 127.0.0.1.32779 ESTABLISHED tcp4 0 0 127.0.0.1.32779 127.0.0.1.199 ESTABLISHED tcp4 0 40 172.29.149.95.22 172.29.96.83.41022 ESTABLISHED tcp4 0 0 172.29.149.95.22 172.29.96.83.41032 ESTABLISHED tcp4 0 0 127.0.0.1.32771 127.0.0.1.32775 ESTABLISHED tcp 0 0 127.0.0.1.32775 127.0.0.1.32771 ESTABLISHED tcp4 0 0 127.0.0.1.32771 127.0.0.1.32776 ESTABLISHED tcp 0 0 127.0.0.1.32776 127.0.0.1.32771 ESTABLISHED tcp4 0 0 127.0.0.1.32771 127.0.0.1.32777 ESTABLISHED tcp 0 0 127.0.0.1.32777 127.0.0.1.32771 ESTABLISHED tcp4 0 0 127.0.0.1.32771 127.0.0.1.32778 ESTABLISHED tcp 0 0 127.0.0.1.32778 127.0.0.1.32771 ESTABLISHED ''' remotes = set() try: data = subprocess.check_output(['netstat', '-f', 'inet', '-n']) # pylint: disable=minimum-python-version except subprocess.CalledProcessError: log.error('Failed netstat') raise lines = salt.utils.stringutils.to_str(data).split('\n') for line in lines: if 'ESTABLISHED' not in line: continue chunks = line.split() local_host, local_port = chunks[3].rsplit('.', 1) remote_host, remote_port = chunks[4].rsplit('.', 1) if which_end == 'remote_port' and int(remote_port) != port: continue if which_end == 'local_port' and int(local_port) != port: continue remotes.add(remote_host) return remotes @jinja_filter('gen_mac') def gen_mac(prefix='AC:DE:48'): ''' Generates a MAC address with the defined OUI prefix. Common prefixes: - ``00:16:3E`` -- Xen - ``00:18:51`` -- OpenVZ - ``00:50:56`` -- VMware (manually generated) - ``52:54:00`` -- QEMU/KVM - ``AC:DE:48`` -- PRIVATE References: - http://standards.ieee.org/develop/regauth/oui/oui.txt - https://www.wireshark.org/tools/oui-lookup.html - https://en.wikipedia.org/wiki/MAC_address ''' return '{0}:{1:02X}:{2:02X}:{3:02X}'.format(prefix, random.randint(0, 0xff), random.randint(0, 0xff), random.randint(0, 0xff)) @jinja_filter('mac_str_to_bytes') def mac_str_to_bytes(mac_str): ''' Convert a MAC address string into bytes. Works with or without separators: b1 = mac_str_to_bytes('08:00:27:13:69:77') b2 = mac_str_to_bytes('080027136977') assert b1 == b2 assert isinstance(b1, bytes) ''' if len(mac_str) == 12: pass elif len(mac_str) == 17: sep = mac_str[2] mac_str = mac_str.replace(sep, '') else: raise ValueError('Invalid MAC address') chars = (int(mac_str[s:s+2], 16) for s in range(0, 12, 2)) return bytes(chars) if six.PY3 else b''.join(chr(x) for x in chars) def refresh_dns(): ''' issue #21397: force glibc to re-read resolv.conf ''' try: res_init() except NameError: # Exception raised loading the library, thus res_init is not defined pass @jinja_filter('connection_check') def connection_check(addr, port=80, safe=False, ipv6=None): ''' Provides a convenient alias for the dns_check filter. ''' return dns_check(addr, port, safe, ipv6) @jinja_filter('dns_check') def dns_check(addr, port=80, safe=False, ipv6=None, attempt_connect=True): ''' Return the ip resolved by dns, but do not exit on failure, only raise an exception. Obeys system preference for IPv4/6 address resolution - this can be overridden by the ipv6 flag. Tries to connect to the address before considering it useful. If no address can be reached, the first one resolved is used as a fallback. ''' error = False lookup = addr seen_ipv6 = False family = socket.AF_INET6 if ipv6 else socket.AF_INET if ipv6 is False else socket.AF_UNSPEC hostnames = [] try: refresh_dns() hostnames = socket.getaddrinfo(addr, port, family, socket.SOCK_STREAM) except TypeError: err = ('Attempt to resolve address \'{0}\' failed. Invalid or unresolveable address').format(lookup) raise SaltSystemExit(code=42, msg=err) except socket.error: error = True # If ipv6 is set to True, attempt another lookup using the IPv4 family, # just in case we're attempting to lookup an IPv4 IP # as an IPv6 hostname. if error and ipv6: try: refresh_dns() hostnames = socket.getaddrinfo(addr, port, socket.AF_INET, socket.SOCK_STREAM) except TypeError: err = ('Attempt to resolve address \'{0}\' failed. Invalid or unresolveable address').format(lookup) raise SaltSystemExit(code=42, msg=err) except socket.error: error = True try: if not hostnames: error = True else: resolved = False candidates = [] for h in hostnames: # Input is IP address, passed through unchanged, just return it if h[4][0] == addr: resolved = salt.utils.zeromq.ip_bracket(addr) break candidate_addr = salt.utils.zeromq.ip_bracket(h[4][0]) # sometimes /etc/hosts contains ::1 localhost if not ipv6 and candidate_addr == '[::1]': continue candidates.append(candidate_addr) if attempt_connect: try: s = socket.socket(h[0], socket.SOCK_STREAM) s.settimeout(2) s.connect((candidate_addr.strip('[]'), h[4][1])) s.close() resolved = candidate_addr break except socket.error: pass if not resolved: if candidates: resolved = candidates[0] else: error = True except TypeError: err = ('Attempt to resolve address \'{0}\' failed. Invalid or unresolveable address').format(lookup) raise SaltSystemExit(code=42, msg=err) except socket.error: error = True if error: err = ('DNS lookup or connection check of \'{0}\' failed.').format(addr) if safe: if salt.log.is_console_configured(): # If logging is not configured it also means that either # the master or minion instance calling this hasn't even # started running log.error(err) raise SaltClientError() raise SaltSystemExit(code=42, msg=err) return resolved def parse_host_port(host_port): """ Takes a string argument specifying host or host:port. Returns a (hostname, port) or (ip_address, port) tuple. If no port is given, the second (port) element of the returned tuple will be None. host:port argument, for example, is accepted in the forms of: - hostname - hostname:1234 - hostname.domain.tld - hostname.domain.tld:5678 - [1234::5]:5678 - 1234::5 - 10.11.12.13:4567 - 10.11.12.13 """ host, port = None, None # default _s_ = host_port[:] if _s_[0] == "[": if "]" in host_port: host, _s_ = _s_.lstrip("[").rsplit("]", 1) host = ipaddress.IPv6Address(host).compressed if _s_[0] == ":": port = int(_s_.lstrip(":")) else: if len(_s_) > 1: raise ValueError('found ambiguous "{}" port in "{}"'.format(_s_, host_port)) else: if _s_.count(":") == 1: host, _hostport_separator_, port = _s_.partition(":") try: port = int(port) except ValueError as _e_: log.error('host_port "%s" port value "%s" is not an integer.', host_port, port) raise _e_ else: host = _s_ try: if not isinstance(host, ipaddress._BaseAddress): host_ip = ipaddress.ip_address(host).compressed host = host_ip except ValueError: log.debug('"%s" Not an IP address? Assuming it is a hostname.', host) if host != sanitize_host(host): log.error('bad hostname: "%s"', host) raise ValueError('bad hostname: "{}"'.format(host)) return host, port
saltstack/salt
salt/modules/mount.py
_active_mounts
python
def _active_mounts(ret): ''' List active mounts on Linux systems ''' _list = _list_mounts() filename = '/proc/self/mounts' if not os.access(filename, os.R_OK): msg = 'File not readable {0}' raise CommandExecutionError(msg.format(filename)) with salt.utils.files.fopen(filename) as ifile: for line in ifile: comps = salt.utils.stringutils.to_unicode(line).split() ret[comps[1]] = {'device': comps[0], 'alt_device': _list.get(comps[1], None), 'fstype': comps[2], 'opts': _resolve_user_group_names(comps[3].split(','))} return ret
List active mounts on Linux systems
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/mount.py#L102-L119
[ "def fopen(*args, **kwargs):\n '''\n Wrapper around open() built-in to set CLOEXEC on the fd.\n\n This flag specifies that the file descriptor should be closed when an exec\n function is invoked;\n\n When a file descriptor is allocated (as with open or dup), this bit is\n initially cleared on the new file descriptor, meaning that descriptor will\n survive into the new program after exec.\n\n NB! We still have small race condition between open and fcntl.\n '''\n if six.PY3:\n try:\n # Don't permit stdin/stdout/stderr to be opened. The boolean False\n # and True are treated by Python 3's open() as file descriptors 0\n # and 1, respectively.\n if args[0] in (0, 1, 2):\n raise TypeError(\n '{0} is not a permitted file descriptor'.format(args[0])\n )\n except IndexError:\n pass\n binary = None\n # ensure 'binary' mode is always used on Windows in Python 2\n if ((six.PY2 and salt.utils.platform.is_windows() and 'binary' not in kwargs) or\n kwargs.pop('binary', False)):\n if len(args) > 1:\n args = list(args)\n if 'b' not in args[1]:\n args[1] = args[1].replace('t', 'b')\n if 'b' not in args[1]:\n args[1] += 'b'\n elif kwargs.get('mode'):\n if 'b' not in kwargs['mode']:\n kwargs['mode'] = kwargs['mode'].replace('t', 'b')\n if 'b' not in kwargs['mode']:\n kwargs['mode'] += 'b'\n else:\n # the default is to read\n kwargs['mode'] = 'rb'\n elif six.PY3 and 'encoding' not in kwargs:\n # In Python 3, if text mode is used and the encoding\n # is not specified, set the encoding to 'utf-8'.\n binary = False\n if len(args) > 1:\n args = list(args)\n if 'b' in args[1]:\n binary = True\n if kwargs.get('mode', None):\n if 'b' in kwargs['mode']:\n binary = True\n if not binary:\n kwargs['encoding'] = __salt_system_encoding__\n\n if six.PY3 and not binary and not kwargs.get('newline', None):\n kwargs['newline'] = ''\n\n f_handle = open(*args, **kwargs) # pylint: disable=resource-leakage\n\n if is_fcntl_available():\n # modify the file descriptor on systems with fcntl\n # unix and unix-like systems only\n try:\n FD_CLOEXEC = fcntl.FD_CLOEXEC # pylint: disable=C0103\n except AttributeError:\n FD_CLOEXEC = 1 # pylint: disable=C0103\n old_flags = fcntl.fcntl(f_handle.fileno(), fcntl.F_GETFD)\n fcntl.fcntl(f_handle.fileno(), fcntl.F_SETFD, old_flags | FD_CLOEXEC)\n\n return f_handle\n", "def to_unicode(s, encoding=None, errors='strict', normalize=False):\n '''\n Given str or unicode, return unicode (str for python 3)\n '''\n def _normalize(s):\n return unicodedata.normalize('NFC', s) if normalize else s\n\n if encoding is None:\n # Try utf-8 first, and fall back to detected encoding\n encoding = ('utf-8', __salt_system_encoding__)\n if not isinstance(encoding, (tuple, list)):\n encoding = (encoding,)\n\n if not encoding:\n raise ValueError('encoding cannot be empty')\n\n exc = None\n if six.PY3:\n if isinstance(s, str):\n return _normalize(s)\n elif isinstance(s, (bytes, bytearray)):\n return _normalize(to_str(s, encoding, errors))\n raise TypeError('expected str, bytes, or bytearray')\n else:\n # This needs to be str and not six.string_types, since if the string is\n # already a unicode type, it does not need to be decoded (and doing so\n # will raise an exception).\n if isinstance(s, unicode): # pylint: disable=incompatible-py3-code,undefined-variable\n return _normalize(s)\n elif isinstance(s, (str, bytearray)):\n for enc in encoding:\n try:\n return _normalize(s.decode(enc, errors))\n except UnicodeDecodeError as err:\n exc = err\n continue\n # The only way we get this far is if a UnicodeDecodeError was\n # raised, otherwise we would have already returned (or raised some\n # other exception).\n raise exc # pylint: disable=raising-bad-type\n raise TypeError('expected str or bytearray')\n", "def _list_mounts():\n ret = {}\n if __grains__['os'] in ['MacOS', 'Darwin']:\n mounts = __salt__['cmd.run_stdout']('mount')\n else:\n mounts = __salt__['cmd.run_stdout']('mount -l')\n\n for line in mounts.split('\\n'):\n comps = re.sub(r\"\\s+\", \" \", line).split()\n if len(comps) >= 3:\n ret[comps[2]] = comps[0]\n return ret\n", "def _resolve_user_group_names(opts):\n '''\n Resolve user and group names in related opts\n '''\n name_id_opts = {'uid': 'user.info',\n 'gid': 'group.info'}\n for ind, opt in enumerate(opts):\n if opt.split('=')[0] in name_id_opts:\n _givenid = opt.split('=')[1]\n _param = opt.split('=')[0]\n _id = _givenid\n if not re.match('[0-9]+$', _givenid):\n _info = __salt__[name_id_opts[_param]](_givenid)\n if _info and _param in _info:\n _id = _info[_param]\n opts[ind] = _param + '=' + six.text_type(_id)\n opts[ind] = opts[ind].replace('\\\\040', '\\\\ ')\n return opts\n" ]
# -*- coding: utf-8 -*- ''' Salt module to manage Unix mounts and the fstab file ''' # Import python libs from __future__ import absolute_import, print_function, unicode_literals import os import re import logging # Import salt libs import salt.utils.args import salt.utils.data import salt.utils.files import salt.utils.path import salt.utils.platform import salt.utils.mount import salt.utils.stringutils from salt.utils.odict import OrderedDict from salt.exceptions import CommandNotFoundError, CommandExecutionError # Import 3rd-party libs from salt.ext import six from salt.ext.six.moves import filter, zip # pylint: disable=import-error,redefined-builtin # Set up logger log = logging.getLogger(__name__) # Define the module's virtual name __virtualname__ = 'mount' def __virtual__(): ''' Only load on POSIX-like systems ''' # Disable on Windows, a specific file module exists: if salt.utils.platform.is_windows(): return (False, 'The mount module cannot be loaded: not a POSIX-like system.') return True def _list_mounts(): ret = {} if __grains__['os'] in ['MacOS', 'Darwin']: mounts = __salt__['cmd.run_stdout']('mount') else: mounts = __salt__['cmd.run_stdout']('mount -l') for line in mounts.split('\n'): comps = re.sub(r"\s+", " ", line).split() if len(comps) >= 3: ret[comps[2]] = comps[0] return ret def _active_mountinfo(ret): _list = _list_mounts() filename = '/proc/self/mountinfo' if not os.access(filename, os.R_OK): msg = 'File not readable {0}' raise CommandExecutionError(msg.format(filename)) if 'disk.blkid' not in __context__: __context__['disk.blkid'] = __salt__['disk.blkid']() blkid_info = __context__['disk.blkid'] with salt.utils.files.fopen(filename) as ifile: for line in ifile: comps = salt.utils.stringutils.to_unicode(line).split() device = comps[2].split(':') # each line can have any number of # optional parameters, we use the # location of the separator field to # determine the location of the elements # after it. _sep = comps.index('-') device_name = comps[_sep + 2] device_uuid = None device_label = None if device_name: device_uuid = blkid_info.get(device_name, {}).get('UUID') device_uuid = device_uuid and device_uuid.lower() device_label = blkid_info.get(device_name, {}).get('LABEL') ret[comps[4]] = {'mountid': comps[0], 'parentid': comps[1], 'major': device[0], 'minor': device[1], 'root': comps[3], 'opts': _resolve_user_group_names(comps[5].split(',')), 'fstype': comps[_sep + 1], 'device': device_name.replace('\\040', '\\ '), 'alt_device': _list.get(comps[4], None), 'superopts': _resolve_user_group_names(comps[_sep + 3].split(',')), 'device_uuid': device_uuid, 'device_label': device_label} return ret def _active_mounts_aix(ret): ''' List active mounts on AIX systems ''' for line in __salt__['cmd.run_stdout']('mount -p').split('\n'): comps = re.sub(r"\s+", " ", line).split() if comps: if comps[0] == 'node' or comps[0] == '--------': continue comps_len = len(comps) if line.startswith((' ', '\t')): curr_opts = _resolve_user_group_names(comps[6].split(',')) if 7 == comps_len else [] if curr_opts: ret[comps[1]] = {'device': comps[0], 'fstype': comps[2], 'opts': curr_opts} else: ret[comps[1]] = {'device': comps[0], 'fstype': comps[2]} else: curr_opts = _resolve_user_group_names(comps[7].split(',')) if 8 == comps_len else [] if curr_opts: ret[comps[2]] = {'node': comps[0], 'device': comps[1], 'fstype': comps[3], 'opts': curr_opts} else: ret[comps[2]] = {'node': comps[0], 'device': comps[1], 'fstype': comps[3]} return ret def _active_mounts_freebsd(ret): ''' List active mounts on FreeBSD systems ''' for line in __salt__['cmd.run_stdout']('mount -p').split('\n'): comps = re.sub(r"\s+", " ", line).split() ret[comps[1]] = {'device': comps[0], 'fstype': comps[2], 'opts': _resolve_user_group_names(comps[3].split(','))} return ret def _active_mounts_solaris(ret): ''' List active mounts on Solaris systems ''' for line in __salt__['cmd.run_stdout']('mount -v').split('\n'): comps = re.sub(r"\s+", " ", line).split() ret[comps[2]] = {'device': comps[0], 'fstype': comps[4], 'opts': _resolve_user_group_names(comps[5].split('/'))} return ret def _active_mounts_openbsd(ret): ''' List active mounts on OpenBSD systems ''' for line in __salt__['cmd.run_stdout']('mount -v').split('\n'): comps = re.sub(r"\s+", " ", line).split() parens = re.findall(r'\((.*?)\)', line, re.DOTALL) if len(parens) > 1: nod = __salt__['cmd.run_stdout']('ls -l {0}'.format(comps[0])) nod = ' '.join(nod.split()).split(" ") ret[comps[3]] = {'device': comps[0], 'fstype': comps[5], 'opts': _resolve_user_group_names(parens[1].split(", ")), 'major': six.text_type(nod[4].strip(",")), 'minor': six.text_type(nod[5]), 'device_uuid': parens[0]} else: ret[comps[2]] = {'device': comps[0], 'fstype': comps[4], 'opts': _resolve_user_group_names(parens[0].split(", "))} return ret def _active_mounts_darwin(ret): ''' List active mounts on Mac OS systems ''' for line in __salt__['cmd.run_stdout']('mount').split('\n'): comps = re.sub(r"\s+", " ", line).split() parens = re.findall(r'\((.*?)\)', line, re.DOTALL)[0].split(", ") ret[comps[2]] = {'device': comps[0], 'fstype': parens[0], 'opts': _resolve_user_group_names(parens[1:])} return ret def _resolve_user_group_names(opts): ''' Resolve user and group names in related opts ''' name_id_opts = {'uid': 'user.info', 'gid': 'group.info'} for ind, opt in enumerate(opts): if opt.split('=')[0] in name_id_opts: _givenid = opt.split('=')[1] _param = opt.split('=')[0] _id = _givenid if not re.match('[0-9]+$', _givenid): _info = __salt__[name_id_opts[_param]](_givenid) if _info and _param in _info: _id = _info[_param] opts[ind] = _param + '=' + six.text_type(_id) opts[ind] = opts[ind].replace('\\040', '\\ ') return opts def active(extended=False): ''' List the active mounts. CLI Example: .. code-block:: bash salt '*' mount.active ''' ret = {} if __grains__['os'] == 'FreeBSD': _active_mounts_freebsd(ret) elif 'AIX' in __grains__['kernel']: _active_mounts_aix(ret) elif __grains__['kernel'] == 'SunOS': _active_mounts_solaris(ret) elif __grains__['os'] == 'OpenBSD': _active_mounts_openbsd(ret) elif __grains__['os'] in ['MacOS', 'Darwin']: _active_mounts_darwin(ret) else: if extended: try: _active_mountinfo(ret) except CommandExecutionError: _active_mounts(ret) else: _active_mounts(ret) return ret class _fstab_entry(object): ''' Utility class for manipulating fstab entries. Primarily we're parsing, formatting, and comparing lines. Parsing emits dicts expected from fstab() or raises a ValueError. Note: We'll probably want to use os.normpath and os.normcase on 'name' ''' class ParseError(ValueError): ''' Error raised when a line isn't parsible as an fstab entry ''' fstab_keys = ('device', 'name', 'fstype', 'opts', 'dump', 'pass_num') # preserve data format compatibility_keys = ('device', 'name', 'fstype', 'opts', 'dump', 'pass') fstab_format = '{device}\t\t{name}\t{fstype}\t{opts}\t{dump} {pass_num}\n' @classmethod def dict_from_line(cls, line, keys=fstab_keys): if len(keys) != 6: raise ValueError('Invalid key array: {0}'.format(keys)) if line.startswith('#'): raise cls.ParseError("Comment!") comps = line.split() if len(comps) < 4 or len(comps) > 6: raise cls.ParseError("Invalid Entry!") comps.extend(['0'] * (len(keys) - len(comps))) return dict(zip(keys, comps)) @classmethod def from_line(cls, *args, **kwargs): return cls(** cls.dict_from_line(*args, **kwargs)) @classmethod def dict_to_line(cls, entry): return cls.fstab_format.format(**entry) def __str__(self): ''' String value, only works for full repr ''' return self.dict_to_line(self.criteria) def __repr__(self): ''' Always works ''' return repr(self.criteria) def pick(self, keys): ''' Returns an instance with just those keys ''' subset = dict([(key, self.criteria[key]) for key in keys]) return self.__class__(**subset) def __init__(self, **criteria): ''' Store non-empty, non-null values to use as filter ''' items = [key_value for key_value in six.iteritems(criteria) if key_value[1] is not None] items = [(key_value1[0], six.text_type(key_value1[1])) for key_value1 in items] self.criteria = dict(items) @staticmethod def norm_path(path): ''' Resolve equivalent paths equivalently ''' return os.path.normcase(os.path.normpath(path)) def match(self, line): ''' Compare potentially partial criteria against line ''' entry = self.dict_from_line(line) for key, value in six.iteritems(self.criteria): if entry[key] != value: return False return True class _vfstab_entry(object): ''' Utility class for manipulating vfstab entries. Primarily we're parsing, formatting, and comparing lines. Parsing emits dicts expected from fstab() or raises a ValueError. Note: We'll probably want to use os.normpath and os.normcase on 'name' Note: This parses vfstab entries on Solaris like systems #device device mount FS fsck mount mount #to mount to fsck point type pass at boot options # /devices - /devices devfs - no - ''' class ParseError(ValueError): '''Error raised when a line isn't parsible as an fstab entry''' vfstab_keys = ('device', 'device_fsck', 'name', 'fstype', 'pass_fsck', 'mount_at_boot', 'opts') # NOTE: weird formatting to match default spacing on Solaris vfstab_format = '{device:<11} {device_fsck:<3} {name:<19} {fstype:<8} {pass_fsck:<3} {mount_at_boot:<6} {opts}\n' @classmethod def dict_from_line(cls, line): if line.startswith('#'): raise cls.ParseError("Comment!") comps = line.split() if len(comps) != 7: raise cls.ParseError("Invalid Entry!") return dict(zip(cls.vfstab_keys, comps)) @classmethod def from_line(cls, *args, **kwargs): return cls(** cls.dict_from_line(*args, **kwargs)) @classmethod def dict_to_line(cls, entry): return cls.vfstab_format.format(**entry) def __str__(self): ''' String value, only works for full repr ''' return self.dict_to_line(self.criteria) def __repr__(self): ''' Always works ''' return repr(self.criteria) def pick(self, keys): ''' Returns an instance with just those keys ''' subset = dict([(key, self.criteria[key]) for key in keys]) return self.__class__(**subset) def __init__(self, **criteria): ''' Store non-empty, non-null values to use as filter ''' items = [key_value for key_value in six.iteritems(criteria) if key_value[1] is not None] items = [(key_value1[0], six.text_type(key_value1[1])) for key_value1 in items] self.criteria = dict(items) @staticmethod def norm_path(path): ''' Resolve equivalent paths equivalently ''' return os.path.normcase(os.path.normpath(path)) def match(self, line): ''' Compare potentially partial criteria against line ''' entry = self.dict_from_line(line) for key, value in six.iteritems(self.criteria): if entry[key] != value: return False return True class _FileSystemsEntry(object): ''' Utility class for manipulating filesystem entries. Primarily we're parsing, formatting, and comparing lines. Parsing emits dicts expected from fstab() or raises a ValueError. Note: We'll probably want to use os.normpath and os.normcase on 'name' ''' class ParseError(ValueError): ''' Error raised when a line isn't parsible as an fstab entry ''' filesystems_keys = ('device', 'name', 'fstype', 'vfstype', 'opts', 'mount') # preserve data format of filesystems compatibility_keys = ('dev', 'dev', 'name', 'fstype', 'vfstype', 'opts', 'mount', 'type', 'vfs', 'account', 'boot', 'check', 'free', 'nodename', 'quota', 'size', 'vol', 'log') @classmethod def dict_from_lines(cls, lines, keys=filesystems_keys): if len(lines) < 2: raise ValueError('Invalid number of lines: {0}'.format(lines)) if not keys: # if empty force default filesystems_keys keys = _FileSystemsEntry.filesystems_keys elif len(keys) < 6: raise ValueError('Invalid key name array: {0}'.format(keys)) blk_lines = lines orddict = OrderedDict() orddict['name'] = blk_lines[0].split(':')[0].strip() blk_lines.pop(0) for line in blk_lines: if line.startswith('#'): raise cls.ParseError("Comment!") comps = line.split('= ') if len(comps) != 2: raise cls.ParseError("Invalid Entry!") key_name = comps[0].strip() if key_name in keys: orddict[key_name] = comps[1].strip() else: raise ValueError('Invalid name for use in filesystems: {0}'.format(key_name)) return orddict @classmethod def dict_from_cmd_line(cls, ipargs, keys): cmdln_dict = ipargs if keys: for key, value in keys: # ignore unknown or local scope keys if key.startswith('__'): continue if key in _FileSystemsEntry.compatibility_keys: cmdln_dict[key] = value return cmdln_dict @classmethod def from_line(cls, *args, **kwargs): return cls(** cls.dict_from_cmd_line(*args, **kwargs)) @classmethod def dict_to_lines(cls, fsys_dict_entry): entry = fsys_dict_entry strg_out = entry['name'] + ':' + os.linesep for k, v in six.viewitems(entry): if 'name' not in k: strg_out += '\t{0}\t\t= {1}'.format(k, v) + os.linesep strg_out += os.linesep return six.text_type(strg_out) def dict_from_entry(self): ret = OrderedDict() ret[self.criteria['name']] = self.criteria return ret def __str__(self): ''' String value, only works for full repr ''' return self.dict_to_lines(self.criteria) def __repr__(self): ''' Always works ''' return repr(self.criteria) def pick(self, keys): ''' Returns an instance with just those keys ''' subset = dict([(key, self.criteria[key]) for key in keys]) return self.__class__(**subset) def __init__(self, **criteria): ''' Store non-empty, non-null values to use as filter ''' items = [key_value for key_value in six.iteritems(criteria) if key_value[1] is not None] items = [(key_value1[0], six.text_type(key_value1[1])) for key_value1 in items] self.criteria = OrderedDict(items) @staticmethod def norm_path(path): ''' Resolve equivalent paths equivalently ''' return os.path.normcase(os.path.normpath(path)) def match(self, fsys_view): ''' Compare potentially partial criteria against built filesystems entry dictionary ''' evalue_dict = fsys_view[1] for key, value in six.viewitems(self.criteria): if key in evalue_dict: if evalue_dict[key] != value: return False else: return False return True def __getitem__(self, key): ''' Return value for input key ''' return self.criteria[key] def fstab(config='/etc/fstab'): ''' .. versionchanged:: 2016.3.2 List the contents of the fstab CLI Example: .. code-block:: bash salt '*' mount.fstab ''' ret = {} if not os.path.isfile(config): return ret with salt.utils.files.fopen(config) as ifile: for line in ifile: line = salt.utils.stringutils.to_unicode(line) try: if __grains__['kernel'] == 'SunOS': # Note: comments use in default vfstab file! if line[0] == '#': continue entry = _vfstab_entry.dict_from_line( line) else: entry = _fstab_entry.dict_from_line( line, _fstab_entry.compatibility_keys) entry['opts'] = entry['opts'].split(',') while entry['name'] in ret: entry['name'] += '_' ret[entry.pop('name')] = entry except _fstab_entry.ParseError: pass except _vfstab_entry.ParseError: pass return ret def vfstab(config='/etc/vfstab'): ''' .. versionadded:: 2016.3.2 List the contents of the vfstab CLI Example: .. code-block:: bash salt '*' mount.vfstab ''' # NOTE: vfstab is a wrapper for fstab return fstab(config) def rm_fstab(name, device, config='/etc/fstab'): ''' .. versionchanged:: 2016.3.2 Remove the mount point from the fstab CLI Example: .. code-block:: bash salt '*' mount.rm_fstab /mnt/foo /dev/sdg ''' modified = False if __grains__['kernel'] == 'SunOS': criteria = _vfstab_entry(name=name, device=device) else: criteria = _fstab_entry(name=name, device=device) lines = [] try: with salt.utils.files.fopen(config, 'r') as ifile: for line in ifile: line = salt.utils.stringutils.to_unicode(line) try: if criteria.match(line): modified = True else: lines.append(line) except _fstab_entry.ParseError: lines.append(line) except _vfstab_entry.ParseError: lines.append(line) except (IOError, OSError) as exc: msg = "Couldn't read from {0}: {1}" raise CommandExecutionError(msg.format(config, exc)) if modified: try: with salt.utils.files.fopen(config, 'wb') as ofile: ofile.writelines(salt.utils.data.encode(lines)) except (IOError, OSError) as exc: msg = "Couldn't write to {0}: {1}" raise CommandExecutionError(msg.format(config, exc)) # Note: not clear why we always return 'True' # --just copying previous behavior at this point... return True def rm_vfstab(name, device, config='/etc/vfstab'): ''' .. versionadded:: 2016.3.2 Remove the mount point from the vfstab CLI Example: .. code-block:: bash salt '*' mount.rm_vfstab /mnt/foo /device/c0t0d0p0 ''' ## NOTE: rm_vfstab is a wrapper for rm_fstab return rm_fstab(name, device, config) def set_fstab( name, device, fstype, opts='defaults', dump=0, pass_num=0, config='/etc/fstab', test=False, match_on='auto', **kwargs): ''' Verify that this mount is represented in the fstab, change the mount to match the data passed, or add the mount if it is not present. CLI Example: .. code-block:: bash salt '*' mount.set_fstab /mnt/foo /dev/sdz1 ext4 ''' # Fix the opts type if it is a list if isinstance(opts, list): opts = ','.join(opts) # preserve arguments for updating entry_args = { 'name': name, 'device': device.replace('\\ ', '\\040'), 'fstype': fstype, 'opts': opts.replace('\\ ', '\\040'), 'dump': dump, 'pass_num': pass_num, } lines = [] ret = None # Transform match_on into list--items will be checked later if isinstance(match_on, list): pass elif not isinstance(match_on, six.string_types): msg = 'match_on must be a string or list of strings' raise CommandExecutionError(msg) elif match_on == 'auto': # Try to guess right criteria for auto.... # NOTE: missing some special fstypes here specialFSes = frozenset([ 'none', 'tmpfs', 'sysfs', 'proc', 'fusectl', 'debugfs', 'securityfs', 'devtmpfs', 'cgroup', 'btrfs']) if fstype in specialFSes: match_on = ['name'] else: match_on = ['device'] else: match_on = [match_on] # generate entry and criteria objects, handle invalid keys in match_on entry = _fstab_entry(**entry_args) try: criteria = entry.pick(match_on) except KeyError: filterFn = lambda key: key not in _fstab_entry.fstab_keys invalid_keys = filter(filterFn, match_on) msg = 'Unrecognized keys in match_on: "{0}"'.format(invalid_keys) raise CommandExecutionError(msg) # parse file, use ret to cache status if not os.path.isfile(config): raise CommandExecutionError('Bad config file "{0}"'.format(config)) try: with salt.utils.files.fopen(config, 'r') as ifile: for line in ifile: line = salt.utils.stringutils.to_unicode(line) try: if criteria.match(line): # Note: If ret isn't None here, # we've matched multiple lines ret = 'present' if entry.match(line): lines.append(line) else: ret = 'change' lines.append(six.text_type(entry)) else: lines.append(line) except _fstab_entry.ParseError: lines.append(line) except (IOError, OSError) as exc: msg = 'Couldn\'t read from {0}: {1}' raise CommandExecutionError(msg.format(config, exc)) # add line if not present or changed if ret is None: lines.append(six.text_type(entry)) ret = 'new' if ret != 'present': # ret in ['new', 'change']: if not salt.utils.args.test_mode(test=test, **kwargs): try: with salt.utils.files.fopen(config, 'wb') as ofile: # The line was changed, commit it! ofile.writelines(salt.utils.data.encode(lines)) except (IOError, OSError): msg = 'File not writable {0}' raise CommandExecutionError(msg.format(config)) return ret def set_vfstab( name, device, fstype, opts='-', device_fsck='-', pass_fsck='-', mount_at_boot='yes', config='/etc/vfstab', test=False, match_on='auto', **kwargs): ''' ..verionadded:: 2016.3.2 Verify that this mount is represented in the fstab, change the mount to match the data passed, or add the mount if it is not present. CLI Example: .. code-block:: bash salt '*' mount.set_vfstab /mnt/foo /device/c0t0d0p0 ufs ''' # Fix the opts type if it is a list if isinstance(opts, list): opts = ','.join(opts) # Map unknown values for mount_at_boot to no if mount_at_boot != 'yes': mount_at_boot = 'no' # preserve arguments for updating entry_args = { 'name': name, 'device': device, 'fstype': fstype, 'opts': opts, 'device_fsck': device_fsck, 'pass_fsck': pass_fsck, 'mount_at_boot': mount_at_boot, } lines = [] ret = None # Transform match_on into list--items will be checked later if isinstance(match_on, list): pass elif not isinstance(match_on, six.string_types): msg = 'match_on must be a string or list of strings' raise CommandExecutionError(msg) elif match_on == 'auto': # Try to guess right criteria for auto.... # NOTE: missing some special fstypes here specialFSes = frozenset([ 'devfs', 'proc', 'ctfs', 'objfs', 'sharefs', 'fs', 'tmpfs']) if fstype in specialFSes: match_on = ['name'] else: match_on = ['device'] else: match_on = [match_on] # generate entry and criteria objects, handle invalid keys in match_on entry = _vfstab_entry(**entry_args) try: criteria = entry.pick(match_on) except KeyError: filterFn = lambda key: key not in _vfstab_entry.vfstab_keys invalid_keys = filter(filterFn, match_on) msg = 'Unrecognized keys in match_on: "{0}"'.format(invalid_keys) raise CommandExecutionError(msg) # parse file, use ret to cache status if not os.path.isfile(config): raise CommandExecutionError('Bad config file "{0}"'.format(config)) try: with salt.utils.files.fopen(config, 'r') as ifile: for line in ifile: line = salt.utils.stringutils.to_unicode(line) try: if criteria.match(line): # Note: If ret isn't None here, # we've matched multiple lines ret = 'present' if entry.match(line): lines.append(line) else: ret = 'change' lines.append(six.text_type(entry)) else: lines.append(line) except _vfstab_entry.ParseError: lines.append(line) except (IOError, OSError) as exc: msg = 'Couldn\'t read from {0}: {1}' raise CommandExecutionError(msg.format(config, exc)) # add line if not present or changed if ret is None: lines.append(six.text_type(entry)) ret = 'new' if ret != 'present': # ret in ['new', 'change']: if not salt.utils.args.test_mode(test=test, **kwargs): try: with salt.utils.files.fopen(config, 'wb') as ofile: # The line was changed, commit it! ofile.writelines(salt.utils.data.encode(lines)) except (IOError, OSError): msg = 'File not writable {0}' raise CommandExecutionError(msg.format(config)) return ret def rm_automaster(name, device, config='/etc/auto_salt'): ''' Remove the mount point from the auto_master CLI Example: .. code-block:: bash salt '*' mount.rm_automaster /mnt/foo /dev/sdg ''' contents = automaster(config) if name not in contents: return True # The entry is present, get rid of it lines = [] try: with salt.utils.files.fopen(config, 'r') as ifile: for line in ifile: line = salt.utils.stringutils.to_unicode(line) if line.startswith('#'): # Commented lines.append(line) continue if not line.strip(): # Blank line lines.append(line) continue comps = line.split() if len(comps) != 3: # Invalid entry lines.append(line) continue comps = line.split() prefix = "/.." name_chk = comps[0].replace(prefix, "") device_fmt = comps[2].split(":") if device: if name_chk == name and device_fmt[1] == device: continue else: if name_chk == name: continue lines.append(line) except (IOError, OSError) as exc: msg = "Couldn't read from {0}: {1}" raise CommandExecutionError(msg.format(config, exc)) try: with salt.utils.files.fopen(config, 'wb') as ofile: ofile.writelines(salt.utils.data.encode(lines)) except (IOError, OSError) as exc: msg = "Couldn't write to {0}: {1}" raise CommandExecutionError(msg.format(config, exc)) # Update automount __salt__['cmd.run']('automount -cv') return True def set_automaster( name, device, fstype, opts='', config='/etc/auto_salt', test=False, **kwargs): ''' Verify that this mount is represented in the auto_salt, change the mount to match the data passed, or add the mount if it is not present. CLI Example: .. code-block:: bash salt '*' mount.set_automaster /mnt/foo /dev/sdz1 ext4 ''' # Fix the opts type if it is a list if isinstance(opts, list): opts = ','.join(opts) lines = [] change = False present = False automaster_file = "/etc/auto_master" if not os.path.isfile(config): __salt__['file.touch'](config) __salt__['file.append'](automaster_file, "/-\t\t\t{0}".format(config)) name = "/..{0}".format(name) device_fmt = "{0}:{1}".format(fstype, device) type_opts = "-fstype={0},{1}".format(fstype, opts) if fstype == 'smbfs': device_fmt = device_fmt.replace(fstype, "") try: with salt.utils.files.fopen(config, 'r') as ifile: for line in ifile: line = salt.utils.stringutils.to_unicode(line) if line.startswith('#'): # Commented lines.append(line) continue if not line.strip(): # Blank line lines.append(line) continue comps = line.split() if len(comps) != 3: # Invalid entry lines.append(line) continue if comps[0] == name or comps[2] == device_fmt: # check to see if there are changes # and fix them if there are any present = True if comps[0] != name: change = True comps[0] = name if comps[1] != type_opts: change = True comps[1] = type_opts if comps[2] != device_fmt: change = True comps[2] = device_fmt if change: log.debug( 'auto_master entry for mount point %s needs to be ' 'updated', name ) newline = ( '{0}\t{1}\t{2}\n'.format( name, type_opts, device_fmt) ) lines.append(newline) else: lines.append(line) except (IOError, OSError) as exc: msg = 'Couldn\'t read from {0}: {1}' raise CommandExecutionError(msg.format(config, exc)) if change: if not salt.utils.args.test_mode(test=test, **kwargs): try: with salt.utils.files.fopen(config, 'wb') as ofile: # The line was changed, commit it! ofile.writelines(salt.utils.data.encode(lines)) except (IOError, OSError): msg = 'File not writable {0}' raise CommandExecutionError(msg.format(config)) return 'change' if not change: if present: # The right entry is already here return 'present' else: if not salt.utils.args.test_mode(test=test, **kwargs): # The entry is new, add it to the end of the fstab newline = ( '{0}\t{1}\t{2}\n'.format( name, type_opts, device_fmt) ) lines.append(newline) try: with salt.utils.files.fopen(config, 'wb') as ofile: # The line was changed, commit it! ofile.writelines(salt.utils.data.encode(lines)) except (IOError, OSError): raise CommandExecutionError( 'File not writable {0}'.format( config ) ) return 'new' def automaster(config='/etc/auto_salt'): ''' List the contents of the auto master CLI Example: .. code-block:: bash salt '*' mount.automaster ''' ret = {} if not os.path.isfile(config): return ret with salt.utils.files.fopen(config) as ifile: for line in ifile: line = salt.utils.stringutils.to_unicode(line) if line.startswith('#'): # Commented continue if not line.strip(): # Blank line continue comps = line.split() if len(comps) != 3: # Invalid entry continue prefix = "/.." name = comps[0].replace(prefix, "") device_fmt = comps[2].split(":") opts = comps[1].split(',') ret[name] = {'device': device_fmt[1], 'fstype': opts[0], 'opts': opts[1:]} return ret def mount(name, device, mkmnt=False, fstype='', opts='defaults', user=None, util='mount'): ''' Mount a device CLI Example: .. code-block:: bash salt '*' mount.mount /mnt/foo /dev/sdz1 True ''' if util != 'mount': # This functionality used to live in img.mount_image if util == 'guestfs': return __salt__['guestfs.mount'](name, root=device) elif util == 'qemu_nbd': mnt = __salt__['qemu_nbd.init'](name, device) if not mnt: return False first = next(six.iterkeys(mnt)) __context__['img.mnt_{0}'.format(first)] = mnt return first return False # Darwin doesn't expect defaults when mounting without other options if 'defaults' in opts and __grains__['os'] in ['MacOS', 'Darwin', 'AIX']: opts = None if isinstance(opts, six.string_types): opts = opts.split(',') if not os.path.exists(name) and mkmnt: __salt__['file.mkdir'](name, user=user) args = '' if opts is not None: lopts = ','.join(opts) args = '-o {0}'.format(lopts) if fstype: # use of fstype on AIX differs from typical Linux use of -t # functionality AIX uses -v vfsname, -t fstype mounts all with # fstype in /etc/filesystems if 'AIX' in __grains__['os']: args += ' -v {0}'.format(fstype) elif 'solaris' in __grains__['os'].lower(): args += ' -F {0}'.format(fstype) else: args += ' -t {0}'.format(fstype) cmd = 'mount {0} {1} {2} '.format(args, device, name) out = __salt__['cmd.run_all'](cmd, runas=user, python_shell=False) if out['retcode']: return out['stderr'] return True def remount(name, device, mkmnt=False, fstype='', opts='defaults', user=None): ''' Attempt to remount a device, if the device is not already mounted, mount is called CLI Example: .. code-block:: bash salt '*' mount.remount /mnt/foo /dev/sdz1 True ''' force_mount = False if __grains__['os'] in ['MacOS', 'Darwin']: if opts == 'defaults': opts = 'noowners' if fstype == 'smbfs': force_mount = True if 'AIX' in __grains__['os']: if opts == 'defaults': opts = [] if isinstance(opts, six.string_types): opts = opts.split(',') mnts = active() if name in mnts: # The mount point is mounted, attempt to remount it with the given data if 'remount' not in opts and __grains__['os'] not in ['OpenBSD', 'MacOS', 'Darwin']: opts.append('remount') if force_mount: # We need to force the mount but first we should unmount umount(name, device, user=user) lopts = ','.join(opts) args = '-o {0}'.format(lopts) if fstype: # use of fstype on AIX differs from typical Linux use of # -t functionality AIX uses -v vfsname, -t fstype mounts # all with fstype in /etc/filesystems if 'AIX' in __grains__['os']: args += ' -v {0}'.format(fstype) elif 'solaris' in __grains__['os'].lower(): args += ' -F {0}'.format(fstype) else: args += ' -t {0}'.format(fstype) if __grains__['os'] not in ['OpenBSD', 'MacOS', 'Darwin'] or force_mount: cmd = 'mount {0} {1} {2} '.format(args, device, name) else: cmd = 'mount -u {0} {1} {2} '.format(args, device, name) out = __salt__['cmd.run_all'](cmd, runas=user, python_shell=False) if out['retcode']: return out['stderr'] return True # Mount a filesystem that isn't already return mount(name, device, mkmnt, fstype, opts, user=user) def umount(name, device=None, user=None, util='mount'): ''' Attempt to unmount a device by specifying the directory it is mounted on CLI Example: .. code-block:: bash salt '*' mount.umount /mnt/foo .. versionadded:: 2015.5.0 .. code-block:: bash salt '*' mount.umount /mnt/foo /dev/xvdc1 ''' if util != 'mount': # This functionality used to live in img.umount_image if 'qemu_nbd.clear' in __salt__: if 'img.mnt_{0}'.format(name) in __context__: __salt__['qemu_nbd.clear'](__context__['img.mnt_{0}'.format(name)]) return mnts = active() if name not in mnts: return "{0} does not have anything mounted".format(name) if not device: cmd = 'umount {0}'.format(name) else: cmd = 'umount {0}'.format(device) out = __salt__['cmd.run_all'](cmd, runas=user, python_shell=False) if out['retcode']: return out['stderr'] return True def is_fuse_exec(cmd): ''' Returns true if the command passed is a fuse mountable application. CLI Example: .. code-block:: bash salt '*' mount.is_fuse_exec sshfs ''' cmd_path = salt.utils.path.which(cmd) # No point in running ldd on a command that doesn't exist if not cmd_path: return False elif not salt.utils.path.which('ldd'): raise CommandNotFoundError('ldd') out = __salt__['cmd.run']('ldd {0}'.format(cmd_path), python_shell=False) return 'libfuse' in out def swaps(): ''' Return a dict containing information on active swap .. versionchanged:: 2016.3.2 CLI Example: .. code-block:: bash salt '*' mount.swaps ''' ret = {} if __grains__['kernel'] == 'SunOS': for line in __salt__['cmd.run_stdout']('swap -l').splitlines(): if line.startswith('swapfile'): continue comps = line.split() ret[comps[0]] = {'type': 'device' if comps[0].startswith(('/dev', 'swap')) else 'file', 'size': int(comps[3]), 'used': (int(comps[3]) - int(comps[4])), 'priority': '-'} elif 'AIX' in __grains__['kernel']: for line in __salt__['cmd.run_stdout']('swap -l').splitlines(): if line.startswith('device'): continue comps = line.split() # AIX uses MB for units ret[comps[0]] = {'type': 'device', 'size': int(comps[3][:-2]) * 1024, 'used': (int(comps[3][:-2]) - int(comps[4][:-2])) * 1024, 'priority': '-'} elif __grains__['os'] != 'OpenBSD': with salt.utils.files.fopen('/proc/swaps') as fp_: for line in fp_: line = salt.utils.stringutils.to_unicode(line) if line.startswith('Filename'): continue comps = line.split() ret[comps[0]] = {'type': comps[1], 'size': comps[2], 'used': comps[3], 'priority': comps[4]} else: for line in __salt__['cmd.run_stdout']('swapctl -kl').splitlines(): if line.startswith(('Device', 'Total')): continue swap_type = "file" comps = line.split() if comps[0].startswith('/dev/'): swap_type = "partition" ret[comps[0]] = {'type': swap_type, 'size': comps[1], 'used': comps[2], 'priority': comps[5]} return ret def swapon(name, priority=None): ''' Activate a swap disk .. versionchanged:: 2016.3.2 CLI Example: .. code-block:: bash salt '*' mount.swapon /root/swapfile ''' ret = {} on_ = swaps() if name in on_: ret['stats'] = on_[name] ret['new'] = False return ret if __grains__['kernel'] == 'SunOS': if __grains__['virtual'] != 'zone': __salt__['cmd.run']('swap -a {0}'.format(name), python_shell=False) else: return False else: cmd = 'swapon {0}'.format(name) if priority and 'AIX' not in __grains__['kernel']: cmd += ' -p {0}'.format(priority) __salt__['cmd.run'](cmd, python_shell=False) on_ = swaps() if name in on_: ret['stats'] = on_[name] ret['new'] = True return ret return ret def swapoff(name): ''' Deactivate a named swap mount .. versionchanged:: 2016.3.2 CLI Example: .. code-block:: bash salt '*' mount.swapoff /root/swapfile ''' on_ = swaps() if name in on_: if __grains__['kernel'] == 'SunOS': if __grains__['virtual'] != 'zone': __salt__['cmd.run']('swap -a {0}'.format(name), python_shell=False) else: return False elif __grains__['os'] != 'OpenBSD': __salt__['cmd.run']('swapoff {0}'.format(name), python_shell=False) else: __salt__['cmd.run']('swapctl -d {0}'.format(name), python_shell=False) on_ = swaps() if name in on_: return False return True return None def is_mounted(name): ''' .. versionadded:: 2014.7.0 Provide information if the path is mounted CLI Example: .. code-block:: bash salt '*' mount.is_mounted /mnt/share ''' active_ = active() if name in active_: return True else: return False def read_mount_cache(name): ''' .. versionadded:: 2018.3.0 Provide information if the path is mounted CLI Example: .. code-block:: bash salt '*' mount.read_mount_cache /mnt/share ''' cache = salt.utils.mount.read_cache(__opts__) if cache: if 'mounts' in cache and cache['mounts']: if name in cache['mounts']: return cache['mounts'][name] return {} def write_mount_cache(real_name, device, mkmnt, fstype, mount_opts): ''' .. versionadded:: 2018.3.0 Provide information if the path is mounted :param real_name: The real name of the mount point where the device is mounted. :param device: The device that is being mounted. :param mkmnt: Whether or not the mount point should be created. :param fstype: The file system that is used. :param mount_opts: Additional options used when mounting the device. :return: Boolean if message was sent successfully. CLI Example: .. code-block:: bash salt '*' mount.write_mount_cache /mnt/share /dev/sda1 False ext4 defaults,nosuid ''' cache = salt.utils.mount.read_cache(__opts__) if not cache: cache = {} cache['mounts'] = {} else: if 'mounts' not in cache: cache['mounts'] = {} cache['mounts'][real_name] = {'device': device, 'fstype': fstype, 'mkmnt': mkmnt, 'opts': mount_opts} cache_write = salt.utils.mount.write_cache(cache, __opts__) if cache_write: return True else: raise CommandExecutionError('Unable to write mount cache.') def delete_mount_cache(real_name): ''' .. versionadded:: 2018.3.0 Provide information if the path is mounted CLI Example: .. code-block:: bash salt '*' mount.delete_mount_cache /mnt/share ''' cache = salt.utils.mount.read_cache(__opts__) if cache: if 'mounts' in cache: if real_name in cache['mounts']: del cache['mounts'][real_name] cache_write = salt.utils.mount.write_cache(cache, __opts__) if not cache_write: raise CommandExecutionError('Unable to write mount cache.') return True def _filesystems(config='/etc/filesystems', leading_key=True): ''' Return the contents of the filesystems in an OrderedDict config File containing filesystem infomation leading_key True return dictionary keyed by 'name' and value as dictionary with other keys, values (name excluded) OrderedDict({ '/dir' : OrderedDict({'dev': '/dev/hd8', .... }})) False return dictionary keyed by 'name' and value as dictionary with all keys, values (name included) OrderedDict({ '/dir' : OrderedDict({'name': '/dir', 'dev': '/dev/hd8', ... })}) ''' ret = OrderedDict() lines = [] parsing_block = False if not os.path.isfile(config) or 'AIX' not in __grains__['kernel']: return ret # read in block of filesystems, block starts with '/' till empty line with salt.utils.files.fopen(config) as ifile: for line in ifile: line = salt.utils.stringutils.to_unicode(line) # skip till first entry if not line.startswith('/') and not parsing_block: continue if line.startswith('/'): parsing_block = True lines.append(line) elif not line.split(): parsing_block = False try: entry = _FileSystemsEntry.dict_from_lines( lines, _FileSystemsEntry.compatibility_keys) lines = [] if 'opts' in entry: entry['opts'] = entry['opts'].split(',') while entry['name'] in ret: entry['name'] += '_' if leading_key: ret[entry.pop('name')] = entry else: ret[entry['name']] = entry except _FileSystemsEntry.ParseError: pass else: lines.append(line) return ret def filesystems(config='/etc/filesystems'): ''' .. versionadded:: 2018.3.3 List the contents of the filesystems CLI Example: .. code-block:: bash salt '*' mount.filesystems ''' ret = {} if 'AIX' not in __grains__['kernel']: return ret ret_dict = _filesystems(config) if ret_dict: ret_key = next(iter(ret_dict.keys())) ret = {ret_key: dict(ret_dict[ret_key])} return ret def set_filesystems( name, device, vfstype, opts='-', mount='true', config='/etc/filesystems', test=False, match_on='auto', **kwargs): ''' .. versionadded:: 2018.3.3 Verify that this mount is represented in the filesystems, change the mount to match the data passed, or add the mount if it is not present on AIX Provide information if the path is mounted :param name: The name of the mount point where the device is mounted. :param device: The device that is being mounted. :param vfstype: The file system that is used (AIX has two fstypes, fstype and vfstype - similar to Linux fstype) :param opts: Additional options used when mounting the device. :param mount: Mount if not mounted, default True. :param config: Configuration file, default /etc/filesystems. :param match: File systems type to match on, default auto CLI Example: .. code-block:: bash salt '*' mount.set_filesystems /mnt/foo /dev/sdz1 jfs2 ''' # Fix the opts type if it is a list if isinstance(opts, list): opts = ','.join(opts) # preserve arguments for updating entry_args = { 'name': name, 'dev': device.replace('\\ ', '\\040'), 'vfstype': vfstype, 'opts': opts, 'mount': mount, } view_lines = [] ret = None if 'AIX' not in __grains__['kernel']: return ret # Transform match_on into list--items will be checked later if isinstance(match_on, list): pass elif not isinstance(match_on, six.string_types): raise CommandExecutionError('match_on must be a string or list of strings') elif match_on == 'auto': # Try to guess right criteria for auto.... # added IBM types from sys/vmount.h after btrfs # NOTE: missing some special fstypes here specialFSes = frozenset([ 'none', 'tmpfs', 'sysfs', 'proc', 'fusectl', 'debugfs', 'securityfs', 'devtmpfs', 'cgroup', 'btrfs', 'cdrfs', 'procfs', 'jfs', 'jfs2', 'nfs', 'sfs', 'nfs3', 'cachefs', 'udfs', 'cifs', 'namefs', 'pmemfs', 'ahafs', 'nfs4', 'autofs', 'stnfs']) if vfstype in specialFSes: match_on = ['name'] else: match_on = ['dev'] else: match_on = [match_on] # generate entry and criteria objects, handle invalid keys in match_on entry_ip = _FileSystemsEntry.from_line(entry_args, kwargs) try: criteria = entry_ip.pick(match_on) except KeyError: filterFn = lambda key: key not in _FileSystemsEntry.compatibility_keys invalid_keys = filter(filterFn, match_on) raise CommandExecutionError('Unrecognized keys in match_on: "{0}"'.format(invalid_keys)) # parse file, use ret to cache status if not os.path.isfile(config): raise CommandExecutionError('Bad config file "{0}"'.format(config)) # read in block of filesystem, block starts with '/' till empty line try: fsys_filedict = _filesystems(config, False) for fsys_view in six.viewitems(fsys_filedict): if criteria.match(fsys_view): ret = 'present' if entry_ip.match(fsys_view): view_lines.append(fsys_view) else: ret = 'change' kv = entry_ip['name'] view_lines.append((kv, entry_ip)) else: view_lines.append(fsys_view) except (IOError, OSError) as exc: raise CommandExecutionError('Couldn\'t read from {0}: {1}'.format(config, exc)) # add line if not present or changed if ret is None: for dict_view in six.viewitems(entry_ip.dict_from_entry()): view_lines.append(dict_view) ret = 'new' if ret != 'present': # ret in ['new', 'change']: try: with salt.utils.files.fopen(config, 'wb') as ofile: # The line was changed, commit it! for fsys_view in view_lines: entry = fsys_view[1] mystrg = _FileSystemsEntry.dict_to_lines(entry) ofile.writelines(salt.utils.data.encode(mystrg)) except (IOError, OSError): raise CommandExecutionError('File not writable {0}'.format(config)) return ret def rm_filesystems(name, device, config='/etc/filesystems'): ''' .. versionadded:: 2018.3.3 Remove the mount point from the filesystems CLI Example: .. code-block:: bash salt '*' mount.rm_filesystems /mnt/foo /dev/sdg ''' modified = False view_lines = [] if 'AIX' not in __grains__['kernel']: return modified criteria = _FileSystemsEntry(name=name, dev=device) try: fsys_filedict = _filesystems(config, False) for fsys_view in six.viewitems(fsys_filedict): try: if criteria.match(fsys_view): modified = True else: view_lines.append(fsys_view) except _FileSystemsEntry.ParseError: view_lines.append(fsys_view) except (IOError, OSError) as exc: raise CommandExecutionError("Couldn't read from {0}: {1}".format(config, exc)) if modified: try: with salt.utils.files.fopen(config, 'wb') as ofile: for fsys_view in view_lines: entry = fsys_view[1] mystrg = _FileSystemsEntry.dict_to_lines(entry) ofile.writelines(salt.utils.data.encode(mystrg)) except (IOError, OSError) as exc: raise CommandExecutionError("Couldn't write to {0}: {1}".format(config, exc)) return modified
saltstack/salt
salt/modules/mount.py
_active_mounts_aix
python
def _active_mounts_aix(ret): ''' List active mounts on AIX systems ''' for line in __salt__['cmd.run_stdout']('mount -p').split('\n'): comps = re.sub(r"\s+", " ", line).split() if comps: if comps[0] == 'node' or comps[0] == '--------': continue comps_len = len(comps) if line.startswith((' ', '\t')): curr_opts = _resolve_user_group_names(comps[6].split(',')) if 7 == comps_len else [] if curr_opts: ret[comps[1]] = {'device': comps[0], 'fstype': comps[2], 'opts': curr_opts} else: ret[comps[1]] = {'device': comps[0], 'fstype': comps[2]} else: curr_opts = _resolve_user_group_names(comps[7].split(',')) if 8 == comps_len else [] if curr_opts: ret[comps[2]] = {'node': comps[0], 'device': comps[1], 'fstype': comps[3], 'opts': curr_opts} else: ret[comps[2]] = {'node': comps[0], 'device': comps[1], 'fstype': comps[3]} return ret
List active mounts on AIX systems
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/mount.py#L122-L152
[ "def _resolve_user_group_names(opts):\n '''\n Resolve user and group names in related opts\n '''\n name_id_opts = {'uid': 'user.info',\n 'gid': 'group.info'}\n for ind, opt in enumerate(opts):\n if opt.split('=')[0] in name_id_opts:\n _givenid = opt.split('=')[1]\n _param = opt.split('=')[0]\n _id = _givenid\n if not re.match('[0-9]+$', _givenid):\n _info = __salt__[name_id_opts[_param]](_givenid)\n if _info and _param in _info:\n _id = _info[_param]\n opts[ind] = _param + '=' + six.text_type(_id)\n opts[ind] = opts[ind].replace('\\\\040', '\\\\ ')\n return opts\n" ]
# -*- coding: utf-8 -*- ''' Salt module to manage Unix mounts and the fstab file ''' # Import python libs from __future__ import absolute_import, print_function, unicode_literals import os import re import logging # Import salt libs import salt.utils.args import salt.utils.data import salt.utils.files import salt.utils.path import salt.utils.platform import salt.utils.mount import salt.utils.stringutils from salt.utils.odict import OrderedDict from salt.exceptions import CommandNotFoundError, CommandExecutionError # Import 3rd-party libs from salt.ext import six from salt.ext.six.moves import filter, zip # pylint: disable=import-error,redefined-builtin # Set up logger log = logging.getLogger(__name__) # Define the module's virtual name __virtualname__ = 'mount' def __virtual__(): ''' Only load on POSIX-like systems ''' # Disable on Windows, a specific file module exists: if salt.utils.platform.is_windows(): return (False, 'The mount module cannot be loaded: not a POSIX-like system.') return True def _list_mounts(): ret = {} if __grains__['os'] in ['MacOS', 'Darwin']: mounts = __salt__['cmd.run_stdout']('mount') else: mounts = __salt__['cmd.run_stdout']('mount -l') for line in mounts.split('\n'): comps = re.sub(r"\s+", " ", line).split() if len(comps) >= 3: ret[comps[2]] = comps[0] return ret def _active_mountinfo(ret): _list = _list_mounts() filename = '/proc/self/mountinfo' if not os.access(filename, os.R_OK): msg = 'File not readable {0}' raise CommandExecutionError(msg.format(filename)) if 'disk.blkid' not in __context__: __context__['disk.blkid'] = __salt__['disk.blkid']() blkid_info = __context__['disk.blkid'] with salt.utils.files.fopen(filename) as ifile: for line in ifile: comps = salt.utils.stringutils.to_unicode(line).split() device = comps[2].split(':') # each line can have any number of # optional parameters, we use the # location of the separator field to # determine the location of the elements # after it. _sep = comps.index('-') device_name = comps[_sep + 2] device_uuid = None device_label = None if device_name: device_uuid = blkid_info.get(device_name, {}).get('UUID') device_uuid = device_uuid and device_uuid.lower() device_label = blkid_info.get(device_name, {}).get('LABEL') ret[comps[4]] = {'mountid': comps[0], 'parentid': comps[1], 'major': device[0], 'minor': device[1], 'root': comps[3], 'opts': _resolve_user_group_names(comps[5].split(',')), 'fstype': comps[_sep + 1], 'device': device_name.replace('\\040', '\\ '), 'alt_device': _list.get(comps[4], None), 'superopts': _resolve_user_group_names(comps[_sep + 3].split(',')), 'device_uuid': device_uuid, 'device_label': device_label} return ret def _active_mounts(ret): ''' List active mounts on Linux systems ''' _list = _list_mounts() filename = '/proc/self/mounts' if not os.access(filename, os.R_OK): msg = 'File not readable {0}' raise CommandExecutionError(msg.format(filename)) with salt.utils.files.fopen(filename) as ifile: for line in ifile: comps = salt.utils.stringutils.to_unicode(line).split() ret[comps[1]] = {'device': comps[0], 'alt_device': _list.get(comps[1], None), 'fstype': comps[2], 'opts': _resolve_user_group_names(comps[3].split(','))} return ret def _active_mounts_freebsd(ret): ''' List active mounts on FreeBSD systems ''' for line in __salt__['cmd.run_stdout']('mount -p').split('\n'): comps = re.sub(r"\s+", " ", line).split() ret[comps[1]] = {'device': comps[0], 'fstype': comps[2], 'opts': _resolve_user_group_names(comps[3].split(','))} return ret def _active_mounts_solaris(ret): ''' List active mounts on Solaris systems ''' for line in __salt__['cmd.run_stdout']('mount -v').split('\n'): comps = re.sub(r"\s+", " ", line).split() ret[comps[2]] = {'device': comps[0], 'fstype': comps[4], 'opts': _resolve_user_group_names(comps[5].split('/'))} return ret def _active_mounts_openbsd(ret): ''' List active mounts on OpenBSD systems ''' for line in __salt__['cmd.run_stdout']('mount -v').split('\n'): comps = re.sub(r"\s+", " ", line).split() parens = re.findall(r'\((.*?)\)', line, re.DOTALL) if len(parens) > 1: nod = __salt__['cmd.run_stdout']('ls -l {0}'.format(comps[0])) nod = ' '.join(nod.split()).split(" ") ret[comps[3]] = {'device': comps[0], 'fstype': comps[5], 'opts': _resolve_user_group_names(parens[1].split(", ")), 'major': six.text_type(nod[4].strip(",")), 'minor': six.text_type(nod[5]), 'device_uuid': parens[0]} else: ret[comps[2]] = {'device': comps[0], 'fstype': comps[4], 'opts': _resolve_user_group_names(parens[0].split(", "))} return ret def _active_mounts_darwin(ret): ''' List active mounts on Mac OS systems ''' for line in __salt__['cmd.run_stdout']('mount').split('\n'): comps = re.sub(r"\s+", " ", line).split() parens = re.findall(r'\((.*?)\)', line, re.DOTALL)[0].split(", ") ret[comps[2]] = {'device': comps[0], 'fstype': parens[0], 'opts': _resolve_user_group_names(parens[1:])} return ret def _resolve_user_group_names(opts): ''' Resolve user and group names in related opts ''' name_id_opts = {'uid': 'user.info', 'gid': 'group.info'} for ind, opt in enumerate(opts): if opt.split('=')[0] in name_id_opts: _givenid = opt.split('=')[1] _param = opt.split('=')[0] _id = _givenid if not re.match('[0-9]+$', _givenid): _info = __salt__[name_id_opts[_param]](_givenid) if _info and _param in _info: _id = _info[_param] opts[ind] = _param + '=' + six.text_type(_id) opts[ind] = opts[ind].replace('\\040', '\\ ') return opts def active(extended=False): ''' List the active mounts. CLI Example: .. code-block:: bash salt '*' mount.active ''' ret = {} if __grains__['os'] == 'FreeBSD': _active_mounts_freebsd(ret) elif 'AIX' in __grains__['kernel']: _active_mounts_aix(ret) elif __grains__['kernel'] == 'SunOS': _active_mounts_solaris(ret) elif __grains__['os'] == 'OpenBSD': _active_mounts_openbsd(ret) elif __grains__['os'] in ['MacOS', 'Darwin']: _active_mounts_darwin(ret) else: if extended: try: _active_mountinfo(ret) except CommandExecutionError: _active_mounts(ret) else: _active_mounts(ret) return ret class _fstab_entry(object): ''' Utility class for manipulating fstab entries. Primarily we're parsing, formatting, and comparing lines. Parsing emits dicts expected from fstab() or raises a ValueError. Note: We'll probably want to use os.normpath and os.normcase on 'name' ''' class ParseError(ValueError): ''' Error raised when a line isn't parsible as an fstab entry ''' fstab_keys = ('device', 'name', 'fstype', 'opts', 'dump', 'pass_num') # preserve data format compatibility_keys = ('device', 'name', 'fstype', 'opts', 'dump', 'pass') fstab_format = '{device}\t\t{name}\t{fstype}\t{opts}\t{dump} {pass_num}\n' @classmethod def dict_from_line(cls, line, keys=fstab_keys): if len(keys) != 6: raise ValueError('Invalid key array: {0}'.format(keys)) if line.startswith('#'): raise cls.ParseError("Comment!") comps = line.split() if len(comps) < 4 or len(comps) > 6: raise cls.ParseError("Invalid Entry!") comps.extend(['0'] * (len(keys) - len(comps))) return dict(zip(keys, comps)) @classmethod def from_line(cls, *args, **kwargs): return cls(** cls.dict_from_line(*args, **kwargs)) @classmethod def dict_to_line(cls, entry): return cls.fstab_format.format(**entry) def __str__(self): ''' String value, only works for full repr ''' return self.dict_to_line(self.criteria) def __repr__(self): ''' Always works ''' return repr(self.criteria) def pick(self, keys): ''' Returns an instance with just those keys ''' subset = dict([(key, self.criteria[key]) for key in keys]) return self.__class__(**subset) def __init__(self, **criteria): ''' Store non-empty, non-null values to use as filter ''' items = [key_value for key_value in six.iteritems(criteria) if key_value[1] is not None] items = [(key_value1[0], six.text_type(key_value1[1])) for key_value1 in items] self.criteria = dict(items) @staticmethod def norm_path(path): ''' Resolve equivalent paths equivalently ''' return os.path.normcase(os.path.normpath(path)) def match(self, line): ''' Compare potentially partial criteria against line ''' entry = self.dict_from_line(line) for key, value in six.iteritems(self.criteria): if entry[key] != value: return False return True class _vfstab_entry(object): ''' Utility class for manipulating vfstab entries. Primarily we're parsing, formatting, and comparing lines. Parsing emits dicts expected from fstab() or raises a ValueError. Note: We'll probably want to use os.normpath and os.normcase on 'name' Note: This parses vfstab entries on Solaris like systems #device device mount FS fsck mount mount #to mount to fsck point type pass at boot options # /devices - /devices devfs - no - ''' class ParseError(ValueError): '''Error raised when a line isn't parsible as an fstab entry''' vfstab_keys = ('device', 'device_fsck', 'name', 'fstype', 'pass_fsck', 'mount_at_boot', 'opts') # NOTE: weird formatting to match default spacing on Solaris vfstab_format = '{device:<11} {device_fsck:<3} {name:<19} {fstype:<8} {pass_fsck:<3} {mount_at_boot:<6} {opts}\n' @classmethod def dict_from_line(cls, line): if line.startswith('#'): raise cls.ParseError("Comment!") comps = line.split() if len(comps) != 7: raise cls.ParseError("Invalid Entry!") return dict(zip(cls.vfstab_keys, comps)) @classmethod def from_line(cls, *args, **kwargs): return cls(** cls.dict_from_line(*args, **kwargs)) @classmethod def dict_to_line(cls, entry): return cls.vfstab_format.format(**entry) def __str__(self): ''' String value, only works for full repr ''' return self.dict_to_line(self.criteria) def __repr__(self): ''' Always works ''' return repr(self.criteria) def pick(self, keys): ''' Returns an instance with just those keys ''' subset = dict([(key, self.criteria[key]) for key in keys]) return self.__class__(**subset) def __init__(self, **criteria): ''' Store non-empty, non-null values to use as filter ''' items = [key_value for key_value in six.iteritems(criteria) if key_value[1] is not None] items = [(key_value1[0], six.text_type(key_value1[1])) for key_value1 in items] self.criteria = dict(items) @staticmethod def norm_path(path): ''' Resolve equivalent paths equivalently ''' return os.path.normcase(os.path.normpath(path)) def match(self, line): ''' Compare potentially partial criteria against line ''' entry = self.dict_from_line(line) for key, value in six.iteritems(self.criteria): if entry[key] != value: return False return True class _FileSystemsEntry(object): ''' Utility class for manipulating filesystem entries. Primarily we're parsing, formatting, and comparing lines. Parsing emits dicts expected from fstab() or raises a ValueError. Note: We'll probably want to use os.normpath and os.normcase on 'name' ''' class ParseError(ValueError): ''' Error raised when a line isn't parsible as an fstab entry ''' filesystems_keys = ('device', 'name', 'fstype', 'vfstype', 'opts', 'mount') # preserve data format of filesystems compatibility_keys = ('dev', 'dev', 'name', 'fstype', 'vfstype', 'opts', 'mount', 'type', 'vfs', 'account', 'boot', 'check', 'free', 'nodename', 'quota', 'size', 'vol', 'log') @classmethod def dict_from_lines(cls, lines, keys=filesystems_keys): if len(lines) < 2: raise ValueError('Invalid number of lines: {0}'.format(lines)) if not keys: # if empty force default filesystems_keys keys = _FileSystemsEntry.filesystems_keys elif len(keys) < 6: raise ValueError('Invalid key name array: {0}'.format(keys)) blk_lines = lines orddict = OrderedDict() orddict['name'] = blk_lines[0].split(':')[0].strip() blk_lines.pop(0) for line in blk_lines: if line.startswith('#'): raise cls.ParseError("Comment!") comps = line.split('= ') if len(comps) != 2: raise cls.ParseError("Invalid Entry!") key_name = comps[0].strip() if key_name in keys: orddict[key_name] = comps[1].strip() else: raise ValueError('Invalid name for use in filesystems: {0}'.format(key_name)) return orddict @classmethod def dict_from_cmd_line(cls, ipargs, keys): cmdln_dict = ipargs if keys: for key, value in keys: # ignore unknown or local scope keys if key.startswith('__'): continue if key in _FileSystemsEntry.compatibility_keys: cmdln_dict[key] = value return cmdln_dict @classmethod def from_line(cls, *args, **kwargs): return cls(** cls.dict_from_cmd_line(*args, **kwargs)) @classmethod def dict_to_lines(cls, fsys_dict_entry): entry = fsys_dict_entry strg_out = entry['name'] + ':' + os.linesep for k, v in six.viewitems(entry): if 'name' not in k: strg_out += '\t{0}\t\t= {1}'.format(k, v) + os.linesep strg_out += os.linesep return six.text_type(strg_out) def dict_from_entry(self): ret = OrderedDict() ret[self.criteria['name']] = self.criteria return ret def __str__(self): ''' String value, only works for full repr ''' return self.dict_to_lines(self.criteria) def __repr__(self): ''' Always works ''' return repr(self.criteria) def pick(self, keys): ''' Returns an instance with just those keys ''' subset = dict([(key, self.criteria[key]) for key in keys]) return self.__class__(**subset) def __init__(self, **criteria): ''' Store non-empty, non-null values to use as filter ''' items = [key_value for key_value in six.iteritems(criteria) if key_value[1] is not None] items = [(key_value1[0], six.text_type(key_value1[1])) for key_value1 in items] self.criteria = OrderedDict(items) @staticmethod def norm_path(path): ''' Resolve equivalent paths equivalently ''' return os.path.normcase(os.path.normpath(path)) def match(self, fsys_view): ''' Compare potentially partial criteria against built filesystems entry dictionary ''' evalue_dict = fsys_view[1] for key, value in six.viewitems(self.criteria): if key in evalue_dict: if evalue_dict[key] != value: return False else: return False return True def __getitem__(self, key): ''' Return value for input key ''' return self.criteria[key] def fstab(config='/etc/fstab'): ''' .. versionchanged:: 2016.3.2 List the contents of the fstab CLI Example: .. code-block:: bash salt '*' mount.fstab ''' ret = {} if not os.path.isfile(config): return ret with salt.utils.files.fopen(config) as ifile: for line in ifile: line = salt.utils.stringutils.to_unicode(line) try: if __grains__['kernel'] == 'SunOS': # Note: comments use in default vfstab file! if line[0] == '#': continue entry = _vfstab_entry.dict_from_line( line) else: entry = _fstab_entry.dict_from_line( line, _fstab_entry.compatibility_keys) entry['opts'] = entry['opts'].split(',') while entry['name'] in ret: entry['name'] += '_' ret[entry.pop('name')] = entry except _fstab_entry.ParseError: pass except _vfstab_entry.ParseError: pass return ret def vfstab(config='/etc/vfstab'): ''' .. versionadded:: 2016.3.2 List the contents of the vfstab CLI Example: .. code-block:: bash salt '*' mount.vfstab ''' # NOTE: vfstab is a wrapper for fstab return fstab(config) def rm_fstab(name, device, config='/etc/fstab'): ''' .. versionchanged:: 2016.3.2 Remove the mount point from the fstab CLI Example: .. code-block:: bash salt '*' mount.rm_fstab /mnt/foo /dev/sdg ''' modified = False if __grains__['kernel'] == 'SunOS': criteria = _vfstab_entry(name=name, device=device) else: criteria = _fstab_entry(name=name, device=device) lines = [] try: with salt.utils.files.fopen(config, 'r') as ifile: for line in ifile: line = salt.utils.stringutils.to_unicode(line) try: if criteria.match(line): modified = True else: lines.append(line) except _fstab_entry.ParseError: lines.append(line) except _vfstab_entry.ParseError: lines.append(line) except (IOError, OSError) as exc: msg = "Couldn't read from {0}: {1}" raise CommandExecutionError(msg.format(config, exc)) if modified: try: with salt.utils.files.fopen(config, 'wb') as ofile: ofile.writelines(salt.utils.data.encode(lines)) except (IOError, OSError) as exc: msg = "Couldn't write to {0}: {1}" raise CommandExecutionError(msg.format(config, exc)) # Note: not clear why we always return 'True' # --just copying previous behavior at this point... return True def rm_vfstab(name, device, config='/etc/vfstab'): ''' .. versionadded:: 2016.3.2 Remove the mount point from the vfstab CLI Example: .. code-block:: bash salt '*' mount.rm_vfstab /mnt/foo /device/c0t0d0p0 ''' ## NOTE: rm_vfstab is a wrapper for rm_fstab return rm_fstab(name, device, config) def set_fstab( name, device, fstype, opts='defaults', dump=0, pass_num=0, config='/etc/fstab', test=False, match_on='auto', **kwargs): ''' Verify that this mount is represented in the fstab, change the mount to match the data passed, or add the mount if it is not present. CLI Example: .. code-block:: bash salt '*' mount.set_fstab /mnt/foo /dev/sdz1 ext4 ''' # Fix the opts type if it is a list if isinstance(opts, list): opts = ','.join(opts) # preserve arguments for updating entry_args = { 'name': name, 'device': device.replace('\\ ', '\\040'), 'fstype': fstype, 'opts': opts.replace('\\ ', '\\040'), 'dump': dump, 'pass_num': pass_num, } lines = [] ret = None # Transform match_on into list--items will be checked later if isinstance(match_on, list): pass elif not isinstance(match_on, six.string_types): msg = 'match_on must be a string or list of strings' raise CommandExecutionError(msg) elif match_on == 'auto': # Try to guess right criteria for auto.... # NOTE: missing some special fstypes here specialFSes = frozenset([ 'none', 'tmpfs', 'sysfs', 'proc', 'fusectl', 'debugfs', 'securityfs', 'devtmpfs', 'cgroup', 'btrfs']) if fstype in specialFSes: match_on = ['name'] else: match_on = ['device'] else: match_on = [match_on] # generate entry and criteria objects, handle invalid keys in match_on entry = _fstab_entry(**entry_args) try: criteria = entry.pick(match_on) except KeyError: filterFn = lambda key: key not in _fstab_entry.fstab_keys invalid_keys = filter(filterFn, match_on) msg = 'Unrecognized keys in match_on: "{0}"'.format(invalid_keys) raise CommandExecutionError(msg) # parse file, use ret to cache status if not os.path.isfile(config): raise CommandExecutionError('Bad config file "{0}"'.format(config)) try: with salt.utils.files.fopen(config, 'r') as ifile: for line in ifile: line = salt.utils.stringutils.to_unicode(line) try: if criteria.match(line): # Note: If ret isn't None here, # we've matched multiple lines ret = 'present' if entry.match(line): lines.append(line) else: ret = 'change' lines.append(six.text_type(entry)) else: lines.append(line) except _fstab_entry.ParseError: lines.append(line) except (IOError, OSError) as exc: msg = 'Couldn\'t read from {0}: {1}' raise CommandExecutionError(msg.format(config, exc)) # add line if not present or changed if ret is None: lines.append(six.text_type(entry)) ret = 'new' if ret != 'present': # ret in ['new', 'change']: if not salt.utils.args.test_mode(test=test, **kwargs): try: with salt.utils.files.fopen(config, 'wb') as ofile: # The line was changed, commit it! ofile.writelines(salt.utils.data.encode(lines)) except (IOError, OSError): msg = 'File not writable {0}' raise CommandExecutionError(msg.format(config)) return ret def set_vfstab( name, device, fstype, opts='-', device_fsck='-', pass_fsck='-', mount_at_boot='yes', config='/etc/vfstab', test=False, match_on='auto', **kwargs): ''' ..verionadded:: 2016.3.2 Verify that this mount is represented in the fstab, change the mount to match the data passed, or add the mount if it is not present. CLI Example: .. code-block:: bash salt '*' mount.set_vfstab /mnt/foo /device/c0t0d0p0 ufs ''' # Fix the opts type if it is a list if isinstance(opts, list): opts = ','.join(opts) # Map unknown values for mount_at_boot to no if mount_at_boot != 'yes': mount_at_boot = 'no' # preserve arguments for updating entry_args = { 'name': name, 'device': device, 'fstype': fstype, 'opts': opts, 'device_fsck': device_fsck, 'pass_fsck': pass_fsck, 'mount_at_boot': mount_at_boot, } lines = [] ret = None # Transform match_on into list--items will be checked later if isinstance(match_on, list): pass elif not isinstance(match_on, six.string_types): msg = 'match_on must be a string or list of strings' raise CommandExecutionError(msg) elif match_on == 'auto': # Try to guess right criteria for auto.... # NOTE: missing some special fstypes here specialFSes = frozenset([ 'devfs', 'proc', 'ctfs', 'objfs', 'sharefs', 'fs', 'tmpfs']) if fstype in specialFSes: match_on = ['name'] else: match_on = ['device'] else: match_on = [match_on] # generate entry and criteria objects, handle invalid keys in match_on entry = _vfstab_entry(**entry_args) try: criteria = entry.pick(match_on) except KeyError: filterFn = lambda key: key not in _vfstab_entry.vfstab_keys invalid_keys = filter(filterFn, match_on) msg = 'Unrecognized keys in match_on: "{0}"'.format(invalid_keys) raise CommandExecutionError(msg) # parse file, use ret to cache status if not os.path.isfile(config): raise CommandExecutionError('Bad config file "{0}"'.format(config)) try: with salt.utils.files.fopen(config, 'r') as ifile: for line in ifile: line = salt.utils.stringutils.to_unicode(line) try: if criteria.match(line): # Note: If ret isn't None here, # we've matched multiple lines ret = 'present' if entry.match(line): lines.append(line) else: ret = 'change' lines.append(six.text_type(entry)) else: lines.append(line) except _vfstab_entry.ParseError: lines.append(line) except (IOError, OSError) as exc: msg = 'Couldn\'t read from {0}: {1}' raise CommandExecutionError(msg.format(config, exc)) # add line if not present or changed if ret is None: lines.append(six.text_type(entry)) ret = 'new' if ret != 'present': # ret in ['new', 'change']: if not salt.utils.args.test_mode(test=test, **kwargs): try: with salt.utils.files.fopen(config, 'wb') as ofile: # The line was changed, commit it! ofile.writelines(salt.utils.data.encode(lines)) except (IOError, OSError): msg = 'File not writable {0}' raise CommandExecutionError(msg.format(config)) return ret def rm_automaster(name, device, config='/etc/auto_salt'): ''' Remove the mount point from the auto_master CLI Example: .. code-block:: bash salt '*' mount.rm_automaster /mnt/foo /dev/sdg ''' contents = automaster(config) if name not in contents: return True # The entry is present, get rid of it lines = [] try: with salt.utils.files.fopen(config, 'r') as ifile: for line in ifile: line = salt.utils.stringutils.to_unicode(line) if line.startswith('#'): # Commented lines.append(line) continue if not line.strip(): # Blank line lines.append(line) continue comps = line.split() if len(comps) != 3: # Invalid entry lines.append(line) continue comps = line.split() prefix = "/.." name_chk = comps[0].replace(prefix, "") device_fmt = comps[2].split(":") if device: if name_chk == name and device_fmt[1] == device: continue else: if name_chk == name: continue lines.append(line) except (IOError, OSError) as exc: msg = "Couldn't read from {0}: {1}" raise CommandExecutionError(msg.format(config, exc)) try: with salt.utils.files.fopen(config, 'wb') as ofile: ofile.writelines(salt.utils.data.encode(lines)) except (IOError, OSError) as exc: msg = "Couldn't write to {0}: {1}" raise CommandExecutionError(msg.format(config, exc)) # Update automount __salt__['cmd.run']('automount -cv') return True def set_automaster( name, device, fstype, opts='', config='/etc/auto_salt', test=False, **kwargs): ''' Verify that this mount is represented in the auto_salt, change the mount to match the data passed, or add the mount if it is not present. CLI Example: .. code-block:: bash salt '*' mount.set_automaster /mnt/foo /dev/sdz1 ext4 ''' # Fix the opts type if it is a list if isinstance(opts, list): opts = ','.join(opts) lines = [] change = False present = False automaster_file = "/etc/auto_master" if not os.path.isfile(config): __salt__['file.touch'](config) __salt__['file.append'](automaster_file, "/-\t\t\t{0}".format(config)) name = "/..{0}".format(name) device_fmt = "{0}:{1}".format(fstype, device) type_opts = "-fstype={0},{1}".format(fstype, opts) if fstype == 'smbfs': device_fmt = device_fmt.replace(fstype, "") try: with salt.utils.files.fopen(config, 'r') as ifile: for line in ifile: line = salt.utils.stringutils.to_unicode(line) if line.startswith('#'): # Commented lines.append(line) continue if not line.strip(): # Blank line lines.append(line) continue comps = line.split() if len(comps) != 3: # Invalid entry lines.append(line) continue if comps[0] == name or comps[2] == device_fmt: # check to see if there are changes # and fix them if there are any present = True if comps[0] != name: change = True comps[0] = name if comps[1] != type_opts: change = True comps[1] = type_opts if comps[2] != device_fmt: change = True comps[2] = device_fmt if change: log.debug( 'auto_master entry for mount point %s needs to be ' 'updated', name ) newline = ( '{0}\t{1}\t{2}\n'.format( name, type_opts, device_fmt) ) lines.append(newline) else: lines.append(line) except (IOError, OSError) as exc: msg = 'Couldn\'t read from {0}: {1}' raise CommandExecutionError(msg.format(config, exc)) if change: if not salt.utils.args.test_mode(test=test, **kwargs): try: with salt.utils.files.fopen(config, 'wb') as ofile: # The line was changed, commit it! ofile.writelines(salt.utils.data.encode(lines)) except (IOError, OSError): msg = 'File not writable {0}' raise CommandExecutionError(msg.format(config)) return 'change' if not change: if present: # The right entry is already here return 'present' else: if not salt.utils.args.test_mode(test=test, **kwargs): # The entry is new, add it to the end of the fstab newline = ( '{0}\t{1}\t{2}\n'.format( name, type_opts, device_fmt) ) lines.append(newline) try: with salt.utils.files.fopen(config, 'wb') as ofile: # The line was changed, commit it! ofile.writelines(salt.utils.data.encode(lines)) except (IOError, OSError): raise CommandExecutionError( 'File not writable {0}'.format( config ) ) return 'new' def automaster(config='/etc/auto_salt'): ''' List the contents of the auto master CLI Example: .. code-block:: bash salt '*' mount.automaster ''' ret = {} if not os.path.isfile(config): return ret with salt.utils.files.fopen(config) as ifile: for line in ifile: line = salt.utils.stringutils.to_unicode(line) if line.startswith('#'): # Commented continue if not line.strip(): # Blank line continue comps = line.split() if len(comps) != 3: # Invalid entry continue prefix = "/.." name = comps[0].replace(prefix, "") device_fmt = comps[2].split(":") opts = comps[1].split(',') ret[name] = {'device': device_fmt[1], 'fstype': opts[0], 'opts': opts[1:]} return ret def mount(name, device, mkmnt=False, fstype='', opts='defaults', user=None, util='mount'): ''' Mount a device CLI Example: .. code-block:: bash salt '*' mount.mount /mnt/foo /dev/sdz1 True ''' if util != 'mount': # This functionality used to live in img.mount_image if util == 'guestfs': return __salt__['guestfs.mount'](name, root=device) elif util == 'qemu_nbd': mnt = __salt__['qemu_nbd.init'](name, device) if not mnt: return False first = next(six.iterkeys(mnt)) __context__['img.mnt_{0}'.format(first)] = mnt return first return False # Darwin doesn't expect defaults when mounting without other options if 'defaults' in opts and __grains__['os'] in ['MacOS', 'Darwin', 'AIX']: opts = None if isinstance(opts, six.string_types): opts = opts.split(',') if not os.path.exists(name) and mkmnt: __salt__['file.mkdir'](name, user=user) args = '' if opts is not None: lopts = ','.join(opts) args = '-o {0}'.format(lopts) if fstype: # use of fstype on AIX differs from typical Linux use of -t # functionality AIX uses -v vfsname, -t fstype mounts all with # fstype in /etc/filesystems if 'AIX' in __grains__['os']: args += ' -v {0}'.format(fstype) elif 'solaris' in __grains__['os'].lower(): args += ' -F {0}'.format(fstype) else: args += ' -t {0}'.format(fstype) cmd = 'mount {0} {1} {2} '.format(args, device, name) out = __salt__['cmd.run_all'](cmd, runas=user, python_shell=False) if out['retcode']: return out['stderr'] return True def remount(name, device, mkmnt=False, fstype='', opts='defaults', user=None): ''' Attempt to remount a device, if the device is not already mounted, mount is called CLI Example: .. code-block:: bash salt '*' mount.remount /mnt/foo /dev/sdz1 True ''' force_mount = False if __grains__['os'] in ['MacOS', 'Darwin']: if opts == 'defaults': opts = 'noowners' if fstype == 'smbfs': force_mount = True if 'AIX' in __grains__['os']: if opts == 'defaults': opts = [] if isinstance(opts, six.string_types): opts = opts.split(',') mnts = active() if name in mnts: # The mount point is mounted, attempt to remount it with the given data if 'remount' not in opts and __grains__['os'] not in ['OpenBSD', 'MacOS', 'Darwin']: opts.append('remount') if force_mount: # We need to force the mount but first we should unmount umount(name, device, user=user) lopts = ','.join(opts) args = '-o {0}'.format(lopts) if fstype: # use of fstype on AIX differs from typical Linux use of # -t functionality AIX uses -v vfsname, -t fstype mounts # all with fstype in /etc/filesystems if 'AIX' in __grains__['os']: args += ' -v {0}'.format(fstype) elif 'solaris' in __grains__['os'].lower(): args += ' -F {0}'.format(fstype) else: args += ' -t {0}'.format(fstype) if __grains__['os'] not in ['OpenBSD', 'MacOS', 'Darwin'] or force_mount: cmd = 'mount {0} {1} {2} '.format(args, device, name) else: cmd = 'mount -u {0} {1} {2} '.format(args, device, name) out = __salt__['cmd.run_all'](cmd, runas=user, python_shell=False) if out['retcode']: return out['stderr'] return True # Mount a filesystem that isn't already return mount(name, device, mkmnt, fstype, opts, user=user) def umount(name, device=None, user=None, util='mount'): ''' Attempt to unmount a device by specifying the directory it is mounted on CLI Example: .. code-block:: bash salt '*' mount.umount /mnt/foo .. versionadded:: 2015.5.0 .. code-block:: bash salt '*' mount.umount /mnt/foo /dev/xvdc1 ''' if util != 'mount': # This functionality used to live in img.umount_image if 'qemu_nbd.clear' in __salt__: if 'img.mnt_{0}'.format(name) in __context__: __salt__['qemu_nbd.clear'](__context__['img.mnt_{0}'.format(name)]) return mnts = active() if name not in mnts: return "{0} does not have anything mounted".format(name) if not device: cmd = 'umount {0}'.format(name) else: cmd = 'umount {0}'.format(device) out = __salt__['cmd.run_all'](cmd, runas=user, python_shell=False) if out['retcode']: return out['stderr'] return True def is_fuse_exec(cmd): ''' Returns true if the command passed is a fuse mountable application. CLI Example: .. code-block:: bash salt '*' mount.is_fuse_exec sshfs ''' cmd_path = salt.utils.path.which(cmd) # No point in running ldd on a command that doesn't exist if not cmd_path: return False elif not salt.utils.path.which('ldd'): raise CommandNotFoundError('ldd') out = __salt__['cmd.run']('ldd {0}'.format(cmd_path), python_shell=False) return 'libfuse' in out def swaps(): ''' Return a dict containing information on active swap .. versionchanged:: 2016.3.2 CLI Example: .. code-block:: bash salt '*' mount.swaps ''' ret = {} if __grains__['kernel'] == 'SunOS': for line in __salt__['cmd.run_stdout']('swap -l').splitlines(): if line.startswith('swapfile'): continue comps = line.split() ret[comps[0]] = {'type': 'device' if comps[0].startswith(('/dev', 'swap')) else 'file', 'size': int(comps[3]), 'used': (int(comps[3]) - int(comps[4])), 'priority': '-'} elif 'AIX' in __grains__['kernel']: for line in __salt__['cmd.run_stdout']('swap -l').splitlines(): if line.startswith('device'): continue comps = line.split() # AIX uses MB for units ret[comps[0]] = {'type': 'device', 'size': int(comps[3][:-2]) * 1024, 'used': (int(comps[3][:-2]) - int(comps[4][:-2])) * 1024, 'priority': '-'} elif __grains__['os'] != 'OpenBSD': with salt.utils.files.fopen('/proc/swaps') as fp_: for line in fp_: line = salt.utils.stringutils.to_unicode(line) if line.startswith('Filename'): continue comps = line.split() ret[comps[0]] = {'type': comps[1], 'size': comps[2], 'used': comps[3], 'priority': comps[4]} else: for line in __salt__['cmd.run_stdout']('swapctl -kl').splitlines(): if line.startswith(('Device', 'Total')): continue swap_type = "file" comps = line.split() if comps[0].startswith('/dev/'): swap_type = "partition" ret[comps[0]] = {'type': swap_type, 'size': comps[1], 'used': comps[2], 'priority': comps[5]} return ret def swapon(name, priority=None): ''' Activate a swap disk .. versionchanged:: 2016.3.2 CLI Example: .. code-block:: bash salt '*' mount.swapon /root/swapfile ''' ret = {} on_ = swaps() if name in on_: ret['stats'] = on_[name] ret['new'] = False return ret if __grains__['kernel'] == 'SunOS': if __grains__['virtual'] != 'zone': __salt__['cmd.run']('swap -a {0}'.format(name), python_shell=False) else: return False else: cmd = 'swapon {0}'.format(name) if priority and 'AIX' not in __grains__['kernel']: cmd += ' -p {0}'.format(priority) __salt__['cmd.run'](cmd, python_shell=False) on_ = swaps() if name in on_: ret['stats'] = on_[name] ret['new'] = True return ret return ret def swapoff(name): ''' Deactivate a named swap mount .. versionchanged:: 2016.3.2 CLI Example: .. code-block:: bash salt '*' mount.swapoff /root/swapfile ''' on_ = swaps() if name in on_: if __grains__['kernel'] == 'SunOS': if __grains__['virtual'] != 'zone': __salt__['cmd.run']('swap -a {0}'.format(name), python_shell=False) else: return False elif __grains__['os'] != 'OpenBSD': __salt__['cmd.run']('swapoff {0}'.format(name), python_shell=False) else: __salt__['cmd.run']('swapctl -d {0}'.format(name), python_shell=False) on_ = swaps() if name in on_: return False return True return None def is_mounted(name): ''' .. versionadded:: 2014.7.0 Provide information if the path is mounted CLI Example: .. code-block:: bash salt '*' mount.is_mounted /mnt/share ''' active_ = active() if name in active_: return True else: return False def read_mount_cache(name): ''' .. versionadded:: 2018.3.0 Provide information if the path is mounted CLI Example: .. code-block:: bash salt '*' mount.read_mount_cache /mnt/share ''' cache = salt.utils.mount.read_cache(__opts__) if cache: if 'mounts' in cache and cache['mounts']: if name in cache['mounts']: return cache['mounts'][name] return {} def write_mount_cache(real_name, device, mkmnt, fstype, mount_opts): ''' .. versionadded:: 2018.3.0 Provide information if the path is mounted :param real_name: The real name of the mount point where the device is mounted. :param device: The device that is being mounted. :param mkmnt: Whether or not the mount point should be created. :param fstype: The file system that is used. :param mount_opts: Additional options used when mounting the device. :return: Boolean if message was sent successfully. CLI Example: .. code-block:: bash salt '*' mount.write_mount_cache /mnt/share /dev/sda1 False ext4 defaults,nosuid ''' cache = salt.utils.mount.read_cache(__opts__) if not cache: cache = {} cache['mounts'] = {} else: if 'mounts' not in cache: cache['mounts'] = {} cache['mounts'][real_name] = {'device': device, 'fstype': fstype, 'mkmnt': mkmnt, 'opts': mount_opts} cache_write = salt.utils.mount.write_cache(cache, __opts__) if cache_write: return True else: raise CommandExecutionError('Unable to write mount cache.') def delete_mount_cache(real_name): ''' .. versionadded:: 2018.3.0 Provide information if the path is mounted CLI Example: .. code-block:: bash salt '*' mount.delete_mount_cache /mnt/share ''' cache = salt.utils.mount.read_cache(__opts__) if cache: if 'mounts' in cache: if real_name in cache['mounts']: del cache['mounts'][real_name] cache_write = salt.utils.mount.write_cache(cache, __opts__) if not cache_write: raise CommandExecutionError('Unable to write mount cache.') return True def _filesystems(config='/etc/filesystems', leading_key=True): ''' Return the contents of the filesystems in an OrderedDict config File containing filesystem infomation leading_key True return dictionary keyed by 'name' and value as dictionary with other keys, values (name excluded) OrderedDict({ '/dir' : OrderedDict({'dev': '/dev/hd8', .... }})) False return dictionary keyed by 'name' and value as dictionary with all keys, values (name included) OrderedDict({ '/dir' : OrderedDict({'name': '/dir', 'dev': '/dev/hd8', ... })}) ''' ret = OrderedDict() lines = [] parsing_block = False if not os.path.isfile(config) or 'AIX' not in __grains__['kernel']: return ret # read in block of filesystems, block starts with '/' till empty line with salt.utils.files.fopen(config) as ifile: for line in ifile: line = salt.utils.stringutils.to_unicode(line) # skip till first entry if not line.startswith('/') and not parsing_block: continue if line.startswith('/'): parsing_block = True lines.append(line) elif not line.split(): parsing_block = False try: entry = _FileSystemsEntry.dict_from_lines( lines, _FileSystemsEntry.compatibility_keys) lines = [] if 'opts' in entry: entry['opts'] = entry['opts'].split(',') while entry['name'] in ret: entry['name'] += '_' if leading_key: ret[entry.pop('name')] = entry else: ret[entry['name']] = entry except _FileSystemsEntry.ParseError: pass else: lines.append(line) return ret def filesystems(config='/etc/filesystems'): ''' .. versionadded:: 2018.3.3 List the contents of the filesystems CLI Example: .. code-block:: bash salt '*' mount.filesystems ''' ret = {} if 'AIX' not in __grains__['kernel']: return ret ret_dict = _filesystems(config) if ret_dict: ret_key = next(iter(ret_dict.keys())) ret = {ret_key: dict(ret_dict[ret_key])} return ret def set_filesystems( name, device, vfstype, opts='-', mount='true', config='/etc/filesystems', test=False, match_on='auto', **kwargs): ''' .. versionadded:: 2018.3.3 Verify that this mount is represented in the filesystems, change the mount to match the data passed, or add the mount if it is not present on AIX Provide information if the path is mounted :param name: The name of the mount point where the device is mounted. :param device: The device that is being mounted. :param vfstype: The file system that is used (AIX has two fstypes, fstype and vfstype - similar to Linux fstype) :param opts: Additional options used when mounting the device. :param mount: Mount if not mounted, default True. :param config: Configuration file, default /etc/filesystems. :param match: File systems type to match on, default auto CLI Example: .. code-block:: bash salt '*' mount.set_filesystems /mnt/foo /dev/sdz1 jfs2 ''' # Fix the opts type if it is a list if isinstance(opts, list): opts = ','.join(opts) # preserve arguments for updating entry_args = { 'name': name, 'dev': device.replace('\\ ', '\\040'), 'vfstype': vfstype, 'opts': opts, 'mount': mount, } view_lines = [] ret = None if 'AIX' not in __grains__['kernel']: return ret # Transform match_on into list--items will be checked later if isinstance(match_on, list): pass elif not isinstance(match_on, six.string_types): raise CommandExecutionError('match_on must be a string or list of strings') elif match_on == 'auto': # Try to guess right criteria for auto.... # added IBM types from sys/vmount.h after btrfs # NOTE: missing some special fstypes here specialFSes = frozenset([ 'none', 'tmpfs', 'sysfs', 'proc', 'fusectl', 'debugfs', 'securityfs', 'devtmpfs', 'cgroup', 'btrfs', 'cdrfs', 'procfs', 'jfs', 'jfs2', 'nfs', 'sfs', 'nfs3', 'cachefs', 'udfs', 'cifs', 'namefs', 'pmemfs', 'ahafs', 'nfs4', 'autofs', 'stnfs']) if vfstype in specialFSes: match_on = ['name'] else: match_on = ['dev'] else: match_on = [match_on] # generate entry and criteria objects, handle invalid keys in match_on entry_ip = _FileSystemsEntry.from_line(entry_args, kwargs) try: criteria = entry_ip.pick(match_on) except KeyError: filterFn = lambda key: key not in _FileSystemsEntry.compatibility_keys invalid_keys = filter(filterFn, match_on) raise CommandExecutionError('Unrecognized keys in match_on: "{0}"'.format(invalid_keys)) # parse file, use ret to cache status if not os.path.isfile(config): raise CommandExecutionError('Bad config file "{0}"'.format(config)) # read in block of filesystem, block starts with '/' till empty line try: fsys_filedict = _filesystems(config, False) for fsys_view in six.viewitems(fsys_filedict): if criteria.match(fsys_view): ret = 'present' if entry_ip.match(fsys_view): view_lines.append(fsys_view) else: ret = 'change' kv = entry_ip['name'] view_lines.append((kv, entry_ip)) else: view_lines.append(fsys_view) except (IOError, OSError) as exc: raise CommandExecutionError('Couldn\'t read from {0}: {1}'.format(config, exc)) # add line if not present or changed if ret is None: for dict_view in six.viewitems(entry_ip.dict_from_entry()): view_lines.append(dict_view) ret = 'new' if ret != 'present': # ret in ['new', 'change']: try: with salt.utils.files.fopen(config, 'wb') as ofile: # The line was changed, commit it! for fsys_view in view_lines: entry = fsys_view[1] mystrg = _FileSystemsEntry.dict_to_lines(entry) ofile.writelines(salt.utils.data.encode(mystrg)) except (IOError, OSError): raise CommandExecutionError('File not writable {0}'.format(config)) return ret def rm_filesystems(name, device, config='/etc/filesystems'): ''' .. versionadded:: 2018.3.3 Remove the mount point from the filesystems CLI Example: .. code-block:: bash salt '*' mount.rm_filesystems /mnt/foo /dev/sdg ''' modified = False view_lines = [] if 'AIX' not in __grains__['kernel']: return modified criteria = _FileSystemsEntry(name=name, dev=device) try: fsys_filedict = _filesystems(config, False) for fsys_view in six.viewitems(fsys_filedict): try: if criteria.match(fsys_view): modified = True else: view_lines.append(fsys_view) except _FileSystemsEntry.ParseError: view_lines.append(fsys_view) except (IOError, OSError) as exc: raise CommandExecutionError("Couldn't read from {0}: {1}".format(config, exc)) if modified: try: with salt.utils.files.fopen(config, 'wb') as ofile: for fsys_view in view_lines: entry = fsys_view[1] mystrg = _FileSystemsEntry.dict_to_lines(entry) ofile.writelines(salt.utils.data.encode(mystrg)) except (IOError, OSError) as exc: raise CommandExecutionError("Couldn't write to {0}: {1}".format(config, exc)) return modified
saltstack/salt
salt/modules/mount.py
_active_mounts_freebsd
python
def _active_mounts_freebsd(ret): ''' List active mounts on FreeBSD systems ''' for line in __salt__['cmd.run_stdout']('mount -p').split('\n'): comps = re.sub(r"\s+", " ", line).split() ret[comps[1]] = {'device': comps[0], 'fstype': comps[2], 'opts': _resolve_user_group_names(comps[3].split(','))} return ret
List active mounts on FreeBSD systems
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/mount.py#L155-L164
[ "def _resolve_user_group_names(opts):\n '''\n Resolve user and group names in related opts\n '''\n name_id_opts = {'uid': 'user.info',\n 'gid': 'group.info'}\n for ind, opt in enumerate(opts):\n if opt.split('=')[0] in name_id_opts:\n _givenid = opt.split('=')[1]\n _param = opt.split('=')[0]\n _id = _givenid\n if not re.match('[0-9]+$', _givenid):\n _info = __salt__[name_id_opts[_param]](_givenid)\n if _info and _param in _info:\n _id = _info[_param]\n opts[ind] = _param + '=' + six.text_type(_id)\n opts[ind] = opts[ind].replace('\\\\040', '\\\\ ')\n return opts\n" ]
# -*- coding: utf-8 -*- ''' Salt module to manage Unix mounts and the fstab file ''' # Import python libs from __future__ import absolute_import, print_function, unicode_literals import os import re import logging # Import salt libs import salt.utils.args import salt.utils.data import salt.utils.files import salt.utils.path import salt.utils.platform import salt.utils.mount import salt.utils.stringutils from salt.utils.odict import OrderedDict from salt.exceptions import CommandNotFoundError, CommandExecutionError # Import 3rd-party libs from salt.ext import six from salt.ext.six.moves import filter, zip # pylint: disable=import-error,redefined-builtin # Set up logger log = logging.getLogger(__name__) # Define the module's virtual name __virtualname__ = 'mount' def __virtual__(): ''' Only load on POSIX-like systems ''' # Disable on Windows, a specific file module exists: if salt.utils.platform.is_windows(): return (False, 'The mount module cannot be loaded: not a POSIX-like system.') return True def _list_mounts(): ret = {} if __grains__['os'] in ['MacOS', 'Darwin']: mounts = __salt__['cmd.run_stdout']('mount') else: mounts = __salt__['cmd.run_stdout']('mount -l') for line in mounts.split('\n'): comps = re.sub(r"\s+", " ", line).split() if len(comps) >= 3: ret[comps[2]] = comps[0] return ret def _active_mountinfo(ret): _list = _list_mounts() filename = '/proc/self/mountinfo' if not os.access(filename, os.R_OK): msg = 'File not readable {0}' raise CommandExecutionError(msg.format(filename)) if 'disk.blkid' not in __context__: __context__['disk.blkid'] = __salt__['disk.blkid']() blkid_info = __context__['disk.blkid'] with salt.utils.files.fopen(filename) as ifile: for line in ifile: comps = salt.utils.stringutils.to_unicode(line).split() device = comps[2].split(':') # each line can have any number of # optional parameters, we use the # location of the separator field to # determine the location of the elements # after it. _sep = comps.index('-') device_name = comps[_sep + 2] device_uuid = None device_label = None if device_name: device_uuid = blkid_info.get(device_name, {}).get('UUID') device_uuid = device_uuid and device_uuid.lower() device_label = blkid_info.get(device_name, {}).get('LABEL') ret[comps[4]] = {'mountid': comps[0], 'parentid': comps[1], 'major': device[0], 'minor': device[1], 'root': comps[3], 'opts': _resolve_user_group_names(comps[5].split(',')), 'fstype': comps[_sep + 1], 'device': device_name.replace('\\040', '\\ '), 'alt_device': _list.get(comps[4], None), 'superopts': _resolve_user_group_names(comps[_sep + 3].split(',')), 'device_uuid': device_uuid, 'device_label': device_label} return ret def _active_mounts(ret): ''' List active mounts on Linux systems ''' _list = _list_mounts() filename = '/proc/self/mounts' if not os.access(filename, os.R_OK): msg = 'File not readable {0}' raise CommandExecutionError(msg.format(filename)) with salt.utils.files.fopen(filename) as ifile: for line in ifile: comps = salt.utils.stringutils.to_unicode(line).split() ret[comps[1]] = {'device': comps[0], 'alt_device': _list.get(comps[1], None), 'fstype': comps[2], 'opts': _resolve_user_group_names(comps[3].split(','))} return ret def _active_mounts_aix(ret): ''' List active mounts on AIX systems ''' for line in __salt__['cmd.run_stdout']('mount -p').split('\n'): comps = re.sub(r"\s+", " ", line).split() if comps: if comps[0] == 'node' or comps[0] == '--------': continue comps_len = len(comps) if line.startswith((' ', '\t')): curr_opts = _resolve_user_group_names(comps[6].split(',')) if 7 == comps_len else [] if curr_opts: ret[comps[1]] = {'device': comps[0], 'fstype': comps[2], 'opts': curr_opts} else: ret[comps[1]] = {'device': comps[0], 'fstype': comps[2]} else: curr_opts = _resolve_user_group_names(comps[7].split(',')) if 8 == comps_len else [] if curr_opts: ret[comps[2]] = {'node': comps[0], 'device': comps[1], 'fstype': comps[3], 'opts': curr_opts} else: ret[comps[2]] = {'node': comps[0], 'device': comps[1], 'fstype': comps[3]} return ret def _active_mounts_solaris(ret): ''' List active mounts on Solaris systems ''' for line in __salt__['cmd.run_stdout']('mount -v').split('\n'): comps = re.sub(r"\s+", " ", line).split() ret[comps[2]] = {'device': comps[0], 'fstype': comps[4], 'opts': _resolve_user_group_names(comps[5].split('/'))} return ret def _active_mounts_openbsd(ret): ''' List active mounts on OpenBSD systems ''' for line in __salt__['cmd.run_stdout']('mount -v').split('\n'): comps = re.sub(r"\s+", " ", line).split() parens = re.findall(r'\((.*?)\)', line, re.DOTALL) if len(parens) > 1: nod = __salt__['cmd.run_stdout']('ls -l {0}'.format(comps[0])) nod = ' '.join(nod.split()).split(" ") ret[comps[3]] = {'device': comps[0], 'fstype': comps[5], 'opts': _resolve_user_group_names(parens[1].split(", ")), 'major': six.text_type(nod[4].strip(",")), 'minor': six.text_type(nod[5]), 'device_uuid': parens[0]} else: ret[comps[2]] = {'device': comps[0], 'fstype': comps[4], 'opts': _resolve_user_group_names(parens[0].split(", "))} return ret def _active_mounts_darwin(ret): ''' List active mounts on Mac OS systems ''' for line in __salt__['cmd.run_stdout']('mount').split('\n'): comps = re.sub(r"\s+", " ", line).split() parens = re.findall(r'\((.*?)\)', line, re.DOTALL)[0].split(", ") ret[comps[2]] = {'device': comps[0], 'fstype': parens[0], 'opts': _resolve_user_group_names(parens[1:])} return ret def _resolve_user_group_names(opts): ''' Resolve user and group names in related opts ''' name_id_opts = {'uid': 'user.info', 'gid': 'group.info'} for ind, opt in enumerate(opts): if opt.split('=')[0] in name_id_opts: _givenid = opt.split('=')[1] _param = opt.split('=')[0] _id = _givenid if not re.match('[0-9]+$', _givenid): _info = __salt__[name_id_opts[_param]](_givenid) if _info and _param in _info: _id = _info[_param] opts[ind] = _param + '=' + six.text_type(_id) opts[ind] = opts[ind].replace('\\040', '\\ ') return opts def active(extended=False): ''' List the active mounts. CLI Example: .. code-block:: bash salt '*' mount.active ''' ret = {} if __grains__['os'] == 'FreeBSD': _active_mounts_freebsd(ret) elif 'AIX' in __grains__['kernel']: _active_mounts_aix(ret) elif __grains__['kernel'] == 'SunOS': _active_mounts_solaris(ret) elif __grains__['os'] == 'OpenBSD': _active_mounts_openbsd(ret) elif __grains__['os'] in ['MacOS', 'Darwin']: _active_mounts_darwin(ret) else: if extended: try: _active_mountinfo(ret) except CommandExecutionError: _active_mounts(ret) else: _active_mounts(ret) return ret class _fstab_entry(object): ''' Utility class for manipulating fstab entries. Primarily we're parsing, formatting, and comparing lines. Parsing emits dicts expected from fstab() or raises a ValueError. Note: We'll probably want to use os.normpath and os.normcase on 'name' ''' class ParseError(ValueError): ''' Error raised when a line isn't parsible as an fstab entry ''' fstab_keys = ('device', 'name', 'fstype', 'opts', 'dump', 'pass_num') # preserve data format compatibility_keys = ('device', 'name', 'fstype', 'opts', 'dump', 'pass') fstab_format = '{device}\t\t{name}\t{fstype}\t{opts}\t{dump} {pass_num}\n' @classmethod def dict_from_line(cls, line, keys=fstab_keys): if len(keys) != 6: raise ValueError('Invalid key array: {0}'.format(keys)) if line.startswith('#'): raise cls.ParseError("Comment!") comps = line.split() if len(comps) < 4 or len(comps) > 6: raise cls.ParseError("Invalid Entry!") comps.extend(['0'] * (len(keys) - len(comps))) return dict(zip(keys, comps)) @classmethod def from_line(cls, *args, **kwargs): return cls(** cls.dict_from_line(*args, **kwargs)) @classmethod def dict_to_line(cls, entry): return cls.fstab_format.format(**entry) def __str__(self): ''' String value, only works for full repr ''' return self.dict_to_line(self.criteria) def __repr__(self): ''' Always works ''' return repr(self.criteria) def pick(self, keys): ''' Returns an instance with just those keys ''' subset = dict([(key, self.criteria[key]) for key in keys]) return self.__class__(**subset) def __init__(self, **criteria): ''' Store non-empty, non-null values to use as filter ''' items = [key_value for key_value in six.iteritems(criteria) if key_value[1] is not None] items = [(key_value1[0], six.text_type(key_value1[1])) for key_value1 in items] self.criteria = dict(items) @staticmethod def norm_path(path): ''' Resolve equivalent paths equivalently ''' return os.path.normcase(os.path.normpath(path)) def match(self, line): ''' Compare potentially partial criteria against line ''' entry = self.dict_from_line(line) for key, value in six.iteritems(self.criteria): if entry[key] != value: return False return True class _vfstab_entry(object): ''' Utility class for manipulating vfstab entries. Primarily we're parsing, formatting, and comparing lines. Parsing emits dicts expected from fstab() or raises a ValueError. Note: We'll probably want to use os.normpath and os.normcase on 'name' Note: This parses vfstab entries on Solaris like systems #device device mount FS fsck mount mount #to mount to fsck point type pass at boot options # /devices - /devices devfs - no - ''' class ParseError(ValueError): '''Error raised when a line isn't parsible as an fstab entry''' vfstab_keys = ('device', 'device_fsck', 'name', 'fstype', 'pass_fsck', 'mount_at_boot', 'opts') # NOTE: weird formatting to match default spacing on Solaris vfstab_format = '{device:<11} {device_fsck:<3} {name:<19} {fstype:<8} {pass_fsck:<3} {mount_at_boot:<6} {opts}\n' @classmethod def dict_from_line(cls, line): if line.startswith('#'): raise cls.ParseError("Comment!") comps = line.split() if len(comps) != 7: raise cls.ParseError("Invalid Entry!") return dict(zip(cls.vfstab_keys, comps)) @classmethod def from_line(cls, *args, **kwargs): return cls(** cls.dict_from_line(*args, **kwargs)) @classmethod def dict_to_line(cls, entry): return cls.vfstab_format.format(**entry) def __str__(self): ''' String value, only works for full repr ''' return self.dict_to_line(self.criteria) def __repr__(self): ''' Always works ''' return repr(self.criteria) def pick(self, keys): ''' Returns an instance with just those keys ''' subset = dict([(key, self.criteria[key]) for key in keys]) return self.__class__(**subset) def __init__(self, **criteria): ''' Store non-empty, non-null values to use as filter ''' items = [key_value for key_value in six.iteritems(criteria) if key_value[1] is not None] items = [(key_value1[0], six.text_type(key_value1[1])) for key_value1 in items] self.criteria = dict(items) @staticmethod def norm_path(path): ''' Resolve equivalent paths equivalently ''' return os.path.normcase(os.path.normpath(path)) def match(self, line): ''' Compare potentially partial criteria against line ''' entry = self.dict_from_line(line) for key, value in six.iteritems(self.criteria): if entry[key] != value: return False return True class _FileSystemsEntry(object): ''' Utility class for manipulating filesystem entries. Primarily we're parsing, formatting, and comparing lines. Parsing emits dicts expected from fstab() or raises a ValueError. Note: We'll probably want to use os.normpath and os.normcase on 'name' ''' class ParseError(ValueError): ''' Error raised when a line isn't parsible as an fstab entry ''' filesystems_keys = ('device', 'name', 'fstype', 'vfstype', 'opts', 'mount') # preserve data format of filesystems compatibility_keys = ('dev', 'dev', 'name', 'fstype', 'vfstype', 'opts', 'mount', 'type', 'vfs', 'account', 'boot', 'check', 'free', 'nodename', 'quota', 'size', 'vol', 'log') @classmethod def dict_from_lines(cls, lines, keys=filesystems_keys): if len(lines) < 2: raise ValueError('Invalid number of lines: {0}'.format(lines)) if not keys: # if empty force default filesystems_keys keys = _FileSystemsEntry.filesystems_keys elif len(keys) < 6: raise ValueError('Invalid key name array: {0}'.format(keys)) blk_lines = lines orddict = OrderedDict() orddict['name'] = blk_lines[0].split(':')[0].strip() blk_lines.pop(0) for line in blk_lines: if line.startswith('#'): raise cls.ParseError("Comment!") comps = line.split('= ') if len(comps) != 2: raise cls.ParseError("Invalid Entry!") key_name = comps[0].strip() if key_name in keys: orddict[key_name] = comps[1].strip() else: raise ValueError('Invalid name for use in filesystems: {0}'.format(key_name)) return orddict @classmethod def dict_from_cmd_line(cls, ipargs, keys): cmdln_dict = ipargs if keys: for key, value in keys: # ignore unknown or local scope keys if key.startswith('__'): continue if key in _FileSystemsEntry.compatibility_keys: cmdln_dict[key] = value return cmdln_dict @classmethod def from_line(cls, *args, **kwargs): return cls(** cls.dict_from_cmd_line(*args, **kwargs)) @classmethod def dict_to_lines(cls, fsys_dict_entry): entry = fsys_dict_entry strg_out = entry['name'] + ':' + os.linesep for k, v in six.viewitems(entry): if 'name' not in k: strg_out += '\t{0}\t\t= {1}'.format(k, v) + os.linesep strg_out += os.linesep return six.text_type(strg_out) def dict_from_entry(self): ret = OrderedDict() ret[self.criteria['name']] = self.criteria return ret def __str__(self): ''' String value, only works for full repr ''' return self.dict_to_lines(self.criteria) def __repr__(self): ''' Always works ''' return repr(self.criteria) def pick(self, keys): ''' Returns an instance with just those keys ''' subset = dict([(key, self.criteria[key]) for key in keys]) return self.__class__(**subset) def __init__(self, **criteria): ''' Store non-empty, non-null values to use as filter ''' items = [key_value for key_value in six.iteritems(criteria) if key_value[1] is not None] items = [(key_value1[0], six.text_type(key_value1[1])) for key_value1 in items] self.criteria = OrderedDict(items) @staticmethod def norm_path(path): ''' Resolve equivalent paths equivalently ''' return os.path.normcase(os.path.normpath(path)) def match(self, fsys_view): ''' Compare potentially partial criteria against built filesystems entry dictionary ''' evalue_dict = fsys_view[1] for key, value in six.viewitems(self.criteria): if key in evalue_dict: if evalue_dict[key] != value: return False else: return False return True def __getitem__(self, key): ''' Return value for input key ''' return self.criteria[key] def fstab(config='/etc/fstab'): ''' .. versionchanged:: 2016.3.2 List the contents of the fstab CLI Example: .. code-block:: bash salt '*' mount.fstab ''' ret = {} if not os.path.isfile(config): return ret with salt.utils.files.fopen(config) as ifile: for line in ifile: line = salt.utils.stringutils.to_unicode(line) try: if __grains__['kernel'] == 'SunOS': # Note: comments use in default vfstab file! if line[0] == '#': continue entry = _vfstab_entry.dict_from_line( line) else: entry = _fstab_entry.dict_from_line( line, _fstab_entry.compatibility_keys) entry['opts'] = entry['opts'].split(',') while entry['name'] in ret: entry['name'] += '_' ret[entry.pop('name')] = entry except _fstab_entry.ParseError: pass except _vfstab_entry.ParseError: pass return ret def vfstab(config='/etc/vfstab'): ''' .. versionadded:: 2016.3.2 List the contents of the vfstab CLI Example: .. code-block:: bash salt '*' mount.vfstab ''' # NOTE: vfstab is a wrapper for fstab return fstab(config) def rm_fstab(name, device, config='/etc/fstab'): ''' .. versionchanged:: 2016.3.2 Remove the mount point from the fstab CLI Example: .. code-block:: bash salt '*' mount.rm_fstab /mnt/foo /dev/sdg ''' modified = False if __grains__['kernel'] == 'SunOS': criteria = _vfstab_entry(name=name, device=device) else: criteria = _fstab_entry(name=name, device=device) lines = [] try: with salt.utils.files.fopen(config, 'r') as ifile: for line in ifile: line = salt.utils.stringutils.to_unicode(line) try: if criteria.match(line): modified = True else: lines.append(line) except _fstab_entry.ParseError: lines.append(line) except _vfstab_entry.ParseError: lines.append(line) except (IOError, OSError) as exc: msg = "Couldn't read from {0}: {1}" raise CommandExecutionError(msg.format(config, exc)) if modified: try: with salt.utils.files.fopen(config, 'wb') as ofile: ofile.writelines(salt.utils.data.encode(lines)) except (IOError, OSError) as exc: msg = "Couldn't write to {0}: {1}" raise CommandExecutionError(msg.format(config, exc)) # Note: not clear why we always return 'True' # --just copying previous behavior at this point... return True def rm_vfstab(name, device, config='/etc/vfstab'): ''' .. versionadded:: 2016.3.2 Remove the mount point from the vfstab CLI Example: .. code-block:: bash salt '*' mount.rm_vfstab /mnt/foo /device/c0t0d0p0 ''' ## NOTE: rm_vfstab is a wrapper for rm_fstab return rm_fstab(name, device, config) def set_fstab( name, device, fstype, opts='defaults', dump=0, pass_num=0, config='/etc/fstab', test=False, match_on='auto', **kwargs): ''' Verify that this mount is represented in the fstab, change the mount to match the data passed, or add the mount if it is not present. CLI Example: .. code-block:: bash salt '*' mount.set_fstab /mnt/foo /dev/sdz1 ext4 ''' # Fix the opts type if it is a list if isinstance(opts, list): opts = ','.join(opts) # preserve arguments for updating entry_args = { 'name': name, 'device': device.replace('\\ ', '\\040'), 'fstype': fstype, 'opts': opts.replace('\\ ', '\\040'), 'dump': dump, 'pass_num': pass_num, } lines = [] ret = None # Transform match_on into list--items will be checked later if isinstance(match_on, list): pass elif not isinstance(match_on, six.string_types): msg = 'match_on must be a string or list of strings' raise CommandExecutionError(msg) elif match_on == 'auto': # Try to guess right criteria for auto.... # NOTE: missing some special fstypes here specialFSes = frozenset([ 'none', 'tmpfs', 'sysfs', 'proc', 'fusectl', 'debugfs', 'securityfs', 'devtmpfs', 'cgroup', 'btrfs']) if fstype in specialFSes: match_on = ['name'] else: match_on = ['device'] else: match_on = [match_on] # generate entry and criteria objects, handle invalid keys in match_on entry = _fstab_entry(**entry_args) try: criteria = entry.pick(match_on) except KeyError: filterFn = lambda key: key not in _fstab_entry.fstab_keys invalid_keys = filter(filterFn, match_on) msg = 'Unrecognized keys in match_on: "{0}"'.format(invalid_keys) raise CommandExecutionError(msg) # parse file, use ret to cache status if not os.path.isfile(config): raise CommandExecutionError('Bad config file "{0}"'.format(config)) try: with salt.utils.files.fopen(config, 'r') as ifile: for line in ifile: line = salt.utils.stringutils.to_unicode(line) try: if criteria.match(line): # Note: If ret isn't None here, # we've matched multiple lines ret = 'present' if entry.match(line): lines.append(line) else: ret = 'change' lines.append(six.text_type(entry)) else: lines.append(line) except _fstab_entry.ParseError: lines.append(line) except (IOError, OSError) as exc: msg = 'Couldn\'t read from {0}: {1}' raise CommandExecutionError(msg.format(config, exc)) # add line if not present or changed if ret is None: lines.append(six.text_type(entry)) ret = 'new' if ret != 'present': # ret in ['new', 'change']: if not salt.utils.args.test_mode(test=test, **kwargs): try: with salt.utils.files.fopen(config, 'wb') as ofile: # The line was changed, commit it! ofile.writelines(salt.utils.data.encode(lines)) except (IOError, OSError): msg = 'File not writable {0}' raise CommandExecutionError(msg.format(config)) return ret def set_vfstab( name, device, fstype, opts='-', device_fsck='-', pass_fsck='-', mount_at_boot='yes', config='/etc/vfstab', test=False, match_on='auto', **kwargs): ''' ..verionadded:: 2016.3.2 Verify that this mount is represented in the fstab, change the mount to match the data passed, or add the mount if it is not present. CLI Example: .. code-block:: bash salt '*' mount.set_vfstab /mnt/foo /device/c0t0d0p0 ufs ''' # Fix the opts type if it is a list if isinstance(opts, list): opts = ','.join(opts) # Map unknown values for mount_at_boot to no if mount_at_boot != 'yes': mount_at_boot = 'no' # preserve arguments for updating entry_args = { 'name': name, 'device': device, 'fstype': fstype, 'opts': opts, 'device_fsck': device_fsck, 'pass_fsck': pass_fsck, 'mount_at_boot': mount_at_boot, } lines = [] ret = None # Transform match_on into list--items will be checked later if isinstance(match_on, list): pass elif not isinstance(match_on, six.string_types): msg = 'match_on must be a string or list of strings' raise CommandExecutionError(msg) elif match_on == 'auto': # Try to guess right criteria for auto.... # NOTE: missing some special fstypes here specialFSes = frozenset([ 'devfs', 'proc', 'ctfs', 'objfs', 'sharefs', 'fs', 'tmpfs']) if fstype in specialFSes: match_on = ['name'] else: match_on = ['device'] else: match_on = [match_on] # generate entry and criteria objects, handle invalid keys in match_on entry = _vfstab_entry(**entry_args) try: criteria = entry.pick(match_on) except KeyError: filterFn = lambda key: key not in _vfstab_entry.vfstab_keys invalid_keys = filter(filterFn, match_on) msg = 'Unrecognized keys in match_on: "{0}"'.format(invalid_keys) raise CommandExecutionError(msg) # parse file, use ret to cache status if not os.path.isfile(config): raise CommandExecutionError('Bad config file "{0}"'.format(config)) try: with salt.utils.files.fopen(config, 'r') as ifile: for line in ifile: line = salt.utils.stringutils.to_unicode(line) try: if criteria.match(line): # Note: If ret isn't None here, # we've matched multiple lines ret = 'present' if entry.match(line): lines.append(line) else: ret = 'change' lines.append(six.text_type(entry)) else: lines.append(line) except _vfstab_entry.ParseError: lines.append(line) except (IOError, OSError) as exc: msg = 'Couldn\'t read from {0}: {1}' raise CommandExecutionError(msg.format(config, exc)) # add line if not present or changed if ret is None: lines.append(six.text_type(entry)) ret = 'new' if ret != 'present': # ret in ['new', 'change']: if not salt.utils.args.test_mode(test=test, **kwargs): try: with salt.utils.files.fopen(config, 'wb') as ofile: # The line was changed, commit it! ofile.writelines(salt.utils.data.encode(lines)) except (IOError, OSError): msg = 'File not writable {0}' raise CommandExecutionError(msg.format(config)) return ret def rm_automaster(name, device, config='/etc/auto_salt'): ''' Remove the mount point from the auto_master CLI Example: .. code-block:: bash salt '*' mount.rm_automaster /mnt/foo /dev/sdg ''' contents = automaster(config) if name not in contents: return True # The entry is present, get rid of it lines = [] try: with salt.utils.files.fopen(config, 'r') as ifile: for line in ifile: line = salt.utils.stringutils.to_unicode(line) if line.startswith('#'): # Commented lines.append(line) continue if not line.strip(): # Blank line lines.append(line) continue comps = line.split() if len(comps) != 3: # Invalid entry lines.append(line) continue comps = line.split() prefix = "/.." name_chk = comps[0].replace(prefix, "") device_fmt = comps[2].split(":") if device: if name_chk == name and device_fmt[1] == device: continue else: if name_chk == name: continue lines.append(line) except (IOError, OSError) as exc: msg = "Couldn't read from {0}: {1}" raise CommandExecutionError(msg.format(config, exc)) try: with salt.utils.files.fopen(config, 'wb') as ofile: ofile.writelines(salt.utils.data.encode(lines)) except (IOError, OSError) as exc: msg = "Couldn't write to {0}: {1}" raise CommandExecutionError(msg.format(config, exc)) # Update automount __salt__['cmd.run']('automount -cv') return True def set_automaster( name, device, fstype, opts='', config='/etc/auto_salt', test=False, **kwargs): ''' Verify that this mount is represented in the auto_salt, change the mount to match the data passed, or add the mount if it is not present. CLI Example: .. code-block:: bash salt '*' mount.set_automaster /mnt/foo /dev/sdz1 ext4 ''' # Fix the opts type if it is a list if isinstance(opts, list): opts = ','.join(opts) lines = [] change = False present = False automaster_file = "/etc/auto_master" if not os.path.isfile(config): __salt__['file.touch'](config) __salt__['file.append'](automaster_file, "/-\t\t\t{0}".format(config)) name = "/..{0}".format(name) device_fmt = "{0}:{1}".format(fstype, device) type_opts = "-fstype={0},{1}".format(fstype, opts) if fstype == 'smbfs': device_fmt = device_fmt.replace(fstype, "") try: with salt.utils.files.fopen(config, 'r') as ifile: for line in ifile: line = salt.utils.stringutils.to_unicode(line) if line.startswith('#'): # Commented lines.append(line) continue if not line.strip(): # Blank line lines.append(line) continue comps = line.split() if len(comps) != 3: # Invalid entry lines.append(line) continue if comps[0] == name or comps[2] == device_fmt: # check to see if there are changes # and fix them if there are any present = True if comps[0] != name: change = True comps[0] = name if comps[1] != type_opts: change = True comps[1] = type_opts if comps[2] != device_fmt: change = True comps[2] = device_fmt if change: log.debug( 'auto_master entry for mount point %s needs to be ' 'updated', name ) newline = ( '{0}\t{1}\t{2}\n'.format( name, type_opts, device_fmt) ) lines.append(newline) else: lines.append(line) except (IOError, OSError) as exc: msg = 'Couldn\'t read from {0}: {1}' raise CommandExecutionError(msg.format(config, exc)) if change: if not salt.utils.args.test_mode(test=test, **kwargs): try: with salt.utils.files.fopen(config, 'wb') as ofile: # The line was changed, commit it! ofile.writelines(salt.utils.data.encode(lines)) except (IOError, OSError): msg = 'File not writable {0}' raise CommandExecutionError(msg.format(config)) return 'change' if not change: if present: # The right entry is already here return 'present' else: if not salt.utils.args.test_mode(test=test, **kwargs): # The entry is new, add it to the end of the fstab newline = ( '{0}\t{1}\t{2}\n'.format( name, type_opts, device_fmt) ) lines.append(newline) try: with salt.utils.files.fopen(config, 'wb') as ofile: # The line was changed, commit it! ofile.writelines(salt.utils.data.encode(lines)) except (IOError, OSError): raise CommandExecutionError( 'File not writable {0}'.format( config ) ) return 'new' def automaster(config='/etc/auto_salt'): ''' List the contents of the auto master CLI Example: .. code-block:: bash salt '*' mount.automaster ''' ret = {} if not os.path.isfile(config): return ret with salt.utils.files.fopen(config) as ifile: for line in ifile: line = salt.utils.stringutils.to_unicode(line) if line.startswith('#'): # Commented continue if not line.strip(): # Blank line continue comps = line.split() if len(comps) != 3: # Invalid entry continue prefix = "/.." name = comps[0].replace(prefix, "") device_fmt = comps[2].split(":") opts = comps[1].split(',') ret[name] = {'device': device_fmt[1], 'fstype': opts[0], 'opts': opts[1:]} return ret def mount(name, device, mkmnt=False, fstype='', opts='defaults', user=None, util='mount'): ''' Mount a device CLI Example: .. code-block:: bash salt '*' mount.mount /mnt/foo /dev/sdz1 True ''' if util != 'mount': # This functionality used to live in img.mount_image if util == 'guestfs': return __salt__['guestfs.mount'](name, root=device) elif util == 'qemu_nbd': mnt = __salt__['qemu_nbd.init'](name, device) if not mnt: return False first = next(six.iterkeys(mnt)) __context__['img.mnt_{0}'.format(first)] = mnt return first return False # Darwin doesn't expect defaults when mounting without other options if 'defaults' in opts and __grains__['os'] in ['MacOS', 'Darwin', 'AIX']: opts = None if isinstance(opts, six.string_types): opts = opts.split(',') if not os.path.exists(name) and mkmnt: __salt__['file.mkdir'](name, user=user) args = '' if opts is not None: lopts = ','.join(opts) args = '-o {0}'.format(lopts) if fstype: # use of fstype on AIX differs from typical Linux use of -t # functionality AIX uses -v vfsname, -t fstype mounts all with # fstype in /etc/filesystems if 'AIX' in __grains__['os']: args += ' -v {0}'.format(fstype) elif 'solaris' in __grains__['os'].lower(): args += ' -F {0}'.format(fstype) else: args += ' -t {0}'.format(fstype) cmd = 'mount {0} {1} {2} '.format(args, device, name) out = __salt__['cmd.run_all'](cmd, runas=user, python_shell=False) if out['retcode']: return out['stderr'] return True def remount(name, device, mkmnt=False, fstype='', opts='defaults', user=None): ''' Attempt to remount a device, if the device is not already mounted, mount is called CLI Example: .. code-block:: bash salt '*' mount.remount /mnt/foo /dev/sdz1 True ''' force_mount = False if __grains__['os'] in ['MacOS', 'Darwin']: if opts == 'defaults': opts = 'noowners' if fstype == 'smbfs': force_mount = True if 'AIX' in __grains__['os']: if opts == 'defaults': opts = [] if isinstance(opts, six.string_types): opts = opts.split(',') mnts = active() if name in mnts: # The mount point is mounted, attempt to remount it with the given data if 'remount' not in opts and __grains__['os'] not in ['OpenBSD', 'MacOS', 'Darwin']: opts.append('remount') if force_mount: # We need to force the mount but first we should unmount umount(name, device, user=user) lopts = ','.join(opts) args = '-o {0}'.format(lopts) if fstype: # use of fstype on AIX differs from typical Linux use of # -t functionality AIX uses -v vfsname, -t fstype mounts # all with fstype in /etc/filesystems if 'AIX' in __grains__['os']: args += ' -v {0}'.format(fstype) elif 'solaris' in __grains__['os'].lower(): args += ' -F {0}'.format(fstype) else: args += ' -t {0}'.format(fstype) if __grains__['os'] not in ['OpenBSD', 'MacOS', 'Darwin'] or force_mount: cmd = 'mount {0} {1} {2} '.format(args, device, name) else: cmd = 'mount -u {0} {1} {2} '.format(args, device, name) out = __salt__['cmd.run_all'](cmd, runas=user, python_shell=False) if out['retcode']: return out['stderr'] return True # Mount a filesystem that isn't already return mount(name, device, mkmnt, fstype, opts, user=user) def umount(name, device=None, user=None, util='mount'): ''' Attempt to unmount a device by specifying the directory it is mounted on CLI Example: .. code-block:: bash salt '*' mount.umount /mnt/foo .. versionadded:: 2015.5.0 .. code-block:: bash salt '*' mount.umount /mnt/foo /dev/xvdc1 ''' if util != 'mount': # This functionality used to live in img.umount_image if 'qemu_nbd.clear' in __salt__: if 'img.mnt_{0}'.format(name) in __context__: __salt__['qemu_nbd.clear'](__context__['img.mnt_{0}'.format(name)]) return mnts = active() if name not in mnts: return "{0} does not have anything mounted".format(name) if not device: cmd = 'umount {0}'.format(name) else: cmd = 'umount {0}'.format(device) out = __salt__['cmd.run_all'](cmd, runas=user, python_shell=False) if out['retcode']: return out['stderr'] return True def is_fuse_exec(cmd): ''' Returns true if the command passed is a fuse mountable application. CLI Example: .. code-block:: bash salt '*' mount.is_fuse_exec sshfs ''' cmd_path = salt.utils.path.which(cmd) # No point in running ldd on a command that doesn't exist if not cmd_path: return False elif not salt.utils.path.which('ldd'): raise CommandNotFoundError('ldd') out = __salt__['cmd.run']('ldd {0}'.format(cmd_path), python_shell=False) return 'libfuse' in out def swaps(): ''' Return a dict containing information on active swap .. versionchanged:: 2016.3.2 CLI Example: .. code-block:: bash salt '*' mount.swaps ''' ret = {} if __grains__['kernel'] == 'SunOS': for line in __salt__['cmd.run_stdout']('swap -l').splitlines(): if line.startswith('swapfile'): continue comps = line.split() ret[comps[0]] = {'type': 'device' if comps[0].startswith(('/dev', 'swap')) else 'file', 'size': int(comps[3]), 'used': (int(comps[3]) - int(comps[4])), 'priority': '-'} elif 'AIX' in __grains__['kernel']: for line in __salt__['cmd.run_stdout']('swap -l').splitlines(): if line.startswith('device'): continue comps = line.split() # AIX uses MB for units ret[comps[0]] = {'type': 'device', 'size': int(comps[3][:-2]) * 1024, 'used': (int(comps[3][:-2]) - int(comps[4][:-2])) * 1024, 'priority': '-'} elif __grains__['os'] != 'OpenBSD': with salt.utils.files.fopen('/proc/swaps') as fp_: for line in fp_: line = salt.utils.stringutils.to_unicode(line) if line.startswith('Filename'): continue comps = line.split() ret[comps[0]] = {'type': comps[1], 'size': comps[2], 'used': comps[3], 'priority': comps[4]} else: for line in __salt__['cmd.run_stdout']('swapctl -kl').splitlines(): if line.startswith(('Device', 'Total')): continue swap_type = "file" comps = line.split() if comps[0].startswith('/dev/'): swap_type = "partition" ret[comps[0]] = {'type': swap_type, 'size': comps[1], 'used': comps[2], 'priority': comps[5]} return ret def swapon(name, priority=None): ''' Activate a swap disk .. versionchanged:: 2016.3.2 CLI Example: .. code-block:: bash salt '*' mount.swapon /root/swapfile ''' ret = {} on_ = swaps() if name in on_: ret['stats'] = on_[name] ret['new'] = False return ret if __grains__['kernel'] == 'SunOS': if __grains__['virtual'] != 'zone': __salt__['cmd.run']('swap -a {0}'.format(name), python_shell=False) else: return False else: cmd = 'swapon {0}'.format(name) if priority and 'AIX' not in __grains__['kernel']: cmd += ' -p {0}'.format(priority) __salt__['cmd.run'](cmd, python_shell=False) on_ = swaps() if name in on_: ret['stats'] = on_[name] ret['new'] = True return ret return ret def swapoff(name): ''' Deactivate a named swap mount .. versionchanged:: 2016.3.2 CLI Example: .. code-block:: bash salt '*' mount.swapoff /root/swapfile ''' on_ = swaps() if name in on_: if __grains__['kernel'] == 'SunOS': if __grains__['virtual'] != 'zone': __salt__['cmd.run']('swap -a {0}'.format(name), python_shell=False) else: return False elif __grains__['os'] != 'OpenBSD': __salt__['cmd.run']('swapoff {0}'.format(name), python_shell=False) else: __salt__['cmd.run']('swapctl -d {0}'.format(name), python_shell=False) on_ = swaps() if name in on_: return False return True return None def is_mounted(name): ''' .. versionadded:: 2014.7.0 Provide information if the path is mounted CLI Example: .. code-block:: bash salt '*' mount.is_mounted /mnt/share ''' active_ = active() if name in active_: return True else: return False def read_mount_cache(name): ''' .. versionadded:: 2018.3.0 Provide information if the path is mounted CLI Example: .. code-block:: bash salt '*' mount.read_mount_cache /mnt/share ''' cache = salt.utils.mount.read_cache(__opts__) if cache: if 'mounts' in cache and cache['mounts']: if name in cache['mounts']: return cache['mounts'][name] return {} def write_mount_cache(real_name, device, mkmnt, fstype, mount_opts): ''' .. versionadded:: 2018.3.0 Provide information if the path is mounted :param real_name: The real name of the mount point where the device is mounted. :param device: The device that is being mounted. :param mkmnt: Whether or not the mount point should be created. :param fstype: The file system that is used. :param mount_opts: Additional options used when mounting the device. :return: Boolean if message was sent successfully. CLI Example: .. code-block:: bash salt '*' mount.write_mount_cache /mnt/share /dev/sda1 False ext4 defaults,nosuid ''' cache = salt.utils.mount.read_cache(__opts__) if not cache: cache = {} cache['mounts'] = {} else: if 'mounts' not in cache: cache['mounts'] = {} cache['mounts'][real_name] = {'device': device, 'fstype': fstype, 'mkmnt': mkmnt, 'opts': mount_opts} cache_write = salt.utils.mount.write_cache(cache, __opts__) if cache_write: return True else: raise CommandExecutionError('Unable to write mount cache.') def delete_mount_cache(real_name): ''' .. versionadded:: 2018.3.0 Provide information if the path is mounted CLI Example: .. code-block:: bash salt '*' mount.delete_mount_cache /mnt/share ''' cache = salt.utils.mount.read_cache(__opts__) if cache: if 'mounts' in cache: if real_name in cache['mounts']: del cache['mounts'][real_name] cache_write = salt.utils.mount.write_cache(cache, __opts__) if not cache_write: raise CommandExecutionError('Unable to write mount cache.') return True def _filesystems(config='/etc/filesystems', leading_key=True): ''' Return the contents of the filesystems in an OrderedDict config File containing filesystem infomation leading_key True return dictionary keyed by 'name' and value as dictionary with other keys, values (name excluded) OrderedDict({ '/dir' : OrderedDict({'dev': '/dev/hd8', .... }})) False return dictionary keyed by 'name' and value as dictionary with all keys, values (name included) OrderedDict({ '/dir' : OrderedDict({'name': '/dir', 'dev': '/dev/hd8', ... })}) ''' ret = OrderedDict() lines = [] parsing_block = False if not os.path.isfile(config) or 'AIX' not in __grains__['kernel']: return ret # read in block of filesystems, block starts with '/' till empty line with salt.utils.files.fopen(config) as ifile: for line in ifile: line = salt.utils.stringutils.to_unicode(line) # skip till first entry if not line.startswith('/') and not parsing_block: continue if line.startswith('/'): parsing_block = True lines.append(line) elif not line.split(): parsing_block = False try: entry = _FileSystemsEntry.dict_from_lines( lines, _FileSystemsEntry.compatibility_keys) lines = [] if 'opts' in entry: entry['opts'] = entry['opts'].split(',') while entry['name'] in ret: entry['name'] += '_' if leading_key: ret[entry.pop('name')] = entry else: ret[entry['name']] = entry except _FileSystemsEntry.ParseError: pass else: lines.append(line) return ret def filesystems(config='/etc/filesystems'): ''' .. versionadded:: 2018.3.3 List the contents of the filesystems CLI Example: .. code-block:: bash salt '*' mount.filesystems ''' ret = {} if 'AIX' not in __grains__['kernel']: return ret ret_dict = _filesystems(config) if ret_dict: ret_key = next(iter(ret_dict.keys())) ret = {ret_key: dict(ret_dict[ret_key])} return ret def set_filesystems( name, device, vfstype, opts='-', mount='true', config='/etc/filesystems', test=False, match_on='auto', **kwargs): ''' .. versionadded:: 2018.3.3 Verify that this mount is represented in the filesystems, change the mount to match the data passed, or add the mount if it is not present on AIX Provide information if the path is mounted :param name: The name of the mount point where the device is mounted. :param device: The device that is being mounted. :param vfstype: The file system that is used (AIX has two fstypes, fstype and vfstype - similar to Linux fstype) :param opts: Additional options used when mounting the device. :param mount: Mount if not mounted, default True. :param config: Configuration file, default /etc/filesystems. :param match: File systems type to match on, default auto CLI Example: .. code-block:: bash salt '*' mount.set_filesystems /mnt/foo /dev/sdz1 jfs2 ''' # Fix the opts type if it is a list if isinstance(opts, list): opts = ','.join(opts) # preserve arguments for updating entry_args = { 'name': name, 'dev': device.replace('\\ ', '\\040'), 'vfstype': vfstype, 'opts': opts, 'mount': mount, } view_lines = [] ret = None if 'AIX' not in __grains__['kernel']: return ret # Transform match_on into list--items will be checked later if isinstance(match_on, list): pass elif not isinstance(match_on, six.string_types): raise CommandExecutionError('match_on must be a string or list of strings') elif match_on == 'auto': # Try to guess right criteria for auto.... # added IBM types from sys/vmount.h after btrfs # NOTE: missing some special fstypes here specialFSes = frozenset([ 'none', 'tmpfs', 'sysfs', 'proc', 'fusectl', 'debugfs', 'securityfs', 'devtmpfs', 'cgroup', 'btrfs', 'cdrfs', 'procfs', 'jfs', 'jfs2', 'nfs', 'sfs', 'nfs3', 'cachefs', 'udfs', 'cifs', 'namefs', 'pmemfs', 'ahafs', 'nfs4', 'autofs', 'stnfs']) if vfstype in specialFSes: match_on = ['name'] else: match_on = ['dev'] else: match_on = [match_on] # generate entry and criteria objects, handle invalid keys in match_on entry_ip = _FileSystemsEntry.from_line(entry_args, kwargs) try: criteria = entry_ip.pick(match_on) except KeyError: filterFn = lambda key: key not in _FileSystemsEntry.compatibility_keys invalid_keys = filter(filterFn, match_on) raise CommandExecutionError('Unrecognized keys in match_on: "{0}"'.format(invalid_keys)) # parse file, use ret to cache status if not os.path.isfile(config): raise CommandExecutionError('Bad config file "{0}"'.format(config)) # read in block of filesystem, block starts with '/' till empty line try: fsys_filedict = _filesystems(config, False) for fsys_view in six.viewitems(fsys_filedict): if criteria.match(fsys_view): ret = 'present' if entry_ip.match(fsys_view): view_lines.append(fsys_view) else: ret = 'change' kv = entry_ip['name'] view_lines.append((kv, entry_ip)) else: view_lines.append(fsys_view) except (IOError, OSError) as exc: raise CommandExecutionError('Couldn\'t read from {0}: {1}'.format(config, exc)) # add line if not present or changed if ret is None: for dict_view in six.viewitems(entry_ip.dict_from_entry()): view_lines.append(dict_view) ret = 'new' if ret != 'present': # ret in ['new', 'change']: try: with salt.utils.files.fopen(config, 'wb') as ofile: # The line was changed, commit it! for fsys_view in view_lines: entry = fsys_view[1] mystrg = _FileSystemsEntry.dict_to_lines(entry) ofile.writelines(salt.utils.data.encode(mystrg)) except (IOError, OSError): raise CommandExecutionError('File not writable {0}'.format(config)) return ret def rm_filesystems(name, device, config='/etc/filesystems'): ''' .. versionadded:: 2018.3.3 Remove the mount point from the filesystems CLI Example: .. code-block:: bash salt '*' mount.rm_filesystems /mnt/foo /dev/sdg ''' modified = False view_lines = [] if 'AIX' not in __grains__['kernel']: return modified criteria = _FileSystemsEntry(name=name, dev=device) try: fsys_filedict = _filesystems(config, False) for fsys_view in six.viewitems(fsys_filedict): try: if criteria.match(fsys_view): modified = True else: view_lines.append(fsys_view) except _FileSystemsEntry.ParseError: view_lines.append(fsys_view) except (IOError, OSError) as exc: raise CommandExecutionError("Couldn't read from {0}: {1}".format(config, exc)) if modified: try: with salt.utils.files.fopen(config, 'wb') as ofile: for fsys_view in view_lines: entry = fsys_view[1] mystrg = _FileSystemsEntry.dict_to_lines(entry) ofile.writelines(salt.utils.data.encode(mystrg)) except (IOError, OSError) as exc: raise CommandExecutionError("Couldn't write to {0}: {1}".format(config, exc)) return modified
saltstack/salt
salt/modules/mount.py
_active_mounts_openbsd
python
def _active_mounts_openbsd(ret): ''' List active mounts on OpenBSD systems ''' for line in __salt__['cmd.run_stdout']('mount -v').split('\n'): comps = re.sub(r"\s+", " ", line).split() parens = re.findall(r'\((.*?)\)', line, re.DOTALL) if len(parens) > 1: nod = __salt__['cmd.run_stdout']('ls -l {0}'.format(comps[0])) nod = ' '.join(nod.split()).split(" ") ret[comps[3]] = {'device': comps[0], 'fstype': comps[5], 'opts': _resolve_user_group_names(parens[1].split(", ")), 'major': six.text_type(nod[4].strip(",")), 'minor': six.text_type(nod[5]), 'device_uuid': parens[0]} else: ret[comps[2]] = {'device': comps[0], 'fstype': comps[4], 'opts': _resolve_user_group_names(parens[0].split(", "))} return ret
List active mounts on OpenBSD systems
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/mount.py#L179-L199
[ "def _resolve_user_group_names(opts):\n '''\n Resolve user and group names in related opts\n '''\n name_id_opts = {'uid': 'user.info',\n 'gid': 'group.info'}\n for ind, opt in enumerate(opts):\n if opt.split('=')[0] in name_id_opts:\n _givenid = opt.split('=')[1]\n _param = opt.split('=')[0]\n _id = _givenid\n if not re.match('[0-9]+$', _givenid):\n _info = __salt__[name_id_opts[_param]](_givenid)\n if _info and _param in _info:\n _id = _info[_param]\n opts[ind] = _param + '=' + six.text_type(_id)\n opts[ind] = opts[ind].replace('\\\\040', '\\\\ ')\n return opts\n" ]
# -*- coding: utf-8 -*- ''' Salt module to manage Unix mounts and the fstab file ''' # Import python libs from __future__ import absolute_import, print_function, unicode_literals import os import re import logging # Import salt libs import salt.utils.args import salt.utils.data import salt.utils.files import salt.utils.path import salt.utils.platform import salt.utils.mount import salt.utils.stringutils from salt.utils.odict import OrderedDict from salt.exceptions import CommandNotFoundError, CommandExecutionError # Import 3rd-party libs from salt.ext import six from salt.ext.six.moves import filter, zip # pylint: disable=import-error,redefined-builtin # Set up logger log = logging.getLogger(__name__) # Define the module's virtual name __virtualname__ = 'mount' def __virtual__(): ''' Only load on POSIX-like systems ''' # Disable on Windows, a specific file module exists: if salt.utils.platform.is_windows(): return (False, 'The mount module cannot be loaded: not a POSIX-like system.') return True def _list_mounts(): ret = {} if __grains__['os'] in ['MacOS', 'Darwin']: mounts = __salt__['cmd.run_stdout']('mount') else: mounts = __salt__['cmd.run_stdout']('mount -l') for line in mounts.split('\n'): comps = re.sub(r"\s+", " ", line).split() if len(comps) >= 3: ret[comps[2]] = comps[0] return ret def _active_mountinfo(ret): _list = _list_mounts() filename = '/proc/self/mountinfo' if not os.access(filename, os.R_OK): msg = 'File not readable {0}' raise CommandExecutionError(msg.format(filename)) if 'disk.blkid' not in __context__: __context__['disk.blkid'] = __salt__['disk.blkid']() blkid_info = __context__['disk.blkid'] with salt.utils.files.fopen(filename) as ifile: for line in ifile: comps = salt.utils.stringutils.to_unicode(line).split() device = comps[2].split(':') # each line can have any number of # optional parameters, we use the # location of the separator field to # determine the location of the elements # after it. _sep = comps.index('-') device_name = comps[_sep + 2] device_uuid = None device_label = None if device_name: device_uuid = blkid_info.get(device_name, {}).get('UUID') device_uuid = device_uuid and device_uuid.lower() device_label = blkid_info.get(device_name, {}).get('LABEL') ret[comps[4]] = {'mountid': comps[0], 'parentid': comps[1], 'major': device[0], 'minor': device[1], 'root': comps[3], 'opts': _resolve_user_group_names(comps[5].split(',')), 'fstype': comps[_sep + 1], 'device': device_name.replace('\\040', '\\ '), 'alt_device': _list.get(comps[4], None), 'superopts': _resolve_user_group_names(comps[_sep + 3].split(',')), 'device_uuid': device_uuid, 'device_label': device_label} return ret def _active_mounts(ret): ''' List active mounts on Linux systems ''' _list = _list_mounts() filename = '/proc/self/mounts' if not os.access(filename, os.R_OK): msg = 'File not readable {0}' raise CommandExecutionError(msg.format(filename)) with salt.utils.files.fopen(filename) as ifile: for line in ifile: comps = salt.utils.stringutils.to_unicode(line).split() ret[comps[1]] = {'device': comps[0], 'alt_device': _list.get(comps[1], None), 'fstype': comps[2], 'opts': _resolve_user_group_names(comps[3].split(','))} return ret def _active_mounts_aix(ret): ''' List active mounts on AIX systems ''' for line in __salt__['cmd.run_stdout']('mount -p').split('\n'): comps = re.sub(r"\s+", " ", line).split() if comps: if comps[0] == 'node' or comps[0] == '--------': continue comps_len = len(comps) if line.startswith((' ', '\t')): curr_opts = _resolve_user_group_names(comps[6].split(',')) if 7 == comps_len else [] if curr_opts: ret[comps[1]] = {'device': comps[0], 'fstype': comps[2], 'opts': curr_opts} else: ret[comps[1]] = {'device': comps[0], 'fstype': comps[2]} else: curr_opts = _resolve_user_group_names(comps[7].split(',')) if 8 == comps_len else [] if curr_opts: ret[comps[2]] = {'node': comps[0], 'device': comps[1], 'fstype': comps[3], 'opts': curr_opts} else: ret[comps[2]] = {'node': comps[0], 'device': comps[1], 'fstype': comps[3]} return ret def _active_mounts_freebsd(ret): ''' List active mounts on FreeBSD systems ''' for line in __salt__['cmd.run_stdout']('mount -p').split('\n'): comps = re.sub(r"\s+", " ", line).split() ret[comps[1]] = {'device': comps[0], 'fstype': comps[2], 'opts': _resolve_user_group_names(comps[3].split(','))} return ret def _active_mounts_solaris(ret): ''' List active mounts on Solaris systems ''' for line in __salt__['cmd.run_stdout']('mount -v').split('\n'): comps = re.sub(r"\s+", " ", line).split() ret[comps[2]] = {'device': comps[0], 'fstype': comps[4], 'opts': _resolve_user_group_names(comps[5].split('/'))} return ret def _active_mounts_darwin(ret): ''' List active mounts on Mac OS systems ''' for line in __salt__['cmd.run_stdout']('mount').split('\n'): comps = re.sub(r"\s+", " ", line).split() parens = re.findall(r'\((.*?)\)', line, re.DOTALL)[0].split(", ") ret[comps[2]] = {'device': comps[0], 'fstype': parens[0], 'opts': _resolve_user_group_names(parens[1:])} return ret def _resolve_user_group_names(opts): ''' Resolve user and group names in related opts ''' name_id_opts = {'uid': 'user.info', 'gid': 'group.info'} for ind, opt in enumerate(opts): if opt.split('=')[0] in name_id_opts: _givenid = opt.split('=')[1] _param = opt.split('=')[0] _id = _givenid if not re.match('[0-9]+$', _givenid): _info = __salt__[name_id_opts[_param]](_givenid) if _info and _param in _info: _id = _info[_param] opts[ind] = _param + '=' + six.text_type(_id) opts[ind] = opts[ind].replace('\\040', '\\ ') return opts def active(extended=False): ''' List the active mounts. CLI Example: .. code-block:: bash salt '*' mount.active ''' ret = {} if __grains__['os'] == 'FreeBSD': _active_mounts_freebsd(ret) elif 'AIX' in __grains__['kernel']: _active_mounts_aix(ret) elif __grains__['kernel'] == 'SunOS': _active_mounts_solaris(ret) elif __grains__['os'] == 'OpenBSD': _active_mounts_openbsd(ret) elif __grains__['os'] in ['MacOS', 'Darwin']: _active_mounts_darwin(ret) else: if extended: try: _active_mountinfo(ret) except CommandExecutionError: _active_mounts(ret) else: _active_mounts(ret) return ret class _fstab_entry(object): ''' Utility class for manipulating fstab entries. Primarily we're parsing, formatting, and comparing lines. Parsing emits dicts expected from fstab() or raises a ValueError. Note: We'll probably want to use os.normpath and os.normcase on 'name' ''' class ParseError(ValueError): ''' Error raised when a line isn't parsible as an fstab entry ''' fstab_keys = ('device', 'name', 'fstype', 'opts', 'dump', 'pass_num') # preserve data format compatibility_keys = ('device', 'name', 'fstype', 'opts', 'dump', 'pass') fstab_format = '{device}\t\t{name}\t{fstype}\t{opts}\t{dump} {pass_num}\n' @classmethod def dict_from_line(cls, line, keys=fstab_keys): if len(keys) != 6: raise ValueError('Invalid key array: {0}'.format(keys)) if line.startswith('#'): raise cls.ParseError("Comment!") comps = line.split() if len(comps) < 4 or len(comps) > 6: raise cls.ParseError("Invalid Entry!") comps.extend(['0'] * (len(keys) - len(comps))) return dict(zip(keys, comps)) @classmethod def from_line(cls, *args, **kwargs): return cls(** cls.dict_from_line(*args, **kwargs)) @classmethod def dict_to_line(cls, entry): return cls.fstab_format.format(**entry) def __str__(self): ''' String value, only works for full repr ''' return self.dict_to_line(self.criteria) def __repr__(self): ''' Always works ''' return repr(self.criteria) def pick(self, keys): ''' Returns an instance with just those keys ''' subset = dict([(key, self.criteria[key]) for key in keys]) return self.__class__(**subset) def __init__(self, **criteria): ''' Store non-empty, non-null values to use as filter ''' items = [key_value for key_value in six.iteritems(criteria) if key_value[1] is not None] items = [(key_value1[0], six.text_type(key_value1[1])) for key_value1 in items] self.criteria = dict(items) @staticmethod def norm_path(path): ''' Resolve equivalent paths equivalently ''' return os.path.normcase(os.path.normpath(path)) def match(self, line): ''' Compare potentially partial criteria against line ''' entry = self.dict_from_line(line) for key, value in six.iteritems(self.criteria): if entry[key] != value: return False return True class _vfstab_entry(object): ''' Utility class for manipulating vfstab entries. Primarily we're parsing, formatting, and comparing lines. Parsing emits dicts expected from fstab() or raises a ValueError. Note: We'll probably want to use os.normpath and os.normcase on 'name' Note: This parses vfstab entries on Solaris like systems #device device mount FS fsck mount mount #to mount to fsck point type pass at boot options # /devices - /devices devfs - no - ''' class ParseError(ValueError): '''Error raised when a line isn't parsible as an fstab entry''' vfstab_keys = ('device', 'device_fsck', 'name', 'fstype', 'pass_fsck', 'mount_at_boot', 'opts') # NOTE: weird formatting to match default spacing on Solaris vfstab_format = '{device:<11} {device_fsck:<3} {name:<19} {fstype:<8} {pass_fsck:<3} {mount_at_boot:<6} {opts}\n' @classmethod def dict_from_line(cls, line): if line.startswith('#'): raise cls.ParseError("Comment!") comps = line.split() if len(comps) != 7: raise cls.ParseError("Invalid Entry!") return dict(zip(cls.vfstab_keys, comps)) @classmethod def from_line(cls, *args, **kwargs): return cls(** cls.dict_from_line(*args, **kwargs)) @classmethod def dict_to_line(cls, entry): return cls.vfstab_format.format(**entry) def __str__(self): ''' String value, only works for full repr ''' return self.dict_to_line(self.criteria) def __repr__(self): ''' Always works ''' return repr(self.criteria) def pick(self, keys): ''' Returns an instance with just those keys ''' subset = dict([(key, self.criteria[key]) for key in keys]) return self.__class__(**subset) def __init__(self, **criteria): ''' Store non-empty, non-null values to use as filter ''' items = [key_value for key_value in six.iteritems(criteria) if key_value[1] is not None] items = [(key_value1[0], six.text_type(key_value1[1])) for key_value1 in items] self.criteria = dict(items) @staticmethod def norm_path(path): ''' Resolve equivalent paths equivalently ''' return os.path.normcase(os.path.normpath(path)) def match(self, line): ''' Compare potentially partial criteria against line ''' entry = self.dict_from_line(line) for key, value in six.iteritems(self.criteria): if entry[key] != value: return False return True class _FileSystemsEntry(object): ''' Utility class for manipulating filesystem entries. Primarily we're parsing, formatting, and comparing lines. Parsing emits dicts expected from fstab() or raises a ValueError. Note: We'll probably want to use os.normpath and os.normcase on 'name' ''' class ParseError(ValueError): ''' Error raised when a line isn't parsible as an fstab entry ''' filesystems_keys = ('device', 'name', 'fstype', 'vfstype', 'opts', 'mount') # preserve data format of filesystems compatibility_keys = ('dev', 'dev', 'name', 'fstype', 'vfstype', 'opts', 'mount', 'type', 'vfs', 'account', 'boot', 'check', 'free', 'nodename', 'quota', 'size', 'vol', 'log') @classmethod def dict_from_lines(cls, lines, keys=filesystems_keys): if len(lines) < 2: raise ValueError('Invalid number of lines: {0}'.format(lines)) if not keys: # if empty force default filesystems_keys keys = _FileSystemsEntry.filesystems_keys elif len(keys) < 6: raise ValueError('Invalid key name array: {0}'.format(keys)) blk_lines = lines orddict = OrderedDict() orddict['name'] = blk_lines[0].split(':')[0].strip() blk_lines.pop(0) for line in blk_lines: if line.startswith('#'): raise cls.ParseError("Comment!") comps = line.split('= ') if len(comps) != 2: raise cls.ParseError("Invalid Entry!") key_name = comps[0].strip() if key_name in keys: orddict[key_name] = comps[1].strip() else: raise ValueError('Invalid name for use in filesystems: {0}'.format(key_name)) return orddict @classmethod def dict_from_cmd_line(cls, ipargs, keys): cmdln_dict = ipargs if keys: for key, value in keys: # ignore unknown or local scope keys if key.startswith('__'): continue if key in _FileSystemsEntry.compatibility_keys: cmdln_dict[key] = value return cmdln_dict @classmethod def from_line(cls, *args, **kwargs): return cls(** cls.dict_from_cmd_line(*args, **kwargs)) @classmethod def dict_to_lines(cls, fsys_dict_entry): entry = fsys_dict_entry strg_out = entry['name'] + ':' + os.linesep for k, v in six.viewitems(entry): if 'name' not in k: strg_out += '\t{0}\t\t= {1}'.format(k, v) + os.linesep strg_out += os.linesep return six.text_type(strg_out) def dict_from_entry(self): ret = OrderedDict() ret[self.criteria['name']] = self.criteria return ret def __str__(self): ''' String value, only works for full repr ''' return self.dict_to_lines(self.criteria) def __repr__(self): ''' Always works ''' return repr(self.criteria) def pick(self, keys): ''' Returns an instance with just those keys ''' subset = dict([(key, self.criteria[key]) for key in keys]) return self.__class__(**subset) def __init__(self, **criteria): ''' Store non-empty, non-null values to use as filter ''' items = [key_value for key_value in six.iteritems(criteria) if key_value[1] is not None] items = [(key_value1[0], six.text_type(key_value1[1])) for key_value1 in items] self.criteria = OrderedDict(items) @staticmethod def norm_path(path): ''' Resolve equivalent paths equivalently ''' return os.path.normcase(os.path.normpath(path)) def match(self, fsys_view): ''' Compare potentially partial criteria against built filesystems entry dictionary ''' evalue_dict = fsys_view[1] for key, value in six.viewitems(self.criteria): if key in evalue_dict: if evalue_dict[key] != value: return False else: return False return True def __getitem__(self, key): ''' Return value for input key ''' return self.criteria[key] def fstab(config='/etc/fstab'): ''' .. versionchanged:: 2016.3.2 List the contents of the fstab CLI Example: .. code-block:: bash salt '*' mount.fstab ''' ret = {} if not os.path.isfile(config): return ret with salt.utils.files.fopen(config) as ifile: for line in ifile: line = salt.utils.stringutils.to_unicode(line) try: if __grains__['kernel'] == 'SunOS': # Note: comments use in default vfstab file! if line[0] == '#': continue entry = _vfstab_entry.dict_from_line( line) else: entry = _fstab_entry.dict_from_line( line, _fstab_entry.compatibility_keys) entry['opts'] = entry['opts'].split(',') while entry['name'] in ret: entry['name'] += '_' ret[entry.pop('name')] = entry except _fstab_entry.ParseError: pass except _vfstab_entry.ParseError: pass return ret def vfstab(config='/etc/vfstab'): ''' .. versionadded:: 2016.3.2 List the contents of the vfstab CLI Example: .. code-block:: bash salt '*' mount.vfstab ''' # NOTE: vfstab is a wrapper for fstab return fstab(config) def rm_fstab(name, device, config='/etc/fstab'): ''' .. versionchanged:: 2016.3.2 Remove the mount point from the fstab CLI Example: .. code-block:: bash salt '*' mount.rm_fstab /mnt/foo /dev/sdg ''' modified = False if __grains__['kernel'] == 'SunOS': criteria = _vfstab_entry(name=name, device=device) else: criteria = _fstab_entry(name=name, device=device) lines = [] try: with salt.utils.files.fopen(config, 'r') as ifile: for line in ifile: line = salt.utils.stringutils.to_unicode(line) try: if criteria.match(line): modified = True else: lines.append(line) except _fstab_entry.ParseError: lines.append(line) except _vfstab_entry.ParseError: lines.append(line) except (IOError, OSError) as exc: msg = "Couldn't read from {0}: {1}" raise CommandExecutionError(msg.format(config, exc)) if modified: try: with salt.utils.files.fopen(config, 'wb') as ofile: ofile.writelines(salt.utils.data.encode(lines)) except (IOError, OSError) as exc: msg = "Couldn't write to {0}: {1}" raise CommandExecutionError(msg.format(config, exc)) # Note: not clear why we always return 'True' # --just copying previous behavior at this point... return True def rm_vfstab(name, device, config='/etc/vfstab'): ''' .. versionadded:: 2016.3.2 Remove the mount point from the vfstab CLI Example: .. code-block:: bash salt '*' mount.rm_vfstab /mnt/foo /device/c0t0d0p0 ''' ## NOTE: rm_vfstab is a wrapper for rm_fstab return rm_fstab(name, device, config) def set_fstab( name, device, fstype, opts='defaults', dump=0, pass_num=0, config='/etc/fstab', test=False, match_on='auto', **kwargs): ''' Verify that this mount is represented in the fstab, change the mount to match the data passed, or add the mount if it is not present. CLI Example: .. code-block:: bash salt '*' mount.set_fstab /mnt/foo /dev/sdz1 ext4 ''' # Fix the opts type if it is a list if isinstance(opts, list): opts = ','.join(opts) # preserve arguments for updating entry_args = { 'name': name, 'device': device.replace('\\ ', '\\040'), 'fstype': fstype, 'opts': opts.replace('\\ ', '\\040'), 'dump': dump, 'pass_num': pass_num, } lines = [] ret = None # Transform match_on into list--items will be checked later if isinstance(match_on, list): pass elif not isinstance(match_on, six.string_types): msg = 'match_on must be a string or list of strings' raise CommandExecutionError(msg) elif match_on == 'auto': # Try to guess right criteria for auto.... # NOTE: missing some special fstypes here specialFSes = frozenset([ 'none', 'tmpfs', 'sysfs', 'proc', 'fusectl', 'debugfs', 'securityfs', 'devtmpfs', 'cgroup', 'btrfs']) if fstype in specialFSes: match_on = ['name'] else: match_on = ['device'] else: match_on = [match_on] # generate entry and criteria objects, handle invalid keys in match_on entry = _fstab_entry(**entry_args) try: criteria = entry.pick(match_on) except KeyError: filterFn = lambda key: key not in _fstab_entry.fstab_keys invalid_keys = filter(filterFn, match_on) msg = 'Unrecognized keys in match_on: "{0}"'.format(invalid_keys) raise CommandExecutionError(msg) # parse file, use ret to cache status if not os.path.isfile(config): raise CommandExecutionError('Bad config file "{0}"'.format(config)) try: with salt.utils.files.fopen(config, 'r') as ifile: for line in ifile: line = salt.utils.stringutils.to_unicode(line) try: if criteria.match(line): # Note: If ret isn't None here, # we've matched multiple lines ret = 'present' if entry.match(line): lines.append(line) else: ret = 'change' lines.append(six.text_type(entry)) else: lines.append(line) except _fstab_entry.ParseError: lines.append(line) except (IOError, OSError) as exc: msg = 'Couldn\'t read from {0}: {1}' raise CommandExecutionError(msg.format(config, exc)) # add line if not present or changed if ret is None: lines.append(six.text_type(entry)) ret = 'new' if ret != 'present': # ret in ['new', 'change']: if not salt.utils.args.test_mode(test=test, **kwargs): try: with salt.utils.files.fopen(config, 'wb') as ofile: # The line was changed, commit it! ofile.writelines(salt.utils.data.encode(lines)) except (IOError, OSError): msg = 'File not writable {0}' raise CommandExecutionError(msg.format(config)) return ret def set_vfstab( name, device, fstype, opts='-', device_fsck='-', pass_fsck='-', mount_at_boot='yes', config='/etc/vfstab', test=False, match_on='auto', **kwargs): ''' ..verionadded:: 2016.3.2 Verify that this mount is represented in the fstab, change the mount to match the data passed, or add the mount if it is not present. CLI Example: .. code-block:: bash salt '*' mount.set_vfstab /mnt/foo /device/c0t0d0p0 ufs ''' # Fix the opts type if it is a list if isinstance(opts, list): opts = ','.join(opts) # Map unknown values for mount_at_boot to no if mount_at_boot != 'yes': mount_at_boot = 'no' # preserve arguments for updating entry_args = { 'name': name, 'device': device, 'fstype': fstype, 'opts': opts, 'device_fsck': device_fsck, 'pass_fsck': pass_fsck, 'mount_at_boot': mount_at_boot, } lines = [] ret = None # Transform match_on into list--items will be checked later if isinstance(match_on, list): pass elif not isinstance(match_on, six.string_types): msg = 'match_on must be a string or list of strings' raise CommandExecutionError(msg) elif match_on == 'auto': # Try to guess right criteria for auto.... # NOTE: missing some special fstypes here specialFSes = frozenset([ 'devfs', 'proc', 'ctfs', 'objfs', 'sharefs', 'fs', 'tmpfs']) if fstype in specialFSes: match_on = ['name'] else: match_on = ['device'] else: match_on = [match_on] # generate entry and criteria objects, handle invalid keys in match_on entry = _vfstab_entry(**entry_args) try: criteria = entry.pick(match_on) except KeyError: filterFn = lambda key: key not in _vfstab_entry.vfstab_keys invalid_keys = filter(filterFn, match_on) msg = 'Unrecognized keys in match_on: "{0}"'.format(invalid_keys) raise CommandExecutionError(msg) # parse file, use ret to cache status if not os.path.isfile(config): raise CommandExecutionError('Bad config file "{0}"'.format(config)) try: with salt.utils.files.fopen(config, 'r') as ifile: for line in ifile: line = salt.utils.stringutils.to_unicode(line) try: if criteria.match(line): # Note: If ret isn't None here, # we've matched multiple lines ret = 'present' if entry.match(line): lines.append(line) else: ret = 'change' lines.append(six.text_type(entry)) else: lines.append(line) except _vfstab_entry.ParseError: lines.append(line) except (IOError, OSError) as exc: msg = 'Couldn\'t read from {0}: {1}' raise CommandExecutionError(msg.format(config, exc)) # add line if not present or changed if ret is None: lines.append(six.text_type(entry)) ret = 'new' if ret != 'present': # ret in ['new', 'change']: if not salt.utils.args.test_mode(test=test, **kwargs): try: with salt.utils.files.fopen(config, 'wb') as ofile: # The line was changed, commit it! ofile.writelines(salt.utils.data.encode(lines)) except (IOError, OSError): msg = 'File not writable {0}' raise CommandExecutionError(msg.format(config)) return ret def rm_automaster(name, device, config='/etc/auto_salt'): ''' Remove the mount point from the auto_master CLI Example: .. code-block:: bash salt '*' mount.rm_automaster /mnt/foo /dev/sdg ''' contents = automaster(config) if name not in contents: return True # The entry is present, get rid of it lines = [] try: with salt.utils.files.fopen(config, 'r') as ifile: for line in ifile: line = salt.utils.stringutils.to_unicode(line) if line.startswith('#'): # Commented lines.append(line) continue if not line.strip(): # Blank line lines.append(line) continue comps = line.split() if len(comps) != 3: # Invalid entry lines.append(line) continue comps = line.split() prefix = "/.." name_chk = comps[0].replace(prefix, "") device_fmt = comps[2].split(":") if device: if name_chk == name and device_fmt[1] == device: continue else: if name_chk == name: continue lines.append(line) except (IOError, OSError) as exc: msg = "Couldn't read from {0}: {1}" raise CommandExecutionError(msg.format(config, exc)) try: with salt.utils.files.fopen(config, 'wb') as ofile: ofile.writelines(salt.utils.data.encode(lines)) except (IOError, OSError) as exc: msg = "Couldn't write to {0}: {1}" raise CommandExecutionError(msg.format(config, exc)) # Update automount __salt__['cmd.run']('automount -cv') return True def set_automaster( name, device, fstype, opts='', config='/etc/auto_salt', test=False, **kwargs): ''' Verify that this mount is represented in the auto_salt, change the mount to match the data passed, or add the mount if it is not present. CLI Example: .. code-block:: bash salt '*' mount.set_automaster /mnt/foo /dev/sdz1 ext4 ''' # Fix the opts type if it is a list if isinstance(opts, list): opts = ','.join(opts) lines = [] change = False present = False automaster_file = "/etc/auto_master" if not os.path.isfile(config): __salt__['file.touch'](config) __salt__['file.append'](automaster_file, "/-\t\t\t{0}".format(config)) name = "/..{0}".format(name) device_fmt = "{0}:{1}".format(fstype, device) type_opts = "-fstype={0},{1}".format(fstype, opts) if fstype == 'smbfs': device_fmt = device_fmt.replace(fstype, "") try: with salt.utils.files.fopen(config, 'r') as ifile: for line in ifile: line = salt.utils.stringutils.to_unicode(line) if line.startswith('#'): # Commented lines.append(line) continue if not line.strip(): # Blank line lines.append(line) continue comps = line.split() if len(comps) != 3: # Invalid entry lines.append(line) continue if comps[0] == name or comps[2] == device_fmt: # check to see if there are changes # and fix them if there are any present = True if comps[0] != name: change = True comps[0] = name if comps[1] != type_opts: change = True comps[1] = type_opts if comps[2] != device_fmt: change = True comps[2] = device_fmt if change: log.debug( 'auto_master entry for mount point %s needs to be ' 'updated', name ) newline = ( '{0}\t{1}\t{2}\n'.format( name, type_opts, device_fmt) ) lines.append(newline) else: lines.append(line) except (IOError, OSError) as exc: msg = 'Couldn\'t read from {0}: {1}' raise CommandExecutionError(msg.format(config, exc)) if change: if not salt.utils.args.test_mode(test=test, **kwargs): try: with salt.utils.files.fopen(config, 'wb') as ofile: # The line was changed, commit it! ofile.writelines(salt.utils.data.encode(lines)) except (IOError, OSError): msg = 'File not writable {0}' raise CommandExecutionError(msg.format(config)) return 'change' if not change: if present: # The right entry is already here return 'present' else: if not salt.utils.args.test_mode(test=test, **kwargs): # The entry is new, add it to the end of the fstab newline = ( '{0}\t{1}\t{2}\n'.format( name, type_opts, device_fmt) ) lines.append(newline) try: with salt.utils.files.fopen(config, 'wb') as ofile: # The line was changed, commit it! ofile.writelines(salt.utils.data.encode(lines)) except (IOError, OSError): raise CommandExecutionError( 'File not writable {0}'.format( config ) ) return 'new' def automaster(config='/etc/auto_salt'): ''' List the contents of the auto master CLI Example: .. code-block:: bash salt '*' mount.automaster ''' ret = {} if not os.path.isfile(config): return ret with salt.utils.files.fopen(config) as ifile: for line in ifile: line = salt.utils.stringutils.to_unicode(line) if line.startswith('#'): # Commented continue if not line.strip(): # Blank line continue comps = line.split() if len(comps) != 3: # Invalid entry continue prefix = "/.." name = comps[0].replace(prefix, "") device_fmt = comps[2].split(":") opts = comps[1].split(',') ret[name] = {'device': device_fmt[1], 'fstype': opts[0], 'opts': opts[1:]} return ret def mount(name, device, mkmnt=False, fstype='', opts='defaults', user=None, util='mount'): ''' Mount a device CLI Example: .. code-block:: bash salt '*' mount.mount /mnt/foo /dev/sdz1 True ''' if util != 'mount': # This functionality used to live in img.mount_image if util == 'guestfs': return __salt__['guestfs.mount'](name, root=device) elif util == 'qemu_nbd': mnt = __salt__['qemu_nbd.init'](name, device) if not mnt: return False first = next(six.iterkeys(mnt)) __context__['img.mnt_{0}'.format(first)] = mnt return first return False # Darwin doesn't expect defaults when mounting without other options if 'defaults' in opts and __grains__['os'] in ['MacOS', 'Darwin', 'AIX']: opts = None if isinstance(opts, six.string_types): opts = opts.split(',') if not os.path.exists(name) and mkmnt: __salt__['file.mkdir'](name, user=user) args = '' if opts is not None: lopts = ','.join(opts) args = '-o {0}'.format(lopts) if fstype: # use of fstype on AIX differs from typical Linux use of -t # functionality AIX uses -v vfsname, -t fstype mounts all with # fstype in /etc/filesystems if 'AIX' in __grains__['os']: args += ' -v {0}'.format(fstype) elif 'solaris' in __grains__['os'].lower(): args += ' -F {0}'.format(fstype) else: args += ' -t {0}'.format(fstype) cmd = 'mount {0} {1} {2} '.format(args, device, name) out = __salt__['cmd.run_all'](cmd, runas=user, python_shell=False) if out['retcode']: return out['stderr'] return True def remount(name, device, mkmnt=False, fstype='', opts='defaults', user=None): ''' Attempt to remount a device, if the device is not already mounted, mount is called CLI Example: .. code-block:: bash salt '*' mount.remount /mnt/foo /dev/sdz1 True ''' force_mount = False if __grains__['os'] in ['MacOS', 'Darwin']: if opts == 'defaults': opts = 'noowners' if fstype == 'smbfs': force_mount = True if 'AIX' in __grains__['os']: if opts == 'defaults': opts = [] if isinstance(opts, six.string_types): opts = opts.split(',') mnts = active() if name in mnts: # The mount point is mounted, attempt to remount it with the given data if 'remount' not in opts and __grains__['os'] not in ['OpenBSD', 'MacOS', 'Darwin']: opts.append('remount') if force_mount: # We need to force the mount but first we should unmount umount(name, device, user=user) lopts = ','.join(opts) args = '-o {0}'.format(lopts) if fstype: # use of fstype on AIX differs from typical Linux use of # -t functionality AIX uses -v vfsname, -t fstype mounts # all with fstype in /etc/filesystems if 'AIX' in __grains__['os']: args += ' -v {0}'.format(fstype) elif 'solaris' in __grains__['os'].lower(): args += ' -F {0}'.format(fstype) else: args += ' -t {0}'.format(fstype) if __grains__['os'] not in ['OpenBSD', 'MacOS', 'Darwin'] or force_mount: cmd = 'mount {0} {1} {2} '.format(args, device, name) else: cmd = 'mount -u {0} {1} {2} '.format(args, device, name) out = __salt__['cmd.run_all'](cmd, runas=user, python_shell=False) if out['retcode']: return out['stderr'] return True # Mount a filesystem that isn't already return mount(name, device, mkmnt, fstype, opts, user=user) def umount(name, device=None, user=None, util='mount'): ''' Attempt to unmount a device by specifying the directory it is mounted on CLI Example: .. code-block:: bash salt '*' mount.umount /mnt/foo .. versionadded:: 2015.5.0 .. code-block:: bash salt '*' mount.umount /mnt/foo /dev/xvdc1 ''' if util != 'mount': # This functionality used to live in img.umount_image if 'qemu_nbd.clear' in __salt__: if 'img.mnt_{0}'.format(name) in __context__: __salt__['qemu_nbd.clear'](__context__['img.mnt_{0}'.format(name)]) return mnts = active() if name not in mnts: return "{0} does not have anything mounted".format(name) if not device: cmd = 'umount {0}'.format(name) else: cmd = 'umount {0}'.format(device) out = __salt__['cmd.run_all'](cmd, runas=user, python_shell=False) if out['retcode']: return out['stderr'] return True def is_fuse_exec(cmd): ''' Returns true if the command passed is a fuse mountable application. CLI Example: .. code-block:: bash salt '*' mount.is_fuse_exec sshfs ''' cmd_path = salt.utils.path.which(cmd) # No point in running ldd on a command that doesn't exist if not cmd_path: return False elif not salt.utils.path.which('ldd'): raise CommandNotFoundError('ldd') out = __salt__['cmd.run']('ldd {0}'.format(cmd_path), python_shell=False) return 'libfuse' in out def swaps(): ''' Return a dict containing information on active swap .. versionchanged:: 2016.3.2 CLI Example: .. code-block:: bash salt '*' mount.swaps ''' ret = {} if __grains__['kernel'] == 'SunOS': for line in __salt__['cmd.run_stdout']('swap -l').splitlines(): if line.startswith('swapfile'): continue comps = line.split() ret[comps[0]] = {'type': 'device' if comps[0].startswith(('/dev', 'swap')) else 'file', 'size': int(comps[3]), 'used': (int(comps[3]) - int(comps[4])), 'priority': '-'} elif 'AIX' in __grains__['kernel']: for line in __salt__['cmd.run_stdout']('swap -l').splitlines(): if line.startswith('device'): continue comps = line.split() # AIX uses MB for units ret[comps[0]] = {'type': 'device', 'size': int(comps[3][:-2]) * 1024, 'used': (int(comps[3][:-2]) - int(comps[4][:-2])) * 1024, 'priority': '-'} elif __grains__['os'] != 'OpenBSD': with salt.utils.files.fopen('/proc/swaps') as fp_: for line in fp_: line = salt.utils.stringutils.to_unicode(line) if line.startswith('Filename'): continue comps = line.split() ret[comps[0]] = {'type': comps[1], 'size': comps[2], 'used': comps[3], 'priority': comps[4]} else: for line in __salt__['cmd.run_stdout']('swapctl -kl').splitlines(): if line.startswith(('Device', 'Total')): continue swap_type = "file" comps = line.split() if comps[0].startswith('/dev/'): swap_type = "partition" ret[comps[0]] = {'type': swap_type, 'size': comps[1], 'used': comps[2], 'priority': comps[5]} return ret def swapon(name, priority=None): ''' Activate a swap disk .. versionchanged:: 2016.3.2 CLI Example: .. code-block:: bash salt '*' mount.swapon /root/swapfile ''' ret = {} on_ = swaps() if name in on_: ret['stats'] = on_[name] ret['new'] = False return ret if __grains__['kernel'] == 'SunOS': if __grains__['virtual'] != 'zone': __salt__['cmd.run']('swap -a {0}'.format(name), python_shell=False) else: return False else: cmd = 'swapon {0}'.format(name) if priority and 'AIX' not in __grains__['kernel']: cmd += ' -p {0}'.format(priority) __salt__['cmd.run'](cmd, python_shell=False) on_ = swaps() if name in on_: ret['stats'] = on_[name] ret['new'] = True return ret return ret def swapoff(name): ''' Deactivate a named swap mount .. versionchanged:: 2016.3.2 CLI Example: .. code-block:: bash salt '*' mount.swapoff /root/swapfile ''' on_ = swaps() if name in on_: if __grains__['kernel'] == 'SunOS': if __grains__['virtual'] != 'zone': __salt__['cmd.run']('swap -a {0}'.format(name), python_shell=False) else: return False elif __grains__['os'] != 'OpenBSD': __salt__['cmd.run']('swapoff {0}'.format(name), python_shell=False) else: __salt__['cmd.run']('swapctl -d {0}'.format(name), python_shell=False) on_ = swaps() if name in on_: return False return True return None def is_mounted(name): ''' .. versionadded:: 2014.7.0 Provide information if the path is mounted CLI Example: .. code-block:: bash salt '*' mount.is_mounted /mnt/share ''' active_ = active() if name in active_: return True else: return False def read_mount_cache(name): ''' .. versionadded:: 2018.3.0 Provide information if the path is mounted CLI Example: .. code-block:: bash salt '*' mount.read_mount_cache /mnt/share ''' cache = salt.utils.mount.read_cache(__opts__) if cache: if 'mounts' in cache and cache['mounts']: if name in cache['mounts']: return cache['mounts'][name] return {} def write_mount_cache(real_name, device, mkmnt, fstype, mount_opts): ''' .. versionadded:: 2018.3.0 Provide information if the path is mounted :param real_name: The real name of the mount point where the device is mounted. :param device: The device that is being mounted. :param mkmnt: Whether or not the mount point should be created. :param fstype: The file system that is used. :param mount_opts: Additional options used when mounting the device. :return: Boolean if message was sent successfully. CLI Example: .. code-block:: bash salt '*' mount.write_mount_cache /mnt/share /dev/sda1 False ext4 defaults,nosuid ''' cache = salt.utils.mount.read_cache(__opts__) if not cache: cache = {} cache['mounts'] = {} else: if 'mounts' not in cache: cache['mounts'] = {} cache['mounts'][real_name] = {'device': device, 'fstype': fstype, 'mkmnt': mkmnt, 'opts': mount_opts} cache_write = salt.utils.mount.write_cache(cache, __opts__) if cache_write: return True else: raise CommandExecutionError('Unable to write mount cache.') def delete_mount_cache(real_name): ''' .. versionadded:: 2018.3.0 Provide information if the path is mounted CLI Example: .. code-block:: bash salt '*' mount.delete_mount_cache /mnt/share ''' cache = salt.utils.mount.read_cache(__opts__) if cache: if 'mounts' in cache: if real_name in cache['mounts']: del cache['mounts'][real_name] cache_write = salt.utils.mount.write_cache(cache, __opts__) if not cache_write: raise CommandExecutionError('Unable to write mount cache.') return True def _filesystems(config='/etc/filesystems', leading_key=True): ''' Return the contents of the filesystems in an OrderedDict config File containing filesystem infomation leading_key True return dictionary keyed by 'name' and value as dictionary with other keys, values (name excluded) OrderedDict({ '/dir' : OrderedDict({'dev': '/dev/hd8', .... }})) False return dictionary keyed by 'name' and value as dictionary with all keys, values (name included) OrderedDict({ '/dir' : OrderedDict({'name': '/dir', 'dev': '/dev/hd8', ... })}) ''' ret = OrderedDict() lines = [] parsing_block = False if not os.path.isfile(config) or 'AIX' not in __grains__['kernel']: return ret # read in block of filesystems, block starts with '/' till empty line with salt.utils.files.fopen(config) as ifile: for line in ifile: line = salt.utils.stringutils.to_unicode(line) # skip till first entry if not line.startswith('/') and not parsing_block: continue if line.startswith('/'): parsing_block = True lines.append(line) elif not line.split(): parsing_block = False try: entry = _FileSystemsEntry.dict_from_lines( lines, _FileSystemsEntry.compatibility_keys) lines = [] if 'opts' in entry: entry['opts'] = entry['opts'].split(',') while entry['name'] in ret: entry['name'] += '_' if leading_key: ret[entry.pop('name')] = entry else: ret[entry['name']] = entry except _FileSystemsEntry.ParseError: pass else: lines.append(line) return ret def filesystems(config='/etc/filesystems'): ''' .. versionadded:: 2018.3.3 List the contents of the filesystems CLI Example: .. code-block:: bash salt '*' mount.filesystems ''' ret = {} if 'AIX' not in __grains__['kernel']: return ret ret_dict = _filesystems(config) if ret_dict: ret_key = next(iter(ret_dict.keys())) ret = {ret_key: dict(ret_dict[ret_key])} return ret def set_filesystems( name, device, vfstype, opts='-', mount='true', config='/etc/filesystems', test=False, match_on='auto', **kwargs): ''' .. versionadded:: 2018.3.3 Verify that this mount is represented in the filesystems, change the mount to match the data passed, or add the mount if it is not present on AIX Provide information if the path is mounted :param name: The name of the mount point where the device is mounted. :param device: The device that is being mounted. :param vfstype: The file system that is used (AIX has two fstypes, fstype and vfstype - similar to Linux fstype) :param opts: Additional options used when mounting the device. :param mount: Mount if not mounted, default True. :param config: Configuration file, default /etc/filesystems. :param match: File systems type to match on, default auto CLI Example: .. code-block:: bash salt '*' mount.set_filesystems /mnt/foo /dev/sdz1 jfs2 ''' # Fix the opts type if it is a list if isinstance(opts, list): opts = ','.join(opts) # preserve arguments for updating entry_args = { 'name': name, 'dev': device.replace('\\ ', '\\040'), 'vfstype': vfstype, 'opts': opts, 'mount': mount, } view_lines = [] ret = None if 'AIX' not in __grains__['kernel']: return ret # Transform match_on into list--items will be checked later if isinstance(match_on, list): pass elif not isinstance(match_on, six.string_types): raise CommandExecutionError('match_on must be a string or list of strings') elif match_on == 'auto': # Try to guess right criteria for auto.... # added IBM types from sys/vmount.h after btrfs # NOTE: missing some special fstypes here specialFSes = frozenset([ 'none', 'tmpfs', 'sysfs', 'proc', 'fusectl', 'debugfs', 'securityfs', 'devtmpfs', 'cgroup', 'btrfs', 'cdrfs', 'procfs', 'jfs', 'jfs2', 'nfs', 'sfs', 'nfs3', 'cachefs', 'udfs', 'cifs', 'namefs', 'pmemfs', 'ahafs', 'nfs4', 'autofs', 'stnfs']) if vfstype in specialFSes: match_on = ['name'] else: match_on = ['dev'] else: match_on = [match_on] # generate entry and criteria objects, handle invalid keys in match_on entry_ip = _FileSystemsEntry.from_line(entry_args, kwargs) try: criteria = entry_ip.pick(match_on) except KeyError: filterFn = lambda key: key not in _FileSystemsEntry.compatibility_keys invalid_keys = filter(filterFn, match_on) raise CommandExecutionError('Unrecognized keys in match_on: "{0}"'.format(invalid_keys)) # parse file, use ret to cache status if not os.path.isfile(config): raise CommandExecutionError('Bad config file "{0}"'.format(config)) # read in block of filesystem, block starts with '/' till empty line try: fsys_filedict = _filesystems(config, False) for fsys_view in six.viewitems(fsys_filedict): if criteria.match(fsys_view): ret = 'present' if entry_ip.match(fsys_view): view_lines.append(fsys_view) else: ret = 'change' kv = entry_ip['name'] view_lines.append((kv, entry_ip)) else: view_lines.append(fsys_view) except (IOError, OSError) as exc: raise CommandExecutionError('Couldn\'t read from {0}: {1}'.format(config, exc)) # add line if not present or changed if ret is None: for dict_view in six.viewitems(entry_ip.dict_from_entry()): view_lines.append(dict_view) ret = 'new' if ret != 'present': # ret in ['new', 'change']: try: with salt.utils.files.fopen(config, 'wb') as ofile: # The line was changed, commit it! for fsys_view in view_lines: entry = fsys_view[1] mystrg = _FileSystemsEntry.dict_to_lines(entry) ofile.writelines(salt.utils.data.encode(mystrg)) except (IOError, OSError): raise CommandExecutionError('File not writable {0}'.format(config)) return ret def rm_filesystems(name, device, config='/etc/filesystems'): ''' .. versionadded:: 2018.3.3 Remove the mount point from the filesystems CLI Example: .. code-block:: bash salt '*' mount.rm_filesystems /mnt/foo /dev/sdg ''' modified = False view_lines = [] if 'AIX' not in __grains__['kernel']: return modified criteria = _FileSystemsEntry(name=name, dev=device) try: fsys_filedict = _filesystems(config, False) for fsys_view in six.viewitems(fsys_filedict): try: if criteria.match(fsys_view): modified = True else: view_lines.append(fsys_view) except _FileSystemsEntry.ParseError: view_lines.append(fsys_view) except (IOError, OSError) as exc: raise CommandExecutionError("Couldn't read from {0}: {1}".format(config, exc)) if modified: try: with salt.utils.files.fopen(config, 'wb') as ofile: for fsys_view in view_lines: entry = fsys_view[1] mystrg = _FileSystemsEntry.dict_to_lines(entry) ofile.writelines(salt.utils.data.encode(mystrg)) except (IOError, OSError) as exc: raise CommandExecutionError("Couldn't write to {0}: {1}".format(config, exc)) return modified
saltstack/salt
salt/modules/mount.py
_active_mounts_darwin
python
def _active_mounts_darwin(ret): ''' List active mounts on Mac OS systems ''' for line in __salt__['cmd.run_stdout']('mount').split('\n'): comps = re.sub(r"\s+", " ", line).split() parens = re.findall(r'\((.*?)\)', line, re.DOTALL)[0].split(", ") ret[comps[2]] = {'device': comps[0], 'fstype': parens[0], 'opts': _resolve_user_group_names(parens[1:])} return ret
List active mounts on Mac OS systems
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/mount.py#L202-L212
[ "def _resolve_user_group_names(opts):\n '''\n Resolve user and group names in related opts\n '''\n name_id_opts = {'uid': 'user.info',\n 'gid': 'group.info'}\n for ind, opt in enumerate(opts):\n if opt.split('=')[0] in name_id_opts:\n _givenid = opt.split('=')[1]\n _param = opt.split('=')[0]\n _id = _givenid\n if not re.match('[0-9]+$', _givenid):\n _info = __salt__[name_id_opts[_param]](_givenid)\n if _info and _param in _info:\n _id = _info[_param]\n opts[ind] = _param + '=' + six.text_type(_id)\n opts[ind] = opts[ind].replace('\\\\040', '\\\\ ')\n return opts\n" ]
# -*- coding: utf-8 -*- ''' Salt module to manage Unix mounts and the fstab file ''' # Import python libs from __future__ import absolute_import, print_function, unicode_literals import os import re import logging # Import salt libs import salt.utils.args import salt.utils.data import salt.utils.files import salt.utils.path import salt.utils.platform import salt.utils.mount import salt.utils.stringutils from salt.utils.odict import OrderedDict from salt.exceptions import CommandNotFoundError, CommandExecutionError # Import 3rd-party libs from salt.ext import six from salt.ext.six.moves import filter, zip # pylint: disable=import-error,redefined-builtin # Set up logger log = logging.getLogger(__name__) # Define the module's virtual name __virtualname__ = 'mount' def __virtual__(): ''' Only load on POSIX-like systems ''' # Disable on Windows, a specific file module exists: if salt.utils.platform.is_windows(): return (False, 'The mount module cannot be loaded: not a POSIX-like system.') return True def _list_mounts(): ret = {} if __grains__['os'] in ['MacOS', 'Darwin']: mounts = __salt__['cmd.run_stdout']('mount') else: mounts = __salt__['cmd.run_stdout']('mount -l') for line in mounts.split('\n'): comps = re.sub(r"\s+", " ", line).split() if len(comps) >= 3: ret[comps[2]] = comps[0] return ret def _active_mountinfo(ret): _list = _list_mounts() filename = '/proc/self/mountinfo' if not os.access(filename, os.R_OK): msg = 'File not readable {0}' raise CommandExecutionError(msg.format(filename)) if 'disk.blkid' not in __context__: __context__['disk.blkid'] = __salt__['disk.blkid']() blkid_info = __context__['disk.blkid'] with salt.utils.files.fopen(filename) as ifile: for line in ifile: comps = salt.utils.stringutils.to_unicode(line).split() device = comps[2].split(':') # each line can have any number of # optional parameters, we use the # location of the separator field to # determine the location of the elements # after it. _sep = comps.index('-') device_name = comps[_sep + 2] device_uuid = None device_label = None if device_name: device_uuid = blkid_info.get(device_name, {}).get('UUID') device_uuid = device_uuid and device_uuid.lower() device_label = blkid_info.get(device_name, {}).get('LABEL') ret[comps[4]] = {'mountid': comps[0], 'parentid': comps[1], 'major': device[0], 'minor': device[1], 'root': comps[3], 'opts': _resolve_user_group_names(comps[5].split(',')), 'fstype': comps[_sep + 1], 'device': device_name.replace('\\040', '\\ '), 'alt_device': _list.get(comps[4], None), 'superopts': _resolve_user_group_names(comps[_sep + 3].split(',')), 'device_uuid': device_uuid, 'device_label': device_label} return ret def _active_mounts(ret): ''' List active mounts on Linux systems ''' _list = _list_mounts() filename = '/proc/self/mounts' if not os.access(filename, os.R_OK): msg = 'File not readable {0}' raise CommandExecutionError(msg.format(filename)) with salt.utils.files.fopen(filename) as ifile: for line in ifile: comps = salt.utils.stringutils.to_unicode(line).split() ret[comps[1]] = {'device': comps[0], 'alt_device': _list.get(comps[1], None), 'fstype': comps[2], 'opts': _resolve_user_group_names(comps[3].split(','))} return ret def _active_mounts_aix(ret): ''' List active mounts on AIX systems ''' for line in __salt__['cmd.run_stdout']('mount -p').split('\n'): comps = re.sub(r"\s+", " ", line).split() if comps: if comps[0] == 'node' or comps[0] == '--------': continue comps_len = len(comps) if line.startswith((' ', '\t')): curr_opts = _resolve_user_group_names(comps[6].split(',')) if 7 == comps_len else [] if curr_opts: ret[comps[1]] = {'device': comps[0], 'fstype': comps[2], 'opts': curr_opts} else: ret[comps[1]] = {'device': comps[0], 'fstype': comps[2]} else: curr_opts = _resolve_user_group_names(comps[7].split(',')) if 8 == comps_len else [] if curr_opts: ret[comps[2]] = {'node': comps[0], 'device': comps[1], 'fstype': comps[3], 'opts': curr_opts} else: ret[comps[2]] = {'node': comps[0], 'device': comps[1], 'fstype': comps[3]} return ret def _active_mounts_freebsd(ret): ''' List active mounts on FreeBSD systems ''' for line in __salt__['cmd.run_stdout']('mount -p').split('\n'): comps = re.sub(r"\s+", " ", line).split() ret[comps[1]] = {'device': comps[0], 'fstype': comps[2], 'opts': _resolve_user_group_names(comps[3].split(','))} return ret def _active_mounts_solaris(ret): ''' List active mounts on Solaris systems ''' for line in __salt__['cmd.run_stdout']('mount -v').split('\n'): comps = re.sub(r"\s+", " ", line).split() ret[comps[2]] = {'device': comps[0], 'fstype': comps[4], 'opts': _resolve_user_group_names(comps[5].split('/'))} return ret def _active_mounts_openbsd(ret): ''' List active mounts on OpenBSD systems ''' for line in __salt__['cmd.run_stdout']('mount -v').split('\n'): comps = re.sub(r"\s+", " ", line).split() parens = re.findall(r'\((.*?)\)', line, re.DOTALL) if len(parens) > 1: nod = __salt__['cmd.run_stdout']('ls -l {0}'.format(comps[0])) nod = ' '.join(nod.split()).split(" ") ret[comps[3]] = {'device': comps[0], 'fstype': comps[5], 'opts': _resolve_user_group_names(parens[1].split(", ")), 'major': six.text_type(nod[4].strip(",")), 'minor': six.text_type(nod[5]), 'device_uuid': parens[0]} else: ret[comps[2]] = {'device': comps[0], 'fstype': comps[4], 'opts': _resolve_user_group_names(parens[0].split(", "))} return ret def _resolve_user_group_names(opts): ''' Resolve user and group names in related opts ''' name_id_opts = {'uid': 'user.info', 'gid': 'group.info'} for ind, opt in enumerate(opts): if opt.split('=')[0] in name_id_opts: _givenid = opt.split('=')[1] _param = opt.split('=')[0] _id = _givenid if not re.match('[0-9]+$', _givenid): _info = __salt__[name_id_opts[_param]](_givenid) if _info and _param in _info: _id = _info[_param] opts[ind] = _param + '=' + six.text_type(_id) opts[ind] = opts[ind].replace('\\040', '\\ ') return opts def active(extended=False): ''' List the active mounts. CLI Example: .. code-block:: bash salt '*' mount.active ''' ret = {} if __grains__['os'] == 'FreeBSD': _active_mounts_freebsd(ret) elif 'AIX' in __grains__['kernel']: _active_mounts_aix(ret) elif __grains__['kernel'] == 'SunOS': _active_mounts_solaris(ret) elif __grains__['os'] == 'OpenBSD': _active_mounts_openbsd(ret) elif __grains__['os'] in ['MacOS', 'Darwin']: _active_mounts_darwin(ret) else: if extended: try: _active_mountinfo(ret) except CommandExecutionError: _active_mounts(ret) else: _active_mounts(ret) return ret class _fstab_entry(object): ''' Utility class for manipulating fstab entries. Primarily we're parsing, formatting, and comparing lines. Parsing emits dicts expected from fstab() or raises a ValueError. Note: We'll probably want to use os.normpath and os.normcase on 'name' ''' class ParseError(ValueError): ''' Error raised when a line isn't parsible as an fstab entry ''' fstab_keys = ('device', 'name', 'fstype', 'opts', 'dump', 'pass_num') # preserve data format compatibility_keys = ('device', 'name', 'fstype', 'opts', 'dump', 'pass') fstab_format = '{device}\t\t{name}\t{fstype}\t{opts}\t{dump} {pass_num}\n' @classmethod def dict_from_line(cls, line, keys=fstab_keys): if len(keys) != 6: raise ValueError('Invalid key array: {0}'.format(keys)) if line.startswith('#'): raise cls.ParseError("Comment!") comps = line.split() if len(comps) < 4 or len(comps) > 6: raise cls.ParseError("Invalid Entry!") comps.extend(['0'] * (len(keys) - len(comps))) return dict(zip(keys, comps)) @classmethod def from_line(cls, *args, **kwargs): return cls(** cls.dict_from_line(*args, **kwargs)) @classmethod def dict_to_line(cls, entry): return cls.fstab_format.format(**entry) def __str__(self): ''' String value, only works for full repr ''' return self.dict_to_line(self.criteria) def __repr__(self): ''' Always works ''' return repr(self.criteria) def pick(self, keys): ''' Returns an instance with just those keys ''' subset = dict([(key, self.criteria[key]) for key in keys]) return self.__class__(**subset) def __init__(self, **criteria): ''' Store non-empty, non-null values to use as filter ''' items = [key_value for key_value in six.iteritems(criteria) if key_value[1] is not None] items = [(key_value1[0], six.text_type(key_value1[1])) for key_value1 in items] self.criteria = dict(items) @staticmethod def norm_path(path): ''' Resolve equivalent paths equivalently ''' return os.path.normcase(os.path.normpath(path)) def match(self, line): ''' Compare potentially partial criteria against line ''' entry = self.dict_from_line(line) for key, value in six.iteritems(self.criteria): if entry[key] != value: return False return True class _vfstab_entry(object): ''' Utility class for manipulating vfstab entries. Primarily we're parsing, formatting, and comparing lines. Parsing emits dicts expected from fstab() or raises a ValueError. Note: We'll probably want to use os.normpath and os.normcase on 'name' Note: This parses vfstab entries on Solaris like systems #device device mount FS fsck mount mount #to mount to fsck point type pass at boot options # /devices - /devices devfs - no - ''' class ParseError(ValueError): '''Error raised when a line isn't parsible as an fstab entry''' vfstab_keys = ('device', 'device_fsck', 'name', 'fstype', 'pass_fsck', 'mount_at_boot', 'opts') # NOTE: weird formatting to match default spacing on Solaris vfstab_format = '{device:<11} {device_fsck:<3} {name:<19} {fstype:<8} {pass_fsck:<3} {mount_at_boot:<6} {opts}\n' @classmethod def dict_from_line(cls, line): if line.startswith('#'): raise cls.ParseError("Comment!") comps = line.split() if len(comps) != 7: raise cls.ParseError("Invalid Entry!") return dict(zip(cls.vfstab_keys, comps)) @classmethod def from_line(cls, *args, **kwargs): return cls(** cls.dict_from_line(*args, **kwargs)) @classmethod def dict_to_line(cls, entry): return cls.vfstab_format.format(**entry) def __str__(self): ''' String value, only works for full repr ''' return self.dict_to_line(self.criteria) def __repr__(self): ''' Always works ''' return repr(self.criteria) def pick(self, keys): ''' Returns an instance with just those keys ''' subset = dict([(key, self.criteria[key]) for key in keys]) return self.__class__(**subset) def __init__(self, **criteria): ''' Store non-empty, non-null values to use as filter ''' items = [key_value for key_value in six.iteritems(criteria) if key_value[1] is not None] items = [(key_value1[0], six.text_type(key_value1[1])) for key_value1 in items] self.criteria = dict(items) @staticmethod def norm_path(path): ''' Resolve equivalent paths equivalently ''' return os.path.normcase(os.path.normpath(path)) def match(self, line): ''' Compare potentially partial criteria against line ''' entry = self.dict_from_line(line) for key, value in six.iteritems(self.criteria): if entry[key] != value: return False return True class _FileSystemsEntry(object): ''' Utility class for manipulating filesystem entries. Primarily we're parsing, formatting, and comparing lines. Parsing emits dicts expected from fstab() or raises a ValueError. Note: We'll probably want to use os.normpath and os.normcase on 'name' ''' class ParseError(ValueError): ''' Error raised when a line isn't parsible as an fstab entry ''' filesystems_keys = ('device', 'name', 'fstype', 'vfstype', 'opts', 'mount') # preserve data format of filesystems compatibility_keys = ('dev', 'dev', 'name', 'fstype', 'vfstype', 'opts', 'mount', 'type', 'vfs', 'account', 'boot', 'check', 'free', 'nodename', 'quota', 'size', 'vol', 'log') @classmethod def dict_from_lines(cls, lines, keys=filesystems_keys): if len(lines) < 2: raise ValueError('Invalid number of lines: {0}'.format(lines)) if not keys: # if empty force default filesystems_keys keys = _FileSystemsEntry.filesystems_keys elif len(keys) < 6: raise ValueError('Invalid key name array: {0}'.format(keys)) blk_lines = lines orddict = OrderedDict() orddict['name'] = blk_lines[0].split(':')[0].strip() blk_lines.pop(0) for line in blk_lines: if line.startswith('#'): raise cls.ParseError("Comment!") comps = line.split('= ') if len(comps) != 2: raise cls.ParseError("Invalid Entry!") key_name = comps[0].strip() if key_name in keys: orddict[key_name] = comps[1].strip() else: raise ValueError('Invalid name for use in filesystems: {0}'.format(key_name)) return orddict @classmethod def dict_from_cmd_line(cls, ipargs, keys): cmdln_dict = ipargs if keys: for key, value in keys: # ignore unknown or local scope keys if key.startswith('__'): continue if key in _FileSystemsEntry.compatibility_keys: cmdln_dict[key] = value return cmdln_dict @classmethod def from_line(cls, *args, **kwargs): return cls(** cls.dict_from_cmd_line(*args, **kwargs)) @classmethod def dict_to_lines(cls, fsys_dict_entry): entry = fsys_dict_entry strg_out = entry['name'] + ':' + os.linesep for k, v in six.viewitems(entry): if 'name' not in k: strg_out += '\t{0}\t\t= {1}'.format(k, v) + os.linesep strg_out += os.linesep return six.text_type(strg_out) def dict_from_entry(self): ret = OrderedDict() ret[self.criteria['name']] = self.criteria return ret def __str__(self): ''' String value, only works for full repr ''' return self.dict_to_lines(self.criteria) def __repr__(self): ''' Always works ''' return repr(self.criteria) def pick(self, keys): ''' Returns an instance with just those keys ''' subset = dict([(key, self.criteria[key]) for key in keys]) return self.__class__(**subset) def __init__(self, **criteria): ''' Store non-empty, non-null values to use as filter ''' items = [key_value for key_value in six.iteritems(criteria) if key_value[1] is not None] items = [(key_value1[0], six.text_type(key_value1[1])) for key_value1 in items] self.criteria = OrderedDict(items) @staticmethod def norm_path(path): ''' Resolve equivalent paths equivalently ''' return os.path.normcase(os.path.normpath(path)) def match(self, fsys_view): ''' Compare potentially partial criteria against built filesystems entry dictionary ''' evalue_dict = fsys_view[1] for key, value in six.viewitems(self.criteria): if key in evalue_dict: if evalue_dict[key] != value: return False else: return False return True def __getitem__(self, key): ''' Return value for input key ''' return self.criteria[key] def fstab(config='/etc/fstab'): ''' .. versionchanged:: 2016.3.2 List the contents of the fstab CLI Example: .. code-block:: bash salt '*' mount.fstab ''' ret = {} if not os.path.isfile(config): return ret with salt.utils.files.fopen(config) as ifile: for line in ifile: line = salt.utils.stringutils.to_unicode(line) try: if __grains__['kernel'] == 'SunOS': # Note: comments use in default vfstab file! if line[0] == '#': continue entry = _vfstab_entry.dict_from_line( line) else: entry = _fstab_entry.dict_from_line( line, _fstab_entry.compatibility_keys) entry['opts'] = entry['opts'].split(',') while entry['name'] in ret: entry['name'] += '_' ret[entry.pop('name')] = entry except _fstab_entry.ParseError: pass except _vfstab_entry.ParseError: pass return ret def vfstab(config='/etc/vfstab'): ''' .. versionadded:: 2016.3.2 List the contents of the vfstab CLI Example: .. code-block:: bash salt '*' mount.vfstab ''' # NOTE: vfstab is a wrapper for fstab return fstab(config) def rm_fstab(name, device, config='/etc/fstab'): ''' .. versionchanged:: 2016.3.2 Remove the mount point from the fstab CLI Example: .. code-block:: bash salt '*' mount.rm_fstab /mnt/foo /dev/sdg ''' modified = False if __grains__['kernel'] == 'SunOS': criteria = _vfstab_entry(name=name, device=device) else: criteria = _fstab_entry(name=name, device=device) lines = [] try: with salt.utils.files.fopen(config, 'r') as ifile: for line in ifile: line = salt.utils.stringutils.to_unicode(line) try: if criteria.match(line): modified = True else: lines.append(line) except _fstab_entry.ParseError: lines.append(line) except _vfstab_entry.ParseError: lines.append(line) except (IOError, OSError) as exc: msg = "Couldn't read from {0}: {1}" raise CommandExecutionError(msg.format(config, exc)) if modified: try: with salt.utils.files.fopen(config, 'wb') as ofile: ofile.writelines(salt.utils.data.encode(lines)) except (IOError, OSError) as exc: msg = "Couldn't write to {0}: {1}" raise CommandExecutionError(msg.format(config, exc)) # Note: not clear why we always return 'True' # --just copying previous behavior at this point... return True def rm_vfstab(name, device, config='/etc/vfstab'): ''' .. versionadded:: 2016.3.2 Remove the mount point from the vfstab CLI Example: .. code-block:: bash salt '*' mount.rm_vfstab /mnt/foo /device/c0t0d0p0 ''' ## NOTE: rm_vfstab is a wrapper for rm_fstab return rm_fstab(name, device, config) def set_fstab( name, device, fstype, opts='defaults', dump=0, pass_num=0, config='/etc/fstab', test=False, match_on='auto', **kwargs): ''' Verify that this mount is represented in the fstab, change the mount to match the data passed, or add the mount if it is not present. CLI Example: .. code-block:: bash salt '*' mount.set_fstab /mnt/foo /dev/sdz1 ext4 ''' # Fix the opts type if it is a list if isinstance(opts, list): opts = ','.join(opts) # preserve arguments for updating entry_args = { 'name': name, 'device': device.replace('\\ ', '\\040'), 'fstype': fstype, 'opts': opts.replace('\\ ', '\\040'), 'dump': dump, 'pass_num': pass_num, } lines = [] ret = None # Transform match_on into list--items will be checked later if isinstance(match_on, list): pass elif not isinstance(match_on, six.string_types): msg = 'match_on must be a string or list of strings' raise CommandExecutionError(msg) elif match_on == 'auto': # Try to guess right criteria for auto.... # NOTE: missing some special fstypes here specialFSes = frozenset([ 'none', 'tmpfs', 'sysfs', 'proc', 'fusectl', 'debugfs', 'securityfs', 'devtmpfs', 'cgroup', 'btrfs']) if fstype in specialFSes: match_on = ['name'] else: match_on = ['device'] else: match_on = [match_on] # generate entry and criteria objects, handle invalid keys in match_on entry = _fstab_entry(**entry_args) try: criteria = entry.pick(match_on) except KeyError: filterFn = lambda key: key not in _fstab_entry.fstab_keys invalid_keys = filter(filterFn, match_on) msg = 'Unrecognized keys in match_on: "{0}"'.format(invalid_keys) raise CommandExecutionError(msg) # parse file, use ret to cache status if not os.path.isfile(config): raise CommandExecutionError('Bad config file "{0}"'.format(config)) try: with salt.utils.files.fopen(config, 'r') as ifile: for line in ifile: line = salt.utils.stringutils.to_unicode(line) try: if criteria.match(line): # Note: If ret isn't None here, # we've matched multiple lines ret = 'present' if entry.match(line): lines.append(line) else: ret = 'change' lines.append(six.text_type(entry)) else: lines.append(line) except _fstab_entry.ParseError: lines.append(line) except (IOError, OSError) as exc: msg = 'Couldn\'t read from {0}: {1}' raise CommandExecutionError(msg.format(config, exc)) # add line if not present or changed if ret is None: lines.append(six.text_type(entry)) ret = 'new' if ret != 'present': # ret in ['new', 'change']: if not salt.utils.args.test_mode(test=test, **kwargs): try: with salt.utils.files.fopen(config, 'wb') as ofile: # The line was changed, commit it! ofile.writelines(salt.utils.data.encode(lines)) except (IOError, OSError): msg = 'File not writable {0}' raise CommandExecutionError(msg.format(config)) return ret def set_vfstab( name, device, fstype, opts='-', device_fsck='-', pass_fsck='-', mount_at_boot='yes', config='/etc/vfstab', test=False, match_on='auto', **kwargs): ''' ..verionadded:: 2016.3.2 Verify that this mount is represented in the fstab, change the mount to match the data passed, or add the mount if it is not present. CLI Example: .. code-block:: bash salt '*' mount.set_vfstab /mnt/foo /device/c0t0d0p0 ufs ''' # Fix the opts type if it is a list if isinstance(opts, list): opts = ','.join(opts) # Map unknown values for mount_at_boot to no if mount_at_boot != 'yes': mount_at_boot = 'no' # preserve arguments for updating entry_args = { 'name': name, 'device': device, 'fstype': fstype, 'opts': opts, 'device_fsck': device_fsck, 'pass_fsck': pass_fsck, 'mount_at_boot': mount_at_boot, } lines = [] ret = None # Transform match_on into list--items will be checked later if isinstance(match_on, list): pass elif not isinstance(match_on, six.string_types): msg = 'match_on must be a string or list of strings' raise CommandExecutionError(msg) elif match_on == 'auto': # Try to guess right criteria for auto.... # NOTE: missing some special fstypes here specialFSes = frozenset([ 'devfs', 'proc', 'ctfs', 'objfs', 'sharefs', 'fs', 'tmpfs']) if fstype in specialFSes: match_on = ['name'] else: match_on = ['device'] else: match_on = [match_on] # generate entry and criteria objects, handle invalid keys in match_on entry = _vfstab_entry(**entry_args) try: criteria = entry.pick(match_on) except KeyError: filterFn = lambda key: key not in _vfstab_entry.vfstab_keys invalid_keys = filter(filterFn, match_on) msg = 'Unrecognized keys in match_on: "{0}"'.format(invalid_keys) raise CommandExecutionError(msg) # parse file, use ret to cache status if not os.path.isfile(config): raise CommandExecutionError('Bad config file "{0}"'.format(config)) try: with salt.utils.files.fopen(config, 'r') as ifile: for line in ifile: line = salt.utils.stringutils.to_unicode(line) try: if criteria.match(line): # Note: If ret isn't None here, # we've matched multiple lines ret = 'present' if entry.match(line): lines.append(line) else: ret = 'change' lines.append(six.text_type(entry)) else: lines.append(line) except _vfstab_entry.ParseError: lines.append(line) except (IOError, OSError) as exc: msg = 'Couldn\'t read from {0}: {1}' raise CommandExecutionError(msg.format(config, exc)) # add line if not present or changed if ret is None: lines.append(six.text_type(entry)) ret = 'new' if ret != 'present': # ret in ['new', 'change']: if not salt.utils.args.test_mode(test=test, **kwargs): try: with salt.utils.files.fopen(config, 'wb') as ofile: # The line was changed, commit it! ofile.writelines(salt.utils.data.encode(lines)) except (IOError, OSError): msg = 'File not writable {0}' raise CommandExecutionError(msg.format(config)) return ret def rm_automaster(name, device, config='/etc/auto_salt'): ''' Remove the mount point from the auto_master CLI Example: .. code-block:: bash salt '*' mount.rm_automaster /mnt/foo /dev/sdg ''' contents = automaster(config) if name not in contents: return True # The entry is present, get rid of it lines = [] try: with salt.utils.files.fopen(config, 'r') as ifile: for line in ifile: line = salt.utils.stringutils.to_unicode(line) if line.startswith('#'): # Commented lines.append(line) continue if not line.strip(): # Blank line lines.append(line) continue comps = line.split() if len(comps) != 3: # Invalid entry lines.append(line) continue comps = line.split() prefix = "/.." name_chk = comps[0].replace(prefix, "") device_fmt = comps[2].split(":") if device: if name_chk == name and device_fmt[1] == device: continue else: if name_chk == name: continue lines.append(line) except (IOError, OSError) as exc: msg = "Couldn't read from {0}: {1}" raise CommandExecutionError(msg.format(config, exc)) try: with salt.utils.files.fopen(config, 'wb') as ofile: ofile.writelines(salt.utils.data.encode(lines)) except (IOError, OSError) as exc: msg = "Couldn't write to {0}: {1}" raise CommandExecutionError(msg.format(config, exc)) # Update automount __salt__['cmd.run']('automount -cv') return True def set_automaster( name, device, fstype, opts='', config='/etc/auto_salt', test=False, **kwargs): ''' Verify that this mount is represented in the auto_salt, change the mount to match the data passed, or add the mount if it is not present. CLI Example: .. code-block:: bash salt '*' mount.set_automaster /mnt/foo /dev/sdz1 ext4 ''' # Fix the opts type if it is a list if isinstance(opts, list): opts = ','.join(opts) lines = [] change = False present = False automaster_file = "/etc/auto_master" if not os.path.isfile(config): __salt__['file.touch'](config) __salt__['file.append'](automaster_file, "/-\t\t\t{0}".format(config)) name = "/..{0}".format(name) device_fmt = "{0}:{1}".format(fstype, device) type_opts = "-fstype={0},{1}".format(fstype, opts) if fstype == 'smbfs': device_fmt = device_fmt.replace(fstype, "") try: with salt.utils.files.fopen(config, 'r') as ifile: for line in ifile: line = salt.utils.stringutils.to_unicode(line) if line.startswith('#'): # Commented lines.append(line) continue if not line.strip(): # Blank line lines.append(line) continue comps = line.split() if len(comps) != 3: # Invalid entry lines.append(line) continue if comps[0] == name or comps[2] == device_fmt: # check to see if there are changes # and fix them if there are any present = True if comps[0] != name: change = True comps[0] = name if comps[1] != type_opts: change = True comps[1] = type_opts if comps[2] != device_fmt: change = True comps[2] = device_fmt if change: log.debug( 'auto_master entry for mount point %s needs to be ' 'updated', name ) newline = ( '{0}\t{1}\t{2}\n'.format( name, type_opts, device_fmt) ) lines.append(newline) else: lines.append(line) except (IOError, OSError) as exc: msg = 'Couldn\'t read from {0}: {1}' raise CommandExecutionError(msg.format(config, exc)) if change: if not salt.utils.args.test_mode(test=test, **kwargs): try: with salt.utils.files.fopen(config, 'wb') as ofile: # The line was changed, commit it! ofile.writelines(salt.utils.data.encode(lines)) except (IOError, OSError): msg = 'File not writable {0}' raise CommandExecutionError(msg.format(config)) return 'change' if not change: if present: # The right entry is already here return 'present' else: if not salt.utils.args.test_mode(test=test, **kwargs): # The entry is new, add it to the end of the fstab newline = ( '{0}\t{1}\t{2}\n'.format( name, type_opts, device_fmt) ) lines.append(newline) try: with salt.utils.files.fopen(config, 'wb') as ofile: # The line was changed, commit it! ofile.writelines(salt.utils.data.encode(lines)) except (IOError, OSError): raise CommandExecutionError( 'File not writable {0}'.format( config ) ) return 'new' def automaster(config='/etc/auto_salt'): ''' List the contents of the auto master CLI Example: .. code-block:: bash salt '*' mount.automaster ''' ret = {} if not os.path.isfile(config): return ret with salt.utils.files.fopen(config) as ifile: for line in ifile: line = salt.utils.stringutils.to_unicode(line) if line.startswith('#'): # Commented continue if not line.strip(): # Blank line continue comps = line.split() if len(comps) != 3: # Invalid entry continue prefix = "/.." name = comps[0].replace(prefix, "") device_fmt = comps[2].split(":") opts = comps[1].split(',') ret[name] = {'device': device_fmt[1], 'fstype': opts[0], 'opts': opts[1:]} return ret def mount(name, device, mkmnt=False, fstype='', opts='defaults', user=None, util='mount'): ''' Mount a device CLI Example: .. code-block:: bash salt '*' mount.mount /mnt/foo /dev/sdz1 True ''' if util != 'mount': # This functionality used to live in img.mount_image if util == 'guestfs': return __salt__['guestfs.mount'](name, root=device) elif util == 'qemu_nbd': mnt = __salt__['qemu_nbd.init'](name, device) if not mnt: return False first = next(six.iterkeys(mnt)) __context__['img.mnt_{0}'.format(first)] = mnt return first return False # Darwin doesn't expect defaults when mounting without other options if 'defaults' in opts and __grains__['os'] in ['MacOS', 'Darwin', 'AIX']: opts = None if isinstance(opts, six.string_types): opts = opts.split(',') if not os.path.exists(name) and mkmnt: __salt__['file.mkdir'](name, user=user) args = '' if opts is not None: lopts = ','.join(opts) args = '-o {0}'.format(lopts) if fstype: # use of fstype on AIX differs from typical Linux use of -t # functionality AIX uses -v vfsname, -t fstype mounts all with # fstype in /etc/filesystems if 'AIX' in __grains__['os']: args += ' -v {0}'.format(fstype) elif 'solaris' in __grains__['os'].lower(): args += ' -F {0}'.format(fstype) else: args += ' -t {0}'.format(fstype) cmd = 'mount {0} {1} {2} '.format(args, device, name) out = __salt__['cmd.run_all'](cmd, runas=user, python_shell=False) if out['retcode']: return out['stderr'] return True def remount(name, device, mkmnt=False, fstype='', opts='defaults', user=None): ''' Attempt to remount a device, if the device is not already mounted, mount is called CLI Example: .. code-block:: bash salt '*' mount.remount /mnt/foo /dev/sdz1 True ''' force_mount = False if __grains__['os'] in ['MacOS', 'Darwin']: if opts == 'defaults': opts = 'noowners' if fstype == 'smbfs': force_mount = True if 'AIX' in __grains__['os']: if opts == 'defaults': opts = [] if isinstance(opts, six.string_types): opts = opts.split(',') mnts = active() if name in mnts: # The mount point is mounted, attempt to remount it with the given data if 'remount' not in opts and __grains__['os'] not in ['OpenBSD', 'MacOS', 'Darwin']: opts.append('remount') if force_mount: # We need to force the mount but first we should unmount umount(name, device, user=user) lopts = ','.join(opts) args = '-o {0}'.format(lopts) if fstype: # use of fstype on AIX differs from typical Linux use of # -t functionality AIX uses -v vfsname, -t fstype mounts # all with fstype in /etc/filesystems if 'AIX' in __grains__['os']: args += ' -v {0}'.format(fstype) elif 'solaris' in __grains__['os'].lower(): args += ' -F {0}'.format(fstype) else: args += ' -t {0}'.format(fstype) if __grains__['os'] not in ['OpenBSD', 'MacOS', 'Darwin'] or force_mount: cmd = 'mount {0} {1} {2} '.format(args, device, name) else: cmd = 'mount -u {0} {1} {2} '.format(args, device, name) out = __salt__['cmd.run_all'](cmd, runas=user, python_shell=False) if out['retcode']: return out['stderr'] return True # Mount a filesystem that isn't already return mount(name, device, mkmnt, fstype, opts, user=user) def umount(name, device=None, user=None, util='mount'): ''' Attempt to unmount a device by specifying the directory it is mounted on CLI Example: .. code-block:: bash salt '*' mount.umount /mnt/foo .. versionadded:: 2015.5.0 .. code-block:: bash salt '*' mount.umount /mnt/foo /dev/xvdc1 ''' if util != 'mount': # This functionality used to live in img.umount_image if 'qemu_nbd.clear' in __salt__: if 'img.mnt_{0}'.format(name) in __context__: __salt__['qemu_nbd.clear'](__context__['img.mnt_{0}'.format(name)]) return mnts = active() if name not in mnts: return "{0} does not have anything mounted".format(name) if not device: cmd = 'umount {0}'.format(name) else: cmd = 'umount {0}'.format(device) out = __salt__['cmd.run_all'](cmd, runas=user, python_shell=False) if out['retcode']: return out['stderr'] return True def is_fuse_exec(cmd): ''' Returns true if the command passed is a fuse mountable application. CLI Example: .. code-block:: bash salt '*' mount.is_fuse_exec sshfs ''' cmd_path = salt.utils.path.which(cmd) # No point in running ldd on a command that doesn't exist if not cmd_path: return False elif not salt.utils.path.which('ldd'): raise CommandNotFoundError('ldd') out = __salt__['cmd.run']('ldd {0}'.format(cmd_path), python_shell=False) return 'libfuse' in out def swaps(): ''' Return a dict containing information on active swap .. versionchanged:: 2016.3.2 CLI Example: .. code-block:: bash salt '*' mount.swaps ''' ret = {} if __grains__['kernel'] == 'SunOS': for line in __salt__['cmd.run_stdout']('swap -l').splitlines(): if line.startswith('swapfile'): continue comps = line.split() ret[comps[0]] = {'type': 'device' if comps[0].startswith(('/dev', 'swap')) else 'file', 'size': int(comps[3]), 'used': (int(comps[3]) - int(comps[4])), 'priority': '-'} elif 'AIX' in __grains__['kernel']: for line in __salt__['cmd.run_stdout']('swap -l').splitlines(): if line.startswith('device'): continue comps = line.split() # AIX uses MB for units ret[comps[0]] = {'type': 'device', 'size': int(comps[3][:-2]) * 1024, 'used': (int(comps[3][:-2]) - int(comps[4][:-2])) * 1024, 'priority': '-'} elif __grains__['os'] != 'OpenBSD': with salt.utils.files.fopen('/proc/swaps') as fp_: for line in fp_: line = salt.utils.stringutils.to_unicode(line) if line.startswith('Filename'): continue comps = line.split() ret[comps[0]] = {'type': comps[1], 'size': comps[2], 'used': comps[3], 'priority': comps[4]} else: for line in __salt__['cmd.run_stdout']('swapctl -kl').splitlines(): if line.startswith(('Device', 'Total')): continue swap_type = "file" comps = line.split() if comps[0].startswith('/dev/'): swap_type = "partition" ret[comps[0]] = {'type': swap_type, 'size': comps[1], 'used': comps[2], 'priority': comps[5]} return ret def swapon(name, priority=None): ''' Activate a swap disk .. versionchanged:: 2016.3.2 CLI Example: .. code-block:: bash salt '*' mount.swapon /root/swapfile ''' ret = {} on_ = swaps() if name in on_: ret['stats'] = on_[name] ret['new'] = False return ret if __grains__['kernel'] == 'SunOS': if __grains__['virtual'] != 'zone': __salt__['cmd.run']('swap -a {0}'.format(name), python_shell=False) else: return False else: cmd = 'swapon {0}'.format(name) if priority and 'AIX' not in __grains__['kernel']: cmd += ' -p {0}'.format(priority) __salt__['cmd.run'](cmd, python_shell=False) on_ = swaps() if name in on_: ret['stats'] = on_[name] ret['new'] = True return ret return ret def swapoff(name): ''' Deactivate a named swap mount .. versionchanged:: 2016.3.2 CLI Example: .. code-block:: bash salt '*' mount.swapoff /root/swapfile ''' on_ = swaps() if name in on_: if __grains__['kernel'] == 'SunOS': if __grains__['virtual'] != 'zone': __salt__['cmd.run']('swap -a {0}'.format(name), python_shell=False) else: return False elif __grains__['os'] != 'OpenBSD': __salt__['cmd.run']('swapoff {0}'.format(name), python_shell=False) else: __salt__['cmd.run']('swapctl -d {0}'.format(name), python_shell=False) on_ = swaps() if name in on_: return False return True return None def is_mounted(name): ''' .. versionadded:: 2014.7.0 Provide information if the path is mounted CLI Example: .. code-block:: bash salt '*' mount.is_mounted /mnt/share ''' active_ = active() if name in active_: return True else: return False def read_mount_cache(name): ''' .. versionadded:: 2018.3.0 Provide information if the path is mounted CLI Example: .. code-block:: bash salt '*' mount.read_mount_cache /mnt/share ''' cache = salt.utils.mount.read_cache(__opts__) if cache: if 'mounts' in cache and cache['mounts']: if name in cache['mounts']: return cache['mounts'][name] return {} def write_mount_cache(real_name, device, mkmnt, fstype, mount_opts): ''' .. versionadded:: 2018.3.0 Provide information if the path is mounted :param real_name: The real name of the mount point where the device is mounted. :param device: The device that is being mounted. :param mkmnt: Whether or not the mount point should be created. :param fstype: The file system that is used. :param mount_opts: Additional options used when mounting the device. :return: Boolean if message was sent successfully. CLI Example: .. code-block:: bash salt '*' mount.write_mount_cache /mnt/share /dev/sda1 False ext4 defaults,nosuid ''' cache = salt.utils.mount.read_cache(__opts__) if not cache: cache = {} cache['mounts'] = {} else: if 'mounts' not in cache: cache['mounts'] = {} cache['mounts'][real_name] = {'device': device, 'fstype': fstype, 'mkmnt': mkmnt, 'opts': mount_opts} cache_write = salt.utils.mount.write_cache(cache, __opts__) if cache_write: return True else: raise CommandExecutionError('Unable to write mount cache.') def delete_mount_cache(real_name): ''' .. versionadded:: 2018.3.0 Provide information if the path is mounted CLI Example: .. code-block:: bash salt '*' mount.delete_mount_cache /mnt/share ''' cache = salt.utils.mount.read_cache(__opts__) if cache: if 'mounts' in cache: if real_name in cache['mounts']: del cache['mounts'][real_name] cache_write = salt.utils.mount.write_cache(cache, __opts__) if not cache_write: raise CommandExecutionError('Unable to write mount cache.') return True def _filesystems(config='/etc/filesystems', leading_key=True): ''' Return the contents of the filesystems in an OrderedDict config File containing filesystem infomation leading_key True return dictionary keyed by 'name' and value as dictionary with other keys, values (name excluded) OrderedDict({ '/dir' : OrderedDict({'dev': '/dev/hd8', .... }})) False return dictionary keyed by 'name' and value as dictionary with all keys, values (name included) OrderedDict({ '/dir' : OrderedDict({'name': '/dir', 'dev': '/dev/hd8', ... })}) ''' ret = OrderedDict() lines = [] parsing_block = False if not os.path.isfile(config) or 'AIX' not in __grains__['kernel']: return ret # read in block of filesystems, block starts with '/' till empty line with salt.utils.files.fopen(config) as ifile: for line in ifile: line = salt.utils.stringutils.to_unicode(line) # skip till first entry if not line.startswith('/') and not parsing_block: continue if line.startswith('/'): parsing_block = True lines.append(line) elif not line.split(): parsing_block = False try: entry = _FileSystemsEntry.dict_from_lines( lines, _FileSystemsEntry.compatibility_keys) lines = [] if 'opts' in entry: entry['opts'] = entry['opts'].split(',') while entry['name'] in ret: entry['name'] += '_' if leading_key: ret[entry.pop('name')] = entry else: ret[entry['name']] = entry except _FileSystemsEntry.ParseError: pass else: lines.append(line) return ret def filesystems(config='/etc/filesystems'): ''' .. versionadded:: 2018.3.3 List the contents of the filesystems CLI Example: .. code-block:: bash salt '*' mount.filesystems ''' ret = {} if 'AIX' not in __grains__['kernel']: return ret ret_dict = _filesystems(config) if ret_dict: ret_key = next(iter(ret_dict.keys())) ret = {ret_key: dict(ret_dict[ret_key])} return ret def set_filesystems( name, device, vfstype, opts='-', mount='true', config='/etc/filesystems', test=False, match_on='auto', **kwargs): ''' .. versionadded:: 2018.3.3 Verify that this mount is represented in the filesystems, change the mount to match the data passed, or add the mount if it is not present on AIX Provide information if the path is mounted :param name: The name of the mount point where the device is mounted. :param device: The device that is being mounted. :param vfstype: The file system that is used (AIX has two fstypes, fstype and vfstype - similar to Linux fstype) :param opts: Additional options used when mounting the device. :param mount: Mount if not mounted, default True. :param config: Configuration file, default /etc/filesystems. :param match: File systems type to match on, default auto CLI Example: .. code-block:: bash salt '*' mount.set_filesystems /mnt/foo /dev/sdz1 jfs2 ''' # Fix the opts type if it is a list if isinstance(opts, list): opts = ','.join(opts) # preserve arguments for updating entry_args = { 'name': name, 'dev': device.replace('\\ ', '\\040'), 'vfstype': vfstype, 'opts': opts, 'mount': mount, } view_lines = [] ret = None if 'AIX' not in __grains__['kernel']: return ret # Transform match_on into list--items will be checked later if isinstance(match_on, list): pass elif not isinstance(match_on, six.string_types): raise CommandExecutionError('match_on must be a string or list of strings') elif match_on == 'auto': # Try to guess right criteria for auto.... # added IBM types from sys/vmount.h after btrfs # NOTE: missing some special fstypes here specialFSes = frozenset([ 'none', 'tmpfs', 'sysfs', 'proc', 'fusectl', 'debugfs', 'securityfs', 'devtmpfs', 'cgroup', 'btrfs', 'cdrfs', 'procfs', 'jfs', 'jfs2', 'nfs', 'sfs', 'nfs3', 'cachefs', 'udfs', 'cifs', 'namefs', 'pmemfs', 'ahafs', 'nfs4', 'autofs', 'stnfs']) if vfstype in specialFSes: match_on = ['name'] else: match_on = ['dev'] else: match_on = [match_on] # generate entry and criteria objects, handle invalid keys in match_on entry_ip = _FileSystemsEntry.from_line(entry_args, kwargs) try: criteria = entry_ip.pick(match_on) except KeyError: filterFn = lambda key: key not in _FileSystemsEntry.compatibility_keys invalid_keys = filter(filterFn, match_on) raise CommandExecutionError('Unrecognized keys in match_on: "{0}"'.format(invalid_keys)) # parse file, use ret to cache status if not os.path.isfile(config): raise CommandExecutionError('Bad config file "{0}"'.format(config)) # read in block of filesystem, block starts with '/' till empty line try: fsys_filedict = _filesystems(config, False) for fsys_view in six.viewitems(fsys_filedict): if criteria.match(fsys_view): ret = 'present' if entry_ip.match(fsys_view): view_lines.append(fsys_view) else: ret = 'change' kv = entry_ip['name'] view_lines.append((kv, entry_ip)) else: view_lines.append(fsys_view) except (IOError, OSError) as exc: raise CommandExecutionError('Couldn\'t read from {0}: {1}'.format(config, exc)) # add line if not present or changed if ret is None: for dict_view in six.viewitems(entry_ip.dict_from_entry()): view_lines.append(dict_view) ret = 'new' if ret != 'present': # ret in ['new', 'change']: try: with salt.utils.files.fopen(config, 'wb') as ofile: # The line was changed, commit it! for fsys_view in view_lines: entry = fsys_view[1] mystrg = _FileSystemsEntry.dict_to_lines(entry) ofile.writelines(salt.utils.data.encode(mystrg)) except (IOError, OSError): raise CommandExecutionError('File not writable {0}'.format(config)) return ret def rm_filesystems(name, device, config='/etc/filesystems'): ''' .. versionadded:: 2018.3.3 Remove the mount point from the filesystems CLI Example: .. code-block:: bash salt '*' mount.rm_filesystems /mnt/foo /dev/sdg ''' modified = False view_lines = [] if 'AIX' not in __grains__['kernel']: return modified criteria = _FileSystemsEntry(name=name, dev=device) try: fsys_filedict = _filesystems(config, False) for fsys_view in six.viewitems(fsys_filedict): try: if criteria.match(fsys_view): modified = True else: view_lines.append(fsys_view) except _FileSystemsEntry.ParseError: view_lines.append(fsys_view) except (IOError, OSError) as exc: raise CommandExecutionError("Couldn't read from {0}: {1}".format(config, exc)) if modified: try: with salt.utils.files.fopen(config, 'wb') as ofile: for fsys_view in view_lines: entry = fsys_view[1] mystrg = _FileSystemsEntry.dict_to_lines(entry) ofile.writelines(salt.utils.data.encode(mystrg)) except (IOError, OSError) as exc: raise CommandExecutionError("Couldn't write to {0}: {1}".format(config, exc)) return modified
saltstack/salt
salt/modules/mount.py
_resolve_user_group_names
python
def _resolve_user_group_names(opts): ''' Resolve user and group names in related opts ''' name_id_opts = {'uid': 'user.info', 'gid': 'group.info'} for ind, opt in enumerate(opts): if opt.split('=')[0] in name_id_opts: _givenid = opt.split('=')[1] _param = opt.split('=')[0] _id = _givenid if not re.match('[0-9]+$', _givenid): _info = __salt__[name_id_opts[_param]](_givenid) if _info and _param in _info: _id = _info[_param] opts[ind] = _param + '=' + six.text_type(_id) opts[ind] = opts[ind].replace('\\040', '\\ ') return opts
Resolve user and group names in related opts
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/mount.py#L215-L232
null
# -*- coding: utf-8 -*- ''' Salt module to manage Unix mounts and the fstab file ''' # Import python libs from __future__ import absolute_import, print_function, unicode_literals import os import re import logging # Import salt libs import salt.utils.args import salt.utils.data import salt.utils.files import salt.utils.path import salt.utils.platform import salt.utils.mount import salt.utils.stringutils from salt.utils.odict import OrderedDict from salt.exceptions import CommandNotFoundError, CommandExecutionError # Import 3rd-party libs from salt.ext import six from salt.ext.six.moves import filter, zip # pylint: disable=import-error,redefined-builtin # Set up logger log = logging.getLogger(__name__) # Define the module's virtual name __virtualname__ = 'mount' def __virtual__(): ''' Only load on POSIX-like systems ''' # Disable on Windows, a specific file module exists: if salt.utils.platform.is_windows(): return (False, 'The mount module cannot be loaded: not a POSIX-like system.') return True def _list_mounts(): ret = {} if __grains__['os'] in ['MacOS', 'Darwin']: mounts = __salt__['cmd.run_stdout']('mount') else: mounts = __salt__['cmd.run_stdout']('mount -l') for line in mounts.split('\n'): comps = re.sub(r"\s+", " ", line).split() if len(comps) >= 3: ret[comps[2]] = comps[0] return ret def _active_mountinfo(ret): _list = _list_mounts() filename = '/proc/self/mountinfo' if not os.access(filename, os.R_OK): msg = 'File not readable {0}' raise CommandExecutionError(msg.format(filename)) if 'disk.blkid' not in __context__: __context__['disk.blkid'] = __salt__['disk.blkid']() blkid_info = __context__['disk.blkid'] with salt.utils.files.fopen(filename) as ifile: for line in ifile: comps = salt.utils.stringutils.to_unicode(line).split() device = comps[2].split(':') # each line can have any number of # optional parameters, we use the # location of the separator field to # determine the location of the elements # after it. _sep = comps.index('-') device_name = comps[_sep + 2] device_uuid = None device_label = None if device_name: device_uuid = blkid_info.get(device_name, {}).get('UUID') device_uuid = device_uuid and device_uuid.lower() device_label = blkid_info.get(device_name, {}).get('LABEL') ret[comps[4]] = {'mountid': comps[0], 'parentid': comps[1], 'major': device[0], 'minor': device[1], 'root': comps[3], 'opts': _resolve_user_group_names(comps[5].split(',')), 'fstype': comps[_sep + 1], 'device': device_name.replace('\\040', '\\ '), 'alt_device': _list.get(comps[4], None), 'superopts': _resolve_user_group_names(comps[_sep + 3].split(',')), 'device_uuid': device_uuid, 'device_label': device_label} return ret def _active_mounts(ret): ''' List active mounts on Linux systems ''' _list = _list_mounts() filename = '/proc/self/mounts' if not os.access(filename, os.R_OK): msg = 'File not readable {0}' raise CommandExecutionError(msg.format(filename)) with salt.utils.files.fopen(filename) as ifile: for line in ifile: comps = salt.utils.stringutils.to_unicode(line).split() ret[comps[1]] = {'device': comps[0], 'alt_device': _list.get(comps[1], None), 'fstype': comps[2], 'opts': _resolve_user_group_names(comps[3].split(','))} return ret def _active_mounts_aix(ret): ''' List active mounts on AIX systems ''' for line in __salt__['cmd.run_stdout']('mount -p').split('\n'): comps = re.sub(r"\s+", " ", line).split() if comps: if comps[0] == 'node' or comps[0] == '--------': continue comps_len = len(comps) if line.startswith((' ', '\t')): curr_opts = _resolve_user_group_names(comps[6].split(',')) if 7 == comps_len else [] if curr_opts: ret[comps[1]] = {'device': comps[0], 'fstype': comps[2], 'opts': curr_opts} else: ret[comps[1]] = {'device': comps[0], 'fstype': comps[2]} else: curr_opts = _resolve_user_group_names(comps[7].split(',')) if 8 == comps_len else [] if curr_opts: ret[comps[2]] = {'node': comps[0], 'device': comps[1], 'fstype': comps[3], 'opts': curr_opts} else: ret[comps[2]] = {'node': comps[0], 'device': comps[1], 'fstype': comps[3]} return ret def _active_mounts_freebsd(ret): ''' List active mounts on FreeBSD systems ''' for line in __salt__['cmd.run_stdout']('mount -p').split('\n'): comps = re.sub(r"\s+", " ", line).split() ret[comps[1]] = {'device': comps[0], 'fstype': comps[2], 'opts': _resolve_user_group_names(comps[3].split(','))} return ret def _active_mounts_solaris(ret): ''' List active mounts on Solaris systems ''' for line in __salt__['cmd.run_stdout']('mount -v').split('\n'): comps = re.sub(r"\s+", " ", line).split() ret[comps[2]] = {'device': comps[0], 'fstype': comps[4], 'opts': _resolve_user_group_names(comps[5].split('/'))} return ret def _active_mounts_openbsd(ret): ''' List active mounts on OpenBSD systems ''' for line in __salt__['cmd.run_stdout']('mount -v').split('\n'): comps = re.sub(r"\s+", " ", line).split() parens = re.findall(r'\((.*?)\)', line, re.DOTALL) if len(parens) > 1: nod = __salt__['cmd.run_stdout']('ls -l {0}'.format(comps[0])) nod = ' '.join(nod.split()).split(" ") ret[comps[3]] = {'device': comps[0], 'fstype': comps[5], 'opts': _resolve_user_group_names(parens[1].split(", ")), 'major': six.text_type(nod[4].strip(",")), 'minor': six.text_type(nod[5]), 'device_uuid': parens[0]} else: ret[comps[2]] = {'device': comps[0], 'fstype': comps[4], 'opts': _resolve_user_group_names(parens[0].split(", "))} return ret def _active_mounts_darwin(ret): ''' List active mounts on Mac OS systems ''' for line in __salt__['cmd.run_stdout']('mount').split('\n'): comps = re.sub(r"\s+", " ", line).split() parens = re.findall(r'\((.*?)\)', line, re.DOTALL)[0].split(", ") ret[comps[2]] = {'device': comps[0], 'fstype': parens[0], 'opts': _resolve_user_group_names(parens[1:])} return ret def active(extended=False): ''' List the active mounts. CLI Example: .. code-block:: bash salt '*' mount.active ''' ret = {} if __grains__['os'] == 'FreeBSD': _active_mounts_freebsd(ret) elif 'AIX' in __grains__['kernel']: _active_mounts_aix(ret) elif __grains__['kernel'] == 'SunOS': _active_mounts_solaris(ret) elif __grains__['os'] == 'OpenBSD': _active_mounts_openbsd(ret) elif __grains__['os'] in ['MacOS', 'Darwin']: _active_mounts_darwin(ret) else: if extended: try: _active_mountinfo(ret) except CommandExecutionError: _active_mounts(ret) else: _active_mounts(ret) return ret class _fstab_entry(object): ''' Utility class for manipulating fstab entries. Primarily we're parsing, formatting, and comparing lines. Parsing emits dicts expected from fstab() or raises a ValueError. Note: We'll probably want to use os.normpath and os.normcase on 'name' ''' class ParseError(ValueError): ''' Error raised when a line isn't parsible as an fstab entry ''' fstab_keys = ('device', 'name', 'fstype', 'opts', 'dump', 'pass_num') # preserve data format compatibility_keys = ('device', 'name', 'fstype', 'opts', 'dump', 'pass') fstab_format = '{device}\t\t{name}\t{fstype}\t{opts}\t{dump} {pass_num}\n' @classmethod def dict_from_line(cls, line, keys=fstab_keys): if len(keys) != 6: raise ValueError('Invalid key array: {0}'.format(keys)) if line.startswith('#'): raise cls.ParseError("Comment!") comps = line.split() if len(comps) < 4 or len(comps) > 6: raise cls.ParseError("Invalid Entry!") comps.extend(['0'] * (len(keys) - len(comps))) return dict(zip(keys, comps)) @classmethod def from_line(cls, *args, **kwargs): return cls(** cls.dict_from_line(*args, **kwargs)) @classmethod def dict_to_line(cls, entry): return cls.fstab_format.format(**entry) def __str__(self): ''' String value, only works for full repr ''' return self.dict_to_line(self.criteria) def __repr__(self): ''' Always works ''' return repr(self.criteria) def pick(self, keys): ''' Returns an instance with just those keys ''' subset = dict([(key, self.criteria[key]) for key in keys]) return self.__class__(**subset) def __init__(self, **criteria): ''' Store non-empty, non-null values to use as filter ''' items = [key_value for key_value in six.iteritems(criteria) if key_value[1] is not None] items = [(key_value1[0], six.text_type(key_value1[1])) for key_value1 in items] self.criteria = dict(items) @staticmethod def norm_path(path): ''' Resolve equivalent paths equivalently ''' return os.path.normcase(os.path.normpath(path)) def match(self, line): ''' Compare potentially partial criteria against line ''' entry = self.dict_from_line(line) for key, value in six.iteritems(self.criteria): if entry[key] != value: return False return True class _vfstab_entry(object): ''' Utility class for manipulating vfstab entries. Primarily we're parsing, formatting, and comparing lines. Parsing emits dicts expected from fstab() or raises a ValueError. Note: We'll probably want to use os.normpath and os.normcase on 'name' Note: This parses vfstab entries on Solaris like systems #device device mount FS fsck mount mount #to mount to fsck point type pass at boot options # /devices - /devices devfs - no - ''' class ParseError(ValueError): '''Error raised when a line isn't parsible as an fstab entry''' vfstab_keys = ('device', 'device_fsck', 'name', 'fstype', 'pass_fsck', 'mount_at_boot', 'opts') # NOTE: weird formatting to match default spacing on Solaris vfstab_format = '{device:<11} {device_fsck:<3} {name:<19} {fstype:<8} {pass_fsck:<3} {mount_at_boot:<6} {opts}\n' @classmethod def dict_from_line(cls, line): if line.startswith('#'): raise cls.ParseError("Comment!") comps = line.split() if len(comps) != 7: raise cls.ParseError("Invalid Entry!") return dict(zip(cls.vfstab_keys, comps)) @classmethod def from_line(cls, *args, **kwargs): return cls(** cls.dict_from_line(*args, **kwargs)) @classmethod def dict_to_line(cls, entry): return cls.vfstab_format.format(**entry) def __str__(self): ''' String value, only works for full repr ''' return self.dict_to_line(self.criteria) def __repr__(self): ''' Always works ''' return repr(self.criteria) def pick(self, keys): ''' Returns an instance with just those keys ''' subset = dict([(key, self.criteria[key]) for key in keys]) return self.__class__(**subset) def __init__(self, **criteria): ''' Store non-empty, non-null values to use as filter ''' items = [key_value for key_value in six.iteritems(criteria) if key_value[1] is not None] items = [(key_value1[0], six.text_type(key_value1[1])) for key_value1 in items] self.criteria = dict(items) @staticmethod def norm_path(path): ''' Resolve equivalent paths equivalently ''' return os.path.normcase(os.path.normpath(path)) def match(self, line): ''' Compare potentially partial criteria against line ''' entry = self.dict_from_line(line) for key, value in six.iteritems(self.criteria): if entry[key] != value: return False return True class _FileSystemsEntry(object): ''' Utility class for manipulating filesystem entries. Primarily we're parsing, formatting, and comparing lines. Parsing emits dicts expected from fstab() or raises a ValueError. Note: We'll probably want to use os.normpath and os.normcase on 'name' ''' class ParseError(ValueError): ''' Error raised when a line isn't parsible as an fstab entry ''' filesystems_keys = ('device', 'name', 'fstype', 'vfstype', 'opts', 'mount') # preserve data format of filesystems compatibility_keys = ('dev', 'dev', 'name', 'fstype', 'vfstype', 'opts', 'mount', 'type', 'vfs', 'account', 'boot', 'check', 'free', 'nodename', 'quota', 'size', 'vol', 'log') @classmethod def dict_from_lines(cls, lines, keys=filesystems_keys): if len(lines) < 2: raise ValueError('Invalid number of lines: {0}'.format(lines)) if not keys: # if empty force default filesystems_keys keys = _FileSystemsEntry.filesystems_keys elif len(keys) < 6: raise ValueError('Invalid key name array: {0}'.format(keys)) blk_lines = lines orddict = OrderedDict() orddict['name'] = blk_lines[0].split(':')[0].strip() blk_lines.pop(0) for line in blk_lines: if line.startswith('#'): raise cls.ParseError("Comment!") comps = line.split('= ') if len(comps) != 2: raise cls.ParseError("Invalid Entry!") key_name = comps[0].strip() if key_name in keys: orddict[key_name] = comps[1].strip() else: raise ValueError('Invalid name for use in filesystems: {0}'.format(key_name)) return orddict @classmethod def dict_from_cmd_line(cls, ipargs, keys): cmdln_dict = ipargs if keys: for key, value in keys: # ignore unknown or local scope keys if key.startswith('__'): continue if key in _FileSystemsEntry.compatibility_keys: cmdln_dict[key] = value return cmdln_dict @classmethod def from_line(cls, *args, **kwargs): return cls(** cls.dict_from_cmd_line(*args, **kwargs)) @classmethod def dict_to_lines(cls, fsys_dict_entry): entry = fsys_dict_entry strg_out = entry['name'] + ':' + os.linesep for k, v in six.viewitems(entry): if 'name' not in k: strg_out += '\t{0}\t\t= {1}'.format(k, v) + os.linesep strg_out += os.linesep return six.text_type(strg_out) def dict_from_entry(self): ret = OrderedDict() ret[self.criteria['name']] = self.criteria return ret def __str__(self): ''' String value, only works for full repr ''' return self.dict_to_lines(self.criteria) def __repr__(self): ''' Always works ''' return repr(self.criteria) def pick(self, keys): ''' Returns an instance with just those keys ''' subset = dict([(key, self.criteria[key]) for key in keys]) return self.__class__(**subset) def __init__(self, **criteria): ''' Store non-empty, non-null values to use as filter ''' items = [key_value for key_value in six.iteritems(criteria) if key_value[1] is not None] items = [(key_value1[0], six.text_type(key_value1[1])) for key_value1 in items] self.criteria = OrderedDict(items) @staticmethod def norm_path(path): ''' Resolve equivalent paths equivalently ''' return os.path.normcase(os.path.normpath(path)) def match(self, fsys_view): ''' Compare potentially partial criteria against built filesystems entry dictionary ''' evalue_dict = fsys_view[1] for key, value in six.viewitems(self.criteria): if key in evalue_dict: if evalue_dict[key] != value: return False else: return False return True def __getitem__(self, key): ''' Return value for input key ''' return self.criteria[key] def fstab(config='/etc/fstab'): ''' .. versionchanged:: 2016.3.2 List the contents of the fstab CLI Example: .. code-block:: bash salt '*' mount.fstab ''' ret = {} if not os.path.isfile(config): return ret with salt.utils.files.fopen(config) as ifile: for line in ifile: line = salt.utils.stringutils.to_unicode(line) try: if __grains__['kernel'] == 'SunOS': # Note: comments use in default vfstab file! if line[0] == '#': continue entry = _vfstab_entry.dict_from_line( line) else: entry = _fstab_entry.dict_from_line( line, _fstab_entry.compatibility_keys) entry['opts'] = entry['opts'].split(',') while entry['name'] in ret: entry['name'] += '_' ret[entry.pop('name')] = entry except _fstab_entry.ParseError: pass except _vfstab_entry.ParseError: pass return ret def vfstab(config='/etc/vfstab'): ''' .. versionadded:: 2016.3.2 List the contents of the vfstab CLI Example: .. code-block:: bash salt '*' mount.vfstab ''' # NOTE: vfstab is a wrapper for fstab return fstab(config) def rm_fstab(name, device, config='/etc/fstab'): ''' .. versionchanged:: 2016.3.2 Remove the mount point from the fstab CLI Example: .. code-block:: bash salt '*' mount.rm_fstab /mnt/foo /dev/sdg ''' modified = False if __grains__['kernel'] == 'SunOS': criteria = _vfstab_entry(name=name, device=device) else: criteria = _fstab_entry(name=name, device=device) lines = [] try: with salt.utils.files.fopen(config, 'r') as ifile: for line in ifile: line = salt.utils.stringutils.to_unicode(line) try: if criteria.match(line): modified = True else: lines.append(line) except _fstab_entry.ParseError: lines.append(line) except _vfstab_entry.ParseError: lines.append(line) except (IOError, OSError) as exc: msg = "Couldn't read from {0}: {1}" raise CommandExecutionError(msg.format(config, exc)) if modified: try: with salt.utils.files.fopen(config, 'wb') as ofile: ofile.writelines(salt.utils.data.encode(lines)) except (IOError, OSError) as exc: msg = "Couldn't write to {0}: {1}" raise CommandExecutionError(msg.format(config, exc)) # Note: not clear why we always return 'True' # --just copying previous behavior at this point... return True def rm_vfstab(name, device, config='/etc/vfstab'): ''' .. versionadded:: 2016.3.2 Remove the mount point from the vfstab CLI Example: .. code-block:: bash salt '*' mount.rm_vfstab /mnt/foo /device/c0t0d0p0 ''' ## NOTE: rm_vfstab is a wrapper for rm_fstab return rm_fstab(name, device, config) def set_fstab( name, device, fstype, opts='defaults', dump=0, pass_num=0, config='/etc/fstab', test=False, match_on='auto', **kwargs): ''' Verify that this mount is represented in the fstab, change the mount to match the data passed, or add the mount if it is not present. CLI Example: .. code-block:: bash salt '*' mount.set_fstab /mnt/foo /dev/sdz1 ext4 ''' # Fix the opts type if it is a list if isinstance(opts, list): opts = ','.join(opts) # preserve arguments for updating entry_args = { 'name': name, 'device': device.replace('\\ ', '\\040'), 'fstype': fstype, 'opts': opts.replace('\\ ', '\\040'), 'dump': dump, 'pass_num': pass_num, } lines = [] ret = None # Transform match_on into list--items will be checked later if isinstance(match_on, list): pass elif not isinstance(match_on, six.string_types): msg = 'match_on must be a string or list of strings' raise CommandExecutionError(msg) elif match_on == 'auto': # Try to guess right criteria for auto.... # NOTE: missing some special fstypes here specialFSes = frozenset([ 'none', 'tmpfs', 'sysfs', 'proc', 'fusectl', 'debugfs', 'securityfs', 'devtmpfs', 'cgroup', 'btrfs']) if fstype in specialFSes: match_on = ['name'] else: match_on = ['device'] else: match_on = [match_on] # generate entry and criteria objects, handle invalid keys in match_on entry = _fstab_entry(**entry_args) try: criteria = entry.pick(match_on) except KeyError: filterFn = lambda key: key not in _fstab_entry.fstab_keys invalid_keys = filter(filterFn, match_on) msg = 'Unrecognized keys in match_on: "{0}"'.format(invalid_keys) raise CommandExecutionError(msg) # parse file, use ret to cache status if not os.path.isfile(config): raise CommandExecutionError('Bad config file "{0}"'.format(config)) try: with salt.utils.files.fopen(config, 'r') as ifile: for line in ifile: line = salt.utils.stringutils.to_unicode(line) try: if criteria.match(line): # Note: If ret isn't None here, # we've matched multiple lines ret = 'present' if entry.match(line): lines.append(line) else: ret = 'change' lines.append(six.text_type(entry)) else: lines.append(line) except _fstab_entry.ParseError: lines.append(line) except (IOError, OSError) as exc: msg = 'Couldn\'t read from {0}: {1}' raise CommandExecutionError(msg.format(config, exc)) # add line if not present or changed if ret is None: lines.append(six.text_type(entry)) ret = 'new' if ret != 'present': # ret in ['new', 'change']: if not salt.utils.args.test_mode(test=test, **kwargs): try: with salt.utils.files.fopen(config, 'wb') as ofile: # The line was changed, commit it! ofile.writelines(salt.utils.data.encode(lines)) except (IOError, OSError): msg = 'File not writable {0}' raise CommandExecutionError(msg.format(config)) return ret def set_vfstab( name, device, fstype, opts='-', device_fsck='-', pass_fsck='-', mount_at_boot='yes', config='/etc/vfstab', test=False, match_on='auto', **kwargs): ''' ..verionadded:: 2016.3.2 Verify that this mount is represented in the fstab, change the mount to match the data passed, or add the mount if it is not present. CLI Example: .. code-block:: bash salt '*' mount.set_vfstab /mnt/foo /device/c0t0d0p0 ufs ''' # Fix the opts type if it is a list if isinstance(opts, list): opts = ','.join(opts) # Map unknown values for mount_at_boot to no if mount_at_boot != 'yes': mount_at_boot = 'no' # preserve arguments for updating entry_args = { 'name': name, 'device': device, 'fstype': fstype, 'opts': opts, 'device_fsck': device_fsck, 'pass_fsck': pass_fsck, 'mount_at_boot': mount_at_boot, } lines = [] ret = None # Transform match_on into list--items will be checked later if isinstance(match_on, list): pass elif not isinstance(match_on, six.string_types): msg = 'match_on must be a string or list of strings' raise CommandExecutionError(msg) elif match_on == 'auto': # Try to guess right criteria for auto.... # NOTE: missing some special fstypes here specialFSes = frozenset([ 'devfs', 'proc', 'ctfs', 'objfs', 'sharefs', 'fs', 'tmpfs']) if fstype in specialFSes: match_on = ['name'] else: match_on = ['device'] else: match_on = [match_on] # generate entry and criteria objects, handle invalid keys in match_on entry = _vfstab_entry(**entry_args) try: criteria = entry.pick(match_on) except KeyError: filterFn = lambda key: key not in _vfstab_entry.vfstab_keys invalid_keys = filter(filterFn, match_on) msg = 'Unrecognized keys in match_on: "{0}"'.format(invalid_keys) raise CommandExecutionError(msg) # parse file, use ret to cache status if not os.path.isfile(config): raise CommandExecutionError('Bad config file "{0}"'.format(config)) try: with salt.utils.files.fopen(config, 'r') as ifile: for line in ifile: line = salt.utils.stringutils.to_unicode(line) try: if criteria.match(line): # Note: If ret isn't None here, # we've matched multiple lines ret = 'present' if entry.match(line): lines.append(line) else: ret = 'change' lines.append(six.text_type(entry)) else: lines.append(line) except _vfstab_entry.ParseError: lines.append(line) except (IOError, OSError) as exc: msg = 'Couldn\'t read from {0}: {1}' raise CommandExecutionError(msg.format(config, exc)) # add line if not present or changed if ret is None: lines.append(six.text_type(entry)) ret = 'new' if ret != 'present': # ret in ['new', 'change']: if not salt.utils.args.test_mode(test=test, **kwargs): try: with salt.utils.files.fopen(config, 'wb') as ofile: # The line was changed, commit it! ofile.writelines(salt.utils.data.encode(lines)) except (IOError, OSError): msg = 'File not writable {0}' raise CommandExecutionError(msg.format(config)) return ret def rm_automaster(name, device, config='/etc/auto_salt'): ''' Remove the mount point from the auto_master CLI Example: .. code-block:: bash salt '*' mount.rm_automaster /mnt/foo /dev/sdg ''' contents = automaster(config) if name not in contents: return True # The entry is present, get rid of it lines = [] try: with salt.utils.files.fopen(config, 'r') as ifile: for line in ifile: line = salt.utils.stringutils.to_unicode(line) if line.startswith('#'): # Commented lines.append(line) continue if not line.strip(): # Blank line lines.append(line) continue comps = line.split() if len(comps) != 3: # Invalid entry lines.append(line) continue comps = line.split() prefix = "/.." name_chk = comps[0].replace(prefix, "") device_fmt = comps[2].split(":") if device: if name_chk == name and device_fmt[1] == device: continue else: if name_chk == name: continue lines.append(line) except (IOError, OSError) as exc: msg = "Couldn't read from {0}: {1}" raise CommandExecutionError(msg.format(config, exc)) try: with salt.utils.files.fopen(config, 'wb') as ofile: ofile.writelines(salt.utils.data.encode(lines)) except (IOError, OSError) as exc: msg = "Couldn't write to {0}: {1}" raise CommandExecutionError(msg.format(config, exc)) # Update automount __salt__['cmd.run']('automount -cv') return True def set_automaster( name, device, fstype, opts='', config='/etc/auto_salt', test=False, **kwargs): ''' Verify that this mount is represented in the auto_salt, change the mount to match the data passed, or add the mount if it is not present. CLI Example: .. code-block:: bash salt '*' mount.set_automaster /mnt/foo /dev/sdz1 ext4 ''' # Fix the opts type if it is a list if isinstance(opts, list): opts = ','.join(opts) lines = [] change = False present = False automaster_file = "/etc/auto_master" if not os.path.isfile(config): __salt__['file.touch'](config) __salt__['file.append'](automaster_file, "/-\t\t\t{0}".format(config)) name = "/..{0}".format(name) device_fmt = "{0}:{1}".format(fstype, device) type_opts = "-fstype={0},{1}".format(fstype, opts) if fstype == 'smbfs': device_fmt = device_fmt.replace(fstype, "") try: with salt.utils.files.fopen(config, 'r') as ifile: for line in ifile: line = salt.utils.stringutils.to_unicode(line) if line.startswith('#'): # Commented lines.append(line) continue if not line.strip(): # Blank line lines.append(line) continue comps = line.split() if len(comps) != 3: # Invalid entry lines.append(line) continue if comps[0] == name or comps[2] == device_fmt: # check to see if there are changes # and fix them if there are any present = True if comps[0] != name: change = True comps[0] = name if comps[1] != type_opts: change = True comps[1] = type_opts if comps[2] != device_fmt: change = True comps[2] = device_fmt if change: log.debug( 'auto_master entry for mount point %s needs to be ' 'updated', name ) newline = ( '{0}\t{1}\t{2}\n'.format( name, type_opts, device_fmt) ) lines.append(newline) else: lines.append(line) except (IOError, OSError) as exc: msg = 'Couldn\'t read from {0}: {1}' raise CommandExecutionError(msg.format(config, exc)) if change: if not salt.utils.args.test_mode(test=test, **kwargs): try: with salt.utils.files.fopen(config, 'wb') as ofile: # The line was changed, commit it! ofile.writelines(salt.utils.data.encode(lines)) except (IOError, OSError): msg = 'File not writable {0}' raise CommandExecutionError(msg.format(config)) return 'change' if not change: if present: # The right entry is already here return 'present' else: if not salt.utils.args.test_mode(test=test, **kwargs): # The entry is new, add it to the end of the fstab newline = ( '{0}\t{1}\t{2}\n'.format( name, type_opts, device_fmt) ) lines.append(newline) try: with salt.utils.files.fopen(config, 'wb') as ofile: # The line was changed, commit it! ofile.writelines(salt.utils.data.encode(lines)) except (IOError, OSError): raise CommandExecutionError( 'File not writable {0}'.format( config ) ) return 'new' def automaster(config='/etc/auto_salt'): ''' List the contents of the auto master CLI Example: .. code-block:: bash salt '*' mount.automaster ''' ret = {} if not os.path.isfile(config): return ret with salt.utils.files.fopen(config) as ifile: for line in ifile: line = salt.utils.stringutils.to_unicode(line) if line.startswith('#'): # Commented continue if not line.strip(): # Blank line continue comps = line.split() if len(comps) != 3: # Invalid entry continue prefix = "/.." name = comps[0].replace(prefix, "") device_fmt = comps[2].split(":") opts = comps[1].split(',') ret[name] = {'device': device_fmt[1], 'fstype': opts[0], 'opts': opts[1:]} return ret def mount(name, device, mkmnt=False, fstype='', opts='defaults', user=None, util='mount'): ''' Mount a device CLI Example: .. code-block:: bash salt '*' mount.mount /mnt/foo /dev/sdz1 True ''' if util != 'mount': # This functionality used to live in img.mount_image if util == 'guestfs': return __salt__['guestfs.mount'](name, root=device) elif util == 'qemu_nbd': mnt = __salt__['qemu_nbd.init'](name, device) if not mnt: return False first = next(six.iterkeys(mnt)) __context__['img.mnt_{0}'.format(first)] = mnt return first return False # Darwin doesn't expect defaults when mounting without other options if 'defaults' in opts and __grains__['os'] in ['MacOS', 'Darwin', 'AIX']: opts = None if isinstance(opts, six.string_types): opts = opts.split(',') if not os.path.exists(name) and mkmnt: __salt__['file.mkdir'](name, user=user) args = '' if opts is not None: lopts = ','.join(opts) args = '-o {0}'.format(lopts) if fstype: # use of fstype on AIX differs from typical Linux use of -t # functionality AIX uses -v vfsname, -t fstype mounts all with # fstype in /etc/filesystems if 'AIX' in __grains__['os']: args += ' -v {0}'.format(fstype) elif 'solaris' in __grains__['os'].lower(): args += ' -F {0}'.format(fstype) else: args += ' -t {0}'.format(fstype) cmd = 'mount {0} {1} {2} '.format(args, device, name) out = __salt__['cmd.run_all'](cmd, runas=user, python_shell=False) if out['retcode']: return out['stderr'] return True def remount(name, device, mkmnt=False, fstype='', opts='defaults', user=None): ''' Attempt to remount a device, if the device is not already mounted, mount is called CLI Example: .. code-block:: bash salt '*' mount.remount /mnt/foo /dev/sdz1 True ''' force_mount = False if __grains__['os'] in ['MacOS', 'Darwin']: if opts == 'defaults': opts = 'noowners' if fstype == 'smbfs': force_mount = True if 'AIX' in __grains__['os']: if opts == 'defaults': opts = [] if isinstance(opts, six.string_types): opts = opts.split(',') mnts = active() if name in mnts: # The mount point is mounted, attempt to remount it with the given data if 'remount' not in opts and __grains__['os'] not in ['OpenBSD', 'MacOS', 'Darwin']: opts.append('remount') if force_mount: # We need to force the mount but first we should unmount umount(name, device, user=user) lopts = ','.join(opts) args = '-o {0}'.format(lopts) if fstype: # use of fstype on AIX differs from typical Linux use of # -t functionality AIX uses -v vfsname, -t fstype mounts # all with fstype in /etc/filesystems if 'AIX' in __grains__['os']: args += ' -v {0}'.format(fstype) elif 'solaris' in __grains__['os'].lower(): args += ' -F {0}'.format(fstype) else: args += ' -t {0}'.format(fstype) if __grains__['os'] not in ['OpenBSD', 'MacOS', 'Darwin'] or force_mount: cmd = 'mount {0} {1} {2} '.format(args, device, name) else: cmd = 'mount -u {0} {1} {2} '.format(args, device, name) out = __salt__['cmd.run_all'](cmd, runas=user, python_shell=False) if out['retcode']: return out['stderr'] return True # Mount a filesystem that isn't already return mount(name, device, mkmnt, fstype, opts, user=user) def umount(name, device=None, user=None, util='mount'): ''' Attempt to unmount a device by specifying the directory it is mounted on CLI Example: .. code-block:: bash salt '*' mount.umount /mnt/foo .. versionadded:: 2015.5.0 .. code-block:: bash salt '*' mount.umount /mnt/foo /dev/xvdc1 ''' if util != 'mount': # This functionality used to live in img.umount_image if 'qemu_nbd.clear' in __salt__: if 'img.mnt_{0}'.format(name) in __context__: __salt__['qemu_nbd.clear'](__context__['img.mnt_{0}'.format(name)]) return mnts = active() if name not in mnts: return "{0} does not have anything mounted".format(name) if not device: cmd = 'umount {0}'.format(name) else: cmd = 'umount {0}'.format(device) out = __salt__['cmd.run_all'](cmd, runas=user, python_shell=False) if out['retcode']: return out['stderr'] return True def is_fuse_exec(cmd): ''' Returns true if the command passed is a fuse mountable application. CLI Example: .. code-block:: bash salt '*' mount.is_fuse_exec sshfs ''' cmd_path = salt.utils.path.which(cmd) # No point in running ldd on a command that doesn't exist if not cmd_path: return False elif not salt.utils.path.which('ldd'): raise CommandNotFoundError('ldd') out = __salt__['cmd.run']('ldd {0}'.format(cmd_path), python_shell=False) return 'libfuse' in out def swaps(): ''' Return a dict containing information on active swap .. versionchanged:: 2016.3.2 CLI Example: .. code-block:: bash salt '*' mount.swaps ''' ret = {} if __grains__['kernel'] == 'SunOS': for line in __salt__['cmd.run_stdout']('swap -l').splitlines(): if line.startswith('swapfile'): continue comps = line.split() ret[comps[0]] = {'type': 'device' if comps[0].startswith(('/dev', 'swap')) else 'file', 'size': int(comps[3]), 'used': (int(comps[3]) - int(comps[4])), 'priority': '-'} elif 'AIX' in __grains__['kernel']: for line in __salt__['cmd.run_stdout']('swap -l').splitlines(): if line.startswith('device'): continue comps = line.split() # AIX uses MB for units ret[comps[0]] = {'type': 'device', 'size': int(comps[3][:-2]) * 1024, 'used': (int(comps[3][:-2]) - int(comps[4][:-2])) * 1024, 'priority': '-'} elif __grains__['os'] != 'OpenBSD': with salt.utils.files.fopen('/proc/swaps') as fp_: for line in fp_: line = salt.utils.stringutils.to_unicode(line) if line.startswith('Filename'): continue comps = line.split() ret[comps[0]] = {'type': comps[1], 'size': comps[2], 'used': comps[3], 'priority': comps[4]} else: for line in __salt__['cmd.run_stdout']('swapctl -kl').splitlines(): if line.startswith(('Device', 'Total')): continue swap_type = "file" comps = line.split() if comps[0].startswith('/dev/'): swap_type = "partition" ret[comps[0]] = {'type': swap_type, 'size': comps[1], 'used': comps[2], 'priority': comps[5]} return ret def swapon(name, priority=None): ''' Activate a swap disk .. versionchanged:: 2016.3.2 CLI Example: .. code-block:: bash salt '*' mount.swapon /root/swapfile ''' ret = {} on_ = swaps() if name in on_: ret['stats'] = on_[name] ret['new'] = False return ret if __grains__['kernel'] == 'SunOS': if __grains__['virtual'] != 'zone': __salt__['cmd.run']('swap -a {0}'.format(name), python_shell=False) else: return False else: cmd = 'swapon {0}'.format(name) if priority and 'AIX' not in __grains__['kernel']: cmd += ' -p {0}'.format(priority) __salt__['cmd.run'](cmd, python_shell=False) on_ = swaps() if name in on_: ret['stats'] = on_[name] ret['new'] = True return ret return ret def swapoff(name): ''' Deactivate a named swap mount .. versionchanged:: 2016.3.2 CLI Example: .. code-block:: bash salt '*' mount.swapoff /root/swapfile ''' on_ = swaps() if name in on_: if __grains__['kernel'] == 'SunOS': if __grains__['virtual'] != 'zone': __salt__['cmd.run']('swap -a {0}'.format(name), python_shell=False) else: return False elif __grains__['os'] != 'OpenBSD': __salt__['cmd.run']('swapoff {0}'.format(name), python_shell=False) else: __salt__['cmd.run']('swapctl -d {0}'.format(name), python_shell=False) on_ = swaps() if name in on_: return False return True return None def is_mounted(name): ''' .. versionadded:: 2014.7.0 Provide information if the path is mounted CLI Example: .. code-block:: bash salt '*' mount.is_mounted /mnt/share ''' active_ = active() if name in active_: return True else: return False def read_mount_cache(name): ''' .. versionadded:: 2018.3.0 Provide information if the path is mounted CLI Example: .. code-block:: bash salt '*' mount.read_mount_cache /mnt/share ''' cache = salt.utils.mount.read_cache(__opts__) if cache: if 'mounts' in cache and cache['mounts']: if name in cache['mounts']: return cache['mounts'][name] return {} def write_mount_cache(real_name, device, mkmnt, fstype, mount_opts): ''' .. versionadded:: 2018.3.0 Provide information if the path is mounted :param real_name: The real name of the mount point where the device is mounted. :param device: The device that is being mounted. :param mkmnt: Whether or not the mount point should be created. :param fstype: The file system that is used. :param mount_opts: Additional options used when mounting the device. :return: Boolean if message was sent successfully. CLI Example: .. code-block:: bash salt '*' mount.write_mount_cache /mnt/share /dev/sda1 False ext4 defaults,nosuid ''' cache = salt.utils.mount.read_cache(__opts__) if not cache: cache = {} cache['mounts'] = {} else: if 'mounts' not in cache: cache['mounts'] = {} cache['mounts'][real_name] = {'device': device, 'fstype': fstype, 'mkmnt': mkmnt, 'opts': mount_opts} cache_write = salt.utils.mount.write_cache(cache, __opts__) if cache_write: return True else: raise CommandExecutionError('Unable to write mount cache.') def delete_mount_cache(real_name): ''' .. versionadded:: 2018.3.0 Provide information if the path is mounted CLI Example: .. code-block:: bash salt '*' mount.delete_mount_cache /mnt/share ''' cache = salt.utils.mount.read_cache(__opts__) if cache: if 'mounts' in cache: if real_name in cache['mounts']: del cache['mounts'][real_name] cache_write = salt.utils.mount.write_cache(cache, __opts__) if not cache_write: raise CommandExecutionError('Unable to write mount cache.') return True def _filesystems(config='/etc/filesystems', leading_key=True): ''' Return the contents of the filesystems in an OrderedDict config File containing filesystem infomation leading_key True return dictionary keyed by 'name' and value as dictionary with other keys, values (name excluded) OrderedDict({ '/dir' : OrderedDict({'dev': '/dev/hd8', .... }})) False return dictionary keyed by 'name' and value as dictionary with all keys, values (name included) OrderedDict({ '/dir' : OrderedDict({'name': '/dir', 'dev': '/dev/hd8', ... })}) ''' ret = OrderedDict() lines = [] parsing_block = False if not os.path.isfile(config) or 'AIX' not in __grains__['kernel']: return ret # read in block of filesystems, block starts with '/' till empty line with salt.utils.files.fopen(config) as ifile: for line in ifile: line = salt.utils.stringutils.to_unicode(line) # skip till first entry if not line.startswith('/') and not parsing_block: continue if line.startswith('/'): parsing_block = True lines.append(line) elif not line.split(): parsing_block = False try: entry = _FileSystemsEntry.dict_from_lines( lines, _FileSystemsEntry.compatibility_keys) lines = [] if 'opts' in entry: entry['opts'] = entry['opts'].split(',') while entry['name'] in ret: entry['name'] += '_' if leading_key: ret[entry.pop('name')] = entry else: ret[entry['name']] = entry except _FileSystemsEntry.ParseError: pass else: lines.append(line) return ret def filesystems(config='/etc/filesystems'): ''' .. versionadded:: 2018.3.3 List the contents of the filesystems CLI Example: .. code-block:: bash salt '*' mount.filesystems ''' ret = {} if 'AIX' not in __grains__['kernel']: return ret ret_dict = _filesystems(config) if ret_dict: ret_key = next(iter(ret_dict.keys())) ret = {ret_key: dict(ret_dict[ret_key])} return ret def set_filesystems( name, device, vfstype, opts='-', mount='true', config='/etc/filesystems', test=False, match_on='auto', **kwargs): ''' .. versionadded:: 2018.3.3 Verify that this mount is represented in the filesystems, change the mount to match the data passed, or add the mount if it is not present on AIX Provide information if the path is mounted :param name: The name of the mount point where the device is mounted. :param device: The device that is being mounted. :param vfstype: The file system that is used (AIX has two fstypes, fstype and vfstype - similar to Linux fstype) :param opts: Additional options used when mounting the device. :param mount: Mount if not mounted, default True. :param config: Configuration file, default /etc/filesystems. :param match: File systems type to match on, default auto CLI Example: .. code-block:: bash salt '*' mount.set_filesystems /mnt/foo /dev/sdz1 jfs2 ''' # Fix the opts type if it is a list if isinstance(opts, list): opts = ','.join(opts) # preserve arguments for updating entry_args = { 'name': name, 'dev': device.replace('\\ ', '\\040'), 'vfstype': vfstype, 'opts': opts, 'mount': mount, } view_lines = [] ret = None if 'AIX' not in __grains__['kernel']: return ret # Transform match_on into list--items will be checked later if isinstance(match_on, list): pass elif not isinstance(match_on, six.string_types): raise CommandExecutionError('match_on must be a string or list of strings') elif match_on == 'auto': # Try to guess right criteria for auto.... # added IBM types from sys/vmount.h after btrfs # NOTE: missing some special fstypes here specialFSes = frozenset([ 'none', 'tmpfs', 'sysfs', 'proc', 'fusectl', 'debugfs', 'securityfs', 'devtmpfs', 'cgroup', 'btrfs', 'cdrfs', 'procfs', 'jfs', 'jfs2', 'nfs', 'sfs', 'nfs3', 'cachefs', 'udfs', 'cifs', 'namefs', 'pmemfs', 'ahafs', 'nfs4', 'autofs', 'stnfs']) if vfstype in specialFSes: match_on = ['name'] else: match_on = ['dev'] else: match_on = [match_on] # generate entry and criteria objects, handle invalid keys in match_on entry_ip = _FileSystemsEntry.from_line(entry_args, kwargs) try: criteria = entry_ip.pick(match_on) except KeyError: filterFn = lambda key: key not in _FileSystemsEntry.compatibility_keys invalid_keys = filter(filterFn, match_on) raise CommandExecutionError('Unrecognized keys in match_on: "{0}"'.format(invalid_keys)) # parse file, use ret to cache status if not os.path.isfile(config): raise CommandExecutionError('Bad config file "{0}"'.format(config)) # read in block of filesystem, block starts with '/' till empty line try: fsys_filedict = _filesystems(config, False) for fsys_view in six.viewitems(fsys_filedict): if criteria.match(fsys_view): ret = 'present' if entry_ip.match(fsys_view): view_lines.append(fsys_view) else: ret = 'change' kv = entry_ip['name'] view_lines.append((kv, entry_ip)) else: view_lines.append(fsys_view) except (IOError, OSError) as exc: raise CommandExecutionError('Couldn\'t read from {0}: {1}'.format(config, exc)) # add line if not present or changed if ret is None: for dict_view in six.viewitems(entry_ip.dict_from_entry()): view_lines.append(dict_view) ret = 'new' if ret != 'present': # ret in ['new', 'change']: try: with salt.utils.files.fopen(config, 'wb') as ofile: # The line was changed, commit it! for fsys_view in view_lines: entry = fsys_view[1] mystrg = _FileSystemsEntry.dict_to_lines(entry) ofile.writelines(salt.utils.data.encode(mystrg)) except (IOError, OSError): raise CommandExecutionError('File not writable {0}'.format(config)) return ret def rm_filesystems(name, device, config='/etc/filesystems'): ''' .. versionadded:: 2018.3.3 Remove the mount point from the filesystems CLI Example: .. code-block:: bash salt '*' mount.rm_filesystems /mnt/foo /dev/sdg ''' modified = False view_lines = [] if 'AIX' not in __grains__['kernel']: return modified criteria = _FileSystemsEntry(name=name, dev=device) try: fsys_filedict = _filesystems(config, False) for fsys_view in six.viewitems(fsys_filedict): try: if criteria.match(fsys_view): modified = True else: view_lines.append(fsys_view) except _FileSystemsEntry.ParseError: view_lines.append(fsys_view) except (IOError, OSError) as exc: raise CommandExecutionError("Couldn't read from {0}: {1}".format(config, exc)) if modified: try: with salt.utils.files.fopen(config, 'wb') as ofile: for fsys_view in view_lines: entry = fsys_view[1] mystrg = _FileSystemsEntry.dict_to_lines(entry) ofile.writelines(salt.utils.data.encode(mystrg)) except (IOError, OSError) as exc: raise CommandExecutionError("Couldn't write to {0}: {1}".format(config, exc)) return modified
saltstack/salt
salt/modules/mount.py
active
python
def active(extended=False): ''' List the active mounts. CLI Example: .. code-block:: bash salt '*' mount.active ''' ret = {} if __grains__['os'] == 'FreeBSD': _active_mounts_freebsd(ret) elif 'AIX' in __grains__['kernel']: _active_mounts_aix(ret) elif __grains__['kernel'] == 'SunOS': _active_mounts_solaris(ret) elif __grains__['os'] == 'OpenBSD': _active_mounts_openbsd(ret) elif __grains__['os'] in ['MacOS', 'Darwin']: _active_mounts_darwin(ret) else: if extended: try: _active_mountinfo(ret) except CommandExecutionError: _active_mounts(ret) else: _active_mounts(ret) return ret
List the active mounts. CLI Example: .. code-block:: bash salt '*' mount.active
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/mount.py#L235-L264
[ "def _active_mountinfo(ret):\n _list = _list_mounts()\n filename = '/proc/self/mountinfo'\n if not os.access(filename, os.R_OK):\n msg = 'File not readable {0}'\n raise CommandExecutionError(msg.format(filename))\n\n if 'disk.blkid' not in __context__:\n __context__['disk.blkid'] = __salt__['disk.blkid']()\n blkid_info = __context__['disk.blkid']\n\n with salt.utils.files.fopen(filename) as ifile:\n for line in ifile:\n comps = salt.utils.stringutils.to_unicode(line).split()\n device = comps[2].split(':')\n # each line can have any number of\n # optional parameters, we use the\n # location of the separator field to\n # determine the location of the elements\n # after it.\n _sep = comps.index('-')\n device_name = comps[_sep + 2]\n device_uuid = None\n device_label = None\n if device_name:\n device_uuid = blkid_info.get(device_name, {}).get('UUID')\n device_uuid = device_uuid and device_uuid.lower()\n device_label = blkid_info.get(device_name, {}).get('LABEL')\n ret[comps[4]] = {'mountid': comps[0],\n 'parentid': comps[1],\n 'major': device[0],\n 'minor': device[1],\n 'root': comps[3],\n 'opts': _resolve_user_group_names(comps[5].split(',')),\n 'fstype': comps[_sep + 1],\n 'device': device_name.replace('\\\\040', '\\\\ '),\n 'alt_device': _list.get(comps[4], None),\n 'superopts': _resolve_user_group_names(comps[_sep + 3].split(',')),\n 'device_uuid': device_uuid,\n 'device_label': device_label}\n return ret\n", "def _active_mounts(ret):\n '''\n List active mounts on Linux systems\n '''\n _list = _list_mounts()\n filename = '/proc/self/mounts'\n if not os.access(filename, os.R_OK):\n msg = 'File not readable {0}'\n raise CommandExecutionError(msg.format(filename))\n\n with salt.utils.files.fopen(filename) as ifile:\n for line in ifile:\n comps = salt.utils.stringutils.to_unicode(line).split()\n ret[comps[1]] = {'device': comps[0],\n 'alt_device': _list.get(comps[1], None),\n 'fstype': comps[2],\n 'opts': _resolve_user_group_names(comps[3].split(','))}\n return ret\n", "def _active_mounts_aix(ret):\n '''\n List active mounts on AIX systems\n '''\n for line in __salt__['cmd.run_stdout']('mount -p').split('\\n'):\n comps = re.sub(r\"\\s+\", \" \", line).split()\n if comps:\n if comps[0] == 'node' or comps[0] == '--------':\n continue\n comps_len = len(comps)\n if line.startswith((' ', '\\t')):\n curr_opts = _resolve_user_group_names(comps[6].split(',')) if 7 == comps_len else []\n if curr_opts:\n ret[comps[1]] = {'device': comps[0],\n 'fstype': comps[2],\n 'opts': curr_opts}\n else:\n ret[comps[1]] = {'device': comps[0],\n 'fstype': comps[2]}\n else:\n curr_opts = _resolve_user_group_names(comps[7].split(',')) if 8 == comps_len else []\n if curr_opts:\n ret[comps[2]] = {'node': comps[0],\n 'device': comps[1],\n 'fstype': comps[3],\n 'opts': curr_opts}\n else:\n ret[comps[2]] = {'node': comps[0],\n 'device': comps[1],\n 'fstype': comps[3]}\n return ret\n", "def _active_mounts_freebsd(ret):\n '''\n List active mounts on FreeBSD systems\n '''\n for line in __salt__['cmd.run_stdout']('mount -p').split('\\n'):\n comps = re.sub(r\"\\s+\", \" \", line).split()\n ret[comps[1]] = {'device': comps[0],\n 'fstype': comps[2],\n 'opts': _resolve_user_group_names(comps[3].split(','))}\n return ret\n", "def _active_mounts_solaris(ret):\n '''\n List active mounts on Solaris systems\n '''\n for line in __salt__['cmd.run_stdout']('mount -v').split('\\n'):\n comps = re.sub(r\"\\s+\", \" \", line).split()\n ret[comps[2]] = {'device': comps[0],\n 'fstype': comps[4],\n 'opts': _resolve_user_group_names(comps[5].split('/'))}\n return ret\n", "def _active_mounts_openbsd(ret):\n '''\n List active mounts on OpenBSD systems\n '''\n for line in __salt__['cmd.run_stdout']('mount -v').split('\\n'):\n comps = re.sub(r\"\\s+\", \" \", line).split()\n parens = re.findall(r'\\((.*?)\\)', line, re.DOTALL)\n if len(parens) > 1:\n nod = __salt__['cmd.run_stdout']('ls -l {0}'.format(comps[0]))\n nod = ' '.join(nod.split()).split(\" \")\n ret[comps[3]] = {'device': comps[0],\n 'fstype': comps[5],\n 'opts': _resolve_user_group_names(parens[1].split(\", \")),\n 'major': six.text_type(nod[4].strip(\",\")),\n 'minor': six.text_type(nod[5]),\n 'device_uuid': parens[0]}\n else:\n ret[comps[2]] = {'device': comps[0],\n 'fstype': comps[4],\n 'opts': _resolve_user_group_names(parens[0].split(\", \"))}\n return ret\n", "def _active_mounts_darwin(ret):\n '''\n List active mounts on Mac OS systems\n '''\n for line in __salt__['cmd.run_stdout']('mount').split('\\n'):\n comps = re.sub(r\"\\s+\", \" \", line).split()\n parens = re.findall(r'\\((.*?)\\)', line, re.DOTALL)[0].split(\", \")\n ret[comps[2]] = {'device': comps[0],\n 'fstype': parens[0],\n 'opts': _resolve_user_group_names(parens[1:])}\n return ret\n" ]
# -*- coding: utf-8 -*- ''' Salt module to manage Unix mounts and the fstab file ''' # Import python libs from __future__ import absolute_import, print_function, unicode_literals import os import re import logging # Import salt libs import salt.utils.args import salt.utils.data import salt.utils.files import salt.utils.path import salt.utils.platform import salt.utils.mount import salt.utils.stringutils from salt.utils.odict import OrderedDict from salt.exceptions import CommandNotFoundError, CommandExecutionError # Import 3rd-party libs from salt.ext import six from salt.ext.six.moves import filter, zip # pylint: disable=import-error,redefined-builtin # Set up logger log = logging.getLogger(__name__) # Define the module's virtual name __virtualname__ = 'mount' def __virtual__(): ''' Only load on POSIX-like systems ''' # Disable on Windows, a specific file module exists: if salt.utils.platform.is_windows(): return (False, 'The mount module cannot be loaded: not a POSIX-like system.') return True def _list_mounts(): ret = {} if __grains__['os'] in ['MacOS', 'Darwin']: mounts = __salt__['cmd.run_stdout']('mount') else: mounts = __salt__['cmd.run_stdout']('mount -l') for line in mounts.split('\n'): comps = re.sub(r"\s+", " ", line).split() if len(comps) >= 3: ret[comps[2]] = comps[0] return ret def _active_mountinfo(ret): _list = _list_mounts() filename = '/proc/self/mountinfo' if not os.access(filename, os.R_OK): msg = 'File not readable {0}' raise CommandExecutionError(msg.format(filename)) if 'disk.blkid' not in __context__: __context__['disk.blkid'] = __salt__['disk.blkid']() blkid_info = __context__['disk.blkid'] with salt.utils.files.fopen(filename) as ifile: for line in ifile: comps = salt.utils.stringutils.to_unicode(line).split() device = comps[2].split(':') # each line can have any number of # optional parameters, we use the # location of the separator field to # determine the location of the elements # after it. _sep = comps.index('-') device_name = comps[_sep + 2] device_uuid = None device_label = None if device_name: device_uuid = blkid_info.get(device_name, {}).get('UUID') device_uuid = device_uuid and device_uuid.lower() device_label = blkid_info.get(device_name, {}).get('LABEL') ret[comps[4]] = {'mountid': comps[0], 'parentid': comps[1], 'major': device[0], 'minor': device[1], 'root': comps[3], 'opts': _resolve_user_group_names(comps[5].split(',')), 'fstype': comps[_sep + 1], 'device': device_name.replace('\\040', '\\ '), 'alt_device': _list.get(comps[4], None), 'superopts': _resolve_user_group_names(comps[_sep + 3].split(',')), 'device_uuid': device_uuid, 'device_label': device_label} return ret def _active_mounts(ret): ''' List active mounts on Linux systems ''' _list = _list_mounts() filename = '/proc/self/mounts' if not os.access(filename, os.R_OK): msg = 'File not readable {0}' raise CommandExecutionError(msg.format(filename)) with salt.utils.files.fopen(filename) as ifile: for line in ifile: comps = salt.utils.stringutils.to_unicode(line).split() ret[comps[1]] = {'device': comps[0], 'alt_device': _list.get(comps[1], None), 'fstype': comps[2], 'opts': _resolve_user_group_names(comps[3].split(','))} return ret def _active_mounts_aix(ret): ''' List active mounts on AIX systems ''' for line in __salt__['cmd.run_stdout']('mount -p').split('\n'): comps = re.sub(r"\s+", " ", line).split() if comps: if comps[0] == 'node' or comps[0] == '--------': continue comps_len = len(comps) if line.startswith((' ', '\t')): curr_opts = _resolve_user_group_names(comps[6].split(',')) if 7 == comps_len else [] if curr_opts: ret[comps[1]] = {'device': comps[0], 'fstype': comps[2], 'opts': curr_opts} else: ret[comps[1]] = {'device': comps[0], 'fstype': comps[2]} else: curr_opts = _resolve_user_group_names(comps[7].split(',')) if 8 == comps_len else [] if curr_opts: ret[comps[2]] = {'node': comps[0], 'device': comps[1], 'fstype': comps[3], 'opts': curr_opts} else: ret[comps[2]] = {'node': comps[0], 'device': comps[1], 'fstype': comps[3]} return ret def _active_mounts_freebsd(ret): ''' List active mounts on FreeBSD systems ''' for line in __salt__['cmd.run_stdout']('mount -p').split('\n'): comps = re.sub(r"\s+", " ", line).split() ret[comps[1]] = {'device': comps[0], 'fstype': comps[2], 'opts': _resolve_user_group_names(comps[3].split(','))} return ret def _active_mounts_solaris(ret): ''' List active mounts on Solaris systems ''' for line in __salt__['cmd.run_stdout']('mount -v').split('\n'): comps = re.sub(r"\s+", " ", line).split() ret[comps[2]] = {'device': comps[0], 'fstype': comps[4], 'opts': _resolve_user_group_names(comps[5].split('/'))} return ret def _active_mounts_openbsd(ret): ''' List active mounts on OpenBSD systems ''' for line in __salt__['cmd.run_stdout']('mount -v').split('\n'): comps = re.sub(r"\s+", " ", line).split() parens = re.findall(r'\((.*?)\)', line, re.DOTALL) if len(parens) > 1: nod = __salt__['cmd.run_stdout']('ls -l {0}'.format(comps[0])) nod = ' '.join(nod.split()).split(" ") ret[comps[3]] = {'device': comps[0], 'fstype': comps[5], 'opts': _resolve_user_group_names(parens[1].split(", ")), 'major': six.text_type(nod[4].strip(",")), 'minor': six.text_type(nod[5]), 'device_uuid': parens[0]} else: ret[comps[2]] = {'device': comps[0], 'fstype': comps[4], 'opts': _resolve_user_group_names(parens[0].split(", "))} return ret def _active_mounts_darwin(ret): ''' List active mounts on Mac OS systems ''' for line in __salt__['cmd.run_stdout']('mount').split('\n'): comps = re.sub(r"\s+", " ", line).split() parens = re.findall(r'\((.*?)\)', line, re.DOTALL)[0].split(", ") ret[comps[2]] = {'device': comps[0], 'fstype': parens[0], 'opts': _resolve_user_group_names(parens[1:])} return ret def _resolve_user_group_names(opts): ''' Resolve user and group names in related opts ''' name_id_opts = {'uid': 'user.info', 'gid': 'group.info'} for ind, opt in enumerate(opts): if opt.split('=')[0] in name_id_opts: _givenid = opt.split('=')[1] _param = opt.split('=')[0] _id = _givenid if not re.match('[0-9]+$', _givenid): _info = __salt__[name_id_opts[_param]](_givenid) if _info and _param in _info: _id = _info[_param] opts[ind] = _param + '=' + six.text_type(_id) opts[ind] = opts[ind].replace('\\040', '\\ ') return opts class _fstab_entry(object): ''' Utility class for manipulating fstab entries. Primarily we're parsing, formatting, and comparing lines. Parsing emits dicts expected from fstab() or raises a ValueError. Note: We'll probably want to use os.normpath and os.normcase on 'name' ''' class ParseError(ValueError): ''' Error raised when a line isn't parsible as an fstab entry ''' fstab_keys = ('device', 'name', 'fstype', 'opts', 'dump', 'pass_num') # preserve data format compatibility_keys = ('device', 'name', 'fstype', 'opts', 'dump', 'pass') fstab_format = '{device}\t\t{name}\t{fstype}\t{opts}\t{dump} {pass_num}\n' @classmethod def dict_from_line(cls, line, keys=fstab_keys): if len(keys) != 6: raise ValueError('Invalid key array: {0}'.format(keys)) if line.startswith('#'): raise cls.ParseError("Comment!") comps = line.split() if len(comps) < 4 or len(comps) > 6: raise cls.ParseError("Invalid Entry!") comps.extend(['0'] * (len(keys) - len(comps))) return dict(zip(keys, comps)) @classmethod def from_line(cls, *args, **kwargs): return cls(** cls.dict_from_line(*args, **kwargs)) @classmethod def dict_to_line(cls, entry): return cls.fstab_format.format(**entry) def __str__(self): ''' String value, only works for full repr ''' return self.dict_to_line(self.criteria) def __repr__(self): ''' Always works ''' return repr(self.criteria) def pick(self, keys): ''' Returns an instance with just those keys ''' subset = dict([(key, self.criteria[key]) for key in keys]) return self.__class__(**subset) def __init__(self, **criteria): ''' Store non-empty, non-null values to use as filter ''' items = [key_value for key_value in six.iteritems(criteria) if key_value[1] is not None] items = [(key_value1[0], six.text_type(key_value1[1])) for key_value1 in items] self.criteria = dict(items) @staticmethod def norm_path(path): ''' Resolve equivalent paths equivalently ''' return os.path.normcase(os.path.normpath(path)) def match(self, line): ''' Compare potentially partial criteria against line ''' entry = self.dict_from_line(line) for key, value in six.iteritems(self.criteria): if entry[key] != value: return False return True class _vfstab_entry(object): ''' Utility class for manipulating vfstab entries. Primarily we're parsing, formatting, and comparing lines. Parsing emits dicts expected from fstab() or raises a ValueError. Note: We'll probably want to use os.normpath and os.normcase on 'name' Note: This parses vfstab entries on Solaris like systems #device device mount FS fsck mount mount #to mount to fsck point type pass at boot options # /devices - /devices devfs - no - ''' class ParseError(ValueError): '''Error raised when a line isn't parsible as an fstab entry''' vfstab_keys = ('device', 'device_fsck', 'name', 'fstype', 'pass_fsck', 'mount_at_boot', 'opts') # NOTE: weird formatting to match default spacing on Solaris vfstab_format = '{device:<11} {device_fsck:<3} {name:<19} {fstype:<8} {pass_fsck:<3} {mount_at_boot:<6} {opts}\n' @classmethod def dict_from_line(cls, line): if line.startswith('#'): raise cls.ParseError("Comment!") comps = line.split() if len(comps) != 7: raise cls.ParseError("Invalid Entry!") return dict(zip(cls.vfstab_keys, comps)) @classmethod def from_line(cls, *args, **kwargs): return cls(** cls.dict_from_line(*args, **kwargs)) @classmethod def dict_to_line(cls, entry): return cls.vfstab_format.format(**entry) def __str__(self): ''' String value, only works for full repr ''' return self.dict_to_line(self.criteria) def __repr__(self): ''' Always works ''' return repr(self.criteria) def pick(self, keys): ''' Returns an instance with just those keys ''' subset = dict([(key, self.criteria[key]) for key in keys]) return self.__class__(**subset) def __init__(self, **criteria): ''' Store non-empty, non-null values to use as filter ''' items = [key_value for key_value in six.iteritems(criteria) if key_value[1] is not None] items = [(key_value1[0], six.text_type(key_value1[1])) for key_value1 in items] self.criteria = dict(items) @staticmethod def norm_path(path): ''' Resolve equivalent paths equivalently ''' return os.path.normcase(os.path.normpath(path)) def match(self, line): ''' Compare potentially partial criteria against line ''' entry = self.dict_from_line(line) for key, value in six.iteritems(self.criteria): if entry[key] != value: return False return True class _FileSystemsEntry(object): ''' Utility class for manipulating filesystem entries. Primarily we're parsing, formatting, and comparing lines. Parsing emits dicts expected from fstab() or raises a ValueError. Note: We'll probably want to use os.normpath and os.normcase on 'name' ''' class ParseError(ValueError): ''' Error raised when a line isn't parsible as an fstab entry ''' filesystems_keys = ('device', 'name', 'fstype', 'vfstype', 'opts', 'mount') # preserve data format of filesystems compatibility_keys = ('dev', 'dev', 'name', 'fstype', 'vfstype', 'opts', 'mount', 'type', 'vfs', 'account', 'boot', 'check', 'free', 'nodename', 'quota', 'size', 'vol', 'log') @classmethod def dict_from_lines(cls, lines, keys=filesystems_keys): if len(lines) < 2: raise ValueError('Invalid number of lines: {0}'.format(lines)) if not keys: # if empty force default filesystems_keys keys = _FileSystemsEntry.filesystems_keys elif len(keys) < 6: raise ValueError('Invalid key name array: {0}'.format(keys)) blk_lines = lines orddict = OrderedDict() orddict['name'] = blk_lines[0].split(':')[0].strip() blk_lines.pop(0) for line in blk_lines: if line.startswith('#'): raise cls.ParseError("Comment!") comps = line.split('= ') if len(comps) != 2: raise cls.ParseError("Invalid Entry!") key_name = comps[0].strip() if key_name in keys: orddict[key_name] = comps[1].strip() else: raise ValueError('Invalid name for use in filesystems: {0}'.format(key_name)) return orddict @classmethod def dict_from_cmd_line(cls, ipargs, keys): cmdln_dict = ipargs if keys: for key, value in keys: # ignore unknown or local scope keys if key.startswith('__'): continue if key in _FileSystemsEntry.compatibility_keys: cmdln_dict[key] = value return cmdln_dict @classmethod def from_line(cls, *args, **kwargs): return cls(** cls.dict_from_cmd_line(*args, **kwargs)) @classmethod def dict_to_lines(cls, fsys_dict_entry): entry = fsys_dict_entry strg_out = entry['name'] + ':' + os.linesep for k, v in six.viewitems(entry): if 'name' not in k: strg_out += '\t{0}\t\t= {1}'.format(k, v) + os.linesep strg_out += os.linesep return six.text_type(strg_out) def dict_from_entry(self): ret = OrderedDict() ret[self.criteria['name']] = self.criteria return ret def __str__(self): ''' String value, only works for full repr ''' return self.dict_to_lines(self.criteria) def __repr__(self): ''' Always works ''' return repr(self.criteria) def pick(self, keys): ''' Returns an instance with just those keys ''' subset = dict([(key, self.criteria[key]) for key in keys]) return self.__class__(**subset) def __init__(self, **criteria): ''' Store non-empty, non-null values to use as filter ''' items = [key_value for key_value in six.iteritems(criteria) if key_value[1] is not None] items = [(key_value1[0], six.text_type(key_value1[1])) for key_value1 in items] self.criteria = OrderedDict(items) @staticmethod def norm_path(path): ''' Resolve equivalent paths equivalently ''' return os.path.normcase(os.path.normpath(path)) def match(self, fsys_view): ''' Compare potentially partial criteria against built filesystems entry dictionary ''' evalue_dict = fsys_view[1] for key, value in six.viewitems(self.criteria): if key in evalue_dict: if evalue_dict[key] != value: return False else: return False return True def __getitem__(self, key): ''' Return value for input key ''' return self.criteria[key] def fstab(config='/etc/fstab'): ''' .. versionchanged:: 2016.3.2 List the contents of the fstab CLI Example: .. code-block:: bash salt '*' mount.fstab ''' ret = {} if not os.path.isfile(config): return ret with salt.utils.files.fopen(config) as ifile: for line in ifile: line = salt.utils.stringutils.to_unicode(line) try: if __grains__['kernel'] == 'SunOS': # Note: comments use in default vfstab file! if line[0] == '#': continue entry = _vfstab_entry.dict_from_line( line) else: entry = _fstab_entry.dict_from_line( line, _fstab_entry.compatibility_keys) entry['opts'] = entry['opts'].split(',') while entry['name'] in ret: entry['name'] += '_' ret[entry.pop('name')] = entry except _fstab_entry.ParseError: pass except _vfstab_entry.ParseError: pass return ret def vfstab(config='/etc/vfstab'): ''' .. versionadded:: 2016.3.2 List the contents of the vfstab CLI Example: .. code-block:: bash salt '*' mount.vfstab ''' # NOTE: vfstab is a wrapper for fstab return fstab(config) def rm_fstab(name, device, config='/etc/fstab'): ''' .. versionchanged:: 2016.3.2 Remove the mount point from the fstab CLI Example: .. code-block:: bash salt '*' mount.rm_fstab /mnt/foo /dev/sdg ''' modified = False if __grains__['kernel'] == 'SunOS': criteria = _vfstab_entry(name=name, device=device) else: criteria = _fstab_entry(name=name, device=device) lines = [] try: with salt.utils.files.fopen(config, 'r') as ifile: for line in ifile: line = salt.utils.stringutils.to_unicode(line) try: if criteria.match(line): modified = True else: lines.append(line) except _fstab_entry.ParseError: lines.append(line) except _vfstab_entry.ParseError: lines.append(line) except (IOError, OSError) as exc: msg = "Couldn't read from {0}: {1}" raise CommandExecutionError(msg.format(config, exc)) if modified: try: with salt.utils.files.fopen(config, 'wb') as ofile: ofile.writelines(salt.utils.data.encode(lines)) except (IOError, OSError) as exc: msg = "Couldn't write to {0}: {1}" raise CommandExecutionError(msg.format(config, exc)) # Note: not clear why we always return 'True' # --just copying previous behavior at this point... return True def rm_vfstab(name, device, config='/etc/vfstab'): ''' .. versionadded:: 2016.3.2 Remove the mount point from the vfstab CLI Example: .. code-block:: bash salt '*' mount.rm_vfstab /mnt/foo /device/c0t0d0p0 ''' ## NOTE: rm_vfstab is a wrapper for rm_fstab return rm_fstab(name, device, config) def set_fstab( name, device, fstype, opts='defaults', dump=0, pass_num=0, config='/etc/fstab', test=False, match_on='auto', **kwargs): ''' Verify that this mount is represented in the fstab, change the mount to match the data passed, or add the mount if it is not present. CLI Example: .. code-block:: bash salt '*' mount.set_fstab /mnt/foo /dev/sdz1 ext4 ''' # Fix the opts type if it is a list if isinstance(opts, list): opts = ','.join(opts) # preserve arguments for updating entry_args = { 'name': name, 'device': device.replace('\\ ', '\\040'), 'fstype': fstype, 'opts': opts.replace('\\ ', '\\040'), 'dump': dump, 'pass_num': pass_num, } lines = [] ret = None # Transform match_on into list--items will be checked later if isinstance(match_on, list): pass elif not isinstance(match_on, six.string_types): msg = 'match_on must be a string or list of strings' raise CommandExecutionError(msg) elif match_on == 'auto': # Try to guess right criteria for auto.... # NOTE: missing some special fstypes here specialFSes = frozenset([ 'none', 'tmpfs', 'sysfs', 'proc', 'fusectl', 'debugfs', 'securityfs', 'devtmpfs', 'cgroup', 'btrfs']) if fstype in specialFSes: match_on = ['name'] else: match_on = ['device'] else: match_on = [match_on] # generate entry and criteria objects, handle invalid keys in match_on entry = _fstab_entry(**entry_args) try: criteria = entry.pick(match_on) except KeyError: filterFn = lambda key: key not in _fstab_entry.fstab_keys invalid_keys = filter(filterFn, match_on) msg = 'Unrecognized keys in match_on: "{0}"'.format(invalid_keys) raise CommandExecutionError(msg) # parse file, use ret to cache status if not os.path.isfile(config): raise CommandExecutionError('Bad config file "{0}"'.format(config)) try: with salt.utils.files.fopen(config, 'r') as ifile: for line in ifile: line = salt.utils.stringutils.to_unicode(line) try: if criteria.match(line): # Note: If ret isn't None here, # we've matched multiple lines ret = 'present' if entry.match(line): lines.append(line) else: ret = 'change' lines.append(six.text_type(entry)) else: lines.append(line) except _fstab_entry.ParseError: lines.append(line) except (IOError, OSError) as exc: msg = 'Couldn\'t read from {0}: {1}' raise CommandExecutionError(msg.format(config, exc)) # add line if not present or changed if ret is None: lines.append(six.text_type(entry)) ret = 'new' if ret != 'present': # ret in ['new', 'change']: if not salt.utils.args.test_mode(test=test, **kwargs): try: with salt.utils.files.fopen(config, 'wb') as ofile: # The line was changed, commit it! ofile.writelines(salt.utils.data.encode(lines)) except (IOError, OSError): msg = 'File not writable {0}' raise CommandExecutionError(msg.format(config)) return ret def set_vfstab( name, device, fstype, opts='-', device_fsck='-', pass_fsck='-', mount_at_boot='yes', config='/etc/vfstab', test=False, match_on='auto', **kwargs): ''' ..verionadded:: 2016.3.2 Verify that this mount is represented in the fstab, change the mount to match the data passed, or add the mount if it is not present. CLI Example: .. code-block:: bash salt '*' mount.set_vfstab /mnt/foo /device/c0t0d0p0 ufs ''' # Fix the opts type if it is a list if isinstance(opts, list): opts = ','.join(opts) # Map unknown values for mount_at_boot to no if mount_at_boot != 'yes': mount_at_boot = 'no' # preserve arguments for updating entry_args = { 'name': name, 'device': device, 'fstype': fstype, 'opts': opts, 'device_fsck': device_fsck, 'pass_fsck': pass_fsck, 'mount_at_boot': mount_at_boot, } lines = [] ret = None # Transform match_on into list--items will be checked later if isinstance(match_on, list): pass elif not isinstance(match_on, six.string_types): msg = 'match_on must be a string or list of strings' raise CommandExecutionError(msg) elif match_on == 'auto': # Try to guess right criteria for auto.... # NOTE: missing some special fstypes here specialFSes = frozenset([ 'devfs', 'proc', 'ctfs', 'objfs', 'sharefs', 'fs', 'tmpfs']) if fstype in specialFSes: match_on = ['name'] else: match_on = ['device'] else: match_on = [match_on] # generate entry and criteria objects, handle invalid keys in match_on entry = _vfstab_entry(**entry_args) try: criteria = entry.pick(match_on) except KeyError: filterFn = lambda key: key not in _vfstab_entry.vfstab_keys invalid_keys = filter(filterFn, match_on) msg = 'Unrecognized keys in match_on: "{0}"'.format(invalid_keys) raise CommandExecutionError(msg) # parse file, use ret to cache status if not os.path.isfile(config): raise CommandExecutionError('Bad config file "{0}"'.format(config)) try: with salt.utils.files.fopen(config, 'r') as ifile: for line in ifile: line = salt.utils.stringutils.to_unicode(line) try: if criteria.match(line): # Note: If ret isn't None here, # we've matched multiple lines ret = 'present' if entry.match(line): lines.append(line) else: ret = 'change' lines.append(six.text_type(entry)) else: lines.append(line) except _vfstab_entry.ParseError: lines.append(line) except (IOError, OSError) as exc: msg = 'Couldn\'t read from {0}: {1}' raise CommandExecutionError(msg.format(config, exc)) # add line if not present or changed if ret is None: lines.append(six.text_type(entry)) ret = 'new' if ret != 'present': # ret in ['new', 'change']: if not salt.utils.args.test_mode(test=test, **kwargs): try: with salt.utils.files.fopen(config, 'wb') as ofile: # The line was changed, commit it! ofile.writelines(salt.utils.data.encode(lines)) except (IOError, OSError): msg = 'File not writable {0}' raise CommandExecutionError(msg.format(config)) return ret def rm_automaster(name, device, config='/etc/auto_salt'): ''' Remove the mount point from the auto_master CLI Example: .. code-block:: bash salt '*' mount.rm_automaster /mnt/foo /dev/sdg ''' contents = automaster(config) if name not in contents: return True # The entry is present, get rid of it lines = [] try: with salt.utils.files.fopen(config, 'r') as ifile: for line in ifile: line = salt.utils.stringutils.to_unicode(line) if line.startswith('#'): # Commented lines.append(line) continue if not line.strip(): # Blank line lines.append(line) continue comps = line.split() if len(comps) != 3: # Invalid entry lines.append(line) continue comps = line.split() prefix = "/.." name_chk = comps[0].replace(prefix, "") device_fmt = comps[2].split(":") if device: if name_chk == name and device_fmt[1] == device: continue else: if name_chk == name: continue lines.append(line) except (IOError, OSError) as exc: msg = "Couldn't read from {0}: {1}" raise CommandExecutionError(msg.format(config, exc)) try: with salt.utils.files.fopen(config, 'wb') as ofile: ofile.writelines(salt.utils.data.encode(lines)) except (IOError, OSError) as exc: msg = "Couldn't write to {0}: {1}" raise CommandExecutionError(msg.format(config, exc)) # Update automount __salt__['cmd.run']('automount -cv') return True def set_automaster( name, device, fstype, opts='', config='/etc/auto_salt', test=False, **kwargs): ''' Verify that this mount is represented in the auto_salt, change the mount to match the data passed, or add the mount if it is not present. CLI Example: .. code-block:: bash salt '*' mount.set_automaster /mnt/foo /dev/sdz1 ext4 ''' # Fix the opts type if it is a list if isinstance(opts, list): opts = ','.join(opts) lines = [] change = False present = False automaster_file = "/etc/auto_master" if not os.path.isfile(config): __salt__['file.touch'](config) __salt__['file.append'](automaster_file, "/-\t\t\t{0}".format(config)) name = "/..{0}".format(name) device_fmt = "{0}:{1}".format(fstype, device) type_opts = "-fstype={0},{1}".format(fstype, opts) if fstype == 'smbfs': device_fmt = device_fmt.replace(fstype, "") try: with salt.utils.files.fopen(config, 'r') as ifile: for line in ifile: line = salt.utils.stringutils.to_unicode(line) if line.startswith('#'): # Commented lines.append(line) continue if not line.strip(): # Blank line lines.append(line) continue comps = line.split() if len(comps) != 3: # Invalid entry lines.append(line) continue if comps[0] == name or comps[2] == device_fmt: # check to see if there are changes # and fix them if there are any present = True if comps[0] != name: change = True comps[0] = name if comps[1] != type_opts: change = True comps[1] = type_opts if comps[2] != device_fmt: change = True comps[2] = device_fmt if change: log.debug( 'auto_master entry for mount point %s needs to be ' 'updated', name ) newline = ( '{0}\t{1}\t{2}\n'.format( name, type_opts, device_fmt) ) lines.append(newline) else: lines.append(line) except (IOError, OSError) as exc: msg = 'Couldn\'t read from {0}: {1}' raise CommandExecutionError(msg.format(config, exc)) if change: if not salt.utils.args.test_mode(test=test, **kwargs): try: with salt.utils.files.fopen(config, 'wb') as ofile: # The line was changed, commit it! ofile.writelines(salt.utils.data.encode(lines)) except (IOError, OSError): msg = 'File not writable {0}' raise CommandExecutionError(msg.format(config)) return 'change' if not change: if present: # The right entry is already here return 'present' else: if not salt.utils.args.test_mode(test=test, **kwargs): # The entry is new, add it to the end of the fstab newline = ( '{0}\t{1}\t{2}\n'.format( name, type_opts, device_fmt) ) lines.append(newline) try: with salt.utils.files.fopen(config, 'wb') as ofile: # The line was changed, commit it! ofile.writelines(salt.utils.data.encode(lines)) except (IOError, OSError): raise CommandExecutionError( 'File not writable {0}'.format( config ) ) return 'new' def automaster(config='/etc/auto_salt'): ''' List the contents of the auto master CLI Example: .. code-block:: bash salt '*' mount.automaster ''' ret = {} if not os.path.isfile(config): return ret with salt.utils.files.fopen(config) as ifile: for line in ifile: line = salt.utils.stringutils.to_unicode(line) if line.startswith('#'): # Commented continue if not line.strip(): # Blank line continue comps = line.split() if len(comps) != 3: # Invalid entry continue prefix = "/.." name = comps[0].replace(prefix, "") device_fmt = comps[2].split(":") opts = comps[1].split(',') ret[name] = {'device': device_fmt[1], 'fstype': opts[0], 'opts': opts[1:]} return ret def mount(name, device, mkmnt=False, fstype='', opts='defaults', user=None, util='mount'): ''' Mount a device CLI Example: .. code-block:: bash salt '*' mount.mount /mnt/foo /dev/sdz1 True ''' if util != 'mount': # This functionality used to live in img.mount_image if util == 'guestfs': return __salt__['guestfs.mount'](name, root=device) elif util == 'qemu_nbd': mnt = __salt__['qemu_nbd.init'](name, device) if not mnt: return False first = next(six.iterkeys(mnt)) __context__['img.mnt_{0}'.format(first)] = mnt return first return False # Darwin doesn't expect defaults when mounting without other options if 'defaults' in opts and __grains__['os'] in ['MacOS', 'Darwin', 'AIX']: opts = None if isinstance(opts, six.string_types): opts = opts.split(',') if not os.path.exists(name) and mkmnt: __salt__['file.mkdir'](name, user=user) args = '' if opts is not None: lopts = ','.join(opts) args = '-o {0}'.format(lopts) if fstype: # use of fstype on AIX differs from typical Linux use of -t # functionality AIX uses -v vfsname, -t fstype mounts all with # fstype in /etc/filesystems if 'AIX' in __grains__['os']: args += ' -v {0}'.format(fstype) elif 'solaris' in __grains__['os'].lower(): args += ' -F {0}'.format(fstype) else: args += ' -t {0}'.format(fstype) cmd = 'mount {0} {1} {2} '.format(args, device, name) out = __salt__['cmd.run_all'](cmd, runas=user, python_shell=False) if out['retcode']: return out['stderr'] return True def remount(name, device, mkmnt=False, fstype='', opts='defaults', user=None): ''' Attempt to remount a device, if the device is not already mounted, mount is called CLI Example: .. code-block:: bash salt '*' mount.remount /mnt/foo /dev/sdz1 True ''' force_mount = False if __grains__['os'] in ['MacOS', 'Darwin']: if opts == 'defaults': opts = 'noowners' if fstype == 'smbfs': force_mount = True if 'AIX' in __grains__['os']: if opts == 'defaults': opts = [] if isinstance(opts, six.string_types): opts = opts.split(',') mnts = active() if name in mnts: # The mount point is mounted, attempt to remount it with the given data if 'remount' not in opts and __grains__['os'] not in ['OpenBSD', 'MacOS', 'Darwin']: opts.append('remount') if force_mount: # We need to force the mount but first we should unmount umount(name, device, user=user) lopts = ','.join(opts) args = '-o {0}'.format(lopts) if fstype: # use of fstype on AIX differs from typical Linux use of # -t functionality AIX uses -v vfsname, -t fstype mounts # all with fstype in /etc/filesystems if 'AIX' in __grains__['os']: args += ' -v {0}'.format(fstype) elif 'solaris' in __grains__['os'].lower(): args += ' -F {0}'.format(fstype) else: args += ' -t {0}'.format(fstype) if __grains__['os'] not in ['OpenBSD', 'MacOS', 'Darwin'] or force_mount: cmd = 'mount {0} {1} {2} '.format(args, device, name) else: cmd = 'mount -u {0} {1} {2} '.format(args, device, name) out = __salt__['cmd.run_all'](cmd, runas=user, python_shell=False) if out['retcode']: return out['stderr'] return True # Mount a filesystem that isn't already return mount(name, device, mkmnt, fstype, opts, user=user) def umount(name, device=None, user=None, util='mount'): ''' Attempt to unmount a device by specifying the directory it is mounted on CLI Example: .. code-block:: bash salt '*' mount.umount /mnt/foo .. versionadded:: 2015.5.0 .. code-block:: bash salt '*' mount.umount /mnt/foo /dev/xvdc1 ''' if util != 'mount': # This functionality used to live in img.umount_image if 'qemu_nbd.clear' in __salt__: if 'img.mnt_{0}'.format(name) in __context__: __salt__['qemu_nbd.clear'](__context__['img.mnt_{0}'.format(name)]) return mnts = active() if name not in mnts: return "{0} does not have anything mounted".format(name) if not device: cmd = 'umount {0}'.format(name) else: cmd = 'umount {0}'.format(device) out = __salt__['cmd.run_all'](cmd, runas=user, python_shell=False) if out['retcode']: return out['stderr'] return True def is_fuse_exec(cmd): ''' Returns true if the command passed is a fuse mountable application. CLI Example: .. code-block:: bash salt '*' mount.is_fuse_exec sshfs ''' cmd_path = salt.utils.path.which(cmd) # No point in running ldd on a command that doesn't exist if not cmd_path: return False elif not salt.utils.path.which('ldd'): raise CommandNotFoundError('ldd') out = __salt__['cmd.run']('ldd {0}'.format(cmd_path), python_shell=False) return 'libfuse' in out def swaps(): ''' Return a dict containing information on active swap .. versionchanged:: 2016.3.2 CLI Example: .. code-block:: bash salt '*' mount.swaps ''' ret = {} if __grains__['kernel'] == 'SunOS': for line in __salt__['cmd.run_stdout']('swap -l').splitlines(): if line.startswith('swapfile'): continue comps = line.split() ret[comps[0]] = {'type': 'device' if comps[0].startswith(('/dev', 'swap')) else 'file', 'size': int(comps[3]), 'used': (int(comps[3]) - int(comps[4])), 'priority': '-'} elif 'AIX' in __grains__['kernel']: for line in __salt__['cmd.run_stdout']('swap -l').splitlines(): if line.startswith('device'): continue comps = line.split() # AIX uses MB for units ret[comps[0]] = {'type': 'device', 'size': int(comps[3][:-2]) * 1024, 'used': (int(comps[3][:-2]) - int(comps[4][:-2])) * 1024, 'priority': '-'} elif __grains__['os'] != 'OpenBSD': with salt.utils.files.fopen('/proc/swaps') as fp_: for line in fp_: line = salt.utils.stringutils.to_unicode(line) if line.startswith('Filename'): continue comps = line.split() ret[comps[0]] = {'type': comps[1], 'size': comps[2], 'used': comps[3], 'priority': comps[4]} else: for line in __salt__['cmd.run_stdout']('swapctl -kl').splitlines(): if line.startswith(('Device', 'Total')): continue swap_type = "file" comps = line.split() if comps[0].startswith('/dev/'): swap_type = "partition" ret[comps[0]] = {'type': swap_type, 'size': comps[1], 'used': comps[2], 'priority': comps[5]} return ret def swapon(name, priority=None): ''' Activate a swap disk .. versionchanged:: 2016.3.2 CLI Example: .. code-block:: bash salt '*' mount.swapon /root/swapfile ''' ret = {} on_ = swaps() if name in on_: ret['stats'] = on_[name] ret['new'] = False return ret if __grains__['kernel'] == 'SunOS': if __grains__['virtual'] != 'zone': __salt__['cmd.run']('swap -a {0}'.format(name), python_shell=False) else: return False else: cmd = 'swapon {0}'.format(name) if priority and 'AIX' not in __grains__['kernel']: cmd += ' -p {0}'.format(priority) __salt__['cmd.run'](cmd, python_shell=False) on_ = swaps() if name in on_: ret['stats'] = on_[name] ret['new'] = True return ret return ret def swapoff(name): ''' Deactivate a named swap mount .. versionchanged:: 2016.3.2 CLI Example: .. code-block:: bash salt '*' mount.swapoff /root/swapfile ''' on_ = swaps() if name in on_: if __grains__['kernel'] == 'SunOS': if __grains__['virtual'] != 'zone': __salt__['cmd.run']('swap -a {0}'.format(name), python_shell=False) else: return False elif __grains__['os'] != 'OpenBSD': __salt__['cmd.run']('swapoff {0}'.format(name), python_shell=False) else: __salt__['cmd.run']('swapctl -d {0}'.format(name), python_shell=False) on_ = swaps() if name in on_: return False return True return None def is_mounted(name): ''' .. versionadded:: 2014.7.0 Provide information if the path is mounted CLI Example: .. code-block:: bash salt '*' mount.is_mounted /mnt/share ''' active_ = active() if name in active_: return True else: return False def read_mount_cache(name): ''' .. versionadded:: 2018.3.0 Provide information if the path is mounted CLI Example: .. code-block:: bash salt '*' mount.read_mount_cache /mnt/share ''' cache = salt.utils.mount.read_cache(__opts__) if cache: if 'mounts' in cache and cache['mounts']: if name in cache['mounts']: return cache['mounts'][name] return {} def write_mount_cache(real_name, device, mkmnt, fstype, mount_opts): ''' .. versionadded:: 2018.3.0 Provide information if the path is mounted :param real_name: The real name of the mount point where the device is mounted. :param device: The device that is being mounted. :param mkmnt: Whether or not the mount point should be created. :param fstype: The file system that is used. :param mount_opts: Additional options used when mounting the device. :return: Boolean if message was sent successfully. CLI Example: .. code-block:: bash salt '*' mount.write_mount_cache /mnt/share /dev/sda1 False ext4 defaults,nosuid ''' cache = salt.utils.mount.read_cache(__opts__) if not cache: cache = {} cache['mounts'] = {} else: if 'mounts' not in cache: cache['mounts'] = {} cache['mounts'][real_name] = {'device': device, 'fstype': fstype, 'mkmnt': mkmnt, 'opts': mount_opts} cache_write = salt.utils.mount.write_cache(cache, __opts__) if cache_write: return True else: raise CommandExecutionError('Unable to write mount cache.') def delete_mount_cache(real_name): ''' .. versionadded:: 2018.3.0 Provide information if the path is mounted CLI Example: .. code-block:: bash salt '*' mount.delete_mount_cache /mnt/share ''' cache = salt.utils.mount.read_cache(__opts__) if cache: if 'mounts' in cache: if real_name in cache['mounts']: del cache['mounts'][real_name] cache_write = salt.utils.mount.write_cache(cache, __opts__) if not cache_write: raise CommandExecutionError('Unable to write mount cache.') return True def _filesystems(config='/etc/filesystems', leading_key=True): ''' Return the contents of the filesystems in an OrderedDict config File containing filesystem infomation leading_key True return dictionary keyed by 'name' and value as dictionary with other keys, values (name excluded) OrderedDict({ '/dir' : OrderedDict({'dev': '/dev/hd8', .... }})) False return dictionary keyed by 'name' and value as dictionary with all keys, values (name included) OrderedDict({ '/dir' : OrderedDict({'name': '/dir', 'dev': '/dev/hd8', ... })}) ''' ret = OrderedDict() lines = [] parsing_block = False if not os.path.isfile(config) or 'AIX' not in __grains__['kernel']: return ret # read in block of filesystems, block starts with '/' till empty line with salt.utils.files.fopen(config) as ifile: for line in ifile: line = salt.utils.stringutils.to_unicode(line) # skip till first entry if not line.startswith('/') and not parsing_block: continue if line.startswith('/'): parsing_block = True lines.append(line) elif not line.split(): parsing_block = False try: entry = _FileSystemsEntry.dict_from_lines( lines, _FileSystemsEntry.compatibility_keys) lines = [] if 'opts' in entry: entry['opts'] = entry['opts'].split(',') while entry['name'] in ret: entry['name'] += '_' if leading_key: ret[entry.pop('name')] = entry else: ret[entry['name']] = entry except _FileSystemsEntry.ParseError: pass else: lines.append(line) return ret def filesystems(config='/etc/filesystems'): ''' .. versionadded:: 2018.3.3 List the contents of the filesystems CLI Example: .. code-block:: bash salt '*' mount.filesystems ''' ret = {} if 'AIX' not in __grains__['kernel']: return ret ret_dict = _filesystems(config) if ret_dict: ret_key = next(iter(ret_dict.keys())) ret = {ret_key: dict(ret_dict[ret_key])} return ret def set_filesystems( name, device, vfstype, opts='-', mount='true', config='/etc/filesystems', test=False, match_on='auto', **kwargs): ''' .. versionadded:: 2018.3.3 Verify that this mount is represented in the filesystems, change the mount to match the data passed, or add the mount if it is not present on AIX Provide information if the path is mounted :param name: The name of the mount point where the device is mounted. :param device: The device that is being mounted. :param vfstype: The file system that is used (AIX has two fstypes, fstype and vfstype - similar to Linux fstype) :param opts: Additional options used when mounting the device. :param mount: Mount if not mounted, default True. :param config: Configuration file, default /etc/filesystems. :param match: File systems type to match on, default auto CLI Example: .. code-block:: bash salt '*' mount.set_filesystems /mnt/foo /dev/sdz1 jfs2 ''' # Fix the opts type if it is a list if isinstance(opts, list): opts = ','.join(opts) # preserve arguments for updating entry_args = { 'name': name, 'dev': device.replace('\\ ', '\\040'), 'vfstype': vfstype, 'opts': opts, 'mount': mount, } view_lines = [] ret = None if 'AIX' not in __grains__['kernel']: return ret # Transform match_on into list--items will be checked later if isinstance(match_on, list): pass elif not isinstance(match_on, six.string_types): raise CommandExecutionError('match_on must be a string or list of strings') elif match_on == 'auto': # Try to guess right criteria for auto.... # added IBM types from sys/vmount.h after btrfs # NOTE: missing some special fstypes here specialFSes = frozenset([ 'none', 'tmpfs', 'sysfs', 'proc', 'fusectl', 'debugfs', 'securityfs', 'devtmpfs', 'cgroup', 'btrfs', 'cdrfs', 'procfs', 'jfs', 'jfs2', 'nfs', 'sfs', 'nfs3', 'cachefs', 'udfs', 'cifs', 'namefs', 'pmemfs', 'ahafs', 'nfs4', 'autofs', 'stnfs']) if vfstype in specialFSes: match_on = ['name'] else: match_on = ['dev'] else: match_on = [match_on] # generate entry and criteria objects, handle invalid keys in match_on entry_ip = _FileSystemsEntry.from_line(entry_args, kwargs) try: criteria = entry_ip.pick(match_on) except KeyError: filterFn = lambda key: key not in _FileSystemsEntry.compatibility_keys invalid_keys = filter(filterFn, match_on) raise CommandExecutionError('Unrecognized keys in match_on: "{0}"'.format(invalid_keys)) # parse file, use ret to cache status if not os.path.isfile(config): raise CommandExecutionError('Bad config file "{0}"'.format(config)) # read in block of filesystem, block starts with '/' till empty line try: fsys_filedict = _filesystems(config, False) for fsys_view in six.viewitems(fsys_filedict): if criteria.match(fsys_view): ret = 'present' if entry_ip.match(fsys_view): view_lines.append(fsys_view) else: ret = 'change' kv = entry_ip['name'] view_lines.append((kv, entry_ip)) else: view_lines.append(fsys_view) except (IOError, OSError) as exc: raise CommandExecutionError('Couldn\'t read from {0}: {1}'.format(config, exc)) # add line if not present or changed if ret is None: for dict_view in six.viewitems(entry_ip.dict_from_entry()): view_lines.append(dict_view) ret = 'new' if ret != 'present': # ret in ['new', 'change']: try: with salt.utils.files.fopen(config, 'wb') as ofile: # The line was changed, commit it! for fsys_view in view_lines: entry = fsys_view[1] mystrg = _FileSystemsEntry.dict_to_lines(entry) ofile.writelines(salt.utils.data.encode(mystrg)) except (IOError, OSError): raise CommandExecutionError('File not writable {0}'.format(config)) return ret def rm_filesystems(name, device, config='/etc/filesystems'): ''' .. versionadded:: 2018.3.3 Remove the mount point from the filesystems CLI Example: .. code-block:: bash salt '*' mount.rm_filesystems /mnt/foo /dev/sdg ''' modified = False view_lines = [] if 'AIX' not in __grains__['kernel']: return modified criteria = _FileSystemsEntry(name=name, dev=device) try: fsys_filedict = _filesystems(config, False) for fsys_view in six.viewitems(fsys_filedict): try: if criteria.match(fsys_view): modified = True else: view_lines.append(fsys_view) except _FileSystemsEntry.ParseError: view_lines.append(fsys_view) except (IOError, OSError) as exc: raise CommandExecutionError("Couldn't read from {0}: {1}".format(config, exc)) if modified: try: with salt.utils.files.fopen(config, 'wb') as ofile: for fsys_view in view_lines: entry = fsys_view[1] mystrg = _FileSystemsEntry.dict_to_lines(entry) ofile.writelines(salt.utils.data.encode(mystrg)) except (IOError, OSError) as exc: raise CommandExecutionError("Couldn't write to {0}: {1}".format(config, exc)) return modified
saltstack/salt
salt/modules/mount.py
fstab
python
def fstab(config='/etc/fstab'): ''' .. versionchanged:: 2016.3.2 List the contents of the fstab CLI Example: .. code-block:: bash salt '*' mount.fstab ''' ret = {} if not os.path.isfile(config): return ret with salt.utils.files.fopen(config) as ifile: for line in ifile: line = salt.utils.stringutils.to_unicode(line) try: if __grains__['kernel'] == 'SunOS': # Note: comments use in default vfstab file! if line[0] == '#': continue entry = _vfstab_entry.dict_from_line( line) else: entry = _fstab_entry.dict_from_line( line, _fstab_entry.compatibility_keys) entry['opts'] = entry['opts'].split(',') while entry['name'] in ret: entry['name'] += '_' ret[entry.pop('name')] = entry except _fstab_entry.ParseError: pass except _vfstab_entry.ParseError: pass return ret
.. versionchanged:: 2016.3.2 List the contents of the fstab CLI Example: .. code-block:: bash salt '*' mount.fstab
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/mount.py#L577-L617
[ "def fopen(*args, **kwargs):\n '''\n Wrapper around open() built-in to set CLOEXEC on the fd.\n\n This flag specifies that the file descriptor should be closed when an exec\n function is invoked;\n\n When a file descriptor is allocated (as with open or dup), this bit is\n initially cleared on the new file descriptor, meaning that descriptor will\n survive into the new program after exec.\n\n NB! We still have small race condition between open and fcntl.\n '''\n if six.PY3:\n try:\n # Don't permit stdin/stdout/stderr to be opened. The boolean False\n # and True are treated by Python 3's open() as file descriptors 0\n # and 1, respectively.\n if args[0] in (0, 1, 2):\n raise TypeError(\n '{0} is not a permitted file descriptor'.format(args[0])\n )\n except IndexError:\n pass\n binary = None\n # ensure 'binary' mode is always used on Windows in Python 2\n if ((six.PY2 and salt.utils.platform.is_windows() and 'binary' not in kwargs) or\n kwargs.pop('binary', False)):\n if len(args) > 1:\n args = list(args)\n if 'b' not in args[1]:\n args[1] = args[1].replace('t', 'b')\n if 'b' not in args[1]:\n args[1] += 'b'\n elif kwargs.get('mode'):\n if 'b' not in kwargs['mode']:\n kwargs['mode'] = kwargs['mode'].replace('t', 'b')\n if 'b' not in kwargs['mode']:\n kwargs['mode'] += 'b'\n else:\n # the default is to read\n kwargs['mode'] = 'rb'\n elif six.PY3 and 'encoding' not in kwargs:\n # In Python 3, if text mode is used and the encoding\n # is not specified, set the encoding to 'utf-8'.\n binary = False\n if len(args) > 1:\n args = list(args)\n if 'b' in args[1]:\n binary = True\n if kwargs.get('mode', None):\n if 'b' in kwargs['mode']:\n binary = True\n if not binary:\n kwargs['encoding'] = __salt_system_encoding__\n\n if six.PY3 and not binary and not kwargs.get('newline', None):\n kwargs['newline'] = ''\n\n f_handle = open(*args, **kwargs) # pylint: disable=resource-leakage\n\n if is_fcntl_available():\n # modify the file descriptor on systems with fcntl\n # unix and unix-like systems only\n try:\n FD_CLOEXEC = fcntl.FD_CLOEXEC # pylint: disable=C0103\n except AttributeError:\n FD_CLOEXEC = 1 # pylint: disable=C0103\n old_flags = fcntl.fcntl(f_handle.fileno(), fcntl.F_GETFD)\n fcntl.fcntl(f_handle.fileno(), fcntl.F_SETFD, old_flags | FD_CLOEXEC)\n\n return f_handle\n", "def to_unicode(s, encoding=None, errors='strict', normalize=False):\n '''\n Given str or unicode, return unicode (str for python 3)\n '''\n def _normalize(s):\n return unicodedata.normalize('NFC', s) if normalize else s\n\n if encoding is None:\n # Try utf-8 first, and fall back to detected encoding\n encoding = ('utf-8', __salt_system_encoding__)\n if not isinstance(encoding, (tuple, list)):\n encoding = (encoding,)\n\n if not encoding:\n raise ValueError('encoding cannot be empty')\n\n exc = None\n if six.PY3:\n if isinstance(s, str):\n return _normalize(s)\n elif isinstance(s, (bytes, bytearray)):\n return _normalize(to_str(s, encoding, errors))\n raise TypeError('expected str, bytes, or bytearray')\n else:\n # This needs to be str and not six.string_types, since if the string is\n # already a unicode type, it does not need to be decoded (and doing so\n # will raise an exception).\n if isinstance(s, unicode): # pylint: disable=incompatible-py3-code,undefined-variable\n return _normalize(s)\n elif isinstance(s, (str, bytearray)):\n for enc in encoding:\n try:\n return _normalize(s.decode(enc, errors))\n except UnicodeDecodeError as err:\n exc = err\n continue\n # The only way we get this far is if a UnicodeDecodeError was\n # raised, otherwise we would have already returned (or raised some\n # other exception).\n raise exc # pylint: disable=raising-bad-type\n raise TypeError('expected str or bytearray')\n", "def dict_from_line(cls, line, keys=fstab_keys):\n if len(keys) != 6:\n raise ValueError('Invalid key array: {0}'.format(keys))\n if line.startswith('#'):\n raise cls.ParseError(\"Comment!\")\n\n comps = line.split()\n if len(comps) < 4 or len(comps) > 6:\n raise cls.ParseError(\"Invalid Entry!\")\n\n comps.extend(['0'] * (len(keys) - len(comps)))\n\n return dict(zip(keys, comps))\n", "def dict_from_line(cls, line):\n if line.startswith('#'):\n raise cls.ParseError(\"Comment!\")\n\n comps = line.split()\n if len(comps) != 7:\n raise cls.ParseError(\"Invalid Entry!\")\n\n return dict(zip(cls.vfstab_keys, comps))\n" ]
# -*- coding: utf-8 -*- ''' Salt module to manage Unix mounts and the fstab file ''' # Import python libs from __future__ import absolute_import, print_function, unicode_literals import os import re import logging # Import salt libs import salt.utils.args import salt.utils.data import salt.utils.files import salt.utils.path import salt.utils.platform import salt.utils.mount import salt.utils.stringutils from salt.utils.odict import OrderedDict from salt.exceptions import CommandNotFoundError, CommandExecutionError # Import 3rd-party libs from salt.ext import six from salt.ext.six.moves import filter, zip # pylint: disable=import-error,redefined-builtin # Set up logger log = logging.getLogger(__name__) # Define the module's virtual name __virtualname__ = 'mount' def __virtual__(): ''' Only load on POSIX-like systems ''' # Disable on Windows, a specific file module exists: if salt.utils.platform.is_windows(): return (False, 'The mount module cannot be loaded: not a POSIX-like system.') return True def _list_mounts(): ret = {} if __grains__['os'] in ['MacOS', 'Darwin']: mounts = __salt__['cmd.run_stdout']('mount') else: mounts = __salt__['cmd.run_stdout']('mount -l') for line in mounts.split('\n'): comps = re.sub(r"\s+", " ", line).split() if len(comps) >= 3: ret[comps[2]] = comps[0] return ret def _active_mountinfo(ret): _list = _list_mounts() filename = '/proc/self/mountinfo' if not os.access(filename, os.R_OK): msg = 'File not readable {0}' raise CommandExecutionError(msg.format(filename)) if 'disk.blkid' not in __context__: __context__['disk.blkid'] = __salt__['disk.blkid']() blkid_info = __context__['disk.blkid'] with salt.utils.files.fopen(filename) as ifile: for line in ifile: comps = salt.utils.stringutils.to_unicode(line).split() device = comps[2].split(':') # each line can have any number of # optional parameters, we use the # location of the separator field to # determine the location of the elements # after it. _sep = comps.index('-') device_name = comps[_sep + 2] device_uuid = None device_label = None if device_name: device_uuid = blkid_info.get(device_name, {}).get('UUID') device_uuid = device_uuid and device_uuid.lower() device_label = blkid_info.get(device_name, {}).get('LABEL') ret[comps[4]] = {'mountid': comps[0], 'parentid': comps[1], 'major': device[0], 'minor': device[1], 'root': comps[3], 'opts': _resolve_user_group_names(comps[5].split(',')), 'fstype': comps[_sep + 1], 'device': device_name.replace('\\040', '\\ '), 'alt_device': _list.get(comps[4], None), 'superopts': _resolve_user_group_names(comps[_sep + 3].split(',')), 'device_uuid': device_uuid, 'device_label': device_label} return ret def _active_mounts(ret): ''' List active mounts on Linux systems ''' _list = _list_mounts() filename = '/proc/self/mounts' if not os.access(filename, os.R_OK): msg = 'File not readable {0}' raise CommandExecutionError(msg.format(filename)) with salt.utils.files.fopen(filename) as ifile: for line in ifile: comps = salt.utils.stringutils.to_unicode(line).split() ret[comps[1]] = {'device': comps[0], 'alt_device': _list.get(comps[1], None), 'fstype': comps[2], 'opts': _resolve_user_group_names(comps[3].split(','))} return ret def _active_mounts_aix(ret): ''' List active mounts on AIX systems ''' for line in __salt__['cmd.run_stdout']('mount -p').split('\n'): comps = re.sub(r"\s+", " ", line).split() if comps: if comps[0] == 'node' or comps[0] == '--------': continue comps_len = len(comps) if line.startswith((' ', '\t')): curr_opts = _resolve_user_group_names(comps[6].split(',')) if 7 == comps_len else [] if curr_opts: ret[comps[1]] = {'device': comps[0], 'fstype': comps[2], 'opts': curr_opts} else: ret[comps[1]] = {'device': comps[0], 'fstype': comps[2]} else: curr_opts = _resolve_user_group_names(comps[7].split(',')) if 8 == comps_len else [] if curr_opts: ret[comps[2]] = {'node': comps[0], 'device': comps[1], 'fstype': comps[3], 'opts': curr_opts} else: ret[comps[2]] = {'node': comps[0], 'device': comps[1], 'fstype': comps[3]} return ret def _active_mounts_freebsd(ret): ''' List active mounts on FreeBSD systems ''' for line in __salt__['cmd.run_stdout']('mount -p').split('\n'): comps = re.sub(r"\s+", " ", line).split() ret[comps[1]] = {'device': comps[0], 'fstype': comps[2], 'opts': _resolve_user_group_names(comps[3].split(','))} return ret def _active_mounts_solaris(ret): ''' List active mounts on Solaris systems ''' for line in __salt__['cmd.run_stdout']('mount -v').split('\n'): comps = re.sub(r"\s+", " ", line).split() ret[comps[2]] = {'device': comps[0], 'fstype': comps[4], 'opts': _resolve_user_group_names(comps[5].split('/'))} return ret def _active_mounts_openbsd(ret): ''' List active mounts on OpenBSD systems ''' for line in __salt__['cmd.run_stdout']('mount -v').split('\n'): comps = re.sub(r"\s+", " ", line).split() parens = re.findall(r'\((.*?)\)', line, re.DOTALL) if len(parens) > 1: nod = __salt__['cmd.run_stdout']('ls -l {0}'.format(comps[0])) nod = ' '.join(nod.split()).split(" ") ret[comps[3]] = {'device': comps[0], 'fstype': comps[5], 'opts': _resolve_user_group_names(parens[1].split(", ")), 'major': six.text_type(nod[4].strip(",")), 'minor': six.text_type(nod[5]), 'device_uuid': parens[0]} else: ret[comps[2]] = {'device': comps[0], 'fstype': comps[4], 'opts': _resolve_user_group_names(parens[0].split(", "))} return ret def _active_mounts_darwin(ret): ''' List active mounts on Mac OS systems ''' for line in __salt__['cmd.run_stdout']('mount').split('\n'): comps = re.sub(r"\s+", " ", line).split() parens = re.findall(r'\((.*?)\)', line, re.DOTALL)[0].split(", ") ret[comps[2]] = {'device': comps[0], 'fstype': parens[0], 'opts': _resolve_user_group_names(parens[1:])} return ret def _resolve_user_group_names(opts): ''' Resolve user and group names in related opts ''' name_id_opts = {'uid': 'user.info', 'gid': 'group.info'} for ind, opt in enumerate(opts): if opt.split('=')[0] in name_id_opts: _givenid = opt.split('=')[1] _param = opt.split('=')[0] _id = _givenid if not re.match('[0-9]+$', _givenid): _info = __salt__[name_id_opts[_param]](_givenid) if _info and _param in _info: _id = _info[_param] opts[ind] = _param + '=' + six.text_type(_id) opts[ind] = opts[ind].replace('\\040', '\\ ') return opts def active(extended=False): ''' List the active mounts. CLI Example: .. code-block:: bash salt '*' mount.active ''' ret = {} if __grains__['os'] == 'FreeBSD': _active_mounts_freebsd(ret) elif 'AIX' in __grains__['kernel']: _active_mounts_aix(ret) elif __grains__['kernel'] == 'SunOS': _active_mounts_solaris(ret) elif __grains__['os'] == 'OpenBSD': _active_mounts_openbsd(ret) elif __grains__['os'] in ['MacOS', 'Darwin']: _active_mounts_darwin(ret) else: if extended: try: _active_mountinfo(ret) except CommandExecutionError: _active_mounts(ret) else: _active_mounts(ret) return ret class _fstab_entry(object): ''' Utility class for manipulating fstab entries. Primarily we're parsing, formatting, and comparing lines. Parsing emits dicts expected from fstab() or raises a ValueError. Note: We'll probably want to use os.normpath and os.normcase on 'name' ''' class ParseError(ValueError): ''' Error raised when a line isn't parsible as an fstab entry ''' fstab_keys = ('device', 'name', 'fstype', 'opts', 'dump', 'pass_num') # preserve data format compatibility_keys = ('device', 'name', 'fstype', 'opts', 'dump', 'pass') fstab_format = '{device}\t\t{name}\t{fstype}\t{opts}\t{dump} {pass_num}\n' @classmethod def dict_from_line(cls, line, keys=fstab_keys): if len(keys) != 6: raise ValueError('Invalid key array: {0}'.format(keys)) if line.startswith('#'): raise cls.ParseError("Comment!") comps = line.split() if len(comps) < 4 or len(comps) > 6: raise cls.ParseError("Invalid Entry!") comps.extend(['0'] * (len(keys) - len(comps))) return dict(zip(keys, comps)) @classmethod def from_line(cls, *args, **kwargs): return cls(** cls.dict_from_line(*args, **kwargs)) @classmethod def dict_to_line(cls, entry): return cls.fstab_format.format(**entry) def __str__(self): ''' String value, only works for full repr ''' return self.dict_to_line(self.criteria) def __repr__(self): ''' Always works ''' return repr(self.criteria) def pick(self, keys): ''' Returns an instance with just those keys ''' subset = dict([(key, self.criteria[key]) for key in keys]) return self.__class__(**subset) def __init__(self, **criteria): ''' Store non-empty, non-null values to use as filter ''' items = [key_value for key_value in six.iteritems(criteria) if key_value[1] is not None] items = [(key_value1[0], six.text_type(key_value1[1])) for key_value1 in items] self.criteria = dict(items) @staticmethod def norm_path(path): ''' Resolve equivalent paths equivalently ''' return os.path.normcase(os.path.normpath(path)) def match(self, line): ''' Compare potentially partial criteria against line ''' entry = self.dict_from_line(line) for key, value in six.iteritems(self.criteria): if entry[key] != value: return False return True class _vfstab_entry(object): ''' Utility class for manipulating vfstab entries. Primarily we're parsing, formatting, and comparing lines. Parsing emits dicts expected from fstab() or raises a ValueError. Note: We'll probably want to use os.normpath and os.normcase on 'name' Note: This parses vfstab entries on Solaris like systems #device device mount FS fsck mount mount #to mount to fsck point type pass at boot options # /devices - /devices devfs - no - ''' class ParseError(ValueError): '''Error raised when a line isn't parsible as an fstab entry''' vfstab_keys = ('device', 'device_fsck', 'name', 'fstype', 'pass_fsck', 'mount_at_boot', 'opts') # NOTE: weird formatting to match default spacing on Solaris vfstab_format = '{device:<11} {device_fsck:<3} {name:<19} {fstype:<8} {pass_fsck:<3} {mount_at_boot:<6} {opts}\n' @classmethod def dict_from_line(cls, line): if line.startswith('#'): raise cls.ParseError("Comment!") comps = line.split() if len(comps) != 7: raise cls.ParseError("Invalid Entry!") return dict(zip(cls.vfstab_keys, comps)) @classmethod def from_line(cls, *args, **kwargs): return cls(** cls.dict_from_line(*args, **kwargs)) @classmethod def dict_to_line(cls, entry): return cls.vfstab_format.format(**entry) def __str__(self): ''' String value, only works for full repr ''' return self.dict_to_line(self.criteria) def __repr__(self): ''' Always works ''' return repr(self.criteria) def pick(self, keys): ''' Returns an instance with just those keys ''' subset = dict([(key, self.criteria[key]) for key in keys]) return self.__class__(**subset) def __init__(self, **criteria): ''' Store non-empty, non-null values to use as filter ''' items = [key_value for key_value in six.iteritems(criteria) if key_value[1] is not None] items = [(key_value1[0], six.text_type(key_value1[1])) for key_value1 in items] self.criteria = dict(items) @staticmethod def norm_path(path): ''' Resolve equivalent paths equivalently ''' return os.path.normcase(os.path.normpath(path)) def match(self, line): ''' Compare potentially partial criteria against line ''' entry = self.dict_from_line(line) for key, value in six.iteritems(self.criteria): if entry[key] != value: return False return True class _FileSystemsEntry(object): ''' Utility class for manipulating filesystem entries. Primarily we're parsing, formatting, and comparing lines. Parsing emits dicts expected from fstab() or raises a ValueError. Note: We'll probably want to use os.normpath and os.normcase on 'name' ''' class ParseError(ValueError): ''' Error raised when a line isn't parsible as an fstab entry ''' filesystems_keys = ('device', 'name', 'fstype', 'vfstype', 'opts', 'mount') # preserve data format of filesystems compatibility_keys = ('dev', 'dev', 'name', 'fstype', 'vfstype', 'opts', 'mount', 'type', 'vfs', 'account', 'boot', 'check', 'free', 'nodename', 'quota', 'size', 'vol', 'log') @classmethod def dict_from_lines(cls, lines, keys=filesystems_keys): if len(lines) < 2: raise ValueError('Invalid number of lines: {0}'.format(lines)) if not keys: # if empty force default filesystems_keys keys = _FileSystemsEntry.filesystems_keys elif len(keys) < 6: raise ValueError('Invalid key name array: {0}'.format(keys)) blk_lines = lines orddict = OrderedDict() orddict['name'] = blk_lines[0].split(':')[0].strip() blk_lines.pop(0) for line in blk_lines: if line.startswith('#'): raise cls.ParseError("Comment!") comps = line.split('= ') if len(comps) != 2: raise cls.ParseError("Invalid Entry!") key_name = comps[0].strip() if key_name in keys: orddict[key_name] = comps[1].strip() else: raise ValueError('Invalid name for use in filesystems: {0}'.format(key_name)) return orddict @classmethod def dict_from_cmd_line(cls, ipargs, keys): cmdln_dict = ipargs if keys: for key, value in keys: # ignore unknown or local scope keys if key.startswith('__'): continue if key in _FileSystemsEntry.compatibility_keys: cmdln_dict[key] = value return cmdln_dict @classmethod def from_line(cls, *args, **kwargs): return cls(** cls.dict_from_cmd_line(*args, **kwargs)) @classmethod def dict_to_lines(cls, fsys_dict_entry): entry = fsys_dict_entry strg_out = entry['name'] + ':' + os.linesep for k, v in six.viewitems(entry): if 'name' not in k: strg_out += '\t{0}\t\t= {1}'.format(k, v) + os.linesep strg_out += os.linesep return six.text_type(strg_out) def dict_from_entry(self): ret = OrderedDict() ret[self.criteria['name']] = self.criteria return ret def __str__(self): ''' String value, only works for full repr ''' return self.dict_to_lines(self.criteria) def __repr__(self): ''' Always works ''' return repr(self.criteria) def pick(self, keys): ''' Returns an instance with just those keys ''' subset = dict([(key, self.criteria[key]) for key in keys]) return self.__class__(**subset) def __init__(self, **criteria): ''' Store non-empty, non-null values to use as filter ''' items = [key_value for key_value in six.iteritems(criteria) if key_value[1] is not None] items = [(key_value1[0], six.text_type(key_value1[1])) for key_value1 in items] self.criteria = OrderedDict(items) @staticmethod def norm_path(path): ''' Resolve equivalent paths equivalently ''' return os.path.normcase(os.path.normpath(path)) def match(self, fsys_view): ''' Compare potentially partial criteria against built filesystems entry dictionary ''' evalue_dict = fsys_view[1] for key, value in six.viewitems(self.criteria): if key in evalue_dict: if evalue_dict[key] != value: return False else: return False return True def __getitem__(self, key): ''' Return value for input key ''' return self.criteria[key] def vfstab(config='/etc/vfstab'): ''' .. versionadded:: 2016.3.2 List the contents of the vfstab CLI Example: .. code-block:: bash salt '*' mount.vfstab ''' # NOTE: vfstab is a wrapper for fstab return fstab(config) def rm_fstab(name, device, config='/etc/fstab'): ''' .. versionchanged:: 2016.3.2 Remove the mount point from the fstab CLI Example: .. code-block:: bash salt '*' mount.rm_fstab /mnt/foo /dev/sdg ''' modified = False if __grains__['kernel'] == 'SunOS': criteria = _vfstab_entry(name=name, device=device) else: criteria = _fstab_entry(name=name, device=device) lines = [] try: with salt.utils.files.fopen(config, 'r') as ifile: for line in ifile: line = salt.utils.stringutils.to_unicode(line) try: if criteria.match(line): modified = True else: lines.append(line) except _fstab_entry.ParseError: lines.append(line) except _vfstab_entry.ParseError: lines.append(line) except (IOError, OSError) as exc: msg = "Couldn't read from {0}: {1}" raise CommandExecutionError(msg.format(config, exc)) if modified: try: with salt.utils.files.fopen(config, 'wb') as ofile: ofile.writelines(salt.utils.data.encode(lines)) except (IOError, OSError) as exc: msg = "Couldn't write to {0}: {1}" raise CommandExecutionError(msg.format(config, exc)) # Note: not clear why we always return 'True' # --just copying previous behavior at this point... return True def rm_vfstab(name, device, config='/etc/vfstab'): ''' .. versionadded:: 2016.3.2 Remove the mount point from the vfstab CLI Example: .. code-block:: bash salt '*' mount.rm_vfstab /mnt/foo /device/c0t0d0p0 ''' ## NOTE: rm_vfstab is a wrapper for rm_fstab return rm_fstab(name, device, config) def set_fstab( name, device, fstype, opts='defaults', dump=0, pass_num=0, config='/etc/fstab', test=False, match_on='auto', **kwargs): ''' Verify that this mount is represented in the fstab, change the mount to match the data passed, or add the mount if it is not present. CLI Example: .. code-block:: bash salt '*' mount.set_fstab /mnt/foo /dev/sdz1 ext4 ''' # Fix the opts type if it is a list if isinstance(opts, list): opts = ','.join(opts) # preserve arguments for updating entry_args = { 'name': name, 'device': device.replace('\\ ', '\\040'), 'fstype': fstype, 'opts': opts.replace('\\ ', '\\040'), 'dump': dump, 'pass_num': pass_num, } lines = [] ret = None # Transform match_on into list--items will be checked later if isinstance(match_on, list): pass elif not isinstance(match_on, six.string_types): msg = 'match_on must be a string or list of strings' raise CommandExecutionError(msg) elif match_on == 'auto': # Try to guess right criteria for auto.... # NOTE: missing some special fstypes here specialFSes = frozenset([ 'none', 'tmpfs', 'sysfs', 'proc', 'fusectl', 'debugfs', 'securityfs', 'devtmpfs', 'cgroup', 'btrfs']) if fstype in specialFSes: match_on = ['name'] else: match_on = ['device'] else: match_on = [match_on] # generate entry and criteria objects, handle invalid keys in match_on entry = _fstab_entry(**entry_args) try: criteria = entry.pick(match_on) except KeyError: filterFn = lambda key: key not in _fstab_entry.fstab_keys invalid_keys = filter(filterFn, match_on) msg = 'Unrecognized keys in match_on: "{0}"'.format(invalid_keys) raise CommandExecutionError(msg) # parse file, use ret to cache status if not os.path.isfile(config): raise CommandExecutionError('Bad config file "{0}"'.format(config)) try: with salt.utils.files.fopen(config, 'r') as ifile: for line in ifile: line = salt.utils.stringutils.to_unicode(line) try: if criteria.match(line): # Note: If ret isn't None here, # we've matched multiple lines ret = 'present' if entry.match(line): lines.append(line) else: ret = 'change' lines.append(six.text_type(entry)) else: lines.append(line) except _fstab_entry.ParseError: lines.append(line) except (IOError, OSError) as exc: msg = 'Couldn\'t read from {0}: {1}' raise CommandExecutionError(msg.format(config, exc)) # add line if not present or changed if ret is None: lines.append(six.text_type(entry)) ret = 'new' if ret != 'present': # ret in ['new', 'change']: if not salt.utils.args.test_mode(test=test, **kwargs): try: with salt.utils.files.fopen(config, 'wb') as ofile: # The line was changed, commit it! ofile.writelines(salt.utils.data.encode(lines)) except (IOError, OSError): msg = 'File not writable {0}' raise CommandExecutionError(msg.format(config)) return ret def set_vfstab( name, device, fstype, opts='-', device_fsck='-', pass_fsck='-', mount_at_boot='yes', config='/etc/vfstab', test=False, match_on='auto', **kwargs): ''' ..verionadded:: 2016.3.2 Verify that this mount is represented in the fstab, change the mount to match the data passed, or add the mount if it is not present. CLI Example: .. code-block:: bash salt '*' mount.set_vfstab /mnt/foo /device/c0t0d0p0 ufs ''' # Fix the opts type if it is a list if isinstance(opts, list): opts = ','.join(opts) # Map unknown values for mount_at_boot to no if mount_at_boot != 'yes': mount_at_boot = 'no' # preserve arguments for updating entry_args = { 'name': name, 'device': device, 'fstype': fstype, 'opts': opts, 'device_fsck': device_fsck, 'pass_fsck': pass_fsck, 'mount_at_boot': mount_at_boot, } lines = [] ret = None # Transform match_on into list--items will be checked later if isinstance(match_on, list): pass elif not isinstance(match_on, six.string_types): msg = 'match_on must be a string or list of strings' raise CommandExecutionError(msg) elif match_on == 'auto': # Try to guess right criteria for auto.... # NOTE: missing some special fstypes here specialFSes = frozenset([ 'devfs', 'proc', 'ctfs', 'objfs', 'sharefs', 'fs', 'tmpfs']) if fstype in specialFSes: match_on = ['name'] else: match_on = ['device'] else: match_on = [match_on] # generate entry and criteria objects, handle invalid keys in match_on entry = _vfstab_entry(**entry_args) try: criteria = entry.pick(match_on) except KeyError: filterFn = lambda key: key not in _vfstab_entry.vfstab_keys invalid_keys = filter(filterFn, match_on) msg = 'Unrecognized keys in match_on: "{0}"'.format(invalid_keys) raise CommandExecutionError(msg) # parse file, use ret to cache status if not os.path.isfile(config): raise CommandExecutionError('Bad config file "{0}"'.format(config)) try: with salt.utils.files.fopen(config, 'r') as ifile: for line in ifile: line = salt.utils.stringutils.to_unicode(line) try: if criteria.match(line): # Note: If ret isn't None here, # we've matched multiple lines ret = 'present' if entry.match(line): lines.append(line) else: ret = 'change' lines.append(six.text_type(entry)) else: lines.append(line) except _vfstab_entry.ParseError: lines.append(line) except (IOError, OSError) as exc: msg = 'Couldn\'t read from {0}: {1}' raise CommandExecutionError(msg.format(config, exc)) # add line if not present or changed if ret is None: lines.append(six.text_type(entry)) ret = 'new' if ret != 'present': # ret in ['new', 'change']: if not salt.utils.args.test_mode(test=test, **kwargs): try: with salt.utils.files.fopen(config, 'wb') as ofile: # The line was changed, commit it! ofile.writelines(salt.utils.data.encode(lines)) except (IOError, OSError): msg = 'File not writable {0}' raise CommandExecutionError(msg.format(config)) return ret def rm_automaster(name, device, config='/etc/auto_salt'): ''' Remove the mount point from the auto_master CLI Example: .. code-block:: bash salt '*' mount.rm_automaster /mnt/foo /dev/sdg ''' contents = automaster(config) if name not in contents: return True # The entry is present, get rid of it lines = [] try: with salt.utils.files.fopen(config, 'r') as ifile: for line in ifile: line = salt.utils.stringutils.to_unicode(line) if line.startswith('#'): # Commented lines.append(line) continue if not line.strip(): # Blank line lines.append(line) continue comps = line.split() if len(comps) != 3: # Invalid entry lines.append(line) continue comps = line.split() prefix = "/.." name_chk = comps[0].replace(prefix, "") device_fmt = comps[2].split(":") if device: if name_chk == name and device_fmt[1] == device: continue else: if name_chk == name: continue lines.append(line) except (IOError, OSError) as exc: msg = "Couldn't read from {0}: {1}" raise CommandExecutionError(msg.format(config, exc)) try: with salt.utils.files.fopen(config, 'wb') as ofile: ofile.writelines(salt.utils.data.encode(lines)) except (IOError, OSError) as exc: msg = "Couldn't write to {0}: {1}" raise CommandExecutionError(msg.format(config, exc)) # Update automount __salt__['cmd.run']('automount -cv') return True def set_automaster( name, device, fstype, opts='', config='/etc/auto_salt', test=False, **kwargs): ''' Verify that this mount is represented in the auto_salt, change the mount to match the data passed, or add the mount if it is not present. CLI Example: .. code-block:: bash salt '*' mount.set_automaster /mnt/foo /dev/sdz1 ext4 ''' # Fix the opts type if it is a list if isinstance(opts, list): opts = ','.join(opts) lines = [] change = False present = False automaster_file = "/etc/auto_master" if not os.path.isfile(config): __salt__['file.touch'](config) __salt__['file.append'](automaster_file, "/-\t\t\t{0}".format(config)) name = "/..{0}".format(name) device_fmt = "{0}:{1}".format(fstype, device) type_opts = "-fstype={0},{1}".format(fstype, opts) if fstype == 'smbfs': device_fmt = device_fmt.replace(fstype, "") try: with salt.utils.files.fopen(config, 'r') as ifile: for line in ifile: line = salt.utils.stringutils.to_unicode(line) if line.startswith('#'): # Commented lines.append(line) continue if not line.strip(): # Blank line lines.append(line) continue comps = line.split() if len(comps) != 3: # Invalid entry lines.append(line) continue if comps[0] == name or comps[2] == device_fmt: # check to see if there are changes # and fix them if there are any present = True if comps[0] != name: change = True comps[0] = name if comps[1] != type_opts: change = True comps[1] = type_opts if comps[2] != device_fmt: change = True comps[2] = device_fmt if change: log.debug( 'auto_master entry for mount point %s needs to be ' 'updated', name ) newline = ( '{0}\t{1}\t{2}\n'.format( name, type_opts, device_fmt) ) lines.append(newline) else: lines.append(line) except (IOError, OSError) as exc: msg = 'Couldn\'t read from {0}: {1}' raise CommandExecutionError(msg.format(config, exc)) if change: if not salt.utils.args.test_mode(test=test, **kwargs): try: with salt.utils.files.fopen(config, 'wb') as ofile: # The line was changed, commit it! ofile.writelines(salt.utils.data.encode(lines)) except (IOError, OSError): msg = 'File not writable {0}' raise CommandExecutionError(msg.format(config)) return 'change' if not change: if present: # The right entry is already here return 'present' else: if not salt.utils.args.test_mode(test=test, **kwargs): # The entry is new, add it to the end of the fstab newline = ( '{0}\t{1}\t{2}\n'.format( name, type_opts, device_fmt) ) lines.append(newline) try: with salt.utils.files.fopen(config, 'wb') as ofile: # The line was changed, commit it! ofile.writelines(salt.utils.data.encode(lines)) except (IOError, OSError): raise CommandExecutionError( 'File not writable {0}'.format( config ) ) return 'new' def automaster(config='/etc/auto_salt'): ''' List the contents of the auto master CLI Example: .. code-block:: bash salt '*' mount.automaster ''' ret = {} if not os.path.isfile(config): return ret with salt.utils.files.fopen(config) as ifile: for line in ifile: line = salt.utils.stringutils.to_unicode(line) if line.startswith('#'): # Commented continue if not line.strip(): # Blank line continue comps = line.split() if len(comps) != 3: # Invalid entry continue prefix = "/.." name = comps[0].replace(prefix, "") device_fmt = comps[2].split(":") opts = comps[1].split(',') ret[name] = {'device': device_fmt[1], 'fstype': opts[0], 'opts': opts[1:]} return ret def mount(name, device, mkmnt=False, fstype='', opts='defaults', user=None, util='mount'): ''' Mount a device CLI Example: .. code-block:: bash salt '*' mount.mount /mnt/foo /dev/sdz1 True ''' if util != 'mount': # This functionality used to live in img.mount_image if util == 'guestfs': return __salt__['guestfs.mount'](name, root=device) elif util == 'qemu_nbd': mnt = __salt__['qemu_nbd.init'](name, device) if not mnt: return False first = next(six.iterkeys(mnt)) __context__['img.mnt_{0}'.format(first)] = mnt return first return False # Darwin doesn't expect defaults when mounting without other options if 'defaults' in opts and __grains__['os'] in ['MacOS', 'Darwin', 'AIX']: opts = None if isinstance(opts, six.string_types): opts = opts.split(',') if not os.path.exists(name) and mkmnt: __salt__['file.mkdir'](name, user=user) args = '' if opts is not None: lopts = ','.join(opts) args = '-o {0}'.format(lopts) if fstype: # use of fstype on AIX differs from typical Linux use of -t # functionality AIX uses -v vfsname, -t fstype mounts all with # fstype in /etc/filesystems if 'AIX' in __grains__['os']: args += ' -v {0}'.format(fstype) elif 'solaris' in __grains__['os'].lower(): args += ' -F {0}'.format(fstype) else: args += ' -t {0}'.format(fstype) cmd = 'mount {0} {1} {2} '.format(args, device, name) out = __salt__['cmd.run_all'](cmd, runas=user, python_shell=False) if out['retcode']: return out['stderr'] return True def remount(name, device, mkmnt=False, fstype='', opts='defaults', user=None): ''' Attempt to remount a device, if the device is not already mounted, mount is called CLI Example: .. code-block:: bash salt '*' mount.remount /mnt/foo /dev/sdz1 True ''' force_mount = False if __grains__['os'] in ['MacOS', 'Darwin']: if opts == 'defaults': opts = 'noowners' if fstype == 'smbfs': force_mount = True if 'AIX' in __grains__['os']: if opts == 'defaults': opts = [] if isinstance(opts, six.string_types): opts = opts.split(',') mnts = active() if name in mnts: # The mount point is mounted, attempt to remount it with the given data if 'remount' not in opts and __grains__['os'] not in ['OpenBSD', 'MacOS', 'Darwin']: opts.append('remount') if force_mount: # We need to force the mount but first we should unmount umount(name, device, user=user) lopts = ','.join(opts) args = '-o {0}'.format(lopts) if fstype: # use of fstype on AIX differs from typical Linux use of # -t functionality AIX uses -v vfsname, -t fstype mounts # all with fstype in /etc/filesystems if 'AIX' in __grains__['os']: args += ' -v {0}'.format(fstype) elif 'solaris' in __grains__['os'].lower(): args += ' -F {0}'.format(fstype) else: args += ' -t {0}'.format(fstype) if __grains__['os'] not in ['OpenBSD', 'MacOS', 'Darwin'] or force_mount: cmd = 'mount {0} {1} {2} '.format(args, device, name) else: cmd = 'mount -u {0} {1} {2} '.format(args, device, name) out = __salt__['cmd.run_all'](cmd, runas=user, python_shell=False) if out['retcode']: return out['stderr'] return True # Mount a filesystem that isn't already return mount(name, device, mkmnt, fstype, opts, user=user) def umount(name, device=None, user=None, util='mount'): ''' Attempt to unmount a device by specifying the directory it is mounted on CLI Example: .. code-block:: bash salt '*' mount.umount /mnt/foo .. versionadded:: 2015.5.0 .. code-block:: bash salt '*' mount.umount /mnt/foo /dev/xvdc1 ''' if util != 'mount': # This functionality used to live in img.umount_image if 'qemu_nbd.clear' in __salt__: if 'img.mnt_{0}'.format(name) in __context__: __salt__['qemu_nbd.clear'](__context__['img.mnt_{0}'.format(name)]) return mnts = active() if name not in mnts: return "{0} does not have anything mounted".format(name) if not device: cmd = 'umount {0}'.format(name) else: cmd = 'umount {0}'.format(device) out = __salt__['cmd.run_all'](cmd, runas=user, python_shell=False) if out['retcode']: return out['stderr'] return True def is_fuse_exec(cmd): ''' Returns true if the command passed is a fuse mountable application. CLI Example: .. code-block:: bash salt '*' mount.is_fuse_exec sshfs ''' cmd_path = salt.utils.path.which(cmd) # No point in running ldd on a command that doesn't exist if not cmd_path: return False elif not salt.utils.path.which('ldd'): raise CommandNotFoundError('ldd') out = __salt__['cmd.run']('ldd {0}'.format(cmd_path), python_shell=False) return 'libfuse' in out def swaps(): ''' Return a dict containing information on active swap .. versionchanged:: 2016.3.2 CLI Example: .. code-block:: bash salt '*' mount.swaps ''' ret = {} if __grains__['kernel'] == 'SunOS': for line in __salt__['cmd.run_stdout']('swap -l').splitlines(): if line.startswith('swapfile'): continue comps = line.split() ret[comps[0]] = {'type': 'device' if comps[0].startswith(('/dev', 'swap')) else 'file', 'size': int(comps[3]), 'used': (int(comps[3]) - int(comps[4])), 'priority': '-'} elif 'AIX' in __grains__['kernel']: for line in __salt__['cmd.run_stdout']('swap -l').splitlines(): if line.startswith('device'): continue comps = line.split() # AIX uses MB for units ret[comps[0]] = {'type': 'device', 'size': int(comps[3][:-2]) * 1024, 'used': (int(comps[3][:-2]) - int(comps[4][:-2])) * 1024, 'priority': '-'} elif __grains__['os'] != 'OpenBSD': with salt.utils.files.fopen('/proc/swaps') as fp_: for line in fp_: line = salt.utils.stringutils.to_unicode(line) if line.startswith('Filename'): continue comps = line.split() ret[comps[0]] = {'type': comps[1], 'size': comps[2], 'used': comps[3], 'priority': comps[4]} else: for line in __salt__['cmd.run_stdout']('swapctl -kl').splitlines(): if line.startswith(('Device', 'Total')): continue swap_type = "file" comps = line.split() if comps[0].startswith('/dev/'): swap_type = "partition" ret[comps[0]] = {'type': swap_type, 'size': comps[1], 'used': comps[2], 'priority': comps[5]} return ret def swapon(name, priority=None): ''' Activate a swap disk .. versionchanged:: 2016.3.2 CLI Example: .. code-block:: bash salt '*' mount.swapon /root/swapfile ''' ret = {} on_ = swaps() if name in on_: ret['stats'] = on_[name] ret['new'] = False return ret if __grains__['kernel'] == 'SunOS': if __grains__['virtual'] != 'zone': __salt__['cmd.run']('swap -a {0}'.format(name), python_shell=False) else: return False else: cmd = 'swapon {0}'.format(name) if priority and 'AIX' not in __grains__['kernel']: cmd += ' -p {0}'.format(priority) __salt__['cmd.run'](cmd, python_shell=False) on_ = swaps() if name in on_: ret['stats'] = on_[name] ret['new'] = True return ret return ret def swapoff(name): ''' Deactivate a named swap mount .. versionchanged:: 2016.3.2 CLI Example: .. code-block:: bash salt '*' mount.swapoff /root/swapfile ''' on_ = swaps() if name in on_: if __grains__['kernel'] == 'SunOS': if __grains__['virtual'] != 'zone': __salt__['cmd.run']('swap -a {0}'.format(name), python_shell=False) else: return False elif __grains__['os'] != 'OpenBSD': __salt__['cmd.run']('swapoff {0}'.format(name), python_shell=False) else: __salt__['cmd.run']('swapctl -d {0}'.format(name), python_shell=False) on_ = swaps() if name in on_: return False return True return None def is_mounted(name): ''' .. versionadded:: 2014.7.0 Provide information if the path is mounted CLI Example: .. code-block:: bash salt '*' mount.is_mounted /mnt/share ''' active_ = active() if name in active_: return True else: return False def read_mount_cache(name): ''' .. versionadded:: 2018.3.0 Provide information if the path is mounted CLI Example: .. code-block:: bash salt '*' mount.read_mount_cache /mnt/share ''' cache = salt.utils.mount.read_cache(__opts__) if cache: if 'mounts' in cache and cache['mounts']: if name in cache['mounts']: return cache['mounts'][name] return {} def write_mount_cache(real_name, device, mkmnt, fstype, mount_opts): ''' .. versionadded:: 2018.3.0 Provide information if the path is mounted :param real_name: The real name of the mount point where the device is mounted. :param device: The device that is being mounted. :param mkmnt: Whether or not the mount point should be created. :param fstype: The file system that is used. :param mount_opts: Additional options used when mounting the device. :return: Boolean if message was sent successfully. CLI Example: .. code-block:: bash salt '*' mount.write_mount_cache /mnt/share /dev/sda1 False ext4 defaults,nosuid ''' cache = salt.utils.mount.read_cache(__opts__) if not cache: cache = {} cache['mounts'] = {} else: if 'mounts' not in cache: cache['mounts'] = {} cache['mounts'][real_name] = {'device': device, 'fstype': fstype, 'mkmnt': mkmnt, 'opts': mount_opts} cache_write = salt.utils.mount.write_cache(cache, __opts__) if cache_write: return True else: raise CommandExecutionError('Unable to write mount cache.') def delete_mount_cache(real_name): ''' .. versionadded:: 2018.3.0 Provide information if the path is mounted CLI Example: .. code-block:: bash salt '*' mount.delete_mount_cache /mnt/share ''' cache = salt.utils.mount.read_cache(__opts__) if cache: if 'mounts' in cache: if real_name in cache['mounts']: del cache['mounts'][real_name] cache_write = salt.utils.mount.write_cache(cache, __opts__) if not cache_write: raise CommandExecutionError('Unable to write mount cache.') return True def _filesystems(config='/etc/filesystems', leading_key=True): ''' Return the contents of the filesystems in an OrderedDict config File containing filesystem infomation leading_key True return dictionary keyed by 'name' and value as dictionary with other keys, values (name excluded) OrderedDict({ '/dir' : OrderedDict({'dev': '/dev/hd8', .... }})) False return dictionary keyed by 'name' and value as dictionary with all keys, values (name included) OrderedDict({ '/dir' : OrderedDict({'name': '/dir', 'dev': '/dev/hd8', ... })}) ''' ret = OrderedDict() lines = [] parsing_block = False if not os.path.isfile(config) or 'AIX' not in __grains__['kernel']: return ret # read in block of filesystems, block starts with '/' till empty line with salt.utils.files.fopen(config) as ifile: for line in ifile: line = salt.utils.stringutils.to_unicode(line) # skip till first entry if not line.startswith('/') and not parsing_block: continue if line.startswith('/'): parsing_block = True lines.append(line) elif not line.split(): parsing_block = False try: entry = _FileSystemsEntry.dict_from_lines( lines, _FileSystemsEntry.compatibility_keys) lines = [] if 'opts' in entry: entry['opts'] = entry['opts'].split(',') while entry['name'] in ret: entry['name'] += '_' if leading_key: ret[entry.pop('name')] = entry else: ret[entry['name']] = entry except _FileSystemsEntry.ParseError: pass else: lines.append(line) return ret def filesystems(config='/etc/filesystems'): ''' .. versionadded:: 2018.3.3 List the contents of the filesystems CLI Example: .. code-block:: bash salt '*' mount.filesystems ''' ret = {} if 'AIX' not in __grains__['kernel']: return ret ret_dict = _filesystems(config) if ret_dict: ret_key = next(iter(ret_dict.keys())) ret = {ret_key: dict(ret_dict[ret_key])} return ret def set_filesystems( name, device, vfstype, opts='-', mount='true', config='/etc/filesystems', test=False, match_on='auto', **kwargs): ''' .. versionadded:: 2018.3.3 Verify that this mount is represented in the filesystems, change the mount to match the data passed, or add the mount if it is not present on AIX Provide information if the path is mounted :param name: The name of the mount point where the device is mounted. :param device: The device that is being mounted. :param vfstype: The file system that is used (AIX has two fstypes, fstype and vfstype - similar to Linux fstype) :param opts: Additional options used when mounting the device. :param mount: Mount if not mounted, default True. :param config: Configuration file, default /etc/filesystems. :param match: File systems type to match on, default auto CLI Example: .. code-block:: bash salt '*' mount.set_filesystems /mnt/foo /dev/sdz1 jfs2 ''' # Fix the opts type if it is a list if isinstance(opts, list): opts = ','.join(opts) # preserve arguments for updating entry_args = { 'name': name, 'dev': device.replace('\\ ', '\\040'), 'vfstype': vfstype, 'opts': opts, 'mount': mount, } view_lines = [] ret = None if 'AIX' not in __grains__['kernel']: return ret # Transform match_on into list--items will be checked later if isinstance(match_on, list): pass elif not isinstance(match_on, six.string_types): raise CommandExecutionError('match_on must be a string or list of strings') elif match_on == 'auto': # Try to guess right criteria for auto.... # added IBM types from sys/vmount.h after btrfs # NOTE: missing some special fstypes here specialFSes = frozenset([ 'none', 'tmpfs', 'sysfs', 'proc', 'fusectl', 'debugfs', 'securityfs', 'devtmpfs', 'cgroup', 'btrfs', 'cdrfs', 'procfs', 'jfs', 'jfs2', 'nfs', 'sfs', 'nfs3', 'cachefs', 'udfs', 'cifs', 'namefs', 'pmemfs', 'ahafs', 'nfs4', 'autofs', 'stnfs']) if vfstype in specialFSes: match_on = ['name'] else: match_on = ['dev'] else: match_on = [match_on] # generate entry and criteria objects, handle invalid keys in match_on entry_ip = _FileSystemsEntry.from_line(entry_args, kwargs) try: criteria = entry_ip.pick(match_on) except KeyError: filterFn = lambda key: key not in _FileSystemsEntry.compatibility_keys invalid_keys = filter(filterFn, match_on) raise CommandExecutionError('Unrecognized keys in match_on: "{0}"'.format(invalid_keys)) # parse file, use ret to cache status if not os.path.isfile(config): raise CommandExecutionError('Bad config file "{0}"'.format(config)) # read in block of filesystem, block starts with '/' till empty line try: fsys_filedict = _filesystems(config, False) for fsys_view in six.viewitems(fsys_filedict): if criteria.match(fsys_view): ret = 'present' if entry_ip.match(fsys_view): view_lines.append(fsys_view) else: ret = 'change' kv = entry_ip['name'] view_lines.append((kv, entry_ip)) else: view_lines.append(fsys_view) except (IOError, OSError) as exc: raise CommandExecutionError('Couldn\'t read from {0}: {1}'.format(config, exc)) # add line if not present or changed if ret is None: for dict_view in six.viewitems(entry_ip.dict_from_entry()): view_lines.append(dict_view) ret = 'new' if ret != 'present': # ret in ['new', 'change']: try: with salt.utils.files.fopen(config, 'wb') as ofile: # The line was changed, commit it! for fsys_view in view_lines: entry = fsys_view[1] mystrg = _FileSystemsEntry.dict_to_lines(entry) ofile.writelines(salt.utils.data.encode(mystrg)) except (IOError, OSError): raise CommandExecutionError('File not writable {0}'.format(config)) return ret def rm_filesystems(name, device, config='/etc/filesystems'): ''' .. versionadded:: 2018.3.3 Remove the mount point from the filesystems CLI Example: .. code-block:: bash salt '*' mount.rm_filesystems /mnt/foo /dev/sdg ''' modified = False view_lines = [] if 'AIX' not in __grains__['kernel']: return modified criteria = _FileSystemsEntry(name=name, dev=device) try: fsys_filedict = _filesystems(config, False) for fsys_view in six.viewitems(fsys_filedict): try: if criteria.match(fsys_view): modified = True else: view_lines.append(fsys_view) except _FileSystemsEntry.ParseError: view_lines.append(fsys_view) except (IOError, OSError) as exc: raise CommandExecutionError("Couldn't read from {0}: {1}".format(config, exc)) if modified: try: with salt.utils.files.fopen(config, 'wb') as ofile: for fsys_view in view_lines: entry = fsys_view[1] mystrg = _FileSystemsEntry.dict_to_lines(entry) ofile.writelines(salt.utils.data.encode(mystrg)) except (IOError, OSError) as exc: raise CommandExecutionError("Couldn't write to {0}: {1}".format(config, exc)) return modified
saltstack/salt
salt/modules/mount.py
rm_fstab
python
def rm_fstab(name, device, config='/etc/fstab'): ''' .. versionchanged:: 2016.3.2 Remove the mount point from the fstab CLI Example: .. code-block:: bash salt '*' mount.rm_fstab /mnt/foo /dev/sdg ''' modified = False if __grains__['kernel'] == 'SunOS': criteria = _vfstab_entry(name=name, device=device) else: criteria = _fstab_entry(name=name, device=device) lines = [] try: with salt.utils.files.fopen(config, 'r') as ifile: for line in ifile: line = salt.utils.stringutils.to_unicode(line) try: if criteria.match(line): modified = True else: lines.append(line) except _fstab_entry.ParseError: lines.append(line) except _vfstab_entry.ParseError: lines.append(line) except (IOError, OSError) as exc: msg = "Couldn't read from {0}: {1}" raise CommandExecutionError(msg.format(config, exc)) if modified: try: with salt.utils.files.fopen(config, 'wb') as ofile: ofile.writelines(salt.utils.data.encode(lines)) except (IOError, OSError) as exc: msg = "Couldn't write to {0}: {1}" raise CommandExecutionError(msg.format(config, exc)) # Note: not clear why we always return 'True' # --just copying previous behavior at this point... return True
.. versionchanged:: 2016.3.2 Remove the mount point from the fstab CLI Example: .. code-block:: bash salt '*' mount.rm_fstab /mnt/foo /dev/sdg
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/mount.py#L636-L685
[ "def encode(data, encoding=None, errors='strict', keep=False,\n preserve_dict_class=False, preserve_tuples=False):\n '''\n Generic function which will encode whichever type is passed, if necessary\n\n If `strict` is True, and `keep` is False, and we fail to encode, a\n UnicodeEncodeError will be raised. Passing `keep` as True allows for the\n original value to silently be returned in cases where encoding fails. This\n can be useful for cases where the data passed to this function is likely to\n contain binary blobs.\n '''\n if isinstance(data, Mapping):\n return encode_dict(data, encoding, errors, keep,\n preserve_dict_class, preserve_tuples)\n elif isinstance(data, list):\n return encode_list(data, encoding, errors, keep,\n preserve_dict_class, preserve_tuples)\n elif isinstance(data, tuple):\n return encode_tuple(data, encoding, errors, keep, preserve_dict_class) \\\n if preserve_tuples \\\n else encode_list(data, encoding, errors, keep,\n preserve_dict_class, preserve_tuples)\n else:\n try:\n return salt.utils.stringutils.to_bytes(data, encoding, errors)\n except TypeError:\n # to_bytes raises a TypeError when input is not a\n # string/bytestring/bytearray. This is expected and simply\n # means we are going to leave the value as-is.\n pass\n except UnicodeEncodeError:\n if not keep:\n raise\n return data\n", "def fopen(*args, **kwargs):\n '''\n Wrapper around open() built-in to set CLOEXEC on the fd.\n\n This flag specifies that the file descriptor should be closed when an exec\n function is invoked;\n\n When a file descriptor is allocated (as with open or dup), this bit is\n initially cleared on the new file descriptor, meaning that descriptor will\n survive into the new program after exec.\n\n NB! We still have small race condition between open and fcntl.\n '''\n if six.PY3:\n try:\n # Don't permit stdin/stdout/stderr to be opened. The boolean False\n # and True are treated by Python 3's open() as file descriptors 0\n # and 1, respectively.\n if args[0] in (0, 1, 2):\n raise TypeError(\n '{0} is not a permitted file descriptor'.format(args[0])\n )\n except IndexError:\n pass\n binary = None\n # ensure 'binary' mode is always used on Windows in Python 2\n if ((six.PY2 and salt.utils.platform.is_windows() and 'binary' not in kwargs) or\n kwargs.pop('binary', False)):\n if len(args) > 1:\n args = list(args)\n if 'b' not in args[1]:\n args[1] = args[1].replace('t', 'b')\n if 'b' not in args[1]:\n args[1] += 'b'\n elif kwargs.get('mode'):\n if 'b' not in kwargs['mode']:\n kwargs['mode'] = kwargs['mode'].replace('t', 'b')\n if 'b' not in kwargs['mode']:\n kwargs['mode'] += 'b'\n else:\n # the default is to read\n kwargs['mode'] = 'rb'\n elif six.PY3 and 'encoding' not in kwargs:\n # In Python 3, if text mode is used and the encoding\n # is not specified, set the encoding to 'utf-8'.\n binary = False\n if len(args) > 1:\n args = list(args)\n if 'b' in args[1]:\n binary = True\n if kwargs.get('mode', None):\n if 'b' in kwargs['mode']:\n binary = True\n if not binary:\n kwargs['encoding'] = __salt_system_encoding__\n\n if six.PY3 and not binary and not kwargs.get('newline', None):\n kwargs['newline'] = ''\n\n f_handle = open(*args, **kwargs) # pylint: disable=resource-leakage\n\n if is_fcntl_available():\n # modify the file descriptor on systems with fcntl\n # unix and unix-like systems only\n try:\n FD_CLOEXEC = fcntl.FD_CLOEXEC # pylint: disable=C0103\n except AttributeError:\n FD_CLOEXEC = 1 # pylint: disable=C0103\n old_flags = fcntl.fcntl(f_handle.fileno(), fcntl.F_GETFD)\n fcntl.fcntl(f_handle.fileno(), fcntl.F_SETFD, old_flags | FD_CLOEXEC)\n\n return f_handle\n", "def to_unicode(s, encoding=None, errors='strict', normalize=False):\n '''\n Given str or unicode, return unicode (str for python 3)\n '''\n def _normalize(s):\n return unicodedata.normalize('NFC', s) if normalize else s\n\n if encoding is None:\n # Try utf-8 first, and fall back to detected encoding\n encoding = ('utf-8', __salt_system_encoding__)\n if not isinstance(encoding, (tuple, list)):\n encoding = (encoding,)\n\n if not encoding:\n raise ValueError('encoding cannot be empty')\n\n exc = None\n if six.PY3:\n if isinstance(s, str):\n return _normalize(s)\n elif isinstance(s, (bytes, bytearray)):\n return _normalize(to_str(s, encoding, errors))\n raise TypeError('expected str, bytes, or bytearray')\n else:\n # This needs to be str and not six.string_types, since if the string is\n # already a unicode type, it does not need to be decoded (and doing so\n # will raise an exception).\n if isinstance(s, unicode): # pylint: disable=incompatible-py3-code,undefined-variable\n return _normalize(s)\n elif isinstance(s, (str, bytearray)):\n for enc in encoding:\n try:\n return _normalize(s.decode(enc, errors))\n except UnicodeDecodeError as err:\n exc = err\n continue\n # The only way we get this far is if a UnicodeDecodeError was\n # raised, otherwise we would have already returned (or raised some\n # other exception).\n raise exc # pylint: disable=raising-bad-type\n raise TypeError('expected str or bytearray')\n", "def match(self, line):\n '''\n Compare potentially partial criteria against line\n '''\n entry = self.dict_from_line(line)\n for key, value in six.iteritems(self.criteria):\n if entry[key] != value:\n return False\n return True\n", "def match(self, line):\n '''\n Compare potentially partial criteria against line\n '''\n entry = self.dict_from_line(line)\n for key, value in six.iteritems(self.criteria):\n if entry[key] != value:\n return False\n return True\n" ]
# -*- coding: utf-8 -*- ''' Salt module to manage Unix mounts and the fstab file ''' # Import python libs from __future__ import absolute_import, print_function, unicode_literals import os import re import logging # Import salt libs import salt.utils.args import salt.utils.data import salt.utils.files import salt.utils.path import salt.utils.platform import salt.utils.mount import salt.utils.stringutils from salt.utils.odict import OrderedDict from salt.exceptions import CommandNotFoundError, CommandExecutionError # Import 3rd-party libs from salt.ext import six from salt.ext.six.moves import filter, zip # pylint: disable=import-error,redefined-builtin # Set up logger log = logging.getLogger(__name__) # Define the module's virtual name __virtualname__ = 'mount' def __virtual__(): ''' Only load on POSIX-like systems ''' # Disable on Windows, a specific file module exists: if salt.utils.platform.is_windows(): return (False, 'The mount module cannot be loaded: not a POSIX-like system.') return True def _list_mounts(): ret = {} if __grains__['os'] in ['MacOS', 'Darwin']: mounts = __salt__['cmd.run_stdout']('mount') else: mounts = __salt__['cmd.run_stdout']('mount -l') for line in mounts.split('\n'): comps = re.sub(r"\s+", " ", line).split() if len(comps) >= 3: ret[comps[2]] = comps[0] return ret def _active_mountinfo(ret): _list = _list_mounts() filename = '/proc/self/mountinfo' if not os.access(filename, os.R_OK): msg = 'File not readable {0}' raise CommandExecutionError(msg.format(filename)) if 'disk.blkid' not in __context__: __context__['disk.blkid'] = __salt__['disk.blkid']() blkid_info = __context__['disk.blkid'] with salt.utils.files.fopen(filename) as ifile: for line in ifile: comps = salt.utils.stringutils.to_unicode(line).split() device = comps[2].split(':') # each line can have any number of # optional parameters, we use the # location of the separator field to # determine the location of the elements # after it. _sep = comps.index('-') device_name = comps[_sep + 2] device_uuid = None device_label = None if device_name: device_uuid = blkid_info.get(device_name, {}).get('UUID') device_uuid = device_uuid and device_uuid.lower() device_label = blkid_info.get(device_name, {}).get('LABEL') ret[comps[4]] = {'mountid': comps[0], 'parentid': comps[1], 'major': device[0], 'minor': device[1], 'root': comps[3], 'opts': _resolve_user_group_names(comps[5].split(',')), 'fstype': comps[_sep + 1], 'device': device_name.replace('\\040', '\\ '), 'alt_device': _list.get(comps[4], None), 'superopts': _resolve_user_group_names(comps[_sep + 3].split(',')), 'device_uuid': device_uuid, 'device_label': device_label} return ret def _active_mounts(ret): ''' List active mounts on Linux systems ''' _list = _list_mounts() filename = '/proc/self/mounts' if not os.access(filename, os.R_OK): msg = 'File not readable {0}' raise CommandExecutionError(msg.format(filename)) with salt.utils.files.fopen(filename) as ifile: for line in ifile: comps = salt.utils.stringutils.to_unicode(line).split() ret[comps[1]] = {'device': comps[0], 'alt_device': _list.get(comps[1], None), 'fstype': comps[2], 'opts': _resolve_user_group_names(comps[3].split(','))} return ret def _active_mounts_aix(ret): ''' List active mounts on AIX systems ''' for line in __salt__['cmd.run_stdout']('mount -p').split('\n'): comps = re.sub(r"\s+", " ", line).split() if comps: if comps[0] == 'node' or comps[0] == '--------': continue comps_len = len(comps) if line.startswith((' ', '\t')): curr_opts = _resolve_user_group_names(comps[6].split(',')) if 7 == comps_len else [] if curr_opts: ret[comps[1]] = {'device': comps[0], 'fstype': comps[2], 'opts': curr_opts} else: ret[comps[1]] = {'device': comps[0], 'fstype': comps[2]} else: curr_opts = _resolve_user_group_names(comps[7].split(',')) if 8 == comps_len else [] if curr_opts: ret[comps[2]] = {'node': comps[0], 'device': comps[1], 'fstype': comps[3], 'opts': curr_opts} else: ret[comps[2]] = {'node': comps[0], 'device': comps[1], 'fstype': comps[3]} return ret def _active_mounts_freebsd(ret): ''' List active mounts on FreeBSD systems ''' for line in __salt__['cmd.run_stdout']('mount -p').split('\n'): comps = re.sub(r"\s+", " ", line).split() ret[comps[1]] = {'device': comps[0], 'fstype': comps[2], 'opts': _resolve_user_group_names(comps[3].split(','))} return ret def _active_mounts_solaris(ret): ''' List active mounts on Solaris systems ''' for line in __salt__['cmd.run_stdout']('mount -v').split('\n'): comps = re.sub(r"\s+", " ", line).split() ret[comps[2]] = {'device': comps[0], 'fstype': comps[4], 'opts': _resolve_user_group_names(comps[5].split('/'))} return ret def _active_mounts_openbsd(ret): ''' List active mounts on OpenBSD systems ''' for line in __salt__['cmd.run_stdout']('mount -v').split('\n'): comps = re.sub(r"\s+", " ", line).split() parens = re.findall(r'\((.*?)\)', line, re.DOTALL) if len(parens) > 1: nod = __salt__['cmd.run_stdout']('ls -l {0}'.format(comps[0])) nod = ' '.join(nod.split()).split(" ") ret[comps[3]] = {'device': comps[0], 'fstype': comps[5], 'opts': _resolve_user_group_names(parens[1].split(", ")), 'major': six.text_type(nod[4].strip(",")), 'minor': six.text_type(nod[5]), 'device_uuid': parens[0]} else: ret[comps[2]] = {'device': comps[0], 'fstype': comps[4], 'opts': _resolve_user_group_names(parens[0].split(", "))} return ret def _active_mounts_darwin(ret): ''' List active mounts on Mac OS systems ''' for line in __salt__['cmd.run_stdout']('mount').split('\n'): comps = re.sub(r"\s+", " ", line).split() parens = re.findall(r'\((.*?)\)', line, re.DOTALL)[0].split(", ") ret[comps[2]] = {'device': comps[0], 'fstype': parens[0], 'opts': _resolve_user_group_names(parens[1:])} return ret def _resolve_user_group_names(opts): ''' Resolve user and group names in related opts ''' name_id_opts = {'uid': 'user.info', 'gid': 'group.info'} for ind, opt in enumerate(opts): if opt.split('=')[0] in name_id_opts: _givenid = opt.split('=')[1] _param = opt.split('=')[0] _id = _givenid if not re.match('[0-9]+$', _givenid): _info = __salt__[name_id_opts[_param]](_givenid) if _info and _param in _info: _id = _info[_param] opts[ind] = _param + '=' + six.text_type(_id) opts[ind] = opts[ind].replace('\\040', '\\ ') return opts def active(extended=False): ''' List the active mounts. CLI Example: .. code-block:: bash salt '*' mount.active ''' ret = {} if __grains__['os'] == 'FreeBSD': _active_mounts_freebsd(ret) elif 'AIX' in __grains__['kernel']: _active_mounts_aix(ret) elif __grains__['kernel'] == 'SunOS': _active_mounts_solaris(ret) elif __grains__['os'] == 'OpenBSD': _active_mounts_openbsd(ret) elif __grains__['os'] in ['MacOS', 'Darwin']: _active_mounts_darwin(ret) else: if extended: try: _active_mountinfo(ret) except CommandExecutionError: _active_mounts(ret) else: _active_mounts(ret) return ret class _fstab_entry(object): ''' Utility class for manipulating fstab entries. Primarily we're parsing, formatting, and comparing lines. Parsing emits dicts expected from fstab() or raises a ValueError. Note: We'll probably want to use os.normpath and os.normcase on 'name' ''' class ParseError(ValueError): ''' Error raised when a line isn't parsible as an fstab entry ''' fstab_keys = ('device', 'name', 'fstype', 'opts', 'dump', 'pass_num') # preserve data format compatibility_keys = ('device', 'name', 'fstype', 'opts', 'dump', 'pass') fstab_format = '{device}\t\t{name}\t{fstype}\t{opts}\t{dump} {pass_num}\n' @classmethod def dict_from_line(cls, line, keys=fstab_keys): if len(keys) != 6: raise ValueError('Invalid key array: {0}'.format(keys)) if line.startswith('#'): raise cls.ParseError("Comment!") comps = line.split() if len(comps) < 4 or len(comps) > 6: raise cls.ParseError("Invalid Entry!") comps.extend(['0'] * (len(keys) - len(comps))) return dict(zip(keys, comps)) @classmethod def from_line(cls, *args, **kwargs): return cls(** cls.dict_from_line(*args, **kwargs)) @classmethod def dict_to_line(cls, entry): return cls.fstab_format.format(**entry) def __str__(self): ''' String value, only works for full repr ''' return self.dict_to_line(self.criteria) def __repr__(self): ''' Always works ''' return repr(self.criteria) def pick(self, keys): ''' Returns an instance with just those keys ''' subset = dict([(key, self.criteria[key]) for key in keys]) return self.__class__(**subset) def __init__(self, **criteria): ''' Store non-empty, non-null values to use as filter ''' items = [key_value for key_value in six.iteritems(criteria) if key_value[1] is not None] items = [(key_value1[0], six.text_type(key_value1[1])) for key_value1 in items] self.criteria = dict(items) @staticmethod def norm_path(path): ''' Resolve equivalent paths equivalently ''' return os.path.normcase(os.path.normpath(path)) def match(self, line): ''' Compare potentially partial criteria against line ''' entry = self.dict_from_line(line) for key, value in six.iteritems(self.criteria): if entry[key] != value: return False return True class _vfstab_entry(object): ''' Utility class for manipulating vfstab entries. Primarily we're parsing, formatting, and comparing lines. Parsing emits dicts expected from fstab() or raises a ValueError. Note: We'll probably want to use os.normpath and os.normcase on 'name' Note: This parses vfstab entries on Solaris like systems #device device mount FS fsck mount mount #to mount to fsck point type pass at boot options # /devices - /devices devfs - no - ''' class ParseError(ValueError): '''Error raised when a line isn't parsible as an fstab entry''' vfstab_keys = ('device', 'device_fsck', 'name', 'fstype', 'pass_fsck', 'mount_at_boot', 'opts') # NOTE: weird formatting to match default spacing on Solaris vfstab_format = '{device:<11} {device_fsck:<3} {name:<19} {fstype:<8} {pass_fsck:<3} {mount_at_boot:<6} {opts}\n' @classmethod def dict_from_line(cls, line): if line.startswith('#'): raise cls.ParseError("Comment!") comps = line.split() if len(comps) != 7: raise cls.ParseError("Invalid Entry!") return dict(zip(cls.vfstab_keys, comps)) @classmethod def from_line(cls, *args, **kwargs): return cls(** cls.dict_from_line(*args, **kwargs)) @classmethod def dict_to_line(cls, entry): return cls.vfstab_format.format(**entry) def __str__(self): ''' String value, only works for full repr ''' return self.dict_to_line(self.criteria) def __repr__(self): ''' Always works ''' return repr(self.criteria) def pick(self, keys): ''' Returns an instance with just those keys ''' subset = dict([(key, self.criteria[key]) for key in keys]) return self.__class__(**subset) def __init__(self, **criteria): ''' Store non-empty, non-null values to use as filter ''' items = [key_value for key_value in six.iteritems(criteria) if key_value[1] is not None] items = [(key_value1[0], six.text_type(key_value1[1])) for key_value1 in items] self.criteria = dict(items) @staticmethod def norm_path(path): ''' Resolve equivalent paths equivalently ''' return os.path.normcase(os.path.normpath(path)) def match(self, line): ''' Compare potentially partial criteria against line ''' entry = self.dict_from_line(line) for key, value in six.iteritems(self.criteria): if entry[key] != value: return False return True class _FileSystemsEntry(object): ''' Utility class for manipulating filesystem entries. Primarily we're parsing, formatting, and comparing lines. Parsing emits dicts expected from fstab() or raises a ValueError. Note: We'll probably want to use os.normpath and os.normcase on 'name' ''' class ParseError(ValueError): ''' Error raised when a line isn't parsible as an fstab entry ''' filesystems_keys = ('device', 'name', 'fstype', 'vfstype', 'opts', 'mount') # preserve data format of filesystems compatibility_keys = ('dev', 'dev', 'name', 'fstype', 'vfstype', 'opts', 'mount', 'type', 'vfs', 'account', 'boot', 'check', 'free', 'nodename', 'quota', 'size', 'vol', 'log') @classmethod def dict_from_lines(cls, lines, keys=filesystems_keys): if len(lines) < 2: raise ValueError('Invalid number of lines: {0}'.format(lines)) if not keys: # if empty force default filesystems_keys keys = _FileSystemsEntry.filesystems_keys elif len(keys) < 6: raise ValueError('Invalid key name array: {0}'.format(keys)) blk_lines = lines orddict = OrderedDict() orddict['name'] = blk_lines[0].split(':')[0].strip() blk_lines.pop(0) for line in blk_lines: if line.startswith('#'): raise cls.ParseError("Comment!") comps = line.split('= ') if len(comps) != 2: raise cls.ParseError("Invalid Entry!") key_name = comps[0].strip() if key_name in keys: orddict[key_name] = comps[1].strip() else: raise ValueError('Invalid name for use in filesystems: {0}'.format(key_name)) return orddict @classmethod def dict_from_cmd_line(cls, ipargs, keys): cmdln_dict = ipargs if keys: for key, value in keys: # ignore unknown or local scope keys if key.startswith('__'): continue if key in _FileSystemsEntry.compatibility_keys: cmdln_dict[key] = value return cmdln_dict @classmethod def from_line(cls, *args, **kwargs): return cls(** cls.dict_from_cmd_line(*args, **kwargs)) @classmethod def dict_to_lines(cls, fsys_dict_entry): entry = fsys_dict_entry strg_out = entry['name'] + ':' + os.linesep for k, v in six.viewitems(entry): if 'name' not in k: strg_out += '\t{0}\t\t= {1}'.format(k, v) + os.linesep strg_out += os.linesep return six.text_type(strg_out) def dict_from_entry(self): ret = OrderedDict() ret[self.criteria['name']] = self.criteria return ret def __str__(self): ''' String value, only works for full repr ''' return self.dict_to_lines(self.criteria) def __repr__(self): ''' Always works ''' return repr(self.criteria) def pick(self, keys): ''' Returns an instance with just those keys ''' subset = dict([(key, self.criteria[key]) for key in keys]) return self.__class__(**subset) def __init__(self, **criteria): ''' Store non-empty, non-null values to use as filter ''' items = [key_value for key_value in six.iteritems(criteria) if key_value[1] is not None] items = [(key_value1[0], six.text_type(key_value1[1])) for key_value1 in items] self.criteria = OrderedDict(items) @staticmethod def norm_path(path): ''' Resolve equivalent paths equivalently ''' return os.path.normcase(os.path.normpath(path)) def match(self, fsys_view): ''' Compare potentially partial criteria against built filesystems entry dictionary ''' evalue_dict = fsys_view[1] for key, value in six.viewitems(self.criteria): if key in evalue_dict: if evalue_dict[key] != value: return False else: return False return True def __getitem__(self, key): ''' Return value for input key ''' return self.criteria[key] def fstab(config='/etc/fstab'): ''' .. versionchanged:: 2016.3.2 List the contents of the fstab CLI Example: .. code-block:: bash salt '*' mount.fstab ''' ret = {} if not os.path.isfile(config): return ret with salt.utils.files.fopen(config) as ifile: for line in ifile: line = salt.utils.stringutils.to_unicode(line) try: if __grains__['kernel'] == 'SunOS': # Note: comments use in default vfstab file! if line[0] == '#': continue entry = _vfstab_entry.dict_from_line( line) else: entry = _fstab_entry.dict_from_line( line, _fstab_entry.compatibility_keys) entry['opts'] = entry['opts'].split(',') while entry['name'] in ret: entry['name'] += '_' ret[entry.pop('name')] = entry except _fstab_entry.ParseError: pass except _vfstab_entry.ParseError: pass return ret def vfstab(config='/etc/vfstab'): ''' .. versionadded:: 2016.3.2 List the contents of the vfstab CLI Example: .. code-block:: bash salt '*' mount.vfstab ''' # NOTE: vfstab is a wrapper for fstab return fstab(config) def rm_vfstab(name, device, config='/etc/vfstab'): ''' .. versionadded:: 2016.3.2 Remove the mount point from the vfstab CLI Example: .. code-block:: bash salt '*' mount.rm_vfstab /mnt/foo /device/c0t0d0p0 ''' ## NOTE: rm_vfstab is a wrapper for rm_fstab return rm_fstab(name, device, config) def set_fstab( name, device, fstype, opts='defaults', dump=0, pass_num=0, config='/etc/fstab', test=False, match_on='auto', **kwargs): ''' Verify that this mount is represented in the fstab, change the mount to match the data passed, or add the mount if it is not present. CLI Example: .. code-block:: bash salt '*' mount.set_fstab /mnt/foo /dev/sdz1 ext4 ''' # Fix the opts type if it is a list if isinstance(opts, list): opts = ','.join(opts) # preserve arguments for updating entry_args = { 'name': name, 'device': device.replace('\\ ', '\\040'), 'fstype': fstype, 'opts': opts.replace('\\ ', '\\040'), 'dump': dump, 'pass_num': pass_num, } lines = [] ret = None # Transform match_on into list--items will be checked later if isinstance(match_on, list): pass elif not isinstance(match_on, six.string_types): msg = 'match_on must be a string or list of strings' raise CommandExecutionError(msg) elif match_on == 'auto': # Try to guess right criteria for auto.... # NOTE: missing some special fstypes here specialFSes = frozenset([ 'none', 'tmpfs', 'sysfs', 'proc', 'fusectl', 'debugfs', 'securityfs', 'devtmpfs', 'cgroup', 'btrfs']) if fstype in specialFSes: match_on = ['name'] else: match_on = ['device'] else: match_on = [match_on] # generate entry and criteria objects, handle invalid keys in match_on entry = _fstab_entry(**entry_args) try: criteria = entry.pick(match_on) except KeyError: filterFn = lambda key: key not in _fstab_entry.fstab_keys invalid_keys = filter(filterFn, match_on) msg = 'Unrecognized keys in match_on: "{0}"'.format(invalid_keys) raise CommandExecutionError(msg) # parse file, use ret to cache status if not os.path.isfile(config): raise CommandExecutionError('Bad config file "{0}"'.format(config)) try: with salt.utils.files.fopen(config, 'r') as ifile: for line in ifile: line = salt.utils.stringutils.to_unicode(line) try: if criteria.match(line): # Note: If ret isn't None here, # we've matched multiple lines ret = 'present' if entry.match(line): lines.append(line) else: ret = 'change' lines.append(six.text_type(entry)) else: lines.append(line) except _fstab_entry.ParseError: lines.append(line) except (IOError, OSError) as exc: msg = 'Couldn\'t read from {0}: {1}' raise CommandExecutionError(msg.format(config, exc)) # add line if not present or changed if ret is None: lines.append(six.text_type(entry)) ret = 'new' if ret != 'present': # ret in ['new', 'change']: if not salt.utils.args.test_mode(test=test, **kwargs): try: with salt.utils.files.fopen(config, 'wb') as ofile: # The line was changed, commit it! ofile.writelines(salt.utils.data.encode(lines)) except (IOError, OSError): msg = 'File not writable {0}' raise CommandExecutionError(msg.format(config)) return ret def set_vfstab( name, device, fstype, opts='-', device_fsck='-', pass_fsck='-', mount_at_boot='yes', config='/etc/vfstab', test=False, match_on='auto', **kwargs): ''' ..verionadded:: 2016.3.2 Verify that this mount is represented in the fstab, change the mount to match the data passed, or add the mount if it is not present. CLI Example: .. code-block:: bash salt '*' mount.set_vfstab /mnt/foo /device/c0t0d0p0 ufs ''' # Fix the opts type if it is a list if isinstance(opts, list): opts = ','.join(opts) # Map unknown values for mount_at_boot to no if mount_at_boot != 'yes': mount_at_boot = 'no' # preserve arguments for updating entry_args = { 'name': name, 'device': device, 'fstype': fstype, 'opts': opts, 'device_fsck': device_fsck, 'pass_fsck': pass_fsck, 'mount_at_boot': mount_at_boot, } lines = [] ret = None # Transform match_on into list--items will be checked later if isinstance(match_on, list): pass elif not isinstance(match_on, six.string_types): msg = 'match_on must be a string or list of strings' raise CommandExecutionError(msg) elif match_on == 'auto': # Try to guess right criteria for auto.... # NOTE: missing some special fstypes here specialFSes = frozenset([ 'devfs', 'proc', 'ctfs', 'objfs', 'sharefs', 'fs', 'tmpfs']) if fstype in specialFSes: match_on = ['name'] else: match_on = ['device'] else: match_on = [match_on] # generate entry and criteria objects, handle invalid keys in match_on entry = _vfstab_entry(**entry_args) try: criteria = entry.pick(match_on) except KeyError: filterFn = lambda key: key not in _vfstab_entry.vfstab_keys invalid_keys = filter(filterFn, match_on) msg = 'Unrecognized keys in match_on: "{0}"'.format(invalid_keys) raise CommandExecutionError(msg) # parse file, use ret to cache status if not os.path.isfile(config): raise CommandExecutionError('Bad config file "{0}"'.format(config)) try: with salt.utils.files.fopen(config, 'r') as ifile: for line in ifile: line = salt.utils.stringutils.to_unicode(line) try: if criteria.match(line): # Note: If ret isn't None here, # we've matched multiple lines ret = 'present' if entry.match(line): lines.append(line) else: ret = 'change' lines.append(six.text_type(entry)) else: lines.append(line) except _vfstab_entry.ParseError: lines.append(line) except (IOError, OSError) as exc: msg = 'Couldn\'t read from {0}: {1}' raise CommandExecutionError(msg.format(config, exc)) # add line if not present or changed if ret is None: lines.append(six.text_type(entry)) ret = 'new' if ret != 'present': # ret in ['new', 'change']: if not salt.utils.args.test_mode(test=test, **kwargs): try: with salt.utils.files.fopen(config, 'wb') as ofile: # The line was changed, commit it! ofile.writelines(salt.utils.data.encode(lines)) except (IOError, OSError): msg = 'File not writable {0}' raise CommandExecutionError(msg.format(config)) return ret def rm_automaster(name, device, config='/etc/auto_salt'): ''' Remove the mount point from the auto_master CLI Example: .. code-block:: bash salt '*' mount.rm_automaster /mnt/foo /dev/sdg ''' contents = automaster(config) if name not in contents: return True # The entry is present, get rid of it lines = [] try: with salt.utils.files.fopen(config, 'r') as ifile: for line in ifile: line = salt.utils.stringutils.to_unicode(line) if line.startswith('#'): # Commented lines.append(line) continue if not line.strip(): # Blank line lines.append(line) continue comps = line.split() if len(comps) != 3: # Invalid entry lines.append(line) continue comps = line.split() prefix = "/.." name_chk = comps[0].replace(prefix, "") device_fmt = comps[2].split(":") if device: if name_chk == name and device_fmt[1] == device: continue else: if name_chk == name: continue lines.append(line) except (IOError, OSError) as exc: msg = "Couldn't read from {0}: {1}" raise CommandExecutionError(msg.format(config, exc)) try: with salt.utils.files.fopen(config, 'wb') as ofile: ofile.writelines(salt.utils.data.encode(lines)) except (IOError, OSError) as exc: msg = "Couldn't write to {0}: {1}" raise CommandExecutionError(msg.format(config, exc)) # Update automount __salt__['cmd.run']('automount -cv') return True def set_automaster( name, device, fstype, opts='', config='/etc/auto_salt', test=False, **kwargs): ''' Verify that this mount is represented in the auto_salt, change the mount to match the data passed, or add the mount if it is not present. CLI Example: .. code-block:: bash salt '*' mount.set_automaster /mnt/foo /dev/sdz1 ext4 ''' # Fix the opts type if it is a list if isinstance(opts, list): opts = ','.join(opts) lines = [] change = False present = False automaster_file = "/etc/auto_master" if not os.path.isfile(config): __salt__['file.touch'](config) __salt__['file.append'](automaster_file, "/-\t\t\t{0}".format(config)) name = "/..{0}".format(name) device_fmt = "{0}:{1}".format(fstype, device) type_opts = "-fstype={0},{1}".format(fstype, opts) if fstype == 'smbfs': device_fmt = device_fmt.replace(fstype, "") try: with salt.utils.files.fopen(config, 'r') as ifile: for line in ifile: line = salt.utils.stringutils.to_unicode(line) if line.startswith('#'): # Commented lines.append(line) continue if not line.strip(): # Blank line lines.append(line) continue comps = line.split() if len(comps) != 3: # Invalid entry lines.append(line) continue if comps[0] == name or comps[2] == device_fmt: # check to see if there are changes # and fix them if there are any present = True if comps[0] != name: change = True comps[0] = name if comps[1] != type_opts: change = True comps[1] = type_opts if comps[2] != device_fmt: change = True comps[2] = device_fmt if change: log.debug( 'auto_master entry for mount point %s needs to be ' 'updated', name ) newline = ( '{0}\t{1}\t{2}\n'.format( name, type_opts, device_fmt) ) lines.append(newline) else: lines.append(line) except (IOError, OSError) as exc: msg = 'Couldn\'t read from {0}: {1}' raise CommandExecutionError(msg.format(config, exc)) if change: if not salt.utils.args.test_mode(test=test, **kwargs): try: with salt.utils.files.fopen(config, 'wb') as ofile: # The line was changed, commit it! ofile.writelines(salt.utils.data.encode(lines)) except (IOError, OSError): msg = 'File not writable {0}' raise CommandExecutionError(msg.format(config)) return 'change' if not change: if present: # The right entry is already here return 'present' else: if not salt.utils.args.test_mode(test=test, **kwargs): # The entry is new, add it to the end of the fstab newline = ( '{0}\t{1}\t{2}\n'.format( name, type_opts, device_fmt) ) lines.append(newline) try: with salt.utils.files.fopen(config, 'wb') as ofile: # The line was changed, commit it! ofile.writelines(salt.utils.data.encode(lines)) except (IOError, OSError): raise CommandExecutionError( 'File not writable {0}'.format( config ) ) return 'new' def automaster(config='/etc/auto_salt'): ''' List the contents of the auto master CLI Example: .. code-block:: bash salt '*' mount.automaster ''' ret = {} if not os.path.isfile(config): return ret with salt.utils.files.fopen(config) as ifile: for line in ifile: line = salt.utils.stringutils.to_unicode(line) if line.startswith('#'): # Commented continue if not line.strip(): # Blank line continue comps = line.split() if len(comps) != 3: # Invalid entry continue prefix = "/.." name = comps[0].replace(prefix, "") device_fmt = comps[2].split(":") opts = comps[1].split(',') ret[name] = {'device': device_fmt[1], 'fstype': opts[0], 'opts': opts[1:]} return ret def mount(name, device, mkmnt=False, fstype='', opts='defaults', user=None, util='mount'): ''' Mount a device CLI Example: .. code-block:: bash salt '*' mount.mount /mnt/foo /dev/sdz1 True ''' if util != 'mount': # This functionality used to live in img.mount_image if util == 'guestfs': return __salt__['guestfs.mount'](name, root=device) elif util == 'qemu_nbd': mnt = __salt__['qemu_nbd.init'](name, device) if not mnt: return False first = next(six.iterkeys(mnt)) __context__['img.mnt_{0}'.format(first)] = mnt return first return False # Darwin doesn't expect defaults when mounting without other options if 'defaults' in opts and __grains__['os'] in ['MacOS', 'Darwin', 'AIX']: opts = None if isinstance(opts, six.string_types): opts = opts.split(',') if not os.path.exists(name) and mkmnt: __salt__['file.mkdir'](name, user=user) args = '' if opts is not None: lopts = ','.join(opts) args = '-o {0}'.format(lopts) if fstype: # use of fstype on AIX differs from typical Linux use of -t # functionality AIX uses -v vfsname, -t fstype mounts all with # fstype in /etc/filesystems if 'AIX' in __grains__['os']: args += ' -v {0}'.format(fstype) elif 'solaris' in __grains__['os'].lower(): args += ' -F {0}'.format(fstype) else: args += ' -t {0}'.format(fstype) cmd = 'mount {0} {1} {2} '.format(args, device, name) out = __salt__['cmd.run_all'](cmd, runas=user, python_shell=False) if out['retcode']: return out['stderr'] return True def remount(name, device, mkmnt=False, fstype='', opts='defaults', user=None): ''' Attempt to remount a device, if the device is not already mounted, mount is called CLI Example: .. code-block:: bash salt '*' mount.remount /mnt/foo /dev/sdz1 True ''' force_mount = False if __grains__['os'] in ['MacOS', 'Darwin']: if opts == 'defaults': opts = 'noowners' if fstype == 'smbfs': force_mount = True if 'AIX' in __grains__['os']: if opts == 'defaults': opts = [] if isinstance(opts, six.string_types): opts = opts.split(',') mnts = active() if name in mnts: # The mount point is mounted, attempt to remount it with the given data if 'remount' not in opts and __grains__['os'] not in ['OpenBSD', 'MacOS', 'Darwin']: opts.append('remount') if force_mount: # We need to force the mount but first we should unmount umount(name, device, user=user) lopts = ','.join(opts) args = '-o {0}'.format(lopts) if fstype: # use of fstype on AIX differs from typical Linux use of # -t functionality AIX uses -v vfsname, -t fstype mounts # all with fstype in /etc/filesystems if 'AIX' in __grains__['os']: args += ' -v {0}'.format(fstype) elif 'solaris' in __grains__['os'].lower(): args += ' -F {0}'.format(fstype) else: args += ' -t {0}'.format(fstype) if __grains__['os'] not in ['OpenBSD', 'MacOS', 'Darwin'] or force_mount: cmd = 'mount {0} {1} {2} '.format(args, device, name) else: cmd = 'mount -u {0} {1} {2} '.format(args, device, name) out = __salt__['cmd.run_all'](cmd, runas=user, python_shell=False) if out['retcode']: return out['stderr'] return True # Mount a filesystem that isn't already return mount(name, device, mkmnt, fstype, opts, user=user) def umount(name, device=None, user=None, util='mount'): ''' Attempt to unmount a device by specifying the directory it is mounted on CLI Example: .. code-block:: bash salt '*' mount.umount /mnt/foo .. versionadded:: 2015.5.0 .. code-block:: bash salt '*' mount.umount /mnt/foo /dev/xvdc1 ''' if util != 'mount': # This functionality used to live in img.umount_image if 'qemu_nbd.clear' in __salt__: if 'img.mnt_{0}'.format(name) in __context__: __salt__['qemu_nbd.clear'](__context__['img.mnt_{0}'.format(name)]) return mnts = active() if name not in mnts: return "{0} does not have anything mounted".format(name) if not device: cmd = 'umount {0}'.format(name) else: cmd = 'umount {0}'.format(device) out = __salt__['cmd.run_all'](cmd, runas=user, python_shell=False) if out['retcode']: return out['stderr'] return True def is_fuse_exec(cmd): ''' Returns true if the command passed is a fuse mountable application. CLI Example: .. code-block:: bash salt '*' mount.is_fuse_exec sshfs ''' cmd_path = salt.utils.path.which(cmd) # No point in running ldd on a command that doesn't exist if not cmd_path: return False elif not salt.utils.path.which('ldd'): raise CommandNotFoundError('ldd') out = __salt__['cmd.run']('ldd {0}'.format(cmd_path), python_shell=False) return 'libfuse' in out def swaps(): ''' Return a dict containing information on active swap .. versionchanged:: 2016.3.2 CLI Example: .. code-block:: bash salt '*' mount.swaps ''' ret = {} if __grains__['kernel'] == 'SunOS': for line in __salt__['cmd.run_stdout']('swap -l').splitlines(): if line.startswith('swapfile'): continue comps = line.split() ret[comps[0]] = {'type': 'device' if comps[0].startswith(('/dev', 'swap')) else 'file', 'size': int(comps[3]), 'used': (int(comps[3]) - int(comps[4])), 'priority': '-'} elif 'AIX' in __grains__['kernel']: for line in __salt__['cmd.run_stdout']('swap -l').splitlines(): if line.startswith('device'): continue comps = line.split() # AIX uses MB for units ret[comps[0]] = {'type': 'device', 'size': int(comps[3][:-2]) * 1024, 'used': (int(comps[3][:-2]) - int(comps[4][:-2])) * 1024, 'priority': '-'} elif __grains__['os'] != 'OpenBSD': with salt.utils.files.fopen('/proc/swaps') as fp_: for line in fp_: line = salt.utils.stringutils.to_unicode(line) if line.startswith('Filename'): continue comps = line.split() ret[comps[0]] = {'type': comps[1], 'size': comps[2], 'used': comps[3], 'priority': comps[4]} else: for line in __salt__['cmd.run_stdout']('swapctl -kl').splitlines(): if line.startswith(('Device', 'Total')): continue swap_type = "file" comps = line.split() if comps[0].startswith('/dev/'): swap_type = "partition" ret[comps[0]] = {'type': swap_type, 'size': comps[1], 'used': comps[2], 'priority': comps[5]} return ret def swapon(name, priority=None): ''' Activate a swap disk .. versionchanged:: 2016.3.2 CLI Example: .. code-block:: bash salt '*' mount.swapon /root/swapfile ''' ret = {} on_ = swaps() if name in on_: ret['stats'] = on_[name] ret['new'] = False return ret if __grains__['kernel'] == 'SunOS': if __grains__['virtual'] != 'zone': __salt__['cmd.run']('swap -a {0}'.format(name), python_shell=False) else: return False else: cmd = 'swapon {0}'.format(name) if priority and 'AIX' not in __grains__['kernel']: cmd += ' -p {0}'.format(priority) __salt__['cmd.run'](cmd, python_shell=False) on_ = swaps() if name in on_: ret['stats'] = on_[name] ret['new'] = True return ret return ret def swapoff(name): ''' Deactivate a named swap mount .. versionchanged:: 2016.3.2 CLI Example: .. code-block:: bash salt '*' mount.swapoff /root/swapfile ''' on_ = swaps() if name in on_: if __grains__['kernel'] == 'SunOS': if __grains__['virtual'] != 'zone': __salt__['cmd.run']('swap -a {0}'.format(name), python_shell=False) else: return False elif __grains__['os'] != 'OpenBSD': __salt__['cmd.run']('swapoff {0}'.format(name), python_shell=False) else: __salt__['cmd.run']('swapctl -d {0}'.format(name), python_shell=False) on_ = swaps() if name in on_: return False return True return None def is_mounted(name): ''' .. versionadded:: 2014.7.0 Provide information if the path is mounted CLI Example: .. code-block:: bash salt '*' mount.is_mounted /mnt/share ''' active_ = active() if name in active_: return True else: return False def read_mount_cache(name): ''' .. versionadded:: 2018.3.0 Provide information if the path is mounted CLI Example: .. code-block:: bash salt '*' mount.read_mount_cache /mnt/share ''' cache = salt.utils.mount.read_cache(__opts__) if cache: if 'mounts' in cache and cache['mounts']: if name in cache['mounts']: return cache['mounts'][name] return {} def write_mount_cache(real_name, device, mkmnt, fstype, mount_opts): ''' .. versionadded:: 2018.3.0 Provide information if the path is mounted :param real_name: The real name of the mount point where the device is mounted. :param device: The device that is being mounted. :param mkmnt: Whether or not the mount point should be created. :param fstype: The file system that is used. :param mount_opts: Additional options used when mounting the device. :return: Boolean if message was sent successfully. CLI Example: .. code-block:: bash salt '*' mount.write_mount_cache /mnt/share /dev/sda1 False ext4 defaults,nosuid ''' cache = salt.utils.mount.read_cache(__opts__) if not cache: cache = {} cache['mounts'] = {} else: if 'mounts' not in cache: cache['mounts'] = {} cache['mounts'][real_name] = {'device': device, 'fstype': fstype, 'mkmnt': mkmnt, 'opts': mount_opts} cache_write = salt.utils.mount.write_cache(cache, __opts__) if cache_write: return True else: raise CommandExecutionError('Unable to write mount cache.') def delete_mount_cache(real_name): ''' .. versionadded:: 2018.3.0 Provide information if the path is mounted CLI Example: .. code-block:: bash salt '*' mount.delete_mount_cache /mnt/share ''' cache = salt.utils.mount.read_cache(__opts__) if cache: if 'mounts' in cache: if real_name in cache['mounts']: del cache['mounts'][real_name] cache_write = salt.utils.mount.write_cache(cache, __opts__) if not cache_write: raise CommandExecutionError('Unable to write mount cache.') return True def _filesystems(config='/etc/filesystems', leading_key=True): ''' Return the contents of the filesystems in an OrderedDict config File containing filesystem infomation leading_key True return dictionary keyed by 'name' and value as dictionary with other keys, values (name excluded) OrderedDict({ '/dir' : OrderedDict({'dev': '/dev/hd8', .... }})) False return dictionary keyed by 'name' and value as dictionary with all keys, values (name included) OrderedDict({ '/dir' : OrderedDict({'name': '/dir', 'dev': '/dev/hd8', ... })}) ''' ret = OrderedDict() lines = [] parsing_block = False if not os.path.isfile(config) or 'AIX' not in __grains__['kernel']: return ret # read in block of filesystems, block starts with '/' till empty line with salt.utils.files.fopen(config) as ifile: for line in ifile: line = salt.utils.stringutils.to_unicode(line) # skip till first entry if not line.startswith('/') and not parsing_block: continue if line.startswith('/'): parsing_block = True lines.append(line) elif not line.split(): parsing_block = False try: entry = _FileSystemsEntry.dict_from_lines( lines, _FileSystemsEntry.compatibility_keys) lines = [] if 'opts' in entry: entry['opts'] = entry['opts'].split(',') while entry['name'] in ret: entry['name'] += '_' if leading_key: ret[entry.pop('name')] = entry else: ret[entry['name']] = entry except _FileSystemsEntry.ParseError: pass else: lines.append(line) return ret def filesystems(config='/etc/filesystems'): ''' .. versionadded:: 2018.3.3 List the contents of the filesystems CLI Example: .. code-block:: bash salt '*' mount.filesystems ''' ret = {} if 'AIX' not in __grains__['kernel']: return ret ret_dict = _filesystems(config) if ret_dict: ret_key = next(iter(ret_dict.keys())) ret = {ret_key: dict(ret_dict[ret_key])} return ret def set_filesystems( name, device, vfstype, opts='-', mount='true', config='/etc/filesystems', test=False, match_on='auto', **kwargs): ''' .. versionadded:: 2018.3.3 Verify that this mount is represented in the filesystems, change the mount to match the data passed, or add the mount if it is not present on AIX Provide information if the path is mounted :param name: The name of the mount point where the device is mounted. :param device: The device that is being mounted. :param vfstype: The file system that is used (AIX has two fstypes, fstype and vfstype - similar to Linux fstype) :param opts: Additional options used when mounting the device. :param mount: Mount if not mounted, default True. :param config: Configuration file, default /etc/filesystems. :param match: File systems type to match on, default auto CLI Example: .. code-block:: bash salt '*' mount.set_filesystems /mnt/foo /dev/sdz1 jfs2 ''' # Fix the opts type if it is a list if isinstance(opts, list): opts = ','.join(opts) # preserve arguments for updating entry_args = { 'name': name, 'dev': device.replace('\\ ', '\\040'), 'vfstype': vfstype, 'opts': opts, 'mount': mount, } view_lines = [] ret = None if 'AIX' not in __grains__['kernel']: return ret # Transform match_on into list--items will be checked later if isinstance(match_on, list): pass elif not isinstance(match_on, six.string_types): raise CommandExecutionError('match_on must be a string or list of strings') elif match_on == 'auto': # Try to guess right criteria for auto.... # added IBM types from sys/vmount.h after btrfs # NOTE: missing some special fstypes here specialFSes = frozenset([ 'none', 'tmpfs', 'sysfs', 'proc', 'fusectl', 'debugfs', 'securityfs', 'devtmpfs', 'cgroup', 'btrfs', 'cdrfs', 'procfs', 'jfs', 'jfs2', 'nfs', 'sfs', 'nfs3', 'cachefs', 'udfs', 'cifs', 'namefs', 'pmemfs', 'ahafs', 'nfs4', 'autofs', 'stnfs']) if vfstype in specialFSes: match_on = ['name'] else: match_on = ['dev'] else: match_on = [match_on] # generate entry and criteria objects, handle invalid keys in match_on entry_ip = _FileSystemsEntry.from_line(entry_args, kwargs) try: criteria = entry_ip.pick(match_on) except KeyError: filterFn = lambda key: key not in _FileSystemsEntry.compatibility_keys invalid_keys = filter(filterFn, match_on) raise CommandExecutionError('Unrecognized keys in match_on: "{0}"'.format(invalid_keys)) # parse file, use ret to cache status if not os.path.isfile(config): raise CommandExecutionError('Bad config file "{0}"'.format(config)) # read in block of filesystem, block starts with '/' till empty line try: fsys_filedict = _filesystems(config, False) for fsys_view in six.viewitems(fsys_filedict): if criteria.match(fsys_view): ret = 'present' if entry_ip.match(fsys_view): view_lines.append(fsys_view) else: ret = 'change' kv = entry_ip['name'] view_lines.append((kv, entry_ip)) else: view_lines.append(fsys_view) except (IOError, OSError) as exc: raise CommandExecutionError('Couldn\'t read from {0}: {1}'.format(config, exc)) # add line if not present or changed if ret is None: for dict_view in six.viewitems(entry_ip.dict_from_entry()): view_lines.append(dict_view) ret = 'new' if ret != 'present': # ret in ['new', 'change']: try: with salt.utils.files.fopen(config, 'wb') as ofile: # The line was changed, commit it! for fsys_view in view_lines: entry = fsys_view[1] mystrg = _FileSystemsEntry.dict_to_lines(entry) ofile.writelines(salt.utils.data.encode(mystrg)) except (IOError, OSError): raise CommandExecutionError('File not writable {0}'.format(config)) return ret def rm_filesystems(name, device, config='/etc/filesystems'): ''' .. versionadded:: 2018.3.3 Remove the mount point from the filesystems CLI Example: .. code-block:: bash salt '*' mount.rm_filesystems /mnt/foo /dev/sdg ''' modified = False view_lines = [] if 'AIX' not in __grains__['kernel']: return modified criteria = _FileSystemsEntry(name=name, dev=device) try: fsys_filedict = _filesystems(config, False) for fsys_view in six.viewitems(fsys_filedict): try: if criteria.match(fsys_view): modified = True else: view_lines.append(fsys_view) except _FileSystemsEntry.ParseError: view_lines.append(fsys_view) except (IOError, OSError) as exc: raise CommandExecutionError("Couldn't read from {0}: {1}".format(config, exc)) if modified: try: with salt.utils.files.fopen(config, 'wb') as ofile: for fsys_view in view_lines: entry = fsys_view[1] mystrg = _FileSystemsEntry.dict_to_lines(entry) ofile.writelines(salt.utils.data.encode(mystrg)) except (IOError, OSError) as exc: raise CommandExecutionError("Couldn't write to {0}: {1}".format(config, exc)) return modified
saltstack/salt
salt/modules/mount.py
set_fstab
python
def set_fstab( name, device, fstype, opts='defaults', dump=0, pass_num=0, config='/etc/fstab', test=False, match_on='auto', **kwargs): ''' Verify that this mount is represented in the fstab, change the mount to match the data passed, or add the mount if it is not present. CLI Example: .. code-block:: bash salt '*' mount.set_fstab /mnt/foo /dev/sdz1 ext4 ''' # Fix the opts type if it is a list if isinstance(opts, list): opts = ','.join(opts) # preserve arguments for updating entry_args = { 'name': name, 'device': device.replace('\\ ', '\\040'), 'fstype': fstype, 'opts': opts.replace('\\ ', '\\040'), 'dump': dump, 'pass_num': pass_num, } lines = [] ret = None # Transform match_on into list--items will be checked later if isinstance(match_on, list): pass elif not isinstance(match_on, six.string_types): msg = 'match_on must be a string or list of strings' raise CommandExecutionError(msg) elif match_on == 'auto': # Try to guess right criteria for auto.... # NOTE: missing some special fstypes here specialFSes = frozenset([ 'none', 'tmpfs', 'sysfs', 'proc', 'fusectl', 'debugfs', 'securityfs', 'devtmpfs', 'cgroup', 'btrfs']) if fstype in specialFSes: match_on = ['name'] else: match_on = ['device'] else: match_on = [match_on] # generate entry and criteria objects, handle invalid keys in match_on entry = _fstab_entry(**entry_args) try: criteria = entry.pick(match_on) except KeyError: filterFn = lambda key: key not in _fstab_entry.fstab_keys invalid_keys = filter(filterFn, match_on) msg = 'Unrecognized keys in match_on: "{0}"'.format(invalid_keys) raise CommandExecutionError(msg) # parse file, use ret to cache status if not os.path.isfile(config): raise CommandExecutionError('Bad config file "{0}"'.format(config)) try: with salt.utils.files.fopen(config, 'r') as ifile: for line in ifile: line = salt.utils.stringutils.to_unicode(line) try: if criteria.match(line): # Note: If ret isn't None here, # we've matched multiple lines ret = 'present' if entry.match(line): lines.append(line) else: ret = 'change' lines.append(six.text_type(entry)) else: lines.append(line) except _fstab_entry.ParseError: lines.append(line) except (IOError, OSError) as exc: msg = 'Couldn\'t read from {0}: {1}' raise CommandExecutionError(msg.format(config, exc)) # add line if not present or changed if ret is None: lines.append(six.text_type(entry)) ret = 'new' if ret != 'present': # ret in ['new', 'change']: if not salt.utils.args.test_mode(test=test, **kwargs): try: with salt.utils.files.fopen(config, 'wb') as ofile: # The line was changed, commit it! ofile.writelines(salt.utils.data.encode(lines)) except (IOError, OSError): msg = 'File not writable {0}' raise CommandExecutionError(msg.format(config)) return ret
Verify that this mount is represented in the fstab, change the mount to match the data passed, or add the mount if it is not present. CLI Example: .. code-block:: bash salt '*' mount.set_fstab /mnt/foo /dev/sdz1 ext4
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/mount.py#L704-L826
[ "def fopen(*args, **kwargs):\n '''\n Wrapper around open() built-in to set CLOEXEC on the fd.\n\n This flag specifies that the file descriptor should be closed when an exec\n function is invoked;\n\n When a file descriptor is allocated (as with open or dup), this bit is\n initially cleared on the new file descriptor, meaning that descriptor will\n survive into the new program after exec.\n\n NB! We still have small race condition between open and fcntl.\n '''\n if six.PY3:\n try:\n # Don't permit stdin/stdout/stderr to be opened. The boolean False\n # and True are treated by Python 3's open() as file descriptors 0\n # and 1, respectively.\n if args[0] in (0, 1, 2):\n raise TypeError(\n '{0} is not a permitted file descriptor'.format(args[0])\n )\n except IndexError:\n pass\n binary = None\n # ensure 'binary' mode is always used on Windows in Python 2\n if ((six.PY2 and salt.utils.platform.is_windows() and 'binary' not in kwargs) or\n kwargs.pop('binary', False)):\n if len(args) > 1:\n args = list(args)\n if 'b' not in args[1]:\n args[1] = args[1].replace('t', 'b')\n if 'b' not in args[1]:\n args[1] += 'b'\n elif kwargs.get('mode'):\n if 'b' not in kwargs['mode']:\n kwargs['mode'] = kwargs['mode'].replace('t', 'b')\n if 'b' not in kwargs['mode']:\n kwargs['mode'] += 'b'\n else:\n # the default is to read\n kwargs['mode'] = 'rb'\n elif six.PY3 and 'encoding' not in kwargs:\n # In Python 3, if text mode is used and the encoding\n # is not specified, set the encoding to 'utf-8'.\n binary = False\n if len(args) > 1:\n args = list(args)\n if 'b' in args[1]:\n binary = True\n if kwargs.get('mode', None):\n if 'b' in kwargs['mode']:\n binary = True\n if not binary:\n kwargs['encoding'] = __salt_system_encoding__\n\n if six.PY3 and not binary and not kwargs.get('newline', None):\n kwargs['newline'] = ''\n\n f_handle = open(*args, **kwargs) # pylint: disable=resource-leakage\n\n if is_fcntl_available():\n # modify the file descriptor on systems with fcntl\n # unix and unix-like systems only\n try:\n FD_CLOEXEC = fcntl.FD_CLOEXEC # pylint: disable=C0103\n except AttributeError:\n FD_CLOEXEC = 1 # pylint: disable=C0103\n old_flags = fcntl.fcntl(f_handle.fileno(), fcntl.F_GETFD)\n fcntl.fcntl(f_handle.fileno(), fcntl.F_SETFD, old_flags | FD_CLOEXEC)\n\n return f_handle\n", "def to_unicode(s, encoding=None, errors='strict', normalize=False):\n '''\n Given str or unicode, return unicode (str for python 3)\n '''\n def _normalize(s):\n return unicodedata.normalize('NFC', s) if normalize else s\n\n if encoding is None:\n # Try utf-8 first, and fall back to detected encoding\n encoding = ('utf-8', __salt_system_encoding__)\n if not isinstance(encoding, (tuple, list)):\n encoding = (encoding,)\n\n if not encoding:\n raise ValueError('encoding cannot be empty')\n\n exc = None\n if six.PY3:\n if isinstance(s, str):\n return _normalize(s)\n elif isinstance(s, (bytes, bytearray)):\n return _normalize(to_str(s, encoding, errors))\n raise TypeError('expected str, bytes, or bytearray')\n else:\n # This needs to be str and not six.string_types, since if the string is\n # already a unicode type, it does not need to be decoded (and doing so\n # will raise an exception).\n if isinstance(s, unicode): # pylint: disable=incompatible-py3-code,undefined-variable\n return _normalize(s)\n elif isinstance(s, (str, bytearray)):\n for enc in encoding:\n try:\n return _normalize(s.decode(enc, errors))\n except UnicodeDecodeError as err:\n exc = err\n continue\n # The only way we get this far is if a UnicodeDecodeError was\n # raised, otherwise we would have already returned (or raised some\n # other exception).\n raise exc # pylint: disable=raising-bad-type\n raise TypeError('expected str or bytearray')\n", "def test_mode(**kwargs):\n '''\n Examines the kwargs passed and returns True if any kwarg which matching\n \"Test\" in any variation on capitalization (i.e. \"TEST\", \"Test\", \"TeSt\",\n etc) contains a True value (as determined by salt.utils.data.is_true).\n '''\n # Once is_true is moved, remove this import and fix the ref below\n import salt.utils\n for arg, value in six.iteritems(kwargs):\n try:\n if arg.lower() == 'test' and salt.utils.data.is_true(value):\n return True\n except AttributeError:\n continue\n return False\n", "def pick(self, keys):\n '''\n Returns an instance with just those keys\n '''\n subset = dict([(key, self.criteria[key]) for key in keys])\n return self.__class__(**subset)\n", "def match(self, line):\n '''\n Compare potentially partial criteria against line\n '''\n entry = self.dict_from_line(line)\n for key, value in six.iteritems(self.criteria):\n if entry[key] != value:\n return False\n return True\n" ]
# -*- coding: utf-8 -*- ''' Salt module to manage Unix mounts and the fstab file ''' # Import python libs from __future__ import absolute_import, print_function, unicode_literals import os import re import logging # Import salt libs import salt.utils.args import salt.utils.data import salt.utils.files import salt.utils.path import salt.utils.platform import salt.utils.mount import salt.utils.stringutils from salt.utils.odict import OrderedDict from salt.exceptions import CommandNotFoundError, CommandExecutionError # Import 3rd-party libs from salt.ext import six from salt.ext.six.moves import filter, zip # pylint: disable=import-error,redefined-builtin # Set up logger log = logging.getLogger(__name__) # Define the module's virtual name __virtualname__ = 'mount' def __virtual__(): ''' Only load on POSIX-like systems ''' # Disable on Windows, a specific file module exists: if salt.utils.platform.is_windows(): return (False, 'The mount module cannot be loaded: not a POSIX-like system.') return True def _list_mounts(): ret = {} if __grains__['os'] in ['MacOS', 'Darwin']: mounts = __salt__['cmd.run_stdout']('mount') else: mounts = __salt__['cmd.run_stdout']('mount -l') for line in mounts.split('\n'): comps = re.sub(r"\s+", " ", line).split() if len(comps) >= 3: ret[comps[2]] = comps[0] return ret def _active_mountinfo(ret): _list = _list_mounts() filename = '/proc/self/mountinfo' if not os.access(filename, os.R_OK): msg = 'File not readable {0}' raise CommandExecutionError(msg.format(filename)) if 'disk.blkid' not in __context__: __context__['disk.blkid'] = __salt__['disk.blkid']() blkid_info = __context__['disk.blkid'] with salt.utils.files.fopen(filename) as ifile: for line in ifile: comps = salt.utils.stringutils.to_unicode(line).split() device = comps[2].split(':') # each line can have any number of # optional parameters, we use the # location of the separator field to # determine the location of the elements # after it. _sep = comps.index('-') device_name = comps[_sep + 2] device_uuid = None device_label = None if device_name: device_uuid = blkid_info.get(device_name, {}).get('UUID') device_uuid = device_uuid and device_uuid.lower() device_label = blkid_info.get(device_name, {}).get('LABEL') ret[comps[4]] = {'mountid': comps[0], 'parentid': comps[1], 'major': device[0], 'minor': device[1], 'root': comps[3], 'opts': _resolve_user_group_names(comps[5].split(',')), 'fstype': comps[_sep + 1], 'device': device_name.replace('\\040', '\\ '), 'alt_device': _list.get(comps[4], None), 'superopts': _resolve_user_group_names(comps[_sep + 3].split(',')), 'device_uuid': device_uuid, 'device_label': device_label} return ret def _active_mounts(ret): ''' List active mounts on Linux systems ''' _list = _list_mounts() filename = '/proc/self/mounts' if not os.access(filename, os.R_OK): msg = 'File not readable {0}' raise CommandExecutionError(msg.format(filename)) with salt.utils.files.fopen(filename) as ifile: for line in ifile: comps = salt.utils.stringutils.to_unicode(line).split() ret[comps[1]] = {'device': comps[0], 'alt_device': _list.get(comps[1], None), 'fstype': comps[2], 'opts': _resolve_user_group_names(comps[3].split(','))} return ret def _active_mounts_aix(ret): ''' List active mounts on AIX systems ''' for line in __salt__['cmd.run_stdout']('mount -p').split('\n'): comps = re.sub(r"\s+", " ", line).split() if comps: if comps[0] == 'node' or comps[0] == '--------': continue comps_len = len(comps) if line.startswith((' ', '\t')): curr_opts = _resolve_user_group_names(comps[6].split(',')) if 7 == comps_len else [] if curr_opts: ret[comps[1]] = {'device': comps[0], 'fstype': comps[2], 'opts': curr_opts} else: ret[comps[1]] = {'device': comps[0], 'fstype': comps[2]} else: curr_opts = _resolve_user_group_names(comps[7].split(',')) if 8 == comps_len else [] if curr_opts: ret[comps[2]] = {'node': comps[0], 'device': comps[1], 'fstype': comps[3], 'opts': curr_opts} else: ret[comps[2]] = {'node': comps[0], 'device': comps[1], 'fstype': comps[3]} return ret def _active_mounts_freebsd(ret): ''' List active mounts on FreeBSD systems ''' for line in __salt__['cmd.run_stdout']('mount -p').split('\n'): comps = re.sub(r"\s+", " ", line).split() ret[comps[1]] = {'device': comps[0], 'fstype': comps[2], 'opts': _resolve_user_group_names(comps[3].split(','))} return ret def _active_mounts_solaris(ret): ''' List active mounts on Solaris systems ''' for line in __salt__['cmd.run_stdout']('mount -v').split('\n'): comps = re.sub(r"\s+", " ", line).split() ret[comps[2]] = {'device': comps[0], 'fstype': comps[4], 'opts': _resolve_user_group_names(comps[5].split('/'))} return ret def _active_mounts_openbsd(ret): ''' List active mounts on OpenBSD systems ''' for line in __salt__['cmd.run_stdout']('mount -v').split('\n'): comps = re.sub(r"\s+", " ", line).split() parens = re.findall(r'\((.*?)\)', line, re.DOTALL) if len(parens) > 1: nod = __salt__['cmd.run_stdout']('ls -l {0}'.format(comps[0])) nod = ' '.join(nod.split()).split(" ") ret[comps[3]] = {'device': comps[0], 'fstype': comps[5], 'opts': _resolve_user_group_names(parens[1].split(", ")), 'major': six.text_type(nod[4].strip(",")), 'minor': six.text_type(nod[5]), 'device_uuid': parens[0]} else: ret[comps[2]] = {'device': comps[0], 'fstype': comps[4], 'opts': _resolve_user_group_names(parens[0].split(", "))} return ret def _active_mounts_darwin(ret): ''' List active mounts on Mac OS systems ''' for line in __salt__['cmd.run_stdout']('mount').split('\n'): comps = re.sub(r"\s+", " ", line).split() parens = re.findall(r'\((.*?)\)', line, re.DOTALL)[0].split(", ") ret[comps[2]] = {'device': comps[0], 'fstype': parens[0], 'opts': _resolve_user_group_names(parens[1:])} return ret def _resolve_user_group_names(opts): ''' Resolve user and group names in related opts ''' name_id_opts = {'uid': 'user.info', 'gid': 'group.info'} for ind, opt in enumerate(opts): if opt.split('=')[0] in name_id_opts: _givenid = opt.split('=')[1] _param = opt.split('=')[0] _id = _givenid if not re.match('[0-9]+$', _givenid): _info = __salt__[name_id_opts[_param]](_givenid) if _info and _param in _info: _id = _info[_param] opts[ind] = _param + '=' + six.text_type(_id) opts[ind] = opts[ind].replace('\\040', '\\ ') return opts def active(extended=False): ''' List the active mounts. CLI Example: .. code-block:: bash salt '*' mount.active ''' ret = {} if __grains__['os'] == 'FreeBSD': _active_mounts_freebsd(ret) elif 'AIX' in __grains__['kernel']: _active_mounts_aix(ret) elif __grains__['kernel'] == 'SunOS': _active_mounts_solaris(ret) elif __grains__['os'] == 'OpenBSD': _active_mounts_openbsd(ret) elif __grains__['os'] in ['MacOS', 'Darwin']: _active_mounts_darwin(ret) else: if extended: try: _active_mountinfo(ret) except CommandExecutionError: _active_mounts(ret) else: _active_mounts(ret) return ret class _fstab_entry(object): ''' Utility class for manipulating fstab entries. Primarily we're parsing, formatting, and comparing lines. Parsing emits dicts expected from fstab() or raises a ValueError. Note: We'll probably want to use os.normpath and os.normcase on 'name' ''' class ParseError(ValueError): ''' Error raised when a line isn't parsible as an fstab entry ''' fstab_keys = ('device', 'name', 'fstype', 'opts', 'dump', 'pass_num') # preserve data format compatibility_keys = ('device', 'name', 'fstype', 'opts', 'dump', 'pass') fstab_format = '{device}\t\t{name}\t{fstype}\t{opts}\t{dump} {pass_num}\n' @classmethod def dict_from_line(cls, line, keys=fstab_keys): if len(keys) != 6: raise ValueError('Invalid key array: {0}'.format(keys)) if line.startswith('#'): raise cls.ParseError("Comment!") comps = line.split() if len(comps) < 4 or len(comps) > 6: raise cls.ParseError("Invalid Entry!") comps.extend(['0'] * (len(keys) - len(comps))) return dict(zip(keys, comps)) @classmethod def from_line(cls, *args, **kwargs): return cls(** cls.dict_from_line(*args, **kwargs)) @classmethod def dict_to_line(cls, entry): return cls.fstab_format.format(**entry) def __str__(self): ''' String value, only works for full repr ''' return self.dict_to_line(self.criteria) def __repr__(self): ''' Always works ''' return repr(self.criteria) def pick(self, keys): ''' Returns an instance with just those keys ''' subset = dict([(key, self.criteria[key]) for key in keys]) return self.__class__(**subset) def __init__(self, **criteria): ''' Store non-empty, non-null values to use as filter ''' items = [key_value for key_value in six.iteritems(criteria) if key_value[1] is not None] items = [(key_value1[0], six.text_type(key_value1[1])) for key_value1 in items] self.criteria = dict(items) @staticmethod def norm_path(path): ''' Resolve equivalent paths equivalently ''' return os.path.normcase(os.path.normpath(path)) def match(self, line): ''' Compare potentially partial criteria against line ''' entry = self.dict_from_line(line) for key, value in six.iteritems(self.criteria): if entry[key] != value: return False return True class _vfstab_entry(object): ''' Utility class for manipulating vfstab entries. Primarily we're parsing, formatting, and comparing lines. Parsing emits dicts expected from fstab() or raises a ValueError. Note: We'll probably want to use os.normpath and os.normcase on 'name' Note: This parses vfstab entries on Solaris like systems #device device mount FS fsck mount mount #to mount to fsck point type pass at boot options # /devices - /devices devfs - no - ''' class ParseError(ValueError): '''Error raised when a line isn't parsible as an fstab entry''' vfstab_keys = ('device', 'device_fsck', 'name', 'fstype', 'pass_fsck', 'mount_at_boot', 'opts') # NOTE: weird formatting to match default spacing on Solaris vfstab_format = '{device:<11} {device_fsck:<3} {name:<19} {fstype:<8} {pass_fsck:<3} {mount_at_boot:<6} {opts}\n' @classmethod def dict_from_line(cls, line): if line.startswith('#'): raise cls.ParseError("Comment!") comps = line.split() if len(comps) != 7: raise cls.ParseError("Invalid Entry!") return dict(zip(cls.vfstab_keys, comps)) @classmethod def from_line(cls, *args, **kwargs): return cls(** cls.dict_from_line(*args, **kwargs)) @classmethod def dict_to_line(cls, entry): return cls.vfstab_format.format(**entry) def __str__(self): ''' String value, only works for full repr ''' return self.dict_to_line(self.criteria) def __repr__(self): ''' Always works ''' return repr(self.criteria) def pick(self, keys): ''' Returns an instance with just those keys ''' subset = dict([(key, self.criteria[key]) for key in keys]) return self.__class__(**subset) def __init__(self, **criteria): ''' Store non-empty, non-null values to use as filter ''' items = [key_value for key_value in six.iteritems(criteria) if key_value[1] is not None] items = [(key_value1[0], six.text_type(key_value1[1])) for key_value1 in items] self.criteria = dict(items) @staticmethod def norm_path(path): ''' Resolve equivalent paths equivalently ''' return os.path.normcase(os.path.normpath(path)) def match(self, line): ''' Compare potentially partial criteria against line ''' entry = self.dict_from_line(line) for key, value in six.iteritems(self.criteria): if entry[key] != value: return False return True class _FileSystemsEntry(object): ''' Utility class for manipulating filesystem entries. Primarily we're parsing, formatting, and comparing lines. Parsing emits dicts expected from fstab() or raises a ValueError. Note: We'll probably want to use os.normpath and os.normcase on 'name' ''' class ParseError(ValueError): ''' Error raised when a line isn't parsible as an fstab entry ''' filesystems_keys = ('device', 'name', 'fstype', 'vfstype', 'opts', 'mount') # preserve data format of filesystems compatibility_keys = ('dev', 'dev', 'name', 'fstype', 'vfstype', 'opts', 'mount', 'type', 'vfs', 'account', 'boot', 'check', 'free', 'nodename', 'quota', 'size', 'vol', 'log') @classmethod def dict_from_lines(cls, lines, keys=filesystems_keys): if len(lines) < 2: raise ValueError('Invalid number of lines: {0}'.format(lines)) if not keys: # if empty force default filesystems_keys keys = _FileSystemsEntry.filesystems_keys elif len(keys) < 6: raise ValueError('Invalid key name array: {0}'.format(keys)) blk_lines = lines orddict = OrderedDict() orddict['name'] = blk_lines[0].split(':')[0].strip() blk_lines.pop(0) for line in blk_lines: if line.startswith('#'): raise cls.ParseError("Comment!") comps = line.split('= ') if len(comps) != 2: raise cls.ParseError("Invalid Entry!") key_name = comps[0].strip() if key_name in keys: orddict[key_name] = comps[1].strip() else: raise ValueError('Invalid name for use in filesystems: {0}'.format(key_name)) return orddict @classmethod def dict_from_cmd_line(cls, ipargs, keys): cmdln_dict = ipargs if keys: for key, value in keys: # ignore unknown or local scope keys if key.startswith('__'): continue if key in _FileSystemsEntry.compatibility_keys: cmdln_dict[key] = value return cmdln_dict @classmethod def from_line(cls, *args, **kwargs): return cls(** cls.dict_from_cmd_line(*args, **kwargs)) @classmethod def dict_to_lines(cls, fsys_dict_entry): entry = fsys_dict_entry strg_out = entry['name'] + ':' + os.linesep for k, v in six.viewitems(entry): if 'name' not in k: strg_out += '\t{0}\t\t= {1}'.format(k, v) + os.linesep strg_out += os.linesep return six.text_type(strg_out) def dict_from_entry(self): ret = OrderedDict() ret[self.criteria['name']] = self.criteria return ret def __str__(self): ''' String value, only works for full repr ''' return self.dict_to_lines(self.criteria) def __repr__(self): ''' Always works ''' return repr(self.criteria) def pick(self, keys): ''' Returns an instance with just those keys ''' subset = dict([(key, self.criteria[key]) for key in keys]) return self.__class__(**subset) def __init__(self, **criteria): ''' Store non-empty, non-null values to use as filter ''' items = [key_value for key_value in six.iteritems(criteria) if key_value[1] is not None] items = [(key_value1[0], six.text_type(key_value1[1])) for key_value1 in items] self.criteria = OrderedDict(items) @staticmethod def norm_path(path): ''' Resolve equivalent paths equivalently ''' return os.path.normcase(os.path.normpath(path)) def match(self, fsys_view): ''' Compare potentially partial criteria against built filesystems entry dictionary ''' evalue_dict = fsys_view[1] for key, value in six.viewitems(self.criteria): if key in evalue_dict: if evalue_dict[key] != value: return False else: return False return True def __getitem__(self, key): ''' Return value for input key ''' return self.criteria[key] def fstab(config='/etc/fstab'): ''' .. versionchanged:: 2016.3.2 List the contents of the fstab CLI Example: .. code-block:: bash salt '*' mount.fstab ''' ret = {} if not os.path.isfile(config): return ret with salt.utils.files.fopen(config) as ifile: for line in ifile: line = salt.utils.stringutils.to_unicode(line) try: if __grains__['kernel'] == 'SunOS': # Note: comments use in default vfstab file! if line[0] == '#': continue entry = _vfstab_entry.dict_from_line( line) else: entry = _fstab_entry.dict_from_line( line, _fstab_entry.compatibility_keys) entry['opts'] = entry['opts'].split(',') while entry['name'] in ret: entry['name'] += '_' ret[entry.pop('name')] = entry except _fstab_entry.ParseError: pass except _vfstab_entry.ParseError: pass return ret def vfstab(config='/etc/vfstab'): ''' .. versionadded:: 2016.3.2 List the contents of the vfstab CLI Example: .. code-block:: bash salt '*' mount.vfstab ''' # NOTE: vfstab is a wrapper for fstab return fstab(config) def rm_fstab(name, device, config='/etc/fstab'): ''' .. versionchanged:: 2016.3.2 Remove the mount point from the fstab CLI Example: .. code-block:: bash salt '*' mount.rm_fstab /mnt/foo /dev/sdg ''' modified = False if __grains__['kernel'] == 'SunOS': criteria = _vfstab_entry(name=name, device=device) else: criteria = _fstab_entry(name=name, device=device) lines = [] try: with salt.utils.files.fopen(config, 'r') as ifile: for line in ifile: line = salt.utils.stringutils.to_unicode(line) try: if criteria.match(line): modified = True else: lines.append(line) except _fstab_entry.ParseError: lines.append(line) except _vfstab_entry.ParseError: lines.append(line) except (IOError, OSError) as exc: msg = "Couldn't read from {0}: {1}" raise CommandExecutionError(msg.format(config, exc)) if modified: try: with salt.utils.files.fopen(config, 'wb') as ofile: ofile.writelines(salt.utils.data.encode(lines)) except (IOError, OSError) as exc: msg = "Couldn't write to {0}: {1}" raise CommandExecutionError(msg.format(config, exc)) # Note: not clear why we always return 'True' # --just copying previous behavior at this point... return True def rm_vfstab(name, device, config='/etc/vfstab'): ''' .. versionadded:: 2016.3.2 Remove the mount point from the vfstab CLI Example: .. code-block:: bash salt '*' mount.rm_vfstab /mnt/foo /device/c0t0d0p0 ''' ## NOTE: rm_vfstab is a wrapper for rm_fstab return rm_fstab(name, device, config) def set_vfstab( name, device, fstype, opts='-', device_fsck='-', pass_fsck='-', mount_at_boot='yes', config='/etc/vfstab', test=False, match_on='auto', **kwargs): ''' ..verionadded:: 2016.3.2 Verify that this mount is represented in the fstab, change the mount to match the data passed, or add the mount if it is not present. CLI Example: .. code-block:: bash salt '*' mount.set_vfstab /mnt/foo /device/c0t0d0p0 ufs ''' # Fix the opts type if it is a list if isinstance(opts, list): opts = ','.join(opts) # Map unknown values for mount_at_boot to no if mount_at_boot != 'yes': mount_at_boot = 'no' # preserve arguments for updating entry_args = { 'name': name, 'device': device, 'fstype': fstype, 'opts': opts, 'device_fsck': device_fsck, 'pass_fsck': pass_fsck, 'mount_at_boot': mount_at_boot, } lines = [] ret = None # Transform match_on into list--items will be checked later if isinstance(match_on, list): pass elif not isinstance(match_on, six.string_types): msg = 'match_on must be a string or list of strings' raise CommandExecutionError(msg) elif match_on == 'auto': # Try to guess right criteria for auto.... # NOTE: missing some special fstypes here specialFSes = frozenset([ 'devfs', 'proc', 'ctfs', 'objfs', 'sharefs', 'fs', 'tmpfs']) if fstype in specialFSes: match_on = ['name'] else: match_on = ['device'] else: match_on = [match_on] # generate entry and criteria objects, handle invalid keys in match_on entry = _vfstab_entry(**entry_args) try: criteria = entry.pick(match_on) except KeyError: filterFn = lambda key: key not in _vfstab_entry.vfstab_keys invalid_keys = filter(filterFn, match_on) msg = 'Unrecognized keys in match_on: "{0}"'.format(invalid_keys) raise CommandExecutionError(msg) # parse file, use ret to cache status if not os.path.isfile(config): raise CommandExecutionError('Bad config file "{0}"'.format(config)) try: with salt.utils.files.fopen(config, 'r') as ifile: for line in ifile: line = salt.utils.stringutils.to_unicode(line) try: if criteria.match(line): # Note: If ret isn't None here, # we've matched multiple lines ret = 'present' if entry.match(line): lines.append(line) else: ret = 'change' lines.append(six.text_type(entry)) else: lines.append(line) except _vfstab_entry.ParseError: lines.append(line) except (IOError, OSError) as exc: msg = 'Couldn\'t read from {0}: {1}' raise CommandExecutionError(msg.format(config, exc)) # add line if not present or changed if ret is None: lines.append(six.text_type(entry)) ret = 'new' if ret != 'present': # ret in ['new', 'change']: if not salt.utils.args.test_mode(test=test, **kwargs): try: with salt.utils.files.fopen(config, 'wb') as ofile: # The line was changed, commit it! ofile.writelines(salt.utils.data.encode(lines)) except (IOError, OSError): msg = 'File not writable {0}' raise CommandExecutionError(msg.format(config)) return ret def rm_automaster(name, device, config='/etc/auto_salt'): ''' Remove the mount point from the auto_master CLI Example: .. code-block:: bash salt '*' mount.rm_automaster /mnt/foo /dev/sdg ''' contents = automaster(config) if name not in contents: return True # The entry is present, get rid of it lines = [] try: with salt.utils.files.fopen(config, 'r') as ifile: for line in ifile: line = salt.utils.stringutils.to_unicode(line) if line.startswith('#'): # Commented lines.append(line) continue if not line.strip(): # Blank line lines.append(line) continue comps = line.split() if len(comps) != 3: # Invalid entry lines.append(line) continue comps = line.split() prefix = "/.." name_chk = comps[0].replace(prefix, "") device_fmt = comps[2].split(":") if device: if name_chk == name and device_fmt[1] == device: continue else: if name_chk == name: continue lines.append(line) except (IOError, OSError) as exc: msg = "Couldn't read from {0}: {1}" raise CommandExecutionError(msg.format(config, exc)) try: with salt.utils.files.fopen(config, 'wb') as ofile: ofile.writelines(salt.utils.data.encode(lines)) except (IOError, OSError) as exc: msg = "Couldn't write to {0}: {1}" raise CommandExecutionError(msg.format(config, exc)) # Update automount __salt__['cmd.run']('automount -cv') return True def set_automaster( name, device, fstype, opts='', config='/etc/auto_salt', test=False, **kwargs): ''' Verify that this mount is represented in the auto_salt, change the mount to match the data passed, or add the mount if it is not present. CLI Example: .. code-block:: bash salt '*' mount.set_automaster /mnt/foo /dev/sdz1 ext4 ''' # Fix the opts type if it is a list if isinstance(opts, list): opts = ','.join(opts) lines = [] change = False present = False automaster_file = "/etc/auto_master" if not os.path.isfile(config): __salt__['file.touch'](config) __salt__['file.append'](automaster_file, "/-\t\t\t{0}".format(config)) name = "/..{0}".format(name) device_fmt = "{0}:{1}".format(fstype, device) type_opts = "-fstype={0},{1}".format(fstype, opts) if fstype == 'smbfs': device_fmt = device_fmt.replace(fstype, "") try: with salt.utils.files.fopen(config, 'r') as ifile: for line in ifile: line = salt.utils.stringutils.to_unicode(line) if line.startswith('#'): # Commented lines.append(line) continue if not line.strip(): # Blank line lines.append(line) continue comps = line.split() if len(comps) != 3: # Invalid entry lines.append(line) continue if comps[0] == name or comps[2] == device_fmt: # check to see if there are changes # and fix them if there are any present = True if comps[0] != name: change = True comps[0] = name if comps[1] != type_opts: change = True comps[1] = type_opts if comps[2] != device_fmt: change = True comps[2] = device_fmt if change: log.debug( 'auto_master entry for mount point %s needs to be ' 'updated', name ) newline = ( '{0}\t{1}\t{2}\n'.format( name, type_opts, device_fmt) ) lines.append(newline) else: lines.append(line) except (IOError, OSError) as exc: msg = 'Couldn\'t read from {0}: {1}' raise CommandExecutionError(msg.format(config, exc)) if change: if not salt.utils.args.test_mode(test=test, **kwargs): try: with salt.utils.files.fopen(config, 'wb') as ofile: # The line was changed, commit it! ofile.writelines(salt.utils.data.encode(lines)) except (IOError, OSError): msg = 'File not writable {0}' raise CommandExecutionError(msg.format(config)) return 'change' if not change: if present: # The right entry is already here return 'present' else: if not salt.utils.args.test_mode(test=test, **kwargs): # The entry is new, add it to the end of the fstab newline = ( '{0}\t{1}\t{2}\n'.format( name, type_opts, device_fmt) ) lines.append(newline) try: with salt.utils.files.fopen(config, 'wb') as ofile: # The line was changed, commit it! ofile.writelines(salt.utils.data.encode(lines)) except (IOError, OSError): raise CommandExecutionError( 'File not writable {0}'.format( config ) ) return 'new' def automaster(config='/etc/auto_salt'): ''' List the contents of the auto master CLI Example: .. code-block:: bash salt '*' mount.automaster ''' ret = {} if not os.path.isfile(config): return ret with salt.utils.files.fopen(config) as ifile: for line in ifile: line = salt.utils.stringutils.to_unicode(line) if line.startswith('#'): # Commented continue if not line.strip(): # Blank line continue comps = line.split() if len(comps) != 3: # Invalid entry continue prefix = "/.." name = comps[0].replace(prefix, "") device_fmt = comps[2].split(":") opts = comps[1].split(',') ret[name] = {'device': device_fmt[1], 'fstype': opts[0], 'opts': opts[1:]} return ret def mount(name, device, mkmnt=False, fstype='', opts='defaults', user=None, util='mount'): ''' Mount a device CLI Example: .. code-block:: bash salt '*' mount.mount /mnt/foo /dev/sdz1 True ''' if util != 'mount': # This functionality used to live in img.mount_image if util == 'guestfs': return __salt__['guestfs.mount'](name, root=device) elif util == 'qemu_nbd': mnt = __salt__['qemu_nbd.init'](name, device) if not mnt: return False first = next(six.iterkeys(mnt)) __context__['img.mnt_{0}'.format(first)] = mnt return first return False # Darwin doesn't expect defaults when mounting without other options if 'defaults' in opts and __grains__['os'] in ['MacOS', 'Darwin', 'AIX']: opts = None if isinstance(opts, six.string_types): opts = opts.split(',') if not os.path.exists(name) and mkmnt: __salt__['file.mkdir'](name, user=user) args = '' if opts is not None: lopts = ','.join(opts) args = '-o {0}'.format(lopts) if fstype: # use of fstype on AIX differs from typical Linux use of -t # functionality AIX uses -v vfsname, -t fstype mounts all with # fstype in /etc/filesystems if 'AIX' in __grains__['os']: args += ' -v {0}'.format(fstype) elif 'solaris' in __grains__['os'].lower(): args += ' -F {0}'.format(fstype) else: args += ' -t {0}'.format(fstype) cmd = 'mount {0} {1} {2} '.format(args, device, name) out = __salt__['cmd.run_all'](cmd, runas=user, python_shell=False) if out['retcode']: return out['stderr'] return True def remount(name, device, mkmnt=False, fstype='', opts='defaults', user=None): ''' Attempt to remount a device, if the device is not already mounted, mount is called CLI Example: .. code-block:: bash salt '*' mount.remount /mnt/foo /dev/sdz1 True ''' force_mount = False if __grains__['os'] in ['MacOS', 'Darwin']: if opts == 'defaults': opts = 'noowners' if fstype == 'smbfs': force_mount = True if 'AIX' in __grains__['os']: if opts == 'defaults': opts = [] if isinstance(opts, six.string_types): opts = opts.split(',') mnts = active() if name in mnts: # The mount point is mounted, attempt to remount it with the given data if 'remount' not in opts and __grains__['os'] not in ['OpenBSD', 'MacOS', 'Darwin']: opts.append('remount') if force_mount: # We need to force the mount but first we should unmount umount(name, device, user=user) lopts = ','.join(opts) args = '-o {0}'.format(lopts) if fstype: # use of fstype on AIX differs from typical Linux use of # -t functionality AIX uses -v vfsname, -t fstype mounts # all with fstype in /etc/filesystems if 'AIX' in __grains__['os']: args += ' -v {0}'.format(fstype) elif 'solaris' in __grains__['os'].lower(): args += ' -F {0}'.format(fstype) else: args += ' -t {0}'.format(fstype) if __grains__['os'] not in ['OpenBSD', 'MacOS', 'Darwin'] or force_mount: cmd = 'mount {0} {1} {2} '.format(args, device, name) else: cmd = 'mount -u {0} {1} {2} '.format(args, device, name) out = __salt__['cmd.run_all'](cmd, runas=user, python_shell=False) if out['retcode']: return out['stderr'] return True # Mount a filesystem that isn't already return mount(name, device, mkmnt, fstype, opts, user=user) def umount(name, device=None, user=None, util='mount'): ''' Attempt to unmount a device by specifying the directory it is mounted on CLI Example: .. code-block:: bash salt '*' mount.umount /mnt/foo .. versionadded:: 2015.5.0 .. code-block:: bash salt '*' mount.umount /mnt/foo /dev/xvdc1 ''' if util != 'mount': # This functionality used to live in img.umount_image if 'qemu_nbd.clear' in __salt__: if 'img.mnt_{0}'.format(name) in __context__: __salt__['qemu_nbd.clear'](__context__['img.mnt_{0}'.format(name)]) return mnts = active() if name not in mnts: return "{0} does not have anything mounted".format(name) if not device: cmd = 'umount {0}'.format(name) else: cmd = 'umount {0}'.format(device) out = __salt__['cmd.run_all'](cmd, runas=user, python_shell=False) if out['retcode']: return out['stderr'] return True def is_fuse_exec(cmd): ''' Returns true if the command passed is a fuse mountable application. CLI Example: .. code-block:: bash salt '*' mount.is_fuse_exec sshfs ''' cmd_path = salt.utils.path.which(cmd) # No point in running ldd on a command that doesn't exist if not cmd_path: return False elif not salt.utils.path.which('ldd'): raise CommandNotFoundError('ldd') out = __salt__['cmd.run']('ldd {0}'.format(cmd_path), python_shell=False) return 'libfuse' in out def swaps(): ''' Return a dict containing information on active swap .. versionchanged:: 2016.3.2 CLI Example: .. code-block:: bash salt '*' mount.swaps ''' ret = {} if __grains__['kernel'] == 'SunOS': for line in __salt__['cmd.run_stdout']('swap -l').splitlines(): if line.startswith('swapfile'): continue comps = line.split() ret[comps[0]] = {'type': 'device' if comps[0].startswith(('/dev', 'swap')) else 'file', 'size': int(comps[3]), 'used': (int(comps[3]) - int(comps[4])), 'priority': '-'} elif 'AIX' in __grains__['kernel']: for line in __salt__['cmd.run_stdout']('swap -l').splitlines(): if line.startswith('device'): continue comps = line.split() # AIX uses MB for units ret[comps[0]] = {'type': 'device', 'size': int(comps[3][:-2]) * 1024, 'used': (int(comps[3][:-2]) - int(comps[4][:-2])) * 1024, 'priority': '-'} elif __grains__['os'] != 'OpenBSD': with salt.utils.files.fopen('/proc/swaps') as fp_: for line in fp_: line = salt.utils.stringutils.to_unicode(line) if line.startswith('Filename'): continue comps = line.split() ret[comps[0]] = {'type': comps[1], 'size': comps[2], 'used': comps[3], 'priority': comps[4]} else: for line in __salt__['cmd.run_stdout']('swapctl -kl').splitlines(): if line.startswith(('Device', 'Total')): continue swap_type = "file" comps = line.split() if comps[0].startswith('/dev/'): swap_type = "partition" ret[comps[0]] = {'type': swap_type, 'size': comps[1], 'used': comps[2], 'priority': comps[5]} return ret def swapon(name, priority=None): ''' Activate a swap disk .. versionchanged:: 2016.3.2 CLI Example: .. code-block:: bash salt '*' mount.swapon /root/swapfile ''' ret = {} on_ = swaps() if name in on_: ret['stats'] = on_[name] ret['new'] = False return ret if __grains__['kernel'] == 'SunOS': if __grains__['virtual'] != 'zone': __salt__['cmd.run']('swap -a {0}'.format(name), python_shell=False) else: return False else: cmd = 'swapon {0}'.format(name) if priority and 'AIX' not in __grains__['kernel']: cmd += ' -p {0}'.format(priority) __salt__['cmd.run'](cmd, python_shell=False) on_ = swaps() if name in on_: ret['stats'] = on_[name] ret['new'] = True return ret return ret def swapoff(name): ''' Deactivate a named swap mount .. versionchanged:: 2016.3.2 CLI Example: .. code-block:: bash salt '*' mount.swapoff /root/swapfile ''' on_ = swaps() if name in on_: if __grains__['kernel'] == 'SunOS': if __grains__['virtual'] != 'zone': __salt__['cmd.run']('swap -a {0}'.format(name), python_shell=False) else: return False elif __grains__['os'] != 'OpenBSD': __salt__['cmd.run']('swapoff {0}'.format(name), python_shell=False) else: __salt__['cmd.run']('swapctl -d {0}'.format(name), python_shell=False) on_ = swaps() if name in on_: return False return True return None def is_mounted(name): ''' .. versionadded:: 2014.7.0 Provide information if the path is mounted CLI Example: .. code-block:: bash salt '*' mount.is_mounted /mnt/share ''' active_ = active() if name in active_: return True else: return False def read_mount_cache(name): ''' .. versionadded:: 2018.3.0 Provide information if the path is mounted CLI Example: .. code-block:: bash salt '*' mount.read_mount_cache /mnt/share ''' cache = salt.utils.mount.read_cache(__opts__) if cache: if 'mounts' in cache and cache['mounts']: if name in cache['mounts']: return cache['mounts'][name] return {} def write_mount_cache(real_name, device, mkmnt, fstype, mount_opts): ''' .. versionadded:: 2018.3.0 Provide information if the path is mounted :param real_name: The real name of the mount point where the device is mounted. :param device: The device that is being mounted. :param mkmnt: Whether or not the mount point should be created. :param fstype: The file system that is used. :param mount_opts: Additional options used when mounting the device. :return: Boolean if message was sent successfully. CLI Example: .. code-block:: bash salt '*' mount.write_mount_cache /mnt/share /dev/sda1 False ext4 defaults,nosuid ''' cache = salt.utils.mount.read_cache(__opts__) if not cache: cache = {} cache['mounts'] = {} else: if 'mounts' not in cache: cache['mounts'] = {} cache['mounts'][real_name] = {'device': device, 'fstype': fstype, 'mkmnt': mkmnt, 'opts': mount_opts} cache_write = salt.utils.mount.write_cache(cache, __opts__) if cache_write: return True else: raise CommandExecutionError('Unable to write mount cache.') def delete_mount_cache(real_name): ''' .. versionadded:: 2018.3.0 Provide information if the path is mounted CLI Example: .. code-block:: bash salt '*' mount.delete_mount_cache /mnt/share ''' cache = salt.utils.mount.read_cache(__opts__) if cache: if 'mounts' in cache: if real_name in cache['mounts']: del cache['mounts'][real_name] cache_write = salt.utils.mount.write_cache(cache, __opts__) if not cache_write: raise CommandExecutionError('Unable to write mount cache.') return True def _filesystems(config='/etc/filesystems', leading_key=True): ''' Return the contents of the filesystems in an OrderedDict config File containing filesystem infomation leading_key True return dictionary keyed by 'name' and value as dictionary with other keys, values (name excluded) OrderedDict({ '/dir' : OrderedDict({'dev': '/dev/hd8', .... }})) False return dictionary keyed by 'name' and value as dictionary with all keys, values (name included) OrderedDict({ '/dir' : OrderedDict({'name': '/dir', 'dev': '/dev/hd8', ... })}) ''' ret = OrderedDict() lines = [] parsing_block = False if not os.path.isfile(config) or 'AIX' not in __grains__['kernel']: return ret # read in block of filesystems, block starts with '/' till empty line with salt.utils.files.fopen(config) as ifile: for line in ifile: line = salt.utils.stringutils.to_unicode(line) # skip till first entry if not line.startswith('/') and not parsing_block: continue if line.startswith('/'): parsing_block = True lines.append(line) elif not line.split(): parsing_block = False try: entry = _FileSystemsEntry.dict_from_lines( lines, _FileSystemsEntry.compatibility_keys) lines = [] if 'opts' in entry: entry['opts'] = entry['opts'].split(',') while entry['name'] in ret: entry['name'] += '_' if leading_key: ret[entry.pop('name')] = entry else: ret[entry['name']] = entry except _FileSystemsEntry.ParseError: pass else: lines.append(line) return ret def filesystems(config='/etc/filesystems'): ''' .. versionadded:: 2018.3.3 List the contents of the filesystems CLI Example: .. code-block:: bash salt '*' mount.filesystems ''' ret = {} if 'AIX' not in __grains__['kernel']: return ret ret_dict = _filesystems(config) if ret_dict: ret_key = next(iter(ret_dict.keys())) ret = {ret_key: dict(ret_dict[ret_key])} return ret def set_filesystems( name, device, vfstype, opts='-', mount='true', config='/etc/filesystems', test=False, match_on='auto', **kwargs): ''' .. versionadded:: 2018.3.3 Verify that this mount is represented in the filesystems, change the mount to match the data passed, or add the mount if it is not present on AIX Provide information if the path is mounted :param name: The name of the mount point where the device is mounted. :param device: The device that is being mounted. :param vfstype: The file system that is used (AIX has two fstypes, fstype and vfstype - similar to Linux fstype) :param opts: Additional options used when mounting the device. :param mount: Mount if not mounted, default True. :param config: Configuration file, default /etc/filesystems. :param match: File systems type to match on, default auto CLI Example: .. code-block:: bash salt '*' mount.set_filesystems /mnt/foo /dev/sdz1 jfs2 ''' # Fix the opts type if it is a list if isinstance(opts, list): opts = ','.join(opts) # preserve arguments for updating entry_args = { 'name': name, 'dev': device.replace('\\ ', '\\040'), 'vfstype': vfstype, 'opts': opts, 'mount': mount, } view_lines = [] ret = None if 'AIX' not in __grains__['kernel']: return ret # Transform match_on into list--items will be checked later if isinstance(match_on, list): pass elif not isinstance(match_on, six.string_types): raise CommandExecutionError('match_on must be a string or list of strings') elif match_on == 'auto': # Try to guess right criteria for auto.... # added IBM types from sys/vmount.h after btrfs # NOTE: missing some special fstypes here specialFSes = frozenset([ 'none', 'tmpfs', 'sysfs', 'proc', 'fusectl', 'debugfs', 'securityfs', 'devtmpfs', 'cgroup', 'btrfs', 'cdrfs', 'procfs', 'jfs', 'jfs2', 'nfs', 'sfs', 'nfs3', 'cachefs', 'udfs', 'cifs', 'namefs', 'pmemfs', 'ahafs', 'nfs4', 'autofs', 'stnfs']) if vfstype in specialFSes: match_on = ['name'] else: match_on = ['dev'] else: match_on = [match_on] # generate entry and criteria objects, handle invalid keys in match_on entry_ip = _FileSystemsEntry.from_line(entry_args, kwargs) try: criteria = entry_ip.pick(match_on) except KeyError: filterFn = lambda key: key not in _FileSystemsEntry.compatibility_keys invalid_keys = filter(filterFn, match_on) raise CommandExecutionError('Unrecognized keys in match_on: "{0}"'.format(invalid_keys)) # parse file, use ret to cache status if not os.path.isfile(config): raise CommandExecutionError('Bad config file "{0}"'.format(config)) # read in block of filesystem, block starts with '/' till empty line try: fsys_filedict = _filesystems(config, False) for fsys_view in six.viewitems(fsys_filedict): if criteria.match(fsys_view): ret = 'present' if entry_ip.match(fsys_view): view_lines.append(fsys_view) else: ret = 'change' kv = entry_ip['name'] view_lines.append((kv, entry_ip)) else: view_lines.append(fsys_view) except (IOError, OSError) as exc: raise CommandExecutionError('Couldn\'t read from {0}: {1}'.format(config, exc)) # add line if not present or changed if ret is None: for dict_view in six.viewitems(entry_ip.dict_from_entry()): view_lines.append(dict_view) ret = 'new' if ret != 'present': # ret in ['new', 'change']: try: with salt.utils.files.fopen(config, 'wb') as ofile: # The line was changed, commit it! for fsys_view in view_lines: entry = fsys_view[1] mystrg = _FileSystemsEntry.dict_to_lines(entry) ofile.writelines(salt.utils.data.encode(mystrg)) except (IOError, OSError): raise CommandExecutionError('File not writable {0}'.format(config)) return ret def rm_filesystems(name, device, config='/etc/filesystems'): ''' .. versionadded:: 2018.3.3 Remove the mount point from the filesystems CLI Example: .. code-block:: bash salt '*' mount.rm_filesystems /mnt/foo /dev/sdg ''' modified = False view_lines = [] if 'AIX' not in __grains__['kernel']: return modified criteria = _FileSystemsEntry(name=name, dev=device) try: fsys_filedict = _filesystems(config, False) for fsys_view in six.viewitems(fsys_filedict): try: if criteria.match(fsys_view): modified = True else: view_lines.append(fsys_view) except _FileSystemsEntry.ParseError: view_lines.append(fsys_view) except (IOError, OSError) as exc: raise CommandExecutionError("Couldn't read from {0}: {1}".format(config, exc)) if modified: try: with salt.utils.files.fopen(config, 'wb') as ofile: for fsys_view in view_lines: entry = fsys_view[1] mystrg = _FileSystemsEntry.dict_to_lines(entry) ofile.writelines(salt.utils.data.encode(mystrg)) except (IOError, OSError) as exc: raise CommandExecutionError("Couldn't write to {0}: {1}".format(config, exc)) return modified
saltstack/salt
salt/modules/mount.py
rm_automaster
python
def rm_automaster(name, device, config='/etc/auto_salt'): ''' Remove the mount point from the auto_master CLI Example: .. code-block:: bash salt '*' mount.rm_automaster /mnt/foo /dev/sdg ''' contents = automaster(config) if name not in contents: return True # The entry is present, get rid of it lines = [] try: with salt.utils.files.fopen(config, 'r') as ifile: for line in ifile: line = salt.utils.stringutils.to_unicode(line) if line.startswith('#'): # Commented lines.append(line) continue if not line.strip(): # Blank line lines.append(line) continue comps = line.split() if len(comps) != 3: # Invalid entry lines.append(line) continue comps = line.split() prefix = "/.." name_chk = comps[0].replace(prefix, "") device_fmt = comps[2].split(":") if device: if name_chk == name and device_fmt[1] == device: continue else: if name_chk == name: continue lines.append(line) except (IOError, OSError) as exc: msg = "Couldn't read from {0}: {1}" raise CommandExecutionError(msg.format(config, exc)) try: with salt.utils.files.fopen(config, 'wb') as ofile: ofile.writelines(salt.utils.data.encode(lines)) except (IOError, OSError) as exc: msg = "Couldn't write to {0}: {1}" raise CommandExecutionError(msg.format(config, exc)) # Update automount __salt__['cmd.run']('automount -cv') return True
Remove the mount point from the auto_master CLI Example: .. code-block:: bash salt '*' mount.rm_automaster /mnt/foo /dev/sdg
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/mount.py#L958-L1016
[ "def encode(data, encoding=None, errors='strict', keep=False,\n preserve_dict_class=False, preserve_tuples=False):\n '''\n Generic function which will encode whichever type is passed, if necessary\n\n If `strict` is True, and `keep` is False, and we fail to encode, a\n UnicodeEncodeError will be raised. Passing `keep` as True allows for the\n original value to silently be returned in cases where encoding fails. This\n can be useful for cases where the data passed to this function is likely to\n contain binary blobs.\n '''\n if isinstance(data, Mapping):\n return encode_dict(data, encoding, errors, keep,\n preserve_dict_class, preserve_tuples)\n elif isinstance(data, list):\n return encode_list(data, encoding, errors, keep,\n preserve_dict_class, preserve_tuples)\n elif isinstance(data, tuple):\n return encode_tuple(data, encoding, errors, keep, preserve_dict_class) \\\n if preserve_tuples \\\n else encode_list(data, encoding, errors, keep,\n preserve_dict_class, preserve_tuples)\n else:\n try:\n return salt.utils.stringutils.to_bytes(data, encoding, errors)\n except TypeError:\n # to_bytes raises a TypeError when input is not a\n # string/bytestring/bytearray. This is expected and simply\n # means we are going to leave the value as-is.\n pass\n except UnicodeEncodeError:\n if not keep:\n raise\n return data\n", "def fopen(*args, **kwargs):\n '''\n Wrapper around open() built-in to set CLOEXEC on the fd.\n\n This flag specifies that the file descriptor should be closed when an exec\n function is invoked;\n\n When a file descriptor is allocated (as with open or dup), this bit is\n initially cleared on the new file descriptor, meaning that descriptor will\n survive into the new program after exec.\n\n NB! We still have small race condition between open and fcntl.\n '''\n if six.PY3:\n try:\n # Don't permit stdin/stdout/stderr to be opened. The boolean False\n # and True are treated by Python 3's open() as file descriptors 0\n # and 1, respectively.\n if args[0] in (0, 1, 2):\n raise TypeError(\n '{0} is not a permitted file descriptor'.format(args[0])\n )\n except IndexError:\n pass\n binary = None\n # ensure 'binary' mode is always used on Windows in Python 2\n if ((six.PY2 and salt.utils.platform.is_windows() and 'binary' not in kwargs) or\n kwargs.pop('binary', False)):\n if len(args) > 1:\n args = list(args)\n if 'b' not in args[1]:\n args[1] = args[1].replace('t', 'b')\n if 'b' not in args[1]:\n args[1] += 'b'\n elif kwargs.get('mode'):\n if 'b' not in kwargs['mode']:\n kwargs['mode'] = kwargs['mode'].replace('t', 'b')\n if 'b' not in kwargs['mode']:\n kwargs['mode'] += 'b'\n else:\n # the default is to read\n kwargs['mode'] = 'rb'\n elif six.PY3 and 'encoding' not in kwargs:\n # In Python 3, if text mode is used and the encoding\n # is not specified, set the encoding to 'utf-8'.\n binary = False\n if len(args) > 1:\n args = list(args)\n if 'b' in args[1]:\n binary = True\n if kwargs.get('mode', None):\n if 'b' in kwargs['mode']:\n binary = True\n if not binary:\n kwargs['encoding'] = __salt_system_encoding__\n\n if six.PY3 and not binary and not kwargs.get('newline', None):\n kwargs['newline'] = ''\n\n f_handle = open(*args, **kwargs) # pylint: disable=resource-leakage\n\n if is_fcntl_available():\n # modify the file descriptor on systems with fcntl\n # unix and unix-like systems only\n try:\n FD_CLOEXEC = fcntl.FD_CLOEXEC # pylint: disable=C0103\n except AttributeError:\n FD_CLOEXEC = 1 # pylint: disable=C0103\n old_flags = fcntl.fcntl(f_handle.fileno(), fcntl.F_GETFD)\n fcntl.fcntl(f_handle.fileno(), fcntl.F_SETFD, old_flags | FD_CLOEXEC)\n\n return f_handle\n", "def to_unicode(s, encoding=None, errors='strict', normalize=False):\n '''\n Given str or unicode, return unicode (str for python 3)\n '''\n def _normalize(s):\n return unicodedata.normalize('NFC', s) if normalize else s\n\n if encoding is None:\n # Try utf-8 first, and fall back to detected encoding\n encoding = ('utf-8', __salt_system_encoding__)\n if not isinstance(encoding, (tuple, list)):\n encoding = (encoding,)\n\n if not encoding:\n raise ValueError('encoding cannot be empty')\n\n exc = None\n if six.PY3:\n if isinstance(s, str):\n return _normalize(s)\n elif isinstance(s, (bytes, bytearray)):\n return _normalize(to_str(s, encoding, errors))\n raise TypeError('expected str, bytes, or bytearray')\n else:\n # This needs to be str and not six.string_types, since if the string is\n # already a unicode type, it does not need to be decoded (and doing so\n # will raise an exception).\n if isinstance(s, unicode): # pylint: disable=incompatible-py3-code,undefined-variable\n return _normalize(s)\n elif isinstance(s, (str, bytearray)):\n for enc in encoding:\n try:\n return _normalize(s.decode(enc, errors))\n except UnicodeDecodeError as err:\n exc = err\n continue\n # The only way we get this far is if a UnicodeDecodeError was\n # raised, otherwise we would have already returned (or raised some\n # other exception).\n raise exc # pylint: disable=raising-bad-type\n raise TypeError('expected str or bytearray')\n", "def automaster(config='/etc/auto_salt'):\n '''\n List the contents of the auto master\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' mount.automaster\n '''\n ret = {}\n if not os.path.isfile(config):\n return ret\n with salt.utils.files.fopen(config) as ifile:\n for line in ifile:\n line = salt.utils.stringutils.to_unicode(line)\n if line.startswith('#'):\n # Commented\n continue\n if not line.strip():\n # Blank line\n continue\n comps = line.split()\n if len(comps) != 3:\n # Invalid entry\n continue\n\n prefix = \"/..\"\n name = comps[0].replace(prefix, \"\")\n device_fmt = comps[2].split(\":\")\n opts = comps[1].split(',')\n\n ret[name] = {'device': device_fmt[1],\n 'fstype': opts[0],\n 'opts': opts[1:]}\n return ret\n" ]
# -*- coding: utf-8 -*- ''' Salt module to manage Unix mounts and the fstab file ''' # Import python libs from __future__ import absolute_import, print_function, unicode_literals import os import re import logging # Import salt libs import salt.utils.args import salt.utils.data import salt.utils.files import salt.utils.path import salt.utils.platform import salt.utils.mount import salt.utils.stringutils from salt.utils.odict import OrderedDict from salt.exceptions import CommandNotFoundError, CommandExecutionError # Import 3rd-party libs from salt.ext import six from salt.ext.six.moves import filter, zip # pylint: disable=import-error,redefined-builtin # Set up logger log = logging.getLogger(__name__) # Define the module's virtual name __virtualname__ = 'mount' def __virtual__(): ''' Only load on POSIX-like systems ''' # Disable on Windows, a specific file module exists: if salt.utils.platform.is_windows(): return (False, 'The mount module cannot be loaded: not a POSIX-like system.') return True def _list_mounts(): ret = {} if __grains__['os'] in ['MacOS', 'Darwin']: mounts = __salt__['cmd.run_stdout']('mount') else: mounts = __salt__['cmd.run_stdout']('mount -l') for line in mounts.split('\n'): comps = re.sub(r"\s+", " ", line).split() if len(comps) >= 3: ret[comps[2]] = comps[0] return ret def _active_mountinfo(ret): _list = _list_mounts() filename = '/proc/self/mountinfo' if not os.access(filename, os.R_OK): msg = 'File not readable {0}' raise CommandExecutionError(msg.format(filename)) if 'disk.blkid' not in __context__: __context__['disk.blkid'] = __salt__['disk.blkid']() blkid_info = __context__['disk.blkid'] with salt.utils.files.fopen(filename) as ifile: for line in ifile: comps = salt.utils.stringutils.to_unicode(line).split() device = comps[2].split(':') # each line can have any number of # optional parameters, we use the # location of the separator field to # determine the location of the elements # after it. _sep = comps.index('-') device_name = comps[_sep + 2] device_uuid = None device_label = None if device_name: device_uuid = blkid_info.get(device_name, {}).get('UUID') device_uuid = device_uuid and device_uuid.lower() device_label = blkid_info.get(device_name, {}).get('LABEL') ret[comps[4]] = {'mountid': comps[0], 'parentid': comps[1], 'major': device[0], 'minor': device[1], 'root': comps[3], 'opts': _resolve_user_group_names(comps[5].split(',')), 'fstype': comps[_sep + 1], 'device': device_name.replace('\\040', '\\ '), 'alt_device': _list.get(comps[4], None), 'superopts': _resolve_user_group_names(comps[_sep + 3].split(',')), 'device_uuid': device_uuid, 'device_label': device_label} return ret def _active_mounts(ret): ''' List active mounts on Linux systems ''' _list = _list_mounts() filename = '/proc/self/mounts' if not os.access(filename, os.R_OK): msg = 'File not readable {0}' raise CommandExecutionError(msg.format(filename)) with salt.utils.files.fopen(filename) as ifile: for line in ifile: comps = salt.utils.stringutils.to_unicode(line).split() ret[comps[1]] = {'device': comps[0], 'alt_device': _list.get(comps[1], None), 'fstype': comps[2], 'opts': _resolve_user_group_names(comps[3].split(','))} return ret def _active_mounts_aix(ret): ''' List active mounts on AIX systems ''' for line in __salt__['cmd.run_stdout']('mount -p').split('\n'): comps = re.sub(r"\s+", " ", line).split() if comps: if comps[0] == 'node' or comps[0] == '--------': continue comps_len = len(comps) if line.startswith((' ', '\t')): curr_opts = _resolve_user_group_names(comps[6].split(',')) if 7 == comps_len else [] if curr_opts: ret[comps[1]] = {'device': comps[0], 'fstype': comps[2], 'opts': curr_opts} else: ret[comps[1]] = {'device': comps[0], 'fstype': comps[2]} else: curr_opts = _resolve_user_group_names(comps[7].split(',')) if 8 == comps_len else [] if curr_opts: ret[comps[2]] = {'node': comps[0], 'device': comps[1], 'fstype': comps[3], 'opts': curr_opts} else: ret[comps[2]] = {'node': comps[0], 'device': comps[1], 'fstype': comps[3]} return ret def _active_mounts_freebsd(ret): ''' List active mounts on FreeBSD systems ''' for line in __salt__['cmd.run_stdout']('mount -p').split('\n'): comps = re.sub(r"\s+", " ", line).split() ret[comps[1]] = {'device': comps[0], 'fstype': comps[2], 'opts': _resolve_user_group_names(comps[3].split(','))} return ret def _active_mounts_solaris(ret): ''' List active mounts on Solaris systems ''' for line in __salt__['cmd.run_stdout']('mount -v').split('\n'): comps = re.sub(r"\s+", " ", line).split() ret[comps[2]] = {'device': comps[0], 'fstype': comps[4], 'opts': _resolve_user_group_names(comps[5].split('/'))} return ret def _active_mounts_openbsd(ret): ''' List active mounts on OpenBSD systems ''' for line in __salt__['cmd.run_stdout']('mount -v').split('\n'): comps = re.sub(r"\s+", " ", line).split() parens = re.findall(r'\((.*?)\)', line, re.DOTALL) if len(parens) > 1: nod = __salt__['cmd.run_stdout']('ls -l {0}'.format(comps[0])) nod = ' '.join(nod.split()).split(" ") ret[comps[3]] = {'device': comps[0], 'fstype': comps[5], 'opts': _resolve_user_group_names(parens[1].split(", ")), 'major': six.text_type(nod[4].strip(",")), 'minor': six.text_type(nod[5]), 'device_uuid': parens[0]} else: ret[comps[2]] = {'device': comps[0], 'fstype': comps[4], 'opts': _resolve_user_group_names(parens[0].split(", "))} return ret def _active_mounts_darwin(ret): ''' List active mounts on Mac OS systems ''' for line in __salt__['cmd.run_stdout']('mount').split('\n'): comps = re.sub(r"\s+", " ", line).split() parens = re.findall(r'\((.*?)\)', line, re.DOTALL)[0].split(", ") ret[comps[2]] = {'device': comps[0], 'fstype': parens[0], 'opts': _resolve_user_group_names(parens[1:])} return ret def _resolve_user_group_names(opts): ''' Resolve user and group names in related opts ''' name_id_opts = {'uid': 'user.info', 'gid': 'group.info'} for ind, opt in enumerate(opts): if opt.split('=')[0] in name_id_opts: _givenid = opt.split('=')[1] _param = opt.split('=')[0] _id = _givenid if not re.match('[0-9]+$', _givenid): _info = __salt__[name_id_opts[_param]](_givenid) if _info and _param in _info: _id = _info[_param] opts[ind] = _param + '=' + six.text_type(_id) opts[ind] = opts[ind].replace('\\040', '\\ ') return opts def active(extended=False): ''' List the active mounts. CLI Example: .. code-block:: bash salt '*' mount.active ''' ret = {} if __grains__['os'] == 'FreeBSD': _active_mounts_freebsd(ret) elif 'AIX' in __grains__['kernel']: _active_mounts_aix(ret) elif __grains__['kernel'] == 'SunOS': _active_mounts_solaris(ret) elif __grains__['os'] == 'OpenBSD': _active_mounts_openbsd(ret) elif __grains__['os'] in ['MacOS', 'Darwin']: _active_mounts_darwin(ret) else: if extended: try: _active_mountinfo(ret) except CommandExecutionError: _active_mounts(ret) else: _active_mounts(ret) return ret class _fstab_entry(object): ''' Utility class for manipulating fstab entries. Primarily we're parsing, formatting, and comparing lines. Parsing emits dicts expected from fstab() or raises a ValueError. Note: We'll probably want to use os.normpath and os.normcase on 'name' ''' class ParseError(ValueError): ''' Error raised when a line isn't parsible as an fstab entry ''' fstab_keys = ('device', 'name', 'fstype', 'opts', 'dump', 'pass_num') # preserve data format compatibility_keys = ('device', 'name', 'fstype', 'opts', 'dump', 'pass') fstab_format = '{device}\t\t{name}\t{fstype}\t{opts}\t{dump} {pass_num}\n' @classmethod def dict_from_line(cls, line, keys=fstab_keys): if len(keys) != 6: raise ValueError('Invalid key array: {0}'.format(keys)) if line.startswith('#'): raise cls.ParseError("Comment!") comps = line.split() if len(comps) < 4 or len(comps) > 6: raise cls.ParseError("Invalid Entry!") comps.extend(['0'] * (len(keys) - len(comps))) return dict(zip(keys, comps)) @classmethod def from_line(cls, *args, **kwargs): return cls(** cls.dict_from_line(*args, **kwargs)) @classmethod def dict_to_line(cls, entry): return cls.fstab_format.format(**entry) def __str__(self): ''' String value, only works for full repr ''' return self.dict_to_line(self.criteria) def __repr__(self): ''' Always works ''' return repr(self.criteria) def pick(self, keys): ''' Returns an instance with just those keys ''' subset = dict([(key, self.criteria[key]) for key in keys]) return self.__class__(**subset) def __init__(self, **criteria): ''' Store non-empty, non-null values to use as filter ''' items = [key_value for key_value in six.iteritems(criteria) if key_value[1] is not None] items = [(key_value1[0], six.text_type(key_value1[1])) for key_value1 in items] self.criteria = dict(items) @staticmethod def norm_path(path): ''' Resolve equivalent paths equivalently ''' return os.path.normcase(os.path.normpath(path)) def match(self, line): ''' Compare potentially partial criteria against line ''' entry = self.dict_from_line(line) for key, value in six.iteritems(self.criteria): if entry[key] != value: return False return True class _vfstab_entry(object): ''' Utility class for manipulating vfstab entries. Primarily we're parsing, formatting, and comparing lines. Parsing emits dicts expected from fstab() or raises a ValueError. Note: We'll probably want to use os.normpath and os.normcase on 'name' Note: This parses vfstab entries on Solaris like systems #device device mount FS fsck mount mount #to mount to fsck point type pass at boot options # /devices - /devices devfs - no - ''' class ParseError(ValueError): '''Error raised when a line isn't parsible as an fstab entry''' vfstab_keys = ('device', 'device_fsck', 'name', 'fstype', 'pass_fsck', 'mount_at_boot', 'opts') # NOTE: weird formatting to match default spacing on Solaris vfstab_format = '{device:<11} {device_fsck:<3} {name:<19} {fstype:<8} {pass_fsck:<3} {mount_at_boot:<6} {opts}\n' @classmethod def dict_from_line(cls, line): if line.startswith('#'): raise cls.ParseError("Comment!") comps = line.split() if len(comps) != 7: raise cls.ParseError("Invalid Entry!") return dict(zip(cls.vfstab_keys, comps)) @classmethod def from_line(cls, *args, **kwargs): return cls(** cls.dict_from_line(*args, **kwargs)) @classmethod def dict_to_line(cls, entry): return cls.vfstab_format.format(**entry) def __str__(self): ''' String value, only works for full repr ''' return self.dict_to_line(self.criteria) def __repr__(self): ''' Always works ''' return repr(self.criteria) def pick(self, keys): ''' Returns an instance with just those keys ''' subset = dict([(key, self.criteria[key]) for key in keys]) return self.__class__(**subset) def __init__(self, **criteria): ''' Store non-empty, non-null values to use as filter ''' items = [key_value for key_value in six.iteritems(criteria) if key_value[1] is not None] items = [(key_value1[0], six.text_type(key_value1[1])) for key_value1 in items] self.criteria = dict(items) @staticmethod def norm_path(path): ''' Resolve equivalent paths equivalently ''' return os.path.normcase(os.path.normpath(path)) def match(self, line): ''' Compare potentially partial criteria against line ''' entry = self.dict_from_line(line) for key, value in six.iteritems(self.criteria): if entry[key] != value: return False return True class _FileSystemsEntry(object): ''' Utility class for manipulating filesystem entries. Primarily we're parsing, formatting, and comparing lines. Parsing emits dicts expected from fstab() or raises a ValueError. Note: We'll probably want to use os.normpath and os.normcase on 'name' ''' class ParseError(ValueError): ''' Error raised when a line isn't parsible as an fstab entry ''' filesystems_keys = ('device', 'name', 'fstype', 'vfstype', 'opts', 'mount') # preserve data format of filesystems compatibility_keys = ('dev', 'dev', 'name', 'fstype', 'vfstype', 'opts', 'mount', 'type', 'vfs', 'account', 'boot', 'check', 'free', 'nodename', 'quota', 'size', 'vol', 'log') @classmethod def dict_from_lines(cls, lines, keys=filesystems_keys): if len(lines) < 2: raise ValueError('Invalid number of lines: {0}'.format(lines)) if not keys: # if empty force default filesystems_keys keys = _FileSystemsEntry.filesystems_keys elif len(keys) < 6: raise ValueError('Invalid key name array: {0}'.format(keys)) blk_lines = lines orddict = OrderedDict() orddict['name'] = blk_lines[0].split(':')[0].strip() blk_lines.pop(0) for line in blk_lines: if line.startswith('#'): raise cls.ParseError("Comment!") comps = line.split('= ') if len(comps) != 2: raise cls.ParseError("Invalid Entry!") key_name = comps[0].strip() if key_name in keys: orddict[key_name] = comps[1].strip() else: raise ValueError('Invalid name for use in filesystems: {0}'.format(key_name)) return orddict @classmethod def dict_from_cmd_line(cls, ipargs, keys): cmdln_dict = ipargs if keys: for key, value in keys: # ignore unknown or local scope keys if key.startswith('__'): continue if key in _FileSystemsEntry.compatibility_keys: cmdln_dict[key] = value return cmdln_dict @classmethod def from_line(cls, *args, **kwargs): return cls(** cls.dict_from_cmd_line(*args, **kwargs)) @classmethod def dict_to_lines(cls, fsys_dict_entry): entry = fsys_dict_entry strg_out = entry['name'] + ':' + os.linesep for k, v in six.viewitems(entry): if 'name' not in k: strg_out += '\t{0}\t\t= {1}'.format(k, v) + os.linesep strg_out += os.linesep return six.text_type(strg_out) def dict_from_entry(self): ret = OrderedDict() ret[self.criteria['name']] = self.criteria return ret def __str__(self): ''' String value, only works for full repr ''' return self.dict_to_lines(self.criteria) def __repr__(self): ''' Always works ''' return repr(self.criteria) def pick(self, keys): ''' Returns an instance with just those keys ''' subset = dict([(key, self.criteria[key]) for key in keys]) return self.__class__(**subset) def __init__(self, **criteria): ''' Store non-empty, non-null values to use as filter ''' items = [key_value for key_value in six.iteritems(criteria) if key_value[1] is not None] items = [(key_value1[0], six.text_type(key_value1[1])) for key_value1 in items] self.criteria = OrderedDict(items) @staticmethod def norm_path(path): ''' Resolve equivalent paths equivalently ''' return os.path.normcase(os.path.normpath(path)) def match(self, fsys_view): ''' Compare potentially partial criteria against built filesystems entry dictionary ''' evalue_dict = fsys_view[1] for key, value in six.viewitems(self.criteria): if key in evalue_dict: if evalue_dict[key] != value: return False else: return False return True def __getitem__(self, key): ''' Return value for input key ''' return self.criteria[key] def fstab(config='/etc/fstab'): ''' .. versionchanged:: 2016.3.2 List the contents of the fstab CLI Example: .. code-block:: bash salt '*' mount.fstab ''' ret = {} if not os.path.isfile(config): return ret with salt.utils.files.fopen(config) as ifile: for line in ifile: line = salt.utils.stringutils.to_unicode(line) try: if __grains__['kernel'] == 'SunOS': # Note: comments use in default vfstab file! if line[0] == '#': continue entry = _vfstab_entry.dict_from_line( line) else: entry = _fstab_entry.dict_from_line( line, _fstab_entry.compatibility_keys) entry['opts'] = entry['opts'].split(',') while entry['name'] in ret: entry['name'] += '_' ret[entry.pop('name')] = entry except _fstab_entry.ParseError: pass except _vfstab_entry.ParseError: pass return ret def vfstab(config='/etc/vfstab'): ''' .. versionadded:: 2016.3.2 List the contents of the vfstab CLI Example: .. code-block:: bash salt '*' mount.vfstab ''' # NOTE: vfstab is a wrapper for fstab return fstab(config) def rm_fstab(name, device, config='/etc/fstab'): ''' .. versionchanged:: 2016.3.2 Remove the mount point from the fstab CLI Example: .. code-block:: bash salt '*' mount.rm_fstab /mnt/foo /dev/sdg ''' modified = False if __grains__['kernel'] == 'SunOS': criteria = _vfstab_entry(name=name, device=device) else: criteria = _fstab_entry(name=name, device=device) lines = [] try: with salt.utils.files.fopen(config, 'r') as ifile: for line in ifile: line = salt.utils.stringutils.to_unicode(line) try: if criteria.match(line): modified = True else: lines.append(line) except _fstab_entry.ParseError: lines.append(line) except _vfstab_entry.ParseError: lines.append(line) except (IOError, OSError) as exc: msg = "Couldn't read from {0}: {1}" raise CommandExecutionError(msg.format(config, exc)) if modified: try: with salt.utils.files.fopen(config, 'wb') as ofile: ofile.writelines(salt.utils.data.encode(lines)) except (IOError, OSError) as exc: msg = "Couldn't write to {0}: {1}" raise CommandExecutionError(msg.format(config, exc)) # Note: not clear why we always return 'True' # --just copying previous behavior at this point... return True def rm_vfstab(name, device, config='/etc/vfstab'): ''' .. versionadded:: 2016.3.2 Remove the mount point from the vfstab CLI Example: .. code-block:: bash salt '*' mount.rm_vfstab /mnt/foo /device/c0t0d0p0 ''' ## NOTE: rm_vfstab is a wrapper for rm_fstab return rm_fstab(name, device, config) def set_fstab( name, device, fstype, opts='defaults', dump=0, pass_num=0, config='/etc/fstab', test=False, match_on='auto', **kwargs): ''' Verify that this mount is represented in the fstab, change the mount to match the data passed, or add the mount if it is not present. CLI Example: .. code-block:: bash salt '*' mount.set_fstab /mnt/foo /dev/sdz1 ext4 ''' # Fix the opts type if it is a list if isinstance(opts, list): opts = ','.join(opts) # preserve arguments for updating entry_args = { 'name': name, 'device': device.replace('\\ ', '\\040'), 'fstype': fstype, 'opts': opts.replace('\\ ', '\\040'), 'dump': dump, 'pass_num': pass_num, } lines = [] ret = None # Transform match_on into list--items will be checked later if isinstance(match_on, list): pass elif not isinstance(match_on, six.string_types): msg = 'match_on must be a string or list of strings' raise CommandExecutionError(msg) elif match_on == 'auto': # Try to guess right criteria for auto.... # NOTE: missing some special fstypes here specialFSes = frozenset([ 'none', 'tmpfs', 'sysfs', 'proc', 'fusectl', 'debugfs', 'securityfs', 'devtmpfs', 'cgroup', 'btrfs']) if fstype in specialFSes: match_on = ['name'] else: match_on = ['device'] else: match_on = [match_on] # generate entry and criteria objects, handle invalid keys in match_on entry = _fstab_entry(**entry_args) try: criteria = entry.pick(match_on) except KeyError: filterFn = lambda key: key not in _fstab_entry.fstab_keys invalid_keys = filter(filterFn, match_on) msg = 'Unrecognized keys in match_on: "{0}"'.format(invalid_keys) raise CommandExecutionError(msg) # parse file, use ret to cache status if not os.path.isfile(config): raise CommandExecutionError('Bad config file "{0}"'.format(config)) try: with salt.utils.files.fopen(config, 'r') as ifile: for line in ifile: line = salt.utils.stringutils.to_unicode(line) try: if criteria.match(line): # Note: If ret isn't None here, # we've matched multiple lines ret = 'present' if entry.match(line): lines.append(line) else: ret = 'change' lines.append(six.text_type(entry)) else: lines.append(line) except _fstab_entry.ParseError: lines.append(line) except (IOError, OSError) as exc: msg = 'Couldn\'t read from {0}: {1}' raise CommandExecutionError(msg.format(config, exc)) # add line if not present or changed if ret is None: lines.append(six.text_type(entry)) ret = 'new' if ret != 'present': # ret in ['new', 'change']: if not salt.utils.args.test_mode(test=test, **kwargs): try: with salt.utils.files.fopen(config, 'wb') as ofile: # The line was changed, commit it! ofile.writelines(salt.utils.data.encode(lines)) except (IOError, OSError): msg = 'File not writable {0}' raise CommandExecutionError(msg.format(config)) return ret def set_vfstab( name, device, fstype, opts='-', device_fsck='-', pass_fsck='-', mount_at_boot='yes', config='/etc/vfstab', test=False, match_on='auto', **kwargs): ''' ..verionadded:: 2016.3.2 Verify that this mount is represented in the fstab, change the mount to match the data passed, or add the mount if it is not present. CLI Example: .. code-block:: bash salt '*' mount.set_vfstab /mnt/foo /device/c0t0d0p0 ufs ''' # Fix the opts type if it is a list if isinstance(opts, list): opts = ','.join(opts) # Map unknown values for mount_at_boot to no if mount_at_boot != 'yes': mount_at_boot = 'no' # preserve arguments for updating entry_args = { 'name': name, 'device': device, 'fstype': fstype, 'opts': opts, 'device_fsck': device_fsck, 'pass_fsck': pass_fsck, 'mount_at_boot': mount_at_boot, } lines = [] ret = None # Transform match_on into list--items will be checked later if isinstance(match_on, list): pass elif not isinstance(match_on, six.string_types): msg = 'match_on must be a string or list of strings' raise CommandExecutionError(msg) elif match_on == 'auto': # Try to guess right criteria for auto.... # NOTE: missing some special fstypes here specialFSes = frozenset([ 'devfs', 'proc', 'ctfs', 'objfs', 'sharefs', 'fs', 'tmpfs']) if fstype in specialFSes: match_on = ['name'] else: match_on = ['device'] else: match_on = [match_on] # generate entry and criteria objects, handle invalid keys in match_on entry = _vfstab_entry(**entry_args) try: criteria = entry.pick(match_on) except KeyError: filterFn = lambda key: key not in _vfstab_entry.vfstab_keys invalid_keys = filter(filterFn, match_on) msg = 'Unrecognized keys in match_on: "{0}"'.format(invalid_keys) raise CommandExecutionError(msg) # parse file, use ret to cache status if not os.path.isfile(config): raise CommandExecutionError('Bad config file "{0}"'.format(config)) try: with salt.utils.files.fopen(config, 'r') as ifile: for line in ifile: line = salt.utils.stringutils.to_unicode(line) try: if criteria.match(line): # Note: If ret isn't None here, # we've matched multiple lines ret = 'present' if entry.match(line): lines.append(line) else: ret = 'change' lines.append(six.text_type(entry)) else: lines.append(line) except _vfstab_entry.ParseError: lines.append(line) except (IOError, OSError) as exc: msg = 'Couldn\'t read from {0}: {1}' raise CommandExecutionError(msg.format(config, exc)) # add line if not present or changed if ret is None: lines.append(six.text_type(entry)) ret = 'new' if ret != 'present': # ret in ['new', 'change']: if not salt.utils.args.test_mode(test=test, **kwargs): try: with salt.utils.files.fopen(config, 'wb') as ofile: # The line was changed, commit it! ofile.writelines(salt.utils.data.encode(lines)) except (IOError, OSError): msg = 'File not writable {0}' raise CommandExecutionError(msg.format(config)) return ret def set_automaster( name, device, fstype, opts='', config='/etc/auto_salt', test=False, **kwargs): ''' Verify that this mount is represented in the auto_salt, change the mount to match the data passed, or add the mount if it is not present. CLI Example: .. code-block:: bash salt '*' mount.set_automaster /mnt/foo /dev/sdz1 ext4 ''' # Fix the opts type if it is a list if isinstance(opts, list): opts = ','.join(opts) lines = [] change = False present = False automaster_file = "/etc/auto_master" if not os.path.isfile(config): __salt__['file.touch'](config) __salt__['file.append'](automaster_file, "/-\t\t\t{0}".format(config)) name = "/..{0}".format(name) device_fmt = "{0}:{1}".format(fstype, device) type_opts = "-fstype={0},{1}".format(fstype, opts) if fstype == 'smbfs': device_fmt = device_fmt.replace(fstype, "") try: with salt.utils.files.fopen(config, 'r') as ifile: for line in ifile: line = salt.utils.stringutils.to_unicode(line) if line.startswith('#'): # Commented lines.append(line) continue if not line.strip(): # Blank line lines.append(line) continue comps = line.split() if len(comps) != 3: # Invalid entry lines.append(line) continue if comps[0] == name or comps[2] == device_fmt: # check to see if there are changes # and fix them if there are any present = True if comps[0] != name: change = True comps[0] = name if comps[1] != type_opts: change = True comps[1] = type_opts if comps[2] != device_fmt: change = True comps[2] = device_fmt if change: log.debug( 'auto_master entry for mount point %s needs to be ' 'updated', name ) newline = ( '{0}\t{1}\t{2}\n'.format( name, type_opts, device_fmt) ) lines.append(newline) else: lines.append(line) except (IOError, OSError) as exc: msg = 'Couldn\'t read from {0}: {1}' raise CommandExecutionError(msg.format(config, exc)) if change: if not salt.utils.args.test_mode(test=test, **kwargs): try: with salt.utils.files.fopen(config, 'wb') as ofile: # The line was changed, commit it! ofile.writelines(salt.utils.data.encode(lines)) except (IOError, OSError): msg = 'File not writable {0}' raise CommandExecutionError(msg.format(config)) return 'change' if not change: if present: # The right entry is already here return 'present' else: if not salt.utils.args.test_mode(test=test, **kwargs): # The entry is new, add it to the end of the fstab newline = ( '{0}\t{1}\t{2}\n'.format( name, type_opts, device_fmt) ) lines.append(newline) try: with salt.utils.files.fopen(config, 'wb') as ofile: # The line was changed, commit it! ofile.writelines(salt.utils.data.encode(lines)) except (IOError, OSError): raise CommandExecutionError( 'File not writable {0}'.format( config ) ) return 'new' def automaster(config='/etc/auto_salt'): ''' List the contents of the auto master CLI Example: .. code-block:: bash salt '*' mount.automaster ''' ret = {} if not os.path.isfile(config): return ret with salt.utils.files.fopen(config) as ifile: for line in ifile: line = salt.utils.stringutils.to_unicode(line) if line.startswith('#'): # Commented continue if not line.strip(): # Blank line continue comps = line.split() if len(comps) != 3: # Invalid entry continue prefix = "/.." name = comps[0].replace(prefix, "") device_fmt = comps[2].split(":") opts = comps[1].split(',') ret[name] = {'device': device_fmt[1], 'fstype': opts[0], 'opts': opts[1:]} return ret def mount(name, device, mkmnt=False, fstype='', opts='defaults', user=None, util='mount'): ''' Mount a device CLI Example: .. code-block:: bash salt '*' mount.mount /mnt/foo /dev/sdz1 True ''' if util != 'mount': # This functionality used to live in img.mount_image if util == 'guestfs': return __salt__['guestfs.mount'](name, root=device) elif util == 'qemu_nbd': mnt = __salt__['qemu_nbd.init'](name, device) if not mnt: return False first = next(six.iterkeys(mnt)) __context__['img.mnt_{0}'.format(first)] = mnt return first return False # Darwin doesn't expect defaults when mounting without other options if 'defaults' in opts and __grains__['os'] in ['MacOS', 'Darwin', 'AIX']: opts = None if isinstance(opts, six.string_types): opts = opts.split(',') if not os.path.exists(name) and mkmnt: __salt__['file.mkdir'](name, user=user) args = '' if opts is not None: lopts = ','.join(opts) args = '-o {0}'.format(lopts) if fstype: # use of fstype on AIX differs from typical Linux use of -t # functionality AIX uses -v vfsname, -t fstype mounts all with # fstype in /etc/filesystems if 'AIX' in __grains__['os']: args += ' -v {0}'.format(fstype) elif 'solaris' in __grains__['os'].lower(): args += ' -F {0}'.format(fstype) else: args += ' -t {0}'.format(fstype) cmd = 'mount {0} {1} {2} '.format(args, device, name) out = __salt__['cmd.run_all'](cmd, runas=user, python_shell=False) if out['retcode']: return out['stderr'] return True def remount(name, device, mkmnt=False, fstype='', opts='defaults', user=None): ''' Attempt to remount a device, if the device is not already mounted, mount is called CLI Example: .. code-block:: bash salt '*' mount.remount /mnt/foo /dev/sdz1 True ''' force_mount = False if __grains__['os'] in ['MacOS', 'Darwin']: if opts == 'defaults': opts = 'noowners' if fstype == 'smbfs': force_mount = True if 'AIX' in __grains__['os']: if opts == 'defaults': opts = [] if isinstance(opts, six.string_types): opts = opts.split(',') mnts = active() if name in mnts: # The mount point is mounted, attempt to remount it with the given data if 'remount' not in opts and __grains__['os'] not in ['OpenBSD', 'MacOS', 'Darwin']: opts.append('remount') if force_mount: # We need to force the mount but first we should unmount umount(name, device, user=user) lopts = ','.join(opts) args = '-o {0}'.format(lopts) if fstype: # use of fstype on AIX differs from typical Linux use of # -t functionality AIX uses -v vfsname, -t fstype mounts # all with fstype in /etc/filesystems if 'AIX' in __grains__['os']: args += ' -v {0}'.format(fstype) elif 'solaris' in __grains__['os'].lower(): args += ' -F {0}'.format(fstype) else: args += ' -t {0}'.format(fstype) if __grains__['os'] not in ['OpenBSD', 'MacOS', 'Darwin'] or force_mount: cmd = 'mount {0} {1} {2} '.format(args, device, name) else: cmd = 'mount -u {0} {1} {2} '.format(args, device, name) out = __salt__['cmd.run_all'](cmd, runas=user, python_shell=False) if out['retcode']: return out['stderr'] return True # Mount a filesystem that isn't already return mount(name, device, mkmnt, fstype, opts, user=user) def umount(name, device=None, user=None, util='mount'): ''' Attempt to unmount a device by specifying the directory it is mounted on CLI Example: .. code-block:: bash salt '*' mount.umount /mnt/foo .. versionadded:: 2015.5.0 .. code-block:: bash salt '*' mount.umount /mnt/foo /dev/xvdc1 ''' if util != 'mount': # This functionality used to live in img.umount_image if 'qemu_nbd.clear' in __salt__: if 'img.mnt_{0}'.format(name) in __context__: __salt__['qemu_nbd.clear'](__context__['img.mnt_{0}'.format(name)]) return mnts = active() if name not in mnts: return "{0} does not have anything mounted".format(name) if not device: cmd = 'umount {0}'.format(name) else: cmd = 'umount {0}'.format(device) out = __salt__['cmd.run_all'](cmd, runas=user, python_shell=False) if out['retcode']: return out['stderr'] return True def is_fuse_exec(cmd): ''' Returns true if the command passed is a fuse mountable application. CLI Example: .. code-block:: bash salt '*' mount.is_fuse_exec sshfs ''' cmd_path = salt.utils.path.which(cmd) # No point in running ldd on a command that doesn't exist if not cmd_path: return False elif not salt.utils.path.which('ldd'): raise CommandNotFoundError('ldd') out = __salt__['cmd.run']('ldd {0}'.format(cmd_path), python_shell=False) return 'libfuse' in out def swaps(): ''' Return a dict containing information on active swap .. versionchanged:: 2016.3.2 CLI Example: .. code-block:: bash salt '*' mount.swaps ''' ret = {} if __grains__['kernel'] == 'SunOS': for line in __salt__['cmd.run_stdout']('swap -l').splitlines(): if line.startswith('swapfile'): continue comps = line.split() ret[comps[0]] = {'type': 'device' if comps[0].startswith(('/dev', 'swap')) else 'file', 'size': int(comps[3]), 'used': (int(comps[3]) - int(comps[4])), 'priority': '-'} elif 'AIX' in __grains__['kernel']: for line in __salt__['cmd.run_stdout']('swap -l').splitlines(): if line.startswith('device'): continue comps = line.split() # AIX uses MB for units ret[comps[0]] = {'type': 'device', 'size': int(comps[3][:-2]) * 1024, 'used': (int(comps[3][:-2]) - int(comps[4][:-2])) * 1024, 'priority': '-'} elif __grains__['os'] != 'OpenBSD': with salt.utils.files.fopen('/proc/swaps') as fp_: for line in fp_: line = salt.utils.stringutils.to_unicode(line) if line.startswith('Filename'): continue comps = line.split() ret[comps[0]] = {'type': comps[1], 'size': comps[2], 'used': comps[3], 'priority': comps[4]} else: for line in __salt__['cmd.run_stdout']('swapctl -kl').splitlines(): if line.startswith(('Device', 'Total')): continue swap_type = "file" comps = line.split() if comps[0].startswith('/dev/'): swap_type = "partition" ret[comps[0]] = {'type': swap_type, 'size': comps[1], 'used': comps[2], 'priority': comps[5]} return ret def swapon(name, priority=None): ''' Activate a swap disk .. versionchanged:: 2016.3.2 CLI Example: .. code-block:: bash salt '*' mount.swapon /root/swapfile ''' ret = {} on_ = swaps() if name in on_: ret['stats'] = on_[name] ret['new'] = False return ret if __grains__['kernel'] == 'SunOS': if __grains__['virtual'] != 'zone': __salt__['cmd.run']('swap -a {0}'.format(name), python_shell=False) else: return False else: cmd = 'swapon {0}'.format(name) if priority and 'AIX' not in __grains__['kernel']: cmd += ' -p {0}'.format(priority) __salt__['cmd.run'](cmd, python_shell=False) on_ = swaps() if name in on_: ret['stats'] = on_[name] ret['new'] = True return ret return ret def swapoff(name): ''' Deactivate a named swap mount .. versionchanged:: 2016.3.2 CLI Example: .. code-block:: bash salt '*' mount.swapoff /root/swapfile ''' on_ = swaps() if name in on_: if __grains__['kernel'] == 'SunOS': if __grains__['virtual'] != 'zone': __salt__['cmd.run']('swap -a {0}'.format(name), python_shell=False) else: return False elif __grains__['os'] != 'OpenBSD': __salt__['cmd.run']('swapoff {0}'.format(name), python_shell=False) else: __salt__['cmd.run']('swapctl -d {0}'.format(name), python_shell=False) on_ = swaps() if name in on_: return False return True return None def is_mounted(name): ''' .. versionadded:: 2014.7.0 Provide information if the path is mounted CLI Example: .. code-block:: bash salt '*' mount.is_mounted /mnt/share ''' active_ = active() if name in active_: return True else: return False def read_mount_cache(name): ''' .. versionadded:: 2018.3.0 Provide information if the path is mounted CLI Example: .. code-block:: bash salt '*' mount.read_mount_cache /mnt/share ''' cache = salt.utils.mount.read_cache(__opts__) if cache: if 'mounts' in cache and cache['mounts']: if name in cache['mounts']: return cache['mounts'][name] return {} def write_mount_cache(real_name, device, mkmnt, fstype, mount_opts): ''' .. versionadded:: 2018.3.0 Provide information if the path is mounted :param real_name: The real name of the mount point where the device is mounted. :param device: The device that is being mounted. :param mkmnt: Whether or not the mount point should be created. :param fstype: The file system that is used. :param mount_opts: Additional options used when mounting the device. :return: Boolean if message was sent successfully. CLI Example: .. code-block:: bash salt '*' mount.write_mount_cache /mnt/share /dev/sda1 False ext4 defaults,nosuid ''' cache = salt.utils.mount.read_cache(__opts__) if not cache: cache = {} cache['mounts'] = {} else: if 'mounts' not in cache: cache['mounts'] = {} cache['mounts'][real_name] = {'device': device, 'fstype': fstype, 'mkmnt': mkmnt, 'opts': mount_opts} cache_write = salt.utils.mount.write_cache(cache, __opts__) if cache_write: return True else: raise CommandExecutionError('Unable to write mount cache.') def delete_mount_cache(real_name): ''' .. versionadded:: 2018.3.0 Provide information if the path is mounted CLI Example: .. code-block:: bash salt '*' mount.delete_mount_cache /mnt/share ''' cache = salt.utils.mount.read_cache(__opts__) if cache: if 'mounts' in cache: if real_name in cache['mounts']: del cache['mounts'][real_name] cache_write = salt.utils.mount.write_cache(cache, __opts__) if not cache_write: raise CommandExecutionError('Unable to write mount cache.') return True def _filesystems(config='/etc/filesystems', leading_key=True): ''' Return the contents of the filesystems in an OrderedDict config File containing filesystem infomation leading_key True return dictionary keyed by 'name' and value as dictionary with other keys, values (name excluded) OrderedDict({ '/dir' : OrderedDict({'dev': '/dev/hd8', .... }})) False return dictionary keyed by 'name' and value as dictionary with all keys, values (name included) OrderedDict({ '/dir' : OrderedDict({'name': '/dir', 'dev': '/dev/hd8', ... })}) ''' ret = OrderedDict() lines = [] parsing_block = False if not os.path.isfile(config) or 'AIX' not in __grains__['kernel']: return ret # read in block of filesystems, block starts with '/' till empty line with salt.utils.files.fopen(config) as ifile: for line in ifile: line = salt.utils.stringutils.to_unicode(line) # skip till first entry if not line.startswith('/') and not parsing_block: continue if line.startswith('/'): parsing_block = True lines.append(line) elif not line.split(): parsing_block = False try: entry = _FileSystemsEntry.dict_from_lines( lines, _FileSystemsEntry.compatibility_keys) lines = [] if 'opts' in entry: entry['opts'] = entry['opts'].split(',') while entry['name'] in ret: entry['name'] += '_' if leading_key: ret[entry.pop('name')] = entry else: ret[entry['name']] = entry except _FileSystemsEntry.ParseError: pass else: lines.append(line) return ret def filesystems(config='/etc/filesystems'): ''' .. versionadded:: 2018.3.3 List the contents of the filesystems CLI Example: .. code-block:: bash salt '*' mount.filesystems ''' ret = {} if 'AIX' not in __grains__['kernel']: return ret ret_dict = _filesystems(config) if ret_dict: ret_key = next(iter(ret_dict.keys())) ret = {ret_key: dict(ret_dict[ret_key])} return ret def set_filesystems( name, device, vfstype, opts='-', mount='true', config='/etc/filesystems', test=False, match_on='auto', **kwargs): ''' .. versionadded:: 2018.3.3 Verify that this mount is represented in the filesystems, change the mount to match the data passed, or add the mount if it is not present on AIX Provide information if the path is mounted :param name: The name of the mount point where the device is mounted. :param device: The device that is being mounted. :param vfstype: The file system that is used (AIX has two fstypes, fstype and vfstype - similar to Linux fstype) :param opts: Additional options used when mounting the device. :param mount: Mount if not mounted, default True. :param config: Configuration file, default /etc/filesystems. :param match: File systems type to match on, default auto CLI Example: .. code-block:: bash salt '*' mount.set_filesystems /mnt/foo /dev/sdz1 jfs2 ''' # Fix the opts type if it is a list if isinstance(opts, list): opts = ','.join(opts) # preserve arguments for updating entry_args = { 'name': name, 'dev': device.replace('\\ ', '\\040'), 'vfstype': vfstype, 'opts': opts, 'mount': mount, } view_lines = [] ret = None if 'AIX' not in __grains__['kernel']: return ret # Transform match_on into list--items will be checked later if isinstance(match_on, list): pass elif not isinstance(match_on, six.string_types): raise CommandExecutionError('match_on must be a string or list of strings') elif match_on == 'auto': # Try to guess right criteria for auto.... # added IBM types from sys/vmount.h after btrfs # NOTE: missing some special fstypes here specialFSes = frozenset([ 'none', 'tmpfs', 'sysfs', 'proc', 'fusectl', 'debugfs', 'securityfs', 'devtmpfs', 'cgroup', 'btrfs', 'cdrfs', 'procfs', 'jfs', 'jfs2', 'nfs', 'sfs', 'nfs3', 'cachefs', 'udfs', 'cifs', 'namefs', 'pmemfs', 'ahafs', 'nfs4', 'autofs', 'stnfs']) if vfstype in specialFSes: match_on = ['name'] else: match_on = ['dev'] else: match_on = [match_on] # generate entry and criteria objects, handle invalid keys in match_on entry_ip = _FileSystemsEntry.from_line(entry_args, kwargs) try: criteria = entry_ip.pick(match_on) except KeyError: filterFn = lambda key: key not in _FileSystemsEntry.compatibility_keys invalid_keys = filter(filterFn, match_on) raise CommandExecutionError('Unrecognized keys in match_on: "{0}"'.format(invalid_keys)) # parse file, use ret to cache status if not os.path.isfile(config): raise CommandExecutionError('Bad config file "{0}"'.format(config)) # read in block of filesystem, block starts with '/' till empty line try: fsys_filedict = _filesystems(config, False) for fsys_view in six.viewitems(fsys_filedict): if criteria.match(fsys_view): ret = 'present' if entry_ip.match(fsys_view): view_lines.append(fsys_view) else: ret = 'change' kv = entry_ip['name'] view_lines.append((kv, entry_ip)) else: view_lines.append(fsys_view) except (IOError, OSError) as exc: raise CommandExecutionError('Couldn\'t read from {0}: {1}'.format(config, exc)) # add line if not present or changed if ret is None: for dict_view in six.viewitems(entry_ip.dict_from_entry()): view_lines.append(dict_view) ret = 'new' if ret != 'present': # ret in ['new', 'change']: try: with salt.utils.files.fopen(config, 'wb') as ofile: # The line was changed, commit it! for fsys_view in view_lines: entry = fsys_view[1] mystrg = _FileSystemsEntry.dict_to_lines(entry) ofile.writelines(salt.utils.data.encode(mystrg)) except (IOError, OSError): raise CommandExecutionError('File not writable {0}'.format(config)) return ret def rm_filesystems(name, device, config='/etc/filesystems'): ''' .. versionadded:: 2018.3.3 Remove the mount point from the filesystems CLI Example: .. code-block:: bash salt '*' mount.rm_filesystems /mnt/foo /dev/sdg ''' modified = False view_lines = [] if 'AIX' not in __grains__['kernel']: return modified criteria = _FileSystemsEntry(name=name, dev=device) try: fsys_filedict = _filesystems(config, False) for fsys_view in six.viewitems(fsys_filedict): try: if criteria.match(fsys_view): modified = True else: view_lines.append(fsys_view) except _FileSystemsEntry.ParseError: view_lines.append(fsys_view) except (IOError, OSError) as exc: raise CommandExecutionError("Couldn't read from {0}: {1}".format(config, exc)) if modified: try: with salt.utils.files.fopen(config, 'wb') as ofile: for fsys_view in view_lines: entry = fsys_view[1] mystrg = _FileSystemsEntry.dict_to_lines(entry) ofile.writelines(salt.utils.data.encode(mystrg)) except (IOError, OSError) as exc: raise CommandExecutionError("Couldn't write to {0}: {1}".format(config, exc)) return modified
saltstack/salt
salt/modules/mount.py
set_automaster
python
def set_automaster( name, device, fstype, opts='', config='/etc/auto_salt', test=False, **kwargs): ''' Verify that this mount is represented in the auto_salt, change the mount to match the data passed, or add the mount if it is not present. CLI Example: .. code-block:: bash salt '*' mount.set_automaster /mnt/foo /dev/sdz1 ext4 ''' # Fix the opts type if it is a list if isinstance(opts, list): opts = ','.join(opts) lines = [] change = False present = False automaster_file = "/etc/auto_master" if not os.path.isfile(config): __salt__['file.touch'](config) __salt__['file.append'](automaster_file, "/-\t\t\t{0}".format(config)) name = "/..{0}".format(name) device_fmt = "{0}:{1}".format(fstype, device) type_opts = "-fstype={0},{1}".format(fstype, opts) if fstype == 'smbfs': device_fmt = device_fmt.replace(fstype, "") try: with salt.utils.files.fopen(config, 'r') as ifile: for line in ifile: line = salt.utils.stringutils.to_unicode(line) if line.startswith('#'): # Commented lines.append(line) continue if not line.strip(): # Blank line lines.append(line) continue comps = line.split() if len(comps) != 3: # Invalid entry lines.append(line) continue if comps[0] == name or comps[2] == device_fmt: # check to see if there are changes # and fix them if there are any present = True if comps[0] != name: change = True comps[0] = name if comps[1] != type_opts: change = True comps[1] = type_opts if comps[2] != device_fmt: change = True comps[2] = device_fmt if change: log.debug( 'auto_master entry for mount point %s needs to be ' 'updated', name ) newline = ( '{0}\t{1}\t{2}\n'.format( name, type_opts, device_fmt) ) lines.append(newline) else: lines.append(line) except (IOError, OSError) as exc: msg = 'Couldn\'t read from {0}: {1}' raise CommandExecutionError(msg.format(config, exc)) if change: if not salt.utils.args.test_mode(test=test, **kwargs): try: with salt.utils.files.fopen(config, 'wb') as ofile: # The line was changed, commit it! ofile.writelines(salt.utils.data.encode(lines)) except (IOError, OSError): msg = 'File not writable {0}' raise CommandExecutionError(msg.format(config)) return 'change' if not change: if present: # The right entry is already here return 'present' else: if not salt.utils.args.test_mode(test=test, **kwargs): # The entry is new, add it to the end of the fstab newline = ( '{0}\t{1}\t{2}\n'.format( name, type_opts, device_fmt) ) lines.append(newline) try: with salt.utils.files.fopen(config, 'wb') as ofile: # The line was changed, commit it! ofile.writelines(salt.utils.data.encode(lines)) except (IOError, OSError): raise CommandExecutionError( 'File not writable {0}'.format( config ) ) return 'new'
Verify that this mount is represented in the auto_salt, change the mount to match the data passed, or add the mount if it is not present. CLI Example: .. code-block:: bash salt '*' mount.set_automaster /mnt/foo /dev/sdz1 ext4
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/mount.py#L1019-L1136
[ "def fopen(*args, **kwargs):\n '''\n Wrapper around open() built-in to set CLOEXEC on the fd.\n\n This flag specifies that the file descriptor should be closed when an exec\n function is invoked;\n\n When a file descriptor is allocated (as with open or dup), this bit is\n initially cleared on the new file descriptor, meaning that descriptor will\n survive into the new program after exec.\n\n NB! We still have small race condition between open and fcntl.\n '''\n if six.PY3:\n try:\n # Don't permit stdin/stdout/stderr to be opened. The boolean False\n # and True are treated by Python 3's open() as file descriptors 0\n # and 1, respectively.\n if args[0] in (0, 1, 2):\n raise TypeError(\n '{0} is not a permitted file descriptor'.format(args[0])\n )\n except IndexError:\n pass\n binary = None\n # ensure 'binary' mode is always used on Windows in Python 2\n if ((six.PY2 and salt.utils.platform.is_windows() and 'binary' not in kwargs) or\n kwargs.pop('binary', False)):\n if len(args) > 1:\n args = list(args)\n if 'b' not in args[1]:\n args[1] = args[1].replace('t', 'b')\n if 'b' not in args[1]:\n args[1] += 'b'\n elif kwargs.get('mode'):\n if 'b' not in kwargs['mode']:\n kwargs['mode'] = kwargs['mode'].replace('t', 'b')\n if 'b' not in kwargs['mode']:\n kwargs['mode'] += 'b'\n else:\n # the default is to read\n kwargs['mode'] = 'rb'\n elif six.PY3 and 'encoding' not in kwargs:\n # In Python 3, if text mode is used and the encoding\n # is not specified, set the encoding to 'utf-8'.\n binary = False\n if len(args) > 1:\n args = list(args)\n if 'b' in args[1]:\n binary = True\n if kwargs.get('mode', None):\n if 'b' in kwargs['mode']:\n binary = True\n if not binary:\n kwargs['encoding'] = __salt_system_encoding__\n\n if six.PY3 and not binary and not kwargs.get('newline', None):\n kwargs['newline'] = ''\n\n f_handle = open(*args, **kwargs) # pylint: disable=resource-leakage\n\n if is_fcntl_available():\n # modify the file descriptor on systems with fcntl\n # unix and unix-like systems only\n try:\n FD_CLOEXEC = fcntl.FD_CLOEXEC # pylint: disable=C0103\n except AttributeError:\n FD_CLOEXEC = 1 # pylint: disable=C0103\n old_flags = fcntl.fcntl(f_handle.fileno(), fcntl.F_GETFD)\n fcntl.fcntl(f_handle.fileno(), fcntl.F_SETFD, old_flags | FD_CLOEXEC)\n\n return f_handle\n", "def to_unicode(s, encoding=None, errors='strict', normalize=False):\n '''\n Given str or unicode, return unicode (str for python 3)\n '''\n def _normalize(s):\n return unicodedata.normalize('NFC', s) if normalize else s\n\n if encoding is None:\n # Try utf-8 first, and fall back to detected encoding\n encoding = ('utf-8', __salt_system_encoding__)\n if not isinstance(encoding, (tuple, list)):\n encoding = (encoding,)\n\n if not encoding:\n raise ValueError('encoding cannot be empty')\n\n exc = None\n if six.PY3:\n if isinstance(s, str):\n return _normalize(s)\n elif isinstance(s, (bytes, bytearray)):\n return _normalize(to_str(s, encoding, errors))\n raise TypeError('expected str, bytes, or bytearray')\n else:\n # This needs to be str and not six.string_types, since if the string is\n # already a unicode type, it does not need to be decoded (and doing so\n # will raise an exception).\n if isinstance(s, unicode): # pylint: disable=incompatible-py3-code,undefined-variable\n return _normalize(s)\n elif isinstance(s, (str, bytearray)):\n for enc in encoding:\n try:\n return _normalize(s.decode(enc, errors))\n except UnicodeDecodeError as err:\n exc = err\n continue\n # The only way we get this far is if a UnicodeDecodeError was\n # raised, otherwise we would have already returned (or raised some\n # other exception).\n raise exc # pylint: disable=raising-bad-type\n raise TypeError('expected str or bytearray')\n", "def test_mode(**kwargs):\n '''\n Examines the kwargs passed and returns True if any kwarg which matching\n \"Test\" in any variation on capitalization (i.e. \"TEST\", \"Test\", \"TeSt\",\n etc) contains a True value (as determined by salt.utils.data.is_true).\n '''\n # Once is_true is moved, remove this import and fix the ref below\n import salt.utils\n for arg, value in six.iteritems(kwargs):\n try:\n if arg.lower() == 'test' and salt.utils.data.is_true(value):\n return True\n except AttributeError:\n continue\n return False\n" ]
# -*- coding: utf-8 -*- ''' Salt module to manage Unix mounts and the fstab file ''' # Import python libs from __future__ import absolute_import, print_function, unicode_literals import os import re import logging # Import salt libs import salt.utils.args import salt.utils.data import salt.utils.files import salt.utils.path import salt.utils.platform import salt.utils.mount import salt.utils.stringutils from salt.utils.odict import OrderedDict from salt.exceptions import CommandNotFoundError, CommandExecutionError # Import 3rd-party libs from salt.ext import six from salt.ext.six.moves import filter, zip # pylint: disable=import-error,redefined-builtin # Set up logger log = logging.getLogger(__name__) # Define the module's virtual name __virtualname__ = 'mount' def __virtual__(): ''' Only load on POSIX-like systems ''' # Disable on Windows, a specific file module exists: if salt.utils.platform.is_windows(): return (False, 'The mount module cannot be loaded: not a POSIX-like system.') return True def _list_mounts(): ret = {} if __grains__['os'] in ['MacOS', 'Darwin']: mounts = __salt__['cmd.run_stdout']('mount') else: mounts = __salt__['cmd.run_stdout']('mount -l') for line in mounts.split('\n'): comps = re.sub(r"\s+", " ", line).split() if len(comps) >= 3: ret[comps[2]] = comps[0] return ret def _active_mountinfo(ret): _list = _list_mounts() filename = '/proc/self/mountinfo' if not os.access(filename, os.R_OK): msg = 'File not readable {0}' raise CommandExecutionError(msg.format(filename)) if 'disk.blkid' not in __context__: __context__['disk.blkid'] = __salt__['disk.blkid']() blkid_info = __context__['disk.blkid'] with salt.utils.files.fopen(filename) as ifile: for line in ifile: comps = salt.utils.stringutils.to_unicode(line).split() device = comps[2].split(':') # each line can have any number of # optional parameters, we use the # location of the separator field to # determine the location of the elements # after it. _sep = comps.index('-') device_name = comps[_sep + 2] device_uuid = None device_label = None if device_name: device_uuid = blkid_info.get(device_name, {}).get('UUID') device_uuid = device_uuid and device_uuid.lower() device_label = blkid_info.get(device_name, {}).get('LABEL') ret[comps[4]] = {'mountid': comps[0], 'parentid': comps[1], 'major': device[0], 'minor': device[1], 'root': comps[3], 'opts': _resolve_user_group_names(comps[5].split(',')), 'fstype': comps[_sep + 1], 'device': device_name.replace('\\040', '\\ '), 'alt_device': _list.get(comps[4], None), 'superopts': _resolve_user_group_names(comps[_sep + 3].split(',')), 'device_uuid': device_uuid, 'device_label': device_label} return ret def _active_mounts(ret): ''' List active mounts on Linux systems ''' _list = _list_mounts() filename = '/proc/self/mounts' if not os.access(filename, os.R_OK): msg = 'File not readable {0}' raise CommandExecutionError(msg.format(filename)) with salt.utils.files.fopen(filename) as ifile: for line in ifile: comps = salt.utils.stringutils.to_unicode(line).split() ret[comps[1]] = {'device': comps[0], 'alt_device': _list.get(comps[1], None), 'fstype': comps[2], 'opts': _resolve_user_group_names(comps[3].split(','))} return ret def _active_mounts_aix(ret): ''' List active mounts on AIX systems ''' for line in __salt__['cmd.run_stdout']('mount -p').split('\n'): comps = re.sub(r"\s+", " ", line).split() if comps: if comps[0] == 'node' or comps[0] == '--------': continue comps_len = len(comps) if line.startswith((' ', '\t')): curr_opts = _resolve_user_group_names(comps[6].split(',')) if 7 == comps_len else [] if curr_opts: ret[comps[1]] = {'device': comps[0], 'fstype': comps[2], 'opts': curr_opts} else: ret[comps[1]] = {'device': comps[0], 'fstype': comps[2]} else: curr_opts = _resolve_user_group_names(comps[7].split(',')) if 8 == comps_len else [] if curr_opts: ret[comps[2]] = {'node': comps[0], 'device': comps[1], 'fstype': comps[3], 'opts': curr_opts} else: ret[comps[2]] = {'node': comps[0], 'device': comps[1], 'fstype': comps[3]} return ret def _active_mounts_freebsd(ret): ''' List active mounts on FreeBSD systems ''' for line in __salt__['cmd.run_stdout']('mount -p').split('\n'): comps = re.sub(r"\s+", " ", line).split() ret[comps[1]] = {'device': comps[0], 'fstype': comps[2], 'opts': _resolve_user_group_names(comps[3].split(','))} return ret def _active_mounts_solaris(ret): ''' List active mounts on Solaris systems ''' for line in __salt__['cmd.run_stdout']('mount -v').split('\n'): comps = re.sub(r"\s+", " ", line).split() ret[comps[2]] = {'device': comps[0], 'fstype': comps[4], 'opts': _resolve_user_group_names(comps[5].split('/'))} return ret def _active_mounts_openbsd(ret): ''' List active mounts on OpenBSD systems ''' for line in __salt__['cmd.run_stdout']('mount -v').split('\n'): comps = re.sub(r"\s+", " ", line).split() parens = re.findall(r'\((.*?)\)', line, re.DOTALL) if len(parens) > 1: nod = __salt__['cmd.run_stdout']('ls -l {0}'.format(comps[0])) nod = ' '.join(nod.split()).split(" ") ret[comps[3]] = {'device': comps[0], 'fstype': comps[5], 'opts': _resolve_user_group_names(parens[1].split(", ")), 'major': six.text_type(nod[4].strip(",")), 'minor': six.text_type(nod[5]), 'device_uuid': parens[0]} else: ret[comps[2]] = {'device': comps[0], 'fstype': comps[4], 'opts': _resolve_user_group_names(parens[0].split(", "))} return ret def _active_mounts_darwin(ret): ''' List active mounts on Mac OS systems ''' for line in __salt__['cmd.run_stdout']('mount').split('\n'): comps = re.sub(r"\s+", " ", line).split() parens = re.findall(r'\((.*?)\)', line, re.DOTALL)[0].split(", ") ret[comps[2]] = {'device': comps[0], 'fstype': parens[0], 'opts': _resolve_user_group_names(parens[1:])} return ret def _resolve_user_group_names(opts): ''' Resolve user and group names in related opts ''' name_id_opts = {'uid': 'user.info', 'gid': 'group.info'} for ind, opt in enumerate(opts): if opt.split('=')[0] in name_id_opts: _givenid = opt.split('=')[1] _param = opt.split('=')[0] _id = _givenid if not re.match('[0-9]+$', _givenid): _info = __salt__[name_id_opts[_param]](_givenid) if _info and _param in _info: _id = _info[_param] opts[ind] = _param + '=' + six.text_type(_id) opts[ind] = opts[ind].replace('\\040', '\\ ') return opts def active(extended=False): ''' List the active mounts. CLI Example: .. code-block:: bash salt '*' mount.active ''' ret = {} if __grains__['os'] == 'FreeBSD': _active_mounts_freebsd(ret) elif 'AIX' in __grains__['kernel']: _active_mounts_aix(ret) elif __grains__['kernel'] == 'SunOS': _active_mounts_solaris(ret) elif __grains__['os'] == 'OpenBSD': _active_mounts_openbsd(ret) elif __grains__['os'] in ['MacOS', 'Darwin']: _active_mounts_darwin(ret) else: if extended: try: _active_mountinfo(ret) except CommandExecutionError: _active_mounts(ret) else: _active_mounts(ret) return ret class _fstab_entry(object): ''' Utility class for manipulating fstab entries. Primarily we're parsing, formatting, and comparing lines. Parsing emits dicts expected from fstab() or raises a ValueError. Note: We'll probably want to use os.normpath and os.normcase on 'name' ''' class ParseError(ValueError): ''' Error raised when a line isn't parsible as an fstab entry ''' fstab_keys = ('device', 'name', 'fstype', 'opts', 'dump', 'pass_num') # preserve data format compatibility_keys = ('device', 'name', 'fstype', 'opts', 'dump', 'pass') fstab_format = '{device}\t\t{name}\t{fstype}\t{opts}\t{dump} {pass_num}\n' @classmethod def dict_from_line(cls, line, keys=fstab_keys): if len(keys) != 6: raise ValueError('Invalid key array: {0}'.format(keys)) if line.startswith('#'): raise cls.ParseError("Comment!") comps = line.split() if len(comps) < 4 or len(comps) > 6: raise cls.ParseError("Invalid Entry!") comps.extend(['0'] * (len(keys) - len(comps))) return dict(zip(keys, comps)) @classmethod def from_line(cls, *args, **kwargs): return cls(** cls.dict_from_line(*args, **kwargs)) @classmethod def dict_to_line(cls, entry): return cls.fstab_format.format(**entry) def __str__(self): ''' String value, only works for full repr ''' return self.dict_to_line(self.criteria) def __repr__(self): ''' Always works ''' return repr(self.criteria) def pick(self, keys): ''' Returns an instance with just those keys ''' subset = dict([(key, self.criteria[key]) for key in keys]) return self.__class__(**subset) def __init__(self, **criteria): ''' Store non-empty, non-null values to use as filter ''' items = [key_value for key_value in six.iteritems(criteria) if key_value[1] is not None] items = [(key_value1[0], six.text_type(key_value1[1])) for key_value1 in items] self.criteria = dict(items) @staticmethod def norm_path(path): ''' Resolve equivalent paths equivalently ''' return os.path.normcase(os.path.normpath(path)) def match(self, line): ''' Compare potentially partial criteria against line ''' entry = self.dict_from_line(line) for key, value in six.iteritems(self.criteria): if entry[key] != value: return False return True class _vfstab_entry(object): ''' Utility class for manipulating vfstab entries. Primarily we're parsing, formatting, and comparing lines. Parsing emits dicts expected from fstab() or raises a ValueError. Note: We'll probably want to use os.normpath and os.normcase on 'name' Note: This parses vfstab entries on Solaris like systems #device device mount FS fsck mount mount #to mount to fsck point type pass at boot options # /devices - /devices devfs - no - ''' class ParseError(ValueError): '''Error raised when a line isn't parsible as an fstab entry''' vfstab_keys = ('device', 'device_fsck', 'name', 'fstype', 'pass_fsck', 'mount_at_boot', 'opts') # NOTE: weird formatting to match default spacing on Solaris vfstab_format = '{device:<11} {device_fsck:<3} {name:<19} {fstype:<8} {pass_fsck:<3} {mount_at_boot:<6} {opts}\n' @classmethod def dict_from_line(cls, line): if line.startswith('#'): raise cls.ParseError("Comment!") comps = line.split() if len(comps) != 7: raise cls.ParseError("Invalid Entry!") return dict(zip(cls.vfstab_keys, comps)) @classmethod def from_line(cls, *args, **kwargs): return cls(** cls.dict_from_line(*args, **kwargs)) @classmethod def dict_to_line(cls, entry): return cls.vfstab_format.format(**entry) def __str__(self): ''' String value, only works for full repr ''' return self.dict_to_line(self.criteria) def __repr__(self): ''' Always works ''' return repr(self.criteria) def pick(self, keys): ''' Returns an instance with just those keys ''' subset = dict([(key, self.criteria[key]) for key in keys]) return self.__class__(**subset) def __init__(self, **criteria): ''' Store non-empty, non-null values to use as filter ''' items = [key_value for key_value in six.iteritems(criteria) if key_value[1] is not None] items = [(key_value1[0], six.text_type(key_value1[1])) for key_value1 in items] self.criteria = dict(items) @staticmethod def norm_path(path): ''' Resolve equivalent paths equivalently ''' return os.path.normcase(os.path.normpath(path)) def match(self, line): ''' Compare potentially partial criteria against line ''' entry = self.dict_from_line(line) for key, value in six.iteritems(self.criteria): if entry[key] != value: return False return True class _FileSystemsEntry(object): ''' Utility class for manipulating filesystem entries. Primarily we're parsing, formatting, and comparing lines. Parsing emits dicts expected from fstab() or raises a ValueError. Note: We'll probably want to use os.normpath and os.normcase on 'name' ''' class ParseError(ValueError): ''' Error raised when a line isn't parsible as an fstab entry ''' filesystems_keys = ('device', 'name', 'fstype', 'vfstype', 'opts', 'mount') # preserve data format of filesystems compatibility_keys = ('dev', 'dev', 'name', 'fstype', 'vfstype', 'opts', 'mount', 'type', 'vfs', 'account', 'boot', 'check', 'free', 'nodename', 'quota', 'size', 'vol', 'log') @classmethod def dict_from_lines(cls, lines, keys=filesystems_keys): if len(lines) < 2: raise ValueError('Invalid number of lines: {0}'.format(lines)) if not keys: # if empty force default filesystems_keys keys = _FileSystemsEntry.filesystems_keys elif len(keys) < 6: raise ValueError('Invalid key name array: {0}'.format(keys)) blk_lines = lines orddict = OrderedDict() orddict['name'] = blk_lines[0].split(':')[0].strip() blk_lines.pop(0) for line in blk_lines: if line.startswith('#'): raise cls.ParseError("Comment!") comps = line.split('= ') if len(comps) != 2: raise cls.ParseError("Invalid Entry!") key_name = comps[0].strip() if key_name in keys: orddict[key_name] = comps[1].strip() else: raise ValueError('Invalid name for use in filesystems: {0}'.format(key_name)) return orddict @classmethod def dict_from_cmd_line(cls, ipargs, keys): cmdln_dict = ipargs if keys: for key, value in keys: # ignore unknown or local scope keys if key.startswith('__'): continue if key in _FileSystemsEntry.compatibility_keys: cmdln_dict[key] = value return cmdln_dict @classmethod def from_line(cls, *args, **kwargs): return cls(** cls.dict_from_cmd_line(*args, **kwargs)) @classmethod def dict_to_lines(cls, fsys_dict_entry): entry = fsys_dict_entry strg_out = entry['name'] + ':' + os.linesep for k, v in six.viewitems(entry): if 'name' not in k: strg_out += '\t{0}\t\t= {1}'.format(k, v) + os.linesep strg_out += os.linesep return six.text_type(strg_out) def dict_from_entry(self): ret = OrderedDict() ret[self.criteria['name']] = self.criteria return ret def __str__(self): ''' String value, only works for full repr ''' return self.dict_to_lines(self.criteria) def __repr__(self): ''' Always works ''' return repr(self.criteria) def pick(self, keys): ''' Returns an instance with just those keys ''' subset = dict([(key, self.criteria[key]) for key in keys]) return self.__class__(**subset) def __init__(self, **criteria): ''' Store non-empty, non-null values to use as filter ''' items = [key_value for key_value in six.iteritems(criteria) if key_value[1] is not None] items = [(key_value1[0], six.text_type(key_value1[1])) for key_value1 in items] self.criteria = OrderedDict(items) @staticmethod def norm_path(path): ''' Resolve equivalent paths equivalently ''' return os.path.normcase(os.path.normpath(path)) def match(self, fsys_view): ''' Compare potentially partial criteria against built filesystems entry dictionary ''' evalue_dict = fsys_view[1] for key, value in six.viewitems(self.criteria): if key in evalue_dict: if evalue_dict[key] != value: return False else: return False return True def __getitem__(self, key): ''' Return value for input key ''' return self.criteria[key] def fstab(config='/etc/fstab'): ''' .. versionchanged:: 2016.3.2 List the contents of the fstab CLI Example: .. code-block:: bash salt '*' mount.fstab ''' ret = {} if not os.path.isfile(config): return ret with salt.utils.files.fopen(config) as ifile: for line in ifile: line = salt.utils.stringutils.to_unicode(line) try: if __grains__['kernel'] == 'SunOS': # Note: comments use in default vfstab file! if line[0] == '#': continue entry = _vfstab_entry.dict_from_line( line) else: entry = _fstab_entry.dict_from_line( line, _fstab_entry.compatibility_keys) entry['opts'] = entry['opts'].split(',') while entry['name'] in ret: entry['name'] += '_' ret[entry.pop('name')] = entry except _fstab_entry.ParseError: pass except _vfstab_entry.ParseError: pass return ret def vfstab(config='/etc/vfstab'): ''' .. versionadded:: 2016.3.2 List the contents of the vfstab CLI Example: .. code-block:: bash salt '*' mount.vfstab ''' # NOTE: vfstab is a wrapper for fstab return fstab(config) def rm_fstab(name, device, config='/etc/fstab'): ''' .. versionchanged:: 2016.3.2 Remove the mount point from the fstab CLI Example: .. code-block:: bash salt '*' mount.rm_fstab /mnt/foo /dev/sdg ''' modified = False if __grains__['kernel'] == 'SunOS': criteria = _vfstab_entry(name=name, device=device) else: criteria = _fstab_entry(name=name, device=device) lines = [] try: with salt.utils.files.fopen(config, 'r') as ifile: for line in ifile: line = salt.utils.stringutils.to_unicode(line) try: if criteria.match(line): modified = True else: lines.append(line) except _fstab_entry.ParseError: lines.append(line) except _vfstab_entry.ParseError: lines.append(line) except (IOError, OSError) as exc: msg = "Couldn't read from {0}: {1}" raise CommandExecutionError(msg.format(config, exc)) if modified: try: with salt.utils.files.fopen(config, 'wb') as ofile: ofile.writelines(salt.utils.data.encode(lines)) except (IOError, OSError) as exc: msg = "Couldn't write to {0}: {1}" raise CommandExecutionError(msg.format(config, exc)) # Note: not clear why we always return 'True' # --just copying previous behavior at this point... return True def rm_vfstab(name, device, config='/etc/vfstab'): ''' .. versionadded:: 2016.3.2 Remove the mount point from the vfstab CLI Example: .. code-block:: bash salt '*' mount.rm_vfstab /mnt/foo /device/c0t0d0p0 ''' ## NOTE: rm_vfstab is a wrapper for rm_fstab return rm_fstab(name, device, config) def set_fstab( name, device, fstype, opts='defaults', dump=0, pass_num=0, config='/etc/fstab', test=False, match_on='auto', **kwargs): ''' Verify that this mount is represented in the fstab, change the mount to match the data passed, or add the mount if it is not present. CLI Example: .. code-block:: bash salt '*' mount.set_fstab /mnt/foo /dev/sdz1 ext4 ''' # Fix the opts type if it is a list if isinstance(opts, list): opts = ','.join(opts) # preserve arguments for updating entry_args = { 'name': name, 'device': device.replace('\\ ', '\\040'), 'fstype': fstype, 'opts': opts.replace('\\ ', '\\040'), 'dump': dump, 'pass_num': pass_num, } lines = [] ret = None # Transform match_on into list--items will be checked later if isinstance(match_on, list): pass elif not isinstance(match_on, six.string_types): msg = 'match_on must be a string or list of strings' raise CommandExecutionError(msg) elif match_on == 'auto': # Try to guess right criteria for auto.... # NOTE: missing some special fstypes here specialFSes = frozenset([ 'none', 'tmpfs', 'sysfs', 'proc', 'fusectl', 'debugfs', 'securityfs', 'devtmpfs', 'cgroup', 'btrfs']) if fstype in specialFSes: match_on = ['name'] else: match_on = ['device'] else: match_on = [match_on] # generate entry and criteria objects, handle invalid keys in match_on entry = _fstab_entry(**entry_args) try: criteria = entry.pick(match_on) except KeyError: filterFn = lambda key: key not in _fstab_entry.fstab_keys invalid_keys = filter(filterFn, match_on) msg = 'Unrecognized keys in match_on: "{0}"'.format(invalid_keys) raise CommandExecutionError(msg) # parse file, use ret to cache status if not os.path.isfile(config): raise CommandExecutionError('Bad config file "{0}"'.format(config)) try: with salt.utils.files.fopen(config, 'r') as ifile: for line in ifile: line = salt.utils.stringutils.to_unicode(line) try: if criteria.match(line): # Note: If ret isn't None here, # we've matched multiple lines ret = 'present' if entry.match(line): lines.append(line) else: ret = 'change' lines.append(six.text_type(entry)) else: lines.append(line) except _fstab_entry.ParseError: lines.append(line) except (IOError, OSError) as exc: msg = 'Couldn\'t read from {0}: {1}' raise CommandExecutionError(msg.format(config, exc)) # add line if not present or changed if ret is None: lines.append(six.text_type(entry)) ret = 'new' if ret != 'present': # ret in ['new', 'change']: if not salt.utils.args.test_mode(test=test, **kwargs): try: with salt.utils.files.fopen(config, 'wb') as ofile: # The line was changed, commit it! ofile.writelines(salt.utils.data.encode(lines)) except (IOError, OSError): msg = 'File not writable {0}' raise CommandExecutionError(msg.format(config)) return ret def set_vfstab( name, device, fstype, opts='-', device_fsck='-', pass_fsck='-', mount_at_boot='yes', config='/etc/vfstab', test=False, match_on='auto', **kwargs): ''' ..verionadded:: 2016.3.2 Verify that this mount is represented in the fstab, change the mount to match the data passed, or add the mount if it is not present. CLI Example: .. code-block:: bash salt '*' mount.set_vfstab /mnt/foo /device/c0t0d0p0 ufs ''' # Fix the opts type if it is a list if isinstance(opts, list): opts = ','.join(opts) # Map unknown values for mount_at_boot to no if mount_at_boot != 'yes': mount_at_boot = 'no' # preserve arguments for updating entry_args = { 'name': name, 'device': device, 'fstype': fstype, 'opts': opts, 'device_fsck': device_fsck, 'pass_fsck': pass_fsck, 'mount_at_boot': mount_at_boot, } lines = [] ret = None # Transform match_on into list--items will be checked later if isinstance(match_on, list): pass elif not isinstance(match_on, six.string_types): msg = 'match_on must be a string or list of strings' raise CommandExecutionError(msg) elif match_on == 'auto': # Try to guess right criteria for auto.... # NOTE: missing some special fstypes here specialFSes = frozenset([ 'devfs', 'proc', 'ctfs', 'objfs', 'sharefs', 'fs', 'tmpfs']) if fstype in specialFSes: match_on = ['name'] else: match_on = ['device'] else: match_on = [match_on] # generate entry and criteria objects, handle invalid keys in match_on entry = _vfstab_entry(**entry_args) try: criteria = entry.pick(match_on) except KeyError: filterFn = lambda key: key not in _vfstab_entry.vfstab_keys invalid_keys = filter(filterFn, match_on) msg = 'Unrecognized keys in match_on: "{0}"'.format(invalid_keys) raise CommandExecutionError(msg) # parse file, use ret to cache status if not os.path.isfile(config): raise CommandExecutionError('Bad config file "{0}"'.format(config)) try: with salt.utils.files.fopen(config, 'r') as ifile: for line in ifile: line = salt.utils.stringutils.to_unicode(line) try: if criteria.match(line): # Note: If ret isn't None here, # we've matched multiple lines ret = 'present' if entry.match(line): lines.append(line) else: ret = 'change' lines.append(six.text_type(entry)) else: lines.append(line) except _vfstab_entry.ParseError: lines.append(line) except (IOError, OSError) as exc: msg = 'Couldn\'t read from {0}: {1}' raise CommandExecutionError(msg.format(config, exc)) # add line if not present or changed if ret is None: lines.append(six.text_type(entry)) ret = 'new' if ret != 'present': # ret in ['new', 'change']: if not salt.utils.args.test_mode(test=test, **kwargs): try: with salt.utils.files.fopen(config, 'wb') as ofile: # The line was changed, commit it! ofile.writelines(salt.utils.data.encode(lines)) except (IOError, OSError): msg = 'File not writable {0}' raise CommandExecutionError(msg.format(config)) return ret def rm_automaster(name, device, config='/etc/auto_salt'): ''' Remove the mount point from the auto_master CLI Example: .. code-block:: bash salt '*' mount.rm_automaster /mnt/foo /dev/sdg ''' contents = automaster(config) if name not in contents: return True # The entry is present, get rid of it lines = [] try: with salt.utils.files.fopen(config, 'r') as ifile: for line in ifile: line = salt.utils.stringutils.to_unicode(line) if line.startswith('#'): # Commented lines.append(line) continue if not line.strip(): # Blank line lines.append(line) continue comps = line.split() if len(comps) != 3: # Invalid entry lines.append(line) continue comps = line.split() prefix = "/.." name_chk = comps[0].replace(prefix, "") device_fmt = comps[2].split(":") if device: if name_chk == name and device_fmt[1] == device: continue else: if name_chk == name: continue lines.append(line) except (IOError, OSError) as exc: msg = "Couldn't read from {0}: {1}" raise CommandExecutionError(msg.format(config, exc)) try: with salt.utils.files.fopen(config, 'wb') as ofile: ofile.writelines(salt.utils.data.encode(lines)) except (IOError, OSError) as exc: msg = "Couldn't write to {0}: {1}" raise CommandExecutionError(msg.format(config, exc)) # Update automount __salt__['cmd.run']('automount -cv') return True def automaster(config='/etc/auto_salt'): ''' List the contents of the auto master CLI Example: .. code-block:: bash salt '*' mount.automaster ''' ret = {} if not os.path.isfile(config): return ret with salt.utils.files.fopen(config) as ifile: for line in ifile: line = salt.utils.stringutils.to_unicode(line) if line.startswith('#'): # Commented continue if not line.strip(): # Blank line continue comps = line.split() if len(comps) != 3: # Invalid entry continue prefix = "/.." name = comps[0].replace(prefix, "") device_fmt = comps[2].split(":") opts = comps[1].split(',') ret[name] = {'device': device_fmt[1], 'fstype': opts[0], 'opts': opts[1:]} return ret def mount(name, device, mkmnt=False, fstype='', opts='defaults', user=None, util='mount'): ''' Mount a device CLI Example: .. code-block:: bash salt '*' mount.mount /mnt/foo /dev/sdz1 True ''' if util != 'mount': # This functionality used to live in img.mount_image if util == 'guestfs': return __salt__['guestfs.mount'](name, root=device) elif util == 'qemu_nbd': mnt = __salt__['qemu_nbd.init'](name, device) if not mnt: return False first = next(six.iterkeys(mnt)) __context__['img.mnt_{0}'.format(first)] = mnt return first return False # Darwin doesn't expect defaults when mounting without other options if 'defaults' in opts and __grains__['os'] in ['MacOS', 'Darwin', 'AIX']: opts = None if isinstance(opts, six.string_types): opts = opts.split(',') if not os.path.exists(name) and mkmnt: __salt__['file.mkdir'](name, user=user) args = '' if opts is not None: lopts = ','.join(opts) args = '-o {0}'.format(lopts) if fstype: # use of fstype on AIX differs from typical Linux use of -t # functionality AIX uses -v vfsname, -t fstype mounts all with # fstype in /etc/filesystems if 'AIX' in __grains__['os']: args += ' -v {0}'.format(fstype) elif 'solaris' in __grains__['os'].lower(): args += ' -F {0}'.format(fstype) else: args += ' -t {0}'.format(fstype) cmd = 'mount {0} {1} {2} '.format(args, device, name) out = __salt__['cmd.run_all'](cmd, runas=user, python_shell=False) if out['retcode']: return out['stderr'] return True def remount(name, device, mkmnt=False, fstype='', opts='defaults', user=None): ''' Attempt to remount a device, if the device is not already mounted, mount is called CLI Example: .. code-block:: bash salt '*' mount.remount /mnt/foo /dev/sdz1 True ''' force_mount = False if __grains__['os'] in ['MacOS', 'Darwin']: if opts == 'defaults': opts = 'noowners' if fstype == 'smbfs': force_mount = True if 'AIX' in __grains__['os']: if opts == 'defaults': opts = [] if isinstance(opts, six.string_types): opts = opts.split(',') mnts = active() if name in mnts: # The mount point is mounted, attempt to remount it with the given data if 'remount' not in opts and __grains__['os'] not in ['OpenBSD', 'MacOS', 'Darwin']: opts.append('remount') if force_mount: # We need to force the mount but first we should unmount umount(name, device, user=user) lopts = ','.join(opts) args = '-o {0}'.format(lopts) if fstype: # use of fstype on AIX differs from typical Linux use of # -t functionality AIX uses -v vfsname, -t fstype mounts # all with fstype in /etc/filesystems if 'AIX' in __grains__['os']: args += ' -v {0}'.format(fstype) elif 'solaris' in __grains__['os'].lower(): args += ' -F {0}'.format(fstype) else: args += ' -t {0}'.format(fstype) if __grains__['os'] not in ['OpenBSD', 'MacOS', 'Darwin'] or force_mount: cmd = 'mount {0} {1} {2} '.format(args, device, name) else: cmd = 'mount -u {0} {1} {2} '.format(args, device, name) out = __salt__['cmd.run_all'](cmd, runas=user, python_shell=False) if out['retcode']: return out['stderr'] return True # Mount a filesystem that isn't already return mount(name, device, mkmnt, fstype, opts, user=user) def umount(name, device=None, user=None, util='mount'): ''' Attempt to unmount a device by specifying the directory it is mounted on CLI Example: .. code-block:: bash salt '*' mount.umount /mnt/foo .. versionadded:: 2015.5.0 .. code-block:: bash salt '*' mount.umount /mnt/foo /dev/xvdc1 ''' if util != 'mount': # This functionality used to live in img.umount_image if 'qemu_nbd.clear' in __salt__: if 'img.mnt_{0}'.format(name) in __context__: __salt__['qemu_nbd.clear'](__context__['img.mnt_{0}'.format(name)]) return mnts = active() if name not in mnts: return "{0} does not have anything mounted".format(name) if not device: cmd = 'umount {0}'.format(name) else: cmd = 'umount {0}'.format(device) out = __salt__['cmd.run_all'](cmd, runas=user, python_shell=False) if out['retcode']: return out['stderr'] return True def is_fuse_exec(cmd): ''' Returns true if the command passed is a fuse mountable application. CLI Example: .. code-block:: bash salt '*' mount.is_fuse_exec sshfs ''' cmd_path = salt.utils.path.which(cmd) # No point in running ldd on a command that doesn't exist if not cmd_path: return False elif not salt.utils.path.which('ldd'): raise CommandNotFoundError('ldd') out = __salt__['cmd.run']('ldd {0}'.format(cmd_path), python_shell=False) return 'libfuse' in out def swaps(): ''' Return a dict containing information on active swap .. versionchanged:: 2016.3.2 CLI Example: .. code-block:: bash salt '*' mount.swaps ''' ret = {} if __grains__['kernel'] == 'SunOS': for line in __salt__['cmd.run_stdout']('swap -l').splitlines(): if line.startswith('swapfile'): continue comps = line.split() ret[comps[0]] = {'type': 'device' if comps[0].startswith(('/dev', 'swap')) else 'file', 'size': int(comps[3]), 'used': (int(comps[3]) - int(comps[4])), 'priority': '-'} elif 'AIX' in __grains__['kernel']: for line in __salt__['cmd.run_stdout']('swap -l').splitlines(): if line.startswith('device'): continue comps = line.split() # AIX uses MB for units ret[comps[0]] = {'type': 'device', 'size': int(comps[3][:-2]) * 1024, 'used': (int(comps[3][:-2]) - int(comps[4][:-2])) * 1024, 'priority': '-'} elif __grains__['os'] != 'OpenBSD': with salt.utils.files.fopen('/proc/swaps') as fp_: for line in fp_: line = salt.utils.stringutils.to_unicode(line) if line.startswith('Filename'): continue comps = line.split() ret[comps[0]] = {'type': comps[1], 'size': comps[2], 'used': comps[3], 'priority': comps[4]} else: for line in __salt__['cmd.run_stdout']('swapctl -kl').splitlines(): if line.startswith(('Device', 'Total')): continue swap_type = "file" comps = line.split() if comps[0].startswith('/dev/'): swap_type = "partition" ret[comps[0]] = {'type': swap_type, 'size': comps[1], 'used': comps[2], 'priority': comps[5]} return ret def swapon(name, priority=None): ''' Activate a swap disk .. versionchanged:: 2016.3.2 CLI Example: .. code-block:: bash salt '*' mount.swapon /root/swapfile ''' ret = {} on_ = swaps() if name in on_: ret['stats'] = on_[name] ret['new'] = False return ret if __grains__['kernel'] == 'SunOS': if __grains__['virtual'] != 'zone': __salt__['cmd.run']('swap -a {0}'.format(name), python_shell=False) else: return False else: cmd = 'swapon {0}'.format(name) if priority and 'AIX' not in __grains__['kernel']: cmd += ' -p {0}'.format(priority) __salt__['cmd.run'](cmd, python_shell=False) on_ = swaps() if name in on_: ret['stats'] = on_[name] ret['new'] = True return ret return ret def swapoff(name): ''' Deactivate a named swap mount .. versionchanged:: 2016.3.2 CLI Example: .. code-block:: bash salt '*' mount.swapoff /root/swapfile ''' on_ = swaps() if name in on_: if __grains__['kernel'] == 'SunOS': if __grains__['virtual'] != 'zone': __salt__['cmd.run']('swap -a {0}'.format(name), python_shell=False) else: return False elif __grains__['os'] != 'OpenBSD': __salt__['cmd.run']('swapoff {0}'.format(name), python_shell=False) else: __salt__['cmd.run']('swapctl -d {0}'.format(name), python_shell=False) on_ = swaps() if name in on_: return False return True return None def is_mounted(name): ''' .. versionadded:: 2014.7.0 Provide information if the path is mounted CLI Example: .. code-block:: bash salt '*' mount.is_mounted /mnt/share ''' active_ = active() if name in active_: return True else: return False def read_mount_cache(name): ''' .. versionadded:: 2018.3.0 Provide information if the path is mounted CLI Example: .. code-block:: bash salt '*' mount.read_mount_cache /mnt/share ''' cache = salt.utils.mount.read_cache(__opts__) if cache: if 'mounts' in cache and cache['mounts']: if name in cache['mounts']: return cache['mounts'][name] return {} def write_mount_cache(real_name, device, mkmnt, fstype, mount_opts): ''' .. versionadded:: 2018.3.0 Provide information if the path is mounted :param real_name: The real name of the mount point where the device is mounted. :param device: The device that is being mounted. :param mkmnt: Whether or not the mount point should be created. :param fstype: The file system that is used. :param mount_opts: Additional options used when mounting the device. :return: Boolean if message was sent successfully. CLI Example: .. code-block:: bash salt '*' mount.write_mount_cache /mnt/share /dev/sda1 False ext4 defaults,nosuid ''' cache = salt.utils.mount.read_cache(__opts__) if not cache: cache = {} cache['mounts'] = {} else: if 'mounts' not in cache: cache['mounts'] = {} cache['mounts'][real_name] = {'device': device, 'fstype': fstype, 'mkmnt': mkmnt, 'opts': mount_opts} cache_write = salt.utils.mount.write_cache(cache, __opts__) if cache_write: return True else: raise CommandExecutionError('Unable to write mount cache.') def delete_mount_cache(real_name): ''' .. versionadded:: 2018.3.0 Provide information if the path is mounted CLI Example: .. code-block:: bash salt '*' mount.delete_mount_cache /mnt/share ''' cache = salt.utils.mount.read_cache(__opts__) if cache: if 'mounts' in cache: if real_name in cache['mounts']: del cache['mounts'][real_name] cache_write = salt.utils.mount.write_cache(cache, __opts__) if not cache_write: raise CommandExecutionError('Unable to write mount cache.') return True def _filesystems(config='/etc/filesystems', leading_key=True): ''' Return the contents of the filesystems in an OrderedDict config File containing filesystem infomation leading_key True return dictionary keyed by 'name' and value as dictionary with other keys, values (name excluded) OrderedDict({ '/dir' : OrderedDict({'dev': '/dev/hd8', .... }})) False return dictionary keyed by 'name' and value as dictionary with all keys, values (name included) OrderedDict({ '/dir' : OrderedDict({'name': '/dir', 'dev': '/dev/hd8', ... })}) ''' ret = OrderedDict() lines = [] parsing_block = False if not os.path.isfile(config) or 'AIX' not in __grains__['kernel']: return ret # read in block of filesystems, block starts with '/' till empty line with salt.utils.files.fopen(config) as ifile: for line in ifile: line = salt.utils.stringutils.to_unicode(line) # skip till first entry if not line.startswith('/') and not parsing_block: continue if line.startswith('/'): parsing_block = True lines.append(line) elif not line.split(): parsing_block = False try: entry = _FileSystemsEntry.dict_from_lines( lines, _FileSystemsEntry.compatibility_keys) lines = [] if 'opts' in entry: entry['opts'] = entry['opts'].split(',') while entry['name'] in ret: entry['name'] += '_' if leading_key: ret[entry.pop('name')] = entry else: ret[entry['name']] = entry except _FileSystemsEntry.ParseError: pass else: lines.append(line) return ret def filesystems(config='/etc/filesystems'): ''' .. versionadded:: 2018.3.3 List the contents of the filesystems CLI Example: .. code-block:: bash salt '*' mount.filesystems ''' ret = {} if 'AIX' not in __grains__['kernel']: return ret ret_dict = _filesystems(config) if ret_dict: ret_key = next(iter(ret_dict.keys())) ret = {ret_key: dict(ret_dict[ret_key])} return ret def set_filesystems( name, device, vfstype, opts='-', mount='true', config='/etc/filesystems', test=False, match_on='auto', **kwargs): ''' .. versionadded:: 2018.3.3 Verify that this mount is represented in the filesystems, change the mount to match the data passed, or add the mount if it is not present on AIX Provide information if the path is mounted :param name: The name of the mount point where the device is mounted. :param device: The device that is being mounted. :param vfstype: The file system that is used (AIX has two fstypes, fstype and vfstype - similar to Linux fstype) :param opts: Additional options used when mounting the device. :param mount: Mount if not mounted, default True. :param config: Configuration file, default /etc/filesystems. :param match: File systems type to match on, default auto CLI Example: .. code-block:: bash salt '*' mount.set_filesystems /mnt/foo /dev/sdz1 jfs2 ''' # Fix the opts type if it is a list if isinstance(opts, list): opts = ','.join(opts) # preserve arguments for updating entry_args = { 'name': name, 'dev': device.replace('\\ ', '\\040'), 'vfstype': vfstype, 'opts': opts, 'mount': mount, } view_lines = [] ret = None if 'AIX' not in __grains__['kernel']: return ret # Transform match_on into list--items will be checked later if isinstance(match_on, list): pass elif not isinstance(match_on, six.string_types): raise CommandExecutionError('match_on must be a string or list of strings') elif match_on == 'auto': # Try to guess right criteria for auto.... # added IBM types from sys/vmount.h after btrfs # NOTE: missing some special fstypes here specialFSes = frozenset([ 'none', 'tmpfs', 'sysfs', 'proc', 'fusectl', 'debugfs', 'securityfs', 'devtmpfs', 'cgroup', 'btrfs', 'cdrfs', 'procfs', 'jfs', 'jfs2', 'nfs', 'sfs', 'nfs3', 'cachefs', 'udfs', 'cifs', 'namefs', 'pmemfs', 'ahafs', 'nfs4', 'autofs', 'stnfs']) if vfstype in specialFSes: match_on = ['name'] else: match_on = ['dev'] else: match_on = [match_on] # generate entry and criteria objects, handle invalid keys in match_on entry_ip = _FileSystemsEntry.from_line(entry_args, kwargs) try: criteria = entry_ip.pick(match_on) except KeyError: filterFn = lambda key: key not in _FileSystemsEntry.compatibility_keys invalid_keys = filter(filterFn, match_on) raise CommandExecutionError('Unrecognized keys in match_on: "{0}"'.format(invalid_keys)) # parse file, use ret to cache status if not os.path.isfile(config): raise CommandExecutionError('Bad config file "{0}"'.format(config)) # read in block of filesystem, block starts with '/' till empty line try: fsys_filedict = _filesystems(config, False) for fsys_view in six.viewitems(fsys_filedict): if criteria.match(fsys_view): ret = 'present' if entry_ip.match(fsys_view): view_lines.append(fsys_view) else: ret = 'change' kv = entry_ip['name'] view_lines.append((kv, entry_ip)) else: view_lines.append(fsys_view) except (IOError, OSError) as exc: raise CommandExecutionError('Couldn\'t read from {0}: {1}'.format(config, exc)) # add line if not present or changed if ret is None: for dict_view in six.viewitems(entry_ip.dict_from_entry()): view_lines.append(dict_view) ret = 'new' if ret != 'present': # ret in ['new', 'change']: try: with salt.utils.files.fopen(config, 'wb') as ofile: # The line was changed, commit it! for fsys_view in view_lines: entry = fsys_view[1] mystrg = _FileSystemsEntry.dict_to_lines(entry) ofile.writelines(salt.utils.data.encode(mystrg)) except (IOError, OSError): raise CommandExecutionError('File not writable {0}'.format(config)) return ret def rm_filesystems(name, device, config='/etc/filesystems'): ''' .. versionadded:: 2018.3.3 Remove the mount point from the filesystems CLI Example: .. code-block:: bash salt '*' mount.rm_filesystems /mnt/foo /dev/sdg ''' modified = False view_lines = [] if 'AIX' not in __grains__['kernel']: return modified criteria = _FileSystemsEntry(name=name, dev=device) try: fsys_filedict = _filesystems(config, False) for fsys_view in six.viewitems(fsys_filedict): try: if criteria.match(fsys_view): modified = True else: view_lines.append(fsys_view) except _FileSystemsEntry.ParseError: view_lines.append(fsys_view) except (IOError, OSError) as exc: raise CommandExecutionError("Couldn't read from {0}: {1}".format(config, exc)) if modified: try: with salt.utils.files.fopen(config, 'wb') as ofile: for fsys_view in view_lines: entry = fsys_view[1] mystrg = _FileSystemsEntry.dict_to_lines(entry) ofile.writelines(salt.utils.data.encode(mystrg)) except (IOError, OSError) as exc: raise CommandExecutionError("Couldn't write to {0}: {1}".format(config, exc)) return modified
saltstack/salt
salt/modules/mount.py
automaster
python
def automaster(config='/etc/auto_salt'): ''' List the contents of the auto master CLI Example: .. code-block:: bash salt '*' mount.automaster ''' ret = {} if not os.path.isfile(config): return ret with salt.utils.files.fopen(config) as ifile: for line in ifile: line = salt.utils.stringutils.to_unicode(line) if line.startswith('#'): # Commented continue if not line.strip(): # Blank line continue comps = line.split() if len(comps) != 3: # Invalid entry continue prefix = "/.." name = comps[0].replace(prefix, "") device_fmt = comps[2].split(":") opts = comps[1].split(',') ret[name] = {'device': device_fmt[1], 'fstype': opts[0], 'opts': opts[1:]} return ret
List the contents of the auto master CLI Example: .. code-block:: bash salt '*' mount.automaster
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/mount.py#L1139-L1174
[ "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 -*- ''' Salt module to manage Unix mounts and the fstab file ''' # Import python libs from __future__ import absolute_import, print_function, unicode_literals import os import re import logging # Import salt libs import salt.utils.args import salt.utils.data import salt.utils.files import salt.utils.path import salt.utils.platform import salt.utils.mount import salt.utils.stringutils from salt.utils.odict import OrderedDict from salt.exceptions import CommandNotFoundError, CommandExecutionError # Import 3rd-party libs from salt.ext import six from salt.ext.six.moves import filter, zip # pylint: disable=import-error,redefined-builtin # Set up logger log = logging.getLogger(__name__) # Define the module's virtual name __virtualname__ = 'mount' def __virtual__(): ''' Only load on POSIX-like systems ''' # Disable on Windows, a specific file module exists: if salt.utils.platform.is_windows(): return (False, 'The mount module cannot be loaded: not a POSIX-like system.') return True def _list_mounts(): ret = {} if __grains__['os'] in ['MacOS', 'Darwin']: mounts = __salt__['cmd.run_stdout']('mount') else: mounts = __salt__['cmd.run_stdout']('mount -l') for line in mounts.split('\n'): comps = re.sub(r"\s+", " ", line).split() if len(comps) >= 3: ret[comps[2]] = comps[0] return ret def _active_mountinfo(ret): _list = _list_mounts() filename = '/proc/self/mountinfo' if not os.access(filename, os.R_OK): msg = 'File not readable {0}' raise CommandExecutionError(msg.format(filename)) if 'disk.blkid' not in __context__: __context__['disk.blkid'] = __salt__['disk.blkid']() blkid_info = __context__['disk.blkid'] with salt.utils.files.fopen(filename) as ifile: for line in ifile: comps = salt.utils.stringutils.to_unicode(line).split() device = comps[2].split(':') # each line can have any number of # optional parameters, we use the # location of the separator field to # determine the location of the elements # after it. _sep = comps.index('-') device_name = comps[_sep + 2] device_uuid = None device_label = None if device_name: device_uuid = blkid_info.get(device_name, {}).get('UUID') device_uuid = device_uuid and device_uuid.lower() device_label = blkid_info.get(device_name, {}).get('LABEL') ret[comps[4]] = {'mountid': comps[0], 'parentid': comps[1], 'major': device[0], 'minor': device[1], 'root': comps[3], 'opts': _resolve_user_group_names(comps[5].split(',')), 'fstype': comps[_sep + 1], 'device': device_name.replace('\\040', '\\ '), 'alt_device': _list.get(comps[4], None), 'superopts': _resolve_user_group_names(comps[_sep + 3].split(',')), 'device_uuid': device_uuid, 'device_label': device_label} return ret def _active_mounts(ret): ''' List active mounts on Linux systems ''' _list = _list_mounts() filename = '/proc/self/mounts' if not os.access(filename, os.R_OK): msg = 'File not readable {0}' raise CommandExecutionError(msg.format(filename)) with salt.utils.files.fopen(filename) as ifile: for line in ifile: comps = salt.utils.stringutils.to_unicode(line).split() ret[comps[1]] = {'device': comps[0], 'alt_device': _list.get(comps[1], None), 'fstype': comps[2], 'opts': _resolve_user_group_names(comps[3].split(','))} return ret def _active_mounts_aix(ret): ''' List active mounts on AIX systems ''' for line in __salt__['cmd.run_stdout']('mount -p').split('\n'): comps = re.sub(r"\s+", " ", line).split() if comps: if comps[0] == 'node' or comps[0] == '--------': continue comps_len = len(comps) if line.startswith((' ', '\t')): curr_opts = _resolve_user_group_names(comps[6].split(',')) if 7 == comps_len else [] if curr_opts: ret[comps[1]] = {'device': comps[0], 'fstype': comps[2], 'opts': curr_opts} else: ret[comps[1]] = {'device': comps[0], 'fstype': comps[2]} else: curr_opts = _resolve_user_group_names(comps[7].split(',')) if 8 == comps_len else [] if curr_opts: ret[comps[2]] = {'node': comps[0], 'device': comps[1], 'fstype': comps[3], 'opts': curr_opts} else: ret[comps[2]] = {'node': comps[0], 'device': comps[1], 'fstype': comps[3]} return ret def _active_mounts_freebsd(ret): ''' List active mounts on FreeBSD systems ''' for line in __salt__['cmd.run_stdout']('mount -p').split('\n'): comps = re.sub(r"\s+", " ", line).split() ret[comps[1]] = {'device': comps[0], 'fstype': comps[2], 'opts': _resolve_user_group_names(comps[3].split(','))} return ret def _active_mounts_solaris(ret): ''' List active mounts on Solaris systems ''' for line in __salt__['cmd.run_stdout']('mount -v').split('\n'): comps = re.sub(r"\s+", " ", line).split() ret[comps[2]] = {'device': comps[0], 'fstype': comps[4], 'opts': _resolve_user_group_names(comps[5].split('/'))} return ret def _active_mounts_openbsd(ret): ''' List active mounts on OpenBSD systems ''' for line in __salt__['cmd.run_stdout']('mount -v').split('\n'): comps = re.sub(r"\s+", " ", line).split() parens = re.findall(r'\((.*?)\)', line, re.DOTALL) if len(parens) > 1: nod = __salt__['cmd.run_stdout']('ls -l {0}'.format(comps[0])) nod = ' '.join(nod.split()).split(" ") ret[comps[3]] = {'device': comps[0], 'fstype': comps[5], 'opts': _resolve_user_group_names(parens[1].split(", ")), 'major': six.text_type(nod[4].strip(",")), 'minor': six.text_type(nod[5]), 'device_uuid': parens[0]} else: ret[comps[2]] = {'device': comps[0], 'fstype': comps[4], 'opts': _resolve_user_group_names(parens[0].split(", "))} return ret def _active_mounts_darwin(ret): ''' List active mounts on Mac OS systems ''' for line in __salt__['cmd.run_stdout']('mount').split('\n'): comps = re.sub(r"\s+", " ", line).split() parens = re.findall(r'\((.*?)\)', line, re.DOTALL)[0].split(", ") ret[comps[2]] = {'device': comps[0], 'fstype': parens[0], 'opts': _resolve_user_group_names(parens[1:])} return ret def _resolve_user_group_names(opts): ''' Resolve user and group names in related opts ''' name_id_opts = {'uid': 'user.info', 'gid': 'group.info'} for ind, opt in enumerate(opts): if opt.split('=')[0] in name_id_opts: _givenid = opt.split('=')[1] _param = opt.split('=')[0] _id = _givenid if not re.match('[0-9]+$', _givenid): _info = __salt__[name_id_opts[_param]](_givenid) if _info and _param in _info: _id = _info[_param] opts[ind] = _param + '=' + six.text_type(_id) opts[ind] = opts[ind].replace('\\040', '\\ ') return opts def active(extended=False): ''' List the active mounts. CLI Example: .. code-block:: bash salt '*' mount.active ''' ret = {} if __grains__['os'] == 'FreeBSD': _active_mounts_freebsd(ret) elif 'AIX' in __grains__['kernel']: _active_mounts_aix(ret) elif __grains__['kernel'] == 'SunOS': _active_mounts_solaris(ret) elif __grains__['os'] == 'OpenBSD': _active_mounts_openbsd(ret) elif __grains__['os'] in ['MacOS', 'Darwin']: _active_mounts_darwin(ret) else: if extended: try: _active_mountinfo(ret) except CommandExecutionError: _active_mounts(ret) else: _active_mounts(ret) return ret class _fstab_entry(object): ''' Utility class for manipulating fstab entries. Primarily we're parsing, formatting, and comparing lines. Parsing emits dicts expected from fstab() or raises a ValueError. Note: We'll probably want to use os.normpath and os.normcase on 'name' ''' class ParseError(ValueError): ''' Error raised when a line isn't parsible as an fstab entry ''' fstab_keys = ('device', 'name', 'fstype', 'opts', 'dump', 'pass_num') # preserve data format compatibility_keys = ('device', 'name', 'fstype', 'opts', 'dump', 'pass') fstab_format = '{device}\t\t{name}\t{fstype}\t{opts}\t{dump} {pass_num}\n' @classmethod def dict_from_line(cls, line, keys=fstab_keys): if len(keys) != 6: raise ValueError('Invalid key array: {0}'.format(keys)) if line.startswith('#'): raise cls.ParseError("Comment!") comps = line.split() if len(comps) < 4 or len(comps) > 6: raise cls.ParseError("Invalid Entry!") comps.extend(['0'] * (len(keys) - len(comps))) return dict(zip(keys, comps)) @classmethod def from_line(cls, *args, **kwargs): return cls(** cls.dict_from_line(*args, **kwargs)) @classmethod def dict_to_line(cls, entry): return cls.fstab_format.format(**entry) def __str__(self): ''' String value, only works for full repr ''' return self.dict_to_line(self.criteria) def __repr__(self): ''' Always works ''' return repr(self.criteria) def pick(self, keys): ''' Returns an instance with just those keys ''' subset = dict([(key, self.criteria[key]) for key in keys]) return self.__class__(**subset) def __init__(self, **criteria): ''' Store non-empty, non-null values to use as filter ''' items = [key_value for key_value in six.iteritems(criteria) if key_value[1] is not None] items = [(key_value1[0], six.text_type(key_value1[1])) for key_value1 in items] self.criteria = dict(items) @staticmethod def norm_path(path): ''' Resolve equivalent paths equivalently ''' return os.path.normcase(os.path.normpath(path)) def match(self, line): ''' Compare potentially partial criteria against line ''' entry = self.dict_from_line(line) for key, value in six.iteritems(self.criteria): if entry[key] != value: return False return True class _vfstab_entry(object): ''' Utility class for manipulating vfstab entries. Primarily we're parsing, formatting, and comparing lines. Parsing emits dicts expected from fstab() or raises a ValueError. Note: We'll probably want to use os.normpath and os.normcase on 'name' Note: This parses vfstab entries on Solaris like systems #device device mount FS fsck mount mount #to mount to fsck point type pass at boot options # /devices - /devices devfs - no - ''' class ParseError(ValueError): '''Error raised when a line isn't parsible as an fstab entry''' vfstab_keys = ('device', 'device_fsck', 'name', 'fstype', 'pass_fsck', 'mount_at_boot', 'opts') # NOTE: weird formatting to match default spacing on Solaris vfstab_format = '{device:<11} {device_fsck:<3} {name:<19} {fstype:<8} {pass_fsck:<3} {mount_at_boot:<6} {opts}\n' @classmethod def dict_from_line(cls, line): if line.startswith('#'): raise cls.ParseError("Comment!") comps = line.split() if len(comps) != 7: raise cls.ParseError("Invalid Entry!") return dict(zip(cls.vfstab_keys, comps)) @classmethod def from_line(cls, *args, **kwargs): return cls(** cls.dict_from_line(*args, **kwargs)) @classmethod def dict_to_line(cls, entry): return cls.vfstab_format.format(**entry) def __str__(self): ''' String value, only works for full repr ''' return self.dict_to_line(self.criteria) def __repr__(self): ''' Always works ''' return repr(self.criteria) def pick(self, keys): ''' Returns an instance with just those keys ''' subset = dict([(key, self.criteria[key]) for key in keys]) return self.__class__(**subset) def __init__(self, **criteria): ''' Store non-empty, non-null values to use as filter ''' items = [key_value for key_value in six.iteritems(criteria) if key_value[1] is not None] items = [(key_value1[0], six.text_type(key_value1[1])) for key_value1 in items] self.criteria = dict(items) @staticmethod def norm_path(path): ''' Resolve equivalent paths equivalently ''' return os.path.normcase(os.path.normpath(path)) def match(self, line): ''' Compare potentially partial criteria against line ''' entry = self.dict_from_line(line) for key, value in six.iteritems(self.criteria): if entry[key] != value: return False return True class _FileSystemsEntry(object): ''' Utility class for manipulating filesystem entries. Primarily we're parsing, formatting, and comparing lines. Parsing emits dicts expected from fstab() or raises a ValueError. Note: We'll probably want to use os.normpath and os.normcase on 'name' ''' class ParseError(ValueError): ''' Error raised when a line isn't parsible as an fstab entry ''' filesystems_keys = ('device', 'name', 'fstype', 'vfstype', 'opts', 'mount') # preserve data format of filesystems compatibility_keys = ('dev', 'dev', 'name', 'fstype', 'vfstype', 'opts', 'mount', 'type', 'vfs', 'account', 'boot', 'check', 'free', 'nodename', 'quota', 'size', 'vol', 'log') @classmethod def dict_from_lines(cls, lines, keys=filesystems_keys): if len(lines) < 2: raise ValueError('Invalid number of lines: {0}'.format(lines)) if not keys: # if empty force default filesystems_keys keys = _FileSystemsEntry.filesystems_keys elif len(keys) < 6: raise ValueError('Invalid key name array: {0}'.format(keys)) blk_lines = lines orddict = OrderedDict() orddict['name'] = blk_lines[0].split(':')[0].strip() blk_lines.pop(0) for line in blk_lines: if line.startswith('#'): raise cls.ParseError("Comment!") comps = line.split('= ') if len(comps) != 2: raise cls.ParseError("Invalid Entry!") key_name = comps[0].strip() if key_name in keys: orddict[key_name] = comps[1].strip() else: raise ValueError('Invalid name for use in filesystems: {0}'.format(key_name)) return orddict @classmethod def dict_from_cmd_line(cls, ipargs, keys): cmdln_dict = ipargs if keys: for key, value in keys: # ignore unknown or local scope keys if key.startswith('__'): continue if key in _FileSystemsEntry.compatibility_keys: cmdln_dict[key] = value return cmdln_dict @classmethod def from_line(cls, *args, **kwargs): return cls(** cls.dict_from_cmd_line(*args, **kwargs)) @classmethod def dict_to_lines(cls, fsys_dict_entry): entry = fsys_dict_entry strg_out = entry['name'] + ':' + os.linesep for k, v in six.viewitems(entry): if 'name' not in k: strg_out += '\t{0}\t\t= {1}'.format(k, v) + os.linesep strg_out += os.linesep return six.text_type(strg_out) def dict_from_entry(self): ret = OrderedDict() ret[self.criteria['name']] = self.criteria return ret def __str__(self): ''' String value, only works for full repr ''' return self.dict_to_lines(self.criteria) def __repr__(self): ''' Always works ''' return repr(self.criteria) def pick(self, keys): ''' Returns an instance with just those keys ''' subset = dict([(key, self.criteria[key]) for key in keys]) return self.__class__(**subset) def __init__(self, **criteria): ''' Store non-empty, non-null values to use as filter ''' items = [key_value for key_value in six.iteritems(criteria) if key_value[1] is not None] items = [(key_value1[0], six.text_type(key_value1[1])) for key_value1 in items] self.criteria = OrderedDict(items) @staticmethod def norm_path(path): ''' Resolve equivalent paths equivalently ''' return os.path.normcase(os.path.normpath(path)) def match(self, fsys_view): ''' Compare potentially partial criteria against built filesystems entry dictionary ''' evalue_dict = fsys_view[1] for key, value in six.viewitems(self.criteria): if key in evalue_dict: if evalue_dict[key] != value: return False else: return False return True def __getitem__(self, key): ''' Return value for input key ''' return self.criteria[key] def fstab(config='/etc/fstab'): ''' .. versionchanged:: 2016.3.2 List the contents of the fstab CLI Example: .. code-block:: bash salt '*' mount.fstab ''' ret = {} if not os.path.isfile(config): return ret with salt.utils.files.fopen(config) as ifile: for line in ifile: line = salt.utils.stringutils.to_unicode(line) try: if __grains__['kernel'] == 'SunOS': # Note: comments use in default vfstab file! if line[0] == '#': continue entry = _vfstab_entry.dict_from_line( line) else: entry = _fstab_entry.dict_from_line( line, _fstab_entry.compatibility_keys) entry['opts'] = entry['opts'].split(',') while entry['name'] in ret: entry['name'] += '_' ret[entry.pop('name')] = entry except _fstab_entry.ParseError: pass except _vfstab_entry.ParseError: pass return ret def vfstab(config='/etc/vfstab'): ''' .. versionadded:: 2016.3.2 List the contents of the vfstab CLI Example: .. code-block:: bash salt '*' mount.vfstab ''' # NOTE: vfstab is a wrapper for fstab return fstab(config) def rm_fstab(name, device, config='/etc/fstab'): ''' .. versionchanged:: 2016.3.2 Remove the mount point from the fstab CLI Example: .. code-block:: bash salt '*' mount.rm_fstab /mnt/foo /dev/sdg ''' modified = False if __grains__['kernel'] == 'SunOS': criteria = _vfstab_entry(name=name, device=device) else: criteria = _fstab_entry(name=name, device=device) lines = [] try: with salt.utils.files.fopen(config, 'r') as ifile: for line in ifile: line = salt.utils.stringutils.to_unicode(line) try: if criteria.match(line): modified = True else: lines.append(line) except _fstab_entry.ParseError: lines.append(line) except _vfstab_entry.ParseError: lines.append(line) except (IOError, OSError) as exc: msg = "Couldn't read from {0}: {1}" raise CommandExecutionError(msg.format(config, exc)) if modified: try: with salt.utils.files.fopen(config, 'wb') as ofile: ofile.writelines(salt.utils.data.encode(lines)) except (IOError, OSError) as exc: msg = "Couldn't write to {0}: {1}" raise CommandExecutionError(msg.format(config, exc)) # Note: not clear why we always return 'True' # --just copying previous behavior at this point... return True def rm_vfstab(name, device, config='/etc/vfstab'): ''' .. versionadded:: 2016.3.2 Remove the mount point from the vfstab CLI Example: .. code-block:: bash salt '*' mount.rm_vfstab /mnt/foo /device/c0t0d0p0 ''' ## NOTE: rm_vfstab is a wrapper for rm_fstab return rm_fstab(name, device, config) def set_fstab( name, device, fstype, opts='defaults', dump=0, pass_num=0, config='/etc/fstab', test=False, match_on='auto', **kwargs): ''' Verify that this mount is represented in the fstab, change the mount to match the data passed, or add the mount if it is not present. CLI Example: .. code-block:: bash salt '*' mount.set_fstab /mnt/foo /dev/sdz1 ext4 ''' # Fix the opts type if it is a list if isinstance(opts, list): opts = ','.join(opts) # preserve arguments for updating entry_args = { 'name': name, 'device': device.replace('\\ ', '\\040'), 'fstype': fstype, 'opts': opts.replace('\\ ', '\\040'), 'dump': dump, 'pass_num': pass_num, } lines = [] ret = None # Transform match_on into list--items will be checked later if isinstance(match_on, list): pass elif not isinstance(match_on, six.string_types): msg = 'match_on must be a string or list of strings' raise CommandExecutionError(msg) elif match_on == 'auto': # Try to guess right criteria for auto.... # NOTE: missing some special fstypes here specialFSes = frozenset([ 'none', 'tmpfs', 'sysfs', 'proc', 'fusectl', 'debugfs', 'securityfs', 'devtmpfs', 'cgroup', 'btrfs']) if fstype in specialFSes: match_on = ['name'] else: match_on = ['device'] else: match_on = [match_on] # generate entry and criteria objects, handle invalid keys in match_on entry = _fstab_entry(**entry_args) try: criteria = entry.pick(match_on) except KeyError: filterFn = lambda key: key not in _fstab_entry.fstab_keys invalid_keys = filter(filterFn, match_on) msg = 'Unrecognized keys in match_on: "{0}"'.format(invalid_keys) raise CommandExecutionError(msg) # parse file, use ret to cache status if not os.path.isfile(config): raise CommandExecutionError('Bad config file "{0}"'.format(config)) try: with salt.utils.files.fopen(config, 'r') as ifile: for line in ifile: line = salt.utils.stringutils.to_unicode(line) try: if criteria.match(line): # Note: If ret isn't None here, # we've matched multiple lines ret = 'present' if entry.match(line): lines.append(line) else: ret = 'change' lines.append(six.text_type(entry)) else: lines.append(line) except _fstab_entry.ParseError: lines.append(line) except (IOError, OSError) as exc: msg = 'Couldn\'t read from {0}: {1}' raise CommandExecutionError(msg.format(config, exc)) # add line if not present or changed if ret is None: lines.append(six.text_type(entry)) ret = 'new' if ret != 'present': # ret in ['new', 'change']: if not salt.utils.args.test_mode(test=test, **kwargs): try: with salt.utils.files.fopen(config, 'wb') as ofile: # The line was changed, commit it! ofile.writelines(salt.utils.data.encode(lines)) except (IOError, OSError): msg = 'File not writable {0}' raise CommandExecutionError(msg.format(config)) return ret def set_vfstab( name, device, fstype, opts='-', device_fsck='-', pass_fsck='-', mount_at_boot='yes', config='/etc/vfstab', test=False, match_on='auto', **kwargs): ''' ..verionadded:: 2016.3.2 Verify that this mount is represented in the fstab, change the mount to match the data passed, or add the mount if it is not present. CLI Example: .. code-block:: bash salt '*' mount.set_vfstab /mnt/foo /device/c0t0d0p0 ufs ''' # Fix the opts type if it is a list if isinstance(opts, list): opts = ','.join(opts) # Map unknown values for mount_at_boot to no if mount_at_boot != 'yes': mount_at_boot = 'no' # preserve arguments for updating entry_args = { 'name': name, 'device': device, 'fstype': fstype, 'opts': opts, 'device_fsck': device_fsck, 'pass_fsck': pass_fsck, 'mount_at_boot': mount_at_boot, } lines = [] ret = None # Transform match_on into list--items will be checked later if isinstance(match_on, list): pass elif not isinstance(match_on, six.string_types): msg = 'match_on must be a string or list of strings' raise CommandExecutionError(msg) elif match_on == 'auto': # Try to guess right criteria for auto.... # NOTE: missing some special fstypes here specialFSes = frozenset([ 'devfs', 'proc', 'ctfs', 'objfs', 'sharefs', 'fs', 'tmpfs']) if fstype in specialFSes: match_on = ['name'] else: match_on = ['device'] else: match_on = [match_on] # generate entry and criteria objects, handle invalid keys in match_on entry = _vfstab_entry(**entry_args) try: criteria = entry.pick(match_on) except KeyError: filterFn = lambda key: key not in _vfstab_entry.vfstab_keys invalid_keys = filter(filterFn, match_on) msg = 'Unrecognized keys in match_on: "{0}"'.format(invalid_keys) raise CommandExecutionError(msg) # parse file, use ret to cache status if not os.path.isfile(config): raise CommandExecutionError('Bad config file "{0}"'.format(config)) try: with salt.utils.files.fopen(config, 'r') as ifile: for line in ifile: line = salt.utils.stringutils.to_unicode(line) try: if criteria.match(line): # Note: If ret isn't None here, # we've matched multiple lines ret = 'present' if entry.match(line): lines.append(line) else: ret = 'change' lines.append(six.text_type(entry)) else: lines.append(line) except _vfstab_entry.ParseError: lines.append(line) except (IOError, OSError) as exc: msg = 'Couldn\'t read from {0}: {1}' raise CommandExecutionError(msg.format(config, exc)) # add line if not present or changed if ret is None: lines.append(six.text_type(entry)) ret = 'new' if ret != 'present': # ret in ['new', 'change']: if not salt.utils.args.test_mode(test=test, **kwargs): try: with salt.utils.files.fopen(config, 'wb') as ofile: # The line was changed, commit it! ofile.writelines(salt.utils.data.encode(lines)) except (IOError, OSError): msg = 'File not writable {0}' raise CommandExecutionError(msg.format(config)) return ret def rm_automaster(name, device, config='/etc/auto_salt'): ''' Remove the mount point from the auto_master CLI Example: .. code-block:: bash salt '*' mount.rm_automaster /mnt/foo /dev/sdg ''' contents = automaster(config) if name not in contents: return True # The entry is present, get rid of it lines = [] try: with salt.utils.files.fopen(config, 'r') as ifile: for line in ifile: line = salt.utils.stringutils.to_unicode(line) if line.startswith('#'): # Commented lines.append(line) continue if not line.strip(): # Blank line lines.append(line) continue comps = line.split() if len(comps) != 3: # Invalid entry lines.append(line) continue comps = line.split() prefix = "/.." name_chk = comps[0].replace(prefix, "") device_fmt = comps[2].split(":") if device: if name_chk == name and device_fmt[1] == device: continue else: if name_chk == name: continue lines.append(line) except (IOError, OSError) as exc: msg = "Couldn't read from {0}: {1}" raise CommandExecutionError(msg.format(config, exc)) try: with salt.utils.files.fopen(config, 'wb') as ofile: ofile.writelines(salt.utils.data.encode(lines)) except (IOError, OSError) as exc: msg = "Couldn't write to {0}: {1}" raise CommandExecutionError(msg.format(config, exc)) # Update automount __salt__['cmd.run']('automount -cv') return True def set_automaster( name, device, fstype, opts='', config='/etc/auto_salt', test=False, **kwargs): ''' Verify that this mount is represented in the auto_salt, change the mount to match the data passed, or add the mount if it is not present. CLI Example: .. code-block:: bash salt '*' mount.set_automaster /mnt/foo /dev/sdz1 ext4 ''' # Fix the opts type if it is a list if isinstance(opts, list): opts = ','.join(opts) lines = [] change = False present = False automaster_file = "/etc/auto_master" if not os.path.isfile(config): __salt__['file.touch'](config) __salt__['file.append'](automaster_file, "/-\t\t\t{0}".format(config)) name = "/..{0}".format(name) device_fmt = "{0}:{1}".format(fstype, device) type_opts = "-fstype={0},{1}".format(fstype, opts) if fstype == 'smbfs': device_fmt = device_fmt.replace(fstype, "") try: with salt.utils.files.fopen(config, 'r') as ifile: for line in ifile: line = salt.utils.stringutils.to_unicode(line) if line.startswith('#'): # Commented lines.append(line) continue if not line.strip(): # Blank line lines.append(line) continue comps = line.split() if len(comps) != 3: # Invalid entry lines.append(line) continue if comps[0] == name or comps[2] == device_fmt: # check to see if there are changes # and fix them if there are any present = True if comps[0] != name: change = True comps[0] = name if comps[1] != type_opts: change = True comps[1] = type_opts if comps[2] != device_fmt: change = True comps[2] = device_fmt if change: log.debug( 'auto_master entry for mount point %s needs to be ' 'updated', name ) newline = ( '{0}\t{1}\t{2}\n'.format( name, type_opts, device_fmt) ) lines.append(newline) else: lines.append(line) except (IOError, OSError) as exc: msg = 'Couldn\'t read from {0}: {1}' raise CommandExecutionError(msg.format(config, exc)) if change: if not salt.utils.args.test_mode(test=test, **kwargs): try: with salt.utils.files.fopen(config, 'wb') as ofile: # The line was changed, commit it! ofile.writelines(salt.utils.data.encode(lines)) except (IOError, OSError): msg = 'File not writable {0}' raise CommandExecutionError(msg.format(config)) return 'change' if not change: if present: # The right entry is already here return 'present' else: if not salt.utils.args.test_mode(test=test, **kwargs): # The entry is new, add it to the end of the fstab newline = ( '{0}\t{1}\t{2}\n'.format( name, type_opts, device_fmt) ) lines.append(newline) try: with salt.utils.files.fopen(config, 'wb') as ofile: # The line was changed, commit it! ofile.writelines(salt.utils.data.encode(lines)) except (IOError, OSError): raise CommandExecutionError( 'File not writable {0}'.format( config ) ) return 'new' def mount(name, device, mkmnt=False, fstype='', opts='defaults', user=None, util='mount'): ''' Mount a device CLI Example: .. code-block:: bash salt '*' mount.mount /mnt/foo /dev/sdz1 True ''' if util != 'mount': # This functionality used to live in img.mount_image if util == 'guestfs': return __salt__['guestfs.mount'](name, root=device) elif util == 'qemu_nbd': mnt = __salt__['qemu_nbd.init'](name, device) if not mnt: return False first = next(six.iterkeys(mnt)) __context__['img.mnt_{0}'.format(first)] = mnt return first return False # Darwin doesn't expect defaults when mounting without other options if 'defaults' in opts and __grains__['os'] in ['MacOS', 'Darwin', 'AIX']: opts = None if isinstance(opts, six.string_types): opts = opts.split(',') if not os.path.exists(name) and mkmnt: __salt__['file.mkdir'](name, user=user) args = '' if opts is not None: lopts = ','.join(opts) args = '-o {0}'.format(lopts) if fstype: # use of fstype on AIX differs from typical Linux use of -t # functionality AIX uses -v vfsname, -t fstype mounts all with # fstype in /etc/filesystems if 'AIX' in __grains__['os']: args += ' -v {0}'.format(fstype) elif 'solaris' in __grains__['os'].lower(): args += ' -F {0}'.format(fstype) else: args += ' -t {0}'.format(fstype) cmd = 'mount {0} {1} {2} '.format(args, device, name) out = __salt__['cmd.run_all'](cmd, runas=user, python_shell=False) if out['retcode']: return out['stderr'] return True def remount(name, device, mkmnt=False, fstype='', opts='defaults', user=None): ''' Attempt to remount a device, if the device is not already mounted, mount is called CLI Example: .. code-block:: bash salt '*' mount.remount /mnt/foo /dev/sdz1 True ''' force_mount = False if __grains__['os'] in ['MacOS', 'Darwin']: if opts == 'defaults': opts = 'noowners' if fstype == 'smbfs': force_mount = True if 'AIX' in __grains__['os']: if opts == 'defaults': opts = [] if isinstance(opts, six.string_types): opts = opts.split(',') mnts = active() if name in mnts: # The mount point is mounted, attempt to remount it with the given data if 'remount' not in opts and __grains__['os'] not in ['OpenBSD', 'MacOS', 'Darwin']: opts.append('remount') if force_mount: # We need to force the mount but first we should unmount umount(name, device, user=user) lopts = ','.join(opts) args = '-o {0}'.format(lopts) if fstype: # use of fstype on AIX differs from typical Linux use of # -t functionality AIX uses -v vfsname, -t fstype mounts # all with fstype in /etc/filesystems if 'AIX' in __grains__['os']: args += ' -v {0}'.format(fstype) elif 'solaris' in __grains__['os'].lower(): args += ' -F {0}'.format(fstype) else: args += ' -t {0}'.format(fstype) if __grains__['os'] not in ['OpenBSD', 'MacOS', 'Darwin'] or force_mount: cmd = 'mount {0} {1} {2} '.format(args, device, name) else: cmd = 'mount -u {0} {1} {2} '.format(args, device, name) out = __salt__['cmd.run_all'](cmd, runas=user, python_shell=False) if out['retcode']: return out['stderr'] return True # Mount a filesystem that isn't already return mount(name, device, mkmnt, fstype, opts, user=user) def umount(name, device=None, user=None, util='mount'): ''' Attempt to unmount a device by specifying the directory it is mounted on CLI Example: .. code-block:: bash salt '*' mount.umount /mnt/foo .. versionadded:: 2015.5.0 .. code-block:: bash salt '*' mount.umount /mnt/foo /dev/xvdc1 ''' if util != 'mount': # This functionality used to live in img.umount_image if 'qemu_nbd.clear' in __salt__: if 'img.mnt_{0}'.format(name) in __context__: __salt__['qemu_nbd.clear'](__context__['img.mnt_{0}'.format(name)]) return mnts = active() if name not in mnts: return "{0} does not have anything mounted".format(name) if not device: cmd = 'umount {0}'.format(name) else: cmd = 'umount {0}'.format(device) out = __salt__['cmd.run_all'](cmd, runas=user, python_shell=False) if out['retcode']: return out['stderr'] return True def is_fuse_exec(cmd): ''' Returns true if the command passed is a fuse mountable application. CLI Example: .. code-block:: bash salt '*' mount.is_fuse_exec sshfs ''' cmd_path = salt.utils.path.which(cmd) # No point in running ldd on a command that doesn't exist if not cmd_path: return False elif not salt.utils.path.which('ldd'): raise CommandNotFoundError('ldd') out = __salt__['cmd.run']('ldd {0}'.format(cmd_path), python_shell=False) return 'libfuse' in out def swaps(): ''' Return a dict containing information on active swap .. versionchanged:: 2016.3.2 CLI Example: .. code-block:: bash salt '*' mount.swaps ''' ret = {} if __grains__['kernel'] == 'SunOS': for line in __salt__['cmd.run_stdout']('swap -l').splitlines(): if line.startswith('swapfile'): continue comps = line.split() ret[comps[0]] = {'type': 'device' if comps[0].startswith(('/dev', 'swap')) else 'file', 'size': int(comps[3]), 'used': (int(comps[3]) - int(comps[4])), 'priority': '-'} elif 'AIX' in __grains__['kernel']: for line in __salt__['cmd.run_stdout']('swap -l').splitlines(): if line.startswith('device'): continue comps = line.split() # AIX uses MB for units ret[comps[0]] = {'type': 'device', 'size': int(comps[3][:-2]) * 1024, 'used': (int(comps[3][:-2]) - int(comps[4][:-2])) * 1024, 'priority': '-'} elif __grains__['os'] != 'OpenBSD': with salt.utils.files.fopen('/proc/swaps') as fp_: for line in fp_: line = salt.utils.stringutils.to_unicode(line) if line.startswith('Filename'): continue comps = line.split() ret[comps[0]] = {'type': comps[1], 'size': comps[2], 'used': comps[3], 'priority': comps[4]} else: for line in __salt__['cmd.run_stdout']('swapctl -kl').splitlines(): if line.startswith(('Device', 'Total')): continue swap_type = "file" comps = line.split() if comps[0].startswith('/dev/'): swap_type = "partition" ret[comps[0]] = {'type': swap_type, 'size': comps[1], 'used': comps[2], 'priority': comps[5]} return ret def swapon(name, priority=None): ''' Activate a swap disk .. versionchanged:: 2016.3.2 CLI Example: .. code-block:: bash salt '*' mount.swapon /root/swapfile ''' ret = {} on_ = swaps() if name in on_: ret['stats'] = on_[name] ret['new'] = False return ret if __grains__['kernel'] == 'SunOS': if __grains__['virtual'] != 'zone': __salt__['cmd.run']('swap -a {0}'.format(name), python_shell=False) else: return False else: cmd = 'swapon {0}'.format(name) if priority and 'AIX' not in __grains__['kernel']: cmd += ' -p {0}'.format(priority) __salt__['cmd.run'](cmd, python_shell=False) on_ = swaps() if name in on_: ret['stats'] = on_[name] ret['new'] = True return ret return ret def swapoff(name): ''' Deactivate a named swap mount .. versionchanged:: 2016.3.2 CLI Example: .. code-block:: bash salt '*' mount.swapoff /root/swapfile ''' on_ = swaps() if name in on_: if __grains__['kernel'] == 'SunOS': if __grains__['virtual'] != 'zone': __salt__['cmd.run']('swap -a {0}'.format(name), python_shell=False) else: return False elif __grains__['os'] != 'OpenBSD': __salt__['cmd.run']('swapoff {0}'.format(name), python_shell=False) else: __salt__['cmd.run']('swapctl -d {0}'.format(name), python_shell=False) on_ = swaps() if name in on_: return False return True return None def is_mounted(name): ''' .. versionadded:: 2014.7.0 Provide information if the path is mounted CLI Example: .. code-block:: bash salt '*' mount.is_mounted /mnt/share ''' active_ = active() if name in active_: return True else: return False def read_mount_cache(name): ''' .. versionadded:: 2018.3.0 Provide information if the path is mounted CLI Example: .. code-block:: bash salt '*' mount.read_mount_cache /mnt/share ''' cache = salt.utils.mount.read_cache(__opts__) if cache: if 'mounts' in cache and cache['mounts']: if name in cache['mounts']: return cache['mounts'][name] return {} def write_mount_cache(real_name, device, mkmnt, fstype, mount_opts): ''' .. versionadded:: 2018.3.0 Provide information if the path is mounted :param real_name: The real name of the mount point where the device is mounted. :param device: The device that is being mounted. :param mkmnt: Whether or not the mount point should be created. :param fstype: The file system that is used. :param mount_opts: Additional options used when mounting the device. :return: Boolean if message was sent successfully. CLI Example: .. code-block:: bash salt '*' mount.write_mount_cache /mnt/share /dev/sda1 False ext4 defaults,nosuid ''' cache = salt.utils.mount.read_cache(__opts__) if not cache: cache = {} cache['mounts'] = {} else: if 'mounts' not in cache: cache['mounts'] = {} cache['mounts'][real_name] = {'device': device, 'fstype': fstype, 'mkmnt': mkmnt, 'opts': mount_opts} cache_write = salt.utils.mount.write_cache(cache, __opts__) if cache_write: return True else: raise CommandExecutionError('Unable to write mount cache.') def delete_mount_cache(real_name): ''' .. versionadded:: 2018.3.0 Provide information if the path is mounted CLI Example: .. code-block:: bash salt '*' mount.delete_mount_cache /mnt/share ''' cache = salt.utils.mount.read_cache(__opts__) if cache: if 'mounts' in cache: if real_name in cache['mounts']: del cache['mounts'][real_name] cache_write = salt.utils.mount.write_cache(cache, __opts__) if not cache_write: raise CommandExecutionError('Unable to write mount cache.') return True def _filesystems(config='/etc/filesystems', leading_key=True): ''' Return the contents of the filesystems in an OrderedDict config File containing filesystem infomation leading_key True return dictionary keyed by 'name' and value as dictionary with other keys, values (name excluded) OrderedDict({ '/dir' : OrderedDict({'dev': '/dev/hd8', .... }})) False return dictionary keyed by 'name' and value as dictionary with all keys, values (name included) OrderedDict({ '/dir' : OrderedDict({'name': '/dir', 'dev': '/dev/hd8', ... })}) ''' ret = OrderedDict() lines = [] parsing_block = False if not os.path.isfile(config) or 'AIX' not in __grains__['kernel']: return ret # read in block of filesystems, block starts with '/' till empty line with salt.utils.files.fopen(config) as ifile: for line in ifile: line = salt.utils.stringutils.to_unicode(line) # skip till first entry if not line.startswith('/') and not parsing_block: continue if line.startswith('/'): parsing_block = True lines.append(line) elif not line.split(): parsing_block = False try: entry = _FileSystemsEntry.dict_from_lines( lines, _FileSystemsEntry.compatibility_keys) lines = [] if 'opts' in entry: entry['opts'] = entry['opts'].split(',') while entry['name'] in ret: entry['name'] += '_' if leading_key: ret[entry.pop('name')] = entry else: ret[entry['name']] = entry except _FileSystemsEntry.ParseError: pass else: lines.append(line) return ret def filesystems(config='/etc/filesystems'): ''' .. versionadded:: 2018.3.3 List the contents of the filesystems CLI Example: .. code-block:: bash salt '*' mount.filesystems ''' ret = {} if 'AIX' not in __grains__['kernel']: return ret ret_dict = _filesystems(config) if ret_dict: ret_key = next(iter(ret_dict.keys())) ret = {ret_key: dict(ret_dict[ret_key])} return ret def set_filesystems( name, device, vfstype, opts='-', mount='true', config='/etc/filesystems', test=False, match_on='auto', **kwargs): ''' .. versionadded:: 2018.3.3 Verify that this mount is represented in the filesystems, change the mount to match the data passed, or add the mount if it is not present on AIX Provide information if the path is mounted :param name: The name of the mount point where the device is mounted. :param device: The device that is being mounted. :param vfstype: The file system that is used (AIX has two fstypes, fstype and vfstype - similar to Linux fstype) :param opts: Additional options used when mounting the device. :param mount: Mount if not mounted, default True. :param config: Configuration file, default /etc/filesystems. :param match: File systems type to match on, default auto CLI Example: .. code-block:: bash salt '*' mount.set_filesystems /mnt/foo /dev/sdz1 jfs2 ''' # Fix the opts type if it is a list if isinstance(opts, list): opts = ','.join(opts) # preserve arguments for updating entry_args = { 'name': name, 'dev': device.replace('\\ ', '\\040'), 'vfstype': vfstype, 'opts': opts, 'mount': mount, } view_lines = [] ret = None if 'AIX' not in __grains__['kernel']: return ret # Transform match_on into list--items will be checked later if isinstance(match_on, list): pass elif not isinstance(match_on, six.string_types): raise CommandExecutionError('match_on must be a string or list of strings') elif match_on == 'auto': # Try to guess right criteria for auto.... # added IBM types from sys/vmount.h after btrfs # NOTE: missing some special fstypes here specialFSes = frozenset([ 'none', 'tmpfs', 'sysfs', 'proc', 'fusectl', 'debugfs', 'securityfs', 'devtmpfs', 'cgroup', 'btrfs', 'cdrfs', 'procfs', 'jfs', 'jfs2', 'nfs', 'sfs', 'nfs3', 'cachefs', 'udfs', 'cifs', 'namefs', 'pmemfs', 'ahafs', 'nfs4', 'autofs', 'stnfs']) if vfstype in specialFSes: match_on = ['name'] else: match_on = ['dev'] else: match_on = [match_on] # generate entry and criteria objects, handle invalid keys in match_on entry_ip = _FileSystemsEntry.from_line(entry_args, kwargs) try: criteria = entry_ip.pick(match_on) except KeyError: filterFn = lambda key: key not in _FileSystemsEntry.compatibility_keys invalid_keys = filter(filterFn, match_on) raise CommandExecutionError('Unrecognized keys in match_on: "{0}"'.format(invalid_keys)) # parse file, use ret to cache status if not os.path.isfile(config): raise CommandExecutionError('Bad config file "{0}"'.format(config)) # read in block of filesystem, block starts with '/' till empty line try: fsys_filedict = _filesystems(config, False) for fsys_view in six.viewitems(fsys_filedict): if criteria.match(fsys_view): ret = 'present' if entry_ip.match(fsys_view): view_lines.append(fsys_view) else: ret = 'change' kv = entry_ip['name'] view_lines.append((kv, entry_ip)) else: view_lines.append(fsys_view) except (IOError, OSError) as exc: raise CommandExecutionError('Couldn\'t read from {0}: {1}'.format(config, exc)) # add line if not present or changed if ret is None: for dict_view in six.viewitems(entry_ip.dict_from_entry()): view_lines.append(dict_view) ret = 'new' if ret != 'present': # ret in ['new', 'change']: try: with salt.utils.files.fopen(config, 'wb') as ofile: # The line was changed, commit it! for fsys_view in view_lines: entry = fsys_view[1] mystrg = _FileSystemsEntry.dict_to_lines(entry) ofile.writelines(salt.utils.data.encode(mystrg)) except (IOError, OSError): raise CommandExecutionError('File not writable {0}'.format(config)) return ret def rm_filesystems(name, device, config='/etc/filesystems'): ''' .. versionadded:: 2018.3.3 Remove the mount point from the filesystems CLI Example: .. code-block:: bash salt '*' mount.rm_filesystems /mnt/foo /dev/sdg ''' modified = False view_lines = [] if 'AIX' not in __grains__['kernel']: return modified criteria = _FileSystemsEntry(name=name, dev=device) try: fsys_filedict = _filesystems(config, False) for fsys_view in six.viewitems(fsys_filedict): try: if criteria.match(fsys_view): modified = True else: view_lines.append(fsys_view) except _FileSystemsEntry.ParseError: view_lines.append(fsys_view) except (IOError, OSError) as exc: raise CommandExecutionError("Couldn't read from {0}: {1}".format(config, exc)) if modified: try: with salt.utils.files.fopen(config, 'wb') as ofile: for fsys_view in view_lines: entry = fsys_view[1] mystrg = _FileSystemsEntry.dict_to_lines(entry) ofile.writelines(salt.utils.data.encode(mystrg)) except (IOError, OSError) as exc: raise CommandExecutionError("Couldn't write to {0}: {1}".format(config, exc)) return modified
saltstack/salt
salt/modules/mount.py
mount
python
def mount(name, device, mkmnt=False, fstype='', opts='defaults', user=None, util='mount'): ''' Mount a device CLI Example: .. code-block:: bash salt '*' mount.mount /mnt/foo /dev/sdz1 True ''' if util != 'mount': # This functionality used to live in img.mount_image if util == 'guestfs': return __salt__['guestfs.mount'](name, root=device) elif util == 'qemu_nbd': mnt = __salt__['qemu_nbd.init'](name, device) if not mnt: return False first = next(six.iterkeys(mnt)) __context__['img.mnt_{0}'.format(first)] = mnt return first return False # Darwin doesn't expect defaults when mounting without other options if 'defaults' in opts and __grains__['os'] in ['MacOS', 'Darwin', 'AIX']: opts = None if isinstance(opts, six.string_types): opts = opts.split(',') if not os.path.exists(name) and mkmnt: __salt__['file.mkdir'](name, user=user) args = '' if opts is not None: lopts = ','.join(opts) args = '-o {0}'.format(lopts) if fstype: # use of fstype on AIX differs from typical Linux use of -t # functionality AIX uses -v vfsname, -t fstype mounts all with # fstype in /etc/filesystems if 'AIX' in __grains__['os']: args += ' -v {0}'.format(fstype) elif 'solaris' in __grains__['os'].lower(): args += ' -F {0}'.format(fstype) else: args += ' -t {0}'.format(fstype) cmd = 'mount {0} {1} {2} '.format(args, device, name) out = __salt__['cmd.run_all'](cmd, runas=user, python_shell=False) if out['retcode']: return out['stderr'] return True
Mount a device CLI Example: .. code-block:: bash salt '*' mount.mount /mnt/foo /dev/sdz1 True
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/mount.py#L1177-L1230
[ "def iterkeys(d, **kw):\n return d.iterkeys(**kw)\n" ]
# -*- coding: utf-8 -*- ''' Salt module to manage Unix mounts and the fstab file ''' # Import python libs from __future__ import absolute_import, print_function, unicode_literals import os import re import logging # Import salt libs import salt.utils.args import salt.utils.data import salt.utils.files import salt.utils.path import salt.utils.platform import salt.utils.mount import salt.utils.stringutils from salt.utils.odict import OrderedDict from salt.exceptions import CommandNotFoundError, CommandExecutionError # Import 3rd-party libs from salt.ext import six from salt.ext.six.moves import filter, zip # pylint: disable=import-error,redefined-builtin # Set up logger log = logging.getLogger(__name__) # Define the module's virtual name __virtualname__ = 'mount' def __virtual__(): ''' Only load on POSIX-like systems ''' # Disable on Windows, a specific file module exists: if salt.utils.platform.is_windows(): return (False, 'The mount module cannot be loaded: not a POSIX-like system.') return True def _list_mounts(): ret = {} if __grains__['os'] in ['MacOS', 'Darwin']: mounts = __salt__['cmd.run_stdout']('mount') else: mounts = __salt__['cmd.run_stdout']('mount -l') for line in mounts.split('\n'): comps = re.sub(r"\s+", " ", line).split() if len(comps) >= 3: ret[comps[2]] = comps[0] return ret def _active_mountinfo(ret): _list = _list_mounts() filename = '/proc/self/mountinfo' if not os.access(filename, os.R_OK): msg = 'File not readable {0}' raise CommandExecutionError(msg.format(filename)) if 'disk.blkid' not in __context__: __context__['disk.blkid'] = __salt__['disk.blkid']() blkid_info = __context__['disk.blkid'] with salt.utils.files.fopen(filename) as ifile: for line in ifile: comps = salt.utils.stringutils.to_unicode(line).split() device = comps[2].split(':') # each line can have any number of # optional parameters, we use the # location of the separator field to # determine the location of the elements # after it. _sep = comps.index('-') device_name = comps[_sep + 2] device_uuid = None device_label = None if device_name: device_uuid = blkid_info.get(device_name, {}).get('UUID') device_uuid = device_uuid and device_uuid.lower() device_label = blkid_info.get(device_name, {}).get('LABEL') ret[comps[4]] = {'mountid': comps[0], 'parentid': comps[1], 'major': device[0], 'minor': device[1], 'root': comps[3], 'opts': _resolve_user_group_names(comps[5].split(',')), 'fstype': comps[_sep + 1], 'device': device_name.replace('\\040', '\\ '), 'alt_device': _list.get(comps[4], None), 'superopts': _resolve_user_group_names(comps[_sep + 3].split(',')), 'device_uuid': device_uuid, 'device_label': device_label} return ret def _active_mounts(ret): ''' List active mounts on Linux systems ''' _list = _list_mounts() filename = '/proc/self/mounts' if not os.access(filename, os.R_OK): msg = 'File not readable {0}' raise CommandExecutionError(msg.format(filename)) with salt.utils.files.fopen(filename) as ifile: for line in ifile: comps = salt.utils.stringutils.to_unicode(line).split() ret[comps[1]] = {'device': comps[0], 'alt_device': _list.get(comps[1], None), 'fstype': comps[2], 'opts': _resolve_user_group_names(comps[3].split(','))} return ret def _active_mounts_aix(ret): ''' List active mounts on AIX systems ''' for line in __salt__['cmd.run_stdout']('mount -p').split('\n'): comps = re.sub(r"\s+", " ", line).split() if comps: if comps[0] == 'node' or comps[0] == '--------': continue comps_len = len(comps) if line.startswith((' ', '\t')): curr_opts = _resolve_user_group_names(comps[6].split(',')) if 7 == comps_len else [] if curr_opts: ret[comps[1]] = {'device': comps[0], 'fstype': comps[2], 'opts': curr_opts} else: ret[comps[1]] = {'device': comps[0], 'fstype': comps[2]} else: curr_opts = _resolve_user_group_names(comps[7].split(',')) if 8 == comps_len else [] if curr_opts: ret[comps[2]] = {'node': comps[0], 'device': comps[1], 'fstype': comps[3], 'opts': curr_opts} else: ret[comps[2]] = {'node': comps[0], 'device': comps[1], 'fstype': comps[3]} return ret def _active_mounts_freebsd(ret): ''' List active mounts on FreeBSD systems ''' for line in __salt__['cmd.run_stdout']('mount -p').split('\n'): comps = re.sub(r"\s+", " ", line).split() ret[comps[1]] = {'device': comps[0], 'fstype': comps[2], 'opts': _resolve_user_group_names(comps[3].split(','))} return ret def _active_mounts_solaris(ret): ''' List active mounts on Solaris systems ''' for line in __salt__['cmd.run_stdout']('mount -v').split('\n'): comps = re.sub(r"\s+", " ", line).split() ret[comps[2]] = {'device': comps[0], 'fstype': comps[4], 'opts': _resolve_user_group_names(comps[5].split('/'))} return ret def _active_mounts_openbsd(ret): ''' List active mounts on OpenBSD systems ''' for line in __salt__['cmd.run_stdout']('mount -v').split('\n'): comps = re.sub(r"\s+", " ", line).split() parens = re.findall(r'\((.*?)\)', line, re.DOTALL) if len(parens) > 1: nod = __salt__['cmd.run_stdout']('ls -l {0}'.format(comps[0])) nod = ' '.join(nod.split()).split(" ") ret[comps[3]] = {'device': comps[0], 'fstype': comps[5], 'opts': _resolve_user_group_names(parens[1].split(", ")), 'major': six.text_type(nod[4].strip(",")), 'minor': six.text_type(nod[5]), 'device_uuid': parens[0]} else: ret[comps[2]] = {'device': comps[0], 'fstype': comps[4], 'opts': _resolve_user_group_names(parens[0].split(", "))} return ret def _active_mounts_darwin(ret): ''' List active mounts on Mac OS systems ''' for line in __salt__['cmd.run_stdout']('mount').split('\n'): comps = re.sub(r"\s+", " ", line).split() parens = re.findall(r'\((.*?)\)', line, re.DOTALL)[0].split(", ") ret[comps[2]] = {'device': comps[0], 'fstype': parens[0], 'opts': _resolve_user_group_names(parens[1:])} return ret def _resolve_user_group_names(opts): ''' Resolve user and group names in related opts ''' name_id_opts = {'uid': 'user.info', 'gid': 'group.info'} for ind, opt in enumerate(opts): if opt.split('=')[0] in name_id_opts: _givenid = opt.split('=')[1] _param = opt.split('=')[0] _id = _givenid if not re.match('[0-9]+$', _givenid): _info = __salt__[name_id_opts[_param]](_givenid) if _info and _param in _info: _id = _info[_param] opts[ind] = _param + '=' + six.text_type(_id) opts[ind] = opts[ind].replace('\\040', '\\ ') return opts def active(extended=False): ''' List the active mounts. CLI Example: .. code-block:: bash salt '*' mount.active ''' ret = {} if __grains__['os'] == 'FreeBSD': _active_mounts_freebsd(ret) elif 'AIX' in __grains__['kernel']: _active_mounts_aix(ret) elif __grains__['kernel'] == 'SunOS': _active_mounts_solaris(ret) elif __grains__['os'] == 'OpenBSD': _active_mounts_openbsd(ret) elif __grains__['os'] in ['MacOS', 'Darwin']: _active_mounts_darwin(ret) else: if extended: try: _active_mountinfo(ret) except CommandExecutionError: _active_mounts(ret) else: _active_mounts(ret) return ret class _fstab_entry(object): ''' Utility class for manipulating fstab entries. Primarily we're parsing, formatting, and comparing lines. Parsing emits dicts expected from fstab() or raises a ValueError. Note: We'll probably want to use os.normpath and os.normcase on 'name' ''' class ParseError(ValueError): ''' Error raised when a line isn't parsible as an fstab entry ''' fstab_keys = ('device', 'name', 'fstype', 'opts', 'dump', 'pass_num') # preserve data format compatibility_keys = ('device', 'name', 'fstype', 'opts', 'dump', 'pass') fstab_format = '{device}\t\t{name}\t{fstype}\t{opts}\t{dump} {pass_num}\n' @classmethod def dict_from_line(cls, line, keys=fstab_keys): if len(keys) != 6: raise ValueError('Invalid key array: {0}'.format(keys)) if line.startswith('#'): raise cls.ParseError("Comment!") comps = line.split() if len(comps) < 4 or len(comps) > 6: raise cls.ParseError("Invalid Entry!") comps.extend(['0'] * (len(keys) - len(comps))) return dict(zip(keys, comps)) @classmethod def from_line(cls, *args, **kwargs): return cls(** cls.dict_from_line(*args, **kwargs)) @classmethod def dict_to_line(cls, entry): return cls.fstab_format.format(**entry) def __str__(self): ''' String value, only works for full repr ''' return self.dict_to_line(self.criteria) def __repr__(self): ''' Always works ''' return repr(self.criteria) def pick(self, keys): ''' Returns an instance with just those keys ''' subset = dict([(key, self.criteria[key]) for key in keys]) return self.__class__(**subset) def __init__(self, **criteria): ''' Store non-empty, non-null values to use as filter ''' items = [key_value for key_value in six.iteritems(criteria) if key_value[1] is not None] items = [(key_value1[0], six.text_type(key_value1[1])) for key_value1 in items] self.criteria = dict(items) @staticmethod def norm_path(path): ''' Resolve equivalent paths equivalently ''' return os.path.normcase(os.path.normpath(path)) def match(self, line): ''' Compare potentially partial criteria against line ''' entry = self.dict_from_line(line) for key, value in six.iteritems(self.criteria): if entry[key] != value: return False return True class _vfstab_entry(object): ''' Utility class for manipulating vfstab entries. Primarily we're parsing, formatting, and comparing lines. Parsing emits dicts expected from fstab() or raises a ValueError. Note: We'll probably want to use os.normpath and os.normcase on 'name' Note: This parses vfstab entries on Solaris like systems #device device mount FS fsck mount mount #to mount to fsck point type pass at boot options # /devices - /devices devfs - no - ''' class ParseError(ValueError): '''Error raised when a line isn't parsible as an fstab entry''' vfstab_keys = ('device', 'device_fsck', 'name', 'fstype', 'pass_fsck', 'mount_at_boot', 'opts') # NOTE: weird formatting to match default spacing on Solaris vfstab_format = '{device:<11} {device_fsck:<3} {name:<19} {fstype:<8} {pass_fsck:<3} {mount_at_boot:<6} {opts}\n' @classmethod def dict_from_line(cls, line): if line.startswith('#'): raise cls.ParseError("Comment!") comps = line.split() if len(comps) != 7: raise cls.ParseError("Invalid Entry!") return dict(zip(cls.vfstab_keys, comps)) @classmethod def from_line(cls, *args, **kwargs): return cls(** cls.dict_from_line(*args, **kwargs)) @classmethod def dict_to_line(cls, entry): return cls.vfstab_format.format(**entry) def __str__(self): ''' String value, only works for full repr ''' return self.dict_to_line(self.criteria) def __repr__(self): ''' Always works ''' return repr(self.criteria) def pick(self, keys): ''' Returns an instance with just those keys ''' subset = dict([(key, self.criteria[key]) for key in keys]) return self.__class__(**subset) def __init__(self, **criteria): ''' Store non-empty, non-null values to use as filter ''' items = [key_value for key_value in six.iteritems(criteria) if key_value[1] is not None] items = [(key_value1[0], six.text_type(key_value1[1])) for key_value1 in items] self.criteria = dict(items) @staticmethod def norm_path(path): ''' Resolve equivalent paths equivalently ''' return os.path.normcase(os.path.normpath(path)) def match(self, line): ''' Compare potentially partial criteria against line ''' entry = self.dict_from_line(line) for key, value in six.iteritems(self.criteria): if entry[key] != value: return False return True class _FileSystemsEntry(object): ''' Utility class for manipulating filesystem entries. Primarily we're parsing, formatting, and comparing lines. Parsing emits dicts expected from fstab() or raises a ValueError. Note: We'll probably want to use os.normpath and os.normcase on 'name' ''' class ParseError(ValueError): ''' Error raised when a line isn't parsible as an fstab entry ''' filesystems_keys = ('device', 'name', 'fstype', 'vfstype', 'opts', 'mount') # preserve data format of filesystems compatibility_keys = ('dev', 'dev', 'name', 'fstype', 'vfstype', 'opts', 'mount', 'type', 'vfs', 'account', 'boot', 'check', 'free', 'nodename', 'quota', 'size', 'vol', 'log') @classmethod def dict_from_lines(cls, lines, keys=filesystems_keys): if len(lines) < 2: raise ValueError('Invalid number of lines: {0}'.format(lines)) if not keys: # if empty force default filesystems_keys keys = _FileSystemsEntry.filesystems_keys elif len(keys) < 6: raise ValueError('Invalid key name array: {0}'.format(keys)) blk_lines = lines orddict = OrderedDict() orddict['name'] = blk_lines[0].split(':')[0].strip() blk_lines.pop(0) for line in blk_lines: if line.startswith('#'): raise cls.ParseError("Comment!") comps = line.split('= ') if len(comps) != 2: raise cls.ParseError("Invalid Entry!") key_name = comps[0].strip() if key_name in keys: orddict[key_name] = comps[1].strip() else: raise ValueError('Invalid name for use in filesystems: {0}'.format(key_name)) return orddict @classmethod def dict_from_cmd_line(cls, ipargs, keys): cmdln_dict = ipargs if keys: for key, value in keys: # ignore unknown or local scope keys if key.startswith('__'): continue if key in _FileSystemsEntry.compatibility_keys: cmdln_dict[key] = value return cmdln_dict @classmethod def from_line(cls, *args, **kwargs): return cls(** cls.dict_from_cmd_line(*args, **kwargs)) @classmethod def dict_to_lines(cls, fsys_dict_entry): entry = fsys_dict_entry strg_out = entry['name'] + ':' + os.linesep for k, v in six.viewitems(entry): if 'name' not in k: strg_out += '\t{0}\t\t= {1}'.format(k, v) + os.linesep strg_out += os.linesep return six.text_type(strg_out) def dict_from_entry(self): ret = OrderedDict() ret[self.criteria['name']] = self.criteria return ret def __str__(self): ''' String value, only works for full repr ''' return self.dict_to_lines(self.criteria) def __repr__(self): ''' Always works ''' return repr(self.criteria) def pick(self, keys): ''' Returns an instance with just those keys ''' subset = dict([(key, self.criteria[key]) for key in keys]) return self.__class__(**subset) def __init__(self, **criteria): ''' Store non-empty, non-null values to use as filter ''' items = [key_value for key_value in six.iteritems(criteria) if key_value[1] is not None] items = [(key_value1[0], six.text_type(key_value1[1])) for key_value1 in items] self.criteria = OrderedDict(items) @staticmethod def norm_path(path): ''' Resolve equivalent paths equivalently ''' return os.path.normcase(os.path.normpath(path)) def match(self, fsys_view): ''' Compare potentially partial criteria against built filesystems entry dictionary ''' evalue_dict = fsys_view[1] for key, value in six.viewitems(self.criteria): if key in evalue_dict: if evalue_dict[key] != value: return False else: return False return True def __getitem__(self, key): ''' Return value for input key ''' return self.criteria[key] def fstab(config='/etc/fstab'): ''' .. versionchanged:: 2016.3.2 List the contents of the fstab CLI Example: .. code-block:: bash salt '*' mount.fstab ''' ret = {} if not os.path.isfile(config): return ret with salt.utils.files.fopen(config) as ifile: for line in ifile: line = salt.utils.stringutils.to_unicode(line) try: if __grains__['kernel'] == 'SunOS': # Note: comments use in default vfstab file! if line[0] == '#': continue entry = _vfstab_entry.dict_from_line( line) else: entry = _fstab_entry.dict_from_line( line, _fstab_entry.compatibility_keys) entry['opts'] = entry['opts'].split(',') while entry['name'] in ret: entry['name'] += '_' ret[entry.pop('name')] = entry except _fstab_entry.ParseError: pass except _vfstab_entry.ParseError: pass return ret def vfstab(config='/etc/vfstab'): ''' .. versionadded:: 2016.3.2 List the contents of the vfstab CLI Example: .. code-block:: bash salt '*' mount.vfstab ''' # NOTE: vfstab is a wrapper for fstab return fstab(config) def rm_fstab(name, device, config='/etc/fstab'): ''' .. versionchanged:: 2016.3.2 Remove the mount point from the fstab CLI Example: .. code-block:: bash salt '*' mount.rm_fstab /mnt/foo /dev/sdg ''' modified = False if __grains__['kernel'] == 'SunOS': criteria = _vfstab_entry(name=name, device=device) else: criteria = _fstab_entry(name=name, device=device) lines = [] try: with salt.utils.files.fopen(config, 'r') as ifile: for line in ifile: line = salt.utils.stringutils.to_unicode(line) try: if criteria.match(line): modified = True else: lines.append(line) except _fstab_entry.ParseError: lines.append(line) except _vfstab_entry.ParseError: lines.append(line) except (IOError, OSError) as exc: msg = "Couldn't read from {0}: {1}" raise CommandExecutionError(msg.format(config, exc)) if modified: try: with salt.utils.files.fopen(config, 'wb') as ofile: ofile.writelines(salt.utils.data.encode(lines)) except (IOError, OSError) as exc: msg = "Couldn't write to {0}: {1}" raise CommandExecutionError(msg.format(config, exc)) # Note: not clear why we always return 'True' # --just copying previous behavior at this point... return True def rm_vfstab(name, device, config='/etc/vfstab'): ''' .. versionadded:: 2016.3.2 Remove the mount point from the vfstab CLI Example: .. code-block:: bash salt '*' mount.rm_vfstab /mnt/foo /device/c0t0d0p0 ''' ## NOTE: rm_vfstab is a wrapper for rm_fstab return rm_fstab(name, device, config) def set_fstab( name, device, fstype, opts='defaults', dump=0, pass_num=0, config='/etc/fstab', test=False, match_on='auto', **kwargs): ''' Verify that this mount is represented in the fstab, change the mount to match the data passed, or add the mount if it is not present. CLI Example: .. code-block:: bash salt '*' mount.set_fstab /mnt/foo /dev/sdz1 ext4 ''' # Fix the opts type if it is a list if isinstance(opts, list): opts = ','.join(opts) # preserve arguments for updating entry_args = { 'name': name, 'device': device.replace('\\ ', '\\040'), 'fstype': fstype, 'opts': opts.replace('\\ ', '\\040'), 'dump': dump, 'pass_num': pass_num, } lines = [] ret = None # Transform match_on into list--items will be checked later if isinstance(match_on, list): pass elif not isinstance(match_on, six.string_types): msg = 'match_on must be a string or list of strings' raise CommandExecutionError(msg) elif match_on == 'auto': # Try to guess right criteria for auto.... # NOTE: missing some special fstypes here specialFSes = frozenset([ 'none', 'tmpfs', 'sysfs', 'proc', 'fusectl', 'debugfs', 'securityfs', 'devtmpfs', 'cgroup', 'btrfs']) if fstype in specialFSes: match_on = ['name'] else: match_on = ['device'] else: match_on = [match_on] # generate entry and criteria objects, handle invalid keys in match_on entry = _fstab_entry(**entry_args) try: criteria = entry.pick(match_on) except KeyError: filterFn = lambda key: key not in _fstab_entry.fstab_keys invalid_keys = filter(filterFn, match_on) msg = 'Unrecognized keys in match_on: "{0}"'.format(invalid_keys) raise CommandExecutionError(msg) # parse file, use ret to cache status if not os.path.isfile(config): raise CommandExecutionError('Bad config file "{0}"'.format(config)) try: with salt.utils.files.fopen(config, 'r') as ifile: for line in ifile: line = salt.utils.stringutils.to_unicode(line) try: if criteria.match(line): # Note: If ret isn't None here, # we've matched multiple lines ret = 'present' if entry.match(line): lines.append(line) else: ret = 'change' lines.append(six.text_type(entry)) else: lines.append(line) except _fstab_entry.ParseError: lines.append(line) except (IOError, OSError) as exc: msg = 'Couldn\'t read from {0}: {1}' raise CommandExecutionError(msg.format(config, exc)) # add line if not present or changed if ret is None: lines.append(six.text_type(entry)) ret = 'new' if ret != 'present': # ret in ['new', 'change']: if not salt.utils.args.test_mode(test=test, **kwargs): try: with salt.utils.files.fopen(config, 'wb') as ofile: # The line was changed, commit it! ofile.writelines(salt.utils.data.encode(lines)) except (IOError, OSError): msg = 'File not writable {0}' raise CommandExecutionError(msg.format(config)) return ret def set_vfstab( name, device, fstype, opts='-', device_fsck='-', pass_fsck='-', mount_at_boot='yes', config='/etc/vfstab', test=False, match_on='auto', **kwargs): ''' ..verionadded:: 2016.3.2 Verify that this mount is represented in the fstab, change the mount to match the data passed, or add the mount if it is not present. CLI Example: .. code-block:: bash salt '*' mount.set_vfstab /mnt/foo /device/c0t0d0p0 ufs ''' # Fix the opts type if it is a list if isinstance(opts, list): opts = ','.join(opts) # Map unknown values for mount_at_boot to no if mount_at_boot != 'yes': mount_at_boot = 'no' # preserve arguments for updating entry_args = { 'name': name, 'device': device, 'fstype': fstype, 'opts': opts, 'device_fsck': device_fsck, 'pass_fsck': pass_fsck, 'mount_at_boot': mount_at_boot, } lines = [] ret = None # Transform match_on into list--items will be checked later if isinstance(match_on, list): pass elif not isinstance(match_on, six.string_types): msg = 'match_on must be a string or list of strings' raise CommandExecutionError(msg) elif match_on == 'auto': # Try to guess right criteria for auto.... # NOTE: missing some special fstypes here specialFSes = frozenset([ 'devfs', 'proc', 'ctfs', 'objfs', 'sharefs', 'fs', 'tmpfs']) if fstype in specialFSes: match_on = ['name'] else: match_on = ['device'] else: match_on = [match_on] # generate entry and criteria objects, handle invalid keys in match_on entry = _vfstab_entry(**entry_args) try: criteria = entry.pick(match_on) except KeyError: filterFn = lambda key: key not in _vfstab_entry.vfstab_keys invalid_keys = filter(filterFn, match_on) msg = 'Unrecognized keys in match_on: "{0}"'.format(invalid_keys) raise CommandExecutionError(msg) # parse file, use ret to cache status if not os.path.isfile(config): raise CommandExecutionError('Bad config file "{0}"'.format(config)) try: with salt.utils.files.fopen(config, 'r') as ifile: for line in ifile: line = salt.utils.stringutils.to_unicode(line) try: if criteria.match(line): # Note: If ret isn't None here, # we've matched multiple lines ret = 'present' if entry.match(line): lines.append(line) else: ret = 'change' lines.append(six.text_type(entry)) else: lines.append(line) except _vfstab_entry.ParseError: lines.append(line) except (IOError, OSError) as exc: msg = 'Couldn\'t read from {0}: {1}' raise CommandExecutionError(msg.format(config, exc)) # add line if not present or changed if ret is None: lines.append(six.text_type(entry)) ret = 'new' if ret != 'present': # ret in ['new', 'change']: if not salt.utils.args.test_mode(test=test, **kwargs): try: with salt.utils.files.fopen(config, 'wb') as ofile: # The line was changed, commit it! ofile.writelines(salt.utils.data.encode(lines)) except (IOError, OSError): msg = 'File not writable {0}' raise CommandExecutionError(msg.format(config)) return ret def rm_automaster(name, device, config='/etc/auto_salt'): ''' Remove the mount point from the auto_master CLI Example: .. code-block:: bash salt '*' mount.rm_automaster /mnt/foo /dev/sdg ''' contents = automaster(config) if name not in contents: return True # The entry is present, get rid of it lines = [] try: with salt.utils.files.fopen(config, 'r') as ifile: for line in ifile: line = salt.utils.stringutils.to_unicode(line) if line.startswith('#'): # Commented lines.append(line) continue if not line.strip(): # Blank line lines.append(line) continue comps = line.split() if len(comps) != 3: # Invalid entry lines.append(line) continue comps = line.split() prefix = "/.." name_chk = comps[0].replace(prefix, "") device_fmt = comps[2].split(":") if device: if name_chk == name and device_fmt[1] == device: continue else: if name_chk == name: continue lines.append(line) except (IOError, OSError) as exc: msg = "Couldn't read from {0}: {1}" raise CommandExecutionError(msg.format(config, exc)) try: with salt.utils.files.fopen(config, 'wb') as ofile: ofile.writelines(salt.utils.data.encode(lines)) except (IOError, OSError) as exc: msg = "Couldn't write to {0}: {1}" raise CommandExecutionError(msg.format(config, exc)) # Update automount __salt__['cmd.run']('automount -cv') return True def set_automaster( name, device, fstype, opts='', config='/etc/auto_salt', test=False, **kwargs): ''' Verify that this mount is represented in the auto_salt, change the mount to match the data passed, or add the mount if it is not present. CLI Example: .. code-block:: bash salt '*' mount.set_automaster /mnt/foo /dev/sdz1 ext4 ''' # Fix the opts type if it is a list if isinstance(opts, list): opts = ','.join(opts) lines = [] change = False present = False automaster_file = "/etc/auto_master" if not os.path.isfile(config): __salt__['file.touch'](config) __salt__['file.append'](automaster_file, "/-\t\t\t{0}".format(config)) name = "/..{0}".format(name) device_fmt = "{0}:{1}".format(fstype, device) type_opts = "-fstype={0},{1}".format(fstype, opts) if fstype == 'smbfs': device_fmt = device_fmt.replace(fstype, "") try: with salt.utils.files.fopen(config, 'r') as ifile: for line in ifile: line = salt.utils.stringutils.to_unicode(line) if line.startswith('#'): # Commented lines.append(line) continue if not line.strip(): # Blank line lines.append(line) continue comps = line.split() if len(comps) != 3: # Invalid entry lines.append(line) continue if comps[0] == name or comps[2] == device_fmt: # check to see if there are changes # and fix them if there are any present = True if comps[0] != name: change = True comps[0] = name if comps[1] != type_opts: change = True comps[1] = type_opts if comps[2] != device_fmt: change = True comps[2] = device_fmt if change: log.debug( 'auto_master entry for mount point %s needs to be ' 'updated', name ) newline = ( '{0}\t{1}\t{2}\n'.format( name, type_opts, device_fmt) ) lines.append(newline) else: lines.append(line) except (IOError, OSError) as exc: msg = 'Couldn\'t read from {0}: {1}' raise CommandExecutionError(msg.format(config, exc)) if change: if not salt.utils.args.test_mode(test=test, **kwargs): try: with salt.utils.files.fopen(config, 'wb') as ofile: # The line was changed, commit it! ofile.writelines(salt.utils.data.encode(lines)) except (IOError, OSError): msg = 'File not writable {0}' raise CommandExecutionError(msg.format(config)) return 'change' if not change: if present: # The right entry is already here return 'present' else: if not salt.utils.args.test_mode(test=test, **kwargs): # The entry is new, add it to the end of the fstab newline = ( '{0}\t{1}\t{2}\n'.format( name, type_opts, device_fmt) ) lines.append(newline) try: with salt.utils.files.fopen(config, 'wb') as ofile: # The line was changed, commit it! ofile.writelines(salt.utils.data.encode(lines)) except (IOError, OSError): raise CommandExecutionError( 'File not writable {0}'.format( config ) ) return 'new' def automaster(config='/etc/auto_salt'): ''' List the contents of the auto master CLI Example: .. code-block:: bash salt '*' mount.automaster ''' ret = {} if not os.path.isfile(config): return ret with salt.utils.files.fopen(config) as ifile: for line in ifile: line = salt.utils.stringutils.to_unicode(line) if line.startswith('#'): # Commented continue if not line.strip(): # Blank line continue comps = line.split() if len(comps) != 3: # Invalid entry continue prefix = "/.." name = comps[0].replace(prefix, "") device_fmt = comps[2].split(":") opts = comps[1].split(',') ret[name] = {'device': device_fmt[1], 'fstype': opts[0], 'opts': opts[1:]} return ret def remount(name, device, mkmnt=False, fstype='', opts='defaults', user=None): ''' Attempt to remount a device, if the device is not already mounted, mount is called CLI Example: .. code-block:: bash salt '*' mount.remount /mnt/foo /dev/sdz1 True ''' force_mount = False if __grains__['os'] in ['MacOS', 'Darwin']: if opts == 'defaults': opts = 'noowners' if fstype == 'smbfs': force_mount = True if 'AIX' in __grains__['os']: if opts == 'defaults': opts = [] if isinstance(opts, six.string_types): opts = opts.split(',') mnts = active() if name in mnts: # The mount point is mounted, attempt to remount it with the given data if 'remount' not in opts and __grains__['os'] not in ['OpenBSD', 'MacOS', 'Darwin']: opts.append('remount') if force_mount: # We need to force the mount but first we should unmount umount(name, device, user=user) lopts = ','.join(opts) args = '-o {0}'.format(lopts) if fstype: # use of fstype on AIX differs from typical Linux use of # -t functionality AIX uses -v vfsname, -t fstype mounts # all with fstype in /etc/filesystems if 'AIX' in __grains__['os']: args += ' -v {0}'.format(fstype) elif 'solaris' in __grains__['os'].lower(): args += ' -F {0}'.format(fstype) else: args += ' -t {0}'.format(fstype) if __grains__['os'] not in ['OpenBSD', 'MacOS', 'Darwin'] or force_mount: cmd = 'mount {0} {1} {2} '.format(args, device, name) else: cmd = 'mount -u {0} {1} {2} '.format(args, device, name) out = __salt__['cmd.run_all'](cmd, runas=user, python_shell=False) if out['retcode']: return out['stderr'] return True # Mount a filesystem that isn't already return mount(name, device, mkmnt, fstype, opts, user=user) def umount(name, device=None, user=None, util='mount'): ''' Attempt to unmount a device by specifying the directory it is mounted on CLI Example: .. code-block:: bash salt '*' mount.umount /mnt/foo .. versionadded:: 2015.5.0 .. code-block:: bash salt '*' mount.umount /mnt/foo /dev/xvdc1 ''' if util != 'mount': # This functionality used to live in img.umount_image if 'qemu_nbd.clear' in __salt__: if 'img.mnt_{0}'.format(name) in __context__: __salt__['qemu_nbd.clear'](__context__['img.mnt_{0}'.format(name)]) return mnts = active() if name not in mnts: return "{0} does not have anything mounted".format(name) if not device: cmd = 'umount {0}'.format(name) else: cmd = 'umount {0}'.format(device) out = __salt__['cmd.run_all'](cmd, runas=user, python_shell=False) if out['retcode']: return out['stderr'] return True def is_fuse_exec(cmd): ''' Returns true if the command passed is a fuse mountable application. CLI Example: .. code-block:: bash salt '*' mount.is_fuse_exec sshfs ''' cmd_path = salt.utils.path.which(cmd) # No point in running ldd on a command that doesn't exist if not cmd_path: return False elif not salt.utils.path.which('ldd'): raise CommandNotFoundError('ldd') out = __salt__['cmd.run']('ldd {0}'.format(cmd_path), python_shell=False) return 'libfuse' in out def swaps(): ''' Return a dict containing information on active swap .. versionchanged:: 2016.3.2 CLI Example: .. code-block:: bash salt '*' mount.swaps ''' ret = {} if __grains__['kernel'] == 'SunOS': for line in __salt__['cmd.run_stdout']('swap -l').splitlines(): if line.startswith('swapfile'): continue comps = line.split() ret[comps[0]] = {'type': 'device' if comps[0].startswith(('/dev', 'swap')) else 'file', 'size': int(comps[3]), 'used': (int(comps[3]) - int(comps[4])), 'priority': '-'} elif 'AIX' in __grains__['kernel']: for line in __salt__['cmd.run_stdout']('swap -l').splitlines(): if line.startswith('device'): continue comps = line.split() # AIX uses MB for units ret[comps[0]] = {'type': 'device', 'size': int(comps[3][:-2]) * 1024, 'used': (int(comps[3][:-2]) - int(comps[4][:-2])) * 1024, 'priority': '-'} elif __grains__['os'] != 'OpenBSD': with salt.utils.files.fopen('/proc/swaps') as fp_: for line in fp_: line = salt.utils.stringutils.to_unicode(line) if line.startswith('Filename'): continue comps = line.split() ret[comps[0]] = {'type': comps[1], 'size': comps[2], 'used': comps[3], 'priority': comps[4]} else: for line in __salt__['cmd.run_stdout']('swapctl -kl').splitlines(): if line.startswith(('Device', 'Total')): continue swap_type = "file" comps = line.split() if comps[0].startswith('/dev/'): swap_type = "partition" ret[comps[0]] = {'type': swap_type, 'size': comps[1], 'used': comps[2], 'priority': comps[5]} return ret def swapon(name, priority=None): ''' Activate a swap disk .. versionchanged:: 2016.3.2 CLI Example: .. code-block:: bash salt '*' mount.swapon /root/swapfile ''' ret = {} on_ = swaps() if name in on_: ret['stats'] = on_[name] ret['new'] = False return ret if __grains__['kernel'] == 'SunOS': if __grains__['virtual'] != 'zone': __salt__['cmd.run']('swap -a {0}'.format(name), python_shell=False) else: return False else: cmd = 'swapon {0}'.format(name) if priority and 'AIX' not in __grains__['kernel']: cmd += ' -p {0}'.format(priority) __salt__['cmd.run'](cmd, python_shell=False) on_ = swaps() if name in on_: ret['stats'] = on_[name] ret['new'] = True return ret return ret def swapoff(name): ''' Deactivate a named swap mount .. versionchanged:: 2016.3.2 CLI Example: .. code-block:: bash salt '*' mount.swapoff /root/swapfile ''' on_ = swaps() if name in on_: if __grains__['kernel'] == 'SunOS': if __grains__['virtual'] != 'zone': __salt__['cmd.run']('swap -a {0}'.format(name), python_shell=False) else: return False elif __grains__['os'] != 'OpenBSD': __salt__['cmd.run']('swapoff {0}'.format(name), python_shell=False) else: __salt__['cmd.run']('swapctl -d {0}'.format(name), python_shell=False) on_ = swaps() if name in on_: return False return True return None def is_mounted(name): ''' .. versionadded:: 2014.7.0 Provide information if the path is mounted CLI Example: .. code-block:: bash salt '*' mount.is_mounted /mnt/share ''' active_ = active() if name in active_: return True else: return False def read_mount_cache(name): ''' .. versionadded:: 2018.3.0 Provide information if the path is mounted CLI Example: .. code-block:: bash salt '*' mount.read_mount_cache /mnt/share ''' cache = salt.utils.mount.read_cache(__opts__) if cache: if 'mounts' in cache and cache['mounts']: if name in cache['mounts']: return cache['mounts'][name] return {} def write_mount_cache(real_name, device, mkmnt, fstype, mount_opts): ''' .. versionadded:: 2018.3.0 Provide information if the path is mounted :param real_name: The real name of the mount point where the device is mounted. :param device: The device that is being mounted. :param mkmnt: Whether or not the mount point should be created. :param fstype: The file system that is used. :param mount_opts: Additional options used when mounting the device. :return: Boolean if message was sent successfully. CLI Example: .. code-block:: bash salt '*' mount.write_mount_cache /mnt/share /dev/sda1 False ext4 defaults,nosuid ''' cache = salt.utils.mount.read_cache(__opts__) if not cache: cache = {} cache['mounts'] = {} else: if 'mounts' not in cache: cache['mounts'] = {} cache['mounts'][real_name] = {'device': device, 'fstype': fstype, 'mkmnt': mkmnt, 'opts': mount_opts} cache_write = salt.utils.mount.write_cache(cache, __opts__) if cache_write: return True else: raise CommandExecutionError('Unable to write mount cache.') def delete_mount_cache(real_name): ''' .. versionadded:: 2018.3.0 Provide information if the path is mounted CLI Example: .. code-block:: bash salt '*' mount.delete_mount_cache /mnt/share ''' cache = salt.utils.mount.read_cache(__opts__) if cache: if 'mounts' in cache: if real_name in cache['mounts']: del cache['mounts'][real_name] cache_write = salt.utils.mount.write_cache(cache, __opts__) if not cache_write: raise CommandExecutionError('Unable to write mount cache.') return True def _filesystems(config='/etc/filesystems', leading_key=True): ''' Return the contents of the filesystems in an OrderedDict config File containing filesystem infomation leading_key True return dictionary keyed by 'name' and value as dictionary with other keys, values (name excluded) OrderedDict({ '/dir' : OrderedDict({'dev': '/dev/hd8', .... }})) False return dictionary keyed by 'name' and value as dictionary with all keys, values (name included) OrderedDict({ '/dir' : OrderedDict({'name': '/dir', 'dev': '/dev/hd8', ... })}) ''' ret = OrderedDict() lines = [] parsing_block = False if not os.path.isfile(config) or 'AIX' not in __grains__['kernel']: return ret # read in block of filesystems, block starts with '/' till empty line with salt.utils.files.fopen(config) as ifile: for line in ifile: line = salt.utils.stringutils.to_unicode(line) # skip till first entry if not line.startswith('/') and not parsing_block: continue if line.startswith('/'): parsing_block = True lines.append(line) elif not line.split(): parsing_block = False try: entry = _FileSystemsEntry.dict_from_lines( lines, _FileSystemsEntry.compatibility_keys) lines = [] if 'opts' in entry: entry['opts'] = entry['opts'].split(',') while entry['name'] in ret: entry['name'] += '_' if leading_key: ret[entry.pop('name')] = entry else: ret[entry['name']] = entry except _FileSystemsEntry.ParseError: pass else: lines.append(line) return ret def filesystems(config='/etc/filesystems'): ''' .. versionadded:: 2018.3.3 List the contents of the filesystems CLI Example: .. code-block:: bash salt '*' mount.filesystems ''' ret = {} if 'AIX' not in __grains__['kernel']: return ret ret_dict = _filesystems(config) if ret_dict: ret_key = next(iter(ret_dict.keys())) ret = {ret_key: dict(ret_dict[ret_key])} return ret def set_filesystems( name, device, vfstype, opts='-', mount='true', config='/etc/filesystems', test=False, match_on='auto', **kwargs): ''' .. versionadded:: 2018.3.3 Verify that this mount is represented in the filesystems, change the mount to match the data passed, or add the mount if it is not present on AIX Provide information if the path is mounted :param name: The name of the mount point where the device is mounted. :param device: The device that is being mounted. :param vfstype: The file system that is used (AIX has two fstypes, fstype and vfstype - similar to Linux fstype) :param opts: Additional options used when mounting the device. :param mount: Mount if not mounted, default True. :param config: Configuration file, default /etc/filesystems. :param match: File systems type to match on, default auto CLI Example: .. code-block:: bash salt '*' mount.set_filesystems /mnt/foo /dev/sdz1 jfs2 ''' # Fix the opts type if it is a list if isinstance(opts, list): opts = ','.join(opts) # preserve arguments for updating entry_args = { 'name': name, 'dev': device.replace('\\ ', '\\040'), 'vfstype': vfstype, 'opts': opts, 'mount': mount, } view_lines = [] ret = None if 'AIX' not in __grains__['kernel']: return ret # Transform match_on into list--items will be checked later if isinstance(match_on, list): pass elif not isinstance(match_on, six.string_types): raise CommandExecutionError('match_on must be a string or list of strings') elif match_on == 'auto': # Try to guess right criteria for auto.... # added IBM types from sys/vmount.h after btrfs # NOTE: missing some special fstypes here specialFSes = frozenset([ 'none', 'tmpfs', 'sysfs', 'proc', 'fusectl', 'debugfs', 'securityfs', 'devtmpfs', 'cgroup', 'btrfs', 'cdrfs', 'procfs', 'jfs', 'jfs2', 'nfs', 'sfs', 'nfs3', 'cachefs', 'udfs', 'cifs', 'namefs', 'pmemfs', 'ahafs', 'nfs4', 'autofs', 'stnfs']) if vfstype in specialFSes: match_on = ['name'] else: match_on = ['dev'] else: match_on = [match_on] # generate entry and criteria objects, handle invalid keys in match_on entry_ip = _FileSystemsEntry.from_line(entry_args, kwargs) try: criteria = entry_ip.pick(match_on) except KeyError: filterFn = lambda key: key not in _FileSystemsEntry.compatibility_keys invalid_keys = filter(filterFn, match_on) raise CommandExecutionError('Unrecognized keys in match_on: "{0}"'.format(invalid_keys)) # parse file, use ret to cache status if not os.path.isfile(config): raise CommandExecutionError('Bad config file "{0}"'.format(config)) # read in block of filesystem, block starts with '/' till empty line try: fsys_filedict = _filesystems(config, False) for fsys_view in six.viewitems(fsys_filedict): if criteria.match(fsys_view): ret = 'present' if entry_ip.match(fsys_view): view_lines.append(fsys_view) else: ret = 'change' kv = entry_ip['name'] view_lines.append((kv, entry_ip)) else: view_lines.append(fsys_view) except (IOError, OSError) as exc: raise CommandExecutionError('Couldn\'t read from {0}: {1}'.format(config, exc)) # add line if not present or changed if ret is None: for dict_view in six.viewitems(entry_ip.dict_from_entry()): view_lines.append(dict_view) ret = 'new' if ret != 'present': # ret in ['new', 'change']: try: with salt.utils.files.fopen(config, 'wb') as ofile: # The line was changed, commit it! for fsys_view in view_lines: entry = fsys_view[1] mystrg = _FileSystemsEntry.dict_to_lines(entry) ofile.writelines(salt.utils.data.encode(mystrg)) except (IOError, OSError): raise CommandExecutionError('File not writable {0}'.format(config)) return ret def rm_filesystems(name, device, config='/etc/filesystems'): ''' .. versionadded:: 2018.3.3 Remove the mount point from the filesystems CLI Example: .. code-block:: bash salt '*' mount.rm_filesystems /mnt/foo /dev/sdg ''' modified = False view_lines = [] if 'AIX' not in __grains__['kernel']: return modified criteria = _FileSystemsEntry(name=name, dev=device) try: fsys_filedict = _filesystems(config, False) for fsys_view in six.viewitems(fsys_filedict): try: if criteria.match(fsys_view): modified = True else: view_lines.append(fsys_view) except _FileSystemsEntry.ParseError: view_lines.append(fsys_view) except (IOError, OSError) as exc: raise CommandExecutionError("Couldn't read from {0}: {1}".format(config, exc)) if modified: try: with salt.utils.files.fopen(config, 'wb') as ofile: for fsys_view in view_lines: entry = fsys_view[1] mystrg = _FileSystemsEntry.dict_to_lines(entry) ofile.writelines(salt.utils.data.encode(mystrg)) except (IOError, OSError) as exc: raise CommandExecutionError("Couldn't write to {0}: {1}".format(config, exc)) return modified
saltstack/salt
salt/modules/mount.py
remount
python
def remount(name, device, mkmnt=False, fstype='', opts='defaults', user=None): ''' Attempt to remount a device, if the device is not already mounted, mount is called CLI Example: .. code-block:: bash salt '*' mount.remount /mnt/foo /dev/sdz1 True ''' force_mount = False if __grains__['os'] in ['MacOS', 'Darwin']: if opts == 'defaults': opts = 'noowners' if fstype == 'smbfs': force_mount = True if 'AIX' in __grains__['os']: if opts == 'defaults': opts = [] if isinstance(opts, six.string_types): opts = opts.split(',') mnts = active() if name in mnts: # The mount point is mounted, attempt to remount it with the given data if 'remount' not in opts and __grains__['os'] not in ['OpenBSD', 'MacOS', 'Darwin']: opts.append('remount') if force_mount: # We need to force the mount but first we should unmount umount(name, device, user=user) lopts = ','.join(opts) args = '-o {0}'.format(lopts) if fstype: # use of fstype on AIX differs from typical Linux use of # -t functionality AIX uses -v vfsname, -t fstype mounts # all with fstype in /etc/filesystems if 'AIX' in __grains__['os']: args += ' -v {0}'.format(fstype) elif 'solaris' in __grains__['os'].lower(): args += ' -F {0}'.format(fstype) else: args += ' -t {0}'.format(fstype) if __grains__['os'] not in ['OpenBSD', 'MacOS', 'Darwin'] or force_mount: cmd = 'mount {0} {1} {2} '.format(args, device, name) else: cmd = 'mount -u {0} {1} {2} '.format(args, device, name) out = __salt__['cmd.run_all'](cmd, runas=user, python_shell=False) if out['retcode']: return out['stderr'] return True # Mount a filesystem that isn't already return mount(name, device, mkmnt, fstype, opts, user=user)
Attempt to remount a device, if the device is not already mounted, mount is called CLI Example: .. code-block:: bash salt '*' mount.remount /mnt/foo /dev/sdz1 True
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/mount.py#L1233-L1288
[ "def active(extended=False):\n '''\n List the active mounts.\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' mount.active\n '''\n ret = {}\n if __grains__['os'] == 'FreeBSD':\n _active_mounts_freebsd(ret)\n elif 'AIX' in __grains__['kernel']:\n _active_mounts_aix(ret)\n elif __grains__['kernel'] == 'SunOS':\n _active_mounts_solaris(ret)\n elif __grains__['os'] == 'OpenBSD':\n _active_mounts_openbsd(ret)\n elif __grains__['os'] in ['MacOS', 'Darwin']:\n _active_mounts_darwin(ret)\n else:\n if extended:\n try:\n _active_mountinfo(ret)\n except CommandExecutionError:\n _active_mounts(ret)\n else:\n _active_mounts(ret)\n return ret\n", "def mount(name, device, mkmnt=False, fstype='', opts='defaults', user=None, util='mount'):\n '''\n Mount a device\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' mount.mount /mnt/foo /dev/sdz1 True\n '''\n if util != 'mount':\n # This functionality used to live in img.mount_image\n if util == 'guestfs':\n return __salt__['guestfs.mount'](name, root=device)\n elif util == 'qemu_nbd':\n mnt = __salt__['qemu_nbd.init'](name, device)\n if not mnt:\n return False\n first = next(six.iterkeys(mnt))\n __context__['img.mnt_{0}'.format(first)] = mnt\n return first\n return False\n\n # Darwin doesn't expect defaults when mounting without other options\n if 'defaults' in opts and __grains__['os'] in ['MacOS', 'Darwin', 'AIX']:\n opts = None\n\n if isinstance(opts, six.string_types):\n opts = opts.split(',')\n\n if not os.path.exists(name) and mkmnt:\n __salt__['file.mkdir'](name, user=user)\n\n args = ''\n if opts is not None:\n lopts = ','.join(opts)\n args = '-o {0}'.format(lopts)\n\n if fstype:\n # use of fstype on AIX differs from typical Linux use of -t\n # functionality AIX uses -v vfsname, -t fstype mounts all with\n # fstype in /etc/filesystems\n if 'AIX' in __grains__['os']:\n args += ' -v {0}'.format(fstype)\n elif 'solaris' in __grains__['os'].lower():\n args += ' -F {0}'.format(fstype)\n else:\n args += ' -t {0}'.format(fstype)\n\n cmd = 'mount {0} {1} {2} '.format(args, device, name)\n out = __salt__['cmd.run_all'](cmd, runas=user, python_shell=False)\n if out['retcode']:\n return out['stderr']\n return True\n", "def umount(name, device=None, user=None, util='mount'):\n '''\n Attempt to unmount a device by specifying the directory it is mounted on\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' mount.umount /mnt/foo\n\n .. versionadded:: 2015.5.0\n .. code-block:: bash\n\n salt '*' mount.umount /mnt/foo /dev/xvdc1\n '''\n if util != 'mount':\n # This functionality used to live in img.umount_image\n if 'qemu_nbd.clear' in __salt__:\n if 'img.mnt_{0}'.format(name) in __context__:\n __salt__['qemu_nbd.clear'](__context__['img.mnt_{0}'.format(name)])\n return\n\n mnts = active()\n if name not in mnts:\n return \"{0} does not have anything mounted\".format(name)\n\n if not device:\n cmd = 'umount {0}'.format(name)\n else:\n cmd = 'umount {0}'.format(device)\n out = __salt__['cmd.run_all'](cmd, runas=user, python_shell=False)\n if out['retcode']:\n return out['stderr']\n return True\n" ]
# -*- coding: utf-8 -*- ''' Salt module to manage Unix mounts and the fstab file ''' # Import python libs from __future__ import absolute_import, print_function, unicode_literals import os import re import logging # Import salt libs import salt.utils.args import salt.utils.data import salt.utils.files import salt.utils.path import salt.utils.platform import salt.utils.mount import salt.utils.stringutils from salt.utils.odict import OrderedDict from salt.exceptions import CommandNotFoundError, CommandExecutionError # Import 3rd-party libs from salt.ext import six from salt.ext.six.moves import filter, zip # pylint: disable=import-error,redefined-builtin # Set up logger log = logging.getLogger(__name__) # Define the module's virtual name __virtualname__ = 'mount' def __virtual__(): ''' Only load on POSIX-like systems ''' # Disable on Windows, a specific file module exists: if salt.utils.platform.is_windows(): return (False, 'The mount module cannot be loaded: not a POSIX-like system.') return True def _list_mounts(): ret = {} if __grains__['os'] in ['MacOS', 'Darwin']: mounts = __salt__['cmd.run_stdout']('mount') else: mounts = __salt__['cmd.run_stdout']('mount -l') for line in mounts.split('\n'): comps = re.sub(r"\s+", " ", line).split() if len(comps) >= 3: ret[comps[2]] = comps[0] return ret def _active_mountinfo(ret): _list = _list_mounts() filename = '/proc/self/mountinfo' if not os.access(filename, os.R_OK): msg = 'File not readable {0}' raise CommandExecutionError(msg.format(filename)) if 'disk.blkid' not in __context__: __context__['disk.blkid'] = __salt__['disk.blkid']() blkid_info = __context__['disk.blkid'] with salt.utils.files.fopen(filename) as ifile: for line in ifile: comps = salt.utils.stringutils.to_unicode(line).split() device = comps[2].split(':') # each line can have any number of # optional parameters, we use the # location of the separator field to # determine the location of the elements # after it. _sep = comps.index('-') device_name = comps[_sep + 2] device_uuid = None device_label = None if device_name: device_uuid = blkid_info.get(device_name, {}).get('UUID') device_uuid = device_uuid and device_uuid.lower() device_label = blkid_info.get(device_name, {}).get('LABEL') ret[comps[4]] = {'mountid': comps[0], 'parentid': comps[1], 'major': device[0], 'minor': device[1], 'root': comps[3], 'opts': _resolve_user_group_names(comps[5].split(',')), 'fstype': comps[_sep + 1], 'device': device_name.replace('\\040', '\\ '), 'alt_device': _list.get(comps[4], None), 'superopts': _resolve_user_group_names(comps[_sep + 3].split(',')), 'device_uuid': device_uuid, 'device_label': device_label} return ret def _active_mounts(ret): ''' List active mounts on Linux systems ''' _list = _list_mounts() filename = '/proc/self/mounts' if not os.access(filename, os.R_OK): msg = 'File not readable {0}' raise CommandExecutionError(msg.format(filename)) with salt.utils.files.fopen(filename) as ifile: for line in ifile: comps = salt.utils.stringutils.to_unicode(line).split() ret[comps[1]] = {'device': comps[0], 'alt_device': _list.get(comps[1], None), 'fstype': comps[2], 'opts': _resolve_user_group_names(comps[3].split(','))} return ret def _active_mounts_aix(ret): ''' List active mounts on AIX systems ''' for line in __salt__['cmd.run_stdout']('mount -p').split('\n'): comps = re.sub(r"\s+", " ", line).split() if comps: if comps[0] == 'node' or comps[0] == '--------': continue comps_len = len(comps) if line.startswith((' ', '\t')): curr_opts = _resolve_user_group_names(comps[6].split(',')) if 7 == comps_len else [] if curr_opts: ret[comps[1]] = {'device': comps[0], 'fstype': comps[2], 'opts': curr_opts} else: ret[comps[1]] = {'device': comps[0], 'fstype': comps[2]} else: curr_opts = _resolve_user_group_names(comps[7].split(',')) if 8 == comps_len else [] if curr_opts: ret[comps[2]] = {'node': comps[0], 'device': comps[1], 'fstype': comps[3], 'opts': curr_opts} else: ret[comps[2]] = {'node': comps[0], 'device': comps[1], 'fstype': comps[3]} return ret def _active_mounts_freebsd(ret): ''' List active mounts on FreeBSD systems ''' for line in __salt__['cmd.run_stdout']('mount -p').split('\n'): comps = re.sub(r"\s+", " ", line).split() ret[comps[1]] = {'device': comps[0], 'fstype': comps[2], 'opts': _resolve_user_group_names(comps[3].split(','))} return ret def _active_mounts_solaris(ret): ''' List active mounts on Solaris systems ''' for line in __salt__['cmd.run_stdout']('mount -v').split('\n'): comps = re.sub(r"\s+", " ", line).split() ret[comps[2]] = {'device': comps[0], 'fstype': comps[4], 'opts': _resolve_user_group_names(comps[5].split('/'))} return ret def _active_mounts_openbsd(ret): ''' List active mounts on OpenBSD systems ''' for line in __salt__['cmd.run_stdout']('mount -v').split('\n'): comps = re.sub(r"\s+", " ", line).split() parens = re.findall(r'\((.*?)\)', line, re.DOTALL) if len(parens) > 1: nod = __salt__['cmd.run_stdout']('ls -l {0}'.format(comps[0])) nod = ' '.join(nod.split()).split(" ") ret[comps[3]] = {'device': comps[0], 'fstype': comps[5], 'opts': _resolve_user_group_names(parens[1].split(", ")), 'major': six.text_type(nod[4].strip(",")), 'minor': six.text_type(nod[5]), 'device_uuid': parens[0]} else: ret[comps[2]] = {'device': comps[0], 'fstype': comps[4], 'opts': _resolve_user_group_names(parens[0].split(", "))} return ret def _active_mounts_darwin(ret): ''' List active mounts on Mac OS systems ''' for line in __salt__['cmd.run_stdout']('mount').split('\n'): comps = re.sub(r"\s+", " ", line).split() parens = re.findall(r'\((.*?)\)', line, re.DOTALL)[0].split(", ") ret[comps[2]] = {'device': comps[0], 'fstype': parens[0], 'opts': _resolve_user_group_names(parens[1:])} return ret def _resolve_user_group_names(opts): ''' Resolve user and group names in related opts ''' name_id_opts = {'uid': 'user.info', 'gid': 'group.info'} for ind, opt in enumerate(opts): if opt.split('=')[0] in name_id_opts: _givenid = opt.split('=')[1] _param = opt.split('=')[0] _id = _givenid if not re.match('[0-9]+$', _givenid): _info = __salt__[name_id_opts[_param]](_givenid) if _info and _param in _info: _id = _info[_param] opts[ind] = _param + '=' + six.text_type(_id) opts[ind] = opts[ind].replace('\\040', '\\ ') return opts def active(extended=False): ''' List the active mounts. CLI Example: .. code-block:: bash salt '*' mount.active ''' ret = {} if __grains__['os'] == 'FreeBSD': _active_mounts_freebsd(ret) elif 'AIX' in __grains__['kernel']: _active_mounts_aix(ret) elif __grains__['kernel'] == 'SunOS': _active_mounts_solaris(ret) elif __grains__['os'] == 'OpenBSD': _active_mounts_openbsd(ret) elif __grains__['os'] in ['MacOS', 'Darwin']: _active_mounts_darwin(ret) else: if extended: try: _active_mountinfo(ret) except CommandExecutionError: _active_mounts(ret) else: _active_mounts(ret) return ret class _fstab_entry(object): ''' Utility class for manipulating fstab entries. Primarily we're parsing, formatting, and comparing lines. Parsing emits dicts expected from fstab() or raises a ValueError. Note: We'll probably want to use os.normpath and os.normcase on 'name' ''' class ParseError(ValueError): ''' Error raised when a line isn't parsible as an fstab entry ''' fstab_keys = ('device', 'name', 'fstype', 'opts', 'dump', 'pass_num') # preserve data format compatibility_keys = ('device', 'name', 'fstype', 'opts', 'dump', 'pass') fstab_format = '{device}\t\t{name}\t{fstype}\t{opts}\t{dump} {pass_num}\n' @classmethod def dict_from_line(cls, line, keys=fstab_keys): if len(keys) != 6: raise ValueError('Invalid key array: {0}'.format(keys)) if line.startswith('#'): raise cls.ParseError("Comment!") comps = line.split() if len(comps) < 4 or len(comps) > 6: raise cls.ParseError("Invalid Entry!") comps.extend(['0'] * (len(keys) - len(comps))) return dict(zip(keys, comps)) @classmethod def from_line(cls, *args, **kwargs): return cls(** cls.dict_from_line(*args, **kwargs)) @classmethod def dict_to_line(cls, entry): return cls.fstab_format.format(**entry) def __str__(self): ''' String value, only works for full repr ''' return self.dict_to_line(self.criteria) def __repr__(self): ''' Always works ''' return repr(self.criteria) def pick(self, keys): ''' Returns an instance with just those keys ''' subset = dict([(key, self.criteria[key]) for key in keys]) return self.__class__(**subset) def __init__(self, **criteria): ''' Store non-empty, non-null values to use as filter ''' items = [key_value for key_value in six.iteritems(criteria) if key_value[1] is not None] items = [(key_value1[0], six.text_type(key_value1[1])) for key_value1 in items] self.criteria = dict(items) @staticmethod def norm_path(path): ''' Resolve equivalent paths equivalently ''' return os.path.normcase(os.path.normpath(path)) def match(self, line): ''' Compare potentially partial criteria against line ''' entry = self.dict_from_line(line) for key, value in six.iteritems(self.criteria): if entry[key] != value: return False return True class _vfstab_entry(object): ''' Utility class for manipulating vfstab entries. Primarily we're parsing, formatting, and comparing lines. Parsing emits dicts expected from fstab() or raises a ValueError. Note: We'll probably want to use os.normpath and os.normcase on 'name' Note: This parses vfstab entries on Solaris like systems #device device mount FS fsck mount mount #to mount to fsck point type pass at boot options # /devices - /devices devfs - no - ''' class ParseError(ValueError): '''Error raised when a line isn't parsible as an fstab entry''' vfstab_keys = ('device', 'device_fsck', 'name', 'fstype', 'pass_fsck', 'mount_at_boot', 'opts') # NOTE: weird formatting to match default spacing on Solaris vfstab_format = '{device:<11} {device_fsck:<3} {name:<19} {fstype:<8} {pass_fsck:<3} {mount_at_boot:<6} {opts}\n' @classmethod def dict_from_line(cls, line): if line.startswith('#'): raise cls.ParseError("Comment!") comps = line.split() if len(comps) != 7: raise cls.ParseError("Invalid Entry!") return dict(zip(cls.vfstab_keys, comps)) @classmethod def from_line(cls, *args, **kwargs): return cls(** cls.dict_from_line(*args, **kwargs)) @classmethod def dict_to_line(cls, entry): return cls.vfstab_format.format(**entry) def __str__(self): ''' String value, only works for full repr ''' return self.dict_to_line(self.criteria) def __repr__(self): ''' Always works ''' return repr(self.criteria) def pick(self, keys): ''' Returns an instance with just those keys ''' subset = dict([(key, self.criteria[key]) for key in keys]) return self.__class__(**subset) def __init__(self, **criteria): ''' Store non-empty, non-null values to use as filter ''' items = [key_value for key_value in six.iteritems(criteria) if key_value[1] is not None] items = [(key_value1[0], six.text_type(key_value1[1])) for key_value1 in items] self.criteria = dict(items) @staticmethod def norm_path(path): ''' Resolve equivalent paths equivalently ''' return os.path.normcase(os.path.normpath(path)) def match(self, line): ''' Compare potentially partial criteria against line ''' entry = self.dict_from_line(line) for key, value in six.iteritems(self.criteria): if entry[key] != value: return False return True class _FileSystemsEntry(object): ''' Utility class for manipulating filesystem entries. Primarily we're parsing, formatting, and comparing lines. Parsing emits dicts expected from fstab() or raises a ValueError. Note: We'll probably want to use os.normpath and os.normcase on 'name' ''' class ParseError(ValueError): ''' Error raised when a line isn't parsible as an fstab entry ''' filesystems_keys = ('device', 'name', 'fstype', 'vfstype', 'opts', 'mount') # preserve data format of filesystems compatibility_keys = ('dev', 'dev', 'name', 'fstype', 'vfstype', 'opts', 'mount', 'type', 'vfs', 'account', 'boot', 'check', 'free', 'nodename', 'quota', 'size', 'vol', 'log') @classmethod def dict_from_lines(cls, lines, keys=filesystems_keys): if len(lines) < 2: raise ValueError('Invalid number of lines: {0}'.format(lines)) if not keys: # if empty force default filesystems_keys keys = _FileSystemsEntry.filesystems_keys elif len(keys) < 6: raise ValueError('Invalid key name array: {0}'.format(keys)) blk_lines = lines orddict = OrderedDict() orddict['name'] = blk_lines[0].split(':')[0].strip() blk_lines.pop(0) for line in blk_lines: if line.startswith('#'): raise cls.ParseError("Comment!") comps = line.split('= ') if len(comps) != 2: raise cls.ParseError("Invalid Entry!") key_name = comps[0].strip() if key_name in keys: orddict[key_name] = comps[1].strip() else: raise ValueError('Invalid name for use in filesystems: {0}'.format(key_name)) return orddict @classmethod def dict_from_cmd_line(cls, ipargs, keys): cmdln_dict = ipargs if keys: for key, value in keys: # ignore unknown or local scope keys if key.startswith('__'): continue if key in _FileSystemsEntry.compatibility_keys: cmdln_dict[key] = value return cmdln_dict @classmethod def from_line(cls, *args, **kwargs): return cls(** cls.dict_from_cmd_line(*args, **kwargs)) @classmethod def dict_to_lines(cls, fsys_dict_entry): entry = fsys_dict_entry strg_out = entry['name'] + ':' + os.linesep for k, v in six.viewitems(entry): if 'name' not in k: strg_out += '\t{0}\t\t= {1}'.format(k, v) + os.linesep strg_out += os.linesep return six.text_type(strg_out) def dict_from_entry(self): ret = OrderedDict() ret[self.criteria['name']] = self.criteria return ret def __str__(self): ''' String value, only works for full repr ''' return self.dict_to_lines(self.criteria) def __repr__(self): ''' Always works ''' return repr(self.criteria) def pick(self, keys): ''' Returns an instance with just those keys ''' subset = dict([(key, self.criteria[key]) for key in keys]) return self.__class__(**subset) def __init__(self, **criteria): ''' Store non-empty, non-null values to use as filter ''' items = [key_value for key_value in six.iteritems(criteria) if key_value[1] is not None] items = [(key_value1[0], six.text_type(key_value1[1])) for key_value1 in items] self.criteria = OrderedDict(items) @staticmethod def norm_path(path): ''' Resolve equivalent paths equivalently ''' return os.path.normcase(os.path.normpath(path)) def match(self, fsys_view): ''' Compare potentially partial criteria against built filesystems entry dictionary ''' evalue_dict = fsys_view[1] for key, value in six.viewitems(self.criteria): if key in evalue_dict: if evalue_dict[key] != value: return False else: return False return True def __getitem__(self, key): ''' Return value for input key ''' return self.criteria[key] def fstab(config='/etc/fstab'): ''' .. versionchanged:: 2016.3.2 List the contents of the fstab CLI Example: .. code-block:: bash salt '*' mount.fstab ''' ret = {} if not os.path.isfile(config): return ret with salt.utils.files.fopen(config) as ifile: for line in ifile: line = salt.utils.stringutils.to_unicode(line) try: if __grains__['kernel'] == 'SunOS': # Note: comments use in default vfstab file! if line[0] == '#': continue entry = _vfstab_entry.dict_from_line( line) else: entry = _fstab_entry.dict_from_line( line, _fstab_entry.compatibility_keys) entry['opts'] = entry['opts'].split(',') while entry['name'] in ret: entry['name'] += '_' ret[entry.pop('name')] = entry except _fstab_entry.ParseError: pass except _vfstab_entry.ParseError: pass return ret def vfstab(config='/etc/vfstab'): ''' .. versionadded:: 2016.3.2 List the contents of the vfstab CLI Example: .. code-block:: bash salt '*' mount.vfstab ''' # NOTE: vfstab is a wrapper for fstab return fstab(config) def rm_fstab(name, device, config='/etc/fstab'): ''' .. versionchanged:: 2016.3.2 Remove the mount point from the fstab CLI Example: .. code-block:: bash salt '*' mount.rm_fstab /mnt/foo /dev/sdg ''' modified = False if __grains__['kernel'] == 'SunOS': criteria = _vfstab_entry(name=name, device=device) else: criteria = _fstab_entry(name=name, device=device) lines = [] try: with salt.utils.files.fopen(config, 'r') as ifile: for line in ifile: line = salt.utils.stringutils.to_unicode(line) try: if criteria.match(line): modified = True else: lines.append(line) except _fstab_entry.ParseError: lines.append(line) except _vfstab_entry.ParseError: lines.append(line) except (IOError, OSError) as exc: msg = "Couldn't read from {0}: {1}" raise CommandExecutionError(msg.format(config, exc)) if modified: try: with salt.utils.files.fopen(config, 'wb') as ofile: ofile.writelines(salt.utils.data.encode(lines)) except (IOError, OSError) as exc: msg = "Couldn't write to {0}: {1}" raise CommandExecutionError(msg.format(config, exc)) # Note: not clear why we always return 'True' # --just copying previous behavior at this point... return True def rm_vfstab(name, device, config='/etc/vfstab'): ''' .. versionadded:: 2016.3.2 Remove the mount point from the vfstab CLI Example: .. code-block:: bash salt '*' mount.rm_vfstab /mnt/foo /device/c0t0d0p0 ''' ## NOTE: rm_vfstab is a wrapper for rm_fstab return rm_fstab(name, device, config) def set_fstab( name, device, fstype, opts='defaults', dump=0, pass_num=0, config='/etc/fstab', test=False, match_on='auto', **kwargs): ''' Verify that this mount is represented in the fstab, change the mount to match the data passed, or add the mount if it is not present. CLI Example: .. code-block:: bash salt '*' mount.set_fstab /mnt/foo /dev/sdz1 ext4 ''' # Fix the opts type if it is a list if isinstance(opts, list): opts = ','.join(opts) # preserve arguments for updating entry_args = { 'name': name, 'device': device.replace('\\ ', '\\040'), 'fstype': fstype, 'opts': opts.replace('\\ ', '\\040'), 'dump': dump, 'pass_num': pass_num, } lines = [] ret = None # Transform match_on into list--items will be checked later if isinstance(match_on, list): pass elif not isinstance(match_on, six.string_types): msg = 'match_on must be a string or list of strings' raise CommandExecutionError(msg) elif match_on == 'auto': # Try to guess right criteria for auto.... # NOTE: missing some special fstypes here specialFSes = frozenset([ 'none', 'tmpfs', 'sysfs', 'proc', 'fusectl', 'debugfs', 'securityfs', 'devtmpfs', 'cgroup', 'btrfs']) if fstype in specialFSes: match_on = ['name'] else: match_on = ['device'] else: match_on = [match_on] # generate entry and criteria objects, handle invalid keys in match_on entry = _fstab_entry(**entry_args) try: criteria = entry.pick(match_on) except KeyError: filterFn = lambda key: key not in _fstab_entry.fstab_keys invalid_keys = filter(filterFn, match_on) msg = 'Unrecognized keys in match_on: "{0}"'.format(invalid_keys) raise CommandExecutionError(msg) # parse file, use ret to cache status if not os.path.isfile(config): raise CommandExecutionError('Bad config file "{0}"'.format(config)) try: with salt.utils.files.fopen(config, 'r') as ifile: for line in ifile: line = salt.utils.stringutils.to_unicode(line) try: if criteria.match(line): # Note: If ret isn't None here, # we've matched multiple lines ret = 'present' if entry.match(line): lines.append(line) else: ret = 'change' lines.append(six.text_type(entry)) else: lines.append(line) except _fstab_entry.ParseError: lines.append(line) except (IOError, OSError) as exc: msg = 'Couldn\'t read from {0}: {1}' raise CommandExecutionError(msg.format(config, exc)) # add line if not present or changed if ret is None: lines.append(six.text_type(entry)) ret = 'new' if ret != 'present': # ret in ['new', 'change']: if not salt.utils.args.test_mode(test=test, **kwargs): try: with salt.utils.files.fopen(config, 'wb') as ofile: # The line was changed, commit it! ofile.writelines(salt.utils.data.encode(lines)) except (IOError, OSError): msg = 'File not writable {0}' raise CommandExecutionError(msg.format(config)) return ret def set_vfstab( name, device, fstype, opts='-', device_fsck='-', pass_fsck='-', mount_at_boot='yes', config='/etc/vfstab', test=False, match_on='auto', **kwargs): ''' ..verionadded:: 2016.3.2 Verify that this mount is represented in the fstab, change the mount to match the data passed, or add the mount if it is not present. CLI Example: .. code-block:: bash salt '*' mount.set_vfstab /mnt/foo /device/c0t0d0p0 ufs ''' # Fix the opts type if it is a list if isinstance(opts, list): opts = ','.join(opts) # Map unknown values for mount_at_boot to no if mount_at_boot != 'yes': mount_at_boot = 'no' # preserve arguments for updating entry_args = { 'name': name, 'device': device, 'fstype': fstype, 'opts': opts, 'device_fsck': device_fsck, 'pass_fsck': pass_fsck, 'mount_at_boot': mount_at_boot, } lines = [] ret = None # Transform match_on into list--items will be checked later if isinstance(match_on, list): pass elif not isinstance(match_on, six.string_types): msg = 'match_on must be a string or list of strings' raise CommandExecutionError(msg) elif match_on == 'auto': # Try to guess right criteria for auto.... # NOTE: missing some special fstypes here specialFSes = frozenset([ 'devfs', 'proc', 'ctfs', 'objfs', 'sharefs', 'fs', 'tmpfs']) if fstype in specialFSes: match_on = ['name'] else: match_on = ['device'] else: match_on = [match_on] # generate entry and criteria objects, handle invalid keys in match_on entry = _vfstab_entry(**entry_args) try: criteria = entry.pick(match_on) except KeyError: filterFn = lambda key: key not in _vfstab_entry.vfstab_keys invalid_keys = filter(filterFn, match_on) msg = 'Unrecognized keys in match_on: "{0}"'.format(invalid_keys) raise CommandExecutionError(msg) # parse file, use ret to cache status if not os.path.isfile(config): raise CommandExecutionError('Bad config file "{0}"'.format(config)) try: with salt.utils.files.fopen(config, 'r') as ifile: for line in ifile: line = salt.utils.stringutils.to_unicode(line) try: if criteria.match(line): # Note: If ret isn't None here, # we've matched multiple lines ret = 'present' if entry.match(line): lines.append(line) else: ret = 'change' lines.append(six.text_type(entry)) else: lines.append(line) except _vfstab_entry.ParseError: lines.append(line) except (IOError, OSError) as exc: msg = 'Couldn\'t read from {0}: {1}' raise CommandExecutionError(msg.format(config, exc)) # add line if not present or changed if ret is None: lines.append(six.text_type(entry)) ret = 'new' if ret != 'present': # ret in ['new', 'change']: if not salt.utils.args.test_mode(test=test, **kwargs): try: with salt.utils.files.fopen(config, 'wb') as ofile: # The line was changed, commit it! ofile.writelines(salt.utils.data.encode(lines)) except (IOError, OSError): msg = 'File not writable {0}' raise CommandExecutionError(msg.format(config)) return ret def rm_automaster(name, device, config='/etc/auto_salt'): ''' Remove the mount point from the auto_master CLI Example: .. code-block:: bash salt '*' mount.rm_automaster /mnt/foo /dev/sdg ''' contents = automaster(config) if name not in contents: return True # The entry is present, get rid of it lines = [] try: with salt.utils.files.fopen(config, 'r') as ifile: for line in ifile: line = salt.utils.stringutils.to_unicode(line) if line.startswith('#'): # Commented lines.append(line) continue if not line.strip(): # Blank line lines.append(line) continue comps = line.split() if len(comps) != 3: # Invalid entry lines.append(line) continue comps = line.split() prefix = "/.." name_chk = comps[0].replace(prefix, "") device_fmt = comps[2].split(":") if device: if name_chk == name and device_fmt[1] == device: continue else: if name_chk == name: continue lines.append(line) except (IOError, OSError) as exc: msg = "Couldn't read from {0}: {1}" raise CommandExecutionError(msg.format(config, exc)) try: with salt.utils.files.fopen(config, 'wb') as ofile: ofile.writelines(salt.utils.data.encode(lines)) except (IOError, OSError) as exc: msg = "Couldn't write to {0}: {1}" raise CommandExecutionError(msg.format(config, exc)) # Update automount __salt__['cmd.run']('automount -cv') return True def set_automaster( name, device, fstype, opts='', config='/etc/auto_salt', test=False, **kwargs): ''' Verify that this mount is represented in the auto_salt, change the mount to match the data passed, or add the mount if it is not present. CLI Example: .. code-block:: bash salt '*' mount.set_automaster /mnt/foo /dev/sdz1 ext4 ''' # Fix the opts type if it is a list if isinstance(opts, list): opts = ','.join(opts) lines = [] change = False present = False automaster_file = "/etc/auto_master" if not os.path.isfile(config): __salt__['file.touch'](config) __salt__['file.append'](automaster_file, "/-\t\t\t{0}".format(config)) name = "/..{0}".format(name) device_fmt = "{0}:{1}".format(fstype, device) type_opts = "-fstype={0},{1}".format(fstype, opts) if fstype == 'smbfs': device_fmt = device_fmt.replace(fstype, "") try: with salt.utils.files.fopen(config, 'r') as ifile: for line in ifile: line = salt.utils.stringutils.to_unicode(line) if line.startswith('#'): # Commented lines.append(line) continue if not line.strip(): # Blank line lines.append(line) continue comps = line.split() if len(comps) != 3: # Invalid entry lines.append(line) continue if comps[0] == name or comps[2] == device_fmt: # check to see if there are changes # and fix them if there are any present = True if comps[0] != name: change = True comps[0] = name if comps[1] != type_opts: change = True comps[1] = type_opts if comps[2] != device_fmt: change = True comps[2] = device_fmt if change: log.debug( 'auto_master entry for mount point %s needs to be ' 'updated', name ) newline = ( '{0}\t{1}\t{2}\n'.format( name, type_opts, device_fmt) ) lines.append(newline) else: lines.append(line) except (IOError, OSError) as exc: msg = 'Couldn\'t read from {0}: {1}' raise CommandExecutionError(msg.format(config, exc)) if change: if not salt.utils.args.test_mode(test=test, **kwargs): try: with salt.utils.files.fopen(config, 'wb') as ofile: # The line was changed, commit it! ofile.writelines(salt.utils.data.encode(lines)) except (IOError, OSError): msg = 'File not writable {0}' raise CommandExecutionError(msg.format(config)) return 'change' if not change: if present: # The right entry is already here return 'present' else: if not salt.utils.args.test_mode(test=test, **kwargs): # The entry is new, add it to the end of the fstab newline = ( '{0}\t{1}\t{2}\n'.format( name, type_opts, device_fmt) ) lines.append(newline) try: with salt.utils.files.fopen(config, 'wb') as ofile: # The line was changed, commit it! ofile.writelines(salt.utils.data.encode(lines)) except (IOError, OSError): raise CommandExecutionError( 'File not writable {0}'.format( config ) ) return 'new' def automaster(config='/etc/auto_salt'): ''' List the contents of the auto master CLI Example: .. code-block:: bash salt '*' mount.automaster ''' ret = {} if not os.path.isfile(config): return ret with salt.utils.files.fopen(config) as ifile: for line in ifile: line = salt.utils.stringutils.to_unicode(line) if line.startswith('#'): # Commented continue if not line.strip(): # Blank line continue comps = line.split() if len(comps) != 3: # Invalid entry continue prefix = "/.." name = comps[0].replace(prefix, "") device_fmt = comps[2].split(":") opts = comps[1].split(',') ret[name] = {'device': device_fmt[1], 'fstype': opts[0], 'opts': opts[1:]} return ret def mount(name, device, mkmnt=False, fstype='', opts='defaults', user=None, util='mount'): ''' Mount a device CLI Example: .. code-block:: bash salt '*' mount.mount /mnt/foo /dev/sdz1 True ''' if util != 'mount': # This functionality used to live in img.mount_image if util == 'guestfs': return __salt__['guestfs.mount'](name, root=device) elif util == 'qemu_nbd': mnt = __salt__['qemu_nbd.init'](name, device) if not mnt: return False first = next(six.iterkeys(mnt)) __context__['img.mnt_{0}'.format(first)] = mnt return first return False # Darwin doesn't expect defaults when mounting without other options if 'defaults' in opts and __grains__['os'] in ['MacOS', 'Darwin', 'AIX']: opts = None if isinstance(opts, six.string_types): opts = opts.split(',') if not os.path.exists(name) and mkmnt: __salt__['file.mkdir'](name, user=user) args = '' if opts is not None: lopts = ','.join(opts) args = '-o {0}'.format(lopts) if fstype: # use of fstype on AIX differs from typical Linux use of -t # functionality AIX uses -v vfsname, -t fstype mounts all with # fstype in /etc/filesystems if 'AIX' in __grains__['os']: args += ' -v {0}'.format(fstype) elif 'solaris' in __grains__['os'].lower(): args += ' -F {0}'.format(fstype) else: args += ' -t {0}'.format(fstype) cmd = 'mount {0} {1} {2} '.format(args, device, name) out = __salt__['cmd.run_all'](cmd, runas=user, python_shell=False) if out['retcode']: return out['stderr'] return True def umount(name, device=None, user=None, util='mount'): ''' Attempt to unmount a device by specifying the directory it is mounted on CLI Example: .. code-block:: bash salt '*' mount.umount /mnt/foo .. versionadded:: 2015.5.0 .. code-block:: bash salt '*' mount.umount /mnt/foo /dev/xvdc1 ''' if util != 'mount': # This functionality used to live in img.umount_image if 'qemu_nbd.clear' in __salt__: if 'img.mnt_{0}'.format(name) in __context__: __salt__['qemu_nbd.clear'](__context__['img.mnt_{0}'.format(name)]) return mnts = active() if name not in mnts: return "{0} does not have anything mounted".format(name) if not device: cmd = 'umount {0}'.format(name) else: cmd = 'umount {0}'.format(device) out = __salt__['cmd.run_all'](cmd, runas=user, python_shell=False) if out['retcode']: return out['stderr'] return True def is_fuse_exec(cmd): ''' Returns true if the command passed is a fuse mountable application. CLI Example: .. code-block:: bash salt '*' mount.is_fuse_exec sshfs ''' cmd_path = salt.utils.path.which(cmd) # No point in running ldd on a command that doesn't exist if not cmd_path: return False elif not salt.utils.path.which('ldd'): raise CommandNotFoundError('ldd') out = __salt__['cmd.run']('ldd {0}'.format(cmd_path), python_shell=False) return 'libfuse' in out def swaps(): ''' Return a dict containing information on active swap .. versionchanged:: 2016.3.2 CLI Example: .. code-block:: bash salt '*' mount.swaps ''' ret = {} if __grains__['kernel'] == 'SunOS': for line in __salt__['cmd.run_stdout']('swap -l').splitlines(): if line.startswith('swapfile'): continue comps = line.split() ret[comps[0]] = {'type': 'device' if comps[0].startswith(('/dev', 'swap')) else 'file', 'size': int(comps[3]), 'used': (int(comps[3]) - int(comps[4])), 'priority': '-'} elif 'AIX' in __grains__['kernel']: for line in __salt__['cmd.run_stdout']('swap -l').splitlines(): if line.startswith('device'): continue comps = line.split() # AIX uses MB for units ret[comps[0]] = {'type': 'device', 'size': int(comps[3][:-2]) * 1024, 'used': (int(comps[3][:-2]) - int(comps[4][:-2])) * 1024, 'priority': '-'} elif __grains__['os'] != 'OpenBSD': with salt.utils.files.fopen('/proc/swaps') as fp_: for line in fp_: line = salt.utils.stringutils.to_unicode(line) if line.startswith('Filename'): continue comps = line.split() ret[comps[0]] = {'type': comps[1], 'size': comps[2], 'used': comps[3], 'priority': comps[4]} else: for line in __salt__['cmd.run_stdout']('swapctl -kl').splitlines(): if line.startswith(('Device', 'Total')): continue swap_type = "file" comps = line.split() if comps[0].startswith('/dev/'): swap_type = "partition" ret[comps[0]] = {'type': swap_type, 'size': comps[1], 'used': comps[2], 'priority': comps[5]} return ret def swapon(name, priority=None): ''' Activate a swap disk .. versionchanged:: 2016.3.2 CLI Example: .. code-block:: bash salt '*' mount.swapon /root/swapfile ''' ret = {} on_ = swaps() if name in on_: ret['stats'] = on_[name] ret['new'] = False return ret if __grains__['kernel'] == 'SunOS': if __grains__['virtual'] != 'zone': __salt__['cmd.run']('swap -a {0}'.format(name), python_shell=False) else: return False else: cmd = 'swapon {0}'.format(name) if priority and 'AIX' not in __grains__['kernel']: cmd += ' -p {0}'.format(priority) __salt__['cmd.run'](cmd, python_shell=False) on_ = swaps() if name in on_: ret['stats'] = on_[name] ret['new'] = True return ret return ret def swapoff(name): ''' Deactivate a named swap mount .. versionchanged:: 2016.3.2 CLI Example: .. code-block:: bash salt '*' mount.swapoff /root/swapfile ''' on_ = swaps() if name in on_: if __grains__['kernel'] == 'SunOS': if __grains__['virtual'] != 'zone': __salt__['cmd.run']('swap -a {0}'.format(name), python_shell=False) else: return False elif __grains__['os'] != 'OpenBSD': __salt__['cmd.run']('swapoff {0}'.format(name), python_shell=False) else: __salt__['cmd.run']('swapctl -d {0}'.format(name), python_shell=False) on_ = swaps() if name in on_: return False return True return None def is_mounted(name): ''' .. versionadded:: 2014.7.0 Provide information if the path is mounted CLI Example: .. code-block:: bash salt '*' mount.is_mounted /mnt/share ''' active_ = active() if name in active_: return True else: return False def read_mount_cache(name): ''' .. versionadded:: 2018.3.0 Provide information if the path is mounted CLI Example: .. code-block:: bash salt '*' mount.read_mount_cache /mnt/share ''' cache = salt.utils.mount.read_cache(__opts__) if cache: if 'mounts' in cache and cache['mounts']: if name in cache['mounts']: return cache['mounts'][name] return {} def write_mount_cache(real_name, device, mkmnt, fstype, mount_opts): ''' .. versionadded:: 2018.3.0 Provide information if the path is mounted :param real_name: The real name of the mount point where the device is mounted. :param device: The device that is being mounted. :param mkmnt: Whether or not the mount point should be created. :param fstype: The file system that is used. :param mount_opts: Additional options used when mounting the device. :return: Boolean if message was sent successfully. CLI Example: .. code-block:: bash salt '*' mount.write_mount_cache /mnt/share /dev/sda1 False ext4 defaults,nosuid ''' cache = salt.utils.mount.read_cache(__opts__) if not cache: cache = {} cache['mounts'] = {} else: if 'mounts' not in cache: cache['mounts'] = {} cache['mounts'][real_name] = {'device': device, 'fstype': fstype, 'mkmnt': mkmnt, 'opts': mount_opts} cache_write = salt.utils.mount.write_cache(cache, __opts__) if cache_write: return True else: raise CommandExecutionError('Unable to write mount cache.') def delete_mount_cache(real_name): ''' .. versionadded:: 2018.3.0 Provide information if the path is mounted CLI Example: .. code-block:: bash salt '*' mount.delete_mount_cache /mnt/share ''' cache = salt.utils.mount.read_cache(__opts__) if cache: if 'mounts' in cache: if real_name in cache['mounts']: del cache['mounts'][real_name] cache_write = salt.utils.mount.write_cache(cache, __opts__) if not cache_write: raise CommandExecutionError('Unable to write mount cache.') return True def _filesystems(config='/etc/filesystems', leading_key=True): ''' Return the contents of the filesystems in an OrderedDict config File containing filesystem infomation leading_key True return dictionary keyed by 'name' and value as dictionary with other keys, values (name excluded) OrderedDict({ '/dir' : OrderedDict({'dev': '/dev/hd8', .... }})) False return dictionary keyed by 'name' and value as dictionary with all keys, values (name included) OrderedDict({ '/dir' : OrderedDict({'name': '/dir', 'dev': '/dev/hd8', ... })}) ''' ret = OrderedDict() lines = [] parsing_block = False if not os.path.isfile(config) or 'AIX' not in __grains__['kernel']: return ret # read in block of filesystems, block starts with '/' till empty line with salt.utils.files.fopen(config) as ifile: for line in ifile: line = salt.utils.stringutils.to_unicode(line) # skip till first entry if not line.startswith('/') and not parsing_block: continue if line.startswith('/'): parsing_block = True lines.append(line) elif not line.split(): parsing_block = False try: entry = _FileSystemsEntry.dict_from_lines( lines, _FileSystemsEntry.compatibility_keys) lines = [] if 'opts' in entry: entry['opts'] = entry['opts'].split(',') while entry['name'] in ret: entry['name'] += '_' if leading_key: ret[entry.pop('name')] = entry else: ret[entry['name']] = entry except _FileSystemsEntry.ParseError: pass else: lines.append(line) return ret def filesystems(config='/etc/filesystems'): ''' .. versionadded:: 2018.3.3 List the contents of the filesystems CLI Example: .. code-block:: bash salt '*' mount.filesystems ''' ret = {} if 'AIX' not in __grains__['kernel']: return ret ret_dict = _filesystems(config) if ret_dict: ret_key = next(iter(ret_dict.keys())) ret = {ret_key: dict(ret_dict[ret_key])} return ret def set_filesystems( name, device, vfstype, opts='-', mount='true', config='/etc/filesystems', test=False, match_on='auto', **kwargs): ''' .. versionadded:: 2018.3.3 Verify that this mount is represented in the filesystems, change the mount to match the data passed, or add the mount if it is not present on AIX Provide information if the path is mounted :param name: The name of the mount point where the device is mounted. :param device: The device that is being mounted. :param vfstype: The file system that is used (AIX has two fstypes, fstype and vfstype - similar to Linux fstype) :param opts: Additional options used when mounting the device. :param mount: Mount if not mounted, default True. :param config: Configuration file, default /etc/filesystems. :param match: File systems type to match on, default auto CLI Example: .. code-block:: bash salt '*' mount.set_filesystems /mnt/foo /dev/sdz1 jfs2 ''' # Fix the opts type if it is a list if isinstance(opts, list): opts = ','.join(opts) # preserve arguments for updating entry_args = { 'name': name, 'dev': device.replace('\\ ', '\\040'), 'vfstype': vfstype, 'opts': opts, 'mount': mount, } view_lines = [] ret = None if 'AIX' not in __grains__['kernel']: return ret # Transform match_on into list--items will be checked later if isinstance(match_on, list): pass elif not isinstance(match_on, six.string_types): raise CommandExecutionError('match_on must be a string or list of strings') elif match_on == 'auto': # Try to guess right criteria for auto.... # added IBM types from sys/vmount.h after btrfs # NOTE: missing some special fstypes here specialFSes = frozenset([ 'none', 'tmpfs', 'sysfs', 'proc', 'fusectl', 'debugfs', 'securityfs', 'devtmpfs', 'cgroup', 'btrfs', 'cdrfs', 'procfs', 'jfs', 'jfs2', 'nfs', 'sfs', 'nfs3', 'cachefs', 'udfs', 'cifs', 'namefs', 'pmemfs', 'ahafs', 'nfs4', 'autofs', 'stnfs']) if vfstype in specialFSes: match_on = ['name'] else: match_on = ['dev'] else: match_on = [match_on] # generate entry and criteria objects, handle invalid keys in match_on entry_ip = _FileSystemsEntry.from_line(entry_args, kwargs) try: criteria = entry_ip.pick(match_on) except KeyError: filterFn = lambda key: key not in _FileSystemsEntry.compatibility_keys invalid_keys = filter(filterFn, match_on) raise CommandExecutionError('Unrecognized keys in match_on: "{0}"'.format(invalid_keys)) # parse file, use ret to cache status if not os.path.isfile(config): raise CommandExecutionError('Bad config file "{0}"'.format(config)) # read in block of filesystem, block starts with '/' till empty line try: fsys_filedict = _filesystems(config, False) for fsys_view in six.viewitems(fsys_filedict): if criteria.match(fsys_view): ret = 'present' if entry_ip.match(fsys_view): view_lines.append(fsys_view) else: ret = 'change' kv = entry_ip['name'] view_lines.append((kv, entry_ip)) else: view_lines.append(fsys_view) except (IOError, OSError) as exc: raise CommandExecutionError('Couldn\'t read from {0}: {1}'.format(config, exc)) # add line if not present or changed if ret is None: for dict_view in six.viewitems(entry_ip.dict_from_entry()): view_lines.append(dict_view) ret = 'new' if ret != 'present': # ret in ['new', 'change']: try: with salt.utils.files.fopen(config, 'wb') as ofile: # The line was changed, commit it! for fsys_view in view_lines: entry = fsys_view[1] mystrg = _FileSystemsEntry.dict_to_lines(entry) ofile.writelines(salt.utils.data.encode(mystrg)) except (IOError, OSError): raise CommandExecutionError('File not writable {0}'.format(config)) return ret def rm_filesystems(name, device, config='/etc/filesystems'): ''' .. versionadded:: 2018.3.3 Remove the mount point from the filesystems CLI Example: .. code-block:: bash salt '*' mount.rm_filesystems /mnt/foo /dev/sdg ''' modified = False view_lines = [] if 'AIX' not in __grains__['kernel']: return modified criteria = _FileSystemsEntry(name=name, dev=device) try: fsys_filedict = _filesystems(config, False) for fsys_view in six.viewitems(fsys_filedict): try: if criteria.match(fsys_view): modified = True else: view_lines.append(fsys_view) except _FileSystemsEntry.ParseError: view_lines.append(fsys_view) except (IOError, OSError) as exc: raise CommandExecutionError("Couldn't read from {0}: {1}".format(config, exc)) if modified: try: with salt.utils.files.fopen(config, 'wb') as ofile: for fsys_view in view_lines: entry = fsys_view[1] mystrg = _FileSystemsEntry.dict_to_lines(entry) ofile.writelines(salt.utils.data.encode(mystrg)) except (IOError, OSError) as exc: raise CommandExecutionError("Couldn't write to {0}: {1}".format(config, exc)) return modified
saltstack/salt
salt/modules/mount.py
umount
python
def umount(name, device=None, user=None, util='mount'): ''' Attempt to unmount a device by specifying the directory it is mounted on CLI Example: .. code-block:: bash salt '*' mount.umount /mnt/foo .. versionadded:: 2015.5.0 .. code-block:: bash salt '*' mount.umount /mnt/foo /dev/xvdc1 ''' if util != 'mount': # This functionality used to live in img.umount_image if 'qemu_nbd.clear' in __salt__: if 'img.mnt_{0}'.format(name) in __context__: __salt__['qemu_nbd.clear'](__context__['img.mnt_{0}'.format(name)]) return mnts = active() if name not in mnts: return "{0} does not have anything mounted".format(name) if not device: cmd = 'umount {0}'.format(name) else: cmd = 'umount {0}'.format(device) out = __salt__['cmd.run_all'](cmd, runas=user, python_shell=False) if out['retcode']: return out['stderr'] return True
Attempt to unmount a device by specifying the directory it is mounted on CLI Example: .. code-block:: bash salt '*' mount.umount /mnt/foo .. versionadded:: 2015.5.0 .. code-block:: bash salt '*' mount.umount /mnt/foo /dev/xvdc1
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/mount.py#L1291-L1324
[ "def active(extended=False):\n '''\n List the active mounts.\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' mount.active\n '''\n ret = {}\n if __grains__['os'] == 'FreeBSD':\n _active_mounts_freebsd(ret)\n elif 'AIX' in __grains__['kernel']:\n _active_mounts_aix(ret)\n elif __grains__['kernel'] == 'SunOS':\n _active_mounts_solaris(ret)\n elif __grains__['os'] == 'OpenBSD':\n _active_mounts_openbsd(ret)\n elif __grains__['os'] in ['MacOS', 'Darwin']:\n _active_mounts_darwin(ret)\n else:\n if extended:\n try:\n _active_mountinfo(ret)\n except CommandExecutionError:\n _active_mounts(ret)\n else:\n _active_mounts(ret)\n return ret\n" ]
# -*- coding: utf-8 -*- ''' Salt module to manage Unix mounts and the fstab file ''' # Import python libs from __future__ import absolute_import, print_function, unicode_literals import os import re import logging # Import salt libs import salt.utils.args import salt.utils.data import salt.utils.files import salt.utils.path import salt.utils.platform import salt.utils.mount import salt.utils.stringutils from salt.utils.odict import OrderedDict from salt.exceptions import CommandNotFoundError, CommandExecutionError # Import 3rd-party libs from salt.ext import six from salt.ext.six.moves import filter, zip # pylint: disable=import-error,redefined-builtin # Set up logger log = logging.getLogger(__name__) # Define the module's virtual name __virtualname__ = 'mount' def __virtual__(): ''' Only load on POSIX-like systems ''' # Disable on Windows, a specific file module exists: if salt.utils.platform.is_windows(): return (False, 'The mount module cannot be loaded: not a POSIX-like system.') return True def _list_mounts(): ret = {} if __grains__['os'] in ['MacOS', 'Darwin']: mounts = __salt__['cmd.run_stdout']('mount') else: mounts = __salt__['cmd.run_stdout']('mount -l') for line in mounts.split('\n'): comps = re.sub(r"\s+", " ", line).split() if len(comps) >= 3: ret[comps[2]] = comps[0] return ret def _active_mountinfo(ret): _list = _list_mounts() filename = '/proc/self/mountinfo' if not os.access(filename, os.R_OK): msg = 'File not readable {0}' raise CommandExecutionError(msg.format(filename)) if 'disk.blkid' not in __context__: __context__['disk.blkid'] = __salt__['disk.blkid']() blkid_info = __context__['disk.blkid'] with salt.utils.files.fopen(filename) as ifile: for line in ifile: comps = salt.utils.stringutils.to_unicode(line).split() device = comps[2].split(':') # each line can have any number of # optional parameters, we use the # location of the separator field to # determine the location of the elements # after it. _sep = comps.index('-') device_name = comps[_sep + 2] device_uuid = None device_label = None if device_name: device_uuid = blkid_info.get(device_name, {}).get('UUID') device_uuid = device_uuid and device_uuid.lower() device_label = blkid_info.get(device_name, {}).get('LABEL') ret[comps[4]] = {'mountid': comps[0], 'parentid': comps[1], 'major': device[0], 'minor': device[1], 'root': comps[3], 'opts': _resolve_user_group_names(comps[5].split(',')), 'fstype': comps[_sep + 1], 'device': device_name.replace('\\040', '\\ '), 'alt_device': _list.get(comps[4], None), 'superopts': _resolve_user_group_names(comps[_sep + 3].split(',')), 'device_uuid': device_uuid, 'device_label': device_label} return ret def _active_mounts(ret): ''' List active mounts on Linux systems ''' _list = _list_mounts() filename = '/proc/self/mounts' if not os.access(filename, os.R_OK): msg = 'File not readable {0}' raise CommandExecutionError(msg.format(filename)) with salt.utils.files.fopen(filename) as ifile: for line in ifile: comps = salt.utils.stringutils.to_unicode(line).split() ret[comps[1]] = {'device': comps[0], 'alt_device': _list.get(comps[1], None), 'fstype': comps[2], 'opts': _resolve_user_group_names(comps[3].split(','))} return ret def _active_mounts_aix(ret): ''' List active mounts on AIX systems ''' for line in __salt__['cmd.run_stdout']('mount -p').split('\n'): comps = re.sub(r"\s+", " ", line).split() if comps: if comps[0] == 'node' or comps[0] == '--------': continue comps_len = len(comps) if line.startswith((' ', '\t')): curr_opts = _resolve_user_group_names(comps[6].split(',')) if 7 == comps_len else [] if curr_opts: ret[comps[1]] = {'device': comps[0], 'fstype': comps[2], 'opts': curr_opts} else: ret[comps[1]] = {'device': comps[0], 'fstype': comps[2]} else: curr_opts = _resolve_user_group_names(comps[7].split(',')) if 8 == comps_len else [] if curr_opts: ret[comps[2]] = {'node': comps[0], 'device': comps[1], 'fstype': comps[3], 'opts': curr_opts} else: ret[comps[2]] = {'node': comps[0], 'device': comps[1], 'fstype': comps[3]} return ret def _active_mounts_freebsd(ret): ''' List active mounts on FreeBSD systems ''' for line in __salt__['cmd.run_stdout']('mount -p').split('\n'): comps = re.sub(r"\s+", " ", line).split() ret[comps[1]] = {'device': comps[0], 'fstype': comps[2], 'opts': _resolve_user_group_names(comps[3].split(','))} return ret def _active_mounts_solaris(ret): ''' List active mounts on Solaris systems ''' for line in __salt__['cmd.run_stdout']('mount -v').split('\n'): comps = re.sub(r"\s+", " ", line).split() ret[comps[2]] = {'device': comps[0], 'fstype': comps[4], 'opts': _resolve_user_group_names(comps[5].split('/'))} return ret def _active_mounts_openbsd(ret): ''' List active mounts on OpenBSD systems ''' for line in __salt__['cmd.run_stdout']('mount -v').split('\n'): comps = re.sub(r"\s+", " ", line).split() parens = re.findall(r'\((.*?)\)', line, re.DOTALL) if len(parens) > 1: nod = __salt__['cmd.run_stdout']('ls -l {0}'.format(comps[0])) nod = ' '.join(nod.split()).split(" ") ret[comps[3]] = {'device': comps[0], 'fstype': comps[5], 'opts': _resolve_user_group_names(parens[1].split(", ")), 'major': six.text_type(nod[4].strip(",")), 'minor': six.text_type(nod[5]), 'device_uuid': parens[0]} else: ret[comps[2]] = {'device': comps[0], 'fstype': comps[4], 'opts': _resolve_user_group_names(parens[0].split(", "))} return ret def _active_mounts_darwin(ret): ''' List active mounts on Mac OS systems ''' for line in __salt__['cmd.run_stdout']('mount').split('\n'): comps = re.sub(r"\s+", " ", line).split() parens = re.findall(r'\((.*?)\)', line, re.DOTALL)[0].split(", ") ret[comps[2]] = {'device': comps[0], 'fstype': parens[0], 'opts': _resolve_user_group_names(parens[1:])} return ret def _resolve_user_group_names(opts): ''' Resolve user and group names in related opts ''' name_id_opts = {'uid': 'user.info', 'gid': 'group.info'} for ind, opt in enumerate(opts): if opt.split('=')[0] in name_id_opts: _givenid = opt.split('=')[1] _param = opt.split('=')[0] _id = _givenid if not re.match('[0-9]+$', _givenid): _info = __salt__[name_id_opts[_param]](_givenid) if _info and _param in _info: _id = _info[_param] opts[ind] = _param + '=' + six.text_type(_id) opts[ind] = opts[ind].replace('\\040', '\\ ') return opts def active(extended=False): ''' List the active mounts. CLI Example: .. code-block:: bash salt '*' mount.active ''' ret = {} if __grains__['os'] == 'FreeBSD': _active_mounts_freebsd(ret) elif 'AIX' in __grains__['kernel']: _active_mounts_aix(ret) elif __grains__['kernel'] == 'SunOS': _active_mounts_solaris(ret) elif __grains__['os'] == 'OpenBSD': _active_mounts_openbsd(ret) elif __grains__['os'] in ['MacOS', 'Darwin']: _active_mounts_darwin(ret) else: if extended: try: _active_mountinfo(ret) except CommandExecutionError: _active_mounts(ret) else: _active_mounts(ret) return ret class _fstab_entry(object): ''' Utility class for manipulating fstab entries. Primarily we're parsing, formatting, and comparing lines. Parsing emits dicts expected from fstab() or raises a ValueError. Note: We'll probably want to use os.normpath and os.normcase on 'name' ''' class ParseError(ValueError): ''' Error raised when a line isn't parsible as an fstab entry ''' fstab_keys = ('device', 'name', 'fstype', 'opts', 'dump', 'pass_num') # preserve data format compatibility_keys = ('device', 'name', 'fstype', 'opts', 'dump', 'pass') fstab_format = '{device}\t\t{name}\t{fstype}\t{opts}\t{dump} {pass_num}\n' @classmethod def dict_from_line(cls, line, keys=fstab_keys): if len(keys) != 6: raise ValueError('Invalid key array: {0}'.format(keys)) if line.startswith('#'): raise cls.ParseError("Comment!") comps = line.split() if len(comps) < 4 or len(comps) > 6: raise cls.ParseError("Invalid Entry!") comps.extend(['0'] * (len(keys) - len(comps))) return dict(zip(keys, comps)) @classmethod def from_line(cls, *args, **kwargs): return cls(** cls.dict_from_line(*args, **kwargs)) @classmethod def dict_to_line(cls, entry): return cls.fstab_format.format(**entry) def __str__(self): ''' String value, only works for full repr ''' return self.dict_to_line(self.criteria) def __repr__(self): ''' Always works ''' return repr(self.criteria) def pick(self, keys): ''' Returns an instance with just those keys ''' subset = dict([(key, self.criteria[key]) for key in keys]) return self.__class__(**subset) def __init__(self, **criteria): ''' Store non-empty, non-null values to use as filter ''' items = [key_value for key_value in six.iteritems(criteria) if key_value[1] is not None] items = [(key_value1[0], six.text_type(key_value1[1])) for key_value1 in items] self.criteria = dict(items) @staticmethod def norm_path(path): ''' Resolve equivalent paths equivalently ''' return os.path.normcase(os.path.normpath(path)) def match(self, line): ''' Compare potentially partial criteria against line ''' entry = self.dict_from_line(line) for key, value in six.iteritems(self.criteria): if entry[key] != value: return False return True class _vfstab_entry(object): ''' Utility class for manipulating vfstab entries. Primarily we're parsing, formatting, and comparing lines. Parsing emits dicts expected from fstab() or raises a ValueError. Note: We'll probably want to use os.normpath and os.normcase on 'name' Note: This parses vfstab entries on Solaris like systems #device device mount FS fsck mount mount #to mount to fsck point type pass at boot options # /devices - /devices devfs - no - ''' class ParseError(ValueError): '''Error raised when a line isn't parsible as an fstab entry''' vfstab_keys = ('device', 'device_fsck', 'name', 'fstype', 'pass_fsck', 'mount_at_boot', 'opts') # NOTE: weird formatting to match default spacing on Solaris vfstab_format = '{device:<11} {device_fsck:<3} {name:<19} {fstype:<8} {pass_fsck:<3} {mount_at_boot:<6} {opts}\n' @classmethod def dict_from_line(cls, line): if line.startswith('#'): raise cls.ParseError("Comment!") comps = line.split() if len(comps) != 7: raise cls.ParseError("Invalid Entry!") return dict(zip(cls.vfstab_keys, comps)) @classmethod def from_line(cls, *args, **kwargs): return cls(** cls.dict_from_line(*args, **kwargs)) @classmethod def dict_to_line(cls, entry): return cls.vfstab_format.format(**entry) def __str__(self): ''' String value, only works for full repr ''' return self.dict_to_line(self.criteria) def __repr__(self): ''' Always works ''' return repr(self.criteria) def pick(self, keys): ''' Returns an instance with just those keys ''' subset = dict([(key, self.criteria[key]) for key in keys]) return self.__class__(**subset) def __init__(self, **criteria): ''' Store non-empty, non-null values to use as filter ''' items = [key_value for key_value in six.iteritems(criteria) if key_value[1] is not None] items = [(key_value1[0], six.text_type(key_value1[1])) for key_value1 in items] self.criteria = dict(items) @staticmethod def norm_path(path): ''' Resolve equivalent paths equivalently ''' return os.path.normcase(os.path.normpath(path)) def match(self, line): ''' Compare potentially partial criteria against line ''' entry = self.dict_from_line(line) for key, value in six.iteritems(self.criteria): if entry[key] != value: return False return True class _FileSystemsEntry(object): ''' Utility class for manipulating filesystem entries. Primarily we're parsing, formatting, and comparing lines. Parsing emits dicts expected from fstab() or raises a ValueError. Note: We'll probably want to use os.normpath and os.normcase on 'name' ''' class ParseError(ValueError): ''' Error raised when a line isn't parsible as an fstab entry ''' filesystems_keys = ('device', 'name', 'fstype', 'vfstype', 'opts', 'mount') # preserve data format of filesystems compatibility_keys = ('dev', 'dev', 'name', 'fstype', 'vfstype', 'opts', 'mount', 'type', 'vfs', 'account', 'boot', 'check', 'free', 'nodename', 'quota', 'size', 'vol', 'log') @classmethod def dict_from_lines(cls, lines, keys=filesystems_keys): if len(lines) < 2: raise ValueError('Invalid number of lines: {0}'.format(lines)) if not keys: # if empty force default filesystems_keys keys = _FileSystemsEntry.filesystems_keys elif len(keys) < 6: raise ValueError('Invalid key name array: {0}'.format(keys)) blk_lines = lines orddict = OrderedDict() orddict['name'] = blk_lines[0].split(':')[0].strip() blk_lines.pop(0) for line in blk_lines: if line.startswith('#'): raise cls.ParseError("Comment!") comps = line.split('= ') if len(comps) != 2: raise cls.ParseError("Invalid Entry!") key_name = comps[0].strip() if key_name in keys: orddict[key_name] = comps[1].strip() else: raise ValueError('Invalid name for use in filesystems: {0}'.format(key_name)) return orddict @classmethod def dict_from_cmd_line(cls, ipargs, keys): cmdln_dict = ipargs if keys: for key, value in keys: # ignore unknown or local scope keys if key.startswith('__'): continue if key in _FileSystemsEntry.compatibility_keys: cmdln_dict[key] = value return cmdln_dict @classmethod def from_line(cls, *args, **kwargs): return cls(** cls.dict_from_cmd_line(*args, **kwargs)) @classmethod def dict_to_lines(cls, fsys_dict_entry): entry = fsys_dict_entry strg_out = entry['name'] + ':' + os.linesep for k, v in six.viewitems(entry): if 'name' not in k: strg_out += '\t{0}\t\t= {1}'.format(k, v) + os.linesep strg_out += os.linesep return six.text_type(strg_out) def dict_from_entry(self): ret = OrderedDict() ret[self.criteria['name']] = self.criteria return ret def __str__(self): ''' String value, only works for full repr ''' return self.dict_to_lines(self.criteria) def __repr__(self): ''' Always works ''' return repr(self.criteria) def pick(self, keys): ''' Returns an instance with just those keys ''' subset = dict([(key, self.criteria[key]) for key in keys]) return self.__class__(**subset) def __init__(self, **criteria): ''' Store non-empty, non-null values to use as filter ''' items = [key_value for key_value in six.iteritems(criteria) if key_value[1] is not None] items = [(key_value1[0], six.text_type(key_value1[1])) for key_value1 in items] self.criteria = OrderedDict(items) @staticmethod def norm_path(path): ''' Resolve equivalent paths equivalently ''' return os.path.normcase(os.path.normpath(path)) def match(self, fsys_view): ''' Compare potentially partial criteria against built filesystems entry dictionary ''' evalue_dict = fsys_view[1] for key, value in six.viewitems(self.criteria): if key in evalue_dict: if evalue_dict[key] != value: return False else: return False return True def __getitem__(self, key): ''' Return value for input key ''' return self.criteria[key] def fstab(config='/etc/fstab'): ''' .. versionchanged:: 2016.3.2 List the contents of the fstab CLI Example: .. code-block:: bash salt '*' mount.fstab ''' ret = {} if not os.path.isfile(config): return ret with salt.utils.files.fopen(config) as ifile: for line in ifile: line = salt.utils.stringutils.to_unicode(line) try: if __grains__['kernel'] == 'SunOS': # Note: comments use in default vfstab file! if line[0] == '#': continue entry = _vfstab_entry.dict_from_line( line) else: entry = _fstab_entry.dict_from_line( line, _fstab_entry.compatibility_keys) entry['opts'] = entry['opts'].split(',') while entry['name'] in ret: entry['name'] += '_' ret[entry.pop('name')] = entry except _fstab_entry.ParseError: pass except _vfstab_entry.ParseError: pass return ret def vfstab(config='/etc/vfstab'): ''' .. versionadded:: 2016.3.2 List the contents of the vfstab CLI Example: .. code-block:: bash salt '*' mount.vfstab ''' # NOTE: vfstab is a wrapper for fstab return fstab(config) def rm_fstab(name, device, config='/etc/fstab'): ''' .. versionchanged:: 2016.3.2 Remove the mount point from the fstab CLI Example: .. code-block:: bash salt '*' mount.rm_fstab /mnt/foo /dev/sdg ''' modified = False if __grains__['kernel'] == 'SunOS': criteria = _vfstab_entry(name=name, device=device) else: criteria = _fstab_entry(name=name, device=device) lines = [] try: with salt.utils.files.fopen(config, 'r') as ifile: for line in ifile: line = salt.utils.stringutils.to_unicode(line) try: if criteria.match(line): modified = True else: lines.append(line) except _fstab_entry.ParseError: lines.append(line) except _vfstab_entry.ParseError: lines.append(line) except (IOError, OSError) as exc: msg = "Couldn't read from {0}: {1}" raise CommandExecutionError(msg.format(config, exc)) if modified: try: with salt.utils.files.fopen(config, 'wb') as ofile: ofile.writelines(salt.utils.data.encode(lines)) except (IOError, OSError) as exc: msg = "Couldn't write to {0}: {1}" raise CommandExecutionError(msg.format(config, exc)) # Note: not clear why we always return 'True' # --just copying previous behavior at this point... return True def rm_vfstab(name, device, config='/etc/vfstab'): ''' .. versionadded:: 2016.3.2 Remove the mount point from the vfstab CLI Example: .. code-block:: bash salt '*' mount.rm_vfstab /mnt/foo /device/c0t0d0p0 ''' ## NOTE: rm_vfstab is a wrapper for rm_fstab return rm_fstab(name, device, config) def set_fstab( name, device, fstype, opts='defaults', dump=0, pass_num=0, config='/etc/fstab', test=False, match_on='auto', **kwargs): ''' Verify that this mount is represented in the fstab, change the mount to match the data passed, or add the mount if it is not present. CLI Example: .. code-block:: bash salt '*' mount.set_fstab /mnt/foo /dev/sdz1 ext4 ''' # Fix the opts type if it is a list if isinstance(opts, list): opts = ','.join(opts) # preserve arguments for updating entry_args = { 'name': name, 'device': device.replace('\\ ', '\\040'), 'fstype': fstype, 'opts': opts.replace('\\ ', '\\040'), 'dump': dump, 'pass_num': pass_num, } lines = [] ret = None # Transform match_on into list--items will be checked later if isinstance(match_on, list): pass elif not isinstance(match_on, six.string_types): msg = 'match_on must be a string or list of strings' raise CommandExecutionError(msg) elif match_on == 'auto': # Try to guess right criteria for auto.... # NOTE: missing some special fstypes here specialFSes = frozenset([ 'none', 'tmpfs', 'sysfs', 'proc', 'fusectl', 'debugfs', 'securityfs', 'devtmpfs', 'cgroup', 'btrfs']) if fstype in specialFSes: match_on = ['name'] else: match_on = ['device'] else: match_on = [match_on] # generate entry and criteria objects, handle invalid keys in match_on entry = _fstab_entry(**entry_args) try: criteria = entry.pick(match_on) except KeyError: filterFn = lambda key: key not in _fstab_entry.fstab_keys invalid_keys = filter(filterFn, match_on) msg = 'Unrecognized keys in match_on: "{0}"'.format(invalid_keys) raise CommandExecutionError(msg) # parse file, use ret to cache status if not os.path.isfile(config): raise CommandExecutionError('Bad config file "{0}"'.format(config)) try: with salt.utils.files.fopen(config, 'r') as ifile: for line in ifile: line = salt.utils.stringutils.to_unicode(line) try: if criteria.match(line): # Note: If ret isn't None here, # we've matched multiple lines ret = 'present' if entry.match(line): lines.append(line) else: ret = 'change' lines.append(six.text_type(entry)) else: lines.append(line) except _fstab_entry.ParseError: lines.append(line) except (IOError, OSError) as exc: msg = 'Couldn\'t read from {0}: {1}' raise CommandExecutionError(msg.format(config, exc)) # add line if not present or changed if ret is None: lines.append(six.text_type(entry)) ret = 'new' if ret != 'present': # ret in ['new', 'change']: if not salt.utils.args.test_mode(test=test, **kwargs): try: with salt.utils.files.fopen(config, 'wb') as ofile: # The line was changed, commit it! ofile.writelines(salt.utils.data.encode(lines)) except (IOError, OSError): msg = 'File not writable {0}' raise CommandExecutionError(msg.format(config)) return ret def set_vfstab( name, device, fstype, opts='-', device_fsck='-', pass_fsck='-', mount_at_boot='yes', config='/etc/vfstab', test=False, match_on='auto', **kwargs): ''' ..verionadded:: 2016.3.2 Verify that this mount is represented in the fstab, change the mount to match the data passed, or add the mount if it is not present. CLI Example: .. code-block:: bash salt '*' mount.set_vfstab /mnt/foo /device/c0t0d0p0 ufs ''' # Fix the opts type if it is a list if isinstance(opts, list): opts = ','.join(opts) # Map unknown values for mount_at_boot to no if mount_at_boot != 'yes': mount_at_boot = 'no' # preserve arguments for updating entry_args = { 'name': name, 'device': device, 'fstype': fstype, 'opts': opts, 'device_fsck': device_fsck, 'pass_fsck': pass_fsck, 'mount_at_boot': mount_at_boot, } lines = [] ret = None # Transform match_on into list--items will be checked later if isinstance(match_on, list): pass elif not isinstance(match_on, six.string_types): msg = 'match_on must be a string or list of strings' raise CommandExecutionError(msg) elif match_on == 'auto': # Try to guess right criteria for auto.... # NOTE: missing some special fstypes here specialFSes = frozenset([ 'devfs', 'proc', 'ctfs', 'objfs', 'sharefs', 'fs', 'tmpfs']) if fstype in specialFSes: match_on = ['name'] else: match_on = ['device'] else: match_on = [match_on] # generate entry and criteria objects, handle invalid keys in match_on entry = _vfstab_entry(**entry_args) try: criteria = entry.pick(match_on) except KeyError: filterFn = lambda key: key not in _vfstab_entry.vfstab_keys invalid_keys = filter(filterFn, match_on) msg = 'Unrecognized keys in match_on: "{0}"'.format(invalid_keys) raise CommandExecutionError(msg) # parse file, use ret to cache status if not os.path.isfile(config): raise CommandExecutionError('Bad config file "{0}"'.format(config)) try: with salt.utils.files.fopen(config, 'r') as ifile: for line in ifile: line = salt.utils.stringutils.to_unicode(line) try: if criteria.match(line): # Note: If ret isn't None here, # we've matched multiple lines ret = 'present' if entry.match(line): lines.append(line) else: ret = 'change' lines.append(six.text_type(entry)) else: lines.append(line) except _vfstab_entry.ParseError: lines.append(line) except (IOError, OSError) as exc: msg = 'Couldn\'t read from {0}: {1}' raise CommandExecutionError(msg.format(config, exc)) # add line if not present or changed if ret is None: lines.append(six.text_type(entry)) ret = 'new' if ret != 'present': # ret in ['new', 'change']: if not salt.utils.args.test_mode(test=test, **kwargs): try: with salt.utils.files.fopen(config, 'wb') as ofile: # The line was changed, commit it! ofile.writelines(salt.utils.data.encode(lines)) except (IOError, OSError): msg = 'File not writable {0}' raise CommandExecutionError(msg.format(config)) return ret def rm_automaster(name, device, config='/etc/auto_salt'): ''' Remove the mount point from the auto_master CLI Example: .. code-block:: bash salt '*' mount.rm_automaster /mnt/foo /dev/sdg ''' contents = automaster(config) if name not in contents: return True # The entry is present, get rid of it lines = [] try: with salt.utils.files.fopen(config, 'r') as ifile: for line in ifile: line = salt.utils.stringutils.to_unicode(line) if line.startswith('#'): # Commented lines.append(line) continue if not line.strip(): # Blank line lines.append(line) continue comps = line.split() if len(comps) != 3: # Invalid entry lines.append(line) continue comps = line.split() prefix = "/.." name_chk = comps[0].replace(prefix, "") device_fmt = comps[2].split(":") if device: if name_chk == name and device_fmt[1] == device: continue else: if name_chk == name: continue lines.append(line) except (IOError, OSError) as exc: msg = "Couldn't read from {0}: {1}" raise CommandExecutionError(msg.format(config, exc)) try: with salt.utils.files.fopen(config, 'wb') as ofile: ofile.writelines(salt.utils.data.encode(lines)) except (IOError, OSError) as exc: msg = "Couldn't write to {0}: {1}" raise CommandExecutionError(msg.format(config, exc)) # Update automount __salt__['cmd.run']('automount -cv') return True def set_automaster( name, device, fstype, opts='', config='/etc/auto_salt', test=False, **kwargs): ''' Verify that this mount is represented in the auto_salt, change the mount to match the data passed, or add the mount if it is not present. CLI Example: .. code-block:: bash salt '*' mount.set_automaster /mnt/foo /dev/sdz1 ext4 ''' # Fix the opts type if it is a list if isinstance(opts, list): opts = ','.join(opts) lines = [] change = False present = False automaster_file = "/etc/auto_master" if not os.path.isfile(config): __salt__['file.touch'](config) __salt__['file.append'](automaster_file, "/-\t\t\t{0}".format(config)) name = "/..{0}".format(name) device_fmt = "{0}:{1}".format(fstype, device) type_opts = "-fstype={0},{1}".format(fstype, opts) if fstype == 'smbfs': device_fmt = device_fmt.replace(fstype, "") try: with salt.utils.files.fopen(config, 'r') as ifile: for line in ifile: line = salt.utils.stringutils.to_unicode(line) if line.startswith('#'): # Commented lines.append(line) continue if not line.strip(): # Blank line lines.append(line) continue comps = line.split() if len(comps) != 3: # Invalid entry lines.append(line) continue if comps[0] == name or comps[2] == device_fmt: # check to see if there are changes # and fix them if there are any present = True if comps[0] != name: change = True comps[0] = name if comps[1] != type_opts: change = True comps[1] = type_opts if comps[2] != device_fmt: change = True comps[2] = device_fmt if change: log.debug( 'auto_master entry for mount point %s needs to be ' 'updated', name ) newline = ( '{0}\t{1}\t{2}\n'.format( name, type_opts, device_fmt) ) lines.append(newline) else: lines.append(line) except (IOError, OSError) as exc: msg = 'Couldn\'t read from {0}: {1}' raise CommandExecutionError(msg.format(config, exc)) if change: if not salt.utils.args.test_mode(test=test, **kwargs): try: with salt.utils.files.fopen(config, 'wb') as ofile: # The line was changed, commit it! ofile.writelines(salt.utils.data.encode(lines)) except (IOError, OSError): msg = 'File not writable {0}' raise CommandExecutionError(msg.format(config)) return 'change' if not change: if present: # The right entry is already here return 'present' else: if not salt.utils.args.test_mode(test=test, **kwargs): # The entry is new, add it to the end of the fstab newline = ( '{0}\t{1}\t{2}\n'.format( name, type_opts, device_fmt) ) lines.append(newline) try: with salt.utils.files.fopen(config, 'wb') as ofile: # The line was changed, commit it! ofile.writelines(salt.utils.data.encode(lines)) except (IOError, OSError): raise CommandExecutionError( 'File not writable {0}'.format( config ) ) return 'new' def automaster(config='/etc/auto_salt'): ''' List the contents of the auto master CLI Example: .. code-block:: bash salt '*' mount.automaster ''' ret = {} if not os.path.isfile(config): return ret with salt.utils.files.fopen(config) as ifile: for line in ifile: line = salt.utils.stringutils.to_unicode(line) if line.startswith('#'): # Commented continue if not line.strip(): # Blank line continue comps = line.split() if len(comps) != 3: # Invalid entry continue prefix = "/.." name = comps[0].replace(prefix, "") device_fmt = comps[2].split(":") opts = comps[1].split(',') ret[name] = {'device': device_fmt[1], 'fstype': opts[0], 'opts': opts[1:]} return ret def mount(name, device, mkmnt=False, fstype='', opts='defaults', user=None, util='mount'): ''' Mount a device CLI Example: .. code-block:: bash salt '*' mount.mount /mnt/foo /dev/sdz1 True ''' if util != 'mount': # This functionality used to live in img.mount_image if util == 'guestfs': return __salt__['guestfs.mount'](name, root=device) elif util == 'qemu_nbd': mnt = __salt__['qemu_nbd.init'](name, device) if not mnt: return False first = next(six.iterkeys(mnt)) __context__['img.mnt_{0}'.format(first)] = mnt return first return False # Darwin doesn't expect defaults when mounting without other options if 'defaults' in opts and __grains__['os'] in ['MacOS', 'Darwin', 'AIX']: opts = None if isinstance(opts, six.string_types): opts = opts.split(',') if not os.path.exists(name) and mkmnt: __salt__['file.mkdir'](name, user=user) args = '' if opts is not None: lopts = ','.join(opts) args = '-o {0}'.format(lopts) if fstype: # use of fstype on AIX differs from typical Linux use of -t # functionality AIX uses -v vfsname, -t fstype mounts all with # fstype in /etc/filesystems if 'AIX' in __grains__['os']: args += ' -v {0}'.format(fstype) elif 'solaris' in __grains__['os'].lower(): args += ' -F {0}'.format(fstype) else: args += ' -t {0}'.format(fstype) cmd = 'mount {0} {1} {2} '.format(args, device, name) out = __salt__['cmd.run_all'](cmd, runas=user, python_shell=False) if out['retcode']: return out['stderr'] return True def remount(name, device, mkmnt=False, fstype='', opts='defaults', user=None): ''' Attempt to remount a device, if the device is not already mounted, mount is called CLI Example: .. code-block:: bash salt '*' mount.remount /mnt/foo /dev/sdz1 True ''' force_mount = False if __grains__['os'] in ['MacOS', 'Darwin']: if opts == 'defaults': opts = 'noowners' if fstype == 'smbfs': force_mount = True if 'AIX' in __grains__['os']: if opts == 'defaults': opts = [] if isinstance(opts, six.string_types): opts = opts.split(',') mnts = active() if name in mnts: # The mount point is mounted, attempt to remount it with the given data if 'remount' not in opts and __grains__['os'] not in ['OpenBSD', 'MacOS', 'Darwin']: opts.append('remount') if force_mount: # We need to force the mount but first we should unmount umount(name, device, user=user) lopts = ','.join(opts) args = '-o {0}'.format(lopts) if fstype: # use of fstype on AIX differs from typical Linux use of # -t functionality AIX uses -v vfsname, -t fstype mounts # all with fstype in /etc/filesystems if 'AIX' in __grains__['os']: args += ' -v {0}'.format(fstype) elif 'solaris' in __grains__['os'].lower(): args += ' -F {0}'.format(fstype) else: args += ' -t {0}'.format(fstype) if __grains__['os'] not in ['OpenBSD', 'MacOS', 'Darwin'] or force_mount: cmd = 'mount {0} {1} {2} '.format(args, device, name) else: cmd = 'mount -u {0} {1} {2} '.format(args, device, name) out = __salt__['cmd.run_all'](cmd, runas=user, python_shell=False) if out['retcode']: return out['stderr'] return True # Mount a filesystem that isn't already return mount(name, device, mkmnt, fstype, opts, user=user) def is_fuse_exec(cmd): ''' Returns true if the command passed is a fuse mountable application. CLI Example: .. code-block:: bash salt '*' mount.is_fuse_exec sshfs ''' cmd_path = salt.utils.path.which(cmd) # No point in running ldd on a command that doesn't exist if not cmd_path: return False elif not salt.utils.path.which('ldd'): raise CommandNotFoundError('ldd') out = __salt__['cmd.run']('ldd {0}'.format(cmd_path), python_shell=False) return 'libfuse' in out def swaps(): ''' Return a dict containing information on active swap .. versionchanged:: 2016.3.2 CLI Example: .. code-block:: bash salt '*' mount.swaps ''' ret = {} if __grains__['kernel'] == 'SunOS': for line in __salt__['cmd.run_stdout']('swap -l').splitlines(): if line.startswith('swapfile'): continue comps = line.split() ret[comps[0]] = {'type': 'device' if comps[0].startswith(('/dev', 'swap')) else 'file', 'size': int(comps[3]), 'used': (int(comps[3]) - int(comps[4])), 'priority': '-'} elif 'AIX' in __grains__['kernel']: for line in __salt__['cmd.run_stdout']('swap -l').splitlines(): if line.startswith('device'): continue comps = line.split() # AIX uses MB for units ret[comps[0]] = {'type': 'device', 'size': int(comps[3][:-2]) * 1024, 'used': (int(comps[3][:-2]) - int(comps[4][:-2])) * 1024, 'priority': '-'} elif __grains__['os'] != 'OpenBSD': with salt.utils.files.fopen('/proc/swaps') as fp_: for line in fp_: line = salt.utils.stringutils.to_unicode(line) if line.startswith('Filename'): continue comps = line.split() ret[comps[0]] = {'type': comps[1], 'size': comps[2], 'used': comps[3], 'priority': comps[4]} else: for line in __salt__['cmd.run_stdout']('swapctl -kl').splitlines(): if line.startswith(('Device', 'Total')): continue swap_type = "file" comps = line.split() if comps[0].startswith('/dev/'): swap_type = "partition" ret[comps[0]] = {'type': swap_type, 'size': comps[1], 'used': comps[2], 'priority': comps[5]} return ret def swapon(name, priority=None): ''' Activate a swap disk .. versionchanged:: 2016.3.2 CLI Example: .. code-block:: bash salt '*' mount.swapon /root/swapfile ''' ret = {} on_ = swaps() if name in on_: ret['stats'] = on_[name] ret['new'] = False return ret if __grains__['kernel'] == 'SunOS': if __grains__['virtual'] != 'zone': __salt__['cmd.run']('swap -a {0}'.format(name), python_shell=False) else: return False else: cmd = 'swapon {0}'.format(name) if priority and 'AIX' not in __grains__['kernel']: cmd += ' -p {0}'.format(priority) __salt__['cmd.run'](cmd, python_shell=False) on_ = swaps() if name in on_: ret['stats'] = on_[name] ret['new'] = True return ret return ret def swapoff(name): ''' Deactivate a named swap mount .. versionchanged:: 2016.3.2 CLI Example: .. code-block:: bash salt '*' mount.swapoff /root/swapfile ''' on_ = swaps() if name in on_: if __grains__['kernel'] == 'SunOS': if __grains__['virtual'] != 'zone': __salt__['cmd.run']('swap -a {0}'.format(name), python_shell=False) else: return False elif __grains__['os'] != 'OpenBSD': __salt__['cmd.run']('swapoff {0}'.format(name), python_shell=False) else: __salt__['cmd.run']('swapctl -d {0}'.format(name), python_shell=False) on_ = swaps() if name in on_: return False return True return None def is_mounted(name): ''' .. versionadded:: 2014.7.0 Provide information if the path is mounted CLI Example: .. code-block:: bash salt '*' mount.is_mounted /mnt/share ''' active_ = active() if name in active_: return True else: return False def read_mount_cache(name): ''' .. versionadded:: 2018.3.0 Provide information if the path is mounted CLI Example: .. code-block:: bash salt '*' mount.read_mount_cache /mnt/share ''' cache = salt.utils.mount.read_cache(__opts__) if cache: if 'mounts' in cache and cache['mounts']: if name in cache['mounts']: return cache['mounts'][name] return {} def write_mount_cache(real_name, device, mkmnt, fstype, mount_opts): ''' .. versionadded:: 2018.3.0 Provide information if the path is mounted :param real_name: The real name of the mount point where the device is mounted. :param device: The device that is being mounted. :param mkmnt: Whether or not the mount point should be created. :param fstype: The file system that is used. :param mount_opts: Additional options used when mounting the device. :return: Boolean if message was sent successfully. CLI Example: .. code-block:: bash salt '*' mount.write_mount_cache /mnt/share /dev/sda1 False ext4 defaults,nosuid ''' cache = salt.utils.mount.read_cache(__opts__) if not cache: cache = {} cache['mounts'] = {} else: if 'mounts' not in cache: cache['mounts'] = {} cache['mounts'][real_name] = {'device': device, 'fstype': fstype, 'mkmnt': mkmnt, 'opts': mount_opts} cache_write = salt.utils.mount.write_cache(cache, __opts__) if cache_write: return True else: raise CommandExecutionError('Unable to write mount cache.') def delete_mount_cache(real_name): ''' .. versionadded:: 2018.3.0 Provide information if the path is mounted CLI Example: .. code-block:: bash salt '*' mount.delete_mount_cache /mnt/share ''' cache = salt.utils.mount.read_cache(__opts__) if cache: if 'mounts' in cache: if real_name in cache['mounts']: del cache['mounts'][real_name] cache_write = salt.utils.mount.write_cache(cache, __opts__) if not cache_write: raise CommandExecutionError('Unable to write mount cache.') return True def _filesystems(config='/etc/filesystems', leading_key=True): ''' Return the contents of the filesystems in an OrderedDict config File containing filesystem infomation leading_key True return dictionary keyed by 'name' and value as dictionary with other keys, values (name excluded) OrderedDict({ '/dir' : OrderedDict({'dev': '/dev/hd8', .... }})) False return dictionary keyed by 'name' and value as dictionary with all keys, values (name included) OrderedDict({ '/dir' : OrderedDict({'name': '/dir', 'dev': '/dev/hd8', ... })}) ''' ret = OrderedDict() lines = [] parsing_block = False if not os.path.isfile(config) or 'AIX' not in __grains__['kernel']: return ret # read in block of filesystems, block starts with '/' till empty line with salt.utils.files.fopen(config) as ifile: for line in ifile: line = salt.utils.stringutils.to_unicode(line) # skip till first entry if not line.startswith('/') and not parsing_block: continue if line.startswith('/'): parsing_block = True lines.append(line) elif not line.split(): parsing_block = False try: entry = _FileSystemsEntry.dict_from_lines( lines, _FileSystemsEntry.compatibility_keys) lines = [] if 'opts' in entry: entry['opts'] = entry['opts'].split(',') while entry['name'] in ret: entry['name'] += '_' if leading_key: ret[entry.pop('name')] = entry else: ret[entry['name']] = entry except _FileSystemsEntry.ParseError: pass else: lines.append(line) return ret def filesystems(config='/etc/filesystems'): ''' .. versionadded:: 2018.3.3 List the contents of the filesystems CLI Example: .. code-block:: bash salt '*' mount.filesystems ''' ret = {} if 'AIX' not in __grains__['kernel']: return ret ret_dict = _filesystems(config) if ret_dict: ret_key = next(iter(ret_dict.keys())) ret = {ret_key: dict(ret_dict[ret_key])} return ret def set_filesystems( name, device, vfstype, opts='-', mount='true', config='/etc/filesystems', test=False, match_on='auto', **kwargs): ''' .. versionadded:: 2018.3.3 Verify that this mount is represented in the filesystems, change the mount to match the data passed, or add the mount if it is not present on AIX Provide information if the path is mounted :param name: The name of the mount point where the device is mounted. :param device: The device that is being mounted. :param vfstype: The file system that is used (AIX has two fstypes, fstype and vfstype - similar to Linux fstype) :param opts: Additional options used when mounting the device. :param mount: Mount if not mounted, default True. :param config: Configuration file, default /etc/filesystems. :param match: File systems type to match on, default auto CLI Example: .. code-block:: bash salt '*' mount.set_filesystems /mnt/foo /dev/sdz1 jfs2 ''' # Fix the opts type if it is a list if isinstance(opts, list): opts = ','.join(opts) # preserve arguments for updating entry_args = { 'name': name, 'dev': device.replace('\\ ', '\\040'), 'vfstype': vfstype, 'opts': opts, 'mount': mount, } view_lines = [] ret = None if 'AIX' not in __grains__['kernel']: return ret # Transform match_on into list--items will be checked later if isinstance(match_on, list): pass elif not isinstance(match_on, six.string_types): raise CommandExecutionError('match_on must be a string or list of strings') elif match_on == 'auto': # Try to guess right criteria for auto.... # added IBM types from sys/vmount.h after btrfs # NOTE: missing some special fstypes here specialFSes = frozenset([ 'none', 'tmpfs', 'sysfs', 'proc', 'fusectl', 'debugfs', 'securityfs', 'devtmpfs', 'cgroup', 'btrfs', 'cdrfs', 'procfs', 'jfs', 'jfs2', 'nfs', 'sfs', 'nfs3', 'cachefs', 'udfs', 'cifs', 'namefs', 'pmemfs', 'ahafs', 'nfs4', 'autofs', 'stnfs']) if vfstype in specialFSes: match_on = ['name'] else: match_on = ['dev'] else: match_on = [match_on] # generate entry and criteria objects, handle invalid keys in match_on entry_ip = _FileSystemsEntry.from_line(entry_args, kwargs) try: criteria = entry_ip.pick(match_on) except KeyError: filterFn = lambda key: key not in _FileSystemsEntry.compatibility_keys invalid_keys = filter(filterFn, match_on) raise CommandExecutionError('Unrecognized keys in match_on: "{0}"'.format(invalid_keys)) # parse file, use ret to cache status if not os.path.isfile(config): raise CommandExecutionError('Bad config file "{0}"'.format(config)) # read in block of filesystem, block starts with '/' till empty line try: fsys_filedict = _filesystems(config, False) for fsys_view in six.viewitems(fsys_filedict): if criteria.match(fsys_view): ret = 'present' if entry_ip.match(fsys_view): view_lines.append(fsys_view) else: ret = 'change' kv = entry_ip['name'] view_lines.append((kv, entry_ip)) else: view_lines.append(fsys_view) except (IOError, OSError) as exc: raise CommandExecutionError('Couldn\'t read from {0}: {1}'.format(config, exc)) # add line if not present or changed if ret is None: for dict_view in six.viewitems(entry_ip.dict_from_entry()): view_lines.append(dict_view) ret = 'new' if ret != 'present': # ret in ['new', 'change']: try: with salt.utils.files.fopen(config, 'wb') as ofile: # The line was changed, commit it! for fsys_view in view_lines: entry = fsys_view[1] mystrg = _FileSystemsEntry.dict_to_lines(entry) ofile.writelines(salt.utils.data.encode(mystrg)) except (IOError, OSError): raise CommandExecutionError('File not writable {0}'.format(config)) return ret def rm_filesystems(name, device, config='/etc/filesystems'): ''' .. versionadded:: 2018.3.3 Remove the mount point from the filesystems CLI Example: .. code-block:: bash salt '*' mount.rm_filesystems /mnt/foo /dev/sdg ''' modified = False view_lines = [] if 'AIX' not in __grains__['kernel']: return modified criteria = _FileSystemsEntry(name=name, dev=device) try: fsys_filedict = _filesystems(config, False) for fsys_view in six.viewitems(fsys_filedict): try: if criteria.match(fsys_view): modified = True else: view_lines.append(fsys_view) except _FileSystemsEntry.ParseError: view_lines.append(fsys_view) except (IOError, OSError) as exc: raise CommandExecutionError("Couldn't read from {0}: {1}".format(config, exc)) if modified: try: with salt.utils.files.fopen(config, 'wb') as ofile: for fsys_view in view_lines: entry = fsys_view[1] mystrg = _FileSystemsEntry.dict_to_lines(entry) ofile.writelines(salt.utils.data.encode(mystrg)) except (IOError, OSError) as exc: raise CommandExecutionError("Couldn't write to {0}: {1}".format(config, exc)) return modified
saltstack/salt
salt/modules/mount.py
is_fuse_exec
python
def is_fuse_exec(cmd): ''' Returns true if the command passed is a fuse mountable application. CLI Example: .. code-block:: bash salt '*' mount.is_fuse_exec sshfs ''' cmd_path = salt.utils.path.which(cmd) # No point in running ldd on a command that doesn't exist if not cmd_path: return False elif not salt.utils.path.which('ldd'): raise CommandNotFoundError('ldd') out = __salt__['cmd.run']('ldd {0}'.format(cmd_path), python_shell=False) return 'libfuse' in out
Returns true if the command passed is a fuse mountable application. CLI Example: .. code-block:: bash salt '*' mount.is_fuse_exec sshfs
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/mount.py#L1327-L1346
null
# -*- coding: utf-8 -*- ''' Salt module to manage Unix mounts and the fstab file ''' # Import python libs from __future__ import absolute_import, print_function, unicode_literals import os import re import logging # Import salt libs import salt.utils.args import salt.utils.data import salt.utils.files import salt.utils.path import salt.utils.platform import salt.utils.mount import salt.utils.stringutils from salt.utils.odict import OrderedDict from salt.exceptions import CommandNotFoundError, CommandExecutionError # Import 3rd-party libs from salt.ext import six from salt.ext.six.moves import filter, zip # pylint: disable=import-error,redefined-builtin # Set up logger log = logging.getLogger(__name__) # Define the module's virtual name __virtualname__ = 'mount' def __virtual__(): ''' Only load on POSIX-like systems ''' # Disable on Windows, a specific file module exists: if salt.utils.platform.is_windows(): return (False, 'The mount module cannot be loaded: not a POSIX-like system.') return True def _list_mounts(): ret = {} if __grains__['os'] in ['MacOS', 'Darwin']: mounts = __salt__['cmd.run_stdout']('mount') else: mounts = __salt__['cmd.run_stdout']('mount -l') for line in mounts.split('\n'): comps = re.sub(r"\s+", " ", line).split() if len(comps) >= 3: ret[comps[2]] = comps[0] return ret def _active_mountinfo(ret): _list = _list_mounts() filename = '/proc/self/mountinfo' if not os.access(filename, os.R_OK): msg = 'File not readable {0}' raise CommandExecutionError(msg.format(filename)) if 'disk.blkid' not in __context__: __context__['disk.blkid'] = __salt__['disk.blkid']() blkid_info = __context__['disk.blkid'] with salt.utils.files.fopen(filename) as ifile: for line in ifile: comps = salt.utils.stringutils.to_unicode(line).split() device = comps[2].split(':') # each line can have any number of # optional parameters, we use the # location of the separator field to # determine the location of the elements # after it. _sep = comps.index('-') device_name = comps[_sep + 2] device_uuid = None device_label = None if device_name: device_uuid = blkid_info.get(device_name, {}).get('UUID') device_uuid = device_uuid and device_uuid.lower() device_label = blkid_info.get(device_name, {}).get('LABEL') ret[comps[4]] = {'mountid': comps[0], 'parentid': comps[1], 'major': device[0], 'minor': device[1], 'root': comps[3], 'opts': _resolve_user_group_names(comps[5].split(',')), 'fstype': comps[_sep + 1], 'device': device_name.replace('\\040', '\\ '), 'alt_device': _list.get(comps[4], None), 'superopts': _resolve_user_group_names(comps[_sep + 3].split(',')), 'device_uuid': device_uuid, 'device_label': device_label} return ret def _active_mounts(ret): ''' List active mounts on Linux systems ''' _list = _list_mounts() filename = '/proc/self/mounts' if not os.access(filename, os.R_OK): msg = 'File not readable {0}' raise CommandExecutionError(msg.format(filename)) with salt.utils.files.fopen(filename) as ifile: for line in ifile: comps = salt.utils.stringutils.to_unicode(line).split() ret[comps[1]] = {'device': comps[0], 'alt_device': _list.get(comps[1], None), 'fstype': comps[2], 'opts': _resolve_user_group_names(comps[3].split(','))} return ret def _active_mounts_aix(ret): ''' List active mounts on AIX systems ''' for line in __salt__['cmd.run_stdout']('mount -p').split('\n'): comps = re.sub(r"\s+", " ", line).split() if comps: if comps[0] == 'node' or comps[0] == '--------': continue comps_len = len(comps) if line.startswith((' ', '\t')): curr_opts = _resolve_user_group_names(comps[6].split(',')) if 7 == comps_len else [] if curr_opts: ret[comps[1]] = {'device': comps[0], 'fstype': comps[2], 'opts': curr_opts} else: ret[comps[1]] = {'device': comps[0], 'fstype': comps[2]} else: curr_opts = _resolve_user_group_names(comps[7].split(',')) if 8 == comps_len else [] if curr_opts: ret[comps[2]] = {'node': comps[0], 'device': comps[1], 'fstype': comps[3], 'opts': curr_opts} else: ret[comps[2]] = {'node': comps[0], 'device': comps[1], 'fstype': comps[3]} return ret def _active_mounts_freebsd(ret): ''' List active mounts on FreeBSD systems ''' for line in __salt__['cmd.run_stdout']('mount -p').split('\n'): comps = re.sub(r"\s+", " ", line).split() ret[comps[1]] = {'device': comps[0], 'fstype': comps[2], 'opts': _resolve_user_group_names(comps[3].split(','))} return ret def _active_mounts_solaris(ret): ''' List active mounts on Solaris systems ''' for line in __salt__['cmd.run_stdout']('mount -v').split('\n'): comps = re.sub(r"\s+", " ", line).split() ret[comps[2]] = {'device': comps[0], 'fstype': comps[4], 'opts': _resolve_user_group_names(comps[5].split('/'))} return ret def _active_mounts_openbsd(ret): ''' List active mounts on OpenBSD systems ''' for line in __salt__['cmd.run_stdout']('mount -v').split('\n'): comps = re.sub(r"\s+", " ", line).split() parens = re.findall(r'\((.*?)\)', line, re.DOTALL) if len(parens) > 1: nod = __salt__['cmd.run_stdout']('ls -l {0}'.format(comps[0])) nod = ' '.join(nod.split()).split(" ") ret[comps[3]] = {'device': comps[0], 'fstype': comps[5], 'opts': _resolve_user_group_names(parens[1].split(", ")), 'major': six.text_type(nod[4].strip(",")), 'minor': six.text_type(nod[5]), 'device_uuid': parens[0]} else: ret[comps[2]] = {'device': comps[0], 'fstype': comps[4], 'opts': _resolve_user_group_names(parens[0].split(", "))} return ret def _active_mounts_darwin(ret): ''' List active mounts on Mac OS systems ''' for line in __salt__['cmd.run_stdout']('mount').split('\n'): comps = re.sub(r"\s+", " ", line).split() parens = re.findall(r'\((.*?)\)', line, re.DOTALL)[0].split(", ") ret[comps[2]] = {'device': comps[0], 'fstype': parens[0], 'opts': _resolve_user_group_names(parens[1:])} return ret def _resolve_user_group_names(opts): ''' Resolve user and group names in related opts ''' name_id_opts = {'uid': 'user.info', 'gid': 'group.info'} for ind, opt in enumerate(opts): if opt.split('=')[0] in name_id_opts: _givenid = opt.split('=')[1] _param = opt.split('=')[0] _id = _givenid if not re.match('[0-9]+$', _givenid): _info = __salt__[name_id_opts[_param]](_givenid) if _info and _param in _info: _id = _info[_param] opts[ind] = _param + '=' + six.text_type(_id) opts[ind] = opts[ind].replace('\\040', '\\ ') return opts def active(extended=False): ''' List the active mounts. CLI Example: .. code-block:: bash salt '*' mount.active ''' ret = {} if __grains__['os'] == 'FreeBSD': _active_mounts_freebsd(ret) elif 'AIX' in __grains__['kernel']: _active_mounts_aix(ret) elif __grains__['kernel'] == 'SunOS': _active_mounts_solaris(ret) elif __grains__['os'] == 'OpenBSD': _active_mounts_openbsd(ret) elif __grains__['os'] in ['MacOS', 'Darwin']: _active_mounts_darwin(ret) else: if extended: try: _active_mountinfo(ret) except CommandExecutionError: _active_mounts(ret) else: _active_mounts(ret) return ret class _fstab_entry(object): ''' Utility class for manipulating fstab entries. Primarily we're parsing, formatting, and comparing lines. Parsing emits dicts expected from fstab() or raises a ValueError. Note: We'll probably want to use os.normpath and os.normcase on 'name' ''' class ParseError(ValueError): ''' Error raised when a line isn't parsible as an fstab entry ''' fstab_keys = ('device', 'name', 'fstype', 'opts', 'dump', 'pass_num') # preserve data format compatibility_keys = ('device', 'name', 'fstype', 'opts', 'dump', 'pass') fstab_format = '{device}\t\t{name}\t{fstype}\t{opts}\t{dump} {pass_num}\n' @classmethod def dict_from_line(cls, line, keys=fstab_keys): if len(keys) != 6: raise ValueError('Invalid key array: {0}'.format(keys)) if line.startswith('#'): raise cls.ParseError("Comment!") comps = line.split() if len(comps) < 4 or len(comps) > 6: raise cls.ParseError("Invalid Entry!") comps.extend(['0'] * (len(keys) - len(comps))) return dict(zip(keys, comps)) @classmethod def from_line(cls, *args, **kwargs): return cls(** cls.dict_from_line(*args, **kwargs)) @classmethod def dict_to_line(cls, entry): return cls.fstab_format.format(**entry) def __str__(self): ''' String value, only works for full repr ''' return self.dict_to_line(self.criteria) def __repr__(self): ''' Always works ''' return repr(self.criteria) def pick(self, keys): ''' Returns an instance with just those keys ''' subset = dict([(key, self.criteria[key]) for key in keys]) return self.__class__(**subset) def __init__(self, **criteria): ''' Store non-empty, non-null values to use as filter ''' items = [key_value for key_value in six.iteritems(criteria) if key_value[1] is not None] items = [(key_value1[0], six.text_type(key_value1[1])) for key_value1 in items] self.criteria = dict(items) @staticmethod def norm_path(path): ''' Resolve equivalent paths equivalently ''' return os.path.normcase(os.path.normpath(path)) def match(self, line): ''' Compare potentially partial criteria against line ''' entry = self.dict_from_line(line) for key, value in six.iteritems(self.criteria): if entry[key] != value: return False return True class _vfstab_entry(object): ''' Utility class for manipulating vfstab entries. Primarily we're parsing, formatting, and comparing lines. Parsing emits dicts expected from fstab() or raises a ValueError. Note: We'll probably want to use os.normpath and os.normcase on 'name' Note: This parses vfstab entries on Solaris like systems #device device mount FS fsck mount mount #to mount to fsck point type pass at boot options # /devices - /devices devfs - no - ''' class ParseError(ValueError): '''Error raised when a line isn't parsible as an fstab entry''' vfstab_keys = ('device', 'device_fsck', 'name', 'fstype', 'pass_fsck', 'mount_at_boot', 'opts') # NOTE: weird formatting to match default spacing on Solaris vfstab_format = '{device:<11} {device_fsck:<3} {name:<19} {fstype:<8} {pass_fsck:<3} {mount_at_boot:<6} {opts}\n' @classmethod def dict_from_line(cls, line): if line.startswith('#'): raise cls.ParseError("Comment!") comps = line.split() if len(comps) != 7: raise cls.ParseError("Invalid Entry!") return dict(zip(cls.vfstab_keys, comps)) @classmethod def from_line(cls, *args, **kwargs): return cls(** cls.dict_from_line(*args, **kwargs)) @classmethod def dict_to_line(cls, entry): return cls.vfstab_format.format(**entry) def __str__(self): ''' String value, only works for full repr ''' return self.dict_to_line(self.criteria) def __repr__(self): ''' Always works ''' return repr(self.criteria) def pick(self, keys): ''' Returns an instance with just those keys ''' subset = dict([(key, self.criteria[key]) for key in keys]) return self.__class__(**subset) def __init__(self, **criteria): ''' Store non-empty, non-null values to use as filter ''' items = [key_value for key_value in six.iteritems(criteria) if key_value[1] is not None] items = [(key_value1[0], six.text_type(key_value1[1])) for key_value1 in items] self.criteria = dict(items) @staticmethod def norm_path(path): ''' Resolve equivalent paths equivalently ''' return os.path.normcase(os.path.normpath(path)) def match(self, line): ''' Compare potentially partial criteria against line ''' entry = self.dict_from_line(line) for key, value in six.iteritems(self.criteria): if entry[key] != value: return False return True class _FileSystemsEntry(object): ''' Utility class for manipulating filesystem entries. Primarily we're parsing, formatting, and comparing lines. Parsing emits dicts expected from fstab() or raises a ValueError. Note: We'll probably want to use os.normpath and os.normcase on 'name' ''' class ParseError(ValueError): ''' Error raised when a line isn't parsible as an fstab entry ''' filesystems_keys = ('device', 'name', 'fstype', 'vfstype', 'opts', 'mount') # preserve data format of filesystems compatibility_keys = ('dev', 'dev', 'name', 'fstype', 'vfstype', 'opts', 'mount', 'type', 'vfs', 'account', 'boot', 'check', 'free', 'nodename', 'quota', 'size', 'vol', 'log') @classmethod def dict_from_lines(cls, lines, keys=filesystems_keys): if len(lines) < 2: raise ValueError('Invalid number of lines: {0}'.format(lines)) if not keys: # if empty force default filesystems_keys keys = _FileSystemsEntry.filesystems_keys elif len(keys) < 6: raise ValueError('Invalid key name array: {0}'.format(keys)) blk_lines = lines orddict = OrderedDict() orddict['name'] = blk_lines[0].split(':')[0].strip() blk_lines.pop(0) for line in blk_lines: if line.startswith('#'): raise cls.ParseError("Comment!") comps = line.split('= ') if len(comps) != 2: raise cls.ParseError("Invalid Entry!") key_name = comps[0].strip() if key_name in keys: orddict[key_name] = comps[1].strip() else: raise ValueError('Invalid name for use in filesystems: {0}'.format(key_name)) return orddict @classmethod def dict_from_cmd_line(cls, ipargs, keys): cmdln_dict = ipargs if keys: for key, value in keys: # ignore unknown or local scope keys if key.startswith('__'): continue if key in _FileSystemsEntry.compatibility_keys: cmdln_dict[key] = value return cmdln_dict @classmethod def from_line(cls, *args, **kwargs): return cls(** cls.dict_from_cmd_line(*args, **kwargs)) @classmethod def dict_to_lines(cls, fsys_dict_entry): entry = fsys_dict_entry strg_out = entry['name'] + ':' + os.linesep for k, v in six.viewitems(entry): if 'name' not in k: strg_out += '\t{0}\t\t= {1}'.format(k, v) + os.linesep strg_out += os.linesep return six.text_type(strg_out) def dict_from_entry(self): ret = OrderedDict() ret[self.criteria['name']] = self.criteria return ret def __str__(self): ''' String value, only works for full repr ''' return self.dict_to_lines(self.criteria) def __repr__(self): ''' Always works ''' return repr(self.criteria) def pick(self, keys): ''' Returns an instance with just those keys ''' subset = dict([(key, self.criteria[key]) for key in keys]) return self.__class__(**subset) def __init__(self, **criteria): ''' Store non-empty, non-null values to use as filter ''' items = [key_value for key_value in six.iteritems(criteria) if key_value[1] is not None] items = [(key_value1[0], six.text_type(key_value1[1])) for key_value1 in items] self.criteria = OrderedDict(items) @staticmethod def norm_path(path): ''' Resolve equivalent paths equivalently ''' return os.path.normcase(os.path.normpath(path)) def match(self, fsys_view): ''' Compare potentially partial criteria against built filesystems entry dictionary ''' evalue_dict = fsys_view[1] for key, value in six.viewitems(self.criteria): if key in evalue_dict: if evalue_dict[key] != value: return False else: return False return True def __getitem__(self, key): ''' Return value for input key ''' return self.criteria[key] def fstab(config='/etc/fstab'): ''' .. versionchanged:: 2016.3.2 List the contents of the fstab CLI Example: .. code-block:: bash salt '*' mount.fstab ''' ret = {} if not os.path.isfile(config): return ret with salt.utils.files.fopen(config) as ifile: for line in ifile: line = salt.utils.stringutils.to_unicode(line) try: if __grains__['kernel'] == 'SunOS': # Note: comments use in default vfstab file! if line[0] == '#': continue entry = _vfstab_entry.dict_from_line( line) else: entry = _fstab_entry.dict_from_line( line, _fstab_entry.compatibility_keys) entry['opts'] = entry['opts'].split(',') while entry['name'] in ret: entry['name'] += '_' ret[entry.pop('name')] = entry except _fstab_entry.ParseError: pass except _vfstab_entry.ParseError: pass return ret def vfstab(config='/etc/vfstab'): ''' .. versionadded:: 2016.3.2 List the contents of the vfstab CLI Example: .. code-block:: bash salt '*' mount.vfstab ''' # NOTE: vfstab is a wrapper for fstab return fstab(config) def rm_fstab(name, device, config='/etc/fstab'): ''' .. versionchanged:: 2016.3.2 Remove the mount point from the fstab CLI Example: .. code-block:: bash salt '*' mount.rm_fstab /mnt/foo /dev/sdg ''' modified = False if __grains__['kernel'] == 'SunOS': criteria = _vfstab_entry(name=name, device=device) else: criteria = _fstab_entry(name=name, device=device) lines = [] try: with salt.utils.files.fopen(config, 'r') as ifile: for line in ifile: line = salt.utils.stringutils.to_unicode(line) try: if criteria.match(line): modified = True else: lines.append(line) except _fstab_entry.ParseError: lines.append(line) except _vfstab_entry.ParseError: lines.append(line) except (IOError, OSError) as exc: msg = "Couldn't read from {0}: {1}" raise CommandExecutionError(msg.format(config, exc)) if modified: try: with salt.utils.files.fopen(config, 'wb') as ofile: ofile.writelines(salt.utils.data.encode(lines)) except (IOError, OSError) as exc: msg = "Couldn't write to {0}: {1}" raise CommandExecutionError(msg.format(config, exc)) # Note: not clear why we always return 'True' # --just copying previous behavior at this point... return True def rm_vfstab(name, device, config='/etc/vfstab'): ''' .. versionadded:: 2016.3.2 Remove the mount point from the vfstab CLI Example: .. code-block:: bash salt '*' mount.rm_vfstab /mnt/foo /device/c0t0d0p0 ''' ## NOTE: rm_vfstab is a wrapper for rm_fstab return rm_fstab(name, device, config) def set_fstab( name, device, fstype, opts='defaults', dump=0, pass_num=0, config='/etc/fstab', test=False, match_on='auto', **kwargs): ''' Verify that this mount is represented in the fstab, change the mount to match the data passed, or add the mount if it is not present. CLI Example: .. code-block:: bash salt '*' mount.set_fstab /mnt/foo /dev/sdz1 ext4 ''' # Fix the opts type if it is a list if isinstance(opts, list): opts = ','.join(opts) # preserve arguments for updating entry_args = { 'name': name, 'device': device.replace('\\ ', '\\040'), 'fstype': fstype, 'opts': opts.replace('\\ ', '\\040'), 'dump': dump, 'pass_num': pass_num, } lines = [] ret = None # Transform match_on into list--items will be checked later if isinstance(match_on, list): pass elif not isinstance(match_on, six.string_types): msg = 'match_on must be a string or list of strings' raise CommandExecutionError(msg) elif match_on == 'auto': # Try to guess right criteria for auto.... # NOTE: missing some special fstypes here specialFSes = frozenset([ 'none', 'tmpfs', 'sysfs', 'proc', 'fusectl', 'debugfs', 'securityfs', 'devtmpfs', 'cgroup', 'btrfs']) if fstype in specialFSes: match_on = ['name'] else: match_on = ['device'] else: match_on = [match_on] # generate entry and criteria objects, handle invalid keys in match_on entry = _fstab_entry(**entry_args) try: criteria = entry.pick(match_on) except KeyError: filterFn = lambda key: key not in _fstab_entry.fstab_keys invalid_keys = filter(filterFn, match_on) msg = 'Unrecognized keys in match_on: "{0}"'.format(invalid_keys) raise CommandExecutionError(msg) # parse file, use ret to cache status if not os.path.isfile(config): raise CommandExecutionError('Bad config file "{0}"'.format(config)) try: with salt.utils.files.fopen(config, 'r') as ifile: for line in ifile: line = salt.utils.stringutils.to_unicode(line) try: if criteria.match(line): # Note: If ret isn't None here, # we've matched multiple lines ret = 'present' if entry.match(line): lines.append(line) else: ret = 'change' lines.append(six.text_type(entry)) else: lines.append(line) except _fstab_entry.ParseError: lines.append(line) except (IOError, OSError) as exc: msg = 'Couldn\'t read from {0}: {1}' raise CommandExecutionError(msg.format(config, exc)) # add line if not present or changed if ret is None: lines.append(six.text_type(entry)) ret = 'new' if ret != 'present': # ret in ['new', 'change']: if not salt.utils.args.test_mode(test=test, **kwargs): try: with salt.utils.files.fopen(config, 'wb') as ofile: # The line was changed, commit it! ofile.writelines(salt.utils.data.encode(lines)) except (IOError, OSError): msg = 'File not writable {0}' raise CommandExecutionError(msg.format(config)) return ret def set_vfstab( name, device, fstype, opts='-', device_fsck='-', pass_fsck='-', mount_at_boot='yes', config='/etc/vfstab', test=False, match_on='auto', **kwargs): ''' ..verionadded:: 2016.3.2 Verify that this mount is represented in the fstab, change the mount to match the data passed, or add the mount if it is not present. CLI Example: .. code-block:: bash salt '*' mount.set_vfstab /mnt/foo /device/c0t0d0p0 ufs ''' # Fix the opts type if it is a list if isinstance(opts, list): opts = ','.join(opts) # Map unknown values for mount_at_boot to no if mount_at_boot != 'yes': mount_at_boot = 'no' # preserve arguments for updating entry_args = { 'name': name, 'device': device, 'fstype': fstype, 'opts': opts, 'device_fsck': device_fsck, 'pass_fsck': pass_fsck, 'mount_at_boot': mount_at_boot, } lines = [] ret = None # Transform match_on into list--items will be checked later if isinstance(match_on, list): pass elif not isinstance(match_on, six.string_types): msg = 'match_on must be a string or list of strings' raise CommandExecutionError(msg) elif match_on == 'auto': # Try to guess right criteria for auto.... # NOTE: missing some special fstypes here specialFSes = frozenset([ 'devfs', 'proc', 'ctfs', 'objfs', 'sharefs', 'fs', 'tmpfs']) if fstype in specialFSes: match_on = ['name'] else: match_on = ['device'] else: match_on = [match_on] # generate entry and criteria objects, handle invalid keys in match_on entry = _vfstab_entry(**entry_args) try: criteria = entry.pick(match_on) except KeyError: filterFn = lambda key: key not in _vfstab_entry.vfstab_keys invalid_keys = filter(filterFn, match_on) msg = 'Unrecognized keys in match_on: "{0}"'.format(invalid_keys) raise CommandExecutionError(msg) # parse file, use ret to cache status if not os.path.isfile(config): raise CommandExecutionError('Bad config file "{0}"'.format(config)) try: with salt.utils.files.fopen(config, 'r') as ifile: for line in ifile: line = salt.utils.stringutils.to_unicode(line) try: if criteria.match(line): # Note: If ret isn't None here, # we've matched multiple lines ret = 'present' if entry.match(line): lines.append(line) else: ret = 'change' lines.append(six.text_type(entry)) else: lines.append(line) except _vfstab_entry.ParseError: lines.append(line) except (IOError, OSError) as exc: msg = 'Couldn\'t read from {0}: {1}' raise CommandExecutionError(msg.format(config, exc)) # add line if not present or changed if ret is None: lines.append(six.text_type(entry)) ret = 'new' if ret != 'present': # ret in ['new', 'change']: if not salt.utils.args.test_mode(test=test, **kwargs): try: with salt.utils.files.fopen(config, 'wb') as ofile: # The line was changed, commit it! ofile.writelines(salt.utils.data.encode(lines)) except (IOError, OSError): msg = 'File not writable {0}' raise CommandExecutionError(msg.format(config)) return ret def rm_automaster(name, device, config='/etc/auto_salt'): ''' Remove the mount point from the auto_master CLI Example: .. code-block:: bash salt '*' mount.rm_automaster /mnt/foo /dev/sdg ''' contents = automaster(config) if name not in contents: return True # The entry is present, get rid of it lines = [] try: with salt.utils.files.fopen(config, 'r') as ifile: for line in ifile: line = salt.utils.stringutils.to_unicode(line) if line.startswith('#'): # Commented lines.append(line) continue if not line.strip(): # Blank line lines.append(line) continue comps = line.split() if len(comps) != 3: # Invalid entry lines.append(line) continue comps = line.split() prefix = "/.." name_chk = comps[0].replace(prefix, "") device_fmt = comps[2].split(":") if device: if name_chk == name and device_fmt[1] == device: continue else: if name_chk == name: continue lines.append(line) except (IOError, OSError) as exc: msg = "Couldn't read from {0}: {1}" raise CommandExecutionError(msg.format(config, exc)) try: with salt.utils.files.fopen(config, 'wb') as ofile: ofile.writelines(salt.utils.data.encode(lines)) except (IOError, OSError) as exc: msg = "Couldn't write to {0}: {1}" raise CommandExecutionError(msg.format(config, exc)) # Update automount __salt__['cmd.run']('automount -cv') return True def set_automaster( name, device, fstype, opts='', config='/etc/auto_salt', test=False, **kwargs): ''' Verify that this mount is represented in the auto_salt, change the mount to match the data passed, or add the mount if it is not present. CLI Example: .. code-block:: bash salt '*' mount.set_automaster /mnt/foo /dev/sdz1 ext4 ''' # Fix the opts type if it is a list if isinstance(opts, list): opts = ','.join(opts) lines = [] change = False present = False automaster_file = "/etc/auto_master" if not os.path.isfile(config): __salt__['file.touch'](config) __salt__['file.append'](automaster_file, "/-\t\t\t{0}".format(config)) name = "/..{0}".format(name) device_fmt = "{0}:{1}".format(fstype, device) type_opts = "-fstype={0},{1}".format(fstype, opts) if fstype == 'smbfs': device_fmt = device_fmt.replace(fstype, "") try: with salt.utils.files.fopen(config, 'r') as ifile: for line in ifile: line = salt.utils.stringutils.to_unicode(line) if line.startswith('#'): # Commented lines.append(line) continue if not line.strip(): # Blank line lines.append(line) continue comps = line.split() if len(comps) != 3: # Invalid entry lines.append(line) continue if comps[0] == name or comps[2] == device_fmt: # check to see if there are changes # and fix them if there are any present = True if comps[0] != name: change = True comps[0] = name if comps[1] != type_opts: change = True comps[1] = type_opts if comps[2] != device_fmt: change = True comps[2] = device_fmt if change: log.debug( 'auto_master entry for mount point %s needs to be ' 'updated', name ) newline = ( '{0}\t{1}\t{2}\n'.format( name, type_opts, device_fmt) ) lines.append(newline) else: lines.append(line) except (IOError, OSError) as exc: msg = 'Couldn\'t read from {0}: {1}' raise CommandExecutionError(msg.format(config, exc)) if change: if not salt.utils.args.test_mode(test=test, **kwargs): try: with salt.utils.files.fopen(config, 'wb') as ofile: # The line was changed, commit it! ofile.writelines(salt.utils.data.encode(lines)) except (IOError, OSError): msg = 'File not writable {0}' raise CommandExecutionError(msg.format(config)) return 'change' if not change: if present: # The right entry is already here return 'present' else: if not salt.utils.args.test_mode(test=test, **kwargs): # The entry is new, add it to the end of the fstab newline = ( '{0}\t{1}\t{2}\n'.format( name, type_opts, device_fmt) ) lines.append(newline) try: with salt.utils.files.fopen(config, 'wb') as ofile: # The line was changed, commit it! ofile.writelines(salt.utils.data.encode(lines)) except (IOError, OSError): raise CommandExecutionError( 'File not writable {0}'.format( config ) ) return 'new' def automaster(config='/etc/auto_salt'): ''' List the contents of the auto master CLI Example: .. code-block:: bash salt '*' mount.automaster ''' ret = {} if not os.path.isfile(config): return ret with salt.utils.files.fopen(config) as ifile: for line in ifile: line = salt.utils.stringutils.to_unicode(line) if line.startswith('#'): # Commented continue if not line.strip(): # Blank line continue comps = line.split() if len(comps) != 3: # Invalid entry continue prefix = "/.." name = comps[0].replace(prefix, "") device_fmt = comps[2].split(":") opts = comps[1].split(',') ret[name] = {'device': device_fmt[1], 'fstype': opts[0], 'opts': opts[1:]} return ret def mount(name, device, mkmnt=False, fstype='', opts='defaults', user=None, util='mount'): ''' Mount a device CLI Example: .. code-block:: bash salt '*' mount.mount /mnt/foo /dev/sdz1 True ''' if util != 'mount': # This functionality used to live in img.mount_image if util == 'guestfs': return __salt__['guestfs.mount'](name, root=device) elif util == 'qemu_nbd': mnt = __salt__['qemu_nbd.init'](name, device) if not mnt: return False first = next(six.iterkeys(mnt)) __context__['img.mnt_{0}'.format(first)] = mnt return first return False # Darwin doesn't expect defaults when mounting without other options if 'defaults' in opts and __grains__['os'] in ['MacOS', 'Darwin', 'AIX']: opts = None if isinstance(opts, six.string_types): opts = opts.split(',') if not os.path.exists(name) and mkmnt: __salt__['file.mkdir'](name, user=user) args = '' if opts is not None: lopts = ','.join(opts) args = '-o {0}'.format(lopts) if fstype: # use of fstype on AIX differs from typical Linux use of -t # functionality AIX uses -v vfsname, -t fstype mounts all with # fstype in /etc/filesystems if 'AIX' in __grains__['os']: args += ' -v {0}'.format(fstype) elif 'solaris' in __grains__['os'].lower(): args += ' -F {0}'.format(fstype) else: args += ' -t {0}'.format(fstype) cmd = 'mount {0} {1} {2} '.format(args, device, name) out = __salt__['cmd.run_all'](cmd, runas=user, python_shell=False) if out['retcode']: return out['stderr'] return True def remount(name, device, mkmnt=False, fstype='', opts='defaults', user=None): ''' Attempt to remount a device, if the device is not already mounted, mount is called CLI Example: .. code-block:: bash salt '*' mount.remount /mnt/foo /dev/sdz1 True ''' force_mount = False if __grains__['os'] in ['MacOS', 'Darwin']: if opts == 'defaults': opts = 'noowners' if fstype == 'smbfs': force_mount = True if 'AIX' in __grains__['os']: if opts == 'defaults': opts = [] if isinstance(opts, six.string_types): opts = opts.split(',') mnts = active() if name in mnts: # The mount point is mounted, attempt to remount it with the given data if 'remount' not in opts and __grains__['os'] not in ['OpenBSD', 'MacOS', 'Darwin']: opts.append('remount') if force_mount: # We need to force the mount but first we should unmount umount(name, device, user=user) lopts = ','.join(opts) args = '-o {0}'.format(lopts) if fstype: # use of fstype on AIX differs from typical Linux use of # -t functionality AIX uses -v vfsname, -t fstype mounts # all with fstype in /etc/filesystems if 'AIX' in __grains__['os']: args += ' -v {0}'.format(fstype) elif 'solaris' in __grains__['os'].lower(): args += ' -F {0}'.format(fstype) else: args += ' -t {0}'.format(fstype) if __grains__['os'] not in ['OpenBSD', 'MacOS', 'Darwin'] or force_mount: cmd = 'mount {0} {1} {2} '.format(args, device, name) else: cmd = 'mount -u {0} {1} {2} '.format(args, device, name) out = __salt__['cmd.run_all'](cmd, runas=user, python_shell=False) if out['retcode']: return out['stderr'] return True # Mount a filesystem that isn't already return mount(name, device, mkmnt, fstype, opts, user=user) def umount(name, device=None, user=None, util='mount'): ''' Attempt to unmount a device by specifying the directory it is mounted on CLI Example: .. code-block:: bash salt '*' mount.umount /mnt/foo .. versionadded:: 2015.5.0 .. code-block:: bash salt '*' mount.umount /mnt/foo /dev/xvdc1 ''' if util != 'mount': # This functionality used to live in img.umount_image if 'qemu_nbd.clear' in __salt__: if 'img.mnt_{0}'.format(name) in __context__: __salt__['qemu_nbd.clear'](__context__['img.mnt_{0}'.format(name)]) return mnts = active() if name not in mnts: return "{0} does not have anything mounted".format(name) if not device: cmd = 'umount {0}'.format(name) else: cmd = 'umount {0}'.format(device) out = __salt__['cmd.run_all'](cmd, runas=user, python_shell=False) if out['retcode']: return out['stderr'] return True def swaps(): ''' Return a dict containing information on active swap .. versionchanged:: 2016.3.2 CLI Example: .. code-block:: bash salt '*' mount.swaps ''' ret = {} if __grains__['kernel'] == 'SunOS': for line in __salt__['cmd.run_stdout']('swap -l').splitlines(): if line.startswith('swapfile'): continue comps = line.split() ret[comps[0]] = {'type': 'device' if comps[0].startswith(('/dev', 'swap')) else 'file', 'size': int(comps[3]), 'used': (int(comps[3]) - int(comps[4])), 'priority': '-'} elif 'AIX' in __grains__['kernel']: for line in __salt__['cmd.run_stdout']('swap -l').splitlines(): if line.startswith('device'): continue comps = line.split() # AIX uses MB for units ret[comps[0]] = {'type': 'device', 'size': int(comps[3][:-2]) * 1024, 'used': (int(comps[3][:-2]) - int(comps[4][:-2])) * 1024, 'priority': '-'} elif __grains__['os'] != 'OpenBSD': with salt.utils.files.fopen('/proc/swaps') as fp_: for line in fp_: line = salt.utils.stringutils.to_unicode(line) if line.startswith('Filename'): continue comps = line.split() ret[comps[0]] = {'type': comps[1], 'size': comps[2], 'used': comps[3], 'priority': comps[4]} else: for line in __salt__['cmd.run_stdout']('swapctl -kl').splitlines(): if line.startswith(('Device', 'Total')): continue swap_type = "file" comps = line.split() if comps[0].startswith('/dev/'): swap_type = "partition" ret[comps[0]] = {'type': swap_type, 'size': comps[1], 'used': comps[2], 'priority': comps[5]} return ret def swapon(name, priority=None): ''' Activate a swap disk .. versionchanged:: 2016.3.2 CLI Example: .. code-block:: bash salt '*' mount.swapon /root/swapfile ''' ret = {} on_ = swaps() if name in on_: ret['stats'] = on_[name] ret['new'] = False return ret if __grains__['kernel'] == 'SunOS': if __grains__['virtual'] != 'zone': __salt__['cmd.run']('swap -a {0}'.format(name), python_shell=False) else: return False else: cmd = 'swapon {0}'.format(name) if priority and 'AIX' not in __grains__['kernel']: cmd += ' -p {0}'.format(priority) __salt__['cmd.run'](cmd, python_shell=False) on_ = swaps() if name in on_: ret['stats'] = on_[name] ret['new'] = True return ret return ret def swapoff(name): ''' Deactivate a named swap mount .. versionchanged:: 2016.3.2 CLI Example: .. code-block:: bash salt '*' mount.swapoff /root/swapfile ''' on_ = swaps() if name in on_: if __grains__['kernel'] == 'SunOS': if __grains__['virtual'] != 'zone': __salt__['cmd.run']('swap -a {0}'.format(name), python_shell=False) else: return False elif __grains__['os'] != 'OpenBSD': __salt__['cmd.run']('swapoff {0}'.format(name), python_shell=False) else: __salt__['cmd.run']('swapctl -d {0}'.format(name), python_shell=False) on_ = swaps() if name in on_: return False return True return None def is_mounted(name): ''' .. versionadded:: 2014.7.0 Provide information if the path is mounted CLI Example: .. code-block:: bash salt '*' mount.is_mounted /mnt/share ''' active_ = active() if name in active_: return True else: return False def read_mount_cache(name): ''' .. versionadded:: 2018.3.0 Provide information if the path is mounted CLI Example: .. code-block:: bash salt '*' mount.read_mount_cache /mnt/share ''' cache = salt.utils.mount.read_cache(__opts__) if cache: if 'mounts' in cache and cache['mounts']: if name in cache['mounts']: return cache['mounts'][name] return {} def write_mount_cache(real_name, device, mkmnt, fstype, mount_opts): ''' .. versionadded:: 2018.3.0 Provide information if the path is mounted :param real_name: The real name of the mount point where the device is mounted. :param device: The device that is being mounted. :param mkmnt: Whether or not the mount point should be created. :param fstype: The file system that is used. :param mount_opts: Additional options used when mounting the device. :return: Boolean if message was sent successfully. CLI Example: .. code-block:: bash salt '*' mount.write_mount_cache /mnt/share /dev/sda1 False ext4 defaults,nosuid ''' cache = salt.utils.mount.read_cache(__opts__) if not cache: cache = {} cache['mounts'] = {} else: if 'mounts' not in cache: cache['mounts'] = {} cache['mounts'][real_name] = {'device': device, 'fstype': fstype, 'mkmnt': mkmnt, 'opts': mount_opts} cache_write = salt.utils.mount.write_cache(cache, __opts__) if cache_write: return True else: raise CommandExecutionError('Unable to write mount cache.') def delete_mount_cache(real_name): ''' .. versionadded:: 2018.3.0 Provide information if the path is mounted CLI Example: .. code-block:: bash salt '*' mount.delete_mount_cache /mnt/share ''' cache = salt.utils.mount.read_cache(__opts__) if cache: if 'mounts' in cache: if real_name in cache['mounts']: del cache['mounts'][real_name] cache_write = salt.utils.mount.write_cache(cache, __opts__) if not cache_write: raise CommandExecutionError('Unable to write mount cache.') return True def _filesystems(config='/etc/filesystems', leading_key=True): ''' Return the contents of the filesystems in an OrderedDict config File containing filesystem infomation leading_key True return dictionary keyed by 'name' and value as dictionary with other keys, values (name excluded) OrderedDict({ '/dir' : OrderedDict({'dev': '/dev/hd8', .... }})) False return dictionary keyed by 'name' and value as dictionary with all keys, values (name included) OrderedDict({ '/dir' : OrderedDict({'name': '/dir', 'dev': '/dev/hd8', ... })}) ''' ret = OrderedDict() lines = [] parsing_block = False if not os.path.isfile(config) or 'AIX' not in __grains__['kernel']: return ret # read in block of filesystems, block starts with '/' till empty line with salt.utils.files.fopen(config) as ifile: for line in ifile: line = salt.utils.stringutils.to_unicode(line) # skip till first entry if not line.startswith('/') and not parsing_block: continue if line.startswith('/'): parsing_block = True lines.append(line) elif not line.split(): parsing_block = False try: entry = _FileSystemsEntry.dict_from_lines( lines, _FileSystemsEntry.compatibility_keys) lines = [] if 'opts' in entry: entry['opts'] = entry['opts'].split(',') while entry['name'] in ret: entry['name'] += '_' if leading_key: ret[entry.pop('name')] = entry else: ret[entry['name']] = entry except _FileSystemsEntry.ParseError: pass else: lines.append(line) return ret def filesystems(config='/etc/filesystems'): ''' .. versionadded:: 2018.3.3 List the contents of the filesystems CLI Example: .. code-block:: bash salt '*' mount.filesystems ''' ret = {} if 'AIX' not in __grains__['kernel']: return ret ret_dict = _filesystems(config) if ret_dict: ret_key = next(iter(ret_dict.keys())) ret = {ret_key: dict(ret_dict[ret_key])} return ret def set_filesystems( name, device, vfstype, opts='-', mount='true', config='/etc/filesystems', test=False, match_on='auto', **kwargs): ''' .. versionadded:: 2018.3.3 Verify that this mount is represented in the filesystems, change the mount to match the data passed, or add the mount if it is not present on AIX Provide information if the path is mounted :param name: The name of the mount point where the device is mounted. :param device: The device that is being mounted. :param vfstype: The file system that is used (AIX has two fstypes, fstype and vfstype - similar to Linux fstype) :param opts: Additional options used when mounting the device. :param mount: Mount if not mounted, default True. :param config: Configuration file, default /etc/filesystems. :param match: File systems type to match on, default auto CLI Example: .. code-block:: bash salt '*' mount.set_filesystems /mnt/foo /dev/sdz1 jfs2 ''' # Fix the opts type if it is a list if isinstance(opts, list): opts = ','.join(opts) # preserve arguments for updating entry_args = { 'name': name, 'dev': device.replace('\\ ', '\\040'), 'vfstype': vfstype, 'opts': opts, 'mount': mount, } view_lines = [] ret = None if 'AIX' not in __grains__['kernel']: return ret # Transform match_on into list--items will be checked later if isinstance(match_on, list): pass elif not isinstance(match_on, six.string_types): raise CommandExecutionError('match_on must be a string or list of strings') elif match_on == 'auto': # Try to guess right criteria for auto.... # added IBM types from sys/vmount.h after btrfs # NOTE: missing some special fstypes here specialFSes = frozenset([ 'none', 'tmpfs', 'sysfs', 'proc', 'fusectl', 'debugfs', 'securityfs', 'devtmpfs', 'cgroup', 'btrfs', 'cdrfs', 'procfs', 'jfs', 'jfs2', 'nfs', 'sfs', 'nfs3', 'cachefs', 'udfs', 'cifs', 'namefs', 'pmemfs', 'ahafs', 'nfs4', 'autofs', 'stnfs']) if vfstype in specialFSes: match_on = ['name'] else: match_on = ['dev'] else: match_on = [match_on] # generate entry and criteria objects, handle invalid keys in match_on entry_ip = _FileSystemsEntry.from_line(entry_args, kwargs) try: criteria = entry_ip.pick(match_on) except KeyError: filterFn = lambda key: key not in _FileSystemsEntry.compatibility_keys invalid_keys = filter(filterFn, match_on) raise CommandExecutionError('Unrecognized keys in match_on: "{0}"'.format(invalid_keys)) # parse file, use ret to cache status if not os.path.isfile(config): raise CommandExecutionError('Bad config file "{0}"'.format(config)) # read in block of filesystem, block starts with '/' till empty line try: fsys_filedict = _filesystems(config, False) for fsys_view in six.viewitems(fsys_filedict): if criteria.match(fsys_view): ret = 'present' if entry_ip.match(fsys_view): view_lines.append(fsys_view) else: ret = 'change' kv = entry_ip['name'] view_lines.append((kv, entry_ip)) else: view_lines.append(fsys_view) except (IOError, OSError) as exc: raise CommandExecutionError('Couldn\'t read from {0}: {1}'.format(config, exc)) # add line if not present or changed if ret is None: for dict_view in six.viewitems(entry_ip.dict_from_entry()): view_lines.append(dict_view) ret = 'new' if ret != 'present': # ret in ['new', 'change']: try: with salt.utils.files.fopen(config, 'wb') as ofile: # The line was changed, commit it! for fsys_view in view_lines: entry = fsys_view[1] mystrg = _FileSystemsEntry.dict_to_lines(entry) ofile.writelines(salt.utils.data.encode(mystrg)) except (IOError, OSError): raise CommandExecutionError('File not writable {0}'.format(config)) return ret def rm_filesystems(name, device, config='/etc/filesystems'): ''' .. versionadded:: 2018.3.3 Remove the mount point from the filesystems CLI Example: .. code-block:: bash salt '*' mount.rm_filesystems /mnt/foo /dev/sdg ''' modified = False view_lines = [] if 'AIX' not in __grains__['kernel']: return modified criteria = _FileSystemsEntry(name=name, dev=device) try: fsys_filedict = _filesystems(config, False) for fsys_view in six.viewitems(fsys_filedict): try: if criteria.match(fsys_view): modified = True else: view_lines.append(fsys_view) except _FileSystemsEntry.ParseError: view_lines.append(fsys_view) except (IOError, OSError) as exc: raise CommandExecutionError("Couldn't read from {0}: {1}".format(config, exc)) if modified: try: with salt.utils.files.fopen(config, 'wb') as ofile: for fsys_view in view_lines: entry = fsys_view[1] mystrg = _FileSystemsEntry.dict_to_lines(entry) ofile.writelines(salt.utils.data.encode(mystrg)) except (IOError, OSError) as exc: raise CommandExecutionError("Couldn't write to {0}: {1}".format(config, exc)) return modified
saltstack/salt
salt/modules/mount.py
swaps
python
def swaps(): ''' Return a dict containing information on active swap .. versionchanged:: 2016.3.2 CLI Example: .. code-block:: bash salt '*' mount.swaps ''' ret = {} if __grains__['kernel'] == 'SunOS': for line in __salt__['cmd.run_stdout']('swap -l').splitlines(): if line.startswith('swapfile'): continue comps = line.split() ret[comps[0]] = {'type': 'device' if comps[0].startswith(('/dev', 'swap')) else 'file', 'size': int(comps[3]), 'used': (int(comps[3]) - int(comps[4])), 'priority': '-'} elif 'AIX' in __grains__['kernel']: for line in __salt__['cmd.run_stdout']('swap -l').splitlines(): if line.startswith('device'): continue comps = line.split() # AIX uses MB for units ret[comps[0]] = {'type': 'device', 'size': int(comps[3][:-2]) * 1024, 'used': (int(comps[3][:-2]) - int(comps[4][:-2])) * 1024, 'priority': '-'} elif __grains__['os'] != 'OpenBSD': with salt.utils.files.fopen('/proc/swaps') as fp_: for line in fp_: line = salt.utils.stringutils.to_unicode(line) if line.startswith('Filename'): continue comps = line.split() ret[comps[0]] = {'type': comps[1], 'size': comps[2], 'used': comps[3], 'priority': comps[4]} else: for line in __salt__['cmd.run_stdout']('swapctl -kl').splitlines(): if line.startswith(('Device', 'Total')): continue swap_type = "file" comps = line.split() if comps[0].startswith('/dev/'): swap_type = "partition" ret[comps[0]] = {'type': swap_type, 'size': comps[1], 'used': comps[2], 'priority': comps[5]} return ret
Return a dict containing information on active swap .. versionchanged:: 2016.3.2 CLI Example: .. code-block:: bash salt '*' mount.swaps
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/mount.py#L1349-L1405
[ "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 -*- ''' Salt module to manage Unix mounts and the fstab file ''' # Import python libs from __future__ import absolute_import, print_function, unicode_literals import os import re import logging # Import salt libs import salt.utils.args import salt.utils.data import salt.utils.files import salt.utils.path import salt.utils.platform import salt.utils.mount import salt.utils.stringutils from salt.utils.odict import OrderedDict from salt.exceptions import CommandNotFoundError, CommandExecutionError # Import 3rd-party libs from salt.ext import six from salt.ext.six.moves import filter, zip # pylint: disable=import-error,redefined-builtin # Set up logger log = logging.getLogger(__name__) # Define the module's virtual name __virtualname__ = 'mount' def __virtual__(): ''' Only load on POSIX-like systems ''' # Disable on Windows, a specific file module exists: if salt.utils.platform.is_windows(): return (False, 'The mount module cannot be loaded: not a POSIX-like system.') return True def _list_mounts(): ret = {} if __grains__['os'] in ['MacOS', 'Darwin']: mounts = __salt__['cmd.run_stdout']('mount') else: mounts = __salt__['cmd.run_stdout']('mount -l') for line in mounts.split('\n'): comps = re.sub(r"\s+", " ", line).split() if len(comps) >= 3: ret[comps[2]] = comps[0] return ret def _active_mountinfo(ret): _list = _list_mounts() filename = '/proc/self/mountinfo' if not os.access(filename, os.R_OK): msg = 'File not readable {0}' raise CommandExecutionError(msg.format(filename)) if 'disk.blkid' not in __context__: __context__['disk.blkid'] = __salt__['disk.blkid']() blkid_info = __context__['disk.blkid'] with salt.utils.files.fopen(filename) as ifile: for line in ifile: comps = salt.utils.stringutils.to_unicode(line).split() device = comps[2].split(':') # each line can have any number of # optional parameters, we use the # location of the separator field to # determine the location of the elements # after it. _sep = comps.index('-') device_name = comps[_sep + 2] device_uuid = None device_label = None if device_name: device_uuid = blkid_info.get(device_name, {}).get('UUID') device_uuid = device_uuid and device_uuid.lower() device_label = blkid_info.get(device_name, {}).get('LABEL') ret[comps[4]] = {'mountid': comps[0], 'parentid': comps[1], 'major': device[0], 'minor': device[1], 'root': comps[3], 'opts': _resolve_user_group_names(comps[5].split(',')), 'fstype': comps[_sep + 1], 'device': device_name.replace('\\040', '\\ '), 'alt_device': _list.get(comps[4], None), 'superopts': _resolve_user_group_names(comps[_sep + 3].split(',')), 'device_uuid': device_uuid, 'device_label': device_label} return ret def _active_mounts(ret): ''' List active mounts on Linux systems ''' _list = _list_mounts() filename = '/proc/self/mounts' if not os.access(filename, os.R_OK): msg = 'File not readable {0}' raise CommandExecutionError(msg.format(filename)) with salt.utils.files.fopen(filename) as ifile: for line in ifile: comps = salt.utils.stringutils.to_unicode(line).split() ret[comps[1]] = {'device': comps[0], 'alt_device': _list.get(comps[1], None), 'fstype': comps[2], 'opts': _resolve_user_group_names(comps[3].split(','))} return ret def _active_mounts_aix(ret): ''' List active mounts on AIX systems ''' for line in __salt__['cmd.run_stdout']('mount -p').split('\n'): comps = re.sub(r"\s+", " ", line).split() if comps: if comps[0] == 'node' or comps[0] == '--------': continue comps_len = len(comps) if line.startswith((' ', '\t')): curr_opts = _resolve_user_group_names(comps[6].split(',')) if 7 == comps_len else [] if curr_opts: ret[comps[1]] = {'device': comps[0], 'fstype': comps[2], 'opts': curr_opts} else: ret[comps[1]] = {'device': comps[0], 'fstype': comps[2]} else: curr_opts = _resolve_user_group_names(comps[7].split(',')) if 8 == comps_len else [] if curr_opts: ret[comps[2]] = {'node': comps[0], 'device': comps[1], 'fstype': comps[3], 'opts': curr_opts} else: ret[comps[2]] = {'node': comps[0], 'device': comps[1], 'fstype': comps[3]} return ret def _active_mounts_freebsd(ret): ''' List active mounts on FreeBSD systems ''' for line in __salt__['cmd.run_stdout']('mount -p').split('\n'): comps = re.sub(r"\s+", " ", line).split() ret[comps[1]] = {'device': comps[0], 'fstype': comps[2], 'opts': _resolve_user_group_names(comps[3].split(','))} return ret def _active_mounts_solaris(ret): ''' List active mounts on Solaris systems ''' for line in __salt__['cmd.run_stdout']('mount -v').split('\n'): comps = re.sub(r"\s+", " ", line).split() ret[comps[2]] = {'device': comps[0], 'fstype': comps[4], 'opts': _resolve_user_group_names(comps[5].split('/'))} return ret def _active_mounts_openbsd(ret): ''' List active mounts on OpenBSD systems ''' for line in __salt__['cmd.run_stdout']('mount -v').split('\n'): comps = re.sub(r"\s+", " ", line).split() parens = re.findall(r'\((.*?)\)', line, re.DOTALL) if len(parens) > 1: nod = __salt__['cmd.run_stdout']('ls -l {0}'.format(comps[0])) nod = ' '.join(nod.split()).split(" ") ret[comps[3]] = {'device': comps[0], 'fstype': comps[5], 'opts': _resolve_user_group_names(parens[1].split(", ")), 'major': six.text_type(nod[4].strip(",")), 'minor': six.text_type(nod[5]), 'device_uuid': parens[0]} else: ret[comps[2]] = {'device': comps[0], 'fstype': comps[4], 'opts': _resolve_user_group_names(parens[0].split(", "))} return ret def _active_mounts_darwin(ret): ''' List active mounts on Mac OS systems ''' for line in __salt__['cmd.run_stdout']('mount').split('\n'): comps = re.sub(r"\s+", " ", line).split() parens = re.findall(r'\((.*?)\)', line, re.DOTALL)[0].split(", ") ret[comps[2]] = {'device': comps[0], 'fstype': parens[0], 'opts': _resolve_user_group_names(parens[1:])} return ret def _resolve_user_group_names(opts): ''' Resolve user and group names in related opts ''' name_id_opts = {'uid': 'user.info', 'gid': 'group.info'} for ind, opt in enumerate(opts): if opt.split('=')[0] in name_id_opts: _givenid = opt.split('=')[1] _param = opt.split('=')[0] _id = _givenid if not re.match('[0-9]+$', _givenid): _info = __salt__[name_id_opts[_param]](_givenid) if _info and _param in _info: _id = _info[_param] opts[ind] = _param + '=' + six.text_type(_id) opts[ind] = opts[ind].replace('\\040', '\\ ') return opts def active(extended=False): ''' List the active mounts. CLI Example: .. code-block:: bash salt '*' mount.active ''' ret = {} if __grains__['os'] == 'FreeBSD': _active_mounts_freebsd(ret) elif 'AIX' in __grains__['kernel']: _active_mounts_aix(ret) elif __grains__['kernel'] == 'SunOS': _active_mounts_solaris(ret) elif __grains__['os'] == 'OpenBSD': _active_mounts_openbsd(ret) elif __grains__['os'] in ['MacOS', 'Darwin']: _active_mounts_darwin(ret) else: if extended: try: _active_mountinfo(ret) except CommandExecutionError: _active_mounts(ret) else: _active_mounts(ret) return ret class _fstab_entry(object): ''' Utility class for manipulating fstab entries. Primarily we're parsing, formatting, and comparing lines. Parsing emits dicts expected from fstab() or raises a ValueError. Note: We'll probably want to use os.normpath and os.normcase on 'name' ''' class ParseError(ValueError): ''' Error raised when a line isn't parsible as an fstab entry ''' fstab_keys = ('device', 'name', 'fstype', 'opts', 'dump', 'pass_num') # preserve data format compatibility_keys = ('device', 'name', 'fstype', 'opts', 'dump', 'pass') fstab_format = '{device}\t\t{name}\t{fstype}\t{opts}\t{dump} {pass_num}\n' @classmethod def dict_from_line(cls, line, keys=fstab_keys): if len(keys) != 6: raise ValueError('Invalid key array: {0}'.format(keys)) if line.startswith('#'): raise cls.ParseError("Comment!") comps = line.split() if len(comps) < 4 or len(comps) > 6: raise cls.ParseError("Invalid Entry!") comps.extend(['0'] * (len(keys) - len(comps))) return dict(zip(keys, comps)) @classmethod def from_line(cls, *args, **kwargs): return cls(** cls.dict_from_line(*args, **kwargs)) @classmethod def dict_to_line(cls, entry): return cls.fstab_format.format(**entry) def __str__(self): ''' String value, only works for full repr ''' return self.dict_to_line(self.criteria) def __repr__(self): ''' Always works ''' return repr(self.criteria) def pick(self, keys): ''' Returns an instance with just those keys ''' subset = dict([(key, self.criteria[key]) for key in keys]) return self.__class__(**subset) def __init__(self, **criteria): ''' Store non-empty, non-null values to use as filter ''' items = [key_value for key_value in six.iteritems(criteria) if key_value[1] is not None] items = [(key_value1[0], six.text_type(key_value1[1])) for key_value1 in items] self.criteria = dict(items) @staticmethod def norm_path(path): ''' Resolve equivalent paths equivalently ''' return os.path.normcase(os.path.normpath(path)) def match(self, line): ''' Compare potentially partial criteria against line ''' entry = self.dict_from_line(line) for key, value in six.iteritems(self.criteria): if entry[key] != value: return False return True class _vfstab_entry(object): ''' Utility class for manipulating vfstab entries. Primarily we're parsing, formatting, and comparing lines. Parsing emits dicts expected from fstab() or raises a ValueError. Note: We'll probably want to use os.normpath and os.normcase on 'name' Note: This parses vfstab entries on Solaris like systems #device device mount FS fsck mount mount #to mount to fsck point type pass at boot options # /devices - /devices devfs - no - ''' class ParseError(ValueError): '''Error raised when a line isn't parsible as an fstab entry''' vfstab_keys = ('device', 'device_fsck', 'name', 'fstype', 'pass_fsck', 'mount_at_boot', 'opts') # NOTE: weird formatting to match default spacing on Solaris vfstab_format = '{device:<11} {device_fsck:<3} {name:<19} {fstype:<8} {pass_fsck:<3} {mount_at_boot:<6} {opts}\n' @classmethod def dict_from_line(cls, line): if line.startswith('#'): raise cls.ParseError("Comment!") comps = line.split() if len(comps) != 7: raise cls.ParseError("Invalid Entry!") return dict(zip(cls.vfstab_keys, comps)) @classmethod def from_line(cls, *args, **kwargs): return cls(** cls.dict_from_line(*args, **kwargs)) @classmethod def dict_to_line(cls, entry): return cls.vfstab_format.format(**entry) def __str__(self): ''' String value, only works for full repr ''' return self.dict_to_line(self.criteria) def __repr__(self): ''' Always works ''' return repr(self.criteria) def pick(self, keys): ''' Returns an instance with just those keys ''' subset = dict([(key, self.criteria[key]) for key in keys]) return self.__class__(**subset) def __init__(self, **criteria): ''' Store non-empty, non-null values to use as filter ''' items = [key_value for key_value in six.iteritems(criteria) if key_value[1] is not None] items = [(key_value1[0], six.text_type(key_value1[1])) for key_value1 in items] self.criteria = dict(items) @staticmethod def norm_path(path): ''' Resolve equivalent paths equivalently ''' return os.path.normcase(os.path.normpath(path)) def match(self, line): ''' Compare potentially partial criteria against line ''' entry = self.dict_from_line(line) for key, value in six.iteritems(self.criteria): if entry[key] != value: return False return True class _FileSystemsEntry(object): ''' Utility class for manipulating filesystem entries. Primarily we're parsing, formatting, and comparing lines. Parsing emits dicts expected from fstab() or raises a ValueError. Note: We'll probably want to use os.normpath and os.normcase on 'name' ''' class ParseError(ValueError): ''' Error raised when a line isn't parsible as an fstab entry ''' filesystems_keys = ('device', 'name', 'fstype', 'vfstype', 'opts', 'mount') # preserve data format of filesystems compatibility_keys = ('dev', 'dev', 'name', 'fstype', 'vfstype', 'opts', 'mount', 'type', 'vfs', 'account', 'boot', 'check', 'free', 'nodename', 'quota', 'size', 'vol', 'log') @classmethod def dict_from_lines(cls, lines, keys=filesystems_keys): if len(lines) < 2: raise ValueError('Invalid number of lines: {0}'.format(lines)) if not keys: # if empty force default filesystems_keys keys = _FileSystemsEntry.filesystems_keys elif len(keys) < 6: raise ValueError('Invalid key name array: {0}'.format(keys)) blk_lines = lines orddict = OrderedDict() orddict['name'] = blk_lines[0].split(':')[0].strip() blk_lines.pop(0) for line in blk_lines: if line.startswith('#'): raise cls.ParseError("Comment!") comps = line.split('= ') if len(comps) != 2: raise cls.ParseError("Invalid Entry!") key_name = comps[0].strip() if key_name in keys: orddict[key_name] = comps[1].strip() else: raise ValueError('Invalid name for use in filesystems: {0}'.format(key_name)) return orddict @classmethod def dict_from_cmd_line(cls, ipargs, keys): cmdln_dict = ipargs if keys: for key, value in keys: # ignore unknown or local scope keys if key.startswith('__'): continue if key in _FileSystemsEntry.compatibility_keys: cmdln_dict[key] = value return cmdln_dict @classmethod def from_line(cls, *args, **kwargs): return cls(** cls.dict_from_cmd_line(*args, **kwargs)) @classmethod def dict_to_lines(cls, fsys_dict_entry): entry = fsys_dict_entry strg_out = entry['name'] + ':' + os.linesep for k, v in six.viewitems(entry): if 'name' not in k: strg_out += '\t{0}\t\t= {1}'.format(k, v) + os.linesep strg_out += os.linesep return six.text_type(strg_out) def dict_from_entry(self): ret = OrderedDict() ret[self.criteria['name']] = self.criteria return ret def __str__(self): ''' String value, only works for full repr ''' return self.dict_to_lines(self.criteria) def __repr__(self): ''' Always works ''' return repr(self.criteria) def pick(self, keys): ''' Returns an instance with just those keys ''' subset = dict([(key, self.criteria[key]) for key in keys]) return self.__class__(**subset) def __init__(self, **criteria): ''' Store non-empty, non-null values to use as filter ''' items = [key_value for key_value in six.iteritems(criteria) if key_value[1] is not None] items = [(key_value1[0], six.text_type(key_value1[1])) for key_value1 in items] self.criteria = OrderedDict(items) @staticmethod def norm_path(path): ''' Resolve equivalent paths equivalently ''' return os.path.normcase(os.path.normpath(path)) def match(self, fsys_view): ''' Compare potentially partial criteria against built filesystems entry dictionary ''' evalue_dict = fsys_view[1] for key, value in six.viewitems(self.criteria): if key in evalue_dict: if evalue_dict[key] != value: return False else: return False return True def __getitem__(self, key): ''' Return value for input key ''' return self.criteria[key] def fstab(config='/etc/fstab'): ''' .. versionchanged:: 2016.3.2 List the contents of the fstab CLI Example: .. code-block:: bash salt '*' mount.fstab ''' ret = {} if not os.path.isfile(config): return ret with salt.utils.files.fopen(config) as ifile: for line in ifile: line = salt.utils.stringutils.to_unicode(line) try: if __grains__['kernel'] == 'SunOS': # Note: comments use in default vfstab file! if line[0] == '#': continue entry = _vfstab_entry.dict_from_line( line) else: entry = _fstab_entry.dict_from_line( line, _fstab_entry.compatibility_keys) entry['opts'] = entry['opts'].split(',') while entry['name'] in ret: entry['name'] += '_' ret[entry.pop('name')] = entry except _fstab_entry.ParseError: pass except _vfstab_entry.ParseError: pass return ret def vfstab(config='/etc/vfstab'): ''' .. versionadded:: 2016.3.2 List the contents of the vfstab CLI Example: .. code-block:: bash salt '*' mount.vfstab ''' # NOTE: vfstab is a wrapper for fstab return fstab(config) def rm_fstab(name, device, config='/etc/fstab'): ''' .. versionchanged:: 2016.3.2 Remove the mount point from the fstab CLI Example: .. code-block:: bash salt '*' mount.rm_fstab /mnt/foo /dev/sdg ''' modified = False if __grains__['kernel'] == 'SunOS': criteria = _vfstab_entry(name=name, device=device) else: criteria = _fstab_entry(name=name, device=device) lines = [] try: with salt.utils.files.fopen(config, 'r') as ifile: for line in ifile: line = salt.utils.stringutils.to_unicode(line) try: if criteria.match(line): modified = True else: lines.append(line) except _fstab_entry.ParseError: lines.append(line) except _vfstab_entry.ParseError: lines.append(line) except (IOError, OSError) as exc: msg = "Couldn't read from {0}: {1}" raise CommandExecutionError(msg.format(config, exc)) if modified: try: with salt.utils.files.fopen(config, 'wb') as ofile: ofile.writelines(salt.utils.data.encode(lines)) except (IOError, OSError) as exc: msg = "Couldn't write to {0}: {1}" raise CommandExecutionError(msg.format(config, exc)) # Note: not clear why we always return 'True' # --just copying previous behavior at this point... return True def rm_vfstab(name, device, config='/etc/vfstab'): ''' .. versionadded:: 2016.3.2 Remove the mount point from the vfstab CLI Example: .. code-block:: bash salt '*' mount.rm_vfstab /mnt/foo /device/c0t0d0p0 ''' ## NOTE: rm_vfstab is a wrapper for rm_fstab return rm_fstab(name, device, config) def set_fstab( name, device, fstype, opts='defaults', dump=0, pass_num=0, config='/etc/fstab', test=False, match_on='auto', **kwargs): ''' Verify that this mount is represented in the fstab, change the mount to match the data passed, or add the mount if it is not present. CLI Example: .. code-block:: bash salt '*' mount.set_fstab /mnt/foo /dev/sdz1 ext4 ''' # Fix the opts type if it is a list if isinstance(opts, list): opts = ','.join(opts) # preserve arguments for updating entry_args = { 'name': name, 'device': device.replace('\\ ', '\\040'), 'fstype': fstype, 'opts': opts.replace('\\ ', '\\040'), 'dump': dump, 'pass_num': pass_num, } lines = [] ret = None # Transform match_on into list--items will be checked later if isinstance(match_on, list): pass elif not isinstance(match_on, six.string_types): msg = 'match_on must be a string or list of strings' raise CommandExecutionError(msg) elif match_on == 'auto': # Try to guess right criteria for auto.... # NOTE: missing some special fstypes here specialFSes = frozenset([ 'none', 'tmpfs', 'sysfs', 'proc', 'fusectl', 'debugfs', 'securityfs', 'devtmpfs', 'cgroup', 'btrfs']) if fstype in specialFSes: match_on = ['name'] else: match_on = ['device'] else: match_on = [match_on] # generate entry and criteria objects, handle invalid keys in match_on entry = _fstab_entry(**entry_args) try: criteria = entry.pick(match_on) except KeyError: filterFn = lambda key: key not in _fstab_entry.fstab_keys invalid_keys = filter(filterFn, match_on) msg = 'Unrecognized keys in match_on: "{0}"'.format(invalid_keys) raise CommandExecutionError(msg) # parse file, use ret to cache status if not os.path.isfile(config): raise CommandExecutionError('Bad config file "{0}"'.format(config)) try: with salt.utils.files.fopen(config, 'r') as ifile: for line in ifile: line = salt.utils.stringutils.to_unicode(line) try: if criteria.match(line): # Note: If ret isn't None here, # we've matched multiple lines ret = 'present' if entry.match(line): lines.append(line) else: ret = 'change' lines.append(six.text_type(entry)) else: lines.append(line) except _fstab_entry.ParseError: lines.append(line) except (IOError, OSError) as exc: msg = 'Couldn\'t read from {0}: {1}' raise CommandExecutionError(msg.format(config, exc)) # add line if not present or changed if ret is None: lines.append(six.text_type(entry)) ret = 'new' if ret != 'present': # ret in ['new', 'change']: if not salt.utils.args.test_mode(test=test, **kwargs): try: with salt.utils.files.fopen(config, 'wb') as ofile: # The line was changed, commit it! ofile.writelines(salt.utils.data.encode(lines)) except (IOError, OSError): msg = 'File not writable {0}' raise CommandExecutionError(msg.format(config)) return ret def set_vfstab( name, device, fstype, opts='-', device_fsck='-', pass_fsck='-', mount_at_boot='yes', config='/etc/vfstab', test=False, match_on='auto', **kwargs): ''' ..verionadded:: 2016.3.2 Verify that this mount is represented in the fstab, change the mount to match the data passed, or add the mount if it is not present. CLI Example: .. code-block:: bash salt '*' mount.set_vfstab /mnt/foo /device/c0t0d0p0 ufs ''' # Fix the opts type if it is a list if isinstance(opts, list): opts = ','.join(opts) # Map unknown values for mount_at_boot to no if mount_at_boot != 'yes': mount_at_boot = 'no' # preserve arguments for updating entry_args = { 'name': name, 'device': device, 'fstype': fstype, 'opts': opts, 'device_fsck': device_fsck, 'pass_fsck': pass_fsck, 'mount_at_boot': mount_at_boot, } lines = [] ret = None # Transform match_on into list--items will be checked later if isinstance(match_on, list): pass elif not isinstance(match_on, six.string_types): msg = 'match_on must be a string or list of strings' raise CommandExecutionError(msg) elif match_on == 'auto': # Try to guess right criteria for auto.... # NOTE: missing some special fstypes here specialFSes = frozenset([ 'devfs', 'proc', 'ctfs', 'objfs', 'sharefs', 'fs', 'tmpfs']) if fstype in specialFSes: match_on = ['name'] else: match_on = ['device'] else: match_on = [match_on] # generate entry and criteria objects, handle invalid keys in match_on entry = _vfstab_entry(**entry_args) try: criteria = entry.pick(match_on) except KeyError: filterFn = lambda key: key not in _vfstab_entry.vfstab_keys invalid_keys = filter(filterFn, match_on) msg = 'Unrecognized keys in match_on: "{0}"'.format(invalid_keys) raise CommandExecutionError(msg) # parse file, use ret to cache status if not os.path.isfile(config): raise CommandExecutionError('Bad config file "{0}"'.format(config)) try: with salt.utils.files.fopen(config, 'r') as ifile: for line in ifile: line = salt.utils.stringutils.to_unicode(line) try: if criteria.match(line): # Note: If ret isn't None here, # we've matched multiple lines ret = 'present' if entry.match(line): lines.append(line) else: ret = 'change' lines.append(six.text_type(entry)) else: lines.append(line) except _vfstab_entry.ParseError: lines.append(line) except (IOError, OSError) as exc: msg = 'Couldn\'t read from {0}: {1}' raise CommandExecutionError(msg.format(config, exc)) # add line if not present or changed if ret is None: lines.append(six.text_type(entry)) ret = 'new' if ret != 'present': # ret in ['new', 'change']: if not salt.utils.args.test_mode(test=test, **kwargs): try: with salt.utils.files.fopen(config, 'wb') as ofile: # The line was changed, commit it! ofile.writelines(salt.utils.data.encode(lines)) except (IOError, OSError): msg = 'File not writable {0}' raise CommandExecutionError(msg.format(config)) return ret def rm_automaster(name, device, config='/etc/auto_salt'): ''' Remove the mount point from the auto_master CLI Example: .. code-block:: bash salt '*' mount.rm_automaster /mnt/foo /dev/sdg ''' contents = automaster(config) if name not in contents: return True # The entry is present, get rid of it lines = [] try: with salt.utils.files.fopen(config, 'r') as ifile: for line in ifile: line = salt.utils.stringutils.to_unicode(line) if line.startswith('#'): # Commented lines.append(line) continue if not line.strip(): # Blank line lines.append(line) continue comps = line.split() if len(comps) != 3: # Invalid entry lines.append(line) continue comps = line.split() prefix = "/.." name_chk = comps[0].replace(prefix, "") device_fmt = comps[2].split(":") if device: if name_chk == name and device_fmt[1] == device: continue else: if name_chk == name: continue lines.append(line) except (IOError, OSError) as exc: msg = "Couldn't read from {0}: {1}" raise CommandExecutionError(msg.format(config, exc)) try: with salt.utils.files.fopen(config, 'wb') as ofile: ofile.writelines(salt.utils.data.encode(lines)) except (IOError, OSError) as exc: msg = "Couldn't write to {0}: {1}" raise CommandExecutionError(msg.format(config, exc)) # Update automount __salt__['cmd.run']('automount -cv') return True def set_automaster( name, device, fstype, opts='', config='/etc/auto_salt', test=False, **kwargs): ''' Verify that this mount is represented in the auto_salt, change the mount to match the data passed, or add the mount if it is not present. CLI Example: .. code-block:: bash salt '*' mount.set_automaster /mnt/foo /dev/sdz1 ext4 ''' # Fix the opts type if it is a list if isinstance(opts, list): opts = ','.join(opts) lines = [] change = False present = False automaster_file = "/etc/auto_master" if not os.path.isfile(config): __salt__['file.touch'](config) __salt__['file.append'](automaster_file, "/-\t\t\t{0}".format(config)) name = "/..{0}".format(name) device_fmt = "{0}:{1}".format(fstype, device) type_opts = "-fstype={0},{1}".format(fstype, opts) if fstype == 'smbfs': device_fmt = device_fmt.replace(fstype, "") try: with salt.utils.files.fopen(config, 'r') as ifile: for line in ifile: line = salt.utils.stringutils.to_unicode(line) if line.startswith('#'): # Commented lines.append(line) continue if not line.strip(): # Blank line lines.append(line) continue comps = line.split() if len(comps) != 3: # Invalid entry lines.append(line) continue if comps[0] == name or comps[2] == device_fmt: # check to see if there are changes # and fix them if there are any present = True if comps[0] != name: change = True comps[0] = name if comps[1] != type_opts: change = True comps[1] = type_opts if comps[2] != device_fmt: change = True comps[2] = device_fmt if change: log.debug( 'auto_master entry for mount point %s needs to be ' 'updated', name ) newline = ( '{0}\t{1}\t{2}\n'.format( name, type_opts, device_fmt) ) lines.append(newline) else: lines.append(line) except (IOError, OSError) as exc: msg = 'Couldn\'t read from {0}: {1}' raise CommandExecutionError(msg.format(config, exc)) if change: if not salt.utils.args.test_mode(test=test, **kwargs): try: with salt.utils.files.fopen(config, 'wb') as ofile: # The line was changed, commit it! ofile.writelines(salt.utils.data.encode(lines)) except (IOError, OSError): msg = 'File not writable {0}' raise CommandExecutionError(msg.format(config)) return 'change' if not change: if present: # The right entry is already here return 'present' else: if not salt.utils.args.test_mode(test=test, **kwargs): # The entry is new, add it to the end of the fstab newline = ( '{0}\t{1}\t{2}\n'.format( name, type_opts, device_fmt) ) lines.append(newline) try: with salt.utils.files.fopen(config, 'wb') as ofile: # The line was changed, commit it! ofile.writelines(salt.utils.data.encode(lines)) except (IOError, OSError): raise CommandExecutionError( 'File not writable {0}'.format( config ) ) return 'new' def automaster(config='/etc/auto_salt'): ''' List the contents of the auto master CLI Example: .. code-block:: bash salt '*' mount.automaster ''' ret = {} if not os.path.isfile(config): return ret with salt.utils.files.fopen(config) as ifile: for line in ifile: line = salt.utils.stringutils.to_unicode(line) if line.startswith('#'): # Commented continue if not line.strip(): # Blank line continue comps = line.split() if len(comps) != 3: # Invalid entry continue prefix = "/.." name = comps[0].replace(prefix, "") device_fmt = comps[2].split(":") opts = comps[1].split(',') ret[name] = {'device': device_fmt[1], 'fstype': opts[0], 'opts': opts[1:]} return ret def mount(name, device, mkmnt=False, fstype='', opts='defaults', user=None, util='mount'): ''' Mount a device CLI Example: .. code-block:: bash salt '*' mount.mount /mnt/foo /dev/sdz1 True ''' if util != 'mount': # This functionality used to live in img.mount_image if util == 'guestfs': return __salt__['guestfs.mount'](name, root=device) elif util == 'qemu_nbd': mnt = __salt__['qemu_nbd.init'](name, device) if not mnt: return False first = next(six.iterkeys(mnt)) __context__['img.mnt_{0}'.format(first)] = mnt return first return False # Darwin doesn't expect defaults when mounting without other options if 'defaults' in opts and __grains__['os'] in ['MacOS', 'Darwin', 'AIX']: opts = None if isinstance(opts, six.string_types): opts = opts.split(',') if not os.path.exists(name) and mkmnt: __salt__['file.mkdir'](name, user=user) args = '' if opts is not None: lopts = ','.join(opts) args = '-o {0}'.format(lopts) if fstype: # use of fstype on AIX differs from typical Linux use of -t # functionality AIX uses -v vfsname, -t fstype mounts all with # fstype in /etc/filesystems if 'AIX' in __grains__['os']: args += ' -v {0}'.format(fstype) elif 'solaris' in __grains__['os'].lower(): args += ' -F {0}'.format(fstype) else: args += ' -t {0}'.format(fstype) cmd = 'mount {0} {1} {2} '.format(args, device, name) out = __salt__['cmd.run_all'](cmd, runas=user, python_shell=False) if out['retcode']: return out['stderr'] return True def remount(name, device, mkmnt=False, fstype='', opts='defaults', user=None): ''' Attempt to remount a device, if the device is not already mounted, mount is called CLI Example: .. code-block:: bash salt '*' mount.remount /mnt/foo /dev/sdz1 True ''' force_mount = False if __grains__['os'] in ['MacOS', 'Darwin']: if opts == 'defaults': opts = 'noowners' if fstype == 'smbfs': force_mount = True if 'AIX' in __grains__['os']: if opts == 'defaults': opts = [] if isinstance(opts, six.string_types): opts = opts.split(',') mnts = active() if name in mnts: # The mount point is mounted, attempt to remount it with the given data if 'remount' not in opts and __grains__['os'] not in ['OpenBSD', 'MacOS', 'Darwin']: opts.append('remount') if force_mount: # We need to force the mount but first we should unmount umount(name, device, user=user) lopts = ','.join(opts) args = '-o {0}'.format(lopts) if fstype: # use of fstype on AIX differs from typical Linux use of # -t functionality AIX uses -v vfsname, -t fstype mounts # all with fstype in /etc/filesystems if 'AIX' in __grains__['os']: args += ' -v {0}'.format(fstype) elif 'solaris' in __grains__['os'].lower(): args += ' -F {0}'.format(fstype) else: args += ' -t {0}'.format(fstype) if __grains__['os'] not in ['OpenBSD', 'MacOS', 'Darwin'] or force_mount: cmd = 'mount {0} {1} {2} '.format(args, device, name) else: cmd = 'mount -u {0} {1} {2} '.format(args, device, name) out = __salt__['cmd.run_all'](cmd, runas=user, python_shell=False) if out['retcode']: return out['stderr'] return True # Mount a filesystem that isn't already return mount(name, device, mkmnt, fstype, opts, user=user) def umount(name, device=None, user=None, util='mount'): ''' Attempt to unmount a device by specifying the directory it is mounted on CLI Example: .. code-block:: bash salt '*' mount.umount /mnt/foo .. versionadded:: 2015.5.0 .. code-block:: bash salt '*' mount.umount /mnt/foo /dev/xvdc1 ''' if util != 'mount': # This functionality used to live in img.umount_image if 'qemu_nbd.clear' in __salt__: if 'img.mnt_{0}'.format(name) in __context__: __salt__['qemu_nbd.clear'](__context__['img.mnt_{0}'.format(name)]) return mnts = active() if name not in mnts: return "{0} does not have anything mounted".format(name) if not device: cmd = 'umount {0}'.format(name) else: cmd = 'umount {0}'.format(device) out = __salt__['cmd.run_all'](cmd, runas=user, python_shell=False) if out['retcode']: return out['stderr'] return True def is_fuse_exec(cmd): ''' Returns true if the command passed is a fuse mountable application. CLI Example: .. code-block:: bash salt '*' mount.is_fuse_exec sshfs ''' cmd_path = salt.utils.path.which(cmd) # No point in running ldd on a command that doesn't exist if not cmd_path: return False elif not salt.utils.path.which('ldd'): raise CommandNotFoundError('ldd') out = __salt__['cmd.run']('ldd {0}'.format(cmd_path), python_shell=False) return 'libfuse' in out def swapon(name, priority=None): ''' Activate a swap disk .. versionchanged:: 2016.3.2 CLI Example: .. code-block:: bash salt '*' mount.swapon /root/swapfile ''' ret = {} on_ = swaps() if name in on_: ret['stats'] = on_[name] ret['new'] = False return ret if __grains__['kernel'] == 'SunOS': if __grains__['virtual'] != 'zone': __salt__['cmd.run']('swap -a {0}'.format(name), python_shell=False) else: return False else: cmd = 'swapon {0}'.format(name) if priority and 'AIX' not in __grains__['kernel']: cmd += ' -p {0}'.format(priority) __salt__['cmd.run'](cmd, python_shell=False) on_ = swaps() if name in on_: ret['stats'] = on_[name] ret['new'] = True return ret return ret def swapoff(name): ''' Deactivate a named swap mount .. versionchanged:: 2016.3.2 CLI Example: .. code-block:: bash salt '*' mount.swapoff /root/swapfile ''' on_ = swaps() if name in on_: if __grains__['kernel'] == 'SunOS': if __grains__['virtual'] != 'zone': __salt__['cmd.run']('swap -a {0}'.format(name), python_shell=False) else: return False elif __grains__['os'] != 'OpenBSD': __salt__['cmd.run']('swapoff {0}'.format(name), python_shell=False) else: __salt__['cmd.run']('swapctl -d {0}'.format(name), python_shell=False) on_ = swaps() if name in on_: return False return True return None def is_mounted(name): ''' .. versionadded:: 2014.7.0 Provide information if the path is mounted CLI Example: .. code-block:: bash salt '*' mount.is_mounted /mnt/share ''' active_ = active() if name in active_: return True else: return False def read_mount_cache(name): ''' .. versionadded:: 2018.3.0 Provide information if the path is mounted CLI Example: .. code-block:: bash salt '*' mount.read_mount_cache /mnt/share ''' cache = salt.utils.mount.read_cache(__opts__) if cache: if 'mounts' in cache and cache['mounts']: if name in cache['mounts']: return cache['mounts'][name] return {} def write_mount_cache(real_name, device, mkmnt, fstype, mount_opts): ''' .. versionadded:: 2018.3.0 Provide information if the path is mounted :param real_name: The real name of the mount point where the device is mounted. :param device: The device that is being mounted. :param mkmnt: Whether or not the mount point should be created. :param fstype: The file system that is used. :param mount_opts: Additional options used when mounting the device. :return: Boolean if message was sent successfully. CLI Example: .. code-block:: bash salt '*' mount.write_mount_cache /mnt/share /dev/sda1 False ext4 defaults,nosuid ''' cache = salt.utils.mount.read_cache(__opts__) if not cache: cache = {} cache['mounts'] = {} else: if 'mounts' not in cache: cache['mounts'] = {} cache['mounts'][real_name] = {'device': device, 'fstype': fstype, 'mkmnt': mkmnt, 'opts': mount_opts} cache_write = salt.utils.mount.write_cache(cache, __opts__) if cache_write: return True else: raise CommandExecutionError('Unable to write mount cache.') def delete_mount_cache(real_name): ''' .. versionadded:: 2018.3.0 Provide information if the path is mounted CLI Example: .. code-block:: bash salt '*' mount.delete_mount_cache /mnt/share ''' cache = salt.utils.mount.read_cache(__opts__) if cache: if 'mounts' in cache: if real_name in cache['mounts']: del cache['mounts'][real_name] cache_write = salt.utils.mount.write_cache(cache, __opts__) if not cache_write: raise CommandExecutionError('Unable to write mount cache.') return True def _filesystems(config='/etc/filesystems', leading_key=True): ''' Return the contents of the filesystems in an OrderedDict config File containing filesystem infomation leading_key True return dictionary keyed by 'name' and value as dictionary with other keys, values (name excluded) OrderedDict({ '/dir' : OrderedDict({'dev': '/dev/hd8', .... }})) False return dictionary keyed by 'name' and value as dictionary with all keys, values (name included) OrderedDict({ '/dir' : OrderedDict({'name': '/dir', 'dev': '/dev/hd8', ... })}) ''' ret = OrderedDict() lines = [] parsing_block = False if not os.path.isfile(config) or 'AIX' not in __grains__['kernel']: return ret # read in block of filesystems, block starts with '/' till empty line with salt.utils.files.fopen(config) as ifile: for line in ifile: line = salt.utils.stringutils.to_unicode(line) # skip till first entry if not line.startswith('/') and not parsing_block: continue if line.startswith('/'): parsing_block = True lines.append(line) elif not line.split(): parsing_block = False try: entry = _FileSystemsEntry.dict_from_lines( lines, _FileSystemsEntry.compatibility_keys) lines = [] if 'opts' in entry: entry['opts'] = entry['opts'].split(',') while entry['name'] in ret: entry['name'] += '_' if leading_key: ret[entry.pop('name')] = entry else: ret[entry['name']] = entry except _FileSystemsEntry.ParseError: pass else: lines.append(line) return ret def filesystems(config='/etc/filesystems'): ''' .. versionadded:: 2018.3.3 List the contents of the filesystems CLI Example: .. code-block:: bash salt '*' mount.filesystems ''' ret = {} if 'AIX' not in __grains__['kernel']: return ret ret_dict = _filesystems(config) if ret_dict: ret_key = next(iter(ret_dict.keys())) ret = {ret_key: dict(ret_dict[ret_key])} return ret def set_filesystems( name, device, vfstype, opts='-', mount='true', config='/etc/filesystems', test=False, match_on='auto', **kwargs): ''' .. versionadded:: 2018.3.3 Verify that this mount is represented in the filesystems, change the mount to match the data passed, or add the mount if it is not present on AIX Provide information if the path is mounted :param name: The name of the mount point where the device is mounted. :param device: The device that is being mounted. :param vfstype: The file system that is used (AIX has two fstypes, fstype and vfstype - similar to Linux fstype) :param opts: Additional options used when mounting the device. :param mount: Mount if not mounted, default True. :param config: Configuration file, default /etc/filesystems. :param match: File systems type to match on, default auto CLI Example: .. code-block:: bash salt '*' mount.set_filesystems /mnt/foo /dev/sdz1 jfs2 ''' # Fix the opts type if it is a list if isinstance(opts, list): opts = ','.join(opts) # preserve arguments for updating entry_args = { 'name': name, 'dev': device.replace('\\ ', '\\040'), 'vfstype': vfstype, 'opts': opts, 'mount': mount, } view_lines = [] ret = None if 'AIX' not in __grains__['kernel']: return ret # Transform match_on into list--items will be checked later if isinstance(match_on, list): pass elif not isinstance(match_on, six.string_types): raise CommandExecutionError('match_on must be a string or list of strings') elif match_on == 'auto': # Try to guess right criteria for auto.... # added IBM types from sys/vmount.h after btrfs # NOTE: missing some special fstypes here specialFSes = frozenset([ 'none', 'tmpfs', 'sysfs', 'proc', 'fusectl', 'debugfs', 'securityfs', 'devtmpfs', 'cgroup', 'btrfs', 'cdrfs', 'procfs', 'jfs', 'jfs2', 'nfs', 'sfs', 'nfs3', 'cachefs', 'udfs', 'cifs', 'namefs', 'pmemfs', 'ahafs', 'nfs4', 'autofs', 'stnfs']) if vfstype in specialFSes: match_on = ['name'] else: match_on = ['dev'] else: match_on = [match_on] # generate entry and criteria objects, handle invalid keys in match_on entry_ip = _FileSystemsEntry.from_line(entry_args, kwargs) try: criteria = entry_ip.pick(match_on) except KeyError: filterFn = lambda key: key not in _FileSystemsEntry.compatibility_keys invalid_keys = filter(filterFn, match_on) raise CommandExecutionError('Unrecognized keys in match_on: "{0}"'.format(invalid_keys)) # parse file, use ret to cache status if not os.path.isfile(config): raise CommandExecutionError('Bad config file "{0}"'.format(config)) # read in block of filesystem, block starts with '/' till empty line try: fsys_filedict = _filesystems(config, False) for fsys_view in six.viewitems(fsys_filedict): if criteria.match(fsys_view): ret = 'present' if entry_ip.match(fsys_view): view_lines.append(fsys_view) else: ret = 'change' kv = entry_ip['name'] view_lines.append((kv, entry_ip)) else: view_lines.append(fsys_view) except (IOError, OSError) as exc: raise CommandExecutionError('Couldn\'t read from {0}: {1}'.format(config, exc)) # add line if not present or changed if ret is None: for dict_view in six.viewitems(entry_ip.dict_from_entry()): view_lines.append(dict_view) ret = 'new' if ret != 'present': # ret in ['new', 'change']: try: with salt.utils.files.fopen(config, 'wb') as ofile: # The line was changed, commit it! for fsys_view in view_lines: entry = fsys_view[1] mystrg = _FileSystemsEntry.dict_to_lines(entry) ofile.writelines(salt.utils.data.encode(mystrg)) except (IOError, OSError): raise CommandExecutionError('File not writable {0}'.format(config)) return ret def rm_filesystems(name, device, config='/etc/filesystems'): ''' .. versionadded:: 2018.3.3 Remove the mount point from the filesystems CLI Example: .. code-block:: bash salt '*' mount.rm_filesystems /mnt/foo /dev/sdg ''' modified = False view_lines = [] if 'AIX' not in __grains__['kernel']: return modified criteria = _FileSystemsEntry(name=name, dev=device) try: fsys_filedict = _filesystems(config, False) for fsys_view in six.viewitems(fsys_filedict): try: if criteria.match(fsys_view): modified = True else: view_lines.append(fsys_view) except _FileSystemsEntry.ParseError: view_lines.append(fsys_view) except (IOError, OSError) as exc: raise CommandExecutionError("Couldn't read from {0}: {1}".format(config, exc)) if modified: try: with salt.utils.files.fopen(config, 'wb') as ofile: for fsys_view in view_lines: entry = fsys_view[1] mystrg = _FileSystemsEntry.dict_to_lines(entry) ofile.writelines(salt.utils.data.encode(mystrg)) except (IOError, OSError) as exc: raise CommandExecutionError("Couldn't write to {0}: {1}".format(config, exc)) return modified
saltstack/salt
salt/modules/mount.py
swapon
python
def swapon(name, priority=None): ''' Activate a swap disk .. versionchanged:: 2016.3.2 CLI Example: .. code-block:: bash salt '*' mount.swapon /root/swapfile ''' ret = {} on_ = swaps() if name in on_: ret['stats'] = on_[name] ret['new'] = False return ret if __grains__['kernel'] == 'SunOS': if __grains__['virtual'] != 'zone': __salt__['cmd.run']('swap -a {0}'.format(name), python_shell=False) else: return False else: cmd = 'swapon {0}'.format(name) if priority and 'AIX' not in __grains__['kernel']: cmd += ' -p {0}'.format(priority) __salt__['cmd.run'](cmd, python_shell=False) on_ = swaps() if name in on_: ret['stats'] = on_[name] ret['new'] = True return ret return ret
Activate a swap disk .. versionchanged:: 2016.3.2 CLI Example: .. code-block:: bash salt '*' mount.swapon /root/swapfile
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/mount.py#L1408-L1444
[ "def swaps():\n '''\n Return a dict containing information on active swap\n\n .. versionchanged:: 2016.3.2\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' mount.swaps\n '''\n ret = {}\n if __grains__['kernel'] == 'SunOS':\n for line in __salt__['cmd.run_stdout']('swap -l').splitlines():\n if line.startswith('swapfile'):\n continue\n comps = line.split()\n ret[comps[0]] = {'type': 'device' if comps[0].startswith(('/dev', 'swap')) else 'file',\n 'size': int(comps[3]),\n 'used': (int(comps[3]) - int(comps[4])),\n 'priority': '-'}\n elif 'AIX' in __grains__['kernel']:\n for line in __salt__['cmd.run_stdout']('swap -l').splitlines():\n if line.startswith('device'):\n continue\n comps = line.split()\n\n # AIX uses MB for units\n ret[comps[0]] = {'type': 'device',\n 'size': int(comps[3][:-2]) * 1024,\n 'used': (int(comps[3][:-2]) - int(comps[4][:-2])) * 1024,\n 'priority': '-'}\n elif __grains__['os'] != 'OpenBSD':\n with salt.utils.files.fopen('/proc/swaps') as fp_:\n for line in fp_:\n line = salt.utils.stringutils.to_unicode(line)\n if line.startswith('Filename'):\n continue\n comps = line.split()\n ret[comps[0]] = {'type': comps[1],\n 'size': comps[2],\n 'used': comps[3],\n 'priority': comps[4]}\n else:\n for line in __salt__['cmd.run_stdout']('swapctl -kl').splitlines():\n if line.startswith(('Device', 'Total')):\n continue\n swap_type = \"file\"\n comps = line.split()\n if comps[0].startswith('/dev/'):\n swap_type = \"partition\"\n ret[comps[0]] = {'type': swap_type,\n 'size': comps[1],\n 'used': comps[2],\n 'priority': comps[5]}\n return ret\n" ]
# -*- coding: utf-8 -*- ''' Salt module to manage Unix mounts and the fstab file ''' # Import python libs from __future__ import absolute_import, print_function, unicode_literals import os import re import logging # Import salt libs import salt.utils.args import salt.utils.data import salt.utils.files import salt.utils.path import salt.utils.platform import salt.utils.mount import salt.utils.stringutils from salt.utils.odict import OrderedDict from salt.exceptions import CommandNotFoundError, CommandExecutionError # Import 3rd-party libs from salt.ext import six from salt.ext.six.moves import filter, zip # pylint: disable=import-error,redefined-builtin # Set up logger log = logging.getLogger(__name__) # Define the module's virtual name __virtualname__ = 'mount' def __virtual__(): ''' Only load on POSIX-like systems ''' # Disable on Windows, a specific file module exists: if salt.utils.platform.is_windows(): return (False, 'The mount module cannot be loaded: not a POSIX-like system.') return True def _list_mounts(): ret = {} if __grains__['os'] in ['MacOS', 'Darwin']: mounts = __salt__['cmd.run_stdout']('mount') else: mounts = __salt__['cmd.run_stdout']('mount -l') for line in mounts.split('\n'): comps = re.sub(r"\s+", " ", line).split() if len(comps) >= 3: ret[comps[2]] = comps[0] return ret def _active_mountinfo(ret): _list = _list_mounts() filename = '/proc/self/mountinfo' if not os.access(filename, os.R_OK): msg = 'File not readable {0}' raise CommandExecutionError(msg.format(filename)) if 'disk.blkid' not in __context__: __context__['disk.blkid'] = __salt__['disk.blkid']() blkid_info = __context__['disk.blkid'] with salt.utils.files.fopen(filename) as ifile: for line in ifile: comps = salt.utils.stringutils.to_unicode(line).split() device = comps[2].split(':') # each line can have any number of # optional parameters, we use the # location of the separator field to # determine the location of the elements # after it. _sep = comps.index('-') device_name = comps[_sep + 2] device_uuid = None device_label = None if device_name: device_uuid = blkid_info.get(device_name, {}).get('UUID') device_uuid = device_uuid and device_uuid.lower() device_label = blkid_info.get(device_name, {}).get('LABEL') ret[comps[4]] = {'mountid': comps[0], 'parentid': comps[1], 'major': device[0], 'minor': device[1], 'root': comps[3], 'opts': _resolve_user_group_names(comps[5].split(',')), 'fstype': comps[_sep + 1], 'device': device_name.replace('\\040', '\\ '), 'alt_device': _list.get(comps[4], None), 'superopts': _resolve_user_group_names(comps[_sep + 3].split(',')), 'device_uuid': device_uuid, 'device_label': device_label} return ret def _active_mounts(ret): ''' List active mounts on Linux systems ''' _list = _list_mounts() filename = '/proc/self/mounts' if not os.access(filename, os.R_OK): msg = 'File not readable {0}' raise CommandExecutionError(msg.format(filename)) with salt.utils.files.fopen(filename) as ifile: for line in ifile: comps = salt.utils.stringutils.to_unicode(line).split() ret[comps[1]] = {'device': comps[0], 'alt_device': _list.get(comps[1], None), 'fstype': comps[2], 'opts': _resolve_user_group_names(comps[3].split(','))} return ret def _active_mounts_aix(ret): ''' List active mounts on AIX systems ''' for line in __salt__['cmd.run_stdout']('mount -p').split('\n'): comps = re.sub(r"\s+", " ", line).split() if comps: if comps[0] == 'node' or comps[0] == '--------': continue comps_len = len(comps) if line.startswith((' ', '\t')): curr_opts = _resolve_user_group_names(comps[6].split(',')) if 7 == comps_len else [] if curr_opts: ret[comps[1]] = {'device': comps[0], 'fstype': comps[2], 'opts': curr_opts} else: ret[comps[1]] = {'device': comps[0], 'fstype': comps[2]} else: curr_opts = _resolve_user_group_names(comps[7].split(',')) if 8 == comps_len else [] if curr_opts: ret[comps[2]] = {'node': comps[0], 'device': comps[1], 'fstype': comps[3], 'opts': curr_opts} else: ret[comps[2]] = {'node': comps[0], 'device': comps[1], 'fstype': comps[3]} return ret def _active_mounts_freebsd(ret): ''' List active mounts on FreeBSD systems ''' for line in __salt__['cmd.run_stdout']('mount -p').split('\n'): comps = re.sub(r"\s+", " ", line).split() ret[comps[1]] = {'device': comps[0], 'fstype': comps[2], 'opts': _resolve_user_group_names(comps[3].split(','))} return ret def _active_mounts_solaris(ret): ''' List active mounts on Solaris systems ''' for line in __salt__['cmd.run_stdout']('mount -v').split('\n'): comps = re.sub(r"\s+", " ", line).split() ret[comps[2]] = {'device': comps[0], 'fstype': comps[4], 'opts': _resolve_user_group_names(comps[5].split('/'))} return ret def _active_mounts_openbsd(ret): ''' List active mounts on OpenBSD systems ''' for line in __salt__['cmd.run_stdout']('mount -v').split('\n'): comps = re.sub(r"\s+", " ", line).split() parens = re.findall(r'\((.*?)\)', line, re.DOTALL) if len(parens) > 1: nod = __salt__['cmd.run_stdout']('ls -l {0}'.format(comps[0])) nod = ' '.join(nod.split()).split(" ") ret[comps[3]] = {'device': comps[0], 'fstype': comps[5], 'opts': _resolve_user_group_names(parens[1].split(", ")), 'major': six.text_type(nod[4].strip(",")), 'minor': six.text_type(nod[5]), 'device_uuid': parens[0]} else: ret[comps[2]] = {'device': comps[0], 'fstype': comps[4], 'opts': _resolve_user_group_names(parens[0].split(", "))} return ret def _active_mounts_darwin(ret): ''' List active mounts on Mac OS systems ''' for line in __salt__['cmd.run_stdout']('mount').split('\n'): comps = re.sub(r"\s+", " ", line).split() parens = re.findall(r'\((.*?)\)', line, re.DOTALL)[0].split(", ") ret[comps[2]] = {'device': comps[0], 'fstype': parens[0], 'opts': _resolve_user_group_names(parens[1:])} return ret def _resolve_user_group_names(opts): ''' Resolve user and group names in related opts ''' name_id_opts = {'uid': 'user.info', 'gid': 'group.info'} for ind, opt in enumerate(opts): if opt.split('=')[0] in name_id_opts: _givenid = opt.split('=')[1] _param = opt.split('=')[0] _id = _givenid if not re.match('[0-9]+$', _givenid): _info = __salt__[name_id_opts[_param]](_givenid) if _info and _param in _info: _id = _info[_param] opts[ind] = _param + '=' + six.text_type(_id) opts[ind] = opts[ind].replace('\\040', '\\ ') return opts def active(extended=False): ''' List the active mounts. CLI Example: .. code-block:: bash salt '*' mount.active ''' ret = {} if __grains__['os'] == 'FreeBSD': _active_mounts_freebsd(ret) elif 'AIX' in __grains__['kernel']: _active_mounts_aix(ret) elif __grains__['kernel'] == 'SunOS': _active_mounts_solaris(ret) elif __grains__['os'] == 'OpenBSD': _active_mounts_openbsd(ret) elif __grains__['os'] in ['MacOS', 'Darwin']: _active_mounts_darwin(ret) else: if extended: try: _active_mountinfo(ret) except CommandExecutionError: _active_mounts(ret) else: _active_mounts(ret) return ret class _fstab_entry(object): ''' Utility class for manipulating fstab entries. Primarily we're parsing, formatting, and comparing lines. Parsing emits dicts expected from fstab() or raises a ValueError. Note: We'll probably want to use os.normpath and os.normcase on 'name' ''' class ParseError(ValueError): ''' Error raised when a line isn't parsible as an fstab entry ''' fstab_keys = ('device', 'name', 'fstype', 'opts', 'dump', 'pass_num') # preserve data format compatibility_keys = ('device', 'name', 'fstype', 'opts', 'dump', 'pass') fstab_format = '{device}\t\t{name}\t{fstype}\t{opts}\t{dump} {pass_num}\n' @classmethod def dict_from_line(cls, line, keys=fstab_keys): if len(keys) != 6: raise ValueError('Invalid key array: {0}'.format(keys)) if line.startswith('#'): raise cls.ParseError("Comment!") comps = line.split() if len(comps) < 4 or len(comps) > 6: raise cls.ParseError("Invalid Entry!") comps.extend(['0'] * (len(keys) - len(comps))) return dict(zip(keys, comps)) @classmethod def from_line(cls, *args, **kwargs): return cls(** cls.dict_from_line(*args, **kwargs)) @classmethod def dict_to_line(cls, entry): return cls.fstab_format.format(**entry) def __str__(self): ''' String value, only works for full repr ''' return self.dict_to_line(self.criteria) def __repr__(self): ''' Always works ''' return repr(self.criteria) def pick(self, keys): ''' Returns an instance with just those keys ''' subset = dict([(key, self.criteria[key]) for key in keys]) return self.__class__(**subset) def __init__(self, **criteria): ''' Store non-empty, non-null values to use as filter ''' items = [key_value for key_value in six.iteritems(criteria) if key_value[1] is not None] items = [(key_value1[0], six.text_type(key_value1[1])) for key_value1 in items] self.criteria = dict(items) @staticmethod def norm_path(path): ''' Resolve equivalent paths equivalently ''' return os.path.normcase(os.path.normpath(path)) def match(self, line): ''' Compare potentially partial criteria against line ''' entry = self.dict_from_line(line) for key, value in six.iteritems(self.criteria): if entry[key] != value: return False return True class _vfstab_entry(object): ''' Utility class for manipulating vfstab entries. Primarily we're parsing, formatting, and comparing lines. Parsing emits dicts expected from fstab() or raises a ValueError. Note: We'll probably want to use os.normpath and os.normcase on 'name' Note: This parses vfstab entries on Solaris like systems #device device mount FS fsck mount mount #to mount to fsck point type pass at boot options # /devices - /devices devfs - no - ''' class ParseError(ValueError): '''Error raised when a line isn't parsible as an fstab entry''' vfstab_keys = ('device', 'device_fsck', 'name', 'fstype', 'pass_fsck', 'mount_at_boot', 'opts') # NOTE: weird formatting to match default spacing on Solaris vfstab_format = '{device:<11} {device_fsck:<3} {name:<19} {fstype:<8} {pass_fsck:<3} {mount_at_boot:<6} {opts}\n' @classmethod def dict_from_line(cls, line): if line.startswith('#'): raise cls.ParseError("Comment!") comps = line.split() if len(comps) != 7: raise cls.ParseError("Invalid Entry!") return dict(zip(cls.vfstab_keys, comps)) @classmethod def from_line(cls, *args, **kwargs): return cls(** cls.dict_from_line(*args, **kwargs)) @classmethod def dict_to_line(cls, entry): return cls.vfstab_format.format(**entry) def __str__(self): ''' String value, only works for full repr ''' return self.dict_to_line(self.criteria) def __repr__(self): ''' Always works ''' return repr(self.criteria) def pick(self, keys): ''' Returns an instance with just those keys ''' subset = dict([(key, self.criteria[key]) for key in keys]) return self.__class__(**subset) def __init__(self, **criteria): ''' Store non-empty, non-null values to use as filter ''' items = [key_value for key_value in six.iteritems(criteria) if key_value[1] is not None] items = [(key_value1[0], six.text_type(key_value1[1])) for key_value1 in items] self.criteria = dict(items) @staticmethod def norm_path(path): ''' Resolve equivalent paths equivalently ''' return os.path.normcase(os.path.normpath(path)) def match(self, line): ''' Compare potentially partial criteria against line ''' entry = self.dict_from_line(line) for key, value in six.iteritems(self.criteria): if entry[key] != value: return False return True class _FileSystemsEntry(object): ''' Utility class for manipulating filesystem entries. Primarily we're parsing, formatting, and comparing lines. Parsing emits dicts expected from fstab() or raises a ValueError. Note: We'll probably want to use os.normpath and os.normcase on 'name' ''' class ParseError(ValueError): ''' Error raised when a line isn't parsible as an fstab entry ''' filesystems_keys = ('device', 'name', 'fstype', 'vfstype', 'opts', 'mount') # preserve data format of filesystems compatibility_keys = ('dev', 'dev', 'name', 'fstype', 'vfstype', 'opts', 'mount', 'type', 'vfs', 'account', 'boot', 'check', 'free', 'nodename', 'quota', 'size', 'vol', 'log') @classmethod def dict_from_lines(cls, lines, keys=filesystems_keys): if len(lines) < 2: raise ValueError('Invalid number of lines: {0}'.format(lines)) if not keys: # if empty force default filesystems_keys keys = _FileSystemsEntry.filesystems_keys elif len(keys) < 6: raise ValueError('Invalid key name array: {0}'.format(keys)) blk_lines = lines orddict = OrderedDict() orddict['name'] = blk_lines[0].split(':')[0].strip() blk_lines.pop(0) for line in blk_lines: if line.startswith('#'): raise cls.ParseError("Comment!") comps = line.split('= ') if len(comps) != 2: raise cls.ParseError("Invalid Entry!") key_name = comps[0].strip() if key_name in keys: orddict[key_name] = comps[1].strip() else: raise ValueError('Invalid name for use in filesystems: {0}'.format(key_name)) return orddict @classmethod def dict_from_cmd_line(cls, ipargs, keys): cmdln_dict = ipargs if keys: for key, value in keys: # ignore unknown or local scope keys if key.startswith('__'): continue if key in _FileSystemsEntry.compatibility_keys: cmdln_dict[key] = value return cmdln_dict @classmethod def from_line(cls, *args, **kwargs): return cls(** cls.dict_from_cmd_line(*args, **kwargs)) @classmethod def dict_to_lines(cls, fsys_dict_entry): entry = fsys_dict_entry strg_out = entry['name'] + ':' + os.linesep for k, v in six.viewitems(entry): if 'name' not in k: strg_out += '\t{0}\t\t= {1}'.format(k, v) + os.linesep strg_out += os.linesep return six.text_type(strg_out) def dict_from_entry(self): ret = OrderedDict() ret[self.criteria['name']] = self.criteria return ret def __str__(self): ''' String value, only works for full repr ''' return self.dict_to_lines(self.criteria) def __repr__(self): ''' Always works ''' return repr(self.criteria) def pick(self, keys): ''' Returns an instance with just those keys ''' subset = dict([(key, self.criteria[key]) for key in keys]) return self.__class__(**subset) def __init__(self, **criteria): ''' Store non-empty, non-null values to use as filter ''' items = [key_value for key_value in six.iteritems(criteria) if key_value[1] is not None] items = [(key_value1[0], six.text_type(key_value1[1])) for key_value1 in items] self.criteria = OrderedDict(items) @staticmethod def norm_path(path): ''' Resolve equivalent paths equivalently ''' return os.path.normcase(os.path.normpath(path)) def match(self, fsys_view): ''' Compare potentially partial criteria against built filesystems entry dictionary ''' evalue_dict = fsys_view[1] for key, value in six.viewitems(self.criteria): if key in evalue_dict: if evalue_dict[key] != value: return False else: return False return True def __getitem__(self, key): ''' Return value for input key ''' return self.criteria[key] def fstab(config='/etc/fstab'): ''' .. versionchanged:: 2016.3.2 List the contents of the fstab CLI Example: .. code-block:: bash salt '*' mount.fstab ''' ret = {} if not os.path.isfile(config): return ret with salt.utils.files.fopen(config) as ifile: for line in ifile: line = salt.utils.stringutils.to_unicode(line) try: if __grains__['kernel'] == 'SunOS': # Note: comments use in default vfstab file! if line[0] == '#': continue entry = _vfstab_entry.dict_from_line( line) else: entry = _fstab_entry.dict_from_line( line, _fstab_entry.compatibility_keys) entry['opts'] = entry['opts'].split(',') while entry['name'] in ret: entry['name'] += '_' ret[entry.pop('name')] = entry except _fstab_entry.ParseError: pass except _vfstab_entry.ParseError: pass return ret def vfstab(config='/etc/vfstab'): ''' .. versionadded:: 2016.3.2 List the contents of the vfstab CLI Example: .. code-block:: bash salt '*' mount.vfstab ''' # NOTE: vfstab is a wrapper for fstab return fstab(config) def rm_fstab(name, device, config='/etc/fstab'): ''' .. versionchanged:: 2016.3.2 Remove the mount point from the fstab CLI Example: .. code-block:: bash salt '*' mount.rm_fstab /mnt/foo /dev/sdg ''' modified = False if __grains__['kernel'] == 'SunOS': criteria = _vfstab_entry(name=name, device=device) else: criteria = _fstab_entry(name=name, device=device) lines = [] try: with salt.utils.files.fopen(config, 'r') as ifile: for line in ifile: line = salt.utils.stringutils.to_unicode(line) try: if criteria.match(line): modified = True else: lines.append(line) except _fstab_entry.ParseError: lines.append(line) except _vfstab_entry.ParseError: lines.append(line) except (IOError, OSError) as exc: msg = "Couldn't read from {0}: {1}" raise CommandExecutionError(msg.format(config, exc)) if modified: try: with salt.utils.files.fopen(config, 'wb') as ofile: ofile.writelines(salt.utils.data.encode(lines)) except (IOError, OSError) as exc: msg = "Couldn't write to {0}: {1}" raise CommandExecutionError(msg.format(config, exc)) # Note: not clear why we always return 'True' # --just copying previous behavior at this point... return True def rm_vfstab(name, device, config='/etc/vfstab'): ''' .. versionadded:: 2016.3.2 Remove the mount point from the vfstab CLI Example: .. code-block:: bash salt '*' mount.rm_vfstab /mnt/foo /device/c0t0d0p0 ''' ## NOTE: rm_vfstab is a wrapper for rm_fstab return rm_fstab(name, device, config) def set_fstab( name, device, fstype, opts='defaults', dump=0, pass_num=0, config='/etc/fstab', test=False, match_on='auto', **kwargs): ''' Verify that this mount is represented in the fstab, change the mount to match the data passed, or add the mount if it is not present. CLI Example: .. code-block:: bash salt '*' mount.set_fstab /mnt/foo /dev/sdz1 ext4 ''' # Fix the opts type if it is a list if isinstance(opts, list): opts = ','.join(opts) # preserve arguments for updating entry_args = { 'name': name, 'device': device.replace('\\ ', '\\040'), 'fstype': fstype, 'opts': opts.replace('\\ ', '\\040'), 'dump': dump, 'pass_num': pass_num, } lines = [] ret = None # Transform match_on into list--items will be checked later if isinstance(match_on, list): pass elif not isinstance(match_on, six.string_types): msg = 'match_on must be a string or list of strings' raise CommandExecutionError(msg) elif match_on == 'auto': # Try to guess right criteria for auto.... # NOTE: missing some special fstypes here specialFSes = frozenset([ 'none', 'tmpfs', 'sysfs', 'proc', 'fusectl', 'debugfs', 'securityfs', 'devtmpfs', 'cgroup', 'btrfs']) if fstype in specialFSes: match_on = ['name'] else: match_on = ['device'] else: match_on = [match_on] # generate entry and criteria objects, handle invalid keys in match_on entry = _fstab_entry(**entry_args) try: criteria = entry.pick(match_on) except KeyError: filterFn = lambda key: key not in _fstab_entry.fstab_keys invalid_keys = filter(filterFn, match_on) msg = 'Unrecognized keys in match_on: "{0}"'.format(invalid_keys) raise CommandExecutionError(msg) # parse file, use ret to cache status if not os.path.isfile(config): raise CommandExecutionError('Bad config file "{0}"'.format(config)) try: with salt.utils.files.fopen(config, 'r') as ifile: for line in ifile: line = salt.utils.stringutils.to_unicode(line) try: if criteria.match(line): # Note: If ret isn't None here, # we've matched multiple lines ret = 'present' if entry.match(line): lines.append(line) else: ret = 'change' lines.append(six.text_type(entry)) else: lines.append(line) except _fstab_entry.ParseError: lines.append(line) except (IOError, OSError) as exc: msg = 'Couldn\'t read from {0}: {1}' raise CommandExecutionError(msg.format(config, exc)) # add line if not present or changed if ret is None: lines.append(six.text_type(entry)) ret = 'new' if ret != 'present': # ret in ['new', 'change']: if not salt.utils.args.test_mode(test=test, **kwargs): try: with salt.utils.files.fopen(config, 'wb') as ofile: # The line was changed, commit it! ofile.writelines(salt.utils.data.encode(lines)) except (IOError, OSError): msg = 'File not writable {0}' raise CommandExecutionError(msg.format(config)) return ret def set_vfstab( name, device, fstype, opts='-', device_fsck='-', pass_fsck='-', mount_at_boot='yes', config='/etc/vfstab', test=False, match_on='auto', **kwargs): ''' ..verionadded:: 2016.3.2 Verify that this mount is represented in the fstab, change the mount to match the data passed, or add the mount if it is not present. CLI Example: .. code-block:: bash salt '*' mount.set_vfstab /mnt/foo /device/c0t0d0p0 ufs ''' # Fix the opts type if it is a list if isinstance(opts, list): opts = ','.join(opts) # Map unknown values for mount_at_boot to no if mount_at_boot != 'yes': mount_at_boot = 'no' # preserve arguments for updating entry_args = { 'name': name, 'device': device, 'fstype': fstype, 'opts': opts, 'device_fsck': device_fsck, 'pass_fsck': pass_fsck, 'mount_at_boot': mount_at_boot, } lines = [] ret = None # Transform match_on into list--items will be checked later if isinstance(match_on, list): pass elif not isinstance(match_on, six.string_types): msg = 'match_on must be a string or list of strings' raise CommandExecutionError(msg) elif match_on == 'auto': # Try to guess right criteria for auto.... # NOTE: missing some special fstypes here specialFSes = frozenset([ 'devfs', 'proc', 'ctfs', 'objfs', 'sharefs', 'fs', 'tmpfs']) if fstype in specialFSes: match_on = ['name'] else: match_on = ['device'] else: match_on = [match_on] # generate entry and criteria objects, handle invalid keys in match_on entry = _vfstab_entry(**entry_args) try: criteria = entry.pick(match_on) except KeyError: filterFn = lambda key: key not in _vfstab_entry.vfstab_keys invalid_keys = filter(filterFn, match_on) msg = 'Unrecognized keys in match_on: "{0}"'.format(invalid_keys) raise CommandExecutionError(msg) # parse file, use ret to cache status if not os.path.isfile(config): raise CommandExecutionError('Bad config file "{0}"'.format(config)) try: with salt.utils.files.fopen(config, 'r') as ifile: for line in ifile: line = salt.utils.stringutils.to_unicode(line) try: if criteria.match(line): # Note: If ret isn't None here, # we've matched multiple lines ret = 'present' if entry.match(line): lines.append(line) else: ret = 'change' lines.append(six.text_type(entry)) else: lines.append(line) except _vfstab_entry.ParseError: lines.append(line) except (IOError, OSError) as exc: msg = 'Couldn\'t read from {0}: {1}' raise CommandExecutionError(msg.format(config, exc)) # add line if not present or changed if ret is None: lines.append(six.text_type(entry)) ret = 'new' if ret != 'present': # ret in ['new', 'change']: if not salt.utils.args.test_mode(test=test, **kwargs): try: with salt.utils.files.fopen(config, 'wb') as ofile: # The line was changed, commit it! ofile.writelines(salt.utils.data.encode(lines)) except (IOError, OSError): msg = 'File not writable {0}' raise CommandExecutionError(msg.format(config)) return ret def rm_automaster(name, device, config='/etc/auto_salt'): ''' Remove the mount point from the auto_master CLI Example: .. code-block:: bash salt '*' mount.rm_automaster /mnt/foo /dev/sdg ''' contents = automaster(config) if name not in contents: return True # The entry is present, get rid of it lines = [] try: with salt.utils.files.fopen(config, 'r') as ifile: for line in ifile: line = salt.utils.stringutils.to_unicode(line) if line.startswith('#'): # Commented lines.append(line) continue if not line.strip(): # Blank line lines.append(line) continue comps = line.split() if len(comps) != 3: # Invalid entry lines.append(line) continue comps = line.split() prefix = "/.." name_chk = comps[0].replace(prefix, "") device_fmt = comps[2].split(":") if device: if name_chk == name and device_fmt[1] == device: continue else: if name_chk == name: continue lines.append(line) except (IOError, OSError) as exc: msg = "Couldn't read from {0}: {1}" raise CommandExecutionError(msg.format(config, exc)) try: with salt.utils.files.fopen(config, 'wb') as ofile: ofile.writelines(salt.utils.data.encode(lines)) except (IOError, OSError) as exc: msg = "Couldn't write to {0}: {1}" raise CommandExecutionError(msg.format(config, exc)) # Update automount __salt__['cmd.run']('automount -cv') return True def set_automaster( name, device, fstype, opts='', config='/etc/auto_salt', test=False, **kwargs): ''' Verify that this mount is represented in the auto_salt, change the mount to match the data passed, or add the mount if it is not present. CLI Example: .. code-block:: bash salt '*' mount.set_automaster /mnt/foo /dev/sdz1 ext4 ''' # Fix the opts type if it is a list if isinstance(opts, list): opts = ','.join(opts) lines = [] change = False present = False automaster_file = "/etc/auto_master" if not os.path.isfile(config): __salt__['file.touch'](config) __salt__['file.append'](automaster_file, "/-\t\t\t{0}".format(config)) name = "/..{0}".format(name) device_fmt = "{0}:{1}".format(fstype, device) type_opts = "-fstype={0},{1}".format(fstype, opts) if fstype == 'smbfs': device_fmt = device_fmt.replace(fstype, "") try: with salt.utils.files.fopen(config, 'r') as ifile: for line in ifile: line = salt.utils.stringutils.to_unicode(line) if line.startswith('#'): # Commented lines.append(line) continue if not line.strip(): # Blank line lines.append(line) continue comps = line.split() if len(comps) != 3: # Invalid entry lines.append(line) continue if comps[0] == name or comps[2] == device_fmt: # check to see if there are changes # and fix them if there are any present = True if comps[0] != name: change = True comps[0] = name if comps[1] != type_opts: change = True comps[1] = type_opts if comps[2] != device_fmt: change = True comps[2] = device_fmt if change: log.debug( 'auto_master entry for mount point %s needs to be ' 'updated', name ) newline = ( '{0}\t{1}\t{2}\n'.format( name, type_opts, device_fmt) ) lines.append(newline) else: lines.append(line) except (IOError, OSError) as exc: msg = 'Couldn\'t read from {0}: {1}' raise CommandExecutionError(msg.format(config, exc)) if change: if not salt.utils.args.test_mode(test=test, **kwargs): try: with salt.utils.files.fopen(config, 'wb') as ofile: # The line was changed, commit it! ofile.writelines(salt.utils.data.encode(lines)) except (IOError, OSError): msg = 'File not writable {0}' raise CommandExecutionError(msg.format(config)) return 'change' if not change: if present: # The right entry is already here return 'present' else: if not salt.utils.args.test_mode(test=test, **kwargs): # The entry is new, add it to the end of the fstab newline = ( '{0}\t{1}\t{2}\n'.format( name, type_opts, device_fmt) ) lines.append(newline) try: with salt.utils.files.fopen(config, 'wb') as ofile: # The line was changed, commit it! ofile.writelines(salt.utils.data.encode(lines)) except (IOError, OSError): raise CommandExecutionError( 'File not writable {0}'.format( config ) ) return 'new' def automaster(config='/etc/auto_salt'): ''' List the contents of the auto master CLI Example: .. code-block:: bash salt '*' mount.automaster ''' ret = {} if not os.path.isfile(config): return ret with salt.utils.files.fopen(config) as ifile: for line in ifile: line = salt.utils.stringutils.to_unicode(line) if line.startswith('#'): # Commented continue if not line.strip(): # Blank line continue comps = line.split() if len(comps) != 3: # Invalid entry continue prefix = "/.." name = comps[0].replace(prefix, "") device_fmt = comps[2].split(":") opts = comps[1].split(',') ret[name] = {'device': device_fmt[1], 'fstype': opts[0], 'opts': opts[1:]} return ret def mount(name, device, mkmnt=False, fstype='', opts='defaults', user=None, util='mount'): ''' Mount a device CLI Example: .. code-block:: bash salt '*' mount.mount /mnt/foo /dev/sdz1 True ''' if util != 'mount': # This functionality used to live in img.mount_image if util == 'guestfs': return __salt__['guestfs.mount'](name, root=device) elif util == 'qemu_nbd': mnt = __salt__['qemu_nbd.init'](name, device) if not mnt: return False first = next(six.iterkeys(mnt)) __context__['img.mnt_{0}'.format(first)] = mnt return first return False # Darwin doesn't expect defaults when mounting without other options if 'defaults' in opts and __grains__['os'] in ['MacOS', 'Darwin', 'AIX']: opts = None if isinstance(opts, six.string_types): opts = opts.split(',') if not os.path.exists(name) and mkmnt: __salt__['file.mkdir'](name, user=user) args = '' if opts is not None: lopts = ','.join(opts) args = '-o {0}'.format(lopts) if fstype: # use of fstype on AIX differs from typical Linux use of -t # functionality AIX uses -v vfsname, -t fstype mounts all with # fstype in /etc/filesystems if 'AIX' in __grains__['os']: args += ' -v {0}'.format(fstype) elif 'solaris' in __grains__['os'].lower(): args += ' -F {0}'.format(fstype) else: args += ' -t {0}'.format(fstype) cmd = 'mount {0} {1} {2} '.format(args, device, name) out = __salt__['cmd.run_all'](cmd, runas=user, python_shell=False) if out['retcode']: return out['stderr'] return True def remount(name, device, mkmnt=False, fstype='', opts='defaults', user=None): ''' Attempt to remount a device, if the device is not already mounted, mount is called CLI Example: .. code-block:: bash salt '*' mount.remount /mnt/foo /dev/sdz1 True ''' force_mount = False if __grains__['os'] in ['MacOS', 'Darwin']: if opts == 'defaults': opts = 'noowners' if fstype == 'smbfs': force_mount = True if 'AIX' in __grains__['os']: if opts == 'defaults': opts = [] if isinstance(opts, six.string_types): opts = opts.split(',') mnts = active() if name in mnts: # The mount point is mounted, attempt to remount it with the given data if 'remount' not in opts and __grains__['os'] not in ['OpenBSD', 'MacOS', 'Darwin']: opts.append('remount') if force_mount: # We need to force the mount but first we should unmount umount(name, device, user=user) lopts = ','.join(opts) args = '-o {0}'.format(lopts) if fstype: # use of fstype on AIX differs from typical Linux use of # -t functionality AIX uses -v vfsname, -t fstype mounts # all with fstype in /etc/filesystems if 'AIX' in __grains__['os']: args += ' -v {0}'.format(fstype) elif 'solaris' in __grains__['os'].lower(): args += ' -F {0}'.format(fstype) else: args += ' -t {0}'.format(fstype) if __grains__['os'] not in ['OpenBSD', 'MacOS', 'Darwin'] or force_mount: cmd = 'mount {0} {1} {2} '.format(args, device, name) else: cmd = 'mount -u {0} {1} {2} '.format(args, device, name) out = __salt__['cmd.run_all'](cmd, runas=user, python_shell=False) if out['retcode']: return out['stderr'] return True # Mount a filesystem that isn't already return mount(name, device, mkmnt, fstype, opts, user=user) def umount(name, device=None, user=None, util='mount'): ''' Attempt to unmount a device by specifying the directory it is mounted on CLI Example: .. code-block:: bash salt '*' mount.umount /mnt/foo .. versionadded:: 2015.5.0 .. code-block:: bash salt '*' mount.umount /mnt/foo /dev/xvdc1 ''' if util != 'mount': # This functionality used to live in img.umount_image if 'qemu_nbd.clear' in __salt__: if 'img.mnt_{0}'.format(name) in __context__: __salt__['qemu_nbd.clear'](__context__['img.mnt_{0}'.format(name)]) return mnts = active() if name not in mnts: return "{0} does not have anything mounted".format(name) if not device: cmd = 'umount {0}'.format(name) else: cmd = 'umount {0}'.format(device) out = __salt__['cmd.run_all'](cmd, runas=user, python_shell=False) if out['retcode']: return out['stderr'] return True def is_fuse_exec(cmd): ''' Returns true if the command passed is a fuse mountable application. CLI Example: .. code-block:: bash salt '*' mount.is_fuse_exec sshfs ''' cmd_path = salt.utils.path.which(cmd) # No point in running ldd on a command that doesn't exist if not cmd_path: return False elif not salt.utils.path.which('ldd'): raise CommandNotFoundError('ldd') out = __salt__['cmd.run']('ldd {0}'.format(cmd_path), python_shell=False) return 'libfuse' in out def swaps(): ''' Return a dict containing information on active swap .. versionchanged:: 2016.3.2 CLI Example: .. code-block:: bash salt '*' mount.swaps ''' ret = {} if __grains__['kernel'] == 'SunOS': for line in __salt__['cmd.run_stdout']('swap -l').splitlines(): if line.startswith('swapfile'): continue comps = line.split() ret[comps[0]] = {'type': 'device' if comps[0].startswith(('/dev', 'swap')) else 'file', 'size': int(comps[3]), 'used': (int(comps[3]) - int(comps[4])), 'priority': '-'} elif 'AIX' in __grains__['kernel']: for line in __salt__['cmd.run_stdout']('swap -l').splitlines(): if line.startswith('device'): continue comps = line.split() # AIX uses MB for units ret[comps[0]] = {'type': 'device', 'size': int(comps[3][:-2]) * 1024, 'used': (int(comps[3][:-2]) - int(comps[4][:-2])) * 1024, 'priority': '-'} elif __grains__['os'] != 'OpenBSD': with salt.utils.files.fopen('/proc/swaps') as fp_: for line in fp_: line = salt.utils.stringutils.to_unicode(line) if line.startswith('Filename'): continue comps = line.split() ret[comps[0]] = {'type': comps[1], 'size': comps[2], 'used': comps[3], 'priority': comps[4]} else: for line in __salt__['cmd.run_stdout']('swapctl -kl').splitlines(): if line.startswith(('Device', 'Total')): continue swap_type = "file" comps = line.split() if comps[0].startswith('/dev/'): swap_type = "partition" ret[comps[0]] = {'type': swap_type, 'size': comps[1], 'used': comps[2], 'priority': comps[5]} return ret def swapoff(name): ''' Deactivate a named swap mount .. versionchanged:: 2016.3.2 CLI Example: .. code-block:: bash salt '*' mount.swapoff /root/swapfile ''' on_ = swaps() if name in on_: if __grains__['kernel'] == 'SunOS': if __grains__['virtual'] != 'zone': __salt__['cmd.run']('swap -a {0}'.format(name), python_shell=False) else: return False elif __grains__['os'] != 'OpenBSD': __salt__['cmd.run']('swapoff {0}'.format(name), python_shell=False) else: __salt__['cmd.run']('swapctl -d {0}'.format(name), python_shell=False) on_ = swaps() if name in on_: return False return True return None def is_mounted(name): ''' .. versionadded:: 2014.7.0 Provide information if the path is mounted CLI Example: .. code-block:: bash salt '*' mount.is_mounted /mnt/share ''' active_ = active() if name in active_: return True else: return False def read_mount_cache(name): ''' .. versionadded:: 2018.3.0 Provide information if the path is mounted CLI Example: .. code-block:: bash salt '*' mount.read_mount_cache /mnt/share ''' cache = salt.utils.mount.read_cache(__opts__) if cache: if 'mounts' in cache and cache['mounts']: if name in cache['mounts']: return cache['mounts'][name] return {} def write_mount_cache(real_name, device, mkmnt, fstype, mount_opts): ''' .. versionadded:: 2018.3.0 Provide information if the path is mounted :param real_name: The real name of the mount point where the device is mounted. :param device: The device that is being mounted. :param mkmnt: Whether or not the mount point should be created. :param fstype: The file system that is used. :param mount_opts: Additional options used when mounting the device. :return: Boolean if message was sent successfully. CLI Example: .. code-block:: bash salt '*' mount.write_mount_cache /mnt/share /dev/sda1 False ext4 defaults,nosuid ''' cache = salt.utils.mount.read_cache(__opts__) if not cache: cache = {} cache['mounts'] = {} else: if 'mounts' not in cache: cache['mounts'] = {} cache['mounts'][real_name] = {'device': device, 'fstype': fstype, 'mkmnt': mkmnt, 'opts': mount_opts} cache_write = salt.utils.mount.write_cache(cache, __opts__) if cache_write: return True else: raise CommandExecutionError('Unable to write mount cache.') def delete_mount_cache(real_name): ''' .. versionadded:: 2018.3.0 Provide information if the path is mounted CLI Example: .. code-block:: bash salt '*' mount.delete_mount_cache /mnt/share ''' cache = salt.utils.mount.read_cache(__opts__) if cache: if 'mounts' in cache: if real_name in cache['mounts']: del cache['mounts'][real_name] cache_write = salt.utils.mount.write_cache(cache, __opts__) if not cache_write: raise CommandExecutionError('Unable to write mount cache.') return True def _filesystems(config='/etc/filesystems', leading_key=True): ''' Return the contents of the filesystems in an OrderedDict config File containing filesystem infomation leading_key True return dictionary keyed by 'name' and value as dictionary with other keys, values (name excluded) OrderedDict({ '/dir' : OrderedDict({'dev': '/dev/hd8', .... }})) False return dictionary keyed by 'name' and value as dictionary with all keys, values (name included) OrderedDict({ '/dir' : OrderedDict({'name': '/dir', 'dev': '/dev/hd8', ... })}) ''' ret = OrderedDict() lines = [] parsing_block = False if not os.path.isfile(config) or 'AIX' not in __grains__['kernel']: return ret # read in block of filesystems, block starts with '/' till empty line with salt.utils.files.fopen(config) as ifile: for line in ifile: line = salt.utils.stringutils.to_unicode(line) # skip till first entry if not line.startswith('/') and not parsing_block: continue if line.startswith('/'): parsing_block = True lines.append(line) elif not line.split(): parsing_block = False try: entry = _FileSystemsEntry.dict_from_lines( lines, _FileSystemsEntry.compatibility_keys) lines = [] if 'opts' in entry: entry['opts'] = entry['opts'].split(',') while entry['name'] in ret: entry['name'] += '_' if leading_key: ret[entry.pop('name')] = entry else: ret[entry['name']] = entry except _FileSystemsEntry.ParseError: pass else: lines.append(line) return ret def filesystems(config='/etc/filesystems'): ''' .. versionadded:: 2018.3.3 List the contents of the filesystems CLI Example: .. code-block:: bash salt '*' mount.filesystems ''' ret = {} if 'AIX' not in __grains__['kernel']: return ret ret_dict = _filesystems(config) if ret_dict: ret_key = next(iter(ret_dict.keys())) ret = {ret_key: dict(ret_dict[ret_key])} return ret def set_filesystems( name, device, vfstype, opts='-', mount='true', config='/etc/filesystems', test=False, match_on='auto', **kwargs): ''' .. versionadded:: 2018.3.3 Verify that this mount is represented in the filesystems, change the mount to match the data passed, or add the mount if it is not present on AIX Provide information if the path is mounted :param name: The name of the mount point where the device is mounted. :param device: The device that is being mounted. :param vfstype: The file system that is used (AIX has two fstypes, fstype and vfstype - similar to Linux fstype) :param opts: Additional options used when mounting the device. :param mount: Mount if not mounted, default True. :param config: Configuration file, default /etc/filesystems. :param match: File systems type to match on, default auto CLI Example: .. code-block:: bash salt '*' mount.set_filesystems /mnt/foo /dev/sdz1 jfs2 ''' # Fix the opts type if it is a list if isinstance(opts, list): opts = ','.join(opts) # preserve arguments for updating entry_args = { 'name': name, 'dev': device.replace('\\ ', '\\040'), 'vfstype': vfstype, 'opts': opts, 'mount': mount, } view_lines = [] ret = None if 'AIX' not in __grains__['kernel']: return ret # Transform match_on into list--items will be checked later if isinstance(match_on, list): pass elif not isinstance(match_on, six.string_types): raise CommandExecutionError('match_on must be a string or list of strings') elif match_on == 'auto': # Try to guess right criteria for auto.... # added IBM types from sys/vmount.h after btrfs # NOTE: missing some special fstypes here specialFSes = frozenset([ 'none', 'tmpfs', 'sysfs', 'proc', 'fusectl', 'debugfs', 'securityfs', 'devtmpfs', 'cgroup', 'btrfs', 'cdrfs', 'procfs', 'jfs', 'jfs2', 'nfs', 'sfs', 'nfs3', 'cachefs', 'udfs', 'cifs', 'namefs', 'pmemfs', 'ahafs', 'nfs4', 'autofs', 'stnfs']) if vfstype in specialFSes: match_on = ['name'] else: match_on = ['dev'] else: match_on = [match_on] # generate entry and criteria objects, handle invalid keys in match_on entry_ip = _FileSystemsEntry.from_line(entry_args, kwargs) try: criteria = entry_ip.pick(match_on) except KeyError: filterFn = lambda key: key not in _FileSystemsEntry.compatibility_keys invalid_keys = filter(filterFn, match_on) raise CommandExecutionError('Unrecognized keys in match_on: "{0}"'.format(invalid_keys)) # parse file, use ret to cache status if not os.path.isfile(config): raise CommandExecutionError('Bad config file "{0}"'.format(config)) # read in block of filesystem, block starts with '/' till empty line try: fsys_filedict = _filesystems(config, False) for fsys_view in six.viewitems(fsys_filedict): if criteria.match(fsys_view): ret = 'present' if entry_ip.match(fsys_view): view_lines.append(fsys_view) else: ret = 'change' kv = entry_ip['name'] view_lines.append((kv, entry_ip)) else: view_lines.append(fsys_view) except (IOError, OSError) as exc: raise CommandExecutionError('Couldn\'t read from {0}: {1}'.format(config, exc)) # add line if not present or changed if ret is None: for dict_view in six.viewitems(entry_ip.dict_from_entry()): view_lines.append(dict_view) ret = 'new' if ret != 'present': # ret in ['new', 'change']: try: with salt.utils.files.fopen(config, 'wb') as ofile: # The line was changed, commit it! for fsys_view in view_lines: entry = fsys_view[1] mystrg = _FileSystemsEntry.dict_to_lines(entry) ofile.writelines(salt.utils.data.encode(mystrg)) except (IOError, OSError): raise CommandExecutionError('File not writable {0}'.format(config)) return ret def rm_filesystems(name, device, config='/etc/filesystems'): ''' .. versionadded:: 2018.3.3 Remove the mount point from the filesystems CLI Example: .. code-block:: bash salt '*' mount.rm_filesystems /mnt/foo /dev/sdg ''' modified = False view_lines = [] if 'AIX' not in __grains__['kernel']: return modified criteria = _FileSystemsEntry(name=name, dev=device) try: fsys_filedict = _filesystems(config, False) for fsys_view in six.viewitems(fsys_filedict): try: if criteria.match(fsys_view): modified = True else: view_lines.append(fsys_view) except _FileSystemsEntry.ParseError: view_lines.append(fsys_view) except (IOError, OSError) as exc: raise CommandExecutionError("Couldn't read from {0}: {1}".format(config, exc)) if modified: try: with salt.utils.files.fopen(config, 'wb') as ofile: for fsys_view in view_lines: entry = fsys_view[1] mystrg = _FileSystemsEntry.dict_to_lines(entry) ofile.writelines(salt.utils.data.encode(mystrg)) except (IOError, OSError) as exc: raise CommandExecutionError("Couldn't write to {0}: {1}".format(config, exc)) return modified
saltstack/salt
salt/modules/mount.py
swapoff
python
def swapoff(name): ''' Deactivate a named swap mount .. versionchanged:: 2016.3.2 CLI Example: .. code-block:: bash salt '*' mount.swapoff /root/swapfile ''' on_ = swaps() if name in on_: if __grains__['kernel'] == 'SunOS': if __grains__['virtual'] != 'zone': __salt__['cmd.run']('swap -a {0}'.format(name), python_shell=False) else: return False elif __grains__['os'] != 'OpenBSD': __salt__['cmd.run']('swapoff {0}'.format(name), python_shell=False) else: __salt__['cmd.run']('swapctl -d {0}'.format(name), python_shell=False) on_ = swaps() if name in on_: return False return True return None
Deactivate a named swap mount .. versionchanged:: 2016.3.2 CLI Example: .. code-block:: bash salt '*' mount.swapoff /root/swapfile
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/mount.py#L1447-L1475
[ "def swaps():\n '''\n Return a dict containing information on active swap\n\n .. versionchanged:: 2016.3.2\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' mount.swaps\n '''\n ret = {}\n if __grains__['kernel'] == 'SunOS':\n for line in __salt__['cmd.run_stdout']('swap -l').splitlines():\n if line.startswith('swapfile'):\n continue\n comps = line.split()\n ret[comps[0]] = {'type': 'device' if comps[0].startswith(('/dev', 'swap')) else 'file',\n 'size': int(comps[3]),\n 'used': (int(comps[3]) - int(comps[4])),\n 'priority': '-'}\n elif 'AIX' in __grains__['kernel']:\n for line in __salt__['cmd.run_stdout']('swap -l').splitlines():\n if line.startswith('device'):\n continue\n comps = line.split()\n\n # AIX uses MB for units\n ret[comps[0]] = {'type': 'device',\n 'size': int(comps[3][:-2]) * 1024,\n 'used': (int(comps[3][:-2]) - int(comps[4][:-2])) * 1024,\n 'priority': '-'}\n elif __grains__['os'] != 'OpenBSD':\n with salt.utils.files.fopen('/proc/swaps') as fp_:\n for line in fp_:\n line = salt.utils.stringutils.to_unicode(line)\n if line.startswith('Filename'):\n continue\n comps = line.split()\n ret[comps[0]] = {'type': comps[1],\n 'size': comps[2],\n 'used': comps[3],\n 'priority': comps[4]}\n else:\n for line in __salt__['cmd.run_stdout']('swapctl -kl').splitlines():\n if line.startswith(('Device', 'Total')):\n continue\n swap_type = \"file\"\n comps = line.split()\n if comps[0].startswith('/dev/'):\n swap_type = \"partition\"\n ret[comps[0]] = {'type': swap_type,\n 'size': comps[1],\n 'used': comps[2],\n 'priority': comps[5]}\n return ret\n" ]
# -*- coding: utf-8 -*- ''' Salt module to manage Unix mounts and the fstab file ''' # Import python libs from __future__ import absolute_import, print_function, unicode_literals import os import re import logging # Import salt libs import salt.utils.args import salt.utils.data import salt.utils.files import salt.utils.path import salt.utils.platform import salt.utils.mount import salt.utils.stringutils from salt.utils.odict import OrderedDict from salt.exceptions import CommandNotFoundError, CommandExecutionError # Import 3rd-party libs from salt.ext import six from salt.ext.six.moves import filter, zip # pylint: disable=import-error,redefined-builtin # Set up logger log = logging.getLogger(__name__) # Define the module's virtual name __virtualname__ = 'mount' def __virtual__(): ''' Only load on POSIX-like systems ''' # Disable on Windows, a specific file module exists: if salt.utils.platform.is_windows(): return (False, 'The mount module cannot be loaded: not a POSIX-like system.') return True def _list_mounts(): ret = {} if __grains__['os'] in ['MacOS', 'Darwin']: mounts = __salt__['cmd.run_stdout']('mount') else: mounts = __salt__['cmd.run_stdout']('mount -l') for line in mounts.split('\n'): comps = re.sub(r"\s+", " ", line).split() if len(comps) >= 3: ret[comps[2]] = comps[0] return ret def _active_mountinfo(ret): _list = _list_mounts() filename = '/proc/self/mountinfo' if not os.access(filename, os.R_OK): msg = 'File not readable {0}' raise CommandExecutionError(msg.format(filename)) if 'disk.blkid' not in __context__: __context__['disk.blkid'] = __salt__['disk.blkid']() blkid_info = __context__['disk.blkid'] with salt.utils.files.fopen(filename) as ifile: for line in ifile: comps = salt.utils.stringutils.to_unicode(line).split() device = comps[2].split(':') # each line can have any number of # optional parameters, we use the # location of the separator field to # determine the location of the elements # after it. _sep = comps.index('-') device_name = comps[_sep + 2] device_uuid = None device_label = None if device_name: device_uuid = blkid_info.get(device_name, {}).get('UUID') device_uuid = device_uuid and device_uuid.lower() device_label = blkid_info.get(device_name, {}).get('LABEL') ret[comps[4]] = {'mountid': comps[0], 'parentid': comps[1], 'major': device[0], 'minor': device[1], 'root': comps[3], 'opts': _resolve_user_group_names(comps[5].split(',')), 'fstype': comps[_sep + 1], 'device': device_name.replace('\\040', '\\ '), 'alt_device': _list.get(comps[4], None), 'superopts': _resolve_user_group_names(comps[_sep + 3].split(',')), 'device_uuid': device_uuid, 'device_label': device_label} return ret def _active_mounts(ret): ''' List active mounts on Linux systems ''' _list = _list_mounts() filename = '/proc/self/mounts' if not os.access(filename, os.R_OK): msg = 'File not readable {0}' raise CommandExecutionError(msg.format(filename)) with salt.utils.files.fopen(filename) as ifile: for line in ifile: comps = salt.utils.stringutils.to_unicode(line).split() ret[comps[1]] = {'device': comps[0], 'alt_device': _list.get(comps[1], None), 'fstype': comps[2], 'opts': _resolve_user_group_names(comps[3].split(','))} return ret def _active_mounts_aix(ret): ''' List active mounts on AIX systems ''' for line in __salt__['cmd.run_stdout']('mount -p').split('\n'): comps = re.sub(r"\s+", " ", line).split() if comps: if comps[0] == 'node' or comps[0] == '--------': continue comps_len = len(comps) if line.startswith((' ', '\t')): curr_opts = _resolve_user_group_names(comps[6].split(',')) if 7 == comps_len else [] if curr_opts: ret[comps[1]] = {'device': comps[0], 'fstype': comps[2], 'opts': curr_opts} else: ret[comps[1]] = {'device': comps[0], 'fstype': comps[2]} else: curr_opts = _resolve_user_group_names(comps[7].split(',')) if 8 == comps_len else [] if curr_opts: ret[comps[2]] = {'node': comps[0], 'device': comps[1], 'fstype': comps[3], 'opts': curr_opts} else: ret[comps[2]] = {'node': comps[0], 'device': comps[1], 'fstype': comps[3]} return ret def _active_mounts_freebsd(ret): ''' List active mounts on FreeBSD systems ''' for line in __salt__['cmd.run_stdout']('mount -p').split('\n'): comps = re.sub(r"\s+", " ", line).split() ret[comps[1]] = {'device': comps[0], 'fstype': comps[2], 'opts': _resolve_user_group_names(comps[3].split(','))} return ret def _active_mounts_solaris(ret): ''' List active mounts on Solaris systems ''' for line in __salt__['cmd.run_stdout']('mount -v').split('\n'): comps = re.sub(r"\s+", " ", line).split() ret[comps[2]] = {'device': comps[0], 'fstype': comps[4], 'opts': _resolve_user_group_names(comps[5].split('/'))} return ret def _active_mounts_openbsd(ret): ''' List active mounts on OpenBSD systems ''' for line in __salt__['cmd.run_stdout']('mount -v').split('\n'): comps = re.sub(r"\s+", " ", line).split() parens = re.findall(r'\((.*?)\)', line, re.DOTALL) if len(parens) > 1: nod = __salt__['cmd.run_stdout']('ls -l {0}'.format(comps[0])) nod = ' '.join(nod.split()).split(" ") ret[comps[3]] = {'device': comps[0], 'fstype': comps[5], 'opts': _resolve_user_group_names(parens[1].split(", ")), 'major': six.text_type(nod[4].strip(",")), 'minor': six.text_type(nod[5]), 'device_uuid': parens[0]} else: ret[comps[2]] = {'device': comps[0], 'fstype': comps[4], 'opts': _resolve_user_group_names(parens[0].split(", "))} return ret def _active_mounts_darwin(ret): ''' List active mounts on Mac OS systems ''' for line in __salt__['cmd.run_stdout']('mount').split('\n'): comps = re.sub(r"\s+", " ", line).split() parens = re.findall(r'\((.*?)\)', line, re.DOTALL)[0].split(", ") ret[comps[2]] = {'device': comps[0], 'fstype': parens[0], 'opts': _resolve_user_group_names(parens[1:])} return ret def _resolve_user_group_names(opts): ''' Resolve user and group names in related opts ''' name_id_opts = {'uid': 'user.info', 'gid': 'group.info'} for ind, opt in enumerate(opts): if opt.split('=')[0] in name_id_opts: _givenid = opt.split('=')[1] _param = opt.split('=')[0] _id = _givenid if not re.match('[0-9]+$', _givenid): _info = __salt__[name_id_opts[_param]](_givenid) if _info and _param in _info: _id = _info[_param] opts[ind] = _param + '=' + six.text_type(_id) opts[ind] = opts[ind].replace('\\040', '\\ ') return opts def active(extended=False): ''' List the active mounts. CLI Example: .. code-block:: bash salt '*' mount.active ''' ret = {} if __grains__['os'] == 'FreeBSD': _active_mounts_freebsd(ret) elif 'AIX' in __grains__['kernel']: _active_mounts_aix(ret) elif __grains__['kernel'] == 'SunOS': _active_mounts_solaris(ret) elif __grains__['os'] == 'OpenBSD': _active_mounts_openbsd(ret) elif __grains__['os'] in ['MacOS', 'Darwin']: _active_mounts_darwin(ret) else: if extended: try: _active_mountinfo(ret) except CommandExecutionError: _active_mounts(ret) else: _active_mounts(ret) return ret class _fstab_entry(object): ''' Utility class for manipulating fstab entries. Primarily we're parsing, formatting, and comparing lines. Parsing emits dicts expected from fstab() or raises a ValueError. Note: We'll probably want to use os.normpath and os.normcase on 'name' ''' class ParseError(ValueError): ''' Error raised when a line isn't parsible as an fstab entry ''' fstab_keys = ('device', 'name', 'fstype', 'opts', 'dump', 'pass_num') # preserve data format compatibility_keys = ('device', 'name', 'fstype', 'opts', 'dump', 'pass') fstab_format = '{device}\t\t{name}\t{fstype}\t{opts}\t{dump} {pass_num}\n' @classmethod def dict_from_line(cls, line, keys=fstab_keys): if len(keys) != 6: raise ValueError('Invalid key array: {0}'.format(keys)) if line.startswith('#'): raise cls.ParseError("Comment!") comps = line.split() if len(comps) < 4 or len(comps) > 6: raise cls.ParseError("Invalid Entry!") comps.extend(['0'] * (len(keys) - len(comps))) return dict(zip(keys, comps)) @classmethod def from_line(cls, *args, **kwargs): return cls(** cls.dict_from_line(*args, **kwargs)) @classmethod def dict_to_line(cls, entry): return cls.fstab_format.format(**entry) def __str__(self): ''' String value, only works for full repr ''' return self.dict_to_line(self.criteria) def __repr__(self): ''' Always works ''' return repr(self.criteria) def pick(self, keys): ''' Returns an instance with just those keys ''' subset = dict([(key, self.criteria[key]) for key in keys]) return self.__class__(**subset) def __init__(self, **criteria): ''' Store non-empty, non-null values to use as filter ''' items = [key_value for key_value in six.iteritems(criteria) if key_value[1] is not None] items = [(key_value1[0], six.text_type(key_value1[1])) for key_value1 in items] self.criteria = dict(items) @staticmethod def norm_path(path): ''' Resolve equivalent paths equivalently ''' return os.path.normcase(os.path.normpath(path)) def match(self, line): ''' Compare potentially partial criteria against line ''' entry = self.dict_from_line(line) for key, value in six.iteritems(self.criteria): if entry[key] != value: return False return True class _vfstab_entry(object): ''' Utility class for manipulating vfstab entries. Primarily we're parsing, formatting, and comparing lines. Parsing emits dicts expected from fstab() or raises a ValueError. Note: We'll probably want to use os.normpath and os.normcase on 'name' Note: This parses vfstab entries on Solaris like systems #device device mount FS fsck mount mount #to mount to fsck point type pass at boot options # /devices - /devices devfs - no - ''' class ParseError(ValueError): '''Error raised when a line isn't parsible as an fstab entry''' vfstab_keys = ('device', 'device_fsck', 'name', 'fstype', 'pass_fsck', 'mount_at_boot', 'opts') # NOTE: weird formatting to match default spacing on Solaris vfstab_format = '{device:<11} {device_fsck:<3} {name:<19} {fstype:<8} {pass_fsck:<3} {mount_at_boot:<6} {opts}\n' @classmethod def dict_from_line(cls, line): if line.startswith('#'): raise cls.ParseError("Comment!") comps = line.split() if len(comps) != 7: raise cls.ParseError("Invalid Entry!") return dict(zip(cls.vfstab_keys, comps)) @classmethod def from_line(cls, *args, **kwargs): return cls(** cls.dict_from_line(*args, **kwargs)) @classmethod def dict_to_line(cls, entry): return cls.vfstab_format.format(**entry) def __str__(self): ''' String value, only works for full repr ''' return self.dict_to_line(self.criteria) def __repr__(self): ''' Always works ''' return repr(self.criteria) def pick(self, keys): ''' Returns an instance with just those keys ''' subset = dict([(key, self.criteria[key]) for key in keys]) return self.__class__(**subset) def __init__(self, **criteria): ''' Store non-empty, non-null values to use as filter ''' items = [key_value for key_value in six.iteritems(criteria) if key_value[1] is not None] items = [(key_value1[0], six.text_type(key_value1[1])) for key_value1 in items] self.criteria = dict(items) @staticmethod def norm_path(path): ''' Resolve equivalent paths equivalently ''' return os.path.normcase(os.path.normpath(path)) def match(self, line): ''' Compare potentially partial criteria against line ''' entry = self.dict_from_line(line) for key, value in six.iteritems(self.criteria): if entry[key] != value: return False return True class _FileSystemsEntry(object): ''' Utility class for manipulating filesystem entries. Primarily we're parsing, formatting, and comparing lines. Parsing emits dicts expected from fstab() or raises a ValueError. Note: We'll probably want to use os.normpath and os.normcase on 'name' ''' class ParseError(ValueError): ''' Error raised when a line isn't parsible as an fstab entry ''' filesystems_keys = ('device', 'name', 'fstype', 'vfstype', 'opts', 'mount') # preserve data format of filesystems compatibility_keys = ('dev', 'dev', 'name', 'fstype', 'vfstype', 'opts', 'mount', 'type', 'vfs', 'account', 'boot', 'check', 'free', 'nodename', 'quota', 'size', 'vol', 'log') @classmethod def dict_from_lines(cls, lines, keys=filesystems_keys): if len(lines) < 2: raise ValueError('Invalid number of lines: {0}'.format(lines)) if not keys: # if empty force default filesystems_keys keys = _FileSystemsEntry.filesystems_keys elif len(keys) < 6: raise ValueError('Invalid key name array: {0}'.format(keys)) blk_lines = lines orddict = OrderedDict() orddict['name'] = blk_lines[0].split(':')[0].strip() blk_lines.pop(0) for line in blk_lines: if line.startswith('#'): raise cls.ParseError("Comment!") comps = line.split('= ') if len(comps) != 2: raise cls.ParseError("Invalid Entry!") key_name = comps[0].strip() if key_name in keys: orddict[key_name] = comps[1].strip() else: raise ValueError('Invalid name for use in filesystems: {0}'.format(key_name)) return orddict @classmethod def dict_from_cmd_line(cls, ipargs, keys): cmdln_dict = ipargs if keys: for key, value in keys: # ignore unknown or local scope keys if key.startswith('__'): continue if key in _FileSystemsEntry.compatibility_keys: cmdln_dict[key] = value return cmdln_dict @classmethod def from_line(cls, *args, **kwargs): return cls(** cls.dict_from_cmd_line(*args, **kwargs)) @classmethod def dict_to_lines(cls, fsys_dict_entry): entry = fsys_dict_entry strg_out = entry['name'] + ':' + os.linesep for k, v in six.viewitems(entry): if 'name' not in k: strg_out += '\t{0}\t\t= {1}'.format(k, v) + os.linesep strg_out += os.linesep return six.text_type(strg_out) def dict_from_entry(self): ret = OrderedDict() ret[self.criteria['name']] = self.criteria return ret def __str__(self): ''' String value, only works for full repr ''' return self.dict_to_lines(self.criteria) def __repr__(self): ''' Always works ''' return repr(self.criteria) def pick(self, keys): ''' Returns an instance with just those keys ''' subset = dict([(key, self.criteria[key]) for key in keys]) return self.__class__(**subset) def __init__(self, **criteria): ''' Store non-empty, non-null values to use as filter ''' items = [key_value for key_value in six.iteritems(criteria) if key_value[1] is not None] items = [(key_value1[0], six.text_type(key_value1[1])) for key_value1 in items] self.criteria = OrderedDict(items) @staticmethod def norm_path(path): ''' Resolve equivalent paths equivalently ''' return os.path.normcase(os.path.normpath(path)) def match(self, fsys_view): ''' Compare potentially partial criteria against built filesystems entry dictionary ''' evalue_dict = fsys_view[1] for key, value in six.viewitems(self.criteria): if key in evalue_dict: if evalue_dict[key] != value: return False else: return False return True def __getitem__(self, key): ''' Return value for input key ''' return self.criteria[key] def fstab(config='/etc/fstab'): ''' .. versionchanged:: 2016.3.2 List the contents of the fstab CLI Example: .. code-block:: bash salt '*' mount.fstab ''' ret = {} if not os.path.isfile(config): return ret with salt.utils.files.fopen(config) as ifile: for line in ifile: line = salt.utils.stringutils.to_unicode(line) try: if __grains__['kernel'] == 'SunOS': # Note: comments use in default vfstab file! if line[0] == '#': continue entry = _vfstab_entry.dict_from_line( line) else: entry = _fstab_entry.dict_from_line( line, _fstab_entry.compatibility_keys) entry['opts'] = entry['opts'].split(',') while entry['name'] in ret: entry['name'] += '_' ret[entry.pop('name')] = entry except _fstab_entry.ParseError: pass except _vfstab_entry.ParseError: pass return ret def vfstab(config='/etc/vfstab'): ''' .. versionadded:: 2016.3.2 List the contents of the vfstab CLI Example: .. code-block:: bash salt '*' mount.vfstab ''' # NOTE: vfstab is a wrapper for fstab return fstab(config) def rm_fstab(name, device, config='/etc/fstab'): ''' .. versionchanged:: 2016.3.2 Remove the mount point from the fstab CLI Example: .. code-block:: bash salt '*' mount.rm_fstab /mnt/foo /dev/sdg ''' modified = False if __grains__['kernel'] == 'SunOS': criteria = _vfstab_entry(name=name, device=device) else: criteria = _fstab_entry(name=name, device=device) lines = [] try: with salt.utils.files.fopen(config, 'r') as ifile: for line in ifile: line = salt.utils.stringutils.to_unicode(line) try: if criteria.match(line): modified = True else: lines.append(line) except _fstab_entry.ParseError: lines.append(line) except _vfstab_entry.ParseError: lines.append(line) except (IOError, OSError) as exc: msg = "Couldn't read from {0}: {1}" raise CommandExecutionError(msg.format(config, exc)) if modified: try: with salt.utils.files.fopen(config, 'wb') as ofile: ofile.writelines(salt.utils.data.encode(lines)) except (IOError, OSError) as exc: msg = "Couldn't write to {0}: {1}" raise CommandExecutionError(msg.format(config, exc)) # Note: not clear why we always return 'True' # --just copying previous behavior at this point... return True def rm_vfstab(name, device, config='/etc/vfstab'): ''' .. versionadded:: 2016.3.2 Remove the mount point from the vfstab CLI Example: .. code-block:: bash salt '*' mount.rm_vfstab /mnt/foo /device/c0t0d0p0 ''' ## NOTE: rm_vfstab is a wrapper for rm_fstab return rm_fstab(name, device, config) def set_fstab( name, device, fstype, opts='defaults', dump=0, pass_num=0, config='/etc/fstab', test=False, match_on='auto', **kwargs): ''' Verify that this mount is represented in the fstab, change the mount to match the data passed, or add the mount if it is not present. CLI Example: .. code-block:: bash salt '*' mount.set_fstab /mnt/foo /dev/sdz1 ext4 ''' # Fix the opts type if it is a list if isinstance(opts, list): opts = ','.join(opts) # preserve arguments for updating entry_args = { 'name': name, 'device': device.replace('\\ ', '\\040'), 'fstype': fstype, 'opts': opts.replace('\\ ', '\\040'), 'dump': dump, 'pass_num': pass_num, } lines = [] ret = None # Transform match_on into list--items will be checked later if isinstance(match_on, list): pass elif not isinstance(match_on, six.string_types): msg = 'match_on must be a string or list of strings' raise CommandExecutionError(msg) elif match_on == 'auto': # Try to guess right criteria for auto.... # NOTE: missing some special fstypes here specialFSes = frozenset([ 'none', 'tmpfs', 'sysfs', 'proc', 'fusectl', 'debugfs', 'securityfs', 'devtmpfs', 'cgroup', 'btrfs']) if fstype in specialFSes: match_on = ['name'] else: match_on = ['device'] else: match_on = [match_on] # generate entry and criteria objects, handle invalid keys in match_on entry = _fstab_entry(**entry_args) try: criteria = entry.pick(match_on) except KeyError: filterFn = lambda key: key not in _fstab_entry.fstab_keys invalid_keys = filter(filterFn, match_on) msg = 'Unrecognized keys in match_on: "{0}"'.format(invalid_keys) raise CommandExecutionError(msg) # parse file, use ret to cache status if not os.path.isfile(config): raise CommandExecutionError('Bad config file "{0}"'.format(config)) try: with salt.utils.files.fopen(config, 'r') as ifile: for line in ifile: line = salt.utils.stringutils.to_unicode(line) try: if criteria.match(line): # Note: If ret isn't None here, # we've matched multiple lines ret = 'present' if entry.match(line): lines.append(line) else: ret = 'change' lines.append(six.text_type(entry)) else: lines.append(line) except _fstab_entry.ParseError: lines.append(line) except (IOError, OSError) as exc: msg = 'Couldn\'t read from {0}: {1}' raise CommandExecutionError(msg.format(config, exc)) # add line if not present or changed if ret is None: lines.append(six.text_type(entry)) ret = 'new' if ret != 'present': # ret in ['new', 'change']: if not salt.utils.args.test_mode(test=test, **kwargs): try: with salt.utils.files.fopen(config, 'wb') as ofile: # The line was changed, commit it! ofile.writelines(salt.utils.data.encode(lines)) except (IOError, OSError): msg = 'File not writable {0}' raise CommandExecutionError(msg.format(config)) return ret def set_vfstab( name, device, fstype, opts='-', device_fsck='-', pass_fsck='-', mount_at_boot='yes', config='/etc/vfstab', test=False, match_on='auto', **kwargs): ''' ..verionadded:: 2016.3.2 Verify that this mount is represented in the fstab, change the mount to match the data passed, or add the mount if it is not present. CLI Example: .. code-block:: bash salt '*' mount.set_vfstab /mnt/foo /device/c0t0d0p0 ufs ''' # Fix the opts type if it is a list if isinstance(opts, list): opts = ','.join(opts) # Map unknown values for mount_at_boot to no if mount_at_boot != 'yes': mount_at_boot = 'no' # preserve arguments for updating entry_args = { 'name': name, 'device': device, 'fstype': fstype, 'opts': opts, 'device_fsck': device_fsck, 'pass_fsck': pass_fsck, 'mount_at_boot': mount_at_boot, } lines = [] ret = None # Transform match_on into list--items will be checked later if isinstance(match_on, list): pass elif not isinstance(match_on, six.string_types): msg = 'match_on must be a string or list of strings' raise CommandExecutionError(msg) elif match_on == 'auto': # Try to guess right criteria for auto.... # NOTE: missing some special fstypes here specialFSes = frozenset([ 'devfs', 'proc', 'ctfs', 'objfs', 'sharefs', 'fs', 'tmpfs']) if fstype in specialFSes: match_on = ['name'] else: match_on = ['device'] else: match_on = [match_on] # generate entry and criteria objects, handle invalid keys in match_on entry = _vfstab_entry(**entry_args) try: criteria = entry.pick(match_on) except KeyError: filterFn = lambda key: key not in _vfstab_entry.vfstab_keys invalid_keys = filter(filterFn, match_on) msg = 'Unrecognized keys in match_on: "{0}"'.format(invalid_keys) raise CommandExecutionError(msg) # parse file, use ret to cache status if not os.path.isfile(config): raise CommandExecutionError('Bad config file "{0}"'.format(config)) try: with salt.utils.files.fopen(config, 'r') as ifile: for line in ifile: line = salt.utils.stringutils.to_unicode(line) try: if criteria.match(line): # Note: If ret isn't None here, # we've matched multiple lines ret = 'present' if entry.match(line): lines.append(line) else: ret = 'change' lines.append(six.text_type(entry)) else: lines.append(line) except _vfstab_entry.ParseError: lines.append(line) except (IOError, OSError) as exc: msg = 'Couldn\'t read from {0}: {1}' raise CommandExecutionError(msg.format(config, exc)) # add line if not present or changed if ret is None: lines.append(six.text_type(entry)) ret = 'new' if ret != 'present': # ret in ['new', 'change']: if not salt.utils.args.test_mode(test=test, **kwargs): try: with salt.utils.files.fopen(config, 'wb') as ofile: # The line was changed, commit it! ofile.writelines(salt.utils.data.encode(lines)) except (IOError, OSError): msg = 'File not writable {0}' raise CommandExecutionError(msg.format(config)) return ret def rm_automaster(name, device, config='/etc/auto_salt'): ''' Remove the mount point from the auto_master CLI Example: .. code-block:: bash salt '*' mount.rm_automaster /mnt/foo /dev/sdg ''' contents = automaster(config) if name not in contents: return True # The entry is present, get rid of it lines = [] try: with salt.utils.files.fopen(config, 'r') as ifile: for line in ifile: line = salt.utils.stringutils.to_unicode(line) if line.startswith('#'): # Commented lines.append(line) continue if not line.strip(): # Blank line lines.append(line) continue comps = line.split() if len(comps) != 3: # Invalid entry lines.append(line) continue comps = line.split() prefix = "/.." name_chk = comps[0].replace(prefix, "") device_fmt = comps[2].split(":") if device: if name_chk == name and device_fmt[1] == device: continue else: if name_chk == name: continue lines.append(line) except (IOError, OSError) as exc: msg = "Couldn't read from {0}: {1}" raise CommandExecutionError(msg.format(config, exc)) try: with salt.utils.files.fopen(config, 'wb') as ofile: ofile.writelines(salt.utils.data.encode(lines)) except (IOError, OSError) as exc: msg = "Couldn't write to {0}: {1}" raise CommandExecutionError(msg.format(config, exc)) # Update automount __salt__['cmd.run']('automount -cv') return True def set_automaster( name, device, fstype, opts='', config='/etc/auto_salt', test=False, **kwargs): ''' Verify that this mount is represented in the auto_salt, change the mount to match the data passed, or add the mount if it is not present. CLI Example: .. code-block:: bash salt '*' mount.set_automaster /mnt/foo /dev/sdz1 ext4 ''' # Fix the opts type if it is a list if isinstance(opts, list): opts = ','.join(opts) lines = [] change = False present = False automaster_file = "/etc/auto_master" if not os.path.isfile(config): __salt__['file.touch'](config) __salt__['file.append'](automaster_file, "/-\t\t\t{0}".format(config)) name = "/..{0}".format(name) device_fmt = "{0}:{1}".format(fstype, device) type_opts = "-fstype={0},{1}".format(fstype, opts) if fstype == 'smbfs': device_fmt = device_fmt.replace(fstype, "") try: with salt.utils.files.fopen(config, 'r') as ifile: for line in ifile: line = salt.utils.stringutils.to_unicode(line) if line.startswith('#'): # Commented lines.append(line) continue if not line.strip(): # Blank line lines.append(line) continue comps = line.split() if len(comps) != 3: # Invalid entry lines.append(line) continue if comps[0] == name or comps[2] == device_fmt: # check to see if there are changes # and fix them if there are any present = True if comps[0] != name: change = True comps[0] = name if comps[1] != type_opts: change = True comps[1] = type_opts if comps[2] != device_fmt: change = True comps[2] = device_fmt if change: log.debug( 'auto_master entry for mount point %s needs to be ' 'updated', name ) newline = ( '{0}\t{1}\t{2}\n'.format( name, type_opts, device_fmt) ) lines.append(newline) else: lines.append(line) except (IOError, OSError) as exc: msg = 'Couldn\'t read from {0}: {1}' raise CommandExecutionError(msg.format(config, exc)) if change: if not salt.utils.args.test_mode(test=test, **kwargs): try: with salt.utils.files.fopen(config, 'wb') as ofile: # The line was changed, commit it! ofile.writelines(salt.utils.data.encode(lines)) except (IOError, OSError): msg = 'File not writable {0}' raise CommandExecutionError(msg.format(config)) return 'change' if not change: if present: # The right entry is already here return 'present' else: if not salt.utils.args.test_mode(test=test, **kwargs): # The entry is new, add it to the end of the fstab newline = ( '{0}\t{1}\t{2}\n'.format( name, type_opts, device_fmt) ) lines.append(newline) try: with salt.utils.files.fopen(config, 'wb') as ofile: # The line was changed, commit it! ofile.writelines(salt.utils.data.encode(lines)) except (IOError, OSError): raise CommandExecutionError( 'File not writable {0}'.format( config ) ) return 'new' def automaster(config='/etc/auto_salt'): ''' List the contents of the auto master CLI Example: .. code-block:: bash salt '*' mount.automaster ''' ret = {} if not os.path.isfile(config): return ret with salt.utils.files.fopen(config) as ifile: for line in ifile: line = salt.utils.stringutils.to_unicode(line) if line.startswith('#'): # Commented continue if not line.strip(): # Blank line continue comps = line.split() if len(comps) != 3: # Invalid entry continue prefix = "/.." name = comps[0].replace(prefix, "") device_fmt = comps[2].split(":") opts = comps[1].split(',') ret[name] = {'device': device_fmt[1], 'fstype': opts[0], 'opts': opts[1:]} return ret def mount(name, device, mkmnt=False, fstype='', opts='defaults', user=None, util='mount'): ''' Mount a device CLI Example: .. code-block:: bash salt '*' mount.mount /mnt/foo /dev/sdz1 True ''' if util != 'mount': # This functionality used to live in img.mount_image if util == 'guestfs': return __salt__['guestfs.mount'](name, root=device) elif util == 'qemu_nbd': mnt = __salt__['qemu_nbd.init'](name, device) if not mnt: return False first = next(six.iterkeys(mnt)) __context__['img.mnt_{0}'.format(first)] = mnt return first return False # Darwin doesn't expect defaults when mounting without other options if 'defaults' in opts and __grains__['os'] in ['MacOS', 'Darwin', 'AIX']: opts = None if isinstance(opts, six.string_types): opts = opts.split(',') if not os.path.exists(name) and mkmnt: __salt__['file.mkdir'](name, user=user) args = '' if opts is not None: lopts = ','.join(opts) args = '-o {0}'.format(lopts) if fstype: # use of fstype on AIX differs from typical Linux use of -t # functionality AIX uses -v vfsname, -t fstype mounts all with # fstype in /etc/filesystems if 'AIX' in __grains__['os']: args += ' -v {0}'.format(fstype) elif 'solaris' in __grains__['os'].lower(): args += ' -F {0}'.format(fstype) else: args += ' -t {0}'.format(fstype) cmd = 'mount {0} {1} {2} '.format(args, device, name) out = __salt__['cmd.run_all'](cmd, runas=user, python_shell=False) if out['retcode']: return out['stderr'] return True def remount(name, device, mkmnt=False, fstype='', opts='defaults', user=None): ''' Attempt to remount a device, if the device is not already mounted, mount is called CLI Example: .. code-block:: bash salt '*' mount.remount /mnt/foo /dev/sdz1 True ''' force_mount = False if __grains__['os'] in ['MacOS', 'Darwin']: if opts == 'defaults': opts = 'noowners' if fstype == 'smbfs': force_mount = True if 'AIX' in __grains__['os']: if opts == 'defaults': opts = [] if isinstance(opts, six.string_types): opts = opts.split(',') mnts = active() if name in mnts: # The mount point is mounted, attempt to remount it with the given data if 'remount' not in opts and __grains__['os'] not in ['OpenBSD', 'MacOS', 'Darwin']: opts.append('remount') if force_mount: # We need to force the mount but first we should unmount umount(name, device, user=user) lopts = ','.join(opts) args = '-o {0}'.format(lopts) if fstype: # use of fstype on AIX differs from typical Linux use of # -t functionality AIX uses -v vfsname, -t fstype mounts # all with fstype in /etc/filesystems if 'AIX' in __grains__['os']: args += ' -v {0}'.format(fstype) elif 'solaris' in __grains__['os'].lower(): args += ' -F {0}'.format(fstype) else: args += ' -t {0}'.format(fstype) if __grains__['os'] not in ['OpenBSD', 'MacOS', 'Darwin'] or force_mount: cmd = 'mount {0} {1} {2} '.format(args, device, name) else: cmd = 'mount -u {0} {1} {2} '.format(args, device, name) out = __salt__['cmd.run_all'](cmd, runas=user, python_shell=False) if out['retcode']: return out['stderr'] return True # Mount a filesystem that isn't already return mount(name, device, mkmnt, fstype, opts, user=user) def umount(name, device=None, user=None, util='mount'): ''' Attempt to unmount a device by specifying the directory it is mounted on CLI Example: .. code-block:: bash salt '*' mount.umount /mnt/foo .. versionadded:: 2015.5.0 .. code-block:: bash salt '*' mount.umount /mnt/foo /dev/xvdc1 ''' if util != 'mount': # This functionality used to live in img.umount_image if 'qemu_nbd.clear' in __salt__: if 'img.mnt_{0}'.format(name) in __context__: __salt__['qemu_nbd.clear'](__context__['img.mnt_{0}'.format(name)]) return mnts = active() if name not in mnts: return "{0} does not have anything mounted".format(name) if not device: cmd = 'umount {0}'.format(name) else: cmd = 'umount {0}'.format(device) out = __salt__['cmd.run_all'](cmd, runas=user, python_shell=False) if out['retcode']: return out['stderr'] return True def is_fuse_exec(cmd): ''' Returns true if the command passed is a fuse mountable application. CLI Example: .. code-block:: bash salt '*' mount.is_fuse_exec sshfs ''' cmd_path = salt.utils.path.which(cmd) # No point in running ldd on a command that doesn't exist if not cmd_path: return False elif not salt.utils.path.which('ldd'): raise CommandNotFoundError('ldd') out = __salt__['cmd.run']('ldd {0}'.format(cmd_path), python_shell=False) return 'libfuse' in out def swaps(): ''' Return a dict containing information on active swap .. versionchanged:: 2016.3.2 CLI Example: .. code-block:: bash salt '*' mount.swaps ''' ret = {} if __grains__['kernel'] == 'SunOS': for line in __salt__['cmd.run_stdout']('swap -l').splitlines(): if line.startswith('swapfile'): continue comps = line.split() ret[comps[0]] = {'type': 'device' if comps[0].startswith(('/dev', 'swap')) else 'file', 'size': int(comps[3]), 'used': (int(comps[3]) - int(comps[4])), 'priority': '-'} elif 'AIX' in __grains__['kernel']: for line in __salt__['cmd.run_stdout']('swap -l').splitlines(): if line.startswith('device'): continue comps = line.split() # AIX uses MB for units ret[comps[0]] = {'type': 'device', 'size': int(comps[3][:-2]) * 1024, 'used': (int(comps[3][:-2]) - int(comps[4][:-2])) * 1024, 'priority': '-'} elif __grains__['os'] != 'OpenBSD': with salt.utils.files.fopen('/proc/swaps') as fp_: for line in fp_: line = salt.utils.stringutils.to_unicode(line) if line.startswith('Filename'): continue comps = line.split() ret[comps[0]] = {'type': comps[1], 'size': comps[2], 'used': comps[3], 'priority': comps[4]} else: for line in __salt__['cmd.run_stdout']('swapctl -kl').splitlines(): if line.startswith(('Device', 'Total')): continue swap_type = "file" comps = line.split() if comps[0].startswith('/dev/'): swap_type = "partition" ret[comps[0]] = {'type': swap_type, 'size': comps[1], 'used': comps[2], 'priority': comps[5]} return ret def swapon(name, priority=None): ''' Activate a swap disk .. versionchanged:: 2016.3.2 CLI Example: .. code-block:: bash salt '*' mount.swapon /root/swapfile ''' ret = {} on_ = swaps() if name in on_: ret['stats'] = on_[name] ret['new'] = False return ret if __grains__['kernel'] == 'SunOS': if __grains__['virtual'] != 'zone': __salt__['cmd.run']('swap -a {0}'.format(name), python_shell=False) else: return False else: cmd = 'swapon {0}'.format(name) if priority and 'AIX' not in __grains__['kernel']: cmd += ' -p {0}'.format(priority) __salt__['cmd.run'](cmd, python_shell=False) on_ = swaps() if name in on_: ret['stats'] = on_[name] ret['new'] = True return ret return ret def is_mounted(name): ''' .. versionadded:: 2014.7.0 Provide information if the path is mounted CLI Example: .. code-block:: bash salt '*' mount.is_mounted /mnt/share ''' active_ = active() if name in active_: return True else: return False def read_mount_cache(name): ''' .. versionadded:: 2018.3.0 Provide information if the path is mounted CLI Example: .. code-block:: bash salt '*' mount.read_mount_cache /mnt/share ''' cache = salt.utils.mount.read_cache(__opts__) if cache: if 'mounts' in cache and cache['mounts']: if name in cache['mounts']: return cache['mounts'][name] return {} def write_mount_cache(real_name, device, mkmnt, fstype, mount_opts): ''' .. versionadded:: 2018.3.0 Provide information if the path is mounted :param real_name: The real name of the mount point where the device is mounted. :param device: The device that is being mounted. :param mkmnt: Whether or not the mount point should be created. :param fstype: The file system that is used. :param mount_opts: Additional options used when mounting the device. :return: Boolean if message was sent successfully. CLI Example: .. code-block:: bash salt '*' mount.write_mount_cache /mnt/share /dev/sda1 False ext4 defaults,nosuid ''' cache = salt.utils.mount.read_cache(__opts__) if not cache: cache = {} cache['mounts'] = {} else: if 'mounts' not in cache: cache['mounts'] = {} cache['mounts'][real_name] = {'device': device, 'fstype': fstype, 'mkmnt': mkmnt, 'opts': mount_opts} cache_write = salt.utils.mount.write_cache(cache, __opts__) if cache_write: return True else: raise CommandExecutionError('Unable to write mount cache.') def delete_mount_cache(real_name): ''' .. versionadded:: 2018.3.0 Provide information if the path is mounted CLI Example: .. code-block:: bash salt '*' mount.delete_mount_cache /mnt/share ''' cache = salt.utils.mount.read_cache(__opts__) if cache: if 'mounts' in cache: if real_name in cache['mounts']: del cache['mounts'][real_name] cache_write = salt.utils.mount.write_cache(cache, __opts__) if not cache_write: raise CommandExecutionError('Unable to write mount cache.') return True def _filesystems(config='/etc/filesystems', leading_key=True): ''' Return the contents of the filesystems in an OrderedDict config File containing filesystem infomation leading_key True return dictionary keyed by 'name' and value as dictionary with other keys, values (name excluded) OrderedDict({ '/dir' : OrderedDict({'dev': '/dev/hd8', .... }})) False return dictionary keyed by 'name' and value as dictionary with all keys, values (name included) OrderedDict({ '/dir' : OrderedDict({'name': '/dir', 'dev': '/dev/hd8', ... })}) ''' ret = OrderedDict() lines = [] parsing_block = False if not os.path.isfile(config) or 'AIX' not in __grains__['kernel']: return ret # read in block of filesystems, block starts with '/' till empty line with salt.utils.files.fopen(config) as ifile: for line in ifile: line = salt.utils.stringutils.to_unicode(line) # skip till first entry if not line.startswith('/') and not parsing_block: continue if line.startswith('/'): parsing_block = True lines.append(line) elif not line.split(): parsing_block = False try: entry = _FileSystemsEntry.dict_from_lines( lines, _FileSystemsEntry.compatibility_keys) lines = [] if 'opts' in entry: entry['opts'] = entry['opts'].split(',') while entry['name'] in ret: entry['name'] += '_' if leading_key: ret[entry.pop('name')] = entry else: ret[entry['name']] = entry except _FileSystemsEntry.ParseError: pass else: lines.append(line) return ret def filesystems(config='/etc/filesystems'): ''' .. versionadded:: 2018.3.3 List the contents of the filesystems CLI Example: .. code-block:: bash salt '*' mount.filesystems ''' ret = {} if 'AIX' not in __grains__['kernel']: return ret ret_dict = _filesystems(config) if ret_dict: ret_key = next(iter(ret_dict.keys())) ret = {ret_key: dict(ret_dict[ret_key])} return ret def set_filesystems( name, device, vfstype, opts='-', mount='true', config='/etc/filesystems', test=False, match_on='auto', **kwargs): ''' .. versionadded:: 2018.3.3 Verify that this mount is represented in the filesystems, change the mount to match the data passed, or add the mount if it is not present on AIX Provide information if the path is mounted :param name: The name of the mount point where the device is mounted. :param device: The device that is being mounted. :param vfstype: The file system that is used (AIX has two fstypes, fstype and vfstype - similar to Linux fstype) :param opts: Additional options used when mounting the device. :param mount: Mount if not mounted, default True. :param config: Configuration file, default /etc/filesystems. :param match: File systems type to match on, default auto CLI Example: .. code-block:: bash salt '*' mount.set_filesystems /mnt/foo /dev/sdz1 jfs2 ''' # Fix the opts type if it is a list if isinstance(opts, list): opts = ','.join(opts) # preserve arguments for updating entry_args = { 'name': name, 'dev': device.replace('\\ ', '\\040'), 'vfstype': vfstype, 'opts': opts, 'mount': mount, } view_lines = [] ret = None if 'AIX' not in __grains__['kernel']: return ret # Transform match_on into list--items will be checked later if isinstance(match_on, list): pass elif not isinstance(match_on, six.string_types): raise CommandExecutionError('match_on must be a string or list of strings') elif match_on == 'auto': # Try to guess right criteria for auto.... # added IBM types from sys/vmount.h after btrfs # NOTE: missing some special fstypes here specialFSes = frozenset([ 'none', 'tmpfs', 'sysfs', 'proc', 'fusectl', 'debugfs', 'securityfs', 'devtmpfs', 'cgroup', 'btrfs', 'cdrfs', 'procfs', 'jfs', 'jfs2', 'nfs', 'sfs', 'nfs3', 'cachefs', 'udfs', 'cifs', 'namefs', 'pmemfs', 'ahafs', 'nfs4', 'autofs', 'stnfs']) if vfstype in specialFSes: match_on = ['name'] else: match_on = ['dev'] else: match_on = [match_on] # generate entry and criteria objects, handle invalid keys in match_on entry_ip = _FileSystemsEntry.from_line(entry_args, kwargs) try: criteria = entry_ip.pick(match_on) except KeyError: filterFn = lambda key: key not in _FileSystemsEntry.compatibility_keys invalid_keys = filter(filterFn, match_on) raise CommandExecutionError('Unrecognized keys in match_on: "{0}"'.format(invalid_keys)) # parse file, use ret to cache status if not os.path.isfile(config): raise CommandExecutionError('Bad config file "{0}"'.format(config)) # read in block of filesystem, block starts with '/' till empty line try: fsys_filedict = _filesystems(config, False) for fsys_view in six.viewitems(fsys_filedict): if criteria.match(fsys_view): ret = 'present' if entry_ip.match(fsys_view): view_lines.append(fsys_view) else: ret = 'change' kv = entry_ip['name'] view_lines.append((kv, entry_ip)) else: view_lines.append(fsys_view) except (IOError, OSError) as exc: raise CommandExecutionError('Couldn\'t read from {0}: {1}'.format(config, exc)) # add line if not present or changed if ret is None: for dict_view in six.viewitems(entry_ip.dict_from_entry()): view_lines.append(dict_view) ret = 'new' if ret != 'present': # ret in ['new', 'change']: try: with salt.utils.files.fopen(config, 'wb') as ofile: # The line was changed, commit it! for fsys_view in view_lines: entry = fsys_view[1] mystrg = _FileSystemsEntry.dict_to_lines(entry) ofile.writelines(salt.utils.data.encode(mystrg)) except (IOError, OSError): raise CommandExecutionError('File not writable {0}'.format(config)) return ret def rm_filesystems(name, device, config='/etc/filesystems'): ''' .. versionadded:: 2018.3.3 Remove the mount point from the filesystems CLI Example: .. code-block:: bash salt '*' mount.rm_filesystems /mnt/foo /dev/sdg ''' modified = False view_lines = [] if 'AIX' not in __grains__['kernel']: return modified criteria = _FileSystemsEntry(name=name, dev=device) try: fsys_filedict = _filesystems(config, False) for fsys_view in six.viewitems(fsys_filedict): try: if criteria.match(fsys_view): modified = True else: view_lines.append(fsys_view) except _FileSystemsEntry.ParseError: view_lines.append(fsys_view) except (IOError, OSError) as exc: raise CommandExecutionError("Couldn't read from {0}: {1}".format(config, exc)) if modified: try: with salt.utils.files.fopen(config, 'wb') as ofile: for fsys_view in view_lines: entry = fsys_view[1] mystrg = _FileSystemsEntry.dict_to_lines(entry) ofile.writelines(salt.utils.data.encode(mystrg)) except (IOError, OSError) as exc: raise CommandExecutionError("Couldn't write to {0}: {1}".format(config, exc)) return modified
saltstack/salt
salt/modules/mount.py
read_mount_cache
python
def read_mount_cache(name): ''' .. versionadded:: 2018.3.0 Provide information if the path is mounted CLI Example: .. code-block:: bash salt '*' mount.read_mount_cache /mnt/share ''' cache = salt.utils.mount.read_cache(__opts__) if cache: if 'mounts' in cache and cache['mounts']: if name in cache['mounts']: return cache['mounts'][name] return {}
.. versionadded:: 2018.3.0 Provide information if the path is mounted CLI Example: .. code-block:: bash salt '*' mount.read_mount_cache /mnt/share
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/mount.py#L1497-L1514
[ "def read_cache(opts):\n '''\n Write the mount cache file.\n '''\n cache_file = get_cache(opts)\n return _read_file(cache_file)\n" ]
# -*- coding: utf-8 -*- ''' Salt module to manage Unix mounts and the fstab file ''' # Import python libs from __future__ import absolute_import, print_function, unicode_literals import os import re import logging # Import salt libs import salt.utils.args import salt.utils.data import salt.utils.files import salt.utils.path import salt.utils.platform import salt.utils.mount import salt.utils.stringutils from salt.utils.odict import OrderedDict from salt.exceptions import CommandNotFoundError, CommandExecutionError # Import 3rd-party libs from salt.ext import six from salt.ext.six.moves import filter, zip # pylint: disable=import-error,redefined-builtin # Set up logger log = logging.getLogger(__name__) # Define the module's virtual name __virtualname__ = 'mount' def __virtual__(): ''' Only load on POSIX-like systems ''' # Disable on Windows, a specific file module exists: if salt.utils.platform.is_windows(): return (False, 'The mount module cannot be loaded: not a POSIX-like system.') return True def _list_mounts(): ret = {} if __grains__['os'] in ['MacOS', 'Darwin']: mounts = __salt__['cmd.run_stdout']('mount') else: mounts = __salt__['cmd.run_stdout']('mount -l') for line in mounts.split('\n'): comps = re.sub(r"\s+", " ", line).split() if len(comps) >= 3: ret[comps[2]] = comps[0] return ret def _active_mountinfo(ret): _list = _list_mounts() filename = '/proc/self/mountinfo' if not os.access(filename, os.R_OK): msg = 'File not readable {0}' raise CommandExecutionError(msg.format(filename)) if 'disk.blkid' not in __context__: __context__['disk.blkid'] = __salt__['disk.blkid']() blkid_info = __context__['disk.blkid'] with salt.utils.files.fopen(filename) as ifile: for line in ifile: comps = salt.utils.stringutils.to_unicode(line).split() device = comps[2].split(':') # each line can have any number of # optional parameters, we use the # location of the separator field to # determine the location of the elements # after it. _sep = comps.index('-') device_name = comps[_sep + 2] device_uuid = None device_label = None if device_name: device_uuid = blkid_info.get(device_name, {}).get('UUID') device_uuid = device_uuid and device_uuid.lower() device_label = blkid_info.get(device_name, {}).get('LABEL') ret[comps[4]] = {'mountid': comps[0], 'parentid': comps[1], 'major': device[0], 'minor': device[1], 'root': comps[3], 'opts': _resolve_user_group_names(comps[5].split(',')), 'fstype': comps[_sep + 1], 'device': device_name.replace('\\040', '\\ '), 'alt_device': _list.get(comps[4], None), 'superopts': _resolve_user_group_names(comps[_sep + 3].split(',')), 'device_uuid': device_uuid, 'device_label': device_label} return ret def _active_mounts(ret): ''' List active mounts on Linux systems ''' _list = _list_mounts() filename = '/proc/self/mounts' if not os.access(filename, os.R_OK): msg = 'File not readable {0}' raise CommandExecutionError(msg.format(filename)) with salt.utils.files.fopen(filename) as ifile: for line in ifile: comps = salt.utils.stringutils.to_unicode(line).split() ret[comps[1]] = {'device': comps[0], 'alt_device': _list.get(comps[1], None), 'fstype': comps[2], 'opts': _resolve_user_group_names(comps[3].split(','))} return ret def _active_mounts_aix(ret): ''' List active mounts on AIX systems ''' for line in __salt__['cmd.run_stdout']('mount -p').split('\n'): comps = re.sub(r"\s+", " ", line).split() if comps: if comps[0] == 'node' or comps[0] == '--------': continue comps_len = len(comps) if line.startswith((' ', '\t')): curr_opts = _resolve_user_group_names(comps[6].split(',')) if 7 == comps_len else [] if curr_opts: ret[comps[1]] = {'device': comps[0], 'fstype': comps[2], 'opts': curr_opts} else: ret[comps[1]] = {'device': comps[0], 'fstype': comps[2]} else: curr_opts = _resolve_user_group_names(comps[7].split(',')) if 8 == comps_len else [] if curr_opts: ret[comps[2]] = {'node': comps[0], 'device': comps[1], 'fstype': comps[3], 'opts': curr_opts} else: ret[comps[2]] = {'node': comps[0], 'device': comps[1], 'fstype': comps[3]} return ret def _active_mounts_freebsd(ret): ''' List active mounts on FreeBSD systems ''' for line in __salt__['cmd.run_stdout']('mount -p').split('\n'): comps = re.sub(r"\s+", " ", line).split() ret[comps[1]] = {'device': comps[0], 'fstype': comps[2], 'opts': _resolve_user_group_names(comps[3].split(','))} return ret def _active_mounts_solaris(ret): ''' List active mounts on Solaris systems ''' for line in __salt__['cmd.run_stdout']('mount -v').split('\n'): comps = re.sub(r"\s+", " ", line).split() ret[comps[2]] = {'device': comps[0], 'fstype': comps[4], 'opts': _resolve_user_group_names(comps[5].split('/'))} return ret def _active_mounts_openbsd(ret): ''' List active mounts on OpenBSD systems ''' for line in __salt__['cmd.run_stdout']('mount -v').split('\n'): comps = re.sub(r"\s+", " ", line).split() parens = re.findall(r'\((.*?)\)', line, re.DOTALL) if len(parens) > 1: nod = __salt__['cmd.run_stdout']('ls -l {0}'.format(comps[0])) nod = ' '.join(nod.split()).split(" ") ret[comps[3]] = {'device': comps[0], 'fstype': comps[5], 'opts': _resolve_user_group_names(parens[1].split(", ")), 'major': six.text_type(nod[4].strip(",")), 'minor': six.text_type(nod[5]), 'device_uuid': parens[0]} else: ret[comps[2]] = {'device': comps[0], 'fstype': comps[4], 'opts': _resolve_user_group_names(parens[0].split(", "))} return ret def _active_mounts_darwin(ret): ''' List active mounts on Mac OS systems ''' for line in __salt__['cmd.run_stdout']('mount').split('\n'): comps = re.sub(r"\s+", " ", line).split() parens = re.findall(r'\((.*?)\)', line, re.DOTALL)[0].split(", ") ret[comps[2]] = {'device': comps[0], 'fstype': parens[0], 'opts': _resolve_user_group_names(parens[1:])} return ret def _resolve_user_group_names(opts): ''' Resolve user and group names in related opts ''' name_id_opts = {'uid': 'user.info', 'gid': 'group.info'} for ind, opt in enumerate(opts): if opt.split('=')[0] in name_id_opts: _givenid = opt.split('=')[1] _param = opt.split('=')[0] _id = _givenid if not re.match('[0-9]+$', _givenid): _info = __salt__[name_id_opts[_param]](_givenid) if _info and _param in _info: _id = _info[_param] opts[ind] = _param + '=' + six.text_type(_id) opts[ind] = opts[ind].replace('\\040', '\\ ') return opts def active(extended=False): ''' List the active mounts. CLI Example: .. code-block:: bash salt '*' mount.active ''' ret = {} if __grains__['os'] == 'FreeBSD': _active_mounts_freebsd(ret) elif 'AIX' in __grains__['kernel']: _active_mounts_aix(ret) elif __grains__['kernel'] == 'SunOS': _active_mounts_solaris(ret) elif __grains__['os'] == 'OpenBSD': _active_mounts_openbsd(ret) elif __grains__['os'] in ['MacOS', 'Darwin']: _active_mounts_darwin(ret) else: if extended: try: _active_mountinfo(ret) except CommandExecutionError: _active_mounts(ret) else: _active_mounts(ret) return ret class _fstab_entry(object): ''' Utility class for manipulating fstab entries. Primarily we're parsing, formatting, and comparing lines. Parsing emits dicts expected from fstab() or raises a ValueError. Note: We'll probably want to use os.normpath and os.normcase on 'name' ''' class ParseError(ValueError): ''' Error raised when a line isn't parsible as an fstab entry ''' fstab_keys = ('device', 'name', 'fstype', 'opts', 'dump', 'pass_num') # preserve data format compatibility_keys = ('device', 'name', 'fstype', 'opts', 'dump', 'pass') fstab_format = '{device}\t\t{name}\t{fstype}\t{opts}\t{dump} {pass_num}\n' @classmethod def dict_from_line(cls, line, keys=fstab_keys): if len(keys) != 6: raise ValueError('Invalid key array: {0}'.format(keys)) if line.startswith('#'): raise cls.ParseError("Comment!") comps = line.split() if len(comps) < 4 or len(comps) > 6: raise cls.ParseError("Invalid Entry!") comps.extend(['0'] * (len(keys) - len(comps))) return dict(zip(keys, comps)) @classmethod def from_line(cls, *args, **kwargs): return cls(** cls.dict_from_line(*args, **kwargs)) @classmethod def dict_to_line(cls, entry): return cls.fstab_format.format(**entry) def __str__(self): ''' String value, only works for full repr ''' return self.dict_to_line(self.criteria) def __repr__(self): ''' Always works ''' return repr(self.criteria) def pick(self, keys): ''' Returns an instance with just those keys ''' subset = dict([(key, self.criteria[key]) for key in keys]) return self.__class__(**subset) def __init__(self, **criteria): ''' Store non-empty, non-null values to use as filter ''' items = [key_value for key_value in six.iteritems(criteria) if key_value[1] is not None] items = [(key_value1[0], six.text_type(key_value1[1])) for key_value1 in items] self.criteria = dict(items) @staticmethod def norm_path(path): ''' Resolve equivalent paths equivalently ''' return os.path.normcase(os.path.normpath(path)) def match(self, line): ''' Compare potentially partial criteria against line ''' entry = self.dict_from_line(line) for key, value in six.iteritems(self.criteria): if entry[key] != value: return False return True class _vfstab_entry(object): ''' Utility class for manipulating vfstab entries. Primarily we're parsing, formatting, and comparing lines. Parsing emits dicts expected from fstab() or raises a ValueError. Note: We'll probably want to use os.normpath and os.normcase on 'name' Note: This parses vfstab entries on Solaris like systems #device device mount FS fsck mount mount #to mount to fsck point type pass at boot options # /devices - /devices devfs - no - ''' class ParseError(ValueError): '''Error raised when a line isn't parsible as an fstab entry''' vfstab_keys = ('device', 'device_fsck', 'name', 'fstype', 'pass_fsck', 'mount_at_boot', 'opts') # NOTE: weird formatting to match default spacing on Solaris vfstab_format = '{device:<11} {device_fsck:<3} {name:<19} {fstype:<8} {pass_fsck:<3} {mount_at_boot:<6} {opts}\n' @classmethod def dict_from_line(cls, line): if line.startswith('#'): raise cls.ParseError("Comment!") comps = line.split() if len(comps) != 7: raise cls.ParseError("Invalid Entry!") return dict(zip(cls.vfstab_keys, comps)) @classmethod def from_line(cls, *args, **kwargs): return cls(** cls.dict_from_line(*args, **kwargs)) @classmethod def dict_to_line(cls, entry): return cls.vfstab_format.format(**entry) def __str__(self): ''' String value, only works for full repr ''' return self.dict_to_line(self.criteria) def __repr__(self): ''' Always works ''' return repr(self.criteria) def pick(self, keys): ''' Returns an instance with just those keys ''' subset = dict([(key, self.criteria[key]) for key in keys]) return self.__class__(**subset) def __init__(self, **criteria): ''' Store non-empty, non-null values to use as filter ''' items = [key_value for key_value in six.iteritems(criteria) if key_value[1] is not None] items = [(key_value1[0], six.text_type(key_value1[1])) for key_value1 in items] self.criteria = dict(items) @staticmethod def norm_path(path): ''' Resolve equivalent paths equivalently ''' return os.path.normcase(os.path.normpath(path)) def match(self, line): ''' Compare potentially partial criteria against line ''' entry = self.dict_from_line(line) for key, value in six.iteritems(self.criteria): if entry[key] != value: return False return True class _FileSystemsEntry(object): ''' Utility class for manipulating filesystem entries. Primarily we're parsing, formatting, and comparing lines. Parsing emits dicts expected from fstab() or raises a ValueError. Note: We'll probably want to use os.normpath and os.normcase on 'name' ''' class ParseError(ValueError): ''' Error raised when a line isn't parsible as an fstab entry ''' filesystems_keys = ('device', 'name', 'fstype', 'vfstype', 'opts', 'mount') # preserve data format of filesystems compatibility_keys = ('dev', 'dev', 'name', 'fstype', 'vfstype', 'opts', 'mount', 'type', 'vfs', 'account', 'boot', 'check', 'free', 'nodename', 'quota', 'size', 'vol', 'log') @classmethod def dict_from_lines(cls, lines, keys=filesystems_keys): if len(lines) < 2: raise ValueError('Invalid number of lines: {0}'.format(lines)) if not keys: # if empty force default filesystems_keys keys = _FileSystemsEntry.filesystems_keys elif len(keys) < 6: raise ValueError('Invalid key name array: {0}'.format(keys)) blk_lines = lines orddict = OrderedDict() orddict['name'] = blk_lines[0].split(':')[0].strip() blk_lines.pop(0) for line in blk_lines: if line.startswith('#'): raise cls.ParseError("Comment!") comps = line.split('= ') if len(comps) != 2: raise cls.ParseError("Invalid Entry!") key_name = comps[0].strip() if key_name in keys: orddict[key_name] = comps[1].strip() else: raise ValueError('Invalid name for use in filesystems: {0}'.format(key_name)) return orddict @classmethod def dict_from_cmd_line(cls, ipargs, keys): cmdln_dict = ipargs if keys: for key, value in keys: # ignore unknown or local scope keys if key.startswith('__'): continue if key in _FileSystemsEntry.compatibility_keys: cmdln_dict[key] = value return cmdln_dict @classmethod def from_line(cls, *args, **kwargs): return cls(** cls.dict_from_cmd_line(*args, **kwargs)) @classmethod def dict_to_lines(cls, fsys_dict_entry): entry = fsys_dict_entry strg_out = entry['name'] + ':' + os.linesep for k, v in six.viewitems(entry): if 'name' not in k: strg_out += '\t{0}\t\t= {1}'.format(k, v) + os.linesep strg_out += os.linesep return six.text_type(strg_out) def dict_from_entry(self): ret = OrderedDict() ret[self.criteria['name']] = self.criteria return ret def __str__(self): ''' String value, only works for full repr ''' return self.dict_to_lines(self.criteria) def __repr__(self): ''' Always works ''' return repr(self.criteria) def pick(self, keys): ''' Returns an instance with just those keys ''' subset = dict([(key, self.criteria[key]) for key in keys]) return self.__class__(**subset) def __init__(self, **criteria): ''' Store non-empty, non-null values to use as filter ''' items = [key_value for key_value in six.iteritems(criteria) if key_value[1] is not None] items = [(key_value1[0], six.text_type(key_value1[1])) for key_value1 in items] self.criteria = OrderedDict(items) @staticmethod def norm_path(path): ''' Resolve equivalent paths equivalently ''' return os.path.normcase(os.path.normpath(path)) def match(self, fsys_view): ''' Compare potentially partial criteria against built filesystems entry dictionary ''' evalue_dict = fsys_view[1] for key, value in six.viewitems(self.criteria): if key in evalue_dict: if evalue_dict[key] != value: return False else: return False return True def __getitem__(self, key): ''' Return value for input key ''' return self.criteria[key] def fstab(config='/etc/fstab'): ''' .. versionchanged:: 2016.3.2 List the contents of the fstab CLI Example: .. code-block:: bash salt '*' mount.fstab ''' ret = {} if not os.path.isfile(config): return ret with salt.utils.files.fopen(config) as ifile: for line in ifile: line = salt.utils.stringutils.to_unicode(line) try: if __grains__['kernel'] == 'SunOS': # Note: comments use in default vfstab file! if line[0] == '#': continue entry = _vfstab_entry.dict_from_line( line) else: entry = _fstab_entry.dict_from_line( line, _fstab_entry.compatibility_keys) entry['opts'] = entry['opts'].split(',') while entry['name'] in ret: entry['name'] += '_' ret[entry.pop('name')] = entry except _fstab_entry.ParseError: pass except _vfstab_entry.ParseError: pass return ret def vfstab(config='/etc/vfstab'): ''' .. versionadded:: 2016.3.2 List the contents of the vfstab CLI Example: .. code-block:: bash salt '*' mount.vfstab ''' # NOTE: vfstab is a wrapper for fstab return fstab(config) def rm_fstab(name, device, config='/etc/fstab'): ''' .. versionchanged:: 2016.3.2 Remove the mount point from the fstab CLI Example: .. code-block:: bash salt '*' mount.rm_fstab /mnt/foo /dev/sdg ''' modified = False if __grains__['kernel'] == 'SunOS': criteria = _vfstab_entry(name=name, device=device) else: criteria = _fstab_entry(name=name, device=device) lines = [] try: with salt.utils.files.fopen(config, 'r') as ifile: for line in ifile: line = salt.utils.stringutils.to_unicode(line) try: if criteria.match(line): modified = True else: lines.append(line) except _fstab_entry.ParseError: lines.append(line) except _vfstab_entry.ParseError: lines.append(line) except (IOError, OSError) as exc: msg = "Couldn't read from {0}: {1}" raise CommandExecutionError(msg.format(config, exc)) if modified: try: with salt.utils.files.fopen(config, 'wb') as ofile: ofile.writelines(salt.utils.data.encode(lines)) except (IOError, OSError) as exc: msg = "Couldn't write to {0}: {1}" raise CommandExecutionError(msg.format(config, exc)) # Note: not clear why we always return 'True' # --just copying previous behavior at this point... return True def rm_vfstab(name, device, config='/etc/vfstab'): ''' .. versionadded:: 2016.3.2 Remove the mount point from the vfstab CLI Example: .. code-block:: bash salt '*' mount.rm_vfstab /mnt/foo /device/c0t0d0p0 ''' ## NOTE: rm_vfstab is a wrapper for rm_fstab return rm_fstab(name, device, config) def set_fstab( name, device, fstype, opts='defaults', dump=0, pass_num=0, config='/etc/fstab', test=False, match_on='auto', **kwargs): ''' Verify that this mount is represented in the fstab, change the mount to match the data passed, or add the mount if it is not present. CLI Example: .. code-block:: bash salt '*' mount.set_fstab /mnt/foo /dev/sdz1 ext4 ''' # Fix the opts type if it is a list if isinstance(opts, list): opts = ','.join(opts) # preserve arguments for updating entry_args = { 'name': name, 'device': device.replace('\\ ', '\\040'), 'fstype': fstype, 'opts': opts.replace('\\ ', '\\040'), 'dump': dump, 'pass_num': pass_num, } lines = [] ret = None # Transform match_on into list--items will be checked later if isinstance(match_on, list): pass elif not isinstance(match_on, six.string_types): msg = 'match_on must be a string or list of strings' raise CommandExecutionError(msg) elif match_on == 'auto': # Try to guess right criteria for auto.... # NOTE: missing some special fstypes here specialFSes = frozenset([ 'none', 'tmpfs', 'sysfs', 'proc', 'fusectl', 'debugfs', 'securityfs', 'devtmpfs', 'cgroup', 'btrfs']) if fstype in specialFSes: match_on = ['name'] else: match_on = ['device'] else: match_on = [match_on] # generate entry and criteria objects, handle invalid keys in match_on entry = _fstab_entry(**entry_args) try: criteria = entry.pick(match_on) except KeyError: filterFn = lambda key: key not in _fstab_entry.fstab_keys invalid_keys = filter(filterFn, match_on) msg = 'Unrecognized keys in match_on: "{0}"'.format(invalid_keys) raise CommandExecutionError(msg) # parse file, use ret to cache status if not os.path.isfile(config): raise CommandExecutionError('Bad config file "{0}"'.format(config)) try: with salt.utils.files.fopen(config, 'r') as ifile: for line in ifile: line = salt.utils.stringutils.to_unicode(line) try: if criteria.match(line): # Note: If ret isn't None here, # we've matched multiple lines ret = 'present' if entry.match(line): lines.append(line) else: ret = 'change' lines.append(six.text_type(entry)) else: lines.append(line) except _fstab_entry.ParseError: lines.append(line) except (IOError, OSError) as exc: msg = 'Couldn\'t read from {0}: {1}' raise CommandExecutionError(msg.format(config, exc)) # add line if not present or changed if ret is None: lines.append(six.text_type(entry)) ret = 'new' if ret != 'present': # ret in ['new', 'change']: if not salt.utils.args.test_mode(test=test, **kwargs): try: with salt.utils.files.fopen(config, 'wb') as ofile: # The line was changed, commit it! ofile.writelines(salt.utils.data.encode(lines)) except (IOError, OSError): msg = 'File not writable {0}' raise CommandExecutionError(msg.format(config)) return ret def set_vfstab( name, device, fstype, opts='-', device_fsck='-', pass_fsck='-', mount_at_boot='yes', config='/etc/vfstab', test=False, match_on='auto', **kwargs): ''' ..verionadded:: 2016.3.2 Verify that this mount is represented in the fstab, change the mount to match the data passed, or add the mount if it is not present. CLI Example: .. code-block:: bash salt '*' mount.set_vfstab /mnt/foo /device/c0t0d0p0 ufs ''' # Fix the opts type if it is a list if isinstance(opts, list): opts = ','.join(opts) # Map unknown values for mount_at_boot to no if mount_at_boot != 'yes': mount_at_boot = 'no' # preserve arguments for updating entry_args = { 'name': name, 'device': device, 'fstype': fstype, 'opts': opts, 'device_fsck': device_fsck, 'pass_fsck': pass_fsck, 'mount_at_boot': mount_at_boot, } lines = [] ret = None # Transform match_on into list--items will be checked later if isinstance(match_on, list): pass elif not isinstance(match_on, six.string_types): msg = 'match_on must be a string or list of strings' raise CommandExecutionError(msg) elif match_on == 'auto': # Try to guess right criteria for auto.... # NOTE: missing some special fstypes here specialFSes = frozenset([ 'devfs', 'proc', 'ctfs', 'objfs', 'sharefs', 'fs', 'tmpfs']) if fstype in specialFSes: match_on = ['name'] else: match_on = ['device'] else: match_on = [match_on] # generate entry and criteria objects, handle invalid keys in match_on entry = _vfstab_entry(**entry_args) try: criteria = entry.pick(match_on) except KeyError: filterFn = lambda key: key not in _vfstab_entry.vfstab_keys invalid_keys = filter(filterFn, match_on) msg = 'Unrecognized keys in match_on: "{0}"'.format(invalid_keys) raise CommandExecutionError(msg) # parse file, use ret to cache status if not os.path.isfile(config): raise CommandExecutionError('Bad config file "{0}"'.format(config)) try: with salt.utils.files.fopen(config, 'r') as ifile: for line in ifile: line = salt.utils.stringutils.to_unicode(line) try: if criteria.match(line): # Note: If ret isn't None here, # we've matched multiple lines ret = 'present' if entry.match(line): lines.append(line) else: ret = 'change' lines.append(six.text_type(entry)) else: lines.append(line) except _vfstab_entry.ParseError: lines.append(line) except (IOError, OSError) as exc: msg = 'Couldn\'t read from {0}: {1}' raise CommandExecutionError(msg.format(config, exc)) # add line if not present or changed if ret is None: lines.append(six.text_type(entry)) ret = 'new' if ret != 'present': # ret in ['new', 'change']: if not salt.utils.args.test_mode(test=test, **kwargs): try: with salt.utils.files.fopen(config, 'wb') as ofile: # The line was changed, commit it! ofile.writelines(salt.utils.data.encode(lines)) except (IOError, OSError): msg = 'File not writable {0}' raise CommandExecutionError(msg.format(config)) return ret def rm_automaster(name, device, config='/etc/auto_salt'): ''' Remove the mount point from the auto_master CLI Example: .. code-block:: bash salt '*' mount.rm_automaster /mnt/foo /dev/sdg ''' contents = automaster(config) if name not in contents: return True # The entry is present, get rid of it lines = [] try: with salt.utils.files.fopen(config, 'r') as ifile: for line in ifile: line = salt.utils.stringutils.to_unicode(line) if line.startswith('#'): # Commented lines.append(line) continue if not line.strip(): # Blank line lines.append(line) continue comps = line.split() if len(comps) != 3: # Invalid entry lines.append(line) continue comps = line.split() prefix = "/.." name_chk = comps[0].replace(prefix, "") device_fmt = comps[2].split(":") if device: if name_chk == name and device_fmt[1] == device: continue else: if name_chk == name: continue lines.append(line) except (IOError, OSError) as exc: msg = "Couldn't read from {0}: {1}" raise CommandExecutionError(msg.format(config, exc)) try: with salt.utils.files.fopen(config, 'wb') as ofile: ofile.writelines(salt.utils.data.encode(lines)) except (IOError, OSError) as exc: msg = "Couldn't write to {0}: {1}" raise CommandExecutionError(msg.format(config, exc)) # Update automount __salt__['cmd.run']('automount -cv') return True def set_automaster( name, device, fstype, opts='', config='/etc/auto_salt', test=False, **kwargs): ''' Verify that this mount is represented in the auto_salt, change the mount to match the data passed, or add the mount if it is not present. CLI Example: .. code-block:: bash salt '*' mount.set_automaster /mnt/foo /dev/sdz1 ext4 ''' # Fix the opts type if it is a list if isinstance(opts, list): opts = ','.join(opts) lines = [] change = False present = False automaster_file = "/etc/auto_master" if not os.path.isfile(config): __salt__['file.touch'](config) __salt__['file.append'](automaster_file, "/-\t\t\t{0}".format(config)) name = "/..{0}".format(name) device_fmt = "{0}:{1}".format(fstype, device) type_opts = "-fstype={0},{1}".format(fstype, opts) if fstype == 'smbfs': device_fmt = device_fmt.replace(fstype, "") try: with salt.utils.files.fopen(config, 'r') as ifile: for line in ifile: line = salt.utils.stringutils.to_unicode(line) if line.startswith('#'): # Commented lines.append(line) continue if not line.strip(): # Blank line lines.append(line) continue comps = line.split() if len(comps) != 3: # Invalid entry lines.append(line) continue if comps[0] == name or comps[2] == device_fmt: # check to see if there are changes # and fix them if there are any present = True if comps[0] != name: change = True comps[0] = name if comps[1] != type_opts: change = True comps[1] = type_opts if comps[2] != device_fmt: change = True comps[2] = device_fmt if change: log.debug( 'auto_master entry for mount point %s needs to be ' 'updated', name ) newline = ( '{0}\t{1}\t{2}\n'.format( name, type_opts, device_fmt) ) lines.append(newline) else: lines.append(line) except (IOError, OSError) as exc: msg = 'Couldn\'t read from {0}: {1}' raise CommandExecutionError(msg.format(config, exc)) if change: if not salt.utils.args.test_mode(test=test, **kwargs): try: with salt.utils.files.fopen(config, 'wb') as ofile: # The line was changed, commit it! ofile.writelines(salt.utils.data.encode(lines)) except (IOError, OSError): msg = 'File not writable {0}' raise CommandExecutionError(msg.format(config)) return 'change' if not change: if present: # The right entry is already here return 'present' else: if not salt.utils.args.test_mode(test=test, **kwargs): # The entry is new, add it to the end of the fstab newline = ( '{0}\t{1}\t{2}\n'.format( name, type_opts, device_fmt) ) lines.append(newline) try: with salt.utils.files.fopen(config, 'wb') as ofile: # The line was changed, commit it! ofile.writelines(salt.utils.data.encode(lines)) except (IOError, OSError): raise CommandExecutionError( 'File not writable {0}'.format( config ) ) return 'new' def automaster(config='/etc/auto_salt'): ''' List the contents of the auto master CLI Example: .. code-block:: bash salt '*' mount.automaster ''' ret = {} if not os.path.isfile(config): return ret with salt.utils.files.fopen(config) as ifile: for line in ifile: line = salt.utils.stringutils.to_unicode(line) if line.startswith('#'): # Commented continue if not line.strip(): # Blank line continue comps = line.split() if len(comps) != 3: # Invalid entry continue prefix = "/.." name = comps[0].replace(prefix, "") device_fmt = comps[2].split(":") opts = comps[1].split(',') ret[name] = {'device': device_fmt[1], 'fstype': opts[0], 'opts': opts[1:]} return ret def mount(name, device, mkmnt=False, fstype='', opts='defaults', user=None, util='mount'): ''' Mount a device CLI Example: .. code-block:: bash salt '*' mount.mount /mnt/foo /dev/sdz1 True ''' if util != 'mount': # This functionality used to live in img.mount_image if util == 'guestfs': return __salt__['guestfs.mount'](name, root=device) elif util == 'qemu_nbd': mnt = __salt__['qemu_nbd.init'](name, device) if not mnt: return False first = next(six.iterkeys(mnt)) __context__['img.mnt_{0}'.format(first)] = mnt return first return False # Darwin doesn't expect defaults when mounting without other options if 'defaults' in opts and __grains__['os'] in ['MacOS', 'Darwin', 'AIX']: opts = None if isinstance(opts, six.string_types): opts = opts.split(',') if not os.path.exists(name) and mkmnt: __salt__['file.mkdir'](name, user=user) args = '' if opts is not None: lopts = ','.join(opts) args = '-o {0}'.format(lopts) if fstype: # use of fstype on AIX differs from typical Linux use of -t # functionality AIX uses -v vfsname, -t fstype mounts all with # fstype in /etc/filesystems if 'AIX' in __grains__['os']: args += ' -v {0}'.format(fstype) elif 'solaris' in __grains__['os'].lower(): args += ' -F {0}'.format(fstype) else: args += ' -t {0}'.format(fstype) cmd = 'mount {0} {1} {2} '.format(args, device, name) out = __salt__['cmd.run_all'](cmd, runas=user, python_shell=False) if out['retcode']: return out['stderr'] return True def remount(name, device, mkmnt=False, fstype='', opts='defaults', user=None): ''' Attempt to remount a device, if the device is not already mounted, mount is called CLI Example: .. code-block:: bash salt '*' mount.remount /mnt/foo /dev/sdz1 True ''' force_mount = False if __grains__['os'] in ['MacOS', 'Darwin']: if opts == 'defaults': opts = 'noowners' if fstype == 'smbfs': force_mount = True if 'AIX' in __grains__['os']: if opts == 'defaults': opts = [] if isinstance(opts, six.string_types): opts = opts.split(',') mnts = active() if name in mnts: # The mount point is mounted, attempt to remount it with the given data if 'remount' not in opts and __grains__['os'] not in ['OpenBSD', 'MacOS', 'Darwin']: opts.append('remount') if force_mount: # We need to force the mount but first we should unmount umount(name, device, user=user) lopts = ','.join(opts) args = '-o {0}'.format(lopts) if fstype: # use of fstype on AIX differs from typical Linux use of # -t functionality AIX uses -v vfsname, -t fstype mounts # all with fstype in /etc/filesystems if 'AIX' in __grains__['os']: args += ' -v {0}'.format(fstype) elif 'solaris' in __grains__['os'].lower(): args += ' -F {0}'.format(fstype) else: args += ' -t {0}'.format(fstype) if __grains__['os'] not in ['OpenBSD', 'MacOS', 'Darwin'] or force_mount: cmd = 'mount {0} {1} {2} '.format(args, device, name) else: cmd = 'mount -u {0} {1} {2} '.format(args, device, name) out = __salt__['cmd.run_all'](cmd, runas=user, python_shell=False) if out['retcode']: return out['stderr'] return True # Mount a filesystem that isn't already return mount(name, device, mkmnt, fstype, opts, user=user) def umount(name, device=None, user=None, util='mount'): ''' Attempt to unmount a device by specifying the directory it is mounted on CLI Example: .. code-block:: bash salt '*' mount.umount /mnt/foo .. versionadded:: 2015.5.0 .. code-block:: bash salt '*' mount.umount /mnt/foo /dev/xvdc1 ''' if util != 'mount': # This functionality used to live in img.umount_image if 'qemu_nbd.clear' in __salt__: if 'img.mnt_{0}'.format(name) in __context__: __salt__['qemu_nbd.clear'](__context__['img.mnt_{0}'.format(name)]) return mnts = active() if name not in mnts: return "{0} does not have anything mounted".format(name) if not device: cmd = 'umount {0}'.format(name) else: cmd = 'umount {0}'.format(device) out = __salt__['cmd.run_all'](cmd, runas=user, python_shell=False) if out['retcode']: return out['stderr'] return True def is_fuse_exec(cmd): ''' Returns true if the command passed is a fuse mountable application. CLI Example: .. code-block:: bash salt '*' mount.is_fuse_exec sshfs ''' cmd_path = salt.utils.path.which(cmd) # No point in running ldd on a command that doesn't exist if not cmd_path: return False elif not salt.utils.path.which('ldd'): raise CommandNotFoundError('ldd') out = __salt__['cmd.run']('ldd {0}'.format(cmd_path), python_shell=False) return 'libfuse' in out def swaps(): ''' Return a dict containing information on active swap .. versionchanged:: 2016.3.2 CLI Example: .. code-block:: bash salt '*' mount.swaps ''' ret = {} if __grains__['kernel'] == 'SunOS': for line in __salt__['cmd.run_stdout']('swap -l').splitlines(): if line.startswith('swapfile'): continue comps = line.split() ret[comps[0]] = {'type': 'device' if comps[0].startswith(('/dev', 'swap')) else 'file', 'size': int(comps[3]), 'used': (int(comps[3]) - int(comps[4])), 'priority': '-'} elif 'AIX' in __grains__['kernel']: for line in __salt__['cmd.run_stdout']('swap -l').splitlines(): if line.startswith('device'): continue comps = line.split() # AIX uses MB for units ret[comps[0]] = {'type': 'device', 'size': int(comps[3][:-2]) * 1024, 'used': (int(comps[3][:-2]) - int(comps[4][:-2])) * 1024, 'priority': '-'} elif __grains__['os'] != 'OpenBSD': with salt.utils.files.fopen('/proc/swaps') as fp_: for line in fp_: line = salt.utils.stringutils.to_unicode(line) if line.startswith('Filename'): continue comps = line.split() ret[comps[0]] = {'type': comps[1], 'size': comps[2], 'used': comps[3], 'priority': comps[4]} else: for line in __salt__['cmd.run_stdout']('swapctl -kl').splitlines(): if line.startswith(('Device', 'Total')): continue swap_type = "file" comps = line.split() if comps[0].startswith('/dev/'): swap_type = "partition" ret[comps[0]] = {'type': swap_type, 'size': comps[1], 'used': comps[2], 'priority': comps[5]} return ret def swapon(name, priority=None): ''' Activate a swap disk .. versionchanged:: 2016.3.2 CLI Example: .. code-block:: bash salt '*' mount.swapon /root/swapfile ''' ret = {} on_ = swaps() if name in on_: ret['stats'] = on_[name] ret['new'] = False return ret if __grains__['kernel'] == 'SunOS': if __grains__['virtual'] != 'zone': __salt__['cmd.run']('swap -a {0}'.format(name), python_shell=False) else: return False else: cmd = 'swapon {0}'.format(name) if priority and 'AIX' not in __grains__['kernel']: cmd += ' -p {0}'.format(priority) __salt__['cmd.run'](cmd, python_shell=False) on_ = swaps() if name in on_: ret['stats'] = on_[name] ret['new'] = True return ret return ret def swapoff(name): ''' Deactivate a named swap mount .. versionchanged:: 2016.3.2 CLI Example: .. code-block:: bash salt '*' mount.swapoff /root/swapfile ''' on_ = swaps() if name in on_: if __grains__['kernel'] == 'SunOS': if __grains__['virtual'] != 'zone': __salt__['cmd.run']('swap -a {0}'.format(name), python_shell=False) else: return False elif __grains__['os'] != 'OpenBSD': __salt__['cmd.run']('swapoff {0}'.format(name), python_shell=False) else: __salt__['cmd.run']('swapctl -d {0}'.format(name), python_shell=False) on_ = swaps() if name in on_: return False return True return None def is_mounted(name): ''' .. versionadded:: 2014.7.0 Provide information if the path is mounted CLI Example: .. code-block:: bash salt '*' mount.is_mounted /mnt/share ''' active_ = active() if name in active_: return True else: return False def write_mount_cache(real_name, device, mkmnt, fstype, mount_opts): ''' .. versionadded:: 2018.3.0 Provide information if the path is mounted :param real_name: The real name of the mount point where the device is mounted. :param device: The device that is being mounted. :param mkmnt: Whether or not the mount point should be created. :param fstype: The file system that is used. :param mount_opts: Additional options used when mounting the device. :return: Boolean if message was sent successfully. CLI Example: .. code-block:: bash salt '*' mount.write_mount_cache /mnt/share /dev/sda1 False ext4 defaults,nosuid ''' cache = salt.utils.mount.read_cache(__opts__) if not cache: cache = {} cache['mounts'] = {} else: if 'mounts' not in cache: cache['mounts'] = {} cache['mounts'][real_name] = {'device': device, 'fstype': fstype, 'mkmnt': mkmnt, 'opts': mount_opts} cache_write = salt.utils.mount.write_cache(cache, __opts__) if cache_write: return True else: raise CommandExecutionError('Unable to write mount cache.') def delete_mount_cache(real_name): ''' .. versionadded:: 2018.3.0 Provide information if the path is mounted CLI Example: .. code-block:: bash salt '*' mount.delete_mount_cache /mnt/share ''' cache = salt.utils.mount.read_cache(__opts__) if cache: if 'mounts' in cache: if real_name in cache['mounts']: del cache['mounts'][real_name] cache_write = salt.utils.mount.write_cache(cache, __opts__) if not cache_write: raise CommandExecutionError('Unable to write mount cache.') return True def _filesystems(config='/etc/filesystems', leading_key=True): ''' Return the contents of the filesystems in an OrderedDict config File containing filesystem infomation leading_key True return dictionary keyed by 'name' and value as dictionary with other keys, values (name excluded) OrderedDict({ '/dir' : OrderedDict({'dev': '/dev/hd8', .... }})) False return dictionary keyed by 'name' and value as dictionary with all keys, values (name included) OrderedDict({ '/dir' : OrderedDict({'name': '/dir', 'dev': '/dev/hd8', ... })}) ''' ret = OrderedDict() lines = [] parsing_block = False if not os.path.isfile(config) or 'AIX' not in __grains__['kernel']: return ret # read in block of filesystems, block starts with '/' till empty line with salt.utils.files.fopen(config) as ifile: for line in ifile: line = salt.utils.stringutils.to_unicode(line) # skip till first entry if not line.startswith('/') and not parsing_block: continue if line.startswith('/'): parsing_block = True lines.append(line) elif not line.split(): parsing_block = False try: entry = _FileSystemsEntry.dict_from_lines( lines, _FileSystemsEntry.compatibility_keys) lines = [] if 'opts' in entry: entry['opts'] = entry['opts'].split(',') while entry['name'] in ret: entry['name'] += '_' if leading_key: ret[entry.pop('name')] = entry else: ret[entry['name']] = entry except _FileSystemsEntry.ParseError: pass else: lines.append(line) return ret def filesystems(config='/etc/filesystems'): ''' .. versionadded:: 2018.3.3 List the contents of the filesystems CLI Example: .. code-block:: bash salt '*' mount.filesystems ''' ret = {} if 'AIX' not in __grains__['kernel']: return ret ret_dict = _filesystems(config) if ret_dict: ret_key = next(iter(ret_dict.keys())) ret = {ret_key: dict(ret_dict[ret_key])} return ret def set_filesystems( name, device, vfstype, opts='-', mount='true', config='/etc/filesystems', test=False, match_on='auto', **kwargs): ''' .. versionadded:: 2018.3.3 Verify that this mount is represented in the filesystems, change the mount to match the data passed, or add the mount if it is not present on AIX Provide information if the path is mounted :param name: The name of the mount point where the device is mounted. :param device: The device that is being mounted. :param vfstype: The file system that is used (AIX has two fstypes, fstype and vfstype - similar to Linux fstype) :param opts: Additional options used when mounting the device. :param mount: Mount if not mounted, default True. :param config: Configuration file, default /etc/filesystems. :param match: File systems type to match on, default auto CLI Example: .. code-block:: bash salt '*' mount.set_filesystems /mnt/foo /dev/sdz1 jfs2 ''' # Fix the opts type if it is a list if isinstance(opts, list): opts = ','.join(opts) # preserve arguments for updating entry_args = { 'name': name, 'dev': device.replace('\\ ', '\\040'), 'vfstype': vfstype, 'opts': opts, 'mount': mount, } view_lines = [] ret = None if 'AIX' not in __grains__['kernel']: return ret # Transform match_on into list--items will be checked later if isinstance(match_on, list): pass elif not isinstance(match_on, six.string_types): raise CommandExecutionError('match_on must be a string or list of strings') elif match_on == 'auto': # Try to guess right criteria for auto.... # added IBM types from sys/vmount.h after btrfs # NOTE: missing some special fstypes here specialFSes = frozenset([ 'none', 'tmpfs', 'sysfs', 'proc', 'fusectl', 'debugfs', 'securityfs', 'devtmpfs', 'cgroup', 'btrfs', 'cdrfs', 'procfs', 'jfs', 'jfs2', 'nfs', 'sfs', 'nfs3', 'cachefs', 'udfs', 'cifs', 'namefs', 'pmemfs', 'ahafs', 'nfs4', 'autofs', 'stnfs']) if vfstype in specialFSes: match_on = ['name'] else: match_on = ['dev'] else: match_on = [match_on] # generate entry and criteria objects, handle invalid keys in match_on entry_ip = _FileSystemsEntry.from_line(entry_args, kwargs) try: criteria = entry_ip.pick(match_on) except KeyError: filterFn = lambda key: key not in _FileSystemsEntry.compatibility_keys invalid_keys = filter(filterFn, match_on) raise CommandExecutionError('Unrecognized keys in match_on: "{0}"'.format(invalid_keys)) # parse file, use ret to cache status if not os.path.isfile(config): raise CommandExecutionError('Bad config file "{0}"'.format(config)) # read in block of filesystem, block starts with '/' till empty line try: fsys_filedict = _filesystems(config, False) for fsys_view in six.viewitems(fsys_filedict): if criteria.match(fsys_view): ret = 'present' if entry_ip.match(fsys_view): view_lines.append(fsys_view) else: ret = 'change' kv = entry_ip['name'] view_lines.append((kv, entry_ip)) else: view_lines.append(fsys_view) except (IOError, OSError) as exc: raise CommandExecutionError('Couldn\'t read from {0}: {1}'.format(config, exc)) # add line if not present or changed if ret is None: for dict_view in six.viewitems(entry_ip.dict_from_entry()): view_lines.append(dict_view) ret = 'new' if ret != 'present': # ret in ['new', 'change']: try: with salt.utils.files.fopen(config, 'wb') as ofile: # The line was changed, commit it! for fsys_view in view_lines: entry = fsys_view[1] mystrg = _FileSystemsEntry.dict_to_lines(entry) ofile.writelines(salt.utils.data.encode(mystrg)) except (IOError, OSError): raise CommandExecutionError('File not writable {0}'.format(config)) return ret def rm_filesystems(name, device, config='/etc/filesystems'): ''' .. versionadded:: 2018.3.3 Remove the mount point from the filesystems CLI Example: .. code-block:: bash salt '*' mount.rm_filesystems /mnt/foo /dev/sdg ''' modified = False view_lines = [] if 'AIX' not in __grains__['kernel']: return modified criteria = _FileSystemsEntry(name=name, dev=device) try: fsys_filedict = _filesystems(config, False) for fsys_view in six.viewitems(fsys_filedict): try: if criteria.match(fsys_view): modified = True else: view_lines.append(fsys_view) except _FileSystemsEntry.ParseError: view_lines.append(fsys_view) except (IOError, OSError) as exc: raise CommandExecutionError("Couldn't read from {0}: {1}".format(config, exc)) if modified: try: with salt.utils.files.fopen(config, 'wb') as ofile: for fsys_view in view_lines: entry = fsys_view[1] mystrg = _FileSystemsEntry.dict_to_lines(entry) ofile.writelines(salt.utils.data.encode(mystrg)) except (IOError, OSError) as exc: raise CommandExecutionError("Couldn't write to {0}: {1}".format(config, exc)) return modified
saltstack/salt
salt/modules/mount.py
write_mount_cache
python
def write_mount_cache(real_name, device, mkmnt, fstype, mount_opts): ''' .. versionadded:: 2018.3.0 Provide information if the path is mounted :param real_name: The real name of the mount point where the device is mounted. :param device: The device that is being mounted. :param mkmnt: Whether or not the mount point should be created. :param fstype: The file system that is used. :param mount_opts: Additional options used when mounting the device. :return: Boolean if message was sent successfully. CLI Example: .. code-block:: bash salt '*' mount.write_mount_cache /mnt/share /dev/sda1 False ext4 defaults,nosuid ''' cache = salt.utils.mount.read_cache(__opts__) if not cache: cache = {} cache['mounts'] = {} else: if 'mounts' not in cache: cache['mounts'] = {} cache['mounts'][real_name] = {'device': device, 'fstype': fstype, 'mkmnt': mkmnt, 'opts': mount_opts} cache_write = salt.utils.mount.write_cache(cache, __opts__) if cache_write: return True else: raise CommandExecutionError('Unable to write mount cache.')
.. versionadded:: 2018.3.0 Provide information if the path is mounted :param real_name: The real name of the mount point where the device is mounted. :param device: The device that is being mounted. :param mkmnt: Whether or not the mount point should be created. :param fstype: The file system that is used. :param mount_opts: Additional options used when mounting the device. :return: Boolean if message was sent successfully. CLI Example: .. code-block:: bash salt '*' mount.write_mount_cache /mnt/share /dev/sda1 False ext4 defaults,nosuid
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/mount.py#L1517-L1558
[ "def read_cache(opts):\n '''\n Write the mount cache file.\n '''\n cache_file = get_cache(opts)\n return _read_file(cache_file)\n", "def write_cache(cache, opts):\n '''\n Write the mount cache file.\n '''\n cache_file = get_cache(opts)\n\n try:\n _cache = salt.utils.stringutils.to_bytes(\n salt.utils.yaml.safe_dump(cache)\n )\n with salt.utils.files.fopen(cache_file, 'wb+') as fp_:\n fp_.write(_cache)\n return True\n except (IOError, OSError):\n log.error('Failed to cache mounts',\n exc_info_on_loglevel=logging.DEBUG)\n return False\n" ]
# -*- coding: utf-8 -*- ''' Salt module to manage Unix mounts and the fstab file ''' # Import python libs from __future__ import absolute_import, print_function, unicode_literals import os import re import logging # Import salt libs import salt.utils.args import salt.utils.data import salt.utils.files import salt.utils.path import salt.utils.platform import salt.utils.mount import salt.utils.stringutils from salt.utils.odict import OrderedDict from salt.exceptions import CommandNotFoundError, CommandExecutionError # Import 3rd-party libs from salt.ext import six from salt.ext.six.moves import filter, zip # pylint: disable=import-error,redefined-builtin # Set up logger log = logging.getLogger(__name__) # Define the module's virtual name __virtualname__ = 'mount' def __virtual__(): ''' Only load on POSIX-like systems ''' # Disable on Windows, a specific file module exists: if salt.utils.platform.is_windows(): return (False, 'The mount module cannot be loaded: not a POSIX-like system.') return True def _list_mounts(): ret = {} if __grains__['os'] in ['MacOS', 'Darwin']: mounts = __salt__['cmd.run_stdout']('mount') else: mounts = __salt__['cmd.run_stdout']('mount -l') for line in mounts.split('\n'): comps = re.sub(r"\s+", " ", line).split() if len(comps) >= 3: ret[comps[2]] = comps[0] return ret def _active_mountinfo(ret): _list = _list_mounts() filename = '/proc/self/mountinfo' if not os.access(filename, os.R_OK): msg = 'File not readable {0}' raise CommandExecutionError(msg.format(filename)) if 'disk.blkid' not in __context__: __context__['disk.blkid'] = __salt__['disk.blkid']() blkid_info = __context__['disk.blkid'] with salt.utils.files.fopen(filename) as ifile: for line in ifile: comps = salt.utils.stringutils.to_unicode(line).split() device = comps[2].split(':') # each line can have any number of # optional parameters, we use the # location of the separator field to # determine the location of the elements # after it. _sep = comps.index('-') device_name = comps[_sep + 2] device_uuid = None device_label = None if device_name: device_uuid = blkid_info.get(device_name, {}).get('UUID') device_uuid = device_uuid and device_uuid.lower() device_label = blkid_info.get(device_name, {}).get('LABEL') ret[comps[4]] = {'mountid': comps[0], 'parentid': comps[1], 'major': device[0], 'minor': device[1], 'root': comps[3], 'opts': _resolve_user_group_names(comps[5].split(',')), 'fstype': comps[_sep + 1], 'device': device_name.replace('\\040', '\\ '), 'alt_device': _list.get(comps[4], None), 'superopts': _resolve_user_group_names(comps[_sep + 3].split(',')), 'device_uuid': device_uuid, 'device_label': device_label} return ret def _active_mounts(ret): ''' List active mounts on Linux systems ''' _list = _list_mounts() filename = '/proc/self/mounts' if not os.access(filename, os.R_OK): msg = 'File not readable {0}' raise CommandExecutionError(msg.format(filename)) with salt.utils.files.fopen(filename) as ifile: for line in ifile: comps = salt.utils.stringutils.to_unicode(line).split() ret[comps[1]] = {'device': comps[0], 'alt_device': _list.get(comps[1], None), 'fstype': comps[2], 'opts': _resolve_user_group_names(comps[3].split(','))} return ret def _active_mounts_aix(ret): ''' List active mounts on AIX systems ''' for line in __salt__['cmd.run_stdout']('mount -p').split('\n'): comps = re.sub(r"\s+", " ", line).split() if comps: if comps[0] == 'node' or comps[0] == '--------': continue comps_len = len(comps) if line.startswith((' ', '\t')): curr_opts = _resolve_user_group_names(comps[6].split(',')) if 7 == comps_len else [] if curr_opts: ret[comps[1]] = {'device': comps[0], 'fstype': comps[2], 'opts': curr_opts} else: ret[comps[1]] = {'device': comps[0], 'fstype': comps[2]} else: curr_opts = _resolve_user_group_names(comps[7].split(',')) if 8 == comps_len else [] if curr_opts: ret[comps[2]] = {'node': comps[0], 'device': comps[1], 'fstype': comps[3], 'opts': curr_opts} else: ret[comps[2]] = {'node': comps[0], 'device': comps[1], 'fstype': comps[3]} return ret def _active_mounts_freebsd(ret): ''' List active mounts on FreeBSD systems ''' for line in __salt__['cmd.run_stdout']('mount -p').split('\n'): comps = re.sub(r"\s+", " ", line).split() ret[comps[1]] = {'device': comps[0], 'fstype': comps[2], 'opts': _resolve_user_group_names(comps[3].split(','))} return ret def _active_mounts_solaris(ret): ''' List active mounts on Solaris systems ''' for line in __salt__['cmd.run_stdout']('mount -v').split('\n'): comps = re.sub(r"\s+", " ", line).split() ret[comps[2]] = {'device': comps[0], 'fstype': comps[4], 'opts': _resolve_user_group_names(comps[5].split('/'))} return ret def _active_mounts_openbsd(ret): ''' List active mounts on OpenBSD systems ''' for line in __salt__['cmd.run_stdout']('mount -v').split('\n'): comps = re.sub(r"\s+", " ", line).split() parens = re.findall(r'\((.*?)\)', line, re.DOTALL) if len(parens) > 1: nod = __salt__['cmd.run_stdout']('ls -l {0}'.format(comps[0])) nod = ' '.join(nod.split()).split(" ") ret[comps[3]] = {'device': comps[0], 'fstype': comps[5], 'opts': _resolve_user_group_names(parens[1].split(", ")), 'major': six.text_type(nod[4].strip(",")), 'minor': six.text_type(nod[5]), 'device_uuid': parens[0]} else: ret[comps[2]] = {'device': comps[0], 'fstype': comps[4], 'opts': _resolve_user_group_names(parens[0].split(", "))} return ret def _active_mounts_darwin(ret): ''' List active mounts on Mac OS systems ''' for line in __salt__['cmd.run_stdout']('mount').split('\n'): comps = re.sub(r"\s+", " ", line).split() parens = re.findall(r'\((.*?)\)', line, re.DOTALL)[0].split(", ") ret[comps[2]] = {'device': comps[0], 'fstype': parens[0], 'opts': _resolve_user_group_names(parens[1:])} return ret def _resolve_user_group_names(opts): ''' Resolve user and group names in related opts ''' name_id_opts = {'uid': 'user.info', 'gid': 'group.info'} for ind, opt in enumerate(opts): if opt.split('=')[0] in name_id_opts: _givenid = opt.split('=')[1] _param = opt.split('=')[0] _id = _givenid if not re.match('[0-9]+$', _givenid): _info = __salt__[name_id_opts[_param]](_givenid) if _info and _param in _info: _id = _info[_param] opts[ind] = _param + '=' + six.text_type(_id) opts[ind] = opts[ind].replace('\\040', '\\ ') return opts def active(extended=False): ''' List the active mounts. CLI Example: .. code-block:: bash salt '*' mount.active ''' ret = {} if __grains__['os'] == 'FreeBSD': _active_mounts_freebsd(ret) elif 'AIX' in __grains__['kernel']: _active_mounts_aix(ret) elif __grains__['kernel'] == 'SunOS': _active_mounts_solaris(ret) elif __grains__['os'] == 'OpenBSD': _active_mounts_openbsd(ret) elif __grains__['os'] in ['MacOS', 'Darwin']: _active_mounts_darwin(ret) else: if extended: try: _active_mountinfo(ret) except CommandExecutionError: _active_mounts(ret) else: _active_mounts(ret) return ret class _fstab_entry(object): ''' Utility class for manipulating fstab entries. Primarily we're parsing, formatting, and comparing lines. Parsing emits dicts expected from fstab() or raises a ValueError. Note: We'll probably want to use os.normpath and os.normcase on 'name' ''' class ParseError(ValueError): ''' Error raised when a line isn't parsible as an fstab entry ''' fstab_keys = ('device', 'name', 'fstype', 'opts', 'dump', 'pass_num') # preserve data format compatibility_keys = ('device', 'name', 'fstype', 'opts', 'dump', 'pass') fstab_format = '{device}\t\t{name}\t{fstype}\t{opts}\t{dump} {pass_num}\n' @classmethod def dict_from_line(cls, line, keys=fstab_keys): if len(keys) != 6: raise ValueError('Invalid key array: {0}'.format(keys)) if line.startswith('#'): raise cls.ParseError("Comment!") comps = line.split() if len(comps) < 4 or len(comps) > 6: raise cls.ParseError("Invalid Entry!") comps.extend(['0'] * (len(keys) - len(comps))) return dict(zip(keys, comps)) @classmethod def from_line(cls, *args, **kwargs): return cls(** cls.dict_from_line(*args, **kwargs)) @classmethod def dict_to_line(cls, entry): return cls.fstab_format.format(**entry) def __str__(self): ''' String value, only works for full repr ''' return self.dict_to_line(self.criteria) def __repr__(self): ''' Always works ''' return repr(self.criteria) def pick(self, keys): ''' Returns an instance with just those keys ''' subset = dict([(key, self.criteria[key]) for key in keys]) return self.__class__(**subset) def __init__(self, **criteria): ''' Store non-empty, non-null values to use as filter ''' items = [key_value for key_value in six.iteritems(criteria) if key_value[1] is not None] items = [(key_value1[0], six.text_type(key_value1[1])) for key_value1 in items] self.criteria = dict(items) @staticmethod def norm_path(path): ''' Resolve equivalent paths equivalently ''' return os.path.normcase(os.path.normpath(path)) def match(self, line): ''' Compare potentially partial criteria against line ''' entry = self.dict_from_line(line) for key, value in six.iteritems(self.criteria): if entry[key] != value: return False return True class _vfstab_entry(object): ''' Utility class for manipulating vfstab entries. Primarily we're parsing, formatting, and comparing lines. Parsing emits dicts expected from fstab() or raises a ValueError. Note: We'll probably want to use os.normpath and os.normcase on 'name' Note: This parses vfstab entries on Solaris like systems #device device mount FS fsck mount mount #to mount to fsck point type pass at boot options # /devices - /devices devfs - no - ''' class ParseError(ValueError): '''Error raised when a line isn't parsible as an fstab entry''' vfstab_keys = ('device', 'device_fsck', 'name', 'fstype', 'pass_fsck', 'mount_at_boot', 'opts') # NOTE: weird formatting to match default spacing on Solaris vfstab_format = '{device:<11} {device_fsck:<3} {name:<19} {fstype:<8} {pass_fsck:<3} {mount_at_boot:<6} {opts}\n' @classmethod def dict_from_line(cls, line): if line.startswith('#'): raise cls.ParseError("Comment!") comps = line.split() if len(comps) != 7: raise cls.ParseError("Invalid Entry!") return dict(zip(cls.vfstab_keys, comps)) @classmethod def from_line(cls, *args, **kwargs): return cls(** cls.dict_from_line(*args, **kwargs)) @classmethod def dict_to_line(cls, entry): return cls.vfstab_format.format(**entry) def __str__(self): ''' String value, only works for full repr ''' return self.dict_to_line(self.criteria) def __repr__(self): ''' Always works ''' return repr(self.criteria) def pick(self, keys): ''' Returns an instance with just those keys ''' subset = dict([(key, self.criteria[key]) for key in keys]) return self.__class__(**subset) def __init__(self, **criteria): ''' Store non-empty, non-null values to use as filter ''' items = [key_value for key_value in six.iteritems(criteria) if key_value[1] is not None] items = [(key_value1[0], six.text_type(key_value1[1])) for key_value1 in items] self.criteria = dict(items) @staticmethod def norm_path(path): ''' Resolve equivalent paths equivalently ''' return os.path.normcase(os.path.normpath(path)) def match(self, line): ''' Compare potentially partial criteria against line ''' entry = self.dict_from_line(line) for key, value in six.iteritems(self.criteria): if entry[key] != value: return False return True class _FileSystemsEntry(object): ''' Utility class for manipulating filesystem entries. Primarily we're parsing, formatting, and comparing lines. Parsing emits dicts expected from fstab() or raises a ValueError. Note: We'll probably want to use os.normpath and os.normcase on 'name' ''' class ParseError(ValueError): ''' Error raised when a line isn't parsible as an fstab entry ''' filesystems_keys = ('device', 'name', 'fstype', 'vfstype', 'opts', 'mount') # preserve data format of filesystems compatibility_keys = ('dev', 'dev', 'name', 'fstype', 'vfstype', 'opts', 'mount', 'type', 'vfs', 'account', 'boot', 'check', 'free', 'nodename', 'quota', 'size', 'vol', 'log') @classmethod def dict_from_lines(cls, lines, keys=filesystems_keys): if len(lines) < 2: raise ValueError('Invalid number of lines: {0}'.format(lines)) if not keys: # if empty force default filesystems_keys keys = _FileSystemsEntry.filesystems_keys elif len(keys) < 6: raise ValueError('Invalid key name array: {0}'.format(keys)) blk_lines = lines orddict = OrderedDict() orddict['name'] = blk_lines[0].split(':')[0].strip() blk_lines.pop(0) for line in blk_lines: if line.startswith('#'): raise cls.ParseError("Comment!") comps = line.split('= ') if len(comps) != 2: raise cls.ParseError("Invalid Entry!") key_name = comps[0].strip() if key_name in keys: orddict[key_name] = comps[1].strip() else: raise ValueError('Invalid name for use in filesystems: {0}'.format(key_name)) return orddict @classmethod def dict_from_cmd_line(cls, ipargs, keys): cmdln_dict = ipargs if keys: for key, value in keys: # ignore unknown or local scope keys if key.startswith('__'): continue if key in _FileSystemsEntry.compatibility_keys: cmdln_dict[key] = value return cmdln_dict @classmethod def from_line(cls, *args, **kwargs): return cls(** cls.dict_from_cmd_line(*args, **kwargs)) @classmethod def dict_to_lines(cls, fsys_dict_entry): entry = fsys_dict_entry strg_out = entry['name'] + ':' + os.linesep for k, v in six.viewitems(entry): if 'name' not in k: strg_out += '\t{0}\t\t= {1}'.format(k, v) + os.linesep strg_out += os.linesep return six.text_type(strg_out) def dict_from_entry(self): ret = OrderedDict() ret[self.criteria['name']] = self.criteria return ret def __str__(self): ''' String value, only works for full repr ''' return self.dict_to_lines(self.criteria) def __repr__(self): ''' Always works ''' return repr(self.criteria) def pick(self, keys): ''' Returns an instance with just those keys ''' subset = dict([(key, self.criteria[key]) for key in keys]) return self.__class__(**subset) def __init__(self, **criteria): ''' Store non-empty, non-null values to use as filter ''' items = [key_value for key_value in six.iteritems(criteria) if key_value[1] is not None] items = [(key_value1[0], six.text_type(key_value1[1])) for key_value1 in items] self.criteria = OrderedDict(items) @staticmethod def norm_path(path): ''' Resolve equivalent paths equivalently ''' return os.path.normcase(os.path.normpath(path)) def match(self, fsys_view): ''' Compare potentially partial criteria against built filesystems entry dictionary ''' evalue_dict = fsys_view[1] for key, value in six.viewitems(self.criteria): if key in evalue_dict: if evalue_dict[key] != value: return False else: return False return True def __getitem__(self, key): ''' Return value for input key ''' return self.criteria[key] def fstab(config='/etc/fstab'): ''' .. versionchanged:: 2016.3.2 List the contents of the fstab CLI Example: .. code-block:: bash salt '*' mount.fstab ''' ret = {} if not os.path.isfile(config): return ret with salt.utils.files.fopen(config) as ifile: for line in ifile: line = salt.utils.stringutils.to_unicode(line) try: if __grains__['kernel'] == 'SunOS': # Note: comments use in default vfstab file! if line[0] == '#': continue entry = _vfstab_entry.dict_from_line( line) else: entry = _fstab_entry.dict_from_line( line, _fstab_entry.compatibility_keys) entry['opts'] = entry['opts'].split(',') while entry['name'] in ret: entry['name'] += '_' ret[entry.pop('name')] = entry except _fstab_entry.ParseError: pass except _vfstab_entry.ParseError: pass return ret def vfstab(config='/etc/vfstab'): ''' .. versionadded:: 2016.3.2 List the contents of the vfstab CLI Example: .. code-block:: bash salt '*' mount.vfstab ''' # NOTE: vfstab is a wrapper for fstab return fstab(config) def rm_fstab(name, device, config='/etc/fstab'): ''' .. versionchanged:: 2016.3.2 Remove the mount point from the fstab CLI Example: .. code-block:: bash salt '*' mount.rm_fstab /mnt/foo /dev/sdg ''' modified = False if __grains__['kernel'] == 'SunOS': criteria = _vfstab_entry(name=name, device=device) else: criteria = _fstab_entry(name=name, device=device) lines = [] try: with salt.utils.files.fopen(config, 'r') as ifile: for line in ifile: line = salt.utils.stringutils.to_unicode(line) try: if criteria.match(line): modified = True else: lines.append(line) except _fstab_entry.ParseError: lines.append(line) except _vfstab_entry.ParseError: lines.append(line) except (IOError, OSError) as exc: msg = "Couldn't read from {0}: {1}" raise CommandExecutionError(msg.format(config, exc)) if modified: try: with salt.utils.files.fopen(config, 'wb') as ofile: ofile.writelines(salt.utils.data.encode(lines)) except (IOError, OSError) as exc: msg = "Couldn't write to {0}: {1}" raise CommandExecutionError(msg.format(config, exc)) # Note: not clear why we always return 'True' # --just copying previous behavior at this point... return True def rm_vfstab(name, device, config='/etc/vfstab'): ''' .. versionadded:: 2016.3.2 Remove the mount point from the vfstab CLI Example: .. code-block:: bash salt '*' mount.rm_vfstab /mnt/foo /device/c0t0d0p0 ''' ## NOTE: rm_vfstab is a wrapper for rm_fstab return rm_fstab(name, device, config) def set_fstab( name, device, fstype, opts='defaults', dump=0, pass_num=0, config='/etc/fstab', test=False, match_on='auto', **kwargs): ''' Verify that this mount is represented in the fstab, change the mount to match the data passed, or add the mount if it is not present. CLI Example: .. code-block:: bash salt '*' mount.set_fstab /mnt/foo /dev/sdz1 ext4 ''' # Fix the opts type if it is a list if isinstance(opts, list): opts = ','.join(opts) # preserve arguments for updating entry_args = { 'name': name, 'device': device.replace('\\ ', '\\040'), 'fstype': fstype, 'opts': opts.replace('\\ ', '\\040'), 'dump': dump, 'pass_num': pass_num, } lines = [] ret = None # Transform match_on into list--items will be checked later if isinstance(match_on, list): pass elif not isinstance(match_on, six.string_types): msg = 'match_on must be a string or list of strings' raise CommandExecutionError(msg) elif match_on == 'auto': # Try to guess right criteria for auto.... # NOTE: missing some special fstypes here specialFSes = frozenset([ 'none', 'tmpfs', 'sysfs', 'proc', 'fusectl', 'debugfs', 'securityfs', 'devtmpfs', 'cgroup', 'btrfs']) if fstype in specialFSes: match_on = ['name'] else: match_on = ['device'] else: match_on = [match_on] # generate entry and criteria objects, handle invalid keys in match_on entry = _fstab_entry(**entry_args) try: criteria = entry.pick(match_on) except KeyError: filterFn = lambda key: key not in _fstab_entry.fstab_keys invalid_keys = filter(filterFn, match_on) msg = 'Unrecognized keys in match_on: "{0}"'.format(invalid_keys) raise CommandExecutionError(msg) # parse file, use ret to cache status if not os.path.isfile(config): raise CommandExecutionError('Bad config file "{0}"'.format(config)) try: with salt.utils.files.fopen(config, 'r') as ifile: for line in ifile: line = salt.utils.stringutils.to_unicode(line) try: if criteria.match(line): # Note: If ret isn't None here, # we've matched multiple lines ret = 'present' if entry.match(line): lines.append(line) else: ret = 'change' lines.append(six.text_type(entry)) else: lines.append(line) except _fstab_entry.ParseError: lines.append(line) except (IOError, OSError) as exc: msg = 'Couldn\'t read from {0}: {1}' raise CommandExecutionError(msg.format(config, exc)) # add line if not present or changed if ret is None: lines.append(six.text_type(entry)) ret = 'new' if ret != 'present': # ret in ['new', 'change']: if not salt.utils.args.test_mode(test=test, **kwargs): try: with salt.utils.files.fopen(config, 'wb') as ofile: # The line was changed, commit it! ofile.writelines(salt.utils.data.encode(lines)) except (IOError, OSError): msg = 'File not writable {0}' raise CommandExecutionError(msg.format(config)) return ret def set_vfstab( name, device, fstype, opts='-', device_fsck='-', pass_fsck='-', mount_at_boot='yes', config='/etc/vfstab', test=False, match_on='auto', **kwargs): ''' ..verionadded:: 2016.3.2 Verify that this mount is represented in the fstab, change the mount to match the data passed, or add the mount if it is not present. CLI Example: .. code-block:: bash salt '*' mount.set_vfstab /mnt/foo /device/c0t0d0p0 ufs ''' # Fix the opts type if it is a list if isinstance(opts, list): opts = ','.join(opts) # Map unknown values for mount_at_boot to no if mount_at_boot != 'yes': mount_at_boot = 'no' # preserve arguments for updating entry_args = { 'name': name, 'device': device, 'fstype': fstype, 'opts': opts, 'device_fsck': device_fsck, 'pass_fsck': pass_fsck, 'mount_at_boot': mount_at_boot, } lines = [] ret = None # Transform match_on into list--items will be checked later if isinstance(match_on, list): pass elif not isinstance(match_on, six.string_types): msg = 'match_on must be a string or list of strings' raise CommandExecutionError(msg) elif match_on == 'auto': # Try to guess right criteria for auto.... # NOTE: missing some special fstypes here specialFSes = frozenset([ 'devfs', 'proc', 'ctfs', 'objfs', 'sharefs', 'fs', 'tmpfs']) if fstype in specialFSes: match_on = ['name'] else: match_on = ['device'] else: match_on = [match_on] # generate entry and criteria objects, handle invalid keys in match_on entry = _vfstab_entry(**entry_args) try: criteria = entry.pick(match_on) except KeyError: filterFn = lambda key: key not in _vfstab_entry.vfstab_keys invalid_keys = filter(filterFn, match_on) msg = 'Unrecognized keys in match_on: "{0}"'.format(invalid_keys) raise CommandExecutionError(msg) # parse file, use ret to cache status if not os.path.isfile(config): raise CommandExecutionError('Bad config file "{0}"'.format(config)) try: with salt.utils.files.fopen(config, 'r') as ifile: for line in ifile: line = salt.utils.stringutils.to_unicode(line) try: if criteria.match(line): # Note: If ret isn't None here, # we've matched multiple lines ret = 'present' if entry.match(line): lines.append(line) else: ret = 'change' lines.append(six.text_type(entry)) else: lines.append(line) except _vfstab_entry.ParseError: lines.append(line) except (IOError, OSError) as exc: msg = 'Couldn\'t read from {0}: {1}' raise CommandExecutionError(msg.format(config, exc)) # add line if not present or changed if ret is None: lines.append(six.text_type(entry)) ret = 'new' if ret != 'present': # ret in ['new', 'change']: if not salt.utils.args.test_mode(test=test, **kwargs): try: with salt.utils.files.fopen(config, 'wb') as ofile: # The line was changed, commit it! ofile.writelines(salt.utils.data.encode(lines)) except (IOError, OSError): msg = 'File not writable {0}' raise CommandExecutionError(msg.format(config)) return ret def rm_automaster(name, device, config='/etc/auto_salt'): ''' Remove the mount point from the auto_master CLI Example: .. code-block:: bash salt '*' mount.rm_automaster /mnt/foo /dev/sdg ''' contents = automaster(config) if name not in contents: return True # The entry is present, get rid of it lines = [] try: with salt.utils.files.fopen(config, 'r') as ifile: for line in ifile: line = salt.utils.stringutils.to_unicode(line) if line.startswith('#'): # Commented lines.append(line) continue if not line.strip(): # Blank line lines.append(line) continue comps = line.split() if len(comps) != 3: # Invalid entry lines.append(line) continue comps = line.split() prefix = "/.." name_chk = comps[0].replace(prefix, "") device_fmt = comps[2].split(":") if device: if name_chk == name and device_fmt[1] == device: continue else: if name_chk == name: continue lines.append(line) except (IOError, OSError) as exc: msg = "Couldn't read from {0}: {1}" raise CommandExecutionError(msg.format(config, exc)) try: with salt.utils.files.fopen(config, 'wb') as ofile: ofile.writelines(salt.utils.data.encode(lines)) except (IOError, OSError) as exc: msg = "Couldn't write to {0}: {1}" raise CommandExecutionError(msg.format(config, exc)) # Update automount __salt__['cmd.run']('automount -cv') return True def set_automaster( name, device, fstype, opts='', config='/etc/auto_salt', test=False, **kwargs): ''' Verify that this mount is represented in the auto_salt, change the mount to match the data passed, or add the mount if it is not present. CLI Example: .. code-block:: bash salt '*' mount.set_automaster /mnt/foo /dev/sdz1 ext4 ''' # Fix the opts type if it is a list if isinstance(opts, list): opts = ','.join(opts) lines = [] change = False present = False automaster_file = "/etc/auto_master" if not os.path.isfile(config): __salt__['file.touch'](config) __salt__['file.append'](automaster_file, "/-\t\t\t{0}".format(config)) name = "/..{0}".format(name) device_fmt = "{0}:{1}".format(fstype, device) type_opts = "-fstype={0},{1}".format(fstype, opts) if fstype == 'smbfs': device_fmt = device_fmt.replace(fstype, "") try: with salt.utils.files.fopen(config, 'r') as ifile: for line in ifile: line = salt.utils.stringutils.to_unicode(line) if line.startswith('#'): # Commented lines.append(line) continue if not line.strip(): # Blank line lines.append(line) continue comps = line.split() if len(comps) != 3: # Invalid entry lines.append(line) continue if comps[0] == name or comps[2] == device_fmt: # check to see if there are changes # and fix them if there are any present = True if comps[0] != name: change = True comps[0] = name if comps[1] != type_opts: change = True comps[1] = type_opts if comps[2] != device_fmt: change = True comps[2] = device_fmt if change: log.debug( 'auto_master entry for mount point %s needs to be ' 'updated', name ) newline = ( '{0}\t{1}\t{2}\n'.format( name, type_opts, device_fmt) ) lines.append(newline) else: lines.append(line) except (IOError, OSError) as exc: msg = 'Couldn\'t read from {0}: {1}' raise CommandExecutionError(msg.format(config, exc)) if change: if not salt.utils.args.test_mode(test=test, **kwargs): try: with salt.utils.files.fopen(config, 'wb') as ofile: # The line was changed, commit it! ofile.writelines(salt.utils.data.encode(lines)) except (IOError, OSError): msg = 'File not writable {0}' raise CommandExecutionError(msg.format(config)) return 'change' if not change: if present: # The right entry is already here return 'present' else: if not salt.utils.args.test_mode(test=test, **kwargs): # The entry is new, add it to the end of the fstab newline = ( '{0}\t{1}\t{2}\n'.format( name, type_opts, device_fmt) ) lines.append(newline) try: with salt.utils.files.fopen(config, 'wb') as ofile: # The line was changed, commit it! ofile.writelines(salt.utils.data.encode(lines)) except (IOError, OSError): raise CommandExecutionError( 'File not writable {0}'.format( config ) ) return 'new' def automaster(config='/etc/auto_salt'): ''' List the contents of the auto master CLI Example: .. code-block:: bash salt '*' mount.automaster ''' ret = {} if not os.path.isfile(config): return ret with salt.utils.files.fopen(config) as ifile: for line in ifile: line = salt.utils.stringutils.to_unicode(line) if line.startswith('#'): # Commented continue if not line.strip(): # Blank line continue comps = line.split() if len(comps) != 3: # Invalid entry continue prefix = "/.." name = comps[0].replace(prefix, "") device_fmt = comps[2].split(":") opts = comps[1].split(',') ret[name] = {'device': device_fmt[1], 'fstype': opts[0], 'opts': opts[1:]} return ret def mount(name, device, mkmnt=False, fstype='', opts='defaults', user=None, util='mount'): ''' Mount a device CLI Example: .. code-block:: bash salt '*' mount.mount /mnt/foo /dev/sdz1 True ''' if util != 'mount': # This functionality used to live in img.mount_image if util == 'guestfs': return __salt__['guestfs.mount'](name, root=device) elif util == 'qemu_nbd': mnt = __salt__['qemu_nbd.init'](name, device) if not mnt: return False first = next(six.iterkeys(mnt)) __context__['img.mnt_{0}'.format(first)] = mnt return first return False # Darwin doesn't expect defaults when mounting without other options if 'defaults' in opts and __grains__['os'] in ['MacOS', 'Darwin', 'AIX']: opts = None if isinstance(opts, six.string_types): opts = opts.split(',') if not os.path.exists(name) and mkmnt: __salt__['file.mkdir'](name, user=user) args = '' if opts is not None: lopts = ','.join(opts) args = '-o {0}'.format(lopts) if fstype: # use of fstype on AIX differs from typical Linux use of -t # functionality AIX uses -v vfsname, -t fstype mounts all with # fstype in /etc/filesystems if 'AIX' in __grains__['os']: args += ' -v {0}'.format(fstype) elif 'solaris' in __grains__['os'].lower(): args += ' -F {0}'.format(fstype) else: args += ' -t {0}'.format(fstype) cmd = 'mount {0} {1} {2} '.format(args, device, name) out = __salt__['cmd.run_all'](cmd, runas=user, python_shell=False) if out['retcode']: return out['stderr'] return True def remount(name, device, mkmnt=False, fstype='', opts='defaults', user=None): ''' Attempt to remount a device, if the device is not already mounted, mount is called CLI Example: .. code-block:: bash salt '*' mount.remount /mnt/foo /dev/sdz1 True ''' force_mount = False if __grains__['os'] in ['MacOS', 'Darwin']: if opts == 'defaults': opts = 'noowners' if fstype == 'smbfs': force_mount = True if 'AIX' in __grains__['os']: if opts == 'defaults': opts = [] if isinstance(opts, six.string_types): opts = opts.split(',') mnts = active() if name in mnts: # The mount point is mounted, attempt to remount it with the given data if 'remount' not in opts and __grains__['os'] not in ['OpenBSD', 'MacOS', 'Darwin']: opts.append('remount') if force_mount: # We need to force the mount but first we should unmount umount(name, device, user=user) lopts = ','.join(opts) args = '-o {0}'.format(lopts) if fstype: # use of fstype on AIX differs from typical Linux use of # -t functionality AIX uses -v vfsname, -t fstype mounts # all with fstype in /etc/filesystems if 'AIX' in __grains__['os']: args += ' -v {0}'.format(fstype) elif 'solaris' in __grains__['os'].lower(): args += ' -F {0}'.format(fstype) else: args += ' -t {0}'.format(fstype) if __grains__['os'] not in ['OpenBSD', 'MacOS', 'Darwin'] or force_mount: cmd = 'mount {0} {1} {2} '.format(args, device, name) else: cmd = 'mount -u {0} {1} {2} '.format(args, device, name) out = __salt__['cmd.run_all'](cmd, runas=user, python_shell=False) if out['retcode']: return out['stderr'] return True # Mount a filesystem that isn't already return mount(name, device, mkmnt, fstype, opts, user=user) def umount(name, device=None, user=None, util='mount'): ''' Attempt to unmount a device by specifying the directory it is mounted on CLI Example: .. code-block:: bash salt '*' mount.umount /mnt/foo .. versionadded:: 2015.5.0 .. code-block:: bash salt '*' mount.umount /mnt/foo /dev/xvdc1 ''' if util != 'mount': # This functionality used to live in img.umount_image if 'qemu_nbd.clear' in __salt__: if 'img.mnt_{0}'.format(name) in __context__: __salt__['qemu_nbd.clear'](__context__['img.mnt_{0}'.format(name)]) return mnts = active() if name not in mnts: return "{0} does not have anything mounted".format(name) if not device: cmd = 'umount {0}'.format(name) else: cmd = 'umount {0}'.format(device) out = __salt__['cmd.run_all'](cmd, runas=user, python_shell=False) if out['retcode']: return out['stderr'] return True def is_fuse_exec(cmd): ''' Returns true if the command passed is a fuse mountable application. CLI Example: .. code-block:: bash salt '*' mount.is_fuse_exec sshfs ''' cmd_path = salt.utils.path.which(cmd) # No point in running ldd on a command that doesn't exist if not cmd_path: return False elif not salt.utils.path.which('ldd'): raise CommandNotFoundError('ldd') out = __salt__['cmd.run']('ldd {0}'.format(cmd_path), python_shell=False) return 'libfuse' in out def swaps(): ''' Return a dict containing information on active swap .. versionchanged:: 2016.3.2 CLI Example: .. code-block:: bash salt '*' mount.swaps ''' ret = {} if __grains__['kernel'] == 'SunOS': for line in __salt__['cmd.run_stdout']('swap -l').splitlines(): if line.startswith('swapfile'): continue comps = line.split() ret[comps[0]] = {'type': 'device' if comps[0].startswith(('/dev', 'swap')) else 'file', 'size': int(comps[3]), 'used': (int(comps[3]) - int(comps[4])), 'priority': '-'} elif 'AIX' in __grains__['kernel']: for line in __salt__['cmd.run_stdout']('swap -l').splitlines(): if line.startswith('device'): continue comps = line.split() # AIX uses MB for units ret[comps[0]] = {'type': 'device', 'size': int(comps[3][:-2]) * 1024, 'used': (int(comps[3][:-2]) - int(comps[4][:-2])) * 1024, 'priority': '-'} elif __grains__['os'] != 'OpenBSD': with salt.utils.files.fopen('/proc/swaps') as fp_: for line in fp_: line = salt.utils.stringutils.to_unicode(line) if line.startswith('Filename'): continue comps = line.split() ret[comps[0]] = {'type': comps[1], 'size': comps[2], 'used': comps[3], 'priority': comps[4]} else: for line in __salt__['cmd.run_stdout']('swapctl -kl').splitlines(): if line.startswith(('Device', 'Total')): continue swap_type = "file" comps = line.split() if comps[0].startswith('/dev/'): swap_type = "partition" ret[comps[0]] = {'type': swap_type, 'size': comps[1], 'used': comps[2], 'priority': comps[5]} return ret def swapon(name, priority=None): ''' Activate a swap disk .. versionchanged:: 2016.3.2 CLI Example: .. code-block:: bash salt '*' mount.swapon /root/swapfile ''' ret = {} on_ = swaps() if name in on_: ret['stats'] = on_[name] ret['new'] = False return ret if __grains__['kernel'] == 'SunOS': if __grains__['virtual'] != 'zone': __salt__['cmd.run']('swap -a {0}'.format(name), python_shell=False) else: return False else: cmd = 'swapon {0}'.format(name) if priority and 'AIX' not in __grains__['kernel']: cmd += ' -p {0}'.format(priority) __salt__['cmd.run'](cmd, python_shell=False) on_ = swaps() if name in on_: ret['stats'] = on_[name] ret['new'] = True return ret return ret def swapoff(name): ''' Deactivate a named swap mount .. versionchanged:: 2016.3.2 CLI Example: .. code-block:: bash salt '*' mount.swapoff /root/swapfile ''' on_ = swaps() if name in on_: if __grains__['kernel'] == 'SunOS': if __grains__['virtual'] != 'zone': __salt__['cmd.run']('swap -a {0}'.format(name), python_shell=False) else: return False elif __grains__['os'] != 'OpenBSD': __salt__['cmd.run']('swapoff {0}'.format(name), python_shell=False) else: __salt__['cmd.run']('swapctl -d {0}'.format(name), python_shell=False) on_ = swaps() if name in on_: return False return True return None def is_mounted(name): ''' .. versionadded:: 2014.7.0 Provide information if the path is mounted CLI Example: .. code-block:: bash salt '*' mount.is_mounted /mnt/share ''' active_ = active() if name in active_: return True else: return False def read_mount_cache(name): ''' .. versionadded:: 2018.3.0 Provide information if the path is mounted CLI Example: .. code-block:: bash salt '*' mount.read_mount_cache /mnt/share ''' cache = salt.utils.mount.read_cache(__opts__) if cache: if 'mounts' in cache and cache['mounts']: if name in cache['mounts']: return cache['mounts'][name] return {} def delete_mount_cache(real_name): ''' .. versionadded:: 2018.3.0 Provide information if the path is mounted CLI Example: .. code-block:: bash salt '*' mount.delete_mount_cache /mnt/share ''' cache = salt.utils.mount.read_cache(__opts__) if cache: if 'mounts' in cache: if real_name in cache['mounts']: del cache['mounts'][real_name] cache_write = salt.utils.mount.write_cache(cache, __opts__) if not cache_write: raise CommandExecutionError('Unable to write mount cache.') return True def _filesystems(config='/etc/filesystems', leading_key=True): ''' Return the contents of the filesystems in an OrderedDict config File containing filesystem infomation leading_key True return dictionary keyed by 'name' and value as dictionary with other keys, values (name excluded) OrderedDict({ '/dir' : OrderedDict({'dev': '/dev/hd8', .... }})) False return dictionary keyed by 'name' and value as dictionary with all keys, values (name included) OrderedDict({ '/dir' : OrderedDict({'name': '/dir', 'dev': '/dev/hd8', ... })}) ''' ret = OrderedDict() lines = [] parsing_block = False if not os.path.isfile(config) or 'AIX' not in __grains__['kernel']: return ret # read in block of filesystems, block starts with '/' till empty line with salt.utils.files.fopen(config) as ifile: for line in ifile: line = salt.utils.stringutils.to_unicode(line) # skip till first entry if not line.startswith('/') and not parsing_block: continue if line.startswith('/'): parsing_block = True lines.append(line) elif not line.split(): parsing_block = False try: entry = _FileSystemsEntry.dict_from_lines( lines, _FileSystemsEntry.compatibility_keys) lines = [] if 'opts' in entry: entry['opts'] = entry['opts'].split(',') while entry['name'] in ret: entry['name'] += '_' if leading_key: ret[entry.pop('name')] = entry else: ret[entry['name']] = entry except _FileSystemsEntry.ParseError: pass else: lines.append(line) return ret def filesystems(config='/etc/filesystems'): ''' .. versionadded:: 2018.3.3 List the contents of the filesystems CLI Example: .. code-block:: bash salt '*' mount.filesystems ''' ret = {} if 'AIX' not in __grains__['kernel']: return ret ret_dict = _filesystems(config) if ret_dict: ret_key = next(iter(ret_dict.keys())) ret = {ret_key: dict(ret_dict[ret_key])} return ret def set_filesystems( name, device, vfstype, opts='-', mount='true', config='/etc/filesystems', test=False, match_on='auto', **kwargs): ''' .. versionadded:: 2018.3.3 Verify that this mount is represented in the filesystems, change the mount to match the data passed, or add the mount if it is not present on AIX Provide information if the path is mounted :param name: The name of the mount point where the device is mounted. :param device: The device that is being mounted. :param vfstype: The file system that is used (AIX has two fstypes, fstype and vfstype - similar to Linux fstype) :param opts: Additional options used when mounting the device. :param mount: Mount if not mounted, default True. :param config: Configuration file, default /etc/filesystems. :param match: File systems type to match on, default auto CLI Example: .. code-block:: bash salt '*' mount.set_filesystems /mnt/foo /dev/sdz1 jfs2 ''' # Fix the opts type if it is a list if isinstance(opts, list): opts = ','.join(opts) # preserve arguments for updating entry_args = { 'name': name, 'dev': device.replace('\\ ', '\\040'), 'vfstype': vfstype, 'opts': opts, 'mount': mount, } view_lines = [] ret = None if 'AIX' not in __grains__['kernel']: return ret # Transform match_on into list--items will be checked later if isinstance(match_on, list): pass elif not isinstance(match_on, six.string_types): raise CommandExecutionError('match_on must be a string or list of strings') elif match_on == 'auto': # Try to guess right criteria for auto.... # added IBM types from sys/vmount.h after btrfs # NOTE: missing some special fstypes here specialFSes = frozenset([ 'none', 'tmpfs', 'sysfs', 'proc', 'fusectl', 'debugfs', 'securityfs', 'devtmpfs', 'cgroup', 'btrfs', 'cdrfs', 'procfs', 'jfs', 'jfs2', 'nfs', 'sfs', 'nfs3', 'cachefs', 'udfs', 'cifs', 'namefs', 'pmemfs', 'ahafs', 'nfs4', 'autofs', 'stnfs']) if vfstype in specialFSes: match_on = ['name'] else: match_on = ['dev'] else: match_on = [match_on] # generate entry and criteria objects, handle invalid keys in match_on entry_ip = _FileSystemsEntry.from_line(entry_args, kwargs) try: criteria = entry_ip.pick(match_on) except KeyError: filterFn = lambda key: key not in _FileSystemsEntry.compatibility_keys invalid_keys = filter(filterFn, match_on) raise CommandExecutionError('Unrecognized keys in match_on: "{0}"'.format(invalid_keys)) # parse file, use ret to cache status if not os.path.isfile(config): raise CommandExecutionError('Bad config file "{0}"'.format(config)) # read in block of filesystem, block starts with '/' till empty line try: fsys_filedict = _filesystems(config, False) for fsys_view in six.viewitems(fsys_filedict): if criteria.match(fsys_view): ret = 'present' if entry_ip.match(fsys_view): view_lines.append(fsys_view) else: ret = 'change' kv = entry_ip['name'] view_lines.append((kv, entry_ip)) else: view_lines.append(fsys_view) except (IOError, OSError) as exc: raise CommandExecutionError('Couldn\'t read from {0}: {1}'.format(config, exc)) # add line if not present or changed if ret is None: for dict_view in six.viewitems(entry_ip.dict_from_entry()): view_lines.append(dict_view) ret = 'new' if ret != 'present': # ret in ['new', 'change']: try: with salt.utils.files.fopen(config, 'wb') as ofile: # The line was changed, commit it! for fsys_view in view_lines: entry = fsys_view[1] mystrg = _FileSystemsEntry.dict_to_lines(entry) ofile.writelines(salt.utils.data.encode(mystrg)) except (IOError, OSError): raise CommandExecutionError('File not writable {0}'.format(config)) return ret def rm_filesystems(name, device, config='/etc/filesystems'): ''' .. versionadded:: 2018.3.3 Remove the mount point from the filesystems CLI Example: .. code-block:: bash salt '*' mount.rm_filesystems /mnt/foo /dev/sdg ''' modified = False view_lines = [] if 'AIX' not in __grains__['kernel']: return modified criteria = _FileSystemsEntry(name=name, dev=device) try: fsys_filedict = _filesystems(config, False) for fsys_view in six.viewitems(fsys_filedict): try: if criteria.match(fsys_view): modified = True else: view_lines.append(fsys_view) except _FileSystemsEntry.ParseError: view_lines.append(fsys_view) except (IOError, OSError) as exc: raise CommandExecutionError("Couldn't read from {0}: {1}".format(config, exc)) if modified: try: with salt.utils.files.fopen(config, 'wb') as ofile: for fsys_view in view_lines: entry = fsys_view[1] mystrg = _FileSystemsEntry.dict_to_lines(entry) ofile.writelines(salt.utils.data.encode(mystrg)) except (IOError, OSError) as exc: raise CommandExecutionError("Couldn't write to {0}: {1}".format(config, exc)) return modified
saltstack/salt
salt/modules/mount.py
delete_mount_cache
python
def delete_mount_cache(real_name): ''' .. versionadded:: 2018.3.0 Provide information if the path is mounted CLI Example: .. code-block:: bash salt '*' mount.delete_mount_cache /mnt/share ''' cache = salt.utils.mount.read_cache(__opts__) if cache: if 'mounts' in cache: if real_name in cache['mounts']: del cache['mounts'][real_name] cache_write = salt.utils.mount.write_cache(cache, __opts__) if not cache_write: raise CommandExecutionError('Unable to write mount cache.') return True
.. versionadded:: 2018.3.0 Provide information if the path is mounted CLI Example: .. code-block:: bash salt '*' mount.delete_mount_cache /mnt/share
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/mount.py#L1561-L1582
[ "def read_cache(opts):\n '''\n Write the mount cache file.\n '''\n cache_file = get_cache(opts)\n return _read_file(cache_file)\n", "def write_cache(cache, opts):\n '''\n Write the mount cache file.\n '''\n cache_file = get_cache(opts)\n\n try:\n _cache = salt.utils.stringutils.to_bytes(\n salt.utils.yaml.safe_dump(cache)\n )\n with salt.utils.files.fopen(cache_file, 'wb+') as fp_:\n fp_.write(_cache)\n return True\n except (IOError, OSError):\n log.error('Failed to cache mounts',\n exc_info_on_loglevel=logging.DEBUG)\n return False\n" ]
# -*- coding: utf-8 -*- ''' Salt module to manage Unix mounts and the fstab file ''' # Import python libs from __future__ import absolute_import, print_function, unicode_literals import os import re import logging # Import salt libs import salt.utils.args import salt.utils.data import salt.utils.files import salt.utils.path import salt.utils.platform import salt.utils.mount import salt.utils.stringutils from salt.utils.odict import OrderedDict from salt.exceptions import CommandNotFoundError, CommandExecutionError # Import 3rd-party libs from salt.ext import six from salt.ext.six.moves import filter, zip # pylint: disable=import-error,redefined-builtin # Set up logger log = logging.getLogger(__name__) # Define the module's virtual name __virtualname__ = 'mount' def __virtual__(): ''' Only load on POSIX-like systems ''' # Disable on Windows, a specific file module exists: if salt.utils.platform.is_windows(): return (False, 'The mount module cannot be loaded: not a POSIX-like system.') return True def _list_mounts(): ret = {} if __grains__['os'] in ['MacOS', 'Darwin']: mounts = __salt__['cmd.run_stdout']('mount') else: mounts = __salt__['cmd.run_stdout']('mount -l') for line in mounts.split('\n'): comps = re.sub(r"\s+", " ", line).split() if len(comps) >= 3: ret[comps[2]] = comps[0] return ret def _active_mountinfo(ret): _list = _list_mounts() filename = '/proc/self/mountinfo' if not os.access(filename, os.R_OK): msg = 'File not readable {0}' raise CommandExecutionError(msg.format(filename)) if 'disk.blkid' not in __context__: __context__['disk.blkid'] = __salt__['disk.blkid']() blkid_info = __context__['disk.blkid'] with salt.utils.files.fopen(filename) as ifile: for line in ifile: comps = salt.utils.stringutils.to_unicode(line).split() device = comps[2].split(':') # each line can have any number of # optional parameters, we use the # location of the separator field to # determine the location of the elements # after it. _sep = comps.index('-') device_name = comps[_sep + 2] device_uuid = None device_label = None if device_name: device_uuid = blkid_info.get(device_name, {}).get('UUID') device_uuid = device_uuid and device_uuid.lower() device_label = blkid_info.get(device_name, {}).get('LABEL') ret[comps[4]] = {'mountid': comps[0], 'parentid': comps[1], 'major': device[0], 'minor': device[1], 'root': comps[3], 'opts': _resolve_user_group_names(comps[5].split(',')), 'fstype': comps[_sep + 1], 'device': device_name.replace('\\040', '\\ '), 'alt_device': _list.get(comps[4], None), 'superopts': _resolve_user_group_names(comps[_sep + 3].split(',')), 'device_uuid': device_uuid, 'device_label': device_label} return ret def _active_mounts(ret): ''' List active mounts on Linux systems ''' _list = _list_mounts() filename = '/proc/self/mounts' if not os.access(filename, os.R_OK): msg = 'File not readable {0}' raise CommandExecutionError(msg.format(filename)) with salt.utils.files.fopen(filename) as ifile: for line in ifile: comps = salt.utils.stringutils.to_unicode(line).split() ret[comps[1]] = {'device': comps[0], 'alt_device': _list.get(comps[1], None), 'fstype': comps[2], 'opts': _resolve_user_group_names(comps[3].split(','))} return ret def _active_mounts_aix(ret): ''' List active mounts on AIX systems ''' for line in __salt__['cmd.run_stdout']('mount -p').split('\n'): comps = re.sub(r"\s+", " ", line).split() if comps: if comps[0] == 'node' or comps[0] == '--------': continue comps_len = len(comps) if line.startswith((' ', '\t')): curr_opts = _resolve_user_group_names(comps[6].split(',')) if 7 == comps_len else [] if curr_opts: ret[comps[1]] = {'device': comps[0], 'fstype': comps[2], 'opts': curr_opts} else: ret[comps[1]] = {'device': comps[0], 'fstype': comps[2]} else: curr_opts = _resolve_user_group_names(comps[7].split(',')) if 8 == comps_len else [] if curr_opts: ret[comps[2]] = {'node': comps[0], 'device': comps[1], 'fstype': comps[3], 'opts': curr_opts} else: ret[comps[2]] = {'node': comps[0], 'device': comps[1], 'fstype': comps[3]} return ret def _active_mounts_freebsd(ret): ''' List active mounts on FreeBSD systems ''' for line in __salt__['cmd.run_stdout']('mount -p').split('\n'): comps = re.sub(r"\s+", " ", line).split() ret[comps[1]] = {'device': comps[0], 'fstype': comps[2], 'opts': _resolve_user_group_names(comps[3].split(','))} return ret def _active_mounts_solaris(ret): ''' List active mounts on Solaris systems ''' for line in __salt__['cmd.run_stdout']('mount -v').split('\n'): comps = re.sub(r"\s+", " ", line).split() ret[comps[2]] = {'device': comps[0], 'fstype': comps[4], 'opts': _resolve_user_group_names(comps[5].split('/'))} return ret def _active_mounts_openbsd(ret): ''' List active mounts on OpenBSD systems ''' for line in __salt__['cmd.run_stdout']('mount -v').split('\n'): comps = re.sub(r"\s+", " ", line).split() parens = re.findall(r'\((.*?)\)', line, re.DOTALL) if len(parens) > 1: nod = __salt__['cmd.run_stdout']('ls -l {0}'.format(comps[0])) nod = ' '.join(nod.split()).split(" ") ret[comps[3]] = {'device': comps[0], 'fstype': comps[5], 'opts': _resolve_user_group_names(parens[1].split(", ")), 'major': six.text_type(nod[4].strip(",")), 'minor': six.text_type(nod[5]), 'device_uuid': parens[0]} else: ret[comps[2]] = {'device': comps[0], 'fstype': comps[4], 'opts': _resolve_user_group_names(parens[0].split(", "))} return ret def _active_mounts_darwin(ret): ''' List active mounts on Mac OS systems ''' for line in __salt__['cmd.run_stdout']('mount').split('\n'): comps = re.sub(r"\s+", " ", line).split() parens = re.findall(r'\((.*?)\)', line, re.DOTALL)[0].split(", ") ret[comps[2]] = {'device': comps[0], 'fstype': parens[0], 'opts': _resolve_user_group_names(parens[1:])} return ret def _resolve_user_group_names(opts): ''' Resolve user and group names in related opts ''' name_id_opts = {'uid': 'user.info', 'gid': 'group.info'} for ind, opt in enumerate(opts): if opt.split('=')[0] in name_id_opts: _givenid = opt.split('=')[1] _param = opt.split('=')[0] _id = _givenid if not re.match('[0-9]+$', _givenid): _info = __salt__[name_id_opts[_param]](_givenid) if _info and _param in _info: _id = _info[_param] opts[ind] = _param + '=' + six.text_type(_id) opts[ind] = opts[ind].replace('\\040', '\\ ') return opts def active(extended=False): ''' List the active mounts. CLI Example: .. code-block:: bash salt '*' mount.active ''' ret = {} if __grains__['os'] == 'FreeBSD': _active_mounts_freebsd(ret) elif 'AIX' in __grains__['kernel']: _active_mounts_aix(ret) elif __grains__['kernel'] == 'SunOS': _active_mounts_solaris(ret) elif __grains__['os'] == 'OpenBSD': _active_mounts_openbsd(ret) elif __grains__['os'] in ['MacOS', 'Darwin']: _active_mounts_darwin(ret) else: if extended: try: _active_mountinfo(ret) except CommandExecutionError: _active_mounts(ret) else: _active_mounts(ret) return ret class _fstab_entry(object): ''' Utility class for manipulating fstab entries. Primarily we're parsing, formatting, and comparing lines. Parsing emits dicts expected from fstab() or raises a ValueError. Note: We'll probably want to use os.normpath and os.normcase on 'name' ''' class ParseError(ValueError): ''' Error raised when a line isn't parsible as an fstab entry ''' fstab_keys = ('device', 'name', 'fstype', 'opts', 'dump', 'pass_num') # preserve data format compatibility_keys = ('device', 'name', 'fstype', 'opts', 'dump', 'pass') fstab_format = '{device}\t\t{name}\t{fstype}\t{opts}\t{dump} {pass_num}\n' @classmethod def dict_from_line(cls, line, keys=fstab_keys): if len(keys) != 6: raise ValueError('Invalid key array: {0}'.format(keys)) if line.startswith('#'): raise cls.ParseError("Comment!") comps = line.split() if len(comps) < 4 or len(comps) > 6: raise cls.ParseError("Invalid Entry!") comps.extend(['0'] * (len(keys) - len(comps))) return dict(zip(keys, comps)) @classmethod def from_line(cls, *args, **kwargs): return cls(** cls.dict_from_line(*args, **kwargs)) @classmethod def dict_to_line(cls, entry): return cls.fstab_format.format(**entry) def __str__(self): ''' String value, only works for full repr ''' return self.dict_to_line(self.criteria) def __repr__(self): ''' Always works ''' return repr(self.criteria) def pick(self, keys): ''' Returns an instance with just those keys ''' subset = dict([(key, self.criteria[key]) for key in keys]) return self.__class__(**subset) def __init__(self, **criteria): ''' Store non-empty, non-null values to use as filter ''' items = [key_value for key_value in six.iteritems(criteria) if key_value[1] is not None] items = [(key_value1[0], six.text_type(key_value1[1])) for key_value1 in items] self.criteria = dict(items) @staticmethod def norm_path(path): ''' Resolve equivalent paths equivalently ''' return os.path.normcase(os.path.normpath(path)) def match(self, line): ''' Compare potentially partial criteria against line ''' entry = self.dict_from_line(line) for key, value in six.iteritems(self.criteria): if entry[key] != value: return False return True class _vfstab_entry(object): ''' Utility class for manipulating vfstab entries. Primarily we're parsing, formatting, and comparing lines. Parsing emits dicts expected from fstab() or raises a ValueError. Note: We'll probably want to use os.normpath and os.normcase on 'name' Note: This parses vfstab entries on Solaris like systems #device device mount FS fsck mount mount #to mount to fsck point type pass at boot options # /devices - /devices devfs - no - ''' class ParseError(ValueError): '''Error raised when a line isn't parsible as an fstab entry''' vfstab_keys = ('device', 'device_fsck', 'name', 'fstype', 'pass_fsck', 'mount_at_boot', 'opts') # NOTE: weird formatting to match default spacing on Solaris vfstab_format = '{device:<11} {device_fsck:<3} {name:<19} {fstype:<8} {pass_fsck:<3} {mount_at_boot:<6} {opts}\n' @classmethod def dict_from_line(cls, line): if line.startswith('#'): raise cls.ParseError("Comment!") comps = line.split() if len(comps) != 7: raise cls.ParseError("Invalid Entry!") return dict(zip(cls.vfstab_keys, comps)) @classmethod def from_line(cls, *args, **kwargs): return cls(** cls.dict_from_line(*args, **kwargs)) @classmethod def dict_to_line(cls, entry): return cls.vfstab_format.format(**entry) def __str__(self): ''' String value, only works for full repr ''' return self.dict_to_line(self.criteria) def __repr__(self): ''' Always works ''' return repr(self.criteria) def pick(self, keys): ''' Returns an instance with just those keys ''' subset = dict([(key, self.criteria[key]) for key in keys]) return self.__class__(**subset) def __init__(self, **criteria): ''' Store non-empty, non-null values to use as filter ''' items = [key_value for key_value in six.iteritems(criteria) if key_value[1] is not None] items = [(key_value1[0], six.text_type(key_value1[1])) for key_value1 in items] self.criteria = dict(items) @staticmethod def norm_path(path): ''' Resolve equivalent paths equivalently ''' return os.path.normcase(os.path.normpath(path)) def match(self, line): ''' Compare potentially partial criteria against line ''' entry = self.dict_from_line(line) for key, value in six.iteritems(self.criteria): if entry[key] != value: return False return True class _FileSystemsEntry(object): ''' Utility class for manipulating filesystem entries. Primarily we're parsing, formatting, and comparing lines. Parsing emits dicts expected from fstab() or raises a ValueError. Note: We'll probably want to use os.normpath and os.normcase on 'name' ''' class ParseError(ValueError): ''' Error raised when a line isn't parsible as an fstab entry ''' filesystems_keys = ('device', 'name', 'fstype', 'vfstype', 'opts', 'mount') # preserve data format of filesystems compatibility_keys = ('dev', 'dev', 'name', 'fstype', 'vfstype', 'opts', 'mount', 'type', 'vfs', 'account', 'boot', 'check', 'free', 'nodename', 'quota', 'size', 'vol', 'log') @classmethod def dict_from_lines(cls, lines, keys=filesystems_keys): if len(lines) < 2: raise ValueError('Invalid number of lines: {0}'.format(lines)) if not keys: # if empty force default filesystems_keys keys = _FileSystemsEntry.filesystems_keys elif len(keys) < 6: raise ValueError('Invalid key name array: {0}'.format(keys)) blk_lines = lines orddict = OrderedDict() orddict['name'] = blk_lines[0].split(':')[0].strip() blk_lines.pop(0) for line in blk_lines: if line.startswith('#'): raise cls.ParseError("Comment!") comps = line.split('= ') if len(comps) != 2: raise cls.ParseError("Invalid Entry!") key_name = comps[0].strip() if key_name in keys: orddict[key_name] = comps[1].strip() else: raise ValueError('Invalid name for use in filesystems: {0}'.format(key_name)) return orddict @classmethod def dict_from_cmd_line(cls, ipargs, keys): cmdln_dict = ipargs if keys: for key, value in keys: # ignore unknown or local scope keys if key.startswith('__'): continue if key in _FileSystemsEntry.compatibility_keys: cmdln_dict[key] = value return cmdln_dict @classmethod def from_line(cls, *args, **kwargs): return cls(** cls.dict_from_cmd_line(*args, **kwargs)) @classmethod def dict_to_lines(cls, fsys_dict_entry): entry = fsys_dict_entry strg_out = entry['name'] + ':' + os.linesep for k, v in six.viewitems(entry): if 'name' not in k: strg_out += '\t{0}\t\t= {1}'.format(k, v) + os.linesep strg_out += os.linesep return six.text_type(strg_out) def dict_from_entry(self): ret = OrderedDict() ret[self.criteria['name']] = self.criteria return ret def __str__(self): ''' String value, only works for full repr ''' return self.dict_to_lines(self.criteria) def __repr__(self): ''' Always works ''' return repr(self.criteria) def pick(self, keys): ''' Returns an instance with just those keys ''' subset = dict([(key, self.criteria[key]) for key in keys]) return self.__class__(**subset) def __init__(self, **criteria): ''' Store non-empty, non-null values to use as filter ''' items = [key_value for key_value in six.iteritems(criteria) if key_value[1] is not None] items = [(key_value1[0], six.text_type(key_value1[1])) for key_value1 in items] self.criteria = OrderedDict(items) @staticmethod def norm_path(path): ''' Resolve equivalent paths equivalently ''' return os.path.normcase(os.path.normpath(path)) def match(self, fsys_view): ''' Compare potentially partial criteria against built filesystems entry dictionary ''' evalue_dict = fsys_view[1] for key, value in six.viewitems(self.criteria): if key in evalue_dict: if evalue_dict[key] != value: return False else: return False return True def __getitem__(self, key): ''' Return value for input key ''' return self.criteria[key] def fstab(config='/etc/fstab'): ''' .. versionchanged:: 2016.3.2 List the contents of the fstab CLI Example: .. code-block:: bash salt '*' mount.fstab ''' ret = {} if not os.path.isfile(config): return ret with salt.utils.files.fopen(config) as ifile: for line in ifile: line = salt.utils.stringutils.to_unicode(line) try: if __grains__['kernel'] == 'SunOS': # Note: comments use in default vfstab file! if line[0] == '#': continue entry = _vfstab_entry.dict_from_line( line) else: entry = _fstab_entry.dict_from_line( line, _fstab_entry.compatibility_keys) entry['opts'] = entry['opts'].split(',') while entry['name'] in ret: entry['name'] += '_' ret[entry.pop('name')] = entry except _fstab_entry.ParseError: pass except _vfstab_entry.ParseError: pass return ret def vfstab(config='/etc/vfstab'): ''' .. versionadded:: 2016.3.2 List the contents of the vfstab CLI Example: .. code-block:: bash salt '*' mount.vfstab ''' # NOTE: vfstab is a wrapper for fstab return fstab(config) def rm_fstab(name, device, config='/etc/fstab'): ''' .. versionchanged:: 2016.3.2 Remove the mount point from the fstab CLI Example: .. code-block:: bash salt '*' mount.rm_fstab /mnt/foo /dev/sdg ''' modified = False if __grains__['kernel'] == 'SunOS': criteria = _vfstab_entry(name=name, device=device) else: criteria = _fstab_entry(name=name, device=device) lines = [] try: with salt.utils.files.fopen(config, 'r') as ifile: for line in ifile: line = salt.utils.stringutils.to_unicode(line) try: if criteria.match(line): modified = True else: lines.append(line) except _fstab_entry.ParseError: lines.append(line) except _vfstab_entry.ParseError: lines.append(line) except (IOError, OSError) as exc: msg = "Couldn't read from {0}: {1}" raise CommandExecutionError(msg.format(config, exc)) if modified: try: with salt.utils.files.fopen(config, 'wb') as ofile: ofile.writelines(salt.utils.data.encode(lines)) except (IOError, OSError) as exc: msg = "Couldn't write to {0}: {1}" raise CommandExecutionError(msg.format(config, exc)) # Note: not clear why we always return 'True' # --just copying previous behavior at this point... return True def rm_vfstab(name, device, config='/etc/vfstab'): ''' .. versionadded:: 2016.3.2 Remove the mount point from the vfstab CLI Example: .. code-block:: bash salt '*' mount.rm_vfstab /mnt/foo /device/c0t0d0p0 ''' ## NOTE: rm_vfstab is a wrapper for rm_fstab return rm_fstab(name, device, config) def set_fstab( name, device, fstype, opts='defaults', dump=0, pass_num=0, config='/etc/fstab', test=False, match_on='auto', **kwargs): ''' Verify that this mount is represented in the fstab, change the mount to match the data passed, or add the mount if it is not present. CLI Example: .. code-block:: bash salt '*' mount.set_fstab /mnt/foo /dev/sdz1 ext4 ''' # Fix the opts type if it is a list if isinstance(opts, list): opts = ','.join(opts) # preserve arguments for updating entry_args = { 'name': name, 'device': device.replace('\\ ', '\\040'), 'fstype': fstype, 'opts': opts.replace('\\ ', '\\040'), 'dump': dump, 'pass_num': pass_num, } lines = [] ret = None # Transform match_on into list--items will be checked later if isinstance(match_on, list): pass elif not isinstance(match_on, six.string_types): msg = 'match_on must be a string or list of strings' raise CommandExecutionError(msg) elif match_on == 'auto': # Try to guess right criteria for auto.... # NOTE: missing some special fstypes here specialFSes = frozenset([ 'none', 'tmpfs', 'sysfs', 'proc', 'fusectl', 'debugfs', 'securityfs', 'devtmpfs', 'cgroup', 'btrfs']) if fstype in specialFSes: match_on = ['name'] else: match_on = ['device'] else: match_on = [match_on] # generate entry and criteria objects, handle invalid keys in match_on entry = _fstab_entry(**entry_args) try: criteria = entry.pick(match_on) except KeyError: filterFn = lambda key: key not in _fstab_entry.fstab_keys invalid_keys = filter(filterFn, match_on) msg = 'Unrecognized keys in match_on: "{0}"'.format(invalid_keys) raise CommandExecutionError(msg) # parse file, use ret to cache status if not os.path.isfile(config): raise CommandExecutionError('Bad config file "{0}"'.format(config)) try: with salt.utils.files.fopen(config, 'r') as ifile: for line in ifile: line = salt.utils.stringutils.to_unicode(line) try: if criteria.match(line): # Note: If ret isn't None here, # we've matched multiple lines ret = 'present' if entry.match(line): lines.append(line) else: ret = 'change' lines.append(six.text_type(entry)) else: lines.append(line) except _fstab_entry.ParseError: lines.append(line) except (IOError, OSError) as exc: msg = 'Couldn\'t read from {0}: {1}' raise CommandExecutionError(msg.format(config, exc)) # add line if not present or changed if ret is None: lines.append(six.text_type(entry)) ret = 'new' if ret != 'present': # ret in ['new', 'change']: if not salt.utils.args.test_mode(test=test, **kwargs): try: with salt.utils.files.fopen(config, 'wb') as ofile: # The line was changed, commit it! ofile.writelines(salt.utils.data.encode(lines)) except (IOError, OSError): msg = 'File not writable {0}' raise CommandExecutionError(msg.format(config)) return ret def set_vfstab( name, device, fstype, opts='-', device_fsck='-', pass_fsck='-', mount_at_boot='yes', config='/etc/vfstab', test=False, match_on='auto', **kwargs): ''' ..verionadded:: 2016.3.2 Verify that this mount is represented in the fstab, change the mount to match the data passed, or add the mount if it is not present. CLI Example: .. code-block:: bash salt '*' mount.set_vfstab /mnt/foo /device/c0t0d0p0 ufs ''' # Fix the opts type if it is a list if isinstance(opts, list): opts = ','.join(opts) # Map unknown values for mount_at_boot to no if mount_at_boot != 'yes': mount_at_boot = 'no' # preserve arguments for updating entry_args = { 'name': name, 'device': device, 'fstype': fstype, 'opts': opts, 'device_fsck': device_fsck, 'pass_fsck': pass_fsck, 'mount_at_boot': mount_at_boot, } lines = [] ret = None # Transform match_on into list--items will be checked later if isinstance(match_on, list): pass elif not isinstance(match_on, six.string_types): msg = 'match_on must be a string or list of strings' raise CommandExecutionError(msg) elif match_on == 'auto': # Try to guess right criteria for auto.... # NOTE: missing some special fstypes here specialFSes = frozenset([ 'devfs', 'proc', 'ctfs', 'objfs', 'sharefs', 'fs', 'tmpfs']) if fstype in specialFSes: match_on = ['name'] else: match_on = ['device'] else: match_on = [match_on] # generate entry and criteria objects, handle invalid keys in match_on entry = _vfstab_entry(**entry_args) try: criteria = entry.pick(match_on) except KeyError: filterFn = lambda key: key not in _vfstab_entry.vfstab_keys invalid_keys = filter(filterFn, match_on) msg = 'Unrecognized keys in match_on: "{0}"'.format(invalid_keys) raise CommandExecutionError(msg) # parse file, use ret to cache status if not os.path.isfile(config): raise CommandExecutionError('Bad config file "{0}"'.format(config)) try: with salt.utils.files.fopen(config, 'r') as ifile: for line in ifile: line = salt.utils.stringutils.to_unicode(line) try: if criteria.match(line): # Note: If ret isn't None here, # we've matched multiple lines ret = 'present' if entry.match(line): lines.append(line) else: ret = 'change' lines.append(six.text_type(entry)) else: lines.append(line) except _vfstab_entry.ParseError: lines.append(line) except (IOError, OSError) as exc: msg = 'Couldn\'t read from {0}: {1}' raise CommandExecutionError(msg.format(config, exc)) # add line if not present or changed if ret is None: lines.append(six.text_type(entry)) ret = 'new' if ret != 'present': # ret in ['new', 'change']: if not salt.utils.args.test_mode(test=test, **kwargs): try: with salt.utils.files.fopen(config, 'wb') as ofile: # The line was changed, commit it! ofile.writelines(salt.utils.data.encode(lines)) except (IOError, OSError): msg = 'File not writable {0}' raise CommandExecutionError(msg.format(config)) return ret def rm_automaster(name, device, config='/etc/auto_salt'): ''' Remove the mount point from the auto_master CLI Example: .. code-block:: bash salt '*' mount.rm_automaster /mnt/foo /dev/sdg ''' contents = automaster(config) if name not in contents: return True # The entry is present, get rid of it lines = [] try: with salt.utils.files.fopen(config, 'r') as ifile: for line in ifile: line = salt.utils.stringutils.to_unicode(line) if line.startswith('#'): # Commented lines.append(line) continue if not line.strip(): # Blank line lines.append(line) continue comps = line.split() if len(comps) != 3: # Invalid entry lines.append(line) continue comps = line.split() prefix = "/.." name_chk = comps[0].replace(prefix, "") device_fmt = comps[2].split(":") if device: if name_chk == name and device_fmt[1] == device: continue else: if name_chk == name: continue lines.append(line) except (IOError, OSError) as exc: msg = "Couldn't read from {0}: {1}" raise CommandExecutionError(msg.format(config, exc)) try: with salt.utils.files.fopen(config, 'wb') as ofile: ofile.writelines(salt.utils.data.encode(lines)) except (IOError, OSError) as exc: msg = "Couldn't write to {0}: {1}" raise CommandExecutionError(msg.format(config, exc)) # Update automount __salt__['cmd.run']('automount -cv') return True def set_automaster( name, device, fstype, opts='', config='/etc/auto_salt', test=False, **kwargs): ''' Verify that this mount is represented in the auto_salt, change the mount to match the data passed, or add the mount if it is not present. CLI Example: .. code-block:: bash salt '*' mount.set_automaster /mnt/foo /dev/sdz1 ext4 ''' # Fix the opts type if it is a list if isinstance(opts, list): opts = ','.join(opts) lines = [] change = False present = False automaster_file = "/etc/auto_master" if not os.path.isfile(config): __salt__['file.touch'](config) __salt__['file.append'](automaster_file, "/-\t\t\t{0}".format(config)) name = "/..{0}".format(name) device_fmt = "{0}:{1}".format(fstype, device) type_opts = "-fstype={0},{1}".format(fstype, opts) if fstype == 'smbfs': device_fmt = device_fmt.replace(fstype, "") try: with salt.utils.files.fopen(config, 'r') as ifile: for line in ifile: line = salt.utils.stringutils.to_unicode(line) if line.startswith('#'): # Commented lines.append(line) continue if not line.strip(): # Blank line lines.append(line) continue comps = line.split() if len(comps) != 3: # Invalid entry lines.append(line) continue if comps[0] == name or comps[2] == device_fmt: # check to see if there are changes # and fix them if there are any present = True if comps[0] != name: change = True comps[0] = name if comps[1] != type_opts: change = True comps[1] = type_opts if comps[2] != device_fmt: change = True comps[2] = device_fmt if change: log.debug( 'auto_master entry for mount point %s needs to be ' 'updated', name ) newline = ( '{0}\t{1}\t{2}\n'.format( name, type_opts, device_fmt) ) lines.append(newline) else: lines.append(line) except (IOError, OSError) as exc: msg = 'Couldn\'t read from {0}: {1}' raise CommandExecutionError(msg.format(config, exc)) if change: if not salt.utils.args.test_mode(test=test, **kwargs): try: with salt.utils.files.fopen(config, 'wb') as ofile: # The line was changed, commit it! ofile.writelines(salt.utils.data.encode(lines)) except (IOError, OSError): msg = 'File not writable {0}' raise CommandExecutionError(msg.format(config)) return 'change' if not change: if present: # The right entry is already here return 'present' else: if not salt.utils.args.test_mode(test=test, **kwargs): # The entry is new, add it to the end of the fstab newline = ( '{0}\t{1}\t{2}\n'.format( name, type_opts, device_fmt) ) lines.append(newline) try: with salt.utils.files.fopen(config, 'wb') as ofile: # The line was changed, commit it! ofile.writelines(salt.utils.data.encode(lines)) except (IOError, OSError): raise CommandExecutionError( 'File not writable {0}'.format( config ) ) return 'new' def automaster(config='/etc/auto_salt'): ''' List the contents of the auto master CLI Example: .. code-block:: bash salt '*' mount.automaster ''' ret = {} if not os.path.isfile(config): return ret with salt.utils.files.fopen(config) as ifile: for line in ifile: line = salt.utils.stringutils.to_unicode(line) if line.startswith('#'): # Commented continue if not line.strip(): # Blank line continue comps = line.split() if len(comps) != 3: # Invalid entry continue prefix = "/.." name = comps[0].replace(prefix, "") device_fmt = comps[2].split(":") opts = comps[1].split(',') ret[name] = {'device': device_fmt[1], 'fstype': opts[0], 'opts': opts[1:]} return ret def mount(name, device, mkmnt=False, fstype='', opts='defaults', user=None, util='mount'): ''' Mount a device CLI Example: .. code-block:: bash salt '*' mount.mount /mnt/foo /dev/sdz1 True ''' if util != 'mount': # This functionality used to live in img.mount_image if util == 'guestfs': return __salt__['guestfs.mount'](name, root=device) elif util == 'qemu_nbd': mnt = __salt__['qemu_nbd.init'](name, device) if not mnt: return False first = next(six.iterkeys(mnt)) __context__['img.mnt_{0}'.format(first)] = mnt return first return False # Darwin doesn't expect defaults when mounting without other options if 'defaults' in opts and __grains__['os'] in ['MacOS', 'Darwin', 'AIX']: opts = None if isinstance(opts, six.string_types): opts = opts.split(',') if not os.path.exists(name) and mkmnt: __salt__['file.mkdir'](name, user=user) args = '' if opts is not None: lopts = ','.join(opts) args = '-o {0}'.format(lopts) if fstype: # use of fstype on AIX differs from typical Linux use of -t # functionality AIX uses -v vfsname, -t fstype mounts all with # fstype in /etc/filesystems if 'AIX' in __grains__['os']: args += ' -v {0}'.format(fstype) elif 'solaris' in __grains__['os'].lower(): args += ' -F {0}'.format(fstype) else: args += ' -t {0}'.format(fstype) cmd = 'mount {0} {1} {2} '.format(args, device, name) out = __salt__['cmd.run_all'](cmd, runas=user, python_shell=False) if out['retcode']: return out['stderr'] return True def remount(name, device, mkmnt=False, fstype='', opts='defaults', user=None): ''' Attempt to remount a device, if the device is not already mounted, mount is called CLI Example: .. code-block:: bash salt '*' mount.remount /mnt/foo /dev/sdz1 True ''' force_mount = False if __grains__['os'] in ['MacOS', 'Darwin']: if opts == 'defaults': opts = 'noowners' if fstype == 'smbfs': force_mount = True if 'AIX' in __grains__['os']: if opts == 'defaults': opts = [] if isinstance(opts, six.string_types): opts = opts.split(',') mnts = active() if name in mnts: # The mount point is mounted, attempt to remount it with the given data if 'remount' not in opts and __grains__['os'] not in ['OpenBSD', 'MacOS', 'Darwin']: opts.append('remount') if force_mount: # We need to force the mount but first we should unmount umount(name, device, user=user) lopts = ','.join(opts) args = '-o {0}'.format(lopts) if fstype: # use of fstype on AIX differs from typical Linux use of # -t functionality AIX uses -v vfsname, -t fstype mounts # all with fstype in /etc/filesystems if 'AIX' in __grains__['os']: args += ' -v {0}'.format(fstype) elif 'solaris' in __grains__['os'].lower(): args += ' -F {0}'.format(fstype) else: args += ' -t {0}'.format(fstype) if __grains__['os'] not in ['OpenBSD', 'MacOS', 'Darwin'] or force_mount: cmd = 'mount {0} {1} {2} '.format(args, device, name) else: cmd = 'mount -u {0} {1} {2} '.format(args, device, name) out = __salt__['cmd.run_all'](cmd, runas=user, python_shell=False) if out['retcode']: return out['stderr'] return True # Mount a filesystem that isn't already return mount(name, device, mkmnt, fstype, opts, user=user) def umount(name, device=None, user=None, util='mount'): ''' Attempt to unmount a device by specifying the directory it is mounted on CLI Example: .. code-block:: bash salt '*' mount.umount /mnt/foo .. versionadded:: 2015.5.0 .. code-block:: bash salt '*' mount.umount /mnt/foo /dev/xvdc1 ''' if util != 'mount': # This functionality used to live in img.umount_image if 'qemu_nbd.clear' in __salt__: if 'img.mnt_{0}'.format(name) in __context__: __salt__['qemu_nbd.clear'](__context__['img.mnt_{0}'.format(name)]) return mnts = active() if name not in mnts: return "{0} does not have anything mounted".format(name) if not device: cmd = 'umount {0}'.format(name) else: cmd = 'umount {0}'.format(device) out = __salt__['cmd.run_all'](cmd, runas=user, python_shell=False) if out['retcode']: return out['stderr'] return True def is_fuse_exec(cmd): ''' Returns true if the command passed is a fuse mountable application. CLI Example: .. code-block:: bash salt '*' mount.is_fuse_exec sshfs ''' cmd_path = salt.utils.path.which(cmd) # No point in running ldd on a command that doesn't exist if not cmd_path: return False elif not salt.utils.path.which('ldd'): raise CommandNotFoundError('ldd') out = __salt__['cmd.run']('ldd {0}'.format(cmd_path), python_shell=False) return 'libfuse' in out def swaps(): ''' Return a dict containing information on active swap .. versionchanged:: 2016.3.2 CLI Example: .. code-block:: bash salt '*' mount.swaps ''' ret = {} if __grains__['kernel'] == 'SunOS': for line in __salt__['cmd.run_stdout']('swap -l').splitlines(): if line.startswith('swapfile'): continue comps = line.split() ret[comps[0]] = {'type': 'device' if comps[0].startswith(('/dev', 'swap')) else 'file', 'size': int(comps[3]), 'used': (int(comps[3]) - int(comps[4])), 'priority': '-'} elif 'AIX' in __grains__['kernel']: for line in __salt__['cmd.run_stdout']('swap -l').splitlines(): if line.startswith('device'): continue comps = line.split() # AIX uses MB for units ret[comps[0]] = {'type': 'device', 'size': int(comps[3][:-2]) * 1024, 'used': (int(comps[3][:-2]) - int(comps[4][:-2])) * 1024, 'priority': '-'} elif __grains__['os'] != 'OpenBSD': with salt.utils.files.fopen('/proc/swaps') as fp_: for line in fp_: line = salt.utils.stringutils.to_unicode(line) if line.startswith('Filename'): continue comps = line.split() ret[comps[0]] = {'type': comps[1], 'size': comps[2], 'used': comps[3], 'priority': comps[4]} else: for line in __salt__['cmd.run_stdout']('swapctl -kl').splitlines(): if line.startswith(('Device', 'Total')): continue swap_type = "file" comps = line.split() if comps[0].startswith('/dev/'): swap_type = "partition" ret[comps[0]] = {'type': swap_type, 'size': comps[1], 'used': comps[2], 'priority': comps[5]} return ret def swapon(name, priority=None): ''' Activate a swap disk .. versionchanged:: 2016.3.2 CLI Example: .. code-block:: bash salt '*' mount.swapon /root/swapfile ''' ret = {} on_ = swaps() if name in on_: ret['stats'] = on_[name] ret['new'] = False return ret if __grains__['kernel'] == 'SunOS': if __grains__['virtual'] != 'zone': __salt__['cmd.run']('swap -a {0}'.format(name), python_shell=False) else: return False else: cmd = 'swapon {0}'.format(name) if priority and 'AIX' not in __grains__['kernel']: cmd += ' -p {0}'.format(priority) __salt__['cmd.run'](cmd, python_shell=False) on_ = swaps() if name in on_: ret['stats'] = on_[name] ret['new'] = True return ret return ret def swapoff(name): ''' Deactivate a named swap mount .. versionchanged:: 2016.3.2 CLI Example: .. code-block:: bash salt '*' mount.swapoff /root/swapfile ''' on_ = swaps() if name in on_: if __grains__['kernel'] == 'SunOS': if __grains__['virtual'] != 'zone': __salt__['cmd.run']('swap -a {0}'.format(name), python_shell=False) else: return False elif __grains__['os'] != 'OpenBSD': __salt__['cmd.run']('swapoff {0}'.format(name), python_shell=False) else: __salt__['cmd.run']('swapctl -d {0}'.format(name), python_shell=False) on_ = swaps() if name in on_: return False return True return None def is_mounted(name): ''' .. versionadded:: 2014.7.0 Provide information if the path is mounted CLI Example: .. code-block:: bash salt '*' mount.is_mounted /mnt/share ''' active_ = active() if name in active_: return True else: return False def read_mount_cache(name): ''' .. versionadded:: 2018.3.0 Provide information if the path is mounted CLI Example: .. code-block:: bash salt '*' mount.read_mount_cache /mnt/share ''' cache = salt.utils.mount.read_cache(__opts__) if cache: if 'mounts' in cache and cache['mounts']: if name in cache['mounts']: return cache['mounts'][name] return {} def write_mount_cache(real_name, device, mkmnt, fstype, mount_opts): ''' .. versionadded:: 2018.3.0 Provide information if the path is mounted :param real_name: The real name of the mount point where the device is mounted. :param device: The device that is being mounted. :param mkmnt: Whether or not the mount point should be created. :param fstype: The file system that is used. :param mount_opts: Additional options used when mounting the device. :return: Boolean if message was sent successfully. CLI Example: .. code-block:: bash salt '*' mount.write_mount_cache /mnt/share /dev/sda1 False ext4 defaults,nosuid ''' cache = salt.utils.mount.read_cache(__opts__) if not cache: cache = {} cache['mounts'] = {} else: if 'mounts' not in cache: cache['mounts'] = {} cache['mounts'][real_name] = {'device': device, 'fstype': fstype, 'mkmnt': mkmnt, 'opts': mount_opts} cache_write = salt.utils.mount.write_cache(cache, __opts__) if cache_write: return True else: raise CommandExecutionError('Unable to write mount cache.') def _filesystems(config='/etc/filesystems', leading_key=True): ''' Return the contents of the filesystems in an OrderedDict config File containing filesystem infomation leading_key True return dictionary keyed by 'name' and value as dictionary with other keys, values (name excluded) OrderedDict({ '/dir' : OrderedDict({'dev': '/dev/hd8', .... }})) False return dictionary keyed by 'name' and value as dictionary with all keys, values (name included) OrderedDict({ '/dir' : OrderedDict({'name': '/dir', 'dev': '/dev/hd8', ... })}) ''' ret = OrderedDict() lines = [] parsing_block = False if not os.path.isfile(config) or 'AIX' not in __grains__['kernel']: return ret # read in block of filesystems, block starts with '/' till empty line with salt.utils.files.fopen(config) as ifile: for line in ifile: line = salt.utils.stringutils.to_unicode(line) # skip till first entry if not line.startswith('/') and not parsing_block: continue if line.startswith('/'): parsing_block = True lines.append(line) elif not line.split(): parsing_block = False try: entry = _FileSystemsEntry.dict_from_lines( lines, _FileSystemsEntry.compatibility_keys) lines = [] if 'opts' in entry: entry['opts'] = entry['opts'].split(',') while entry['name'] in ret: entry['name'] += '_' if leading_key: ret[entry.pop('name')] = entry else: ret[entry['name']] = entry except _FileSystemsEntry.ParseError: pass else: lines.append(line) return ret def filesystems(config='/etc/filesystems'): ''' .. versionadded:: 2018.3.3 List the contents of the filesystems CLI Example: .. code-block:: bash salt '*' mount.filesystems ''' ret = {} if 'AIX' not in __grains__['kernel']: return ret ret_dict = _filesystems(config) if ret_dict: ret_key = next(iter(ret_dict.keys())) ret = {ret_key: dict(ret_dict[ret_key])} return ret def set_filesystems( name, device, vfstype, opts='-', mount='true', config='/etc/filesystems', test=False, match_on='auto', **kwargs): ''' .. versionadded:: 2018.3.3 Verify that this mount is represented in the filesystems, change the mount to match the data passed, or add the mount if it is not present on AIX Provide information if the path is mounted :param name: The name of the mount point where the device is mounted. :param device: The device that is being mounted. :param vfstype: The file system that is used (AIX has two fstypes, fstype and vfstype - similar to Linux fstype) :param opts: Additional options used when mounting the device. :param mount: Mount if not mounted, default True. :param config: Configuration file, default /etc/filesystems. :param match: File systems type to match on, default auto CLI Example: .. code-block:: bash salt '*' mount.set_filesystems /mnt/foo /dev/sdz1 jfs2 ''' # Fix the opts type if it is a list if isinstance(opts, list): opts = ','.join(opts) # preserve arguments for updating entry_args = { 'name': name, 'dev': device.replace('\\ ', '\\040'), 'vfstype': vfstype, 'opts': opts, 'mount': mount, } view_lines = [] ret = None if 'AIX' not in __grains__['kernel']: return ret # Transform match_on into list--items will be checked later if isinstance(match_on, list): pass elif not isinstance(match_on, six.string_types): raise CommandExecutionError('match_on must be a string or list of strings') elif match_on == 'auto': # Try to guess right criteria for auto.... # added IBM types from sys/vmount.h after btrfs # NOTE: missing some special fstypes here specialFSes = frozenset([ 'none', 'tmpfs', 'sysfs', 'proc', 'fusectl', 'debugfs', 'securityfs', 'devtmpfs', 'cgroup', 'btrfs', 'cdrfs', 'procfs', 'jfs', 'jfs2', 'nfs', 'sfs', 'nfs3', 'cachefs', 'udfs', 'cifs', 'namefs', 'pmemfs', 'ahafs', 'nfs4', 'autofs', 'stnfs']) if vfstype in specialFSes: match_on = ['name'] else: match_on = ['dev'] else: match_on = [match_on] # generate entry and criteria objects, handle invalid keys in match_on entry_ip = _FileSystemsEntry.from_line(entry_args, kwargs) try: criteria = entry_ip.pick(match_on) except KeyError: filterFn = lambda key: key not in _FileSystemsEntry.compatibility_keys invalid_keys = filter(filterFn, match_on) raise CommandExecutionError('Unrecognized keys in match_on: "{0}"'.format(invalid_keys)) # parse file, use ret to cache status if not os.path.isfile(config): raise CommandExecutionError('Bad config file "{0}"'.format(config)) # read in block of filesystem, block starts with '/' till empty line try: fsys_filedict = _filesystems(config, False) for fsys_view in six.viewitems(fsys_filedict): if criteria.match(fsys_view): ret = 'present' if entry_ip.match(fsys_view): view_lines.append(fsys_view) else: ret = 'change' kv = entry_ip['name'] view_lines.append((kv, entry_ip)) else: view_lines.append(fsys_view) except (IOError, OSError) as exc: raise CommandExecutionError('Couldn\'t read from {0}: {1}'.format(config, exc)) # add line if not present or changed if ret is None: for dict_view in six.viewitems(entry_ip.dict_from_entry()): view_lines.append(dict_view) ret = 'new' if ret != 'present': # ret in ['new', 'change']: try: with salt.utils.files.fopen(config, 'wb') as ofile: # The line was changed, commit it! for fsys_view in view_lines: entry = fsys_view[1] mystrg = _FileSystemsEntry.dict_to_lines(entry) ofile.writelines(salt.utils.data.encode(mystrg)) except (IOError, OSError): raise CommandExecutionError('File not writable {0}'.format(config)) return ret def rm_filesystems(name, device, config='/etc/filesystems'): ''' .. versionadded:: 2018.3.3 Remove the mount point from the filesystems CLI Example: .. code-block:: bash salt '*' mount.rm_filesystems /mnt/foo /dev/sdg ''' modified = False view_lines = [] if 'AIX' not in __grains__['kernel']: return modified criteria = _FileSystemsEntry(name=name, dev=device) try: fsys_filedict = _filesystems(config, False) for fsys_view in six.viewitems(fsys_filedict): try: if criteria.match(fsys_view): modified = True else: view_lines.append(fsys_view) except _FileSystemsEntry.ParseError: view_lines.append(fsys_view) except (IOError, OSError) as exc: raise CommandExecutionError("Couldn't read from {0}: {1}".format(config, exc)) if modified: try: with salt.utils.files.fopen(config, 'wb') as ofile: for fsys_view in view_lines: entry = fsys_view[1] mystrg = _FileSystemsEntry.dict_to_lines(entry) ofile.writelines(salt.utils.data.encode(mystrg)) except (IOError, OSError) as exc: raise CommandExecutionError("Couldn't write to {0}: {1}".format(config, exc)) return modified
saltstack/salt
salt/modules/mount.py
_filesystems
python
def _filesystems(config='/etc/filesystems', leading_key=True): ''' Return the contents of the filesystems in an OrderedDict config File containing filesystem infomation leading_key True return dictionary keyed by 'name' and value as dictionary with other keys, values (name excluded) OrderedDict({ '/dir' : OrderedDict({'dev': '/dev/hd8', .... }})) False return dictionary keyed by 'name' and value as dictionary with all keys, values (name included) OrderedDict({ '/dir' : OrderedDict({'name': '/dir', 'dev': '/dev/hd8', ... })}) ''' ret = OrderedDict() lines = [] parsing_block = False if not os.path.isfile(config) or 'AIX' not in __grains__['kernel']: return ret # read in block of filesystems, block starts with '/' till empty line with salt.utils.files.fopen(config) as ifile: for line in ifile: line = salt.utils.stringutils.to_unicode(line) # skip till first entry if not line.startswith('/') and not parsing_block: continue if line.startswith('/'): parsing_block = True lines.append(line) elif not line.split(): parsing_block = False try: entry = _FileSystemsEntry.dict_from_lines( lines, _FileSystemsEntry.compatibility_keys) lines = [] if 'opts' in entry: entry['opts'] = entry['opts'].split(',') while entry['name'] in ret: entry['name'] += '_' if leading_key: ret[entry.pop('name')] = entry else: ret[entry['name']] = entry except _FileSystemsEntry.ParseError: pass else: lines.append(line) return ret
Return the contents of the filesystems in an OrderedDict config File containing filesystem infomation leading_key True return dictionary keyed by 'name' and value as dictionary with other keys, values (name excluded) OrderedDict({ '/dir' : OrderedDict({'dev': '/dev/hd8', .... }})) False return dictionary keyed by 'name' and value as dictionary with all keys, values (name included) OrderedDict({ '/dir' : OrderedDict({'name': '/dir', 'dev': '/dev/hd8', ... })})
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/mount.py#L1585-L1639
[ "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 -*- ''' Salt module to manage Unix mounts and the fstab file ''' # Import python libs from __future__ import absolute_import, print_function, unicode_literals import os import re import logging # Import salt libs import salt.utils.args import salt.utils.data import salt.utils.files import salt.utils.path import salt.utils.platform import salt.utils.mount import salt.utils.stringutils from salt.utils.odict import OrderedDict from salt.exceptions import CommandNotFoundError, CommandExecutionError # Import 3rd-party libs from salt.ext import six from salt.ext.six.moves import filter, zip # pylint: disable=import-error,redefined-builtin # Set up logger log = logging.getLogger(__name__) # Define the module's virtual name __virtualname__ = 'mount' def __virtual__(): ''' Only load on POSIX-like systems ''' # Disable on Windows, a specific file module exists: if salt.utils.platform.is_windows(): return (False, 'The mount module cannot be loaded: not a POSIX-like system.') return True def _list_mounts(): ret = {} if __grains__['os'] in ['MacOS', 'Darwin']: mounts = __salt__['cmd.run_stdout']('mount') else: mounts = __salt__['cmd.run_stdout']('mount -l') for line in mounts.split('\n'): comps = re.sub(r"\s+", " ", line).split() if len(comps) >= 3: ret[comps[2]] = comps[0] return ret def _active_mountinfo(ret): _list = _list_mounts() filename = '/proc/self/mountinfo' if not os.access(filename, os.R_OK): msg = 'File not readable {0}' raise CommandExecutionError(msg.format(filename)) if 'disk.blkid' not in __context__: __context__['disk.blkid'] = __salt__['disk.blkid']() blkid_info = __context__['disk.blkid'] with salt.utils.files.fopen(filename) as ifile: for line in ifile: comps = salt.utils.stringutils.to_unicode(line).split() device = comps[2].split(':') # each line can have any number of # optional parameters, we use the # location of the separator field to # determine the location of the elements # after it. _sep = comps.index('-') device_name = comps[_sep + 2] device_uuid = None device_label = None if device_name: device_uuid = blkid_info.get(device_name, {}).get('UUID') device_uuid = device_uuid and device_uuid.lower() device_label = blkid_info.get(device_name, {}).get('LABEL') ret[comps[4]] = {'mountid': comps[0], 'parentid': comps[1], 'major': device[0], 'minor': device[1], 'root': comps[3], 'opts': _resolve_user_group_names(comps[5].split(',')), 'fstype': comps[_sep + 1], 'device': device_name.replace('\\040', '\\ '), 'alt_device': _list.get(comps[4], None), 'superopts': _resolve_user_group_names(comps[_sep + 3].split(',')), 'device_uuid': device_uuid, 'device_label': device_label} return ret def _active_mounts(ret): ''' List active mounts on Linux systems ''' _list = _list_mounts() filename = '/proc/self/mounts' if not os.access(filename, os.R_OK): msg = 'File not readable {0}' raise CommandExecutionError(msg.format(filename)) with salt.utils.files.fopen(filename) as ifile: for line in ifile: comps = salt.utils.stringutils.to_unicode(line).split() ret[comps[1]] = {'device': comps[0], 'alt_device': _list.get(comps[1], None), 'fstype': comps[2], 'opts': _resolve_user_group_names(comps[3].split(','))} return ret def _active_mounts_aix(ret): ''' List active mounts on AIX systems ''' for line in __salt__['cmd.run_stdout']('mount -p').split('\n'): comps = re.sub(r"\s+", " ", line).split() if comps: if comps[0] == 'node' or comps[0] == '--------': continue comps_len = len(comps) if line.startswith((' ', '\t')): curr_opts = _resolve_user_group_names(comps[6].split(',')) if 7 == comps_len else [] if curr_opts: ret[comps[1]] = {'device': comps[0], 'fstype': comps[2], 'opts': curr_opts} else: ret[comps[1]] = {'device': comps[0], 'fstype': comps[2]} else: curr_opts = _resolve_user_group_names(comps[7].split(',')) if 8 == comps_len else [] if curr_opts: ret[comps[2]] = {'node': comps[0], 'device': comps[1], 'fstype': comps[3], 'opts': curr_opts} else: ret[comps[2]] = {'node': comps[0], 'device': comps[1], 'fstype': comps[3]} return ret def _active_mounts_freebsd(ret): ''' List active mounts on FreeBSD systems ''' for line in __salt__['cmd.run_stdout']('mount -p').split('\n'): comps = re.sub(r"\s+", " ", line).split() ret[comps[1]] = {'device': comps[0], 'fstype': comps[2], 'opts': _resolve_user_group_names(comps[3].split(','))} return ret def _active_mounts_solaris(ret): ''' List active mounts on Solaris systems ''' for line in __salt__['cmd.run_stdout']('mount -v').split('\n'): comps = re.sub(r"\s+", " ", line).split() ret[comps[2]] = {'device': comps[0], 'fstype': comps[4], 'opts': _resolve_user_group_names(comps[5].split('/'))} return ret def _active_mounts_openbsd(ret): ''' List active mounts on OpenBSD systems ''' for line in __salt__['cmd.run_stdout']('mount -v').split('\n'): comps = re.sub(r"\s+", " ", line).split() parens = re.findall(r'\((.*?)\)', line, re.DOTALL) if len(parens) > 1: nod = __salt__['cmd.run_stdout']('ls -l {0}'.format(comps[0])) nod = ' '.join(nod.split()).split(" ") ret[comps[3]] = {'device': comps[0], 'fstype': comps[5], 'opts': _resolve_user_group_names(parens[1].split(", ")), 'major': six.text_type(nod[4].strip(",")), 'minor': six.text_type(nod[5]), 'device_uuid': parens[0]} else: ret[comps[2]] = {'device': comps[0], 'fstype': comps[4], 'opts': _resolve_user_group_names(parens[0].split(", "))} return ret def _active_mounts_darwin(ret): ''' List active mounts on Mac OS systems ''' for line in __salt__['cmd.run_stdout']('mount').split('\n'): comps = re.sub(r"\s+", " ", line).split() parens = re.findall(r'\((.*?)\)', line, re.DOTALL)[0].split(", ") ret[comps[2]] = {'device': comps[0], 'fstype': parens[0], 'opts': _resolve_user_group_names(parens[1:])} return ret def _resolve_user_group_names(opts): ''' Resolve user and group names in related opts ''' name_id_opts = {'uid': 'user.info', 'gid': 'group.info'} for ind, opt in enumerate(opts): if opt.split('=')[0] in name_id_opts: _givenid = opt.split('=')[1] _param = opt.split('=')[0] _id = _givenid if not re.match('[0-9]+$', _givenid): _info = __salt__[name_id_opts[_param]](_givenid) if _info and _param in _info: _id = _info[_param] opts[ind] = _param + '=' + six.text_type(_id) opts[ind] = opts[ind].replace('\\040', '\\ ') return opts def active(extended=False): ''' List the active mounts. CLI Example: .. code-block:: bash salt '*' mount.active ''' ret = {} if __grains__['os'] == 'FreeBSD': _active_mounts_freebsd(ret) elif 'AIX' in __grains__['kernel']: _active_mounts_aix(ret) elif __grains__['kernel'] == 'SunOS': _active_mounts_solaris(ret) elif __grains__['os'] == 'OpenBSD': _active_mounts_openbsd(ret) elif __grains__['os'] in ['MacOS', 'Darwin']: _active_mounts_darwin(ret) else: if extended: try: _active_mountinfo(ret) except CommandExecutionError: _active_mounts(ret) else: _active_mounts(ret) return ret class _fstab_entry(object): ''' Utility class for manipulating fstab entries. Primarily we're parsing, formatting, and comparing lines. Parsing emits dicts expected from fstab() or raises a ValueError. Note: We'll probably want to use os.normpath and os.normcase on 'name' ''' class ParseError(ValueError): ''' Error raised when a line isn't parsible as an fstab entry ''' fstab_keys = ('device', 'name', 'fstype', 'opts', 'dump', 'pass_num') # preserve data format compatibility_keys = ('device', 'name', 'fstype', 'opts', 'dump', 'pass') fstab_format = '{device}\t\t{name}\t{fstype}\t{opts}\t{dump} {pass_num}\n' @classmethod def dict_from_line(cls, line, keys=fstab_keys): if len(keys) != 6: raise ValueError('Invalid key array: {0}'.format(keys)) if line.startswith('#'): raise cls.ParseError("Comment!") comps = line.split() if len(comps) < 4 or len(comps) > 6: raise cls.ParseError("Invalid Entry!") comps.extend(['0'] * (len(keys) - len(comps))) return dict(zip(keys, comps)) @classmethod def from_line(cls, *args, **kwargs): return cls(** cls.dict_from_line(*args, **kwargs)) @classmethod def dict_to_line(cls, entry): return cls.fstab_format.format(**entry) def __str__(self): ''' String value, only works for full repr ''' return self.dict_to_line(self.criteria) def __repr__(self): ''' Always works ''' return repr(self.criteria) def pick(self, keys): ''' Returns an instance with just those keys ''' subset = dict([(key, self.criteria[key]) for key in keys]) return self.__class__(**subset) def __init__(self, **criteria): ''' Store non-empty, non-null values to use as filter ''' items = [key_value for key_value in six.iteritems(criteria) if key_value[1] is not None] items = [(key_value1[0], six.text_type(key_value1[1])) for key_value1 in items] self.criteria = dict(items) @staticmethod def norm_path(path): ''' Resolve equivalent paths equivalently ''' return os.path.normcase(os.path.normpath(path)) def match(self, line): ''' Compare potentially partial criteria against line ''' entry = self.dict_from_line(line) for key, value in six.iteritems(self.criteria): if entry[key] != value: return False return True class _vfstab_entry(object): ''' Utility class for manipulating vfstab entries. Primarily we're parsing, formatting, and comparing lines. Parsing emits dicts expected from fstab() or raises a ValueError. Note: We'll probably want to use os.normpath and os.normcase on 'name' Note: This parses vfstab entries on Solaris like systems #device device mount FS fsck mount mount #to mount to fsck point type pass at boot options # /devices - /devices devfs - no - ''' class ParseError(ValueError): '''Error raised when a line isn't parsible as an fstab entry''' vfstab_keys = ('device', 'device_fsck', 'name', 'fstype', 'pass_fsck', 'mount_at_boot', 'opts') # NOTE: weird formatting to match default spacing on Solaris vfstab_format = '{device:<11} {device_fsck:<3} {name:<19} {fstype:<8} {pass_fsck:<3} {mount_at_boot:<6} {opts}\n' @classmethod def dict_from_line(cls, line): if line.startswith('#'): raise cls.ParseError("Comment!") comps = line.split() if len(comps) != 7: raise cls.ParseError("Invalid Entry!") return dict(zip(cls.vfstab_keys, comps)) @classmethod def from_line(cls, *args, **kwargs): return cls(** cls.dict_from_line(*args, **kwargs)) @classmethod def dict_to_line(cls, entry): return cls.vfstab_format.format(**entry) def __str__(self): ''' String value, only works for full repr ''' return self.dict_to_line(self.criteria) def __repr__(self): ''' Always works ''' return repr(self.criteria) def pick(self, keys): ''' Returns an instance with just those keys ''' subset = dict([(key, self.criteria[key]) for key in keys]) return self.__class__(**subset) def __init__(self, **criteria): ''' Store non-empty, non-null values to use as filter ''' items = [key_value for key_value in six.iteritems(criteria) if key_value[1] is not None] items = [(key_value1[0], six.text_type(key_value1[1])) for key_value1 in items] self.criteria = dict(items) @staticmethod def norm_path(path): ''' Resolve equivalent paths equivalently ''' return os.path.normcase(os.path.normpath(path)) def match(self, line): ''' Compare potentially partial criteria against line ''' entry = self.dict_from_line(line) for key, value in six.iteritems(self.criteria): if entry[key] != value: return False return True class _FileSystemsEntry(object): ''' Utility class for manipulating filesystem entries. Primarily we're parsing, formatting, and comparing lines. Parsing emits dicts expected from fstab() or raises a ValueError. Note: We'll probably want to use os.normpath and os.normcase on 'name' ''' class ParseError(ValueError): ''' Error raised when a line isn't parsible as an fstab entry ''' filesystems_keys = ('device', 'name', 'fstype', 'vfstype', 'opts', 'mount') # preserve data format of filesystems compatibility_keys = ('dev', 'dev', 'name', 'fstype', 'vfstype', 'opts', 'mount', 'type', 'vfs', 'account', 'boot', 'check', 'free', 'nodename', 'quota', 'size', 'vol', 'log') @classmethod def dict_from_lines(cls, lines, keys=filesystems_keys): if len(lines) < 2: raise ValueError('Invalid number of lines: {0}'.format(lines)) if not keys: # if empty force default filesystems_keys keys = _FileSystemsEntry.filesystems_keys elif len(keys) < 6: raise ValueError('Invalid key name array: {0}'.format(keys)) blk_lines = lines orddict = OrderedDict() orddict['name'] = blk_lines[0].split(':')[0].strip() blk_lines.pop(0) for line in blk_lines: if line.startswith('#'): raise cls.ParseError("Comment!") comps = line.split('= ') if len(comps) != 2: raise cls.ParseError("Invalid Entry!") key_name = comps[0].strip() if key_name in keys: orddict[key_name] = comps[1].strip() else: raise ValueError('Invalid name for use in filesystems: {0}'.format(key_name)) return orddict @classmethod def dict_from_cmd_line(cls, ipargs, keys): cmdln_dict = ipargs if keys: for key, value in keys: # ignore unknown or local scope keys if key.startswith('__'): continue if key in _FileSystemsEntry.compatibility_keys: cmdln_dict[key] = value return cmdln_dict @classmethod def from_line(cls, *args, **kwargs): return cls(** cls.dict_from_cmd_line(*args, **kwargs)) @classmethod def dict_to_lines(cls, fsys_dict_entry): entry = fsys_dict_entry strg_out = entry['name'] + ':' + os.linesep for k, v in six.viewitems(entry): if 'name' not in k: strg_out += '\t{0}\t\t= {1}'.format(k, v) + os.linesep strg_out += os.linesep return six.text_type(strg_out) def dict_from_entry(self): ret = OrderedDict() ret[self.criteria['name']] = self.criteria return ret def __str__(self): ''' String value, only works for full repr ''' return self.dict_to_lines(self.criteria) def __repr__(self): ''' Always works ''' return repr(self.criteria) def pick(self, keys): ''' Returns an instance with just those keys ''' subset = dict([(key, self.criteria[key]) for key in keys]) return self.__class__(**subset) def __init__(self, **criteria): ''' Store non-empty, non-null values to use as filter ''' items = [key_value for key_value in six.iteritems(criteria) if key_value[1] is not None] items = [(key_value1[0], six.text_type(key_value1[1])) for key_value1 in items] self.criteria = OrderedDict(items) @staticmethod def norm_path(path): ''' Resolve equivalent paths equivalently ''' return os.path.normcase(os.path.normpath(path)) def match(self, fsys_view): ''' Compare potentially partial criteria against built filesystems entry dictionary ''' evalue_dict = fsys_view[1] for key, value in six.viewitems(self.criteria): if key in evalue_dict: if evalue_dict[key] != value: return False else: return False return True def __getitem__(self, key): ''' Return value for input key ''' return self.criteria[key] def fstab(config='/etc/fstab'): ''' .. versionchanged:: 2016.3.2 List the contents of the fstab CLI Example: .. code-block:: bash salt '*' mount.fstab ''' ret = {} if not os.path.isfile(config): return ret with salt.utils.files.fopen(config) as ifile: for line in ifile: line = salt.utils.stringutils.to_unicode(line) try: if __grains__['kernel'] == 'SunOS': # Note: comments use in default vfstab file! if line[0] == '#': continue entry = _vfstab_entry.dict_from_line( line) else: entry = _fstab_entry.dict_from_line( line, _fstab_entry.compatibility_keys) entry['opts'] = entry['opts'].split(',') while entry['name'] in ret: entry['name'] += '_' ret[entry.pop('name')] = entry except _fstab_entry.ParseError: pass except _vfstab_entry.ParseError: pass return ret def vfstab(config='/etc/vfstab'): ''' .. versionadded:: 2016.3.2 List the contents of the vfstab CLI Example: .. code-block:: bash salt '*' mount.vfstab ''' # NOTE: vfstab is a wrapper for fstab return fstab(config) def rm_fstab(name, device, config='/etc/fstab'): ''' .. versionchanged:: 2016.3.2 Remove the mount point from the fstab CLI Example: .. code-block:: bash salt '*' mount.rm_fstab /mnt/foo /dev/sdg ''' modified = False if __grains__['kernel'] == 'SunOS': criteria = _vfstab_entry(name=name, device=device) else: criteria = _fstab_entry(name=name, device=device) lines = [] try: with salt.utils.files.fopen(config, 'r') as ifile: for line in ifile: line = salt.utils.stringutils.to_unicode(line) try: if criteria.match(line): modified = True else: lines.append(line) except _fstab_entry.ParseError: lines.append(line) except _vfstab_entry.ParseError: lines.append(line) except (IOError, OSError) as exc: msg = "Couldn't read from {0}: {1}" raise CommandExecutionError(msg.format(config, exc)) if modified: try: with salt.utils.files.fopen(config, 'wb') as ofile: ofile.writelines(salt.utils.data.encode(lines)) except (IOError, OSError) as exc: msg = "Couldn't write to {0}: {1}" raise CommandExecutionError(msg.format(config, exc)) # Note: not clear why we always return 'True' # --just copying previous behavior at this point... return True def rm_vfstab(name, device, config='/etc/vfstab'): ''' .. versionadded:: 2016.3.2 Remove the mount point from the vfstab CLI Example: .. code-block:: bash salt '*' mount.rm_vfstab /mnt/foo /device/c0t0d0p0 ''' ## NOTE: rm_vfstab is a wrapper for rm_fstab return rm_fstab(name, device, config) def set_fstab( name, device, fstype, opts='defaults', dump=0, pass_num=0, config='/etc/fstab', test=False, match_on='auto', **kwargs): ''' Verify that this mount is represented in the fstab, change the mount to match the data passed, or add the mount if it is not present. CLI Example: .. code-block:: bash salt '*' mount.set_fstab /mnt/foo /dev/sdz1 ext4 ''' # Fix the opts type if it is a list if isinstance(opts, list): opts = ','.join(opts) # preserve arguments for updating entry_args = { 'name': name, 'device': device.replace('\\ ', '\\040'), 'fstype': fstype, 'opts': opts.replace('\\ ', '\\040'), 'dump': dump, 'pass_num': pass_num, } lines = [] ret = None # Transform match_on into list--items will be checked later if isinstance(match_on, list): pass elif not isinstance(match_on, six.string_types): msg = 'match_on must be a string or list of strings' raise CommandExecutionError(msg) elif match_on == 'auto': # Try to guess right criteria for auto.... # NOTE: missing some special fstypes here specialFSes = frozenset([ 'none', 'tmpfs', 'sysfs', 'proc', 'fusectl', 'debugfs', 'securityfs', 'devtmpfs', 'cgroup', 'btrfs']) if fstype in specialFSes: match_on = ['name'] else: match_on = ['device'] else: match_on = [match_on] # generate entry and criteria objects, handle invalid keys in match_on entry = _fstab_entry(**entry_args) try: criteria = entry.pick(match_on) except KeyError: filterFn = lambda key: key not in _fstab_entry.fstab_keys invalid_keys = filter(filterFn, match_on) msg = 'Unrecognized keys in match_on: "{0}"'.format(invalid_keys) raise CommandExecutionError(msg) # parse file, use ret to cache status if not os.path.isfile(config): raise CommandExecutionError('Bad config file "{0}"'.format(config)) try: with salt.utils.files.fopen(config, 'r') as ifile: for line in ifile: line = salt.utils.stringutils.to_unicode(line) try: if criteria.match(line): # Note: If ret isn't None here, # we've matched multiple lines ret = 'present' if entry.match(line): lines.append(line) else: ret = 'change' lines.append(six.text_type(entry)) else: lines.append(line) except _fstab_entry.ParseError: lines.append(line) except (IOError, OSError) as exc: msg = 'Couldn\'t read from {0}: {1}' raise CommandExecutionError(msg.format(config, exc)) # add line if not present or changed if ret is None: lines.append(six.text_type(entry)) ret = 'new' if ret != 'present': # ret in ['new', 'change']: if not salt.utils.args.test_mode(test=test, **kwargs): try: with salt.utils.files.fopen(config, 'wb') as ofile: # The line was changed, commit it! ofile.writelines(salt.utils.data.encode(lines)) except (IOError, OSError): msg = 'File not writable {0}' raise CommandExecutionError(msg.format(config)) return ret def set_vfstab( name, device, fstype, opts='-', device_fsck='-', pass_fsck='-', mount_at_boot='yes', config='/etc/vfstab', test=False, match_on='auto', **kwargs): ''' ..verionadded:: 2016.3.2 Verify that this mount is represented in the fstab, change the mount to match the data passed, or add the mount if it is not present. CLI Example: .. code-block:: bash salt '*' mount.set_vfstab /mnt/foo /device/c0t0d0p0 ufs ''' # Fix the opts type if it is a list if isinstance(opts, list): opts = ','.join(opts) # Map unknown values for mount_at_boot to no if mount_at_boot != 'yes': mount_at_boot = 'no' # preserve arguments for updating entry_args = { 'name': name, 'device': device, 'fstype': fstype, 'opts': opts, 'device_fsck': device_fsck, 'pass_fsck': pass_fsck, 'mount_at_boot': mount_at_boot, } lines = [] ret = None # Transform match_on into list--items will be checked later if isinstance(match_on, list): pass elif not isinstance(match_on, six.string_types): msg = 'match_on must be a string or list of strings' raise CommandExecutionError(msg) elif match_on == 'auto': # Try to guess right criteria for auto.... # NOTE: missing some special fstypes here specialFSes = frozenset([ 'devfs', 'proc', 'ctfs', 'objfs', 'sharefs', 'fs', 'tmpfs']) if fstype in specialFSes: match_on = ['name'] else: match_on = ['device'] else: match_on = [match_on] # generate entry and criteria objects, handle invalid keys in match_on entry = _vfstab_entry(**entry_args) try: criteria = entry.pick(match_on) except KeyError: filterFn = lambda key: key not in _vfstab_entry.vfstab_keys invalid_keys = filter(filterFn, match_on) msg = 'Unrecognized keys in match_on: "{0}"'.format(invalid_keys) raise CommandExecutionError(msg) # parse file, use ret to cache status if not os.path.isfile(config): raise CommandExecutionError('Bad config file "{0}"'.format(config)) try: with salt.utils.files.fopen(config, 'r') as ifile: for line in ifile: line = salt.utils.stringutils.to_unicode(line) try: if criteria.match(line): # Note: If ret isn't None here, # we've matched multiple lines ret = 'present' if entry.match(line): lines.append(line) else: ret = 'change' lines.append(six.text_type(entry)) else: lines.append(line) except _vfstab_entry.ParseError: lines.append(line) except (IOError, OSError) as exc: msg = 'Couldn\'t read from {0}: {1}' raise CommandExecutionError(msg.format(config, exc)) # add line if not present or changed if ret is None: lines.append(six.text_type(entry)) ret = 'new' if ret != 'present': # ret in ['new', 'change']: if not salt.utils.args.test_mode(test=test, **kwargs): try: with salt.utils.files.fopen(config, 'wb') as ofile: # The line was changed, commit it! ofile.writelines(salt.utils.data.encode(lines)) except (IOError, OSError): msg = 'File not writable {0}' raise CommandExecutionError(msg.format(config)) return ret def rm_automaster(name, device, config='/etc/auto_salt'): ''' Remove the mount point from the auto_master CLI Example: .. code-block:: bash salt '*' mount.rm_automaster /mnt/foo /dev/sdg ''' contents = automaster(config) if name not in contents: return True # The entry is present, get rid of it lines = [] try: with salt.utils.files.fopen(config, 'r') as ifile: for line in ifile: line = salt.utils.stringutils.to_unicode(line) if line.startswith('#'): # Commented lines.append(line) continue if not line.strip(): # Blank line lines.append(line) continue comps = line.split() if len(comps) != 3: # Invalid entry lines.append(line) continue comps = line.split() prefix = "/.." name_chk = comps[0].replace(prefix, "") device_fmt = comps[2].split(":") if device: if name_chk == name and device_fmt[1] == device: continue else: if name_chk == name: continue lines.append(line) except (IOError, OSError) as exc: msg = "Couldn't read from {0}: {1}" raise CommandExecutionError(msg.format(config, exc)) try: with salt.utils.files.fopen(config, 'wb') as ofile: ofile.writelines(salt.utils.data.encode(lines)) except (IOError, OSError) as exc: msg = "Couldn't write to {0}: {1}" raise CommandExecutionError(msg.format(config, exc)) # Update automount __salt__['cmd.run']('automount -cv') return True def set_automaster( name, device, fstype, opts='', config='/etc/auto_salt', test=False, **kwargs): ''' Verify that this mount is represented in the auto_salt, change the mount to match the data passed, or add the mount if it is not present. CLI Example: .. code-block:: bash salt '*' mount.set_automaster /mnt/foo /dev/sdz1 ext4 ''' # Fix the opts type if it is a list if isinstance(opts, list): opts = ','.join(opts) lines = [] change = False present = False automaster_file = "/etc/auto_master" if not os.path.isfile(config): __salt__['file.touch'](config) __salt__['file.append'](automaster_file, "/-\t\t\t{0}".format(config)) name = "/..{0}".format(name) device_fmt = "{0}:{1}".format(fstype, device) type_opts = "-fstype={0},{1}".format(fstype, opts) if fstype == 'smbfs': device_fmt = device_fmt.replace(fstype, "") try: with salt.utils.files.fopen(config, 'r') as ifile: for line in ifile: line = salt.utils.stringutils.to_unicode(line) if line.startswith('#'): # Commented lines.append(line) continue if not line.strip(): # Blank line lines.append(line) continue comps = line.split() if len(comps) != 3: # Invalid entry lines.append(line) continue if comps[0] == name or comps[2] == device_fmt: # check to see if there are changes # and fix them if there are any present = True if comps[0] != name: change = True comps[0] = name if comps[1] != type_opts: change = True comps[1] = type_opts if comps[2] != device_fmt: change = True comps[2] = device_fmt if change: log.debug( 'auto_master entry for mount point %s needs to be ' 'updated', name ) newline = ( '{0}\t{1}\t{2}\n'.format( name, type_opts, device_fmt) ) lines.append(newline) else: lines.append(line) except (IOError, OSError) as exc: msg = 'Couldn\'t read from {0}: {1}' raise CommandExecutionError(msg.format(config, exc)) if change: if not salt.utils.args.test_mode(test=test, **kwargs): try: with salt.utils.files.fopen(config, 'wb') as ofile: # The line was changed, commit it! ofile.writelines(salt.utils.data.encode(lines)) except (IOError, OSError): msg = 'File not writable {0}' raise CommandExecutionError(msg.format(config)) return 'change' if not change: if present: # The right entry is already here return 'present' else: if not salt.utils.args.test_mode(test=test, **kwargs): # The entry is new, add it to the end of the fstab newline = ( '{0}\t{1}\t{2}\n'.format( name, type_opts, device_fmt) ) lines.append(newline) try: with salt.utils.files.fopen(config, 'wb') as ofile: # The line was changed, commit it! ofile.writelines(salt.utils.data.encode(lines)) except (IOError, OSError): raise CommandExecutionError( 'File not writable {0}'.format( config ) ) return 'new' def automaster(config='/etc/auto_salt'): ''' List the contents of the auto master CLI Example: .. code-block:: bash salt '*' mount.automaster ''' ret = {} if not os.path.isfile(config): return ret with salt.utils.files.fopen(config) as ifile: for line in ifile: line = salt.utils.stringutils.to_unicode(line) if line.startswith('#'): # Commented continue if not line.strip(): # Blank line continue comps = line.split() if len(comps) != 3: # Invalid entry continue prefix = "/.." name = comps[0].replace(prefix, "") device_fmt = comps[2].split(":") opts = comps[1].split(',') ret[name] = {'device': device_fmt[1], 'fstype': opts[0], 'opts': opts[1:]} return ret def mount(name, device, mkmnt=False, fstype='', opts='defaults', user=None, util='mount'): ''' Mount a device CLI Example: .. code-block:: bash salt '*' mount.mount /mnt/foo /dev/sdz1 True ''' if util != 'mount': # This functionality used to live in img.mount_image if util == 'guestfs': return __salt__['guestfs.mount'](name, root=device) elif util == 'qemu_nbd': mnt = __salt__['qemu_nbd.init'](name, device) if not mnt: return False first = next(six.iterkeys(mnt)) __context__['img.mnt_{0}'.format(first)] = mnt return first return False # Darwin doesn't expect defaults when mounting without other options if 'defaults' in opts and __grains__['os'] in ['MacOS', 'Darwin', 'AIX']: opts = None if isinstance(opts, six.string_types): opts = opts.split(',') if not os.path.exists(name) and mkmnt: __salt__['file.mkdir'](name, user=user) args = '' if opts is not None: lopts = ','.join(opts) args = '-o {0}'.format(lopts) if fstype: # use of fstype on AIX differs from typical Linux use of -t # functionality AIX uses -v vfsname, -t fstype mounts all with # fstype in /etc/filesystems if 'AIX' in __grains__['os']: args += ' -v {0}'.format(fstype) elif 'solaris' in __grains__['os'].lower(): args += ' -F {0}'.format(fstype) else: args += ' -t {0}'.format(fstype) cmd = 'mount {0} {1} {2} '.format(args, device, name) out = __salt__['cmd.run_all'](cmd, runas=user, python_shell=False) if out['retcode']: return out['stderr'] return True def remount(name, device, mkmnt=False, fstype='', opts='defaults', user=None): ''' Attempt to remount a device, if the device is not already mounted, mount is called CLI Example: .. code-block:: bash salt '*' mount.remount /mnt/foo /dev/sdz1 True ''' force_mount = False if __grains__['os'] in ['MacOS', 'Darwin']: if opts == 'defaults': opts = 'noowners' if fstype == 'smbfs': force_mount = True if 'AIX' in __grains__['os']: if opts == 'defaults': opts = [] if isinstance(opts, six.string_types): opts = opts.split(',') mnts = active() if name in mnts: # The mount point is mounted, attempt to remount it with the given data if 'remount' not in opts and __grains__['os'] not in ['OpenBSD', 'MacOS', 'Darwin']: opts.append('remount') if force_mount: # We need to force the mount but first we should unmount umount(name, device, user=user) lopts = ','.join(opts) args = '-o {0}'.format(lopts) if fstype: # use of fstype on AIX differs from typical Linux use of # -t functionality AIX uses -v vfsname, -t fstype mounts # all with fstype in /etc/filesystems if 'AIX' in __grains__['os']: args += ' -v {0}'.format(fstype) elif 'solaris' in __grains__['os'].lower(): args += ' -F {0}'.format(fstype) else: args += ' -t {0}'.format(fstype) if __grains__['os'] not in ['OpenBSD', 'MacOS', 'Darwin'] or force_mount: cmd = 'mount {0} {1} {2} '.format(args, device, name) else: cmd = 'mount -u {0} {1} {2} '.format(args, device, name) out = __salt__['cmd.run_all'](cmd, runas=user, python_shell=False) if out['retcode']: return out['stderr'] return True # Mount a filesystem that isn't already return mount(name, device, mkmnt, fstype, opts, user=user) def umount(name, device=None, user=None, util='mount'): ''' Attempt to unmount a device by specifying the directory it is mounted on CLI Example: .. code-block:: bash salt '*' mount.umount /mnt/foo .. versionadded:: 2015.5.0 .. code-block:: bash salt '*' mount.umount /mnt/foo /dev/xvdc1 ''' if util != 'mount': # This functionality used to live in img.umount_image if 'qemu_nbd.clear' in __salt__: if 'img.mnt_{0}'.format(name) in __context__: __salt__['qemu_nbd.clear'](__context__['img.mnt_{0}'.format(name)]) return mnts = active() if name not in mnts: return "{0} does not have anything mounted".format(name) if not device: cmd = 'umount {0}'.format(name) else: cmd = 'umount {0}'.format(device) out = __salt__['cmd.run_all'](cmd, runas=user, python_shell=False) if out['retcode']: return out['stderr'] return True def is_fuse_exec(cmd): ''' Returns true if the command passed is a fuse mountable application. CLI Example: .. code-block:: bash salt '*' mount.is_fuse_exec sshfs ''' cmd_path = salt.utils.path.which(cmd) # No point in running ldd on a command that doesn't exist if not cmd_path: return False elif not salt.utils.path.which('ldd'): raise CommandNotFoundError('ldd') out = __salt__['cmd.run']('ldd {0}'.format(cmd_path), python_shell=False) return 'libfuse' in out def swaps(): ''' Return a dict containing information on active swap .. versionchanged:: 2016.3.2 CLI Example: .. code-block:: bash salt '*' mount.swaps ''' ret = {} if __grains__['kernel'] == 'SunOS': for line in __salt__['cmd.run_stdout']('swap -l').splitlines(): if line.startswith('swapfile'): continue comps = line.split() ret[comps[0]] = {'type': 'device' if comps[0].startswith(('/dev', 'swap')) else 'file', 'size': int(comps[3]), 'used': (int(comps[3]) - int(comps[4])), 'priority': '-'} elif 'AIX' in __grains__['kernel']: for line in __salt__['cmd.run_stdout']('swap -l').splitlines(): if line.startswith('device'): continue comps = line.split() # AIX uses MB for units ret[comps[0]] = {'type': 'device', 'size': int(comps[3][:-2]) * 1024, 'used': (int(comps[3][:-2]) - int(comps[4][:-2])) * 1024, 'priority': '-'} elif __grains__['os'] != 'OpenBSD': with salt.utils.files.fopen('/proc/swaps') as fp_: for line in fp_: line = salt.utils.stringutils.to_unicode(line) if line.startswith('Filename'): continue comps = line.split() ret[comps[0]] = {'type': comps[1], 'size': comps[2], 'used': comps[3], 'priority': comps[4]} else: for line in __salt__['cmd.run_stdout']('swapctl -kl').splitlines(): if line.startswith(('Device', 'Total')): continue swap_type = "file" comps = line.split() if comps[0].startswith('/dev/'): swap_type = "partition" ret[comps[0]] = {'type': swap_type, 'size': comps[1], 'used': comps[2], 'priority': comps[5]} return ret def swapon(name, priority=None): ''' Activate a swap disk .. versionchanged:: 2016.3.2 CLI Example: .. code-block:: bash salt '*' mount.swapon /root/swapfile ''' ret = {} on_ = swaps() if name in on_: ret['stats'] = on_[name] ret['new'] = False return ret if __grains__['kernel'] == 'SunOS': if __grains__['virtual'] != 'zone': __salt__['cmd.run']('swap -a {0}'.format(name), python_shell=False) else: return False else: cmd = 'swapon {0}'.format(name) if priority and 'AIX' not in __grains__['kernel']: cmd += ' -p {0}'.format(priority) __salt__['cmd.run'](cmd, python_shell=False) on_ = swaps() if name in on_: ret['stats'] = on_[name] ret['new'] = True return ret return ret def swapoff(name): ''' Deactivate a named swap mount .. versionchanged:: 2016.3.2 CLI Example: .. code-block:: bash salt '*' mount.swapoff /root/swapfile ''' on_ = swaps() if name in on_: if __grains__['kernel'] == 'SunOS': if __grains__['virtual'] != 'zone': __salt__['cmd.run']('swap -a {0}'.format(name), python_shell=False) else: return False elif __grains__['os'] != 'OpenBSD': __salt__['cmd.run']('swapoff {0}'.format(name), python_shell=False) else: __salt__['cmd.run']('swapctl -d {0}'.format(name), python_shell=False) on_ = swaps() if name in on_: return False return True return None def is_mounted(name): ''' .. versionadded:: 2014.7.0 Provide information if the path is mounted CLI Example: .. code-block:: bash salt '*' mount.is_mounted /mnt/share ''' active_ = active() if name in active_: return True else: return False def read_mount_cache(name): ''' .. versionadded:: 2018.3.0 Provide information if the path is mounted CLI Example: .. code-block:: bash salt '*' mount.read_mount_cache /mnt/share ''' cache = salt.utils.mount.read_cache(__opts__) if cache: if 'mounts' in cache and cache['mounts']: if name in cache['mounts']: return cache['mounts'][name] return {} def write_mount_cache(real_name, device, mkmnt, fstype, mount_opts): ''' .. versionadded:: 2018.3.0 Provide information if the path is mounted :param real_name: The real name of the mount point where the device is mounted. :param device: The device that is being mounted. :param mkmnt: Whether or not the mount point should be created. :param fstype: The file system that is used. :param mount_opts: Additional options used when mounting the device. :return: Boolean if message was sent successfully. CLI Example: .. code-block:: bash salt '*' mount.write_mount_cache /mnt/share /dev/sda1 False ext4 defaults,nosuid ''' cache = salt.utils.mount.read_cache(__opts__) if not cache: cache = {} cache['mounts'] = {} else: if 'mounts' not in cache: cache['mounts'] = {} cache['mounts'][real_name] = {'device': device, 'fstype': fstype, 'mkmnt': mkmnt, 'opts': mount_opts} cache_write = salt.utils.mount.write_cache(cache, __opts__) if cache_write: return True else: raise CommandExecutionError('Unable to write mount cache.') def delete_mount_cache(real_name): ''' .. versionadded:: 2018.3.0 Provide information if the path is mounted CLI Example: .. code-block:: bash salt '*' mount.delete_mount_cache /mnt/share ''' cache = salt.utils.mount.read_cache(__opts__) if cache: if 'mounts' in cache: if real_name in cache['mounts']: del cache['mounts'][real_name] cache_write = salt.utils.mount.write_cache(cache, __opts__) if not cache_write: raise CommandExecutionError('Unable to write mount cache.') return True def filesystems(config='/etc/filesystems'): ''' .. versionadded:: 2018.3.3 List the contents of the filesystems CLI Example: .. code-block:: bash salt '*' mount.filesystems ''' ret = {} if 'AIX' not in __grains__['kernel']: return ret ret_dict = _filesystems(config) if ret_dict: ret_key = next(iter(ret_dict.keys())) ret = {ret_key: dict(ret_dict[ret_key])} return ret def set_filesystems( name, device, vfstype, opts='-', mount='true', config='/etc/filesystems', test=False, match_on='auto', **kwargs): ''' .. versionadded:: 2018.3.3 Verify that this mount is represented in the filesystems, change the mount to match the data passed, or add the mount if it is not present on AIX Provide information if the path is mounted :param name: The name of the mount point where the device is mounted. :param device: The device that is being mounted. :param vfstype: The file system that is used (AIX has two fstypes, fstype and vfstype - similar to Linux fstype) :param opts: Additional options used when mounting the device. :param mount: Mount if not mounted, default True. :param config: Configuration file, default /etc/filesystems. :param match: File systems type to match on, default auto CLI Example: .. code-block:: bash salt '*' mount.set_filesystems /mnt/foo /dev/sdz1 jfs2 ''' # Fix the opts type if it is a list if isinstance(opts, list): opts = ','.join(opts) # preserve arguments for updating entry_args = { 'name': name, 'dev': device.replace('\\ ', '\\040'), 'vfstype': vfstype, 'opts': opts, 'mount': mount, } view_lines = [] ret = None if 'AIX' not in __grains__['kernel']: return ret # Transform match_on into list--items will be checked later if isinstance(match_on, list): pass elif not isinstance(match_on, six.string_types): raise CommandExecutionError('match_on must be a string or list of strings') elif match_on == 'auto': # Try to guess right criteria for auto.... # added IBM types from sys/vmount.h after btrfs # NOTE: missing some special fstypes here specialFSes = frozenset([ 'none', 'tmpfs', 'sysfs', 'proc', 'fusectl', 'debugfs', 'securityfs', 'devtmpfs', 'cgroup', 'btrfs', 'cdrfs', 'procfs', 'jfs', 'jfs2', 'nfs', 'sfs', 'nfs3', 'cachefs', 'udfs', 'cifs', 'namefs', 'pmemfs', 'ahafs', 'nfs4', 'autofs', 'stnfs']) if vfstype in specialFSes: match_on = ['name'] else: match_on = ['dev'] else: match_on = [match_on] # generate entry and criteria objects, handle invalid keys in match_on entry_ip = _FileSystemsEntry.from_line(entry_args, kwargs) try: criteria = entry_ip.pick(match_on) except KeyError: filterFn = lambda key: key not in _FileSystemsEntry.compatibility_keys invalid_keys = filter(filterFn, match_on) raise CommandExecutionError('Unrecognized keys in match_on: "{0}"'.format(invalid_keys)) # parse file, use ret to cache status if not os.path.isfile(config): raise CommandExecutionError('Bad config file "{0}"'.format(config)) # read in block of filesystem, block starts with '/' till empty line try: fsys_filedict = _filesystems(config, False) for fsys_view in six.viewitems(fsys_filedict): if criteria.match(fsys_view): ret = 'present' if entry_ip.match(fsys_view): view_lines.append(fsys_view) else: ret = 'change' kv = entry_ip['name'] view_lines.append((kv, entry_ip)) else: view_lines.append(fsys_view) except (IOError, OSError) as exc: raise CommandExecutionError('Couldn\'t read from {0}: {1}'.format(config, exc)) # add line if not present or changed if ret is None: for dict_view in six.viewitems(entry_ip.dict_from_entry()): view_lines.append(dict_view) ret = 'new' if ret != 'present': # ret in ['new', 'change']: try: with salt.utils.files.fopen(config, 'wb') as ofile: # The line was changed, commit it! for fsys_view in view_lines: entry = fsys_view[1] mystrg = _FileSystemsEntry.dict_to_lines(entry) ofile.writelines(salt.utils.data.encode(mystrg)) except (IOError, OSError): raise CommandExecutionError('File not writable {0}'.format(config)) return ret def rm_filesystems(name, device, config='/etc/filesystems'): ''' .. versionadded:: 2018.3.3 Remove the mount point from the filesystems CLI Example: .. code-block:: bash salt '*' mount.rm_filesystems /mnt/foo /dev/sdg ''' modified = False view_lines = [] if 'AIX' not in __grains__['kernel']: return modified criteria = _FileSystemsEntry(name=name, dev=device) try: fsys_filedict = _filesystems(config, False) for fsys_view in six.viewitems(fsys_filedict): try: if criteria.match(fsys_view): modified = True else: view_lines.append(fsys_view) except _FileSystemsEntry.ParseError: view_lines.append(fsys_view) except (IOError, OSError) as exc: raise CommandExecutionError("Couldn't read from {0}: {1}".format(config, exc)) if modified: try: with salt.utils.files.fopen(config, 'wb') as ofile: for fsys_view in view_lines: entry = fsys_view[1] mystrg = _FileSystemsEntry.dict_to_lines(entry) ofile.writelines(salt.utils.data.encode(mystrg)) except (IOError, OSError) as exc: raise CommandExecutionError("Couldn't write to {0}: {1}".format(config, exc)) return modified
saltstack/salt
salt/modules/mount.py
filesystems
python
def filesystems(config='/etc/filesystems'): ''' .. versionadded:: 2018.3.3 List the contents of the filesystems CLI Example: .. code-block:: bash salt '*' mount.filesystems ''' ret = {} if 'AIX' not in __grains__['kernel']: return ret ret_dict = _filesystems(config) if ret_dict: ret_key = next(iter(ret_dict.keys())) ret = {ret_key: dict(ret_dict[ret_key])} return ret
.. versionadded:: 2018.3.3 List the contents of the filesystems CLI Example: .. code-block:: bash salt '*' mount.filesystems
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/mount.py#L1642-L1663
[ "def _filesystems(config='/etc/filesystems', leading_key=True):\n '''\n Return the contents of the filesystems in an OrderedDict\n\n config\n File containing filesystem infomation\n\n leading_key\n True return dictionary keyed by 'name' and value as dictionary with other keys, values (name excluded)\n OrderedDict({ '/dir' : OrderedDict({'dev': '/dev/hd8', .... }}))\n\n False return dictionary keyed by 'name' and value as dictionary with all keys, values (name included)\n OrderedDict({ '/dir' : OrderedDict({'name': '/dir', 'dev': '/dev/hd8', ... })})\n '''\n ret = OrderedDict()\n lines = []\n parsing_block = False\n if not os.path.isfile(config) or 'AIX' not in __grains__['kernel']:\n return ret\n\n # read in block of filesystems, block starts with '/' till empty line\n with salt.utils.files.fopen(config) as ifile:\n for line in ifile:\n line = salt.utils.stringutils.to_unicode(line)\n\n # skip till first entry\n if not line.startswith('/') and not parsing_block:\n continue\n\n if line.startswith('/'):\n parsing_block = True\n lines.append(line)\n elif not line.split():\n parsing_block = False\n try:\n entry = _FileSystemsEntry.dict_from_lines(\n lines,\n _FileSystemsEntry.compatibility_keys)\n lines = []\n if 'opts' in entry:\n entry['opts'] = entry['opts'].split(',')\n while entry['name'] in ret:\n entry['name'] += '_'\n\n if leading_key:\n ret[entry.pop('name')] = entry\n else:\n ret[entry['name']] = entry\n\n except _FileSystemsEntry.ParseError:\n pass\n else:\n lines.append(line)\n\n return ret\n", "def keys(self):\n 'od.keys() -> list of keys in od'\n return list(self)\n" ]
# -*- coding: utf-8 -*- ''' Salt module to manage Unix mounts and the fstab file ''' # Import python libs from __future__ import absolute_import, print_function, unicode_literals import os import re import logging # Import salt libs import salt.utils.args import salt.utils.data import salt.utils.files import salt.utils.path import salt.utils.platform import salt.utils.mount import salt.utils.stringutils from salt.utils.odict import OrderedDict from salt.exceptions import CommandNotFoundError, CommandExecutionError # Import 3rd-party libs from salt.ext import six from salt.ext.six.moves import filter, zip # pylint: disable=import-error,redefined-builtin # Set up logger log = logging.getLogger(__name__) # Define the module's virtual name __virtualname__ = 'mount' def __virtual__(): ''' Only load on POSIX-like systems ''' # Disable on Windows, a specific file module exists: if salt.utils.platform.is_windows(): return (False, 'The mount module cannot be loaded: not a POSIX-like system.') return True def _list_mounts(): ret = {} if __grains__['os'] in ['MacOS', 'Darwin']: mounts = __salt__['cmd.run_stdout']('mount') else: mounts = __salt__['cmd.run_stdout']('mount -l') for line in mounts.split('\n'): comps = re.sub(r"\s+", " ", line).split() if len(comps) >= 3: ret[comps[2]] = comps[0] return ret def _active_mountinfo(ret): _list = _list_mounts() filename = '/proc/self/mountinfo' if not os.access(filename, os.R_OK): msg = 'File not readable {0}' raise CommandExecutionError(msg.format(filename)) if 'disk.blkid' not in __context__: __context__['disk.blkid'] = __salt__['disk.blkid']() blkid_info = __context__['disk.blkid'] with salt.utils.files.fopen(filename) as ifile: for line in ifile: comps = salt.utils.stringutils.to_unicode(line).split() device = comps[2].split(':') # each line can have any number of # optional parameters, we use the # location of the separator field to # determine the location of the elements # after it. _sep = comps.index('-') device_name = comps[_sep + 2] device_uuid = None device_label = None if device_name: device_uuid = blkid_info.get(device_name, {}).get('UUID') device_uuid = device_uuid and device_uuid.lower() device_label = blkid_info.get(device_name, {}).get('LABEL') ret[comps[4]] = {'mountid': comps[0], 'parentid': comps[1], 'major': device[0], 'minor': device[1], 'root': comps[3], 'opts': _resolve_user_group_names(comps[5].split(',')), 'fstype': comps[_sep + 1], 'device': device_name.replace('\\040', '\\ '), 'alt_device': _list.get(comps[4], None), 'superopts': _resolve_user_group_names(comps[_sep + 3].split(',')), 'device_uuid': device_uuid, 'device_label': device_label} return ret def _active_mounts(ret): ''' List active mounts on Linux systems ''' _list = _list_mounts() filename = '/proc/self/mounts' if not os.access(filename, os.R_OK): msg = 'File not readable {0}' raise CommandExecutionError(msg.format(filename)) with salt.utils.files.fopen(filename) as ifile: for line in ifile: comps = salt.utils.stringutils.to_unicode(line).split() ret[comps[1]] = {'device': comps[0], 'alt_device': _list.get(comps[1], None), 'fstype': comps[2], 'opts': _resolve_user_group_names(comps[3].split(','))} return ret def _active_mounts_aix(ret): ''' List active mounts on AIX systems ''' for line in __salt__['cmd.run_stdout']('mount -p').split('\n'): comps = re.sub(r"\s+", " ", line).split() if comps: if comps[0] == 'node' or comps[0] == '--------': continue comps_len = len(comps) if line.startswith((' ', '\t')): curr_opts = _resolve_user_group_names(comps[6].split(',')) if 7 == comps_len else [] if curr_opts: ret[comps[1]] = {'device': comps[0], 'fstype': comps[2], 'opts': curr_opts} else: ret[comps[1]] = {'device': comps[0], 'fstype': comps[2]} else: curr_opts = _resolve_user_group_names(comps[7].split(',')) if 8 == comps_len else [] if curr_opts: ret[comps[2]] = {'node': comps[0], 'device': comps[1], 'fstype': comps[3], 'opts': curr_opts} else: ret[comps[2]] = {'node': comps[0], 'device': comps[1], 'fstype': comps[3]} return ret def _active_mounts_freebsd(ret): ''' List active mounts on FreeBSD systems ''' for line in __salt__['cmd.run_stdout']('mount -p').split('\n'): comps = re.sub(r"\s+", " ", line).split() ret[comps[1]] = {'device': comps[0], 'fstype': comps[2], 'opts': _resolve_user_group_names(comps[3].split(','))} return ret def _active_mounts_solaris(ret): ''' List active mounts on Solaris systems ''' for line in __salt__['cmd.run_stdout']('mount -v').split('\n'): comps = re.sub(r"\s+", " ", line).split() ret[comps[2]] = {'device': comps[0], 'fstype': comps[4], 'opts': _resolve_user_group_names(comps[5].split('/'))} return ret def _active_mounts_openbsd(ret): ''' List active mounts on OpenBSD systems ''' for line in __salt__['cmd.run_stdout']('mount -v').split('\n'): comps = re.sub(r"\s+", " ", line).split() parens = re.findall(r'\((.*?)\)', line, re.DOTALL) if len(parens) > 1: nod = __salt__['cmd.run_stdout']('ls -l {0}'.format(comps[0])) nod = ' '.join(nod.split()).split(" ") ret[comps[3]] = {'device': comps[0], 'fstype': comps[5], 'opts': _resolve_user_group_names(parens[1].split(", ")), 'major': six.text_type(nod[4].strip(",")), 'minor': six.text_type(nod[5]), 'device_uuid': parens[0]} else: ret[comps[2]] = {'device': comps[0], 'fstype': comps[4], 'opts': _resolve_user_group_names(parens[0].split(", "))} return ret def _active_mounts_darwin(ret): ''' List active mounts on Mac OS systems ''' for line in __salt__['cmd.run_stdout']('mount').split('\n'): comps = re.sub(r"\s+", " ", line).split() parens = re.findall(r'\((.*?)\)', line, re.DOTALL)[0].split(", ") ret[comps[2]] = {'device': comps[0], 'fstype': parens[0], 'opts': _resolve_user_group_names(parens[1:])} return ret def _resolve_user_group_names(opts): ''' Resolve user and group names in related opts ''' name_id_opts = {'uid': 'user.info', 'gid': 'group.info'} for ind, opt in enumerate(opts): if opt.split('=')[0] in name_id_opts: _givenid = opt.split('=')[1] _param = opt.split('=')[0] _id = _givenid if not re.match('[0-9]+$', _givenid): _info = __salt__[name_id_opts[_param]](_givenid) if _info and _param in _info: _id = _info[_param] opts[ind] = _param + '=' + six.text_type(_id) opts[ind] = opts[ind].replace('\\040', '\\ ') return opts def active(extended=False): ''' List the active mounts. CLI Example: .. code-block:: bash salt '*' mount.active ''' ret = {} if __grains__['os'] == 'FreeBSD': _active_mounts_freebsd(ret) elif 'AIX' in __grains__['kernel']: _active_mounts_aix(ret) elif __grains__['kernel'] == 'SunOS': _active_mounts_solaris(ret) elif __grains__['os'] == 'OpenBSD': _active_mounts_openbsd(ret) elif __grains__['os'] in ['MacOS', 'Darwin']: _active_mounts_darwin(ret) else: if extended: try: _active_mountinfo(ret) except CommandExecutionError: _active_mounts(ret) else: _active_mounts(ret) return ret class _fstab_entry(object): ''' Utility class for manipulating fstab entries. Primarily we're parsing, formatting, and comparing lines. Parsing emits dicts expected from fstab() or raises a ValueError. Note: We'll probably want to use os.normpath and os.normcase on 'name' ''' class ParseError(ValueError): ''' Error raised when a line isn't parsible as an fstab entry ''' fstab_keys = ('device', 'name', 'fstype', 'opts', 'dump', 'pass_num') # preserve data format compatibility_keys = ('device', 'name', 'fstype', 'opts', 'dump', 'pass') fstab_format = '{device}\t\t{name}\t{fstype}\t{opts}\t{dump} {pass_num}\n' @classmethod def dict_from_line(cls, line, keys=fstab_keys): if len(keys) != 6: raise ValueError('Invalid key array: {0}'.format(keys)) if line.startswith('#'): raise cls.ParseError("Comment!") comps = line.split() if len(comps) < 4 or len(comps) > 6: raise cls.ParseError("Invalid Entry!") comps.extend(['0'] * (len(keys) - len(comps))) return dict(zip(keys, comps)) @classmethod def from_line(cls, *args, **kwargs): return cls(** cls.dict_from_line(*args, **kwargs)) @classmethod def dict_to_line(cls, entry): return cls.fstab_format.format(**entry) def __str__(self): ''' String value, only works for full repr ''' return self.dict_to_line(self.criteria) def __repr__(self): ''' Always works ''' return repr(self.criteria) def pick(self, keys): ''' Returns an instance with just those keys ''' subset = dict([(key, self.criteria[key]) for key in keys]) return self.__class__(**subset) def __init__(self, **criteria): ''' Store non-empty, non-null values to use as filter ''' items = [key_value for key_value in six.iteritems(criteria) if key_value[1] is not None] items = [(key_value1[0], six.text_type(key_value1[1])) for key_value1 in items] self.criteria = dict(items) @staticmethod def norm_path(path): ''' Resolve equivalent paths equivalently ''' return os.path.normcase(os.path.normpath(path)) def match(self, line): ''' Compare potentially partial criteria against line ''' entry = self.dict_from_line(line) for key, value in six.iteritems(self.criteria): if entry[key] != value: return False return True class _vfstab_entry(object): ''' Utility class for manipulating vfstab entries. Primarily we're parsing, formatting, and comparing lines. Parsing emits dicts expected from fstab() or raises a ValueError. Note: We'll probably want to use os.normpath and os.normcase on 'name' Note: This parses vfstab entries on Solaris like systems #device device mount FS fsck mount mount #to mount to fsck point type pass at boot options # /devices - /devices devfs - no - ''' class ParseError(ValueError): '''Error raised when a line isn't parsible as an fstab entry''' vfstab_keys = ('device', 'device_fsck', 'name', 'fstype', 'pass_fsck', 'mount_at_boot', 'opts') # NOTE: weird formatting to match default spacing on Solaris vfstab_format = '{device:<11} {device_fsck:<3} {name:<19} {fstype:<8} {pass_fsck:<3} {mount_at_boot:<6} {opts}\n' @classmethod def dict_from_line(cls, line): if line.startswith('#'): raise cls.ParseError("Comment!") comps = line.split() if len(comps) != 7: raise cls.ParseError("Invalid Entry!") return dict(zip(cls.vfstab_keys, comps)) @classmethod def from_line(cls, *args, **kwargs): return cls(** cls.dict_from_line(*args, **kwargs)) @classmethod def dict_to_line(cls, entry): return cls.vfstab_format.format(**entry) def __str__(self): ''' String value, only works for full repr ''' return self.dict_to_line(self.criteria) def __repr__(self): ''' Always works ''' return repr(self.criteria) def pick(self, keys): ''' Returns an instance with just those keys ''' subset = dict([(key, self.criteria[key]) for key in keys]) return self.__class__(**subset) def __init__(self, **criteria): ''' Store non-empty, non-null values to use as filter ''' items = [key_value for key_value in six.iteritems(criteria) if key_value[1] is not None] items = [(key_value1[0], six.text_type(key_value1[1])) for key_value1 in items] self.criteria = dict(items) @staticmethod def norm_path(path): ''' Resolve equivalent paths equivalently ''' return os.path.normcase(os.path.normpath(path)) def match(self, line): ''' Compare potentially partial criteria against line ''' entry = self.dict_from_line(line) for key, value in six.iteritems(self.criteria): if entry[key] != value: return False return True class _FileSystemsEntry(object): ''' Utility class for manipulating filesystem entries. Primarily we're parsing, formatting, and comparing lines. Parsing emits dicts expected from fstab() or raises a ValueError. Note: We'll probably want to use os.normpath and os.normcase on 'name' ''' class ParseError(ValueError): ''' Error raised when a line isn't parsible as an fstab entry ''' filesystems_keys = ('device', 'name', 'fstype', 'vfstype', 'opts', 'mount') # preserve data format of filesystems compatibility_keys = ('dev', 'dev', 'name', 'fstype', 'vfstype', 'opts', 'mount', 'type', 'vfs', 'account', 'boot', 'check', 'free', 'nodename', 'quota', 'size', 'vol', 'log') @classmethod def dict_from_lines(cls, lines, keys=filesystems_keys): if len(lines) < 2: raise ValueError('Invalid number of lines: {0}'.format(lines)) if not keys: # if empty force default filesystems_keys keys = _FileSystemsEntry.filesystems_keys elif len(keys) < 6: raise ValueError('Invalid key name array: {0}'.format(keys)) blk_lines = lines orddict = OrderedDict() orddict['name'] = blk_lines[0].split(':')[0].strip() blk_lines.pop(0) for line in blk_lines: if line.startswith('#'): raise cls.ParseError("Comment!") comps = line.split('= ') if len(comps) != 2: raise cls.ParseError("Invalid Entry!") key_name = comps[0].strip() if key_name in keys: orddict[key_name] = comps[1].strip() else: raise ValueError('Invalid name for use in filesystems: {0}'.format(key_name)) return orddict @classmethod def dict_from_cmd_line(cls, ipargs, keys): cmdln_dict = ipargs if keys: for key, value in keys: # ignore unknown or local scope keys if key.startswith('__'): continue if key in _FileSystemsEntry.compatibility_keys: cmdln_dict[key] = value return cmdln_dict @classmethod def from_line(cls, *args, **kwargs): return cls(** cls.dict_from_cmd_line(*args, **kwargs)) @classmethod def dict_to_lines(cls, fsys_dict_entry): entry = fsys_dict_entry strg_out = entry['name'] + ':' + os.linesep for k, v in six.viewitems(entry): if 'name' not in k: strg_out += '\t{0}\t\t= {1}'.format(k, v) + os.linesep strg_out += os.linesep return six.text_type(strg_out) def dict_from_entry(self): ret = OrderedDict() ret[self.criteria['name']] = self.criteria return ret def __str__(self): ''' String value, only works for full repr ''' return self.dict_to_lines(self.criteria) def __repr__(self): ''' Always works ''' return repr(self.criteria) def pick(self, keys): ''' Returns an instance with just those keys ''' subset = dict([(key, self.criteria[key]) for key in keys]) return self.__class__(**subset) def __init__(self, **criteria): ''' Store non-empty, non-null values to use as filter ''' items = [key_value for key_value in six.iteritems(criteria) if key_value[1] is not None] items = [(key_value1[0], six.text_type(key_value1[1])) for key_value1 in items] self.criteria = OrderedDict(items) @staticmethod def norm_path(path): ''' Resolve equivalent paths equivalently ''' return os.path.normcase(os.path.normpath(path)) def match(self, fsys_view): ''' Compare potentially partial criteria against built filesystems entry dictionary ''' evalue_dict = fsys_view[1] for key, value in six.viewitems(self.criteria): if key in evalue_dict: if evalue_dict[key] != value: return False else: return False return True def __getitem__(self, key): ''' Return value for input key ''' return self.criteria[key] def fstab(config='/etc/fstab'): ''' .. versionchanged:: 2016.3.2 List the contents of the fstab CLI Example: .. code-block:: bash salt '*' mount.fstab ''' ret = {} if not os.path.isfile(config): return ret with salt.utils.files.fopen(config) as ifile: for line in ifile: line = salt.utils.stringutils.to_unicode(line) try: if __grains__['kernel'] == 'SunOS': # Note: comments use in default vfstab file! if line[0] == '#': continue entry = _vfstab_entry.dict_from_line( line) else: entry = _fstab_entry.dict_from_line( line, _fstab_entry.compatibility_keys) entry['opts'] = entry['opts'].split(',') while entry['name'] in ret: entry['name'] += '_' ret[entry.pop('name')] = entry except _fstab_entry.ParseError: pass except _vfstab_entry.ParseError: pass return ret def vfstab(config='/etc/vfstab'): ''' .. versionadded:: 2016.3.2 List the contents of the vfstab CLI Example: .. code-block:: bash salt '*' mount.vfstab ''' # NOTE: vfstab is a wrapper for fstab return fstab(config) def rm_fstab(name, device, config='/etc/fstab'): ''' .. versionchanged:: 2016.3.2 Remove the mount point from the fstab CLI Example: .. code-block:: bash salt '*' mount.rm_fstab /mnt/foo /dev/sdg ''' modified = False if __grains__['kernel'] == 'SunOS': criteria = _vfstab_entry(name=name, device=device) else: criteria = _fstab_entry(name=name, device=device) lines = [] try: with salt.utils.files.fopen(config, 'r') as ifile: for line in ifile: line = salt.utils.stringutils.to_unicode(line) try: if criteria.match(line): modified = True else: lines.append(line) except _fstab_entry.ParseError: lines.append(line) except _vfstab_entry.ParseError: lines.append(line) except (IOError, OSError) as exc: msg = "Couldn't read from {0}: {1}" raise CommandExecutionError(msg.format(config, exc)) if modified: try: with salt.utils.files.fopen(config, 'wb') as ofile: ofile.writelines(salt.utils.data.encode(lines)) except (IOError, OSError) as exc: msg = "Couldn't write to {0}: {1}" raise CommandExecutionError(msg.format(config, exc)) # Note: not clear why we always return 'True' # --just copying previous behavior at this point... return True def rm_vfstab(name, device, config='/etc/vfstab'): ''' .. versionadded:: 2016.3.2 Remove the mount point from the vfstab CLI Example: .. code-block:: bash salt '*' mount.rm_vfstab /mnt/foo /device/c0t0d0p0 ''' ## NOTE: rm_vfstab is a wrapper for rm_fstab return rm_fstab(name, device, config) def set_fstab( name, device, fstype, opts='defaults', dump=0, pass_num=0, config='/etc/fstab', test=False, match_on='auto', **kwargs): ''' Verify that this mount is represented in the fstab, change the mount to match the data passed, or add the mount if it is not present. CLI Example: .. code-block:: bash salt '*' mount.set_fstab /mnt/foo /dev/sdz1 ext4 ''' # Fix the opts type if it is a list if isinstance(opts, list): opts = ','.join(opts) # preserve arguments for updating entry_args = { 'name': name, 'device': device.replace('\\ ', '\\040'), 'fstype': fstype, 'opts': opts.replace('\\ ', '\\040'), 'dump': dump, 'pass_num': pass_num, } lines = [] ret = None # Transform match_on into list--items will be checked later if isinstance(match_on, list): pass elif not isinstance(match_on, six.string_types): msg = 'match_on must be a string or list of strings' raise CommandExecutionError(msg) elif match_on == 'auto': # Try to guess right criteria for auto.... # NOTE: missing some special fstypes here specialFSes = frozenset([ 'none', 'tmpfs', 'sysfs', 'proc', 'fusectl', 'debugfs', 'securityfs', 'devtmpfs', 'cgroup', 'btrfs']) if fstype in specialFSes: match_on = ['name'] else: match_on = ['device'] else: match_on = [match_on] # generate entry and criteria objects, handle invalid keys in match_on entry = _fstab_entry(**entry_args) try: criteria = entry.pick(match_on) except KeyError: filterFn = lambda key: key not in _fstab_entry.fstab_keys invalid_keys = filter(filterFn, match_on) msg = 'Unrecognized keys in match_on: "{0}"'.format(invalid_keys) raise CommandExecutionError(msg) # parse file, use ret to cache status if not os.path.isfile(config): raise CommandExecutionError('Bad config file "{0}"'.format(config)) try: with salt.utils.files.fopen(config, 'r') as ifile: for line in ifile: line = salt.utils.stringutils.to_unicode(line) try: if criteria.match(line): # Note: If ret isn't None here, # we've matched multiple lines ret = 'present' if entry.match(line): lines.append(line) else: ret = 'change' lines.append(six.text_type(entry)) else: lines.append(line) except _fstab_entry.ParseError: lines.append(line) except (IOError, OSError) as exc: msg = 'Couldn\'t read from {0}: {1}' raise CommandExecutionError(msg.format(config, exc)) # add line if not present or changed if ret is None: lines.append(six.text_type(entry)) ret = 'new' if ret != 'present': # ret in ['new', 'change']: if not salt.utils.args.test_mode(test=test, **kwargs): try: with salt.utils.files.fopen(config, 'wb') as ofile: # The line was changed, commit it! ofile.writelines(salt.utils.data.encode(lines)) except (IOError, OSError): msg = 'File not writable {0}' raise CommandExecutionError(msg.format(config)) return ret def set_vfstab( name, device, fstype, opts='-', device_fsck='-', pass_fsck='-', mount_at_boot='yes', config='/etc/vfstab', test=False, match_on='auto', **kwargs): ''' ..verionadded:: 2016.3.2 Verify that this mount is represented in the fstab, change the mount to match the data passed, or add the mount if it is not present. CLI Example: .. code-block:: bash salt '*' mount.set_vfstab /mnt/foo /device/c0t0d0p0 ufs ''' # Fix the opts type if it is a list if isinstance(opts, list): opts = ','.join(opts) # Map unknown values for mount_at_boot to no if mount_at_boot != 'yes': mount_at_boot = 'no' # preserve arguments for updating entry_args = { 'name': name, 'device': device, 'fstype': fstype, 'opts': opts, 'device_fsck': device_fsck, 'pass_fsck': pass_fsck, 'mount_at_boot': mount_at_boot, } lines = [] ret = None # Transform match_on into list--items will be checked later if isinstance(match_on, list): pass elif not isinstance(match_on, six.string_types): msg = 'match_on must be a string or list of strings' raise CommandExecutionError(msg) elif match_on == 'auto': # Try to guess right criteria for auto.... # NOTE: missing some special fstypes here specialFSes = frozenset([ 'devfs', 'proc', 'ctfs', 'objfs', 'sharefs', 'fs', 'tmpfs']) if fstype in specialFSes: match_on = ['name'] else: match_on = ['device'] else: match_on = [match_on] # generate entry and criteria objects, handle invalid keys in match_on entry = _vfstab_entry(**entry_args) try: criteria = entry.pick(match_on) except KeyError: filterFn = lambda key: key not in _vfstab_entry.vfstab_keys invalid_keys = filter(filterFn, match_on) msg = 'Unrecognized keys in match_on: "{0}"'.format(invalid_keys) raise CommandExecutionError(msg) # parse file, use ret to cache status if not os.path.isfile(config): raise CommandExecutionError('Bad config file "{0}"'.format(config)) try: with salt.utils.files.fopen(config, 'r') as ifile: for line in ifile: line = salt.utils.stringutils.to_unicode(line) try: if criteria.match(line): # Note: If ret isn't None here, # we've matched multiple lines ret = 'present' if entry.match(line): lines.append(line) else: ret = 'change' lines.append(six.text_type(entry)) else: lines.append(line) except _vfstab_entry.ParseError: lines.append(line) except (IOError, OSError) as exc: msg = 'Couldn\'t read from {0}: {1}' raise CommandExecutionError(msg.format(config, exc)) # add line if not present or changed if ret is None: lines.append(six.text_type(entry)) ret = 'new' if ret != 'present': # ret in ['new', 'change']: if not salt.utils.args.test_mode(test=test, **kwargs): try: with salt.utils.files.fopen(config, 'wb') as ofile: # The line was changed, commit it! ofile.writelines(salt.utils.data.encode(lines)) except (IOError, OSError): msg = 'File not writable {0}' raise CommandExecutionError(msg.format(config)) return ret def rm_automaster(name, device, config='/etc/auto_salt'): ''' Remove the mount point from the auto_master CLI Example: .. code-block:: bash salt '*' mount.rm_automaster /mnt/foo /dev/sdg ''' contents = automaster(config) if name not in contents: return True # The entry is present, get rid of it lines = [] try: with salt.utils.files.fopen(config, 'r') as ifile: for line in ifile: line = salt.utils.stringutils.to_unicode(line) if line.startswith('#'): # Commented lines.append(line) continue if not line.strip(): # Blank line lines.append(line) continue comps = line.split() if len(comps) != 3: # Invalid entry lines.append(line) continue comps = line.split() prefix = "/.." name_chk = comps[0].replace(prefix, "") device_fmt = comps[2].split(":") if device: if name_chk == name and device_fmt[1] == device: continue else: if name_chk == name: continue lines.append(line) except (IOError, OSError) as exc: msg = "Couldn't read from {0}: {1}" raise CommandExecutionError(msg.format(config, exc)) try: with salt.utils.files.fopen(config, 'wb') as ofile: ofile.writelines(salt.utils.data.encode(lines)) except (IOError, OSError) as exc: msg = "Couldn't write to {0}: {1}" raise CommandExecutionError(msg.format(config, exc)) # Update automount __salt__['cmd.run']('automount -cv') return True def set_automaster( name, device, fstype, opts='', config='/etc/auto_salt', test=False, **kwargs): ''' Verify that this mount is represented in the auto_salt, change the mount to match the data passed, or add the mount if it is not present. CLI Example: .. code-block:: bash salt '*' mount.set_automaster /mnt/foo /dev/sdz1 ext4 ''' # Fix the opts type if it is a list if isinstance(opts, list): opts = ','.join(opts) lines = [] change = False present = False automaster_file = "/etc/auto_master" if not os.path.isfile(config): __salt__['file.touch'](config) __salt__['file.append'](automaster_file, "/-\t\t\t{0}".format(config)) name = "/..{0}".format(name) device_fmt = "{0}:{1}".format(fstype, device) type_opts = "-fstype={0},{1}".format(fstype, opts) if fstype == 'smbfs': device_fmt = device_fmt.replace(fstype, "") try: with salt.utils.files.fopen(config, 'r') as ifile: for line in ifile: line = salt.utils.stringutils.to_unicode(line) if line.startswith('#'): # Commented lines.append(line) continue if not line.strip(): # Blank line lines.append(line) continue comps = line.split() if len(comps) != 3: # Invalid entry lines.append(line) continue if comps[0] == name or comps[2] == device_fmt: # check to see if there are changes # and fix them if there are any present = True if comps[0] != name: change = True comps[0] = name if comps[1] != type_opts: change = True comps[1] = type_opts if comps[2] != device_fmt: change = True comps[2] = device_fmt if change: log.debug( 'auto_master entry for mount point %s needs to be ' 'updated', name ) newline = ( '{0}\t{1}\t{2}\n'.format( name, type_opts, device_fmt) ) lines.append(newline) else: lines.append(line) except (IOError, OSError) as exc: msg = 'Couldn\'t read from {0}: {1}' raise CommandExecutionError(msg.format(config, exc)) if change: if not salt.utils.args.test_mode(test=test, **kwargs): try: with salt.utils.files.fopen(config, 'wb') as ofile: # The line was changed, commit it! ofile.writelines(salt.utils.data.encode(lines)) except (IOError, OSError): msg = 'File not writable {0}' raise CommandExecutionError(msg.format(config)) return 'change' if not change: if present: # The right entry is already here return 'present' else: if not salt.utils.args.test_mode(test=test, **kwargs): # The entry is new, add it to the end of the fstab newline = ( '{0}\t{1}\t{2}\n'.format( name, type_opts, device_fmt) ) lines.append(newline) try: with salt.utils.files.fopen(config, 'wb') as ofile: # The line was changed, commit it! ofile.writelines(salt.utils.data.encode(lines)) except (IOError, OSError): raise CommandExecutionError( 'File not writable {0}'.format( config ) ) return 'new' def automaster(config='/etc/auto_salt'): ''' List the contents of the auto master CLI Example: .. code-block:: bash salt '*' mount.automaster ''' ret = {} if not os.path.isfile(config): return ret with salt.utils.files.fopen(config) as ifile: for line in ifile: line = salt.utils.stringutils.to_unicode(line) if line.startswith('#'): # Commented continue if not line.strip(): # Blank line continue comps = line.split() if len(comps) != 3: # Invalid entry continue prefix = "/.." name = comps[0].replace(prefix, "") device_fmt = comps[2].split(":") opts = comps[1].split(',') ret[name] = {'device': device_fmt[1], 'fstype': opts[0], 'opts': opts[1:]} return ret def mount(name, device, mkmnt=False, fstype='', opts='defaults', user=None, util='mount'): ''' Mount a device CLI Example: .. code-block:: bash salt '*' mount.mount /mnt/foo /dev/sdz1 True ''' if util != 'mount': # This functionality used to live in img.mount_image if util == 'guestfs': return __salt__['guestfs.mount'](name, root=device) elif util == 'qemu_nbd': mnt = __salt__['qemu_nbd.init'](name, device) if not mnt: return False first = next(six.iterkeys(mnt)) __context__['img.mnt_{0}'.format(first)] = mnt return first return False # Darwin doesn't expect defaults when mounting without other options if 'defaults' in opts and __grains__['os'] in ['MacOS', 'Darwin', 'AIX']: opts = None if isinstance(opts, six.string_types): opts = opts.split(',') if not os.path.exists(name) and mkmnt: __salt__['file.mkdir'](name, user=user) args = '' if opts is not None: lopts = ','.join(opts) args = '-o {0}'.format(lopts) if fstype: # use of fstype on AIX differs from typical Linux use of -t # functionality AIX uses -v vfsname, -t fstype mounts all with # fstype in /etc/filesystems if 'AIX' in __grains__['os']: args += ' -v {0}'.format(fstype) elif 'solaris' in __grains__['os'].lower(): args += ' -F {0}'.format(fstype) else: args += ' -t {0}'.format(fstype) cmd = 'mount {0} {1} {2} '.format(args, device, name) out = __salt__['cmd.run_all'](cmd, runas=user, python_shell=False) if out['retcode']: return out['stderr'] return True def remount(name, device, mkmnt=False, fstype='', opts='defaults', user=None): ''' Attempt to remount a device, if the device is not already mounted, mount is called CLI Example: .. code-block:: bash salt '*' mount.remount /mnt/foo /dev/sdz1 True ''' force_mount = False if __grains__['os'] in ['MacOS', 'Darwin']: if opts == 'defaults': opts = 'noowners' if fstype == 'smbfs': force_mount = True if 'AIX' in __grains__['os']: if opts == 'defaults': opts = [] if isinstance(opts, six.string_types): opts = opts.split(',') mnts = active() if name in mnts: # The mount point is mounted, attempt to remount it with the given data if 'remount' not in opts and __grains__['os'] not in ['OpenBSD', 'MacOS', 'Darwin']: opts.append('remount') if force_mount: # We need to force the mount but first we should unmount umount(name, device, user=user) lopts = ','.join(opts) args = '-o {0}'.format(lopts) if fstype: # use of fstype on AIX differs from typical Linux use of # -t functionality AIX uses -v vfsname, -t fstype mounts # all with fstype in /etc/filesystems if 'AIX' in __grains__['os']: args += ' -v {0}'.format(fstype) elif 'solaris' in __grains__['os'].lower(): args += ' -F {0}'.format(fstype) else: args += ' -t {0}'.format(fstype) if __grains__['os'] not in ['OpenBSD', 'MacOS', 'Darwin'] or force_mount: cmd = 'mount {0} {1} {2} '.format(args, device, name) else: cmd = 'mount -u {0} {1} {2} '.format(args, device, name) out = __salt__['cmd.run_all'](cmd, runas=user, python_shell=False) if out['retcode']: return out['stderr'] return True # Mount a filesystem that isn't already return mount(name, device, mkmnt, fstype, opts, user=user) def umount(name, device=None, user=None, util='mount'): ''' Attempt to unmount a device by specifying the directory it is mounted on CLI Example: .. code-block:: bash salt '*' mount.umount /mnt/foo .. versionadded:: 2015.5.0 .. code-block:: bash salt '*' mount.umount /mnt/foo /dev/xvdc1 ''' if util != 'mount': # This functionality used to live in img.umount_image if 'qemu_nbd.clear' in __salt__: if 'img.mnt_{0}'.format(name) in __context__: __salt__['qemu_nbd.clear'](__context__['img.mnt_{0}'.format(name)]) return mnts = active() if name not in mnts: return "{0} does not have anything mounted".format(name) if not device: cmd = 'umount {0}'.format(name) else: cmd = 'umount {0}'.format(device) out = __salt__['cmd.run_all'](cmd, runas=user, python_shell=False) if out['retcode']: return out['stderr'] return True def is_fuse_exec(cmd): ''' Returns true if the command passed is a fuse mountable application. CLI Example: .. code-block:: bash salt '*' mount.is_fuse_exec sshfs ''' cmd_path = salt.utils.path.which(cmd) # No point in running ldd on a command that doesn't exist if not cmd_path: return False elif not salt.utils.path.which('ldd'): raise CommandNotFoundError('ldd') out = __salt__['cmd.run']('ldd {0}'.format(cmd_path), python_shell=False) return 'libfuse' in out def swaps(): ''' Return a dict containing information on active swap .. versionchanged:: 2016.3.2 CLI Example: .. code-block:: bash salt '*' mount.swaps ''' ret = {} if __grains__['kernel'] == 'SunOS': for line in __salt__['cmd.run_stdout']('swap -l').splitlines(): if line.startswith('swapfile'): continue comps = line.split() ret[comps[0]] = {'type': 'device' if comps[0].startswith(('/dev', 'swap')) else 'file', 'size': int(comps[3]), 'used': (int(comps[3]) - int(comps[4])), 'priority': '-'} elif 'AIX' in __grains__['kernel']: for line in __salt__['cmd.run_stdout']('swap -l').splitlines(): if line.startswith('device'): continue comps = line.split() # AIX uses MB for units ret[comps[0]] = {'type': 'device', 'size': int(comps[3][:-2]) * 1024, 'used': (int(comps[3][:-2]) - int(comps[4][:-2])) * 1024, 'priority': '-'} elif __grains__['os'] != 'OpenBSD': with salt.utils.files.fopen('/proc/swaps') as fp_: for line in fp_: line = salt.utils.stringutils.to_unicode(line) if line.startswith('Filename'): continue comps = line.split() ret[comps[0]] = {'type': comps[1], 'size': comps[2], 'used': comps[3], 'priority': comps[4]} else: for line in __salt__['cmd.run_stdout']('swapctl -kl').splitlines(): if line.startswith(('Device', 'Total')): continue swap_type = "file" comps = line.split() if comps[0].startswith('/dev/'): swap_type = "partition" ret[comps[0]] = {'type': swap_type, 'size': comps[1], 'used': comps[2], 'priority': comps[5]} return ret def swapon(name, priority=None): ''' Activate a swap disk .. versionchanged:: 2016.3.2 CLI Example: .. code-block:: bash salt '*' mount.swapon /root/swapfile ''' ret = {} on_ = swaps() if name in on_: ret['stats'] = on_[name] ret['new'] = False return ret if __grains__['kernel'] == 'SunOS': if __grains__['virtual'] != 'zone': __salt__['cmd.run']('swap -a {0}'.format(name), python_shell=False) else: return False else: cmd = 'swapon {0}'.format(name) if priority and 'AIX' not in __grains__['kernel']: cmd += ' -p {0}'.format(priority) __salt__['cmd.run'](cmd, python_shell=False) on_ = swaps() if name in on_: ret['stats'] = on_[name] ret['new'] = True return ret return ret def swapoff(name): ''' Deactivate a named swap mount .. versionchanged:: 2016.3.2 CLI Example: .. code-block:: bash salt '*' mount.swapoff /root/swapfile ''' on_ = swaps() if name in on_: if __grains__['kernel'] == 'SunOS': if __grains__['virtual'] != 'zone': __salt__['cmd.run']('swap -a {0}'.format(name), python_shell=False) else: return False elif __grains__['os'] != 'OpenBSD': __salt__['cmd.run']('swapoff {0}'.format(name), python_shell=False) else: __salt__['cmd.run']('swapctl -d {0}'.format(name), python_shell=False) on_ = swaps() if name in on_: return False return True return None def is_mounted(name): ''' .. versionadded:: 2014.7.0 Provide information if the path is mounted CLI Example: .. code-block:: bash salt '*' mount.is_mounted /mnt/share ''' active_ = active() if name in active_: return True else: return False def read_mount_cache(name): ''' .. versionadded:: 2018.3.0 Provide information if the path is mounted CLI Example: .. code-block:: bash salt '*' mount.read_mount_cache /mnt/share ''' cache = salt.utils.mount.read_cache(__opts__) if cache: if 'mounts' in cache and cache['mounts']: if name in cache['mounts']: return cache['mounts'][name] return {} def write_mount_cache(real_name, device, mkmnt, fstype, mount_opts): ''' .. versionadded:: 2018.3.0 Provide information if the path is mounted :param real_name: The real name of the mount point where the device is mounted. :param device: The device that is being mounted. :param mkmnt: Whether or not the mount point should be created. :param fstype: The file system that is used. :param mount_opts: Additional options used when mounting the device. :return: Boolean if message was sent successfully. CLI Example: .. code-block:: bash salt '*' mount.write_mount_cache /mnt/share /dev/sda1 False ext4 defaults,nosuid ''' cache = salt.utils.mount.read_cache(__opts__) if not cache: cache = {} cache['mounts'] = {} else: if 'mounts' not in cache: cache['mounts'] = {} cache['mounts'][real_name] = {'device': device, 'fstype': fstype, 'mkmnt': mkmnt, 'opts': mount_opts} cache_write = salt.utils.mount.write_cache(cache, __opts__) if cache_write: return True else: raise CommandExecutionError('Unable to write mount cache.') def delete_mount_cache(real_name): ''' .. versionadded:: 2018.3.0 Provide information if the path is mounted CLI Example: .. code-block:: bash salt '*' mount.delete_mount_cache /mnt/share ''' cache = salt.utils.mount.read_cache(__opts__) if cache: if 'mounts' in cache: if real_name in cache['mounts']: del cache['mounts'][real_name] cache_write = salt.utils.mount.write_cache(cache, __opts__) if not cache_write: raise CommandExecutionError('Unable to write mount cache.') return True def _filesystems(config='/etc/filesystems', leading_key=True): ''' Return the contents of the filesystems in an OrderedDict config File containing filesystem infomation leading_key True return dictionary keyed by 'name' and value as dictionary with other keys, values (name excluded) OrderedDict({ '/dir' : OrderedDict({'dev': '/dev/hd8', .... }})) False return dictionary keyed by 'name' and value as dictionary with all keys, values (name included) OrderedDict({ '/dir' : OrderedDict({'name': '/dir', 'dev': '/dev/hd8', ... })}) ''' ret = OrderedDict() lines = [] parsing_block = False if not os.path.isfile(config) or 'AIX' not in __grains__['kernel']: return ret # read in block of filesystems, block starts with '/' till empty line with salt.utils.files.fopen(config) as ifile: for line in ifile: line = salt.utils.stringutils.to_unicode(line) # skip till first entry if not line.startswith('/') and not parsing_block: continue if line.startswith('/'): parsing_block = True lines.append(line) elif not line.split(): parsing_block = False try: entry = _FileSystemsEntry.dict_from_lines( lines, _FileSystemsEntry.compatibility_keys) lines = [] if 'opts' in entry: entry['opts'] = entry['opts'].split(',') while entry['name'] in ret: entry['name'] += '_' if leading_key: ret[entry.pop('name')] = entry else: ret[entry['name']] = entry except _FileSystemsEntry.ParseError: pass else: lines.append(line) return ret def set_filesystems( name, device, vfstype, opts='-', mount='true', config='/etc/filesystems', test=False, match_on='auto', **kwargs): ''' .. versionadded:: 2018.3.3 Verify that this mount is represented in the filesystems, change the mount to match the data passed, or add the mount if it is not present on AIX Provide information if the path is mounted :param name: The name of the mount point where the device is mounted. :param device: The device that is being mounted. :param vfstype: The file system that is used (AIX has two fstypes, fstype and vfstype - similar to Linux fstype) :param opts: Additional options used when mounting the device. :param mount: Mount if not mounted, default True. :param config: Configuration file, default /etc/filesystems. :param match: File systems type to match on, default auto CLI Example: .. code-block:: bash salt '*' mount.set_filesystems /mnt/foo /dev/sdz1 jfs2 ''' # Fix the opts type if it is a list if isinstance(opts, list): opts = ','.join(opts) # preserve arguments for updating entry_args = { 'name': name, 'dev': device.replace('\\ ', '\\040'), 'vfstype': vfstype, 'opts': opts, 'mount': mount, } view_lines = [] ret = None if 'AIX' not in __grains__['kernel']: return ret # Transform match_on into list--items will be checked later if isinstance(match_on, list): pass elif not isinstance(match_on, six.string_types): raise CommandExecutionError('match_on must be a string or list of strings') elif match_on == 'auto': # Try to guess right criteria for auto.... # added IBM types from sys/vmount.h after btrfs # NOTE: missing some special fstypes here specialFSes = frozenset([ 'none', 'tmpfs', 'sysfs', 'proc', 'fusectl', 'debugfs', 'securityfs', 'devtmpfs', 'cgroup', 'btrfs', 'cdrfs', 'procfs', 'jfs', 'jfs2', 'nfs', 'sfs', 'nfs3', 'cachefs', 'udfs', 'cifs', 'namefs', 'pmemfs', 'ahafs', 'nfs4', 'autofs', 'stnfs']) if vfstype in specialFSes: match_on = ['name'] else: match_on = ['dev'] else: match_on = [match_on] # generate entry and criteria objects, handle invalid keys in match_on entry_ip = _FileSystemsEntry.from_line(entry_args, kwargs) try: criteria = entry_ip.pick(match_on) except KeyError: filterFn = lambda key: key not in _FileSystemsEntry.compatibility_keys invalid_keys = filter(filterFn, match_on) raise CommandExecutionError('Unrecognized keys in match_on: "{0}"'.format(invalid_keys)) # parse file, use ret to cache status if not os.path.isfile(config): raise CommandExecutionError('Bad config file "{0}"'.format(config)) # read in block of filesystem, block starts with '/' till empty line try: fsys_filedict = _filesystems(config, False) for fsys_view in six.viewitems(fsys_filedict): if criteria.match(fsys_view): ret = 'present' if entry_ip.match(fsys_view): view_lines.append(fsys_view) else: ret = 'change' kv = entry_ip['name'] view_lines.append((kv, entry_ip)) else: view_lines.append(fsys_view) except (IOError, OSError) as exc: raise CommandExecutionError('Couldn\'t read from {0}: {1}'.format(config, exc)) # add line if not present or changed if ret is None: for dict_view in six.viewitems(entry_ip.dict_from_entry()): view_lines.append(dict_view) ret = 'new' if ret != 'present': # ret in ['new', 'change']: try: with salt.utils.files.fopen(config, 'wb') as ofile: # The line was changed, commit it! for fsys_view in view_lines: entry = fsys_view[1] mystrg = _FileSystemsEntry.dict_to_lines(entry) ofile.writelines(salt.utils.data.encode(mystrg)) except (IOError, OSError): raise CommandExecutionError('File not writable {0}'.format(config)) return ret def rm_filesystems(name, device, config='/etc/filesystems'): ''' .. versionadded:: 2018.3.3 Remove the mount point from the filesystems CLI Example: .. code-block:: bash salt '*' mount.rm_filesystems /mnt/foo /dev/sdg ''' modified = False view_lines = [] if 'AIX' not in __grains__['kernel']: return modified criteria = _FileSystemsEntry(name=name, dev=device) try: fsys_filedict = _filesystems(config, False) for fsys_view in six.viewitems(fsys_filedict): try: if criteria.match(fsys_view): modified = True else: view_lines.append(fsys_view) except _FileSystemsEntry.ParseError: view_lines.append(fsys_view) except (IOError, OSError) as exc: raise CommandExecutionError("Couldn't read from {0}: {1}".format(config, exc)) if modified: try: with salt.utils.files.fopen(config, 'wb') as ofile: for fsys_view in view_lines: entry = fsys_view[1] mystrg = _FileSystemsEntry.dict_to_lines(entry) ofile.writelines(salt.utils.data.encode(mystrg)) except (IOError, OSError) as exc: raise CommandExecutionError("Couldn't write to {0}: {1}".format(config, exc)) return modified
saltstack/salt
salt/modules/mount.py
set_filesystems
python
def set_filesystems( name, device, vfstype, opts='-', mount='true', config='/etc/filesystems', test=False, match_on='auto', **kwargs): ''' .. versionadded:: 2018.3.3 Verify that this mount is represented in the filesystems, change the mount to match the data passed, or add the mount if it is not present on AIX Provide information if the path is mounted :param name: The name of the mount point where the device is mounted. :param device: The device that is being mounted. :param vfstype: The file system that is used (AIX has two fstypes, fstype and vfstype - similar to Linux fstype) :param opts: Additional options used when mounting the device. :param mount: Mount if not mounted, default True. :param config: Configuration file, default /etc/filesystems. :param match: File systems type to match on, default auto CLI Example: .. code-block:: bash salt '*' mount.set_filesystems /mnt/foo /dev/sdz1 jfs2 ''' # Fix the opts type if it is a list if isinstance(opts, list): opts = ','.join(opts) # preserve arguments for updating entry_args = { 'name': name, 'dev': device.replace('\\ ', '\\040'), 'vfstype': vfstype, 'opts': opts, 'mount': mount, } view_lines = [] ret = None if 'AIX' not in __grains__['kernel']: return ret # Transform match_on into list--items will be checked later if isinstance(match_on, list): pass elif not isinstance(match_on, six.string_types): raise CommandExecutionError('match_on must be a string or list of strings') elif match_on == 'auto': # Try to guess right criteria for auto.... # added IBM types from sys/vmount.h after btrfs # NOTE: missing some special fstypes here specialFSes = frozenset([ 'none', 'tmpfs', 'sysfs', 'proc', 'fusectl', 'debugfs', 'securityfs', 'devtmpfs', 'cgroup', 'btrfs', 'cdrfs', 'procfs', 'jfs', 'jfs2', 'nfs', 'sfs', 'nfs3', 'cachefs', 'udfs', 'cifs', 'namefs', 'pmemfs', 'ahafs', 'nfs4', 'autofs', 'stnfs']) if vfstype in specialFSes: match_on = ['name'] else: match_on = ['dev'] else: match_on = [match_on] # generate entry and criteria objects, handle invalid keys in match_on entry_ip = _FileSystemsEntry.from_line(entry_args, kwargs) try: criteria = entry_ip.pick(match_on) except KeyError: filterFn = lambda key: key not in _FileSystemsEntry.compatibility_keys invalid_keys = filter(filterFn, match_on) raise CommandExecutionError('Unrecognized keys in match_on: "{0}"'.format(invalid_keys)) # parse file, use ret to cache status if not os.path.isfile(config): raise CommandExecutionError('Bad config file "{0}"'.format(config)) # read in block of filesystem, block starts with '/' till empty line try: fsys_filedict = _filesystems(config, False) for fsys_view in six.viewitems(fsys_filedict): if criteria.match(fsys_view): ret = 'present' if entry_ip.match(fsys_view): view_lines.append(fsys_view) else: ret = 'change' kv = entry_ip['name'] view_lines.append((kv, entry_ip)) else: view_lines.append(fsys_view) except (IOError, OSError) as exc: raise CommandExecutionError('Couldn\'t read from {0}: {1}'.format(config, exc)) # add line if not present or changed if ret is None: for dict_view in six.viewitems(entry_ip.dict_from_entry()): view_lines.append(dict_view) ret = 'new' if ret != 'present': # ret in ['new', 'change']: try: with salt.utils.files.fopen(config, 'wb') as ofile: # The line was changed, commit it! for fsys_view in view_lines: entry = fsys_view[1] mystrg = _FileSystemsEntry.dict_to_lines(entry) ofile.writelines(salt.utils.data.encode(mystrg)) except (IOError, OSError): raise CommandExecutionError('File not writable {0}'.format(config)) return ret
.. versionadded:: 2018.3.3 Verify that this mount is represented in the filesystems, change the mount to match the data passed, or add the mount if it is not present on AIX Provide information if the path is mounted :param name: The name of the mount point where the device is mounted. :param device: The device that is being mounted. :param vfstype: The file system that is used (AIX has two fstypes, fstype and vfstype - similar to Linux fstype) :param opts: Additional options used when mounting the device. :param mount: Mount if not mounted, default True. :param config: Configuration file, default /etc/filesystems. :param match: File systems type to match on, default auto CLI Example: .. code-block:: bash salt '*' mount.set_filesystems /mnt/foo /dev/sdz1 jfs2
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/mount.py#L1666-L1810
[ "def encode(data, encoding=None, errors='strict', keep=False,\n preserve_dict_class=False, preserve_tuples=False):\n '''\n Generic function which will encode whichever type is passed, if necessary\n\n If `strict` is True, and `keep` is False, and we fail to encode, a\n UnicodeEncodeError will be raised. Passing `keep` as True allows for the\n original value to silently be returned in cases where encoding fails. This\n can be useful for cases where the data passed to this function is likely to\n contain binary blobs.\n '''\n if isinstance(data, Mapping):\n return encode_dict(data, encoding, errors, keep,\n preserve_dict_class, preserve_tuples)\n elif isinstance(data, list):\n return encode_list(data, encoding, errors, keep,\n preserve_dict_class, preserve_tuples)\n elif isinstance(data, tuple):\n return encode_tuple(data, encoding, errors, keep, preserve_dict_class) \\\n if preserve_tuples \\\n else encode_list(data, encoding, errors, keep,\n preserve_dict_class, preserve_tuples)\n else:\n try:\n return salt.utils.stringutils.to_bytes(data, encoding, errors)\n except TypeError:\n # to_bytes raises a TypeError when input is not a\n # string/bytestring/bytearray. This is expected and simply\n # means we are going to leave the value as-is.\n pass\n except UnicodeEncodeError:\n if not keep:\n raise\n return data\n", "def 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 _filesystems(config='/etc/filesystems', leading_key=True):\n '''\n Return the contents of the filesystems in an OrderedDict\n\n config\n File containing filesystem infomation\n\n leading_key\n True return dictionary keyed by 'name' and value as dictionary with other keys, values (name excluded)\n OrderedDict({ '/dir' : OrderedDict({'dev': '/dev/hd8', .... }}))\n\n False return dictionary keyed by 'name' and value as dictionary with all keys, values (name included)\n OrderedDict({ '/dir' : OrderedDict({'name': '/dir', 'dev': '/dev/hd8', ... })})\n '''\n ret = OrderedDict()\n lines = []\n parsing_block = False\n if not os.path.isfile(config) or 'AIX' not in __grains__['kernel']:\n return ret\n\n # read in block of filesystems, block starts with '/' till empty line\n with salt.utils.files.fopen(config) as ifile:\n for line in ifile:\n line = salt.utils.stringutils.to_unicode(line)\n\n # skip till first entry\n if not line.startswith('/') and not parsing_block:\n continue\n\n if line.startswith('/'):\n parsing_block = True\n lines.append(line)\n elif not line.split():\n parsing_block = False\n try:\n entry = _FileSystemsEntry.dict_from_lines(\n lines,\n _FileSystemsEntry.compatibility_keys)\n lines = []\n if 'opts' in entry:\n entry['opts'] = entry['opts'].split(',')\n while entry['name'] in ret:\n entry['name'] += '_'\n\n if leading_key:\n ret[entry.pop('name')] = entry\n else:\n ret[entry['name']] = entry\n\n except _FileSystemsEntry.ParseError:\n pass\n else:\n lines.append(line)\n\n return ret\n", "def from_line(cls, *args, **kwargs):\n return cls(** cls.dict_from_cmd_line(*args, **kwargs))\n", "def dict_to_lines(cls, fsys_dict_entry):\n entry = fsys_dict_entry\n strg_out = entry['name'] + ':' + os.linesep\n for k, v in six.viewitems(entry):\n if 'name' not in k:\n strg_out += '\\t{0}\\t\\t= {1}'.format(k, v) + os.linesep\n strg_out += os.linesep\n return six.text_type(strg_out)\n", "def dict_from_entry(self):\n ret = OrderedDict()\n ret[self.criteria['name']] = self.criteria\n return ret\n", "def pick(self, keys):\n '''\n Returns an instance with just those keys\n '''\n subset = dict([(key, self.criteria[key]) for key in keys])\n return self.__class__(**subset)\n", "def match(self, fsys_view):\n '''\n Compare potentially partial criteria against built filesystems entry dictionary\n '''\n evalue_dict = fsys_view[1]\n for key, value in six.viewitems(self.criteria):\n if key in evalue_dict:\n if evalue_dict[key] != value:\n return False\n else:\n return False\n return True\n" ]
# -*- coding: utf-8 -*- ''' Salt module to manage Unix mounts and the fstab file ''' # Import python libs from __future__ import absolute_import, print_function, unicode_literals import os import re import logging # Import salt libs import salt.utils.args import salt.utils.data import salt.utils.files import salt.utils.path import salt.utils.platform import salt.utils.mount import salt.utils.stringutils from salt.utils.odict import OrderedDict from salt.exceptions import CommandNotFoundError, CommandExecutionError # Import 3rd-party libs from salt.ext import six from salt.ext.six.moves import filter, zip # pylint: disable=import-error,redefined-builtin # Set up logger log = logging.getLogger(__name__) # Define the module's virtual name __virtualname__ = 'mount' def __virtual__(): ''' Only load on POSIX-like systems ''' # Disable on Windows, a specific file module exists: if salt.utils.platform.is_windows(): return (False, 'The mount module cannot be loaded: not a POSIX-like system.') return True def _list_mounts(): ret = {} if __grains__['os'] in ['MacOS', 'Darwin']: mounts = __salt__['cmd.run_stdout']('mount') else: mounts = __salt__['cmd.run_stdout']('mount -l') for line in mounts.split('\n'): comps = re.sub(r"\s+", " ", line).split() if len(comps) >= 3: ret[comps[2]] = comps[0] return ret def _active_mountinfo(ret): _list = _list_mounts() filename = '/proc/self/mountinfo' if not os.access(filename, os.R_OK): msg = 'File not readable {0}' raise CommandExecutionError(msg.format(filename)) if 'disk.blkid' not in __context__: __context__['disk.blkid'] = __salt__['disk.blkid']() blkid_info = __context__['disk.blkid'] with salt.utils.files.fopen(filename) as ifile: for line in ifile: comps = salt.utils.stringutils.to_unicode(line).split() device = comps[2].split(':') # each line can have any number of # optional parameters, we use the # location of the separator field to # determine the location of the elements # after it. _sep = comps.index('-') device_name = comps[_sep + 2] device_uuid = None device_label = None if device_name: device_uuid = blkid_info.get(device_name, {}).get('UUID') device_uuid = device_uuid and device_uuid.lower() device_label = blkid_info.get(device_name, {}).get('LABEL') ret[comps[4]] = {'mountid': comps[0], 'parentid': comps[1], 'major': device[0], 'minor': device[1], 'root': comps[3], 'opts': _resolve_user_group_names(comps[5].split(',')), 'fstype': comps[_sep + 1], 'device': device_name.replace('\\040', '\\ '), 'alt_device': _list.get(comps[4], None), 'superopts': _resolve_user_group_names(comps[_sep + 3].split(',')), 'device_uuid': device_uuid, 'device_label': device_label} return ret def _active_mounts(ret): ''' List active mounts on Linux systems ''' _list = _list_mounts() filename = '/proc/self/mounts' if not os.access(filename, os.R_OK): msg = 'File not readable {0}' raise CommandExecutionError(msg.format(filename)) with salt.utils.files.fopen(filename) as ifile: for line in ifile: comps = salt.utils.stringutils.to_unicode(line).split() ret[comps[1]] = {'device': comps[0], 'alt_device': _list.get(comps[1], None), 'fstype': comps[2], 'opts': _resolve_user_group_names(comps[3].split(','))} return ret def _active_mounts_aix(ret): ''' List active mounts on AIX systems ''' for line in __salt__['cmd.run_stdout']('mount -p').split('\n'): comps = re.sub(r"\s+", " ", line).split() if comps: if comps[0] == 'node' or comps[0] == '--------': continue comps_len = len(comps) if line.startswith((' ', '\t')): curr_opts = _resolve_user_group_names(comps[6].split(',')) if 7 == comps_len else [] if curr_opts: ret[comps[1]] = {'device': comps[0], 'fstype': comps[2], 'opts': curr_opts} else: ret[comps[1]] = {'device': comps[0], 'fstype': comps[2]} else: curr_opts = _resolve_user_group_names(comps[7].split(',')) if 8 == comps_len else [] if curr_opts: ret[comps[2]] = {'node': comps[0], 'device': comps[1], 'fstype': comps[3], 'opts': curr_opts} else: ret[comps[2]] = {'node': comps[0], 'device': comps[1], 'fstype': comps[3]} return ret def _active_mounts_freebsd(ret): ''' List active mounts on FreeBSD systems ''' for line in __salt__['cmd.run_stdout']('mount -p').split('\n'): comps = re.sub(r"\s+", " ", line).split() ret[comps[1]] = {'device': comps[0], 'fstype': comps[2], 'opts': _resolve_user_group_names(comps[3].split(','))} return ret def _active_mounts_solaris(ret): ''' List active mounts on Solaris systems ''' for line in __salt__['cmd.run_stdout']('mount -v').split('\n'): comps = re.sub(r"\s+", " ", line).split() ret[comps[2]] = {'device': comps[0], 'fstype': comps[4], 'opts': _resolve_user_group_names(comps[5].split('/'))} return ret def _active_mounts_openbsd(ret): ''' List active mounts on OpenBSD systems ''' for line in __salt__['cmd.run_stdout']('mount -v').split('\n'): comps = re.sub(r"\s+", " ", line).split() parens = re.findall(r'\((.*?)\)', line, re.DOTALL) if len(parens) > 1: nod = __salt__['cmd.run_stdout']('ls -l {0}'.format(comps[0])) nod = ' '.join(nod.split()).split(" ") ret[comps[3]] = {'device': comps[0], 'fstype': comps[5], 'opts': _resolve_user_group_names(parens[1].split(", ")), 'major': six.text_type(nod[4].strip(",")), 'minor': six.text_type(nod[5]), 'device_uuid': parens[0]} else: ret[comps[2]] = {'device': comps[0], 'fstype': comps[4], 'opts': _resolve_user_group_names(parens[0].split(", "))} return ret def _active_mounts_darwin(ret): ''' List active mounts on Mac OS systems ''' for line in __salt__['cmd.run_stdout']('mount').split('\n'): comps = re.sub(r"\s+", " ", line).split() parens = re.findall(r'\((.*?)\)', line, re.DOTALL)[0].split(", ") ret[comps[2]] = {'device': comps[0], 'fstype': parens[0], 'opts': _resolve_user_group_names(parens[1:])} return ret def _resolve_user_group_names(opts): ''' Resolve user and group names in related opts ''' name_id_opts = {'uid': 'user.info', 'gid': 'group.info'} for ind, opt in enumerate(opts): if opt.split('=')[0] in name_id_opts: _givenid = opt.split('=')[1] _param = opt.split('=')[0] _id = _givenid if not re.match('[0-9]+$', _givenid): _info = __salt__[name_id_opts[_param]](_givenid) if _info and _param in _info: _id = _info[_param] opts[ind] = _param + '=' + six.text_type(_id) opts[ind] = opts[ind].replace('\\040', '\\ ') return opts def active(extended=False): ''' List the active mounts. CLI Example: .. code-block:: bash salt '*' mount.active ''' ret = {} if __grains__['os'] == 'FreeBSD': _active_mounts_freebsd(ret) elif 'AIX' in __grains__['kernel']: _active_mounts_aix(ret) elif __grains__['kernel'] == 'SunOS': _active_mounts_solaris(ret) elif __grains__['os'] == 'OpenBSD': _active_mounts_openbsd(ret) elif __grains__['os'] in ['MacOS', 'Darwin']: _active_mounts_darwin(ret) else: if extended: try: _active_mountinfo(ret) except CommandExecutionError: _active_mounts(ret) else: _active_mounts(ret) return ret class _fstab_entry(object): ''' Utility class for manipulating fstab entries. Primarily we're parsing, formatting, and comparing lines. Parsing emits dicts expected from fstab() or raises a ValueError. Note: We'll probably want to use os.normpath and os.normcase on 'name' ''' class ParseError(ValueError): ''' Error raised when a line isn't parsible as an fstab entry ''' fstab_keys = ('device', 'name', 'fstype', 'opts', 'dump', 'pass_num') # preserve data format compatibility_keys = ('device', 'name', 'fstype', 'opts', 'dump', 'pass') fstab_format = '{device}\t\t{name}\t{fstype}\t{opts}\t{dump} {pass_num}\n' @classmethod def dict_from_line(cls, line, keys=fstab_keys): if len(keys) != 6: raise ValueError('Invalid key array: {0}'.format(keys)) if line.startswith('#'): raise cls.ParseError("Comment!") comps = line.split() if len(comps) < 4 or len(comps) > 6: raise cls.ParseError("Invalid Entry!") comps.extend(['0'] * (len(keys) - len(comps))) return dict(zip(keys, comps)) @classmethod def from_line(cls, *args, **kwargs): return cls(** cls.dict_from_line(*args, **kwargs)) @classmethod def dict_to_line(cls, entry): return cls.fstab_format.format(**entry) def __str__(self): ''' String value, only works for full repr ''' return self.dict_to_line(self.criteria) def __repr__(self): ''' Always works ''' return repr(self.criteria) def pick(self, keys): ''' Returns an instance with just those keys ''' subset = dict([(key, self.criteria[key]) for key in keys]) return self.__class__(**subset) def __init__(self, **criteria): ''' Store non-empty, non-null values to use as filter ''' items = [key_value for key_value in six.iteritems(criteria) if key_value[1] is not None] items = [(key_value1[0], six.text_type(key_value1[1])) for key_value1 in items] self.criteria = dict(items) @staticmethod def norm_path(path): ''' Resolve equivalent paths equivalently ''' return os.path.normcase(os.path.normpath(path)) def match(self, line): ''' Compare potentially partial criteria against line ''' entry = self.dict_from_line(line) for key, value in six.iteritems(self.criteria): if entry[key] != value: return False return True class _vfstab_entry(object): ''' Utility class for manipulating vfstab entries. Primarily we're parsing, formatting, and comparing lines. Parsing emits dicts expected from fstab() or raises a ValueError. Note: We'll probably want to use os.normpath and os.normcase on 'name' Note: This parses vfstab entries on Solaris like systems #device device mount FS fsck mount mount #to mount to fsck point type pass at boot options # /devices - /devices devfs - no - ''' class ParseError(ValueError): '''Error raised when a line isn't parsible as an fstab entry''' vfstab_keys = ('device', 'device_fsck', 'name', 'fstype', 'pass_fsck', 'mount_at_boot', 'opts') # NOTE: weird formatting to match default spacing on Solaris vfstab_format = '{device:<11} {device_fsck:<3} {name:<19} {fstype:<8} {pass_fsck:<3} {mount_at_boot:<6} {opts}\n' @classmethod def dict_from_line(cls, line): if line.startswith('#'): raise cls.ParseError("Comment!") comps = line.split() if len(comps) != 7: raise cls.ParseError("Invalid Entry!") return dict(zip(cls.vfstab_keys, comps)) @classmethod def from_line(cls, *args, **kwargs): return cls(** cls.dict_from_line(*args, **kwargs)) @classmethod def dict_to_line(cls, entry): return cls.vfstab_format.format(**entry) def __str__(self): ''' String value, only works for full repr ''' return self.dict_to_line(self.criteria) def __repr__(self): ''' Always works ''' return repr(self.criteria) def pick(self, keys): ''' Returns an instance with just those keys ''' subset = dict([(key, self.criteria[key]) for key in keys]) return self.__class__(**subset) def __init__(self, **criteria): ''' Store non-empty, non-null values to use as filter ''' items = [key_value for key_value in six.iteritems(criteria) if key_value[1] is not None] items = [(key_value1[0], six.text_type(key_value1[1])) for key_value1 in items] self.criteria = dict(items) @staticmethod def norm_path(path): ''' Resolve equivalent paths equivalently ''' return os.path.normcase(os.path.normpath(path)) def match(self, line): ''' Compare potentially partial criteria against line ''' entry = self.dict_from_line(line) for key, value in six.iteritems(self.criteria): if entry[key] != value: return False return True class _FileSystemsEntry(object): ''' Utility class for manipulating filesystem entries. Primarily we're parsing, formatting, and comparing lines. Parsing emits dicts expected from fstab() or raises a ValueError. Note: We'll probably want to use os.normpath and os.normcase on 'name' ''' class ParseError(ValueError): ''' Error raised when a line isn't parsible as an fstab entry ''' filesystems_keys = ('device', 'name', 'fstype', 'vfstype', 'opts', 'mount') # preserve data format of filesystems compatibility_keys = ('dev', 'dev', 'name', 'fstype', 'vfstype', 'opts', 'mount', 'type', 'vfs', 'account', 'boot', 'check', 'free', 'nodename', 'quota', 'size', 'vol', 'log') @classmethod def dict_from_lines(cls, lines, keys=filesystems_keys): if len(lines) < 2: raise ValueError('Invalid number of lines: {0}'.format(lines)) if not keys: # if empty force default filesystems_keys keys = _FileSystemsEntry.filesystems_keys elif len(keys) < 6: raise ValueError('Invalid key name array: {0}'.format(keys)) blk_lines = lines orddict = OrderedDict() orddict['name'] = blk_lines[0].split(':')[0].strip() blk_lines.pop(0) for line in blk_lines: if line.startswith('#'): raise cls.ParseError("Comment!") comps = line.split('= ') if len(comps) != 2: raise cls.ParseError("Invalid Entry!") key_name = comps[0].strip() if key_name in keys: orddict[key_name] = comps[1].strip() else: raise ValueError('Invalid name for use in filesystems: {0}'.format(key_name)) return orddict @classmethod def dict_from_cmd_line(cls, ipargs, keys): cmdln_dict = ipargs if keys: for key, value in keys: # ignore unknown or local scope keys if key.startswith('__'): continue if key in _FileSystemsEntry.compatibility_keys: cmdln_dict[key] = value return cmdln_dict @classmethod def from_line(cls, *args, **kwargs): return cls(** cls.dict_from_cmd_line(*args, **kwargs)) @classmethod def dict_to_lines(cls, fsys_dict_entry): entry = fsys_dict_entry strg_out = entry['name'] + ':' + os.linesep for k, v in six.viewitems(entry): if 'name' not in k: strg_out += '\t{0}\t\t= {1}'.format(k, v) + os.linesep strg_out += os.linesep return six.text_type(strg_out) def dict_from_entry(self): ret = OrderedDict() ret[self.criteria['name']] = self.criteria return ret def __str__(self): ''' String value, only works for full repr ''' return self.dict_to_lines(self.criteria) def __repr__(self): ''' Always works ''' return repr(self.criteria) def pick(self, keys): ''' Returns an instance with just those keys ''' subset = dict([(key, self.criteria[key]) for key in keys]) return self.__class__(**subset) def __init__(self, **criteria): ''' Store non-empty, non-null values to use as filter ''' items = [key_value for key_value in six.iteritems(criteria) if key_value[1] is not None] items = [(key_value1[0], six.text_type(key_value1[1])) for key_value1 in items] self.criteria = OrderedDict(items) @staticmethod def norm_path(path): ''' Resolve equivalent paths equivalently ''' return os.path.normcase(os.path.normpath(path)) def match(self, fsys_view): ''' Compare potentially partial criteria against built filesystems entry dictionary ''' evalue_dict = fsys_view[1] for key, value in six.viewitems(self.criteria): if key in evalue_dict: if evalue_dict[key] != value: return False else: return False return True def __getitem__(self, key): ''' Return value for input key ''' return self.criteria[key] def fstab(config='/etc/fstab'): ''' .. versionchanged:: 2016.3.2 List the contents of the fstab CLI Example: .. code-block:: bash salt '*' mount.fstab ''' ret = {} if not os.path.isfile(config): return ret with salt.utils.files.fopen(config) as ifile: for line in ifile: line = salt.utils.stringutils.to_unicode(line) try: if __grains__['kernel'] == 'SunOS': # Note: comments use in default vfstab file! if line[0] == '#': continue entry = _vfstab_entry.dict_from_line( line) else: entry = _fstab_entry.dict_from_line( line, _fstab_entry.compatibility_keys) entry['opts'] = entry['opts'].split(',') while entry['name'] in ret: entry['name'] += '_' ret[entry.pop('name')] = entry except _fstab_entry.ParseError: pass except _vfstab_entry.ParseError: pass return ret def vfstab(config='/etc/vfstab'): ''' .. versionadded:: 2016.3.2 List the contents of the vfstab CLI Example: .. code-block:: bash salt '*' mount.vfstab ''' # NOTE: vfstab is a wrapper for fstab return fstab(config) def rm_fstab(name, device, config='/etc/fstab'): ''' .. versionchanged:: 2016.3.2 Remove the mount point from the fstab CLI Example: .. code-block:: bash salt '*' mount.rm_fstab /mnt/foo /dev/sdg ''' modified = False if __grains__['kernel'] == 'SunOS': criteria = _vfstab_entry(name=name, device=device) else: criteria = _fstab_entry(name=name, device=device) lines = [] try: with salt.utils.files.fopen(config, 'r') as ifile: for line in ifile: line = salt.utils.stringutils.to_unicode(line) try: if criteria.match(line): modified = True else: lines.append(line) except _fstab_entry.ParseError: lines.append(line) except _vfstab_entry.ParseError: lines.append(line) except (IOError, OSError) as exc: msg = "Couldn't read from {0}: {1}" raise CommandExecutionError(msg.format(config, exc)) if modified: try: with salt.utils.files.fopen(config, 'wb') as ofile: ofile.writelines(salt.utils.data.encode(lines)) except (IOError, OSError) as exc: msg = "Couldn't write to {0}: {1}" raise CommandExecutionError(msg.format(config, exc)) # Note: not clear why we always return 'True' # --just copying previous behavior at this point... return True def rm_vfstab(name, device, config='/etc/vfstab'): ''' .. versionadded:: 2016.3.2 Remove the mount point from the vfstab CLI Example: .. code-block:: bash salt '*' mount.rm_vfstab /mnt/foo /device/c0t0d0p0 ''' ## NOTE: rm_vfstab is a wrapper for rm_fstab return rm_fstab(name, device, config) def set_fstab( name, device, fstype, opts='defaults', dump=0, pass_num=0, config='/etc/fstab', test=False, match_on='auto', **kwargs): ''' Verify that this mount is represented in the fstab, change the mount to match the data passed, or add the mount if it is not present. CLI Example: .. code-block:: bash salt '*' mount.set_fstab /mnt/foo /dev/sdz1 ext4 ''' # Fix the opts type if it is a list if isinstance(opts, list): opts = ','.join(opts) # preserve arguments for updating entry_args = { 'name': name, 'device': device.replace('\\ ', '\\040'), 'fstype': fstype, 'opts': opts.replace('\\ ', '\\040'), 'dump': dump, 'pass_num': pass_num, } lines = [] ret = None # Transform match_on into list--items will be checked later if isinstance(match_on, list): pass elif not isinstance(match_on, six.string_types): msg = 'match_on must be a string or list of strings' raise CommandExecutionError(msg) elif match_on == 'auto': # Try to guess right criteria for auto.... # NOTE: missing some special fstypes here specialFSes = frozenset([ 'none', 'tmpfs', 'sysfs', 'proc', 'fusectl', 'debugfs', 'securityfs', 'devtmpfs', 'cgroup', 'btrfs']) if fstype in specialFSes: match_on = ['name'] else: match_on = ['device'] else: match_on = [match_on] # generate entry and criteria objects, handle invalid keys in match_on entry = _fstab_entry(**entry_args) try: criteria = entry.pick(match_on) except KeyError: filterFn = lambda key: key not in _fstab_entry.fstab_keys invalid_keys = filter(filterFn, match_on) msg = 'Unrecognized keys in match_on: "{0}"'.format(invalid_keys) raise CommandExecutionError(msg) # parse file, use ret to cache status if not os.path.isfile(config): raise CommandExecutionError('Bad config file "{0}"'.format(config)) try: with salt.utils.files.fopen(config, 'r') as ifile: for line in ifile: line = salt.utils.stringutils.to_unicode(line) try: if criteria.match(line): # Note: If ret isn't None here, # we've matched multiple lines ret = 'present' if entry.match(line): lines.append(line) else: ret = 'change' lines.append(six.text_type(entry)) else: lines.append(line) except _fstab_entry.ParseError: lines.append(line) except (IOError, OSError) as exc: msg = 'Couldn\'t read from {0}: {1}' raise CommandExecutionError(msg.format(config, exc)) # add line if not present or changed if ret is None: lines.append(six.text_type(entry)) ret = 'new' if ret != 'present': # ret in ['new', 'change']: if not salt.utils.args.test_mode(test=test, **kwargs): try: with salt.utils.files.fopen(config, 'wb') as ofile: # The line was changed, commit it! ofile.writelines(salt.utils.data.encode(lines)) except (IOError, OSError): msg = 'File not writable {0}' raise CommandExecutionError(msg.format(config)) return ret def set_vfstab( name, device, fstype, opts='-', device_fsck='-', pass_fsck='-', mount_at_boot='yes', config='/etc/vfstab', test=False, match_on='auto', **kwargs): ''' ..verionadded:: 2016.3.2 Verify that this mount is represented in the fstab, change the mount to match the data passed, or add the mount if it is not present. CLI Example: .. code-block:: bash salt '*' mount.set_vfstab /mnt/foo /device/c0t0d0p0 ufs ''' # Fix the opts type if it is a list if isinstance(opts, list): opts = ','.join(opts) # Map unknown values for mount_at_boot to no if mount_at_boot != 'yes': mount_at_boot = 'no' # preserve arguments for updating entry_args = { 'name': name, 'device': device, 'fstype': fstype, 'opts': opts, 'device_fsck': device_fsck, 'pass_fsck': pass_fsck, 'mount_at_boot': mount_at_boot, } lines = [] ret = None # Transform match_on into list--items will be checked later if isinstance(match_on, list): pass elif not isinstance(match_on, six.string_types): msg = 'match_on must be a string or list of strings' raise CommandExecutionError(msg) elif match_on == 'auto': # Try to guess right criteria for auto.... # NOTE: missing some special fstypes here specialFSes = frozenset([ 'devfs', 'proc', 'ctfs', 'objfs', 'sharefs', 'fs', 'tmpfs']) if fstype in specialFSes: match_on = ['name'] else: match_on = ['device'] else: match_on = [match_on] # generate entry and criteria objects, handle invalid keys in match_on entry = _vfstab_entry(**entry_args) try: criteria = entry.pick(match_on) except KeyError: filterFn = lambda key: key not in _vfstab_entry.vfstab_keys invalid_keys = filter(filterFn, match_on) msg = 'Unrecognized keys in match_on: "{0}"'.format(invalid_keys) raise CommandExecutionError(msg) # parse file, use ret to cache status if not os.path.isfile(config): raise CommandExecutionError('Bad config file "{0}"'.format(config)) try: with salt.utils.files.fopen(config, 'r') as ifile: for line in ifile: line = salt.utils.stringutils.to_unicode(line) try: if criteria.match(line): # Note: If ret isn't None here, # we've matched multiple lines ret = 'present' if entry.match(line): lines.append(line) else: ret = 'change' lines.append(six.text_type(entry)) else: lines.append(line) except _vfstab_entry.ParseError: lines.append(line) except (IOError, OSError) as exc: msg = 'Couldn\'t read from {0}: {1}' raise CommandExecutionError(msg.format(config, exc)) # add line if not present or changed if ret is None: lines.append(six.text_type(entry)) ret = 'new' if ret != 'present': # ret in ['new', 'change']: if not salt.utils.args.test_mode(test=test, **kwargs): try: with salt.utils.files.fopen(config, 'wb') as ofile: # The line was changed, commit it! ofile.writelines(salt.utils.data.encode(lines)) except (IOError, OSError): msg = 'File not writable {0}' raise CommandExecutionError(msg.format(config)) return ret def rm_automaster(name, device, config='/etc/auto_salt'): ''' Remove the mount point from the auto_master CLI Example: .. code-block:: bash salt '*' mount.rm_automaster /mnt/foo /dev/sdg ''' contents = automaster(config) if name not in contents: return True # The entry is present, get rid of it lines = [] try: with salt.utils.files.fopen(config, 'r') as ifile: for line in ifile: line = salt.utils.stringutils.to_unicode(line) if line.startswith('#'): # Commented lines.append(line) continue if not line.strip(): # Blank line lines.append(line) continue comps = line.split() if len(comps) != 3: # Invalid entry lines.append(line) continue comps = line.split() prefix = "/.." name_chk = comps[0].replace(prefix, "") device_fmt = comps[2].split(":") if device: if name_chk == name and device_fmt[1] == device: continue else: if name_chk == name: continue lines.append(line) except (IOError, OSError) as exc: msg = "Couldn't read from {0}: {1}" raise CommandExecutionError(msg.format(config, exc)) try: with salt.utils.files.fopen(config, 'wb') as ofile: ofile.writelines(salt.utils.data.encode(lines)) except (IOError, OSError) as exc: msg = "Couldn't write to {0}: {1}" raise CommandExecutionError(msg.format(config, exc)) # Update automount __salt__['cmd.run']('automount -cv') return True def set_automaster( name, device, fstype, opts='', config='/etc/auto_salt', test=False, **kwargs): ''' Verify that this mount is represented in the auto_salt, change the mount to match the data passed, or add the mount if it is not present. CLI Example: .. code-block:: bash salt '*' mount.set_automaster /mnt/foo /dev/sdz1 ext4 ''' # Fix the opts type if it is a list if isinstance(opts, list): opts = ','.join(opts) lines = [] change = False present = False automaster_file = "/etc/auto_master" if not os.path.isfile(config): __salt__['file.touch'](config) __salt__['file.append'](automaster_file, "/-\t\t\t{0}".format(config)) name = "/..{0}".format(name) device_fmt = "{0}:{1}".format(fstype, device) type_opts = "-fstype={0},{1}".format(fstype, opts) if fstype == 'smbfs': device_fmt = device_fmt.replace(fstype, "") try: with salt.utils.files.fopen(config, 'r') as ifile: for line in ifile: line = salt.utils.stringutils.to_unicode(line) if line.startswith('#'): # Commented lines.append(line) continue if not line.strip(): # Blank line lines.append(line) continue comps = line.split() if len(comps) != 3: # Invalid entry lines.append(line) continue if comps[0] == name or comps[2] == device_fmt: # check to see if there are changes # and fix them if there are any present = True if comps[0] != name: change = True comps[0] = name if comps[1] != type_opts: change = True comps[1] = type_opts if comps[2] != device_fmt: change = True comps[2] = device_fmt if change: log.debug( 'auto_master entry for mount point %s needs to be ' 'updated', name ) newline = ( '{0}\t{1}\t{2}\n'.format( name, type_opts, device_fmt) ) lines.append(newline) else: lines.append(line) except (IOError, OSError) as exc: msg = 'Couldn\'t read from {0}: {1}' raise CommandExecutionError(msg.format(config, exc)) if change: if not salt.utils.args.test_mode(test=test, **kwargs): try: with salt.utils.files.fopen(config, 'wb') as ofile: # The line was changed, commit it! ofile.writelines(salt.utils.data.encode(lines)) except (IOError, OSError): msg = 'File not writable {0}' raise CommandExecutionError(msg.format(config)) return 'change' if not change: if present: # The right entry is already here return 'present' else: if not salt.utils.args.test_mode(test=test, **kwargs): # The entry is new, add it to the end of the fstab newline = ( '{0}\t{1}\t{2}\n'.format( name, type_opts, device_fmt) ) lines.append(newline) try: with salt.utils.files.fopen(config, 'wb') as ofile: # The line was changed, commit it! ofile.writelines(salt.utils.data.encode(lines)) except (IOError, OSError): raise CommandExecutionError( 'File not writable {0}'.format( config ) ) return 'new' def automaster(config='/etc/auto_salt'): ''' List the contents of the auto master CLI Example: .. code-block:: bash salt '*' mount.automaster ''' ret = {} if not os.path.isfile(config): return ret with salt.utils.files.fopen(config) as ifile: for line in ifile: line = salt.utils.stringutils.to_unicode(line) if line.startswith('#'): # Commented continue if not line.strip(): # Blank line continue comps = line.split() if len(comps) != 3: # Invalid entry continue prefix = "/.." name = comps[0].replace(prefix, "") device_fmt = comps[2].split(":") opts = comps[1].split(',') ret[name] = {'device': device_fmt[1], 'fstype': opts[0], 'opts': opts[1:]} return ret def mount(name, device, mkmnt=False, fstype='', opts='defaults', user=None, util='mount'): ''' Mount a device CLI Example: .. code-block:: bash salt '*' mount.mount /mnt/foo /dev/sdz1 True ''' if util != 'mount': # This functionality used to live in img.mount_image if util == 'guestfs': return __salt__['guestfs.mount'](name, root=device) elif util == 'qemu_nbd': mnt = __salt__['qemu_nbd.init'](name, device) if not mnt: return False first = next(six.iterkeys(mnt)) __context__['img.mnt_{0}'.format(first)] = mnt return first return False # Darwin doesn't expect defaults when mounting without other options if 'defaults' in opts and __grains__['os'] in ['MacOS', 'Darwin', 'AIX']: opts = None if isinstance(opts, six.string_types): opts = opts.split(',') if not os.path.exists(name) and mkmnt: __salt__['file.mkdir'](name, user=user) args = '' if opts is not None: lopts = ','.join(opts) args = '-o {0}'.format(lopts) if fstype: # use of fstype on AIX differs from typical Linux use of -t # functionality AIX uses -v vfsname, -t fstype mounts all with # fstype in /etc/filesystems if 'AIX' in __grains__['os']: args += ' -v {0}'.format(fstype) elif 'solaris' in __grains__['os'].lower(): args += ' -F {0}'.format(fstype) else: args += ' -t {0}'.format(fstype) cmd = 'mount {0} {1} {2} '.format(args, device, name) out = __salt__['cmd.run_all'](cmd, runas=user, python_shell=False) if out['retcode']: return out['stderr'] return True def remount(name, device, mkmnt=False, fstype='', opts='defaults', user=None): ''' Attempt to remount a device, if the device is not already mounted, mount is called CLI Example: .. code-block:: bash salt '*' mount.remount /mnt/foo /dev/sdz1 True ''' force_mount = False if __grains__['os'] in ['MacOS', 'Darwin']: if opts == 'defaults': opts = 'noowners' if fstype == 'smbfs': force_mount = True if 'AIX' in __grains__['os']: if opts == 'defaults': opts = [] if isinstance(opts, six.string_types): opts = opts.split(',') mnts = active() if name in mnts: # The mount point is mounted, attempt to remount it with the given data if 'remount' not in opts and __grains__['os'] not in ['OpenBSD', 'MacOS', 'Darwin']: opts.append('remount') if force_mount: # We need to force the mount but first we should unmount umount(name, device, user=user) lopts = ','.join(opts) args = '-o {0}'.format(lopts) if fstype: # use of fstype on AIX differs from typical Linux use of # -t functionality AIX uses -v vfsname, -t fstype mounts # all with fstype in /etc/filesystems if 'AIX' in __grains__['os']: args += ' -v {0}'.format(fstype) elif 'solaris' in __grains__['os'].lower(): args += ' -F {0}'.format(fstype) else: args += ' -t {0}'.format(fstype) if __grains__['os'] not in ['OpenBSD', 'MacOS', 'Darwin'] or force_mount: cmd = 'mount {0} {1} {2} '.format(args, device, name) else: cmd = 'mount -u {0} {1} {2} '.format(args, device, name) out = __salt__['cmd.run_all'](cmd, runas=user, python_shell=False) if out['retcode']: return out['stderr'] return True # Mount a filesystem that isn't already return mount(name, device, mkmnt, fstype, opts, user=user) def umount(name, device=None, user=None, util='mount'): ''' Attempt to unmount a device by specifying the directory it is mounted on CLI Example: .. code-block:: bash salt '*' mount.umount /mnt/foo .. versionadded:: 2015.5.0 .. code-block:: bash salt '*' mount.umount /mnt/foo /dev/xvdc1 ''' if util != 'mount': # This functionality used to live in img.umount_image if 'qemu_nbd.clear' in __salt__: if 'img.mnt_{0}'.format(name) in __context__: __salt__['qemu_nbd.clear'](__context__['img.mnt_{0}'.format(name)]) return mnts = active() if name not in mnts: return "{0} does not have anything mounted".format(name) if not device: cmd = 'umount {0}'.format(name) else: cmd = 'umount {0}'.format(device) out = __salt__['cmd.run_all'](cmd, runas=user, python_shell=False) if out['retcode']: return out['stderr'] return True def is_fuse_exec(cmd): ''' Returns true if the command passed is a fuse mountable application. CLI Example: .. code-block:: bash salt '*' mount.is_fuse_exec sshfs ''' cmd_path = salt.utils.path.which(cmd) # No point in running ldd on a command that doesn't exist if not cmd_path: return False elif not salt.utils.path.which('ldd'): raise CommandNotFoundError('ldd') out = __salt__['cmd.run']('ldd {0}'.format(cmd_path), python_shell=False) return 'libfuse' in out def swaps(): ''' Return a dict containing information on active swap .. versionchanged:: 2016.3.2 CLI Example: .. code-block:: bash salt '*' mount.swaps ''' ret = {} if __grains__['kernel'] == 'SunOS': for line in __salt__['cmd.run_stdout']('swap -l').splitlines(): if line.startswith('swapfile'): continue comps = line.split() ret[comps[0]] = {'type': 'device' if comps[0].startswith(('/dev', 'swap')) else 'file', 'size': int(comps[3]), 'used': (int(comps[3]) - int(comps[4])), 'priority': '-'} elif 'AIX' in __grains__['kernel']: for line in __salt__['cmd.run_stdout']('swap -l').splitlines(): if line.startswith('device'): continue comps = line.split() # AIX uses MB for units ret[comps[0]] = {'type': 'device', 'size': int(comps[3][:-2]) * 1024, 'used': (int(comps[3][:-2]) - int(comps[4][:-2])) * 1024, 'priority': '-'} elif __grains__['os'] != 'OpenBSD': with salt.utils.files.fopen('/proc/swaps') as fp_: for line in fp_: line = salt.utils.stringutils.to_unicode(line) if line.startswith('Filename'): continue comps = line.split() ret[comps[0]] = {'type': comps[1], 'size': comps[2], 'used': comps[3], 'priority': comps[4]} else: for line in __salt__['cmd.run_stdout']('swapctl -kl').splitlines(): if line.startswith(('Device', 'Total')): continue swap_type = "file" comps = line.split() if comps[0].startswith('/dev/'): swap_type = "partition" ret[comps[0]] = {'type': swap_type, 'size': comps[1], 'used': comps[2], 'priority': comps[5]} return ret def swapon(name, priority=None): ''' Activate a swap disk .. versionchanged:: 2016.3.2 CLI Example: .. code-block:: bash salt '*' mount.swapon /root/swapfile ''' ret = {} on_ = swaps() if name in on_: ret['stats'] = on_[name] ret['new'] = False return ret if __grains__['kernel'] == 'SunOS': if __grains__['virtual'] != 'zone': __salt__['cmd.run']('swap -a {0}'.format(name), python_shell=False) else: return False else: cmd = 'swapon {0}'.format(name) if priority and 'AIX' not in __grains__['kernel']: cmd += ' -p {0}'.format(priority) __salt__['cmd.run'](cmd, python_shell=False) on_ = swaps() if name in on_: ret['stats'] = on_[name] ret['new'] = True return ret return ret def swapoff(name): ''' Deactivate a named swap mount .. versionchanged:: 2016.3.2 CLI Example: .. code-block:: bash salt '*' mount.swapoff /root/swapfile ''' on_ = swaps() if name in on_: if __grains__['kernel'] == 'SunOS': if __grains__['virtual'] != 'zone': __salt__['cmd.run']('swap -a {0}'.format(name), python_shell=False) else: return False elif __grains__['os'] != 'OpenBSD': __salt__['cmd.run']('swapoff {0}'.format(name), python_shell=False) else: __salt__['cmd.run']('swapctl -d {0}'.format(name), python_shell=False) on_ = swaps() if name in on_: return False return True return None def is_mounted(name): ''' .. versionadded:: 2014.7.0 Provide information if the path is mounted CLI Example: .. code-block:: bash salt '*' mount.is_mounted /mnt/share ''' active_ = active() if name in active_: return True else: return False def read_mount_cache(name): ''' .. versionadded:: 2018.3.0 Provide information if the path is mounted CLI Example: .. code-block:: bash salt '*' mount.read_mount_cache /mnt/share ''' cache = salt.utils.mount.read_cache(__opts__) if cache: if 'mounts' in cache and cache['mounts']: if name in cache['mounts']: return cache['mounts'][name] return {} def write_mount_cache(real_name, device, mkmnt, fstype, mount_opts): ''' .. versionadded:: 2018.3.0 Provide information if the path is mounted :param real_name: The real name of the mount point where the device is mounted. :param device: The device that is being mounted. :param mkmnt: Whether or not the mount point should be created. :param fstype: The file system that is used. :param mount_opts: Additional options used when mounting the device. :return: Boolean if message was sent successfully. CLI Example: .. code-block:: bash salt '*' mount.write_mount_cache /mnt/share /dev/sda1 False ext4 defaults,nosuid ''' cache = salt.utils.mount.read_cache(__opts__) if not cache: cache = {} cache['mounts'] = {} else: if 'mounts' not in cache: cache['mounts'] = {} cache['mounts'][real_name] = {'device': device, 'fstype': fstype, 'mkmnt': mkmnt, 'opts': mount_opts} cache_write = salt.utils.mount.write_cache(cache, __opts__) if cache_write: return True else: raise CommandExecutionError('Unable to write mount cache.') def delete_mount_cache(real_name): ''' .. versionadded:: 2018.3.0 Provide information if the path is mounted CLI Example: .. code-block:: bash salt '*' mount.delete_mount_cache /mnt/share ''' cache = salt.utils.mount.read_cache(__opts__) if cache: if 'mounts' in cache: if real_name in cache['mounts']: del cache['mounts'][real_name] cache_write = salt.utils.mount.write_cache(cache, __opts__) if not cache_write: raise CommandExecutionError('Unable to write mount cache.') return True def _filesystems(config='/etc/filesystems', leading_key=True): ''' Return the contents of the filesystems in an OrderedDict config File containing filesystem infomation leading_key True return dictionary keyed by 'name' and value as dictionary with other keys, values (name excluded) OrderedDict({ '/dir' : OrderedDict({'dev': '/dev/hd8', .... }})) False return dictionary keyed by 'name' and value as dictionary with all keys, values (name included) OrderedDict({ '/dir' : OrderedDict({'name': '/dir', 'dev': '/dev/hd8', ... })}) ''' ret = OrderedDict() lines = [] parsing_block = False if not os.path.isfile(config) or 'AIX' not in __grains__['kernel']: return ret # read in block of filesystems, block starts with '/' till empty line with salt.utils.files.fopen(config) as ifile: for line in ifile: line = salt.utils.stringutils.to_unicode(line) # skip till first entry if not line.startswith('/') and not parsing_block: continue if line.startswith('/'): parsing_block = True lines.append(line) elif not line.split(): parsing_block = False try: entry = _FileSystemsEntry.dict_from_lines( lines, _FileSystemsEntry.compatibility_keys) lines = [] if 'opts' in entry: entry['opts'] = entry['opts'].split(',') while entry['name'] in ret: entry['name'] += '_' if leading_key: ret[entry.pop('name')] = entry else: ret[entry['name']] = entry except _FileSystemsEntry.ParseError: pass else: lines.append(line) return ret def filesystems(config='/etc/filesystems'): ''' .. versionadded:: 2018.3.3 List the contents of the filesystems CLI Example: .. code-block:: bash salt '*' mount.filesystems ''' ret = {} if 'AIX' not in __grains__['kernel']: return ret ret_dict = _filesystems(config) if ret_dict: ret_key = next(iter(ret_dict.keys())) ret = {ret_key: dict(ret_dict[ret_key])} return ret def rm_filesystems(name, device, config='/etc/filesystems'): ''' .. versionadded:: 2018.3.3 Remove the mount point from the filesystems CLI Example: .. code-block:: bash salt '*' mount.rm_filesystems /mnt/foo /dev/sdg ''' modified = False view_lines = [] if 'AIX' not in __grains__['kernel']: return modified criteria = _FileSystemsEntry(name=name, dev=device) try: fsys_filedict = _filesystems(config, False) for fsys_view in six.viewitems(fsys_filedict): try: if criteria.match(fsys_view): modified = True else: view_lines.append(fsys_view) except _FileSystemsEntry.ParseError: view_lines.append(fsys_view) except (IOError, OSError) as exc: raise CommandExecutionError("Couldn't read from {0}: {1}".format(config, exc)) if modified: try: with salt.utils.files.fopen(config, 'wb') as ofile: for fsys_view in view_lines: entry = fsys_view[1] mystrg = _FileSystemsEntry.dict_to_lines(entry) ofile.writelines(salt.utils.data.encode(mystrg)) except (IOError, OSError) as exc: raise CommandExecutionError("Couldn't write to {0}: {1}".format(config, exc)) return modified
saltstack/salt
salt/modules/mount.py
rm_filesystems
python
def rm_filesystems(name, device, config='/etc/filesystems'): ''' .. versionadded:: 2018.3.3 Remove the mount point from the filesystems CLI Example: .. code-block:: bash salt '*' mount.rm_filesystems /mnt/foo /dev/sdg ''' modified = False view_lines = [] if 'AIX' not in __grains__['kernel']: return modified criteria = _FileSystemsEntry(name=name, dev=device) try: fsys_filedict = _filesystems(config, False) for fsys_view in six.viewitems(fsys_filedict): try: if criteria.match(fsys_view): modified = True else: view_lines.append(fsys_view) except _FileSystemsEntry.ParseError: view_lines.append(fsys_view) except (IOError, OSError) as exc: raise CommandExecutionError("Couldn't read from {0}: {1}".format(config, exc)) if modified: try: with salt.utils.files.fopen(config, 'wb') as ofile: for fsys_view in view_lines: entry = fsys_view[1] mystrg = _FileSystemsEntry.dict_to_lines(entry) ofile.writelines(salt.utils.data.encode(mystrg)) except (IOError, OSError) as exc: raise CommandExecutionError("Couldn't write to {0}: {1}".format(config, exc)) return modified
.. versionadded:: 2018.3.3 Remove the mount point from the filesystems CLI Example: .. code-block:: bash salt '*' mount.rm_filesystems /mnt/foo /dev/sdg
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/mount.py#L1813-L1857
[ "def encode(data, encoding=None, errors='strict', keep=False,\n preserve_dict_class=False, preserve_tuples=False):\n '''\n Generic function which will encode whichever type is passed, if necessary\n\n If `strict` is True, and `keep` is False, and we fail to encode, a\n UnicodeEncodeError will be raised. Passing `keep` as True allows for the\n original value to silently be returned in cases where encoding fails. This\n can be useful for cases where the data passed to this function is likely to\n contain binary blobs.\n '''\n if isinstance(data, Mapping):\n return encode_dict(data, encoding, errors, keep,\n preserve_dict_class, preserve_tuples)\n elif isinstance(data, list):\n return encode_list(data, encoding, errors, keep,\n preserve_dict_class, preserve_tuples)\n elif isinstance(data, tuple):\n return encode_tuple(data, encoding, errors, keep, preserve_dict_class) \\\n if preserve_tuples \\\n else encode_list(data, encoding, errors, keep,\n preserve_dict_class, preserve_tuples)\n else:\n try:\n return salt.utils.stringutils.to_bytes(data, encoding, errors)\n except TypeError:\n # to_bytes raises a TypeError when input is not a\n # string/bytestring/bytearray. This is expected and simply\n # means we are going to leave the value as-is.\n pass\n except UnicodeEncodeError:\n if not keep:\n raise\n return data\n", "def 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 _filesystems(config='/etc/filesystems', leading_key=True):\n '''\n Return the contents of the filesystems in an OrderedDict\n\n config\n File containing filesystem infomation\n\n leading_key\n True return dictionary keyed by 'name' and value as dictionary with other keys, values (name excluded)\n OrderedDict({ '/dir' : OrderedDict({'dev': '/dev/hd8', .... }}))\n\n False return dictionary keyed by 'name' and value as dictionary with all keys, values (name included)\n OrderedDict({ '/dir' : OrderedDict({'name': '/dir', 'dev': '/dev/hd8', ... })})\n '''\n ret = OrderedDict()\n lines = []\n parsing_block = False\n if not os.path.isfile(config) or 'AIX' not in __grains__['kernel']:\n return ret\n\n # read in block of filesystems, block starts with '/' till empty line\n with salt.utils.files.fopen(config) as ifile:\n for line in ifile:\n line = salt.utils.stringutils.to_unicode(line)\n\n # skip till first entry\n if not line.startswith('/') and not parsing_block:\n continue\n\n if line.startswith('/'):\n parsing_block = True\n lines.append(line)\n elif not line.split():\n parsing_block = False\n try:\n entry = _FileSystemsEntry.dict_from_lines(\n lines,\n _FileSystemsEntry.compatibility_keys)\n lines = []\n if 'opts' in entry:\n entry['opts'] = entry['opts'].split(',')\n while entry['name'] in ret:\n entry['name'] += '_'\n\n if leading_key:\n ret[entry.pop('name')] = entry\n else:\n ret[entry['name']] = entry\n\n except _FileSystemsEntry.ParseError:\n pass\n else:\n lines.append(line)\n\n return ret\n", "def dict_to_lines(cls, fsys_dict_entry):\n entry = fsys_dict_entry\n strg_out = entry['name'] + ':' + os.linesep\n for k, v in six.viewitems(entry):\n if 'name' not in k:\n strg_out += '\\t{0}\\t\\t= {1}'.format(k, v) + os.linesep\n strg_out += os.linesep\n return six.text_type(strg_out)\n", "def match(self, fsys_view):\n '''\n Compare potentially partial criteria against built filesystems entry dictionary\n '''\n evalue_dict = fsys_view[1]\n for key, value in six.viewitems(self.criteria):\n if key in evalue_dict:\n if evalue_dict[key] != value:\n return False\n else:\n return False\n return True\n" ]
# -*- coding: utf-8 -*- ''' Salt module to manage Unix mounts and the fstab file ''' # Import python libs from __future__ import absolute_import, print_function, unicode_literals import os import re import logging # Import salt libs import salt.utils.args import salt.utils.data import salt.utils.files import salt.utils.path import salt.utils.platform import salt.utils.mount import salt.utils.stringutils from salt.utils.odict import OrderedDict from salt.exceptions import CommandNotFoundError, CommandExecutionError # Import 3rd-party libs from salt.ext import six from salt.ext.six.moves import filter, zip # pylint: disable=import-error,redefined-builtin # Set up logger log = logging.getLogger(__name__) # Define the module's virtual name __virtualname__ = 'mount' def __virtual__(): ''' Only load on POSIX-like systems ''' # Disable on Windows, a specific file module exists: if salt.utils.platform.is_windows(): return (False, 'The mount module cannot be loaded: not a POSIX-like system.') return True def _list_mounts(): ret = {} if __grains__['os'] in ['MacOS', 'Darwin']: mounts = __salt__['cmd.run_stdout']('mount') else: mounts = __salt__['cmd.run_stdout']('mount -l') for line in mounts.split('\n'): comps = re.sub(r"\s+", " ", line).split() if len(comps) >= 3: ret[comps[2]] = comps[0] return ret def _active_mountinfo(ret): _list = _list_mounts() filename = '/proc/self/mountinfo' if not os.access(filename, os.R_OK): msg = 'File not readable {0}' raise CommandExecutionError(msg.format(filename)) if 'disk.blkid' not in __context__: __context__['disk.blkid'] = __salt__['disk.blkid']() blkid_info = __context__['disk.blkid'] with salt.utils.files.fopen(filename) as ifile: for line in ifile: comps = salt.utils.stringutils.to_unicode(line).split() device = comps[2].split(':') # each line can have any number of # optional parameters, we use the # location of the separator field to # determine the location of the elements # after it. _sep = comps.index('-') device_name = comps[_sep + 2] device_uuid = None device_label = None if device_name: device_uuid = blkid_info.get(device_name, {}).get('UUID') device_uuid = device_uuid and device_uuid.lower() device_label = blkid_info.get(device_name, {}).get('LABEL') ret[comps[4]] = {'mountid': comps[0], 'parentid': comps[1], 'major': device[0], 'minor': device[1], 'root': comps[3], 'opts': _resolve_user_group_names(comps[5].split(',')), 'fstype': comps[_sep + 1], 'device': device_name.replace('\\040', '\\ '), 'alt_device': _list.get(comps[4], None), 'superopts': _resolve_user_group_names(comps[_sep + 3].split(',')), 'device_uuid': device_uuid, 'device_label': device_label} return ret def _active_mounts(ret): ''' List active mounts on Linux systems ''' _list = _list_mounts() filename = '/proc/self/mounts' if not os.access(filename, os.R_OK): msg = 'File not readable {0}' raise CommandExecutionError(msg.format(filename)) with salt.utils.files.fopen(filename) as ifile: for line in ifile: comps = salt.utils.stringutils.to_unicode(line).split() ret[comps[1]] = {'device': comps[0], 'alt_device': _list.get(comps[1], None), 'fstype': comps[2], 'opts': _resolve_user_group_names(comps[3].split(','))} return ret def _active_mounts_aix(ret): ''' List active mounts on AIX systems ''' for line in __salt__['cmd.run_stdout']('mount -p').split('\n'): comps = re.sub(r"\s+", " ", line).split() if comps: if comps[0] == 'node' or comps[0] == '--------': continue comps_len = len(comps) if line.startswith((' ', '\t')): curr_opts = _resolve_user_group_names(comps[6].split(',')) if 7 == comps_len else [] if curr_opts: ret[comps[1]] = {'device': comps[0], 'fstype': comps[2], 'opts': curr_opts} else: ret[comps[1]] = {'device': comps[0], 'fstype': comps[2]} else: curr_opts = _resolve_user_group_names(comps[7].split(',')) if 8 == comps_len else [] if curr_opts: ret[comps[2]] = {'node': comps[0], 'device': comps[1], 'fstype': comps[3], 'opts': curr_opts} else: ret[comps[2]] = {'node': comps[0], 'device': comps[1], 'fstype': comps[3]} return ret def _active_mounts_freebsd(ret): ''' List active mounts on FreeBSD systems ''' for line in __salt__['cmd.run_stdout']('mount -p').split('\n'): comps = re.sub(r"\s+", " ", line).split() ret[comps[1]] = {'device': comps[0], 'fstype': comps[2], 'opts': _resolve_user_group_names(comps[3].split(','))} return ret def _active_mounts_solaris(ret): ''' List active mounts on Solaris systems ''' for line in __salt__['cmd.run_stdout']('mount -v').split('\n'): comps = re.sub(r"\s+", " ", line).split() ret[comps[2]] = {'device': comps[0], 'fstype': comps[4], 'opts': _resolve_user_group_names(comps[5].split('/'))} return ret def _active_mounts_openbsd(ret): ''' List active mounts on OpenBSD systems ''' for line in __salt__['cmd.run_stdout']('mount -v').split('\n'): comps = re.sub(r"\s+", " ", line).split() parens = re.findall(r'\((.*?)\)', line, re.DOTALL) if len(parens) > 1: nod = __salt__['cmd.run_stdout']('ls -l {0}'.format(comps[0])) nod = ' '.join(nod.split()).split(" ") ret[comps[3]] = {'device': comps[0], 'fstype': comps[5], 'opts': _resolve_user_group_names(parens[1].split(", ")), 'major': six.text_type(nod[4].strip(",")), 'minor': six.text_type(nod[5]), 'device_uuid': parens[0]} else: ret[comps[2]] = {'device': comps[0], 'fstype': comps[4], 'opts': _resolve_user_group_names(parens[0].split(", "))} return ret def _active_mounts_darwin(ret): ''' List active mounts on Mac OS systems ''' for line in __salt__['cmd.run_stdout']('mount').split('\n'): comps = re.sub(r"\s+", " ", line).split() parens = re.findall(r'\((.*?)\)', line, re.DOTALL)[0].split(", ") ret[comps[2]] = {'device': comps[0], 'fstype': parens[0], 'opts': _resolve_user_group_names(parens[1:])} return ret def _resolve_user_group_names(opts): ''' Resolve user and group names in related opts ''' name_id_opts = {'uid': 'user.info', 'gid': 'group.info'} for ind, opt in enumerate(opts): if opt.split('=')[0] in name_id_opts: _givenid = opt.split('=')[1] _param = opt.split('=')[0] _id = _givenid if not re.match('[0-9]+$', _givenid): _info = __salt__[name_id_opts[_param]](_givenid) if _info and _param in _info: _id = _info[_param] opts[ind] = _param + '=' + six.text_type(_id) opts[ind] = opts[ind].replace('\\040', '\\ ') return opts def active(extended=False): ''' List the active mounts. CLI Example: .. code-block:: bash salt '*' mount.active ''' ret = {} if __grains__['os'] == 'FreeBSD': _active_mounts_freebsd(ret) elif 'AIX' in __grains__['kernel']: _active_mounts_aix(ret) elif __grains__['kernel'] == 'SunOS': _active_mounts_solaris(ret) elif __grains__['os'] == 'OpenBSD': _active_mounts_openbsd(ret) elif __grains__['os'] in ['MacOS', 'Darwin']: _active_mounts_darwin(ret) else: if extended: try: _active_mountinfo(ret) except CommandExecutionError: _active_mounts(ret) else: _active_mounts(ret) return ret class _fstab_entry(object): ''' Utility class for manipulating fstab entries. Primarily we're parsing, formatting, and comparing lines. Parsing emits dicts expected from fstab() or raises a ValueError. Note: We'll probably want to use os.normpath and os.normcase on 'name' ''' class ParseError(ValueError): ''' Error raised when a line isn't parsible as an fstab entry ''' fstab_keys = ('device', 'name', 'fstype', 'opts', 'dump', 'pass_num') # preserve data format compatibility_keys = ('device', 'name', 'fstype', 'opts', 'dump', 'pass') fstab_format = '{device}\t\t{name}\t{fstype}\t{opts}\t{dump} {pass_num}\n' @classmethod def dict_from_line(cls, line, keys=fstab_keys): if len(keys) != 6: raise ValueError('Invalid key array: {0}'.format(keys)) if line.startswith('#'): raise cls.ParseError("Comment!") comps = line.split() if len(comps) < 4 or len(comps) > 6: raise cls.ParseError("Invalid Entry!") comps.extend(['0'] * (len(keys) - len(comps))) return dict(zip(keys, comps)) @classmethod def from_line(cls, *args, **kwargs): return cls(** cls.dict_from_line(*args, **kwargs)) @classmethod def dict_to_line(cls, entry): return cls.fstab_format.format(**entry) def __str__(self): ''' String value, only works for full repr ''' return self.dict_to_line(self.criteria) def __repr__(self): ''' Always works ''' return repr(self.criteria) def pick(self, keys): ''' Returns an instance with just those keys ''' subset = dict([(key, self.criteria[key]) for key in keys]) return self.__class__(**subset) def __init__(self, **criteria): ''' Store non-empty, non-null values to use as filter ''' items = [key_value for key_value in six.iteritems(criteria) if key_value[1] is not None] items = [(key_value1[0], six.text_type(key_value1[1])) for key_value1 in items] self.criteria = dict(items) @staticmethod def norm_path(path): ''' Resolve equivalent paths equivalently ''' return os.path.normcase(os.path.normpath(path)) def match(self, line): ''' Compare potentially partial criteria against line ''' entry = self.dict_from_line(line) for key, value in six.iteritems(self.criteria): if entry[key] != value: return False return True class _vfstab_entry(object): ''' Utility class for manipulating vfstab entries. Primarily we're parsing, formatting, and comparing lines. Parsing emits dicts expected from fstab() or raises a ValueError. Note: We'll probably want to use os.normpath and os.normcase on 'name' Note: This parses vfstab entries on Solaris like systems #device device mount FS fsck mount mount #to mount to fsck point type pass at boot options # /devices - /devices devfs - no - ''' class ParseError(ValueError): '''Error raised when a line isn't parsible as an fstab entry''' vfstab_keys = ('device', 'device_fsck', 'name', 'fstype', 'pass_fsck', 'mount_at_boot', 'opts') # NOTE: weird formatting to match default spacing on Solaris vfstab_format = '{device:<11} {device_fsck:<3} {name:<19} {fstype:<8} {pass_fsck:<3} {mount_at_boot:<6} {opts}\n' @classmethod def dict_from_line(cls, line): if line.startswith('#'): raise cls.ParseError("Comment!") comps = line.split() if len(comps) != 7: raise cls.ParseError("Invalid Entry!") return dict(zip(cls.vfstab_keys, comps)) @classmethod def from_line(cls, *args, **kwargs): return cls(** cls.dict_from_line(*args, **kwargs)) @classmethod def dict_to_line(cls, entry): return cls.vfstab_format.format(**entry) def __str__(self): ''' String value, only works for full repr ''' return self.dict_to_line(self.criteria) def __repr__(self): ''' Always works ''' return repr(self.criteria) def pick(self, keys): ''' Returns an instance with just those keys ''' subset = dict([(key, self.criteria[key]) for key in keys]) return self.__class__(**subset) def __init__(self, **criteria): ''' Store non-empty, non-null values to use as filter ''' items = [key_value for key_value in six.iteritems(criteria) if key_value[1] is not None] items = [(key_value1[0], six.text_type(key_value1[1])) for key_value1 in items] self.criteria = dict(items) @staticmethod def norm_path(path): ''' Resolve equivalent paths equivalently ''' return os.path.normcase(os.path.normpath(path)) def match(self, line): ''' Compare potentially partial criteria against line ''' entry = self.dict_from_line(line) for key, value in six.iteritems(self.criteria): if entry[key] != value: return False return True class _FileSystemsEntry(object): ''' Utility class for manipulating filesystem entries. Primarily we're parsing, formatting, and comparing lines. Parsing emits dicts expected from fstab() or raises a ValueError. Note: We'll probably want to use os.normpath and os.normcase on 'name' ''' class ParseError(ValueError): ''' Error raised when a line isn't parsible as an fstab entry ''' filesystems_keys = ('device', 'name', 'fstype', 'vfstype', 'opts', 'mount') # preserve data format of filesystems compatibility_keys = ('dev', 'dev', 'name', 'fstype', 'vfstype', 'opts', 'mount', 'type', 'vfs', 'account', 'boot', 'check', 'free', 'nodename', 'quota', 'size', 'vol', 'log') @classmethod def dict_from_lines(cls, lines, keys=filesystems_keys): if len(lines) < 2: raise ValueError('Invalid number of lines: {0}'.format(lines)) if not keys: # if empty force default filesystems_keys keys = _FileSystemsEntry.filesystems_keys elif len(keys) < 6: raise ValueError('Invalid key name array: {0}'.format(keys)) blk_lines = lines orddict = OrderedDict() orddict['name'] = blk_lines[0].split(':')[0].strip() blk_lines.pop(0) for line in blk_lines: if line.startswith('#'): raise cls.ParseError("Comment!") comps = line.split('= ') if len(comps) != 2: raise cls.ParseError("Invalid Entry!") key_name = comps[0].strip() if key_name in keys: orddict[key_name] = comps[1].strip() else: raise ValueError('Invalid name for use in filesystems: {0}'.format(key_name)) return orddict @classmethod def dict_from_cmd_line(cls, ipargs, keys): cmdln_dict = ipargs if keys: for key, value in keys: # ignore unknown or local scope keys if key.startswith('__'): continue if key in _FileSystemsEntry.compatibility_keys: cmdln_dict[key] = value return cmdln_dict @classmethod def from_line(cls, *args, **kwargs): return cls(** cls.dict_from_cmd_line(*args, **kwargs)) @classmethod def dict_to_lines(cls, fsys_dict_entry): entry = fsys_dict_entry strg_out = entry['name'] + ':' + os.linesep for k, v in six.viewitems(entry): if 'name' not in k: strg_out += '\t{0}\t\t= {1}'.format(k, v) + os.linesep strg_out += os.linesep return six.text_type(strg_out) def dict_from_entry(self): ret = OrderedDict() ret[self.criteria['name']] = self.criteria return ret def __str__(self): ''' String value, only works for full repr ''' return self.dict_to_lines(self.criteria) def __repr__(self): ''' Always works ''' return repr(self.criteria) def pick(self, keys): ''' Returns an instance with just those keys ''' subset = dict([(key, self.criteria[key]) for key in keys]) return self.__class__(**subset) def __init__(self, **criteria): ''' Store non-empty, non-null values to use as filter ''' items = [key_value for key_value in six.iteritems(criteria) if key_value[1] is not None] items = [(key_value1[0], six.text_type(key_value1[1])) for key_value1 in items] self.criteria = OrderedDict(items) @staticmethod def norm_path(path): ''' Resolve equivalent paths equivalently ''' return os.path.normcase(os.path.normpath(path)) def match(self, fsys_view): ''' Compare potentially partial criteria against built filesystems entry dictionary ''' evalue_dict = fsys_view[1] for key, value in six.viewitems(self.criteria): if key in evalue_dict: if evalue_dict[key] != value: return False else: return False return True def __getitem__(self, key): ''' Return value for input key ''' return self.criteria[key] def fstab(config='/etc/fstab'): ''' .. versionchanged:: 2016.3.2 List the contents of the fstab CLI Example: .. code-block:: bash salt '*' mount.fstab ''' ret = {} if not os.path.isfile(config): return ret with salt.utils.files.fopen(config) as ifile: for line in ifile: line = salt.utils.stringutils.to_unicode(line) try: if __grains__['kernel'] == 'SunOS': # Note: comments use in default vfstab file! if line[0] == '#': continue entry = _vfstab_entry.dict_from_line( line) else: entry = _fstab_entry.dict_from_line( line, _fstab_entry.compatibility_keys) entry['opts'] = entry['opts'].split(',') while entry['name'] in ret: entry['name'] += '_' ret[entry.pop('name')] = entry except _fstab_entry.ParseError: pass except _vfstab_entry.ParseError: pass return ret def vfstab(config='/etc/vfstab'): ''' .. versionadded:: 2016.3.2 List the contents of the vfstab CLI Example: .. code-block:: bash salt '*' mount.vfstab ''' # NOTE: vfstab is a wrapper for fstab return fstab(config) def rm_fstab(name, device, config='/etc/fstab'): ''' .. versionchanged:: 2016.3.2 Remove the mount point from the fstab CLI Example: .. code-block:: bash salt '*' mount.rm_fstab /mnt/foo /dev/sdg ''' modified = False if __grains__['kernel'] == 'SunOS': criteria = _vfstab_entry(name=name, device=device) else: criteria = _fstab_entry(name=name, device=device) lines = [] try: with salt.utils.files.fopen(config, 'r') as ifile: for line in ifile: line = salt.utils.stringutils.to_unicode(line) try: if criteria.match(line): modified = True else: lines.append(line) except _fstab_entry.ParseError: lines.append(line) except _vfstab_entry.ParseError: lines.append(line) except (IOError, OSError) as exc: msg = "Couldn't read from {0}: {1}" raise CommandExecutionError(msg.format(config, exc)) if modified: try: with salt.utils.files.fopen(config, 'wb') as ofile: ofile.writelines(salt.utils.data.encode(lines)) except (IOError, OSError) as exc: msg = "Couldn't write to {0}: {1}" raise CommandExecutionError(msg.format(config, exc)) # Note: not clear why we always return 'True' # --just copying previous behavior at this point... return True def rm_vfstab(name, device, config='/etc/vfstab'): ''' .. versionadded:: 2016.3.2 Remove the mount point from the vfstab CLI Example: .. code-block:: bash salt '*' mount.rm_vfstab /mnt/foo /device/c0t0d0p0 ''' ## NOTE: rm_vfstab is a wrapper for rm_fstab return rm_fstab(name, device, config) def set_fstab( name, device, fstype, opts='defaults', dump=0, pass_num=0, config='/etc/fstab', test=False, match_on='auto', **kwargs): ''' Verify that this mount is represented in the fstab, change the mount to match the data passed, or add the mount if it is not present. CLI Example: .. code-block:: bash salt '*' mount.set_fstab /mnt/foo /dev/sdz1 ext4 ''' # Fix the opts type if it is a list if isinstance(opts, list): opts = ','.join(opts) # preserve arguments for updating entry_args = { 'name': name, 'device': device.replace('\\ ', '\\040'), 'fstype': fstype, 'opts': opts.replace('\\ ', '\\040'), 'dump': dump, 'pass_num': pass_num, } lines = [] ret = None # Transform match_on into list--items will be checked later if isinstance(match_on, list): pass elif not isinstance(match_on, six.string_types): msg = 'match_on must be a string or list of strings' raise CommandExecutionError(msg) elif match_on == 'auto': # Try to guess right criteria for auto.... # NOTE: missing some special fstypes here specialFSes = frozenset([ 'none', 'tmpfs', 'sysfs', 'proc', 'fusectl', 'debugfs', 'securityfs', 'devtmpfs', 'cgroup', 'btrfs']) if fstype in specialFSes: match_on = ['name'] else: match_on = ['device'] else: match_on = [match_on] # generate entry and criteria objects, handle invalid keys in match_on entry = _fstab_entry(**entry_args) try: criteria = entry.pick(match_on) except KeyError: filterFn = lambda key: key not in _fstab_entry.fstab_keys invalid_keys = filter(filterFn, match_on) msg = 'Unrecognized keys in match_on: "{0}"'.format(invalid_keys) raise CommandExecutionError(msg) # parse file, use ret to cache status if not os.path.isfile(config): raise CommandExecutionError('Bad config file "{0}"'.format(config)) try: with salt.utils.files.fopen(config, 'r') as ifile: for line in ifile: line = salt.utils.stringutils.to_unicode(line) try: if criteria.match(line): # Note: If ret isn't None here, # we've matched multiple lines ret = 'present' if entry.match(line): lines.append(line) else: ret = 'change' lines.append(six.text_type(entry)) else: lines.append(line) except _fstab_entry.ParseError: lines.append(line) except (IOError, OSError) as exc: msg = 'Couldn\'t read from {0}: {1}' raise CommandExecutionError(msg.format(config, exc)) # add line if not present or changed if ret is None: lines.append(six.text_type(entry)) ret = 'new' if ret != 'present': # ret in ['new', 'change']: if not salt.utils.args.test_mode(test=test, **kwargs): try: with salt.utils.files.fopen(config, 'wb') as ofile: # The line was changed, commit it! ofile.writelines(salt.utils.data.encode(lines)) except (IOError, OSError): msg = 'File not writable {0}' raise CommandExecutionError(msg.format(config)) return ret def set_vfstab( name, device, fstype, opts='-', device_fsck='-', pass_fsck='-', mount_at_boot='yes', config='/etc/vfstab', test=False, match_on='auto', **kwargs): ''' ..verionadded:: 2016.3.2 Verify that this mount is represented in the fstab, change the mount to match the data passed, or add the mount if it is not present. CLI Example: .. code-block:: bash salt '*' mount.set_vfstab /mnt/foo /device/c0t0d0p0 ufs ''' # Fix the opts type if it is a list if isinstance(opts, list): opts = ','.join(opts) # Map unknown values for mount_at_boot to no if mount_at_boot != 'yes': mount_at_boot = 'no' # preserve arguments for updating entry_args = { 'name': name, 'device': device, 'fstype': fstype, 'opts': opts, 'device_fsck': device_fsck, 'pass_fsck': pass_fsck, 'mount_at_boot': mount_at_boot, } lines = [] ret = None # Transform match_on into list--items will be checked later if isinstance(match_on, list): pass elif not isinstance(match_on, six.string_types): msg = 'match_on must be a string or list of strings' raise CommandExecutionError(msg) elif match_on == 'auto': # Try to guess right criteria for auto.... # NOTE: missing some special fstypes here specialFSes = frozenset([ 'devfs', 'proc', 'ctfs', 'objfs', 'sharefs', 'fs', 'tmpfs']) if fstype in specialFSes: match_on = ['name'] else: match_on = ['device'] else: match_on = [match_on] # generate entry and criteria objects, handle invalid keys in match_on entry = _vfstab_entry(**entry_args) try: criteria = entry.pick(match_on) except KeyError: filterFn = lambda key: key not in _vfstab_entry.vfstab_keys invalid_keys = filter(filterFn, match_on) msg = 'Unrecognized keys in match_on: "{0}"'.format(invalid_keys) raise CommandExecutionError(msg) # parse file, use ret to cache status if not os.path.isfile(config): raise CommandExecutionError('Bad config file "{0}"'.format(config)) try: with salt.utils.files.fopen(config, 'r') as ifile: for line in ifile: line = salt.utils.stringutils.to_unicode(line) try: if criteria.match(line): # Note: If ret isn't None here, # we've matched multiple lines ret = 'present' if entry.match(line): lines.append(line) else: ret = 'change' lines.append(six.text_type(entry)) else: lines.append(line) except _vfstab_entry.ParseError: lines.append(line) except (IOError, OSError) as exc: msg = 'Couldn\'t read from {0}: {1}' raise CommandExecutionError(msg.format(config, exc)) # add line if not present or changed if ret is None: lines.append(six.text_type(entry)) ret = 'new' if ret != 'present': # ret in ['new', 'change']: if not salt.utils.args.test_mode(test=test, **kwargs): try: with salt.utils.files.fopen(config, 'wb') as ofile: # The line was changed, commit it! ofile.writelines(salt.utils.data.encode(lines)) except (IOError, OSError): msg = 'File not writable {0}' raise CommandExecutionError(msg.format(config)) return ret def rm_automaster(name, device, config='/etc/auto_salt'): ''' Remove the mount point from the auto_master CLI Example: .. code-block:: bash salt '*' mount.rm_automaster /mnt/foo /dev/sdg ''' contents = automaster(config) if name not in contents: return True # The entry is present, get rid of it lines = [] try: with salt.utils.files.fopen(config, 'r') as ifile: for line in ifile: line = salt.utils.stringutils.to_unicode(line) if line.startswith('#'): # Commented lines.append(line) continue if not line.strip(): # Blank line lines.append(line) continue comps = line.split() if len(comps) != 3: # Invalid entry lines.append(line) continue comps = line.split() prefix = "/.." name_chk = comps[0].replace(prefix, "") device_fmt = comps[2].split(":") if device: if name_chk == name and device_fmt[1] == device: continue else: if name_chk == name: continue lines.append(line) except (IOError, OSError) as exc: msg = "Couldn't read from {0}: {1}" raise CommandExecutionError(msg.format(config, exc)) try: with salt.utils.files.fopen(config, 'wb') as ofile: ofile.writelines(salt.utils.data.encode(lines)) except (IOError, OSError) as exc: msg = "Couldn't write to {0}: {1}" raise CommandExecutionError(msg.format(config, exc)) # Update automount __salt__['cmd.run']('automount -cv') return True def set_automaster( name, device, fstype, opts='', config='/etc/auto_salt', test=False, **kwargs): ''' Verify that this mount is represented in the auto_salt, change the mount to match the data passed, or add the mount if it is not present. CLI Example: .. code-block:: bash salt '*' mount.set_automaster /mnt/foo /dev/sdz1 ext4 ''' # Fix the opts type if it is a list if isinstance(opts, list): opts = ','.join(opts) lines = [] change = False present = False automaster_file = "/etc/auto_master" if not os.path.isfile(config): __salt__['file.touch'](config) __salt__['file.append'](automaster_file, "/-\t\t\t{0}".format(config)) name = "/..{0}".format(name) device_fmt = "{0}:{1}".format(fstype, device) type_opts = "-fstype={0},{1}".format(fstype, opts) if fstype == 'smbfs': device_fmt = device_fmt.replace(fstype, "") try: with salt.utils.files.fopen(config, 'r') as ifile: for line in ifile: line = salt.utils.stringutils.to_unicode(line) if line.startswith('#'): # Commented lines.append(line) continue if not line.strip(): # Blank line lines.append(line) continue comps = line.split() if len(comps) != 3: # Invalid entry lines.append(line) continue if comps[0] == name or comps[2] == device_fmt: # check to see if there are changes # and fix them if there are any present = True if comps[0] != name: change = True comps[0] = name if comps[1] != type_opts: change = True comps[1] = type_opts if comps[2] != device_fmt: change = True comps[2] = device_fmt if change: log.debug( 'auto_master entry for mount point %s needs to be ' 'updated', name ) newline = ( '{0}\t{1}\t{2}\n'.format( name, type_opts, device_fmt) ) lines.append(newline) else: lines.append(line) except (IOError, OSError) as exc: msg = 'Couldn\'t read from {0}: {1}' raise CommandExecutionError(msg.format(config, exc)) if change: if not salt.utils.args.test_mode(test=test, **kwargs): try: with salt.utils.files.fopen(config, 'wb') as ofile: # The line was changed, commit it! ofile.writelines(salt.utils.data.encode(lines)) except (IOError, OSError): msg = 'File not writable {0}' raise CommandExecutionError(msg.format(config)) return 'change' if not change: if present: # The right entry is already here return 'present' else: if not salt.utils.args.test_mode(test=test, **kwargs): # The entry is new, add it to the end of the fstab newline = ( '{0}\t{1}\t{2}\n'.format( name, type_opts, device_fmt) ) lines.append(newline) try: with salt.utils.files.fopen(config, 'wb') as ofile: # The line was changed, commit it! ofile.writelines(salt.utils.data.encode(lines)) except (IOError, OSError): raise CommandExecutionError( 'File not writable {0}'.format( config ) ) return 'new' def automaster(config='/etc/auto_salt'): ''' List the contents of the auto master CLI Example: .. code-block:: bash salt '*' mount.automaster ''' ret = {} if not os.path.isfile(config): return ret with salt.utils.files.fopen(config) as ifile: for line in ifile: line = salt.utils.stringutils.to_unicode(line) if line.startswith('#'): # Commented continue if not line.strip(): # Blank line continue comps = line.split() if len(comps) != 3: # Invalid entry continue prefix = "/.." name = comps[0].replace(prefix, "") device_fmt = comps[2].split(":") opts = comps[1].split(',') ret[name] = {'device': device_fmt[1], 'fstype': opts[0], 'opts': opts[1:]} return ret def mount(name, device, mkmnt=False, fstype='', opts='defaults', user=None, util='mount'): ''' Mount a device CLI Example: .. code-block:: bash salt '*' mount.mount /mnt/foo /dev/sdz1 True ''' if util != 'mount': # This functionality used to live in img.mount_image if util == 'guestfs': return __salt__['guestfs.mount'](name, root=device) elif util == 'qemu_nbd': mnt = __salt__['qemu_nbd.init'](name, device) if not mnt: return False first = next(six.iterkeys(mnt)) __context__['img.mnt_{0}'.format(first)] = mnt return first return False # Darwin doesn't expect defaults when mounting without other options if 'defaults' in opts and __grains__['os'] in ['MacOS', 'Darwin', 'AIX']: opts = None if isinstance(opts, six.string_types): opts = opts.split(',') if not os.path.exists(name) and mkmnt: __salt__['file.mkdir'](name, user=user) args = '' if opts is not None: lopts = ','.join(opts) args = '-o {0}'.format(lopts) if fstype: # use of fstype on AIX differs from typical Linux use of -t # functionality AIX uses -v vfsname, -t fstype mounts all with # fstype in /etc/filesystems if 'AIX' in __grains__['os']: args += ' -v {0}'.format(fstype) elif 'solaris' in __grains__['os'].lower(): args += ' -F {0}'.format(fstype) else: args += ' -t {0}'.format(fstype) cmd = 'mount {0} {1} {2} '.format(args, device, name) out = __salt__['cmd.run_all'](cmd, runas=user, python_shell=False) if out['retcode']: return out['stderr'] return True def remount(name, device, mkmnt=False, fstype='', opts='defaults', user=None): ''' Attempt to remount a device, if the device is not already mounted, mount is called CLI Example: .. code-block:: bash salt '*' mount.remount /mnt/foo /dev/sdz1 True ''' force_mount = False if __grains__['os'] in ['MacOS', 'Darwin']: if opts == 'defaults': opts = 'noowners' if fstype == 'smbfs': force_mount = True if 'AIX' in __grains__['os']: if opts == 'defaults': opts = [] if isinstance(opts, six.string_types): opts = opts.split(',') mnts = active() if name in mnts: # The mount point is mounted, attempt to remount it with the given data if 'remount' not in opts and __grains__['os'] not in ['OpenBSD', 'MacOS', 'Darwin']: opts.append('remount') if force_mount: # We need to force the mount but first we should unmount umount(name, device, user=user) lopts = ','.join(opts) args = '-o {0}'.format(lopts) if fstype: # use of fstype on AIX differs from typical Linux use of # -t functionality AIX uses -v vfsname, -t fstype mounts # all with fstype in /etc/filesystems if 'AIX' in __grains__['os']: args += ' -v {0}'.format(fstype) elif 'solaris' in __grains__['os'].lower(): args += ' -F {0}'.format(fstype) else: args += ' -t {0}'.format(fstype) if __grains__['os'] not in ['OpenBSD', 'MacOS', 'Darwin'] or force_mount: cmd = 'mount {0} {1} {2} '.format(args, device, name) else: cmd = 'mount -u {0} {1} {2} '.format(args, device, name) out = __salt__['cmd.run_all'](cmd, runas=user, python_shell=False) if out['retcode']: return out['stderr'] return True # Mount a filesystem that isn't already return mount(name, device, mkmnt, fstype, opts, user=user) def umount(name, device=None, user=None, util='mount'): ''' Attempt to unmount a device by specifying the directory it is mounted on CLI Example: .. code-block:: bash salt '*' mount.umount /mnt/foo .. versionadded:: 2015.5.0 .. code-block:: bash salt '*' mount.umount /mnt/foo /dev/xvdc1 ''' if util != 'mount': # This functionality used to live in img.umount_image if 'qemu_nbd.clear' in __salt__: if 'img.mnt_{0}'.format(name) in __context__: __salt__['qemu_nbd.clear'](__context__['img.mnt_{0}'.format(name)]) return mnts = active() if name not in mnts: return "{0} does not have anything mounted".format(name) if not device: cmd = 'umount {0}'.format(name) else: cmd = 'umount {0}'.format(device) out = __salt__['cmd.run_all'](cmd, runas=user, python_shell=False) if out['retcode']: return out['stderr'] return True def is_fuse_exec(cmd): ''' Returns true if the command passed is a fuse mountable application. CLI Example: .. code-block:: bash salt '*' mount.is_fuse_exec sshfs ''' cmd_path = salt.utils.path.which(cmd) # No point in running ldd on a command that doesn't exist if not cmd_path: return False elif not salt.utils.path.which('ldd'): raise CommandNotFoundError('ldd') out = __salt__['cmd.run']('ldd {0}'.format(cmd_path), python_shell=False) return 'libfuse' in out def swaps(): ''' Return a dict containing information on active swap .. versionchanged:: 2016.3.2 CLI Example: .. code-block:: bash salt '*' mount.swaps ''' ret = {} if __grains__['kernel'] == 'SunOS': for line in __salt__['cmd.run_stdout']('swap -l').splitlines(): if line.startswith('swapfile'): continue comps = line.split() ret[comps[0]] = {'type': 'device' if comps[0].startswith(('/dev', 'swap')) else 'file', 'size': int(comps[3]), 'used': (int(comps[3]) - int(comps[4])), 'priority': '-'} elif 'AIX' in __grains__['kernel']: for line in __salt__['cmd.run_stdout']('swap -l').splitlines(): if line.startswith('device'): continue comps = line.split() # AIX uses MB for units ret[comps[0]] = {'type': 'device', 'size': int(comps[3][:-2]) * 1024, 'used': (int(comps[3][:-2]) - int(comps[4][:-2])) * 1024, 'priority': '-'} elif __grains__['os'] != 'OpenBSD': with salt.utils.files.fopen('/proc/swaps') as fp_: for line in fp_: line = salt.utils.stringutils.to_unicode(line) if line.startswith('Filename'): continue comps = line.split() ret[comps[0]] = {'type': comps[1], 'size': comps[2], 'used': comps[3], 'priority': comps[4]} else: for line in __salt__['cmd.run_stdout']('swapctl -kl').splitlines(): if line.startswith(('Device', 'Total')): continue swap_type = "file" comps = line.split() if comps[0].startswith('/dev/'): swap_type = "partition" ret[comps[0]] = {'type': swap_type, 'size': comps[1], 'used': comps[2], 'priority': comps[5]} return ret def swapon(name, priority=None): ''' Activate a swap disk .. versionchanged:: 2016.3.2 CLI Example: .. code-block:: bash salt '*' mount.swapon /root/swapfile ''' ret = {} on_ = swaps() if name in on_: ret['stats'] = on_[name] ret['new'] = False return ret if __grains__['kernel'] == 'SunOS': if __grains__['virtual'] != 'zone': __salt__['cmd.run']('swap -a {0}'.format(name), python_shell=False) else: return False else: cmd = 'swapon {0}'.format(name) if priority and 'AIX' not in __grains__['kernel']: cmd += ' -p {0}'.format(priority) __salt__['cmd.run'](cmd, python_shell=False) on_ = swaps() if name in on_: ret['stats'] = on_[name] ret['new'] = True return ret return ret def swapoff(name): ''' Deactivate a named swap mount .. versionchanged:: 2016.3.2 CLI Example: .. code-block:: bash salt '*' mount.swapoff /root/swapfile ''' on_ = swaps() if name in on_: if __grains__['kernel'] == 'SunOS': if __grains__['virtual'] != 'zone': __salt__['cmd.run']('swap -a {0}'.format(name), python_shell=False) else: return False elif __grains__['os'] != 'OpenBSD': __salt__['cmd.run']('swapoff {0}'.format(name), python_shell=False) else: __salt__['cmd.run']('swapctl -d {0}'.format(name), python_shell=False) on_ = swaps() if name in on_: return False return True return None def is_mounted(name): ''' .. versionadded:: 2014.7.0 Provide information if the path is mounted CLI Example: .. code-block:: bash salt '*' mount.is_mounted /mnt/share ''' active_ = active() if name in active_: return True else: return False def read_mount_cache(name): ''' .. versionadded:: 2018.3.0 Provide information if the path is mounted CLI Example: .. code-block:: bash salt '*' mount.read_mount_cache /mnt/share ''' cache = salt.utils.mount.read_cache(__opts__) if cache: if 'mounts' in cache and cache['mounts']: if name in cache['mounts']: return cache['mounts'][name] return {} def write_mount_cache(real_name, device, mkmnt, fstype, mount_opts): ''' .. versionadded:: 2018.3.0 Provide information if the path is mounted :param real_name: The real name of the mount point where the device is mounted. :param device: The device that is being mounted. :param mkmnt: Whether or not the mount point should be created. :param fstype: The file system that is used. :param mount_opts: Additional options used when mounting the device. :return: Boolean if message was sent successfully. CLI Example: .. code-block:: bash salt '*' mount.write_mount_cache /mnt/share /dev/sda1 False ext4 defaults,nosuid ''' cache = salt.utils.mount.read_cache(__opts__) if not cache: cache = {} cache['mounts'] = {} else: if 'mounts' not in cache: cache['mounts'] = {} cache['mounts'][real_name] = {'device': device, 'fstype': fstype, 'mkmnt': mkmnt, 'opts': mount_opts} cache_write = salt.utils.mount.write_cache(cache, __opts__) if cache_write: return True else: raise CommandExecutionError('Unable to write mount cache.') def delete_mount_cache(real_name): ''' .. versionadded:: 2018.3.0 Provide information if the path is mounted CLI Example: .. code-block:: bash salt '*' mount.delete_mount_cache /mnt/share ''' cache = salt.utils.mount.read_cache(__opts__) if cache: if 'mounts' in cache: if real_name in cache['mounts']: del cache['mounts'][real_name] cache_write = salt.utils.mount.write_cache(cache, __opts__) if not cache_write: raise CommandExecutionError('Unable to write mount cache.') return True def _filesystems(config='/etc/filesystems', leading_key=True): ''' Return the contents of the filesystems in an OrderedDict config File containing filesystem infomation leading_key True return dictionary keyed by 'name' and value as dictionary with other keys, values (name excluded) OrderedDict({ '/dir' : OrderedDict({'dev': '/dev/hd8', .... }})) False return dictionary keyed by 'name' and value as dictionary with all keys, values (name included) OrderedDict({ '/dir' : OrderedDict({'name': '/dir', 'dev': '/dev/hd8', ... })}) ''' ret = OrderedDict() lines = [] parsing_block = False if not os.path.isfile(config) or 'AIX' not in __grains__['kernel']: return ret # read in block of filesystems, block starts with '/' till empty line with salt.utils.files.fopen(config) as ifile: for line in ifile: line = salt.utils.stringutils.to_unicode(line) # skip till first entry if not line.startswith('/') and not parsing_block: continue if line.startswith('/'): parsing_block = True lines.append(line) elif not line.split(): parsing_block = False try: entry = _FileSystemsEntry.dict_from_lines( lines, _FileSystemsEntry.compatibility_keys) lines = [] if 'opts' in entry: entry['opts'] = entry['opts'].split(',') while entry['name'] in ret: entry['name'] += '_' if leading_key: ret[entry.pop('name')] = entry else: ret[entry['name']] = entry except _FileSystemsEntry.ParseError: pass else: lines.append(line) return ret def filesystems(config='/etc/filesystems'): ''' .. versionadded:: 2018.3.3 List the contents of the filesystems CLI Example: .. code-block:: bash salt '*' mount.filesystems ''' ret = {} if 'AIX' not in __grains__['kernel']: return ret ret_dict = _filesystems(config) if ret_dict: ret_key = next(iter(ret_dict.keys())) ret = {ret_key: dict(ret_dict[ret_key])} return ret def set_filesystems( name, device, vfstype, opts='-', mount='true', config='/etc/filesystems', test=False, match_on='auto', **kwargs): ''' .. versionadded:: 2018.3.3 Verify that this mount is represented in the filesystems, change the mount to match the data passed, or add the mount if it is not present on AIX Provide information if the path is mounted :param name: The name of the mount point where the device is mounted. :param device: The device that is being mounted. :param vfstype: The file system that is used (AIX has two fstypes, fstype and vfstype - similar to Linux fstype) :param opts: Additional options used when mounting the device. :param mount: Mount if not mounted, default True. :param config: Configuration file, default /etc/filesystems. :param match: File systems type to match on, default auto CLI Example: .. code-block:: bash salt '*' mount.set_filesystems /mnt/foo /dev/sdz1 jfs2 ''' # Fix the opts type if it is a list if isinstance(opts, list): opts = ','.join(opts) # preserve arguments for updating entry_args = { 'name': name, 'dev': device.replace('\\ ', '\\040'), 'vfstype': vfstype, 'opts': opts, 'mount': mount, } view_lines = [] ret = None if 'AIX' not in __grains__['kernel']: return ret # Transform match_on into list--items will be checked later if isinstance(match_on, list): pass elif not isinstance(match_on, six.string_types): raise CommandExecutionError('match_on must be a string or list of strings') elif match_on == 'auto': # Try to guess right criteria for auto.... # added IBM types from sys/vmount.h after btrfs # NOTE: missing some special fstypes here specialFSes = frozenset([ 'none', 'tmpfs', 'sysfs', 'proc', 'fusectl', 'debugfs', 'securityfs', 'devtmpfs', 'cgroup', 'btrfs', 'cdrfs', 'procfs', 'jfs', 'jfs2', 'nfs', 'sfs', 'nfs3', 'cachefs', 'udfs', 'cifs', 'namefs', 'pmemfs', 'ahafs', 'nfs4', 'autofs', 'stnfs']) if vfstype in specialFSes: match_on = ['name'] else: match_on = ['dev'] else: match_on = [match_on] # generate entry and criteria objects, handle invalid keys in match_on entry_ip = _FileSystemsEntry.from_line(entry_args, kwargs) try: criteria = entry_ip.pick(match_on) except KeyError: filterFn = lambda key: key not in _FileSystemsEntry.compatibility_keys invalid_keys = filter(filterFn, match_on) raise CommandExecutionError('Unrecognized keys in match_on: "{0}"'.format(invalid_keys)) # parse file, use ret to cache status if not os.path.isfile(config): raise CommandExecutionError('Bad config file "{0}"'.format(config)) # read in block of filesystem, block starts with '/' till empty line try: fsys_filedict = _filesystems(config, False) for fsys_view in six.viewitems(fsys_filedict): if criteria.match(fsys_view): ret = 'present' if entry_ip.match(fsys_view): view_lines.append(fsys_view) else: ret = 'change' kv = entry_ip['name'] view_lines.append((kv, entry_ip)) else: view_lines.append(fsys_view) except (IOError, OSError) as exc: raise CommandExecutionError('Couldn\'t read from {0}: {1}'.format(config, exc)) # add line if not present or changed if ret is None: for dict_view in six.viewitems(entry_ip.dict_from_entry()): view_lines.append(dict_view) ret = 'new' if ret != 'present': # ret in ['new', 'change']: try: with salt.utils.files.fopen(config, 'wb') as ofile: # The line was changed, commit it! for fsys_view in view_lines: entry = fsys_view[1] mystrg = _FileSystemsEntry.dict_to_lines(entry) ofile.writelines(salt.utils.data.encode(mystrg)) except (IOError, OSError): raise CommandExecutionError('File not writable {0}'.format(config)) return ret
saltstack/salt
salt/modules/mount.py
_fstab_entry.pick
python
def pick(self, keys): ''' Returns an instance with just those keys ''' subset = dict([(key, self.criteria[key]) for key in keys]) return self.__class__(**subset)
Returns an instance with just those keys
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/mount.py#L323-L328
null
class _fstab_entry(object): ''' Utility class for manipulating fstab entries. Primarily we're parsing, formatting, and comparing lines. Parsing emits dicts expected from fstab() or raises a ValueError. Note: We'll probably want to use os.normpath and os.normcase on 'name' ''' class ParseError(ValueError): ''' Error raised when a line isn't parsible as an fstab entry ''' fstab_keys = ('device', 'name', 'fstype', 'opts', 'dump', 'pass_num') # preserve data format compatibility_keys = ('device', 'name', 'fstype', 'opts', 'dump', 'pass') fstab_format = '{device}\t\t{name}\t{fstype}\t{opts}\t{dump} {pass_num}\n' @classmethod def dict_from_line(cls, line, keys=fstab_keys): if len(keys) != 6: raise ValueError('Invalid key array: {0}'.format(keys)) if line.startswith('#'): raise cls.ParseError("Comment!") comps = line.split() if len(comps) < 4 or len(comps) > 6: raise cls.ParseError("Invalid Entry!") comps.extend(['0'] * (len(keys) - len(comps))) return dict(zip(keys, comps)) @classmethod def from_line(cls, *args, **kwargs): return cls(** cls.dict_from_line(*args, **kwargs)) @classmethod def dict_to_line(cls, entry): return cls.fstab_format.format(**entry) def __str__(self): ''' String value, only works for full repr ''' return self.dict_to_line(self.criteria) def __repr__(self): ''' Always works ''' return repr(self.criteria) def __init__(self, **criteria): ''' Store non-empty, non-null values to use as filter ''' items = [key_value for key_value in six.iteritems(criteria) if key_value[1] is not None] items = [(key_value1[0], six.text_type(key_value1[1])) for key_value1 in items] self.criteria = dict(items) @staticmethod def norm_path(path): ''' Resolve equivalent paths equivalently ''' return os.path.normcase(os.path.normpath(path)) def match(self, line): ''' Compare potentially partial criteria against line ''' entry = self.dict_from_line(line) for key, value in six.iteritems(self.criteria): if entry[key] != value: return False return True
saltstack/salt
salt/modules/mount.py
_fstab_entry.match
python
def match(self, line): ''' Compare potentially partial criteria against line ''' entry = self.dict_from_line(line) for key, value in six.iteritems(self.criteria): if entry[key] != value: return False return True
Compare potentially partial criteria against line
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/mount.py#L345-L353
[ "def iteritems(d, **kw):\n return d.iteritems(**kw)\n", "def dict_from_line(cls, line, keys=fstab_keys):\n if len(keys) != 6:\n raise ValueError('Invalid key array: {0}'.format(keys))\n if line.startswith('#'):\n raise cls.ParseError(\"Comment!\")\n\n comps = line.split()\n if len(comps) < 4 or len(comps) > 6:\n raise cls.ParseError(\"Invalid Entry!\")\n\n comps.extend(['0'] * (len(keys) - len(comps)))\n\n return dict(zip(keys, comps))\n" ]
class _fstab_entry(object): ''' Utility class for manipulating fstab entries. Primarily we're parsing, formatting, and comparing lines. Parsing emits dicts expected from fstab() or raises a ValueError. Note: We'll probably want to use os.normpath and os.normcase on 'name' ''' class ParseError(ValueError): ''' Error raised when a line isn't parsible as an fstab entry ''' fstab_keys = ('device', 'name', 'fstype', 'opts', 'dump', 'pass_num') # preserve data format compatibility_keys = ('device', 'name', 'fstype', 'opts', 'dump', 'pass') fstab_format = '{device}\t\t{name}\t{fstype}\t{opts}\t{dump} {pass_num}\n' @classmethod def dict_from_line(cls, line, keys=fstab_keys): if len(keys) != 6: raise ValueError('Invalid key array: {0}'.format(keys)) if line.startswith('#'): raise cls.ParseError("Comment!") comps = line.split() if len(comps) < 4 or len(comps) > 6: raise cls.ParseError("Invalid Entry!") comps.extend(['0'] * (len(keys) - len(comps))) return dict(zip(keys, comps)) @classmethod def from_line(cls, *args, **kwargs): return cls(** cls.dict_from_line(*args, **kwargs)) @classmethod def dict_to_line(cls, entry): return cls.fstab_format.format(**entry) def __str__(self): ''' String value, only works for full repr ''' return self.dict_to_line(self.criteria) def __repr__(self): ''' Always works ''' return repr(self.criteria) def pick(self, keys): ''' Returns an instance with just those keys ''' subset = dict([(key, self.criteria[key]) for key in keys]) return self.__class__(**subset) def __init__(self, **criteria): ''' Store non-empty, non-null values to use as filter ''' items = [key_value for key_value in six.iteritems(criteria) if key_value[1] is not None] items = [(key_value1[0], six.text_type(key_value1[1])) for key_value1 in items] self.criteria = dict(items) @staticmethod def norm_path(path): ''' Resolve equivalent paths equivalently ''' return os.path.normcase(os.path.normpath(path))
saltstack/salt
salt/modules/mount.py
_FileSystemsEntry.match
python
def match(self, fsys_view): ''' Compare potentially partial criteria against built filesystems entry dictionary ''' evalue_dict = fsys_view[1] for key, value in six.viewitems(self.criteria): if key in evalue_dict: if evalue_dict[key] != value: return False else: return False return True
Compare potentially partial criteria against built filesystems entry dictionary
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/mount.py#L557-L568
null
class _FileSystemsEntry(object): ''' Utility class for manipulating filesystem entries. Primarily we're parsing, formatting, and comparing lines. Parsing emits dicts expected from fstab() or raises a ValueError. Note: We'll probably want to use os.normpath and os.normcase on 'name' ''' class ParseError(ValueError): ''' Error raised when a line isn't parsible as an fstab entry ''' filesystems_keys = ('device', 'name', 'fstype', 'vfstype', 'opts', 'mount') # preserve data format of filesystems compatibility_keys = ('dev', 'dev', 'name', 'fstype', 'vfstype', 'opts', 'mount', 'type', 'vfs', 'account', 'boot', 'check', 'free', 'nodename', 'quota', 'size', 'vol', 'log') @classmethod def dict_from_lines(cls, lines, keys=filesystems_keys): if len(lines) < 2: raise ValueError('Invalid number of lines: {0}'.format(lines)) if not keys: # if empty force default filesystems_keys keys = _FileSystemsEntry.filesystems_keys elif len(keys) < 6: raise ValueError('Invalid key name array: {0}'.format(keys)) blk_lines = lines orddict = OrderedDict() orddict['name'] = blk_lines[0].split(':')[0].strip() blk_lines.pop(0) for line in blk_lines: if line.startswith('#'): raise cls.ParseError("Comment!") comps = line.split('= ') if len(comps) != 2: raise cls.ParseError("Invalid Entry!") key_name = comps[0].strip() if key_name in keys: orddict[key_name] = comps[1].strip() else: raise ValueError('Invalid name for use in filesystems: {0}'.format(key_name)) return orddict @classmethod def dict_from_cmd_line(cls, ipargs, keys): cmdln_dict = ipargs if keys: for key, value in keys: # ignore unknown or local scope keys if key.startswith('__'): continue if key in _FileSystemsEntry.compatibility_keys: cmdln_dict[key] = value return cmdln_dict @classmethod def from_line(cls, *args, **kwargs): return cls(** cls.dict_from_cmd_line(*args, **kwargs)) @classmethod def dict_to_lines(cls, fsys_dict_entry): entry = fsys_dict_entry strg_out = entry['name'] + ':' + os.linesep for k, v in six.viewitems(entry): if 'name' not in k: strg_out += '\t{0}\t\t= {1}'.format(k, v) + os.linesep strg_out += os.linesep return six.text_type(strg_out) def dict_from_entry(self): ret = OrderedDict() ret[self.criteria['name']] = self.criteria return ret def __str__(self): ''' String value, only works for full repr ''' return self.dict_to_lines(self.criteria) def __repr__(self): ''' Always works ''' return repr(self.criteria) def pick(self, keys): ''' Returns an instance with just those keys ''' subset = dict([(key, self.criteria[key]) for key in keys]) return self.__class__(**subset) def __init__(self, **criteria): ''' Store non-empty, non-null values to use as filter ''' items = [key_value for key_value in six.iteritems(criteria) if key_value[1] is not None] items = [(key_value1[0], six.text_type(key_value1[1])) for key_value1 in items] self.criteria = OrderedDict(items) @staticmethod def norm_path(path): ''' Resolve equivalent paths equivalently ''' return os.path.normcase(os.path.normpath(path)) def __getitem__(self, key): ''' Return value for input key ''' return self.criteria[key]
saltstack/salt
salt/utils/napalm.py
virtual
python
def virtual(opts, virtualname, filename): ''' Returns the __virtual__. ''' if ((HAS_NAPALM and NAPALM_MAJOR >= 2) or HAS_NAPALM_BASE) and (is_proxy(opts) or is_minion(opts)): return virtualname else: return ( False, ( '"{vname}"" {filename} cannot be loaded: ' 'NAPALM is not installed: ``pip install napalm``' ).format( vname=virtualname, filename='({filename})'.format(filename=filename) ) )
Returns the __virtual__.
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/napalm.py#L94-L110
[ "def is_proxy(opts):\n '''\n Is this a NAPALM proxy?\n '''\n return salt.utils.platform.is_proxy() and opts.get('proxy', {}).get('proxytype') == 'napalm'\n" ]
# -*- coding: utf-8 -*- ''' Utils for the NAPALM modules and proxy. .. seealso:: - :mod:`NAPALM grains: select network devices based on their characteristics <salt.grains.napalm>` - :mod:`NET module: network basic features <salt.modules.napalm_network>` - :mod:`NTP operational and configuration management module <salt.modules.napalm_ntp>` - :mod:`BGP operational and configuration management module <salt.modules.napalm_bgp>` - :mod:`Routes details <salt.modules.napalm_route>` - :mod:`SNMP configuration module <salt.modules.napalm_snmp>` - :mod:`Users configuration management <salt.modules.napalm_users>` .. versionadded:: 2017.7.0 ''' # Import Python libs from __future__ import absolute_import, unicode_literals, print_function import copy import traceback import logging import importlib from functools import wraps # Import Salt libs from salt.ext import six import salt.output import salt.utils.platform import salt.utils.args # Import third party libs try: # will try to import NAPALM # https://github.com/napalm-automation/napalm # pylint: disable=W0611 import napalm import napalm.base as napalm_base # pylint: enable=W0611 HAS_NAPALM = True HAS_NAPALM_BASE = False # doesn't matter anymore, but needed for the logic below try: NAPALM_MAJOR = int(napalm.__version__.split('.')[0]) except AttributeError: NAPALM_MAJOR = 0 except ImportError: HAS_NAPALM = False try: import napalm_base HAS_NAPALM_BASE = True except ImportError: HAS_NAPALM_BASE = False try: # try importing ConnectionClosedException # from napalm-base # this exception has been introduced only in version 0.24.0 from napalm_base.exceptions import ConnectionClosedException HAS_CONN_CLOSED_EXC_CLASS = True except ImportError: HAS_CONN_CLOSED_EXC_CLASS = False log = logging.getLogger(__file__) def is_proxy(opts): ''' Is this a NAPALM proxy? ''' return salt.utils.platform.is_proxy() and opts.get('proxy', {}).get('proxytype') == 'napalm' def is_always_alive(opts): ''' Is always alive required? ''' return opts.get('proxy', {}).get('always_alive', True) def not_always_alive(opts): ''' Should this proxy be always alive? ''' return (is_proxy(opts) and not is_always_alive(opts)) or is_minion(opts) def is_minion(opts): ''' Is this a NAPALM straight minion? ''' return not salt.utils.platform.is_proxy() and 'napalm' in opts def call(napalm_device, method, *args, **kwargs): ''' Calls arbitrary methods from the network driver instance. Please check the readthedocs_ page for the updated list of getters. .. _readthedocs: http://napalm.readthedocs.org/en/latest/support/index.html#getters-support-matrix method Specifies the name of the method to be called. *args Arguments. **kwargs More arguments. :return: A dictionary with three keys: * result (True/False): if the operation succeeded * out (object): returns the object as-is from the call * comment (string): provides more details in case the call failed * traceback (string): complete traceback in case of exception. \ Please submit an issue including this traceback \ on the `correct driver repo`_ and make sure to read the FAQ_ .. _`correct driver repo`: https://github.com/napalm-automation/napalm/issues/new .. FAQ_: https://github.com/napalm-automation/napalm#faq Example: .. code-block:: python salt.utils.napalm.call( napalm_object, 'cli', [ 'show version', 'show chassis fan' ] ) ''' result = False out = None opts = napalm_device.get('__opts__', {}) retry = kwargs.pop('__retry', True) # retry executing the task? force_reconnect = kwargs.get('force_reconnect', False) if force_reconnect: log.debug('Forced reconnection initiated') log.debug('The current opts (under the proxy key):') log.debug(opts['proxy']) opts['proxy'].update(**kwargs) log.debug('Updated to:') log.debug(opts['proxy']) napalm_device = get_device(opts) try: if not napalm_device.get('UP', False): raise Exception('not connected') # if connected will try to execute desired command kwargs_copy = {} kwargs_copy.update(kwargs) for karg, warg in six.iteritems(kwargs_copy): # lets clear None arguments # to not be sent to NAPALM methods if warg is None: kwargs.pop(karg) out = getattr(napalm_device.get('DRIVER'), method)(*args, **kwargs) # calls the method with the specified parameters result = True except Exception as error: # either not connected # either unable to execute the command hostname = napalm_device.get('HOSTNAME', '[unspecified hostname]') err_tb = traceback.format_exc() # let's get the full traceback and display for debugging reasons. if isinstance(error, NotImplementedError): comment = '{method} is not implemented for the NAPALM {driver} driver!'.format( method=method, driver=napalm_device.get('DRIVER_NAME') ) elif retry and HAS_CONN_CLOSED_EXC_CLASS and isinstance(error, ConnectionClosedException): # Received disconection whilst executing the operation. # Instructed to retry (default behaviour) # thus trying to re-establish the connection # and re-execute the command # if any of the operations (close, open, call) will rise again ConnectionClosedException # it will fail loudly. kwargs['__retry'] = False # do not attempt re-executing comment = 'Disconnected from {device}. Trying to reconnect.'.format(device=hostname) log.error(err_tb) log.error(comment) log.debug('Clearing the connection with %s', hostname) call(napalm_device, 'close', __retry=False) # safely close the connection # Make sure we don't leave any TCP connection open behind # if we fail to close properly, we might not be able to access the log.debug('Re-opening the connection with %s', hostname) call(napalm_device, 'open', __retry=False) log.debug('Connection re-opened with %s', hostname) log.debug('Re-executing %s', method) return call(napalm_device, method, *args, **kwargs) # If still not able to reconnect and execute the task, # the proxy keepalive feature (if enabled) will attempt # to reconnect. # If the device is using a SSH-based connection, the failure # will also notify the paramiko transport and the `is_alive` flag # is going to be set correctly. # More background: the network device may decide to disconnect, # although the SSH session itself is alive and usable, the reason # being the lack of activity on the CLI. # Paramiko's keepalive doesn't help in this case, as the ServerAliveInterval # are targeting the transport layer, whilst the device takes the decision # when there isn't any activity on the CLI, thus at the application layer. # Moreover, the disconnect is silent and paramiko's is_alive flag will # continue to return True, although the connection is already unusable. # For more info, see https://github.com/paramiko/paramiko/issues/813. # But after a command fails, the `is_alive` flag becomes aware of these # changes and will return False from there on. And this is how the # Salt proxy keepalive helps: immediately after the first failure, it # will know the state of the connection and will try reconnecting. else: comment = 'Cannot execute "{method}" on {device}{port} as {user}. Reason: {error}!'.format( device=napalm_device.get('HOSTNAME', '[unspecified hostname]'), port=(':{port}'.format(port=napalm_device.get('OPTIONAL_ARGS', {}).get('port')) if napalm_device.get('OPTIONAL_ARGS', {}).get('port') else ''), user=napalm_device.get('USERNAME', ''), method=method, error=error ) log.error(comment) log.error(err_tb) return { 'out': {}, 'result': False, 'comment': comment, 'traceback': err_tb } finally: if opts and not_always_alive(opts) and napalm_device.get('CLOSE', True): # either running in a not-always-alive proxy # either running in a regular minion # close the connection when the call is over # unless the CLOSE is explicitly set as False napalm_device['DRIVER'].close() return { 'out': out, 'result': result, 'comment': '' } def get_device_opts(opts, salt_obj=None): ''' Returns the options of the napalm device. :pram: opts :return: the network device opts ''' network_device = {} # by default, look in the proxy config details device_dict = opts.get('proxy', {}) if is_proxy(opts) else opts.get('napalm', {}) if opts.get('proxy') or opts.get('napalm'): opts['multiprocessing'] = device_dict.get('multiprocessing', False) # Most NAPALM drivers are SSH-based, so multiprocessing should default to False. # But the user can be allows one to have a different value for the multiprocessing, which will # override the opts. if not device_dict: # still not able to setup log.error('Incorrect minion config. Please specify at least the napalm driver name!') # either under the proxy hier, either under the napalm in the config file network_device['HOSTNAME'] = device_dict.get('host') or \ device_dict.get('hostname') or \ device_dict.get('fqdn') or \ device_dict.get('ip') network_device['USERNAME'] = device_dict.get('username') or \ device_dict.get('user') network_device['DRIVER_NAME'] = device_dict.get('driver') or \ device_dict.get('os') network_device['PASSWORD'] = device_dict.get('passwd') or \ device_dict.get('password') or \ device_dict.get('pass') or \ '' network_device['TIMEOUT'] = device_dict.get('timeout', 60) network_device['OPTIONAL_ARGS'] = device_dict.get('optional_args', {}) network_device['ALWAYS_ALIVE'] = device_dict.get('always_alive', True) network_device['PROVIDER'] = device_dict.get('provider') network_device['UP'] = False # get driver object form NAPALM if 'config_lock' not in network_device['OPTIONAL_ARGS']: network_device['OPTIONAL_ARGS']['config_lock'] = False if network_device['ALWAYS_ALIVE'] and 'keepalive' not in network_device['OPTIONAL_ARGS']: network_device['OPTIONAL_ARGS']['keepalive'] = 5 # 5 seconds keepalive return network_device def get_device(opts, salt_obj=None): ''' Initialise the connection with the network device through NAPALM. :param: opts :return: the network device object ''' log.debug('Setting up NAPALM connection') network_device = get_device_opts(opts, salt_obj=salt_obj) provider_lib = napalm_base if network_device.get('PROVIDER'): # In case the user requires a different provider library, # other than napalm-base. # For example, if napalm-base does not satisfy the requirements # and needs to be enahanced with more specific features, # we may need to define a custom library on top of napalm-base # with the constraint that it still needs to provide the # `get_network_driver` function. However, even this can be # extended later, if really needed. # Configuration example: # provider: napalm_base_example try: provider_lib = importlib.import_module(network_device.get('PROVIDER')) except ImportError as ierr: log.error('Unable to import %s', network_device.get('PROVIDER'), exc_info=True) log.error('Falling back to napalm-base') _driver_ = provider_lib.get_network_driver(network_device.get('DRIVER_NAME')) try: network_device['DRIVER'] = _driver_( network_device.get('HOSTNAME', ''), network_device.get('USERNAME', ''), network_device.get('PASSWORD', ''), timeout=network_device['TIMEOUT'], optional_args=network_device['OPTIONAL_ARGS'] ) network_device.get('DRIVER').open() # no exception raised here, means connection established network_device['UP'] = True except napalm_base.exceptions.ConnectionException as error: base_err_msg = "Cannot connect to {hostname}{port} as {username}.".format( hostname=network_device.get('HOSTNAME', '[unspecified hostname]'), port=(':{port}'.format(port=network_device.get('OPTIONAL_ARGS', {}).get('port')) if network_device.get('OPTIONAL_ARGS', {}).get('port') else ''), username=network_device.get('USERNAME', '') ) log.error(base_err_msg) log.error( "Please check error: %s", error ) raise napalm_base.exceptions.ConnectionException(base_err_msg) return network_device def proxy_napalm_wrap(func): ''' This decorator is used to make the execution module functions available outside a proxy minion, or when running inside a proxy minion. If we are running in a proxy, retrieve the connection details from the __proxy__ injected variable. If we are not, then use the connection information from the opts. :param func: :return: ''' @wraps(func) def func_wrapper(*args, **kwargs): wrapped_global_namespace = func.__globals__ # get __opts__ and __proxy__ from func_globals proxy = wrapped_global_namespace.get('__proxy__') opts = copy.deepcopy(wrapped_global_namespace.get('__opts__')) # in any case, will inject the `napalm_device` global # the execution modules will make use of this variable from now on # previously they were accessing the device properties through the __proxy__ object always_alive = opts.get('proxy', {}).get('always_alive', True) # force_reconnect is a magic keyword arg that allows one to establish # a separate connection to the network device running under an always # alive Proxy Minion, using new credentials (overriding the ones # configured in the opts / pillar. force_reconnect = kwargs.get('force_reconnect', False) if force_reconnect: log.debug('Usage of reconnect force detected') log.debug('Opts before merging') log.debug(opts['proxy']) opts['proxy'].update(**kwargs) log.debug('Opts after merging') log.debug(opts['proxy']) if is_proxy(opts) and always_alive: # if it is running in a NAPALM Proxy and it's using the default # always alive behaviour, will get the cached copy of the network # device object which should preserve the connection. if force_reconnect: wrapped_global_namespace['napalm_device'] = get_device(opts) else: wrapped_global_namespace['napalm_device'] = proxy['napalm.get_device']() elif is_proxy(opts) and not always_alive: # if still proxy, but the user does not want the SSH session always alive # get a new device instance # which establishes a new connection # which is closed just before the call() function defined above returns if 'inherit_napalm_device' not in kwargs or ('inherit_napalm_device' in kwargs and not kwargs['inherit_napalm_device']): # try to open a new connection # but only if the function does not inherit the napalm driver # for configuration management this is very important, # in order to make sure we are editing the same session. try: wrapped_global_namespace['napalm_device'] = get_device(opts) except napalm_base.exceptions.ConnectionException as nce: log.error(nce) return '{base_msg}. See log for details.'.format( base_msg=six.text_type(nce.msg) ) else: # in case the `inherit_napalm_device` is set # and it also has a non-empty value, # the global var `napalm_device` will be overridden. # this is extremely important for configuration-related features # as all actions must be issued within the same configuration session # otherwise we risk to open multiple sessions wrapped_global_namespace['napalm_device'] = kwargs['inherit_napalm_device'] else: # if not a NAPLAM proxy # thus it is running on a regular minion, directly on the network device # or another flavour of Minion from where we can invoke arbitrary # NAPALM commands # get __salt__ from func_globals log.debug('Not running in a NAPALM Proxy Minion') _salt_obj = wrapped_global_namespace.get('__salt__') napalm_opts = _salt_obj['config.get']('napalm', {}) napalm_inventory = _salt_obj['config.get']('napalm_inventory', {}) log.debug('NAPALM opts found in the Minion config') log.debug(napalm_opts) clean_kwargs = salt.utils.args.clean_kwargs(**kwargs) napalm_opts.update(clean_kwargs) # no need for deeper merge log.debug('Merging the found opts with the CLI args') log.debug(napalm_opts) host = napalm_opts.get('host') or napalm_opts.get('hostname') or\ napalm_opts.get('fqdn') or napalm_opts.get('ip') if host and napalm_inventory and isinstance(napalm_inventory, dict) and\ host in napalm_inventory: inventory_opts = napalm_inventory[host] log.debug('Found %s in the NAPALM inventory:', host) log.debug(inventory_opts) napalm_opts.update(inventory_opts) log.debug('Merging the config for %s with the details found in the napalm inventory:', host) log.debug(napalm_opts) opts = copy.deepcopy(opts) # make sure we don't override the original # opts, but just inject the CLI args from the kwargs to into the # object manipulated by ``get_device_opts`` to extract the # connection details, then use then to establish the connection. opts['napalm'] = napalm_opts if 'inherit_napalm_device' not in kwargs or ('inherit_napalm_device' in kwargs and not kwargs['inherit_napalm_device']): # try to open a new connection # but only if the function does not inherit the napalm driver # for configuration management this is very important, # in order to make sure we are editing the same session. try: wrapped_global_namespace['napalm_device'] = get_device(opts, salt_obj=_salt_obj) except napalm_base.exceptions.ConnectionException as nce: log.error(nce) return '{base_msg}. See log for details.'.format( base_msg=six.text_type(nce.msg) ) else: # in case the `inherit_napalm_device` is set # and it also has a non-empty value, # the global var `napalm_device` will be overridden. # this is extremely important for configuration-related features # as all actions must be issued within the same configuration session # otherwise we risk to open multiple sessions wrapped_global_namespace['napalm_device'] = kwargs['inherit_napalm_device'] if not_always_alive(opts): # inject the __opts__ only when not always alive # otherwise, we don't want to overload the always-alive proxies wrapped_global_namespace['napalm_device']['__opts__'] = opts ret = func(*args, **kwargs) if force_reconnect: log.debug('That was a forced reconnect, gracefully clearing up') device = wrapped_global_namespace['napalm_device'] closing = call(device, 'close', __retry=False) return ret return func_wrapper def default_ret(name): ''' Return the default dict of the state output. ''' ret = { 'name': name, 'changes': {}, 'result': False, 'comment': '' } return ret def loaded_ret(ret, loaded, test, debug, compliance_report=False, opts=None): ''' Return the final state output. ret The initial state output structure. loaded The loaded dictionary. ''' # Always get the comment changes = {} ret['comment'] = loaded['comment'] if 'diff' in loaded: changes['diff'] = loaded['diff'] if 'commit_id' in loaded: changes['commit_id'] = loaded['commit_id'] if 'compliance_report' in loaded: if compliance_report: changes['compliance_report'] = loaded['compliance_report'] if debug and 'loaded_config' in loaded: changes['loaded_config'] = loaded['loaded_config'] if changes.get('diff'): ret['comment'] = '{comment_base}\n\nConfiguration diff:\n\n{diff}'.format(comment_base=ret['comment'], diff=changes['diff']) if changes.get('loaded_config'): ret['comment'] = '{comment_base}\n\nLoaded config:\n\n{loaded_cfg}'.format( comment_base=ret['comment'], loaded_cfg=changes['loaded_config']) if changes.get('compliance_report'): ret['comment'] = '{comment_base}\n\nCompliance report:\n\n{compliance}'.format( comment_base=ret['comment'], compliance=salt.output.string_format(changes['compliance_report'], 'nested', opts=opts)) if not loaded.get('result', False): # Failure of some sort return ret if not loaded.get('already_configured', True): # We're making changes if test: ret['result'] = None return ret # Not test, changes were applied ret.update({ 'result': True, 'changes': changes, 'comment': "Configuration changed!\n{}".format(loaded['comment']) }) return ret # No changes ret.update({ 'result': True, 'changes': {} }) return ret
saltstack/salt
salt/utils/napalm.py
call
python
def call(napalm_device, method, *args, **kwargs): ''' Calls arbitrary methods from the network driver instance. Please check the readthedocs_ page for the updated list of getters. .. _readthedocs: http://napalm.readthedocs.org/en/latest/support/index.html#getters-support-matrix method Specifies the name of the method to be called. *args Arguments. **kwargs More arguments. :return: A dictionary with three keys: * result (True/False): if the operation succeeded * out (object): returns the object as-is from the call * comment (string): provides more details in case the call failed * traceback (string): complete traceback in case of exception. \ Please submit an issue including this traceback \ on the `correct driver repo`_ and make sure to read the FAQ_ .. _`correct driver repo`: https://github.com/napalm-automation/napalm/issues/new .. FAQ_: https://github.com/napalm-automation/napalm#faq Example: .. code-block:: python salt.utils.napalm.call( napalm_object, 'cli', [ 'show version', 'show chassis fan' ] ) ''' result = False out = None opts = napalm_device.get('__opts__', {}) retry = kwargs.pop('__retry', True) # retry executing the task? force_reconnect = kwargs.get('force_reconnect', False) if force_reconnect: log.debug('Forced reconnection initiated') log.debug('The current opts (under the proxy key):') log.debug(opts['proxy']) opts['proxy'].update(**kwargs) log.debug('Updated to:') log.debug(opts['proxy']) napalm_device = get_device(opts) try: if not napalm_device.get('UP', False): raise Exception('not connected') # if connected will try to execute desired command kwargs_copy = {} kwargs_copy.update(kwargs) for karg, warg in six.iteritems(kwargs_copy): # lets clear None arguments # to not be sent to NAPALM methods if warg is None: kwargs.pop(karg) out = getattr(napalm_device.get('DRIVER'), method)(*args, **kwargs) # calls the method with the specified parameters result = True except Exception as error: # either not connected # either unable to execute the command hostname = napalm_device.get('HOSTNAME', '[unspecified hostname]') err_tb = traceback.format_exc() # let's get the full traceback and display for debugging reasons. if isinstance(error, NotImplementedError): comment = '{method} is not implemented for the NAPALM {driver} driver!'.format( method=method, driver=napalm_device.get('DRIVER_NAME') ) elif retry and HAS_CONN_CLOSED_EXC_CLASS and isinstance(error, ConnectionClosedException): # Received disconection whilst executing the operation. # Instructed to retry (default behaviour) # thus trying to re-establish the connection # and re-execute the command # if any of the operations (close, open, call) will rise again ConnectionClosedException # it will fail loudly. kwargs['__retry'] = False # do not attempt re-executing comment = 'Disconnected from {device}. Trying to reconnect.'.format(device=hostname) log.error(err_tb) log.error(comment) log.debug('Clearing the connection with %s', hostname) call(napalm_device, 'close', __retry=False) # safely close the connection # Make sure we don't leave any TCP connection open behind # if we fail to close properly, we might not be able to access the log.debug('Re-opening the connection with %s', hostname) call(napalm_device, 'open', __retry=False) log.debug('Connection re-opened with %s', hostname) log.debug('Re-executing %s', method) return call(napalm_device, method, *args, **kwargs) # If still not able to reconnect and execute the task, # the proxy keepalive feature (if enabled) will attempt # to reconnect. # If the device is using a SSH-based connection, the failure # will also notify the paramiko transport and the `is_alive` flag # is going to be set correctly. # More background: the network device may decide to disconnect, # although the SSH session itself is alive and usable, the reason # being the lack of activity on the CLI. # Paramiko's keepalive doesn't help in this case, as the ServerAliveInterval # are targeting the transport layer, whilst the device takes the decision # when there isn't any activity on the CLI, thus at the application layer. # Moreover, the disconnect is silent and paramiko's is_alive flag will # continue to return True, although the connection is already unusable. # For more info, see https://github.com/paramiko/paramiko/issues/813. # But after a command fails, the `is_alive` flag becomes aware of these # changes and will return False from there on. And this is how the # Salt proxy keepalive helps: immediately after the first failure, it # will know the state of the connection and will try reconnecting. else: comment = 'Cannot execute "{method}" on {device}{port} as {user}. Reason: {error}!'.format( device=napalm_device.get('HOSTNAME', '[unspecified hostname]'), port=(':{port}'.format(port=napalm_device.get('OPTIONAL_ARGS', {}).get('port')) if napalm_device.get('OPTIONAL_ARGS', {}).get('port') else ''), user=napalm_device.get('USERNAME', ''), method=method, error=error ) log.error(comment) log.error(err_tb) return { 'out': {}, 'result': False, 'comment': comment, 'traceback': err_tb } finally: if opts and not_always_alive(opts) and napalm_device.get('CLOSE', True): # either running in a not-always-alive proxy # either running in a regular minion # close the connection when the call is over # unless the CLOSE is explicitly set as False napalm_device['DRIVER'].close() return { 'out': out, 'result': result, 'comment': '' }
Calls arbitrary methods from the network driver instance. Please check the readthedocs_ page for the updated list of getters. .. _readthedocs: http://napalm.readthedocs.org/en/latest/support/index.html#getters-support-matrix method Specifies the name of the method to be called. *args Arguments. **kwargs More arguments. :return: A dictionary with three keys: * result (True/False): if the operation succeeded * out (object): returns the object as-is from the call * comment (string): provides more details in case the call failed * traceback (string): complete traceback in case of exception. \ Please submit an issue including this traceback \ on the `correct driver repo`_ and make sure to read the FAQ_ .. _`correct driver repo`: https://github.com/napalm-automation/napalm/issues/new .. FAQ_: https://github.com/napalm-automation/napalm#faq Example: .. code-block:: python salt.utils.napalm.call( napalm_object, 'cli', [ 'show version', 'show chassis fan' ] )
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/napalm.py#L113-L258
[ "def iteritems(d, **kw):\n return d.iteritems(**kw)\n", "def get_device(opts, salt_obj=None):\n '''\n Initialise the connection with the network device through NAPALM.\n :param: opts\n :return: the network device object\n '''\n log.debug('Setting up NAPALM connection')\n network_device = get_device_opts(opts, salt_obj=salt_obj)\n provider_lib = napalm_base\n if network_device.get('PROVIDER'):\n # In case the user requires a different provider library,\n # other than napalm-base.\n # For example, if napalm-base does not satisfy the requirements\n # and needs to be enahanced with more specific features,\n # we may need to define a custom library on top of napalm-base\n # with the constraint that it still needs to provide the\n # `get_network_driver` function. However, even this can be\n # extended later, if really needed.\n # Configuration example:\n # provider: napalm_base_example\n try:\n provider_lib = importlib.import_module(network_device.get('PROVIDER'))\n except ImportError as ierr:\n log.error('Unable to import %s',\n network_device.get('PROVIDER'),\n exc_info=True)\n log.error('Falling back to napalm-base')\n _driver_ = provider_lib.get_network_driver(network_device.get('DRIVER_NAME'))\n try:\n network_device['DRIVER'] = _driver_(\n network_device.get('HOSTNAME', ''),\n network_device.get('USERNAME', ''),\n network_device.get('PASSWORD', ''),\n timeout=network_device['TIMEOUT'],\n optional_args=network_device['OPTIONAL_ARGS']\n )\n network_device.get('DRIVER').open()\n # no exception raised here, means connection established\n network_device['UP'] = True\n except napalm_base.exceptions.ConnectionException as error:\n base_err_msg = \"Cannot connect to {hostname}{port} as {username}.\".format(\n hostname=network_device.get('HOSTNAME', '[unspecified hostname]'),\n port=(':{port}'.format(port=network_device.get('OPTIONAL_ARGS', {}).get('port'))\n if network_device.get('OPTIONAL_ARGS', {}).get('port') else ''),\n username=network_device.get('USERNAME', '')\n )\n log.error(base_err_msg)\n log.error(\n \"Please check error: %s\", error\n )\n raise napalm_base.exceptions.ConnectionException(base_err_msg)\n return network_device\n", "def not_always_alive(opts):\n '''\n Should this proxy be always alive?\n '''\n return (is_proxy(opts) and not is_always_alive(opts)) or is_minion(opts)\n" ]
# -*- coding: utf-8 -*- ''' Utils for the NAPALM modules and proxy. .. seealso:: - :mod:`NAPALM grains: select network devices based on their characteristics <salt.grains.napalm>` - :mod:`NET module: network basic features <salt.modules.napalm_network>` - :mod:`NTP operational and configuration management module <salt.modules.napalm_ntp>` - :mod:`BGP operational and configuration management module <salt.modules.napalm_bgp>` - :mod:`Routes details <salt.modules.napalm_route>` - :mod:`SNMP configuration module <salt.modules.napalm_snmp>` - :mod:`Users configuration management <salt.modules.napalm_users>` .. versionadded:: 2017.7.0 ''' # Import Python libs from __future__ import absolute_import, unicode_literals, print_function import copy import traceback import logging import importlib from functools import wraps # Import Salt libs from salt.ext import six import salt.output import salt.utils.platform import salt.utils.args # Import third party libs try: # will try to import NAPALM # https://github.com/napalm-automation/napalm # pylint: disable=W0611 import napalm import napalm.base as napalm_base # pylint: enable=W0611 HAS_NAPALM = True HAS_NAPALM_BASE = False # doesn't matter anymore, but needed for the logic below try: NAPALM_MAJOR = int(napalm.__version__.split('.')[0]) except AttributeError: NAPALM_MAJOR = 0 except ImportError: HAS_NAPALM = False try: import napalm_base HAS_NAPALM_BASE = True except ImportError: HAS_NAPALM_BASE = False try: # try importing ConnectionClosedException # from napalm-base # this exception has been introduced only in version 0.24.0 from napalm_base.exceptions import ConnectionClosedException HAS_CONN_CLOSED_EXC_CLASS = True except ImportError: HAS_CONN_CLOSED_EXC_CLASS = False log = logging.getLogger(__file__) def is_proxy(opts): ''' Is this a NAPALM proxy? ''' return salt.utils.platform.is_proxy() and opts.get('proxy', {}).get('proxytype') == 'napalm' def is_always_alive(opts): ''' Is always alive required? ''' return opts.get('proxy', {}).get('always_alive', True) def not_always_alive(opts): ''' Should this proxy be always alive? ''' return (is_proxy(opts) and not is_always_alive(opts)) or is_minion(opts) def is_minion(opts): ''' Is this a NAPALM straight minion? ''' return not salt.utils.platform.is_proxy() and 'napalm' in opts def virtual(opts, virtualname, filename): ''' Returns the __virtual__. ''' if ((HAS_NAPALM and NAPALM_MAJOR >= 2) or HAS_NAPALM_BASE) and (is_proxy(opts) or is_minion(opts)): return virtualname else: return ( False, ( '"{vname}"" {filename} cannot be loaded: ' 'NAPALM is not installed: ``pip install napalm``' ).format( vname=virtualname, filename='({filename})'.format(filename=filename) ) ) def get_device_opts(opts, salt_obj=None): ''' Returns the options of the napalm device. :pram: opts :return: the network device opts ''' network_device = {} # by default, look in the proxy config details device_dict = opts.get('proxy', {}) if is_proxy(opts) else opts.get('napalm', {}) if opts.get('proxy') or opts.get('napalm'): opts['multiprocessing'] = device_dict.get('multiprocessing', False) # Most NAPALM drivers are SSH-based, so multiprocessing should default to False. # But the user can be allows one to have a different value for the multiprocessing, which will # override the opts. if not device_dict: # still not able to setup log.error('Incorrect minion config. Please specify at least the napalm driver name!') # either under the proxy hier, either under the napalm in the config file network_device['HOSTNAME'] = device_dict.get('host') or \ device_dict.get('hostname') or \ device_dict.get('fqdn') or \ device_dict.get('ip') network_device['USERNAME'] = device_dict.get('username') or \ device_dict.get('user') network_device['DRIVER_NAME'] = device_dict.get('driver') or \ device_dict.get('os') network_device['PASSWORD'] = device_dict.get('passwd') or \ device_dict.get('password') or \ device_dict.get('pass') or \ '' network_device['TIMEOUT'] = device_dict.get('timeout', 60) network_device['OPTIONAL_ARGS'] = device_dict.get('optional_args', {}) network_device['ALWAYS_ALIVE'] = device_dict.get('always_alive', True) network_device['PROVIDER'] = device_dict.get('provider') network_device['UP'] = False # get driver object form NAPALM if 'config_lock' not in network_device['OPTIONAL_ARGS']: network_device['OPTIONAL_ARGS']['config_lock'] = False if network_device['ALWAYS_ALIVE'] and 'keepalive' not in network_device['OPTIONAL_ARGS']: network_device['OPTIONAL_ARGS']['keepalive'] = 5 # 5 seconds keepalive return network_device def get_device(opts, salt_obj=None): ''' Initialise the connection with the network device through NAPALM. :param: opts :return: the network device object ''' log.debug('Setting up NAPALM connection') network_device = get_device_opts(opts, salt_obj=salt_obj) provider_lib = napalm_base if network_device.get('PROVIDER'): # In case the user requires a different provider library, # other than napalm-base. # For example, if napalm-base does not satisfy the requirements # and needs to be enahanced with more specific features, # we may need to define a custom library on top of napalm-base # with the constraint that it still needs to provide the # `get_network_driver` function. However, even this can be # extended later, if really needed. # Configuration example: # provider: napalm_base_example try: provider_lib = importlib.import_module(network_device.get('PROVIDER')) except ImportError as ierr: log.error('Unable to import %s', network_device.get('PROVIDER'), exc_info=True) log.error('Falling back to napalm-base') _driver_ = provider_lib.get_network_driver(network_device.get('DRIVER_NAME')) try: network_device['DRIVER'] = _driver_( network_device.get('HOSTNAME', ''), network_device.get('USERNAME', ''), network_device.get('PASSWORD', ''), timeout=network_device['TIMEOUT'], optional_args=network_device['OPTIONAL_ARGS'] ) network_device.get('DRIVER').open() # no exception raised here, means connection established network_device['UP'] = True except napalm_base.exceptions.ConnectionException as error: base_err_msg = "Cannot connect to {hostname}{port} as {username}.".format( hostname=network_device.get('HOSTNAME', '[unspecified hostname]'), port=(':{port}'.format(port=network_device.get('OPTIONAL_ARGS', {}).get('port')) if network_device.get('OPTIONAL_ARGS', {}).get('port') else ''), username=network_device.get('USERNAME', '') ) log.error(base_err_msg) log.error( "Please check error: %s", error ) raise napalm_base.exceptions.ConnectionException(base_err_msg) return network_device def proxy_napalm_wrap(func): ''' This decorator is used to make the execution module functions available outside a proxy minion, or when running inside a proxy minion. If we are running in a proxy, retrieve the connection details from the __proxy__ injected variable. If we are not, then use the connection information from the opts. :param func: :return: ''' @wraps(func) def func_wrapper(*args, **kwargs): wrapped_global_namespace = func.__globals__ # get __opts__ and __proxy__ from func_globals proxy = wrapped_global_namespace.get('__proxy__') opts = copy.deepcopy(wrapped_global_namespace.get('__opts__')) # in any case, will inject the `napalm_device` global # the execution modules will make use of this variable from now on # previously they were accessing the device properties through the __proxy__ object always_alive = opts.get('proxy', {}).get('always_alive', True) # force_reconnect is a magic keyword arg that allows one to establish # a separate connection to the network device running under an always # alive Proxy Minion, using new credentials (overriding the ones # configured in the opts / pillar. force_reconnect = kwargs.get('force_reconnect', False) if force_reconnect: log.debug('Usage of reconnect force detected') log.debug('Opts before merging') log.debug(opts['proxy']) opts['proxy'].update(**kwargs) log.debug('Opts after merging') log.debug(opts['proxy']) if is_proxy(opts) and always_alive: # if it is running in a NAPALM Proxy and it's using the default # always alive behaviour, will get the cached copy of the network # device object which should preserve the connection. if force_reconnect: wrapped_global_namespace['napalm_device'] = get_device(opts) else: wrapped_global_namespace['napalm_device'] = proxy['napalm.get_device']() elif is_proxy(opts) and not always_alive: # if still proxy, but the user does not want the SSH session always alive # get a new device instance # which establishes a new connection # which is closed just before the call() function defined above returns if 'inherit_napalm_device' not in kwargs or ('inherit_napalm_device' in kwargs and not kwargs['inherit_napalm_device']): # try to open a new connection # but only if the function does not inherit the napalm driver # for configuration management this is very important, # in order to make sure we are editing the same session. try: wrapped_global_namespace['napalm_device'] = get_device(opts) except napalm_base.exceptions.ConnectionException as nce: log.error(nce) return '{base_msg}. See log for details.'.format( base_msg=six.text_type(nce.msg) ) else: # in case the `inherit_napalm_device` is set # and it also has a non-empty value, # the global var `napalm_device` will be overridden. # this is extremely important for configuration-related features # as all actions must be issued within the same configuration session # otherwise we risk to open multiple sessions wrapped_global_namespace['napalm_device'] = kwargs['inherit_napalm_device'] else: # if not a NAPLAM proxy # thus it is running on a regular minion, directly on the network device # or another flavour of Minion from where we can invoke arbitrary # NAPALM commands # get __salt__ from func_globals log.debug('Not running in a NAPALM Proxy Minion') _salt_obj = wrapped_global_namespace.get('__salt__') napalm_opts = _salt_obj['config.get']('napalm', {}) napalm_inventory = _salt_obj['config.get']('napalm_inventory', {}) log.debug('NAPALM opts found in the Minion config') log.debug(napalm_opts) clean_kwargs = salt.utils.args.clean_kwargs(**kwargs) napalm_opts.update(clean_kwargs) # no need for deeper merge log.debug('Merging the found opts with the CLI args') log.debug(napalm_opts) host = napalm_opts.get('host') or napalm_opts.get('hostname') or\ napalm_opts.get('fqdn') or napalm_opts.get('ip') if host and napalm_inventory and isinstance(napalm_inventory, dict) and\ host in napalm_inventory: inventory_opts = napalm_inventory[host] log.debug('Found %s in the NAPALM inventory:', host) log.debug(inventory_opts) napalm_opts.update(inventory_opts) log.debug('Merging the config for %s with the details found in the napalm inventory:', host) log.debug(napalm_opts) opts = copy.deepcopy(opts) # make sure we don't override the original # opts, but just inject the CLI args from the kwargs to into the # object manipulated by ``get_device_opts`` to extract the # connection details, then use then to establish the connection. opts['napalm'] = napalm_opts if 'inherit_napalm_device' not in kwargs or ('inherit_napalm_device' in kwargs and not kwargs['inherit_napalm_device']): # try to open a new connection # but only if the function does not inherit the napalm driver # for configuration management this is very important, # in order to make sure we are editing the same session. try: wrapped_global_namespace['napalm_device'] = get_device(opts, salt_obj=_salt_obj) except napalm_base.exceptions.ConnectionException as nce: log.error(nce) return '{base_msg}. See log for details.'.format( base_msg=six.text_type(nce.msg) ) else: # in case the `inherit_napalm_device` is set # and it also has a non-empty value, # the global var `napalm_device` will be overridden. # this is extremely important for configuration-related features # as all actions must be issued within the same configuration session # otherwise we risk to open multiple sessions wrapped_global_namespace['napalm_device'] = kwargs['inherit_napalm_device'] if not_always_alive(opts): # inject the __opts__ only when not always alive # otherwise, we don't want to overload the always-alive proxies wrapped_global_namespace['napalm_device']['__opts__'] = opts ret = func(*args, **kwargs) if force_reconnect: log.debug('That was a forced reconnect, gracefully clearing up') device = wrapped_global_namespace['napalm_device'] closing = call(device, 'close', __retry=False) return ret return func_wrapper def default_ret(name): ''' Return the default dict of the state output. ''' ret = { 'name': name, 'changes': {}, 'result': False, 'comment': '' } return ret def loaded_ret(ret, loaded, test, debug, compliance_report=False, opts=None): ''' Return the final state output. ret The initial state output structure. loaded The loaded dictionary. ''' # Always get the comment changes = {} ret['comment'] = loaded['comment'] if 'diff' in loaded: changes['diff'] = loaded['diff'] if 'commit_id' in loaded: changes['commit_id'] = loaded['commit_id'] if 'compliance_report' in loaded: if compliance_report: changes['compliance_report'] = loaded['compliance_report'] if debug and 'loaded_config' in loaded: changes['loaded_config'] = loaded['loaded_config'] if changes.get('diff'): ret['comment'] = '{comment_base}\n\nConfiguration diff:\n\n{diff}'.format(comment_base=ret['comment'], diff=changes['diff']) if changes.get('loaded_config'): ret['comment'] = '{comment_base}\n\nLoaded config:\n\n{loaded_cfg}'.format( comment_base=ret['comment'], loaded_cfg=changes['loaded_config']) if changes.get('compliance_report'): ret['comment'] = '{comment_base}\n\nCompliance report:\n\n{compliance}'.format( comment_base=ret['comment'], compliance=salt.output.string_format(changes['compliance_report'], 'nested', opts=opts)) if not loaded.get('result', False): # Failure of some sort return ret if not loaded.get('already_configured', True): # We're making changes if test: ret['result'] = None return ret # Not test, changes were applied ret.update({ 'result': True, 'changes': changes, 'comment': "Configuration changed!\n{}".format(loaded['comment']) }) return ret # No changes ret.update({ 'result': True, 'changes': {} }) return ret
saltstack/salt
salt/utils/napalm.py
get_device_opts
python
def get_device_opts(opts, salt_obj=None): ''' Returns the options of the napalm device. :pram: opts :return: the network device opts ''' network_device = {} # by default, look in the proxy config details device_dict = opts.get('proxy', {}) if is_proxy(opts) else opts.get('napalm', {}) if opts.get('proxy') or opts.get('napalm'): opts['multiprocessing'] = device_dict.get('multiprocessing', False) # Most NAPALM drivers are SSH-based, so multiprocessing should default to False. # But the user can be allows one to have a different value for the multiprocessing, which will # override the opts. if not device_dict: # still not able to setup log.error('Incorrect minion config. Please specify at least the napalm driver name!') # either under the proxy hier, either under the napalm in the config file network_device['HOSTNAME'] = device_dict.get('host') or \ device_dict.get('hostname') or \ device_dict.get('fqdn') or \ device_dict.get('ip') network_device['USERNAME'] = device_dict.get('username') or \ device_dict.get('user') network_device['DRIVER_NAME'] = device_dict.get('driver') or \ device_dict.get('os') network_device['PASSWORD'] = device_dict.get('passwd') or \ device_dict.get('password') or \ device_dict.get('pass') or \ '' network_device['TIMEOUT'] = device_dict.get('timeout', 60) network_device['OPTIONAL_ARGS'] = device_dict.get('optional_args', {}) network_device['ALWAYS_ALIVE'] = device_dict.get('always_alive', True) network_device['PROVIDER'] = device_dict.get('provider') network_device['UP'] = False # get driver object form NAPALM if 'config_lock' not in network_device['OPTIONAL_ARGS']: network_device['OPTIONAL_ARGS']['config_lock'] = False if network_device['ALWAYS_ALIVE'] and 'keepalive' not in network_device['OPTIONAL_ARGS']: network_device['OPTIONAL_ARGS']['keepalive'] = 5 # 5 seconds keepalive return network_device
Returns the options of the napalm device. :pram: opts :return: the network device opts
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/napalm.py#L261-L301
[ "def is_proxy(opts):\n '''\n Is this a NAPALM proxy?\n '''\n return salt.utils.platform.is_proxy() and opts.get('proxy', {}).get('proxytype') == 'napalm'\n" ]
# -*- coding: utf-8 -*- ''' Utils for the NAPALM modules and proxy. .. seealso:: - :mod:`NAPALM grains: select network devices based on their characteristics <salt.grains.napalm>` - :mod:`NET module: network basic features <salt.modules.napalm_network>` - :mod:`NTP operational and configuration management module <salt.modules.napalm_ntp>` - :mod:`BGP operational and configuration management module <salt.modules.napalm_bgp>` - :mod:`Routes details <salt.modules.napalm_route>` - :mod:`SNMP configuration module <salt.modules.napalm_snmp>` - :mod:`Users configuration management <salt.modules.napalm_users>` .. versionadded:: 2017.7.0 ''' # Import Python libs from __future__ import absolute_import, unicode_literals, print_function import copy import traceback import logging import importlib from functools import wraps # Import Salt libs from salt.ext import six import salt.output import salt.utils.platform import salt.utils.args # Import third party libs try: # will try to import NAPALM # https://github.com/napalm-automation/napalm # pylint: disable=W0611 import napalm import napalm.base as napalm_base # pylint: enable=W0611 HAS_NAPALM = True HAS_NAPALM_BASE = False # doesn't matter anymore, but needed for the logic below try: NAPALM_MAJOR = int(napalm.__version__.split('.')[0]) except AttributeError: NAPALM_MAJOR = 0 except ImportError: HAS_NAPALM = False try: import napalm_base HAS_NAPALM_BASE = True except ImportError: HAS_NAPALM_BASE = False try: # try importing ConnectionClosedException # from napalm-base # this exception has been introduced only in version 0.24.0 from napalm_base.exceptions import ConnectionClosedException HAS_CONN_CLOSED_EXC_CLASS = True except ImportError: HAS_CONN_CLOSED_EXC_CLASS = False log = logging.getLogger(__file__) def is_proxy(opts): ''' Is this a NAPALM proxy? ''' return salt.utils.platform.is_proxy() and opts.get('proxy', {}).get('proxytype') == 'napalm' def is_always_alive(opts): ''' Is always alive required? ''' return opts.get('proxy', {}).get('always_alive', True) def not_always_alive(opts): ''' Should this proxy be always alive? ''' return (is_proxy(opts) and not is_always_alive(opts)) or is_minion(opts) def is_minion(opts): ''' Is this a NAPALM straight minion? ''' return not salt.utils.platform.is_proxy() and 'napalm' in opts def virtual(opts, virtualname, filename): ''' Returns the __virtual__. ''' if ((HAS_NAPALM and NAPALM_MAJOR >= 2) or HAS_NAPALM_BASE) and (is_proxy(opts) or is_minion(opts)): return virtualname else: return ( False, ( '"{vname}"" {filename} cannot be loaded: ' 'NAPALM is not installed: ``pip install napalm``' ).format( vname=virtualname, filename='({filename})'.format(filename=filename) ) ) def call(napalm_device, method, *args, **kwargs): ''' Calls arbitrary methods from the network driver instance. Please check the readthedocs_ page for the updated list of getters. .. _readthedocs: http://napalm.readthedocs.org/en/latest/support/index.html#getters-support-matrix method Specifies the name of the method to be called. *args Arguments. **kwargs More arguments. :return: A dictionary with three keys: * result (True/False): if the operation succeeded * out (object): returns the object as-is from the call * comment (string): provides more details in case the call failed * traceback (string): complete traceback in case of exception. \ Please submit an issue including this traceback \ on the `correct driver repo`_ and make sure to read the FAQ_ .. _`correct driver repo`: https://github.com/napalm-automation/napalm/issues/new .. FAQ_: https://github.com/napalm-automation/napalm#faq Example: .. code-block:: python salt.utils.napalm.call( napalm_object, 'cli', [ 'show version', 'show chassis fan' ] ) ''' result = False out = None opts = napalm_device.get('__opts__', {}) retry = kwargs.pop('__retry', True) # retry executing the task? force_reconnect = kwargs.get('force_reconnect', False) if force_reconnect: log.debug('Forced reconnection initiated') log.debug('The current opts (under the proxy key):') log.debug(opts['proxy']) opts['proxy'].update(**kwargs) log.debug('Updated to:') log.debug(opts['proxy']) napalm_device = get_device(opts) try: if not napalm_device.get('UP', False): raise Exception('not connected') # if connected will try to execute desired command kwargs_copy = {} kwargs_copy.update(kwargs) for karg, warg in six.iteritems(kwargs_copy): # lets clear None arguments # to not be sent to NAPALM methods if warg is None: kwargs.pop(karg) out = getattr(napalm_device.get('DRIVER'), method)(*args, **kwargs) # calls the method with the specified parameters result = True except Exception as error: # either not connected # either unable to execute the command hostname = napalm_device.get('HOSTNAME', '[unspecified hostname]') err_tb = traceback.format_exc() # let's get the full traceback and display for debugging reasons. if isinstance(error, NotImplementedError): comment = '{method} is not implemented for the NAPALM {driver} driver!'.format( method=method, driver=napalm_device.get('DRIVER_NAME') ) elif retry and HAS_CONN_CLOSED_EXC_CLASS and isinstance(error, ConnectionClosedException): # Received disconection whilst executing the operation. # Instructed to retry (default behaviour) # thus trying to re-establish the connection # and re-execute the command # if any of the operations (close, open, call) will rise again ConnectionClosedException # it will fail loudly. kwargs['__retry'] = False # do not attempt re-executing comment = 'Disconnected from {device}. Trying to reconnect.'.format(device=hostname) log.error(err_tb) log.error(comment) log.debug('Clearing the connection with %s', hostname) call(napalm_device, 'close', __retry=False) # safely close the connection # Make sure we don't leave any TCP connection open behind # if we fail to close properly, we might not be able to access the log.debug('Re-opening the connection with %s', hostname) call(napalm_device, 'open', __retry=False) log.debug('Connection re-opened with %s', hostname) log.debug('Re-executing %s', method) return call(napalm_device, method, *args, **kwargs) # If still not able to reconnect and execute the task, # the proxy keepalive feature (if enabled) will attempt # to reconnect. # If the device is using a SSH-based connection, the failure # will also notify the paramiko transport and the `is_alive` flag # is going to be set correctly. # More background: the network device may decide to disconnect, # although the SSH session itself is alive and usable, the reason # being the lack of activity on the CLI. # Paramiko's keepalive doesn't help in this case, as the ServerAliveInterval # are targeting the transport layer, whilst the device takes the decision # when there isn't any activity on the CLI, thus at the application layer. # Moreover, the disconnect is silent and paramiko's is_alive flag will # continue to return True, although the connection is already unusable. # For more info, see https://github.com/paramiko/paramiko/issues/813. # But after a command fails, the `is_alive` flag becomes aware of these # changes and will return False from there on. And this is how the # Salt proxy keepalive helps: immediately after the first failure, it # will know the state of the connection and will try reconnecting. else: comment = 'Cannot execute "{method}" on {device}{port} as {user}. Reason: {error}!'.format( device=napalm_device.get('HOSTNAME', '[unspecified hostname]'), port=(':{port}'.format(port=napalm_device.get('OPTIONAL_ARGS', {}).get('port')) if napalm_device.get('OPTIONAL_ARGS', {}).get('port') else ''), user=napalm_device.get('USERNAME', ''), method=method, error=error ) log.error(comment) log.error(err_tb) return { 'out': {}, 'result': False, 'comment': comment, 'traceback': err_tb } finally: if opts and not_always_alive(opts) and napalm_device.get('CLOSE', True): # either running in a not-always-alive proxy # either running in a regular minion # close the connection when the call is over # unless the CLOSE is explicitly set as False napalm_device['DRIVER'].close() return { 'out': out, 'result': result, 'comment': '' } def get_device(opts, salt_obj=None): ''' Initialise the connection with the network device through NAPALM. :param: opts :return: the network device object ''' log.debug('Setting up NAPALM connection') network_device = get_device_opts(opts, salt_obj=salt_obj) provider_lib = napalm_base if network_device.get('PROVIDER'): # In case the user requires a different provider library, # other than napalm-base. # For example, if napalm-base does not satisfy the requirements # and needs to be enahanced with more specific features, # we may need to define a custom library on top of napalm-base # with the constraint that it still needs to provide the # `get_network_driver` function. However, even this can be # extended later, if really needed. # Configuration example: # provider: napalm_base_example try: provider_lib = importlib.import_module(network_device.get('PROVIDER')) except ImportError as ierr: log.error('Unable to import %s', network_device.get('PROVIDER'), exc_info=True) log.error('Falling back to napalm-base') _driver_ = provider_lib.get_network_driver(network_device.get('DRIVER_NAME')) try: network_device['DRIVER'] = _driver_( network_device.get('HOSTNAME', ''), network_device.get('USERNAME', ''), network_device.get('PASSWORD', ''), timeout=network_device['TIMEOUT'], optional_args=network_device['OPTIONAL_ARGS'] ) network_device.get('DRIVER').open() # no exception raised here, means connection established network_device['UP'] = True except napalm_base.exceptions.ConnectionException as error: base_err_msg = "Cannot connect to {hostname}{port} as {username}.".format( hostname=network_device.get('HOSTNAME', '[unspecified hostname]'), port=(':{port}'.format(port=network_device.get('OPTIONAL_ARGS', {}).get('port')) if network_device.get('OPTIONAL_ARGS', {}).get('port') else ''), username=network_device.get('USERNAME', '') ) log.error(base_err_msg) log.error( "Please check error: %s", error ) raise napalm_base.exceptions.ConnectionException(base_err_msg) return network_device def proxy_napalm_wrap(func): ''' This decorator is used to make the execution module functions available outside a proxy minion, or when running inside a proxy minion. If we are running in a proxy, retrieve the connection details from the __proxy__ injected variable. If we are not, then use the connection information from the opts. :param func: :return: ''' @wraps(func) def func_wrapper(*args, **kwargs): wrapped_global_namespace = func.__globals__ # get __opts__ and __proxy__ from func_globals proxy = wrapped_global_namespace.get('__proxy__') opts = copy.deepcopy(wrapped_global_namespace.get('__opts__')) # in any case, will inject the `napalm_device` global # the execution modules will make use of this variable from now on # previously they were accessing the device properties through the __proxy__ object always_alive = opts.get('proxy', {}).get('always_alive', True) # force_reconnect is a magic keyword arg that allows one to establish # a separate connection to the network device running under an always # alive Proxy Minion, using new credentials (overriding the ones # configured in the opts / pillar. force_reconnect = kwargs.get('force_reconnect', False) if force_reconnect: log.debug('Usage of reconnect force detected') log.debug('Opts before merging') log.debug(opts['proxy']) opts['proxy'].update(**kwargs) log.debug('Opts after merging') log.debug(opts['proxy']) if is_proxy(opts) and always_alive: # if it is running in a NAPALM Proxy and it's using the default # always alive behaviour, will get the cached copy of the network # device object which should preserve the connection. if force_reconnect: wrapped_global_namespace['napalm_device'] = get_device(opts) else: wrapped_global_namespace['napalm_device'] = proxy['napalm.get_device']() elif is_proxy(opts) and not always_alive: # if still proxy, but the user does not want the SSH session always alive # get a new device instance # which establishes a new connection # which is closed just before the call() function defined above returns if 'inherit_napalm_device' not in kwargs or ('inherit_napalm_device' in kwargs and not kwargs['inherit_napalm_device']): # try to open a new connection # but only if the function does not inherit the napalm driver # for configuration management this is very important, # in order to make sure we are editing the same session. try: wrapped_global_namespace['napalm_device'] = get_device(opts) except napalm_base.exceptions.ConnectionException as nce: log.error(nce) return '{base_msg}. See log for details.'.format( base_msg=six.text_type(nce.msg) ) else: # in case the `inherit_napalm_device` is set # and it also has a non-empty value, # the global var `napalm_device` will be overridden. # this is extremely important for configuration-related features # as all actions must be issued within the same configuration session # otherwise we risk to open multiple sessions wrapped_global_namespace['napalm_device'] = kwargs['inherit_napalm_device'] else: # if not a NAPLAM proxy # thus it is running on a regular minion, directly on the network device # or another flavour of Minion from where we can invoke arbitrary # NAPALM commands # get __salt__ from func_globals log.debug('Not running in a NAPALM Proxy Minion') _salt_obj = wrapped_global_namespace.get('__salt__') napalm_opts = _salt_obj['config.get']('napalm', {}) napalm_inventory = _salt_obj['config.get']('napalm_inventory', {}) log.debug('NAPALM opts found in the Minion config') log.debug(napalm_opts) clean_kwargs = salt.utils.args.clean_kwargs(**kwargs) napalm_opts.update(clean_kwargs) # no need for deeper merge log.debug('Merging the found opts with the CLI args') log.debug(napalm_opts) host = napalm_opts.get('host') or napalm_opts.get('hostname') or\ napalm_opts.get('fqdn') or napalm_opts.get('ip') if host and napalm_inventory and isinstance(napalm_inventory, dict) and\ host in napalm_inventory: inventory_opts = napalm_inventory[host] log.debug('Found %s in the NAPALM inventory:', host) log.debug(inventory_opts) napalm_opts.update(inventory_opts) log.debug('Merging the config for %s with the details found in the napalm inventory:', host) log.debug(napalm_opts) opts = copy.deepcopy(opts) # make sure we don't override the original # opts, but just inject the CLI args from the kwargs to into the # object manipulated by ``get_device_opts`` to extract the # connection details, then use then to establish the connection. opts['napalm'] = napalm_opts if 'inherit_napalm_device' not in kwargs or ('inherit_napalm_device' in kwargs and not kwargs['inherit_napalm_device']): # try to open a new connection # but only if the function does not inherit the napalm driver # for configuration management this is very important, # in order to make sure we are editing the same session. try: wrapped_global_namespace['napalm_device'] = get_device(opts, salt_obj=_salt_obj) except napalm_base.exceptions.ConnectionException as nce: log.error(nce) return '{base_msg}. See log for details.'.format( base_msg=six.text_type(nce.msg) ) else: # in case the `inherit_napalm_device` is set # and it also has a non-empty value, # the global var `napalm_device` will be overridden. # this is extremely important for configuration-related features # as all actions must be issued within the same configuration session # otherwise we risk to open multiple sessions wrapped_global_namespace['napalm_device'] = kwargs['inherit_napalm_device'] if not_always_alive(opts): # inject the __opts__ only when not always alive # otherwise, we don't want to overload the always-alive proxies wrapped_global_namespace['napalm_device']['__opts__'] = opts ret = func(*args, **kwargs) if force_reconnect: log.debug('That was a forced reconnect, gracefully clearing up') device = wrapped_global_namespace['napalm_device'] closing = call(device, 'close', __retry=False) return ret return func_wrapper def default_ret(name): ''' Return the default dict of the state output. ''' ret = { 'name': name, 'changes': {}, 'result': False, 'comment': '' } return ret def loaded_ret(ret, loaded, test, debug, compliance_report=False, opts=None): ''' Return the final state output. ret The initial state output structure. loaded The loaded dictionary. ''' # Always get the comment changes = {} ret['comment'] = loaded['comment'] if 'diff' in loaded: changes['diff'] = loaded['diff'] if 'commit_id' in loaded: changes['commit_id'] = loaded['commit_id'] if 'compliance_report' in loaded: if compliance_report: changes['compliance_report'] = loaded['compliance_report'] if debug and 'loaded_config' in loaded: changes['loaded_config'] = loaded['loaded_config'] if changes.get('diff'): ret['comment'] = '{comment_base}\n\nConfiguration diff:\n\n{diff}'.format(comment_base=ret['comment'], diff=changes['diff']) if changes.get('loaded_config'): ret['comment'] = '{comment_base}\n\nLoaded config:\n\n{loaded_cfg}'.format( comment_base=ret['comment'], loaded_cfg=changes['loaded_config']) if changes.get('compliance_report'): ret['comment'] = '{comment_base}\n\nCompliance report:\n\n{compliance}'.format( comment_base=ret['comment'], compliance=salt.output.string_format(changes['compliance_report'], 'nested', opts=opts)) if not loaded.get('result', False): # Failure of some sort return ret if not loaded.get('already_configured', True): # We're making changes if test: ret['result'] = None return ret # Not test, changes were applied ret.update({ 'result': True, 'changes': changes, 'comment': "Configuration changed!\n{}".format(loaded['comment']) }) return ret # No changes ret.update({ 'result': True, 'changes': {} }) return ret
saltstack/salt
salt/utils/napalm.py
get_device
python
def get_device(opts, salt_obj=None): ''' Initialise the connection with the network device through NAPALM. :param: opts :return: the network device object ''' log.debug('Setting up NAPALM connection') network_device = get_device_opts(opts, salt_obj=salt_obj) provider_lib = napalm_base if network_device.get('PROVIDER'): # In case the user requires a different provider library, # other than napalm-base. # For example, if napalm-base does not satisfy the requirements # and needs to be enahanced with more specific features, # we may need to define a custom library on top of napalm-base # with the constraint that it still needs to provide the # `get_network_driver` function. However, even this can be # extended later, if really needed. # Configuration example: # provider: napalm_base_example try: provider_lib = importlib.import_module(network_device.get('PROVIDER')) except ImportError as ierr: log.error('Unable to import %s', network_device.get('PROVIDER'), exc_info=True) log.error('Falling back to napalm-base') _driver_ = provider_lib.get_network_driver(network_device.get('DRIVER_NAME')) try: network_device['DRIVER'] = _driver_( network_device.get('HOSTNAME', ''), network_device.get('USERNAME', ''), network_device.get('PASSWORD', ''), timeout=network_device['TIMEOUT'], optional_args=network_device['OPTIONAL_ARGS'] ) network_device.get('DRIVER').open() # no exception raised here, means connection established network_device['UP'] = True except napalm_base.exceptions.ConnectionException as error: base_err_msg = "Cannot connect to {hostname}{port} as {username}.".format( hostname=network_device.get('HOSTNAME', '[unspecified hostname]'), port=(':{port}'.format(port=network_device.get('OPTIONAL_ARGS', {}).get('port')) if network_device.get('OPTIONAL_ARGS', {}).get('port') else ''), username=network_device.get('USERNAME', '') ) log.error(base_err_msg) log.error( "Please check error: %s", error ) raise napalm_base.exceptions.ConnectionException(base_err_msg) return network_device
Initialise the connection with the network device through NAPALM. :param: opts :return: the network device object
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/napalm.py#L304-L355
[ "def get_device_opts(opts, salt_obj=None):\n '''\n Returns the options of the napalm device.\n :pram: opts\n :return: the network device opts\n '''\n network_device = {}\n # by default, look in the proxy config details\n device_dict = opts.get('proxy', {}) if is_proxy(opts) else opts.get('napalm', {})\n if opts.get('proxy') or opts.get('napalm'):\n opts['multiprocessing'] = device_dict.get('multiprocessing', False)\n # Most NAPALM drivers are SSH-based, so multiprocessing should default to False.\n # But the user can be allows one to have a different value for the multiprocessing, which will\n # override the opts.\n if not device_dict:\n # still not able to setup\n log.error('Incorrect minion config. Please specify at least the napalm driver name!')\n # either under the proxy hier, either under the napalm in the config file\n network_device['HOSTNAME'] = device_dict.get('host') or \\\n device_dict.get('hostname') or \\\n device_dict.get('fqdn') or \\\n device_dict.get('ip')\n network_device['USERNAME'] = device_dict.get('username') or \\\n device_dict.get('user')\n network_device['DRIVER_NAME'] = device_dict.get('driver') or \\\n device_dict.get('os')\n network_device['PASSWORD'] = device_dict.get('passwd') or \\\n device_dict.get('password') or \\\n device_dict.get('pass') or \\\n ''\n network_device['TIMEOUT'] = device_dict.get('timeout', 60)\n network_device['OPTIONAL_ARGS'] = device_dict.get('optional_args', {})\n network_device['ALWAYS_ALIVE'] = device_dict.get('always_alive', True)\n network_device['PROVIDER'] = device_dict.get('provider')\n network_device['UP'] = False\n # get driver object form NAPALM\n if 'config_lock' not in network_device['OPTIONAL_ARGS']:\n network_device['OPTIONAL_ARGS']['config_lock'] = False\n if network_device['ALWAYS_ALIVE'] and 'keepalive' not in network_device['OPTIONAL_ARGS']:\n network_device['OPTIONAL_ARGS']['keepalive'] = 5 # 5 seconds keepalive\n return network_device\n" ]
# -*- coding: utf-8 -*- ''' Utils for the NAPALM modules and proxy. .. seealso:: - :mod:`NAPALM grains: select network devices based on their characteristics <salt.grains.napalm>` - :mod:`NET module: network basic features <salt.modules.napalm_network>` - :mod:`NTP operational and configuration management module <salt.modules.napalm_ntp>` - :mod:`BGP operational and configuration management module <salt.modules.napalm_bgp>` - :mod:`Routes details <salt.modules.napalm_route>` - :mod:`SNMP configuration module <salt.modules.napalm_snmp>` - :mod:`Users configuration management <salt.modules.napalm_users>` .. versionadded:: 2017.7.0 ''' # Import Python libs from __future__ import absolute_import, unicode_literals, print_function import copy import traceback import logging import importlib from functools import wraps # Import Salt libs from salt.ext import six import salt.output import salt.utils.platform import salt.utils.args # Import third party libs try: # will try to import NAPALM # https://github.com/napalm-automation/napalm # pylint: disable=W0611 import napalm import napalm.base as napalm_base # pylint: enable=W0611 HAS_NAPALM = True HAS_NAPALM_BASE = False # doesn't matter anymore, but needed for the logic below try: NAPALM_MAJOR = int(napalm.__version__.split('.')[0]) except AttributeError: NAPALM_MAJOR = 0 except ImportError: HAS_NAPALM = False try: import napalm_base HAS_NAPALM_BASE = True except ImportError: HAS_NAPALM_BASE = False try: # try importing ConnectionClosedException # from napalm-base # this exception has been introduced only in version 0.24.0 from napalm_base.exceptions import ConnectionClosedException HAS_CONN_CLOSED_EXC_CLASS = True except ImportError: HAS_CONN_CLOSED_EXC_CLASS = False log = logging.getLogger(__file__) def is_proxy(opts): ''' Is this a NAPALM proxy? ''' return salt.utils.platform.is_proxy() and opts.get('proxy', {}).get('proxytype') == 'napalm' def is_always_alive(opts): ''' Is always alive required? ''' return opts.get('proxy', {}).get('always_alive', True) def not_always_alive(opts): ''' Should this proxy be always alive? ''' return (is_proxy(opts) and not is_always_alive(opts)) or is_minion(opts) def is_minion(opts): ''' Is this a NAPALM straight minion? ''' return not salt.utils.platform.is_proxy() and 'napalm' in opts def virtual(opts, virtualname, filename): ''' Returns the __virtual__. ''' if ((HAS_NAPALM and NAPALM_MAJOR >= 2) or HAS_NAPALM_BASE) and (is_proxy(opts) or is_minion(opts)): return virtualname else: return ( False, ( '"{vname}"" {filename} cannot be loaded: ' 'NAPALM is not installed: ``pip install napalm``' ).format( vname=virtualname, filename='({filename})'.format(filename=filename) ) ) def call(napalm_device, method, *args, **kwargs): ''' Calls arbitrary methods from the network driver instance. Please check the readthedocs_ page for the updated list of getters. .. _readthedocs: http://napalm.readthedocs.org/en/latest/support/index.html#getters-support-matrix method Specifies the name of the method to be called. *args Arguments. **kwargs More arguments. :return: A dictionary with three keys: * result (True/False): if the operation succeeded * out (object): returns the object as-is from the call * comment (string): provides more details in case the call failed * traceback (string): complete traceback in case of exception. \ Please submit an issue including this traceback \ on the `correct driver repo`_ and make sure to read the FAQ_ .. _`correct driver repo`: https://github.com/napalm-automation/napalm/issues/new .. FAQ_: https://github.com/napalm-automation/napalm#faq Example: .. code-block:: python salt.utils.napalm.call( napalm_object, 'cli', [ 'show version', 'show chassis fan' ] ) ''' result = False out = None opts = napalm_device.get('__opts__', {}) retry = kwargs.pop('__retry', True) # retry executing the task? force_reconnect = kwargs.get('force_reconnect', False) if force_reconnect: log.debug('Forced reconnection initiated') log.debug('The current opts (under the proxy key):') log.debug(opts['proxy']) opts['proxy'].update(**kwargs) log.debug('Updated to:') log.debug(opts['proxy']) napalm_device = get_device(opts) try: if not napalm_device.get('UP', False): raise Exception('not connected') # if connected will try to execute desired command kwargs_copy = {} kwargs_copy.update(kwargs) for karg, warg in six.iteritems(kwargs_copy): # lets clear None arguments # to not be sent to NAPALM methods if warg is None: kwargs.pop(karg) out = getattr(napalm_device.get('DRIVER'), method)(*args, **kwargs) # calls the method with the specified parameters result = True except Exception as error: # either not connected # either unable to execute the command hostname = napalm_device.get('HOSTNAME', '[unspecified hostname]') err_tb = traceback.format_exc() # let's get the full traceback and display for debugging reasons. if isinstance(error, NotImplementedError): comment = '{method} is not implemented for the NAPALM {driver} driver!'.format( method=method, driver=napalm_device.get('DRIVER_NAME') ) elif retry and HAS_CONN_CLOSED_EXC_CLASS and isinstance(error, ConnectionClosedException): # Received disconection whilst executing the operation. # Instructed to retry (default behaviour) # thus trying to re-establish the connection # and re-execute the command # if any of the operations (close, open, call) will rise again ConnectionClosedException # it will fail loudly. kwargs['__retry'] = False # do not attempt re-executing comment = 'Disconnected from {device}. Trying to reconnect.'.format(device=hostname) log.error(err_tb) log.error(comment) log.debug('Clearing the connection with %s', hostname) call(napalm_device, 'close', __retry=False) # safely close the connection # Make sure we don't leave any TCP connection open behind # if we fail to close properly, we might not be able to access the log.debug('Re-opening the connection with %s', hostname) call(napalm_device, 'open', __retry=False) log.debug('Connection re-opened with %s', hostname) log.debug('Re-executing %s', method) return call(napalm_device, method, *args, **kwargs) # If still not able to reconnect and execute the task, # the proxy keepalive feature (if enabled) will attempt # to reconnect. # If the device is using a SSH-based connection, the failure # will also notify the paramiko transport and the `is_alive` flag # is going to be set correctly. # More background: the network device may decide to disconnect, # although the SSH session itself is alive and usable, the reason # being the lack of activity on the CLI. # Paramiko's keepalive doesn't help in this case, as the ServerAliveInterval # are targeting the transport layer, whilst the device takes the decision # when there isn't any activity on the CLI, thus at the application layer. # Moreover, the disconnect is silent and paramiko's is_alive flag will # continue to return True, although the connection is already unusable. # For more info, see https://github.com/paramiko/paramiko/issues/813. # But after a command fails, the `is_alive` flag becomes aware of these # changes and will return False from there on. And this is how the # Salt proxy keepalive helps: immediately after the first failure, it # will know the state of the connection and will try reconnecting. else: comment = 'Cannot execute "{method}" on {device}{port} as {user}. Reason: {error}!'.format( device=napalm_device.get('HOSTNAME', '[unspecified hostname]'), port=(':{port}'.format(port=napalm_device.get('OPTIONAL_ARGS', {}).get('port')) if napalm_device.get('OPTIONAL_ARGS', {}).get('port') else ''), user=napalm_device.get('USERNAME', ''), method=method, error=error ) log.error(comment) log.error(err_tb) return { 'out': {}, 'result': False, 'comment': comment, 'traceback': err_tb } finally: if opts and not_always_alive(opts) and napalm_device.get('CLOSE', True): # either running in a not-always-alive proxy # either running in a regular minion # close the connection when the call is over # unless the CLOSE is explicitly set as False napalm_device['DRIVER'].close() return { 'out': out, 'result': result, 'comment': '' } def get_device_opts(opts, salt_obj=None): ''' Returns the options of the napalm device. :pram: opts :return: the network device opts ''' network_device = {} # by default, look in the proxy config details device_dict = opts.get('proxy', {}) if is_proxy(opts) else opts.get('napalm', {}) if opts.get('proxy') or opts.get('napalm'): opts['multiprocessing'] = device_dict.get('multiprocessing', False) # Most NAPALM drivers are SSH-based, so multiprocessing should default to False. # But the user can be allows one to have a different value for the multiprocessing, which will # override the opts. if not device_dict: # still not able to setup log.error('Incorrect minion config. Please specify at least the napalm driver name!') # either under the proxy hier, either under the napalm in the config file network_device['HOSTNAME'] = device_dict.get('host') or \ device_dict.get('hostname') or \ device_dict.get('fqdn') or \ device_dict.get('ip') network_device['USERNAME'] = device_dict.get('username') or \ device_dict.get('user') network_device['DRIVER_NAME'] = device_dict.get('driver') or \ device_dict.get('os') network_device['PASSWORD'] = device_dict.get('passwd') or \ device_dict.get('password') or \ device_dict.get('pass') or \ '' network_device['TIMEOUT'] = device_dict.get('timeout', 60) network_device['OPTIONAL_ARGS'] = device_dict.get('optional_args', {}) network_device['ALWAYS_ALIVE'] = device_dict.get('always_alive', True) network_device['PROVIDER'] = device_dict.get('provider') network_device['UP'] = False # get driver object form NAPALM if 'config_lock' not in network_device['OPTIONAL_ARGS']: network_device['OPTIONAL_ARGS']['config_lock'] = False if network_device['ALWAYS_ALIVE'] and 'keepalive' not in network_device['OPTIONAL_ARGS']: network_device['OPTIONAL_ARGS']['keepalive'] = 5 # 5 seconds keepalive return network_device def proxy_napalm_wrap(func): ''' This decorator is used to make the execution module functions available outside a proxy minion, or when running inside a proxy minion. If we are running in a proxy, retrieve the connection details from the __proxy__ injected variable. If we are not, then use the connection information from the opts. :param func: :return: ''' @wraps(func) def func_wrapper(*args, **kwargs): wrapped_global_namespace = func.__globals__ # get __opts__ and __proxy__ from func_globals proxy = wrapped_global_namespace.get('__proxy__') opts = copy.deepcopy(wrapped_global_namespace.get('__opts__')) # in any case, will inject the `napalm_device` global # the execution modules will make use of this variable from now on # previously they were accessing the device properties through the __proxy__ object always_alive = opts.get('proxy', {}).get('always_alive', True) # force_reconnect is a magic keyword arg that allows one to establish # a separate connection to the network device running under an always # alive Proxy Minion, using new credentials (overriding the ones # configured in the opts / pillar. force_reconnect = kwargs.get('force_reconnect', False) if force_reconnect: log.debug('Usage of reconnect force detected') log.debug('Opts before merging') log.debug(opts['proxy']) opts['proxy'].update(**kwargs) log.debug('Opts after merging') log.debug(opts['proxy']) if is_proxy(opts) and always_alive: # if it is running in a NAPALM Proxy and it's using the default # always alive behaviour, will get the cached copy of the network # device object which should preserve the connection. if force_reconnect: wrapped_global_namespace['napalm_device'] = get_device(opts) else: wrapped_global_namespace['napalm_device'] = proxy['napalm.get_device']() elif is_proxy(opts) and not always_alive: # if still proxy, but the user does not want the SSH session always alive # get a new device instance # which establishes a new connection # which is closed just before the call() function defined above returns if 'inherit_napalm_device' not in kwargs or ('inherit_napalm_device' in kwargs and not kwargs['inherit_napalm_device']): # try to open a new connection # but only if the function does not inherit the napalm driver # for configuration management this is very important, # in order to make sure we are editing the same session. try: wrapped_global_namespace['napalm_device'] = get_device(opts) except napalm_base.exceptions.ConnectionException as nce: log.error(nce) return '{base_msg}. See log for details.'.format( base_msg=six.text_type(nce.msg) ) else: # in case the `inherit_napalm_device` is set # and it also has a non-empty value, # the global var `napalm_device` will be overridden. # this is extremely important for configuration-related features # as all actions must be issued within the same configuration session # otherwise we risk to open multiple sessions wrapped_global_namespace['napalm_device'] = kwargs['inherit_napalm_device'] else: # if not a NAPLAM proxy # thus it is running on a regular minion, directly on the network device # or another flavour of Minion from where we can invoke arbitrary # NAPALM commands # get __salt__ from func_globals log.debug('Not running in a NAPALM Proxy Minion') _salt_obj = wrapped_global_namespace.get('__salt__') napalm_opts = _salt_obj['config.get']('napalm', {}) napalm_inventory = _salt_obj['config.get']('napalm_inventory', {}) log.debug('NAPALM opts found in the Minion config') log.debug(napalm_opts) clean_kwargs = salt.utils.args.clean_kwargs(**kwargs) napalm_opts.update(clean_kwargs) # no need for deeper merge log.debug('Merging the found opts with the CLI args') log.debug(napalm_opts) host = napalm_opts.get('host') or napalm_opts.get('hostname') or\ napalm_opts.get('fqdn') or napalm_opts.get('ip') if host and napalm_inventory and isinstance(napalm_inventory, dict) and\ host in napalm_inventory: inventory_opts = napalm_inventory[host] log.debug('Found %s in the NAPALM inventory:', host) log.debug(inventory_opts) napalm_opts.update(inventory_opts) log.debug('Merging the config for %s with the details found in the napalm inventory:', host) log.debug(napalm_opts) opts = copy.deepcopy(opts) # make sure we don't override the original # opts, but just inject the CLI args from the kwargs to into the # object manipulated by ``get_device_opts`` to extract the # connection details, then use then to establish the connection. opts['napalm'] = napalm_opts if 'inherit_napalm_device' not in kwargs or ('inherit_napalm_device' in kwargs and not kwargs['inherit_napalm_device']): # try to open a new connection # but only if the function does not inherit the napalm driver # for configuration management this is very important, # in order to make sure we are editing the same session. try: wrapped_global_namespace['napalm_device'] = get_device(opts, salt_obj=_salt_obj) except napalm_base.exceptions.ConnectionException as nce: log.error(nce) return '{base_msg}. See log for details.'.format( base_msg=six.text_type(nce.msg) ) else: # in case the `inherit_napalm_device` is set # and it also has a non-empty value, # the global var `napalm_device` will be overridden. # this is extremely important for configuration-related features # as all actions must be issued within the same configuration session # otherwise we risk to open multiple sessions wrapped_global_namespace['napalm_device'] = kwargs['inherit_napalm_device'] if not_always_alive(opts): # inject the __opts__ only when not always alive # otherwise, we don't want to overload the always-alive proxies wrapped_global_namespace['napalm_device']['__opts__'] = opts ret = func(*args, **kwargs) if force_reconnect: log.debug('That was a forced reconnect, gracefully clearing up') device = wrapped_global_namespace['napalm_device'] closing = call(device, 'close', __retry=False) return ret return func_wrapper def default_ret(name): ''' Return the default dict of the state output. ''' ret = { 'name': name, 'changes': {}, 'result': False, 'comment': '' } return ret def loaded_ret(ret, loaded, test, debug, compliance_report=False, opts=None): ''' Return the final state output. ret The initial state output structure. loaded The loaded dictionary. ''' # Always get the comment changes = {} ret['comment'] = loaded['comment'] if 'diff' in loaded: changes['diff'] = loaded['diff'] if 'commit_id' in loaded: changes['commit_id'] = loaded['commit_id'] if 'compliance_report' in loaded: if compliance_report: changes['compliance_report'] = loaded['compliance_report'] if debug and 'loaded_config' in loaded: changes['loaded_config'] = loaded['loaded_config'] if changes.get('diff'): ret['comment'] = '{comment_base}\n\nConfiguration diff:\n\n{diff}'.format(comment_base=ret['comment'], diff=changes['diff']) if changes.get('loaded_config'): ret['comment'] = '{comment_base}\n\nLoaded config:\n\n{loaded_cfg}'.format( comment_base=ret['comment'], loaded_cfg=changes['loaded_config']) if changes.get('compliance_report'): ret['comment'] = '{comment_base}\n\nCompliance report:\n\n{compliance}'.format( comment_base=ret['comment'], compliance=salt.output.string_format(changes['compliance_report'], 'nested', opts=opts)) if not loaded.get('result', False): # Failure of some sort return ret if not loaded.get('already_configured', True): # We're making changes if test: ret['result'] = None return ret # Not test, changes were applied ret.update({ 'result': True, 'changes': changes, 'comment': "Configuration changed!\n{}".format(loaded['comment']) }) return ret # No changes ret.update({ 'result': True, 'changes': {} }) return ret
saltstack/salt
salt/utils/napalm.py
proxy_napalm_wrap
python
def proxy_napalm_wrap(func): ''' This decorator is used to make the execution module functions available outside a proxy minion, or when running inside a proxy minion. If we are running in a proxy, retrieve the connection details from the __proxy__ injected variable. If we are not, then use the connection information from the opts. :param func: :return: ''' @wraps(func) def func_wrapper(*args, **kwargs): wrapped_global_namespace = func.__globals__ # get __opts__ and __proxy__ from func_globals proxy = wrapped_global_namespace.get('__proxy__') opts = copy.deepcopy(wrapped_global_namespace.get('__opts__')) # in any case, will inject the `napalm_device` global # the execution modules will make use of this variable from now on # previously they were accessing the device properties through the __proxy__ object always_alive = opts.get('proxy', {}).get('always_alive', True) # force_reconnect is a magic keyword arg that allows one to establish # a separate connection to the network device running under an always # alive Proxy Minion, using new credentials (overriding the ones # configured in the opts / pillar. force_reconnect = kwargs.get('force_reconnect', False) if force_reconnect: log.debug('Usage of reconnect force detected') log.debug('Opts before merging') log.debug(opts['proxy']) opts['proxy'].update(**kwargs) log.debug('Opts after merging') log.debug(opts['proxy']) if is_proxy(opts) and always_alive: # if it is running in a NAPALM Proxy and it's using the default # always alive behaviour, will get the cached copy of the network # device object which should preserve the connection. if force_reconnect: wrapped_global_namespace['napalm_device'] = get_device(opts) else: wrapped_global_namespace['napalm_device'] = proxy['napalm.get_device']() elif is_proxy(opts) and not always_alive: # if still proxy, but the user does not want the SSH session always alive # get a new device instance # which establishes a new connection # which is closed just before the call() function defined above returns if 'inherit_napalm_device' not in kwargs or ('inherit_napalm_device' in kwargs and not kwargs['inherit_napalm_device']): # try to open a new connection # but only if the function does not inherit the napalm driver # for configuration management this is very important, # in order to make sure we are editing the same session. try: wrapped_global_namespace['napalm_device'] = get_device(opts) except napalm_base.exceptions.ConnectionException as nce: log.error(nce) return '{base_msg}. See log for details.'.format( base_msg=six.text_type(nce.msg) ) else: # in case the `inherit_napalm_device` is set # and it also has a non-empty value, # the global var `napalm_device` will be overridden. # this is extremely important for configuration-related features # as all actions must be issued within the same configuration session # otherwise we risk to open multiple sessions wrapped_global_namespace['napalm_device'] = kwargs['inherit_napalm_device'] else: # if not a NAPLAM proxy # thus it is running on a regular minion, directly on the network device # or another flavour of Minion from where we can invoke arbitrary # NAPALM commands # get __salt__ from func_globals log.debug('Not running in a NAPALM Proxy Minion') _salt_obj = wrapped_global_namespace.get('__salt__') napalm_opts = _salt_obj['config.get']('napalm', {}) napalm_inventory = _salt_obj['config.get']('napalm_inventory', {}) log.debug('NAPALM opts found in the Minion config') log.debug(napalm_opts) clean_kwargs = salt.utils.args.clean_kwargs(**kwargs) napalm_opts.update(clean_kwargs) # no need for deeper merge log.debug('Merging the found opts with the CLI args') log.debug(napalm_opts) host = napalm_opts.get('host') or napalm_opts.get('hostname') or\ napalm_opts.get('fqdn') or napalm_opts.get('ip') if host and napalm_inventory and isinstance(napalm_inventory, dict) and\ host in napalm_inventory: inventory_opts = napalm_inventory[host] log.debug('Found %s in the NAPALM inventory:', host) log.debug(inventory_opts) napalm_opts.update(inventory_opts) log.debug('Merging the config for %s with the details found in the napalm inventory:', host) log.debug(napalm_opts) opts = copy.deepcopy(opts) # make sure we don't override the original # opts, but just inject the CLI args from the kwargs to into the # object manipulated by ``get_device_opts`` to extract the # connection details, then use then to establish the connection. opts['napalm'] = napalm_opts if 'inherit_napalm_device' not in kwargs or ('inherit_napalm_device' in kwargs and not kwargs['inherit_napalm_device']): # try to open a new connection # but only if the function does not inherit the napalm driver # for configuration management this is very important, # in order to make sure we are editing the same session. try: wrapped_global_namespace['napalm_device'] = get_device(opts, salt_obj=_salt_obj) except napalm_base.exceptions.ConnectionException as nce: log.error(nce) return '{base_msg}. See log for details.'.format( base_msg=six.text_type(nce.msg) ) else: # in case the `inherit_napalm_device` is set # and it also has a non-empty value, # the global var `napalm_device` will be overridden. # this is extremely important for configuration-related features # as all actions must be issued within the same configuration session # otherwise we risk to open multiple sessions wrapped_global_namespace['napalm_device'] = kwargs['inherit_napalm_device'] if not_always_alive(opts): # inject the __opts__ only when not always alive # otherwise, we don't want to overload the always-alive proxies wrapped_global_namespace['napalm_device']['__opts__'] = opts ret = func(*args, **kwargs) if force_reconnect: log.debug('That was a forced reconnect, gracefully clearing up') device = wrapped_global_namespace['napalm_device'] closing = call(device, 'close', __retry=False) return ret return func_wrapper
This decorator is used to make the execution module functions available outside a proxy minion, or when running inside a proxy minion. If we are running in a proxy, retrieve the connection details from the __proxy__ injected variable. If we are not, then use the connection information from the opts. :param func: :return:
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/napalm.py#L358-L486
null
# -*- coding: utf-8 -*- ''' Utils for the NAPALM modules and proxy. .. seealso:: - :mod:`NAPALM grains: select network devices based on their characteristics <salt.grains.napalm>` - :mod:`NET module: network basic features <salt.modules.napalm_network>` - :mod:`NTP operational and configuration management module <salt.modules.napalm_ntp>` - :mod:`BGP operational and configuration management module <salt.modules.napalm_bgp>` - :mod:`Routes details <salt.modules.napalm_route>` - :mod:`SNMP configuration module <salt.modules.napalm_snmp>` - :mod:`Users configuration management <salt.modules.napalm_users>` .. versionadded:: 2017.7.0 ''' # Import Python libs from __future__ import absolute_import, unicode_literals, print_function import copy import traceback import logging import importlib from functools import wraps # Import Salt libs from salt.ext import six import salt.output import salt.utils.platform import salt.utils.args # Import third party libs try: # will try to import NAPALM # https://github.com/napalm-automation/napalm # pylint: disable=W0611 import napalm import napalm.base as napalm_base # pylint: enable=W0611 HAS_NAPALM = True HAS_NAPALM_BASE = False # doesn't matter anymore, but needed for the logic below try: NAPALM_MAJOR = int(napalm.__version__.split('.')[0]) except AttributeError: NAPALM_MAJOR = 0 except ImportError: HAS_NAPALM = False try: import napalm_base HAS_NAPALM_BASE = True except ImportError: HAS_NAPALM_BASE = False try: # try importing ConnectionClosedException # from napalm-base # this exception has been introduced only in version 0.24.0 from napalm_base.exceptions import ConnectionClosedException HAS_CONN_CLOSED_EXC_CLASS = True except ImportError: HAS_CONN_CLOSED_EXC_CLASS = False log = logging.getLogger(__file__) def is_proxy(opts): ''' Is this a NAPALM proxy? ''' return salt.utils.platform.is_proxy() and opts.get('proxy', {}).get('proxytype') == 'napalm' def is_always_alive(opts): ''' Is always alive required? ''' return opts.get('proxy', {}).get('always_alive', True) def not_always_alive(opts): ''' Should this proxy be always alive? ''' return (is_proxy(opts) and not is_always_alive(opts)) or is_minion(opts) def is_minion(opts): ''' Is this a NAPALM straight minion? ''' return not salt.utils.platform.is_proxy() and 'napalm' in opts def virtual(opts, virtualname, filename): ''' Returns the __virtual__. ''' if ((HAS_NAPALM and NAPALM_MAJOR >= 2) or HAS_NAPALM_BASE) and (is_proxy(opts) or is_minion(opts)): return virtualname else: return ( False, ( '"{vname}"" {filename} cannot be loaded: ' 'NAPALM is not installed: ``pip install napalm``' ).format( vname=virtualname, filename='({filename})'.format(filename=filename) ) ) def call(napalm_device, method, *args, **kwargs): ''' Calls arbitrary methods from the network driver instance. Please check the readthedocs_ page for the updated list of getters. .. _readthedocs: http://napalm.readthedocs.org/en/latest/support/index.html#getters-support-matrix method Specifies the name of the method to be called. *args Arguments. **kwargs More arguments. :return: A dictionary with three keys: * result (True/False): if the operation succeeded * out (object): returns the object as-is from the call * comment (string): provides more details in case the call failed * traceback (string): complete traceback in case of exception. \ Please submit an issue including this traceback \ on the `correct driver repo`_ and make sure to read the FAQ_ .. _`correct driver repo`: https://github.com/napalm-automation/napalm/issues/new .. FAQ_: https://github.com/napalm-automation/napalm#faq Example: .. code-block:: python salt.utils.napalm.call( napalm_object, 'cli', [ 'show version', 'show chassis fan' ] ) ''' result = False out = None opts = napalm_device.get('__opts__', {}) retry = kwargs.pop('__retry', True) # retry executing the task? force_reconnect = kwargs.get('force_reconnect', False) if force_reconnect: log.debug('Forced reconnection initiated') log.debug('The current opts (under the proxy key):') log.debug(opts['proxy']) opts['proxy'].update(**kwargs) log.debug('Updated to:') log.debug(opts['proxy']) napalm_device = get_device(opts) try: if not napalm_device.get('UP', False): raise Exception('not connected') # if connected will try to execute desired command kwargs_copy = {} kwargs_copy.update(kwargs) for karg, warg in six.iteritems(kwargs_copy): # lets clear None arguments # to not be sent to NAPALM methods if warg is None: kwargs.pop(karg) out = getattr(napalm_device.get('DRIVER'), method)(*args, **kwargs) # calls the method with the specified parameters result = True except Exception as error: # either not connected # either unable to execute the command hostname = napalm_device.get('HOSTNAME', '[unspecified hostname]') err_tb = traceback.format_exc() # let's get the full traceback and display for debugging reasons. if isinstance(error, NotImplementedError): comment = '{method} is not implemented for the NAPALM {driver} driver!'.format( method=method, driver=napalm_device.get('DRIVER_NAME') ) elif retry and HAS_CONN_CLOSED_EXC_CLASS and isinstance(error, ConnectionClosedException): # Received disconection whilst executing the operation. # Instructed to retry (default behaviour) # thus trying to re-establish the connection # and re-execute the command # if any of the operations (close, open, call) will rise again ConnectionClosedException # it will fail loudly. kwargs['__retry'] = False # do not attempt re-executing comment = 'Disconnected from {device}. Trying to reconnect.'.format(device=hostname) log.error(err_tb) log.error(comment) log.debug('Clearing the connection with %s', hostname) call(napalm_device, 'close', __retry=False) # safely close the connection # Make sure we don't leave any TCP connection open behind # if we fail to close properly, we might not be able to access the log.debug('Re-opening the connection with %s', hostname) call(napalm_device, 'open', __retry=False) log.debug('Connection re-opened with %s', hostname) log.debug('Re-executing %s', method) return call(napalm_device, method, *args, **kwargs) # If still not able to reconnect and execute the task, # the proxy keepalive feature (if enabled) will attempt # to reconnect. # If the device is using a SSH-based connection, the failure # will also notify the paramiko transport and the `is_alive` flag # is going to be set correctly. # More background: the network device may decide to disconnect, # although the SSH session itself is alive and usable, the reason # being the lack of activity on the CLI. # Paramiko's keepalive doesn't help in this case, as the ServerAliveInterval # are targeting the transport layer, whilst the device takes the decision # when there isn't any activity on the CLI, thus at the application layer. # Moreover, the disconnect is silent and paramiko's is_alive flag will # continue to return True, although the connection is already unusable. # For more info, see https://github.com/paramiko/paramiko/issues/813. # But after a command fails, the `is_alive` flag becomes aware of these # changes and will return False from there on. And this is how the # Salt proxy keepalive helps: immediately after the first failure, it # will know the state of the connection and will try reconnecting. else: comment = 'Cannot execute "{method}" on {device}{port} as {user}. Reason: {error}!'.format( device=napalm_device.get('HOSTNAME', '[unspecified hostname]'), port=(':{port}'.format(port=napalm_device.get('OPTIONAL_ARGS', {}).get('port')) if napalm_device.get('OPTIONAL_ARGS', {}).get('port') else ''), user=napalm_device.get('USERNAME', ''), method=method, error=error ) log.error(comment) log.error(err_tb) return { 'out': {}, 'result': False, 'comment': comment, 'traceback': err_tb } finally: if opts and not_always_alive(opts) and napalm_device.get('CLOSE', True): # either running in a not-always-alive proxy # either running in a regular minion # close the connection when the call is over # unless the CLOSE is explicitly set as False napalm_device['DRIVER'].close() return { 'out': out, 'result': result, 'comment': '' } def get_device_opts(opts, salt_obj=None): ''' Returns the options of the napalm device. :pram: opts :return: the network device opts ''' network_device = {} # by default, look in the proxy config details device_dict = opts.get('proxy', {}) if is_proxy(opts) else opts.get('napalm', {}) if opts.get('proxy') or opts.get('napalm'): opts['multiprocessing'] = device_dict.get('multiprocessing', False) # Most NAPALM drivers are SSH-based, so multiprocessing should default to False. # But the user can be allows one to have a different value for the multiprocessing, which will # override the opts. if not device_dict: # still not able to setup log.error('Incorrect minion config. Please specify at least the napalm driver name!') # either under the proxy hier, either under the napalm in the config file network_device['HOSTNAME'] = device_dict.get('host') or \ device_dict.get('hostname') or \ device_dict.get('fqdn') or \ device_dict.get('ip') network_device['USERNAME'] = device_dict.get('username') or \ device_dict.get('user') network_device['DRIVER_NAME'] = device_dict.get('driver') or \ device_dict.get('os') network_device['PASSWORD'] = device_dict.get('passwd') or \ device_dict.get('password') or \ device_dict.get('pass') or \ '' network_device['TIMEOUT'] = device_dict.get('timeout', 60) network_device['OPTIONAL_ARGS'] = device_dict.get('optional_args', {}) network_device['ALWAYS_ALIVE'] = device_dict.get('always_alive', True) network_device['PROVIDER'] = device_dict.get('provider') network_device['UP'] = False # get driver object form NAPALM if 'config_lock' not in network_device['OPTIONAL_ARGS']: network_device['OPTIONAL_ARGS']['config_lock'] = False if network_device['ALWAYS_ALIVE'] and 'keepalive' not in network_device['OPTIONAL_ARGS']: network_device['OPTIONAL_ARGS']['keepalive'] = 5 # 5 seconds keepalive return network_device def get_device(opts, salt_obj=None): ''' Initialise the connection with the network device through NAPALM. :param: opts :return: the network device object ''' log.debug('Setting up NAPALM connection') network_device = get_device_opts(opts, salt_obj=salt_obj) provider_lib = napalm_base if network_device.get('PROVIDER'): # In case the user requires a different provider library, # other than napalm-base. # For example, if napalm-base does not satisfy the requirements # and needs to be enahanced with more specific features, # we may need to define a custom library on top of napalm-base # with the constraint that it still needs to provide the # `get_network_driver` function. However, even this can be # extended later, if really needed. # Configuration example: # provider: napalm_base_example try: provider_lib = importlib.import_module(network_device.get('PROVIDER')) except ImportError as ierr: log.error('Unable to import %s', network_device.get('PROVIDER'), exc_info=True) log.error('Falling back to napalm-base') _driver_ = provider_lib.get_network_driver(network_device.get('DRIVER_NAME')) try: network_device['DRIVER'] = _driver_( network_device.get('HOSTNAME', ''), network_device.get('USERNAME', ''), network_device.get('PASSWORD', ''), timeout=network_device['TIMEOUT'], optional_args=network_device['OPTIONAL_ARGS'] ) network_device.get('DRIVER').open() # no exception raised here, means connection established network_device['UP'] = True except napalm_base.exceptions.ConnectionException as error: base_err_msg = "Cannot connect to {hostname}{port} as {username}.".format( hostname=network_device.get('HOSTNAME', '[unspecified hostname]'), port=(':{port}'.format(port=network_device.get('OPTIONAL_ARGS', {}).get('port')) if network_device.get('OPTIONAL_ARGS', {}).get('port') else ''), username=network_device.get('USERNAME', '') ) log.error(base_err_msg) log.error( "Please check error: %s", error ) raise napalm_base.exceptions.ConnectionException(base_err_msg) return network_device def default_ret(name): ''' Return the default dict of the state output. ''' ret = { 'name': name, 'changes': {}, 'result': False, 'comment': '' } return ret def loaded_ret(ret, loaded, test, debug, compliance_report=False, opts=None): ''' Return the final state output. ret The initial state output structure. loaded The loaded dictionary. ''' # Always get the comment changes = {} ret['comment'] = loaded['comment'] if 'diff' in loaded: changes['diff'] = loaded['diff'] if 'commit_id' in loaded: changes['commit_id'] = loaded['commit_id'] if 'compliance_report' in loaded: if compliance_report: changes['compliance_report'] = loaded['compliance_report'] if debug and 'loaded_config' in loaded: changes['loaded_config'] = loaded['loaded_config'] if changes.get('diff'): ret['comment'] = '{comment_base}\n\nConfiguration diff:\n\n{diff}'.format(comment_base=ret['comment'], diff=changes['diff']) if changes.get('loaded_config'): ret['comment'] = '{comment_base}\n\nLoaded config:\n\n{loaded_cfg}'.format( comment_base=ret['comment'], loaded_cfg=changes['loaded_config']) if changes.get('compliance_report'): ret['comment'] = '{comment_base}\n\nCompliance report:\n\n{compliance}'.format( comment_base=ret['comment'], compliance=salt.output.string_format(changes['compliance_report'], 'nested', opts=opts)) if not loaded.get('result', False): # Failure of some sort return ret if not loaded.get('already_configured', True): # We're making changes if test: ret['result'] = None return ret # Not test, changes were applied ret.update({ 'result': True, 'changes': changes, 'comment': "Configuration changed!\n{}".format(loaded['comment']) }) return ret # No changes ret.update({ 'result': True, 'changes': {} }) return ret
saltstack/salt
salt/utils/napalm.py
loaded_ret
python
def loaded_ret(ret, loaded, test, debug, compliance_report=False, opts=None): ''' Return the final state output. ret The initial state output structure. loaded The loaded dictionary. ''' # Always get the comment changes = {} ret['comment'] = loaded['comment'] if 'diff' in loaded: changes['diff'] = loaded['diff'] if 'commit_id' in loaded: changes['commit_id'] = loaded['commit_id'] if 'compliance_report' in loaded: if compliance_report: changes['compliance_report'] = loaded['compliance_report'] if debug and 'loaded_config' in loaded: changes['loaded_config'] = loaded['loaded_config'] if changes.get('diff'): ret['comment'] = '{comment_base}\n\nConfiguration diff:\n\n{diff}'.format(comment_base=ret['comment'], diff=changes['diff']) if changes.get('loaded_config'): ret['comment'] = '{comment_base}\n\nLoaded config:\n\n{loaded_cfg}'.format( comment_base=ret['comment'], loaded_cfg=changes['loaded_config']) if changes.get('compliance_report'): ret['comment'] = '{comment_base}\n\nCompliance report:\n\n{compliance}'.format( comment_base=ret['comment'], compliance=salt.output.string_format(changes['compliance_report'], 'nested', opts=opts)) if not loaded.get('result', False): # Failure of some sort return ret if not loaded.get('already_configured', True): # We're making changes if test: ret['result'] = None return ret # Not test, changes were applied ret.update({ 'result': True, 'changes': changes, 'comment': "Configuration changed!\n{}".format(loaded['comment']) }) return ret # No changes ret.update({ 'result': True, 'changes': {} }) return ret
Return the final state output. ret The initial state output structure. loaded The loaded dictionary.
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/napalm.py#L502-L553
[ "def string_format(data, out, opts=None, **kwargs):\n '''\n Return the formatted outputter string, removing the ANSI escape sequences.\n '''\n raw_output = try_printout(data, out, opts, **kwargs)\n ansi_escape = re.compile(r'\\x1b[^m]*m')\n return ansi_escape.sub('', raw_output)\n" ]
# -*- coding: utf-8 -*- ''' Utils for the NAPALM modules and proxy. .. seealso:: - :mod:`NAPALM grains: select network devices based on their characteristics <salt.grains.napalm>` - :mod:`NET module: network basic features <salt.modules.napalm_network>` - :mod:`NTP operational and configuration management module <salt.modules.napalm_ntp>` - :mod:`BGP operational and configuration management module <salt.modules.napalm_bgp>` - :mod:`Routes details <salt.modules.napalm_route>` - :mod:`SNMP configuration module <salt.modules.napalm_snmp>` - :mod:`Users configuration management <salt.modules.napalm_users>` .. versionadded:: 2017.7.0 ''' # Import Python libs from __future__ import absolute_import, unicode_literals, print_function import copy import traceback import logging import importlib from functools import wraps # Import Salt libs from salt.ext import six import salt.output import salt.utils.platform import salt.utils.args # Import third party libs try: # will try to import NAPALM # https://github.com/napalm-automation/napalm # pylint: disable=W0611 import napalm import napalm.base as napalm_base # pylint: enable=W0611 HAS_NAPALM = True HAS_NAPALM_BASE = False # doesn't matter anymore, but needed for the logic below try: NAPALM_MAJOR = int(napalm.__version__.split('.')[0]) except AttributeError: NAPALM_MAJOR = 0 except ImportError: HAS_NAPALM = False try: import napalm_base HAS_NAPALM_BASE = True except ImportError: HAS_NAPALM_BASE = False try: # try importing ConnectionClosedException # from napalm-base # this exception has been introduced only in version 0.24.0 from napalm_base.exceptions import ConnectionClosedException HAS_CONN_CLOSED_EXC_CLASS = True except ImportError: HAS_CONN_CLOSED_EXC_CLASS = False log = logging.getLogger(__file__) def is_proxy(opts): ''' Is this a NAPALM proxy? ''' return salt.utils.platform.is_proxy() and opts.get('proxy', {}).get('proxytype') == 'napalm' def is_always_alive(opts): ''' Is always alive required? ''' return opts.get('proxy', {}).get('always_alive', True) def not_always_alive(opts): ''' Should this proxy be always alive? ''' return (is_proxy(opts) and not is_always_alive(opts)) or is_minion(opts) def is_minion(opts): ''' Is this a NAPALM straight minion? ''' return not salt.utils.platform.is_proxy() and 'napalm' in opts def virtual(opts, virtualname, filename): ''' Returns the __virtual__. ''' if ((HAS_NAPALM and NAPALM_MAJOR >= 2) or HAS_NAPALM_BASE) and (is_proxy(opts) or is_minion(opts)): return virtualname else: return ( False, ( '"{vname}"" {filename} cannot be loaded: ' 'NAPALM is not installed: ``pip install napalm``' ).format( vname=virtualname, filename='({filename})'.format(filename=filename) ) ) def call(napalm_device, method, *args, **kwargs): ''' Calls arbitrary methods from the network driver instance. Please check the readthedocs_ page for the updated list of getters. .. _readthedocs: http://napalm.readthedocs.org/en/latest/support/index.html#getters-support-matrix method Specifies the name of the method to be called. *args Arguments. **kwargs More arguments. :return: A dictionary with three keys: * result (True/False): if the operation succeeded * out (object): returns the object as-is from the call * comment (string): provides more details in case the call failed * traceback (string): complete traceback in case of exception. \ Please submit an issue including this traceback \ on the `correct driver repo`_ and make sure to read the FAQ_ .. _`correct driver repo`: https://github.com/napalm-automation/napalm/issues/new .. FAQ_: https://github.com/napalm-automation/napalm#faq Example: .. code-block:: python salt.utils.napalm.call( napalm_object, 'cli', [ 'show version', 'show chassis fan' ] ) ''' result = False out = None opts = napalm_device.get('__opts__', {}) retry = kwargs.pop('__retry', True) # retry executing the task? force_reconnect = kwargs.get('force_reconnect', False) if force_reconnect: log.debug('Forced reconnection initiated') log.debug('The current opts (under the proxy key):') log.debug(opts['proxy']) opts['proxy'].update(**kwargs) log.debug('Updated to:') log.debug(opts['proxy']) napalm_device = get_device(opts) try: if not napalm_device.get('UP', False): raise Exception('not connected') # if connected will try to execute desired command kwargs_copy = {} kwargs_copy.update(kwargs) for karg, warg in six.iteritems(kwargs_copy): # lets clear None arguments # to not be sent to NAPALM methods if warg is None: kwargs.pop(karg) out = getattr(napalm_device.get('DRIVER'), method)(*args, **kwargs) # calls the method with the specified parameters result = True except Exception as error: # either not connected # either unable to execute the command hostname = napalm_device.get('HOSTNAME', '[unspecified hostname]') err_tb = traceback.format_exc() # let's get the full traceback and display for debugging reasons. if isinstance(error, NotImplementedError): comment = '{method} is not implemented for the NAPALM {driver} driver!'.format( method=method, driver=napalm_device.get('DRIVER_NAME') ) elif retry and HAS_CONN_CLOSED_EXC_CLASS and isinstance(error, ConnectionClosedException): # Received disconection whilst executing the operation. # Instructed to retry (default behaviour) # thus trying to re-establish the connection # and re-execute the command # if any of the operations (close, open, call) will rise again ConnectionClosedException # it will fail loudly. kwargs['__retry'] = False # do not attempt re-executing comment = 'Disconnected from {device}. Trying to reconnect.'.format(device=hostname) log.error(err_tb) log.error(comment) log.debug('Clearing the connection with %s', hostname) call(napalm_device, 'close', __retry=False) # safely close the connection # Make sure we don't leave any TCP connection open behind # if we fail to close properly, we might not be able to access the log.debug('Re-opening the connection with %s', hostname) call(napalm_device, 'open', __retry=False) log.debug('Connection re-opened with %s', hostname) log.debug('Re-executing %s', method) return call(napalm_device, method, *args, **kwargs) # If still not able to reconnect and execute the task, # the proxy keepalive feature (if enabled) will attempt # to reconnect. # If the device is using a SSH-based connection, the failure # will also notify the paramiko transport and the `is_alive` flag # is going to be set correctly. # More background: the network device may decide to disconnect, # although the SSH session itself is alive and usable, the reason # being the lack of activity on the CLI. # Paramiko's keepalive doesn't help in this case, as the ServerAliveInterval # are targeting the transport layer, whilst the device takes the decision # when there isn't any activity on the CLI, thus at the application layer. # Moreover, the disconnect is silent and paramiko's is_alive flag will # continue to return True, although the connection is already unusable. # For more info, see https://github.com/paramiko/paramiko/issues/813. # But after a command fails, the `is_alive` flag becomes aware of these # changes and will return False from there on. And this is how the # Salt proxy keepalive helps: immediately after the first failure, it # will know the state of the connection and will try reconnecting. else: comment = 'Cannot execute "{method}" on {device}{port} as {user}. Reason: {error}!'.format( device=napalm_device.get('HOSTNAME', '[unspecified hostname]'), port=(':{port}'.format(port=napalm_device.get('OPTIONAL_ARGS', {}).get('port')) if napalm_device.get('OPTIONAL_ARGS', {}).get('port') else ''), user=napalm_device.get('USERNAME', ''), method=method, error=error ) log.error(comment) log.error(err_tb) return { 'out': {}, 'result': False, 'comment': comment, 'traceback': err_tb } finally: if opts and not_always_alive(opts) and napalm_device.get('CLOSE', True): # either running in a not-always-alive proxy # either running in a regular minion # close the connection when the call is over # unless the CLOSE is explicitly set as False napalm_device['DRIVER'].close() return { 'out': out, 'result': result, 'comment': '' } def get_device_opts(opts, salt_obj=None): ''' Returns the options of the napalm device. :pram: opts :return: the network device opts ''' network_device = {} # by default, look in the proxy config details device_dict = opts.get('proxy', {}) if is_proxy(opts) else opts.get('napalm', {}) if opts.get('proxy') or opts.get('napalm'): opts['multiprocessing'] = device_dict.get('multiprocessing', False) # Most NAPALM drivers are SSH-based, so multiprocessing should default to False. # But the user can be allows one to have a different value for the multiprocessing, which will # override the opts. if not device_dict: # still not able to setup log.error('Incorrect minion config. Please specify at least the napalm driver name!') # either under the proxy hier, either under the napalm in the config file network_device['HOSTNAME'] = device_dict.get('host') or \ device_dict.get('hostname') or \ device_dict.get('fqdn') or \ device_dict.get('ip') network_device['USERNAME'] = device_dict.get('username') or \ device_dict.get('user') network_device['DRIVER_NAME'] = device_dict.get('driver') or \ device_dict.get('os') network_device['PASSWORD'] = device_dict.get('passwd') or \ device_dict.get('password') or \ device_dict.get('pass') or \ '' network_device['TIMEOUT'] = device_dict.get('timeout', 60) network_device['OPTIONAL_ARGS'] = device_dict.get('optional_args', {}) network_device['ALWAYS_ALIVE'] = device_dict.get('always_alive', True) network_device['PROVIDER'] = device_dict.get('provider') network_device['UP'] = False # get driver object form NAPALM if 'config_lock' not in network_device['OPTIONAL_ARGS']: network_device['OPTIONAL_ARGS']['config_lock'] = False if network_device['ALWAYS_ALIVE'] and 'keepalive' not in network_device['OPTIONAL_ARGS']: network_device['OPTIONAL_ARGS']['keepalive'] = 5 # 5 seconds keepalive return network_device def get_device(opts, salt_obj=None): ''' Initialise the connection with the network device through NAPALM. :param: opts :return: the network device object ''' log.debug('Setting up NAPALM connection') network_device = get_device_opts(opts, salt_obj=salt_obj) provider_lib = napalm_base if network_device.get('PROVIDER'): # In case the user requires a different provider library, # other than napalm-base. # For example, if napalm-base does not satisfy the requirements # and needs to be enahanced with more specific features, # we may need to define a custom library on top of napalm-base # with the constraint that it still needs to provide the # `get_network_driver` function. However, even this can be # extended later, if really needed. # Configuration example: # provider: napalm_base_example try: provider_lib = importlib.import_module(network_device.get('PROVIDER')) except ImportError as ierr: log.error('Unable to import %s', network_device.get('PROVIDER'), exc_info=True) log.error('Falling back to napalm-base') _driver_ = provider_lib.get_network_driver(network_device.get('DRIVER_NAME')) try: network_device['DRIVER'] = _driver_( network_device.get('HOSTNAME', ''), network_device.get('USERNAME', ''), network_device.get('PASSWORD', ''), timeout=network_device['TIMEOUT'], optional_args=network_device['OPTIONAL_ARGS'] ) network_device.get('DRIVER').open() # no exception raised here, means connection established network_device['UP'] = True except napalm_base.exceptions.ConnectionException as error: base_err_msg = "Cannot connect to {hostname}{port} as {username}.".format( hostname=network_device.get('HOSTNAME', '[unspecified hostname]'), port=(':{port}'.format(port=network_device.get('OPTIONAL_ARGS', {}).get('port')) if network_device.get('OPTIONAL_ARGS', {}).get('port') else ''), username=network_device.get('USERNAME', '') ) log.error(base_err_msg) log.error( "Please check error: %s", error ) raise napalm_base.exceptions.ConnectionException(base_err_msg) return network_device def proxy_napalm_wrap(func): ''' This decorator is used to make the execution module functions available outside a proxy minion, or when running inside a proxy minion. If we are running in a proxy, retrieve the connection details from the __proxy__ injected variable. If we are not, then use the connection information from the opts. :param func: :return: ''' @wraps(func) def func_wrapper(*args, **kwargs): wrapped_global_namespace = func.__globals__ # get __opts__ and __proxy__ from func_globals proxy = wrapped_global_namespace.get('__proxy__') opts = copy.deepcopy(wrapped_global_namespace.get('__opts__')) # in any case, will inject the `napalm_device` global # the execution modules will make use of this variable from now on # previously they were accessing the device properties through the __proxy__ object always_alive = opts.get('proxy', {}).get('always_alive', True) # force_reconnect is a magic keyword arg that allows one to establish # a separate connection to the network device running under an always # alive Proxy Minion, using new credentials (overriding the ones # configured in the opts / pillar. force_reconnect = kwargs.get('force_reconnect', False) if force_reconnect: log.debug('Usage of reconnect force detected') log.debug('Opts before merging') log.debug(opts['proxy']) opts['proxy'].update(**kwargs) log.debug('Opts after merging') log.debug(opts['proxy']) if is_proxy(opts) and always_alive: # if it is running in a NAPALM Proxy and it's using the default # always alive behaviour, will get the cached copy of the network # device object which should preserve the connection. if force_reconnect: wrapped_global_namespace['napalm_device'] = get_device(opts) else: wrapped_global_namespace['napalm_device'] = proxy['napalm.get_device']() elif is_proxy(opts) and not always_alive: # if still proxy, but the user does not want the SSH session always alive # get a new device instance # which establishes a new connection # which is closed just before the call() function defined above returns if 'inherit_napalm_device' not in kwargs or ('inherit_napalm_device' in kwargs and not kwargs['inherit_napalm_device']): # try to open a new connection # but only if the function does not inherit the napalm driver # for configuration management this is very important, # in order to make sure we are editing the same session. try: wrapped_global_namespace['napalm_device'] = get_device(opts) except napalm_base.exceptions.ConnectionException as nce: log.error(nce) return '{base_msg}. See log for details.'.format( base_msg=six.text_type(nce.msg) ) else: # in case the `inherit_napalm_device` is set # and it also has a non-empty value, # the global var `napalm_device` will be overridden. # this is extremely important for configuration-related features # as all actions must be issued within the same configuration session # otherwise we risk to open multiple sessions wrapped_global_namespace['napalm_device'] = kwargs['inherit_napalm_device'] else: # if not a NAPLAM proxy # thus it is running on a regular minion, directly on the network device # or another flavour of Minion from where we can invoke arbitrary # NAPALM commands # get __salt__ from func_globals log.debug('Not running in a NAPALM Proxy Minion') _salt_obj = wrapped_global_namespace.get('__salt__') napalm_opts = _salt_obj['config.get']('napalm', {}) napalm_inventory = _salt_obj['config.get']('napalm_inventory', {}) log.debug('NAPALM opts found in the Minion config') log.debug(napalm_opts) clean_kwargs = salt.utils.args.clean_kwargs(**kwargs) napalm_opts.update(clean_kwargs) # no need for deeper merge log.debug('Merging the found opts with the CLI args') log.debug(napalm_opts) host = napalm_opts.get('host') or napalm_opts.get('hostname') or\ napalm_opts.get('fqdn') or napalm_opts.get('ip') if host and napalm_inventory and isinstance(napalm_inventory, dict) and\ host in napalm_inventory: inventory_opts = napalm_inventory[host] log.debug('Found %s in the NAPALM inventory:', host) log.debug(inventory_opts) napalm_opts.update(inventory_opts) log.debug('Merging the config for %s with the details found in the napalm inventory:', host) log.debug(napalm_opts) opts = copy.deepcopy(opts) # make sure we don't override the original # opts, but just inject the CLI args from the kwargs to into the # object manipulated by ``get_device_opts`` to extract the # connection details, then use then to establish the connection. opts['napalm'] = napalm_opts if 'inherit_napalm_device' not in kwargs or ('inherit_napalm_device' in kwargs and not kwargs['inherit_napalm_device']): # try to open a new connection # but only if the function does not inherit the napalm driver # for configuration management this is very important, # in order to make sure we are editing the same session. try: wrapped_global_namespace['napalm_device'] = get_device(opts, salt_obj=_salt_obj) except napalm_base.exceptions.ConnectionException as nce: log.error(nce) return '{base_msg}. See log for details.'.format( base_msg=six.text_type(nce.msg) ) else: # in case the `inherit_napalm_device` is set # and it also has a non-empty value, # the global var `napalm_device` will be overridden. # this is extremely important for configuration-related features # as all actions must be issued within the same configuration session # otherwise we risk to open multiple sessions wrapped_global_namespace['napalm_device'] = kwargs['inherit_napalm_device'] if not_always_alive(opts): # inject the __opts__ only when not always alive # otherwise, we don't want to overload the always-alive proxies wrapped_global_namespace['napalm_device']['__opts__'] = opts ret = func(*args, **kwargs) if force_reconnect: log.debug('That was a forced reconnect, gracefully clearing up') device = wrapped_global_namespace['napalm_device'] closing = call(device, 'close', __retry=False) return ret return func_wrapper def default_ret(name): ''' Return the default dict of the state output. ''' ret = { 'name': name, 'changes': {}, 'result': False, 'comment': '' } return ret
saltstack/salt
salt/engines/webhook.py
start
python
def start(address=None, port=5000, ssl_crt=None, ssl_key=None): ''' Api to listen for webhooks to send to the reactor. Implement the webhook behavior in an engine. :py:class:`rest_cherrypy Webhook docs <salt.netapi.rest_cherrypy.app.Webhook>` Unlike the rest_cherrypy Webhook, this is only an unauthenticated webhook endpoint. If an authenticated webhook endpoint is needed, use the salt-api webhook which runs on the master and authenticates through eauth. .. note: This is really meant to be used on the minion, because salt-api needs to be run on the master for use with eauth. .. warning:: Unauthenticated endpoint This engine sends webhook calls to the event stream. If the engine is running on a minion with `file_client: local` the event is sent to the minion event stream. Otherwise it is sent to the master event stream. Example Config .. code-block:: yaml engines: - webhook: {} .. code-block:: yaml engines: - webhook: port: 8000 address: 10.128.1.145 ssl_crt: /etc/pki/tls/certs/localhost.crt ssl_key: /etc/pki/tls/certs/localhost.key .. note: For making an unsigned key, use the following command `salt-call --local tls.create_self_signed_cert` ''' if __opts__.get('__role') == 'master': fire_master = salt.utils.event.get_master_event(__opts__, __opts__['sock_dir']).fire_event else: fire_master = None def fire(tag, msg): ''' How to fire the event ''' if fire_master: fire_master(msg, tag) else: __salt__['event.send'](tag, msg) class WebHook(tornado.web.RequestHandler): # pylint: disable=abstract-method def post(self, tag): # pylint: disable=arguments-differ body = self.request.body headers = self.request.headers payload = { 'headers': headers if isinstance(headers, dict) else dict(headers), 'body': salt.utils.stringutils.to_str(body), } fire('salt/engines/hook/' + tag, payload) application = tornado.web.Application([(r"/(.*)", WebHook), ]) ssl_options = None if all([ssl_crt, ssl_key]): ssl_options = {"certfile": ssl_crt, "keyfile": ssl_key} io_loop = tornado.ioloop.IOLoop(make_current=False) io_loop.make_current() http_server = tornado.httpserver.HTTPServer(application, ssl_options=ssl_options) http_server.listen(port, address=address) io_loop.start()
Api to listen for webhooks to send to the reactor. Implement the webhook behavior in an engine. :py:class:`rest_cherrypy Webhook docs <salt.netapi.rest_cherrypy.app.Webhook>` Unlike the rest_cherrypy Webhook, this is only an unauthenticated webhook endpoint. If an authenticated webhook endpoint is needed, use the salt-api webhook which runs on the master and authenticates through eauth. .. note: This is really meant to be used on the minion, because salt-api needs to be run on the master for use with eauth. .. warning:: Unauthenticated endpoint This engine sends webhook calls to the event stream. If the engine is running on a minion with `file_client: local` the event is sent to the minion event stream. Otherwise it is sent to the master event stream. Example Config .. code-block:: yaml engines: - webhook: {} .. code-block:: yaml engines: - webhook: port: 8000 address: 10.128.1.145 ssl_crt: /etc/pki/tls/certs/localhost.crt ssl_key: /etc/pki/tls/certs/localhost.key .. note: For making an unsigned key, use the following command `salt-call --local tls.create_self_signed_cert`
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/engines/webhook.py#L17-L88
[ "def get_master_event(opts, sock_dir, listen=True, io_loop=None, raise_errors=False, keep_loop=False):\n '''\n Return an event object suitable for the named transport\n '''\n # TODO: AIO core is separate from transport\n if opts['transport'] in ('zeromq', 'tcp', 'detect'):\n return MasterEvent(sock_dir, opts, listen=listen, io_loop=io_loop, raise_errors=raise_errors, keep_loop=keep_loop)\n" ]
# -*- coding: utf-8 -*- ''' Send events from webhook api ''' from __future__ import absolute_import, print_function, unicode_literals # import tornado library import tornado.httpserver import tornado.ioloop import tornado.web # import salt libs import salt.utils.event import salt.utils.stringutils
saltstack/salt
salt/states/win_wua.py
installed
python
def installed(name, updates=None): ''' Ensure Microsoft Updates are installed. Updates will be downloaded if needed. Args: name (str): The identifier of a single update to install. updates (list): A list of identifiers for updates to be installed. Overrides ``name``. Default is None. .. note:: Identifiers can be the GUID, the KB number, or any part of the Title of the Microsoft update. GUIDs and KBs are the preferred method to ensure you're installing the correct update. .. warning:: Using a partial KB number or a partial Title could result in more than one update being installed. Returns: dict: A dictionary containing the results of the update CLI Example: .. code-block:: yaml # using a GUID install_update: wua.installed: - name: 28cf1b09-2b1a-458c-9bd1-971d1b26b211 # using a KB install_update: wua.installed: - name: KB3194343 # using the full Title install_update: wua.installed: - name: Security Update for Adobe Flash Player for Windows 10 Version 1607 (for x64-based Systems) (KB3194343) # Install multiple updates install_updates: wua.installed: - updates: - KB3194343 - 28cf1b09-2b1a-458c-9bd1-971d1b26b211 ''' if isinstance(updates, six.string_types): updates = [updates] if not updates: updates = name ret = {'name': name, 'changes': {}, 'result': True, 'comment': ''} wua = salt.utils.win_update.WindowsUpdateAgent() # Search for updates install_list = wua.search(updates) # No updates found if install_list.count() == 0: ret['comment'] = 'No updates found' return ret # List of updates to download download = salt.utils.win_update.Updates() for item in install_list.updates: if not salt.utils.data.is_true(item.IsDownloaded): download.updates.Add(item) # List of updates to install install = salt.utils.win_update.Updates() installed_updates = [] for item in install_list.updates: if not salt.utils.data.is_true(item.IsInstalled): install.updates.Add(item) else: installed_updates.extend('KB' + kb for kb in item.KBArticleIDs) if install.count() == 0: ret['comment'] = 'Updates already installed: ' ret['comment'] += '\n - '.join(installed_updates) return ret # Return comment of changes if test. if __opts__['test']: ret['result'] = None ret['comment'] = 'Updates will be installed:' for update in install.updates: ret['comment'] += '\n' ret['comment'] += ': '.join( [update.Identity.UpdateID, update.Title]) return ret # Download updates wua.download(download) # Install updates wua.install(install) # Refresh windows update info wua.refresh() post_info = wua.updates().list() # Verify the installation for item in install.list(): if not salt.utils.data.is_true(post_info[item]['Installed']): ret['changes']['failed'] = { item: {'Title': post_info[item]['Title'][:40] + '...', 'KBs': post_info[item]['KBs']} } ret['result'] = False else: ret['changes']['installed'] = { item: {'Title': post_info[item]['Title'][:40] + '...', 'NeedsReboot': post_info[item]['NeedsReboot'], 'KBs': post_info[item]['KBs']} } if ret['changes'].get('failed', False): ret['comment'] = 'Updates failed' else: ret['comment'] = 'Updates installed successfully' return ret
Ensure Microsoft Updates are installed. Updates will be downloaded if needed. Args: name (str): The identifier of a single update to install. updates (list): A list of identifiers for updates to be installed. Overrides ``name``. Default is None. .. note:: Identifiers can be the GUID, the KB number, or any part of the Title of the Microsoft update. GUIDs and KBs are the preferred method to ensure you're installing the correct update. .. warning:: Using a partial KB number or a partial Title could result in more than one update being installed. Returns: dict: A dictionary containing the results of the update CLI Example: .. code-block:: yaml # using a GUID install_update: wua.installed: - name: 28cf1b09-2b1a-458c-9bd1-971d1b26b211 # using a KB install_update: wua.installed: - name: KB3194343 # using the full Title install_update: wua.installed: - name: Security Update for Adobe Flash Player for Windows 10 Version 1607 (for x64-based Systems) (KB3194343) # Install multiple updates install_updates: wua.installed: - updates: - KB3194343 - 28cf1b09-2b1a-458c-9bd1-971d1b26b211
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/win_wua.py#L80-L211
[ "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 count(self):\n '''\n Return how many records are in the Microsoft Update Collection\n\n Returns:\n int: The number of updates in the collection\n\n Code Example:\n\n .. code-block:: python\n\n import salt.utils.win_update\n updates = salt.utils.win_update.Updates()\n updates.count()\n '''\n return self.updates.Count\n", "def updates(self):\n '''\n Get the contents of ``_updates`` (all updates) and puts them in an\n Updates class to expose the list and summary functions.\n\n Returns:\n Updates: An instance of the Updates class with all updates for the\n system.\n\n .. code-block:: python\n\n import salt.utils.win_update\n wua = salt.utils.win_update.WindowsUpdateAgent()\n updates = wua.updates()\n\n # To get a list\n updates.list()\n\n # To get a summary\n updates.summary()\n '''\n updates = Updates()\n found = updates.updates\n\n for update in self._updates:\n found.Add(update)\n\n return updates\n", "def refresh(self):\n '''\n Refresh the contents of the ``_updates`` collection. This gets all\n updates in the Windows Update system and loads them into the collection.\n This is the part that is slow.\n\n Code Example:\n\n .. code-block:: python\n\n import salt.utils.win_update\n wua = salt.utils.win_update.WindowsUpdateAgent()\n wua.refresh()\n '''\n # https://msdn.microsoft.com/en-us/library/windows/desktop/aa386526(v=vs.85).aspx\n search_string = 'Type=\\'Software\\' or ' \\\n 'Type=\\'Driver\\''\n\n # Create searcher object\n searcher = self._session.CreateUpdateSearcher()\n self._session.ClientApplicationID = 'Salt: Load Updates'\n\n # Load all updates into the updates collection\n try:\n results = searcher.Search(search_string)\n if results.Updates.Count == 0:\n log.debug('No Updates found for:\\n\\t\\t%s', search_string)\n return 'No Updates found: {0}'.format(search_string)\n except pywintypes.com_error as error:\n # Something happened, raise an error\n hr, msg, exc, arg = error.args # pylint: disable=W0633\n try:\n failure_code = self.fail_codes[exc[5]]\n except KeyError:\n failure_code = 'Unknown Failure: {0}'.format(error)\n\n log.error('Search Failed: %s\\n\\t\\t%s', failure_code, search_string)\n raise CommandExecutionError(failure_code)\n\n self._updates = results.Updates\n", "def search(self, search_string):\n '''\n Search for either a single update or a specific list of updates. GUIDs\n are searched first, then KB numbers, and finally Titles.\n\n Args:\n\n search_string (str, list): The search string to use to find the\n update. This can be the GUID or KB of the update (preferred). It can\n also be the full Title of the update or any part of the Title. A\n partial Title search is less specific and can return multiple\n results.\n\n Returns:\n Updates: An instance of Updates with the results of the search\n\n Code Example:\n\n .. code-block:: python\n\n import salt.utils.win_update\n wua = salt.utils.win_update.WindowsUpdateAgent()\n\n # search for a single update and show its details\n updates = wua.search('KB3194343')\n updates.list()\n\n # search for a list of updates and show their details\n updates = wua.search(['KB3195432', '12345678-abcd-1234-abcd-1234567890ab'])\n updates.list()\n '''\n updates = Updates()\n found = updates.updates\n\n if isinstance(search_string, six.string_types):\n search_string = [search_string]\n\n if isinstance(search_string, six.integer_types):\n search_string = [six.text_type(search_string)]\n\n for update in self._updates:\n\n for find in search_string:\n\n # Search by GUID\n if find == update.Identity.UpdateID:\n found.Add(update)\n continue\n\n # Search by KB\n if find in ['KB' + item for item in update.KBArticleIDs]:\n found.Add(update)\n continue\n\n # Search by KB without the KB in front\n if find in [item for item in update.KBArticleIDs]:\n found.Add(update)\n continue\n\n # Search by Title\n if find in update.Title:\n found.Add(update)\n continue\n\n return updates\n", "def download(self, updates):\n '''\n Download the updates passed in the updates collection. Load the updates\n collection using ``search`` or ``available``\n\n Args:\n\n updates (Updates): An instance of the Updates class containing a\n the updates to be downloaded.\n\n Returns:\n dict: A dictionary containing the results of the download\n\n Code Example:\n\n .. code-block:: python\n\n import salt.utils.win_update\n wua = salt.utils.win_update.WindowsUpdateAgent()\n\n # Download KB3195454\n updates = wua.search('KB3195454')\n results = wua.download(updates)\n '''\n\n # Check for empty list\n if updates.count() == 0:\n ret = {'Success': False,\n 'Updates': 'Nothing to download'}\n return ret\n\n # Initialize the downloader object and list collection\n downloader = self._session.CreateUpdateDownloader()\n self._session.ClientApplicationID = 'Salt: Download Update'\n with salt.utils.winapi.Com():\n download_list = win32com.client.Dispatch('Microsoft.Update.UpdateColl')\n\n ret = {'Updates': {}}\n\n # Check for updates that aren't already downloaded\n for update in updates.updates:\n\n # Define uid to keep the lines shorter\n uid = update.Identity.UpdateID\n ret['Updates'][uid] = {}\n ret['Updates'][uid]['Title'] = update.Title\n ret['Updates'][uid]['AlreadyDownloaded'] = \\\n bool(update.IsDownloaded)\n\n # Accept EULA\n if not salt.utils.data.is_true(update.EulaAccepted):\n log.debug('Accepting EULA: %s', update.Title)\n update.AcceptEula() # pylint: disable=W0104\n\n # Update already downloaded\n if not salt.utils.data.is_true(update.IsDownloaded):\n log.debug('To Be Downloaded: %s', uid)\n log.debug('\\tTitle: %s', update.Title)\n download_list.Add(update)\n\n # Check the download list\n if download_list.Count == 0:\n ret = {'Success': True,\n 'Updates': 'Nothing to download'}\n return ret\n\n # Send the list to the downloader\n downloader.Updates = download_list\n\n # Download the list\n try:\n log.debug('Downloading Updates')\n result = downloader.Download()\n except pywintypes.com_error as error:\n # Something happened, raise an error\n hr, msg, exc, arg = error.args # pylint: disable=W0633\n try:\n failure_code = self.fail_codes[exc[5]]\n except KeyError:\n failure_code = 'Unknown Failure: {0}'.format(error)\n\n log.error('Download Failed: %s', failure_code)\n raise CommandExecutionError(failure_code)\n\n # Lookup dictionary\n result_code = {0: 'Download Not Started',\n 1: 'Download In Progress',\n 2: 'Download Succeeded',\n 3: 'Download Succeeded With Errors',\n 4: 'Download Failed',\n 5: 'Download Aborted'}\n\n log.debug('Download Complete')\n log.debug(result_code[result.ResultCode])\n ret['Message'] = result_code[result.ResultCode]\n\n # Was the download successful?\n if result.ResultCode in [2, 3]:\n log.debug('Downloaded Successfully')\n ret['Success'] = True\n else:\n log.debug('Download Failed')\n ret['Success'] = False\n\n # Report results for each update\n for i in range(download_list.Count):\n uid = download_list.Item(i).Identity.UpdateID\n ret['Updates'][uid]['Result'] = \\\n result_code[result.GetUpdateResult(i).ResultCode]\n\n return ret\n", "def install(self, updates):\n '''\n Install the updates passed in the updates collection. Load the updates\n collection using the ``search`` or ``available`` functions. If the\n updates need to be downloaded, use the ``download`` function.\n\n Args:\n\n updates (Updates): An instance of the Updates class containing a\n the updates to be installed.\n\n Returns:\n dict: A dictionary containing the results of the installation\n\n Code Example:\n\n .. code-block:: python\n\n import salt.utils.win_update\n wua = salt.utils.win_update.WindowsUpdateAgent()\n\n # install KB3195454\n updates = wua.search('KB3195454')\n results = wua.download(updates)\n results = wua.install(updates)\n '''\n # Check for empty list\n if updates.count() == 0:\n ret = {'Success': False,\n 'Updates': 'Nothing to install'}\n return ret\n\n installer = self._session.CreateUpdateInstaller()\n self._session.ClientApplicationID = 'Salt: Install Update'\n with salt.utils.winapi.Com():\n install_list = win32com.client.Dispatch('Microsoft.Update.UpdateColl')\n\n ret = {'Updates': {}}\n\n # Check for updates that aren't already installed\n for update in updates.updates:\n\n # Define uid to keep the lines shorter\n uid = update.Identity.UpdateID\n ret['Updates'][uid] = {}\n ret['Updates'][uid]['Title'] = update.Title\n ret['Updates'][uid]['AlreadyInstalled'] = bool(update.IsInstalled)\n\n # Make sure the update has actually been installed\n if not salt.utils.data.is_true(update.IsInstalled):\n log.debug('To Be Installed: %s', uid)\n log.debug('\\tTitle: %s', update.Title)\n install_list.Add(update)\n\n # Check the install list\n if install_list.Count == 0:\n ret = {'Success': True,\n 'Updates': 'Nothing to install'}\n return ret\n\n # Send the list to the installer\n installer.Updates = install_list\n\n # Install the list\n try:\n log.debug('Installing Updates')\n result = installer.Install()\n\n except pywintypes.com_error as error:\n # Something happened, raise an error\n hr, msg, exc, arg = error.args # pylint: disable=W0633\n try:\n failure_code = self.fail_codes[exc[5]]\n except KeyError:\n failure_code = 'Unknown Failure: {0}'.format(error)\n\n log.error('Install Failed: %s', failure_code)\n raise CommandExecutionError(failure_code)\n\n # Lookup dictionary\n result_code = {0: 'Installation Not Started',\n 1: 'Installation In Progress',\n 2: 'Installation Succeeded',\n 3: 'Installation Succeeded With Errors',\n 4: 'Installation Failed',\n 5: 'Installation Aborted'}\n\n log.debug('Install Complete')\n log.debug(result_code[result.ResultCode])\n ret['Message'] = result_code[result.ResultCode]\n\n if result.ResultCode in [2, 3]:\n ret['Success'] = True\n ret['NeedsReboot'] = result.RebootRequired\n log.debug('NeedsReboot: %s', result.RebootRequired)\n else:\n log.debug('Install Failed')\n ret['Success'] = False\n\n reboot = {0: 'Never Reboot',\n 1: 'Always Reboot',\n 2: 'Poss Reboot'}\n for i in range(install_list.Count):\n uid = install_list.Item(i).Identity.UpdateID\n ret['Updates'][uid]['Result'] = \\\n result_code[result.GetUpdateResult(i).ResultCode]\n ret['Updates'][uid]['RebootBehavior'] = \\\n reboot[install_list.Item(i).InstallationBehavior.RebootBehavior]\n\n return ret\n" ]
# -*- coding: utf-8 -*- ''' Installation of Windows Updates using the Windows Update Agent .. versionadded:: 2017.7.0 Salt can manage Windows updates via the "wua" state module. Updates can be installed and removed. Update management declarations are as follows: For installation: .. code-block:: yaml # Install a single update using the KB KB3194343: wua.installed # Install a single update using the name parameter install_update: wua.installed: - name: KB3194343 # Install multiple updates using the updates parameter and a combination of # KB number and GUID install_updates: wua.installed: - updates: - KB3194343 - bb1dbb26-3fb6-45fd-bb05-e3c8e379195c For removal: .. code-block:: yaml # Remove a single update using the KB KB3194343: wua.removed # Remove a single update using the name parameter remove_update: wua.removed: - name: KB3194343 # Remove multiple updates using the updates parameter and a combination of # KB number and GUID remove_updates: wua.removed: - updates: - KB3194343 - bb1dbb26-3fb6-45fd-bb05-e3c8e379195c ''' # Import Python libs from __future__ import absolute_import, unicode_literals, print_function import logging # Import Salt libs from salt.ext import six import salt.utils.data import salt.utils.platform import salt.utils.win_update log = logging.getLogger(__name__) __virtualname__ = 'wua' def __virtual__(): ''' Only valid on Windows machines ''' if not salt.utils.platform.is_windows(): return False, 'WUA: Only available on Window systems' if not salt.utils.win_update.HAS_PYWIN32: return False, 'WUA: Requires PyWin32 libraries' return __virtualname__ def removed(name, updates=None): ''' Ensure Microsoft Updates are uninstalled. Args: name (str): The identifier of a single update to uninstall. updates (list): A list of identifiers for updates to be removed. Overrides ``name``. Default is None. .. note:: Identifiers can be the GUID, the KB number, or any part of the Title of the Microsoft update. GUIDs and KBs are the preferred method to ensure you're uninstalling the correct update. .. warning:: Using a partial KB number or a partial Title could result in more than one update being removed. Returns: dict: A dictionary containing the results of the removal CLI Example: .. code-block:: yaml # using a GUID uninstall_update: wua.removed: - name: 28cf1b09-2b1a-458c-9bd1-971d1b26b211 # using a KB uninstall_update: wua.removed: - name: KB3194343 # using the full Title uninstall_update: wua.removed: - name: Security Update for Adobe Flash Player for Windows 10 Version 1607 (for x64-based Systems) (KB3194343) # Install multiple updates uninstall_updates: wua.removed: - updates: - KB3194343 - 28cf1b09-2b1a-458c-9bd1-971d1b26b211 ''' if isinstance(updates, six.string_types): updates = [updates] if not updates: updates = name ret = {'name': name, 'changes': {}, 'result': True, 'comment': ''} wua = salt.utils.win_update.WindowsUpdateAgent() # Search for updates updates = wua.search(updates) # No updates found if updates.count() == 0: ret['comment'] = 'No updates found' return ret # List of updates to uninstall uninstall = salt.utils.win_update.Updates() removed_updates = [] for item in updates.updates: if salt.utils.data.is_true(item.IsInstalled): uninstall.updates.Add(item) else: removed_updates.extend('KB' + kb for kb in item.KBArticleIDs) if uninstall.count() == 0: ret['comment'] = 'Updates already removed: ' ret['comment'] += '\n - '.join(removed_updates) return ret # Return comment of changes if test. if __opts__['test']: ret['result'] = None ret['comment'] = 'Updates will be removed:' for update in uninstall.updates: ret['comment'] += '\n' ret['comment'] += ': '.join( [update.Identity.UpdateID, update.Title]) return ret # Install updates wua.uninstall(uninstall) # Refresh windows update info wua.refresh() post_info = wua.updates().list() # Verify the installation for item in uninstall.list(): if salt.utils.data.is_true(post_info[item]['Installed']): ret['changes']['failed'] = { item: {'Title': post_info[item]['Title'][:40] + '...', 'KBs': post_info[item]['KBs']} } ret['result'] = False else: ret['changes']['removed'] = { item: {'Title': post_info[item]['Title'][:40] + '...', 'NeedsReboot': post_info[item]['NeedsReboot'], 'KBs': post_info[item]['KBs']} } if ret['changes'].get('failed', False): ret['comment'] = 'Updates failed' else: ret['comment'] = 'Updates removed successfully' return ret def uptodate(name, software=True, drivers=False, skip_hidden=False, skip_mandatory=False, skip_reboot=True, categories=None, severities=None,): ''' Ensure Microsoft Updates that match the passed criteria are installed. Updates will be downloaded if needed. This state allows you to update a system without specifying a specific update to apply. All matching updates will be installed. Args: name (str): The name has no functional value and is only used as a tracking reference software (bool): Include software updates in the results (default is True) drivers (bool): Include driver updates in the results (default is False) skip_hidden (bool): Skip updates that have been hidden. Default is False. skip_mandatory (bool): Skip mandatory updates. Default is False. skip_reboot (bool): Skip updates that require a reboot. Default is True. categories (list): Specify the categories to list. Must be passed as a list. All categories returned by default. Categories include the following: * Critical Updates * Definition Updates * Drivers (make sure you set drivers=True) * Feature Packs * Security Updates * Update Rollups * Updates * Update Rollups * Windows 7 * Windows 8.1 * Windows 8.1 drivers * Windows 8.1 and later drivers * Windows Defender severities (list): Specify the severities to include. Must be passed as a list. All severities returned by default. Severities include the following: * Critical * Important Returns: dict: A dictionary containing the results of the update CLI Example: .. code-block:: yaml # Update the system using the state defaults update_system: wua.uptodate # Update the drivers update_drivers: wua.uptodate: - software: False - drivers: True - skip_reboot: False # Apply all critical updates update_critical: wua.uptodate: - severities: - Critical ''' ret = {'name': name, 'changes': {}, 'result': True, 'comment': ''} wua = salt.utils.win_update.WindowsUpdateAgent() available_updates = wua.available( skip_hidden=skip_hidden, skip_installed=True, skip_mandatory=skip_mandatory, skip_reboot=skip_reboot, software=software, drivers=drivers, categories=categories, severities=severities) # No updates found if available_updates.count() == 0: ret['comment'] = 'No updates found' return ret updates = list(available_updates.list().keys()) # Search for updates install_list = wua.search(updates) # List of updates to download download = salt.utils.win_update.Updates() for item in install_list.updates: if not salt.utils.data.is_true(item.IsDownloaded): download.updates.Add(item) # List of updates to install install = salt.utils.win_update.Updates() for item in install_list.updates: if not salt.utils.data.is_true(item.IsInstalled): install.updates.Add(item) # Return comment of changes if test. if __opts__['test']: ret['result'] = None ret['comment'] = 'Updates will be installed:' for update in install.updates: ret['comment'] += '\n' ret['comment'] += ': '.join( [update.Identity.UpdateID, update.Title]) return ret # Download updates wua.download(download) # Install updates wua.install(install) # Refresh windows update info wua.refresh() post_info = wua.updates().list() # Verify the installation for item in install.list(): if not salt.utils.data.is_true(post_info[item]['Installed']): ret['changes']['failed'] = { item: {'Title': post_info[item]['Title'][:40] + '...', 'KBs': post_info[item]['KBs']} } ret['result'] = False else: ret['changes']['installed'] = { item: {'Title': post_info[item]['Title'][:40] + '...', 'NeedsReboot': post_info[item]['NeedsReboot'], 'KBs': post_info[item]['KBs']} } if ret['changes'].get('failed', False): ret['comment'] = 'Updates failed' else: ret['comment'] = 'Updates installed successfully' return ret
saltstack/salt
salt/states/win_wua.py
removed
python
def removed(name, updates=None): ''' Ensure Microsoft Updates are uninstalled. Args: name (str): The identifier of a single update to uninstall. updates (list): A list of identifiers for updates to be removed. Overrides ``name``. Default is None. .. note:: Identifiers can be the GUID, the KB number, or any part of the Title of the Microsoft update. GUIDs and KBs are the preferred method to ensure you're uninstalling the correct update. .. warning:: Using a partial KB number or a partial Title could result in more than one update being removed. Returns: dict: A dictionary containing the results of the removal CLI Example: .. code-block:: yaml # using a GUID uninstall_update: wua.removed: - name: 28cf1b09-2b1a-458c-9bd1-971d1b26b211 # using a KB uninstall_update: wua.removed: - name: KB3194343 # using the full Title uninstall_update: wua.removed: - name: Security Update for Adobe Flash Player for Windows 10 Version 1607 (for x64-based Systems) (KB3194343) # Install multiple updates uninstall_updates: wua.removed: - updates: - KB3194343 - 28cf1b09-2b1a-458c-9bd1-971d1b26b211 ''' if isinstance(updates, six.string_types): updates = [updates] if not updates: updates = name ret = {'name': name, 'changes': {}, 'result': True, 'comment': ''} wua = salt.utils.win_update.WindowsUpdateAgent() # Search for updates updates = wua.search(updates) # No updates found if updates.count() == 0: ret['comment'] = 'No updates found' return ret # List of updates to uninstall uninstall = salt.utils.win_update.Updates() removed_updates = [] for item in updates.updates: if salt.utils.data.is_true(item.IsInstalled): uninstall.updates.Add(item) else: removed_updates.extend('KB' + kb for kb in item.KBArticleIDs) if uninstall.count() == 0: ret['comment'] = 'Updates already removed: ' ret['comment'] += '\n - '.join(removed_updates) return ret # Return comment of changes if test. if __opts__['test']: ret['result'] = None ret['comment'] = 'Updates will be removed:' for update in uninstall.updates: ret['comment'] += '\n' ret['comment'] += ': '.join( [update.Identity.UpdateID, update.Title]) return ret # Install updates wua.uninstall(uninstall) # Refresh windows update info wua.refresh() post_info = wua.updates().list() # Verify the installation for item in uninstall.list(): if salt.utils.data.is_true(post_info[item]['Installed']): ret['changes']['failed'] = { item: {'Title': post_info[item]['Title'][:40] + '...', 'KBs': post_info[item]['KBs']} } ret['result'] = False else: ret['changes']['removed'] = { item: {'Title': post_info[item]['Title'][:40] + '...', 'NeedsReboot': post_info[item]['NeedsReboot'], 'KBs': post_info[item]['KBs']} } if ret['changes'].get('failed', False): ret['comment'] = 'Updates failed' else: ret['comment'] = 'Updates removed successfully' return ret
Ensure Microsoft Updates are uninstalled. Args: name (str): The identifier of a single update to uninstall. updates (list): A list of identifiers for updates to be removed. Overrides ``name``. Default is None. .. note:: Identifiers can be the GUID, the KB number, or any part of the Title of the Microsoft update. GUIDs and KBs are the preferred method to ensure you're uninstalling the correct update. .. warning:: Using a partial KB number or a partial Title could result in more than one update being removed. Returns: dict: A dictionary containing the results of the removal CLI Example: .. code-block:: yaml # using a GUID uninstall_update: wua.removed: - name: 28cf1b09-2b1a-458c-9bd1-971d1b26b211 # using a KB uninstall_update: wua.removed: - name: KB3194343 # using the full Title uninstall_update: wua.removed: - name: Security Update for Adobe Flash Player for Windows 10 Version 1607 (for x64-based Systems) (KB3194343) # Install multiple updates uninstall_updates: wua.removed: - updates: - KB3194343 - 28cf1b09-2b1a-458c-9bd1-971d1b26b211
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/win_wua.py#L214-L335
[ "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 count(self):\n '''\n Return how many records are in the Microsoft Update Collection\n\n Returns:\n int: The number of updates in the collection\n\n Code Example:\n\n .. code-block:: python\n\n import salt.utils.win_update\n updates = salt.utils.win_update.Updates()\n updates.count()\n '''\n return self.updates.Count\n", "def updates(self):\n '''\n Get the contents of ``_updates`` (all updates) and puts them in an\n Updates class to expose the list and summary functions.\n\n Returns:\n Updates: An instance of the Updates class with all updates for the\n system.\n\n .. code-block:: python\n\n import salt.utils.win_update\n wua = salt.utils.win_update.WindowsUpdateAgent()\n updates = wua.updates()\n\n # To get a list\n updates.list()\n\n # To get a summary\n updates.summary()\n '''\n updates = Updates()\n found = updates.updates\n\n for update in self._updates:\n found.Add(update)\n\n return updates\n", "def refresh(self):\n '''\n Refresh the contents of the ``_updates`` collection. This gets all\n updates in the Windows Update system and loads them into the collection.\n This is the part that is slow.\n\n Code Example:\n\n .. code-block:: python\n\n import salt.utils.win_update\n wua = salt.utils.win_update.WindowsUpdateAgent()\n wua.refresh()\n '''\n # https://msdn.microsoft.com/en-us/library/windows/desktop/aa386526(v=vs.85).aspx\n search_string = 'Type=\\'Software\\' or ' \\\n 'Type=\\'Driver\\''\n\n # Create searcher object\n searcher = self._session.CreateUpdateSearcher()\n self._session.ClientApplicationID = 'Salt: Load Updates'\n\n # Load all updates into the updates collection\n try:\n results = searcher.Search(search_string)\n if results.Updates.Count == 0:\n log.debug('No Updates found for:\\n\\t\\t%s', search_string)\n return 'No Updates found: {0}'.format(search_string)\n except pywintypes.com_error as error:\n # Something happened, raise an error\n hr, msg, exc, arg = error.args # pylint: disable=W0633\n try:\n failure_code = self.fail_codes[exc[5]]\n except KeyError:\n failure_code = 'Unknown Failure: {0}'.format(error)\n\n log.error('Search Failed: %s\\n\\t\\t%s', failure_code, search_string)\n raise CommandExecutionError(failure_code)\n\n self._updates = results.Updates\n", "def search(self, search_string):\n '''\n Search for either a single update or a specific list of updates. GUIDs\n are searched first, then KB numbers, and finally Titles.\n\n Args:\n\n search_string (str, list): The search string to use to find the\n update. This can be the GUID or KB of the update (preferred). It can\n also be the full Title of the update or any part of the Title. A\n partial Title search is less specific and can return multiple\n results.\n\n Returns:\n Updates: An instance of Updates with the results of the search\n\n Code Example:\n\n .. code-block:: python\n\n import salt.utils.win_update\n wua = salt.utils.win_update.WindowsUpdateAgent()\n\n # search for a single update and show its details\n updates = wua.search('KB3194343')\n updates.list()\n\n # search for a list of updates and show their details\n updates = wua.search(['KB3195432', '12345678-abcd-1234-abcd-1234567890ab'])\n updates.list()\n '''\n updates = Updates()\n found = updates.updates\n\n if isinstance(search_string, six.string_types):\n search_string = [search_string]\n\n if isinstance(search_string, six.integer_types):\n search_string = [six.text_type(search_string)]\n\n for update in self._updates:\n\n for find in search_string:\n\n # Search by GUID\n if find == update.Identity.UpdateID:\n found.Add(update)\n continue\n\n # Search by KB\n if find in ['KB' + item for item in update.KBArticleIDs]:\n found.Add(update)\n continue\n\n # Search by KB without the KB in front\n if find in [item for item in update.KBArticleIDs]:\n found.Add(update)\n continue\n\n # Search by Title\n if find in update.Title:\n found.Add(update)\n continue\n\n return updates\n", "def uninstall(self, updates):\n '''\n Uninstall the updates passed in the updates collection. Load the updates\n collection using the ``search`` or ``available`` functions.\n\n .. note:: Starting with Windows 10 the Windows Update Agent is unable to\n uninstall updates. An ``Uninstall Not Allowed`` error is returned. If\n this error is encountered this function will instead attempt to use\n ``dism.exe`` to perform the uninstallation. ``dism.exe`` may fail to\n to find the KB number for the package. In that case, removal will fail.\n\n Args:\n\n updates (Updates): An instance of the Updates class containing a\n the updates to be uninstalled.\n\n Returns:\n dict: A dictionary containing the results of the uninstallation\n\n Code Example:\n\n .. code-block:: python\n\n import salt.utils.win_update\n wua = salt.utils.win_update.WindowsUpdateAgent()\n\n # uninstall KB3195454\n updates = wua.search('KB3195454')\n results = wua.uninstall(updates)\n '''\n # This doesn't work with the WUA API since Windows 10. It always returns\n # \"0x80240028 # Uninstall not allowed\". The full message is: \"The update\n # could not be uninstalled because the request did not originate from a\n # Windows Server Update Services (WSUS) server.\n\n # Check for empty list\n if updates.count() == 0:\n ret = {'Success': False,\n 'Updates': 'Nothing to uninstall'}\n return ret\n\n installer = self._session.CreateUpdateInstaller()\n self._session.ClientApplicationID = 'Salt: Install Update'\n with salt.utils.winapi.Com():\n uninstall_list = win32com.client.Dispatch('Microsoft.Update.UpdateColl')\n\n ret = {'Updates': {}}\n\n # Check for updates that aren't already installed\n for update in updates.updates:\n\n # Define uid to keep the lines shorter\n uid = update.Identity.UpdateID\n ret['Updates'][uid] = {}\n ret['Updates'][uid]['Title'] = update.Title\n ret['Updates'][uid]['AlreadyUninstalled'] = \\\n not bool(update.IsInstalled)\n\n # Make sure the update has actually been Uninstalled\n if salt.utils.data.is_true(update.IsInstalled):\n log.debug('To Be Uninstalled: %s', uid)\n log.debug('\\tTitle: %s', update.Title)\n uninstall_list.Add(update)\n\n # Check the install list\n if uninstall_list.Count == 0:\n ret = {'Success': False,\n 'Updates': 'Nothing to uninstall'}\n return ret\n\n # Send the list to the installer\n installer.Updates = uninstall_list\n\n # Uninstall the list\n try:\n log.debug('Uninstalling Updates')\n result = installer.Uninstall()\n\n except pywintypes.com_error as error:\n # Something happened, return error or try using DISM\n hr, msg, exc, arg = error.args # pylint: disable=W0633\n try:\n failure_code = self.fail_codes[exc[5]]\n except KeyError:\n failure_code = 'Unknown Failure: {0}'.format(error)\n\n # If \"Uninstall Not Allowed\" error, try using DISM\n if exc[5] == -2145124312:\n log.debug('Uninstall Failed with WUA, attempting with DISM')\n try:\n\n # Go through each update...\n for item in uninstall_list:\n\n # Look for the KB numbers\n for kb in item.KBArticleIDs:\n\n # Get the list of packages\n cmd = ['dism', '/Online', '/Get-Packages']\n pkg_list = self._run(cmd)[0].splitlines()\n\n # Find the KB in the pkg_list\n for item in pkg_list:\n\n # Uninstall if found\n if 'kb' + kb in item.lower():\n pkg = item.split(' : ')[1]\n\n ret['DismPackage'] = pkg\n\n cmd = ['dism',\n '/Online',\n '/Remove-Package',\n '/PackageName:{0}'.format(pkg),\n '/Quiet',\n '/NoRestart']\n\n self._run(cmd)\n\n except CommandExecutionError as exc:\n log.debug('Uninstall using DISM failed')\n log.debug('Command: %s', ' '.join(cmd))\n log.debug('Error: %s', exc)\n raise CommandExecutionError(\n 'Uninstall using DISM failed: {0}'.format(exc))\n\n # DISM Uninstall Completed Successfully\n log.debug('Uninstall Completed using DISM')\n\n # Populate the return dictionary\n ret['Success'] = True\n ret['Message'] = 'Uninstalled using DISM'\n ret['NeedsReboot'] = needs_reboot()\n log.debug('NeedsReboot: %s', ret['NeedsReboot'])\n\n # Refresh the Updates Table\n self.refresh()\n\n reboot = {0: 'Never Reboot',\n 1: 'Always Reboot',\n 2: 'Poss Reboot'}\n\n # Check the status of each update\n for update in self._updates:\n uid = update.Identity.UpdateID\n for item in uninstall_list:\n if item.Identity.UpdateID == uid:\n if not update.IsInstalled:\n ret['Updates'][uid]['Result'] = \\\n 'Uninstallation Succeeded'\n else:\n ret['Updates'][uid]['Result'] = \\\n 'Uninstallation Failed'\n ret['Updates'][uid]['RebootBehavior'] = \\\n reboot[update.InstallationBehavior.RebootBehavior]\n\n return ret\n\n # Found a differenct exception, Raise error\n log.error('Uninstall Failed: %s', failure_code)\n raise CommandExecutionError(failure_code)\n\n # Lookup dictionary\n result_code = {0: 'Uninstallation Not Started',\n 1: 'Uninstallation In Progress',\n 2: 'Uninstallation Succeeded',\n 3: 'Uninstallation Succeeded With Errors',\n 4: 'Uninstallation Failed',\n 5: 'Uninstallation Aborted'}\n\n log.debug('Uninstall Complete')\n log.debug(result_code[result.ResultCode])\n ret['Message'] = result_code[result.ResultCode]\n\n if result.ResultCode in [2, 3]:\n ret['Success'] = True\n ret['NeedsReboot'] = result.RebootRequired\n log.debug('NeedsReboot: %s', result.RebootRequired)\n else:\n log.debug('Uninstall Failed')\n ret['Success'] = False\n\n reboot = {0: 'Never Reboot',\n 1: 'Always Reboot',\n 2: 'Poss Reboot'}\n for i in range(uninstall_list.Count):\n uid = uninstall_list.Item(i).Identity.UpdateID\n ret['Updates'][uid]['Result'] = \\\n result_code[result.GetUpdateResult(i).ResultCode]\n ret['Updates'][uid]['RebootBehavior'] = reboot[\n uninstall_list.Item(i).InstallationBehavior.RebootBehavior]\n\n return ret\n" ]
# -*- coding: utf-8 -*- ''' Installation of Windows Updates using the Windows Update Agent .. versionadded:: 2017.7.0 Salt can manage Windows updates via the "wua" state module. Updates can be installed and removed. Update management declarations are as follows: For installation: .. code-block:: yaml # Install a single update using the KB KB3194343: wua.installed # Install a single update using the name parameter install_update: wua.installed: - name: KB3194343 # Install multiple updates using the updates parameter and a combination of # KB number and GUID install_updates: wua.installed: - updates: - KB3194343 - bb1dbb26-3fb6-45fd-bb05-e3c8e379195c For removal: .. code-block:: yaml # Remove a single update using the KB KB3194343: wua.removed # Remove a single update using the name parameter remove_update: wua.removed: - name: KB3194343 # Remove multiple updates using the updates parameter and a combination of # KB number and GUID remove_updates: wua.removed: - updates: - KB3194343 - bb1dbb26-3fb6-45fd-bb05-e3c8e379195c ''' # Import Python libs from __future__ import absolute_import, unicode_literals, print_function import logging # Import Salt libs from salt.ext import six import salt.utils.data import salt.utils.platform import salt.utils.win_update log = logging.getLogger(__name__) __virtualname__ = 'wua' def __virtual__(): ''' Only valid on Windows machines ''' if not salt.utils.platform.is_windows(): return False, 'WUA: Only available on Window systems' if not salt.utils.win_update.HAS_PYWIN32: return False, 'WUA: Requires PyWin32 libraries' return __virtualname__ def installed(name, updates=None): ''' Ensure Microsoft Updates are installed. Updates will be downloaded if needed. Args: name (str): The identifier of a single update to install. updates (list): A list of identifiers for updates to be installed. Overrides ``name``. Default is None. .. note:: Identifiers can be the GUID, the KB number, or any part of the Title of the Microsoft update. GUIDs and KBs are the preferred method to ensure you're installing the correct update. .. warning:: Using a partial KB number or a partial Title could result in more than one update being installed. Returns: dict: A dictionary containing the results of the update CLI Example: .. code-block:: yaml # using a GUID install_update: wua.installed: - name: 28cf1b09-2b1a-458c-9bd1-971d1b26b211 # using a KB install_update: wua.installed: - name: KB3194343 # using the full Title install_update: wua.installed: - name: Security Update for Adobe Flash Player for Windows 10 Version 1607 (for x64-based Systems) (KB3194343) # Install multiple updates install_updates: wua.installed: - updates: - KB3194343 - 28cf1b09-2b1a-458c-9bd1-971d1b26b211 ''' if isinstance(updates, six.string_types): updates = [updates] if not updates: updates = name ret = {'name': name, 'changes': {}, 'result': True, 'comment': ''} wua = salt.utils.win_update.WindowsUpdateAgent() # Search for updates install_list = wua.search(updates) # No updates found if install_list.count() == 0: ret['comment'] = 'No updates found' return ret # List of updates to download download = salt.utils.win_update.Updates() for item in install_list.updates: if not salt.utils.data.is_true(item.IsDownloaded): download.updates.Add(item) # List of updates to install install = salt.utils.win_update.Updates() installed_updates = [] for item in install_list.updates: if not salt.utils.data.is_true(item.IsInstalled): install.updates.Add(item) else: installed_updates.extend('KB' + kb for kb in item.KBArticleIDs) if install.count() == 0: ret['comment'] = 'Updates already installed: ' ret['comment'] += '\n - '.join(installed_updates) return ret # Return comment of changes if test. if __opts__['test']: ret['result'] = None ret['comment'] = 'Updates will be installed:' for update in install.updates: ret['comment'] += '\n' ret['comment'] += ': '.join( [update.Identity.UpdateID, update.Title]) return ret # Download updates wua.download(download) # Install updates wua.install(install) # Refresh windows update info wua.refresh() post_info = wua.updates().list() # Verify the installation for item in install.list(): if not salt.utils.data.is_true(post_info[item]['Installed']): ret['changes']['failed'] = { item: {'Title': post_info[item]['Title'][:40] + '...', 'KBs': post_info[item]['KBs']} } ret['result'] = False else: ret['changes']['installed'] = { item: {'Title': post_info[item]['Title'][:40] + '...', 'NeedsReboot': post_info[item]['NeedsReboot'], 'KBs': post_info[item]['KBs']} } if ret['changes'].get('failed', False): ret['comment'] = 'Updates failed' else: ret['comment'] = 'Updates installed successfully' return ret def uptodate(name, software=True, drivers=False, skip_hidden=False, skip_mandatory=False, skip_reboot=True, categories=None, severities=None,): ''' Ensure Microsoft Updates that match the passed criteria are installed. Updates will be downloaded if needed. This state allows you to update a system without specifying a specific update to apply. All matching updates will be installed. Args: name (str): The name has no functional value and is only used as a tracking reference software (bool): Include software updates in the results (default is True) drivers (bool): Include driver updates in the results (default is False) skip_hidden (bool): Skip updates that have been hidden. Default is False. skip_mandatory (bool): Skip mandatory updates. Default is False. skip_reboot (bool): Skip updates that require a reboot. Default is True. categories (list): Specify the categories to list. Must be passed as a list. All categories returned by default. Categories include the following: * Critical Updates * Definition Updates * Drivers (make sure you set drivers=True) * Feature Packs * Security Updates * Update Rollups * Updates * Update Rollups * Windows 7 * Windows 8.1 * Windows 8.1 drivers * Windows 8.1 and later drivers * Windows Defender severities (list): Specify the severities to include. Must be passed as a list. All severities returned by default. Severities include the following: * Critical * Important Returns: dict: A dictionary containing the results of the update CLI Example: .. code-block:: yaml # Update the system using the state defaults update_system: wua.uptodate # Update the drivers update_drivers: wua.uptodate: - software: False - drivers: True - skip_reboot: False # Apply all critical updates update_critical: wua.uptodate: - severities: - Critical ''' ret = {'name': name, 'changes': {}, 'result': True, 'comment': ''} wua = salt.utils.win_update.WindowsUpdateAgent() available_updates = wua.available( skip_hidden=skip_hidden, skip_installed=True, skip_mandatory=skip_mandatory, skip_reboot=skip_reboot, software=software, drivers=drivers, categories=categories, severities=severities) # No updates found if available_updates.count() == 0: ret['comment'] = 'No updates found' return ret updates = list(available_updates.list().keys()) # Search for updates install_list = wua.search(updates) # List of updates to download download = salt.utils.win_update.Updates() for item in install_list.updates: if not salt.utils.data.is_true(item.IsDownloaded): download.updates.Add(item) # List of updates to install install = salt.utils.win_update.Updates() for item in install_list.updates: if not salt.utils.data.is_true(item.IsInstalled): install.updates.Add(item) # Return comment of changes if test. if __opts__['test']: ret['result'] = None ret['comment'] = 'Updates will be installed:' for update in install.updates: ret['comment'] += '\n' ret['comment'] += ': '.join( [update.Identity.UpdateID, update.Title]) return ret # Download updates wua.download(download) # Install updates wua.install(install) # Refresh windows update info wua.refresh() post_info = wua.updates().list() # Verify the installation for item in install.list(): if not salt.utils.data.is_true(post_info[item]['Installed']): ret['changes']['failed'] = { item: {'Title': post_info[item]['Title'][:40] + '...', 'KBs': post_info[item]['KBs']} } ret['result'] = False else: ret['changes']['installed'] = { item: {'Title': post_info[item]['Title'][:40] + '...', 'NeedsReboot': post_info[item]['NeedsReboot'], 'KBs': post_info[item]['KBs']} } if ret['changes'].get('failed', False): ret['comment'] = 'Updates failed' else: ret['comment'] = 'Updates installed successfully' return ret
saltstack/salt
salt/states/win_wua.py
uptodate
python
def uptodate(name, software=True, drivers=False, skip_hidden=False, skip_mandatory=False, skip_reboot=True, categories=None, severities=None,): ''' Ensure Microsoft Updates that match the passed criteria are installed. Updates will be downloaded if needed. This state allows you to update a system without specifying a specific update to apply. All matching updates will be installed. Args: name (str): The name has no functional value and is only used as a tracking reference software (bool): Include software updates in the results (default is True) drivers (bool): Include driver updates in the results (default is False) skip_hidden (bool): Skip updates that have been hidden. Default is False. skip_mandatory (bool): Skip mandatory updates. Default is False. skip_reboot (bool): Skip updates that require a reboot. Default is True. categories (list): Specify the categories to list. Must be passed as a list. All categories returned by default. Categories include the following: * Critical Updates * Definition Updates * Drivers (make sure you set drivers=True) * Feature Packs * Security Updates * Update Rollups * Updates * Update Rollups * Windows 7 * Windows 8.1 * Windows 8.1 drivers * Windows 8.1 and later drivers * Windows Defender severities (list): Specify the severities to include. Must be passed as a list. All severities returned by default. Severities include the following: * Critical * Important Returns: dict: A dictionary containing the results of the update CLI Example: .. code-block:: yaml # Update the system using the state defaults update_system: wua.uptodate # Update the drivers update_drivers: wua.uptodate: - software: False - drivers: True - skip_reboot: False # Apply all critical updates update_critical: wua.uptodate: - severities: - Critical ''' ret = {'name': name, 'changes': {}, 'result': True, 'comment': ''} wua = salt.utils.win_update.WindowsUpdateAgent() available_updates = wua.available( skip_hidden=skip_hidden, skip_installed=True, skip_mandatory=skip_mandatory, skip_reboot=skip_reboot, software=software, drivers=drivers, categories=categories, severities=severities) # No updates found if available_updates.count() == 0: ret['comment'] = 'No updates found' return ret updates = list(available_updates.list().keys()) # Search for updates install_list = wua.search(updates) # List of updates to download download = salt.utils.win_update.Updates() for item in install_list.updates: if not salt.utils.data.is_true(item.IsDownloaded): download.updates.Add(item) # List of updates to install install = salt.utils.win_update.Updates() for item in install_list.updates: if not salt.utils.data.is_true(item.IsInstalled): install.updates.Add(item) # Return comment of changes if test. if __opts__['test']: ret['result'] = None ret['comment'] = 'Updates will be installed:' for update in install.updates: ret['comment'] += '\n' ret['comment'] += ': '.join( [update.Identity.UpdateID, update.Title]) return ret # Download updates wua.download(download) # Install updates wua.install(install) # Refresh windows update info wua.refresh() post_info = wua.updates().list() # Verify the installation for item in install.list(): if not salt.utils.data.is_true(post_info[item]['Installed']): ret['changes']['failed'] = { item: {'Title': post_info[item]['Title'][:40] + '...', 'KBs': post_info[item]['KBs']} } ret['result'] = False else: ret['changes']['installed'] = { item: {'Title': post_info[item]['Title'][:40] + '...', 'NeedsReboot': post_info[item]['NeedsReboot'], 'KBs': post_info[item]['KBs']} } if ret['changes'].get('failed', False): ret['comment'] = 'Updates failed' else: ret['comment'] = 'Updates installed successfully' return ret
Ensure Microsoft Updates that match the passed criteria are installed. Updates will be downloaded if needed. This state allows you to update a system without specifying a specific update to apply. All matching updates will be installed. Args: name (str): The name has no functional value and is only used as a tracking reference software (bool): Include software updates in the results (default is True) drivers (bool): Include driver updates in the results (default is False) skip_hidden (bool): Skip updates that have been hidden. Default is False. skip_mandatory (bool): Skip mandatory updates. Default is False. skip_reboot (bool): Skip updates that require a reboot. Default is True. categories (list): Specify the categories to list. Must be passed as a list. All categories returned by default. Categories include the following: * Critical Updates * Definition Updates * Drivers (make sure you set drivers=True) * Feature Packs * Security Updates * Update Rollups * Updates * Update Rollups * Windows 7 * Windows 8.1 * Windows 8.1 drivers * Windows 8.1 and later drivers * Windows Defender severities (list): Specify the severities to include. Must be passed as a list. All severities returned by default. Severities include the following: * Critical * Important Returns: dict: A dictionary containing the results of the update CLI Example: .. code-block:: yaml # Update the system using the state defaults update_system: wua.uptodate # Update the drivers update_drivers: wua.uptodate: - software: False - drivers: True - skip_reboot: False # Apply all critical updates update_critical: wua.uptodate: - severities: - Critical
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/win_wua.py#L338-L504
[ "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 count(self):\n '''\n Return how many records are in the Microsoft Update Collection\n\n Returns:\n int: The number of updates in the collection\n\n Code Example:\n\n .. code-block:: python\n\n import salt.utils.win_update\n updates = salt.utils.win_update.Updates()\n updates.count()\n '''\n return self.updates.Count\n", "def list(self):\n '''\n Create a dictionary with the details for the updates in the collection.\n\n Returns:\n dict: Details about each update\n\n .. code-block:: cfg\n\n List of Updates:\n {'<GUID>': {'Title': <title>,\n 'KB': <KB>,\n 'GUID': <the globally unique identifier for the update>\n 'Description': <description>,\n 'Downloaded': <has the update been downloaded>,\n 'Installed': <has the update been installed>,\n 'Mandatory': <is the update mandatory>,\n 'UserInput': <is user input required>,\n 'EULAAccepted': <has the EULA been accepted>,\n 'Severity': <update severity>,\n 'NeedsReboot': <is the update installed and awaiting reboot>,\n 'RebootBehavior': <will the update require a reboot>,\n 'Categories': [ '<category 1>',\n '<category 2>',\n ...]\n }\n }\n\n Code Example:\n\n .. code-block:: python\n\n import salt.utils.win_update\n updates = salt.utils.win_update.Updates()\n updates.list()\n '''\n # https://msdn.microsoft.com/en-us/library/windows/desktop/aa386099(v=vs.85).aspx\n if self.count() == 0:\n return 'Nothing to return'\n\n log.debug('Building a detailed report of the results.')\n\n # Build a dictionary containing details for each update\n results = {}\n for update in self.updates:\n\n results[update.Identity.UpdateID] = {\n 'guid': update.Identity.UpdateID,\n 'Title': six.text_type(update.Title),\n 'Type': self.update_types[update.Type],\n 'Description': update.Description,\n 'Downloaded': bool(update.IsDownloaded),\n 'Installed': bool(update.IsInstalled),\n 'Mandatory': bool(update.IsMandatory),\n 'EULAAccepted': bool(update.EulaAccepted),\n 'NeedsReboot': bool(update.RebootRequired),\n 'Severity': six.text_type(update.MsrcSeverity),\n 'UserInput':\n bool(update.InstallationBehavior.CanRequestUserInput),\n 'RebootBehavior':\n self.reboot_behavior[\n update.InstallationBehavior.RebootBehavior],\n 'KBs': ['KB' + item for item in update.KBArticleIDs],\n 'Categories': [item.Name for item in update.Categories]\n }\n\n return results\n", "def updates(self):\n '''\n Get the contents of ``_updates`` (all updates) and puts them in an\n Updates class to expose the list and summary functions.\n\n Returns:\n Updates: An instance of the Updates class with all updates for the\n system.\n\n .. code-block:: python\n\n import salt.utils.win_update\n wua = salt.utils.win_update.WindowsUpdateAgent()\n updates = wua.updates()\n\n # To get a list\n updates.list()\n\n # To get a summary\n updates.summary()\n '''\n updates = Updates()\n found = updates.updates\n\n for update in self._updates:\n found.Add(update)\n\n return updates\n", "def refresh(self):\n '''\n Refresh the contents of the ``_updates`` collection. This gets all\n updates in the Windows Update system and loads them into the collection.\n This is the part that is slow.\n\n Code Example:\n\n .. code-block:: python\n\n import salt.utils.win_update\n wua = salt.utils.win_update.WindowsUpdateAgent()\n wua.refresh()\n '''\n # https://msdn.microsoft.com/en-us/library/windows/desktop/aa386526(v=vs.85).aspx\n search_string = 'Type=\\'Software\\' or ' \\\n 'Type=\\'Driver\\''\n\n # Create searcher object\n searcher = self._session.CreateUpdateSearcher()\n self._session.ClientApplicationID = 'Salt: Load Updates'\n\n # Load all updates into the updates collection\n try:\n results = searcher.Search(search_string)\n if results.Updates.Count == 0:\n log.debug('No Updates found for:\\n\\t\\t%s', search_string)\n return 'No Updates found: {0}'.format(search_string)\n except pywintypes.com_error as error:\n # Something happened, raise an error\n hr, msg, exc, arg = error.args # pylint: disable=W0633\n try:\n failure_code = self.fail_codes[exc[5]]\n except KeyError:\n failure_code = 'Unknown Failure: {0}'.format(error)\n\n log.error('Search Failed: %s\\n\\t\\t%s', failure_code, search_string)\n raise CommandExecutionError(failure_code)\n\n self._updates = results.Updates\n", "def available(self,\n skip_hidden=True,\n skip_installed=True,\n skip_mandatory=False,\n skip_reboot=False,\n software=True,\n drivers=True,\n categories=None,\n severities=None):\n '''\n Gets a list of all updates available on the system that match the passed\n criteria.\n\n Args:\n\n skip_hidden (bool): Skip hidden updates. Default is True\n\n skip_installed (bool): Skip installed updates. Default is True\n\n skip_mandatory (bool): Skip mandatory updates. Default is False\n\n skip_reboot (bool): Skip updates that can or do require reboot.\n Default is False\n\n software (bool): Include software updates. Default is True\n\n drivers (bool): Include driver updates. Default is True\n\n categories (list): Include updates that have these categories.\n Default is none (all categories).\n\n Categories include the following:\n\n * Critical Updates\n * Definition Updates\n * Drivers (make sure you set drivers=True)\n * Feature Packs\n * Security Updates\n * Update Rollups\n * Updates\n * Update Rollups\n * Windows 7\n * Windows 8.1\n * Windows 8.1 drivers\n * Windows 8.1 and later drivers\n * Windows Defender\n\n severities (list): Include updates that have these severities.\n Default is none (all severities).\n\n Severities include the following:\n\n * Critical\n * Important\n\n .. note:: All updates are either software or driver updates. If both\n ``software`` and ``drivers`` is False, nothing will be returned.\n\n Returns:\n\n Updates: An instance of Updates with the results of the search.\n\n Code Example:\n\n .. code-block:: python\n\n import salt.utils.win_update\n wua = salt.utils.win_update.WindowsUpdateAgent()\n\n # Gets all updates and shows a summary\n updates = wua.available\n updates.summary()\n\n # Get a list of Critical updates\n updates = wua.available(categories=['Critical Updates'])\n updates.list()\n '''\n # https://msdn.microsoft.com/en-us/library/windows/desktop/aa386099(v=vs.85).aspx\n updates = Updates()\n found = updates.updates\n\n for update in self._updates:\n\n if salt.utils.data.is_true(update.IsHidden) and skip_hidden:\n continue\n\n if salt.utils.data.is_true(update.IsInstalled) and skip_installed:\n continue\n\n if salt.utils.data.is_true(update.IsMandatory) and skip_mandatory:\n continue\n\n if salt.utils.data.is_true(\n update.InstallationBehavior.RebootBehavior) and skip_reboot:\n continue\n\n if not software and update.Type == 1:\n continue\n\n if not drivers and update.Type == 2:\n continue\n\n if categories is not None:\n match = False\n for category in update.Categories:\n if category.Name in categories:\n match = True\n if not match:\n continue\n\n if severities is not None:\n if update.MsrcSeverity not in severities:\n continue\n\n found.Add(update)\n\n return updates\n", "def search(self, search_string):\n '''\n Search for either a single update or a specific list of updates. GUIDs\n are searched first, then KB numbers, and finally Titles.\n\n Args:\n\n search_string (str, list): The search string to use to find the\n update. This can be the GUID or KB of the update (preferred). It can\n also be the full Title of the update or any part of the Title. A\n partial Title search is less specific and can return multiple\n results.\n\n Returns:\n Updates: An instance of Updates with the results of the search\n\n Code Example:\n\n .. code-block:: python\n\n import salt.utils.win_update\n wua = salt.utils.win_update.WindowsUpdateAgent()\n\n # search for a single update and show its details\n updates = wua.search('KB3194343')\n updates.list()\n\n # search for a list of updates and show their details\n updates = wua.search(['KB3195432', '12345678-abcd-1234-abcd-1234567890ab'])\n updates.list()\n '''\n updates = Updates()\n found = updates.updates\n\n if isinstance(search_string, six.string_types):\n search_string = [search_string]\n\n if isinstance(search_string, six.integer_types):\n search_string = [six.text_type(search_string)]\n\n for update in self._updates:\n\n for find in search_string:\n\n # Search by GUID\n if find == update.Identity.UpdateID:\n found.Add(update)\n continue\n\n # Search by KB\n if find in ['KB' + item for item in update.KBArticleIDs]:\n found.Add(update)\n continue\n\n # Search by KB without the KB in front\n if find in [item for item in update.KBArticleIDs]:\n found.Add(update)\n continue\n\n # Search by Title\n if find in update.Title:\n found.Add(update)\n continue\n\n return updates\n", "def download(self, updates):\n '''\n Download the updates passed in the updates collection. Load the updates\n collection using ``search`` or ``available``\n\n Args:\n\n updates (Updates): An instance of the Updates class containing a\n the updates to be downloaded.\n\n Returns:\n dict: A dictionary containing the results of the download\n\n Code Example:\n\n .. code-block:: python\n\n import salt.utils.win_update\n wua = salt.utils.win_update.WindowsUpdateAgent()\n\n # Download KB3195454\n updates = wua.search('KB3195454')\n results = wua.download(updates)\n '''\n\n # Check for empty list\n if updates.count() == 0:\n ret = {'Success': False,\n 'Updates': 'Nothing to download'}\n return ret\n\n # Initialize the downloader object and list collection\n downloader = self._session.CreateUpdateDownloader()\n self._session.ClientApplicationID = 'Salt: Download Update'\n with salt.utils.winapi.Com():\n download_list = win32com.client.Dispatch('Microsoft.Update.UpdateColl')\n\n ret = {'Updates': {}}\n\n # Check for updates that aren't already downloaded\n for update in updates.updates:\n\n # Define uid to keep the lines shorter\n uid = update.Identity.UpdateID\n ret['Updates'][uid] = {}\n ret['Updates'][uid]['Title'] = update.Title\n ret['Updates'][uid]['AlreadyDownloaded'] = \\\n bool(update.IsDownloaded)\n\n # Accept EULA\n if not salt.utils.data.is_true(update.EulaAccepted):\n log.debug('Accepting EULA: %s', update.Title)\n update.AcceptEula() # pylint: disable=W0104\n\n # Update already downloaded\n if not salt.utils.data.is_true(update.IsDownloaded):\n log.debug('To Be Downloaded: %s', uid)\n log.debug('\\tTitle: %s', update.Title)\n download_list.Add(update)\n\n # Check the download list\n if download_list.Count == 0:\n ret = {'Success': True,\n 'Updates': 'Nothing to download'}\n return ret\n\n # Send the list to the downloader\n downloader.Updates = download_list\n\n # Download the list\n try:\n log.debug('Downloading Updates')\n result = downloader.Download()\n except pywintypes.com_error as error:\n # Something happened, raise an error\n hr, msg, exc, arg = error.args # pylint: disable=W0633\n try:\n failure_code = self.fail_codes[exc[5]]\n except KeyError:\n failure_code = 'Unknown Failure: {0}'.format(error)\n\n log.error('Download Failed: %s', failure_code)\n raise CommandExecutionError(failure_code)\n\n # Lookup dictionary\n result_code = {0: 'Download Not Started',\n 1: 'Download In Progress',\n 2: 'Download Succeeded',\n 3: 'Download Succeeded With Errors',\n 4: 'Download Failed',\n 5: 'Download Aborted'}\n\n log.debug('Download Complete')\n log.debug(result_code[result.ResultCode])\n ret['Message'] = result_code[result.ResultCode]\n\n # Was the download successful?\n if result.ResultCode in [2, 3]:\n log.debug('Downloaded Successfully')\n ret['Success'] = True\n else:\n log.debug('Download Failed')\n ret['Success'] = False\n\n # Report results for each update\n for i in range(download_list.Count):\n uid = download_list.Item(i).Identity.UpdateID\n ret['Updates'][uid]['Result'] = \\\n result_code[result.GetUpdateResult(i).ResultCode]\n\n return ret\n", "def install(self, updates):\n '''\n Install the updates passed in the updates collection. Load the updates\n collection using the ``search`` or ``available`` functions. If the\n updates need to be downloaded, use the ``download`` function.\n\n Args:\n\n updates (Updates): An instance of the Updates class containing a\n the updates to be installed.\n\n Returns:\n dict: A dictionary containing the results of the installation\n\n Code Example:\n\n .. code-block:: python\n\n import salt.utils.win_update\n wua = salt.utils.win_update.WindowsUpdateAgent()\n\n # install KB3195454\n updates = wua.search('KB3195454')\n results = wua.download(updates)\n results = wua.install(updates)\n '''\n # Check for empty list\n if updates.count() == 0:\n ret = {'Success': False,\n 'Updates': 'Nothing to install'}\n return ret\n\n installer = self._session.CreateUpdateInstaller()\n self._session.ClientApplicationID = 'Salt: Install Update'\n with salt.utils.winapi.Com():\n install_list = win32com.client.Dispatch('Microsoft.Update.UpdateColl')\n\n ret = {'Updates': {}}\n\n # Check for updates that aren't already installed\n for update in updates.updates:\n\n # Define uid to keep the lines shorter\n uid = update.Identity.UpdateID\n ret['Updates'][uid] = {}\n ret['Updates'][uid]['Title'] = update.Title\n ret['Updates'][uid]['AlreadyInstalled'] = bool(update.IsInstalled)\n\n # Make sure the update has actually been installed\n if not salt.utils.data.is_true(update.IsInstalled):\n log.debug('To Be Installed: %s', uid)\n log.debug('\\tTitle: %s', update.Title)\n install_list.Add(update)\n\n # Check the install list\n if install_list.Count == 0:\n ret = {'Success': True,\n 'Updates': 'Nothing to install'}\n return ret\n\n # Send the list to the installer\n installer.Updates = install_list\n\n # Install the list\n try:\n log.debug('Installing Updates')\n result = installer.Install()\n\n except pywintypes.com_error as error:\n # Something happened, raise an error\n hr, msg, exc, arg = error.args # pylint: disable=W0633\n try:\n failure_code = self.fail_codes[exc[5]]\n except KeyError:\n failure_code = 'Unknown Failure: {0}'.format(error)\n\n log.error('Install Failed: %s', failure_code)\n raise CommandExecutionError(failure_code)\n\n # Lookup dictionary\n result_code = {0: 'Installation Not Started',\n 1: 'Installation In Progress',\n 2: 'Installation Succeeded',\n 3: 'Installation Succeeded With Errors',\n 4: 'Installation Failed',\n 5: 'Installation Aborted'}\n\n log.debug('Install Complete')\n log.debug(result_code[result.ResultCode])\n ret['Message'] = result_code[result.ResultCode]\n\n if result.ResultCode in [2, 3]:\n ret['Success'] = True\n ret['NeedsReboot'] = result.RebootRequired\n log.debug('NeedsReboot: %s', result.RebootRequired)\n else:\n log.debug('Install Failed')\n ret['Success'] = False\n\n reboot = {0: 'Never Reboot',\n 1: 'Always Reboot',\n 2: 'Poss Reboot'}\n for i in range(install_list.Count):\n uid = install_list.Item(i).Identity.UpdateID\n ret['Updates'][uid]['Result'] = \\\n result_code[result.GetUpdateResult(i).ResultCode]\n ret['Updates'][uid]['RebootBehavior'] = \\\n reboot[install_list.Item(i).InstallationBehavior.RebootBehavior]\n\n return ret\n" ]
# -*- coding: utf-8 -*- ''' Installation of Windows Updates using the Windows Update Agent .. versionadded:: 2017.7.0 Salt can manage Windows updates via the "wua" state module. Updates can be installed and removed. Update management declarations are as follows: For installation: .. code-block:: yaml # Install a single update using the KB KB3194343: wua.installed # Install a single update using the name parameter install_update: wua.installed: - name: KB3194343 # Install multiple updates using the updates parameter and a combination of # KB number and GUID install_updates: wua.installed: - updates: - KB3194343 - bb1dbb26-3fb6-45fd-bb05-e3c8e379195c For removal: .. code-block:: yaml # Remove a single update using the KB KB3194343: wua.removed # Remove a single update using the name parameter remove_update: wua.removed: - name: KB3194343 # Remove multiple updates using the updates parameter and a combination of # KB number and GUID remove_updates: wua.removed: - updates: - KB3194343 - bb1dbb26-3fb6-45fd-bb05-e3c8e379195c ''' # Import Python libs from __future__ import absolute_import, unicode_literals, print_function import logging # Import Salt libs from salt.ext import six import salt.utils.data import salt.utils.platform import salt.utils.win_update log = logging.getLogger(__name__) __virtualname__ = 'wua' def __virtual__(): ''' Only valid on Windows machines ''' if not salt.utils.platform.is_windows(): return False, 'WUA: Only available on Window systems' if not salt.utils.win_update.HAS_PYWIN32: return False, 'WUA: Requires PyWin32 libraries' return __virtualname__ def installed(name, updates=None): ''' Ensure Microsoft Updates are installed. Updates will be downloaded if needed. Args: name (str): The identifier of a single update to install. updates (list): A list of identifiers for updates to be installed. Overrides ``name``. Default is None. .. note:: Identifiers can be the GUID, the KB number, or any part of the Title of the Microsoft update. GUIDs and KBs are the preferred method to ensure you're installing the correct update. .. warning:: Using a partial KB number or a partial Title could result in more than one update being installed. Returns: dict: A dictionary containing the results of the update CLI Example: .. code-block:: yaml # using a GUID install_update: wua.installed: - name: 28cf1b09-2b1a-458c-9bd1-971d1b26b211 # using a KB install_update: wua.installed: - name: KB3194343 # using the full Title install_update: wua.installed: - name: Security Update for Adobe Flash Player for Windows 10 Version 1607 (for x64-based Systems) (KB3194343) # Install multiple updates install_updates: wua.installed: - updates: - KB3194343 - 28cf1b09-2b1a-458c-9bd1-971d1b26b211 ''' if isinstance(updates, six.string_types): updates = [updates] if not updates: updates = name ret = {'name': name, 'changes': {}, 'result': True, 'comment': ''} wua = salt.utils.win_update.WindowsUpdateAgent() # Search for updates install_list = wua.search(updates) # No updates found if install_list.count() == 0: ret['comment'] = 'No updates found' return ret # List of updates to download download = salt.utils.win_update.Updates() for item in install_list.updates: if not salt.utils.data.is_true(item.IsDownloaded): download.updates.Add(item) # List of updates to install install = salt.utils.win_update.Updates() installed_updates = [] for item in install_list.updates: if not salt.utils.data.is_true(item.IsInstalled): install.updates.Add(item) else: installed_updates.extend('KB' + kb for kb in item.KBArticleIDs) if install.count() == 0: ret['comment'] = 'Updates already installed: ' ret['comment'] += '\n - '.join(installed_updates) return ret # Return comment of changes if test. if __opts__['test']: ret['result'] = None ret['comment'] = 'Updates will be installed:' for update in install.updates: ret['comment'] += '\n' ret['comment'] += ': '.join( [update.Identity.UpdateID, update.Title]) return ret # Download updates wua.download(download) # Install updates wua.install(install) # Refresh windows update info wua.refresh() post_info = wua.updates().list() # Verify the installation for item in install.list(): if not salt.utils.data.is_true(post_info[item]['Installed']): ret['changes']['failed'] = { item: {'Title': post_info[item]['Title'][:40] + '...', 'KBs': post_info[item]['KBs']} } ret['result'] = False else: ret['changes']['installed'] = { item: {'Title': post_info[item]['Title'][:40] + '...', 'NeedsReboot': post_info[item]['NeedsReboot'], 'KBs': post_info[item]['KBs']} } if ret['changes'].get('failed', False): ret['comment'] = 'Updates failed' else: ret['comment'] = 'Updates installed successfully' return ret def removed(name, updates=None): ''' Ensure Microsoft Updates are uninstalled. Args: name (str): The identifier of a single update to uninstall. updates (list): A list of identifiers for updates to be removed. Overrides ``name``. Default is None. .. note:: Identifiers can be the GUID, the KB number, or any part of the Title of the Microsoft update. GUIDs and KBs are the preferred method to ensure you're uninstalling the correct update. .. warning:: Using a partial KB number or a partial Title could result in more than one update being removed. Returns: dict: A dictionary containing the results of the removal CLI Example: .. code-block:: yaml # using a GUID uninstall_update: wua.removed: - name: 28cf1b09-2b1a-458c-9bd1-971d1b26b211 # using a KB uninstall_update: wua.removed: - name: KB3194343 # using the full Title uninstall_update: wua.removed: - name: Security Update for Adobe Flash Player for Windows 10 Version 1607 (for x64-based Systems) (KB3194343) # Install multiple updates uninstall_updates: wua.removed: - updates: - KB3194343 - 28cf1b09-2b1a-458c-9bd1-971d1b26b211 ''' if isinstance(updates, six.string_types): updates = [updates] if not updates: updates = name ret = {'name': name, 'changes': {}, 'result': True, 'comment': ''} wua = salt.utils.win_update.WindowsUpdateAgent() # Search for updates updates = wua.search(updates) # No updates found if updates.count() == 0: ret['comment'] = 'No updates found' return ret # List of updates to uninstall uninstall = salt.utils.win_update.Updates() removed_updates = [] for item in updates.updates: if salt.utils.data.is_true(item.IsInstalled): uninstall.updates.Add(item) else: removed_updates.extend('KB' + kb for kb in item.KBArticleIDs) if uninstall.count() == 0: ret['comment'] = 'Updates already removed: ' ret['comment'] += '\n - '.join(removed_updates) return ret # Return comment of changes if test. if __opts__['test']: ret['result'] = None ret['comment'] = 'Updates will be removed:' for update in uninstall.updates: ret['comment'] += '\n' ret['comment'] += ': '.join( [update.Identity.UpdateID, update.Title]) return ret # Install updates wua.uninstall(uninstall) # Refresh windows update info wua.refresh() post_info = wua.updates().list() # Verify the installation for item in uninstall.list(): if salt.utils.data.is_true(post_info[item]['Installed']): ret['changes']['failed'] = { item: {'Title': post_info[item]['Title'][:40] + '...', 'KBs': post_info[item]['KBs']} } ret['result'] = False else: ret['changes']['removed'] = { item: {'Title': post_info[item]['Title'][:40] + '...', 'NeedsReboot': post_info[item]['NeedsReboot'], 'KBs': post_info[item]['KBs']} } if ret['changes'].get('failed', False): ret['comment'] = 'Updates failed' else: ret['comment'] = 'Updates removed successfully' return ret
saltstack/salt
salt/log/handlers/fluent_mod.py
MessageFormatter.format_graylog_v0
python
def format_graylog_v0(self, record): ''' Graylog 'raw' format is essentially the raw record, minimally munged to provide the bare minimum that td-agent requires to accept and route the event. This is well suited to a config where the client td-agents log directly to Graylog. ''' message_dict = { 'message': record.getMessage(), 'timestamp': self.formatTime(record), # Graylog uses syslog levels, not whatever it is Python does... 'level': syslog_levels.get(record.levelname, 'ALERT'), 'tag': self.tag } if record.exc_info: exc_info = self.formatException(record.exc_info) message_dict.update({'full_message': exc_info}) # Add any extra attributes to the message field for key, value in six.iteritems(record.__dict__): if key in ('args', 'asctime', 'bracketlevel', 'bracketname', 'bracketprocess', 'created', 'exc_info', 'exc_text', 'id', 'levelname', 'levelno', 'msecs', 'msecs', 'message', 'msg', 'relativeCreated', 'version'): # These are already handled above or explicitly pruned. continue if isinstance(value, (six.string_types, bool, dict, float, int, list, types.NoneType)): # pylint: disable=W1699 val = value else: val = repr(value) message_dict.update({'{0}'.format(key): val}) return message_dict
Graylog 'raw' format is essentially the raw record, minimally munged to provide the bare minimum that td-agent requires to accept and route the event. This is well suited to a config where the client td-agents log directly to Graylog.
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/log/handlers/fluent_mod.py#L218-L249
[ "def iteritems(d, **kw):\n return d.iteritems(**kw)\n", "def formatTime(self, record, datefmt=None):\n if self.payload_type == 'gelf': # GELF uses epoch times\n return record.created\n return datetime.datetime.utcfromtimestamp(record.created).isoformat()[:-3] + 'Z'\n" ]
class MessageFormatter(logging.Formatter, NewStyleClassMixIn): def __init__(self, payload_type, version, tags, msg_type=None, msg_path=None): self.payload_type = payload_type self.version = version self.tag = tags[0] if tags else 'salt' # 'salt' for backwards compat self.tags = tags self.msg_path = msg_path if msg_path else payload_type self.msg_type = msg_type if msg_type else payload_type format_func = 'format_{0}_v{1}'.format(payload_type, version).replace('.', '_') self.format = getattr(self, format_func) super(MessageFormatter, self).__init__(fmt=None, datefmt=None) def formatTime(self, record, datefmt=None): if self.payload_type == 'gelf': # GELF uses epoch times return record.created return datetime.datetime.utcfromtimestamp(record.created).isoformat()[:-3] + 'Z' def format_gelf_v1_1(self, record): ''' If your agent is (or can be) configured to forward pre-formed GELF to Graylog with ZERO fluent processing, this function is for YOU, pal... ''' message_dict = { 'version': self.version, 'host': salt.utils.network.get_fqhostname(), 'short_message': record.getMessage(), 'timestamp': self.formatTime(record), 'level': syslog_levels.get(record.levelname, 'ALERT'), "_tag": self.tag } if record.exc_info: exc_info = self.formatException(record.exc_info) message_dict.update({'full_message': exc_info}) # Add any extra attributes to the message field for key, value in six.iteritems(record.__dict__): if key in ('args', 'asctime', 'bracketlevel', 'bracketname', 'bracketprocess', 'created', 'exc_info', 'exc_text', 'id', 'levelname', 'levelno', 'msecs', 'msecs', 'message', 'msg', 'relativeCreated', 'version'): # These are already handled above or explicitly avoided. continue if isinstance(value, (six.string_types, bool, dict, float, int, list, types.NoneType)): # pylint: disable=W1699 val = value else: val = repr(value) # GELF spec require "non-standard" fields to be prefixed with '_' (underscore). message_dict.update({'_{0}'.format(key): val}) return message_dict def format_logstash_v0(self, record): ''' Messages are formatted in logstash's expected format. ''' host = salt.utils.network.get_fqhostname() message_dict = { '@timestamp': self.formatTime(record), '@fields': { 'levelname': record.levelname, 'logger': record.name, 'lineno': record.lineno, 'pathname': record.pathname, 'process': record.process, 'threadName': record.threadName, 'funcName': record.funcName, 'processName': record.processName }, '@message': record.getMessage(), '@source': '{0}://{1}/{2}'.format( self.msg_type, host, self.msg_path ), '@source_host': host, '@source_path': self.msg_path, '@tags': self.tags, '@type': self.msg_type, } if record.exc_info: message_dict['@fields']['exc_info'] = self.formatException( record.exc_info ) # Add any extra attributes to the message field for key, value in six.iteritems(record.__dict__): if key in ('args', 'asctime', 'created', 'exc_info', 'exc_text', 'filename', 'funcName', 'id', 'levelname', 'levelno', 'lineno', 'module', 'msecs', 'msecs', 'message', 'msg', 'name', 'pathname', 'process', 'processName', 'relativeCreated', 'thread', 'threadName'): # These are already handled above or not handled at all continue if value is None: message_dict['@fields'][key] = value continue if isinstance(value, (six.string_types, bool, dict, float, int, list)): message_dict['@fields'][key] = value continue message_dict['@fields'][key] = repr(value) return message_dict def format_logstash_v1(self, record): ''' Messages are formatted in logstash's expected format. ''' message_dict = { '@version': 1, '@timestamp': self.formatTime(record), 'host': salt.utils.network.get_fqhostname(), 'levelname': record.levelname, 'logger': record.name, 'lineno': record.lineno, 'pathname': record.pathname, 'process': record.process, 'threadName': record.threadName, 'funcName': record.funcName, 'processName': record.processName, 'message': record.getMessage(), 'tags': self.tags, 'type': self.msg_type } if record.exc_info: message_dict['exc_info'] = self.formatException( record.exc_info ) # Add any extra attributes to the message field for key, value in six.iteritems(record.__dict__): if key in ('args', 'asctime', 'created', 'exc_info', 'exc_text', 'filename', 'funcName', 'id', 'levelname', 'levelno', 'lineno', 'module', 'msecs', 'msecs', 'message', 'msg', 'name', 'pathname', 'process', 'processName', 'relativeCreated', 'thread', 'threadName'): # These are already handled above or not handled at all continue if value is None: message_dict[key] = value continue if isinstance(value, (six.string_types, bool, dict, float, int, list)): message_dict[key] = value continue message_dict[key] = repr(value) return message_dict
saltstack/salt
salt/log/handlers/fluent_mod.py
MessageFormatter.format_logstash_v0
python
def format_logstash_v0(self, record): ''' Messages are formatted in logstash's expected format. ''' host = salt.utils.network.get_fqhostname() message_dict = { '@timestamp': self.formatTime(record), '@fields': { 'levelname': record.levelname, 'logger': record.name, 'lineno': record.lineno, 'pathname': record.pathname, 'process': record.process, 'threadName': record.threadName, 'funcName': record.funcName, 'processName': record.processName }, '@message': record.getMessage(), '@source': '{0}://{1}/{2}'.format( self.msg_type, host, self.msg_path ), '@source_host': host, '@source_path': self.msg_path, '@tags': self.tags, '@type': self.msg_type, } if record.exc_info: message_dict['@fields']['exc_info'] = self.formatException( record.exc_info ) # Add any extra attributes to the message field for key, value in six.iteritems(record.__dict__): if key in ('args', 'asctime', 'created', 'exc_info', 'exc_text', 'filename', 'funcName', 'id', 'levelname', 'levelno', 'lineno', 'module', 'msecs', 'msecs', 'message', 'msg', 'name', 'pathname', 'process', 'processName', 'relativeCreated', 'thread', 'threadName'): # These are already handled above or not handled at all continue if value is None: message_dict['@fields'][key] = value continue if isinstance(value, (six.string_types, bool, dict, float, int, list)): message_dict['@fields'][key] = value continue message_dict['@fields'][key] = repr(value) return message_dict
Messages are formatted in logstash's expected format.
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/log/handlers/fluent_mod.py#L286-L339
[ "def iteritems(d, **kw):\n return d.iteritems(**kw)\n", "def get_fqhostname():\n '''\n Returns the fully qualified hostname\n '''\n # try getaddrinfo()\n fqdn = None\n try:\n addrinfo = socket.getaddrinfo(\n socket.gethostname(), 0, socket.AF_UNSPEC, socket.SOCK_STREAM,\n socket.SOL_TCP, socket.AI_CANONNAME\n )\n for info in addrinfo:\n # info struct [family, socktype, proto, canonname, sockaddr]\n # On Windows `canonname` can be an empty string\n # This can cause the function to return `None`\n if len(info) > 3 and info[3]:\n fqdn = info[3]\n break\n except socket.gaierror:\n pass # NOTE: this used to log.error() but it was later disabled\n except socket.error as err:\n log.debug('socket.getaddrinfo() failure while finding fqdn: %s', err)\n if fqdn is None:\n fqdn = socket.getfqdn()\n return fqdn\n", "def formatTime(self, record, datefmt=None):\n if self.payload_type == 'gelf': # GELF uses epoch times\n return record.created\n return datetime.datetime.utcfromtimestamp(record.created).isoformat()[:-3] + 'Z'\n" ]
class MessageFormatter(logging.Formatter, NewStyleClassMixIn): def __init__(self, payload_type, version, tags, msg_type=None, msg_path=None): self.payload_type = payload_type self.version = version self.tag = tags[0] if tags else 'salt' # 'salt' for backwards compat self.tags = tags self.msg_path = msg_path if msg_path else payload_type self.msg_type = msg_type if msg_type else payload_type format_func = 'format_{0}_v{1}'.format(payload_type, version).replace('.', '_') self.format = getattr(self, format_func) super(MessageFormatter, self).__init__(fmt=None, datefmt=None) def formatTime(self, record, datefmt=None): if self.payload_type == 'gelf': # GELF uses epoch times return record.created return datetime.datetime.utcfromtimestamp(record.created).isoformat()[:-3] + 'Z' def format_graylog_v0(self, record): ''' Graylog 'raw' format is essentially the raw record, minimally munged to provide the bare minimum that td-agent requires to accept and route the event. This is well suited to a config where the client td-agents log directly to Graylog. ''' message_dict = { 'message': record.getMessage(), 'timestamp': self.formatTime(record), # Graylog uses syslog levels, not whatever it is Python does... 'level': syslog_levels.get(record.levelname, 'ALERT'), 'tag': self.tag } if record.exc_info: exc_info = self.formatException(record.exc_info) message_dict.update({'full_message': exc_info}) # Add any extra attributes to the message field for key, value in six.iteritems(record.__dict__): if key in ('args', 'asctime', 'bracketlevel', 'bracketname', 'bracketprocess', 'created', 'exc_info', 'exc_text', 'id', 'levelname', 'levelno', 'msecs', 'msecs', 'message', 'msg', 'relativeCreated', 'version'): # These are already handled above or explicitly pruned. continue if isinstance(value, (six.string_types, bool, dict, float, int, list, types.NoneType)): # pylint: disable=W1699 val = value else: val = repr(value) message_dict.update({'{0}'.format(key): val}) return message_dict def format_gelf_v1_1(self, record): ''' If your agent is (or can be) configured to forward pre-formed GELF to Graylog with ZERO fluent processing, this function is for YOU, pal... ''' message_dict = { 'version': self.version, 'host': salt.utils.network.get_fqhostname(), 'short_message': record.getMessage(), 'timestamp': self.formatTime(record), 'level': syslog_levels.get(record.levelname, 'ALERT'), "_tag": self.tag } if record.exc_info: exc_info = self.formatException(record.exc_info) message_dict.update({'full_message': exc_info}) # Add any extra attributes to the message field for key, value in six.iteritems(record.__dict__): if key in ('args', 'asctime', 'bracketlevel', 'bracketname', 'bracketprocess', 'created', 'exc_info', 'exc_text', 'id', 'levelname', 'levelno', 'msecs', 'msecs', 'message', 'msg', 'relativeCreated', 'version'): # These are already handled above or explicitly avoided. continue if isinstance(value, (six.string_types, bool, dict, float, int, list, types.NoneType)): # pylint: disable=W1699 val = value else: val = repr(value) # GELF spec require "non-standard" fields to be prefixed with '_' (underscore). message_dict.update({'_{0}'.format(key): val}) return message_dict def format_logstash_v1(self, record): ''' Messages are formatted in logstash's expected format. ''' message_dict = { '@version': 1, '@timestamp': self.formatTime(record), 'host': salt.utils.network.get_fqhostname(), 'levelname': record.levelname, 'logger': record.name, 'lineno': record.lineno, 'pathname': record.pathname, 'process': record.process, 'threadName': record.threadName, 'funcName': record.funcName, 'processName': record.processName, 'message': record.getMessage(), 'tags': self.tags, 'type': self.msg_type } if record.exc_info: message_dict['exc_info'] = self.formatException( record.exc_info ) # Add any extra attributes to the message field for key, value in six.iteritems(record.__dict__): if key in ('args', 'asctime', 'created', 'exc_info', 'exc_text', 'filename', 'funcName', 'id', 'levelname', 'levelno', 'lineno', 'module', 'msecs', 'msecs', 'message', 'msg', 'name', 'pathname', 'process', 'processName', 'relativeCreated', 'thread', 'threadName'): # These are already handled above or not handled at all continue if value is None: message_dict[key] = value continue if isinstance(value, (six.string_types, bool, dict, float, int, list)): message_dict[key] = value continue message_dict[key] = repr(value) return message_dict
saltstack/salt
salt/wheel/minions.py
connected
python
def connected(): ''' List all connected minions on a salt-master ''' opts = salt.config.master_config(__opts__['conf_file']) if opts.get('con_cache'): cache_cli = CacheCli(opts) minions = cache_cli.get_cached() else: minions = list(salt.utils.minions.CkMinions(opts).connected_ids()) return minions
List all connected minions on a salt-master
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/wheel/minions.py#L15-L26
[ "def master_config(path, env_var='SALT_MASTER_CONFIG', defaults=None, exit_on_config_errors=False):\n '''\n Reads in the master configuration file and sets up default options\n\n This is useful for running the actual master daemon. For running\n Master-side client interfaces that need the master opts see\n :py:func:`salt.client.client_config`.\n '''\n if defaults is None:\n defaults = DEFAULT_MASTER_OPTS.copy()\n\n if not os.environ.get(env_var, None):\n # No valid setting was given using the configuration variable.\n # Lets see is SALT_CONFIG_DIR is of any use\n salt_config_dir = os.environ.get('SALT_CONFIG_DIR', None)\n if salt_config_dir:\n env_config_file_path = os.path.join(salt_config_dir, 'master')\n if salt_config_dir and os.path.isfile(env_config_file_path):\n # We can get a configuration file using SALT_CONFIG_DIR, let's\n # update the environment with this information\n os.environ[env_var] = env_config_file_path\n\n overrides = load_config(path, env_var, DEFAULT_MASTER_OPTS['conf_file'])\n default_include = overrides.get('default_include',\n defaults['default_include'])\n include = overrides.get('include', [])\n\n overrides.update(include_config(default_include, path, verbose=False,\n exit_on_config_errors=exit_on_config_errors))\n overrides.update(include_config(include, path, verbose=True,\n exit_on_config_errors=exit_on_config_errors))\n opts = apply_master_config(overrides, defaults)\n _validate_ssh_minion_opts(opts)\n _validate_opts(opts)\n # If 'nodegroups:' is uncommented in the master config file, and there are\n # no nodegroups defined, opts['nodegroups'] will be None. Fix this by\n # reverting this value to the default, as if 'nodegroups:' was commented\n # out or not present.\n if opts.get('nodegroups') is None:\n opts['nodegroups'] = DEFAULT_MASTER_OPTS.get('nodegroups', {})\n if salt.utils.data.is_dictlist(opts['nodegroups']):\n opts['nodegroups'] = salt.utils.data.repack_dictlist(opts['nodegroups'])\n apply_sdb(opts)\n return opts\n", "def get_cached(self):\n '''\n queries the ConCache for a list of currently connected minions\n '''\n msg = self.serial.dumps('minions')\n self.creq_out.send(msg)\n min_list = self.serial.loads(self.creq_out.recv())\n return min_list\n", "def connected_ids(self, subset=None, show_ip=False, show_ipv4=None, include_localhost=None):\n '''\n Return a set of all connected minion ids, optionally within a subset\n '''\n if include_localhost is not None:\n salt.utils.versions.warn_until(\n 'Sodium',\n 'The \\'include_localhost\\' argument is no longer required; any'\n 'connected localhost minion will always be included.'\n )\n if show_ipv4 is not None:\n salt.utils.versions.warn_until(\n 'Sodium',\n 'The \\'show_ipv4\\' argument has been renamed to \\'show_ip\\' as'\n 'it now also includes IPv6 addresses for IPv6-connected'\n 'minions.'\n )\n minions = set()\n if self.opts.get('minion_data_cache', False):\n search = self.cache.list('minions')\n if search is None:\n return minions\n addrs = salt.utils.network.local_port_tcp(int(self.opts['publish_port']))\n if '127.0.0.1' in addrs:\n # Add in the address of a possible locally-connected minion.\n addrs.discard('127.0.0.1')\n addrs.update(set(salt.utils.network.ip_addrs(include_loopback=False)))\n if '::1' in addrs:\n # Add in the address of a possible locally-connected minion.\n addrs.discard('::1')\n addrs.update(set(salt.utils.network.ip_addrs6(include_loopback=False)))\n if subset:\n search = subset\n for id_ in search:\n try:\n mdata = self.cache.fetch('minions/{0}'.format(id_), 'data')\n except SaltCacheError:\n # If a SaltCacheError is explicitly raised during the fetch operation,\n # permission was denied to open the cached data.p file. Continue on as\n # in the releases <= 2016.3. (An explicit error raise was added in PR\n # #35388. See issue #36867 for more information.\n continue\n if mdata is None:\n continue\n grains = mdata.get('grains', {})\n for ipv4 in grains.get('ipv4', []):\n if ipv4 in addrs:\n if show_ip:\n minions.add((id_, ipv4))\n else:\n minions.add(id_)\n break\n for ipv6 in grains.get('ipv6', []):\n if ipv6 in addrs:\n if show_ip:\n minions.add((id_, ipv6))\n else:\n minions.add(id_)\n break\n return minions\n" ]
# -*- coding: utf-8 -*- ''' Wheel system wrapper for connected minions ''' # Import Python libs from __future__ import absolute_import, print_function, unicode_literals # Import Salt libs from salt.utils.cache import CacheCli import salt.config import salt.utils.minions
saltstack/salt
salt/cloud/clouds/digitalocean.py
get_configured_provider
python
def get_configured_provider(): ''' Return the first configured instance. ''' return config.is_provider_configured( opts=__opts__, provider=__active_provider_name__ or __virtualname__, aliases=__virtual_aliases__, required_keys=('personal_access_token',) )
Return the first configured instance.
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/digitalocean.py#L81-L90
[ "def is_provider_configured(opts, provider, required_keys=(), log_message=True, aliases=()):\n '''\n Check and return the first matching and fully configured cloud provider\n configuration.\n '''\n if ':' in provider:\n alias, driver = provider.split(':')\n if alias not in opts['providers']:\n return False\n if driver not in opts['providers'][alias]:\n return False\n for key in required_keys:\n if opts['providers'][alias][driver].get(key, None) is None:\n if log_message is True:\n # There's at least one require configuration key which is not\n # set.\n log.warning(\n \"The required '%s' configuration setting is missing \"\n \"from the '%s' driver, which is configured under the \"\n \"'%s' alias.\", key, provider, alias\n )\n return False\n # If we reached this far, there's a properly configured provider.\n # Return it!\n return opts['providers'][alias][driver]\n\n for alias, drivers in six.iteritems(opts['providers']):\n for driver, provider_details in six.iteritems(drivers):\n if driver != provider and driver not in aliases:\n continue\n\n # If we reached this far, we have a matching provider, let's see if\n # all required configuration keys are present and not None.\n skip_provider = False\n for key in required_keys:\n if provider_details.get(key, None) is None:\n if log_message is True:\n # This provider does not include all necessary keys,\n # continue to next one.\n log.warning(\n \"The required '%s' configuration setting is \"\n \"missing from the '%s' driver, which is configured \"\n \"under the '%s' alias.\", key, provider, alias\n )\n skip_provider = True\n break\n\n if skip_provider:\n continue\n\n # If we reached this far, the provider included all required keys\n return provider_details\n\n # If we reached this point, the provider is not configured.\n return False\n" ]
# -*- coding: utf-8 -*- ''' DigitalOcean Cloud Module ========================= The DigitalOcean cloud module is used to control access to the DigitalOcean VPS system. Use of this module requires a requires a ``personal_access_token``, an ``ssh_key_file``, and at least one SSH key name in ``ssh_key_names``. More ``ssh_key_names`` can be added by separating each key with a comma. The ``personal_access_token`` can be found in the DigitalOcean web interface in the "Apps & API" section. The SSH key name can be found under the "SSH Keys" section. .. code-block:: yaml # Note: This example is for /etc/salt/cloud.providers or any file in the # /etc/salt/cloud.providers.d/ directory. my-digital-ocean-config: personal_access_token: xxx ssh_key_file: /path/to/ssh/key/file ssh_key_names: my-key-name,my-key-name-2 driver: digitalocean :depends: requests ''' # Import Python Libs from __future__ import absolute_import, print_function, unicode_literals import decimal import logging import os import pprint import time # Import Salt Libs import salt.utils.cloud import salt.utils.files import salt.utils.json import salt.utils.stringutils import salt.config as config from salt.exceptions import ( SaltCloudConfigError, SaltInvocationError, SaltCloudNotFound, SaltCloudSystemExit, SaltCloudExecutionFailure, SaltCloudExecutionTimeout ) from salt.ext import six from salt.ext.six.moves import zip # Import Third Party Libs try: import requests HAS_REQUESTS = True except ImportError: HAS_REQUESTS = False # Get logging started log = logging.getLogger(__name__) __virtualname__ = 'digitalocean' __virtual_aliases__ = ('digital_ocean', 'do') # Only load in this module if the DIGITALOCEAN configurations are in place def __virtual__(): ''' Check for DigitalOcean configurations ''' if get_configured_provider() is False: return False if get_dependencies() is False: return False return __virtualname__ def get_dependencies(): ''' Warn if dependencies aren't met. ''' return config.check_driver_dependencies( __virtualname__, {'requests': HAS_REQUESTS} ) def avail_locations(call=None): ''' Return a dict of all available VM locations on the cloud provider with relevant data ''' if call == 'action': raise SaltCloudSystemExit( 'The avail_locations function must be called with ' '-f or --function, or with the --list-locations option' ) items = query(method='regions') ret = {} for region in items['regions']: ret[region['name']] = {} for item in six.iterkeys(region): ret[region['name']][item] = six.text_type(region[item]) return ret def avail_images(call=None): ''' Return a list of the images that are on the provider ''' if call == 'action': raise SaltCloudSystemExit( 'The avail_images function must be called with ' '-f or --function, or with the --list-images option' ) fetch = True page = 1 ret = {} while fetch: items = query(method='images', command='?page=' + six.text_type(page) + '&per_page=200') for image in items['images']: ret[image['name']] = {} for item in six.iterkeys(image): ret[image['name']][item] = image[item] page += 1 try: fetch = 'next' in items['links']['pages'] except KeyError: fetch = False return ret def avail_sizes(call=None): ''' Return a list of the image sizes that are on the provider ''' if call == 'action': raise SaltCloudSystemExit( 'The avail_sizes function must be called with ' '-f or --function, or with the --list-sizes option' ) items = query(method='sizes', command='?per_page=100') ret = {} for size in items['sizes']: ret[size['slug']] = {} for item in six.iterkeys(size): ret[size['slug']][item] = six.text_type(size[item]) 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.' ) return _list_nodes() def list_nodes_full(call=None, for_output=True): ''' 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.' ) return _list_nodes(full=True, for_output=for_output) 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('function'), __opts__['query.selection'], call, ) def get_image(vm_): ''' Return the image object to use ''' images = avail_images() vm_image = config.get_cloud_config_value( 'image', vm_, __opts__, search_global=False ) if not isinstance(vm_image, six.string_types): vm_image = six.text_type(vm_image) for image in images: if vm_image in (images[image]['name'], images[image]['slug'], images[image]['id']): if images[image]['slug'] is not None: return images[image]['slug'] return int(images[image]['id']) raise SaltCloudNotFound( 'The specified image, \'{0}\', could not be found.'.format(vm_image) ) def get_size(vm_): ''' Return the VM's size. Used by create_node(). ''' sizes = avail_sizes() vm_size = six.text_type(config.get_cloud_config_value( 'size', vm_, __opts__, search_global=False )) for size in sizes: if vm_size.lower() == sizes[size]['slug']: return sizes[size]['slug'] raise SaltCloudNotFound( 'The specified size, \'{0}\', could not be found.'.format(vm_size) ) def get_location(vm_): ''' Return the VM's location ''' locations = avail_locations() vm_location = six.text_type(config.get_cloud_config_value( 'location', vm_, __opts__, search_global=False )) for location in locations: if vm_location in (locations[location]['name'], locations[location]['slug']): return locations[location]['slug'] raise SaltCloudNotFound( 'The specified location, \'{0}\', could not be found.'.format( vm_location ) ) def create_node(args): ''' Create a node ''' node = query(method='droplets', args=args, http_method='post') return node 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 'digitalocean', vm_['profile'], vm_=vm_) is False: return False except AttributeError: pass __utils__['cloud.fire_event']( 'event', 'starting create', 'salt/cloud/{0}/creating'.format(vm_['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', vm_['name']) kwargs = { 'name': vm_['name'], 'size': get_size(vm_), 'image': get_image(vm_), 'region': get_location(vm_), 'ssh_keys': [], 'tags': [] } # backwards compat ssh_key_name = config.get_cloud_config_value( 'ssh_key_name', vm_, __opts__, search_global=False ) if ssh_key_name: kwargs['ssh_keys'].append(get_keyid(ssh_key_name)) ssh_key_names = config.get_cloud_config_value( 'ssh_key_names', vm_, __opts__, search_global=False, default=False ) if ssh_key_names: for key in ssh_key_names.split(','): kwargs['ssh_keys'].append(get_keyid(key)) key_filename = config.get_cloud_config_value( 'ssh_key_file', vm_, __opts__, search_global=False, default=None ) if key_filename is not None and not os.path.isfile(key_filename): raise SaltCloudConfigError( 'The defined key_filename \'{0}\' does not exist'.format( key_filename ) ) if not __opts__.get('ssh_agent', False) and key_filename is None: raise SaltCloudConfigError( 'The DigitalOcean driver requires an ssh_key_file and an ssh_key_name ' 'because it does not supply a root password upon building the server.' ) ssh_interface = config.get_cloud_config_value( 'ssh_interface', vm_, __opts__, search_global=False, default='public' ) if ssh_interface in ['private', 'public']: log.info("ssh_interface: Setting interface for ssh to %s", ssh_interface) kwargs['ssh_interface'] = ssh_interface else: raise SaltCloudConfigError( "The DigitalOcean driver requires ssh_interface to be defined as 'public' or 'private'." ) private_networking = config.get_cloud_config_value( 'private_networking', vm_, __opts__, search_global=False, default=None, ) if private_networking is not None: if not isinstance(private_networking, bool): raise SaltCloudConfigError("'private_networking' should be a boolean value.") kwargs['private_networking'] = private_networking if not private_networking and ssh_interface == 'private': raise SaltCloudConfigError( "The DigitalOcean driver requires ssh_interface if defined as 'private' " "then private_networking should be set as 'True'." ) backups_enabled = config.get_cloud_config_value( 'backups_enabled', vm_, __opts__, search_global=False, default=None, ) if backups_enabled is not None: if not isinstance(backups_enabled, bool): raise SaltCloudConfigError("'backups_enabled' should be a boolean value.") kwargs['backups'] = backups_enabled ipv6 = config.get_cloud_config_value( 'ipv6', vm_, __opts__, search_global=False, default=None, ) if ipv6 is not None: if not isinstance(ipv6, bool): raise SaltCloudConfigError("'ipv6' should be a boolean value.") kwargs['ipv6'] = ipv6 monitoring = config.get_cloud_config_value( 'monitoring', vm_, __opts__, search_global=False, default=None, ) if monitoring is not None: if not isinstance(monitoring, bool): raise SaltCloudConfigError("'monitoring' should be a boolean value.") kwargs['monitoring'] = monitoring kwargs['tags'] = config.get_cloud_config_value( 'tags', vm_, __opts__, search_global=False, default=False ) userdata_file = config.get_cloud_config_value( 'userdata_file', vm_, __opts__, search_global=False, default=None ) if userdata_file is not None: try: with salt.utils.files.fopen(userdata_file, 'r') as fp_: kwargs['user_data'] = salt.utils.cloud.userdata_template( __opts__, vm_, salt.utils.stringutils.to_unicode(fp_.read()) ) except Exception as exc: log.exception( 'Failed to read userdata from %s: %s', userdata_file, exc) create_dns_record = config.get_cloud_config_value( 'create_dns_record', vm_, __opts__, search_global=False, default=None, ) if create_dns_record: log.info('create_dns_record: will attempt to write DNS records') default_dns_domain = None dns_domain_name = vm_['name'].split('.') if len(dns_domain_name) > 2: log.debug('create_dns_record: inferring default dns_hostname, dns_domain from minion name as FQDN') default_dns_hostname = '.'.join(dns_domain_name[:-2]) default_dns_domain = '.'.join(dns_domain_name[-2:]) else: log.debug("create_dns_record: can't infer dns_domain from %s", vm_['name']) default_dns_hostname = dns_domain_name[0] dns_hostname = config.get_cloud_config_value( 'dns_hostname', vm_, __opts__, search_global=False, default=default_dns_hostname, ) dns_domain = config.get_cloud_config_value( 'dns_domain', vm_, __opts__, search_global=False, default=default_dns_domain, ) if dns_hostname and dns_domain: log.info('create_dns_record: using dns_hostname="%s", dns_domain="%s"', dns_hostname, dns_domain) __add_dns_addr__ = lambda t, d: post_dns_record(dns_domain=dns_domain, name=dns_hostname, record_type=t, record_data=d) log.debug('create_dns_record: %s', __add_dns_addr__) else: log.error('create_dns_record: could not determine dns_hostname and/or dns_domain') raise SaltCloudConfigError( '\'create_dns_record\' must be a dict specifying "domain" ' 'and "hostname" or the minion name must be an FQDN.' ) __utils__['cloud.fire_event']( 'event', 'requesting instance', 'salt/cloud/{0}/requesting'.format(vm_['name']), args=__utils__['cloud.filter_event']('requesting', kwargs, list(kwargs)), sock_dir=__opts__['sock_dir'], transport=__opts__['transport'] ) try: ret = create_node(kwargs) except Exception as exc: log.error( 'Error creating %s on DIGITALOCEAN\n\n' 'The following exception was thrown when trying to ' 'run the initial deployment: %s', vm_['name'], exc, # Show the traceback if the debug logging level is enabled exc_info_on_loglevel=logging.DEBUG ) return False def __query_node_data(vm_name): data = show_instance(vm_name, 'action') if not data: # Trigger an error in the wait_for_ip function return False if data['networks'].get('v4'): for network in data['networks']['v4']: if network['type'] == 'public': return data return False try: data = salt.utils.cloud.wait_for_ip( __query_node_data, update_args=(vm_['name'],), timeout=config.get_cloud_config_value( 'wait_for_ip_timeout', vm_, __opts__, default=10 * 60), interval=config.get_cloud_config_value( 'wait_for_ip_interval', vm_, __opts__, default=10), ) except (SaltCloudExecutionTimeout, SaltCloudExecutionFailure) as exc: try: # It might be already up, let's destroy it! destroy(vm_['name']) except SaltCloudSystemExit: pass finally: raise SaltCloudSystemExit(six.text_type(exc)) if not vm_.get('ssh_host'): vm_['ssh_host'] = None # add DNS records, set ssh_host, default to first found IP, preferring IPv4 for ssh bootstrap script target addr_families, dns_arec_types = (('v4', 'v6'), ('A', 'AAAA')) arec_map = dict(list(zip(addr_families, dns_arec_types))) for facing, addr_family, ip_address in [(net['type'], family, net['ip_address']) for family in addr_families for net in data['networks'][family]]: log.info('found %s IP%s interface for "%s"', facing, addr_family, ip_address) dns_rec_type = arec_map[addr_family] if facing == 'public': if create_dns_record: __add_dns_addr__(dns_rec_type, ip_address) if facing == ssh_interface: if not vm_['ssh_host']: vm_['ssh_host'] = ip_address if vm_['ssh_host'] is None: raise SaltCloudSystemExit( 'No suitable IP addresses found for ssh minion bootstrapping: {0}'.format(repr(data['networks'])) ) log.debug( 'Found public IP address to use for ssh minion bootstrapping: %s', vm_['ssh_host'] ) vm_['key_filename'] = key_filename ret = __utils__['cloud.bootstrap'](vm_, __opts__) ret.update(data) log.info('Created Cloud VM \'%s\'', vm_['name']) log.debug( '\'%s\' VM creation details:\n%s', vm_['name'], pprint.pformat(data) ) __utils__['cloud.fire_event']( 'event', 'created instance', 'salt/cloud/{0}/created'.format(vm_['name']), args=__utils__['cloud.filter_event']('created', vm_, ['name', 'profile', 'provider', 'driver']), sock_dir=__opts__['sock_dir'], transport=__opts__['transport'] ) return ret def query(method='droplets', droplet_id=None, command=None, args=None, http_method='get'): ''' Make a web call to DigitalOcean ''' base_path = six.text_type(config.get_cloud_config_value( 'api_root', get_configured_provider(), __opts__, search_global=False, default='https://api.digitalocean.com/v2' )) path = '{0}/{1}/'.format(base_path, method) if droplet_id: path += '{0}/'.format(droplet_id) if command: path += command if not isinstance(args, dict): args = {} personal_access_token = config.get_cloud_config_value( 'personal_access_token', get_configured_provider(), __opts__, search_global=False ) data = salt.utils.json.dumps(args) requester = getattr(requests, http_method) request = requester(path, data=data, headers={'Authorization': 'Bearer ' + personal_access_token, 'Content-Type': 'application/json'}) if request.status_code > 299: raise SaltCloudSystemExit( 'An error occurred while querying DigitalOcean. HTTP Code: {0} ' 'Error: \'{1}\''.format( request.status_code, # request.read() request.text ) ) log.debug(request.url) # success without data if request.status_code == 204: return True content = request.text result = salt.utils.json.loads(content) if result.get('status', '').lower() == 'error': raise SaltCloudSystemExit( pprint.pformat(result.get('error_message', {})) ) return result 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 show_instance(name, call=None): ''' Show the details from DigitalOcean concerning a droplet ''' if call != 'action': raise SaltCloudSystemExit( 'The show_instance action must be called with -a or --action.' ) node = _get_node(name) __utils__['cloud.cache_node'](node, __active_provider_name__, __opts__) return node def _get_node(name): attempts = 10 while attempts >= 0: try: return list_nodes_full(for_output=False)[name] except KeyError: attempts -= 1 log.debug( 'Failed to get the data for node \'%s\'. Remaining ' 'attempts: %s', name, attempts ) # Just a little delay between attempts... time.sleep(0.5) return {} def list_keypairs(call=None): ''' Return a dict of all available VM locations on the cloud provider with relevant data ''' if call != 'function': log.error( 'The list_keypairs function must be called with -f or --function.' ) return False fetch = True page = 1 ret = {} while fetch: items = query(method='account/keys', command='?page=' + six.text_type(page) + '&per_page=100') for key_pair in items['ssh_keys']: name = key_pair['name'] if name in ret: raise SaltCloudSystemExit( 'A duplicate key pair name, \'{0}\', was found in DigitalOcean\'s ' 'key pair list. Please change the key name stored by DigitalOcean. ' 'Be sure to adjust the value of \'ssh_key_file\' in your cloud ' 'profile or provider configuration, if necessary.'.format( name ) ) ret[name] = {} for item in six.iterkeys(key_pair): ret[name][item] = six.text_type(key_pair[item]) page += 1 try: fetch = 'next' in items['links']['pages'] except KeyError: fetch = False return ret def show_keypair(kwargs=None, call=None): ''' Show the details of an SSH keypair ''' if call != 'function': log.error( 'The show_keypair function must be called with -f or --function.' ) return False if not kwargs: kwargs = {} if 'keyname' not in kwargs: log.error('A keyname is required.') return False keypairs = list_keypairs(call='function') keyid = keypairs[kwargs['keyname']]['id'] log.debug('Key ID is %s', keyid) details = query(method='account/keys', command=keyid) return details def import_keypair(kwargs=None, call=None): ''' Upload public key to cloud provider. Similar to EC2 import_keypair. .. versionadded:: 2016.11.0 kwargs file(mandatory): public key file-name keyname(mandatory): public key name in the provider ''' with salt.utils.files.fopen(kwargs['file'], 'r') as public_key_filename: public_key_content = salt.utils.stringutils.to_unicode(public_key_filename.read()) digitalocean_kwargs = { 'name': kwargs['keyname'], 'public_key': public_key_content } created_result = create_key(digitalocean_kwargs, call=call) return created_result def create_key(kwargs=None, call=None): ''' Upload a public key ''' if call != 'function': log.error( 'The create_key function must be called with -f or --function.' ) return False try: result = query( method='account', command='keys', args={'name': kwargs['name'], 'public_key': kwargs['public_key']}, http_method='post' ) except KeyError: log.info('`name` and `public_key` arguments must be specified') return False return result def remove_key(kwargs=None, call=None): ''' Delete public key ''' if call != 'function': log.error( 'The create_key function must be called with -f or --function.' ) return False try: result = query( method='account', command='keys/' + kwargs['id'], http_method='delete' ) except KeyError: log.info('`id` argument must be specified') return False return result def get_keyid(keyname): ''' Return the ID of the keyname ''' if not keyname: return None keypairs = list_keypairs(call='function') keyid = keypairs[keyname]['id'] if keyid: return keyid raise SaltCloudNotFound('The specified ssh key could not be found.') def destroy(name, call=None): ''' Destroy a node. Will check termination protection and warn if enabled. 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'] ) data = show_instance(name, call='action') node = query(method='droplets', droplet_id=data['id'], http_method='delete') ## This is all terribly optomistic: # vm_ = get_vm_config(name=name) # delete_dns_record = config.get_cloud_config_value( # 'delete_dns_record', vm_, __opts__, search_global=False, default=None, # ) # TODO: when _vm config data can be made available, we should honor the configuration settings, # but until then, we should assume stale DNS records are bad, and default behavior should be to # delete them if we can. When this is resolved, also resolve the comments a couple of lines below. delete_dns_record = True if not isinstance(delete_dns_record, bool): raise SaltCloudConfigError( '\'delete_dns_record\' should be a boolean value.' ) # When the "to do" a few lines up is resolved, remove these lines and use the if/else logic below. log.debug('Deleting DNS records for %s.', name) destroy_dns_records(name) # Until the "to do" from line 754 is taken care of, we don't need this logic. # if delete_dns_record: # log.debug('Deleting DNS records for %s.', name) # destroy_dns_records(name) # else: # log.debug('delete_dns_record : %s', delete_dns_record) # for line in pprint.pformat(dir()).splitlines(): # log.debug('delete context: %s', line) __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 node def post_dns_record(**kwargs): ''' Creates a DNS record for the given name if the domain is managed with DO. ''' if 'kwargs' in kwargs: # flatten kwargs if called via salt-cloud -f f_kwargs = kwargs['kwargs'] del kwargs['kwargs'] kwargs.update(f_kwargs) mandatory_kwargs = ('dns_domain', 'name', 'record_type', 'record_data') for i in mandatory_kwargs: if kwargs[i]: pass else: error = '{0}="{1}" ## all mandatory args must be provided: {2}'.format(i, kwargs[i], mandatory_kwargs) raise SaltInvocationError(error) domain = query(method='domains', droplet_id=kwargs['dns_domain']) if domain: result = query( method='domains', droplet_id=kwargs['dns_domain'], command='records', args={'type': kwargs['record_type'], 'name': kwargs['name'], 'data': kwargs['record_data']}, http_method='post' ) return result return False def destroy_dns_records(fqdn): ''' Deletes DNS records for the given hostname if the domain is managed with DO. ''' domain = '.'.join(fqdn.split('.')[-2:]) hostname = '.'.join(fqdn.split('.')[:-2]) # TODO: remove this when the todo on 754 is available try: response = query(method='domains', droplet_id=domain, command='records') except SaltCloudSystemExit: log.debug('Failed to find domains.') return False log.debug("found DNS records: %s", pprint.pformat(response)) records = response['domain_records'] if records: record_ids = [r['id'] for r in records if r['name'].decode() == hostname] log.debug("deleting DNS record IDs: %s", record_ids) for id_ in record_ids: try: log.info('deleting DNS record %s', id_) ret = query( method='domains', droplet_id=domain, command='records/{0}'.format(id_), http_method='delete' ) except SaltCloudSystemExit: log.error('failed to delete DNS domain %s record ID %s.', domain, hostname) log.debug('DNS deletion REST call returned: %s', pprint.pformat(ret)) return False def show_pricing(kwargs=None, call=None): ''' Show pricing for a particular profile. This is only an estimate, based on unofficial pricing sources. .. versionadded:: 2015.8.0 CLI Examples: .. code-block:: bash salt-cloud -f show_pricing my-digitalocean-config profile=my-profile ''' profile = __opts__['profiles'].get(kwargs['profile'], {}) if not profile: return {'Error': 'The requested profile was not found'} # Make sure the profile belongs to DigitalOcean provider = profile.get('provider', '0:0') comps = provider.split(':') if len(comps) < 2 or comps[1] != 'digitalocean': return {'Error': 'The requested profile does not belong to DigitalOcean'} raw = {} ret = {} sizes = avail_sizes() ret['per_hour'] = decimal.Decimal(sizes[profile['size']]['price_hourly']) ret['per_day'] = ret['per_hour'] * 24 ret['per_week'] = ret['per_day'] * 7 ret['per_month'] = decimal.Decimal(sizes[profile['size']]['price_monthly']) ret['per_year'] = ret['per_week'] * 52 if kwargs.get('raw', False): ret['_raw'] = raw return {profile['profile']: ret} def list_floating_ips(call=None): ''' Return a list of the floating ips that are on the provider .. versionadded:: 2016.3.0 CLI Examples: .. code-block:: bash salt-cloud -f list_floating_ips my-digitalocean-config ''' if call == 'action': raise SaltCloudSystemExit( 'The list_floating_ips function must be called with ' '-f or --function, or with the --list-floating-ips option' ) fetch = True page = 1 ret = {} while fetch: items = query(method='floating_ips', command='?page=' + six.text_type(page) + '&per_page=200') for floating_ip in items['floating_ips']: ret[floating_ip['ip']] = {} for item in six.iterkeys(floating_ip): ret[floating_ip['ip']][item] = floating_ip[item] page += 1 try: fetch = 'next' in items['links']['pages'] except KeyError: fetch = False return ret def show_floating_ip(kwargs=None, call=None): ''' Show the details of a floating IP .. versionadded:: 2016.3.0 CLI Examples: .. code-block:: bash salt-cloud -f show_floating_ip my-digitalocean-config floating_ip='45.55.96.47' ''' if call != 'function': log.error( 'The show_floating_ip function must be called with -f or --function.' ) return False if not kwargs: kwargs = {} if 'floating_ip' not in kwargs: log.error('A floating IP is required.') return False floating_ip = kwargs['floating_ip'] log.debug('Floating ip is %s', floating_ip) details = query(method='floating_ips', command=floating_ip) return details def create_floating_ip(kwargs=None, call=None): ''' Create a new floating IP .. versionadded:: 2016.3.0 CLI Examples: .. code-block:: bash salt-cloud -f create_floating_ip my-digitalocean-config region='NYC2' salt-cloud -f create_floating_ip my-digitalocean-config droplet_id='1234567' ''' if call != 'function': log.error( 'The create_floating_ip function must be called with -f or --function.' ) return False if not kwargs: kwargs = {} if 'droplet_id' in kwargs: result = query(method='floating_ips', args={'droplet_id': kwargs['droplet_id']}, http_method='post') return result elif 'region' in kwargs: result = query(method='floating_ips', args={'region': kwargs['region']}, http_method='post') return result else: log.error('A droplet_id or region is required.') return False def delete_floating_ip(kwargs=None, call=None): ''' Delete a floating IP .. versionadded:: 2016.3.0 CLI Examples: .. code-block:: bash salt-cloud -f delete_floating_ip my-digitalocean-config floating_ip='45.55.96.47' ''' if call != 'function': log.error( 'The delete_floating_ip function must be called with -f or --function.' ) return False if not kwargs: kwargs = {} if 'floating_ip' not in kwargs: log.error('A floating IP is required.') return False floating_ip = kwargs['floating_ip'] log.debug('Floating ip is %s', kwargs['floating_ip']) result = query(method='floating_ips', command=floating_ip, http_method='delete') return result def assign_floating_ip(kwargs=None, call=None): ''' Assign a floating IP .. versionadded:: 2016.3.0 CLI Examples: .. code-block:: bash salt-cloud -f assign_floating_ip my-digitalocean-config droplet_id=1234567 floating_ip='45.55.96.47' ''' if call != 'function': log.error( 'The assign_floating_ip function must be called with -f or --function.' ) return False if not kwargs: kwargs = {} if 'floating_ip' and 'droplet_id' not in kwargs: log.error('A floating IP and droplet_id is required.') return False result = query(method='floating_ips', command=kwargs['floating_ip'] + '/actions', args={'droplet_id': kwargs['droplet_id'], 'type': 'assign'}, http_method='post') return result def unassign_floating_ip(kwargs=None, call=None): ''' Unassign a floating IP .. versionadded:: 2016.3.0 CLI Examples: .. code-block:: bash salt-cloud -f unassign_floating_ip my-digitalocean-config floating_ip='45.55.96.47' ''' if call != 'function': log.error( 'The inassign_floating_ip function must be called with -f or --function.' ) return False if not kwargs: kwargs = {} if 'floating_ip' not in kwargs: log.error('A floating IP is required.') return False result = query(method='floating_ips', command=kwargs['floating_ip'] + '/actions', args={'type': 'unassign'}, http_method='post') return result def _list_nodes(full=False, for_output=False): ''' Helper function to format and parse node data. ''' fetch = True page = 1 ret = {} while fetch: items = query(method='droplets', command='?page=' + six.text_type(page) + '&per_page=200') for node in items['droplets']: name = node['name'] ret[name] = {} if full: ret[name] = _get_full_output(node, for_output=for_output) else: public_ips, private_ips = _get_ips(node['networks']) ret[name] = { 'id': node['id'], 'image': node['image']['name'], 'name': name, 'private_ips': private_ips, 'public_ips': public_ips, 'size': node['size_slug'], 'state': six.text_type(node['status']), } page += 1 try: fetch = 'next' in items['links']['pages'] except KeyError: fetch = False return ret def reboot(name, call=None): ''' Reboot a droplet in DigitalOcean. .. versionadded:: 2015.8.8 name The name of the droplet to restart. CLI Example: .. code-block:: bash salt-cloud -a reboot droplet_name ''' if call != 'action': raise SaltCloudSystemExit( 'The restart action must be called with -a or --action.' ) data = show_instance(name, call='action') if data.get('status') == 'off': return {'success': True, 'action': 'stop', 'status': 'off', 'msg': 'Machine is already off.'} ret = query(droplet_id=data['id'], command='actions', args={'type': 'reboot'}, http_method='post') return {'success': True, 'action': ret['action']['type'], 'state': ret['action']['status']} def start(name, call=None): ''' Start a droplet in DigitalOcean. .. versionadded:: 2015.8.8 name The name of the droplet to start. CLI Example: .. code-block:: bash salt-cloud -a start droplet_name ''' if call != 'action': raise SaltCloudSystemExit( 'The start action must be called with -a or --action.' ) data = show_instance(name, call='action') if data.get('status') == 'active': return {'success': True, 'action': 'start', 'status': 'active', 'msg': 'Machine is already running.'} ret = query(droplet_id=data['id'], command='actions', args={'type': 'power_on'}, http_method='post') return {'success': True, 'action': ret['action']['type'], 'state': ret['action']['status']} def stop(name, call=None): ''' Stop a droplet in DigitalOcean. .. versionadded:: 2015.8.8 name The name of the droplet to stop. CLI Example: .. code-block:: bash salt-cloud -a stop droplet_name ''' if call != 'action': raise SaltCloudSystemExit( 'The stop action must be called with -a or --action.' ) data = show_instance(name, call='action') if data.get('status') == 'off': return {'success': True, 'action': 'stop', 'status': 'off', 'msg': 'Machine is already off.'} ret = query(droplet_id=data['id'], command='actions', args={'type': 'shutdown'}, http_method='post') return {'success': True, 'action': ret['action']['type'], 'state': ret['action']['status']} def _get_full_output(node, for_output=False): ''' Helper function for _list_nodes to loop through all node information. Returns a dictionary containing the full information of a node. ''' ret = {} for item in six.iterkeys(node): value = node[item] if value is not None and for_output: value = six.text_type(value) ret[item] = value return ret def _get_ips(networks): ''' Helper function for list_nodes. Returns public and private ip lists based on a given network dictionary. ''' v4s = networks.get('v4') v6s = networks.get('v6') public_ips = [] private_ips = [] if v4s: for item in v4s: ip_type = item.get('type') ip_address = item.get('ip_address') if ip_type == 'public': public_ips.append(ip_address) if ip_type == 'private': private_ips.append(ip_address) if v6s: for item in v6s: ip_type = item.get('type') ip_address = item.get('ip_address') if ip_type == 'public': public_ips.append(ip_address) if ip_type == 'private': private_ips.append(ip_address) return public_ips, private_ips
saltstack/salt
salt/cloud/clouds/digitalocean.py
avail_locations
python
def avail_locations(call=None): ''' Return a dict of all available VM locations on the cloud provider with relevant data ''' if call == 'action': raise SaltCloudSystemExit( 'The avail_locations function must be called with ' '-f or --function, or with the --list-locations option' ) items = query(method='regions') ret = {} for region in items['regions']: ret[region['name']] = {} for item in six.iterkeys(region): ret[region['name']][item] = six.text_type(region[item]) return ret
Return a dict of all available VM locations on the cloud provider with relevant data
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/digitalocean.py#L103-L121
[ "def iterkeys(d, **kw):\n return d.iterkeys(**kw)\n", "def query(method='droplets', droplet_id=None, command=None, args=None, http_method='get'):\n '''\n Make a web call to DigitalOcean\n '''\n base_path = six.text_type(config.get_cloud_config_value(\n 'api_root',\n get_configured_provider(),\n __opts__,\n search_global=False,\n default='https://api.digitalocean.com/v2'\n ))\n\n path = '{0}/{1}/'.format(base_path, method)\n\n if droplet_id:\n path += '{0}/'.format(droplet_id)\n\n if command:\n path += command\n\n if not isinstance(args, dict):\n args = {}\n\n personal_access_token = config.get_cloud_config_value(\n 'personal_access_token', get_configured_provider(), __opts__, search_global=False\n )\n\n data = salt.utils.json.dumps(args)\n\n requester = getattr(requests, http_method)\n request = requester(path, data=data, headers={'Authorization': 'Bearer ' + personal_access_token, 'Content-Type': 'application/json'})\n if request.status_code > 299:\n raise SaltCloudSystemExit(\n 'An error occurred while querying DigitalOcean. HTTP Code: {0} '\n 'Error: \\'{1}\\''.format(\n request.status_code,\n # request.read()\n request.text\n )\n )\n\n log.debug(request.url)\n\n # success without data\n if request.status_code == 204:\n return True\n\n content = request.text\n\n result = salt.utils.json.loads(content)\n if result.get('status', '').lower() == 'error':\n raise SaltCloudSystemExit(\n pprint.pformat(result.get('error_message', {}))\n )\n\n return result\n" ]
# -*- coding: utf-8 -*- ''' DigitalOcean Cloud Module ========================= The DigitalOcean cloud module is used to control access to the DigitalOcean VPS system. Use of this module requires a requires a ``personal_access_token``, an ``ssh_key_file``, and at least one SSH key name in ``ssh_key_names``. More ``ssh_key_names`` can be added by separating each key with a comma. The ``personal_access_token`` can be found in the DigitalOcean web interface in the "Apps & API" section. The SSH key name can be found under the "SSH Keys" section. .. code-block:: yaml # Note: This example is for /etc/salt/cloud.providers or any file in the # /etc/salt/cloud.providers.d/ directory. my-digital-ocean-config: personal_access_token: xxx ssh_key_file: /path/to/ssh/key/file ssh_key_names: my-key-name,my-key-name-2 driver: digitalocean :depends: requests ''' # Import Python Libs from __future__ import absolute_import, print_function, unicode_literals import decimal import logging import os import pprint import time # Import Salt Libs import salt.utils.cloud import salt.utils.files import salt.utils.json import salt.utils.stringutils import salt.config as config from salt.exceptions import ( SaltCloudConfigError, SaltInvocationError, SaltCloudNotFound, SaltCloudSystemExit, SaltCloudExecutionFailure, SaltCloudExecutionTimeout ) from salt.ext import six from salt.ext.six.moves import zip # Import Third Party Libs try: import requests HAS_REQUESTS = True except ImportError: HAS_REQUESTS = False # Get logging started log = logging.getLogger(__name__) __virtualname__ = 'digitalocean' __virtual_aliases__ = ('digital_ocean', 'do') # Only load in this module if the DIGITALOCEAN configurations are in place def __virtual__(): ''' Check for DigitalOcean 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=__opts__, provider=__active_provider_name__ or __virtualname__, aliases=__virtual_aliases__, required_keys=('personal_access_token',) ) def get_dependencies(): ''' Warn if dependencies aren't met. ''' return config.check_driver_dependencies( __virtualname__, {'requests': HAS_REQUESTS} ) def avail_images(call=None): ''' Return a list of the images that are on the provider ''' if call == 'action': raise SaltCloudSystemExit( 'The avail_images function must be called with ' '-f or --function, or with the --list-images option' ) fetch = True page = 1 ret = {} while fetch: items = query(method='images', command='?page=' + six.text_type(page) + '&per_page=200') for image in items['images']: ret[image['name']] = {} for item in six.iterkeys(image): ret[image['name']][item] = image[item] page += 1 try: fetch = 'next' in items['links']['pages'] except KeyError: fetch = False return ret def avail_sizes(call=None): ''' Return a list of the image sizes that are on the provider ''' if call == 'action': raise SaltCloudSystemExit( 'The avail_sizes function must be called with ' '-f or --function, or with the --list-sizes option' ) items = query(method='sizes', command='?per_page=100') ret = {} for size in items['sizes']: ret[size['slug']] = {} for item in six.iterkeys(size): ret[size['slug']][item] = six.text_type(size[item]) 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.' ) return _list_nodes() def list_nodes_full(call=None, for_output=True): ''' 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.' ) return _list_nodes(full=True, for_output=for_output) 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('function'), __opts__['query.selection'], call, ) def get_image(vm_): ''' Return the image object to use ''' images = avail_images() vm_image = config.get_cloud_config_value( 'image', vm_, __opts__, search_global=False ) if not isinstance(vm_image, six.string_types): vm_image = six.text_type(vm_image) for image in images: if vm_image in (images[image]['name'], images[image]['slug'], images[image]['id']): if images[image]['slug'] is not None: return images[image]['slug'] return int(images[image]['id']) raise SaltCloudNotFound( 'The specified image, \'{0}\', could not be found.'.format(vm_image) ) def get_size(vm_): ''' Return the VM's size. Used by create_node(). ''' sizes = avail_sizes() vm_size = six.text_type(config.get_cloud_config_value( 'size', vm_, __opts__, search_global=False )) for size in sizes: if vm_size.lower() == sizes[size]['slug']: return sizes[size]['slug'] raise SaltCloudNotFound( 'The specified size, \'{0}\', could not be found.'.format(vm_size) ) def get_location(vm_): ''' Return the VM's location ''' locations = avail_locations() vm_location = six.text_type(config.get_cloud_config_value( 'location', vm_, __opts__, search_global=False )) for location in locations: if vm_location in (locations[location]['name'], locations[location]['slug']): return locations[location]['slug'] raise SaltCloudNotFound( 'The specified location, \'{0}\', could not be found.'.format( vm_location ) ) def create_node(args): ''' Create a node ''' node = query(method='droplets', args=args, http_method='post') return node 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 'digitalocean', vm_['profile'], vm_=vm_) is False: return False except AttributeError: pass __utils__['cloud.fire_event']( 'event', 'starting create', 'salt/cloud/{0}/creating'.format(vm_['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', vm_['name']) kwargs = { 'name': vm_['name'], 'size': get_size(vm_), 'image': get_image(vm_), 'region': get_location(vm_), 'ssh_keys': [], 'tags': [] } # backwards compat ssh_key_name = config.get_cloud_config_value( 'ssh_key_name', vm_, __opts__, search_global=False ) if ssh_key_name: kwargs['ssh_keys'].append(get_keyid(ssh_key_name)) ssh_key_names = config.get_cloud_config_value( 'ssh_key_names', vm_, __opts__, search_global=False, default=False ) if ssh_key_names: for key in ssh_key_names.split(','): kwargs['ssh_keys'].append(get_keyid(key)) key_filename = config.get_cloud_config_value( 'ssh_key_file', vm_, __opts__, search_global=False, default=None ) if key_filename is not None and not os.path.isfile(key_filename): raise SaltCloudConfigError( 'The defined key_filename \'{0}\' does not exist'.format( key_filename ) ) if not __opts__.get('ssh_agent', False) and key_filename is None: raise SaltCloudConfigError( 'The DigitalOcean driver requires an ssh_key_file and an ssh_key_name ' 'because it does not supply a root password upon building the server.' ) ssh_interface = config.get_cloud_config_value( 'ssh_interface', vm_, __opts__, search_global=False, default='public' ) if ssh_interface in ['private', 'public']: log.info("ssh_interface: Setting interface for ssh to %s", ssh_interface) kwargs['ssh_interface'] = ssh_interface else: raise SaltCloudConfigError( "The DigitalOcean driver requires ssh_interface to be defined as 'public' or 'private'." ) private_networking = config.get_cloud_config_value( 'private_networking', vm_, __opts__, search_global=False, default=None, ) if private_networking is not None: if not isinstance(private_networking, bool): raise SaltCloudConfigError("'private_networking' should be a boolean value.") kwargs['private_networking'] = private_networking if not private_networking and ssh_interface == 'private': raise SaltCloudConfigError( "The DigitalOcean driver requires ssh_interface if defined as 'private' " "then private_networking should be set as 'True'." ) backups_enabled = config.get_cloud_config_value( 'backups_enabled', vm_, __opts__, search_global=False, default=None, ) if backups_enabled is not None: if not isinstance(backups_enabled, bool): raise SaltCloudConfigError("'backups_enabled' should be a boolean value.") kwargs['backups'] = backups_enabled ipv6 = config.get_cloud_config_value( 'ipv6', vm_, __opts__, search_global=False, default=None, ) if ipv6 is not None: if not isinstance(ipv6, bool): raise SaltCloudConfigError("'ipv6' should be a boolean value.") kwargs['ipv6'] = ipv6 monitoring = config.get_cloud_config_value( 'monitoring', vm_, __opts__, search_global=False, default=None, ) if monitoring is not None: if not isinstance(monitoring, bool): raise SaltCloudConfigError("'monitoring' should be a boolean value.") kwargs['monitoring'] = monitoring kwargs['tags'] = config.get_cloud_config_value( 'tags', vm_, __opts__, search_global=False, default=False ) userdata_file = config.get_cloud_config_value( 'userdata_file', vm_, __opts__, search_global=False, default=None ) if userdata_file is not None: try: with salt.utils.files.fopen(userdata_file, 'r') as fp_: kwargs['user_data'] = salt.utils.cloud.userdata_template( __opts__, vm_, salt.utils.stringutils.to_unicode(fp_.read()) ) except Exception as exc: log.exception( 'Failed to read userdata from %s: %s', userdata_file, exc) create_dns_record = config.get_cloud_config_value( 'create_dns_record', vm_, __opts__, search_global=False, default=None, ) if create_dns_record: log.info('create_dns_record: will attempt to write DNS records') default_dns_domain = None dns_domain_name = vm_['name'].split('.') if len(dns_domain_name) > 2: log.debug('create_dns_record: inferring default dns_hostname, dns_domain from minion name as FQDN') default_dns_hostname = '.'.join(dns_domain_name[:-2]) default_dns_domain = '.'.join(dns_domain_name[-2:]) else: log.debug("create_dns_record: can't infer dns_domain from %s", vm_['name']) default_dns_hostname = dns_domain_name[0] dns_hostname = config.get_cloud_config_value( 'dns_hostname', vm_, __opts__, search_global=False, default=default_dns_hostname, ) dns_domain = config.get_cloud_config_value( 'dns_domain', vm_, __opts__, search_global=False, default=default_dns_domain, ) if dns_hostname and dns_domain: log.info('create_dns_record: using dns_hostname="%s", dns_domain="%s"', dns_hostname, dns_domain) __add_dns_addr__ = lambda t, d: post_dns_record(dns_domain=dns_domain, name=dns_hostname, record_type=t, record_data=d) log.debug('create_dns_record: %s', __add_dns_addr__) else: log.error('create_dns_record: could not determine dns_hostname and/or dns_domain') raise SaltCloudConfigError( '\'create_dns_record\' must be a dict specifying "domain" ' 'and "hostname" or the minion name must be an FQDN.' ) __utils__['cloud.fire_event']( 'event', 'requesting instance', 'salt/cloud/{0}/requesting'.format(vm_['name']), args=__utils__['cloud.filter_event']('requesting', kwargs, list(kwargs)), sock_dir=__opts__['sock_dir'], transport=__opts__['transport'] ) try: ret = create_node(kwargs) except Exception as exc: log.error( 'Error creating %s on DIGITALOCEAN\n\n' 'The following exception was thrown when trying to ' 'run the initial deployment: %s', vm_['name'], exc, # Show the traceback if the debug logging level is enabled exc_info_on_loglevel=logging.DEBUG ) return False def __query_node_data(vm_name): data = show_instance(vm_name, 'action') if not data: # Trigger an error in the wait_for_ip function return False if data['networks'].get('v4'): for network in data['networks']['v4']: if network['type'] == 'public': return data return False try: data = salt.utils.cloud.wait_for_ip( __query_node_data, update_args=(vm_['name'],), timeout=config.get_cloud_config_value( 'wait_for_ip_timeout', vm_, __opts__, default=10 * 60), interval=config.get_cloud_config_value( 'wait_for_ip_interval', vm_, __opts__, default=10), ) except (SaltCloudExecutionTimeout, SaltCloudExecutionFailure) as exc: try: # It might be already up, let's destroy it! destroy(vm_['name']) except SaltCloudSystemExit: pass finally: raise SaltCloudSystemExit(six.text_type(exc)) if not vm_.get('ssh_host'): vm_['ssh_host'] = None # add DNS records, set ssh_host, default to first found IP, preferring IPv4 for ssh bootstrap script target addr_families, dns_arec_types = (('v4', 'v6'), ('A', 'AAAA')) arec_map = dict(list(zip(addr_families, dns_arec_types))) for facing, addr_family, ip_address in [(net['type'], family, net['ip_address']) for family in addr_families for net in data['networks'][family]]: log.info('found %s IP%s interface for "%s"', facing, addr_family, ip_address) dns_rec_type = arec_map[addr_family] if facing == 'public': if create_dns_record: __add_dns_addr__(dns_rec_type, ip_address) if facing == ssh_interface: if not vm_['ssh_host']: vm_['ssh_host'] = ip_address if vm_['ssh_host'] is None: raise SaltCloudSystemExit( 'No suitable IP addresses found for ssh minion bootstrapping: {0}'.format(repr(data['networks'])) ) log.debug( 'Found public IP address to use for ssh minion bootstrapping: %s', vm_['ssh_host'] ) vm_['key_filename'] = key_filename ret = __utils__['cloud.bootstrap'](vm_, __opts__) ret.update(data) log.info('Created Cloud VM \'%s\'', vm_['name']) log.debug( '\'%s\' VM creation details:\n%s', vm_['name'], pprint.pformat(data) ) __utils__['cloud.fire_event']( 'event', 'created instance', 'salt/cloud/{0}/created'.format(vm_['name']), args=__utils__['cloud.filter_event']('created', vm_, ['name', 'profile', 'provider', 'driver']), sock_dir=__opts__['sock_dir'], transport=__opts__['transport'] ) return ret def query(method='droplets', droplet_id=None, command=None, args=None, http_method='get'): ''' Make a web call to DigitalOcean ''' base_path = six.text_type(config.get_cloud_config_value( 'api_root', get_configured_provider(), __opts__, search_global=False, default='https://api.digitalocean.com/v2' )) path = '{0}/{1}/'.format(base_path, method) if droplet_id: path += '{0}/'.format(droplet_id) if command: path += command if not isinstance(args, dict): args = {} personal_access_token = config.get_cloud_config_value( 'personal_access_token', get_configured_provider(), __opts__, search_global=False ) data = salt.utils.json.dumps(args) requester = getattr(requests, http_method) request = requester(path, data=data, headers={'Authorization': 'Bearer ' + personal_access_token, 'Content-Type': 'application/json'}) if request.status_code > 299: raise SaltCloudSystemExit( 'An error occurred while querying DigitalOcean. HTTP Code: {0} ' 'Error: \'{1}\''.format( request.status_code, # request.read() request.text ) ) log.debug(request.url) # success without data if request.status_code == 204: return True content = request.text result = salt.utils.json.loads(content) if result.get('status', '').lower() == 'error': raise SaltCloudSystemExit( pprint.pformat(result.get('error_message', {})) ) return result 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 show_instance(name, call=None): ''' Show the details from DigitalOcean concerning a droplet ''' if call != 'action': raise SaltCloudSystemExit( 'The show_instance action must be called with -a or --action.' ) node = _get_node(name) __utils__['cloud.cache_node'](node, __active_provider_name__, __opts__) return node def _get_node(name): attempts = 10 while attempts >= 0: try: return list_nodes_full(for_output=False)[name] except KeyError: attempts -= 1 log.debug( 'Failed to get the data for node \'%s\'. Remaining ' 'attempts: %s', name, attempts ) # Just a little delay between attempts... time.sleep(0.5) return {} def list_keypairs(call=None): ''' Return a dict of all available VM locations on the cloud provider with relevant data ''' if call != 'function': log.error( 'The list_keypairs function must be called with -f or --function.' ) return False fetch = True page = 1 ret = {} while fetch: items = query(method='account/keys', command='?page=' + six.text_type(page) + '&per_page=100') for key_pair in items['ssh_keys']: name = key_pair['name'] if name in ret: raise SaltCloudSystemExit( 'A duplicate key pair name, \'{0}\', was found in DigitalOcean\'s ' 'key pair list. Please change the key name stored by DigitalOcean. ' 'Be sure to adjust the value of \'ssh_key_file\' in your cloud ' 'profile or provider configuration, if necessary.'.format( name ) ) ret[name] = {} for item in six.iterkeys(key_pair): ret[name][item] = six.text_type(key_pair[item]) page += 1 try: fetch = 'next' in items['links']['pages'] except KeyError: fetch = False return ret def show_keypair(kwargs=None, call=None): ''' Show the details of an SSH keypair ''' if call != 'function': log.error( 'The show_keypair function must be called with -f or --function.' ) return False if not kwargs: kwargs = {} if 'keyname' not in kwargs: log.error('A keyname is required.') return False keypairs = list_keypairs(call='function') keyid = keypairs[kwargs['keyname']]['id'] log.debug('Key ID is %s', keyid) details = query(method='account/keys', command=keyid) return details def import_keypair(kwargs=None, call=None): ''' Upload public key to cloud provider. Similar to EC2 import_keypair. .. versionadded:: 2016.11.0 kwargs file(mandatory): public key file-name keyname(mandatory): public key name in the provider ''' with salt.utils.files.fopen(kwargs['file'], 'r') as public_key_filename: public_key_content = salt.utils.stringutils.to_unicode(public_key_filename.read()) digitalocean_kwargs = { 'name': kwargs['keyname'], 'public_key': public_key_content } created_result = create_key(digitalocean_kwargs, call=call) return created_result def create_key(kwargs=None, call=None): ''' Upload a public key ''' if call != 'function': log.error( 'The create_key function must be called with -f or --function.' ) return False try: result = query( method='account', command='keys', args={'name': kwargs['name'], 'public_key': kwargs['public_key']}, http_method='post' ) except KeyError: log.info('`name` and `public_key` arguments must be specified') return False return result def remove_key(kwargs=None, call=None): ''' Delete public key ''' if call != 'function': log.error( 'The create_key function must be called with -f or --function.' ) return False try: result = query( method='account', command='keys/' + kwargs['id'], http_method='delete' ) except KeyError: log.info('`id` argument must be specified') return False return result def get_keyid(keyname): ''' Return the ID of the keyname ''' if not keyname: return None keypairs = list_keypairs(call='function') keyid = keypairs[keyname]['id'] if keyid: return keyid raise SaltCloudNotFound('The specified ssh key could not be found.') def destroy(name, call=None): ''' Destroy a node. Will check termination protection and warn if enabled. 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'] ) data = show_instance(name, call='action') node = query(method='droplets', droplet_id=data['id'], http_method='delete') ## This is all terribly optomistic: # vm_ = get_vm_config(name=name) # delete_dns_record = config.get_cloud_config_value( # 'delete_dns_record', vm_, __opts__, search_global=False, default=None, # ) # TODO: when _vm config data can be made available, we should honor the configuration settings, # but until then, we should assume stale DNS records are bad, and default behavior should be to # delete them if we can. When this is resolved, also resolve the comments a couple of lines below. delete_dns_record = True if not isinstance(delete_dns_record, bool): raise SaltCloudConfigError( '\'delete_dns_record\' should be a boolean value.' ) # When the "to do" a few lines up is resolved, remove these lines and use the if/else logic below. log.debug('Deleting DNS records for %s.', name) destroy_dns_records(name) # Until the "to do" from line 754 is taken care of, we don't need this logic. # if delete_dns_record: # log.debug('Deleting DNS records for %s.', name) # destroy_dns_records(name) # else: # log.debug('delete_dns_record : %s', delete_dns_record) # for line in pprint.pformat(dir()).splitlines(): # log.debug('delete context: %s', line) __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 node def post_dns_record(**kwargs): ''' Creates a DNS record for the given name if the domain is managed with DO. ''' if 'kwargs' in kwargs: # flatten kwargs if called via salt-cloud -f f_kwargs = kwargs['kwargs'] del kwargs['kwargs'] kwargs.update(f_kwargs) mandatory_kwargs = ('dns_domain', 'name', 'record_type', 'record_data') for i in mandatory_kwargs: if kwargs[i]: pass else: error = '{0}="{1}" ## all mandatory args must be provided: {2}'.format(i, kwargs[i], mandatory_kwargs) raise SaltInvocationError(error) domain = query(method='domains', droplet_id=kwargs['dns_domain']) if domain: result = query( method='domains', droplet_id=kwargs['dns_domain'], command='records', args={'type': kwargs['record_type'], 'name': kwargs['name'], 'data': kwargs['record_data']}, http_method='post' ) return result return False def destroy_dns_records(fqdn): ''' Deletes DNS records for the given hostname if the domain is managed with DO. ''' domain = '.'.join(fqdn.split('.')[-2:]) hostname = '.'.join(fqdn.split('.')[:-2]) # TODO: remove this when the todo on 754 is available try: response = query(method='domains', droplet_id=domain, command='records') except SaltCloudSystemExit: log.debug('Failed to find domains.') return False log.debug("found DNS records: %s", pprint.pformat(response)) records = response['domain_records'] if records: record_ids = [r['id'] for r in records if r['name'].decode() == hostname] log.debug("deleting DNS record IDs: %s", record_ids) for id_ in record_ids: try: log.info('deleting DNS record %s', id_) ret = query( method='domains', droplet_id=domain, command='records/{0}'.format(id_), http_method='delete' ) except SaltCloudSystemExit: log.error('failed to delete DNS domain %s record ID %s.', domain, hostname) log.debug('DNS deletion REST call returned: %s', pprint.pformat(ret)) return False def show_pricing(kwargs=None, call=None): ''' Show pricing for a particular profile. This is only an estimate, based on unofficial pricing sources. .. versionadded:: 2015.8.0 CLI Examples: .. code-block:: bash salt-cloud -f show_pricing my-digitalocean-config profile=my-profile ''' profile = __opts__['profiles'].get(kwargs['profile'], {}) if not profile: return {'Error': 'The requested profile was not found'} # Make sure the profile belongs to DigitalOcean provider = profile.get('provider', '0:0') comps = provider.split(':') if len(comps) < 2 or comps[1] != 'digitalocean': return {'Error': 'The requested profile does not belong to DigitalOcean'} raw = {} ret = {} sizes = avail_sizes() ret['per_hour'] = decimal.Decimal(sizes[profile['size']]['price_hourly']) ret['per_day'] = ret['per_hour'] * 24 ret['per_week'] = ret['per_day'] * 7 ret['per_month'] = decimal.Decimal(sizes[profile['size']]['price_monthly']) ret['per_year'] = ret['per_week'] * 52 if kwargs.get('raw', False): ret['_raw'] = raw return {profile['profile']: ret} def list_floating_ips(call=None): ''' Return a list of the floating ips that are on the provider .. versionadded:: 2016.3.0 CLI Examples: .. code-block:: bash salt-cloud -f list_floating_ips my-digitalocean-config ''' if call == 'action': raise SaltCloudSystemExit( 'The list_floating_ips function must be called with ' '-f or --function, or with the --list-floating-ips option' ) fetch = True page = 1 ret = {} while fetch: items = query(method='floating_ips', command='?page=' + six.text_type(page) + '&per_page=200') for floating_ip in items['floating_ips']: ret[floating_ip['ip']] = {} for item in six.iterkeys(floating_ip): ret[floating_ip['ip']][item] = floating_ip[item] page += 1 try: fetch = 'next' in items['links']['pages'] except KeyError: fetch = False return ret def show_floating_ip(kwargs=None, call=None): ''' Show the details of a floating IP .. versionadded:: 2016.3.0 CLI Examples: .. code-block:: bash salt-cloud -f show_floating_ip my-digitalocean-config floating_ip='45.55.96.47' ''' if call != 'function': log.error( 'The show_floating_ip function must be called with -f or --function.' ) return False if not kwargs: kwargs = {} if 'floating_ip' not in kwargs: log.error('A floating IP is required.') return False floating_ip = kwargs['floating_ip'] log.debug('Floating ip is %s', floating_ip) details = query(method='floating_ips', command=floating_ip) return details def create_floating_ip(kwargs=None, call=None): ''' Create a new floating IP .. versionadded:: 2016.3.0 CLI Examples: .. code-block:: bash salt-cloud -f create_floating_ip my-digitalocean-config region='NYC2' salt-cloud -f create_floating_ip my-digitalocean-config droplet_id='1234567' ''' if call != 'function': log.error( 'The create_floating_ip function must be called with -f or --function.' ) return False if not kwargs: kwargs = {} if 'droplet_id' in kwargs: result = query(method='floating_ips', args={'droplet_id': kwargs['droplet_id']}, http_method='post') return result elif 'region' in kwargs: result = query(method='floating_ips', args={'region': kwargs['region']}, http_method='post') return result else: log.error('A droplet_id or region is required.') return False def delete_floating_ip(kwargs=None, call=None): ''' Delete a floating IP .. versionadded:: 2016.3.0 CLI Examples: .. code-block:: bash salt-cloud -f delete_floating_ip my-digitalocean-config floating_ip='45.55.96.47' ''' if call != 'function': log.error( 'The delete_floating_ip function must be called with -f or --function.' ) return False if not kwargs: kwargs = {} if 'floating_ip' not in kwargs: log.error('A floating IP is required.') return False floating_ip = kwargs['floating_ip'] log.debug('Floating ip is %s', kwargs['floating_ip']) result = query(method='floating_ips', command=floating_ip, http_method='delete') return result def assign_floating_ip(kwargs=None, call=None): ''' Assign a floating IP .. versionadded:: 2016.3.0 CLI Examples: .. code-block:: bash salt-cloud -f assign_floating_ip my-digitalocean-config droplet_id=1234567 floating_ip='45.55.96.47' ''' if call != 'function': log.error( 'The assign_floating_ip function must be called with -f or --function.' ) return False if not kwargs: kwargs = {} if 'floating_ip' and 'droplet_id' not in kwargs: log.error('A floating IP and droplet_id is required.') return False result = query(method='floating_ips', command=kwargs['floating_ip'] + '/actions', args={'droplet_id': kwargs['droplet_id'], 'type': 'assign'}, http_method='post') return result def unassign_floating_ip(kwargs=None, call=None): ''' Unassign a floating IP .. versionadded:: 2016.3.0 CLI Examples: .. code-block:: bash salt-cloud -f unassign_floating_ip my-digitalocean-config floating_ip='45.55.96.47' ''' if call != 'function': log.error( 'The inassign_floating_ip function must be called with -f or --function.' ) return False if not kwargs: kwargs = {} if 'floating_ip' not in kwargs: log.error('A floating IP is required.') return False result = query(method='floating_ips', command=kwargs['floating_ip'] + '/actions', args={'type': 'unassign'}, http_method='post') return result def _list_nodes(full=False, for_output=False): ''' Helper function to format and parse node data. ''' fetch = True page = 1 ret = {} while fetch: items = query(method='droplets', command='?page=' + six.text_type(page) + '&per_page=200') for node in items['droplets']: name = node['name'] ret[name] = {} if full: ret[name] = _get_full_output(node, for_output=for_output) else: public_ips, private_ips = _get_ips(node['networks']) ret[name] = { 'id': node['id'], 'image': node['image']['name'], 'name': name, 'private_ips': private_ips, 'public_ips': public_ips, 'size': node['size_slug'], 'state': six.text_type(node['status']), } page += 1 try: fetch = 'next' in items['links']['pages'] except KeyError: fetch = False return ret def reboot(name, call=None): ''' Reboot a droplet in DigitalOcean. .. versionadded:: 2015.8.8 name The name of the droplet to restart. CLI Example: .. code-block:: bash salt-cloud -a reboot droplet_name ''' if call != 'action': raise SaltCloudSystemExit( 'The restart action must be called with -a or --action.' ) data = show_instance(name, call='action') if data.get('status') == 'off': return {'success': True, 'action': 'stop', 'status': 'off', 'msg': 'Machine is already off.'} ret = query(droplet_id=data['id'], command='actions', args={'type': 'reboot'}, http_method='post') return {'success': True, 'action': ret['action']['type'], 'state': ret['action']['status']} def start(name, call=None): ''' Start a droplet in DigitalOcean. .. versionadded:: 2015.8.8 name The name of the droplet to start. CLI Example: .. code-block:: bash salt-cloud -a start droplet_name ''' if call != 'action': raise SaltCloudSystemExit( 'The start action must be called with -a or --action.' ) data = show_instance(name, call='action') if data.get('status') == 'active': return {'success': True, 'action': 'start', 'status': 'active', 'msg': 'Machine is already running.'} ret = query(droplet_id=data['id'], command='actions', args={'type': 'power_on'}, http_method='post') return {'success': True, 'action': ret['action']['type'], 'state': ret['action']['status']} def stop(name, call=None): ''' Stop a droplet in DigitalOcean. .. versionadded:: 2015.8.8 name The name of the droplet to stop. CLI Example: .. code-block:: bash salt-cloud -a stop droplet_name ''' if call != 'action': raise SaltCloudSystemExit( 'The stop action must be called with -a or --action.' ) data = show_instance(name, call='action') if data.get('status') == 'off': return {'success': True, 'action': 'stop', 'status': 'off', 'msg': 'Machine is already off.'} ret = query(droplet_id=data['id'], command='actions', args={'type': 'shutdown'}, http_method='post') return {'success': True, 'action': ret['action']['type'], 'state': ret['action']['status']} def _get_full_output(node, for_output=False): ''' Helper function for _list_nodes to loop through all node information. Returns a dictionary containing the full information of a node. ''' ret = {} for item in six.iterkeys(node): value = node[item] if value is not None and for_output: value = six.text_type(value) ret[item] = value return ret def _get_ips(networks): ''' Helper function for list_nodes. Returns public and private ip lists based on a given network dictionary. ''' v4s = networks.get('v4') v6s = networks.get('v6') public_ips = [] private_ips = [] if v4s: for item in v4s: ip_type = item.get('type') ip_address = item.get('ip_address') if ip_type == 'public': public_ips.append(ip_address) if ip_type == 'private': private_ips.append(ip_address) if v6s: for item in v6s: ip_type = item.get('type') ip_address = item.get('ip_address') if ip_type == 'public': public_ips.append(ip_address) if ip_type == 'private': private_ips.append(ip_address) return public_ips, private_ips
saltstack/salt
salt/cloud/clouds/digitalocean.py
avail_images
python
def avail_images(call=None): ''' Return a list of the images that are on the provider ''' if call == 'action': raise SaltCloudSystemExit( 'The avail_images function must be called with ' '-f or --function, or with the --list-images option' ) fetch = True page = 1 ret = {} while fetch: items = query(method='images', command='?page=' + six.text_type(page) + '&per_page=200') for image in items['images']: ret[image['name']] = {} for item in six.iterkeys(image): ret[image['name']][item] = image[item] page += 1 try: fetch = 'next' in items['links']['pages'] except KeyError: fetch = False return ret
Return a list of the images that are on the provider
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/digitalocean.py#L124-L152
[ "def iterkeys(d, **kw):\n return d.iterkeys(**kw)\n", "def query(method='droplets', droplet_id=None, command=None, args=None, http_method='get'):\n '''\n Make a web call to DigitalOcean\n '''\n base_path = six.text_type(config.get_cloud_config_value(\n 'api_root',\n get_configured_provider(),\n __opts__,\n search_global=False,\n default='https://api.digitalocean.com/v2'\n ))\n\n path = '{0}/{1}/'.format(base_path, method)\n\n if droplet_id:\n path += '{0}/'.format(droplet_id)\n\n if command:\n path += command\n\n if not isinstance(args, dict):\n args = {}\n\n personal_access_token = config.get_cloud_config_value(\n 'personal_access_token', get_configured_provider(), __opts__, search_global=False\n )\n\n data = salt.utils.json.dumps(args)\n\n requester = getattr(requests, http_method)\n request = requester(path, data=data, headers={'Authorization': 'Bearer ' + personal_access_token, 'Content-Type': 'application/json'})\n if request.status_code > 299:\n raise SaltCloudSystemExit(\n 'An error occurred while querying DigitalOcean. HTTP Code: {0} '\n 'Error: \\'{1}\\''.format(\n request.status_code,\n # request.read()\n request.text\n )\n )\n\n log.debug(request.url)\n\n # success without data\n if request.status_code == 204:\n return True\n\n content = request.text\n\n result = salt.utils.json.loads(content)\n if result.get('status', '').lower() == 'error':\n raise SaltCloudSystemExit(\n pprint.pformat(result.get('error_message', {}))\n )\n\n return result\n" ]
# -*- coding: utf-8 -*- ''' DigitalOcean Cloud Module ========================= The DigitalOcean cloud module is used to control access to the DigitalOcean VPS system. Use of this module requires a requires a ``personal_access_token``, an ``ssh_key_file``, and at least one SSH key name in ``ssh_key_names``. More ``ssh_key_names`` can be added by separating each key with a comma. The ``personal_access_token`` can be found in the DigitalOcean web interface in the "Apps & API" section. The SSH key name can be found under the "SSH Keys" section. .. code-block:: yaml # Note: This example is for /etc/salt/cloud.providers or any file in the # /etc/salt/cloud.providers.d/ directory. my-digital-ocean-config: personal_access_token: xxx ssh_key_file: /path/to/ssh/key/file ssh_key_names: my-key-name,my-key-name-2 driver: digitalocean :depends: requests ''' # Import Python Libs from __future__ import absolute_import, print_function, unicode_literals import decimal import logging import os import pprint import time # Import Salt Libs import salt.utils.cloud import salt.utils.files import salt.utils.json import salt.utils.stringutils import salt.config as config from salt.exceptions import ( SaltCloudConfigError, SaltInvocationError, SaltCloudNotFound, SaltCloudSystemExit, SaltCloudExecutionFailure, SaltCloudExecutionTimeout ) from salt.ext import six from salt.ext.six.moves import zip # Import Third Party Libs try: import requests HAS_REQUESTS = True except ImportError: HAS_REQUESTS = False # Get logging started log = logging.getLogger(__name__) __virtualname__ = 'digitalocean' __virtual_aliases__ = ('digital_ocean', 'do') # Only load in this module if the DIGITALOCEAN configurations are in place def __virtual__(): ''' Check for DigitalOcean 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=__opts__, provider=__active_provider_name__ or __virtualname__, aliases=__virtual_aliases__, required_keys=('personal_access_token',) ) def get_dependencies(): ''' Warn if dependencies aren't met. ''' return config.check_driver_dependencies( __virtualname__, {'requests': HAS_REQUESTS} ) def avail_locations(call=None): ''' Return a dict of all available VM locations on the cloud provider with relevant data ''' if call == 'action': raise SaltCloudSystemExit( 'The avail_locations function must be called with ' '-f or --function, or with the --list-locations option' ) items = query(method='regions') ret = {} for region in items['regions']: ret[region['name']] = {} for item in six.iterkeys(region): ret[region['name']][item] = six.text_type(region[item]) return ret def avail_sizes(call=None): ''' Return a list of the image sizes that are on the provider ''' if call == 'action': raise SaltCloudSystemExit( 'The avail_sizes function must be called with ' '-f or --function, or with the --list-sizes option' ) items = query(method='sizes', command='?per_page=100') ret = {} for size in items['sizes']: ret[size['slug']] = {} for item in six.iterkeys(size): ret[size['slug']][item] = six.text_type(size[item]) 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.' ) return _list_nodes() def list_nodes_full(call=None, for_output=True): ''' 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.' ) return _list_nodes(full=True, for_output=for_output) 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('function'), __opts__['query.selection'], call, ) def get_image(vm_): ''' Return the image object to use ''' images = avail_images() vm_image = config.get_cloud_config_value( 'image', vm_, __opts__, search_global=False ) if not isinstance(vm_image, six.string_types): vm_image = six.text_type(vm_image) for image in images: if vm_image in (images[image]['name'], images[image]['slug'], images[image]['id']): if images[image]['slug'] is not None: return images[image]['slug'] return int(images[image]['id']) raise SaltCloudNotFound( 'The specified image, \'{0}\', could not be found.'.format(vm_image) ) def get_size(vm_): ''' Return the VM's size. Used by create_node(). ''' sizes = avail_sizes() vm_size = six.text_type(config.get_cloud_config_value( 'size', vm_, __opts__, search_global=False )) for size in sizes: if vm_size.lower() == sizes[size]['slug']: return sizes[size]['slug'] raise SaltCloudNotFound( 'The specified size, \'{0}\', could not be found.'.format(vm_size) ) def get_location(vm_): ''' Return the VM's location ''' locations = avail_locations() vm_location = six.text_type(config.get_cloud_config_value( 'location', vm_, __opts__, search_global=False )) for location in locations: if vm_location in (locations[location]['name'], locations[location]['slug']): return locations[location]['slug'] raise SaltCloudNotFound( 'The specified location, \'{0}\', could not be found.'.format( vm_location ) ) def create_node(args): ''' Create a node ''' node = query(method='droplets', args=args, http_method='post') return node 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 'digitalocean', vm_['profile'], vm_=vm_) is False: return False except AttributeError: pass __utils__['cloud.fire_event']( 'event', 'starting create', 'salt/cloud/{0}/creating'.format(vm_['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', vm_['name']) kwargs = { 'name': vm_['name'], 'size': get_size(vm_), 'image': get_image(vm_), 'region': get_location(vm_), 'ssh_keys': [], 'tags': [] } # backwards compat ssh_key_name = config.get_cloud_config_value( 'ssh_key_name', vm_, __opts__, search_global=False ) if ssh_key_name: kwargs['ssh_keys'].append(get_keyid(ssh_key_name)) ssh_key_names = config.get_cloud_config_value( 'ssh_key_names', vm_, __opts__, search_global=False, default=False ) if ssh_key_names: for key in ssh_key_names.split(','): kwargs['ssh_keys'].append(get_keyid(key)) key_filename = config.get_cloud_config_value( 'ssh_key_file', vm_, __opts__, search_global=False, default=None ) if key_filename is not None and not os.path.isfile(key_filename): raise SaltCloudConfigError( 'The defined key_filename \'{0}\' does not exist'.format( key_filename ) ) if not __opts__.get('ssh_agent', False) and key_filename is None: raise SaltCloudConfigError( 'The DigitalOcean driver requires an ssh_key_file and an ssh_key_name ' 'because it does not supply a root password upon building the server.' ) ssh_interface = config.get_cloud_config_value( 'ssh_interface', vm_, __opts__, search_global=False, default='public' ) if ssh_interface in ['private', 'public']: log.info("ssh_interface: Setting interface for ssh to %s", ssh_interface) kwargs['ssh_interface'] = ssh_interface else: raise SaltCloudConfigError( "The DigitalOcean driver requires ssh_interface to be defined as 'public' or 'private'." ) private_networking = config.get_cloud_config_value( 'private_networking', vm_, __opts__, search_global=False, default=None, ) if private_networking is not None: if not isinstance(private_networking, bool): raise SaltCloudConfigError("'private_networking' should be a boolean value.") kwargs['private_networking'] = private_networking if not private_networking and ssh_interface == 'private': raise SaltCloudConfigError( "The DigitalOcean driver requires ssh_interface if defined as 'private' " "then private_networking should be set as 'True'." ) backups_enabled = config.get_cloud_config_value( 'backups_enabled', vm_, __opts__, search_global=False, default=None, ) if backups_enabled is not None: if not isinstance(backups_enabled, bool): raise SaltCloudConfigError("'backups_enabled' should be a boolean value.") kwargs['backups'] = backups_enabled ipv6 = config.get_cloud_config_value( 'ipv6', vm_, __opts__, search_global=False, default=None, ) if ipv6 is not None: if not isinstance(ipv6, bool): raise SaltCloudConfigError("'ipv6' should be a boolean value.") kwargs['ipv6'] = ipv6 monitoring = config.get_cloud_config_value( 'monitoring', vm_, __opts__, search_global=False, default=None, ) if monitoring is not None: if not isinstance(monitoring, bool): raise SaltCloudConfigError("'monitoring' should be a boolean value.") kwargs['monitoring'] = monitoring kwargs['tags'] = config.get_cloud_config_value( 'tags', vm_, __opts__, search_global=False, default=False ) userdata_file = config.get_cloud_config_value( 'userdata_file', vm_, __opts__, search_global=False, default=None ) if userdata_file is not None: try: with salt.utils.files.fopen(userdata_file, 'r') as fp_: kwargs['user_data'] = salt.utils.cloud.userdata_template( __opts__, vm_, salt.utils.stringutils.to_unicode(fp_.read()) ) except Exception as exc: log.exception( 'Failed to read userdata from %s: %s', userdata_file, exc) create_dns_record = config.get_cloud_config_value( 'create_dns_record', vm_, __opts__, search_global=False, default=None, ) if create_dns_record: log.info('create_dns_record: will attempt to write DNS records') default_dns_domain = None dns_domain_name = vm_['name'].split('.') if len(dns_domain_name) > 2: log.debug('create_dns_record: inferring default dns_hostname, dns_domain from minion name as FQDN') default_dns_hostname = '.'.join(dns_domain_name[:-2]) default_dns_domain = '.'.join(dns_domain_name[-2:]) else: log.debug("create_dns_record: can't infer dns_domain from %s", vm_['name']) default_dns_hostname = dns_domain_name[0] dns_hostname = config.get_cloud_config_value( 'dns_hostname', vm_, __opts__, search_global=False, default=default_dns_hostname, ) dns_domain = config.get_cloud_config_value( 'dns_domain', vm_, __opts__, search_global=False, default=default_dns_domain, ) if dns_hostname and dns_domain: log.info('create_dns_record: using dns_hostname="%s", dns_domain="%s"', dns_hostname, dns_domain) __add_dns_addr__ = lambda t, d: post_dns_record(dns_domain=dns_domain, name=dns_hostname, record_type=t, record_data=d) log.debug('create_dns_record: %s', __add_dns_addr__) else: log.error('create_dns_record: could not determine dns_hostname and/or dns_domain') raise SaltCloudConfigError( '\'create_dns_record\' must be a dict specifying "domain" ' 'and "hostname" or the minion name must be an FQDN.' ) __utils__['cloud.fire_event']( 'event', 'requesting instance', 'salt/cloud/{0}/requesting'.format(vm_['name']), args=__utils__['cloud.filter_event']('requesting', kwargs, list(kwargs)), sock_dir=__opts__['sock_dir'], transport=__opts__['transport'] ) try: ret = create_node(kwargs) except Exception as exc: log.error( 'Error creating %s on DIGITALOCEAN\n\n' 'The following exception was thrown when trying to ' 'run the initial deployment: %s', vm_['name'], exc, # Show the traceback if the debug logging level is enabled exc_info_on_loglevel=logging.DEBUG ) return False def __query_node_data(vm_name): data = show_instance(vm_name, 'action') if not data: # Trigger an error in the wait_for_ip function return False if data['networks'].get('v4'): for network in data['networks']['v4']: if network['type'] == 'public': return data return False try: data = salt.utils.cloud.wait_for_ip( __query_node_data, update_args=(vm_['name'],), timeout=config.get_cloud_config_value( 'wait_for_ip_timeout', vm_, __opts__, default=10 * 60), interval=config.get_cloud_config_value( 'wait_for_ip_interval', vm_, __opts__, default=10), ) except (SaltCloudExecutionTimeout, SaltCloudExecutionFailure) as exc: try: # It might be already up, let's destroy it! destroy(vm_['name']) except SaltCloudSystemExit: pass finally: raise SaltCloudSystemExit(six.text_type(exc)) if not vm_.get('ssh_host'): vm_['ssh_host'] = None # add DNS records, set ssh_host, default to first found IP, preferring IPv4 for ssh bootstrap script target addr_families, dns_arec_types = (('v4', 'v6'), ('A', 'AAAA')) arec_map = dict(list(zip(addr_families, dns_arec_types))) for facing, addr_family, ip_address in [(net['type'], family, net['ip_address']) for family in addr_families for net in data['networks'][family]]: log.info('found %s IP%s interface for "%s"', facing, addr_family, ip_address) dns_rec_type = arec_map[addr_family] if facing == 'public': if create_dns_record: __add_dns_addr__(dns_rec_type, ip_address) if facing == ssh_interface: if not vm_['ssh_host']: vm_['ssh_host'] = ip_address if vm_['ssh_host'] is None: raise SaltCloudSystemExit( 'No suitable IP addresses found for ssh minion bootstrapping: {0}'.format(repr(data['networks'])) ) log.debug( 'Found public IP address to use for ssh minion bootstrapping: %s', vm_['ssh_host'] ) vm_['key_filename'] = key_filename ret = __utils__['cloud.bootstrap'](vm_, __opts__) ret.update(data) log.info('Created Cloud VM \'%s\'', vm_['name']) log.debug( '\'%s\' VM creation details:\n%s', vm_['name'], pprint.pformat(data) ) __utils__['cloud.fire_event']( 'event', 'created instance', 'salt/cloud/{0}/created'.format(vm_['name']), args=__utils__['cloud.filter_event']('created', vm_, ['name', 'profile', 'provider', 'driver']), sock_dir=__opts__['sock_dir'], transport=__opts__['transport'] ) return ret def query(method='droplets', droplet_id=None, command=None, args=None, http_method='get'): ''' Make a web call to DigitalOcean ''' base_path = six.text_type(config.get_cloud_config_value( 'api_root', get_configured_provider(), __opts__, search_global=False, default='https://api.digitalocean.com/v2' )) path = '{0}/{1}/'.format(base_path, method) if droplet_id: path += '{0}/'.format(droplet_id) if command: path += command if not isinstance(args, dict): args = {} personal_access_token = config.get_cloud_config_value( 'personal_access_token', get_configured_provider(), __opts__, search_global=False ) data = salt.utils.json.dumps(args) requester = getattr(requests, http_method) request = requester(path, data=data, headers={'Authorization': 'Bearer ' + personal_access_token, 'Content-Type': 'application/json'}) if request.status_code > 299: raise SaltCloudSystemExit( 'An error occurred while querying DigitalOcean. HTTP Code: {0} ' 'Error: \'{1}\''.format( request.status_code, # request.read() request.text ) ) log.debug(request.url) # success without data if request.status_code == 204: return True content = request.text result = salt.utils.json.loads(content) if result.get('status', '').lower() == 'error': raise SaltCloudSystemExit( pprint.pformat(result.get('error_message', {})) ) return result 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 show_instance(name, call=None): ''' Show the details from DigitalOcean concerning a droplet ''' if call != 'action': raise SaltCloudSystemExit( 'The show_instance action must be called with -a or --action.' ) node = _get_node(name) __utils__['cloud.cache_node'](node, __active_provider_name__, __opts__) return node def _get_node(name): attempts = 10 while attempts >= 0: try: return list_nodes_full(for_output=False)[name] except KeyError: attempts -= 1 log.debug( 'Failed to get the data for node \'%s\'. Remaining ' 'attempts: %s', name, attempts ) # Just a little delay between attempts... time.sleep(0.5) return {} def list_keypairs(call=None): ''' Return a dict of all available VM locations on the cloud provider with relevant data ''' if call != 'function': log.error( 'The list_keypairs function must be called with -f or --function.' ) return False fetch = True page = 1 ret = {} while fetch: items = query(method='account/keys', command='?page=' + six.text_type(page) + '&per_page=100') for key_pair in items['ssh_keys']: name = key_pair['name'] if name in ret: raise SaltCloudSystemExit( 'A duplicate key pair name, \'{0}\', was found in DigitalOcean\'s ' 'key pair list. Please change the key name stored by DigitalOcean. ' 'Be sure to adjust the value of \'ssh_key_file\' in your cloud ' 'profile or provider configuration, if necessary.'.format( name ) ) ret[name] = {} for item in six.iterkeys(key_pair): ret[name][item] = six.text_type(key_pair[item]) page += 1 try: fetch = 'next' in items['links']['pages'] except KeyError: fetch = False return ret def show_keypair(kwargs=None, call=None): ''' Show the details of an SSH keypair ''' if call != 'function': log.error( 'The show_keypair function must be called with -f or --function.' ) return False if not kwargs: kwargs = {} if 'keyname' not in kwargs: log.error('A keyname is required.') return False keypairs = list_keypairs(call='function') keyid = keypairs[kwargs['keyname']]['id'] log.debug('Key ID is %s', keyid) details = query(method='account/keys', command=keyid) return details def import_keypair(kwargs=None, call=None): ''' Upload public key to cloud provider. Similar to EC2 import_keypair. .. versionadded:: 2016.11.0 kwargs file(mandatory): public key file-name keyname(mandatory): public key name in the provider ''' with salt.utils.files.fopen(kwargs['file'], 'r') as public_key_filename: public_key_content = salt.utils.stringutils.to_unicode(public_key_filename.read()) digitalocean_kwargs = { 'name': kwargs['keyname'], 'public_key': public_key_content } created_result = create_key(digitalocean_kwargs, call=call) return created_result def create_key(kwargs=None, call=None): ''' Upload a public key ''' if call != 'function': log.error( 'The create_key function must be called with -f or --function.' ) return False try: result = query( method='account', command='keys', args={'name': kwargs['name'], 'public_key': kwargs['public_key']}, http_method='post' ) except KeyError: log.info('`name` and `public_key` arguments must be specified') return False return result def remove_key(kwargs=None, call=None): ''' Delete public key ''' if call != 'function': log.error( 'The create_key function must be called with -f or --function.' ) return False try: result = query( method='account', command='keys/' + kwargs['id'], http_method='delete' ) except KeyError: log.info('`id` argument must be specified') return False return result def get_keyid(keyname): ''' Return the ID of the keyname ''' if not keyname: return None keypairs = list_keypairs(call='function') keyid = keypairs[keyname]['id'] if keyid: return keyid raise SaltCloudNotFound('The specified ssh key could not be found.') def destroy(name, call=None): ''' Destroy a node. Will check termination protection and warn if enabled. 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'] ) data = show_instance(name, call='action') node = query(method='droplets', droplet_id=data['id'], http_method='delete') ## This is all terribly optomistic: # vm_ = get_vm_config(name=name) # delete_dns_record = config.get_cloud_config_value( # 'delete_dns_record', vm_, __opts__, search_global=False, default=None, # ) # TODO: when _vm config data can be made available, we should honor the configuration settings, # but until then, we should assume stale DNS records are bad, and default behavior should be to # delete them if we can. When this is resolved, also resolve the comments a couple of lines below. delete_dns_record = True if not isinstance(delete_dns_record, bool): raise SaltCloudConfigError( '\'delete_dns_record\' should be a boolean value.' ) # When the "to do" a few lines up is resolved, remove these lines and use the if/else logic below. log.debug('Deleting DNS records for %s.', name) destroy_dns_records(name) # Until the "to do" from line 754 is taken care of, we don't need this logic. # if delete_dns_record: # log.debug('Deleting DNS records for %s.', name) # destroy_dns_records(name) # else: # log.debug('delete_dns_record : %s', delete_dns_record) # for line in pprint.pformat(dir()).splitlines(): # log.debug('delete context: %s', line) __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 node def post_dns_record(**kwargs): ''' Creates a DNS record for the given name if the domain is managed with DO. ''' if 'kwargs' in kwargs: # flatten kwargs if called via salt-cloud -f f_kwargs = kwargs['kwargs'] del kwargs['kwargs'] kwargs.update(f_kwargs) mandatory_kwargs = ('dns_domain', 'name', 'record_type', 'record_data') for i in mandatory_kwargs: if kwargs[i]: pass else: error = '{0}="{1}" ## all mandatory args must be provided: {2}'.format(i, kwargs[i], mandatory_kwargs) raise SaltInvocationError(error) domain = query(method='domains', droplet_id=kwargs['dns_domain']) if domain: result = query( method='domains', droplet_id=kwargs['dns_domain'], command='records', args={'type': kwargs['record_type'], 'name': kwargs['name'], 'data': kwargs['record_data']}, http_method='post' ) return result return False def destroy_dns_records(fqdn): ''' Deletes DNS records for the given hostname if the domain is managed with DO. ''' domain = '.'.join(fqdn.split('.')[-2:]) hostname = '.'.join(fqdn.split('.')[:-2]) # TODO: remove this when the todo on 754 is available try: response = query(method='domains', droplet_id=domain, command='records') except SaltCloudSystemExit: log.debug('Failed to find domains.') return False log.debug("found DNS records: %s", pprint.pformat(response)) records = response['domain_records'] if records: record_ids = [r['id'] for r in records if r['name'].decode() == hostname] log.debug("deleting DNS record IDs: %s", record_ids) for id_ in record_ids: try: log.info('deleting DNS record %s', id_) ret = query( method='domains', droplet_id=domain, command='records/{0}'.format(id_), http_method='delete' ) except SaltCloudSystemExit: log.error('failed to delete DNS domain %s record ID %s.', domain, hostname) log.debug('DNS deletion REST call returned: %s', pprint.pformat(ret)) return False def show_pricing(kwargs=None, call=None): ''' Show pricing for a particular profile. This is only an estimate, based on unofficial pricing sources. .. versionadded:: 2015.8.0 CLI Examples: .. code-block:: bash salt-cloud -f show_pricing my-digitalocean-config profile=my-profile ''' profile = __opts__['profiles'].get(kwargs['profile'], {}) if not profile: return {'Error': 'The requested profile was not found'} # Make sure the profile belongs to DigitalOcean provider = profile.get('provider', '0:0') comps = provider.split(':') if len(comps) < 2 or comps[1] != 'digitalocean': return {'Error': 'The requested profile does not belong to DigitalOcean'} raw = {} ret = {} sizes = avail_sizes() ret['per_hour'] = decimal.Decimal(sizes[profile['size']]['price_hourly']) ret['per_day'] = ret['per_hour'] * 24 ret['per_week'] = ret['per_day'] * 7 ret['per_month'] = decimal.Decimal(sizes[profile['size']]['price_monthly']) ret['per_year'] = ret['per_week'] * 52 if kwargs.get('raw', False): ret['_raw'] = raw return {profile['profile']: ret} def list_floating_ips(call=None): ''' Return a list of the floating ips that are on the provider .. versionadded:: 2016.3.0 CLI Examples: .. code-block:: bash salt-cloud -f list_floating_ips my-digitalocean-config ''' if call == 'action': raise SaltCloudSystemExit( 'The list_floating_ips function must be called with ' '-f or --function, or with the --list-floating-ips option' ) fetch = True page = 1 ret = {} while fetch: items = query(method='floating_ips', command='?page=' + six.text_type(page) + '&per_page=200') for floating_ip in items['floating_ips']: ret[floating_ip['ip']] = {} for item in six.iterkeys(floating_ip): ret[floating_ip['ip']][item] = floating_ip[item] page += 1 try: fetch = 'next' in items['links']['pages'] except KeyError: fetch = False return ret def show_floating_ip(kwargs=None, call=None): ''' Show the details of a floating IP .. versionadded:: 2016.3.0 CLI Examples: .. code-block:: bash salt-cloud -f show_floating_ip my-digitalocean-config floating_ip='45.55.96.47' ''' if call != 'function': log.error( 'The show_floating_ip function must be called with -f or --function.' ) return False if not kwargs: kwargs = {} if 'floating_ip' not in kwargs: log.error('A floating IP is required.') return False floating_ip = kwargs['floating_ip'] log.debug('Floating ip is %s', floating_ip) details = query(method='floating_ips', command=floating_ip) return details def create_floating_ip(kwargs=None, call=None): ''' Create a new floating IP .. versionadded:: 2016.3.0 CLI Examples: .. code-block:: bash salt-cloud -f create_floating_ip my-digitalocean-config region='NYC2' salt-cloud -f create_floating_ip my-digitalocean-config droplet_id='1234567' ''' if call != 'function': log.error( 'The create_floating_ip function must be called with -f or --function.' ) return False if not kwargs: kwargs = {} if 'droplet_id' in kwargs: result = query(method='floating_ips', args={'droplet_id': kwargs['droplet_id']}, http_method='post') return result elif 'region' in kwargs: result = query(method='floating_ips', args={'region': kwargs['region']}, http_method='post') return result else: log.error('A droplet_id or region is required.') return False def delete_floating_ip(kwargs=None, call=None): ''' Delete a floating IP .. versionadded:: 2016.3.0 CLI Examples: .. code-block:: bash salt-cloud -f delete_floating_ip my-digitalocean-config floating_ip='45.55.96.47' ''' if call != 'function': log.error( 'The delete_floating_ip function must be called with -f or --function.' ) return False if not kwargs: kwargs = {} if 'floating_ip' not in kwargs: log.error('A floating IP is required.') return False floating_ip = kwargs['floating_ip'] log.debug('Floating ip is %s', kwargs['floating_ip']) result = query(method='floating_ips', command=floating_ip, http_method='delete') return result def assign_floating_ip(kwargs=None, call=None): ''' Assign a floating IP .. versionadded:: 2016.3.0 CLI Examples: .. code-block:: bash salt-cloud -f assign_floating_ip my-digitalocean-config droplet_id=1234567 floating_ip='45.55.96.47' ''' if call != 'function': log.error( 'The assign_floating_ip function must be called with -f or --function.' ) return False if not kwargs: kwargs = {} if 'floating_ip' and 'droplet_id' not in kwargs: log.error('A floating IP and droplet_id is required.') return False result = query(method='floating_ips', command=kwargs['floating_ip'] + '/actions', args={'droplet_id': kwargs['droplet_id'], 'type': 'assign'}, http_method='post') return result def unassign_floating_ip(kwargs=None, call=None): ''' Unassign a floating IP .. versionadded:: 2016.3.0 CLI Examples: .. code-block:: bash salt-cloud -f unassign_floating_ip my-digitalocean-config floating_ip='45.55.96.47' ''' if call != 'function': log.error( 'The inassign_floating_ip function must be called with -f or --function.' ) return False if not kwargs: kwargs = {} if 'floating_ip' not in kwargs: log.error('A floating IP is required.') return False result = query(method='floating_ips', command=kwargs['floating_ip'] + '/actions', args={'type': 'unassign'}, http_method='post') return result def _list_nodes(full=False, for_output=False): ''' Helper function to format and parse node data. ''' fetch = True page = 1 ret = {} while fetch: items = query(method='droplets', command='?page=' + six.text_type(page) + '&per_page=200') for node in items['droplets']: name = node['name'] ret[name] = {} if full: ret[name] = _get_full_output(node, for_output=for_output) else: public_ips, private_ips = _get_ips(node['networks']) ret[name] = { 'id': node['id'], 'image': node['image']['name'], 'name': name, 'private_ips': private_ips, 'public_ips': public_ips, 'size': node['size_slug'], 'state': six.text_type(node['status']), } page += 1 try: fetch = 'next' in items['links']['pages'] except KeyError: fetch = False return ret def reboot(name, call=None): ''' Reboot a droplet in DigitalOcean. .. versionadded:: 2015.8.8 name The name of the droplet to restart. CLI Example: .. code-block:: bash salt-cloud -a reboot droplet_name ''' if call != 'action': raise SaltCloudSystemExit( 'The restart action must be called with -a or --action.' ) data = show_instance(name, call='action') if data.get('status') == 'off': return {'success': True, 'action': 'stop', 'status': 'off', 'msg': 'Machine is already off.'} ret = query(droplet_id=data['id'], command='actions', args={'type': 'reboot'}, http_method='post') return {'success': True, 'action': ret['action']['type'], 'state': ret['action']['status']} def start(name, call=None): ''' Start a droplet in DigitalOcean. .. versionadded:: 2015.8.8 name The name of the droplet to start. CLI Example: .. code-block:: bash salt-cloud -a start droplet_name ''' if call != 'action': raise SaltCloudSystemExit( 'The start action must be called with -a or --action.' ) data = show_instance(name, call='action') if data.get('status') == 'active': return {'success': True, 'action': 'start', 'status': 'active', 'msg': 'Machine is already running.'} ret = query(droplet_id=data['id'], command='actions', args={'type': 'power_on'}, http_method='post') return {'success': True, 'action': ret['action']['type'], 'state': ret['action']['status']} def stop(name, call=None): ''' Stop a droplet in DigitalOcean. .. versionadded:: 2015.8.8 name The name of the droplet to stop. CLI Example: .. code-block:: bash salt-cloud -a stop droplet_name ''' if call != 'action': raise SaltCloudSystemExit( 'The stop action must be called with -a or --action.' ) data = show_instance(name, call='action') if data.get('status') == 'off': return {'success': True, 'action': 'stop', 'status': 'off', 'msg': 'Machine is already off.'} ret = query(droplet_id=data['id'], command='actions', args={'type': 'shutdown'}, http_method='post') return {'success': True, 'action': ret['action']['type'], 'state': ret['action']['status']} def _get_full_output(node, for_output=False): ''' Helper function for _list_nodes to loop through all node information. Returns a dictionary containing the full information of a node. ''' ret = {} for item in six.iterkeys(node): value = node[item] if value is not None and for_output: value = six.text_type(value) ret[item] = value return ret def _get_ips(networks): ''' Helper function for list_nodes. Returns public and private ip lists based on a given network dictionary. ''' v4s = networks.get('v4') v6s = networks.get('v6') public_ips = [] private_ips = [] if v4s: for item in v4s: ip_type = item.get('type') ip_address = item.get('ip_address') if ip_type == 'public': public_ips.append(ip_address) if ip_type == 'private': private_ips.append(ip_address) if v6s: for item in v6s: ip_type = item.get('type') ip_address = item.get('ip_address') if ip_type == 'public': public_ips.append(ip_address) if ip_type == 'private': private_ips.append(ip_address) return public_ips, private_ips
saltstack/salt
salt/cloud/clouds/digitalocean.py
avail_sizes
python
def avail_sizes(call=None): ''' Return a list of the image sizes that are on the provider ''' if call == 'action': raise SaltCloudSystemExit( 'The avail_sizes function must be called with ' '-f or --function, or with the --list-sizes option' ) items = query(method='sizes', command='?per_page=100') ret = {} for size in items['sizes']: ret[size['slug']] = {} for item in six.iterkeys(size): ret[size['slug']][item] = six.text_type(size[item]) return ret
Return a list of the image sizes that are on the provider
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/digitalocean.py#L155-L172
[ "def iterkeys(d, **kw):\n return d.iterkeys(**kw)\n", "def query(method='droplets', droplet_id=None, command=None, args=None, http_method='get'):\n '''\n Make a web call to DigitalOcean\n '''\n base_path = six.text_type(config.get_cloud_config_value(\n 'api_root',\n get_configured_provider(),\n __opts__,\n search_global=False,\n default='https://api.digitalocean.com/v2'\n ))\n\n path = '{0}/{1}/'.format(base_path, method)\n\n if droplet_id:\n path += '{0}/'.format(droplet_id)\n\n if command:\n path += command\n\n if not isinstance(args, dict):\n args = {}\n\n personal_access_token = config.get_cloud_config_value(\n 'personal_access_token', get_configured_provider(), __opts__, search_global=False\n )\n\n data = salt.utils.json.dumps(args)\n\n requester = getattr(requests, http_method)\n request = requester(path, data=data, headers={'Authorization': 'Bearer ' + personal_access_token, 'Content-Type': 'application/json'})\n if request.status_code > 299:\n raise SaltCloudSystemExit(\n 'An error occurred while querying DigitalOcean. HTTP Code: {0} '\n 'Error: \\'{1}\\''.format(\n request.status_code,\n # request.read()\n request.text\n )\n )\n\n log.debug(request.url)\n\n # success without data\n if request.status_code == 204:\n return True\n\n content = request.text\n\n result = salt.utils.json.loads(content)\n if result.get('status', '').lower() == 'error':\n raise SaltCloudSystemExit(\n pprint.pformat(result.get('error_message', {}))\n )\n\n return result\n" ]
# -*- coding: utf-8 -*- ''' DigitalOcean Cloud Module ========================= The DigitalOcean cloud module is used to control access to the DigitalOcean VPS system. Use of this module requires a requires a ``personal_access_token``, an ``ssh_key_file``, and at least one SSH key name in ``ssh_key_names``. More ``ssh_key_names`` can be added by separating each key with a comma. The ``personal_access_token`` can be found in the DigitalOcean web interface in the "Apps & API" section. The SSH key name can be found under the "SSH Keys" section. .. code-block:: yaml # Note: This example is for /etc/salt/cloud.providers or any file in the # /etc/salt/cloud.providers.d/ directory. my-digital-ocean-config: personal_access_token: xxx ssh_key_file: /path/to/ssh/key/file ssh_key_names: my-key-name,my-key-name-2 driver: digitalocean :depends: requests ''' # Import Python Libs from __future__ import absolute_import, print_function, unicode_literals import decimal import logging import os import pprint import time # Import Salt Libs import salt.utils.cloud import salt.utils.files import salt.utils.json import salt.utils.stringutils import salt.config as config from salt.exceptions import ( SaltCloudConfigError, SaltInvocationError, SaltCloudNotFound, SaltCloudSystemExit, SaltCloudExecutionFailure, SaltCloudExecutionTimeout ) from salt.ext import six from salt.ext.six.moves import zip # Import Third Party Libs try: import requests HAS_REQUESTS = True except ImportError: HAS_REQUESTS = False # Get logging started log = logging.getLogger(__name__) __virtualname__ = 'digitalocean' __virtual_aliases__ = ('digital_ocean', 'do') # Only load in this module if the DIGITALOCEAN configurations are in place def __virtual__(): ''' Check for DigitalOcean 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=__opts__, provider=__active_provider_name__ or __virtualname__, aliases=__virtual_aliases__, required_keys=('personal_access_token',) ) def get_dependencies(): ''' Warn if dependencies aren't met. ''' return config.check_driver_dependencies( __virtualname__, {'requests': HAS_REQUESTS} ) def avail_locations(call=None): ''' Return a dict of all available VM locations on the cloud provider with relevant data ''' if call == 'action': raise SaltCloudSystemExit( 'The avail_locations function must be called with ' '-f or --function, or with the --list-locations option' ) items = query(method='regions') ret = {} for region in items['regions']: ret[region['name']] = {} for item in six.iterkeys(region): ret[region['name']][item] = six.text_type(region[item]) return ret def avail_images(call=None): ''' Return a list of the images that are on the provider ''' if call == 'action': raise SaltCloudSystemExit( 'The avail_images function must be called with ' '-f or --function, or with the --list-images option' ) fetch = True page = 1 ret = {} while fetch: items = query(method='images', command='?page=' + six.text_type(page) + '&per_page=200') for image in items['images']: ret[image['name']] = {} for item in six.iterkeys(image): ret[image['name']][item] = image[item] page += 1 try: fetch = 'next' in items['links']['pages'] except KeyError: fetch = False 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.' ) return _list_nodes() def list_nodes_full(call=None, for_output=True): ''' 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.' ) return _list_nodes(full=True, for_output=for_output) 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('function'), __opts__['query.selection'], call, ) def get_image(vm_): ''' Return the image object to use ''' images = avail_images() vm_image = config.get_cloud_config_value( 'image', vm_, __opts__, search_global=False ) if not isinstance(vm_image, six.string_types): vm_image = six.text_type(vm_image) for image in images: if vm_image in (images[image]['name'], images[image]['slug'], images[image]['id']): if images[image]['slug'] is not None: return images[image]['slug'] return int(images[image]['id']) raise SaltCloudNotFound( 'The specified image, \'{0}\', could not be found.'.format(vm_image) ) def get_size(vm_): ''' Return the VM's size. Used by create_node(). ''' sizes = avail_sizes() vm_size = six.text_type(config.get_cloud_config_value( 'size', vm_, __opts__, search_global=False )) for size in sizes: if vm_size.lower() == sizes[size]['slug']: return sizes[size]['slug'] raise SaltCloudNotFound( 'The specified size, \'{0}\', could not be found.'.format(vm_size) ) def get_location(vm_): ''' Return the VM's location ''' locations = avail_locations() vm_location = six.text_type(config.get_cloud_config_value( 'location', vm_, __opts__, search_global=False )) for location in locations: if vm_location in (locations[location]['name'], locations[location]['slug']): return locations[location]['slug'] raise SaltCloudNotFound( 'The specified location, \'{0}\', could not be found.'.format( vm_location ) ) def create_node(args): ''' Create a node ''' node = query(method='droplets', args=args, http_method='post') return node 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 'digitalocean', vm_['profile'], vm_=vm_) is False: return False except AttributeError: pass __utils__['cloud.fire_event']( 'event', 'starting create', 'salt/cloud/{0}/creating'.format(vm_['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', vm_['name']) kwargs = { 'name': vm_['name'], 'size': get_size(vm_), 'image': get_image(vm_), 'region': get_location(vm_), 'ssh_keys': [], 'tags': [] } # backwards compat ssh_key_name = config.get_cloud_config_value( 'ssh_key_name', vm_, __opts__, search_global=False ) if ssh_key_name: kwargs['ssh_keys'].append(get_keyid(ssh_key_name)) ssh_key_names = config.get_cloud_config_value( 'ssh_key_names', vm_, __opts__, search_global=False, default=False ) if ssh_key_names: for key in ssh_key_names.split(','): kwargs['ssh_keys'].append(get_keyid(key)) key_filename = config.get_cloud_config_value( 'ssh_key_file', vm_, __opts__, search_global=False, default=None ) if key_filename is not None and not os.path.isfile(key_filename): raise SaltCloudConfigError( 'The defined key_filename \'{0}\' does not exist'.format( key_filename ) ) if not __opts__.get('ssh_agent', False) and key_filename is None: raise SaltCloudConfigError( 'The DigitalOcean driver requires an ssh_key_file and an ssh_key_name ' 'because it does not supply a root password upon building the server.' ) ssh_interface = config.get_cloud_config_value( 'ssh_interface', vm_, __opts__, search_global=False, default='public' ) if ssh_interface in ['private', 'public']: log.info("ssh_interface: Setting interface for ssh to %s", ssh_interface) kwargs['ssh_interface'] = ssh_interface else: raise SaltCloudConfigError( "The DigitalOcean driver requires ssh_interface to be defined as 'public' or 'private'." ) private_networking = config.get_cloud_config_value( 'private_networking', vm_, __opts__, search_global=False, default=None, ) if private_networking is not None: if not isinstance(private_networking, bool): raise SaltCloudConfigError("'private_networking' should be a boolean value.") kwargs['private_networking'] = private_networking if not private_networking and ssh_interface == 'private': raise SaltCloudConfigError( "The DigitalOcean driver requires ssh_interface if defined as 'private' " "then private_networking should be set as 'True'." ) backups_enabled = config.get_cloud_config_value( 'backups_enabled', vm_, __opts__, search_global=False, default=None, ) if backups_enabled is not None: if not isinstance(backups_enabled, bool): raise SaltCloudConfigError("'backups_enabled' should be a boolean value.") kwargs['backups'] = backups_enabled ipv6 = config.get_cloud_config_value( 'ipv6', vm_, __opts__, search_global=False, default=None, ) if ipv6 is not None: if not isinstance(ipv6, bool): raise SaltCloudConfigError("'ipv6' should be a boolean value.") kwargs['ipv6'] = ipv6 monitoring = config.get_cloud_config_value( 'monitoring', vm_, __opts__, search_global=False, default=None, ) if monitoring is not None: if not isinstance(monitoring, bool): raise SaltCloudConfigError("'monitoring' should be a boolean value.") kwargs['monitoring'] = monitoring kwargs['tags'] = config.get_cloud_config_value( 'tags', vm_, __opts__, search_global=False, default=False ) userdata_file = config.get_cloud_config_value( 'userdata_file', vm_, __opts__, search_global=False, default=None ) if userdata_file is not None: try: with salt.utils.files.fopen(userdata_file, 'r') as fp_: kwargs['user_data'] = salt.utils.cloud.userdata_template( __opts__, vm_, salt.utils.stringutils.to_unicode(fp_.read()) ) except Exception as exc: log.exception( 'Failed to read userdata from %s: %s', userdata_file, exc) create_dns_record = config.get_cloud_config_value( 'create_dns_record', vm_, __opts__, search_global=False, default=None, ) if create_dns_record: log.info('create_dns_record: will attempt to write DNS records') default_dns_domain = None dns_domain_name = vm_['name'].split('.') if len(dns_domain_name) > 2: log.debug('create_dns_record: inferring default dns_hostname, dns_domain from minion name as FQDN') default_dns_hostname = '.'.join(dns_domain_name[:-2]) default_dns_domain = '.'.join(dns_domain_name[-2:]) else: log.debug("create_dns_record: can't infer dns_domain from %s", vm_['name']) default_dns_hostname = dns_domain_name[0] dns_hostname = config.get_cloud_config_value( 'dns_hostname', vm_, __opts__, search_global=False, default=default_dns_hostname, ) dns_domain = config.get_cloud_config_value( 'dns_domain', vm_, __opts__, search_global=False, default=default_dns_domain, ) if dns_hostname and dns_domain: log.info('create_dns_record: using dns_hostname="%s", dns_domain="%s"', dns_hostname, dns_domain) __add_dns_addr__ = lambda t, d: post_dns_record(dns_domain=dns_domain, name=dns_hostname, record_type=t, record_data=d) log.debug('create_dns_record: %s', __add_dns_addr__) else: log.error('create_dns_record: could not determine dns_hostname and/or dns_domain') raise SaltCloudConfigError( '\'create_dns_record\' must be a dict specifying "domain" ' 'and "hostname" or the minion name must be an FQDN.' ) __utils__['cloud.fire_event']( 'event', 'requesting instance', 'salt/cloud/{0}/requesting'.format(vm_['name']), args=__utils__['cloud.filter_event']('requesting', kwargs, list(kwargs)), sock_dir=__opts__['sock_dir'], transport=__opts__['transport'] ) try: ret = create_node(kwargs) except Exception as exc: log.error( 'Error creating %s on DIGITALOCEAN\n\n' 'The following exception was thrown when trying to ' 'run the initial deployment: %s', vm_['name'], exc, # Show the traceback if the debug logging level is enabled exc_info_on_loglevel=logging.DEBUG ) return False def __query_node_data(vm_name): data = show_instance(vm_name, 'action') if not data: # Trigger an error in the wait_for_ip function return False if data['networks'].get('v4'): for network in data['networks']['v4']: if network['type'] == 'public': return data return False try: data = salt.utils.cloud.wait_for_ip( __query_node_data, update_args=(vm_['name'],), timeout=config.get_cloud_config_value( 'wait_for_ip_timeout', vm_, __opts__, default=10 * 60), interval=config.get_cloud_config_value( 'wait_for_ip_interval', vm_, __opts__, default=10), ) except (SaltCloudExecutionTimeout, SaltCloudExecutionFailure) as exc: try: # It might be already up, let's destroy it! destroy(vm_['name']) except SaltCloudSystemExit: pass finally: raise SaltCloudSystemExit(six.text_type(exc)) if not vm_.get('ssh_host'): vm_['ssh_host'] = None # add DNS records, set ssh_host, default to first found IP, preferring IPv4 for ssh bootstrap script target addr_families, dns_arec_types = (('v4', 'v6'), ('A', 'AAAA')) arec_map = dict(list(zip(addr_families, dns_arec_types))) for facing, addr_family, ip_address in [(net['type'], family, net['ip_address']) for family in addr_families for net in data['networks'][family]]: log.info('found %s IP%s interface for "%s"', facing, addr_family, ip_address) dns_rec_type = arec_map[addr_family] if facing == 'public': if create_dns_record: __add_dns_addr__(dns_rec_type, ip_address) if facing == ssh_interface: if not vm_['ssh_host']: vm_['ssh_host'] = ip_address if vm_['ssh_host'] is None: raise SaltCloudSystemExit( 'No suitable IP addresses found for ssh minion bootstrapping: {0}'.format(repr(data['networks'])) ) log.debug( 'Found public IP address to use for ssh minion bootstrapping: %s', vm_['ssh_host'] ) vm_['key_filename'] = key_filename ret = __utils__['cloud.bootstrap'](vm_, __opts__) ret.update(data) log.info('Created Cloud VM \'%s\'', vm_['name']) log.debug( '\'%s\' VM creation details:\n%s', vm_['name'], pprint.pformat(data) ) __utils__['cloud.fire_event']( 'event', 'created instance', 'salt/cloud/{0}/created'.format(vm_['name']), args=__utils__['cloud.filter_event']('created', vm_, ['name', 'profile', 'provider', 'driver']), sock_dir=__opts__['sock_dir'], transport=__opts__['transport'] ) return ret def query(method='droplets', droplet_id=None, command=None, args=None, http_method='get'): ''' Make a web call to DigitalOcean ''' base_path = six.text_type(config.get_cloud_config_value( 'api_root', get_configured_provider(), __opts__, search_global=False, default='https://api.digitalocean.com/v2' )) path = '{0}/{1}/'.format(base_path, method) if droplet_id: path += '{0}/'.format(droplet_id) if command: path += command if not isinstance(args, dict): args = {} personal_access_token = config.get_cloud_config_value( 'personal_access_token', get_configured_provider(), __opts__, search_global=False ) data = salt.utils.json.dumps(args) requester = getattr(requests, http_method) request = requester(path, data=data, headers={'Authorization': 'Bearer ' + personal_access_token, 'Content-Type': 'application/json'}) if request.status_code > 299: raise SaltCloudSystemExit( 'An error occurred while querying DigitalOcean. HTTP Code: {0} ' 'Error: \'{1}\''.format( request.status_code, # request.read() request.text ) ) log.debug(request.url) # success without data if request.status_code == 204: return True content = request.text result = salt.utils.json.loads(content) if result.get('status', '').lower() == 'error': raise SaltCloudSystemExit( pprint.pformat(result.get('error_message', {})) ) return result 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 show_instance(name, call=None): ''' Show the details from DigitalOcean concerning a droplet ''' if call != 'action': raise SaltCloudSystemExit( 'The show_instance action must be called with -a or --action.' ) node = _get_node(name) __utils__['cloud.cache_node'](node, __active_provider_name__, __opts__) return node def _get_node(name): attempts = 10 while attempts >= 0: try: return list_nodes_full(for_output=False)[name] except KeyError: attempts -= 1 log.debug( 'Failed to get the data for node \'%s\'. Remaining ' 'attempts: %s', name, attempts ) # Just a little delay between attempts... time.sleep(0.5) return {} def list_keypairs(call=None): ''' Return a dict of all available VM locations on the cloud provider with relevant data ''' if call != 'function': log.error( 'The list_keypairs function must be called with -f or --function.' ) return False fetch = True page = 1 ret = {} while fetch: items = query(method='account/keys', command='?page=' + six.text_type(page) + '&per_page=100') for key_pair in items['ssh_keys']: name = key_pair['name'] if name in ret: raise SaltCloudSystemExit( 'A duplicate key pair name, \'{0}\', was found in DigitalOcean\'s ' 'key pair list. Please change the key name stored by DigitalOcean. ' 'Be sure to adjust the value of \'ssh_key_file\' in your cloud ' 'profile or provider configuration, if necessary.'.format( name ) ) ret[name] = {} for item in six.iterkeys(key_pair): ret[name][item] = six.text_type(key_pair[item]) page += 1 try: fetch = 'next' in items['links']['pages'] except KeyError: fetch = False return ret def show_keypair(kwargs=None, call=None): ''' Show the details of an SSH keypair ''' if call != 'function': log.error( 'The show_keypair function must be called with -f or --function.' ) return False if not kwargs: kwargs = {} if 'keyname' not in kwargs: log.error('A keyname is required.') return False keypairs = list_keypairs(call='function') keyid = keypairs[kwargs['keyname']]['id'] log.debug('Key ID is %s', keyid) details = query(method='account/keys', command=keyid) return details def import_keypair(kwargs=None, call=None): ''' Upload public key to cloud provider. Similar to EC2 import_keypair. .. versionadded:: 2016.11.0 kwargs file(mandatory): public key file-name keyname(mandatory): public key name in the provider ''' with salt.utils.files.fopen(kwargs['file'], 'r') as public_key_filename: public_key_content = salt.utils.stringutils.to_unicode(public_key_filename.read()) digitalocean_kwargs = { 'name': kwargs['keyname'], 'public_key': public_key_content } created_result = create_key(digitalocean_kwargs, call=call) return created_result def create_key(kwargs=None, call=None): ''' Upload a public key ''' if call != 'function': log.error( 'The create_key function must be called with -f or --function.' ) return False try: result = query( method='account', command='keys', args={'name': kwargs['name'], 'public_key': kwargs['public_key']}, http_method='post' ) except KeyError: log.info('`name` and `public_key` arguments must be specified') return False return result def remove_key(kwargs=None, call=None): ''' Delete public key ''' if call != 'function': log.error( 'The create_key function must be called with -f or --function.' ) return False try: result = query( method='account', command='keys/' + kwargs['id'], http_method='delete' ) except KeyError: log.info('`id` argument must be specified') return False return result def get_keyid(keyname): ''' Return the ID of the keyname ''' if not keyname: return None keypairs = list_keypairs(call='function') keyid = keypairs[keyname]['id'] if keyid: return keyid raise SaltCloudNotFound('The specified ssh key could not be found.') def destroy(name, call=None): ''' Destroy a node. Will check termination protection and warn if enabled. 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'] ) data = show_instance(name, call='action') node = query(method='droplets', droplet_id=data['id'], http_method='delete') ## This is all terribly optomistic: # vm_ = get_vm_config(name=name) # delete_dns_record = config.get_cloud_config_value( # 'delete_dns_record', vm_, __opts__, search_global=False, default=None, # ) # TODO: when _vm config data can be made available, we should honor the configuration settings, # but until then, we should assume stale DNS records are bad, and default behavior should be to # delete them if we can. When this is resolved, also resolve the comments a couple of lines below. delete_dns_record = True if not isinstance(delete_dns_record, bool): raise SaltCloudConfigError( '\'delete_dns_record\' should be a boolean value.' ) # When the "to do" a few lines up is resolved, remove these lines and use the if/else logic below. log.debug('Deleting DNS records for %s.', name) destroy_dns_records(name) # Until the "to do" from line 754 is taken care of, we don't need this logic. # if delete_dns_record: # log.debug('Deleting DNS records for %s.', name) # destroy_dns_records(name) # else: # log.debug('delete_dns_record : %s', delete_dns_record) # for line in pprint.pformat(dir()).splitlines(): # log.debug('delete context: %s', line) __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 node def post_dns_record(**kwargs): ''' Creates a DNS record for the given name if the domain is managed with DO. ''' if 'kwargs' in kwargs: # flatten kwargs if called via salt-cloud -f f_kwargs = kwargs['kwargs'] del kwargs['kwargs'] kwargs.update(f_kwargs) mandatory_kwargs = ('dns_domain', 'name', 'record_type', 'record_data') for i in mandatory_kwargs: if kwargs[i]: pass else: error = '{0}="{1}" ## all mandatory args must be provided: {2}'.format(i, kwargs[i], mandatory_kwargs) raise SaltInvocationError(error) domain = query(method='domains', droplet_id=kwargs['dns_domain']) if domain: result = query( method='domains', droplet_id=kwargs['dns_domain'], command='records', args={'type': kwargs['record_type'], 'name': kwargs['name'], 'data': kwargs['record_data']}, http_method='post' ) return result return False def destroy_dns_records(fqdn): ''' Deletes DNS records for the given hostname if the domain is managed with DO. ''' domain = '.'.join(fqdn.split('.')[-2:]) hostname = '.'.join(fqdn.split('.')[:-2]) # TODO: remove this when the todo on 754 is available try: response = query(method='domains', droplet_id=domain, command='records') except SaltCloudSystemExit: log.debug('Failed to find domains.') return False log.debug("found DNS records: %s", pprint.pformat(response)) records = response['domain_records'] if records: record_ids = [r['id'] for r in records if r['name'].decode() == hostname] log.debug("deleting DNS record IDs: %s", record_ids) for id_ in record_ids: try: log.info('deleting DNS record %s', id_) ret = query( method='domains', droplet_id=domain, command='records/{0}'.format(id_), http_method='delete' ) except SaltCloudSystemExit: log.error('failed to delete DNS domain %s record ID %s.', domain, hostname) log.debug('DNS deletion REST call returned: %s', pprint.pformat(ret)) return False def show_pricing(kwargs=None, call=None): ''' Show pricing for a particular profile. This is only an estimate, based on unofficial pricing sources. .. versionadded:: 2015.8.0 CLI Examples: .. code-block:: bash salt-cloud -f show_pricing my-digitalocean-config profile=my-profile ''' profile = __opts__['profiles'].get(kwargs['profile'], {}) if not profile: return {'Error': 'The requested profile was not found'} # Make sure the profile belongs to DigitalOcean provider = profile.get('provider', '0:0') comps = provider.split(':') if len(comps) < 2 or comps[1] != 'digitalocean': return {'Error': 'The requested profile does not belong to DigitalOcean'} raw = {} ret = {} sizes = avail_sizes() ret['per_hour'] = decimal.Decimal(sizes[profile['size']]['price_hourly']) ret['per_day'] = ret['per_hour'] * 24 ret['per_week'] = ret['per_day'] * 7 ret['per_month'] = decimal.Decimal(sizes[profile['size']]['price_monthly']) ret['per_year'] = ret['per_week'] * 52 if kwargs.get('raw', False): ret['_raw'] = raw return {profile['profile']: ret} def list_floating_ips(call=None): ''' Return a list of the floating ips that are on the provider .. versionadded:: 2016.3.0 CLI Examples: .. code-block:: bash salt-cloud -f list_floating_ips my-digitalocean-config ''' if call == 'action': raise SaltCloudSystemExit( 'The list_floating_ips function must be called with ' '-f or --function, or with the --list-floating-ips option' ) fetch = True page = 1 ret = {} while fetch: items = query(method='floating_ips', command='?page=' + six.text_type(page) + '&per_page=200') for floating_ip in items['floating_ips']: ret[floating_ip['ip']] = {} for item in six.iterkeys(floating_ip): ret[floating_ip['ip']][item] = floating_ip[item] page += 1 try: fetch = 'next' in items['links']['pages'] except KeyError: fetch = False return ret def show_floating_ip(kwargs=None, call=None): ''' Show the details of a floating IP .. versionadded:: 2016.3.0 CLI Examples: .. code-block:: bash salt-cloud -f show_floating_ip my-digitalocean-config floating_ip='45.55.96.47' ''' if call != 'function': log.error( 'The show_floating_ip function must be called with -f or --function.' ) return False if not kwargs: kwargs = {} if 'floating_ip' not in kwargs: log.error('A floating IP is required.') return False floating_ip = kwargs['floating_ip'] log.debug('Floating ip is %s', floating_ip) details = query(method='floating_ips', command=floating_ip) return details def create_floating_ip(kwargs=None, call=None): ''' Create a new floating IP .. versionadded:: 2016.3.0 CLI Examples: .. code-block:: bash salt-cloud -f create_floating_ip my-digitalocean-config region='NYC2' salt-cloud -f create_floating_ip my-digitalocean-config droplet_id='1234567' ''' if call != 'function': log.error( 'The create_floating_ip function must be called with -f or --function.' ) return False if not kwargs: kwargs = {} if 'droplet_id' in kwargs: result = query(method='floating_ips', args={'droplet_id': kwargs['droplet_id']}, http_method='post') return result elif 'region' in kwargs: result = query(method='floating_ips', args={'region': kwargs['region']}, http_method='post') return result else: log.error('A droplet_id or region is required.') return False def delete_floating_ip(kwargs=None, call=None): ''' Delete a floating IP .. versionadded:: 2016.3.0 CLI Examples: .. code-block:: bash salt-cloud -f delete_floating_ip my-digitalocean-config floating_ip='45.55.96.47' ''' if call != 'function': log.error( 'The delete_floating_ip function must be called with -f or --function.' ) return False if not kwargs: kwargs = {} if 'floating_ip' not in kwargs: log.error('A floating IP is required.') return False floating_ip = kwargs['floating_ip'] log.debug('Floating ip is %s', kwargs['floating_ip']) result = query(method='floating_ips', command=floating_ip, http_method='delete') return result def assign_floating_ip(kwargs=None, call=None): ''' Assign a floating IP .. versionadded:: 2016.3.0 CLI Examples: .. code-block:: bash salt-cloud -f assign_floating_ip my-digitalocean-config droplet_id=1234567 floating_ip='45.55.96.47' ''' if call != 'function': log.error( 'The assign_floating_ip function must be called with -f or --function.' ) return False if not kwargs: kwargs = {} if 'floating_ip' and 'droplet_id' not in kwargs: log.error('A floating IP and droplet_id is required.') return False result = query(method='floating_ips', command=kwargs['floating_ip'] + '/actions', args={'droplet_id': kwargs['droplet_id'], 'type': 'assign'}, http_method='post') return result def unassign_floating_ip(kwargs=None, call=None): ''' Unassign a floating IP .. versionadded:: 2016.3.0 CLI Examples: .. code-block:: bash salt-cloud -f unassign_floating_ip my-digitalocean-config floating_ip='45.55.96.47' ''' if call != 'function': log.error( 'The inassign_floating_ip function must be called with -f or --function.' ) return False if not kwargs: kwargs = {} if 'floating_ip' not in kwargs: log.error('A floating IP is required.') return False result = query(method='floating_ips', command=kwargs['floating_ip'] + '/actions', args={'type': 'unassign'}, http_method='post') return result def _list_nodes(full=False, for_output=False): ''' Helper function to format and parse node data. ''' fetch = True page = 1 ret = {} while fetch: items = query(method='droplets', command='?page=' + six.text_type(page) + '&per_page=200') for node in items['droplets']: name = node['name'] ret[name] = {} if full: ret[name] = _get_full_output(node, for_output=for_output) else: public_ips, private_ips = _get_ips(node['networks']) ret[name] = { 'id': node['id'], 'image': node['image']['name'], 'name': name, 'private_ips': private_ips, 'public_ips': public_ips, 'size': node['size_slug'], 'state': six.text_type(node['status']), } page += 1 try: fetch = 'next' in items['links']['pages'] except KeyError: fetch = False return ret def reboot(name, call=None): ''' Reboot a droplet in DigitalOcean. .. versionadded:: 2015.8.8 name The name of the droplet to restart. CLI Example: .. code-block:: bash salt-cloud -a reboot droplet_name ''' if call != 'action': raise SaltCloudSystemExit( 'The restart action must be called with -a or --action.' ) data = show_instance(name, call='action') if data.get('status') == 'off': return {'success': True, 'action': 'stop', 'status': 'off', 'msg': 'Machine is already off.'} ret = query(droplet_id=data['id'], command='actions', args={'type': 'reboot'}, http_method='post') return {'success': True, 'action': ret['action']['type'], 'state': ret['action']['status']} def start(name, call=None): ''' Start a droplet in DigitalOcean. .. versionadded:: 2015.8.8 name The name of the droplet to start. CLI Example: .. code-block:: bash salt-cloud -a start droplet_name ''' if call != 'action': raise SaltCloudSystemExit( 'The start action must be called with -a or --action.' ) data = show_instance(name, call='action') if data.get('status') == 'active': return {'success': True, 'action': 'start', 'status': 'active', 'msg': 'Machine is already running.'} ret = query(droplet_id=data['id'], command='actions', args={'type': 'power_on'}, http_method='post') return {'success': True, 'action': ret['action']['type'], 'state': ret['action']['status']} def stop(name, call=None): ''' Stop a droplet in DigitalOcean. .. versionadded:: 2015.8.8 name The name of the droplet to stop. CLI Example: .. code-block:: bash salt-cloud -a stop droplet_name ''' if call != 'action': raise SaltCloudSystemExit( 'The stop action must be called with -a or --action.' ) data = show_instance(name, call='action') if data.get('status') == 'off': return {'success': True, 'action': 'stop', 'status': 'off', 'msg': 'Machine is already off.'} ret = query(droplet_id=data['id'], command='actions', args={'type': 'shutdown'}, http_method='post') return {'success': True, 'action': ret['action']['type'], 'state': ret['action']['status']} def _get_full_output(node, for_output=False): ''' Helper function for _list_nodes to loop through all node information. Returns a dictionary containing the full information of a node. ''' ret = {} for item in six.iterkeys(node): value = node[item] if value is not None and for_output: value = six.text_type(value) ret[item] = value return ret def _get_ips(networks): ''' Helper function for list_nodes. Returns public and private ip lists based on a given network dictionary. ''' v4s = networks.get('v4') v6s = networks.get('v6') public_ips = [] private_ips = [] if v4s: for item in v4s: ip_type = item.get('type') ip_address = item.get('ip_address') if ip_type == 'public': public_ips.append(ip_address) if ip_type == 'private': private_ips.append(ip_address) if v6s: for item in v6s: ip_type = item.get('type') ip_address = item.get('ip_address') if ip_type == 'public': public_ips.append(ip_address) if ip_type == 'private': private_ips.append(ip_address) return public_ips, private_ips
saltstack/salt
salt/cloud/clouds/digitalocean.py
list_nodes_full
python
def list_nodes_full(call=None, for_output=True): ''' 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.' ) return _list_nodes(full=True, for_output=for_output)
Return a list of the VMs that are on the provider
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/digitalocean.py#L186-L194
[ "def _list_nodes(full=False, for_output=False):\n '''\n Helper function to format and parse node data.\n '''\n fetch = True\n page = 1\n ret = {}\n\n while fetch:\n items = query(method='droplets',\n command='?page=' + six.text_type(page) + '&per_page=200')\n for node in items['droplets']:\n name = node['name']\n ret[name] = {}\n if full:\n ret[name] = _get_full_output(node, for_output=for_output)\n else:\n public_ips, private_ips = _get_ips(node['networks'])\n ret[name] = {\n 'id': node['id'],\n 'image': node['image']['name'],\n 'name': name,\n 'private_ips': private_ips,\n 'public_ips': public_ips,\n 'size': node['size_slug'],\n 'state': six.text_type(node['status']),\n }\n\n page += 1\n try:\n fetch = 'next' in items['links']['pages']\n except KeyError:\n fetch = False\n\n return ret\n" ]
# -*- coding: utf-8 -*- ''' DigitalOcean Cloud Module ========================= The DigitalOcean cloud module is used to control access to the DigitalOcean VPS system. Use of this module requires a requires a ``personal_access_token``, an ``ssh_key_file``, and at least one SSH key name in ``ssh_key_names``. More ``ssh_key_names`` can be added by separating each key with a comma. The ``personal_access_token`` can be found in the DigitalOcean web interface in the "Apps & API" section. The SSH key name can be found under the "SSH Keys" section. .. code-block:: yaml # Note: This example is for /etc/salt/cloud.providers or any file in the # /etc/salt/cloud.providers.d/ directory. my-digital-ocean-config: personal_access_token: xxx ssh_key_file: /path/to/ssh/key/file ssh_key_names: my-key-name,my-key-name-2 driver: digitalocean :depends: requests ''' # Import Python Libs from __future__ import absolute_import, print_function, unicode_literals import decimal import logging import os import pprint import time # Import Salt Libs import salt.utils.cloud import salt.utils.files import salt.utils.json import salt.utils.stringutils import salt.config as config from salt.exceptions import ( SaltCloudConfigError, SaltInvocationError, SaltCloudNotFound, SaltCloudSystemExit, SaltCloudExecutionFailure, SaltCloudExecutionTimeout ) from salt.ext import six from salt.ext.six.moves import zip # Import Third Party Libs try: import requests HAS_REQUESTS = True except ImportError: HAS_REQUESTS = False # Get logging started log = logging.getLogger(__name__) __virtualname__ = 'digitalocean' __virtual_aliases__ = ('digital_ocean', 'do') # Only load in this module if the DIGITALOCEAN configurations are in place def __virtual__(): ''' Check for DigitalOcean 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=__opts__, provider=__active_provider_name__ or __virtualname__, aliases=__virtual_aliases__, required_keys=('personal_access_token',) ) def get_dependencies(): ''' Warn if dependencies aren't met. ''' return config.check_driver_dependencies( __virtualname__, {'requests': HAS_REQUESTS} ) def avail_locations(call=None): ''' Return a dict of all available VM locations on the cloud provider with relevant data ''' if call == 'action': raise SaltCloudSystemExit( 'The avail_locations function must be called with ' '-f or --function, or with the --list-locations option' ) items = query(method='regions') ret = {} for region in items['regions']: ret[region['name']] = {} for item in six.iterkeys(region): ret[region['name']][item] = six.text_type(region[item]) return ret def avail_images(call=None): ''' Return a list of the images that are on the provider ''' if call == 'action': raise SaltCloudSystemExit( 'The avail_images function must be called with ' '-f or --function, or with the --list-images option' ) fetch = True page = 1 ret = {} while fetch: items = query(method='images', command='?page=' + six.text_type(page) + '&per_page=200') for image in items['images']: ret[image['name']] = {} for item in six.iterkeys(image): ret[image['name']][item] = image[item] page += 1 try: fetch = 'next' in items['links']['pages'] except KeyError: fetch = False return ret def avail_sizes(call=None): ''' Return a list of the image sizes that are on the provider ''' if call == 'action': raise SaltCloudSystemExit( 'The avail_sizes function must be called with ' '-f or --function, or with the --list-sizes option' ) items = query(method='sizes', command='?per_page=100') ret = {} for size in items['sizes']: ret[size['slug']] = {} for item in six.iterkeys(size): ret[size['slug']][item] = six.text_type(size[item]) 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.' ) return _list_nodes() 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('function'), __opts__['query.selection'], call, ) def get_image(vm_): ''' Return the image object to use ''' images = avail_images() vm_image = config.get_cloud_config_value( 'image', vm_, __opts__, search_global=False ) if not isinstance(vm_image, six.string_types): vm_image = six.text_type(vm_image) for image in images: if vm_image in (images[image]['name'], images[image]['slug'], images[image]['id']): if images[image]['slug'] is not None: return images[image]['slug'] return int(images[image]['id']) raise SaltCloudNotFound( 'The specified image, \'{0}\', could not be found.'.format(vm_image) ) def get_size(vm_): ''' Return the VM's size. Used by create_node(). ''' sizes = avail_sizes() vm_size = six.text_type(config.get_cloud_config_value( 'size', vm_, __opts__, search_global=False )) for size in sizes: if vm_size.lower() == sizes[size]['slug']: return sizes[size]['slug'] raise SaltCloudNotFound( 'The specified size, \'{0}\', could not be found.'.format(vm_size) ) def get_location(vm_): ''' Return the VM's location ''' locations = avail_locations() vm_location = six.text_type(config.get_cloud_config_value( 'location', vm_, __opts__, search_global=False )) for location in locations: if vm_location in (locations[location]['name'], locations[location]['slug']): return locations[location]['slug'] raise SaltCloudNotFound( 'The specified location, \'{0}\', could not be found.'.format( vm_location ) ) def create_node(args): ''' Create a node ''' node = query(method='droplets', args=args, http_method='post') return node 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 'digitalocean', vm_['profile'], vm_=vm_) is False: return False except AttributeError: pass __utils__['cloud.fire_event']( 'event', 'starting create', 'salt/cloud/{0}/creating'.format(vm_['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', vm_['name']) kwargs = { 'name': vm_['name'], 'size': get_size(vm_), 'image': get_image(vm_), 'region': get_location(vm_), 'ssh_keys': [], 'tags': [] } # backwards compat ssh_key_name = config.get_cloud_config_value( 'ssh_key_name', vm_, __opts__, search_global=False ) if ssh_key_name: kwargs['ssh_keys'].append(get_keyid(ssh_key_name)) ssh_key_names = config.get_cloud_config_value( 'ssh_key_names', vm_, __opts__, search_global=False, default=False ) if ssh_key_names: for key in ssh_key_names.split(','): kwargs['ssh_keys'].append(get_keyid(key)) key_filename = config.get_cloud_config_value( 'ssh_key_file', vm_, __opts__, search_global=False, default=None ) if key_filename is not None and not os.path.isfile(key_filename): raise SaltCloudConfigError( 'The defined key_filename \'{0}\' does not exist'.format( key_filename ) ) if not __opts__.get('ssh_agent', False) and key_filename is None: raise SaltCloudConfigError( 'The DigitalOcean driver requires an ssh_key_file and an ssh_key_name ' 'because it does not supply a root password upon building the server.' ) ssh_interface = config.get_cloud_config_value( 'ssh_interface', vm_, __opts__, search_global=False, default='public' ) if ssh_interface in ['private', 'public']: log.info("ssh_interface: Setting interface for ssh to %s", ssh_interface) kwargs['ssh_interface'] = ssh_interface else: raise SaltCloudConfigError( "The DigitalOcean driver requires ssh_interface to be defined as 'public' or 'private'." ) private_networking = config.get_cloud_config_value( 'private_networking', vm_, __opts__, search_global=False, default=None, ) if private_networking is not None: if not isinstance(private_networking, bool): raise SaltCloudConfigError("'private_networking' should be a boolean value.") kwargs['private_networking'] = private_networking if not private_networking and ssh_interface == 'private': raise SaltCloudConfigError( "The DigitalOcean driver requires ssh_interface if defined as 'private' " "then private_networking should be set as 'True'." ) backups_enabled = config.get_cloud_config_value( 'backups_enabled', vm_, __opts__, search_global=False, default=None, ) if backups_enabled is not None: if not isinstance(backups_enabled, bool): raise SaltCloudConfigError("'backups_enabled' should be a boolean value.") kwargs['backups'] = backups_enabled ipv6 = config.get_cloud_config_value( 'ipv6', vm_, __opts__, search_global=False, default=None, ) if ipv6 is not None: if not isinstance(ipv6, bool): raise SaltCloudConfigError("'ipv6' should be a boolean value.") kwargs['ipv6'] = ipv6 monitoring = config.get_cloud_config_value( 'monitoring', vm_, __opts__, search_global=False, default=None, ) if monitoring is not None: if not isinstance(monitoring, bool): raise SaltCloudConfigError("'monitoring' should be a boolean value.") kwargs['monitoring'] = monitoring kwargs['tags'] = config.get_cloud_config_value( 'tags', vm_, __opts__, search_global=False, default=False ) userdata_file = config.get_cloud_config_value( 'userdata_file', vm_, __opts__, search_global=False, default=None ) if userdata_file is not None: try: with salt.utils.files.fopen(userdata_file, 'r') as fp_: kwargs['user_data'] = salt.utils.cloud.userdata_template( __opts__, vm_, salt.utils.stringutils.to_unicode(fp_.read()) ) except Exception as exc: log.exception( 'Failed to read userdata from %s: %s', userdata_file, exc) create_dns_record = config.get_cloud_config_value( 'create_dns_record', vm_, __opts__, search_global=False, default=None, ) if create_dns_record: log.info('create_dns_record: will attempt to write DNS records') default_dns_domain = None dns_domain_name = vm_['name'].split('.') if len(dns_domain_name) > 2: log.debug('create_dns_record: inferring default dns_hostname, dns_domain from minion name as FQDN') default_dns_hostname = '.'.join(dns_domain_name[:-2]) default_dns_domain = '.'.join(dns_domain_name[-2:]) else: log.debug("create_dns_record: can't infer dns_domain from %s", vm_['name']) default_dns_hostname = dns_domain_name[0] dns_hostname = config.get_cloud_config_value( 'dns_hostname', vm_, __opts__, search_global=False, default=default_dns_hostname, ) dns_domain = config.get_cloud_config_value( 'dns_domain', vm_, __opts__, search_global=False, default=default_dns_domain, ) if dns_hostname and dns_domain: log.info('create_dns_record: using dns_hostname="%s", dns_domain="%s"', dns_hostname, dns_domain) __add_dns_addr__ = lambda t, d: post_dns_record(dns_domain=dns_domain, name=dns_hostname, record_type=t, record_data=d) log.debug('create_dns_record: %s', __add_dns_addr__) else: log.error('create_dns_record: could not determine dns_hostname and/or dns_domain') raise SaltCloudConfigError( '\'create_dns_record\' must be a dict specifying "domain" ' 'and "hostname" or the minion name must be an FQDN.' ) __utils__['cloud.fire_event']( 'event', 'requesting instance', 'salt/cloud/{0}/requesting'.format(vm_['name']), args=__utils__['cloud.filter_event']('requesting', kwargs, list(kwargs)), sock_dir=__opts__['sock_dir'], transport=__opts__['transport'] ) try: ret = create_node(kwargs) except Exception as exc: log.error( 'Error creating %s on DIGITALOCEAN\n\n' 'The following exception was thrown when trying to ' 'run the initial deployment: %s', vm_['name'], exc, # Show the traceback if the debug logging level is enabled exc_info_on_loglevel=logging.DEBUG ) return False def __query_node_data(vm_name): data = show_instance(vm_name, 'action') if not data: # Trigger an error in the wait_for_ip function return False if data['networks'].get('v4'): for network in data['networks']['v4']: if network['type'] == 'public': return data return False try: data = salt.utils.cloud.wait_for_ip( __query_node_data, update_args=(vm_['name'],), timeout=config.get_cloud_config_value( 'wait_for_ip_timeout', vm_, __opts__, default=10 * 60), interval=config.get_cloud_config_value( 'wait_for_ip_interval', vm_, __opts__, default=10), ) except (SaltCloudExecutionTimeout, SaltCloudExecutionFailure) as exc: try: # It might be already up, let's destroy it! destroy(vm_['name']) except SaltCloudSystemExit: pass finally: raise SaltCloudSystemExit(six.text_type(exc)) if not vm_.get('ssh_host'): vm_['ssh_host'] = None # add DNS records, set ssh_host, default to first found IP, preferring IPv4 for ssh bootstrap script target addr_families, dns_arec_types = (('v4', 'v6'), ('A', 'AAAA')) arec_map = dict(list(zip(addr_families, dns_arec_types))) for facing, addr_family, ip_address in [(net['type'], family, net['ip_address']) for family in addr_families for net in data['networks'][family]]: log.info('found %s IP%s interface for "%s"', facing, addr_family, ip_address) dns_rec_type = arec_map[addr_family] if facing == 'public': if create_dns_record: __add_dns_addr__(dns_rec_type, ip_address) if facing == ssh_interface: if not vm_['ssh_host']: vm_['ssh_host'] = ip_address if vm_['ssh_host'] is None: raise SaltCloudSystemExit( 'No suitable IP addresses found for ssh minion bootstrapping: {0}'.format(repr(data['networks'])) ) log.debug( 'Found public IP address to use for ssh minion bootstrapping: %s', vm_['ssh_host'] ) vm_['key_filename'] = key_filename ret = __utils__['cloud.bootstrap'](vm_, __opts__) ret.update(data) log.info('Created Cloud VM \'%s\'', vm_['name']) log.debug( '\'%s\' VM creation details:\n%s', vm_['name'], pprint.pformat(data) ) __utils__['cloud.fire_event']( 'event', 'created instance', 'salt/cloud/{0}/created'.format(vm_['name']), args=__utils__['cloud.filter_event']('created', vm_, ['name', 'profile', 'provider', 'driver']), sock_dir=__opts__['sock_dir'], transport=__opts__['transport'] ) return ret def query(method='droplets', droplet_id=None, command=None, args=None, http_method='get'): ''' Make a web call to DigitalOcean ''' base_path = six.text_type(config.get_cloud_config_value( 'api_root', get_configured_provider(), __opts__, search_global=False, default='https://api.digitalocean.com/v2' )) path = '{0}/{1}/'.format(base_path, method) if droplet_id: path += '{0}/'.format(droplet_id) if command: path += command if not isinstance(args, dict): args = {} personal_access_token = config.get_cloud_config_value( 'personal_access_token', get_configured_provider(), __opts__, search_global=False ) data = salt.utils.json.dumps(args) requester = getattr(requests, http_method) request = requester(path, data=data, headers={'Authorization': 'Bearer ' + personal_access_token, 'Content-Type': 'application/json'}) if request.status_code > 299: raise SaltCloudSystemExit( 'An error occurred while querying DigitalOcean. HTTP Code: {0} ' 'Error: \'{1}\''.format( request.status_code, # request.read() request.text ) ) log.debug(request.url) # success without data if request.status_code == 204: return True content = request.text result = salt.utils.json.loads(content) if result.get('status', '').lower() == 'error': raise SaltCloudSystemExit( pprint.pformat(result.get('error_message', {})) ) return result 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 show_instance(name, call=None): ''' Show the details from DigitalOcean concerning a droplet ''' if call != 'action': raise SaltCloudSystemExit( 'The show_instance action must be called with -a or --action.' ) node = _get_node(name) __utils__['cloud.cache_node'](node, __active_provider_name__, __opts__) return node def _get_node(name): attempts = 10 while attempts >= 0: try: return list_nodes_full(for_output=False)[name] except KeyError: attempts -= 1 log.debug( 'Failed to get the data for node \'%s\'. Remaining ' 'attempts: %s', name, attempts ) # Just a little delay between attempts... time.sleep(0.5) return {} def list_keypairs(call=None): ''' Return a dict of all available VM locations on the cloud provider with relevant data ''' if call != 'function': log.error( 'The list_keypairs function must be called with -f or --function.' ) return False fetch = True page = 1 ret = {} while fetch: items = query(method='account/keys', command='?page=' + six.text_type(page) + '&per_page=100') for key_pair in items['ssh_keys']: name = key_pair['name'] if name in ret: raise SaltCloudSystemExit( 'A duplicate key pair name, \'{0}\', was found in DigitalOcean\'s ' 'key pair list. Please change the key name stored by DigitalOcean. ' 'Be sure to adjust the value of \'ssh_key_file\' in your cloud ' 'profile or provider configuration, if necessary.'.format( name ) ) ret[name] = {} for item in six.iterkeys(key_pair): ret[name][item] = six.text_type(key_pair[item]) page += 1 try: fetch = 'next' in items['links']['pages'] except KeyError: fetch = False return ret def show_keypair(kwargs=None, call=None): ''' Show the details of an SSH keypair ''' if call != 'function': log.error( 'The show_keypair function must be called with -f or --function.' ) return False if not kwargs: kwargs = {} if 'keyname' not in kwargs: log.error('A keyname is required.') return False keypairs = list_keypairs(call='function') keyid = keypairs[kwargs['keyname']]['id'] log.debug('Key ID is %s', keyid) details = query(method='account/keys', command=keyid) return details def import_keypair(kwargs=None, call=None): ''' Upload public key to cloud provider. Similar to EC2 import_keypair. .. versionadded:: 2016.11.0 kwargs file(mandatory): public key file-name keyname(mandatory): public key name in the provider ''' with salt.utils.files.fopen(kwargs['file'], 'r') as public_key_filename: public_key_content = salt.utils.stringutils.to_unicode(public_key_filename.read()) digitalocean_kwargs = { 'name': kwargs['keyname'], 'public_key': public_key_content } created_result = create_key(digitalocean_kwargs, call=call) return created_result def create_key(kwargs=None, call=None): ''' Upload a public key ''' if call != 'function': log.error( 'The create_key function must be called with -f or --function.' ) return False try: result = query( method='account', command='keys', args={'name': kwargs['name'], 'public_key': kwargs['public_key']}, http_method='post' ) except KeyError: log.info('`name` and `public_key` arguments must be specified') return False return result def remove_key(kwargs=None, call=None): ''' Delete public key ''' if call != 'function': log.error( 'The create_key function must be called with -f or --function.' ) return False try: result = query( method='account', command='keys/' + kwargs['id'], http_method='delete' ) except KeyError: log.info('`id` argument must be specified') return False return result def get_keyid(keyname): ''' Return the ID of the keyname ''' if not keyname: return None keypairs = list_keypairs(call='function') keyid = keypairs[keyname]['id'] if keyid: return keyid raise SaltCloudNotFound('The specified ssh key could not be found.') def destroy(name, call=None): ''' Destroy a node. Will check termination protection and warn if enabled. 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'] ) data = show_instance(name, call='action') node = query(method='droplets', droplet_id=data['id'], http_method='delete') ## This is all terribly optomistic: # vm_ = get_vm_config(name=name) # delete_dns_record = config.get_cloud_config_value( # 'delete_dns_record', vm_, __opts__, search_global=False, default=None, # ) # TODO: when _vm config data can be made available, we should honor the configuration settings, # but until then, we should assume stale DNS records are bad, and default behavior should be to # delete them if we can. When this is resolved, also resolve the comments a couple of lines below. delete_dns_record = True if not isinstance(delete_dns_record, bool): raise SaltCloudConfigError( '\'delete_dns_record\' should be a boolean value.' ) # When the "to do" a few lines up is resolved, remove these lines and use the if/else logic below. log.debug('Deleting DNS records for %s.', name) destroy_dns_records(name) # Until the "to do" from line 754 is taken care of, we don't need this logic. # if delete_dns_record: # log.debug('Deleting DNS records for %s.', name) # destroy_dns_records(name) # else: # log.debug('delete_dns_record : %s', delete_dns_record) # for line in pprint.pformat(dir()).splitlines(): # log.debug('delete context: %s', line) __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 node def post_dns_record(**kwargs): ''' Creates a DNS record for the given name if the domain is managed with DO. ''' if 'kwargs' in kwargs: # flatten kwargs if called via salt-cloud -f f_kwargs = kwargs['kwargs'] del kwargs['kwargs'] kwargs.update(f_kwargs) mandatory_kwargs = ('dns_domain', 'name', 'record_type', 'record_data') for i in mandatory_kwargs: if kwargs[i]: pass else: error = '{0}="{1}" ## all mandatory args must be provided: {2}'.format(i, kwargs[i], mandatory_kwargs) raise SaltInvocationError(error) domain = query(method='domains', droplet_id=kwargs['dns_domain']) if domain: result = query( method='domains', droplet_id=kwargs['dns_domain'], command='records', args={'type': kwargs['record_type'], 'name': kwargs['name'], 'data': kwargs['record_data']}, http_method='post' ) return result return False def destroy_dns_records(fqdn): ''' Deletes DNS records for the given hostname if the domain is managed with DO. ''' domain = '.'.join(fqdn.split('.')[-2:]) hostname = '.'.join(fqdn.split('.')[:-2]) # TODO: remove this when the todo on 754 is available try: response = query(method='domains', droplet_id=domain, command='records') except SaltCloudSystemExit: log.debug('Failed to find domains.') return False log.debug("found DNS records: %s", pprint.pformat(response)) records = response['domain_records'] if records: record_ids = [r['id'] for r in records if r['name'].decode() == hostname] log.debug("deleting DNS record IDs: %s", record_ids) for id_ in record_ids: try: log.info('deleting DNS record %s', id_) ret = query( method='domains', droplet_id=domain, command='records/{0}'.format(id_), http_method='delete' ) except SaltCloudSystemExit: log.error('failed to delete DNS domain %s record ID %s.', domain, hostname) log.debug('DNS deletion REST call returned: %s', pprint.pformat(ret)) return False def show_pricing(kwargs=None, call=None): ''' Show pricing for a particular profile. This is only an estimate, based on unofficial pricing sources. .. versionadded:: 2015.8.0 CLI Examples: .. code-block:: bash salt-cloud -f show_pricing my-digitalocean-config profile=my-profile ''' profile = __opts__['profiles'].get(kwargs['profile'], {}) if not profile: return {'Error': 'The requested profile was not found'} # Make sure the profile belongs to DigitalOcean provider = profile.get('provider', '0:0') comps = provider.split(':') if len(comps) < 2 or comps[1] != 'digitalocean': return {'Error': 'The requested profile does not belong to DigitalOcean'} raw = {} ret = {} sizes = avail_sizes() ret['per_hour'] = decimal.Decimal(sizes[profile['size']]['price_hourly']) ret['per_day'] = ret['per_hour'] * 24 ret['per_week'] = ret['per_day'] * 7 ret['per_month'] = decimal.Decimal(sizes[profile['size']]['price_monthly']) ret['per_year'] = ret['per_week'] * 52 if kwargs.get('raw', False): ret['_raw'] = raw return {profile['profile']: ret} def list_floating_ips(call=None): ''' Return a list of the floating ips that are on the provider .. versionadded:: 2016.3.0 CLI Examples: .. code-block:: bash salt-cloud -f list_floating_ips my-digitalocean-config ''' if call == 'action': raise SaltCloudSystemExit( 'The list_floating_ips function must be called with ' '-f or --function, or with the --list-floating-ips option' ) fetch = True page = 1 ret = {} while fetch: items = query(method='floating_ips', command='?page=' + six.text_type(page) + '&per_page=200') for floating_ip in items['floating_ips']: ret[floating_ip['ip']] = {} for item in six.iterkeys(floating_ip): ret[floating_ip['ip']][item] = floating_ip[item] page += 1 try: fetch = 'next' in items['links']['pages'] except KeyError: fetch = False return ret def show_floating_ip(kwargs=None, call=None): ''' Show the details of a floating IP .. versionadded:: 2016.3.0 CLI Examples: .. code-block:: bash salt-cloud -f show_floating_ip my-digitalocean-config floating_ip='45.55.96.47' ''' if call != 'function': log.error( 'The show_floating_ip function must be called with -f or --function.' ) return False if not kwargs: kwargs = {} if 'floating_ip' not in kwargs: log.error('A floating IP is required.') return False floating_ip = kwargs['floating_ip'] log.debug('Floating ip is %s', floating_ip) details = query(method='floating_ips', command=floating_ip) return details def create_floating_ip(kwargs=None, call=None): ''' Create a new floating IP .. versionadded:: 2016.3.0 CLI Examples: .. code-block:: bash salt-cloud -f create_floating_ip my-digitalocean-config region='NYC2' salt-cloud -f create_floating_ip my-digitalocean-config droplet_id='1234567' ''' if call != 'function': log.error( 'The create_floating_ip function must be called with -f or --function.' ) return False if not kwargs: kwargs = {} if 'droplet_id' in kwargs: result = query(method='floating_ips', args={'droplet_id': kwargs['droplet_id']}, http_method='post') return result elif 'region' in kwargs: result = query(method='floating_ips', args={'region': kwargs['region']}, http_method='post') return result else: log.error('A droplet_id or region is required.') return False def delete_floating_ip(kwargs=None, call=None): ''' Delete a floating IP .. versionadded:: 2016.3.0 CLI Examples: .. code-block:: bash salt-cloud -f delete_floating_ip my-digitalocean-config floating_ip='45.55.96.47' ''' if call != 'function': log.error( 'The delete_floating_ip function must be called with -f or --function.' ) return False if not kwargs: kwargs = {} if 'floating_ip' not in kwargs: log.error('A floating IP is required.') return False floating_ip = kwargs['floating_ip'] log.debug('Floating ip is %s', kwargs['floating_ip']) result = query(method='floating_ips', command=floating_ip, http_method='delete') return result def assign_floating_ip(kwargs=None, call=None): ''' Assign a floating IP .. versionadded:: 2016.3.0 CLI Examples: .. code-block:: bash salt-cloud -f assign_floating_ip my-digitalocean-config droplet_id=1234567 floating_ip='45.55.96.47' ''' if call != 'function': log.error( 'The assign_floating_ip function must be called with -f or --function.' ) return False if not kwargs: kwargs = {} if 'floating_ip' and 'droplet_id' not in kwargs: log.error('A floating IP and droplet_id is required.') return False result = query(method='floating_ips', command=kwargs['floating_ip'] + '/actions', args={'droplet_id': kwargs['droplet_id'], 'type': 'assign'}, http_method='post') return result def unassign_floating_ip(kwargs=None, call=None): ''' Unassign a floating IP .. versionadded:: 2016.3.0 CLI Examples: .. code-block:: bash salt-cloud -f unassign_floating_ip my-digitalocean-config floating_ip='45.55.96.47' ''' if call != 'function': log.error( 'The inassign_floating_ip function must be called with -f or --function.' ) return False if not kwargs: kwargs = {} if 'floating_ip' not in kwargs: log.error('A floating IP is required.') return False result = query(method='floating_ips', command=kwargs['floating_ip'] + '/actions', args={'type': 'unassign'}, http_method='post') return result def _list_nodes(full=False, for_output=False): ''' Helper function to format and parse node data. ''' fetch = True page = 1 ret = {} while fetch: items = query(method='droplets', command='?page=' + six.text_type(page) + '&per_page=200') for node in items['droplets']: name = node['name'] ret[name] = {} if full: ret[name] = _get_full_output(node, for_output=for_output) else: public_ips, private_ips = _get_ips(node['networks']) ret[name] = { 'id': node['id'], 'image': node['image']['name'], 'name': name, 'private_ips': private_ips, 'public_ips': public_ips, 'size': node['size_slug'], 'state': six.text_type(node['status']), } page += 1 try: fetch = 'next' in items['links']['pages'] except KeyError: fetch = False return ret def reboot(name, call=None): ''' Reboot a droplet in DigitalOcean. .. versionadded:: 2015.8.8 name The name of the droplet to restart. CLI Example: .. code-block:: bash salt-cloud -a reboot droplet_name ''' if call != 'action': raise SaltCloudSystemExit( 'The restart action must be called with -a or --action.' ) data = show_instance(name, call='action') if data.get('status') == 'off': return {'success': True, 'action': 'stop', 'status': 'off', 'msg': 'Machine is already off.'} ret = query(droplet_id=data['id'], command='actions', args={'type': 'reboot'}, http_method='post') return {'success': True, 'action': ret['action']['type'], 'state': ret['action']['status']} def start(name, call=None): ''' Start a droplet in DigitalOcean. .. versionadded:: 2015.8.8 name The name of the droplet to start. CLI Example: .. code-block:: bash salt-cloud -a start droplet_name ''' if call != 'action': raise SaltCloudSystemExit( 'The start action must be called with -a or --action.' ) data = show_instance(name, call='action') if data.get('status') == 'active': return {'success': True, 'action': 'start', 'status': 'active', 'msg': 'Machine is already running.'} ret = query(droplet_id=data['id'], command='actions', args={'type': 'power_on'}, http_method='post') return {'success': True, 'action': ret['action']['type'], 'state': ret['action']['status']} def stop(name, call=None): ''' Stop a droplet in DigitalOcean. .. versionadded:: 2015.8.8 name The name of the droplet to stop. CLI Example: .. code-block:: bash salt-cloud -a stop droplet_name ''' if call != 'action': raise SaltCloudSystemExit( 'The stop action must be called with -a or --action.' ) data = show_instance(name, call='action') if data.get('status') == 'off': return {'success': True, 'action': 'stop', 'status': 'off', 'msg': 'Machine is already off.'} ret = query(droplet_id=data['id'], command='actions', args={'type': 'shutdown'}, http_method='post') return {'success': True, 'action': ret['action']['type'], 'state': ret['action']['status']} def _get_full_output(node, for_output=False): ''' Helper function for _list_nodes to loop through all node information. Returns a dictionary containing the full information of a node. ''' ret = {} for item in six.iterkeys(node): value = node[item] if value is not None and for_output: value = six.text_type(value) ret[item] = value return ret def _get_ips(networks): ''' Helper function for list_nodes. Returns public and private ip lists based on a given network dictionary. ''' v4s = networks.get('v4') v6s = networks.get('v6') public_ips = [] private_ips = [] if v4s: for item in v4s: ip_type = item.get('type') ip_address = item.get('ip_address') if ip_type == 'public': public_ips.append(ip_address) if ip_type == 'private': private_ips.append(ip_address) if v6s: for item in v6s: ip_type = item.get('type') ip_address = item.get('ip_address') if ip_type == 'public': public_ips.append(ip_address) if ip_type == 'private': private_ips.append(ip_address) return public_ips, private_ips
saltstack/salt
salt/cloud/clouds/digitalocean.py
get_image
python
def get_image(vm_): ''' Return the image object to use ''' images = avail_images() vm_image = config.get_cloud_config_value( 'image', vm_, __opts__, search_global=False ) if not isinstance(vm_image, six.string_types): vm_image = six.text_type(vm_image) for image in images: if vm_image in (images[image]['name'], images[image]['slug'], images[image]['id']): if images[image]['slug'] is not None: return images[image]['slug'] return int(images[image]['id']) raise SaltCloudNotFound( 'The specified image, \'{0}\', could not be found.'.format(vm_image) )
Return the image object to use
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/digitalocean.py#L206-L226
[ "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 avail_images(call=None):\n '''\n Return a list of the images that are on the provider\n '''\n if call == 'action':\n raise SaltCloudSystemExit(\n 'The avail_images function must be called with '\n '-f or --function, or with the --list-images option'\n )\n\n fetch = True\n page = 1\n ret = {}\n\n while fetch:\n items = query(method='images', command='?page=' + six.text_type(page) + '&per_page=200')\n\n for image in items['images']:\n ret[image['name']] = {}\n for item in six.iterkeys(image):\n ret[image['name']][item] = image[item]\n\n page += 1\n try:\n fetch = 'next' in items['links']['pages']\n except KeyError:\n fetch = False\n\n return ret\n" ]
# -*- coding: utf-8 -*- ''' DigitalOcean Cloud Module ========================= The DigitalOcean cloud module is used to control access to the DigitalOcean VPS system. Use of this module requires a requires a ``personal_access_token``, an ``ssh_key_file``, and at least one SSH key name in ``ssh_key_names``. More ``ssh_key_names`` can be added by separating each key with a comma. The ``personal_access_token`` can be found in the DigitalOcean web interface in the "Apps & API" section. The SSH key name can be found under the "SSH Keys" section. .. code-block:: yaml # Note: This example is for /etc/salt/cloud.providers or any file in the # /etc/salt/cloud.providers.d/ directory. my-digital-ocean-config: personal_access_token: xxx ssh_key_file: /path/to/ssh/key/file ssh_key_names: my-key-name,my-key-name-2 driver: digitalocean :depends: requests ''' # Import Python Libs from __future__ import absolute_import, print_function, unicode_literals import decimal import logging import os import pprint import time # Import Salt Libs import salt.utils.cloud import salt.utils.files import salt.utils.json import salt.utils.stringutils import salt.config as config from salt.exceptions import ( SaltCloudConfigError, SaltInvocationError, SaltCloudNotFound, SaltCloudSystemExit, SaltCloudExecutionFailure, SaltCloudExecutionTimeout ) from salt.ext import six from salt.ext.six.moves import zip # Import Third Party Libs try: import requests HAS_REQUESTS = True except ImportError: HAS_REQUESTS = False # Get logging started log = logging.getLogger(__name__) __virtualname__ = 'digitalocean' __virtual_aliases__ = ('digital_ocean', 'do') # Only load in this module if the DIGITALOCEAN configurations are in place def __virtual__(): ''' Check for DigitalOcean 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=__opts__, provider=__active_provider_name__ or __virtualname__, aliases=__virtual_aliases__, required_keys=('personal_access_token',) ) def get_dependencies(): ''' Warn if dependencies aren't met. ''' return config.check_driver_dependencies( __virtualname__, {'requests': HAS_REQUESTS} ) def avail_locations(call=None): ''' Return a dict of all available VM locations on the cloud provider with relevant data ''' if call == 'action': raise SaltCloudSystemExit( 'The avail_locations function must be called with ' '-f or --function, or with the --list-locations option' ) items = query(method='regions') ret = {} for region in items['regions']: ret[region['name']] = {} for item in six.iterkeys(region): ret[region['name']][item] = six.text_type(region[item]) return ret def avail_images(call=None): ''' Return a list of the images that are on the provider ''' if call == 'action': raise SaltCloudSystemExit( 'The avail_images function must be called with ' '-f or --function, or with the --list-images option' ) fetch = True page = 1 ret = {} while fetch: items = query(method='images', command='?page=' + six.text_type(page) + '&per_page=200') for image in items['images']: ret[image['name']] = {} for item in six.iterkeys(image): ret[image['name']][item] = image[item] page += 1 try: fetch = 'next' in items['links']['pages'] except KeyError: fetch = False return ret def avail_sizes(call=None): ''' Return a list of the image sizes that are on the provider ''' if call == 'action': raise SaltCloudSystemExit( 'The avail_sizes function must be called with ' '-f or --function, or with the --list-sizes option' ) items = query(method='sizes', command='?per_page=100') ret = {} for size in items['sizes']: ret[size['slug']] = {} for item in six.iterkeys(size): ret[size['slug']][item] = six.text_type(size[item]) 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.' ) return _list_nodes() def list_nodes_full(call=None, for_output=True): ''' 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.' ) return _list_nodes(full=True, for_output=for_output) 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('function'), __opts__['query.selection'], call, ) def get_size(vm_): ''' Return the VM's size. Used by create_node(). ''' sizes = avail_sizes() vm_size = six.text_type(config.get_cloud_config_value( 'size', vm_, __opts__, search_global=False )) for size in sizes: if vm_size.lower() == sizes[size]['slug']: return sizes[size]['slug'] raise SaltCloudNotFound( 'The specified size, \'{0}\', could not be found.'.format(vm_size) ) def get_location(vm_): ''' Return the VM's location ''' locations = avail_locations() vm_location = six.text_type(config.get_cloud_config_value( 'location', vm_, __opts__, search_global=False )) for location in locations: if vm_location in (locations[location]['name'], locations[location]['slug']): return locations[location]['slug'] raise SaltCloudNotFound( 'The specified location, \'{0}\', could not be found.'.format( vm_location ) ) def create_node(args): ''' Create a node ''' node = query(method='droplets', args=args, http_method='post') return node 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 'digitalocean', vm_['profile'], vm_=vm_) is False: return False except AttributeError: pass __utils__['cloud.fire_event']( 'event', 'starting create', 'salt/cloud/{0}/creating'.format(vm_['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', vm_['name']) kwargs = { 'name': vm_['name'], 'size': get_size(vm_), 'image': get_image(vm_), 'region': get_location(vm_), 'ssh_keys': [], 'tags': [] } # backwards compat ssh_key_name = config.get_cloud_config_value( 'ssh_key_name', vm_, __opts__, search_global=False ) if ssh_key_name: kwargs['ssh_keys'].append(get_keyid(ssh_key_name)) ssh_key_names = config.get_cloud_config_value( 'ssh_key_names', vm_, __opts__, search_global=False, default=False ) if ssh_key_names: for key in ssh_key_names.split(','): kwargs['ssh_keys'].append(get_keyid(key)) key_filename = config.get_cloud_config_value( 'ssh_key_file', vm_, __opts__, search_global=False, default=None ) if key_filename is not None and not os.path.isfile(key_filename): raise SaltCloudConfigError( 'The defined key_filename \'{0}\' does not exist'.format( key_filename ) ) if not __opts__.get('ssh_agent', False) and key_filename is None: raise SaltCloudConfigError( 'The DigitalOcean driver requires an ssh_key_file and an ssh_key_name ' 'because it does not supply a root password upon building the server.' ) ssh_interface = config.get_cloud_config_value( 'ssh_interface', vm_, __opts__, search_global=False, default='public' ) if ssh_interface in ['private', 'public']: log.info("ssh_interface: Setting interface for ssh to %s", ssh_interface) kwargs['ssh_interface'] = ssh_interface else: raise SaltCloudConfigError( "The DigitalOcean driver requires ssh_interface to be defined as 'public' or 'private'." ) private_networking = config.get_cloud_config_value( 'private_networking', vm_, __opts__, search_global=False, default=None, ) if private_networking is not None: if not isinstance(private_networking, bool): raise SaltCloudConfigError("'private_networking' should be a boolean value.") kwargs['private_networking'] = private_networking if not private_networking and ssh_interface == 'private': raise SaltCloudConfigError( "The DigitalOcean driver requires ssh_interface if defined as 'private' " "then private_networking should be set as 'True'." ) backups_enabled = config.get_cloud_config_value( 'backups_enabled', vm_, __opts__, search_global=False, default=None, ) if backups_enabled is not None: if not isinstance(backups_enabled, bool): raise SaltCloudConfigError("'backups_enabled' should be a boolean value.") kwargs['backups'] = backups_enabled ipv6 = config.get_cloud_config_value( 'ipv6', vm_, __opts__, search_global=False, default=None, ) if ipv6 is not None: if not isinstance(ipv6, bool): raise SaltCloudConfigError("'ipv6' should be a boolean value.") kwargs['ipv6'] = ipv6 monitoring = config.get_cloud_config_value( 'monitoring', vm_, __opts__, search_global=False, default=None, ) if monitoring is not None: if not isinstance(monitoring, bool): raise SaltCloudConfigError("'monitoring' should be a boolean value.") kwargs['monitoring'] = monitoring kwargs['tags'] = config.get_cloud_config_value( 'tags', vm_, __opts__, search_global=False, default=False ) userdata_file = config.get_cloud_config_value( 'userdata_file', vm_, __opts__, search_global=False, default=None ) if userdata_file is not None: try: with salt.utils.files.fopen(userdata_file, 'r') as fp_: kwargs['user_data'] = salt.utils.cloud.userdata_template( __opts__, vm_, salt.utils.stringutils.to_unicode(fp_.read()) ) except Exception as exc: log.exception( 'Failed to read userdata from %s: %s', userdata_file, exc) create_dns_record = config.get_cloud_config_value( 'create_dns_record', vm_, __opts__, search_global=False, default=None, ) if create_dns_record: log.info('create_dns_record: will attempt to write DNS records') default_dns_domain = None dns_domain_name = vm_['name'].split('.') if len(dns_domain_name) > 2: log.debug('create_dns_record: inferring default dns_hostname, dns_domain from minion name as FQDN') default_dns_hostname = '.'.join(dns_domain_name[:-2]) default_dns_domain = '.'.join(dns_domain_name[-2:]) else: log.debug("create_dns_record: can't infer dns_domain from %s", vm_['name']) default_dns_hostname = dns_domain_name[0] dns_hostname = config.get_cloud_config_value( 'dns_hostname', vm_, __opts__, search_global=False, default=default_dns_hostname, ) dns_domain = config.get_cloud_config_value( 'dns_domain', vm_, __opts__, search_global=False, default=default_dns_domain, ) if dns_hostname and dns_domain: log.info('create_dns_record: using dns_hostname="%s", dns_domain="%s"', dns_hostname, dns_domain) __add_dns_addr__ = lambda t, d: post_dns_record(dns_domain=dns_domain, name=dns_hostname, record_type=t, record_data=d) log.debug('create_dns_record: %s', __add_dns_addr__) else: log.error('create_dns_record: could not determine dns_hostname and/or dns_domain') raise SaltCloudConfigError( '\'create_dns_record\' must be a dict specifying "domain" ' 'and "hostname" or the minion name must be an FQDN.' ) __utils__['cloud.fire_event']( 'event', 'requesting instance', 'salt/cloud/{0}/requesting'.format(vm_['name']), args=__utils__['cloud.filter_event']('requesting', kwargs, list(kwargs)), sock_dir=__opts__['sock_dir'], transport=__opts__['transport'] ) try: ret = create_node(kwargs) except Exception as exc: log.error( 'Error creating %s on DIGITALOCEAN\n\n' 'The following exception was thrown when trying to ' 'run the initial deployment: %s', vm_['name'], exc, # Show the traceback if the debug logging level is enabled exc_info_on_loglevel=logging.DEBUG ) return False def __query_node_data(vm_name): data = show_instance(vm_name, 'action') if not data: # Trigger an error in the wait_for_ip function return False if data['networks'].get('v4'): for network in data['networks']['v4']: if network['type'] == 'public': return data return False try: data = salt.utils.cloud.wait_for_ip( __query_node_data, update_args=(vm_['name'],), timeout=config.get_cloud_config_value( 'wait_for_ip_timeout', vm_, __opts__, default=10 * 60), interval=config.get_cloud_config_value( 'wait_for_ip_interval', vm_, __opts__, default=10), ) except (SaltCloudExecutionTimeout, SaltCloudExecutionFailure) as exc: try: # It might be already up, let's destroy it! destroy(vm_['name']) except SaltCloudSystemExit: pass finally: raise SaltCloudSystemExit(six.text_type(exc)) if not vm_.get('ssh_host'): vm_['ssh_host'] = None # add DNS records, set ssh_host, default to first found IP, preferring IPv4 for ssh bootstrap script target addr_families, dns_arec_types = (('v4', 'v6'), ('A', 'AAAA')) arec_map = dict(list(zip(addr_families, dns_arec_types))) for facing, addr_family, ip_address in [(net['type'], family, net['ip_address']) for family in addr_families for net in data['networks'][family]]: log.info('found %s IP%s interface for "%s"', facing, addr_family, ip_address) dns_rec_type = arec_map[addr_family] if facing == 'public': if create_dns_record: __add_dns_addr__(dns_rec_type, ip_address) if facing == ssh_interface: if not vm_['ssh_host']: vm_['ssh_host'] = ip_address if vm_['ssh_host'] is None: raise SaltCloudSystemExit( 'No suitable IP addresses found for ssh minion bootstrapping: {0}'.format(repr(data['networks'])) ) log.debug( 'Found public IP address to use for ssh minion bootstrapping: %s', vm_['ssh_host'] ) vm_['key_filename'] = key_filename ret = __utils__['cloud.bootstrap'](vm_, __opts__) ret.update(data) log.info('Created Cloud VM \'%s\'', vm_['name']) log.debug( '\'%s\' VM creation details:\n%s', vm_['name'], pprint.pformat(data) ) __utils__['cloud.fire_event']( 'event', 'created instance', 'salt/cloud/{0}/created'.format(vm_['name']), args=__utils__['cloud.filter_event']('created', vm_, ['name', 'profile', 'provider', 'driver']), sock_dir=__opts__['sock_dir'], transport=__opts__['transport'] ) return ret def query(method='droplets', droplet_id=None, command=None, args=None, http_method='get'): ''' Make a web call to DigitalOcean ''' base_path = six.text_type(config.get_cloud_config_value( 'api_root', get_configured_provider(), __opts__, search_global=False, default='https://api.digitalocean.com/v2' )) path = '{0}/{1}/'.format(base_path, method) if droplet_id: path += '{0}/'.format(droplet_id) if command: path += command if not isinstance(args, dict): args = {} personal_access_token = config.get_cloud_config_value( 'personal_access_token', get_configured_provider(), __opts__, search_global=False ) data = salt.utils.json.dumps(args) requester = getattr(requests, http_method) request = requester(path, data=data, headers={'Authorization': 'Bearer ' + personal_access_token, 'Content-Type': 'application/json'}) if request.status_code > 299: raise SaltCloudSystemExit( 'An error occurred while querying DigitalOcean. HTTP Code: {0} ' 'Error: \'{1}\''.format( request.status_code, # request.read() request.text ) ) log.debug(request.url) # success without data if request.status_code == 204: return True content = request.text result = salt.utils.json.loads(content) if result.get('status', '').lower() == 'error': raise SaltCloudSystemExit( pprint.pformat(result.get('error_message', {})) ) return result 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 show_instance(name, call=None): ''' Show the details from DigitalOcean concerning a droplet ''' if call != 'action': raise SaltCloudSystemExit( 'The show_instance action must be called with -a or --action.' ) node = _get_node(name) __utils__['cloud.cache_node'](node, __active_provider_name__, __opts__) return node def _get_node(name): attempts = 10 while attempts >= 0: try: return list_nodes_full(for_output=False)[name] except KeyError: attempts -= 1 log.debug( 'Failed to get the data for node \'%s\'. Remaining ' 'attempts: %s', name, attempts ) # Just a little delay between attempts... time.sleep(0.5) return {} def list_keypairs(call=None): ''' Return a dict of all available VM locations on the cloud provider with relevant data ''' if call != 'function': log.error( 'The list_keypairs function must be called with -f or --function.' ) return False fetch = True page = 1 ret = {} while fetch: items = query(method='account/keys', command='?page=' + six.text_type(page) + '&per_page=100') for key_pair in items['ssh_keys']: name = key_pair['name'] if name in ret: raise SaltCloudSystemExit( 'A duplicate key pair name, \'{0}\', was found in DigitalOcean\'s ' 'key pair list. Please change the key name stored by DigitalOcean. ' 'Be sure to adjust the value of \'ssh_key_file\' in your cloud ' 'profile or provider configuration, if necessary.'.format( name ) ) ret[name] = {} for item in six.iterkeys(key_pair): ret[name][item] = six.text_type(key_pair[item]) page += 1 try: fetch = 'next' in items['links']['pages'] except KeyError: fetch = False return ret def show_keypair(kwargs=None, call=None): ''' Show the details of an SSH keypair ''' if call != 'function': log.error( 'The show_keypair function must be called with -f or --function.' ) return False if not kwargs: kwargs = {} if 'keyname' not in kwargs: log.error('A keyname is required.') return False keypairs = list_keypairs(call='function') keyid = keypairs[kwargs['keyname']]['id'] log.debug('Key ID is %s', keyid) details = query(method='account/keys', command=keyid) return details def import_keypair(kwargs=None, call=None): ''' Upload public key to cloud provider. Similar to EC2 import_keypair. .. versionadded:: 2016.11.0 kwargs file(mandatory): public key file-name keyname(mandatory): public key name in the provider ''' with salt.utils.files.fopen(kwargs['file'], 'r') as public_key_filename: public_key_content = salt.utils.stringutils.to_unicode(public_key_filename.read()) digitalocean_kwargs = { 'name': kwargs['keyname'], 'public_key': public_key_content } created_result = create_key(digitalocean_kwargs, call=call) return created_result def create_key(kwargs=None, call=None): ''' Upload a public key ''' if call != 'function': log.error( 'The create_key function must be called with -f or --function.' ) return False try: result = query( method='account', command='keys', args={'name': kwargs['name'], 'public_key': kwargs['public_key']}, http_method='post' ) except KeyError: log.info('`name` and `public_key` arguments must be specified') return False return result def remove_key(kwargs=None, call=None): ''' Delete public key ''' if call != 'function': log.error( 'The create_key function must be called with -f or --function.' ) return False try: result = query( method='account', command='keys/' + kwargs['id'], http_method='delete' ) except KeyError: log.info('`id` argument must be specified') return False return result def get_keyid(keyname): ''' Return the ID of the keyname ''' if not keyname: return None keypairs = list_keypairs(call='function') keyid = keypairs[keyname]['id'] if keyid: return keyid raise SaltCloudNotFound('The specified ssh key could not be found.') def destroy(name, call=None): ''' Destroy a node. Will check termination protection and warn if enabled. 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'] ) data = show_instance(name, call='action') node = query(method='droplets', droplet_id=data['id'], http_method='delete') ## This is all terribly optomistic: # vm_ = get_vm_config(name=name) # delete_dns_record = config.get_cloud_config_value( # 'delete_dns_record', vm_, __opts__, search_global=False, default=None, # ) # TODO: when _vm config data can be made available, we should honor the configuration settings, # but until then, we should assume stale DNS records are bad, and default behavior should be to # delete them if we can. When this is resolved, also resolve the comments a couple of lines below. delete_dns_record = True if not isinstance(delete_dns_record, bool): raise SaltCloudConfigError( '\'delete_dns_record\' should be a boolean value.' ) # When the "to do" a few lines up is resolved, remove these lines and use the if/else logic below. log.debug('Deleting DNS records for %s.', name) destroy_dns_records(name) # Until the "to do" from line 754 is taken care of, we don't need this logic. # if delete_dns_record: # log.debug('Deleting DNS records for %s.', name) # destroy_dns_records(name) # else: # log.debug('delete_dns_record : %s', delete_dns_record) # for line in pprint.pformat(dir()).splitlines(): # log.debug('delete context: %s', line) __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 node def post_dns_record(**kwargs): ''' Creates a DNS record for the given name if the domain is managed with DO. ''' if 'kwargs' in kwargs: # flatten kwargs if called via salt-cloud -f f_kwargs = kwargs['kwargs'] del kwargs['kwargs'] kwargs.update(f_kwargs) mandatory_kwargs = ('dns_domain', 'name', 'record_type', 'record_data') for i in mandatory_kwargs: if kwargs[i]: pass else: error = '{0}="{1}" ## all mandatory args must be provided: {2}'.format(i, kwargs[i], mandatory_kwargs) raise SaltInvocationError(error) domain = query(method='domains', droplet_id=kwargs['dns_domain']) if domain: result = query( method='domains', droplet_id=kwargs['dns_domain'], command='records', args={'type': kwargs['record_type'], 'name': kwargs['name'], 'data': kwargs['record_data']}, http_method='post' ) return result return False def destroy_dns_records(fqdn): ''' Deletes DNS records for the given hostname if the domain is managed with DO. ''' domain = '.'.join(fqdn.split('.')[-2:]) hostname = '.'.join(fqdn.split('.')[:-2]) # TODO: remove this when the todo on 754 is available try: response = query(method='domains', droplet_id=domain, command='records') except SaltCloudSystemExit: log.debug('Failed to find domains.') return False log.debug("found DNS records: %s", pprint.pformat(response)) records = response['domain_records'] if records: record_ids = [r['id'] for r in records if r['name'].decode() == hostname] log.debug("deleting DNS record IDs: %s", record_ids) for id_ in record_ids: try: log.info('deleting DNS record %s', id_) ret = query( method='domains', droplet_id=domain, command='records/{0}'.format(id_), http_method='delete' ) except SaltCloudSystemExit: log.error('failed to delete DNS domain %s record ID %s.', domain, hostname) log.debug('DNS deletion REST call returned: %s', pprint.pformat(ret)) return False def show_pricing(kwargs=None, call=None): ''' Show pricing for a particular profile. This is only an estimate, based on unofficial pricing sources. .. versionadded:: 2015.8.0 CLI Examples: .. code-block:: bash salt-cloud -f show_pricing my-digitalocean-config profile=my-profile ''' profile = __opts__['profiles'].get(kwargs['profile'], {}) if not profile: return {'Error': 'The requested profile was not found'} # Make sure the profile belongs to DigitalOcean provider = profile.get('provider', '0:0') comps = provider.split(':') if len(comps) < 2 or comps[1] != 'digitalocean': return {'Error': 'The requested profile does not belong to DigitalOcean'} raw = {} ret = {} sizes = avail_sizes() ret['per_hour'] = decimal.Decimal(sizes[profile['size']]['price_hourly']) ret['per_day'] = ret['per_hour'] * 24 ret['per_week'] = ret['per_day'] * 7 ret['per_month'] = decimal.Decimal(sizes[profile['size']]['price_monthly']) ret['per_year'] = ret['per_week'] * 52 if kwargs.get('raw', False): ret['_raw'] = raw return {profile['profile']: ret} def list_floating_ips(call=None): ''' Return a list of the floating ips that are on the provider .. versionadded:: 2016.3.0 CLI Examples: .. code-block:: bash salt-cloud -f list_floating_ips my-digitalocean-config ''' if call == 'action': raise SaltCloudSystemExit( 'The list_floating_ips function must be called with ' '-f or --function, or with the --list-floating-ips option' ) fetch = True page = 1 ret = {} while fetch: items = query(method='floating_ips', command='?page=' + six.text_type(page) + '&per_page=200') for floating_ip in items['floating_ips']: ret[floating_ip['ip']] = {} for item in six.iterkeys(floating_ip): ret[floating_ip['ip']][item] = floating_ip[item] page += 1 try: fetch = 'next' in items['links']['pages'] except KeyError: fetch = False return ret def show_floating_ip(kwargs=None, call=None): ''' Show the details of a floating IP .. versionadded:: 2016.3.0 CLI Examples: .. code-block:: bash salt-cloud -f show_floating_ip my-digitalocean-config floating_ip='45.55.96.47' ''' if call != 'function': log.error( 'The show_floating_ip function must be called with -f or --function.' ) return False if not kwargs: kwargs = {} if 'floating_ip' not in kwargs: log.error('A floating IP is required.') return False floating_ip = kwargs['floating_ip'] log.debug('Floating ip is %s', floating_ip) details = query(method='floating_ips', command=floating_ip) return details def create_floating_ip(kwargs=None, call=None): ''' Create a new floating IP .. versionadded:: 2016.3.0 CLI Examples: .. code-block:: bash salt-cloud -f create_floating_ip my-digitalocean-config region='NYC2' salt-cloud -f create_floating_ip my-digitalocean-config droplet_id='1234567' ''' if call != 'function': log.error( 'The create_floating_ip function must be called with -f or --function.' ) return False if not kwargs: kwargs = {} if 'droplet_id' in kwargs: result = query(method='floating_ips', args={'droplet_id': kwargs['droplet_id']}, http_method='post') return result elif 'region' in kwargs: result = query(method='floating_ips', args={'region': kwargs['region']}, http_method='post') return result else: log.error('A droplet_id or region is required.') return False def delete_floating_ip(kwargs=None, call=None): ''' Delete a floating IP .. versionadded:: 2016.3.0 CLI Examples: .. code-block:: bash salt-cloud -f delete_floating_ip my-digitalocean-config floating_ip='45.55.96.47' ''' if call != 'function': log.error( 'The delete_floating_ip function must be called with -f or --function.' ) return False if not kwargs: kwargs = {} if 'floating_ip' not in kwargs: log.error('A floating IP is required.') return False floating_ip = kwargs['floating_ip'] log.debug('Floating ip is %s', kwargs['floating_ip']) result = query(method='floating_ips', command=floating_ip, http_method='delete') return result def assign_floating_ip(kwargs=None, call=None): ''' Assign a floating IP .. versionadded:: 2016.3.0 CLI Examples: .. code-block:: bash salt-cloud -f assign_floating_ip my-digitalocean-config droplet_id=1234567 floating_ip='45.55.96.47' ''' if call != 'function': log.error( 'The assign_floating_ip function must be called with -f or --function.' ) return False if not kwargs: kwargs = {} if 'floating_ip' and 'droplet_id' not in kwargs: log.error('A floating IP and droplet_id is required.') return False result = query(method='floating_ips', command=kwargs['floating_ip'] + '/actions', args={'droplet_id': kwargs['droplet_id'], 'type': 'assign'}, http_method='post') return result def unassign_floating_ip(kwargs=None, call=None): ''' Unassign a floating IP .. versionadded:: 2016.3.0 CLI Examples: .. code-block:: bash salt-cloud -f unassign_floating_ip my-digitalocean-config floating_ip='45.55.96.47' ''' if call != 'function': log.error( 'The inassign_floating_ip function must be called with -f or --function.' ) return False if not kwargs: kwargs = {} if 'floating_ip' not in kwargs: log.error('A floating IP is required.') return False result = query(method='floating_ips', command=kwargs['floating_ip'] + '/actions', args={'type': 'unassign'}, http_method='post') return result def _list_nodes(full=False, for_output=False): ''' Helper function to format and parse node data. ''' fetch = True page = 1 ret = {} while fetch: items = query(method='droplets', command='?page=' + six.text_type(page) + '&per_page=200') for node in items['droplets']: name = node['name'] ret[name] = {} if full: ret[name] = _get_full_output(node, for_output=for_output) else: public_ips, private_ips = _get_ips(node['networks']) ret[name] = { 'id': node['id'], 'image': node['image']['name'], 'name': name, 'private_ips': private_ips, 'public_ips': public_ips, 'size': node['size_slug'], 'state': six.text_type(node['status']), } page += 1 try: fetch = 'next' in items['links']['pages'] except KeyError: fetch = False return ret def reboot(name, call=None): ''' Reboot a droplet in DigitalOcean. .. versionadded:: 2015.8.8 name The name of the droplet to restart. CLI Example: .. code-block:: bash salt-cloud -a reboot droplet_name ''' if call != 'action': raise SaltCloudSystemExit( 'The restart action must be called with -a or --action.' ) data = show_instance(name, call='action') if data.get('status') == 'off': return {'success': True, 'action': 'stop', 'status': 'off', 'msg': 'Machine is already off.'} ret = query(droplet_id=data['id'], command='actions', args={'type': 'reboot'}, http_method='post') return {'success': True, 'action': ret['action']['type'], 'state': ret['action']['status']} def start(name, call=None): ''' Start a droplet in DigitalOcean. .. versionadded:: 2015.8.8 name The name of the droplet to start. CLI Example: .. code-block:: bash salt-cloud -a start droplet_name ''' if call != 'action': raise SaltCloudSystemExit( 'The start action must be called with -a or --action.' ) data = show_instance(name, call='action') if data.get('status') == 'active': return {'success': True, 'action': 'start', 'status': 'active', 'msg': 'Machine is already running.'} ret = query(droplet_id=data['id'], command='actions', args={'type': 'power_on'}, http_method='post') return {'success': True, 'action': ret['action']['type'], 'state': ret['action']['status']} def stop(name, call=None): ''' Stop a droplet in DigitalOcean. .. versionadded:: 2015.8.8 name The name of the droplet to stop. CLI Example: .. code-block:: bash salt-cloud -a stop droplet_name ''' if call != 'action': raise SaltCloudSystemExit( 'The stop action must be called with -a or --action.' ) data = show_instance(name, call='action') if data.get('status') == 'off': return {'success': True, 'action': 'stop', 'status': 'off', 'msg': 'Machine is already off.'} ret = query(droplet_id=data['id'], command='actions', args={'type': 'shutdown'}, http_method='post') return {'success': True, 'action': ret['action']['type'], 'state': ret['action']['status']} def _get_full_output(node, for_output=False): ''' Helper function for _list_nodes to loop through all node information. Returns a dictionary containing the full information of a node. ''' ret = {} for item in six.iterkeys(node): value = node[item] if value is not None and for_output: value = six.text_type(value) ret[item] = value return ret def _get_ips(networks): ''' Helper function for list_nodes. Returns public and private ip lists based on a given network dictionary. ''' v4s = networks.get('v4') v6s = networks.get('v6') public_ips = [] private_ips = [] if v4s: for item in v4s: ip_type = item.get('type') ip_address = item.get('ip_address') if ip_type == 'public': public_ips.append(ip_address) if ip_type == 'private': private_ips.append(ip_address) if v6s: for item in v6s: ip_type = item.get('type') ip_address = item.get('ip_address') if ip_type == 'public': public_ips.append(ip_address) if ip_type == 'private': private_ips.append(ip_address) return public_ips, private_ips
saltstack/salt
salt/cloud/clouds/digitalocean.py
get_size
python
def get_size(vm_): ''' Return the VM's size. Used by create_node(). ''' sizes = avail_sizes() vm_size = six.text_type(config.get_cloud_config_value( 'size', vm_, __opts__, search_global=False )) for size in sizes: if vm_size.lower() == sizes[size]['slug']: return sizes[size]['slug'] raise SaltCloudNotFound( 'The specified size, \'{0}\', could not be found.'.format(vm_size) )
Return the VM's size. Used by create_node().
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/digitalocean.py#L229-L242
[ "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 avail_sizes(call=None):\n '''\n Return a list of the image sizes that are on the provider\n '''\n if call == 'action':\n raise SaltCloudSystemExit(\n 'The avail_sizes function must be called with '\n '-f or --function, or with the --list-sizes option'\n )\n\n items = query(method='sizes', command='?per_page=100')\n ret = {}\n for size in items['sizes']:\n ret[size['slug']] = {}\n for item in six.iterkeys(size):\n ret[size['slug']][item] = six.text_type(size[item])\n\n return ret\n" ]
# -*- coding: utf-8 -*- ''' DigitalOcean Cloud Module ========================= The DigitalOcean cloud module is used to control access to the DigitalOcean VPS system. Use of this module requires a requires a ``personal_access_token``, an ``ssh_key_file``, and at least one SSH key name in ``ssh_key_names``. More ``ssh_key_names`` can be added by separating each key with a comma. The ``personal_access_token`` can be found in the DigitalOcean web interface in the "Apps & API" section. The SSH key name can be found under the "SSH Keys" section. .. code-block:: yaml # Note: This example is for /etc/salt/cloud.providers or any file in the # /etc/salt/cloud.providers.d/ directory. my-digital-ocean-config: personal_access_token: xxx ssh_key_file: /path/to/ssh/key/file ssh_key_names: my-key-name,my-key-name-2 driver: digitalocean :depends: requests ''' # Import Python Libs from __future__ import absolute_import, print_function, unicode_literals import decimal import logging import os import pprint import time # Import Salt Libs import salt.utils.cloud import salt.utils.files import salt.utils.json import salt.utils.stringutils import salt.config as config from salt.exceptions import ( SaltCloudConfigError, SaltInvocationError, SaltCloudNotFound, SaltCloudSystemExit, SaltCloudExecutionFailure, SaltCloudExecutionTimeout ) from salt.ext import six from salt.ext.six.moves import zip # Import Third Party Libs try: import requests HAS_REQUESTS = True except ImportError: HAS_REQUESTS = False # Get logging started log = logging.getLogger(__name__) __virtualname__ = 'digitalocean' __virtual_aliases__ = ('digital_ocean', 'do') # Only load in this module if the DIGITALOCEAN configurations are in place def __virtual__(): ''' Check for DigitalOcean 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=__opts__, provider=__active_provider_name__ or __virtualname__, aliases=__virtual_aliases__, required_keys=('personal_access_token',) ) def get_dependencies(): ''' Warn if dependencies aren't met. ''' return config.check_driver_dependencies( __virtualname__, {'requests': HAS_REQUESTS} ) def avail_locations(call=None): ''' Return a dict of all available VM locations on the cloud provider with relevant data ''' if call == 'action': raise SaltCloudSystemExit( 'The avail_locations function must be called with ' '-f or --function, or with the --list-locations option' ) items = query(method='regions') ret = {} for region in items['regions']: ret[region['name']] = {} for item in six.iterkeys(region): ret[region['name']][item] = six.text_type(region[item]) return ret def avail_images(call=None): ''' Return a list of the images that are on the provider ''' if call == 'action': raise SaltCloudSystemExit( 'The avail_images function must be called with ' '-f or --function, or with the --list-images option' ) fetch = True page = 1 ret = {} while fetch: items = query(method='images', command='?page=' + six.text_type(page) + '&per_page=200') for image in items['images']: ret[image['name']] = {} for item in six.iterkeys(image): ret[image['name']][item] = image[item] page += 1 try: fetch = 'next' in items['links']['pages'] except KeyError: fetch = False return ret def avail_sizes(call=None): ''' Return a list of the image sizes that are on the provider ''' if call == 'action': raise SaltCloudSystemExit( 'The avail_sizes function must be called with ' '-f or --function, or with the --list-sizes option' ) items = query(method='sizes', command='?per_page=100') ret = {} for size in items['sizes']: ret[size['slug']] = {} for item in six.iterkeys(size): ret[size['slug']][item] = six.text_type(size[item]) 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.' ) return _list_nodes() def list_nodes_full(call=None, for_output=True): ''' 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.' ) return _list_nodes(full=True, for_output=for_output) 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('function'), __opts__['query.selection'], call, ) def get_image(vm_): ''' Return the image object to use ''' images = avail_images() vm_image = config.get_cloud_config_value( 'image', vm_, __opts__, search_global=False ) if not isinstance(vm_image, six.string_types): vm_image = six.text_type(vm_image) for image in images: if vm_image in (images[image]['name'], images[image]['slug'], images[image]['id']): if images[image]['slug'] is not None: return images[image]['slug'] return int(images[image]['id']) raise SaltCloudNotFound( 'The specified image, \'{0}\', could not be found.'.format(vm_image) ) def get_location(vm_): ''' Return the VM's location ''' locations = avail_locations() vm_location = six.text_type(config.get_cloud_config_value( 'location', vm_, __opts__, search_global=False )) for location in locations: if vm_location in (locations[location]['name'], locations[location]['slug']): return locations[location]['slug'] raise SaltCloudNotFound( 'The specified location, \'{0}\', could not be found.'.format( vm_location ) ) def create_node(args): ''' Create a node ''' node = query(method='droplets', args=args, http_method='post') return node 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 'digitalocean', vm_['profile'], vm_=vm_) is False: return False except AttributeError: pass __utils__['cloud.fire_event']( 'event', 'starting create', 'salt/cloud/{0}/creating'.format(vm_['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', vm_['name']) kwargs = { 'name': vm_['name'], 'size': get_size(vm_), 'image': get_image(vm_), 'region': get_location(vm_), 'ssh_keys': [], 'tags': [] } # backwards compat ssh_key_name = config.get_cloud_config_value( 'ssh_key_name', vm_, __opts__, search_global=False ) if ssh_key_name: kwargs['ssh_keys'].append(get_keyid(ssh_key_name)) ssh_key_names = config.get_cloud_config_value( 'ssh_key_names', vm_, __opts__, search_global=False, default=False ) if ssh_key_names: for key in ssh_key_names.split(','): kwargs['ssh_keys'].append(get_keyid(key)) key_filename = config.get_cloud_config_value( 'ssh_key_file', vm_, __opts__, search_global=False, default=None ) if key_filename is not None and not os.path.isfile(key_filename): raise SaltCloudConfigError( 'The defined key_filename \'{0}\' does not exist'.format( key_filename ) ) if not __opts__.get('ssh_agent', False) and key_filename is None: raise SaltCloudConfigError( 'The DigitalOcean driver requires an ssh_key_file and an ssh_key_name ' 'because it does not supply a root password upon building the server.' ) ssh_interface = config.get_cloud_config_value( 'ssh_interface', vm_, __opts__, search_global=False, default='public' ) if ssh_interface in ['private', 'public']: log.info("ssh_interface: Setting interface for ssh to %s", ssh_interface) kwargs['ssh_interface'] = ssh_interface else: raise SaltCloudConfigError( "The DigitalOcean driver requires ssh_interface to be defined as 'public' or 'private'." ) private_networking = config.get_cloud_config_value( 'private_networking', vm_, __opts__, search_global=False, default=None, ) if private_networking is not None: if not isinstance(private_networking, bool): raise SaltCloudConfigError("'private_networking' should be a boolean value.") kwargs['private_networking'] = private_networking if not private_networking and ssh_interface == 'private': raise SaltCloudConfigError( "The DigitalOcean driver requires ssh_interface if defined as 'private' " "then private_networking should be set as 'True'." ) backups_enabled = config.get_cloud_config_value( 'backups_enabled', vm_, __opts__, search_global=False, default=None, ) if backups_enabled is not None: if not isinstance(backups_enabled, bool): raise SaltCloudConfigError("'backups_enabled' should be a boolean value.") kwargs['backups'] = backups_enabled ipv6 = config.get_cloud_config_value( 'ipv6', vm_, __opts__, search_global=False, default=None, ) if ipv6 is not None: if not isinstance(ipv6, bool): raise SaltCloudConfigError("'ipv6' should be a boolean value.") kwargs['ipv6'] = ipv6 monitoring = config.get_cloud_config_value( 'monitoring', vm_, __opts__, search_global=False, default=None, ) if monitoring is not None: if not isinstance(monitoring, bool): raise SaltCloudConfigError("'monitoring' should be a boolean value.") kwargs['monitoring'] = monitoring kwargs['tags'] = config.get_cloud_config_value( 'tags', vm_, __opts__, search_global=False, default=False ) userdata_file = config.get_cloud_config_value( 'userdata_file', vm_, __opts__, search_global=False, default=None ) if userdata_file is not None: try: with salt.utils.files.fopen(userdata_file, 'r') as fp_: kwargs['user_data'] = salt.utils.cloud.userdata_template( __opts__, vm_, salt.utils.stringutils.to_unicode(fp_.read()) ) except Exception as exc: log.exception( 'Failed to read userdata from %s: %s', userdata_file, exc) create_dns_record = config.get_cloud_config_value( 'create_dns_record', vm_, __opts__, search_global=False, default=None, ) if create_dns_record: log.info('create_dns_record: will attempt to write DNS records') default_dns_domain = None dns_domain_name = vm_['name'].split('.') if len(dns_domain_name) > 2: log.debug('create_dns_record: inferring default dns_hostname, dns_domain from minion name as FQDN') default_dns_hostname = '.'.join(dns_domain_name[:-2]) default_dns_domain = '.'.join(dns_domain_name[-2:]) else: log.debug("create_dns_record: can't infer dns_domain from %s", vm_['name']) default_dns_hostname = dns_domain_name[0] dns_hostname = config.get_cloud_config_value( 'dns_hostname', vm_, __opts__, search_global=False, default=default_dns_hostname, ) dns_domain = config.get_cloud_config_value( 'dns_domain', vm_, __opts__, search_global=False, default=default_dns_domain, ) if dns_hostname and dns_domain: log.info('create_dns_record: using dns_hostname="%s", dns_domain="%s"', dns_hostname, dns_domain) __add_dns_addr__ = lambda t, d: post_dns_record(dns_domain=dns_domain, name=dns_hostname, record_type=t, record_data=d) log.debug('create_dns_record: %s', __add_dns_addr__) else: log.error('create_dns_record: could not determine dns_hostname and/or dns_domain') raise SaltCloudConfigError( '\'create_dns_record\' must be a dict specifying "domain" ' 'and "hostname" or the minion name must be an FQDN.' ) __utils__['cloud.fire_event']( 'event', 'requesting instance', 'salt/cloud/{0}/requesting'.format(vm_['name']), args=__utils__['cloud.filter_event']('requesting', kwargs, list(kwargs)), sock_dir=__opts__['sock_dir'], transport=__opts__['transport'] ) try: ret = create_node(kwargs) except Exception as exc: log.error( 'Error creating %s on DIGITALOCEAN\n\n' 'The following exception was thrown when trying to ' 'run the initial deployment: %s', vm_['name'], exc, # Show the traceback if the debug logging level is enabled exc_info_on_loglevel=logging.DEBUG ) return False def __query_node_data(vm_name): data = show_instance(vm_name, 'action') if not data: # Trigger an error in the wait_for_ip function return False if data['networks'].get('v4'): for network in data['networks']['v4']: if network['type'] == 'public': return data return False try: data = salt.utils.cloud.wait_for_ip( __query_node_data, update_args=(vm_['name'],), timeout=config.get_cloud_config_value( 'wait_for_ip_timeout', vm_, __opts__, default=10 * 60), interval=config.get_cloud_config_value( 'wait_for_ip_interval', vm_, __opts__, default=10), ) except (SaltCloudExecutionTimeout, SaltCloudExecutionFailure) as exc: try: # It might be already up, let's destroy it! destroy(vm_['name']) except SaltCloudSystemExit: pass finally: raise SaltCloudSystemExit(six.text_type(exc)) if not vm_.get('ssh_host'): vm_['ssh_host'] = None # add DNS records, set ssh_host, default to first found IP, preferring IPv4 for ssh bootstrap script target addr_families, dns_arec_types = (('v4', 'v6'), ('A', 'AAAA')) arec_map = dict(list(zip(addr_families, dns_arec_types))) for facing, addr_family, ip_address in [(net['type'], family, net['ip_address']) for family in addr_families for net in data['networks'][family]]: log.info('found %s IP%s interface for "%s"', facing, addr_family, ip_address) dns_rec_type = arec_map[addr_family] if facing == 'public': if create_dns_record: __add_dns_addr__(dns_rec_type, ip_address) if facing == ssh_interface: if not vm_['ssh_host']: vm_['ssh_host'] = ip_address if vm_['ssh_host'] is None: raise SaltCloudSystemExit( 'No suitable IP addresses found for ssh minion bootstrapping: {0}'.format(repr(data['networks'])) ) log.debug( 'Found public IP address to use for ssh minion bootstrapping: %s', vm_['ssh_host'] ) vm_['key_filename'] = key_filename ret = __utils__['cloud.bootstrap'](vm_, __opts__) ret.update(data) log.info('Created Cloud VM \'%s\'', vm_['name']) log.debug( '\'%s\' VM creation details:\n%s', vm_['name'], pprint.pformat(data) ) __utils__['cloud.fire_event']( 'event', 'created instance', 'salt/cloud/{0}/created'.format(vm_['name']), args=__utils__['cloud.filter_event']('created', vm_, ['name', 'profile', 'provider', 'driver']), sock_dir=__opts__['sock_dir'], transport=__opts__['transport'] ) return ret def query(method='droplets', droplet_id=None, command=None, args=None, http_method='get'): ''' Make a web call to DigitalOcean ''' base_path = six.text_type(config.get_cloud_config_value( 'api_root', get_configured_provider(), __opts__, search_global=False, default='https://api.digitalocean.com/v2' )) path = '{0}/{1}/'.format(base_path, method) if droplet_id: path += '{0}/'.format(droplet_id) if command: path += command if not isinstance(args, dict): args = {} personal_access_token = config.get_cloud_config_value( 'personal_access_token', get_configured_provider(), __opts__, search_global=False ) data = salt.utils.json.dumps(args) requester = getattr(requests, http_method) request = requester(path, data=data, headers={'Authorization': 'Bearer ' + personal_access_token, 'Content-Type': 'application/json'}) if request.status_code > 299: raise SaltCloudSystemExit( 'An error occurred while querying DigitalOcean. HTTP Code: {0} ' 'Error: \'{1}\''.format( request.status_code, # request.read() request.text ) ) log.debug(request.url) # success without data if request.status_code == 204: return True content = request.text result = salt.utils.json.loads(content) if result.get('status', '').lower() == 'error': raise SaltCloudSystemExit( pprint.pformat(result.get('error_message', {})) ) return result 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 show_instance(name, call=None): ''' Show the details from DigitalOcean concerning a droplet ''' if call != 'action': raise SaltCloudSystemExit( 'The show_instance action must be called with -a or --action.' ) node = _get_node(name) __utils__['cloud.cache_node'](node, __active_provider_name__, __opts__) return node def _get_node(name): attempts = 10 while attempts >= 0: try: return list_nodes_full(for_output=False)[name] except KeyError: attempts -= 1 log.debug( 'Failed to get the data for node \'%s\'. Remaining ' 'attempts: %s', name, attempts ) # Just a little delay between attempts... time.sleep(0.5) return {} def list_keypairs(call=None): ''' Return a dict of all available VM locations on the cloud provider with relevant data ''' if call != 'function': log.error( 'The list_keypairs function must be called with -f or --function.' ) return False fetch = True page = 1 ret = {} while fetch: items = query(method='account/keys', command='?page=' + six.text_type(page) + '&per_page=100') for key_pair in items['ssh_keys']: name = key_pair['name'] if name in ret: raise SaltCloudSystemExit( 'A duplicate key pair name, \'{0}\', was found in DigitalOcean\'s ' 'key pair list. Please change the key name stored by DigitalOcean. ' 'Be sure to adjust the value of \'ssh_key_file\' in your cloud ' 'profile or provider configuration, if necessary.'.format( name ) ) ret[name] = {} for item in six.iterkeys(key_pair): ret[name][item] = six.text_type(key_pair[item]) page += 1 try: fetch = 'next' in items['links']['pages'] except KeyError: fetch = False return ret def show_keypair(kwargs=None, call=None): ''' Show the details of an SSH keypair ''' if call != 'function': log.error( 'The show_keypair function must be called with -f or --function.' ) return False if not kwargs: kwargs = {} if 'keyname' not in kwargs: log.error('A keyname is required.') return False keypairs = list_keypairs(call='function') keyid = keypairs[kwargs['keyname']]['id'] log.debug('Key ID is %s', keyid) details = query(method='account/keys', command=keyid) return details def import_keypair(kwargs=None, call=None): ''' Upload public key to cloud provider. Similar to EC2 import_keypair. .. versionadded:: 2016.11.0 kwargs file(mandatory): public key file-name keyname(mandatory): public key name in the provider ''' with salt.utils.files.fopen(kwargs['file'], 'r') as public_key_filename: public_key_content = salt.utils.stringutils.to_unicode(public_key_filename.read()) digitalocean_kwargs = { 'name': kwargs['keyname'], 'public_key': public_key_content } created_result = create_key(digitalocean_kwargs, call=call) return created_result def create_key(kwargs=None, call=None): ''' Upload a public key ''' if call != 'function': log.error( 'The create_key function must be called with -f or --function.' ) return False try: result = query( method='account', command='keys', args={'name': kwargs['name'], 'public_key': kwargs['public_key']}, http_method='post' ) except KeyError: log.info('`name` and `public_key` arguments must be specified') return False return result def remove_key(kwargs=None, call=None): ''' Delete public key ''' if call != 'function': log.error( 'The create_key function must be called with -f or --function.' ) return False try: result = query( method='account', command='keys/' + kwargs['id'], http_method='delete' ) except KeyError: log.info('`id` argument must be specified') return False return result def get_keyid(keyname): ''' Return the ID of the keyname ''' if not keyname: return None keypairs = list_keypairs(call='function') keyid = keypairs[keyname]['id'] if keyid: return keyid raise SaltCloudNotFound('The specified ssh key could not be found.') def destroy(name, call=None): ''' Destroy a node. Will check termination protection and warn if enabled. 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'] ) data = show_instance(name, call='action') node = query(method='droplets', droplet_id=data['id'], http_method='delete') ## This is all terribly optomistic: # vm_ = get_vm_config(name=name) # delete_dns_record = config.get_cloud_config_value( # 'delete_dns_record', vm_, __opts__, search_global=False, default=None, # ) # TODO: when _vm config data can be made available, we should honor the configuration settings, # but until then, we should assume stale DNS records are bad, and default behavior should be to # delete them if we can. When this is resolved, also resolve the comments a couple of lines below. delete_dns_record = True if not isinstance(delete_dns_record, bool): raise SaltCloudConfigError( '\'delete_dns_record\' should be a boolean value.' ) # When the "to do" a few lines up is resolved, remove these lines and use the if/else logic below. log.debug('Deleting DNS records for %s.', name) destroy_dns_records(name) # Until the "to do" from line 754 is taken care of, we don't need this logic. # if delete_dns_record: # log.debug('Deleting DNS records for %s.', name) # destroy_dns_records(name) # else: # log.debug('delete_dns_record : %s', delete_dns_record) # for line in pprint.pformat(dir()).splitlines(): # log.debug('delete context: %s', line) __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 node def post_dns_record(**kwargs): ''' Creates a DNS record for the given name if the domain is managed with DO. ''' if 'kwargs' in kwargs: # flatten kwargs if called via salt-cloud -f f_kwargs = kwargs['kwargs'] del kwargs['kwargs'] kwargs.update(f_kwargs) mandatory_kwargs = ('dns_domain', 'name', 'record_type', 'record_data') for i in mandatory_kwargs: if kwargs[i]: pass else: error = '{0}="{1}" ## all mandatory args must be provided: {2}'.format(i, kwargs[i], mandatory_kwargs) raise SaltInvocationError(error) domain = query(method='domains', droplet_id=kwargs['dns_domain']) if domain: result = query( method='domains', droplet_id=kwargs['dns_domain'], command='records', args={'type': kwargs['record_type'], 'name': kwargs['name'], 'data': kwargs['record_data']}, http_method='post' ) return result return False def destroy_dns_records(fqdn): ''' Deletes DNS records for the given hostname if the domain is managed with DO. ''' domain = '.'.join(fqdn.split('.')[-2:]) hostname = '.'.join(fqdn.split('.')[:-2]) # TODO: remove this when the todo on 754 is available try: response = query(method='domains', droplet_id=domain, command='records') except SaltCloudSystemExit: log.debug('Failed to find domains.') return False log.debug("found DNS records: %s", pprint.pformat(response)) records = response['domain_records'] if records: record_ids = [r['id'] for r in records if r['name'].decode() == hostname] log.debug("deleting DNS record IDs: %s", record_ids) for id_ in record_ids: try: log.info('deleting DNS record %s', id_) ret = query( method='domains', droplet_id=domain, command='records/{0}'.format(id_), http_method='delete' ) except SaltCloudSystemExit: log.error('failed to delete DNS domain %s record ID %s.', domain, hostname) log.debug('DNS deletion REST call returned: %s', pprint.pformat(ret)) return False def show_pricing(kwargs=None, call=None): ''' Show pricing for a particular profile. This is only an estimate, based on unofficial pricing sources. .. versionadded:: 2015.8.0 CLI Examples: .. code-block:: bash salt-cloud -f show_pricing my-digitalocean-config profile=my-profile ''' profile = __opts__['profiles'].get(kwargs['profile'], {}) if not profile: return {'Error': 'The requested profile was not found'} # Make sure the profile belongs to DigitalOcean provider = profile.get('provider', '0:0') comps = provider.split(':') if len(comps) < 2 or comps[1] != 'digitalocean': return {'Error': 'The requested profile does not belong to DigitalOcean'} raw = {} ret = {} sizes = avail_sizes() ret['per_hour'] = decimal.Decimal(sizes[profile['size']]['price_hourly']) ret['per_day'] = ret['per_hour'] * 24 ret['per_week'] = ret['per_day'] * 7 ret['per_month'] = decimal.Decimal(sizes[profile['size']]['price_monthly']) ret['per_year'] = ret['per_week'] * 52 if kwargs.get('raw', False): ret['_raw'] = raw return {profile['profile']: ret} def list_floating_ips(call=None): ''' Return a list of the floating ips that are on the provider .. versionadded:: 2016.3.0 CLI Examples: .. code-block:: bash salt-cloud -f list_floating_ips my-digitalocean-config ''' if call == 'action': raise SaltCloudSystemExit( 'The list_floating_ips function must be called with ' '-f or --function, or with the --list-floating-ips option' ) fetch = True page = 1 ret = {} while fetch: items = query(method='floating_ips', command='?page=' + six.text_type(page) + '&per_page=200') for floating_ip in items['floating_ips']: ret[floating_ip['ip']] = {} for item in six.iterkeys(floating_ip): ret[floating_ip['ip']][item] = floating_ip[item] page += 1 try: fetch = 'next' in items['links']['pages'] except KeyError: fetch = False return ret def show_floating_ip(kwargs=None, call=None): ''' Show the details of a floating IP .. versionadded:: 2016.3.0 CLI Examples: .. code-block:: bash salt-cloud -f show_floating_ip my-digitalocean-config floating_ip='45.55.96.47' ''' if call != 'function': log.error( 'The show_floating_ip function must be called with -f or --function.' ) return False if not kwargs: kwargs = {} if 'floating_ip' not in kwargs: log.error('A floating IP is required.') return False floating_ip = kwargs['floating_ip'] log.debug('Floating ip is %s', floating_ip) details = query(method='floating_ips', command=floating_ip) return details def create_floating_ip(kwargs=None, call=None): ''' Create a new floating IP .. versionadded:: 2016.3.0 CLI Examples: .. code-block:: bash salt-cloud -f create_floating_ip my-digitalocean-config region='NYC2' salt-cloud -f create_floating_ip my-digitalocean-config droplet_id='1234567' ''' if call != 'function': log.error( 'The create_floating_ip function must be called with -f or --function.' ) return False if not kwargs: kwargs = {} if 'droplet_id' in kwargs: result = query(method='floating_ips', args={'droplet_id': kwargs['droplet_id']}, http_method='post') return result elif 'region' in kwargs: result = query(method='floating_ips', args={'region': kwargs['region']}, http_method='post') return result else: log.error('A droplet_id or region is required.') return False def delete_floating_ip(kwargs=None, call=None): ''' Delete a floating IP .. versionadded:: 2016.3.0 CLI Examples: .. code-block:: bash salt-cloud -f delete_floating_ip my-digitalocean-config floating_ip='45.55.96.47' ''' if call != 'function': log.error( 'The delete_floating_ip function must be called with -f or --function.' ) return False if not kwargs: kwargs = {} if 'floating_ip' not in kwargs: log.error('A floating IP is required.') return False floating_ip = kwargs['floating_ip'] log.debug('Floating ip is %s', kwargs['floating_ip']) result = query(method='floating_ips', command=floating_ip, http_method='delete') return result def assign_floating_ip(kwargs=None, call=None): ''' Assign a floating IP .. versionadded:: 2016.3.0 CLI Examples: .. code-block:: bash salt-cloud -f assign_floating_ip my-digitalocean-config droplet_id=1234567 floating_ip='45.55.96.47' ''' if call != 'function': log.error( 'The assign_floating_ip function must be called with -f or --function.' ) return False if not kwargs: kwargs = {} if 'floating_ip' and 'droplet_id' not in kwargs: log.error('A floating IP and droplet_id is required.') return False result = query(method='floating_ips', command=kwargs['floating_ip'] + '/actions', args={'droplet_id': kwargs['droplet_id'], 'type': 'assign'}, http_method='post') return result def unassign_floating_ip(kwargs=None, call=None): ''' Unassign a floating IP .. versionadded:: 2016.3.0 CLI Examples: .. code-block:: bash salt-cloud -f unassign_floating_ip my-digitalocean-config floating_ip='45.55.96.47' ''' if call != 'function': log.error( 'The inassign_floating_ip function must be called with -f or --function.' ) return False if not kwargs: kwargs = {} if 'floating_ip' not in kwargs: log.error('A floating IP is required.') return False result = query(method='floating_ips', command=kwargs['floating_ip'] + '/actions', args={'type': 'unassign'}, http_method='post') return result def _list_nodes(full=False, for_output=False): ''' Helper function to format and parse node data. ''' fetch = True page = 1 ret = {} while fetch: items = query(method='droplets', command='?page=' + six.text_type(page) + '&per_page=200') for node in items['droplets']: name = node['name'] ret[name] = {} if full: ret[name] = _get_full_output(node, for_output=for_output) else: public_ips, private_ips = _get_ips(node['networks']) ret[name] = { 'id': node['id'], 'image': node['image']['name'], 'name': name, 'private_ips': private_ips, 'public_ips': public_ips, 'size': node['size_slug'], 'state': six.text_type(node['status']), } page += 1 try: fetch = 'next' in items['links']['pages'] except KeyError: fetch = False return ret def reboot(name, call=None): ''' Reboot a droplet in DigitalOcean. .. versionadded:: 2015.8.8 name The name of the droplet to restart. CLI Example: .. code-block:: bash salt-cloud -a reboot droplet_name ''' if call != 'action': raise SaltCloudSystemExit( 'The restart action must be called with -a or --action.' ) data = show_instance(name, call='action') if data.get('status') == 'off': return {'success': True, 'action': 'stop', 'status': 'off', 'msg': 'Machine is already off.'} ret = query(droplet_id=data['id'], command='actions', args={'type': 'reboot'}, http_method='post') return {'success': True, 'action': ret['action']['type'], 'state': ret['action']['status']} def start(name, call=None): ''' Start a droplet in DigitalOcean. .. versionadded:: 2015.8.8 name The name of the droplet to start. CLI Example: .. code-block:: bash salt-cloud -a start droplet_name ''' if call != 'action': raise SaltCloudSystemExit( 'The start action must be called with -a or --action.' ) data = show_instance(name, call='action') if data.get('status') == 'active': return {'success': True, 'action': 'start', 'status': 'active', 'msg': 'Machine is already running.'} ret = query(droplet_id=data['id'], command='actions', args={'type': 'power_on'}, http_method='post') return {'success': True, 'action': ret['action']['type'], 'state': ret['action']['status']} def stop(name, call=None): ''' Stop a droplet in DigitalOcean. .. versionadded:: 2015.8.8 name The name of the droplet to stop. CLI Example: .. code-block:: bash salt-cloud -a stop droplet_name ''' if call != 'action': raise SaltCloudSystemExit( 'The stop action must be called with -a or --action.' ) data = show_instance(name, call='action') if data.get('status') == 'off': return {'success': True, 'action': 'stop', 'status': 'off', 'msg': 'Machine is already off.'} ret = query(droplet_id=data['id'], command='actions', args={'type': 'shutdown'}, http_method='post') return {'success': True, 'action': ret['action']['type'], 'state': ret['action']['status']} def _get_full_output(node, for_output=False): ''' Helper function for _list_nodes to loop through all node information. Returns a dictionary containing the full information of a node. ''' ret = {} for item in six.iterkeys(node): value = node[item] if value is not None and for_output: value = six.text_type(value) ret[item] = value return ret def _get_ips(networks): ''' Helper function for list_nodes. Returns public and private ip lists based on a given network dictionary. ''' v4s = networks.get('v4') v6s = networks.get('v6') public_ips = [] private_ips = [] if v4s: for item in v4s: ip_type = item.get('type') ip_address = item.get('ip_address') if ip_type == 'public': public_ips.append(ip_address) if ip_type == 'private': private_ips.append(ip_address) if v6s: for item in v6s: ip_type = item.get('type') ip_address = item.get('ip_address') if ip_type == 'public': public_ips.append(ip_address) if ip_type == 'private': private_ips.append(ip_address) return public_ips, private_ips
saltstack/salt
salt/cloud/clouds/digitalocean.py
get_location
python
def get_location(vm_): ''' Return the VM's location ''' locations = avail_locations() vm_location = six.text_type(config.get_cloud_config_value( 'location', vm_, __opts__, search_global=False )) for location in locations: if vm_location in (locations[location]['name'], locations[location]['slug']): return locations[location]['slug'] raise SaltCloudNotFound( 'The specified location, \'{0}\', could not be found.'.format( vm_location ) )
Return the VM's location
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/digitalocean.py#L245-L262
[ "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 avail_locations(call=None):\n '''\n Return a dict of all available VM locations on the cloud provider with\n relevant data\n '''\n if call == 'action':\n raise SaltCloudSystemExit(\n 'The avail_locations function must be called with '\n '-f or --function, or with the --list-locations option'\n )\n\n items = query(method='regions')\n ret = {}\n for region in items['regions']:\n ret[region['name']] = {}\n for item in six.iterkeys(region):\n ret[region['name']][item] = six.text_type(region[item])\n\n return ret\n" ]
# -*- coding: utf-8 -*- ''' DigitalOcean Cloud Module ========================= The DigitalOcean cloud module is used to control access to the DigitalOcean VPS system. Use of this module requires a requires a ``personal_access_token``, an ``ssh_key_file``, and at least one SSH key name in ``ssh_key_names``. More ``ssh_key_names`` can be added by separating each key with a comma. The ``personal_access_token`` can be found in the DigitalOcean web interface in the "Apps & API" section. The SSH key name can be found under the "SSH Keys" section. .. code-block:: yaml # Note: This example is for /etc/salt/cloud.providers or any file in the # /etc/salt/cloud.providers.d/ directory. my-digital-ocean-config: personal_access_token: xxx ssh_key_file: /path/to/ssh/key/file ssh_key_names: my-key-name,my-key-name-2 driver: digitalocean :depends: requests ''' # Import Python Libs from __future__ import absolute_import, print_function, unicode_literals import decimal import logging import os import pprint import time # Import Salt Libs import salt.utils.cloud import salt.utils.files import salt.utils.json import salt.utils.stringutils import salt.config as config from salt.exceptions import ( SaltCloudConfigError, SaltInvocationError, SaltCloudNotFound, SaltCloudSystemExit, SaltCloudExecutionFailure, SaltCloudExecutionTimeout ) from salt.ext import six from salt.ext.six.moves import zip # Import Third Party Libs try: import requests HAS_REQUESTS = True except ImportError: HAS_REQUESTS = False # Get logging started log = logging.getLogger(__name__) __virtualname__ = 'digitalocean' __virtual_aliases__ = ('digital_ocean', 'do') # Only load in this module if the DIGITALOCEAN configurations are in place def __virtual__(): ''' Check for DigitalOcean 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=__opts__, provider=__active_provider_name__ or __virtualname__, aliases=__virtual_aliases__, required_keys=('personal_access_token',) ) def get_dependencies(): ''' Warn if dependencies aren't met. ''' return config.check_driver_dependencies( __virtualname__, {'requests': HAS_REQUESTS} ) def avail_locations(call=None): ''' Return a dict of all available VM locations on the cloud provider with relevant data ''' if call == 'action': raise SaltCloudSystemExit( 'The avail_locations function must be called with ' '-f or --function, or with the --list-locations option' ) items = query(method='regions') ret = {} for region in items['regions']: ret[region['name']] = {} for item in six.iterkeys(region): ret[region['name']][item] = six.text_type(region[item]) return ret def avail_images(call=None): ''' Return a list of the images that are on the provider ''' if call == 'action': raise SaltCloudSystemExit( 'The avail_images function must be called with ' '-f or --function, or with the --list-images option' ) fetch = True page = 1 ret = {} while fetch: items = query(method='images', command='?page=' + six.text_type(page) + '&per_page=200') for image in items['images']: ret[image['name']] = {} for item in six.iterkeys(image): ret[image['name']][item] = image[item] page += 1 try: fetch = 'next' in items['links']['pages'] except KeyError: fetch = False return ret def avail_sizes(call=None): ''' Return a list of the image sizes that are on the provider ''' if call == 'action': raise SaltCloudSystemExit( 'The avail_sizes function must be called with ' '-f or --function, or with the --list-sizes option' ) items = query(method='sizes', command='?per_page=100') ret = {} for size in items['sizes']: ret[size['slug']] = {} for item in six.iterkeys(size): ret[size['slug']][item] = six.text_type(size[item]) 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.' ) return _list_nodes() def list_nodes_full(call=None, for_output=True): ''' 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.' ) return _list_nodes(full=True, for_output=for_output) 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('function'), __opts__['query.selection'], call, ) def get_image(vm_): ''' Return the image object to use ''' images = avail_images() vm_image = config.get_cloud_config_value( 'image', vm_, __opts__, search_global=False ) if not isinstance(vm_image, six.string_types): vm_image = six.text_type(vm_image) for image in images: if vm_image in (images[image]['name'], images[image]['slug'], images[image]['id']): if images[image]['slug'] is not None: return images[image]['slug'] return int(images[image]['id']) raise SaltCloudNotFound( 'The specified image, \'{0}\', could not be found.'.format(vm_image) ) def get_size(vm_): ''' Return the VM's size. Used by create_node(). ''' sizes = avail_sizes() vm_size = six.text_type(config.get_cloud_config_value( 'size', vm_, __opts__, search_global=False )) for size in sizes: if vm_size.lower() == sizes[size]['slug']: return sizes[size]['slug'] raise SaltCloudNotFound( 'The specified size, \'{0}\', could not be found.'.format(vm_size) ) def create_node(args): ''' Create a node ''' node = query(method='droplets', args=args, http_method='post') return node 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 'digitalocean', vm_['profile'], vm_=vm_) is False: return False except AttributeError: pass __utils__['cloud.fire_event']( 'event', 'starting create', 'salt/cloud/{0}/creating'.format(vm_['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', vm_['name']) kwargs = { 'name': vm_['name'], 'size': get_size(vm_), 'image': get_image(vm_), 'region': get_location(vm_), 'ssh_keys': [], 'tags': [] } # backwards compat ssh_key_name = config.get_cloud_config_value( 'ssh_key_name', vm_, __opts__, search_global=False ) if ssh_key_name: kwargs['ssh_keys'].append(get_keyid(ssh_key_name)) ssh_key_names = config.get_cloud_config_value( 'ssh_key_names', vm_, __opts__, search_global=False, default=False ) if ssh_key_names: for key in ssh_key_names.split(','): kwargs['ssh_keys'].append(get_keyid(key)) key_filename = config.get_cloud_config_value( 'ssh_key_file', vm_, __opts__, search_global=False, default=None ) if key_filename is not None and not os.path.isfile(key_filename): raise SaltCloudConfigError( 'The defined key_filename \'{0}\' does not exist'.format( key_filename ) ) if not __opts__.get('ssh_agent', False) and key_filename is None: raise SaltCloudConfigError( 'The DigitalOcean driver requires an ssh_key_file and an ssh_key_name ' 'because it does not supply a root password upon building the server.' ) ssh_interface = config.get_cloud_config_value( 'ssh_interface', vm_, __opts__, search_global=False, default='public' ) if ssh_interface in ['private', 'public']: log.info("ssh_interface: Setting interface for ssh to %s", ssh_interface) kwargs['ssh_interface'] = ssh_interface else: raise SaltCloudConfigError( "The DigitalOcean driver requires ssh_interface to be defined as 'public' or 'private'." ) private_networking = config.get_cloud_config_value( 'private_networking', vm_, __opts__, search_global=False, default=None, ) if private_networking is not None: if not isinstance(private_networking, bool): raise SaltCloudConfigError("'private_networking' should be a boolean value.") kwargs['private_networking'] = private_networking if not private_networking and ssh_interface == 'private': raise SaltCloudConfigError( "The DigitalOcean driver requires ssh_interface if defined as 'private' " "then private_networking should be set as 'True'." ) backups_enabled = config.get_cloud_config_value( 'backups_enabled', vm_, __opts__, search_global=False, default=None, ) if backups_enabled is not None: if not isinstance(backups_enabled, bool): raise SaltCloudConfigError("'backups_enabled' should be a boolean value.") kwargs['backups'] = backups_enabled ipv6 = config.get_cloud_config_value( 'ipv6', vm_, __opts__, search_global=False, default=None, ) if ipv6 is not None: if not isinstance(ipv6, bool): raise SaltCloudConfigError("'ipv6' should be a boolean value.") kwargs['ipv6'] = ipv6 monitoring = config.get_cloud_config_value( 'monitoring', vm_, __opts__, search_global=False, default=None, ) if monitoring is not None: if not isinstance(monitoring, bool): raise SaltCloudConfigError("'monitoring' should be a boolean value.") kwargs['monitoring'] = monitoring kwargs['tags'] = config.get_cloud_config_value( 'tags', vm_, __opts__, search_global=False, default=False ) userdata_file = config.get_cloud_config_value( 'userdata_file', vm_, __opts__, search_global=False, default=None ) if userdata_file is not None: try: with salt.utils.files.fopen(userdata_file, 'r') as fp_: kwargs['user_data'] = salt.utils.cloud.userdata_template( __opts__, vm_, salt.utils.stringutils.to_unicode(fp_.read()) ) except Exception as exc: log.exception( 'Failed to read userdata from %s: %s', userdata_file, exc) create_dns_record = config.get_cloud_config_value( 'create_dns_record', vm_, __opts__, search_global=False, default=None, ) if create_dns_record: log.info('create_dns_record: will attempt to write DNS records') default_dns_domain = None dns_domain_name = vm_['name'].split('.') if len(dns_domain_name) > 2: log.debug('create_dns_record: inferring default dns_hostname, dns_domain from minion name as FQDN') default_dns_hostname = '.'.join(dns_domain_name[:-2]) default_dns_domain = '.'.join(dns_domain_name[-2:]) else: log.debug("create_dns_record: can't infer dns_domain from %s", vm_['name']) default_dns_hostname = dns_domain_name[0] dns_hostname = config.get_cloud_config_value( 'dns_hostname', vm_, __opts__, search_global=False, default=default_dns_hostname, ) dns_domain = config.get_cloud_config_value( 'dns_domain', vm_, __opts__, search_global=False, default=default_dns_domain, ) if dns_hostname and dns_domain: log.info('create_dns_record: using dns_hostname="%s", dns_domain="%s"', dns_hostname, dns_domain) __add_dns_addr__ = lambda t, d: post_dns_record(dns_domain=dns_domain, name=dns_hostname, record_type=t, record_data=d) log.debug('create_dns_record: %s', __add_dns_addr__) else: log.error('create_dns_record: could not determine dns_hostname and/or dns_domain') raise SaltCloudConfigError( '\'create_dns_record\' must be a dict specifying "domain" ' 'and "hostname" or the minion name must be an FQDN.' ) __utils__['cloud.fire_event']( 'event', 'requesting instance', 'salt/cloud/{0}/requesting'.format(vm_['name']), args=__utils__['cloud.filter_event']('requesting', kwargs, list(kwargs)), sock_dir=__opts__['sock_dir'], transport=__opts__['transport'] ) try: ret = create_node(kwargs) except Exception as exc: log.error( 'Error creating %s on DIGITALOCEAN\n\n' 'The following exception was thrown when trying to ' 'run the initial deployment: %s', vm_['name'], exc, # Show the traceback if the debug logging level is enabled exc_info_on_loglevel=logging.DEBUG ) return False def __query_node_data(vm_name): data = show_instance(vm_name, 'action') if not data: # Trigger an error in the wait_for_ip function return False if data['networks'].get('v4'): for network in data['networks']['v4']: if network['type'] == 'public': return data return False try: data = salt.utils.cloud.wait_for_ip( __query_node_data, update_args=(vm_['name'],), timeout=config.get_cloud_config_value( 'wait_for_ip_timeout', vm_, __opts__, default=10 * 60), interval=config.get_cloud_config_value( 'wait_for_ip_interval', vm_, __opts__, default=10), ) except (SaltCloudExecutionTimeout, SaltCloudExecutionFailure) as exc: try: # It might be already up, let's destroy it! destroy(vm_['name']) except SaltCloudSystemExit: pass finally: raise SaltCloudSystemExit(six.text_type(exc)) if not vm_.get('ssh_host'): vm_['ssh_host'] = None # add DNS records, set ssh_host, default to first found IP, preferring IPv4 for ssh bootstrap script target addr_families, dns_arec_types = (('v4', 'v6'), ('A', 'AAAA')) arec_map = dict(list(zip(addr_families, dns_arec_types))) for facing, addr_family, ip_address in [(net['type'], family, net['ip_address']) for family in addr_families for net in data['networks'][family]]: log.info('found %s IP%s interface for "%s"', facing, addr_family, ip_address) dns_rec_type = arec_map[addr_family] if facing == 'public': if create_dns_record: __add_dns_addr__(dns_rec_type, ip_address) if facing == ssh_interface: if not vm_['ssh_host']: vm_['ssh_host'] = ip_address if vm_['ssh_host'] is None: raise SaltCloudSystemExit( 'No suitable IP addresses found for ssh minion bootstrapping: {0}'.format(repr(data['networks'])) ) log.debug( 'Found public IP address to use for ssh minion bootstrapping: %s', vm_['ssh_host'] ) vm_['key_filename'] = key_filename ret = __utils__['cloud.bootstrap'](vm_, __opts__) ret.update(data) log.info('Created Cloud VM \'%s\'', vm_['name']) log.debug( '\'%s\' VM creation details:\n%s', vm_['name'], pprint.pformat(data) ) __utils__['cloud.fire_event']( 'event', 'created instance', 'salt/cloud/{0}/created'.format(vm_['name']), args=__utils__['cloud.filter_event']('created', vm_, ['name', 'profile', 'provider', 'driver']), sock_dir=__opts__['sock_dir'], transport=__opts__['transport'] ) return ret def query(method='droplets', droplet_id=None, command=None, args=None, http_method='get'): ''' Make a web call to DigitalOcean ''' base_path = six.text_type(config.get_cloud_config_value( 'api_root', get_configured_provider(), __opts__, search_global=False, default='https://api.digitalocean.com/v2' )) path = '{0}/{1}/'.format(base_path, method) if droplet_id: path += '{0}/'.format(droplet_id) if command: path += command if not isinstance(args, dict): args = {} personal_access_token = config.get_cloud_config_value( 'personal_access_token', get_configured_provider(), __opts__, search_global=False ) data = salt.utils.json.dumps(args) requester = getattr(requests, http_method) request = requester(path, data=data, headers={'Authorization': 'Bearer ' + personal_access_token, 'Content-Type': 'application/json'}) if request.status_code > 299: raise SaltCloudSystemExit( 'An error occurred while querying DigitalOcean. HTTP Code: {0} ' 'Error: \'{1}\''.format( request.status_code, # request.read() request.text ) ) log.debug(request.url) # success without data if request.status_code == 204: return True content = request.text result = salt.utils.json.loads(content) if result.get('status', '').lower() == 'error': raise SaltCloudSystemExit( pprint.pformat(result.get('error_message', {})) ) return result 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 show_instance(name, call=None): ''' Show the details from DigitalOcean concerning a droplet ''' if call != 'action': raise SaltCloudSystemExit( 'The show_instance action must be called with -a or --action.' ) node = _get_node(name) __utils__['cloud.cache_node'](node, __active_provider_name__, __opts__) return node def _get_node(name): attempts = 10 while attempts >= 0: try: return list_nodes_full(for_output=False)[name] except KeyError: attempts -= 1 log.debug( 'Failed to get the data for node \'%s\'. Remaining ' 'attempts: %s', name, attempts ) # Just a little delay between attempts... time.sleep(0.5) return {} def list_keypairs(call=None): ''' Return a dict of all available VM locations on the cloud provider with relevant data ''' if call != 'function': log.error( 'The list_keypairs function must be called with -f or --function.' ) return False fetch = True page = 1 ret = {} while fetch: items = query(method='account/keys', command='?page=' + six.text_type(page) + '&per_page=100') for key_pair in items['ssh_keys']: name = key_pair['name'] if name in ret: raise SaltCloudSystemExit( 'A duplicate key pair name, \'{0}\', was found in DigitalOcean\'s ' 'key pair list. Please change the key name stored by DigitalOcean. ' 'Be sure to adjust the value of \'ssh_key_file\' in your cloud ' 'profile or provider configuration, if necessary.'.format( name ) ) ret[name] = {} for item in six.iterkeys(key_pair): ret[name][item] = six.text_type(key_pair[item]) page += 1 try: fetch = 'next' in items['links']['pages'] except KeyError: fetch = False return ret def show_keypair(kwargs=None, call=None): ''' Show the details of an SSH keypair ''' if call != 'function': log.error( 'The show_keypair function must be called with -f or --function.' ) return False if not kwargs: kwargs = {} if 'keyname' not in kwargs: log.error('A keyname is required.') return False keypairs = list_keypairs(call='function') keyid = keypairs[kwargs['keyname']]['id'] log.debug('Key ID is %s', keyid) details = query(method='account/keys', command=keyid) return details def import_keypair(kwargs=None, call=None): ''' Upload public key to cloud provider. Similar to EC2 import_keypair. .. versionadded:: 2016.11.0 kwargs file(mandatory): public key file-name keyname(mandatory): public key name in the provider ''' with salt.utils.files.fopen(kwargs['file'], 'r') as public_key_filename: public_key_content = salt.utils.stringutils.to_unicode(public_key_filename.read()) digitalocean_kwargs = { 'name': kwargs['keyname'], 'public_key': public_key_content } created_result = create_key(digitalocean_kwargs, call=call) return created_result def create_key(kwargs=None, call=None): ''' Upload a public key ''' if call != 'function': log.error( 'The create_key function must be called with -f or --function.' ) return False try: result = query( method='account', command='keys', args={'name': kwargs['name'], 'public_key': kwargs['public_key']}, http_method='post' ) except KeyError: log.info('`name` and `public_key` arguments must be specified') return False return result def remove_key(kwargs=None, call=None): ''' Delete public key ''' if call != 'function': log.error( 'The create_key function must be called with -f or --function.' ) return False try: result = query( method='account', command='keys/' + kwargs['id'], http_method='delete' ) except KeyError: log.info('`id` argument must be specified') return False return result def get_keyid(keyname): ''' Return the ID of the keyname ''' if not keyname: return None keypairs = list_keypairs(call='function') keyid = keypairs[keyname]['id'] if keyid: return keyid raise SaltCloudNotFound('The specified ssh key could not be found.') def destroy(name, call=None): ''' Destroy a node. Will check termination protection and warn if enabled. 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'] ) data = show_instance(name, call='action') node = query(method='droplets', droplet_id=data['id'], http_method='delete') ## This is all terribly optomistic: # vm_ = get_vm_config(name=name) # delete_dns_record = config.get_cloud_config_value( # 'delete_dns_record', vm_, __opts__, search_global=False, default=None, # ) # TODO: when _vm config data can be made available, we should honor the configuration settings, # but until then, we should assume stale DNS records are bad, and default behavior should be to # delete them if we can. When this is resolved, also resolve the comments a couple of lines below. delete_dns_record = True if not isinstance(delete_dns_record, bool): raise SaltCloudConfigError( '\'delete_dns_record\' should be a boolean value.' ) # When the "to do" a few lines up is resolved, remove these lines and use the if/else logic below. log.debug('Deleting DNS records for %s.', name) destroy_dns_records(name) # Until the "to do" from line 754 is taken care of, we don't need this logic. # if delete_dns_record: # log.debug('Deleting DNS records for %s.', name) # destroy_dns_records(name) # else: # log.debug('delete_dns_record : %s', delete_dns_record) # for line in pprint.pformat(dir()).splitlines(): # log.debug('delete context: %s', line) __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 node def post_dns_record(**kwargs): ''' Creates a DNS record for the given name if the domain is managed with DO. ''' if 'kwargs' in kwargs: # flatten kwargs if called via salt-cloud -f f_kwargs = kwargs['kwargs'] del kwargs['kwargs'] kwargs.update(f_kwargs) mandatory_kwargs = ('dns_domain', 'name', 'record_type', 'record_data') for i in mandatory_kwargs: if kwargs[i]: pass else: error = '{0}="{1}" ## all mandatory args must be provided: {2}'.format(i, kwargs[i], mandatory_kwargs) raise SaltInvocationError(error) domain = query(method='domains', droplet_id=kwargs['dns_domain']) if domain: result = query( method='domains', droplet_id=kwargs['dns_domain'], command='records', args={'type': kwargs['record_type'], 'name': kwargs['name'], 'data': kwargs['record_data']}, http_method='post' ) return result return False def destroy_dns_records(fqdn): ''' Deletes DNS records for the given hostname if the domain is managed with DO. ''' domain = '.'.join(fqdn.split('.')[-2:]) hostname = '.'.join(fqdn.split('.')[:-2]) # TODO: remove this when the todo on 754 is available try: response = query(method='domains', droplet_id=domain, command='records') except SaltCloudSystemExit: log.debug('Failed to find domains.') return False log.debug("found DNS records: %s", pprint.pformat(response)) records = response['domain_records'] if records: record_ids = [r['id'] for r in records if r['name'].decode() == hostname] log.debug("deleting DNS record IDs: %s", record_ids) for id_ in record_ids: try: log.info('deleting DNS record %s', id_) ret = query( method='domains', droplet_id=domain, command='records/{0}'.format(id_), http_method='delete' ) except SaltCloudSystemExit: log.error('failed to delete DNS domain %s record ID %s.', domain, hostname) log.debug('DNS deletion REST call returned: %s', pprint.pformat(ret)) return False def show_pricing(kwargs=None, call=None): ''' Show pricing for a particular profile. This is only an estimate, based on unofficial pricing sources. .. versionadded:: 2015.8.0 CLI Examples: .. code-block:: bash salt-cloud -f show_pricing my-digitalocean-config profile=my-profile ''' profile = __opts__['profiles'].get(kwargs['profile'], {}) if not profile: return {'Error': 'The requested profile was not found'} # Make sure the profile belongs to DigitalOcean provider = profile.get('provider', '0:0') comps = provider.split(':') if len(comps) < 2 or comps[1] != 'digitalocean': return {'Error': 'The requested profile does not belong to DigitalOcean'} raw = {} ret = {} sizes = avail_sizes() ret['per_hour'] = decimal.Decimal(sizes[profile['size']]['price_hourly']) ret['per_day'] = ret['per_hour'] * 24 ret['per_week'] = ret['per_day'] * 7 ret['per_month'] = decimal.Decimal(sizes[profile['size']]['price_monthly']) ret['per_year'] = ret['per_week'] * 52 if kwargs.get('raw', False): ret['_raw'] = raw return {profile['profile']: ret} def list_floating_ips(call=None): ''' Return a list of the floating ips that are on the provider .. versionadded:: 2016.3.0 CLI Examples: .. code-block:: bash salt-cloud -f list_floating_ips my-digitalocean-config ''' if call == 'action': raise SaltCloudSystemExit( 'The list_floating_ips function must be called with ' '-f or --function, or with the --list-floating-ips option' ) fetch = True page = 1 ret = {} while fetch: items = query(method='floating_ips', command='?page=' + six.text_type(page) + '&per_page=200') for floating_ip in items['floating_ips']: ret[floating_ip['ip']] = {} for item in six.iterkeys(floating_ip): ret[floating_ip['ip']][item] = floating_ip[item] page += 1 try: fetch = 'next' in items['links']['pages'] except KeyError: fetch = False return ret def show_floating_ip(kwargs=None, call=None): ''' Show the details of a floating IP .. versionadded:: 2016.3.0 CLI Examples: .. code-block:: bash salt-cloud -f show_floating_ip my-digitalocean-config floating_ip='45.55.96.47' ''' if call != 'function': log.error( 'The show_floating_ip function must be called with -f or --function.' ) return False if not kwargs: kwargs = {} if 'floating_ip' not in kwargs: log.error('A floating IP is required.') return False floating_ip = kwargs['floating_ip'] log.debug('Floating ip is %s', floating_ip) details = query(method='floating_ips', command=floating_ip) return details def create_floating_ip(kwargs=None, call=None): ''' Create a new floating IP .. versionadded:: 2016.3.0 CLI Examples: .. code-block:: bash salt-cloud -f create_floating_ip my-digitalocean-config region='NYC2' salt-cloud -f create_floating_ip my-digitalocean-config droplet_id='1234567' ''' if call != 'function': log.error( 'The create_floating_ip function must be called with -f or --function.' ) return False if not kwargs: kwargs = {} if 'droplet_id' in kwargs: result = query(method='floating_ips', args={'droplet_id': kwargs['droplet_id']}, http_method='post') return result elif 'region' in kwargs: result = query(method='floating_ips', args={'region': kwargs['region']}, http_method='post') return result else: log.error('A droplet_id or region is required.') return False def delete_floating_ip(kwargs=None, call=None): ''' Delete a floating IP .. versionadded:: 2016.3.0 CLI Examples: .. code-block:: bash salt-cloud -f delete_floating_ip my-digitalocean-config floating_ip='45.55.96.47' ''' if call != 'function': log.error( 'The delete_floating_ip function must be called with -f or --function.' ) return False if not kwargs: kwargs = {} if 'floating_ip' not in kwargs: log.error('A floating IP is required.') return False floating_ip = kwargs['floating_ip'] log.debug('Floating ip is %s', kwargs['floating_ip']) result = query(method='floating_ips', command=floating_ip, http_method='delete') return result def assign_floating_ip(kwargs=None, call=None): ''' Assign a floating IP .. versionadded:: 2016.3.0 CLI Examples: .. code-block:: bash salt-cloud -f assign_floating_ip my-digitalocean-config droplet_id=1234567 floating_ip='45.55.96.47' ''' if call != 'function': log.error( 'The assign_floating_ip function must be called with -f or --function.' ) return False if not kwargs: kwargs = {} if 'floating_ip' and 'droplet_id' not in kwargs: log.error('A floating IP and droplet_id is required.') return False result = query(method='floating_ips', command=kwargs['floating_ip'] + '/actions', args={'droplet_id': kwargs['droplet_id'], 'type': 'assign'}, http_method='post') return result def unassign_floating_ip(kwargs=None, call=None): ''' Unassign a floating IP .. versionadded:: 2016.3.0 CLI Examples: .. code-block:: bash salt-cloud -f unassign_floating_ip my-digitalocean-config floating_ip='45.55.96.47' ''' if call != 'function': log.error( 'The inassign_floating_ip function must be called with -f or --function.' ) return False if not kwargs: kwargs = {} if 'floating_ip' not in kwargs: log.error('A floating IP is required.') return False result = query(method='floating_ips', command=kwargs['floating_ip'] + '/actions', args={'type': 'unassign'}, http_method='post') return result def _list_nodes(full=False, for_output=False): ''' Helper function to format and parse node data. ''' fetch = True page = 1 ret = {} while fetch: items = query(method='droplets', command='?page=' + six.text_type(page) + '&per_page=200') for node in items['droplets']: name = node['name'] ret[name] = {} if full: ret[name] = _get_full_output(node, for_output=for_output) else: public_ips, private_ips = _get_ips(node['networks']) ret[name] = { 'id': node['id'], 'image': node['image']['name'], 'name': name, 'private_ips': private_ips, 'public_ips': public_ips, 'size': node['size_slug'], 'state': six.text_type(node['status']), } page += 1 try: fetch = 'next' in items['links']['pages'] except KeyError: fetch = False return ret def reboot(name, call=None): ''' Reboot a droplet in DigitalOcean. .. versionadded:: 2015.8.8 name The name of the droplet to restart. CLI Example: .. code-block:: bash salt-cloud -a reboot droplet_name ''' if call != 'action': raise SaltCloudSystemExit( 'The restart action must be called with -a or --action.' ) data = show_instance(name, call='action') if data.get('status') == 'off': return {'success': True, 'action': 'stop', 'status': 'off', 'msg': 'Machine is already off.'} ret = query(droplet_id=data['id'], command='actions', args={'type': 'reboot'}, http_method='post') return {'success': True, 'action': ret['action']['type'], 'state': ret['action']['status']} def start(name, call=None): ''' Start a droplet in DigitalOcean. .. versionadded:: 2015.8.8 name The name of the droplet to start. CLI Example: .. code-block:: bash salt-cloud -a start droplet_name ''' if call != 'action': raise SaltCloudSystemExit( 'The start action must be called with -a or --action.' ) data = show_instance(name, call='action') if data.get('status') == 'active': return {'success': True, 'action': 'start', 'status': 'active', 'msg': 'Machine is already running.'} ret = query(droplet_id=data['id'], command='actions', args={'type': 'power_on'}, http_method='post') return {'success': True, 'action': ret['action']['type'], 'state': ret['action']['status']} def stop(name, call=None): ''' Stop a droplet in DigitalOcean. .. versionadded:: 2015.8.8 name The name of the droplet to stop. CLI Example: .. code-block:: bash salt-cloud -a stop droplet_name ''' if call != 'action': raise SaltCloudSystemExit( 'The stop action must be called with -a or --action.' ) data = show_instance(name, call='action') if data.get('status') == 'off': return {'success': True, 'action': 'stop', 'status': 'off', 'msg': 'Machine is already off.'} ret = query(droplet_id=data['id'], command='actions', args={'type': 'shutdown'}, http_method='post') return {'success': True, 'action': ret['action']['type'], 'state': ret['action']['status']} def _get_full_output(node, for_output=False): ''' Helper function for _list_nodes to loop through all node information. Returns a dictionary containing the full information of a node. ''' ret = {} for item in six.iterkeys(node): value = node[item] if value is not None and for_output: value = six.text_type(value) ret[item] = value return ret def _get_ips(networks): ''' Helper function for list_nodes. Returns public and private ip lists based on a given network dictionary. ''' v4s = networks.get('v4') v6s = networks.get('v6') public_ips = [] private_ips = [] if v4s: for item in v4s: ip_type = item.get('type') ip_address = item.get('ip_address') if ip_type == 'public': public_ips.append(ip_address) if ip_type == 'private': private_ips.append(ip_address) if v6s: for item in v6s: ip_type = item.get('type') ip_address = item.get('ip_address') if ip_type == 'public': public_ips.append(ip_address) if ip_type == 'private': private_ips.append(ip_address) return public_ips, private_ips
saltstack/salt
salt/cloud/clouds/digitalocean.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 'digitalocean', vm_['profile'], vm_=vm_) is False: return False except AttributeError: pass __utils__['cloud.fire_event']( 'event', 'starting create', 'salt/cloud/{0}/creating'.format(vm_['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', vm_['name']) kwargs = { 'name': vm_['name'], 'size': get_size(vm_), 'image': get_image(vm_), 'region': get_location(vm_), 'ssh_keys': [], 'tags': [] } # backwards compat ssh_key_name = config.get_cloud_config_value( 'ssh_key_name', vm_, __opts__, search_global=False ) if ssh_key_name: kwargs['ssh_keys'].append(get_keyid(ssh_key_name)) ssh_key_names = config.get_cloud_config_value( 'ssh_key_names', vm_, __opts__, search_global=False, default=False ) if ssh_key_names: for key in ssh_key_names.split(','): kwargs['ssh_keys'].append(get_keyid(key)) key_filename = config.get_cloud_config_value( 'ssh_key_file', vm_, __opts__, search_global=False, default=None ) if key_filename is not None and not os.path.isfile(key_filename): raise SaltCloudConfigError( 'The defined key_filename \'{0}\' does not exist'.format( key_filename ) ) if not __opts__.get('ssh_agent', False) and key_filename is None: raise SaltCloudConfigError( 'The DigitalOcean driver requires an ssh_key_file and an ssh_key_name ' 'because it does not supply a root password upon building the server.' ) ssh_interface = config.get_cloud_config_value( 'ssh_interface', vm_, __opts__, search_global=False, default='public' ) if ssh_interface in ['private', 'public']: log.info("ssh_interface: Setting interface for ssh to %s", ssh_interface) kwargs['ssh_interface'] = ssh_interface else: raise SaltCloudConfigError( "The DigitalOcean driver requires ssh_interface to be defined as 'public' or 'private'." ) private_networking = config.get_cloud_config_value( 'private_networking', vm_, __opts__, search_global=False, default=None, ) if private_networking is not None: if not isinstance(private_networking, bool): raise SaltCloudConfigError("'private_networking' should be a boolean value.") kwargs['private_networking'] = private_networking if not private_networking and ssh_interface == 'private': raise SaltCloudConfigError( "The DigitalOcean driver requires ssh_interface if defined as 'private' " "then private_networking should be set as 'True'." ) backups_enabled = config.get_cloud_config_value( 'backups_enabled', vm_, __opts__, search_global=False, default=None, ) if backups_enabled is not None: if not isinstance(backups_enabled, bool): raise SaltCloudConfigError("'backups_enabled' should be a boolean value.") kwargs['backups'] = backups_enabled ipv6 = config.get_cloud_config_value( 'ipv6', vm_, __opts__, search_global=False, default=None, ) if ipv6 is not None: if not isinstance(ipv6, bool): raise SaltCloudConfigError("'ipv6' should be a boolean value.") kwargs['ipv6'] = ipv6 monitoring = config.get_cloud_config_value( 'monitoring', vm_, __opts__, search_global=False, default=None, ) if monitoring is not None: if not isinstance(monitoring, bool): raise SaltCloudConfigError("'monitoring' should be a boolean value.") kwargs['monitoring'] = monitoring kwargs['tags'] = config.get_cloud_config_value( 'tags', vm_, __opts__, search_global=False, default=False ) userdata_file = config.get_cloud_config_value( 'userdata_file', vm_, __opts__, search_global=False, default=None ) if userdata_file is not None: try: with salt.utils.files.fopen(userdata_file, 'r') as fp_: kwargs['user_data'] = salt.utils.cloud.userdata_template( __opts__, vm_, salt.utils.stringutils.to_unicode(fp_.read()) ) except Exception as exc: log.exception( 'Failed to read userdata from %s: %s', userdata_file, exc) create_dns_record = config.get_cloud_config_value( 'create_dns_record', vm_, __opts__, search_global=False, default=None, ) if create_dns_record: log.info('create_dns_record: will attempt to write DNS records') default_dns_domain = None dns_domain_name = vm_['name'].split('.') if len(dns_domain_name) > 2: log.debug('create_dns_record: inferring default dns_hostname, dns_domain from minion name as FQDN') default_dns_hostname = '.'.join(dns_domain_name[:-2]) default_dns_domain = '.'.join(dns_domain_name[-2:]) else: log.debug("create_dns_record: can't infer dns_domain from %s", vm_['name']) default_dns_hostname = dns_domain_name[0] dns_hostname = config.get_cloud_config_value( 'dns_hostname', vm_, __opts__, search_global=False, default=default_dns_hostname, ) dns_domain = config.get_cloud_config_value( 'dns_domain', vm_, __opts__, search_global=False, default=default_dns_domain, ) if dns_hostname and dns_domain: log.info('create_dns_record: using dns_hostname="%s", dns_domain="%s"', dns_hostname, dns_domain) __add_dns_addr__ = lambda t, d: post_dns_record(dns_domain=dns_domain, name=dns_hostname, record_type=t, record_data=d) log.debug('create_dns_record: %s', __add_dns_addr__) else: log.error('create_dns_record: could not determine dns_hostname and/or dns_domain') raise SaltCloudConfigError( '\'create_dns_record\' must be a dict specifying "domain" ' 'and "hostname" or the minion name must be an FQDN.' ) __utils__['cloud.fire_event']( 'event', 'requesting instance', 'salt/cloud/{0}/requesting'.format(vm_['name']), args=__utils__['cloud.filter_event']('requesting', kwargs, list(kwargs)), sock_dir=__opts__['sock_dir'], transport=__opts__['transport'] ) try: ret = create_node(kwargs) except Exception as exc: log.error( 'Error creating %s on DIGITALOCEAN\n\n' 'The following exception was thrown when trying to ' 'run the initial deployment: %s', vm_['name'], exc, # Show the traceback if the debug logging level is enabled exc_info_on_loglevel=logging.DEBUG ) return False def __query_node_data(vm_name): data = show_instance(vm_name, 'action') if not data: # Trigger an error in the wait_for_ip function return False if data['networks'].get('v4'): for network in data['networks']['v4']: if network['type'] == 'public': return data return False try: data = salt.utils.cloud.wait_for_ip( __query_node_data, update_args=(vm_['name'],), timeout=config.get_cloud_config_value( 'wait_for_ip_timeout', vm_, __opts__, default=10 * 60), interval=config.get_cloud_config_value( 'wait_for_ip_interval', vm_, __opts__, default=10), ) except (SaltCloudExecutionTimeout, SaltCloudExecutionFailure) as exc: try: # It might be already up, let's destroy it! destroy(vm_['name']) except SaltCloudSystemExit: pass finally: raise SaltCloudSystemExit(six.text_type(exc)) if not vm_.get('ssh_host'): vm_['ssh_host'] = None # add DNS records, set ssh_host, default to first found IP, preferring IPv4 for ssh bootstrap script target addr_families, dns_arec_types = (('v4', 'v6'), ('A', 'AAAA')) arec_map = dict(list(zip(addr_families, dns_arec_types))) for facing, addr_family, ip_address in [(net['type'], family, net['ip_address']) for family in addr_families for net in data['networks'][family]]: log.info('found %s IP%s interface for "%s"', facing, addr_family, ip_address) dns_rec_type = arec_map[addr_family] if facing == 'public': if create_dns_record: __add_dns_addr__(dns_rec_type, ip_address) if facing == ssh_interface: if not vm_['ssh_host']: vm_['ssh_host'] = ip_address if vm_['ssh_host'] is None: raise SaltCloudSystemExit( 'No suitable IP addresses found for ssh minion bootstrapping: {0}'.format(repr(data['networks'])) ) log.debug( 'Found public IP address to use for ssh minion bootstrapping: %s', vm_['ssh_host'] ) vm_['key_filename'] = key_filename ret = __utils__['cloud.bootstrap'](vm_, __opts__) ret.update(data) log.info('Created Cloud VM \'%s\'', vm_['name']) log.debug( '\'%s\' VM creation details:\n%s', vm_['name'], pprint.pformat(data) ) __utils__['cloud.fire_event']( 'event', 'created instance', 'salt/cloud/{0}/created'.format(vm_['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/digitalocean.py#L273-L546
[ "def destroy(name, call=None):\n '''\n Destroy a node. Will check termination protection and warn if enabled.\n\n CLI Example:\n\n .. code-block:: bash\n\n salt-cloud --destroy mymachine\n '''\n if call == 'function':\n raise SaltCloudSystemExit(\n 'The destroy action must be called with -d, --destroy, '\n '-a or --action.'\n )\n\n __utils__['cloud.fire_event'](\n 'event',\n 'destroying instance',\n 'salt/cloud/{0}/destroying'.format(name),\n args={'name': name},\n sock_dir=__opts__['sock_dir'],\n transport=__opts__['transport']\n )\n\n data = show_instance(name, call='action')\n node = query(method='droplets', droplet_id=data['id'], http_method='delete')\n\n ## This is all terribly optomistic:\n # vm_ = get_vm_config(name=name)\n # delete_dns_record = config.get_cloud_config_value(\n # 'delete_dns_record', vm_, __opts__, search_global=False, default=None,\n # )\n # TODO: when _vm config data can be made available, we should honor the configuration settings,\n # but until then, we should assume stale DNS records are bad, and default behavior should be to\n # delete them if we can. When this is resolved, also resolve the comments a couple of lines below.\n delete_dns_record = True\n\n if not isinstance(delete_dns_record, bool):\n raise SaltCloudConfigError(\n '\\'delete_dns_record\\' should be a boolean value.'\n )\n # When the \"to do\" a few lines up is resolved, remove these lines and use the if/else logic below.\n log.debug('Deleting DNS records for %s.', name)\n destroy_dns_records(name)\n\n # Until the \"to do\" from line 754 is taken care of, we don't need this logic.\n # if delete_dns_record:\n # log.debug('Deleting DNS records for %s.', name)\n # destroy_dns_records(name)\n # else:\n # log.debug('delete_dns_record : %s', delete_dns_record)\n # for line in pprint.pformat(dir()).splitlines():\n # log.debug('delete context: %s', line)\n\n __utils__['cloud.fire_event'](\n 'event',\n 'destroyed instance',\n 'salt/cloud/{0}/destroyed'.format(name),\n args={'name': name},\n sock_dir=__opts__['sock_dir'],\n transport=__opts__['transport']\n )\n\n if __opts__.get('update_cachedir', False) is True:\n __utils__['cloud.delete_minion_cachedir'](name, __active_provider_name__.split(':')[0], __opts__)\n\n return node\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", "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_):\n '''\n Return the VM's location\n '''\n locations = avail_locations()\n vm_location = six.text_type(config.get_cloud_config_value(\n 'location', vm_, __opts__, search_global=False\n ))\n\n for location in locations:\n if vm_location in (locations[location]['name'],\n locations[location]['slug']):\n return locations[location]['slug']\n raise SaltCloudNotFound(\n 'The specified location, \\'{0}\\', could not be found.'.format(\n vm_location\n )\n )\n", "def get_image(vm_):\n '''\n Return the image object to use\n '''\n images = avail_images()\n vm_image = config.get_cloud_config_value(\n 'image', vm_, __opts__, search_global=False\n )\n if not isinstance(vm_image, six.string_types):\n vm_image = six.text_type(vm_image)\n\n for image in images:\n if vm_image in (images[image]['name'],\n images[image]['slug'],\n images[image]['id']):\n if images[image]['slug'] is not None:\n return images[image]['slug']\n return int(images[image]['id'])\n raise SaltCloudNotFound(\n 'The specified image, \\'{0}\\', could not be found.'.format(vm_image)\n )\n", "def get_size(vm_):\n '''\n Return the VM's size. Used by create_node().\n '''\n sizes = avail_sizes()\n vm_size = six.text_type(config.get_cloud_config_value(\n 'size', vm_, __opts__, search_global=False\n ))\n for size in sizes:\n if vm_size.lower() == sizes[size]['slug']:\n return sizes[size]['slug']\n raise SaltCloudNotFound(\n 'The specified size, \\'{0}\\', could not be found.'.format(vm_size)\n )\n", "def create_node(args):\n '''\n Create a node\n '''\n node = query(method='droplets', args=args, http_method='post')\n return node\n", "def wait_for_ip(update_callback,\n update_args=None,\n update_kwargs=None,\n timeout=5 * 60,\n interval=5,\n interval_multiplier=1,\n max_failures=10):\n '''\n Helper function that waits for an IP address for a specific maximum amount\n of time.\n\n :param update_callback: callback function which queries the cloud provider\n for the VM ip address. It must return None if the\n required data, IP included, is not available yet.\n :param update_args: Arguments to pass to update_callback\n :param update_kwargs: Keyword arguments to pass to update_callback\n :param timeout: The maximum amount of time(in seconds) to wait for the IP\n address.\n :param interval: The looping interval, i.e., the amount of time to sleep\n before the next iteration.\n :param interval_multiplier: Increase the interval by this multiplier after\n each request; helps with throttling\n :param max_failures: If update_callback returns ``False`` it's considered\n query failure. This value is the amount of failures\n accepted before giving up.\n :returns: The update_callback returned data\n :raises: SaltCloudExecutionTimeout\n\n '''\n if update_args is None:\n update_args = ()\n if update_kwargs is None:\n update_kwargs = {}\n\n duration = timeout\n while True:\n log.debug(\n 'Waiting for VM IP. Giving up in 00:%02d:%02d.',\n int(timeout // 60), int(timeout % 60)\n )\n data = update_callback(*update_args, **update_kwargs)\n if data is False:\n log.debug(\n '\\'update_callback\\' has returned \\'False\\', which is '\n 'considered a failure. Remaining Failures: %s.', max_failures\n )\n max_failures -= 1\n if max_failures <= 0:\n raise SaltCloudExecutionFailure(\n 'Too many failures occurred while waiting for '\n 'the IP address.'\n )\n elif data is not None:\n return data\n\n if timeout < 0:\n raise SaltCloudExecutionTimeout(\n 'Unable to get IP for 00:{0:02d}:{1:02d}.'.format(\n int(duration // 60),\n int(duration % 60)\n )\n )\n time.sleep(interval)\n timeout -= interval\n\n if interval_multiplier > 1:\n interval *= interval_multiplier\n if interval > timeout:\n interval = timeout + 1\n log.info('Interval multiplier in effect; interval is '\n 'now %ss.', interval)\n", "def userdata_template(opts, vm_, userdata):\n '''\n Use the configured templating engine to template the userdata file\n '''\n # No userdata, no need to template anything\n if userdata is None:\n return userdata\n\n userdata_template = salt.config.get_cloud_config_value(\n 'userdata_template', vm_, opts, search_global=False, default=None\n )\n if userdata_template is False:\n return userdata\n # Use the cloud profile's userdata_template, otherwise get it from the\n # master configuration file.\n renderer = opts.get('userdata_template') \\\n if userdata_template is None \\\n else userdata_template\n if renderer is None:\n return userdata\n else:\n render_opts = opts.copy()\n render_opts.update(vm_)\n rend = salt.loader.render(render_opts, {})\n blacklist = opts['renderer_blacklist']\n whitelist = opts['renderer_whitelist']\n templated = salt.template.compile_template(\n ':string:',\n rend,\n renderer,\n blacklist,\n whitelist,\n input_data=userdata,\n )\n if not isinstance(templated, six.string_types):\n # template renderers like \"jinja\" should return a StringIO\n try:\n templated = ''.join(templated.readlines())\n except AttributeError:\n log.warning(\n 'Templated userdata resulted in non-string result (%s), '\n 'converting to string', templated\n )\n templated = six.text_type(templated)\n\n return templated\n", "def get_keyid(keyname):\n '''\n Return the ID of the keyname\n '''\n if not keyname:\n return None\n keypairs = list_keypairs(call='function')\n keyid = keypairs[keyname]['id']\n if keyid:\n return keyid\n raise SaltCloudNotFound('The specified ssh key could not be found.')\n", "__add_dns_addr__ = lambda t, d: post_dns_record(dns_domain=dns_domain,\n name=dns_hostname,\n record_type=t,\n record_data=d)\n" ]
# -*- coding: utf-8 -*- ''' DigitalOcean Cloud Module ========================= The DigitalOcean cloud module is used to control access to the DigitalOcean VPS system. Use of this module requires a requires a ``personal_access_token``, an ``ssh_key_file``, and at least one SSH key name in ``ssh_key_names``. More ``ssh_key_names`` can be added by separating each key with a comma. The ``personal_access_token`` can be found in the DigitalOcean web interface in the "Apps & API" section. The SSH key name can be found under the "SSH Keys" section. .. code-block:: yaml # Note: This example is for /etc/salt/cloud.providers or any file in the # /etc/salt/cloud.providers.d/ directory. my-digital-ocean-config: personal_access_token: xxx ssh_key_file: /path/to/ssh/key/file ssh_key_names: my-key-name,my-key-name-2 driver: digitalocean :depends: requests ''' # Import Python Libs from __future__ import absolute_import, print_function, unicode_literals import decimal import logging import os import pprint import time # Import Salt Libs import salt.utils.cloud import salt.utils.files import salt.utils.json import salt.utils.stringutils import salt.config as config from salt.exceptions import ( SaltCloudConfigError, SaltInvocationError, SaltCloudNotFound, SaltCloudSystemExit, SaltCloudExecutionFailure, SaltCloudExecutionTimeout ) from salt.ext import six from salt.ext.six.moves import zip # Import Third Party Libs try: import requests HAS_REQUESTS = True except ImportError: HAS_REQUESTS = False # Get logging started log = logging.getLogger(__name__) __virtualname__ = 'digitalocean' __virtual_aliases__ = ('digital_ocean', 'do') # Only load in this module if the DIGITALOCEAN configurations are in place def __virtual__(): ''' Check for DigitalOcean 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=__opts__, provider=__active_provider_name__ or __virtualname__, aliases=__virtual_aliases__, required_keys=('personal_access_token',) ) def get_dependencies(): ''' Warn if dependencies aren't met. ''' return config.check_driver_dependencies( __virtualname__, {'requests': HAS_REQUESTS} ) def avail_locations(call=None): ''' Return a dict of all available VM locations on the cloud provider with relevant data ''' if call == 'action': raise SaltCloudSystemExit( 'The avail_locations function must be called with ' '-f or --function, or with the --list-locations option' ) items = query(method='regions') ret = {} for region in items['regions']: ret[region['name']] = {} for item in six.iterkeys(region): ret[region['name']][item] = six.text_type(region[item]) return ret def avail_images(call=None): ''' Return a list of the images that are on the provider ''' if call == 'action': raise SaltCloudSystemExit( 'The avail_images function must be called with ' '-f or --function, or with the --list-images option' ) fetch = True page = 1 ret = {} while fetch: items = query(method='images', command='?page=' + six.text_type(page) + '&per_page=200') for image in items['images']: ret[image['name']] = {} for item in six.iterkeys(image): ret[image['name']][item] = image[item] page += 1 try: fetch = 'next' in items['links']['pages'] except KeyError: fetch = False return ret def avail_sizes(call=None): ''' Return a list of the image sizes that are on the provider ''' if call == 'action': raise SaltCloudSystemExit( 'The avail_sizes function must be called with ' '-f or --function, or with the --list-sizes option' ) items = query(method='sizes', command='?per_page=100') ret = {} for size in items['sizes']: ret[size['slug']] = {} for item in six.iterkeys(size): ret[size['slug']][item] = six.text_type(size[item]) 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.' ) return _list_nodes() def list_nodes_full(call=None, for_output=True): ''' 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.' ) return _list_nodes(full=True, for_output=for_output) 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('function'), __opts__['query.selection'], call, ) def get_image(vm_): ''' Return the image object to use ''' images = avail_images() vm_image = config.get_cloud_config_value( 'image', vm_, __opts__, search_global=False ) if not isinstance(vm_image, six.string_types): vm_image = six.text_type(vm_image) for image in images: if vm_image in (images[image]['name'], images[image]['slug'], images[image]['id']): if images[image]['slug'] is not None: return images[image]['slug'] return int(images[image]['id']) raise SaltCloudNotFound( 'The specified image, \'{0}\', could not be found.'.format(vm_image) ) def get_size(vm_): ''' Return the VM's size. Used by create_node(). ''' sizes = avail_sizes() vm_size = six.text_type(config.get_cloud_config_value( 'size', vm_, __opts__, search_global=False )) for size in sizes: if vm_size.lower() == sizes[size]['slug']: return sizes[size]['slug'] raise SaltCloudNotFound( 'The specified size, \'{0}\', could not be found.'.format(vm_size) ) def get_location(vm_): ''' Return the VM's location ''' locations = avail_locations() vm_location = six.text_type(config.get_cloud_config_value( 'location', vm_, __opts__, search_global=False )) for location in locations: if vm_location in (locations[location]['name'], locations[location]['slug']): return locations[location]['slug'] raise SaltCloudNotFound( 'The specified location, \'{0}\', could not be found.'.format( vm_location ) ) def create_node(args): ''' Create a node ''' node = query(method='droplets', args=args, http_method='post') return node def query(method='droplets', droplet_id=None, command=None, args=None, http_method='get'): ''' Make a web call to DigitalOcean ''' base_path = six.text_type(config.get_cloud_config_value( 'api_root', get_configured_provider(), __opts__, search_global=False, default='https://api.digitalocean.com/v2' )) path = '{0}/{1}/'.format(base_path, method) if droplet_id: path += '{0}/'.format(droplet_id) if command: path += command if not isinstance(args, dict): args = {} personal_access_token = config.get_cloud_config_value( 'personal_access_token', get_configured_provider(), __opts__, search_global=False ) data = salt.utils.json.dumps(args) requester = getattr(requests, http_method) request = requester(path, data=data, headers={'Authorization': 'Bearer ' + personal_access_token, 'Content-Type': 'application/json'}) if request.status_code > 299: raise SaltCloudSystemExit( 'An error occurred while querying DigitalOcean. HTTP Code: {0} ' 'Error: \'{1}\''.format( request.status_code, # request.read() request.text ) ) log.debug(request.url) # success without data if request.status_code == 204: return True content = request.text result = salt.utils.json.loads(content) if result.get('status', '').lower() == 'error': raise SaltCloudSystemExit( pprint.pformat(result.get('error_message', {})) ) return result 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 show_instance(name, call=None): ''' Show the details from DigitalOcean concerning a droplet ''' if call != 'action': raise SaltCloudSystemExit( 'The show_instance action must be called with -a or --action.' ) node = _get_node(name) __utils__['cloud.cache_node'](node, __active_provider_name__, __opts__) return node def _get_node(name): attempts = 10 while attempts >= 0: try: return list_nodes_full(for_output=False)[name] except KeyError: attempts -= 1 log.debug( 'Failed to get the data for node \'%s\'. Remaining ' 'attempts: %s', name, attempts ) # Just a little delay between attempts... time.sleep(0.5) return {} def list_keypairs(call=None): ''' Return a dict of all available VM locations on the cloud provider with relevant data ''' if call != 'function': log.error( 'The list_keypairs function must be called with -f or --function.' ) return False fetch = True page = 1 ret = {} while fetch: items = query(method='account/keys', command='?page=' + six.text_type(page) + '&per_page=100') for key_pair in items['ssh_keys']: name = key_pair['name'] if name in ret: raise SaltCloudSystemExit( 'A duplicate key pair name, \'{0}\', was found in DigitalOcean\'s ' 'key pair list. Please change the key name stored by DigitalOcean. ' 'Be sure to adjust the value of \'ssh_key_file\' in your cloud ' 'profile or provider configuration, if necessary.'.format( name ) ) ret[name] = {} for item in six.iterkeys(key_pair): ret[name][item] = six.text_type(key_pair[item]) page += 1 try: fetch = 'next' in items['links']['pages'] except KeyError: fetch = False return ret def show_keypair(kwargs=None, call=None): ''' Show the details of an SSH keypair ''' if call != 'function': log.error( 'The show_keypair function must be called with -f or --function.' ) return False if not kwargs: kwargs = {} if 'keyname' not in kwargs: log.error('A keyname is required.') return False keypairs = list_keypairs(call='function') keyid = keypairs[kwargs['keyname']]['id'] log.debug('Key ID is %s', keyid) details = query(method='account/keys', command=keyid) return details def import_keypair(kwargs=None, call=None): ''' Upload public key to cloud provider. Similar to EC2 import_keypair. .. versionadded:: 2016.11.0 kwargs file(mandatory): public key file-name keyname(mandatory): public key name in the provider ''' with salt.utils.files.fopen(kwargs['file'], 'r') as public_key_filename: public_key_content = salt.utils.stringutils.to_unicode(public_key_filename.read()) digitalocean_kwargs = { 'name': kwargs['keyname'], 'public_key': public_key_content } created_result = create_key(digitalocean_kwargs, call=call) return created_result def create_key(kwargs=None, call=None): ''' Upload a public key ''' if call != 'function': log.error( 'The create_key function must be called with -f or --function.' ) return False try: result = query( method='account', command='keys', args={'name': kwargs['name'], 'public_key': kwargs['public_key']}, http_method='post' ) except KeyError: log.info('`name` and `public_key` arguments must be specified') return False return result def remove_key(kwargs=None, call=None): ''' Delete public key ''' if call != 'function': log.error( 'The create_key function must be called with -f or --function.' ) return False try: result = query( method='account', command='keys/' + kwargs['id'], http_method='delete' ) except KeyError: log.info('`id` argument must be specified') return False return result def get_keyid(keyname): ''' Return the ID of the keyname ''' if not keyname: return None keypairs = list_keypairs(call='function') keyid = keypairs[keyname]['id'] if keyid: return keyid raise SaltCloudNotFound('The specified ssh key could not be found.') def destroy(name, call=None): ''' Destroy a node. Will check termination protection and warn if enabled. 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'] ) data = show_instance(name, call='action') node = query(method='droplets', droplet_id=data['id'], http_method='delete') ## This is all terribly optomistic: # vm_ = get_vm_config(name=name) # delete_dns_record = config.get_cloud_config_value( # 'delete_dns_record', vm_, __opts__, search_global=False, default=None, # ) # TODO: when _vm config data can be made available, we should honor the configuration settings, # but until then, we should assume stale DNS records are bad, and default behavior should be to # delete them if we can. When this is resolved, also resolve the comments a couple of lines below. delete_dns_record = True if not isinstance(delete_dns_record, bool): raise SaltCloudConfigError( '\'delete_dns_record\' should be a boolean value.' ) # When the "to do" a few lines up is resolved, remove these lines and use the if/else logic below. log.debug('Deleting DNS records for %s.', name) destroy_dns_records(name) # Until the "to do" from line 754 is taken care of, we don't need this logic. # if delete_dns_record: # log.debug('Deleting DNS records for %s.', name) # destroy_dns_records(name) # else: # log.debug('delete_dns_record : %s', delete_dns_record) # for line in pprint.pformat(dir()).splitlines(): # log.debug('delete context: %s', line) __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 node def post_dns_record(**kwargs): ''' Creates a DNS record for the given name if the domain is managed with DO. ''' if 'kwargs' in kwargs: # flatten kwargs if called via salt-cloud -f f_kwargs = kwargs['kwargs'] del kwargs['kwargs'] kwargs.update(f_kwargs) mandatory_kwargs = ('dns_domain', 'name', 'record_type', 'record_data') for i in mandatory_kwargs: if kwargs[i]: pass else: error = '{0}="{1}" ## all mandatory args must be provided: {2}'.format(i, kwargs[i], mandatory_kwargs) raise SaltInvocationError(error) domain = query(method='domains', droplet_id=kwargs['dns_domain']) if domain: result = query( method='domains', droplet_id=kwargs['dns_domain'], command='records', args={'type': kwargs['record_type'], 'name': kwargs['name'], 'data': kwargs['record_data']}, http_method='post' ) return result return False def destroy_dns_records(fqdn): ''' Deletes DNS records for the given hostname if the domain is managed with DO. ''' domain = '.'.join(fqdn.split('.')[-2:]) hostname = '.'.join(fqdn.split('.')[:-2]) # TODO: remove this when the todo on 754 is available try: response = query(method='domains', droplet_id=domain, command='records') except SaltCloudSystemExit: log.debug('Failed to find domains.') return False log.debug("found DNS records: %s", pprint.pformat(response)) records = response['domain_records'] if records: record_ids = [r['id'] for r in records if r['name'].decode() == hostname] log.debug("deleting DNS record IDs: %s", record_ids) for id_ in record_ids: try: log.info('deleting DNS record %s', id_) ret = query( method='domains', droplet_id=domain, command='records/{0}'.format(id_), http_method='delete' ) except SaltCloudSystemExit: log.error('failed to delete DNS domain %s record ID %s.', domain, hostname) log.debug('DNS deletion REST call returned: %s', pprint.pformat(ret)) return False def show_pricing(kwargs=None, call=None): ''' Show pricing for a particular profile. This is only an estimate, based on unofficial pricing sources. .. versionadded:: 2015.8.0 CLI Examples: .. code-block:: bash salt-cloud -f show_pricing my-digitalocean-config profile=my-profile ''' profile = __opts__['profiles'].get(kwargs['profile'], {}) if not profile: return {'Error': 'The requested profile was not found'} # Make sure the profile belongs to DigitalOcean provider = profile.get('provider', '0:0') comps = provider.split(':') if len(comps) < 2 or comps[1] != 'digitalocean': return {'Error': 'The requested profile does not belong to DigitalOcean'} raw = {} ret = {} sizes = avail_sizes() ret['per_hour'] = decimal.Decimal(sizes[profile['size']]['price_hourly']) ret['per_day'] = ret['per_hour'] * 24 ret['per_week'] = ret['per_day'] * 7 ret['per_month'] = decimal.Decimal(sizes[profile['size']]['price_monthly']) ret['per_year'] = ret['per_week'] * 52 if kwargs.get('raw', False): ret['_raw'] = raw return {profile['profile']: ret} def list_floating_ips(call=None): ''' Return a list of the floating ips that are on the provider .. versionadded:: 2016.3.0 CLI Examples: .. code-block:: bash salt-cloud -f list_floating_ips my-digitalocean-config ''' if call == 'action': raise SaltCloudSystemExit( 'The list_floating_ips function must be called with ' '-f or --function, or with the --list-floating-ips option' ) fetch = True page = 1 ret = {} while fetch: items = query(method='floating_ips', command='?page=' + six.text_type(page) + '&per_page=200') for floating_ip in items['floating_ips']: ret[floating_ip['ip']] = {} for item in six.iterkeys(floating_ip): ret[floating_ip['ip']][item] = floating_ip[item] page += 1 try: fetch = 'next' in items['links']['pages'] except KeyError: fetch = False return ret def show_floating_ip(kwargs=None, call=None): ''' Show the details of a floating IP .. versionadded:: 2016.3.0 CLI Examples: .. code-block:: bash salt-cloud -f show_floating_ip my-digitalocean-config floating_ip='45.55.96.47' ''' if call != 'function': log.error( 'The show_floating_ip function must be called with -f or --function.' ) return False if not kwargs: kwargs = {} if 'floating_ip' not in kwargs: log.error('A floating IP is required.') return False floating_ip = kwargs['floating_ip'] log.debug('Floating ip is %s', floating_ip) details = query(method='floating_ips', command=floating_ip) return details def create_floating_ip(kwargs=None, call=None): ''' Create a new floating IP .. versionadded:: 2016.3.0 CLI Examples: .. code-block:: bash salt-cloud -f create_floating_ip my-digitalocean-config region='NYC2' salt-cloud -f create_floating_ip my-digitalocean-config droplet_id='1234567' ''' if call != 'function': log.error( 'The create_floating_ip function must be called with -f or --function.' ) return False if not kwargs: kwargs = {} if 'droplet_id' in kwargs: result = query(method='floating_ips', args={'droplet_id': kwargs['droplet_id']}, http_method='post') return result elif 'region' in kwargs: result = query(method='floating_ips', args={'region': kwargs['region']}, http_method='post') return result else: log.error('A droplet_id or region is required.') return False def delete_floating_ip(kwargs=None, call=None): ''' Delete a floating IP .. versionadded:: 2016.3.0 CLI Examples: .. code-block:: bash salt-cloud -f delete_floating_ip my-digitalocean-config floating_ip='45.55.96.47' ''' if call != 'function': log.error( 'The delete_floating_ip function must be called with -f or --function.' ) return False if not kwargs: kwargs = {} if 'floating_ip' not in kwargs: log.error('A floating IP is required.') return False floating_ip = kwargs['floating_ip'] log.debug('Floating ip is %s', kwargs['floating_ip']) result = query(method='floating_ips', command=floating_ip, http_method='delete') return result def assign_floating_ip(kwargs=None, call=None): ''' Assign a floating IP .. versionadded:: 2016.3.0 CLI Examples: .. code-block:: bash salt-cloud -f assign_floating_ip my-digitalocean-config droplet_id=1234567 floating_ip='45.55.96.47' ''' if call != 'function': log.error( 'The assign_floating_ip function must be called with -f or --function.' ) return False if not kwargs: kwargs = {} if 'floating_ip' and 'droplet_id' not in kwargs: log.error('A floating IP and droplet_id is required.') return False result = query(method='floating_ips', command=kwargs['floating_ip'] + '/actions', args={'droplet_id': kwargs['droplet_id'], 'type': 'assign'}, http_method='post') return result def unassign_floating_ip(kwargs=None, call=None): ''' Unassign a floating IP .. versionadded:: 2016.3.0 CLI Examples: .. code-block:: bash salt-cloud -f unassign_floating_ip my-digitalocean-config floating_ip='45.55.96.47' ''' if call != 'function': log.error( 'The inassign_floating_ip function must be called with -f or --function.' ) return False if not kwargs: kwargs = {} if 'floating_ip' not in kwargs: log.error('A floating IP is required.') return False result = query(method='floating_ips', command=kwargs['floating_ip'] + '/actions', args={'type': 'unassign'}, http_method='post') return result def _list_nodes(full=False, for_output=False): ''' Helper function to format and parse node data. ''' fetch = True page = 1 ret = {} while fetch: items = query(method='droplets', command='?page=' + six.text_type(page) + '&per_page=200') for node in items['droplets']: name = node['name'] ret[name] = {} if full: ret[name] = _get_full_output(node, for_output=for_output) else: public_ips, private_ips = _get_ips(node['networks']) ret[name] = { 'id': node['id'], 'image': node['image']['name'], 'name': name, 'private_ips': private_ips, 'public_ips': public_ips, 'size': node['size_slug'], 'state': six.text_type(node['status']), } page += 1 try: fetch = 'next' in items['links']['pages'] except KeyError: fetch = False return ret def reboot(name, call=None): ''' Reboot a droplet in DigitalOcean. .. versionadded:: 2015.8.8 name The name of the droplet to restart. CLI Example: .. code-block:: bash salt-cloud -a reboot droplet_name ''' if call != 'action': raise SaltCloudSystemExit( 'The restart action must be called with -a or --action.' ) data = show_instance(name, call='action') if data.get('status') == 'off': return {'success': True, 'action': 'stop', 'status': 'off', 'msg': 'Machine is already off.'} ret = query(droplet_id=data['id'], command='actions', args={'type': 'reboot'}, http_method='post') return {'success': True, 'action': ret['action']['type'], 'state': ret['action']['status']} def start(name, call=None): ''' Start a droplet in DigitalOcean. .. versionadded:: 2015.8.8 name The name of the droplet to start. CLI Example: .. code-block:: bash salt-cloud -a start droplet_name ''' if call != 'action': raise SaltCloudSystemExit( 'The start action must be called with -a or --action.' ) data = show_instance(name, call='action') if data.get('status') == 'active': return {'success': True, 'action': 'start', 'status': 'active', 'msg': 'Machine is already running.'} ret = query(droplet_id=data['id'], command='actions', args={'type': 'power_on'}, http_method='post') return {'success': True, 'action': ret['action']['type'], 'state': ret['action']['status']} def stop(name, call=None): ''' Stop a droplet in DigitalOcean. .. versionadded:: 2015.8.8 name The name of the droplet to stop. CLI Example: .. code-block:: bash salt-cloud -a stop droplet_name ''' if call != 'action': raise SaltCloudSystemExit( 'The stop action must be called with -a or --action.' ) data = show_instance(name, call='action') if data.get('status') == 'off': return {'success': True, 'action': 'stop', 'status': 'off', 'msg': 'Machine is already off.'} ret = query(droplet_id=data['id'], command='actions', args={'type': 'shutdown'}, http_method='post') return {'success': True, 'action': ret['action']['type'], 'state': ret['action']['status']} def _get_full_output(node, for_output=False): ''' Helper function for _list_nodes to loop through all node information. Returns a dictionary containing the full information of a node. ''' ret = {} for item in six.iterkeys(node): value = node[item] if value is not None and for_output: value = six.text_type(value) ret[item] = value return ret def _get_ips(networks): ''' Helper function for list_nodes. Returns public and private ip lists based on a given network dictionary. ''' v4s = networks.get('v4') v6s = networks.get('v6') public_ips = [] private_ips = [] if v4s: for item in v4s: ip_type = item.get('type') ip_address = item.get('ip_address') if ip_type == 'public': public_ips.append(ip_address) if ip_type == 'private': private_ips.append(ip_address) if v6s: for item in v6s: ip_type = item.get('type') ip_address = item.get('ip_address') if ip_type == 'public': public_ips.append(ip_address) if ip_type == 'private': private_ips.append(ip_address) return public_ips, private_ips
saltstack/salt
salt/cloud/clouds/digitalocean.py
query
python
def query(method='droplets', droplet_id=None, command=None, args=None, http_method='get'): ''' Make a web call to DigitalOcean ''' base_path = six.text_type(config.get_cloud_config_value( 'api_root', get_configured_provider(), __opts__, search_global=False, default='https://api.digitalocean.com/v2' )) path = '{0}/{1}/'.format(base_path, method) if droplet_id: path += '{0}/'.format(droplet_id) if command: path += command if not isinstance(args, dict): args = {} personal_access_token = config.get_cloud_config_value( 'personal_access_token', get_configured_provider(), __opts__, search_global=False ) data = salt.utils.json.dumps(args) requester = getattr(requests, http_method) request = requester(path, data=data, headers={'Authorization': 'Bearer ' + personal_access_token, 'Content-Type': 'application/json'}) if request.status_code > 299: raise SaltCloudSystemExit( 'An error occurred while querying DigitalOcean. HTTP Code: {0} ' 'Error: \'{1}\''.format( request.status_code, # request.read() request.text ) ) log.debug(request.url) # success without data if request.status_code == 204: return True content = request.text result = salt.utils.json.loads(content) if result.get('status', '').lower() == 'error': raise SaltCloudSystemExit( pprint.pformat(result.get('error_message', {})) ) return result
Make a web call to DigitalOcean
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/digitalocean.py#L549-L604
[ "def loads(s, **kwargs):\n '''\n .. versionadded:: 2018.3.0\n\n Wraps json.loads and prevents a traceback in the event that a bytestring is\n passed to the function. (Python < 3.6 cannot load bytestrings)\n\n You can pass an alternate json module (loaded via import_json() above)\n using the _json_module argument)\n '''\n json_module = kwargs.pop('_json_module', json)\n try:\n return json_module.loads(s, **kwargs)\n except TypeError as exc:\n # json.loads cannot load bytestrings in Python < 3.6\n if six.PY3 and isinstance(s, bytes):\n return json_module.loads(salt.utils.stringutils.to_unicode(s), **kwargs)\n else:\n raise exc\n", "def dumps(obj, **kwargs):\n '''\n .. versionadded:: 2018.3.0\n\n Wraps json.dumps, and assumes that ensure_ascii is False (unless explicitly\n passed as True) for unicode compatibility. Note that setting it to True\n will mess up any unicode characters, as they will be dumped as the string\n literal version of the unicode code point.\n\n On Python 2, encodes the result to a str since json.dumps does not want\n unicode types.\n\n You can pass an alternate json module (loaded via import_json() above)\n using the _json_module argument)\n '''\n json_module = kwargs.pop('_json_module', json)\n orig_enc_func = kwargs.pop('default', lambda x: x)\n\n def _enc_func(obj):\n obj = ThreadLocalProxy.unproxy(obj)\n return orig_enc_func(obj)\n\n if 'ensure_ascii' not in kwargs:\n kwargs['ensure_ascii'] = False\n if six.PY2:\n obj = salt.utils.data.encode(obj)\n return json_module.dumps(obj, default=_enc_func, **kwargs) # future lint: blacklisted-function\n", "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 get_configured_provider():\n '''\n Return the first configured instance.\n '''\n return config.is_provider_configured(\n opts=__opts__,\n provider=__active_provider_name__ or __virtualname__,\n aliases=__virtual_aliases__,\n required_keys=('personal_access_token',)\n )\n" ]
# -*- coding: utf-8 -*- ''' DigitalOcean Cloud Module ========================= The DigitalOcean cloud module is used to control access to the DigitalOcean VPS system. Use of this module requires a requires a ``personal_access_token``, an ``ssh_key_file``, and at least one SSH key name in ``ssh_key_names``. More ``ssh_key_names`` can be added by separating each key with a comma. The ``personal_access_token`` can be found in the DigitalOcean web interface in the "Apps & API" section. The SSH key name can be found under the "SSH Keys" section. .. code-block:: yaml # Note: This example is for /etc/salt/cloud.providers or any file in the # /etc/salt/cloud.providers.d/ directory. my-digital-ocean-config: personal_access_token: xxx ssh_key_file: /path/to/ssh/key/file ssh_key_names: my-key-name,my-key-name-2 driver: digitalocean :depends: requests ''' # Import Python Libs from __future__ import absolute_import, print_function, unicode_literals import decimal import logging import os import pprint import time # Import Salt Libs import salt.utils.cloud import salt.utils.files import salt.utils.json import salt.utils.stringutils import salt.config as config from salt.exceptions import ( SaltCloudConfigError, SaltInvocationError, SaltCloudNotFound, SaltCloudSystemExit, SaltCloudExecutionFailure, SaltCloudExecutionTimeout ) from salt.ext import six from salt.ext.six.moves import zip # Import Third Party Libs try: import requests HAS_REQUESTS = True except ImportError: HAS_REQUESTS = False # Get logging started log = logging.getLogger(__name__) __virtualname__ = 'digitalocean' __virtual_aliases__ = ('digital_ocean', 'do') # Only load in this module if the DIGITALOCEAN configurations are in place def __virtual__(): ''' Check for DigitalOcean 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=__opts__, provider=__active_provider_name__ or __virtualname__, aliases=__virtual_aliases__, required_keys=('personal_access_token',) ) def get_dependencies(): ''' Warn if dependencies aren't met. ''' return config.check_driver_dependencies( __virtualname__, {'requests': HAS_REQUESTS} ) def avail_locations(call=None): ''' Return a dict of all available VM locations on the cloud provider with relevant data ''' if call == 'action': raise SaltCloudSystemExit( 'The avail_locations function must be called with ' '-f or --function, or with the --list-locations option' ) items = query(method='regions') ret = {} for region in items['regions']: ret[region['name']] = {} for item in six.iterkeys(region): ret[region['name']][item] = six.text_type(region[item]) return ret def avail_images(call=None): ''' Return a list of the images that are on the provider ''' if call == 'action': raise SaltCloudSystemExit( 'The avail_images function must be called with ' '-f or --function, or with the --list-images option' ) fetch = True page = 1 ret = {} while fetch: items = query(method='images', command='?page=' + six.text_type(page) + '&per_page=200') for image in items['images']: ret[image['name']] = {} for item in six.iterkeys(image): ret[image['name']][item] = image[item] page += 1 try: fetch = 'next' in items['links']['pages'] except KeyError: fetch = False return ret def avail_sizes(call=None): ''' Return a list of the image sizes that are on the provider ''' if call == 'action': raise SaltCloudSystemExit( 'The avail_sizes function must be called with ' '-f or --function, or with the --list-sizes option' ) items = query(method='sizes', command='?per_page=100') ret = {} for size in items['sizes']: ret[size['slug']] = {} for item in six.iterkeys(size): ret[size['slug']][item] = six.text_type(size[item]) 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.' ) return _list_nodes() def list_nodes_full(call=None, for_output=True): ''' 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.' ) return _list_nodes(full=True, for_output=for_output) 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('function'), __opts__['query.selection'], call, ) def get_image(vm_): ''' Return the image object to use ''' images = avail_images() vm_image = config.get_cloud_config_value( 'image', vm_, __opts__, search_global=False ) if not isinstance(vm_image, six.string_types): vm_image = six.text_type(vm_image) for image in images: if vm_image in (images[image]['name'], images[image]['slug'], images[image]['id']): if images[image]['slug'] is not None: return images[image]['slug'] return int(images[image]['id']) raise SaltCloudNotFound( 'The specified image, \'{0}\', could not be found.'.format(vm_image) ) def get_size(vm_): ''' Return the VM's size. Used by create_node(). ''' sizes = avail_sizes() vm_size = six.text_type(config.get_cloud_config_value( 'size', vm_, __opts__, search_global=False )) for size in sizes: if vm_size.lower() == sizes[size]['slug']: return sizes[size]['slug'] raise SaltCloudNotFound( 'The specified size, \'{0}\', could not be found.'.format(vm_size) ) def get_location(vm_): ''' Return the VM's location ''' locations = avail_locations() vm_location = six.text_type(config.get_cloud_config_value( 'location', vm_, __opts__, search_global=False )) for location in locations: if vm_location in (locations[location]['name'], locations[location]['slug']): return locations[location]['slug'] raise SaltCloudNotFound( 'The specified location, \'{0}\', could not be found.'.format( vm_location ) ) def create_node(args): ''' Create a node ''' node = query(method='droplets', args=args, http_method='post') return node 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 'digitalocean', vm_['profile'], vm_=vm_) is False: return False except AttributeError: pass __utils__['cloud.fire_event']( 'event', 'starting create', 'salt/cloud/{0}/creating'.format(vm_['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', vm_['name']) kwargs = { 'name': vm_['name'], 'size': get_size(vm_), 'image': get_image(vm_), 'region': get_location(vm_), 'ssh_keys': [], 'tags': [] } # backwards compat ssh_key_name = config.get_cloud_config_value( 'ssh_key_name', vm_, __opts__, search_global=False ) if ssh_key_name: kwargs['ssh_keys'].append(get_keyid(ssh_key_name)) ssh_key_names = config.get_cloud_config_value( 'ssh_key_names', vm_, __opts__, search_global=False, default=False ) if ssh_key_names: for key in ssh_key_names.split(','): kwargs['ssh_keys'].append(get_keyid(key)) key_filename = config.get_cloud_config_value( 'ssh_key_file', vm_, __opts__, search_global=False, default=None ) if key_filename is not None and not os.path.isfile(key_filename): raise SaltCloudConfigError( 'The defined key_filename \'{0}\' does not exist'.format( key_filename ) ) if not __opts__.get('ssh_agent', False) and key_filename is None: raise SaltCloudConfigError( 'The DigitalOcean driver requires an ssh_key_file and an ssh_key_name ' 'because it does not supply a root password upon building the server.' ) ssh_interface = config.get_cloud_config_value( 'ssh_interface', vm_, __opts__, search_global=False, default='public' ) if ssh_interface in ['private', 'public']: log.info("ssh_interface: Setting interface for ssh to %s", ssh_interface) kwargs['ssh_interface'] = ssh_interface else: raise SaltCloudConfigError( "The DigitalOcean driver requires ssh_interface to be defined as 'public' or 'private'." ) private_networking = config.get_cloud_config_value( 'private_networking', vm_, __opts__, search_global=False, default=None, ) if private_networking is not None: if not isinstance(private_networking, bool): raise SaltCloudConfigError("'private_networking' should be a boolean value.") kwargs['private_networking'] = private_networking if not private_networking and ssh_interface == 'private': raise SaltCloudConfigError( "The DigitalOcean driver requires ssh_interface if defined as 'private' " "then private_networking should be set as 'True'." ) backups_enabled = config.get_cloud_config_value( 'backups_enabled', vm_, __opts__, search_global=False, default=None, ) if backups_enabled is not None: if not isinstance(backups_enabled, bool): raise SaltCloudConfigError("'backups_enabled' should be a boolean value.") kwargs['backups'] = backups_enabled ipv6 = config.get_cloud_config_value( 'ipv6', vm_, __opts__, search_global=False, default=None, ) if ipv6 is not None: if not isinstance(ipv6, bool): raise SaltCloudConfigError("'ipv6' should be a boolean value.") kwargs['ipv6'] = ipv6 monitoring = config.get_cloud_config_value( 'monitoring', vm_, __opts__, search_global=False, default=None, ) if monitoring is not None: if not isinstance(monitoring, bool): raise SaltCloudConfigError("'monitoring' should be a boolean value.") kwargs['monitoring'] = monitoring kwargs['tags'] = config.get_cloud_config_value( 'tags', vm_, __opts__, search_global=False, default=False ) userdata_file = config.get_cloud_config_value( 'userdata_file', vm_, __opts__, search_global=False, default=None ) if userdata_file is not None: try: with salt.utils.files.fopen(userdata_file, 'r') as fp_: kwargs['user_data'] = salt.utils.cloud.userdata_template( __opts__, vm_, salt.utils.stringutils.to_unicode(fp_.read()) ) except Exception as exc: log.exception( 'Failed to read userdata from %s: %s', userdata_file, exc) create_dns_record = config.get_cloud_config_value( 'create_dns_record', vm_, __opts__, search_global=False, default=None, ) if create_dns_record: log.info('create_dns_record: will attempt to write DNS records') default_dns_domain = None dns_domain_name = vm_['name'].split('.') if len(dns_domain_name) > 2: log.debug('create_dns_record: inferring default dns_hostname, dns_domain from minion name as FQDN') default_dns_hostname = '.'.join(dns_domain_name[:-2]) default_dns_domain = '.'.join(dns_domain_name[-2:]) else: log.debug("create_dns_record: can't infer dns_domain from %s", vm_['name']) default_dns_hostname = dns_domain_name[0] dns_hostname = config.get_cloud_config_value( 'dns_hostname', vm_, __opts__, search_global=False, default=default_dns_hostname, ) dns_domain = config.get_cloud_config_value( 'dns_domain', vm_, __opts__, search_global=False, default=default_dns_domain, ) if dns_hostname and dns_domain: log.info('create_dns_record: using dns_hostname="%s", dns_domain="%s"', dns_hostname, dns_domain) __add_dns_addr__ = lambda t, d: post_dns_record(dns_domain=dns_domain, name=dns_hostname, record_type=t, record_data=d) log.debug('create_dns_record: %s', __add_dns_addr__) else: log.error('create_dns_record: could not determine dns_hostname and/or dns_domain') raise SaltCloudConfigError( '\'create_dns_record\' must be a dict specifying "domain" ' 'and "hostname" or the minion name must be an FQDN.' ) __utils__['cloud.fire_event']( 'event', 'requesting instance', 'salt/cloud/{0}/requesting'.format(vm_['name']), args=__utils__['cloud.filter_event']('requesting', kwargs, list(kwargs)), sock_dir=__opts__['sock_dir'], transport=__opts__['transport'] ) try: ret = create_node(kwargs) except Exception as exc: log.error( 'Error creating %s on DIGITALOCEAN\n\n' 'The following exception was thrown when trying to ' 'run the initial deployment: %s', vm_['name'], exc, # Show the traceback if the debug logging level is enabled exc_info_on_loglevel=logging.DEBUG ) return False def __query_node_data(vm_name): data = show_instance(vm_name, 'action') if not data: # Trigger an error in the wait_for_ip function return False if data['networks'].get('v4'): for network in data['networks']['v4']: if network['type'] == 'public': return data return False try: data = salt.utils.cloud.wait_for_ip( __query_node_data, update_args=(vm_['name'],), timeout=config.get_cloud_config_value( 'wait_for_ip_timeout', vm_, __opts__, default=10 * 60), interval=config.get_cloud_config_value( 'wait_for_ip_interval', vm_, __opts__, default=10), ) except (SaltCloudExecutionTimeout, SaltCloudExecutionFailure) as exc: try: # It might be already up, let's destroy it! destroy(vm_['name']) except SaltCloudSystemExit: pass finally: raise SaltCloudSystemExit(six.text_type(exc)) if not vm_.get('ssh_host'): vm_['ssh_host'] = None # add DNS records, set ssh_host, default to first found IP, preferring IPv4 for ssh bootstrap script target addr_families, dns_arec_types = (('v4', 'v6'), ('A', 'AAAA')) arec_map = dict(list(zip(addr_families, dns_arec_types))) for facing, addr_family, ip_address in [(net['type'], family, net['ip_address']) for family in addr_families for net in data['networks'][family]]: log.info('found %s IP%s interface for "%s"', facing, addr_family, ip_address) dns_rec_type = arec_map[addr_family] if facing == 'public': if create_dns_record: __add_dns_addr__(dns_rec_type, ip_address) if facing == ssh_interface: if not vm_['ssh_host']: vm_['ssh_host'] = ip_address if vm_['ssh_host'] is None: raise SaltCloudSystemExit( 'No suitable IP addresses found for ssh minion bootstrapping: {0}'.format(repr(data['networks'])) ) log.debug( 'Found public IP address to use for ssh minion bootstrapping: %s', vm_['ssh_host'] ) vm_['key_filename'] = key_filename ret = __utils__['cloud.bootstrap'](vm_, __opts__) ret.update(data) log.info('Created Cloud VM \'%s\'', vm_['name']) log.debug( '\'%s\' VM creation details:\n%s', vm_['name'], pprint.pformat(data) ) __utils__['cloud.fire_event']( 'event', 'created instance', 'salt/cloud/{0}/created'.format(vm_['name']), args=__utils__['cloud.filter_event']('created', vm_, ['name', 'profile', 'provider', 'driver']), sock_dir=__opts__['sock_dir'], transport=__opts__['transport'] ) return ret 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 show_instance(name, call=None): ''' Show the details from DigitalOcean concerning a droplet ''' if call != 'action': raise SaltCloudSystemExit( 'The show_instance action must be called with -a or --action.' ) node = _get_node(name) __utils__['cloud.cache_node'](node, __active_provider_name__, __opts__) return node def _get_node(name): attempts = 10 while attempts >= 0: try: return list_nodes_full(for_output=False)[name] except KeyError: attempts -= 1 log.debug( 'Failed to get the data for node \'%s\'. Remaining ' 'attempts: %s', name, attempts ) # Just a little delay between attempts... time.sleep(0.5) return {} def list_keypairs(call=None): ''' Return a dict of all available VM locations on the cloud provider with relevant data ''' if call != 'function': log.error( 'The list_keypairs function must be called with -f or --function.' ) return False fetch = True page = 1 ret = {} while fetch: items = query(method='account/keys', command='?page=' + six.text_type(page) + '&per_page=100') for key_pair in items['ssh_keys']: name = key_pair['name'] if name in ret: raise SaltCloudSystemExit( 'A duplicate key pair name, \'{0}\', was found in DigitalOcean\'s ' 'key pair list. Please change the key name stored by DigitalOcean. ' 'Be sure to adjust the value of \'ssh_key_file\' in your cloud ' 'profile or provider configuration, if necessary.'.format( name ) ) ret[name] = {} for item in six.iterkeys(key_pair): ret[name][item] = six.text_type(key_pair[item]) page += 1 try: fetch = 'next' in items['links']['pages'] except KeyError: fetch = False return ret def show_keypair(kwargs=None, call=None): ''' Show the details of an SSH keypair ''' if call != 'function': log.error( 'The show_keypair function must be called with -f or --function.' ) return False if not kwargs: kwargs = {} if 'keyname' not in kwargs: log.error('A keyname is required.') return False keypairs = list_keypairs(call='function') keyid = keypairs[kwargs['keyname']]['id'] log.debug('Key ID is %s', keyid) details = query(method='account/keys', command=keyid) return details def import_keypair(kwargs=None, call=None): ''' Upload public key to cloud provider. Similar to EC2 import_keypair. .. versionadded:: 2016.11.0 kwargs file(mandatory): public key file-name keyname(mandatory): public key name in the provider ''' with salt.utils.files.fopen(kwargs['file'], 'r') as public_key_filename: public_key_content = salt.utils.stringutils.to_unicode(public_key_filename.read()) digitalocean_kwargs = { 'name': kwargs['keyname'], 'public_key': public_key_content } created_result = create_key(digitalocean_kwargs, call=call) return created_result def create_key(kwargs=None, call=None): ''' Upload a public key ''' if call != 'function': log.error( 'The create_key function must be called with -f or --function.' ) return False try: result = query( method='account', command='keys', args={'name': kwargs['name'], 'public_key': kwargs['public_key']}, http_method='post' ) except KeyError: log.info('`name` and `public_key` arguments must be specified') return False return result def remove_key(kwargs=None, call=None): ''' Delete public key ''' if call != 'function': log.error( 'The create_key function must be called with -f or --function.' ) return False try: result = query( method='account', command='keys/' + kwargs['id'], http_method='delete' ) except KeyError: log.info('`id` argument must be specified') return False return result def get_keyid(keyname): ''' Return the ID of the keyname ''' if not keyname: return None keypairs = list_keypairs(call='function') keyid = keypairs[keyname]['id'] if keyid: return keyid raise SaltCloudNotFound('The specified ssh key could not be found.') def destroy(name, call=None): ''' Destroy a node. Will check termination protection and warn if enabled. 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'] ) data = show_instance(name, call='action') node = query(method='droplets', droplet_id=data['id'], http_method='delete') ## This is all terribly optomistic: # vm_ = get_vm_config(name=name) # delete_dns_record = config.get_cloud_config_value( # 'delete_dns_record', vm_, __opts__, search_global=False, default=None, # ) # TODO: when _vm config data can be made available, we should honor the configuration settings, # but until then, we should assume stale DNS records are bad, and default behavior should be to # delete them if we can. When this is resolved, also resolve the comments a couple of lines below. delete_dns_record = True if not isinstance(delete_dns_record, bool): raise SaltCloudConfigError( '\'delete_dns_record\' should be a boolean value.' ) # When the "to do" a few lines up is resolved, remove these lines and use the if/else logic below. log.debug('Deleting DNS records for %s.', name) destroy_dns_records(name) # Until the "to do" from line 754 is taken care of, we don't need this logic. # if delete_dns_record: # log.debug('Deleting DNS records for %s.', name) # destroy_dns_records(name) # else: # log.debug('delete_dns_record : %s', delete_dns_record) # for line in pprint.pformat(dir()).splitlines(): # log.debug('delete context: %s', line) __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 node def post_dns_record(**kwargs): ''' Creates a DNS record for the given name if the domain is managed with DO. ''' if 'kwargs' in kwargs: # flatten kwargs if called via salt-cloud -f f_kwargs = kwargs['kwargs'] del kwargs['kwargs'] kwargs.update(f_kwargs) mandatory_kwargs = ('dns_domain', 'name', 'record_type', 'record_data') for i in mandatory_kwargs: if kwargs[i]: pass else: error = '{0}="{1}" ## all mandatory args must be provided: {2}'.format(i, kwargs[i], mandatory_kwargs) raise SaltInvocationError(error) domain = query(method='domains', droplet_id=kwargs['dns_domain']) if domain: result = query( method='domains', droplet_id=kwargs['dns_domain'], command='records', args={'type': kwargs['record_type'], 'name': kwargs['name'], 'data': kwargs['record_data']}, http_method='post' ) return result return False def destroy_dns_records(fqdn): ''' Deletes DNS records for the given hostname if the domain is managed with DO. ''' domain = '.'.join(fqdn.split('.')[-2:]) hostname = '.'.join(fqdn.split('.')[:-2]) # TODO: remove this when the todo on 754 is available try: response = query(method='domains', droplet_id=domain, command='records') except SaltCloudSystemExit: log.debug('Failed to find domains.') return False log.debug("found DNS records: %s", pprint.pformat(response)) records = response['domain_records'] if records: record_ids = [r['id'] for r in records if r['name'].decode() == hostname] log.debug("deleting DNS record IDs: %s", record_ids) for id_ in record_ids: try: log.info('deleting DNS record %s', id_) ret = query( method='domains', droplet_id=domain, command='records/{0}'.format(id_), http_method='delete' ) except SaltCloudSystemExit: log.error('failed to delete DNS domain %s record ID %s.', domain, hostname) log.debug('DNS deletion REST call returned: %s', pprint.pformat(ret)) return False def show_pricing(kwargs=None, call=None): ''' Show pricing for a particular profile. This is only an estimate, based on unofficial pricing sources. .. versionadded:: 2015.8.0 CLI Examples: .. code-block:: bash salt-cloud -f show_pricing my-digitalocean-config profile=my-profile ''' profile = __opts__['profiles'].get(kwargs['profile'], {}) if not profile: return {'Error': 'The requested profile was not found'} # Make sure the profile belongs to DigitalOcean provider = profile.get('provider', '0:0') comps = provider.split(':') if len(comps) < 2 or comps[1] != 'digitalocean': return {'Error': 'The requested profile does not belong to DigitalOcean'} raw = {} ret = {} sizes = avail_sizes() ret['per_hour'] = decimal.Decimal(sizes[profile['size']]['price_hourly']) ret['per_day'] = ret['per_hour'] * 24 ret['per_week'] = ret['per_day'] * 7 ret['per_month'] = decimal.Decimal(sizes[profile['size']]['price_monthly']) ret['per_year'] = ret['per_week'] * 52 if kwargs.get('raw', False): ret['_raw'] = raw return {profile['profile']: ret} def list_floating_ips(call=None): ''' Return a list of the floating ips that are on the provider .. versionadded:: 2016.3.0 CLI Examples: .. code-block:: bash salt-cloud -f list_floating_ips my-digitalocean-config ''' if call == 'action': raise SaltCloudSystemExit( 'The list_floating_ips function must be called with ' '-f or --function, or with the --list-floating-ips option' ) fetch = True page = 1 ret = {} while fetch: items = query(method='floating_ips', command='?page=' + six.text_type(page) + '&per_page=200') for floating_ip in items['floating_ips']: ret[floating_ip['ip']] = {} for item in six.iterkeys(floating_ip): ret[floating_ip['ip']][item] = floating_ip[item] page += 1 try: fetch = 'next' in items['links']['pages'] except KeyError: fetch = False return ret def show_floating_ip(kwargs=None, call=None): ''' Show the details of a floating IP .. versionadded:: 2016.3.0 CLI Examples: .. code-block:: bash salt-cloud -f show_floating_ip my-digitalocean-config floating_ip='45.55.96.47' ''' if call != 'function': log.error( 'The show_floating_ip function must be called with -f or --function.' ) return False if not kwargs: kwargs = {} if 'floating_ip' not in kwargs: log.error('A floating IP is required.') return False floating_ip = kwargs['floating_ip'] log.debug('Floating ip is %s', floating_ip) details = query(method='floating_ips', command=floating_ip) return details def create_floating_ip(kwargs=None, call=None): ''' Create a new floating IP .. versionadded:: 2016.3.0 CLI Examples: .. code-block:: bash salt-cloud -f create_floating_ip my-digitalocean-config region='NYC2' salt-cloud -f create_floating_ip my-digitalocean-config droplet_id='1234567' ''' if call != 'function': log.error( 'The create_floating_ip function must be called with -f or --function.' ) return False if not kwargs: kwargs = {} if 'droplet_id' in kwargs: result = query(method='floating_ips', args={'droplet_id': kwargs['droplet_id']}, http_method='post') return result elif 'region' in kwargs: result = query(method='floating_ips', args={'region': kwargs['region']}, http_method='post') return result else: log.error('A droplet_id or region is required.') return False def delete_floating_ip(kwargs=None, call=None): ''' Delete a floating IP .. versionadded:: 2016.3.0 CLI Examples: .. code-block:: bash salt-cloud -f delete_floating_ip my-digitalocean-config floating_ip='45.55.96.47' ''' if call != 'function': log.error( 'The delete_floating_ip function must be called with -f or --function.' ) return False if not kwargs: kwargs = {} if 'floating_ip' not in kwargs: log.error('A floating IP is required.') return False floating_ip = kwargs['floating_ip'] log.debug('Floating ip is %s', kwargs['floating_ip']) result = query(method='floating_ips', command=floating_ip, http_method='delete') return result def assign_floating_ip(kwargs=None, call=None): ''' Assign a floating IP .. versionadded:: 2016.3.0 CLI Examples: .. code-block:: bash salt-cloud -f assign_floating_ip my-digitalocean-config droplet_id=1234567 floating_ip='45.55.96.47' ''' if call != 'function': log.error( 'The assign_floating_ip function must be called with -f or --function.' ) return False if not kwargs: kwargs = {} if 'floating_ip' and 'droplet_id' not in kwargs: log.error('A floating IP and droplet_id is required.') return False result = query(method='floating_ips', command=kwargs['floating_ip'] + '/actions', args={'droplet_id': kwargs['droplet_id'], 'type': 'assign'}, http_method='post') return result def unassign_floating_ip(kwargs=None, call=None): ''' Unassign a floating IP .. versionadded:: 2016.3.0 CLI Examples: .. code-block:: bash salt-cloud -f unassign_floating_ip my-digitalocean-config floating_ip='45.55.96.47' ''' if call != 'function': log.error( 'The inassign_floating_ip function must be called with -f or --function.' ) return False if not kwargs: kwargs = {} if 'floating_ip' not in kwargs: log.error('A floating IP is required.') return False result = query(method='floating_ips', command=kwargs['floating_ip'] + '/actions', args={'type': 'unassign'}, http_method='post') return result def _list_nodes(full=False, for_output=False): ''' Helper function to format and parse node data. ''' fetch = True page = 1 ret = {} while fetch: items = query(method='droplets', command='?page=' + six.text_type(page) + '&per_page=200') for node in items['droplets']: name = node['name'] ret[name] = {} if full: ret[name] = _get_full_output(node, for_output=for_output) else: public_ips, private_ips = _get_ips(node['networks']) ret[name] = { 'id': node['id'], 'image': node['image']['name'], 'name': name, 'private_ips': private_ips, 'public_ips': public_ips, 'size': node['size_slug'], 'state': six.text_type(node['status']), } page += 1 try: fetch = 'next' in items['links']['pages'] except KeyError: fetch = False return ret def reboot(name, call=None): ''' Reboot a droplet in DigitalOcean. .. versionadded:: 2015.8.8 name The name of the droplet to restart. CLI Example: .. code-block:: bash salt-cloud -a reboot droplet_name ''' if call != 'action': raise SaltCloudSystemExit( 'The restart action must be called with -a or --action.' ) data = show_instance(name, call='action') if data.get('status') == 'off': return {'success': True, 'action': 'stop', 'status': 'off', 'msg': 'Machine is already off.'} ret = query(droplet_id=data['id'], command='actions', args={'type': 'reboot'}, http_method='post') return {'success': True, 'action': ret['action']['type'], 'state': ret['action']['status']} def start(name, call=None): ''' Start a droplet in DigitalOcean. .. versionadded:: 2015.8.8 name The name of the droplet to start. CLI Example: .. code-block:: bash salt-cloud -a start droplet_name ''' if call != 'action': raise SaltCloudSystemExit( 'The start action must be called with -a or --action.' ) data = show_instance(name, call='action') if data.get('status') == 'active': return {'success': True, 'action': 'start', 'status': 'active', 'msg': 'Machine is already running.'} ret = query(droplet_id=data['id'], command='actions', args={'type': 'power_on'}, http_method='post') return {'success': True, 'action': ret['action']['type'], 'state': ret['action']['status']} def stop(name, call=None): ''' Stop a droplet in DigitalOcean. .. versionadded:: 2015.8.8 name The name of the droplet to stop. CLI Example: .. code-block:: bash salt-cloud -a stop droplet_name ''' if call != 'action': raise SaltCloudSystemExit( 'The stop action must be called with -a or --action.' ) data = show_instance(name, call='action') if data.get('status') == 'off': return {'success': True, 'action': 'stop', 'status': 'off', 'msg': 'Machine is already off.'} ret = query(droplet_id=data['id'], command='actions', args={'type': 'shutdown'}, http_method='post') return {'success': True, 'action': ret['action']['type'], 'state': ret['action']['status']} def _get_full_output(node, for_output=False): ''' Helper function for _list_nodes to loop through all node information. Returns a dictionary containing the full information of a node. ''' ret = {} for item in six.iterkeys(node): value = node[item] if value is not None and for_output: value = six.text_type(value) ret[item] = value return ret def _get_ips(networks): ''' Helper function for list_nodes. Returns public and private ip lists based on a given network dictionary. ''' v4s = networks.get('v4') v6s = networks.get('v6') public_ips = [] private_ips = [] if v4s: for item in v4s: ip_type = item.get('type') ip_address = item.get('ip_address') if ip_type == 'public': public_ips.append(ip_address) if ip_type == 'private': private_ips.append(ip_address) if v6s: for item in v6s: ip_type = item.get('type') ip_address = item.get('ip_address') if ip_type == 'public': public_ips.append(ip_address) if ip_type == 'private': private_ips.append(ip_address) return public_ips, private_ips
saltstack/salt
salt/cloud/clouds/digitalocean.py
show_instance
python
def show_instance(name, call=None): ''' Show the details from DigitalOcean concerning a droplet ''' if call != 'action': raise SaltCloudSystemExit( 'The show_instance action must be called with -a or --action.' ) node = _get_node(name) __utils__['cloud.cache_node'](node, __active_provider_name__, __opts__) return node
Show the details from DigitalOcean concerning a droplet
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/digitalocean.py#L622-L632
[ "def _get_node(name):\n attempts = 10\n while attempts >= 0:\n try:\n return list_nodes_full(for_output=False)[name]\n except KeyError:\n attempts -= 1\n log.debug(\n 'Failed to get the data for node \\'%s\\'. Remaining '\n 'attempts: %s', name, attempts\n )\n # Just a little delay between attempts...\n time.sleep(0.5)\n return {}\n" ]
# -*- coding: utf-8 -*- ''' DigitalOcean Cloud Module ========================= The DigitalOcean cloud module is used to control access to the DigitalOcean VPS system. Use of this module requires a requires a ``personal_access_token``, an ``ssh_key_file``, and at least one SSH key name in ``ssh_key_names``. More ``ssh_key_names`` can be added by separating each key with a comma. The ``personal_access_token`` can be found in the DigitalOcean web interface in the "Apps & API" section. The SSH key name can be found under the "SSH Keys" section. .. code-block:: yaml # Note: This example is for /etc/salt/cloud.providers or any file in the # /etc/salt/cloud.providers.d/ directory. my-digital-ocean-config: personal_access_token: xxx ssh_key_file: /path/to/ssh/key/file ssh_key_names: my-key-name,my-key-name-2 driver: digitalocean :depends: requests ''' # Import Python Libs from __future__ import absolute_import, print_function, unicode_literals import decimal import logging import os import pprint import time # Import Salt Libs import salt.utils.cloud import salt.utils.files import salt.utils.json import salt.utils.stringutils import salt.config as config from salt.exceptions import ( SaltCloudConfigError, SaltInvocationError, SaltCloudNotFound, SaltCloudSystemExit, SaltCloudExecutionFailure, SaltCloudExecutionTimeout ) from salt.ext import six from salt.ext.six.moves import zip # Import Third Party Libs try: import requests HAS_REQUESTS = True except ImportError: HAS_REQUESTS = False # Get logging started log = logging.getLogger(__name__) __virtualname__ = 'digitalocean' __virtual_aliases__ = ('digital_ocean', 'do') # Only load in this module if the DIGITALOCEAN configurations are in place def __virtual__(): ''' Check for DigitalOcean 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=__opts__, provider=__active_provider_name__ or __virtualname__, aliases=__virtual_aliases__, required_keys=('personal_access_token',) ) def get_dependencies(): ''' Warn if dependencies aren't met. ''' return config.check_driver_dependencies( __virtualname__, {'requests': HAS_REQUESTS} ) def avail_locations(call=None): ''' Return a dict of all available VM locations on the cloud provider with relevant data ''' if call == 'action': raise SaltCloudSystemExit( 'The avail_locations function must be called with ' '-f or --function, or with the --list-locations option' ) items = query(method='regions') ret = {} for region in items['regions']: ret[region['name']] = {} for item in six.iterkeys(region): ret[region['name']][item] = six.text_type(region[item]) return ret def avail_images(call=None): ''' Return a list of the images that are on the provider ''' if call == 'action': raise SaltCloudSystemExit( 'The avail_images function must be called with ' '-f or --function, or with the --list-images option' ) fetch = True page = 1 ret = {} while fetch: items = query(method='images', command='?page=' + six.text_type(page) + '&per_page=200') for image in items['images']: ret[image['name']] = {} for item in six.iterkeys(image): ret[image['name']][item] = image[item] page += 1 try: fetch = 'next' in items['links']['pages'] except KeyError: fetch = False return ret def avail_sizes(call=None): ''' Return a list of the image sizes that are on the provider ''' if call == 'action': raise SaltCloudSystemExit( 'The avail_sizes function must be called with ' '-f or --function, or with the --list-sizes option' ) items = query(method='sizes', command='?per_page=100') ret = {} for size in items['sizes']: ret[size['slug']] = {} for item in six.iterkeys(size): ret[size['slug']][item] = six.text_type(size[item]) 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.' ) return _list_nodes() def list_nodes_full(call=None, for_output=True): ''' 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.' ) return _list_nodes(full=True, for_output=for_output) 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('function'), __opts__['query.selection'], call, ) def get_image(vm_): ''' Return the image object to use ''' images = avail_images() vm_image = config.get_cloud_config_value( 'image', vm_, __opts__, search_global=False ) if not isinstance(vm_image, six.string_types): vm_image = six.text_type(vm_image) for image in images: if vm_image in (images[image]['name'], images[image]['slug'], images[image]['id']): if images[image]['slug'] is not None: return images[image]['slug'] return int(images[image]['id']) raise SaltCloudNotFound( 'The specified image, \'{0}\', could not be found.'.format(vm_image) ) def get_size(vm_): ''' Return the VM's size. Used by create_node(). ''' sizes = avail_sizes() vm_size = six.text_type(config.get_cloud_config_value( 'size', vm_, __opts__, search_global=False )) for size in sizes: if vm_size.lower() == sizes[size]['slug']: return sizes[size]['slug'] raise SaltCloudNotFound( 'The specified size, \'{0}\', could not be found.'.format(vm_size) ) def get_location(vm_): ''' Return the VM's location ''' locations = avail_locations() vm_location = six.text_type(config.get_cloud_config_value( 'location', vm_, __opts__, search_global=False )) for location in locations: if vm_location in (locations[location]['name'], locations[location]['slug']): return locations[location]['slug'] raise SaltCloudNotFound( 'The specified location, \'{0}\', could not be found.'.format( vm_location ) ) def create_node(args): ''' Create a node ''' node = query(method='droplets', args=args, http_method='post') return node 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 'digitalocean', vm_['profile'], vm_=vm_) is False: return False except AttributeError: pass __utils__['cloud.fire_event']( 'event', 'starting create', 'salt/cloud/{0}/creating'.format(vm_['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', vm_['name']) kwargs = { 'name': vm_['name'], 'size': get_size(vm_), 'image': get_image(vm_), 'region': get_location(vm_), 'ssh_keys': [], 'tags': [] } # backwards compat ssh_key_name = config.get_cloud_config_value( 'ssh_key_name', vm_, __opts__, search_global=False ) if ssh_key_name: kwargs['ssh_keys'].append(get_keyid(ssh_key_name)) ssh_key_names = config.get_cloud_config_value( 'ssh_key_names', vm_, __opts__, search_global=False, default=False ) if ssh_key_names: for key in ssh_key_names.split(','): kwargs['ssh_keys'].append(get_keyid(key)) key_filename = config.get_cloud_config_value( 'ssh_key_file', vm_, __opts__, search_global=False, default=None ) if key_filename is not None and not os.path.isfile(key_filename): raise SaltCloudConfigError( 'The defined key_filename \'{0}\' does not exist'.format( key_filename ) ) if not __opts__.get('ssh_agent', False) and key_filename is None: raise SaltCloudConfigError( 'The DigitalOcean driver requires an ssh_key_file and an ssh_key_name ' 'because it does not supply a root password upon building the server.' ) ssh_interface = config.get_cloud_config_value( 'ssh_interface', vm_, __opts__, search_global=False, default='public' ) if ssh_interface in ['private', 'public']: log.info("ssh_interface: Setting interface for ssh to %s", ssh_interface) kwargs['ssh_interface'] = ssh_interface else: raise SaltCloudConfigError( "The DigitalOcean driver requires ssh_interface to be defined as 'public' or 'private'." ) private_networking = config.get_cloud_config_value( 'private_networking', vm_, __opts__, search_global=False, default=None, ) if private_networking is not None: if not isinstance(private_networking, bool): raise SaltCloudConfigError("'private_networking' should be a boolean value.") kwargs['private_networking'] = private_networking if not private_networking and ssh_interface == 'private': raise SaltCloudConfigError( "The DigitalOcean driver requires ssh_interface if defined as 'private' " "then private_networking should be set as 'True'." ) backups_enabled = config.get_cloud_config_value( 'backups_enabled', vm_, __opts__, search_global=False, default=None, ) if backups_enabled is not None: if not isinstance(backups_enabled, bool): raise SaltCloudConfigError("'backups_enabled' should be a boolean value.") kwargs['backups'] = backups_enabled ipv6 = config.get_cloud_config_value( 'ipv6', vm_, __opts__, search_global=False, default=None, ) if ipv6 is not None: if not isinstance(ipv6, bool): raise SaltCloudConfigError("'ipv6' should be a boolean value.") kwargs['ipv6'] = ipv6 monitoring = config.get_cloud_config_value( 'monitoring', vm_, __opts__, search_global=False, default=None, ) if monitoring is not None: if not isinstance(monitoring, bool): raise SaltCloudConfigError("'monitoring' should be a boolean value.") kwargs['monitoring'] = monitoring kwargs['tags'] = config.get_cloud_config_value( 'tags', vm_, __opts__, search_global=False, default=False ) userdata_file = config.get_cloud_config_value( 'userdata_file', vm_, __opts__, search_global=False, default=None ) if userdata_file is not None: try: with salt.utils.files.fopen(userdata_file, 'r') as fp_: kwargs['user_data'] = salt.utils.cloud.userdata_template( __opts__, vm_, salt.utils.stringutils.to_unicode(fp_.read()) ) except Exception as exc: log.exception( 'Failed to read userdata from %s: %s', userdata_file, exc) create_dns_record = config.get_cloud_config_value( 'create_dns_record', vm_, __opts__, search_global=False, default=None, ) if create_dns_record: log.info('create_dns_record: will attempt to write DNS records') default_dns_domain = None dns_domain_name = vm_['name'].split('.') if len(dns_domain_name) > 2: log.debug('create_dns_record: inferring default dns_hostname, dns_domain from minion name as FQDN') default_dns_hostname = '.'.join(dns_domain_name[:-2]) default_dns_domain = '.'.join(dns_domain_name[-2:]) else: log.debug("create_dns_record: can't infer dns_domain from %s", vm_['name']) default_dns_hostname = dns_domain_name[0] dns_hostname = config.get_cloud_config_value( 'dns_hostname', vm_, __opts__, search_global=False, default=default_dns_hostname, ) dns_domain = config.get_cloud_config_value( 'dns_domain', vm_, __opts__, search_global=False, default=default_dns_domain, ) if dns_hostname and dns_domain: log.info('create_dns_record: using dns_hostname="%s", dns_domain="%s"', dns_hostname, dns_domain) __add_dns_addr__ = lambda t, d: post_dns_record(dns_domain=dns_domain, name=dns_hostname, record_type=t, record_data=d) log.debug('create_dns_record: %s', __add_dns_addr__) else: log.error('create_dns_record: could not determine dns_hostname and/or dns_domain') raise SaltCloudConfigError( '\'create_dns_record\' must be a dict specifying "domain" ' 'and "hostname" or the minion name must be an FQDN.' ) __utils__['cloud.fire_event']( 'event', 'requesting instance', 'salt/cloud/{0}/requesting'.format(vm_['name']), args=__utils__['cloud.filter_event']('requesting', kwargs, list(kwargs)), sock_dir=__opts__['sock_dir'], transport=__opts__['transport'] ) try: ret = create_node(kwargs) except Exception as exc: log.error( 'Error creating %s on DIGITALOCEAN\n\n' 'The following exception was thrown when trying to ' 'run the initial deployment: %s', vm_['name'], exc, # Show the traceback if the debug logging level is enabled exc_info_on_loglevel=logging.DEBUG ) return False def __query_node_data(vm_name): data = show_instance(vm_name, 'action') if not data: # Trigger an error in the wait_for_ip function return False if data['networks'].get('v4'): for network in data['networks']['v4']: if network['type'] == 'public': return data return False try: data = salt.utils.cloud.wait_for_ip( __query_node_data, update_args=(vm_['name'],), timeout=config.get_cloud_config_value( 'wait_for_ip_timeout', vm_, __opts__, default=10 * 60), interval=config.get_cloud_config_value( 'wait_for_ip_interval', vm_, __opts__, default=10), ) except (SaltCloudExecutionTimeout, SaltCloudExecutionFailure) as exc: try: # It might be already up, let's destroy it! destroy(vm_['name']) except SaltCloudSystemExit: pass finally: raise SaltCloudSystemExit(six.text_type(exc)) if not vm_.get('ssh_host'): vm_['ssh_host'] = None # add DNS records, set ssh_host, default to first found IP, preferring IPv4 for ssh bootstrap script target addr_families, dns_arec_types = (('v4', 'v6'), ('A', 'AAAA')) arec_map = dict(list(zip(addr_families, dns_arec_types))) for facing, addr_family, ip_address in [(net['type'], family, net['ip_address']) for family in addr_families for net in data['networks'][family]]: log.info('found %s IP%s interface for "%s"', facing, addr_family, ip_address) dns_rec_type = arec_map[addr_family] if facing == 'public': if create_dns_record: __add_dns_addr__(dns_rec_type, ip_address) if facing == ssh_interface: if not vm_['ssh_host']: vm_['ssh_host'] = ip_address if vm_['ssh_host'] is None: raise SaltCloudSystemExit( 'No suitable IP addresses found for ssh minion bootstrapping: {0}'.format(repr(data['networks'])) ) log.debug( 'Found public IP address to use for ssh minion bootstrapping: %s', vm_['ssh_host'] ) vm_['key_filename'] = key_filename ret = __utils__['cloud.bootstrap'](vm_, __opts__) ret.update(data) log.info('Created Cloud VM \'%s\'', vm_['name']) log.debug( '\'%s\' VM creation details:\n%s', vm_['name'], pprint.pformat(data) ) __utils__['cloud.fire_event']( 'event', 'created instance', 'salt/cloud/{0}/created'.format(vm_['name']), args=__utils__['cloud.filter_event']('created', vm_, ['name', 'profile', 'provider', 'driver']), sock_dir=__opts__['sock_dir'], transport=__opts__['transport'] ) return ret def query(method='droplets', droplet_id=None, command=None, args=None, http_method='get'): ''' Make a web call to DigitalOcean ''' base_path = six.text_type(config.get_cloud_config_value( 'api_root', get_configured_provider(), __opts__, search_global=False, default='https://api.digitalocean.com/v2' )) path = '{0}/{1}/'.format(base_path, method) if droplet_id: path += '{0}/'.format(droplet_id) if command: path += command if not isinstance(args, dict): args = {} personal_access_token = config.get_cloud_config_value( 'personal_access_token', get_configured_provider(), __opts__, search_global=False ) data = salt.utils.json.dumps(args) requester = getattr(requests, http_method) request = requester(path, data=data, headers={'Authorization': 'Bearer ' + personal_access_token, 'Content-Type': 'application/json'}) if request.status_code > 299: raise SaltCloudSystemExit( 'An error occurred while querying DigitalOcean. HTTP Code: {0} ' 'Error: \'{1}\''.format( request.status_code, # request.read() request.text ) ) log.debug(request.url) # success without data if request.status_code == 204: return True content = request.text result = salt.utils.json.loads(content) if result.get('status', '').lower() == 'error': raise SaltCloudSystemExit( pprint.pformat(result.get('error_message', {})) ) return result 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_node(name): attempts = 10 while attempts >= 0: try: return list_nodes_full(for_output=False)[name] except KeyError: attempts -= 1 log.debug( 'Failed to get the data for node \'%s\'. Remaining ' 'attempts: %s', name, attempts ) # Just a little delay between attempts... time.sleep(0.5) return {} def list_keypairs(call=None): ''' Return a dict of all available VM locations on the cloud provider with relevant data ''' if call != 'function': log.error( 'The list_keypairs function must be called with -f or --function.' ) return False fetch = True page = 1 ret = {} while fetch: items = query(method='account/keys', command='?page=' + six.text_type(page) + '&per_page=100') for key_pair in items['ssh_keys']: name = key_pair['name'] if name in ret: raise SaltCloudSystemExit( 'A duplicate key pair name, \'{0}\', was found in DigitalOcean\'s ' 'key pair list. Please change the key name stored by DigitalOcean. ' 'Be sure to adjust the value of \'ssh_key_file\' in your cloud ' 'profile or provider configuration, if necessary.'.format( name ) ) ret[name] = {} for item in six.iterkeys(key_pair): ret[name][item] = six.text_type(key_pair[item]) page += 1 try: fetch = 'next' in items['links']['pages'] except KeyError: fetch = False return ret def show_keypair(kwargs=None, call=None): ''' Show the details of an SSH keypair ''' if call != 'function': log.error( 'The show_keypair function must be called with -f or --function.' ) return False if not kwargs: kwargs = {} if 'keyname' not in kwargs: log.error('A keyname is required.') return False keypairs = list_keypairs(call='function') keyid = keypairs[kwargs['keyname']]['id'] log.debug('Key ID is %s', keyid) details = query(method='account/keys', command=keyid) return details def import_keypair(kwargs=None, call=None): ''' Upload public key to cloud provider. Similar to EC2 import_keypair. .. versionadded:: 2016.11.0 kwargs file(mandatory): public key file-name keyname(mandatory): public key name in the provider ''' with salt.utils.files.fopen(kwargs['file'], 'r') as public_key_filename: public_key_content = salt.utils.stringutils.to_unicode(public_key_filename.read()) digitalocean_kwargs = { 'name': kwargs['keyname'], 'public_key': public_key_content } created_result = create_key(digitalocean_kwargs, call=call) return created_result def create_key(kwargs=None, call=None): ''' Upload a public key ''' if call != 'function': log.error( 'The create_key function must be called with -f or --function.' ) return False try: result = query( method='account', command='keys', args={'name': kwargs['name'], 'public_key': kwargs['public_key']}, http_method='post' ) except KeyError: log.info('`name` and `public_key` arguments must be specified') return False return result def remove_key(kwargs=None, call=None): ''' Delete public key ''' if call != 'function': log.error( 'The create_key function must be called with -f or --function.' ) return False try: result = query( method='account', command='keys/' + kwargs['id'], http_method='delete' ) except KeyError: log.info('`id` argument must be specified') return False return result def get_keyid(keyname): ''' Return the ID of the keyname ''' if not keyname: return None keypairs = list_keypairs(call='function') keyid = keypairs[keyname]['id'] if keyid: return keyid raise SaltCloudNotFound('The specified ssh key could not be found.') def destroy(name, call=None): ''' Destroy a node. Will check termination protection and warn if enabled. 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'] ) data = show_instance(name, call='action') node = query(method='droplets', droplet_id=data['id'], http_method='delete') ## This is all terribly optomistic: # vm_ = get_vm_config(name=name) # delete_dns_record = config.get_cloud_config_value( # 'delete_dns_record', vm_, __opts__, search_global=False, default=None, # ) # TODO: when _vm config data can be made available, we should honor the configuration settings, # but until then, we should assume stale DNS records are bad, and default behavior should be to # delete them if we can. When this is resolved, also resolve the comments a couple of lines below. delete_dns_record = True if not isinstance(delete_dns_record, bool): raise SaltCloudConfigError( '\'delete_dns_record\' should be a boolean value.' ) # When the "to do" a few lines up is resolved, remove these lines and use the if/else logic below. log.debug('Deleting DNS records for %s.', name) destroy_dns_records(name) # Until the "to do" from line 754 is taken care of, we don't need this logic. # if delete_dns_record: # log.debug('Deleting DNS records for %s.', name) # destroy_dns_records(name) # else: # log.debug('delete_dns_record : %s', delete_dns_record) # for line in pprint.pformat(dir()).splitlines(): # log.debug('delete context: %s', line) __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 node def post_dns_record(**kwargs): ''' Creates a DNS record for the given name if the domain is managed with DO. ''' if 'kwargs' in kwargs: # flatten kwargs if called via salt-cloud -f f_kwargs = kwargs['kwargs'] del kwargs['kwargs'] kwargs.update(f_kwargs) mandatory_kwargs = ('dns_domain', 'name', 'record_type', 'record_data') for i in mandatory_kwargs: if kwargs[i]: pass else: error = '{0}="{1}" ## all mandatory args must be provided: {2}'.format(i, kwargs[i], mandatory_kwargs) raise SaltInvocationError(error) domain = query(method='domains', droplet_id=kwargs['dns_domain']) if domain: result = query( method='domains', droplet_id=kwargs['dns_domain'], command='records', args={'type': kwargs['record_type'], 'name': kwargs['name'], 'data': kwargs['record_data']}, http_method='post' ) return result return False def destroy_dns_records(fqdn): ''' Deletes DNS records for the given hostname if the domain is managed with DO. ''' domain = '.'.join(fqdn.split('.')[-2:]) hostname = '.'.join(fqdn.split('.')[:-2]) # TODO: remove this when the todo on 754 is available try: response = query(method='domains', droplet_id=domain, command='records') except SaltCloudSystemExit: log.debug('Failed to find domains.') return False log.debug("found DNS records: %s", pprint.pformat(response)) records = response['domain_records'] if records: record_ids = [r['id'] for r in records if r['name'].decode() == hostname] log.debug("deleting DNS record IDs: %s", record_ids) for id_ in record_ids: try: log.info('deleting DNS record %s', id_) ret = query( method='domains', droplet_id=domain, command='records/{0}'.format(id_), http_method='delete' ) except SaltCloudSystemExit: log.error('failed to delete DNS domain %s record ID %s.', domain, hostname) log.debug('DNS deletion REST call returned: %s', pprint.pformat(ret)) return False def show_pricing(kwargs=None, call=None): ''' Show pricing for a particular profile. This is only an estimate, based on unofficial pricing sources. .. versionadded:: 2015.8.0 CLI Examples: .. code-block:: bash salt-cloud -f show_pricing my-digitalocean-config profile=my-profile ''' profile = __opts__['profiles'].get(kwargs['profile'], {}) if not profile: return {'Error': 'The requested profile was not found'} # Make sure the profile belongs to DigitalOcean provider = profile.get('provider', '0:0') comps = provider.split(':') if len(comps) < 2 or comps[1] != 'digitalocean': return {'Error': 'The requested profile does not belong to DigitalOcean'} raw = {} ret = {} sizes = avail_sizes() ret['per_hour'] = decimal.Decimal(sizes[profile['size']]['price_hourly']) ret['per_day'] = ret['per_hour'] * 24 ret['per_week'] = ret['per_day'] * 7 ret['per_month'] = decimal.Decimal(sizes[profile['size']]['price_monthly']) ret['per_year'] = ret['per_week'] * 52 if kwargs.get('raw', False): ret['_raw'] = raw return {profile['profile']: ret} def list_floating_ips(call=None): ''' Return a list of the floating ips that are on the provider .. versionadded:: 2016.3.0 CLI Examples: .. code-block:: bash salt-cloud -f list_floating_ips my-digitalocean-config ''' if call == 'action': raise SaltCloudSystemExit( 'The list_floating_ips function must be called with ' '-f or --function, or with the --list-floating-ips option' ) fetch = True page = 1 ret = {} while fetch: items = query(method='floating_ips', command='?page=' + six.text_type(page) + '&per_page=200') for floating_ip in items['floating_ips']: ret[floating_ip['ip']] = {} for item in six.iterkeys(floating_ip): ret[floating_ip['ip']][item] = floating_ip[item] page += 1 try: fetch = 'next' in items['links']['pages'] except KeyError: fetch = False return ret def show_floating_ip(kwargs=None, call=None): ''' Show the details of a floating IP .. versionadded:: 2016.3.0 CLI Examples: .. code-block:: bash salt-cloud -f show_floating_ip my-digitalocean-config floating_ip='45.55.96.47' ''' if call != 'function': log.error( 'The show_floating_ip function must be called with -f or --function.' ) return False if not kwargs: kwargs = {} if 'floating_ip' not in kwargs: log.error('A floating IP is required.') return False floating_ip = kwargs['floating_ip'] log.debug('Floating ip is %s', floating_ip) details = query(method='floating_ips', command=floating_ip) return details def create_floating_ip(kwargs=None, call=None): ''' Create a new floating IP .. versionadded:: 2016.3.0 CLI Examples: .. code-block:: bash salt-cloud -f create_floating_ip my-digitalocean-config region='NYC2' salt-cloud -f create_floating_ip my-digitalocean-config droplet_id='1234567' ''' if call != 'function': log.error( 'The create_floating_ip function must be called with -f or --function.' ) return False if not kwargs: kwargs = {} if 'droplet_id' in kwargs: result = query(method='floating_ips', args={'droplet_id': kwargs['droplet_id']}, http_method='post') return result elif 'region' in kwargs: result = query(method='floating_ips', args={'region': kwargs['region']}, http_method='post') return result else: log.error('A droplet_id or region is required.') return False def delete_floating_ip(kwargs=None, call=None): ''' Delete a floating IP .. versionadded:: 2016.3.0 CLI Examples: .. code-block:: bash salt-cloud -f delete_floating_ip my-digitalocean-config floating_ip='45.55.96.47' ''' if call != 'function': log.error( 'The delete_floating_ip function must be called with -f or --function.' ) return False if not kwargs: kwargs = {} if 'floating_ip' not in kwargs: log.error('A floating IP is required.') return False floating_ip = kwargs['floating_ip'] log.debug('Floating ip is %s', kwargs['floating_ip']) result = query(method='floating_ips', command=floating_ip, http_method='delete') return result def assign_floating_ip(kwargs=None, call=None): ''' Assign a floating IP .. versionadded:: 2016.3.0 CLI Examples: .. code-block:: bash salt-cloud -f assign_floating_ip my-digitalocean-config droplet_id=1234567 floating_ip='45.55.96.47' ''' if call != 'function': log.error( 'The assign_floating_ip function must be called with -f or --function.' ) return False if not kwargs: kwargs = {} if 'floating_ip' and 'droplet_id' not in kwargs: log.error('A floating IP and droplet_id is required.') return False result = query(method='floating_ips', command=kwargs['floating_ip'] + '/actions', args={'droplet_id': kwargs['droplet_id'], 'type': 'assign'}, http_method='post') return result def unassign_floating_ip(kwargs=None, call=None): ''' Unassign a floating IP .. versionadded:: 2016.3.0 CLI Examples: .. code-block:: bash salt-cloud -f unassign_floating_ip my-digitalocean-config floating_ip='45.55.96.47' ''' if call != 'function': log.error( 'The inassign_floating_ip function must be called with -f or --function.' ) return False if not kwargs: kwargs = {} if 'floating_ip' not in kwargs: log.error('A floating IP is required.') return False result = query(method='floating_ips', command=kwargs['floating_ip'] + '/actions', args={'type': 'unassign'}, http_method='post') return result def _list_nodes(full=False, for_output=False): ''' Helper function to format and parse node data. ''' fetch = True page = 1 ret = {} while fetch: items = query(method='droplets', command='?page=' + six.text_type(page) + '&per_page=200') for node in items['droplets']: name = node['name'] ret[name] = {} if full: ret[name] = _get_full_output(node, for_output=for_output) else: public_ips, private_ips = _get_ips(node['networks']) ret[name] = { 'id': node['id'], 'image': node['image']['name'], 'name': name, 'private_ips': private_ips, 'public_ips': public_ips, 'size': node['size_slug'], 'state': six.text_type(node['status']), } page += 1 try: fetch = 'next' in items['links']['pages'] except KeyError: fetch = False return ret def reboot(name, call=None): ''' Reboot a droplet in DigitalOcean. .. versionadded:: 2015.8.8 name The name of the droplet to restart. CLI Example: .. code-block:: bash salt-cloud -a reboot droplet_name ''' if call != 'action': raise SaltCloudSystemExit( 'The restart action must be called with -a or --action.' ) data = show_instance(name, call='action') if data.get('status') == 'off': return {'success': True, 'action': 'stop', 'status': 'off', 'msg': 'Machine is already off.'} ret = query(droplet_id=data['id'], command='actions', args={'type': 'reboot'}, http_method='post') return {'success': True, 'action': ret['action']['type'], 'state': ret['action']['status']} def start(name, call=None): ''' Start a droplet in DigitalOcean. .. versionadded:: 2015.8.8 name The name of the droplet to start. CLI Example: .. code-block:: bash salt-cloud -a start droplet_name ''' if call != 'action': raise SaltCloudSystemExit( 'The start action must be called with -a or --action.' ) data = show_instance(name, call='action') if data.get('status') == 'active': return {'success': True, 'action': 'start', 'status': 'active', 'msg': 'Machine is already running.'} ret = query(droplet_id=data['id'], command='actions', args={'type': 'power_on'}, http_method='post') return {'success': True, 'action': ret['action']['type'], 'state': ret['action']['status']} def stop(name, call=None): ''' Stop a droplet in DigitalOcean. .. versionadded:: 2015.8.8 name The name of the droplet to stop. CLI Example: .. code-block:: bash salt-cloud -a stop droplet_name ''' if call != 'action': raise SaltCloudSystemExit( 'The stop action must be called with -a or --action.' ) data = show_instance(name, call='action') if data.get('status') == 'off': return {'success': True, 'action': 'stop', 'status': 'off', 'msg': 'Machine is already off.'} ret = query(droplet_id=data['id'], command='actions', args={'type': 'shutdown'}, http_method='post') return {'success': True, 'action': ret['action']['type'], 'state': ret['action']['status']} def _get_full_output(node, for_output=False): ''' Helper function for _list_nodes to loop through all node information. Returns a dictionary containing the full information of a node. ''' ret = {} for item in six.iterkeys(node): value = node[item] if value is not None and for_output: value = six.text_type(value) ret[item] = value return ret def _get_ips(networks): ''' Helper function for list_nodes. Returns public and private ip lists based on a given network dictionary. ''' v4s = networks.get('v4') v6s = networks.get('v6') public_ips = [] private_ips = [] if v4s: for item in v4s: ip_type = item.get('type') ip_address = item.get('ip_address') if ip_type == 'public': public_ips.append(ip_address) if ip_type == 'private': private_ips.append(ip_address) if v6s: for item in v6s: ip_type = item.get('type') ip_address = item.get('ip_address') if ip_type == 'public': public_ips.append(ip_address) if ip_type == 'private': private_ips.append(ip_address) return public_ips, private_ips
saltstack/salt
salt/cloud/clouds/digitalocean.py
list_keypairs
python
def list_keypairs(call=None): ''' Return a dict of all available VM locations on the cloud provider with relevant data ''' if call != 'function': log.error( 'The list_keypairs function must be called with -f or --function.' ) return False fetch = True page = 1 ret = {} while fetch: items = query(method='account/keys', command='?page=' + six.text_type(page) + '&per_page=100') for key_pair in items['ssh_keys']: name = key_pair['name'] if name in ret: raise SaltCloudSystemExit( 'A duplicate key pair name, \'{0}\', was found in DigitalOcean\'s ' 'key pair list. Please change the key name stored by DigitalOcean. ' 'Be sure to adjust the value of \'ssh_key_file\' in your cloud ' 'profile or provider configuration, if necessary.'.format( name ) ) ret[name] = {} for item in six.iterkeys(key_pair): ret[name][item] = six.text_type(key_pair[item]) page += 1 try: fetch = 'next' in items['links']['pages'] except KeyError: fetch = False return ret
Return a dict of all available VM locations on the cloud provider with relevant data
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/digitalocean.py#L651-L691
[ "def iterkeys(d, **kw):\n return d.iterkeys(**kw)\n", "def query(method='droplets', droplet_id=None, command=None, args=None, http_method='get'):\n '''\n Make a web call to DigitalOcean\n '''\n base_path = six.text_type(config.get_cloud_config_value(\n 'api_root',\n get_configured_provider(),\n __opts__,\n search_global=False,\n default='https://api.digitalocean.com/v2'\n ))\n\n path = '{0}/{1}/'.format(base_path, method)\n\n if droplet_id:\n path += '{0}/'.format(droplet_id)\n\n if command:\n path += command\n\n if not isinstance(args, dict):\n args = {}\n\n personal_access_token = config.get_cloud_config_value(\n 'personal_access_token', get_configured_provider(), __opts__, search_global=False\n )\n\n data = salt.utils.json.dumps(args)\n\n requester = getattr(requests, http_method)\n request = requester(path, data=data, headers={'Authorization': 'Bearer ' + personal_access_token, 'Content-Type': 'application/json'})\n if request.status_code > 299:\n raise SaltCloudSystemExit(\n 'An error occurred while querying DigitalOcean. HTTP Code: {0} '\n 'Error: \\'{1}\\''.format(\n request.status_code,\n # request.read()\n request.text\n )\n )\n\n log.debug(request.url)\n\n # success without data\n if request.status_code == 204:\n return True\n\n content = request.text\n\n result = salt.utils.json.loads(content)\n if result.get('status', '').lower() == 'error':\n raise SaltCloudSystemExit(\n pprint.pformat(result.get('error_message', {}))\n )\n\n return result\n" ]
# -*- coding: utf-8 -*- ''' DigitalOcean Cloud Module ========================= The DigitalOcean cloud module is used to control access to the DigitalOcean VPS system. Use of this module requires a requires a ``personal_access_token``, an ``ssh_key_file``, and at least one SSH key name in ``ssh_key_names``. More ``ssh_key_names`` can be added by separating each key with a comma. The ``personal_access_token`` can be found in the DigitalOcean web interface in the "Apps & API" section. The SSH key name can be found under the "SSH Keys" section. .. code-block:: yaml # Note: This example is for /etc/salt/cloud.providers or any file in the # /etc/salt/cloud.providers.d/ directory. my-digital-ocean-config: personal_access_token: xxx ssh_key_file: /path/to/ssh/key/file ssh_key_names: my-key-name,my-key-name-2 driver: digitalocean :depends: requests ''' # Import Python Libs from __future__ import absolute_import, print_function, unicode_literals import decimal import logging import os import pprint import time # Import Salt Libs import salt.utils.cloud import salt.utils.files import salt.utils.json import salt.utils.stringutils import salt.config as config from salt.exceptions import ( SaltCloudConfigError, SaltInvocationError, SaltCloudNotFound, SaltCloudSystemExit, SaltCloudExecutionFailure, SaltCloudExecutionTimeout ) from salt.ext import six from salt.ext.six.moves import zip # Import Third Party Libs try: import requests HAS_REQUESTS = True except ImportError: HAS_REQUESTS = False # Get logging started log = logging.getLogger(__name__) __virtualname__ = 'digitalocean' __virtual_aliases__ = ('digital_ocean', 'do') # Only load in this module if the DIGITALOCEAN configurations are in place def __virtual__(): ''' Check for DigitalOcean 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=__opts__, provider=__active_provider_name__ or __virtualname__, aliases=__virtual_aliases__, required_keys=('personal_access_token',) ) def get_dependencies(): ''' Warn if dependencies aren't met. ''' return config.check_driver_dependencies( __virtualname__, {'requests': HAS_REQUESTS} ) def avail_locations(call=None): ''' Return a dict of all available VM locations on the cloud provider with relevant data ''' if call == 'action': raise SaltCloudSystemExit( 'The avail_locations function must be called with ' '-f or --function, or with the --list-locations option' ) items = query(method='regions') ret = {} for region in items['regions']: ret[region['name']] = {} for item in six.iterkeys(region): ret[region['name']][item] = six.text_type(region[item]) return ret def avail_images(call=None): ''' Return a list of the images that are on the provider ''' if call == 'action': raise SaltCloudSystemExit( 'The avail_images function must be called with ' '-f or --function, or with the --list-images option' ) fetch = True page = 1 ret = {} while fetch: items = query(method='images', command='?page=' + six.text_type(page) + '&per_page=200') for image in items['images']: ret[image['name']] = {} for item in six.iterkeys(image): ret[image['name']][item] = image[item] page += 1 try: fetch = 'next' in items['links']['pages'] except KeyError: fetch = False return ret def avail_sizes(call=None): ''' Return a list of the image sizes that are on the provider ''' if call == 'action': raise SaltCloudSystemExit( 'The avail_sizes function must be called with ' '-f or --function, or with the --list-sizes option' ) items = query(method='sizes', command='?per_page=100') ret = {} for size in items['sizes']: ret[size['slug']] = {} for item in six.iterkeys(size): ret[size['slug']][item] = six.text_type(size[item]) 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.' ) return _list_nodes() def list_nodes_full(call=None, for_output=True): ''' 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.' ) return _list_nodes(full=True, for_output=for_output) 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('function'), __opts__['query.selection'], call, ) def get_image(vm_): ''' Return the image object to use ''' images = avail_images() vm_image = config.get_cloud_config_value( 'image', vm_, __opts__, search_global=False ) if not isinstance(vm_image, six.string_types): vm_image = six.text_type(vm_image) for image in images: if vm_image in (images[image]['name'], images[image]['slug'], images[image]['id']): if images[image]['slug'] is not None: return images[image]['slug'] return int(images[image]['id']) raise SaltCloudNotFound( 'The specified image, \'{0}\', could not be found.'.format(vm_image) ) def get_size(vm_): ''' Return the VM's size. Used by create_node(). ''' sizes = avail_sizes() vm_size = six.text_type(config.get_cloud_config_value( 'size', vm_, __opts__, search_global=False )) for size in sizes: if vm_size.lower() == sizes[size]['slug']: return sizes[size]['slug'] raise SaltCloudNotFound( 'The specified size, \'{0}\', could not be found.'.format(vm_size) ) def get_location(vm_): ''' Return the VM's location ''' locations = avail_locations() vm_location = six.text_type(config.get_cloud_config_value( 'location', vm_, __opts__, search_global=False )) for location in locations: if vm_location in (locations[location]['name'], locations[location]['slug']): return locations[location]['slug'] raise SaltCloudNotFound( 'The specified location, \'{0}\', could not be found.'.format( vm_location ) ) def create_node(args): ''' Create a node ''' node = query(method='droplets', args=args, http_method='post') return node 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 'digitalocean', vm_['profile'], vm_=vm_) is False: return False except AttributeError: pass __utils__['cloud.fire_event']( 'event', 'starting create', 'salt/cloud/{0}/creating'.format(vm_['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', vm_['name']) kwargs = { 'name': vm_['name'], 'size': get_size(vm_), 'image': get_image(vm_), 'region': get_location(vm_), 'ssh_keys': [], 'tags': [] } # backwards compat ssh_key_name = config.get_cloud_config_value( 'ssh_key_name', vm_, __opts__, search_global=False ) if ssh_key_name: kwargs['ssh_keys'].append(get_keyid(ssh_key_name)) ssh_key_names = config.get_cloud_config_value( 'ssh_key_names', vm_, __opts__, search_global=False, default=False ) if ssh_key_names: for key in ssh_key_names.split(','): kwargs['ssh_keys'].append(get_keyid(key)) key_filename = config.get_cloud_config_value( 'ssh_key_file', vm_, __opts__, search_global=False, default=None ) if key_filename is not None and not os.path.isfile(key_filename): raise SaltCloudConfigError( 'The defined key_filename \'{0}\' does not exist'.format( key_filename ) ) if not __opts__.get('ssh_agent', False) and key_filename is None: raise SaltCloudConfigError( 'The DigitalOcean driver requires an ssh_key_file and an ssh_key_name ' 'because it does not supply a root password upon building the server.' ) ssh_interface = config.get_cloud_config_value( 'ssh_interface', vm_, __opts__, search_global=False, default='public' ) if ssh_interface in ['private', 'public']: log.info("ssh_interface: Setting interface for ssh to %s", ssh_interface) kwargs['ssh_interface'] = ssh_interface else: raise SaltCloudConfigError( "The DigitalOcean driver requires ssh_interface to be defined as 'public' or 'private'." ) private_networking = config.get_cloud_config_value( 'private_networking', vm_, __opts__, search_global=False, default=None, ) if private_networking is not None: if not isinstance(private_networking, bool): raise SaltCloudConfigError("'private_networking' should be a boolean value.") kwargs['private_networking'] = private_networking if not private_networking and ssh_interface == 'private': raise SaltCloudConfigError( "The DigitalOcean driver requires ssh_interface if defined as 'private' " "then private_networking should be set as 'True'." ) backups_enabled = config.get_cloud_config_value( 'backups_enabled', vm_, __opts__, search_global=False, default=None, ) if backups_enabled is not None: if not isinstance(backups_enabled, bool): raise SaltCloudConfigError("'backups_enabled' should be a boolean value.") kwargs['backups'] = backups_enabled ipv6 = config.get_cloud_config_value( 'ipv6', vm_, __opts__, search_global=False, default=None, ) if ipv6 is not None: if not isinstance(ipv6, bool): raise SaltCloudConfigError("'ipv6' should be a boolean value.") kwargs['ipv6'] = ipv6 monitoring = config.get_cloud_config_value( 'monitoring', vm_, __opts__, search_global=False, default=None, ) if monitoring is not None: if not isinstance(monitoring, bool): raise SaltCloudConfigError("'monitoring' should be a boolean value.") kwargs['monitoring'] = monitoring kwargs['tags'] = config.get_cloud_config_value( 'tags', vm_, __opts__, search_global=False, default=False ) userdata_file = config.get_cloud_config_value( 'userdata_file', vm_, __opts__, search_global=False, default=None ) if userdata_file is not None: try: with salt.utils.files.fopen(userdata_file, 'r') as fp_: kwargs['user_data'] = salt.utils.cloud.userdata_template( __opts__, vm_, salt.utils.stringutils.to_unicode(fp_.read()) ) except Exception as exc: log.exception( 'Failed to read userdata from %s: %s', userdata_file, exc) create_dns_record = config.get_cloud_config_value( 'create_dns_record', vm_, __opts__, search_global=False, default=None, ) if create_dns_record: log.info('create_dns_record: will attempt to write DNS records') default_dns_domain = None dns_domain_name = vm_['name'].split('.') if len(dns_domain_name) > 2: log.debug('create_dns_record: inferring default dns_hostname, dns_domain from minion name as FQDN') default_dns_hostname = '.'.join(dns_domain_name[:-2]) default_dns_domain = '.'.join(dns_domain_name[-2:]) else: log.debug("create_dns_record: can't infer dns_domain from %s", vm_['name']) default_dns_hostname = dns_domain_name[0] dns_hostname = config.get_cloud_config_value( 'dns_hostname', vm_, __opts__, search_global=False, default=default_dns_hostname, ) dns_domain = config.get_cloud_config_value( 'dns_domain', vm_, __opts__, search_global=False, default=default_dns_domain, ) if dns_hostname and dns_domain: log.info('create_dns_record: using dns_hostname="%s", dns_domain="%s"', dns_hostname, dns_domain) __add_dns_addr__ = lambda t, d: post_dns_record(dns_domain=dns_domain, name=dns_hostname, record_type=t, record_data=d) log.debug('create_dns_record: %s', __add_dns_addr__) else: log.error('create_dns_record: could not determine dns_hostname and/or dns_domain') raise SaltCloudConfigError( '\'create_dns_record\' must be a dict specifying "domain" ' 'and "hostname" or the minion name must be an FQDN.' ) __utils__['cloud.fire_event']( 'event', 'requesting instance', 'salt/cloud/{0}/requesting'.format(vm_['name']), args=__utils__['cloud.filter_event']('requesting', kwargs, list(kwargs)), sock_dir=__opts__['sock_dir'], transport=__opts__['transport'] ) try: ret = create_node(kwargs) except Exception as exc: log.error( 'Error creating %s on DIGITALOCEAN\n\n' 'The following exception was thrown when trying to ' 'run the initial deployment: %s', vm_['name'], exc, # Show the traceback if the debug logging level is enabled exc_info_on_loglevel=logging.DEBUG ) return False def __query_node_data(vm_name): data = show_instance(vm_name, 'action') if not data: # Trigger an error in the wait_for_ip function return False if data['networks'].get('v4'): for network in data['networks']['v4']: if network['type'] == 'public': return data return False try: data = salt.utils.cloud.wait_for_ip( __query_node_data, update_args=(vm_['name'],), timeout=config.get_cloud_config_value( 'wait_for_ip_timeout', vm_, __opts__, default=10 * 60), interval=config.get_cloud_config_value( 'wait_for_ip_interval', vm_, __opts__, default=10), ) except (SaltCloudExecutionTimeout, SaltCloudExecutionFailure) as exc: try: # It might be already up, let's destroy it! destroy(vm_['name']) except SaltCloudSystemExit: pass finally: raise SaltCloudSystemExit(six.text_type(exc)) if not vm_.get('ssh_host'): vm_['ssh_host'] = None # add DNS records, set ssh_host, default to first found IP, preferring IPv4 for ssh bootstrap script target addr_families, dns_arec_types = (('v4', 'v6'), ('A', 'AAAA')) arec_map = dict(list(zip(addr_families, dns_arec_types))) for facing, addr_family, ip_address in [(net['type'], family, net['ip_address']) for family in addr_families for net in data['networks'][family]]: log.info('found %s IP%s interface for "%s"', facing, addr_family, ip_address) dns_rec_type = arec_map[addr_family] if facing == 'public': if create_dns_record: __add_dns_addr__(dns_rec_type, ip_address) if facing == ssh_interface: if not vm_['ssh_host']: vm_['ssh_host'] = ip_address if vm_['ssh_host'] is None: raise SaltCloudSystemExit( 'No suitable IP addresses found for ssh minion bootstrapping: {0}'.format(repr(data['networks'])) ) log.debug( 'Found public IP address to use for ssh minion bootstrapping: %s', vm_['ssh_host'] ) vm_['key_filename'] = key_filename ret = __utils__['cloud.bootstrap'](vm_, __opts__) ret.update(data) log.info('Created Cloud VM \'%s\'', vm_['name']) log.debug( '\'%s\' VM creation details:\n%s', vm_['name'], pprint.pformat(data) ) __utils__['cloud.fire_event']( 'event', 'created instance', 'salt/cloud/{0}/created'.format(vm_['name']), args=__utils__['cloud.filter_event']('created', vm_, ['name', 'profile', 'provider', 'driver']), sock_dir=__opts__['sock_dir'], transport=__opts__['transport'] ) return ret def query(method='droplets', droplet_id=None, command=None, args=None, http_method='get'): ''' Make a web call to DigitalOcean ''' base_path = six.text_type(config.get_cloud_config_value( 'api_root', get_configured_provider(), __opts__, search_global=False, default='https://api.digitalocean.com/v2' )) path = '{0}/{1}/'.format(base_path, method) if droplet_id: path += '{0}/'.format(droplet_id) if command: path += command if not isinstance(args, dict): args = {} personal_access_token = config.get_cloud_config_value( 'personal_access_token', get_configured_provider(), __opts__, search_global=False ) data = salt.utils.json.dumps(args) requester = getattr(requests, http_method) request = requester(path, data=data, headers={'Authorization': 'Bearer ' + personal_access_token, 'Content-Type': 'application/json'}) if request.status_code > 299: raise SaltCloudSystemExit( 'An error occurred while querying DigitalOcean. HTTP Code: {0} ' 'Error: \'{1}\''.format( request.status_code, # request.read() request.text ) ) log.debug(request.url) # success without data if request.status_code == 204: return True content = request.text result = salt.utils.json.loads(content) if result.get('status', '').lower() == 'error': raise SaltCloudSystemExit( pprint.pformat(result.get('error_message', {})) ) return result 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 show_instance(name, call=None): ''' Show the details from DigitalOcean concerning a droplet ''' if call != 'action': raise SaltCloudSystemExit( 'The show_instance action must be called with -a or --action.' ) node = _get_node(name) __utils__['cloud.cache_node'](node, __active_provider_name__, __opts__) return node def _get_node(name): attempts = 10 while attempts >= 0: try: return list_nodes_full(for_output=False)[name] except KeyError: attempts -= 1 log.debug( 'Failed to get the data for node \'%s\'. Remaining ' 'attempts: %s', name, attempts ) # Just a little delay between attempts... time.sleep(0.5) return {} def show_keypair(kwargs=None, call=None): ''' Show the details of an SSH keypair ''' if call != 'function': log.error( 'The show_keypair function must be called with -f or --function.' ) return False if not kwargs: kwargs = {} if 'keyname' not in kwargs: log.error('A keyname is required.') return False keypairs = list_keypairs(call='function') keyid = keypairs[kwargs['keyname']]['id'] log.debug('Key ID is %s', keyid) details = query(method='account/keys', command=keyid) return details def import_keypair(kwargs=None, call=None): ''' Upload public key to cloud provider. Similar to EC2 import_keypair. .. versionadded:: 2016.11.0 kwargs file(mandatory): public key file-name keyname(mandatory): public key name in the provider ''' with salt.utils.files.fopen(kwargs['file'], 'r') as public_key_filename: public_key_content = salt.utils.stringutils.to_unicode(public_key_filename.read()) digitalocean_kwargs = { 'name': kwargs['keyname'], 'public_key': public_key_content } created_result = create_key(digitalocean_kwargs, call=call) return created_result def create_key(kwargs=None, call=None): ''' Upload a public key ''' if call != 'function': log.error( 'The create_key function must be called with -f or --function.' ) return False try: result = query( method='account', command='keys', args={'name': kwargs['name'], 'public_key': kwargs['public_key']}, http_method='post' ) except KeyError: log.info('`name` and `public_key` arguments must be specified') return False return result def remove_key(kwargs=None, call=None): ''' Delete public key ''' if call != 'function': log.error( 'The create_key function must be called with -f or --function.' ) return False try: result = query( method='account', command='keys/' + kwargs['id'], http_method='delete' ) except KeyError: log.info('`id` argument must be specified') return False return result def get_keyid(keyname): ''' Return the ID of the keyname ''' if not keyname: return None keypairs = list_keypairs(call='function') keyid = keypairs[keyname]['id'] if keyid: return keyid raise SaltCloudNotFound('The specified ssh key could not be found.') def destroy(name, call=None): ''' Destroy a node. Will check termination protection and warn if enabled. 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'] ) data = show_instance(name, call='action') node = query(method='droplets', droplet_id=data['id'], http_method='delete') ## This is all terribly optomistic: # vm_ = get_vm_config(name=name) # delete_dns_record = config.get_cloud_config_value( # 'delete_dns_record', vm_, __opts__, search_global=False, default=None, # ) # TODO: when _vm config data can be made available, we should honor the configuration settings, # but until then, we should assume stale DNS records are bad, and default behavior should be to # delete them if we can. When this is resolved, also resolve the comments a couple of lines below. delete_dns_record = True if not isinstance(delete_dns_record, bool): raise SaltCloudConfigError( '\'delete_dns_record\' should be a boolean value.' ) # When the "to do" a few lines up is resolved, remove these lines and use the if/else logic below. log.debug('Deleting DNS records for %s.', name) destroy_dns_records(name) # Until the "to do" from line 754 is taken care of, we don't need this logic. # if delete_dns_record: # log.debug('Deleting DNS records for %s.', name) # destroy_dns_records(name) # else: # log.debug('delete_dns_record : %s', delete_dns_record) # for line in pprint.pformat(dir()).splitlines(): # log.debug('delete context: %s', line) __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 node def post_dns_record(**kwargs): ''' Creates a DNS record for the given name if the domain is managed with DO. ''' if 'kwargs' in kwargs: # flatten kwargs if called via salt-cloud -f f_kwargs = kwargs['kwargs'] del kwargs['kwargs'] kwargs.update(f_kwargs) mandatory_kwargs = ('dns_domain', 'name', 'record_type', 'record_data') for i in mandatory_kwargs: if kwargs[i]: pass else: error = '{0}="{1}" ## all mandatory args must be provided: {2}'.format(i, kwargs[i], mandatory_kwargs) raise SaltInvocationError(error) domain = query(method='domains', droplet_id=kwargs['dns_domain']) if domain: result = query( method='domains', droplet_id=kwargs['dns_domain'], command='records', args={'type': kwargs['record_type'], 'name': kwargs['name'], 'data': kwargs['record_data']}, http_method='post' ) return result return False def destroy_dns_records(fqdn): ''' Deletes DNS records for the given hostname if the domain is managed with DO. ''' domain = '.'.join(fqdn.split('.')[-2:]) hostname = '.'.join(fqdn.split('.')[:-2]) # TODO: remove this when the todo on 754 is available try: response = query(method='domains', droplet_id=domain, command='records') except SaltCloudSystemExit: log.debug('Failed to find domains.') return False log.debug("found DNS records: %s", pprint.pformat(response)) records = response['domain_records'] if records: record_ids = [r['id'] for r in records if r['name'].decode() == hostname] log.debug("deleting DNS record IDs: %s", record_ids) for id_ in record_ids: try: log.info('deleting DNS record %s', id_) ret = query( method='domains', droplet_id=domain, command='records/{0}'.format(id_), http_method='delete' ) except SaltCloudSystemExit: log.error('failed to delete DNS domain %s record ID %s.', domain, hostname) log.debug('DNS deletion REST call returned: %s', pprint.pformat(ret)) return False def show_pricing(kwargs=None, call=None): ''' Show pricing for a particular profile. This is only an estimate, based on unofficial pricing sources. .. versionadded:: 2015.8.0 CLI Examples: .. code-block:: bash salt-cloud -f show_pricing my-digitalocean-config profile=my-profile ''' profile = __opts__['profiles'].get(kwargs['profile'], {}) if not profile: return {'Error': 'The requested profile was not found'} # Make sure the profile belongs to DigitalOcean provider = profile.get('provider', '0:0') comps = provider.split(':') if len(comps) < 2 or comps[1] != 'digitalocean': return {'Error': 'The requested profile does not belong to DigitalOcean'} raw = {} ret = {} sizes = avail_sizes() ret['per_hour'] = decimal.Decimal(sizes[profile['size']]['price_hourly']) ret['per_day'] = ret['per_hour'] * 24 ret['per_week'] = ret['per_day'] * 7 ret['per_month'] = decimal.Decimal(sizes[profile['size']]['price_monthly']) ret['per_year'] = ret['per_week'] * 52 if kwargs.get('raw', False): ret['_raw'] = raw return {profile['profile']: ret} def list_floating_ips(call=None): ''' Return a list of the floating ips that are on the provider .. versionadded:: 2016.3.0 CLI Examples: .. code-block:: bash salt-cloud -f list_floating_ips my-digitalocean-config ''' if call == 'action': raise SaltCloudSystemExit( 'The list_floating_ips function must be called with ' '-f or --function, or with the --list-floating-ips option' ) fetch = True page = 1 ret = {} while fetch: items = query(method='floating_ips', command='?page=' + six.text_type(page) + '&per_page=200') for floating_ip in items['floating_ips']: ret[floating_ip['ip']] = {} for item in six.iterkeys(floating_ip): ret[floating_ip['ip']][item] = floating_ip[item] page += 1 try: fetch = 'next' in items['links']['pages'] except KeyError: fetch = False return ret def show_floating_ip(kwargs=None, call=None): ''' Show the details of a floating IP .. versionadded:: 2016.3.0 CLI Examples: .. code-block:: bash salt-cloud -f show_floating_ip my-digitalocean-config floating_ip='45.55.96.47' ''' if call != 'function': log.error( 'The show_floating_ip function must be called with -f or --function.' ) return False if not kwargs: kwargs = {} if 'floating_ip' not in kwargs: log.error('A floating IP is required.') return False floating_ip = kwargs['floating_ip'] log.debug('Floating ip is %s', floating_ip) details = query(method='floating_ips', command=floating_ip) return details def create_floating_ip(kwargs=None, call=None): ''' Create a new floating IP .. versionadded:: 2016.3.0 CLI Examples: .. code-block:: bash salt-cloud -f create_floating_ip my-digitalocean-config region='NYC2' salt-cloud -f create_floating_ip my-digitalocean-config droplet_id='1234567' ''' if call != 'function': log.error( 'The create_floating_ip function must be called with -f or --function.' ) return False if not kwargs: kwargs = {} if 'droplet_id' in kwargs: result = query(method='floating_ips', args={'droplet_id': kwargs['droplet_id']}, http_method='post') return result elif 'region' in kwargs: result = query(method='floating_ips', args={'region': kwargs['region']}, http_method='post') return result else: log.error('A droplet_id or region is required.') return False def delete_floating_ip(kwargs=None, call=None): ''' Delete a floating IP .. versionadded:: 2016.3.0 CLI Examples: .. code-block:: bash salt-cloud -f delete_floating_ip my-digitalocean-config floating_ip='45.55.96.47' ''' if call != 'function': log.error( 'The delete_floating_ip function must be called with -f or --function.' ) return False if not kwargs: kwargs = {} if 'floating_ip' not in kwargs: log.error('A floating IP is required.') return False floating_ip = kwargs['floating_ip'] log.debug('Floating ip is %s', kwargs['floating_ip']) result = query(method='floating_ips', command=floating_ip, http_method='delete') return result def assign_floating_ip(kwargs=None, call=None): ''' Assign a floating IP .. versionadded:: 2016.3.0 CLI Examples: .. code-block:: bash salt-cloud -f assign_floating_ip my-digitalocean-config droplet_id=1234567 floating_ip='45.55.96.47' ''' if call != 'function': log.error( 'The assign_floating_ip function must be called with -f or --function.' ) return False if not kwargs: kwargs = {} if 'floating_ip' and 'droplet_id' not in kwargs: log.error('A floating IP and droplet_id is required.') return False result = query(method='floating_ips', command=kwargs['floating_ip'] + '/actions', args={'droplet_id': kwargs['droplet_id'], 'type': 'assign'}, http_method='post') return result def unassign_floating_ip(kwargs=None, call=None): ''' Unassign a floating IP .. versionadded:: 2016.3.0 CLI Examples: .. code-block:: bash salt-cloud -f unassign_floating_ip my-digitalocean-config floating_ip='45.55.96.47' ''' if call != 'function': log.error( 'The inassign_floating_ip function must be called with -f or --function.' ) return False if not kwargs: kwargs = {} if 'floating_ip' not in kwargs: log.error('A floating IP is required.') return False result = query(method='floating_ips', command=kwargs['floating_ip'] + '/actions', args={'type': 'unassign'}, http_method='post') return result def _list_nodes(full=False, for_output=False): ''' Helper function to format and parse node data. ''' fetch = True page = 1 ret = {} while fetch: items = query(method='droplets', command='?page=' + six.text_type(page) + '&per_page=200') for node in items['droplets']: name = node['name'] ret[name] = {} if full: ret[name] = _get_full_output(node, for_output=for_output) else: public_ips, private_ips = _get_ips(node['networks']) ret[name] = { 'id': node['id'], 'image': node['image']['name'], 'name': name, 'private_ips': private_ips, 'public_ips': public_ips, 'size': node['size_slug'], 'state': six.text_type(node['status']), } page += 1 try: fetch = 'next' in items['links']['pages'] except KeyError: fetch = False return ret def reboot(name, call=None): ''' Reboot a droplet in DigitalOcean. .. versionadded:: 2015.8.8 name The name of the droplet to restart. CLI Example: .. code-block:: bash salt-cloud -a reboot droplet_name ''' if call != 'action': raise SaltCloudSystemExit( 'The restart action must be called with -a or --action.' ) data = show_instance(name, call='action') if data.get('status') == 'off': return {'success': True, 'action': 'stop', 'status': 'off', 'msg': 'Machine is already off.'} ret = query(droplet_id=data['id'], command='actions', args={'type': 'reboot'}, http_method='post') return {'success': True, 'action': ret['action']['type'], 'state': ret['action']['status']} def start(name, call=None): ''' Start a droplet in DigitalOcean. .. versionadded:: 2015.8.8 name The name of the droplet to start. CLI Example: .. code-block:: bash salt-cloud -a start droplet_name ''' if call != 'action': raise SaltCloudSystemExit( 'The start action must be called with -a or --action.' ) data = show_instance(name, call='action') if data.get('status') == 'active': return {'success': True, 'action': 'start', 'status': 'active', 'msg': 'Machine is already running.'} ret = query(droplet_id=data['id'], command='actions', args={'type': 'power_on'}, http_method='post') return {'success': True, 'action': ret['action']['type'], 'state': ret['action']['status']} def stop(name, call=None): ''' Stop a droplet in DigitalOcean. .. versionadded:: 2015.8.8 name The name of the droplet to stop. CLI Example: .. code-block:: bash salt-cloud -a stop droplet_name ''' if call != 'action': raise SaltCloudSystemExit( 'The stop action must be called with -a or --action.' ) data = show_instance(name, call='action') if data.get('status') == 'off': return {'success': True, 'action': 'stop', 'status': 'off', 'msg': 'Machine is already off.'} ret = query(droplet_id=data['id'], command='actions', args={'type': 'shutdown'}, http_method='post') return {'success': True, 'action': ret['action']['type'], 'state': ret['action']['status']} def _get_full_output(node, for_output=False): ''' Helper function for _list_nodes to loop through all node information. Returns a dictionary containing the full information of a node. ''' ret = {} for item in six.iterkeys(node): value = node[item] if value is not None and for_output: value = six.text_type(value) ret[item] = value return ret def _get_ips(networks): ''' Helper function for list_nodes. Returns public and private ip lists based on a given network dictionary. ''' v4s = networks.get('v4') v6s = networks.get('v6') public_ips = [] private_ips = [] if v4s: for item in v4s: ip_type = item.get('type') ip_address = item.get('ip_address') if ip_type == 'public': public_ips.append(ip_address) if ip_type == 'private': private_ips.append(ip_address) if v6s: for item in v6s: ip_type = item.get('type') ip_address = item.get('ip_address') if ip_type == 'public': public_ips.append(ip_address) if ip_type == 'private': private_ips.append(ip_address) return public_ips, private_ips
saltstack/salt
salt/cloud/clouds/digitalocean.py
show_keypair
python
def show_keypair(kwargs=None, call=None): ''' Show the details of an SSH keypair ''' if call != 'function': log.error( 'The show_keypair function must be called with -f or --function.' ) return False if not kwargs: kwargs = {} if 'keyname' not in kwargs: log.error('A keyname is required.') return False keypairs = list_keypairs(call='function') keyid = keypairs[kwargs['keyname']]['id'] log.debug('Key ID is %s', keyid) details = query(method='account/keys', command=keyid) return details
Show the details of an SSH keypair
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/digitalocean.py#L694-L717
[ "def query(method='droplets', droplet_id=None, command=None, args=None, http_method='get'):\n '''\n Make a web call to DigitalOcean\n '''\n base_path = six.text_type(config.get_cloud_config_value(\n 'api_root',\n get_configured_provider(),\n __opts__,\n search_global=False,\n default='https://api.digitalocean.com/v2'\n ))\n\n path = '{0}/{1}/'.format(base_path, method)\n\n if droplet_id:\n path += '{0}/'.format(droplet_id)\n\n if command:\n path += command\n\n if not isinstance(args, dict):\n args = {}\n\n personal_access_token = config.get_cloud_config_value(\n 'personal_access_token', get_configured_provider(), __opts__, search_global=False\n )\n\n data = salt.utils.json.dumps(args)\n\n requester = getattr(requests, http_method)\n request = requester(path, data=data, headers={'Authorization': 'Bearer ' + personal_access_token, 'Content-Type': 'application/json'})\n if request.status_code > 299:\n raise SaltCloudSystemExit(\n 'An error occurred while querying DigitalOcean. HTTP Code: {0} '\n 'Error: \\'{1}\\''.format(\n request.status_code,\n # request.read()\n request.text\n )\n )\n\n log.debug(request.url)\n\n # success without data\n if request.status_code == 204:\n return True\n\n content = request.text\n\n result = salt.utils.json.loads(content)\n if result.get('status', '').lower() == 'error':\n raise SaltCloudSystemExit(\n pprint.pformat(result.get('error_message', {}))\n )\n\n return result\n", "def list_keypairs(call=None):\n '''\n Return a dict of all available VM locations on the cloud provider with\n relevant data\n '''\n if call != 'function':\n log.error(\n 'The list_keypairs function must be called with -f or --function.'\n )\n return False\n\n fetch = True\n page = 1\n ret = {}\n\n while fetch:\n items = query(method='account/keys', command='?page=' + six.text_type(page) +\n '&per_page=100')\n\n for key_pair in items['ssh_keys']:\n name = key_pair['name']\n if name in ret:\n raise SaltCloudSystemExit(\n 'A duplicate key pair name, \\'{0}\\', was found in DigitalOcean\\'s '\n 'key pair list. Please change the key name stored by DigitalOcean. '\n 'Be sure to adjust the value of \\'ssh_key_file\\' in your cloud '\n 'profile or provider configuration, if necessary.'.format(\n name\n )\n )\n ret[name] = {}\n for item in six.iterkeys(key_pair):\n ret[name][item] = six.text_type(key_pair[item])\n\n page += 1\n try:\n fetch = 'next' in items['links']['pages']\n except KeyError:\n fetch = False\n\n return ret\n" ]
# -*- coding: utf-8 -*- ''' DigitalOcean Cloud Module ========================= The DigitalOcean cloud module is used to control access to the DigitalOcean VPS system. Use of this module requires a requires a ``personal_access_token``, an ``ssh_key_file``, and at least one SSH key name in ``ssh_key_names``. More ``ssh_key_names`` can be added by separating each key with a comma. The ``personal_access_token`` can be found in the DigitalOcean web interface in the "Apps & API" section. The SSH key name can be found under the "SSH Keys" section. .. code-block:: yaml # Note: This example is for /etc/salt/cloud.providers or any file in the # /etc/salt/cloud.providers.d/ directory. my-digital-ocean-config: personal_access_token: xxx ssh_key_file: /path/to/ssh/key/file ssh_key_names: my-key-name,my-key-name-2 driver: digitalocean :depends: requests ''' # Import Python Libs from __future__ import absolute_import, print_function, unicode_literals import decimal import logging import os import pprint import time # Import Salt Libs import salt.utils.cloud import salt.utils.files import salt.utils.json import salt.utils.stringutils import salt.config as config from salt.exceptions import ( SaltCloudConfigError, SaltInvocationError, SaltCloudNotFound, SaltCloudSystemExit, SaltCloudExecutionFailure, SaltCloudExecutionTimeout ) from salt.ext import six from salt.ext.six.moves import zip # Import Third Party Libs try: import requests HAS_REQUESTS = True except ImportError: HAS_REQUESTS = False # Get logging started log = logging.getLogger(__name__) __virtualname__ = 'digitalocean' __virtual_aliases__ = ('digital_ocean', 'do') # Only load in this module if the DIGITALOCEAN configurations are in place def __virtual__(): ''' Check for DigitalOcean 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=__opts__, provider=__active_provider_name__ or __virtualname__, aliases=__virtual_aliases__, required_keys=('personal_access_token',) ) def get_dependencies(): ''' Warn if dependencies aren't met. ''' return config.check_driver_dependencies( __virtualname__, {'requests': HAS_REQUESTS} ) def avail_locations(call=None): ''' Return a dict of all available VM locations on the cloud provider with relevant data ''' if call == 'action': raise SaltCloudSystemExit( 'The avail_locations function must be called with ' '-f or --function, or with the --list-locations option' ) items = query(method='regions') ret = {} for region in items['regions']: ret[region['name']] = {} for item in six.iterkeys(region): ret[region['name']][item] = six.text_type(region[item]) return ret def avail_images(call=None): ''' Return a list of the images that are on the provider ''' if call == 'action': raise SaltCloudSystemExit( 'The avail_images function must be called with ' '-f or --function, or with the --list-images option' ) fetch = True page = 1 ret = {} while fetch: items = query(method='images', command='?page=' + six.text_type(page) + '&per_page=200') for image in items['images']: ret[image['name']] = {} for item in six.iterkeys(image): ret[image['name']][item] = image[item] page += 1 try: fetch = 'next' in items['links']['pages'] except KeyError: fetch = False return ret def avail_sizes(call=None): ''' Return a list of the image sizes that are on the provider ''' if call == 'action': raise SaltCloudSystemExit( 'The avail_sizes function must be called with ' '-f or --function, or with the --list-sizes option' ) items = query(method='sizes', command='?per_page=100') ret = {} for size in items['sizes']: ret[size['slug']] = {} for item in six.iterkeys(size): ret[size['slug']][item] = six.text_type(size[item]) 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.' ) return _list_nodes() def list_nodes_full(call=None, for_output=True): ''' 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.' ) return _list_nodes(full=True, for_output=for_output) 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('function'), __opts__['query.selection'], call, ) def get_image(vm_): ''' Return the image object to use ''' images = avail_images() vm_image = config.get_cloud_config_value( 'image', vm_, __opts__, search_global=False ) if not isinstance(vm_image, six.string_types): vm_image = six.text_type(vm_image) for image in images: if vm_image in (images[image]['name'], images[image]['slug'], images[image]['id']): if images[image]['slug'] is not None: return images[image]['slug'] return int(images[image]['id']) raise SaltCloudNotFound( 'The specified image, \'{0}\', could not be found.'.format(vm_image) ) def get_size(vm_): ''' Return the VM's size. Used by create_node(). ''' sizes = avail_sizes() vm_size = six.text_type(config.get_cloud_config_value( 'size', vm_, __opts__, search_global=False )) for size in sizes: if vm_size.lower() == sizes[size]['slug']: return sizes[size]['slug'] raise SaltCloudNotFound( 'The specified size, \'{0}\', could not be found.'.format(vm_size) ) def get_location(vm_): ''' Return the VM's location ''' locations = avail_locations() vm_location = six.text_type(config.get_cloud_config_value( 'location', vm_, __opts__, search_global=False )) for location in locations: if vm_location in (locations[location]['name'], locations[location]['slug']): return locations[location]['slug'] raise SaltCloudNotFound( 'The specified location, \'{0}\', could not be found.'.format( vm_location ) ) def create_node(args): ''' Create a node ''' node = query(method='droplets', args=args, http_method='post') return node 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 'digitalocean', vm_['profile'], vm_=vm_) is False: return False except AttributeError: pass __utils__['cloud.fire_event']( 'event', 'starting create', 'salt/cloud/{0}/creating'.format(vm_['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', vm_['name']) kwargs = { 'name': vm_['name'], 'size': get_size(vm_), 'image': get_image(vm_), 'region': get_location(vm_), 'ssh_keys': [], 'tags': [] } # backwards compat ssh_key_name = config.get_cloud_config_value( 'ssh_key_name', vm_, __opts__, search_global=False ) if ssh_key_name: kwargs['ssh_keys'].append(get_keyid(ssh_key_name)) ssh_key_names = config.get_cloud_config_value( 'ssh_key_names', vm_, __opts__, search_global=False, default=False ) if ssh_key_names: for key in ssh_key_names.split(','): kwargs['ssh_keys'].append(get_keyid(key)) key_filename = config.get_cloud_config_value( 'ssh_key_file', vm_, __opts__, search_global=False, default=None ) if key_filename is not None and not os.path.isfile(key_filename): raise SaltCloudConfigError( 'The defined key_filename \'{0}\' does not exist'.format( key_filename ) ) if not __opts__.get('ssh_agent', False) and key_filename is None: raise SaltCloudConfigError( 'The DigitalOcean driver requires an ssh_key_file and an ssh_key_name ' 'because it does not supply a root password upon building the server.' ) ssh_interface = config.get_cloud_config_value( 'ssh_interface', vm_, __opts__, search_global=False, default='public' ) if ssh_interface in ['private', 'public']: log.info("ssh_interface: Setting interface for ssh to %s", ssh_interface) kwargs['ssh_interface'] = ssh_interface else: raise SaltCloudConfigError( "The DigitalOcean driver requires ssh_interface to be defined as 'public' or 'private'." ) private_networking = config.get_cloud_config_value( 'private_networking', vm_, __opts__, search_global=False, default=None, ) if private_networking is not None: if not isinstance(private_networking, bool): raise SaltCloudConfigError("'private_networking' should be a boolean value.") kwargs['private_networking'] = private_networking if not private_networking and ssh_interface == 'private': raise SaltCloudConfigError( "The DigitalOcean driver requires ssh_interface if defined as 'private' " "then private_networking should be set as 'True'." ) backups_enabled = config.get_cloud_config_value( 'backups_enabled', vm_, __opts__, search_global=False, default=None, ) if backups_enabled is not None: if not isinstance(backups_enabled, bool): raise SaltCloudConfigError("'backups_enabled' should be a boolean value.") kwargs['backups'] = backups_enabled ipv6 = config.get_cloud_config_value( 'ipv6', vm_, __opts__, search_global=False, default=None, ) if ipv6 is not None: if not isinstance(ipv6, bool): raise SaltCloudConfigError("'ipv6' should be a boolean value.") kwargs['ipv6'] = ipv6 monitoring = config.get_cloud_config_value( 'monitoring', vm_, __opts__, search_global=False, default=None, ) if monitoring is not None: if not isinstance(monitoring, bool): raise SaltCloudConfigError("'monitoring' should be a boolean value.") kwargs['monitoring'] = monitoring kwargs['tags'] = config.get_cloud_config_value( 'tags', vm_, __opts__, search_global=False, default=False ) userdata_file = config.get_cloud_config_value( 'userdata_file', vm_, __opts__, search_global=False, default=None ) if userdata_file is not None: try: with salt.utils.files.fopen(userdata_file, 'r') as fp_: kwargs['user_data'] = salt.utils.cloud.userdata_template( __opts__, vm_, salt.utils.stringutils.to_unicode(fp_.read()) ) except Exception as exc: log.exception( 'Failed to read userdata from %s: %s', userdata_file, exc) create_dns_record = config.get_cloud_config_value( 'create_dns_record', vm_, __opts__, search_global=False, default=None, ) if create_dns_record: log.info('create_dns_record: will attempt to write DNS records') default_dns_domain = None dns_domain_name = vm_['name'].split('.') if len(dns_domain_name) > 2: log.debug('create_dns_record: inferring default dns_hostname, dns_domain from minion name as FQDN') default_dns_hostname = '.'.join(dns_domain_name[:-2]) default_dns_domain = '.'.join(dns_domain_name[-2:]) else: log.debug("create_dns_record: can't infer dns_domain from %s", vm_['name']) default_dns_hostname = dns_domain_name[0] dns_hostname = config.get_cloud_config_value( 'dns_hostname', vm_, __opts__, search_global=False, default=default_dns_hostname, ) dns_domain = config.get_cloud_config_value( 'dns_domain', vm_, __opts__, search_global=False, default=default_dns_domain, ) if dns_hostname and dns_domain: log.info('create_dns_record: using dns_hostname="%s", dns_domain="%s"', dns_hostname, dns_domain) __add_dns_addr__ = lambda t, d: post_dns_record(dns_domain=dns_domain, name=dns_hostname, record_type=t, record_data=d) log.debug('create_dns_record: %s', __add_dns_addr__) else: log.error('create_dns_record: could not determine dns_hostname and/or dns_domain') raise SaltCloudConfigError( '\'create_dns_record\' must be a dict specifying "domain" ' 'and "hostname" or the minion name must be an FQDN.' ) __utils__['cloud.fire_event']( 'event', 'requesting instance', 'salt/cloud/{0}/requesting'.format(vm_['name']), args=__utils__['cloud.filter_event']('requesting', kwargs, list(kwargs)), sock_dir=__opts__['sock_dir'], transport=__opts__['transport'] ) try: ret = create_node(kwargs) except Exception as exc: log.error( 'Error creating %s on DIGITALOCEAN\n\n' 'The following exception was thrown when trying to ' 'run the initial deployment: %s', vm_['name'], exc, # Show the traceback if the debug logging level is enabled exc_info_on_loglevel=logging.DEBUG ) return False def __query_node_data(vm_name): data = show_instance(vm_name, 'action') if not data: # Trigger an error in the wait_for_ip function return False if data['networks'].get('v4'): for network in data['networks']['v4']: if network['type'] == 'public': return data return False try: data = salt.utils.cloud.wait_for_ip( __query_node_data, update_args=(vm_['name'],), timeout=config.get_cloud_config_value( 'wait_for_ip_timeout', vm_, __opts__, default=10 * 60), interval=config.get_cloud_config_value( 'wait_for_ip_interval', vm_, __opts__, default=10), ) except (SaltCloudExecutionTimeout, SaltCloudExecutionFailure) as exc: try: # It might be already up, let's destroy it! destroy(vm_['name']) except SaltCloudSystemExit: pass finally: raise SaltCloudSystemExit(six.text_type(exc)) if not vm_.get('ssh_host'): vm_['ssh_host'] = None # add DNS records, set ssh_host, default to first found IP, preferring IPv4 for ssh bootstrap script target addr_families, dns_arec_types = (('v4', 'v6'), ('A', 'AAAA')) arec_map = dict(list(zip(addr_families, dns_arec_types))) for facing, addr_family, ip_address in [(net['type'], family, net['ip_address']) for family in addr_families for net in data['networks'][family]]: log.info('found %s IP%s interface for "%s"', facing, addr_family, ip_address) dns_rec_type = arec_map[addr_family] if facing == 'public': if create_dns_record: __add_dns_addr__(dns_rec_type, ip_address) if facing == ssh_interface: if not vm_['ssh_host']: vm_['ssh_host'] = ip_address if vm_['ssh_host'] is None: raise SaltCloudSystemExit( 'No suitable IP addresses found for ssh minion bootstrapping: {0}'.format(repr(data['networks'])) ) log.debug( 'Found public IP address to use for ssh minion bootstrapping: %s', vm_['ssh_host'] ) vm_['key_filename'] = key_filename ret = __utils__['cloud.bootstrap'](vm_, __opts__) ret.update(data) log.info('Created Cloud VM \'%s\'', vm_['name']) log.debug( '\'%s\' VM creation details:\n%s', vm_['name'], pprint.pformat(data) ) __utils__['cloud.fire_event']( 'event', 'created instance', 'salt/cloud/{0}/created'.format(vm_['name']), args=__utils__['cloud.filter_event']('created', vm_, ['name', 'profile', 'provider', 'driver']), sock_dir=__opts__['sock_dir'], transport=__opts__['transport'] ) return ret def query(method='droplets', droplet_id=None, command=None, args=None, http_method='get'): ''' Make a web call to DigitalOcean ''' base_path = six.text_type(config.get_cloud_config_value( 'api_root', get_configured_provider(), __opts__, search_global=False, default='https://api.digitalocean.com/v2' )) path = '{0}/{1}/'.format(base_path, method) if droplet_id: path += '{0}/'.format(droplet_id) if command: path += command if not isinstance(args, dict): args = {} personal_access_token = config.get_cloud_config_value( 'personal_access_token', get_configured_provider(), __opts__, search_global=False ) data = salt.utils.json.dumps(args) requester = getattr(requests, http_method) request = requester(path, data=data, headers={'Authorization': 'Bearer ' + personal_access_token, 'Content-Type': 'application/json'}) if request.status_code > 299: raise SaltCloudSystemExit( 'An error occurred while querying DigitalOcean. HTTP Code: {0} ' 'Error: \'{1}\''.format( request.status_code, # request.read() request.text ) ) log.debug(request.url) # success without data if request.status_code == 204: return True content = request.text result = salt.utils.json.loads(content) if result.get('status', '').lower() == 'error': raise SaltCloudSystemExit( pprint.pformat(result.get('error_message', {})) ) return result 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 show_instance(name, call=None): ''' Show the details from DigitalOcean concerning a droplet ''' if call != 'action': raise SaltCloudSystemExit( 'The show_instance action must be called with -a or --action.' ) node = _get_node(name) __utils__['cloud.cache_node'](node, __active_provider_name__, __opts__) return node def _get_node(name): attempts = 10 while attempts >= 0: try: return list_nodes_full(for_output=False)[name] except KeyError: attempts -= 1 log.debug( 'Failed to get the data for node \'%s\'. Remaining ' 'attempts: %s', name, attempts ) # Just a little delay between attempts... time.sleep(0.5) return {} def list_keypairs(call=None): ''' Return a dict of all available VM locations on the cloud provider with relevant data ''' if call != 'function': log.error( 'The list_keypairs function must be called with -f or --function.' ) return False fetch = True page = 1 ret = {} while fetch: items = query(method='account/keys', command='?page=' + six.text_type(page) + '&per_page=100') for key_pair in items['ssh_keys']: name = key_pair['name'] if name in ret: raise SaltCloudSystemExit( 'A duplicate key pair name, \'{0}\', was found in DigitalOcean\'s ' 'key pair list. Please change the key name stored by DigitalOcean. ' 'Be sure to adjust the value of \'ssh_key_file\' in your cloud ' 'profile or provider configuration, if necessary.'.format( name ) ) ret[name] = {} for item in six.iterkeys(key_pair): ret[name][item] = six.text_type(key_pair[item]) page += 1 try: fetch = 'next' in items['links']['pages'] except KeyError: fetch = False return ret def import_keypair(kwargs=None, call=None): ''' Upload public key to cloud provider. Similar to EC2 import_keypair. .. versionadded:: 2016.11.0 kwargs file(mandatory): public key file-name keyname(mandatory): public key name in the provider ''' with salt.utils.files.fopen(kwargs['file'], 'r') as public_key_filename: public_key_content = salt.utils.stringutils.to_unicode(public_key_filename.read()) digitalocean_kwargs = { 'name': kwargs['keyname'], 'public_key': public_key_content } created_result = create_key(digitalocean_kwargs, call=call) return created_result def create_key(kwargs=None, call=None): ''' Upload a public key ''' if call != 'function': log.error( 'The create_key function must be called with -f or --function.' ) return False try: result = query( method='account', command='keys', args={'name': kwargs['name'], 'public_key': kwargs['public_key']}, http_method='post' ) except KeyError: log.info('`name` and `public_key` arguments must be specified') return False return result def remove_key(kwargs=None, call=None): ''' Delete public key ''' if call != 'function': log.error( 'The create_key function must be called with -f or --function.' ) return False try: result = query( method='account', command='keys/' + kwargs['id'], http_method='delete' ) except KeyError: log.info('`id` argument must be specified') return False return result def get_keyid(keyname): ''' Return the ID of the keyname ''' if not keyname: return None keypairs = list_keypairs(call='function') keyid = keypairs[keyname]['id'] if keyid: return keyid raise SaltCloudNotFound('The specified ssh key could not be found.') def destroy(name, call=None): ''' Destroy a node. Will check termination protection and warn if enabled. 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'] ) data = show_instance(name, call='action') node = query(method='droplets', droplet_id=data['id'], http_method='delete') ## This is all terribly optomistic: # vm_ = get_vm_config(name=name) # delete_dns_record = config.get_cloud_config_value( # 'delete_dns_record', vm_, __opts__, search_global=False, default=None, # ) # TODO: when _vm config data can be made available, we should honor the configuration settings, # but until then, we should assume stale DNS records are bad, and default behavior should be to # delete them if we can. When this is resolved, also resolve the comments a couple of lines below. delete_dns_record = True if not isinstance(delete_dns_record, bool): raise SaltCloudConfigError( '\'delete_dns_record\' should be a boolean value.' ) # When the "to do" a few lines up is resolved, remove these lines and use the if/else logic below. log.debug('Deleting DNS records for %s.', name) destroy_dns_records(name) # Until the "to do" from line 754 is taken care of, we don't need this logic. # if delete_dns_record: # log.debug('Deleting DNS records for %s.', name) # destroy_dns_records(name) # else: # log.debug('delete_dns_record : %s', delete_dns_record) # for line in pprint.pformat(dir()).splitlines(): # log.debug('delete context: %s', line) __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 node def post_dns_record(**kwargs): ''' Creates a DNS record for the given name if the domain is managed with DO. ''' if 'kwargs' in kwargs: # flatten kwargs if called via salt-cloud -f f_kwargs = kwargs['kwargs'] del kwargs['kwargs'] kwargs.update(f_kwargs) mandatory_kwargs = ('dns_domain', 'name', 'record_type', 'record_data') for i in mandatory_kwargs: if kwargs[i]: pass else: error = '{0}="{1}" ## all mandatory args must be provided: {2}'.format(i, kwargs[i], mandatory_kwargs) raise SaltInvocationError(error) domain = query(method='domains', droplet_id=kwargs['dns_domain']) if domain: result = query( method='domains', droplet_id=kwargs['dns_domain'], command='records', args={'type': kwargs['record_type'], 'name': kwargs['name'], 'data': kwargs['record_data']}, http_method='post' ) return result return False def destroy_dns_records(fqdn): ''' Deletes DNS records for the given hostname if the domain is managed with DO. ''' domain = '.'.join(fqdn.split('.')[-2:]) hostname = '.'.join(fqdn.split('.')[:-2]) # TODO: remove this when the todo on 754 is available try: response = query(method='domains', droplet_id=domain, command='records') except SaltCloudSystemExit: log.debug('Failed to find domains.') return False log.debug("found DNS records: %s", pprint.pformat(response)) records = response['domain_records'] if records: record_ids = [r['id'] for r in records if r['name'].decode() == hostname] log.debug("deleting DNS record IDs: %s", record_ids) for id_ in record_ids: try: log.info('deleting DNS record %s', id_) ret = query( method='domains', droplet_id=domain, command='records/{0}'.format(id_), http_method='delete' ) except SaltCloudSystemExit: log.error('failed to delete DNS domain %s record ID %s.', domain, hostname) log.debug('DNS deletion REST call returned: %s', pprint.pformat(ret)) return False def show_pricing(kwargs=None, call=None): ''' Show pricing for a particular profile. This is only an estimate, based on unofficial pricing sources. .. versionadded:: 2015.8.0 CLI Examples: .. code-block:: bash salt-cloud -f show_pricing my-digitalocean-config profile=my-profile ''' profile = __opts__['profiles'].get(kwargs['profile'], {}) if not profile: return {'Error': 'The requested profile was not found'} # Make sure the profile belongs to DigitalOcean provider = profile.get('provider', '0:0') comps = provider.split(':') if len(comps) < 2 or comps[1] != 'digitalocean': return {'Error': 'The requested profile does not belong to DigitalOcean'} raw = {} ret = {} sizes = avail_sizes() ret['per_hour'] = decimal.Decimal(sizes[profile['size']]['price_hourly']) ret['per_day'] = ret['per_hour'] * 24 ret['per_week'] = ret['per_day'] * 7 ret['per_month'] = decimal.Decimal(sizes[profile['size']]['price_monthly']) ret['per_year'] = ret['per_week'] * 52 if kwargs.get('raw', False): ret['_raw'] = raw return {profile['profile']: ret} def list_floating_ips(call=None): ''' Return a list of the floating ips that are on the provider .. versionadded:: 2016.3.0 CLI Examples: .. code-block:: bash salt-cloud -f list_floating_ips my-digitalocean-config ''' if call == 'action': raise SaltCloudSystemExit( 'The list_floating_ips function must be called with ' '-f or --function, or with the --list-floating-ips option' ) fetch = True page = 1 ret = {} while fetch: items = query(method='floating_ips', command='?page=' + six.text_type(page) + '&per_page=200') for floating_ip in items['floating_ips']: ret[floating_ip['ip']] = {} for item in six.iterkeys(floating_ip): ret[floating_ip['ip']][item] = floating_ip[item] page += 1 try: fetch = 'next' in items['links']['pages'] except KeyError: fetch = False return ret def show_floating_ip(kwargs=None, call=None): ''' Show the details of a floating IP .. versionadded:: 2016.3.0 CLI Examples: .. code-block:: bash salt-cloud -f show_floating_ip my-digitalocean-config floating_ip='45.55.96.47' ''' if call != 'function': log.error( 'The show_floating_ip function must be called with -f or --function.' ) return False if not kwargs: kwargs = {} if 'floating_ip' not in kwargs: log.error('A floating IP is required.') return False floating_ip = kwargs['floating_ip'] log.debug('Floating ip is %s', floating_ip) details = query(method='floating_ips', command=floating_ip) return details def create_floating_ip(kwargs=None, call=None): ''' Create a new floating IP .. versionadded:: 2016.3.0 CLI Examples: .. code-block:: bash salt-cloud -f create_floating_ip my-digitalocean-config region='NYC2' salt-cloud -f create_floating_ip my-digitalocean-config droplet_id='1234567' ''' if call != 'function': log.error( 'The create_floating_ip function must be called with -f or --function.' ) return False if not kwargs: kwargs = {} if 'droplet_id' in kwargs: result = query(method='floating_ips', args={'droplet_id': kwargs['droplet_id']}, http_method='post') return result elif 'region' in kwargs: result = query(method='floating_ips', args={'region': kwargs['region']}, http_method='post') return result else: log.error('A droplet_id or region is required.') return False def delete_floating_ip(kwargs=None, call=None): ''' Delete a floating IP .. versionadded:: 2016.3.0 CLI Examples: .. code-block:: bash salt-cloud -f delete_floating_ip my-digitalocean-config floating_ip='45.55.96.47' ''' if call != 'function': log.error( 'The delete_floating_ip function must be called with -f or --function.' ) return False if not kwargs: kwargs = {} if 'floating_ip' not in kwargs: log.error('A floating IP is required.') return False floating_ip = kwargs['floating_ip'] log.debug('Floating ip is %s', kwargs['floating_ip']) result = query(method='floating_ips', command=floating_ip, http_method='delete') return result def assign_floating_ip(kwargs=None, call=None): ''' Assign a floating IP .. versionadded:: 2016.3.0 CLI Examples: .. code-block:: bash salt-cloud -f assign_floating_ip my-digitalocean-config droplet_id=1234567 floating_ip='45.55.96.47' ''' if call != 'function': log.error( 'The assign_floating_ip function must be called with -f or --function.' ) return False if not kwargs: kwargs = {} if 'floating_ip' and 'droplet_id' not in kwargs: log.error('A floating IP and droplet_id is required.') return False result = query(method='floating_ips', command=kwargs['floating_ip'] + '/actions', args={'droplet_id': kwargs['droplet_id'], 'type': 'assign'}, http_method='post') return result def unassign_floating_ip(kwargs=None, call=None): ''' Unassign a floating IP .. versionadded:: 2016.3.0 CLI Examples: .. code-block:: bash salt-cloud -f unassign_floating_ip my-digitalocean-config floating_ip='45.55.96.47' ''' if call != 'function': log.error( 'The inassign_floating_ip function must be called with -f or --function.' ) return False if not kwargs: kwargs = {} if 'floating_ip' not in kwargs: log.error('A floating IP is required.') return False result = query(method='floating_ips', command=kwargs['floating_ip'] + '/actions', args={'type': 'unassign'}, http_method='post') return result def _list_nodes(full=False, for_output=False): ''' Helper function to format and parse node data. ''' fetch = True page = 1 ret = {} while fetch: items = query(method='droplets', command='?page=' + six.text_type(page) + '&per_page=200') for node in items['droplets']: name = node['name'] ret[name] = {} if full: ret[name] = _get_full_output(node, for_output=for_output) else: public_ips, private_ips = _get_ips(node['networks']) ret[name] = { 'id': node['id'], 'image': node['image']['name'], 'name': name, 'private_ips': private_ips, 'public_ips': public_ips, 'size': node['size_slug'], 'state': six.text_type(node['status']), } page += 1 try: fetch = 'next' in items['links']['pages'] except KeyError: fetch = False return ret def reboot(name, call=None): ''' Reboot a droplet in DigitalOcean. .. versionadded:: 2015.8.8 name The name of the droplet to restart. CLI Example: .. code-block:: bash salt-cloud -a reboot droplet_name ''' if call != 'action': raise SaltCloudSystemExit( 'The restart action must be called with -a or --action.' ) data = show_instance(name, call='action') if data.get('status') == 'off': return {'success': True, 'action': 'stop', 'status': 'off', 'msg': 'Machine is already off.'} ret = query(droplet_id=data['id'], command='actions', args={'type': 'reboot'}, http_method='post') return {'success': True, 'action': ret['action']['type'], 'state': ret['action']['status']} def start(name, call=None): ''' Start a droplet in DigitalOcean. .. versionadded:: 2015.8.8 name The name of the droplet to start. CLI Example: .. code-block:: bash salt-cloud -a start droplet_name ''' if call != 'action': raise SaltCloudSystemExit( 'The start action must be called with -a or --action.' ) data = show_instance(name, call='action') if data.get('status') == 'active': return {'success': True, 'action': 'start', 'status': 'active', 'msg': 'Machine is already running.'} ret = query(droplet_id=data['id'], command='actions', args={'type': 'power_on'}, http_method='post') return {'success': True, 'action': ret['action']['type'], 'state': ret['action']['status']} def stop(name, call=None): ''' Stop a droplet in DigitalOcean. .. versionadded:: 2015.8.8 name The name of the droplet to stop. CLI Example: .. code-block:: bash salt-cloud -a stop droplet_name ''' if call != 'action': raise SaltCloudSystemExit( 'The stop action must be called with -a or --action.' ) data = show_instance(name, call='action') if data.get('status') == 'off': return {'success': True, 'action': 'stop', 'status': 'off', 'msg': 'Machine is already off.'} ret = query(droplet_id=data['id'], command='actions', args={'type': 'shutdown'}, http_method='post') return {'success': True, 'action': ret['action']['type'], 'state': ret['action']['status']} def _get_full_output(node, for_output=False): ''' Helper function for _list_nodes to loop through all node information. Returns a dictionary containing the full information of a node. ''' ret = {} for item in six.iterkeys(node): value = node[item] if value is not None and for_output: value = six.text_type(value) ret[item] = value return ret def _get_ips(networks): ''' Helper function for list_nodes. Returns public and private ip lists based on a given network dictionary. ''' v4s = networks.get('v4') v6s = networks.get('v6') public_ips = [] private_ips = [] if v4s: for item in v4s: ip_type = item.get('type') ip_address = item.get('ip_address') if ip_type == 'public': public_ips.append(ip_address) if ip_type == 'private': private_ips.append(ip_address) if v6s: for item in v6s: ip_type = item.get('type') ip_address = item.get('ip_address') if ip_type == 'public': public_ips.append(ip_address) if ip_type == 'private': private_ips.append(ip_address) return public_ips, private_ips
saltstack/salt
salt/cloud/clouds/digitalocean.py
import_keypair
python
def import_keypair(kwargs=None, call=None): ''' Upload public key to cloud provider. Similar to EC2 import_keypair. .. versionadded:: 2016.11.0 kwargs file(mandatory): public key file-name keyname(mandatory): public key name in the provider ''' with salt.utils.files.fopen(kwargs['file'], 'r') as public_key_filename: public_key_content = salt.utils.stringutils.to_unicode(public_key_filename.read()) digitalocean_kwargs = { 'name': kwargs['keyname'], 'public_key': public_key_content } created_result = create_key(digitalocean_kwargs, call=call) return created_result
Upload public key to cloud provider. Similar to EC2 import_keypair. .. versionadded:: 2016.11.0 kwargs file(mandatory): public key file-name keyname(mandatory): public key name in the provider
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/digitalocean.py#L720-L740
[ "def fopen(*args, **kwargs):\n '''\n Wrapper around open() built-in to set CLOEXEC on the fd.\n\n This flag specifies that the file descriptor should be closed when an exec\n function is invoked;\n\n When a file descriptor is allocated (as with open or dup), this bit is\n initially cleared on the new file descriptor, meaning that descriptor will\n survive into the new program after exec.\n\n NB! We still have small race condition between open and fcntl.\n '''\n if six.PY3:\n try:\n # Don't permit stdin/stdout/stderr to be opened. The boolean False\n # and True are treated by Python 3's open() as file descriptors 0\n # and 1, respectively.\n if args[0] in (0, 1, 2):\n raise TypeError(\n '{0} is not a permitted file descriptor'.format(args[0])\n )\n except IndexError:\n pass\n binary = None\n # ensure 'binary' mode is always used on Windows in Python 2\n if ((six.PY2 and salt.utils.platform.is_windows() and 'binary' not in kwargs) or\n kwargs.pop('binary', False)):\n if len(args) > 1:\n args = list(args)\n if 'b' not in args[1]:\n args[1] = args[1].replace('t', 'b')\n if 'b' not in args[1]:\n args[1] += 'b'\n elif kwargs.get('mode'):\n if 'b' not in kwargs['mode']:\n kwargs['mode'] = kwargs['mode'].replace('t', 'b')\n if 'b' not in kwargs['mode']:\n kwargs['mode'] += 'b'\n else:\n # the default is to read\n kwargs['mode'] = 'rb'\n elif six.PY3 and 'encoding' not in kwargs:\n # In Python 3, if text mode is used and the encoding\n # is not specified, set the encoding to 'utf-8'.\n binary = False\n if len(args) > 1:\n args = list(args)\n if 'b' in args[1]:\n binary = True\n if kwargs.get('mode', None):\n if 'b' in kwargs['mode']:\n binary = True\n if not binary:\n kwargs['encoding'] = __salt_system_encoding__\n\n if six.PY3 and not binary and not kwargs.get('newline', None):\n kwargs['newline'] = ''\n\n f_handle = open(*args, **kwargs) # pylint: disable=resource-leakage\n\n if is_fcntl_available():\n # modify the file descriptor on systems with fcntl\n # unix and unix-like systems only\n try:\n FD_CLOEXEC = fcntl.FD_CLOEXEC # pylint: disable=C0103\n except AttributeError:\n FD_CLOEXEC = 1 # pylint: disable=C0103\n old_flags = fcntl.fcntl(f_handle.fileno(), fcntl.F_GETFD)\n fcntl.fcntl(f_handle.fileno(), fcntl.F_SETFD, old_flags | FD_CLOEXEC)\n\n return f_handle\n", "def to_unicode(s, encoding=None, errors='strict', normalize=False):\n '''\n Given str or unicode, return unicode (str for python 3)\n '''\n def _normalize(s):\n return unicodedata.normalize('NFC', s) if normalize else s\n\n if encoding is None:\n # Try utf-8 first, and fall back to detected encoding\n encoding = ('utf-8', __salt_system_encoding__)\n if not isinstance(encoding, (tuple, list)):\n encoding = (encoding,)\n\n if not encoding:\n raise ValueError('encoding cannot be empty')\n\n exc = None\n if six.PY3:\n if isinstance(s, str):\n return _normalize(s)\n elif isinstance(s, (bytes, bytearray)):\n return _normalize(to_str(s, encoding, errors))\n raise TypeError('expected str, bytes, or bytearray')\n else:\n # This needs to be str and not six.string_types, since if the string is\n # already a unicode type, it does not need to be decoded (and doing so\n # will raise an exception).\n if isinstance(s, unicode): # pylint: disable=incompatible-py3-code,undefined-variable\n return _normalize(s)\n elif isinstance(s, (str, bytearray)):\n for enc in encoding:\n try:\n return _normalize(s.decode(enc, errors))\n except UnicodeDecodeError as err:\n exc = err\n continue\n # The only way we get this far is if a UnicodeDecodeError was\n # raised, otherwise we would have already returned (or raised some\n # other exception).\n raise exc # pylint: disable=raising-bad-type\n raise TypeError('expected str or bytearray')\n", "def create_key(kwargs=None, call=None):\n '''\n Upload a public key\n '''\n if call != 'function':\n log.error(\n 'The create_key function must be called with -f or --function.'\n )\n return False\n\n try:\n result = query(\n method='account',\n command='keys',\n args={'name': kwargs['name'],\n 'public_key': kwargs['public_key']},\n http_method='post'\n )\n except KeyError:\n log.info('`name` and `public_key` arguments must be specified')\n return False\n\n return result\n" ]
# -*- coding: utf-8 -*- ''' DigitalOcean Cloud Module ========================= The DigitalOcean cloud module is used to control access to the DigitalOcean VPS system. Use of this module requires a requires a ``personal_access_token``, an ``ssh_key_file``, and at least one SSH key name in ``ssh_key_names``. More ``ssh_key_names`` can be added by separating each key with a comma. The ``personal_access_token`` can be found in the DigitalOcean web interface in the "Apps & API" section. The SSH key name can be found under the "SSH Keys" section. .. code-block:: yaml # Note: This example is for /etc/salt/cloud.providers or any file in the # /etc/salt/cloud.providers.d/ directory. my-digital-ocean-config: personal_access_token: xxx ssh_key_file: /path/to/ssh/key/file ssh_key_names: my-key-name,my-key-name-2 driver: digitalocean :depends: requests ''' # Import Python Libs from __future__ import absolute_import, print_function, unicode_literals import decimal import logging import os import pprint import time # Import Salt Libs import salt.utils.cloud import salt.utils.files import salt.utils.json import salt.utils.stringutils import salt.config as config from salt.exceptions import ( SaltCloudConfigError, SaltInvocationError, SaltCloudNotFound, SaltCloudSystemExit, SaltCloudExecutionFailure, SaltCloudExecutionTimeout ) from salt.ext import six from salt.ext.six.moves import zip # Import Third Party Libs try: import requests HAS_REQUESTS = True except ImportError: HAS_REQUESTS = False # Get logging started log = logging.getLogger(__name__) __virtualname__ = 'digitalocean' __virtual_aliases__ = ('digital_ocean', 'do') # Only load in this module if the DIGITALOCEAN configurations are in place def __virtual__(): ''' Check for DigitalOcean 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=__opts__, provider=__active_provider_name__ or __virtualname__, aliases=__virtual_aliases__, required_keys=('personal_access_token',) ) def get_dependencies(): ''' Warn if dependencies aren't met. ''' return config.check_driver_dependencies( __virtualname__, {'requests': HAS_REQUESTS} ) def avail_locations(call=None): ''' Return a dict of all available VM locations on the cloud provider with relevant data ''' if call == 'action': raise SaltCloudSystemExit( 'The avail_locations function must be called with ' '-f or --function, or with the --list-locations option' ) items = query(method='regions') ret = {} for region in items['regions']: ret[region['name']] = {} for item in six.iterkeys(region): ret[region['name']][item] = six.text_type(region[item]) return ret def avail_images(call=None): ''' Return a list of the images that are on the provider ''' if call == 'action': raise SaltCloudSystemExit( 'The avail_images function must be called with ' '-f or --function, or with the --list-images option' ) fetch = True page = 1 ret = {} while fetch: items = query(method='images', command='?page=' + six.text_type(page) + '&per_page=200') for image in items['images']: ret[image['name']] = {} for item in six.iterkeys(image): ret[image['name']][item] = image[item] page += 1 try: fetch = 'next' in items['links']['pages'] except KeyError: fetch = False return ret def avail_sizes(call=None): ''' Return a list of the image sizes that are on the provider ''' if call == 'action': raise SaltCloudSystemExit( 'The avail_sizes function must be called with ' '-f or --function, or with the --list-sizes option' ) items = query(method='sizes', command='?per_page=100') ret = {} for size in items['sizes']: ret[size['slug']] = {} for item in six.iterkeys(size): ret[size['slug']][item] = six.text_type(size[item]) 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.' ) return _list_nodes() def list_nodes_full(call=None, for_output=True): ''' 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.' ) return _list_nodes(full=True, for_output=for_output) 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('function'), __opts__['query.selection'], call, ) def get_image(vm_): ''' Return the image object to use ''' images = avail_images() vm_image = config.get_cloud_config_value( 'image', vm_, __opts__, search_global=False ) if not isinstance(vm_image, six.string_types): vm_image = six.text_type(vm_image) for image in images: if vm_image in (images[image]['name'], images[image]['slug'], images[image]['id']): if images[image]['slug'] is not None: return images[image]['slug'] return int(images[image]['id']) raise SaltCloudNotFound( 'The specified image, \'{0}\', could not be found.'.format(vm_image) ) def get_size(vm_): ''' Return the VM's size. Used by create_node(). ''' sizes = avail_sizes() vm_size = six.text_type(config.get_cloud_config_value( 'size', vm_, __opts__, search_global=False )) for size in sizes: if vm_size.lower() == sizes[size]['slug']: return sizes[size]['slug'] raise SaltCloudNotFound( 'The specified size, \'{0}\', could not be found.'.format(vm_size) ) def get_location(vm_): ''' Return the VM's location ''' locations = avail_locations() vm_location = six.text_type(config.get_cloud_config_value( 'location', vm_, __opts__, search_global=False )) for location in locations: if vm_location in (locations[location]['name'], locations[location]['slug']): return locations[location]['slug'] raise SaltCloudNotFound( 'The specified location, \'{0}\', could not be found.'.format( vm_location ) ) def create_node(args): ''' Create a node ''' node = query(method='droplets', args=args, http_method='post') return node 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 'digitalocean', vm_['profile'], vm_=vm_) is False: return False except AttributeError: pass __utils__['cloud.fire_event']( 'event', 'starting create', 'salt/cloud/{0}/creating'.format(vm_['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', vm_['name']) kwargs = { 'name': vm_['name'], 'size': get_size(vm_), 'image': get_image(vm_), 'region': get_location(vm_), 'ssh_keys': [], 'tags': [] } # backwards compat ssh_key_name = config.get_cloud_config_value( 'ssh_key_name', vm_, __opts__, search_global=False ) if ssh_key_name: kwargs['ssh_keys'].append(get_keyid(ssh_key_name)) ssh_key_names = config.get_cloud_config_value( 'ssh_key_names', vm_, __opts__, search_global=False, default=False ) if ssh_key_names: for key in ssh_key_names.split(','): kwargs['ssh_keys'].append(get_keyid(key)) key_filename = config.get_cloud_config_value( 'ssh_key_file', vm_, __opts__, search_global=False, default=None ) if key_filename is not None and not os.path.isfile(key_filename): raise SaltCloudConfigError( 'The defined key_filename \'{0}\' does not exist'.format( key_filename ) ) if not __opts__.get('ssh_agent', False) and key_filename is None: raise SaltCloudConfigError( 'The DigitalOcean driver requires an ssh_key_file and an ssh_key_name ' 'because it does not supply a root password upon building the server.' ) ssh_interface = config.get_cloud_config_value( 'ssh_interface', vm_, __opts__, search_global=False, default='public' ) if ssh_interface in ['private', 'public']: log.info("ssh_interface: Setting interface for ssh to %s", ssh_interface) kwargs['ssh_interface'] = ssh_interface else: raise SaltCloudConfigError( "The DigitalOcean driver requires ssh_interface to be defined as 'public' or 'private'." ) private_networking = config.get_cloud_config_value( 'private_networking', vm_, __opts__, search_global=False, default=None, ) if private_networking is not None: if not isinstance(private_networking, bool): raise SaltCloudConfigError("'private_networking' should be a boolean value.") kwargs['private_networking'] = private_networking if not private_networking and ssh_interface == 'private': raise SaltCloudConfigError( "The DigitalOcean driver requires ssh_interface if defined as 'private' " "then private_networking should be set as 'True'." ) backups_enabled = config.get_cloud_config_value( 'backups_enabled', vm_, __opts__, search_global=False, default=None, ) if backups_enabled is not None: if not isinstance(backups_enabled, bool): raise SaltCloudConfigError("'backups_enabled' should be a boolean value.") kwargs['backups'] = backups_enabled ipv6 = config.get_cloud_config_value( 'ipv6', vm_, __opts__, search_global=False, default=None, ) if ipv6 is not None: if not isinstance(ipv6, bool): raise SaltCloudConfigError("'ipv6' should be a boolean value.") kwargs['ipv6'] = ipv6 monitoring = config.get_cloud_config_value( 'monitoring', vm_, __opts__, search_global=False, default=None, ) if monitoring is not None: if not isinstance(monitoring, bool): raise SaltCloudConfigError("'monitoring' should be a boolean value.") kwargs['monitoring'] = monitoring kwargs['tags'] = config.get_cloud_config_value( 'tags', vm_, __opts__, search_global=False, default=False ) userdata_file = config.get_cloud_config_value( 'userdata_file', vm_, __opts__, search_global=False, default=None ) if userdata_file is not None: try: with salt.utils.files.fopen(userdata_file, 'r') as fp_: kwargs['user_data'] = salt.utils.cloud.userdata_template( __opts__, vm_, salt.utils.stringutils.to_unicode(fp_.read()) ) except Exception as exc: log.exception( 'Failed to read userdata from %s: %s', userdata_file, exc) create_dns_record = config.get_cloud_config_value( 'create_dns_record', vm_, __opts__, search_global=False, default=None, ) if create_dns_record: log.info('create_dns_record: will attempt to write DNS records') default_dns_domain = None dns_domain_name = vm_['name'].split('.') if len(dns_domain_name) > 2: log.debug('create_dns_record: inferring default dns_hostname, dns_domain from minion name as FQDN') default_dns_hostname = '.'.join(dns_domain_name[:-2]) default_dns_domain = '.'.join(dns_domain_name[-2:]) else: log.debug("create_dns_record: can't infer dns_domain from %s", vm_['name']) default_dns_hostname = dns_domain_name[0] dns_hostname = config.get_cloud_config_value( 'dns_hostname', vm_, __opts__, search_global=False, default=default_dns_hostname, ) dns_domain = config.get_cloud_config_value( 'dns_domain', vm_, __opts__, search_global=False, default=default_dns_domain, ) if dns_hostname and dns_domain: log.info('create_dns_record: using dns_hostname="%s", dns_domain="%s"', dns_hostname, dns_domain) __add_dns_addr__ = lambda t, d: post_dns_record(dns_domain=dns_domain, name=dns_hostname, record_type=t, record_data=d) log.debug('create_dns_record: %s', __add_dns_addr__) else: log.error('create_dns_record: could not determine dns_hostname and/or dns_domain') raise SaltCloudConfigError( '\'create_dns_record\' must be a dict specifying "domain" ' 'and "hostname" or the minion name must be an FQDN.' ) __utils__['cloud.fire_event']( 'event', 'requesting instance', 'salt/cloud/{0}/requesting'.format(vm_['name']), args=__utils__['cloud.filter_event']('requesting', kwargs, list(kwargs)), sock_dir=__opts__['sock_dir'], transport=__opts__['transport'] ) try: ret = create_node(kwargs) except Exception as exc: log.error( 'Error creating %s on DIGITALOCEAN\n\n' 'The following exception was thrown when trying to ' 'run the initial deployment: %s', vm_['name'], exc, # Show the traceback if the debug logging level is enabled exc_info_on_loglevel=logging.DEBUG ) return False def __query_node_data(vm_name): data = show_instance(vm_name, 'action') if not data: # Trigger an error in the wait_for_ip function return False if data['networks'].get('v4'): for network in data['networks']['v4']: if network['type'] == 'public': return data return False try: data = salt.utils.cloud.wait_for_ip( __query_node_data, update_args=(vm_['name'],), timeout=config.get_cloud_config_value( 'wait_for_ip_timeout', vm_, __opts__, default=10 * 60), interval=config.get_cloud_config_value( 'wait_for_ip_interval', vm_, __opts__, default=10), ) except (SaltCloudExecutionTimeout, SaltCloudExecutionFailure) as exc: try: # It might be already up, let's destroy it! destroy(vm_['name']) except SaltCloudSystemExit: pass finally: raise SaltCloudSystemExit(six.text_type(exc)) if not vm_.get('ssh_host'): vm_['ssh_host'] = None # add DNS records, set ssh_host, default to first found IP, preferring IPv4 for ssh bootstrap script target addr_families, dns_arec_types = (('v4', 'v6'), ('A', 'AAAA')) arec_map = dict(list(zip(addr_families, dns_arec_types))) for facing, addr_family, ip_address in [(net['type'], family, net['ip_address']) for family in addr_families for net in data['networks'][family]]: log.info('found %s IP%s interface for "%s"', facing, addr_family, ip_address) dns_rec_type = arec_map[addr_family] if facing == 'public': if create_dns_record: __add_dns_addr__(dns_rec_type, ip_address) if facing == ssh_interface: if not vm_['ssh_host']: vm_['ssh_host'] = ip_address if vm_['ssh_host'] is None: raise SaltCloudSystemExit( 'No suitable IP addresses found for ssh minion bootstrapping: {0}'.format(repr(data['networks'])) ) log.debug( 'Found public IP address to use for ssh minion bootstrapping: %s', vm_['ssh_host'] ) vm_['key_filename'] = key_filename ret = __utils__['cloud.bootstrap'](vm_, __opts__) ret.update(data) log.info('Created Cloud VM \'%s\'', vm_['name']) log.debug( '\'%s\' VM creation details:\n%s', vm_['name'], pprint.pformat(data) ) __utils__['cloud.fire_event']( 'event', 'created instance', 'salt/cloud/{0}/created'.format(vm_['name']), args=__utils__['cloud.filter_event']('created', vm_, ['name', 'profile', 'provider', 'driver']), sock_dir=__opts__['sock_dir'], transport=__opts__['transport'] ) return ret def query(method='droplets', droplet_id=None, command=None, args=None, http_method='get'): ''' Make a web call to DigitalOcean ''' base_path = six.text_type(config.get_cloud_config_value( 'api_root', get_configured_provider(), __opts__, search_global=False, default='https://api.digitalocean.com/v2' )) path = '{0}/{1}/'.format(base_path, method) if droplet_id: path += '{0}/'.format(droplet_id) if command: path += command if not isinstance(args, dict): args = {} personal_access_token = config.get_cloud_config_value( 'personal_access_token', get_configured_provider(), __opts__, search_global=False ) data = salt.utils.json.dumps(args) requester = getattr(requests, http_method) request = requester(path, data=data, headers={'Authorization': 'Bearer ' + personal_access_token, 'Content-Type': 'application/json'}) if request.status_code > 299: raise SaltCloudSystemExit( 'An error occurred while querying DigitalOcean. HTTP Code: {0} ' 'Error: \'{1}\''.format( request.status_code, # request.read() request.text ) ) log.debug(request.url) # success without data if request.status_code == 204: return True content = request.text result = salt.utils.json.loads(content) if result.get('status', '').lower() == 'error': raise SaltCloudSystemExit( pprint.pformat(result.get('error_message', {})) ) return result 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 show_instance(name, call=None): ''' Show the details from DigitalOcean concerning a droplet ''' if call != 'action': raise SaltCloudSystemExit( 'The show_instance action must be called with -a or --action.' ) node = _get_node(name) __utils__['cloud.cache_node'](node, __active_provider_name__, __opts__) return node def _get_node(name): attempts = 10 while attempts >= 0: try: return list_nodes_full(for_output=False)[name] except KeyError: attempts -= 1 log.debug( 'Failed to get the data for node \'%s\'. Remaining ' 'attempts: %s', name, attempts ) # Just a little delay between attempts... time.sleep(0.5) return {} def list_keypairs(call=None): ''' Return a dict of all available VM locations on the cloud provider with relevant data ''' if call != 'function': log.error( 'The list_keypairs function must be called with -f or --function.' ) return False fetch = True page = 1 ret = {} while fetch: items = query(method='account/keys', command='?page=' + six.text_type(page) + '&per_page=100') for key_pair in items['ssh_keys']: name = key_pair['name'] if name in ret: raise SaltCloudSystemExit( 'A duplicate key pair name, \'{0}\', was found in DigitalOcean\'s ' 'key pair list. Please change the key name stored by DigitalOcean. ' 'Be sure to adjust the value of \'ssh_key_file\' in your cloud ' 'profile or provider configuration, if necessary.'.format( name ) ) ret[name] = {} for item in six.iterkeys(key_pair): ret[name][item] = six.text_type(key_pair[item]) page += 1 try: fetch = 'next' in items['links']['pages'] except KeyError: fetch = False return ret def show_keypair(kwargs=None, call=None): ''' Show the details of an SSH keypair ''' if call != 'function': log.error( 'The show_keypair function must be called with -f or --function.' ) return False if not kwargs: kwargs = {} if 'keyname' not in kwargs: log.error('A keyname is required.') return False keypairs = list_keypairs(call='function') keyid = keypairs[kwargs['keyname']]['id'] log.debug('Key ID is %s', keyid) details = query(method='account/keys', command=keyid) return details def create_key(kwargs=None, call=None): ''' Upload a public key ''' if call != 'function': log.error( 'The create_key function must be called with -f or --function.' ) return False try: result = query( method='account', command='keys', args={'name': kwargs['name'], 'public_key': kwargs['public_key']}, http_method='post' ) except KeyError: log.info('`name` and `public_key` arguments must be specified') return False return result def remove_key(kwargs=None, call=None): ''' Delete public key ''' if call != 'function': log.error( 'The create_key function must be called with -f or --function.' ) return False try: result = query( method='account', command='keys/' + kwargs['id'], http_method='delete' ) except KeyError: log.info('`id` argument must be specified') return False return result def get_keyid(keyname): ''' Return the ID of the keyname ''' if not keyname: return None keypairs = list_keypairs(call='function') keyid = keypairs[keyname]['id'] if keyid: return keyid raise SaltCloudNotFound('The specified ssh key could not be found.') def destroy(name, call=None): ''' Destroy a node. Will check termination protection and warn if enabled. 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'] ) data = show_instance(name, call='action') node = query(method='droplets', droplet_id=data['id'], http_method='delete') ## This is all terribly optomistic: # vm_ = get_vm_config(name=name) # delete_dns_record = config.get_cloud_config_value( # 'delete_dns_record', vm_, __opts__, search_global=False, default=None, # ) # TODO: when _vm config data can be made available, we should honor the configuration settings, # but until then, we should assume stale DNS records are bad, and default behavior should be to # delete them if we can. When this is resolved, also resolve the comments a couple of lines below. delete_dns_record = True if not isinstance(delete_dns_record, bool): raise SaltCloudConfigError( '\'delete_dns_record\' should be a boolean value.' ) # When the "to do" a few lines up is resolved, remove these lines and use the if/else logic below. log.debug('Deleting DNS records for %s.', name) destroy_dns_records(name) # Until the "to do" from line 754 is taken care of, we don't need this logic. # if delete_dns_record: # log.debug('Deleting DNS records for %s.', name) # destroy_dns_records(name) # else: # log.debug('delete_dns_record : %s', delete_dns_record) # for line in pprint.pformat(dir()).splitlines(): # log.debug('delete context: %s', line) __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 node def post_dns_record(**kwargs): ''' Creates a DNS record for the given name if the domain is managed with DO. ''' if 'kwargs' in kwargs: # flatten kwargs if called via salt-cloud -f f_kwargs = kwargs['kwargs'] del kwargs['kwargs'] kwargs.update(f_kwargs) mandatory_kwargs = ('dns_domain', 'name', 'record_type', 'record_data') for i in mandatory_kwargs: if kwargs[i]: pass else: error = '{0}="{1}" ## all mandatory args must be provided: {2}'.format(i, kwargs[i], mandatory_kwargs) raise SaltInvocationError(error) domain = query(method='domains', droplet_id=kwargs['dns_domain']) if domain: result = query( method='domains', droplet_id=kwargs['dns_domain'], command='records', args={'type': kwargs['record_type'], 'name': kwargs['name'], 'data': kwargs['record_data']}, http_method='post' ) return result return False def destroy_dns_records(fqdn): ''' Deletes DNS records for the given hostname if the domain is managed with DO. ''' domain = '.'.join(fqdn.split('.')[-2:]) hostname = '.'.join(fqdn.split('.')[:-2]) # TODO: remove this when the todo on 754 is available try: response = query(method='domains', droplet_id=domain, command='records') except SaltCloudSystemExit: log.debug('Failed to find domains.') return False log.debug("found DNS records: %s", pprint.pformat(response)) records = response['domain_records'] if records: record_ids = [r['id'] for r in records if r['name'].decode() == hostname] log.debug("deleting DNS record IDs: %s", record_ids) for id_ in record_ids: try: log.info('deleting DNS record %s', id_) ret = query( method='domains', droplet_id=domain, command='records/{0}'.format(id_), http_method='delete' ) except SaltCloudSystemExit: log.error('failed to delete DNS domain %s record ID %s.', domain, hostname) log.debug('DNS deletion REST call returned: %s', pprint.pformat(ret)) return False def show_pricing(kwargs=None, call=None): ''' Show pricing for a particular profile. This is only an estimate, based on unofficial pricing sources. .. versionadded:: 2015.8.0 CLI Examples: .. code-block:: bash salt-cloud -f show_pricing my-digitalocean-config profile=my-profile ''' profile = __opts__['profiles'].get(kwargs['profile'], {}) if not profile: return {'Error': 'The requested profile was not found'} # Make sure the profile belongs to DigitalOcean provider = profile.get('provider', '0:0') comps = provider.split(':') if len(comps) < 2 or comps[1] != 'digitalocean': return {'Error': 'The requested profile does not belong to DigitalOcean'} raw = {} ret = {} sizes = avail_sizes() ret['per_hour'] = decimal.Decimal(sizes[profile['size']]['price_hourly']) ret['per_day'] = ret['per_hour'] * 24 ret['per_week'] = ret['per_day'] * 7 ret['per_month'] = decimal.Decimal(sizes[profile['size']]['price_monthly']) ret['per_year'] = ret['per_week'] * 52 if kwargs.get('raw', False): ret['_raw'] = raw return {profile['profile']: ret} def list_floating_ips(call=None): ''' Return a list of the floating ips that are on the provider .. versionadded:: 2016.3.0 CLI Examples: .. code-block:: bash salt-cloud -f list_floating_ips my-digitalocean-config ''' if call == 'action': raise SaltCloudSystemExit( 'The list_floating_ips function must be called with ' '-f or --function, or with the --list-floating-ips option' ) fetch = True page = 1 ret = {} while fetch: items = query(method='floating_ips', command='?page=' + six.text_type(page) + '&per_page=200') for floating_ip in items['floating_ips']: ret[floating_ip['ip']] = {} for item in six.iterkeys(floating_ip): ret[floating_ip['ip']][item] = floating_ip[item] page += 1 try: fetch = 'next' in items['links']['pages'] except KeyError: fetch = False return ret def show_floating_ip(kwargs=None, call=None): ''' Show the details of a floating IP .. versionadded:: 2016.3.0 CLI Examples: .. code-block:: bash salt-cloud -f show_floating_ip my-digitalocean-config floating_ip='45.55.96.47' ''' if call != 'function': log.error( 'The show_floating_ip function must be called with -f or --function.' ) return False if not kwargs: kwargs = {} if 'floating_ip' not in kwargs: log.error('A floating IP is required.') return False floating_ip = kwargs['floating_ip'] log.debug('Floating ip is %s', floating_ip) details = query(method='floating_ips', command=floating_ip) return details def create_floating_ip(kwargs=None, call=None): ''' Create a new floating IP .. versionadded:: 2016.3.0 CLI Examples: .. code-block:: bash salt-cloud -f create_floating_ip my-digitalocean-config region='NYC2' salt-cloud -f create_floating_ip my-digitalocean-config droplet_id='1234567' ''' if call != 'function': log.error( 'The create_floating_ip function must be called with -f or --function.' ) return False if not kwargs: kwargs = {} if 'droplet_id' in kwargs: result = query(method='floating_ips', args={'droplet_id': kwargs['droplet_id']}, http_method='post') return result elif 'region' in kwargs: result = query(method='floating_ips', args={'region': kwargs['region']}, http_method='post') return result else: log.error('A droplet_id or region is required.') return False def delete_floating_ip(kwargs=None, call=None): ''' Delete a floating IP .. versionadded:: 2016.3.0 CLI Examples: .. code-block:: bash salt-cloud -f delete_floating_ip my-digitalocean-config floating_ip='45.55.96.47' ''' if call != 'function': log.error( 'The delete_floating_ip function must be called with -f or --function.' ) return False if not kwargs: kwargs = {} if 'floating_ip' not in kwargs: log.error('A floating IP is required.') return False floating_ip = kwargs['floating_ip'] log.debug('Floating ip is %s', kwargs['floating_ip']) result = query(method='floating_ips', command=floating_ip, http_method='delete') return result def assign_floating_ip(kwargs=None, call=None): ''' Assign a floating IP .. versionadded:: 2016.3.0 CLI Examples: .. code-block:: bash salt-cloud -f assign_floating_ip my-digitalocean-config droplet_id=1234567 floating_ip='45.55.96.47' ''' if call != 'function': log.error( 'The assign_floating_ip function must be called with -f or --function.' ) return False if not kwargs: kwargs = {} if 'floating_ip' and 'droplet_id' not in kwargs: log.error('A floating IP and droplet_id is required.') return False result = query(method='floating_ips', command=kwargs['floating_ip'] + '/actions', args={'droplet_id': kwargs['droplet_id'], 'type': 'assign'}, http_method='post') return result def unassign_floating_ip(kwargs=None, call=None): ''' Unassign a floating IP .. versionadded:: 2016.3.0 CLI Examples: .. code-block:: bash salt-cloud -f unassign_floating_ip my-digitalocean-config floating_ip='45.55.96.47' ''' if call != 'function': log.error( 'The inassign_floating_ip function must be called with -f or --function.' ) return False if not kwargs: kwargs = {} if 'floating_ip' not in kwargs: log.error('A floating IP is required.') return False result = query(method='floating_ips', command=kwargs['floating_ip'] + '/actions', args={'type': 'unassign'}, http_method='post') return result def _list_nodes(full=False, for_output=False): ''' Helper function to format and parse node data. ''' fetch = True page = 1 ret = {} while fetch: items = query(method='droplets', command='?page=' + six.text_type(page) + '&per_page=200') for node in items['droplets']: name = node['name'] ret[name] = {} if full: ret[name] = _get_full_output(node, for_output=for_output) else: public_ips, private_ips = _get_ips(node['networks']) ret[name] = { 'id': node['id'], 'image': node['image']['name'], 'name': name, 'private_ips': private_ips, 'public_ips': public_ips, 'size': node['size_slug'], 'state': six.text_type(node['status']), } page += 1 try: fetch = 'next' in items['links']['pages'] except KeyError: fetch = False return ret def reboot(name, call=None): ''' Reboot a droplet in DigitalOcean. .. versionadded:: 2015.8.8 name The name of the droplet to restart. CLI Example: .. code-block:: bash salt-cloud -a reboot droplet_name ''' if call != 'action': raise SaltCloudSystemExit( 'The restart action must be called with -a or --action.' ) data = show_instance(name, call='action') if data.get('status') == 'off': return {'success': True, 'action': 'stop', 'status': 'off', 'msg': 'Machine is already off.'} ret = query(droplet_id=data['id'], command='actions', args={'type': 'reboot'}, http_method='post') return {'success': True, 'action': ret['action']['type'], 'state': ret['action']['status']} def start(name, call=None): ''' Start a droplet in DigitalOcean. .. versionadded:: 2015.8.8 name The name of the droplet to start. CLI Example: .. code-block:: bash salt-cloud -a start droplet_name ''' if call != 'action': raise SaltCloudSystemExit( 'The start action must be called with -a or --action.' ) data = show_instance(name, call='action') if data.get('status') == 'active': return {'success': True, 'action': 'start', 'status': 'active', 'msg': 'Machine is already running.'} ret = query(droplet_id=data['id'], command='actions', args={'type': 'power_on'}, http_method='post') return {'success': True, 'action': ret['action']['type'], 'state': ret['action']['status']} def stop(name, call=None): ''' Stop a droplet in DigitalOcean. .. versionadded:: 2015.8.8 name The name of the droplet to stop. CLI Example: .. code-block:: bash salt-cloud -a stop droplet_name ''' if call != 'action': raise SaltCloudSystemExit( 'The stop action must be called with -a or --action.' ) data = show_instance(name, call='action') if data.get('status') == 'off': return {'success': True, 'action': 'stop', 'status': 'off', 'msg': 'Machine is already off.'} ret = query(droplet_id=data['id'], command='actions', args={'type': 'shutdown'}, http_method='post') return {'success': True, 'action': ret['action']['type'], 'state': ret['action']['status']} def _get_full_output(node, for_output=False): ''' Helper function for _list_nodes to loop through all node information. Returns a dictionary containing the full information of a node. ''' ret = {} for item in six.iterkeys(node): value = node[item] if value is not None and for_output: value = six.text_type(value) ret[item] = value return ret def _get_ips(networks): ''' Helper function for list_nodes. Returns public and private ip lists based on a given network dictionary. ''' v4s = networks.get('v4') v6s = networks.get('v6') public_ips = [] private_ips = [] if v4s: for item in v4s: ip_type = item.get('type') ip_address = item.get('ip_address') if ip_type == 'public': public_ips.append(ip_address) if ip_type == 'private': private_ips.append(ip_address) if v6s: for item in v6s: ip_type = item.get('type') ip_address = item.get('ip_address') if ip_type == 'public': public_ips.append(ip_address) if ip_type == 'private': private_ips.append(ip_address) return public_ips, private_ips
saltstack/salt
salt/cloud/clouds/digitalocean.py
create_key
python
def create_key(kwargs=None, call=None): ''' Upload a public key ''' if call != 'function': log.error( 'The create_key function must be called with -f or --function.' ) return False try: result = query( method='account', command='keys', args={'name': kwargs['name'], 'public_key': kwargs['public_key']}, http_method='post' ) except KeyError: log.info('`name` and `public_key` arguments must be specified') return False return result
Upload a public key
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/digitalocean.py#L743-L765
[ "def query(method='droplets', droplet_id=None, command=None, args=None, http_method='get'):\n '''\n Make a web call to DigitalOcean\n '''\n base_path = six.text_type(config.get_cloud_config_value(\n 'api_root',\n get_configured_provider(),\n __opts__,\n search_global=False,\n default='https://api.digitalocean.com/v2'\n ))\n\n path = '{0}/{1}/'.format(base_path, method)\n\n if droplet_id:\n path += '{0}/'.format(droplet_id)\n\n if command:\n path += command\n\n if not isinstance(args, dict):\n args = {}\n\n personal_access_token = config.get_cloud_config_value(\n 'personal_access_token', get_configured_provider(), __opts__, search_global=False\n )\n\n data = salt.utils.json.dumps(args)\n\n requester = getattr(requests, http_method)\n request = requester(path, data=data, headers={'Authorization': 'Bearer ' + personal_access_token, 'Content-Type': 'application/json'})\n if request.status_code > 299:\n raise SaltCloudSystemExit(\n 'An error occurred while querying DigitalOcean. HTTP Code: {0} '\n 'Error: \\'{1}\\''.format(\n request.status_code,\n # request.read()\n request.text\n )\n )\n\n log.debug(request.url)\n\n # success without data\n if request.status_code == 204:\n return True\n\n content = request.text\n\n result = salt.utils.json.loads(content)\n if result.get('status', '').lower() == 'error':\n raise SaltCloudSystemExit(\n pprint.pformat(result.get('error_message', {}))\n )\n\n return result\n" ]
# -*- coding: utf-8 -*- ''' DigitalOcean Cloud Module ========================= The DigitalOcean cloud module is used to control access to the DigitalOcean VPS system. Use of this module requires a requires a ``personal_access_token``, an ``ssh_key_file``, and at least one SSH key name in ``ssh_key_names``. More ``ssh_key_names`` can be added by separating each key with a comma. The ``personal_access_token`` can be found in the DigitalOcean web interface in the "Apps & API" section. The SSH key name can be found under the "SSH Keys" section. .. code-block:: yaml # Note: This example is for /etc/salt/cloud.providers or any file in the # /etc/salt/cloud.providers.d/ directory. my-digital-ocean-config: personal_access_token: xxx ssh_key_file: /path/to/ssh/key/file ssh_key_names: my-key-name,my-key-name-2 driver: digitalocean :depends: requests ''' # Import Python Libs from __future__ import absolute_import, print_function, unicode_literals import decimal import logging import os import pprint import time # Import Salt Libs import salt.utils.cloud import salt.utils.files import salt.utils.json import salt.utils.stringutils import salt.config as config from salt.exceptions import ( SaltCloudConfigError, SaltInvocationError, SaltCloudNotFound, SaltCloudSystemExit, SaltCloudExecutionFailure, SaltCloudExecutionTimeout ) from salt.ext import six from salt.ext.six.moves import zip # Import Third Party Libs try: import requests HAS_REQUESTS = True except ImportError: HAS_REQUESTS = False # Get logging started log = logging.getLogger(__name__) __virtualname__ = 'digitalocean' __virtual_aliases__ = ('digital_ocean', 'do') # Only load in this module if the DIGITALOCEAN configurations are in place def __virtual__(): ''' Check for DigitalOcean 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=__opts__, provider=__active_provider_name__ or __virtualname__, aliases=__virtual_aliases__, required_keys=('personal_access_token',) ) def get_dependencies(): ''' Warn if dependencies aren't met. ''' return config.check_driver_dependencies( __virtualname__, {'requests': HAS_REQUESTS} ) def avail_locations(call=None): ''' Return a dict of all available VM locations on the cloud provider with relevant data ''' if call == 'action': raise SaltCloudSystemExit( 'The avail_locations function must be called with ' '-f or --function, or with the --list-locations option' ) items = query(method='regions') ret = {} for region in items['regions']: ret[region['name']] = {} for item in six.iterkeys(region): ret[region['name']][item] = six.text_type(region[item]) return ret def avail_images(call=None): ''' Return a list of the images that are on the provider ''' if call == 'action': raise SaltCloudSystemExit( 'The avail_images function must be called with ' '-f or --function, or with the --list-images option' ) fetch = True page = 1 ret = {} while fetch: items = query(method='images', command='?page=' + six.text_type(page) + '&per_page=200') for image in items['images']: ret[image['name']] = {} for item in six.iterkeys(image): ret[image['name']][item] = image[item] page += 1 try: fetch = 'next' in items['links']['pages'] except KeyError: fetch = False return ret def avail_sizes(call=None): ''' Return a list of the image sizes that are on the provider ''' if call == 'action': raise SaltCloudSystemExit( 'The avail_sizes function must be called with ' '-f or --function, or with the --list-sizes option' ) items = query(method='sizes', command='?per_page=100') ret = {} for size in items['sizes']: ret[size['slug']] = {} for item in six.iterkeys(size): ret[size['slug']][item] = six.text_type(size[item]) 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.' ) return _list_nodes() def list_nodes_full(call=None, for_output=True): ''' 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.' ) return _list_nodes(full=True, for_output=for_output) 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('function'), __opts__['query.selection'], call, ) def get_image(vm_): ''' Return the image object to use ''' images = avail_images() vm_image = config.get_cloud_config_value( 'image', vm_, __opts__, search_global=False ) if not isinstance(vm_image, six.string_types): vm_image = six.text_type(vm_image) for image in images: if vm_image in (images[image]['name'], images[image]['slug'], images[image]['id']): if images[image]['slug'] is not None: return images[image]['slug'] return int(images[image]['id']) raise SaltCloudNotFound( 'The specified image, \'{0}\', could not be found.'.format(vm_image) ) def get_size(vm_): ''' Return the VM's size. Used by create_node(). ''' sizes = avail_sizes() vm_size = six.text_type(config.get_cloud_config_value( 'size', vm_, __opts__, search_global=False )) for size in sizes: if vm_size.lower() == sizes[size]['slug']: return sizes[size]['slug'] raise SaltCloudNotFound( 'The specified size, \'{0}\', could not be found.'.format(vm_size) ) def get_location(vm_): ''' Return the VM's location ''' locations = avail_locations() vm_location = six.text_type(config.get_cloud_config_value( 'location', vm_, __opts__, search_global=False )) for location in locations: if vm_location in (locations[location]['name'], locations[location]['slug']): return locations[location]['slug'] raise SaltCloudNotFound( 'The specified location, \'{0}\', could not be found.'.format( vm_location ) ) def create_node(args): ''' Create a node ''' node = query(method='droplets', args=args, http_method='post') return node 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 'digitalocean', vm_['profile'], vm_=vm_) is False: return False except AttributeError: pass __utils__['cloud.fire_event']( 'event', 'starting create', 'salt/cloud/{0}/creating'.format(vm_['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', vm_['name']) kwargs = { 'name': vm_['name'], 'size': get_size(vm_), 'image': get_image(vm_), 'region': get_location(vm_), 'ssh_keys': [], 'tags': [] } # backwards compat ssh_key_name = config.get_cloud_config_value( 'ssh_key_name', vm_, __opts__, search_global=False ) if ssh_key_name: kwargs['ssh_keys'].append(get_keyid(ssh_key_name)) ssh_key_names = config.get_cloud_config_value( 'ssh_key_names', vm_, __opts__, search_global=False, default=False ) if ssh_key_names: for key in ssh_key_names.split(','): kwargs['ssh_keys'].append(get_keyid(key)) key_filename = config.get_cloud_config_value( 'ssh_key_file', vm_, __opts__, search_global=False, default=None ) if key_filename is not None and not os.path.isfile(key_filename): raise SaltCloudConfigError( 'The defined key_filename \'{0}\' does not exist'.format( key_filename ) ) if not __opts__.get('ssh_agent', False) and key_filename is None: raise SaltCloudConfigError( 'The DigitalOcean driver requires an ssh_key_file and an ssh_key_name ' 'because it does not supply a root password upon building the server.' ) ssh_interface = config.get_cloud_config_value( 'ssh_interface', vm_, __opts__, search_global=False, default='public' ) if ssh_interface in ['private', 'public']: log.info("ssh_interface: Setting interface for ssh to %s", ssh_interface) kwargs['ssh_interface'] = ssh_interface else: raise SaltCloudConfigError( "The DigitalOcean driver requires ssh_interface to be defined as 'public' or 'private'." ) private_networking = config.get_cloud_config_value( 'private_networking', vm_, __opts__, search_global=False, default=None, ) if private_networking is not None: if not isinstance(private_networking, bool): raise SaltCloudConfigError("'private_networking' should be a boolean value.") kwargs['private_networking'] = private_networking if not private_networking and ssh_interface == 'private': raise SaltCloudConfigError( "The DigitalOcean driver requires ssh_interface if defined as 'private' " "then private_networking should be set as 'True'." ) backups_enabled = config.get_cloud_config_value( 'backups_enabled', vm_, __opts__, search_global=False, default=None, ) if backups_enabled is not None: if not isinstance(backups_enabled, bool): raise SaltCloudConfigError("'backups_enabled' should be a boolean value.") kwargs['backups'] = backups_enabled ipv6 = config.get_cloud_config_value( 'ipv6', vm_, __opts__, search_global=False, default=None, ) if ipv6 is not None: if not isinstance(ipv6, bool): raise SaltCloudConfigError("'ipv6' should be a boolean value.") kwargs['ipv6'] = ipv6 monitoring = config.get_cloud_config_value( 'monitoring', vm_, __opts__, search_global=False, default=None, ) if monitoring is not None: if not isinstance(monitoring, bool): raise SaltCloudConfigError("'monitoring' should be a boolean value.") kwargs['monitoring'] = monitoring kwargs['tags'] = config.get_cloud_config_value( 'tags', vm_, __opts__, search_global=False, default=False ) userdata_file = config.get_cloud_config_value( 'userdata_file', vm_, __opts__, search_global=False, default=None ) if userdata_file is not None: try: with salt.utils.files.fopen(userdata_file, 'r') as fp_: kwargs['user_data'] = salt.utils.cloud.userdata_template( __opts__, vm_, salt.utils.stringutils.to_unicode(fp_.read()) ) except Exception as exc: log.exception( 'Failed to read userdata from %s: %s', userdata_file, exc) create_dns_record = config.get_cloud_config_value( 'create_dns_record', vm_, __opts__, search_global=False, default=None, ) if create_dns_record: log.info('create_dns_record: will attempt to write DNS records') default_dns_domain = None dns_domain_name = vm_['name'].split('.') if len(dns_domain_name) > 2: log.debug('create_dns_record: inferring default dns_hostname, dns_domain from minion name as FQDN') default_dns_hostname = '.'.join(dns_domain_name[:-2]) default_dns_domain = '.'.join(dns_domain_name[-2:]) else: log.debug("create_dns_record: can't infer dns_domain from %s", vm_['name']) default_dns_hostname = dns_domain_name[0] dns_hostname = config.get_cloud_config_value( 'dns_hostname', vm_, __opts__, search_global=False, default=default_dns_hostname, ) dns_domain = config.get_cloud_config_value( 'dns_domain', vm_, __opts__, search_global=False, default=default_dns_domain, ) if dns_hostname and dns_domain: log.info('create_dns_record: using dns_hostname="%s", dns_domain="%s"', dns_hostname, dns_domain) __add_dns_addr__ = lambda t, d: post_dns_record(dns_domain=dns_domain, name=dns_hostname, record_type=t, record_data=d) log.debug('create_dns_record: %s', __add_dns_addr__) else: log.error('create_dns_record: could not determine dns_hostname and/or dns_domain') raise SaltCloudConfigError( '\'create_dns_record\' must be a dict specifying "domain" ' 'and "hostname" or the minion name must be an FQDN.' ) __utils__['cloud.fire_event']( 'event', 'requesting instance', 'salt/cloud/{0}/requesting'.format(vm_['name']), args=__utils__['cloud.filter_event']('requesting', kwargs, list(kwargs)), sock_dir=__opts__['sock_dir'], transport=__opts__['transport'] ) try: ret = create_node(kwargs) except Exception as exc: log.error( 'Error creating %s on DIGITALOCEAN\n\n' 'The following exception was thrown when trying to ' 'run the initial deployment: %s', vm_['name'], exc, # Show the traceback if the debug logging level is enabled exc_info_on_loglevel=logging.DEBUG ) return False def __query_node_data(vm_name): data = show_instance(vm_name, 'action') if not data: # Trigger an error in the wait_for_ip function return False if data['networks'].get('v4'): for network in data['networks']['v4']: if network['type'] == 'public': return data return False try: data = salt.utils.cloud.wait_for_ip( __query_node_data, update_args=(vm_['name'],), timeout=config.get_cloud_config_value( 'wait_for_ip_timeout', vm_, __opts__, default=10 * 60), interval=config.get_cloud_config_value( 'wait_for_ip_interval', vm_, __opts__, default=10), ) except (SaltCloudExecutionTimeout, SaltCloudExecutionFailure) as exc: try: # It might be already up, let's destroy it! destroy(vm_['name']) except SaltCloudSystemExit: pass finally: raise SaltCloudSystemExit(six.text_type(exc)) if not vm_.get('ssh_host'): vm_['ssh_host'] = None # add DNS records, set ssh_host, default to first found IP, preferring IPv4 for ssh bootstrap script target addr_families, dns_arec_types = (('v4', 'v6'), ('A', 'AAAA')) arec_map = dict(list(zip(addr_families, dns_arec_types))) for facing, addr_family, ip_address in [(net['type'], family, net['ip_address']) for family in addr_families for net in data['networks'][family]]: log.info('found %s IP%s interface for "%s"', facing, addr_family, ip_address) dns_rec_type = arec_map[addr_family] if facing == 'public': if create_dns_record: __add_dns_addr__(dns_rec_type, ip_address) if facing == ssh_interface: if not vm_['ssh_host']: vm_['ssh_host'] = ip_address if vm_['ssh_host'] is None: raise SaltCloudSystemExit( 'No suitable IP addresses found for ssh minion bootstrapping: {0}'.format(repr(data['networks'])) ) log.debug( 'Found public IP address to use for ssh minion bootstrapping: %s', vm_['ssh_host'] ) vm_['key_filename'] = key_filename ret = __utils__['cloud.bootstrap'](vm_, __opts__) ret.update(data) log.info('Created Cloud VM \'%s\'', vm_['name']) log.debug( '\'%s\' VM creation details:\n%s', vm_['name'], pprint.pformat(data) ) __utils__['cloud.fire_event']( 'event', 'created instance', 'salt/cloud/{0}/created'.format(vm_['name']), args=__utils__['cloud.filter_event']('created', vm_, ['name', 'profile', 'provider', 'driver']), sock_dir=__opts__['sock_dir'], transport=__opts__['transport'] ) return ret def query(method='droplets', droplet_id=None, command=None, args=None, http_method='get'): ''' Make a web call to DigitalOcean ''' base_path = six.text_type(config.get_cloud_config_value( 'api_root', get_configured_provider(), __opts__, search_global=False, default='https://api.digitalocean.com/v2' )) path = '{0}/{1}/'.format(base_path, method) if droplet_id: path += '{0}/'.format(droplet_id) if command: path += command if not isinstance(args, dict): args = {} personal_access_token = config.get_cloud_config_value( 'personal_access_token', get_configured_provider(), __opts__, search_global=False ) data = salt.utils.json.dumps(args) requester = getattr(requests, http_method) request = requester(path, data=data, headers={'Authorization': 'Bearer ' + personal_access_token, 'Content-Type': 'application/json'}) if request.status_code > 299: raise SaltCloudSystemExit( 'An error occurred while querying DigitalOcean. HTTP Code: {0} ' 'Error: \'{1}\''.format( request.status_code, # request.read() request.text ) ) log.debug(request.url) # success without data if request.status_code == 204: return True content = request.text result = salt.utils.json.loads(content) if result.get('status', '').lower() == 'error': raise SaltCloudSystemExit( pprint.pformat(result.get('error_message', {})) ) return result 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 show_instance(name, call=None): ''' Show the details from DigitalOcean concerning a droplet ''' if call != 'action': raise SaltCloudSystemExit( 'The show_instance action must be called with -a or --action.' ) node = _get_node(name) __utils__['cloud.cache_node'](node, __active_provider_name__, __opts__) return node def _get_node(name): attempts = 10 while attempts >= 0: try: return list_nodes_full(for_output=False)[name] except KeyError: attempts -= 1 log.debug( 'Failed to get the data for node \'%s\'. Remaining ' 'attempts: %s', name, attempts ) # Just a little delay between attempts... time.sleep(0.5) return {} def list_keypairs(call=None): ''' Return a dict of all available VM locations on the cloud provider with relevant data ''' if call != 'function': log.error( 'The list_keypairs function must be called with -f or --function.' ) return False fetch = True page = 1 ret = {} while fetch: items = query(method='account/keys', command='?page=' + six.text_type(page) + '&per_page=100') for key_pair in items['ssh_keys']: name = key_pair['name'] if name in ret: raise SaltCloudSystemExit( 'A duplicate key pair name, \'{0}\', was found in DigitalOcean\'s ' 'key pair list. Please change the key name stored by DigitalOcean. ' 'Be sure to adjust the value of \'ssh_key_file\' in your cloud ' 'profile or provider configuration, if necessary.'.format( name ) ) ret[name] = {} for item in six.iterkeys(key_pair): ret[name][item] = six.text_type(key_pair[item]) page += 1 try: fetch = 'next' in items['links']['pages'] except KeyError: fetch = False return ret def show_keypair(kwargs=None, call=None): ''' Show the details of an SSH keypair ''' if call != 'function': log.error( 'The show_keypair function must be called with -f or --function.' ) return False if not kwargs: kwargs = {} if 'keyname' not in kwargs: log.error('A keyname is required.') return False keypairs = list_keypairs(call='function') keyid = keypairs[kwargs['keyname']]['id'] log.debug('Key ID is %s', keyid) details = query(method='account/keys', command=keyid) return details def import_keypair(kwargs=None, call=None): ''' Upload public key to cloud provider. Similar to EC2 import_keypair. .. versionadded:: 2016.11.0 kwargs file(mandatory): public key file-name keyname(mandatory): public key name in the provider ''' with salt.utils.files.fopen(kwargs['file'], 'r') as public_key_filename: public_key_content = salt.utils.stringutils.to_unicode(public_key_filename.read()) digitalocean_kwargs = { 'name': kwargs['keyname'], 'public_key': public_key_content } created_result = create_key(digitalocean_kwargs, call=call) return created_result def remove_key(kwargs=None, call=None): ''' Delete public key ''' if call != 'function': log.error( 'The create_key function must be called with -f or --function.' ) return False try: result = query( method='account', command='keys/' + kwargs['id'], http_method='delete' ) except KeyError: log.info('`id` argument must be specified') return False return result def get_keyid(keyname): ''' Return the ID of the keyname ''' if not keyname: return None keypairs = list_keypairs(call='function') keyid = keypairs[keyname]['id'] if keyid: return keyid raise SaltCloudNotFound('The specified ssh key could not be found.') def destroy(name, call=None): ''' Destroy a node. Will check termination protection and warn if enabled. 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'] ) data = show_instance(name, call='action') node = query(method='droplets', droplet_id=data['id'], http_method='delete') ## This is all terribly optomistic: # vm_ = get_vm_config(name=name) # delete_dns_record = config.get_cloud_config_value( # 'delete_dns_record', vm_, __opts__, search_global=False, default=None, # ) # TODO: when _vm config data can be made available, we should honor the configuration settings, # but until then, we should assume stale DNS records are bad, and default behavior should be to # delete them if we can. When this is resolved, also resolve the comments a couple of lines below. delete_dns_record = True if not isinstance(delete_dns_record, bool): raise SaltCloudConfigError( '\'delete_dns_record\' should be a boolean value.' ) # When the "to do" a few lines up is resolved, remove these lines and use the if/else logic below. log.debug('Deleting DNS records for %s.', name) destroy_dns_records(name) # Until the "to do" from line 754 is taken care of, we don't need this logic. # if delete_dns_record: # log.debug('Deleting DNS records for %s.', name) # destroy_dns_records(name) # else: # log.debug('delete_dns_record : %s', delete_dns_record) # for line in pprint.pformat(dir()).splitlines(): # log.debug('delete context: %s', line) __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 node def post_dns_record(**kwargs): ''' Creates a DNS record for the given name if the domain is managed with DO. ''' if 'kwargs' in kwargs: # flatten kwargs if called via salt-cloud -f f_kwargs = kwargs['kwargs'] del kwargs['kwargs'] kwargs.update(f_kwargs) mandatory_kwargs = ('dns_domain', 'name', 'record_type', 'record_data') for i in mandatory_kwargs: if kwargs[i]: pass else: error = '{0}="{1}" ## all mandatory args must be provided: {2}'.format(i, kwargs[i], mandatory_kwargs) raise SaltInvocationError(error) domain = query(method='domains', droplet_id=kwargs['dns_domain']) if domain: result = query( method='domains', droplet_id=kwargs['dns_domain'], command='records', args={'type': kwargs['record_type'], 'name': kwargs['name'], 'data': kwargs['record_data']}, http_method='post' ) return result return False def destroy_dns_records(fqdn): ''' Deletes DNS records for the given hostname if the domain is managed with DO. ''' domain = '.'.join(fqdn.split('.')[-2:]) hostname = '.'.join(fqdn.split('.')[:-2]) # TODO: remove this when the todo on 754 is available try: response = query(method='domains', droplet_id=domain, command='records') except SaltCloudSystemExit: log.debug('Failed to find domains.') return False log.debug("found DNS records: %s", pprint.pformat(response)) records = response['domain_records'] if records: record_ids = [r['id'] for r in records if r['name'].decode() == hostname] log.debug("deleting DNS record IDs: %s", record_ids) for id_ in record_ids: try: log.info('deleting DNS record %s', id_) ret = query( method='domains', droplet_id=domain, command='records/{0}'.format(id_), http_method='delete' ) except SaltCloudSystemExit: log.error('failed to delete DNS domain %s record ID %s.', domain, hostname) log.debug('DNS deletion REST call returned: %s', pprint.pformat(ret)) return False def show_pricing(kwargs=None, call=None): ''' Show pricing for a particular profile. This is only an estimate, based on unofficial pricing sources. .. versionadded:: 2015.8.0 CLI Examples: .. code-block:: bash salt-cloud -f show_pricing my-digitalocean-config profile=my-profile ''' profile = __opts__['profiles'].get(kwargs['profile'], {}) if not profile: return {'Error': 'The requested profile was not found'} # Make sure the profile belongs to DigitalOcean provider = profile.get('provider', '0:0') comps = provider.split(':') if len(comps) < 2 or comps[1] != 'digitalocean': return {'Error': 'The requested profile does not belong to DigitalOcean'} raw = {} ret = {} sizes = avail_sizes() ret['per_hour'] = decimal.Decimal(sizes[profile['size']]['price_hourly']) ret['per_day'] = ret['per_hour'] * 24 ret['per_week'] = ret['per_day'] * 7 ret['per_month'] = decimal.Decimal(sizes[profile['size']]['price_monthly']) ret['per_year'] = ret['per_week'] * 52 if kwargs.get('raw', False): ret['_raw'] = raw return {profile['profile']: ret} def list_floating_ips(call=None): ''' Return a list of the floating ips that are on the provider .. versionadded:: 2016.3.0 CLI Examples: .. code-block:: bash salt-cloud -f list_floating_ips my-digitalocean-config ''' if call == 'action': raise SaltCloudSystemExit( 'The list_floating_ips function must be called with ' '-f or --function, or with the --list-floating-ips option' ) fetch = True page = 1 ret = {} while fetch: items = query(method='floating_ips', command='?page=' + six.text_type(page) + '&per_page=200') for floating_ip in items['floating_ips']: ret[floating_ip['ip']] = {} for item in six.iterkeys(floating_ip): ret[floating_ip['ip']][item] = floating_ip[item] page += 1 try: fetch = 'next' in items['links']['pages'] except KeyError: fetch = False return ret def show_floating_ip(kwargs=None, call=None): ''' Show the details of a floating IP .. versionadded:: 2016.3.0 CLI Examples: .. code-block:: bash salt-cloud -f show_floating_ip my-digitalocean-config floating_ip='45.55.96.47' ''' if call != 'function': log.error( 'The show_floating_ip function must be called with -f or --function.' ) return False if not kwargs: kwargs = {} if 'floating_ip' not in kwargs: log.error('A floating IP is required.') return False floating_ip = kwargs['floating_ip'] log.debug('Floating ip is %s', floating_ip) details = query(method='floating_ips', command=floating_ip) return details def create_floating_ip(kwargs=None, call=None): ''' Create a new floating IP .. versionadded:: 2016.3.0 CLI Examples: .. code-block:: bash salt-cloud -f create_floating_ip my-digitalocean-config region='NYC2' salt-cloud -f create_floating_ip my-digitalocean-config droplet_id='1234567' ''' if call != 'function': log.error( 'The create_floating_ip function must be called with -f or --function.' ) return False if not kwargs: kwargs = {} if 'droplet_id' in kwargs: result = query(method='floating_ips', args={'droplet_id': kwargs['droplet_id']}, http_method='post') return result elif 'region' in kwargs: result = query(method='floating_ips', args={'region': kwargs['region']}, http_method='post') return result else: log.error('A droplet_id or region is required.') return False def delete_floating_ip(kwargs=None, call=None): ''' Delete a floating IP .. versionadded:: 2016.3.0 CLI Examples: .. code-block:: bash salt-cloud -f delete_floating_ip my-digitalocean-config floating_ip='45.55.96.47' ''' if call != 'function': log.error( 'The delete_floating_ip function must be called with -f or --function.' ) return False if not kwargs: kwargs = {} if 'floating_ip' not in kwargs: log.error('A floating IP is required.') return False floating_ip = kwargs['floating_ip'] log.debug('Floating ip is %s', kwargs['floating_ip']) result = query(method='floating_ips', command=floating_ip, http_method='delete') return result def assign_floating_ip(kwargs=None, call=None): ''' Assign a floating IP .. versionadded:: 2016.3.0 CLI Examples: .. code-block:: bash salt-cloud -f assign_floating_ip my-digitalocean-config droplet_id=1234567 floating_ip='45.55.96.47' ''' if call != 'function': log.error( 'The assign_floating_ip function must be called with -f or --function.' ) return False if not kwargs: kwargs = {} if 'floating_ip' and 'droplet_id' not in kwargs: log.error('A floating IP and droplet_id is required.') return False result = query(method='floating_ips', command=kwargs['floating_ip'] + '/actions', args={'droplet_id': kwargs['droplet_id'], 'type': 'assign'}, http_method='post') return result def unassign_floating_ip(kwargs=None, call=None): ''' Unassign a floating IP .. versionadded:: 2016.3.0 CLI Examples: .. code-block:: bash salt-cloud -f unassign_floating_ip my-digitalocean-config floating_ip='45.55.96.47' ''' if call != 'function': log.error( 'The inassign_floating_ip function must be called with -f or --function.' ) return False if not kwargs: kwargs = {} if 'floating_ip' not in kwargs: log.error('A floating IP is required.') return False result = query(method='floating_ips', command=kwargs['floating_ip'] + '/actions', args={'type': 'unassign'}, http_method='post') return result def _list_nodes(full=False, for_output=False): ''' Helper function to format and parse node data. ''' fetch = True page = 1 ret = {} while fetch: items = query(method='droplets', command='?page=' + six.text_type(page) + '&per_page=200') for node in items['droplets']: name = node['name'] ret[name] = {} if full: ret[name] = _get_full_output(node, for_output=for_output) else: public_ips, private_ips = _get_ips(node['networks']) ret[name] = { 'id': node['id'], 'image': node['image']['name'], 'name': name, 'private_ips': private_ips, 'public_ips': public_ips, 'size': node['size_slug'], 'state': six.text_type(node['status']), } page += 1 try: fetch = 'next' in items['links']['pages'] except KeyError: fetch = False return ret def reboot(name, call=None): ''' Reboot a droplet in DigitalOcean. .. versionadded:: 2015.8.8 name The name of the droplet to restart. CLI Example: .. code-block:: bash salt-cloud -a reboot droplet_name ''' if call != 'action': raise SaltCloudSystemExit( 'The restart action must be called with -a or --action.' ) data = show_instance(name, call='action') if data.get('status') == 'off': return {'success': True, 'action': 'stop', 'status': 'off', 'msg': 'Machine is already off.'} ret = query(droplet_id=data['id'], command='actions', args={'type': 'reboot'}, http_method='post') return {'success': True, 'action': ret['action']['type'], 'state': ret['action']['status']} def start(name, call=None): ''' Start a droplet in DigitalOcean. .. versionadded:: 2015.8.8 name The name of the droplet to start. CLI Example: .. code-block:: bash salt-cloud -a start droplet_name ''' if call != 'action': raise SaltCloudSystemExit( 'The start action must be called with -a or --action.' ) data = show_instance(name, call='action') if data.get('status') == 'active': return {'success': True, 'action': 'start', 'status': 'active', 'msg': 'Machine is already running.'} ret = query(droplet_id=data['id'], command='actions', args={'type': 'power_on'}, http_method='post') return {'success': True, 'action': ret['action']['type'], 'state': ret['action']['status']} def stop(name, call=None): ''' Stop a droplet in DigitalOcean. .. versionadded:: 2015.8.8 name The name of the droplet to stop. CLI Example: .. code-block:: bash salt-cloud -a stop droplet_name ''' if call != 'action': raise SaltCloudSystemExit( 'The stop action must be called with -a or --action.' ) data = show_instance(name, call='action') if data.get('status') == 'off': return {'success': True, 'action': 'stop', 'status': 'off', 'msg': 'Machine is already off.'} ret = query(droplet_id=data['id'], command='actions', args={'type': 'shutdown'}, http_method='post') return {'success': True, 'action': ret['action']['type'], 'state': ret['action']['status']} def _get_full_output(node, for_output=False): ''' Helper function for _list_nodes to loop through all node information. Returns a dictionary containing the full information of a node. ''' ret = {} for item in six.iterkeys(node): value = node[item] if value is not None and for_output: value = six.text_type(value) ret[item] = value return ret def _get_ips(networks): ''' Helper function for list_nodes. Returns public and private ip lists based on a given network dictionary. ''' v4s = networks.get('v4') v6s = networks.get('v6') public_ips = [] private_ips = [] if v4s: for item in v4s: ip_type = item.get('type') ip_address = item.get('ip_address') if ip_type == 'public': public_ips.append(ip_address) if ip_type == 'private': private_ips.append(ip_address) if v6s: for item in v6s: ip_type = item.get('type') ip_address = item.get('ip_address') if ip_type == 'public': public_ips.append(ip_address) if ip_type == 'private': private_ips.append(ip_address) return public_ips, private_ips
saltstack/salt
salt/cloud/clouds/digitalocean.py
get_keyid
python
def get_keyid(keyname): ''' Return the ID of the keyname ''' if not keyname: return None keypairs = list_keypairs(call='function') keyid = keypairs[keyname]['id'] if keyid: return keyid raise SaltCloudNotFound('The specified ssh key could not be found.')
Return the ID of the keyname
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/digitalocean.py#L791-L801
[ "def list_keypairs(call=None):\n '''\n Return a dict of all available VM locations on the cloud provider with\n relevant data\n '''\n if call != 'function':\n log.error(\n 'The list_keypairs function must be called with -f or --function.'\n )\n return False\n\n fetch = True\n page = 1\n ret = {}\n\n while fetch:\n items = query(method='account/keys', command='?page=' + six.text_type(page) +\n '&per_page=100')\n\n for key_pair in items['ssh_keys']:\n name = key_pair['name']\n if name in ret:\n raise SaltCloudSystemExit(\n 'A duplicate key pair name, \\'{0}\\', was found in DigitalOcean\\'s '\n 'key pair list. Please change the key name stored by DigitalOcean. '\n 'Be sure to adjust the value of \\'ssh_key_file\\' in your cloud '\n 'profile or provider configuration, if necessary.'.format(\n name\n )\n )\n ret[name] = {}\n for item in six.iterkeys(key_pair):\n ret[name][item] = six.text_type(key_pair[item])\n\n page += 1\n try:\n fetch = 'next' in items['links']['pages']\n except KeyError:\n fetch = False\n\n return ret\n" ]
# -*- coding: utf-8 -*- ''' DigitalOcean Cloud Module ========================= The DigitalOcean cloud module is used to control access to the DigitalOcean VPS system. Use of this module requires a requires a ``personal_access_token``, an ``ssh_key_file``, and at least one SSH key name in ``ssh_key_names``. More ``ssh_key_names`` can be added by separating each key with a comma. The ``personal_access_token`` can be found in the DigitalOcean web interface in the "Apps & API" section. The SSH key name can be found under the "SSH Keys" section. .. code-block:: yaml # Note: This example is for /etc/salt/cloud.providers or any file in the # /etc/salt/cloud.providers.d/ directory. my-digital-ocean-config: personal_access_token: xxx ssh_key_file: /path/to/ssh/key/file ssh_key_names: my-key-name,my-key-name-2 driver: digitalocean :depends: requests ''' # Import Python Libs from __future__ import absolute_import, print_function, unicode_literals import decimal import logging import os import pprint import time # Import Salt Libs import salt.utils.cloud import salt.utils.files import salt.utils.json import salt.utils.stringutils import salt.config as config from salt.exceptions import ( SaltCloudConfigError, SaltInvocationError, SaltCloudNotFound, SaltCloudSystemExit, SaltCloudExecutionFailure, SaltCloudExecutionTimeout ) from salt.ext import six from salt.ext.six.moves import zip # Import Third Party Libs try: import requests HAS_REQUESTS = True except ImportError: HAS_REQUESTS = False # Get logging started log = logging.getLogger(__name__) __virtualname__ = 'digitalocean' __virtual_aliases__ = ('digital_ocean', 'do') # Only load in this module if the DIGITALOCEAN configurations are in place def __virtual__(): ''' Check for DigitalOcean 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=__opts__, provider=__active_provider_name__ or __virtualname__, aliases=__virtual_aliases__, required_keys=('personal_access_token',) ) def get_dependencies(): ''' Warn if dependencies aren't met. ''' return config.check_driver_dependencies( __virtualname__, {'requests': HAS_REQUESTS} ) def avail_locations(call=None): ''' Return a dict of all available VM locations on the cloud provider with relevant data ''' if call == 'action': raise SaltCloudSystemExit( 'The avail_locations function must be called with ' '-f or --function, or with the --list-locations option' ) items = query(method='regions') ret = {} for region in items['regions']: ret[region['name']] = {} for item in six.iterkeys(region): ret[region['name']][item] = six.text_type(region[item]) return ret def avail_images(call=None): ''' Return a list of the images that are on the provider ''' if call == 'action': raise SaltCloudSystemExit( 'The avail_images function must be called with ' '-f or --function, or with the --list-images option' ) fetch = True page = 1 ret = {} while fetch: items = query(method='images', command='?page=' + six.text_type(page) + '&per_page=200') for image in items['images']: ret[image['name']] = {} for item in six.iterkeys(image): ret[image['name']][item] = image[item] page += 1 try: fetch = 'next' in items['links']['pages'] except KeyError: fetch = False return ret def avail_sizes(call=None): ''' Return a list of the image sizes that are on the provider ''' if call == 'action': raise SaltCloudSystemExit( 'The avail_sizes function must be called with ' '-f or --function, or with the --list-sizes option' ) items = query(method='sizes', command='?per_page=100') ret = {} for size in items['sizes']: ret[size['slug']] = {} for item in six.iterkeys(size): ret[size['slug']][item] = six.text_type(size[item]) 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.' ) return _list_nodes() def list_nodes_full(call=None, for_output=True): ''' 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.' ) return _list_nodes(full=True, for_output=for_output) 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('function'), __opts__['query.selection'], call, ) def get_image(vm_): ''' Return the image object to use ''' images = avail_images() vm_image = config.get_cloud_config_value( 'image', vm_, __opts__, search_global=False ) if not isinstance(vm_image, six.string_types): vm_image = six.text_type(vm_image) for image in images: if vm_image in (images[image]['name'], images[image]['slug'], images[image]['id']): if images[image]['slug'] is not None: return images[image]['slug'] return int(images[image]['id']) raise SaltCloudNotFound( 'The specified image, \'{0}\', could not be found.'.format(vm_image) ) def get_size(vm_): ''' Return the VM's size. Used by create_node(). ''' sizes = avail_sizes() vm_size = six.text_type(config.get_cloud_config_value( 'size', vm_, __opts__, search_global=False )) for size in sizes: if vm_size.lower() == sizes[size]['slug']: return sizes[size]['slug'] raise SaltCloudNotFound( 'The specified size, \'{0}\', could not be found.'.format(vm_size) ) def get_location(vm_): ''' Return the VM's location ''' locations = avail_locations() vm_location = six.text_type(config.get_cloud_config_value( 'location', vm_, __opts__, search_global=False )) for location in locations: if vm_location in (locations[location]['name'], locations[location]['slug']): return locations[location]['slug'] raise SaltCloudNotFound( 'The specified location, \'{0}\', could not be found.'.format( vm_location ) ) def create_node(args): ''' Create a node ''' node = query(method='droplets', args=args, http_method='post') return node 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 'digitalocean', vm_['profile'], vm_=vm_) is False: return False except AttributeError: pass __utils__['cloud.fire_event']( 'event', 'starting create', 'salt/cloud/{0}/creating'.format(vm_['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', vm_['name']) kwargs = { 'name': vm_['name'], 'size': get_size(vm_), 'image': get_image(vm_), 'region': get_location(vm_), 'ssh_keys': [], 'tags': [] } # backwards compat ssh_key_name = config.get_cloud_config_value( 'ssh_key_name', vm_, __opts__, search_global=False ) if ssh_key_name: kwargs['ssh_keys'].append(get_keyid(ssh_key_name)) ssh_key_names = config.get_cloud_config_value( 'ssh_key_names', vm_, __opts__, search_global=False, default=False ) if ssh_key_names: for key in ssh_key_names.split(','): kwargs['ssh_keys'].append(get_keyid(key)) key_filename = config.get_cloud_config_value( 'ssh_key_file', vm_, __opts__, search_global=False, default=None ) if key_filename is not None and not os.path.isfile(key_filename): raise SaltCloudConfigError( 'The defined key_filename \'{0}\' does not exist'.format( key_filename ) ) if not __opts__.get('ssh_agent', False) and key_filename is None: raise SaltCloudConfigError( 'The DigitalOcean driver requires an ssh_key_file and an ssh_key_name ' 'because it does not supply a root password upon building the server.' ) ssh_interface = config.get_cloud_config_value( 'ssh_interface', vm_, __opts__, search_global=False, default='public' ) if ssh_interface in ['private', 'public']: log.info("ssh_interface: Setting interface for ssh to %s", ssh_interface) kwargs['ssh_interface'] = ssh_interface else: raise SaltCloudConfigError( "The DigitalOcean driver requires ssh_interface to be defined as 'public' or 'private'." ) private_networking = config.get_cloud_config_value( 'private_networking', vm_, __opts__, search_global=False, default=None, ) if private_networking is not None: if not isinstance(private_networking, bool): raise SaltCloudConfigError("'private_networking' should be a boolean value.") kwargs['private_networking'] = private_networking if not private_networking and ssh_interface == 'private': raise SaltCloudConfigError( "The DigitalOcean driver requires ssh_interface if defined as 'private' " "then private_networking should be set as 'True'." ) backups_enabled = config.get_cloud_config_value( 'backups_enabled', vm_, __opts__, search_global=False, default=None, ) if backups_enabled is not None: if not isinstance(backups_enabled, bool): raise SaltCloudConfigError("'backups_enabled' should be a boolean value.") kwargs['backups'] = backups_enabled ipv6 = config.get_cloud_config_value( 'ipv6', vm_, __opts__, search_global=False, default=None, ) if ipv6 is not None: if not isinstance(ipv6, bool): raise SaltCloudConfigError("'ipv6' should be a boolean value.") kwargs['ipv6'] = ipv6 monitoring = config.get_cloud_config_value( 'monitoring', vm_, __opts__, search_global=False, default=None, ) if monitoring is not None: if not isinstance(monitoring, bool): raise SaltCloudConfigError("'monitoring' should be a boolean value.") kwargs['monitoring'] = monitoring kwargs['tags'] = config.get_cloud_config_value( 'tags', vm_, __opts__, search_global=False, default=False ) userdata_file = config.get_cloud_config_value( 'userdata_file', vm_, __opts__, search_global=False, default=None ) if userdata_file is not None: try: with salt.utils.files.fopen(userdata_file, 'r') as fp_: kwargs['user_data'] = salt.utils.cloud.userdata_template( __opts__, vm_, salt.utils.stringutils.to_unicode(fp_.read()) ) except Exception as exc: log.exception( 'Failed to read userdata from %s: %s', userdata_file, exc) create_dns_record = config.get_cloud_config_value( 'create_dns_record', vm_, __opts__, search_global=False, default=None, ) if create_dns_record: log.info('create_dns_record: will attempt to write DNS records') default_dns_domain = None dns_domain_name = vm_['name'].split('.') if len(dns_domain_name) > 2: log.debug('create_dns_record: inferring default dns_hostname, dns_domain from minion name as FQDN') default_dns_hostname = '.'.join(dns_domain_name[:-2]) default_dns_domain = '.'.join(dns_domain_name[-2:]) else: log.debug("create_dns_record: can't infer dns_domain from %s", vm_['name']) default_dns_hostname = dns_domain_name[0] dns_hostname = config.get_cloud_config_value( 'dns_hostname', vm_, __opts__, search_global=False, default=default_dns_hostname, ) dns_domain = config.get_cloud_config_value( 'dns_domain', vm_, __opts__, search_global=False, default=default_dns_domain, ) if dns_hostname and dns_domain: log.info('create_dns_record: using dns_hostname="%s", dns_domain="%s"', dns_hostname, dns_domain) __add_dns_addr__ = lambda t, d: post_dns_record(dns_domain=dns_domain, name=dns_hostname, record_type=t, record_data=d) log.debug('create_dns_record: %s', __add_dns_addr__) else: log.error('create_dns_record: could not determine dns_hostname and/or dns_domain') raise SaltCloudConfigError( '\'create_dns_record\' must be a dict specifying "domain" ' 'and "hostname" or the minion name must be an FQDN.' ) __utils__['cloud.fire_event']( 'event', 'requesting instance', 'salt/cloud/{0}/requesting'.format(vm_['name']), args=__utils__['cloud.filter_event']('requesting', kwargs, list(kwargs)), sock_dir=__opts__['sock_dir'], transport=__opts__['transport'] ) try: ret = create_node(kwargs) except Exception as exc: log.error( 'Error creating %s on DIGITALOCEAN\n\n' 'The following exception was thrown when trying to ' 'run the initial deployment: %s', vm_['name'], exc, # Show the traceback if the debug logging level is enabled exc_info_on_loglevel=logging.DEBUG ) return False def __query_node_data(vm_name): data = show_instance(vm_name, 'action') if not data: # Trigger an error in the wait_for_ip function return False if data['networks'].get('v4'): for network in data['networks']['v4']: if network['type'] == 'public': return data return False try: data = salt.utils.cloud.wait_for_ip( __query_node_data, update_args=(vm_['name'],), timeout=config.get_cloud_config_value( 'wait_for_ip_timeout', vm_, __opts__, default=10 * 60), interval=config.get_cloud_config_value( 'wait_for_ip_interval', vm_, __opts__, default=10), ) except (SaltCloudExecutionTimeout, SaltCloudExecutionFailure) as exc: try: # It might be already up, let's destroy it! destroy(vm_['name']) except SaltCloudSystemExit: pass finally: raise SaltCloudSystemExit(six.text_type(exc)) if not vm_.get('ssh_host'): vm_['ssh_host'] = None # add DNS records, set ssh_host, default to first found IP, preferring IPv4 for ssh bootstrap script target addr_families, dns_arec_types = (('v4', 'v6'), ('A', 'AAAA')) arec_map = dict(list(zip(addr_families, dns_arec_types))) for facing, addr_family, ip_address in [(net['type'], family, net['ip_address']) for family in addr_families for net in data['networks'][family]]: log.info('found %s IP%s interface for "%s"', facing, addr_family, ip_address) dns_rec_type = arec_map[addr_family] if facing == 'public': if create_dns_record: __add_dns_addr__(dns_rec_type, ip_address) if facing == ssh_interface: if not vm_['ssh_host']: vm_['ssh_host'] = ip_address if vm_['ssh_host'] is None: raise SaltCloudSystemExit( 'No suitable IP addresses found for ssh minion bootstrapping: {0}'.format(repr(data['networks'])) ) log.debug( 'Found public IP address to use for ssh minion bootstrapping: %s', vm_['ssh_host'] ) vm_['key_filename'] = key_filename ret = __utils__['cloud.bootstrap'](vm_, __opts__) ret.update(data) log.info('Created Cloud VM \'%s\'', vm_['name']) log.debug( '\'%s\' VM creation details:\n%s', vm_['name'], pprint.pformat(data) ) __utils__['cloud.fire_event']( 'event', 'created instance', 'salt/cloud/{0}/created'.format(vm_['name']), args=__utils__['cloud.filter_event']('created', vm_, ['name', 'profile', 'provider', 'driver']), sock_dir=__opts__['sock_dir'], transport=__opts__['transport'] ) return ret def query(method='droplets', droplet_id=None, command=None, args=None, http_method='get'): ''' Make a web call to DigitalOcean ''' base_path = six.text_type(config.get_cloud_config_value( 'api_root', get_configured_provider(), __opts__, search_global=False, default='https://api.digitalocean.com/v2' )) path = '{0}/{1}/'.format(base_path, method) if droplet_id: path += '{0}/'.format(droplet_id) if command: path += command if not isinstance(args, dict): args = {} personal_access_token = config.get_cloud_config_value( 'personal_access_token', get_configured_provider(), __opts__, search_global=False ) data = salt.utils.json.dumps(args) requester = getattr(requests, http_method) request = requester(path, data=data, headers={'Authorization': 'Bearer ' + personal_access_token, 'Content-Type': 'application/json'}) if request.status_code > 299: raise SaltCloudSystemExit( 'An error occurred while querying DigitalOcean. HTTP Code: {0} ' 'Error: \'{1}\''.format( request.status_code, # request.read() request.text ) ) log.debug(request.url) # success without data if request.status_code == 204: return True content = request.text result = salt.utils.json.loads(content) if result.get('status', '').lower() == 'error': raise SaltCloudSystemExit( pprint.pformat(result.get('error_message', {})) ) return result 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 show_instance(name, call=None): ''' Show the details from DigitalOcean concerning a droplet ''' if call != 'action': raise SaltCloudSystemExit( 'The show_instance action must be called with -a or --action.' ) node = _get_node(name) __utils__['cloud.cache_node'](node, __active_provider_name__, __opts__) return node def _get_node(name): attempts = 10 while attempts >= 0: try: return list_nodes_full(for_output=False)[name] except KeyError: attempts -= 1 log.debug( 'Failed to get the data for node \'%s\'. Remaining ' 'attempts: %s', name, attempts ) # Just a little delay between attempts... time.sleep(0.5) return {} def list_keypairs(call=None): ''' Return a dict of all available VM locations on the cloud provider with relevant data ''' if call != 'function': log.error( 'The list_keypairs function must be called with -f or --function.' ) return False fetch = True page = 1 ret = {} while fetch: items = query(method='account/keys', command='?page=' + six.text_type(page) + '&per_page=100') for key_pair in items['ssh_keys']: name = key_pair['name'] if name in ret: raise SaltCloudSystemExit( 'A duplicate key pair name, \'{0}\', was found in DigitalOcean\'s ' 'key pair list. Please change the key name stored by DigitalOcean. ' 'Be sure to adjust the value of \'ssh_key_file\' in your cloud ' 'profile or provider configuration, if necessary.'.format( name ) ) ret[name] = {} for item in six.iterkeys(key_pair): ret[name][item] = six.text_type(key_pair[item]) page += 1 try: fetch = 'next' in items['links']['pages'] except KeyError: fetch = False return ret def show_keypair(kwargs=None, call=None): ''' Show the details of an SSH keypair ''' if call != 'function': log.error( 'The show_keypair function must be called with -f or --function.' ) return False if not kwargs: kwargs = {} if 'keyname' not in kwargs: log.error('A keyname is required.') return False keypairs = list_keypairs(call='function') keyid = keypairs[kwargs['keyname']]['id'] log.debug('Key ID is %s', keyid) details = query(method='account/keys', command=keyid) return details def import_keypair(kwargs=None, call=None): ''' Upload public key to cloud provider. Similar to EC2 import_keypair. .. versionadded:: 2016.11.0 kwargs file(mandatory): public key file-name keyname(mandatory): public key name in the provider ''' with salt.utils.files.fopen(kwargs['file'], 'r') as public_key_filename: public_key_content = salt.utils.stringutils.to_unicode(public_key_filename.read()) digitalocean_kwargs = { 'name': kwargs['keyname'], 'public_key': public_key_content } created_result = create_key(digitalocean_kwargs, call=call) return created_result def create_key(kwargs=None, call=None): ''' Upload a public key ''' if call != 'function': log.error( 'The create_key function must be called with -f or --function.' ) return False try: result = query( method='account', command='keys', args={'name': kwargs['name'], 'public_key': kwargs['public_key']}, http_method='post' ) except KeyError: log.info('`name` and `public_key` arguments must be specified') return False return result def remove_key(kwargs=None, call=None): ''' Delete public key ''' if call != 'function': log.error( 'The create_key function must be called with -f or --function.' ) return False try: result = query( method='account', command='keys/' + kwargs['id'], http_method='delete' ) except KeyError: log.info('`id` argument must be specified') return False return result def destroy(name, call=None): ''' Destroy a node. Will check termination protection and warn if enabled. 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'] ) data = show_instance(name, call='action') node = query(method='droplets', droplet_id=data['id'], http_method='delete') ## This is all terribly optomistic: # vm_ = get_vm_config(name=name) # delete_dns_record = config.get_cloud_config_value( # 'delete_dns_record', vm_, __opts__, search_global=False, default=None, # ) # TODO: when _vm config data can be made available, we should honor the configuration settings, # but until then, we should assume stale DNS records are bad, and default behavior should be to # delete them if we can. When this is resolved, also resolve the comments a couple of lines below. delete_dns_record = True if not isinstance(delete_dns_record, bool): raise SaltCloudConfigError( '\'delete_dns_record\' should be a boolean value.' ) # When the "to do" a few lines up is resolved, remove these lines and use the if/else logic below. log.debug('Deleting DNS records for %s.', name) destroy_dns_records(name) # Until the "to do" from line 754 is taken care of, we don't need this logic. # if delete_dns_record: # log.debug('Deleting DNS records for %s.', name) # destroy_dns_records(name) # else: # log.debug('delete_dns_record : %s', delete_dns_record) # for line in pprint.pformat(dir()).splitlines(): # log.debug('delete context: %s', line) __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 node def post_dns_record(**kwargs): ''' Creates a DNS record for the given name if the domain is managed with DO. ''' if 'kwargs' in kwargs: # flatten kwargs if called via salt-cloud -f f_kwargs = kwargs['kwargs'] del kwargs['kwargs'] kwargs.update(f_kwargs) mandatory_kwargs = ('dns_domain', 'name', 'record_type', 'record_data') for i in mandatory_kwargs: if kwargs[i]: pass else: error = '{0}="{1}" ## all mandatory args must be provided: {2}'.format(i, kwargs[i], mandatory_kwargs) raise SaltInvocationError(error) domain = query(method='domains', droplet_id=kwargs['dns_domain']) if domain: result = query( method='domains', droplet_id=kwargs['dns_domain'], command='records', args={'type': kwargs['record_type'], 'name': kwargs['name'], 'data': kwargs['record_data']}, http_method='post' ) return result return False def destroy_dns_records(fqdn): ''' Deletes DNS records for the given hostname if the domain is managed with DO. ''' domain = '.'.join(fqdn.split('.')[-2:]) hostname = '.'.join(fqdn.split('.')[:-2]) # TODO: remove this when the todo on 754 is available try: response = query(method='domains', droplet_id=domain, command='records') except SaltCloudSystemExit: log.debug('Failed to find domains.') return False log.debug("found DNS records: %s", pprint.pformat(response)) records = response['domain_records'] if records: record_ids = [r['id'] for r in records if r['name'].decode() == hostname] log.debug("deleting DNS record IDs: %s", record_ids) for id_ in record_ids: try: log.info('deleting DNS record %s', id_) ret = query( method='domains', droplet_id=domain, command='records/{0}'.format(id_), http_method='delete' ) except SaltCloudSystemExit: log.error('failed to delete DNS domain %s record ID %s.', domain, hostname) log.debug('DNS deletion REST call returned: %s', pprint.pformat(ret)) return False def show_pricing(kwargs=None, call=None): ''' Show pricing for a particular profile. This is only an estimate, based on unofficial pricing sources. .. versionadded:: 2015.8.0 CLI Examples: .. code-block:: bash salt-cloud -f show_pricing my-digitalocean-config profile=my-profile ''' profile = __opts__['profiles'].get(kwargs['profile'], {}) if not profile: return {'Error': 'The requested profile was not found'} # Make sure the profile belongs to DigitalOcean provider = profile.get('provider', '0:0') comps = provider.split(':') if len(comps) < 2 or comps[1] != 'digitalocean': return {'Error': 'The requested profile does not belong to DigitalOcean'} raw = {} ret = {} sizes = avail_sizes() ret['per_hour'] = decimal.Decimal(sizes[profile['size']]['price_hourly']) ret['per_day'] = ret['per_hour'] * 24 ret['per_week'] = ret['per_day'] * 7 ret['per_month'] = decimal.Decimal(sizes[profile['size']]['price_monthly']) ret['per_year'] = ret['per_week'] * 52 if kwargs.get('raw', False): ret['_raw'] = raw return {profile['profile']: ret} def list_floating_ips(call=None): ''' Return a list of the floating ips that are on the provider .. versionadded:: 2016.3.0 CLI Examples: .. code-block:: bash salt-cloud -f list_floating_ips my-digitalocean-config ''' if call == 'action': raise SaltCloudSystemExit( 'The list_floating_ips function must be called with ' '-f or --function, or with the --list-floating-ips option' ) fetch = True page = 1 ret = {} while fetch: items = query(method='floating_ips', command='?page=' + six.text_type(page) + '&per_page=200') for floating_ip in items['floating_ips']: ret[floating_ip['ip']] = {} for item in six.iterkeys(floating_ip): ret[floating_ip['ip']][item] = floating_ip[item] page += 1 try: fetch = 'next' in items['links']['pages'] except KeyError: fetch = False return ret def show_floating_ip(kwargs=None, call=None): ''' Show the details of a floating IP .. versionadded:: 2016.3.0 CLI Examples: .. code-block:: bash salt-cloud -f show_floating_ip my-digitalocean-config floating_ip='45.55.96.47' ''' if call != 'function': log.error( 'The show_floating_ip function must be called with -f or --function.' ) return False if not kwargs: kwargs = {} if 'floating_ip' not in kwargs: log.error('A floating IP is required.') return False floating_ip = kwargs['floating_ip'] log.debug('Floating ip is %s', floating_ip) details = query(method='floating_ips', command=floating_ip) return details def create_floating_ip(kwargs=None, call=None): ''' Create a new floating IP .. versionadded:: 2016.3.0 CLI Examples: .. code-block:: bash salt-cloud -f create_floating_ip my-digitalocean-config region='NYC2' salt-cloud -f create_floating_ip my-digitalocean-config droplet_id='1234567' ''' if call != 'function': log.error( 'The create_floating_ip function must be called with -f or --function.' ) return False if not kwargs: kwargs = {} if 'droplet_id' in kwargs: result = query(method='floating_ips', args={'droplet_id': kwargs['droplet_id']}, http_method='post') return result elif 'region' in kwargs: result = query(method='floating_ips', args={'region': kwargs['region']}, http_method='post') return result else: log.error('A droplet_id or region is required.') return False def delete_floating_ip(kwargs=None, call=None): ''' Delete a floating IP .. versionadded:: 2016.3.0 CLI Examples: .. code-block:: bash salt-cloud -f delete_floating_ip my-digitalocean-config floating_ip='45.55.96.47' ''' if call != 'function': log.error( 'The delete_floating_ip function must be called with -f or --function.' ) return False if not kwargs: kwargs = {} if 'floating_ip' not in kwargs: log.error('A floating IP is required.') return False floating_ip = kwargs['floating_ip'] log.debug('Floating ip is %s', kwargs['floating_ip']) result = query(method='floating_ips', command=floating_ip, http_method='delete') return result def assign_floating_ip(kwargs=None, call=None): ''' Assign a floating IP .. versionadded:: 2016.3.0 CLI Examples: .. code-block:: bash salt-cloud -f assign_floating_ip my-digitalocean-config droplet_id=1234567 floating_ip='45.55.96.47' ''' if call != 'function': log.error( 'The assign_floating_ip function must be called with -f or --function.' ) return False if not kwargs: kwargs = {} if 'floating_ip' and 'droplet_id' not in kwargs: log.error('A floating IP and droplet_id is required.') return False result = query(method='floating_ips', command=kwargs['floating_ip'] + '/actions', args={'droplet_id': kwargs['droplet_id'], 'type': 'assign'}, http_method='post') return result def unassign_floating_ip(kwargs=None, call=None): ''' Unassign a floating IP .. versionadded:: 2016.3.0 CLI Examples: .. code-block:: bash salt-cloud -f unassign_floating_ip my-digitalocean-config floating_ip='45.55.96.47' ''' if call != 'function': log.error( 'The inassign_floating_ip function must be called with -f or --function.' ) return False if not kwargs: kwargs = {} if 'floating_ip' not in kwargs: log.error('A floating IP is required.') return False result = query(method='floating_ips', command=kwargs['floating_ip'] + '/actions', args={'type': 'unassign'}, http_method='post') return result def _list_nodes(full=False, for_output=False): ''' Helper function to format and parse node data. ''' fetch = True page = 1 ret = {} while fetch: items = query(method='droplets', command='?page=' + six.text_type(page) + '&per_page=200') for node in items['droplets']: name = node['name'] ret[name] = {} if full: ret[name] = _get_full_output(node, for_output=for_output) else: public_ips, private_ips = _get_ips(node['networks']) ret[name] = { 'id': node['id'], 'image': node['image']['name'], 'name': name, 'private_ips': private_ips, 'public_ips': public_ips, 'size': node['size_slug'], 'state': six.text_type(node['status']), } page += 1 try: fetch = 'next' in items['links']['pages'] except KeyError: fetch = False return ret def reboot(name, call=None): ''' Reboot a droplet in DigitalOcean. .. versionadded:: 2015.8.8 name The name of the droplet to restart. CLI Example: .. code-block:: bash salt-cloud -a reboot droplet_name ''' if call != 'action': raise SaltCloudSystemExit( 'The restart action must be called with -a or --action.' ) data = show_instance(name, call='action') if data.get('status') == 'off': return {'success': True, 'action': 'stop', 'status': 'off', 'msg': 'Machine is already off.'} ret = query(droplet_id=data['id'], command='actions', args={'type': 'reboot'}, http_method='post') return {'success': True, 'action': ret['action']['type'], 'state': ret['action']['status']} def start(name, call=None): ''' Start a droplet in DigitalOcean. .. versionadded:: 2015.8.8 name The name of the droplet to start. CLI Example: .. code-block:: bash salt-cloud -a start droplet_name ''' if call != 'action': raise SaltCloudSystemExit( 'The start action must be called with -a or --action.' ) data = show_instance(name, call='action') if data.get('status') == 'active': return {'success': True, 'action': 'start', 'status': 'active', 'msg': 'Machine is already running.'} ret = query(droplet_id=data['id'], command='actions', args={'type': 'power_on'}, http_method='post') return {'success': True, 'action': ret['action']['type'], 'state': ret['action']['status']} def stop(name, call=None): ''' Stop a droplet in DigitalOcean. .. versionadded:: 2015.8.8 name The name of the droplet to stop. CLI Example: .. code-block:: bash salt-cloud -a stop droplet_name ''' if call != 'action': raise SaltCloudSystemExit( 'The stop action must be called with -a or --action.' ) data = show_instance(name, call='action') if data.get('status') == 'off': return {'success': True, 'action': 'stop', 'status': 'off', 'msg': 'Machine is already off.'} ret = query(droplet_id=data['id'], command='actions', args={'type': 'shutdown'}, http_method='post') return {'success': True, 'action': ret['action']['type'], 'state': ret['action']['status']} def _get_full_output(node, for_output=False): ''' Helper function for _list_nodes to loop through all node information. Returns a dictionary containing the full information of a node. ''' ret = {} for item in six.iterkeys(node): value = node[item] if value is not None and for_output: value = six.text_type(value) ret[item] = value return ret def _get_ips(networks): ''' Helper function for list_nodes. Returns public and private ip lists based on a given network dictionary. ''' v4s = networks.get('v4') v6s = networks.get('v6') public_ips = [] private_ips = [] if v4s: for item in v4s: ip_type = item.get('type') ip_address = item.get('ip_address') if ip_type == 'public': public_ips.append(ip_address) if ip_type == 'private': private_ips.append(ip_address) if v6s: for item in v6s: ip_type = item.get('type') ip_address = item.get('ip_address') if ip_type == 'public': public_ips.append(ip_address) if ip_type == 'private': private_ips.append(ip_address) return public_ips, private_ips
saltstack/salt
salt/cloud/clouds/digitalocean.py
destroy
python
def destroy(name, call=None): ''' Destroy a node. Will check termination protection and warn if enabled. 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'] ) data = show_instance(name, call='action') node = query(method='droplets', droplet_id=data['id'], http_method='delete') ## This is all terribly optomistic: # vm_ = get_vm_config(name=name) # delete_dns_record = config.get_cloud_config_value( # 'delete_dns_record', vm_, __opts__, search_global=False, default=None, # ) # TODO: when _vm config data can be made available, we should honor the configuration settings, # but until then, we should assume stale DNS records are bad, and default behavior should be to # delete them if we can. When this is resolved, also resolve the comments a couple of lines below. delete_dns_record = True if not isinstance(delete_dns_record, bool): raise SaltCloudConfigError( '\'delete_dns_record\' should be a boolean value.' ) # When the "to do" a few lines up is resolved, remove these lines and use the if/else logic below. log.debug('Deleting DNS records for %s.', name) destroy_dns_records(name) # Until the "to do" from line 754 is taken care of, we don't need this logic. # if delete_dns_record: # log.debug('Deleting DNS records for %s.', name) # destroy_dns_records(name) # else: # log.debug('delete_dns_record : %s', delete_dns_record) # for line in pprint.pformat(dir()).splitlines(): # log.debug('delete context: %s', line) __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 node
Destroy a node. Will check termination protection and warn if enabled. CLI Example: .. code-block:: bash salt-cloud --destroy mymachine
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/digitalocean.py#L804-L871
[ "def query(method='droplets', droplet_id=None, command=None, args=None, http_method='get'):\n '''\n Make a web call to DigitalOcean\n '''\n base_path = six.text_type(config.get_cloud_config_value(\n 'api_root',\n get_configured_provider(),\n __opts__,\n search_global=False,\n default='https://api.digitalocean.com/v2'\n ))\n\n path = '{0}/{1}/'.format(base_path, method)\n\n if droplet_id:\n path += '{0}/'.format(droplet_id)\n\n if command:\n path += command\n\n if not isinstance(args, dict):\n args = {}\n\n personal_access_token = config.get_cloud_config_value(\n 'personal_access_token', get_configured_provider(), __opts__, search_global=False\n )\n\n data = salt.utils.json.dumps(args)\n\n requester = getattr(requests, http_method)\n request = requester(path, data=data, headers={'Authorization': 'Bearer ' + personal_access_token, 'Content-Type': 'application/json'})\n if request.status_code > 299:\n raise SaltCloudSystemExit(\n 'An error occurred while querying DigitalOcean. HTTP Code: {0} '\n 'Error: \\'{1}\\''.format(\n request.status_code,\n # request.read()\n request.text\n )\n )\n\n log.debug(request.url)\n\n # success without data\n if request.status_code == 204:\n return True\n\n content = request.text\n\n result = salt.utils.json.loads(content)\n if result.get('status', '').lower() == 'error':\n raise SaltCloudSystemExit(\n pprint.pformat(result.get('error_message', {}))\n )\n\n return result\n", "def show_instance(name, call=None):\n '''\n Show the details from DigitalOcean concerning a droplet\n '''\n if call != 'action':\n raise SaltCloudSystemExit(\n 'The show_instance action must be called with -a or --action.'\n )\n node = _get_node(name)\n __utils__['cloud.cache_node'](node, __active_provider_name__, __opts__)\n return node\n", "def destroy_dns_records(fqdn):\n '''\n Deletes DNS records for the given hostname if the domain is managed with DO.\n '''\n domain = '.'.join(fqdn.split('.')[-2:])\n hostname = '.'.join(fqdn.split('.')[:-2])\n # TODO: remove this when the todo on 754 is available\n try:\n response = query(method='domains', droplet_id=domain, command='records')\n except SaltCloudSystemExit:\n log.debug('Failed to find domains.')\n return False\n log.debug(\"found DNS records: %s\", pprint.pformat(response))\n records = response['domain_records']\n\n if records:\n record_ids = [r['id'] for r in records if r['name'].decode() == hostname]\n log.debug(\"deleting DNS record IDs: %s\", record_ids)\n for id_ in record_ids:\n try:\n log.info('deleting DNS record %s', id_)\n ret = query(\n method='domains',\n droplet_id=domain,\n command='records/{0}'.format(id_),\n http_method='delete'\n )\n except SaltCloudSystemExit:\n log.error('failed to delete DNS domain %s record ID %s.', domain, hostname)\n log.debug('DNS deletion REST call returned: %s', pprint.pformat(ret))\n\n return False\n" ]
# -*- coding: utf-8 -*- ''' DigitalOcean Cloud Module ========================= The DigitalOcean cloud module is used to control access to the DigitalOcean VPS system. Use of this module requires a requires a ``personal_access_token``, an ``ssh_key_file``, and at least one SSH key name in ``ssh_key_names``. More ``ssh_key_names`` can be added by separating each key with a comma. The ``personal_access_token`` can be found in the DigitalOcean web interface in the "Apps & API" section. The SSH key name can be found under the "SSH Keys" section. .. code-block:: yaml # Note: This example is for /etc/salt/cloud.providers or any file in the # /etc/salt/cloud.providers.d/ directory. my-digital-ocean-config: personal_access_token: xxx ssh_key_file: /path/to/ssh/key/file ssh_key_names: my-key-name,my-key-name-2 driver: digitalocean :depends: requests ''' # Import Python Libs from __future__ import absolute_import, print_function, unicode_literals import decimal import logging import os import pprint import time # Import Salt Libs import salt.utils.cloud import salt.utils.files import salt.utils.json import salt.utils.stringutils import salt.config as config from salt.exceptions import ( SaltCloudConfigError, SaltInvocationError, SaltCloudNotFound, SaltCloudSystemExit, SaltCloudExecutionFailure, SaltCloudExecutionTimeout ) from salt.ext import six from salt.ext.six.moves import zip # Import Third Party Libs try: import requests HAS_REQUESTS = True except ImportError: HAS_REQUESTS = False # Get logging started log = logging.getLogger(__name__) __virtualname__ = 'digitalocean' __virtual_aliases__ = ('digital_ocean', 'do') # Only load in this module if the DIGITALOCEAN configurations are in place def __virtual__(): ''' Check for DigitalOcean 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=__opts__, provider=__active_provider_name__ or __virtualname__, aliases=__virtual_aliases__, required_keys=('personal_access_token',) ) def get_dependencies(): ''' Warn if dependencies aren't met. ''' return config.check_driver_dependencies( __virtualname__, {'requests': HAS_REQUESTS} ) def avail_locations(call=None): ''' Return a dict of all available VM locations on the cloud provider with relevant data ''' if call == 'action': raise SaltCloudSystemExit( 'The avail_locations function must be called with ' '-f or --function, or with the --list-locations option' ) items = query(method='regions') ret = {} for region in items['regions']: ret[region['name']] = {} for item in six.iterkeys(region): ret[region['name']][item] = six.text_type(region[item]) return ret def avail_images(call=None): ''' Return a list of the images that are on the provider ''' if call == 'action': raise SaltCloudSystemExit( 'The avail_images function must be called with ' '-f or --function, or with the --list-images option' ) fetch = True page = 1 ret = {} while fetch: items = query(method='images', command='?page=' + six.text_type(page) + '&per_page=200') for image in items['images']: ret[image['name']] = {} for item in six.iterkeys(image): ret[image['name']][item] = image[item] page += 1 try: fetch = 'next' in items['links']['pages'] except KeyError: fetch = False return ret def avail_sizes(call=None): ''' Return a list of the image sizes that are on the provider ''' if call == 'action': raise SaltCloudSystemExit( 'The avail_sizes function must be called with ' '-f or --function, or with the --list-sizes option' ) items = query(method='sizes', command='?per_page=100') ret = {} for size in items['sizes']: ret[size['slug']] = {} for item in six.iterkeys(size): ret[size['slug']][item] = six.text_type(size[item]) 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.' ) return _list_nodes() def list_nodes_full(call=None, for_output=True): ''' 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.' ) return _list_nodes(full=True, for_output=for_output) 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('function'), __opts__['query.selection'], call, ) def get_image(vm_): ''' Return the image object to use ''' images = avail_images() vm_image = config.get_cloud_config_value( 'image', vm_, __opts__, search_global=False ) if not isinstance(vm_image, six.string_types): vm_image = six.text_type(vm_image) for image in images: if vm_image in (images[image]['name'], images[image]['slug'], images[image]['id']): if images[image]['slug'] is not None: return images[image]['slug'] return int(images[image]['id']) raise SaltCloudNotFound( 'The specified image, \'{0}\', could not be found.'.format(vm_image) ) def get_size(vm_): ''' Return the VM's size. Used by create_node(). ''' sizes = avail_sizes() vm_size = six.text_type(config.get_cloud_config_value( 'size', vm_, __opts__, search_global=False )) for size in sizes: if vm_size.lower() == sizes[size]['slug']: return sizes[size]['slug'] raise SaltCloudNotFound( 'The specified size, \'{0}\', could not be found.'.format(vm_size) ) def get_location(vm_): ''' Return the VM's location ''' locations = avail_locations() vm_location = six.text_type(config.get_cloud_config_value( 'location', vm_, __opts__, search_global=False )) for location in locations: if vm_location in (locations[location]['name'], locations[location]['slug']): return locations[location]['slug'] raise SaltCloudNotFound( 'The specified location, \'{0}\', could not be found.'.format( vm_location ) ) def create_node(args): ''' Create a node ''' node = query(method='droplets', args=args, http_method='post') return node 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 'digitalocean', vm_['profile'], vm_=vm_) is False: return False except AttributeError: pass __utils__['cloud.fire_event']( 'event', 'starting create', 'salt/cloud/{0}/creating'.format(vm_['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', vm_['name']) kwargs = { 'name': vm_['name'], 'size': get_size(vm_), 'image': get_image(vm_), 'region': get_location(vm_), 'ssh_keys': [], 'tags': [] } # backwards compat ssh_key_name = config.get_cloud_config_value( 'ssh_key_name', vm_, __opts__, search_global=False ) if ssh_key_name: kwargs['ssh_keys'].append(get_keyid(ssh_key_name)) ssh_key_names = config.get_cloud_config_value( 'ssh_key_names', vm_, __opts__, search_global=False, default=False ) if ssh_key_names: for key in ssh_key_names.split(','): kwargs['ssh_keys'].append(get_keyid(key)) key_filename = config.get_cloud_config_value( 'ssh_key_file', vm_, __opts__, search_global=False, default=None ) if key_filename is not None and not os.path.isfile(key_filename): raise SaltCloudConfigError( 'The defined key_filename \'{0}\' does not exist'.format( key_filename ) ) if not __opts__.get('ssh_agent', False) and key_filename is None: raise SaltCloudConfigError( 'The DigitalOcean driver requires an ssh_key_file and an ssh_key_name ' 'because it does not supply a root password upon building the server.' ) ssh_interface = config.get_cloud_config_value( 'ssh_interface', vm_, __opts__, search_global=False, default='public' ) if ssh_interface in ['private', 'public']: log.info("ssh_interface: Setting interface for ssh to %s", ssh_interface) kwargs['ssh_interface'] = ssh_interface else: raise SaltCloudConfigError( "The DigitalOcean driver requires ssh_interface to be defined as 'public' or 'private'." ) private_networking = config.get_cloud_config_value( 'private_networking', vm_, __opts__, search_global=False, default=None, ) if private_networking is not None: if not isinstance(private_networking, bool): raise SaltCloudConfigError("'private_networking' should be a boolean value.") kwargs['private_networking'] = private_networking if not private_networking and ssh_interface == 'private': raise SaltCloudConfigError( "The DigitalOcean driver requires ssh_interface if defined as 'private' " "then private_networking should be set as 'True'." ) backups_enabled = config.get_cloud_config_value( 'backups_enabled', vm_, __opts__, search_global=False, default=None, ) if backups_enabled is not None: if not isinstance(backups_enabled, bool): raise SaltCloudConfigError("'backups_enabled' should be a boolean value.") kwargs['backups'] = backups_enabled ipv6 = config.get_cloud_config_value( 'ipv6', vm_, __opts__, search_global=False, default=None, ) if ipv6 is not None: if not isinstance(ipv6, bool): raise SaltCloudConfigError("'ipv6' should be a boolean value.") kwargs['ipv6'] = ipv6 monitoring = config.get_cloud_config_value( 'monitoring', vm_, __opts__, search_global=False, default=None, ) if monitoring is not None: if not isinstance(monitoring, bool): raise SaltCloudConfigError("'monitoring' should be a boolean value.") kwargs['monitoring'] = monitoring kwargs['tags'] = config.get_cloud_config_value( 'tags', vm_, __opts__, search_global=False, default=False ) userdata_file = config.get_cloud_config_value( 'userdata_file', vm_, __opts__, search_global=False, default=None ) if userdata_file is not None: try: with salt.utils.files.fopen(userdata_file, 'r') as fp_: kwargs['user_data'] = salt.utils.cloud.userdata_template( __opts__, vm_, salt.utils.stringutils.to_unicode(fp_.read()) ) except Exception as exc: log.exception( 'Failed to read userdata from %s: %s', userdata_file, exc) create_dns_record = config.get_cloud_config_value( 'create_dns_record', vm_, __opts__, search_global=False, default=None, ) if create_dns_record: log.info('create_dns_record: will attempt to write DNS records') default_dns_domain = None dns_domain_name = vm_['name'].split('.') if len(dns_domain_name) > 2: log.debug('create_dns_record: inferring default dns_hostname, dns_domain from minion name as FQDN') default_dns_hostname = '.'.join(dns_domain_name[:-2]) default_dns_domain = '.'.join(dns_domain_name[-2:]) else: log.debug("create_dns_record: can't infer dns_domain from %s", vm_['name']) default_dns_hostname = dns_domain_name[0] dns_hostname = config.get_cloud_config_value( 'dns_hostname', vm_, __opts__, search_global=False, default=default_dns_hostname, ) dns_domain = config.get_cloud_config_value( 'dns_domain', vm_, __opts__, search_global=False, default=default_dns_domain, ) if dns_hostname and dns_domain: log.info('create_dns_record: using dns_hostname="%s", dns_domain="%s"', dns_hostname, dns_domain) __add_dns_addr__ = lambda t, d: post_dns_record(dns_domain=dns_domain, name=dns_hostname, record_type=t, record_data=d) log.debug('create_dns_record: %s', __add_dns_addr__) else: log.error('create_dns_record: could not determine dns_hostname and/or dns_domain') raise SaltCloudConfigError( '\'create_dns_record\' must be a dict specifying "domain" ' 'and "hostname" or the minion name must be an FQDN.' ) __utils__['cloud.fire_event']( 'event', 'requesting instance', 'salt/cloud/{0}/requesting'.format(vm_['name']), args=__utils__['cloud.filter_event']('requesting', kwargs, list(kwargs)), sock_dir=__opts__['sock_dir'], transport=__opts__['transport'] ) try: ret = create_node(kwargs) except Exception as exc: log.error( 'Error creating %s on DIGITALOCEAN\n\n' 'The following exception was thrown when trying to ' 'run the initial deployment: %s', vm_['name'], exc, # Show the traceback if the debug logging level is enabled exc_info_on_loglevel=logging.DEBUG ) return False def __query_node_data(vm_name): data = show_instance(vm_name, 'action') if not data: # Trigger an error in the wait_for_ip function return False if data['networks'].get('v4'): for network in data['networks']['v4']: if network['type'] == 'public': return data return False try: data = salt.utils.cloud.wait_for_ip( __query_node_data, update_args=(vm_['name'],), timeout=config.get_cloud_config_value( 'wait_for_ip_timeout', vm_, __opts__, default=10 * 60), interval=config.get_cloud_config_value( 'wait_for_ip_interval', vm_, __opts__, default=10), ) except (SaltCloudExecutionTimeout, SaltCloudExecutionFailure) as exc: try: # It might be already up, let's destroy it! destroy(vm_['name']) except SaltCloudSystemExit: pass finally: raise SaltCloudSystemExit(six.text_type(exc)) if not vm_.get('ssh_host'): vm_['ssh_host'] = None # add DNS records, set ssh_host, default to first found IP, preferring IPv4 for ssh bootstrap script target addr_families, dns_arec_types = (('v4', 'v6'), ('A', 'AAAA')) arec_map = dict(list(zip(addr_families, dns_arec_types))) for facing, addr_family, ip_address in [(net['type'], family, net['ip_address']) for family in addr_families for net in data['networks'][family]]: log.info('found %s IP%s interface for "%s"', facing, addr_family, ip_address) dns_rec_type = arec_map[addr_family] if facing == 'public': if create_dns_record: __add_dns_addr__(dns_rec_type, ip_address) if facing == ssh_interface: if not vm_['ssh_host']: vm_['ssh_host'] = ip_address if vm_['ssh_host'] is None: raise SaltCloudSystemExit( 'No suitable IP addresses found for ssh minion bootstrapping: {0}'.format(repr(data['networks'])) ) log.debug( 'Found public IP address to use for ssh minion bootstrapping: %s', vm_['ssh_host'] ) vm_['key_filename'] = key_filename ret = __utils__['cloud.bootstrap'](vm_, __opts__) ret.update(data) log.info('Created Cloud VM \'%s\'', vm_['name']) log.debug( '\'%s\' VM creation details:\n%s', vm_['name'], pprint.pformat(data) ) __utils__['cloud.fire_event']( 'event', 'created instance', 'salt/cloud/{0}/created'.format(vm_['name']), args=__utils__['cloud.filter_event']('created', vm_, ['name', 'profile', 'provider', 'driver']), sock_dir=__opts__['sock_dir'], transport=__opts__['transport'] ) return ret def query(method='droplets', droplet_id=None, command=None, args=None, http_method='get'): ''' Make a web call to DigitalOcean ''' base_path = six.text_type(config.get_cloud_config_value( 'api_root', get_configured_provider(), __opts__, search_global=False, default='https://api.digitalocean.com/v2' )) path = '{0}/{1}/'.format(base_path, method) if droplet_id: path += '{0}/'.format(droplet_id) if command: path += command if not isinstance(args, dict): args = {} personal_access_token = config.get_cloud_config_value( 'personal_access_token', get_configured_provider(), __opts__, search_global=False ) data = salt.utils.json.dumps(args) requester = getattr(requests, http_method) request = requester(path, data=data, headers={'Authorization': 'Bearer ' + personal_access_token, 'Content-Type': 'application/json'}) if request.status_code > 299: raise SaltCloudSystemExit( 'An error occurred while querying DigitalOcean. HTTP Code: {0} ' 'Error: \'{1}\''.format( request.status_code, # request.read() request.text ) ) log.debug(request.url) # success without data if request.status_code == 204: return True content = request.text result = salt.utils.json.loads(content) if result.get('status', '').lower() == 'error': raise SaltCloudSystemExit( pprint.pformat(result.get('error_message', {})) ) return result 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 show_instance(name, call=None): ''' Show the details from DigitalOcean concerning a droplet ''' if call != 'action': raise SaltCloudSystemExit( 'The show_instance action must be called with -a or --action.' ) node = _get_node(name) __utils__['cloud.cache_node'](node, __active_provider_name__, __opts__) return node def _get_node(name): attempts = 10 while attempts >= 0: try: return list_nodes_full(for_output=False)[name] except KeyError: attempts -= 1 log.debug( 'Failed to get the data for node \'%s\'. Remaining ' 'attempts: %s', name, attempts ) # Just a little delay between attempts... time.sleep(0.5) return {} def list_keypairs(call=None): ''' Return a dict of all available VM locations on the cloud provider with relevant data ''' if call != 'function': log.error( 'The list_keypairs function must be called with -f or --function.' ) return False fetch = True page = 1 ret = {} while fetch: items = query(method='account/keys', command='?page=' + six.text_type(page) + '&per_page=100') for key_pair in items['ssh_keys']: name = key_pair['name'] if name in ret: raise SaltCloudSystemExit( 'A duplicate key pair name, \'{0}\', was found in DigitalOcean\'s ' 'key pair list. Please change the key name stored by DigitalOcean. ' 'Be sure to adjust the value of \'ssh_key_file\' in your cloud ' 'profile or provider configuration, if necessary.'.format( name ) ) ret[name] = {} for item in six.iterkeys(key_pair): ret[name][item] = six.text_type(key_pair[item]) page += 1 try: fetch = 'next' in items['links']['pages'] except KeyError: fetch = False return ret def show_keypair(kwargs=None, call=None): ''' Show the details of an SSH keypair ''' if call != 'function': log.error( 'The show_keypair function must be called with -f or --function.' ) return False if not kwargs: kwargs = {} if 'keyname' not in kwargs: log.error('A keyname is required.') return False keypairs = list_keypairs(call='function') keyid = keypairs[kwargs['keyname']]['id'] log.debug('Key ID is %s', keyid) details = query(method='account/keys', command=keyid) return details def import_keypair(kwargs=None, call=None): ''' Upload public key to cloud provider. Similar to EC2 import_keypair. .. versionadded:: 2016.11.0 kwargs file(mandatory): public key file-name keyname(mandatory): public key name in the provider ''' with salt.utils.files.fopen(kwargs['file'], 'r') as public_key_filename: public_key_content = salt.utils.stringutils.to_unicode(public_key_filename.read()) digitalocean_kwargs = { 'name': kwargs['keyname'], 'public_key': public_key_content } created_result = create_key(digitalocean_kwargs, call=call) return created_result def create_key(kwargs=None, call=None): ''' Upload a public key ''' if call != 'function': log.error( 'The create_key function must be called with -f or --function.' ) return False try: result = query( method='account', command='keys', args={'name': kwargs['name'], 'public_key': kwargs['public_key']}, http_method='post' ) except KeyError: log.info('`name` and `public_key` arguments must be specified') return False return result def remove_key(kwargs=None, call=None): ''' Delete public key ''' if call != 'function': log.error( 'The create_key function must be called with -f or --function.' ) return False try: result = query( method='account', command='keys/' + kwargs['id'], http_method='delete' ) except KeyError: log.info('`id` argument must be specified') return False return result def get_keyid(keyname): ''' Return the ID of the keyname ''' if not keyname: return None keypairs = list_keypairs(call='function') keyid = keypairs[keyname]['id'] if keyid: return keyid raise SaltCloudNotFound('The specified ssh key could not be found.') def post_dns_record(**kwargs): ''' Creates a DNS record for the given name if the domain is managed with DO. ''' if 'kwargs' in kwargs: # flatten kwargs if called via salt-cloud -f f_kwargs = kwargs['kwargs'] del kwargs['kwargs'] kwargs.update(f_kwargs) mandatory_kwargs = ('dns_domain', 'name', 'record_type', 'record_data') for i in mandatory_kwargs: if kwargs[i]: pass else: error = '{0}="{1}" ## all mandatory args must be provided: {2}'.format(i, kwargs[i], mandatory_kwargs) raise SaltInvocationError(error) domain = query(method='domains', droplet_id=kwargs['dns_domain']) if domain: result = query( method='domains', droplet_id=kwargs['dns_domain'], command='records', args={'type': kwargs['record_type'], 'name': kwargs['name'], 'data': kwargs['record_data']}, http_method='post' ) return result return False def destroy_dns_records(fqdn): ''' Deletes DNS records for the given hostname if the domain is managed with DO. ''' domain = '.'.join(fqdn.split('.')[-2:]) hostname = '.'.join(fqdn.split('.')[:-2]) # TODO: remove this when the todo on 754 is available try: response = query(method='domains', droplet_id=domain, command='records') except SaltCloudSystemExit: log.debug('Failed to find domains.') return False log.debug("found DNS records: %s", pprint.pformat(response)) records = response['domain_records'] if records: record_ids = [r['id'] for r in records if r['name'].decode() == hostname] log.debug("deleting DNS record IDs: %s", record_ids) for id_ in record_ids: try: log.info('deleting DNS record %s', id_) ret = query( method='domains', droplet_id=domain, command='records/{0}'.format(id_), http_method='delete' ) except SaltCloudSystemExit: log.error('failed to delete DNS domain %s record ID %s.', domain, hostname) log.debug('DNS deletion REST call returned: %s', pprint.pformat(ret)) return False def show_pricing(kwargs=None, call=None): ''' Show pricing for a particular profile. This is only an estimate, based on unofficial pricing sources. .. versionadded:: 2015.8.0 CLI Examples: .. code-block:: bash salt-cloud -f show_pricing my-digitalocean-config profile=my-profile ''' profile = __opts__['profiles'].get(kwargs['profile'], {}) if not profile: return {'Error': 'The requested profile was not found'} # Make sure the profile belongs to DigitalOcean provider = profile.get('provider', '0:0') comps = provider.split(':') if len(comps) < 2 or comps[1] != 'digitalocean': return {'Error': 'The requested profile does not belong to DigitalOcean'} raw = {} ret = {} sizes = avail_sizes() ret['per_hour'] = decimal.Decimal(sizes[profile['size']]['price_hourly']) ret['per_day'] = ret['per_hour'] * 24 ret['per_week'] = ret['per_day'] * 7 ret['per_month'] = decimal.Decimal(sizes[profile['size']]['price_monthly']) ret['per_year'] = ret['per_week'] * 52 if kwargs.get('raw', False): ret['_raw'] = raw return {profile['profile']: ret} def list_floating_ips(call=None): ''' Return a list of the floating ips that are on the provider .. versionadded:: 2016.3.0 CLI Examples: .. code-block:: bash salt-cloud -f list_floating_ips my-digitalocean-config ''' if call == 'action': raise SaltCloudSystemExit( 'The list_floating_ips function must be called with ' '-f or --function, or with the --list-floating-ips option' ) fetch = True page = 1 ret = {} while fetch: items = query(method='floating_ips', command='?page=' + six.text_type(page) + '&per_page=200') for floating_ip in items['floating_ips']: ret[floating_ip['ip']] = {} for item in six.iterkeys(floating_ip): ret[floating_ip['ip']][item] = floating_ip[item] page += 1 try: fetch = 'next' in items['links']['pages'] except KeyError: fetch = False return ret def show_floating_ip(kwargs=None, call=None): ''' Show the details of a floating IP .. versionadded:: 2016.3.0 CLI Examples: .. code-block:: bash salt-cloud -f show_floating_ip my-digitalocean-config floating_ip='45.55.96.47' ''' if call != 'function': log.error( 'The show_floating_ip function must be called with -f or --function.' ) return False if not kwargs: kwargs = {} if 'floating_ip' not in kwargs: log.error('A floating IP is required.') return False floating_ip = kwargs['floating_ip'] log.debug('Floating ip is %s', floating_ip) details = query(method='floating_ips', command=floating_ip) return details def create_floating_ip(kwargs=None, call=None): ''' Create a new floating IP .. versionadded:: 2016.3.0 CLI Examples: .. code-block:: bash salt-cloud -f create_floating_ip my-digitalocean-config region='NYC2' salt-cloud -f create_floating_ip my-digitalocean-config droplet_id='1234567' ''' if call != 'function': log.error( 'The create_floating_ip function must be called with -f or --function.' ) return False if not kwargs: kwargs = {} if 'droplet_id' in kwargs: result = query(method='floating_ips', args={'droplet_id': kwargs['droplet_id']}, http_method='post') return result elif 'region' in kwargs: result = query(method='floating_ips', args={'region': kwargs['region']}, http_method='post') return result else: log.error('A droplet_id or region is required.') return False def delete_floating_ip(kwargs=None, call=None): ''' Delete a floating IP .. versionadded:: 2016.3.0 CLI Examples: .. code-block:: bash salt-cloud -f delete_floating_ip my-digitalocean-config floating_ip='45.55.96.47' ''' if call != 'function': log.error( 'The delete_floating_ip function must be called with -f or --function.' ) return False if not kwargs: kwargs = {} if 'floating_ip' not in kwargs: log.error('A floating IP is required.') return False floating_ip = kwargs['floating_ip'] log.debug('Floating ip is %s', kwargs['floating_ip']) result = query(method='floating_ips', command=floating_ip, http_method='delete') return result def assign_floating_ip(kwargs=None, call=None): ''' Assign a floating IP .. versionadded:: 2016.3.0 CLI Examples: .. code-block:: bash salt-cloud -f assign_floating_ip my-digitalocean-config droplet_id=1234567 floating_ip='45.55.96.47' ''' if call != 'function': log.error( 'The assign_floating_ip function must be called with -f or --function.' ) return False if not kwargs: kwargs = {} if 'floating_ip' and 'droplet_id' not in kwargs: log.error('A floating IP and droplet_id is required.') return False result = query(method='floating_ips', command=kwargs['floating_ip'] + '/actions', args={'droplet_id': kwargs['droplet_id'], 'type': 'assign'}, http_method='post') return result def unassign_floating_ip(kwargs=None, call=None): ''' Unassign a floating IP .. versionadded:: 2016.3.0 CLI Examples: .. code-block:: bash salt-cloud -f unassign_floating_ip my-digitalocean-config floating_ip='45.55.96.47' ''' if call != 'function': log.error( 'The inassign_floating_ip function must be called with -f or --function.' ) return False if not kwargs: kwargs = {} if 'floating_ip' not in kwargs: log.error('A floating IP is required.') return False result = query(method='floating_ips', command=kwargs['floating_ip'] + '/actions', args={'type': 'unassign'}, http_method='post') return result def _list_nodes(full=False, for_output=False): ''' Helper function to format and parse node data. ''' fetch = True page = 1 ret = {} while fetch: items = query(method='droplets', command='?page=' + six.text_type(page) + '&per_page=200') for node in items['droplets']: name = node['name'] ret[name] = {} if full: ret[name] = _get_full_output(node, for_output=for_output) else: public_ips, private_ips = _get_ips(node['networks']) ret[name] = { 'id': node['id'], 'image': node['image']['name'], 'name': name, 'private_ips': private_ips, 'public_ips': public_ips, 'size': node['size_slug'], 'state': six.text_type(node['status']), } page += 1 try: fetch = 'next' in items['links']['pages'] except KeyError: fetch = False return ret def reboot(name, call=None): ''' Reboot a droplet in DigitalOcean. .. versionadded:: 2015.8.8 name The name of the droplet to restart. CLI Example: .. code-block:: bash salt-cloud -a reboot droplet_name ''' if call != 'action': raise SaltCloudSystemExit( 'The restart action must be called with -a or --action.' ) data = show_instance(name, call='action') if data.get('status') == 'off': return {'success': True, 'action': 'stop', 'status': 'off', 'msg': 'Machine is already off.'} ret = query(droplet_id=data['id'], command='actions', args={'type': 'reboot'}, http_method='post') return {'success': True, 'action': ret['action']['type'], 'state': ret['action']['status']} def start(name, call=None): ''' Start a droplet in DigitalOcean. .. versionadded:: 2015.8.8 name The name of the droplet to start. CLI Example: .. code-block:: bash salt-cloud -a start droplet_name ''' if call != 'action': raise SaltCloudSystemExit( 'The start action must be called with -a or --action.' ) data = show_instance(name, call='action') if data.get('status') == 'active': return {'success': True, 'action': 'start', 'status': 'active', 'msg': 'Machine is already running.'} ret = query(droplet_id=data['id'], command='actions', args={'type': 'power_on'}, http_method='post') return {'success': True, 'action': ret['action']['type'], 'state': ret['action']['status']} def stop(name, call=None): ''' Stop a droplet in DigitalOcean. .. versionadded:: 2015.8.8 name The name of the droplet to stop. CLI Example: .. code-block:: bash salt-cloud -a stop droplet_name ''' if call != 'action': raise SaltCloudSystemExit( 'The stop action must be called with -a or --action.' ) data = show_instance(name, call='action') if data.get('status') == 'off': return {'success': True, 'action': 'stop', 'status': 'off', 'msg': 'Machine is already off.'} ret = query(droplet_id=data['id'], command='actions', args={'type': 'shutdown'}, http_method='post') return {'success': True, 'action': ret['action']['type'], 'state': ret['action']['status']} def _get_full_output(node, for_output=False): ''' Helper function for _list_nodes to loop through all node information. Returns a dictionary containing the full information of a node. ''' ret = {} for item in six.iterkeys(node): value = node[item] if value is not None and for_output: value = six.text_type(value) ret[item] = value return ret def _get_ips(networks): ''' Helper function for list_nodes. Returns public and private ip lists based on a given network dictionary. ''' v4s = networks.get('v4') v6s = networks.get('v6') public_ips = [] private_ips = [] if v4s: for item in v4s: ip_type = item.get('type') ip_address = item.get('ip_address') if ip_type == 'public': public_ips.append(ip_address) if ip_type == 'private': private_ips.append(ip_address) if v6s: for item in v6s: ip_type = item.get('type') ip_address = item.get('ip_address') if ip_type == 'public': public_ips.append(ip_address) if ip_type == 'private': private_ips.append(ip_address) return public_ips, private_ips
saltstack/salt
salt/cloud/clouds/digitalocean.py
post_dns_record
python
def post_dns_record(**kwargs): ''' Creates a DNS record for the given name if the domain is managed with DO. ''' if 'kwargs' in kwargs: # flatten kwargs if called via salt-cloud -f f_kwargs = kwargs['kwargs'] del kwargs['kwargs'] kwargs.update(f_kwargs) mandatory_kwargs = ('dns_domain', 'name', 'record_type', 'record_data') for i in mandatory_kwargs: if kwargs[i]: pass else: error = '{0}="{1}" ## all mandatory args must be provided: {2}'.format(i, kwargs[i], mandatory_kwargs) raise SaltInvocationError(error) domain = query(method='domains', droplet_id=kwargs['dns_domain']) if domain: result = query( method='domains', droplet_id=kwargs['dns_domain'], command='records', args={'type': kwargs['record_type'], 'name': kwargs['name'], 'data': kwargs['record_data']}, http_method='post' ) return result return False
Creates a DNS record for the given name if the domain is managed with DO.
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/digitalocean.py#L874-L902
[ "def query(method='droplets', droplet_id=None, command=None, args=None, http_method='get'):\n '''\n Make a web call to DigitalOcean\n '''\n base_path = six.text_type(config.get_cloud_config_value(\n 'api_root',\n get_configured_provider(),\n __opts__,\n search_global=False,\n default='https://api.digitalocean.com/v2'\n ))\n\n path = '{0}/{1}/'.format(base_path, method)\n\n if droplet_id:\n path += '{0}/'.format(droplet_id)\n\n if command:\n path += command\n\n if not isinstance(args, dict):\n args = {}\n\n personal_access_token = config.get_cloud_config_value(\n 'personal_access_token', get_configured_provider(), __opts__, search_global=False\n )\n\n data = salt.utils.json.dumps(args)\n\n requester = getattr(requests, http_method)\n request = requester(path, data=data, headers={'Authorization': 'Bearer ' + personal_access_token, 'Content-Type': 'application/json'})\n if request.status_code > 299:\n raise SaltCloudSystemExit(\n 'An error occurred while querying DigitalOcean. HTTP Code: {0} '\n 'Error: \\'{1}\\''.format(\n request.status_code,\n # request.read()\n request.text\n )\n )\n\n log.debug(request.url)\n\n # success without data\n if request.status_code == 204:\n return True\n\n content = request.text\n\n result = salt.utils.json.loads(content)\n if result.get('status', '').lower() == 'error':\n raise SaltCloudSystemExit(\n pprint.pformat(result.get('error_message', {}))\n )\n\n return result\n" ]
# -*- coding: utf-8 -*- ''' DigitalOcean Cloud Module ========================= The DigitalOcean cloud module is used to control access to the DigitalOcean VPS system. Use of this module requires a requires a ``personal_access_token``, an ``ssh_key_file``, and at least one SSH key name in ``ssh_key_names``. More ``ssh_key_names`` can be added by separating each key with a comma. The ``personal_access_token`` can be found in the DigitalOcean web interface in the "Apps & API" section. The SSH key name can be found under the "SSH Keys" section. .. code-block:: yaml # Note: This example is for /etc/salt/cloud.providers or any file in the # /etc/salt/cloud.providers.d/ directory. my-digital-ocean-config: personal_access_token: xxx ssh_key_file: /path/to/ssh/key/file ssh_key_names: my-key-name,my-key-name-2 driver: digitalocean :depends: requests ''' # Import Python Libs from __future__ import absolute_import, print_function, unicode_literals import decimal import logging import os import pprint import time # Import Salt Libs import salt.utils.cloud import salt.utils.files import salt.utils.json import salt.utils.stringutils import salt.config as config from salt.exceptions import ( SaltCloudConfigError, SaltInvocationError, SaltCloudNotFound, SaltCloudSystemExit, SaltCloudExecutionFailure, SaltCloudExecutionTimeout ) from salt.ext import six from salt.ext.six.moves import zip # Import Third Party Libs try: import requests HAS_REQUESTS = True except ImportError: HAS_REQUESTS = False # Get logging started log = logging.getLogger(__name__) __virtualname__ = 'digitalocean' __virtual_aliases__ = ('digital_ocean', 'do') # Only load in this module if the DIGITALOCEAN configurations are in place def __virtual__(): ''' Check for DigitalOcean 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=__opts__, provider=__active_provider_name__ or __virtualname__, aliases=__virtual_aliases__, required_keys=('personal_access_token',) ) def get_dependencies(): ''' Warn if dependencies aren't met. ''' return config.check_driver_dependencies( __virtualname__, {'requests': HAS_REQUESTS} ) def avail_locations(call=None): ''' Return a dict of all available VM locations on the cloud provider with relevant data ''' if call == 'action': raise SaltCloudSystemExit( 'The avail_locations function must be called with ' '-f or --function, or with the --list-locations option' ) items = query(method='regions') ret = {} for region in items['regions']: ret[region['name']] = {} for item in six.iterkeys(region): ret[region['name']][item] = six.text_type(region[item]) return ret def avail_images(call=None): ''' Return a list of the images that are on the provider ''' if call == 'action': raise SaltCloudSystemExit( 'The avail_images function must be called with ' '-f or --function, or with the --list-images option' ) fetch = True page = 1 ret = {} while fetch: items = query(method='images', command='?page=' + six.text_type(page) + '&per_page=200') for image in items['images']: ret[image['name']] = {} for item in six.iterkeys(image): ret[image['name']][item] = image[item] page += 1 try: fetch = 'next' in items['links']['pages'] except KeyError: fetch = False return ret def avail_sizes(call=None): ''' Return a list of the image sizes that are on the provider ''' if call == 'action': raise SaltCloudSystemExit( 'The avail_sizes function must be called with ' '-f or --function, or with the --list-sizes option' ) items = query(method='sizes', command='?per_page=100') ret = {} for size in items['sizes']: ret[size['slug']] = {} for item in six.iterkeys(size): ret[size['slug']][item] = six.text_type(size[item]) 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.' ) return _list_nodes() def list_nodes_full(call=None, for_output=True): ''' 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.' ) return _list_nodes(full=True, for_output=for_output) 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('function'), __opts__['query.selection'], call, ) def get_image(vm_): ''' Return the image object to use ''' images = avail_images() vm_image = config.get_cloud_config_value( 'image', vm_, __opts__, search_global=False ) if not isinstance(vm_image, six.string_types): vm_image = six.text_type(vm_image) for image in images: if vm_image in (images[image]['name'], images[image]['slug'], images[image]['id']): if images[image]['slug'] is not None: return images[image]['slug'] return int(images[image]['id']) raise SaltCloudNotFound( 'The specified image, \'{0}\', could not be found.'.format(vm_image) ) def get_size(vm_): ''' Return the VM's size. Used by create_node(). ''' sizes = avail_sizes() vm_size = six.text_type(config.get_cloud_config_value( 'size', vm_, __opts__, search_global=False )) for size in sizes: if vm_size.lower() == sizes[size]['slug']: return sizes[size]['slug'] raise SaltCloudNotFound( 'The specified size, \'{0}\', could not be found.'.format(vm_size) ) def get_location(vm_): ''' Return the VM's location ''' locations = avail_locations() vm_location = six.text_type(config.get_cloud_config_value( 'location', vm_, __opts__, search_global=False )) for location in locations: if vm_location in (locations[location]['name'], locations[location]['slug']): return locations[location]['slug'] raise SaltCloudNotFound( 'The specified location, \'{0}\', could not be found.'.format( vm_location ) ) def create_node(args): ''' Create a node ''' node = query(method='droplets', args=args, http_method='post') return node 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 'digitalocean', vm_['profile'], vm_=vm_) is False: return False except AttributeError: pass __utils__['cloud.fire_event']( 'event', 'starting create', 'salt/cloud/{0}/creating'.format(vm_['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', vm_['name']) kwargs = { 'name': vm_['name'], 'size': get_size(vm_), 'image': get_image(vm_), 'region': get_location(vm_), 'ssh_keys': [], 'tags': [] } # backwards compat ssh_key_name = config.get_cloud_config_value( 'ssh_key_name', vm_, __opts__, search_global=False ) if ssh_key_name: kwargs['ssh_keys'].append(get_keyid(ssh_key_name)) ssh_key_names = config.get_cloud_config_value( 'ssh_key_names', vm_, __opts__, search_global=False, default=False ) if ssh_key_names: for key in ssh_key_names.split(','): kwargs['ssh_keys'].append(get_keyid(key)) key_filename = config.get_cloud_config_value( 'ssh_key_file', vm_, __opts__, search_global=False, default=None ) if key_filename is not None and not os.path.isfile(key_filename): raise SaltCloudConfigError( 'The defined key_filename \'{0}\' does not exist'.format( key_filename ) ) if not __opts__.get('ssh_agent', False) and key_filename is None: raise SaltCloudConfigError( 'The DigitalOcean driver requires an ssh_key_file and an ssh_key_name ' 'because it does not supply a root password upon building the server.' ) ssh_interface = config.get_cloud_config_value( 'ssh_interface', vm_, __opts__, search_global=False, default='public' ) if ssh_interface in ['private', 'public']: log.info("ssh_interface: Setting interface for ssh to %s", ssh_interface) kwargs['ssh_interface'] = ssh_interface else: raise SaltCloudConfigError( "The DigitalOcean driver requires ssh_interface to be defined as 'public' or 'private'." ) private_networking = config.get_cloud_config_value( 'private_networking', vm_, __opts__, search_global=False, default=None, ) if private_networking is not None: if not isinstance(private_networking, bool): raise SaltCloudConfigError("'private_networking' should be a boolean value.") kwargs['private_networking'] = private_networking if not private_networking and ssh_interface == 'private': raise SaltCloudConfigError( "The DigitalOcean driver requires ssh_interface if defined as 'private' " "then private_networking should be set as 'True'." ) backups_enabled = config.get_cloud_config_value( 'backups_enabled', vm_, __opts__, search_global=False, default=None, ) if backups_enabled is not None: if not isinstance(backups_enabled, bool): raise SaltCloudConfigError("'backups_enabled' should be a boolean value.") kwargs['backups'] = backups_enabled ipv6 = config.get_cloud_config_value( 'ipv6', vm_, __opts__, search_global=False, default=None, ) if ipv6 is not None: if not isinstance(ipv6, bool): raise SaltCloudConfigError("'ipv6' should be a boolean value.") kwargs['ipv6'] = ipv6 monitoring = config.get_cloud_config_value( 'monitoring', vm_, __opts__, search_global=False, default=None, ) if monitoring is not None: if not isinstance(monitoring, bool): raise SaltCloudConfigError("'monitoring' should be a boolean value.") kwargs['monitoring'] = monitoring kwargs['tags'] = config.get_cloud_config_value( 'tags', vm_, __opts__, search_global=False, default=False ) userdata_file = config.get_cloud_config_value( 'userdata_file', vm_, __opts__, search_global=False, default=None ) if userdata_file is not None: try: with salt.utils.files.fopen(userdata_file, 'r') as fp_: kwargs['user_data'] = salt.utils.cloud.userdata_template( __opts__, vm_, salt.utils.stringutils.to_unicode(fp_.read()) ) except Exception as exc: log.exception( 'Failed to read userdata from %s: %s', userdata_file, exc) create_dns_record = config.get_cloud_config_value( 'create_dns_record', vm_, __opts__, search_global=False, default=None, ) if create_dns_record: log.info('create_dns_record: will attempt to write DNS records') default_dns_domain = None dns_domain_name = vm_['name'].split('.') if len(dns_domain_name) > 2: log.debug('create_dns_record: inferring default dns_hostname, dns_domain from minion name as FQDN') default_dns_hostname = '.'.join(dns_domain_name[:-2]) default_dns_domain = '.'.join(dns_domain_name[-2:]) else: log.debug("create_dns_record: can't infer dns_domain from %s", vm_['name']) default_dns_hostname = dns_domain_name[0] dns_hostname = config.get_cloud_config_value( 'dns_hostname', vm_, __opts__, search_global=False, default=default_dns_hostname, ) dns_domain = config.get_cloud_config_value( 'dns_domain', vm_, __opts__, search_global=False, default=default_dns_domain, ) if dns_hostname and dns_domain: log.info('create_dns_record: using dns_hostname="%s", dns_domain="%s"', dns_hostname, dns_domain) __add_dns_addr__ = lambda t, d: post_dns_record(dns_domain=dns_domain, name=dns_hostname, record_type=t, record_data=d) log.debug('create_dns_record: %s', __add_dns_addr__) else: log.error('create_dns_record: could not determine dns_hostname and/or dns_domain') raise SaltCloudConfigError( '\'create_dns_record\' must be a dict specifying "domain" ' 'and "hostname" or the minion name must be an FQDN.' ) __utils__['cloud.fire_event']( 'event', 'requesting instance', 'salt/cloud/{0}/requesting'.format(vm_['name']), args=__utils__['cloud.filter_event']('requesting', kwargs, list(kwargs)), sock_dir=__opts__['sock_dir'], transport=__opts__['transport'] ) try: ret = create_node(kwargs) except Exception as exc: log.error( 'Error creating %s on DIGITALOCEAN\n\n' 'The following exception was thrown when trying to ' 'run the initial deployment: %s', vm_['name'], exc, # Show the traceback if the debug logging level is enabled exc_info_on_loglevel=logging.DEBUG ) return False def __query_node_data(vm_name): data = show_instance(vm_name, 'action') if not data: # Trigger an error in the wait_for_ip function return False if data['networks'].get('v4'): for network in data['networks']['v4']: if network['type'] == 'public': return data return False try: data = salt.utils.cloud.wait_for_ip( __query_node_data, update_args=(vm_['name'],), timeout=config.get_cloud_config_value( 'wait_for_ip_timeout', vm_, __opts__, default=10 * 60), interval=config.get_cloud_config_value( 'wait_for_ip_interval', vm_, __opts__, default=10), ) except (SaltCloudExecutionTimeout, SaltCloudExecutionFailure) as exc: try: # It might be already up, let's destroy it! destroy(vm_['name']) except SaltCloudSystemExit: pass finally: raise SaltCloudSystemExit(six.text_type(exc)) if not vm_.get('ssh_host'): vm_['ssh_host'] = None # add DNS records, set ssh_host, default to first found IP, preferring IPv4 for ssh bootstrap script target addr_families, dns_arec_types = (('v4', 'v6'), ('A', 'AAAA')) arec_map = dict(list(zip(addr_families, dns_arec_types))) for facing, addr_family, ip_address in [(net['type'], family, net['ip_address']) for family in addr_families for net in data['networks'][family]]: log.info('found %s IP%s interface for "%s"', facing, addr_family, ip_address) dns_rec_type = arec_map[addr_family] if facing == 'public': if create_dns_record: __add_dns_addr__(dns_rec_type, ip_address) if facing == ssh_interface: if not vm_['ssh_host']: vm_['ssh_host'] = ip_address if vm_['ssh_host'] is None: raise SaltCloudSystemExit( 'No suitable IP addresses found for ssh minion bootstrapping: {0}'.format(repr(data['networks'])) ) log.debug( 'Found public IP address to use for ssh minion bootstrapping: %s', vm_['ssh_host'] ) vm_['key_filename'] = key_filename ret = __utils__['cloud.bootstrap'](vm_, __opts__) ret.update(data) log.info('Created Cloud VM \'%s\'', vm_['name']) log.debug( '\'%s\' VM creation details:\n%s', vm_['name'], pprint.pformat(data) ) __utils__['cloud.fire_event']( 'event', 'created instance', 'salt/cloud/{0}/created'.format(vm_['name']), args=__utils__['cloud.filter_event']('created', vm_, ['name', 'profile', 'provider', 'driver']), sock_dir=__opts__['sock_dir'], transport=__opts__['transport'] ) return ret def query(method='droplets', droplet_id=None, command=None, args=None, http_method='get'): ''' Make a web call to DigitalOcean ''' base_path = six.text_type(config.get_cloud_config_value( 'api_root', get_configured_provider(), __opts__, search_global=False, default='https://api.digitalocean.com/v2' )) path = '{0}/{1}/'.format(base_path, method) if droplet_id: path += '{0}/'.format(droplet_id) if command: path += command if not isinstance(args, dict): args = {} personal_access_token = config.get_cloud_config_value( 'personal_access_token', get_configured_provider(), __opts__, search_global=False ) data = salt.utils.json.dumps(args) requester = getattr(requests, http_method) request = requester(path, data=data, headers={'Authorization': 'Bearer ' + personal_access_token, 'Content-Type': 'application/json'}) if request.status_code > 299: raise SaltCloudSystemExit( 'An error occurred while querying DigitalOcean. HTTP Code: {0} ' 'Error: \'{1}\''.format( request.status_code, # request.read() request.text ) ) log.debug(request.url) # success without data if request.status_code == 204: return True content = request.text result = salt.utils.json.loads(content) if result.get('status', '').lower() == 'error': raise SaltCloudSystemExit( pprint.pformat(result.get('error_message', {})) ) return result 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 show_instance(name, call=None): ''' Show the details from DigitalOcean concerning a droplet ''' if call != 'action': raise SaltCloudSystemExit( 'The show_instance action must be called with -a or --action.' ) node = _get_node(name) __utils__['cloud.cache_node'](node, __active_provider_name__, __opts__) return node def _get_node(name): attempts = 10 while attempts >= 0: try: return list_nodes_full(for_output=False)[name] except KeyError: attempts -= 1 log.debug( 'Failed to get the data for node \'%s\'. Remaining ' 'attempts: %s', name, attempts ) # Just a little delay between attempts... time.sleep(0.5) return {} def list_keypairs(call=None): ''' Return a dict of all available VM locations on the cloud provider with relevant data ''' if call != 'function': log.error( 'The list_keypairs function must be called with -f or --function.' ) return False fetch = True page = 1 ret = {} while fetch: items = query(method='account/keys', command='?page=' + six.text_type(page) + '&per_page=100') for key_pair in items['ssh_keys']: name = key_pair['name'] if name in ret: raise SaltCloudSystemExit( 'A duplicate key pair name, \'{0}\', was found in DigitalOcean\'s ' 'key pair list. Please change the key name stored by DigitalOcean. ' 'Be sure to adjust the value of \'ssh_key_file\' in your cloud ' 'profile or provider configuration, if necessary.'.format( name ) ) ret[name] = {} for item in six.iterkeys(key_pair): ret[name][item] = six.text_type(key_pair[item]) page += 1 try: fetch = 'next' in items['links']['pages'] except KeyError: fetch = False return ret def show_keypair(kwargs=None, call=None): ''' Show the details of an SSH keypair ''' if call != 'function': log.error( 'The show_keypair function must be called with -f or --function.' ) return False if not kwargs: kwargs = {} if 'keyname' not in kwargs: log.error('A keyname is required.') return False keypairs = list_keypairs(call='function') keyid = keypairs[kwargs['keyname']]['id'] log.debug('Key ID is %s', keyid) details = query(method='account/keys', command=keyid) return details def import_keypair(kwargs=None, call=None): ''' Upload public key to cloud provider. Similar to EC2 import_keypair. .. versionadded:: 2016.11.0 kwargs file(mandatory): public key file-name keyname(mandatory): public key name in the provider ''' with salt.utils.files.fopen(kwargs['file'], 'r') as public_key_filename: public_key_content = salt.utils.stringutils.to_unicode(public_key_filename.read()) digitalocean_kwargs = { 'name': kwargs['keyname'], 'public_key': public_key_content } created_result = create_key(digitalocean_kwargs, call=call) return created_result def create_key(kwargs=None, call=None): ''' Upload a public key ''' if call != 'function': log.error( 'The create_key function must be called with -f or --function.' ) return False try: result = query( method='account', command='keys', args={'name': kwargs['name'], 'public_key': kwargs['public_key']}, http_method='post' ) except KeyError: log.info('`name` and `public_key` arguments must be specified') return False return result def remove_key(kwargs=None, call=None): ''' Delete public key ''' if call != 'function': log.error( 'The create_key function must be called with -f or --function.' ) return False try: result = query( method='account', command='keys/' + kwargs['id'], http_method='delete' ) except KeyError: log.info('`id` argument must be specified') return False return result def get_keyid(keyname): ''' Return the ID of the keyname ''' if not keyname: return None keypairs = list_keypairs(call='function') keyid = keypairs[keyname]['id'] if keyid: return keyid raise SaltCloudNotFound('The specified ssh key could not be found.') def destroy(name, call=None): ''' Destroy a node. Will check termination protection and warn if enabled. 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'] ) data = show_instance(name, call='action') node = query(method='droplets', droplet_id=data['id'], http_method='delete') ## This is all terribly optomistic: # vm_ = get_vm_config(name=name) # delete_dns_record = config.get_cloud_config_value( # 'delete_dns_record', vm_, __opts__, search_global=False, default=None, # ) # TODO: when _vm config data can be made available, we should honor the configuration settings, # but until then, we should assume stale DNS records are bad, and default behavior should be to # delete them if we can. When this is resolved, also resolve the comments a couple of lines below. delete_dns_record = True if not isinstance(delete_dns_record, bool): raise SaltCloudConfigError( '\'delete_dns_record\' should be a boolean value.' ) # When the "to do" a few lines up is resolved, remove these lines and use the if/else logic below. log.debug('Deleting DNS records for %s.', name) destroy_dns_records(name) # Until the "to do" from line 754 is taken care of, we don't need this logic. # if delete_dns_record: # log.debug('Deleting DNS records for %s.', name) # destroy_dns_records(name) # else: # log.debug('delete_dns_record : %s', delete_dns_record) # for line in pprint.pformat(dir()).splitlines(): # log.debug('delete context: %s', line) __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 node def destroy_dns_records(fqdn): ''' Deletes DNS records for the given hostname if the domain is managed with DO. ''' domain = '.'.join(fqdn.split('.')[-2:]) hostname = '.'.join(fqdn.split('.')[:-2]) # TODO: remove this when the todo on 754 is available try: response = query(method='domains', droplet_id=domain, command='records') except SaltCloudSystemExit: log.debug('Failed to find domains.') return False log.debug("found DNS records: %s", pprint.pformat(response)) records = response['domain_records'] if records: record_ids = [r['id'] for r in records if r['name'].decode() == hostname] log.debug("deleting DNS record IDs: %s", record_ids) for id_ in record_ids: try: log.info('deleting DNS record %s', id_) ret = query( method='domains', droplet_id=domain, command='records/{0}'.format(id_), http_method='delete' ) except SaltCloudSystemExit: log.error('failed to delete DNS domain %s record ID %s.', domain, hostname) log.debug('DNS deletion REST call returned: %s', pprint.pformat(ret)) return False def show_pricing(kwargs=None, call=None): ''' Show pricing for a particular profile. This is only an estimate, based on unofficial pricing sources. .. versionadded:: 2015.8.0 CLI Examples: .. code-block:: bash salt-cloud -f show_pricing my-digitalocean-config profile=my-profile ''' profile = __opts__['profiles'].get(kwargs['profile'], {}) if not profile: return {'Error': 'The requested profile was not found'} # Make sure the profile belongs to DigitalOcean provider = profile.get('provider', '0:0') comps = provider.split(':') if len(comps) < 2 or comps[1] != 'digitalocean': return {'Error': 'The requested profile does not belong to DigitalOcean'} raw = {} ret = {} sizes = avail_sizes() ret['per_hour'] = decimal.Decimal(sizes[profile['size']]['price_hourly']) ret['per_day'] = ret['per_hour'] * 24 ret['per_week'] = ret['per_day'] * 7 ret['per_month'] = decimal.Decimal(sizes[profile['size']]['price_monthly']) ret['per_year'] = ret['per_week'] * 52 if kwargs.get('raw', False): ret['_raw'] = raw return {profile['profile']: ret} def list_floating_ips(call=None): ''' Return a list of the floating ips that are on the provider .. versionadded:: 2016.3.0 CLI Examples: .. code-block:: bash salt-cloud -f list_floating_ips my-digitalocean-config ''' if call == 'action': raise SaltCloudSystemExit( 'The list_floating_ips function must be called with ' '-f or --function, or with the --list-floating-ips option' ) fetch = True page = 1 ret = {} while fetch: items = query(method='floating_ips', command='?page=' + six.text_type(page) + '&per_page=200') for floating_ip in items['floating_ips']: ret[floating_ip['ip']] = {} for item in six.iterkeys(floating_ip): ret[floating_ip['ip']][item] = floating_ip[item] page += 1 try: fetch = 'next' in items['links']['pages'] except KeyError: fetch = False return ret def show_floating_ip(kwargs=None, call=None): ''' Show the details of a floating IP .. versionadded:: 2016.3.0 CLI Examples: .. code-block:: bash salt-cloud -f show_floating_ip my-digitalocean-config floating_ip='45.55.96.47' ''' if call != 'function': log.error( 'The show_floating_ip function must be called with -f or --function.' ) return False if not kwargs: kwargs = {} if 'floating_ip' not in kwargs: log.error('A floating IP is required.') return False floating_ip = kwargs['floating_ip'] log.debug('Floating ip is %s', floating_ip) details = query(method='floating_ips', command=floating_ip) return details def create_floating_ip(kwargs=None, call=None): ''' Create a new floating IP .. versionadded:: 2016.3.0 CLI Examples: .. code-block:: bash salt-cloud -f create_floating_ip my-digitalocean-config region='NYC2' salt-cloud -f create_floating_ip my-digitalocean-config droplet_id='1234567' ''' if call != 'function': log.error( 'The create_floating_ip function must be called with -f or --function.' ) return False if not kwargs: kwargs = {} if 'droplet_id' in kwargs: result = query(method='floating_ips', args={'droplet_id': kwargs['droplet_id']}, http_method='post') return result elif 'region' in kwargs: result = query(method='floating_ips', args={'region': kwargs['region']}, http_method='post') return result else: log.error('A droplet_id or region is required.') return False def delete_floating_ip(kwargs=None, call=None): ''' Delete a floating IP .. versionadded:: 2016.3.0 CLI Examples: .. code-block:: bash salt-cloud -f delete_floating_ip my-digitalocean-config floating_ip='45.55.96.47' ''' if call != 'function': log.error( 'The delete_floating_ip function must be called with -f or --function.' ) return False if not kwargs: kwargs = {} if 'floating_ip' not in kwargs: log.error('A floating IP is required.') return False floating_ip = kwargs['floating_ip'] log.debug('Floating ip is %s', kwargs['floating_ip']) result = query(method='floating_ips', command=floating_ip, http_method='delete') return result def assign_floating_ip(kwargs=None, call=None): ''' Assign a floating IP .. versionadded:: 2016.3.0 CLI Examples: .. code-block:: bash salt-cloud -f assign_floating_ip my-digitalocean-config droplet_id=1234567 floating_ip='45.55.96.47' ''' if call != 'function': log.error( 'The assign_floating_ip function must be called with -f or --function.' ) return False if not kwargs: kwargs = {} if 'floating_ip' and 'droplet_id' not in kwargs: log.error('A floating IP and droplet_id is required.') return False result = query(method='floating_ips', command=kwargs['floating_ip'] + '/actions', args={'droplet_id': kwargs['droplet_id'], 'type': 'assign'}, http_method='post') return result def unassign_floating_ip(kwargs=None, call=None): ''' Unassign a floating IP .. versionadded:: 2016.3.0 CLI Examples: .. code-block:: bash salt-cloud -f unassign_floating_ip my-digitalocean-config floating_ip='45.55.96.47' ''' if call != 'function': log.error( 'The inassign_floating_ip function must be called with -f or --function.' ) return False if not kwargs: kwargs = {} if 'floating_ip' not in kwargs: log.error('A floating IP is required.') return False result = query(method='floating_ips', command=kwargs['floating_ip'] + '/actions', args={'type': 'unassign'}, http_method='post') return result def _list_nodes(full=False, for_output=False): ''' Helper function to format and parse node data. ''' fetch = True page = 1 ret = {} while fetch: items = query(method='droplets', command='?page=' + six.text_type(page) + '&per_page=200') for node in items['droplets']: name = node['name'] ret[name] = {} if full: ret[name] = _get_full_output(node, for_output=for_output) else: public_ips, private_ips = _get_ips(node['networks']) ret[name] = { 'id': node['id'], 'image': node['image']['name'], 'name': name, 'private_ips': private_ips, 'public_ips': public_ips, 'size': node['size_slug'], 'state': six.text_type(node['status']), } page += 1 try: fetch = 'next' in items['links']['pages'] except KeyError: fetch = False return ret def reboot(name, call=None): ''' Reboot a droplet in DigitalOcean. .. versionadded:: 2015.8.8 name The name of the droplet to restart. CLI Example: .. code-block:: bash salt-cloud -a reboot droplet_name ''' if call != 'action': raise SaltCloudSystemExit( 'The restart action must be called with -a or --action.' ) data = show_instance(name, call='action') if data.get('status') == 'off': return {'success': True, 'action': 'stop', 'status': 'off', 'msg': 'Machine is already off.'} ret = query(droplet_id=data['id'], command='actions', args={'type': 'reboot'}, http_method='post') return {'success': True, 'action': ret['action']['type'], 'state': ret['action']['status']} def start(name, call=None): ''' Start a droplet in DigitalOcean. .. versionadded:: 2015.8.8 name The name of the droplet to start. CLI Example: .. code-block:: bash salt-cloud -a start droplet_name ''' if call != 'action': raise SaltCloudSystemExit( 'The start action must be called with -a or --action.' ) data = show_instance(name, call='action') if data.get('status') == 'active': return {'success': True, 'action': 'start', 'status': 'active', 'msg': 'Machine is already running.'} ret = query(droplet_id=data['id'], command='actions', args={'type': 'power_on'}, http_method='post') return {'success': True, 'action': ret['action']['type'], 'state': ret['action']['status']} def stop(name, call=None): ''' Stop a droplet in DigitalOcean. .. versionadded:: 2015.8.8 name The name of the droplet to stop. CLI Example: .. code-block:: bash salt-cloud -a stop droplet_name ''' if call != 'action': raise SaltCloudSystemExit( 'The stop action must be called with -a or --action.' ) data = show_instance(name, call='action') if data.get('status') == 'off': return {'success': True, 'action': 'stop', 'status': 'off', 'msg': 'Machine is already off.'} ret = query(droplet_id=data['id'], command='actions', args={'type': 'shutdown'}, http_method='post') return {'success': True, 'action': ret['action']['type'], 'state': ret['action']['status']} def _get_full_output(node, for_output=False): ''' Helper function for _list_nodes to loop through all node information. Returns a dictionary containing the full information of a node. ''' ret = {} for item in six.iterkeys(node): value = node[item] if value is not None and for_output: value = six.text_type(value) ret[item] = value return ret def _get_ips(networks): ''' Helper function for list_nodes. Returns public and private ip lists based on a given network dictionary. ''' v4s = networks.get('v4') v6s = networks.get('v6') public_ips = [] private_ips = [] if v4s: for item in v4s: ip_type = item.get('type') ip_address = item.get('ip_address') if ip_type == 'public': public_ips.append(ip_address) if ip_type == 'private': private_ips.append(ip_address) if v6s: for item in v6s: ip_type = item.get('type') ip_address = item.get('ip_address') if ip_type == 'public': public_ips.append(ip_address) if ip_type == 'private': private_ips.append(ip_address) return public_ips, private_ips
saltstack/salt
salt/cloud/clouds/digitalocean.py
destroy_dns_records
python
def destroy_dns_records(fqdn): ''' Deletes DNS records for the given hostname if the domain is managed with DO. ''' domain = '.'.join(fqdn.split('.')[-2:]) hostname = '.'.join(fqdn.split('.')[:-2]) # TODO: remove this when the todo on 754 is available try: response = query(method='domains', droplet_id=domain, command='records') except SaltCloudSystemExit: log.debug('Failed to find domains.') return False log.debug("found DNS records: %s", pprint.pformat(response)) records = response['domain_records'] if records: record_ids = [r['id'] for r in records if r['name'].decode() == hostname] log.debug("deleting DNS record IDs: %s", record_ids) for id_ in record_ids: try: log.info('deleting DNS record %s', id_) ret = query( method='domains', droplet_id=domain, command='records/{0}'.format(id_), http_method='delete' ) except SaltCloudSystemExit: log.error('failed to delete DNS domain %s record ID %s.', domain, hostname) log.debug('DNS deletion REST call returned: %s', pprint.pformat(ret)) return False
Deletes DNS records for the given hostname if the domain is managed with DO.
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/digitalocean.py#L905-L936
[ "def query(method='droplets', droplet_id=None, command=None, args=None, http_method='get'):\n '''\n Make a web call to DigitalOcean\n '''\n base_path = six.text_type(config.get_cloud_config_value(\n 'api_root',\n get_configured_provider(),\n __opts__,\n search_global=False,\n default='https://api.digitalocean.com/v2'\n ))\n\n path = '{0}/{1}/'.format(base_path, method)\n\n if droplet_id:\n path += '{0}/'.format(droplet_id)\n\n if command:\n path += command\n\n if not isinstance(args, dict):\n args = {}\n\n personal_access_token = config.get_cloud_config_value(\n 'personal_access_token', get_configured_provider(), __opts__, search_global=False\n )\n\n data = salt.utils.json.dumps(args)\n\n requester = getattr(requests, http_method)\n request = requester(path, data=data, headers={'Authorization': 'Bearer ' + personal_access_token, 'Content-Type': 'application/json'})\n if request.status_code > 299:\n raise SaltCloudSystemExit(\n 'An error occurred while querying DigitalOcean. HTTP Code: {0} '\n 'Error: \\'{1}\\''.format(\n request.status_code,\n # request.read()\n request.text\n )\n )\n\n log.debug(request.url)\n\n # success without data\n if request.status_code == 204:\n return True\n\n content = request.text\n\n result = salt.utils.json.loads(content)\n if result.get('status', '').lower() == 'error':\n raise SaltCloudSystemExit(\n pprint.pformat(result.get('error_message', {}))\n )\n\n return result\n" ]
# -*- coding: utf-8 -*- ''' DigitalOcean Cloud Module ========================= The DigitalOcean cloud module is used to control access to the DigitalOcean VPS system. Use of this module requires a requires a ``personal_access_token``, an ``ssh_key_file``, and at least one SSH key name in ``ssh_key_names``. More ``ssh_key_names`` can be added by separating each key with a comma. The ``personal_access_token`` can be found in the DigitalOcean web interface in the "Apps & API" section. The SSH key name can be found under the "SSH Keys" section. .. code-block:: yaml # Note: This example is for /etc/salt/cloud.providers or any file in the # /etc/salt/cloud.providers.d/ directory. my-digital-ocean-config: personal_access_token: xxx ssh_key_file: /path/to/ssh/key/file ssh_key_names: my-key-name,my-key-name-2 driver: digitalocean :depends: requests ''' # Import Python Libs from __future__ import absolute_import, print_function, unicode_literals import decimal import logging import os import pprint import time # Import Salt Libs import salt.utils.cloud import salt.utils.files import salt.utils.json import salt.utils.stringutils import salt.config as config from salt.exceptions import ( SaltCloudConfigError, SaltInvocationError, SaltCloudNotFound, SaltCloudSystemExit, SaltCloudExecutionFailure, SaltCloudExecutionTimeout ) from salt.ext import six from salt.ext.six.moves import zip # Import Third Party Libs try: import requests HAS_REQUESTS = True except ImportError: HAS_REQUESTS = False # Get logging started log = logging.getLogger(__name__) __virtualname__ = 'digitalocean' __virtual_aliases__ = ('digital_ocean', 'do') # Only load in this module if the DIGITALOCEAN configurations are in place def __virtual__(): ''' Check for DigitalOcean 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=__opts__, provider=__active_provider_name__ or __virtualname__, aliases=__virtual_aliases__, required_keys=('personal_access_token',) ) def get_dependencies(): ''' Warn if dependencies aren't met. ''' return config.check_driver_dependencies( __virtualname__, {'requests': HAS_REQUESTS} ) def avail_locations(call=None): ''' Return a dict of all available VM locations on the cloud provider with relevant data ''' if call == 'action': raise SaltCloudSystemExit( 'The avail_locations function must be called with ' '-f or --function, or with the --list-locations option' ) items = query(method='regions') ret = {} for region in items['regions']: ret[region['name']] = {} for item in six.iterkeys(region): ret[region['name']][item] = six.text_type(region[item]) return ret def avail_images(call=None): ''' Return a list of the images that are on the provider ''' if call == 'action': raise SaltCloudSystemExit( 'The avail_images function must be called with ' '-f or --function, or with the --list-images option' ) fetch = True page = 1 ret = {} while fetch: items = query(method='images', command='?page=' + six.text_type(page) + '&per_page=200') for image in items['images']: ret[image['name']] = {} for item in six.iterkeys(image): ret[image['name']][item] = image[item] page += 1 try: fetch = 'next' in items['links']['pages'] except KeyError: fetch = False return ret def avail_sizes(call=None): ''' Return a list of the image sizes that are on the provider ''' if call == 'action': raise SaltCloudSystemExit( 'The avail_sizes function must be called with ' '-f or --function, or with the --list-sizes option' ) items = query(method='sizes', command='?per_page=100') ret = {} for size in items['sizes']: ret[size['slug']] = {} for item in six.iterkeys(size): ret[size['slug']][item] = six.text_type(size[item]) 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.' ) return _list_nodes() def list_nodes_full(call=None, for_output=True): ''' 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.' ) return _list_nodes(full=True, for_output=for_output) 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('function'), __opts__['query.selection'], call, ) def get_image(vm_): ''' Return the image object to use ''' images = avail_images() vm_image = config.get_cloud_config_value( 'image', vm_, __opts__, search_global=False ) if not isinstance(vm_image, six.string_types): vm_image = six.text_type(vm_image) for image in images: if vm_image in (images[image]['name'], images[image]['slug'], images[image]['id']): if images[image]['slug'] is not None: return images[image]['slug'] return int(images[image]['id']) raise SaltCloudNotFound( 'The specified image, \'{0}\', could not be found.'.format(vm_image) ) def get_size(vm_): ''' Return the VM's size. Used by create_node(). ''' sizes = avail_sizes() vm_size = six.text_type(config.get_cloud_config_value( 'size', vm_, __opts__, search_global=False )) for size in sizes: if vm_size.lower() == sizes[size]['slug']: return sizes[size]['slug'] raise SaltCloudNotFound( 'The specified size, \'{0}\', could not be found.'.format(vm_size) ) def get_location(vm_): ''' Return the VM's location ''' locations = avail_locations() vm_location = six.text_type(config.get_cloud_config_value( 'location', vm_, __opts__, search_global=False )) for location in locations: if vm_location in (locations[location]['name'], locations[location]['slug']): return locations[location]['slug'] raise SaltCloudNotFound( 'The specified location, \'{0}\', could not be found.'.format( vm_location ) ) def create_node(args): ''' Create a node ''' node = query(method='droplets', args=args, http_method='post') return node 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 'digitalocean', vm_['profile'], vm_=vm_) is False: return False except AttributeError: pass __utils__['cloud.fire_event']( 'event', 'starting create', 'salt/cloud/{0}/creating'.format(vm_['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', vm_['name']) kwargs = { 'name': vm_['name'], 'size': get_size(vm_), 'image': get_image(vm_), 'region': get_location(vm_), 'ssh_keys': [], 'tags': [] } # backwards compat ssh_key_name = config.get_cloud_config_value( 'ssh_key_name', vm_, __opts__, search_global=False ) if ssh_key_name: kwargs['ssh_keys'].append(get_keyid(ssh_key_name)) ssh_key_names = config.get_cloud_config_value( 'ssh_key_names', vm_, __opts__, search_global=False, default=False ) if ssh_key_names: for key in ssh_key_names.split(','): kwargs['ssh_keys'].append(get_keyid(key)) key_filename = config.get_cloud_config_value( 'ssh_key_file', vm_, __opts__, search_global=False, default=None ) if key_filename is not None and not os.path.isfile(key_filename): raise SaltCloudConfigError( 'The defined key_filename \'{0}\' does not exist'.format( key_filename ) ) if not __opts__.get('ssh_agent', False) and key_filename is None: raise SaltCloudConfigError( 'The DigitalOcean driver requires an ssh_key_file and an ssh_key_name ' 'because it does not supply a root password upon building the server.' ) ssh_interface = config.get_cloud_config_value( 'ssh_interface', vm_, __opts__, search_global=False, default='public' ) if ssh_interface in ['private', 'public']: log.info("ssh_interface: Setting interface for ssh to %s", ssh_interface) kwargs['ssh_interface'] = ssh_interface else: raise SaltCloudConfigError( "The DigitalOcean driver requires ssh_interface to be defined as 'public' or 'private'." ) private_networking = config.get_cloud_config_value( 'private_networking', vm_, __opts__, search_global=False, default=None, ) if private_networking is not None: if not isinstance(private_networking, bool): raise SaltCloudConfigError("'private_networking' should be a boolean value.") kwargs['private_networking'] = private_networking if not private_networking and ssh_interface == 'private': raise SaltCloudConfigError( "The DigitalOcean driver requires ssh_interface if defined as 'private' " "then private_networking should be set as 'True'." ) backups_enabled = config.get_cloud_config_value( 'backups_enabled', vm_, __opts__, search_global=False, default=None, ) if backups_enabled is not None: if not isinstance(backups_enabled, bool): raise SaltCloudConfigError("'backups_enabled' should be a boolean value.") kwargs['backups'] = backups_enabled ipv6 = config.get_cloud_config_value( 'ipv6', vm_, __opts__, search_global=False, default=None, ) if ipv6 is not None: if not isinstance(ipv6, bool): raise SaltCloudConfigError("'ipv6' should be a boolean value.") kwargs['ipv6'] = ipv6 monitoring = config.get_cloud_config_value( 'monitoring', vm_, __opts__, search_global=False, default=None, ) if monitoring is not None: if not isinstance(monitoring, bool): raise SaltCloudConfigError("'monitoring' should be a boolean value.") kwargs['monitoring'] = monitoring kwargs['tags'] = config.get_cloud_config_value( 'tags', vm_, __opts__, search_global=False, default=False ) userdata_file = config.get_cloud_config_value( 'userdata_file', vm_, __opts__, search_global=False, default=None ) if userdata_file is not None: try: with salt.utils.files.fopen(userdata_file, 'r') as fp_: kwargs['user_data'] = salt.utils.cloud.userdata_template( __opts__, vm_, salt.utils.stringutils.to_unicode(fp_.read()) ) except Exception as exc: log.exception( 'Failed to read userdata from %s: %s', userdata_file, exc) create_dns_record = config.get_cloud_config_value( 'create_dns_record', vm_, __opts__, search_global=False, default=None, ) if create_dns_record: log.info('create_dns_record: will attempt to write DNS records') default_dns_domain = None dns_domain_name = vm_['name'].split('.') if len(dns_domain_name) > 2: log.debug('create_dns_record: inferring default dns_hostname, dns_domain from minion name as FQDN') default_dns_hostname = '.'.join(dns_domain_name[:-2]) default_dns_domain = '.'.join(dns_domain_name[-2:]) else: log.debug("create_dns_record: can't infer dns_domain from %s", vm_['name']) default_dns_hostname = dns_domain_name[0] dns_hostname = config.get_cloud_config_value( 'dns_hostname', vm_, __opts__, search_global=False, default=default_dns_hostname, ) dns_domain = config.get_cloud_config_value( 'dns_domain', vm_, __opts__, search_global=False, default=default_dns_domain, ) if dns_hostname and dns_domain: log.info('create_dns_record: using dns_hostname="%s", dns_domain="%s"', dns_hostname, dns_domain) __add_dns_addr__ = lambda t, d: post_dns_record(dns_domain=dns_domain, name=dns_hostname, record_type=t, record_data=d) log.debug('create_dns_record: %s', __add_dns_addr__) else: log.error('create_dns_record: could not determine dns_hostname and/or dns_domain') raise SaltCloudConfigError( '\'create_dns_record\' must be a dict specifying "domain" ' 'and "hostname" or the minion name must be an FQDN.' ) __utils__['cloud.fire_event']( 'event', 'requesting instance', 'salt/cloud/{0}/requesting'.format(vm_['name']), args=__utils__['cloud.filter_event']('requesting', kwargs, list(kwargs)), sock_dir=__opts__['sock_dir'], transport=__opts__['transport'] ) try: ret = create_node(kwargs) except Exception as exc: log.error( 'Error creating %s on DIGITALOCEAN\n\n' 'The following exception was thrown when trying to ' 'run the initial deployment: %s', vm_['name'], exc, # Show the traceback if the debug logging level is enabled exc_info_on_loglevel=logging.DEBUG ) return False def __query_node_data(vm_name): data = show_instance(vm_name, 'action') if not data: # Trigger an error in the wait_for_ip function return False if data['networks'].get('v4'): for network in data['networks']['v4']: if network['type'] == 'public': return data return False try: data = salt.utils.cloud.wait_for_ip( __query_node_data, update_args=(vm_['name'],), timeout=config.get_cloud_config_value( 'wait_for_ip_timeout', vm_, __opts__, default=10 * 60), interval=config.get_cloud_config_value( 'wait_for_ip_interval', vm_, __opts__, default=10), ) except (SaltCloudExecutionTimeout, SaltCloudExecutionFailure) as exc: try: # It might be already up, let's destroy it! destroy(vm_['name']) except SaltCloudSystemExit: pass finally: raise SaltCloudSystemExit(six.text_type(exc)) if not vm_.get('ssh_host'): vm_['ssh_host'] = None # add DNS records, set ssh_host, default to first found IP, preferring IPv4 for ssh bootstrap script target addr_families, dns_arec_types = (('v4', 'v6'), ('A', 'AAAA')) arec_map = dict(list(zip(addr_families, dns_arec_types))) for facing, addr_family, ip_address in [(net['type'], family, net['ip_address']) for family in addr_families for net in data['networks'][family]]: log.info('found %s IP%s interface for "%s"', facing, addr_family, ip_address) dns_rec_type = arec_map[addr_family] if facing == 'public': if create_dns_record: __add_dns_addr__(dns_rec_type, ip_address) if facing == ssh_interface: if not vm_['ssh_host']: vm_['ssh_host'] = ip_address if vm_['ssh_host'] is None: raise SaltCloudSystemExit( 'No suitable IP addresses found for ssh minion bootstrapping: {0}'.format(repr(data['networks'])) ) log.debug( 'Found public IP address to use for ssh minion bootstrapping: %s', vm_['ssh_host'] ) vm_['key_filename'] = key_filename ret = __utils__['cloud.bootstrap'](vm_, __opts__) ret.update(data) log.info('Created Cloud VM \'%s\'', vm_['name']) log.debug( '\'%s\' VM creation details:\n%s', vm_['name'], pprint.pformat(data) ) __utils__['cloud.fire_event']( 'event', 'created instance', 'salt/cloud/{0}/created'.format(vm_['name']), args=__utils__['cloud.filter_event']('created', vm_, ['name', 'profile', 'provider', 'driver']), sock_dir=__opts__['sock_dir'], transport=__opts__['transport'] ) return ret def query(method='droplets', droplet_id=None, command=None, args=None, http_method='get'): ''' Make a web call to DigitalOcean ''' base_path = six.text_type(config.get_cloud_config_value( 'api_root', get_configured_provider(), __opts__, search_global=False, default='https://api.digitalocean.com/v2' )) path = '{0}/{1}/'.format(base_path, method) if droplet_id: path += '{0}/'.format(droplet_id) if command: path += command if not isinstance(args, dict): args = {} personal_access_token = config.get_cloud_config_value( 'personal_access_token', get_configured_provider(), __opts__, search_global=False ) data = salt.utils.json.dumps(args) requester = getattr(requests, http_method) request = requester(path, data=data, headers={'Authorization': 'Bearer ' + personal_access_token, 'Content-Type': 'application/json'}) if request.status_code > 299: raise SaltCloudSystemExit( 'An error occurred while querying DigitalOcean. HTTP Code: {0} ' 'Error: \'{1}\''.format( request.status_code, # request.read() request.text ) ) log.debug(request.url) # success without data if request.status_code == 204: return True content = request.text result = salt.utils.json.loads(content) if result.get('status', '').lower() == 'error': raise SaltCloudSystemExit( pprint.pformat(result.get('error_message', {})) ) return result 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 show_instance(name, call=None): ''' Show the details from DigitalOcean concerning a droplet ''' if call != 'action': raise SaltCloudSystemExit( 'The show_instance action must be called with -a or --action.' ) node = _get_node(name) __utils__['cloud.cache_node'](node, __active_provider_name__, __opts__) return node def _get_node(name): attempts = 10 while attempts >= 0: try: return list_nodes_full(for_output=False)[name] except KeyError: attempts -= 1 log.debug( 'Failed to get the data for node \'%s\'. Remaining ' 'attempts: %s', name, attempts ) # Just a little delay between attempts... time.sleep(0.5) return {} def list_keypairs(call=None): ''' Return a dict of all available VM locations on the cloud provider with relevant data ''' if call != 'function': log.error( 'The list_keypairs function must be called with -f or --function.' ) return False fetch = True page = 1 ret = {} while fetch: items = query(method='account/keys', command='?page=' + six.text_type(page) + '&per_page=100') for key_pair in items['ssh_keys']: name = key_pair['name'] if name in ret: raise SaltCloudSystemExit( 'A duplicate key pair name, \'{0}\', was found in DigitalOcean\'s ' 'key pair list. Please change the key name stored by DigitalOcean. ' 'Be sure to adjust the value of \'ssh_key_file\' in your cloud ' 'profile or provider configuration, if necessary.'.format( name ) ) ret[name] = {} for item in six.iterkeys(key_pair): ret[name][item] = six.text_type(key_pair[item]) page += 1 try: fetch = 'next' in items['links']['pages'] except KeyError: fetch = False return ret def show_keypair(kwargs=None, call=None): ''' Show the details of an SSH keypair ''' if call != 'function': log.error( 'The show_keypair function must be called with -f or --function.' ) return False if not kwargs: kwargs = {} if 'keyname' not in kwargs: log.error('A keyname is required.') return False keypairs = list_keypairs(call='function') keyid = keypairs[kwargs['keyname']]['id'] log.debug('Key ID is %s', keyid) details = query(method='account/keys', command=keyid) return details def import_keypair(kwargs=None, call=None): ''' Upload public key to cloud provider. Similar to EC2 import_keypair. .. versionadded:: 2016.11.0 kwargs file(mandatory): public key file-name keyname(mandatory): public key name in the provider ''' with salt.utils.files.fopen(kwargs['file'], 'r') as public_key_filename: public_key_content = salt.utils.stringutils.to_unicode(public_key_filename.read()) digitalocean_kwargs = { 'name': kwargs['keyname'], 'public_key': public_key_content } created_result = create_key(digitalocean_kwargs, call=call) return created_result def create_key(kwargs=None, call=None): ''' Upload a public key ''' if call != 'function': log.error( 'The create_key function must be called with -f or --function.' ) return False try: result = query( method='account', command='keys', args={'name': kwargs['name'], 'public_key': kwargs['public_key']}, http_method='post' ) except KeyError: log.info('`name` and `public_key` arguments must be specified') return False return result def remove_key(kwargs=None, call=None): ''' Delete public key ''' if call != 'function': log.error( 'The create_key function must be called with -f or --function.' ) return False try: result = query( method='account', command='keys/' + kwargs['id'], http_method='delete' ) except KeyError: log.info('`id` argument must be specified') return False return result def get_keyid(keyname): ''' Return the ID of the keyname ''' if not keyname: return None keypairs = list_keypairs(call='function') keyid = keypairs[keyname]['id'] if keyid: return keyid raise SaltCloudNotFound('The specified ssh key could not be found.') def destroy(name, call=None): ''' Destroy a node. Will check termination protection and warn if enabled. 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'] ) data = show_instance(name, call='action') node = query(method='droplets', droplet_id=data['id'], http_method='delete') ## This is all terribly optomistic: # vm_ = get_vm_config(name=name) # delete_dns_record = config.get_cloud_config_value( # 'delete_dns_record', vm_, __opts__, search_global=False, default=None, # ) # TODO: when _vm config data can be made available, we should honor the configuration settings, # but until then, we should assume stale DNS records are bad, and default behavior should be to # delete them if we can. When this is resolved, also resolve the comments a couple of lines below. delete_dns_record = True if not isinstance(delete_dns_record, bool): raise SaltCloudConfigError( '\'delete_dns_record\' should be a boolean value.' ) # When the "to do" a few lines up is resolved, remove these lines and use the if/else logic below. log.debug('Deleting DNS records for %s.', name) destroy_dns_records(name) # Until the "to do" from line 754 is taken care of, we don't need this logic. # if delete_dns_record: # log.debug('Deleting DNS records for %s.', name) # destroy_dns_records(name) # else: # log.debug('delete_dns_record : %s', delete_dns_record) # for line in pprint.pformat(dir()).splitlines(): # log.debug('delete context: %s', line) __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 node def post_dns_record(**kwargs): ''' Creates a DNS record for the given name if the domain is managed with DO. ''' if 'kwargs' in kwargs: # flatten kwargs if called via salt-cloud -f f_kwargs = kwargs['kwargs'] del kwargs['kwargs'] kwargs.update(f_kwargs) mandatory_kwargs = ('dns_domain', 'name', 'record_type', 'record_data') for i in mandatory_kwargs: if kwargs[i]: pass else: error = '{0}="{1}" ## all mandatory args must be provided: {2}'.format(i, kwargs[i], mandatory_kwargs) raise SaltInvocationError(error) domain = query(method='domains', droplet_id=kwargs['dns_domain']) if domain: result = query( method='domains', droplet_id=kwargs['dns_domain'], command='records', args={'type': kwargs['record_type'], 'name': kwargs['name'], 'data': kwargs['record_data']}, http_method='post' ) return result return False def show_pricing(kwargs=None, call=None): ''' Show pricing for a particular profile. This is only an estimate, based on unofficial pricing sources. .. versionadded:: 2015.8.0 CLI Examples: .. code-block:: bash salt-cloud -f show_pricing my-digitalocean-config profile=my-profile ''' profile = __opts__['profiles'].get(kwargs['profile'], {}) if not profile: return {'Error': 'The requested profile was not found'} # Make sure the profile belongs to DigitalOcean provider = profile.get('provider', '0:0') comps = provider.split(':') if len(comps) < 2 or comps[1] != 'digitalocean': return {'Error': 'The requested profile does not belong to DigitalOcean'} raw = {} ret = {} sizes = avail_sizes() ret['per_hour'] = decimal.Decimal(sizes[profile['size']]['price_hourly']) ret['per_day'] = ret['per_hour'] * 24 ret['per_week'] = ret['per_day'] * 7 ret['per_month'] = decimal.Decimal(sizes[profile['size']]['price_monthly']) ret['per_year'] = ret['per_week'] * 52 if kwargs.get('raw', False): ret['_raw'] = raw return {profile['profile']: ret} def list_floating_ips(call=None): ''' Return a list of the floating ips that are on the provider .. versionadded:: 2016.3.0 CLI Examples: .. code-block:: bash salt-cloud -f list_floating_ips my-digitalocean-config ''' if call == 'action': raise SaltCloudSystemExit( 'The list_floating_ips function must be called with ' '-f or --function, or with the --list-floating-ips option' ) fetch = True page = 1 ret = {} while fetch: items = query(method='floating_ips', command='?page=' + six.text_type(page) + '&per_page=200') for floating_ip in items['floating_ips']: ret[floating_ip['ip']] = {} for item in six.iterkeys(floating_ip): ret[floating_ip['ip']][item] = floating_ip[item] page += 1 try: fetch = 'next' in items['links']['pages'] except KeyError: fetch = False return ret def show_floating_ip(kwargs=None, call=None): ''' Show the details of a floating IP .. versionadded:: 2016.3.0 CLI Examples: .. code-block:: bash salt-cloud -f show_floating_ip my-digitalocean-config floating_ip='45.55.96.47' ''' if call != 'function': log.error( 'The show_floating_ip function must be called with -f or --function.' ) return False if not kwargs: kwargs = {} if 'floating_ip' not in kwargs: log.error('A floating IP is required.') return False floating_ip = kwargs['floating_ip'] log.debug('Floating ip is %s', floating_ip) details = query(method='floating_ips', command=floating_ip) return details def create_floating_ip(kwargs=None, call=None): ''' Create a new floating IP .. versionadded:: 2016.3.0 CLI Examples: .. code-block:: bash salt-cloud -f create_floating_ip my-digitalocean-config region='NYC2' salt-cloud -f create_floating_ip my-digitalocean-config droplet_id='1234567' ''' if call != 'function': log.error( 'The create_floating_ip function must be called with -f or --function.' ) return False if not kwargs: kwargs = {} if 'droplet_id' in kwargs: result = query(method='floating_ips', args={'droplet_id': kwargs['droplet_id']}, http_method='post') return result elif 'region' in kwargs: result = query(method='floating_ips', args={'region': kwargs['region']}, http_method='post') return result else: log.error('A droplet_id or region is required.') return False def delete_floating_ip(kwargs=None, call=None): ''' Delete a floating IP .. versionadded:: 2016.3.0 CLI Examples: .. code-block:: bash salt-cloud -f delete_floating_ip my-digitalocean-config floating_ip='45.55.96.47' ''' if call != 'function': log.error( 'The delete_floating_ip function must be called with -f or --function.' ) return False if not kwargs: kwargs = {} if 'floating_ip' not in kwargs: log.error('A floating IP is required.') return False floating_ip = kwargs['floating_ip'] log.debug('Floating ip is %s', kwargs['floating_ip']) result = query(method='floating_ips', command=floating_ip, http_method='delete') return result def assign_floating_ip(kwargs=None, call=None): ''' Assign a floating IP .. versionadded:: 2016.3.0 CLI Examples: .. code-block:: bash salt-cloud -f assign_floating_ip my-digitalocean-config droplet_id=1234567 floating_ip='45.55.96.47' ''' if call != 'function': log.error( 'The assign_floating_ip function must be called with -f or --function.' ) return False if not kwargs: kwargs = {} if 'floating_ip' and 'droplet_id' not in kwargs: log.error('A floating IP and droplet_id is required.') return False result = query(method='floating_ips', command=kwargs['floating_ip'] + '/actions', args={'droplet_id': kwargs['droplet_id'], 'type': 'assign'}, http_method='post') return result def unassign_floating_ip(kwargs=None, call=None): ''' Unassign a floating IP .. versionadded:: 2016.3.0 CLI Examples: .. code-block:: bash salt-cloud -f unassign_floating_ip my-digitalocean-config floating_ip='45.55.96.47' ''' if call != 'function': log.error( 'The inassign_floating_ip function must be called with -f or --function.' ) return False if not kwargs: kwargs = {} if 'floating_ip' not in kwargs: log.error('A floating IP is required.') return False result = query(method='floating_ips', command=kwargs['floating_ip'] + '/actions', args={'type': 'unassign'}, http_method='post') return result def _list_nodes(full=False, for_output=False): ''' Helper function to format and parse node data. ''' fetch = True page = 1 ret = {} while fetch: items = query(method='droplets', command='?page=' + six.text_type(page) + '&per_page=200') for node in items['droplets']: name = node['name'] ret[name] = {} if full: ret[name] = _get_full_output(node, for_output=for_output) else: public_ips, private_ips = _get_ips(node['networks']) ret[name] = { 'id': node['id'], 'image': node['image']['name'], 'name': name, 'private_ips': private_ips, 'public_ips': public_ips, 'size': node['size_slug'], 'state': six.text_type(node['status']), } page += 1 try: fetch = 'next' in items['links']['pages'] except KeyError: fetch = False return ret def reboot(name, call=None): ''' Reboot a droplet in DigitalOcean. .. versionadded:: 2015.8.8 name The name of the droplet to restart. CLI Example: .. code-block:: bash salt-cloud -a reboot droplet_name ''' if call != 'action': raise SaltCloudSystemExit( 'The restart action must be called with -a or --action.' ) data = show_instance(name, call='action') if data.get('status') == 'off': return {'success': True, 'action': 'stop', 'status': 'off', 'msg': 'Machine is already off.'} ret = query(droplet_id=data['id'], command='actions', args={'type': 'reboot'}, http_method='post') return {'success': True, 'action': ret['action']['type'], 'state': ret['action']['status']} def start(name, call=None): ''' Start a droplet in DigitalOcean. .. versionadded:: 2015.8.8 name The name of the droplet to start. CLI Example: .. code-block:: bash salt-cloud -a start droplet_name ''' if call != 'action': raise SaltCloudSystemExit( 'The start action must be called with -a or --action.' ) data = show_instance(name, call='action') if data.get('status') == 'active': return {'success': True, 'action': 'start', 'status': 'active', 'msg': 'Machine is already running.'} ret = query(droplet_id=data['id'], command='actions', args={'type': 'power_on'}, http_method='post') return {'success': True, 'action': ret['action']['type'], 'state': ret['action']['status']} def stop(name, call=None): ''' Stop a droplet in DigitalOcean. .. versionadded:: 2015.8.8 name The name of the droplet to stop. CLI Example: .. code-block:: bash salt-cloud -a stop droplet_name ''' if call != 'action': raise SaltCloudSystemExit( 'The stop action must be called with -a or --action.' ) data = show_instance(name, call='action') if data.get('status') == 'off': return {'success': True, 'action': 'stop', 'status': 'off', 'msg': 'Machine is already off.'} ret = query(droplet_id=data['id'], command='actions', args={'type': 'shutdown'}, http_method='post') return {'success': True, 'action': ret['action']['type'], 'state': ret['action']['status']} def _get_full_output(node, for_output=False): ''' Helper function for _list_nodes to loop through all node information. Returns a dictionary containing the full information of a node. ''' ret = {} for item in six.iterkeys(node): value = node[item] if value is not None and for_output: value = six.text_type(value) ret[item] = value return ret def _get_ips(networks): ''' Helper function for list_nodes. Returns public and private ip lists based on a given network dictionary. ''' v4s = networks.get('v4') v6s = networks.get('v6') public_ips = [] private_ips = [] if v4s: for item in v4s: ip_type = item.get('type') ip_address = item.get('ip_address') if ip_type == 'public': public_ips.append(ip_address) if ip_type == 'private': private_ips.append(ip_address) if v6s: for item in v6s: ip_type = item.get('type') ip_address = item.get('ip_address') if ip_type == 'public': public_ips.append(ip_address) if ip_type == 'private': private_ips.append(ip_address) return public_ips, private_ips