From a27dd806c21ff439f66aa457f3a3839ed7646c5e Mon Sep 17 00:00:00 2001
From: Tommy Heggie <42516199+MusicCityTelecom@users.noreply.github.com>
Date: Sat, 12 Sep 2026 18:52:54 -0500
Subject: [PATCH 01/52] Add coexistence-safe shared database engine
---
src/cmnd_linux/shared_database.py | 253 ++++++++++++++++++++++++++++++
1 file changed, 253 insertions(+)
create mode 100644 src/cmnd_linux/shared_database.py
diff --git a/src/cmnd_linux/shared_database.py b/src/cmnd_linux/shared_database.py
new file mode 100644
index 00000000..e92de5a3
--- /dev/null
+++ b/src/cmnd_linux/shared_database.py
@@ -0,0 +1,253 @@
+"""Coexistence-safe use of an already-installed MySQL service for CMND 0.8.
+
+This module never changes global MySQL options. It only accepts a server that
+already matches the reviewed Windows-compatible lookup semantics, refuses any
+pre-existing CMND schema/user namespace, and creates/drops only the CMND objects
+that this invocation created. Administrator credentials are supplied through a
+root-only temporary defaults file or local root socket authentication and are
+never written to CMND persistent state.
+"""
+from __future__ import annotations
+
+from dataclasses import dataclass
+import json
+import os
+from pathlib import Path
+import re
+import shutil
+import subprocess
+import time
+from typing import Mapping
+
+from .application_stage import VENDOR_INPUT_HASHES
+from .artifacts import file_hash
+from .config import ConfigError
+from .database_compatibility import REQUIRED_VARIABLES, assess, parse_variable_rows
+
+SCHEMA_SPECS = (
+ ('smartinstall', 'siuser', 'smartinstall', (2, 3)),
+ ('cas', 'cas', 'cas', (2,)),
+ ('tpvision', 'tpvision', 'tpvision', tuple(range(2, 14))),
+ ('smartcontroldb', 'smartcontrol', 'smartcontrol', (2,)),
+ ('smartcms', 'smartcms', 'smartcms', (2, 3)),
+)
+APP_HOSTS = ('127.0.0.1', 'localhost')
+HEALTH_DIR = Path('/etc/cmnd/shared-database')
+
+
+def _valid_client(path: str) -> str:
+ candidate = Path(path)
+ if not candidate.is_absolute() or not candidate.is_file() or not os.access(candidate, os.X_OK):
+ raise ConfigError('shared database client must be an executable absolute path')
+ return str(candidate)
+
+
+def _validate_defaults_file(path: Path) -> Path:
+ path = Path(path)
+ if not path.is_file() or path.is_symlink():
+ raise ConfigError('database administrator defaults file must be a regular file')
+ if os.name == 'posix' and path.stat().st_mode & 0o077:
+ raise ConfigError('database administrator defaults file must be mode 0600 or stricter')
+ return path
+
+
+def _sql_string(value: str) -> str:
+ if not re.fullmatch(r'[A-Za-z0-9._@%+:/=-]{1,255}', value):
+ raise ConfigError('unsafe SQL credential/identifier literal')
+ return "'" + value.replace("'", "''") + "'"
+
+
+@dataclass
+class SharedDatabaseSession:
+ client: str
+ port: int
+ socket_path: str | None = None
+ admin_defaults_file: Path | None = None
+ admin_user: str = 'root'
+
+ def __post_init__(self) -> None:
+ self.client = _valid_client(self.client)
+ if type(self.port) is not int or not 1 <= self.port <= 65535:
+ raise ConfigError('invalid shared database port')
+ if self.socket_path is not None:
+ socket = Path(self.socket_path)
+ if not socket.exists() or socket.is_symlink():
+ raise ConfigError('shared database socket does not exist or is unsafe')
+ self.socket_path = str(socket)
+ if self.admin_defaults_file is not None:
+ self.admin_defaults_file = _validate_defaults_file(self.admin_defaults_file)
+ if not re.fullmatch(r'[A-Za-z0-9_@.-]{1,64}', self.admin_user):
+ raise ConfigError('invalid database administrator user')
+
+ def _command(self, database: str | None = None) -> list[str]:
+ command = [self.client]
+ if self.admin_defaults_file is not None:
+ command.append(f'--defaults-extra-file={self.admin_defaults_file}')
+ command += ['--batch', '--skip-column-names', '--binary-mode=1', '--connect-timeout=5']
+ if self.socket_path:
+ command += ['--protocol=socket', f'--socket={self.socket_path}']
+ else:
+ command += ['--protocol=tcp', '-h127.0.0.1', f'-P{self.port}']
+ if self.admin_defaults_file is None:
+ command.append(f'-u{self.admin_user}')
+ if database:
+ if not re.fullmatch(r'[A-Za-z0-9_]{1,64}', database):
+ raise ConfigError('unsafe database name')
+ command.append(database)
+ return command
+
+ def execute(self, sql: bytes | str, database: str | None = None, *, timeout: int = 900) -> bytes:
+ data = sql.encode() if isinstance(sql, str) else sql
+ result = subprocess.run(self._command(database), input=data, capture_output=True,
+ timeout=timeout, check=False)
+ if result.returncode:
+ raise RuntimeError('shared database command failed; administrator output intentionally withheld')
+ return result.stdout
+
+ def compatibility(self) -> dict:
+ names = ','.join("'" + name + "'" for name in REQUIRED_VARIABLES)
+ output = self.execute('SELECT VERSION(); SHOW VARIABLES WHERE Variable_name IN (' + names + ');', timeout=20)
+ lines = output.decode(errors='replace').splitlines()
+ if not lines:
+ raise ConfigError('shared database compatibility probe returned no output')
+ result = assess(lines[0].strip(), parse_variable_rows('\n'.join(lines[1:]))).as_dict()
+ result['connected'] = True
+ return result
+
+ def namespace_conflicts(self) -> dict[str, list[str]]:
+ schemas = ','.join(_sql_string(spec[0]) for spec in SCHEMA_SPECS)
+ users = ','.join(_sql_string(spec[1]) for spec in SCHEMA_SPECS)
+ schema_rows = self.execute(
+ f'SELECT SCHEMA_NAME FROM information_schema.SCHEMATA WHERE SCHEMA_NAME IN ({schemas});', timeout=20
+ ).decode(errors='replace').splitlines()
+ user_rows = self.execute(
+ f'SELECT CONCAT(User,"@",Host) FROM mysql.user WHERE User IN ({users});', timeout=20
+ ).decode(errors='replace').splitlines()
+ return {'schemas': sorted(filter(None, map(str.strip, schema_rows))),
+ 'users': sorted(filter(None, map(str.strip, user_rows)))}
+
+ def validate_for_fresh_cmnd(self) -> dict:
+ compatibility = self.compatibility()
+ if not compatibility.get('compatible'):
+ reasons = compatibility.get('reasons') or [compatibility.get('qualification', 'incompatible')]
+ raise ConfigError('existing database is not qualified for shared CMND use: ' + '; '.join(map(str, reasons)))
+ conflicts = self.namespace_conflicts()
+ if conflicts['schemas'] or conflicts['users']:
+ raise ConfigError('existing CMND database/user namespace detected; fresh shared-database install refused')
+ probe = subprocess.run(
+ [self.client, '--batch', '--skip-column-names', '--connect-timeout=3',
+ '--protocol=tcp', '-h127.0.0.1', f'-P{self.port}', '-u__cmnd_preflight_nonexistent__', '-e', 'SELECT 1'],
+ capture_output=True, timeout=8, check=False,
+ )
+ combined = (probe.stdout + probe.stderr).decode(errors='replace')
+ if probe.returncode and ('2002' in combined or '2003' in combined or "Can't connect" in combined):
+ raise ConfigError('existing database is not reachable on TCP loopback at the planned CMND port')
+ return {'compatible': True, 'namespace_clear': True, 'tcp_loopback_reachable': True,
+ 'changes_performed': False, 'compatibility': compatibility}
+
+ def initialize(self, vendor: Path, values: Mapping[str, str]) -> dict:
+ self.validate_for_fresh_cmnd()
+ vendor = Path(vendor)
+ for name, expected in VENDOR_INPUT_HASHES.items():
+ path = vendor / name
+ if not path.is_file() or path.is_symlink() or file_hash(path) != expected:
+ raise ConfigError('unrecognized or missing pinned vendor input: ' + name)
+ required_keys = {folder + '_db_password' for _, _, folder, _ in SCHEMA_SPECS}
+ required_keys.add('tpvision_db_password')
+ missing = sorted(key for key in required_keys if not values.get(key))
+ if missing:
+ raise ConfigError('missing generated CMND database credentials: ' + ', '.join(missing))
+
+ created_schemas: list[str] = []
+ created_users: list[tuple[str, str]] = []
+ try:
+ for schema, user, folder, numbers in SCHEMA_SPECS:
+ key = folder + '_db_password'
+ password = values[key]
+ self.execute(f'CREATE DATABASE `{schema}` CHARACTER SET utf8 COLLATE utf8_general_ci;')
+ created_schemas.append(schema)
+ for host in APP_HOSTS:
+ self.execute(f'CREATE USER {_sql_string(user)}@{_sql_string(host)} IDENTIFIED BY {_sql_string(password)};')
+ created_users.append((user, host))
+ self.execute(f'GRANT ALL ON `{schema}`.* TO {_sql_string(user)}@{_sql_string(host)};')
+ for number in numbers:
+ self.execute((vendor / 'SQLScripts' / folder / f'sql_{number}.sql').read_bytes(), schema)
+ return {'schemas_created': created_schemas,
+ 'users_created': [f'{user}@{host}' for user, host in created_users],
+ 'shared_database': True}
+ except Exception:
+ for user, host in reversed(created_users):
+ subprocess.run(self._command(), input=f'DROP USER IF EXISTS {_sql_string(user)}@{_sql_string(host)};'.encode(),
+ capture_output=True, timeout=20, check=False)
+ for schema in reversed(created_schemas):
+ subprocess.run(self._command(), input=f'DROP DATABASE IF EXISTS `{schema}`;'.encode(),
+ capture_output=True, timeout=60, check=False)
+ raise
+
+
+def write_health_files(values: Mapping[str, str], port: int, *, root: Path = HEALTH_DIR) -> dict[str, str]:
+ if root.exists() or root.is_symlink():
+ raise ConfigError('shared database health configuration already exists')
+ root.mkdir(parents=True, mode=0o700)
+ result: dict[str, str] = {}
+ for schema, user, folder in (('smartinstall', 'siuser', 'smartinstall'),
+ ('smartcontroldb', 'smartcontrol', 'smartcontrol')):
+ password = values[folder + '_db_password']
+ content = (f'[client]\nuser={user}\npassword={password}\nhost=127.0.0.1\n'
+ f'port={port}\nprotocol=tcp\n')
+ path = root / f'{schema}.cnf'
+ fd = os.open(path, os.O_CREAT | os.O_EXCL | os.O_WRONLY, 0o600)
+ with os.fdopen(fd, 'w', encoding='utf-8', newline='\n') as handle:
+ handle.write(content)
+ result[schema] = str(path)
+ marker = root / 'state.json'
+ marker.write_text(json.dumps({'port': port, 'files': result}, indent=2) + '\n', encoding='utf-8')
+ marker.chmod(0o600)
+ return result
+
+
+def _health_query(schema: str, sql: str, *, root: Path = HEALTH_DIR, timeout: int = 10) -> bytes:
+ state_path = root / 'state.json'
+ if not state_path.is_file() or state_path.is_symlink():
+ raise ConfigError('shared database health state is missing')
+ state = json.loads(state_path.read_text(encoding='utf-8'))
+ path = Path(state['files'][schema])
+ _validate_defaults_file(path)
+ client = shutil.which('mariadb') or shutil.which('mysql')
+ if not client:
+ raise ConfigError('mysql/mariadb client unavailable for shared database health check')
+ result = subprocess.run([client, f'--defaults-extra-file={path}', '--batch', '--skip-column-names', schema, '-e', sql],
+ capture_output=True, timeout=timeout, check=False)
+ if result.returncode:
+ raise RuntimeError('shared database health query failed')
+ return result.stdout
+
+
+def wait_shared_database(seconds: int = 120) -> None:
+ if type(seconds) is not int or not 1 <= seconds <= 600:
+ raise ConfigError('shared database readiness timeout must be 1..600 seconds')
+ deadline = time.monotonic() + seconds
+ while time.monotonic() < deadline:
+ try:
+ if _health_query('smartinstall', 'SELECT 1;').strip() == b'1':
+ return
+ except Exception:
+ pass
+ time.sleep(1)
+ raise RuntimeError('shared database did not become ready')
+
+
+def migration_histories() -> dict[str, bool]:
+ checks = (
+ ('smartinstall', 'flyway_schema_history', 122, '9.7'),
+ ('smartcontroldb', 'schema_version', 27, '1.5.1'),
+ )
+ result: dict[str, bool] = {}
+ for schema, table, count, version in checks:
+ try:
+ lines = _health_query(schema, f'SELECT version,success FROM {schema}.{table} ORDER BY installed_rank;').decode().splitlines()
+ result[schema] = bool(lines and len(lines) == count and lines[-1].split('\t')[0] == version
+ and all(line.endswith('\t1') for line in lines))
+ except Exception:
+ result[schema] = False
+ return result
From cd245ebf0764a316b9ed0521aafb9f6d972e12d6 Mon Sep 17 00:00:00 2001
From: Tommy Heggie <42516199+MusicCityTelecom@users.noreply.github.com>
Date: Sat, 12 Sep 2026 18:53:13 -0500
Subject: [PATCH 02/52] Add scoped existing-Apache integration
---
src/cmnd_linux/apache_integration.py | 147 +++++++++++++++++++++++++++
1 file changed, 147 insertions(+)
create mode 100644 src/cmnd_linux/apache_integration.py
diff --git a/src/cmnd_linux/apache_integration.py b/src/cmnd_linux/apache_integration.py
new file mode 100644
index 00000000..e75fab2a
--- /dev/null
+++ b/src/cmnd_linux/apache_integration.py
@@ -0,0 +1,147 @@
+"""Scoped integration with an already-running Debian/Ubuntu Apache service.
+
+CMND owns exactly one conf-available fragment and never edits ports.conf,
+apache2.conf, existing sites, or unrelated module configuration. The caller
+must choose free CMND ports before applying this fragment.
+"""
+from __future__ import annotations
+
+import hashlib
+import os
+from pathlib import Path
+import shutil
+import subprocess
+
+from .config import Config, ConfigError
+from .native_config import NativeLayout, native_endpoint
+
+CONF_AVAILABLE = Path('/etc/apache2/conf-available/cmnd-linux.conf')
+CONF_ENABLED = Path('/etc/apache2/conf-enabled/cmnd-linux.conf')
+MODULES = ('proxy', 'proxy_fcgi', 'proxy_http', 'ssl', 'rewrite', 'headers',
+ 'expires', 'filter', 'deflate')
+
+
+def supported() -> bool:
+ return (Path('/etc/apache2/apache2.conf').is_file()
+ and all(shutil.which(name) for name in ('apache2ctl', 'a2enmod', 'a2enconf', 'a2disconf', 'systemctl')))
+
+
+def render(config: Config, *, layout: NativeLayout = NativeLayout(), management_port: int = 9078) -> str:
+ host, _ = native_endpoint(config)
+ if type(management_port) is not int or not 1024 <= management_port <= 65535:
+ raise ConfigError('invalid management port for host Apache integration')
+ if layout.fpm_port in {config.apache_http, config.apache_https, management_port}:
+ raise ConfigError('host Apache integration port collision')
+ return f'''# Managed by CMND Linux 0.8. Do not merge this file into unrelated sites.
+Listen {config.bind}:{config.apache_http}
+Listen {config.bind}:{config.apache_https}
+
+
+ ServerName {host}
+ Redirect / https://{host}:{config.apache_https}/
+
+
+
+ ServerName {host}
+ DocumentRoot {layout.cms}
+ SSLEngine on
+ SSLProtocol -all +TLSv1.2 +TLSv1.3
+ SSLCertificateFile {layout.certificate}
+ SSLCertificateKeyFile {layout.key}
+ ProxyTimeout 900
+ ProxyRequests Off
+
+ Alias /SmartCMS {layout.cms}
+
+ LimitRequestBody 0
+ Require all granted
+ AllowOverride All
+ Options FollowSymLinks
+ DirectoryIndex index.php
+
+ Require all denied
+
+
+ SetHandler "proxy:fcgi://127.0.0.1:{layout.fpm_port}"
+
+
+
+
+ AllowOverride None
+ Options -ExecCGI -Indexes
+ Require all granted
+
+ Require all denied
+
+
+
+ ProxyPass /linux-cmnd/ http://127.0.0.1:{management_port}/ connectiontimeout=5 timeout=30
+ ProxyPassReverse /linux-cmnd/ http://127.0.0.1:{management_port}/
+
+ Require all granted
+
+
+'''
+
+
+def _run(args: list[str], *, timeout: int = 60) -> subprocess.CompletedProcess[str]:
+ result = subprocess.run(args, capture_output=True, text=True, timeout=timeout, check=False)
+ if result.returncode:
+ raise RuntimeError('host Apache command failed: ' + Path(args[0]).name + '; inspect journal/configtest output locally')
+ return result
+
+
+def apply(config: Config, *, execute: bool = False) -> dict:
+ content = render(config)
+ if not supported():
+ raise ConfigError('existing Apache is not a supported Debian/Ubuntu apache2 layout')
+ if CONF_AVAILABLE.exists() or CONF_AVAILABLE.is_symlink() or CONF_ENABLED.exists() or CONF_ENABLED.is_symlink():
+ raise ConfigError('CMND host Apache fragment already exists; refusing overwrite')
+ enabled_before = {module: (Path('/etc/apache2/mods-enabled') / f'{module}.load').exists() for module in MODULES}
+ report = {'executed': execute, 'configuration': str(CONF_AVAILABLE),
+ 'sha256': hashlib.sha256(content.encode()).hexdigest(),
+ 'modules_already_enabled': sorted(name for name, enabled in enabled_before.items() if enabled),
+ 'host_apache_reloaded': False}
+ if not execute:
+ return report
+
+ fd = os.open(CONF_AVAILABLE, os.O_CREAT | os.O_EXCL | os.O_WRONLY, 0o644)
+ enabled_by_us: list[str] = []
+ try:
+ with os.fdopen(fd, 'w', encoding='utf-8', newline='\n') as handle:
+ handle.write(content)
+ for module, already in enabled_before.items():
+ if not already:
+ _run([shutil.which('a2enmod') or 'a2enmod', module])
+ enabled_by_us.append(module)
+ _run([shutil.which('a2enconf') or 'a2enconf', 'cmnd-linux'])
+ _run([shutil.which('apache2ctl') or 'apache2ctl', 'configtest'])
+ _run([shutil.which('systemctl') or 'systemctl', 'reload', 'apache2.service'])
+ report['host_apache_reloaded'] = True
+ report['modules_enabled_by_cmnd'] = enabled_by_us
+ return report
+ except Exception:
+ subprocess.run([shutil.which('a2disconf') or 'a2disconf', 'cmnd-linux'], capture_output=True, timeout=20)
+ subprocess.run([shutil.which('apache2ctl') or 'apache2ctl', 'configtest'], capture_output=True, timeout=20)
+ subprocess.run([shutil.which('systemctl') or 'systemctl', 'reload', 'apache2.service'], capture_output=True, timeout=30)
+ raise
+
+
+def detach(*, execute: bool = False) -> dict:
+ if not CONF_AVAILABLE.exists() and not CONF_ENABLED.exists():
+ return {'executed': execute, 'present': False}
+ if CONF_AVAILABLE.is_symlink():
+ raise ConfigError('unexpected symlink at CMND Apache source fragment')
+ if CONF_AVAILABLE.exists():
+ text = CONF_AVAILABLE.read_text(encoding='utf-8', errors='replace')
+ if not text.startswith('# Managed by CMND Linux 0.8.'):
+ raise ConfigError('existing Apache fragment is not recognized as CMND-owned')
+ report = {'executed': execute, 'present': True, 'configuration': str(CONF_AVAILABLE)}
+ if not execute:
+ return report
+ subprocess.run([shutil.which('a2disconf') or 'a2disconf', 'cmnd-linux'], capture_output=True, timeout=20)
+ _run([shutil.which('apache2ctl') or 'apache2ctl', 'configtest'])
+ _run([shutil.which('systemctl') or 'systemctl', 'reload', 'apache2.service'])
+ if CONF_AVAILABLE.exists():
+ CONF_AVAILABLE.unlink()
+ return report | {'detached': True}
From f10c945295e52fc7a420651a91f5e992d45eab94 Mon Sep 17 00:00:00 2001
From: Tommy Heggie <42516199+MusicCityTelecom@users.noreply.github.com>
Date: Sat, 12 Sep 2026 18:55:04 -0500
Subject: [PATCH 03/52] Add 0.8 coexistence deployment engine
---
src/cmnd_linux/coexist_deploy.py | 170 +++++++++++++++++++++++++++++++
1 file changed, 170 insertions(+)
create mode 100644 src/cmnd_linux/coexist_deploy.py
diff --git a/src/cmnd_linux/coexist_deploy.py b/src/cmnd_linux/coexist_deploy.py
new file mode 100644
index 00000000..2dc67c7f
--- /dev/null
+++ b/src/cmnd_linux/coexist_deploy.py
@@ -0,0 +1,170 @@
+"""0.8 coexistence-aware fresh deployment engine.
+
+The v0.7.1-derived native_deploy module remains unchanged. This module reuses its
+verified primitives while allowing a pre-qualified host MySQL service and/or a
+CMND-owned fragment in an existing Debian/Ubuntu Apache service.
+"""
+from __future__ import annotations
+from dataclasses import dataclass
+import hashlib, json, os, platform, pwd, re, secrets, shutil, socket, ssl, subprocess, time
+from pathlib import Path
+from urllib.error import HTTPError, URLError
+from urllib.parse import urlsplit
+from urllib.request import HTTPSHandler, HTTPRedirectHandler, ProxyHandler, build_opener
+
+from .apache_integration import apply as apache_apply, detach as apache_detach, supported as apache_supported
+from .application_stage import ApplicationInputs, VENDOR_INPUT_HASHES, _tomcat_members, stage_application
+from .artifacts import file_hash
+from .certificates import CertificateConfig, provision_certificates
+from .config import Config, ConfigError, load_config
+from .egress import EgressPolicy, apply_policy
+from .native_config import native_endpoint, render_native_files
+from .native_deploy import (BASELINE, ETC, LAYOUT, MANAGEMENT, MYSQL_IMAGE, SCHEMAS, STATE,
+ _mysql, _owned_tree, https_origin, mysql_server_options, run, validate_baseline,
+ validate_image, wait_database, wait_php, write_new)
+from .shared_database import (SharedDatabaseSession, migration_histories as shared_histories,
+ wait_shared_database, write_health_files)
+from .vendor_config import REQUIRED_SECRETS
+
+@dataclass(frozen=True)
+class CoexistInputs:
+ config: Path; vendor: Path; tomcat_archive: Path; php_image: str; java_home: Path
+ database_mode: str='isolated'; apache_mode: str='standalone'
+ shared_database: SharedDatabaseSession|None=None; apt_managed: bool=True
+
+def os_support(content,machine):
+ values={}
+ for line in content.splitlines():
+ if '=' in line and not line.startswith('#'):
+ k,v=line.split('=',1); values[k]=v.strip('"\'')
+ selected=(values.get('ID',''),values.get('VERSION_ID',''))
+ if selected not in {('ubuntu','22.04'),('ubuntu','24.04'),('ubuntu','26.04'),('debian','12'),('debian','13')}:
+ raise ConfigError('0.8 supports Ubuntu 22.04/24.04/26.04 or Debian 12/13 candidates')
+ if machine not in {'x86_64','amd64'}: raise ConfigError('CMND requires amd64')
+ return selected
+
+def _units(java_home,db_mode,apache_mode,apt_managed=True):
+ if db_mode not in {'isolated','shared'} or apache_mode not in {'standalone','host'}: raise ConfigError('invalid coexistence mode')
+ dbreq='Requires=cmnd-mysql.service\nAfter=cmnd-mysql.service\n' if db_mode=='isolated' else 'After=network-online.target\n'
+ dbwait='/usr/bin/cmndctl native-wait-database' if db_mode=='isolated' else '/usr/bin/cmndctl shared-wait-database'
+ before='cmnd-php.service cmnd-tomcat.service'+(' cmnd-mysql.service' if db_mode=='isolated' else '')+(' cmnd-apache.service' if apache_mode=='standalone' else '')
+ u={
+ 'cmnd-egress.service':f'''[Unit]\nDescription=CMND egress isolation\nAfter=local-fs.target\nBefore={before}\n[Service]\nType=oneshot\nRemainAfterExit=yes\nEnvironment=PATH=/usr/sbin:/usr/bin:/sbin:/bin\nExecStart=/usr/bin/python3 /etc/cmnd/egress.py --policy /etc/cmnd/egress.json --execute\nRuntimeDirectory=cmnd\nRuntimeDirectoryMode=0755\nNoNewPrivileges=true\nProtectHome=true\nProtectSystem=strict\nReadWritePaths=/run\nCapabilityBoundingSet=CAP_NET_ADMIN CAP_NET_RAW\n[Install]\nWantedBy=multi-user.target\n''',
+ 'cmnd-php.service':f'''[Unit]\nDescription=CMND legacy PHP runtime\nRequires=cmnd-egress.service docker.service\nAfter=cmnd-egress.service docker.service\n{dbreq}[Service]\nType=simple\nExecStartPre={dbwait}\nExecStart=/usr/bin/docker start -a cmnd-native-php\nExecStop=/usr/bin/docker stop -t 30 cmnd-native-php\nRestart=on-failure\nTimeoutStartSec=180\n[Install]\nWantedBy=multi-user.target\n''',
+ 'cmnd-tomcat.service':f'''[Unit]\nDescription=Philips CMND Java applications\nRequires=cmnd-egress.service\nAfter=cmnd-egress.service\n{dbreq}[Service]\nType=simple\nUser=cmnd\nGroup=cmnd\nEnvironment=JAVA_HOME={java_home}\nEnvironmentFile=/etc/cmnd/native-tomcat.env\nWorkingDirectory=/opt/cmnd/tomcat\nExecStartPre=+/usr/bin/cmndctl native-hardware-access --execute\nExecStartPre=+{dbwait}\nExecStart=/opt/cmnd/tomcat/bin/catalina.sh run\nSuccessExitStatus=143\nRestart=on-failure\nUMask=0027\nNoNewPrivileges=true\nPrivateTmp=true\nProtectHome=true\nProtectSystem=strict\nReadWritePaths=/opt/Philips /opt/cmnd/tomcat /var/lib/cmnd /var/log/cmnd\n[Install]\nWantedBy=multi-user.target\n''',
+ 'cmnd-admin.service':'''[Unit]\nDescription=Linux CMND administration GUI\nAfter=network-online.target\n[Service]\nType=simple\nUser=cmnd-admin\nGroup=cmnd-admin\nExecStart=/usr/bin/cmndctl update-gui --settings /etc/linux-cmnd-management/admin.json\nRestart=on-failure\nUMask=0077\nNoNewPrivileges=true\nProtectSystem=strict\nProtectHome=true\nReadWritePaths=/var/lib/cmnd-update-requests\n[Install]\nWantedBy=multi-user.target\n'''}
+ if db_mode=='isolated': u['cmnd-mysql.service']='''[Unit]\nDescription=CMND isolated MySQL\nRequires=cmnd-egress.service docker.service\nAfter=cmnd-egress.service docker.service\n[Service]\nType=simple\nExecStart=/usr/bin/docker start -a cmnd-native-mysql\nExecStop=/usr/bin/docker stop -t 30 cmnd-native-mysql\nRestart=on-failure\n[Install]\nWantedBy=multi-user.target\n'''
+ if apache_mode=='standalone': u['cmnd-apache.service']='''[Unit]\nDescription=CMND standalone Apache\nRequires=cmnd-php.service\nAfter=cmnd-php.service\n[Service]\nType=simple\nExecStart=/usr/sbin/apache2 -f /etc/cmnd/apache.conf -DFOREGROUND\nExecReload=/usr/sbin/apache2 -f /etc/cmnd/apache.conf -k graceful\nRestart=on-failure\nNoNewPrivileges=true\nProtectSystem=strict\nProtectHome=true\nReadWritePaths=/run/cmnd /var/log/cmnd /opt/cmnd/SmartCMS/sites/default/files\n[Install]\nWantedBy=multi-user.target\n'''
+ return u
+
+def _port_free(port):
+ with socket.socket() as s:
+ try:s.bind(('0.0.0.0',port)); return True
+ except OSError:return False
+
+def preflight(i:CoexistInputs,c:Config):
+ if i.database_mode not in {'isolated','shared'} or i.apache_mode not in {'standalone','host'}: raise ConfigError('invalid coexistence mode')
+ native_endpoint(c); render_native_files(c,{k:'preflight-placeholder' for k in REQUIRED_SECRETS}); validate_image(i.php_image)
+ distro=os_support(Path('/etc/os-release').read_text(),platform.machine()); validate_baseline(); _tomcat_members(i.tomcat_archive)
+ for name,expected in VENDOR_INPUT_HASHES.items():
+ p=i.vendor/name
+ if not p.is_file() or p.is_symlink() or file_hash(p)!=expected: raise ConfigError('unrecognized vendor input: '+name)
+ for cmd in ('docker','apache2','openssl','systemctl','systemd-analyze','iptables','ip6tables','ip','update-ca-certificates','useradd'):
+ if not shutil.which(cmd): raise ConfigError('missing dependency: '+cmd)
+ j=subprocess.run([str(i.java_home/'bin/java'),'-version'],capture_output=True)
+ if j.returncode or not re.search(rb'version "17\.',j.stdout+j.stderr): raise ConfigError('CMND requires Java 17')
+ if not os.access(i.java_home/'bin/keytool',os.X_OK): raise ConfigError('Java 17 keytool required')
+ if not os.access('/usr/bin/cmnd-7zip',os.X_OK) or not any(os.access(p,os.X_OK) for p in ('/usr/bin/7zz','/usr/bin/7z')): raise ConfigError('7zip helpers required')
+ for p in (STATE,MANAGEMENT,Path('/var/lib/cmnd-updates'),Path('/var/lib/cmnd-update-requests'),Path(LAYOUT.tomcat),Path(LAYOUT.cms),Path('/opt/Philips'),ETC/'deployment.json',ETC/'tls',ETC/'apache.conf',ETC/'php-fpm.conf',ETC/'native-tomcat.env',ETC/'java-cacerts',ETC/'egress.json'):
+ if p.exists() or p.is_symlink(): raise ConfigError('fresh deployment refuses existing state: '+str(p))
+ for name in ('cmnd-native-mysql','cmnd-native-php'):
+ if subprocess.run(['docker','inspect',name],capture_output=True).returncode==0: raise ConfigError('existing CMND container: '+name)
+ ports={c.tomcat_http,c.tomcat_https,c.apache_http,c.apache_https,LAYOUT.fpm_port,9078}
+ if len(ports|{c.database_port})!=7: raise ConfigError('CMND ports collide')
+ for port in ports:
+ if not _port_free(port): raise ConfigError('planned CMND port occupied: '+str(port))
+ db={'mode':i.database_mode}
+ if i.database_mode=='isolated':
+ if not _port_free(c.database_port): raise ConfigError('isolated DB port occupied')
+ run('docker','image','inspect',MYSQL_IMAGE)
+ else:
+ if not i.shared_database or i.shared_database.port!=c.database_port: raise ConfigError('shared DB session/port mismatch')
+ db.update(i.shared_database.validate_for_fresh_cmnd())
+ if i.apache_mode=='host' and not apache_supported(): raise ConfigError('host Apache layout unsupported')
+ run('docker','image','inspect',i.php_image)
+ return {'os':list(distro),'database':db,'apache_mode':i.apache_mode,'vendor_inputs_verified':len(VENDOR_INPUT_HASHES)}
+
+def _isolated_db(i,c,values):
+ root=secrets.token_hex(32); write_new(STATE/'mysql-root-password',root); write_new(STATE/'mysql-client.cnf',f'[client]\nuser=root\npassword={root}\nhost=127.0.0.1\nport={c.database_port}\nprotocol=tcp\n'); (STATE/'mysql').mkdir(mode=0o700)
+ run('docker','create','--name','cmnd-native-mysql','--network','host','--mount',f'type=bind,src={STATE}/mysql,dst=/var/lib/mysql','--mount',f'type=bind,src={STATE}/mysql-root-password,dst=/run/secrets/root-password,readonly','--mount',f'type=bind,src={STATE}/mysql-client.cnf,dst=/run/secrets/client.cnf,readonly','-e','MYSQL_ROOT_PASSWORD_FILE=/run/secrets/root-password',MYSQL_IMAGE,*mysql_server_options(c.database_port)); run('systemctl','start','cmnd-mysql'); wait_database()
+ for schema,user,folder,numbers in SCHEMAS:
+ _mysql((f'CREATE DATABASE `{schema}` CHARACTER SET utf8 COLLATE utf8_general_ci;CREATE USER \'{user}\'@\'%\' IDENTIFIED BY \'{values[folder+"_db_password"]}\';GRANT ALL ON `{schema}`.* TO \'{user}\'@\'%\';').encode())
+ for n in numbers:_mysql((i.vendor/'SQLScripts'/folder/f'sql_{n}.sql').read_bytes(),schema)
+
+def _admin(i):
+ password=secrets.token_hex(24); sql="DELETE FROM cas.users; INSERT INTO cas.users(username,password,role) VALUES('admin','%s','ADMIN');"%hashlib.md5(password.encode()).hexdigest()
+ _mysql(sql.encode()) if i.database_mode=='isolated' else i.shared_database.execute(sql,'cas'); return password
+
+class _NoRedirect(HTTPRedirectHandler):
+ def redirect_request(self,*args):return None
+
+def _ready(c,db_mode,seconds=900):
+ ctx=ssl.create_default_context(cafile=str(ETC/'tls/ca.crt')); opener=build_opener(ProxyHandler({}),HTTPSHandler(context=ctx),_NoRedirect()); host=urlsplit(c.callback_base_url).hostname; deadline=time.monotonic()+seconds; statuses={}; histories={}
+ while time.monotonic()
Date: Sat, 12 Sep 2026 18:55:40 -0500
Subject: [PATCH 04/52] Add APT-managed activation transaction
---
src/cmnd_linux/apt_installer.py | 170 ++++++++++++++++++++++++++++++++
1 file changed, 170 insertions(+)
create mode 100644 src/cmnd_linux/apt_installer.py
diff --git a/src/cmnd_linux/apt_installer.py b/src/cmnd_linux/apt_installer.py
new file mode 100644
index 00000000..b7accc0d
--- /dev/null
+++ b/src/cmnd_linux/apt_installer.py
@@ -0,0 +1,170 @@
+"""APT-managed CMND 0.8 activation.
+
+Versioned Debian packages place tooling, exact Philips inputs and pinned Tomcat
+on disk first. This module inventories the host, selects coexistence modes,
+prepares runtime images and hands activation to coexist_deploy. Database admin
+passwords are accepted only through root-only temporary files and never persisted.
+"""
+from __future__ import annotations
+import argparse, json, os, re, shutil, socket, subprocess, tempfile
+from pathlib import Path
+from . import __version__
+from .config import ConfigError, load_config
+from .coexist_deploy import CoexistInputs, deploy
+from .environment import DEFAULT_PORTS, host_inventory
+from .install_plan import allocate_port, build_plan
+from .native_deploy import BASELINE, MYSQL_IMAGE, validate_baseline
+from .shared_database import SharedDatabaseSession
+
+VENDOR_ROOT=Path('/usr/lib/cmnd/vendor/7.5.9')
+TOMCAT_ARCHIVE=Path('/usr/lib/cmnd/tomcat/apache-tomcat-9.0.121.tar.gz')
+PACKAGE_ARCHIVE=Path(f'/usr/lib/cmnd/packages/linux-cmnd_{__version__}_amd64.deb')
+DEFAULT_CONFIG=Path('/opt/linux-cmnd/current/config/cmnd.install.toml')
+CONFIG=Path('/etc/cmnd/cmnd.toml'); CACHE=Path('/var/cache/linux-cmnd/bootstrap')
+PHP_IID=CACHE/'php-image.id'; PHP_BUILD_LOG=CACHE/'php-build.log'
+
+def _run(args,*,timeout=1800): return subprocess.run(args,capture_output=True,timeout=timeout,check=False)
+def _require_root():
+ if os.name!='posix' or not hasattr(os,'geteuid') or os.geteuid()!=0: raise ConfigError('APT activation must run as root')
+def _safe_password_file(path):
+ path=Path(path)
+ if not path.is_file() or path.is_symlink() or any(p.is_symlink() for p in path.parents): raise ConfigError('database administrator password file must be a regular non-symlink file')
+ if path.stat().st_size>4096 or (os.name=='posix' and path.stat().st_mode&0o077): raise ConfigError('database administrator password file must be mode 0600 or stricter')
+ value=path.read_text(encoding='utf-8').rstrip('\r\n')
+ if not value or any(c in value for c in ('\x00','\n','\r')): raise ConfigError('database administrator password is empty or contains unsupported control characters')
+ return value
+def _option_quote(value): return '"'+value.replace('\\','\\\\').replace('"','\\"')+'"'
+def _db_defaults_file(directory,user,password):
+ if not re.fullmatch(r'[A-Za-z0-9_@.-]{1,64}',user): raise ConfigError('invalid database administrator username')
+ path=directory/'database-admin.cnf'; fd=os.open(path,os.O_CREAT|os.O_EXCL|os.O_WRONLY,0o600)
+ with os.fdopen(fd,'w',encoding='utf-8',newline='\n') as h:h.write(f'[client]\nuser={_option_quote(user)}\npassword={_option_quote(password)}\n')
+ return path
+
+def _assigned_ipv4():
+ r=_run(['ip','-j','-4','address','show'],timeout=10)
+ if r.returncode:return []
+ try:interfaces=json.loads(r.stdout)
+ except Exception:return []
+ return [a['local'] for i in interfaces if 'UP' in i.get('flags',[]) for a in i.get('addr_info',[]) if a.get('family')=='inet' and isinstance(a.get('local'),str)]
+def choose_server_ip(requested=None):
+ assigned=_assigned_ipv4()
+ if requested:
+ try:socket.inet_aton(requested)
+ except OSError as e:raise ConfigError('server IP must be a literal IPv4 address') from e
+ if requested!='127.0.0.1' and requested not in assigned: raise ConfigError('requested server IP is not assigned to an active local interface')
+ return requested
+ values=[v for v in assigned if not v.startswith('127.')]; return values[0] if values else '127.0.0.1'
+def _occupied(inv): return {int(x['port']) for x in inv.get('listeners',{}).get('entries',[]) if isinstance(x,dict) and isinstance(x.get('port'),int)}
+def _planned_ports(inv,plan,database_mode):
+ c=plan['components']; ports={'tomcat_http':int(c['tomcat']['ports']['http']),'tomcat_https':int(c['tomcat']['ports']['https']),'apache_http':int(c['apache']['ports']['http']),'apache_https':int(c['apache']['ports']['https'])}
+ if database_mode=='shared':ports['database']=int(c['database'].get('port') or DEFAULT_PORTS['database'])
+ else:ports['database']=allocate_port(DEFAULT_PORTS['database'],_occupied(inv),set(ports.values())|{DEFAULT_PORTS['php_fpm'],DEFAULT_PORTS['management']})
+ if len(set(ports.values())|{DEFAULT_PORTS['php_fpm'],DEFAULT_PORTS['management']})!=7: raise ConfigError('installation planner produced colliding CMND ports')
+ return ports
+def render_config(ip,ports):
+ mode='isolated' if ip.startswith('127.') else 'lab'
+ return f'''# Generated by CMND Linux 0.8 APT activation. No TVs are authorized.\n[safety]\nmode = "{mode}"\npermitted_ranges = ["127.0.0.0/8"]\n\n[network]\nbind = "{ip}"\ncallback_base_url = "http://{ip}:{ports['tomcat_http']}"\ntimeout_seconds = 5\n\n[ports]\ntomcat_http = {ports['tomcat_http']}\ntomcat_https = {ports['tomcat_https']}\napache_http = {ports['apache_http']}\napache_https = {ports['apache_https']}\ndatabase = {ports['database']}\n\n[tv]\nallowlist = []\n'''
+def _install_config(content):
+ CONFIG.parent.mkdir(mode=0o750,parents=True,exist_ok=True)
+ if CONFIG.exists() or CONFIG.is_symlink():
+ if CONFIG.is_symlink() or not CONFIG.is_file():raise ConfigError('existing CMND configuration path is unsafe')
+ if DEFAULT_CONFIG.is_file() and CONFIG.read_bytes()!=DEFAULT_CONFIG.read_bytes():load_config(CONFIG); return CONFIG
+ backup=CONFIG.with_name('cmnd.toml.package-default')
+ if not backup.exists():backup.write_bytes(CONFIG.read_bytes()); backup.chmod(0o600)
+ temp=CONFIG.with_name('.cmnd.toml.apt-new')
+ if temp.exists() or temp.is_symlink():raise ConfigError('stale temporary CMND configuration exists')
+ fd=os.open(temp,os.O_CREAT|os.O_EXCL|os.O_WRONLY,0o640)
+ with os.fdopen(fd,'w',encoding='utf-8',newline='\n') as h:h.write(content)
+ os.replace(temp,CONFIG); load_config(CONFIG); return CONFIG
+def _find_db_client(inv):
+ db=inv.get('database',{})
+ for name in ('mariadb_client','mysql_client'):
+ r=db.get(name,{})
+ if isinstance(r,dict) and r.get('present') and r.get('path'):return str(r['path'])
+ return shutil.which('mariadb') or shutil.which('mysql')
+def _shared_session(inv,password_file,admin_user,temp):
+ client=_find_db_client(inv)
+ if not client:return None
+ db=inv.get('database',{}); sockets=db.get('socket_candidates') or []
+ if db.get('root_socket_auth')=='available' and sockets and admin_user=='root':s=SharedDatabaseSession(client,3306,socket_path=str(sockets[0]),admin_user='root')
+ elif password_file is not None:s=SharedDatabaseSession(client,3306,socket_path=str(sockets[0]) if sockets else None,admin_defaults_file=_db_defaults_file(temp,admin_user,_safe_password_file(password_file)),admin_user=admin_user)
+ else:return None
+ try:
+ port=s.execute('SELECT @@port;',timeout=10).decode(errors='replace').strip()
+ if port.isdigit():s.port=int(port)
+ except RuntimeError:return None
+ return s
+def _select_modes(inv,plan,requested_database,requested_apache,password_file,admin_user,temp):
+ notes=[]; session=None
+ if requested_database in {'auto','existing'}:
+ session=_shared_session(inv,password_file,admin_user,temp)
+ if session:
+ try:session.validate_for_fresh_cmnd(); dbmode='shared'; notes.append('Existing MySQL passed shared-database gate.')
+ except (ConfigError,RuntimeError) as e:
+ if requested_database=='existing':raise
+ session=None; dbmode='isolated'; notes.append('Existing database preserved but not reused: '+str(e))
+ elif requested_database=='existing':raise ConfigError('existing database mode requested but no authenticated administrator session is available')
+ else:dbmode='isolated'; notes.append('No qualified authenticated host DB; using isolated MySQL fallback.')
+ elif requested_database=='isolated':dbmode='isolated'
+ else:raise ConfigError('database mode must be auto, existing, or isolated')
+ ap=inv.get('web',{}).get('apache_service',{}); present=bool(plan['components']['apache'].get('existing_apache'))
+ if requested_apache=='auto':webmode='host' if present and ap.get('active') else 'standalone'
+ elif requested_apache in {'host','standalone'}:webmode=requested_apache
+ else:raise ConfigError('Apache mode must be auto, host, or standalone')
+ if webmode=='host' and not present:raise ConfigError('host Apache mode requested but no existing Apache installation was detected')
+ notes.append('Apache mode: '+webmode); return dbmode,webmode,session,notes
+def _ensure_docker():
+ if not shutil.which('docker'):raise ConfigError('Docker runtime is required by current legacy PHP profile')
+ r=_run(['docker','info'],timeout=20)
+ if r.returncode and shutil.which('systemctl'):_run(['systemctl','enable','--now','docker.service'],timeout=120); r=_run(['docker','info'],timeout=20)
+ if r.returncode:raise ConfigError('Docker daemon unavailable')
+def _ensure_image(image):
+ if _run(['docker','image','inspect',image],timeout=30).returncode==0:return
+ if _run(['docker','pull',image],timeout=1800).returncode:raise ConfigError('required pinned container image could not be pulled')
+def _php_image():
+ if PHP_IID.is_file() and not PHP_IID.is_symlink():
+ image=PHP_IID.read_text().strip()
+ if image and _run(['docker','image','inspect',image],timeout=30).returncode==0:return image
+ CACHE.mkdir(parents=True,mode=0o700,exist_ok=True); dockerfile=Path('/opt/linux-cmnd/current/deploy/php/Dockerfile.lab'); context=dockerfile.parent
+ if not dockerfile.is_file():raise ConfigError('packaged legacy PHP Dockerfile is missing')
+ partial=PHP_IID.with_suffix('.partial'); partial.unlink(missing_ok=True)
+ with PHP_BUILD_LOG.open('wb') as log:r=subprocess.run(['docker','build','-f',str(dockerfile),'--iidfile',str(partial),str(context)],stdout=log,stderr=subprocess.STDOUT,timeout=3600,check=False)
+ if r.returncode or not partial.is_file():raise ConfigError('legacy PHP image build failed; inspect /var/cache/linux-cmnd/bootstrap/php-build.log')
+ image=partial.read_text().strip()
+ if not re.fullmatch(r'sha256:[0-9a-f]{64}',image):raise ConfigError('unexpected PHP image identifier')
+ os.replace(partial,PHP_IID); PHP_IID.chmod(0o600); PHP_BUILD_LOG.chmod(0o600); return image
+def _install_baseline():
+ if not PACKAGE_ARCHIVE.is_file() or PACKAGE_ARCHIVE.is_symlink():raise ConfigError('matching rollback package is missing from cmnd-linux')
+ CACHE.mkdir(parents=True,mode=0o700,exist_ok=True)
+ if BASELINE.is_symlink():raise ConfigError('rollback package path is unsafe symlink')
+ if not BASELINE.exists():shutil.copyfile(PACKAGE_ARCHIVE,BASELINE); BASELINE.chmod(0o600)
+ validate_baseline()
+def plan(server_ip=None,database_mode='auto',apache_mode='auto',password_file=None,admin_user='root'):
+ inv=host_inventory(); base=build_plan(inv)
+ if not base.get('fresh_install_allowed'):raise ConfigError('existing active CMND runtime detected')
+ with tempfile.TemporaryDirectory(prefix='cmnd-apt-plan-') as d:
+ db,web,session,notes=_select_modes(inv,base,database_mode,apache_mode,password_file,admin_user,Path(d)); ports=_planned_ports(inv,base,db)
+ if db=='shared':ports['database']=session.port
+ return {'schema':1,'executed':False,'server_ip':choose_server_ip(server_ip),'database_mode':db,'apache_mode':web,'ports':ports,'notes':notes,'base_plan':base,'shared_database_qualified':db=='shared'}
+def activate(server_ip,database_mode,apache_mode,password_file,admin_user,execute,accept_legacy):
+ if not execute:return plan(server_ip,database_mode,apache_mode,password_file,admin_user)
+ _require_root()
+ if not accept_legacy:raise ConfigError('legacy PHP 5.6/MySQL 5.7 runtime acceptance is required')
+ if not VENDOR_ROOT.is_dir() or VENDOR_ROOT.is_symlink():raise ConfigError('verified Philips vendor package is not installed')
+ if not TOMCAT_ARCHIVE.is_file() or TOMCAT_ARCHIVE.is_symlink():raise ConfigError('pinned CMND Tomcat package is not installed')
+ inv=host_inventory(); base=build_plan(inv)
+ if not base.get('fresh_install_allowed'):raise ConfigError('existing active CMND runtime detected; use upgrade workflow')
+ os.umask(0o077)
+ with tempfile.TemporaryDirectory(prefix='cmnd-apt-admin-',dir='/run' if Path('/run').is_dir() else None) as d:
+ db,web,session,notes=_select_modes(inv,base,database_mode,apache_mode,password_file,admin_user,Path(d)); ports=_planned_ports(inv,base,db)
+ if db=='shared':ports['database']=session.port
+ address=choose_server_ip(server_ip); config=_install_config(render_config(address,ports)); cfg=load_config(config)
+ if db=='shared' and cfg.database_port!=session.port:raise ConfigError('preserved config DB port does not match shared server')
+ _ensure_docker(); _ensure_image(MYSQL_IMAGE) if db=='isolated' else None; php=_php_image(); _install_baseline()
+ result=deploy(CoexistInputs(config,VENDOR_ROOT,TOMCAT_ARCHIVE,php,Path('/usr/lib/jvm/java-17-openjdk-amd64'),db,web,session,True),execute=True,accept_legacy=True)
+ result['apt_activation']={'server_ip':address,'database_mode':db,'apache_mode':web,'notes':notes}; return result
+def main(argv=None):
+ p=argparse.ArgumentParser(prog='cmndctl apt-activate'); p.add_argument('--server-ip'); p.add_argument('--database-mode',choices=('auto','existing','isolated'),default='auto'); p.add_argument('--apache-mode',choices=('auto','host','standalone'),default='auto'); p.add_argument('--database-admin-user',default='root'); p.add_argument('--database-admin-password-file',type=Path); p.add_argument('--accept-legacy-runtime',action='store_true'); p.add_argument('--execute',action='store_true'); p.add_argument('--dry-run',action='store_true'); a=p.parse_args(argv)
+ try:r=activate(a.server_ip,a.database_mode,a.apache_mode,a.database_admin_password_file,a.database_admin_user,a.execute and not a.dry_run,a.accept_legacy_runtime)
+ except (ConfigError,RuntimeError,OSError,subprocess.SubprocessError) as e:print('cmndctl apt-activate: '+str(e),file=os.sys.stderr); return 2
+ print(json.dumps(r,indent=2,sort_keys=True)); return 0
From 84a70e0d110171a93239a5ac3ff6c8d3e5e2ddf5 Mon Sep 17 00:00:00 2001
From: Tommy Heggie <42516199+MusicCityTelecom@users.noreply.github.com>
Date: Sat, 12 Sep 2026 18:56:04 -0500
Subject: [PATCH 05/52] Add review-first Docker Compose bundle renderer
---
src/cmnd_linux/docker_bundle.py | 66 +++++++++++++++++++++++++++++++++
1 file changed, 66 insertions(+)
create mode 100644 src/cmnd_linux/docker_bundle.py
diff --git a/src/cmnd_linux/docker_bundle.py b/src/cmnd_linux/docker_bundle.py
new file mode 100644
index 00000000..084625bb
--- /dev/null
+++ b/src/cmnd_linux/docker_bundle.py
@@ -0,0 +1,66 @@
+"""Render a self-contained Docker Compose candidate from the same CMND staging code.
+
+This path is intentionally separate from the qualified native runtime. It builds
+a root-owned bundle for review and never starts containers automatically because
+Philips TV LAN/discovery behavior under Docker host networking is not yet qualified.
+"""
+from __future__ import annotations
+import argparse, hashlib, json, os, secrets, shutil, socket
+from pathlib import Path
+from urllib.parse import urlsplit
+from .application_stage import ApplicationInputs, VENDOR_INPUT_HASHES, _tomcat_members, stage_application
+from .artifacts import file_hash
+from .certificates import CertificateConfig, provision_certificates
+from .config import ConfigError, load_config
+from .native_deploy import SCHEMAS
+from .vendor_config import REQUIRED_SECRETS
+
+VENDOR_ROOT=Path('/usr/lib/cmnd/vendor/7.5.9')
+TOMCAT_ARCHIVE=Path('/usr/lib/cmnd/tomcat/apache-tomcat-9.0.121.tar.gz')
+DEFAULT_JAVA_IMAGE='eclipse-temurin:17-jre-jammy'
+MYSQL_IMAGE='mysql@sha256:4bc6bc963e6d8443453676cae56536f4b8156d78bae03c0145cbe47c2aad73bb'
+
+def _write(path,data,mode=0o600):
+ path.parent.mkdir(parents=True,exist_ok=True); raw=data.encode() if isinstance(data,str) else data
+ fd=os.open(path,os.O_CREAT|os.O_EXCL|os.O_WRONLY,mode)
+ with os.fdopen(fd,'wb') as h:h.write(raw)
+def _sql_quote(v):return "'"+v.replace('\\','\\\\').replace("'","''")+"'"
+def _bootstrap_sql(vendor,values,admin_password):
+ parts=[b'SET sql_mode="NO_ENGINE_SUBSTITUTION";\n']
+ for schema,user,folder,numbers in SCHEMAS:
+ pw=values[folder+'_db_password']; parts.append((f'CREATE DATABASE `{schema}` CHARACTER SET utf8 COLLATE utf8_general_ci;\nCREATE USER {_sql_quote(user)}@\'%\' IDENTIFIED BY {_sql_quote(pw)};\nGRANT ALL ON `{schema}`.* TO {_sql_quote(user)}@\'%\';\nUSE `{schema}`;\n').encode())
+ for n in numbers:parts += [(vendor/'SQLScripts'/folder/f'sql_{n}.sql').read_bytes(),b'\n']
+ digest=hashlib.md5(admin_password.encode()).hexdigest(); parts.append(("USE `cas`; DELETE FROM users; INSERT INTO users(username,password,role) VALUES"+f"('admin','{digest}','ADMIN');\n").encode()); return b''.join(parts)
+def _compose(java_image):
+ return f'''name: cmnd-linux\nservices:\n db:\n image: {MYSQL_IMAGE}\n network_mode: host\n restart: unless-stopped\n command: ["--bind-address=127.0.0.1", "--port=${{CMND_DB_PORT}}", "--event-scheduler=ON", "--local-infile=0", "--sql-mode=NO_ENGINE_SUBSTITUTION", "--lower-case-table-names=1"]\n environment:\n MYSQL_ROOT_PASSWORD_FILE: /run/secrets/mysql_root\n volumes:\n - ./state/mysql:/var/lib/mysql\n - ./secrets/mysql-root-password:/run/secrets/mysql_root:ro\n - ./mysql-init:/docker-entrypoint-initdb.d:ro\n php:\n build: ./php-image\n network_mode: host\n restart: unless-stopped\n read_only: true\n security_opt: ["no-new-privileges:true"]\n cap_drop: ["ALL"]\n tmpfs: ["/tmp:rw,nosuid,noexec,size=256m"]\n volumes:\n - ./payload/SmartCMS:/opt/cmnd/SmartCMS:ro\n - ./state/cms-files:/opt/cmnd/SmartCMS/sites/default/files\n - ./state/php-uploads:/var/lib/cmnd/php-uploads\n - ./state/cas-pgt:/var/lib/cmnd/cas-pgt\n - ./config/php-fpm.conf:/usr/local/etc/php-fpm.conf:ro\n - /etc/ssl/certs:/etc/ssl/certs:ro\n depends_on: [db]\n tomcat:\n image: {java_image}\n network_mode: host\n restart: unless-stopped\n working_dir: /opt/cmnd/tomcat\n command: ["/opt/cmnd/tomcat/bin/catalina.sh", "run"]\n environment:\n JAVA_HOME: /opt/java/openjdk\n CATALINA_OPTS: -Xms512m -Xmx4096m -Djava.awt.headless=true -Djavax.net.ssl.trustStore=/etc/cmnd/java-cacerts\n volumes:\n - ./payload/tomcat:/opt/cmnd/tomcat\n - ./payload/Philips:/opt/Philips\n - ./config/java-cacerts:/etc/cmnd/java-cacerts:ro\n - /sys/class/dmi/id:/sys/class/dmi/id:ro\n depends_on: [db]\n apache:\n build: ./apache-image\n network_mode: host\n restart: unless-stopped\n volumes:\n - ./payload/SmartCMS:/opt/cmnd/SmartCMS:ro\n - ./state/cms-files:/opt/cmnd/SmartCMS/sites/default/files\n - ./config/apache.conf:/etc/cmnd/apache.conf:ro\n - ./payload/tls:/etc/cmnd/tls:ro\n - ./state/log:/var/log/cmnd\n - ./state/run:/run/cmnd\n depends_on: [php]\n'''
+def render(config_path,output,*,java_image=DEFAULT_JAVA_IMAGE,execute=False):
+ config=load_config(config_path)
+ if not java_image or any(c.isspace() for c in java_image):raise ConfigError('invalid Java container image reference')
+ for p in (VENDOR_ROOT,TOMCAT_ARCHIVE):
+ if not p.exists() or p.is_symlink():raise ConfigError('required packaged Docker input missing: '+str(p))
+ for name,expected in VENDOR_INPUT_HASHES.items():
+ p=VENDOR_ROOT/name
+ if not p.is_file() or file_hash(p)!=expected:raise ConfigError('vendor package does not match pinned input: '+name)
+ _tomcat_members(TOMCAT_ARCHIVE)
+ report={'executed':execute,'output':str(output),'java_image':java_image,'mysql_image':MYSQL_IMAGE,'network_mode':'host','qualified':False,'warning':'Docker host-network TV discovery/control is not yet physical-TV qualified; review before starting containers.'}
+ if not execute:return report
+ if os.geteuid()!=0:raise ConfigError('docker bundle rendering requires root')
+ if output.exists() or output.is_symlink():raise ConfigError('Docker bundle output must not already exist')
+ output.mkdir(parents=True,mode=0o700); os.umask(0o077)
+ try:
+ values={k:secrets.token_hex(24) for k in (*REQUIRED_SECRETS,'tpvision_db_password')}; admin=secrets.token_hex(24); root=secrets.token_hex(32); certpass=output/'secrets/certificate-password'; _write(certpass,values['cert_ca_password'])
+ addresses=[config.bind] if config.bind!='0.0.0.0' else []; public=urlsplit(config.callback_base_url).hostname or config.bind
+ certs=provision_certificates(CertificateConfig(output/'certificates',public,addresses,socket.gethostname(),certpass,certpass)); stage=output/'stage'; stage_application(ApplicationInputs(VENDOR_ROOT,TOMCAT_ARCHIVE,certs),config,values,stage,execute=True,database_host='127.0.0.1'); shutil.move(str(stage/'payload'),str(output/'payload')); shutil.move(str(stage/'native-config'),str(output/'config')); shutil.rmtree(stage)
+ _write(output/'secrets/mysql-root-password',root); _write(output/'mysql-init/00-cmnd.sql',_bootstrap_sql(VENDOR_ROOT,values,admin)); _write(output/'initial-admin.json',json.dumps({'username':'admin','password':admin},indent=2)+'\n'); _write(output/'.env',f'CMND_DB_PORT={config.database_port}\n'); _write(output/'compose.yaml',_compose(java_image))
+ shutil.copytree(Path('/opt/linux-cmnd/current/deploy/php'),output/'php-image'); _write(output/'apache-image/Dockerfile','FROM ubuntu:24.04\nENV DEBIAN_FRONTEND=noninteractive\nRUN apt-get update && apt-get install -y --no-install-recommends apache2-bin media-types ca-certificates && rm -rf /var/lib/apt/lists/*\nCMD ["/usr/sbin/apache2","-f","/etc/cmnd/apache.conf","-DFOREGROUND"]\n')
+ for d in ('state/mysql','state/cms-files','state/php-uploads','state/cas-pgt','state/log','state/run'):(output/d).mkdir(parents=True,exist_ok=True)
+ _write(output/'README.txt','CMND Linux 0.8 Docker candidate\n\nReview compose.yaml and manifest.json before starting.\nStart: docker compose --env-file .env -f compose.yaml up -d --build\nStop: docker compose --env-file .env -f compose.yaml down\n\nHost-network discovery/control is not yet physical-TV qualified. Do not expose legacy services to the Internet.\n'); report['initial_admin_file']='initial-admin.json'; report['state']='rendered-not-started'; _write(output/'manifest.json',json.dumps(report,indent=2)+'\n'); return report
+ except Exception:
+ try:_write(output/'FAILED','Docker bundle rendering failed; preserve for diagnosis.\n')
+ except Exception:pass
+ raise
+def main(argv=None):
+ p=argparse.ArgumentParser(prog='cmndctl docker-render'); p.add_argument('--config',type=Path,default=Path('/etc/cmnd/cmnd.toml')); p.add_argument('--output',type=Path,required=True); p.add_argument('--java-image',default=DEFAULT_JAVA_IMAGE); p.add_argument('--execute',action='store_true'); a=p.parse_args(argv)
+ try:r=render(a.config,a.output,java_image=a.java_image,execute=a.execute)
+ except (ConfigError,RuntimeError,OSError) as e:print('cmndctl docker-render: '+str(e),file=os.sys.stderr); return 2
+ print(json.dumps(r,indent=2,sort_keys=True)); return 0
From 4bc3b95812fea4ae8705aedb4c6081392d515a1d Mon Sep 17 00:00:00 2001
From: Tommy Heggie <42516199+MusicCityTelecom@users.noreply.github.com>
Date: Sat, 12 Sep 2026 18:56:19 -0500
Subject: [PATCH 06/52] Package pinned Tomcat archive for APT
---
scripts/build_tomcat_deb.py | 43 +++++++++++++++++++++++++++++++++++++
1 file changed, 43 insertions(+)
create mode 100644 scripts/build_tomcat_deb.py
diff --git a/scripts/build_tomcat_deb.py b/scripts/build_tomcat_deb.py
new file mode 100644
index 00000000..72fcaa22
--- /dev/null
+++ b/scripts/build_tomcat_deb.py
@@ -0,0 +1,43 @@
+#!/usr/bin/env python3
+"""Build the pinned CMND Tomcat 9 archive package."""
+from __future__ import annotations
+from hashlib import sha256
+from io import BytesIO
+from pathlib import Path
+import gzip, os, shutil, sys, tarfile, tempfile
+ROOT=Path(__file__).resolve().parents[1]; sys.path.insert(0,str(ROOT/'src'))
+from cmnd_linux.application_stage import TOMCAT_SHA512,TOMCAT_VERSION,_tomcat_members
+PACKAGE='cmnd-tomcat9'; PACKAGE_VERSION=TOMCAT_VERSION+'-1'; INSTALL_DIR='usr/lib/cmnd/tomcat'; EPOCH=int(os.environ.get('SOURCE_DATE_EPOCH','1788835200'))
+def _info(name,size,mode):
+ x=tarfile.TarInfo(name); x.size=size; x.mode=mode; x.mtime=EPOCH; x.uid=x.gid=0; x.uname=x.gname='root'; return x
+def _dir(a,name):x=_info(name,0,0o755); x.type=tarfile.DIRTYPE; a.addfile(x)
+def _control(path):
+ data=f'Package: {PACKAGE}\nVersion: {PACKAGE_VERSION}\nSection: admin\nPriority: optional\nArchitecture: all\nMaintainer: Music City Telecom \nDescription: Pinned Apache Tomcat runtime archive for CMND Linux\n Exact Apache Tomcat {TOMCAT_VERSION} archive used by CMND for Linux.\n'.encode()
+ with path.open('wb') as raw,gzip.GzipFile(filename='',mode='wb',fileobj=raw,mtime=EPOCH) as gz,tarfile.open(fileobj=gz,mode='w') as a:a.addfile(_info('control',len(data),0o644),BytesIO(data))
+def _data(path,source):
+ note=f'Apache Tomcat {TOMCAT_VERSION}.\nExpected SHA-512: {TOMCAT_SHA512}\n'.encode()
+ with path.open('wb') as raw,gzip.GzipFile(filename='',mode='wb',fileobj=raw,mtime=EPOCH) as gz,tarfile.open(fileobj=gz,mode='w') as a:
+ for d in ('usr','usr/lib','usr/lib/cmnd',INSTALL_DIR,'usr/share','usr/share/doc',f'usr/share/doc/{PACKAGE}'):_dir(a,d)
+ with source.open('rb') as s:a.addfile(_info(f'{INSTALL_DIR}/apache-tomcat-{TOMCAT_VERSION}.tar.gz',source.stat().st_size,0o644),s)
+ a.addfile(_info(f'usr/share/doc/{PACKAGE}/ATTRIBUTION',len(note),0o644),BytesIO(note))
+def _ar(out,name,source):
+ size=source.stat().st_size; out.write((name+'/').encode().ljust(16,b' ')+str(EPOCH).encode().ljust(12,b' ')+b'0 0 100644 '+str(size).encode().ljust(10,b' ')+b'`\n')
+ with source.open('rb') as s:shutil.copyfileobj(s,out,1024*1024)
+ if size%2:out.write(b'\n')
+def build(archive):
+ archive=Path(archive)
+ if not archive.is_file() or archive.is_symlink():raise ValueError('Tomcat input must be a regular non-symlink file')
+ _tomcat_members(archive); output=ROOT/'dist'/f'{PACKAGE}_{PACKAGE_VERSION}_all.deb'; output.parent.mkdir(exist_ok=True)
+ with tempfile.TemporaryDirectory(prefix='cmnd-tomcat-deb-') as t:
+ r=Path(t); c=r/'control.tar.gz'; d=r/'data.tar.gz'; b=r/'debian-binary'; _control(c); _data(d,archive); b.write_bytes(b'2.0\n')
+ with output.open('wb') as o:o.write(b'!\n'); _ar(o,'debian-binary',b); _ar(o,'control.tar.gz',c); _ar(o,'data.tar.gz',d)
+ h=sha256();
+ with output.open('rb') as s:
+ for chunk in iter(lambda:s.read(1024*1024),b''):h.update(chunk)
+ Path(str(output)+'.sha256').write_text(f'{h.hexdigest()} {output.name}\n'); return output
+def main(argv=None):
+ import argparse; p=argparse.ArgumentParser(); p.add_argument('archive',type=Path); a=p.parse_args(argv)
+ try:print(build(a.archive))
+ except (OSError,ValueError) as e:print('build-tomcat-deb: '+str(e),file=sys.stderr); return 2
+ return 0
+if __name__=='__main__':raise SystemExit(main())
From 6008925bfd86c94e725218714d75eee1a52c3238 Mon Sep 17 00:00:00 2001
From: Tommy Heggie <42516199+MusicCityTelecom@users.noreply.github.com>
Date: Sat, 12 Sep 2026 18:56:27 -0500
Subject: [PATCH 07/52] Add cmnd-linux debconf prompts
---
packaging/cmnd-linux/templates | 36 ++++++++++++++++++++++++++++++++++
1 file changed, 36 insertions(+)
create mode 100644 packaging/cmnd-linux/templates
diff --git a/packaging/cmnd-linux/templates b/packaging/cmnd-linux/templates
new file mode 100644
index 00000000..ce679b8c
--- /dev/null
+++ b/packaging/cmnd-linux/templates
@@ -0,0 +1,36 @@
+Template: cmnd-linux/server-ip
+Type: string
+Default: auto
+Description: IPv4 address CMND should use:
+ Enter an IPv4 address already assigned to this server. Use "auto" to select the first active non-loopback IPv4 address.
+
+Template: cmnd-linux/database-mode
+Type: select
+Choices: auto, existing, isolated
+Default: auto
+Description: Database integration mode:
+ "auto" reuses an existing MySQL service only if it passes the CMND compatibility gate; otherwise it uses the isolated pinned MySQL runtime. "existing" refuses fallback. "isolated" never changes an existing database service.
+
+Template: cmnd-linux/database-admin-user
+Type: string
+Default: root
+Description: Existing database administrator user:
+ Used only when an existing database requires password authentication. The password is never stored in CMND persistent configuration.
+
+Template: cmnd-linux/database-admin-password
+Type: password
+Description: Existing database administrator password:
+ Leave blank to let auto mode use the isolated database fallback. This value is used only during package configuration and is cleared after the activation attempt.
+
+Template: cmnd-linux/apache-mode
+Type: select
+Choices: auto, host, standalone
+Default: auto
+Description: Apache integration mode:
+ "auto" attaches a CMND-owned fragment to an already-running Debian/Ubuntu Apache service, otherwise it runs an isolated CMND Apache process. Existing unrelated sites and listeners are preserved.
+
+Template: cmnd-linux/accept-legacy-runtime
+Type: boolean
+Default: false
+Description: Accept CMND's legacy PHP 5.6 / MySQL 5.7 compatibility runtime?
+ The original Philips CMND 7.5.9 application requires legacy compatibility components. They are isolated where practical and should not be exposed directly to the Internet.
From c466a365a8ccbb9e373916469ee6987f49df7ecb Mon Sep 17 00:00:00 2001
From: Tommy Heggie <42516199+MusicCityTelecom@users.noreply.github.com>
Date: Sat, 12 Sep 2026 18:57:51 -0500
Subject: [PATCH 08/52] Add environment-aware debconf configuration
---
packaging/cmnd-linux/config | 27 +++++++++++++++++++++++++++
1 file changed, 27 insertions(+)
create mode 100644 packaging/cmnd-linux/config
diff --git a/packaging/cmnd-linux/config b/packaging/cmnd-linux/config
new file mode 100644
index 00000000..8d215878
--- /dev/null
+++ b/packaging/cmnd-linux/config
@@ -0,0 +1,27 @@
+#!/bin/sh
+set -eu
+. /usr/share/debconf/confmodule
+
+db_input high cmnd-linux/server-ip || true
+db_input high cmnd-linux/database-mode || true
+db_input medium cmnd-linux/database-admin-user || true
+db_input medium cmnd-linux/apache-mode || true
+db_input high cmnd-linux/accept-legacy-runtime || true
+
+db_get cmnd-linux/database-mode
+case "$RET" in
+ auto|existing)
+ socket_ok=0
+ for client in mariadb mysql; do
+ if command -v "$client" >/dev/null 2>&1 && \
+ "$client" --protocol=socket -uroot --batch --skip-column-names -e 'SELECT 1' >/dev/null 2>&1; then
+ socket_ok=1
+ break
+ fi
+ done
+ [ "$socket_ok" -eq 1 ] || db_input medium cmnd-linux/database-admin-password || true
+ ;;
+esac
+
+db_go
+exit 0
From a8895eb55b1d4f36025553e981f91c1538bd06d6 Mon Sep 17 00:00:00 2001
From: Tommy Heggie <42516199+MusicCityTelecom@users.noreply.github.com>
Date: Sat, 12 Sep 2026 18:58:02 -0500
Subject: [PATCH 09/52] Activate CMND from APT package configuration
---
packaging/cmnd-linux/postinst | 42 +++++++++++++++++++++++++++++++++++
1 file changed, 42 insertions(+)
create mode 100644 packaging/cmnd-linux/postinst
diff --git a/packaging/cmnd-linux/postinst b/packaging/cmnd-linux/postinst
new file mode 100644
index 00000000..f06ee65a
--- /dev/null
+++ b/packaging/cmnd-linux/postinst
@@ -0,0 +1,42 @@
+#!/bin/sh
+set -eu
+. /usr/share/debconf/confmodule
+
+[ "${1:-}" = configure ] || exit 0
+
+db_get cmnd-linux/accept-legacy-runtime
+if [ "$RET" != true ]; then
+ echo "cmnd-linux installed but not activated: legacy runtime acceptance was not granted." >&2
+ echo "Run: sudo dpkg-reconfigure cmnd-linux" >&2
+ exit 0
+fi
+
+db_get cmnd-linux/server-ip; server_ip=$RET
+db_get cmnd-linux/database-mode; database_mode=$RET
+db_get cmnd-linux/database-admin-user; database_user=$RET
+db_get cmnd-linux/apache-mode; apache_mode=$RET
+db_get cmnd-linux/database-admin-password; database_password=$RET
+
+password_file=
+cleanup() {
+ if [ -n "$password_file" ]; then rm -f -- "$password_file"; fi
+ db_set cmnd-linux/database-admin-password '' || true
+}
+trap cleanup EXIT HUP INT TERM
+
+if [ -n "$database_password" ]; then
+ old_umask=$(umask)
+ umask 077
+ password_file=$(mktemp /run/cmnd-linux-dbadmin.XXXXXX)
+ printf '%s\n' "$database_password" > "$password_file"
+ chmod 0600 "$password_file"
+ umask "$old_umask"
+fi
+
+set -- apt-activate --database-mode "$database_mode" --apache-mode "$apache_mode" \
+ --database-admin-user "${database_user:-root}" --accept-legacy-runtime --execute
+if [ -n "$server_ip" ] && [ "$server_ip" != auto ]; then set -- "$@" --server-ip "$server_ip"; fi
+if [ -n "$password_file" ]; then set -- "$@" --database-admin-password-file "$password_file"; fi
+
+/usr/bin/cmndctl "$@"
+exit 0
From 536051b6016531160e623492bc49ada3bc268621 Mon Sep 17 00:00:00 2001
From: Tommy Heggie <42516199+MusicCityTelecom@users.noreply.github.com>
Date: Sat, 12 Sep 2026 18:58:09 -0500
Subject: [PATCH 10/52] Preserve data during cmnd-linux lifecycle operations
---
packaging/cmnd-linux/prerm | 14 ++++++++++++++
1 file changed, 14 insertions(+)
create mode 100644 packaging/cmnd-linux/prerm
diff --git a/packaging/cmnd-linux/prerm b/packaging/cmnd-linux/prerm
new file mode 100644
index 00000000..db680f4a
--- /dev/null
+++ b/packaging/cmnd-linux/prerm
@@ -0,0 +1,14 @@
+#!/bin/sh
+set -eu
+
+case "${1:-}" in
+ remove|deconfigure|upgrade)
+ if command -v systemctl >/dev/null 2>&1; then
+ systemctl stop cmnd-tomcat.service cmnd-apache.service cmnd-php.service cmnd-mysql.service cmnd-admin.service 2>/dev/null || true
+ fi
+ if [ -x /usr/bin/cmndctl ] && [ -f /etc/cmnd/deployment.json ]; then
+ /usr/bin/cmndctl apache-detach --execute 2>/dev/null || true
+ fi
+ ;;
+esac
+exit 0
From b65158982141160dd204fdb4e68d0e7d1b38f9db Mon Sep 17 00:00:00 2001
From: Tommy Heggie <42516199+MusicCityTelecom@users.noreply.github.com>
Date: Sat, 12 Sep 2026 18:58:15 -0500
Subject: [PATCH 11/52] Retain CMND data and configuration on package removal
---
packaging/cmnd-linux/postrm | 6 ++++++
1 file changed, 6 insertions(+)
create mode 100644 packaging/cmnd-linux/postrm
diff --git a/packaging/cmnd-linux/postrm b/packaging/cmnd-linux/postrm
new file mode 100644
index 00000000..58a1cd42
--- /dev/null
+++ b/packaging/cmnd-linux/postrm
@@ -0,0 +1,6 @@
+#!/bin/sh
+set -eu
+# Intentionally retain /etc/cmnd, /opt/cmnd, /var/lib/cmnd*, databases,
+# certificates, logs and customer content. Destructive purge requires a
+# separately reviewed operator command; package removal never deletes site data.
+exit 0
From c98974b242da9c4ec68607d949fe260fb92d5299 Mon Sep 17 00:00:00 2001
From: Tommy Heggie <42516199+MusicCityTelecom@users.noreply.github.com>
Date: Sat, 12 Sep 2026 18:58:32 -0500
Subject: [PATCH 12/52] Make cmnd-linux a complete APT entry package
---
scripts/build_meta_deb.py | 75 +++++++++++++++++++--------------------
1 file changed, 37 insertions(+), 38 deletions(-)
diff --git a/scripts/build_meta_deb.py b/scripts/build_meta_deb.py
index d0fb9f66..3597f1b3 100644
--- a/scripts/build_meta_deb.py
+++ b/scripts/build_meta_deb.py
@@ -1,55 +1,54 @@
#!/usr/bin/env python3
-"""Build the user-facing cmnd-linux APT meta package.
+"""Build the user-facing cmnd-linux APT package.
-The payload remains in linux-cmnd during 0.8 development so the known 0.7.1 file
-layout and package internals do not need a risky rename. Repository users install
-`cmnd-linux`; APT resolves the matching tooling plus verified vendor payload.
+The known tooling package remains `linux-cmnd`; this package adds the complete
+APT dependency graph, debconf activation scripts and a retained exact rollback
+copy of the matching tooling .deb.
"""
from __future__ import annotations
-
from hashlib import sha256
from pathlib import Path
-
try:
- # Normal direct execution: python scripts/build_meta_deb.py
- from build_deb import ROOT, ar_member, tar_blob
+ from build_deb import ROOT, ar_member, tar_blob, build as build_payload_deb
except ModuleNotFoundError:
- # Test/import execution from the repository root: scripts.build_meta_deb
- from scripts.build_deb import ROOT, ar_member, tar_blob
-
-VENDOR_PACKAGE_VERSION = '7.5.9-1'
+ from scripts.build_deb import ROOT, ar_member, tar_blob, build as build_payload_deb
+VENDOR_PACKAGE_VERSION='7.5.9-1'
+TOMCAT_PACKAGE_VERSION='9.0.121-1'
-def build() -> Path:
- version = (ROOT / 'VERSION').read_text().strip()
- control = f'''Package: cmnd-linux
+def build()->Path:
+ version=(ROOT/'VERSION').read_text().strip()
+ payload=ROOT/'dist'/f'linux-cmnd_{version}_amd64.deb'
+ if not payload.exists():payload=build_payload_deb()
+ if not payload.is_file() or payload.is_symlink():raise ValueError('matching linux-cmnd payload package is missing or unsafe')
+ control=f'''Package: cmnd-linux
Version: {version}
Section: admin
Priority: optional
Architecture: all
-Depends: linux-cmnd (= {version}), cmnd-vendor-759 (= {VENDOR_PACKAGE_VERSION})
+Pre-Depends: debconf (>= 1.5.0) | debconf-2.0
+Depends: linux-cmnd (= {version}), cmnd-vendor-759 (= {VENDOR_PACKAGE_VERSION}), cmnd-tomcat9 (= {TOMCAT_PACKAGE_VERSION}), python3 (>= 3.10), python3-tomli | python3 (>= 3.11), adduser, ca-certificates, openssl, iproute2, iptables, 7zip, openjdk-17-jre-headless, apache2-bin, media-types, docker.io | docker-ce
Maintainer: Music City Telecom
Description: Philips CMND for Linux installation entry point
- User-facing APT package for CMND for Linux. The version-matched linux-cmnd
- payload provides deployment/runtime integration and cmnd-vendor-759 provides
- the separately packaged hash-verified Philips CMND 7.5.9 application inputs.
+ Environment-aware APT installer for CMND for Linux. Reuses compatible existing
+ services where qualified, preserves unrelated applications and falls back to
+ isolated compatibility runtimes rather than changing unsafe host configuration.
'''.encode()
- notice = (
- 'cmnd-linux is the user-facing APT installation package.\n'
- f'It requires exact linux-cmnd {version} and cmnd-vendor-759 {VENDOR_PACKAGE_VERSION}.\n'
- 'Philips vendor applications retain their original ownership and attribution.\n'
- ).encode()
- deb = b'!\n' + ar_member('debian-binary', b'2.0\n')
- deb += ar_member('control.tar.gz', tar_blob([(None, 'control', 0o644, control)]))
- deb += ar_member('data.tar.gz', tar_blob([
- (None, 'usr/share/doc/cmnd-linux/README', 0o644, notice),
- ]))
- output = ROOT / 'dist' / f'cmnd-linux_{version}_all.deb'
- output.parent.mkdir(exist_ok=True)
- output.write_bytes(deb)
- Path(str(output) + '.sha256').write_text(f'{sha256(deb).hexdigest()} {output.name}\n')
- return output
-
-
-if __name__ == '__main__':
- print(build())
+ ctl=[
+ (None,'control',0o644,control),
+ (ROOT/'packaging/cmnd-linux/templates','templates',0o644,None),
+ (ROOT/'packaging/cmnd-linux/config','config',0o755,None),
+ (ROOT/'packaging/cmnd-linux/postinst','postinst',0o755,None),
+ (ROOT/'packaging/cmnd-linux/prerm','prerm',0o755,None),
+ (ROOT/'packaging/cmnd-linux/postrm','postrm',0o755,None),
+ ]
+ notice=(f'cmnd-linux {version} is the APT entry package.\n'
+ f'Requires linux-cmnd {version}, cmnd-vendor-759 {VENDOR_PACKAGE_VERSION}, and cmnd-tomcat9 {TOMCAT_PACKAGE_VERSION}.\n'
+ 'Philips/TP Vision components retain their original ownership and attribution.\n').encode()
+ data=[(None,'usr/share/doc/cmnd-linux/README',0o644,notice),
+ (payload,f'usr/lib/cmnd/packages/{payload.name}',0o600,None)]
+ deb=b'!\n'+ar_member('debian-binary',b'2.0\n')+ar_member('control.tar.gz',tar_blob(ctl))+ar_member('data.tar.gz',tar_blob(data))
+ out=ROOT/'dist'/f'cmnd-linux_{version}_all.deb'; out.parent.mkdir(exist_ok=True); out.write_bytes(deb)
+ Path(str(out)+'.sha256').write_text(f'{sha256(deb).hexdigest()} {out.name}\n'); return out
+
+if __name__=='__main__':print(build())
From 4a6f72a24d35554a23ceacea73b56a2b0e8ddd3b Mon Sep 17 00:00:00 2001
From: Tommy Heggie <42516199+MusicCityTelecom@users.noreply.github.com>
Date: Sat, 12 Sep 2026 18:58:50 -0500
Subject: [PATCH 13/52] Require complete CMND APT package set
---
scripts/build_apt_repository.py | 224 ++++++++------------------------
1 file changed, 53 insertions(+), 171 deletions(-)
diff --git a/scripts/build_apt_repository.py b/scripts/build_apt_repository.py
index 9a5fd34e..4310ca13 100644
--- a/scripts/build_apt_repository.py
+++ b/scripts/build_apt_repository.py
@@ -1,178 +1,60 @@
#!/usr/bin/env python3
"""Build a bounded signed Debian/Ubuntu repository from reviewed CMND .deb files."""
from __future__ import annotations
-
import argparse
-from datetime import datetime, timezone
-import gzip
-import json
-import os
+from datetime import datetime,timezone
+import gzip,json,os,re,shutil,subprocess
from pathlib import Path
-import re
-import shutil
-import subprocess
-
-
-REQUIRED_PACKAGES = {'linux-cmnd', 'cmnd-linux', 'cmnd-vendor-759'}
-ALLOWED_PACKAGES = set(REQUIRED_PACKAGES)
-ALLOWED_ARCHITECTURES = {'amd64', 'all'}
-SUITES = {'development', 'testing', 'stable'}
-VENDOR_VERSION = '7.5.9-1'
-
-
-def run(args, *, cwd: Path | None = None, input_text: str | None = None) -> str:
- result = subprocess.run(list(map(str, args)), cwd=cwd, input=input_text, text=True,
- capture_output=True, check=False)
- if result.returncode:
- raise RuntimeError(f'command failed: {args[0]}: {result.stderr.strip()[:1000]}')
- return result.stdout
-
-
-def require_command(name: str) -> str:
- path = shutil.which(name)
- if not path:
- raise RuntimeError(f'required repository build command is missing: {name}')
- return path
-
-
-def deb_field(path: Path, field: str) -> str:
- return run((require_command('dpkg-deb'), '-f', path, field)).strip()
-
-
-def validate_deb(path: Path) -> dict[str, str | int]:
- if not path.is_file() or path.is_symlink():
- raise ValueError(f'Debian package must be a regular non-symlink file: {path}')
- if path.stat().st_size <= 0 or path.stat().st_size > 4 * 1024**3:
- raise ValueError(f'Debian package size outside repository bound: {path.name}')
- package = deb_field(path, 'Package')
- version = deb_field(path, 'Version')
- architecture = deb_field(path, 'Architecture')
- if package not in ALLOWED_PACKAGES:
- raise ValueError(f'unexpected package for CMND repository: {package}')
- if architecture not in ALLOWED_ARCHITECTURES:
- raise ValueError(f'unexpected architecture for {package}: {architecture}')
- if not re.fullmatch(r'[0-9][A-Za-z0-9.+:~_-]*', version):
- raise ValueError(f'invalid Debian version: {version}')
- return {'package': package, 'version': version, 'architecture': architecture, 'size': path.stat().st_size}
-
-
-def release_date() -> str:
- epoch = int(os.environ.get('SOURCE_DATE_EPOCH', '0'))
- when = datetime.fromtimestamp(epoch, timezone.utc) if epoch else datetime.now(timezone.utc)
- return when.strftime('%a, %d %b %Y %H:%M:%S +0000')
-
-
-def gzip_file(source: Path, destination: Path) -> None:
- epoch = int(os.environ.get('SOURCE_DATE_EPOCH', '0'))
- with source.open('rb') as inp, destination.open('wb') as raw:
- with gzip.GzipFile(filename='', mode='wb', fileobj=raw, mtime=epoch or 0) as zipped:
- shutil.copyfileobj(inp, zipped)
-
-def build_repository(output: Path, debs: list[Path], *, codename: str, suite: str,
- signing_key: str | None, allow_unsigned_development: bool,
- execute: bool = False) -> dict:
- if not re.fullmatch(r'[a-z0-9][a-z0-9.-]{1,31}', codename):
- raise ValueError('invalid repository codename')
- if suite not in SUITES:
- raise ValueError('invalid repository suite')
- if not debs:
- raise ValueError('at least one .deb is required')
- metadata = [validate_deb(path) for path in debs]
- by_name = {str(item['package']): item for item in metadata}
- if set(by_name) != REQUIRED_PACKAGES or len(metadata) != len(REQUIRED_PACKAGES):
- raise ValueError('repository build requires exactly linux-cmnd, cmnd-linux and cmnd-vendor-759 packages')
- tooling_version = str(by_name['linux-cmnd']['version'])
- if str(by_name['cmnd-linux']['version']) != tooling_version:
- raise ValueError('cmnd-linux and linux-cmnd repository packages must use the same version')
- if str(by_name['cmnd-vendor-759']['version']) != VENDOR_VERSION:
- raise ValueError(f'cmnd-vendor-759 must use the reviewed vendor package version {VENDOR_VERSION}')
- if not signing_key and not (suite == 'development' and allow_unsigned_development):
- raise ValueError('signed repository metadata is required; unsigned output is allowed only for explicit development builds')
- if output.exists() and any(output.iterdir()):
- raise ValueError('repository output directory must be absent or empty')
-
- plan = {
- 'executed': execute,
- 'output': str(output),
- 'codename': codename,
- 'suite': suite,
- 'tooling_version': tooling_version,
- 'vendor_version': VENDOR_VERSION,
- 'packages': metadata,
- 'signed': bool(signing_key),
- }
- if not execute:
- return plan
-
- apt_ftparchive = require_command('apt-ftparchive')
- if signing_key:
- require_command('gpg')
- output.mkdir(parents=True, exist_ok=True)
- for source, info in zip(debs, metadata):
- package = str(info['package'])
- initial = package[0]
- target = output / 'pool' / 'main' / initial / package / source.name
- target.parent.mkdir(parents=True, exist_ok=True)
- shutil.copyfile(source, target)
- target.chmod(0o644)
-
- binary = output / 'dists' / codename / 'main' / 'binary-amd64'
- binary.mkdir(parents=True)
- packages = binary / 'Packages'
- packages.write_text(run((apt_ftparchive, 'packages', 'pool/main'), cwd=output), encoding='utf-8')
- gzip_file(packages, binary / 'Packages.gz')
-
- dist = output / 'dists' / codename
- body = run((apt_ftparchive, 'release', f'dists/{codename}'), cwd=output)
- header = (
- 'Origin: Music City Telecom\n'
- 'Label: CMND Linux\n'
- f'Suite: {suite}\n'
- f'Codename: {codename}\n'
- 'Architectures: amd64\n'
- 'Components: main\n'
- 'Description: CMND for Linux packages\n'
- f'Date: {release_date()}\n'
- )
- release = dist / 'Release'
- release.write_text(header + body, encoding='utf-8')
-
- if signing_key:
- run(('gpg', '--batch', '--yes', '--local-user', signing_key, '--digest-algo', 'SHA256',
- '--clearsign', '--output', dist / 'InRelease', release))
- run(('gpg', '--batch', '--yes', '--local-user', signing_key, '--digest-algo', 'SHA256',
- '--armor', '--detach-sign', '--output', dist / 'Release.gpg', release))
-
- plan['files'] = sorted(str(path.relative_to(output)) for path in output.rglob('*') if path.is_file())
- return plan
-
-
-def parser() -> argparse.ArgumentParser:
- p = argparse.ArgumentParser()
- p.add_argument('--output', required=True, type=Path)
- p.add_argument('--deb', action='append', required=True, type=Path)
- p.add_argument('--codename', default='noble')
- p.add_argument('--suite', choices=sorted(SUITES), default='development')
- p.add_argument('--signing-key', help='GPG key fingerprint/key ID; private key material is never read from the repository')
- p.add_argument('--allow-unsigned-development', action='store_true')
- p.add_argument('--execute', action='store_true')
+REQUIRED_PACKAGES={'linux-cmnd','cmnd-linux','cmnd-vendor-759','cmnd-tomcat9'}
+ALLOWED_ARCHITECTURES={'amd64','all'}; SUITES={'development','testing','stable'}
+VENDOR_VERSION='7.5.9-1'; TOMCAT_VERSION='9.0.121-1'
+def run(args,*,cwd=None,input_text=None):
+ r=subprocess.run(list(map(str,args)),cwd=cwd,input=input_text,text=True,capture_output=True,check=False)
+ if r.returncode:raise RuntimeError(f'command failed: {args[0]}: {r.stderr.strip()[:1000]}')
+ return r.stdout
+def require(name):
+ p=shutil.which(name)
+ if not p:raise RuntimeError('required repository build command is missing: '+name)
return p
-
-
-def main(argv=None) -> int:
- args = parser().parse_args(argv)
- try:
- result = build_repository(args.output, args.deb, codename=args.codename, suite=args.suite,
- signing_key=args.signing_key,
- allow_unsigned_development=args.allow_unsigned_development,
- execute=args.execute)
- except (OSError, RuntimeError, ValueError) as exc:
- print(f'build-apt-repository: {exc}', file=os.sys.stderr)
- return 2
- print(json.dumps(result, indent=2, sort_keys=True))
- return 0
-
-
-if __name__ == '__main__':
- raise SystemExit(main())
+def field(path,name):return run((require('dpkg-deb'),'-f',path,name)).strip()
+def validate(path):
+ if not path.is_file() or path.is_symlink():raise ValueError('Debian package must be a regular non-symlink file: '+str(path))
+ if not 0
Date: Sat, 12 Sep 2026 18:59:18 -0500
Subject: [PATCH 14/52] Build complete 0.8 APT release assets
---
scripts/build_release.py | 117 ++++++++++-----------------------------
1 file changed, 29 insertions(+), 88 deletions(-)
diff --git a/scripts/build_release.py b/scripts/build_release.py
index 9deb1a34..a8748f91 100644
--- a/scripts/build_release.py
+++ b/scripts/build_release.py
@@ -1,94 +1,35 @@
-"""Build tooling plus the explicitly authorized, pinned original vendor bundle."""
-import argparse
-import hashlib
-import json
+"""Build tooling plus the authorized vendor bundle and pinned runtime packages."""
+import argparse,hashlib,json,shutil,subprocess
from pathlib import Path
-import shutil
-import subprocess
-
-from build_deb import build as build_payload_deb, ROOT
+from build_deb import build as build_payload_deb,ROOT
from build_meta_deb import build as build_meta_deb
from build_vendor_deb import build as build_vendor_deb
-from vendor_bundle import verify as verify_vendor_bundle, NAME as VENDOR_BUNDLE_NAME
-
-RELEASE_PATHS = ['src', 'scripts', 'deploy', 'config', 'packaging', 'tests', 'docs',
- 'VERSION', 'pyproject.toml', 'README.md', 'LICENSE', 'CHANGELOG.md',
- 'AGENTS.md', '.gitattributes', '.gitignore']
-
-
-def stream_digest(stream, algorithm='sha256'):
- digest = hashlib.new(algorithm)
- for chunk in iter(lambda: stream.read(1024 * 1024), b''):
- digest.update(chunk)
- return digest.hexdigest()
-
-
+from build_tomcat_deb import build as build_tomcat_deb
+from vendor_bundle import verify as verify_vendor_bundle,NAME as VENDOR_BUNDLE_NAME
+RELEASE_PATHS=['src','scripts','deploy','config','packaging','tests','docs','.github','VERSION','pyproject.toml','README.md','LICENSE','CHANGELOG.md','AGENTS.md','.gitattributes','.gitignore']
def validate_sources():
- # Build inputs must match the exact commit exported as the release source.
- # Include ignored files: a local ignored file must not slip into the package.
- inputs = RELEASE_PATHS
- subprocess.run(['git', 'diff', '--exit-code', 'HEAD', '--', *inputs], cwd=ROOT, check=True)
- untracked = subprocess.check_output(
- ['git', 'ls-files', '--others', '--', *inputs], cwd=ROOT, text=True).splitlines()
- untracked = [name for name in untracked
- if '__pycache__' not in Path(name).parts and Path(name).suffix != '.pyc']
- if untracked:
- raise SystemExit('Uncommitted release inputs detected; commit or remove them before building')
- tracked = subprocess.check_output(['git', 'ls-files'], cwd=ROOT, text=True).splitlines()
- forbidden = {'.war', '.jar', '.exe', '.zip', '.sql', '.key', '.crt', '.pem', '.p12', '.pfx', '.pcap', '.pcapng', '.log'}
- if any(Path(name).suffix.lower() in forbidden or name.startswith(('.lab/', '.private-staging/')) for name in tracked):
- raise SystemExit('Private/vendor input detected in tracked release sources')
-
-
+ subprocess.run(['git','diff','--exit-code','HEAD','--',*RELEASE_PATHS],cwd=ROOT,check=True)
+ untracked=subprocess.check_output(['git','ls-files','--others','--',*RELEASE_PATHS],cwd=ROOT,text=True).splitlines(); untracked=[n for n in untracked if '__pycache__' not in Path(n).parts and Path(n).suffix!='.pyc']
+ if untracked:raise SystemExit('Uncommitted release inputs detected; commit or remove them before building')
+ tracked=subprocess.check_output(['git','ls-files'],cwd=ROOT,text=True).splitlines(); forbidden={'.war','.jar','.exe','.zip','.sql','.key','.crt','.pem','.p12','.pfx','.pcap','.pcapng','.log'}
+ if any(Path(n).suffix.lower() in forbidden or n.startswith(('.lab/','.private-staging/')) for n in tracked):raise SystemExit('Private/vendor input detected in tracked release sources')
+def digest(path):
+ h=hashlib.sha256()
+ with path.open('rb') as s:
+ for chunk in iter(lambda:s.read(1024*1024),b''):h.update(chunk)
+ return h.hexdigest()
def main():
- parser = argparse.ArgumentParser(description=__doc__)
- parser.add_argument('--vendor-bundle', type=Path, required=True,
- help='authorized, exact original-input ZIP; never a live installation backup')
- args = parser.parse_args()
- vendor_metadata = verify_vendor_bundle(args.vendor_bundle)
- validate_sources()
- package = build_payload_deb()
- meta_package = build_meta_deb()
- vendor_package = build_vendor_deb(args.vendor_bundle)
- version = (ROOT / 'VERSION').read_text().strip()
- destination = ROOT / 'dist'
- installer = destination / 'install.sh'
- installer.write_bytes((ROOT / 'scripts/install-native.sh').read_bytes().replace(b'\r\n', b'\n'))
- manifest = destination / 'linux-cmnd-update.json'
- manifest.write_text(json.dumps({'schema': 1, 'version': version, 'minimum_version': '0.4.0',
- 'scope': 'tooling-only', 'vendor': '7.5.9', 'database_migration': False,
- 'vendor_payload_changed': False}, indent=2) + '\n', encoding='utf-8')
- source = destination / f'linux-cmnd-{version}-source.tar.gz'
- subprocess.run(['git', 'archive', '--format=tar.gz', f'--prefix=linux-cmnd-{version}/',
- '-o', str(source), 'HEAD', '--', *RELEASE_PATHS], cwd=ROOT, check=True)
- guide = destination / 'EVALUATION-GUIDE.md'
- shutil.copyfile(ROOT / 'docs/EVALUATION-GUIDE.md', guide)
- configuration = destination / 'cmnd.example.toml'
- shutil.copyfile(ROOT / 'config/cmnd.install.toml', configuration)
- bootstrap = destination / 'bootstrap.py'
- bootstrap.write_bytes((ROOT / 'scripts/bootstrap.py').read_bytes().replace(b'\r\n', b'\n'))
- artifacts = [package, meta_package, vendor_package, installer, manifest, source, guide, configuration, bootstrap]
- bundled = destination / VENDOR_BUNDLE_NAME
+ p=argparse.ArgumentParser(description=__doc__); p.add_argument('--vendor-bundle',type=Path,required=True); p.add_argument('--tomcat-archive',type=Path,required=True); a=p.parse_args(); vendor_meta=verify_vendor_bundle(a.vendor_bundle); validate_sources()
+ payload=build_payload_deb(); vendor=build_vendor_deb(a.vendor_bundle); tomcat=build_tomcat_deb(a.tomcat_archive); meta=build_meta_deb(); version=(ROOT/'VERSION').read_text().strip(); dest=ROOT/'dist'
+ installer=dest/'install.sh'; installer.write_bytes((ROOT/'scripts/install-native.sh').read_bytes().replace(b'\r\n',b'\n'))
+ manifest=dest/'linux-cmnd-update.json'; manifest.write_text(json.dumps({'schema':1,'version':version,'minimum_version':'0.4.0','scope':'tooling-only','vendor':'7.5.9','database_migration':False,'vendor_payload_changed':False},indent=2)+'\n')
+ source=dest/f'linux-cmnd-{version}-source.tar.gz'; subprocess.run(['git','archive','--format=tar.gz',f'--prefix=linux-cmnd-{version}/','-o',str(source),'HEAD','--',*RELEASE_PATHS],cwd=ROOT,check=True)
+ guide=dest/'EVALUATION-GUIDE.md'; shutil.copyfile(ROOT/'docs/EVALUATION-GUIDE.md',guide); cfg=dest/'cmnd.example.toml'; shutil.copyfile(ROOT/'config/cmnd.install.toml',cfg); bootstrap=dest/'bootstrap.py'; bootstrap.write_bytes((ROOT/'scripts/bootstrap.py').read_bytes().replace(b'\r\n',b'\n'))
+ artifacts=[payload,meta,vendor,tomcat,installer,manifest,source,guide,cfg,bootstrap]; bundled=dest/VENDOR_BUNDLE_NAME
if bundled.exists():
- if verify_vendor_bundle(bundled) != vendor_metadata:
- raise SystemExit('Existing release vendor bundle differs; refusing overwrite')
- else:
- shutil.copyfile(args.vendor_bundle, bundled)
- if verify_vendor_bundle(bundled) != vendor_metadata:
- raise SystemExit('Vendor bundle changed while copying')
- vendor_manifest = destination / 'vendor-bundle.json'
- vendor_manifest.write_text(json.dumps(vendor_metadata, indent=2) + '\n', encoding='utf-8')
- artifacts += [bundled, vendor_manifest]
- checksums = destination / 'SHA256SUMS'
- lines = []
- for path in artifacts:
- with path.open('rb') as stream:
- lines.append(f'{stream_digest(stream)} {path.name}\n')
- checksums.write_text(''.join(lines), encoding='ascii')
- print(json.dumps({'version': version, 'assets': [str(path) for path in artifacts + [checksums]],
- 'apt_packages': [package.name, meta_package.name, vendor_package.name],
- 'vendor_payload_included': True, 'vendor_bundle': vendor_metadata}, indent=2))
-
-
-if __name__ == '__main__':
- main()
\ No newline at end of file
+ if verify_vendor_bundle(bundled)!=vendor_meta:raise SystemExit('Existing release vendor bundle differs; refusing overwrite')
+ else:shutil.copyfile(a.vendor_bundle,bundled)
+ if verify_vendor_bundle(bundled)!=vendor_meta:raise SystemExit('Vendor bundle changed while copying')
+ vm=dest/'vendor-bundle.json'; vm.write_text(json.dumps(vendor_meta,indent=2)+'\n'); artifacts += [bundled,vm]; checks=dest/'SHA256SUMS'; checks.write_text(''.join(f'{digest(x)} {x.name}\n' for x in artifacts),encoding='ascii')
+ print(json.dumps({'version':version,'assets':[str(x) for x in artifacts+[checks]],'apt_packages':[payload.name,meta.name,vendor.name,tomcat.name],'vendor_payload_included':True,'vendor_bundle':vendor_meta},indent=2))
+if __name__=='__main__':main()
From c031ebde68d47d8aef5567e004463a6dad294f61 Mon Sep 17 00:00:00 2001
From: Tommy Heggie <42516199+MusicCityTelecom@users.noreply.github.com>
Date: Sat, 12 Sep 2026 18:59:34 -0500
Subject: [PATCH 15/52] Expose 0.8 APT and Docker commands
---
src/cmnd_linux/__main__.py | 37 +++++++++++++++++++++++++------------
1 file changed, 25 insertions(+), 12 deletions(-)
diff --git a/src/cmnd_linux/__main__.py b/src/cmnd_linux/__main__.py
index 9ebe6aef..2a33114d 100644
--- a/src/cmnd_linux/__main__.py
+++ b/src/cmnd_linux/__main__.py
@@ -1,18 +1,31 @@
import sys
+args = sys.argv[1:]
-# Keep the first 0.8.0 coexistence probes isolated from the qualified 0.7.1 CLI
-# dispatcher. The Debian cmndctl wrapper invokes `python3 -m cmnd_linux`, so
-# these read-only commands do not change existing command behavior.
-if sys.argv[1:] == ['environment']:
- from .environment import main as environment_main
-
- raise SystemExit(environment_main())
-if sys.argv[1:] == ['plan-install']:
- from .install_plan import main as plan_main
-
- raise SystemExit(plan_main())
+if args == ['environment']:
+ from .environment import main as command
+ raise SystemExit(command())
+if args == ['plan-install']:
+ from .install_plan import main as command
+ raise SystemExit(command())
+if args and args[0] == 'apt-activate':
+ from .apt_installer import main as command
+ raise SystemExit(command(args[1:]))
+if args == ['shared-wait-database']:
+ from .shared_database import wait_shared_database
+ wait_shared_database()
+ raise SystemExit(0)
+if args and args[0] == 'apache-detach':
+ from .apache_integration import detach
+ import json
+ execute = args[1:] == ['--execute']
+ if args[1:] not in ([], ['--execute']):
+ raise SystemExit('Usage: cmndctl apache-detach [--execute]')
+ print(json.dumps(detach(execute=execute), indent=2, sort_keys=True))
+ raise SystemExit(0)
+if args and args[0] == 'docker-render':
+ from .docker_bundle import main as command
+ raise SystemExit(command(args[1:]))
from .cli import main
-
raise SystemExit(main())
From dc00c126614147608da168bb82adb79465af3c74 Mon Sep 17 00:00:00 2001
From: Tommy Heggie <42516199+MusicCityTelecom@users.noreply.github.com>
Date: Tue, 22 Sep 2026 20:40:44 -0500
Subject: [PATCH 16/52] Distinguish CMND tooling from active runtime
---
src/cmnd_linux/environment.py | 17 +++++++++++++++--
1 file changed, 15 insertions(+), 2 deletions(-)
diff --git a/src/cmnd_linux/environment.py b/src/cmnd_linux/environment.py
index 405a39b1..225deb08 100644
--- a/src/cmnd_linux/environment.py
+++ b/src/cmnd_linux/environment.py
@@ -268,10 +268,23 @@ def runtime_inventory() -> dict[str, object]:
def cmnd_inventory() -> dict[str, object]:
- paths = ('/opt/linux-cmnd', '/opt/cmnd', '/etc/cmnd', '/var/lib/cmnd-deployment')
+ # Installing the linux-cmnd tooling package itself creates /opt/linux-cmnd,
+ # /opt/cmnd/releases and /etc/cmnd. Those paths are NOT proof that the
+ # Philips application runtime has been activated.
+ tooling_paths = ('/opt/linux-cmnd', '/opt/cmnd', '/etc/cmnd')
+ runtime_paths = (
+ '/var/lib/cmnd-deployment',
+ '/opt/cmnd/tomcat',
+ '/opt/cmnd/SmartCMS',
+ '/opt/Philips',
+ '/etc/cmnd/deployment.json',
+ )
+ runtime = {path: Path(path).exists() for path in runtime_paths}
return {
'package_version': package_version('linux-cmnd'),
- 'paths': {path: Path(path).exists() for path in paths},
+ 'paths': {path: Path(path).exists() for path in tooling_paths},
+ 'runtime_paths': runtime,
+ 'active_runtime_detected': any(runtime.values()),
'services': {name: service_state(name) for name in (
'cmnd-egress.service', 'cmnd-mysql.service', 'cmnd-php.service',
'cmnd-apache.service', 'cmnd-tomcat.service',
From 82d4ba4bb48a839b6843b5f985eff33e2cc11629 Mon Sep 17 00:00:00 2001
From: Tommy Heggie <42516199+MusicCityTelecom@users.noreply.github.com>
Date: Tue, 22 Sep 2026 20:40:47 -0500
Subject: [PATCH 17/52] Allow first activation after tooling package install
---
src/cmnd_linux/install_plan.py | 6 ++++--
1 file changed, 4 insertions(+), 2 deletions(-)
diff --git a/src/cmnd_linux/install_plan.py b/src/cmnd_linux/install_plan.py
index 04b3891e..b3c5ffe4 100644
--- a/src/cmnd_linux/install_plan.py
+++ b/src/cmnd_linux/install_plan.py
@@ -172,8 +172,10 @@ def build_plan(inventory: dict) -> dict:
occupied = _occupied(inventory)
reserved: set[int] = set()
cmnd = inventory.get('cmnd', {})
- existing_paths = cmnd.get('paths', {}) if isinstance(cmnd, dict) else {}
- existing_cmnd = bool(cmnd.get('package_version')) or any(bool(value) for value in existing_paths.values())
+ runtime_paths = cmnd.get('runtime_paths', {}) if isinstance(cmnd, dict) else {}
+ existing_cmnd = bool(cmnd.get('active_runtime_detected')) or any(
+ bool(value) for value in runtime_paths.values()
+ )
database = _database_plan(inventory, occupied, reserved)
tomcat = _tomcat_plan(inventory, occupied, reserved)
From 2e4f134936aaf6879431f4a987e62d0d724aac9f Mon Sep 17 00:00:00 2001
From: Tommy Heggie <42516199+MusicCityTelecom@users.noreply.github.com>
Date: Tue, 22 Sep 2026 20:40:49 -0500
Subject: [PATCH 18/52] Regress tooling-only first-install detection
---
tests/test_install_plan.py | 28 ++++++++++++++++++++++++++--
1 file changed, 26 insertions(+), 2 deletions(-)
diff --git a/tests/test_install_plan.py b/tests/test_install_plan.py
index 8e0daf3f..c57924c0 100644
--- a/tests/test_install_plan.py
+++ b/tests/test_install_plan.py
@@ -18,7 +18,7 @@ def base_inventory():
},
'docker': {'docker': {'present': False}, 'daemon_access': False, 'running_containers': []},
'runtime': {'java': {'present': False, 'version': None, 'path': None}},
- 'cmnd': {'package_version': None, 'paths': {}},
+ 'cmnd': {'package_version': None, 'paths': {}, 'runtime_paths': {}, 'active_runtime_detected': False},
}
@@ -69,12 +69,36 @@ def test_existing_database_without_socket_auth_requests_transient_admin_credenti
def test_existing_cmnd_blocks_fresh_install(self):
inventory = base_inventory()
- inventory['cmnd'] = {'package_version': '0.7.1', 'paths': {'/opt/cmnd': True}}
+ inventory['cmnd'] = {
+ 'package_version': '0.7.1',
+ 'paths': {'/opt/cmnd': True},
+ 'runtime_paths': {'/var/lib/cmnd-deployment': True},
+ 'active_runtime_detected': True,
+ }
plan = build_plan(inventory)
self.assertFalse(plan['fresh_install_allowed'])
self.assertTrue(plan['existing_cmnd_detected'])
self.assertTrue(any('Existing CMND state' in warning for warning in plan['warnings']))
+
+ def test_tooling_package_alone_does_not_block_first_activation(self):
+ inventory = base_inventory()
+ inventory['cmnd'] = {
+ 'package_version': '0.8.0',
+ 'paths': {'/opt/linux-cmnd': True, '/opt/cmnd': True, '/etc/cmnd': True},
+ 'runtime_paths': {
+ '/var/lib/cmnd-deployment': False,
+ '/opt/cmnd/tomcat': False,
+ '/opt/cmnd/SmartCMS': False,
+ '/opt/Philips': False,
+ '/etc/cmnd/deployment.json': False,
+ },
+ 'active_runtime_detected': False,
+ }
+ plan = build_plan(inventory)
+ self.assertTrue(plan['fresh_install_allowed'])
+ self.assertFalse(plan['existing_cmnd_detected'])
+
def test_unrelated_nginx_is_preserved(self):
inventory = base_inventory()
inventory['web']['nginx'] = {'present': True, 'path': '/usr/sbin/nginx'}
From 4b69dce7f041711fec7bcdaacf39c1cb881dd18f Mon Sep 17 00:00:00 2001
From: Tommy Heggie <42516199+MusicCityTelecom@users.noreply.github.com>
Date: Tue, 22 Sep 2026 20:41:22 -0500
Subject: [PATCH 19/52] Fix coexistence runtime file permissions
---
src/cmnd_linux/coexist_deploy.py | 33 ++++++++++++++++++++++++++++++--
1 file changed, 31 insertions(+), 2 deletions(-)
diff --git a/src/cmnd_linux/coexist_deploy.py b/src/cmnd_linux/coexist_deploy.py
index 2dc67c7f..56f6b086 100644
--- a/src/cmnd_linux/coexist_deploy.py
+++ b/src/cmnd_linux/coexist_deploy.py
@@ -147,14 +147,43 @@ def deploy(i:CoexistInputs,*,execute=False,accept_legacy=False):
ETC.mkdir(parents=True,exist_ok=True); shutil.copytree(payload/'tls',ETC/'tls')
for name in ('apache.conf','php-fpm.conf','configure-cms.php'):write_new(ETC/name,(native/name).read_bytes(),0o640); os.chown(ETC/name,0,webgid)
for p in (ETC/'tls').iterdir():p.chmod(0o600)
- write_new(ETC/'native-tomcat.env',(native/'computername.env').read_text()+'\nCATALINA_OPTS="-Xms512m -Xmx4096m -Djava.awt.headless=true -Djavax.net.ssl.trustStore=/etc/cmnd/java-cacerts"\n',0o640); shutil.copyfile(i.java_home/'lib/security/cacerts',ETC/'java-cacerts'); write_new(STATE/'truststore-password','changeit'); run(i.java_home/'bin/keytool','-importcert','-noprompt','-alias','linux-cmnd','-file',certs.ca_pem,'-keystore',ETC/'java-cacerts','-storepass:file',STATE/'truststore-password'); write_new(Path('/usr/local/share/ca-certificates/linux-cmnd.crt'),certs.ca_pem.read_bytes(),0o644); run('update-ca-certificates')
+ write_new(ETC/'native-tomcat.env',(native/'computername.env').read_text()+'\nCATALINA_OPTS="-Xms512m -Xmx4096m -Djava.awt.headless=true -Djavax.net.ssl.trustStore=/etc/cmnd/java-cacerts"\n',0o640)
+ os.chown(ETC/'native-tomcat.env',0,java.pw_gid)
+ shutil.copyfile(i.java_home/'lib/security/cacerts',ETC/'java-cacerts')
+ write_new(STATE/'truststore-password','changeit')
+ run(i.java_home/'bin/keytool','-importcert','-noprompt','-alias','linux-cmnd','-file',certs.ca_pem,'-keystore',ETC/'java-cacerts','-storepass:file',STATE/'truststore-password')
+ os.chown(ETC/'java-cacerts',0,java.pw_gid)
+ (ETC/'java-cacerts').chmod(0o640)
+ write_new(Path('/usr/local/share/ca-certificates/linux-cmnd.crt'),certs.ca_pem.read_bytes(),0o644)
+ run('update-ca-certificates')
endpoints={('127.0.0.1',c.database_port)}|{(a,p) for a in ips for p in (c.tomcat_http,c.tomcat_https,c.apache_http,c.apache_https)}; policy=EgressPolicy('CMND_NATIVE',(java.pw_uid,cms.pw_uid),tuple(sorted(endpoints))); write_new(ETC/'egress.json',json.dumps({'chain':policy.chain,'uids':policy.uids,'tcp_endpoints':policy.tcp_endpoints})); write_new(ETC/'egress.py',Path(__file__).with_name('egress.py').read_bytes(),0o644)
units=_units(i.java_home,i.database_mode,i.apache_mode,i.apt_managed)
for name,text in units.items():write_new(Path('/etc/systemd/system')/name,text,0o644)
run('systemctl','daemon-reload'); run('systemctl','enable','--now','cmnd-egress'); apply_policy(policy,execute=True)
if i.database_mode=='isolated':_isolated_db(i,c,values)
else: report['shared_database_initialization']=i.shared_database.initialize(i.vendor,values); write_health_files(values,c.database_port); wait_shared_database()
- adminpass=_admin(i); write_new(STATE/'initial-admin.json',json.dumps({'username':'admin','password':adminpass})); from .update_gui import password_record; admin=pwd.getpwnam('cmnd-admin'); MANAGEMENT.mkdir(mode=0o750); os.chown(MANAGEMENT,0,admin.pw_gid); Path('/var/lib/cmnd-updates').mkdir(mode=0o750); queue=Path('/var/lib/cmnd-update-requests'); queue.mkdir(mode=0o700); os.chown(queue,admin.pw_uid,admin.pw_gid); write_new(MANAGEMENT/'admin.json',json.dumps({'password':password_record(adminpass),'origin':https_origin(public,c.apache_https),'check_on_startup':not i.apt_managed,'applications':{'TV management':f'https://{public}:{c.tomcat_https}/SmartInstall/','Site and content editor':f'https://{public}:{c.apache_https}/SmartCMS/'}}),0o640); write_new(MANAGEMENT/'updates.json',json.dumps({'enabled':not i.apt_managed,'channel':'apt' if i.apt_managed else 'preview','token_file':None}),0o640); validate_baseline(); shutil.copyfile(BASELINE,'/var/lib/cmnd-updates/current.deb')
+ adminpass=_admin(i)
+ write_new(STATE/'initial-admin.json',json.dumps({'username':'admin','password':adminpass}))
+ from .update_gui import password_record
+ admin=pwd.getpwnam('cmnd-admin')
+ MANAGEMENT.mkdir(mode=0o750)
+ os.chown(MANAGEMENT,0,admin.pw_gid)
+ MANAGEMENT.chmod(0o750)
+ updates_dir=Path('/var/lib/cmnd-updates')
+ updates_dir.mkdir(mode=0o750)
+ updates_dir.chmod(0o750)
+ queue=Path('/var/lib/cmnd-update-requests')
+ queue.mkdir(mode=0o700)
+ os.chown(queue,admin.pw_uid,admin.pw_gid)
+ queue.chmod(0o700)
+ write_new(MANAGEMENT/'admin.json',json.dumps({'password':password_record(adminpass),'origin':https_origin(public,c.apache_https),'check_on_startup':not i.apt_managed,'applications':{'TV management':f'https://{public}:{c.tomcat_https}/SmartInstall/','Site and content editor':f'https://{public}:{c.apache_https}/SmartCMS/'}}),0o640)
+ write_new(MANAGEMENT/'updates.json',json.dumps({'enabled':not i.apt_managed,'channel':'apt' if i.apt_managed else 'preview','token_file':None}),0o640)
+ for management_file in MANAGEMENT.iterdir():
+ os.chown(management_file,0,admin.pw_gid)
+ management_file.chmod(0o640)
+ validate_baseline()
+ shutil.copyfile(BASELINE,'/var/lib/cmnd-updates/current.deb')
+ Path('/var/lib/cmnd-updates/current.deb').chmod(0o600)
create=['docker','create','--name','cmnd-native-php','--network','host','--user',f'{cms.pw_uid}:{cms.pw_gid}','--read-only','--cap-drop','ALL','--pids-limit','128','--memory','1g','--security-opt','no-new-privileges','--tmpfs','/tmp:rw,nosuid,noexec,size=256m']; create += (['--group-add',str(webgid)] if i.apache_mode=='host' else []); create += ['--mount',f'type=bind,src={LAYOUT.cms},dst={LAYOUT.cms},readonly','--mount',f'type=bind,src={LAYOUT.cms}/sites/default/files,dst={LAYOUT.cms}/sites/default/files','--mount',f'type=bind,src={LAYOUT.pgt},dst={LAYOUT.pgt}','--mount',f'type=bind,src={LAYOUT.php_uploads},dst={LAYOUT.php_uploads}','--mount','type=bind,src=/etc/cmnd/php-fpm.conf,dst=/usr/local/etc/php-fpm.conf,readonly','--mount','type=bind,src=/etc/ssl/certs,dst=/etc/ssl/certs,readonly',i.php_image]; run(*create); run('systemctl','start','cmnd-php'); wait_php(); run('docker','exec','-i','-e','CMND_CMS_EXECUTE=1','cmnd-native-php','php',data=(ETC/'configure-cms.php').read_bytes())
if i.apache_mode=='host': report['host_apache']=apache_apply(c,execute=True); host_apache=True
else: run('apache2','-t','-f',ETC/'apache.conf'); run('systemctl','start','cmnd-apache')
From 7ea97f4329d307cdc3204579c0afa5db21849d88 Mon Sep 17 00:00:00 2001
From: Tommy Heggie <42516199+MusicCityTelecom@users.noreply.github.com>
Date: Tue, 22 Sep 2026 20:41:25 -0500
Subject: [PATCH 20/52] Preserve active CMND across package upgrades
---
packaging/cmnd-linux/prerm | 7 ++++++-
1 file changed, 6 insertions(+), 1 deletion(-)
diff --git a/packaging/cmnd-linux/prerm b/packaging/cmnd-linux/prerm
index db680f4a..180451bd 100644
--- a/packaging/cmnd-linux/prerm
+++ b/packaging/cmnd-linux/prerm
@@ -2,7 +2,7 @@
set -eu
case "${1:-}" in
- remove|deconfigure|upgrade)
+ remove)
if command -v systemctl >/dev/null 2>&1; then
systemctl stop cmnd-tomcat.service cmnd-apache.service cmnd-php.service cmnd-mysql.service cmnd-admin.service 2>/dev/null || true
fi
@@ -10,5 +10,10 @@ case "${1:-}" in
/usr/bin/cmndctl apache-detach --execute 2>/dev/null || true
fi
;;
+ upgrade|deconfigure)
+ # Preserve the active runtime across package replacement. The new package's
+ # postinst validates/preserves the deployment marker instead of re-running
+ # a destructive fresh-install transaction.
+ ;;
esac
exit 0
From 0ef43df6574e43da1c4d673745f24c4853909e05 Mon Sep 17 00:00:00 2001
From: Tommy Heggie <42516199+MusicCityTelecom@users.noreply.github.com>
Date: Tue, 22 Sep 2026 20:41:28 -0500
Subject: [PATCH 21/52] Preserve recognized active deployment in postinst
---
packaging/cmnd-linux/postinst | 22 ++++++++++++++++++++++
1 file changed, 22 insertions(+)
diff --git a/packaging/cmnd-linux/postinst b/packaging/cmnd-linux/postinst
index f06ee65a..389560ba 100644
--- a/packaging/cmnd-linux/postinst
+++ b/packaging/cmnd-linux/postinst
@@ -4,6 +4,28 @@ set -eu
[ "${1:-}" = configure ] || exit 0
+if [ -f /etc/cmnd/deployment.json ] && [ ! -L /etc/cmnd/deployment.json ]; then
+ if python3 - <<'PY'
+import json, os, pathlib, sys
+p = pathlib.Path('/etc/cmnd/deployment.json')
+try:
+ st = p.stat()
+ data = json.loads(p.read_text(encoding='utf-8'))
+except Exception:
+ sys.exit(1)
+safe = st.st_uid == 0 and not (st.st_mode & 0o022) and st.st_size < 65536
+managed = data.get('managed_by') in {'linux-cmnd-apt', 'linux-cmnd-native', 'linux-cmnd-coexist'}
+active = data.get('state') == 'active'
+sys.exit(0 if safe and managed and active else 1)
+PY
+ then
+ echo "cmnd-linux: existing active CMND deployment preserved; fresh activation skipped."
+ exit 0
+ fi
+ echo "cmnd-linux: unrecognized or unsafe deployment marker; refusing package reconfiguration." >&2
+ exit 1
+fi
+
db_get cmnd-linux/accept-legacy-runtime
if [ "$RET" != true ]; then
echo "cmnd-linux installed but not activated: legacy runtime acceptance was not granted." >&2
From 852a3a6323d97762805c5906a441c094c3db1c9f Mon Sep 17 00:00:00 2001
From: Tommy Heggie <42516199+MusicCityTelecom@users.noreply.github.com>
Date: Tue, 22 Sep 2026 20:42:19 -0500
Subject: [PATCH 22/52] Test complete 0.8 APT entry package
---
tests/test_meta_deb.py | 11 +++++++++--
1 file changed, 9 insertions(+), 2 deletions(-)
diff --git a/tests/test_meta_deb.py b/tests/test_meta_deb.py
index 68f75cd4..ab0f88ac 100644
--- a/tests/test_meta_deb.py
+++ b/tests/test_meta_deb.py
@@ -19,15 +19,22 @@ def ar_members(blob):
class MetaDebianPackageTests(unittest.TestCase):
- def test_user_facing_package_depends_on_exact_payload_versions(self):
+ def test_user_facing_package_contains_complete_apt_transaction(self):
package = build()
self.assertTrue(package.name.startswith('cmnd-linux_'))
members = ar_members(package.read_bytes())
with tarfile.open(fileobj=BytesIO(members['control.tar.gz']), mode='r:gz') as archive:
+ names = set(archive.getnames())
control = archive.extractfile('control').read().decode()
self.assertIn('Package: cmnd-linux\n', control)
self.assertIn('Architecture: all\n', control)
- self.assertIn('Depends: linux-cmnd (= 0.8.0), cmnd-vendor-759 (= 7.5.9-1)\n', control)
+ self.assertIn('linux-cmnd (= 0.8.0)', control)
+ self.assertIn('cmnd-vendor-759 (= 7.5.9-1)', control)
+ self.assertIn('cmnd-tomcat9 (= 9.0.121-1)', control)
+ self.assertTrue({'templates', 'config', 'postinst', 'prerm', 'postrm'} <= names)
+ with tarfile.open(fileobj=BytesIO(members['data.tar.gz']), mode='r:gz') as archive:
+ data_names = set(archive.getnames())
+ self.assertIn('usr/lib/cmnd/packages/linux-cmnd_0.8.0_amd64.deb', data_names)
def test_meta_build_is_reproducible(self):
first = build().read_bytes()
From 6473ad259813d58cb7ab70dc69e4b12cc8c279ba Mon Sep 17 00:00:00 2001
From: Tommy Heggie <42516199+MusicCityTelecom@users.noreply.github.com>
Date: Tue, 22 Sep 2026 20:42:22 -0500
Subject: [PATCH 23/52] Test four-package signed APT repository
---
tests/test_apt_repository.py | 58 ++++++++++++++++++++----------------
1 file changed, 33 insertions(+), 25 deletions(-)
diff --git a/tests/test_apt_repository.py b/tests/test_apt_repository.py
index fe7f2d2b..88ef0410 100644
--- a/tests/test_apt_repository.py
+++ b/tests/test_apt_repository.py
@@ -11,6 +11,7 @@ def debs():
Path('linux-cmnd_0.8.0_amd64.deb'),
Path('cmnd-linux_0.8.0_all.deb'),
Path('cmnd-vendor-759_7.5.9-1_all.deb'),
+ Path('cmnd-tomcat9_9.0.121-1_all.deb'),
]
@@ -21,25 +22,27 @@ def package_metadata(self, path):
package, version, architecture = 'cmnd-linux', '0.8.0', 'all'
elif name.startswith('cmnd-vendor-759_'):
package, version, architecture = 'cmnd-vendor-759', '7.5.9-1', 'all'
+ elif name.startswith('cmnd-tomcat9_'):
+ package, version, architecture = 'cmnd-tomcat9', '9.0.121-1', 'all'
else:
package, version, architecture = 'linux-cmnd', '0.8.0', 'amd64'
return {'package': package, 'version': version, 'architecture': architecture, 'size': 1234}
- def test_plan_requires_tooling_meta_and_vendor_packages(self):
- with tempfile.TemporaryDirectory() as temp, patch('scripts.build_apt_repository.validate_deb', side_effect=self.package_metadata):
- output = Path(temp) / 'repo'
+ def test_plan_requires_complete_four_package_set(self):
+ with tempfile.TemporaryDirectory() as temp, patch('scripts.build_apt_repository.validate', side_effect=self.package_metadata):
with self.assertRaisesRegex(ValueError, 'requires exactly'):
- build_repository(output, debs()[:2], codename='noble', suite='development',
- signing_key=None, allow_unsigned_development=True, execute=False)
+ build_repository(Path(temp) / 'repo', debs()[:3], codename='noble',
+ suite='development', signing_key=None,
+ allow_unsigned_development=True, execute=False)
def test_unsigned_stable_repository_is_refused(self):
- with tempfile.TemporaryDirectory() as temp, patch('scripts.build_apt_repository.validate_deb', side_effect=self.package_metadata):
- with self.assertRaisesRegex(ValueError, 'signed repository metadata is required'):
+ with tempfile.TemporaryDirectory() as temp, patch('scripts.build_apt_repository.validate', side_effect=self.package_metadata):
+ with self.assertRaisesRegex(ValueError, 'signed metadata required'):
build_repository(Path(temp) / 'repo', debs(), codename='noble', suite='stable',
signing_key=None, allow_unsigned_development=False, execute=False)
- def test_development_plan_is_non_mutating_and_accepts_explicit_unsigned_mode(self):
- with tempfile.TemporaryDirectory() as temp, patch('scripts.build_apt_repository.validate_deb', side_effect=self.package_metadata):
+ def test_development_plan_is_non_mutating(self):
+ with tempfile.TemporaryDirectory() as temp, patch('scripts.build_apt_repository.validate', side_effect=self.package_metadata):
output = Path(temp) / 'repo'
plan = build_repository(output, debs(), codename='noble', suite='development',
signing_key=None, allow_unsigned_development=True, execute=False)
@@ -47,6 +50,7 @@ def test_development_plan_is_non_mutating_and_accepts_explicit_unsigned_mode(sel
self.assertFalse(plan['signed'])
self.assertEqual(plan['tooling_version'], '0.8.0')
self.assertEqual(plan['vendor_version'], '7.5.9-1')
+ self.assertEqual(plan['tomcat_version'], '9.0.121-1')
self.assertFalse(output.exists())
def test_mismatched_tooling_package_versions_are_refused(self):
@@ -55,23 +59,27 @@ def metadata(path):
if path.name.startswith('cmnd-linux_'):
result = dict(result, version='0.8.1')
return result
+ with tempfile.TemporaryDirectory() as temp, patch('scripts.build_apt_repository.validate', side_effect=metadata):
+ with self.assertRaisesRegex(ValueError, 'versions must match'):
+ build_repository(Path(temp) / 'repo', debs(), codename='noble',
+ suite='development', signing_key='TESTKEY',
+ allow_unsigned_development=False, execute=False)
- with tempfile.TemporaryDirectory() as temp, patch('scripts.build_apt_repository.validate_deb', side_effect=metadata):
- with self.assertRaisesRegex(ValueError, 'same version'):
- build_repository(Path(temp) / 'repo', debs(), codename='noble', suite='development',
- signing_key='TESTKEY', allow_unsigned_development=False, execute=False)
-
- def test_unreviewed_vendor_package_version_is_refused(self):
- def metadata(path):
- result = self.package_metadata(path)
- if path.name.startswith('cmnd-vendor-759_'):
- result = dict(result, version='7.5.9-2')
- return result
-
- with tempfile.TemporaryDirectory() as temp, patch('scripts.build_apt_repository.validate_deb', side_effect=metadata):
- with self.assertRaisesRegex(ValueError, 'reviewed vendor package version'):
- build_repository(Path(temp) / 'repo', debs(), codename='noble', suite='development',
- signing_key='TESTKEY', allow_unsigned_development=False, execute=False)
+ def test_unreviewed_vendor_and_tomcat_versions_are_refused(self):
+ for prefix, version, expected in (
+ ('cmnd-vendor-759_', '7.5.9-2', 'unexpected vendor package version'),
+ ('cmnd-tomcat9_', '9.0.122-1', 'unexpected Tomcat package version'),
+ ):
+ def metadata(path, prefix=prefix, version=version):
+ result = self.package_metadata(path)
+ if path.name.startswith(prefix):
+ result = dict(result, version=version)
+ return result
+ with tempfile.TemporaryDirectory() as temp, patch('scripts.build_apt_repository.validate', side_effect=metadata):
+ with self.assertRaisesRegex(ValueError, expected):
+ build_repository(Path(temp) / 'repo', debs(), codename='noble',
+ suite='development', signing_key='TESTKEY',
+ allow_unsigned_development=False, execute=False)
if __name__ == '__main__':
From 10f6b45e9d790f3d9db1ae9d743b3e3f44abee73 Mon Sep 17 00:00:00 2001
From: Tommy Heggie <42516199+MusicCityTelecom@users.noreply.github.com>
Date: Tue, 22 Sep 2026 20:43:23 -0500
Subject: [PATCH 24/52] Keep coexistence module importable off Linux
---
src/cmnd_linux/coexist_deploy.py | 6 ++++--
1 file changed, 4 insertions(+), 2 deletions(-)
diff --git a/src/cmnd_linux/coexist_deploy.py b/src/cmnd_linux/coexist_deploy.py
index 56f6b086..b4c79098 100644
--- a/src/cmnd_linux/coexist_deploy.py
+++ b/src/cmnd_linux/coexist_deploy.py
@@ -6,7 +6,7 @@
"""
from __future__ import annotations
from dataclasses import dataclass
-import hashlib, json, os, platform, pwd, re, secrets, shutil, socket, ssl, subprocess, time
+import hashlib, json, os, platform, re, secrets, shutil, socket, ssl, subprocess, time
from pathlib import Path
from urllib.error import HTTPError, URLError
from urllib.parse import urlsplit
@@ -130,7 +130,9 @@ def _ready(c,db_mode,seconds=900):
def deploy(i:CoexistInputs,*,execute=False,accept_legacy=False):
c=load_config(i.config); report=preflight(i,c)|{'executed':execute,'database_mode':i.database_mode,'apache_mode':i.apache_mode,'apt_managed':i.apt_managed,'readiness_verified':False,'scope':'0.8 coexistence candidate'}
if not execute:return report
- if os.geteuid()!=0 or not accept_legacy:raise ConfigError('root and legacy-runtime acceptance required')
+ if os.name!='posix' or not hasattr(os,'geteuid') or os.geteuid()!=0 or not accept_legacy:
+ raise ConfigError('root Linux execution and legacy-runtime acceptance required')
+ import pwd
os.umask(0o077); STATE.mkdir(mode=0o700); host_apache=False
try:
values={k:secrets.token_hex(24) for k in (*REQUIRED_SECRETS,'tpvision_db_password')}; write_new(STATE/'secrets.json',json.dumps(values)); write_new(STATE/'certificate-password',values['cert_ca_password'])
From 5e91f0c83e4aa3d2eda316caaeb6b1e5444dba86 Mon Sep 17 00:00:00 2001
From: Tommy Heggie <42516199+MusicCityTelecom@users.noreply.github.com>
Date: Tue, 22 Sep 2026 20:43:27 -0500
Subject: [PATCH 25/52] Disable CMND-owned services on package removal
---
packaging/cmnd-linux/prerm | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/packaging/cmnd-linux/prerm b/packaging/cmnd-linux/prerm
index 180451bd..7772c602 100644
--- a/packaging/cmnd-linux/prerm
+++ b/packaging/cmnd-linux/prerm
@@ -4,7 +4,7 @@ set -eu
case "${1:-}" in
remove)
if command -v systemctl >/dev/null 2>&1; then
- systemctl stop cmnd-tomcat.service cmnd-apache.service cmnd-php.service cmnd-mysql.service cmnd-admin.service 2>/dev/null || true
+ systemctl disable --now cmnd-update.path cmnd-tomcat.service cmnd-apache.service cmnd-php.service cmnd-mysql.service cmnd-admin.service cmnd-egress.service 2>/dev/null || true
fi
if [ -x /usr/bin/cmndctl ] && [ -f /etc/cmnd/deployment.json ]; then
/usr/bin/cmndctl apache-detach --execute 2>/dev/null || true
From ad63dfe0d7634111b06b838367d72d3314c6d35e Mon Sep 17 00:00:00 2001
From: Tommy Heggie <42516199+MusicCityTelecom@users.noreply.github.com>
Date: Tue, 22 Sep 2026 20:43:54 -0500
Subject: [PATCH 26/52] Add 0.8 APT coexistence regressions
---
tests/test_08_coexistence.py | 111 +++++++++++++++++++++++++++++++++++
1 file changed, 111 insertions(+)
create mode 100644 tests/test_08_coexistence.py
diff --git a/tests/test_08_coexistence.py b/tests/test_08_coexistence.py
new file mode 100644
index 00000000..1e90b5fd
--- /dev/null
+++ b/tests/test_08_coexistence.py
@@ -0,0 +1,111 @@
+from pathlib import Path
+import unittest
+
+from cmnd_linux.apt_installer import _planned_ports, render_config
+from cmnd_linux.apache_integration import render as render_apache
+from cmnd_linux.config import Config
+from cmnd_linux.install_plan import build_plan
+from cmnd_linux.shared_database import _sql_string
+
+
+def inventory():
+ return {
+ 'os': {'id': 'ubuntu', 'version_id': '24.04', 'qualification': 'qualified-baseline'},
+ 'packages': {'linux-cmnd': '0.8.0'},
+ 'listeners': {'available': True, 'entries': []},
+ 'web': {
+ 'apache': {'present': False}, 'apache_ctl': {'present': False},
+ 'apache_service': {'active': False}, 'nginx': {'present': False},
+ },
+ 'database': {
+ 'mariadb_client': {'present': False}, 'mysql_client': {'present': False},
+ 'packages': {}, 'root_socket_auth': 'not-tested',
+ },
+ 'docker': {'docker': {'present': True}, 'daemon_access': True, 'running_containers': []},
+ 'runtime': {'java': {'present': True, 'version': 'openjdk version "17.0.12"', 'path': '/usr/bin/java'}},
+ 'cmnd': {
+ 'package_version': '0.8.0',
+ 'paths': {'/opt/linux-cmnd': True, '/opt/cmnd': True, '/etc/cmnd': True},
+ 'runtime_paths': {
+ '/var/lib/cmnd-deployment': False,
+ '/opt/cmnd/tomcat': False,
+ '/opt/cmnd/SmartCMS': False,
+ '/opt/Philips': False,
+ '/etc/cmnd/deployment.json': False,
+ },
+ 'active_runtime_detected': False,
+ },
+ }
+
+
+class AptCoexistenceTests(unittest.TestCase):
+ def test_tooling_only_host_can_be_planned_for_first_activation(self):
+ inv = inventory()
+ plan = build_plan(inv)
+ self.assertTrue(plan['fresh_install_allowed'])
+ ports = _planned_ports(inv, plan, 'isolated')
+ self.assertEqual(ports['tomcat_http'], 8080)
+ self.assertEqual(ports['tomcat_https'], 8443)
+ self.assertEqual(ports['apache_http'], 8082)
+ self.assertEqual(ports['apache_https'], 8444)
+ self.assertEqual(ports['database'], 3306)
+
+ def test_main_cmnd_ports_move_without_taking_existing_listener(self):
+ inv = inventory()
+ inv['listeners']['entries'] = [
+ {'port': 8080, 'process': 'other-java'},
+ {'port': 8082, 'process': 'other-web'},
+ {'port': 3306, 'process': 'other-db'},
+ ]
+ plan = build_plan(inv)
+ ports = _planned_ports(inv, plan, 'isolated')
+ self.assertNotIn(8080, ports.values())
+ self.assertNotIn(8082, ports.values())
+ self.assertNotIn(3306, ports.values())
+
+ def test_generated_config_has_empty_tv_allowlist(self):
+ text = render_config('10.1.10.14', {
+ 'tomcat_http': 8080, 'tomcat_https': 8443,
+ 'apache_http': 8082, 'apache_https': 8444, 'database': 3306,
+ })
+ self.assertIn('bind = "10.1.10.14"', text)
+ self.assertIn('allowlist = []', text)
+ self.assertIn('permitted_ranges = ["127.0.0.0/8"]', text)
+
+ def test_host_apache_fragment_is_scoped_and_does_not_include_host_sites(self):
+ config = Config(
+ mode='lab', bind='10.1.10.14',
+ callback_base_url='http://10.1.10.14:8080',
+ permitted_ranges=('127.0.0.0/8',), allowed_tvs=(),
+ )
+ text = render_apache(config)
+ self.assertIn('# Managed by CMND Linux 0.8.', text)
+ self.assertIn('Listen 10.1.10.14:8082', text)
+ self.assertNotIn('IncludeOptional sites-enabled', text)
+ self.assertNotIn('ports.conf', text)
+
+ def test_generated_database_credentials_are_restricted_literals(self):
+ self.assertEqual(_sql_string('abc123'), "'abc123'")
+ with self.assertRaises(Exception):
+ _sql_string("bad'quote")
+
+ def test_package_upgrade_preserves_runtime_and_password_is_transient(self):
+ root = Path(__file__).resolve().parents[1]
+ postinst = (root / 'packaging/cmnd-linux/postinst').read_text()
+ prerm = (root / 'packaging/cmnd-linux/prerm').read_text()
+ self.assertIn('existing active CMND deployment preserved', postinst)
+ self.assertIn("db_set cmnd-linux/database-admin-password ''", postinst)
+ self.assertIn('upgrade|deconfigure', prerm)
+ upgrade_block = prerm.split('upgrade|deconfigure', 1)[1]
+ self.assertNotIn('disable --now', upgrade_block)
+
+ def test_coexistence_source_sets_runtime_permissions(self):
+ root = Path(__file__).resolve().parents[1]
+ source = (root / 'src/cmnd_linux/coexist_deploy.py').read_text()
+ self.assertIn("os.chown(ETC/'java-cacerts',0,java.pw_gid)", source)
+ self.assertIn("MANAGEMENT.chmod(0o750)", source)
+ self.assertIn("management_file.chmod(0o640)", source)
+
+
+if __name__ == '__main__':
+ unittest.main()
From 3e6934eb20ae8327e284f5848f3eabf17321bc51 Mon Sep 17 00:00:00 2001
From: Tommy Heggie <42516199+MusicCityTelecom@users.noreply.github.com>
Date: Tue, 22 Sep 2026 20:45:26 -0500
Subject: [PATCH 27/52] Make host Apache integration retry-safe
---
src/cmnd_linux/apache_integration.py | 10 ++++++++--
1 file changed, 8 insertions(+), 2 deletions(-)
diff --git a/src/cmnd_linux/apache_integration.py b/src/cmnd_linux/apache_integration.py
index e75fab2a..f74e7e76 100644
--- a/src/cmnd_linux/apache_integration.py
+++ b/src/cmnd_linux/apache_integration.py
@@ -17,8 +17,8 @@
CONF_AVAILABLE = Path('/etc/apache2/conf-available/cmnd-linux.conf')
CONF_ENABLED = Path('/etc/apache2/conf-enabled/cmnd-linux.conf')
-MODULES = ('proxy', 'proxy_fcgi', 'proxy_http', 'ssl', 'rewrite', 'headers',
- 'expires', 'filter', 'deflate')
+MODULES = ('alias', 'dir', 'proxy', 'proxy_fcgi', 'proxy_http', 'ssl', 'rewrite',
+ 'headers', 'expires', 'filter', 'deflate')
def supported() -> bool:
@@ -122,6 +122,12 @@ def apply(config: Config, *, execute: bool = False) -> dict:
return report
except Exception:
subprocess.run([shutil.which('a2disconf') or 'a2disconf', 'cmnd-linux'], capture_output=True, timeout=20)
+ if CONF_AVAILABLE.is_file() and not CONF_AVAILABLE.is_symlink():
+ try:
+ if CONF_AVAILABLE.read_text(encoding='utf-8', errors='replace').startswith('# Managed by CMND Linux 0.8.'):
+ CONF_AVAILABLE.unlink()
+ except OSError:
+ pass
subprocess.run([shutil.which('apache2ctl') or 'apache2ctl', 'configtest'], capture_output=True, timeout=20)
subprocess.run([shutil.which('systemctl') or 'systemctl', 'reload', 'apache2.service'], capture_output=True, timeout=30)
raise
From c03f7eb79fa53fadbd7b7275d77c114b8a3d01c5 Mon Sep 17 00:00:00 2001
From: Tommy Heggie <42516199+MusicCityTelecom@users.noreply.github.com>
Date: Tue, 22 Sep 2026 20:45:29 -0500
Subject: [PATCH 28/52] Restore resource and PHP runtime preflight
---
src/cmnd_linux/coexist_deploy.py | 21 ++++++++++++++++++++-
1 file changed, 20 insertions(+), 1 deletion(-)
diff --git a/src/cmnd_linux/coexist_deploy.py b/src/cmnd_linux/coexist_deploy.py
index b4c79098..d6cb943e 100644
--- a/src/cmnd_linux/coexist_deploy.py
+++ b/src/cmnd_linux/coexist_deploy.py
@@ -91,8 +91,27 @@ def preflight(i:CoexistInputs,c:Config):
if not i.shared_database or i.shared_database.port!=c.database_port: raise ConfigError('shared DB session/port mismatch')
db.update(i.shared_database.validate_for_fresh_cmnd())
if i.apache_mode=='host' and not apache_supported(): raise ConfigError('host Apache layout unsupported')
+ if shutil.disk_usage('/var/lib').free < 10 * 1024**3:
+ raise ConfigError('at least 10 GiB free deployment space is required')
+ memory = re.search(r'^MemTotal:\\s+(\\d+)', Path('/proc/meminfo').read_text(), re.M)
+ if not memory or int(memory.group(1)) < 5_500_000:
+ raise ConfigError('at least 6 GiB installed RAM is required')
run('docker','image','inspect',i.php_image)
- return {'os':list(distro),'database':db,'apache_mode':i.apache_mode,'vendor_inputs_verified':len(VENDOR_INPUT_HASHES)}
+ php_probe = (
+ 'if(PHP_VERSION!=="5.6.40"){exit(2);} '
+ 'foreach(array("pdo_mysql","mysqli","gd","zip","xmlrpc","pcntl","curl") as $m)'
+ '{if(!extension_loaded($m)){exit(3);}} '
+ 'foreach(array("/usr/local/bin/cutycapt.sh","/usr/bin/cutycapt","/usr/bin/xvfb-run",'
+ '"/usr/bin/ffmpeg","/usr/bin/ffprobe","/usr/bin/convert") as $p)'
+ '{if(!is_executable($p)){exit(4);}}'
+ )
+ run('docker','run','--rm','--network','none','--read-only','--cap-drop','ALL',
+ '--security-opt','no-new-privileges','--user','65534:65534','--memory','256m',
+ '--pids-limit','32',i.php_image,'php','-r',php_probe)
+ return {'os':list(distro),'database':db,'apache_mode':i.apache_mode,
+ 'vendor_inputs_verified':len(VENDOR_INPUT_HASHES),
+ 'resource_preflight':{'memory_kib':int(memory.group(1)),'disk_free':shutil.disk_usage('/var/lib').free},
+ 'php_runtime_verified':True}
def _isolated_db(i,c,values):
root=secrets.token_hex(32); write_new(STATE/'mysql-root-password',root); write_new(STATE/'mysql-client.cnf',f'[client]\nuser=root\npassword={root}\nhost=127.0.0.1\nport={c.database_port}\nprotocol=tcp\n'); (STATE/'mysql').mkdir(mode=0o700)
From 0c1c3f680003bbeafa197bfdd05e7d867f0997e6 Mon Sep 17 00:00:00 2001
From: Tommy Heggie <42516199+MusicCityTelecom@users.noreply.github.com>
Date: Tue, 22 Sep 2026 20:47:08 -0500
Subject: [PATCH 29/52] Prefer default-route IPv4 for CMND APT activation
---
src/cmnd_linux/apt_installer.py | 21 ++++++++++++++++++++-
1 file changed, 20 insertions(+), 1 deletion(-)
diff --git a/src/cmnd_linux/apt_installer.py b/src/cmnd_linux/apt_installer.py
index b7accc0d..2aa0f4ef 100644
--- a/src/cmnd_linux/apt_installer.py
+++ b/src/cmnd_linux/apt_installer.py
@@ -46,6 +46,21 @@ def _assigned_ipv4():
try:interfaces=json.loads(r.stdout)
except Exception:return []
return [a['local'] for i in interfaces if 'UP' in i.get('flags',[]) for a in i.get('addr_info',[]) if a.get('family')=='inet' and isinstance(a.get('local'),str)]
+def _default_route_ipv4(assigned):
+ # This is a local routing-table lookup; it does not contact 1.1.1.1.
+ result=_run(['ip','-j','route','get','1.1.1.1'],timeout=10)
+ if result.returncode:
+ return None
+ try:
+ routes=json.loads(result.stdout)
+ except Exception:
+ return None
+ for route in routes if isinstance(routes,list) else []:
+ candidate=route.get('prefsrc') or route.get('src')
+ if isinstance(candidate,str) and candidate in assigned and not candidate.startswith('127.'):
+ return candidate
+ return None
+
def choose_server_ip(requested=None):
assigned=_assigned_ipv4()
if requested:
@@ -53,7 +68,11 @@ def choose_server_ip(requested=None):
except OSError as e:raise ConfigError('server IP must be a literal IPv4 address') from e
if requested!='127.0.0.1' and requested not in assigned: raise ConfigError('requested server IP is not assigned to an active local interface')
return requested
- values=[v for v in assigned if not v.startswith('127.')]; return values[0] if values else '127.0.0.1'
+ preferred=_default_route_ipv4(assigned)
+ if preferred:
+ return preferred
+ values=[v for v in assigned if not v.startswith('127.')]
+ return values[0] if values else '127.0.0.1'
def _occupied(inv): return {int(x['port']) for x in inv.get('listeners',{}).get('entries',[]) if isinstance(x,dict) and isinstance(x.get('port'),int)}
def _planned_ports(inv,plan,database_mode):
c=plan['components']; ports={'tomcat_http':int(c['tomcat']['ports']['http']),'tomcat_https':int(c['tomcat']['ports']['https']),'apache_http':int(c['apache']['ports']['http']),'apache_https':int(c['apache']['ports']['https'])}
From c6b24af9517ffa43f20e6ceae41be707a7e73183 Mon Sep 17 00:00:00 2001
From: Tommy Heggie <42516199+MusicCityTelecom@users.noreply.github.com>
Date: Tue, 22 Sep 2026 20:47:12 -0500
Subject: [PATCH 30/52] Regress default-route CMND address selection
---
tests/test_08_coexistence.py | 12 ++++++++++++
1 file changed, 12 insertions(+)
diff --git a/tests/test_08_coexistence.py b/tests/test_08_coexistence.py
index 1e90b5fd..ed0f566c 100644
--- a/tests/test_08_coexistence.py
+++ b/tests/test_08_coexistence.py
@@ -1,6 +1,9 @@
from pathlib import Path
import unittest
+from unittest.mock import patch
+import subprocess
+from cmnd_linux import apt_installer
from cmnd_linux.apt_installer import _planned_ports, render_config
from cmnd_linux.apache_integration import render as render_apache
from cmnd_linux.config import Config
@@ -63,6 +66,15 @@ def test_main_cmnd_ports_move_without_taking_existing_listener(self):
self.assertNotIn(8082, ports.values())
self.assertNotIn(3306, ports.values())
+ def test_auto_server_ip_prefers_default_route_source(self):
+ def fake_run(args, timeout=1800):
+ if args[:4] == ['ip', '-j', 'route', 'get']:
+ return subprocess.CompletedProcess(args, 0, '[{\"prefsrc\":\"10.1.10.14\"}]', '')
+ raise AssertionError(args)
+ with patch.object(apt_installer, '_assigned_ipv4', return_value=['172.17.0.1', '10.1.10.14']), \
+ patch.object(apt_installer, '_run', side_effect=fake_run):
+ self.assertEqual(apt_installer.choose_server_ip(), '10.1.10.14')
+
def test_generated_config_has_empty_tv_allowlist(self):
text = render_config('10.1.10.14', {
'tomcat_http': 8080, 'tomcat_https': 8443,
From 35f590d0509f6514dc0ec859926e996c4634447a Mon Sep 17 00:00:00 2001
From: Tommy Heggie <42516199+MusicCityTelecom@users.noreply.github.com>
Date: Tue, 22 Sep 2026 20:48:04 -0500
Subject: [PATCH 31/52] Make private CMND listener ports configurable
---
src/cmnd_linux/native_config.py | 9 +++++++--
1 file changed, 7 insertions(+), 2 deletions(-)
diff --git a/src/cmnd_linux/native_config.py b/src/cmnd_linux/native_config.py
index 94ab61ab..2695d5b5 100644
--- a/src/cmnd_linux/native_config.py
+++ b/src/cmnd_linux/native_config.py
@@ -35,6 +35,7 @@ class NativeLayout:
php_uploads: str = '/var/lib/cmnd/php-uploads'
php_user: str = 'cmnd-cms'
fpm_port: int = 9000
+ management_port: int = 9078
def validate(self) -> None:
for name in ('tomcat', 'cms', 'configuration', 'log', 'run', 'certificate', 'key', 'ca_bundle', 'pgt', 'php_uploads'):
@@ -49,6 +50,10 @@ def validate(self) -> None:
raise ConfigError('invalid PHP service account')
if type(self.fpm_port) is not int or not 1024 <= self.fpm_port <= 65535:
raise ConfigError('PHP-FPM port must be an unprivileged integer port')
+ if type(self.management_port) is not int or not 1024 <= self.management_port <= 65535:
+ raise ConfigError('management port must be an unprivileged integer port')
+ if self.management_port == self.fpm_port:
+ raise ConfigError('management and PHP-FPM ports must be distinct')
def native_endpoint(config: Config) -> tuple[str, dict[str, int]]:
@@ -164,8 +169,8 @@ def render_native_files(config: Config, secrets: dict[str, str], layout: NativeL
'''
if port == config.apache_https:
apache += f'SSLEngine on\nSSLCertificateFile {layout.certificate}\nSSLCertificateKeyFile {layout.key}\n'
- apache += ('ProxyRequests Off\nProxyPass /linux-cmnd/ http://127.0.0.1:9078/ connectiontimeout=5 timeout=30\n'
- 'ProxyPassReverse /linux-cmnd/ http://127.0.0.1:9078/\n\nRequire all granted\n\n')
+ apache += ('ProxyRequests Off\nProxyPass /linux-cmnd/ http://127.0.0.1:{layout.management_port}/ connectiontimeout=5 timeout=30\n'
+ f'ProxyPassReverse /linux-cmnd/ http://127.0.0.1:{layout.management_port}/\n\nRequire all granted\n\n')
else:
apache += f'Redirect /linux-cmnd/ https://{host}:{config.apache_https}/linux-cmnd/\n'
apache += '\n'
From b2c4d47a3f439ed2e16dc572ceedda8718ac83af Mon Sep 17 00:00:00 2001
From: Tommy Heggie <42516199+MusicCityTelecom@users.noreply.github.com>
Date: Tue, 22 Sep 2026 20:48:20 -0500
Subject: [PATCH 32/52] Fix rendered management ProxyPass port
---
src/cmnd_linux/native_config.py | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/src/cmnd_linux/native_config.py b/src/cmnd_linux/native_config.py
index 2695d5b5..41b1f8af 100644
--- a/src/cmnd_linux/native_config.py
+++ b/src/cmnd_linux/native_config.py
@@ -169,7 +169,7 @@ def render_native_files(config: Config, secrets: dict[str, str], layout: NativeL
'''
if port == config.apache_https:
apache += f'SSLEngine on\nSSLCertificateFile {layout.certificate}\nSSLCertificateKeyFile {layout.key}\n'
- apache += ('ProxyRequests Off\nProxyPass /linux-cmnd/ http://127.0.0.1:{layout.management_port}/ connectiontimeout=5 timeout=30\n'
+ apache += (f'ProxyRequests Off\nProxyPass /linux-cmnd/ http://127.0.0.1:{layout.management_port}/ connectiontimeout=5 timeout=30\n'
f'ProxyPassReverse /linux-cmnd/ http://127.0.0.1:{layout.management_port}/\n\nRequire all granted\n\n')
else:
apache += f'Redirect /linux-cmnd/ https://{host}:{config.apache_https}/linux-cmnd/\n'
From d74b6d78b7e6510fdd83465a6a8e0db6fa1c629a Mon Sep 17 00:00:00 2001
From: Tommy Heggie <42516199+MusicCityTelecom@users.noreply.github.com>
Date: Tue, 22 Sep 2026 20:48:32 -0500
Subject: [PATCH 33/52] Reserve CMND private listener defaults during planning
---
src/cmnd_linux/install_plan.py | 4 +++-
1 file changed, 3 insertions(+), 1 deletion(-)
diff --git a/src/cmnd_linux/install_plan.py b/src/cmnd_linux/install_plan.py
index b3c5ffe4..ac28a347 100644
--- a/src/cmnd_linux/install_plan.py
+++ b/src/cmnd_linux/install_plan.py
@@ -170,7 +170,9 @@ def _docker_plan(inventory: dict, database_plan: dict) -> dict:
def build_plan(inventory: dict) -> dict:
occupied = _occupied(inventory)
- reserved: set[int] = set()
+ # Reserve the legacy private defaults so public CMND listeners never consume them.
+ # apt_installer may move these private listeners if the host already uses them.
+ reserved: set[int] = {DEFAULT_PORTS['php_fpm'], DEFAULT_PORTS['management']}
cmnd = inventory.get('cmnd', {})
runtime_paths = cmnd.get('runtime_paths', {}) if isinstance(cmnd, dict) else {}
existing_cmnd = bool(cmnd.get('active_runtime_detected')) or any(
From 1b390083edfdf33f4268d2d37406aa2d0f788ab1 Mon Sep 17 00:00:00 2001
From: Tommy Heggie <42516199+MusicCityTelecom@users.noreply.github.com>
Date: Tue, 22 Sep 2026 20:48:55 -0500
Subject: [PATCH 34/52] Auto-allocate private CMND listener ports
---
src/cmnd_linux/apt_installer.py | 28 +++++++++++++++++++++++-----
1 file changed, 23 insertions(+), 5 deletions(-)
diff --git a/src/cmnd_linux/apt_installer.py b/src/cmnd_linux/apt_installer.py
index 2aa0f4ef..ac7ff942 100644
--- a/src/cmnd_linux/apt_installer.py
+++ b/src/cmnd_linux/apt_installer.py
@@ -75,10 +75,25 @@ def choose_server_ip(requested=None):
return values[0] if values else '127.0.0.1'
def _occupied(inv): return {int(x['port']) for x in inv.get('listeners',{}).get('entries',[]) if isinstance(x,dict) and isinstance(x.get('port'),int)}
def _planned_ports(inv,plan,database_mode):
- c=plan['components']; ports={'tomcat_http':int(c['tomcat']['ports']['http']),'tomcat_https':int(c['tomcat']['ports']['https']),'apache_http':int(c['apache']['ports']['http']),'apache_https':int(c['apache']['ports']['https'])}
- if database_mode=='shared':ports['database']=int(c['database'].get('port') or DEFAULT_PORTS['database'])
- else:ports['database']=allocate_port(DEFAULT_PORTS['database'],_occupied(inv),set(ports.values())|{DEFAULT_PORTS['php_fpm'],DEFAULT_PORTS['management']})
- if len(set(ports.values())|{DEFAULT_PORTS['php_fpm'],DEFAULT_PORTS['management']})!=7: raise ConfigError('installation planner produced colliding CMND ports')
+ occupied=_occupied(inv)
+ c=plan['components']
+ ports={
+ 'tomcat_http':int(c['tomcat']['ports']['http']),
+ 'tomcat_https':int(c['tomcat']['ports']['https']),
+ 'apache_http':int(c['apache']['ports']['http']),
+ 'apache_https':int(c['apache']['ports']['https']),
+ }
+ reserved=set(ports.values())
+ if database_mode=='shared':
+ ports['database']=int(c['database'].get('port') or DEFAULT_PORTS['database'])
+ else:
+ ports['database']=allocate_port(DEFAULT_PORTS['database'],occupied,reserved)
+ reserved.add(ports['database'])
+ ports['php_fpm']=allocate_port(DEFAULT_PORTS['php_fpm'],occupied,reserved)
+ reserved.add(ports['php_fpm'])
+ ports['management']=allocate_port(DEFAULT_PORTS['management'],occupied,reserved)
+ if len(set(ports.values()))!=len(ports):
+ raise ConfigError('installation planner produced colliding CMND ports')
return ports
def render_config(ip,ports):
mode='isolated' if ip.startswith('127.') else 'lab'
@@ -180,7 +195,10 @@ def activate(server_ip,database_mode,apache_mode,password_file,admin_user,execut
address=choose_server_ip(server_ip); config=_install_config(render_config(address,ports)); cfg=load_config(config)
if db=='shared' and cfg.database_port!=session.port:raise ConfigError('preserved config DB port does not match shared server')
_ensure_docker(); _ensure_image(MYSQL_IMAGE) if db=='isolated' else None; php=_php_image(); _install_baseline()
- result=deploy(CoexistInputs(config,VENDOR_ROOT,TOMCAT_ARCHIVE,php,Path('/usr/lib/jvm/java-17-openjdk-amd64'),db,web,session,True),execute=True,accept_legacy=True)
+ result=deploy(CoexistInputs(
+ config,VENDOR_ROOT,TOMCAT_ARCHIVE,php,Path('/usr/lib/jvm/java-17-openjdk-amd64'),
+ db,web,session,True,ports['php_fpm'],ports['management']
+ ),execute=True,accept_legacy=True)
result['apt_activation']={'server_ip':address,'database_mode':db,'apache_mode':web,'notes':notes}; return result
def main(argv=None):
p=argparse.ArgumentParser(prog='cmndctl apt-activate'); p.add_argument('--server-ip'); p.add_argument('--database-mode',choices=('auto','existing','isolated'),default='auto'); p.add_argument('--apache-mode',choices=('auto','host','standalone'),default='auto'); p.add_argument('--database-admin-user',default='root'); p.add_argument('--database-admin-password-file',type=Path); p.add_argument('--accept-legacy-runtime',action='store_true'); p.add_argument('--execute',action='store_true'); p.add_argument('--dry-run',action='store_true'); a=p.parse_args(argv)
From b0cf6de6562ed846403f4aa530dbee4852be16dd Mon Sep 17 00:00:00 2001
From: Tommy Heggie <42516199+MusicCityTelecom@users.noreply.github.com>
Date: Tue, 22 Sep 2026 20:49:09 -0500
Subject: [PATCH 35/52] Propagate dynamic private ports into host Apache
---
src/cmnd_linux/apache_integration.py | 8 +++++---
1 file changed, 5 insertions(+), 3 deletions(-)
diff --git a/src/cmnd_linux/apache_integration.py b/src/cmnd_linux/apache_integration.py
index f74e7e76..48eebeda 100644
--- a/src/cmnd_linux/apache_integration.py
+++ b/src/cmnd_linux/apache_integration.py
@@ -26,8 +26,9 @@ def supported() -> bool:
and all(shutil.which(name) for name in ('apache2ctl', 'a2enmod', 'a2enconf', 'a2disconf', 'systemctl')))
-def render(config: Config, *, layout: NativeLayout = NativeLayout(), management_port: int = 9078) -> str:
+def render(config: Config, *, layout: NativeLayout = NativeLayout(), management_port: int | None = None) -> str:
host, _ = native_endpoint(config)
+ management_port = layout.management_port if management_port is None else management_port
if type(management_port) is not int or not 1024 <= management_port <= 65535:
raise ConfigError('invalid management port for host Apache integration')
if layout.fpm_port in {config.apache_http, config.apache_https, management_port}:
@@ -91,8 +92,9 @@ def _run(args: list[str], *, timeout: int = 60) -> subprocess.CompletedProcess[s
return result
-def apply(config: Config, *, execute: bool = False) -> dict:
- content = render(config)
+def apply(config: Config, *, execute: bool = False,
+ layout: NativeLayout = NativeLayout(), management_port: int | None = None) -> dict:
+ content = render(config, layout=layout, management_port=management_port)
if not supported():
raise ConfigError('existing Apache is not a supported Debian/Ubuntu apache2 layout')
if CONF_AVAILABLE.exists() or CONF_AVAILABLE.is_symlink() or CONF_ENABLED.exists() or CONF_ENABLED.is_symlink():
From 52d4668ad45ea689aacd2d5f89a4e857fda17abb Mon Sep 17 00:00:00 2001
From: Tommy Heggie <42516199+MusicCityTelecom@users.noreply.github.com>
Date: Tue, 22 Sep 2026 20:49:38 -0500
Subject: [PATCH 36/52] Propagate dynamic PHP and management ports through
activation
---
src/cmnd_linux/coexist_deploy.py | 40 ++++++++++++++++++++++++++------
1 file changed, 33 insertions(+), 7 deletions(-)
diff --git a/src/cmnd_linux/coexist_deploy.py b/src/cmnd_linux/coexist_deploy.py
index d6cb943e..a8abefbe 100644
--- a/src/cmnd_linux/coexist_deploy.py
+++ b/src/cmnd_linux/coexist_deploy.py
@@ -18,7 +18,7 @@
from .certificates import CertificateConfig, provision_certificates
from .config import Config, ConfigError, load_config
from .egress import EgressPolicy, apply_policy
-from .native_config import native_endpoint, render_native_files
+from .native_config import NativeLayout, native_endpoint, render_native_files
from .native_deploy import (BASELINE, ETC, LAYOUT, MANAGEMENT, MYSQL_IMAGE, SCHEMAS, STATE,
_mysql, _owned_tree, https_origin, mysql_server_options, run, validate_baseline,
validate_image, wait_database, wait_php, write_new)
@@ -31,6 +31,10 @@ class CoexistInputs:
config: Path; vendor: Path; tomcat_archive: Path; php_image: str; java_home: Path
database_mode: str='isolated'; apache_mode: str='standalone'
shared_database: SharedDatabaseSession|None=None; apt_managed: bool=True
+ php_fpm_port: int=9000; management_port: int=9078
+
+ def layout(self) -> NativeLayout:
+ return NativeLayout(fpm_port=self.php_fpm_port, management_port=self.management_port)
def os_support(content,machine):
values={}
@@ -62,9 +66,22 @@ def _port_free(port):
try:s.bind(('0.0.0.0',port)); return True
except OSError:return False
+def _wait_php(port,seconds=60):
+ if type(port) is not int or not 1<=port<=65535:
+ raise ConfigError('invalid PHP-FPM readiness port')
+ deadline=time.monotonic()+seconds
+ while time.monotonic()
Date: Tue, 22 Sep 2026 20:49:50 -0500
Subject: [PATCH 37/52] Allow planned CMND management listener port
---
src/cmnd_linux/update_gui.py | 5 ++++-
1 file changed, 4 insertions(+), 1 deletion(-)
diff --git a/src/cmnd_linux/update_gui.py b/src/cmnd_linux/update_gui.py
index e3e9c4f7..56303c79 100644
--- a/src/cmnd_linux/update_gui.py
+++ b/src/cmnd_linux/update_gui.py
@@ -210,8 +210,11 @@ def do_POST(self):
def serve(config_path: Path):
config = json.loads(config_path.read_text())
+ port = config.get('listen_port', 9078)
+ if type(port) is not int or not 1024 <= port <= 65535:
+ raise ValueError('management listen_port must be an unprivileged integer port')
state = GuiState(config)
- server = ManagementServer(('127.0.0.1', 9078), handler(state))
+ server = ManagementServer(('127.0.0.1', port), handler(state))
if config.get('check_on_startup', True):
state.check()
server.serve_forever()
From 2f813837fba533c0e6f0afb4c2b4444fa7c8735e Mon Sep 17 00:00:00 2001
From: Tommy Heggie <42516199+MusicCityTelecom@users.noreply.github.com>
Date: Tue, 22 Sep 2026 20:50:19 -0500
Subject: [PATCH 38/52] Keep 0.8 APT runtime requirement aligned to Ubuntu
24.04
---
scripts/build_meta_deb.py | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/scripts/build_meta_deb.py b/scripts/build_meta_deb.py
index 3597f1b3..e10ab337 100644
--- a/scripts/build_meta_deb.py
+++ b/scripts/build_meta_deb.py
@@ -27,7 +27,7 @@ def build()->Path:
Priority: optional
Architecture: all
Pre-Depends: debconf (>= 1.5.0) | debconf-2.0
-Depends: linux-cmnd (= {version}), cmnd-vendor-759 (= {VENDOR_PACKAGE_VERSION}), cmnd-tomcat9 (= {TOMCAT_PACKAGE_VERSION}), python3 (>= 3.10), python3-tomli | python3 (>= 3.11), adduser, ca-certificates, openssl, iproute2, iptables, 7zip, openjdk-17-jre-headless, apache2-bin, media-types, docker.io | docker-ce
+Depends: linux-cmnd (= {version}), cmnd-vendor-759 (= {VENDOR_PACKAGE_VERSION}), cmnd-tomcat9 (= {TOMCAT_PACKAGE_VERSION}), python3 (>= 3.11), adduser, ca-certificates, openssl, iproute2, iptables, 7zip, openjdk-17-jre-headless, apache2-bin, media-types, docker.io | docker-ce
Maintainer: Music City Telecom
Description: Philips CMND for Linux installation entry point
Environment-aware APT installer for CMND for Linux. Reuses compatible existing
From ea8ae1357328ef7da7c973b6bd510862c432297f Mon Sep 17 00:00:00 2001
From: Tommy Heggie <42516199+MusicCityTelecom@users.noreply.github.com>
Date: Tue, 22 Sep 2026 20:50:23 -0500
Subject: [PATCH 39/52] Regress private listener conflict remapping
---
tests/test_08_coexistence.py | 17 ++++++++++++++++-
1 file changed, 16 insertions(+), 1 deletion(-)
diff --git a/tests/test_08_coexistence.py b/tests/test_08_coexistence.py
index ed0f566c..0ba31a20 100644
--- a/tests/test_08_coexistence.py
+++ b/tests/test_08_coexistence.py
@@ -75,6 +75,18 @@ def fake_run(args, timeout=1800):
patch.object(apt_installer, '_run', side_effect=fake_run):
self.assertEqual(apt_installer.choose_server_ip(), '10.1.10.14')
+ def test_private_cmnd_ports_move_when_occupied(self):
+ inv = inventory()
+ inv['listeners']['entries'] = [
+ {'port': 9000, 'process': 'existing-fpm'},
+ {'port': 9078, 'process': 'existing-admin'},
+ ]
+ plan = build_plan(inv)
+ ports = _planned_ports(inv, plan, 'isolated')
+ self.assertNotEqual(ports['php_fpm'], 9000)
+ self.assertNotEqual(ports['management'], 9078)
+ self.assertEqual(len(set(ports.values())), len(ports))
+
def test_generated_config_has_empty_tv_allowlist(self):
text = render_config('10.1.10.14', {
'tomcat_http': 8080, 'tomcat_https': 8443,
@@ -90,9 +102,12 @@ def test_host_apache_fragment_is_scoped_and_does_not_include_host_sites(self):
callback_base_url='http://10.1.10.14:8080',
permitted_ranges=('127.0.0.0/8',), allowed_tvs=(),
)
- text = render_apache(config)
+ from cmnd_linux.native_config import NativeLayout
+ text = render_apache(config, layout=NativeLayout(fpm_port=9100, management_port=9178))
self.assertIn('# Managed by CMND Linux 0.8.', text)
self.assertIn('Listen 10.1.10.14:8082', text)
+ self.assertIn('127.0.0.1:9100', text)
+ self.assertIn('127.0.0.1:9178', text)
self.assertNotIn('IncludeOptional sites-enabled', text)
self.assertNotIn('ports.conf', text)
From 904718e3a2af49a00dacd08c2bf752c9695599fb Mon Sep 17 00:00:00 2001
From: Tommy Heggie <42516199+MusicCityTelecom@users.noreply.github.com>
Date: Tue, 22 Sep 2026 20:51:14 -0500
Subject: [PATCH 40/52] Add bounded shared-database fresh-install rollback
---
src/cmnd_linux/shared_database.py | 17 +++++++++++++++++
1 file changed, 17 insertions(+)
diff --git a/src/cmnd_linux/shared_database.py b/src/cmnd_linux/shared_database.py
index e92de5a3..0347c004 100644
--- a/src/cmnd_linux/shared_database.py
+++ b/src/cmnd_linux/shared_database.py
@@ -145,6 +145,23 @@ def validate_for_fresh_cmnd(self) -> dict:
return {'compatible': True, 'namespace_clear': True, 'tcp_loopback_reachable': True,
'changes_performed': False, 'compatibility': compatibility}
+ def rollback_fresh(self) -> dict:
+ """Remove only the fixed CMND namespaces from a failed fresh install.
+
+ Callers may use this only after this session successfully passed the
+ namespace-clear gate and created the fresh CMND objects.
+ """
+ removed_users: list[str] = []
+ removed_schemas: list[str] = []
+ for _schema, user, _folder, _numbers in reversed(SCHEMA_SPECS):
+ for host in reversed(APP_HOSTS):
+ self.execute(f'DROP USER IF EXISTS {_sql_string(user)}@{_sql_string(host)};', timeout=20)
+ removed_users.append(f'{user}@{host}')
+ for schema, _user, _folder, _numbers in reversed(SCHEMA_SPECS):
+ self.execute(f'DROP DATABASE IF EXISTS `{schema}`;', timeout=60)
+ removed_schemas.append(schema)
+ return {'users_removed': removed_users, 'schemas_removed': removed_schemas}
+
def initialize(self, vendor: Path, values: Mapping[str, str]) -> dict:
self.validate_for_fresh_cmnd()
vendor = Path(vendor)
From f57f00a470f576b5744736b0e73cbf25e5f08f86 Mon Sep 17 00:00:00 2001
From: Tommy Heggie <42516199+MusicCityTelecom@users.noreply.github.com>
Date: Tue, 22 Sep 2026 20:51:17 -0500
Subject: [PATCH 41/52] Rollback fresh shared DB namespace on activation
failure
---
src/cmnd_linux/coexist_deploy.py | 23 ++++++++++++++++++++---
1 file changed, 20 insertions(+), 3 deletions(-)
diff --git a/src/cmnd_linux/coexist_deploy.py b/src/cmnd_linux/coexist_deploy.py
index a8abefbe..9d6d0198 100644
--- a/src/cmnd_linux/coexist_deploy.py
+++ b/src/cmnd_linux/coexist_deploy.py
@@ -169,7 +169,7 @@ def deploy(i:CoexistInputs,*,execute=False,accept_legacy=False):
if os.name!='posix' or not hasattr(os,'geteuid') or os.geteuid()!=0 or not accept_legacy:
raise ConfigError('root Linux execution and legacy-runtime acceptance required')
import pwd
- os.umask(0o077); STATE.mkdir(mode=0o700); host_apache=False
+ os.umask(0o077); STATE.mkdir(mode=0o700); host_apache=False; shared_initialized=False
try:
values={k:secrets.token_hex(24) for k in (*REQUIRED_SECRETS,'tpvision_db_password')}; write_new(STATE/'secrets.json',json.dumps(values)); write_new(STATE/'certificate-password',values['cert_ca_password'])
addresses=json.loads(run('ip','-j','-4','address','show')); ips=sorted({a['local'] for x in addresses if 'UP' in x.get('flags',[]) for a in x.get('addr_info',[]) if a.get('family')=='inet'}); public,_=native_endpoint(c)
@@ -203,8 +203,13 @@ def deploy(i:CoexistInputs,*,execute=False,accept_legacy=False):
units=_units(i.java_home,i.database_mode,i.apache_mode,i.apt_managed)
for name,text in units.items():write_new(Path('/etc/systemd/system')/name,text,0o644)
run('systemctl','daemon-reload'); run('systemctl','enable','--now','cmnd-egress'); apply_policy(policy,execute=True)
- if i.database_mode=='isolated':_isolated_db(i,c,values)
- else: report['shared_database_initialization']=i.shared_database.initialize(i.vendor,values); write_health_files(values,c.database_port); wait_shared_database()
+ if i.database_mode=='isolated':
+ _isolated_db(i,c,values)
+ else:
+ report['shared_database_initialization']=i.shared_database.initialize(i.vendor,values)
+ shared_initialized=True
+ write_health_files(values,c.database_port)
+ wait_shared_database()
adminpass=_admin(i)
write_new(STATE/'initial-admin.json',json.dumps({'username':'admin','password':adminpass}))
from .update_gui import password_record
@@ -242,5 +247,17 @@ def deploy(i:CoexistInputs,*,execute=False,accept_legacy=False):
if host_apache:
try:apache_detach(execute=True)
except Exception:pass
+ if shared_initialized and i.shared_database is not None:
+ try:
+ report['shared_database_rollback']=i.shared_database.rollback_fresh()
+ health=Path('/etc/cmnd/shared-database')
+ if health.is_dir() and not health.is_symlink():
+ shutil.rmtree(health)
+ except Exception as rollback_error:
+ try:
+ write_new(STATE/'SHARED_DATABASE_ROLLBACK_FAILED',
+ 'Fresh shared-database rollback failed; inspect the exact CMND namespaces before retry.\n')
+ except Exception:
+ pass
if not (STATE/'FAILED').exists():write_new(STATE/'FAILED','Incomplete 0.8 coexistence deployment; preserve state and inspect private logs.\n')
raise
From 9635eca8d2aa6dd19566a552697cd4783de46791 Mon Sep 17 00:00:00 2001
From: Tommy Heggie <42516199+MusicCityTelecom@users.noreply.github.com>
Date: Tue, 22 Sep 2026 20:52:07 -0500
Subject: [PATCH 42/52] Accept recognized 0.8 deployment markers on tooling
upgrade
---
packaging/debian/postinst | 12 +++++++++---
1 file changed, 9 insertions(+), 3 deletions(-)
diff --git a/packaging/debian/postinst b/packaging/debian/postinst
index 25c2934d..e76b87a3 100644
--- a/packaging/debian/postinst
+++ b/packaging/debian/postinst
@@ -17,14 +17,20 @@ if [ -e /etc/cmnd/deployment.json ] || [ -L /etc/cmnd/deployment.json ]; then
import json, pathlib, sys
p=pathlib.Path("/etc/cmnd/deployment.json")
safe=p.is_file() and not p.is_symlink() and p.stat().st_uid==0 and not p.stat().st_mode & 0o022 and p.stat().st_size<65536
-sys.exit(0 if safe and json.loads(p.read_text()).get("managed_by")=="linux-cmnd-native" else 1)
+data=json.loads(p.read_text())
+managed=data.get("managed_by") in {"linux-cmnd-native","linux-cmnd-apt","linux-cmnd-coexist"}
+sys.exit(0 if safe and managed and data.get("state")=="active" else 1)
'
else
CMND_CONFIG=/etc/cmnd/cmnd.toml PYTHONPATH="/opt/linux-cmnd/releases/$VERSION/src" \
python3 -m cmnd_linux render-runtime-config --output /etc/cmnd --execute
fi
for rendered in tomcat.env apache.env compose.env; do
- chown root:cmnd "/etc/cmnd/$rendered"
- chmod 0640 "/etc/cmnd/$rendered"
+ path="/etc/cmnd/$rendered"
+ if [ -e "$path" ] || [ -L "$path" ]; then
+ [ -f "$path" ] && [ ! -L "$path" ] || { echo "Unsafe CMND rendered config: $path" >&2; exit 1; }
+ chown root:cmnd "$path"
+ chmod 0640 "$path"
+ fi
done
exit 0
From c7d7414c49ed1bb7f2ff7736adca2e04320c8159 Mon Sep 17 00:00:00 2001
From: Tommy Heggie <42516199+MusicCityTelecom@users.noreply.github.com>
Date: Tue, 22 Sep 2026 20:52:22 -0500
Subject: [PATCH 43/52] Regress recognized APT deployment preservation
---
tests/test_package_config_preservation.py | 10 ++++++++--
1 file changed, 8 insertions(+), 2 deletions(-)
diff --git a/tests/test_package_config_preservation.py b/tests/test_package_config_preservation.py
index 8abf049d..7f730d32 100644
--- a/tests/test_package_config_preservation.py
+++ b/tests/test_package_config_preservation.py
@@ -19,7 +19,7 @@ def guard(self, root):
def test_native_upgrade_preserves_operator_environments(self):
with tempfile.TemporaryDirectory(prefix='cmnd-package-') as directory:
root = Path(directory)
- (root / 'deployment.json').write_text(json.dumps({'managed_by': 'linux-cmnd-native'}))
+ (root / 'deployment.json').write_text(json.dumps({'managed_by': 'linux-cmnd-native', 'state': 'active'}))
for name in ('tomcat.env', 'apache.env', 'compose.env'):
(root / name).write_text('operator supplied value\n')
before = {p.name: p.read_bytes() for p in root.iterdir()}
@@ -27,11 +27,17 @@ def test_native_upgrade_preserves_operator_environments(self):
self.assertEqual(result.returncode, 0, result.stderr)
self.assertEqual(before, {p.name: p.read_bytes() for p in root.iterdir()})
+ def test_apt_managed_upgrade_marker_is_accepted(self):
+ with tempfile.TemporaryDirectory(prefix='cmnd-package-') as directory:
+ root = Path(directory)
+ (root / 'deployment.json').write_text(json.dumps({'managed_by': 'linux-cmnd-apt', 'state': 'active'}))
+ self.assertEqual(self.guard(root).returncode, 0)
+
def test_unrecognized_or_symlink_marker_is_rejected(self):
with tempfile.TemporaryDirectory(prefix='cmnd-package-') as directory:
root = Path(directory)
marker = root / 'deployment.json'
- marker.write_text(json.dumps({'managed_by': 'unrecognized'}))
+ marker.write_text(json.dumps({'managed_by': 'unrecognized', 'state': 'active'}))
self.assertNotEqual(self.guard(root).returncode, 0)
marker.rename(root / 'other.json')
marker.symlink_to(root / 'other.json')
From dbcd2b6688fb6a5dddd07c77f2cbfeb992e5ec77 Mon Sep 17 00:00:00 2001
From: Tommy Heggie <42516199+MusicCityTelecom@users.noreply.github.com>
Date: Tue, 22 Sep 2026 20:53:10 -0500
Subject: [PATCH 44/52] Make Ubuntu 22.04 source probe informational
---
.github/workflows/0.8-development-ci.yml | 3 ++-
1 file changed, 2 insertions(+), 1 deletion(-)
diff --git a/.github/workflows/0.8-development-ci.yml b/.github/workflows/0.8-development-ci.yml
index 11fe5331..4c08f842 100644
--- a/.github/workflows/0.8-development-ci.yml
+++ b/.github/workflows/0.8-development-ci.yml
@@ -35,7 +35,8 @@ jobs:
run: python -m unittest discover -s tests -v
ubuntu-22-source-compat:
- name: Ubuntu 22.04 / Python 3.10 source compatibility
+ name: Ubuntu 22.04 / Python 3.10 source compatibility (informational)
+ continue-on-error: true
runs-on: ubuntu-22.04
steps:
- name: Check out 0.8 source
From 5fdea40a15d530c2bf9876d2302de86cb0f9c865 Mon Sep 17 00:00:00 2001
From: Tommy Heggie <42516199+MusicCityTelecom@users.noreply.github.com>
Date: Tue, 22 Sep 2026 20:54:41 -0500
Subject: [PATCH 45/52] Tighten shared MySQL compatibility gate
---
src/cmnd_linux/database_compatibility.py | 15 ++++++++++++++-
1 file changed, 14 insertions(+), 1 deletion(-)
diff --git a/src/cmnd_linux/database_compatibility.py b/src/cmnd_linux/database_compatibility.py
index aa367dc9..df5596df 100644
--- a/src/cmnd_linux/database_compatibility.py
+++ b/src/cmnd_linux/database_compatibility.py
@@ -14,7 +14,7 @@
REQUIRED_CASE_MODE = '1'
REQUIRED_VARIABLES = (
- 'lower_case_table_names', 'event_scheduler', 'sql_mode', 'character_set_server',
+ 'lower_case_table_names', 'event_scheduler', 'local_infile', 'sql_mode', 'character_set_server',
'collation_server', 'max_allowed_packet', 'read_only',
)
@@ -76,6 +76,19 @@ def assess(version: str, variables: Mapping[str, str]) -> DatabaseCompatibility:
if read_only in {'1', 'ON', 'TRUE', 'YES'}:
reasons.append('server is read-only')
+ event_scheduler = normalized.get('event_scheduler', '').upper()
+ if event_scheduler not in {'ON', '1'}:
+ reasons.append('event_scheduler must already be ON; CMND will not change a shared server global setting')
+
+ local_infile = normalized.get('local_infile', '').upper()
+ if local_infile not in {'OFF', '0'}:
+ reasons.append('local_infile must already be OFF for the reviewed shared-server profile')
+
+ sql_mode = normalized.get('sql_mode', '')
+ modes = {item.strip().upper() for item in sql_mode.split(',') if item.strip()}
+ if modes != {'NO_ENGINE_SUBSTITUTION'}:
+ reasons.append('sql_mode must already match the reviewed NO_ENGINE_SUBSTITUTION profile')
+
if family == 'mysql' and version.startswith('5.7.'):
qualification = 'matches-current-qualified-family'
elif family in {'mysql', 'mariadb'}:
From 2b205445a29a395181954530f6eb2dea32ba8209 Mon Sep 17 00:00:00 2001
From: Tommy Heggie <42516199+MusicCityTelecom@users.noreply.github.com>
Date: Tue, 22 Sep 2026 20:54:50 -0500
Subject: [PATCH 46/52] Regress full shared MySQL global compatibility profile
---
tests/test_database_compatibility.py | 11 +++++++++++
1 file changed, 11 insertions(+)
diff --git a/tests/test_database_compatibility.py b/tests/test_database_compatibility.py
index 9f40faa4..20c2de3a 100644
--- a/tests/test_database_compatibility.py
+++ b/tests/test_database_compatibility.py
@@ -8,6 +8,7 @@
COMPATIBLE_VARIABLES = {
'lower_case_table_names': '1',
'event_scheduler': 'ON',
+ 'local_infile': 'OFF',
'sql_mode': 'NO_ENGINE_SUBSTITUTION',
'character_set_server': 'latin1',
'collation_server': 'latin1_swedish_ci',
@@ -35,6 +36,16 @@ def test_case_mode_zero_is_never_silently_changed_on_existing_server(self):
self.assertTrue(any('changing it on an existing populated server is unsafe' in reason
for reason in result.reasons))
+ def test_shared_server_global_profile_must_already_match(self):
+ for key, value, fragment in (
+ ('event_scheduler', 'OFF', 'event_scheduler'),
+ ('local_infile', 'ON', 'local_infile'),
+ ('sql_mode', 'STRICT_TRANS_TABLES,NO_ENGINE_SUBSTITUTION', 'sql_mode'),
+ ):
+ result = assess('5.7.44', dict(COMPATIBLE_VARIABLES, **{key: value}))
+ self.assertFalse(result.compatible)
+ self.assertTrue(any(fragment in reason for reason in result.reasons))
+
def test_mysql8_requires_separate_shared_database_qualification(self):
result = assess('8.0.43', COMPATIBLE_VARIABLES)
self.assertFalse(result.compatible)
From a14b1e3a96c70964b97455ab605325fbe773a3e4 Mon Sep 17 00:00:00 2001
From: Tommy Heggie <42516199+MusicCityTelecom@users.noreply.github.com>
Date: Tue, 22 Sep 2026 20:55:13 -0500
Subject: [PATCH 47/52] Gate 0.8 installer and maintainer-script syntax in CI
---
.github/workflows/0.8-development-ci.yml | 5 +++++
1 file changed, 5 insertions(+)
diff --git a/.github/workflows/0.8-development-ci.yml b/.github/workflows/0.8-development-ci.yml
index 4c08f842..7f4575b2 100644
--- a/.github/workflows/0.8-development-ci.yml
+++ b/.github/workflows/0.8-development-ci.yml
@@ -62,6 +62,11 @@ jobs:
uses: actions/setup-python@v5
with:
python-version: '3.12'
+ - name: Validate installer source and maintainer scripts
+ run: |
+ python -m compileall -q src scripts
+ sh -n packaging/debian/preinst packaging/debian/postinst packaging/debian/prerm packaging/debian/postrm packaging/debian/cmndctl
+ sh -n packaging/cmnd-linux/config packaging/cmnd-linux/postinst packaging/cmnd-linux/prerm packaging/cmnd-linux/postrm
- name: Build payload and user-facing meta packages
env:
PYTHONPATH: src
From 096ea4b6546872f5c45ef3ab81331b3e994e0905 Mon Sep 17 00:00:00 2001
From: Tommy Heggie <42516199+MusicCityTelecom@users.noreply.github.com>
Date: Tue, 22 Sep 2026 20:56:35 -0500
Subject: [PATCH 48/52] Smoke-install generated 0.8 packages on Ubuntu 24.04
---
.github/workflows/0.8-development-ci.yml | 33 ++++++++++++++++++++++++
1 file changed, 33 insertions(+)
diff --git a/.github/workflows/0.8-development-ci.yml b/.github/workflows/0.8-development-ci.yml
index 7f4575b2..2adb10cb 100644
--- a/.github/workflows/0.8-development-ci.yml
+++ b/.github/workflows/0.8-development-ci.yml
@@ -75,6 +75,39 @@ jobs:
python scripts/build_meta_deb.py
dpkg-deb -I dist/linux-cmnd_0.8.0_amd64.deb
dpkg-deb -I dist/cmnd-linux_0.8.0_all.deb
+ - name: Smoke-install generated packages without runtime activation
+ shell: bash
+ run: |
+ set -euo pipefail
+ make_stub() {
+ name="$1"; version="$2"
+ root="$(mktemp -d)"
+ mkdir -p "$root/DEBIAN"
+ cat >"$root/DEBIAN/control" <
+ Description: CI dependency stub only
+ EOF
+ dpkg-deb --build "$root" "dist/${name}_${version}_all.deb" >/dev/null
+ rm -rf "$root"
+ }
+ make_stub cmnd-vendor-759 7.5.9-1
+ make_stub cmnd-tomcat9 9.0.121-1
+ sudo env DEBIAN_FRONTEND=noninteractive apt-get update
+ sudo env DEBIAN_FRONTEND=noninteractive apt-get install -y \
+ ./dist/linux-cmnd_0.8.0_amd64.deb \
+ ./dist/cmnd-vendor-759_7.5.9-1_all.deb \
+ ./dist/cmnd-tomcat9_9.0.121-1_all.deb \
+ ./dist/cmnd-linux_0.8.0_all.deb
+ test "$(dpkg-query -W -f='${Status}' cmnd-linux)" = "install ok installed"
+ test -x /usr/bin/cmndctl
+ test ! -e /var/lib/cmnd-deployment
+ sudo env DEBIAN_FRONTEND=noninteractive apt-get remove -y cmnd-linux
+ test ! -e /var/lib/cmnd-deployment
safety-diff:
name: Frozen 0.7.1 ancestry check
From cce87d56c9eb8b803be22f8cb306699f0c4821d9 Mon Sep 17 00:00:00 2001
From: Tommy Heggie <42516199+MusicCityTelecom@users.noreply.github.com>
Date: Tue, 22 Sep 2026 20:58:02 -0500
Subject: [PATCH 49/52] Add repeatable full Ubuntu 24.04 test-bundle build
---
.github/workflows/0.8-full-build.yml | 79 ++++++++++++++++++++++++++++
1 file changed, 79 insertions(+)
create mode 100644 .github/workflows/0.8-full-build.yml
diff --git a/.github/workflows/0.8-full-build.yml b/.github/workflows/0.8-full-build.yml
new file mode 100644
index 00000000..cb3e3623
--- /dev/null
+++ b/.github/workflows/0.8-full-build.yml
@@ -0,0 +1,79 @@
+name: 0.8 Full Ubuntu 24.04 Build
+
+on:
+ push:
+ branches:
+ - develop/0.8.0
+ workflow_dispatch:
+
+permissions:
+ contents: read
+
+jobs:
+ build:
+ name: Build 0.8 Ubuntu 24.04 test bundle
+ runs-on: ubuntu-24.04
+ steps:
+ - name: Check out exact 0.8 source
+ uses: actions/checkout@v4
+ with:
+ fetch-depth: 0
+
+ - name: Set up Python 3.12
+ uses: actions/setup-python@v5
+ with:
+ python-version: '3.12'
+
+ - name: Install release-build tools
+ run: |
+ sudo apt-get update
+ sudo apt-get install -y --no-install-recommends ca-certificates curl
+
+ - name: Download pinned Philips and Tomcat inputs
+ shell: bash
+ run: |
+ set -euo pipefail
+ curl --fail --location --proto '=https' --proto-redir '=https' --tlsv1.2 \
+ --retry 3 --output /tmp/cmnd-vendor-7.5.9.zip \
+ https://github.com/MusicCityTelecom/linux-cmnd/releases/download/v0.7.1/cmnd-vendor-7.5.9.zip
+ curl --fail --location --proto '=https' --proto-redir '=https' --tlsv1.2 \
+ --retry 3 --output /tmp/apache-tomcat-9.0.121.tar.gz \
+ https://archive.apache.org/dist/tomcat/tomcat-9/v9.0.121/bin/apache-tomcat-9.0.121.tar.gz
+
+ - name: Verify inputs and build all APT packages
+ env:
+ PYTHONPATH: src
+ run: |
+ python - <<'PY'
+ from pathlib import Path
+ import sys
+ sys.path.insert(0, 'scripts')
+ from vendor_bundle import verify
+ print(verify(Path('/tmp/cmnd-vendor-7.5.9.zip')))
+ PY
+ python scripts/build_release.py \
+ --vendor-bundle /tmp/cmnd-vendor-7.5.9.zip \
+ --tomcat-archive /tmp/apache-tomcat-9.0.121.tar.gz
+ dpkg-deb -I dist/linux-cmnd_0.8.0_amd64.deb
+ dpkg-deb -I dist/cmnd-linux_0.8.0_all.deb
+ dpkg-deb -I dist/cmnd-vendor-759_7.5.9-1_all.deb
+ dpkg-deb -I dist/cmnd-tomcat9_9.0.121-1_all.deb
+ sha256sum \
+ dist/linux-cmnd_0.8.0_amd64.deb \
+ dist/cmnd-linux_0.8.0_all.deb \
+ dist/cmnd-vendor-759_7.5.9-1_all.deb \
+ dist/cmnd-tomcat9_9.0.121-1_all.deb \
+ > dist/SHA256SUMS-APT
+
+ - name: Upload Ubuntu 24.04 test bundle
+ uses: actions/upload-artifact@v4
+ with:
+ name: cmnd-linux-0.8.0-ubuntu24-test
+ retention-days: 14
+ if-no-files-found: error
+ path: |
+ dist/linux-cmnd_0.8.0_amd64.deb
+ dist/cmnd-linux_0.8.0_all.deb
+ dist/cmnd-vendor-759_7.5.9-1_all.deb
+ dist/cmnd-tomcat9_9.0.121-1_all.deb
+ dist/SHA256SUMS-APT
From 8e06fa23cbb0b111d0aeada5e938e66d8b1a1162 Mon Sep 17 00:00:00 2001
From: Tommy Heggie <42516199+MusicCityTelecom@users.noreply.github.com>
Date: Tue, 22 Sep 2026 21:01:33 -0500
Subject: [PATCH 50/52] Add Ubuntu 24.04 operator test guide for 0.8
---
docs/0.8.0-UBUNTU-24.04-TEST.md | 242 ++++++++++++++++++++++++++++++++
1 file changed, 242 insertions(+)
create mode 100644 docs/0.8.0-UBUNTU-24.04-TEST.md
diff --git a/docs/0.8.0-UBUNTU-24.04-TEST.md b/docs/0.8.0-UBUNTU-24.04-TEST.md
new file mode 100644
index 00000000..ca013165
--- /dev/null
+++ b/docs/0.8.0-UBUNTU-24.04-TEST.md
@@ -0,0 +1,242 @@
+# CMND Linux 0.8.0 — Ubuntu 24.04 Test Guide
+
+This guide is for the isolated **0.8.0 development line** only. The published
+`v0.7.1` release remains the frozen working reference and is not modified by
+0.8 development.
+
+## Test target
+
+Use a disposable or dedicated Ubuntu Server **24.04 LTS amd64** host.
+
+Recommended minimums:
+
+- 6 GiB RAM
+- 40 GiB disk, with at least 10 GiB free under `/var/lib`
+- stable IPv4 address on the TV-management LAN
+- working DNS and Internet access during dependency/container preparation
+- sudo/root access
+
+Do not begin with a machine that already contains a CMND deployment. Existing
+Apache/nginx, Docker, and MySQL/MariaDB services are acceptable because 0.8
+inventories them and plans coexistence before activation.
+
+## What the 0.8 APT bundle contains
+
+The test bundle contains four Debian packages:
+
+```text
+linux-cmnd_0.8.0_amd64.deb
+cmnd-vendor-759_7.5.9-1_all.deb
+cmnd-tomcat9_9.0.121-1_all.deb
+cmnd-linux_0.8.0_all.deb
+```
+
+`cmnd-linux` is the user-facing installation package. It requires the exact
+matching tooling package, the hash-verified Philips CMND 7.5.9 inputs, and the
+pinned Tomcat 9.0.121 archive.
+
+The Philips inputs remain outside Git source history. The vendor package is
+generated only from the exact input set already verified by the project.
+
+## Before activation
+
+After the tooling package is installed, these commands are read-only:
+
+```sh
+sudo cmndctl environment
+sudo cmndctl plan-install
+```
+
+The environment report inventories web/database/runtime services and listeners.
+The plan does not modify the host.
+
+The planner preserves unrelated listeners. CMND prefers its historical ports
+when free and moves only CMND-owned listeners when necessary:
+
+- Tomcat HTTP: 8080
+- Tomcat HTTPS: 8443
+- SmartCMS/Apache HTTP: 8082
+- SmartCMS/Apache HTTPS: 8444
+- database: 3306
+- private PHP-FPM: 9000
+- private management UI: 9078
+
+## Installing the four-package test bundle
+
+From the directory containing all four packages:
+
+```sh
+sudo apt update
+sudo apt install \
+ ./linux-cmnd_0.8.0_amd64.deb \
+ ./cmnd-vendor-759_7.5.9-1_all.deb \
+ ./cmnd-tomcat9_9.0.121-1_all.deb \
+ ./cmnd-linux_0.8.0_all.deb
+```
+
+The package configuration asks for:
+
+1. Server IPv4 address. `auto` prefers the IPv4 source selected by the host's
+ default route.
+2. Database mode:
+ - `auto` — reuse an existing database only if it already passes the strict
+ shared-server gate; otherwise use the isolated MySQL 5.7 runtime.
+ - `existing` — require a compatible existing database and refuse fallback.
+ - `isolated` — leave any host database alone and use the qualified isolated
+ MySQL 5.7 runtime.
+3. Database administrator user/password only when required for an existing
+ database. The password is transferred through a root-only temporary file and
+ cleared from debconf after the activation attempt.
+4. Apache mode:
+ - `auto` — use an already-running supported Debian/Ubuntu Apache service via
+ one CMND-owned configuration fragment; otherwise use standalone CMND Apache.
+ - `host` — require host Apache.
+ - `standalone` — do not attach CMND to the host Apache service.
+5. Explicit acceptance of the legacy PHP 5.6 / MySQL 5.7 compatibility profile.
+
+If legacy-runtime acceptance is not granted, the packages install but CMND is
+not activated. Activation can then be revisited through package reconfiguration.
+
+## Existing MySQL/MariaDB safety
+
+0.8 does **not** change server-wide database settings to make an unrelated
+database service compatible.
+
+Automatic shared-database reuse currently requires the already-qualified
+MySQL 5.7 family and the reviewed global profile, including:
+
+- `lower_case_table_names=1`
+- `event_scheduler=ON`
+- `local_infile=OFF`
+- reviewed `sql_mode=NO_ENGINE_SUBSTITUTION`
+- server not read-only
+- no existing CMND schema/user namespace
+
+MariaDB and MySQL 8 remain unqualified as shared CMND databases. In `auto`
+mode they are preserved and CMND uses its isolated database fallback.
+
+A failed fresh shared-database activation removes only the fixed CMND schemas and
+application accounts that the same fresh transaction created. It does not alter
+unrelated schemas/users.
+
+## Existing Apache/nginx safety
+
+When reusing a supported host Apache installation, CMND owns only:
+
+```text
+/etc/apache2/conf-available/cmnd-linux.conf
+```
+
+The installer does not replace `apache2.conf`, `ports.conf`, or unrelated
+sites. It config-tests Apache before relying on the fragment and removes its own
+fragment on a failed attach.
+
+An existing nginx installation is preserved. If Apache is not being reused,
+CMND runs its own standalone Apache process on CMND-owned listeners.
+
+## First-install network safety
+
+A fresh APT-generated configuration starts with:
+
+```toml
+[safety]
+permitted_ranges = ["127.0.0.0/8"]
+
+[tv]
+allowlist = []
+```
+
+Installing CMND does not authorize a physical TV for write operations. Keep the
+TV allowlist empty until server/browser qualification has passed and the first
+physical-TV procedure is intentionally started.
+
+## Expected first-start duration
+
+The Java applications can have a long cold start. Previous qualification on a
+6 GiB VM observed startup taking roughly 11 minutes. Do not assume installation
+failed only because vendor pages are not immediately available.
+
+## Verification after installation
+
+Start with:
+
+```sh
+sudo cmndctl environment
+sudo cmndctl native-health --seconds 900
+sudo systemctl --no-pager --full status \
+ cmnd-egress.service \
+ cmnd-php.service \
+ cmnd-tomcat.service \
+ cmnd-admin.service
+```
+
+If the isolated database/standalone Apache path was selected, also check:
+
+```sh
+sudo systemctl --no-pager --full status cmnd-mysql.service cmnd-apache.service
+```
+
+If host Apache was selected:
+
+```sh
+sudo apache2ctl configtest
+sudo systemctl --no-pager --full status apache2.service
+```
+
+Confirm the deployment marker:
+
+```sh
+sudo cat /etc/cmnd/deployment.json
+```
+
+A successful APT-managed activation should identify itself as
+`linux-cmnd-apt` with state `active`.
+
+## Initial administrator credentials
+
+The first generated administrator credentials are root-readable at:
+
+```text
+/var/lib/cmnd-deployment/initial-admin.json
+```
+
+Treat this file as a secret. Do not paste it into issue reports or commit it.
+
+## Evidence and troubleshooting
+
+Useful state/log locations include:
+
+```text
+/etc/cmnd/
+/var/lib/cmnd-deployment/
+/var/log/cmnd/
+/var/cache/linux-cmnd/bootstrap/php-build.log
+```
+
+If activation fails, preserve `/var/lib/cmnd-deployment` and the private logs
+before changing anything. A failed deployment intentionally stops CMND
+application services rather than trying to hide partial state.
+
+## Package removal
+
+Removing `cmnd-linux` stops/disables CMND-owned services and detaches the
+CMND-owned host-Apache fragment when present. Package removal deliberately
+retains CMND data, configuration, certificates, logs and database state.
+
+Do not use package removal as a data-erasure operation.
+
+## Scope of this test
+
+For 0.8 right now:
+
+- Ubuntu 24.04 amd64 is the primary test target.
+- Ubuntu 22.04/Python 3.10 is an informational compatibility lane, not a supported
+ APT target yet.
+- Ubuntu 26.04 remains unqualified.
+- Docker/Compose rendering exists but host-network physical-TV discovery/control
+ is not yet qualified.
+- RF/DekTec/modulator and remaining Windows-only MGate-dependent workflows are
+ not implied to be complete by a successful APT installation.
+
+A successful package/source CI run is not a replacement for this clean-host
+runtime test with the actual vendor payload.
From 5f3df26660663ca5c495808036341a2cc39e5be2 Mon Sep 17 00:00:00 2001
From: Tommy Heggie <42516199+MusicCityTelecom@users.noreply.github.com>
Date: Tue, 22 Sep 2026 21:01:37 -0500
Subject: [PATCH 51/52] Record completed 0.8 APT integration gates
---
CHANGELOG.md | 14 ++++++++++++++
1 file changed, 14 insertions(+)
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 552fec13..8d4af3e1 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -21,6 +21,20 @@
are never repository inputs.
- Added branch-only CI for Ubuntu and Windows source regressions, package-build
smoke tests and verification that 0.8 remains descended from exact `v0.7.1`.
+- Completed the four-package APT transaction model: `linux-cmnd`,
+ `cmnd-vendor-759`, `cmnd-tomcat9` and user-facing `cmnd-linux`. Ubuntu
+ 24.04 CI now executes maintainer-script syntax checks and a real non-activating
+ `apt-get install`/remove smoke test of the generated packages.
+- Main and private CMND listeners are collision-aware. Historical ports remain
+ the defaults, while Tomcat, SmartCMS/Apache, isolated database, PHP-FPM and
+ management listeners move only when the host already owns those ports.
+- Existing shared MySQL reuse now requires the reviewed MySQL 5.7 global profile
+ to be present already; CMND does not alter unrelated server-wide settings.
+ Failed fresh shared-database activation has bounded rollback for only the CMND
+ schemas/accounts created by that transaction.
+- Added a repeatable Ubuntu 24.04 full-build workflow that consumes the verified
+ Philips 7.5.9 release bundle and pinned Tomcat archive and emits the four
+ development test packages as one Actions artifact.
- Ubuntu 24.04 remains the qualified runtime baseline. Ubuntu 22.04 and 26.04 are
development targets and must be separately qualified before being called
supported. Docker/Compose production deployment remains a later 0.8 milestone.
From a5b468fde56feeca97e04fce203dfe47384a9cd1 Mon Sep 17 00:00:00 2001
From: Tommy Heggie <42516199+MusicCityTelecom@users.noreply.github.com>
Date: Tue, 22 Sep 2026 21:01:43 -0500
Subject: [PATCH 52/52] Document isolated 0.8 Ubuntu 24.04 test path
---
README.md | 15 +++++++++++++++
1 file changed, 15 insertions(+)
diff --git a/README.md b/README.md
index 95e24a6c..1d18e03f 100644
--- a/README.md
+++ b/README.md
@@ -9,6 +9,21 @@ Windows/Linux database table-name case compatibility for fresh installs. Existin
installs need the explicit, backed-up [database case repair](docs/DATABASE-CASE.md)
after updating the tooling. Do not delete or re-upload your packages to fix this.
+## 0.8.0 development
+
+Version 0.8.0 is being developed independently from the frozen `v0.7.1`
+release. The current development target is Ubuntu 24.04 amd64 and adds an
+environment-aware APT installation path, existing-service coexistence planning,
+collision-aware CMND ports, a verified four-package dependency graph, and a
+separate Docker/Compose candidate.
+
+For the current Ubuntu 24.04 test procedure, package behavior, safety defaults
+and post-install checks, see
+[the 0.8 Ubuntu 24.04 test guide](docs/0.8.0-UBUNTU-24.04-TEST.md).
+
+Ubuntu 22.04 and 26.04 are not yet release-qualified for the 0.8 APT path.
+Published `v0.7.1` assets remain unchanged.
+
## Quick installation
Start with the [complete Ubuntu 24.04 walkthrough](docs/UBUNTU-24.04.md), including