Initial public release of ShellGleam
This commit is contained in:
29 files changed
+3140
No files matched your search
@@ -0,0 +1 @@
|
||||
* text=auto eol=lf
|
||||
@@ -0,0 +1,22 @@
|
||||
---
|
||||
name: Bug report
|
||||
about: Report unexpected dashboard or installer behavior
|
||||
title: ''
|
||||
labels: bug
|
||||
assignees: ''
|
||||
---
|
||||
|
||||
**What happened?**
|
||||
|
||||
**What did you expect?**
|
||||
|
||||
**Steps to reproduce**
|
||||
|
||||
**Environment**
|
||||
- Distribution/version:
|
||||
- Python version:
|
||||
- Shell/terminal:
|
||||
- ShellGleam version:
|
||||
|
||||
**Sanitized output**
|
||||
Remove real hostnames, IPs, usernames, container names and credentials before posting.
|
||||
@@ -0,0 +1,6 @@
|
||||
version: 2
|
||||
updates:
|
||||
- package-ecosystem: github-actions
|
||||
directory: /
|
||||
schedule:
|
||||
interval: monthly
|
||||
@@ -0,0 +1,23 @@
|
||||
name: CI
|
||||
on:
|
||||
push:
|
||||
branches: [main]
|
||||
pull_request:
|
||||
permissions:
|
||||
contents: read
|
||||
jobs:
|
||||
test:
|
||||
runs-on: ubuntu-latest
|
||||
strategy:
|
||||
matrix:
|
||||
python: ['3.9', '3.13']
|
||||
steps:
|
||||
- uses: actions/checkout@v7
|
||||
with:
|
||||
persist-credentials: false
|
||||
- uses: actions/setup-python@v7
|
||||
with:
|
||||
python-version: ${{ matrix.python }}
|
||||
- run: python -m unittest discover -s tests -v
|
||||
- run: bash -n scripts/bootstrap.sh deploy.sh && sh -n setup.sh
|
||||
- run: python scripts/build_site.py
|
||||
@@ -0,0 +1,41 @@
|
||||
name: Pages
|
||||
on:
|
||||
push:
|
||||
branches: [main]
|
||||
workflow_dispatch:
|
||||
permissions:
|
||||
contents: read
|
||||
concurrency:
|
||||
group: pages
|
||||
cancel-in-progress: false
|
||||
jobs:
|
||||
build:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v7
|
||||
with:
|
||||
persist-credentials: false
|
||||
- uses: actions/setup-python@v7
|
||||
with:
|
||||
python-version: '3.13'
|
||||
- run: python -m unittest discover -s tests -v
|
||||
- name: Build website and installer
|
||||
env:
|
||||
SITE_URL: https://${{ github.repository_owner }}.github.io/${{ github.event.repository.name }}
|
||||
run: python scripts/build_site.py --site-url "$SITE_URL"
|
||||
- uses: actions/upload-pages-artifact@v4
|
||||
with:
|
||||
path: _site
|
||||
deploy:
|
||||
needs: build
|
||||
runs-on: ubuntu-latest
|
||||
permissions:
|
||||
pages: write
|
||||
id-token: write
|
||||
environment:
|
||||
name: github-pages
|
||||
url: ${{ steps.deployment.outputs.page_url }}
|
||||
steps:
|
||||
- name: Deploy GitHub Pages
|
||||
id: deployment
|
||||
uses: actions/deploy-pages@v4
|
||||
+13
@@ -0,0 +1,13 @@
|
||||
__pycache__/
|
||||
*.py[cod]
|
||||
.idea/
|
||||
.vscode/
|
||||
.venv/
|
||||
_site/
|
||||
.env
|
||||
.env.*
|
||||
*.pem
|
||||
*.key
|
||||
*.tar.gz
|
||||
*.log
|
||||
.DS_Store
|
||||
@@ -0,0 +1,8 @@
|
||||
# Changelog
|
||||
|
||||
## 1.0.0
|
||||
|
||||
- Configurable system, runtime and health dashboard for Linux login sessions.
|
||||
- Independent per-login rendering with bounded probes and ASCII support.
|
||||
- Validated setup, original backups, exception rollback and uninstall.
|
||||
- Static documentation site and checksum-verified remote installer.
|
||||
@@ -0,0 +1,22 @@
|
||||
# Contributing
|
||||
|
||||
Small, focused pull requests are welcome. Explain the behavior being changed,
|
||||
include meaningful regression tests, and keep login fast and failure-tolerant.
|
||||
|
||||
Use Python 3.9+ and the standard library. Run:
|
||||
|
||||
```bash
|
||||
python3 -m unittest discover -s tests -v
|
||||
bash -n scripts/bootstrap.sh deploy.sh
|
||||
sh -n setup.sh
|
||||
python3 scripts/build_site.py
|
||||
```
|
||||
|
||||
Website source lives in `site/`; generated output belongs in `_site/` and is
|
||||
not committed. Please use fictional hostnames and addresses from documentation
|
||||
ranges in examples. Never submit credentials, live server output, private
|
||||
addresses or customer deployment notes. Review both source and built artifacts.
|
||||
|
||||
Installer tests operate in temporary filesystem roots. Test real SSH/PAM changes
|
||||
only on a disposable VM with a second recovery session. Preserve rollback,
|
||||
symlink metadata and concurrent-session behavior when changing installation.
|
||||
@@ -0,0 +1,21 @@
|
||||
MIT License
|
||||
|
||||
Copyright (c) 2026 ShellGleam contributors
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
@@ -0,0 +1,157 @@
|
||||
<div align="center">
|
||||
|
||||
# ✦ ShellGleam
|
||||
|
||||
**A brighter first look at your Linux server.**
|
||||
|
||||
A beautiful, configurable login dashboard for Ubuntu and Debian.
|
||||
System metrics, services, containers, and health checks — before your first command.
|
||||
|
||||
[Website & installer](https://meghdadfadaee.github.io/shell-gleam/) · [Configuration](docs/configuration.md) · [Operations](docs/operations.md) · [MIT license](LICENSE)
|
||||
|
||||
</div>
|
||||
|
||||
```text
|
||||
╭────────────────────────────────────────────────────────────────────────╮
|
||||
│ ◆ ORBIT ● HEALTHY │
|
||||
│ Ubuntu 24.04 LTS · 192.0.2.10 │
|
||||
├─ SYSTEM ───────────────────────────────────────────────────────────────┤
|
||||
│ │
|
||||
│ ↑ Uptime 12d 4h ≋ Load average 0.24 (8 cores) │
|
||||
│ Memory ████░░░░░░░░░░░░░░ 23% · 3.7 / 16.0 GiB │
|
||||
│ Disk / ██████░░░░░░░░░░░░ 34% · 68.0 / 200.0 GiB │
|
||||
│ │
|
||||
├─ RUNTIME ──────────────────────────────────────────────────────────────┤
|
||||
│ ● Nginx is online │
|
||||
│ ● Docker is online │
|
||||
│ 4 containers running · 4 healthchecked │
|
||||
├─ HEALTH ───────────────────────────────────────────────────────────────┤
|
||||
│ ✓ No failed systemd units │
|
||||
│ ✓ Packages current (cached) │
|
||||
│ ✓ No reboot needed │
|
||||
╰────────────────────────────────────────────────────────────────────────╯
|
||||
```
|
||||
|
||||
*Illustrative output. Hostnames, addresses and metrics above are fictional.*
|
||||
|
||||
## Install in one command
|
||||
|
||||
```bash
|
||||
curl -fsSL https://meghdadfadaee.github.io/shell-gleam/setup.sh | bash
|
||||
```
|
||||
|
||||
The bootstrap downloads a versioned package, verifies its embedded SHA-256,
|
||||
and requests `sudo` if needed. It retains setup at `/opt/shell-gleam`.
|
||||
|
||||
Pass options after `bash -s --`:
|
||||
|
||||
```bash
|
||||
curl -fsSL https://meghdadfadaee.github.io/shell-gleam/setup.sh | bash -s -- install --title ORBIT
|
||||
curl -fsSL https://meghdadfadaee.github.io/shell-gleam/setup.sh | bash -s -- install --wizard
|
||||
curl -fsSL https://meghdadfadaee.github.io/shell-gleam/setup.sh | bash -s -- install --dry-run
|
||||
```
|
||||
|
||||
Prefer to inspect first? Download the generated script, read it, then execute:
|
||||
|
||||
```bash
|
||||
curl -fsSLo shell-gleam-setup.sh https://meghdadfadaee.github.io/shell-gleam/setup.sh
|
||||
less shell-gleam-setup.sh
|
||||
bash shell-gleam-setup.sh install --wizard
|
||||
```
|
||||
|
||||
For automation, enable `set -o pipefail` in your calling Bash shell to propagate
|
||||
curl failures through the pipeline. The checksum detects payload corruption or a
|
||||
script/package mismatch; it is not an independent signature of the publisher.
|
||||
|
||||
## What you get
|
||||
|
||||
- **A useful first glance:** uptime, CPU load, memory and disk bars.
|
||||
- **Runtime visibility:** configurable systemd services and local Docker state.
|
||||
- **Honest health checks:** failed units, cached update age, reboot and firmware notices.
|
||||
Containers without healthchecks are never described as healthy.
|
||||
- **All login users:** optional PAM session display, independent rendering for concurrent logins.
|
||||
- **Your style:** JSON configuration, Unicode or ASCII, colors, sections and thresholds.
|
||||
- **Reversible setup:** original backups, rollback on handled errors, uninstall and reinstall support.
|
||||
- **Small footprint:** Python's standard library; no network requests during login.
|
||||
|
||||
## Requirements
|
||||
|
||||
Ubuntu/Debian with Python **3.9+**, systemd, GNU `timeout`, Debian `run-parts`,
|
||||
OpenSSH server and the standard `pam_motd`/`pam_exec` modules. SSH must already use
|
||||
`UsePAM yes` and `PrintMotd no`. Both `/etc/pam.d/sshd` and `/etc/pam.d/login`
|
||||
must have the normal dynamic MOTD entry. Preflight checks reject unsupported
|
||||
setups before making system changes. Other distributions are not supported yet.
|
||||
The bootstrap also needs Bash and curl; it does not install packages.
|
||||
|
||||
## Install from source
|
||||
|
||||
```bash
|
||||
git clone https://github.com/meghdadfadaee/shell-gleam.git
|
||||
cd shell-gleam
|
||||
sudo ./setup.sh install --wizard
|
||||
```
|
||||
|
||||
Or copy this directory to the server. `./deploy.sh root@your-server` copies it
|
||||
to `/opt/shell-gleam` over SSH and installs it; set `SSH_CONFIG` if needed.
|
||||
|
||||
## Make it yours
|
||||
|
||||
```bash
|
||||
sudoedit /etc/server-status/config.json
|
||||
server-status --check
|
||||
sudo server-status --no-color
|
||||
```
|
||||
|
||||
The repository is named `shell-gleam`; the installed preview command and settings
|
||||
path remain `server-status`. Configuration changes apply on the next login.
|
||||
See [all options and examples](docs/configuration.md).
|
||||
|
||||
```json
|
||||
{
|
||||
"title": "ORBIT",
|
||||
"services": [{"unit": "nginx.service", "label": "Nginx", "required": true}],
|
||||
"disks": ["/", "/srv"],
|
||||
"docker": false,
|
||||
"disk_warning": 70,
|
||||
"disk_critical": 85,
|
||||
"footer": "Welcome aboard."
|
||||
}
|
||||
```
|
||||
|
||||
A supplied config overlays built-in defaults. Reinstalling without overrides
|
||||
preserves the server's existing config. Missing optional services are neutral;
|
||||
missing required services and unavailable probes raise ATTENTION.
|
||||
|
||||
## Undo
|
||||
|
||||
```bash
|
||||
sudo /opt/shell-gleam/setup.sh uninstall --dry-run
|
||||
sudo /opt/shell-gleam/setup.sh uninstall
|
||||
```
|
||||
|
||||
If installed from a checkout, run `sudo ./setup.sh uninstall` there instead.
|
||||
Backups remain root-only in `/var/lib/server-status`. Uninstall restores original
|
||||
PAM display entries, stock hooks and static/dynamic messages. [Details and limitations](docs/operations.md).
|
||||
|
||||
## Website and releases
|
||||
|
||||
The [website](https://meghdadfadaee.github.io/shell-gleam/) provides an interactive
|
||||
dashboard preview, command builder and remote installer. GitHub Actions tests
|
||||
changes and publishes the site and a checksum-verified setup package from `main`.
|
||||
|
||||
For release maintenance, custom domains and forks, see the
|
||||
[publishing guide](docs/publishing.md).
|
||||
|
||||
## Development
|
||||
|
||||
```bash
|
||||
python3 -m unittest discover -s tests -v
|
||||
python3 src/server_status.py --config config/default.json --no-color
|
||||
python3 scripts/build_site.py
|
||||
python3 -m http.server 8000 --directory _site
|
||||
```
|
||||
|
||||
Open `http://localhost:8000`. The site has no package manager, framework,
|
||||
external fonts, trackers or third-party runtime assets. See [CONTRIBUTING.md](CONTRIBUTING.md).
|
||||
|
||||
MIT licensed. Demo content uses fictional hostnames and documentation-only IP addresses.
|
||||
+13
@@ -0,0 +1,13 @@
|
||||
# Security
|
||||
|
||||
ShellGleam changes privileged login message-display configuration. Review the
|
||||
installer before running it. Its PAM entry is optional; authentication and
|
||||
authorization rules are not changed. Keep installed code and config root-owned.
|
||||
|
||||
Do not include credentials, live hostnames or sensitive logs in public issues.
|
||||
For a vulnerability, use GitHub's **Security → Report a vulnerability** if private
|
||||
reporting is enabled. Otherwise, open a minimal issue requesting a private
|
||||
reporting channel without publishing exploit details or secrets.
|
||||
|
||||
The bootstrap checksum detects corruption and script/package mismatch. It does
|
||||
not provide independent publisher authentication. No telemetry is collected.
|
||||
@@ -0,0 +1,23 @@
|
||||
{
|
||||
"title": "",
|
||||
"address": "auto",
|
||||
"width": 72,
|
||||
"color": true,
|
||||
"ascii": false,
|
||||
"sections": ["system", "runtime", "health"],
|
||||
"services": [
|
||||
{"unit": "nginx.service", "label": "Nginx", "required": false},
|
||||
{"unit": "docker.service", "label": "Docker", "required": false}
|
||||
],
|
||||
"disks": ["/"],
|
||||
"docker": true,
|
||||
"command_timeout": 1.0,
|
||||
"memory_warning": 75,
|
||||
"memory_critical": 90,
|
||||
"disk_warning": 75,
|
||||
"disk_critical": 90,
|
||||
"load_warning": 0.7,
|
||||
"load_critical": 1.0,
|
||||
"updates_max_age_hours": 48,
|
||||
"footer": ""
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
#!/usr/bin/env bash
|
||||
set -euo pipefail
|
||||
if [[ $# != 1 || $1 == -* ]]; then
|
||||
echo "Usage: [SSH_CONFIG=path] $0 root@server" >&2
|
||||
exit 2
|
||||
fi
|
||||
project_dir=$(CDPATH= cd -- "$(dirname -- "$0")" && pwd)
|
||||
ssh_args=()
|
||||
if [[ -n ${SSH_CONFIG:-} ]]; then
|
||||
ssh_args+=(-F "$SSH_CONFIG")
|
||||
fi
|
||||
tar -C "$project_dir" --exclude='__pycache__' -czf - setup.sh deploy.sh README.md src config tests docs reference |
|
||||
ssh "${ssh_args[@]}" "$1" 'mkdir -p /opt/shell-gleam && tar -xzf - -C /opt/shell-gleam && cd /opt/shell-gleam && ./setup.sh install'
|
||||
@@ -0,0 +1,54 @@
|
||||
# Configuration
|
||||
|
||||
Live file: `/etc/server-status/config.json`. Validate with `server-status --check`;
|
||||
preview with `sudo server-status --no-color`. Changes appear on the next login.
|
||||
|
||||
`config/default.json` lists every setting. For an alternate file use
|
||||
`sudo ./setup.sh install --config /absolute/path/config.json`. A supplied file
|
||||
overlays built-in defaults, rather than merging with existing settings. Unknown
|
||||
keys and invalid types are rejected before installation. `--wizard` prompts for
|
||||
a title, address, services and disks; remote wizard setup reads `/dev/tty`.
|
||||
|
||||
| Key | Default / accepted values |
|
||||
| --- | --- |
|
||||
| `title` | Empty: automatic uppercase short hostname |
|
||||
| `address` | `auto`: first IPv4 from `hostname -I`; override for multiple interfaces |
|
||||
| `width` | `72`; integer 52–120, interior columns |
|
||||
| `color` | `true`; manual previews honor `NO_COLOR` |
|
||||
| `ascii` | `false`; use plain ASCII borders, bars and symbols |
|
||||
| `sections` | `["system", "runtime", "health"]`; reorder or omit |
|
||||
| `services` | Nginx and Docker, optional; up to 16 `{unit,label,required}` objects |
|
||||
| `disks` | `["/"]`; 1–8 absolute filesystem paths |
|
||||
| `docker` | `true`; query the local Unix socket if CLI is installed |
|
||||
| `command_timeout` | `1.0`; 0.1–2 seconds per concurrent subprocess |
|
||||
| `memory_warning`, `memory_critical` | `75`, `90` percent |
|
||||
| `disk_warning`, `disk_critical` | `75`, `90` percent |
|
||||
| `load_warning`, `load_critical` | `0.7`, `1.0` load per CPU |
|
||||
| `updates_max_age_hours` | `48`; age limit for Ubuntu update-notifier data |
|
||||
| `footer` | Empty; optional message |
|
||||
|
||||
Resource thresholds, failed units, inactive installed services, required missing
|
||||
services, unknown/stale updates and unhealthy containers affect the summary.
|
||||
Checks still affect the summary when their display section is hidden.
|
||||
Missing optional services are neutral. A systemd active state is not an
|
||||
application readiness check; configure the actual unit for your workload.
|
||||
|
||||
Example database configuration:
|
||||
|
||||
```json
|
||||
{
|
||||
"title": "DATABASE",
|
||||
"services": [
|
||||
{"unit": "postgresql.service", "label": "PostgreSQL", "required": true},
|
||||
{"unit": "ssh.service", "label": "SSH", "required": true}
|
||||
],
|
||||
"disks": ["/", "/var/lib/postgresql"],
|
||||
"docker": false,
|
||||
"disk_warning": 70,
|
||||
"disk_critical": 85
|
||||
}
|
||||
```
|
||||
|
||||
The PostgreSQL umbrella service may be active when a cluster is down; select
|
||||
its specific cluster unit if needed. Settings and rendered container names are
|
||||
visible to login users. Do not place secrets in the configuration.
|
||||
@@ -0,0 +1,81 @@
|
||||
# Operations and implementation
|
||||
|
||||
## System-wide login
|
||||
|
||||
The installer writes a root-owned renderer at `/usr/local/bin/server-status`,
|
||||
JSON settings at `/etc/server-status/config.json` and a bounded shell wrapper at
|
||||
`/etc/update-motd.d/00-server-status`.
|
||||
|
||||
It replaces only the dynamic MOTD session-display entry in `/etc/pam.d/sshd`
|
||||
and `/etc/pam.d/login` with optional `pam_exec.so stdout type=open_session`.
|
||||
Every session receives independent output, avoiding the shared dynamic MOTD
|
||||
cache race during concurrent logins. Authentication and authorization rules and
|
||||
SSH daemon settings are unchanged. The second static MOTD entry remains intact;
|
||||
`/etc/motd` is emptied with its original content backed up. No daemon restart is
|
||||
needed. SSH's normal `Last login` line remains.
|
||||
|
||||
Standard executable MOTD scripts are renamed with `~server-status-disabled`.
|
||||
The installer checks `run-parts --lsbsysinit --test /etc/update-motd.d` to ensure
|
||||
only the managed hook remains selected. The tilde matters: ordinary run-parts
|
||||
and PAM's LSB mode accept different filenames. Renaming in place preserves
|
||||
relative symlinks and avoids changing a linked package-owned file's mode.
|
||||
|
||||
## Bounded probes
|
||||
|
||||
External probes run concurrently with configurable individual timeouts. The
|
||||
wrapper adds a six-second overall timeout and one-second kill grace period.
|
||||
It shows an unavailable notice on failure and returns success to PAM. Kernel
|
||||
uninterruptible I/O cannot be forcibly timed out by normal userspace tools.
|
||||
Python runs with `-I`, the command PATH is fixed, and text control characters
|
||||
are removed. Only root should be able to modify installed code and settings.
|
||||
|
||||
Login does not access the network, run apt, or install dependencies. Package
|
||||
updates come from Ubuntu's existing update-notifier cache; missing or old data
|
||||
is unknown/stale. `/run/reboot-required` is an OS hint, not an independent audit.
|
||||
Docker queries the local socket regardless of caller Docker context; containers
|
||||
without healthchecks are not labeled healthy. A manual preview runs with the
|
||||
caller's permissions and may show Docker unavailable without sudo.
|
||||
|
||||
## Backup, reinstall, uninstall
|
||||
|
||||
Original content, mode, ownership and symlink targets are recorded once per path
|
||||
in `/var/lib/server-status/manifest.json`; the directory is root-only. Each
|
||||
operation also snapshots its current touched files for exception rollback.
|
||||
`flock` serializes installation changes; replacement writes are atomic per file.
|
||||
|
||||
Reinstall preserves current settings unless overrides are supplied. It also
|
||||
disables new package MOTD hooks. After package upgrades, rerun setup if stock
|
||||
messages or PAM display entries reappear.
|
||||
|
||||
Uninstall restores pre-install content, including both PAM files, and retains
|
||||
backups. Save later manual edits you want to keep before uninstalling. File
|
||||
replacement and exception rollback are not a multi-file power-loss transaction.
|
||||
After SIGKILL or power loss, inspect the newest backup folder and manifest before
|
||||
proceeding. VM snapshots provide a stronger recovery boundary.
|
||||
|
||||
## Troubleshooting
|
||||
|
||||
Check `server-status --check`, `sudo server-status`, `sudo sshd -T`, executable
|
||||
hook permissions and the two PAM session-display entries. User MOTD opt-outs,
|
||||
non-login shells, `su`/`sudo`, and SSH command/SFTP sessions do not necessarily
|
||||
show a login message. Noninteractive SSH command output should remain clean.
|
||||
|
||||
Extra messages may come from `/etc/motd.d`, `/run/motd.d`, `/usr/lib/motd.d`, user
|
||||
shell files or SSH `Banner`; those sources are not removed. Fixed-width Unicode
|
||||
output depends on your terminal font. Select ASCII mode and a smaller width for
|
||||
limited terminals.
|
||||
|
||||
## Remote bootstrap
|
||||
|
||||
GitHub Pages serves a generated Bash bootstrap and a versioned archive whose
|
||||
SHA-256 is embedded in that script. Download and verification happen before
|
||||
sudo and installation. The extractor rejects links, traversal paths and large
|
||||
unexpected archives. The package is built from an explicit file allowlist;
|
||||
local dotfiles, deployment notes, credentials and arbitrary files cannot enter
|
||||
it by a recursive copy. Checksums detect mismatches and corruption, not a
|
||||
compromised publisher. The website makes no requests to visitors' servers.
|
||||
|
||||
The verified source is retained in `/opt/shell-gleam` for future uninstall. Dry
|
||||
runs execute from the temporary package without copying it into `/opt`.
|
||||
Temporary downloads are removed on exit. For local integration tests only,
|
||||
`SHELL_GLEAM_BASE_URL=http://127.0.0.1:PORT` can point to a local build.
|
||||
@@ -0,0 +1,52 @@
|
||||
# Website and release maintenance
|
||||
|
||||
ShellGleam is maintained in
|
||||
[`meghdadfadaee/shell-gleam`](https://github.com/meghdadfadaee/shell-gleam).
|
||||
|
||||
- Website: `https://meghdadfadaee.github.io/shell-gleam/`
|
||||
- Bootstrap: `https://meghdadfadaee.github.io/shell-gleam/setup.sh`
|
||||
- License: MIT
|
||||
|
||||
## GitHub Pages
|
||||
|
||||
The **Pages** workflow tests the source, builds the static website and installer
|
||||
package, and deploys `_site` from `main`. Repository Settings → Pages must use
|
||||
**GitHub Actions** as the source. Run the workflow manually to redeploy the
|
||||
current version without a source change.
|
||||
|
||||
Only the built `_site` directory is published. Do not enable branch publishing
|
||||
from the repository root, where `setup.sh` is the local source installer.
|
||||
|
||||
## Build and inspect locally
|
||||
|
||||
```bash
|
||||
python3 -m unittest discover -s tests -v
|
||||
python3 scripts/build_site.py
|
||||
python3 -m http.server 8000 --directory _site
|
||||
```
|
||||
|
||||
The build creates a content-addressed payload, embedded-checksum bootstrap,
|
||||
`release.json` and a checksum list under `_site/downloads`. The payload uses an
|
||||
explicit source allowlist, normalized metadata and reproducible compression.
|
||||
Public demo data is fictional and uses documentation-only IP addresses.
|
||||
|
||||
No live server deployment records or captured production outputs belong in
|
||||
this repository. Sanitize screenshots and examples before committing them.
|
||||
Use a GitHub no-reply commit email to keep your personal email private.
|
||||
|
||||
## Releases
|
||||
|
||||
Update `VERSION` and `CHANGELOG.md`, run tests, and push to `main` to redeploy.
|
||||
Previously downloaded bootstrap scripts refer to their exact package; after a
|
||||
later site deployment replaces that package, fetch a fresh bootstrap. A missing
|
||||
old package fails safely rather than silently installing another version.
|
||||
|
||||
## Forks and custom domains
|
||||
|
||||
For another account or repository, update links in the README and `site/`.
|
||||
The workflow passes its own account/repository URL to `scripts/build_site.py`.
|
||||
For a custom domain, change the workflow's `SITE_URL` and the website's
|
||||
`BASE_URL` in `site/app.js` together.
|
||||
|
||||
The landing page has no external fonts, analytics, trackers or runtime assets.
|
||||
Its customization form only changes a local preview and generated command.
|
||||
Executable
+98
@@ -0,0 +1,98 @@
|
||||
#!/usr/bin/env bash
|
||||
# ShellGleam remote installer. Published by scripts/build_site.py.
|
||||
set -euo pipefail
|
||||
|
||||
main() {
|
||||
if [[ ${1:-} == --help || ${1:-} == -h ]]; then
|
||||
cat <<'HELP'
|
||||
ShellGleam — a brighter first look at your Linux server.
|
||||
Usage: curl -fsSL https://meghdadfadaee.github.io/shell-gleam/setup.sh | bash -s -- [options]
|
||||
|
||||
Setup options: install (default), uninstall, status, --dry-run, --wizard,
|
||||
--title NAME, --address IP, --config FILE, --no-color, --ascii
|
||||
Downloads and verifies a versioned package before requesting sudo.
|
||||
Persistent project: /opt/shell-gleam. Live config: /etc/server-status/config.json.
|
||||
HELP
|
||||
return
|
||||
fi
|
||||
local base_url=${SHELL_GLEAM_BASE_URL:-@@SITE_URL@@}
|
||||
local expected='@@SHA256@@'
|
||||
local artifact='@@ARCHIVE@@'
|
||||
local work_dir
|
||||
case "$base_url" in
|
||||
https://*) ;;
|
||||
http://127.0.0.1:*|http://localhost:*) ;;
|
||||
*) echo 'ShellGleam: download URL must use HTTPS (loopback HTTP is allowed for local testing).' >&2; return 1 ;;
|
||||
esac
|
||||
for dependency in curl python3 bash; do
|
||||
command -v "$dependency" >/dev/null || { echo "ShellGleam: install $dependency first." >&2; return 1; }
|
||||
done
|
||||
python3 -c 'import sys; sys.exit(0 if sys.version_info >= (3, 9) else "ShellGleam requires Python 3.9+")'
|
||||
work_dir=$(mktemp -d "${TMPDIR:-/tmp}/shell-gleam.XXXXXXXX")
|
||||
shell_gleam_temp_dir=$work_dir
|
||||
trap '[[ -z ${shell_gleam_temp_dir:-} ]] || rm -rf -- "$shell_gleam_temp_dir"' EXIT
|
||||
echo 'ShellGleam: downloading the verified setup package…'
|
||||
curl --fail --silent --show-error --location --retry 2 --connect-timeout 15 --max-time 120 \
|
||||
--proto '=https,http' --proto-redir '=https' "$base_url/$artifact" -o "$work_dir/package.tar.gz"
|
||||
python3 - "$work_dir/package.tar.gz" "$expected" "$work_dir" <<'PY'
|
||||
import hashlib
|
||||
from pathlib import Path, PurePosixPath
|
||||
import shutil
|
||||
import sys
|
||||
import tarfile
|
||||
archive, expected, directory = sys.argv[1:]
|
||||
if hashlib.sha256(Path(archive).read_bytes()).hexdigest() != expected:
|
||||
sys.exit('ShellGleam: checksum mismatch; nothing installed.')
|
||||
root = Path(directory)
|
||||
with tarfile.open(archive, 'r:gz') as package:
|
||||
members = package.getmembers()
|
||||
if len(members) > 1000 or sum(m.size for m in members) > 20 * 1024 * 1024:
|
||||
sys.exit('ShellGleam: unexpected package size.')
|
||||
for member in members:
|
||||
path = PurePosixPath(member.name)
|
||||
if (path.is_absolute() or '..' in path.parts or not path.parts
|
||||
or path.parts[0] != 'shell-gleam' or not (member.isfile() or member.isdir())):
|
||||
sys.exit('ShellGleam: unsafe package member; nothing installed.')
|
||||
for member in members:
|
||||
target = root / member.name
|
||||
if member.isdir():
|
||||
target.mkdir(parents=True, exist_ok=True)
|
||||
else:
|
||||
target.parent.mkdir(parents=True, exist_ok=True)
|
||||
with package.extractfile(member) as source, target.open('wb') as destination:
|
||||
shutil.copyfileobj(source, destination)
|
||||
target.chmod(0o755 if member.mode & 0o111 else 0o644)
|
||||
print('ShellGleam: SHA-256 verified.')
|
||||
PY
|
||||
local dry_run=false wizard=false
|
||||
for argument in "$@"; do
|
||||
[[ $argument != --dry-run && $argument != status ]] || dry_run=true
|
||||
[[ $argument != --wizard ]] || wizard=true
|
||||
done
|
||||
local -a elevation=()
|
||||
if [[ $(id -u) != 0 ]]; then
|
||||
command -v sudo >/dev/null || { echo 'ShellGleam: run as root or install sudo.' >&2; return 1; }
|
||||
elevation=(sudo)
|
||||
fi
|
||||
# Absolute --config paths remain valid after changing the project directory.
|
||||
# The argument array is forwarded unchanged; never evaluate user arguments.
|
||||
if $wizard && ! { : </dev/tty; } 2>/dev/null; then
|
||||
echo 'ShellGleam: --wizard requires an interactive terminal.' >&2
|
||||
return 1
|
||||
fi
|
||||
if $dry_run; then
|
||||
if $wizard; then
|
||||
"${elevation[@]}" bash "$work_dir/shell-gleam/setup.sh" "$@" </dev/tty
|
||||
else
|
||||
"${elevation[@]}" bash "$work_dir/shell-gleam/setup.sh" "$@"
|
||||
fi
|
||||
else
|
||||
local run='set -e; payload=$1; shift; mkdir -p /opt/shell-gleam; cp -R "$payload"/. /opt/shell-gleam/; exec bash /opt/shell-gleam/setup.sh "$@"'
|
||||
if $wizard; then
|
||||
"${elevation[@]}" bash -c "$run" shell-gleam "$work_dir/shell-gleam" "$@" </dev/tty
|
||||
else
|
||||
"${elevation[@]}" bash -c "$run" shell-gleam "$work_dir/shell-gleam" "$@"
|
||||
fi
|
||||
fi
|
||||
}
|
||||
main "$@"
|
||||
Executable
+64
@@ -0,0 +1,64 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Build a static Pages site and reproducible, allowlisted installer payload."""
|
||||
import argparse
|
||||
import gzip
|
||||
import hashlib
|
||||
import io
|
||||
import json
|
||||
from pathlib import Path
|
||||
import shutil
|
||||
import tarfile
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
PACKAGE_FILES = (
|
||||
'setup.sh', 'deploy.sh', 'README.md', 'LICENSE', 'VERSION',
|
||||
'src/server_status.py', 'src/install.py', 'config/default.json',
|
||||
'docs/configuration.md', 'docs/operations.md',
|
||||
)
|
||||
ASSETS = ('index.html', 'style.css', 'app.js', 'favicon.svg', 'social.svg')
|
||||
|
||||
|
||||
def build(output, site_url):
|
||||
output = Path(output).resolve()
|
||||
if output == ROOT or ROOT.is_relative_to(output):
|
||||
raise ValueError('output must not contain the source repository')
|
||||
output.mkdir(parents=True, exist_ok=True)
|
||||
for name in ASSETS:
|
||||
shutil.copyfile(ROOT / 'site' / name, output / name)
|
||||
(output / '.nojekyll').write_text('')
|
||||
buffer = io.BytesIO()
|
||||
with gzip.GzipFile(fileobj=buffer, mode='wb', filename='', mtime=0) as compressed:
|
||||
with tarfile.open(fileobj=compressed, mode='w') as package:
|
||||
for name in sorted(PACKAGE_FILES):
|
||||
source = ROOT / name
|
||||
if source.is_symlink():
|
||||
raise ValueError('payload cannot contain symlinks: ' + name)
|
||||
data = source.read_bytes()
|
||||
info = tarfile.TarInfo('shell-gleam/' + name)
|
||||
info.size = len(data)
|
||||
info.mode = 0o755 if name.endswith('.sh') else 0o644
|
||||
info.mtime = 0
|
||||
package.addfile(info, io.BytesIO(data))
|
||||
data = buffer.getvalue()
|
||||
digest = hashlib.sha256(data).hexdigest()
|
||||
artifact = 'downloads/shell-gleam-' + digest[:16] + '.tar.gz'
|
||||
(output / 'downloads').mkdir(exist_ok=True)
|
||||
(output / artifact).write_bytes(data)
|
||||
(output / 'downloads/SHA256SUMS').write_text(digest + ' ' + Path(artifact).name + '\n')
|
||||
template = (ROOT / 'scripts/bootstrap.sh').read_text()
|
||||
installer = template.replace('@@SHA256@@', digest).replace('@@ARCHIVE@@', artifact).replace('@@SITE_URL@@', site_url.rstrip('/'))
|
||||
(output / 'setup.sh').write_text(installer)
|
||||
(output / 'setup.sh').chmod(0o755)
|
||||
manifest = {'name': 'shell-gleam', 'version': (ROOT / 'VERSION').read_text().strip(),
|
||||
'archive': artifact, 'sha256': digest, 'files': list(PACKAGE_FILES)}
|
||||
(output / 'release.json').write_text(json.dumps(manifest, indent=2) + '\n')
|
||||
print('Built ShellGleam site: ' + str(output))
|
||||
return manifest
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument('--output', type=Path, default=ROOT / '_site')
|
||||
parser.add_argument('--site-url', default='https://meghdadfadaee.github.io/shell-gleam')
|
||||
args = parser.parse_args()
|
||||
build(args.output, args.site_url)
|
||||
@@ -0,0 +1,4 @@
|
||||
#!/bin/sh
|
||||
set -eu
|
||||
PROJECT_DIR=$(CDPATH= cd -- "$(dirname -- "$0")" && pwd)
|
||||
exec python3 "$PROJECT_DIR/src/install.py" "$@"
|
||||
+100
@@ -0,0 +1,100 @@
|
||||
'use strict';
|
||||
const BASE_URL = 'https://meghdadfadaee.github.io/shell-gleam';
|
||||
const form = document.querySelector('#config-form');
|
||||
const dashboard = document.querySelector('#dashboard');
|
||||
const commandNode = document.querySelector('#install-command');
|
||||
const statusNode = document.querySelector('#copy-status');
|
||||
let health = 'healthy';
|
||||
let wizard = false;
|
||||
|
||||
function quoteShell(value) {
|
||||
return "'" + value.replace(/'/g, "'\\''") + "'";
|
||||
}
|
||||
function commandFor({ title, ascii, color, wizard }) {
|
||||
let command = `curl -fsSL ${BASE_URL}/setup.sh | bash`;
|
||||
const args = [];
|
||||
if (title && title !== 'ORBIT') args.push('--title', quoteShell(title));
|
||||
if (ascii) args.push('--ascii');
|
||||
if (!color) args.push('--no-color');
|
||||
if (wizard) args.push('--wizard');
|
||||
if (args.length) command += ' -s -- install ' + args.join(' ');
|
||||
return command;
|
||||
}
|
||||
function render() {
|
||||
const title = (form.elements.title.value.trim() || 'ORBIT').replace(/[\u0000-\u001f\u007f]/g, '');
|
||||
const ascii = form.elements.ascii.checked;
|
||||
const color = form.elements.color.checked;
|
||||
const warning = health === 'attention';
|
||||
const width = 66;
|
||||
const horizontal = ascii ? '-' : '─';
|
||||
const vertical = ascii ? '|' : '│';
|
||||
const symbol = { diamond: ascii ? '*' : '◆', dot: ascii ? '*' : '●', tick: ascii ? '+' : '✓', warn: ascii ? '!' : '⚠', up: ascii ? '^' : '↑' };
|
||||
function add(text, className = '') {
|
||||
const node = document.createElement('span');
|
||||
if (color) node.className = className;
|
||||
node.textContent = text + '\n';
|
||||
dashboard.append(node);
|
||||
}
|
||||
function line(text = '', className = '') {
|
||||
const content = Array.from(text).slice(0, width - 2).join('');
|
||||
add(vertical + ' ' + content.padEnd(width - 2) + ' ' + vertical, className);
|
||||
}
|
||||
function divider(label) {
|
||||
const content = horizontal + ' ' + label + ' ';
|
||||
add((ascii ? '+' : '├') + content + horizontal.repeat(width - content.length) + (ascii ? '+' : '┤'), 'term-border');
|
||||
}
|
||||
const bar = (filled) => (ascii ? '#' : '█').repeat(filled) + (ascii ? '-' : '░').repeat(18 - filled);
|
||||
dashboard.replaceChildren();
|
||||
add((ascii ? '+' : '╭') + horizontal.repeat(width) + (ascii ? '+' : '╮'), 'term-border');
|
||||
const right = symbol.dot + ' ' + (warning ? 'ATTENTION' : 'HEALTHY');
|
||||
const left = symbol.diamond + ' ' + Array.from(title.toUpperCase()).slice(0, 32).join('');
|
||||
line(left + ' '.repeat(Math.max(2, width - 2 - Array.from(left).length - right.length)) + right, warning ? 'term-warning' : 'term-good');
|
||||
line(' Ubuntu 24.04 LTS / 192.0.2.10', 'term-dim');
|
||||
divider('SYSTEM'); line();
|
||||
line(` ${symbol.up} Uptime 12d 4h ${ascii ? '~' : '≋'} Load average 0.24 (8 cores)`, 'term-title');
|
||||
line(` Memory ${bar(4)} 23% / 3.7 / 16.0 GiB`, 'term-good');
|
||||
line(` Disk / ${bar(warning ? 16 : 6)} ${warning ? '91%' : '34%'} / ${warning ? '182' : '68'} / 200 GiB`, warning ? 'term-warning' : 'term-good'); line();
|
||||
divider('RUNTIME'); line();
|
||||
line(` ${symbol.dot} Nginx is online`, 'term-good');
|
||||
line(` ${symbol.dot} Docker is online`, 'term-good');
|
||||
line(warning ? ' 4 running / 1 unhealthy / 0 failed' : ' 4 containers running / 4 healthchecked', warning ? 'term-warning' : 'term-good'); line();
|
||||
divider('HEALTH'); line();
|
||||
line(warning ? ` ${symbol.warn} 1 unit failed / worker.service` : ` ${symbol.tick} No failed systemd units`, warning ? 'term-warning' : 'term-good');
|
||||
line(` ${symbol.tick} Packages current (cached)`, 'term-good');
|
||||
line(` ${symbol.tick} No reboot needed`, 'term-good'); line();
|
||||
add((ascii ? '+' : '╰') + horizontal.repeat(width) + (ascii ? '+' : '╯'), 'term-border');
|
||||
commandNode.textContent = commandFor({ title, ascii, color, wizard });
|
||||
statusNode.textContent = '';
|
||||
}
|
||||
form.addEventListener('input', render);
|
||||
form.addEventListener('submit', (event) => event.preventDefault());
|
||||
document.querySelectorAll('[data-state]').forEach(button => {
|
||||
button.addEventListener('click', () => {
|
||||
health = button.dataset.state;
|
||||
document.querySelectorAll('[data-state]').forEach(item => {
|
||||
const selected = item === button;
|
||||
item.classList.toggle('selected', selected);
|
||||
item.setAttribute('aria-pressed', String(selected));
|
||||
});
|
||||
render();
|
||||
});
|
||||
});
|
||||
document.querySelector('#wizard-toggle').addEventListener('click', event => {
|
||||
wizard = !wizard;
|
||||
event.currentTarget.setAttribute('aria-pressed', String(wizard));
|
||||
event.currentTarget.textContent = wizard ? 'Setup wizard included ✓' : 'Use the setup wizard →';
|
||||
render();
|
||||
});
|
||||
document.querySelector('#copy-command').addEventListener('click', async () => {
|
||||
try {
|
||||
await navigator.clipboard.writeText(commandNode.textContent);
|
||||
statusNode.textContent = 'Copied. Your next login is looking brighter.';
|
||||
} catch {
|
||||
const range = document.createRange();
|
||||
range.selectNodeContents(commandNode);
|
||||
const selection = window.getSelection();
|
||||
selection.removeAllRanges(); selection.addRange(range);
|
||||
statusNode.textContent = 'Command selected. Press Ctrl+C (or Cmd+C) to copy.';
|
||||
}
|
||||
});
|
||||
render();
|
||||
@@ -0,0 +1 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 64 64"><rect width="64" height="64" rx="14" fill="#f5f3eb"/><g stroke="#d85531" stroke-width="7" stroke-linecap="round"><path d="M32 11v42M11 32h42M17 17l30 30M17 47l30-30"/></g></svg>
|
||||
|
After Width: | Height: | Size: 238 B |
@@ -0,0 +1,75 @@
|
||||
<!doctype html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||
<meta name="theme-color" content="#f5f3eb">
|
||||
<meta name="description" content="A brighter first look at your Linux server. ShellGleam turns SSH login into a beautiful, configurable dashboard. Open source, small footprint, reversible setup.">
|
||||
<meta property="og:title" content="ShellGleam — before your first command">
|
||||
<meta property="og:description" content="A beautiful little dashboard. A much better hello. Meet your server at a glance.">
|
||||
<meta property="og:type" content="website">
|
||||
<meta property="og:image" content="https://meghdadfadaee.github.io/shell-gleam/social.svg">
|
||||
<meta name="color-scheme" content="light">
|
||||
<title>ShellGleam — a brighter first look</title>
|
||||
<link rel="icon" href="favicon.svg" type="image/svg+xml">
|
||||
<link rel="stylesheet" href="style.css">
|
||||
<script src="app.js" defer></script>
|
||||
</head>
|
||||
<body>
|
||||
<a class="skip" href="#main">Skip to content</a>
|
||||
<header class="site-header wrap">
|
||||
<a class="brand" href="#" aria-label="ShellGleam home"><span class="brand-mark" aria-hidden="true"><svg viewBox="0 0 64 64" fill="none" aria-hidden="true"><path d="M32 6v52M6 32h52M14 14l36 36M14 50l36-36" stroke="currentColor" stroke-width="7" stroke-linecap="round"/></svg></span>ShellGleam<span class="brand-dot">.</span></a>
|
||||
<nav aria-label="Main navigation"><a href="#preview">The dashboard</a><a href="#configure">Make it yours</a><a class="nav-github" href="https://github.com/meghdadfadaee/shell-gleam">GitHub <span aria-hidden="true">↗</span></a></nav>
|
||||
</header>
|
||||
<main id="main">
|
||||
<section class="hero wrap" aria-labelledby="hero-title">
|
||||
<div class="hero-copy">
|
||||
<p class="eyebrow"><span class="live-dot"></span> A SMALL UPGRADE TO YOUR EVERYDAY SSH</p>
|
||||
<h1 id="hero-title">A better hello<br>from your<br><em>server.</em><span class="hero-spark" aria-hidden="true"><svg viewBox="0 0 64 64" fill="none" aria-hidden="true"><path d="M32 6v52M6 32h52M14 14l36 36M14 50l36-36" stroke="currentColor" stroke-width="7" stroke-linecap="round"/></svg></span></h1>
|
||||
<p class="hero-description">All the signs of life, right when you log in.<br>A beautiful little dashboard. A much better first glance.</p>
|
||||
<div class="hero-actions"><a class="button button-dark" href="#install">Give your shell a gleam <span aria-hidden="true">↗</span></a><a class="text-link" href="#preview">Take a look <span aria-hidden="true">↓</span></a></div>
|
||||
<p class="hero-meta">OPEN SOURCE <span> / </span> PYTHON STDLIB <span> / </span> MADE FOR LINUX</p>
|
||||
</div>
|
||||
<div class="hero-visual" id="preview">
|
||||
<div class="visual-label"><span>01 / YOUR NEXT LOGIN</span><span>LIVE PREVIEW <i class="live-dot"></i></span></div>
|
||||
<div class="terminal">
|
||||
<div class="terminal-chrome"><span class="traffic" aria-hidden="true"><i></i><i></i><i></i></span><span>orbit — ssh</span><span aria-hidden="true">⌘</span></div>
|
||||
<div class="terminal-body"><p class="terminal-command"><span>~ ❯</span> ssh orbit</p><pre id="dashboard" aria-label="Illustrative server login dashboard"></pre><p class="terminal-prompt"><span>orbit:~$</span> <i class="cursor" aria-hidden="true"></i></p></div>
|
||||
<div class="terminal-footer"><span><i class="live-dot"></i> READY BEFORE YOU ARE</span><span>NO LOGIN NETWORK REQUESTS</span></div>
|
||||
</div>
|
||||
<div class="preview-controls"><div class="segmented" role="group" aria-label="Preview health state"><button type="button" class="selected" data-state="healthy" aria-pressed="true">All good</button><button type="button" data-state="attention" aria-pressed="false">Needs a look</button></div><span>Demo data. Real possibility.</span></div>
|
||||
<div class="hand-note" aria-hidden="true">your server, at a glance <span>↖</span></div>
|
||||
<noscript><p>This interactive preview needs JavaScript. The installer and documentation work without it.</p></noscript>
|
||||
</div>
|
||||
</section>
|
||||
<div class="spec-strip"><div class="wrap spec-inner"><span><b>01</b> Install once</span><span><b>02</b> Every login user</span><span><b>03</b> Your rules, your look</span><span><b>04</b> Undo anytime</span></div></div>
|
||||
<section class="intro wrap" aria-labelledby="intro-title">
|
||||
<div><p class="eyebrow">LESS DIGGING. MORE KNOWING.</p><h2 id="intro-title">The first ten commands,<br><em>in one first glance.</em></h2></div>
|
||||
<p>Uptime. Memory. That container acting up.<br>ShellGleam brings the useful bits together, so you can spend less time checking in and more time getting on with it.</p>
|
||||
</section>
|
||||
<section class="features wrap" aria-label="Dashboard features">
|
||||
<article><span class="feature-number">01 / SYSTEM</span><div class="feature-graphic metric-graphic" aria-hidden="true"><span>MEMORY <strong>23%</strong></span><div><i></i></div><span>LOAD <strong>0.24 / 8</strong></span></div><h3>A pulse, not a puzzle.</h3><p>Uptime, CPU load, memory and disks. Clear bars and adjustable thresholds tell you where things stand.</p></article>
|
||||
<article><span class="feature-number">02 / RUNTIME</span><div class="feature-graphic runtime-graphic" aria-hidden="true"><span><i class="live-dot"></i> nginx <small>online</small></span><span><i class="live-dot"></i> docker <small>4 running</small></span></div><h3>Know what’s running.</h3><p>Pick the systemd services you care about. See local Docker state and actual healthcheck results.</p></article>
|
||||
<article><span class="feature-number">03 / HEALTH</span><div class="feature-graphic health-graphic" aria-hidden="true"><span class="health-icon">✓</span><span>Nothing to chase.<small>NO REBOOT NEEDED</small></span></div><h3>A little peace of mind.</h3><p>Failed units, cached package updates and reboot notices. Unknown data stays unknown. No false confidence.</p></article>
|
||||
</section>
|
||||
<section class="config-section" id="configure" aria-labelledby="config-title"><div class="wrap config-layout">
|
||||
<div class="config-copy"><p class="eyebrow">FEELS LIKE YOUR PLACE</p><h2 id="config-title">Your server.<br><em>Your kind of hello.</em></h2><p>A name, a few preferences, and you’re home.<br>Make it yours here, then copy your install command.</p><a class="text-link" href="https://github.com/meghdadfadaee/shell-gleam/blob/main/docs/configuration.md">Explore every JSON setting <span aria-hidden="true">↗</span></a><div class="config-footnote"><span aria-hidden="true">↳</span> Preview only. Nothing here connects to your server.</div></div>
|
||||
<form class="config-card" id="config-form">
|
||||
<div class="card-caption"><span>YOUR SHELLGLEAM RECIPE</span><span aria-hidden="true">✳︎</span></div>
|
||||
<label for="server-name">Call your server something nice</label><input id="server-name" name="title" value="ORBIT" placeholder="ORBIT" maxlength="40" autocomplete="off" spellcheck="false">
|
||||
<fieldset><legend>The small details</legend><label class="switch-row" for="ascii-mode"><span>Keep it classic<small>ASCII symbols for simpler terminals</small></span><input id="ascii-mode" type="checkbox" name="ascii"><span class="switch" aria-hidden="true"></span></label><label class="switch-row" for="color-mode"><span>A little color<small>Make the important things stand out</small></span><input id="color-mode" type="checkbox" name="color" checked><span class="switch" aria-hidden="true"></span></label></fieldset>
|
||||
<div class="config-tip"><span aria-hidden="true">↳</span> Services, disks and thresholds? The setup wizard has you covered.</div>
|
||||
</form>
|
||||
</div></section>
|
||||
<section class="install-section wrap" id="install" aria-labelledby="install-title">
|
||||
<div class="install-heading"><div><p class="eyebrow">FROM BLANK TO BRIGHT</p><h2 id="install-title">One line.<br><em>A better login.</em></h2></div><p>Ubuntu or Debian. Python 3.9+. Bash and curl.<br>The installer asks for sudo when it needs it.</p></div>
|
||||
<div class="install-box"><div class="install-box-top"><span><span class="tiny-square"></span> RUN ON YOUR SERVER</span><button type="button" class="copy-button" id="copy-command">Copy command <span aria-hidden="true">↗</span></button></div><pre><code id="install-command">curl -fsSL https://meghdadfadaee.github.io/shell-gleam/setup.sh | bash</code></pre><div class="install-box-bottom"><span>SHA-256 verified package <span aria-hidden="true">·</span> No login network requests</span><a href="setup.sh">Read the installer ↗</a></div></div>
|
||||
<p id="copy-status" class="copy-status" role="status" aria-live="polite"></p>
|
||||
<div class="install-details"><div><span class="detail-icon" aria-hidden="true">↗</span><h3>Want a guided setup?</h3><p>Add <code>--wizard</code> to choose a name, services and disks in your terminal.</p><button type="button" class="text-link" id="wizard-toggle" aria-pressed="false">Use the setup wizard <span aria-hidden="true">→</span></button></div><div><span class="detail-icon" aria-hidden="true">↶</span><h3>Easy come. Easy go.</h3><p>Original login files are backed up. Restore them with one command.</p><code class="undo-code">sudo /opt/shell-gleam/setup.sh uninstall</code></div></div>
|
||||
<details class="requirements"><summary>The details before you install <span aria-hidden="true">+</span></summary><div><p>Supports Ubuntu/Debian with systemd, Python 3.9+, GNU timeout, Debian run-parts, OpenSSH and standard PAM MOTD/exec modules. Setup checks compatibility before making changes. Docker is optional.</p><p>Installation replaces two PAM message-display entries, backs up the originals, and leaves authentication rules and SSH daemon settings unchanged. Additional MOTD snippets may still appear. Checksum verification detects corruption and package mismatch; it is not an independent publisher signature.</p><p>Prefer to read before running? Download <a href="setup.sh">setup.sh</a> and inspect it. For scripted pipelines, enable <code>set -o pipefail</code> to catch curl failures. <a href="https://github.com/meghdadfadaee/shell-gleam/blob/main/docs/operations.md">Read the operations guide ↗</a></p></div></details>
|
||||
</section>
|
||||
<section class="closing wrap"><span class="closing-mark" aria-hidden="true"><svg viewBox="0 0 64 64" fill="none" aria-hidden="true"><path d="M32 6v52M6 32h52M14 14l36 36M14 50l36-36" stroke="currentColor" stroke-width="7" stroke-linecap="round"/></svg></span><p>A little less noise.<br><em>A little more gleam.</em></p><a class="button button-outline" href="https://github.com/meghdadfadaee/shell-gleam">Find it on GitHub <span aria-hidden="true">↗</span></a></section>
|
||||
</main>
|
||||
<footer class="site-footer wrap"><a class="brand" href="#"><span class="brand-mark" aria-hidden="true"><svg viewBox="0 0 64 64" fill="none" aria-hidden="true"><path d="M32 6v52M6 32h52M14 14l36 36M14 50l36-36" stroke="currentColor" stroke-width="7" stroke-linecap="round"/></svg></span>ShellGleam.</a><p>Small footprint. Open source. Yours to make better.</p><div><a href="https://github.com/meghdadfadaee/shell-gleam/blob/main/LICENSE">MIT license</a><a href="https://github.com/meghdadfadaee/shell-gleam">Source ↗</a></div></footer>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1200 630"><rect width="1200" height="630" fill="#f5f3eb"/><g fill="#242b29" font-family="Arial,sans-serif"><text x="80" y="110" font-size="36" font-weight="bold">✳ ShellGleam.</text><text x="80" y="255" font-size="84" letter-spacing="-4">A better hello</text><text x="80" y="350" font-size="84" letter-spacing="-4">from your server.</text><text x="80" y="440" font-size="27" fill="#68716c">A beautiful, configurable Linux login dashboard.</text><text x="80" y="548" font-size="20" font-family="monospace">OPEN SOURCE / PYTHON STDLIB / MADE FOR LINUX</text></g><path d="M1030 80v110m-55-55h110m-94-39 78 78m-78 0 78-78" stroke="#d85531" stroke-width="14" stroke-linecap="round"/></svg>
|
||||
|
After Width: | Height: | Size: 740 B |
+1414
File diff suppressed because it is too large.
Load diff
+263
@@ -0,0 +1,263 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Install a system-wide Ubuntu/Debian MOTD with transactional backup/restore."""
|
||||
import argparse
|
||||
import fcntl
|
||||
import importlib.util
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import re
|
||||
import shutil
|
||||
import stat
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
|
||||
PROJECT = Path(__file__).resolve().parents[1]
|
||||
HOOK = '/etc/update-motd.d/00-server-status'
|
||||
BINARY = '/usr/local/bin/server-status'
|
||||
CONFIG = '/etc/server-status/config.json'
|
||||
STATE = '/var/lib/server-status'
|
||||
SUFFIX = '~server-status-disabled'
|
||||
PAM_FILES = ('/etc/pam.d/sshd', '/etc/pam.d/login')
|
||||
PAM_LINE = 'session optional pam_exec.so stdout type=open_session quiet /etc/update-motd.d/00-server-status'
|
||||
PAM_PATTERN = re.compile(r'^session[^\n]*pam_motd\.so[^\n]*motd=/run/motd\.dynamic[^\n]*$', re.MULTILINE)
|
||||
WRAPPER = '''#!/bin/sh
|
||||
# Managed by server-status. PAM invokes this for all users.
|
||||
# Keep login working even if probes, disks or configuration fail.
|
||||
PATH=/usr/sbin:/usr/bin:/sbin:/bin
|
||||
export PATH
|
||||
export PYTHONIOENCODING=utf-8
|
||||
if ! /usr/bin/timeout --kill-after=1 6 /usr/bin/python3 -I /usr/local/bin/server-status 2>/dev/null; then
|
||||
printf '\\n Server status unavailable; run server-status to diagnose.\\n\\n'
|
||||
fi
|
||||
exit 0
|
||||
'''
|
||||
|
||||
|
||||
def renderer():
|
||||
spec = importlib.util.spec_from_file_location('server_status', PROJECT / 'src/server_status.py')
|
||||
module = importlib.util.module_from_spec(spec)
|
||||
spec.loader.exec_module(module)
|
||||
return module
|
||||
|
||||
|
||||
def atomic(path, data, mode=0o644):
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
fd, temporary = tempfile.mkstemp(prefix='.server-status-', dir=path.parent)
|
||||
try:
|
||||
with os.fdopen(fd, 'wb') as stream:
|
||||
stream.write(data)
|
||||
stream.flush()
|
||||
os.fsync(stream.fileno())
|
||||
os.chmod(temporary, mode)
|
||||
os.replace(temporary, path)
|
||||
finally:
|
||||
if os.path.exists(temporary):
|
||||
os.unlink(temporary)
|
||||
|
||||
|
||||
class Installation:
|
||||
def __init__(self, root):
|
||||
self.root = root
|
||||
self.state = self.path(STATE)
|
||||
self.manifest = self.state / 'manifest.json'
|
||||
|
||||
def path(self, absolute):
|
||||
return self.root / absolute.lstrip('/')
|
||||
|
||||
def snapshot(self, names, folder):
|
||||
folder.mkdir(parents=True, exist_ok=True, mode=0o700)
|
||||
records = {}
|
||||
for i, name in enumerate(names):
|
||||
path = self.path(name)
|
||||
if path.is_symlink():
|
||||
records[name] = {'kind': 'symlink', 'target': os.readlink(path), 'uid': path.lstat().st_uid, 'gid': path.lstat().st_gid}
|
||||
elif path.exists():
|
||||
if not path.is_file():
|
||||
raise ValueError(f'refusing to replace non-file: {name}')
|
||||
backup = folder / str(i)
|
||||
shutil.copy2(path, backup)
|
||||
info = path.stat()
|
||||
records[name] = {'kind': 'file', 'backup': str(backup.relative_to(self.state)), 'mode': stat.S_IMODE(info.st_mode), 'uid': info.st_uid, 'gid': info.st_gid}
|
||||
else:
|
||||
records[name] = {'kind': 'absent'}
|
||||
return records
|
||||
|
||||
def restore(self, records):
|
||||
for name, record in records.items():
|
||||
path = self.path(name)
|
||||
if path.is_symlink() or path.is_file():
|
||||
path.unlink()
|
||||
elif path.exists():
|
||||
raise ValueError(f'refusing to overwrite directory during restore: {name}')
|
||||
if record['kind'] != 'absent':
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
if record['kind'] == 'symlink':
|
||||
path.symlink_to(record['target'])
|
||||
os.lchown(path, record['uid'], record['gid'])
|
||||
else:
|
||||
shutil.copy2(self.state / record['backup'], path)
|
||||
os.chmod(path, record['mode'])
|
||||
os.chown(path, record['uid'], record['gid'])
|
||||
|
||||
def hooks(self):
|
||||
directory = self.path('/etc/update-motd.d')
|
||||
if shutil.which('run-parts'):
|
||||
selected = subprocess.run(['run-parts', '--lsbsysinit', '--test', str(directory)], capture_output=True, text=True, check=True, timeout=5)
|
||||
return sorted('/etc/update-motd.d/' + Path(line).name for line in selected.stdout.splitlines() if Path(line).name != Path(HOOK).name)
|
||||
return sorted('/etc/update-motd.d/' + p.name for p in directory.iterdir()
|
||||
if p.name != Path(HOOK).name and re.fullmatch(r'[A-Za-z0-9_-]+', p.name)
|
||||
and (p.is_file() or p.is_symlink()) and os.access(p, os.X_OK))
|
||||
|
||||
def install(self, cfg, dry_run):
|
||||
hooks = self.hooks()
|
||||
names = [BINARY, CONFIG, HOOK, '/etc/motd', '/run/motd.dynamic', *PAM_FILES]
|
||||
for name in hooks:
|
||||
if self.path(name + SUFFIX).exists() or self.path(name + SUFFIX).is_symlink():
|
||||
raise ValueError('disabled-hook name collision: ' + name + SUFFIX)
|
||||
names.extend([name, name + SUFFIX])
|
||||
print('Install system-wide banner; disable ' + str(len(hooks)) + ' Ubuntu MOTD hooks.')
|
||||
print('Configuration: ' + str(self.path(CONFIG)))
|
||||
if dry_run:
|
||||
print('Dry run: no files changed.')
|
||||
return
|
||||
existing = json.loads(self.manifest.read_text()) if self.manifest.exists() else {}
|
||||
transaction = Path(tempfile.mkdtemp(prefix='backup-', dir=self.state))
|
||||
before = self.snapshot(names, transaction)
|
||||
baseline = dict(existing)
|
||||
for name, record in before.items():
|
||||
baseline.setdefault(name, record)
|
||||
try:
|
||||
for name in hooks:
|
||||
os.replace(self.path(name), self.path(name + SUFFIX))
|
||||
atomic(self.path(BINARY), (PROJECT / 'src/server_status.py').read_bytes(), 0o755)
|
||||
atomic(self.path(CONFIG), (json.dumps(cfg, indent=2, ensure_ascii=False) + '\n').encode())
|
||||
atomic(self.path(HOOK), WRAPPER.encode(), 0o755)
|
||||
for name in PAM_FILES:
|
||||
pam = self.path(name)
|
||||
content = pam.read_text()
|
||||
if PAM_LINE not in content:
|
||||
updated, count = PAM_PATTERN.subn(PAM_LINE, content)
|
||||
if count != 1:
|
||||
raise ValueError('expected one dynamic MOTD session entry in ' + name)
|
||||
atomic(pam, updated.encode(), stat.S_IMODE(pam.stat().st_mode))
|
||||
# Empty rather than remove a symlink: restore() has the original target.
|
||||
atomic(self.path('/etc/motd'), b'')
|
||||
if self.root == Path('/'):
|
||||
selected = subprocess.run(['/usr/bin/run-parts', '--lsbsysinit', '--test', '/etc/update-motd.d'], capture_output=True, text=True, check=True, timeout=5)
|
||||
if selected.stdout.splitlines() != [HOOK]:
|
||||
raise ValueError('unexpected executable MOTD hooks: ' + selected.stdout)
|
||||
refresh = subprocess.run(['/usr/bin/timeout', '--kill-after=1', '8', '/usr/bin/python3', '-I', BINARY], capture_output=True, timeout=10)
|
||||
if refresh.returncode:
|
||||
raise ValueError('initial rendering failed: ' + refresh.stderr.decode(errors='replace'))
|
||||
atomic(self.path('/run/motd.dynamic'), refresh.stdout)
|
||||
atomic(self.manifest, (json.dumps(baseline, indent=2) + '\n').encode(), 0o600)
|
||||
except BaseException:
|
||||
self.restore(before)
|
||||
raise
|
||||
print('Installed. Existing config preserved unless --config or customization flags were supplied.')
|
||||
print('Undo: sudo ./setup.sh uninstall')
|
||||
|
||||
def uninstall(self, dry_run):
|
||||
if not self.manifest.exists():
|
||||
print('No managed installation found.')
|
||||
return
|
||||
original = json.loads(self.manifest.read_text())
|
||||
print('Restore ' + str(len(original)) + ' paths from the original installation backup.')
|
||||
if dry_run:
|
||||
print('Dry run: no files changed.')
|
||||
return
|
||||
transaction = Path(tempfile.mkdtemp(prefix='uninstall-', dir=self.state))
|
||||
before = self.snapshot(list(original), transaction)
|
||||
try:
|
||||
self.restore(original)
|
||||
self.manifest.rename(self.state / 'last-uninstall.json')
|
||||
except BaseException:
|
||||
self.restore(before)
|
||||
raise
|
||||
print('Original login messages restored. Backups retained in ' + str(self.state))
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument('action', choices=('install', 'uninstall', 'status'), nargs='?', default='install')
|
||||
parser.add_argument('--config', type=Path, help='JSON configuration; validated before changes')
|
||||
parser.add_argument('--title', help='display name (default: hostname)')
|
||||
parser.add_argument('--address', help='display address (default: auto)')
|
||||
parser.add_argument('--no-color', action='store_true')
|
||||
parser.add_argument('--ascii', action='store_true')
|
||||
parser.add_argument('--wizard', action='store_true', help='interactive title, address, services and disk customization')
|
||||
parser.add_argument('--dry-run', action='store_true')
|
||||
parser.add_argument('--root', type=Path, default=Path('/'), help=argparse.SUPPRESS)
|
||||
args = parser.parse_args()
|
||||
installation = Installation(args.root.resolve())
|
||||
if args.action == 'status':
|
||||
print('Installed' if installation.manifest.exists() else 'Not installed')
|
||||
print('Backup directory: ' + str(installation.state))
|
||||
return 0
|
||||
if installation.root == Path('/'):
|
||||
if any(not Path(p).exists() for p in ('/usr/bin/python3', '/usr/bin/timeout', '/usr/bin/run-parts')):
|
||||
raise ValueError('requires python3, GNU coreutils timeout and Debian run-parts')
|
||||
if args.action == 'install':
|
||||
for pam in ('sshd', 'login'):
|
||||
content = Path('/etc/pam.d/' + pam).read_text()
|
||||
if PAM_LINE not in content and not any('pam_motd.so' in line and not line.lstrip().startswith('#') and 'noupdate' not in line and 'motd=/run/motd.dynamic' in line for line in content.splitlines()):
|
||||
raise ValueError('requires existing dynamic pam_motd configuration in /etc/pam.d/' + pam)
|
||||
if not list(Path('/usr/lib').glob('**/security/pam_exec.so')) and not Path('/lib/security/pam_exec.so').exists():
|
||||
raise ValueError('requires the standard pam_exec.so session module')
|
||||
check = subprocess.run(['/usr/sbin/sshd', '-T'], capture_output=True, text=True, timeout=5)
|
||||
if check.returncode or 'usepam yes' not in check.stdout or 'printmotd no' not in check.stdout:
|
||||
raise ValueError('SSH must already have UsePAM yes and PrintMotd no; only MOTD session-display lines are managed')
|
||||
if args.action == 'install':
|
||||
source = args.config or (installation.path(CONFIG) if installation.path(CONFIG).exists() else PROJECT / 'config/default.json')
|
||||
if not source.is_file():
|
||||
raise ValueError('configuration file not found: ' + str(source))
|
||||
cfg = renderer().config(source)
|
||||
if args.title is not None:
|
||||
cfg['title'] = args.title
|
||||
if args.address is not None:
|
||||
cfg['address'] = args.address
|
||||
if args.no_color:
|
||||
cfg['color'] = False
|
||||
if args.ascii:
|
||||
cfg['ascii'] = True
|
||||
if args.wizard:
|
||||
cfg['title'] = input(f'Display title [{cfg["title"] or "automatic hostname"}]: ').strip() or cfg['title']
|
||||
cfg['address'] = input(f'IP address [{cfg["address"]}]: ').strip() or cfg['address']
|
||||
units = input('Service units, comma separated (blank: keep current; none: no services): ').strip()
|
||||
if units:
|
||||
cfg['services'] = [] if units == 'none' else [{'unit': unit.strip(), 'label': unit.strip().removesuffix('.service'), 'required': True} for unit in units.split(',')]
|
||||
disks = input('Disk paths, comma separated (blank: keep current): ').strip()
|
||||
if disks:
|
||||
cfg['disks'] = [d.strip() for d in disks.split(',')]
|
||||
# Validate CLI/wizard values before touching the system.
|
||||
with tempfile.TemporaryDirectory() as directory:
|
||||
candidate = Path(directory) / 'config.json'
|
||||
candidate.write_text(json.dumps(cfg))
|
||||
cfg = renderer().config(candidate)
|
||||
if args.dry_run:
|
||||
if args.action == 'install':
|
||||
installation.install(cfg, True)
|
||||
else:
|
||||
installation.uninstall(True)
|
||||
return 0
|
||||
if os.geteuid() != 0:
|
||||
raise ValueError('run installation/uninstallation with sudo (or use --dry-run)')
|
||||
installation.state.mkdir(parents=True, exist_ok=True, mode=0o700)
|
||||
os.chmod(installation.state, 0o700)
|
||||
with (installation.state / 'lock').open('w') as lock:
|
||||
fcntl.flock(lock, fcntl.LOCK_EX)
|
||||
if args.action == 'install':
|
||||
installation.install(cfg, False)
|
||||
else:
|
||||
installation.uninstall(False)
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
try:
|
||||
sys.exit(main())
|
||||
except (ValueError, OSError, subprocess.SubprocessError) as exc:
|
||||
print('setup: ' + str(exc), file=sys.stderr)
|
||||
sys.exit(1)
|
||||
Executable
+294
@@ -0,0 +1,294 @@
|
||||
#!/usr/bin/python3
|
||||
"""A bounded, dependency-free system status MOTD for Linux."""
|
||||
import argparse
|
||||
import concurrent.futures
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import re
|
||||
import shutil
|
||||
import socket
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
import unicodedata
|
||||
|
||||
DEFAULTS = {
|
||||
'title': '', 'address': 'auto', 'width': 72, 'color': True, 'ascii': False,
|
||||
'sections': ['system', 'runtime', 'health'],
|
||||
'services': [{'unit': 'nginx.service', 'label': 'Nginx', 'required': False},
|
||||
{'unit': 'docker.service', 'label': 'Docker', 'required': False}],
|
||||
'disks': ['/'], 'docker': True, 'command_timeout': 1.0,
|
||||
'memory_warning': 75, 'memory_critical': 90, 'disk_warning': 75,
|
||||
'disk_critical': 90, 'load_warning': .7, 'load_critical': 1.,
|
||||
'updates_max_age_hours': 48, 'footer': '',
|
||||
}
|
||||
ANSI = re.compile(r'\x1b\[[0-9;]*m')
|
||||
|
||||
|
||||
def clean(value):
|
||||
return ''.join(c for c in str(value) if unicodedata.category(c)[0] != 'C')
|
||||
|
||||
|
||||
def cells(value):
|
||||
return sum(0 if unicodedata.combining(c) else
|
||||
2 if unicodedata.east_asian_width(c) in ('W', 'F') else 1
|
||||
for c in ANSI.sub('', value))
|
||||
|
||||
|
||||
def clip(value, width):
|
||||
result = ''
|
||||
for char in clean(value):
|
||||
if cells(result + char) > width:
|
||||
break
|
||||
result += char
|
||||
return result
|
||||
|
||||
|
||||
def config(path):
|
||||
cfg = dict(DEFAULTS)
|
||||
if path and Path(path).exists():
|
||||
overrides = json.loads(Path(path).read_text())
|
||||
if not isinstance(overrides, dict):
|
||||
raise ValueError('configuration must be a JSON object')
|
||||
unknown = set(overrides) - set(DEFAULTS)
|
||||
if unknown:
|
||||
raise ValueError('unknown settings: ' + ', '.join(sorted(unknown)))
|
||||
cfg.update(overrides)
|
||||
for key in ('title', 'address', 'footer'):
|
||||
if not isinstance(cfg[key], str):
|
||||
raise ValueError(key + ' must be a string')
|
||||
for key in ('color', 'ascii', 'docker'):
|
||||
if type(cfg[key]) is not bool:
|
||||
raise ValueError(key + ' must be true or false')
|
||||
if type(cfg['width']) is not int or not 52 <= cfg['width'] <= 120:
|
||||
raise ValueError('width must be an integer from 52 to 120')
|
||||
for key in ('command_timeout', 'updates_max_age_hours', 'memory_warning',
|
||||
'memory_critical', 'disk_warning', 'disk_critical', 'load_warning', 'load_critical'):
|
||||
if type(cfg[key]) not in (int, float) or not 0 < cfg[key] < float('inf'):
|
||||
raise ValueError(key + ' must be a positive finite number')
|
||||
if not .1 <= cfg['command_timeout'] <= 2:
|
||||
raise ValueError('command_timeout must be between 0.1 and 2 seconds')
|
||||
for metric in ('memory', 'disk', 'load'):
|
||||
if cfg[metric + '_warning'] >= cfg[metric + '_critical']:
|
||||
raise ValueError(metric + ': warning must be below critical')
|
||||
for metric in ('memory', 'disk'):
|
||||
if cfg[metric + '_critical'] > 100:
|
||||
raise ValueError(metric + '_critical must be at most 100')
|
||||
if not isinstance(cfg['sections'], list) or any(s not in ('system', 'runtime', 'health') for s in cfg['sections']):
|
||||
raise ValueError('sections must contain system, runtime or health')
|
||||
if not isinstance(cfg['disks'], list) or not 1 <= len(cfg['disks']) <= 8 or any(not isinstance(d, str) or not d.startswith('/') for d in cfg['disks']):
|
||||
raise ValueError('disks must contain 1-8 absolute paths')
|
||||
if not isinstance(cfg['services'], list) or len(cfg['services']) > 16:
|
||||
raise ValueError('services must be a list of at most 16 entries')
|
||||
for service in cfg['services']:
|
||||
if not isinstance(service, dict) or set(service) - {'unit', 'label', 'required'}:
|
||||
raise ValueError('each service accepts unit, label and required')
|
||||
if not re.fullmatch(r'[A-Za-z0-9_][A-Za-z0-9_@.:-]*', service.get('unit', '')):
|
||||
raise ValueError('invalid service unit')
|
||||
if not isinstance(service.get('label', ''), str) or type(service.get('required', False)) is not bool:
|
||||
raise ValueError('invalid service label or required flag')
|
||||
return cfg
|
||||
|
||||
|
||||
def command(args, timeout):
|
||||
try:
|
||||
p = subprocess.run(args, capture_output=True, text=True, timeout=timeout,
|
||||
env={**os.environ, 'LC_ALL': 'C', 'PATH': '/usr/sbin:/usr/bin:/sbin:/bin'})
|
||||
return p.returncode, p.stdout.strip()
|
||||
except (OSError, subprocess.TimeoutExpired, UnicodeError):
|
||||
return -1, ''
|
||||
|
||||
|
||||
def read(path):
|
||||
try:
|
||||
return Path(path).read_text()
|
||||
except OSError:
|
||||
return ''
|
||||
|
||||
|
||||
def update_status(path, max_age, now=None):
|
||||
source = Path(path)
|
||||
try:
|
||||
age = (time.time() if now is None else now) - source.stat().st_mtime
|
||||
text = source.read_text()
|
||||
except OSError:
|
||||
return 'Package updates unknown (no cached data)', True
|
||||
match = re.search(r'(?m)^\s*(\d+)\s+(?:updates? (?:can be applied|available)|packages? can be updated)', text)
|
||||
if not match:
|
||||
return 'Package updates unknown (unrecognized cache)', True
|
||||
count = int(match[1])
|
||||
if age > max_age * 3600:
|
||||
return f'Package cache stale ({count} updates last reported)', True
|
||||
return (f'{count} package updates available' if count else 'Packages current (cached)'), bool(count)
|
||||
|
||||
|
||||
def docker_status(result):
|
||||
code, output = result
|
||||
if code:
|
||||
return 'Container status unavailable', True
|
||||
rows = [r.split('|', 2) for r in output.splitlines() if len(r.split('|', 2)) == 3]
|
||||
running = sum(r[1] == 'running' for r in rows)
|
||||
unhealthy = sum('(unhealthy)' in r[2] for r in rows)
|
||||
starting = sum('(health: starting)' in r[2] for r in rows)
|
||||
healthy = sum('(healthy)' in r[2] for r in rows)
|
||||
failed = sum(r[1] in ('dead', 'restarting') or (r[1] == 'exited' and not r[2].startswith('Exited (0)')) for r in rows)
|
||||
text = f'{running} containers running'
|
||||
if unhealthy or failed or starting:
|
||||
text += f' · {unhealthy} unhealthy · {failed} failed · {starting} starting'
|
||||
elif running:
|
||||
text += f' · {healthy} healthchecked' if healthy else ' · no healthchecks'
|
||||
return text, bool(unhealthy or failed or starting)
|
||||
|
||||
|
||||
def collect(cfg):
|
||||
jobs = {'failed': ['systemctl', '--failed', '--no-legend', '--plain', '--no-pager'],
|
||||
'ip': ['hostname', '-I']}
|
||||
for i, service in enumerate(cfg['services']):
|
||||
jobs[f'service{i}'] = ['systemctl', 'show', service['unit'], '--property=LoadState,ActiveState', '--no-pager']
|
||||
if cfg['docker'] and shutil.which('docker'):
|
||||
# Pin the local daemon: never inherit a user's remote Docker context.
|
||||
jobs['docker'] = ['docker', '--host', 'unix:///var/run/docker.sock', 'ps', '-a', '--format', '{{.Names}}|{{.State}}|{{.Status}}']
|
||||
with concurrent.futures.ThreadPoolExecutor(max_workers=20) as executor:
|
||||
futures = {k: executor.submit(command, args, cfg['command_timeout']) for k, args in jobs.items()}
|
||||
results = {k: future.result() for k, future in futures.items()}
|
||||
return results
|
||||
|
||||
|
||||
def render(cfg, results):
|
||||
rows = []
|
||||
attention = False
|
||||
def add(section, text, level='normal'):
|
||||
nonlocal attention
|
||||
rows.append((section, clean(text), level))
|
||||
attention |= level in ('warning', 'critical')
|
||||
def level(value, metric):
|
||||
return 'critical' if value >= cfg[metric + '_critical'] else 'warning' if value >= cfg[metric + '_warning'] else 'good'
|
||||
try:
|
||||
seconds = int(float(read('/proc/uptime').split()[0]))
|
||||
uptime = f'{seconds // 86400}d {seconds % 86400 // 3600}h' if seconds >= 86400 else f'{seconds // 3600}h {seconds % 3600 // 60}m'
|
||||
load = float(read('/proc/loadavg').split()[0])
|
||||
cores = os.cpu_count() or 1
|
||||
add('system', f'↑ Uptime {uptime} ≋ Load average {load:.2f} ({cores} cores)', level(load / cores, 'load'))
|
||||
memory = {k: int(v.split()[0]) for k, v in (line.split(':', 1) for line in read('/proc/meminfo').splitlines())}
|
||||
total = memory['MemTotal']; used = total - memory['MemAvailable']
|
||||
percent = used / total * 100
|
||||
add('system', f'Memory {bar(percent, cfg)} {percent:.0f}% · {used / 1048576:.1f} / {total / 1048576:.1f} GiB', level(percent, 'memory'))
|
||||
except (ValueError, KeyError, IndexError, ZeroDivisionError):
|
||||
add('system', 'System metrics unavailable', 'warning')
|
||||
for disk in cfg['disks']:
|
||||
try:
|
||||
usage = shutil.disk_usage(disk)
|
||||
stat = os.statvfs(disk)
|
||||
# Match df: percentage uses space available to non-root, excluding reserved blocks.
|
||||
denominator = usage.used + stat.f_bavail * stat.f_frsize
|
||||
percent = usage.used / denominator * 100 if denominator else 0
|
||||
add('system', f'Disk {disk} {bar(percent, cfg)} {percent:.0f}% · {usage.used / 1073741824:.1f} / {usage.total / 1073741824:.1f} GiB', level(percent, 'disk'))
|
||||
except OSError:
|
||||
add('system', f'Disk {disk}: unavailable', 'warning')
|
||||
for i, service in enumerate(cfg['services']):
|
||||
code, output = results[f'service{i}']
|
||||
properties = dict(line.split('=', 1) for line in output.splitlines() if '=' in line)
|
||||
label = service.get('label') or service['unit']
|
||||
if code or properties.get('LoadState') in (None, 'not-found'):
|
||||
missing = properties.get('LoadState') == 'not-found'
|
||||
add('runtime', f'● {label}: {"not installed" if missing else "status unavailable"}', 'warning' if service.get('required') or not missing else 'normal')
|
||||
elif properties.get('ActiveState') == 'active':
|
||||
add('runtime', f'● {label} is online', 'good')
|
||||
else:
|
||||
add('runtime', f'● {label} is {properties.get("ActiveState", "unknown")}', 'warning')
|
||||
if cfg['docker']:
|
||||
if 'docker' in results:
|
||||
text, warning = docker_status(results['docker'])
|
||||
add('runtime', ' ' + text, 'warning' if warning else 'good')
|
||||
else:
|
||||
add('runtime', ' Docker CLI not installed')
|
||||
code, output = results['failed']
|
||||
if code:
|
||||
add('health', '⚠ Failed services: status unavailable', 'warning')
|
||||
else:
|
||||
failed = [line.split()[0] for line in output.splitlines() if line.strip()]
|
||||
add('health', f'⚠ {len(failed)} units failed · ' + ', '.join(failed[:3]) if failed else '✓ No failed systemd units', 'warning' if failed else 'good')
|
||||
updates, warning = update_status('/var/lib/update-notifier/updates-available', cfg['updates_max_age_hours'])
|
||||
add('health', ('↑ ' if warning else '✓ ') + updates, 'warning' if warning else 'good')
|
||||
reboot = Path('/run/reboot-required').exists()
|
||||
add('health', '↻ Reboot required' if reboot else '✓ No reboot needed', 'warning' if reboot else 'good')
|
||||
firmware = read('/run/motd.d/85-fwupd')
|
||||
match = re.search(r'(\d+) devices? have a firmware upgrade available', firmware)
|
||||
if match and int(match[1]):
|
||||
add('health', f'↑ {match[1]} firmware upgrades available', 'warning')
|
||||
os_name = 'Linux'
|
||||
for line in read('/etc/os-release').splitlines():
|
||||
if line.startswith('PRETTY_NAME='):
|
||||
os_name = line.split('=', 1)[1].strip('"')
|
||||
ip = cfg['address']
|
||||
if ip == 'auto':
|
||||
addresses = results['ip'][1].split()
|
||||
ip = next((a for a in addresses if ':' not in a), addresses[0] if addresses else 'address unavailable')
|
||||
title = cfg['title'] or socket.gethostname().split('.')[0].upper()
|
||||
return box(cfg, title, os_name + ' · ' + ip, rows, attention)
|
||||
|
||||
|
||||
def bar(percent, cfg):
|
||||
filled = max(0, min(18, int(percent * 18 / 100 + .5)))
|
||||
return ('#' if cfg['ascii'] else '█') * filled + ('-' if cfg['ascii'] else '░') * (18 - filled)
|
||||
|
||||
|
||||
def box(cfg, title, subtitle, rows, attention):
|
||||
width = cfg['width']
|
||||
color = cfg['color'] and 'NO_COLOR' not in os.environ
|
||||
colors = {'normal': '', 'good': '\033[32m', 'warning': '\033[33m', 'critical': '\033[31m', 'border': '\033[36m'}
|
||||
def paint(text, kind):
|
||||
return colors[kind] + text + '\033[0m' if color and colors[kind] else text
|
||||
ascii_mode = cfg['ascii']
|
||||
h, v = ('-', '|') if ascii_mode else ('─', '│')
|
||||
tl, tr, bl, br, ml, mr = ('+',) * 6 if ascii_mode else ('╭', '╮', '╰', '╯', '├', '┤')
|
||||
def plain(text):
|
||||
if ascii_mode:
|
||||
for a, b in {'◆': '*', '●': '*', '↑': '^', '≋': '~', '✓': '+', '⚠': '!', '↻': '*', '·': '/'}.items():
|
||||
text = text.replace(a, b)
|
||||
text = text.encode('ascii', 'replace').decode()
|
||||
return clean(text)
|
||||
def line(text='', kind='normal'):
|
||||
text = clip(plain(text), width - 2)
|
||||
return ' ' + paint(v, 'border') + ' ' + paint(text, kind) + ' ' * (width - 1 - cells(text)) + paint(v, 'border')
|
||||
status = ('● ATTENTION' if attention else '● HEALTHY')
|
||||
left = clip(plain('◆ ' + title), width - cells(plain(status)) - 4)
|
||||
header = left + ' ' * (width - 2 - cells(left) - cells(plain(status))) + status
|
||||
output = ['', ' ' + paint(tl + h * width + tr, 'border'), line(header, 'warning' if attention else 'good'), line(' ' + subtitle)]
|
||||
for section in cfg['sections']:
|
||||
label = h + ' ' + section.upper() + ' '
|
||||
output.append(' ' + paint(ml + label + h * (width - cells(label)) + mr, 'border'))
|
||||
output.append(line())
|
||||
for row_section, text, kind in rows:
|
||||
if row_section == section:
|
||||
output.append(line(' ' + text, kind))
|
||||
output.append(line())
|
||||
if cfg['footer']:
|
||||
output.append(line(cfg['footer']))
|
||||
output.extend([' ' + paint(bl + h * width + br, 'border'), ''])
|
||||
return '\n'.join(output) + '\n'
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument('--config', default='/etc/server-status/config.json')
|
||||
parser.add_argument('--check', action='store_true', help='validate configuration without running probes')
|
||||
parser.add_argument('--no-color', action='store_true')
|
||||
args = parser.parse_args()
|
||||
try:
|
||||
cfg = config(args.config)
|
||||
if args.no_color:
|
||||
cfg['color'] = False
|
||||
if args.check:
|
||||
print('Configuration valid')
|
||||
return 0
|
||||
print(render(cfg, collect(cfg)), end='')
|
||||
return 0
|
||||
except (ValueError, OSError, TypeError) as exc:
|
||||
print('server-status: ' + str(exc), file=sys.stderr)
|
||||
return 1
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
sys.exit(main())
|
||||
@@ -0,0 +1,138 @@
|
||||
import hashlib
|
||||
import importlib.util
|
||||
import io
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import shutil
|
||||
import subprocess
|
||||
import tarfile
|
||||
import tempfile
|
||||
import unittest
|
||||
from unittest.mock import patch
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
spec = importlib.util.spec_from_file_location('build_site', ROOT / 'scripts/build_site.py')
|
||||
builder = importlib.util.module_from_spec(spec)
|
||||
spec.loader.exec_module(builder)
|
||||
|
||||
|
||||
class BuildTests(unittest.TestCase):
|
||||
def test_reproducible_payload_exact_allowlist_and_rendered_bootstrap(self):
|
||||
with tempfile.TemporaryDirectory() as directory:
|
||||
root = Path(directory)
|
||||
first = builder.build(root / 'first', 'https://example.github.io/shell-gleam')
|
||||
second = builder.build(root / 'second', 'https://example.github.io/shell-gleam')
|
||||
self.assertEqual(first, second)
|
||||
archive = root / 'first' / first['archive']
|
||||
self.assertEqual(hashlib.sha256(archive.read_bytes()).hexdigest(), first['sha256'])
|
||||
with tarfile.open(archive) as package:
|
||||
self.assertEqual(set(package.getnames()), {'shell-gleam/' + name for name in builder.PACKAGE_FILES})
|
||||
self.assertTrue(all(member.isfile() for member in package))
|
||||
bootstrap = (root / 'first/setup.sh').read_text()
|
||||
self.assertNotIn('@@', bootstrap)
|
||||
self.assertIn(first['sha256'], bootstrap)
|
||||
self.assertIn('https://example.github.io/shell-gleam', bootstrap)
|
||||
subprocess.run(['bash', '-n', str(root / 'first/setup.sh')], check=True)
|
||||
|
||||
def test_unlisted_local_file_never_enters_package(self):
|
||||
with tempfile.TemporaryDirectory() as directory:
|
||||
fixture = Path(directory) / 'source'
|
||||
for name in (*builder.PACKAGE_FILES, 'scripts/bootstrap.sh', *('site/' + a for a in builder.ASSETS)):
|
||||
destination = fixture / name
|
||||
destination.parent.mkdir(parents=True, exist_ok=True)
|
||||
shutil.copyfile(ROOT / name, destination)
|
||||
(fixture / 'config/local-secret.json').write_text('{"token":"do-not-package"}')
|
||||
with patch.object(builder, 'ROOT', fixture):
|
||||
release = builder.build(Path(directory) / 'output', 'https://example.github.io/shell-gleam')
|
||||
with tarfile.open(Path(directory) / 'output' / release['archive']) as package:
|
||||
self.assertFalse(any('local-secret' in name for name in package.getnames()))
|
||||
|
||||
def test_source_root_cannot_be_output(self):
|
||||
with self.assertRaises(ValueError):
|
||||
builder.build(ROOT, 'https://example.github.io/shell-gleam')
|
||||
|
||||
|
||||
class BootstrapTests(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.temp = tempfile.TemporaryDirectory()
|
||||
self.addCleanup(self.temp.cleanup)
|
||||
self.root = Path(self.temp.name)
|
||||
self.bin = self.root / 'bin'
|
||||
self.bin.mkdir()
|
||||
self.tmp = self.root / 'tmp'
|
||||
self.tmp.mkdir()
|
||||
self.archive = self.root / 'payload.tar.gz'
|
||||
for name, content in {
|
||||
'id': '#!/bin/sh\necho 0\n',
|
||||
'curl': '#!/usr/bin/env python3\nimport os,shutil,sys\nif os.environ.get("TEST_CURL_FAIL"): sys.exit(22)\nshutil.copyfile(os.environ["TEST_ARCHIVE"], sys.argv[sys.argv.index("-o")+1])\n',
|
||||
}.items():
|
||||
path = self.bin / name
|
||||
path.write_text(content)
|
||||
path.chmod(0o755)
|
||||
self.env = {**os.environ, 'PATH': str(self.bin) + ':' + os.environ['PATH'],
|
||||
'TEST_ARCHIVE': str(self.archive), 'TMPDIR': str(self.tmp),
|
||||
'SHELL_GLEAM_BASE_URL': 'http://127.0.0.1:8000'}
|
||||
|
||||
def package(self, name='shell-gleam/setup.sh', symlink=False):
|
||||
with tarfile.open(self.archive, 'w:gz') as package:
|
||||
data = b'#!/bin/sh\nprintf "ARG=<%s>\\n" "$@"\n'
|
||||
member = tarfile.TarInfo(name)
|
||||
member.mode = 0o755
|
||||
if symlink:
|
||||
member.type = tarfile.SYMTYPE
|
||||
member.linkname = '/etc/passwd'
|
||||
package.addfile(member)
|
||||
else:
|
||||
member.size = len(data)
|
||||
package.addfile(member, io.BytesIO(data))
|
||||
|
||||
def run_bootstrap(self, *args, wrong_checksum=False):
|
||||
checksum = hashlib.sha256(self.archive.read_bytes()).hexdigest()
|
||||
template = (ROOT / 'scripts/bootstrap.sh').read_text()
|
||||
script = template.replace('@@SHA256@@', '0' * 64 if wrong_checksum else checksum).replace('@@ARCHIVE@@', 'downloads/test.tar.gz').replace('@@SITE_URL@@', 'https://example.github.io/shell-gleam')
|
||||
return subprocess.run(['bash', '-s', '--', *args], input=script, capture_output=True, text=True, env=self.env)
|
||||
|
||||
def test_piped_execution_argument_forwarding_and_cleanup(self):
|
||||
self.package()
|
||||
result = self.run_bootstrap('install', '--dry-run', '--title', "O'Brien $(touch nope); *")
|
||||
self.assertEqual(result.returncode, 0, result.stderr)
|
||||
self.assertIn("ARG=<O'Brien $(touch nope); *>", result.stdout)
|
||||
self.assertIn('SHA-256 verified', result.stdout)
|
||||
self.assertEqual(list(self.tmp.iterdir()), [])
|
||||
|
||||
def test_checksum_failure_stops_before_setup(self):
|
||||
self.package()
|
||||
result = self.run_bootstrap('--dry-run', wrong_checksum=True)
|
||||
self.assertNotEqual(result.returncode, 0)
|
||||
self.assertIn('checksum mismatch', result.stderr)
|
||||
self.assertNotIn('ARG=', result.stdout)
|
||||
self.assertEqual(list(self.tmp.iterdir()), [])
|
||||
|
||||
def test_traversal_and_symlinks_rejected(self):
|
||||
for name, symlink in [('shell-gleam/../../escape', False), ('shell-gleam/link', True)]:
|
||||
with self.subTest(name=name):
|
||||
self.package(name, symlink)
|
||||
result = self.run_bootstrap('--dry-run')
|
||||
self.assertNotEqual(result.returncode, 0)
|
||||
self.assertIn('unsafe package', result.stderr)
|
||||
self.assertFalse((self.root / 'escape').exists())
|
||||
|
||||
def test_download_failure_stops_before_setup(self):
|
||||
self.package()
|
||||
self.env['TEST_CURL_FAIL'] = '1'
|
||||
result = self.run_bootstrap('--dry-run')
|
||||
self.assertEqual(result.returncode, 22)
|
||||
self.assertNotIn('ARG=', result.stdout)
|
||||
self.assertEqual(list(self.tmp.iterdir()), [])
|
||||
|
||||
def test_non_https_remote_override_rejected(self):
|
||||
self.package()
|
||||
self.env['SHELL_GLEAM_BASE_URL'] = 'http://example.com'
|
||||
result = self.run_bootstrap('--dry-run')
|
||||
self.assertNotEqual(result.returncode, 0)
|
||||
self.assertIn('must use HTTPS', result.stderr)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
@@ -0,0 +1,137 @@
|
||||
import importlib.util
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import tempfile
|
||||
import unittest
|
||||
from unittest.mock import patch
|
||||
import sys
|
||||
import shutil
|
||||
import subprocess
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / 'src'))
|
||||
import server_status as status
|
||||
import install
|
||||
|
||||
|
||||
class RendererTests(unittest.TestCase):
|
||||
def test_cache_fresh_stale_missing_and_actual_ubuntu_format(self):
|
||||
with tempfile.TemporaryDirectory() as directory:
|
||||
cache = Path(directory) / 'updates'
|
||||
self.assertTrue(status.update_status(cache, 48)[1])
|
||||
cache.write_text('Expanded Security Maintenance is not enabled.\n\n0 updates can be applied immediately.\n')
|
||||
self.assertFalse(status.update_status(cache, 48)[1])
|
||||
self.assertTrue(status.update_status(cache, 48, cache.stat().st_mtime + 49 * 3600)[1])
|
||||
cache.write_text('12 updates can be applied immediately.\n')
|
||||
self.assertIn('12 package', status.update_status(cache, 48)[0])
|
||||
cache.write_text('unknown output')
|
||||
self.assertIn('unknown', status.update_status(cache, 48)[0])
|
||||
|
||||
def test_docker_health_is_not_invented(self):
|
||||
self.assertIn('no healthchecks', status.docker_status((0, 'web|running|Up 2 days'))[0])
|
||||
text, warning = status.docker_status((0, 'web|running|Up 2 days (healthy)\nworker|exited|Exited (1) 2 days ago'))
|
||||
self.assertTrue(warning)
|
||||
self.assertIn('1 failed', text)
|
||||
self.assertTrue(status.docker_status((-1, ''))[1])
|
||||
self.assertFalse(status.docker_status((0, 'job|exited|Exited (0) 1 day ago'))[1])
|
||||
|
||||
def test_border_alignment_truncation_control_codes_and_ascii(self):
|
||||
cfg = dict(status.DEFAULTS, color=False)
|
||||
for ascii_mode in (False, True):
|
||||
cfg['ascii'] = ascii_mode
|
||||
output = status.box(cfg, '測試' * 60 + '\x1b[31m', 'Ubuntu', [('system', 'x' * 200, 'normal')], True)
|
||||
lines = [line for line in output.splitlines() if line]
|
||||
self.assertEqual({status.cells(line) for line in lines}, {76})
|
||||
self.assertNotIn('\x1b', output)
|
||||
if ascii_mode:
|
||||
output.encode('ascii')
|
||||
|
||||
def test_invalid_configuration_rejected(self):
|
||||
with tempfile.TemporaryDirectory() as directory:
|
||||
path = Path(directory) / 'config.json'
|
||||
for invalid in ({'width': 4}, {'command_timeout': 9}, {'services': [{'unit': '--help'}]}, {'sections': ['mystery']}, {'disk_warning': 95, 'disk_critical': 80}, {'color': 'yes'}, {'typo': True}, {'command_timeout': float('nan')}):
|
||||
path.write_text(json.dumps(invalid))
|
||||
with self.subTest(invalid=invalid), self.assertRaises(ValueError):
|
||||
status.config(path)
|
||||
|
||||
|
||||
class InstallerTests(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.temporary = tempfile.TemporaryDirectory()
|
||||
self.addCleanup(self.temporary.cleanup)
|
||||
self.root = Path(self.temporary.name)
|
||||
self.instance = install.Installation(self.root)
|
||||
self.instance.state.mkdir(parents=True)
|
||||
for name in install.PAM_FILES:
|
||||
pam = self.instance.path(name)
|
||||
pam.parent.mkdir(parents=True, exist_ok=True)
|
||||
pam.write_text('# authentication unchanged\n@include common-auth\nsession optional pam_motd.so motd=/run/motd.dynamic\nsession optional pam_motd.so noupdate\n')
|
||||
hooks = self.root / 'etc/update-motd.d'
|
||||
hooks.mkdir(parents=True)
|
||||
self.header = hooks / '00-header'
|
||||
self.header.write_text('#!/bin/sh\necho old\n')
|
||||
self.header.chmod(0o751)
|
||||
(hooks / '50-landscape').symlink_to('/usr/share/landscape/wrapper')
|
||||
# A relative executable symlink must be preserved as a symlink.
|
||||
(hooks / '10-link').symlink_to('00-header')
|
||||
(self.root / 'etc/motd').write_text('original static MOTD')
|
||||
|
||||
def test_reinstall_new_package_hooks_and_uninstall_restore(self):
|
||||
self.instance.install(dict(status.DEFAULTS), False)
|
||||
self.assertIn(install.PAM_LINE, self.instance.path(install.PAM_FILES[0]).read_text())
|
||||
self.assertFalse(self.header.exists())
|
||||
self.assertTrue(Path(str(self.header) + install.SUFFIX).exists())
|
||||
config = self.instance.path(install.CONFIG)
|
||||
customized = dict(status.DEFAULTS, title='CUSTOM')
|
||||
config.write_text(json.dumps(customized))
|
||||
new_hook = self.root / 'etc/update-motd.d/90-new-package'
|
||||
new_hook.write_text('new')
|
||||
new_hook.chmod(0o755)
|
||||
self.instance.install(customized, False)
|
||||
self.assertEqual(json.loads(config.read_text())['title'], 'CUSTOM')
|
||||
self.assertFalse(new_hook.exists())
|
||||
self.instance.uninstall(False)
|
||||
for name in install.PAM_FILES:
|
||||
content = self.instance.path(name).read_text()
|
||||
self.assertIn('pam_motd.so motd=/run/motd.dynamic', content)
|
||||
self.assertNotIn('pam_exec.so', content)
|
||||
self.assertIn('@include common-auth', content)
|
||||
self.assertEqual(self.header.read_text(), '#!/bin/sh\necho old\n')
|
||||
self.assertEqual(self.header.stat().st_mode & 0o777, 0o751)
|
||||
self.assertEqual(os.readlink(self.root / 'etc/update-motd.d/10-link'), '00-header')
|
||||
self.assertEqual((self.root / 'etc/motd').read_text(), 'original static MOTD')
|
||||
self.assertTrue(new_hook.exists())
|
||||
self.assertFalse(self.instance.path(install.HOOK).exists())
|
||||
self.assertFalse(config.exists())
|
||||
self.instance.uninstall(False)
|
||||
|
||||
@unittest.skipUnless(shutil.which('run-parts'), 'Debian run-parts unavailable')
|
||||
def test_pam_lsbsysinit_selects_only_managed_hook(self):
|
||||
self.instance.install(dict(status.DEFAULTS), False)
|
||||
selected = subprocess.check_output(['run-parts', '--lsbsysinit', '--test', str(self.root / 'etc/update-motd.d')], text=True)
|
||||
self.assertEqual(selected.splitlines(), [str(self.instance.path(install.HOOK))])
|
||||
|
||||
def test_failure_restores_previous_files(self):
|
||||
real_atomic = install.atomic
|
||||
def fail_static(path, data, mode=0o644):
|
||||
if path == self.instance.path('/etc/motd'):
|
||||
raise OSError('simulated disk error')
|
||||
real_atomic(path, data, mode)
|
||||
with patch.object(install, 'atomic', fail_static), self.assertRaises(OSError):
|
||||
self.instance.install(dict(status.DEFAULTS), False)
|
||||
self.assertTrue(self.header.exists())
|
||||
self.assertEqual((self.root / 'etc/motd').read_text(), 'original static MOTD')
|
||||
self.assertFalse(self.instance.path(install.BINARY).exists())
|
||||
self.assertFalse(self.instance.manifest.exists())
|
||||
for name in install.PAM_FILES:
|
||||
self.assertIn('pam_motd.so motd=/run/motd.dynamic', self.instance.path(name).read_text())
|
||||
self.assertNotIn('pam_exec.so', self.instance.path(name).read_text())
|
||||
|
||||
def test_dry_run_changes_nothing(self):
|
||||
self.instance.install(dict(status.DEFAULTS), True)
|
||||
self.assertTrue(self.header.exists())
|
||||
self.assertFalse(self.instance.manifest.exists())
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
Reference in new issue
Block a user