api/machines: init put_machine replacing create_machine and set_machine_config

This allows creating and configuring a machine in one single step.
This commit is contained in:
DavHau
2023-11-13 20:25:52 +07:00
parent 0dae746bed
commit 2fafc9a38b
8 changed files with 35 additions and 88 deletions

View File

@@ -1,5 +1,4 @@
import logging
import re
from pathlib import Path
from typing import Any
@@ -31,15 +30,3 @@ class MachineConfig(BaseModel):
# allow extra fields to cover the full spectrum of a nixos config
class Config:
extra = Extra.allow
class MachineCreate(BaseModel):
name: str
@classmethod
@validator("name")
def validate_hostname(cls, v: str) -> str:
hostname_regex = r"^(?!-)[A-Za-z0-9-]{1,63}(?<!-)$"
if not re.match(hostname_regex, v):
raise ValueError("Machine name must be a valid hostname")
return v

View File

@@ -3,9 +3,10 @@ import logging
from typing import Annotated
from fastapi import APIRouter, Body
from fastapi.encoders import jsonable_encoder
from clan_cli.webui.api_errors import MissingClanImports
from clan_cli.webui.api_inputs import MachineConfig, MachineCreate
from clan_cli.webui.api_inputs import MachineConfig
from ...config.machine import (
config_for_machine,
@@ -13,7 +14,6 @@ from ...config.machine import (
verify_machine_config,
)
from ...config.schema import machine_schema
from ...machines.create import create_machine as _create_machine
from ...machines.list import list_machines as _list_machines
from ...types import FlakeName
from ..api_outputs import (
@@ -40,14 +40,6 @@ async def list_machines(flake_name: FlakeName) -> MachinesResponse:
return MachinesResponse(machines=machines)
@router.post("/api/{flake_name}/machines", tags=[Tags.machine], status_code=201)
async def create_machine(
flake_name: FlakeName, machine: Annotated[MachineCreate, Body()]
) -> MachineResponse:
await _create_machine(flake_name, machine.name)
return MachineResponse(machine=Machine(name=machine.name, status=Status.UNKNOWN))
@router.get("/api/{flake_name}/machines/{name}", tags=[Tags.machine])
async def get_machine(flake_name: FlakeName, name: str) -> MachineResponse:
log.error("TODO")
@@ -61,10 +53,14 @@ async def get_machine_config(flake_name: FlakeName, name: str) -> ConfigResponse
@router.put("/api/{flake_name}/machines/{name}/config", tags=[Tags.machine])
async def set_machine_config(
async def put_machine(
flake_name: FlakeName, name: str, config: Annotated[MachineConfig, Body()]
) -> None:
conf = dict(config)
"""
Set the config for a machine.
Creates the machine if it doesn't yet exist.
"""
conf = jsonable_encoder(config)
set_config_for_machine(flake_name, name, conf)