views.py 2.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. # Copyright: (c) OpenSpug Organization. https://github.com/openspug/spug
  2. # Copyright: (c) <spug.dev@gmail.com>
  3. # Released under the AGPL-3.0 License.
  4. from django.views.generic import View
  5. from django_redis import get_redis_connection
  6. from django.conf import settings
  7. from libs import json_response, JsonParser, Argument, human_datetime
  8. from apps.exec.models import ExecTemplate
  9. from apps.host.models import Host
  10. from apps.account.utils import has_host_perm
  11. import uuid
  12. import json
  13. class TemplateView(View):
  14. def get(self, request):
  15. templates = ExecTemplate.objects.all()
  16. types = [x['type'] for x in templates.order_by('type').values('type').distinct()]
  17. return json_response({'types': types, 'templates': [x.to_dict() for x in templates]})
  18. def post(self, request):
  19. form, error = JsonParser(
  20. Argument('id', type=int, required=False),
  21. Argument('name', help='请输入模版名称'),
  22. Argument('type', help='请选择模版类型'),
  23. Argument('body', help='请输入模版内容'),
  24. Argument('desc', required=False)
  25. ).parse(request.body)
  26. if error is None:
  27. if form.id:
  28. form.updated_at = human_datetime()
  29. form.updated_by = request.user
  30. ExecTemplate.objects.filter(pk=form.pop('id')).update(**form)
  31. else:
  32. form.created_by = request.user
  33. ExecTemplate.objects.create(**form)
  34. return json_response(error=error)
  35. def delete(self, request):
  36. form, error = JsonParser(
  37. Argument('id', type=int, help='请指定操作对象')
  38. ).parse(request.GET)
  39. if error is None:
  40. ExecTemplate.objects.filter(pk=form.id).delete()
  41. return json_response(error=error)
  42. def do_task(request):
  43. form, error = JsonParser(
  44. Argument('host_ids', type=list, filter=lambda x: len(x), help='请选择执行主机'),
  45. Argument('command', help='请输入执行命令内容')
  46. ).parse(request.body)
  47. if error is None:
  48. if not has_host_perm(request.user, form.host_ids):
  49. return json_response(error='无权访问主机,请联系管理员')
  50. token, rds = uuid.uuid4().hex, get_redis_connection()
  51. for host in Host.objects.filter(id__in=form.host_ids):
  52. data = dict(
  53. key=host.id,
  54. name=host.name,
  55. token=token,
  56. hostname=host.hostname,
  57. port=host.port,
  58. username=host.username,
  59. command=form.command,
  60. pkey=host.private_key,
  61. )
  62. rds.rpush(settings.EXEC_WORKER_KEY, json.dumps(data))
  63. return json_response(token)
  64. return json_response(error=error)