jumpserver/apps/assets/migrations/0102_auto_20220711_1413.py

66 lines
2.1 KiB
Python
Raw Normal View History

2022-07-12 02:54:23 +00:00
# Generated by Django 3.2.12 on 2022-07-11 06:13
2022-07-13 08:36:49 +00:00
import time
2022-07-12 02:54:23 +00:00
from django.db import migrations
def migrate_accounts(apps, schema_editor):
auth_book_model = apps.get_model('assets', 'AuthBook')
account_model = apps.get_model('assets', 'Account')
2022-07-13 08:36:49 +00:00
count = 0
bulk_size = 1000
2022-07-14 02:56:09 +00:00
print("\nStart migrate accounts")
2022-07-13 08:36:49 +00:00
while True:
2022-07-14 02:56:09 +00:00
start = time.time()
2022-07-13 08:36:49 +00:00
auth_books = auth_book_model.objects \
2022-07-14 02:56:09 +00:00
.prefetch_related('systemuser') \
.all()[count:count+bulk_size]
count += len(auth_books)
2022-07-13 08:36:49 +00:00
if not auth_books:
break
accounts = []
2022-07-14 02:56:09 +00:00
# auth book 和 account 相同的属性
2022-07-13 08:36:49 +00:00
same_attrs = [
'id', 'comment', 'date_created', 'date_updated',
'created_by', 'asset_id', 'org_id',
]
# 认证的属性,可能是 authbook 的,可能是 systemuser 的
auth_attrs = ['username', 'password', 'private_key', 'public_key']
for auth_book in auth_books:
values = {attr: getattr(auth_book, attr) for attr in same_attrs}
values['protocol'] = 'ssh'
values['version'] = 1
system_user = auth_book.systemuser
if auth_book.systemuser:
values.update({attr: getattr(system_user, attr) for attr in auth_attrs})
values['protocol'] = system_user.protocol
values['created_by'] = str(system_user.id)
2022-07-15 10:03:32 +00:00
values['type'] = system_user.type
2022-07-13 08:36:49 +00:00
auth_book_auth = {attr: getattr(auth_book, attr) for attr in auth_attrs}
auth_book_auth = {attr: value for attr, value in auth_book_auth.items() if value}
values.update(auth_book_auth)
account = account_model(**values)
accounts.append(account)
account_model.objects.bulk_create(accounts, ignore_conflicts=True)
print("Create accounts: {}-{} using: {:.2f}s".format(
2022-07-14 02:56:09 +00:00
count - bulk_size, count, time.time()-start
2022-07-13 08:36:49 +00:00
))
2022-07-12 02:54:23 +00:00
class Migration(migrations.Migration):
dependencies = [
2022-08-04 02:44:11 +00:00
('assets', '0101_auto_20220711_1409'),
2022-07-12 02:54:23 +00:00
]
operations = [
2022-07-13 08:36:49 +00:00
migrations.RunPython(migrate_accounts)
2022-07-12 02:54:23 +00:00
]