perf: 修改 ansible

This commit is contained in:
ibuler
2022-09-29 20:44:45 +08:00
committed by 老广
parent cd847c483a
commit 41589c5305
29 changed files with 450 additions and 283 deletions

View File

@@ -4,4 +4,3 @@
from .adhoc import *
from .celery import *
from .command import *
from .automation import *

View File

@@ -1,5 +0,0 @@
from .change_auth import *
from .collect import *
from .push import *
from .verify import *
from .common import *

View File

@@ -1,2 +0,0 @@
# -*- coding: utf-8 -*-
#

View File

@@ -1,71 +0,0 @@
from django.db import models
from django.utils.translation import ugettext_lazy as _
from ops.const import SSHKeyStrategy, PasswordStrategy, StrategyChoice
from ops.utils import generate_random_password
from common.db.fields import (
EncryptCharField, EncryptTextField, JsonDictCharField
)
from .common import AutomationStrategy
class ChangeAuthStrategy(AutomationStrategy):
is_password = models.BooleanField(default=True)
password_strategy = models.CharField(
max_length=128, blank=True, null=True, choices=PasswordStrategy.choices,
verbose_name=_('Password strategy')
)
password_rules = JsonDictCharField(
max_length=2048, blank=True, null=True, verbose_name=_('Password rules')
)
password = EncryptCharField(
max_length=256, blank=True, null=True, verbose_name=_('Password')
)
is_ssh_key = models.BooleanField(default=False)
ssh_key_strategy = models.CharField(
max_length=128, blank=True, null=True, choices=SSHKeyStrategy.choices,
verbose_name=_('SSH Key strategy')
)
private_key = EncryptTextField(
max_length=4096, blank=True, null=True, verbose_name=_('SSH private key')
)
public_key = EncryptTextField(
max_length=4096, blank=True, null=True, verbose_name=_('SSH public key')
)
recipients = models.ManyToManyField(
'users.User', related_name='recipients_change_auth_strategy', blank=True,
verbose_name=_("Recipient")
)
class Meta:
verbose_name = _("Change auth strategy")
def gen_execute_password(self):
if self.password_strategy == PasswordStrategy.custom:
return self.password
elif self.password_strategy == PasswordStrategy.random_one:
return generate_random_password(**self.password_rules)
else:
return None
def to_attr_json(self):
attr_json = super().to_attr_json()
attr_json.update({
'type': StrategyChoice.change_auth,
'password': self.gen_execute_password(),
'is_password': self.is_password,
'password_rules': self.password_rules,
'password_strategy': self.password_strategy,
'is_ssh_key': self.is_ssh_key,
'public_key': self.public_key,
'private_key': self.private_key,
'ssh_key_strategy': self.ssh_key_strategy,
'recipients': {
str(recipient.id): (str(recipient), bool(recipient.secret_key))
for recipient in self.recipients.all()
}
})
return attr_json

View File

@@ -1,16 +0,0 @@
from django.utils.translation import ugettext_lazy as _
from ops.const import StrategyChoice
from .common import AutomationStrategy
class CollectStrategy(AutomationStrategy):
class Meta:
verbose_name = _("Collect strategy")
def to_attr_json(self):
attr_json = super().to_attr_json()
attr_json.update({
'type': StrategyChoice.collect
})
return attr_json

View File

