Sync and backup: a secondary WROLPi and a backup drive copy the library (#957)

* A secondary WROLPi copies its primary's library over HTTP

A WROLPi with role "secondary" pulls from its primary: a manifest of every
FileGroup's files (/api/sync/manifest), then each missing or changed file
from the primary's Caddy /media/ (resumable, written to a hidden partial and
renamed with the primary's mtime), a refresh, then the library configs,
imported as the primary wrote them.  wrolpi.yaml contributes only its library
settings.  Files deleted on the primary are kept.

A secondary never saves the synced configs and never downloads.  Its API
answers 503 SYNCING while a sync runs, and every page warns that it is a
copy.  It syncs in a daily window or on "Sync now"; WROL Mode stops it.

On a Pi 4 (no AES instructions) the client uses TLS 1.2 ChaCha20, which
pulls ~110 MB/s from Caddy versus ~41 MB/s for rsync over ssh.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Sync has its own /admin tab; a sync's reads from the primary are bounded

The sync settings and progress move from Settings (and the component
gallery, which is for library components) to /admin/sync.

A download never writes past the size in the primary's manifest, and configs,
listings, and manifest pages are capped.  A primary address may not carry a
user name or password (it is logged and shown).  While a sync runs, the API
answers only the exact requests that show its progress or stop it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* A sync keeps the secondary's replaced configs in today's config backup

The first copy of the day is kept, like a save, so a config backup import
undoes a sync's config changes.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Docker's Caddy logs every request

`docker compose logs -f web` shows each request with its status, size and
duration, e.g. a secondary's /media/ downloads during a sync.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* A sync reports its progress as it downloads, and refuses quietly

The status updated only when a page of 500 FileGroups finished, so a page of
large files looked stuck; it now updates every 2 seconds.  Requests refused
while syncing are answered by the middleware instead of raised, so the UI's
polling no longer logs an error each time.  The primary's version is stored
without its trailing newline.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* A WROLPi can back up to a second drive; sync settings live in sync.yaml

The Sync tab's Backup Drive copies the media directory to a second mounted
drive with rsync during the sync window (hourly), or on "Back Up Now".
Nothing on the backup drive is deleted.  The Tags and playlists directories
are left out (WROLPi rebuilds them from the configs), and the database is
written as an SQLite snapshot rather than copied as files, so the drive can be
mounted as the media directory and start.  A backup is written only while the
chosen drive (by UUID) is mounted where it was chosen, and is not the media or
system drive; rsync is stopped if the drive disappears.  Not in Docker, which
cannot reach other drives.

Role, primary, window and backup drive move from wrolpi.yaml to sync.yaml:
they belong to this machine, and are never copied from a primary.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* The Sync tab shows the configured backup drive

getSettings copies each setting by name and did not list the backup drive,
so the Sync tab showed "None" while one was configured.  It also dropped
`version`.  A test now fails for any setting the API sends that getSettings
drops.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* A backup can go to a folder on its drive, and remembers its last success

The Backup Drive panel takes a folder on the chosen drive.  The drive is
checked through the folder's mount point: the folder is written only when the
drive with the saved UUID is mounted there, so a folder left on the system
drive by an unplugged drive, or on another drive mounted inside the chosen
one, is refused.  A missing folder is created once the drive is checked.

When the last backup succeeded is saved in sync.yaml, so it is known after a
restart.  "Stop Backup" is disabled while the database snapshot is written (it
runs to the end), and a finished backup clears the request to stop.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* The backup drive has its own window

The sync window was shown in the Sync panel but also scheduled the backup
drive.  The Backup Drive panel now has its own window (sync.yaml
backup_window_start/end), saved with the drive; the sync window is shown,
and used, only for a secondary's sync.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Sync and the backup drive can each exclude folders

A secondary or a backup drive may be smaller than the primary's library.
Each Sync tab panel has its own excluded folders in sync.yaml, chosen in
a folder browser: a secondary browses its primary's folders (through
Caddy), the backup drive browses this WROLPi's media directory.  Excluded
folders are never copied; what was copied before is kept.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* The folder browser does not offer lost+found

Every ext4 drive has a root-only lost+found folder; a sync and a backup
never copy it, so it is not offered for exclusion.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* A sync never writes into config or tags, whatever their case

On a media drive that ignores case (exFAT, NTFS, macOS), a manifest path
like Config/wrolpi.db is the real config folder. The protected and
unlisted top-level folders are now compared case-insensitively in the
manifest, in resolve_destination, in excluded-folder validation, and in
both folder listings.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* A backup writes the database snapshot only when the database changed

Every backup rewrote the whole database snapshot (2.5 GB on a busy
WROLPi), even on the window's idle hourly runs. The snapshot is now
skipped when the live database (its size and mtime, and those of a
non-empty WAL) and the drive's copy are both unchanged since the last
snapshot. The record is in memory, so the first backup after a restart
writes it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Remove the unused save_sync_config switch

Nothing activated it; SyncConfig saves directly.  The test server's
log_message override is called by http.server, so it goes in the
vulture baseline.

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:
lrnselfreliance 2026-11-11 10:53:34 -07:00 • committed by Roland
parent 86f168d2c1
commit 6cd233dce6
No known key found for this signature in database
GPG key ID: 1BA620CE6C9A4680
40 changed files with 4663 additions and 19 deletions

View file

