1
0
mirror of https://github.com/netbox-community/netbox.git synced 2024-05-10 07:54:54 +00:00

70 lines
2.3 KiB
Python
Raw Normal View History

2020-06-22 13:10:56 -04:00
import sys
from django.db import migrations
def replicate_interfaces(apps, schema_editor):
ContentType = apps.get_model('contenttypes', 'ContentType')
TaggedItem = apps.get_model('extras', 'TaggedItem')
2020-06-22 13:10:56 -04:00
Interface = apps.get_model('dcim', 'Interface')
IPAddress = apps.get_model('ipam', 'IPAddress')
2020-06-23 13:16:21 -04:00
VMInterface = apps.get_model('virtualization', 'VMInterface')
2020-06-22 13:10:56 -04:00
interface_ct = ContentType.objects.get_for_model(Interface)
2020-06-23 13:16:21 -04:00
vminterface_ct = ContentType.objects.get_for_model(VMInterface)
2020-06-22 13:10:56 -04:00
# Replicate dcim.Interface instances assigned to VirtualMachines
original_interfaces = Interface.objects.filter(virtual_machine__isnull=False)
for interface in original_interfaces:
vminterface = VMInterface(
2020-06-22 13:10:56 -04:00
virtual_machine=interface.virtual_machine,
name=interface.name,
enabled=interface.enabled,
mac_address=interface.mac_address,
mtu=interface.mtu,
mode=interface.mode,
description=interface.description,
untagged_vlan=interface.untagged_vlan,
)
vminterface.save()
2020-06-22 13:10:56 -04:00
# Copy tagged VLANs
vminterface.tagged_vlans.set(interface.tagged_vlans.all())
2020-06-22 13:10:56 -04:00
# Reassign tags to the new instance
TaggedItem.objects.filter(
content_type=interface_ct, object_id=interface.pk
).update(
content_type=vminterface_ct, object_id=vminterface.pk
2020-06-22 13:10:56 -04:00
)
# Update any assigned IPAddresses
IPAddress.objects.filter(assigned_object_id=interface.pk).update(
2020-06-23 13:16:21 -04:00
assigned_object_type=vminterface_ct,
assigned_object_id=vminterface.pk
2020-06-22 13:10:56 -04:00
)
replicated_count = VMInterface.objects.count()
if 'test' not in sys.argv:
print(f"\n Replicated {replicated_count} interfaces ", end='', flush=True)
# Verify that all interfaces have been replicated
assert replicated_count == original_interfaces.count(), "Replicated interfaces count does not match original count!"
# Delete all interfaces not assigned to a Device
Interface.objects.filter(device__isnull=True).delete()
2020-06-22 13:10:56 -04:00
class Migration(migrations.Migration):
dependencies = [
('ipam', '0037_ipaddress_assignment'),
2020-06-23 13:16:21 -04:00
('virtualization', '0015_vminterface'),
2020-06-22 13:10:56 -04:00
]
operations = [
migrations.RunPython(
code=replicate_interfaces
),
]