mirror of
https://github.com/lrnselfreliance/wrolpi.git
synced 2026-11-19 14:36:22 -05:00
The Settings upgrade can switch to a chosen branch (#954)
* The Settings upgrade can switch to a chosen branch
The Upgrade panel gains a Branch input: a dropdown listing the current
branch, master, and release that also takes a typed branch name.
/api/upgrade/start accepts an optional {"branch": ...}; without it the
current branch is upgraded as before. A branch is written into the systemd
env file and passed to `upgrade.sh -b`, so only plain git branch names are
accepted.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* The Controller upgrade refuses a branch that is not a plain branch name
The Controller's upgrade script wrote its branch straight into the systemd
env file, so a newline in it added a variable, and a leading dash became an
upgrade.sh option. It now accepts the same branch names as the API, and no
script parameter may span lines.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
---------
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
parent
f3f762ef1b
commit
d88db90ce9
10 changed files with 304 additions and 28 deletions
|
|
@ -2226,8 +2226,10 @@ export async function checkUpgrade(force = false) {
|
|||
return null;
|
||||
}
|
||||
|
||||
export async function triggerUpgrade() {
|
||||
const response = await apiPost(`${API_URI}/upgrade/start`);
|
||||
// `branch` upgrades from that branch; without it the current branch is upgraded.
|
||||
export async function triggerUpgrade(branch = null) {
|
||||
const body = branch ? {branch} : undefined;
|
||||
const response = await apiPost(`${API_URI}/upgrade/start`, body);
|
||||
if (!response.ok) {
|
||||
const message = await getErrorMessage(response, 'Failed to start upgrade. See server logs.');
|
||||
toast({
|
||||
|
|
|
|||
|
|
@ -2,6 +2,7 @@ import React, {useContext, useState} from 'react';
|
|||
import {ThemeContext} from '../contexts/contexts';
|
||||
import {
|
||||
ActionInput,
|
||||
Autocomplete,
|
||||
Button,
|
||||
Card,
|
||||
CardGroup,
|
||||
|
|
@ -789,7 +790,11 @@ export function ThemeSamplePage() {
|
|||
<NumberInput label='Depth' description='Follow links this far.'
|
||||
defaultValue={2} min={1} max={4}/>
|
||||
</div>
|
||||
<div style={{marginTop: 12}}>
|
||||
<div style={{marginTop: 12, display: 'grid', gridTemplateColumns: '1fr 2fr', gap: 12}}>
|
||||
{/* A dropdown that also takes a typed value; open it to check the dropdown. */}
|
||||
<Autocomplete label='Branch' description='Choose a branch, or type another.'
|
||||
defaultValue='release' data={['release', 'master']}
|
||||
filter={({options}) => options}/>
|
||||
<Textarea label='Notes' placeholder='Notes about this download…' minRows={2}/>
|
||||
</div>
|
||||
<div style={{marginTop: 12}}>
|
||||
|
|
|
|||
|
|
@ -17,6 +17,7 @@ import {ConfigsTable} from "./Configs";
|
|||
import {navColorHexMap} from "../Vars";
|
||||
import {Link} from "react-router";
|
||||
import {
|
||||
Autocomplete,
|
||||
Button,
|
||||
Divider,
|
||||
Grid,
|
||||
|
|
@ -101,11 +102,34 @@ export function ShutdownButton() {
|
|||
</APIButton>
|
||||
}
|
||||
|
||||
// The branches offered in the upgrade branch picker; any other branch name can be typed.
|
||||
const UPGRADE_BRANCHES = ['master', 'release'];
|
||||
|
||||
export function UpgradeBranchInput({currentBranch, value, onChange, disabled}) {
|
||||
const data = [...new Set([currentBranch, ...UPGRADE_BRANCHES].filter(Boolean))];
|
||||
return <Autocomplete
|
||||
label='Branch'
|
||||
description='Choose a branch, or type the name of another.'
|
||||
data={data}
|
||||
value={value}
|
||||
onChange={onChange}
|
||||
disabled={disabled}
|
||||
// Always list every branch; the typed value is a choice of its own, not a search.
|
||||
filter={({options}) => options}
|
||||
style={{maxWidth: '20em', marginBottom: '1em'}}
|
||||
/>;
|
||||
}
|
||||
|
||||
export function UpgradeSegment() {
|
||||
const {status, fetchStatus, loaded} = React.useContext(StatusContext);
|
||||
const dockerized = useDockerized();
|
||||
const [upgrading, setUpgrading] = React.useState(false);
|
||||
const [checking, setChecking] = React.useState(false);
|
||||
const currentBranch = status?.git_branch;
|
||||
// null until the user picks a branch, so the current branch is shown once status arrives.
|
||||
const [chosenBranch, setChosenBranch] = React.useState(null);
|
||||
const branch = (chosenBranch ?? currentBranch ?? '').trim();
|
||||
const switchingBranch = Boolean(branch) && branch !== currentBranch;
|
||||
|
||||
const handleCheckUpgrade = async () => {
|
||||
setChecking(true);
|
||||
|
|
@ -126,10 +150,12 @@ export function UpgradeSegment() {
|
|||
const handleUpgrade = async () => {
|
||||
setUpgrading(true);
|
||||
try {
|
||||
const response = await triggerUpgrade();
|
||||
const response = await triggerUpgrade(branch || null);
|
||||
if (response.ok) {
|
||||
// Redirect to Controller UI for upgrade status
|
||||
window.location.href = '/controller/?upgrade=true';
|
||||
} else {
|
||||
setUpgrading(false);
|
||||
}
|
||||
} catch (e) {
|
||||
setUpgrading(false);
|
||||
|
|
@ -152,13 +178,35 @@ export function UpgradeSegment() {
|
|||
</Panel>;
|
||||
}
|
||||
|
||||
const branchInput = <UpgradeBranchInput
|
||||
currentBranch={currentBranch}
|
||||
value={branch}
|
||||
onChange={setChosenBranch}
|
||||
disabled={upgrading}
|
||||
/>;
|
||||
|
||||
const upgradeButton = <APIButton
|
||||
role='save'
|
||||
size='big'
|
||||
onClick={handleUpgrade}
|
||||
disabled={upgrading || !branch}
|
||||
confirmContent={switchingBranch
|
||||
? `This will switch WROLPi from branch ${currentBranch || 'unknown'} to ${branch}. `
|
||||
+ 'The system will be temporarily unavailable during the upgrade. Are you sure?'
|
||||
: 'This will upgrade WROLPi. The system will be temporarily unavailable during the upgrade. Are you sure?'}
|
||||
confirmButton='Start Upgrade'
|
||||
>
|
||||
{upgrading ? 'Starting Upgrade...' : switchingBranch ? `Upgrade to ${branch}` : 'Upgrade Now'}
|
||||
</APIButton>;
|
||||
|
||||
// No update available
|
||||
if (!status?.update_available) {
|
||||
return <Panel id='upgrade'>
|
||||
<Header as='h3'>System Upgrade</Header>
|
||||
<p>Your WROLPi is up to date.</p>
|
||||
<p>Version: <strong>v{status?.version}</strong> on branch <strong>{status?.git_branch || 'unknown'}</strong>
|
||||
<p>Version: <strong>v{status?.version}</strong> on branch <strong>{currentBranch || 'unknown'}</strong>
|
||||
</p>
|
||||
{branchInput}
|
||||
<APIButton
|
||||
role='primary'
|
||||
onClick={handleCheckUpgrade}
|
||||
|
|
@ -166,6 +214,8 @@ export function UpgradeSegment() {
|
|||
>
|
||||
{checking ? 'Checking...' : 'Check for Upgrades'}
|
||||
</APIButton>
|
||||
{/* An up-to-date branch has nothing to upgrade; another branch can still be switched to. */}
|
||||
{switchingBranch && upgradeButton}
|
||||
</Panel>;
|
||||
}
|
||||
|
||||
|
|
@ -174,21 +224,13 @@ export function UpgradeSegment() {
|
|||
<Header as='h3' icon='arrow alternate circle up'>
|
||||
Upgrade Available
|
||||
</Header>
|
||||
<p>Branch: <strong>{status?.git_branch}</strong></p>
|
||||
<p>Branch: <strong>{currentBranch}</strong></p>
|
||||
<p>Current commit: <strong>{status?.current_commit}</strong></p>
|
||||
<p>Latest commit: <strong>{status?.latest_commit}</strong></p>
|
||||
<p><strong>{status?.commits_behind}</strong> commit(s) behind</p>
|
||||
|
||||
<APIButton
|
||||
role='save'
|
||||
size='big'
|
||||
onClick={handleUpgrade}
|
||||
disabled={upgrading}
|
||||
confirmContent='This will upgrade WROLPi. The system will be temporarily unavailable during the upgrade. Are you sure?'
|
||||
confirmButton='Start Upgrade'
|
||||
>
|
||||
{upgrading ? 'Starting Upgrade...' : 'Upgrade Now'}
|
||||
</APIButton>
|
||||
{branchInput}
|
||||
{upgradeButton}
|
||||
</Panel>;
|
||||
}
|
||||
|
||||
|
|
|
|||
63
app/src/components/admin/UpgradeSegment.test.js
Normal file
63
app/src/components/admin/UpgradeSegment.test.js
Normal file
|
|
@ -0,0 +1,63 @@
|
|||
import React from 'react';
|
||||
import {fireEvent, screen, waitFor} from '@testing-library/react';
|
||||
import {render} from '../../test-utils';
|
||||
import {UpgradeSegment} from './Settings';
|
||||
import {triggerUpgrade} from '../../api';
|
||||
|
||||
jest.mock('../../api', () => ({
|
||||
...jest.requireActual('../../api'),
|
||||
// Not ok, so the page does not navigate to the Controller.
|
||||
triggerUpgrade: jest.fn(() => Promise.resolve({ok: false})),
|
||||
}));
|
||||
|
||||
const upToDate = {status: {update_available: false, version: '1.0', git_branch: 'feature'}, loaded: true};
|
||||
const updateAvailable = {
|
||||
status: {update_available: true, version: '1.0', git_branch: 'release', commits_behind: 2},
|
||||
loaded: true,
|
||||
};
|
||||
|
||||
const branchInput = () => screen.getByLabelText('Branch', {selector: 'input'});
|
||||
|
||||
const confirmUpgrade = async (buttonName) => {
|
||||
fireEvent.click(screen.getByRole('button', {name: buttonName}));
|
||||
fireEvent.click(await screen.findByRole('button', {name: 'Start Upgrade'}));
|
||||
};
|
||||
|
||||
beforeEach(() => {
|
||||
triggerUpgrade.mockClear();
|
||||
});
|
||||
|
||||
describe('UpgradeSegment branch picker', () => {
|
||||
test('starts on the current branch and lists it with master and release', async () => {
|
||||
render(<UpgradeSegment/>, {status: upToDate});
|
||||
expect(branchInput()).toHaveValue('feature');
|
||||
|
||||
fireEvent.focus(branchInput());
|
||||
fireEvent.click(branchInput());
|
||||
const options = (await screen.findAllByRole('option')).map(i => i.textContent);
|
||||
expect(options).toEqual(['feature', 'master', 'release']);
|
||||
});
|
||||
|
||||
test('an up to date branch offers no upgrade until another branch is chosen', async () => {
|
||||
render(<UpgradeSegment/>, {status: upToDate});
|
||||
expect(screen.queryByRole('button', {name: /^Upgrade/})).not.toBeInTheDocument();
|
||||
|
||||
fireEvent.change(branchInput(), {target: {value: 'master'}});
|
||||
await confirmUpgrade('Upgrade to master');
|
||||
await waitFor(() => expect(triggerUpgrade).toHaveBeenCalledWith('master'));
|
||||
});
|
||||
|
||||
test('a typed branch name is upgraded to', async () => {
|
||||
render(<UpgradeSegment/>, {status: updateAvailable});
|
||||
fireEvent.change(branchInput(), {target: {value: ' my-branch '}});
|
||||
await confirmUpgrade('Upgrade to my-branch');
|
||||
await waitFor(() => expect(triggerUpgrade).toHaveBeenCalledWith('my-branch'));
|
||||
});
|
||||
|
||||
test('an available update upgrades the current branch by default', async () => {
|
||||
render(<UpgradeSegment/>, {status: updateAvailable});
|
||||
expect(branchInput()).toHaveValue('release');
|
||||
await confirmUpgrade('Upgrade Now');
|
||||
await waitFor(() => expect(triggerUpgrade).toHaveBeenCalledWith('release'));
|
||||
});
|
||||
});
|
||||
|
|
@ -1,5 +1,6 @@
|
|||
import React, {forwardRef, useId} from 'react';
|
||||
import {
|
||||
Autocomplete,
|
||||
Checkbox as MCheckbox,
|
||||
MultiSelect,
|
||||
NumberInput,
|
||||
|
|
@ -215,6 +216,7 @@ export function ColoredInput({
|
|||
}
|
||||
|
||||
export {
|
||||
Autocomplete,
|
||||
MTextInput as TextInput,
|
||||
MTextarea as Textarea,
|
||||
MSelect as Select,
|
||||
|
|
|
|||
|
|
@ -6,6 +6,7 @@ Uses systemd oneshot services for process survival across controller restarts.
|
|||
"""
|
||||
|
||||
import logging
|
||||
import re
|
||||
import subprocess
|
||||
import time
|
||||
from datetime import datetime, timezone
|
||||
|
|
@ -15,6 +16,22 @@ from controller.lib.config import is_docker_mode
|
|||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
# A branch is written into the systemd env file and passed to `upgrade.sh -b`, so only plain git branch names are
|
||||
# accepted: no whitespace (a newline would add an env variable), no leading dash (an option), no `..`.
|
||||
# Matches `wrolpi.upgrade.validate_branch`.
|
||||
BRANCH_PATTERN = re.compile(r"[A-Za-z0-9_][A-Za-z0-9_.\-]*(/[A-Za-z0-9_][A-Za-z0-9_.\-]*)*")
|
||||
MAX_BRANCH_LENGTH = 200
|
||||
|
||||
|
||||
def is_valid_branch(branch: str) -> bool:
|
||||
"""Return True if `branch` is a branch name `upgrade.sh` may be given."""
|
||||
return isinstance(branch, str) \
|
||||
and len(branch) <= MAX_BRANCH_LENGTH \
|
||||
and BRANCH_PATTERN.fullmatch(branch) is not None \
|
||||
and ".." not in branch \
|
||||
and not branch.endswith((".", ".lock"))
|
||||
|
||||
|
||||
# Available scripts with their configurations
|
||||
# Parameters define inputs that scripts accept:
|
||||
# - name: Parameter name (used as env var name, e.g., "branch" -> "BRANCH=value")
|
||||
|
|
@ -254,6 +271,15 @@ def start_script(name: str, params: Optional[dict] = None) -> dict:
|
|||
env_file = script_config.get("env_file")
|
||||
if env_file:
|
||||
values = {key: value for key, value in (params or {}).items() if value}
|
||||
for parameter in parameters:
|
||||
value = values.get(parameter["name"])
|
||||
if value is None:
|
||||
continue
|
||||
# Each value is one line of the env file.
|
||||
if parameter["type"] == "branch" and not is_valid_branch(value):
|
||||
return {"success": False, "error": f"Invalid branch name: {value!r}"}
|
||||
if "\n" in str(value) or "\r" in str(value):
|
||||
return {"success": False, "error": f"Invalid {parameter['label']}: must be a single line"}
|
||||
for parameter in parameters:
|
||||
if parameter["type"] == "branch" and not values.get(parameter["name"]):
|
||||
# upgrade.sh upgrades the current branch when it is not given one.
|
||||
|
|
|
|||
|
|
@ -6,6 +6,8 @@ import subprocess
|
|||
import time
|
||||
from unittest import mock
|
||||
|
||||
import pytest
|
||||
|
||||
from controller.lib.scripts import (
|
||||
_get_service_timing,
|
||||
AVAILABLE_SCRIPTS,
|
||||
|
|
@ -280,6 +282,26 @@ class TestStartScript:
|
|||
popen.assert_not_called()
|
||||
|
||||
|
||||
@pytest.mark.parametrize("branch", [
|
||||
"master\nEVIL=1", "master\rEVIL=1", "-b", "a..b", "a b", "foo.lock", "foo/", "/foo", "a//b", "a$b", "x" * 256,
|
||||
])
|
||||
def test_invalid_branch_is_rejected(self, tmp_path, branch):
|
||||
"""The branch is written into the systemd env file and passed to `upgrade.sh -b`; a branch name git would
|
||||
refuse, or one that could add a line to the env file, never starts an upgrade."""
|
||||
result, env_file, popen = self._start_upgrade(tmp_path, {"branch": branch})
|
||||
assert result["success"] is False
|
||||
assert "branch" in result["error"].lower()
|
||||
assert not env_file.exists()
|
||||
popen.assert_not_called()
|
||||
|
||||
@pytest.mark.parametrize("branch", ["master", "release", "feature/new-thing", "v1.2_fix"])
|
||||
def test_valid_branch_is_written(self, tmp_path, branch):
|
||||
result, env_file, popen = self._start_upgrade(tmp_path, {"branch": branch})
|
||||
assert result["success"] is True
|
||||
assert env_file.read_text() == f"BRANCH={branch}\n"
|
||||
popen.assert_called_once()
|
||||
|
||||
|
||||
class TestGetScriptOutput:
|
||||
"""Tests for get_script_output function."""
|
||||
|
||||
|
|
|
|||
|
|
@ -770,7 +770,7 @@ async def get_upgrade_check(request: Request):
|
|||
@openapi.definition(description='Start WROLPi upgrade')
|
||||
@native_only
|
||||
@wrol_mode_check
|
||||
async def post_upgrade_start(_: Request):
|
||||
async def post_upgrade_start(request: Request):
|
||||
"""
|
||||
Trigger the WROLPi upgrade process.
|
||||
|
||||
|
|
@ -780,12 +780,16 @@ async def post_upgrade_start(_: Request):
|
|||
3. Run upgrade scripts
|
||||
4. Restart services
|
||||
|
||||
The optional JSON body `{"branch": "master"}` upgrades from that branch; without it the current branch is
|
||||
upgraded.
|
||||
|
||||
The frontend should redirect to the maintenance page after calling this.
|
||||
Returns 202 Accepted as the upgrade runs asynchronously.
|
||||
"""
|
||||
from wrolpi.upgrade import start_upgrade
|
||||
|
||||
await start_upgrade()
|
||||
body = request.json if isinstance(request.json, dict) else {}
|
||||
await start_upgrade(body.get('branch') or None)
|
||||
return response.empty(HTTPStatus.ACCEPTED)
|
||||
|
||||
|
||||
|
|
|
|||
|
|
@ -2,10 +2,12 @@
|
|||
Tests for the WROLPi upgrade system.
|
||||
"""
|
||||
import subprocess
|
||||
from http import HTTPStatus
|
||||
from unittest.mock import patch, MagicMock
|
||||
|
||||
import pytest
|
||||
|
||||
from wrolpi.errors import ValidationError
|
||||
from wrolpi.upgrade import (
|
||||
check_for_update,
|
||||
get_current_branch,
|
||||
|
|
@ -296,6 +298,57 @@ class TestStartUpgrade:
|
|||
call_args = mock_popen.call_args[0][0]
|
||||
assert call_args == ['sudo', 'systemctl', 'start', 'wrolpi-upgrade.service']
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_start_upgrade_chosen_branch(self, tmp_path):
|
||||
"""A branch the user chose is upgraded instead of the current branch."""
|
||||
mock_script_path = MagicMock()
|
||||
mock_script_path.is_file.return_value = True
|
||||
|
||||
env_file = tmp_path / 'wrolpi-upgrade.env'
|
||||
|
||||
with patch('wrolpi.upgrade.DOCKERIZED', False), \
|
||||
patch('wrolpi.upgrade.UPGRADE_SCRIPT', mock_script_path), \
|
||||
patch('wrolpi.upgrade.get_current_branch', return_value='release'), \
|
||||
patch('wrolpi.upgrade.subprocess.Popen') as mock_popen, \
|
||||
patch('wrolpi.upgrade.pathlib.Path', return_value=env_file), \
|
||||
patch('wrolpi.events.Events.send_upgrade_started'):
|
||||
await start_upgrade('feature/new-thing')
|
||||
|
||||
assert env_file.read_text() == 'BRANCH=feature/new-thing\n'
|
||||
mock_popen.assert_called_once()
|
||||
|
||||
@pytest.mark.parametrize('branch', [
|
||||
'master\nEVIL=1',
|
||||
'-b',
|
||||
'a..b',
|
||||
'a b',
|
||||
'foo.lock',
|
||||
'foo/',
|
||||
'/foo',
|
||||
'a//b',
|
||||
'a$b',
|
||||
'x' * 256,
|
||||
])
|
||||
@pytest.mark.asyncio
|
||||
async def test_start_upgrade_rejects_invalid_branch(self, tmp_path, branch):
|
||||
"""A branch name git would refuse, or one that could escape the env file, never starts an upgrade."""
|
||||
mock_script_path = MagicMock()
|
||||
mock_script_path.is_file.return_value = True
|
||||
|
||||
env_file = tmp_path / 'wrolpi-upgrade.env'
|
||||
|
||||
with patch('wrolpi.upgrade.DOCKERIZED', False), \
|
||||
patch('wrolpi.upgrade.UPGRADE_SCRIPT', mock_script_path), \
|
||||
patch('wrolpi.upgrade.subprocess.Popen') as mock_popen, \
|
||||
patch('wrolpi.upgrade.pathlib.Path', return_value=env_file), \
|
||||
patch('wrolpi.events.Events.send_upgrade_started') as mock_event:
|
||||
with pytest.raises(ValidationError):
|
||||
await start_upgrade(branch)
|
||||
|
||||
assert not env_file.exists()
|
||||
mock_popen.assert_not_called()
|
||||
mock_event.assert_not_called()
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_start_upgrade_skipped_in_docker(self):
|
||||
"""start_upgrade does nothing in Docker environment."""
|
||||
|
|
@ -412,3 +465,33 @@ async def test_refresh_update_status_can_skip_fetch():
|
|||
await refresh_update_status({}, fetch=False)
|
||||
await refresh_update_status({})
|
||||
assert seen == [False, True]
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_upgrade_start_api_branch(async_client):
|
||||
"""The upgrade endpoint passes the chosen branch on, and refuses an invalid one."""
|
||||
with patch('wrolpi.common.DOCKERIZED', False), \
|
||||
patch('wrolpi.upgrade.DOCKERIZED', False), \
|
||||
patch('wrolpi.upgrade.UPGRADE_SCRIPT') as mock_script_path, \
|
||||
patch('wrolpi.upgrade.subprocess.Popen') as mock_popen, \
|
||||
patch('wrolpi.upgrade.write_upgrade_env') as mock_write, \
|
||||
patch('wrolpi.events.Events.send_upgrade_started'):
|
||||
mock_script_path.is_file.return_value = True
|
||||
|
||||
request, response = await async_client.post('/api/upgrade/start', json={'branch': 'master'})
|
||||
assert response.status_code == HTTPStatus.ACCEPTED
|
||||
mock_write.assert_called_once_with('master')
|
||||
mock_popen.assert_called_once()
|
||||
|
||||
mock_write.reset_mock()
|
||||
mock_popen.reset_mock()
|
||||
request, response = await async_client.post('/api/upgrade/start', json={'branch': 'master\nEVIL=1'})
|
||||
assert response.status_code == HTTPStatus.BAD_REQUEST
|
||||
mock_write.assert_not_called()
|
||||
mock_popen.assert_not_called()
|
||||
|
||||
# No body upgrades the current branch, as before.
|
||||
with patch('wrolpi.upgrade.get_current_branch', return_value='release'):
|
||||
request, response = await async_client.post('/api/upgrade/start')
|
||||
assert response.status_code == HTTPStatus.ACCEPTED
|
||||
mock_write.assert_called_once_with('release')
|
||||
|
|
|
|||
|
|
@ -6,9 +6,11 @@ with the remote origin branch, and to trigger the upgrade process.
|
|||
"""
|
||||
import asyncio
|
||||
import pathlib
|
||||
import re
|
||||
import subprocess
|
||||
|
||||
from wrolpi.common import logger, wrol_mode_check
|
||||
from wrolpi.errors import ValidationError
|
||||
from wrolpi.vars import DOCKERIZED, PROJECT_DIR
|
||||
|
||||
logger = logger.getChild(__name__)
|
||||
|
|
@ -16,6 +18,30 @@ logger = logger.getChild(__name__)
|
|||
# Path to the upgrade script.
|
||||
UPGRADE_SCRIPT = PROJECT_DIR / 'upgrade.sh'
|
||||
|
||||
# The env file systemd reads for wrolpi-upgrade.service.
|
||||
UPGRADE_ENV_FILE = '/tmp/wrolpi-upgrade.env'
|
||||
|
||||
# A branch is written into the systemd env file and passed to `upgrade.sh -b`, so only plain git branch names are
|
||||
# accepted: no whitespace (a newline would add an env variable), no leading dash (an option), no `..`.
|
||||
BRANCH_PATTERN = re.compile(r'[A-Za-z0-9_][A-Za-z0-9_.\-]*(/[A-Za-z0-9_][A-Za-z0-9_.\-]*)*')
|
||||
MAX_BRANCH_LENGTH = 200
|
||||
|
||||
|
||||
def validate_branch(branch: str) -> str:
|
||||
"""Return `branch` if it is a branch name `upgrade.sh` may be given, otherwise raise ValidationError."""
|
||||
if not isinstance(branch, str) \
|
||||
or len(branch) > MAX_BRANCH_LENGTH \
|
||||
or not BRANCH_PATTERN.fullmatch(branch) \
|
||||
or '..' in branch \
|
||||
or branch.endswith(('.', '.lock')):
|
||||
raise ValidationError(f'Invalid branch name: {branch!r}')
|
||||
return branch
|
||||
|
||||
|
||||
def write_upgrade_env(branch: str):
|
||||
"""Write the branch for the systemd upgrade service to read."""
|
||||
pathlib.Path(UPGRADE_ENV_FILE).write_text(f'BRANCH={branch}\n')
|
||||
|
||||
|
||||
def git_fetch() -> bool:
|
||||
"""
|
||||
|
|
@ -228,14 +254,14 @@ async def refresh_update_status(status, fetch: bool = True) -> dict:
|
|||
return result
|
||||
|
||||
|
||||
async def start_upgrade():
|
||||
async def start_upgrade(branch: str = None):
|
||||
"""
|
||||
Start the WROLPi upgrade process.
|
||||
|
||||
This executes /opt/wrolpi/upgrade.sh in a detached subprocess so it survives
|
||||
the API shutdown (upgrade.sh stops the API service).
|
||||
|
||||
The upgrade will use the currently checked out branch (e.g., 'release' or 'master').
|
||||
The upgrade will use `branch`, or the currently checked out branch (e.g., 'release' or 'master') when none is given.
|
||||
|
||||
The frontend should redirect to the maintenance page after calling this.
|
||||
"""
|
||||
|
|
@ -249,20 +275,21 @@ async def start_upgrade():
|
|||
logger.error(f'Upgrade script not found: {UPGRADE_SCRIPT}')
|
||||
return
|
||||
|
||||
# Get current branch to upgrade from the same branch
|
||||
branch = get_current_branch()
|
||||
if not branch:
|
||||
logger.error('Could not determine current branch, defaulting to release')
|
||||
branch = 'release'
|
||||
if branch:
|
||||
validate_branch(branch)
|
||||
else:
|
||||
# Upgrade from the same branch.
|
||||
branch = get_current_branch()
|
||||
if not branch:
|
||||
logger.error('Could not determine current branch, defaulting to release')
|
||||
branch = 'release'
|
||||
|
||||
logger.warning(f'Starting WROLPi upgrade on branch: {branch}')
|
||||
|
||||
# Send event to notify frontend
|
||||
Events.send_upgrade_started(f'WROLPi upgrade is starting on branch {branch}. Please wait...')
|
||||
|
||||
# Write branch to environment file for the systemd service to read.
|
||||
env_file = pathlib.Path('/tmp/wrolpi-upgrade.env')
|
||||
env_file.write_text(f'BRANCH={branch}\n')
|
||||
write_upgrade_env(branch)
|
||||
|
||||
# Use systemd to run the upgrade service. This ensures the upgrade process
|
||||
# survives when the API is stopped, as systemd manages it independently.
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue