hack mac: be a proper python class

This commit is contained in:
Nico Schottelius 2020-01-23 21:15:26 +01:00
parent 8e839aeb44
commit c881c7ce4d

View file

@ -38,7 +38,8 @@ class MAC(object):
self.config = config self.config = config
self.db = DB(config, prefix="/mac") self.db = DB(config, prefix="/mac")
self.prefix = 0x002000000000 self.prefix = 0x420000000000
self._number = 0 # Not set by default
@staticmethod @staticmethod
def validate_mac(mac): def validate_mac(mac):
@ -56,35 +57,40 @@ class MAC(object):
def last_used_mac(self): def last_used_mac(self):
return self.int_to_mac(self.prefix + self.last_used_index()) return self.int_to_mac(self.prefix + self.last_used_index())
@staticmethod def to_colon_format(self):
def int_to_mac(number): b = self._number.to_bytes(6, byteorder="big")
b = number.to_bytes(6, byteorder="big")
return ':'.join(format(s, '02x') for s in b) return ':'.join(format(s, '02x') for s in b)
def get_next(self, vmuuid=None, as_int=False): def to_str_format(self):
b = self._number.to_bytes(6, byteorder="big")
return ''.join(format(s, '02x') for s in b)
def create(self):
last_number = self.last_used_index() last_number = self.last_used_index()
# FIXME: compare to 48bit minus prefix length to the power of 2 if last_number == int('0xffffffff', 16):
if last_number == int('0xffffff', 16):
raise UncloudException("Exhausted all possible mac addresses - try to free some") raise UncloudException("Exhausted all possible mac addresses - try to free some")
next_number = last_number + 1 next_number = last_number + 1
next_number_string = "{:012x}".format(next_number) self._number = self.prefix + next_number
next_mac_number = self.prefix + next_number #next_number_string = "{:012x}".format(next_number)
next_mac = self.int_to_mac(next_mac_number) #next_mac = self.int_to_mac(next_mac_number)
# db_entry = {}
db_entry = {} # db_entry['vm_uuid'] = vmuuid
db_entry['vm_uuid'] = vmuuid # db_entry['index'] = next_number
db_entry['index'] = next_number # db_entry['mac_address'] = next_mac
db_entry['mac_address'] = next_mac
# should be one transaction # should be one transaction
self.db.increment("last_used_index") # self.db.increment("last_used_index")
self.db.set("used/{}".format(next_mac), # self.db.set("used/{}".format(next_mac),
db_entry, as_json=True) # db_entry, as_json=True)
if as_int: def __int__(self):
return next_mac_number return self._number
else:
return next_mac def __repr__(self):
return self.to_str_format()
def __str__(self):
return self.to_colon_format()