2019-12-22 07:26:48 +00:00
|
|
|
import subprocess as sp
|
|
|
|
import random
|
|
|
|
import logging
|
|
|
|
import socket
|
|
|
|
from contextlib import closing
|
|
|
|
|
|
|
|
logger = logging.getLogger(__name__)
|
|
|
|
|
|
|
|
|
|
|
|
def random_bytes(num=6):
|
|
|
|
return [random.randrange(256) for _ in range(num)]
|
|
|
|
|
|
|
|
|
2019-12-30 09:35:07 +00:00
|
|
|
def generate_mac(
|
|
|
|
uaa=False, multicast=False, oui=None, separator=":", byte_fmt="%02x"
|
|
|
|
):
|
2019-12-22 07:26:48 +00:00
|
|
|
mac = random_bytes()
|
|
|
|
if oui:
|
|
|
|
if type(oui) == str:
|
|
|
|
oui = [int(chunk) for chunk in oui.split(separator)]
|
|
|
|
mac = oui + random_bytes(num=6 - len(oui))
|
|
|
|
else:
|
|
|
|
if multicast:
|
|
|
|
mac[0] |= 1 # set bit 0
|
|
|
|
else:
|
|
|
|
mac[0] &= ~1 # clear bit 0
|
|
|
|
if uaa:
|
|
|
|
mac[0] &= ~(1 << 1) # clear bit 1
|
|
|
|
else:
|
|
|
|
mac[0] |= 1 << 1 # set bit 1
|
|
|
|
return separator.join(byte_fmt % b for b in mac)
|
|
|
|
|
|
|
|
|
|
|
|
def create_dev(script, _id, dev, ip=None):
|
2019-12-30 09:35:07 +00:00
|
|
|
command = [
|
|
|
|
"sudo",
|
|
|
|
"-p",
|
|
|
|
"Enter password to create network devices for vm: ",
|
|
|
|
script,
|
|
|
|
str(_id),
|
|
|
|
dev,
|
|
|
|
]
|
2019-12-22 07:26:48 +00:00
|
|
|
if ip:
|
|
|
|
command.append(ip)
|
|
|
|
try:
|
|
|
|
output = sp.check_output(command, stderr=sp.PIPE)
|
2019-12-29 18:14:39 +00:00
|
|
|
except Exception:
|
2019-12-30 09:35:07 +00:00
|
|
|
logger.exception("Creation of interface %s failed.", dev)
|
2019-12-22 07:26:48 +00:00
|
|
|
return None
|
|
|
|
else:
|
2019-12-30 09:35:07 +00:00
|
|
|
return output.decode("utf-8").strip()
|
2019-12-22 07:26:48 +00:00
|
|
|
|
|
|
|
|
|
|
|
def delete_network_interface(iface):
|
|
|
|
try:
|
2019-12-29 18:14:39 +00:00
|
|
|
sp.check_output(
|
|
|
|
[
|
2019-12-30 09:35:07 +00:00
|
|
|
"sudo",
|
|
|
|
"-p",
|
|
|
|
"Enter password to remove {} network device: ".format(
|
|
|
|
iface
|
|
|
|
),
|
|
|
|
"ip",
|
|
|
|
"link",
|
|
|
|
"del",
|
|
|
|
iface,
|
|
|
|
],
|
|
|
|
stderr=sp.PIPE,
|
2019-12-29 18:14:39 +00:00
|
|
|
)
|
2019-12-22 07:26:48 +00:00
|
|
|
except Exception:
|
2019-12-30 09:35:07 +00:00
|
|
|
logger.exception("Interface %s Deletion failed", iface)
|
2019-12-22 07:26:48 +00:00
|
|
|
|
|
|
|
|
|
|
|
def find_free_port():
|
2019-12-30 09:35:07 +00:00
|
|
|
with closing(
|
|
|
|
socket.socket(socket.AF_INET, socket.SOCK_STREAM)
|
|
|
|
) as s:
|
2019-12-22 07:26:48 +00:00
|
|
|
try:
|
2019-12-30 09:35:07 +00:00
|
|
|
s.bind(("", 0))
|
2019-12-22 07:26:48 +00:00
|
|
|
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
|
|
|
|
except Exception:
|
|
|
|
return None
|
|
|
|
else:
|
|
|
|
return s.getsockname()[1]
|