Files
rust-discovery/web/src/devices.tsx
T
kevin_janssenandClaude Fable 5.2 e29257b808
Rust development slice / linux (push) Failing after 7s
Group the device overview by hypervisor, Hetzner, physical and unassigned devices
Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-20 22:57:02 +01:00

902 lines
36 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import { useEffect, useState } from 'react';
import {
ApiError,
objectId,
page,
pretty,
record,
request,
session,
tenantPath,
type RecordValue,
type Session,
type Tenant
} from './api';
import { AdminControl } from './management';
import { allowed } from './safety';
import { CatalogCheckNotice } from './catalog-check';
import { devicePlatform } from './script-catalog';
import { DeviceInventoryPanels, systemDetails } from './device-inventory';
import { OPNsenseDetails } from './opnsense';
import { ProxmoxDetails } from './proxmox';
import { DeviceCustomerTransfer } from './device-customer-transfer';
import { HypervisorAssignment, HypervisorLabel } from './device-hypervisor';
import { groupDevices, type FleetGroup, type RowRole } from './device-groups';
import { ErrorBox, errorText, useResource } from './resource';
import { NavIcon, orderDetailRoute } from './navigation';
import { orderTitle, Status } from './order-presentation';
import { RecoveryReview, recoveryAsset, recoveryTenant } from './recovery-review';
import { EchoProbeReview } from './echo-probe-review';
import { EchoCompletionReview } from './echo-completion-review';
import { SyncAlignmentReview } from './sync-alignment-review';
import { SystemNonstartReview } from './system-nonstart-review';
const unknown = 'Nicht gemeldet';
const noPurpose = 'Nicht hinterlegt';
const plural = (n: number, one: string, many: string) => `${n} ${n === 1 ? one : many}`;
function groupName(group: FleetGroup) {
return group.kind === 'hypervisor' ? 'Hypervisor ' + (group.title || 'unbekannt')
: group.kind === 'hetzner' ? 'Hetzner Cloud'
: group.kind === 'physical' ? 'Physische Geräte' : 'Nicht zugeordnet';
}
/** How a listed virtual machine got its place under a registered hypervisor. */
function linkSource(d: RecordValue) {
if (!d.hypervisor || typeof d.hypervisor !== 'object') return '';
const info = record(d.hypervisor);
return info.kind !== 'device' ? '' : info.source === 'proxmox' ? 'automatisch erkannt' : 'manuell zugeordnet';
}
function GroupHeader({ group, showCustomer }: { group: FleetGroup; showCustomer: boolean }) {
const guests = group.rows.filter((r) => r.role !== 'host').length;
const machines = plural(guests, 'virtuelle Maschine', 'virtuelle Maschinen');
const [icon, eyebrow, title, facts] =
group.kind === 'hypervisor'
? (['server', 'Hypervisor',
group.hostPath ? <a href={'#' + group.hostPath}>{group.title || 'Unbekannter Host'}</a> : group.title || 'Unbekannter Host',
[guests ? machines : 'Keine zugeordneten virtuellen Maschinen',
!group.hostListed && 'Host in dieser Ansicht nicht enthalten',
showCustomer && group.customer]] as const)
: group.kind === 'hetzner'
? (['cloud', 'Externer Anbieter', 'Hetzner Cloud', [machines, 'Platzhalter, kein Gerät im Bestand']] as const)
: group.kind === 'physical'
? (['geraete', 'Eigene Hardware', 'Physische Geräte', [plural(guests, 'Gerät', 'Geräte')]] as const)
: (['offen', 'Ohne Zuordnung', 'Nicht zugeordnet',
[plural(guests, 'Gerät', 'Geräte'), 'kein Hypervisor oder Gerätetyp erkannt']] as const);
return (
<div className="fleet-group-head">
<span className="group-icon"><NavIcon name={icon} /></span>
<div>
<span className="group-eyebrow">{eyebrow}</span>
<strong>{title}</strong>
</div>
<p>{facts.filter(Boolean).map((fact, i) => <span key={i}>{fact}</span>)}</p>
</div>
);
}
const number = new Intl.NumberFormat('de-DE', { maximumFractionDigits: 1 });
const date = new Intl.DateTimeFormat('de-DE', { dateStyle: 'medium', timeStyle: 'short' });
function label(value: unknown) {
return typeof value === 'string' && value.trim() ? value : unknown;
}
function time(value: unknown) {
const t = typeof value === 'string' ? Date.parse(value) : NaN;
return Number.isFinite(t) ? date.format(t) : unknown;
}
function gib(v: unknown) {
return typeof v === 'number' && Number.isFinite(v) && v >= 0 ? number.format(v / 2 ** 30) : null;
}
function capacity(free: unknown, total: unknown) {
if (typeof total !== 'number' || !Number.isFinite(total) || total <= 0)
return { text: unknown, usedPercent: null };
const used = typeof free === 'number' && free >= 0 && free <= total ? total - free : null;
return {
text: `${gib(used) ?? '–'} / ${gib(total)} GiB`,
usedPercent: used === null ? null : (used / total) * 100
};
}
function cpuUsage(value: unknown) {
return typeof value === 'number' && Number.isFinite(value) && value >= 0 && value <= 100
? `${number.format(value)} %`
: unknown;
}
function measuredAt(value: unknown) {
const observed = time(value);
return observed === unknown ? undefined : `Gemessen am ${observed}`;
}
function cpu(d: RecordValue) {
const model = label(d.cpu_model),
count = d.cpu_logical_count;
const threads =
typeof count === 'number' && count > 0 ? `${count} log. CPU${count === 1 ? '' : 's'}` : '';
return {
primary: model === unknown ? threads || unknown : model,
secondary: model === unknown ? '' : threads
};
}
const states: Record<string, string> = {
online: 'Online',
offline: 'Offline',
never_seen: 'Ohne Erstkontakt',
revoked: 'Widerrufen',
archived: 'Archiviert',
replaced: 'Ersetzt',
unverified: 'Identität unbestätigt'
};
function Presence({ d }: { d: RecordValue }) {
const state =
typeof d.lifecycle === 'string' && d.lifecycle !== 'current' ? d.lifecycle : String(d.status);
return (
<span
className={
'presence ' + (state === 'online' ? 'online' : state === 'offline' ? 'offline' : 'historic')
}
>
<i />
{states[state] ?? 'Unbekannt'}
</span>
);
}
function Capacity({ free, total }: {
free: unknown;
total: unknown;
}) {
const { text, usedPercent } = capacity(free, total);
const displayUsed = usedPercent === null ? null : Math.round(usedPercent * 10) / 10;
const usedLabel = displayUsed === null ? '' : `${number.format(displayUsed)} % belegt`;
const breakdown = displayUsed === null ? '' : `${usedLabel}, ${number.format(100 - displayUsed)} % frei`;
return (
<>
<span>{text}</span>
{usedPercent !== null && (
<>
<span className="capacity-track" role="img"
aria-label={breakdown} title={breakdown}>
<span className="capacity-used" style={{ width: `${usedPercent}%` }} />
<span className="capacity-free" />
</span>
<small className="capacity-caption" aria-hidden="true">{usedLabel}</small>
</>
)}
</>
);
}
function LinuxDisk({ disk, groups }: { disk: RecordValue; groups: string[] }) {
const { used_bytes: used, available_bytes: free, total_bytes: total } = disk;
const size = typeof total === 'number' && Number.isFinite(total) && total > 0 ? total : null;
const valid = size !== null && typeof used === 'number' && used >= 0 && typeof free === 'number' && free >= 0 && used + free <= size;
const usedPct = valid ? used / size * 100 : 0, freePct = valid ? free / size * 100 : 0;
const summary = valid ? `${number.format(usedPct)} % belegt, ${number.format(freePct)} % frei, ${number.format(Math.max(0,100-usedPct-freePct))} % nicht zugeordnet` : 'Belegung nicht ermittelbar';
const group = disk.kind === 'group';
return <div className="drive-capacity">
<strong>{group ? 'Verbund: ' : ''}{label(disk.name)}</strong>
{typeof disk.model === 'string' && <small>{disk.model}</small>}
{group && Array.isArray(disk.members) && disk.members.length > 0 && <small>{disk.members.filter(v => typeof v === 'string').join(', ')}</small>}
{!group && groups.length > 0 && <small>Im Verbund: {groups.join(', ')}</small>}
<div>{size === null ? 'Größe nicht gemeldet' : `${valid ? gib(used) : '–'} / ${gib(size)} GiB`}</div>
{size !== null && <span className="capacity-track disk-track" role="img" aria-label={summary} title={summary}>
<span className="capacity-used" style={{width:`${usedPct}%`}} />
<span className="capacity-free" style={{width:`${freePct}%`}} />
</span>}
<small>{valid ? `${number.format(usedPct)} % belegt` : summary}</small>
</div>;
}
function DiskCapacity({ device }: { device: RecordValue }) {
if ('disks' in device) {
const disks = Array.isArray(device.disks) ? device.disks.filter(d => d && typeof d === 'object' && ['disk','group'].includes(d.kind) && typeof d.name === 'string') : [];
return <>{disks.length ? disks.map((disk,i) => <LinuxDisk key={`${disk.kind}/${disk.name}/${i}`} disk={disk}
groups={disk.kind === 'disk' ? disks.filter(g => g.kind === 'group' && Array.isArray(g.members) && g.members.includes(disk.name)).map(g => g.name) : []}/>) :
<small>Keine Festplatten gemeldet</small>}
{device.disks_truncated === true && <small>Liste gekürzt</small>}</>;
}
// Only Windows fleet rows use drive letters. Linux mount inventories remain
// available in the detail view, without expanding every fleet row.
const drives = Array.isArray(device.volumes)
? device.volumes.map(v => record(v)).filter(v => typeof v.name === 'string' && /^[A-Z]:$/.test(v.name)) : [];
if (!drives.length) return <>{device.source_id === 'linux.base' && <small>Root-Dateisystem /</small>}
<Capacity free={device.disk_free_bytes} total={device.disk_total_bytes} /></>;
return <>{drives.map(drive => (
<div className="drive-capacity" key={String(drive.name)}>
<strong>{String(drive.name)}</strong>{' '}<Capacity free={drive.free_bytes} total={drive.total_bytes} />
</div>
))}</>;
}
type Target = { customer: string; ids: string[] };
type Props = {
detailPath: string;
auth: Session;
customers: Tenant[];
filter: string;
onFilter: (id: string) => void;
selection: Target;
onSelection: (s: Target) => void;
onCreateOrder: () => void;
onEnroll: () => void;
onOperation: (customer: string, id: string, jobId: string) => void;
};
function devicePath(customer: string, asset: string) {
return tenantPath(customer, '/devices/' + encodeURIComponent(asset));
}
function DevicePurpose({ value, path, customer, editor, success, onSaved }: {
value: string;
path: string;
customer: string;
editor: Session | null;
success: boolean;
onSaved: () => void;
}) {
const [draft, setDraft] = useState<string | null>(null);
const [busy, setBusy] = useState(false);
const [error, setError] = useState<string | null>(null);
const tooLong = Array.from(draft?.trim() ?? '').length > 500;
const close = () => { setDraft(null); setError(null); };
return (
<section className="device-purpose">
<h2>Zweck</h2>
{editor && draft !== null ? (
<form onSubmit={async (e) => {
e.preventDefault();
if (busy || tooLong) return;
setBusy(true);
setError(null);
try {
await request(path + '/purpose', {
method: 'PATCH', tenantId: customer, csrf: editor.csrf_token, body: { purpose: draft }
});
close();
onSaved();
} catch (e) {
setError(errorText(e));
} finally {
setBusy(false);
}
}}>
<label>
Zweck des Geräts
<textarea autoFocus rows={3} value={draft} disabled={busy}
aria-describedby="device-purpose-help" aria-invalid={tooLong}
onChange={(e) => setDraft(e.target.value)} />
</label>
<p id="device-purpose-help" className={tooLong ? 'error' : 'muted'}>
{tooLong ? 'Der Zweck ist zu lang. ' : ''}Maximal 500 Zeichen. Zum Entfernen das Feld leeren.
</p>
<ErrorBox error={error} />
<button type="submit" disabled={busy || tooLong}>{busy ? 'Speichert …' : 'Zweck speichern'}</button>{' '}
<button type="button" className="quiet" disabled={busy} onClick={close}>Abbrechen</button>
</form>
) : (
<>
<p className={'purpose-text' + (value ? '' : ' muted')}>{value || noPurpose}</p>
{editor && <button className="quiet" onClick={() => setDraft(value)}>Zweck bearbeiten</button>}
{success && <p role="status">Zweck gespeichert.</p>}
</>
)}
</section>
);
}
function reportedScriptProfiles(device: RecordValue) {
const os = devicePlatform(device);
if (!os || !Array.isArray(device.capabilities)) return 'Nicht gemeldet';
const caps = new Set(device.capabilities);
if (!caps.has('run_script')) return 'Nicht gemeldet';
const windows = os === 'windows';
const identity = windows ? 'system' : 'root';
const service = os==='opnsense' && !caps.has('opnsense.posix/1') ? 'Kernelabfrage als Dienstkonto' : windows ? 'PowerShell als Dienstkonto' : 'Shell als Dienstkonto';
if (!caps.has(os + '.base/1') || caps.has(windows ? 'linux.base/1' : 'windows.base/1')) return 'Nicht gemeldet';
if (windows && !['rmm.sync.v1', 'script.powershell/1', 'script.powershell.process_remote_signed/1'].every(cap => caps.has(cap)))
return 'Nicht gemeldet';
const admin = ['rmm.sync.v1', 'script.full_maintenance/1', 'helper.' + identity + '.v1', identity + ':run_script']
.every(capability => caps.has(capability));
return admin ? service + ' und als Administrator (' + (windows ? 'SYSTEM' : 'root') + ')' : service;
}
function DeviceDetail({
customer,
asset,
agent,
auth,
customers,
back,
openOperation,
changed
}: {
customer: string;
asset: string;
agent: string;
auth: Session;
customers: Tenant[];
back: () => void;
openOperation: (id: string, jobId: string) => void;
changed: (notice?: string) => void;
}) {
const path = devicePath(customer, asset);
const detail = useResource(
async (signal) => record(await request(path + '?agent_id=' + encodeURIComponent(agent), { signal })),
[customer, asset, agent],
true
);
const membership = useResource(
async (signal) => session(await request('/auth/session', { signal, tenantId: customer })),
[customer, auth.principal.id]
);
const [busy, setBusy] = useState(false),
[error, setError] = useState<string | null>(null);
const [confirmDelete, setConfirmDelete] = useState(false);
const [managing, setManaging] = useState(false);
const [purposeSaved, setPurposeSaved] = useState(false);
const d = detail.data;
const scoped = membership.data;
const volumes = Array.isArray(d?.volumes) ? d.volumes.map((v) => record(v)) : [];
const jobs = Array.isArray(d?.recent_jobs) ? d.recent_jobs.map((v) => record(v)) : null;
const facts = d && [
['Kunde', label(d.customer_name)],
['Type', label(d.device_type)],
['Betriebssystem', label(d.os)],
...systemDetails(d, time),
['RAM belegt / gesamt', capacity(d.ram_available_bytes, d.ram_total_bytes).text],
['CPU', [cpu(d).primary, cpu(d).secondary].filter(Boolean).join(' · ')],
['CPU-Auslastung', [cpuUsage(d.cpu_usage_percent), measuredAt(d.cpu_usage_observed_at)].filter(Boolean).join(' · ')],
['Speicher belegt / gesamt', capacity(d.disk_free_bytes, d.disk_total_bytes).text],
['Letzter Kontakt', time(d.last_contact_at)],
['Inventar erhoben', time(d.observed_at)],
['Agentversion', label(d.agent_version)],
['Vom Agenten gemeldete Skriptausführung', reportedScriptProfiles(d)]
];
return (
<div className="device-detail">
<button className="quiet" onClick={back}>
<NavIcon name="zurueck" /> Zur Geräteliste
</button>
<ErrorBox error={detail.error ?? membership.error} />
{!d && !detail.error && <p>Inventar wird geladen …</p>}
{d && (
<>
<div className="page-title">
<div>
<h1>{label(d.hostname)}</h1>
<Presence d={d} />
<HypervisorLabel device={d} />
</div>
</div>
<section>
<h2>Geräteinformationen</h2>
<dl className="facts">
{facts?.map(([k, v]) => (
<div key={k}>
<dt>{k}</dt>
<dd>{v}</dd>
</div>
))}
</dl>
</section>
<DevicePurpose
value={typeof d.purpose === 'string' ? d.purpose : ''}
path={path}
customer={customer}
editor={scoped && allowed(scoped, 'devices:revoke') && allowed(scoped, 'inventory:read') ? scoped : null}
success={purposeSaved}
onSaved={() => { setPurposeSaved(true); detail.reload(); }}
/>
<OPNsenseDetails device={d} />
<ProxmoxDetails device={d} />
<DeviceInventoryPanels device={d} />
{volumes.length > 0 && (
<section>
<h2>Laufwerke</h2>
<div className="table">
<table>
<thead>
<tr>
<th>Laufwerk</th>
<th>Speicher belegt / gesamt</th>
</tr>
</thead>
<tbody>
{volumes.map((v, i) => (
<tr key={i}>
<td>{label(v.name)}</td>
<td>{capacity(v.free_bytes, v.total_bytes).text}</td>
</tr>
))}
</tbody>
</table>
</div>
</section>
)}
{jobs && (
<section>
<h2>Letzte Aufträge</h2>
{jobs.length === 0 ? (
<p className="muted">Keine Aufträge für dieses Gerät.</p>
) : (
<ul className="job-list">
{jobs.map((job) => {
const id = objectId(job, 'operation'), jobId = objectId(job, 'job');
const title = orderTitle(job);
return <li className="job-row" key={jobId}>
<div className="device-job-name"><strong>{title}</strong><small>{time(job.created_at)}</small></div>
<Status value={job.state}/>
<a className="quiet" href={'#auftraege/' + orderDetailRoute(customer, id, jobId)}
aria-label={'Ergebnis öffnen · ' + title + ' · ' + time(job.created_at)}
onClick={event => {
if (event.ctrlKey || event.metaKey || event.shiftKey || event.altKey) return;
event.preventDefault();
openOperation(id, jobId);
}}>Ergebnis öffnen</a>
</li>;
})}
</ul>
)}
</section>
)}
<section>
<details>
<summary>Technische Daten</summary>
<CatalogCheckNotice device={d} />
<pre aria-label="Vollständiges Geräteinventar">{pretty(d)}</pre>
</details>
{scoped && allowed(scoped, 'devices:revoke') &&
d.tenant_id === customer && d.asset_id === asset && d.agent_id === agent && (
<details open={managing} onToggle={e => setManaging(e.currentTarget.open)}>
<summary>Gerät verwalten</summary>
<ErrorBox error={error} />
{d.device_type === 'virtual' && d.lifecycle === 'current' &&
<HypervisorAssignment device={d} customer={customer} asset={asset} agent={agent} auth={scoped} />}
<DeviceCustomerTransfer auth={scoped} customer={customer} asset={asset} agent={agent}
customers={customers} active={d.lifecycle === 'current'}
supported={Array.isArray(d.capabilities) && d.capabilities.includes('device.customer_transfer/1')} />
{['archived', 'current'].includes(String(d.lifecycle)) && (
<button
disabled={busy}
onClick={async () => {
setBusy(true);
setError(null);
try {
await request(path + '/archive', {
csrf: scoped.csrf_token,
body: { archived: d.lifecycle !== 'archived' }
});
changed();
} catch (e) {
setError(errorText(e));
} finally {
setBusy(false);
}
}}
>
{d.lifecycle === 'archived'
? 'Zurück in den Bestand'
: 'In die Historie verschieben'}
</button>
)}
{d.lifecycle !== 'revoked' && (
<AdminControl
auth={scoped}
path={path + '/revocation?agent_id=' + encodeURIComponent(agent)}
permission="devices:revoke"
title="Geräteidentität widerrufen"
warning="Der Widerruf unterbricht die Geräteverwaltung und sperrt neue Starts. Danach können Sie diese Kopplung endgültig löschen. Eine Wiederaufnahme erfordert eine neue Registrierung."
done={detail.reload}
/>
)}
{d.lifecycle === 'revoked' && (confirmDelete ? (
<div>
<p className="warning">
Die Kopplung von <strong>{label(d.hostname)}</strong> bei <strong>{label(d.customer_name)}</strong>
{' '}wird mit ihrem Inventar und ihren Geräteergebnissen dauerhaft gelöscht.
Andere Installationen bleiben erhalten.
</p>
<p>Kopplungs-ID <code>{agent}</code></p>
<button className="danger" disabled={busy} onClick={async () => {
setBusy(true);
setError(null);
try {
await request(path + '?agent_id=' + encodeURIComponent(agent), {
method: 'DELETE', csrf: scoped.csrf_token, tenantId: customer
});
changed(`Kopplung von „${label(d.hostname)}“ bei „${label(d.customer_name)}“ gelöscht.`);
} catch (e) {
if (e instanceof ApiError && e.code === 'DEVICE_HAS_OPEN_WORK') {
setError('Für diese Kopplung gibt es offene Aufträge oder Genehmigungen. Prüfen Sie diese vor dem Löschen.');
} else if (e instanceof ApiError && e.code === 'DEVICE_REVOCATION_REQUIRED') {
setError('Widerrufen Sie diese Geräteidentität vor dem Löschen.');
} else {
setError(errorText(e));
}
} finally {
setBusy(false);
}
}}>Endgültig löschen</button>
<button className="quiet" disabled={busy} onClick={() => {
setConfirmDelete(false);
setError(null);
}}>Abbrechen</button>
</div>
) : (
<button className="danger" onClick={() => setConfirmDelete(true)}>Kopplung löschen</button>
))}
</details>
)}
</section>
{scoped?.principal.simulated &&
customer === recoveryTenant &&
asset === recoveryAsset &&
allowed(scoped, 'inventory:read') && (
<details>
<summary>Entwicklungsabnahmen</summary>
<SystemNonstartReview auth={scoped} />
<SyncAlignmentReview auth={scoped} />
<EchoProbeReview auth={scoped} />
<EchoCompletionReview auth={scoped} />
<RecoveryReview auth={scoped} />
</details>
)}
</>
)}
</div>
);
}
export function Devices({
detailPath,
auth,
customers,
filter,
onFilter,
selection,
onSelection,
onEnroll,
onCreateOrder,
onOperation
}: Props) {
const [search, setSearch] = useState(''),
[query, setQuery] = useState(''),
[status, setStatus] = useState(''),
[history, setHistory] = useState(false);
const [deletionNotice, setDeletionNotice] = useState('');
const [trail, setTrail] = useState<{ filter: string; routes: string[] }>({ filter, routes: [] });
const routes = trail.filter === filter ? trail.routes : [];
function setRoutes(next: string[] | ((old: string[]) => string[])) {
setTrail(old => ({ filter, routes: typeof next === 'function' ? next(old.filter === filter ? old.routes : []) : next }));
}
const [customerId, assetId, agentId] = detailPath.split('/');
const target =
customerId && assetId && agentId ? { customer: customerId, asset: assetId, agent: agentId } : null;
const back = () => {
window.location.hash = 'geraete';
};
const cursor = routes[routes.length - 1];
useEffect(() => {
const timer = setTimeout(() => {
setQuery(search.trim());
setRoutes([]);
}, 200);
return () => clearTimeout(timer);
}, [search]);
useEffect(() => setTrail({ filter, routes: [] }), [filter]);
const list = useResource(
async (signal) => {
if (target) return null;
const params = new URLSearchParams({ view: history ? 'history' : 'current', limit: '40' });
if (query) params.set('q', query);
if (status && !history) params.set('status', status);
if (cursor) params.set('cursor', cursor);
const path = filter ? tenantPath(filter, '/devices') : '/api/v1/devices';
return page(await request(path + '?' + params, { signal }));
},
[filter, query, history, status, cursor, detailPath],
true
);
function setView(historic: boolean) {
setRoutes([]);
setHistory(historic);
onSelection({ customer: '', ids: [] });
}
function select(d: RecordValue, checked: boolean) {
const asset = objectId(d, 'asset'),
customer = objectId(d, 'tenant');
if (checked && selection.ids.length && customer !== selection.customer) return;
const ids = checked ? [...selection.ids, asset] : selection.ids.filter((id) => id !== asset);
onSelection({ customer: ids.length ? customer : '', ids });
}
if (target)
return (
<DeviceDetail
key={detailPath}
{...target}
auth={auth}
customers={customers}
back={back}
openOperation={(id, jobId) => onOperation(target.customer, id, jobId)}
changed={(notice) => {
setDeletionNotice(notice ?? '');
back();
setRoutes([]);
onSelection({ customer: '', ids: [] });
list.reload();
}}
/>
);
const columns = ['Hostname', 'Type', 'Zweck', 'OS', 'Status', 'Speicher belegt / gesamt', 'RAM belegt / gesamt', 'CPU', 'Kunde'];
const row = (d: RecordValue, role: RowRole | 'flat') => {
const asset = objectId(d, 'asset'),
agent = objectId(d, 'agent'),
customer = objectId(d, 'tenant'),
model = cpu(d),
purpose = typeof d.purpose === 'string' ? d.purpose : '';
const show = () => {
setDeletionNotice('');
window.location.hash = ['geraete', customer, asset, agent]
.map(encodeURIComponent)
.join('/');
};
const another = selection.ids.length > 0 && selection.customer !== customer;
return (
<tr key={agent} onClick={show} className={role === 'flat' ? undefined : role}>
{!history && (
<td className="target-col" onClick={(e) => e.stopPropagation()}>
<input
type="checkbox"
aria-label={'Ziel ' + asset}
title={
another ? 'Aufträge werden je Kunde geplant' : 'Für Auftrag auswählen'
}
disabled={another}
checked={selection.customer === customer && selection.ids.includes(asset)}
onChange={(e) => select(d, e.target.checked)}
/>
</td>
)}
<td className="hostname">
<button
className="host-link"
onClick={(e) => {
e.stopPropagation();
show();
}}
>
{label(d.hostname)}
</button>
{role === 'flat' && <HypervisorLabel device={d} />}
{role === 'guest' && linkSource(d) && <small className="link-source">{linkSource(d)}</small>}
</td>
<td data-label="Type">{label(d.device_type)}</td>
<td data-label="Zweck" className="purpose-col">
<span className={'purpose-text' + (purpose ? '' : ' muted')} title={purpose || undefined}>
{purpose || noPurpose}
</span>
</td>
<td data-label="OS">{label(d.os)}</td>
<td data-label="Status" className="device-presence">
<Presence d={d} />
{d.status === 'offline' && d.lifecycle === 'current' && (
<small>Zuletzt {time(d.last_contact_at)}</small>
)}
</td>
<td data-label="Speicher belegt / gesamt" className="capacity-cell">
<DiskCapacity device={d} />
</td>
<td data-label="RAM belegt / gesamt" className="capacity-cell" title={measuredAt(d.ram_observed_at)}>
<Capacity free={d.ram_available_bytes} total={d.ram_total_bytes} />
</td>
<td data-label="CPU">
{model.primary}
{model.secondary && <small>{model.secondary}</small>}
<small title={measuredAt(d.cpu_usage_observed_at)}>
Auslastung {cpuUsage(d.cpu_usage_percent)}
</small>
</td>
<td data-label="Kunde">{label(d.customer_name)}</td>
</tr>
);
};
/** Every block shares these column widths, so the blocks line up under one heading. */
const table = (rows: { device: RecordValue; role: RowRole | 'flat' }[], heading: 'visible' | 'hidden' | 'only') => (
<div className={'table fleet-table' + (heading === 'only' ? ' fleet-head' : '')} aria-hidden={heading === 'only' || undefined}>
<table>
<colgroup>
{!history && <col className="target-col" />}
{columns.map((h) => <col key={h} className={h === 'Zweck' ? 'purpose-col' : h === 'Hostname' ? 'host-col' : undefined} />)}
</colgroup>
<thead className={heading === 'hidden' ? 'sr-only' : undefined}>
<tr>
{!history && (
<th className="target-col">
<span className="sr-only">Ziel auswählen</span>
</th>
)}
{columns.map((h) => (
<th scope="col" key={h} className={h === 'Zweck' ? 'purpose-col' : undefined}>
{h}
</th>
))}
</tr>
</thead>
{heading !== 'only' && <tbody>{rows.map((r) => row(r.device, r.role))}</tbody>}
</table>
</div>
);
return (
<>
<div className="page-title">
<div>
<h1>Geräte</h1>
</div>
{allowed(auth, 'devices:enroll') && (
<button className="primary" onClick={onEnroll}>
<NavIcon name="plus" /> Gerät aufnehmen
</button>
)}
</div>
{deletionNotice && <p role="status">{deletionNotice}</p>}
<section className="fleet" aria-label="Gerätebestand">
<div className="fleet-tabs">
<button
aria-pressed={!history}
onClick={() => {
if (history) setView(false);
}}
>
Bestand
</button>
<button
aria-pressed={history}
onClick={() => {
if (!history) setView(true);
}}
>
Historie
</button>
</div>
<div className="filters">
<label className="search-box">
<span className="sr-only">Hostname suchen</span>
<NavIcon name="suchen" />
<input
type="search"
placeholder="Hostname suchen …"
maxLength={120}
value={search}
onChange={(e) => setSearch(e.target.value)}
/>
</label>
<label>
<span>Kunde im Gerätebestand</span>
<select
aria-label="Kunde im Gerätebestand"
value={filter}
onChange={(e) => {
setRoutes([]);
onFilter(e.target.value);
}}
>
<option value="">Alle Kunden</option>
{customers.map((c) => (
<option value={c.tenant_id} key={c.tenant_id}>
{c.name}
</option>
))}
</select>
</label>
{!history && (
<label>
<span>Status</span>
<select
aria-label="Status"
value={status}
onChange={(e) => {
setRoutes([]);
setStatus(e.target.value);
}}
>
<option value="">Jeder Status</option>
<option value="online">Online</option>
<option value="offline">Offline</option>
</select>
</label>
)}
</div>
<ErrorBox error={list.error} />
{history && (
<p className="history-hint">
Ausgemusterte Geräte und Registrierungen ohne bestätigte Identität.
</p>
)}
{!list.data && !list.error && <p className="list-message">Geräte werden geladen …</p>}
{list.data && (
<>
{history ? (
table(list.data.items.map((device) => ({ device, role: 'flat' as const })), 'visible')
) : (
!!list.data.items.length && (
<div className="fleet-groups">
{table([], 'only')}
{groupDevices(list.data.items).map((group) => (
<div className={'fleet-group ' + group.kind} role="group" aria-label={groupName(group)} key={group.key}>
<GroupHeader group={group} showCustomer={!filter} />
{table(group.rows, 'hidden')}
</div>
))}
</div>
)
)}
{!list.data.items.length && (
<div className="empty-list">
<NavIcon name="geraete" />
<h3>
{query || filter || status
? 'Keine passenden Geräte'
: 'Keine Geräte in dieser Ansicht'}
</h3>
{(query || filter || status) && (
<button
className="quiet"
onClick={() => {
setSearch('');
setQuery('');
setRoutes([]);
setStatus('');
onFilter('');
}}
>
Filter zurücksetzen
</button>
)}
</div>
)}
<div className="list-footer">
<span>
{list.data.items.length} {list.data.items.length === 1 ? 'Gerät' : 'Geräte'}
{cursor || list.data.next_cursor ? ' auf dieser Seite' : ''} · Stand{' '}
{time(list.data.as_of)}
</span>
{(cursor || list.data.next_cursor) && (
<div>
<button
className="quiet"
disabled={!cursor}
onClick={() => setRoutes((old) => old.slice(0, -1))}
>
Zurück
</button>
<button
className="quiet"
disabled={!list.data.next_cursor}
onClick={() => {
const next = list.data?.next_cursor;
if (next) setRoutes((old) => [...old, next]);
}}
>
Weiter
</button>
</div>
)}
</div>
</>
)}
</section>
{!!selection.ids.length && (
<div className="selection">
<div>
<strong>
{selection.ids.length} {selection.ids.length === 1 ? 'Gerät' : 'Geräte'} ausgewählt
</strong>
<small>{customers.find((c) => c.tenant_id === selection.customer)?.name}</small>
</div>
<button className="quiet" onClick={() => onSelection({ customer: '', ids: [] })}>
Auswahl aufheben
</button>
<button disabled={!allowed(auth, 'operations:plan') || !allowed(auth, 'scripts:execute')} onClick={onCreateOrder}>Auftrag erstellen</button>
</div>
)}
</>
);
}