Let a check's type decide how it is drawn and listed

An availability check already had a stored type: machine, service or
device. The map added this week ignored it and read the check's name, so
"Core switch" was drawn as a switch and a check typed Device and named
"usw-24" was not. A check that probed a default gateway was a router
whatever it said. Pulse had two ideas of what a check is, and the form
that sets the type could not predict what the map would draw.

The stored type is now the one thing every page reads.

The server accepts three more types: router, switch and access point.
One browser module names all six and is read by the form, the settings
list and the map. The map draws a router, a switch or an access point as
that device with the ways in, and every other type as a check. That
includes a machine: only a Pulse agent makes a machine, on the map as on
the Machines table. The map no longer reads names or compares addresses.

The name reading is not thrown away. It moved into the form as an offer
beside Target type ("This looks like your switch"), with a button. A
name or a gateway address can suggest a type; nothing changes until the
owner takes it.

Links follow the same rule. A check's tile, an availability alert and a
record's owner link open that check's detail, where each used to land on
the whole list, or for an alert on Proxmox. The map's unmonitored
gateway tile creates a router check, and closing or saving that form
returns to the map.

A remote probe agent validates the type before it probes and does
nothing else with it, so an agent older than these types is sent
"device" for them and the saved type stays on the server. An older
server cannot run them at all; the availability guide says to set such
checks to Other device before a downgrade.

Not fixed here: a save that completes after the owner has left for a
second add form can close that form. The form's completion callback has
always outlived it.

