コード例 #1
0
ファイル: add.py プロジェクト: MingZhai/orthos2
    def post(self, request, fqdn, *args, **kwargs):
        """Add annotation to machine."""
        try:
            result = get_machine(fqdn,
                                 redirect_to='api:annotation_add',
                                 data=request.GET)
            if isinstance(result, Serializer):
                return result.as_json
            elif isinstance(result, HttpResponseRedirect):
                return result
            machine = result
        except Exception as e:
            return ErrorMessage(str(e)).as_json

        data = json.loads(request.body.decode('utf-8'))['form']
        form = AnnotationAPIForm(data, machine=machine)

        if form.is_valid():
            try:
                cleaned_data = form.cleaned_data
                annotation = Annotation(machine_id=machine.pk,
                                        reporter=request.user,
                                        text=cleaned_data['text'])
                annotation.save()
            except Exception as e:
                logger.exception(e)
                return ErrorMessage("Something went wrong!").as_json

            return Message('Ok.').as_json

        return ErrorMessage("\n{}".format(
            format_cli_form_errors(form))).as_json
コード例 #2
0
ファイル: add.py プロジェクト: MingZhai/orthos2
    def post(self, request, *args, **kwargs):
        """Add remotepowerdevice."""
        if not request.user.is_superuser:
            return ErrorMessage(
                "Only superusers are allowed to perform this action!").as_json

        data = json.loads(request.body.decode('utf-8'))['form']
        form = RemotePowerDeviceAPIForm(data)

        if form.is_valid():

            cleaned_data = form.cleaned_data
            new_device = RemotePowerDevice(username=cleaned_data['username'],
                                           password=cleaned_data['password'],
                                           mac=cleaned_data['mac'],
                                           fqdn=cleaned_data['fqdn'])

            try:
                new_device.save()
            except Exception as e:
                logger.exception(e)
                return ErrorMessage("Something went wrong!").as_json

            return Message('Ok.').as_json

        return ErrorMessage("\n{}".format(
            format_cli_form_errors(form))).as_json
コード例 #3
0
ファイル: add.py プロジェクト: MingZhai/orthos2
    def post(self, request, *args, **kwargs):
        """Add machine."""
        if not request.user.is_superuser:
            return ErrorMessage(
                "Only superusers are allowed to perform this action!").as_json

        data = json.loads(request.body.decode('utf-8'))['form']
        form = MachineAPIForm(data)

        if form.is_valid():

            cleaned_data = form.cleaned_data
            mac_address = cleaned_data['mac_address']
            del cleaned_data['mac_address']
            hypervisor = None
            if cleaned_data['hypervisor_fqdn']:
                hypervisor = Machine.objects.get(
                    fqdn=cleaned_data['hypervisor_fqdn'])
            del cleaned_data['hypervisor_fqdn']
            new_machine = Machine(**cleaned_data)
            new_machine.hypervisor = hypervisor
            new_machine.mac_address = mac_address
            try:
                new_machine.save()
            except Exception as e:
                logger.exception(e)
                return ErrorMessage("Something went wrong!").as_json

            return Message('Ok.').as_json

        return ErrorMessage("\n{}".format(
            format_cli_form_errors(form))).as_json
コード例 #4
0
ファイル: delete.py プロジェクト: m-rey/orthos2
    def post(self, request, *args, **kwargs):
        """Delete machine."""
        if not request.user.is_superuser:
            return ErrorMessage(
                "Only superusers are allowed to perform this action!").as_json

        data = json.loads(request.body.decode('utf-8'))['form']
        form = DeleteMachineAPIForm(data)

        if form.is_valid():

            try:
                cleaned_data = form.cleaned_data

                machine = Machine.objects.get(
                    fqdn__iexact=cleaned_data['fqdn'])

                if machine.is_virtual_machine():
                    host = machine.get_hypervisor()

                    if host.virtualization_api is None:
                        return ErrorMessage(
                            "No virtualization API found!").as_json

                    if host.virtualization_api.remove(machine):
                        result = machine.delete()
                else:
                    result = machine.delete()

                theader = [
                    {
                        'objects': 'Deleted objects'
                    },
                    {
                        'count': '#'
                    },
                ]

                response = {
                    'header': {
                        'type': 'TABLE',
                        'theader': theader
                    },
                    'data': [],
                }
                for key, value in result[1].items():
                    response['data'].append({
                        'objects': key.replace('data.', ''),
                        'count': value
                    })
                return JsonResponse(response)

            except Exception as e:
                logger.exception(e)
                return ErrorMessage("Something went wrong!").as_json

        return ErrorMessage("\n{}".format(
            format_cli_form_errors(form))).as_json
