2023-10-25 02:03:33 +00:00
|
|
|
import hashlib
|
2023-02-20 11:12:57 +00:00
|
|
|
import json
|
2022-10-09 12:54:11 +00:00
|
|
|
import os
|
2022-10-28 10:28:41 +00:00
|
|
|
import shutil
|
|
|
|
from socket import gethostname
|
2022-10-09 12:54:11 +00:00
|
|
|
|
2023-04-13 11:02:04 +00:00
|
|
|
import yaml
|
2022-10-09 12:54:11 +00:00
|
|
|
from django.conf import settings
|
|
|
|
from django.utils import timezone
|
2022-10-12 10:08:57 +00:00
|
|
|
from django.utils.translation import gettext as _
|
2023-08-15 10:50:48 +00:00
|
|
|
from sshtunnel import SSHTunnelForwarder
|
2022-10-09 12:54:11 +00:00
|
|
|
|
2022-10-12 10:08:57 +00:00
|
|
|
from assets.automations.methods import platform_automation_methods
|
2023-03-08 10:52:00 +00:00
|
|
|
from common.utils import get_logger, lazyproperty, is_openssh_format_key, ssh_pubkey_gen
|
2022-10-12 10:08:57 +00:00
|
|
|
from ops.ansible import JMSInventory, PlaybookRunner, DefaultCallback
|
|
|
|
|
|
|
|
logger = get_logger(__name__)
|
|
|
|
|
|
|
|
|
|
|
|
class PlaybookCallback(DefaultCallback):
|
|
|
|
def playbook_on_stats(self, event_data, **kwargs):
|
|
|
|
super().playbook_on_stats(event_data, **kwargs)
|
2022-10-09 12:54:11 +00:00
|
|
|
|
|
|
|
|
|
|
|
class BasePlaybookManager:
|
2022-10-12 10:08:57 +00:00
|
|
|
bulk_size = 100
|
2022-10-09 12:54:11 +00:00
|
|
|
ansible_account_policy = 'privileged_first'
|
2023-02-10 06:07:20 +00:00
|
|
|
ansible_account_prefer = 'root,Administrator'
|
2022-10-09 12:54:11 +00:00
|
|
|
|
|
|
|
def __init__(self, execution):
|
|
|
|
self.execution = execution
|
2022-10-12 10:08:57 +00:00
|
|
|
self.method_id_meta_mapper = {
|
|
|
|
method['id']: method
|
2023-01-16 11:02:09 +00:00
|
|
|
for method in self.platform_automation_methods
|
2022-10-12 10:08:57 +00:00
|
|
|
if method['method'] == self.__class__.method_type()
|
|
|
|
}
|
|
|
|
# 根据执行方式就行分组, 不同资产的改密、推送等操作可能会使用不同的执行方式
|
|
|
|
# 然后根据执行方式分组, 再根据 bulk_size 分组, 生成不同的 playbook
|
|
|
|
self.playbooks = []
|
2023-02-21 12:27:44 +00:00
|
|
|
self.gateway_servers = dict()
|
2023-04-13 11:02:04 +00:00
|
|
|
params = self.execution.snapshot.get('params')
|
|
|
|
self.params = params or {}
|
|
|
|
|
|
|
|
def get_params(self, automation, method_type):
|
|
|
|
method_attr = '{}_method'.format(method_type)
|
|
|
|
method_params = '{}_params'.format(method_type)
|
|
|
|
method_id = getattr(automation, method_attr)
|
|
|
|
automation_params = getattr(automation, method_params)
|
|
|
|
serializer = self.method_id_meta_mapper[method_id]['params_serializer']
|
|
|
|
|
|
|
|
if serializer is None:
|
|
|
|
return {}
|
|
|
|
|
2023-04-14 10:31:09 +00:00
|
|
|
data = self.params.get(method_id)
|
|
|
|
if not data:
|
2023-07-05 06:28:26 +00:00
|
|
|
data = automation_params.get(method_id, {})
|
2023-04-13 11:02:04 +00:00
|
|
|
params = serializer(data).data
|
|
|
|
return {
|
|
|
|
field_name: automation_params.get(field_name, '')
|
|
|
|
if not params[field_name] else params[field_name]
|
|
|
|
for field_name in params
|
|
|
|
}
|
2022-10-12 10:08:57 +00:00
|
|
|
|
2023-01-16 11:02:09 +00:00
|
|
|
@property
|
|
|
|
def platform_automation_methods(self):
|
|
|
|
return platform_automation_methods
|
|
|
|
|
2022-10-12 10:08:57 +00:00
|
|
|
@classmethod
|
|
|
|
def method_type(cls):
|
|
|
|
raise NotImplementedError
|
2022-10-09 12:54:11 +00:00
|
|
|
|
2022-10-13 12:28:18 +00:00
|
|
|
def get_assets_group_by_platform(self):
|
2023-01-16 11:02:09 +00:00
|
|
|
return self.execution.all_assets_group_by_platform()
|
2022-10-13 12:28:18 +00:00
|
|
|
|
2023-02-22 07:13:51 +00:00
|
|
|
def prepare_runtime_dir(self):
|
2022-10-09 12:54:11 +00:00
|
|
|
ansible_dir = settings.ANSIBLE_DIR
|
2023-01-16 11:02:09 +00:00
|
|
|
task_name = self.execution.snapshot['name']
|
|
|
|
dir_name = '{}_{}'.format(task_name.replace(' ', '_'), self.execution.id)
|
2022-10-09 12:54:11 +00:00
|
|
|
path = os.path.join(
|
2022-10-21 10:19:09 +00:00
|
|
|
ansible_dir, 'automations', self.execution.snapshot['type'],
|
2022-10-13 12:28:18 +00:00
|
|
|
dir_name, timezone.now().strftime('%Y%m%d_%H%M%S')
|
2022-10-09 12:54:11 +00:00
|
|
|
)
|
2022-10-13 12:28:18 +00:00
|
|
|
if not os.path.exists(path):
|
|
|
|
os.makedirs(path, exist_ok=True, mode=0o755)
|
2023-02-22 07:13:51 +00:00
|
|
|
return path
|
|
|
|
|
|
|
|
@lazyproperty
|
|
|
|
def runtime_dir(self):
|
|
|
|
path = self.prepare_runtime_dir()
|
2023-02-21 05:00:04 +00:00
|
|
|
if settings.DEBUG_DEV:
|
2023-02-22 07:13:51 +00:00
|
|
|
msg = 'Ansible runtime dir: {}'.format(path)
|
|
|
|
print(msg)
|
2022-10-09 12:54:11 +00:00
|
|
|
return path
|
|
|
|
|
2023-01-29 08:25:16 +00:00
|
|
|
@staticmethod
|
|
|
|
def write_cert_to_file(filename, content):
|
|
|
|
with open(filename, 'w') as f:
|
|
|
|
f.write(content)
|
|
|
|
return filename
|
|
|
|
|
|
|
|
def convert_cert_to_file(self, host, path_dir):
|
|
|
|
if not path_dir:
|
|
|
|
return host
|
|
|
|
|
2023-02-02 02:32:48 +00:00
|
|
|
specific = host.get('jms_asset', {}).get('secret_info', {})
|
2023-01-29 08:25:16 +00:00
|
|
|
cert_fields = ('ca_cert', 'client_key', 'client_cert')
|
|
|
|
filtered = list(filter(lambda x: specific.get(x), cert_fields))
|
|
|
|
if not filtered:
|
|
|
|
return host
|
|
|
|
|
|
|
|
cert_dir = os.path.join(path_dir, 'certs')
|
|
|
|
if not os.path.exists(cert_dir):
|
|
|
|
os.makedirs(cert_dir, 0o700, True)
|
|
|
|
|
|
|
|
for f in filtered:
|
|
|
|
result = self.write_cert_to_file(
|
|
|
|
os.path.join(cert_dir, f), specific.get(f)
|
|
|
|
)
|
2023-02-02 02:32:48 +00:00
|
|
|
host['jms_asset']['secret_info'][f] = result
|
2023-01-29 08:25:16 +00:00
|
|
|
return host
|
|
|
|
|
2022-10-12 10:08:57 +00:00
|
|
|
def host_callback(self, host, automation=None, **kwargs):
|
2023-04-13 11:02:04 +00:00
|
|
|
method_type = self.__class__.method_type()
|
|
|
|
enabled_attr = '{}_enabled'.format(method_type)
|
|
|
|
method_attr = '{}_method'.format(method_type)
|
2022-10-12 10:08:57 +00:00
|
|
|
|
|
|
|
method_enabled = automation and \
|
2022-11-04 11:18:15 +00:00
|
|
|
getattr(automation, enabled_attr) and \
|
|
|
|
getattr(automation, method_attr) and \
|
|
|
|
getattr(automation, method_attr) in self.method_id_meta_mapper
|
2022-10-12 10:08:57 +00:00
|
|
|
|
|
|
|
if not method_enabled:
|
2022-10-13 12:28:18 +00:00
|
|
|
host['error'] = _('{} disabled'.format(self.__class__.method_type()))
|
2022-10-12 10:08:57 +00:00
|
|
|
return host
|
2023-01-29 08:25:16 +00:00
|
|
|
|
|
|
|
host = self.convert_cert_to_file(host, kwargs.get('path_dir'))
|
2023-04-13 11:02:04 +00:00
|
|
|
host['params'] = self.get_params(automation, method_type)
|
2022-10-12 10:08:57 +00:00
|
|
|
return host
|
2022-10-09 12:54:11 +00:00
|
|
|
|
2022-10-28 10:28:41 +00:00
|
|
|
@staticmethod
|
|
|
|
def generate_public_key(private_key):
|
|
|
|
return ssh_pubkey_gen(private_key=private_key, hostname=gethostname())
|
|
|
|
|
|
|
|
@staticmethod
|
|
|
|
def generate_private_key_path(secret, path_dir):
|
2023-10-25 02:03:33 +00:00
|
|
|
key_name = '.' + hashlib.md5(secret.encode('utf-8')).hexdigest()
|
2022-10-28 10:28:41 +00:00
|
|
|
key_path = os.path.join(path_dir, key_name)
|
2022-11-01 03:52:51 +00:00
|
|
|
|
2022-10-28 10:28:41 +00:00
|
|
|
if not os.path.exists(key_path):
|
2023-03-02 10:50:09 +00:00
|
|
|
# https://github.com/ansible/ansible-runner/issues/544
|
|
|
|
# ssh requires OpenSSH format keys to have a full ending newline.
|
|
|
|
# It does not require this for old-style PEM keys.
|
|
|
|
with open(key_path, 'w') as f:
|
|
|
|
f.write(secret)
|
2023-03-02 11:05:27 +00:00
|
|
|
if is_openssh_format_key(secret.encode('utf-8')):
|
2023-03-02 10:50:09 +00:00
|
|
|
f.write("\n")
|
2022-10-28 10:28:41 +00:00
|
|
|
os.chmod(key_path, 0o400)
|
|
|
|
return key_path
|
|
|
|
|
2022-10-13 12:28:18 +00:00
|
|
|
def generate_inventory(self, platformed_assets, inventory_path):
|
2022-10-09 12:54:11 +00:00
|
|
|
inventory = JMSInventory(
|
2022-10-13 12:28:18 +00:00
|
|
|
assets=platformed_assets,
|
2023-02-10 06:07:20 +00:00
|
|
|
account_prefer=self.ansible_account_prefer,
|
2022-10-09 12:54:11 +00:00
|
|
|
account_policy=self.ansible_account_policy,
|
2022-10-28 10:28:41 +00:00
|
|
|
host_callback=self.host_callback,
|
2023-04-26 10:50:30 +00:00
|
|
|
task_type=self.__class__.method_type(),
|
2022-10-09 12:54:11 +00:00
|
|
|
)
|
2022-10-13 12:28:18 +00:00
|
|
|
inventory.write_to_file(inventory_path)
|
|
|
|
|
|
|
|
def generate_playbook(self, platformed_assets, platform, sub_playbook_dir):
|
|
|
|
method_id = getattr(platform.automation, '{}_method'.format(self.__class__.method_type()))
|
|
|
|
method = self.method_id_meta_mapper.get(method_id)
|
|
|
|
if not method:
|
|
|
|
logger.error("Method not found: {}".format(method_id))
|
2023-09-20 03:12:15 +00:00
|
|
|
return
|
2022-10-13 12:28:18 +00:00
|
|
|
method_playbook_dir_path = method['dir']
|
|
|
|
sub_playbook_path = os.path.join(sub_playbook_dir, 'project', 'main.yml')
|
|
|
|
shutil.copytree(method_playbook_dir_path, os.path.dirname(sub_playbook_path))
|
|
|
|
|
|
|
|
with open(sub_playbook_path, 'r') as f:
|
|
|
|
plays = yaml.safe_load(f)
|
|
|
|
for play in plays:
|
|
|
|
play['hosts'] = 'all'
|
|
|
|
|
|
|
|
with open(sub_playbook_path, 'w') as f:
|
|
|
|
yaml.safe_dump(plays, f)
|
|
|
|
return sub_playbook_path
|
2022-10-12 10:08:57 +00:00
|
|
|
|
|
|
|
def get_runners(self):
|
2023-02-20 12:14:06 +00:00
|
|
|
assets_group_by_platform = self.get_assets_group_by_platform()
|
2023-02-22 03:18:42 +00:00
|
|
|
if settings.DEBUG_DEV:
|
2023-02-22 07:13:51 +00:00
|
|
|
msg = 'Assets group by platform: {}'.format(dict(assets_group_by_platform))
|
|
|
|
print(msg)
|
2022-10-12 10:08:57 +00:00
|
|
|
runners = []
|
2023-02-20 12:14:06 +00:00
|
|
|
for platform, assets in assets_group_by_platform.items():
|
2023-09-20 03:12:15 +00:00
|
|
|
if not assets:
|
|
|
|
continue
|
|
|
|
if not platform.automation or not platform.automation.ansible_enabled:
|
|
|
|
print(_(" - Platform {} ansible disabled").format(platform.name))
|
|
|
|
continue
|
2022-10-28 10:28:41 +00:00
|
|
|
assets_bulked = [assets[i:i + self.bulk_size] for i in range(0, len(assets), self.bulk_size)]
|
2022-10-13 12:28:18 +00:00
|
|
|
|
|
|
|
for i, _assets in enumerate(assets_bulked, start=1):
|
|
|
|
sub_dir = '{}_{}'.format(platform.name, i)
|
|
|
|
playbook_dir = os.path.join(self.runtime_dir, sub_dir)
|
|
|
|
inventory_path = os.path.join(self.runtime_dir, sub_dir, 'hosts.json')
|
|
|
|
self.generate_inventory(_assets, inventory_path)
|
|
|
|
playbook_path = self.generate_playbook(_assets, platform, playbook_dir)
|
2023-09-20 03:12:15 +00:00
|
|
|
if not playbook_path:
|
|
|
|
continue
|
2022-10-13 12:28:18 +00:00
|
|
|
|
|
|
|
runer = PlaybookRunner(
|
|
|
|
inventory_path,
|
|
|
|
playbook_path,
|
|
|
|
self.runtime_dir,
|
|
|
|
callback=PlaybookCallback(),
|
|
|
|
)
|
2023-02-21 07:33:15 +00:00
|
|
|
|
|
|
|
with open(inventory_path, 'r') as f:
|
|
|
|
inventory_data = json.load(f)
|
|
|
|
if not inventory_data['all'].get('hosts'):
|
|
|
|
continue
|
|
|
|
|
2022-10-13 12:28:18 +00:00
|
|
|
runners.append(runer)
|
2022-10-12 10:08:57 +00:00
|
|
|
return runners
|
|
|
|
|
2022-10-14 08:33:24 +00:00
|
|
|
def on_host_success(self, host, result):
|
|
|
|
pass
|
|
|
|
|
|
|
|
def on_host_error(self, host, error, result):
|
2023-05-16 09:20:15 +00:00
|
|
|
if settings.DEBUG_DEV:
|
|
|
|
print('host error: {} -> {}'.format(host, error))
|
2022-10-14 08:33:24 +00:00
|
|
|
|
2022-10-13 12:28:18 +00:00
|
|
|
def on_runner_success(self, runner, cb):
|
2022-10-14 08:33:24 +00:00
|
|
|
summary = cb.summary
|
|
|
|
for state, hosts in summary.items():
|
|
|
|
for host in hosts:
|
2022-10-17 03:22:21 +00:00
|
|
|
result = cb.host_results.get(host)
|
2022-10-14 08:33:24 +00:00
|
|
|
if state == 'ok':
|
|
|
|
self.on_host_success(host, result)
|
2022-11-04 11:18:15 +00:00
|
|
|
elif state == 'skipped':
|
2023-02-22 07:13:51 +00:00
|
|
|
pass
|
2022-10-14 08:33:24 +00:00
|
|
|
else:
|
|
|
|
error = hosts.get(host)
|
|
|
|
self.on_host_error(host, error, result)
|
2022-10-09 12:54:11 +00:00
|
|
|
|
2022-10-12 10:08:57 +00:00
|
|
|
def on_runner_failed(self, runner, e):
|
|
|
|
print("Runner failed: {} {}".format(e, self))
|
2022-10-09 12:54:11 +00:00
|
|
|
|
2023-02-21 12:27:44 +00:00
|
|
|
@staticmethod
|
|
|
|
def file_to_json(path):
|
|
|
|
with open(path, 'r') as f:
|
|
|
|
d = json.load(f)
|
|
|
|
return d
|
2022-10-09 12:54:11 +00:00
|
|
|
|
2023-02-22 07:13:51 +00:00
|
|
|
@staticmethod
|
|
|
|
def json_dumps(data):
|
|
|
|
return json.dumps(data, indent=4, sort_keys=True)
|
|
|
|
|
2023-02-20 11:12:57 +00:00
|
|
|
@staticmethod
|
2023-02-21 12:27:44 +00:00
|
|
|
def json_to_file(path, data):
|
|
|
|
with open(path, 'w') as f:
|
2023-02-22 07:13:51 +00:00
|
|
|
json.dump(data, f, indent=4, sort_keys=True)
|
2023-02-21 12:27:44 +00:00
|
|
|
|
|
|
|
def local_gateway_prepare(self, runner):
|
|
|
|
info = self.file_to_json(runner.inventory)
|
2023-02-23 10:15:31 +00:00
|
|
|
servers, not_valid = [], []
|
2023-02-21 12:27:44 +00:00
|
|
|
for k, host in info['all']['hosts'].items():
|
2023-08-01 07:38:08 +00:00
|
|
|
jms_asset, jms_gateway = host.get('jms_asset'), host.get('gateway')
|
2023-02-21 12:27:44 +00:00
|
|
|
if not jms_gateway:
|
|
|
|
continue
|
2023-02-23 10:15:31 +00:00
|
|
|
try:
|
2023-08-15 10:50:48 +00:00
|
|
|
server = SSHTunnelForwarder(
|
|
|
|
(jms_gateway['address'], jms_gateway['port']),
|
|
|
|
ssh_username=jms_gateway['username'],
|
|
|
|
ssh_password=jms_gateway['secret'],
|
|
|
|
ssh_pkey=jms_gateway['private_key_path'],
|
|
|
|
remote_bind_address=(jms_asset['address'], jms_asset['port'])
|
|
|
|
)
|
2023-02-23 10:15:31 +00:00
|
|
|
server.start()
|
2023-08-15 10:50:48 +00:00
|
|
|
except Exception as e:
|
2023-02-23 10:15:31 +00:00
|
|
|
err_msg = 'Gateway is not active: %s' % jms_asset.get('name', '')
|
2023-08-15 10:50:48 +00:00
|
|
|
print(f'\033[31m {err_msg} 原因: {e} \033[0m\n')
|
2023-02-23 10:15:31 +00:00
|
|
|
not_valid.append(k)
|
|
|
|
else:
|
2023-04-03 01:57:40 +00:00
|
|
|
host['ansible_host'] = jms_asset['address'] = '127.0.0.1'
|
|
|
|
host['ansible_port'] = jms_asset['port'] = server.local_bind_port
|
2023-02-23 10:15:31 +00:00
|
|
|
servers.append(server)
|
|
|
|
|
|
|
|
# 网域不可连接的,就不继续执行此资源的后续任务了
|
|
|
|
for a in set(not_valid):
|
|
|
|
info['all']['hosts'].pop(a)
|
2023-02-21 12:27:44 +00:00
|
|
|
self.json_to_file(runner.inventory, info)
|
|
|
|
self.gateway_servers[runner.id] = servers
|
|
|
|
|
|
|
|
def local_gateway_clean(self, runner):
|
|
|
|
servers = self.gateway_servers.get(runner.id, [])
|
2023-02-22 07:13:51 +00:00
|
|
|
for s in servers:
|
|
|
|
try:
|
2023-02-21 12:27:44 +00:00
|
|
|
s.stop()
|
2023-02-22 07:13:51 +00:00
|
|
|
except Exception:
|
|
|
|
pass
|
2023-02-21 12:27:44 +00:00
|
|
|
|
|
|
|
def before_runner_start(self, runner):
|
|
|
|
self.local_gateway_prepare(runner)
|
|
|
|
|
|
|
|
def after_runner_end(self, runner):
|
|
|
|
self.local_gateway_clean(runner)
|
|
|
|
|
2023-02-22 07:13:51 +00:00
|
|
|
def delete_runtime_dir(self):
|
2023-02-20 11:12:57 +00:00
|
|
|
if settings.DEBUG_DEV:
|
|
|
|
return
|
2023-02-22 07:13:51 +00:00
|
|
|
shutil.rmtree(self.runtime_dir)
|
2023-02-20 11:12:57 +00:00
|
|
|
|
2022-10-28 10:28:41 +00:00
|
|
|
def run(self, *args, **kwargs):
|
2023-09-20 03:12:15 +00:00
|
|
|
print(">>> 任务准备阶段\n")
|
2022-10-12 10:08:57 +00:00
|
|
|
runners = self.get_runners()
|
|
|
|
if len(runners) > 1:
|
2023-02-22 07:13:51 +00:00
|
|
|
print("### 分次执行任务, 总共 {}\n".format(len(runners)))
|
2023-02-10 06:37:55 +00:00
|
|
|
elif len(runners) == 1:
|
2022-10-12 10:08:57 +00:00
|
|
|
print(">>> 开始执行任务\n")
|
2023-02-10 06:37:55 +00:00
|
|
|
else:
|
|
|
|
print("### 没有需要执行的任务\n")
|
2022-10-12 10:08:57 +00:00
|
|
|
|
2022-11-07 08:10:26 +00:00
|
|
|
self.execution.date_start = timezone.now()
|
2022-10-12 10:08:57 +00:00
|
|
|
for i, runner in enumerate(runners, start=1):
|
|
|
|
if len(runners) > 1:
|
|
|
|
print(">>> 开始执行第 {} 批任务".format(i))
|
2022-10-13 09:47:29 +00:00
|
|
|
self.before_runner_start(runner)
|
2022-10-12 10:08:57 +00:00
|
|
|
try:
|
|
|
|
cb = runner.run(**kwargs)
|
2022-10-13 12:28:18 +00:00
|
|
|
self.on_runner_success(runner, cb)
|
2022-10-12 10:08:57 +00:00
|
|
|
except Exception as e:
|
|
|
|
self.on_runner_failed(runner, e)
|
2023-02-21 07:33:15 +00:00
|
|
|
finally:
|
2023-02-21 12:32:44 +00:00
|
|
|
self.after_runner_end(runner)
|
2023-02-21 07:33:15 +00:00
|
|
|
print('\n')
|
2022-11-09 07:42:21 +00:00
|
|
|
self.execution.status = 'success'
|
2022-11-07 08:10:26 +00:00
|
|
|
self.execution.date_finished = timezone.now()
|
|
|
|
self.execution.save()
|
2023-02-22 07:13:51 +00:00
|
|
|
self.delete_runtime_dir()
|