Can create VM from UI

This commit is contained in:
Pierre HUBERT 2023-10-16 19:00:15 +02:00
parent 7ef5afb978
commit fbfe4f00c5
12 changed files with 420 additions and 10 deletions

View File

@ -16,7 +16,21 @@ struct StaticConfig {
local_auth_enabled: bool, local_auth_enabled: bool,
oidc_auth_enabled: bool, oidc_auth_enabled: bool,
iso_mimetypes: &'static [&'static str], iso_mimetypes: &'static [&'static str],
constraints: ServerConstraints,
}
#[derive(serde::Serialize)]
struct LenConstraints {
min: usize,
max: usize,
}
#[derive(serde::Serialize)]
struct ServerConstraints {
iso_max_size: usize, iso_max_size: usize,
name_size: LenConstraints,
title_size: LenConstraints,
memory_size: LenConstraints,
} }
pub async fn static_config(local_auth: LocalAuthEnabled) -> impl Responder { pub async fn static_config(local_auth: LocalAuthEnabled) -> impl Responder {
@ -25,7 +39,16 @@ pub async fn static_config(local_auth: LocalAuthEnabled) -> impl Responder {
local_auth_enabled: *local_auth, local_auth_enabled: *local_auth,
oidc_auth_enabled: !AppConfig::get().disable_oidc, oidc_auth_enabled: !AppConfig::get().disable_oidc,
iso_mimetypes: &constants::ALLOWED_ISO_MIME_TYPES, iso_mimetypes: &constants::ALLOWED_ISO_MIME_TYPES,
iso_max_size: constants::ISO_MAX_SIZE, constraints: ServerConstraints {
iso_max_size: constants::ISO_MAX_SIZE,
name_size: LenConstraints { min: 2, max: 50 },
title_size: LenConstraints { min: 0, max: 50 },
memory_size: LenConstraints {
min: constants::MIN_VM_MEMORY,
max: constants::MAX_VM_MEMORY,
},
},
}) })
} }

View File

