An operator could see that an endpoint was behind the published build but had no way to act on it. update_app resolves against Application rows, and the agent lives in the version store, so there was nothing to push. Bridge the two: the staged build is packaged and registered as a reserved Application row, and a managed PowerShell script is seeded to install it. The endpoint downloads that package over the existing collector-authenticated app-package route, so no parallel delivery path is introduced. The new route prepares the delivery and then DELEGATES to enqueue_endpoint_command as a digest-pinned run_script. It deliberately does not implement its own enqueue: a second path would duplicate, and eventually drift from, the endpoint lock, the Configuration Policy gate, stale-command reaping and the at-most-one-in-flight rule. A fleet-wide agent swap is the last action that should skip a quarantine check. Tests pin that delegation rather than only the happy path. Because it lands as run_script, the caller needs endpoints.runscript on top of endpoints.agentupdate. That is intended: this delivers arbitrary SYSTEM PowerShell by the same mechanism as any other script push. The audit event is written only on an actual 201, so a refused push does not record an upgrade that never happened. Replacing the agent is self-modifying the control plane - the process receiving the command is the one being swapped. The script therefore re-launches itself detached and exits immediately, because the agent runs run_script as a direct child and holds its stdout/stderr pipes while waiting on it. Expect the command to report queued rather than success: the process that would report completion is stopped mid-run. Judge the result by the version the endpoint reports afterward. Tray relaunch does not use the installer's `explorer.exe <path>` trick. That works in install-shopdbagent.ps1 only because the installer runs as the user - note its own `-ne "SYSTEM"` guard. This script always runs as SYSTEM in session 0, where the hand-off reaches no shell and exits 0, so Start-Process reported success for a relaunch that never happened. It also cannot descend into the session with a token-duplicating launch: UserContextSpool documents that WTSQueryUserToken is blocked by endpoint protection on these hosts. Instead a one-shot scheduled task targets the pinned ShopFloor account, matching how the user-context spool already resolves that user, and the tray must run as that account or the mapped-drive probe reports the wrong (empty) drive table. The relaunch is verified by polling for the process rather than assumed, and stays best-effort: the Run key still starts the tray at next logon, and a late tray is not worth rolling back a good agent upgrade. panel_status now carries agentbehind/agentversion/agentcurrent so the UI gates the action on a flag rather than parsing "(behind X)" out of a label. The button is confirmed by typing UPDATE, naming both versions and the service interruption, matching how run_script and system_restart are gated. Verified on live endpoints: upgraded 1.13.0.0 and 1.15.0.0 machines to 1.16.0.0. run_script delivery, digest fetch and system context all predate 1.13.0.0, so no minimum agent version is declared for this path.
137 lines
5.3 KiB
Python
137 lines
5.3 KiB
Python
"""Seed the agent self-upgrade script into the ShopDB script library.
|
|
|
|
run_script only delivers bodies that live in the script library, pinned by
|
|
SHA-256. The upgrade template therefore has to exist as a real Script row with
|
|
a stored body before any upgrade can be pushed.
|
|
|
|
The template is source-controlled at
|
|
plugins/endpoints/api/templates/upgrade-shopdbagent.ps1 and seeded from there
|
|
rather than typed into the library by hand, so the reviewed script and the one
|
|
endpoints actually run are the same artifact. Editing the row's body in the UI
|
|
is pointless - the next seed overwrites it.
|
|
|
|
It lives under the plugin, not under agent/, because the Docker image copies
|
|
shopdb/, plugins/, migrations/ and scripts/ but NOT agent/. A template read
|
|
from agent/ resolves fine on a developer checkout and then fails in the
|
|
deployed container, which is the worst place to discover it.
|
|
|
|
One placeholder is rendered at seed time: the agent application's appid, which
|
|
only exists once agentregistry has created the row. Rendering happens BEFORE
|
|
the digest is computed, so the stored body and its sha256 always agree; a
|
|
substitution done after hashing would fail the agent's verification.
|
|
"""
|
|
|
|
import hashlib
|
|
import os
|
|
|
|
from shopdb.api import Script, db, script_body_location
|
|
|
|
from . import agentregistry
|
|
|
|
# Reserved script name. Unique in the library, which makes seeding idempotent
|
|
# and keeps a hand-made script from colliding with the managed one.
|
|
UPGRADE_SCRIPT_NAME = 'ShopDB Endpoint Agent Self-Upgrade'
|
|
|
|
_UPGRADE_DESCRIPTION = (
|
|
'Managed: downloads the current published agent bundle and replaces the '
|
|
'installed agent in place, then restarts the service. Seeded from source '
|
|
'control - edits here are overwritten.'
|
|
)
|
|
|
|
# Substituted with the agent application's appid so the script can fetch its
|
|
# payload from the existing collector-authenticated app-package route.
|
|
_APPID_TOKEN = '{{AGENT_APPID}}'
|
|
|
|
_TEMPLATE_FILENAME = 'upgrade-shopdbagent.ps1'
|
|
|
|
|
|
def template_path():
|
|
return os.path.join(os.path.dirname(os.path.abspath(__file__)),
|
|
'templates', _TEMPLATE_FILENAME)
|
|
|
|
|
|
def _script_dir():
|
|
"""Where script bodies live. Resolved through the contract surface helper
|
|
so this cannot drift from the directory the download route serves from."""
|
|
directory, _prefix = script_body_location()
|
|
return directory
|
|
|
|
|
|
def render_template(appid):
|
|
"""Return the upgrade script body with the appid substituted.
|
|
|
|
Raises if the placeholder is missing: that means the template was edited
|
|
in a way that breaks the download, and seeding a script that would fetch
|
|
from a literal '{{AGENT_APPID}}' path is worse than refusing.
|
|
"""
|
|
with open(template_path(), 'r', encoding='utf-8') as handle:
|
|
body = handle.read()
|
|
if _APPID_TOKEN not in body:
|
|
raise ValueError(
|
|
'upgrade template is missing the {} placeholder; refusing to seed '
|
|
'a script that cannot resolve its package'.format(_APPID_TOKEN))
|
|
return body.replace(_APPID_TOKEN, str(appid))
|
|
|
|
|
|
def seed_upgrade_script():
|
|
"""Create or refresh the managed upgrade script row and its body.
|
|
|
|
Returns a dict describing the seeded script, or None when the agent
|
|
application row does not exist yet (nothing to point the download at).
|
|
Idempotent: unchanged input rewrites nothing and leaves the digest alone.
|
|
"""
|
|
app = agentregistry.get_agent_application()
|
|
if app is None:
|
|
return None
|
|
|
|
body = render_template(app.appid).encode('utf-8')
|
|
digest = hashlib.sha256(body).hexdigest()
|
|
|
|
script = Script.query.filter_by(scriptname=UPGRADE_SCRIPT_NAME).first()
|
|
created = script is None
|
|
if created:
|
|
script = Script(
|
|
scriptname=UPGRADE_SCRIPT_NAME,
|
|
scriptdescription=_UPGRADE_DESCRIPTION,
|
|
# SYSTEM: the script stops a service, writes into Program Files,
|
|
# and edits HKLM. None of that is available in a user context.
|
|
runcontext='system',
|
|
# Failures always report; success is opt-in. Capture it here
|
|
# because an upgrade that "succeeded" but rolled back internally
|
|
# is only diagnosable from the transcript.
|
|
captureoutput=True,
|
|
)
|
|
db.session.add(script)
|
|
db.session.flush()
|
|
|
|
# Body filename follows the library convention (script-<id>.ps1) so the
|
|
# collector download route serves it like any other script.
|
|
filename = 'script-{}.ps1'.format(script.scriptid)
|
|
path = os.path.join(_script_dir(), filename)
|
|
|
|
unchanged = (script.filename == filename and script.sha256 == digest
|
|
and os.path.isfile(path))
|
|
if not unchanged:
|
|
os.makedirs(_script_dir(), exist_ok=True)
|
|
# Temp-then-replace so an interrupted write cannot leave a truncated
|
|
# body at the path the row's digest already claims to describe.
|
|
temppath = path + '.tmp'
|
|
with open(temppath, 'wb') as handle:
|
|
handle.write(body)
|
|
os.replace(temppath, path)
|
|
script.filename = filename
|
|
script.sha256 = digest
|
|
|
|
script.scriptdescription = _UPGRADE_DESCRIPTION
|
|
db.session.commit()
|
|
|
|
return {
|
|
'scriptid': script.scriptid,
|
|
'scriptname': script.scriptname,
|
|
'created': created,
|
|
'updated': not unchanged,
|
|
'sha256': digest,
|
|
'bytes': len(body),
|
|
'appid': app.appid,
|
|
}
|