@ -6,6 +6,7 @@ import {SettingsPage} from "./Settings";
import {StatusPage} from "./Status";
import {ControllerPage} from "./ControllerPage";
import {ExtensionPage} from "./ExtensionPage";
import {SyncPage} from "./Sync";
export default function AdminRoute() {
@ -13,6 +14,7 @@ export default function AdminRoute() {
{text: 'Downloads', to: '/admin', key: 'admin', end: true},
{text: 'Settings', to: '/admin/settings', key: 'settings'},
{text: 'Status', to: '/admin/status', key: 'status'},
{text: 'Sync', to: '/admin/sync', key: 'sync'},
{text: 'Control', to: '/admin/controller', key: 'controller'},
{text: 'Extension', to: '/admin/extension', key: 'extension'},
];
@ -23,6 +25,7 @@ export default function AdminRoute() {
<Route path='/' exact element={<DownloadsPage/>}/>
<Route path='settings' exact element={<SettingsPage/>}/>
<Route path='status' exact element={<StatusPage/>}/>
<Route path='sync' exact element={<SyncPage/>}/>
<Route path='controller' exact element={<ControllerPage/>}/>
<Route path='extension' exact element={<ExtensionPage/>}/>
</Routes>

View file

@ -26,6 +26,7 @@ import {
useTitle,
WROLModeMessage
} from "../Common";
import {SecondaryRoleMessage} from "./Sync";
import {
Button,
ButtonGroup,
@ -715,6 +716,8 @@ export function DownloadsPage() {
return <>
<WROLModeMessage content='Downloads are disabled because WROL Mode is enabled.'/>
<SecondaryRoleMessage content="Downloads are disabled on a secondary WROLPi; its primary downloads, and every
sync copies the primary's library here."/>
<DownloadWindowMessage/>
<DailyLimitMessage/>
<DisableDownloadsToggle/>

View file

@ -0,0 +1,575 @@
import React from "react";
import {SettingsContext, StatusContext} from "../../contexts/contexts";
import {
cancelBackup,
cancelSync,
getSyncDirectories,
PrimaryUnreachableError,
runBackup,
runSync,
saveSyncSettings,
testSync
} from "../../api";
import {getDisks} from "../../api/controller";
import {humanFileSize, isoDatetimeToAgoPopup, useTitle} from "../Common";
import {Link} from "react-router";
import {useDockerized, useSyncRole, useWROLMode} from "../../hooks/customHooks";
import {
Button,
Checkbox,
Header,
Icon,
IconButton,
Message,
Modal,
Panel,
Progress,
Select,
TextInput,
toast
} from "../ui";
const roleOptions = [
{value: 'primary', label: 'Primary'},
{value: 'secondary', label: 'Secondary'},
];
/** The sync's progress: how many of the primary's FileGroups have been compared. */
function syncPercent(sync) {
if (!sync || !sync.max_id) {
return 0;
}
// FileGroup ids are not contiguous; `groups_seen / max_id` underestimates, it never overshoots.
return Math.min(100, Math.round(100 * sync.groups_seen / sync.max_id));
}
function syncProgressLabel(sync) {
const downloaded = `${sync.files_downloaded} / ${sync.files_to_download} files`;
return `${sync.phase === 'configs' ? 'Importing configs' : downloaded} (${humanFileSize(sync.bytes_downloaded)})`;
}
/**
* Shown on every page of a secondary WROLPi, so nobody mistakes it for the primary. WROL Mode stops syncing,
* so the warning goes away with it.
*/
export function SecondaryRoleMessage({content}) {
const role = useSyncRole();
const wrolMode = useWROLMode();
const {settings} = React.useContext(SettingsContext);
if (role !== 'secondary' || wrolMode) {
return null;
}
return <SecondaryRoleNotice primaryUrl={settings?.sync_primary_url} content={content}/>
}
export function SecondaryRoleNotice({primaryUrl, content}) {
return <Message kind='warning' icon='copy' title='Secondary WROLPi'>
{content || <>
This WROLPi is a copy of <b>{primaryUrl || 'its primary'}</b>. Every sync replaces its library with the
primary's, so changes made here are lost. Do not use it as a primary. Enable WROL Mode to stop syncing.
{' '}<Link to='/admin/sync'>Sync settings</Link>
</>}
</Message>
}
/** The progress and outcome of a secondary's sync. */
export function SyncStatus({sync, running}) {
if (!sync) {
return null;
}
return <div>
{running && <Progress percent={syncPercent(sync)} label={syncProgressLabel(sync)}/>}
<p>
<b>Last successful sync:</b> {sync.last_success_at ? isoDatetimeToAgoPopup(sync.last_success_at) : 'Never'}
</p>
{!running && sync.finished_at && <p>
<b>Last sync:</b> {sync.files_downloaded} files downloaded
({humanFileSize(sync.bytes_downloaded)}), {sync.files_failed} failed
{sync.files_excluded > 0 && <>, {sync.files_excluded} excluded</>}
</p>}
{sync.disk_full && <Message kind='error' icon='hdd' title='The drive is full'>
Some files were not synced because the drive is nearly full.
</Message>}
{sync.last_error && !running && <Message kind='error' icon='warning' title='Sync problem'>
{sync.last_error}
</Message>}
{sync.last_skip_reason && !running && <p style={{color: 'var(--muted)'}}>
Not synced: {sync.last_skip_reason}
</p>}
</div>
}
/** Covers the app while a secondary syncs; its API refuses requests until the sync finishes. */
export function SyncingOverlay() {
const {status} = React.useContext(StatusContext);
const role = useSyncRole();
const running = role === 'secondary' && status?.flags?.sync_running === true;
if (!running) {
return null;
}
return <div className='wrolpi-sync-overlay' role='alertdialog' aria-modal='true' aria-label='Syncing'
style={{
position: 'fixed', inset: 0, zIndex: 1000, display: 'flex', alignItems: 'center',
justifyContent: 'center', padding: 16, background: 'rgba(0, 0, 0, 0.6)',
}}>
<SyncingPanel sync={status.sync} onCancel={cancelSync}/>
</div>
}
/** What the SyncingOverlay shows. */
export function SyncingPanel({sync, onCancel}) {
return <Panel style={{maxWidth: '32em', width: '100%'}}>
<Header as='h2' icon='sync'>Syncing from the primary</Header>
<p>
This WROLPi is copying the library of {sync?.primary_url || 'its primary'}. It is unavailable
until the sync finishes.
</p>
<Progress percent={syncPercent(sync)} label={sync ? syncProgressLabel(sync) : null}/>
<Button color='red' onClick={onCancel} style={{marginTop: '1em'}}>Stop Sync</Button>
</Panel>
}
/** The Settings panel: this WROLPi's role, and (for a secondary) its primary and sync window. */
/** Is `path` an excluded folder, or inside one? */
export function isExcludedPath(path, excluded) {
return (excluded || []).some(i => path === i || path.startsWith(`${i}/`));
}
/** Excluded folders without the ones already inside another excluded folder, sorted. */
export function simplifyExcluded(excluded) {
const unique = Array.from(new Set(excluded || []));
return unique.filter(i => !unique.some(j => j !== i && i.startsWith(`${j}/`))).sort();
}
function ExcludeFolderRow({folder, depth, source, chosen, onToggle}) {
const [open, setOpen] = React.useState(false);
const [children, setChildren] = React.useState(null);
const [error, setError] = React.useState(null);
const checked = chosen.has(folder.path);
// A folder inside a chosen folder is excluded with it, whether or not it was chosen itself.
const inherited = isExcludedPath(folder.path, Array.from(chosen).filter(i => i !== folder.path));
const toggleOpen = async () => {
if (!open && children === null) {
try {
setChildren(await getSyncDirectories(folder.path, source));
} catch (e) {
setError(e.message);
}
}
setOpen(!open);
};
return <>
<div style={{display: 'flex', alignItems: 'center', gap: '0.5em', paddingLeft: `${depth * 1.5}em`}}
data-testid='exclude-folder-row'>
<IconButton icon={open ? 'chevron down' : 'chevron right'} size='xs' onClick={toggleOpen}
label={`${open ? 'Close' : 'Open'} ${folder.name}`}/>
<Checkbox checked={checked || inherited} disabled={inherited} aria-label={folder.path}
onChange={() => onToggle(folder.path)}
label={<span><Icon name='folder'/> {folder.name}</span>}/>
{inherited && <span style={{color: 'var(--muted)', fontSize: '0.85em'}}>excluded with its parent</span>}
</div>
{open && error && <p style={{paddingLeft: `${(depth + 1) * 1.5}em`, color: 'var(--muted)'}}>{error}</p>}
{open && children && children.length === 0 && <p
style={{paddingLeft: `${(depth + 1) * 1.5 + 2}em`, color: 'var(--muted)', margin: 0}}>No folders</p>}
{open && children && children.map(child => <ExcludeFolderRow key={child.path} folder={child} depth={depth + 1}
source={source} chosen={chosen}
onToggle={onToggle}/>)}
</>
}
/** Choose folders in a tree; `source` is 'local' (this WROLPi's media directory) or 'primary'. */
export function ExcludeFolderModal({open, onClose, value, onSubmit, source}) {
const [chosen, setChosen] = React.useState(new Set());
const [folders, setFolders] = React.useState(null);
const [error, setError] = React.useState(null);
React.useEffect(() => {
if (!open) {
return;
}
setChosen(new Set(value || []));
setFolders(null);
setError(null);
getSyncDirectories('', source)
.then(setFolders)
.catch(e => setError(e instanceof PrimaryUnreachableError
? `The primary did not answer: ${e.message}` : e.message));
}, [open, source, value]);
const onToggle = path => {
const next = new Set(chosen);
next.has(path) ? next.delete(path) : next.add(path);
setChosen(next);
};
return <Modal open={open} onClose={onClose}>
<Modal.Header>{source === 'primary' ? "Exclude the primary's folders" : 'Exclude folders'}</Modal.Header>
<Modal.Content>
<p>Checked folders, and everything inside them, are not copied.</p>
{error && <Message kind='error' icon='warning' title='Could not list the folders'>{error}</Message>}
{!error && folders === null && <p>Loading folders...</p>}
{folders && folders.length === 0 && <p>No folders</p>}
{folders && folders.map(folder => <ExcludeFolderRow key={folder.path} folder={folder} depth={0}
source={source} chosen={chosen}
onToggle={onToggle}/>)}
</Modal.Content>
<Modal.Actions>
<Button role='cancel' style={{marginRight: 'auto'}} onClick={onClose}>Cancel</Button>
<Button color='violet' onClick={() => onSubmit(simplifyExcluded(Array.from(chosen)))}>Done</Button>
</Modal.Actions>
</Modal>
}
/** The folders a sync or a backup does not copy, and the button that chooses them. */
export function ExcludedDirectories({value, onChange, source, disabled}) {
const [open, setOpen] = React.useState(false);
const excluded = value || [];
return <div style={{margin: '0.5em 0'}}>
<label><b>Excluded folders</b></label>
{excluded.length === 0
? <p style={{color: 'var(--muted)', margin: '0.25em 0'}}>Nothing excluded; every folder is copied.</p>
: <ul style={{listStyle: 'none', padding: 0, margin: '0.25em 0'}}>
{excluded.map(path => <li key={path} style={{display: 'flex', alignItems: 'center', gap: '0.5em'}}>
<Icon name='folder'/> <span>{path}</span>
<IconButton icon='close' size='xs' label={`Copy ${path} again`} disabled={disabled}
onClick={() => onChange(excluded.filter(i => i !== path))}/>
</li>)}
</ul>}
<Button icon='folder open' onClick={() => setOpen(true)} disabled={disabled}>Choose Folders</Button>
<p style={{color: 'var(--muted)', fontSize: '0.9em'}}>
Files already copied into an excluded folder are kept; delete them yourself to free space.
</p>
<ExcludeFolderModal open={open} onClose={() => setOpen(false)} value={excluded} source={source}
onSubmit={chosen => {
onChange(chosen);
setOpen(false);
}}/>
</div>
}
export function SyncSection() {
const {settings, fetchSettings} = React.useContext(SettingsContext);
const {status} = React.useContext(StatusContext);
const wrolMode = useWROLMode();
const [state, setState] = React.useState({});
const [testResult, setTestResult] = React.useState(null);
const [saving, setSaving] = React.useState(false);
// Only these values reset the form; the settings are re-fetched while the user types.
const loaded = Boolean(settings);
const role = settings?.role;
const primaryUrl = settings?.sync_primary_url;
const windowStart = settings?.sync_window_start;
const windowEnd = settings?.sync_window_end;
const excludedKey = JSON.stringify(settings?.sync_excluded_directories || []);
React.useEffect(() => {
if (loaded) {
setState({
role: role || 'primary',
sync_primary_url: primaryUrl || '',
sync_window_start: windowStart || '',
sync_window_end: windowEnd || '',
sync_excluded_directories: JSON.parse(excludedKey),
});
}
}, [loaded, role, primaryUrl, windowStart, windowEnd, excludedKey]);
if (!settings) {
return null;
}
const secondary = state.role === 'secondary';
const saved = secondary && settings.role === 'secondary' && settings.sync_primary_url;
const running = status?.flags?.sync_running === true;
const save = async () => {
setSaving(true);
try {
const response = await saveSyncSettings(state);
if (response?.ok) {
toast({type: 'success', title: 'Sync settings saved', time: 3000});
setTestResult(null);
}
await fetchSettings();
} finally {
setSaving(false);
}
};
const test = async () => {
setTestResult(await testSync());
};
const syncNow = async () => {
const response = await runSync();
if (response?.ok) {
toast({type: 'info', title: 'Sync requested', description: 'The sync starts in a few seconds.', time: 3000});
}
};
return <Panel>
<Header as='h3' icon='copy'>Sync</Header>
<p>
A <b>secondary</b> WROLPi keeps a copy of a <b>primary</b> WROLPi's library: its files, tags,
channels, domains, playlists, and other library settings. Files deleted on the primary are kept.
</p>
<div style={{margin: '0.5em 0', maxWidth: '20em'}}>
<label><b>This WROLPi is</b></label>
<Select data={roleOptions} value={state.role} allowDeselect={false} disabled={wrolMode}
onChange={value => setState({...state, role: value})}/>
</div>
{secondary && <>
<Message kind='warning' icon='warning' title='A secondary is overwritten'>
Every sync replaces this WROLPi's library with the primary's; changes made here are lost.
It does not download, and it is unavailable while it syncs.
</Message>
<div style={{margin: '0.5em 0', maxWidth: '30em'}}>
<label><b>Primary address</b></label>
<TextInput placeholder='https://192.168.0.10' value={state.sync_primary_url} disabled={wrolMode}
onChange={e => setState({...state, sync_primary_url: e.currentTarget.value})}/>
</div>
</>}
{secondary && <>
<div style={{display: 'flex', gap: '1em', flexWrap: 'wrap', margin: '0.5em 0'}}>
<div>
<label><b>Sync Window Start</b></label>
<TextInput type='time' value={state.sync_window_start} disabled={wrolMode}
onChange={e => setState({...state, sync_window_start: e.currentTarget.value})}/>
</div>
<div>
<label><b>Sync Window End</b></label>
<TextInput type='time' value={state.sync_window_end} disabled={wrolMode}
onChange={e => setState({...state, sync_window_end: e.currentTarget.value})}/>
</div>
</div>
<p style={{color: 'var(--muted)', fontSize: '0.9em'}}>
Within the window, this secondary syncs every 15 minutes. Leave both empty to sync only with
"Sync Now".
</p>
</>}
{/* The primary's folders can only be listed once this WROLPi knows its primary. */}
{secondary && saved && <ExcludedDirectories value={state.sync_excluded_directories} source='primary'
disabled={wrolMode}
onChange={value => setState({
...state,
sync_excluded_directories: value
})}/>}
<div style={{display: 'flex', gap: '0.5em', flexWrap: 'wrap'}}>
<Button color='violet' onClick={save} disabled={wrolMode || saving}>Save</Button>
{saved && <Button onClick={test} disabled={wrolMode}>Test Connection</Button>}
{saved && <Button onClick={syncNow} disabled={wrolMode || running}>Sync Now</Button>}
</div>
{testResult && (testResult.ok
? <Message kind='success' icon='check' title='The primary answered'>
WROLPi {testResult.info?.version} at {settings.sync_primary_url}
</Message>
: <Message kind='error' icon='warning' title='The primary did not answer'>{testResult.error}</Message>)}
{wrolMode && settings.role === 'secondary' && <Message kind='info' icon='lock' title='Syncing is stopped'>
WROL Mode is enabled; this WROLPi does not sync.
</Message>}
{settings.role === 'secondary' && <SyncStatus sync={status?.sync} running={running}/>}
</Panel>
}
/** The drives a backup can be written to: mounted under /media, and not the media drive. */
export function backupDriveOptions(disks, mediaDirectory) {
const media = mediaDirectory || '/media/wrolpi';
return (disks || [])
.filter(d => d.mountpoint && d.uuid && d.mountpoint.startsWith('/media/')
&& d.mountpoint !== media && d.mountpoint !== '/media/wrolpi_temp_onboarding')
.map(d => ({value: d.mountpoint, uuid: d.uuid, label: `${d.label || d.name} (${d.size}) at ${d.mountpoint}`}));
}
/** Split a saved backup directory into the drive it is on (its option) and the folder on that drive. */
export function splitBackupDirectory(directory, uuid, options) {
if (!directory) {
return {drive: '', folder: ''};
}
const onDrive = options.filter(i => directory === i.value || directory.startsWith(`${i.value}/`));
// The drive with the saved UUID, else the deepest mount point that holds the directory.
const drive = onDrive.find(i => i.uuid === uuid)
|| onDrive.sort((a, b) => b.value.length - a.value.length)[0];
if (!drive) {
return {drive: directory, folder: ''};
}
return {drive: drive.value, folder: directory.slice(drive.value.length).replace(/^\/+/, '')};
}
/** The progress and outcome of copying the media directory to the backup drive. */
export function BackupStatus({backup, running}) {
if (!backup) {
return null;
}
return <div>
{running && <Progress percent={backup.percent}
label={`${backup.phase === 'database' ? 'Copying the database (this finishes first)'
: `${backup.files_transferred} files`} (${humanFileSize(backup.bytes_transferred)})`}/>}
<p>
<b>Last successful backup:</b> {backup.last_success_at
? isoDatetimeToAgoPopup(backup.last_success_at) : 'Never'}
</p>
{backup.last_error && !running && <Message kind='error' icon='warning' title='Backup problem'>
{backup.last_error}
</Message>}
{backup.last_skip_reason && !running && <p style={{color: 'var(--muted)'}}>
Not backed up: {backup.last_skip_reason}
</p>}
</div>
}
/** The Sync tab's backup drive: a second drive this WROLPi copies its media directory to. */
export function BackupDriveSection() {
const {settings, fetchSettings} = React.useContext(SettingsContext);
const {status} = React.useContext(StatusContext);
const wrolMode = useWROLMode();
const dockerized = useDockerized();
const [disks, setDisks] = React.useState(null);
const [disksError, setDisksError] = React.useState(null);
const [drive, setDrive] = React.useState('');
const [folder, setFolder] = React.useState('');
const [windowStart, setWindowStart] = React.useState('');
const [windowEnd, setWindowEnd] = React.useState('');
const [excluded, setExcluded] = React.useState([]);
const [saving, setSaving] = React.useState(false);
const savedDirectory = settings?.backup_directory || '';
const savedUuid = settings?.backup_device_uuid || '';
const options = backupDriveOptions(disks, settings?.media_directory);
const saved = splitBackupDirectory(savedDirectory, savedUuid, options);
React.useEffect(() => {
setDrive(saved.drive);
setFolder(saved.folder);
}, [saved.drive, saved.folder]);
const savedWindowStart = settings?.backup_window_start || '';
const savedWindowEnd = settings?.backup_window_end || '';
React.useEffect(() => {
setWindowStart(savedWindowStart);
setWindowEnd(savedWindowEnd);
}, [savedWindowStart, savedWindowEnd]);
const savedExcluded = JSON.stringify(settings?.backup_excluded_directories || []);
React.useEffect(() => {
setExcluded(JSON.parse(savedExcluded));
}, [savedExcluded]);
React.useEffect(() => {
if (dockerized === false) {
getDisks().then(setDisks).catch(e => setDisksError(e.message));
}
}, [dockerized]);
if (!settings || dockerized !== false) {
// Docker cannot reach other drives.
return null;
}
if (saved.drive && !options.find(i => i.value === saved.drive)) {
// The chosen drive is unplugged; keep showing it.
options.push({value: saved.drive, uuid: savedUuid, label: `${saved.drive} (not mounted)`});
}
const data = [{value: 'none', label: 'None'}, ...options.map(({value, label}) => ({value, label}))];
const running = status?.flags?.backup_running === true;
const save = async () => {
setSaving(true);
try {
const chosen = options.find(i => i.value === drive);
const cleanFolder = folder.trim().replace(/^\/+|\/+$/g, '');
const response = await saveSyncSettings({
backup_directory: chosen ? (cleanFolder ? `${chosen.value}/${cleanFolder}` : chosen.value) : '',
backup_device_uuid: chosen ? chosen.uuid : '',
backup_window_start: chosen ? windowStart : '',
backup_window_end: chosen ? windowEnd : '',
backup_excluded_directories: excluded,
});
if (response?.ok) {
toast({type: 'success', title: 'Backup drive saved', time: 3000});
}
await fetchSettings();
} finally {
setSaving(false);
}
};
const backUpNow = async () => {
const response = await runBackup();
if (response?.ok) {
toast({type: 'info', title: 'Backup requested', description: 'The backup starts in a few seconds.',
time: 3000});
}
};
return <Panel>
<Header as='h3' icon='hdd'>Backup Drive</Header>
<p>
Copy this WROLPi's media directory to a second drive, so the drive can replace the media drive if it
fails. Files deleted here are kept on the backup drive.
</p>
{disksError && <Message kind='error' icon='warning' title='Could not list drives'>{disksError}</Message>}
<div style={{margin: '0.5em 0', maxWidth: '30em'}}>
<label><b>Backup drive</b></label>
<Select data={data} value={drive || 'none'} allowDeselect={false} disabled={wrolMode}
onChange={value => setDrive(value === 'none' ? '' : value)}/>
</div>
{drive && <div style={{margin: '0.5em 0', maxWidth: '30em'}}>
<label><b>Folder on the drive</b></label>
<TextInput placeholder='The whole drive' value={folder} disabled={wrolMode}
onChange={e => setFolder(e.currentTarget.value)}/>
<p style={{color: 'var(--muted)', fontSize: '0.9em'}}>
The media directory is copied into this folder; leave it empty to use the whole drive.
</p>
</div>}
{drive && <>
<div style={{display: 'flex', gap: '1em', flexWrap: 'wrap', margin: '0.5em 0'}}>
<div>
<label><b>Backup Window Start</b></label>
<TextInput type='time' value={windowStart} disabled={wrolMode} aria-label='Backup Window Start'
onChange={e => setWindowStart(e.currentTarget.value)}/>
</div>
<div>
<label><b>Backup Window End</b></label>
<TextInput type='time' value={windowEnd} disabled={wrolMode} aria-label='Backup Window End'
onChange={e => setWindowEnd(e.currentTarget.value)}/>
</div>
</div>
<p style={{color: 'var(--muted)', fontSize: '0.9em'}}>
Within the window, the backup drive is updated every hour. Leave both empty to back up only with
"Back Up Now".
</p>
<ExcludedDirectories value={excluded} onChange={setExcluded} source='local' disabled={wrolMode}/>
</>}
<div style={{display: 'flex', gap: '0.5em', flexWrap: 'wrap'}}>
<Button color='violet' onClick={save} disabled={wrolMode || saving}>Save</Button>
{savedDirectory && !running && <Button onClick={backUpNow} disabled={wrolMode}>Back Up Now</Button>}
{/* The database snapshot runs to the end; a half-written database is worse than waiting for it. */}
{running && <Button color='red' onClick={cancelBackup} disabled={status?.backup?.phase === 'database'}>
Stop Backup
</Button>}
</div>
{savedDirectory && <BackupStatus backup={status?.backup} running={running}/>}
</Panel>
}
/** The Sync tab of /admin. */
export function SyncPage() {
useTitle('Sync');
return <div className='wrolpi-stack'>
<SecondaryRoleMessage/>
<SyncSection/>
<BackupDriveSection/>
</div>
}

View file

@ -0,0 +1,343 @@
import React from 'react';
import {fireEvent, screen, waitFor} from '@testing-library/react';
import {renderWithProviders} from '../../test-utils';
import {backupStatusFixture, settingsFixture, statusFixture, syncStatusFixture} from '../../test-fixtures';
import {
BackupDriveSection, backupDriveOptions, ExcludedDirectories, isExcludedPath, SecondaryRoleMessage, simplifyExcluded,
splitBackupDirectory, SyncingOverlay, SyncSection,
} from './Sync';
jest.mock('../../api/controller', () => ({
getDisks: jest.fn(),
}));
jest.mock('../../api', () => ({
cancelBackup: jest.fn(),
runBackup: jest.fn(),
cancelSync: jest.fn(),
runSync: jest.fn(),
saveSyncSettings: jest.fn(),
testSync: jest.fn(),
getSyncDirectories: jest.fn(),
PrimaryUnreachableError: class PrimaryUnreachableError extends Error {
},
}));
import {
cancelBackup, cancelSync, getSyncDirectories, PrimaryUnreachableError, runBackup, runSync, saveSyncSettings, testSync,
} from '../../api';
import {getDisks} from '../../api/controller';
beforeEach(() => {
// react-scripts resets mock implementations before each test.
cancelSync.mockResolvedValue({ok: true});
runSync.mockResolvedValue({ok: true});
saveSyncSettings.mockResolvedValue({ok: true});
testSync.mockResolvedValue({ok: true, info: {version: '0.30.5-beta'}});
runBackup.mockResolvedValue({ok: true});
cancelBackup.mockResolvedValue({ok: true});
getDisks.mockResolvedValue(disks);
getSyncDirectories.mockImplementation(async path => folderTree[path] || []);
});
const folderTree = {
'': [{name: 'Movies', path: 'Movies'}, {name: 'videos', path: 'videos'}],
'videos': [{name: 'channel', path: 'videos/channel'}],
'videos/channel': [],
};
const disks = [
{name: 'sda1', size: '9.1T', mountpoint: '/media/wrolpi_backup', label: 'Decay2of2', uuid: 'uuid-backup'},
{name: 'sdb1', size: '9.1T', mountpoint: '/media/wrolpi', label: 'Decay1of2', uuid: 'uuid-media'},
{name: 'mmcblk0p2', size: '118.6G', mountpoint: '/', label: 'rootfs', uuid: 'uuid-root'},
{name: 'sdc1', size: '64G', mountpoint: null, label: 'stick', uuid: 'uuid-stick'},
];
const secondary = (overrides = {}) => ({
settings: settingsFixture({role: 'secondary', sync_primary_url: 'https://192.168.0.10', ...overrides}),
});
describe('SecondaryRoleMessage', () => {
it('warns on a secondary', () => {
renderWithProviders(<SecondaryRoleMessage/>, {settings: secondary()});
expect(screen.getByText('Secondary WROLPi')).toBeInTheDocument();
expect(screen.getByText('https://192.168.0.10')).toBeInTheDocument();
});
it('is absent on a primary', () => {
renderWithProviders(<SecondaryRoleMessage/>);
expect(screen.queryByText('Secondary WROLPi')).not.toBeInTheDocument();
});
it('goes away in WROL Mode, which stops syncing', () => {
renderWithProviders(<SecondaryRoleMessage/>, {settings: secondary({wrol_mode: true})});
expect(screen.queryByText('Secondary WROLPi')).not.toBeInTheDocument();
});
});
describe('SyncingOverlay', () => {
const syncing = (sync = {}) => ({
status: statusFixture({
flags: {sync_running: true},
sync: syncStatusFixture({state: 'running', phase: 'files', groups_seen: 50, max_id: 100, ...sync}),
}),
});
it('covers the app while a secondary syncs', () => {
renderWithProviders(<SyncingOverlay/>, {settings: secondary(), status: syncing()});
expect(screen.getByRole('alertdialog', {name: 'Syncing'})).toBeInTheDocument();
expect(screen.getByText('Syncing from the primary')).toBeInTheDocument();
fireEvent.click(screen.getByText('Stop Sync'));
expect(cancelSync).toHaveBeenCalled();
});
it('is absent when not syncing', () => {
renderWithProviders(<SyncingOverlay/>, {settings: secondary()});
expect(screen.queryByRole('alertdialog')).not.toBeInTheDocument();
});
it('is absent on a primary', () => {
renderWithProviders(<SyncingOverlay/>, {status: syncing()});
expect(screen.queryByRole('alertdialog')).not.toBeInTheDocument();
});
});
describe('SyncSection', () => {
it('a primary shows only its role', () => {
// Even with a backup drive: the backup has its own window, in its own panel.
renderWithProviders(<SyncSection/>, {settings: {settings: settingsFixture({
backup_directory: '/media/wrolpi_backup', backup_device_uuid: 'uuid-backup'})}});
expect(screen.getByText('This WROLPi is')).toBeInTheDocument();
expect(screen.queryByText('Primary address')).not.toBeInTheDocument();
expect(screen.queryByText('Sync Window Start')).not.toBeInTheDocument();
expect(screen.queryByText('Sync Now')).not.toBeInTheDocument();
});
it('a secondary shows its primary, window, and sync controls', async () => {
const status = {status: statusFixture({sync: syncStatusFixture({last_error: 'The primary did not answer'})})};
renderWithProviders(<SyncSection/>, {settings: secondary({sync_window_start: '01:00'}), status});
expect(screen.getByDisplayValue('https://192.168.0.10')).toBeInTheDocument();
expect(screen.getByDisplayValue('01:00')).toBeInTheDocument();
expect(screen.getByText('The primary did not answer')).toBeInTheDocument();
fireEvent.click(screen.getByText('Sync Now'));
await waitFor(() => expect(runSync).toHaveBeenCalled());
fireEvent.click(screen.getByText('Save'));
await waitFor(() => expect(saveSyncSettings).toHaveBeenCalledWith({
role: 'secondary', sync_primary_url: 'https://192.168.0.10', sync_window_start: '01:00',
sync_window_end: '', sync_excluded_directories: [],
}));
});
it('WROL Mode stops syncing', () => {
renderWithProviders(<SyncSection/>, {settings: secondary({wrol_mode: true})});
expect(screen.getByText('Syncing is stopped')).toBeInTheDocument();
expect(screen.getByText('Sync Now').closest('button')).toBeDisabled();
});
});
describe('backupDriveOptions', () => {
it('lists mounted drives under /media that are not the media drive', () => {
expect(backupDriveOptions(disks, '/media/wrolpi')).toEqual([
{value: '/media/wrolpi_backup', uuid: 'uuid-backup', label: 'Decay2of2 (9.1T) at /media/wrolpi_backup'},
]);
});
});
describe('BackupDriveSection', () => {
it('saves the chosen drive with its UUID', async () => {
renderWithProviders(<BackupDriveSection/>);
await waitFor(() => expect(getDisks).toHaveBeenCalled());
fireEvent.click(screen.getByDisplayValue('None'));
fireEvent.click(await screen.findByText('Decay2of2 (9.1T) at /media/wrolpi_backup'));
fireEvent.click(screen.getByText('Save'));
await waitFor(() => expect(saveSyncSettings).toHaveBeenCalledWith({
backup_directory: '/media/wrolpi_backup', backup_device_uuid: 'uuid-backup',
backup_window_start: '', backup_window_end: '', backup_excluded_directories: [],
}));
});
it('shows the backup and runs it on request', async () => {
const settings = {settings: settingsFixture({backup_directory: '/media/wrolpi_backup',
backup_device_uuid: 'uuid-backup'})};
const status = {status: statusFixture({backup: backupStatusFixture({last_error: 'rsync failed (12)'})})};
renderWithProviders(<BackupDriveSection/>, {settings, status});
expect(await screen.findByDisplayValue('Decay2of2 (9.1T) at /media/wrolpi_backup')).toBeInTheDocument();
expect(screen.getByText('rsync failed (12)')).toBeInTheDocument();
fireEvent.click(screen.getByText('Back Up Now'));
await waitFor(() => expect(runBackup).toHaveBeenCalled());
});
it('keeps an unplugged drive selected', async () => {
getDisks.mockResolvedValue([]);
const settings = {settings: settingsFixture({backup_directory: '/media/gone', backup_device_uuid: 'x'})};
renderWithProviders(<BackupDriveSection/>, {settings});
expect(await screen.findByDisplayValue('/media/gone (not mounted)')).toBeInTheDocument();
});
it('offers to stop a running backup', async () => {
const settings = {settings: settingsFixture({backup_directory: '/media/wrolpi_backup',
backup_device_uuid: 'uuid-backup'})};
const status = {status: statusFixture({flags: {backup_running: true},
backup: backupStatusFixture({state: 'running', phase: 'files', percent: 40})})};
renderWithProviders(<BackupDriveSection/>, {settings, status});
fireEvent.click(await screen.findByText('Stop Backup'));
expect(cancelBackup).toHaveBeenCalled();
});
it('is absent in Docker, which cannot reach other drives', () => {
renderWithProviders(<BackupDriveSection/>, {status: {status: statusFixture({dockerized: true})}});
expect(screen.queryByText('Backup Drive')).not.toBeInTheDocument();
expect(getDisks).not.toHaveBeenCalled();
});
});
describe('splitBackupDirectory', () => {
const options = [
{value: '/media/backup', uuid: 'uuid-backup'},
{value: '/media/backup/nested', uuid: 'uuid-nested'},
];
it('finds the drive and the folder on it', () => {
expect(splitBackupDirectory('/media/backup', 'uuid-backup', options))
.toEqual({drive: '/media/backup', folder: ''});
expect(splitBackupDirectory('/media/backup/wrolpi/library', 'uuid-backup', options))
.toEqual({drive: '/media/backup', folder: 'wrolpi/library'});
});
it('prefers the drive with the saved UUID', () => {
expect(splitBackupDirectory('/media/backup/nested/wrolpi', 'uuid-nested', options))
.toEqual({drive: '/media/backup/nested', folder: 'wrolpi'});
expect(splitBackupDirectory('/media/backup/nested/wrolpi', 'uuid-backup', options))
.toEqual({drive: '/media/backup', folder: 'nested/wrolpi'});
});
it('does not mistake a similarly named drive', () => {
expect(splitBackupDirectory('/media/backup2/wrolpi', 'x', options)).toEqual({drive: '/media/backup2/wrolpi', folder: ''});
});
it('is empty without a backup', () => {
expect(splitBackupDirectory('', '', options)).toEqual({drive: '', folder: ''});
});
});
describe('BackupDriveSection folder', () => {
it('saves a folder on the chosen drive', async () => {
renderWithProviders(<BackupDriveSection/>);
await waitFor(() => expect(getDisks).toHaveBeenCalled());
fireEvent.click(screen.getByDisplayValue('None'));
fireEvent.click(await screen.findByText('Decay2of2 (9.1T) at /media/wrolpi_backup'));
fireEvent.change(screen.getByPlaceholderText('The whole drive'), {target: {value: '/wrolpi/library/'}});
fireEvent.click(screen.getByText('Save'));
await waitFor(() => expect(saveSyncSettings).toHaveBeenCalledWith({
backup_directory: '/media/wrolpi_backup/wrolpi/library', backup_device_uuid: 'uuid-backup',
backup_window_start: '', backup_window_end: '', backup_excluded_directories: [],
}));
});
it('shows the saved folder', async () => {
const settings = {settings: settingsFixture({backup_directory: '/media/wrolpi_backup/wrolpi',
backup_device_uuid: 'uuid-backup'})};
renderWithProviders(<BackupDriveSection/>, {settings});
expect(await screen.findByDisplayValue('Decay2of2 (9.1T) at /media/wrolpi_backup')).toBeInTheDocument();
expect(screen.getByPlaceholderText('The whole drive')).toHaveValue('wrolpi');
});
});
describe('BackupDriveSection database phase', () => {
it('cannot be stopped while the database is copied', async () => {
const settings = {settings: settingsFixture({backup_directory: '/media/wrolpi_backup',
backup_device_uuid: 'uuid-backup'})};
const status = {status: statusFixture({flags: {backup_running: true},
backup: backupStatusFixture({state: 'running', phase: 'database'})})};
renderWithProviders(<BackupDriveSection/>, {settings, status});
expect((await screen.findByText('Stop Backup')).closest('button')).toBeDisabled();
});
});
describe('BackupDriveSection window', () => {
it('saves its own window with the drive', async () => {
const settings = {settings: settingsFixture({backup_directory: '/media/wrolpi_backup',
backup_device_uuid: 'uuid-backup', backup_window_start: '01:00', backup_window_end: '05:00'})};
renderWithProviders(<BackupDriveSection/>, {settings});
await screen.findByDisplayValue('Decay2of2 (9.1T) at /media/wrolpi_backup');
expect(screen.getByLabelText('Backup Window Start')).toHaveValue('01:00');
fireEvent.change(screen.getByLabelText('Backup Window End'), {target: {value: '04:30'}});
fireEvent.click(screen.getByText('Save'));
await waitFor(() => expect(saveSyncSettings).toHaveBeenCalledWith({
backup_directory: '/media/wrolpi_backup', backup_device_uuid: 'uuid-backup',
backup_window_start: '01:00', backup_window_end: '04:30', backup_excluded_directories: [],
}));
});
});
describe('excluded folders', () => {
it('isExcludedPath matches a folder and what is inside it, not a similar name', () => {
expect(isExcludedPath('Movies', ['Movies'])).toBe(true);
expect(isExcludedPath('Movies/a', ['Movies'])).toBe(true);
expect(isExcludedPath('Movies2', ['Movies'])).toBe(false);
});
it('simplifyExcluded drops folders inside another', () => {
expect(simplifyExcluded(['videos/channel', 'Movies', 'videos', 'Movies'])).toEqual(['Movies', 'videos']);
});
it('lists the excluded folders and removes one', () => {
const onChange = jest.fn();
renderWithProviders(<ExcludedDirectories value={['Movies', 'videos/channel']} onChange={onChange}
source='local'/>);
expect(screen.getByText('Movies')).toBeInTheDocument();
fireEvent.click(screen.getByLabelText('Copy Movies again'));
expect(onChange).toHaveBeenCalledWith(['videos/channel']);
});
it('chooses folders in the tree; a folder inside a checked folder is excluded with it', async () => {
const onChange = jest.fn();
renderWithProviders(<ExcludedDirectories value={[]} onChange={onChange} source='primary'/>);
expect(screen.getByText('Nothing excluded; every folder is copied.')).toBeInTheDocument();
fireEvent.click(screen.getByText('Choose Folders'));
await screen.findByLabelText('videos');
expect(getSyncDirectories).toHaveBeenCalledWith('', 'primary');
fireEvent.click(screen.getByLabelText('Open videos'));
const child = await screen.findByLabelText('videos/channel');
expect(getSyncDirectories).toHaveBeenCalledWith('videos', 'primary');
fireEvent.click(child);
fireEvent.click(screen.getByLabelText('videos'));
await waitFor(() => expect(screen.getByLabelText('videos/channel')).toBeDisabled());
expect(screen.getByLabelText('videos/channel')).toBeChecked();
expect(screen.getByText('excluded with its parent')).toBeInTheDocument();
fireEvent.click(screen.getByText('Done'));
expect(onChange).toHaveBeenCalledWith(['videos']);
});
it('says when the primary does not answer', async () => {
getSyncDirectories.mockRejectedValue(new PrimaryUnreachableError('connection refused'));
renderWithProviders(<ExcludedDirectories value={[]} onChange={jest.fn()} source='primary'/>);
fireEvent.click(screen.getByText('Choose Folders'));
expect(await screen.findByText('The primary did not answer: connection refused')).toBeInTheDocument();
});
it('a secondary saves its excluded folders', async () => {
renderWithProviders(<SyncSection/>, {settings: secondary({sync_excluded_directories: ['Movies']})});
expect(screen.getByText('Movies')).toBeInTheDocument();
fireEvent.click(screen.getByText('Save'));
await waitFor(() => expect(saveSyncSettings).toHaveBeenCalledWith(
expect.objectContaining({sync_excluded_directories: ['Movies']})));
});
it('the backup drive saves its own excluded folders', async () => {
const settings = {settings: settingsFixture({backup_directory: '/media/wrolpi_backup',
backup_device_uuid: 'uuid-backup', backup_excluded_directories: ['Movies']})};
renderWithProviders(<BackupDriveSection/>, {settings});
await screen.findByDisplayValue('Decay2of2 (9.1T) at /media/wrolpi_backup');
fireEvent.click(screen.getByLabelText('Copy Movies again'));
fireEvent.click(screen.getByText('Save'));
await waitFor(() => expect(saveSyncSettings).toHaveBeenCalledWith(
expect.objectContaining({backup_excluded_directories: []})));
});
});