Files
rust-discovery/web/src/device-hypervisor.tsx
T

120 lines
5.3 KiB
TypeScript

import { useEffect, useState } from 'react';
import { ApiError, record, request, tenantPath, type RecordValue, type Session } from './api';
import { NavIcon } from './navigation';
import { ErrorBox, errorText, useResource } from './resource';
type Host = { asset_id: string; agent_id: string; hostname: string };
function host(value: unknown): Host | null {
if (!value || typeof value !== 'object' || Array.isArray(value)) return null;
const row = record(value);
const { asset_id, agent_id, hostname } = row;
return typeof asset_id === 'string' && typeof agent_id === 'string' && typeof hostname === 'string'
? { asset_id, agent_id, hostname }
: null;
}
export function HypervisorLabel({ device }: { device: RecordValue }) {
if (device.device_type !== 'virtual' || !device.hypervisor) return null;
const info = record(device.hypervisor);
if (info.kind === 'device') {
const target = host(info);
if (!target || typeof device.tenant_id !== 'string') return null;
const path = ['geraete', device.tenant_id, target.asset_id, target.agent_id].map(encodeURIComponent).join('/');
return <span className="vm-hypervisor">
<NavIcon name="geraete" /><span>Hypervisor <a href={'#' + path} onClick={event => event.stopPropagation()}>
{target.hostname}
</a></span>
</span>;
}
return info.kind === 'placeholder' && info.provider === 'hetzner' ? (
<span className="vm-hypervisor">
<NavIcon name="geraete" /><span>Hypervisor <strong>Hetzner Cloud</strong> <span className="muted">· Platzhalter</span></span>
</span>
) : null;
}
function assignmentError(e: unknown) {
if (e instanceof ApiError) {
if (e.code === 'HYPERVISOR_UNAVAILABLE') return 'Dieser Hypervisor ist im Kundenbestand derzeit nicht verfügbar.';
if (e.code === 'HYPERVISOR_REQUIRES_VM') return 'Die Installation meldet sich derzeit als anderer Gerätetyp.';
if (e.code === 'NOT_FOUND') return 'Diese VM-Kopplung ist nicht mehr im Bestand.';
}
return errorText(e);
}
export function HypervisorAssignment({ device, customer, asset, agent, auth }: {
device: RecordValue; customer: string; asset: string; agent: string; auth: Session;
}) {
const [open, setOpen] = useState(false);
const [search, setSearch] = useState('');
const [query, setQuery] = useState('');
const [draft, setDraft] = useState<string | null>(null);
const [busy, setBusy] = useState(false);
const [notice, setNotice] = useState('');
const [error, setError] = useState<string | null>(null);
const assigned = typeof device.assigned_hypervisor_asset_id === 'string' ? device.assigned_hypervisor_asset_id : '';
const value = draft ?? assigned;
useEffect(() => {
const timer = setTimeout(() => setQuery(search.trim()), 220);
return () => clearTimeout(timer);
}, [search]);
const options = useResource(async signal => {
if (!open) return null;
const data = record(await request(tenantPath(customer, '/hypervisors?q=' + encodeURIComponent(query)),
{ tenantId: customer, signal }));
if (!Array.isArray(data.items)) throw new Error('Die Hypervisor-Liste konnte nicht gelesen werden.');
return { hosts: data.items.map(host).filter((item): item is Host => item !== null), truncated: data.truncated === true };
}, [customer, open, query]);
const assignedHost = host(device.hypervisor);
const hosts = options.data?.hosts ?? [];
const selectedMissing = !!value && !hosts.some(item => item.asset_id === value);
const canSave = value !== assigned && (!value || !selectedMissing);
return <details onToggle={e => {
setOpen(e.currentTarget.open);
if (!e.currentTarget.open) {
setDraft(null);
setSearch('');
setNotice('');
setError(null);
}
}}>
<summary>Hypervisor zuordnen</summary>
{open && <form onSubmit={async e => {
e.preventDefault();
if (!canSave || busy) return;
setBusy(true);
setError(null);
setNotice('');
try {
await request(tenantPath(customer, '/devices/' + encodeURIComponent(asset) + '/hypervisor?agent_id=' + encodeURIComponent(agent)), {
tenantId: customer, csrf: auth.csrf_token, body: { hypervisor_asset_id: value || null }
});
setNotice(value ? 'Hypervisor zugeordnet.' : 'Hostzuordnung entfernt.');
} catch (e) {
setError(assignmentError(e));
} finally {
setBusy(false);
}
}}>
<label>Hypervisor suchen<input type="search" maxLength={120} value={search}
onChange={e => setSearch(e.target.value)} /></label>
<ErrorBox error={error ?? options.error} />
{options.data?.truncated && <p className="muted">Weitere Hypervisoren lassen sich über die Suche finden.</p>}
<label>Hypervisor auswählen<select aria-label="Hypervisor auswählen" value={value}
onChange={e => { setDraft(e.target.value); setNotice(''); setError(null); }} disabled={busy}>
<option value="">Kein konkreter Hypervisor</option>
{selectedMissing && <option value={value} disabled>
{assignedHost?.asset_id === value ? assignedHost.hostname : 'Zugeordneter Host außerhalb der Treffer'}
</option>}
{hosts.map(item => <option key={item.asset_id} value={item.asset_id}>{item.hostname}</option>)}
</select></label>
<button className="primary" disabled={busy || !canSave}>Zuordnung speichern</button>
{notice && <p role="status">{notice}</p>}
</form>}
</details>;
}