Hyper V Discovery Developer Guide - edmozley/freeitsm GitHub Wiki
How the virtual estate (#199 Parts A and B) is built, and the rules a change must keep. The user page is Hyper-V and Failover Cluster discovery; the reasoning is in the design.
In one breath: a read-only PowerShell collector pushes a report per scope. One service (VirtualEstateService) applies it to eleven virt_* tables (ten, plus virt_storage_volumes since 5.4.0), under the inventory ingest's rules: observed time, complete/partial sections, stale/replay/conflict, a savepoint per section, removal is not deletion. Identity changes are raised for a person. Each connection is a pushed source on job health. The tables are named for the estate, not Hyper-V, so vCenter, Proxmox and Cloud Director can move onto them, and Parts B and C are built once.
🗄️ schema · 🧠 rules · 🔌 REST · 🖥️ UI · 🩺 job health · 🪟 collector · 🧪 tests
| 🎨 | File | What it does there |
|---|---|---|
| 🗄️ |
database/freeitsm.sql, includes/db_verify_schema.php, includes/db_verify_indexes.php, api/system/db_verify.php, includes/db_verify_modules.php
|
Eleven virt_* tables; children cascade from virt_connections and virt_vms. virt_ maps to Assets |
| 🧠 | includes/services/virtual_estate.php |
submit(), the seven apply_*() sections (apply_storage_volumes() since 5.4.0), decideReview(), mintKey(), freshness(), storageReady(), storageInventory(), watch()
|
| 🩺 |
cron/virt_watch.php, includes/job_registry.php (virt_watch), includes/services/notifications.php (hyperv.collector), includes/entity_links.php (virt_connection) |
The collector watch (§9) |
| 🔌 |
api/v1/resources/virtual_estate.php, api/v1/lib/routes.php, api/v1/lib/permissions.php, api/v1/spec.json
|
POST /virtual-estate/{id}/reports (only the connection's api_key_id), GET /virtual-estate/{id}; permission virtual_estate
|
| 🖥️ |
api/assets/hyperv_connections.php, asset-management/settings/hyperv.js, asset-management/settings/index.php, asset-management/settings/manifest.php
|
Assets → Settings → Hyper-V (Cap::ASSETS_HYPERV, sensitive: it mints keys) |
| 🖥️ |
api/assets/get_servers.php, asset-management/servers/index.php
|
Hyper-V rows (scoped to the analyst's companies), the reports panel, hosts and clusters |
| 🩺 |
includes/job_registry.php (jobRegistryAll()), includes/job_health.php, includes/job_runs.php, api/reporting/job_health.php
|
One virt_push_<id> entry per active connection; trigger push
|
| 🪟 | scripts/Invoke-HyperVInventory.ps1 |
The collector |
| 🧪 | tests/virtual-estate.php |
47 checks - every scenario in criterion 7, REST key gating, job health |
| 🧪 |
tests/virtual-estate-storage.php, tests/virtual-estate-storage-browser.php
|
Storage (§8) and the watch (§9) on synthetic reports; the Servers storage panel in headless Chrome |
| 🧪 |
tests/hyperv-collector.php, tests/hyperv-collector/Mock-HyperV.ps1
|
The REAL collector against mocked cmdlets, its reports through the REAL ingest, and sending to the local API (Windows only) |
| 🧪 |
tests/virtual-estate-load.php, tests/fixtures/virtual-estate/synthetic.php
|
Sizing on the synthetic reference estates; the fixture generator |
| 📄 | samples/hyperv/ |
Fully synthetic example reports and their generator |
| Table | Identity (external_id) |
Notes |
|---|---|---|
virt_connections |
- | One company (tenant_id); api_key_id is the only key accepted; interval, grace, retention; stale_alerted_at (§9) |
virt_clusters |
Get-Cluster Id |
quorum type, witness; six storage_* columns (§8) |
virt_storage_volumes |
sha256 of cluster id, resource id, partition name |
one row per CSV partition (§8) |
virt_hosts |
hardware UUID, or name:<host>
|
identity_kind source / name; cluster_id; node_state
|
virt_cluster_roles |
Get-ClusterGroup Id |
owner host, preferred owners |
virt_vms |
Get-VM Id |
host, cluster, is_clustered (NULL = unknown), role, possible_owners_json (host row ids) |
virt_vm_disks, virt_vm_networks
|
per VM | replaced as a set by a complete section; observed_at guards against older reports |
virt_placements |
- | one open row per VM; a host change closes it and opens another |
virt_reports |
- | every report received and what each section came to |
virt_identity_reviews |
- | open → same / different / superseded |
Every discovered row carries first_seen_at, last_seen_observed_at, not_seen_since and not_confirmed_since.
submit(connection, report)
envelope(): schema_version 1, observed_at with a timezone (not in the future), scope, sections
scope_key = hash of the scope; fingerprint = hash of scope + sections + unreadable
newest applied report for this scope: newer -> stale | same time, same hash, applied -> replayed
same time, different hash -> 409 observation_conflict
same time, same hash, partial -> apply again (retries the failed sections)
JobRun::start('virt_push_<id>', 'push')
one transaction; per section a SAVEPOINT: clusters, hosts, cluster_roles, vms, vm_disks, vm_networks,
storage_volumes (optional; a SAVEPOINT per cluster inside it - §8)
markUnconfirmed() raiseIdentityReviews() purge() commit
record the report; connection's last_report_at, last_outcome, last_summary
200 applied | 207 partial | 422 failed
-
Upsert by
(connection_id, external_id), reading the connection's rows once per section (FOR UPDATE). An object last observed after this report is skipped (stale_objects), so an older report sent under a different scope can never wind it back. -
Complete marks not-seen, within scope only.
markNotSeen()limits itself to what the report's scope covers - its clusters, and the hosts in them or named as standalone - and skips anything on an unreadable host or cluster (onUnreadable()). -
Unreadable is "not confirmed", never "gone" (
markUnconfirmed()). - Hosts are referenced by NAME inside a report (a VM's host, a role's owner, possible owners), resolved per report against the hosts just applied. That is what lets a host rename keep its VMs.
-
Hardware UUIDs are checked: all-zero, all-F, malformed, or the same UUID on two hosts in one report →
name:identity. -
A bad item fails its section, rolled back to the savepoint, not skipped. Unknown VMs in
vm_disks/vm_networksfail the section rather than dropping data.
raiseIdentityReviews() pairs a row that is not seen with a live row of the same kind, same name (case-insensitive), first seen at or after the old one was last seen. For hosts, it also pairs two name-identity hosts in the same cluster. Raised once per pair.
decideReview(same) keeps the old row - its id, first seen and placements - and gives it the new identity and the new row's current facts. It moves the new row's disks, adapters, placements and anything pointing at it, then deletes the new row. It refuses (review_changed, case closed as superseded) if the old row is seen again or the new one goes before the decision.
jobRegistryAll($conn) = the scheduled jobs + one entry per active connection: key virt_push_<id>, 'pushed' => true, interval and grace from the connection, its own name (name_params). Runs are recorded by submit() with trigger push, and the freshness rule counts push beside cron and web. An unreadable host makes the run partial.
If the connections table cannot be read, health shows a Pushed sources: unknown entry, never silence.
Windows PowerShell 5.1 syntax throughout (no ??, no ternary). It only calls Get-* and CIM reads. Per cluster it reads Get-Cluster, Get-ClusterQuorum, Get-ClusterNode and Get-ClusterGroup. For each "Virtual Machine" resource it reads VmID (Get-ClusterParameter) and its possible owners (Get-ClusterOwnerNode). Per host it reads the UUID (Win32_ComputerSystemProduct), the OS, Get-VMHost, Get-VM, disks (Get-VMHardDiskDrive + Get-VHD) and adapters (+ VLAN). A host or cluster that throws goes into unreadable. A VM detail that throws is null.
With -IncludeStorage (1.1.0, off by default) it also reads Get-ClusterSharedVolume -Cluster once per cluster (Read-ClusterStorage) - see §8.
-TestAccess records every read through Try-Read and prints the table, exiting 2 if anything was refused. -Redact uses an HMAC keyed on %ProgramData%\FreeITSM\redact.key: names become host-1a2b3c4d, ids become stable fake GUIDs, error text is replaced outright.
Reports go to <ApiUrl>/api/v1/index.php?path=/virtual-estate/<id>/reports with Authorization: Bearer, which works without URL rewriting.
includes/services/virtual_estate_cmdb.php (VirtualEstateCmdbService), with api/assets/hyperv_cmdb.php (the panel) and api/cmdb/discovery_source.php (the CI's Discovered card).
| Table | What it is |
|---|---|
virt_cmdb_mappings |
per connection: classes per kind, the four relationship types, sync_names, enabled
|
cmdb_object_sources |
bindings as periods - one live per CI and per object, start_source / end_reason (unbound, ci_deleted, rebound). Same shape as asset_ci_links
|
cmdb_relationship_sources |
the relationships the sync created - the only ones it ever changes or removes |
virt_cmdb_decisions |
create_new, leave_unbound, ci_deleted - what the sync must not decide alone |
status() decides each object: bound → keep (rename if allowed); open identity review as the new object → waiting; a decision → as decided; a same-name unbound CI of the mapped class in the company → match (never bound by name); otherwise create.
sync(): one transaction, a savepoint per CI (a class requiring properties fails that object only), then syncEdges(). It wants a set of edges from the virt rows and diffs it against the edges it owns. It does not adopt an identical edge a person drew, and it keeps owned edges of objects that are not seen. Workflow events fire after the commit. VirtualEstateService::submit() calls it after the report's own commit, so a CMDB problem never loses a report.
Hooks: CmdbService::deleteObject() → ciDeleted(); the connection delete in api/assets/hyperv_connections.php → connectionDeleted() (live bindings end as connection_deleted, rows kept - forCi() LEFT JOINs the connection; mapping, decisions and cmdb_relationship_sources deleted, as none has a foreign key); VirtualEstateService::rebind() → rebound() (the old row keeps its binding; a binding only the new row had moves; if both had one, the new one ends as rebound); purge() skips bound objects via boundIdsSql(); cmdbMemberState() → memberState() and cmdbPossibleOwners() → possibleOwnerCis() feed Part C.
🧪 tests/virtual-estate-cmdb.php - 32 checks, from the preview to unbinding.
-
TRAP:
Ris an alias. The redaction helper was first calledR.ris PowerShell's alias forInvoke-History, and an alias beats a function, so everyR 'host' $nameranInvoke-History. It isMasknow. CheckGet-Alias <name>before naming a short function. -
TRAP: PowerShell scoping is dynamic. A mocked cmdlet that read
$uuidsaw the collector's$uuidvariable, not the mock's own table. The mock's tables are named$Mock*for that reason. -
TRAP: comma binds tighter than
+.@('10.0.0.' + $n, 'fe80::1')is ONE string. Parenthesise. -
TRAP:
jobRegistry()is the scheduled jobs only. Anything listing or looking up jobs must usejobRegistryAll($conn). -
TRAP: Part B binds CIs to virt row ids.
decideReview()keeps the old row for that reason, andpurge()skips a bound object. - TRAP: a person who deletes a relationship the sync owns sees it come back on the next report - discovery is the authority for its own edges. Unbinding the object is how to stop that.
-
TRAP:
api/system/db_verify.php$primaryKeys. A new table whose key is notidmust be listed there, or Database Verification fails to create it.virt_cmdb_mappings,cmdb_relationship_sourcesandvirt_cmdb_decisionsare. -
TRAP: the merge guard reads every
host_idcolumn as an asset reference, because Software's is one.virt_vms.host_idandvirt_placements.host_idare inAssetMergeService::NOT_REFERENCES. -
TRAP: storage before Database Verification. An upgraded install runs the new code before anybody runs Verification. Every query that touches
virt_storage_volumesor astorage_*column must sit behindVirtualEstateService::storageReady()(§8). -
TRAP: storage errors never go in the report's top-level
unreadablelist. That list marks hosts and clusters unreadable, which would mark the VMs read in the same report Not confirmed. A storage failure is the cluster's ownstorage_read_error. - TRAP: never sum VM disk sizes into storage. VHDX sizes are what the VMs were given, not what the shared volume holds; the Servers panel says so in a comment too.
-
Size. On this dev box: 800 VMs ≈ 1 s, 8,000 VMs ≈ 9 s in one 7.5 MB report (
tests/virtual-estate-load.php). Recommend-ReportPer Cluster.
The collector's reads have only met mocked cmdlets. The property names it relies on - IsClustered, MemoryAssigned, OwnerGroup.Id, the VmID parameter, Win32_ComputerSystemProduct.UUID - are Microsoft's documented ones. Whether they hold on every Windows Server version, and whether the narrower permissions are enough, can only be confirmed on a real estate. The user page says so. The same goes for -IncludeStorage (§8): SharedVolumeInfo, Partition.Name, Size, FreeSpace and IsPartitionSizeValid are read defensively (Get-StorageProperty, so a missing property is unknown, not a crash), but have never met a real cluster.
(5.4.0, PR #351 by Dr4inder · review)
The report. An optional section, sent only by a collector run with -IncludeStorage:
"storage_volumes": {
"clusters": [
{ "cluster_id": "<Get-Cluster Id>", "complete": true, "error": null,
"items": [ { "resource_id": "...", "volume_id": "...", "name": "Cluster Disk 1",
"path": "C:\\ClusterStorage\\Volume1", "filesystem": "CSVFS_ReFS", "state": "Online",
"coordinator_node": "HV01", "total_bytes": 4398046511104, "free_bytes": 1099511627776 } ] },
{ "cluster_id": "...", "complete": false, "error": "Access denied", "items": [] }
]
}apply_storage_volumes() - completeness and failure are per cluster:
- A cluster must belong to the connection and the report's scope; one read per cluster.
- A cluster in the report's top-level
unreadablelist gets a failed storage read even if the collector sent none - its storage cannot be confirmed. -
Per cluster:
FOR UPDATEitsstorage_last_attempted_at; a report observed before it isstalefor that cluster (the watermark moves on failed reads too, so an older report under another scope cannot bring back older facts). Then aSAVEPOINT virt_storage_cluster: upsert byexternal_id=sha256(json_encode([cluster, resource_id, volume_id])); a complete read marks the cluster's other volumes not seen (markNotSeen()scoped to that one cluster); an incomplete or failed one marks themnot_confirmed_since. A bad item rolls back that cluster only. -
Bytes (
storageBytes()): an exact non-negative BIGINT, or null. Never coerced to 0;0free is real; free greater than total becomes null;used_bytesonly from a valid pair. -
The cluster's storage columns, written after every attempt:
storage_last_attempted_at,storage_read_error,storage_last_observed_at(good reads only),storage_failing_since(kept while it keeps failing) andstorage_failed_runs(reset to 0 by a good read).storage_alerted_atbelongs to §9. - The section's outcome: applied, partial (some clusters failed) or failed.
storageReady() - has Database Verification added virt_storage_volumes and the cluster's storage columns? Cached per request; $storageReadyOverride lets a test pretend. Until it is true:
| Where | Before Verification |
|---|---|
apply_storage_volumes() |
Throws storage_unavailable - the section fails (207, Run Database Verification to accept storage); the other sections apply |
storageInventory() / Servers |
Nothing - Servers says Storage not collected |
GET /virtual-estate/{id} |
counts.storage_volumes 0, storage []
|
purge() |
Leaves storage alone, and clusters are purged as before |
Deleting a connection (api/assets/hyperv_connections.php) |
Skips the explicit DELETE FROM virt_storage_volumes (the foreign key cascades once Verification has added it) |
watch() |
Checks connections only |
storageInventory($conn, $connectionIds) - the one read model for Servers (api/assets/get_servers.php) and REST: clusters with their storage state and volumes, grouped by connection.
Retention (purge(), Ed's decision on the review): volumes follow the VMs' rule - deleted once not_seen_since is older than the connection's retention_days, and so are the volumes of a cluster that is itself past it (and not bound to a CI). Volumes are purged before clusters, and a cluster is kept while any volume still points at it. purge() only ever runs inside submit(), after a report that was neither stale nor a replay - so a silent collector, or a late old report, never removes anything.
The Servers panel (renderStorage() in asset-management/servers/index.php): grouped by connection and cluster, Storage not confirmed with the error, Storage could not be read in the last N reports, since ... once failed_runs > 1, Last complete storage read, and an unnamed cluster shown by its id.
(5.4.0, asked for on the #351 review.) A collector that stops sends nothing, so nothing in submit() can notice. A scheduled job has to.
| Registry |
virt_watch in jobRegistry(): php cron/virt_watch.php, every 60 minutes, grace 120, max runtime 5; needed while any virt_connections.is_active = 1; module assets in $jobModules (not needed with Assets off) |
| Script |
cron/virt_watch.php - command line only, cronModuleSwitchedOff(), JobRun::lock() / start() / finish(), calls VirtualEstateService::watch($conn)
|
| Columns |
virt_connections.stale_alerted_at, virt_clusters.storage_alerted_at - when the bell was sent; null = not told, or recovered |
| Notification | type hyperv.collector (NotificationsService::types(), on by default, switchable in Preferences), entity virt_connection → asset-management/servers/ (entityLink()), mapped to module assets so it hides with Assets off |
watch($conn, ?$now, ?$only) returns ['stale', 'storage', 'cleared', 'told']:
- Does nothing until
ready()and thestale_alerted_atcolumn exist. -
Each switched-on connection:
freshness()=overdue(later than its own interval plus grace - the Servers page's Overdue) andstale_alerted_atnull → tell, then stamp it. Not overdue but stamped → clear it, so the next silence tells again. A connection that has never reported isfreshness()never, not overdue - left to Background jobs. -
Each cluster (only once
storageReady()):storage_read_errorset,storage_alerted_atnull andstorage_failed_runs >= 2→ tell and stamp. Two in a row, because one failed read can be a blip (Ed, 2026-11-15) - and the Servers page starts warning at the same point. Error gone but stamped → clear.
watchRecipients($conn, $c) - every active analyst with analystCanAccessModule('assets'), Cap::ASSETS_HYPERV and analystCanAccessTenant() for the connection's company (the default company when tenant_id is null) - the people who could open the connection on Assets → Settings → Hyper-V and fix it.
tell() calls NotificationsService::notify() once per recipient and never throws - a bell failure is logged ([virt watch] bell:) and the stamp is still written, so a broken bell cannot turn into an hourly retry storm.
The titles and bodies are English, built in watch() (Hyper-V collector stopped reporting: <name>, Cluster storage could not be read: <cluster> (<connection>)), like other bell texts written by a job.
🧪 tests/virtual-estate-storage.php (FREEITSM_TEST_DATABASE=<disposable db>, after Database Verification) covers, beside every storage case in §8: one overdue connection told once and not again, cleared by an on-time report and told again on the next silence; one failed storage read telling nobody; two in a row telling once; a good read clearing it; recipients limited to analysts with Assets and the Hyper-V capability; a stale report never purging, even past the retention setting; and the three "not ready" cases from the table above.