Contract-Neutral: the unified-resources, api-contracts, frontend-primitives, monitoring and alerts contracts are updated in this commit. storage-recovery names routing/resourceLinks.ts as a shared file; the one addition there is a path to an availability check, and no storage or recovery route changes.
This commit is contained in:
rcourtman
2026-11-19 11:57:19 +00:00
parent 97d6d3111c
commit 244c5f577d
45 changed files with 963 additions and 277 deletions
+1 -1
View File
@@ -2095,7 +2095,7 @@ the API for automation.
Target payload fields:
- `name` - Display name.
- `targetKind` - `machine`, `service`, or `device`; defaults to `service`.
- `targetKind` - what the check is on: `service`, `machine`, `router`, `switch`, `access_point`, or `device`; defaults to `service`. The map draws a router, switch or access point as that device.
- `address` - Hostname, IP address, or URL.
- `protocol` - `icmp`, `tcp`, `udp`, `http`, or `https`. The input alias `ping` is accepted and is stored/returned as canonical `icmp`.
- `port` - Required for `tcp`/`udp`, optional for `http`/`https`, and omitted for `icmp`.
+21 -4
View File
@@ -26,8 +26,9 @@ policies, or [check DNS answers](#check-that-dns-answers-correctly).
## Add a local check
1. Open **Settings → Monitoring → Availability checks** and add a target.
2. Give it a name, choose its protocol, and enter the address and any required
port or path. The Pulse server must be able to resolve and reach that address.
2. Choose its **Target type**, give it a name, choose its protocol, and enter
the address and any required port or path. The Pulse server must be able to
resolve and reach that address.
3. Review the polling interval, timeout and failure threshold. A missed check
is evaluated under those settings, not a promise of an immediate alert.
4. Save the enabled target and inspect its observations. Use **This Pulse
@@ -38,8 +39,24 @@ policies, or [check DNS answers](#check-that-dns-answers-correctly).
Keep credentials and private target addresses out of public screenshots and
support reports. Use a service you own or are authorised to monitor.
A check on a router, switch or access point is also drawn on the map as that
device. See [Add your router, switch or access point](MAP.md#add-your-router-switch-or-access-point).
The target type says what the check is on, and every page reads it:
| Target type | Use it for | On the map |
| --- | --- | --- |
| Website or service | A site, an API, a port | **Checks** |
| Machine or server | A computer without a Pulse agent | **Checks** |
| Router or firewall, Switch, Access point | Network gear | **Ways in**, as that device |
| Other device | A printer, a UPS, a sensor | **Checks** |
A machine check does not add the computer to **Machines**; that takes a Pulse
agent.
The router, switch and access point types need a Pulse server that knows
them. Before downgrading to an older release, set those checks to **Other
device**: an older server cannot run a check of a type it does not know, and
reports it unreachable.
See [Add your router, switch or access point](MAP.md#add-your-router-switch-or-access-point).
## Check from another network with Pro
+2 -2
View File
@@ -984,8 +984,8 @@ Supported protocols:
| `udp` | A request/response UDP service, or an open-or-filtered observation | `address`, `port`, UDP result policy |
| `http` / `https` | Web UI or health endpoint availability | `address`, optional `port`, optional `path` |
Saved targets include `name`, `targetKind` (`machine`, `service`, or
`device`), `address`, `protocol`, `enabled`, polling interval, timeout,
Saved targets include `name`, `targetKind` (`service`, `machine`, `router`,
`switch`, `access_point`, or `device`), `address`, `protocol`, `enabled`, polling interval, timeout,
failure threshold, and an optional `linkedResourceId`. UDP targets select
`response_required` (send up to 512 UTF-8 bytes and require a response) or
`open_or_filtered` (silence is indeterminate, not proof of reachability); an
+17 -15
View File
@@ -14,7 +14,7 @@ the map button in the header.
| **Ways in** | Reverse proxies, VPNs, DNS, and your router, switches and access points |
| Network pills | Each network, with how many things are on it |
| Boxes such as **Media**, **Monitoring**, **Databases** | Guests and containers, grouped by what they are for |
| **Checks** | Availability checks on things that are not network gear |
| **Checks** | Availability checks on websites, services, machines without an agent and other devices |
| **Storage**, **Backups**, **Hardware** | Pools, backup targets and the machines everything runs on |
Each tile has a status dot: healthy, needs attention, critical, not reporting
@@ -41,26 +41,28 @@ box without renaming it.
## Add your router, switch or access point
Pulse cannot see network gear by itself. An
[availability check](AVAILABILITY.md) puts it on the map.
[availability check](AVAILABILITY.md) puts it on the map, and the check's
**Target type** says what it is.
**Your router.** A gateway nothing monitors is drawn as a dashed tile that
says "not monitored". Click it. The check form opens with the address filled
in; save it, and the tile becomes your router with a live status.
says "not monitored". Click it. The check form opens as a router with the
address filled in; save it, and you are back on the map with the tile as your
router and a live status.
**A switch or access point.** Add a check for its address in **Settings →
Monitoring → Availability checks**, and put what it is in the name:
**Anything else.** Add a check in **Settings → Monitoring → Availability
checks** and choose its type:
| To draw | Use one of these words in the check's name |
| Target type | Where the map draws it |
| --- | --- |
| A router | `router`, `firewall`, `modem`, `OPNsense`, `pfSense`, `MikroTik`, `OpenWrt`, `FritzBox`, `UDM`, `USG` |
| A switch | `switch` |
| An access point | `AP`, `WiFi`, `WLAN`, `access point` |
| Router or firewall, Switch, Access point | In **Ways in**, as that device |
| Website or service, Machine or server, Other device | In **Checks** |
"Core switch" and "AP living room" both work. The word must stand on its own:
"apt-cache" is not an access point. A check named for nothing in the table
stays in **Checks**, unless it probes a machine's default gateway, which
makes it a router whatever it is called. To change how a check is drawn,
rename it.
The type decides, not the name. When a check's name says what it is ("Core
switch"), or its address is exactly a monitored machine's default gateway,
the form offers the matching type; nothing changes until you choose it. To
move a check on the map, change its type.
Click a check's tile to open that check.
## Connections
@@ -4188,6 +4188,11 @@ Render-heavy alert overview ownership now routes through
and `frontend-modern/src/features/alerts/AlertOverviewAlertCard.tsx` instead
of rebuilding stats-card, active-alert, and timeline-card presentation inline
inside `frontend-modern/src/features/alerts/OverviewTab.tsx`.
An availability alert names one check, so its card links to that check:
`AlertOverviewAlertCard.tsx` sends a `network-endpoint` alert with a resource
id to `buildAvailabilityCheckPath`, the Availability checks table with that
row's detail open. Before 2026-11-19 it fell through the platform rules and
landed on Proxmox.
`AlertOverviewAlertCard.tsx` also owns the compact delivery-status placement,
while `deliveryDiagnosisPresentation.ts` owns the reason-to-copy and tone
mapping. Acknowledged cards keep their canonical badge and omit that redundant
@@ -3968,8 +3968,12 @@ a new API state machine, queue contract, or verification-accounting field.
`internal/api/platform_mock_connections.go`,
`frontend-modern/src/api/availabilityTargets.ts`, and the unified-resource
availability payload together. The bounded `targetKind` vocabulary is
`machine`, `service`, and `device`; missing legacy values default to
`service`. Browser add-dialog routes may carry a `targetKind` query value
`service`, `machine`, `router`, `switch`, `access_point`, and `device`;
missing legacy values default to `service`. The three network-gear kinds
were added on 2026-11-19 so the owner states what a check is on and the
map draws it as that; `AvailabilityTargetKind.IsNetworkGear` names them,
and `frontend-modern/src/utils/availabilityTargetKinds.ts` is the browser's
one definition of the vocabulary. Browser add-dialog routes may carry a `targetKind` query value
to preselect that bounded kind, but the persisted contract remains the
`AvailabilityTarget.targetKind` payload. Browser consumers must not place
availability targets into Standalone Machines from that classification;
@@ -8376,7 +8376,13 @@ and `address` on the add route, built by `buildAvailabilityTargetAddPath` and
read by `getAvailabilityTargetAddPrefill`. They start the form's Name and
Address fields and save nothing; each is trimmed, cut at a hostname's length
and ignored off the add route. The map's unmonitored gateway tile is the first
such link, with `targetKind=device`.
such link, with `targetKind=router` and `from=map`. `from` names the page that
sent the owner, and `map` is the only value read: closing or saving the dialog
then returns to the map. No address or path is taken from the link. The
dialog's title and its save button are worded from the kind by
`getAvailabilityTargetAddLabel`, and the form's Target type list is
`AVAILABILITY_TARGET_KINDS`, so a kind added there appears in the form, the
settings list and the map together.
Former nested aliases such as `/settings/infrastructure/install`,
`/settings/infrastructure/platforms/proxmox/pbs`,
`/settings/infrastructure/api/pve`, and `/settings/workloads/docker` must fail
@@ -6588,9 +6588,14 @@ never encode that state as a confirmed failure or a healthy observation. The reg
binding the source envelope to the check resource and cloning a separately
bound envelope for any matched-resource facet projection after correlation.
Availability target kind is monitoring-owned runtime metadata, not a frontend
guess. Saved targets carry the bounded `targetKind` values `machine`, `service`,
and `device`; monitoring must preserve that value in probe status, supplemental
resource availability data, and availability tags. Missing legacy target kinds
guess. Saved targets carry the bounded `targetKind` values `service`, `machine`,
`router`, `switch`, `access_point`, and `device`; monitoring must preserve that value in probe status, supplemental
resource availability data, and availability tags. The one place the saved
kind is not sent as it is saved is a remote probe agent's assignment:
`availabilityProbeAgentTargetKind` sends `device` for the three network-gear
kinds, because an agent validates the kind before it probes and one built
before those kinds existed would refuse them and report the check unreachable
without probing. The agent does nothing else with the kind. Missing legacy target kinds
default to `service`, and monitoring must not promote a ping, TCP, or HTTP probe
to a machine solely from address shape, protocol, name, or successful reachability.
Mock-mode availability targets must use that same provider vocabulary. The
@@ -4392,33 +4392,39 @@ What the diagram does with them:
said on that thing instead. A resolver is said only on something already
drawn.
- The dashed gateway tile is a link, because "not monitored" has one thing to
do about it: it opens the availability add dialog as a device ping check
named `Gateway` with the gateway's address filled in, and nothing is saved
until the owner saves it. Its hover says "Click to add a check" and a touch
tap says "Tap again to add a check", since every other tile opens the thing
it shows. Once a check probes that address the check is the monitored thing
that answers on it, so the dashed tile is gone and the check's tile says
whose gateway it is. With names hidden the address is not on the page and
the tile is no link.
- A check on a router, a switch or an access point is drawn as that device
in the Ways in box, with its own glyph and the device as its caption, and
not in the Checks box. The map knows the device two ways and no other: the
check probes an address that is a machine's default gateway, which makes it
a router whatever it is called; or its name says so (`resolveMapDeviceRole`,
whole words only, so `apt-cache` is no access point). `gateway` is not such
a word, because an API gateway is checked too. The role decides the glyph,
the caption and the box and nothing else: the tile still opens the check,
and a name that says none of these stays a plain check. With names hidden
the tile keeps its device and its box and reads `Router 1`, `Switch 1` or
`AP 1`. No setting stores the role; an owner changes it by renaming the
check.
do about it: it opens the availability add dialog as a router check named
`Gateway` with the gateway's address filled in, and nothing is saved until
the owner saves it. The link says it came from the map, and closing or
saving that dialog returns there, where the new tile is. Its hover says
"Click to add a check" and a touch tap says "Tap again to add a check",
since every other tile opens the thing it shows. Once a check probes that
address the check is the monitored thing that answers on it, so the dashed
tile is gone and the check's tile says whose gateway it is. With names
hidden the address is not on the page and the tile is no link.
- A check is drawn by its stored kind and by nothing else. The kind is the
owner's statement of what the check is on, set in the availability form,
and `frontend-modern/src/utils/availabilityTargetKinds.ts` is the one
definition every surface reads: the form's list, the settings label and the
map. A `router`, `switch` or `access_point` check is drawn as that device in
the Ways in box, with its own glyph and the device as its caption. Every
other kind, `machine` included, is a tile in the Checks box: only a Pulse
agent makes a machine, on the map as on the Machines table. The map does not
read a check's name or compare its address to a gateway to decide what it
is; that guess was built on 2026-11-19 and removed the same day, because it
made the map disagree with the form. The same reading now lives in the form
as `suggestAvailabilityTargetKind`, which offers a kind beside the Target
type field and changes nothing until the owner takes it. With names hidden
a gear tile keeps its device and its box and reads `Router 1`, `Switch 1`
or `AP 1`.
- A check's tile opens that check: `buildResourcePagePath` sends every
`network-endpoint` to `buildAvailabilityCheckPath`, the Availability checks
table with that row's detail open, so the map, an alert and any other link
to a check land on the check and not on the list it is in.
- How a thing gets onto the map is not something the map can show, so the
page says it in one line beside the legend, "Apps and network gear are
recognised by name", and links the shipped guide `docs/MAP.md` (`MAP_DOC_URL`).
The guide is where the words an owner can use are listed, so a word added to
`resolveMapDeviceRole` is added to its table in the same change. The line
stays that short: the legend's height is a fixed allowance in the fit to
one screen. `FRITZ!Box` is read as the one word its owner means.
page says it in one line beside the legend, "Apps are recognised by name,
checks are drawn by their type", and links the shipped guide `docs/MAP.md`
(`MAP_DOC_URL`). The line stays that short: the legend's height is a fixed
allowance in the fit to one screen.
- A saved image has no pointer, so it has no rings. The captions carry the
facts there.
@@ -0,0 +1,71 @@
{
"version": 1,
"base_sha": "97d6d3111c1a8522074136ebb07c090c3e4835e0",
"verified_at": "2026-11-19T11:57:19Z",
"result": "passed",
"changed_paths": [
"frontend-modern/src/api/availabilityTargets.ts",
"frontend-modern/src/components/Settings/AvailabilitySettingsPanel.tsx",
"frontend-modern/src/components/Settings/ConnectionEditor/CredentialSlots/AvailabilityTargetSlot.tsx",
"frontend-modern/src/components/Settings/availabilitySettingsModel.ts",
"frontend-modern/src/features/alerts/AlertOverviewAlertCard.tsx",
"frontend-modern/src/features/infrastructureMap/InfrastructureMapSurface.tsx",
"frontend-modern/src/features/infrastructureMap/infrastructureMapCatalogue.ts",
"frontend-modern/src/features/infrastructureMap/infrastructureMapModel.ts",
"frontend-modern/src/features/infrastructureMap/infrastructureMapServices.ts",
"frontend-modern/src/features/platformNavigation/resourcePagePath.ts",
"frontend-modern/src/features/platformPage/RecordOwnerLink.tsx",
"frontend-modern/src/features/standalone/AvailabilityChecksTable.tsx",
"frontend-modern/src/features/standalone/StandalonePageSurface.tsx",
"frontend-modern/src/routing/resourceLinks.ts",
"frontend-modern/src/utils/availabilityTargetKinds.ts"
],
"content_sha256": {
"frontend-modern/src/api/availabilityTargets.ts": "36c57d5b45b033915c632b6af07ddda96fd78000d49147c6dd07109387c364c9",
"frontend-modern/src/components/Settings/AvailabilitySettingsPanel.tsx": "71747f55cc0a6c2f44bb795ac8087b14ae34b9b64bfa2460ffb2e4c3d769d909",
"frontend-modern/src/components/Settings/ConnectionEditor/CredentialSlots/AvailabilityTargetSlot.tsx": "9a0ab3e132058fe9452df2f30c0ce139b33ee49be251a0f9542c17797febd163",
"frontend-modern/src/components/Settings/availabilitySettingsModel.ts": "054165bf8364deac86ccbe96b519a61a4da057731e1d94c435bd7550dd2be4d1",
"frontend-modern/src/features/alerts/AlertOverviewAlertCard.tsx": "88118a3634a7f56f0c4cece152e81fbeb3c273663e83d7888308c438572c8702",
"frontend-modern/src/features/infrastructureMap/InfrastructureMapSurface.tsx": "738889c582d78ad1afd83ab097dfc63382fbda6eeb5c67b5bddd0db5ffdb5a2d",
"frontend-modern/src/features/infrastructureMap/infrastructureMapCatalogue.ts": "96d9b971489962c06efcce9b681c6317058406455f3787fe6052733d67408cf3",
"frontend-modern/src/features/infrastructureMap/infrastructureMapModel.ts": "4b32bdc67323a4e87d3cc3a1f2de643bb912f99f035efdde360463a7f0c01bdf",
"frontend-modern/src/features/infrastructureMap/infrastructureMapServices.ts": "32f0692c4b42ab7a9c9e2cad453133acc9dd80f8b93792d67034fe88fad9b513",
"frontend-modern/src/features/platformNavigation/resourcePagePath.ts": "96d3f4d208c49a3481835da155679772f27c5d21210bade208acfd46af343c16",
"frontend-modern/src/features/platformPage/RecordOwnerLink.tsx": "c5113c6b3b1ce8a6be2385ab55fa26afe090b0b14a590edd7385f395848e1e9e",
"frontend-modern/src/features/standalone/AvailabilityChecksTable.tsx": "82294cd11483d4fec7e191f0b0b5b845a664d72551adba076cf7b61f1a5c8036",
"frontend-modern/src/features/standalone/StandalonePageSurface.tsx": "fc4ed4f70eb99d4dab9c6a2c83e885a7f38db809880a9a78224faeb0be6505af",
"frontend-modern/src/routing/resourceLinks.ts": "ab97fb3c0c3d418ab11831b12d984046c7ecd8e3153042d220634e8c6ffcb929",
"frontend-modern/src/utils/availabilityTargetKinds.ts": "4110d55a28087b9b634803098bba0127daaf5219e34acfe2e235dcf370ef05d4"
},
"routes": [
"/map",
"/settings/monitoring/availability?add=target",
"/standalone/availability?view=table&check=<id>"
],
"viewports": [
{
"width": 1440,
"height": 900
},
{
"width": 390,
"height": 844
}
],
"states": [
"final runtime bytes served by a Vite dev server from a clone of main plus this change on pulse-dev, driven by headless Chromium through Playwright, against a private Pulse built from the same clone with no mock data: one real host agent, and checks made through the API on loopback addresses (access_point, machine, service, device). The API refused a check of an unknown type with 400",
"1440x900, /map before: 'Living room' (access_point) was in Ways in beside the dashed 'not monitored' gateway. 'old-nas' (machine), 'Printer' (device) and 'Router admin page' (service) were in Checks: a machine check is not drawn as hardware, and a name alone moves nothing",
"1440x900: the gateway tile's link carried targetKind=router and from=map. It opened 'Add router check' with Target type router, Name 'Gateway' and no suggestion. Pressing 'Add router check' returned to /map",
"1440x900, the add form as a service check: Target type listed Website or service, Machine or server, Router or firewall, Switch, Access point, Other device. Typing the name 'Garage switch' showed 'This looks like your switch. The map draws it as one when its type says so.' with the type still service. 'Use Switch' set the type to switch, removed the offer and reworded the save button to 'Add switch check'. Saving closed the dialog on the settings page",
"1440x900, /map after: Ways in held 'Garage switch' (switch), 'Gateway' (router) and 'Living room' (access point), each with its glyph; Checks and Hardware were unchanged; no tile said 'not monitored'. The footer read 'Apps are recognised by name, checks are drawn by their type. How the map works'. The map ended at 744 of 900",
"1440x900: clicking the 'Garage switch' tile opened /standalone/availability?view=table&check=<its id> with six rows and exactly one detail open, 'Collapse details for Garage switch'",
"390x844, touch: the same three tiles in Ways in, the same three in Checks, the map ending at 788 above the fixed navigation at 799",
"no page error in either context",
"not checked: light theme, Firefox, Safari, a real phone, a remote probe agent older than the new types (covered by a server test of the payload it is sent), an availability alert's link in a browser (covered by a component test), a table long enough to window its rows"
],
"interactions": [
"clicked the unmonitored gateway tile, saved the router check and was returned to the map",
"typed a name into the add form, took the offered type and saved the check",
"clicked a check's tile on the map and read which detail the checks table opened"
]
}
+1 -1
View File
@@ -2095,7 +2095,7 @@ the API for automation.
Target payload fields:
- `name` - Display name.
- `targetKind` - `machine`, `service`, or `device`; defaults to `service`.
- `targetKind` - what the check is on: `service`, `machine`, `router`, `switch`, `access_point`, or `device`; defaults to `service`. The map draws a router, switch or access point as that device.
- `address` - Hostname, IP address, or URL.
- `protocol` - `icmp`, `tcp`, `udp`, `http`, or `https`. The input alias `ping` is accepted and is stored/returned as canonical `icmp`.
- `port` - Required for `tcp`/`udp`, optional for `http`/`https`, and omitted for `icmp`.
+21 -4
View File
@@ -26,8 +26,9 @@ policies, or [check DNS answers](#check-that-dns-answers-correctly).
## Add a local check
1. Open **Settings → Monitoring → Availability checks** and add a target.
2. Give it a name, choose its protocol, and enter the address and any required
port or path. The Pulse server must be able to resolve and reach that address.
2. Choose its **Target type**, give it a name, choose its protocol, and enter
the address and any required port or path. The Pulse server must be able to
resolve and reach that address.
3. Review the polling interval, timeout and failure threshold. A missed check
is evaluated under those settings, not a promise of an immediate alert.
4. Save the enabled target and inspect its observations. Use **This Pulse
@@ -38,8 +39,24 @@ policies, or [check DNS answers](#check-that-dns-answers-correctly).
Keep credentials and private target addresses out of public screenshots and
support reports. Use a service you own or are authorised to monitor.
A check on a router, switch or access point is also drawn on the map as that
device. See [Add your router, switch or access point](MAP.md#add-your-router-switch-or-access-point).
The target type says what the check is on, and every page reads it:
| Target type | Use it for | On the map |
| --- | --- | --- |
| Website or service | A site, an API, a port | **Checks** |
| Machine or server | A computer without a Pulse agent | **Checks** |
| Router or firewall, Switch, Access point | Network gear | **Ways in**, as that device |
| Other device | A printer, a UPS, a sensor | **Checks** |
A machine check does not add the computer to **Machines**; that takes a Pulse
agent.
The router, switch and access point types need a Pulse server that knows
them. Before downgrading to an older release, set those checks to **Other
device**: an older server cannot run a check of a type it does not know, and
reports it unreachable.
See [Add your router, switch or access point](MAP.md#add-your-router-switch-or-access-point).
## Check from another network with Pro
+2 -2
View File
@@ -984,8 +984,8 @@ Supported protocols:
| `udp` | A request/response UDP service, or an open-or-filtered observation | `address`, `port`, UDP result policy |
| `http` / `https` | Web UI or health endpoint availability | `address`, optional `port`, optional `path` |
Saved targets include `name`, `targetKind` (`machine`, `service`, or
`device`), `address`, `protocol`, `enabled`, polling interval, timeout,
Saved targets include `name`, `targetKind` (`service`, `machine`, `router`,
`switch`, `access_point`, or `device`), `address`, `protocol`, `enabled`, polling interval, timeout,
failure threshold, and an optional `linkedResourceId`. UDP targets select
`response_required` (send up to 512 UTF-8 bytes and require a response) or
`open_or_filtered` (silence is indeterminate, not proof of reachability); an
+17 -15
View File
@@ -14,7 +14,7 @@ the map button in the header.
| **Ways in** | Reverse proxies, VPNs, DNS, and your router, switches and access points |
| Network pills | Each network, with how many things are on it |
| Boxes such as **Media**, **Monitoring**, **Databases** | Guests and containers, grouped by what they are for |
| **Checks** | Availability checks on things that are not network gear |
| **Checks** | Availability checks on websites, services, machines without an agent and other devices |
| **Storage**, **Backups**, **Hardware** | Pools, backup targets and the machines everything runs on |
Each tile has a status dot: healthy, needs attention, critical, not reporting
@@ -41,26 +41,28 @@ box without renaming it.
## Add your router, switch or access point
Pulse cannot see network gear by itself. An
[availability check](AVAILABILITY.md) puts it on the map.
[availability check](AVAILABILITY.md) puts it on the map, and the check's
**Target type** says what it is.
**Your router.** A gateway nothing monitors is drawn as a dashed tile that
says "not monitored". Click it. The check form opens with the address filled
in; save it, and the tile becomes your router with a live status.
says "not monitored". Click it. The check form opens as a router with the
address filled in; save it, and you are back on the map with the tile as your
router and a live status.
**A switch or access point.** Add a check for its address in **Settings →
Monitoring → Availability checks**, and put what it is in the name:
**Anything else.** Add a check in **Settings → Monitoring → Availability
checks** and choose its type:
| To draw | Use one of these words in the check's name |
| Target type | Where the map draws it |
| --- | --- |
| A router | `router`, `firewall`, `modem`, `OPNsense`, `pfSense`, `MikroTik`, `OpenWrt`, `FritzBox`, `UDM`, `USG` |
| A switch | `switch` |
| An access point | `AP`, `WiFi`, `WLAN`, `access point` |
| Router or firewall, Switch, Access point | In **Ways in**, as that device |
| Website or service, Machine or server, Other device | In **Checks** |
"Core switch" and "AP living room" both work. The word must stand on its own:
"apt-cache" is not an access point. A check named for nothing in the table
stays in **Checks**, unless it probes a machine's default gateway, which
makes it a router whatever it is called. To change how a check is drawn,
rename it.
The type decides, not the name. When a check's name says what it is ("Core
switch"), or its address is exactly a monitored machine's default gateway,
the form offers the matching type; nothing changes until you choose it. To
move a check on the map, change its type.
Click a check's tile to open that check.
## Connections
@@ -5,7 +5,9 @@ const AVAILABILITY_TARGETS_PATH = '/api/availability-targets';
export type AvailabilityProbeProtocol = 'icmp' | 'tcp' | 'udp' | 'http' | 'https';
export type AvailabilityUDPMode = 'response_required' | 'open_or_filtered';
export type AvailabilityTargetKind = 'machine' | 'service' | 'device';
/** What a check is on. `@/utils/availabilityTargetKinds` says what each one means. */
export type AvailabilityTargetKind =
'service' | 'machine' | 'router' | 'switch' | 'access_point' | 'device';
export type AvailabilityHTTPMethod = 'HEAD' | 'GET' | 'POST';
export type AvailabilityHTTPAuthType = 'none' | 'basic' | 'bearer';
@@ -3,6 +3,8 @@ import { Show, createEffect, createMemo, createSignal, onMount, type Component }
import type { Resource } from '@/types/resource';
import { isAgentlessAvailabilityResource } from '@/features/standalone/standalonePageModel';
import { useLocation, useNavigate } from '@solidjs/router';
import { INFRASTRUCTURE_MAP_PATH } from '@/routing/resourceLinks';
import { getAvailabilityTargetAddLabel, isNetworkGearKind } from '@/utils/availabilityTargetKinds';
import Plus from 'lucide-solid/icons/plus';
import RotateCw from 'lucide-solid/icons/rotate-cw';
import Activity from 'lucide-solid/icons/activity';
@@ -95,8 +97,21 @@ export const AvailabilitySettingsPanel: Component = () => {
};
const closeDialog = (replace = false) => {
const current = dialog();
setDialog(null);
setDeleteConfirmingId(null);
// The map sent the owner here to add one thing. Saved or not, that is
// where they were, and where what they added is drawn.
if (
current?.mode === 'add' &&
current.prefill.from === 'map' &&
// Only while this page is still the one they are on: a save that lands
// after they have gone elsewhere must not pull them back.
location.pathname.replace(/\/+$/, '') === buildAvailabilitySettingsPath()
) {
navigate(INFRASTRUCTURE_MAP_PATH, { replace: true });
return;
}
if (location.pathname === buildAvailabilitySettingsPath() && location.search) {
navigate(buildAvailabilitySettingsPath(), { replace, scroll: false });
}
@@ -180,16 +195,7 @@ export const AvailabilitySettingsPanel: Component = () => {
const dialogTitle = createMemo(() => {
const current = dialog();
if (current?.mode === 'edit') return `Manage ${current.target.name}`;
if (current?.mode === 'add' && current.initialTargetKind === 'machine') {
return 'Add machine check';
}
if (
current?.mode === 'add' &&
(current.initialTargetKind === 'service' || current.initialTargetKind === 'device')
) {
return 'Add service/device check';
}
return 'Add availability check';
return getAvailabilityTargetAddLabel(current?.initialTargetKind);
});
const dialogDescription = createMemo(() => {
@@ -200,6 +206,9 @@ export const AvailabilitySettingsPanel: Component = () => {
if (current?.mode === 'add' && current.initialTargetKind === 'machine') {
return 'Use reachability checks for servers, desktops, laptops, and other computers that do not run Pulse Agent.';
}
if (current?.mode === 'add' && isNetworkGearKind(current.initialTargetKind)) {
return 'Pulse cannot see network gear by itself. A check gives it a live status and draws it on the map as the device it is.';
}
return 'Use ICMP ping, TCP port, or HTTP checks for devices and services that cannot run Pulse Agent.';
});
@@ -29,6 +29,12 @@ import {
type AvailabilityTargetPresetID,
} from '../availabilityTargetPresets';
import { useResources } from '@/hooks/useResources';
import {
AVAILABILITY_TARGET_KINDS,
getAvailabilityTargetAddLabel,
getAvailabilityTargetKindInfo,
suggestAvailabilityTargetKind,
} from '@/utils/availabilityTargetKinds';
import { getSourcePlatformLabel } from '@/utils/sourcePlatforms';
import { getPreferredInfrastructureDisplayName } from '@/utils/resourceIdentity';
import { getResourceTypeLabel } from '@/utils/resourceTypePresentation';
@@ -434,29 +440,42 @@ export const AvailabilityTargetSlot: Component<AvailabilityTargetSlotProps> = (p
selectedPresetConfig()?.addressPlaceholder ??
(form().protocol === 'http' || form().protocol === 'https'
? `${form().protocol}://service.local/status`
: form().targetKind === 'machine'
? 'server.local'
: form().targetKind === 'service'
? 'service.local'
: 'device.local');
: (getAvailabilityTargetKindInfo(form().targetKind)?.addressPlaceholder ?? 'device.local'));
const portPlaceholder = () =>
selectedPresetConfig()?.portPlaceholder ??
(form().protocol === 'http' || form().protocol === 'https' ? 'Optional' : '1883');
const namePlaceholder = () =>
form().targetKind === 'machine'
? 'mac-mini'
: form().targetKind === 'service'
? 'mqtt-broker'
: 'energy-monitor';
getAvailabilityTargetKindInfo(form().targetKind)?.namePlaceholder ?? 'energy-monitor';
const addButtonLabel = () =>
form().targetKind === 'machine'
? 'Add machine check'
: form().targetKind === 'service' || form().targetKind === 'device'
? 'Add service/device check'
: 'Add target';
const addButtonLabel = () => getAvailabilityTargetAddLabel(form().targetKind);
// What machines Pulse monitors use as their default gateway: a check on one
// of those addresses is a check on the router.
const gatewayAddresses = createMemo(() => {
const addresses = new Set<string>();
for (const resource of resources()) {
for (const gateway of resource.agent?.defaultGateways ?? []) {
if (gateway.address) addresses.add(gateway.address);
}
}
return addresses;
});
// Offered, never applied: the owner's choice of type is what every page
// reads, so a name must not change it behind their back. Nothing is offered
// once the type says what the thing is.
const suggestedKind = createMemo(() => {
const current = form().targetKind;
if (current !== 'service' && current !== 'device') return undefined;
return getAvailabilityTargetKindInfo(
suggestAvailabilityTargetKind({
name: form().name,
address: form().address,
gatewayAddresses: gatewayAddresses(),
}),
);
});
const handlePresetChange = (presetId: AvailabilityTargetPresetID) => {
setSelectedPreset(presetId);
@@ -565,9 +584,9 @@ export const AvailabilityTargetSlot: Component<AvailabilityTargetSlotProps> = (p
updateForm({ targetKind: event.currentTarget.value as AvailabilityTargetKind })
}
>
<option value="machine">Machine or server</option>
<option value="service">Service endpoint</option>
<option value="device">Device or controller</option>
<For each={AVAILABILITY_TARGET_KINDS}>
{(kind) => <option value={kind.value}>{kind.label}</option>}
</For>
</FormSelect>
<label class={formField}>
<span class={formLabel}>Name</span>
@@ -578,6 +597,25 @@ export const AvailabilityTargetSlot: Component<AvailabilityTargetSlotProps> = (p
placeholder={namePlaceholder()}
/>
</label>
<Show when={suggestedKind()}>
{(kind) => (
<p
class="flex flex-wrap items-center gap-x-3 gap-y-1 text-xs text-muted sm:col-span-2"
data-testid="availability-kind-suggestion"
>
<span>
This looks like your {kind().noun}. The map draws it as one when its type says so.
</span>
<Button
variant="outline"
size="settingsAction"
onClick={() => updateForm({ targetKind: kind().value })}
>
Use {kind().label}
</Button>
</p>
)}
</Show>
<FormSelect
label="Probe"
value={form().protocol}
@@ -122,7 +122,7 @@ describe('AvailabilityTargetSlot', () => {
it('starts from the name and address a link filled in, as a ping check to save', async () => {
render(() => (
<AvailabilityTargetSlot
initialTargetKind="device"
initialTargetKind="router"
initialName="Gateway"
initialAddress="192.168.0.1"
onCancel={vi.fn()}
@@ -131,8 +131,10 @@ describe('AvailabilityTargetSlot', () => {
));
expect(screen.getByLabelText('Name')).toHaveValue('Gateway');
expect(screen.getByLabelText('Target type')).toHaveValue('device');
expect(screen.getByLabelText('Target type')).toHaveValue('router');
expect(screen.getByDisplayValue('192.168.0.1')).toBeInTheDocument();
// Its type already says what it is, so nothing is offered.
expect(screen.queryByTestId('availability-kind-suggestion')).toBeNull();
// Nothing is saved until the owner says so.
expect(mockedCreate).not.toHaveBeenCalled();
@@ -141,7 +143,7 @@ describe('AvailabilityTargetSlot', () => {
expect(mockedCreate).toHaveBeenCalledWith(
expect.objectContaining({
name: 'Gateway',
targetKind: 'device',
targetKind: 'router',
address: '192.168.0.1',
protocol: 'icmp',
enabled: true,
@@ -150,6 +152,63 @@ describe('AvailabilityTargetSlot', () => {
);
});
it('offers every kind of thing a check can be on, in one list', () => {
render(() => <AvailabilityTargetSlot onCancel={vi.fn()} onSaved={vi.fn()} />);
const options = [...screen.getByLabelText('Target type').querySelectorAll('option')];
expect(options.map((option) => [option.value, option.textContent])).toEqual([
['service', 'Website or service'],
['machine', 'Machine or server'],
['router', 'Router or firewall'],
['switch', 'Switch'],
['access_point', 'Access point'],
['device', 'Other device'],
]);
});
it('offers network gear when the name says so, and changes nothing until asked', async () => {
render(() => <AvailabilityTargetSlot onCancel={vi.fn()} onSaved={vi.fn()} />);
expect(screen.queryByTestId('availability-kind-suggestion')).toBeNull();
fireEvent.input(screen.getByLabelText('Name'), { target: { value: 'Core switch' } });
// Offered, and the type is still what it was.
expect(screen.getByTestId('availability-kind-suggestion')).toHaveTextContent(
'This looks like your switch.',
);
expect(screen.getByLabelText('Target type')).toHaveValue('service');
fireEvent.click(screen.getByRole('button', { name: 'Use Switch' }));
expect(screen.getByLabelText('Target type')).toHaveValue('switch');
// Said once the type says it, the offer goes.
expect(screen.queryByTestId('availability-kind-suggestion')).toBeNull();
expect(screen.getByRole('button', { name: 'Add switch check' })).toBeInTheDocument();
});
it('offers a router for a check on a monitored machine’s default gateway', () => {
resourceMocks.resources = [
{
id: 'host-1',
type: 'agent',
name: 'tower',
agent: { defaultGateways: [{ address: '192.168.0.1' }] },
} as never,
];
render(() => (
<AvailabilityTargetSlot
initialName="Fritz"
initialAddress="192.168.0.1"
onCancel={vi.fn()}
onSaved={vi.fn()}
/>
));
expect(screen.getByTestId('availability-kind-suggestion')).toHaveTextContent(
'This looks like your router.',
);
expect(screen.getByRole('button', { name: 'Use Router or firewall' })).toBeInTheDocument();
});
it('starts machine add routes as machine reachability checks', async () => {
const onSaved = vi.fn();
render(() => (
@@ -278,6 +278,21 @@ describe('AvailabilitySettingsPanel', () => {
expect(prefilled).toHaveAttribute('data-initial-name', 'Gateway');
expect(prefilled).toHaveAttribute('data-initial-address', '192.168.0.1');
// The map's link: a router, and closing the form goes back to the map.
cleanup();
navigateSpy.mockClear();
routeState.search = '?add=target&targetKind=router&name=Gateway&address=192.168.0.1&from=map';
render(() => <AvailabilitySettingsPanel />);
await waitFor(() => expect(screen.getByTestId('availability-target-slot')).toBeInTheDocument());
expect(screen.getByRole('heading', { name: 'Add router check' })).toBeInTheDocument();
expect(screen.getByText(/draws it on the map as the device it is/)).toBeInTheDocument();
expect(screen.getByTestId('availability-target-slot')).toHaveAttribute(
'data-initial-target-kind',
'router',
);
fireEvent.click(screen.getByRole('button', { name: 'Mock save' }));
expect(navigateSpy).toHaveBeenLastCalledWith('/map', { replace: true });
cleanup();
routeState.search = '?add=target&targetKind=machine';
render(() => <AvailabilitySettingsPanel />);
@@ -88,6 +88,25 @@ describe('availabilitySettingsModel', () => {
address: 'fe80::1',
});
// The map says it sent the owner, by name. No address is read from a link.
const fromMap = buildAvailabilityTargetAddPath('router', {
name: 'Gateway',
address: '192.168.0.1',
from: 'map',
});
expect(fromMap).toBe(
'/settings/monitoring/availability?add=target&targetKind=router&name=Gateway&address=192.168.0.1&from=map',
);
expect(getAvailabilityTargetAddPrefill(pathname, `?${fromMap.split('?')[1]}`)).toEqual({
name: 'Gateway',
address: '192.168.0.1',
from: 'map',
});
expect(
getAvailabilityTargetAddPrefill(pathname, '?add=target&from=/evil').from,
).toBeUndefined();
expect(getAvailabilityTargetAddKind(pathname, `?${fromMap.split('?')[1]}`)).toBe('router');
// Nothing to fill in leaves the path as it was, and reads back as nothing.
expect(buildAvailabilityTargetAddPath('device', { name: ' ', address: '' })).toBe(
'/settings/monitoring/availability?add=target&targetKind=device',
@@ -1,5 +1,9 @@
import type { AvailabilityTarget, AvailabilityTargetKind } from '@/api/availabilityTargets';
import type { Resource } from '@/types/resource';
import {
getAvailabilityTargetKindInfo,
normalizeAvailabilityTargetKind,
} from '@/utils/availabilityTargetKinds';
import { getStandaloneResourceStatusIndicator } from '@/features/standalone/standalonePageModel';
import {
PROBE_AGENT_STALE_LABEL,
@@ -14,23 +18,13 @@ export const AVAILABILITY_ADD_TARGET_VALUE = 'target';
export const AVAILABILITY_TARGET_KIND_QUERY_PARAM = 'targetKind';
export const AVAILABILITY_TARGET_NAME_QUERY_PARAM = 'name';
export const AVAILABILITY_TARGET_ADDRESS_QUERY_PARAM = 'address';
export const AVAILABILITY_TARGET_FROM_QUERY_PARAM = 'from';
export function buildAvailabilitySettingsPath(): string {
return AVAILABILITY_SETTINGS_PATH;
}
const AVAILABILITY_TARGET_KIND_VALUES: readonly AvailabilityTargetKind[] = [
'machine',
'service',
'device',
];
export function normalizeAvailabilityTargetKind(
value: string | null | undefined,
): AvailabilityTargetKind | undefined {
const normalized = value?.trim().toLowerCase();
return AVAILABILITY_TARGET_KIND_VALUES.find((kind) => kind === normalized);
}
export { normalizeAvailabilityTargetKind };
/**
* What a link can fill in on the add-check form, for a thing another page
@@ -40,6 +34,12 @@ export function normalizeAvailabilityTargetKind(
export interface AvailabilityTargetAddPrefill {
name?: string;
address?: string;
/**
* The page that sent the owner here, when closing the form should take them
* back to it. Only the map does, and only by this name: no address is read
* from the link.
*/
from?: 'map';
}
// As long as a hostname can be. A longer value is not an address.
@@ -58,6 +58,7 @@ export function buildAvailabilityTargetAddPath(
if (name) params.set(AVAILABILITY_TARGET_NAME_QUERY_PARAM, name);
const address = prefill.address?.trim();
if (address) params.set(AVAILABILITY_TARGET_ADDRESS_QUERY_PARAM, address);
if (prefill.from === 'map') params.set(AVAILABILITY_TARGET_FROM_QUERY_PARAM, 'map');
return `${AVAILABILITY_SETTINGS_PATH}?${params.toString()}`;
}
@@ -71,7 +72,12 @@ export function getAvailabilityTargetAddPrefill(
params.get(key)?.trim().slice(0, AVAILABILITY_PREFILL_MAX_LENGTH) || undefined;
const name = read(AVAILABILITY_TARGET_NAME_QUERY_PARAM);
const address = read(AVAILABILITY_TARGET_ADDRESS_QUERY_PARAM);
return { ...(name ? { name } : {}), ...(address ? { address } : {}) };
const fromMap = params.get(AVAILABILITY_TARGET_FROM_QUERY_PARAM)?.trim() === 'map';
return {
...(name ? { name } : {}),
...(address ? { address } : {}),
...(fromMap ? { from: 'map' as const } : {}),
};
}
export function shouldOpenAvailabilityTargetAddDialog(pathname: string, search: string): boolean {
@@ -112,17 +118,9 @@ export function getAvailabilityTargetMethodLabel(target: AvailabilityTarget): st
}
export function getAvailabilityTargetKindLabel(target: AvailabilityTarget): string {
switch (target.targetKind) {
case 'machine':
return 'Machine';
case 'device':
return 'Device';
case 'service':
case undefined:
return 'Service';
default:
return 'Endpoint';
}
// A check saved before kinds existed is a service, as the server defaults it.
if (target.targetKind === undefined) return 'Service';
return getAvailabilityTargetKindInfo(target.targetKind)?.short ?? 'Endpoint';
}
export function getAvailabilityTargetAddressLabel(target: AvailabilityTarget): string {
@@ -52,6 +52,7 @@ import {
buildDockerPath,
buildKubernetesPath,
buildProxmoxPath,
buildAvailabilityCheckPath,
buildStandalonePath,
buildTrueNASPath,
buildVmwarePath,
@@ -256,9 +257,13 @@ export function AlertOverviewAlertCard(props: AlertOverviewAlertCardProps) {
const resourceLink = (): string => {
const storageLink = storagePoolLink();
if (storageLink) return storageLink;
const page = platformLink();
const metadata = props.alert.metadata;
const resourceType = metadata?.resourceType;
// An availability alert is about one check, and its page opens that
// check. Left to the platform rules below it landed on Proxmox.
const checkId = props.alert.resourceId?.trim();
if (resourceType === 'network-endpoint' && checkId) return buildAvailabilityCheckPath(checkId);
const page = platformLink();
// A per-filesystem alert names `<guest>-disk-<key>` and an orphaned backup
// names `backup-subject:...`; neither is a resource the registry can open.
// A filesystem alert that carries its guest's id opens that guest.
@@ -82,7 +82,13 @@ const UNMONITORED_CHECK_NAME = 'Gateway';
const hitLines = (hit: MapHit): string[] =>
[
hit.meta,
[hit.address, hit.detail ? `Published ${hit.detail}` : ''].filter(Boolean).join(' · '),
[
// A plain check's caption is its address, so the line above has said it.
hit.address && !hit.meta.includes(hit.address) ? hit.address : '',
hit.detail ? `Published ${hit.detail}` : '',
]
.filter(Boolean)
.join(' · '),
...(hit.links ?? []),
[
hit.cpu !== undefined ? `CPU ${Math.round(hit.cpu)}%` : '',
@@ -186,9 +192,10 @@ export function InfrastructureMapSurface() {
// A thing nothing monitors has no page. Its tile leads to the form that
// adds a check for it, which is the one thing there is to do about it.
if (hit?.checkAddress) {
return buildAvailabilityTargetAddPath('device', {
return buildAvailabilityTargetAddPath('router', {
name: UNMONITORED_CHECK_NAME,
address: hit.checkAddress,
from: 'map',
});
}
const resource = hit ? resourceById().get(hit.id) : undefined;
@@ -466,7 +473,7 @@ export function InfrastructureMapSurface() {
</li>
{/* How a thing gets onto the map is not something the map can show. */}
<li class="ml-auto">
Apps and network gear are recognised by name.{' '}
Apps are recognised by name, checks are drawn by their type.{' '}
<a href={MAP_DOC_URL} class="underline underline-offset-2 hover:text-base-content">
How the map works
</a>
@@ -338,7 +338,9 @@ describe('InfrastructureMapSurface connections', () => {
it('says how a thing gets onto the map, and links the guide that explains it', () => {
draw();
expect(screen.getByText(/Apps and network gear are recognised by name\./)).toBeTruthy();
expect(
screen.getByText(/Apps are recognised by name, checks are drawn by their type\./),
).toBeTruthy();
const guide = screen.getByRole('link', { name: 'How the map works' });
expect(guide.getAttribute('href')).toBe('/docs/MAP');
});
@@ -434,7 +436,7 @@ describe('InfrastructureMapSurface connections', () => {
describe('a gateway nothing monitors', () => {
const ADD_CHECK =
'/settings/monitoring/availability?add=target&targetKind=device&name=Gateway&address=192.168.0.1';
'/settings/monitoring/availability?add=target&targetKind=router&name=Gateway&address=192.168.0.1&from=map';
beforeEach(() => {
resourcesMock.value = [
resource({
@@ -169,6 +169,7 @@ const estate = (): Resource[] => [
type: 'network-endpoint',
name: 'opnsense-edge',
status: 'offline',
availability: { targetKind: 'router' },
}),
resource({ id: 'mini', type: 'agent', name: 'mini-pc', platformType: 'agent' }),
];
@@ -273,8 +274,8 @@ describe('buildInfrastructureMapModel', () => {
expect(checks.isResource).toBe(false);
expect(checks.health).toBe('critical');
expect(checks.sections[0].items.map((item) => item.name)).toEqual(['opnsense-edge']);
// Its name says what it is on, which is what the diagram draws it as.
expect(checks.sections[0].items[0].device).toBe('router');
// Its owner typed it a router, which is what the diagram draws it as.
expect(checks.sections[0].items[0].checkKind).toBe('router');
});
it('counts what it drew and what needs attention', () => {
@@ -380,7 +381,7 @@ describe('anonymizeInfrastructureMapModel', () => {
// A check on network gear keeps what it is on and loses what it was called.
expect(hostNamed(anonymous.blocks, 'Availability checks').sections[0].items[0]).toMatchObject({
name: 'Router 1',
device: 'router',
checkKind: 'router',
});
});
@@ -6,7 +6,6 @@ import {
resolveMapApp,
resolveMapAppLogo,
resolveMapCategory,
resolveMapDeviceRole,
} from '../infrastructureMapCatalogue';
import {
anonymizeInfrastructureMapModel,
@@ -434,56 +433,49 @@ describe('buildServiceDiagram', () => {
expect(drawn).not.toMatch(/delly|minipc|Tower|rstack|ps4|authentik|192\.168/);
});
it('knows network gear from what its owner called the check', () => {
for (const name of ['Router', 'OPNsense', 'pfsense-fw', 'FRITZ!Box 7590', 'UDM Pro']) {
expect(resolveMapDeviceRole(name)).toBe('router');
}
for (const name of ['Core switch', 'switch-24-rack', 'USW_Switch_8']) {
expect(resolveMapDeviceRole(name)).toBe('switch');
}
for (const name of ['AP living room', 'ap-garage', 'Wi-Fi upstairs', 'Access Point 2']) {
expect(resolveMapDeviceRole(name)).toBe('access-point');
}
// A wireless router is the router. A word inside another word is not it.
expect(resolveMapDeviceRole('Router AP')).toBe('router');
for (const name of ['Status page', 'API gateway', 'Nintendo Switch', 'apt-cache', 'Grafana']) {
expect(resolveMapDeviceRole(name)).toBeUndefined();
}
});
it('draws a check on network gear as that gear, with the ways in', () => {
const check = (id: string, name: string, address: string): Resource =>
const check = (id: string, name: string, address: string, targetKind: string): Resource =>
resource({
id,
type: 'network-endpoint',
name,
platformType: 'availability',
availability: { address },
availability: { address, targetKind },
} as Parameters<typeof resource>[0]);
const resources = [
...homelab(),
check('check-switch', 'Core switch', '192.168.10.2'),
check('check-ap', 'AP living room', '192.168.10.3'),
check('check-fw', 'OPNsense', '192.168.10.1'),
check('check-site', 'Status page', 'status.example.test'),
// Named for nothing a switch is called: the type its owner chose decides.
check('check-switch', 'usw-24-rack', '192.168.10.2', 'switch'),
check('check-ap', 'Living room', '192.168.10.3', 'access_point'),
check('check-fw', 'Edge', '192.168.10.1', 'router'),
check('check-nas', 'old-nas', '192.168.10.9', 'machine'),
// And a name alone decides nothing.
check('check-site', 'Router admin page', '192.168.10.80', 'service'),
check('check-ups', 'Rack UPS', '192.168.10.81', 'device'),
];
const diagram = diagramOf(resources);
const gear = (diagram.access?.tiles ?? []).filter((tile) => tile.id.startsWith('check-'));
expect(gear.map((tile) => [tile.name, tile.caption, tile.platform])).toEqual([
['AP living room', 'access point', 'access-point'],
['Core switch', 'switch', 'switch'],
['OPNsense', 'router', 'gateway'],
['Edge', 'router', 'gateway'],
['Living room', 'access point', 'access-point'],
['usw-24-rack', 'switch', 'switch'],
]);
// Each opens its check, and keeps its address for the hover.
expect(gear.every((tile) => tile.navigable && tile.typeLabel === 'Check')).toBe(true);
expect(gear.map((tile) => tile.address)).toEqual([
'192.168.10.1',
'192.168.10.3',
'192.168.10.2',
'192.168.10.1',
]);
// A check on anything else stays a check.
expect(names(diagram.groups.find((group) => group.key === 'checks'))).toEqual(['Status page']);
// A check on anything else stays a check, whatever it is called. That
// includes a machine: only a Pulse agent makes a machine.
expect(names(diagram.groups.find((group) => group.key === 'checks'))).toEqual([
'old-nas',
'Rack UPS',
'Router admin page',
]);
expect(diagram.hardware?.tiles.some((tile) => tile.id === 'check-nas')).toBe(false);
// With names hidden it is the same gear in the same box.
const hidden = buildServiceDiagram(
@@ -498,7 +490,11 @@ describe('buildServiceDiagram', () => {
['Router 1', 'router'],
['Switch 1', 'switch'],
]);
expect(names(hidden.groups.find((group) => group.key === 'checks'))).toEqual(['Check 1']);
expect(names(hidden.groups.find((group) => group.key === 'checks'))).toEqual([
'Check 1',
'Check 2',
'Check 3',
]);
});
it('counts what each box holds and gives probed endpoints a box of their own', () => {
@@ -690,14 +686,14 @@ describe('buildServiceDiagram', () => {
id: 'check-router',
type: 'network-endpoint',
name: 'Gateway',
availability: { address: '192.168.0.1' },
// What the map's own link to the form sets.
availability: { address: '192.168.0.1', targetKind: 'router' },
} as Parameters<typeof resource>[0]),
]),
);
// Monitored now, so nothing says it is not. A check on a machine's
// default gateway is on the router whatever it is called, so it is
// drawn as one, where the dashed tile was.
// Monitored now, so nothing says it is not, and typed as a router, so
// it is drawn as one where the dashed tile was.
expect(diagram.gateways).toEqual([]);
expect(diagram.access?.tiles.map((tile) => tile.id)).toEqual(['check-router']);
expect(tileOf(diagram, 'check-router')).toMatchObject({
@@ -425,55 +425,3 @@ export const resolveMapCategory = (
}
return 'other';
};
/** The network gear an availability check can be recognised as. */
export type MapDeviceRole = 'router' | 'switch' | 'access-point';
export const MAP_DEVICE_ROLE_LABEL: Record<MapDeviceRole, string> = {
router: 'Router',
switch: 'Switch',
'access-point': 'Access point',
};
// Words an owner gives the thing, and the systems a router runs. `gateway`
// is left out: an API gateway and a mail gateway are checked too, and a
// check on a real default gateway is known by its address.
const ROUTER_WORDS = new Set([
'router',
'firewall',
'modem',
'opnsense',
'pfsense',
'mikrotik',
'routeros',
'edgerouter',
'openwrt',
'fritzbox',
'udm',
'usg',
]);
const SWITCH_WORDS = new Set(['switch', 'switches']);
const ACCESS_POINT_WORDS = new Set(['ap', 'aps', 'wifi', 'wlan', 'accesspoint']);
// A console is not network gear, whatever it is called.
const NOT_GEAR_WORDS = new Set(['nintendo', 'kvm']);
/**
* The network gear a check is on, from its name, the way an app is known
* from its container's. It decides the tile's glyph and box and nothing
* else, and a name that says none of these is left a plain check.
*/
export const resolveMapDeviceRole = (name: string): MapDeviceRole | undefined => {
const words = name
.toLowerCase()
.replace(/wi-fi/g, 'wifi')
// FRITZ!Box is one word to its owner.
.replace(/!/g, '')
.replace(/access[\s_-]*points?/g, 'accesspoint')
.split(/[^a-z0-9]+/)
.filter(Boolean);
if (words.some((word) => NOT_GEAR_WORDS.has(word))) return undefined;
if (words.some((word) => ROUTER_WORDS.has(word))) return 'router';
if (words.some((word) => SWITCH_WORDS.has(word))) return 'switch';
if (words.some((word) => ACCESS_POINT_WORDS.has(word))) return 'access-point';
return undefined;
};
@@ -1,13 +1,13 @@
import type { Resource, ResourceType } from '@/types/resource';
import { getDiskPercent, getMemoryPercent } from '@/types/resource';
import { formatBytes } from '@/utils/format';
import type { AvailabilityTargetKind } from '@/api/availabilityTargets';
import { normalizeAvailabilityTargetKind } from '@/utils/availabilityTargetKinds';
import {
resolveMapApp,
resolveMapCategory,
resolveMapDeviceRole,
type MapApp,
type MapCategoryId,
type MapDeviceRole,
} from './infrastructureMapCatalogue';
import { resolveMapConnections, type MapConnections } from './infrastructureMapConnections';
import {
@@ -55,8 +55,12 @@ export interface MapItem {
app?: MapApp;
/** The group a guest or container is drawn in on the service diagram. */
category?: MapCategoryId;
/** The network gear a check is on, when its name or its address says so. */
device?: MapDeviceRole;
/**
* What an availability check is on, as its owner typed it. The map reads
* the kind and never works one out: a router, switch or access point is
* drawn as that device, and every other kind as a check.
*/
checkKind?: AvailabilityTargetKind;
}
export interface MapSection {
@@ -177,11 +181,11 @@ const SYSTEM_CONTAINER_LABEL = 'System container';
const itemStandIn = (typeLabel: string): string =>
typeLabel === SYSTEM_CONTAINER_LABEL ? 'Container' : typeLabel;
/** And for network gear, which stays the gear it is with its name hidden. */
const DEVICE_STAND_IN: Record<MapDeviceRole, string> = {
/** And for a check, which stays what it is on with its name hidden. */
const CHECK_STAND_IN: Partial<Record<AvailabilityTargetKind, string>> = {
router: 'Router',
switch: 'Switch',
'access-point': 'AP',
access_point: 'AP',
};
const GROUP_TYPE_LABEL: Partial<Record<MapPlatform, string>> = {
@@ -429,8 +433,11 @@ export function buildInfrastructureMapModel(
for (const resource of resources) {
if (drafts.has(resource.id)) continue;
if (resource.type === 'network-endpoint') {
const device = resolveMapDeviceRole(displayName(resource));
checks.push({ ...toItem(resource, 'Check', attachments), ...(device ? { device } : {}) });
const checkKind = normalizeAvailabilityTargetKind(resource.availability?.targetKind);
checks.push({
...toItem(resource, 'Check', attachments),
...(checkKind ? { checkKind } : {}),
});
continue;
}
const draft = owningDraft(resource);
@@ -539,13 +546,6 @@ export function buildInfrastructureMapModel(
},
});
}
const connections = ownedConnections(resources, attachments);
// A check that probes a machine's default gateway is on the router,
// whatever its owner called it.
const gatewayOwners = new Set(connections.gateways.map((gateway) => gateway.resourceId));
for (const check of checks) {
if (!check.device && gatewayOwners.has(check.id)) check.device = 'router';
}
if (checks.length > 0) {
checks.sort(byName);
blocks.push({
@@ -565,7 +565,7 @@ export function buildInfrastructureMapModel(
});
}
return summarize(blocks, networks.segments, connections);
return summarize(blocks, networks.segments, ownedConnections(resources, attachments));
}
// A gateway or resolver address that exactly one thing on the map answers on
@@ -703,7 +703,7 @@ export function anonymizeInfrastructureMapModel(
? item.app.label
: nameFor(
item.id,
item.device ? DEVICE_STAND_IN[item.device] : itemStandIn(item.typeLabel),
(item.checkKind && CHECK_STAND_IN[item.checkKind]) || itemStandIn(item.typeLabel),
),
}));
const anonymizeHost = ({ address: _address, ...host }: MapHost): MapHost => ({
@@ -1,10 +1,13 @@
import {
getAvailabilityTargetKindInfo,
isNetworkGearKind,
type AvailabilityNetworkGearKind,
} from '@/utils/availabilityTargetKinds';
import {
MAP_CATEGORY_LABEL,
MAP_CATEGORY_ORDER,
MAP_DEVICE_ROLE_LABEL,
type MapAppRole,
type MapCategoryId,
type MapDeviceRole,
} from './infrastructureMapCatalogue';
import { mapRouteLabel } from './infrastructureMapConnections';
import type { MapGlyphKey } from './infrastructureMapLayout';
@@ -295,22 +298,22 @@ const serviceTile = (item: MapItem, host: MapHost, plan: NetworkPlan): DiagramTi
navigable: true,
});
const DEVICE_GLYPH: Record<MapDeviceRole, MapGlyphKey> = {
const GEAR_GLYPH: Record<AvailabilityNetworkGearKind, MapGlyphKey> = {
router: 'gateway',
switch: 'switch',
'access-point': 'access-point',
access_point: 'access-point',
};
// A check on a router, a switch or an access point. It is drawn as the
// device and says which, where a plain check says its address.
const deviceTile = (item: MapItem, device: MapDeviceRole): DiagramTile => ({
const gearTile = (item: MapItem, kind: AvailabilityNetworkGearKind): DiagramTile => ({
id: item.id,
name: item.name,
caption: MAP_DEVICE_ROLE_LABEL[device].toLowerCase(),
caption: getAvailabilityTargetKindInfo(kind)?.noun ?? kind,
typeLabel: item.typeLabel,
status: item.status,
health: item.health,
platform: DEVICE_GLYPH[device],
platform: GEAR_GLYPH[kind],
address: item.address,
navigable: true,
});
@@ -426,16 +429,18 @@ export function buildServiceDiagram(
}
}
serviceCount += services;
// What Pulse probes from outside (a router, a site) is not a service on
// What Pulse probes from outside (a site, a printer) is not a service on
// any host here, so each check is a tile in a box of its own. Network
// gear is the exception: it is how traffic gets in and around, so it
// sits with the ways in, where an unmonitored gateway is drawn too.
// sits with the ways in, where an unmonitored gateway is drawn too. A
// machine check stays a check here as it does everywhere: only a Pulse
// agent makes a machine.
if (host.platform === 'checks' && !host.isResource) {
for (const section of host.sections) {
for (const item of section.items) {
if (item.device) {
if (isNetworkGearKind(item.checkKind)) {
const list = byCategory.get('access') ?? [];
list.push(deviceTile(item, item.device));
list.push(gearTile(item, item.checkKind));
byCategory.set('access', list);
continue;
}
@@ -229,7 +229,8 @@ describe('buildResourcePagePath', () => {
sources: ['availability' as never],
}),
}),
).toBe('/standalone/availability');
// That check, not the list it is in.
).toBe('/standalone/availability?view=table&check=endpoint-1');
});
it('opens the thresholds tab that holds a resource, searched to its name', () => {
expect(buildResourceThresholdsPath({ id: 'c-1', name: 'nginx', type: 'app-container' })).toBe(
@@ -4,6 +4,7 @@ import {
buildDockerPath,
buildKubernetesPath,
buildProxmoxPath,
buildAvailabilityCheckPath,
buildStandalonePath,
buildStorageRouteSearch,
buildTrueNASPath,
@@ -239,7 +240,9 @@ export function buildResourcePagePath(subject: ResourcePageSubject): string | nu
const isNetwork = NETWORK_TYPES.has(type) || NETWORK_TYPES.has(hintType);
// Availability checks are endpoints Pulse probes, listed beside Machines.
if (type === 'network-endpoint') return buildStandalonePath('availability');
if (type === 'network-endpoint') {
return id ? buildAvailabilityCheckPath(id) : buildStandalonePath('availability');
}
switch (platform) {
case 'proxmox':
@@ -23,6 +23,7 @@ const RESOURCE_FOCUS_PARAMS: ReadonlySet<string> = new Set([
DOCKER_QUERY_PARAMS.query,
KUBERNETES_QUERY_PARAMS.query,
STANDALONE_QUERY_PARAMS.query,
STANDALONE_QUERY_PARAMS.check,
]);
/**
@@ -2,6 +2,7 @@ import { useRelativeTimeNow } from '@/utils/relativeTimeClock';
import { A } from '@solidjs/router';
import {
Show,
createEffect,
createMemo,
createResource,
onCleanup,
@@ -117,6 +118,8 @@ export const AvailabilityChecksTable: Component<{
probeAgentOptions?: readonly ProbeAgentOption[];
view?: AvailabilityChecksView;
onViewChange?: (view: AvailabilityChecksView) => void;
/** A check a link asked for by id: its detail opens once it has loaded. */
focusCheckId?: string;
externalSearch?: () => string;
onExternalSearchChange?: (value: string) => void;
externalStatus?: () => PlatformResourceStatusFilter;
@@ -146,9 +149,15 @@ export const AvailabilityChecksTable: Component<{
}
tableState.resetFilters();
};
const orderedChecks = createMemo(() =>
sortStandaloneResourcesByAttention(tableState.filtered(), now()),
);
const orderedChecks = createMemo(() => {
const sorted = sortStandaloneResourcesByAttention(tableState.filtered(), now());
// A check a link asked for leads the table, so its row is on screen and
// inside the window of rows that are drawn at all.
const asked = props.focusCheckId;
const index = asked ? sorted.findIndex((resource) => resource.id === asked) : -1;
if (index <= 0) return sorted;
return [sorted[index], ...sorted.slice(0, index), ...sorted.slice(index + 1)];
});
const historyTargetIDs = createMemo(() =>
props.resources
.map((resource) => availabilityFor(resource)?.targetId)
@@ -184,6 +193,33 @@ export const AvailabilityChecksTable: Component<{
);
const drawer = createPlatformResourceDetailState({ idPrefix: 'availability-check-detail' });
const resolveResourceLabel = createPlatformResourceLabelResolver(() => props.resources);
// A link from the map or an alert names one check. Open it once, when it
// has arrived, and leave the owner free to close it afterwards.
let focusedCheckId = '';
createEffect(() => {
const id = props.focusCheckId;
if (!id) {
// The link is gone from the address, so the same one can be followed again.
focusedCheckId = '';
return;
}
if (id === focusedCheckId) return;
// Only a check among the rows shown has a detail to open. One a filter
// hides waits here until the filter lets it through.
const check = orderedChecks().find((resource) => resource.id === id);
if (!check) return;
focusedCheckId = id;
drawer.open(check);
// It leads the table, so the top of the table is where it is. A page
// that was already scrolled is brought back there, where its row is
// among the ones drawn.
queueMicrotask(() => {
document
.querySelector('[data-availability-check-row]')
?.closest('table')
?.scrollIntoView?.({ block: 'start' });
});
});
return (
<Show
@@ -186,6 +186,10 @@ export function StandalonePageSurface() {
model().availabilityChecks.length,
),
);
const focusedCheckId = createMemo(() => {
const value = searchParams[STANDALONE_QUERY_PARAMS.check];
return (Array.isArray(value) ? value[0] : value)?.trim() || undefined;
});
const setAvailabilityView = (view: AvailabilityChecksView) => {
setSearchParams({ [STANDALONE_QUERY_PARAMS.view]: view }, { replace: true });
};
@@ -287,6 +291,7 @@ export function StandalonePageSurface() {
probeAgentOptions={buildProbeAgentOptions(model().machines)}
view={availabilityView()}
onViewChange={setAvailabilityView}
focusCheckId={focusedCheckId()}
externalSearch={machineSearchFilter}
onExternalSearchChange={setMachineSearchFilter}
externalStatus={machineStatusFilter}
@@ -43,7 +43,11 @@ const availabilityResource = (overrides: Partial<Resource> = {}): Resource =>
...overrides,
}) as Resource;
const renderTable = (resources: Resource[], probeAgentOptions?: ProbeAgentOption[]) =>
const renderTable = (
resources: Resource[],
probeAgentOptions?: ProbeAgentOption[],
focusCheckId?: string,
) =>
render(() => (
<Router>
<Route
@@ -55,6 +59,7 @@ const renderTable = (resources: Resource[], probeAgentOptions?: ProbeAgentOption
emptyTitle="No checks"
emptyDescription="Add checks"
probeAgentOptions={probeAgentOptions}
focusCheckId={focusCheckId}
/>
)}
/>
@@ -131,6 +136,25 @@ describe('AvailabilityChecksTable', () => {
).not.toBeNull();
});
it('opens the detail of the check a link asked for, and no other', () => {
const asked = availabilityResource();
const other = availabilityResource({ id: 'availability:other', name: 'Other check' });
const { container } = renderTable([other, asked], undefined, asked.id);
const open = [...container.querySelectorAll('[data-inline-platform-resource-detail-for]')];
expect(
open.map((node) => node.getAttribute('data-inline-platform-resource-detail-for')),
).toEqual([asked.id]);
// The owner can close it: the link opens it once and does not hold it open.
fireEvent.click(screen.getByRole('button', { name: `Collapse details for ${asked.name}` }));
expect(container.querySelector('[data-inline-platform-resource-detail-for]')).toBeNull();
});
it('opens nothing for a link that names no check on the page', () => {
const { container } = renderTable([availabilityResource()], undefined, 'availability:gone');
expect(container.querySelector('[data-inline-platform-resource-detail-for]')).toBeNull();
});
it('places failing checks before healthy checks by default', () => {
const view = renderTable([
availabilityResource({ id: 'healthy', name: 'Healthy', displayName: 'Healthy' }),
@@ -46,6 +46,7 @@ import {
STANDALONE_DEFAULT_TAB,
STANDALONE_PATH,
STANDALONE_QUERY_PARAMS,
buildAvailabilityCheckPath,
TRUENAS_PATH,
VMWARE_PATH,
buildPatrolControlPath,
@@ -189,7 +190,16 @@ describe('resource link routing contract', () => {
it('builds canonical Machines, container runtime, Kubernetes, TrueNAS, and vSphere tab paths', () => {
expect(STANDALONE_PATH).toBe('/standalone');
expect(STANDALONE_DEFAULT_TAB).toBe('machines');
expect(STANDALONE_QUERY_PARAMS).toEqual({ query: 'q', status: 'status', view: 'view' });
expect(STANDALONE_QUERY_PARAMS).toEqual({
query: 'q',
status: 'status',
view: 'view',
check: 'check',
});
// One check's detail, on the table that holds it.
expect(buildAvailabilityCheckPath('availability:router 1')).toBe(
'/standalone/availability?view=table&check=availability%3Arouter+1',
);
expect(buildStandalonePath()).toBe('/standalone/machines');
expect(buildStandalonePath('')).toBe('/standalone');
@@ -20,7 +20,21 @@ export const STANDALONE_QUERY_PARAMS = {
query: 'q',
status: 'status',
view: 'view',
/** The availability check whose detail a link opens. */
check: 'check',
} as const;
/**
* The Availability checks page with one check's detail open. The table is
* named, because the detail is a row of it and a large estate opens on the
* fleet view.
*/
export const buildAvailabilityCheckPath = (checkId: string): string => {
const params = new URLSearchParams();
params.set(STANDALONE_QUERY_PARAMS.view, 'table');
params.set(STANDALONE_QUERY_PARAMS.check, checkId);
return `${STANDALONE_PATH}/availability?${params.toString()}`;
};
export const PROXMOX_PATH = '/proxmox';
export const PROXMOX_DEFAULT_TAB = 'overview';
export const PROXMOX_BACKUPS_PATH = `${PROXMOX_PATH}/backups`;
@@ -0,0 +1,89 @@
import { describe, expect, it } from 'vitest';
import {
AVAILABILITY_TARGET_KINDS,
AVAILABILITY_TARGET_KIND_VALUES,
getAvailabilityTargetAddLabel,
getAvailabilityTargetKindInfo,
isNetworkGearKind,
normalizeAvailabilityTargetKind,
suggestAvailabilityTargetKind,
} from '../availabilityTargetKinds';
describe('availability target kinds', () => {
it('names every kind the server accepts, once, for every page that shows one', () => {
expect(AVAILABILITY_TARGET_KIND_VALUES).toEqual([
'service',
'machine',
'router',
'switch',
'access_point',
'device',
]);
expect(AVAILABILITY_TARGET_KINDS.map((kind) => kind.label)).toEqual([
'Website or service',
'Machine or server',
'Router or firewall',
'Switch',
'Access point',
'Other device',
]);
expect(getAvailabilityTargetKindInfo(' Access_Point ')?.noun).toBe('access point');
expect(getAvailabilityTargetKindInfo('database')).toBeUndefined();
expect(normalizeAvailabilityTargetKind('Machine')).toBe('machine');
expect(normalizeAvailabilityTargetKind('vm')).toBeUndefined();
});
it('knows which kinds are network gear', () => {
expect(AVAILABILITY_TARGET_KIND_VALUES.filter((kind) => isNetworkGearKind(kind))).toEqual([
'router',
'switch',
'access_point',
]);
expect(isNetworkGearKind(undefined)).toBe(false);
});
it('words the button that saves a new check after what the check is on', () => {
expect(getAvailabilityTargetAddLabel('machine')).toBe('Add machine check');
expect(getAvailabilityTargetAddLabel('router')).toBe('Add router check');
expect(getAvailabilityTargetAddLabel('access_point')).toBe('Add access point check');
expect(getAvailabilityTargetAddLabel('service')).toBe('Add service/device check');
expect(getAvailabilityTargetAddLabel('device')).toBe('Add service/device check');
expect(getAvailabilityTargetAddLabel(undefined)).toBe('Add availability check');
});
it('suggests network gear from what the owner called the check', () => {
const suggest = (name: string) => suggestAvailabilityTargetKind({ name });
for (const name of ['Router', 'OPNsense', 'pfsense-fw', 'FRITZ!Box 7590', 'UDM Pro']) {
expect(suggest(name)).toBe('router');
}
for (const name of ['Core switch', 'switch-24-rack', 'USW_Switch_8']) {
expect(suggest(name)).toBe('switch');
}
for (const name of ['AP living room', 'ap-garage', 'Wi-Fi upstairs', 'Access Point 2']) {
expect(suggest(name)).toBe('access_point');
}
// A wireless router is the router. A word inside another word is not it.
expect(suggest('Router AP')).toBe('router');
for (const name of ['Status page', 'API gateway', 'Nintendo Switch', 'apt-cache', 'Grafana']) {
expect(suggest(name)).toBeUndefined();
}
});
it('suggests a router for a check on a default gateway, whatever it is called', () => {
const gatewayAddresses = new Set(['192.168.0.1']);
expect(
suggestAvailabilityTargetKind({ name: 'Fritz', address: ' 192.168.0.1 ', gatewayAddresses }),
).toBe('router');
expect(
suggestAvailabilityTargetKind({ name: 'Fritz', address: '192.168.0.9', gatewayAddresses }),
).toBeUndefined();
// A name that says otherwise is not overruled by the address.
expect(
suggestAvailabilityTargetKind({
name: 'Core switch',
address: '192.168.0.1',
gatewayAddresses,
}),
).toBe('switch');
});
});
@@ -107,10 +107,11 @@ describe('docsLinks', () => {
);
});
it('publishes the API and metrics history references exactly as written', () => {
it('publishes the API, configuration and metrics history references exactly as written', () => {
// The in-app docs serve these copies; the history route's accepted
// resourceType list must not differ between the two.
for (const guide of ['API.md', 'METRICS_HISTORY.md']) {
// resourceType list and the availability check types an API client may
// send must not differ between the two.
for (const guide of ['API.md', 'CONFIGURATION.md', 'METRICS_HISTORY.md']) {
expect(readFileSync(path.join(frontendRoot, 'public/docs', guide), 'utf8')).toBe(
readFileSync(path.join(repoRoot, 'docs', guide), 'utf8'),
);
@@ -0,0 +1,165 @@
import type { AvailabilityTargetKind } from '@/api/availabilityTargets';
/**
* What an availability check is on. The kind is the owner's statement of what
* the thing is, stored with the check, and it is the one place every surface
* reads: the form that sets it, the lists that name it and the map, which
* draws network gear as gear. No surface works a kind out for itself. A
* `machine` check is still a check: only a Pulse agent makes a Machines row.
*/
export interface AvailabilityTargetKindInfo {
value: AvailabilityTargetKind;
/** The choice in the form. */
label: string;
/** For a list or a badge. */
short: string;
/** In a sentence, a button or under a map tile. */
noun: string;
namePlaceholder: string;
addressPlaceholder: string;
}
export const AVAILABILITY_TARGET_KINDS: readonly AvailabilityTargetKindInfo[] = [
{
value: 'service',
label: 'Website or service',
short: 'Service',
noun: 'service',
namePlaceholder: 'mqtt-broker',
addressPlaceholder: 'service.local',
},
{
value: 'machine',
label: 'Machine or server',
short: 'Machine',
noun: 'machine',
namePlaceholder: 'mac-mini',
addressPlaceholder: 'server.local',
},
{
value: 'router',
label: 'Router or firewall',
short: 'Router',
noun: 'router',
namePlaceholder: 'router',
addressPlaceholder: '192.168.1.1',
},
{
value: 'switch',
label: 'Switch',
short: 'Switch',
noun: 'switch',
namePlaceholder: 'core-switch',
addressPlaceholder: 'switch.local',
},
{
value: 'access_point',
label: 'Access point',
short: 'Access point',
noun: 'access point',
namePlaceholder: 'ap-living-room',
addressPlaceholder: 'ap.local',
},
{
value: 'device',
label: 'Other device',
short: 'Device',
noun: 'device',
namePlaceholder: 'energy-monitor',
addressPlaceholder: 'device.local',
},
];
const KIND_BY_VALUE = new Map(AVAILABILITY_TARGET_KINDS.map((kind) => [kind.value, kind]));
export const AVAILABILITY_TARGET_KIND_VALUES: readonly AvailabilityTargetKind[] =
AVAILABILITY_TARGET_KINDS.map((kind) => kind.value);
/** The kind a stored or typed value names, or nothing when it names none. */
export function normalizeAvailabilityTargetKind(
value: string | null | undefined,
): AvailabilityTargetKind | undefined {
const normalized = value?.trim().toLowerCase();
return AVAILABILITY_TARGET_KIND_VALUES.find((kind) => kind === normalized);
}
export const getAvailabilityTargetKindInfo = (
value: string | null | undefined,
): AvailabilityTargetKindInfo | undefined => {
const kind = normalizeAvailabilityTargetKind(value);
return kind ? KIND_BY_VALUE.get(kind) : undefined;
};
export type AvailabilityNetworkGearKind = 'router' | 'switch' | 'access_point';
/** A router, a switch or an access point: what a network is made of. */
export const isNetworkGearKind = (
value: string | null | undefined,
): value is AvailabilityNetworkGearKind => {
const kind = normalizeAvailabilityTargetKind(value);
return kind === 'router' || kind === 'switch' || kind === 'access_point';
};
// Words an owner gives the thing, and the systems a router runs. `gateway`
// is left out: an API gateway and a mail gateway are checked too, and a
// check on a real default gateway is known by its address.
const ROUTER_WORDS = new Set([
'router',
'firewall',
'modem',
'opnsense',
'pfsense',
'mikrotik',
'routeros',
'edgerouter',
'openwrt',
'fritzbox',
'udm',
'usg',
]);
const SWITCH_WORDS = new Set(['switch', 'switches']);
const ACCESS_POINT_WORDS = new Set(['ap', 'aps', 'wifi', 'wlan', 'accesspoint']);
// A console is not network gear, whatever it is called.
const NOT_GEAR_WORDS = new Set(['nintendo', 'kvm']);
export interface AvailabilityTargetKindSubject {
name?: string;
address?: string;
/** Addresses that monitored machines use as their default gateway. */
gatewayAddresses?: ReadonlySet<string>;
}
/**
* The network gear a check looks like it is on, to offer in the form. It is
* a suggestion and nothing reads it but the form: the owner takes it or
* leaves it, and what they save is the kind. Whole words only, so
* `apt-cache` is no access point.
*/
export const suggestAvailabilityTargetKind = (
subject: AvailabilityTargetKindSubject,
): AvailabilityNetworkGearKind | undefined => {
const words = (subject.name ?? '')
.toLowerCase()
.replace(/wi-fi/g, 'wifi')
// FRITZ!Box is one word to its owner.
.replace(/!/g, '')
.replace(/access[\s_-]*points?/g, 'accesspoint')
.split(/[^a-z0-9]+/)
.filter(Boolean);
if (!words.some((word) => NOT_GEAR_WORDS.has(word))) {
if (words.some((word) => ROUTER_WORDS.has(word))) return 'router';
if (words.some((word) => SWITCH_WORDS.has(word))) return 'switch';
if (words.some((word) => ACCESS_POINT_WORDS.has(word))) return 'access_point';
}
const address = subject.address?.trim();
if (address && subject.gatewayAddresses?.has(address)) return 'router';
return undefined;
};
/** The words on the button that saves a new check of this kind. */
export const getAvailabilityTargetAddLabel = (value: string | null | undefined): string => {
const kind = normalizeAvailabilityTargetKind(value);
if (kind === 'service' || kind === 'device') return 'Add service/device check';
const info = kind ? KIND_BY_VALUE.get(kind) : undefined;
return info ? `Add ${info.noun} check` : 'Add availability check';
};
+24 -4
View File
@@ -98,12 +98,31 @@ const (
type AvailabilityTargetKind string
// What a check is on. The kind is the owner's statement of what the thing
// is, and every surface that shows a check reads it: the settings form, the
// lists and the map, which draws network gear as gear with the ways in.
// Nothing infers it from a name. A machine kind is wording only: it never
// makes an agentless target a Machines row.
const (
AvailabilityTargetMachine AvailabilityTargetKind = "machine"
AvailabilityTargetService AvailabilityTargetKind = "service"
AvailabilityTargetDevice AvailabilityTargetKind = "device"
AvailabilityTargetMachine AvailabilityTargetKind = "machine"
AvailabilityTargetService AvailabilityTargetKind = "service"
AvailabilityTargetDevice AvailabilityTargetKind = "device"
AvailabilityTargetRouter AvailabilityTargetKind = "router"
AvailabilityTargetSwitch AvailabilityTargetKind = "switch"
AvailabilityTargetAccessPoint AvailabilityTargetKind = "access_point"
)
// IsNetworkGear reports whether the kind is a router, a switch or an access
// point: the things a network is made of, as opposed to things on it.
func (k AvailabilityTargetKind) IsNetworkGear() bool {
switch k {
case AvailabilityTargetRouter, AvailabilityTargetSwitch, AvailabilityTargetAccessPoint:
return true
default:
return false
}
}
// AvailabilityTarget represents an agentless endpoint monitored through a
// lightweight availability probe.
type AvailabilityTarget struct {
@@ -342,7 +361,8 @@ func (t AvailabilityTarget) Validate() error {
return fmt.Errorf("availability target address is required")
}
switch t.TargetKind {
case AvailabilityTargetMachine, AvailabilityTargetService, AvailabilityTargetDevice:
case AvailabilityTargetMachine, AvailabilityTargetService, AvailabilityTargetDevice,
AvailabilityTargetRouter, AvailabilityTargetSwitch, AvailabilityTargetAccessPoint:
default:
return fmt.Errorf("unsupported availability target kind %q", t.TargetKind)
}
+35
View File
@@ -190,6 +190,41 @@ func TestAvailabilityTargetValidateAcceptsPingAlias(t *testing.T) {
}
}
func TestAvailabilityTargetValidateAcceptsEveryTargetKind(t *testing.T) {
gear := map[AvailabilityTargetKind]bool{
AvailabilityTargetRouter: true,
AvailabilityTargetSwitch: true,
AvailabilityTargetAccessPoint: true,
}
for _, kind := range []AvailabilityTargetKind{
AvailabilityTargetMachine,
AvailabilityTargetService,
AvailabilityTargetDevice,
AvailabilityTargetRouter,
AvailabilityTargetSwitch,
AvailabilityTargetAccessPoint,
} {
target := NewAvailabilityTarget()
target.Name = "thing"
target.Address = "192.168.0.1"
target.TargetKind = kind
if err := target.Validate(); err != nil {
t.Fatalf("Validate() with kind %q = %v, want nil", kind, err)
}
if got := kind.IsNetworkGear(); got != gear[kind] {
t.Fatalf("%q.IsNetworkGear() = %v, want %v", kind, got, gear[kind])
}
}
// A kind arrives from the API in any case and is stored in one.
spelled := NewAvailabilityTarget()
spelled.Address = "192.168.0.3"
spelled.TargetKind = AvailabilityTargetKind(" Access_Point ")
if got := NormalizeAvailabilityTarget(spelled).TargetKind; got != AvailabilityTargetAccessPoint {
t.Fatalf("normalized kind = %q, want %q", got, AvailabilityTargetAccessPoint)
}
}
func TestAvailabilityTargetValidateRejectsUnsupportedTargetKind(t *testing.T) {
target := NormalizeAvailabilityTarget(AvailabilityTarget{
TargetKind: AvailabilityTargetKind("database"),
@@ -382,6 +382,18 @@ func (m *Monitor) availabilityProbeTargetsForAgent(hostID string) []map[string]i
return assigned
}
// availabilityProbeAgentTargetKind is the kind an agent is told. An agent
// validates the kind before it probes and does nothing else with it, and an
// agent older than the router, switch and access-point kinds rejects them and
// reports the check unreachable without sending a packet. Those three are
// devices to it; the saved kind stays on the server, where every reader is.
func availabilityProbeAgentTargetKind(kind config.AvailabilityTargetKind) config.AvailabilityTargetKind {
if kind.IsNetworkGear() {
return config.AvailabilityTargetDevice
}
return kind
}
// availabilityProbeAgentTargetPayload carries only what the agent needs to run
// the check. Failure accounting and resource linkage stay server-side.
func availabilityProbeAgentTargetPayload(target config.AvailabilityTarget) map[string]interface{} {
@@ -389,7 +401,7 @@ func availabilityProbeAgentTargetPayload(target config.AvailabilityTarget) map[s
"id": target.ID,
"configRevision": target.ConfigRevision,
"name": target.DisplayName(),
"targetKind": string(target.TargetKind),
"targetKind": string(availabilityProbeAgentTargetKind(target.TargetKind)),
"address": target.Address,
"protocol": string(target.Protocol),
"enabled": target.Enabled,
@@ -448,6 +448,33 @@ func TestGetHostAgentConfigIncludesOnlyOwnAssignedTargets(t *testing.T) {
}
}
func TestAvailabilityProbeAgentPayloadSendsGearAsDevice(t *testing.T) {
// An agent built before these kinds existed refuses them before probing.
for kind, want := range map[config.AvailabilityTargetKind]config.AvailabilityTargetKind{
config.AvailabilityTargetRouter: config.AvailabilityTargetDevice,
config.AvailabilityTargetSwitch: config.AvailabilityTargetDevice,
config.AvailabilityTargetAccessPoint: config.AvailabilityTargetDevice,
config.AvailabilityTargetDevice: config.AvailabilityTargetDevice,
config.AvailabilityTargetMachine: config.AvailabilityTargetMachine,
config.AvailabilityTargetService: config.AvailabilityTargetService,
} {
target := config.NewAvailabilityTarget()
target.Name = "thing"
target.Address = "192.168.0.1"
target.TargetKind = kind
payload := availabilityProbeAgentTargetPayload(target)
if got := payload["targetKind"]; got != string(want) {
t.Fatalf("payload kind for %q = %v, want %q", kind, got, want)
}
// What the agent is sent passes the validator every agent has.
sent := target
sent.TargetKind = want
if err := sent.Validate(); err != nil {
t.Fatalf("Validate() of the kind sent for %q = %v", kind, err)
}
}
}
func TestGetHostAgentConfigPayloadCarriesProbeParameters(t *testing.T) {
monitor := newProbeAgentTestMonitor(t, config.AvailabilityTarget{
ID: "udp-check",
@@ -686,9 +686,12 @@ func TestResourceAPIReportMergeExcludesRegistryLinkFolds(t *testing.T) {
func TestAgentlessAvailabilityTargetKindStaysCanonical(t *testing.T) {
requiredSnippets := map[string][]string{
filepath.Join("..", "config", "availability.go"): {
"AvailabilityTargetMachine AvailabilityTargetKind = \"machine\"",
"AvailabilityTargetService AvailabilityTargetKind = \"service\"",
"AvailabilityTargetDevice AvailabilityTargetKind = \"device\"",
"AvailabilityTargetMachine AvailabilityTargetKind = \"machine\"",
"AvailabilityTargetService AvailabilityTargetKind = \"service\"",
"AvailabilityTargetDevice AvailabilityTargetKind = \"device\"",
"AvailabilityTargetRouter AvailabilityTargetKind = \"router\"",
"AvailabilityTargetSwitch AvailabilityTargetKind = \"switch\"",
"AvailabilityTargetAccessPoint AvailabilityTargetKind = \"access_point\"",
"TargetKind AvailabilityTargetKind `json:\"targetKind,omitempty\"`",
"target.TargetKind = AvailabilityTargetKind(strings.ToLower(strings.TrimSpace(string(target.TargetKind))))",
"LinkedResourceID string `json:\"linkedResourceId,omitempty\"`",
@@ -712,7 +715,8 @@ func TestAgentlessAvailabilityTargetKindStaysCanonical(t *testing.T) {
"LastSuccess *time.Time `json:\"lastSuccess,omitempty\"`",
},
filepath.Join("..", "..", "frontend-modern", "src", "api", "availabilityTargets.ts"): {
"export type AvailabilityTargetKind = 'machine' | 'service' | 'device';",
"export type AvailabilityTargetKind =",
"'service' | 'machine' | 'router' | 'switch' | 'access_point' | 'device';",
"targetKind?: AvailabilityTargetKind;",
},
// standalonePageModel.ts no longer references targetKind: commit