lxc-network/lxc_net/network.py

56 lines
1.4 KiB
Python
Raw Normal View History

2020-03-09 12:14:48 +01:00
""" Network objects """
from . import settings
from . import util
from .xml_template import XMLTemplate
2020-03-09 12:14:48 +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):
super().__init__(conn)
2020-03-09 12:14:48 +01:00
if not name:
name = str(self.id)
self.name = settings.PREFIX + "_link_" + name
2020-03-09 12:14:48 +01:00
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(
2020-03-09 12:14:48 +01:00
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()