mirror of
https://github.com/ChuckBuilds/LEDMatrix.git
synced 2026-08-21 10:29:06 +00:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
6642a78d0e |
@@ -1,85 +0,0 @@
|
|||||||
"""A check that could not run must not be reported as "up to date".
|
|
||||||
|
|
||||||
check-update returned update_available=False whenever git failed. The banner
|
|
||||||
is the only route to the update button, so a checkout git refuses to touch
|
|
||||||
looked exactly like a current one -- permanently, and with nothing for the
|
|
||||||
user to act on. The usual cause is an install performed as root, after which
|
|
||||||
every git command fails with "detected dubious ownership".
|
|
||||||
"""
|
|
||||||
import subprocess
|
|
||||||
import sys
|
|
||||||
from pathlib import Path
|
|
||||||
from unittest.mock import patch
|
|
||||||
|
|
||||||
import pytest
|
|
||||||
from flask import Flask
|
|
||||||
|
|
||||||
sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
|
|
||||||
|
|
||||||
from web_interface.blueprints import api_v3 as mod # noqa: E402
|
|
||||||
from web_interface.blueprints.api_v3 import api_v3 # noqa: E402
|
|
||||||
|
|
||||||
DUBIOUS = ("fatal: detected dubious ownership in repository at "
|
|
||||||
"'/home/pi/LEDMatrix'\nTo add an exception for this directory, call:\n"
|
|
||||||
"\tgit config --global --add safe.directory /home/pi/LEDMatrix\n")
|
|
||||||
|
|
||||||
|
|
||||||
@pytest.fixture
|
|
||||||
def client():
|
|
||||||
app = Flask(__name__)
|
|
||||||
app.config['TESTING'] = True
|
|
||||||
app.register_blueprint(api_v3, url_prefix='/api/v3')
|
|
||||||
mod._update_check_cache['result'] = None
|
|
||||||
mod._update_check_cache['ts'] = 0
|
|
||||||
return app.test_client()
|
|
||||||
|
|
||||||
|
|
||||||
def _fetch_fails(stderr: bytes):
|
|
||||||
def fake_run(args, **kwargs):
|
|
||||||
if args[:2] == ['git', 'fetch']:
|
|
||||||
return subprocess.CompletedProcess(args, 1, stdout=b'', stderr=stderr)
|
|
||||||
return subprocess.CompletedProcess(args, 0, stdout='', stderr='')
|
|
||||||
return fake_run
|
|
||||||
|
|
||||||
|
|
||||||
class TestFailedCheckIsNotSilence:
|
|
||||||
def test_dubious_ownership_is_reported_not_swallowed(self, client):
|
|
||||||
with patch.object(mod.subprocess, 'run', _fetch_fails(DUBIOUS.encode())):
|
|
||||||
data = client.get('/api/v3/system/check-update').get_json()
|
|
||||||
assert data['check_failed'] is True, (
|
|
||||||
"a git failure was reported as a successful 'no update' check")
|
|
||||||
assert data['update_available'] is False
|
|
||||||
|
|
||||||
def test_the_message_tells_the_user_what_to_do(self, client):
|
|
||||||
with patch.object(mod.subprocess, 'run', _fetch_fails(DUBIOUS.encode())):
|
|
||||||
data = client.get('/api/v3/system/check-update').get_json()
|
|
||||||
assert 'chown' in data['error'], (
|
|
||||||
"dubious ownership is unactionable without the fix command")
|
|
||||||
assert 'root' in data['error']
|
|
||||||
|
|
||||||
def test_an_ordinary_git_failure_still_surfaces(self, client):
|
|
||||||
with patch.object(mod.subprocess, 'run',
|
|
||||||
_fetch_fails(b'fatal: some other git problem\n')):
|
|
||||||
data = client.get('/api/v3/system/check-update').get_json()
|
|
||||||
assert data['check_failed'] is True
|
|
||||||
assert 'some other git problem' in data['error']
|
|
||||||
|
|
||||||
def test_offline_reads_as_offline(self, client):
|
|
||||||
with patch.object(mod.subprocess, 'run',
|
|
||||||
_fetch_fails(b'fatal: could not resolve host: github.com\n')):
|
|
||||||
data = client.get('/api/v3/system/check-update').get_json()
|
|
||||||
assert 'Could not reach GitHub' in data['error']
|
|
||||||
|
|
||||||
|
|
||||||
class TestSuccessPathUnchanged:
|
|
||||||
def test_up_to_date_carries_no_failure_flag(self, client):
|
|
||||||
def fake_run(args, **kwargs):
|
|
||||||
if args[:2] == ['git', 'fetch']:
|
|
||||||
return subprocess.CompletedProcess(args, 0, stdout=b'', stderr=b'')
|
|
||||||
if args[:2] == ['git', 'rev-parse']:
|
|
||||||
return subprocess.CompletedProcess(args, 0, stdout='abc123\n', stderr='')
|
|
||||||
return subprocess.CompletedProcess(args, 0, stdout='0\n', stderr='')
|
|
||||||
with patch.object(mod.subprocess, 'run', fake_run):
|
|
||||||
data = client.get('/api/v3/system/check-update').get_json()
|
|
||||||
assert data['update_available'] is False
|
|
||||||
assert not data.get('check_failed'), "a healthy check must not look like a failure"
|
|
||||||
@@ -0,0 +1,84 @@
|
|||||||
|
"""A pull that changed nothing on the running system is not an applied update.
|
||||||
|
|
||||||
|
git_pull replaces files on disk and restarts nothing -- there is no systemctl
|
||||||
|
call anywhere in the handler. The display and web services keep running the
|
||||||
|
code they loaded at boot, so the user is told "Code updated successfully" and
|
||||||
|
sees no change until they happen to reboot. The response now says whether a
|
||||||
|
restart is owed, and the UI raises the existing restart-pending banner.
|
||||||
|
"""
|
||||||
|
import subprocess
|
||||||
|
import sys
|
||||||
|
from pathlib import Path
|
||||||
|
from unittest.mock import patch
|
||||||
|
|
||||||
|
import pytest
|
||||||
|
from flask import Flask
|
||||||
|
|
||||||
|
sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
|
||||||
|
|
||||||
|
from web_interface.blueprints import api_v3 as mod # noqa: E402
|
||||||
|
from web_interface.blueprints.api_v3 import api_v3 # noqa: E402
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.fixture
|
||||||
|
def client():
|
||||||
|
app = Flask(__name__)
|
||||||
|
app.config['TESTING'] = True
|
||||||
|
app.register_blueprint(api_v3, url_prefix='/api/v3')
|
||||||
|
# The handler consults these after a successful pull; None is the
|
||||||
|
# "not wired up" case it already guards for.
|
||||||
|
api_v3.plugin_store_manager = None
|
||||||
|
api_v3.config_manager = None
|
||||||
|
return app.test_client()
|
||||||
|
|
||||||
|
|
||||||
|
def _git(heads, pull_rc=0, pull_out='Updating a1b2c3..d4e5f6\n'):
|
||||||
|
"""Fake git. `heads` are the successive answers to rev-parse HEAD."""
|
||||||
|
seq = list(heads)
|
||||||
|
|
||||||
|
def run(args, **kwargs):
|
||||||
|
def ok(stdout='', rc=0, b=False):
|
||||||
|
return subprocess.CompletedProcess(
|
||||||
|
args, rc, stdout=(stdout.encode() if b else stdout),
|
||||||
|
stderr=(b'' if b else ''))
|
||||||
|
if args[:2] == ['git', 'rev-parse'] and args[-1] == 'HEAD':
|
||||||
|
return ok(seq.pop(0) + '\n' if seq else 'deadbeef\n')
|
||||||
|
if 'symbolic-full-name' in args or '@{u}' in args:
|
||||||
|
return ok('origin/main\n')
|
||||||
|
if args[:2] == ['git', 'status']:
|
||||||
|
return ok('')
|
||||||
|
if args[:2] == ['git', 'diff']:
|
||||||
|
return ok('')
|
||||||
|
if args[:2] == ['git', 'pull']:
|
||||||
|
return ok(pull_out, pull_rc)
|
||||||
|
return ok('')
|
||||||
|
return run
|
||||||
|
|
||||||
|
|
||||||
|
def _pull(client):
|
||||||
|
return client.post('/api/v3/system/action',
|
||||||
|
json={'action': 'git_pull'}).get_json()
|
||||||
|
|
||||||
|
|
||||||
|
class TestRestartIsRequestedWhenCodeChanged:
|
||||||
|
def test_a_pull_that_moved_head_asks_for_a_restart(self, client):
|
||||||
|
with patch.object(mod.subprocess, 'run', _git(['aaa111', 'bbb222'])):
|
||||||
|
data = _pull(client)
|
||||||
|
assert data['status'] == 'success'
|
||||||
|
assert data['restart_required'] is True, (
|
||||||
|
"new code on disk, services still running the old code, and "
|
||||||
|
"nothing told the user to restart")
|
||||||
|
|
||||||
|
def test_already_up_to_date_does_not(self, client):
|
||||||
|
with patch.object(mod.subprocess, 'run',
|
||||||
|
_git(['aaa111', 'aaa111'], pull_out='Already up to date.\n')):
|
||||||
|
data = _pull(client)
|
||||||
|
assert data['status'] == 'success'
|
||||||
|
assert data['restart_required'] is False, (
|
||||||
|
"prompting after a no-op update trains users to ignore the prompt")
|
||||||
|
|
||||||
|
def test_a_failed_pull_does_not(self, client):
|
||||||
|
with patch.object(mod.subprocess, 'run', _git(['aaa111'], pull_rc=1)):
|
||||||
|
data = _pull(client)
|
||||||
|
assert data['status'] == 'error'
|
||||||
|
assert data['restart_required'] is False
|
||||||
@@ -1821,33 +1821,6 @@ def get_system_version():
|
|||||||
_update_check_cache: Dict[str, Any] = {'result': None, 'ts': 0.0}
|
_update_check_cache: Dict[str, Any] = {'result': None, 'ts': 0.0}
|
||||||
_UPDATE_CHECK_TTL = 300 # 5 minutes — avoids a git fetch on every page load
|
_UPDATE_CHECK_TTL = 300 # 5 minutes — avoids a git fetch on every page load
|
||||||
|
|
||||||
def _update_check_failed(detail: str) -> Dict[str, Any]:
|
|
||||||
"""A check that could not run is not the same as being up to date.
|
|
||||||
|
|
||||||
Reporting update_available=False on a git failure hides the banner, and
|
|
||||||
the banner is the only route to the update button -- so a checkout git
|
|
||||||
refuses to touch looks exactly like a current one, permanently. The most
|
|
||||||
common cause is an install performed as root: git then reports "dubious
|
|
||||||
ownership" and every command fails, including the fetch here.
|
|
||||||
"""
|
|
||||||
return {'update_available': False, 'remote_sha': 'unknown',
|
|
||||||
'commits_behind': 0, 'check_failed': True, 'error': detail}
|
|
||||||
|
|
||||||
|
|
||||||
def _describe_git_failure(stderr: str) -> str:
|
|
||||||
"""Turn git's stderr into something the user can act on."""
|
|
||||||
text = (stderr or '').strip()
|
|
||||||
if 'dubious ownership' in text or 'detected dubious ownership' in text:
|
|
||||||
return ("This checkout is owned by a different user than the one "
|
|
||||||
"running the web interface, so git refuses to use it. It is "
|
|
||||||
"usually the result of installing as root. Fix the ownership "
|
|
||||||
"and the update will work: sudo chown -R $USER:$USER "
|
|
||||||
+ str(PROJECT_ROOT))
|
|
||||||
if 'could not resolve host' in text.lower() or 'network is unreachable' in text.lower():
|
|
||||||
return "Could not reach GitHub to check for updates."
|
|
||||||
return "Could not check for updates: " + (text.splitlines()[0] if text else "git failed")
|
|
||||||
|
|
||||||
|
|
||||||
@api_v3.route('/system/check-update', methods=['GET'])
|
@api_v3.route('/system/check-update', methods=['GET'])
|
||||||
def check_for_update():
|
def check_for_update():
|
||||||
"""Check whether a newer LEDMatrix commit is available on origin/main."""
|
"""Check whether a newer LEDMatrix commit is available on origin/main."""
|
||||||
@@ -1863,13 +1836,12 @@ def check_for_update():
|
|||||||
capture_output=True, timeout=10, cwd=cwd,
|
capture_output=True, timeout=10, cwd=cwd,
|
||||||
)
|
)
|
||||||
if fetch_result.returncode != 0:
|
if fetch_result.returncode != 0:
|
||||||
stderr = fetch_result.stderr.decode(errors='replace').strip()
|
|
||||||
logger.warning("check-update: git fetch failed (rc=%d): %s",
|
logger.warning("check-update: git fetch failed (rc=%d): %s",
|
||||||
fetch_result.returncode, stderr)
|
fetch_result.returncode,
|
||||||
failed = _update_check_failed(_describe_git_failure(stderr))
|
fetch_result.stderr.decode(errors='replace').strip())
|
||||||
_update_check_cache['result'] = failed
|
_update_check_cache['result'] = _safe
|
||||||
_update_check_cache['ts'] = now
|
_update_check_cache['ts'] = now
|
||||||
return jsonify(failed)
|
return jsonify(_safe)
|
||||||
local = subprocess.run(
|
local = subprocess.run(
|
||||||
['git', 'rev-parse', 'HEAD'],
|
['git', 'rev-parse', 'HEAD'],
|
||||||
capture_output=True, text=True, timeout=5, cwd=cwd,
|
capture_output=True, text=True, timeout=5, cwd=cwd,
|
||||||
@@ -1897,8 +1869,7 @@ def check_for_update():
|
|||||||
return jsonify(result)
|
return jsonify(result)
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
logger.warning("check-update failed: %s", e)
|
logger.warning("check-update failed: %s", e)
|
||||||
return jsonify(_update_check_failed(
|
return jsonify(_safe)
|
||||||
"Could not check for updates; see logs for details."))
|
|
||||||
|
|
||||||
@api_v3.route('/system/action', methods=['POST'])
|
@api_v3.route('/system/action', methods=['POST'])
|
||||||
def execute_system_action():
|
def execute_system_action():
|
||||||
@@ -2025,6 +1996,11 @@ def execute_system_action():
|
|||||||
except subprocess.TimeoutExpired:
|
except subprocess.TimeoutExpired:
|
||||||
logger.warning("git rev-parse timed out before pull")
|
logger.warning("git rev-parse timed out before pull")
|
||||||
|
|
||||||
|
# Whether the pull actually brought new code in. "Already up to
|
||||||
|
# date" is a success too, and prompting for a restart then would
|
||||||
|
# train users to ignore the prompt.
|
||||||
|
code_changed = False
|
||||||
|
|
||||||
# Perform the git pull. Branches without an upstream were given
|
# Perform the git pull. Branches without an upstream were given
|
||||||
# an explicit "origin <branch>" above so the update still works.
|
# an explicit "origin <branch>" above so the update still works.
|
||||||
result = subprocess.run(
|
result = subprocess.run(
|
||||||
@@ -2068,6 +2044,7 @@ def execute_system_action():
|
|||||||
capture_output=True, text=True, timeout=10, cwd=project_dir)
|
capture_output=True, text=True, timeout=10, cwd=project_dir)
|
||||||
new_head = _post.stdout.strip() if _post.returncode == 0 else None
|
new_head = _post.stdout.strip() if _post.returncode == 0 else None
|
||||||
if old_head and new_head and old_head != new_head:
|
if old_head and new_head and old_head != new_head:
|
||||||
|
code_changed = True
|
||||||
diff = subprocess.run(
|
diff = subprocess.run(
|
||||||
['git', 'diff', '--name-only', f'{old_head}..{new_head}'],
|
['git', 'diff', '--name-only', f'{old_head}..{new_head}'],
|
||||||
capture_output=True, text=True, timeout=15, cwd=project_dir)
|
capture_output=True, text=True, timeout=15, cwd=project_dir)
|
||||||
@@ -2127,9 +2104,14 @@ def execute_system_action():
|
|||||||
if ln.strip()), '')
|
if ln.strip()), '')
|
||||||
pull_message = f"Update failed: {detail}" if detail else "Update failed; check logs for details"
|
pull_message = f"Update failed: {detail}" if detail else "Update failed; check logs for details"
|
||||||
|
|
||||||
|
# Nothing here restarts anything: the pull replaces files on
|
||||||
|
# disk while the display and web services keep running the code
|
||||||
|
# they loaded at boot. Without this the user is told the update
|
||||||
|
# succeeded and sees no change until they happen to reboot.
|
||||||
return jsonify({
|
return jsonify({
|
||||||
'status': 'success' if result.returncode == 0 else 'error',
|
'status': 'success' if result.returncode == 0 else 'error',
|
||||||
'message': pull_message,
|
'message': pull_message,
|
||||||
|
'restart_required': bool(result.returncode == 0 and code_changed),
|
||||||
})
|
})
|
||||||
elif action == 'checkout_branch':
|
elif action == 'checkout_branch':
|
||||||
# Switch branches from the Tools tab. Needed because a checkout
|
# Switch branches from the Tools tab. Needed because a checkout
|
||||||
|
|||||||
@@ -116,14 +116,25 @@ document.body.addEventListener('htmx:afterRequest', function(event) {
|
|||||||
// ===== Restart-pending banner =====
|
// ===== Restart-pending banner =====
|
||||||
// Shown after restart-requiring saves; persists across tab switches (and
|
// Shown after restart-requiring saves; persists across tab switches (and
|
||||||
// reloads, via sessionStorage) until the display restarts or it's dismissed.
|
// reloads, via sessionStorage) until the display restarts or it's dismissed.
|
||||||
window.showRestartPending = function() {
|
window.showRestartPending = function(message) {
|
||||||
try { sessionStorage.setItem('ledmatrix-restart-pending', '1'); } catch { /* private browsing */ }
|
try {
|
||||||
|
sessionStorage.setItem('ledmatrix-restart-pending', '1');
|
||||||
|
// Persisted alongside the flag: a code update and a config save want
|
||||||
|
// different wording, and the banner outlives the page that raised it.
|
||||||
|
if (message) sessionStorage.setItem('ledmatrix-restart-pending-text', message);
|
||||||
|
else sessionStorage.removeItem('ledmatrix-restart-pending-text');
|
||||||
|
} catch { /* private browsing */ }
|
||||||
const banner = document.getElementById('restart-pending-banner');
|
const banner = document.getElementById('restart-pending-banner');
|
||||||
|
const text = document.getElementById('restart-pending-text');
|
||||||
|
if (text && message) text.textContent = message;
|
||||||
if (banner) banner.style.display = 'block';
|
if (banner) banner.style.display = 'block';
|
||||||
};
|
};
|
||||||
|
|
||||||
window.dismissRestartPending = function() {
|
window.dismissRestartPending = function() {
|
||||||
try { sessionStorage.removeItem('ledmatrix-restart-pending'); } catch { /* no-op */ }
|
try {
|
||||||
|
sessionStorage.removeItem('ledmatrix-restart-pending');
|
||||||
|
sessionStorage.removeItem('ledmatrix-restart-pending-text');
|
||||||
|
} catch { /* no-op */ }
|
||||||
const banner = document.getElementById('restart-pending-banner');
|
const banner = document.getElementById('restart-pending-banner');
|
||||||
if (banner) banner.style.display = 'none';
|
if (banner) banner.style.display = 'none';
|
||||||
};
|
};
|
||||||
@@ -151,6 +162,9 @@ document.addEventListener('DOMContentLoaded', function() {
|
|||||||
try {
|
try {
|
||||||
if (sessionStorage.getItem('ledmatrix-restart-pending') === '1') {
|
if (sessionStorage.getItem('ledmatrix-restart-pending') === '1') {
|
||||||
const banner = document.getElementById('restart-pending-banner');
|
const banner = document.getElementById('restart-pending-banner');
|
||||||
|
const saved = sessionStorage.getItem('ledmatrix-restart-pending-text');
|
||||||
|
const text = document.getElementById('restart-pending-text');
|
||||||
|
if (text && saved) text.textContent = saved;
|
||||||
if (banner) banner.style.display = 'block';
|
if (banner) banner.style.display = 'block';
|
||||||
}
|
}
|
||||||
} catch { /* no-op */ }
|
} catch { /* no-op */ }
|
||||||
|
|||||||
@@ -413,7 +413,8 @@
|
|||||||
<div class="flex items-center justify-between">
|
<div class="flex items-center justify-between">
|
||||||
<div class="flex items-center space-x-3">
|
<div class="flex items-center space-x-3">
|
||||||
<i class="fas fa-rotate text-lg"></i>
|
<i class="fas fa-rotate text-lg"></i>
|
||||||
<span class="text-sm font-medium" aria-live="polite">
|
<span class="text-sm font-medium" aria-live="polite"
|
||||||
|
id="restart-pending-text">
|
||||||
Configuration saved — restart the display to apply the changes
|
Configuration saved — restart the display to apply the changes
|
||||||
</span>
|
</span>
|
||||||
</div>
|
</div>
|
||||||
@@ -1107,29 +1108,15 @@
|
|||||||
fetch('/api/v3/system/check-update')
|
fetch('/api/v3/system/check-update')
|
||||||
.then(function(r) { return r.json(); })
|
.then(function(r) { return r.json(); })
|
||||||
.then(function(data) {
|
.then(function(data) {
|
||||||
var banner = document.getElementById('update-banner');
|
|
||||||
var btn = document.getElementById('update-banner-btn');
|
|
||||||
if (data.check_failed) {
|
|
||||||
// A check that could not run is not the same as being up
|
|
||||||
// to date. Hiding the banner here made a checkout git
|
|
||||||
// refuses to touch look permanently current, with no
|
|
||||||
// route to the update button and nothing to act on.
|
|
||||||
document.getElementById('update-banner-text').textContent =
|
|
||||||
data.error || 'Could not check for updates.';
|
|
||||||
if (btn) btn.style.display = 'none';
|
|
||||||
banner.style.display = '';
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
if (btn) btn.style.display = '';
|
|
||||||
if (data.update_available && getDismissedSha() !== data.remote_sha) {
|
if (data.update_available && getDismissedSha() !== data.remote_sha) {
|
||||||
var n = data.commits_behind || 0;
|
var n = data.commits_behind || 0;
|
||||||
var msg = 'A new LEDMatrix update is available';
|
var msg = 'A new LEDMatrix update is available';
|
||||||
if (n > 0) msg += ' (' + n + ' commit' + (n > 1 ? 's' : '') + ')';
|
if (n > 0) msg += ' (' + n + ' commit' + (n > 1 ? 's' : '') + ')';
|
||||||
document.getElementById('update-banner-text').textContent = msg;
|
document.getElementById('update-banner-text').textContent = msg;
|
||||||
banner.style.display = '';
|
document.getElementById('update-banner').style.display = '';
|
||||||
try { sessionStorage.setItem('update-sha', data.remote_sha); } catch(e) {}
|
try { sessionStorage.setItem('update-sha', data.remote_sha); } catch(e) {}
|
||||||
} else {
|
} else {
|
||||||
banner.style.display = 'none';
|
document.getElementById('update-banner').style.display = 'none';
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
.catch(function() {});
|
.catch(function() {});
|
||||||
@@ -1160,6 +1147,13 @@
|
|||||||
if (data.status === 'success') {
|
if (data.status === 'success') {
|
||||||
document.getElementById('update-banner').style.display = 'none';
|
document.getElementById('update-banner').style.display = 'none';
|
||||||
try { sessionStorage.removeItem('update-sha-dismissed'); } catch(e) {}
|
try { sessionStorage.removeItem('update-sha-dismissed'); } catch(e) {}
|
||||||
|
// The pull replaced files on disk; the running services still
|
||||||
|
// hold the code they loaded at boot. Ask for the restart that
|
||||||
|
// makes the update actually take effect.
|
||||||
|
if (data.restart_required && typeof window.showRestartPending === 'function') {
|
||||||
|
window.showRestartPending(
|
||||||
|
'Update installed \u2014 restart the display to run the new code');
|
||||||
|
}
|
||||||
}
|
}
|
||||||
if (typeof showNotification === 'function') {
|
if (typeof showNotification === 'function') {
|
||||||
showNotification(data.message || 'Update complete', data.status || 'success');
|
showNotification(data.message || 'Update complete', data.status || 'success');
|
||||||
|
|||||||
Reference in New Issue
Block a user