jumpserver/apps/assets/migrations/0093_auto_20220403_1627.py

61 lines
1.7 KiB
Python
Raw Normal View History

2022-04-02 10:35:46 +00:00
# Generated by Django 3.1.14 on 2022-04-02 08:27
from django.utils import timezone
2022-04-12 11:24:59 +00:00
from django.db import migrations, models
2022-04-02 10:35:46 +00:00
2022-09-14 12:55:14 +00:00
def migrate_to_host(apps, schema_editor):
asset_model = apps.get_model("assets", "Asset")
host_model = apps.get_model("assets", 'Host')
db_alias = schema_editor.connection.alias
2022-04-02 10:35:46 +00:00
2022-09-16 03:45:50 +00:00
count = 0
2022-04-02 10:35:46 +00:00
batch_size = 1000
while True:
2022-09-16 03:45:50 +00:00
assets = asset_model.objects.using(db_alias).all()[count:count+batch_size]
2022-09-14 12:55:14 +00:00
if not assets:
2022-04-02 10:35:46 +00:00
break
2022-09-16 03:45:50 +00:00
count += len(assets)
2022-09-14 12:55:14 +00:00
hosts = [host_model(asset_ptr=asset) for asset in assets]
host_model.objects.using(db_alias).bulk_create(hosts, ignore_conflicts=True)
2022-04-02 10:35:46 +00:00
2022-09-14 12:55:14 +00:00
def migrate_hardware_info(apps, *args):
2022-08-04 02:44:11 +00:00
asset_model = apps.get_model("assets", "Asset")
2022-09-14 12:55:14 +00:00
count = 0
2022-08-04 02:44:11 +00:00
batch_size = 1000
2022-09-14 12:55:14 +00:00
hardware_fields = [
'vendor', 'model', 'sn', 'cpu_model', 'cpu_count', 'cpu_cores',
'cpu_vcpus', 'memory', 'disk_total', 'disk_info', 'os', 'os_arch',
'os_version', 'hostname_raw', 'number'
]
2022-08-04 02:44:11 +00:00
while True:
2022-09-16 03:45:50 +00:00
assets = asset_model.objects.all()[count:count+batch_size]
2022-08-04 02:44:11 +00:00
if not assets:
break
2022-09-16 03:45:50 +00:00
count += len(assets)
2022-08-04 02:44:11 +00:00
2022-09-14 12:55:14 +00:00
updated = []
for asset in assets:
2022-09-16 03:45:50 +00:00
info = {field: getattr(asset, field) for field in hardware_fields if getattr(asset, field)}
2022-09-14 12:55:14 +00:00
if not info:
continue
asset.info = info
updated.append(asset)
asset_model.objects.bulk_update(updated, ['info'])
2022-08-04 02:44:11 +00:00
2022-04-02 10:35:46 +00:00
class Migration(migrations.Migration):
dependencies = [
2022-08-04 02:44:11 +00:00
('assets', '0092_add_host'),
2022-04-02 10:35:46 +00:00
]
operations = [
2022-09-14 12:55:14 +00:00
migrations.RunPython(migrate_hardware_info),
2022-08-04 02:44:11 +00:00
migrations.RunPython(migrate_to_host),
2022-04-02 10:35:46 +00:00
]