1
0

test_network.py 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639
  1. # -*- coding: utf-8 -*-
  2. # Import Python libs
  3. from __future__ import absolute_import, unicode_literals, print_function
  4. import logging
  5. import socket
  6. import textwrap
  7. # Import Salt Testing libs
  8. from tests.support.unit import skipIf
  9. from tests.support.unit import TestCase
  10. from tests.support.mock import (
  11. MagicMock,
  12. mock_open,
  13. patch,
  14. NO_MOCK,
  15. NO_MOCK_REASON,
  16. )
  17. # Import salt libs
  18. import salt.utils.network as network
  19. from salt._compat import ipaddress
  20. log = logging.getLogger(__name__)
  21. LINUX = '''\
  22. eth0 Link encap:Ethernet HWaddr e0:3f:49:85:6a:af
  23. inet addr:10.10.10.56 Bcast:10.10.10.255 Mask:255.255.252.0
  24. inet6 addr: fe80::e23f:49ff:fe85:6aaf/64 Scope:Link
  25. UP BROADCAST RUNNING MULTICAST MTU:1500 Metric:1
  26. RX packets:643363 errors:0 dropped:0 overruns:0 frame:0
  27. TX packets:196539 errors:0 dropped:0 overruns:0 carrier:0
  28. collisions:0 txqueuelen:1000
  29. RX bytes:386388355 (368.4 MiB) TX bytes:25600939 (24.4 MiB)
  30. lo Link encap:Local Loopback
  31. inet addr:127.0.0.1 Mask:255.0.0.0
  32. inet6 addr: ::1/128 Scope:Host
  33. UP LOOPBACK RUNNING MTU:65536 Metric:1
  34. RX packets:548901 errors:0 dropped:0 overruns:0 frame:0
  35. TX packets:548901 errors:0 dropped:0 overruns:0 carrier:0
  36. collisions:0 txqueuelen:0
  37. RX bytes:613479895 (585.0 MiB) TX bytes:613479895 (585.0 MiB)
  38. '''
  39. FREEBSD = '''
  40. em0: flags=8843<UP,BROADCAST,RUNNING,SIMPLEX,MULTICAST> metric 0 mtu 1500
  41. options=4219b<RXCSUM,TXCSUM,VLAN_MTU,VLAN_HWTAGGING,VLAN_HWCSUM,TSO4,WOL_MAGIC,VLAN_HWTSO>
  42. ether 00:30:48:ff:ff:ff
  43. inet 10.10.10.250 netmask 0xffffffe0 broadcast 10.10.10.255
  44. inet 10.10.10.56 netmask 0xffffffc0 broadcast 10.10.10.63
  45. media: Ethernet autoselect (1000baseT <full-duplex>)
  46. status: active
  47. em1: flags=8c02<BROADCAST,OACTIVE,SIMPLEX,MULTICAST> metric 0 mtu 1500
  48. options=4219b<RXCSUM,TXCSUM,VLAN_MTU,VLAN_HWTAGGING,VLAN_HWCSUM,TSO4,WOL_MAGIC,VLAN_HWTSO>
  49. ether 00:30:48:aa:aa:aa
  50. media: Ethernet autoselect
  51. status: no carrier
  52. plip0: flags=8810<POINTOPOINT,SIMPLEX,MULTICAST> metric 0 mtu 1500
  53. lo0: flags=8049<UP,LOOPBACK,RUNNING,MULTICAST> metric 0 mtu 16384
  54. options=3<RXCSUM,TXCSUM>
  55. inet6 fe80::1%lo0 prefixlen 64 scopeid 0x8
  56. inet6 ::1 prefixlen 128
  57. inet 127.0.0.1 netmask 0xff000000
  58. nd6 options=3<PERFORMNUD,ACCEPT_RTADV>
  59. tun0: flags=8051<UP,POINTOPOINT,RUNNING,MULTICAST> metric 0 mtu 1500
  60. options=80000<LINKSTATE>
  61. inet 10.12.0.1 --> 10.12.0.2 netmask 0xffffffff
  62. Opened by PID 1964
  63. '''
  64. SOLARIS = '''\
  65. lo0: flags=2001000849<UP,LOOPBACK,RUNNING,MULTICAST,IPv4,VIRTUAL> mtu 8232 index 1
  66. inet 127.0.0.1 netmask ff000000
  67. net0: flags=100001100943<UP,BROADCAST,RUNNING,PROMISC,MULTICAST,ROUTER,IPv4,PHYSRUNNING> mtu 1500 index 2
  68. inet 10.10.10.38 netmask ffffffe0 broadcast 10.10.10.63
  69. ilbint0: flags=110001100843<UP,BROADCAST,RUNNING,MULTICAST,ROUTER,IPv4,VRRP,PHYSRUNNING> mtu 1500 index 3
  70. inet 10.6.0.11 netmask ffffff00 broadcast 10.6.0.255
  71. ilbext0: flags=110001100843<UP,BROADCAST,RUNNING,MULTICAST,ROUTER,IPv4,VRRP,PHYSRUNNING> mtu 1500 index 4
  72. inet 10.10.11.11 netmask ffffffe0 broadcast 10.10.11.31
  73. ilbext0:1: flags=110001100843<UP,BROADCAST,RUNNING,MULTICAST,ROUTER,IPv4,VRRP,PHYSRUNNING> mtu 1500 index 4
  74. inet 10.10.11.12 netmask ffffffe0 broadcast 10.10.11.31
  75. vpn0: flags=1000011008d1<UP,POINTOPOINT,RUNNING,NOARP,MULTICAST,ROUTER,IPv4,PHYSRUNNING> mtu 1480 index 5
  76. inet tunnel src 10.10.11.12 tunnel dst 10.10.5.5
  77. tunnel hop limit 64
  78. inet 10.6.0.14 --> 10.6.0.15 netmask ff000000
  79. lo0: flags=2002000849<UP,LOOPBACK,RUNNING,MULTICAST,IPv6,VIRTUAL> mtu 8252 index 1
  80. inet6 ::1/128
  81. net0: flags=120002004941<UP,RUNNING,PROMISC,MULTICAST,DHCP,IPv6,PHYSRUNNING> mtu 1500 index 2
  82. inet6 fe80::221:9bff:fefd:2a22/10
  83. ilbint0: flags=120002000840<RUNNING,MULTICAST,IPv6,PHYSRUNNING> mtu 1500 index 3
  84. inet6 ::/0
  85. ilbext0: flags=120002000840<RUNNING,MULTICAST,IPv6,PHYSRUNNING> mtu 1500 index 4
  86. inet6 ::/0
  87. vpn0: flags=120002200850<POINTOPOINT,RUNNING,MULTICAST,NONUD,IPv6,PHYSRUNNING> mtu 1480 index 5
  88. inet tunnel src 10.10.11.12 tunnel dst 10.10.5.5
  89. tunnel hop limit 64
  90. inet6 ::/0 --> fe80::b2d6:7c10
  91. '''
  92. NETBSD = '''\
  93. vioif0: flags=0x8943<UP,BROADCAST,RUNNING,PROMISC,SIMPLEX,MULTICAST> mtu 1500
  94. ec_capabilities=1<VLAN_MTU>
  95. ec_enabled=0
  96. address: 00:a0:98:e6:83:18
  97. inet 192.168.1.80/24 broadcast 192.168.1.255 flags 0x0
  98. inet6 fe80::2a0:98ff:fee6:8318%vioif0/64 flags 0x0 scopeid 0x1
  99. lo0: flags=0x8049<UP,LOOPBACK,RUNNING,MULTICAST> mtu 33624
  100. inet 127.0.0.1/8 flags 0x0
  101. inet6 ::1/128 flags 0x20<NODAD>
  102. inet6 fe80::1%lo0/64 flags 0x0 scopeid 0x2
  103. '''
  104. FREEBSD_SOCKSTAT = '''\
  105. USER COMMAND PID FD PROTO LOCAL ADDRESS FOREIGN ADDRESS
  106. root python2.7 1294 41 tcp4 127.0.0.1:61115 127.0.0.1:4506
  107. '''
  108. FREEBSD_SOCKSTAT_WITH_FAT_PID = '''\
  109. USER COMMAND PID FD PROTO LOCAL ADDRESS FOREIGN ADDRESS
  110. salt-master python2.781106 35 tcp4 127.0.0.1:61115 127.0.0.1:4506
  111. '''
  112. IPV4_SUBNETS = {True: ('10.10.0.0/24',),
  113. False: ('10.10.0.0', '10.10.0.0/33', 'FOO', 9, '0.9.800.1000/24')}
  114. IPV6_SUBNETS = {True: ('::1/128',),
  115. False: ('::1', '::1/129', 'FOO', 9, 'aj01::feac/64')}
  116. @skipIf(NO_MOCK, NO_MOCK_REASON)
  117. class NetworkTestCase(TestCase):
  118. def test_sanitize_host(self):
  119. ret = network.sanitize_host('10.1./2.$3')
  120. self.assertEqual(ret, '10.1.2.3')
  121. def test_host_to_ips(self):
  122. '''
  123. NOTE: When this test fails it's usually because the IP address has
  124. changed. In these cases, we just need to update the IP address in the
  125. assertion.
  126. '''
  127. def _side_effect(host, *args):
  128. try:
  129. return {
  130. 'github.com': [
  131. (2, 1, 6, '', ('192.30.255.112', 0)),
  132. (2, 1, 6, '', ('192.30.255.113', 0)),
  133. ],
  134. 'ipv6host.foo': [
  135. (socket.AF_INET6, 1, 6, '', ('2001:a71::1', 0, 0, 0)),
  136. ],
  137. }[host]
  138. except KeyError:
  139. raise socket.gaierror(-2, 'Name or service not known')
  140. getaddrinfo_mock = MagicMock(side_effect=_side_effect)
  141. with patch.object(socket, 'getaddrinfo', getaddrinfo_mock):
  142. # Test host that can be resolved
  143. ret = network.host_to_ips('github.com')
  144. self.assertEqual(ret, ['192.30.255.112', '192.30.255.113'])
  145. # Test ipv6
  146. ret = network.host_to_ips('ipv6host.foo')
  147. self.assertEqual(ret, ['2001:a71::1'])
  148. # Test host that can't be resolved
  149. ret = network.host_to_ips('someothersite.com')
  150. self.assertEqual(ret, None)
  151. def test_generate_minion_id(self):
  152. self.assertTrue(network.generate_minion_id())
  153. def test__generate_minion_id_with_unicode_in_etc_hosts(self):
  154. '''
  155. Test that unicode in /etc/hosts doesn't raise an error when
  156. _generate_minion_id() helper is called to gather the hosts.
  157. '''
  158. content = textwrap.dedent('''\
  159. # 以下为主机名解析
  160. ## ccc
  161. 127.0.0.1 localhost thisismyhostname # 本机
  162. ''')
  163. fopen_mock = mock_open(read_data={'/etc/hosts': content})
  164. with patch('salt.utils.files.fopen', fopen_mock):
  165. assert 'thisismyhostname' in network._generate_minion_id()
  166. def test_is_ip(self):
  167. self.assertTrue(network.is_ip('10.10.0.3'))
  168. self.assertFalse(network.is_ip('0.9.800.1000'))
  169. # Check 16-char-long unicode string
  170. # https://github.com/saltstack/salt/issues/51258
  171. self.assertFalse(network.is_ipv6('sixteen-char-str'))
  172. def test_is_ipv4(self):
  173. self.assertTrue(network.is_ipv4('10.10.0.3'))
  174. self.assertFalse(network.is_ipv4('10.100.1'))
  175. self.assertFalse(network.is_ipv4('2001:db8:0:1:1:1:1:1'))
  176. # Check 16-char-long unicode string
  177. # https://github.com/saltstack/salt/issues/51258
  178. self.assertFalse(network.is_ipv4('sixteen-char-str'))
  179. def test_is_ipv6(self):
  180. self.assertTrue(network.is_ipv6('2001:db8:0:1:1:1:1:1'))
  181. self.assertTrue(network.is_ipv6('0:0:0:0:0:0:0:1'))
  182. self.assertTrue(network.is_ipv6('::1'))
  183. self.assertTrue(network.is_ipv6('::'))
  184. self.assertTrue(network.is_ipv6('2001:0db8:85a3:0000:0000:8a2e:0370:7334'))
  185. self.assertTrue(network.is_ipv6('2001:0db8:85a3::8a2e:0370:7334'))
  186. self.assertFalse(network.is_ipv6('2001:0db8:0370:7334'))
  187. self.assertFalse(network.is_ipv6('2001:0db8:::0370:7334'))
  188. self.assertFalse(network.is_ipv6('10.0.1.2'))
  189. self.assertFalse(network.is_ipv6('2001.0db8.85a3.0000.0000.8a2e.0370.7334'))
  190. # Check 16-char-long unicode string
  191. # https://github.com/saltstack/salt/issues/51258
  192. self.assertFalse(network.is_ipv6('sixteen-char-str'))
  193. def test_parse_host_port(self):
  194. _ip = ipaddress.ip_address
  195. good_host_ports = {
  196. '10.10.0.3': (_ip('10.10.0.3').compressed, None),
  197. '10.10.0.3:1234': (_ip('10.10.0.3').compressed, 1234),
  198. '2001:0db8:85a3::8a2e:0370:7334': (_ip('2001:0db8:85a3::8a2e:0370:7334').compressed, None),
  199. '[2001:0db8:85a3::8a2e:0370:7334]:1234': (_ip('2001:0db8:85a3::8a2e:0370:7334').compressed, 1234),
  200. '2001:0db8:85a3::7334': (_ip('2001:0db8:85a3::7334').compressed, None),
  201. '[2001:0db8:85a3::7334]:1234': (_ip('2001:0db8:85a3::7334').compressed, 1234)
  202. }
  203. bad_host_ports = [
  204. '10.10.0.3/24',
  205. '10.10.0.3::1234',
  206. '2001:0db8:0370:7334',
  207. '2001:0db8:0370::7334]:1234',
  208. '2001:0db8:0370:0:a:b:c:d:1234'
  209. ]
  210. for host_port, assertion_value in good_host_ports.items():
  211. host = port = None
  212. host, port = network.parse_host_port(host_port)
  213. self.assertEqual((host, port), assertion_value)
  214. for host_port in bad_host_ports:
  215. try:
  216. self.assertRaises(ValueError, network.parse_host_port, host_port)
  217. except AssertionError as _e_:
  218. log.error('bad host_port value: "%s" failed to trigger ValueError exception', host_port)
  219. raise _e_
  220. def test_dns_check(self):
  221. class MockSocket(object):
  222. def __init__(self, *args, **kwargs):
  223. pass
  224. def __call__(self, *args, **kwargs):
  225. pass
  226. def setsockopt(self, *args, **kwargs):
  227. pass
  228. def sendto(self, *args, **kwargs):
  229. pass
  230. def connect(self, *args, **kwargs):
  231. pass
  232. def close(self, *args, **kwargs):
  233. pass
  234. hosts = [
  235. {'host': '10.10.0.3',
  236. 'port': '',
  237. 'mocked': [(2, 1, 6, '', ('10.10.0.3', 0))],
  238. 'ret': '10.10.0.3'},
  239. {'host': '10.10.0.3',
  240. 'port': '1234',
  241. 'mocked': [(2, 1, 6, '', ('10.10.0.3', 0))],
  242. 'ret': '10.10.0.3'},
  243. {'host': '2001:0db8:85a3::8a2e:0370:7334',
  244. 'port': '',
  245. 'mocked': [(10, 1, 6, '', ('2001:db8:85a3::8a2e:370:7334', 0, 0, 0))],
  246. 'ret': '2001:db8:85a3::8a2e:370:7334'},
  247. {'host': '2001:0db8:85a3::8a2e:370:7334',
  248. 'port': '1234',
  249. 'mocked': [(10, 1, 6, '', ('2001:db8:85a3::8a2e:370:7334', 0, 0, 0))],
  250. 'ret': '2001:db8:85a3::8a2e:370:7334'},
  251. {'host': 'salt-master',
  252. 'port': '1234',
  253. 'mocked': [(2, 1, 6, '', ('127.0.0.1', 0))],
  254. 'ret': '127.0.0.1'},
  255. ]
  256. for host in hosts:
  257. with patch.object(socket, 'getaddrinfo', MagicMock(return_value=host['mocked'])):
  258. with patch('socket.socket', MockSocket):
  259. ret = network.dns_check(host['host'], host['port'])
  260. self.assertEqual(ret, host['ret'])
  261. def test_is_subnet(self):
  262. for subnet_data in (IPV4_SUBNETS, IPV6_SUBNETS):
  263. for item in subnet_data[True]:
  264. log.debug('Testing that %s is a valid subnet', item)
  265. self.assertTrue(network.is_subnet(item))
  266. for item in subnet_data[False]:
  267. log.debug('Testing that %s is not a valid subnet', item)
  268. self.assertFalse(network.is_subnet(item))
  269. def test_is_ipv4_subnet(self):
  270. for item in IPV4_SUBNETS[True]:
  271. log.debug('Testing that %s is a valid subnet', item)
  272. self.assertTrue(network.is_ipv4_subnet(item))
  273. for item in IPV4_SUBNETS[False]:
  274. log.debug('Testing that %s is not a valid subnet', item)
  275. self.assertFalse(network.is_ipv4_subnet(item))
  276. def test_is_ipv6_subnet(self):
  277. for item in IPV6_SUBNETS[True]:
  278. log.debug('Testing that %s is a valid subnet', item)
  279. self.assertTrue(network.is_ipv6_subnet(item))
  280. for item in IPV6_SUBNETS[False]:
  281. log.debug('Testing that %s is not a valid subnet', item)
  282. self.assertFalse(network.is_ipv6_subnet(item))
  283. def test_cidr_to_ipv4_netmask(self):
  284. self.assertEqual(network.cidr_to_ipv4_netmask(24), '255.255.255.0')
  285. self.assertEqual(network.cidr_to_ipv4_netmask(21), '255.255.248.0')
  286. self.assertEqual(network.cidr_to_ipv4_netmask(17), '255.255.128.0')
  287. self.assertEqual(network.cidr_to_ipv4_netmask(9), '255.128.0.0')
  288. self.assertEqual(network.cidr_to_ipv4_netmask(36), '')
  289. self.assertEqual(network.cidr_to_ipv4_netmask('lol'), '')
  290. def test_number_of_set_bits_to_ipv4_netmask(self):
  291. set_bits_to_netmask = network._number_of_set_bits_to_ipv4_netmask(0xffffff00)
  292. self.assertEqual(set_bits_to_netmask, '255.255.255.0')
  293. set_bits_to_netmask = network._number_of_set_bits_to_ipv4_netmask(0xffff6400)
  294. def test_hex2ip(self):
  295. self.assertEqual(network.hex2ip('0x4A7D2B63'), '74.125.43.99')
  296. self.assertEqual(network.hex2ip('0x4A7D2B63', invert=True), '99.43.125.74')
  297. self.assertEqual(network.hex2ip('00000000000000000000FFFF7F000001'), '127.0.0.1')
  298. self.assertEqual(network.hex2ip('0000000000000000FFFF00000100007F', invert=True), '127.0.0.1')
  299. self.assertEqual(network.hex2ip('20010DB8000000000000000000000000'), '2001:db8::')
  300. self.assertEqual(network.hex2ip('B80D0120000000000000000000000000', invert=True), '2001:db8::')
  301. def test_interfaces_ifconfig_linux(self):
  302. interfaces = network._interfaces_ifconfig(LINUX)
  303. self.assertEqual(interfaces,
  304. {'eth0': {'hwaddr': 'e0:3f:49:85:6a:af',
  305. 'inet': [{'address': '10.10.10.56',
  306. 'broadcast': '10.10.10.255',
  307. 'netmask': '255.255.252.0'}],
  308. 'inet6': [{'address': 'fe80::e23f:49ff:fe85:6aaf',
  309. 'prefixlen': '64',
  310. 'scope': 'link'}],
  311. 'up': True},
  312. 'lo': {'inet': [{'address': '127.0.0.1',
  313. 'netmask': '255.0.0.0'}],
  314. 'inet6': [{'address': '::1',
  315. 'prefixlen': '128',
  316. 'scope': 'host'}],
  317. 'up': True}}
  318. )
  319. def test_interfaces_ifconfig_freebsd(self):
  320. interfaces = network._interfaces_ifconfig(FREEBSD)
  321. self.assertEqual(interfaces,
  322. {'': {'up': False},
  323. 'em0': {'hwaddr': '00:30:48:ff:ff:ff',
  324. 'inet': [{'address': '10.10.10.250',
  325. 'broadcast': '10.10.10.255',
  326. 'netmask': '255.255.255.224'},
  327. {'address': '10.10.10.56',
  328. 'broadcast': '10.10.10.63',
  329. 'netmask': '255.255.255.192'}],
  330. 'up': True},
  331. 'em1': {'hwaddr': '00:30:48:aa:aa:aa',
  332. 'up': False},
  333. 'lo0': {'inet': [{'address': '127.0.0.1',
  334. 'netmask': '255.0.0.0'}],
  335. 'inet6': [{'address': 'fe80::1',
  336. 'prefixlen': '64',
  337. 'scope': '0x8'},
  338. {'address': '::1',
  339. 'prefixlen': '128',
  340. 'scope': None}],
  341. 'up': True},
  342. 'plip0': {'up': False},
  343. 'tun0': {'inet': [{'address': '10.12.0.1',
  344. 'netmask': '255.255.255.255'}],
  345. 'up': True}}
  346. )
  347. def test_interfaces_ifconfig_solaris(self):
  348. with patch('salt.utils.platform.is_sunos', lambda: True):
  349. interfaces = network._interfaces_ifconfig(SOLARIS)
  350. expected_interfaces = {'ilbint0':
  351. {'inet6': [],
  352. 'inet': [{'broadcast': '10.6.0.255',
  353. 'netmask': '255.255.255.0',
  354. 'address': '10.6.0.11'}],
  355. 'up': True},
  356. 'lo0':
  357. {'inet6': [{'prefixlen': '128',
  358. 'address': '::1'}],
  359. 'inet': [{'netmask': '255.0.0.0',
  360. 'address': '127.0.0.1'}],
  361. 'up': True},
  362. 'ilbext0': {'inet6': [],
  363. 'inet': [{'broadcast': '10.10.11.31',
  364. 'netmask': '255.255.255.224',
  365. 'address': '10.10.11.11'},
  366. {'broadcast': '10.10.11.31',
  367. 'netmask': '255.255.255.224',
  368. 'address': '10.10.11.12'}],
  369. 'up': True},
  370. 'vpn0': {'inet6': [],
  371. 'inet': [{'netmask': '255.0.0.0',
  372. 'address': '10.6.0.14'}],
  373. 'up': True},
  374. 'net0': {'inet6': [{'prefixlen': '10',
  375. 'address': 'fe80::221:9bff:fefd:2a22'}],
  376. 'inet': [{'broadcast': '10.10.10.63',
  377. 'netmask': '255.255.255.224',
  378. 'address': '10.10.10.38'}],
  379. 'up': True}}
  380. self.assertEqual(interfaces, expected_interfaces)
  381. def test_interfaces_ifconfig_netbsd(self):
  382. interfaces = network._netbsd_interfaces_ifconfig(NETBSD)
  383. self.assertEqual(interfaces,
  384. {'lo0': {'inet': [{'address': '127.0.0.1', 'netmask': '255.0.0.0'}],
  385. 'inet6': [{'address': 'fe80::1',
  386. 'prefixlen': '64',
  387. 'scope': 'lo0'}],
  388. 'up': True},
  389. 'vioif0': {'hwaddr': '00:a0:98:e6:83:18',
  390. 'inet': [{'address': '192.168.1.80',
  391. 'broadcast': '192.168.1.255',
  392. 'netmask': '255.255.255.0'}],
  393. 'inet6': [{'address': 'fe80::2a0:98ff:fee6:8318',
  394. 'prefixlen': '64',
  395. 'scope': 'vioif0'}],
  396. 'up': True}}
  397. )
  398. def test_freebsd_remotes_on(self):
  399. with patch('salt.utils.platform.is_sunos', lambda: False):
  400. with patch('salt.utils.platform.is_freebsd', lambda: True):
  401. with patch('subprocess.check_output',
  402. return_value=FREEBSD_SOCKSTAT):
  403. remotes = network._freebsd_remotes_on('4506', 'remote')
  404. self.assertEqual(remotes, set(['127.0.0.1']))
  405. def test_freebsd_remotes_on_with_fat_pid(self):
  406. with patch('salt.utils.platform.is_sunos', lambda: False):
  407. with patch('salt.utils.platform.is_freebsd', lambda: True):
  408. with patch('subprocess.check_output',
  409. return_value=FREEBSD_SOCKSTAT_WITH_FAT_PID):
  410. remotes = network._freebsd_remotes_on('4506', 'remote')
  411. self.assertEqual(remotes, set(['127.0.0.1']))
  412. def test_generate_minion_id_distinct(self):
  413. '''
  414. Test if minion IDs are distinct in the pool.
  415. :return:
  416. '''
  417. with patch('platform.node', MagicMock(return_value='nodename')), \
  418. patch('socket.gethostname', MagicMock(return_value='hostname')), \
  419. patch('socket.getfqdn', MagicMock(return_value='hostname.domainname.blank')), \
  420. patch('socket.getaddrinfo', MagicMock(return_value=[(2, 3, 0, 'attrname', ('127.0.1.1', 0))])), \
  421. patch('salt.utils.files.fopen', mock_open()), \
  422. patch('salt.utils.network.ip_addrs', MagicMock(return_value=['1.2.3.4', '5.6.7.8'])):
  423. self.assertEqual(network._generate_minion_id(),
  424. ['hostname.domainname.blank', 'nodename', 'hostname', '1.2.3.4', '5.6.7.8'])
  425. def test_generate_minion_id_127_name(self):
  426. '''
  427. Test if minion IDs can be named 127.foo
  428. :return:
  429. '''
  430. with patch('platform.node', MagicMock(return_value='127')), \
  431. patch('socket.gethostname', MagicMock(return_value='127')), \
  432. patch('socket.getfqdn', MagicMock(return_value='127.domainname.blank')), \
  433. patch('socket.getaddrinfo', MagicMock(return_value=[(2, 3, 0, 'attrname', ('127.0.1.1', 0))])), \
  434. patch('salt.utils.files.fopen', mock_open()), \
  435. patch('salt.utils.network.ip_addrs', MagicMock(return_value=['1.2.3.4', '5.6.7.8'])):
  436. self.assertEqual(network._generate_minion_id(),
  437. ['127.domainname.blank', '127', '1.2.3.4', '5.6.7.8'])
  438. def test_generate_minion_id_127_name_startswith(self):
  439. '''
  440. Test if minion IDs can be named starting from "127"
  441. :return:
  442. '''
  443. with patch('platform.node', MagicMock(return_value='127890')), \
  444. patch('socket.gethostname', MagicMock(return_value='127890')), \
  445. patch('socket.getfqdn', MagicMock(return_value='127890.domainname.blank')), \
  446. patch('socket.getaddrinfo', MagicMock(return_value=[(2, 3, 0, 'attrname', ('127.0.1.1', 0))])), \
  447. patch('salt.utils.files.fopen', mock_open()), \
  448. patch('salt.utils.network.ip_addrs', MagicMock(return_value=['1.2.3.4', '5.6.7.8'])):
  449. self.assertEqual(network._generate_minion_id(),
  450. ['127890.domainname.blank', '127890', '1.2.3.4', '5.6.7.8'])
  451. def test_generate_minion_id_duplicate(self):
  452. '''
  453. Test if IP addresses in the minion IDs are distinct in the pool
  454. :return:
  455. '''
  456. with patch('platform.node', MagicMock(return_value='hostname')), \
  457. patch('socket.gethostname', MagicMock(return_value='hostname')), \
  458. patch('socket.getfqdn', MagicMock(return_value='hostname')), \
  459. patch('socket.getaddrinfo', MagicMock(return_value=[(2, 3, 0, 'hostname', ('127.0.1.1', 0))])), \
  460. patch('salt.utils.files.fopen', mock_open()), \
  461. patch('salt.utils.network.ip_addrs', MagicMock(return_value=['1.2.3.4', '1.2.3.4', '1.2.3.4'])):
  462. self.assertEqual(network._generate_minion_id(), ['hostname', '1.2.3.4'])
  463. def test_generate_minion_id_platform_used(self):
  464. '''
  465. Test if platform.node is used for the first occurrence.
  466. The platform.node is most common hostname resolver before anything else.
  467. :return:
  468. '''
  469. with patch('platform.node', MagicMock(return_value='very.long.and.complex.domain.name')), \
  470. patch('socket.gethostname', MagicMock(return_value='hostname')), \
  471. patch('socket.getfqdn', MagicMock(return_value='')), \
  472. patch('socket.getaddrinfo', MagicMock(return_value=[(2, 3, 0, 'hostname', ('127.0.1.1', 0))])), \
  473. patch('salt.utils.files.fopen', mock_open()), \
  474. patch('salt.utils.network.ip_addrs', MagicMock(return_value=['1.2.3.4', '1.2.3.4', '1.2.3.4'])):
  475. self.assertEqual(network.generate_minion_id(), 'very.long.and.complex.domain.name')
  476. def test_generate_minion_id_platform_localhost_filtered(self):
  477. '''
  478. Test if localhost is filtered from the first occurrence.
  479. :return:
  480. '''
  481. with patch('platform.node', MagicMock(return_value='localhost')), \
  482. patch('socket.gethostname', MagicMock(return_value='pick.me')), \
  483. patch('socket.getfqdn', MagicMock(return_value='hostname.domainname.blank')), \
  484. patch('socket.getaddrinfo', MagicMock(return_value=[(2, 3, 0, 'hostname', ('127.0.1.1', 0))])), \
  485. patch('salt.utils.files.fopen', mock_open()), \
  486. patch('salt.utils.network.ip_addrs', MagicMock(return_value=['1.2.3.4', '1.2.3.4', '1.2.3.4'])):
  487. self.assertEqual(network.generate_minion_id(), 'hostname.domainname.blank')
  488. def test_generate_minion_id_platform_localhost_filtered_all(self):
  489. '''
  490. Test if any of the localhost is filtered from everywhere.
  491. :return:
  492. '''
  493. with patch('platform.node', MagicMock(return_value='localhost')), \
  494. patch('socket.gethostname', MagicMock(return_value='ip6-loopback')), \
  495. patch('socket.getfqdn', MagicMock(return_value='ip6-localhost')), \
  496. patch('socket.getaddrinfo', MagicMock(return_value=[(2, 3, 0, 'localhost', ('127.0.1.1', 0))])), \
  497. patch('salt.utils.files.fopen', mock_open()), \
  498. patch('salt.utils.network.ip_addrs', MagicMock(return_value=['127.0.0.1', '::1', 'fe00::0', 'fe02::1', '1.2.3.4'])):
  499. self.assertEqual(network.generate_minion_id(), '1.2.3.4')
  500. def test_generate_minion_id_platform_localhost_only(self):
  501. '''
  502. Test if there is no other choice but localhost.
  503. :return:
  504. '''
  505. with patch('platform.node', MagicMock(return_value='localhost')), \
  506. patch('socket.gethostname', MagicMock(return_value='ip6-loopback')), \
  507. patch('socket.getfqdn', MagicMock(return_value='ip6-localhost')), \
  508. patch('socket.getaddrinfo', MagicMock(return_value=[(2, 3, 0, 'localhost', ('127.0.1.1', 0))])), \
  509. patch('salt.utils.files.fopen', mock_open()), \
  510. patch('salt.utils.network.ip_addrs', MagicMock(return_value=['127.0.0.1', '::1', 'fe00::0', 'fe02::1'])):
  511. self.assertEqual(network.generate_minion_id(), 'localhost')
  512. def test_generate_minion_id_platform_fqdn(self):
  513. '''
  514. Test if fqdn is picked up.
  515. :return:
  516. '''
  517. with patch('platform.node', MagicMock(return_value='localhost')), \
  518. patch('socket.gethostname', MagicMock(return_value='ip6-loopback')), \
  519. patch('socket.getfqdn', MagicMock(return_value='pick.me')), \
  520. patch('socket.getaddrinfo', MagicMock(return_value=[(2, 3, 0, 'localhost', ('127.0.1.1', 0))])), \
  521. patch('salt.utils.files.fopen', mock_open()), \
  522. patch('salt.utils.network.ip_addrs', MagicMock(return_value=['127.0.0.1', '::1', 'fe00::0', 'fe02::1'])):
  523. self.assertEqual(network.generate_minion_id(), 'pick.me')
  524. def test_generate_minion_id_platform_localhost_addrinfo(self):
  525. '''
  526. Test if addinfo is picked up.
  527. :return:
  528. '''
  529. with patch('platform.node', MagicMock(return_value='localhost')), \
  530. patch('socket.gethostname', MagicMock(return_value='ip6-loopback')), \
  531. patch('socket.getfqdn', MagicMock(return_value='ip6-localhost')), \
  532. patch('socket.getaddrinfo', MagicMock(return_value=[(2, 3, 0, 'pick.me', ('127.0.1.1', 0))])), \
  533. patch('salt.utils.files.fopen', mock_open()), \
  534. patch('salt.utils.network.ip_addrs', MagicMock(return_value=['127.0.0.1', '::1', 'fe00::0', 'fe02::1'])):
  535. self.assertEqual(network.generate_minion_id(), 'pick.me')
  536. def test_generate_minion_id_platform_ip_addr_only(self):
  537. '''
  538. Test if IP address is the only what is used as a Minion ID in case no DNS name.
  539. :return:
  540. '''
  541. with patch('platform.node', MagicMock(return_value='localhost')), \
  542. patch('socket.gethostname', MagicMock(return_value='ip6-loopback')), \
  543. patch('socket.getfqdn', MagicMock(return_value='ip6-localhost')), \
  544. patch('socket.getaddrinfo', MagicMock(return_value=[(2, 3, 0, 'localhost', ('127.0.1.1', 0))])), \
  545. patch('salt.utils.files.fopen', mock_open()), \
  546. patch('salt.utils.network.ip_addrs', MagicMock(return_value=['127.0.0.1', '::1', 'fe00::0', 'fe02::1', '1.2.3.4'])):
  547. self.assertEqual(network.generate_minion_id(), '1.2.3.4')
  548. def test_gen_mac(self):
  549. with patch('random.randint', return_value=1) as random_mock:
  550. self.assertEqual(random_mock.return_value, 1)
  551. ret = network.gen_mac('00:16:3E')
  552. expected_mac = '00:16:3E:01:01:01'
  553. self.assertEqual(ret, expected_mac)
  554. def test_mac_str_to_bytes(self):
  555. self.assertRaises(ValueError, network.mac_str_to_bytes, '31337')
  556. self.assertRaises(ValueError, network.mac_str_to_bytes, '0001020304056')
  557. self.assertRaises(ValueError, network.mac_str_to_bytes, '00:01:02:03:04:056')
  558. self.assertRaises(ValueError, network.mac_str_to_bytes, 'a0:b0:c0:d0:e0:fg')
  559. self.assertEqual(b'\x10\x08\x06\x04\x02\x00', network.mac_str_to_bytes('100806040200'))
  560. self.assertEqual(b'\xf8\xe7\xd6\xc5\xb4\xa3', network.mac_str_to_bytes('f8e7d6c5b4a3'))
  561. def test_generate_minion_id_with_long_hostname(self):
  562. '''
  563. Validate the fix for:
  564. https://github.com/saltstack/salt/issues/51160
  565. '''
  566. long_name = 'localhost-abcdefghijklmnopqrstuvwxyz-abcdefghijklmnopqrstuvwxyz'
  567. with patch('socket.gethostname', MagicMock(return_value=long_name)):
  568. # An exception is raised if unicode is passed to socket.getfqdn
  569. minion_id = network.generate_minion_id()
  570. assert minion_id != '', minion_id