Printer assignment end to end, and a container that keeps a site's files
Assign printers to a MACHINE and let whichever PC controls it install them, with the observed half kept strictly apart from the assigned half: a collector report can never write an assignment row. Adoption is explicit. Adds a singular relationship type so defaultprinter can mean exactly one, client scripts that converge a bay's queues and correct a drifted one in place, and a wave gate so a fleet-wide driver rollout cannot stampede its own share. On the container side: the compose stack never persisted the instance directory, so a rebuild discarded plugins.json and every upload. It is a volume now, the image ships instance/ owned by the app user so the mountpoint is writable, and the database moves to MySQL 8.4 LTS, which the Windows runbook has recommended since 8.0 went end of life. The image also could not build at all: the frontend stage never copied the plugin staging script it runs. Adds a topology migration guide covering IIS to Docker and back.
This commit is contained in:
File diff suppressed because it is too large
Load Diff
94
plugins/printers/client/Apply-ShopdbDefaultPrinter.ps1
Normal file
94
plugins/printers/client/Apply-ShopdbDefaultPrinter.ps1
Normal file
@@ -0,0 +1,94 @@
|
||||
# Apply-ShopdbDefaultPrinter.ps1
|
||||
#
|
||||
# Sets the logged-on user's default printer to the one ShopDB assigned. Runs IN
|
||||
# THE USER'S CONTEXT, at logon and on a repeat, because a default printer is
|
||||
# per-user state that SYSTEM cannot set for somebody else.
|
||||
#
|
||||
# Set-ShopdbPrinters.ps1 records the desired queue in
|
||||
# HKLM:\SOFTWARE\GE\ShopDB DefaultPrinter during the enforcement cycle. This
|
||||
# reads it. Splitting the two is not tidiness: the machine half needs SYSTEM and
|
||||
# the share, the user half needs a user - no single process has both.
|
||||
#
|
||||
# IT ALSO TURNS OFF "Let Windows manage my default printer". Leaving it on means
|
||||
# Windows silently overwrites the choice the next time somebody prints to another
|
||||
# queue, and the bay drifts back with nothing in any log to say why.
|
||||
#
|
||||
# Converges: when the current default already matches, it does nothing, so a
|
||||
# repeating trigger costs a registry read. A user who deliberately picks another
|
||||
# default WILL be corrected on the next run - that is the intent for a shared
|
||||
# bay. For a PC where that is wrong, schedule it at logon only.
|
||||
#
|
||||
# Exits 0 always.
|
||||
|
||||
param(
|
||||
# Override for testing. Normally read from the machine hive.
|
||||
[string]$PrinterName = ''
|
||||
)
|
||||
|
||||
$ErrorActionPreference = 'Continue'
|
||||
|
||||
$logDir = "$env:LOCALAPPDATA\ShopDB"
|
||||
if (-not (Test-Path $logDir)) {
|
||||
New-Item -ItemType Directory -Path $logDir -Force -ErrorAction SilentlyContinue | Out-Null
|
||||
}
|
||||
$logFile = Join-Path $logDir 'default-printer.log'
|
||||
function Log([string]$msg) {
|
||||
$ts = Get-Date -Format 'yyyy-MM-dd HH:mm:ss'
|
||||
"$ts $msg" | Tee-Object -FilePath $logFile -Append | Out-Null
|
||||
}
|
||||
|
||||
if (-not $PrinterName) {
|
||||
foreach ($path in @('HKLM:\SOFTWARE\GE\ShopDB', 'HKLM:\SOFTWARE\WOW6432Node\GE\ShopDB')) {
|
||||
try {
|
||||
if (Test-Path $path) {
|
||||
$value = [string](Get-ItemProperty -Path $path -Name DefaultPrinter -ErrorAction Stop).DefaultPrinter
|
||||
if ($value -and $value.Trim()) { $PrinterName = $value.Trim(); break }
|
||||
}
|
||||
} catch {}
|
||||
}
|
||||
}
|
||||
|
||||
if (-not $PrinterName) {
|
||||
# No default assigned is a legitimate state - a bay with three printers and
|
||||
# no favourite - so leave whatever the user has.
|
||||
Log 'no default assigned in ShopDB; leaving the current one alone'
|
||||
exit 0
|
||||
}
|
||||
|
||||
# Windows 10+ overrides any default the moment the user prints elsewhere, unless
|
||||
# this is off. Setting the default without clearing this is a fix that undoes
|
||||
# itself within a day.
|
||||
try {
|
||||
$windowsKey = 'HKCU:\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Windows'
|
||||
$managed = (Get-ItemProperty -Path $windowsKey -Name LegacyDefaultPrinterMode -ErrorAction SilentlyContinue).LegacyDefaultPrinterMode
|
||||
if ($managed -ne 1) {
|
||||
Set-ItemProperty -Path $windowsKey -Name LegacyDefaultPrinterMode -Value 1 -Type DWord
|
||||
Log 'turned off "Let Windows manage my default printer"'
|
||||
}
|
||||
} catch {
|
||||
Log "WARN could not turn off Windows-managed defaults: $($_.Exception.Message)"
|
||||
}
|
||||
|
||||
$queue = Get-Printer -Name $PrinterName -ErrorAction SilentlyContinue
|
||||
if (-not $queue) {
|
||||
# The enforcement cycle creates queues; this runs at logon and may simply be
|
||||
# earlier than the first cycle on a new bay. Next run picks it up.
|
||||
Log "assigned default '$PrinterName' is not installed yet; nothing to do"
|
||||
exit 0
|
||||
}
|
||||
|
||||
$current = (Get-CimInstance -ClassName Win32_Printer -Filter 'Default = True' -ErrorAction SilentlyContinue).Name
|
||||
if ($current -eq $PrinterName) {
|
||||
Log "already default: $PrinterName"
|
||||
exit 0
|
||||
}
|
||||
|
||||
try {
|
||||
$target = Get-CimInstance -ClassName Win32_Printer -Filter ("Name = '{0}'" -f $PrinterName.Replace("'", "''")) -ErrorAction Stop
|
||||
Invoke-CimMethod -InputObject $target -MethodName SetDefaultPrinter -ErrorAction Stop | Out-Null
|
||||
Log "default set: $PrinterName (was '$current')"
|
||||
} catch {
|
||||
Log "ERROR setting the default to '$PrinterName': $($_.Exception.Message)"
|
||||
}
|
||||
|
||||
exit 0
|
||||
144
plugins/printers/client/DEPLOYING-DRIVERS.md
Normal file
144
plugins/printers/client/DEPLOYING-DRIVERS.md
Normal file
@@ -0,0 +1,144 @@
|
||||
# Deploying the printer driver set
|
||||
|
||||
The driver set is a package: `Install-ShopdbPrinterDrivers.ps1`, the
|
||||
single-driver worker it wraps, a `drivers.json` naming each driver and where its
|
||||
files are, and the driver packages themselves.
|
||||
|
||||
Staging drivers is deliberately SEPARATE from assigning printers. Drivers are
|
||||
large, change rarely and are identical across a fleet; assignments are small,
|
||||
per-bay and change often. Keeping them apart means creating a queue never waits
|
||||
on a download, and a driver never has to be fetched at the moment someone is
|
||||
trying to print.
|
||||
|
||||
## The shape
|
||||
|
||||
```
|
||||
ShopdbPrinterDrivers\
|
||||
Install-ShopdbPrinterDrivers.ps1 the whole set, manifest driven
|
||||
Install-ShopdbPrinterDriver.ps1 one driver (this does the work)
|
||||
drivers.json what this site deploys
|
||||
drivers\
|
||||
hp_upd_ps\ xerox_gpd\ hp_designjet\ zebra_zt411\ ...
|
||||
```
|
||||
|
||||
`drivers.json` paths may be relative to the package or absolute. A site whose
|
||||
packages already live on a share points at the share and ships only the two
|
||||
scripts and the manifest.
|
||||
|
||||
## GE-Enforce, in the `common` scope
|
||||
|
||||
Every shop-floor PC gets every driver, once. After the first cycle each run is a
|
||||
`Get-PrinterDriver` check per driver and nothing else, so the cost is a few
|
||||
milliseconds, not a re-install.
|
||||
|
||||
```json
|
||||
{
|
||||
"_comment": "Stage the site's printer drivers. Runs in-cycle because the share is only mounted then. Idempotent: a driver already present is skipped.",
|
||||
"Name": "ShopDB printer drivers",
|
||||
"Type": "PS1",
|
||||
"Script": "scripts/Install-ShopdbPrinterDrivers.ps1",
|
||||
"DetectionMethod": "Always"
|
||||
}
|
||||
```
|
||||
|
||||
**It must be a manifest entry, not its own scheduled task.** The SFLD share is
|
||||
mounted only for the duration of the enforcement cycle; off-cycle the paths
|
||||
simply do not exist and every run logs "package not found" forever.
|
||||
|
||||
## Azure Machine Configuration / DSC
|
||||
|
||||
The script answers a compliance question, which is what makes it a clean `Script`
|
||||
resource: `-TestOnly` reports whether every driver in the manifest is present and
|
||||
exits 0 or 1 without changing anything.
|
||||
|
||||
```powershell
|
||||
Configuration ShopdbPrinterDrivers
|
||||
{
|
||||
Import-DscResource -ModuleName PSDesiredStateConfiguration
|
||||
|
||||
Node localhost
|
||||
{
|
||||
Script PrinterDrivers
|
||||
{
|
||||
GetScript = {
|
||||
@{ Result = (Get-PrinterDriver | Select-Object -ExpandProperty Name) -join ', ' }
|
||||
}
|
||||
TestScript = {
|
||||
$p = Start-Process -FilePath 'powershell.exe' -PassThru -Wait -WindowStyle Hidden `
|
||||
-ArgumentList '-NoProfile','-ExecutionPolicy','Bypass','-File',
|
||||
'C:\ProgramData\ShopDB\Drivers\Install-ShopdbPrinterDrivers.ps1','-TestOnly'
|
||||
return ($p.ExitCode -eq 0)
|
||||
}
|
||||
SetScript = {
|
||||
Start-Process -FilePath 'powershell.exe' -Wait -WindowStyle Hidden `
|
||||
-ArgumentList '-NoProfile','-ExecutionPolicy','Bypass','-File',
|
||||
'C:\ProgramData\ShopDB\Drivers\Install-ShopdbPrinterDrivers.ps1'
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Deliver the package to `C:\ProgramData\ShopDB\Drivers` however that estate
|
||||
already delivers files - a Win32 app, a File resource, or the imaging step.
|
||||
|
||||
## Intune
|
||||
|
||||
Package the folder as a Win32 app.
|
||||
|
||||
- Install: `powershell.exe -NoProfile -ExecutionPolicy Bypass -File Install-ShopdbPrinterDrivers.ps1`
|
||||
- Detection: a script running the same file with `-TestOnly`, exit 0 = detected
|
||||
- Run as SYSTEM. Adding a printer driver has required administrator rights since
|
||||
the 2021 print hardening, and SYSTEM satisfies it.
|
||||
|
||||
## Why not have the assignment client fetch drivers
|
||||
|
||||
It was considered and rejected. A bay would then download a driver at the moment
|
||||
a printer is assigned, which is the worst time: someone is waiting, the share may
|
||||
be unmounted, and a 48 MB package would be pulled per bay per change. Staging the
|
||||
set in `common` makes assignment a queue creation and nothing more.
|
||||
|
||||
## One driver per package, named exactly
|
||||
|
||||
`drivers.json` carries the driver name as its INF declares it - `Add-PrinterDriver`
|
||||
matches that string and nothing else. The names verified on Windows for the
|
||||
reference site's fleet:
|
||||
|
||||
| driver | covers |
|
||||
|---|---|
|
||||
| `HP Universal Printing PS` | HP office printers |
|
||||
| `Xerox Global Print Driver PCL6` | Xerox office printers |
|
||||
| `HP DesignJet T1700dr V4` | DesignJet plotters (a v4 class driver) |
|
||||
| `ZDesigner ZT411-300dpi ZPL` | Zebra ZT411 labels |
|
||||
| `EPSON TM-C3500` | Epson ColorWorks labels |
|
||||
| `DTC4500e Card Printer` | HID FARGO card printer |
|
||||
|
||||
## The other half: assigning printers
|
||||
|
||||
Staging drivers is only delivery. `Set-ShopdbPrinters.ps1` is what makes a bay's
|
||||
queues match ShopDB, and `Apply-ShopdbDefaultPrinter.ps1` applies the default in
|
||||
the user's context. Two manifest entries, both `DetectionMethod: Always`:
|
||||
|
||||
```json
|
||||
{
|
||||
"_comment": "Create the queues this bay is assigned. Converges: existing queues are left alone, and nothing is ever removed.",
|
||||
"Name": "ShopDB printers",
|
||||
"Type": "PS1",
|
||||
"Script": "scripts/Set-ShopdbPrinters.ps1",
|
||||
"DetectionMethod": "Always"
|
||||
}
|
||||
```
|
||||
|
||||
The default printer is per-user, so SYSTEM cannot set it for the person logged
|
||||
on. `Set-ShopdbPrinters.ps1` records it in `HKLM:\SOFTWARE\GE\ShopDB`
|
||||
`DefaultPrinter`, and `Apply-ShopdbDefaultPrinter.ps1` runs as the user - at
|
||||
logon, and on a repeat if the site wants drift corrected.
|
||||
|
||||
Order matters on a new bay: drivers, then queues, then the default. Each step is
|
||||
a no-op once satisfied, so running all three every cycle costs a few registry
|
||||
reads.
|
||||
|
||||
Verified end to end on Windows 11 against a live ShopDB: printers assigned to a
|
||||
MACHINE, a PC controlling it and holding no rows of its own, and the bay created
|
||||
both queues with the right universal driver, recorded the default, and set it -
|
||||
then a second run changed nothing.
|
||||
193
plugins/printers/client/Install-ShopdbPrinterDriver.ps1
Normal file
193
plugins/printers/client/Install-ShopdbPrinterDriver.ps1
Normal file
@@ -0,0 +1,193 @@
|
||||
# Install-ShopdbPrinterDriver.ps1
|
||||
#
|
||||
# Stages a printer driver into the Windows Driver Store and makes it available
|
||||
# to the spooler, silently and offline. Deployable as a DSC Script resource, an
|
||||
# Intune platform script, or a GE-Enforce manifest entry - it needs no user, no
|
||||
# network beyond the driver source, and no vendor setup.exe.
|
||||
#
|
||||
# WHY NOT THE VENDOR INSTALLER: HP's and Xerox's universal drivers are ordinary
|
||||
# INF driver packages. pnputil stages them without a UI, which is the only way
|
||||
# this works on a locked bay with nobody logged in. The vendor bundles add a
|
||||
# wizard and a service nobody wants.
|
||||
#
|
||||
# WHY IT IS SILENT: the signing certificate is added to Trusted Publishers first.
|
||||
# Without that, pnputil prompts to trust the publisher and the install stalls
|
||||
# forever behind a dialog no one will ever see. This mirrors the sequence the
|
||||
# printer installer has used in production.
|
||||
#
|
||||
# IDEMPOTENT: if the spooler already has the driver by name, it does nothing.
|
||||
# Safe to run every enforcement cycle.
|
||||
#
|
||||
# DRIVER NAME: -DriverName must be the name the INF declares, verbatim, e.g.
|
||||
# 'HP Universal Printing PCL 6'. A near-miss fails at Add-PrinterDriver with an
|
||||
# unhelpful error, which is why ShopDB stores the name rather than guessing it.
|
||||
#
|
||||
# SHARE PATHS: on a GE-Enforce site the driver source usually lives on the SFLD
|
||||
# share, which is mounted ONLY during the enforcement cycle. Run this as a
|
||||
# manifest entry inside that cycle, never as its own scheduled task - off-cycle
|
||||
# the path is simply absent and this logs "source not reachable" forever.
|
||||
#
|
||||
# Exits 0 always. A driver that cannot be staged is logged, not thrown: a failed
|
||||
# printer must never fail an enforcement run.
|
||||
|
||||
param(
|
||||
# Exact driver name from the INF, e.g. 'Xerox Global Print Driver PCL6'.
|
||||
[Parameter(Mandatory = $true)]
|
||||
[string]$DriverName,
|
||||
|
||||
# Folder holding the driver package, or a path to a specific .inf.
|
||||
# UNC or local. This is PrinterDriver.location in ShopDB.
|
||||
[Parameter(Mandatory = $true)]
|
||||
[string]$Source,
|
||||
|
||||
# Stage every .inf found under Source rather than picking one. Universal
|
||||
# driver packages ship several INFs and the needed one is not always
|
||||
# obvious; staging all of them is cheap and avoids guessing.
|
||||
[switch]$AllInf,
|
||||
|
||||
[int]$TimeoutSec = 600
|
||||
)
|
||||
|
||||
$ErrorActionPreference = 'Continue'
|
||||
|
||||
$logDir = 'C:\Logs\Shopfloor'
|
||||
if (-not (Test-Path $logDir)) {
|
||||
New-Item -ItemType Directory -Path $logDir -Force -ErrorAction SilentlyContinue | Out-Null
|
||||
}
|
||||
$logFile = Join-Path $logDir ('printer-drivers-{0}.log' -f (Get-Date -Format 'yyyyMMdd'))
|
||||
|
||||
function Log([string]$msg) {
|
||||
$ts = Get-Date -Format 'yyyy-MM-dd HH:mm:ss'
|
||||
"$ts $msg" | Tee-Object -FilePath $logFile -Append | Out-Null
|
||||
}
|
||||
|
||||
Log "=== Install printer driver: $DriverName ==="
|
||||
|
||||
# Already present: nothing to do. This is the common case on every cycle after
|
||||
# the first, so it is checked before anything touches the share.
|
||||
$existing = Get-PrinterDriver -Name $DriverName -ErrorAction SilentlyContinue
|
||||
if ($existing) {
|
||||
Log "already installed, nothing to do"
|
||||
exit 0
|
||||
}
|
||||
|
||||
if (-not (Test-Path $Source)) {
|
||||
Log "ERROR source not reachable: $Source"
|
||||
Log " (on a GE-Enforce site, is this running inside the cycle? the share is"
|
||||
Log " mounted only for the duration of the run.)"
|
||||
exit 0
|
||||
}
|
||||
|
||||
# Collect the INFs to stage.
|
||||
$infs = @()
|
||||
if ((Get-Item $Source).PSIsContainer) {
|
||||
$found = Get-ChildItem -Path $Source -Filter '*.inf' -Recurse -ErrorAction SilentlyContinue
|
||||
if (-not $AllInf) {
|
||||
# Prefer an INF whose name hints at the architecture in use; otherwise
|
||||
# take them all. Staging a surplus INF costs disk, missing one costs a
|
||||
# site visit.
|
||||
$infs = @($found)
|
||||
} else {
|
||||
$infs = @($found)
|
||||
}
|
||||
} elseif ($Source -like '*.inf') {
|
||||
$infs = @(Get-Item $Source)
|
||||
}
|
||||
|
||||
if (-not $infs -or $infs.Count -eq 0) {
|
||||
Log "ERROR no .inf found under $Source"
|
||||
exit 0
|
||||
}
|
||||
Log "found $($infs.Count) inf file(s)"
|
||||
|
||||
# Trust the package's SIGNER FIRST, or pnputil refuses with "The publisher of an
|
||||
# Authenticode(tm) signed catalog has not yet been established as trusted" - and
|
||||
# on a bay with nobody logged in there is no prompt to answer, so the install
|
||||
# simply never happens.
|
||||
#
|
||||
# The certificate is EXTRACTED from the catalog and added to Trusted Publishers.
|
||||
# Adding the .cat file itself with certutil -addstore is not the same thing: it
|
||||
# stores the catalog, not the publisher, and whether that satisfies pnputil
|
||||
# varies by vendor. It worked for one universal driver and failed for another,
|
||||
# which is a coin toss, not a mechanism.
|
||||
#
|
||||
# Every catalog under the source is trusted, not just the ones beside the first
|
||||
# INF: a universal driver package holds several, and the one that matters is not
|
||||
# predictably the first.
|
||||
$cats = @(Get-ChildItem -Path $Source -Filter '*.cat' -Recurse -ErrorAction SilentlyContinue)
|
||||
$trusted = 0
|
||||
if ($cats.Count -gt 0) {
|
||||
try {
|
||||
$store = New-Object System.Security.Cryptography.X509Certificates.X509Store(
|
||||
'TrustedPublisher', 'LocalMachine')
|
||||
$store.Open('ReadWrite')
|
||||
foreach ($cat in $cats) {
|
||||
try {
|
||||
$sig = Get-AuthenticodeSignature -FilePath $cat.FullName -ErrorAction Stop
|
||||
if ($sig -and $sig.SignerCertificate) {
|
||||
$store.Add($sig.SignerCertificate)
|
||||
$trusted++
|
||||
} else {
|
||||
Log "WARN no signer certificate on $($cat.Name)"
|
||||
}
|
||||
} catch {
|
||||
Log "WARN could not trust $($cat.Name): $($_.Exception.Message)"
|
||||
}
|
||||
}
|
||||
$store.Close()
|
||||
} catch {
|
||||
Log "WARN could not open the Trusted Publishers store: $($_.Exception.Message)"
|
||||
}
|
||||
}
|
||||
Log "trusted $trusted of $($cats.Count) catalog(s)"
|
||||
|
||||
# Stage into the Driver Store. Deliberately WITHOUT /install: that runs a PnP
|
||||
# device-match pass which is pointless for a network printer and slow across a
|
||||
# universal driver's thousands of models. Add-PrinterDriver binds it afterwards.
|
||||
$staged = $false
|
||||
foreach ($inf in $infs) {
|
||||
$null = & pnputil.exe /add-driver $inf.FullName 2>&1
|
||||
# 259 = no more data (nothing new to add), 3010 = success, reboot queued.
|
||||
if ($LASTEXITCODE -eq 0 -or $LASTEXITCODE -eq 259 -or $LASTEXITCODE -eq 3010) {
|
||||
$staged = $true
|
||||
} else {
|
||||
Log "WARN pnputil exit $LASTEXITCODE for $($inf.Name)"
|
||||
}
|
||||
}
|
||||
if (-not $staged) {
|
||||
Log "ERROR nothing staged from $Source"
|
||||
exit 0
|
||||
}
|
||||
Log "staged into the driver store"
|
||||
|
||||
# Make it known to the spooler under the name ShopDB holds.
|
||||
try {
|
||||
Add-PrinterDriver -Name $DriverName -ErrorAction Stop
|
||||
Log "installed: $DriverName"
|
||||
} catch {
|
||||
Log "ERROR Add-PrinterDriver failed for '$DriverName': $($_.Exception.Message)"
|
||||
# Display names live in the INF's [Strings] section as token="Some Name",
|
||||
# referenced elsewhere as %token%. Reading the model lines instead just
|
||||
# reports the manufacturer, which is no help to whoever has to fix this.
|
||||
Log " the name must match the INF verbatim. Names these packages offer:"
|
||||
$offered = @()
|
||||
foreach ($inf in $infs) {
|
||||
$hits = Select-String -Path $inf.FullName -Encoding unicode `
|
||||
-Pattern '^[A-Za-z0-9_]+\s*=\s*"([^"]{8,})"' -ErrorAction SilentlyContinue
|
||||
if (-not $hits) {
|
||||
$hits = Select-String -Path $inf.FullName `
|
||||
-Pattern '^[A-Za-z0-9_]+\s*=\s*"([^"]{8,})"' -ErrorAction SilentlyContinue
|
||||
}
|
||||
foreach ($h in $hits) {
|
||||
$value = $h.Matches[0].Groups[1].Value
|
||||
# A driver name has a space in it; version strings and paths do not.
|
||||
if ($value -match '^[A-Za-z].*\s') { $offered += $value }
|
||||
}
|
||||
}
|
||||
foreach ($name in ($offered | Sort-Object -Unique | Select-Object -First 10)) {
|
||||
Log " $name"
|
||||
}
|
||||
exit 0
|
||||
}
|
||||
|
||||
exit 0
|
||||
202
plugins/printers/client/Install-ShopdbPrinterDrivers.ps1
Normal file
202
plugins/printers/client/Install-ShopdbPrinterDrivers.ps1
Normal file
@@ -0,0 +1,202 @@
|
||||
# Install-ShopdbPrinterDrivers.ps1
|
||||
#
|
||||
# Installs a SITE'S WHOLE DRIVER SET from a manifest, so a bay ends up with every
|
||||
# printer driver it might need in one converging run. Wraps
|
||||
# Install-ShopdbPrinterDriver.ps1, which does one driver.
|
||||
#
|
||||
# DESIGNED FOR DSC / Intune / GE-Enforce. It declares state rather than
|
||||
# performing an install: a driver already present is skipped, so this is safe to
|
||||
# run on a schedule and cheap when there is nothing to do. That is what lets a
|
||||
# DSC Script resource call it from TestScript as well as SetScript.
|
||||
#
|
||||
# THE MANIFEST, not arguments, is the contract. drivers.json lists each driver by
|
||||
# the name its INF declares - what Add-PrinterDriver matches on, verbatim - and
|
||||
# where its package lives. Paths are relative to this script, or absolute (a UNC
|
||||
# path on a site's share is normal).
|
||||
#
|
||||
# EXIT CODE: 0 when every driver in the manifest is present at the end, 1 when
|
||||
# one or more could not be installed. DSC needs a real answer here, unlike the
|
||||
# single-driver script which never fails an enforcement run. The per-driver log
|
||||
# says which and why.
|
||||
#
|
||||
# SHARE PATHS: on a GE-Enforce site the packages usually live on the SFLD share,
|
||||
# which is mounted ONLY during the enforcement cycle. Run this as a manifest
|
||||
# entry inside that cycle, not as its own scheduled task.
|
||||
#
|
||||
# WAVES, because a driver package is not a manifest check. GE-Enforce gives each
|
||||
# PC a start offset of SHA256(hostname) % 5 MINUTES and then repeats every 5
|
||||
# minutes, which was sized for reading a few KB of JSON. A driver set is 100 MB
|
||||
# for the two universals and 226 MB for a full site, so the day an entry lands
|
||||
# the whole fleet pulls it inside one 5-minute window: roughly 30 GB across 300
|
||||
# bays, on the same share every bay needs for everything else. The failure is not
|
||||
# slow drivers, it is a floor that stops converging.
|
||||
#
|
||||
# -WaveStart with -Waves spreads that out. Each PC derives its own wave from its
|
||||
# hostname and does nothing until its turn, so there is no central coordination,
|
||||
# no per-bay configuration and nothing to reconcile afterwards. The hash is the
|
||||
# same idiom Register-GEEnforce.ps1 uses for its offset, SHA-256 rather than MD5
|
||||
# because FIPS-enforced bays disable MD5 outright.
|
||||
#
|
||||
# A bay switched off during its wave installs on its next cycle instead. Late is
|
||||
# a non-event here; the wave sets the earliest moment, not a deadline.
|
||||
#
|
||||
# Unparseable wave arguments FAIL CLOSED - nothing installs, and it says so every
|
||||
# cycle. Failing open would restore precisely the stampede this exists to avoid,
|
||||
# and 30 GB cannot be un-sent, whereas a typo that installs nothing is loud in
|
||||
# the log and fixed in a minute.
|
||||
|
||||
param(
|
||||
# Defaults to drivers.json beside this script.
|
||||
[string]$Manifest = '',
|
||||
|
||||
# Install only these driver names; everything else in the manifest is
|
||||
# ignored. For a bay that needs one driver out of a site-wide set.
|
||||
[string[]]$Only = @(),
|
||||
|
||||
# Report what is missing and change nothing. This is what a DSC TestScript
|
||||
# calls: exit 0 means compliant. A bay whose wave has not arrived is
|
||||
# compliant BY DESIGN - not installed is its desired state today.
|
||||
[switch]$TestOnly,
|
||||
|
||||
# Date the rollout opens, e.g. '2026-08-25' or '2026-08-25 22:00'. Empty
|
||||
# means no gating at all, which is right for imaging time: a bay being built
|
||||
# is one bay, and it should come off the line complete.
|
||||
[string]$WaveStart = '',
|
||||
|
||||
# How many waves to spread the fleet across. 0 or 1 means everyone at once.
|
||||
# 300 bays over 10 daily waves is ~30 bays and ~3 GB a day.
|
||||
[int]$Waves = 0,
|
||||
|
||||
# Wave spacing. Hours finishes a 10-wave rollout inside a day; Days is the
|
||||
# cautious setting when nobody is watching the share.
|
||||
[ValidateSet('Days', 'Hours')]
|
||||
[string]$WaveUnit = 'Days',
|
||||
|
||||
# Pilot bays skip the gate. Use this to prove one bay before the fleet.
|
||||
[switch]$IgnoreWave
|
||||
)
|
||||
|
||||
$ErrorActionPreference = 'Continue'
|
||||
|
||||
$here = Split-Path -Parent $MyInvocation.MyCommand.Path
|
||||
if (-not $Manifest) { $Manifest = Join-Path $here 'drivers.json' }
|
||||
|
||||
$logDir = 'C:\Logs\Shopfloor'
|
||||
if (-not (Test-Path $logDir)) {
|
||||
New-Item -ItemType Directory -Path $logDir -Force -ErrorAction SilentlyContinue | Out-Null
|
||||
}
|
||||
$logFile = Join-Path $logDir ('printer-drivers-{0}.log' -f (Get-Date -Format 'yyyyMMdd'))
|
||||
function Log([string]$msg) {
|
||||
$ts = Get-Date -Format 'yyyy-MM-dd HH:mm:ss'
|
||||
"$ts [set] $msg" | Tee-Object -FilePath $logFile -Append | Out-Null
|
||||
}
|
||||
|
||||
# The gate runs BEFORE the manifest is read, because the manifest lives on the
|
||||
# share too. A bay that is not due this wave must not touch the share at all -
|
||||
# reading it is cheap, but 300 bays deciding to read it in the same 5 minutes is
|
||||
# how this whole problem starts.
|
||||
if ($WaveStart -and -not $IgnoreWave) {
|
||||
$start = [datetime]::MinValue
|
||||
if (-not [datetime]::TryParse($WaveStart, [ref]$start)) {
|
||||
Log "ERROR -WaveStart '$WaveStart' is not a date. Refusing to install."
|
||||
Log ' (failing closed on purpose: guessing here would release the whole fleet at once)'
|
||||
exit 1
|
||||
}
|
||||
|
||||
$waveCount = $Waves
|
||||
if ($waveCount -lt 1) { $waveCount = 1 }
|
||||
|
||||
# Same hostname hash as the enforcer's own start offset, so a bay's wave is
|
||||
# stable for the life of its name: it cannot drift between cycles, and a
|
||||
# rerun never moves a PC into a different wave.
|
||||
$hostHash = [System.BitConverter]::ToUInt32(
|
||||
[System.Security.Cryptography.SHA256]::Create().ComputeHash(
|
||||
[System.Text.Encoding]::UTF8.GetBytes([System.Environment]::MachineName)), 0)
|
||||
$wave = [int]($hostHash % [uint32]$waveCount)
|
||||
|
||||
if ($WaveUnit -eq 'Hours') { $due = $start.AddHours($wave) }
|
||||
else { $due = $start.AddDays($wave) }
|
||||
|
||||
if ((Get-Date) -lt $due) {
|
||||
Log ("wave {0} of {1} for {2}; not due until {3}. Nothing to do." -f `
|
||||
$wave, $waveCount, [System.Environment]::MachineName,
|
||||
$due.ToString('yyyy-MM-dd HH:mm'))
|
||||
exit 0
|
||||
}
|
||||
Log ("wave {0} of {1} opened {2}; proceeding" -f `
|
||||
$wave, $waveCount, $due.ToString('yyyy-MM-dd HH:mm'))
|
||||
}
|
||||
|
||||
if (-not (Test-Path $Manifest)) {
|
||||
Log "ERROR manifest not found: $Manifest"
|
||||
exit 1
|
||||
}
|
||||
|
||||
try {
|
||||
$config = Get-Content -Raw -Path $Manifest | ConvertFrom-Json
|
||||
} catch {
|
||||
Log "ERROR manifest is not valid JSON: $($_.Exception.Message)"
|
||||
exit 1
|
||||
}
|
||||
|
||||
$wanted = @($config.drivers)
|
||||
if ($Only.Count -gt 0) {
|
||||
$wanted = @($wanted | Where-Object { $Only -contains $_.drivername })
|
||||
}
|
||||
if ($wanted.Count -eq 0) {
|
||||
Log "nothing to do: the manifest selects no drivers"
|
||||
exit 0
|
||||
}
|
||||
|
||||
$single = Join-Path $here 'Install-ShopdbPrinterDriver.ps1'
|
||||
if (-not (Test-Path $single)) {
|
||||
Log "ERROR Install-ShopdbPrinterDriver.ps1 is not beside this script"
|
||||
exit 1
|
||||
}
|
||||
|
||||
$missing = @()
|
||||
foreach ($driver in $wanted) {
|
||||
$name = $driver.drivername
|
||||
if (-not $name) { continue }
|
||||
|
||||
if (Get-PrinterDriver -Name $name -ErrorAction SilentlyContinue) {
|
||||
Log "present: $name"
|
||||
continue
|
||||
}
|
||||
|
||||
if ($TestOnly) {
|
||||
Log "MISSING: $name"
|
||||
$missing += $name
|
||||
continue
|
||||
}
|
||||
|
||||
# Relative paths are resolved against the package, so the whole thing can be
|
||||
# copied anywhere - a share, C:\ProgramData, an Intune staging folder - and
|
||||
# still find its own payloads.
|
||||
$path = $driver.path
|
||||
if ($path -and -not [System.IO.Path]::IsPathRooted($path)) {
|
||||
$path = Join-Path $here $path
|
||||
}
|
||||
if (-not $path -or -not (Test-Path $path)) {
|
||||
Log "ERROR package not found for '$name': $path"
|
||||
$missing += $name
|
||||
continue
|
||||
}
|
||||
|
||||
Log "installing: $name"
|
||||
& $single -DriverName $name -Source $path | Out-Null
|
||||
|
||||
if (Get-PrinterDriver -Name $name -ErrorAction SilentlyContinue) {
|
||||
Log "installed: $name"
|
||||
} else {
|
||||
Log "FAILED: $name (see the per-driver lines above)"
|
||||
$missing += $name
|
||||
}
|
||||
}
|
||||
|
||||
if ($missing.Count -gt 0) {
|
||||
Log ("not present: {0}" -f ($missing -join ', '))
|
||||
exit 1
|
||||
}
|
||||
Log "all $($wanted.Count) driver(s) present"
|
||||
exit 0
|
||||
314
plugins/printers/client/Report-PrintersToShopDB.ps1
Normal file
314
plugins/printers/client/Report-PrintersToShopDB.ps1
Normal file
@@ -0,0 +1,314 @@
|
||||
# Report-PrintersToShopDB.ps1
|
||||
#
|
||||
# Reports the print queues this PC ACTUALLY has to ShopDB, so the register can
|
||||
# be compared against what the bay is SUPPOSED to have. ShopDB knows the
|
||||
# assignment (GET /api/printers/for-host/<hostname>, applied by
|
||||
# Set-ShopdbPrinters.ps1); it has never known what is really installed. This is
|
||||
# that missing half.
|
||||
#
|
||||
# TARGET: the ADR-006 collector API.
|
||||
# POST <shopdb>/api/collector/printers
|
||||
# The server is NOT baked in. It comes from HKLM:\SOFTWARE\GE\ShopDB BaseUrl,
|
||||
# which Install-GEEnforce.ps1 provisions and the enforcement client already
|
||||
# needs, or from -ApiUrl in the manifest entry's Args. ADR-015: a site name in
|
||||
# product code is a defect, and this script ships to every site.
|
||||
#
|
||||
# READ ONLY. It calls nothing that creates, changes or removes a queue, a port
|
||||
# or a driver - only Get-*. Convergence is Set-ShopdbPrinters.ps1's job and
|
||||
# stays there; a reporter that also fixes things cannot be trusted to tell you
|
||||
# what was broken.
|
||||
#
|
||||
# OBSERVED IS NOT ASSIGNED. The server stores this in its own table and never
|
||||
# turns it into an assignment on its own. A drifted bay reporting its drift must
|
||||
# not be able to redefine what correct means.
|
||||
#
|
||||
# THE LATEST REPORT REPLACES THE PREVIOUS ONE for this hostname, which makes an
|
||||
# empty queues list a legitimate "this bay has no printers" and wipes the host's
|
||||
# observed rows. So a FAILED enumeration must send NOTHING rather than an empty
|
||||
# list - see the $enumerated flag below. Reporting nothing loses one cycle;
|
||||
# reporting [] after a WMI hiccup deletes real state and reads as a bay that
|
||||
# lost its printers.
|
||||
#
|
||||
# AUTH: the collector API does NOT honor the GE-Enforce IP allowlist (that only
|
||||
# covers the geenforce fetch/report endpoints). It needs a collector.ingest key,
|
||||
# sent as the X-API-Key header. The key is read from HKLM:\SOFTWARE\GE\ShopDB
|
||||
# CollectorKey (the same secret store Report-AssetToShopDB.ps1 uses; provisioned
|
||||
# at imaging), or overridden via the manifest entry's Args -ApiKey. Never bake
|
||||
# the key into the manifest JSON on the share.
|
||||
#
|
||||
# Runs every GE-Enforce cycle as a Type=PS1 / DetectionMethod=Always entry under
|
||||
# the SYSTEM task. Always exits 0 so a printer problem never fails an
|
||||
# enforcement run; failures are logged, never thrown.
|
||||
|
||||
param(
|
||||
# Flask collector endpoint for the printers plugin. Empty resolves from
|
||||
# HKLM:\SOFTWARE\GE\ShopDB BaseUrl; override here if the path ever moves.
|
||||
[string]$ApiUrl = '',
|
||||
|
||||
# collector.ingest key (X-API-Key). Default: read from the GE-Enforce secret
|
||||
# store in the registry. Override with -ApiKey via Args for testing.
|
||||
[string]$ApiKey = '',
|
||||
|
||||
# Identity field of the payload. Defaults to this machine's name, which is
|
||||
# what the assignment side (for-host) and the computers collector both key on.
|
||||
[string]$Hostname = $env:COMPUTERNAME,
|
||||
|
||||
[int]$TimeoutSec = 30,
|
||||
|
||||
# Enumerate and log the payload, post nothing. For proving what a bay would
|
||||
# report before a site is pointed at a live server.
|
||||
[switch]$WhatIfOnly
|
||||
)
|
||||
|
||||
$ErrorActionPreference = 'Continue'
|
||||
|
||||
# Force TLS 1.2 - older images default to SystemDefault which may negotiate a
|
||||
# protocol the site rejects; the collector POST is HTTPS.
|
||||
[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12
|
||||
|
||||
$logDir = 'C:\Logs\Shopfloor'
|
||||
if (-not (Test-Path $logDir)) {
|
||||
New-Item -ItemType Directory -Path $logDir -Force -ErrorAction SilentlyContinue | Out-Null
|
||||
}
|
||||
$logFile = Join-Path $logDir ('report-printers-{0}.log' -f (Get-Date -Format 'yyyyMMdd'))
|
||||
|
||||
function Log([string]$msg) {
|
||||
$ts = Get-Date -Format 'yyyy-MM-dd HH:mm:ss'
|
||||
"$ts $msg" | Tee-Object -FilePath $logFile -Append | Out-Null
|
||||
}
|
||||
|
||||
$REGPATHS = @('HKLM:\SOFTWARE\GE\ShopDB', 'HKLM:\SOFTWARE\WOW6432Node\GE\ShopDB')
|
||||
|
||||
function Get-ShopdbRegValue([string]$name) {
|
||||
foreach ($path in $REGPATHS) {
|
||||
try {
|
||||
if (Test-Path $path) {
|
||||
$value = [string](Get-ItemProperty -Path $path -Name $name -ErrorAction Stop).$name
|
||||
if ($value -and $value.Trim()) { return $value.Trim() }
|
||||
}
|
||||
} catch {}
|
||||
}
|
||||
return ''
|
||||
}
|
||||
|
||||
Log "=== Report printers to ShopDB (collector) : $Hostname ==="
|
||||
|
||||
# Server from the GE-Enforce config hive when not passed via Args. Any site
|
||||
# running this script is running the enforcement client, which cannot work
|
||||
# without BaseUrl, so it is present wherever this is deployed.
|
||||
if (-not $ApiUrl) {
|
||||
$base = Get-ShopdbRegValue 'BaseUrl'
|
||||
if ($base) { $ApiUrl = $base.TrimEnd('/') + '/api/collector/printers' }
|
||||
}
|
||||
if (-not $ApiUrl -and -not $WhatIfOnly) {
|
||||
Log 'ERROR no ShopDB URL (HKLM:\SOFTWARE\GE\ShopDB BaseUrl or -ApiUrl). Skipping.'
|
||||
exit 0
|
||||
}
|
||||
|
||||
# collector key from the GE-Enforce secret store when not passed via Args.
|
||||
if (-not $ApiKey) { $ApiKey = Get-ShopdbRegValue 'CollectorKey' }
|
||||
if (-not $ApiKey -and -not $WhatIfOnly) {
|
||||
Log 'ERROR no collector key (HKLM:\SOFTWARE\GE\ShopDB CollectorKey or -ApiKey). Skipping.'
|
||||
exit 0
|
||||
}
|
||||
|
||||
# Queues that are not devices: the Windows-supplied virtual printers plus the
|
||||
# Office writers. They exist on every image, match nothing in the register, and
|
||||
# would each land as an UNKNOWN row on every bay in the fleet.
|
||||
#
|
||||
# Matched on the PORT, not the queue name, because the name is whatever a user
|
||||
# renamed it to while the port of a virtual device is fixed. Two of them are
|
||||
# matched on driver as well, since a redirected-port queue can share PORTPROMPT.
|
||||
$VIRTUALPORTS = @('PORTPROMPT:', 'SHRFAX:', 'XPSPort:', 'nul:', 'NUL:')
|
||||
$VIRTUALDRIVERS = @(
|
||||
'Microsoft XPS Document Writer',
|
||||
'Microsoft XPS Document Writer v4',
|
||||
'Microsoft Print To PDF',
|
||||
'Microsoft Shared Fax Driver',
|
||||
'Send to Microsoft OneNote Driver',
|
||||
'Microsoft Software Printer Driver'
|
||||
)
|
||||
|
||||
function Test-VirtualQueue([string]$portname, [string]$drivername) {
|
||||
foreach ($p in $VIRTUALPORTS) {
|
||||
if ($portname -and $portname.Trim().ToLower() -eq $p.ToLower()) { return $true }
|
||||
}
|
||||
# OneNote's port is a per-install GUID path, so it can only be caught here.
|
||||
if ($portname -and $portname -like 'Microsoft.Office.OneNote*') { return $true }
|
||||
foreach ($d in $VIRTUALDRIVERS) {
|
||||
if ($drivername -and $drivername.Trim().ToLower() -eq $d.ToLower()) { return $true }
|
||||
}
|
||||
return $false
|
||||
}
|
||||
|
||||
# Port address is the primary match key server-side: an IP or FQDN is
|
||||
# unambiguous where a queue name is a local habit. Built once as a lookup so a
|
||||
# bay with 8 queues does not re-enumerate ports 8 times.
|
||||
#
|
||||
# A port with no host address (USB, WSD, a redirected port) reports a null
|
||||
# address and matches on name alone, which is correct: a locally attached
|
||||
# printer is still a real printer worth seeing.
|
||||
$portAddresses = @{}
|
||||
$portsRead = $false
|
||||
try {
|
||||
foreach ($port in (Get-PrinterPort -ErrorAction Stop)) {
|
||||
$address = ''
|
||||
if ($port.PSObject.Properties['PrinterHostAddress']) {
|
||||
$address = [string]$port.PrinterHostAddress
|
||||
}
|
||||
if ($port.Name) { $portAddresses[[string]$port.Name] = $address.Trim() }
|
||||
}
|
||||
$portsRead = $true
|
||||
} catch {
|
||||
Log "WARN Get-PrinterPort failed, falling back to WMI ports: $($_.Exception.Message)"
|
||||
}
|
||||
if (-not $portsRead) {
|
||||
# PS 5.1-era hosts without the PrintManagement module, and images where the
|
||||
# spooler cmdlets are broken but WMI still answers.
|
||||
try {
|
||||
foreach ($port in (Get-CimInstance -ClassName Win32_TCPIPPrinterPort -ErrorAction Stop)) {
|
||||
if ($port.Name) { $portAddresses[[string]$port.Name] = ([string]$port.HostAddress).Trim() }
|
||||
}
|
||||
$portsRead = $true
|
||||
} catch {
|
||||
# Not fatal: queues still report, just without an address to match on.
|
||||
Log "WARN could not read printer ports at all: $($_.Exception.Message)"
|
||||
}
|
||||
}
|
||||
|
||||
# The queues themselves. $enumerated stays false unless a read actually
|
||||
# succeeded, because "no queues" and "could not look" are the same empty list
|
||||
# and the server treats them very differently (see the header).
|
||||
$queues = @()
|
||||
$enumerated = $false
|
||||
try {
|
||||
foreach ($printer in (Get-Printer -ErrorAction Stop)) {
|
||||
$queues += [pscustomobject]@{
|
||||
queuename = [string]$printer.Name
|
||||
drivername = [string]$printer.DriverName
|
||||
portname = [string]$printer.PortName
|
||||
}
|
||||
}
|
||||
$enumerated = $true
|
||||
} catch {
|
||||
Log "WARN Get-Printer failed, falling back to WMI queues: $($_.Exception.Message)"
|
||||
}
|
||||
if (-not $enumerated) {
|
||||
try {
|
||||
foreach ($printer in (Get-CimInstance -ClassName Win32_Printer -ErrorAction Stop)) {
|
||||
$queues += [pscustomobject]@{
|
||||
queuename = [string]$printer.Name
|
||||
drivername = [string]$printer.DriverName
|
||||
portname = [string]$printer.PortName
|
||||
}
|
||||
}
|
||||
$enumerated = $true
|
||||
} catch {
|
||||
Log "ERROR could not enumerate printers: $($_.Exception.Message)"
|
||||
}
|
||||
}
|
||||
|
||||
if (-not $enumerated) {
|
||||
# Deliberately posts nothing. An empty report REPLACES this host's observed
|
||||
# rows, so a failed read must not be able to claim the bay has no printers.
|
||||
Log 'ERROR enumeration failed; posting NOTHING so the last good report stands.'
|
||||
exit 0
|
||||
}
|
||||
|
||||
# Which queue the interactive user actually prints to. This process is SYSTEM,
|
||||
# and the default printer is per user, so Win32_Printer.Default here describes
|
||||
# the SYSTEM session and is usually wrong. Read the console user's own value
|
||||
# first: HKU\<sid>\...\Windows Device holds "<queue>,winspool,<port>".
|
||||
$defaultName = ''
|
||||
try {
|
||||
$consoleUser = [string](Get-CimInstance -ClassName Win32_ComputerSystem -ErrorAction Stop).UserName
|
||||
if ($consoleUser) {
|
||||
$sid = (New-Object System.Security.Principal.NTAccount($consoleUser)).Translate(
|
||||
[System.Security.Principal.SecurityIdentifier]).Value
|
||||
$devicePath = "Registry::HKEY_USERS\$sid\Software\Microsoft\Windows NT\CurrentVersion\Windows"
|
||||
$device = [string](Get-ItemProperty -Path $devicePath -Name Device -ErrorAction Stop).Device
|
||||
if ($device) { $defaultName = ($device -split ',')[0].Trim() }
|
||||
if ($defaultName) { Log "default for $consoleUser : $defaultName" }
|
||||
}
|
||||
} catch {
|
||||
# Nobody logged on, a roaming hive not loaded, or a name that will not
|
||||
# translate. Not worth a warning every cycle on an unattended bay.
|
||||
}
|
||||
if (-not $defaultName) {
|
||||
# Falls back to whatever this session sees. Marked in the log because a
|
||||
# SYSTEM-session default is weak evidence and a reviewer should know which
|
||||
# one they are looking at before seeding an assignment from it.
|
||||
try {
|
||||
$sysDefault = Get-CimInstance -ClassName Win32_Printer -ErrorAction Stop |
|
||||
Where-Object { $_.Default } | Select-Object -First 1
|
||||
if ($sysDefault) {
|
||||
$defaultName = [string]$sysDefault.Name
|
||||
Log "default from the SYSTEM session (no console user): $defaultName"
|
||||
}
|
||||
} catch {}
|
||||
}
|
||||
|
||||
$reported = @()
|
||||
$skipped = 0
|
||||
foreach ($queue in $queues) {
|
||||
if (-not $queue.queuename) { continue }
|
||||
if (Test-VirtualQueue $queue.portname $queue.drivername) { $skipped++; continue }
|
||||
|
||||
$portAddress = ''
|
||||
if ($queue.portname -and $portAddresses.ContainsKey($queue.portname)) {
|
||||
$portAddress = [string]$portAddresses[$queue.portname]
|
||||
}
|
||||
|
||||
$row = @{
|
||||
queuename = $queue.queuename
|
||||
isdefault = ($defaultName -and $queue.queuename -eq $defaultName)
|
||||
}
|
||||
# Sent only when present: a null is "not known", and an empty string would
|
||||
# read as a driver or a port genuinely named nothing.
|
||||
if ($queue.drivername) { $row['drivername'] = $queue.drivername }
|
||||
if ($queue.portname) { $row['portname'] = $queue.portname }
|
||||
if ($portAddress) { $row['portaddress'] = $portAddress }
|
||||
|
||||
$reported += $row
|
||||
Log ("queue: {0} | driver={1} | port={2} | address={3} | default={4}" -f `
|
||||
$queue.queuename, $queue.drivername, $queue.portname, $portAddress, $row['isdefault'])
|
||||
}
|
||||
|
||||
Log "reporting $($reported.Count) queue(s), $skipped virtual queue(s) skipped"
|
||||
if ($reported.Count -eq 0) {
|
||||
# Legitimate and meaningful: it clears this host's observed rows so the
|
||||
# comparison shows every assigned printer as missing, which is exactly what
|
||||
# a bay with no queues is.
|
||||
Log 'no real queues on this host; reporting an empty set (clears observed state)'
|
||||
}
|
||||
|
||||
# Collector schema fields (lowercase concatenated). hostname is the identity
|
||||
# field. observedat is sent for the record and named to match the declared
|
||||
# collector schema; the server stamps its own and ignores this one.
|
||||
$body = @{
|
||||
hostname = $Hostname
|
||||
queues = @($reported)
|
||||
observedat = (Get-Date).ToUniversalTime().ToString('yyyy-MM-ddTHH:mm:ss')
|
||||
}
|
||||
|
||||
# Depth 4 covers hostname -> queues -> row -> value; the default of 2 flattens
|
||||
# the rows to type names.
|
||||
$json = $body | ConvertTo-Json -Compress -Depth 4
|
||||
|
||||
if ($WhatIfOnly) {
|
||||
Log "WOULD POST $ApiUrl $json"
|
||||
exit 0
|
||||
}
|
||||
|
||||
Log ("POST {0} host={1} queues={2}" -f $ApiUrl, $Hostname, $reported.Count)
|
||||
try {
|
||||
$response = Invoke-RestMethod -Uri $ApiUrl -Method Post -Body $json `
|
||||
-ContentType 'application/json' `
|
||||
-Headers @{ 'X-API-Key' = $ApiKey } `
|
||||
-TimeoutSec $TimeoutSec -ErrorAction Stop
|
||||
Log ("RESPONSE {0}" -f ($response | ConvertTo-Json -Compress -Depth 4))
|
||||
} catch {
|
||||
Log "ERROR POST failed: $($_.Exception.Message)"
|
||||
}
|
||||
|
||||
exit 0
|
||||
379
plugins/printers/client/Set-ShopdbPrinters.ps1
Normal file
379
plugins/printers/client/Set-ShopdbPrinters.ps1
Normal file
@@ -0,0 +1,379 @@
|
||||
# Set-ShopdbPrinters.ps1
|
||||
#
|
||||
# Makes this PC's printers match what ShopDB says the bay should have. Asks
|
||||
# GET /api/printers/for-host/<hostname> and creates any queue that is missing.
|
||||
#
|
||||
# WHY THE ASSIGNMENT IS NOT ON THIS PC: it is on the MACHINE, and reaches
|
||||
# whichever PC controls it. A reimaged or swapped box inherits the bay's printers
|
||||
# with nothing saved off the old one - the asset register is the backup.
|
||||
#
|
||||
# CONVERGES, does not install. A queue that already exists is left alone, so this
|
||||
# is cheap to run every enforcement cycle and safe to run twice.
|
||||
#
|
||||
# NEVER REMOVES A QUEUE. If a printer disappears from the response - because the
|
||||
# API had a bad minute, or someone unassigned it - the bay keeps printing. Taking
|
||||
# printers away from a working bay because of a transient error is the one
|
||||
# failure this must not have.
|
||||
#
|
||||
# DRIVERS ARE NOT FETCHED HERE. Install-ShopdbPrinterDrivers.ps1 stages the site's
|
||||
# set in the common scope, once per bay. A queue is created against a driver that
|
||||
# is already present; if it is not, that is logged and the printer is skipped,
|
||||
# because downloading 48 MB while somebody waits to print is the wrong moment.
|
||||
#
|
||||
# THE DEFAULT PRINTER IS PER USER. This runs as SYSTEM and cannot set it for the
|
||||
# logged-on person, so it records the desired default in HKLM and leaves applying
|
||||
# it to a logon task. Without that, SYSTEM would set a default nobody sees.
|
||||
#
|
||||
# IT ALSO REGISTERS THAT LOGON TASK, and stages a LOCAL copy of
|
||||
# Apply-ShopdbDefaultPrinter.ps1 for it to run. Recording a default that nothing
|
||||
# ever applies was the gap: the queues appeared, the default never moved. The
|
||||
# local copy is not tidiness - the share this script runs from is mounted only
|
||||
# for the enforcement cycle, and the task fires at logon when it is gone.
|
||||
#
|
||||
# Exits 0 always: a printer problem must not fail an enforcement run.
|
||||
|
||||
param(
|
||||
# ShopDB base URL. Empty resolves from HKLM:\SOFTWARE\GE\ShopDB BaseUrl,
|
||||
# written by Install-GEEnforce.ps1 and already present wherever this runs.
|
||||
[string]$BaseUrl = '',
|
||||
|
||||
# Defaults to this machine's name, which is what the collector upserts by.
|
||||
[string]$Hostname = $env:COMPUTERNAME,
|
||||
|
||||
[int]$TimeoutSec = 30,
|
||||
|
||||
# Where the per-user logon script is staged. Anywhere is fine as long as it
|
||||
# is on this PC and every user can read it.
|
||||
[string]$LocalScriptDir = (Join-Path ([Environment]::GetFolderPath('CommonApplicationData')) 'ShopDB'),
|
||||
|
||||
[string]$LogonTaskName = 'ShopDB default printer',
|
||||
|
||||
# The task runs as a GROUP, not a person: a shared bay has no one owner and
|
||||
# the default must be applied for whoever logs on. If this name does not
|
||||
# resolve - it is localised on non-English Windows - the well-known SID is
|
||||
# tried instead.
|
||||
[string]$UsersGroup = 'BUILTIN\Users',
|
||||
|
||||
# 0 means at logon only. A shared bay where people pick their own default
|
||||
# can be pulled back on a repeat; a single-user PC should not be, so the
|
||||
# neutral default is the one that does not argue with the user.
|
||||
[int]$RepeatMinutes = 0,
|
||||
|
||||
# For a site that deploys the logon task by GPO instead.
|
||||
[switch]$NoLogonTask,
|
||||
|
||||
# Report what would change and touch nothing.
|
||||
[switch]$WhatIfOnly
|
||||
)
|
||||
|
||||
$ErrorActionPreference = 'Continue'
|
||||
[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12
|
||||
|
||||
$logDir = 'C:\Logs\Shopfloor'
|
||||
if (-not (Test-Path $logDir)) {
|
||||
New-Item -ItemType Directory -Path $logDir -Force -ErrorAction SilentlyContinue | Out-Null
|
||||
}
|
||||
$logFile = Join-Path $logDir ('printers-{0}.log' -f (Get-Date -Format 'yyyyMMdd'))
|
||||
function Log([string]$msg) {
|
||||
$ts = Get-Date -Format 'yyyy-MM-dd HH:mm:ss'
|
||||
"$ts $msg" | Tee-Object -FilePath $logFile -Append | Out-Null
|
||||
}
|
||||
|
||||
# Resolved once, at script scope: $PSScriptRoot is empty when the file is piped
|
||||
# into powershell rather than run by path, and the logon script sits beside this
|
||||
# one.
|
||||
$SCRIPTDIR = $PSScriptRoot
|
||||
if (-not $SCRIPTDIR -and $MyInvocation.MyCommand.Path) {
|
||||
$SCRIPTDIR = Split-Path -Parent $MyInvocation.MyCommand.Path
|
||||
}
|
||||
|
||||
function Ensure-LogonTask {
|
||||
# Half of this feature is per-user state that SYSTEM cannot write. All SYSTEM
|
||||
# can do is arrange for something to run AS the user later, which is this
|
||||
# task. Nothing else registered it, so the default was recorded every cycle
|
||||
# and applied never.
|
||||
if ($NoLogonTask) {
|
||||
Log 'logon task: skipped (-NoLogonTask)'
|
||||
return
|
||||
}
|
||||
|
||||
$source = ''
|
||||
if ($SCRIPTDIR) { $source = Join-Path $SCRIPTDIR 'Apply-ShopdbDefaultPrinter.ps1' }
|
||||
if (-not $source -or -not (Test-Path $source)) {
|
||||
Log "SKIP logon task: Apply-ShopdbDefaultPrinter.ps1 is not beside this script"
|
||||
return
|
||||
}
|
||||
|
||||
# THE LOCAL COPY IS LOAD-BEARING. This script runs from a share that is
|
||||
# mounted only for the enforcement cycle; the task fires at logon, when the
|
||||
# share is gone. A task pointing at the share never runs and says nothing.
|
||||
$localscript = Join-Path $LocalScriptDir 'Apply-ShopdbDefaultPrinter.ps1'
|
||||
$refreshed = $false
|
||||
try {
|
||||
if (-not (Test-Path $LocalScriptDir)) {
|
||||
# Inherited ACL is what is wanted here: every user can read it, only
|
||||
# admins can write it, so the task cannot be pointed somewhere else.
|
||||
New-Item -ItemType Directory -Path $LocalScriptDir -Force -ErrorAction Stop | Out-Null
|
||||
}
|
||||
$stale = $true
|
||||
if (Test-Path $localscript) {
|
||||
$stale = (Get-FileHash -Path $localscript -Algorithm SHA256).Hash -ne
|
||||
(Get-FileHash -Path $source -Algorithm SHA256).Hash
|
||||
}
|
||||
if ($stale) {
|
||||
if ($WhatIfOnly) {
|
||||
Log "WOULD stage the logon script at $localscript"
|
||||
} else {
|
||||
Copy-Item -Path $source -Destination $localscript -Force -ErrorAction Stop
|
||||
$refreshed = $true
|
||||
Log "staged the logon script at $localscript"
|
||||
}
|
||||
}
|
||||
} catch {
|
||||
# No local copy means no task worth registering - a task pointing at a
|
||||
# file that is not there is worse than no task, because it looks fine.
|
||||
Log "ERROR staging ${localscript}: $($_.Exception.Message)"
|
||||
return
|
||||
}
|
||||
|
||||
$arguments = "-NoProfile -ExecutionPolicy Bypass -WindowStyle Hidden -File `"$localscript`""
|
||||
|
||||
$task = Get-ScheduledTask -TaskName $LogonTaskName -ErrorAction SilentlyContinue
|
||||
if ($task -and -not $refreshed) {
|
||||
# Re-registering every cycle throws away the task's run history, which
|
||||
# is the only evidence it ever fired. So it is replaced only when it
|
||||
# points somewhere other than the local copy, or has no group principal
|
||||
# - a task left behind running as one person applies one person's
|
||||
# default. Matched on the PATH rather than the whole argument string
|
||||
# because Task Scheduler is free to normalise quoting, and an exact
|
||||
# compare would churn over a difference that changes nothing.
|
||||
$registered = @($task.Actions)[0]
|
||||
$pointslocal = $registered -and $registered.Arguments -and
|
||||
$registered.Arguments.IndexOf($localscript, [StringComparison]::OrdinalIgnoreCase) -ge 0
|
||||
if ($pointslocal -and $task.Principal.GroupId) {
|
||||
Log "logon task present: $LogonTaskName"
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
if ($WhatIfOnly) {
|
||||
Log "WOULD register the logon task: $LogonTaskName -> $localscript"
|
||||
return
|
||||
}
|
||||
|
||||
try {
|
||||
$triggers = @(New-ScheduledTaskTrigger -AtLogOn)
|
||||
if ($RepeatMinutes -gt 0) {
|
||||
$triggers += New-ScheduledTaskTrigger -Once -At (Get-Date) `
|
||||
-RepetitionInterval (New-TimeSpan -Minutes $RepeatMinutes)
|
||||
}
|
||||
$action = New-ScheduledTaskAction -Execute 'powershell.exe' -Argument $arguments
|
||||
$settings = New-ScheduledTaskSettingsSet -AllowStartIfOnBatteries `
|
||||
-DontStopIfGoingOnBatteries -StartWhenAvailable
|
||||
} catch {
|
||||
# An SKU without the ScheduledTasks module is the likely reason. Nothing
|
||||
# to register with, and still not a reason to fail the run.
|
||||
Log "ERROR building the logon task: $($_.Exception.Message)"
|
||||
return
|
||||
}
|
||||
|
||||
# Limited, not Highest: setting your own default printer needs no elevation,
|
||||
# and a task the whole Users group can trigger should not have any.
|
||||
$candidates = @($UsersGroup)
|
||||
if ($UsersGroup -ne 'S-1-5-32-545') { $candidates += 'S-1-5-32-545' }
|
||||
|
||||
$lasterror = 'no principal accepted'
|
||||
foreach ($groupid in $candidates) {
|
||||
try {
|
||||
$principal = New-ScheduledTaskPrincipal -GroupId $groupid -RunLevel Limited -ErrorAction Stop
|
||||
Register-ScheduledTask -TaskName $LogonTaskName -Action $action -Trigger $triggers `
|
||||
-Principal $principal -Settings $settings -Force -ErrorAction Stop | Out-Null
|
||||
Log "registered the logon task: $LogonTaskName as $groupid"
|
||||
return
|
||||
} catch {
|
||||
$lasterror = $_.Exception.Message
|
||||
}
|
||||
}
|
||||
|
||||
# A missing logon task means the default is not applied. It does not mean the
|
||||
# queues are wrong, so it is logged and the run carries on.
|
||||
Log "ERROR registering ${LogonTaskName}: $lasterror"
|
||||
}
|
||||
|
||||
$REGPATH = 'HKLM:\SOFTWARE\GE\ShopDB'
|
||||
|
||||
if (-not $BaseUrl) {
|
||||
foreach ($path in @($REGPATH, 'HKLM:\SOFTWARE\WOW6432Node\GE\ShopDB')) {
|
||||
try {
|
||||
if (Test-Path $path) {
|
||||
$value = [string](Get-ItemProperty -Path $path -Name BaseUrl -ErrorAction Stop).BaseUrl
|
||||
if ($value -and $value.Trim()) { $BaseUrl = $value.Trim(); break }
|
||||
}
|
||||
} catch {}
|
||||
}
|
||||
}
|
||||
if (-not $BaseUrl) {
|
||||
Log 'ERROR no ShopDB URL (HKLM:\SOFTWARE\GE\ShopDB BaseUrl or -BaseUrl). Skipping.'
|
||||
exit 0
|
||||
}
|
||||
|
||||
Log "=== Set printers for $Hostname ==="
|
||||
|
||||
# Before the API call on purpose: the task depends on files on this PC, not on
|
||||
# the server. A bad minute from the API must not leave a bay with no way to apply
|
||||
# the default it was already told about.
|
||||
Ensure-LogonTask
|
||||
|
||||
$url = $BaseUrl.TrimEnd('/') + '/api/printers/for-host/' + [uri]::EscapeDataString($Hostname)
|
||||
try {
|
||||
$response = Invoke-RestMethod -Uri $url -Method Get -TimeoutSec $TimeoutSec
|
||||
} catch {
|
||||
# An unreachable server means "no information", not "no printers". Changing
|
||||
# nothing is the only safe response.
|
||||
Log "ERROR could not read $url : $($_.Exception.Message)"
|
||||
exit 0
|
||||
}
|
||||
|
||||
$payload = $response.data
|
||||
if ($null -eq $payload) { $payload = $response }
|
||||
$wanted = @($payload.printers)
|
||||
$defaultid = $payload.defaultprinterid
|
||||
|
||||
if ($wanted.Count -eq 0) {
|
||||
Log 'nothing assigned to this host'
|
||||
exit 0
|
||||
}
|
||||
Log "assigned: $($wanted.Count) printer(s)"
|
||||
|
||||
function Ensure-Port([string]$address) {
|
||||
$portname = 'IP_' + $address
|
||||
if (-not (Get-PrinterPort -Name $portname -ErrorAction SilentlyContinue)) {
|
||||
Add-PrinterPort -Name $portname -PrinterHostAddress $address -ErrorAction Stop
|
||||
Log "port: $portname"
|
||||
}
|
||||
return $portname
|
||||
}
|
||||
|
||||
function Repair-Queue($queue, [string]$address, [string]$drivername) {
|
||||
$name = $queue.Name
|
||||
|
||||
# The address ShopDB holds is the truth about where the printer IS. A queue
|
||||
# left pointing at the old address prints into the void, and looks fine.
|
||||
if ($address) {
|
||||
$wantedport = 'IP_' + $address
|
||||
if ($queue.PortName -ne $wantedport) {
|
||||
if ($WhatIfOnly) {
|
||||
Log "WOULD repoint $name : $($queue.PortName) -> $wantedport"
|
||||
} else {
|
||||
try {
|
||||
$portname = Ensure-Port $address
|
||||
Set-Printer -Name $name -PortName $portname -ErrorAction Stop
|
||||
Log "repointed $name : $($queue.PortName) -> $portname"
|
||||
} catch {
|
||||
Log "ERROR repointing ${name}: $($_.Exception.Message)"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
# A queue built on a driver the site has moved off keeps using it forever.
|
||||
# Only corrected when the wanted driver is actually staged - swapping a queue
|
||||
# onto a driver that is not installed would break a working printer.
|
||||
if ($drivername -and $queue.DriverName -ne $drivername) {
|
||||
if (-not (Get-PrinterDriver -Name $drivername -ErrorAction SilentlyContinue)) {
|
||||
Log "SKIP driver fix for $name : '$drivername' is not staged"
|
||||
} elseif ($WhatIfOnly) {
|
||||
Log "WOULD re-driver $name : $($queue.DriverName) -> $drivername"
|
||||
} else {
|
||||
try {
|
||||
Set-Printer -Name $name -DriverName $drivername -ErrorAction Stop
|
||||
Log "re-drivered $name : $($queue.DriverName) -> $drivername"
|
||||
} catch {
|
||||
Log "ERROR re-drivering ${name}: $($_.Exception.Message)"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if ($queue.PortName -eq ('IP_' + $address) -and
|
||||
($drivername -eq '' -or $queue.DriverName -eq $drivername)) {
|
||||
Log "present: $name"
|
||||
}
|
||||
}
|
||||
|
||||
$existing = @{}
|
||||
foreach ($queue in (Get-Printer -ErrorAction SilentlyContinue)) {
|
||||
$existing[$queue.Name] = $queue
|
||||
}
|
||||
|
||||
$defaultname = ''
|
||||
foreach ($printer in $wanted) {
|
||||
$name = $printer.queuename
|
||||
if (-not $name) { continue }
|
||||
if ($printer.printerid -eq $defaultid) { $defaultname = $name }
|
||||
|
||||
$address = $printer.hostname
|
||||
if (-not $address) { $address = $printer.ipaddress }
|
||||
$drivername = $printer.drivername
|
||||
|
||||
if ($existing.ContainsKey($name)) {
|
||||
# A queue with the right NAME can still be wrong: pointing at a printer
|
||||
# that has moved, or built on a driver that has since been replaced.
|
||||
# Absence used to be the only thing fixed, so a bay with a stale queue
|
||||
# looked converged and printed to the wrong device.
|
||||
#
|
||||
# Corrected IN PLACE with Set-Printer, never removed and recreated: the
|
||||
# queue keeps its name, its sharing, its permissions, and whoever has it
|
||||
# as their default keeps it.
|
||||
Repair-Queue $existing[$name] $address $drivername
|
||||
continue
|
||||
}
|
||||
|
||||
if (-not $address) {
|
||||
Log "SKIP $name : no hostname or IP to point a port at"
|
||||
continue
|
||||
}
|
||||
|
||||
if (-not $drivername) {
|
||||
Log "SKIP $name : ShopDB has no driver name for it"
|
||||
continue
|
||||
}
|
||||
if (-not (Get-PrinterDriver -Name $drivername -ErrorAction SilentlyContinue)) {
|
||||
# Deliberately not fetched here - see the header.
|
||||
Log "SKIP $name : driver '$drivername' is not staged on this PC"
|
||||
continue
|
||||
}
|
||||
|
||||
if ($WhatIfOnly) {
|
||||
Log "WOULD create: $name -> $address ($drivername)"
|
||||
continue
|
||||
}
|
||||
|
||||
try {
|
||||
$portname = Ensure-Port $address
|
||||
Add-Printer -Name $name -DriverName $drivername -PortName $portname -ErrorAction Stop
|
||||
Log "created: $name -> $address ($drivername)"
|
||||
} catch {
|
||||
Log "ERROR creating ${name}: $($_.Exception.Message)"
|
||||
}
|
||||
}
|
||||
|
||||
# The default is recorded, not applied: this process is SYSTEM and the setting
|
||||
# is per user. The logon task registered above runs
|
||||
# Apply-ShopdbDefaultPrinter.ps1, which reads this value in the user's context.
|
||||
if ($defaultname) {
|
||||
if ($WhatIfOnly) {
|
||||
Log "WOULD record default: $defaultname"
|
||||
} else {
|
||||
try {
|
||||
if (-not (Test-Path $REGPATH)) { New-Item -Path $REGPATH -Force | Out-Null }
|
||||
Set-ItemProperty -Path $REGPATH -Name DefaultPrinter -Value $defaultname
|
||||
Log "default recorded for the logon task: $defaultname"
|
||||
} catch {
|
||||
Log "ERROR recording the default: $($_.Exception.Message)"
|
||||
}
|
||||
}
|
||||
} else {
|
||||
Log 'no default assigned'
|
||||
}
|
||||
|
||||
exit 0
|
||||
35
plugins/printers/client/drivers.example.json
Normal file
35
plugins/printers/client/drivers.example.json
Normal file
@@ -0,0 +1,35 @@
|
||||
{
|
||||
"_comment": "Driver set for a site. Each entry names a driver EXACTLY as its INF declares it (what Add-PrinterDriver matches on) and where its package lives, relative to the package root or as an absolute UNC path. Copy to drivers.json and edit for the site.",
|
||||
"drivers": [
|
||||
{
|
||||
"drivername": "HP Universal Printing PS",
|
||||
"path": "drivers/hp_upd_ps",
|
||||
"covers": "HP office printers (universal)"
|
||||
},
|
||||
{
|
||||
"drivername": "Xerox Global Print Driver PCL6",
|
||||
"path": "drivers/xerox_gpd",
|
||||
"covers": "Xerox office printers (universal)"
|
||||
},
|
||||
{
|
||||
"drivername": "HP DesignJet T1700dr V4",
|
||||
"path": "drivers/hp_designjet",
|
||||
"covers": "DesignJet T1700 / T1700dr plotters"
|
||||
},
|
||||
{
|
||||
"drivername": "ZDesigner ZT411-300dpi ZPL",
|
||||
"path": "drivers/zebra_zt411",
|
||||
"covers": "Zebra ZT411 label printers"
|
||||
},
|
||||
{
|
||||
"drivername": "EPSON TM-C3500",
|
||||
"path": "drivers/epson_tmc3500",
|
||||
"covers": "Epson ColorWorks C3500 label printers"
|
||||
},
|
||||
{
|
||||
"drivername": "DTC4500e Card Printer",
|
||||
"path": "drivers/hid_dtc4500e",
|
||||
"covers": "HID FARGO DTC4500e card printer"
|
||||
}
|
||||
]
|
||||
}
|
||||
43
plugins/printers/migrations/versions/0003_drivername.py
Normal file
43
plugins/printers/migrations/versions/0003_drivername.py
Normal file
@@ -0,0 +1,43 @@
|
||||
"""Add drivername to printerdrivers (exact INF driver name).
|
||||
|
||||
`location` points at the driver package; `name` is what a human calls it.
|
||||
Add-PrinterDriver needs neither - it needs the driver name exactly as the INF
|
||||
declares it ('HP Universal Printing PCL 6'), which nothing in the row carried.
|
||||
Nullable: existing rows have no INF name until someone types it in.
|
||||
|
||||
Guarded/idempotent: skips when the table is absent (plugin disabled) or the
|
||||
column already exists (e.g. a test DB built by db.create_all() from the model).
|
||||
|
||||
Revision ID: printers0003drivername
|
||||
Revises: printers0002supplyalerts
|
||||
"""
|
||||
from alembic import op
|
||||
import sqlalchemy as sa
|
||||
|
||||
|
||||
# revision identifiers, used by Alembic.
|
||||
revision = 'printers0003drivername'
|
||||
down_revision = 'printers0002supplyalerts'
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
|
||||
def upgrade():
|
||||
bind = op.get_bind()
|
||||
inspector = sa.inspect(bind)
|
||||
if 'printerdrivers' not in inspector.get_table_names():
|
||||
return
|
||||
columns = {column['name'] for column in inspector.get_columns('printerdrivers')}
|
||||
if 'drivername' not in columns:
|
||||
op.add_column('printerdrivers',
|
||||
sa.Column('drivername', sa.String(length=255), nullable=True))
|
||||
|
||||
|
||||
def downgrade():
|
||||
bind = op.get_bind()
|
||||
inspector = sa.inspect(bind)
|
||||
if 'printerdrivers' not in inspector.get_table_names():
|
||||
return
|
||||
columns = {column['name'] for column in inspector.get_columns('printerdrivers')}
|
||||
if 'drivername' in columns:
|
||||
op.drop_column('printerdrivers', 'drivername')
|
||||
44
plugins/printers/migrations/versions/0004_drivervendor.py
Normal file
44
plugins/printers/migrations/versions/0004_drivervendor.py
Normal file
@@ -0,0 +1,44 @@
|
||||
"""Give a printer driver a vendor, so one row can serve a whole make.
|
||||
|
||||
HP's and Xerox's universal drivers cover 41 of the reference site's 44 printers
|
||||
between them, but a driver could only be bound to ONE modelnumberid - so covering
|
||||
them meant 21 near-duplicate rows all pointing at the same package, a table
|
||||
nobody would keep true. A driver with no model and a vendor now serves every
|
||||
printer of that make, and a per-model row still wins where one genuinely differs
|
||||
(a plotter, a card printer, a label printer).
|
||||
|
||||
Nullable and guarded: a re-run is a no-op, and existing rows keep working
|
||||
unchanged because model matching is still tried first.
|
||||
|
||||
Revision ID: printers0004drivervendor
|
||||
Revises: printers0003drivername
|
||||
"""
|
||||
from alembic import op
|
||||
import sqlalchemy as sa
|
||||
|
||||
|
||||
revision = 'printers0004drivervendor'
|
||||
down_revision = 'printers0003drivername'
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
|
||||
def upgrade():
|
||||
bind = op.get_bind()
|
||||
inspector = sa.inspect(bind)
|
||||
columns = {column['name'] for column in inspector.get_columns('printerdrivers')}
|
||||
if 'vendorid' not in columns:
|
||||
op.add_column('printerdrivers', sa.Column('vendorid', sa.Integer(), nullable=True))
|
||||
# No FK constraint: printerdrivers is a plugin table and vendors is core.
|
||||
# ADR-008 keeps plugin chains from writing constraints across that line,
|
||||
# and the resolver treats a vendor that no longer exists as no match.
|
||||
op.create_index('idx_printerdriver_vendor', 'printerdrivers', ['vendorid'])
|
||||
|
||||
|
||||
def downgrade():
|
||||
bind = op.get_bind()
|
||||
inspector = sa.inspect(bind)
|
||||
columns = {column['name'] for column in inspector.get_columns('printerdrivers')}
|
||||
if 'vendorid' in columns:
|
||||
op.drop_index('idx_printerdriver_vendor', table_name='printerdrivers')
|
||||
op.drop_column('printerdrivers', 'vendorid')
|
||||
85
plugins/printers/migrations/versions/0005_observedqueues.py
Normal file
85
plugins/printers/migrations/versions/0005_observedqueues.py
Normal file
@@ -0,0 +1,85 @@
|
||||
"""printers: printerobservedqueues table (what a bay reported it HAS).
|
||||
|
||||
ShopDB already knows what a bay SHOULD have (usesprinter/defaultprinter rows on
|
||||
the machine). This table holds the other half: the queues a PC reported through
|
||||
POST /api/collector/printers. Observed and assigned stay in separate tables on
|
||||
purpose, so observed drift can never be mistaken for desired state.
|
||||
|
||||
One row per observed queue; the latest report for a host replaces all of that
|
||||
host's rows. The unique index on (hostname, queuename) is the guard that turns a
|
||||
half-finished replace into an IntegrityError instead of duplicate queues.
|
||||
|
||||
Explicit ops rather than create_plugin_tables: the helper builds a per-plugin
|
||||
MetaData filtered to the plugin's own tables, so the foreign key to the core
|
||||
assets table cannot resolve at CreateTable-compile time. Same reason the backups
|
||||
baseline spells its ops out.
|
||||
|
||||
Guarded both ways, so a re-run (or a database where db.create_all already built
|
||||
the table) is a no-op.
|
||||
|
||||
Revision ID: printers0005observedqueues
|
||||
Revises: printers0004drivervendor
|
||||
"""
|
||||
from alembic import op
|
||||
import sqlalchemy as sa
|
||||
|
||||
|
||||
# revision identifiers, used by Alembic.
|
||||
revision = 'printers0005observedqueues'
|
||||
down_revision = 'printers0004drivervendor'
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
|
||||
def upgrade():
|
||||
bind = op.get_bind()
|
||||
inspector = sa.inspect(bind)
|
||||
if 'printerobservedqueues' in inspector.get_table_names():
|
||||
return
|
||||
op.create_table(
|
||||
'printerobservedqueues',
|
||||
sa.Column('printerobservedqueueid', sa.Integer(), nullable=False),
|
||||
# Nullable and no index of its own beyond the explicit one below: an
|
||||
# unenrolled bay still gets to report, and hostname is what identifies
|
||||
# the report.
|
||||
sa.Column('assetid', sa.Integer(), nullable=True),
|
||||
sa.Column('hostname', sa.String(length=255), nullable=False),
|
||||
sa.Column('queuename', sa.String(length=255), nullable=False),
|
||||
sa.Column('drivername', sa.String(length=255), nullable=True),
|
||||
sa.Column('portname', sa.String(length=255), nullable=True),
|
||||
sa.Column('portaddress', sa.String(length=255), nullable=True),
|
||||
sa.Column('isdefault', sa.Boolean(), nullable=False,
|
||||
server_default=sa.false()),
|
||||
sa.Column('isshared', sa.Boolean(), nullable=False,
|
||||
server_default=sa.false()),
|
||||
sa.Column('observedat', sa.DateTime(), nullable=False),
|
||||
sa.Column('createddate', sa.DateTime(), nullable=False),
|
||||
sa.Column('modifieddate', sa.DateTime(), nullable=False),
|
||||
sa.Column('isactive', sa.Boolean(), nullable=False,
|
||||
server_default=sa.true()),
|
||||
sa.ForeignKeyConstraint(['assetid'], ['assets.assetid'],
|
||||
ondelete='CASCADE'),
|
||||
sa.PrimaryKeyConstraint('printerobservedqueueid'),
|
||||
# Doubles as the read index for the hostname filter (leftmost column),
|
||||
# so no separate hostname index is created.
|
||||
sa.UniqueConstraint('hostname', 'queuename',
|
||||
name='uq_printerobservedqueue_host_queue'),
|
||||
)
|
||||
# Port address is the primary match key from an observed queue back to a
|
||||
# printer asset, so every comparison read hits it.
|
||||
op.create_index('idx_printerobservedqueues_portaddress',
|
||||
'printerobservedqueues', ['portaddress'])
|
||||
op.create_index('idx_printerobservedqueues_assetid',
|
||||
'printerobservedqueues', ['assetid'])
|
||||
|
||||
|
||||
def downgrade():
|
||||
bind = op.get_bind()
|
||||
inspector = sa.inspect(bind)
|
||||
if 'printerobservedqueues' not in inspector.get_table_names():
|
||||
return
|
||||
op.drop_index('idx_printerobservedqueues_assetid',
|
||||
table_name='printerobservedqueues')
|
||||
op.drop_index('idx_printerobservedqueues_portaddress',
|
||||
table_name='printerobservedqueues')
|
||||
op.drop_table('printerobservedqueues')
|
||||
@@ -9,6 +9,7 @@ from .model_supply import ( # data-driven model -> toner/drum/waste mapping
|
||||
CAPACITY_TIERS,
|
||||
)
|
||||
from .supply_alert import PrinterSupplyAlert # per-printer toner alert state
|
||||
from .printer_observation import PrinterObservedQueue # observed queues per bay
|
||||
|
||||
__all__ = [
|
||||
'Printer',
|
||||
@@ -16,6 +17,7 @@ __all__ = [
|
||||
'PrinterDriver',
|
||||
'ModelSupply',
|
||||
'PrinterSupplyAlert',
|
||||
'PrinterObservedQueue',
|
||||
'SUPPLY_TYPES',
|
||||
'SUPPLY_COLORS',
|
||||
'CAPACITY_TIERS',
|
||||
|
||||
@@ -11,6 +11,15 @@ class PrinterDriver(db.Model):
|
||||
# SMB path (\\\\server\\share\\...) or HTTP URL to the driver package
|
||||
location = db.Column(db.String(500), nullable=False)
|
||||
description = db.Column(db.Text)
|
||||
# Exact driver name as the INF declares it: Add-PrinterDriver matches on
|
||||
# this string, not on `name`, which is ours to choose
|
||||
drivername = db.Column(db.String(255))
|
||||
# Optional: attach a driver to a whole VENDOR rather than one model. A
|
||||
# universal driver (HP UPD, Xerox GPD) serves every printer of that make, and
|
||||
# binding it to one model would mean a near-duplicate row per model.
|
||||
# Model wins over vendor when both match - see _printer_driver.
|
||||
vendorid = db.Column(db.Integer, nullable=True, index=True)
|
||||
|
||||
# Optional: attach a driver to a specific printer model
|
||||
modelnumberid = db.Column(
|
||||
db.Integer,
|
||||
@@ -27,6 +36,8 @@ class PrinterDriver(db.Model):
|
||||
'name': self.name,
|
||||
'location': self.location,
|
||||
'description': self.description,
|
||||
'drivername': self.drivername,
|
||||
'vendorid': self.vendorid,
|
||||
'modelnumberid': self.modelnumberid,
|
||||
'modelname': self.model.modelnumber if self.model else None,
|
||||
'isactive': bool(self.isactive),
|
||||
|
||||
109
plugins/printers/models/printer_observation.py
Normal file
109
plugins/printers/models/printer_observation.py
Normal file
@@ -0,0 +1,109 @@
|
||||
"""What a bay actually HAS: one row per printer queue a PC reported.
|
||||
|
||||
This is the observed half of the printer loop. The assigned half already exists
|
||||
as usesprinter/defaultprinter relationship rows on the machine, and the two are
|
||||
kept apart on purpose: the moment a drifted bay's observed state is allowed to
|
||||
write assignment rows, enforcement stops meaning anything. Nothing in this table
|
||||
is desired state, and no code may promote it to desired state without a person
|
||||
asking for that explicitly.
|
||||
|
||||
Current state, not history. The latest report for a host REPLACES every row that
|
||||
host had before, so "what does this bay have" is a plain filter and never a
|
||||
question about time. An append-only table would grow with every GE-Enforce cycle
|
||||
and answer that question wrong. The audit log already records each ingest, which
|
||||
is where the history lives.
|
||||
|
||||
Rows are keyed by hostname as reported, with assetid as a resolved convenience:
|
||||
a bay can report before anyone creates its computer record, and the report must
|
||||
still land. Matching an observed queue back to a ShopDB printer asset happens at
|
||||
READ time (port address first, then queue name) so a printer added tomorrow
|
||||
matches without the bay re-reporting.
|
||||
|
||||
Replacement is a hard DELETE of the host's rows, not a soft one: the inherited
|
||||
isactive flag is not a soft-delete marker here, because a queue that is gone
|
||||
from the bay is not observed state that has been retired, it is state that was
|
||||
never observed again.
|
||||
"""
|
||||
|
||||
from shopdb.api import db, BaseModel
|
||||
|
||||
|
||||
class PrinterObservedQueue(BaseModel):
|
||||
"""One Windows print queue seen on one reporting PC at one point in time."""
|
||||
|
||||
__tablename__ = 'printerobservedqueues'
|
||||
|
||||
printerobservedqueueid = db.Column(db.Integer, primary_key=True)
|
||||
|
||||
# The reporting PC, resolved at ingest. Nullable because an unenrolled bay
|
||||
# still gets to report, and no backref: core assets must not grow a
|
||||
# dependency on this plugin.
|
||||
assetid = db.Column(
|
||||
db.Integer,
|
||||
db.ForeignKey('assets.assetid', ondelete='CASCADE'),
|
||||
nullable=True,
|
||||
comment='Reporting PC asset, resolved from hostname at ingest',
|
||||
)
|
||||
asset = db.relationship('Asset', lazy='select', viewonly=True)
|
||||
|
||||
# Authoritative identity of the report, stored as sent. assetid can be null
|
||||
# or can go stale after a rename; hostname is what the replace keys on.
|
||||
hostname = db.Column(
|
||||
db.String(255),
|
||||
nullable=False,
|
||||
comment='Reporting PC hostname, as sent by the collector',
|
||||
)
|
||||
|
||||
queuename = db.Column(
|
||||
db.String(255),
|
||||
nullable=False,
|
||||
comment='Windows printer (queue) name',
|
||||
)
|
||||
drivername = db.Column(
|
||||
db.String(255),
|
||||
comment='Windows driver name, verbatim; comparable to printerdrivers.drivername',
|
||||
)
|
||||
portname = db.Column(
|
||||
db.String(255),
|
||||
comment='Windows port name, freeform',
|
||||
)
|
||||
# Primary match key: an IP or FQDN identifies a device unambiguously, where
|
||||
# a queue name is only ever a convention. Null for non-TCP/IP ports.
|
||||
portaddress = db.Column(
|
||||
db.String(255),
|
||||
comment='Host address the port points at (IP or FQDN)',
|
||||
)
|
||||
|
||||
isdefault = db.Column(
|
||||
db.Boolean,
|
||||
nullable=False,
|
||||
default=False,
|
||||
comment='Was the default queue for the reporting context',
|
||||
)
|
||||
isshared = db.Column(
|
||||
db.Boolean,
|
||||
nullable=False,
|
||||
default=False,
|
||||
comment='Queue is shared off this PC',
|
||||
)
|
||||
|
||||
# Server-stamped once per report, so every row of one report carries the
|
||||
# same value and "when did this bay last report" needs no aggregate.
|
||||
observedat = db.Column(
|
||||
db.DateTime,
|
||||
nullable=False,
|
||||
comment='When the report that produced this row was ingested',
|
||||
)
|
||||
|
||||
__table_args__ = (
|
||||
# Windows queue names are unique per host, so this doubles as the read
|
||||
# index for the hostname filter and turns a botched partial replace into
|
||||
# an IntegrityError instead of silent duplicate queues.
|
||||
db.UniqueConstraint('hostname', 'queuename',
|
||||
name='uq_printerobservedqueue_host_queue'),
|
||||
db.Index('idx_printerobservedqueues_portaddress', 'portaddress'),
|
||||
db.Index('idx_printerobservedqueues_assetid', 'assetid'),
|
||||
)
|
||||
|
||||
def __repr__(self):
|
||||
return f"<PrinterObservedQueue {self.hostname}:{self.queuename}>"
|
||||
@@ -3,6 +3,8 @@
|
||||
import json
|
||||
import logging
|
||||
from pathlib import Path
|
||||
import re
|
||||
|
||||
from typing import List, Dict, Optional, Type
|
||||
|
||||
from flask import Flask, Blueprint
|
||||
@@ -12,13 +14,49 @@ from shopdb.plugins.base import BasePlugin, PluginMeta
|
||||
from shopdb.api import db, AssetType
|
||||
|
||||
from .models import (
|
||||
Printer, PrinterType, ModelSupply, PrinterDriver, PrinterSupplyAlert
|
||||
Printer, PrinterType, ModelSupply, PrinterDriver, PrinterSupplyAlert,
|
||||
PrinterObservedQueue
|
||||
)
|
||||
from .api import printers_asset_bp
|
||||
from .services import ZabbixService
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
# Widths of the text columns on printerobservedqueues. A Windows queue name
|
||||
# tops out well below this, but a report is unattended machine input: one
|
||||
# oversized string must not turn into a 500 the bay retries every cycle.
|
||||
OBSERVEDTEXTLIMIT = 255
|
||||
|
||||
|
||||
def _observed_text(value, fieldname, warnings):
|
||||
"""Trim one reported string to what the column holds, or None if blank."""
|
||||
if value is None:
|
||||
return None
|
||||
text = str(value).strip()
|
||||
if not text:
|
||||
return None
|
||||
if len(text) > OBSERVEDTEXTLIMIT:
|
||||
warnings.append('truncated {} longer than {} characters'.format(
|
||||
fieldname, OBSERVEDTEXTLIMIT))
|
||||
text = text[:OBSERVEDTEXTLIMIT]
|
||||
return text
|
||||
|
||||
|
||||
def _observed_bool(value):
|
||||
"""Coerce a reported flag to bool.
|
||||
|
||||
PowerShell's ConvertTo-Json emits real booleans, but hand-built payloads
|
||||
and older clients send 'True'/'true'/1, and a bare truthiness test would
|
||||
read the string 'False' as a default printer.
|
||||
"""
|
||||
if isinstance(value, bool):
|
||||
return value
|
||||
if isinstance(value, (int, float)):
|
||||
return bool(value)
|
||||
if isinstance(value, str):
|
||||
return value.strip().lower() in ('true', '1', 'yes')
|
||||
return False
|
||||
|
||||
|
||||
class PrintersPlugin(BasePlugin):
|
||||
"""
|
||||
@@ -79,6 +117,7 @@ class PrintersPlugin(BasePlugin):
|
||||
PrinterDriver, # driver links (SMB/HTTP)
|
||||
ModelSupply, # model -> toner/drum/waste part numbers
|
||||
PrinterSupplyAlert, # per-printer toner alert crossing state
|
||||
PrinterObservedQueue, # what a bay reports it ACTUALLY has
|
||||
]
|
||||
|
||||
def get_services(self) -> Dict[str, Type]:
|
||||
@@ -109,11 +148,16 @@ class PrintersPlugin(BasePlugin):
|
||||
logger.info("Printers plugin installed")
|
||||
|
||||
def get_settings_defaults(self) -> List[dict]:
|
||||
"""Low-toner alert settings.
|
||||
"""Low-toner alert settings plus the dashboard threshold.
|
||||
|
||||
The framework seeds these at install, at enable, and on every
|
||||
`flask plugin upgrade-all`, so a key added in a later version reaches a
|
||||
site that installed an earlier one.
|
||||
|
||||
ONE definition only. There were two, and the later one shadowed this
|
||||
list outright: every alert setting below was silently never declared,
|
||||
so the alerts settings page wrote keys the plugin did not own and a new
|
||||
site seeded none of them. Add keys here; do not add a second method.
|
||||
"""
|
||||
return [
|
||||
{
|
||||
@@ -164,6 +208,16 @@ class PrintersPlugin(BasePlugin):
|
||||
'description': 'Toner percent remaining at or below which a '
|
||||
'critical email fires',
|
||||
},
|
||||
{
|
||||
'key': 'printers_dashboardpercent',
|
||||
'value': '5',
|
||||
'valuetype': 'integer',
|
||||
'category': 'printers',
|
||||
'description': 'Supply percentage at or below which a printer '
|
||||
'appears on the dashboard. Tighter than the '
|
||||
'low-supplies report, which is for planning an '
|
||||
'order rather than walking out to change one.',
|
||||
},
|
||||
]
|
||||
|
||||
def _ensure_asset_type(self) -> None:
|
||||
@@ -286,21 +340,6 @@ class PrintersPlugin(BasePlugin):
|
||||
|
||||
return [printerscli]
|
||||
|
||||
def get_settings_defaults(self) -> List[Dict]:
|
||||
"""Settings this plugin owns for the dashboard card."""
|
||||
return [
|
||||
{
|
||||
'key': 'printers_dashboardpercent',
|
||||
'value': '5',
|
||||
'valuetype': 'integer',
|
||||
'category': 'printers',
|
||||
'description': 'Supply percentage at or below which a printer '
|
||||
'appears on the dashboard. Tighter than the '
|
||||
'low-supplies report, which is for planning an '
|
||||
'order rather than walking out to change one.',
|
||||
},
|
||||
]
|
||||
|
||||
def get_dashboard_widgets(self) -> List[Dict]:
|
||||
"""Dashboard card: printers needing a cartridge.
|
||||
|
||||
@@ -379,3 +418,258 @@ class PrintersPlugin(BasePlugin):
|
||||
('printers.edit', 'Edit printers', 'printers'),
|
||||
('printers.delete', 'Delete printers', 'printers'),
|
||||
]
|
||||
|
||||
# ---- ADR-006 collector contract -------------------------------------
|
||||
|
||||
def get_collector_schema(self) -> Optional[dict]:
|
||||
"""What a bay reports it ACTUALLY has (POST /api/collector/printers).
|
||||
|
||||
The observed half of the printer story. ShopDB already knows what a
|
||||
host SHOULD have (/api/printers/for-host); this is what enumerating the
|
||||
host found, kept apart from the assignment so drift stays visible.
|
||||
|
||||
Declaring this schema is what registers the endpoint - the dispatcher
|
||||
in shopdb/core/api/collector.py discovers it, and brings the collector
|
||||
key / managed-token auth and the audit row with it.
|
||||
"""
|
||||
return {
|
||||
'identityfield': 'hostname',
|
||||
'fields': {
|
||||
'type': 'object',
|
||||
'required': ['hostname', 'queues'],
|
||||
'properties': {
|
||||
'hostname': {
|
||||
'type': 'string',
|
||||
'description': 'Reporting PC (COMPUTERNAME or its '
|
||||
'FQDN). The identity of the report: '
|
||||
'the PC asset is resolved from it, but '
|
||||
'the rows are keyed by the name, so an '
|
||||
'unenrolled bay still reports.',
|
||||
},
|
||||
'queues': {
|
||||
'type': 'array',
|
||||
'description': "Every real print queue on the host. "
|
||||
"This REPLACES the host's previous set, "
|
||||
"so an empty array is a valid report "
|
||||
"that clears it. A client whose "
|
||||
"enumeration FAILED must send nothing "
|
||||
"at all - never an empty array.",
|
||||
'items': {
|
||||
'type': 'object',
|
||||
'required': ['queuename'],
|
||||
'properties': {
|
||||
'queuename': {
|
||||
'type': 'string',
|
||||
'description': 'Windows printer name.',
|
||||
},
|
||||
'drivername': {
|
||||
'type': 'string',
|
||||
'description': 'Driver name verbatim, as '
|
||||
'the INF spells it.',
|
||||
},
|
||||
'portname': {
|
||||
'type': 'string',
|
||||
'description': 'Windows port name.',
|
||||
},
|
||||
'portaddress': {
|
||||
'type': 'string',
|
||||
'description': 'PrinterHostAddress of a '
|
||||
'TCP/IP port - an IP or '
|
||||
'FQDN. The primary key for '
|
||||
'matching this queue to a '
|
||||
'printer asset; omit it for '
|
||||
'a non-TCP port.',
|
||||
},
|
||||
'isdefault': {
|
||||
'type': 'boolean',
|
||||
'description': 'True on the one queue that '
|
||||
'is the default printer.',
|
||||
},
|
||||
'isshared': {
|
||||
'type': 'boolean',
|
||||
'description': 'True when the queue is '
|
||||
'shared off this PC.',
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
'observedat': {
|
||||
'type': 'string',
|
||||
'format': 'date-time',
|
||||
'description': 'Accepted and ignored. The server stamps '
|
||||
'observedat at ingest, so a bay with a '
|
||||
'wrong clock cannot report itself fresh '
|
||||
'or stale.',
|
||||
},
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
def apply_collector_payload(self, payload: dict) -> dict:
|
||||
"""Replace one host's observed queue set (ADR-006).
|
||||
|
||||
THIS NEVER WRITES AN ASSIGNMENT. Observed and assigned are separate
|
||||
tables on purpose: the moment a drifted bay's report is allowed to
|
||||
become what that bay is told to install, enforcement stops meaning
|
||||
anything.
|
||||
Seeding an assignment from observed state is a human action through
|
||||
PUT /api/printers/assignments/for-asset/<id>.
|
||||
|
||||
Replace, not append: this is current state, so the latest report is the
|
||||
whole truth for that host. Nothing is matched to a printer asset here
|
||||
either - resolution happens at read time, so a printer added to ShopDB
|
||||
tomorrow matches yesterday's report without the bay reporting again.
|
||||
"""
|
||||
from datetime import datetime, timezone
|
||||
|
||||
warnings = []
|
||||
hostname = (payload.get('hostname') or '').strip()
|
||||
if not hostname:
|
||||
raise ValueError('hostname is required')
|
||||
|
||||
queues = payload.get('queues')
|
||||
if queues is None:
|
||||
# Absent and empty are NOT the same thing. [] is a host that
|
||||
# genuinely has no queues and clears its rows; a missing key is a
|
||||
# malformed report, and treating it as a wipe would let one client
|
||||
# bug erase the observed state of the fleet host by host.
|
||||
raise ValueError('queues is required; send an empty array for a '
|
||||
'host with no queues')
|
||||
if not isinstance(queues, list):
|
||||
raise ValueError('queues must be an array')
|
||||
|
||||
# One stamp for the whole report, so "when did this bay last report"
|
||||
# reads off any row of it rather than a MAX over the set.
|
||||
observedat = datetime.now(timezone.utc).replace(tzinfo=None)
|
||||
|
||||
# Resolved BEFORE the rows are written: assetid is a convenience for
|
||||
# the read paths, and hostname stays the identity that the replace
|
||||
# keys on, so an unresolved host still records everything it reported.
|
||||
assetid = self._observed_assetid(hostname, warnings)
|
||||
|
||||
# Case-folded on both sides: one script sends COMPUTERNAME uppercase
|
||||
# and another the lowercase FQDN, and MySQL forgives that while SQLite
|
||||
# does not. Uncompared, the replace would leave the other spelling's
|
||||
# rows in place and the host would appear to have every queue twice.
|
||||
#
|
||||
# A bulk delete so the DELETE reaches the database BEFORE the inserts
|
||||
# below: a re-report repeats the same queue names, and the
|
||||
# (hostname, queuename) unique index rejects the new rows if the old
|
||||
# ones are still there. synchronize_session='fetch' costs one select
|
||||
# and keeps the session's identity map honest, so a caller that read
|
||||
# these rows earlier in the same request does not keep deleted ones.
|
||||
# Every spelling of this host, not just the one it sent. The READ path
|
||||
# treats a short name and its FQDN as the same machine, so a delete that
|
||||
# matched only the exact string would leave the other spelling's rows
|
||||
# behind and the host would appear to have every queue twice - the bug
|
||||
# this replace exists to prevent. A PC that enrolls short and later
|
||||
# reports fully qualified is normal, not exotic.
|
||||
shortname = hostname.lower().split('.')[0]
|
||||
predicate = db.or_(
|
||||
db.func.lower(PrinterObservedQueue.hostname) == hostname.lower(),
|
||||
db.func.lower(PrinterObservedQueue.hostname) == shortname)
|
||||
if re.match(r'^[a-z0-9-]+$', shortname):
|
||||
# Prefix match only for a plain name, as the read path does: a
|
||||
# wildcard built from arbitrary input would delete another PC's rows.
|
||||
predicate = db.or_(
|
||||
predicate,
|
||||
db.func.lower(PrinterObservedQueue.hostname).like(shortname + '.%'))
|
||||
|
||||
db.session.query(PrinterObservedQueue).filter(predicate).delete(
|
||||
synchronize_session='fetch')
|
||||
|
||||
seennames = set()
|
||||
defaultqueue = None
|
||||
stored = 0
|
||||
for entry in queues:
|
||||
if not isinstance(entry, dict):
|
||||
warnings.append('ignored a queue entry that was not an object')
|
||||
continue
|
||||
|
||||
queuename = _observed_text(entry.get('queuename'), 'queuename',
|
||||
warnings)
|
||||
if not queuename:
|
||||
warnings.append('ignored a queue with no queuename')
|
||||
continue
|
||||
if queuename.lower() in seennames:
|
||||
# Windows cannot hold two queues of one name on a host, so this
|
||||
# is a doubled line in the report. Dropping it keeps the
|
||||
# (hostname, queuename) unique index from failing the whole
|
||||
# report over one bad row.
|
||||
warnings.append(
|
||||
'ignored duplicate queue {!r}'.format(queuename))
|
||||
continue
|
||||
seennames.add(queuename.lower())
|
||||
|
||||
isdefault = _observed_bool(entry.get('isdefault'))
|
||||
if isdefault and defaultqueue is not None:
|
||||
# A host has exactly one default printer. Two means the client
|
||||
# misread it, and keeping both would leave the seed candidate
|
||||
# picking one at random.
|
||||
warnings.append(
|
||||
'more than one queue reported as default; kept {!r}'.format(
|
||||
defaultqueue))
|
||||
isdefault = False
|
||||
if isdefault:
|
||||
defaultqueue = queuename
|
||||
|
||||
db.session.add(PrinterObservedQueue(
|
||||
hostname=hostname,
|
||||
queuename=queuename,
|
||||
drivername=_observed_text(entry.get('drivername'), 'drivername',
|
||||
warnings),
|
||||
portname=_observed_text(entry.get('portname'), 'portname',
|
||||
warnings),
|
||||
portaddress=_observed_text(entry.get('portaddress'),
|
||||
'portaddress', warnings),
|
||||
isdefault=isdefault,
|
||||
isshared=_observed_bool(entry.get('isshared')),
|
||||
assetid=assetid,
|
||||
observedat=observedat,
|
||||
))
|
||||
stored += 1
|
||||
|
||||
# flush, not commit: the collector dispatcher owns the transaction and
|
||||
# commits after writing its AuditLog row. Committing here would leave
|
||||
# an unaudited report behind if that write then failed.
|
||||
db.session.flush()
|
||||
|
||||
# Always 'updated'. This endpoint replaces observed rows and creates no
|
||||
# asset, so 'created' never applies, and calling an identical re-report
|
||||
# 'noop' would hide that the bay is still checking in.
|
||||
return {
|
||||
'action': 'updated',
|
||||
'assetid': assetid,
|
||||
'warnings': warnings,
|
||||
'extra': {'queuecount': stored},
|
||||
}
|
||||
|
||||
def _observed_assetid(self, hostname, warnings):
|
||||
"""Computer asset this hostname belongs to, or None with a warning.
|
||||
|
||||
Reuses the resolver behind /api/printers/for-host rather than repeating
|
||||
it: if the two ever disagreed, a bay would be compared against the
|
||||
assignment of a different PC than the one it was told to install from.
|
||||
|
||||
An unknown hostname is a WARNING, not an error. A bay reporting before
|
||||
its PC record exists is normal on a new build, the rows are keyed by
|
||||
hostname and resolve the moment that record appears, and a 500 here
|
||||
would make the client retry and log a failure on every cycle forever.
|
||||
"""
|
||||
try:
|
||||
from .api.asset_routes import _computer_by_hostname
|
||||
row = _computer_by_hostname(hostname)
|
||||
except ImportError:
|
||||
# A lean site can run without the computers plugin (ADR-013). The
|
||||
# observed rows are still worth keeping - they just stay unresolved.
|
||||
warnings.append('computers plugin not installed; observed queues '
|
||||
'stored against the hostname only')
|
||||
return None
|
||||
|
||||
if row is None:
|
||||
warnings.append(
|
||||
'hostname {!r} does not match a known PC; observed queues '
|
||||
'stored unresolved'.format(hostname))
|
||||
return None
|
||||
# _computer_by_hostname returns the (Computer, Asset) pair.
|
||||
return row[1].assetid
|
||||
|
||||
Reference in New Issue
Block a user