Upgrading Sanic to 22.6.2.

This commit is contained in:
Roland 2022-10-09 18:42:23 -06:00 • committed by lrnselfreliance
parent 798f232fc5
commit f0f48164f5
5 changed files with 52 additions and 66 deletions

44
main.py
View file

@ -1,18 +1,18 @@
#! /usr/bin/env python3
import argparse
import asyncio
import inspect
import logging
import os
import sys
import pytz
from sanic import Sanic
from sanic.signals import Event
from wrolpi import root_api, BEFORE_STARTUP_FUNCTIONS, admin, after_startup
from wrolpi import root_api, BEFORE_STARTUP_FUNCTIONS, admin
from wrolpi.common import logger, get_config, import_modules, check_media_directory, limit_concurrent, wrol_mode_enabled
from wrolpi.dates import set_timezone
from wrolpi.downloader import download_manager
from wrolpi.root_api import api_app
from wrolpi.vars import PROJECT_DIR, DOCKERIZED, PYTEST
from wrolpi.version import get_version_string
@ -71,7 +71,7 @@ def launch_interactive_shell():
code.interact(banner=INTERACTIVE_BANNER, local=locals())
async def main(loop):
def main():
parser = argparse.ArgumentParser()
parser.add_argument('-v', '--verbose', action='count')
parser.add_argument('--version', action='store_true', default=False)
@ -111,7 +111,7 @@ async def main(loop):
return 0
logger.warning(f'Starting with: {sys.argv}')
await set_log_level(args)
set_log_level(args)
logger.debug(get_version_string())
if DOCKERIZED:
@ -142,17 +142,15 @@ async def main(loop):
for func in BEFORE_STARTUP_FUNCTIONS:
try:
logger.debug(f'Calling {func} before startup.')
coro = func()
if inspect.iscoroutine(coro):
await coro
func()
except Exception as e:
logger.warning(f'Startup {func} failed!', exc_info=e)
# Run the API.
return root_api.main(loop, args)
return root_api.main(args)
async def set_log_level(args):
def set_log_level(args):
"""
Set the level at the root logger so all children that have been created (or will be created) share the same level.
"""
@ -172,9 +170,8 @@ async def set_log_level(args):
logger.warning(f'Logging level: {level_name}')
@after_startup
@limit_concurrent(1)
async def periodic_downloads(app: Sanic, loop):
@api_app.after_server_start
async def periodic_downloads(app: Sanic):
"""
Starts the perpetual downloader on download manager.
@ -184,22 +181,22 @@ async def periodic_downloads(app: Sanic, loop):
download_manager.reset_downloads()
if wrol_mode_enabled():
logger.warning(f'Not starting download manager because WROL Mode is enabled.')
logger.warning('Not starting download manager because WROL Mode is enabled.')
download_manager.disable()
return
config = get_config()
if config.download_on_startup is False:
logger.warning(f'Not starting download manager because Downloads are disabled on startup.')
logger.warning('Not starting download manager because Downloads are disabled on startup.')
download_manager.disable()
return
download_manager.enable()
await app.add_task(download_manager.perpetual_download())
app.add_task(download_manager.perpetual_download())
@after_startup
async def start_workers(app: Sanic, loop):
@api_app.after_server_start
async def start_workers(app: Sanic):
"""All Sanic processes have their own Download workers."""
if wrol_mode_enabled():
logger.warning(f'Not starting download workers because WROL Mode is enabled.')
@ -209,11 +206,10 @@ async def start_workers(app: Sanic, loop):
download_manager.start_workers()
@after_startup
@limit_concurrent(1)
async def bandwidth_worker(app: Sanic, loop):
@api_app.after_server_start
async def bandwidth_worker(app: Sanic):
from wrolpi import status
await app.add_task(status.bandwidth_worker())
app.add_task(status.bandwidth_worker())
@root_api.api_app.signal(Event.SERVER_SHUTDOWN_BEFORE)
@ -225,6 +221,4 @@ def handle_server_shutdown(*args, **kwargs):
if __name__ == '__main__':
loop_ = asyncio.get_event_loop()
result_ = loop_.run_until_complete(main(loop_))
sys.exit(result_)
sys.exit(main())

View file

@ -15,9 +15,9 @@ pytest==6.2.5
python-dotenv==0.19.2
python-magic~=0.4.27
pytz==2021.3
sanic-ext==22.1.2
sanic-testing==0.8.2
sanic==21.12.2
sanic-ext==22.6.3
sanic-testing==22.6.0
sanic==22.6.2
selenium==4.1.0
srt==3.5.1
websockets==10.1

View file

@ -7,7 +7,7 @@ from sanic import response
from sanic_ext import validate
from sanic_ext.extensions.openapi import openapi
from wrolpi.common import get_media_directory, api_param_limiter, wrol_mode_check
from wrolpi.common import get_media_directory, wrol_mode_check
from wrolpi.errors import InvalidFile
from wrolpi.root_api import get_blueprint, json_response
from . import lib, schema
@ -71,10 +71,6 @@ async def delete_file(_: Request, body: schema.DeleteRequest):
return response.empty()
files_limit_limiter = api_param_limiter(100)
files_offset_limiter = api_param_limiter(100, 0)
@bp.post('/refresh')
@openapi.description('Find and index all files in the media directory.')
@wrol_mode_check
@ -87,7 +83,7 @@ async def refresh(_: Request):
@openapi.description('Find and index all files in the provided directory.')
@validate(schema.DirectoryRefreshRequest)
@wrol_mode_check
async def refresh(_: Request, body: schema.DirectoryRefreshRequest):
async def refresh_directory(_: Request, body: schema.DirectoryRefreshRequest):
directory = get_media_directory() / body.directory
if PYTEST:
await lib.refresh_directory_files_recursively(directory)

View file

@ -24,7 +24,6 @@ from wrolpi.dates import set_timezone
from wrolpi.downloader import download_manager
from wrolpi.errors import WROLModeEnabled, InvalidTimezone, API_ERRORS, APIError, ValidationError, HotspotError
from wrolpi.schema import RegexRequest, RegexResponse, SettingsRequest, SettingsResponse, DownloadRequest, EchoResponse
from wrolpi.vars import DOCKERIZED
from wrolpi.version import __version__
logger = logger.getChild(__name__)
@ -33,9 +32,9 @@ api_app = Sanic(name='api_app')
DEFAULT_HOST, DEFAULT_PORT = '127.0.0.1', '8081'
root_api = Blueprint('RootAPI', url_prefix='/api')
api_bp = Blueprint('RootAPI', url_prefix='/api')
BLUEPRINTS = [root_api, ]
BLUEPRINTS = [api_bp, ]
def get_blueprint(name: str, url_prefix: str) -> Blueprint:
@ -51,13 +50,12 @@ def add_blueprint(bp: Union[Blueprint, BlueprintGroup]):
BLUEPRINTS.append(bp)
def run_webserver(loop, host: str, port: int, workers: int = 8):
def run_webserver(host: str, port: int, workers: int = 8):
# Attach all blueprints after they have been defined.
for bp in BLUEPRINTS:
api_app.blueprint(bp)
# TODO remove the auto reload when development is stable
kwargs = dict(host=host, port=port, workers=workers, auto_reload=DOCKERIZED)
kwargs = dict(host=host, port=port, workers=workers, debug=False, access_log=False, auto_reload=True)
logger.debug(f'Running Sanic {sanic_version} with kwargs {kwargs}')
return api_app.run(**kwargs)
@ -70,8 +68,8 @@ def init_parser(parser):
help='How many web workers to run')
def main(loop, args):
return run_webserver(loop, args.host, args.port, args.workers)
def main(args):
return run_webserver(args.host, args.port, args.workers)
index_html = '''
@ -94,7 +92,7 @@ def index(_):
return response.html(index_html)
@root_api.route('/echo', methods=['GET', 'POST', 'PUT', 'DELETE', 'PATCH', 'OPTIONS'])
@api_bp.route('/echo', methods=['GET', 'POST', 'PUT', 'DELETE', 'PATCH', 'OPTIONS'])
@openapi.description('Echo whatever is sent to this.')
@openapi.response(HTTPStatus.OK, EchoResponse)
async def echo(request: Request):
@ -108,7 +106,7 @@ async def echo(request: Request):
return response.json(ret)
@root_api.route('/settings', methods=['GET', 'OPTIONS'])
@api_bp.route('/settings', methods=['GET', 'OPTIONS'])
@openapi.description('Get WROLPi settings')
@openapi.response(HTTPStatus.OK, SettingsResponse)
def get_settings(_: Request):
@ -134,7 +132,7 @@ def get_settings(_: Request):
return json_response(settings)
@root_api.patch('/settings')
@api_bp.patch('/settings')
@openapi.description('Update WROLPi settings')
@validate(json=SettingsRequest)
def update_settings(_: Request, body: SettingsRequest):
@ -178,7 +176,7 @@ def update_settings(_: Request, body: SettingsRequest):
return response.empty()
@root_api.post('/valid_regex')
@api_bp.post('/valid_regex')
@openapi.description('Check if the regex is valid.')
@openapi.response(HTTPStatus.OK, RegexResponse)
@openapi.response(HTTPStatus.BAD_REQUEST, RegexResponse)
@ -191,7 +189,7 @@ def valid_regex(_: Request, body: RegexRequest):
return response.json({'valid': False, 'regex': body.regex}, HTTPStatus.BAD_REQUEST)
@root_api.post('/download')
@api_bp.post('/download')
@openapi.description('Download the many URLs that are provided.')
@validate(DownloadRequest)
@wrol_mode_check
@ -210,49 +208,49 @@ async def post_download(_: Request, body: DownloadRequest):
return response.empty()
@root_api.get('/download')
@api_bp.get('/download')
@openapi.description('Get all Downloads that need to be processed.')
async def get_downloads(_: Request):
data = download_manager.get_fe_downloads()
return json_response(data)
@root_api.post('/download/<download_id:int>/kill')
@api_bp.post('/download/<download_id:int>/kill')
@openapi.description('Kill a download. It will be stopped if it is pending.')
async def kill_download(_: Request, download_id: int):
download_manager.kill_download(download_id)
return response.empty()
@root_api.post('/download/kill')
@api_bp.post('/download/kill')
@openapi.description('Kill all downloads. Disable downloading.')
async def kill_downloads(_: Request):
download_manager.disable()
return response.empty()
@root_api.post('/download/enable')
@api_bp.post('/download/enable')
@openapi.description('Enable and start downloading.')
async def enable_downloads(_: Request):
download_manager.enable()
return response.empty()
@root_api.post('/download/clear_completed')
@api_bp.post('/download/clear_completed')
@openapi.description('Clear completed downloads')
async def clear_completed(_: Request):
download_manager.delete_completed()
return response.empty()
@root_api.post('/download/clear_failed')
@api_bp.post('/download/clear_failed')
@openapi.description('Clear failed downloads')
async def clear_failed(_: Request):
download_manager.delete_failed()
return response.empty()
@root_api.delete('/download/<download_id:integer>')
@api_bp.delete('/download/<download_id:integer>')
@openapi.description('Delete a download')
@wrol_mode_check
async def delete_download(_: Request, download_id: int):
@ -260,7 +258,7 @@ async def delete_download(_: Request, download_id: int):
return response.empty(HTTPStatus.NO_CONTENT if deleted else HTTPStatus.NOT_FOUND)
@root_api.get('/downloaders')
@api_bp.get('/downloaders')
@openapi.description('List all Downloaders that can be specified by the user.')
async def get_downloaders(_: Request):
downloaders = download_manager.list_downloaders()
@ -269,7 +267,7 @@ async def get_downloaders(_: Request):
return json_response(ret)
@root_api.post('/hotspot/on')
@api_bp.post('/hotspot/on')
@openapi.description('Turn on the hotspot')
@native_only
async def hotspot_on(_: Request):
@ -279,7 +277,7 @@ async def hotspot_on(_: Request):
return response.empty(HTTPStatus.INTERNAL_SERVER_ERROR)
@root_api.post('/hotspot/off')
@api_bp.post('/hotspot/off')
@openapi.description('Turn off the hotspot')
@native_only
async def hotspot_off(_: Request):
@ -289,7 +287,7 @@ async def hotspot_off(_: Request):
return response.empty(HTTPStatus.INTERNAL_SERVER_ERROR)
@root_api.post('/throttle/on')
@api_bp.post('/throttle/on')
@openapi.description('Turn on CPU throttling')
@native_only
async def throttle_on(_: Request):
@ -299,7 +297,7 @@ async def throttle_on(_: Request):
return response.empty(HTTPStatus.INTERNAL_SERVER_ERROR)
@root_api.post('/throttle/off')
@api_bp.post('/throttle/off')
@openapi.description('Turn off CPU throttling')
@native_only
async def throttle_off(_: Request):
@ -309,7 +307,7 @@ async def throttle_off(_: Request):
return response.empty(HTTPStatus.INTERNAL_SERVER_ERROR)
@root_api.get('/status')
@api_bp.get('/status')
@openapi.description('Get the status of CPU/load/etc.')
async def get_status(_: Request):
s = await status.get_status()

View file

@ -339,21 +339,19 @@ def _get_nic_tick(name_):
def _calculate_bytes_per_second(history: List[Tuple]) -> Tuple[int, int, int]:
"""
Calculate the bytes-per-second between the oldest and newest tick.
"""
"""Calculate the bytes-per-second between the oldest and newest tick."""
(oldest_now, oldest_recv, oldest_sent, _), (newest_now, newest_recv, newest_sent, _) = \
history[0], history[-1]
elapsed = int(newest_now - oldest_now)
if elapsed == 0:
return 0, 0, 0
bytes_recv_ps = int((newest_recv - oldest_recv) // elapsed)
bytes_sent_ps = int((newest_sent - oldest_sent) // elapsed)
return bytes_recv_ps, bytes_sent_ps, elapsed
async def bandwidth_worker(count: int = None):
"""
A background process which will gather historical data about all NIC bandwidth statistics.
"""
"""A background process which will gather historical data about all NIC bandwidth statistics."""
if not psutil:
return