diff --git a/homeassistant-addon/CHANGELOG.md b/homeassistant-addon/CHANGELOG.md index 6f65b348..dea16b0e 100644 --- a/homeassistant-addon/CHANGELOG.md +++ b/homeassistant-addon/CHANGELOG.md @@ -11,6 +11,12 @@ If this add-on saves you time, you can [buy me a coffee](https://buymeacoffee.co Releases before 1.22.0 are in the [changelog archive](https://github.com/dougrathbone/cgateweb/blob/master/homeassistant-addon/CHANGELOG-archive.md). +## [1.40.3](https://github.com/dougrathbone/cgateweb/releases/tag/v1.40.3) - 2026-11-14 + +### Fixed + +- **A project saved by an older C-Gate now loads after upgrading managed C-Gate to 3.8.0.** The add-on migrates the database when C-Gate refuses it, and keeps a copy beside the original. ([#174](https://github.com/dougrathbone/cgateweb/issues/174)) + ## [1.40.2](https://github.com/dougrathbone/cgateweb/releases/tag/v1.40.2) - 2026-11-14 ### Fixed diff --git a/homeassistant-addon/DOCS.md b/homeassistant-addon/DOCS.md index de93b11d..24929783 100644 --- a/homeassistant-addon/DOCS.md +++ b/homeassistant-addon/DOCS.md @@ -505,6 +505,8 @@ If it persists on a current version, the project genuinely has no synchronised u **If the network stays Closed after you click Open Network:** current C-Bus Toolkit needs C-Gate 3.8.0. The add-on's built-in download is 3.3.2, which answers `OriginateInProject` with 402 and Toolkit leaves the network Closed even though the interface is running and Home Assistant can control it. Download C-Gate 3.8.0 from Clipsal, place the zip in `/share/cgate/`, and restart. If C-Gate install source is left unset, a zip in that folder is what gets installed. Set it to upload if you previously chose download. Turn on Force C-Gate Reinstall for one restart if C-Gate is already installed, then turn it off again (#122). +**If C-Gate 3.8.0 is running but the project never loads:** a project last saved by an older C-Gate has to be migrated before 3.8.0 will open it, and until then every command fails with "network not found". From 1.40.3 the add-on runs that migration when C-Gate refuses the database, and keeps a copy of it next to the original (`HOME.db.before-schema-migrate` for a project named HOME). Restart the add-on once after upgrading (#174). + > **Remember what mapping this port means.** C-Gate has no authentication beyond the address list, and `program` sits above `admin` in its access levels, so it also permits shutting C-Gate down. Map to a single specific address, never a subnet, and never expose it to the internet. ## Finding Your C-Bus Network ID diff --git a/homeassistant-addon/config.yaml b/homeassistant-addon/config.yaml index d1e89117..6db6d1fb 100644 --- a/homeassistant-addon/config.yaml +++ b/homeassistant-addon/config.yaml @@ -1,5 +1,5 @@ name: "C-Gate Web Bridge" -version: "1.40.2" +version: "1.40.3" slug: cgateweb description: "Bridge between Clipsal C-Bus systems and MQTT/Home Assistant" url: "https://github.com/dougrathbone/cgateweb" diff --git a/homeassistant-addon/rootfs/etc/services.d/cgateweb/run b/homeassistant-addon/rootfs/etc/services.d/cgateweb/run index 0b83ae65..1151c841 100755 --- a/homeassistant-addon/rootfs/etc/services.d/cgateweb/run +++ b/homeassistant-addon/rootfs/etc/services.d/cgateweb/run @@ -24,6 +24,12 @@ if [[ "${CGATE_MODE}" == "managed" ]]; then done bashio::log.info "C-Gate is ready" + # Issue #174: C-Gate 3.8.0 will not load a project database written by + # 3.3.x until TRANSFORM MIGRATE_SQL runs. Do that before the bridge + # starts, so it does not spend the boot sending commands at a project + # that was never loaded. The script exits 0 unless it is interrupted. + cgateweb-migrate-project || true + # ALPHA (issue #28): when the opt-in cgate_serial_device is configured, # dump what C-Gate sees (PORT LIST / IFLIST) into the log. Backgrounded: # the nc query can block up to its -w timeout and diagnostics must not diff --git a/homeassistant-addon/rootfs/usr/bin/cgateweb-migrate-project b/homeassistant-addon/rootfs/usr/bin/cgateweb-migrate-project new file mode 100755 index 00000000..92d51ad6 --- /dev/null +++ b/homeassistant-addon/rootfs/usr/bin/cgateweb-migrate-project @@ -0,0 +1,150 @@ +#!/usr/bin/with-contenv bashio +# ============================================================================== +# Migrate a managed C-Gate project database when this C-Gate cannot load it. +# +# C-Gate 3.8.0 rejects a project last written by 3.3.x with: +# 408 ... SchemaVersion is 13 and must be 14 - perform a TRANSFORM MIGRATE_SQL +# and then every bridge command fails because the project never starts (#174). +# The command that fixes it is `transform migrate_sql `, followed by +# project load, use and start. This script does that, and only that. +# +# It must never break add-on startup. A query failure, a project that is +# already started, or a load error that is not the schema mismatch all exit 0. +# ============================================================================== +set -euo pipefail + +CGATE_MODE=$(bashio::config 'cgate_mode' 'remote') +if [[ "${CGATE_MODE}" != "managed" ]]; then + exit 0 +fi + +PROJECT=$(bashio::config 'cgate_project' 'HOME') +if [[ "${PROJECT}" == "null" || -z "${PROJECT}" ]]; then + PROJECT="HOME" +fi +# Same rule as cgate-install.sh. The name is sent as a C-Gate command argument +# and used as a directory name, so anything else is refused rather than escaped. +if [[ ! "${PROJECT}" =~ ^[A-Za-z0-9_]{1,32}$ ]]; then + bashio::log.warning "cgate_project is not a usable project name; skipping schema migration" + exit 0 +fi + +if [[ -n "${CGATEWEB_CGATE_PORT:-}" ]]; then + CGATE_PORT="${CGATEWEB_CGATE_PORT}" +else + CGATE_PORT=$(bashio::config 'cgate_port' '20023') +fi +CGATE_HOST="${CGATEWEB_CGATE_HOST:-127.0.0.1}" +CGATE_DIR="${CGATE_DIR:-/data/cgate}" +POLLS="${CGATEWEB_MIGRATE_POLLS:-4}" +POLL_INTERVAL="${CGATEWEB_MIGRATE_POLL_INTERVAL:-2}" + +# One C-Gate command, response body only (the 201 greeting is discarded). +# Tests set CGATEWEB_CGATE_QUERY to a program that reads the command on stdin. +# Production uses bash /dev/tcp, which the integration probe already relies on. +_cgate_query() { + local cmd="$1" + if [[ -n "${CGATEWEB_CGATE_QUERY:-}" ]]; then + printf '%s\n' "${cmd}" | "${CGATEWEB_CGATE_QUERY}" 2>&1 || true + return 0 + fi + # shellcheck disable=SC2016 + timeout 8 bash -c ' + host="$1"; port="$2"; cmd="$3" + exec 3<>"/dev/tcp/${host}/${port}" || exit 1 + IFS= read -r -t 3 -u 3 _greeting || true + printf "%s\r\n" "${cmd}" >&3 + while IFS= read -r -t 5 -u 3 line; do + printf "%s\n" "${line}" + [[ "${line}" =~ ^[0-9]{3}[[:space:]] ]] && break + done + ' bash "${CGATE_HOST}" "${CGATE_PORT}" "${cmd}" 2>&1 || true +} + +# project list lines look like "project=HOME state=started" (integration test +# asserts that form). Anything else for this project (loading, loaded) is left +# alone: project load would change a project that is already coming up. +_project_state() { + local out="$1" + if [[ "${out}" == *"project=${PROJECT} state=started"* ]]; then + printf 'started' + elif [[ "${out}" == *"project=${PROJECT} state=stopped"* || "${out}" == *"project=${PROJECT} state=failed"* ]]; then + printf 'stopped' + elif [[ "${out}" == *"project=${PROJECT} state="* ]]; then + printf 'other' + else + printf 'missing' + fi +} + +_is_schema_mismatch() { + [[ "$1" == *SchemaVersion* && "$1" == *MIGRATE_SQL* ]] +} + +_response_ok() { + [[ "$1" =~ (^|[^0-9])2[0-9]{2}[[:space:]] ]] +} + +list_out="" +state="missing" +poll=0 +while [[ "${poll}" -lt "${POLLS}" ]]; do + poll=$((poll + 1)) + list_out=$(_cgate_query "project list") + list_out="${list_out//$'\r'/}" + state=$(_project_state "${list_out}") + [[ "${state}" == "started" ]] && exit 0 + [[ "${state}" == "stopped" ]] && break + [[ "${poll}" -lt "${POLLS}" ]] && sleep "${POLL_INTERVAL}" +done + +if [[ -z "${list_out//[[:space:]]/}" ]]; then + bashio::log.warning "Could not query C-Gate project list; skipping schema migration" + exit 0 +fi + +# A project that is loading or already loaded is not this bug. Only a stopped +# project, or one missing after the wait, is asked to load — that is when +# 3.8.0 returns the schema error instead of starting the project. +if [[ "${state}" != "stopped" && "${state}" != "missing" ]]; then + exit 0 +fi + +load_out=$(_cgate_query "project load ${PROJECT}") +load_out="${load_out//$'\r'/}" +if ! _is_schema_mismatch "${load_out}"; then + exit 0 +fi + +db="${CGATE_DIR}/Projects/${PROJECT}/${PROJECT}.db" +backup="${db}.before-schema-migrate" +if [[ ! -f "${db}" ]]; then + bashio::log.warning "C-Gate cannot load project ${PROJECT} (database schema is too old) but ${db} is not there, so it was not migrated" + exit 0 +fi +if [[ ! -f "${backup}" ]]; then + if ! cp -p "${db}" "${backup}"; then + bashio::log.warning "Could not copy ${db} before migrating it; leaving the project database unchanged" + exit 0 + fi + bashio::log.info "Saved a copy of project ${PROJECT} as ${backup}" +fi + +bashio::log.warning "C-Gate refused to load project ${PROJECT} because its database schema is older than this C-Gate. Migrating it." +migrate_out=$(_cgate_query "transform migrate_sql ${PROJECT}") +migrate_out="${migrate_out//$'\r'/}" +if ! _response_ok "${migrate_out}"; then + bashio::log.warning "Schema migration for project ${PROJECT} failed. The copy from before the attempt is ${backup}" + exit 0 +fi + +_cgate_query "project load ${PROJECT}" >/dev/null +_cgate_query "project use ${PROJECT}" >/dev/null +start_out=$(_cgate_query "project start ${PROJECT}") +start_out="${start_out//$'\r'/}" +if _response_ok "${start_out}"; then + bashio::log.info "Project ${PROJECT} was migrated and started." +else + bashio::log.warning "Project ${PROJECT} was migrated but did not start. The copy from before the migration is ${backup}" +fi +exit 0 diff --git a/package-lock.json b/package-lock.json index a08f4f57..372bd862 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "cgateweb", - "version": "1.40.2", + "version": "1.40.3", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "cgateweb", - "version": "1.40.2", + "version": "1.40.3", "license": "MIT", "dependencies": { "adm-zip": "^0.6.1", diff --git a/package.json b/package.json index 5b24118d..c5fddbc1 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "cgateweb", - "version": "1.40.2", + "version": "1.40.3", "description": "Node.js bridge connecting Clipsal C-Bus automation systems to MQTT for Home Assistant integration", "keywords": [ "cbus", diff --git a/tests/cgateMigrateProject.test.js b/tests/cgateMigrateProject.test.js new file mode 100644 index 00000000..36c4cb75 --- /dev/null +++ b/tests/cgateMigrateProject.test.js @@ -0,0 +1,257 @@ +const { execFileSync } = require('child_process'); +const fs = require('fs'); +const os = require('os'); +const path = require('path'); +const { posixBashAvailable } = require('./helpers/posixBash'); +const { BASHIO_STUB_WITH_LOGS } = require('./helpers/bashioStub'); +const { addonBin, addonPath } = require('./helpers/addonPaths'); + +const describeBash = posixBashAvailable() ? describe : describe.skip; + +const SCRIPT = addonBin('cgateweb-migrate-project'); +const RUN_SCRIPT = addonPath('etc', 'services.d', 'cgateweb', 'run'); + +const SCHEMA_ERROR = '408 Operation failed: Project load failed: Error reading db file: Incompatible project: SchemaVersion is 13 and must be 14 - perform a TRANSFORM MIGRATE_SQL command to fix this'; + +// Reads the C-Gate command on stdin, records it, and answers from CGW_RESPONSES +// (one response per line of the file, consumed in order). A response of "-" is +// an empty reply. +const QUERY_STUB = `#!/usr/bin/env bash +cmd=$(cat) +printf '%s\\n' "$cmd" >> "$CGW_CMDS" +resp=$(head -n 1 "$CGW_RESPONSES") +if [[ -n "$resp" ]]; then + tail -n +2 "$CGW_RESPONSES" > "$CGW_RESPONSES.next" + mv "$CGW_RESPONSES.next" "$CGW_RESPONSES" +fi +if [[ "$resp" != "-" ]]; then + printf '%s\\n' "$resp" +fi +exit 0 +`; + +function runMigrate({ config = {}, responses = [], extraEnv = {}, withDb = false, backupContents = null } = {}) { + const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'cgw-migrate-')); + const bin = path.join(dir, 'bin'); + fs.mkdirSync(bin); + fs.writeFileSync(path.join(bin, 'cgate-query'), QUERY_STUB, { mode: 0o755 }); + const responsesFile = path.join(dir, 'responses.txt'); + fs.writeFileSync(responsesFile, responses.join('\n') + (responses.length ? '\n' : '')); + const cgateDir = path.join(dir, 'cgate'); + if (withDb) { + const projectDir = path.join(cgateDir, 'Projects', 'HOME'); + fs.mkdirSync(projectDir, { recursive: true }); + fs.writeFileSync(path.join(projectDir, 'HOME.db'), 'original-database'); + if (backupContents !== null) { + fs.writeFileSync(path.join(projectDir, 'HOME.db.before-schema-migrate'), backupContents); + } + } + const env = { + ...process.env, + PATH: `${bin}${path.delimiter}${process.env.PATH}`, + CGW_MIGRATE_SCRIPT: SCRIPT, + CGW_CMDS: path.join(dir, 'cmds.txt'), + CGW_RESPONSES: responsesFile, + CGATEWEB_CGATE_QUERY: path.join(bin, 'cgate-query'), + CGATE_DIR: cgateDir, + CGATEWEB_MIGRATE_POLLS: '2', + CGATEWEB_MIGRATE_POLL_INTERVAL: '0', + ...extraEnv + }; + for (const [key, value] of Object.entries(config)) { + env[`CGW_TEST_${key}`] = value; + } + try { + const output = execFileSync('bash', ['-c', `${BASHIO_STUB_WITH_LOGS}\nsource "$CGW_MIGRATE_SCRIPT"`], { + encoding: 'utf8', + env + }); + return { status: 0, output, dir, cgateDir }; + } catch (error) { + return { + status: error.status, + output: `${error.stdout || ''}${error.stderr || ''}`, + dir, + cgateDir + }; + } +} + +function commands(result) { + const file = path.join(result.dir, 'cmds.txt'); + if (!fs.existsSync(file)) return []; + return fs.readFileSync(file, 'utf8').split('\n').filter(Boolean); +} + +function cleanup(result) { + fs.rmSync(result.dir, { recursive: true, force: true }); +} + +describe('cgateweb service run', () => { + test('migrates a too-old project before the bridge starts', () => { + const run = fs.readFileSync(RUN_SCRIPT, 'utf8'); + expect(run).toMatch(/cgateweb-migrate-project/); + }); +}); + +describeBash('cgateweb-migrate-project (issue #174)', () => { + test('does nothing in remote mode', () => { + const result = runMigrate({ + config: { cgate_mode: 'remote', cgate_project: 'HOME' }, + responses: ['320 project=HOME state=stopped'] + }); + try { + expect(result.status).toBe(0); + expect(commands(result)).toEqual([]); + expect(result.output.trim()).toBe(''); + } finally { + cleanup(result); + } + }); + + test('does nothing when the project is already started', () => { + const result = runMigrate({ + config: { cgate_mode: 'managed', cgate_project: 'HOME' }, + responses: ['320 project=HOME state=started\n200 OK.'] + }); + try { + expect(result.status).toBe(0); + expect(commands(result)).toEqual(['project list']); + } finally { + cleanup(result); + } + }); + + test('does not load a project that is still coming up', () => { + const result = runMigrate({ + config: { cgate_mode: 'managed', cgate_project: 'HOME' }, + responses: [ + '320 project=HOME state=loading', + '320 project=HOME state=loaded' + ] + }); + try { + expect(commands(result)).toEqual(['project list', 'project list']); + expect(result.output).not.toMatch(/Migrating/); + } finally { + cleanup(result); + } + }); + + test('migrates a stopped project whose database schema is too old, and keeps a copy', () => { + const result = runMigrate({ + config: { cgate_mode: 'managed', cgate_project: 'HOME' }, + withDb: true, + responses: [ + '320 project=HOME state=stopped', + SCHEMA_ERROR, + '200 OK.', + '200 OK.', + '200 OK.', + '200 OK.' + ] + }); + try { + expect(result.status).toBe(0); + expect(commands(result)).toEqual([ + 'project list', + 'project load HOME', + 'transform migrate_sql HOME', + 'project load HOME', + 'project use HOME', + 'project start HOME' + ]); + const projectDir = path.join(result.cgateDir, 'Projects', 'HOME'); + expect(fs.readFileSync(path.join(projectDir, 'HOME.db.before-schema-migrate'), 'utf8')).toBe('original-database'); + expect(result.output).toMatch(/Migrating it/); + expect(result.output).toMatch(/migrated and started/); + } finally { + cleanup(result); + } + }); + + test('does not migrate a load failure that is not the schema mismatch', () => { + const result = runMigrate({ + config: { cgate_mode: 'managed', cgate_project: 'HOME' }, + withDb: true, + responses: [ + '320 project=HOME state=stopped', + '408 Operation failed: Project load failed: file is locked' + ] + }); + try { + expect(commands(result)).toEqual(['project list', 'project load HOME']); + expect(fs.existsSync(path.join(result.cgateDir, 'Projects', 'HOME', 'HOME.db.before-schema-migrate'))).toBe(false); + expect(result.output).not.toMatch(/Migrating/); + } finally { + cleanup(result); + } + }); + + test('does not replace a copy saved by an earlier attempt', () => { + const result = runMigrate({ + config: { cgate_mode: 'managed', cgate_project: 'HOME' }, + withDb: true, + backupContents: 'first-copy', + responses: [ + '320 project=HOME state=stopped', + SCHEMA_ERROR, + '408 migration failed' + ] + }); + try { + expect(commands(result)).toEqual([ + 'project list', + 'project load HOME', + 'transform migrate_sql HOME' + ]); + expect(fs.readFileSync(path.join(result.cgateDir, 'Projects', 'HOME', 'HOME.db.before-schema-migrate'), 'utf8')).toBe('first-copy'); + expect(result.output).toMatch(/failed/); + } finally { + cleanup(result); + } + }); + + test('skips the migration when the project database file is missing', () => { + const result = runMigrate({ + config: { cgate_mode: 'managed', cgate_project: 'HOME' }, + responses: [ + '320 project=HOME state=stopped', + SCHEMA_ERROR + ] + }); + try { + expect(commands(result)).toEqual(['project list', 'project load HOME']); + expect(result.output).toMatch(/not there/); + } finally { + cleanup(result); + } + }); + + test('refuses a project name that is not safe to send', () => { + const result = runMigrate({ + config: { cgate_mode: 'managed', cgate_project: 'HOME;quit' } + }); + try { + expect(result.status).toBe(0); + expect(commands(result)).toEqual([]); + expect(result.output).toMatch(/not a usable project name/); + } finally { + cleanup(result); + } + }); + + test('warns and continues when C-Gate does not answer', () => { + const result = runMigrate({ + config: { cgate_mode: 'managed', cgate_project: 'HOME' }, + responses: ['-', '-'] + }); + try { + expect(result.status).toBe(0); + expect(commands(result)).toEqual(['project list', 'project list']); + expect(result.output).toMatch(/Could not query/); + } finally { + cleanup(result); + } + }); +});