Improve cms_net to more reliably wake up minions on other subnets

This commit is contained in:
Adam Goldsmith 2022-05-09 16:37:00 -04:00
parent 895f6736d9
commit 36f349941c

View File

@ -5,21 +5,26 @@ Network tools to run from the Master, specific to the Claremont MakerSpace
import logging
import socket
import netifaces
import salt.utils.network
log = logging.getLogger(__name__)
def wol(mac, bcast="255.255.255.255", destport=9):
"Like network.wol, but sends on each interface"
dest = salt.utils.network.mac_str_to_bytes(mac)
for iface in netifaces.interfaces():
if iface == 'lo':
continue
with socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as sock:
sock.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
sock.setsockopt(socket.SOL_SOCKET, socket.SO_BINDTODEVICE, iface.encode('ascii'))
sock.sendto(b"\xff" * 6 + dest * 16, (bcast, int(destport)))
return True
def wolmatch(tgt, destport=9):
'''
Send a "Magic Packet" to wake up Minions that are matched in the
grains cache, automatically determining the destination broadcast address
CLI Example:
.. code-block:: bash
salt-run network.wolmatch minion_id
'''
'Like network.wolmatch'
ret = []
minions = __salt__['cache.grains'](tgt, 'compound')
for name, minion in minions.items():
@ -27,16 +32,11 @@ def wolmatch(tgt, destport=9):
continue
# NOTE: FIVE, NINE, and TEN all should have eth addr as well, why is there only one printed?
for iface, mac in minion['hwaddr_interfaces'].items():
if iface == 'lo':
if iface == 'lo' or mac == ':::::':
continue
mac = mac.strip()
#print(name, iface, mac, minion['ip_interfaces'])
if 'ip4_interfaces' in minion and iface in minion['ip_interfaces']:
ip_addrs = minion['ip4_interfaces'][iface]
for ip_addr in ip_addrs:
[subnet, _, _] = ip_addr.rpartition('.')
bcast = subnet + '.255'
__salt__['network.wol'](mac, bcast, destport)
log.info('Waking up %s', mac)
ret.append(f"{name}: {ip_addrs} {mac}")
wol(mac, destport=destport)
log.info('Waking up %s', mac)
ret.append(f"{name}: {mac}")
return ret