mirror of
https://github.com/lrnselfreliance/wrolpi.git
synced 2026-11-25 01:16:18 -05:00
Merge pull request #115 from lrnselfreliance/feature/debian-install
Feature/debian install Signed-off-by: Roland <roland@learningselfreliance.com>
This commit is contained in:
commit
be4c3a5021
28 changed files with 578 additions and 188 deletions
18
README.md
18
README.md
|
|
@ -45,7 +45,7 @@ You can try out WROLPi by running the docker containers.
|
|||
1. [Install docker-ce](https://docs.docker.com/install/linux/docker-ce/debian/) and
|
||||
[docker-compose](https://docs.docker.com/compose/install/)
|
||||
2. Copy the latest WROLPi code
|
||||
* `git clone git@github.com:lrnselfreliance/wrolpi.git`
|
||||
* `git clone https://github.com/lrnselfreliance/wrolpi.git`
|
||||
3. Change directory into the code base
|
||||
* `cd wrolpi`
|
||||
4. Build the containers
|
||||
|
|
@ -62,6 +62,22 @@ You can try out WROLPi by running the docker containers.
|
|||
9. Browse to WROLPi
|
||||
* http://0.0.0.0:8080
|
||||
|
||||
# Debian 11 Install
|
||||
|
||||
Install WROLPi onto a fresh Debian 11 system.
|
||||
|
||||
**Warning: this will clobber anything else on the system! Do not run this installation script elsewhere!**
|
||||
|
||||
1. Install [Debian 11](https://www.debian.org/) onto a laptop or other computer.
|
||||
2. Login to the new system.
|
||||
3. Get the WROLPi installation script
|
||||
* `wget https://raw.githubusercontent.com/lrnselfreliance/wrolpi/release/install.sh -O /tmp/install.sh`
|
||||
4. Run the installation script
|
||||
* `sudo /bin/bash /tmp/install.sh`
|
||||
5. Start WROLPi
|
||||
* `sudo systemctl start wrolpi.target`
|
||||
6. Browse to the IP address of your WROLPi!
|
||||
|
||||
# RaspberryPi Install
|
||||
|
||||
Install WROLPi onto a fresh Raspberry Pi.
|
||||
|
|
|
|||
39
etc/debian11/000-default.conf
Normal file
39
etc/debian11/000-default.conf
Normal file
|
|
@ -0,0 +1,39 @@
|
|||
<VirtualHost *:8084>
|
||||
# The ServerName directive sets the request scheme, hostname and port that
|
||||
# the server uses to identify itself. This is used when creating
|
||||
# redirection URLs. In the context of virtual hosts, the ServerName
|
||||
# specifies what hostname must appear in the request's Host: header to
|
||||
# match this virtual host. For the default virtual host (this file) this
|
||||
# value is not decisive as it is used as a last resort host regardless.
|
||||
# However, you must set it for any further virtual host explicitly.
|
||||
#ServerName www.example.com
|
||||
|
||||
ServerAdmin webmaster@localhost
|
||||
|
||||
LoadTileConfigFile /etc/renderd.conf
|
||||
ModTileRenderdSocketName /var/run/renderd/renderd.sock
|
||||
# Timeout before giving up for a tile to be rendered
|
||||
ModTileRequestTimeout 0
|
||||
# Timeout before giving up for a tile to be rendered that is otherwise missing
|
||||
ModTileMissingRequestTimeout 30
|
||||
|
||||
DocumentRoot /var/www/html
|
||||
|
||||
# Available loglevels: trace8, ..., trace1, debug, info, notice, warn,
|
||||
# error, crit, alert, emerg.
|
||||
# It is also possible to configure the loglevel for particular
|
||||
# modules, e.g.
|
||||
#LogLevel info ssl:warn
|
||||
|
||||
ErrorLog ${APACHE_LOG_DIR}/error.log
|
||||
CustomLog ${APACHE_LOG_DIR}/access.log combined
|
||||
|
||||
# For most configuration files from conf-available/, which are
|
||||
# enabled or disabled at a global level, it is possible to
|
||||
# include a line for only one particular virtual host. For example the
|
||||
# following line enables the CGI configuration for this host only
|
||||
# after it has been globally disabled with "a2disconf".
|
||||
#Include conf-available/serve-cgi-bin.conf
|
||||
</VirtualHost>
|
||||
|
||||
# vim: syntax=apache ts=4 sw=4 sts=4 sr noet
|
||||
1
etc/debian11/README.md
Normal file
1
etc/debian11/README.md
Normal file
|
|
@ -0,0 +1 @@
|
|||
The files in `etc` are files necessary to build an on-the-metal WROLPi.
|
||||
37
etc/debian11/index.html
Normal file
37
etc/debian11/index.html
Normal file
|
|
@ -0,0 +1,37 @@
|
|||
<!DOCTYPE HTML>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="utf-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<script src="/leaflet.js"></script>
|
||||
<link rel="stylesheet" href="/leaflet.css" />
|
||||
<style>
|
||||
html, body {
|
||||
height: 100%;
|
||||
padding: 0;
|
||||
margin: 0;
|
||||
}
|
||||
#map {
|
||||
/* configure the size of the map */
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
}
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<div id="map"></div>
|
||||
<script>
|
||||
// initialize Leaflet
|
||||
var map = L.map('map').setView({lon: 0, lat: 0}, 2);
|
||||
|
||||
// add the OpenStreetMap tiles
|
||||
L.tileLayer(`http://${window.location.hostname}:8084/hot/{z}/{x}/{y}.png`, {
|
||||
maxZoom: 19,
|
||||
attribution: '© <a href="https://openstreetmap.org/copyright">OpenStreetMap contributors</a>'
|
||||
}).addTo(map);
|
||||
|
||||
// show the scale bar on the lower left corner
|
||||
L.control.scale({imperial: true, metric: true}).addTo(map);
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
15
etc/debian11/ports.conf
Normal file
15
etc/debian11/ports.conf
Normal file
|
|
@ -0,0 +1,15 @@
|
|||
# If you just change the port or add more ports here, you will likely also
|
||||
# have to change the VirtualHost statement in
|
||||
# /etc/apache2/sites-enabled/000-default.conf
|
||||
|
||||
Listen 8084
|
||||
|
||||
<IfModule ssl_module>
|
||||
Listen 443
|
||||
</IfModule>
|
||||
|
||||
<IfModule mod_gnutls.c>
|
||||
Listen 443
|
||||
</IfModule>
|
||||
|
||||
# vim: syntax=apache ts=4 sw=4 sts=4 sr noet
|
||||
18
etc/debian11/renderd.conf
Normal file
18
etc/debian11/renderd.conf
Normal file
|
|
@ -0,0 +1,18 @@
|
|||
[renderd]
|
||||
stats_file=/run/renderd/renderd.stats
|
||||
socketname=/run/renderd/renderd.sock
|
||||
num_threads=4
|
||||
tile_dir=/var/cache/renderd/tiles
|
||||
|
||||
[mapnik]
|
||||
plugins_dir=/usr/lib/mapnik/3.1/input
|
||||
font_dir=/usr/share/fonts/truetype
|
||||
font_dir_recurse=true
|
||||
|
||||
[ajt]
|
||||
URI=/hot/
|
||||
TILEDIR=/var/lib/mod_tile
|
||||
XML=/opt/openstreetmap-carto/mapnik.xml
|
||||
HOST=localhost
|
||||
TILESIZE=256
|
||||
MAXZOOM=20
|
||||
13
etc/debian11/wrolpi-app.service
Normal file
13
etc/debian11/wrolpi-app.service
Normal file
|
|
@ -0,0 +1,13 @@
|
|||
[Unit]
|
||||
Description=WROLPi React APP
|
||||
Wants=wrolpi-api.service
|
||||
PartOf=wrolpi.target
|
||||
|
||||
[Service]
|
||||
ExecStart=/usr/local/bin/serve -s build -l 5000
|
||||
Group=wrolpi
|
||||
User=wrolpi
|
||||
WorkingDirectory=/opt/wrolpi/app/
|
||||
|
||||
[Install]
|
||||
WantedBy=default.target
|
||||
39
etc/ubuntu20.04/000-default.conf
Normal file
39
etc/ubuntu20.04/000-default.conf
Normal file
|
|
@ -0,0 +1,39 @@
|
|||
<VirtualHost *:8084>
|
||||
# The ServerName directive sets the request scheme, hostname and port that
|
||||
# the server uses to identify itself. This is used when creating
|
||||
# redirection URLs. In the context of virtual hosts, the ServerName
|
||||
# specifies what hostname must appear in the request's Host: header to
|
||||
# match this virtual host. For the default virtual host (this file) this
|
||||
# value is not decisive as it is used as a last resort host regardless.
|
||||
# However, you must set it for any further virtual host explicitly.
|
||||
#ServerName www.example.com
|
||||
|
||||
ServerAdmin webmaster@localhost
|
||||
|
||||
LoadTileConfigFile /usr/local/etc/renderd.conf
|
||||
ModTileRenderdSocketName /var/run/renderd/renderd.sock
|
||||
# Timeout before giving up for a tile to be rendered
|
||||
ModTileRequestTimeout 0
|
||||
# Timeout before giving up for a tile to be rendered that is otherwise missing
|
||||
ModTileMissingRequestTimeout 30
|
||||
|
||||
DocumentRoot /var/www/html
|
||||
|
||||
# Available loglevels: trace8, ..., trace1, debug, info, notice, warn,
|
||||
# error, crit, alert, emerg.
|
||||
# It is also possible to configure the loglevel for particular
|
||||
# modules, e.g.
|
||||
#LogLevel info ssl:warn
|
||||
|
||||
ErrorLog ${APACHE_LOG_DIR}/error.log
|
||||
CustomLog ${APACHE_LOG_DIR}/access.log combined
|
||||
|
||||
# For most configuration files from conf-available/, which are
|
||||
# enabled or disabled at a global level, it is possible to
|
||||
# include a line for only one particular virtual host. For example the
|
||||
# following line enables the CGI configuration for this host only
|
||||
# after it has been globally disabled with "a2disconf".
|
||||
#Include conf-available/serve-cgi-bin.conf
|
||||
</VirtualHost>
|
||||
|
||||
# vim: syntax=apache ts=4 sw=4 sts=4 sr noet
|
||||
37
etc/ubuntu20.04/index.html
Normal file
37
etc/ubuntu20.04/index.html
Normal file
|
|
@ -0,0 +1,37 @@
|
|||
<!DOCTYPE HTML>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="utf-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<script src="/leaflet.js"></script>
|
||||
<link rel="stylesheet" href="/leaflet.css" />
|
||||
<style>
|
||||
html, body {
|
||||
height: 100%;
|
||||
padding: 0;
|
||||
margin: 0;
|
||||
}
|
||||
#map {
|
||||
/* configure the size of the map */
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
}
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<div id="map"></div>
|
||||
<script>
|
||||
// initialize Leaflet
|
||||
var map = L.map('map').setView({lon: 0, lat: 0}, 2);
|
||||
|
||||
// add the OpenStreetMap tiles
|
||||
L.tileLayer(`http://${window.location.hostname}:8084/hot/{z}/{x}/{y}.png`, {
|
||||
maxZoom: 19,
|
||||
attribution: '© <a href="https://openstreetmap.org/copyright">OpenStreetMap contributors</a>'
|
||||
}).addTo(map);
|
||||
|
||||
// show the scale bar on the lower left corner
|
||||
L.control.scale({imperial: true, metric: true}).addTo(map);
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
1
etc/ubuntu20.04/mod_tile.conf
Normal file
1
etc/ubuntu20.04/mod_tile.conf
Normal file
|
|
@ -0,0 +1 @@
|
|||
LoadModule tile_module /usr/lib/apache2/modules/mod_tile.so
|
||||
15
etc/ubuntu20.04/ports.conf
Normal file
15
etc/ubuntu20.04/ports.conf
Normal file
|
|
@ -0,0 +1,15 @@
|
|||
# If you just change the port or add more ports here, you will likely also
|
||||
# have to change the VirtualHost statement in
|
||||
# /etc/apache2/sites-enabled/000-default.conf
|
||||
|
||||
Listen 8084
|
||||
|
||||
<IfModule ssl_module>
|
||||
Listen 443
|
||||
</IfModule>
|
||||
|
||||
<IfModule mod_gnutls.c>
|
||||
Listen 443
|
||||
</IfModule>
|
||||
|
||||
# vim: syntax=apache ts=4 sw=4 sts=4 sr noet
|
||||
17
etc/ubuntu20.04/renderd.conf
Normal file
17
etc/ubuntu20.04/renderd.conf
Normal file
|
|
@ -0,0 +1,17 @@
|
|||
[renderd]
|
||||
num_threads=4
|
||||
tile_dir=/var/lib/mod_tile
|
||||
stats_file=/var/run/renderd/renderd.stats
|
||||
|
||||
[mapnik]
|
||||
plugins_dir=/usr/lib/mapnik/3.0/input
|
||||
font_dir=/usr/share/fonts/truetype
|
||||
font_dir_recurse=1
|
||||
|
||||
[ajt]
|
||||
URI=/hot/
|
||||
TILEDIR=/var/lib/mod_tile
|
||||
XML=/opt/openstreetmap-carto/mapnik.xml
|
||||
HOST=localhost
|
||||
TILESIZE=256
|
||||
MAXZOOM=20
|
||||
24
install.sh
24
install.sh
|
|
@ -30,8 +30,17 @@ while getopts ":hb:" option; do
|
|||
esac
|
||||
done
|
||||
|
||||
if (! grep 'Raspberry Pi' /proc/cpuinfo >/dev/null); then
|
||||
echo 'This script can only be run on a Raspberry Pi!' && exit 2
|
||||
rpi=false
|
||||
debian11=false
|
||||
if (grep 'Raspberry Pi' /proc/cpuinfo >/dev/null); then
|
||||
rpi=true
|
||||
fi
|
||||
if (grep 'PRETTY_NAME="Debian GNU/Linux 11 (bullseye)"' /etc/os-release >/dev/null); then
|
||||
debian11=true
|
||||
fi
|
||||
|
||||
if [[ ${rpi} == false && ${debian11} == false ]]; then
|
||||
echo 'This script can only be run on a Raspberry Pi or Debian 11!' && exit 2
|
||||
fi
|
||||
|
||||
set -x
|
||||
|
|
@ -46,10 +55,15 @@ git --version
|
|||
git clone https://github.com/lrnselfreliance/wrolpi.git /opt/wrolpi || :
|
||||
(cd /opt/wrolpi && git fetch && git checkout "${BRANCH}" && git reset --hard origin/"${BRANCH}") || exit 4
|
||||
|
||||
/opt/wrolpi/scripts/ubuntu_20.04_install.sh 2>&1 | tee /opt/wrolpi/install.log
|
||||
install_code=$?
|
||||
if [ ${rpi} == true ]; then
|
||||
/opt/wrolpi/scripts/install_ubuntu_20.04.sh 2>&1 | tee /opt/wrolpi/install.log
|
||||
install_code=${PIPESTATUS[0]}
|
||||
elif [ ${debian11} == true ]; then
|
||||
/opt/wrolpi/scripts/install_debian_11.sh 2>&1 | tee /opt/wrolpi/install.log
|
||||
install_code=${PIPESTATUS[0]}
|
||||
fi
|
||||
|
||||
set +x
|
||||
|
||||
echo "Install end $(date '+%Y-%m-%d %H:%M:%S')" >>/opt/wrolpi/install.log
|
||||
exit ${install_code}
|
||||
exit "${install_code}"
|
||||
|
|
|
|||
|
|
@ -16,6 +16,7 @@ from selenium import webdriver
|
|||
from sqlalchemy.orm import Session
|
||||
|
||||
from modules.archive.models import Domain, Archive
|
||||
from wrolpi.cmd import which
|
||||
from wrolpi.common import get_media_directory, logger, chunks, extract_domain, chdir, escape_file_name, walk
|
||||
from wrolpi.dates import now, Seconds, local_timezone
|
||||
from wrolpi.db import get_db_session, get_db_curs, get_ranked_models
|
||||
|
|
@ -55,9 +56,7 @@ def get_archive_directory() -> pathlib.Path:
|
|||
|
||||
|
||||
def get_domain_directory(url: str) -> pathlib.Path:
|
||||
"""
|
||||
Get the archive directory for a particular domain.
|
||||
"""
|
||||
"""Get the archive directory for a particular domain."""
|
||||
domain = extract_domain(url)
|
||||
directory = get_archive_directory() / domain
|
||||
if directory.is_dir():
|
||||
|
|
@ -70,9 +69,7 @@ def get_domain_directory(url: str) -> pathlib.Path:
|
|||
|
||||
|
||||
def get_new_archive_files(url: str, title: Optional[str]) -> ArchiveFiles:
|
||||
"""
|
||||
Create a list of archive files using a shared name schema. Raise an error if any of them exist.
|
||||
"""
|
||||
"""Create a list of archive files using a shared name schema. Raise an error if any of them exist."""
|
||||
directory = get_domain_directory(url)
|
||||
# Datetime is valid in Linux and Windows.
|
||||
dt = archive_strftime(now())
|
||||
|
|
@ -149,15 +146,25 @@ def request_archive(url: str):
|
|||
return singlefile, readability, screenshot
|
||||
|
||||
|
||||
SINGLE_FILE_PATH = which('single-file',
|
||||
'/usr/bin/single-file', # rpi ubuntu
|
||||
'/usr/local/bin/single-file', # debian
|
||||
warn=True)
|
||||
CHROMIUM = which('chromium-browser', 'chromium',
|
||||
'/usr/bin/chromium-browser', # rpi ubuntu
|
||||
'/usr/bin/chromium', # debian
|
||||
warn=True
|
||||
)
|
||||
|
||||
|
||||
def local_singlefile(url: str):
|
||||
"""Run the single-file executable to create an HTML file archive."""
|
||||
single_file_path = pathlib.Path('/usr/bin/single-file')
|
||||
if not single_file_path.is_file():
|
||||
raise FileNotFoundError(f'single-file not found at {single_file_path}')
|
||||
if not SINGLE_FILE_PATH.is_file():
|
||||
raise FileNotFoundError(f'single-file not found')
|
||||
|
||||
cmd = (str(single_file_path),
|
||||
cmd = (str(SINGLE_FILE_PATH),
|
||||
url,
|
||||
'--browser-executable-path', '/usr/bin/chromium-browser',
|
||||
'--browser-executable-path', CHROMIUM,
|
||||
'--browser-args', '["--no-sandbox"]',
|
||||
'--dump-content')
|
||||
logger.debug(f'archive cmd: {cmd}')
|
||||
|
|
@ -167,7 +174,7 @@ def local_singlefile(url: str):
|
|||
|
||||
|
||||
def local_screenshot(url: str) -> bytes:
|
||||
"""Take a screenshot of the URL using selenium."""
|
||||
"""Take a screenshot of the URL using chromedriver."""
|
||||
logger.info(f'Screenshot: {url}')
|
||||
|
||||
# Set Chromium to headless. Use a wide window size so that screenshot will be the "desktop" version of the page.
|
||||
|
|
@ -186,14 +193,19 @@ def local_screenshot(url: str) -> bytes:
|
|||
return png
|
||||
|
||||
|
||||
READABILITY_PATH = which('readability-extractor',
|
||||
'/usr/bin/readability-extractor', # rpi ubuntu
|
||||
'/usr/local/bin/readability-extractor', # debian
|
||||
warn=True)
|
||||
|
||||
|
||||
def local_extract_readability(path: str, url: str) -> dict:
|
||||
"""Extract the readability from an HTML file, typically from single-file."""
|
||||
logger.info(f'readability for {url}')
|
||||
readability_path = pathlib.Path('/usr/bin/readability-extractor')
|
||||
if not readability_path.is_file():
|
||||
raise FileNotFoundError(f'Readability extractor not found at {readability_path}')
|
||||
if not READABILITY_PATH.is_file():
|
||||
raise FileNotFoundError(f'Readability extractor not found')
|
||||
|
||||
cmd = (readability_path, path, url)
|
||||
cmd = (READABILITY_PATH, path, url)
|
||||
logger.debug(f'readability cmd: {cmd}')
|
||||
output = subprocess.check_output(cmd, timeout=60 * 3)
|
||||
output = json.loads(output)
|
||||
|
|
|
|||
|
|
@ -7,6 +7,7 @@ from typing import List
|
|||
from sqlalchemy.orm import Session
|
||||
|
||||
from modules.map.models import MapFile
|
||||
from wrolpi.cmd import which
|
||||
from wrolpi.common import get_media_directory, walk, logger, wrol_mode_check
|
||||
from wrolpi.dates import now, timedelta_to_timestamp
|
||||
from wrolpi.db import optional_session, get_db_session
|
||||
|
|
@ -104,9 +105,12 @@ async def import_pbfs(pbfs: List[str]):
|
|||
IMPORT_EVENT.clear()
|
||||
|
||||
|
||||
BASH = which('bash', '/bin/bash', warn=True)
|
||||
|
||||
|
||||
async def import_pbf(pbf: Path):
|
||||
"""Run the osm2pgsql binary to import a PBF map file."""
|
||||
cmd = f'/bin/bash {PROJECT_DIR}/scripts/import_map.sh {pbf.absolute()}'
|
||||
cmd = f'{BASH} {PROJECT_DIR}/scripts/import_map.sh {pbf.absolute()}'
|
||||
logger.debug(f'Running import script: {cmd}')
|
||||
start = now()
|
||||
proc = await asyncio.create_subprocess_shell(cmd, stderr=asyncio.subprocess.PIPE, stdout=asyncio.subprocess.PIPE)
|
||||
|
|
|
|||
102
scripts/install_debian_11.sh
Executable file
102
scripts/install_debian_11.sh
Executable file
|
|
@ -0,0 +1,102 @@
|
|||
#!/bin/bash
|
||||
echo "Debian 11 install start: $(date '+%Y-%m-%d %H:%M:%S')"
|
||||
|
||||
set -x
|
||||
set -e
|
||||
|
||||
[ -z "$(find -H /var/lib/apt/lists -maxdepth 0 -mtime -1)" ] && apt update
|
||||
# Install dependencies
|
||||
apt install -y apt-transport-https ca-certificates curl gnupg-agent gcc libpq-dev software-properties-common \
|
||||
postgresql-13 nginx-full nginx-doc python3-full python3-dev python3-doc python3-venv htop vim ffmpeg hostapd \
|
||||
texlive-latex-base texlive-latex-extra chromium chromium-driver cpufrequtils network-manager npm
|
||||
|
||||
# Install Archiving tools.
|
||||
npm install -g 'git+https://github.com/gildas-lormeau/SingleFile'
|
||||
npm install -g 'git+https://github.com/pirate/readability-extractor'
|
||||
|
||||
# Build React app
|
||||
[[ ! -f /usr/local/bin/serve || ! -f /usr/bin/serve ]] && npm -g install serve
|
||||
cd /opt/wrolpi/app || exit 5
|
||||
npm install || npm install || npm install || npm install # try install multiple times
|
||||
npm run build
|
||||
|
||||
# Setup the virtual environment that main.py expects
|
||||
pip3 --version || (
|
||||
# If no pip, install pip
|
||||
curl https://bootstrap.pypa.io/get-pip.py -o /tmp/get-pip.py &&
|
||||
python3 /tmp/get-pip.py
|
||||
)
|
||||
|
||||
# Install python requirements files
|
||||
pip3 install -r /opt/wrolpi/requirements.txt
|
||||
|
||||
# Install the WROLPi nginx config over the default nginx config.
|
||||
cp /opt/wrolpi/nginx.conf /etc/nginx/nginx.conf
|
||||
cp /opt/wrolpi/50x.html /var/www/50x.html
|
||||
/usr/sbin/nginx -s reload
|
||||
|
||||
# Create the WROLPi user
|
||||
grep wrolpi /etc/passwd || useradd -md /home/wrolpi wrolpi -s "$(command -v bash)"
|
||||
chown -R wrolpi:wrolpi /opt/wrolpi
|
||||
|
||||
# Give WROLPi group a few privileged commands via sudo without password.
|
||||
cat >/etc/sudoers.d/90-wrolpi <<'EOF'
|
||||
%wrolpi ALL=(ALL) NOPASSWD:/usr/bin/nmcli,/usr/bin/cpufreq-set
|
||||
EOF
|
||||
chmod 660 /etc/sudoers.d/90-wrolpi
|
||||
# Verify this new file is valid.
|
||||
visudo -c -f /etc/sudoers.d/90-wrolpi
|
||||
|
||||
# Create the media directory. This should be mounted by the maintainer.
|
||||
[ -d /media/wrolpi ] || mkdir /media/wrolpi
|
||||
chown wrolpi:wrolpi /media/wrolpi
|
||||
|
||||
# Install the systemd services
|
||||
cp /opt/wrolpi/etc/ubuntu20.04/wrolpi-api.service /etc/systemd/system/
|
||||
cp /opt/wrolpi/etc/debian11/wrolpi-app.service /etc/systemd/system/
|
||||
cp /opt/wrolpi/etc/ubuntu20.04/wrolpi.target /etc/systemd/system/
|
||||
/usr/bin/systemctl daemon-reload
|
||||
systemctl enable wrolpi-api.service
|
||||
systemctl enable wrolpi-app.service
|
||||
# Stop the services so the user has to start them again. We don't want to run outdated services when updating.
|
||||
systemctl stop wrolpi-api.service
|
||||
systemctl stop wrolpi-app.service
|
||||
|
||||
# Configure Postgresql. Do this after the API is stopped.
|
||||
sudo -u postgres psql -c '\l' | grep wrolpi || (
|
||||
sudo -u postgres createuser wrolpi &&
|
||||
sudo -u postgres psql -c "alter user postgres password 'wrolpi'" &&
|
||||
sudo -u postgres psql -c "alter user wrolpi password 'wrolpi'" &&
|
||||
sudo -u postgres createdb -E UTF8 -O wrolpi wrolpi
|
||||
)
|
||||
# Initialize/upgrade the WROLPi database.
|
||||
(cd /opt/wrolpi && /usr/bin/python3 /opt/wrolpi/main.py db upgrade)
|
||||
|
||||
# Run the map installation script.
|
||||
/opt/wrolpi/scripts/install_map_debian_11.sh
|
||||
|
||||
set +x
|
||||
|
||||
ip=$(hostname -I | cut -d' ' -f1)
|
||||
if [[ $ip == *":"* ]]; then
|
||||
# Don't suggest the ipv6 address.
|
||||
ip=$(hostname -I | cut -d' ' -f2)
|
||||
fi
|
||||
|
||||
echo "
|
||||
|
||||
WROLPi has successfully been installed!
|
||||
|
||||
Mount your external hard drive to /media/wrolpi if you have one.
|
||||
|
||||
Start the WROLPi services using:
|
||||
# sudo systemctl start wrolpi.target
|
||||
|
||||
then navigate to: http://${ip}
|
||||
|
||||
Or, join to the Wifi hotspot:
|
||||
SSID: WROLPi
|
||||
Password: wrolpi hotspot
|
||||
|
||||
When on the hotspot, WROLPi is accessible at http://192.168.0.1
|
||||
"
|
||||
70
scripts/install_map_debian_11.sh
Executable file
70
scripts/install_map_debian_11.sh
Executable file
|
|
@ -0,0 +1,70 @@
|
|||
#! /usr/bin/bash
|
||||
# This script installs OpenStreetMap tile server.
|
||||
# This server uses Apache2, renderd and mod_tile to render and display map tiles.
|
||||
|
||||
set -x
|
||||
set -e
|
||||
|
||||
# Update if we haven't updated in the last day.
|
||||
[ -z "$(find -H /var/lib/apt/lists -maxdepth 0 -mtime -1)" ] && apt update
|
||||
# Install map dependencies.
|
||||
apt install -y libapache2-mod-tile renderd tar unzip wget bzip2 apache2 lua5.1 mapnik-utils python3-mapnik gdal-bin \
|
||||
fonts-noto-cjk fonts-noto-hinted fonts-noto-unhinted ttf-unifont
|
||||
|
||||
/usr/bin/npm install -g carto
|
||||
/usr/local/bin/carto -v
|
||||
|
||||
# Create `gis` database for map.
|
||||
sudo -u postgres psql -c '\l' | grep gis || sudo -u postgres createdb -E UTF8 -O wrolpi gis
|
||||
sudo -u postgres psql -d gis -c "CREATE EXTENSION postgis;" || :
|
||||
sudo -u postgres psql -d gis -c "CREATE EXTENSION hstore;" || :
|
||||
sudo -u postgres psql -d gis -c "ALTER TABLE geometry_columns OWNER TO wrolpi;"
|
||||
sudo -u postgres psql -d gis -c "ALTER TABLE spatial_ref_sys OWNER TO wrolpi;"
|
||||
|
||||
# Install Debian 11 compatible mod_tile.
|
||||
git clone -b switch2osm https://github.com/lrnselfreliance/mod_tile.git /tmp/mod_tile || :
|
||||
# Install init/systemd config to start map service on startup.
|
||||
cp /tmp/mod_tile/debian/renderd.init /etc/init.d/renderd
|
||||
sudo chmod +x /etc/init.d/renderd
|
||||
sed -i -e 's/^RUNASUSER.*/RUNASUSER=wrolpi/' /etc/init.d/renderd
|
||||
sed -i -e 's/^DAEMON=.*/DAEMON=\/usr\/bin\/$NAME/' /etc/init.d/renderd
|
||||
sed -i -e 's/^DAEMON_ARGS=.*/DAEMON_ARGS="-c \/etc\/renderd.conf"/' /etc/init.d/renderd
|
||||
cp /tmp/mod_tile/debian/renderd.service /lib/systemd/system/
|
||||
chmod +x /etc/init.d/renderd
|
||||
[ ! -d /var/lib/mod_tile ] && mkdir /var/lib/mod_tile
|
||||
chown wrolpi /var/lib/mod_tile
|
||||
|
||||
# Initialize gis database.
|
||||
git clone https://github.com/lrnselfreliance/openstreetmap-carto.git /opt/openstreetmap-carto || :
|
||||
chown -R wrolpi:wrolpi /opt/openstreetmap-carto
|
||||
cd /opt/openstreetmap-carto
|
||||
if [[ ! -f /opt/openstreetmap-carto/mapnik.xml || ! -s /opt/openstreetmap-carto/mapnik.xml ]]; then
|
||||
/usr/local/bin/carto project.mml >/opt/openstreetmap-carto/mapnik.xml
|
||||
fi
|
||||
# Initialize indexes and global polygons.
|
||||
sudo -u wrolpi /opt/openstreetmap-carto/scripts/get-external-data.py -d gis -U wrolpi
|
||||
# Use D.C. to initialized DB because it is so small.
|
||||
wget --continue https://download.geofabrik.de/north-america/us/district-of-columbia-latest.osm.pbf \
|
||||
-O /tmp/district-of-columbia-latest.osm.pbf
|
||||
# Run import in "create" mode so basic tables will be created.
|
||||
sudo -u wrolpi osm2pgsql -d gis --create --slim -G --hstore --tag-transform-script \
|
||||
/opt/openstreetmap-carto/openstreetmap-carto.lua -C 2000 --number-processes 4 \
|
||||
-S /opt/openstreetmap-carto/openstreetmap-carto.style /tmp/district-of-columbia-latest.osm.pbf
|
||||
sudo -u wrolpi psql -d gis -f /opt/openstreetmap-carto/indexes.sql
|
||||
|
||||
cp /opt/wrolpi/etc/debian11/renderd.conf /etc/renderd.conf
|
||||
# Configure Apache2 to listen on 8084.
|
||||
cp /opt/wrolpi/etc/debian11/ports.conf /etc/apache2/ports.conf
|
||||
cp /opt/wrolpi/etc/debian11/000-default.conf /etc/apache2/sites-available/000-default.conf
|
||||
# Copy Leaflet files to Apache's directory so they can be used offline.
|
||||
cp /opt/wrolpi/etc/debian11/index.html \
|
||||
/opt/wrolpi/modules/map/leaflet.js \
|
||||
/opt/wrolpi/modules/map/leaflet.css /var/www/html/
|
||||
chmod 644 /var/www/html/*
|
||||
|
||||
systemctl enable renderd
|
||||
systemctl stop renderd
|
||||
systemctl start renderd
|
||||
|
||||
systemctl stop apache2
|
||||
systemctl start apache2
|
||||
|
|
@ -26,7 +26,7 @@ sudo -u postgres psql -d gis -c "ALTER TABLE geometry_columns OWNER TO wrolpi;"
|
|||
sudo -u postgres psql -d gis -c "ALTER TABLE spatial_ref_sys OWNER TO wrolpi;"
|
||||
|
||||
# Install Ubuntu 20.04 compatible mod_tile.
|
||||
git clone -b switch2osm git://github.com/lrnselfreliance/mod_tile.git /tmp/mod_tile || :
|
||||
git clone -b switch2osm https://github.com/lrnselfreliance/mod_tile.git /tmp/mod_tile || :
|
||||
if [ ! -f /usr/lib/apache2/modules/mod_tile.so ]; then
|
||||
(cd /tmp/mod_tile && ./autogen.sh && ./configure && make -j4 && make install && make install-mod_tile && ldconfig)
|
||||
fi
|
||||
|
|
@ -40,7 +40,7 @@ chmod +x /etc/init.d/renderd
|
|||
chown wrolpi /var/lib/mod_tile
|
||||
|
||||
# Initialize gis database.
|
||||
git clone git://github.com/lrnselfreliance/openstreetmap-carto.git /opt/openstreetmap-carto || :
|
||||
git clone https://github.com/lrnselfreliance/openstreetmap-carto.git /opt/openstreetmap-carto || :
|
||||
chown -R wrolpi:wrolpi /opt/openstreetmap-carto
|
||||
cd /opt/openstreetmap-carto
|
||||
if [[ ! -f /opt/openstreetmap-carto/mapnik.xml || ! -s /opt/openstreetmap-carto/mapnik.xml ]]; then
|
||||
|
|
@ -85,133 +85,16 @@ fi
|
|||
|
||||
set -e
|
||||
|
||||
cat >/usr/local/etc/renderd.conf <<'EOF'
|
||||
[renderd]
|
||||
num_threads=4
|
||||
tile_dir=/var/lib/mod_tile
|
||||
stats_file=/var/run/renderd/renderd.stats
|
||||
|
||||
[mapnik]
|
||||
plugins_dir=/usr/lib/mapnik/3.0/input
|
||||
font_dir=/usr/share/fonts/truetype
|
||||
font_dir_recurse=1
|
||||
|
||||
[ajt]
|
||||
URI=/hot/
|
||||
TILEDIR=/var/lib/mod_tile
|
||||
XML=/opt/openstreetmap-carto/mapnik.xml
|
||||
HOST=localhost
|
||||
TILESIZE=256
|
||||
MAXZOOM=20
|
||||
EOF
|
||||
|
||||
cp /opt/wrolpi/etc/ubuntu20.04/rendred.conf /usr/local/etc/renderd.conf
|
||||
# Enable mod_tile.
|
||||
cat >>/etc/apache2/conf-available/mod_tile.conf <<'EOF'
|
||||
LoadModule tile_module /usr/lib/apache2/modules/mod_tile.so
|
||||
EOF
|
||||
cp /opt/wrolpi/etc/ubuntu20.04/mod_tile.conf /etc/apache2/conf-available/mod_tile.conf
|
||||
|
||||
/usr/sbin/a2enconf mod_tile
|
||||
|
||||
# Configure Apache2 to listen on 8084.
|
||||
cat >/etc/apache2/ports.conf <<'EOF'
|
||||
# If you just change the port or add more ports here, you will likely also
|
||||
# have to change the VirtualHost statement in
|
||||
# /etc/apache2/sites-enabled/000-default.conf
|
||||
|
||||
Listen 8084
|
||||
|
||||
<IfModule ssl_module>
|
||||
Listen 443
|
||||
</IfModule>
|
||||
|
||||
<IfModule mod_gnutls.c>
|
||||
Listen 443
|
||||
</IfModule>
|
||||
|
||||
# vim: syntax=apache ts=4 sw=4 sts=4 sr noet
|
||||
EOF
|
||||
|
||||
cat >/etc/apache2/sites-available/000-default.conf <<'EOF'
|
||||
<VirtualHost *:8084>
|
||||
# The ServerName directive sets the request scheme, hostname and port that
|
||||
# the server uses to identify itself. This is used when creating
|
||||
# redirection URLs. In the context of virtual hosts, the ServerName
|
||||
# specifies what hostname must appear in the request's Host: header to
|
||||
# match this virtual host. For the default virtual host (this file) this
|
||||
# value is not decisive as it is used as a last resort host regardless.
|
||||
# However, you must set it for any further virtual host explicitly.
|
||||
#ServerName www.example.com
|
||||
|
||||
ServerAdmin webmaster@localhost
|
||||
|
||||
LoadTileConfigFile /usr/local/etc/renderd.conf
|
||||
ModTileRenderdSocketName /var/run/renderd/renderd.sock
|
||||
# Timeout before giving up for a tile to be rendered
|
||||
ModTileRequestTimeout 0
|
||||
# Timeout before giving up for a tile to be rendered that is otherwise missing
|
||||
ModTileMissingRequestTimeout 30
|
||||
|
||||
DocumentRoot /var/www/html
|
||||
|
||||
# Available loglevels: trace8, ..., trace1, debug, info, notice, warn,
|
||||
# error, crit, alert, emerg.
|
||||
# It is also possible to configure the loglevel for particular
|
||||
# modules, e.g.
|
||||
#LogLevel info ssl:warn
|
||||
|
||||
ErrorLog ${APACHE_LOG_DIR}/error.log
|
||||
CustomLog ${APACHE_LOG_DIR}/access.log combined
|
||||
|
||||
# For most configuration files from conf-available/, which are
|
||||
# enabled or disabled at a global level, it is possible to
|
||||
# include a line for only one particular virtual host. For example the
|
||||
# following line enables the CGI configuration for this host only
|
||||
# after it has been globally disabled with "a2disconf".
|
||||
#Include conf-available/serve-cgi-bin.conf
|
||||
</VirtualHost>
|
||||
|
||||
# vim: syntax=apache ts=4 sw=4 sts=4 sr noet
|
||||
EOF
|
||||
|
||||
cat >/var/www/html/index.html <<'EOF'
|
||||
<!DOCTYPE HTML>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="utf-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<script src="/leaflet.js"></script>
|
||||
<link rel="stylesheet" href="/leaflet.css" />
|
||||
<style>
|
||||
html, body {
|
||||
height: 100%;
|
||||
padding: 0;
|
||||
margin: 0;
|
||||
}
|
||||
#map {
|
||||
/* configure the size of the map */
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
}
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<div id="map"></div>
|
||||
<script>
|
||||
// initialize Leaflet
|
||||
var map = L.map('map').setView({lon: 0, lat: 0}, 2);
|
||||
|
||||
// add the OpenStreetMap tiles
|
||||
L.tileLayer(`http://${window.location.hostname}:8084/hot/{z}/{x}/{y}.png`, {
|
||||
maxZoom: 19,
|
||||
attribution: '© <a href="https://openstreetmap.org/copyright">OpenStreetMap contributors</a>'
|
||||
}).addTo(map);
|
||||
|
||||
// show the scale bar on the lower left corner
|
||||
L.control.scale({imperial: true, metric: true}).addTo(map);
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
EOF
|
||||
|
||||
cp /opt/wrolpi/etc/ubuntu20.04/ports.conf /etc/apache2/ports.conf
|
||||
cp /opt/wrolpi/etc/ubuntu20.04/000-default.conf /etc/apache2/sites-available/000-default.conf
|
||||
cp /opt/wrolpi/etc/ubuntu20.04/index.html /var/www/html/index.html
|
||||
# Copy Leaflet files to Apache's directory so they can be used offline.
|
||||
cp /opt/wrolpi/modules/map/leaflet.js /var/www/html/leaflet.js
|
||||
cp /opt/wrolpi/modules/map/leaflet.css /var/www/html/leaflet.css
|
||||
|
|
@ -1,10 +1,9 @@
|
|||
#!/bin/bash
|
||||
echo "Ubuntu 20.04 install start: $(date '+%Y-%m-%d %H:%M:%S')"
|
||||
|
||||
set -x
|
||||
set -e
|
||||
|
||||
echo "Ubuntu 20.04 install start: $(date '+%Y-%m-%d %H:%M:%S')"
|
||||
|
||||
# Install npm repos.
|
||||
curl -fsSL https://deb.nodesource.com/setup_14.x | bash -
|
||||
# Update if we haven't updated in the last day.
|
||||
|
|
@ -16,7 +15,7 @@ apt install -y apt-transport-https ca-certificates curl gnupg-agent gcc libpq-de
|
|||
cpufrequtils network-manager
|
||||
|
||||
# Install Archiving tools.
|
||||
npm install -g "gildas-lormeau/SingleFile#master"
|
||||
npm install -g 'git+https://github.com/gildas-lormeau/SingleFile'
|
||||
npm install -g 'git+https://github.com/pirate/readability-extractor'
|
||||
|
||||
# Setup the virtual environment that main.py expects
|
||||
|
|
@ -57,9 +56,9 @@ visudo -c -f /etc/sudoers.d/90-wrolpi
|
|||
chown wrolpi:wrolpi /media/wrolpi
|
||||
|
||||
# Install the systemd services
|
||||
cp /opt/wrolpi/systemd/wrolpi-api.service /etc/systemd/system/
|
||||
cp /opt/wrolpi/systemd/wrolpi-app.service /etc/systemd/system/
|
||||
cp /opt/wrolpi/systemd/wrolpi.target /etc/systemd/system/
|
||||
cp /opt/wrolpi/etc/ubuntu20.04/wrolpi-api.service /etc/systemd/system/
|
||||
cp /opt/wrolpi/etc/ubuntu20.04/wrolpi-app.service /etc/systemd/system/
|
||||
cp /opt/wrolpi/etc/ubuntu20.04/wrolpi.target /etc/systemd/system/
|
||||
/usr/bin/systemctl daemon-reload
|
||||
systemctl enable wrolpi-api.service
|
||||
systemctl enable wrolpi-app.service
|
||||
|
|
@ -78,7 +77,7 @@ sudo -u postgres psql -c '\l' | grep wrolpi || (
|
|||
(cd /opt/wrolpi && /usr/bin/python3 /opt/wrolpi/main.py db upgrade)
|
||||
|
||||
# Run the map installation script.
|
||||
/opt/wrolpi/scripts/ubuntu_20.04_install_map.sh
|
||||
/opt/wrolpi/scripts/install_map_ubuntu_20.04.sh
|
||||
|
||||
set +x
|
||||
|
||||
|
|
@ -1,28 +1,16 @@
|
|||
import enum
|
||||
import pathlib
|
||||
import subprocess
|
||||
|
||||
from wrolpi.cmd import which
|
||||
from wrolpi.common import logger
|
||||
from wrolpi.vars import PYTEST, DEFAULT_CPU_FREQUENCY, DOCKERIZED
|
||||
from wrolpi.vars import DEFAULT_CPU_FREQUENCY, DOCKERIZED
|
||||
|
||||
logger = logger.getChild(__name__)
|
||||
|
||||
# Location on an RPi
|
||||
SUDO_BIN = pathlib.Path('/usr/bin/sudo')
|
||||
if not SUDO_BIN.is_file() and not PYTEST and not DOCKERIZED:
|
||||
logger.error('COULD NOT FIND sudo!!!')
|
||||
|
||||
NMCLI_BIN = pathlib.Path('/usr/bin/nmcli')
|
||||
if not NMCLI_BIN.is_file() and not PYTEST and not DOCKERIZED:
|
||||
logger.error('COULD NOT FIND nmcli!!!')
|
||||
|
||||
CPUFREQ_INFO_BIN = pathlib.Path('/usr/bin/cpufreq-info')
|
||||
if not CPUFREQ_INFO_BIN.is_file() and not PYTEST and not DOCKERIZED:
|
||||
logger.error('COULD NOT FIND cpufreq-info!!!')
|
||||
|
||||
CPUFREQ_SET_BIN = pathlib.Path('/usr/bin/cpufreq-set')
|
||||
if not CPUFREQ_SET_BIN.is_file() and not PYTEST and not DOCKERIZED:
|
||||
logger.error('COULD NOT FIND cpufreq-set!!!')
|
||||
SUDO = which('sudo', '/usr/bin/sudo')
|
||||
NMCLI = which('nmcli', '/usr/bin/nmcli')
|
||||
CPUFREQ_INFO = which('cpufreq-info', '/usr/bin/cpufreq-info')
|
||||
CPUFREQ_SET = which('cpufreq-set', '/usr/bin/cpufreq-set')
|
||||
|
||||
POWER_SAVE_FREQ = 'powersave' # noqa
|
||||
|
||||
|
|
@ -35,7 +23,7 @@ class HotspotStatus(enum.Enum):
|
|||
|
||||
|
||||
def hotspot_status() -> HotspotStatus:
|
||||
cmd = (NMCLI_BIN,)
|
||||
cmd = (NMCLI,)
|
||||
try:
|
||||
output = subprocess.check_output(cmd).decode().strip()
|
||||
except FileNotFoundError as e:
|
||||
|
|
@ -67,13 +55,13 @@ def enable_hotspot():
|
|||
return enable_hotspot()
|
||||
elif status == HotspotStatus.disconnected:
|
||||
# Radio is on, but not connected. Good, turn it into a hotspot.
|
||||
cmd = (SUDO_BIN, NMCLI_BIN, 'device', 'wifi', 'hotspot', 'ifname', 'wlan0',
|
||||
cmd = (SUDO, NMCLI, 'device', 'wifi', 'hotspot', 'ifname', 'wlan0',
|
||||
'ssid', 'WROLPi', 'password', 'wrolpi hotspot')
|
||||
subprocess.check_call(cmd)
|
||||
return True
|
||||
elif status == HotspotStatus.unavailable:
|
||||
# Radio is not on, turn it on.
|
||||
cmd = (SUDO_BIN, NMCLI_BIN, 'radio', 'wifi', 'on')
|
||||
cmd = (SUDO, NMCLI, 'radio', 'wifi', 'on')
|
||||
subprocess.check_call(cmd)
|
||||
return enable_hotspot()
|
||||
elif status == HotspotStatus.unknown:
|
||||
|
|
@ -82,7 +70,7 @@ def enable_hotspot():
|
|||
|
||||
def disable_hotspot():
|
||||
"""Turn off the wlan0 interface."""
|
||||
cmd = (SUDO_BIN, NMCLI_BIN, 'radio', 'wifi', 'off')
|
||||
cmd = (SUDO, NMCLI, 'radio', 'wifi', 'off')
|
||||
try:
|
||||
subprocess.check_call(cmd)
|
||||
return True
|
||||
|
|
@ -109,7 +97,7 @@ GOVERNOR_MAP = {
|
|||
|
||||
|
||||
def throttle_status() -> GovernorStatus:
|
||||
cmd = (CPUFREQ_INFO_BIN,)
|
||||
cmd = (CPUFREQ_INFO,)
|
||||
try:
|
||||
output = subprocess.check_output(cmd)
|
||||
except FileNotFoundError as e:
|
||||
|
|
@ -129,7 +117,7 @@ def throttle_status() -> GovernorStatus:
|
|||
def throttle_cpu_on() -> bool:
|
||||
"""Call cpufreq-set to throttle CPU."""
|
||||
try:
|
||||
cmd = (SUDO_BIN, CPUFREQ_SET_BIN, '-g', POWER_SAVE_FREQ)
|
||||
cmd = (SUDO, CPUFREQ_SET, '-g', POWER_SAVE_FREQ)
|
||||
subprocess.check_call(cmd)
|
||||
return True
|
||||
except FileNotFoundError:
|
||||
|
|
@ -140,7 +128,7 @@ def throttle_cpu_on() -> bool:
|
|||
def throttle_cpu_off() -> bool:
|
||||
"""Call cpufreq-set to un-throttle CPU."""
|
||||
try:
|
||||
cmd = (SUDO_BIN, CPUFREQ_SET_BIN, '-g', DEFAULT_CPU_FREQUENCY)
|
||||
cmd = (SUDO, CPUFREQ_SET, '-g', DEFAULT_CPU_FREQUENCY)
|
||||
subprocess.check_call(cmd)
|
||||
return True
|
||||
except FileNotFoundError:
|
||||
|
|
|
|||
34
wrolpi/cmd.py
Normal file
34
wrolpi/cmd.py
Normal file
|
|
@ -0,0 +1,34 @@
|
|||
import os
|
||||
import shutil
|
||||
from pathlib import Path
|
||||
|
||||
from wrolpi.common import logger
|
||||
from wrolpi.vars import PYTEST, DOCKERIZED
|
||||
|
||||
logger = logger.getChild(__name__)
|
||||
|
||||
|
||||
def is_executable(path: Path) -> bool:
|
||||
"""Returns True if the file is executable."""
|
||||
return path.is_file() and os.access(path, os.X_OK)
|
||||
|
||||
|
||||
def which(*possible_paths: str, warn: bool = False) -> Path:
|
||||
"""
|
||||
Find an executable in the system $PATH. If the executable cannot be found in $PATH, then return the first
|
||||
executable found in possible_paths.
|
||||
|
||||
Returns None if no executable can be found.
|
||||
"""
|
||||
possible_paths = map(Path, possible_paths)
|
||||
for path in possible_paths:
|
||||
if is_executable(path):
|
||||
# `path` was an absolute file which is executable.
|
||||
return path.absolute()
|
||||
path = shutil.which(path)
|
||||
if path and (path := Path(path).absolute()) and is_executable(path):
|
||||
# `path` was a name or relative path.
|
||||
return path
|
||||
|
||||
if warn and not PYTEST and not DOCKERIZED:
|
||||
logger.warning(f'Cannot find executable {possible_paths[0]}')
|
||||
|
|
@ -19,7 +19,8 @@ def test_hotspot_status():
|
|||
def test_enable_hotspot_disconnected():
|
||||
"""Enable hotspot with wifi on."""
|
||||
with mock.patch('wrolpi.admin.hotspot_status') as mock_hotspot_status, \
|
||||
mock.patch('wrolpi.admin.subprocess') as mock_subprocess:
|
||||
mock.patch('wrolpi.admin.subprocess') as mock_subprocess, \
|
||||
mock.patch('wrolpi.admin.NMCLI', PosixPath('/usr/bin/nmcli')):
|
||||
mock_hotspot_status.return_value = HotspotStatus.disconnected
|
||||
mock_subprocess.check_output.return_value = 0
|
||||
assert admin.enable_hotspot() is True
|
||||
|
|
@ -31,7 +32,8 @@ def test_enable_hotspot_disconnected():
|
|||
def test_enable_hotspot_unavailable():
|
||||
"""Enable hotspot with wifi off."""
|
||||
with mock.patch('wrolpi.admin.hotspot_status') as mock_hotspot_status, \
|
||||
mock.patch('wrolpi.admin.subprocess') as mock_subprocess:
|
||||
mock.patch('wrolpi.admin.subprocess') as mock_subprocess, \
|
||||
mock.patch('wrolpi.admin.NMCLI', PosixPath('/usr/bin/nmcli')):
|
||||
mock_hotspot_status.side_effect = [HotspotStatus.unavailable, HotspotStatus.disconnected]
|
||||
mock_subprocess.check_output.return_value = 0
|
||||
assert admin.enable_hotspot() is True
|
||||
|
|
@ -46,7 +48,8 @@ def test_enable_hotspot_unavailable():
|
|||
def test_enable_hotspot_connected():
|
||||
"""Enable hotspot with the hotspot alaready enabled."""
|
||||
with mock.patch('wrolpi.admin.hotspot_status') as mock_hotspot_status, \
|
||||
mock.patch('wrolpi.admin.subprocess') as mock_subprocess:
|
||||
mock.patch('wrolpi.admin.subprocess') as mock_subprocess, \
|
||||
mock.patch('wrolpi.admin.NMCLI', PosixPath('/usr/bin/nmcli')):
|
||||
mock_hotspot_status.side_effect = [
|
||||
HotspotStatus.connected,
|
||||
HotspotStatus.unavailable,
|
||||
|
|
@ -64,7 +67,8 @@ def test_enable_hotspot_connected():
|
|||
|
||||
|
||||
def test_throttle_on():
|
||||
with mock.patch('wrolpi.admin.subprocess') as mock_subprocess:
|
||||
with mock.patch('wrolpi.admin.subprocess') as mock_subprocess, \
|
||||
mock.patch('wrolpi.admin.CPUFREQ_SET', PosixPath('/usr/bin/cpufreq-set')):
|
||||
assert admin.throttle_cpu_on()
|
||||
mock_subprocess.check_call.assert_called_once_with(
|
||||
(PosixPath('/usr/bin/sudo'), PosixPath('/usr/bin/cpufreq-set'), '-g', 'powersave')
|
||||
|
|
@ -72,7 +76,8 @@ def test_throttle_on():
|
|||
|
||||
|
||||
def test_throttle_off():
|
||||
with mock.patch('wrolpi.admin.subprocess') as mock_subprocess:
|
||||
with mock.patch('wrolpi.admin.subprocess') as mock_subprocess, \
|
||||
mock.patch('wrolpi.admin.CPUFREQ_SET', PosixPath('/usr/bin/cpufreq-set')):
|
||||
assert admin.throttle_cpu_off()
|
||||
mock_subprocess.check_call.assert_called_once_with(
|
||||
(PosixPath('/usr/bin/sudo'), PosixPath('/usr/bin/cpufreq-set'), '-g', 'ondemand')
|
||||
|
|
|
|||
29
wrolpi/test/test_cmd.py
Normal file
29
wrolpi/test/test_cmd.py
Normal file
|
|
@ -0,0 +1,29 @@
|
|||
import os
|
||||
from pathlib import Path
|
||||
|
||||
from wrolpi import cmd
|
||||
from wrolpi.test.common import skip_circleci
|
||||
|
||||
|
||||
def test_which(test_directory):
|
||||
# Default location in Debian Linux.
|
||||
assert cmd.which('ls') == Path('/usr/bin/ls')
|
||||
# This executable does not exist.
|
||||
assert cmd.which('asdf') is None
|
||||
# The alternative path does not exist either.
|
||||
assert cmd.which('asdf', 'asdf') is None
|
||||
# Directories are ignored.
|
||||
assert cmd.which('asdf', '/tmp') is None
|
||||
|
||||
# Create an executable.
|
||||
foo = test_directory / 'foo'
|
||||
foo.touch()
|
||||
assert cmd.which('asdf', str(foo)) is None
|
||||
os.chmod(foo, 0o777)
|
||||
assert cmd.which('asdf', str(foo)) == foo
|
||||
|
||||
|
||||
@skip_circleci
|
||||
def test_which_chromium():
|
||||
# Multiple names can be tried.
|
||||
assert cmd.which('chromium-browser', 'chromium') == Path('/usr/bin/chromium')
|
||||
|
|
@ -61,8 +61,10 @@ class TestRootAPI(TestAPI):
|
|||
assert json.loads(response.body) == {'valid': False, 'regex': '.*(missing parenthesis.*'}
|
||||
|
||||
def test_get_settings(self):
|
||||
request, response = api_app.test_client.get('/api/settings')
|
||||
self.assertOK(response)
|
||||
with mock.patch('wrolpi.admin.CPUFREQ_INFO', '/usr/bin/cpufreq-info'), \
|
||||
mock.patch('wrolpi.admin.NMCLI', '/usr/bin/nmcli'):
|
||||
request, response = api_app.test_client.get('/api/settings')
|
||||
self.assertOK(response)
|
||||
|
||||
@wrap_test_db
|
||||
def test_get_downloads(self):
|
||||
|
|
|
|||
|
|
@ -1,4 +1,4 @@
|
|||
__version__ = '0.4.0-beta'
|
||||
__version__ = '0.4.1-beta'
|
||||
|
||||
import subprocess
|
||||
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue