2020-03-09 12:14:48 +01:00
|
|
|
""" Network objects """
|
|
|
|
|
2020-03-09 12:58:57 +01:00
|
|
|
from . import settings
|
|
|
|
from . import util
|
|
|
|
from .xml_template import XMLTemplate
|
2020-03-09 12:14:48 +01:00
|
|
|
|
|
|
|
import libvirt
|
|
|
|
|
|
|
|
|
2020-03-09 13:00:43 +01:00
|
|
|
class Network(util.LibvirtObject):
|
2020-03-09 12:14:48 +01:00
|
|
|
class AlreadyExists(Exception):
|
|
|
|
def __str__(self):
|
|
|
|
return "This network is already instanciated"
|
|
|
|
|
|
|
|
def __init__(self, conn, name=None):
|
2020-03-09 13:00:43 +01:00
|
|
|
super().__init__(conn)
|
2020-03-09 12:14:48 +01:00
|
|
|
|
|
|
|
if not name:
|
|
|
|
name = str(self.id)
|
|
|
|
|
|
|
|
self.name = settings.PREFIX + "_" + name
|
|
|
|
self.bridge_id = settings.NETWORK_ID * 0xFF + self.id
|
|
|
|
self.bridge_mac = util.MACAddress(self.id, None)
|
|
|
|
self.ipv4 = util.Addrv4(self.id, None)
|
|
|
|
self.ipv6 = util.Addrv6(self.id, None)
|
|
|
|
self.lxc_network = None
|
|
|
|
|
|
|
|
try:
|
|
|
|
if self.conn.networkLookupByName(self.name):
|
|
|
|
raise self.AlreadyExists()
|
|
|
|
except libvirt.libvirtError:
|
|
|
|
pass
|
|
|
|
|
|
|
|
def create(self):
|
|
|
|
if self.lxc_network:
|
|
|
|
raise self.AlreadyExists()
|
|
|
|
|
|
|
|
xml = XMLTemplate("templates/network.xml").inst(
|
|
|
|
name=self.name,
|
|
|
|
uuid=self.uuid,
|
|
|
|
bridge_id=self.bridge_id,
|
|
|
|
mac=self.bridge_mac,
|
|
|
|
addrv4=self.ipv4,
|
|
|
|
netmaskv4=self.ipv4.netmask,
|
|
|
|
addrv6=self.ipv6,
|
|
|
|
prefixv6=self.ipv6.prefix,
|
|
|
|
)
|
|
|
|
|
|
|
|
self.lxc_network = self.conn.networkCreateXML(xml)
|
2020-03-09 12:24:37 +01:00
|
|
|
|
|
|
|
def cleanup(self):
|
|
|
|
if self.lxc_network:
|
|
|
|
self.lxc_network.destroy()
|
|
|
|
|
|
|
|
def __enter__(self):
|
|
|
|
self.create()
|
|
|
|
return self
|
|
|
|
|
|
|
|
def __exit__(self, exc_type, exc_val, exc_tb):
|
|
|
|
self.cleanup()
|
|
|
|
|
|
|
|
def __del__(self):
|
|
|
|
self.cleanup()
|