Esempio n. 1
0
    def get(self, request, *args, **kwargs):
        """
        Perform machine setup.
        """
        fqdn = request.GET.get('fqdn', None)
        option_or_choice = request.GET.get('option_or_choice', None)
        choice = None

        try:
            result = get_machine(fqdn,
                                 redirect_to='api:setup',
                                 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 option_or_choice.lower() == 'list':
            return self._list(request, machine)
        else:
            choice = option_or_choice
            return self._setup(request, machine, choice)

        return ErrorMessage("Something went wrong!").as_json
Esempio n. 2
0
    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
Esempio n. 3
0
    def get(self, request, *args, **kwargs):
        """
        Return reservation history of machine.
        """
        fqdn = request.GET.get('fqdn', None)
        option = request.GET.get('option', None)

        try:
            result = get_machine(fqdn,
                                 redirect_to='api:rescan',
                                 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 option not in MachineCheck.Scan.Action.as_list:
            return ErrorMessage("Unknown option '{}'!".format(option)).as_json

        try:
            machine.scan(option)

            if not machine.collect_system_information:
                return InfoMessage(
                    "Collecting system information is disabled for this machine."
                ).as_json

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

        return Message("OK.").as_json
Esempio n. 4
0
    def get(self, request, *args, **kwargs):
        """
        Return form for adding a remotepower.
        """
        fqdn = request.GET.get('fqdn', None)
        try:
            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 isinstance(request.user, AnonymousUser) or not request.auth:
            return AuthRequiredSerializer().as_json

        if not request.user.is_superuser:
            return ErrorMessage(
                "Only superusers are allowed to perform this action!").as_json

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

        form = RemotePowerAPIForm(machine=machine)

        input = InputSerializer(form.as_dict(),
                                self.URL_POST.format(fqdn=machine.fqdn),
                                form.get_order())
        return input.as_json
Esempio n. 5
0
    def get(self, request, *args, **kwargs):
        """
        Return reservation form for valid machine.
        """
        fqdn = request.GET.get('fqdn', None)

        try:
            result = get_machine(fqdn,
                                 redirect_to='api:reserve',
                                 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 isinstance(request.user, AnonymousUser) or not request.auth:
            return AuthRequiredSerializer().as_json

        form = ReserveMachineAPIForm(username=request.user.username,
                                     reason=machine.reserved_reason)

        input = InputSerializer(form.as_dict(),
                                self.URL_POST.format(id=machine.pk),
                                form.get_order())
        return input.as_json
Esempio n. 6
0
    def get(self, request, *args, **kwargs):
        """
        Return form for adding an annotation.
        """
        fqdn = request.GET.get('fqdn', None)
        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

        if isinstance(request.user, AnonymousUser) or not request.auth:
            return AuthRequiredSerializer().as_json

        form = AnnotationAPIForm(machine=machine)

        input = InputSerializer(form.as_dict(),
                                self.URL_POST.format(fqdn=machine.fqdn),
                                form.get_order())
        return input.as_json
Esempio n. 7
0
    def get(self, request, *args, **kwargs):
        """
        Release a machine.
        """
        fqdn = request.GET.get('fqdn', None)

        try:
            result = get_machine(fqdn,
                                 redirect_to='api:release',
                                 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 isinstance(request.user, AnonymousUser) or not request.auth:
            return AuthRequiredSerializer().as_json

        try:
            machine.release(user=request.user)
            return Message('OK.').as_json
        except Exception as e:
            return ErrorMessage(str(e)).as_json
    def get(self, request, *args, **kwargs):
        """
        Return reservation history of machine.
        """
        fqdn = request.GET.get('fqdn', None)

        try:
            result = get_machine(fqdn,
                                 redirect_to='api:history',
                                 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

        history = ReservationHistory.objects.filter(machine__fqdn=machine.fqdn)

        if history.count() == 0:
            return InfoMessage("No history available yet.").as_json

        theader = [{
            'user': '******'
        }, {
            'at': 'Reserved at'
        }, {
            'until': 'Reserved until'
        }, {
            'reason': 'Reason'
        }]
        response = {
            'header': {
                'type': 'TABLE',
                'theader': theader
            },
            'data': []
        }

        for item in history:
            response['data'].append({
                'user':
                item.reserved_by,
                'at':
                item.reserved_at,
                'until':
                item.reserved_until,
                'reason':
                item.reserved_reason.replace('\n', '')
            })

        return JsonResponse(response)
Esempio n. 9
0
    def get(self, request, *args, **kwargs):
        """
        Perform machine power cycle.
        """
        fqdn = request.GET.get('fqdn', None)
        action = request.GET.get('action', None)

        if action.lower() not in RemotePower.Action.as_list:
            return ErrorMessage("Unknown action '{}'!".format(action)).as_json

        try:
            result = get_machine(
                fqdn,
                redirect_to='api:powercycle',
                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 isinstance(request.user, AnonymousUser) or not request.auth:
            return AuthRequiredSerializer().as_json

        if not machine.has_remotepower():
            return ErrorMessage("Machine has no remote power!").as_json

        try:
            result = machine.powercycle(action.lower(), user=request.user)

            if action.lower() == RemotePower.Action.STATUS:
                return Message("Status: {} ({})".format(
                    result.capitalize(),
                    machine.remotepower.name
                )).as_json

            if result:
                return Message("OK.").as_json
            else:
                return ErrorMessage("Something went wrong!").as_json

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

        return ErrorMessage("Something went wrong!").as_json
Esempio n. 10
0
    def post(self, request, fqdn, *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:
            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
Esempio n. 11
0
    def get(self, request, *args, **kwargs):
        """
        Return machine information.
        """
        fqdn = request.GET.get('fqdn', None)
        response = {}

        try:
            result = get_machine(
                fqdn,
                redirect_to='api:machine',
                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

        machine.enclosure.fetch_location(machine.pk)
        machine = MachineSerializer(machine)

        order = [
            'fqdn',
            'architecture',
            'ipv4',
            'ipv6',
            'serial_number',
            'product_code',
            'comment',
            'nda',
            None,
            'system',
            'enclosure',
            'group',
            None,
            'location_room',
            'location_rack',
            'location_rack_position',
            None,
            'reserved_by',
            'reserved_reason',
            'reserved_at',
            'reserved_until',
            None,
            'status_ipv4',
            'status_ipv6',
            'status_ssh',
            'status_login',
            'status_abuild',
            None,
            'cpu_model',
            'cpu_id',
            'cpu_physical',
            'cpu_cores',
            'cpu_threads',
            'cpu_flags',
            'ram_amount',
            None,
            'serial_type',
            'serial_cscreen_server',
            'serial_management_bmc',
            'serial_console_server',
            'serial_device',
            'serial_port',
            'serial_command',
            'serial_comment',
            'serial_baud_rate',
            'serial_kernel_device',
            None,
            'power_type',
            'power_management_bmc',
            'power_host',
            'power_port',
            'power_device',
            'power_comment',
            [
                'installations', [
                    'distribution',
                    'active',
                    'partition',
                    'architecture',
                    'kernelversion'
                ]
            ],
            [
                'networkinterfaces', [
                    'mac_address',
                    'name',
                    'ethernet_type',
                    'driver_module',
                    'primary',
                ]
            ],
            [
                'annotations', [
                    'text',
                    'reporter',
                    'created'
                ]
            ]
        ]

        response['header'] = {'type': 'INFO', 'order': order}
        response['data'] = machine.data_info

        return JsonResponse(response)
Esempio n. 12
0
    def get(self, request, *args, **kwargs):
        """
        Trigger regeneration of machine-related/service files.
        """
        fqdn = request.GET.get('fqdn', None)
        option = request.GET.get('option', None)
        service = request.GET.get('service', None)

        if service and (service.lower()
                        in [Regenerate.COBBLER, Regenerate.SERIALCONSOLE]):
            if isinstance(request.user, AnonymousUser) or not request.auth:
                return AuthRequiredSerializer().as_json

            if not request.user.is_superuser:
                return ErrorMessage(
                    "Only superusers are allowed to perform this action!"
                ).as_json

            # regenerate Cobbler entries
            if service.lower() == Regenerate.COBBLER:
                signal_cobbler_regenerate.send(sender=None, domain_id=None)
                return Message("Regenerate Cobbler entries...").as_json

            # regenerate serial console entries iterating over all cscreen servers
            elif service.lower() == Regenerate.SERIALCONSOLE:
                machines = SerialConsole.objects.all().values_list(
                    'cscreen_server__fqdn', flat=True)

                for fqdn in machines.distinct():
                    signal_serialconsole_regenerate.send(
                        sender=None, cscreen_server_fqdn=fqdn)

                return Message("Regenerate serial console entries...").as_json

        elif (fqdn is not None) and (option is not None):
            try:
                result = get_machine(fqdn,
                                     redirect_to='api:regenerate',
                                     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 option.lower() not in [Regenerate.MOTD]:
                return ErrorMessage(
                    "Unknown option '{}'!".format(option)).as_json

            if isinstance(request.user, AnonymousUser) or not request.auth:
                return AuthRequiredSerializer().as_json

            try:
                if option.lower() == Regenerate.MOTD:
                    machine.update_motd(user=request.user)
                    return Message("OK.").as_json
            except Exception as e:
                return ErrorMessage(str(e)).as_json

        return ErrorMessage("Unknown service '{}'!".format(service)).as_json