コード例 #5
0
ファイル: add.py プロジェクト: MingZhai/orthos2
    def post(self, request, architecture, *args, **kwargs):
        """Add virtual machine for specific `architecture`."""
        data = json.loads(request.body.decode('utf-8'))['form']

        try:
            host = Machine.api.get(fqdn__iexact=data['host'],
                                   vm_dedicated_host=True)
        except Machine.DoesNotExist:
            return ErrorMessage("Host doesn't exist!").as_json
        except Exception as e:
            return ErrorMessage(str(e)).as_json

        if not host.virtualization_api:
            return ErrorMessage("No virtualization API available!").as_json

        form = VirtualMachineAPIForm(
            data, virtualization_api=host.virtualization_api)

        if form.is_valid():
            try:
                vm = host.virtualization_api.create(**form.cleaned_data)

                vm.reserve(reason='VM of {}'.format(request.user),
                           until=add_offset_to_date(30),
                           user=request.user)

                theader = [
                    {
                        'fqdn': 'FQDN'
                    },
                    {
                        'mac_address': 'MAC address'
                    },
                ]
                if vm.vnc['enabled']:
                    theader.append({'vnc': 'VNC'})

                response = {
                    'header': {
                        'type': 'TABLE',
                        'theader': theader
                    },
                    'data': [{
                        'fqdn': vm.fqdn,
                        'mac_address': vm.mac_address
                    }],
                }
                if vm.vnc['enabled']:
                    response['data'][0]['vnc'] = '{}:{}'.format(
                        host.fqdn, vm.vnc['port'])

                return JsonResponse(response)

            except Exception as e:
                return ErrorMessage(str(e)).as_json

        return ErrorMessage("\n{}".format(
            format_cli_form_errors(form))).as_json
コード例 #6
0
ファイル: reserve.py プロジェクト: openSUSE/orthos2
    def post(self, request, id, *args, **kwargs):
        """Process reservation."""
        try:
            machine = Machine.objects.get(pk=id)
        except Machine.DoesNotExist:
            return ErrorMessage("Machine doesn't exist!").as_json

        try:
            data = json.loads(request.body.decode('utf-8'))['form']

            if data['until'] == 0 and request.user.is_superuser:
                # set to 'infinite'
                data['until'] = datetime.date.max
            else:
                # set 'until' field (=offset) to concrete date for form validation
                data['until'] = add_offset_to_date(data['until'],
                                                   as_string=True)

            form = ReserveMachineAPIForm(data)
        except (KeyError, ValueError):
            return ErrorMessage("Data format is invalid!").as_json

        if form.is_valid():
            reason = form.cleaned_data['reason']
            until = form.cleaned_data['until']
            username = form.cleaned_data['username']

            try:
                user = User.objects.get(username=username)
            except Exception:
                return ErrorMessage("User doesn't exist!").as_json

            try:
                machine.reserve(reason,
                                until,
                                user=request.user,
                                reserve_for_user=user)
                return Message('OK.').as_json

            except Exception as e:
                return ErrorMessage(str(e)).as_json
        else:
            return ErrorMessage("\n{}".format(
                format_cli_form_errors(form))).as_json
コード例 #7
0
ファイル: add.py プロジェクト: MingZhai/orthos2
    def post(self, request, *args, **kwargs):
        """Add remote power to machine."""
        if not request.user.is_superuser:
            return ErrorMessage(
                "Only superusers are allowed to perform this action!").as_json

        try:
            fqdn = request.path.split("/")[-1]
            result = get_machine(fqdn,
                                 redirect_to='api:remotepower_add',
                                 data=request.GET)
            if isinstance(result, Serializer):
                return result.as_json
            elif isinstance(result, HttpResponseRedirect):
                return result
            machine = result
        except Exception as e:
            return ErrorMessage(str(e)).as_json

        if machine.has_remotepower():
            return InfoMessage("Machine has already a remote power.").as_json

        data = json.loads(request.body.decode('utf-8'))['form']
        form = RemotePowerAPIForm(data, machine=machine)

        if form.is_valid():
            try:
                remotepower = RemotePower(**form.cleaned_data)
                remotepower.save()
            except Exception as e:
                logger.exception(e)
                return ErrorMessage("Something went wrong!").as_json

            return Message('Ok.').as_json

        return ErrorMessage("\n{}".format(
            format_cli_form_errors(form))).as_json
コード例 #8
0
ファイル: add.py プロジェクト: MingZhai/orthos2
    def post(self, request, *args, **kwargs):
        """Add BMC to machine."""
        try:

            fqdn = request.path.split("/")[-1]
            result = get_machine(fqdn,
                                 redirect_to='api:bmc_add',
                                 data=request.GET)
            if isinstance(result, Serializer):
                return result.as_json
            elif isinstance(result, HttpResponseRedirect):
                return result
            machine = result
        except Exception as e:
            return ErrorMessage(str(e)).as_json

        data = json.loads(request.body.decode('utf-8'))['form']
        form = BMCAPIForm(data, machine=machine)

        if form.is_valid():
            try:
                cleaned_data = form.cleaned_data
                bmc = BMC(machine=machine,
                          fqdn=cleaned_data['fqdn'],
                          mac=cleaned_data['mac'],
                          username=cleaned_data['username'],
                          password=cleaned_data['password'],
                          fence_name=cleaned_data['fence_name'])
                bmc.save()
            except Exception as e:
                logger.exception(e)
                return ErrorMessage("Something went wrong!").as_json

            return Message('Ok.').as_json

        return ErrorMessage("\n{}".format(
            format_cli_form_errors(form))).as_json