+def rename_netdev(old_name, new_name):
+ log("Changing the name of %s to %s" % (old_name, new_name))
+ run_command(['/sbin/ifconfig', old_name, 'down'])
+ if not run_command(['/sbin/ip', 'link', 'set', old_name,
+ 'name', new_name]):
+ raise Error("Could not rename %s to %s" % (old_name, new_name))
+
+# Check whether 'pif' exists and has the correct MAC.
+# If not, try to find a device with the correct MAC and rename it.
+# 'already_renamed' is used to avoid infinite recursion.
+def remap_pif(pif, already_renamed=[]):
+ pifrec = db.get_pif_record(pif)
+ device = pifrec['device']
+ mac = pifrec['MAC']
+
+ # Is there a network device named 'device' at all?
+ device_exists = interface_exists(device)
+ if device_exists:
+ # Yes. Does it have MAC 'mac'?
+ found_mac = get_netdev_mac(device)
+ if found_mac and mac.lower() == found_mac.lower():
+ # Yes, everything checks out the way we want. Nothing to do.
+ return
+ else:
+ log("No network device %s" % device)
+
+ # What device has MAC 'mac'?
+ cur_device = get_netdev_by_mac(mac)
+ if not cur_device:
+ log("No network device has MAC %s" % mac)
+ return
+
+ # First rename 'device', if it exists, to get it out of the way
+ # for 'cur_device' to replace it.
+ if device_exists:
+ rename_netdev(device, "dev%d" % random.getrandbits(24))
+
+ # Rename 'cur_device' to 'device'.
+ rename_netdev(cur_device, device)
+