@@ -1,111 +0,0 @@
import uuid
from celery import current_task
from django.db import models
from django.utils.translation import ugettext_lazy as _
from common.const.choices import Trigger
from common.mixins.models import CommonModelMixin
from common.db.fields import EncryptJsonDictTextField
from orgs.mixins.models import OrgModelMixin
from ops.mixin import PeriodTaskModelMixin
from ops.tasks import execute_automation_strategy
from ops.task_handlers import ExecutionManager
class AutomationStrategy(CommonModelMixin, PeriodTaskModelMixin, OrgModelMixin):
id = models.UUIDField(default=uuid.uuid4, primary_key=True)
accounts = models.JSONField(default=list, verbose_name=_("Accounts"))
nodes = models.ManyToManyField(
'assets.Node', related_name='automation_strategy', blank=True, verbose_name=_("Nodes")
)
assets = models.ManyToManyField(
'assets.Asset', related_name='automation_strategy', blank=True, verbose_name=_("Assets")
)
comment = models.TextField(blank=True, verbose_name=_('Comment'))
def __str__(self):
return self.name + '@' + str(self.created_by)
def get_register_task(self):
name = "automation_strategy_period_{}".format(str(self.id)[:8])
task = execute_automation_strategy.name
args = (str(self.id), Trigger.timing)
kwargs = {}
return name, task, args, kwargs
def to_attr_json(self):
return {
'name': self.name,
'accounts': self.accounts,
'assets': list(self.assets.all().values_list('id', flat=True)),
'nodes': list(self.assets.all().values_list('id', flat=True)),
}
def execute(self, trigger):
try:
eid = current_task.request.id
except AttributeError:
eid = str(uuid.uuid4())
execution = AutomationStrategyExecution.objects.create(
id=eid, strategy=self, snapshot=self.to_attr_json(), trigger=trigger
)
return execution.start()
class Meta:
unique_together = [('org_id', 'name')]
verbose_name = _("Automation plan")
class AutomationStrategyExecution(OrgModelMixin):
id = models.UUIDField(default=uuid.uuid4, primary_key=True)
date_created = models.DateTimeField(auto_now_add=True)
timedelta = models.FloatField(default=0.0, verbose_name=_('Time'), null=True)
date_start = models.DateTimeField(auto_now_add=True, verbose_name=_('Date start'))
snapshot = EncryptJsonDictTextField(
default=dict, blank=True, null=True, verbose_name=_('Automation snapshot')
)
strategy = models.ForeignKey(
'AutomationStrategy', related_name='execution', on_delete=models.CASCADE,
verbose_name=_('Automation strategy')
)
trigger = models.CharField(
max_length=128, default=Trigger.manual, choices=Trigger.choices, verbose_name=_('Trigger mode')
)
class Meta:
verbose_name = _('Automation strategy execution')
@property
def manager_type(self):
return self.snapshot['type']
def start(self):
manager = ExecutionManager(execution=self)
return manager.run()
class AutomationStrategyTask(OrgModelMixin):
id = models.UUIDField(default=uuid.uuid4, primary_key=True)
asset = models.ForeignKey(
'assets.Asset', on_delete=models.CASCADE, verbose_name=_('Asset')
)
account = models.ForeignKey(
'assets.Account', on_delete=models.CASCADE, verbose_name=_('Account')
)
is_success = models.BooleanField(default=False, verbose_name=_('Is success'))
timedelta = models.FloatField(default=0.0, null=True, verbose_name=_('Time'))
date_start = models.DateTimeField(auto_now_add=True, verbose_name=_('Date start'))
reason = models.CharField(max_length=1024, blank=True, null=True, verbose_name=_('Reason'))
execution = models.ForeignKey(
'AutomationStrategyExecution', related_name='task', on_delete=models.CASCADE,
verbose_name=_('Automation strategy execution')
)
class Meta:
verbose_name = _('Automation strategy task')
@property
def handler_type(self):
return self.execution.snapshot['type']

View File

@@ -1,16 +0,0 @@
from django.utils.translation import ugettext_lazy as _
from ops.const import StrategyChoice
from .common import AutomationStrategy
class PushStrategy(AutomationStrategy):
class Meta:
verbose_name = _("Push strategy")
def to_attr_json(self):
attr_json = super().to_attr_json()
attr_json.update({
'type': StrategyChoice.push
})
return attr_json

View File

@@ -1,16 +0,0 @@
from django.utils.translation import ugettext_lazy as _
from ops.const import StrategyChoice
from .common import AutomationStrategy
class VerifyStrategy(AutomationStrategy):
class Meta:
verbose_name = _("Verify strategy")
def to_attr_json(self):
attr_json = super().to_attr_json()
attr_json.update({
'type': StrategyChoice.verify
})
return attr_json

View File

@@ -9,32 +9,16 @@ from django.db import models
class CeleryTask(models.Model):
WAITING = "waiting"
RUNNING = "running"
FINISHED = "finished"
LOG_DIR = os.path.join(settings.PROJECT_DIR, 'data', 'celery')
STATUS_CHOICES = (
(WAITING, WAITING),
(RUNNING, RUNNING),
(FINISHED, FINISHED),
)
id = models.UUIDField(primary_key=True, default=uuid.uuid4)
name = models.CharField(max_length=1024)
status = models.CharField(max_length=128, choices=STATUS_CHOICES, db_index=True)
log_path = models.CharField(max_length=256, blank=True, null=True)
args = models.JSONField(verbose_name=_("Args"))
kwargs = models.JSONField(verbose_name=_("Kwargs"))
state = models.CharField(max_length=16, verbose_name=_("State"))
is_finished = models.BooleanField(default=False, verbose_name=_("Finished"))
date_published = models.DateTimeField(auto_now_add=True)
date_start = models.DateTimeField(null=True)
date_finished = models.DateTimeField(null=True)
def __str__(self):
return "{}: {}".format(self.name, self.id)
def is_finished(self):
return self.status == self.FINISHED
@property
def full_log_path(self):
if not self.log_path:
return None
return os.path.join(self.LOG_DIR, self.log_path)

View File

@@ -0,0 +1,16 @@
from django.db import models
from django.utils.translation import gettext_lazy as _
from orgs.mixins.models import JMSOrgBaseModel
from ..mixin import PeriodTaskModelMixin
class PlaybookTask(PeriodTaskModelMixin, JMSOrgBaseModel):
assets = models.ManyToManyField('assets.Asset', verbose_name=_("Assets"))
account = models.CharField(max_length=128, default='root', verbose_name=_('Account'))
playbook = models.FilePathField(max_length=1024, verbose_name=_("Playbook"))
owner = models.CharField(max_length=1024, verbose_name=_("Owner"))
comment = models.TextField(blank=True, verbose_name=_("Comment"))
def get_register_task(self):
pass