@ -10,6 +10,11 @@ struct VMInfoAndState {
state: DomainState, state: DomainState,
} }
#[derive(serde::Serialize)]
struct VMUuid {
uuid: DomainXMLUuid,
}
/// Create a new VM /// Create a new VM
pub async fn create(client: LibVirtReq, req: web::Json<VMInfo>) -> HttpResult { pub async fn create(client: LibVirtReq, req: web::Json<VMInfo>) -> HttpResult {
let domain = match req.0.to_domain() { let domain = match req.0.to_domain() {
@ -21,7 +26,7 @@ pub async fn create(client: LibVirtReq, req: web::Json<VMInfo>) -> HttpResult {
}; };
let id = client.update_domain(domain).await?; let id = client.update_domain(domain).await?;
Ok(HttpResponse::Ok().json(id)) Ok(HttpResponse::Ok().json(VMUuid { uuid: id }))
} }
/// Get the list of domains /// Get the list of domains

View File

@ -25,6 +25,7 @@
"@types/node": "^16.18.48", "@types/node": "^16.18.48",
"@types/react": "^18.2.21", "@types/react": "^18.2.21",
"@types/react-dom": "^18.2.7", "@types/react-dom": "^18.2.7",
"@types/uuid": "^9.0.5",
"filesize": "^10.0.12", "filesize": "^10.0.12",
"humanize-duration": "^3.29.0", "humanize-duration": "^3.29.0",
"mui-file-input": "^3.0.1", "mui-file-input": "^3.0.1",
@ -33,6 +34,7 @@
"react-router-dom": "^6.15.0", "react-router-dom": "^6.15.0",
"react-scripts": "5.0.1", "react-scripts": "5.0.1",
"typescript": "^4.9.5", "typescript": "^4.9.5",
"uuid": "^9.0.1",
"web-vitals": "^2.1.4" "web-vitals": "^2.1.4"
} }
}, },
@ -4754,6 +4756,11 @@
"resolved": "https://registry.npmjs.org/@types/trusted-types/-/trusted-types-2.0.3.tgz", "resolved": "https://registry.npmjs.org/@types/trusted-types/-/trusted-types-2.0.3.tgz",
"integrity": "sha512-NfQ4gyz38SL8sDNrSixxU2Os1a5xcdFxipAFxYEuLUlvU2uDwS4NUpsImcf1//SlWItCVMMLiylsxbmNMToV/g==" "integrity": "sha512-NfQ4gyz38SL8sDNrSixxU2Os1a5xcdFxipAFxYEuLUlvU2uDwS4NUpsImcf1//SlWItCVMMLiylsxbmNMToV/g=="
}, },
"node_modules/@types/uuid": {
"version": "9.0.5",
"resolved": "https://registry.npmjs.org/@types/uuid/-/uuid-9.0.5.tgz",
"integrity": "sha512-xfHdwa1FMJ082prjSJpoEI57GZITiQz10r3vEJCHa2khEFQjKy91aWKz6+zybzssCvXUwE1LQWgWVwZ4nYUvHQ=="
},
"node_modules/@types/ws": { "node_modules/@types/ws": {
"version": "8.5.5", "version": "8.5.5",
"resolved": "https://registry.npmjs.org/@types/ws/-/ws-8.5.5.tgz", "resolved": "https://registry.npmjs.org/@types/ws/-/ws-8.5.5.tgz",
@ -16091,6 +16098,14 @@
"websocket-driver": "^0.7.4" "websocket-driver": "^0.7.4"
} }
}, },
"node_modules/sockjs/node_modules/uuid": {
"version": "8.3.2",
"resolved": "https://registry.npmjs.org/uuid/-/uuid-8.3.2.tgz",
"integrity": "sha512-+NYs2QeMWy+GWFOEm9xnn6HCDp0l7QBD7ml8zLUmJ+93Q5NF0NocErnwkTkXVFNiX3/fpC6afS8Dhb/gz7R7eg==",
"bin": {
"uuid": "dist/bin/uuid"
}
},
"node_modules/source-list-map": { "node_modules/source-list-map": {
"version": "2.0.1", "version": "2.0.1",
"resolved": "https://registry.npmjs.org/source-list-map/-/source-list-map-2.0.1.tgz", "resolved": "https://registry.npmjs.org/source-list-map/-/source-list-map-2.0.1.tgz",
@ -17255,9 +17270,13 @@
} }
}, },
"node_modules/uuid": { "node_modules/uuid": {
"version": "8.3.2", "version": "9.0.1",
"resolved": "https://registry.npmjs.org/uuid/-/uuid-8.3.2.tgz", "resolved": "https://registry.npmjs.org/uuid/-/uuid-9.0.1.tgz",
"integrity": "sha512-+NYs2QeMWy+GWFOEm9xnn6HCDp0l7QBD7ml8zLUmJ+93Q5NF0NocErnwkTkXVFNiX3/fpC6afS8Dhb/gz7R7eg==", "integrity": "sha512-b+1eJOlsR9K8HJpow9Ok3fiWOWSIcIzXodvv0rQjVoOVNpWMpxf1wZNpt4y9h10odCNrqnYp1OBzRktckBe3sA==",
"funding": [
"https://github.com/sponsors/broofa",
"https://github.com/sponsors/ctavan"
],
"bin": { "bin": {
"uuid": "dist/bin/uuid" "uuid": "dist/bin/uuid"
} }
@ -21469,6 +21488,11 @@
"resolved": "https://registry.npmjs.org/@types/trusted-types/-/trusted-types-2.0.3.tgz", "resolved": "https://registry.npmjs.org/@types/trusted-types/-/trusted-types-2.0.3.tgz",
"integrity": "sha512-NfQ4gyz38SL8sDNrSixxU2Os1a5xcdFxipAFxYEuLUlvU2uDwS4NUpsImcf1//SlWItCVMMLiylsxbmNMToV/g==" "integrity": "sha512-NfQ4gyz38SL8sDNrSixxU2Os1a5xcdFxipAFxYEuLUlvU2uDwS4NUpsImcf1//SlWItCVMMLiylsxbmNMToV/g=="
}, },
"@types/uuid": {
"version": "9.0.5",
"resolved": "https://registry.npmjs.org/@types/uuid/-/uuid-9.0.5.tgz",
"integrity": "sha512-xfHdwa1FMJ082prjSJpoEI57GZITiQz10r3vEJCHa2khEFQjKy91aWKz6+zybzssCvXUwE1LQWgWVwZ4nYUvHQ=="
},
"@types/ws": { "@types/ws": {
"version": "8.5.5", "version": "8.5.5",
"resolved": "https://registry.npmjs.org/@types/ws/-/ws-8.5.5.tgz", "resolved": "https://registry.npmjs.org/@types/ws/-/ws-8.5.5.tgz",
@ -29487,6 +29511,13 @@
"faye-websocket": "^0.11.3", "faye-websocket": "^0.11.3",
"uuid": "^8.3.2", "uuid": "^8.3.2",
"websocket-driver": "^0.7.4" "websocket-driver": "^0.7.4"
},
"dependencies": {
"uuid": {
"version": "8.3.2",
"resolved": "https://registry.npmjs.org/uuid/-/uuid-8.3.2.tgz",
"integrity": "sha512-+NYs2QeMWy+GWFOEm9xnn6HCDp0l7QBD7ml8zLUmJ+93Q5NF0NocErnwkTkXVFNiX3/fpC6afS8Dhb/gz7R7eg=="
}
} }
}, },
"source-list-map": { "source-list-map": {
@ -30346,9 +30377,9 @@
"integrity": "sha512-pMZTvIkT1d+TFGvDOqodOclx0QWkkgi6Tdoa8gC8ffGAAqz9pzPTZWAybbsHHoED/ztMtkv/VoYTYyShUn81hA==" "integrity": "sha512-pMZTvIkT1d+TFGvDOqodOclx0QWkkgi6Tdoa8gC8ffGAAqz9pzPTZWAybbsHHoED/ztMtkv/VoYTYyShUn81hA=="
}, },
"uuid": { "uuid": {
"version": "8.3.2", "version": "9.0.1",
"resolved": "https://registry.npmjs.org/uuid/-/uuid-8.3.2.tgz", "resolved": "https://registry.npmjs.org/uuid/-/uuid-9.0.1.tgz",
"integrity": "sha512-+NYs2QeMWy+GWFOEm9xnn6HCDp0l7QBD7ml8zLUmJ+93Q5NF0NocErnwkTkXVFNiX3/fpC6afS8Dhb/gz7R7eg==" "integrity": "sha512-b+1eJOlsR9K8HJpow9Ok3fiWOWSIcIzXodvv0rQjVoOVNpWMpxf1wZNpt4y9h10odCNrqnYp1OBzRktckBe3sA=="
}, },
"v8-to-istanbul": { "v8-to-istanbul": {
"version": "8.1.1", "version": "8.1.1",

View File

@ -20,6 +20,7 @@
"@types/node": "^16.18.48", "@types/node": "^16.18.48",
"@types/react": "^18.2.21", "@types/react": "^18.2.21",
"@types/react-dom": "^18.2.7", "@types/react-dom": "^18.2.7",
"@types/uuid": "^9.0.5",
"filesize": "^10.0.12", "filesize": "^10.0.12",
"humanize-duration": "^3.29.0", "humanize-duration": "^3.29.0",
"mui-file-input": "^3.0.1", "mui-file-input": "^3.0.1",
@ -28,6 +29,7 @@
"react-router-dom": "^6.15.0", "react-router-dom": "^6.15.0",
"react-scripts": "5.0.1", "react-scripts": "5.0.1",
"typescript": "^4.9.5", "typescript": "^4.9.5",
"uuid": "^9.0.1",
"web-vitals": "^2.1.4" "web-vitals": "^2.1.4"
}, },
"scripts": { "scripts": {

View File

@ -16,6 +16,7 @@ import { IsoFilesRoute } from "./routes/IsoFilesRoute";
import { ServerApi } from "./api/ServerApi"; import { ServerApi } from "./api/ServerApi";
import { SysInfoRoute } from "./routes/SysInfoRoute"; import { SysInfoRoute } from "./routes/SysInfoRoute";
import { VirtualMachinesRoute } from "./routes/VirtualMachinesRoute"; import { VirtualMachinesRoute } from "./routes/VirtualMachinesRoute";
import { CreateVMRoute, EditVMRoute } from "./routes/EditVMRoute";
interface AuthContext { interface AuthContext {
signedIn: boolean; signedIn: boolean;
@ -37,7 +38,11 @@ export function App() {
signedIn || ServerApi.Config.auth_disabled ? ( signedIn || ServerApi.Config.auth_disabled ? (
<Route path="*" element={<BaseAuthenticatedPage />}> <Route path="*" element={<BaseAuthenticatedPage />}>
<Route path="iso" element={<IsoFilesRoute />} /> <Route path="iso" element={<IsoFilesRoute />} />
<Route path="vms" element={<VirtualMachinesRoute />} /> <Route path="vms" element={<VirtualMachinesRoute />} />
<Route path="vms/new" element={<CreateVMRoute />} />
<Route path="vms/:uuid/edit" element={<EditVMRoute />} />
<Route path="sysinfo" element={<SysInfoRoute />} /> <Route path="sysinfo" element={<SysInfoRoute />} />
<Route path="*" element={<NotFoundRoute />} /> <Route path="*" element={<NotFoundRoute />} />
</Route> </Route>

View File

@ -5,7 +5,19 @@ export interface ServerConfig {
local_auth_enabled: boolean; local_auth_enabled: boolean;
oidc_auth_enabled: boolean; oidc_auth_enabled: boolean;
iso_mimetypes: string[]; iso_mimetypes: string[];
constraints: ServerConstraints;
}
export interface ServerConstraints {
iso_max_size: number; iso_max_size: number;
name_size: LenConstraint;
title_size: LenConstraint;
memory_size: LenConstraint;
}
export interface LenConstraint {
min: number;
max: number;
} }
let config: ServerConfig | null = null; let config: ServerConfig | null = null;

View File

@ -52,12 +52,35 @@ export class VMInfo implements VMInfoInterface {
this.vnc_access = int.vnc_access; this.vnc_access = int.vnc_access;
} }
static NewEmpty(): VMInfo {
return new VMInfo({
name: "",
boot_type: "UEFI",
architecture: "x86_64",
memory: 1024,
vnc_access: true,
});
}
get ViewURL(): string { get ViewURL(): string {
return `/api/vm/${this.uuid}`; return `/api/vm/${this.uuid}`;
} }
} }
export class VMApi { export class VMApi {
/**
* Create a new virtual machine
*/
static async Create(v: VMInfo): Promise<{ uuid: string }> {
return (
await APIClient.exec({
uri: `/vm/create`,
method: "POST",
jsonData: v,
})
).data;
}
/** /**
* Get the list of defined virtual machines * Get the list of defined virtual machines
*/ */

View File

@ -0,0 +1,195 @@
import React, { PropsWithChildren } from "react";
import { useNavigate } from "react-router-dom";
import { VMApi, VMInfo } from "../api/VMApi";
import { useSnackbar } from "../hooks/providers/SnackbarProvider";
import { VirtWebRouteContainer } from "../widgets/VirtWebRouteContainer";
import { Button, Paper, Typography } from "@mui/material";
import { TextInput } from "../widgets/forms/TextInput";
import { ServerApi } from "../api/ServerApi";
import { validate as validateUUID } from "uuid";
import { SelectInput } from "../widgets/forms/SelectInput";
import { CheckboxInput } from "../widgets/forms/CheckboxInput";
export function CreateVMRoute(): React.ReactElement {
const snackbar = useSnackbar();
const navigate = useNavigate();
const [vm] = React.useState(VMInfo.NewEmpty);
const create = async (v: VMInfo) => {
const res = await VMApi.Create(v);
snackbar("The virtual machine was successfully created!");
v.uuid = res.uuid;
navigate(v.ViewURL);
};
return (
<EditVMInner
vm={vm}
isCreating={true}
onSave={create}
onCancel={() => navigate("/vms")}
/>
);
}
export function EditVMRoute(): React.ReactElement {
return <>todo</>;
}
function EditVMInner(p: {
vm: VMInfo;
isCreating: boolean;
onCancel: () => void;
onSave: (vm: VMInfo) => Promise<void>;
}): React.ReactElement {
const [changed, setChanged] = React.useState(false);
const [, updateState] = React.useState<any>();
const forceUpdate = React.useCallback(() => updateState({}), []);
const valueChanged = () => {
setChanged(true);
forceUpdate();
};
return (
<VirtWebRouteContainer
label={p.isCreating ? "Create a Virtual Machine" : "Edit Virtual Machine"}
actions={
<span>
{changed && (
<Button
variant="contained"
onClick={() => p.onSave(p.vm)}
style={{ marginRight: "10px" }}
>
{p.isCreating ? "Create" : "Save"}
</Button>
)}
<Button onClick={p.onCancel} variant="outlined">
Cancel
</Button>
</span>
}
>
{/* Metadata section */}
<EditSection title="Metadata">
<TextInput
label="Name"
editable={true}
value={p.vm.name}
onValueChange={(v) => {
p.vm.name = v ?? "";
valueChanged();
}}
size={ServerApi.Config.constraints.name_size}
/>
<TextInput label="UUID" editable={false} value={p.vm.uuid} />
<TextInput
label="VM genid"
editable={true}
value={p.vm.genid}
onValueChange={(v) => {
p.vm.genid = v;
valueChanged();
}}
checkValue={(v) => validateUUID(v)}
/>
<TextInput
label="Title"
editable={true}
value={p.vm.title}
onValueChange={(v) => {
p.vm.title = v;
valueChanged();
}}
size={ServerApi.Config.constraints.title_size}
/>
<TextInput
label="Description"
editable={true}
value={p.vm.description}
onValueChange={(v) => {
p.vm.description = v;
valueChanged();
}}
multiline={true}
/>
</EditSection>
{/* General section */}
<EditSection title="General">
<SelectInput
editing={true}
label="CPU Architecture"
onValueChange={(v) => {
p.vm.architecture = v! as any;
valueChanged();
}}
value={p.vm.architecture}
options={[
{ label: "i686", value: "i686" },
{ label: "x86_64", value: "x86_64" },
]}
/>
<SelectInput
editing={true}
label="Boot type"
onValueChange={(v) => {
p.vm.boot_type = v! as any;
valueChanged();
}}
value={p.vm.boot_type}
options={[
{ label: "UEFI with Secure Boot", value: "UEFISecureBoot" },
{ label: "UEFI", value: "UEFI" },
]}
/>
<TextInput
label="Memory (MB)"
editable={true}
type="number"
value={p.vm.memory.toString()}
onValueChange={(v) => {
p.vm.memory = Number(v ?? "0");
valueChanged();
}}
checkValue={(v) =>
Number(v) > ServerApi.Config.constraints.memory_size.min &&
Number(v) < ServerApi.Config.constraints.memory_size.max
}
/>
<CheckboxInput
editable={true}
label="Enable VNC access"
checked={p.vm.vnc_access}
onValueChange={(v) => {
p.vm.vnc_access = v;
valueChanged();
}}
/>
</EditSection>
</VirtWebRouteContainer>
);
}
function EditSection(
p: { title: string } & PropsWithChildren
): React.ReactElement {
return (
<Paper style={{ margin: "10px", padding: "10px" }}>
<Typography variant="h5" style={{ marginBottom: "15px" }}>
{p.title}
</Typography>
{p.children}
</Paper>
);
}

View File

@ -68,10 +68,10 @@ function UploadIsoFileCard(p: {
); );
const handleChange = (newValue: File | null) => { const handleChange = (newValue: File | null) => {
if (newValue && newValue.size > ServerApi.Config.iso_max_size) { if (newValue && newValue.size > ServerApi.Config.constraints.iso_max_size) {
alert( alert(
`The file is too big (max size allowed: ${filesize( `The file is too big (max size allowed: ${filesize(
ServerApi.Config.iso_max_size ServerApi.Config.constraints.iso_max_size
)}` )}`
); );
return; return;

View File

@ -0,0 +1,25 @@
import { Checkbox, FormControlLabel, Typography } from "@mui/material";
export function CheckboxInput(p: {
editable: boolean;
label: string;
checked: boolean | undefined;
onValueChange: (v: boolean) => void;
}): React.ReactElement {
if (!p.editable && p.checked)
return <Typography variant="body2">{p.label}</Typography>;
if (!p.editable) return <></>;
return (
<FormControlLabel
control={
<Checkbox
checked={p.checked}
onChange={(e) => p.onValueChange(e.target.checked)}
/>
}
label={p.label}
/>
);
}

View File

@ -0,0 +1,38 @@
import { FormControl, InputLabel, MenuItem, Select } from "@mui/material";
import { TextInput } from "./TextInput";
export interface SelectOption {
value: string;
label: string;
}
export function SelectInput(p: {
value?: string;
editing: boolean;
label: string;
options: SelectOption[];
onValueChange: (o?: string) => void;
}): React.ReactElement {
if (!p.editing && !p.value) return <></>;
if (!p.editing) {
const value = p.options.find((o) => o.value === p.value)?.label;
return <TextInput label={p.label} editable={p.editing} value={value} />;
}
return (
<FormControl fullWidth variant="standard" style={{ marginBottom: "15px" }}>
<InputLabel>{p.label}</InputLabel>
<Select
value={p.value ?? ""}
label={p.label}
onChange={(e) => p.onValueChange(e.target.value)}
>
{p.options.map((e) => (
<MenuItem key={e.value} value={e.value}>
{e.label}
</MenuItem>
))}
</Select>
</FormControl>
);
}

View File

@ -0,0 +1,51 @@
import { TextField } from "@mui/material";
import { LenConstraint } from "../../api/ServerApi";
/**
* Couple / Member property edition
*/
export function TextInput(p: {
label: string;
editable: boolean;
value?: string;
onValueChange?: (newVal: string | undefined) => void;
size?: LenConstraint;
checkValue?: (s: string) => boolean;
multiline?: boolean;
minRows?: number;
maxRows?: number;
type?: React.HTMLInputTypeAttribute;
}): React.ReactElement {
if (((!p.editable && p.value) ?? "") === "") return <></>;
return (
<TextField
label={p.label}
value={p.value}
onChange={(e) =>
p.onValueChange?.(
e.target.value.length === 0 ? undefined : e.target.value
)
}
inputProps={{
maxLength: p.size?.max,
}}
InputProps={{
readOnly: !p.editable,
type: p.type,
}}
variant={p.editable ? "standard" : "standard"}
style={{ width: "100%", marginBottom: "15px" }}
multiline={p.multiline}
minRows={p.minRows}
maxRows={p.maxRows}
error={
(p.checkValue &&
p.value &&
p.value.length > 0 &&
!p.checkValue(p.value)) ||
false
}
/>
);
}