Beispiel #1
0
class OneProjectSerializer(ProjectSerializer, _InventoryOperations):
    repository = vst_fields.VSTCharField(default='MANUAL')
    owner = UserSerializer(read_only=True)
    notes = vst_fields.TextareaField(required=False, allow_blank=True)
    readme_content = vst_fields.HtmlField(read_only=True, label='Information')
    execute_view_data = vst_serializers.DataSerializer(read_only=True,
                                                       allow_null=True)

    class Meta:
        model = models.Project
        fields = (
            'id',
            'name',
            'repository',
            'status',
            'revision',
            'branch',
            'owner',
            'notes',
            'readme_content',
            'execute_view_data',
        )

    @transaction.atomic()
    def sync(self) -> Response:
        self.instance.start_repo_task("sync")
        serializer = ActionResponseSerializer(data=dict(
            detail="Sync with {}.".format(self.instance.repository)))
        serializer.is_valid(True)
        return Response(serializer.data, status.HTTP_200_OK)

    def _get_ansible_serializer(self, kind: str) -> serializers.Serializer:
        view = self.context['view']
        exec_method = getattr(view, 'execute_{}'.format(kind), None)
        if exec_method is None:  # nocv
            raise Exception('Unknown kind')
        serializer_class = exec_method.kwargs['serializer_class']
        serializer = serializer_class(context=self.context)
        serializer.project = self.instance
        return serializer

    def _execution(self, kind: str, data: Dict, user: User,
                   **kwargs) -> Response:
        template = data.pop("template", None)
        inventory = data.get("inventory", None)
        msg = "Started in the inventory {}.".format(
            inventory
            if inventory else 'specified in the project configuration.')
        if template is not None:
            init_type = "template"
            obj_id = template
            msg = 'Start template [id={}].'.format(template)
        else:
            init_type = "project"
            obj_id = self.instance.id
            serializer = self._get_ansible_serializer(kind.lower())
            data = {
                k: v
                for k, v in serializer.to_internal_value(data).items()
                if k in data.keys() or v
            }
        target = data.pop(kind)
        try:
            target = str(target)
        except UnicodeEncodeError:  # nocv
            target = target.encode('utf-8')
        history_id = self.instance.execute(kind,
                                           str(target),
                                           initiator=obj_id,
                                           initiator_type=init_type,
                                           executor=user,
                                           **data)
        rdata = ExecuteResponseSerializer(
            data=dict(detail=msg, history_id=history_id, executor=user.id))
        rdata.is_valid(raise_exception=True)
        return Response(rdata.data, status.HTTP_201_CREATED)

    def execute_playbook(self, request) -> Response:
        return self._execution("playbook", dict(request.data), request.user)

    def execute_module(self, request) -> Response:
        return self._execution("module", dict(request.data), request.user)
Beispiel #2
0
class OneProjectSerializer(ProjectSerializer, _InventoryOperations):
    repository = vst_fields.VSTCharField(default='MANUAL')
    owner = UserSerializer(read_only=True)
    notes = vst_fields.TextareaField(required=False, allow_blank=True)
    readme_content = vst_fields.HtmlField(read_only=True, label='Information')
    execute_view_data = vst_serializers.DataSerializer(read_only=True,
                                                       allow_null=True)

    class Meta:
        model = models.Project
        fields = (
            'id',
            'name',
            'repository',
            'status',
            'revision',
            'branch',
            'owner',
            'notes',
            'readme_content',
            'execute_view_data',
        )

    @transaction.atomic()
    def sync(self):
        self.instance.start_repo_task("sync")
        serializer = ActionResponseSerializer(data=dict(
            detail="Sync with {}.".format(self.instance.repository)))
        serializer.is_valid(True)
        return Response(serializer.data, status.HTTP_200_OK)

    def _get_execution_inventory(self, template, inventory, user):
        if template or inventory is None:
            return inventory
        try:
            inventory = Inventory.objects.get(id=int(inventory))
            if not inventory.acl_handler.viewable_by(user):  # nocv
                raise PermissionDenied(
                    "You don't have permission to inventory.")
        except ValueError:
            pass
        return inventory

    def _execution(self, kind, data, user, **kwargs):
        template = kwargs.pop("template", None)
        inventory = self._get_execution_inventory(template,
                                                  data.pop("inventory", None),
                                                  user)
        msg = "Started in the inventory {}.".format(
            inventory
            if inventory else 'specified in the project configuration.')
        if template is not None:
            init_type = "template"
            obj_id = template
            data['template_option'] = kwargs.get('template_option', None)
            msg = 'Start template [id={}].'.format(template)
        else:
            init_type = "project"
            obj_id = self.instance.id
            if kind.lower() == 'module':
                serializer = AnsibleModuleSerializer()
            elif kind.lower() == 'playbook':
                serializer = AnsiblePlaybookSerializer()
            else:  # nocv
                raise Exception('Unknown kind')
            data = {
                k: v
                for k, v in serializer.to_internal_value(data).items()
                if k in data.keys() or v
            }
        history_id = self.instance.execute(kind,
                                           str(data.pop(kind)),
                                           inventory,
                                           initiator=obj_id,
                                           initiator_type=init_type,
                                           executor=user,
                                           **data)
        rdata = ExecuteResponseSerializer(
            data=dict(detail=msg, history_id=history_id, executor=user.id))
        rdata.is_valid(raise_exception=True)
        return Response(rdata.data, status.HTTP_201_CREATED)

    def execute_playbook(self, request):
        return self._execution("playbook", dict(request.data), request.user)

    def execute_module(self, request):
        return self._execution("module", dict(request.data), request.user)