Repository navigation
Expand file tree
/
Copy pathdeploy_emcomm_node_gui.py
More file actions
executable file
·5631 lines (4905 loc) · 264 KB
/
Copy pathdeploy_emcomm_node_gui.py
File metadata and controls
executable file
·5631 lines (4905 loc) · 264 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
#
# EMCOMM Field Node provisioner
# Copyright (C) 2026 WSNQ705
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <https://www.gnu.org/licenses/>.
#
"""
EMCOMM Field Node — Automated Provisioner (GUI)
Builds a standardized, offline-capable emergency-communications
workstation on a Linux laptop: positioning and time sync, HF/VHF digital
modes, offline mapping, an offline reference library, and packet/mesh
tooling. Intended for ARES/RACES/CERT-style volunteer groups, EOC
support positions, and field deployments where internet and cellular
service cannot be assumed.
Every stage is an independently checkable step on the options screen,
all unchecked by default, so a run can install just what a given node
needs. "Select All" performs a full build.
REQUIREMENTS
sudo apt install python3-tk python3-requests
python3-tk is not bundled with Python on Debian/Ubuntu/Mint and the GUI
will not start without it. python3-requests is optional (downloads fall
back to curl).
RUNNING
Run from the directory containing this script, as your normal user —
NOT with sudo. It refuses to start as root. You are asked for your sudo
password once, in the window; it drives a temporary mode-0700 "askpass"
helper for the duration of the run and is deleted when the run ends. It
is never written anywhere else and never leaves the machine.
python3 deploy_emcomm_node_gui.py
WHAT THIS SCRIPT EXPECTS ALONGSIDE IT
Configuration profiles and reference material are NOT bundled — each
group supplies its own. Every step degrades gracefully with a visible
warning when a file is absent, so a partial set is fine:
configs/JS8Call.ini JS8Call profile (see placeholders below)
configs/QMapShack.conf QMapShack profile (see placeholders below)
configs/analog_channels.csv CHIRP channel list for analog radios
configs/ale_channels.zcp ion2G HF ALE channel plan
configs/satdump_tles.txt Curated TLE set for SatDump
scripts/fetch_map_tiles.py Offline map tile fetcher for your area
docs/*.pdf Reference library, served over loopback
scripts/Packages/ Locally cached .deb packages
PROFILE PLACEHOLDERS
Shipped profiles must not carry a real callsign or an absolute home
path — a profile captured from a working install will carry both, and
every node built from it then transmits under someone else's identity.
Use these tokens instead; they are substituted at provisioning time:
MYCALL_PLACEHOLDER -> the callsign entered at the prompt
HOME_PLACEHOLDER -> the provisioning user's $HOME
LICENSING
Transmitting with JS8Call, ion2G HF ALE, Direwolf/APRS or on amateur
DMR requires a valid amateur radio license. Receive-only use does not.
GMRS requires a GMRS license; FRS, MURS and Meshtastic (915 MHz ISM) do
not. The callsign entered at provisioning is written into the JS8Call
profile — set a real, licensed callsign before transmitting.
KNOWN LIMITATIONS
- Cancel takes effect BETWEEN steps, not mid-command. An apt-get or a
SatDump build already running finishes (or fails) first.
- Steps are not dependency-checked. Running "QLog / ion2G HF ALE"
without "System packages" assumes wine and unzip are already
installed. This is deliberate, so a single step can be re-run.
- Long steps show only a spinner; their output is captured and shown
in full only if the step fails.
"""
from __future__ import annotations
import datetime
import getpass
import hashlib
import importlib.util
import json
import math
import os
import platform
import queue
import re
import shutil
import signal
import stat
import struct
import subprocess
import sys
import tempfile
import threading
from contextlib import contextmanager
from dataclasses import dataclass, field
from pathlib import Path
from typing import Callable, Optional
# Tk is not bundled with Python on Debian, Ubuntu or Mint, and without it this
# script cannot start at all. Unguarded, that arrives as a ModuleNotFoundError
# traceback: accurate, and useless to the operator it is aimed at. README.md and
# TESTING.md both say to install it beforehand -- this says so at the one moment
# the person who skipped that is actually looking.
try:
import tkinter as tk
from tkinter import messagebox, scrolledtext, ttk
except ImportError:
sys.exit(
"\nThis provisioner needs Tk, which Debian, Ubuntu and Mint do not bundle\n"
"with Python. Install it and run this again:\n"
"\n"
" sudo apt install python3-tk\n"
)
# ===========================================================================
# Naming
#
# Every path, unit and file name in this provisioner derives from the
# constants below, so a group deploying under its own name edits this block
# and nothing else.
#
# Four namespaces, four conventions, each matching whatever reads it:
#
# OPERATOR_PREFIX $HOME directories an operator browses, possibly under
# stress. CamelCase with an underscore, which sorts them
# above Desktop/Documents in a file manager — deliberate:
# field data belongs at the top of the home folder, not
# buried under ~/.local/share.
# STATE_DIR_NAME hidden per-user state the operator never opens.
# SYSTEM_DIR system configuration. FHS-conventional lowercase.
# UNIT_PREFIX systemd units, udev-invoked scripts, the sudoers
# drop-in — anything read by system tooling. Lowercase
# with hyphens, which is systemd's own convention and the
# usual shape for an executable in /usr/local/bin.
# ===========================================================================
#: Release this file belongs to, without the leading "v".
#:
#: Hand-maintained, and deliberately not derived from `git describe`: the
#: released artifact is a tarball with no .git alongside it, so anything
#: asking git would report "unknown" on precisely the copy an operator runs.
#: Bump it in the commit that precedes the tag, so a clone of main never
#: claims to be a release it is ahead of.
VERSION = "1.0.5"
PROJECT = "emcomm"
OPERATOR_PREFIX = "EMCOMM"
STATE_DIR_NAME = "." + PROJECT
LOG_DIR_NAME = STATE_DIR_NAME + "/logs"
SYSTEM_DIR = "/etc/" + PROJECT
UNIT_PREFIX = PROJECT
DATA_DIR_NAME = OPERATOR_PREFIX + "_Data"
APPS_DIR_NAME = OPERATOR_PREFIX + "_Apps"
NODE_CONF = SYSTEM_DIR + "/node.conf"
SUDOERS_FILE = "/etc/sudoers.d/" + UNIT_PREFIX + "-automation"
AUTOSTART_UNIT = UNIT_PREFIX + "-autostart.service"
#: Mesh -> GPX bridge. 120s is a compromise: each poll opens the serial port
#: for a few seconds, so a faster cadence leaves the radio busy a larger
#: fraction of the time, and mesh positions do not change fast enough to
#: justify it.
MESH_GPX_UNIT_NAME = UNIT_PREFIX + "-mesh-gpx.service"
MESH_GPX_INTERVAL = 120
DOCS_SERVER_UNIT = UNIT_PREFIX + "-docs-server.service"
AUTOSTART_SCRIPT = UNIT_PREFIX + "-autostart-sequence.sh"
DOCK_EVENT_SH = "/usr/local/bin/" + UNIT_PREFIX + "-dock-event.sh"
# Offline map layers: (fetcher --layer value, QMapShack .tms filename, title).
#
# The fetcher writes tiles to Offline_Tiles/<layer>/, and the .tms files below
# are generated from the same tuple, so the two can no longer disagree. They
# did: the .tms files pointed at Offline_Tiles/Topo/ and .../Satellite/ while
# the fetcher wrote .../topo/ and .../imagery/, so QMapShack found nothing
# even when tiles were present.
TILE_FETCHER = Path("scripts/fetch_map_tiles.py")
AREA_DIR = Path("configs/areas")
def load_tile_fetcher():
"""Import the tile fetcher so the estimate shown to the operator and the
tiering below use the SAME maths the download itself uses. A second
implementation of the tile arithmetic would drift from the first, and the
operator would be shown a number that is not what happens.
Returns None if the script is missing or unloadable; callers degrade rather
than crash.
"""
try:
spec = importlib.util.spec_from_file_location("fetch_map_tiles", TILE_FETCHER)
mod = importlib.util.module_from_spec(spec)
spec.loader.exec_module(mod)
return mod
except Exception: # noqa: BLE001 — a broken fetcher must not stop the GUI
return None
SAMPLE_AREA = AREA_DIR / "example-area.json.sample"
def _bounds(spec: dict):
"""(north, south, east, west) as floats, or None if the spec lacks them."""
try:
return tuple(round(float(spec[k]), 6) for k in ("north", "south", "east", "west"))
except (KeyError, TypeError, ValueError):
return None
def is_unmodified_sample(spec: dict) -> bool:
"""True if `spec` has the shipped sample's exact bounds.
The sample ships as .json.sample so it is never read as a live area, but a
clone that predates that rename leaves a real example-area.json on disk.
configs/areas/*.json is gitignored, so git never mentions it and the file
is fetched in silence — someone else's city, at full detail, before the
operator's own area.
Compared by bounds rather than by filename: an operator who edited the
sample in place has a legitimate area and must not have it skipped.
"""
mine = _bounds(spec)
if mine is None or not SAMPLE_AREA.is_file():
return False
try:
theirs = _bounds(json.loads(SAMPLE_AREA.read_text(errors="replace")))
except (OSError, ValueError):
return False
return theirs is not None and mine == theirs
def fetch_passes(spec: dict, tf) -> list:
"""[(description, bbox, (min_zoom, max_zoom))] for one operating area.
An area given as a center and radius is fetched in two passes: full street
detail in the inner ring where a node actually navigates, and orientation
zoom out to the full radius. Fetching the whole radius at street zoom is
what turns a 150-mile area into a multi-hour, multi-gigabyte download —
roughly 350,000 tiles against a public USGS endpoint.
A hand-written rectangle has no center, so it gets a single pass.
"""
center = spec.get("center") or {}
lat, lon, radius = center.get("lat"), center.get("lon"), spec.get("radius_miles")
if tf and lat is not None and lon is not None and radius:
detail_r = min(float(spec.get("detail_radius_miles", tf.DETAIL_RADIUS_MILES)),
float(radius))
passes = [(f"detail {detail_r:g} mi",
tf.box_from_center(float(lat), float(lon), detail_r), tf.DETAIL_ZOOMS)]
if float(radius) > detail_r:
passes.append((f"overview {float(radius):g} mi",
tf.box_from_center(float(lat), float(lon), float(radius)),
tf.OVERVIEW_ZOOMS))
return passes
try:
box = {k: float(spec[k]) for k in ("north", "south", "east", "west")}
except (KeyError, TypeError, ValueError):
return []
return [("area", box, tf.DETAIL_ZOOMS if tf else (10, 15))]
MAP_LAYERS = (
("topo", "Topo_Offline.tms", "Topographic (Offline)"),
("imagery", "Satellite_Offline.tms", "Satellite Imagery (Offline)"),
)
# ---------------------------------------------------------------------------
# QMapShack settings
#
# QMapShack stores its settings through QSettings, which on Linux is an INI
# file under the organization name the application sets. QMapShack's main.cpp
# sets that to "QLandkarte", so the file is:
#
# ~/.config/QLandkarte/QMapShack.conf
#
# NOT QLandkarteGT. That was the predecessor project, and a profile staged
# there is read by nothing -- which is how this provisioner registered its
# offline maps into a directory QMapShack never opens, while a verification
# row confirmed the file was present.
# ---------------------------------------------------------------------------
QMS_CONF_REL = Path(".config") / "QLandkarte" / "QMapShack.conf"
QMS_CONF_LEGACY_REL = Path(".config") / "QLandkarteGT" / "QMapShack.conf"
# QMapShack keys its saved views by a generated "key_<md5>" that cannot be
# predicted from here. It also carries a backward-compatibility path: a view
# group whose name does NOT start with "key_" is taken as a legacy canvas
# name, and that group's settings are loaded (CCanvas.cpp, storedKey branch).
# Seeding under a plain name is therefore stable across versions.
QMS_VIEW_GROUP = "View 1"
# QSettings percent-encodes the space when it WRITES a group name, so the
# view QMapShack saves is "View%201" -- while a literal "View 1" in the file
# reads back identically, because Qt unescapes on read. Both spellings work
# going in; only one comes back out.
#
# That asymmetry is why every check below has to know both. A check that
# knows only the literal form cannot see the group QMapShack itself wrote, so
# on the second run it concludes there is no saved view and seeds one --
# writing a second posFocus line over the operator's own. Seeding is supposed
# to happen exactly once, on a profile that has never been opened.
QMS_VIEW_GROUP_ENC = "View%201"
def qms_view_prefixes() -> tuple:
"""Both spellings of the view group prefix, the one Qt writes first."""
return ("Views\\%s\\" % QMS_VIEW_GROUP_ENC,
"Views\\%s\\" % QMS_VIEW_GROUP)
# Square (tile-aligned) scales, which is the table that matches a slippy tile
# pyramid: index i has MPIXEL / 2**(20 - i) meters per pixel, so
# zoomIndex = 20 - slippy_zoom over the 17 levels it defines (z4..z20).
QMS_SCALES_SQUARE = 1
QMS_ZOOM_BASE = 20
QMS_DEFAULT_VIEW_ZOOM = 12 # orientation level; the fetcher always has it
def _qt_ini_escape(raw: bytes) -> tuple:
"""Qt's QSettings INI escaping. Returns (escaped, needs_quotes).
Reimplemented rather than shelled out to because a node has no Qt Python
bindings. Verified against Qt's own reader over 3,005 coordinates spanning
the poles, the antimeridian and the byte patterns that force quoting.
"""
simple = {0x07: r"\a", 0x08: r"\b", 0x0C: r"\f",
0x0A: r"\n", 0x0D: r"\r", 0x09: r"\t", 0x0B: r"\v"}
out, escape_next_if_digit, needs_quotes = [], False, False
for b in raw:
if b == 0x00:
out.append(r"\0")
escape_next_if_digit = True
continue
if b in simple:
out.append(simple[b])
escape_next_if_digit = False
continue
if b == 0x22:
out.append('\\"')
escape_next_if_digit = False
continue
if b == 0x5C:
out.append("\\\\")
escape_next_if_digit = False
continue
if b <= 0x1F or b >= 0x7F:
# Qt writes the hex unpadded and lowercase, which is exactly why
# it then escapes a following hex digit: "\xe" + "f" would
# otherwise read back as a single byte 0xef.
out.append("\\x%x" % b)
escape_next_if_digit = True
continue
ch = chr(b)
if ch in ";,=":
needs_quotes = True
if escape_next_if_digit and ch in "0123456789abcdefABCDEF":
out.append("\\x%x" % b)
escape_next_if_digit = True
continue
out.append(ch)
escape_next_if_digit = False
return "".join(out), needs_quotes
def qsettings_qpointf(x: float, y: float) -> str:
"""The exact INI text QSettings writes for QPointF(x, y).
Most of QMapShack's settings are plain text. The view center is not: it is
a QPointF serialized as a binary QVariant, type id 26, two big-endian
doubles, escaped into the INI. There is no text form QMapShack will read
instead -- QVariant::toPointF() on a string yields (0, 0).
"""
blob = b"@Variant(" + struct.pack(">Idd", 26, x, y) + b")"
escaped, needs_quotes = _qt_ini_escape(blob)
return '"%s"' % escaped if needs_quotes else escaped
def utm_proj_for(lat: float, lon: float) -> str:
"""A proj4 string for the UTM zone containing (lat, lon).
QMapShack has no MGRS or USNG support of any kind -- the strings appear
nowhere in its source, and its grid takes a proj4 projection. US National
Grid is MGRS on NAD83, so a UTM grid for the operating area's zone draws
the same lines USNG does; what it cannot do is label them with USNG's
100 km square letters. That is a QMapShack limitation, not a setting.
"""
zone = min(60, max(1, int((lon + 180.0) / 6.0) + 1))
south = " +south" if lat < 0 else ""
return ("+proj=utm +zone=%d%s +datum=WGS84 +units=m +no_defs"
% (zone, south))
def tile_zoom_range(layer_dir: Path) -> tuple:
"""(min_z, max_z) actually present on disk, or None when nothing is.
A .tms that does not declare its range gets QMapShack's defaults of 1 and
21, so the canvas asks for zoom levels the fetcher never downloaded. Every
one of those is a miss that still costs a path lookup.
"""
zooms = []
try:
for child in layer_dir.iterdir():
if child.is_dir() and child.name.isdigit():
zooms.append(int(child.name))
except OSError:
return None
return (min(zooms), max(zooms)) if zooms else None
#: A .tms MinZoomLevel/MaxZoomLevel is NOT a slippy zoom. It is QMapShack's own
#: scale index, and it runs the other way: CMapTMS::draw() computes
#:
#: zMax = 21 - layer.minZoomLevel # highest slippy z the layer may use
#: zMin = 21 - layer.maxZoomLevel # lowest slippy z the layer may use
#:
#: so the element named "Min" bounds the zoomed-IN end. Writing the slippy
#: numbers straight in told QMapShack a z10-15 pyramid served z6-z11: it then
#: clamped the canvas to z11, asked for z6-z9 tiles that do not exist, and sat
#: on "22 tiles pending" over a blank canvas. Found on a node, not in a test.
TMS_ZOOM_BASE = 21
def tms_zoom_levels(zrange: tuple) -> tuple:
"""(MinZoomLevel, MaxZoomLevel) for a slippy (min_z, max_z) tile range."""
min_z, max_z = zrange
return TMS_ZOOM_BASE - max_z, TMS_ZOOM_BASE - min_z
def _qms_text_value(s: str) -> str:
"""A plain string as QSettings would write it into an INI."""
escaped, needs_quotes = _qt_ini_escape(s.encode("utf-8"))
return '"%s"' % escaped if needs_quotes else escaped
def qms_map_key(tms: Path) -> str:
"""QMapShack's identifier for a map file: MD5 of its first 4096 bytes.
CMapItem::setFilename() hashes exactly that much and uses the hex digest
as the key everything else in the config hangs off. A .tms is far smaller
than 4 KiB, so in practice this is the hash of the whole file -- and it
changes whenever the file does, which is why the map registration below is
written in the same step that writes the .tms.
"""
with tms.open("rb") as f:
return hashlib.md5(f.read(4096)).hexdigest()
def _canvas_edit(lines: list, additions: list) -> list:
"""Insert key=value lines at the end of the [Canvas] section."""
block = ["%s=%s" % (k, v) for k, v in additions]
try:
start = lines.index("[Canvas]")
except ValueError:
if lines and lines[-1].strip():
lines.append("")
return lines + ["[Canvas]"] + block
end = len(lines)
for i in range(start + 1, len(lines)):
if lines[i].startswith("["):
end = i
break
lines[end:end] = block
return lines
def configure_qmapshack(conf: Path, maps_dir: Path, tms_files: list,
lat=None, lon=None,
zoom: int = QMS_DEFAULT_VIEW_ZOOM) -> dict:
"""Make QMapShack find, draw and open on the offline maps.
Three separate things have to be true before a downloaded tile pyramid is
visible, and none of them follows from the others:
1. mapPath has to name the directory, or QMapShack never lists the .tms
files at all. This used to be written only when a group supplied a
QMapShack.conf to stage -- and configs/ ships empty, so on a stock
clone it was never written and the maps were invisible.
2. A map QMapShack meets for the first time is added with status Unused
(CMapDraw::loadMapList), which means listed but NOT drawn. Registering
it under map2/keysKnownMaps with isActive=true is what makes it draw
on first launch instead of after the operator finds and clicks it.
3. The view has to be over the area the tiles cover.
Every part is a seed, never an overwrite: an operator who has run
QMapShack once has their own answer to all three in this file, and
QMapShack rewrites it on exit.
tms_files is in priority order: the first becomes the active map, the rest
are left for the operator to switch to. Two active raster layers stack, and
the upper one simply hides the lower, which reads as the lower one being
broken.
"""
# surrogateescape, not "replace": this is Qt's file, and a byte this
# provisioner cannot decode must come back out unchanged rather than as a
# replacement character written over somebody's staged profile.
lines = (conf.read_text(errors="surrogateescape").splitlines()
if conf.is_file() else [])
done = {}
# Hand-edited rather than run through configparser: this file is Qt's, not
# ours. configparser would rewrite every line it did not understand, and
# the keys here carry backslashes and the values carry Qt's own escaping.
def has(key):
return any(l.startswith(key + "=") for l in lines)
def has_view(suffix):
"""True when EITHER spelling of the view group carries this key."""
return any(has(p + suffix) for p in qms_view_prefixes())
# --- 1. the directory the .tms files live in --------------------------
want_path = str(maps_dir)
for i, line in enumerate(lines):
if line.startswith("mapPath="):
if want_path in line:
done["mapPath"] = "already listed"
else:
# Qt writes a QStringList comma-separated, so this appends
# rather than replacing whatever the operator already had.
lines[i] = line + ", " + want_path
done["mapPath"] = "appended"
break
else:
lines = _canvas_edit(lines, [("mapPath", _qms_text_value(want_path))])
done["mapPath"] = "added"
# --- 2. the maps themselves, so the first one draws -------------------
# Two schemas, because which one the installed QMapShack reads depends on
# its version and the field build is older than the rename:
#
# map2/keysKnownMaps + map2/<key>/isActive current QMapShack
# map/active = <key>, ... what came before it
#
# A build that predates map2 ignores those keys completely -- the maps
# still appear in the Maps tab, because loadMapList() scans mapPath and
# adds whatever it finds as Unused, but nothing is activated and the
# canvas stays empty until the operator clicks one. That is exactly the
# symptom this function exists to prevent, so both are written.
#
# Current QMapShack reads map/active too: loadMapList() applies it after
# map2, unconditionally, calling activate() on each key. The cost is that
# nothing ever deletes that legacy group there, so it re-activates on
# every launch. On the build this targets it is the native key and gets
# rewritten on exit, which is the trade being made.
vprefix = qms_view_prefixes()[0]
prefix = vprefix + "map2\\"
present = [f for f in tms_files if f.is_file()]
if not present:
done["maps"] = "no .tms files to register"
elif has_view("map2\\keysKnownMaps") or has_view("map\\active"):
done["maps"] = "kept"
else:
keys = [qms_map_key(f) for f in present]
adds = [(prefix + "keysKnownMaps", ", ".join(keys[:1]))]
# Only the first is activated; see the docstring on stacking.
adds.append((prefix + keys[0] + "\\isActive", "true"))
adds.append((prefix + keys[0] + "\\filename",
_qms_text_value(str(present[0]))))
adds.append((vprefix + "map\\active", keys[0]))
lines = _canvas_edit(lines, adds)
done["maps"] = "registered %s as the active map" % present[0].name
# --- 3. the view over the area ----------------------------------------
if lat is None or lon is None:
done["view"] = "no operating area"
elif has_view("posFocus"):
done["view"] = "kept"
else:
lines = _canvas_edit(lines, [
(vprefix + "posFocus",
qsettings_qpointf(math.radians(lon), math.radians(lat))),
(vprefix + "map2\\zoomIndex", str(QMS_ZOOM_BASE - zoom)),
# Same split as the map list above: a build predating map2 reads
# the zoom index from map/, and ignoring that opened the canvas
# at whatever QMapShack defaulted to rather than over the area.
(vprefix + "map\\zoomIndex", str(QMS_ZOOM_BASE - zoom)),
(vprefix + "scales", str(QMS_SCALES_SQUARE)),
(vprefix + "grid\\proj", _qms_text_value(utm_proj_for(lat, lon))),
])
done["view"] = "seeded"
conf.parent.mkdir(parents=True, exist_ok=True)
conf.write_text("\n".join(lines) + "\n", errors="surrogateescape")
return done
def area_center(spec: dict) -> tuple:
"""(lat, lon) for an operating area given either way, or None."""
center = spec.get("center") or {}
if center.get("lat") is not None and center.get("lon") is not None:
try:
return float(center["lat"]), float(center["lon"])
except (TypeError, ValueError):
return None
try:
box = {k: float(spec[k]) for k in ("north", "south", "east", "west")}
except (KeyError, TypeError, ValueError):
return None
return ((box["north"] + box["south"]) / 2.0,
(box["east"] + box["west"]) / 2.0)
try:
import requests
except ImportError:
requests = None
# ===========================================================================
# Low-level helpers (same behavior as the CLI port; logging goes through
# a callback instead of print(), and every "sudo" call routes through the
# askpass session so it works with no controlling terminal).
# ===========================================================================
def _current_user() -> str:
"""The invoking user's login name.
os.getlogin() reads the controlling terminal, which a GUI launched from a
desktop session may not have — it raises OSError there, which would kill
the run at Ctx construction before any step began.
"""
return os.environ.get("USER") or getpass.getuser()
def hostname_from_node_id(node_id: str) -> str:
"""An RFC 1123 hostname label derived from a callsign / node ID.
Node IDs are free text; a hostname may hold only letters, digits and
hyphens, may not begin or end with one, and stops at 63 characters.
Returns "" when nothing usable survives, in which case the caller must
leave the system name alone rather than guess at one.
"""
h = re.sub(r"[^A-Za-z0-9-]", "-", node_id)
h = re.sub(r"-{2,}", "-", h).strip("-")
return h[:63].strip("-")
def rewrite_hosts(lines: list, hostname: str) -> list:
"""/etc/hosts with its 127.0.1.1 entry pointed at `hostname`.
Pure and idempotent: every other line survives byte for byte, duplicate
127.0.1.1 entries collapse to one, and a file without such an entry gets
one directly after the loopback line, which is where Debian puts it.
"""
out, replaced = [], False
for line in lines:
if line.split()[:1] == ["127.0.1.1"]:
if not replaced:
out.append("127.0.1.1\t" + hostname)
replaced = True
continue
out.append(line)
if not replaced:
idx = next((i for i, l in enumerate(out) if l.split()[:1] == ["127.0.0.1"]), -1)
out.insert(idx + 1, "127.0.1.1\t" + hostname)
return out
class ProvisioningCanceled(Exception):
"""Raised between steps when the user hits Cancel."""
class ProvisioningError(Exception):
"""Raised when a step fails in a way the run cannot continue from."""
class SpinResult:
"""Mutable outcome flag yielded by Ctx.spin() — defaults to success;
a check=False call that fails without raising should set .ok = False
explicitly so the spinner resolves to the right glyph."""
__slots__ = ("ok",)
def __init__(self):
self.ok = True
class AskpassSession:
"""
Sets up a `sudo -A` helper so every `sudo` call in this script works
from a GUI with no TTY, using a password collected once at startup.
The password is written into a private (mode 0700) temp script that
just echoes it back to sudo when sudo invokes it as $SUDO_ASKPASS.
The file is removed as soon as the session ends (success, failure,
or cancel — see the `with` usage in run_provisioning()).
"""
def __init__(self, password: str):
fd, path = tempfile.mkstemp(prefix=UNIT_PREFIX + "-askpass-", suffix=".sh")
os.close(fd)
self.path = Path(path)
# Single-quote-safe embedding of the password.
escaped = password.replace("'", "'\\''")
self.path.write_text(f"#!/bin/sh\necho '{escaped}'\n")
self.path.chmod(stat.S_IRWXU) # 0700 — owner only
def env(self) -> dict:
e = os.environ.copy()
e["SUDO_ASKPASS"] = str(self.path)
return e
def verify(self) -> bool:
"""Validate the password now, so bad input fails fast at startup
rather than 30 seconds into package installation."""
r = subprocess.run(["sudo", "-A", "-v"], env=self.env(),
capture_output=True, text=True)
return r.returncode == 0
def close(self):
self.path.unlink(missing_ok=True)
class RunLog:
"""A plain-text transcript of one provisioning run, written as it happens.
The GUI log pane is ephemeral. It dies with the window, and its failure
output is deliberately condensed so that 588 progress redraws cannot bury
the one line that says what actually went wrong. The file is the copy that
survives, and it is the UNCONDENSED one: every line the pane shows, plus
the complete captured output of every command that failed, plus the
verification rows and the final result.
A run that goes wrong on a field laptop has to be reportable as one path.
Reconstructing it from screenshots of a scrolled pane loses exactly the
part that matters, every time.
Nothing here raises. A transcript that cannot be written is reported once,
in the pane, and the deployment carries on. The log is diagnostic; losing
it must never cost the operator the node.
"""
#: Level tag written into the file. Fixed width, so the message column
#: lines up and `grep FAIL` finds every failure in one pass.
TAGS = {"info": "INFO", "ok": " OK ", "warn": "WARN", "err": "FAIL",
"spin": " >> ", "head": "----"}
KEEP = 10 # run logs retained; older ones are pruned on open
def __init__(self, directory: Path):
self.path: Optional[Path] = None
self.error: Optional[str] = None
self.started = datetime.datetime.now()
self._fh = None
try:
directory.mkdir(parents=True, exist_ok=True)
path = directory / self.started.strftime("provision-%Y%m%d-%H%M%S.log")
# Line buffered. A run killed part-way through -- power loss on
# battery, a hard reboot, the lid closed on a laptop mid-install --
# still leaves everything up to the last line on disk, and that is
# precisely the run whose log is worth having.
self._fh = path.open("w", encoding="utf-8", errors="replace", buffering=1)
self.path = path
except Exception as e: # noqa: BLE001 -- see the class docstring
self.error = str(e)
return
self._prune(directory)
def _prune(self, directory: Path):
"""Keep the newest KEEP logs. A node reprovisioned repeatedly should
not accumulate transcripts in a hidden directory nobody opens."""
try:
logs = sorted(directory.glob("provision-*.log"))
for old in logs[:-self.KEEP]:
old.unlink(missing_ok=True)
except Exception: # noqa: BLE001
pass # tidying is optional; logging is not
# -- writing --------------------------------------------------------
def write(self, message: str, level: str = "info"):
"""One timestamped, tagged entry. Multi-line messages get a timestamp
on every line, so the file stays sortable and greppable by time."""
tag = self.TAGS.get(level, "INFO")
stamp = datetime.datetime.now().strftime("%H:%M:%S")
self._emit("".join("%s [%s] %s\n" % (stamp, tag, line)
for line in message.split("\n")))
def raw(self, text: str):
"""A verbatim block -- captured output of a command, kept exactly as
the command emitted it. Indented into a gutter so it is visibly not a
line the provisioner wrote, but otherwise untouched: no condensing, no
truncation. This is the whole point of the file."""
self._emit("".join(" | %s\n" % line
for line in text.rstrip("\n").split("\n")))
def banner(self, text: str):
"""Header/footer block, written without timestamps."""
self._emit(text if text.endswith("\n") else text + "\n")
def _emit(self, text: str):
if self._fh is None:
return
try:
self._fh.write(text)
except Exception as e: # noqa: BLE001 -- see the class docstring
# Out of disk is a real field condition, and it is not the only
# way a handle goes bad. Whatever it was, record why the transcript
# stops and stop trying: this class exists to describe a failing
# run, so it must not become one.
self.error = str(e)
self.close()
def close(self):
if self._fh is None:
return
try:
self._fh.close()
except Exception: # noqa: BLE001 -- closing must not raise either
pass
self._fh = None
# -- header / footer ------------------------------------------------
def header(self, node_id: str, user: str, selected: list, skipped: list):
try:
pretty = next((l.split("=", 1)[1].strip().strip('"')
for l in Path("/etc/os-release").read_text().splitlines()
if l.startswith("PRETTY_NAME=")), "unknown")
except OSError:
pretty = "unknown"
uname = os.uname()
lines = [
"=" * 72,
"%s Field Node provisioner v%s -- run log" % (OPERATOR_PREFIX, VERSION),
"=" * 72,
"Started : %s" % self.started.strftime("%Y-%m-%d %H:%M:%S %Z").strip(),
# Which build produced this transcript. The summary screen shows
# it too, but the screen closes and this file is what gets
# attached to a problem report.
"Version : v%s" % VERSION,
"Node ID : %s" % node_id,
"User : %s" % user,
"Host : %s -- %s" % (uname.nodename, pretty),
"Kernel : %s %s" % (uname.sysname, uname.release),
"Python : %s (%s)" % (platform.python_version(), sys.executable),
"Script : %s" % Path(__file__).resolve(),
# The provisioner reads configs/, docs/ and scripts/ by RELATIVE
# path, so a run launched from the wrong directory finds none of
# them and warns its way to a hollow node. Record where it ran.
"Working dir: %s" % os.getcwd(),
"",
"Steps selected (%d of %d):" % (len(selected), len(selected) + len(skipped)),
]
lines += [" %s" % label for label in selected] or [" (none)"]
lines += ["", "Steps skipped (%d):" % len(skipped)]
lines += [" %s" % label for label in skipped] or [" (none)"]
lines += ["=" * 72, ""]
self.banner("\n".join(lines))
def footer(self, title: str, ran: int, skipped: int, failed_steps: list,
passed: int, warned: int, failed: int):
end = datetime.datetime.now()
lines = ["", "=" * 72, "RESULT: %s" % title,
" %d step(s) run, %d skipped" % (ran, skipped)]
if failed_steps:
lines.append(" %d step(s) failed:" % len(failed_steps))
lines += [" %s" % label for label in failed_steps]
lines.append("Verification: %d passed, %d warning(s), %d failed"
% (passed, warned, failed))
lines.append("Finished: %s (elapsed %s)"
% (end.strftime("%Y-%m-%d %H:%M:%S"),
str(end - self.started).split(".")[0]))
lines += ["=" * 72, ""]
self.banner("\n".join(lines))
@dataclass
class Ctx:
"""Shared state threaded through every step function."""
home: Path
user: str
node_id: str
askpass: AskpassSession
log: Callable[[str, str], None] # log(message, level)
cancel_check: Callable[[], None] # raises ProvisioningCanceled
spin_start: Callable[[str], None] # begin an animated "in progress" log line
spin_stop: Callable[[bool], None] # resolve it to a check mark / cross
spin_progress: Callable[[str], None] # update the trailing text of the active spin line
data_dir: Path = field(init=False)
# `make install` succeeded, so /usr/bin/satdump and
# /usr/share/applications/satdump.desktop exist. Gates anything needing
# those paths -- specifically the desktop shortcut in finalize().
#
# The name is this precise because one flag once conflated "a binary
# exists somewhere" with "it was installed to /usr", and a failed
# `make install` still added a shortcut to a binary that was not there.
# A build-tree SatDump is usable and reads ~/.config/satdump the same
# way; it just has nothing under /usr to point a shortcut at.
satdump_system_installed: bool = False
def __post_init__(self):
self.data_dir = self.home / DATA_DIR_NAME
# The child ctx.run() is currently waiting on, so Cancel can reach it.
# Written from the worker thread and read from the Tk thread, hence
# the lock: without it the reader can see a process object that the
# worker has already finished with.
self._active_child = None
self._child_lock = threading.Lock()
# Nothing here has a terminal to prompt into (unzip's "replace
# file?", apt's debconf dialogs, needrestart's service-restart
# prompt). Without a way to answer, an interactive prompt is a
# silent, uncancellable hang — see stdin=DEVNULL below for the
# other half of this fix.
os.environ["DEBIAN_FRONTEND"] = "noninteractive"
@contextmanager
def spin(self, label: str):
"""Wrap a long-running block with an animated log line:
with ctx.spin("Installing core packages..."):
ctx.sudo("apt", "install", "-y", *packages)
Resolves to a check mark on normal exit, a cross on any raised
exception. For a check=False call whose success is judged by
return code rather than an exception, set `result.ok` yourself:
with ctx.spin("Building SatDump...") as result:
build_status = ctx.run([...], check=False).returncode
result.ok = (build_status == 0)
"""
self.cancel_check()
self.spin_start(label)
result = SpinResult()
try:
yield result
except BaseException:
self.spin_stop(False)
raise
else:
self.spin_stop(result.ok)
# -- process helpers -----------------------------------------------
# All of these capture stdout+stderr (merged) instead of letting the
# child inherit the launching terminal — nothing from apt/wine/git/
# cmake/make prints to the console behind the GUI. On success the
# captured text is simply discarded (the GUI's own curated ctx.log
# messages are what's shown). On a hard failure (check=True raising
# CalledProcessError), the captured output travels with the
# exception and _run_provisioning() dumps it into the GUI log —
# so failures get MORE diagnostic detail than before, not less.
#
# stdin is likewise always DEVNULL: any child that tries to prompt
# interactively (unzip on a file conflict, a stray debconf dialog)
# gets immediate EOF instead of blocking on input nothing can ever
# supply — a GUI child has no terminal to prompt into, so a hang
# here would otherwise be silent AND uncancellable, since Cancel
# only checks between steps, not mid-command.
def run(self, cmd, check=True, interruptible=True, **kw):
"""Run a child and wait for it. Interruptible by Cancel, by default.
Popen rather than subprocess.run so the process is nameable while it
runs -- subprocess.run gives no handle until it is over, which is the
reason Cancel used to be checkpoint-only. start_new_session puts the
child in its own process group so terminate_active_child() can signal
the whole tree: killing `make` alone leaves its compilers running.
interruptible=False for anything that must not be stopped part-way.
Nothing in this file passes it yet; ctx.sudo() is the blunt version of
the same idea, and is never interruptible -- see there.
"""
self.cancel_check()
kw.setdefault("stdin", subprocess.DEVNULL)
kw.setdefault("stdout", subprocess.PIPE)
kw.setdefault("stderr", subprocess.STDOUT)
kw.setdefault("text", True)
if not interruptible:
return subprocess.run(cmd, check=check, **kw)
proc = subprocess.Popen(cmd, start_new_session=True, **kw)
with self._child_lock:
self._active_child = proc
try:
out, _ = proc.communicate()
finally:
with self._child_lock:
self._active_child = None
# A terminated child surfaces as an ordinary non-zero exit. Ask whether
# Cancel was pressed before reporting it as a command failure, so a
# deliberate stop does not read as a broken step.
self.cancel_check()
if check and proc.returncode != 0:
raise subprocess.CalledProcessError(proc.returncode, cmd, output=out)
return subprocess.CompletedProcess(cmd, proc.returncode, out, None)
def terminate_active_child(self):
"""Signal the child ctx.run() is waiting on, if any. Safe to call from
another thread, and a no-op when nothing is running.
SIGTERM to the process group, not the process: `make -j` and
`fetch_map_tiles.py` both have children of their own, and signaling
only the leader leaves those orphaned and still working.
"""