From 253701703922cbddc6e5d116798deb2c2a76432e Mon Sep 17 00:00:00 2001 From: Roland Date: Thu, 17 Aug 2023 20:07:02 -0600 Subject: [PATCH] Creating shutdown and restart buttons. --- app/src/api.js | 21 ++++- app/src/components/Common.js | 1 + app/src/components/admin/AdminRoute.js | 4 +- app/src/components/admin/Settings.js | 103 +++++++++++++++++++++-- app/src/hooks/customHooks.js | 7 +- pi-gen/stage2/04-wrolpi/03-run-chroot.sh | 2 + scripts/install_debian_11.sh | 2 + scripts/install_raspberrypios.sh | 2 + wrolpi/admin.py | 38 +++++++++ wrolpi/errors.py | 12 +++ wrolpi/root_api.py | 20 ++++- 11 files changed, 198 insertions(+), 14 deletions(-) diff --git a/app/src/api.js b/app/src/api.js index c390ed9e..e68edbe7 100644 --- a/app/src/api.js +++ b/app/src/api.js @@ -1024,7 +1024,20 @@ export async function deleteOutdatedZims() { return response.status === 204; } -export async function ignoreOutdatedZims() { - const response = await apiPost(`${API_URI}/zim/outdated`); - return response.status === 204; -} \ No newline at end of file +export async function postShutdown() { + const response = await apiPost(`${API_URI}/shutdown`); + if (response.status !== 204) { + // Return the error. + return await response.json(); + } + return null +} + +export async function postRestart() { + const response = await apiPost(`${API_URI}/restart`); + if (response.status !== 204) { + // Return the error. + return await response.json(); + } + return null +} diff --git a/app/src/components/Common.js b/app/src/components/Common.js index 1f49c52b..a62ec43e 100644 --- a/app/src/components/Common.js +++ b/app/src/components/Common.js @@ -1363,6 +1363,7 @@ export function useAPIButton( onClose={() => setConfirmOpen(false)} onCancel={() => setConfirmOpen(false)} onConfirm={localOnConfirm} + confirmButton={confirmButton} /> } diff --git a/app/src/components/admin/AdminRoute.js b/app/src/components/admin/AdminRoute.js index caef815f..c1f670fe 100644 --- a/app/src/components/admin/AdminRoute.js +++ b/app/src/components/admin/AdminRoute.js @@ -6,7 +6,7 @@ import {Route, Routes} from "react-router-dom"; import {ThemeContext} from "../../contexts/contexts"; import {Header, Loader, Segment} from "../Theme"; import {DownloadsPage} from "./Downloads"; -import {Settings} from "./Settings"; +import {SettingsPage} from "./Settings"; import {Status} from "./Status"; class WROLMode extends React.Component { @@ -78,7 +78,7 @@ export default function AdminRoute() { }/> - }/> + }/> }/> }/> diff --git a/app/src/components/admin/Settings.js b/app/src/components/admin/Settings.js index 184d13da..a8f44726 100644 --- a/app/src/components/admin/Settings.js +++ b/app/src/components/admin/Settings.js @@ -1,12 +1,102 @@ import React from "react"; -import {getSettings, saveSettings} from "../../api"; +import {getSettings, postRestart, postShutdown, saveSettings} from "../../api"; import {Button, Form, FormGroup, FormInput, Header, Loader, Modal, ModalContent, ModalHeader, Segment} from "../Theme"; import {Container, Dimmer, Icon} from "semantic-ui-react"; import {ThemeContext} from "../../contexts/contexts"; import {APIButton, HelpPopup, HotspotToggle, ThrottleToggle, Toggle, WROLModeMessage} from "../Common"; import QRCode from "react-qr-code"; +import {toast} from "react-semantic-toasts-2"; +import {useDockerized} from "../../hooks/customHooks"; -export class Settings extends React.Component { +export function ShutdownButton() { + const dockerized = useDockerized(); + + const handleShutdown = async () => { + try { + const response = await postShutdown(); + if (response && response['code'] === 'SHUTDOWN_FAILED') { + toast({ + title: 'Shutdown Failed', + description: response['error'], + time: 5000, + type: "error", + }) + } else if (response !== null) { + toast({ + title: 'Shutdown Failed', + description: 'Unknown error when attempting shutdown', + time: 5000, + type: "error", + }) + } + } catch (e) { + toast({ + title: 'Shutdown Failed', + description: 'Failed to request WROLPi shutdown', + time: 5000, + type: "error", + }) + throw e; + } + } + + return + Shutdown + +} + +export function RestartButton() { + const dockerized = useDockerized(); + + const handleRestart = async () => { + try { + const response = await postRestart(); + if (response && response['code'] === 'RESTART_FAILED') { + toast({ + title: 'Restart Failed', + description: response['error'], + time: 5000, + type: "error", + }) + } else if (response !== null) { + toast({ + title: 'Restart Failed', + description: 'Unknown error when attempting restart', + time: 5000, + type: "error", + }) + } + } catch (e) { + toast({ + title: 'Restart Failed', + description: 'Failed to request WROLPi restart', + time: 5000, + type: "error", + }) + throw e; + } + } + + return + Restart + +} + +export class SettingsPage extends React.Component { constructor(props) { super(props); @@ -21,7 +111,6 @@ export class Settings extends React.Component { download_on_startup: null, download_timeout: null, hotspot_device: null, - hotspot_on_startup: null, hotspot_password: null, hotspot_ssid: null, hotspot_status: null, @@ -43,7 +132,6 @@ export class Settings extends React.Component { download_on_startup: settings.download_on_startup, download_timeout: settings.download_timeout || '', hotspot_device: settings.hotspot_device, - hotspot_on_startup: settings.hotspot_on_startup, hotspot_password: settings.hotspot_password, hotspot_ssid: settings.hotspot_ssid, hotspot_status: settings.hotspot_status, @@ -65,7 +153,6 @@ export class Settings extends React.Component { download_on_startup: this.state.download_on_startup, download_timeout: this.state.download_timeout ? parseInt(this.state.download_timeout) : 0, hotspot_device: this.state.hotspot_device, - hotspot_on_startup: this.state.hotspot_on_startup, hotspot_password: this.state.hotspot_password, hotspot_ssid: this.state.hotspot_ssid, ignore_outdated_zims: this.state.ignore_outdated_zims, @@ -113,7 +200,6 @@ export class Settings extends React.Component { download_on_startup, download_timeout, hotspot_device, - hotspot_on_startup, hotspot_password, hotspot_ssid, ignore_outdated_zims, @@ -235,6 +321,11 @@ export class Settings extends React.Component { + + + + + } } diff --git a/app/src/hooks/customHooks.js b/app/src/hooks/customHooks.js index 412b409d..77593f2f 100644 --- a/app/src/hooks/customHooks.js +++ b/app/src/hooks/customHooks.js @@ -1085,4 +1085,9 @@ export const useWROLMode = () => { // Returns the current boolean WROL Mode, during fetch this returns null. const {status} = useContext(StatusContext); return status ? status.wrol_mode : null; -} \ No newline at end of file +} + +export const useDockerized = () => { + const {status} = React.useContext(StatusContext); + return status && status['dockerized'] === true; +} diff --git a/pi-gen/stage2/04-wrolpi/03-run-chroot.sh b/pi-gen/stage2/04-wrolpi/03-run-chroot.sh index 362dfb19..a61ef679 100755 --- a/pi-gen/stage2/04-wrolpi/03-run-chroot.sh +++ b/pi-gen/stage2/04-wrolpi/03-run-chroot.sh @@ -67,6 +67,8 @@ cat >/etc/sudoers.d/90-wrolpi <<'EOF' %wrolpi ALL= NOPASSWD:/usr/bin/systemctl stop wrolpi-app.service %wrolpi ALL= NOPASSWD:/usr/bin/systemctl start wrolpi-app.service %wrolpi ALL= NOPASSWD:/opt/wrolpi/scripts/import_map.sh +%wrolpi ALL= NOPASSWD:poweroff +%wrolpi ALL= NOPASSWD:reboot EOF chmod 660 /etc/sudoers.d/90-wrolpi diff --git a/scripts/install_debian_11.sh b/scripts/install_debian_11.sh index d7ed63b1..06cf957d 100755 --- a/scripts/install_debian_11.sh +++ b/scripts/install_debian_11.sh @@ -89,6 +89,8 @@ cat >/etc/sudoers.d/90-wrolpi <<'EOF' %wrolpi ALL= NOPASSWD:/usr/bin/systemctl stop wrolpi-app.service %wrolpi ALL= NOPASSWD:/usr/bin/systemctl start wrolpi-app.service %wrolpi ALL= NOPASSWD:/opt/wrolpi/scripts/import_map.sh +%wrolpi ALL= NOPASSWD:poweroff +%wrolpi ALL= NOPASSWD:reboot EOF chmod 660 /etc/sudoers.d/90-wrolpi # Verify this new file is valid. diff --git a/scripts/install_raspberrypios.sh b/scripts/install_raspberrypios.sh index 13dec20a..257cef68 100755 --- a/scripts/install_raspberrypios.sh +++ b/scripts/install_raspberrypios.sh @@ -99,6 +99,8 @@ cat >/etc/sudoers.d/90-wrolpi <<'EOF' %wrolpi ALL= NOPASSWD:/usr/bin/systemctl stop wrolpi-app.service %wrolpi ALL= NOPASSWD:/usr/bin/systemctl start wrolpi-app.service %wrolpi ALL= NOPASSWD:/opt/wrolpi/scripts/import_map.sh +%wrolpi ALL= NOPASSWD:poweroff +%wrolpi ALL= NOPASSWD:reboot EOF chmod 660 /etc/sudoers.d/90-wrolpi # Verify this new file is valid. diff --git a/wrolpi/admin.py b/wrolpi/admin.py index 708c23cf..fdfa9290 100644 --- a/wrolpi/admin.py +++ b/wrolpi/admin.py @@ -1,8 +1,10 @@ +import asyncio import enum import subprocess from wrolpi.cmd import NMCLI_BIN, CPUFREQ_INFO_BIN, SUDO_BIN, CPUFREQ_SET_BIN from wrolpi.common import logger, WROLPI_CONFIG, get_warn_once +from wrolpi.errors import RestartFailed, ShutdownFailed from wrolpi.vars import DEFAULT_CPU_FREQUENCY, DOCKERIZED logger = logger.getChild(__name__) @@ -141,3 +143,39 @@ def throttle_cpu_off() -> bool: except FileNotFoundError: if not DOCKERIZED: logger.error('Could not disable CPU throttle', exc_info=True) + + +async def restart(): + """Restart the WROLPi. + + @raise RestartFailed: If restart is not possible, or if sudo command failed.""" + if DOCKERIZED: + raise RestartFailed('Cannot restart because we are dockerized') + + try: + cmd = f'{SUDO_BIN} reboot' + proc = await asyncio.create_subprocess_shell(cmd, stderr=asyncio.subprocess.PIPE, + stdout=asyncio.subprocess.PIPE) + except subprocess.CalledProcessError as e: + raise RestartFailed() from e + + if proc.returncode != 0: + raise RestartFailed(f'Got return code {proc.returncode}') + + +async def shutdown(): + """Shutdown the WROLPi. + + @raise ShutdownFailed: If shutdown is not possible, or if sudo command failed.""" + if DOCKERIZED: + raise ShutdownFailed('Cannot shutdown because we are dockerized') + + try: + cmd = f'{SUDO_BIN} poweroff' + proc = await asyncio.create_subprocess_shell(cmd, stderr=asyncio.subprocess.PIPE, + stdout=asyncio.subprocess.PIPE) + except subprocess.CalledProcessError as e: + raise ShutdownFailed() from e + + if proc.returncode != 0: + raise ShutdownFailed(f'Got return code {proc.returncode}') diff --git a/wrolpi/errors.py b/wrolpi/errors.py index 27f663f8..9fbf87e7 100644 --- a/wrolpi/errors.py +++ b/wrolpi/errors.py @@ -119,3 +119,15 @@ class HotspotPasswordTooShort(APIError): code = 'HOTSPOT_PASSWORD_TOO_SHORT' summary = 'Hotspot password must be at least 8 characters' status = HTTPStatus.BAD_REQUEST + + +class RestartFailed(APIError): + code = 'RESTART_FAILED' + summary = 'Unable to restart the WROLPi' + status = HTTPStatus.INTERNAL_SERVER_ERROR + + +class ShutdownFailed(APIError): + code = 'SHUTDOWN_FAILED' + summary = 'Unable to shutdown the WROLPi' + status = HTTPStatus.INTERNAL_SERVER_ERROR diff --git a/wrolpi/root_api.py b/wrolpi/root_api.py index e44ded90..abd3fa50 100644 --- a/wrolpi/root_api.py +++ b/wrolpi/root_api.py @@ -25,7 +25,7 @@ from wrolpi.common import logger, get_config, wrol_mode_enabled, Base, get_media from wrolpi.dates import now, strptime from wrolpi.downloader import download_manager from wrolpi.errors import WROLModeEnabled, APIError, HotspotError, InvalidDownload, \ - HotspotPasswordTooShort + HotspotPasswordTooShort, ShutdownFailed, RestartFailed from wrolpi.events import get_events, Events from wrolpi.files.lib import get_file_statistics, estimate_search from wrolpi.vars import API_HOST, API_PORT, DOCKERIZED, API_DEBUG, API_ACCESS_LOG, API_WORKERS, API_AUTO_RELOAD, \ @@ -501,6 +501,24 @@ async def post_search_estimate(_: Request, body: schema.SearchEstimateRequest): return json_response(ret) +@api_bp.post('/restart') +async def post_restart(_: Request): + if DOCKERIZED: + raise RestartFailed(f'Cannot restart when running in Docker') + + await admin.restart() + return response.empty(HTTPStatus.NO_CONTENT) + + +@api_bp.post('/shutdown') +async def post_shutdown(_: Request): + if DOCKERIZED: + raise ShutdownFailed(f'Cannot shutdown when running in Docker') + + await admin.shutdown() + return response.empty(HTTPStatus.NO_CONTENT) + + class CustomJSONEncoder(json.JSONEncoder): def default(self, obj):