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() != 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
def _setup(self, request, machine, distribution): """Trigger machine setup for `machine` with `distribution`.""" if isinstance(request.user, AnonymousUser) or not request.auth: return AuthRequiredSerializer().as_json machinegroup = None if machine.group and not machine.group.setup_use_architecture: machinegroup = machine.group.name valid = machine.fqdn_domain.is_valid_setup_choice( distribution, machine.architecture.name, machinegroup=machinegroup) if not valid: return ErrorMessage( "Unknown choice '{}'! Use 'SETUP <fqdn> list'.".format( distribution)).as_json try: result = machine.setup(distribution) if result: message = "OK." if not machine.has_remotepower(): message += " This machine has no remote power - "\ "a manuall reboot may be required." return Message(message).as_json else: return ErrorMessage( "Machine has no setup capability! Please contact '{}'.". format(machine.get_support_contact())).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) 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
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
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
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
def get(self, request, *args, **kwargs): """Return form for adding a virtual machine.""" architectures = self._get_available_architectures() architecture = request.GET.get('arch', None) if architecture.lower() not in architectures: return Message("Available architectures: {}".format( '|'.join(architectures))).as_json if isinstance(request.user, AnonymousUser) or not request.auth: return AuthRequiredSerializer().as_json hosts = Machine.api.filter(vm_dedicated_host=True, architecture__name=architecture) host = None for host_ in hosts: if host_.virtualization_api and ( host_.get_virtual_machines().count() < host_.vm_max): host = host_ break if host is None: return ErrorMessage("No virtual machine hosts left!").as_json form = VirtualMachineAPIForm( virtualization_api=host.virtualization_api) input = InputSerializer(form.as_dict(host), self.URL_POST.format(arch=architecture), form.get_order()) return input.as_json
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
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
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
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
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): """Trigger regeneration of machine-related/service files.""" service = request.GET.get('service', None) fqdn = request.GET.get('fqdn', None) machine = None 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 not service: return ErrorMessage("Service not set").as_json if fqdn: try: machine = get_machine(fqdn, redirect_to='api:regenerate', data=request.GET) if not machine: return ErrorMessage( "machine {} not found".format(fqdn)).as_json if isinstance(machine, Serializer): return machine.as_json elif isinstance(machine, HttpResponseRedirect): return machine except Exception as e: return ErrorMessage(str(e)).as_json # regenerate Cobbler entries if service.lower() == RegenerateCommand.COBBLER: domain_id = None if fqdn: domain = get_domain(fqdn) if not domain: return ErrorMessage("No domain found for machine: " + fqdn).as_json o_domain = Domain.objects.get(name=domain) if not o_domain: return ErrorMessage("No orthos domain found for domain: " + domain).as_json domain_id = getattr(o_domain, 'id', None) if not domain_id: return ErrorMessage( "Could not find id for orthos domain: " + domain).as_json msg = 'domain ' + domain else: domain = None msg = 'all domains' signal_cobbler_regenerate.send(sender=None, domain_id=domain_id) return Message("Regenerate Cobbler entries for " + msg).as_json # regenerate serial console entries iterating over all cscreen servers elif service.lower() == RegenerateCommand.SERIALCONSOLE: machines = SerialConsole.objects.all().values_list( 'cscreen_server__fqdn', flat=True) if fqdn: if fqdn in machines.distinct(): signal_serialconsole_regenerate.send( sender=None, cscreen_server_fqdn=fqdn) msg = fqdn else: return ErrorMessage("Not a serial console server: " + fqdn).as_json else: msg = '' for fqdn in machines.distinct(): signal_serialconsole_regenerate.send( sender=None, cscreen_server_fqdn=fqdn) msg += ' ' + fqdn return Message( "Regenerated serial console entries for serial console servers: " + msg).as_json # regenerate MOTD (only works per machine atm) elif service.lower() == RegenerateCommand.MOTD: if not fqdn: return Message("regenerte motd needs fqdn parameter").as_json machine.update_motd(user=request.user) return Message("OK.").as_json else: return ErrorMessage("Unknown service {}".format(service)).as_json return ErrorMessage("Unknown error - params: {} - {}".format( service, fqdn)).as_json