2022-01-10 11:02:18 +00:00
|
|
|
import os
|
|
|
|
import time
|
2022-01-17 07:58:39 +00:00
|
|
|
from collections import defaultdict, OrderedDict
|
2022-01-10 11:02:18 +00:00
|
|
|
|
|
|
|
from django.conf import settings
|
2023-08-01 10:17:02 +00:00
|
|
|
from openpyxl import Workbook
|
2022-01-17 07:58:39 +00:00
|
|
|
from rest_framework import serializers
|
2022-01-10 11:02:18 +00:00
|
|
|
|
2023-01-16 11:02:09 +00:00
|
|
|
from accounts.notifications import AccountBackupExecutionTaskMsg
|
2023-08-01 10:17:02 +00:00
|
|
|
from accounts.serializers import AccountSecretSerializer
|
|
|
|
from assets.const import AllTypes
|
2022-01-10 11:02:18 +00:00
|
|
|
from common.utils.file import encrypt_and_compress_zip_file
|
2023-08-01 10:17:02 +00:00
|
|
|
from common.utils.timezone import local_now_display
|
|
|
|
from users.models import User
|
2022-01-10 11:02:18 +00:00
|
|
|
|
|
|
|
PATH = os.path.join(os.path.dirname(settings.BASE_DIR), 'tmp')
|
|
|
|
|
|
|
|
|
2022-01-17 07:58:39 +00:00
|
|
|
class BaseAccountHandler:
|
|
|
|
@classmethod
|
|
|
|
def unpack_data(cls, serializer_data, data=None):
|
|
|
|
if data is None:
|
|
|
|
data = {}
|
|
|
|
for k, v in serializer_data.items():
|
|
|
|
if isinstance(v, OrderedDict):
|
|
|
|
cls.unpack_data(v, data)
|
|
|
|
else:
|
|
|
|
data[k] = v
|
|
|
|
return data
|
|
|
|
|
|
|
|
@classmethod
|
|
|
|
def get_header_fields(cls, serializer: serializers.Serializer):
|
|
|
|
try:
|
|
|
|
backup_fields = getattr(serializer, 'Meta').fields_backup
|
|
|
|
except AttributeError:
|
|
|
|
backup_fields = serializer.fields.keys()
|
|
|
|
header_fields = {}
|
|
|
|
for field in backup_fields:
|
|
|
|
v = serializer.fields[field]
|
|
|
|
if isinstance(v, serializers.Serializer):
|
|
|
|
_fields = cls.get_header_fields(v)
|
|
|
|
header_fields.update(_fields)
|
|
|
|
else:
|
2022-06-30 09:06:50 +00:00
|
|
|
header_fields[field] = str(v.label)
|
2022-01-17 07:58:39 +00:00
|
|
|
return header_fields
|
|
|
|
|
2022-09-01 08:31:20 +00:00
|
|
|
@classmethod
|
|
|
|
def create_row(cls, data, header_fields):
|
|
|
|
data = cls.unpack_data(data)
|
2022-01-17 07:58:39 +00:00
|
|
|
row_dict = {}
|
|
|
|
for field, header_name in header_fields.items():
|
2022-09-01 08:31:20 +00:00
|
|
|
row_dict[header_name] = str(data.get(field, field))
|
2022-01-17 07:58:39 +00:00
|
|
|
return row_dict
|
|
|
|
|
2022-09-01 08:31:20 +00:00
|
|
|
@classmethod
|
|
|
|
def add_rows(cls, data, header_fields, sheet):
|
|
|
|
data_map = defaultdict(list)
|
|
|
|
for i in data:
|
|
|
|
row = cls.create_row(i, header_fields)
|
|
|
|
if sheet not in data_map:
|
|
|
|
data_map[sheet].append(list(row.keys()))
|
|
|
|
data_map[sheet].append(list(row.values()))
|
|
|
|
return data_map
|
|
|
|
|
2022-01-17 07:58:39 +00:00
|
|
|
|
|
|
|
class AssetAccountHandler(BaseAccountHandler):
|
2022-01-10 11:02:18 +00:00
|
|
|
@staticmethod
|
|
|
|
def get_filename(plan_name):
|
|
|
|
filename = os.path.join(
|
2022-08-29 11:49:45 +00:00
|
|
|
PATH, f'{plan_name}-{local_now_display()}-{time.time()}.xlsx'
|
2022-01-10 11:02:18 +00:00
|
|
|
)
|
|
|
|
return filename
|
|
|
|
|
2023-08-07 07:50:09 +00:00
|
|
|
@staticmethod
|
|
|
|
def handler_secret(data, section):
|
|
|
|
for account_data in data:
|
|
|
|
secret = account_data.get('secret')
|
|
|
|
if not secret:
|
|
|
|
continue
|
|
|
|
length = len(secret)
|
|
|
|
index = length // 2
|
|
|
|
if section == "front":
|
|
|
|
secret = secret[:index] + '*' * (length - index)
|
|
|
|
elif section == "back":
|
|
|
|
secret = '*' * (length - index) + secret[index:]
|
|
|
|
account_data['secret'] = secret
|
|
|
|
|
2022-01-17 07:58:39 +00:00
|
|
|
@classmethod
|
2023-08-07 07:50:09 +00:00
|
|
|
def create_data_map(cls, accounts, section):
|
2022-06-30 09:06:50 +00:00
|
|
|
data_map = defaultdict(list)
|
2022-01-10 11:02:18 +00:00
|
|
|
|
2023-02-17 09:14:53 +00:00
|
|
|
if not accounts.exists():
|
2022-06-30 09:06:50 +00:00
|
|
|
return data_map
|
2022-01-10 11:02:18 +00:00
|
|
|
|
2022-12-12 04:33:45 +00:00
|
|
|
type_dict = {}
|
2022-09-16 09:24:27 +00:00
|
|
|
for i in AllTypes.grouped_choices_to_objs():
|
|
|
|
for j in i['children']:
|
2022-12-12 04:33:45 +00:00
|
|
|
type_dict[j['value']] = j['display_name']
|
2022-09-01 08:31:20 +00:00
|
|
|
|
2023-02-17 09:14:53 +00:00
|
|
|
header_fields = cls.get_header_fields(AccountSecretSerializer(accounts.first()))
|
2022-12-12 04:33:45 +00:00
|
|
|
account_type_map = defaultdict(list)
|
2023-02-17 09:14:53 +00:00
|
|
|
for account in accounts:
|
2022-12-12 04:33:45 +00:00
|
|
|
account_type_map[account.type].append(account)
|
2022-09-01 08:31:20 +00:00
|
|
|
|
|
|
|
data_map = {}
|
2023-02-17 09:14:53 +00:00
|
|
|
for tp, _accounts in account_type_map.items():
|
2022-12-12 04:33:45 +00:00
|
|
|
sheet_name = type_dict.get(tp, tp)
|
2023-02-17 09:14:53 +00:00
|
|
|
data = AccountSecretSerializer(_accounts, many=True).data
|
2023-08-07 07:50:09 +00:00
|
|
|
cls.handler_secret(data, section)
|
2022-09-01 08:31:20 +00:00
|
|
|
data_map.update(cls.add_rows(data, header_fields, sheet_name))
|
2022-01-10 11:02:18 +00:00
|
|
|
|
2023-08-01 10:17:02 +00:00
|
|
|
print('\n\033[33m- 共备份 {} 条账号\033[0m'.format(accounts.count()))
|
2022-06-30 09:06:50 +00:00
|
|
|
return data_map
|
2022-01-10 11:02:18 +00:00
|
|
|
|
|
|
|
|
|
|
|
class AccountBackupHandler:
|
|
|
|
def __init__(self, execution):
|
|
|
|
self.execution = execution
|
|
|
|
self.plan_name = self.execution.plan.name
|
|
|
|
self.is_frozen = False # 任务状态冻结标志
|
|
|
|
|
2023-08-07 07:50:09 +00:00
|
|
|
def create_excel(self, section='complete'):
|
2023-08-01 10:17:02 +00:00
|
|
|
print(
|
2022-01-10 11:02:18 +00:00
|
|
|
'\n'
|
2022-01-17 07:58:39 +00:00
|
|
|
'\033[32m>>> 正在生成资产或应用相关备份信息文件\033[0m'
|
2022-01-10 11:02:18 +00:00
|
|
|
''
|
|
|
|
)
|
|
|
|
# Print task start date
|
|
|
|
time_start = time.time()
|
2022-01-17 07:58:39 +00:00
|
|
|
files = []
|
2023-02-17 09:14:53 +00:00
|
|
|
accounts = self.execution.backup_accounts
|
2023-08-07 07:50:09 +00:00
|
|
|
data_map = AssetAccountHandler.create_data_map(accounts, section)
|
2022-08-29 11:49:45 +00:00
|
|
|
if not data_map:
|
|
|
|
return files
|
|
|
|
|
|
|
|
filename = AssetAccountHandler.get_filename(self.plan_name)
|
|
|
|
|
|
|
|
wb = Workbook(filename)
|
|
|
|
for sheet, data in data_map.items():
|
|
|
|
ws = wb.create_sheet(str(sheet))
|
|
|
|
for row in data:
|
|
|
|
ws.append(row)
|
|
|
|
wb.save(filename)
|
|
|
|
files.append(filename)
|
2022-01-10 11:02:18 +00:00
|
|
|
timedelta = round((time.time() - time_start), 2)
|
2023-08-01 10:17:02 +00:00
|
|
|
print('步骤完成: 用时 {}s'.format(timedelta))
|
2022-01-17 07:58:39 +00:00
|
|
|
return files
|
2022-01-10 11:02:18 +00:00
|
|
|
|
2022-04-20 03:18:50 +00:00
|
|
|
def send_backup_mail(self, files, recipients):
|
2022-01-17 07:58:39 +00:00
|
|
|
if not files:
|
|
|
|
return
|
2022-01-10 11:02:18 +00:00
|
|
|
recipients = User.objects.filter(id__in=list(recipients))
|
2023-08-01 10:17:02 +00:00
|
|
|
print(
|
2022-01-10 11:02:18 +00:00
|
|
|
'\n'
|
|
|
|
'\033[32m>>> 发送备份邮件\033[0m'
|
|
|
|
''
|
|
|
|
)
|
|
|
|
plan_name = self.plan_name
|
|
|
|
for user in recipients:
|
|
|
|
if not user.secret_key:
|
|
|
|
attachment_list = []
|
|
|
|
else:
|
|
|
|
password = user.secret_key.encode('utf8')
|
|
|
|
attachment = os.path.join(PATH, f'{plan_name}-{local_now_display()}-{time.time()}.zip')
|
|
|
|
encrypt_and_compress_zip_file(attachment, password, files)
|
|
|
|
attachment_list = [attachment, ]
|
|
|
|
AccountBackupExecutionTaskMsg(plan_name, user).publish(attachment_list)
|
2023-08-01 10:17:02 +00:00
|
|
|
print('邮件已发送至{}({})'.format(user, user.email))
|
2022-01-10 11:02:18 +00:00
|
|
|
for file in files:
|
|
|
|
os.remove(file)
|
|
|
|
|
|
|
|
def step_perform_task_update(self, is_success, reason):
|
|
|
|
self.execution.reason = reason[:1024]
|
|
|
|
self.execution.is_success = is_success
|
|
|
|
self.execution.save()
|
2023-08-01 10:17:02 +00:00
|
|
|
print('已完成对任务状态的更新')
|
2022-01-10 11:02:18 +00:00
|
|
|
|
2023-08-07 07:50:09 +00:00
|
|
|
@staticmethod
|
|
|
|
def step_finished(is_success):
|
2022-01-10 11:02:18 +00:00
|
|
|
if is_success:
|
2023-08-01 10:17:02 +00:00
|
|
|
print('任务执行成功')
|
2022-01-10 11:02:18 +00:00
|
|
|
else:
|
2023-08-01 10:17:02 +00:00
|
|
|
print('任务执行失败')
|
2022-01-10 11:02:18 +00:00
|
|
|
|
|
|
|
def _run(self):
|
|
|
|
is_success = False
|
|
|
|
error = '-'
|
|
|
|
try:
|
2023-08-07 07:50:09 +00:00
|
|
|
recipients_part_one = self.execution.snapshot.get('recipients_part_one', [])
|
|
|
|
recipients_part_two = self.execution.snapshot.get('recipients_part_two', [])
|
|
|
|
if not recipients_part_one and not recipients_part_two:
|
2023-08-01 10:17:02 +00:00
|
|
|
print(
|
2022-04-20 03:18:50 +00:00
|
|
|
'\n'
|
|
|
|
'\033[32m>>> 该备份任务未分配收件人\033[0m'
|
|
|
|
''
|
|
|
|
)
|
2023-08-07 07:50:09 +00:00
|
|
|
if recipients_part_one and recipients_part_two:
|
|
|
|
files = self.create_excel(section='front')
|
|
|
|
self.send_backup_mail(files, recipients_part_one)
|
|
|
|
|
|
|
|
files = self.create_excel(section='back')
|
|
|
|
self.send_backup_mail(files, recipients_part_two)
|
2022-04-20 03:18:50 +00:00
|
|
|
else:
|
2023-08-07 07:50:09 +00:00
|
|
|
recipients = recipients_part_one or recipients_part_two
|
2022-04-20 03:18:50 +00:00
|
|
|
files = self.create_excel()
|
|
|
|
self.send_backup_mail(files, recipients)
|
2022-01-10 11:02:18 +00:00
|
|
|
except Exception as e:
|
|
|
|
self.is_frozen = True
|
2023-08-01 10:17:02 +00:00
|
|
|
print('任务执行被异常中断')
|
|
|
|
print('下面打印发生异常的 Traceback 信息 : ')
|
|
|
|
print(e)
|
2022-01-10 11:02:18 +00:00
|
|
|
error = str(e)
|
|
|
|
else:
|
|
|
|
is_success = True
|
|
|
|
finally:
|
|
|
|
reason = error
|
|
|
|
self.step_perform_task_update(is_success, reason)
|
|
|
|
self.step_finished(is_success)
|
|
|
|
|
|
|
|
def run(self):
|
2023-08-01 10:17:02 +00:00
|
|
|
print('任务开始: {}'.format(local_now_display()))
|
2022-01-10 11:02:18 +00:00
|
|
|
time_start = time.time()
|
|
|
|
try:
|
|
|
|
self._run()
|
|
|
|
except Exception as e:
|
2023-08-01 10:17:02 +00:00
|
|
|
print('任务运行出现异常')
|
|
|
|
print('下面显示异常 Traceback 信息: ')
|
|
|
|
print(e)
|
2022-01-10 11:02:18 +00:00
|
|
|
finally:
|
2023-08-01 10:17:02 +00:00
|
|
|
print('\n任务结束: {}'.format(local_now_display()))
|
2022-01-10 11:02:18 +00:00
|
|
|
timedelta = round((time.time() - time_start), 2)
|
2023-08-01 10:17:02 +00:00
|
|
|
print('用时: {}'.format(timedelta))
|