Display role vocabulary, migration commit fix, stale enforcement reports

This commit is contained in:
2026-08-13 09:30:40 -04:00
parent d327ea1a5c
commit 5dcc7e30af
16 changed files with 490 additions and 46 deletions

View File

@@ -11,7 +11,7 @@ Two audiences:
import ipaddress
import os
import time
from datetime import datetime
from datetime import datetime, timedelta
from functools import wraps
from flask import Blueprint, request, Response, send_file, current_app, g
@@ -1061,6 +1061,29 @@ def _attach_backup_state(facts, hostnames):
if revision.lastseenat else None)
def _report_stale_cutoff():
"""(cutoff datetime, threshold minutes) for 'this PC has gone quiet'.
A report is a record of one cycle, not a heartbeat with an expiry: nothing
ages it. So a PC that stops reporting keeps the status of its last good
cycle and reads as healthy while it is unplugged. Comparing receivedat - the
SERVER's clock, not anything the client asserts - against a threshold is
what turns silence into a visible state.
Returns (None, 0) when the check is disabled, so callers skip it entirely.
"""
from shopdb.api import Setting
try:
minutes = int(Setting.get('geenforce_reportstaleminutes', 30) or 0)
except (TypeError, ValueError):
minutes = 30
if minutes <= 0:
return None, 0
# Same clock helper that WROTE receivedat (naive UTC), so the two cannot
# drift into comparing an aware datetime against a naive one.
return service._utcnow() - timedelta(minutes=minutes), minutes
@geenforce_bp.route('/reports', methods=['GET'])
@jwt_required()
@require_permission('geenforce.manage')
@@ -1084,6 +1107,7 @@ def list_reports():
facts = _asset_facts({report.hostname for report in reports
if report.hostname})
stalecutoff, stalafter = _report_stale_cutoff()
latest_cache = {}
data = []
for report in reports:
@@ -1092,6 +1116,9 @@ def list_reports():
latest_cache[key] = _current_published_version(*key)
latest = latest_cache[key]
known = facts.get((report.hostname or '').lower(), {})
isstale = (stalecutoff is not None
and (report.receivedat is None
or report.receivedat < stalecutoff))
data.append({
'reportid': report.reportid,
'hostname': report.hostname,
@@ -1118,7 +1145,14 @@ def list_reports():
'receivedlatest': (latest is not None
and report.appliedversion == latest),
'enforcerversion': report.enforcerversion,
# 'status' is what the PC said about its LAST cycle and is left
# exactly as reported. 'isstale' is the server's own judgement that
# no cycle has been heard from in too long - a PC switched off after
# a clean run reports 'ok' forever, so the two are different facts
# and the table shows both.
'status': report.status,
'isstale': isstale,
'staleafterminutes': stalafter,
'installed': report.installedcount,
'skipped': report.skippedcount,
'failed': report.failedcount,

View File

@@ -88,7 +88,14 @@
</span>
</td>
<td class="muted">{{ report.appliedversion ?? '-' }} / {{ report.latestversion ?? '-' }}</td>
<td><span class="badge" :class="statusClass(report.status)">{{ report.status }}</span></td>
<!-- A PC that stops reporting keeps the status of its last good
cycle, so silence has to outrank it: 'stale' shows instead,
with what it last reported kept in the tooltip. -->
<td>
<span v-if="report.isstale" class="badge badge-warning"
:title="staleTitle(report)">stale</span>
<span v-else class="badge" :class="statusClass(report.status)">{{ report.status }}</span>
</td>
<td>{{ report.installed }}</td>
<td class="muted">{{ report.skipped }}</td>
<td :class="{ 'fail-count': report.failed }">{{ report.failed }}</td>
@@ -183,6 +190,12 @@ async function openDetail(reportid) {
function statusClass(status) {
return { ok: 'badge-success', selfhealed: 'badge-info', failed: 'badge-danger' }[status] || ''
}
function staleTitle(report) {
const last = report.receivedat ? formatDate(report.receivedat) : 'never'
return `No report for over ${report.staleafterminutes} minutes.`
+ ` Last heard ${last}, reporting "${report.status}".`
}
function actionClass(action) {
return { installed: 'badge-info', skipped: 'badge-success', failed: 'badge-danger',
filtered: '' }[action] || ''

View File

@@ -5,7 +5,7 @@
"description": "GE-Enforce manifest store. Owns imaging PC-type scopes and their install manifests (apps, scripts, files, registry, version gates) as shopdb data, served to the GE-Enforce client as JSON. Requires GE-Enforce lib >= 2.6 on target PCs (the _CmmVersion gate).",
"author": "ShopDB Team",
"dependencies": [],
"core_version": ">=0.7.0,<1.0.0",
"core_version": ">=0.18.0,<1.0.0",
"api_prefix": "/api/geenforce",
"default_enabled": false,
"provides": {

View File

@@ -141,6 +141,26 @@ class GeEnforcePlugin(BasePlugin):
},
]
def get_settings_defaults(self) -> List[Dict]:
"""How long a PC may go quiet before the fleet table calls it stale."""
return [
{
'key': 'geenforce_reportstaleminutes',
'value': '30',
'valuetype': 'integer',
'category': 'geenforce',
'description': 'Minutes without an enforcement report before a '
'PC is shown as stale. A report records how the '
'LAST cycle went, so a PC that stops reporting '
'keeps whatever status it last sent - it reads '
'as healthy while it is switched off. Set to 0 '
'to disable the check.',
# Server-side only: nothing on a PC reads this, so it stays off
# the public settings surface.
'public': False,
},
]
def init_app(self, app: Flask, db_instance) -> None:
logger.info(f"GE-Enforce plugin initialized (v{self.meta.version})")

View File

@@ -30,7 +30,7 @@ running replace_scope_draft is an idempotent draft rebuild.
import hashlib
import os
from shopdb.api import db
from shopdb.api import db, DISPLAY_ROLE_PATHS
from . import service
@@ -47,17 +47,18 @@ RELAUNCH_WINDOW_JSON = (
# Data-driven display-type -> kiosk target map. The value of
# C:\Enrollment\display-type.txt selects the row; the target is a route the
# kiosk browser opens against the local kiosk base URL. Edit here to retarget a
# subtype. Keys are matched case-insensitively by the dispatcher.
# kiosk browser opens against the local kiosk base URL. Keys are matched
# case-insensitively by the dispatcher.
#
# NOT a copy any more: this IS core's DISPLAY_ROLE_PATHS, read through the
# contract surface. It used to be a second map with the same routes under
# different names, which is how a display could report a role core could not
# store. Retarget a subtype in shopdb/core/models/dashboarddefault.py.
#
# TODO-confirm: 3DPrintRoom points at the printedparts /parts-kiosk route as a
# PLACEHOLDER. Confirm the real 3D-print-room kiosk target with the floor team
# before this scope is published to production displays.
DISPLAY_TYPE_TARGETS = {
'Dashboard': '/shopfloor',
'Lobby': '/tv',
'3DPrintRoom': '/parts-kiosk',
}
DISPLAY_TYPE_TARGETS = DISPLAY_ROLE_PATHS
DISPATCHER_FILENAME = 'Invoke-DisplayKioskDispatch.ps1'

View File

@@ -16,7 +16,7 @@ from datetime import datetime, timezone
from flask import current_app
from sqlalchemy import func
from shopdb.api import db, Application
from shopdb.api import db, Application, normalize_display_role
from .models import (
ManifestScope, ManifestPublishedVersion, ManifestEnforcementReport,
@@ -49,6 +49,25 @@ class LibVersionTooOldError(Exception):
'if you are certain those PCs must not receive this scope.')
def _canonical_subtype(value):
"""Store a reported subtype under core's role vocabulary where it names one.
A display reports the literal contents of C:\\Enrollment\\display-type.txt,
hand-edited on the machine, so casing drifts freely. Normalising on the way
in means the fleet table reads one vocabulary rather than whatever each
kiosk happened to be typed as.
A value that names NO known role is kept VERBATIM, not dropped: an unknown
subtype is a kiosk with a typo or a role nobody told the server about, and
both are things you want to see in the table rather than have silently
blanked. Non-display scopes report no subtype at all and land as None.
"""
text = (value or '').strip()
if not text:
return None
return normalize_display_role(text) or text
def _utcnow():
return datetime.now(timezone.utc).replace(tzinfo=None)
@@ -263,7 +282,7 @@ def record_enforcement_report(payload):
phase=phase,
appliedversion=payload.get('appliedversion'),
enforcerversion=payload.get('enforcerversion'),
subtype=(payload.get('subtype') or None),
subtype=_canonical_subtype(payload.get('subtype')),
installedcount=installed,
skippedcount=int(counts.get('skipped', 0)),
failedcount=failed,