2023-02-21 05:00:04 +00:00
|
|
|
from rest_framework.generics import CreateAPIView
|
|
|
|
from rest_framework.response import Response
|
|
|
|
|
|
|
|
from accounts import serializers
|
|
|
|
from accounts.tasks import verify_accounts_connectivity_task, push_accounts_to_assets_task
|
2023-02-21 14:57:31 +00:00
|
|
|
from assets.exceptions import NotSupportedTemporarilyError
|
2023-02-21 05:00:04 +00:00
|
|
|
|
|
|
|
__all__ = [
|
|
|
|
'AccountsTaskCreateAPI',
|
|
|
|
]
|
|
|
|
|
|
|
|
|
|
|
|
class AccountsTaskCreateAPI(CreateAPIView):
|
|
|
|
serializer_class = serializers.AccountTaskSerializer
|
|
|
|
|
|
|
|
def check_permissions(self, request):
|
2023-02-21 05:47:47 +00:00
|
|
|
act = request.data.get('action')
|
|
|
|
if act == 'push':
|
|
|
|
code = 'accounts.push_account'
|
|
|
|
else:
|
|
|
|
code = 'accounts.verify_account'
|
|
|
|
return request.user.has_perm(code)
|
2023-02-21 05:00:04 +00:00
|
|
|
|
|
|
|
def perform_create(self, serializer):
|
|
|
|
data = serializer.validated_data
|
|
|
|
accounts = data.get('accounts', [])
|
2023-02-22 12:31:20 +00:00
|
|
|
account_ids = [str(a.id) for a in accounts]
|
2023-02-21 05:00:04 +00:00
|
|
|
|
|
|
|
if data['action'] == 'push':
|
|
|
|
task = push_accounts_to_assets_task.delay(account_ids)
|
|
|
|
else:
|
2023-02-21 14:57:31 +00:00
|
|
|
account = accounts[0]
|
|
|
|
asset = account.asset
|
|
|
|
if not asset.auto_info['ansible_enabled'] or \
|
|
|
|
not asset.auto_info['ping_enabled']:
|
|
|
|
raise NotSupportedTemporarilyError()
|
2023-02-21 05:00:04 +00:00
|
|
|
task = verify_accounts_connectivity_task.delay(account_ids)
|
|
|
|
|
|
|
|
data = getattr(serializer, '_data', {})
|
|
|
|
data["task"] = task.id
|
|
|
|
setattr(serializer, '_data', data)
|
|
|
|
return task
|
|
|
|
|
|
|
|
def get_exception_handler(self):
|
|
|
|
def handler(e, context):
|
|
|
|
return Response({"error": str(e)}, status=400)
|
|
|
|
|
|
|
|
return handler
|