mirror of
https://github.com/lrnselfreliance/wrolpi.git
synced 2026-11-25 17:36:18 -05:00
Top processes are displayed on Status page. Nice of renderd is lowered to avoid clobbering system at startup.
This commit is contained in:
parent
47b4da1cfe
commit
317f3f3dfb
26 changed files with 500 additions and 415 deletions
|
|
@ -76,6 +76,31 @@ jobs:
|
|||
command: './venv/bin/pytest -svv --junitxml=test-results.xml'
|
||||
- store_test_results:
|
||||
path: test-results.xml
|
||||
api-alembic-migrations:
|
||||
docker:
|
||||
- image: cimg/python:3.11
|
||||
- image: cimg/postgres:15.6
|
||||
environment:
|
||||
POSTGRES_USER: wrolpi
|
||||
POSTGRES_DB: wrolpi
|
||||
POSTGRES_PASSWORD: "wrolpi"
|
||||
resource_class: medium
|
||||
steps:
|
||||
- checkout
|
||||
- restore_cache:
|
||||
key: deps-3.11-{{ checksum "requirements.txt" }}-2
|
||||
- run:
|
||||
name: Install Requirements
|
||||
command: |
|
||||
python3 -m venv venv
|
||||
. venv/bin/activate
|
||||
pip install -r requirements.txt
|
||||
- save_cache:
|
||||
key: deps-3.11-{{ checksum "requirements.txt" }}-2
|
||||
paths:
|
||||
- "venv"
|
||||
- run:
|
||||
command: ./venv/bin/python ./main.py db upgrade
|
||||
api-tests-3-12:
|
||||
docker:
|
||||
- image: cimg/python:3.12
|
||||
|
|
@ -172,6 +197,7 @@ workflows:
|
|||
jobs:
|
||||
- sanic-api-start
|
||||
- api-tests-3-11
|
||||
- api-alembic-migrations
|
||||
# - api-tests-3-12 Sanic does not yet support 3.12.
|
||||
wrolpi-app-test:
|
||||
jobs:
|
||||
|
|
|
|||
|
|
@ -6,6 +6,7 @@ Create Date: 2024-07-31 14:58:29.583029
|
|||
|
||||
"""
|
||||
import os
|
||||
import sys
|
||||
|
||||
from alembic import op
|
||||
from sqlalchemy.orm import Session
|
||||
|
|
@ -38,9 +39,12 @@ def upgrade():
|
|||
if need_commit:
|
||||
session.commit()
|
||||
|
||||
config = get_tags_config()
|
||||
config.initialize()
|
||||
config.save_tags(session, ignore_lock=True)
|
||||
try:
|
||||
config = get_tags_config()
|
||||
config.initialize()
|
||||
config.save_tags(session, ignore_lock=True)
|
||||
except FileNotFoundError:
|
||||
print(f'Failed to save tags config probably because media directory does not exist', file=sys.stderr)
|
||||
|
||||
|
||||
def downgrade():
|
||||
|
|
|
|||
|
|
@ -6,12 +6,16 @@ Create Date: 2024-06-25 22:13:23.885687
|
|||
|
||||
"""
|
||||
import os
|
||||
import pathlib
|
||||
|
||||
from alembic import op
|
||||
from sqlalchemy import Column, Integer, String, Boolean, JSON, Date
|
||||
from sqlalchemy.ext.declarative import declarative_base
|
||||
from sqlalchemy.orm import Session
|
||||
from sqlalchemy.orm import Session, deferred
|
||||
|
||||
from modules.videos.lib import link_channel_and_downloads
|
||||
from wrolpi.common import ModelHelper
|
||||
from wrolpi.media_path import MediaPathType
|
||||
|
||||
# revision identifiers, used by Alembic.
|
||||
revision = '8d0d81bc9c34'
|
||||
|
|
@ -24,6 +28,33 @@ DOCKERIZED = True if os.environ.get('DOCKER', '').lower().startswith('t') else F
|
|||
Base = declarative_base()
|
||||
|
||||
|
||||
# The `Channel` model at the time of this migration.
|
||||
class MChannel(ModelHelper, Base):
|
||||
__tablename__ = 'channel'
|
||||
id = Column(Integer, primary_key=True)
|
||||
name = Column(String)
|
||||
url = Column(String, unique=True)
|
||||
directory: pathlib.Path = Column(MediaPathType)
|
||||
generate_posters = Column(Boolean, default=False)
|
||||
calculate_duration = Column(Boolean, default=True)
|
||||
source_id = Column(String)
|
||||
refreshed = Column(Boolean, default=False)
|
||||
|
||||
info_json = deferred(Column(JSON))
|
||||
info_date = Column(Date)
|
||||
|
||||
@staticmethod
|
||||
def get_by_url(url: str, session: Session = None):
|
||||
if not url:
|
||||
raise RuntimeError('Must provide URL to get Channel')
|
||||
channel = session.query(MChannel).filter_by(url=url).one_or_none()
|
||||
return channel
|
||||
|
||||
def get_rss_url(self) -> str | None:
|
||||
if self.url and self.source_id and 'youtube.com' in self.url:
|
||||
return f'https://www.youtube.com/feeds/videos.xml?channel_id={self.source_id}'
|
||||
|
||||
|
||||
def upgrade():
|
||||
bind = op.get_bind()
|
||||
session = Session(bind=bind)
|
||||
|
|
@ -31,7 +62,7 @@ def upgrade():
|
|||
session.execute('ALTER TABLE download ADD CONSTRAINT download_url_unique UNIQUE (url)')
|
||||
session.execute('ALTER TABLE download ADD COLUMN channel_id INTEGER REFERENCES channel(id)')
|
||||
|
||||
link_channel_and_downloads(session)
|
||||
link_channel_and_downloads(session, MChannel)
|
||||
|
||||
session.execute('ALTER TABLE channel DROP COLUMN IF EXISTS match_regex')
|
||||
session.execute('ALTER TABLE channel DROP COLUMN IF EXISTS download_frequency')
|
||||
|
|
|
|||
|
|
@ -307,10 +307,10 @@ function DashboardStatus() {
|
|||
let load = {};
|
||||
let cores = 0;
|
||||
let pending_downloads = '?';
|
||||
if (status && status['cpu_info']) {
|
||||
percent = status['cpu_info']['percent'];
|
||||
load = status['load'];
|
||||
cores = status['cpu_info']['cores'];
|
||||
if (status && status['cpu_stats']) {
|
||||
percent = status['cpu_stats']['percent'];
|
||||
load = status['load_stats'];
|
||||
cores = status['cpu_stats']['cores'];
|
||||
}
|
||||
|
||||
const {downloads} = status;
|
||||
|
|
@ -319,8 +319,9 @@ function DashboardStatus() {
|
|||
}
|
||||
|
||||
let bandwidths = <ProgressPlaceholder/>;
|
||||
if (status && status['bandwidth']) {
|
||||
bandwidths = status['bandwidth'].map(i => <BandwidthProgressCombined key={i['name']} bandwidth={i}/>);
|
||||
if (status && status['nic_bandwidth_stats']) {
|
||||
bandwidths = Object.entries(status['nic_bandwidth_stats'])
|
||||
.map(([name, bandwidth]) => <BandwidthProgressCombined key={name} bandwidth={bandwidth}/>);
|
||||
}
|
||||
|
||||
return <Segment>
|
||||
|
|
|
|||
|
|
@ -271,7 +271,10 @@ function ChannelPage({create, header}) {
|
|||
} catch (e) {
|
||||
console.error('Failed to tag channel', e);
|
||||
} finally {
|
||||
await fetchChannel();
|
||||
setTimeout(async () => {
|
||||
// Delay fetch because config needs to be written.
|
||||
await fetchChannel();
|
||||
}, 500);
|
||||
}
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -1644,7 +1644,7 @@ export function HandPointMessage({children, size = null}) {
|
|||
</Message>
|
||||
}
|
||||
|
||||
export function WarningMessage({children, size = null, icon='exclamation'}) {
|
||||
export function WarningMessage({children, size = null, icon = 'exclamation'}) {
|
||||
// Use color='yellow' because "warning" does not work.
|
||||
return <Message color='yellow' icon size={size}>
|
||||
<SIcon name={icon}/>
|
||||
|
|
@ -1654,7 +1654,7 @@ export function WarningMessage({children, size = null, icon='exclamation'}) {
|
|||
</Message>
|
||||
}
|
||||
|
||||
export function ErrorMessage({children, size = null, icon='exclamation'}) {
|
||||
export function ErrorMessage({children, size = null, icon = 'exclamation'}) {
|
||||
return <Message error icon size={size}>
|
||||
<SIcon name={icon}/>
|
||||
<Message.Content>{children}</Message.Content>
|
||||
|
|
|
|||
|
|
@ -1,12 +1,12 @@
|
|||
import React from "react";
|
||||
import {NavLink} from "react-router-dom";
|
||||
import {Dropdown, Menu} from "semantic-ui-react";
|
||||
import {Media, SettingsContext, ThemeContext} from "../contexts/contexts";
|
||||
import Icon from "semantic-ui-react/dist/commonjs/elements/Icon";
|
||||
import {Link, NavLink} from "react-router-dom";
|
||||
import {Dropdown, Icon as SIcon, Menu} from "semantic-ui-react";
|
||||
import {Media, SettingsContext, StatusContext, ThemeContext} from "../contexts/contexts";
|
||||
import {CPUTemperatureIcon, DarkModeToggle, HotspotStatusIcon, NAME, SystemLoadIcon} from "./Common";
|
||||
import {ShareButton} from "./Share";
|
||||
import {useWROLMode} from "../hooks/customHooks";
|
||||
import {SearchIconButton} from "./Search";
|
||||
import {Icon} from "./Theme";
|
||||
|
||||
const links = [
|
||||
{text: 'Videos', to: '/videos', key: 'videos'},
|
||||
|
|
@ -61,10 +61,11 @@ function NavIconWrapper(props) {
|
|||
|
||||
export function NavBar() {
|
||||
const wrolModeEnabled = useWROLMode();
|
||||
const {status} = React.useContext(StatusContext);
|
||||
const {settings} = React.useContext(SettingsContext);
|
||||
const wrolpiIcon = <img src='/icon.svg' height='32px' width='32px' alt='WROLPi Home Icon'/>;
|
||||
const name = <i>{NAME || wrolpiIcon}</i>;
|
||||
const topNavText = wrolModeEnabled ? <>{name} <Icon name='lock'/></> : name;
|
||||
const topNavText = wrolModeEnabled ? <>{name} <SIcon name='lock'/></> : name;
|
||||
const {i} = React.useContext(ThemeContext);
|
||||
const navColor = settings && settings.nav_color ? settings.nav_color : 'violet';
|
||||
|
||||
|
|
@ -73,9 +74,14 @@ export function NavBar() {
|
|||
</NavLink>;
|
||||
|
||||
// Display the temperature icon first because it can cause the system to throttle.
|
||||
const warningIcon = <CPUTemperatureIcon fallback={<SystemLoadIcon/>}/>
|
||||
const warningIcon = <CPUTemperatureIcon fallback={<SystemLoadIcon/>}/>;
|
||||
|
||||
const refreshingIcon = status.flags && status.flags.refreshing ?
|
||||
<Link to='/files'><Icon loading name='circle notch' size='large'/></Link>
|
||||
: null;
|
||||
|
||||
const icons = <React.Fragment>
|
||||
<NavIconWrapper>{refreshingIcon}</NavIconWrapper>
|
||||
<NavIconWrapper>{warningIcon}</NavIconWrapper>
|
||||
<NavIconWrapper><ShareButton/></NavIconWrapper>
|
||||
<NavIconWrapper><HotspotStatusIcon/></NavIconWrapper>
|
||||
|
|
|
|||
|
|
@ -1,10 +1,20 @@
|
|||
import {Accordion, Header, Progress, Segment, Statistic, StatisticGroup} from "../Theme";
|
||||
import {Accordion, Header, Progress, Segment, Statistic, StatisticGroup, Table} from "../Theme";
|
||||
import React, {useContext} from "react";
|
||||
import {humanBandwidth, humanFileSize, LoadStatistic, useTitle} from "../Common";
|
||||
import {ProgressPlaceholder} from "../Placeholder";
|
||||
import Grid from "semantic-ui-react/dist/commonjs/collections/Grid";
|
||||
import {Media, SettingsContext, StatusContext, ThemeContext} from "../../contexts/contexts";
|
||||
import {AccordionContent, AccordionTitle, SegmentGroup} from "semantic-ui-react";
|
||||
import {
|
||||
AccordionContent,
|
||||
AccordionTitle,
|
||||
SegmentGroup,
|
||||
TableBody,
|
||||
TableCell,
|
||||
TableHeader,
|
||||
TableHeaderCell,
|
||||
TableRow
|
||||
} from "semantic-ui-react";
|
||||
import _ from "lodash";
|
||||
import Icon from "semantic-ui-react/dist/commonjs/elements/Icon";
|
||||
|
||||
function DriveInfo({used, size, percent, mount}) {
|
||||
|
|
@ -38,17 +48,17 @@ function DiskBandwidthProgress({bytes_ps, total, label, ...props}) {
|
|||
return <Progress percent={percent} label={label} color={color} key={label} {...props}/>;
|
||||
}
|
||||
|
||||
function DiskBandwidth({name, bytes_read_ps, bytes_write_ps, maximum_read_ps, maximum_write_ps}) {
|
||||
function DiskBandwidth({name, bytes_read_ps, bytes_write_ps, max_read_ps, max_write_ps}) {
|
||||
const read = <DiskBandwidthProgress
|
||||
bytes_ps={bytes_read_ps}
|
||||
total={maximum_read_ps}
|
||||
total={max_read_ps}
|
||||
label={`${name} read`}
|
||||
size='tiny'
|
||||
disabled={bytes_read_ps === 0}
|
||||
/>;
|
||||
const write = <DiskBandwidthProgress
|
||||
bytes_ps={bytes_write_ps}
|
||||
total={maximum_write_ps}
|
||||
total={max_write_ps}
|
||||
label={`${name} write`}
|
||||
size='tiny'
|
||||
disabled={bytes_write_ps === 0}
|
||||
|
|
@ -79,7 +89,7 @@ export function BandwidthProgress({label = '', bytes, maxBytes, ...props}) {
|
|||
maxBytes = maxBytes || 125_000_000;
|
||||
|
||||
label = `${label} (${humanBandwidth(bytes)})`;
|
||||
const percent = (bytes / maxBytes);
|
||||
const percent = (bytes / maxBytes) * 100;
|
||||
if (percent > 70) {
|
||||
props['color'] = 'yellow';
|
||||
} else if (percent > 90) {
|
||||
|
|
@ -91,10 +101,10 @@ export function BandwidthProgress({label = '', bytes, maxBytes, ...props}) {
|
|||
|
||||
export function BandwidthProgressGroup({bandwidth, ...props}) {
|
||||
// NIC speed to bytes.
|
||||
const maxBytes = bandwidth['speed'] * 125_000;
|
||||
const maxBytes = bandwidth['speed'] * 1000 * 1000 / 8;
|
||||
|
||||
const recv = <BandwidthProgress
|
||||
bytes={bandwidth['bytes_recv']}
|
||||
bytes={bandwidth['bytes_recv_ps']}
|
||||
label={`${bandwidth['name']} In`}
|
||||
maxBytes={maxBytes}
|
||||
size='small'
|
||||
|
|
@ -102,7 +112,7 @@ export function BandwidthProgressGroup({bandwidth, ...props}) {
|
|||
/>;
|
||||
|
||||
const sent = <BandwidthProgress
|
||||
bytes={bandwidth['bytes_sent']}
|
||||
bytes={bandwidth['bytes_sent_ps']}
|
||||
label={`${bandwidth['name']} Out`}
|
||||
maxBytes={maxBytes}
|
||||
size='small'
|
||||
|
|
@ -122,7 +132,7 @@ export function BandwidthProgressGroup({bandwidth, ...props}) {
|
|||
}
|
||||
|
||||
export function BandwidthProgressCombined({bandwidth, ...props}) {
|
||||
const maxBytes = bandwidth['speed'] ? bandwidth['speed'] * 125_000 : 125_000_000;
|
||||
const maxBytes = bandwidth['speed'] ? bandwidth['speed'] * 1000 * 1000 / 8 : 125_000_000;
|
||||
const combined = bandwidth['bytes_recv'] + bandwidth['bytes_sent']
|
||||
return <BandwidthProgress label={bandwidth['name']} bytes={combined} maxBytes={maxBytes} {...props}/>
|
||||
}
|
||||
|
|
@ -160,6 +170,15 @@ export function MemoryUsageProgress({percent, label}) {
|
|||
return <Progress percent={percent} progress color={color} label={label} size={size}/>
|
||||
}
|
||||
|
||||
function ProcessInfoRow({pid, command, percent_cpu, percent_mem}) {
|
||||
const color = percent_cpu >= 80 ? 'orange' : null;
|
||||
return <TableRow color={color}>
|
||||
<TableCell className='column-ellipsis'>{command}</TableCell>
|
||||
<TableCell textAlign='right'>{percent_cpu}</TableCell>
|
||||
<TableCell textAlign='right'>{percent_mem}</TableCell>
|
||||
<TableCell textAlign='right'>{pid}</TableCell>
|
||||
</TableRow>
|
||||
}
|
||||
|
||||
export function StatusPage() {
|
||||
useTitle('Status');
|
||||
|
|
@ -175,30 +194,32 @@ export function StatusPage() {
|
|||
let temperature;
|
||||
let high_temperature;
|
||||
let critical_temperature;
|
||||
let processesStats = null;
|
||||
let minute_1;
|
||||
let minute_5;
|
||||
let minute_15;
|
||||
let bandwidth;
|
||||
let drives = [];
|
||||
let disk_bandwidth = [];
|
||||
let nicBandwidthStats;
|
||||
let drivesStats = [];
|
||||
let diskBandwidthStats = [];
|
||||
let memoryPercent;
|
||||
let memorySize;
|
||||
|
||||
if (status && status['cpu_info']) {
|
||||
const {cpu_info, load, memory_stats} = status;
|
||||
percent = cpu_info['percent'];
|
||||
cores = cpu_info['cores'];
|
||||
temperature = cpu_info['temperature'];
|
||||
high_temperature = cpu_info['high_temperature'];
|
||||
critical_temperature = cpu_info['critical_temperature'];
|
||||
if (status && status['cpu_stats']) {
|
||||
const {cpu_stats, load_stats, memory_stats, processes_stats} = status;
|
||||
percent = cpu_stats['percent'];
|
||||
cores = cpu_stats['cores'];
|
||||
temperature = cpu_stats['temperature'];
|
||||
high_temperature = cpu_stats['high_temperature'];
|
||||
critical_temperature = cpu_stats['critical_temperature'];
|
||||
processesStats = processes_stats;
|
||||
|
||||
minute_1 = load['minute_1'];
|
||||
minute_5 = load['minute_5'];
|
||||
minute_15 = load['minute_15'];
|
||||
minute_1 = load_stats['minute_1'];
|
||||
minute_5 = load_stats['minute_5'];
|
||||
minute_15 = load_stats['minute_15'];
|
||||
|
||||
drives = status['drives'];
|
||||
bandwidth = status['bandwidth'];
|
||||
disk_bandwidth = status['disk_bandwidth'];
|
||||
drivesStats = status['drives_stats'];
|
||||
nicBandwidthStats = status['nic_bandwidth_stats'];
|
||||
diskBandwidthStats = status['disk_bandwidth_stats'];
|
||||
|
||||
memoryPercent = Math.round(memory_stats['used'] / memory_stats['total'] * 100);
|
||||
memorySize = humanFileSize(memory_stats['total'], 0);
|
||||
|
|
@ -218,6 +239,10 @@ export function StatusPage() {
|
|||
setActiveIndex(activeIndex === index ? -1 : index);
|
||||
}
|
||||
|
||||
const noProcessesRow = <TableRow>
|
||||
<TableCell colSpan={4}>No top processes</TableCell>
|
||||
</TableRow>
|
||||
|
||||
return <SegmentGroup>
|
||||
<Media at='mobile'>
|
||||
<Segment>
|
||||
|
|
@ -255,20 +280,45 @@ export function StatusPage() {
|
|||
|
||||
<Segment>
|
||||
<SizedHeader>Drive Bandwidth</SizedHeader>
|
||||
{disk_bandwidth && disk_bandwidth.length > 0 ? disk_bandwidth.map((disk) => <DiskBandwidth
|
||||
key={disk['name']} {...disk}/>)
|
||||
{!_.isEmpty(diskBandwidthStats) ?
|
||||
Object.entries(diskBandwidthStats).map(([name, disk]) => <DiskBandwidth key={name} {...disk}/>)
|
||||
: <ProgressPlaceholder/>}
|
||||
</Segment>
|
||||
|
||||
<Segment>
|
||||
<SizedHeader>Network Bandwidth</SizedHeader>
|
||||
{bandwidth ? bandwidth.map(i => <BandwidthProgressGroup key={i['name']} bandwidth={i}/>)
|
||||
{!_.isEmpty(nicBandwidthStats) ?
|
||||
Object.entries(nicBandwidthStats).map(([name, stats]) => <BandwidthProgressGroup key={name}
|
||||
bandwidth={stats}/>)
|
||||
: <ProgressPlaceholder/>}
|
||||
</Segment>
|
||||
|
||||
<Segment>
|
||||
<SizedHeader>Top Processes</SizedHeader>
|
||||
<Table unstackable striped className='table-ellipsis'>
|
||||
<TableHeader>
|
||||
<TableRow>
|
||||
<TableHeaderCell width={10}>Command</TableHeaderCell>
|
||||
<TableHeaderCell width={2} textAlign='right'>CPU %</TableHeaderCell>
|
||||
<TableHeaderCell width={2} textAlign='right'>Mem %</TableHeaderCell>
|
||||
<TableHeaderCell width={2} textAlign='right'>PID</TableHeaderCell>
|
||||
</TableRow>
|
||||
</TableHeader>
|
||||
<TableBody>
|
||||
{processesStats && processesStats.length === 0 ?
|
||||
noProcessesRow :
|
||||
processesStats && processesStats.length > 0 ?
|
||||
processesStats.map(i => <ProcessInfoRow key={i.pid} {...i}/>)
|
||||
: <TableRow><TableCell><ProgressPlaceholder/></TableCell></TableRow>
|
||||
}
|
||||
</TableBody>
|
||||
</Table>
|
||||
</Segment>
|
||||
|
||||
<Segment>
|
||||
<SizedHeader>Drive Usage</SizedHeader>
|
||||
{drives && drives.length > 0 ? drives.map((drive) => <DriveInfo key={drive['mount']} {...drive}/>)
|
||||
{drivesStats && drivesStats.length > 0 ? drivesStats.map((drive) => <DriveInfo
|
||||
key={drive['mount']} {...drive}/>)
|
||||
: <ProgressPlaceholder/>}
|
||||
</Segment>
|
||||
|
||||
|
|
|
|||
|
|
@ -6,6 +6,8 @@ After=network.target auditd.service
|
|||
[Service]
|
||||
# Delay startup so WROLPi API has time to start.
|
||||
ExecStartPre=/bin/sleep 30
|
||||
# Map is intense, but not a high priority.
|
||||
Nice=19
|
||||
ExecStart=/usr/bin/renderd -f
|
||||
User=_renderd
|
||||
|
||||
|
|
|
|||
3
main.py
3
main.py
|
|
@ -2,6 +2,7 @@
|
|||
import argparse
|
||||
import asyncio
|
||||
import logging
|
||||
import os
|
||||
import sys
|
||||
|
||||
from sanic import Sanic
|
||||
|
|
@ -224,7 +225,7 @@ async def start_single_tasks(app: Sanic):
|
|||
app.add_task(perpetual_have_internet_worker()) # noqa
|
||||
|
||||
await app.dispatch('wrolpi.periodic.start_video_missing_comments_download')
|
||||
await app.dispatch('wrolpi.periodic.bandwidth')
|
||||
await app.dispatch('wrolpi.periodic.status')
|
||||
|
||||
try:
|
||||
flag_outdated_zim_files()
|
||||
|
|
|
|||
|
|
@ -261,27 +261,21 @@ async def tag_channel(tag_name: str | None, directory: pathlib.Path | None, chan
|
|||
"""Add a Tag to a Channel, or remove a Tag from a Channel if no `tag_name` is provided.
|
||||
|
||||
Move the Channel to the new directory, if provided."""
|
||||
from wrolpi.tags import Tag
|
||||
|
||||
if directory and flags.refreshing.is_set():
|
||||
raise RefreshConflict('Refusing to move channel while file refresh is in progress')
|
||||
|
||||
channel = Channel.find_by_id(channel_id, session)
|
||||
|
||||
if tag_name:
|
||||
tag = Tag.find_by_name(tag_name, session)
|
||||
channel.tag_id = tag.id
|
||||
channel.tag = tag
|
||||
else:
|
||||
channel.tag = channel.tag_id = None
|
||||
|
||||
channel.flush()
|
||||
session.commit()
|
||||
|
||||
# Do not move Channel files into a directory with files.
|
||||
if directory and directory != channel.directory and directory.is_dir() and next(directory.iterdir(), None):
|
||||
raise ChannelDirectoryConflict('Channel directory already exists and is not empty')
|
||||
|
||||
# May also clear the tag if `tag_name` is None.
|
||||
channel.set_tag(tag_name)
|
||||
channel.flush()
|
||||
session.commit()
|
||||
|
||||
# Only move Channel when requested.
|
||||
if directory:
|
||||
# Move to newly defined directory only if necessary.
|
||||
|
|
|
|||
|
|
@ -17,6 +17,7 @@ from wrolpi.common import get_relative_to_media_directory, walk
|
|||
from wrolpi.dates import now
|
||||
from wrolpi.db import get_db_session
|
||||
from wrolpi.downloader import download_manager, Download, DownloadResult
|
||||
from wrolpi.files.models import Directory
|
||||
from wrolpi.test.common import assert_dict_contains
|
||||
|
||||
|
||||
|
|
@ -489,6 +490,8 @@ async def test_tag_channel(test_async_client, test_session, test_directory, chan
|
|||
assert str(get_relative_to_media_directory(v2.video_path)) == 'videos/Channel Name/video2.mp4'
|
||||
video_files = [i for i in walk(videos_directory) if i.is_file()]
|
||||
assert len(video_files) == 3
|
||||
# Channel's directory is indexed.
|
||||
assert [i.path for i in test_session.query(Directory)] == [channel.directory, ]
|
||||
|
||||
body = dict(tag_name=tag.name, directory='videos/Tag Name/Channel Name')
|
||||
request, response = await test_async_client.post(f'/api/videos/channels/{channel.id}/tag', json=body)
|
||||
|
|
@ -508,6 +511,8 @@ async def test_tag_channel(test_async_client, test_session, test_directory, chan
|
|||
f'{d1} was not moved'
|
||||
assert d2.settings['destination'] == str(test_directory / 'videos/Tag Name/Channel Name'), \
|
||||
f'{d2} was not moved'
|
||||
# Directory record was replaced.
|
||||
assert [i.path for i in test_session.query(Directory)] == [channel.directory, ]
|
||||
|
||||
# Videos were moved
|
||||
v1, v2 = test_session.query(Video).order_by(Video.id).all()
|
||||
|
|
@ -535,6 +540,7 @@ async def test_tag_channel(test_async_client, test_session, test_directory, chan
|
|||
d1, d2 = test_session.query(Download).all()
|
||||
assert d1.settings['destination'] == str(test_directory / 'videos/Channel Name'), f'{d1} was not moved'
|
||||
assert d2.settings['destination'] == str(test_directory / 'videos/Channel Name'), f'{d2} was not moved'
|
||||
assert [i.path for i in test_session.query(Directory)] == [channel.directory, ]
|
||||
|
||||
# Channel can be Tagged, without moving directories.
|
||||
body = dict(tag_name=tag.name)
|
||||
|
|
@ -549,6 +555,7 @@ async def test_tag_channel(test_async_client, test_session, test_directory, chan
|
|||
d1, d2 = test_session.query(Download).all()
|
||||
assert d1.settings['destination'] == str(test_directory / 'videos/Channel Name'), f'{d1} was not moved'
|
||||
assert d2.settings['destination'] == str(test_directory / 'videos/Channel Name'), f'{d2} was not moved'
|
||||
assert [i.path for i in test_session.query(Directory)] == [channel.directory, ]
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
|
|
@ -574,6 +581,7 @@ async def test_move_channel(test_async_client, test_session, test_directory, cha
|
|||
assert str(channel.directory) == str(test_directory / 'videos/New Directory')
|
||||
assert str(vid1.video_path).startswith(str(test_directory / 'videos/New Directory/'))
|
||||
assert str(vid2.video_path).startswith(str(test_directory / 'videos/New Directory/'))
|
||||
assert [i.path for i in test_session.query(Directory)] == [test_directory / 'videos/New Directory', ]
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
|
|
@ -605,7 +613,7 @@ async def test_move_channel_after_terminal_move(test_async_client, test_session,
|
|||
|
||||
@pytest.mark.asyncio
|
||||
async def test_search_tagged_channels(test_async_client, test_session, channel_factory, tag_factory,
|
||||
video_factory):
|
||||
video_factory):
|
||||
"""Tagged Channels can be searched."""
|
||||
tag = await tag_factory()
|
||||
test_session.commit()
|
||||
|
|
|
|||
|
|
@ -9,13 +9,14 @@ from uuid import uuid4
|
|||
import mock
|
||||
import pytest
|
||||
from PIL import Image
|
||||
from requests import session
|
||||
|
||||
from modules.videos.downloader import VideoDownloader, ChannelDownloader
|
||||
from modules.videos.lib import set_test_channels_config, set_test_downloader_config, format_videos_destination
|
||||
from modules.videos.models import Channel, Video
|
||||
from wrolpi.api_utils import api_app
|
||||
from wrolpi.downloader import DownloadFrequency, DownloadManager
|
||||
from wrolpi.files.models import FileGroup
|
||||
from wrolpi.files.models import FileGroup, Directory
|
||||
from wrolpi.vars import PROJECT_DIR
|
||||
|
||||
|
||||
|
|
@ -53,6 +54,7 @@ def channel_factory(test_session, test_directory):
|
|||
channel.directory.mkdir(exist_ok=True, parents=True)
|
||||
test_session.add(channel)
|
||||
test_session.flush([channel])
|
||||
test_session.add(Directory(path=channel.directory, name=channel.directory.name))
|
||||
assert channel.id and channel.url
|
||||
if download_frequency:
|
||||
download = channel.get_or_create_download(channel.url, download_frequency)
|
||||
|
|
|
|||
|
|
@ -4,7 +4,7 @@ import html
|
|||
import pathlib
|
||||
import re
|
||||
import traceback
|
||||
from typing import Generator
|
||||
from typing import Generator, Type
|
||||
from typing import Tuple, Optional
|
||||
|
||||
import pytz
|
||||
|
|
@ -16,7 +16,7 @@ from modules.videos.models import Video
|
|||
from wrolpi import before_startup, dates, flags
|
||||
from wrolpi.captions import extract_captions
|
||||
from wrolpi.common import ConfigFile, limit_concurrent, get_wrolpi_config, extract_domain, \
|
||||
escape_file_name, get_media_directory, background_task
|
||||
escape_file_name, get_media_directory, background_task, Base
|
||||
from wrolpi.dates import Seconds, from_timestamp
|
||||
from wrolpi.db import get_db_curs, get_db_session, optional_session
|
||||
from wrolpi.downloader import Download
|
||||
|
|
@ -472,7 +472,8 @@ def import_channels_config():
|
|||
channel.delete_with_videos()
|
||||
|
||||
# Create any missing Downloads. Associated Downloads with any necessary Channels.
|
||||
link_channel_and_downloads()
|
||||
with get_db_session() as session:
|
||||
link_channel_and_downloads(session)
|
||||
|
||||
except Exception as e:
|
||||
channel_import_logger.warning('Failed to load channels config!', exc_info=e)
|
||||
|
|
@ -481,8 +482,7 @@ def import_channels_config():
|
|||
raise
|
||||
|
||||
|
||||
@optional_session
|
||||
def link_channel_and_downloads(session: Session):
|
||||
def link_channel_and_downloads(session: Session, channel_: Type[Base] = Channel):
|
||||
"""Create any missing Downloads for any Channel.url/Channel.directory that has a Download. Associate any Download
|
||||
related to a Channel."""
|
||||
# Only Downloads with a frequency can be a Channel Download.
|
||||
|
|
@ -491,7 +491,7 @@ def link_channel_and_downloads(session: Session):
|
|||
downloads_by_url = {i.url: i for i in downloads}
|
||||
# Many Downloads may share the same destination.
|
||||
downloads_with_destination = [i for i in downloads if (i.settings or dict()).get('destination')]
|
||||
channels = session.query(Channel).all()
|
||||
channels = session.query(channel_).all()
|
||||
|
||||
need_commit = False
|
||||
for channel in channels:
|
||||
|
|
@ -514,7 +514,7 @@ def link_channel_and_downloads(session: Session):
|
|||
|
||||
# Associate any Download which shares a Channel's URL.
|
||||
for download in downloads:
|
||||
channel = Channel.get_by_url(download.url)
|
||||
channel = channel_.get_by_url(download.url, session)
|
||||
if channel and not download.channel_id:
|
||||
download.channel_id = channel.id
|
||||
need_commit = True
|
||||
|
|
|
|||
|
|
@ -1,5 +1,4 @@
|
|||
import json
|
||||
import json
|
||||
import pathlib
|
||||
from typing import Optional, Dict, List
|
||||
|
||||
|
|
@ -682,6 +681,20 @@ class Channel(ModelHelper, Base):
|
|||
curs.execute(stmt, dict(id=self.id))
|
||||
return dict(curs.fetchone())
|
||||
|
||||
def set_tag(self, tag_id_or_name: int | str | None) -> Tag | None:
|
||||
"""Change the Tag relationship of this Channel. Will clear the Tag if provided with None."""
|
||||
session = Session.object_session(self)
|
||||
if tag_id_or_name is None:
|
||||
# Clear tag.
|
||||
self.tag = None
|
||||
elif isinstance(tag_id_or_name, int):
|
||||
self.tag = Tag.find_by_id(tag_id_or_name, session)
|
||||
elif isinstance(tag_id_or_name, str):
|
||||
self.tag = Tag.find_by_name(tag_id_or_name, session)
|
||||
# Copy the id in case some code needs the id before flush.
|
||||
self.tag_id = self.tag.id if self.tag else None
|
||||
return self.tag
|
||||
|
||||
async def refresh_files(self, send_events: bool = True):
|
||||
"""Refresh all files within this Channel's directory. Mark this channel as refreshed."""
|
||||
logger.debug(f'{self}.refresh_files')
|
||||
|
|
|
|||
|
|
@ -8,6 +8,7 @@ beautifulsoup4==4.12.2
|
|||
cachetools==5.3.0
|
||||
ebooklib==0.18
|
||||
feedparser==6.0.10
|
||||
jc==1.25.3
|
||||
libzim==3.3.0.post0
|
||||
mock==5.1.0
|
||||
psutil==5.9.5
|
||||
|
|
|
|||
|
|
@ -1,5 +1,6 @@
|
|||
import wrolpi.files.api # noqa Import from files so the blueprint is attached.
|
||||
import wrolpi.scrape_downloader # noqa
|
||||
import wrolpi.status # noqa
|
||||
|
||||
BEFORE_STARTUP_FUNCTIONS = []
|
||||
|
||||
|
|
|
|||
|
|
@ -85,3 +85,4 @@ YT_DLP_BIN = which(
|
|||
)
|
||||
FFPROBE_BIN = which('ffprobe', '/usr/bin/ffprobe')
|
||||
FFMPEG_BIN = which('ffmpeg', '/usr/bin/ffmpeg')
|
||||
JC_BIN = which('jc', '/usr/bin/jc')
|
||||
|
|
@ -1930,15 +1930,11 @@ def is_hardlinked(path: pathlib.Path) -> bool:
|
|||
return path.stat().st_nlink > 1
|
||||
|
||||
|
||||
def _default_predicate(i):
|
||||
return i
|
||||
|
||||
|
||||
def unique_by_predicate(
|
||||
iterable: list | tuple | set,
|
||||
iterable: list | tuple | set | Generator,
|
||||
predicate: callable = None,
|
||||
) -> list | tuple | set:
|
||||
"""Finds only unique items in the provided iterable based on the predicate function. Order is preserved.
|
||||
"""Finds the first unique items in the provided iterable based on the predicate function. Order is preserved.
|
||||
|
||||
`predicate` defaults to the items themselves.
|
||||
|
||||
|
|
@ -1949,8 +1945,11 @@ def unique_by_predicate(
|
|||
>>> unique_by_predicate([1, 1, 2, 3, 3, 3, 3, 4], None)
|
||||
# [ 1, 2, 3, 4 ]
|
||||
"""
|
||||
predicate = predicate or _default_predicate # Return an iterable based off the object itself by default.
|
||||
predicate = predicate or (lambda i: i) # Return an iterable based off the object itself by default.
|
||||
seen = set()
|
||||
unique_items = [i for i in iterable if not ((key := predicate(i)) in seen or seen.add(key))]
|
||||
# Return the same type as the input iterable
|
||||
return iterable.__class__(unique_items) # For other iterable types
|
||||
if isinstance(iterable, Generator):
|
||||
# Return a list when provided iterable is a Generator.
|
||||
return unique_items
|
||||
# Return the same type as the provided iterable
|
||||
return iterable.__class__(unique_items)
|
||||
|
|
|
|||
|
|
@ -28,9 +28,7 @@ def attach_shared_contexts(app: Sanic):
|
|||
# Shared dicts.
|
||||
app.shared_ctx.refresh = manager.dict()
|
||||
app.shared_ctx.uploaded_files = manager.dict()
|
||||
app.shared_ctx.bandwidth = manager.dict()
|
||||
app.shared_ctx.disks_bandwidth = manager.dict()
|
||||
app.shared_ctx.max_disks_bandwidth = manager.dict()
|
||||
app.shared_ctx.status = manager.dict()
|
||||
app.shared_ctx.map_importing = manager.dict()
|
||||
# Shared lists.
|
||||
app.shared_ctx.events_history = manager.list()
|
||||
|
|
@ -71,9 +69,14 @@ def reset_shared_contexts(app: Sanic):
|
|||
# Shared dicts.
|
||||
app.shared_ctx.refresh.clear()
|
||||
app.shared_ctx.uploaded_files.clear()
|
||||
app.shared_ctx.bandwidth.clear()
|
||||
app.shared_ctx.disks_bandwidth.clear()
|
||||
app.shared_ctx.max_disks_bandwidth.clear()
|
||||
app.shared_ctx.status.clear()
|
||||
app.shared_ctx.status.update(dict(
|
||||
cpu_stats=dict(),
|
||||
load_stats=dict(),
|
||||
drives_stats=list(),
|
||||
processes_stats=list(),
|
||||
memory_stats=dict(),
|
||||
))
|
||||
app.shared_ctx.map_importing.clear()
|
||||
# Shared ints
|
||||
app.shared_ctx.log_level.value = default_log_level
|
||||
|
|
|
|||
|
|
@ -1199,6 +1199,8 @@ async def _move(destination: pathlib.Path, *sources: pathlib.Path, session: Sess
|
|||
|
||||
# The files that will be moved. [ (old_file, new_file), ... ]
|
||||
plan: Dict[pathlib.Path, pathlib.Path] = dict()
|
||||
# Directories that will need to be cleaned up.
|
||||
old_directories = unique_by_predicate(i if i.is_dir() else i.parent for i in sources)
|
||||
|
||||
def add_file_group_to_plan(file_group_: FileGroup):
|
||||
primary_path_ = file_group_.primary_path
|
||||
|
|
@ -1343,6 +1345,14 @@ async def _move(destination: pathlib.Path, *sources: pathlib.Path, session: Sess
|
|||
delete_directory(destination)
|
||||
raise
|
||||
|
||||
# Clean up any old Directory records.
|
||||
for old_directory in old_directories:
|
||||
# Delete directories that do no exist, or are empty.
|
||||
if not old_directory.is_dir() or next(old_directory.iterdir(), None) is None:
|
||||
directories = session.query(Directory).filter(Directory.path.like(str(old_directory)))
|
||||
for directory in directories:
|
||||
session.delete(directory)
|
||||
|
||||
return plan
|
||||
|
||||
|
||||
|
|
|
|||
|
|
@ -443,3 +443,6 @@ class Directory(ModelHelper, Base):
|
|||
name=self.name,
|
||||
)
|
||||
return d
|
||||
|
||||
def __repr__(self):
|
||||
return f'<Directory path={repr(str(self.path))}>'
|
||||
|
|
|
|||
|
|
@ -17,7 +17,7 @@ from modules.map.api import map_bp
|
|||
from modules.otp.api import otp_bp
|
||||
from modules.videos.api import videos_bp
|
||||
from modules.zim.api import zim_bp
|
||||
from wrolpi import admin, status, flags, schema, dates
|
||||
from wrolpi import admin, flags, schema, dates
|
||||
from wrolpi import tags
|
||||
from wrolpi.admin import HotspotStatus
|
||||
from wrolpi.api_utils import json_response, json_error_handler, api_app
|
||||
|
|
@ -417,7 +417,6 @@ async def throttle_off(_: Request):
|
|||
@api_bp.get('/status')
|
||||
@openapi.description('Get the status of CPU/load/etc.')
|
||||
async def get_status(_: Request):
|
||||
s = await status.get_status()
|
||||
downloads = dict()
|
||||
if flags.db_up.is_set():
|
||||
try:
|
||||
|
|
@ -426,23 +425,19 @@ async def get_status(_: Request):
|
|||
logger.debug('Unable to get download status', exc_info=e)
|
||||
|
||||
ret = dict(
|
||||
bandwidth=s.bandwidth,
|
||||
cpu_info=s.cpu_info,
|
||||
disk_bandwidth=s.disk_bandwidth,
|
||||
dockerized=DOCKERIZED,
|
||||
is_rpi=IS_RPI,
|
||||
is_rpi4=IS_RPI4,
|
||||
is_rpi5=IS_RPI5,
|
||||
downloads=downloads,
|
||||
drives=s.drives,
|
||||
flags=flags.get_flags(),
|
||||
hotspot_status=admin.hotspot_status().name,
|
||||
hotspot_ssid=admin.get_current_ssid(get_wrolpi_config().hotspot_device),
|
||||
load=s.load,
|
||||
memory_stats=s.memory_stats,
|
||||
throttle_status=admin.throttle_status().name,
|
||||
version=__version__,
|
||||
wrol_mode=wrol_mode_enabled(),
|
||||
# Include all stats from status worker.
|
||||
**api_app.shared_ctx.status,
|
||||
)
|
||||
return json_response(ret)
|
||||
|
||||
|
|
|
|||
492
wrolpi/status.py
492
wrolpi/status.py
|
|
@ -1,5 +1,6 @@
|
|||
#!/usr/bin/env python3
|
||||
import asyncio
|
||||
import json
|
||||
import multiprocessing
|
||||
import pathlib
|
||||
import re
|
||||
|
|
@ -10,9 +11,11 @@ from decimal import Decimal
|
|||
from pathlib import Path
|
||||
from typing import List, Optional, Tuple
|
||||
|
||||
import jc
|
||||
|
||||
from wrolpi.api_utils import api_app
|
||||
from wrolpi.cmd import which
|
||||
from wrolpi.common import logger, get_warn_once
|
||||
from wrolpi.common import logger, get_warn_once, unique_by_predicate
|
||||
from wrolpi.dates import now
|
||||
|
||||
try:
|
||||
|
|
@ -26,6 +29,8 @@ logger = logger.getChild(__name__)
|
|||
UPTIME_BIN = which('uptime', '/usr/bin/uptime')
|
||||
|
||||
warn_once = get_warn_once('Unable to use psutil', logger)
|
||||
warn_cpu_once = get_warn_once('Cannot read CPU stats', logger)
|
||||
status_worker_warn_once = get_warn_once('Status worker encountered error', logger)
|
||||
|
||||
|
||||
@dataclass
|
||||
|
|
@ -43,17 +48,10 @@ class SystemLoad:
|
|||
|
||||
|
||||
LOAD_REGEX = re.compile(r'.+?load average: (.+?), (.+?), (.*)')
|
||||
|
||||
|
||||
def get_load_psutil() -> SystemLoad:
|
||||
load = SystemLoad(*list(map(Decimal, psutil.getloadavg())))
|
||||
return load
|
||||
|
||||
|
||||
LOAD_AVG_FILE = pathlib.Path('/proc/loadavg')
|
||||
|
||||
|
||||
async def get_load() -> SystemLoad:
|
||||
async def get_load_stats() -> SystemLoad:
|
||||
"""Read loadavg file and return the 1, 5, and 15 minute system loads."""
|
||||
# Read load information from proc file.
|
||||
# Example: 0.99 1.06 1.02 1/2305 43879
|
||||
|
|
@ -63,6 +61,22 @@ async def get_load() -> SystemLoad:
|
|||
return load
|
||||
|
||||
|
||||
@dataclass
|
||||
class ProcessInfo:
|
||||
pid: int = None
|
||||
percent_cpu: int = None
|
||||
percent_mem: int = None
|
||||
command: str = None
|
||||
|
||||
def __json__(self) -> dict:
|
||||
return dict(
|
||||
pid=self.pid,
|
||||
percent_cpu=self.percent_cpu,
|
||||
percent_mem=self.percent_mem,
|
||||
command=self.command,
|
||||
)
|
||||
|
||||
|
||||
@dataclass
|
||||
class CPUInfo:
|
||||
cores: int = None
|
||||
|
|
@ -71,8 +85,8 @@ class CPUInfo:
|
|||
min_frequency: int = None
|
||||
percent: int = None
|
||||
temperature: Optional[int] = None
|
||||
high_temperature: Optional[int] = None
|
||||
critical_temperature: Optional[int] = None
|
||||
high_temperature: Optional[float] = None
|
||||
critical_temperature: Optional[float] = None
|
||||
|
||||
def __json__(self) -> dict:
|
||||
return dict(
|
||||
|
|
@ -94,87 +108,83 @@ TEMPERATURE_PATH = Path('/sys/class/thermal/thermal_zone0/temp')
|
|||
TOP_REGEX = re.compile(r'^%Cpu\(s\):\s+(\d+\.\d+)', re.MULTILINE)
|
||||
|
||||
|
||||
def get_cpu_info_psutil() -> CPUInfo:
|
||||
cpu_freq = psutil.cpu_freq()
|
||||
percent = psutil.cpu_percent(interval=0.1)
|
||||
async def get_cpu_stats() -> CPUInfo:
|
||||
"""Get core count, max freq, min freq, current freq, cpu temperature."""
|
||||
percent = int(psutil.cpu_percent())
|
||||
|
||||
# Prefer "coretemp", fallback to the first temperature.
|
||||
# Get temperature from system file.
|
||||
temperature = cur_frequency = max_frequency = min_frequency = None
|
||||
if TEMPERATURE_PATH.is_file():
|
||||
try:
|
||||
temperature = int(TEMPERATURE_PATH.read_text()) // 1000
|
||||
min_frequency = int(MIN_FREQUENCY_PATH.read_text())
|
||||
max_frequency = int(MAX_FREQUENCY_PATH.read_text())
|
||||
cur_frequency = int(CUR_FREQUENCY_PATH.read_text())
|
||||
except Exception as e:
|
||||
warn_cpu_once(e)
|
||||
|
||||
# Get temperature using psutil.
|
||||
temp = psutil.sensors_temperatures()
|
||||
name = 'coretemp' if 'coretemp' in temp else list(temp.keys())[0]
|
||||
# Temperatures may be None. Get average temperatures from CPU because one core may be hot.
|
||||
temperatures = temp.get(name)
|
||||
temperature = statistics.median([i.current or 0 for i in temperatures])
|
||||
temperature = temperature or statistics.median([i.current or 0 for i in temperatures])
|
||||
high_temperature = statistics.median([i.high or 0 for i in temperatures])
|
||||
critical_temperature = statistics.median([i.critical or 0 for i in temperatures])
|
||||
|
||||
# Temperatures my not exist.
|
||||
if not high_temperature:
|
||||
high_temperature = 60
|
||||
if not critical_temperature:
|
||||
critical_temperature = 95
|
||||
# Temperatures may not exist.
|
||||
high_temperature = high_temperature or 60
|
||||
critical_temperature = critical_temperature or 95
|
||||
|
||||
if high_temperature and high_temperature == critical_temperature:
|
||||
# Display yellow warning before red warning.
|
||||
high_temperature = critical_temperature - 25
|
||||
|
||||
info = CPUInfo(
|
||||
cores=psutil.cpu_count(logical=True),
|
||||
cur_frequency=int(cpu_freq.current),
|
||||
min_frequency=int(cpu_freq.min),
|
||||
max_frequency=int(cpu_freq.max),
|
||||
percent=int(percent),
|
||||
temperature=int(temperature),
|
||||
high_temperature=int(high_temperature),
|
||||
critical_temperature=int(critical_temperature),
|
||||
)
|
||||
return info
|
||||
|
||||
|
||||
async def get_cpu_info() -> CPUInfo:
|
||||
"""Get core count, max freq, min freq, current freq, cpu temperature."""
|
||||
try:
|
||||
return get_cpu_info_psutil()
|
||||
except Exception as e:
|
||||
warn_once(e)
|
||||
|
||||
# Fallback to using `top` to fetch CPU information.
|
||||
proc = await asyncio.create_subprocess_shell(
|
||||
'top -bn1',
|
||||
stdout=subprocess.PIPE,
|
||||
stderr=subprocess.PIPE,
|
||||
)
|
||||
stdout, stderr = await proc.communicate()
|
||||
match = TOP_REGEX.search(stdout.decode())
|
||||
if proc.returncode != 0 or not match:
|
||||
logger.warning(f'Unable to get CPU top with exit {proc.returncode}')
|
||||
percent = None
|
||||
else:
|
||||
percent = int(Decimal(match.groups()[0]))
|
||||
|
||||
if not TEMPERATURE_PATH.is_file():
|
||||
warn_once(f'CPU temperature file does not exist!')
|
||||
return CPUInfo(percent=percent)
|
||||
|
||||
try:
|
||||
temperature = int(TEMPERATURE_PATH.read_text()) // 1000
|
||||
min_frequency = int(MIN_FREQUENCY_PATH.read_text())
|
||||
max_frequency = int(MAX_FREQUENCY_PATH.read_text())
|
||||
cur_frequency = int(CUR_FREQUENCY_PATH.read_text())
|
||||
except Exception as e:
|
||||
logger.warning(f'Unable to get CPU info', exc_info=e)
|
||||
return CPUInfo(percent=percent)
|
||||
|
||||
info = CPUInfo(
|
||||
cores=multiprocessing.cpu_count(),
|
||||
cur_frequency=cur_frequency - min_frequency, # Current frequency is between minimum and maximum.
|
||||
critical_temperature=int(critical_temperature) if critical_temperature else None,
|
||||
# Current frequency is between minimum and maximum.
|
||||
cur_frequency=cur_frequency - min_frequency if cur_frequency else None,
|
||||
high_temperature=int(high_temperature) if high_temperature else None,
|
||||
max_frequency=max_frequency,
|
||||
min_frequency=min_frequency,
|
||||
percent=percent,
|
||||
temperature=temperature,
|
||||
temperature=int(temperature) if temperature else None,
|
||||
)
|
||||
return info
|
||||
|
||||
|
||||
PS_CMD = 'ps aux --sort=-%cpu --cols=512'
|
||||
IGNORED_PROCESS_COMMANDS = {PS_CMD, '<defunct>'}
|
||||
|
||||
|
||||
async def get_processes_stats() -> List[ProcessInfo]:
|
||||
proc = await asyncio.create_subprocess_shell(
|
||||
PS_CMD,
|
||||
stdout=subprocess.PIPE,
|
||||
stderr=subprocess.PIPE,
|
||||
)
|
||||
# Do not include `ps` in the top processes.
|
||||
ps_pid = proc.pid
|
||||
stdout, stderr = await proc.communicate()
|
||||
|
||||
ps_info = jc.parse('ps', stdout.decode(), quiet=True)
|
||||
processes = sorted(ps_info, key=lambda i: i['cpu_percent'], reverse=True)
|
||||
processes = [i for i in processes if i['pid'] != ps_pid
|
||||
and i['cpu_percent'] > 1
|
||||
and not any(j in i['command'] for j in IGNORED_PROCESS_COMMANDS)]
|
||||
processes = unique_by_predicate(processes, lambda i: i['command'][:30])
|
||||
processes = processes[:10]
|
||||
processes_info = [ProcessInfo(
|
||||
pid=int(i['pid']),
|
||||
percent_cpu=int(i['cpu_percent']),
|
||||
percent_mem=int(i['mem_percent']),
|
||||
command=i['command'],
|
||||
) for i in processes]
|
||||
|
||||
return processes_info
|
||||
|
||||
|
||||
MEMORY_TOTAL = re.compile(r'^MemTotal:\s+(\d+)\s+kB$', re.MULTILINE)
|
||||
MEMORY_FREE = re.compile(r'^MemFree:\s+(\d+)\s+kB$', re.MULTILINE)
|
||||
MEMORY_CACHED = re.compile(r'^Cached:\s+(\d+)\s+kB$', re.MULTILINE)
|
||||
|
|
@ -279,7 +289,7 @@ def get_drives_info_psutil() -> List[DriveInfo]:
|
|||
return info
|
||||
|
||||
|
||||
async def get_drives_info() -> List[DriveInfo]:
|
||||
async def get_drives_stats() -> List[DriveInfo]:
|
||||
try:
|
||||
return get_drives_info_psutil()
|
||||
except Exception as e:
|
||||
|
|
@ -319,6 +329,7 @@ class NICBandwidthInfo:
|
|||
elapsed: int = None
|
||||
name: str = None
|
||||
speed: int = None
|
||||
now: float = None
|
||||
|
||||
def __json__(self) -> dict:
|
||||
return dict(
|
||||
|
|
@ -339,33 +350,29 @@ IGNORED_NIC_NAMES = {
|
|||
}
|
||||
|
||||
|
||||
def get_nic_names() -> List[str]:
|
||||
"""Finds all non-virtual and non-docker network interface names."""
|
||||
names = []
|
||||
for name, nic in psutil.net_if_stats().items():
|
||||
if any(name.startswith(i) for i in IGNORED_NIC_NAMES):
|
||||
continue
|
||||
names.append(name)
|
||||
return names
|
||||
|
||||
|
||||
@dataclass
|
||||
class DiskBandwidthInfo:
|
||||
bytes_recv: int = None
|
||||
bytes_sent: int = None
|
||||
bytes_read_ps: int = None
|
||||
bytes_write_ps: int = None
|
||||
elapsed: int = None
|
||||
name: str = None
|
||||
maximum_read_ps: int = None
|
||||
maximum_write_ps: int = None
|
||||
now: float = None
|
||||
max_read_ps: int = None
|
||||
max_write_ps: int = None
|
||||
|
||||
def __json__(self) -> dict:
|
||||
return dict(
|
||||
bytes_recv=self.bytes_recv,
|
||||
bytes_sent=self.bytes_sent,
|
||||
bytes_read_ps=self.bytes_read_ps,
|
||||
bytes_write_ps=self.bytes_write_ps,
|
||||
elapsed=self.elapsed,
|
||||
name=self.name,
|
||||
maximum_read_ps=self.maximum_read_ps,
|
||||
maximum_write_ps=self.maximum_write_ps,
|
||||
now=self.now,
|
||||
max_read_ps=self.max_read_ps,
|
||||
max_write_ps=self.max_write_ps,
|
||||
)
|
||||
|
||||
|
||||
|
|
@ -375,212 +382,159 @@ IGNORED_DISK_NAMES = (
|
|||
)
|
||||
|
||||
|
||||
async def get_bandwidth_info() -> Tuple[List[NICBandwidthInfo], List[DiskBandwidthInfo]]:
|
||||
"""Get all bandwidth information for all NICs and Disks."""
|
||||
from wrolpi.api_utils import api_app
|
||||
nics_info = []
|
||||
disks_info = []
|
||||
|
||||
try:
|
||||
for name in sorted(api_app.shared_ctx.bandwidth.keys()):
|
||||
nic = api_app.shared_ctx.bandwidth[name]
|
||||
if 'bytes_recv_ps' not in nic:
|
||||
# Not stats collected yet.
|
||||
continue
|
||||
nics_info.append(NICBandwidthInfo(
|
||||
bytes_recv=nic['bytes_recv_ps'],
|
||||
bytes_sent=nic['bytes_sent_ps'],
|
||||
elapsed=nic['elapsed'],
|
||||
name=name,
|
||||
speed=nic['speed'],
|
||||
))
|
||||
used_disks = []
|
||||
for name in sorted(api_app.shared_ctx.disks_bandwidth.keys()):
|
||||
disk = api_app.shared_ctx.disks_bandwidth[name]
|
||||
if 'bytes_read_ps' not in disk:
|
||||
# No status collected yet
|
||||
continue
|
||||
if any(name.startswith(i) for i in used_disks):
|
||||
# Report only the first disk. Do not report it's partitions. Disks are sorted to make this work!
|
||||
# i.e. report "sda" but not "sda1" or "sda2".
|
||||
continue
|
||||
if any(name.startswith(i) for i in IGNORED_DISK_NAMES):
|
||||
continue
|
||||
used_disks.append(name)
|
||||
|
||||
try:
|
||||
maximum_read_ps = max(disk['bytes_read_ps'],
|
||||
api_app.shared_ctx.max_disks_bandwidth[name]['maximum_read_ps'])
|
||||
maximum_write_ps = max(disk['bytes_write_ps'],
|
||||
api_app.shared_ctx.max_disks_bandwidth[name]['maximum_write_ps'])
|
||||
except KeyError:
|
||||
# Use a low first value. Hopefully all drives are capable of this speed.
|
||||
maximum_read_ps = 500_000
|
||||
maximum_write_ps = 500_000
|
||||
# Always write the new maximums.
|
||||
value = {name: {'maximum_read_ps': maximum_read_ps, 'maximum_write_ps': maximum_write_ps}}
|
||||
api_app.shared_ctx.max_disks_bandwidth.update(value)
|
||||
|
||||
disks_info.append(DiskBandwidthInfo(
|
||||
bytes_read_ps=disk['bytes_read_ps'],
|
||||
bytes_write_ps=disk['bytes_write_ps'],
|
||||
elapsed=disk['elapsed'],
|
||||
name=name,
|
||||
maximum_read_ps=maximum_read_ps,
|
||||
maximum_write_ps=maximum_write_ps,
|
||||
))
|
||||
except Exception as e:
|
||||
warn_once(e)
|
||||
|
||||
return nics_info, disks_info
|
||||
|
||||
|
||||
def _get_nic_tick(name_):
|
||||
def _get_nic_counters() -> dict:
|
||||
"""
|
||||
Get the instant network statistics for the provided NIC.
|
||||
"""
|
||||
try:
|
||||
counter = psutil.net_io_counters(pernic=True, nowrap=True)[name_]
|
||||
stats = psutil.net_if_stats()[name_]
|
||||
return now().timestamp(), counter.bytes_recv, counter.bytes_sent, int(stats.speed)
|
||||
except Exception as e:
|
||||
warn_once(e)
|
||||
return 0, 0, 0, 0
|
||||
timestamp = now().timestamp()
|
||||
counters = dict()
|
||||
if_stats = psutil.net_if_stats()
|
||||
for name, counter in psutil.net_io_counters(pernic=True, nowrap=True).items():
|
||||
if name in IGNORED_NIC_NAMES:
|
||||
continue
|
||||
stats = if_stats[name]
|
||||
counters[name] = {
|
||||
'name': name,
|
||||
'now': timestamp,
|
||||
'bytes_recv': counter.bytes_recv,
|
||||
'bytes_sent': counter.bytes_sent,
|
||||
'speed': int(stats.speed),
|
||||
}
|
||||
return counters
|
||||
|
||||
|
||||
def _calculate_bytes_per_second(history: List[Tuple]) -> Tuple[int, int, int]:
|
||||
def _get_disk_counters() -> dict:
|
||||
"""
|
||||
Get the instant disk statistics for the provided NIC.
|
||||
"""
|
||||
timestamp = now().timestamp()
|
||||
counters = dict()
|
||||
|
||||
for name, counter in sorted(psutil.disk_io_counters(perdisk=True).items(), key=lambda i: i[0]):
|
||||
if any(name.startswith(i) for i in counters):
|
||||
# Report only the first disk. Do not report its partitions. Disks are sorted to make this work!
|
||||
# i.e. report "sda" but not "sda1" or "sda2".
|
||||
continue
|
||||
if any(name.startswith(i) for i in IGNORED_DISK_NAMES):
|
||||
continue
|
||||
counters[name] = {
|
||||
'name': name,
|
||||
'now': timestamp,
|
||||
'bytes_recv': counter.read_bytes,
|
||||
'bytes_sent': counter.write_bytes,
|
||||
}
|
||||
|
||||
return counters
|
||||
|
||||
|
||||
def _calculate_bytes_per_second(old_stats: dict, new_stats: dict) -> Tuple[int, int, int]:
|
||||
"""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)
|
||||
old_now, old_recv, old_sent = old_stats['now'], old_stats['bytes_recv'], old_stats['bytes_sent']
|
||||
new_now, new_recv, new_sent = new_stats['now'], new_stats['bytes_recv'], new_stats['bytes_sent']
|
||||
elapsed = int(new_now - old_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)
|
||||
bytes_recv_ps = int((new_recv - old_recv) // elapsed)
|
||||
bytes_sent_ps = int((new_sent - old_sent) // elapsed)
|
||||
return bytes_recv_ps, bytes_sent_ps, elapsed
|
||||
|
||||
|
||||
@api_app.signal('wrolpi.periodic.bandwidth')
|
||||
async def bandwidth_worker(count: int = None):
|
||||
"""A background process which will gather historical data about all NIC bandwidth statistics."""
|
||||
from wrolpi.api_utils import api_app
|
||||
@api_app.signal('wrolpi.periodic.status')
|
||||
async def status_worker(count: int = None, sleep_time: int = 5):
|
||||
"""A background process which will gather historical data about system statistics."""
|
||||
shared_status = api_app.shared_ctx.status
|
||||
|
||||
if not psutil:
|
||||
return
|
||||
if count is not None and count <= 0:
|
||||
logger.debug('Status worker ran out of count')
|
||||
return dict(**shared_status)
|
||||
|
||||
logger.info('Bandwidth worker started')
|
||||
load_stats = None
|
||||
try:
|
||||
# Update global `status` dict with stats that are gathered instantly.
|
||||
cpu_stats, load_stats, drives_stats, memory_stats, processes_stats = await asyncio.gather(
|
||||
get_cpu_stats(),
|
||||
get_load_stats(),
|
||||
get_drives_stats(),
|
||||
get_memory_stats(),
|
||||
get_processes_stats(),
|
||||
)
|
||||
shared_status.update({
|
||||
'cpu_stats': cpu_stats.__json__(),
|
||||
'load_stats': load_stats.__json__(),
|
||||
'drives_stats': [i.__json__() for i in drives_stats],
|
||||
'processes_stats': [i.__json__() for i in processes_stats],
|
||||
'memory_stats': memory_stats.__json__(),
|
||||
})
|
||||
|
||||
nic_names = get_nic_names()
|
||||
|
||||
def append_all_stats():
|
||||
for name_ in nic_names:
|
||||
nic = api_app.shared_ctx.bandwidth.get(name_)
|
||||
if not nic:
|
||||
# Initialize history for this NIC.
|
||||
api_app.shared_ctx.bandwidth.update({
|
||||
name_: dict(historical=[_get_nic_tick(name_), ]),
|
||||
})
|
||||
else:
|
||||
# Append to history for this NIC.
|
||||
nic['historical'] = (nic['historical'] + [_get_nic_tick(name_), ])[-21:]
|
||||
api_app.shared_ctx.bandwidth.update({name_: nic})
|
||||
|
||||
timestamp = now().timestamp()
|
||||
for name_, disk in psutil.disk_io_counters(perdisk=True).items():
|
||||
tic = timestamp, disk.read_bytes, disk.write_bytes
|
||||
if bw := api_app.shared_ctx.disks_bandwidth.get(name_):
|
||||
bw['historical'] = (bw['historical'] + [tic, ])[-21:]
|
||||
api_app.shared_ctx.disks_bandwidth.update({name_: bw})
|
||||
else:
|
||||
api_app.shared_ctx.disks_bandwidth.update({
|
||||
name_: dict(historical=[tic, ]),
|
||||
})
|
||||
|
||||
# Initialize the stats.
|
||||
append_all_stats()
|
||||
|
||||
while count is None or count > 0:
|
||||
try:
|
||||
await asyncio.sleep(1)
|
||||
except asyncio.CancelledError:
|
||||
# Server is restarting.
|
||||
break
|
||||
|
||||
if count is not None:
|
||||
count -= 1
|
||||
|
||||
append_all_stats()
|
||||
|
||||
# Calculate the difference between the first and last bandwidth ticks for all NICs.
|
||||
for name, nic in api_app.shared_ctx.bandwidth.items():
|
||||
historical = nic['historical']
|
||||
bytes_recv_ps, bytes_sent_ps, elapsed = _calculate_bytes_per_second(historical)
|
||||
api_app.shared_ctx.bandwidth.update({
|
||||
name: dict(
|
||||
historical=historical,
|
||||
bytes_recv_ps=bytes_recv_ps,
|
||||
bytes_sent_ps=bytes_sent_ps,
|
||||
elapsed=elapsed,
|
||||
speed=historical[-1][-1], # Use the most recent speed.
|
||||
)
|
||||
if 'disk_bandwidth_stats' not in shared_status:
|
||||
# Worker has just been started, fill it with some starting bandwidth data.
|
||||
disk_info = _get_disk_counters()
|
||||
for name in disk_info.keys():
|
||||
disk_info[name].update({'max_read_ps': 500_000, 'max_write_ps': 500_000})
|
||||
shared_status.update({
|
||||
'nic_bandwidth_stats': _get_nic_counters(),
|
||||
'disk_bandwidth_stats': disk_info,
|
||||
})
|
||||
for name, stats in api_app.shared_ctx.disks_bandwidth.items():
|
||||
if 'historical' not in stats:
|
||||
continue
|
||||
# Break out and call the `finally` code below.
|
||||
return
|
||||
|
||||
historical = stats['historical']
|
||||
bytes_read_ps, bytes_write_ps, elapsed = _calculate_bytes_per_second(historical)
|
||||
api_app.shared_ctx.disks_bandwidth.update({
|
||||
name: dict(
|
||||
historical=historical,
|
||||
bytes_read_ps=bytes_read_ps,
|
||||
bytes_write_ps=bytes_write_ps,
|
||||
elapsed=elapsed,
|
||||
)
|
||||
})
|
||||
# Calculate the difference between the previous status worker's bandwidth count and now.
|
||||
new_nic_stats = _get_nic_counters()
|
||||
old_nic_stats = shared_status['nic_bandwidth_stats']
|
||||
nic_bandwidth_stats = dict()
|
||||
for name, old_stats in old_nic_stats.items():
|
||||
new_stats = new_nic_stats[name]
|
||||
bytes_recv_ps, bytes_sent_ps, elapsed = _calculate_bytes_per_second(old_stats, new_stats)
|
||||
new_stats.update(dict(
|
||||
bytes_recv_ps=bytes_recv_ps,
|
||||
bytes_sent_ps=bytes_sent_ps,
|
||||
elapsed=elapsed,
|
||||
))
|
||||
nic_bandwidth_stats[name] = new_stats
|
||||
|
||||
# Calculate the difference between the previous status worker's disk bandwidth count and now.
|
||||
new_disk_stats = _get_disk_counters()
|
||||
old_disk_stats = shared_status['disk_bandwidth_stats']
|
||||
disk_bandwidth_stats = dict()
|
||||
for name, old_stats in old_disk_stats.items():
|
||||
new_stats = new_disk_stats[name]
|
||||
bytes_read_ps, bytes_write_ps, elapsed = _calculate_bytes_per_second(old_stats, new_stats)
|
||||
new_stats.update(dict(
|
||||
bytes_read_ps=bytes_read_ps,
|
||||
bytes_write_ps=bytes_write_ps,
|
||||
elapsed=elapsed,
|
||||
max_read_ps=max(bytes_read_ps, old_stats['max_read_ps']),
|
||||
max_write_ps=max(bytes_write_ps, old_stats['max_write_ps']),
|
||||
))
|
||||
disk_bandwidth_stats[name] = new_stats
|
||||
|
||||
@dataclass
|
||||
class Status:
|
||||
cpu_info: CPUInfo
|
||||
load: SystemLoad
|
||||
drives: List[DriveInfo]
|
||||
bandwidth: NICBandwidthInfo
|
||||
disk_bandwidth: DiskBandwidthInfo
|
||||
memory_stats: MemoryStats
|
||||
shared_status.update({
|
||||
'nic_bandwidth_stats': nic_bandwidth_stats,
|
||||
'disk_bandwidth_stats': disk_bandwidth_stats,
|
||||
})
|
||||
except Exception as e:
|
||||
status_worker_warn_once(e)
|
||||
raise
|
||||
finally:
|
||||
if load_stats and load_stats.minute_1 and load_stats.minute_1 > multiprocessing.cpu_count():
|
||||
# System is stressed, slow down status updates.
|
||||
await asyncio.sleep(sleep_time)
|
||||
|
||||
|
||||
async def get_status() -> Status:
|
||||
cpu_info, load, drives, memory_stats, (nic_bandwidth, disk_bandwidth) = await asyncio.gather(
|
||||
get_cpu_info(),
|
||||
get_load(),
|
||||
get_drives_info(),
|
||||
get_memory_stats(),
|
||||
get_bandwidth_info(),
|
||||
)
|
||||
return Status(
|
||||
cpu_info=cpu_info,
|
||||
load=load,
|
||||
drives=drives,
|
||||
bandwidth=nic_bandwidth,
|
||||
disk_bandwidth=disk_bandwidth,
|
||||
memory_stats=memory_stats,
|
||||
)
|
||||
# Always sleep so this does not become a busy loop with errors.
|
||||
await asyncio.sleep(sleep_time)
|
||||
if count:
|
||||
# Running in testing, or __main__.
|
||||
return await status_worker(count - 1, sleep_time)
|
||||
else:
|
||||
await api_app.dispatch('wrolpi.periodic.status', context={'sleep_time': sleep_time})
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
from pprint import pprint
|
||||
from wrolpi.contexts import attach_shared_contexts
|
||||
|
||||
loop = asyncio.get_event_loop()
|
||||
|
||||
loop.run_until_complete(bandwidth_worker(2))
|
||||
|
||||
task = asyncio.gather(
|
||||
get_cpu_info(),
|
||||
get_memory_stats(),
|
||||
get_load(),
|
||||
get_drives_info(),
|
||||
get_bandwidth_info(),
|
||||
)
|
||||
info_ = loop.run_until_complete(task)
|
||||
pprint(info_)
|
||||
SKIP_DISPATCH = True
|
||||
attach_shared_contexts(api_app)
|
||||
loop.run_until_complete(status_worker(2, sleep_time=2))
|
||||
print(json.dumps(dict(api_app.shared_ctx.status), indent=2))
|
||||
|
|
|
|||
|
|
@ -378,15 +378,15 @@ async def test_get_status(test_async_client, test_session):
|
|||
"""Get the server status information."""
|
||||
request, response = await test_async_client.get('/api/status')
|
||||
assert response.status_code == HTTPStatus.OK
|
||||
assert 'cpu_info' in response.json and isinstance(response.json['cpu_info'], dict)
|
||||
assert 'load' in response.json and isinstance(response.json['load'], dict)
|
||||
assert 'drives' in response.json and isinstance(response.json['drives'], list)
|
||||
assert 'downloads' in response.json and isinstance(response.json['downloads'], dict)
|
||||
assert 'hotspot_status' in response.json and isinstance(response.json['hotspot_status'], str)
|
||||
assert 'throttle_status' in response.json and isinstance(response.json['throttle_status'], str)
|
||||
assert 'version' in response.json and isinstance(response.json['version'], str)
|
||||
assert 'memory_stats' in response.json and isinstance(response.json['memory_stats'], dict)
|
||||
assert 'flags' in response.json and isinstance(response.json['flags'], dict)
|
||||
assert isinstance(response.json.get('cpu_stats'), dict), 'cpu_stats should be a dict'
|
||||
assert isinstance(response.json.get('load_stats'), dict), 'load_stats should be a dict'
|
||||
assert isinstance(response.json.get('drives_stats'), list), 'drive_stats should be a dict'
|
||||
assert isinstance(response.json.get('downloads'), dict), 'downloads should be a dict'
|
||||
assert isinstance(response.json.get('hotspot_status'), str), 'hotspot_status should be a str'
|
||||
assert isinstance(response.json.get('throttle_status'), str), 'throttle_status should be a str'
|
||||
assert isinstance(response.json.get('version'), str), 'version should be a str'
|
||||
assert isinstance(response.json.get('memory_stats'), dict), 'memory_stats should be a dict'
|
||||
assert isinstance(response.json.get('flags'), dict), 'flags should be a dict'
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
|
|
|
|||
|
|
@ -7,9 +7,9 @@ from wrolpi import status
|
|||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_get_load():
|
||||
async def test_get_load(test_async_client):
|
||||
"""Test reading load information from /proc/loadavg."""
|
||||
load = await status.get_load()
|
||||
load = await status.get_load_stats()
|
||||
assert isinstance(load, status.SystemLoad)
|
||||
|
||||
assert isinstance(load.minute_1, Decimal) and load.minute_1 >= 0
|
||||
|
|
@ -18,63 +18,40 @@ async def test_get_load():
|
|||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_get_cpu_info():
|
||||
async def test_get_cpu_stats(test_async_client):
|
||||
"""Minimum CPU info testing because this will fail in docker, etc."""
|
||||
info = await status.get_cpu_info()
|
||||
info = await status.get_cpu_stats()
|
||||
assert isinstance(info, status.CPUInfo)
|
||||
assert isinstance(info.percent, int)
|
||||
assert isinstance(info.temperature, int)
|
||||
assert isinstance(info.high_temperature, int)
|
||||
assert isinstance(info.critical_temperature, int)
|
||||
|
||||
with mock.patch('wrolpi.status.get_cpu_info_psutil') as mock_get_cpu_info_psutil:
|
||||
# Fallback to subprocess when psutil is not available.
|
||||
mock_get_cpu_info_psutil.side_effect = Exception('testing no psutil')
|
||||
info = await status.get_cpu_info()
|
||||
assert isinstance(info, status.CPUInfo)
|
||||
assert isinstance(info.percent, int)
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_get_drives_info():
|
||||
async def test_get_drives_stats(test_async_client):
|
||||
"""Minimum drives info testing because this will fail in docker, etc."""
|
||||
info = await status.get_drives_info()
|
||||
info = await status.get_drives_stats()
|
||||
assert isinstance(info, list)
|
||||
assert len(info) >= 1
|
||||
assert isinstance(info[0], status.DriveInfo)
|
||||
|
||||
with mock.patch('wrolpi.status.get_drives_info_psutil') as mock_get_drives_info_psutil:
|
||||
with mock.patch('wrolpi.status.get_drives_info_psutil') as mock_get_drives_stats_psutil:
|
||||
# Fallback to subprocess when psutil is not available.
|
||||
mock_get_drives_info_psutil.side_effect = Exception('testing no psutil')
|
||||
info = await status.get_drives_info()
|
||||
mock_get_drives_stats_psutil.side_effect = Exception('testing no psutil')
|
||||
info = await status.get_drives_stats()
|
||||
assert isinstance(info, list)
|
||||
assert len(info) >= 1
|
||||
assert isinstance(info[0], status.DriveInfo)
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_get_bandwidth_info():
|
||||
"""Bandwidth requires psutil"""
|
||||
nic_bandwidths, disk_bandwidths = await status.get_bandwidth_info()
|
||||
assert nic_bandwidths == []
|
||||
assert disk_bandwidths == []
|
||||
async def test_status_worker(test_async_client):
|
||||
"""Status worker calls itself perpetually, but can be limited during testing."""
|
||||
from wrolpi.api_utils import api_app
|
||||
assert test_async_client.sanic_app.shared_ctx.status['cpu_stats'] == dict()
|
||||
|
||||
await status.bandwidth_worker(2)
|
||||
nic_bandwidths, disk_bandwidths = await status.get_bandwidth_info()
|
||||
assert isinstance(nic_bandwidths, list)
|
||||
assert len(nic_bandwidths) > 0
|
||||
assert isinstance(nic_bandwidths[0], status.NICBandwidthInfo)
|
||||
assert isinstance(disk_bandwidths, list)
|
||||
assert len(disk_bandwidths) > 0
|
||||
assert isinstance(disk_bandwidths[0], status.DiskBandwidthInfo)
|
||||
|
||||
with mock.patch('wrolpi.status.psutil.net_io_counters') as mock_net_io_counters:
|
||||
# NO FALLBACK!
|
||||
mock_net_io_counters.side_effect = Exception('testing no psutil')
|
||||
await status.bandwidth_worker(1)
|
||||
nic_bandwidths, disk_bandwidths = await status.get_bandwidth_info()
|
||||
assert isinstance(nic_bandwidths[0].bytes_recv, int)
|
||||
assert isinstance(nic_bandwidths[0].bytes_sent, int)
|
||||
assert isinstance(nic_bandwidths[0].elapsed, int)
|
||||
assert isinstance(nic_bandwidths[0].speed, int)
|
||||
assert isinstance(nic_bandwidths[0].name, str)
|
||||
# Status worker fills out stats as it goes along.
|
||||
await status.status_worker(count=2)
|
||||
assert api_app.shared_ctx.status['nic_bandwidth_stats']
|
||||
assert 'bytes_recv' in list(api_app.shared_ctx.status['nic_bandwidth_stats'].values())[0]
|
||||
assert api_app.shared_ctx.status['disk_bandwidth_stats']
|
||||
assert 'bytes_recv' in list(api_app.shared_ctx.status['disk_bandwidth_stats'].values())[0]
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue