Add network definition file

This commit is contained in:
Théophile Bastian 2020-03-09 12:14:48 +01:00
parent 90baaa8d03
commit b06ce7c12b
2 changed files with 75 additions and 0 deletions

64
src/network.py Normal file
View file

@ -0,0 +1,64 @@
""" Network objects """
import settings
import util
from xml_template import XMLTemplate
import uuid
import libvirt
class Network(util.NumberedClass):
class AlreadyExists(Exception):
def __str__(self):
return "This network is already instanciated"
class TooMany(Exception):
def __init__(self, count):
self.count = count
def __str__(self):
return (
"Limit number reached. The current instance #{} does not fit in IPv4"
).format(self.count)
def __init__(self, conn, name=None):
super().__init__()
if self.id > 250:
raise self.TooMany(self.id)
if not name:
name = str(self.id)
self.conn = conn
self.uuid = uuid.uuid4()
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)

11
src/templates/network.xml Normal file
View file

@ -0,0 +1,11 @@
<network>
<name>{name}</name>
<uuid>{uuid}</uuid>
<bridge name='virbr{bridge_id}' stp='on' delay='0'/>
<mac address='{mac}'/>
<domain name='{name}'/>
<ip address='{addrv4}' netmask='{netmaskv4}'>
</ip>
<ip family='ipv6' address='{addrv6}' prefix='{prefixv6}'>
</ip>
</network>