uncloud-mravi/uncloud/hack/mac.py
Nico Schottelius b877ab13b3 add hack code
2020-01-15 10:02:37 +01:00

90 lines
2.6 KiB
Python
Executable file

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# 2012 Nico Schottelius (nico-cinv at schottelius.org)
#
# This file is part of cinv.
#
# cinv is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# cinv is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with cinv. If not, see <http://www.gnu.org/licenses/>.
#
#
import argparse
import logging
import os.path
import os
import re
import json
from uncloud import UncloudException
from uncloud.hack.db import DB
log = logging.getLogger(__name__)
class MAC(object):
def __init__(self, config):
self.config = config
self.db = DB(config, prefix="/mac")
self.prefix = 0x002000000000
@staticmethod
def validate_mac(mac):
if not re.match(r'([0-9A-F]{2}[-:]){5}[0-9A-F]{2}$', mac, re.I):
raise Error("Not a valid mac address: %s" % mac)
def last_used_index(self):
value = self.db.get("last_used_index")
if not value:
self.db.set("last_used_index", "0")
value = self.db.get("last_used_index")
return int(value)
def last_used_mac(self):
return self.int_to_mac(self.prefix + self.last_used_index())
@staticmethod
def int_to_mac(number):
b = number.to_bytes(6, byteorder="big")
return ':'.join(format(s, '02x') for s in b)
def get_next(self, vmuuid=None, as_int=False):
last_number = self.last_used_index()
# FIXME: compare to 48bit minus prefix length to the power of 2
if last_number == int('0xffffff', 16):
raise UncloudException("Exhausted all possible mac addresses - try to free some")
next_number = last_number + 1
next_number_string = "{:012x}".format(next_number)
next_mac_number = self.prefix + next_number
next_mac = self.int_to_mac(next_mac_number)
db_entry = {}
db_entry['vm_uuid'] = vmuuid
db_entry['index'] = next_number
db_entry['mac_address'] = next_mac
# should be one transaction
self.db.increment("last_used_index")
self.db.set("used/{}".format(next_mac),
db_entry, as_json=True)
if as_int:
return next_mac_number
else:
return next_mac