webui: implement /api/machines/{name}/schema

This commit is contained in:
DavHau
2023-08-25 21:26:30 +02:00
parent 6d4d455626
commit fb76ad45e8
10 changed files with 121 additions and 11 deletions

View File

@@ -0,0 +1,47 @@
import json
import subprocess
import sys
from pathlib import Path
from typing import Optional
from ..dirs import get_clan_flake_toplevel
def schema_for_machine(machine_name: str, flake: Optional[Path] = None) -> dict:
if flake is None:
flake = get_clan_flake_toplevel()
# use nix eval to read from .#clanModules.<module_name>.options
proc = subprocess.run(
[
"nix",
"eval",
"--json",
"--impure",
"--show-trace",
"--extra-experimental-features",
"nix-command flakes",
"--expr",
f"""
let
flake = builtins.getFlake (toString {flake});
lib = flake.inputs.nixpkgs.lib;
module = builtins.trace (builtins.attrNames flake) flake.clanModules.machine-{machine_name};
evaled = lib.evalModules {{
modules = [module];
}};
clanOptions = evaled.options.clan;
jsonschemaLib = import {Path(__file__).parent / "jsonschema"} {{ inherit lib; }};
jsonschema = jsonschemaLib.parseOptions clanOptions;
in
jsonschema
""",
],
capture_output=True,
text=True,
)
if proc.returncode != 0:
print(proc.stderr, file=sys.stderr)
raise Exception(
f"Failed to read schema for machine {machine_name}:\n{proc.stderr}"
)
return json.loads(proc.stdout)

View File

@@ -2,6 +2,7 @@ from typing import Annotated
from fastapi import APIRouter, Body
from ...config.machine import schema_for_machine
from ...machines.create import create_machine as _create_machine
from ...machines.list import list_machines as _list_machines
from ..schemas import (
@@ -11,7 +12,6 @@ from ..schemas import (
MachineCreate,
MachineResponse,
MachinesResponse,
Schema,
SchemaResponse,
Status,
)
@@ -54,5 +54,5 @@ async def set_machine_config(
@router.get("/api/machines/{name}/schema")
async def get_machine_schema(name: str) -> SchemaResponse:
print("TODO")
return SchemaResponse(schema=Schema())
schema = schema_for_machine(name)
return SchemaResponse(schema=schema)

View File

@@ -34,9 +34,5 @@ class ConfigResponse(BaseModel):
config: Config
class Schema(BaseModel):
pass
class SchemaResponse(BaseModel):
schema_: Schema = Field(alias="schema")
schema_: dict = Field(alias="schema")