""" Network objects """ from . import settings from . import util from .xml_template import XMLTemplate class Network(util.LibvirtObject): class AlreadyExists(Exception): def __str__(self): return "This network is already instanciated" def __init__(self, conn, name=None): super().__init__(conn) if not name: name = str(self.id) self.name = settings.PREFIX + "_link_" + 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 def create(self): if self.lxc_network: raise self.AlreadyExists() xml = XMLTemplate("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) 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()