init
This commit is contained in:
@@ -0,0 +1,21 @@
|
||||
MIT License
|
||||
|
||||
Copyright (c) 2026 WM 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,177 @@
|
||||
# WM — Webman / Workerman Process Manager
|
||||
|
||||
一个由 **systemd** 托管进程的轻量级 PHP CLI。它不运行新的常驻守护程序,不会改动被管理项目的源码,并能通过一个命令管理几十个项目。
|
||||
|
||||
> **当前版本:0.1.2(CLI 配色与排版升级)**。已通过使用模拟 systemctl 的自动化测试,以及生成 Unit 的 `systemd-analyze verify` 语法检查;**未在你的真实服务器上执行 systemctl 启停**。建议先在测试服务器或非关键业务上试用。
|
||||
|
||||
## 系统要求
|
||||
|
||||
- Linux + systemd(支持 `Type=exec`,建议 systemd ≥ 246)
|
||||
- PHP CLI ≥ 8.2,启用 `proc_open`(推荐 PHP 8.4)
|
||||
- 使用 systemd 系统服务的管理操作需 root/sudo 权限
|
||||
- 仅管理本机服务,不支持 Windows、macOS systemd 或 Docker 内没有 systemd 的环境
|
||||
- 独立运行,**无 Composer 运行时依赖**
|
||||
|
||||
## 安装
|
||||
|
||||
下载 `wm.phar` 后:
|
||||
|
||||
```bash
|
||||
sudo install -m 0755 wm.phar /usr/local/bin/wm
|
||||
wm --version
|
||||
```
|
||||
|
||||
或直接使用源码:
|
||||
|
||||
```bash
|
||||
php bin/wm help
|
||||
php tests/run.php
|
||||
php -d phar.readonly=0 build/phar.php
|
||||
```
|
||||
|
||||
`wm help` 查看所有命令。不带参数在交互式终端中打开可操作的项目菜单。
|
||||
|
||||
## 终端界面(v0.1.2)
|
||||
|
||||
`wm ls` 和 `wm status <项目>` 采用简洁的彩色终端视图,**不清屏、不占据全屏、不常驻刷新**。运行状态与开机自启状态互相独立,既用颜色、也用符号区分:
|
||||
|
||||
| 信息 | 文本样式 | ANSI 颜色 | 含义 |
|
||||
|---|---|---|---|
|
||||
| 运行状态 | `● active` | 绿色 | 主服务正在运行 |
|
||||
| 运行状态 | `● failed` | 红色 | systemd 报告失败 |
|
||||
| 运行状态 | `○ inactive` | 灰色 | 未运行 |
|
||||
| 运行状态 | `◐ activating` | 黄色 | 正在启动 |
|
||||
| 开机自启 | `◆ enabled` | 青色 | 已启用开机自启(**不代表当前正在运行**) |
|
||||
| 开机自启 | `◇ disabled` | 灰色 | 未启用开机自启 |
|
||||
| 开机自启 | `◆ masked` | 红色 | 已屏蔽 |
|
||||
| 运行用户 | `root !` | 黄色 | 仅标识高权限运行用户,不阻止操作 |
|
||||
|
||||
`wm ls` 同时展示项目总数、active 数、enabled 数和非零的 failed 数。较窄终端会省略 `PATH` 一列,完整路径仍保留在 `wm info <项目>`、`wm ls --json` 中;宽终端(`COLUMNS >= 135`)会显示路径列。
|
||||
|
||||
```bash
|
||||
wm ls # TTY 自动彩色;非 TTY 默认不使用 ANSI
|
||||
wm status auth # 单服务详细信息(运行/自启分别着色)
|
||||
wm ls --color=always # 即使管道输出也强制颜色
|
||||
wm ls --color=never # 始终使用纯文本
|
||||
wm ls --no-ansi # 等价的纯文本选项,优先于 --color
|
||||
wm ls --json # 始终是纯 JSON,不含 ANSI 控制码
|
||||
```
|
||||
|
||||
`--color=auto` 为默认值,遵循标准输出是否为 TTY 及 `NO_COLOR` 环境变量。显式 `--color=always` 可以覆盖 `NO_COLOR`,但不能覆盖 `--no-ansi` 和 `--json`。不带参数的 `wm` 在交互式终端继续提供普通行式菜单,没有全屏 TUI 的额外依赖。
|
||||
|
||||
## 快速上手
|
||||
|
||||
**首先确认项目当前是否已手动启动**。如果已经通过 `php start.php start -d` 启动,请在接管前记录其运行信息、妥善停止原实例,并确认端口释放;不应把同一个应用重复启动。
|
||||
|
||||
```bash
|
||||
# 只做预览,绝不修改文件:
|
||||
sudo wm add auth /www/auth-center --user www-data --dry-run
|
||||
|
||||
# 注册已有 Webman 项目并设置开机启动(默认不立即启动):
|
||||
sudo wm add auth /www/auth-center --user www-data --enable
|
||||
|
||||
# 已确保旧实例停止后启动:
|
||||
sudo wm start auth
|
||||
|
||||
# 注册 Workerman(默认前台,由 systemd 托管):
|
||||
sudo wm add chat /opt/chat --type workerman --user www-data --enable
|
||||
|
||||
# 特权端口服务可以直接使用 root;无需额外开关或确认:
|
||||
sudo wm add dns /opt/dns --type workerman --user root --enable
|
||||
sudo wm start chat
|
||||
|
||||
# 如果你确认项目已经配置了 Worker::$pidFile,并希望用 daemon 模式:
|
||||
sudo wm add tasks /opt/tasks --type workerman --mode daemon \
|
||||
--pid-file /opt/tasks/runtime/workerman.pid --user www-data
|
||||
|
||||
wm ls
|
||||
wm info auth
|
||||
sudo wm restart auth
|
||||
sudo wm reload auth
|
||||
sudo wm restart --all
|
||||
sudo wm enable chat
|
||||
sudo wm disable chat
|
||||
wm logs auth --source stdout -f
|
||||
wm logs chat --source journal -f
|
||||
sudo wm doctor auth
|
||||
```
|
||||
|
||||
## 设计原则
|
||||
|
||||
| 配置项 | Webman 默认 | Workerman 默认 |
|
||||
|---|---|---|
|
||||
| 模式 | `daemon` | `foreground` |
|
||||
| ExecStart | `php start.php start -d` | `php start.php start` |
|
||||
| systemd Type | `forking` | `exec` |
|
||||
| PIDFile | `runtime/webman.pid` | 不需要 |
|
||||
| 平滑重载 | `SIGUSR1` 通知主进程 | `SIGUSR1` 通知主进程 |
|
||||
| 停止 | `SIGINT` 给主进程,超时清理 | 同左 |
|
||||
| 标准输出 | Webman 原生 `runtime/logs/stdout.log` | journald |
|
||||
|
||||
**注意:** Webman 的 `runtime/webman.pid` 是常见默认值,但可以在 `config/server.php` 中自定义;如果自定义过,请传入正确的 `--pid-file`。原生 Workerman 也有自动生成 PID 文件的行为,但文件位置随项目与版本可能不同;Workerman 的 `daemon` 模式要求明确指定 **和源码配置一致的** PID 路径,WM 不会擅自注入或重写 `Worker::$pidFile`。
|
||||
|
||||
`foreground` 模式启动 Workerman 时,Workerman 官方称其为 debug mode,主要区别是未 daemonize、标准输出处理方式不同;交给 systemd 后关闭 SSH 不会停止服务。**Webman 不建议随意切换到 foreground**,因为它的 monitor 插件通常会在无 `-d` 时监视文件并自动重载。PHP 应用自己的 `app.debug` 等设置不会因为 WM 自动切换。
|
||||
|
||||
## 命令
|
||||
|
||||
```text
|
||||
wm 交互式菜单(需要 TTY)
|
||||
wm add <name> <path> [options] 注册项目
|
||||
wm import <dir> --recursive 扫描并导入;默认需要确认
|
||||
wm import <dir> --recursive --dry-run
|
||||
wm ls 查看列表与状态
|
||||
wm info <name> 详细信息
|
||||
wm status [name] 状态
|
||||
wm start|stop|restart|reload <name>
|
||||
wm start|stop|restart|reload --all
|
||||
wm enable|disable <name> [--now]
|
||||
wm enable|disable --all
|
||||
wm logs <name> [-f] [--source auto|journal|stdout|workerman|app]
|
||||
wm doctor [name] 检测安装环境与注册服务
|
||||
wm sync [name] [--dry-run] 根据注册信息重建 service unit
|
||||
wm remove <name> --yes 注销服务,不删除项目源码或数据
|
||||
```
|
||||
|
||||
自动化脚本使用 `--json --no-interaction`,所有进程控制参数都经过数组方式执行,不借助 shell 拼接。`wm ls --json` 将完整输出状态数据。
|
||||
|
||||
## 路径与权限
|
||||
|
||||
默认:
|
||||
|
||||
```text
|
||||
/etc/wm/projects.d/<name>.json 项目注册信息
|
||||
/etc/systemd/system/wm-<name>.service 自动生成的 unit
|
||||
```
|
||||
|
||||
默认使用当前命令执行用户(包括 root),可使用 `--user 用户名` 显式指定任意已存在的 Linux 用户,**包括 root**。WM 不限制 root,也不要求 `--force` 或二次确认。`wm ls` 会对 root 运行的服务做醒目但非阻断的标识。须确保选定用户对项目源码有读取权限,对 `runtime/`、PID 和日志目录有写入权限。
|
||||
|
||||
目录可以分散在 `/srv/`、`/opt/`、`/www/` 等各处。`wm add` 不会执行你的应用代码,也不要求修改源码。**注册本身不会启动项目**,除非显式加 `--now`。
|
||||
|
||||
WM 检测 Unit 文件的专用标记,不会覆盖或删除外部手写 Unit。`remove` 会停用、注销对应 service,但永不删除原应用目录。
|
||||
|
||||
## 安全和迁移提醒
|
||||
|
||||
- **重要:** 已手动运行的项目应先用项目自己的正常 stop 命令停止。Webman daemon 模式会检查已知 PID 文件防止重复启动;Workerman foreground 模式没有统一可靠的方式识别所有历史实例,仍需人工确认端口、进程。批量 `start --all` 前尤其要核对。
|
||||
- 运行用户由管理员自行决定。特权端口服务(例如 DNS 53)可以显式指定 `--user root`;更细粒度的端口授权可另行设置,但 WM 不强制。`WM_CONFIG_DIR`、`WM_UNIT_DIR`、`WM_SYSTEMCTL`、`WM_JOURNALCTL` 环境变量只供开发和自动化测试;生产 sudo 环境不要接受不可信变量。
|
||||
- 注册项目只提供进程生命周期管理;不负责 PHP 扩展安装、端口分配、日志轮换、数据库健康检查或应用 HTTP 存活检测。
|
||||
- 异常重启仅涵盖 systemd 观察到的服务主进程退出;**业务进程卡死但主进程存活**不一定自动恢复。
|
||||
- 业务代码修改可以执行 `wm reload`;涉及 Worker 进程配置、Composer 依赖或 PHP 运行环境变更,建议 `wm restart`。
|
||||
- 如果修改了注册 JSON,执行 `sudo wm sync` 同步;不建议直接编辑生成的 unit。
|
||||
- 避免把 WM 用作面向公网的任意命令执行接口。未来如果加入 Web UI,需单独设计受限授权机制。
|
||||
|
||||
## 开发与测试
|
||||
|
||||
```bash
|
||||
php tests/run.php
|
||||
php -d phar.readonly=0 build/phar.php
|
||||
php dist/wm.phar help
|
||||
```
|
||||
|
||||
测试使用隔离临时目录 + 假 systemctl,不会启动或关闭主机服务。可以使用 `/usr/bin/systemd-analyze verify` 验证生成的 Unit 语法。
|
||||
|
||||
## 相关文档
|
||||
|
||||
- Webman 配置:[webman.workerman.net/doc/en/config.html](https://webman.workerman.net/doc/en/config.html)
|
||||
- Webman 启动说明:[webman.workerman.net/doc/en/attention.html](https://webman.workerman.net/doc/en/attention.html)
|
||||
- Workerman PID 文件:[manual.workerman.net/doc/en/worker/pid-file.html](https://manual.workerman.net/doc/en/worker/pid-file.html)
|
||||
- systemd service:[freedesktop.org/software/systemd/man/](https://www.freedesktop.org/software/systemd/man/latest/systemd.service.html)
|
||||
@@ -0,0 +1,11 @@
|
||||
#!/usr/bin/env php
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
$autoload = __DIR__ . '/../src/autoload.php';
|
||||
if (class_exists('Phar') && Phar::running(false) !== '') {
|
||||
$autoload = 'phar://' . Phar::running(false) . '/src/autoload.php';
|
||||
}
|
||||
require $autoload;
|
||||
exit((new WM\App())->run($argv));
|
||||
Executable
+6
@@ -0,0 +1,6 @@
|
||||
#!/usr/bin/env sh
|
||||
set -eu
|
||||
cd "$(dirname "$0")/.."
|
||||
php tests/run.php
|
||||
php -d phar.readonly=0 build/phar.php
|
||||
php dist/wm.phar --version
|
||||
@@ -0,0 +1,30 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
$root = dirname(__DIR__);
|
||||
$target = $root . '/dist/wm.phar';
|
||||
if (ini_get('phar.readonly')) {
|
||||
fwrite(STDERR, "PHAR creation is disabled; run php -d phar.readonly=0 build/phar.php\n");
|
||||
exit(1);
|
||||
}
|
||||
if (file_exists($target)) {
|
||||
unlink($target);
|
||||
}
|
||||
$phar = new Phar($target, 0, 'wm.phar');
|
||||
$phar->startBuffering();
|
||||
foreach (['bin/wm', 'src/autoload.php', 'src/App.php', 'src/Runtime.php', 'src/Registry.php', 'src/Project.php', 'src/Systemd.php', 'src/Process.php', 'src/UI.php'] as $path) {
|
||||
$phar->addFile($root . '/' . $path, $path);
|
||||
}
|
||||
$stub = <<<'STUB'
|
||||
#!/usr/bin/env php
|
||||
<?php
|
||||
Phar::mapPhar('wm.phar');
|
||||
require 'phar://wm.phar/bin/wm';
|
||||
__HALT_COMPILER();
|
||||
STUB;
|
||||
$phar->setStub($stub . "\n");
|
||||
$phar->setSignatureAlgorithm(Phar::SHA256);
|
||||
$phar->stopBuffering();
|
||||
chmod($target, 0755);
|
||||
echo "Built {$target} (" . number_format(filesize($target)) . " bytes)\n";
|
||||
@@ -0,0 +1,15 @@
|
||||
{
|
||||
"name": "laysense/wm",
|
||||
"description": "Lightweight systemd-backed CLI for Webman and Workerman",
|
||||
"type": "project",
|
||||
"license": "MIT",
|
||||
"require": {
|
||||
"php": ">=8.2",
|
||||
"ext-json": "*"
|
||||
},
|
||||
"bin": ["bin/wm"],
|
||||
"scripts": {
|
||||
"test": "@php tests/run.php",
|
||||
"build": "@php -d phar.readonly=0 build/phar.php"
|
||||
}
|
||||
}
|
||||
BIN
Binary file not shown.
+771
@@ -0,0 +1,771 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace WM;
|
||||
|
||||
use RuntimeException;
|
||||
use Throwable;
|
||||
|
||||
final class App
|
||||
{
|
||||
private Registry $registry;
|
||||
private Systemd $systemd;
|
||||
private UI $ui;
|
||||
private bool $nonInteractive = false;
|
||||
|
||||
public function __construct()
|
||||
{
|
||||
$this->registry = new Registry((string) (getenv('WM_CONFIG_DIR') ?: '/etc/wm/projects.d'));
|
||||
$this->systemd = new Systemd((string) (getenv('WM_UNIT_DIR') ?: '/etc/systemd/system'), (string) (getenv('WM_SYSTEMCTL') ?: '/usr/bin/systemctl'));
|
||||
$this->ui = new UI(false, false);
|
||||
}
|
||||
|
||||
/** @param list<string> $argv */
|
||||
public function run(array $argv): int
|
||||
{
|
||||
$args = array_slice($argv, 1);
|
||||
$json = false;
|
||||
try {
|
||||
$json = $this->extractFlag($args, '--json');
|
||||
$this->ui = new UI(false, $json); // Error output is valid even if option parsing fails.
|
||||
$plain = $this->extractFlag($args, '--no-ansi');
|
||||
$color = $this->extractColor($args);
|
||||
$this->nonInteractive = $this->extractFlag($args, '--no-interaction');
|
||||
$ansi = !$json && !$plain && ($color === 'always' || ($color === 'auto'
|
||||
&& getenv('NO_COLOR') === false && function_exists('stream_isatty') && stream_isatty(STDOUT)));
|
||||
$this->ui = new UI($ansi, $json);
|
||||
$command = array_shift($args);
|
||||
if ($command === null) {
|
||||
if (!$this->nonInteractive && $this->ui->interactive()) {
|
||||
return $this->menu();
|
||||
}
|
||||
return $this->help();
|
||||
}
|
||||
if (in_array($command, ['--help', '-h', 'help'], true)) {
|
||||
return $this->help();
|
||||
}
|
||||
if (in_array($command, ['--version', '-V', 'version'], true)) {
|
||||
$this->ui->output(['version' => '0.1.2']);
|
||||
if (!$json) {
|
||||
echo "WM 0.1.2\n";
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
[$pos, $opts] = $this->parse($args);
|
||||
return match ($command) {
|
||||
'add' => $this->add($pos, $opts),
|
||||
'ls', 'list' => $this->listing($pos, $opts),
|
||||
'status', 'info' => $this->status($pos, $opts, $command === 'info'),
|
||||
'start', 'stop', 'restart', 'reload', 'enable', 'disable' => $this->manage($command, $pos, $opts),
|
||||
'remove', 'rm' => $this->remove($pos, $opts),
|
||||
'sync' => $this->sync($pos, $opts),
|
||||
'doctor' => $this->doctor($pos, $opts),
|
||||
'logs' => $this->logs($pos, $opts),
|
||||
'import' => $this->import($pos, $opts),
|
||||
default => throw new RuntimeException("Unknown command: {$command}. Run 'wm help'."),
|
||||
};
|
||||
} catch (Throwable $e) {
|
||||
if ($json) {
|
||||
$this->ui->output(['ok' => false, 'error' => $e->getMessage()]);
|
||||
} else {
|
||||
fwrite(STDERR, $this->ui->color('✗ ', '1;31') . $e->getMessage() . "\n");
|
||||
}
|
||||
return 1;
|
||||
}
|
||||
}
|
||||
|
||||
/** @param list<string> $args */
|
||||
private function extractFlag(array &$args, string $flag): bool
|
||||
{
|
||||
$found = false;
|
||||
$args = array_values(array_filter($args, static function (string $arg) use ($flag, &$found): bool {
|
||||
if ($arg === $flag) {
|
||||
$found = true;
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}));
|
||||
return $found;
|
||||
}
|
||||
|
||||
/** @param list<string> $args */
|
||||
private function extractColor(array &$args): string
|
||||
{
|
||||
$color = 'auto';
|
||||
$filtered = [];
|
||||
for ($i = 0; $i < count($args); ++$i) {
|
||||
$arg = $args[$i];
|
||||
if ($arg !== '--color' && !str_starts_with($arg, '--color=')) {
|
||||
$filtered[] = $arg;
|
||||
continue;
|
||||
}
|
||||
$value = $arg === '--color' ? ($args[++$i] ?? '') : substr($arg, strlen('--color='));
|
||||
if (!in_array($value, ['auto', 'always', 'never'], true)) {
|
||||
throw new RuntimeException('--color must be auto, always, or never.');
|
||||
}
|
||||
$color = $value;
|
||||
}
|
||||
$args = $filtered;
|
||||
return $color;
|
||||
}
|
||||
|
||||
/** @param list<string> $args
|
||||
* @return array{0:list<string>,1:array<string,string|bool>}
|
||||
*/
|
||||
private function parse(array $args): array
|
||||
{
|
||||
$positionals = [];
|
||||
$options = [];
|
||||
$flags = ['all', 'now', 'enable', 'yes', 'dry-run', 'recursive', 'force', 'follow'];
|
||||
$values = ['type', 'php', 'user', 'entry', 'mode', 'pid-file', 'lines', 'source'];
|
||||
for ($i = 0; $i < count($args); ++$i) {
|
||||
$arg = $args[$i];
|
||||
if ($arg === '-f') {
|
||||
$options['follow'] = true;
|
||||
continue;
|
||||
}
|
||||
if ($arg === '--') {
|
||||
array_push($positionals, ...array_slice($args, $i + 1));
|
||||
break;
|
||||
}
|
||||
if (!str_starts_with($arg, '--')) {
|
||||
$positionals[] = $arg;
|
||||
continue;
|
||||
}
|
||||
[$key, $inline] = array_pad(explode('=', substr($arg, 2), 2), 2, null);
|
||||
if (in_array($key, $flags, true)) {
|
||||
if ($inline !== null) {
|
||||
throw new RuntimeException("Flag --{$key} does not accept a value.");
|
||||
}
|
||||
$options[$key] = true;
|
||||
} elseif (in_array($key, $values, true)) {
|
||||
$value = $inline ?? ($args[++$i] ?? null);
|
||||
if ($value === null || $value === '' || str_starts_with($value, '--')) {
|
||||
throw new RuntimeException("Missing value for --{$key}");
|
||||
}
|
||||
$options[$key] = $value;
|
||||
} else {
|
||||
throw new RuntimeException("Unknown option: --{$key}");
|
||||
}
|
||||
}
|
||||
return [$positionals, $options];
|
||||
}
|
||||
|
||||
/** @param array<string,string|bool> $opts
|
||||
* @param list<string> $allowed
|
||||
*/
|
||||
private function checkOptions(array $opts, array $allowed): void
|
||||
{
|
||||
foreach ($opts as $key => $_) {
|
||||
if (!in_array($key, $allowed, true)) {
|
||||
throw new RuntimeException("Unsupported option for this command: --{$key}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** @param list<string> $args */
|
||||
private function exactly(array $args, int $min, int $max): void
|
||||
{
|
||||
if (count($args) < $min || count($args) > $max) {
|
||||
throw new RuntimeException("Expected {$min}" . ($min === $max ? '' : "–{$max}") . ' argument(s). See wm help.');
|
||||
}
|
||||
}
|
||||
|
||||
private function help(): int
|
||||
{
|
||||
$help = <<<'HELP'
|
||||
WM — Webman / Workerman process manager v0.1.2
|
||||
|
||||
USAGE
|
||||
wm [command] [arguments] [options]
|
||||
|
||||
PROJECTS
|
||||
add <name> <path> Register a project; does not start by default
|
||||
import <dir> --recursive Discover and register projects
|
||||
ls List registered projects and live states
|
||||
info <name> Detailed project information
|
||||
status [name] Live status of one or all projects
|
||||
remove <name> Unregister (does not delete project files)
|
||||
sync [name] Regenerate systemd units from registry
|
||||
doctor [name] Validate project and server configuration
|
||||
|
||||
LIFECYCLE
|
||||
start|stop|restart|reload <name> Operate one project
|
||||
start|stop|restart|reload --all Operate all projects
|
||||
enable|disable <name> [--now] Manage auto-start (also start/stop with --now)
|
||||
enable|disable --all Manage all projects
|
||||
logs <name> [-f] Follow or view logs
|
||||
|
||||
ADD OPTIONS
|
||||
--type webman|workerman Auto-detected when possible
|
||||
--mode daemon|foreground Defaults: webman=daemon, workerman=foreground
|
||||
--php /path/php Default: php in PATH
|
||||
--user USER Service user (defaults to current user; root allowed)
|
||||
--entry start.php Entry file (relative to project)
|
||||
--pid-file /absolute/path Required for Workerman daemon mode
|
||||
--enable Enable start on boot
|
||||
--now Start service after registering
|
||||
--dry-run Show generated unit without writing
|
||||
|
||||
OTHER OPTIONS
|
||||
--yes Skip confirmation for remove/import
|
||||
--recursive Recursively scan directories for import
|
||||
--source auto|journal|stdout|workerman|app Logs source
|
||||
--lines 100 Number of log lines
|
||||
--json Structured output; disables ANSI
|
||||
--no-ansi Disable terminal colors
|
||||
--color auto|always|never Color policy (auto respects NO_COLOR and TTY)
|
||||
--no-interaction Never prompt for input
|
||||
|
||||
EXAMPLES
|
||||
sudo wm add auth /srv/auth --enable --now
|
||||
sudo wm add chat /srv/chat --type workerman --user www-data
|
||||
wm ls
|
||||
wm restart --all
|
||||
wm logs auth -f
|
||||
|
||||
Run 'wm' without arguments in a terminal for an interactive menu.
|
||||
HELP;
|
||||
$this->ui->output(['help' => $help]);
|
||||
if (!$this->ui->json) {
|
||||
echo $help . "\n";
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
/** @param list<string> $pos
|
||||
* @param array<string,string|bool> $opts
|
||||
*/
|
||||
private function add(array $pos, array $opts): int
|
||||
{
|
||||
$this->checkOptions($opts, ['type', 'php', 'user', 'entry', 'mode', 'pid-file', 'enable', 'now', 'dry-run']);
|
||||
$this->exactly($pos, 0, 2);
|
||||
$name = $pos[0] ?? null;
|
||||
$path = $pos[1] ?? null;
|
||||
if (($name === null || $path === null) && !$this->nonInteractive && $this->ui->interactive()) {
|
||||
$this->ui->title('Register a new project');
|
||||
$path ??= $this->ui->ask('Project directory');
|
||||
$name ??= $this->ui->ask('Project name', $this->suggestName($path));
|
||||
}
|
||||
if (!$name || !$path) {
|
||||
throw new RuntimeException('Usage: wm add <name> <path> [--type ...] [--enable] [--now]');
|
||||
}
|
||||
$settings = ['name' => $name, 'path' => $path];
|
||||
foreach (['type' => 'type', 'php' => 'php', 'user' => 'user', 'entry' => 'entry', 'mode' => 'mode', 'pid-file' => 'pid_file'] as $option => $key) {
|
||||
if (isset($opts[$option])) {
|
||||
$settings[$key] = $opts[$option];
|
||||
}
|
||||
}
|
||||
$project = Project::create($settings);
|
||||
$unit = $this->systemd->render($project);
|
||||
if (isset($opts['dry-run'])) {
|
||||
if ($this->ui->json) {
|
||||
$this->ui->output(['project' => $project, 'unit' => $unit, 'dry_run' => true]);
|
||||
} else {
|
||||
$this->ui->title('Dry-run · ' . $project['name']);
|
||||
$this->ui->line($unit);
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
$this->addProject($project, isset($opts['enable']), isset($opts['now']));
|
||||
$this->ui->output(['ok' => true, 'project' => $project, 'enabled' => isset($opts['enable']), 'started' => isset($opts['now'])]);
|
||||
$this->ui->ok("Registered {$project['name']} ({$project['type']}, {$project['mode']})");
|
||||
$pid = Project::existingPid($project);
|
||||
if ($pid !== null && !isset($opts['now'])) {
|
||||
$this->ui->warning("An existing process is using PID {$pid}; stop it cleanly before systemd takes over.");
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
/** @param array<string,mixed> $project */
|
||||
private function addProject(array $project, bool $enable, bool $now): void
|
||||
{
|
||||
$name = $project['name'];
|
||||
if ($now) {
|
||||
$this->assertNoUnmanagedProcess($project);
|
||||
}
|
||||
$this->locked(function () use ($project, $name): void {
|
||||
if (is_file($this->registry->file($name))) {
|
||||
throw new RuntimeException("Project already registered: {$name}");
|
||||
}
|
||||
$this->systemd->install($project);
|
||||
try {
|
||||
$this->registry->put($project);
|
||||
$this->systemd->reload();
|
||||
} catch (Throwable $e) {
|
||||
$this->registry->remove($name);
|
||||
$this->systemd->remove($name);
|
||||
try {
|
||||
$this->systemd->reload();
|
||||
} catch (Throwable) {
|
||||
}
|
||||
throw $e;
|
||||
}
|
||||
});
|
||||
if ($enable) {
|
||||
$this->systemd->must(['enable', $this->systemd->unitName($name)]);
|
||||
}
|
||||
if ($now) {
|
||||
$this->systemd->must(['start', $this->systemd->unitName($name)]);
|
||||
}
|
||||
}
|
||||
|
||||
/** @param array<string,mixed> $project */
|
||||
private function assertNoUnmanagedProcess(array $project): void
|
||||
{
|
||||
$pid = Project::existingPid($project);
|
||||
$state = $this->systemd->show($project['name']);
|
||||
if ($pid !== null && ($state['ActiveState'] ?? '') !== 'active') {
|
||||
throw new RuntimeException("Existing unmanaged PID {$pid} detected. Project registered, but not started. Stop the existing instance first.");
|
||||
}
|
||||
}
|
||||
|
||||
/** @param list<string> $pos
|
||||
* @param array<string,string|bool> $opts
|
||||
*/
|
||||
private function listing(array $pos, array $opts): int
|
||||
{
|
||||
$this->checkOptions($opts, []);
|
||||
$this->exactly($pos, 0, 0);
|
||||
$data = [];
|
||||
foreach ($this->registry->all() as $project) {
|
||||
$state = $this->systemd->show($project['name']);
|
||||
$data[] = [
|
||||
'name' => $project['name'],
|
||||
'type' => $project['type'],
|
||||
'user' => $project['user'],
|
||||
'mode' => $project['mode'],
|
||||
'state' => $state['ActiveState'] ?? 'unknown',
|
||||
'enabled' => $state['UnitFileState'] ?? 'unknown',
|
||||
'pid' => (int) ($state['MainPID'] ?? 0),
|
||||
'path' => $project['path'],
|
||||
];
|
||||
}
|
||||
$this->ui->output(['projects' => $data, 'total' => count($data)]);
|
||||
if (!$this->ui->json) {
|
||||
$this->ui->title('WM / Projects');
|
||||
$running = count(array_filter($data, static fn (array $p): bool => $p['state'] === 'active'));
|
||||
$enabled = count(array_filter($data, static fn (array $p): bool => in_array($p['enabled'], ['enabled', 'enabled-runtime'], true)));
|
||||
$failed = count(array_filter($data, static fn (array $p): bool => $p['state'] === 'failed'));
|
||||
$this->ui->projectSummary(count($data), $running, $enabled, $failed);
|
||||
// The full path stays in wm info / JSON; avoid an overly wide terminal table.
|
||||
$includePath = $this->ui->terminalWidth() >= 135;
|
||||
$rows = [];
|
||||
$styles = [];
|
||||
foreach ($data as $index => $p) {
|
||||
$root = $p['user'] === 'root';
|
||||
$rows[] = [
|
||||
$p['name'], $p['type'], $root ? 'root !' : $p['user'],
|
||||
$this->ui->stateLabel($p['state']),
|
||||
$this->ui->bootLabel($p['enabled']),
|
||||
(string) ($p['pid'] ?: '–'),
|
||||
];
|
||||
if ($includePath) {
|
||||
$rows[$index][] = $p['path'];
|
||||
}
|
||||
$styles[$index] = [0 => '1', 3 => $this->ui->stateStyle($p['state']), 4 => $this->ui->bootStyle($p['enabled'])];
|
||||
if ($root) {
|
||||
$styles[$index][2] = '1;33'; // Warning only; root is a supported run user.
|
||||
}
|
||||
}
|
||||
$columns = ['NAME', 'TYPE', 'USER', 'STATUS', 'AUTOSTART', 'PID'];
|
||||
if ($includePath) {
|
||||
$columns[] = 'PATH';
|
||||
}
|
||||
$this->ui->table($columns, $rows, $styles);
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
/** @param list<string> $pos
|
||||
* @param array<string,string|bool> $opts
|
||||
*/
|
||||
private function status(array $pos, array $opts, bool $detail): int
|
||||
{
|
||||
$this->checkOptions($opts, $detail ? [] : ['all']);
|
||||
$this->exactly($pos, $detail ? 1 : 0, isset($opts['all']) ? 0 : 1);
|
||||
if ($pos === []) {
|
||||
return $this->listing([], []);
|
||||
}
|
||||
$project = $this->registry->get($pos[0]);
|
||||
$state = $this->systemd->show($project['name']);
|
||||
$data = ['project' => $project, 'systemd' => $state, 'unit' => $this->systemd->unitPath($project['name'])];
|
||||
$this->ui->output($data);
|
||||
if (!$this->ui->json) {
|
||||
$this->ui->title(($detail ? 'WM / Info / ' : 'WM / Status / ') . $project['name']);
|
||||
$this->ui->section('Application');
|
||||
foreach (['type', 'path', 'entry', 'php', 'user', 'mode', 'pid_file'] as $key) {
|
||||
$value = (string) ($project[$key] ?? '–');
|
||||
$this->ui->keyValue($key, $key === 'user' && $value === 'root' ? 'root !' : $value,
|
||||
$key === 'user' && $value === 'root' ? '1;33' : null);
|
||||
}
|
||||
$this->ui->line();
|
||||
$this->ui->section('systemd');
|
||||
$this->ui->keyValue('ActiveState', $this->ui->stateLabel($state['ActiveState'] ?? 'unknown'),
|
||||
$this->ui->stateStyle($state['ActiveState'] ?? 'unknown'));
|
||||
$this->ui->keyValue('UnitFileState', $this->ui->bootLabel($state['UnitFileState'] ?? 'unknown'),
|
||||
$this->ui->bootStyle($state['UnitFileState'] ?? 'unknown'));
|
||||
foreach (['LoadState', 'SubState', 'MainPID', 'ActiveEnterTimestamp', 'NeedDaemonReload'] as $key) {
|
||||
$this->ui->keyValue($key, $state[$key] ?? '–');
|
||||
}
|
||||
$this->ui->line();
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
/** @param list<string> $pos
|
||||
* @param array<string,string|bool> $opts
|
||||
*/
|
||||
private function manage(string $action, array $pos, array $opts): int
|
||||
{
|
||||
$this->checkOptions($opts, ['all', 'now']);
|
||||
if (isset($opts['now']) && !in_array($action, ['enable', 'disable'], true)) {
|
||||
throw new RuntimeException('--now is only supported with enable/disable (or add).');
|
||||
}
|
||||
$all = isset($opts['all']);
|
||||
$this->exactly($pos, $all ? 0 : 1, $all ? 0 : 1);
|
||||
$projects = $all ? $this->registry->all() : [$this->registry->get($pos[0])];
|
||||
$results = [];
|
||||
$failed = false;
|
||||
foreach ($projects as $project) {
|
||||
$name = $project['name'];
|
||||
try {
|
||||
if (in_array($action, ['start', 'restart'], true) || ($action === 'enable' && isset($opts['now']))) {
|
||||
$this->assertNoUnmanagedProcess($project);
|
||||
}
|
||||
$args = [$action];
|
||||
if (isset($opts['now'])) {
|
||||
$args[] = '--now';
|
||||
}
|
||||
$args[] = $this->systemd->unitName($name);
|
||||
$this->systemd->must($args);
|
||||
$results[$name] = 'ok';
|
||||
$this->ui->ok("{$action}: {$name}");
|
||||
} catch (Throwable $e) {
|
||||
$failed = true;
|
||||
$results[$name] = $e->getMessage();
|
||||
if (!$this->ui->json) {
|
||||
$this->ui->warning("{$action} {$name}: {$e->getMessage()}");
|
||||
}
|
||||
}
|
||||
}
|
||||
$this->ui->output(['ok' => !$failed, 'action' => $action, 'results' => $results]);
|
||||
return $failed ? 1 : 0;
|
||||
}
|
||||
|
||||
/** @param list<string> $pos
|
||||
* @param array<string,string|bool> $opts
|
||||
*/
|
||||
private function remove(array $pos, array $opts): int
|
||||
{
|
||||
$this->checkOptions($opts, ['yes']);
|
||||
$this->exactly($pos, 1, 1);
|
||||
$name = $pos[0];
|
||||
$this->registry->get($name);
|
||||
if (is_file($this->systemd->unitPath($name)) && !$this->systemd->unitOwned($name)) {
|
||||
throw new RuntimeException('Cannot remove an unmanaged service unit.');
|
||||
}
|
||||
$state = $this->systemd->show($name);
|
||||
$active = in_array($state['ActiveState'] ?? '', ['active', 'activating', 'reloading'], true);
|
||||
if (!isset($opts['yes'])) {
|
||||
if ($this->nonInteractive || !$this->ui->interactive() || !$this->ui->confirm("Unregister {$name}" . ($active ? ' (running service will be stopped)' : '') . '?')) {
|
||||
throw new RuntimeException('Confirmation required. Use --yes to unregister.');
|
||||
}
|
||||
}
|
||||
if ($active) {
|
||||
$this->systemd->must(['stop', $this->systemd->unitName($name)]);
|
||||
}
|
||||
if (is_file($this->systemd->unitPath($name))) {
|
||||
$this->systemd->must(['disable', $this->systemd->unitName($name)]);
|
||||
}
|
||||
$this->locked(function () use ($name): void {
|
||||
$this->systemd->remove($name);
|
||||
$this->systemd->reload();
|
||||
$this->registry->remove($name);
|
||||
});
|
||||
$this->ui->output(['ok' => true, 'removed' => $name, 'source_deleted' => false]);
|
||||
$this->ui->ok("Unregistered {$name} (project source untouched)");
|
||||
return 0;
|
||||
}
|
||||
|
||||
/** @param list<string> $pos
|
||||
* @param array<string,string|bool> $opts
|
||||
*/
|
||||
private function sync(array $pos, array $opts): int
|
||||
{
|
||||
$this->checkOptions($opts, ['dry-run']);
|
||||
$this->exactly($pos, 0, 1);
|
||||
$projects = $pos ? [$this->registry->get($pos[0])] : $this->registry->all();
|
||||
$changes = [];
|
||||
$this->locked(function () use ($projects, &$changes, $opts): void {
|
||||
foreach ($projects as $project) {
|
||||
$file = $this->systemd->unitPath($project['name']);
|
||||
$expected = $this->systemd->render($project);
|
||||
$old = is_file($file) ? (string) file_get_contents($file) : null;
|
||||
if ($old !== $expected) {
|
||||
if ($old !== null && !$this->systemd->unitOwned($project['name'])) {
|
||||
throw new RuntimeException("Refusing to overwrite unmanaged unit: {$file}");
|
||||
}
|
||||
$changes[] = $project['name'];
|
||||
if (!isset($opts['dry-run'])) {
|
||||
$this->systemd->install($project);
|
||||
}
|
||||
}
|
||||
}
|
||||
if ($changes !== [] && !isset($opts['dry-run'])) {
|
||||
$this->systemd->reload();
|
||||
}
|
||||
});
|
||||
$this->ui->output(['ok' => true, 'changed' => $changes, 'dry_run' => isset($opts['dry-run'])]);
|
||||
$this->ui->ok(count($changes) . (isset($opts['dry-run']) ? ' unit(s) would change' : ' unit(s) synchronized'));
|
||||
return 0;
|
||||
}
|
||||
|
||||
/** @param list<string> $pos
|
||||
* @param array<string,string|bool> $opts
|
||||
*/
|
||||
private function doctor(array $pos, array $opts): int
|
||||
{
|
||||
$this->checkOptions($opts, []);
|
||||
$this->exactly($pos, 0, 1);
|
||||
$checks = [];
|
||||
$checks[] = ['check' => 'OS', 'ok' => PHP_OS_FAMILY === 'Linux', 'detail' => PHP_OS_FAMILY];
|
||||
$checks[] = ['check' => 'PHP CLI', 'ok' => PHP_VERSION_ID >= 80200, 'detail' => PHP_VERSION];
|
||||
$checks[] = ['check' => 'systemctl executable', 'ok' => is_executable((string) (getenv('WM_SYSTEMCTL') ?: '/usr/bin/systemctl')), 'detail' => (string) (getenv('WM_SYSTEMCTL') ?: '/usr/bin/systemctl')];
|
||||
$checks[] = ['check' => 'registry writable', 'ok' => Runtime::canCreateWithin($this->registry->directory), 'detail' => $this->registry->directory];
|
||||
$checks[] = ['check' => 'unit dir writable', 'ok' => is_writable($this->systemd->unitDirectory), 'detail' => $this->systemd->unitDirectory];
|
||||
$projects = $pos ? [$this->registry->get($pos[0])] : $this->registry->all();
|
||||
foreach ($projects as $p) {
|
||||
$prefix = $p['name'] . ': ';
|
||||
$checks[] = ['check' => $prefix . 'entry', 'ok' => is_file($p['path'] . '/' . $p['entry']), 'detail' => $p['entry']];
|
||||
$checks[] = ['check' => $prefix . 'PHP', 'ok' => is_executable($p['php']), 'detail' => $p['php']];
|
||||
$checks[] = ['check' => $prefix . 'user', 'ok' => !function_exists('posix_getpwnam') || posix_getpwnam($p['user']) !== false, 'detail' => $p['user']];
|
||||
if ($p['mode'] === 'daemon') {
|
||||
$checks[] = ['check' => $prefix . 'PID directory', 'ok' => is_dir(dirname($p['pid_file'])) && is_writable(dirname($p['pid_file'])), 'detail' => $p['pid_file']];
|
||||
}
|
||||
$checks[] = ['check' => $prefix . 'unit', 'ok' => $this->systemd->unitOwned($p['name']), 'detail' => $this->systemd->unitPath($p['name'])];
|
||||
}
|
||||
$ok = !in_array(false, array_column($checks, 'ok'), true);
|
||||
$this->ui->output(['ok' => $ok, 'checks' => $checks]);
|
||||
if (!$this->ui->json) {
|
||||
$this->ui->title('WM / Diagnostics');
|
||||
foreach ($checks as $check) {
|
||||
$this->ui->line(' ' . $this->ui->color($check['ok'] ? '✓' : '✗', $check['ok'] ? '32' : '31') . ' ' . str_pad($check['check'], 26) . ' ' . $check['detail']);
|
||||
}
|
||||
$this->ui->line();
|
||||
}
|
||||
return $ok ? 0 : 1;
|
||||
}
|
||||
|
||||
/** @param list<string> $pos
|
||||
* @param array<string,string|bool> $opts
|
||||
*/
|
||||
private function logs(array $pos, array $opts): int
|
||||
{
|
||||
$this->checkOptions($opts, ['source', 'lines', 'follow']);
|
||||
$this->exactly($pos, 1, 1);
|
||||
if ($this->ui->json) {
|
||||
throw new RuntimeException('Logs streaming does not support --json.');
|
||||
}
|
||||
$p = $this->registry->get($pos[0]);
|
||||
$lines = (string) ($opts['lines'] ?? '100');
|
||||
if (!preg_match('/^[1-9][0-9]{0,5}$/D', $lines)) {
|
||||
throw new RuntimeException('--lines must be a positive integer <= 999999');
|
||||
}
|
||||
$source = (string) ($opts['source'] ?? 'auto');
|
||||
if (!in_array($source, ['auto', 'journal', 'stdout', 'workerman', 'app'], true)) {
|
||||
throw new RuntimeException('Invalid logs source.');
|
||||
}
|
||||
$files = [
|
||||
'stdout' => $p['path'] . '/runtime/logs/stdout.log',
|
||||
'workerman' => $p['path'] . '/runtime/logs/workerman.log',
|
||||
'app' => $p['path'] . '/runtime/logs/webman.log',
|
||||
];
|
||||
if ($source === 'auto') {
|
||||
$source = $p['mode'] === 'daemon' && is_file($files['stdout']) ? 'stdout' : 'journal';
|
||||
}
|
||||
if ($source === 'journal') {
|
||||
$cmd = [(string) (getenv('WM_JOURNALCTL') ?: '/usr/bin/journalctl'), '-u', $this->systemd->unitName($p['name']), '--no-pager', '-n', $lines];
|
||||
} else {
|
||||
if (!is_file($files[$source])) {
|
||||
throw new RuntimeException("Log file does not exist: {$files[$source]}");
|
||||
}
|
||||
$cmd = ['/usr/bin/tail', '-n', $lines, $files[$source]];
|
||||
}
|
||||
if (isset($opts['follow'])) {
|
||||
$cmd[] = '-f';
|
||||
}
|
||||
$result = Process::run($cmd, true);
|
||||
return $result['code'] === 0 ? 0 : 1;
|
||||
}
|
||||
|
||||
/** @param list<string> $pos
|
||||
* @param array<string,string|bool> $opts
|
||||
*/
|
||||
private function import(array $pos, array $opts): int
|
||||
{
|
||||
$this->checkOptions($opts, ['recursive', 'dry-run', 'yes', 'user', 'php', 'mode', 'type']);
|
||||
$this->exactly($pos, 1, 1);
|
||||
$root = Runtime::canonicalDirectory($pos[0]);
|
||||
$directories = $this->scan($root, isset($opts['recursive']));
|
||||
$existing = $this->registry->all();
|
||||
$usedNames = array_column($existing, 'path', 'name');
|
||||
$usedPaths = array_column($existing, 'name', 'path');
|
||||
$found = [];
|
||||
$skipped = [];
|
||||
foreach ($directories as $dir) {
|
||||
if (isset($usedPaths[$dir])) {
|
||||
$skipped[] = "Already registered: {$dir}";
|
||||
continue;
|
||||
}
|
||||
$name = $this->suggestName($dir);
|
||||
$base = $name;
|
||||
$suffix = 2;
|
||||
while (isset($usedNames[$name])) {
|
||||
$name = substr($base, 0, 45) . '-' . $suffix++;
|
||||
}
|
||||
$settings = ['name' => $name, 'path' => $dir];
|
||||
foreach (['user' => 'user', 'php' => 'php', 'mode' => 'mode', 'type' => 'type'] as $option => $key) {
|
||||
if (isset($opts[$option])) {
|
||||
$settings[$key] = $opts[$option];
|
||||
}
|
||||
}
|
||||
try {
|
||||
$project = Project::create($settings);
|
||||
$found[] = $project;
|
||||
$usedNames[$name] = $dir;
|
||||
} catch (Throwable $e) {
|
||||
$skipped[] = "{$dir}: {$e->getMessage()}";
|
||||
}
|
||||
}
|
||||
if (isset($opts['dry-run'])) {
|
||||
$this->ui->output(['found' => $found, 'skipped' => $skipped, 'dry_run' => true]);
|
||||
if (!$this->ui->json) {
|
||||
$this->ui->title('Import preview');
|
||||
$this->ui->table(['NAME', 'TYPE', 'PATH'], array_map(static fn (array $p): array => [$p['name'], $p['type'], $p['path']], $found));
|
||||
foreach ($skipped as $reason) {
|
||||
$this->ui->warning($reason);
|
||||
}
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
if ($found !== [] && !isset($opts['yes'])) {
|
||||
if ($this->nonInteractive || !$this->ui->interactive() || !$this->ui->confirm('Register ' . count($found) . ' project(s)?')) {
|
||||
throw new RuntimeException('Confirmation required; use --yes or preview with --dry-run.');
|
||||
}
|
||||
}
|
||||
$added = [];
|
||||
$errors = [];
|
||||
foreach ($found as $p) {
|
||||
try {
|
||||
$this->addProject($p, false, false);
|
||||
$added[] = $p['name'];
|
||||
$this->ui->ok("Imported {$p['name']}");
|
||||
} catch (Throwable $e) {
|
||||
$errors[$p['name']] = $e->getMessage();
|
||||
}
|
||||
}
|
||||
$this->ui->output(['ok' => $errors === [], 'added' => $added, 'skipped' => $skipped, 'errors' => $errors]);
|
||||
return $errors === [] ? 0 : 1;
|
||||
}
|
||||
|
||||
/** @return list<string> */
|
||||
private function scan(string $root, bool $recursive): array
|
||||
{
|
||||
$results = [];
|
||||
$pending = [[$root, 0]];
|
||||
$ignored = ['.git', 'vendor', 'node_modules', 'runtime', 'cache', 'tests', 'test'];
|
||||
while ($pending !== []) {
|
||||
[$dir, $depth] = array_shift($pending);
|
||||
if (is_file($dir . '/start.php')) {
|
||||
$results[] = $dir;
|
||||
continue; // Never descend inside a project.
|
||||
}
|
||||
if (!$recursive || $depth >= 6) {
|
||||
continue;
|
||||
}
|
||||
foreach (scandir($dir) ?: [] as $name) {
|
||||
if ($name[0] === '.' || in_array($name, $ignored, true)) {
|
||||
continue;
|
||||
}
|
||||
$path = $dir . '/' . $name;
|
||||
if (is_dir($path) && !is_link($path)) {
|
||||
$pending[] = [$path, $depth + 1];
|
||||
}
|
||||
}
|
||||
}
|
||||
sort($results);
|
||||
return $results;
|
||||
}
|
||||
|
||||
private function suggestName(string $path): string
|
||||
{
|
||||
$name = strtolower(basename(rtrim($path, '/')));
|
||||
$name = (string) preg_replace('/[^a-z0-9_-]+/', '-', $name);
|
||||
$name = (string) preg_replace('/^[^a-z]+/', '', $name);
|
||||
return substr($name, 0, 40) ?: 'project';
|
||||
}
|
||||
|
||||
/** @param callable():void $fn */
|
||||
private function locked(callable $fn): void
|
||||
{
|
||||
Runtime::directory($this->registry->directory);
|
||||
$file = $this->registry->directory . '/.wm.lock';
|
||||
if (is_link($file)) {
|
||||
throw new RuntimeException('Refusing symlinked registry lock file');
|
||||
}
|
||||
$handle = fopen($file, 'c');
|
||||
if ($handle === false) {
|
||||
throw new RuntimeException("Cannot open registry lock: {$file}");
|
||||
}
|
||||
try {
|
||||
if (!flock($handle, LOCK_EX)) {
|
||||
throw new RuntimeException('Cannot acquire registry lock');
|
||||
}
|
||||
$fn();
|
||||
} finally {
|
||||
flock($handle, LOCK_UN);
|
||||
fclose($handle);
|
||||
}
|
||||
}
|
||||
|
||||
private function menu(): int
|
||||
{
|
||||
while (true) {
|
||||
$this->listing([], []);
|
||||
$this->ui->line(' ' . $this->ui->color('[a]', '1;36') . ' Add project '
|
||||
. $this->ui->color('[s]', '1;36') . ' Manage project '
|
||||
. $this->ui->color('[r]', '1;36') . ' Refresh '
|
||||
. $this->ui->color('[q]', '90') . ' Quit');
|
||||
$command = trim($this->ui->ask('Action', 'q'));
|
||||
if ($command === 'q') {
|
||||
return 0;
|
||||
}
|
||||
if ($command === 'r') {
|
||||
continue;
|
||||
}
|
||||
if ($command === 'a') {
|
||||
$this->add([], []);
|
||||
continue;
|
||||
}
|
||||
if ($command === 's') {
|
||||
$projects = array_column($this->registry->all(), 'name');
|
||||
$name = $this->ui->ask('Project name (' . implode(', ', $projects) . ')');
|
||||
if (!in_array($name, $projects, true)) {
|
||||
$this->ui->warning('Unknown project');
|
||||
continue;
|
||||
}
|
||||
$this->status([$name], [], true);
|
||||
$this->ui->line(' ' . $this->ui->color('start stop restart reload', '1;32')
|
||||
. ' ' . $this->ui->color('enable disable', '1;36'));
|
||||
$action = $this->ui->ask('Action (Enter to return)');
|
||||
if (in_array($action, ['start', 'stop', 'restart', 'reload', 'enable', 'disable'], true)) {
|
||||
$this->manage($action, [$name], []);
|
||||
}
|
||||
continue;
|
||||
}
|
||||
$this->ui->warning('Unknown action');
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,73 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace WM;
|
||||
|
||||
use RuntimeException;
|
||||
|
||||
final class Process
|
||||
{
|
||||
/** @param list<string> $argv
|
||||
* @return array{code:int,stdout:string,stderr:string}
|
||||
*/
|
||||
public static function run(array $argv, bool $stream = false): array
|
||||
{
|
||||
if ($argv === [] || !is_string($argv[0])) {
|
||||
throw new RuntimeException('Invalid command');
|
||||
}
|
||||
$pipes = [];
|
||||
$proc = @proc_open($argv, [0 => ['file', '/dev/null', 'r'], 1 => ['pipe', 'w'], 2 => ['pipe', 'w']], $pipes, null, null, ['bypass_shell' => true]);
|
||||
if (!is_resource($proc)) {
|
||||
throw new RuntimeException('Cannot launch command: ' . $argv[0]);
|
||||
}
|
||||
stream_set_blocking($pipes[1], false);
|
||||
stream_set_blocking($pipes[2], false);
|
||||
$out = '';
|
||||
$err = '';
|
||||
try {
|
||||
while (true) {
|
||||
$read = [];
|
||||
foreach ([1, 2] as $i) {
|
||||
if (!feof($pipes[$i])) {
|
||||
$read[] = $pipes[$i];
|
||||
}
|
||||
}
|
||||
if ($read === []) {
|
||||
break;
|
||||
}
|
||||
$write = null;
|
||||
$except = null;
|
||||
$ready = @stream_select($read, $write, $except, 1, 0);
|
||||
if ($ready === false) {
|
||||
break;
|
||||
}
|
||||
if ($ready === 0) {
|
||||
continue;
|
||||
}
|
||||
foreach ($read as $handle) {
|
||||
$chunk = fread($handle, 8192);
|
||||
if ($chunk === false || $chunk === '') {
|
||||
continue;
|
||||
}
|
||||
if ($handle === $pipes[1]) {
|
||||
$out .= $stream ? '' : $chunk;
|
||||
if ($stream) {
|
||||
fwrite(STDOUT, $chunk);
|
||||
}
|
||||
} else {
|
||||
$err .= $stream ? '' : $chunk;
|
||||
if ($stream) {
|
||||
fwrite(STDERR, $chunk);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
} finally {
|
||||
fclose($pipes[1]);
|
||||
fclose($pipes[2]);
|
||||
}
|
||||
$code = proc_close($proc);
|
||||
return ['code' => $code, 'stdout' => $out, 'stderr' => $err];
|
||||
}
|
||||
}
|
||||
+111
@@ -0,0 +1,111 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace WM;
|
||||
|
||||
use RuntimeException;
|
||||
|
||||
final class Project
|
||||
{
|
||||
public static function detectType(string $path): ?string
|
||||
{
|
||||
$composer = $path . '/composer.json';
|
||||
if (is_file($composer)) {
|
||||
$config = json_decode((string) file_get_contents($composer), true);
|
||||
$requires = is_array($config) ? array_merge($config['require'] ?? [], $config['require-dev'] ?? []) : [];
|
||||
if (isset($requires['workerman/webman']) || isset($requires['workerman/webman-framework']) || isset($requires['webman/webman'])) {
|
||||
return 'webman';
|
||||
}
|
||||
if (isset($requires['workerman/workerman']) || isset($requires['workerman/gateway-worker'])) {
|
||||
return 'workerman';
|
||||
}
|
||||
}
|
||||
if (is_file($path . '/config/server.php') && is_dir($path . '/app')) {
|
||||
return 'webman';
|
||||
}
|
||||
if (is_dir($path . '/vendor/workerman/webman') || is_dir($path . '/vendor/workerman/webman-framework')) {
|
||||
return 'webman';
|
||||
}
|
||||
if (is_dir($path . '/vendor/workerman/workerman')) {
|
||||
return 'workerman';
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/** @param array<string,mixed> $settings
|
||||
* @return array<string,mixed>
|
||||
*/
|
||||
public static function create(array $settings): array
|
||||
{
|
||||
$name = Runtime::assertName((string) ($settings['name'] ?? ''));
|
||||
$path = Runtime::canonicalDirectory((string) ($settings['path'] ?? ''));
|
||||
$type = (string) ($settings['type'] ?? self::detectType($path) ?? '');
|
||||
if (!in_array($type, ['webman', 'workerman'], true)) {
|
||||
throw new RuntimeException('Cannot detect framework. Specify --type webman|workerman.');
|
||||
}
|
||||
$mode = (string) ($settings['mode'] ?? ($type === 'webman' ? 'daemon' : 'foreground'));
|
||||
if (!in_array($mode, ['daemon', 'foreground'], true)) {
|
||||
throw new RuntimeException('Mode must be daemon or foreground.');
|
||||
}
|
||||
$entry = (string) ($settings['entry'] ?? 'start.php');
|
||||
Runtime::assertSafeValue($entry, 'entry');
|
||||
if (str_starts_with($entry, '/') || str_starts_with($entry, '-') || preg_match('~(^|/)\.\.?(/|$)~', $entry)) {
|
||||
throw new RuntimeException('Entry must be a relative PHP file within the project.');
|
||||
}
|
||||
$file = Runtime::canonicalFile($path . '/' . $entry);
|
||||
if (!str_starts_with($file, rtrim($path, '/') . '/') || pathinfo($file, PATHINFO_EXTENSION) !== 'php') {
|
||||
throw new RuntimeException('Entry must resolve to a PHP file inside the project.');
|
||||
}
|
||||
$entry = substr($file, strlen(rtrim($path, '/')) + 1);
|
||||
$php = Runtime::resolveExecutable((string) ($settings['php'] ?? 'php'));
|
||||
$user = (string) ($settings['user'] ?? Runtime::defaultUser());
|
||||
if (!preg_match('/^[a-z_][a-z0-9_-]*\$?$/iD', $user)) {
|
||||
throw new RuntimeException('Invalid Linux user name.');
|
||||
}
|
||||
if (function_exists('posix_getpwnam') && posix_getpwnam($user) === false) {
|
||||
throw new RuntimeException("Linux user does not exist: {$user}");
|
||||
}
|
||||
$pidFile = $settings['pid_file'] ?? null;
|
||||
if ($mode === 'daemon') {
|
||||
if ($pidFile === null && $type === 'webman') {
|
||||
$pidFile = $path . '/runtime/webman.pid';
|
||||
}
|
||||
if (!is_string($pidFile)) {
|
||||
throw new RuntimeException('Workerman daemon mode requires --pid-file matching Worker::$pidFile in your project.');
|
||||
}
|
||||
$pidFile = Runtime::validAbsolutePath($pidFile, 'PID file');
|
||||
} else {
|
||||
$pidFile = null;
|
||||
}
|
||||
return [
|
||||
'name' => $name,
|
||||
'type' => $type,
|
||||
'path' => $path,
|
||||
'entry' => $entry,
|
||||
'php' => $php,
|
||||
'user' => $user,
|
||||
'mode' => $mode,
|
||||
'pid_file' => $pidFile,
|
||||
'created_at' => gmdate('c'),
|
||||
];
|
||||
}
|
||||
|
||||
/** @param array<string,mixed> $project */
|
||||
public static function existingPid(array $project): ?int
|
||||
{
|
||||
$file = $project['pid_file'] ?? null;
|
||||
if (!is_string($file) || !is_file($file)) {
|
||||
return null;
|
||||
}
|
||||
$pidText = trim((string) @file_get_contents($file));
|
||||
if (!preg_match('/^[1-9][0-9]*$/D', $pidText)) {
|
||||
return null;
|
||||
}
|
||||
$pid = (int) $pidText;
|
||||
if ($pid <= 1 || !function_exists('posix_kill')) {
|
||||
return null;
|
||||
}
|
||||
return @posix_kill($pid, 0) || (function_exists('posix_get_last_error') && posix_get_last_error() === 1) ? $pid : null;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,65 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace WM;
|
||||
|
||||
use RuntimeException;
|
||||
|
||||
final class Registry
|
||||
{
|
||||
public function __construct(public readonly string $directory)
|
||||
{
|
||||
}
|
||||
|
||||
public function file(string $name): string
|
||||
{
|
||||
return $this->directory . '/' . Runtime::assertName($name) . '.json';
|
||||
}
|
||||
|
||||
/** @return array<string,mixed> */
|
||||
public function get(string $name): array
|
||||
{
|
||||
$file = $this->file($name);
|
||||
if (is_link($file)) {
|
||||
throw new RuntimeException("Refusing symlinked project registry: {$file}");
|
||||
}
|
||||
if (!is_file($file)) {
|
||||
throw new RuntimeException("Project not registered: {$name}");
|
||||
}
|
||||
$data = json_decode((string) file_get_contents($file), true, 512, JSON_THROW_ON_ERROR);
|
||||
if (!is_array($data) || ($data['name'] ?? null) !== $name) {
|
||||
throw new RuntimeException("Corrupt project registry: {$file}");
|
||||
}
|
||||
return $data;
|
||||
}
|
||||
|
||||
/** @return list<array<string,mixed>> */
|
||||
public function all(): array
|
||||
{
|
||||
$projects = [];
|
||||
foreach (glob($this->directory . '/*.json') ?: [] as $file) {
|
||||
if (is_link($file)) {
|
||||
throw new RuntimeException("Refusing symlinked project config: {$file}");
|
||||
}
|
||||
$name = basename($file, '.json');
|
||||
$projects[] = $this->get($name);
|
||||
}
|
||||
usort($projects, fn (array $a, array $b): int => strcmp($a['name'], $b['name']));
|
||||
return $projects;
|
||||
}
|
||||
|
||||
/** @param array<string,mixed> $project */
|
||||
public function put(array $project): void
|
||||
{
|
||||
Runtime::atomicWrite($this->file((string) $project['name']), json_encode($project, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE | JSON_THROW_ON_ERROR) . "\n", 0644);
|
||||
}
|
||||
|
||||
public function remove(string $name): void
|
||||
{
|
||||
$file = $this->file($name);
|
||||
if (is_file($file) && !unlink($file)) {
|
||||
throw new RuntimeException("Cannot remove project config: {$file}");
|
||||
}
|
||||
}
|
||||
}
|
||||
+134
@@ -0,0 +1,134 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace WM;
|
||||
|
||||
use RuntimeException;
|
||||
|
||||
final class Runtime
|
||||
{
|
||||
public static function directory(string $path, int $mode = 0755): void
|
||||
{
|
||||
if (!is_dir($path) && !mkdir($path, $mode, true) && !is_dir($path)) {
|
||||
throw new RuntimeException("Unable to create directory: {$path}");
|
||||
}
|
||||
}
|
||||
|
||||
public static function atomicWrite(string $file, string $contents, int $mode = 0644): void
|
||||
{
|
||||
self::directory(dirname($file));
|
||||
if (is_link($file)) {
|
||||
throw new RuntimeException("Refusing to overwrite symlink: {$file}");
|
||||
}
|
||||
$tmp = tempnam(dirname($file), '.wm-');
|
||||
if ($tmp === false) {
|
||||
throw new RuntimeException("Unable to prepare temporary file for {$file}");
|
||||
}
|
||||
try {
|
||||
if (file_put_contents($tmp, $contents, LOCK_EX) !== strlen($contents)) {
|
||||
throw new RuntimeException("Unable to write {$tmp}");
|
||||
}
|
||||
chmod($tmp, $mode);
|
||||
if (!rename($tmp, $file)) {
|
||||
throw new RuntimeException("Unable to replace {$file}");
|
||||
}
|
||||
} finally {
|
||||
if (file_exists($tmp)) {
|
||||
unlink($tmp);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public static function assertName(string $name): string
|
||||
{
|
||||
if (!preg_match('/^[a-z][a-z0-9_-]{0,47}$/D', $name)) {
|
||||
throw new RuntimeException('Invalid project name. Use 1–48 lowercase letters, digits, underscores or hyphens, starting with a letter.');
|
||||
}
|
||||
return $name;
|
||||
}
|
||||
|
||||
public static function assertSafeValue(string $value, string $label): string
|
||||
{
|
||||
if ($value === '' || preg_match('/[\x00-\x1F\x7F]/', $value)) {
|
||||
throw new RuntimeException("Invalid {$label}: empty/control characters are prohibited");
|
||||
}
|
||||
return $value;
|
||||
}
|
||||
|
||||
public static function canonicalFile(string $path): string
|
||||
{
|
||||
$resolved = realpath($path);
|
||||
if ($resolved === false || !is_file($resolved)) {
|
||||
throw new RuntimeException("File not found: {$path}");
|
||||
}
|
||||
return self::assertSafeValue($resolved, 'file');
|
||||
}
|
||||
|
||||
public static function canonicalDirectory(string $path): string
|
||||
{
|
||||
$resolved = realpath($path);
|
||||
if ($resolved === false || !is_dir($resolved)) {
|
||||
throw new RuntimeException("Directory not found: {$path}");
|
||||
}
|
||||
return self::assertSafeValue($resolved, 'directory');
|
||||
}
|
||||
|
||||
public static function validAbsolutePath(string $path, string $label): string
|
||||
{
|
||||
self::assertSafeValue($path, $label);
|
||||
if (!str_starts_with($path, '/') || preg_match('~(^|/)\.\.?(/|$)~', $path)) {
|
||||
throw new RuntimeException("{$label} must be an absolute path without . or .. segments");
|
||||
}
|
||||
return $path;
|
||||
}
|
||||
|
||||
public static function resolveExecutable(string $php): string
|
||||
{
|
||||
if (!str_contains($php, '/')) {
|
||||
$path = (string) getenv('PATH');
|
||||
foreach (explode(PATH_SEPARATOR, $path) as $directory) {
|
||||
if ($directory !== '' && is_executable($directory . '/' . $php)) {
|
||||
$php = $directory . '/' . $php;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
$php = self::canonicalFile($php);
|
||||
if (!is_executable($php)) {
|
||||
throw new RuntimeException("Not executable: {$php}");
|
||||
}
|
||||
return $php;
|
||||
}
|
||||
|
||||
public static function canCreateWithin(string $directory): bool
|
||||
{
|
||||
$cursor = $directory;
|
||||
while (!file_exists($cursor)) {
|
||||
$parent = dirname($cursor);
|
||||
if ($parent === $cursor) {
|
||||
return false;
|
||||
}
|
||||
$cursor = $parent;
|
||||
}
|
||||
return is_dir($cursor) && is_writable($cursor);
|
||||
}
|
||||
|
||||
public static function currentUser(): string
|
||||
{
|
||||
if (function_exists('posix_getpwuid')) {
|
||||
$info = posix_getpwuid(posix_geteuid());
|
||||
return (string) ($info['name'] ?? '');
|
||||
}
|
||||
return '';
|
||||
}
|
||||
|
||||
public static function defaultUser(): string
|
||||
{
|
||||
$current = self::currentUser();
|
||||
if ($current !== '') {
|
||||
return $current;
|
||||
}
|
||||
throw new RuntimeException('Unable to detect the current user; provide --user USER.');
|
||||
}
|
||||
}
|
||||
+163
@@ -0,0 +1,163 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace WM;
|
||||
|
||||
use RuntimeException;
|
||||
|
||||
final class Systemd
|
||||
{
|
||||
public const MARKER = '# Managed by WM; generated automatically; do not edit. Keep changes in /etc/wm/projects.d.';
|
||||
|
||||
public function __construct(public readonly string $unitDirectory, private readonly string $executable = '/usr/bin/systemctl')
|
||||
{
|
||||
}
|
||||
|
||||
public function unitName(string $name): string
|
||||
{
|
||||
return 'wm-' . Runtime::assertName($name) . '.service';
|
||||
}
|
||||
|
||||
public function unitPath(string $name): string
|
||||
{
|
||||
return $this->unitDirectory . '/' . $this->unitName($name);
|
||||
}
|
||||
|
||||
private static function escape(string $value): string
|
||||
{
|
||||
Runtime::assertSafeValue($value, 'systemd value');
|
||||
return str_replace(['\\', '"', '%', '$'], ['\\\\', '\\"', '%%', '$$'], $value);
|
||||
}
|
||||
|
||||
private static function token(string $value): string
|
||||
{
|
||||
return '"' . self::escape($value) . '"';
|
||||
}
|
||||
|
||||
/** @param array<string,mixed> $p */
|
||||
public function render(array $p): string
|
||||
{
|
||||
$name = Runtime::assertName((string) $p['name']);
|
||||
$type = $p['mode'] === 'daemon' ? 'forking' : 'exec';
|
||||
$command = self::token((string) $p['php']) . ' ' . self::token((string) $p['entry']) . ' start';
|
||||
if ($type === 'forking') {
|
||||
$command .= ' -d';
|
||||
}
|
||||
$pid = $type === 'forking' ? 'PIDFile=' . self::pathEscape((string) $p['pid_file']) . "\n" : '';
|
||||
return self::MARKER . "\n" . (<<<UNIT
|
||||
[Unit]
|
||||
Description=WM managed {$name} ({$p['type']})
|
||||
After=network-online.target
|
||||
Wants=network-online.target
|
||||
StartLimitIntervalSec=60
|
||||
StartLimitBurst=5
|
||||
|
||||
[Service]
|
||||
Type={$type}
|
||||
User={$p['user']}
|
||||
WorkingDirectory={$this->workingDirectory($p['path'])}
|
||||
ExecStart={$command}
|
||||
ExecReload=/bin/kill -USR1 \$MAINPID
|
||||
{$pid}Restart=on-failure
|
||||
RestartSec=5s
|
||||
KillSignal=SIGINT
|
||||
KillMode=mixed
|
||||
TimeoutStopSec=45s
|
||||
LimitNOFILE=65535
|
||||
StandardOutput=journal
|
||||
StandardError=journal
|
||||
|
||||
[Install]
|
||||
WantedBy=multi-user.target
|
||||
UNIT
|
||||
) . "\n";
|
||||
|
||||
}
|
||||
|
||||
private static function pathEscape(string $path): string
|
||||
{
|
||||
Runtime::validAbsolutePath($path, 'systemd path');
|
||||
// Paths are directive values, not Exec* arguments: no $-substitution.
|
||||
// Encode whitespace and quoting characters as systemd C escapes.
|
||||
return str_replace(['\\', ' ', '"', '%', '#'], ['\\\\', '\\x20', '\\x22', '%%', '\\x23'], $path);
|
||||
}
|
||||
|
||||
private function workingDirectory(string $path): string
|
||||
{
|
||||
return self::pathEscape($path);
|
||||
}
|
||||
|
||||
public function unitOwned(string $name): bool
|
||||
{
|
||||
$file = $this->unitPath($name);
|
||||
if (is_link($file)) {
|
||||
throw new RuntimeException("Refusing symlinked unit: {$file}");
|
||||
}
|
||||
if (!is_file($file)) {
|
||||
return false;
|
||||
}
|
||||
return str_starts_with((string) file_get_contents($file), self::MARKER);
|
||||
}
|
||||
|
||||
/** @param array<string,mixed> $p */
|
||||
public function install(array $p): void
|
||||
{
|
||||
$file = $this->unitPath($p['name']);
|
||||
if ((is_file($file) || is_link($file)) && !$this->unitOwned($p['name'])) {
|
||||
throw new RuntimeException("Refusing to overwrite unmanaged service unit: {$file}");
|
||||
}
|
||||
Runtime::atomicWrite($file, $this->render($p));
|
||||
}
|
||||
|
||||
public function remove(string $name): void
|
||||
{
|
||||
$file = $this->unitPath($name);
|
||||
if (is_file($file) || is_link($file)) {
|
||||
if (!$this->unitOwned($name)) {
|
||||
throw new RuntimeException("Refusing to delete unmanaged service unit: {$file}");
|
||||
}
|
||||
if (!unlink($file)) {
|
||||
throw new RuntimeException("Cannot delete service unit: {$file}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** @param list<string> $args */
|
||||
public function call(array $args, bool $stream = false): array
|
||||
{
|
||||
return Process::run(array_merge([$this->executable], $args), $stream);
|
||||
}
|
||||
|
||||
public function reload(): void
|
||||
{
|
||||
$this->must(['daemon-reload']);
|
||||
}
|
||||
|
||||
/** @param list<string> $args */
|
||||
public function must(array $args): string
|
||||
{
|
||||
$result = $this->call($args);
|
||||
if ($result['code'] !== 0) {
|
||||
throw new RuntimeException('systemctl ' . implode(' ', $args) . ': ' . trim($result['stderr'] ?: $result['stdout']));
|
||||
}
|
||||
return $result['stdout'];
|
||||
}
|
||||
|
||||
/** @return array<string,string> */
|
||||
public function show(string $name): array
|
||||
{
|
||||
$result = $this->call(['show', $this->unitName($name), '--no-pager', '--property=LoadState,ActiveState,SubState,MainPID,UnitFileState,ActiveEnterTimestamp,NeedDaemonReload']);
|
||||
if ($result['code'] !== 0) {
|
||||
return ['ActiveState' => 'unknown', 'LoadState' => 'unknown', 'error' => trim($result['stderr'])];
|
||||
}
|
||||
$properties = [];
|
||||
foreach (explode("\n", $result['stdout']) as $line) {
|
||||
if (str_contains($line, '=')) {
|
||||
[$k, $v] = explode('=', $line, 2);
|
||||
$properties[$k] = $v;
|
||||
}
|
||||
}
|
||||
return $properties;
|
||||
}
|
||||
}
|
||||
+256
@@ -0,0 +1,256 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace WM;
|
||||
|
||||
/** A small, dependency-free terminal renderer; never takes over the screen. */
|
||||
final class UI
|
||||
{
|
||||
public function __construct(public readonly bool $ansi, public readonly bool $json)
|
||||
{
|
||||
}
|
||||
|
||||
public function color(string $text, string $code): string
|
||||
{
|
||||
return $this->ansi ? "\033[{$code}m{$text}\033[0m" : $text;
|
||||
}
|
||||
|
||||
public function title(string $heading): void
|
||||
{
|
||||
if (!$this->json) {
|
||||
echo "\n" . $this->color('◆', '1;36') . ' ' . $this->color($heading, '1') . "\n\n";
|
||||
}
|
||||
}
|
||||
|
||||
public function section(string $heading): void
|
||||
{
|
||||
if (!$this->json) {
|
||||
echo ' ' . $this->color(strtoupper($heading), '1;90') . "\n";
|
||||
}
|
||||
}
|
||||
|
||||
public function keyValue(string $label, string $value, ?string $style = null): void
|
||||
{
|
||||
if (!$this->json) {
|
||||
echo ' ' . $this->color(str_pad($label, 22), '90') . ($style ? $this->color($value, $style) : $value) . "\n";
|
||||
}
|
||||
}
|
||||
|
||||
public function ok(string $message): void
|
||||
{
|
||||
if (!$this->json) {
|
||||
echo ' ' . $this->color('✓', '1;32') . " {$message}\n";
|
||||
}
|
||||
}
|
||||
|
||||
public function warning(string $message): void
|
||||
{
|
||||
if (!$this->json) {
|
||||
echo ' ' . $this->color('!', '1;33') . " {$message}\n";
|
||||
}
|
||||
}
|
||||
|
||||
public function line(string $message = ''): void
|
||||
{
|
||||
if (!$this->json) {
|
||||
echo $message . "\n";
|
||||
}
|
||||
}
|
||||
|
||||
public function output(mixed $data): void
|
||||
{
|
||||
if ($this->json) {
|
||||
echo json_encode($data, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_THROW_ON_ERROR) . "\n";
|
||||
}
|
||||
}
|
||||
|
||||
/** Run state and boot policy use different symbols AND colors. */
|
||||
public function stateLabel(string $state): string
|
||||
{
|
||||
return match ($state) {
|
||||
'active' => '● active',
|
||||
'inactive' => '○ inactive',
|
||||
'activating' => '◐ activating',
|
||||
'deactivating' => '◐ stopping',
|
||||
'reloading' => '↻ reloading',
|
||||
'failed' => '● failed',
|
||||
default => '○ ' . $state,
|
||||
};
|
||||
}
|
||||
|
||||
public function stateStyle(string $state): string
|
||||
{
|
||||
return match ($state) {
|
||||
'active' => '1;32', // green: currently running
|
||||
'failed' => '1;31', // red: failed
|
||||
'activating', 'deactivating' => '1;33',
|
||||
'reloading' => '1;35',
|
||||
default => '90', // gray: stopped/unknown
|
||||
};
|
||||
}
|
||||
|
||||
public function bootLabel(string $boot): string
|
||||
{
|
||||
return match ($boot) {
|
||||
'enabled' => '◆ enabled',
|
||||
'enabled-runtime' => '◆ enabled*',
|
||||
'disabled' => '◇ disabled',
|
||||
'masked', 'masked-runtime' => '◆ masked',
|
||||
'static' => '◇ static',
|
||||
'indirect' => '◇ indirect',
|
||||
default => '◇ ' . $boot,
|
||||
};
|
||||
}
|
||||
|
||||
public function bootStyle(string $boot): string
|
||||
{
|
||||
return match ($boot) {
|
||||
'enabled', 'enabled-runtime' => '1;36', // cyan: starts on boot, independent of running
|
||||
'masked', 'masked-runtime' => '1;31',
|
||||
'static', 'indirect', 'linked', 'linked-runtime' => '33',
|
||||
default => '90',
|
||||
};
|
||||
}
|
||||
|
||||
public function projectSummary(int $total, int $running, int $enabled, int $failed): void
|
||||
{
|
||||
if ($this->json) {
|
||||
return;
|
||||
}
|
||||
$parts = [
|
||||
$this->color($total . ' projects', '1'),
|
||||
$this->color('● ' . $running . ' active', '1;32'),
|
||||
$this->color('◆ ' . $enabled . ' enabled', '1;36'),
|
||||
];
|
||||
if ($failed > 0) {
|
||||
$parts[] = $this->color('● ' . $failed . ' failed', '1;31');
|
||||
}
|
||||
echo ' ' . implode($this->color(' · ', '90'), $parts) . "\n\n";
|
||||
}
|
||||
|
||||
/** Visible terminal width. COLUMNS is the portable, non-invasive override. */
|
||||
public function terminalWidth(): int
|
||||
{
|
||||
$columns = getenv('COLUMNS');
|
||||
if (is_string($columns) && ctype_digit($columns) && (int) $columns >= 40 && (int) $columns <= 1000) {
|
||||
return (int) $columns;
|
||||
}
|
||||
return 116;
|
||||
}
|
||||
|
||||
private function visibleWidth(string $text): int
|
||||
{
|
||||
if (function_exists('mb_strwidth')) {
|
||||
return mb_strwidth($text, 'UTF-8');
|
||||
}
|
||||
$chars = preg_split('//u', $text, -1, PREG_SPLIT_NO_EMPTY);
|
||||
if ($chars === false) {
|
||||
return strlen($text);
|
||||
}
|
||||
$width = 0;
|
||||
foreach ($chars as $char) {
|
||||
$width += preg_match('/[\p{Han}\p{Hiragana}\p{Katakana}\p{Hangul}\x{FF01}-\x{FF60}\x{FFE0}-\x{FFE6}]/u', $char) ? 2 : 1;
|
||||
}
|
||||
return $width;
|
||||
}
|
||||
|
||||
private function clip(string $text, int $maxWidth): string
|
||||
{
|
||||
if ($this->visibleWidth($text) <= $maxWidth) {
|
||||
return $text;
|
||||
}
|
||||
$chars = preg_split('//u', $text, -1, PREG_SPLIT_NO_EMPTY);
|
||||
if ($chars === false) {
|
||||
return substr($text, 0, max(0, $maxWidth - 3)) . '...';
|
||||
}
|
||||
$result = '';
|
||||
$width = 0;
|
||||
foreach ($chars as $char) {
|
||||
$next = $this->visibleWidth($char);
|
||||
if ($width + $next > $maxWidth - 1) {
|
||||
break;
|
||||
}
|
||||
$result .= $char;
|
||||
$width += $next;
|
||||
}
|
||||
return $result . '…';
|
||||
}
|
||||
|
||||
/** @param list<string> $columns
|
||||
* @param list<list<string>> $rows
|
||||
* @param array<int,array<int,string>> $styles ANSI styles keyed by row, then column
|
||||
*/
|
||||
public function table(array $columns, array $rows, array $styles = []): void
|
||||
{
|
||||
if ($this->json || $columns === []) {
|
||||
return;
|
||||
}
|
||||
$widths = [];
|
||||
foreach ($columns as $i => $column) {
|
||||
$widths[$i] = max(6, $this->visibleWidth($column));
|
||||
foreach ($rows as $row) {
|
||||
$widths[$i] = min(52, max($widths[$i], $this->visibleWidth($row[$i] ?? '')));
|
||||
}
|
||||
}
|
||||
$available = max(40, $this->terminalWidth() - 4);
|
||||
$overhead = (count($widths) - 1) * 3;
|
||||
$minWidths = array_map(fn (int $i): int => max(6, $this->visibleWidth($columns[$i])), array_keys($widths));
|
||||
// Reduce the widest flexible cell first, preserving column headings and status labels.
|
||||
while (array_sum($widths) + $overhead > $available) {
|
||||
$candidate = null;
|
||||
foreach ($widths as $i => $width) {
|
||||
if ($width <= $minWidths[$i]) {
|
||||
continue;
|
||||
}
|
||||
if ($candidate === null || $width > $widths[$candidate]) {
|
||||
$candidate = $i;
|
||||
}
|
||||
}
|
||||
if ($candidate === null) {
|
||||
break;
|
||||
}
|
||||
--$widths[$candidate];
|
||||
}
|
||||
$render = function (array $cells, array $cellStyles = []) use ($widths): string {
|
||||
$parts = [];
|
||||
foreach ($cells as $i => $cell) {
|
||||
$visible = $this->clip($cell, $widths[$i]);
|
||||
$padded = $visible . str_repeat(' ', max(0, $widths[$i] - $this->visibleWidth($visible)));
|
||||
$parts[] = isset($cellStyles[$i]) ? $this->color($padded, $cellStyles[$i]) : $padded;
|
||||
}
|
||||
return ' ' . implode(' ', $parts);
|
||||
};
|
||||
echo $this->color($render($columns), '1;90') . "\n";
|
||||
echo $this->color(' ' . str_repeat('─', array_sum($widths) + $overhead), '90') . "\n";
|
||||
foreach ($rows as $index => $row) {
|
||||
echo $render($row, $styles[$index] ?? []) . "\n";
|
||||
}
|
||||
if ($rows === []) {
|
||||
echo $this->color(' (no projects)', '90') . "\n";
|
||||
}
|
||||
echo "\n";
|
||||
}
|
||||
|
||||
public function interactive(): bool
|
||||
{
|
||||
return function_exists('stream_isatty') && stream_isatty(STDIN);
|
||||
}
|
||||
|
||||
public function ask(string $question, ?string $default = null): string
|
||||
{
|
||||
$suffix = $default !== null && $default !== '' ? " [{$default}]" : '';
|
||||
echo $this->color(' › ', '1;36') . $question . $this->color($suffix, '90') . ': ';
|
||||
$value = trim((string) fgets(STDIN));
|
||||
return $value === '' ? (string) $default : $value;
|
||||
}
|
||||
|
||||
public function confirm(string $question, bool $default = false): bool
|
||||
{
|
||||
$value = strtolower($this->ask($question . ($default ? ' [Y/n]' : ' [y/N]')));
|
||||
if ($value === '') {
|
||||
return $default;
|
||||
}
|
||||
return in_array($value, ['y', 'yes'], true);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
spl_autoload_register(static function (string $class): void {
|
||||
if (str_starts_with($class, 'WM\\')) {
|
||||
$file = __DIR__ . '/' . substr($class, 3) . '.php';
|
||||
if (is_file($file)) {
|
||||
require $file;
|
||||
}
|
||||
}
|
||||
});
|
||||
+235
@@ -0,0 +1,235 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
require dirname(__DIR__) . '/src/autoload.php';
|
||||
|
||||
use WM\Process;
|
||||
use WM\Systemd;
|
||||
|
||||
$work = sys_get_temp_dir() . '/wm-tests-' . getmypid();
|
||||
mkdir($work, 0700, true);
|
||||
mkdir("{$work}/projects", 0755);
|
||||
mkdir("{$work}/units", 0755);
|
||||
mkdir("{$work}/apps", 0755);
|
||||
$callLog = "{$work}/calls.log";
|
||||
$mock = "{$work}/systemctl";
|
||||
file_put_contents($mock, <<<'SH'
|
||||
#!/bin/sh
|
||||
printf '%s\n' "$*" >> "$WM_TEST_LOG"
|
||||
if [ "$1" = 'show' ]; then
|
||||
printf '%s\n' 'LoadState=loaded' "ActiveState=${WM_TEST_ACTIVE:-inactive}" 'SubState=dead' 'MainPID=0' "UnitFileState=${WM_TEST_ENABLED:-disabled}" 'NeedDaemonReload=no'
|
||||
exit 0
|
||||
fi
|
||||
if [ "$1" = 'daemon-reload' ] && [ "$WM_FAIL_RELOAD" = '1' ]; then
|
||||
echo 'Simulated failure' >&2
|
||||
exit 1
|
||||
fi
|
||||
exit 0
|
||||
SH);
|
||||
chmod($mock, 0755);
|
||||
putenv("WM_CONFIG_DIR={$work}/projects");
|
||||
putenv("WM_UNIT_DIR={$work}/units");
|
||||
putenv("WM_SYSTEMCTL={$mock}");
|
||||
putenv("WM_TEST_LOG={$callLog}");
|
||||
putenv('NO_COLOR=1');
|
||||
$php = PHP_BINARY;
|
||||
$wm = dirname(__DIR__) . '/bin/wm';
|
||||
$assertions = 0;
|
||||
function expect(bool $condition, string $reason): void
|
||||
{
|
||||
global $assertions;
|
||||
$assertions++;
|
||||
if (!$condition) {
|
||||
throw new RuntimeException("Assertion failed: {$reason}");
|
||||
}
|
||||
}
|
||||
function cli(array $args): array
|
||||
{
|
||||
global $php, $wm;
|
||||
return Process::run([$php, $wm, ...$args]);
|
||||
}
|
||||
function fixture(string $name, string $type): string
|
||||
{
|
||||
global $work;
|
||||
$dir = "{$work}/apps/{$name}";
|
||||
mkdir($dir, 0755, true);
|
||||
file_put_contents("{$dir}/start.php", "<?php /* test fixture */\n");
|
||||
file_put_contents("{$dir}/composer.json", json_encode(['require' => [$type === 'webman' ? 'workerman/webman' : 'workerman/workerman' => '^2.0']]));
|
||||
return $dir;
|
||||
}
|
||||
try {
|
||||
$auth = fixture('auth', 'webman');
|
||||
$chat = fixture('chat', 'workerman');
|
||||
mkdir($auth . '/runtime', 0755);
|
||||
$res = cli(['help']);
|
||||
expect($res['code'] === 0 && str_contains($res['stdout'], 'add <name>'), 'help');
|
||||
$res = cli(['add', 'auth', $auth, '--user', 'nobody', '--dry-run', '--json']);
|
||||
expect($res['code'] === 0, 'webman dry run');
|
||||
$preview = json_decode($res['stdout'], true);
|
||||
expect(str_contains($preview['unit'], 'Type=forking'), 'webman forking');
|
||||
expect(str_contains($preview['unit'], 'PIDFile=' . $auth . '/runtime/webman.pid'), 'webman PID path');
|
||||
expect(!is_file("{$work}/projects/auth.json"), 'dry run no writes');
|
||||
$res = cli(['add', 'auth', $auth, '--user', 'nobody', '--enable', '--now', '--json']);
|
||||
expect($res['code'] === 0, 'add webman enabled and started: ' . $res['stderr'] . $res['stdout']);
|
||||
expect(is_file("{$work}/projects/auth.json"), 'registry written');
|
||||
expect(is_file("{$work}/units/wm-auth.service"), 'unit written');
|
||||
expect(str_contains(file_get_contents($callLog), 'daemon-reload'), 'reload invoked');
|
||||
expect(str_contains(file_get_contents($callLog), 'enable wm-auth.service'), 'enable invoked');
|
||||
expect(str_contains(file_get_contents($callLog), 'start wm-auth.service'), 'start invoked');
|
||||
$res = cli(['add', 'chat', $chat, '--user', 'nobody', '--json']);
|
||||
expect($res['code'] === 0, 'add workerman');
|
||||
$unit = file_get_contents("{$work}/units/wm-chat.service");
|
||||
expect(str_contains($unit, 'Type=exec'), 'workerman foreground');
|
||||
expect(!str_contains($unit, 'PIDFile='), 'workerman no explicit pid');
|
||||
expect(str_contains($unit, 'ExecReload=/bin/kill -USR1 $MAINPID'), 'signal reload');
|
||||
$res = cli(['add', 'again', $chat, '--user', 'nobody', '--mode', 'daemon', '--json']);
|
||||
expect($res['code'] !== 0 && str_contains($res['stdout'], '--pid-file'), 'workerman daemon requires pid');
|
||||
$res = cli(['ls', '--json']);
|
||||
$listing = json_decode($res['stdout'], true);
|
||||
expect($listing['total'] === 2, 'list count');
|
||||
expect($listing['projects'][0]['name'] === 'auth', 'list sorted');
|
||||
// Color is a view concern: active=green, enabled=cyan, root=yellow; JSON stays unchanged.
|
||||
putenv('WM_TEST_ACTIVE=active');
|
||||
putenv('WM_TEST_ENABLED=enabled');
|
||||
$res = cli(['ls', '--color=always']);
|
||||
expect($res['code'] === 0, 'colored list works');
|
||||
expect(str_contains($res['stdout'], "\033[1;32m") && str_contains($res['stdout'], '● active'), 'active appears green');
|
||||
expect(str_contains($res['stdout'], "\033[1;36m") && str_contains($res['stdout'], '◆ enabled'), 'enabled appears cyan');
|
||||
expect(str_contains($res['stdout'], '2 projects') && str_contains($res['stdout'], '2 active') && str_contains($res['stdout'], '2 enabled'), 'status summary counts');
|
||||
$res = cli(['status', 'auth', '--color=always']);
|
||||
expect(str_contains($res['stdout'], '● active') && str_contains($res['stdout'], '◆ enabled'), 'status detail shares color scheme');
|
||||
$res = cli(['status', 'auth', '--no-ansi']);
|
||||
expect(str_contains($res['stdout'], 'ActiveEnterTimestamp '), 'long detail keys retain spacing');
|
||||
$res = cli(['ls', '--color=always', '--no-ansi']);
|
||||
expect(!str_contains($res['stdout'], "\033[") && str_contains($res['stdout'], '● active'), '--no-ansi suppresses all colors');
|
||||
$res = cli(['ls', '--color=always', '--json']);
|
||||
expect($res['code'] === 0 && !str_contains($res['stdout'], "\033[") && json_decode($res['stdout'], true)['projects'][0]['enabled'] === 'enabled', 'JSON always plain and structurally unchanged');
|
||||
$res = cli(['ls', '--color=invalid']);
|
||||
expect($res['code'] !== 0, 'invalid color option rejected');
|
||||
putenv('WM_TEST_ACTIVE=failed');
|
||||
putenv('WM_TEST_ENABLED=disabled');
|
||||
$res = cli(['ls', '--color=always']);
|
||||
expect(str_contains($res['stdout'], "\033[1;31m") && str_contains($res['stdout'], '● failed'), 'failed appears red');
|
||||
expect(str_contains($res['stdout'], '◇ disabled') && str_contains($res['stdout'], "\033[90m"), 'disabled appears gray');
|
||||
putenv('WM_TEST_ACTIVE');
|
||||
putenv('WM_TEST_ENABLED');
|
||||
putenv('COLUMNS=74');
|
||||
$res = cli(['ls', '--no-ansi']);
|
||||
expect(!str_contains($res['stdout'], 'PATH'), 'narrow terminal omits path column');
|
||||
putenv('COLUMNS=160');
|
||||
$res = cli(['ls', '--no-ansi']);
|
||||
expect(str_contains($res['stdout'], 'PATH'), 'wide terminal includes path column');
|
||||
putenv('COLUMNS');
|
||||
$res = cli(['sync', '--json']);
|
||||
expect($res['code'] === 0 && json_decode($res['stdout'], true)['changed'] === [], 'sync idempotent');
|
||||
$res = cli(['status', 'chat', '--json']);
|
||||
expect($res['code'] === 0 && json_decode($res['stdout'], true)['project']['mode'] === 'foreground', 'status');
|
||||
$res = cli(['add', 'Auth; rm -rf /', $auth, '--json']);
|
||||
expect($res['code'] !== 0, 'reject malicious name');
|
||||
$res = cli(['start', '--all', '--json']);
|
||||
expect($res['code'] === 0, 'start all');
|
||||
$res = cli(['status', '--all', '--json']);
|
||||
expect($res['code'] === 0 && json_decode($res['stdout'], true)['total'] === 2, 'status --all');
|
||||
$res = cli(['enable', 'auth', '--now', '--json']);
|
||||
expect($res['code'] === 0 && str_contains(file_get_contents($callLog), 'enable --now wm-auth.service'), 'enable --now');
|
||||
$res = cli(['disable', 'chat', '--now', '--json']);
|
||||
expect($res['code'] === 0 && str_contains(file_get_contents($callLog), 'disable --now wm-chat.service'), 'disable --now');
|
||||
$res = cli(['remove', 'chat', '--yes', '--json']);
|
||||
expect($res['code'] === 0, 'remove');
|
||||
expect(!is_file("{$work}/projects/chat.json") && !is_file("{$work}/units/wm-chat.service"), 'remove unit/config');
|
||||
expect(is_file("{$chat}/start.php"), 'remove preserves source');
|
||||
// A failed systemctl daemon-reload must roll back a new registration.
|
||||
putenv('WM_FAIL_RELOAD=1');
|
||||
$res = cli(['add', 'failcase', $chat, '--user', 'nobody', '--json']);
|
||||
expect($res['code'] !== 0, 'mock systemctl failure');
|
||||
expect(!is_file("{$work}/projects/failcase.json"), 'registry rollback');
|
||||
expect(!is_file("{$work}/units/wm-failcase.service"), 'unit rollback');
|
||||
putenv('WM_FAIL_RELOAD');
|
||||
// Detect a running PID outside systemd; refuse to start a duplicate.
|
||||
file_put_contents($auth . '/runtime/webman.pid', (string) getmypid());
|
||||
$res = cli(['restart', 'auth', '--json']);
|
||||
expect($res['code'] !== 0 && str_contains($res['stdout'], 'unmanaged PID'), 'existing unmanaged daemon protected');
|
||||
unlink($auth . '/runtime/webman.pid');
|
||||
// Recursive import preview never changes registry.
|
||||
$res = cli(['import', "{$work}/apps", '--recursive', '--dry-run', '--user', 'nobody', '--json']);
|
||||
expect($res['code'] === 0, 'import preview');
|
||||
$import = json_decode($res['stdout'], true);
|
||||
expect(count($import['found']) === 1 && $import['found'][0]['name'] === 'chat', 'import finds unregistered workerman');
|
||||
$res = cli(['import', "{$work}/apps", '--recursive', '--yes', '--user', 'nobody', '--json']);
|
||||
expect($res['code'] === 0 && in_array('chat', json_decode($res['stdout'], true)['added']), 'import registers');
|
||||
// Registry/sync should preserve a single source of truth and recover drift.
|
||||
file_put_contents("{$work}/units/wm-chat.service", Systemd::MARKER . "\n# drift\n");
|
||||
$res = cli(['sync', '--dry-run', '--json']);
|
||||
expect($res['code'] === 0 && in_array('chat', json_decode($res['stdout'], true)['changed']), 'sync preview detects drift');
|
||||
expect(str_contains(file_get_contents("{$work}/units/wm-chat.service"), "# drift"), 'sync preview does not write');
|
||||
file_put_contents("{$work}/units/wm-chat.service", "# broken\n");
|
||||
$res = cli(['sync', '--json']);
|
||||
expect($res['code'] !== 0, 'sync refuses unmanaged unit');
|
||||
unlink("{$work}/units/wm-chat.service");
|
||||
$res = cli(['sync', '--json']);
|
||||
expect($res['code'] === 0 && is_file("{$work}/units/wm-chat.service"), 'sync restores missing unit');
|
||||
// Root is a regular, explicitly permitted service account. It is highlighted, never blocked.
|
||||
$dns = fixture('dns', 'workerman');
|
||||
$res = cli(['add', 'dns', $dns, '--user', 'root', '--enable', '--now', '--json']);
|
||||
expect($res['code'] === 0, 'explicit root registration can enable and start without extra flags: ' . $res['stderr'] . $res['stdout']);
|
||||
$unit = file_get_contents("{$work}/units/wm-dns.service");
|
||||
expect(str_contains($unit, 'User=root'), 'systemd unit permits User=root');
|
||||
$res = cli(['ls', '--json']);
|
||||
$entries = json_decode($res['stdout'], true)['projects'];
|
||||
$rootRows = array_values(array_filter($entries, static fn (array $row): bool => $row['name'] === 'dns'));
|
||||
expect(count($rootRows) === 1 && $rootRows[0]['user'] === 'root', 'list JSON reports root user');
|
||||
$res = cli(['ls', '--no-ansi']);
|
||||
expect(str_contains($res['stdout'], 'root !'), 'list marks root without disrupting operation');
|
||||
$res = cli(['sync', 'dns', '--json']);
|
||||
expect($res['code'] === 0, 'sync accepts root account');
|
||||
$res = cli(['add', 'authroot', $auth, '--user', 'root', '--dry-run', '--json']);
|
||||
expect($res['code'] === 0 && str_contains(json_decode($res['stdout'], true)['unit'], 'User=root'), 'webman also allows root account');
|
||||
if (is_executable('/usr/bin/systemd-analyze')) {
|
||||
$res = Process::run(['/usr/bin/systemd-analyze', 'verify', "{$work}/units/wm-dns.service"]);
|
||||
expect($res['code'] === 0, 'systemd accepts User=root: ' . $res['stderr']);
|
||||
}
|
||||
$res = cli(['add', 'auto-user', $dns, '--dry-run', '--json']);
|
||||
expect($res['code'] === 0 && json_decode($res['stdout'], true)['project']['user'] === \WM\Runtime::currentUser(), 'unspecified service user defaults to current user');
|
||||
$dnsImport = fixture('dnsimport', 'workerman');
|
||||
$res = cli(['import', $dnsImport, '--user', 'root', '--yes', '--json']);
|
||||
expect($res['code'] === 0, 'import accepts root account');
|
||||
$imported = json_decode(file_get_contents("{$work}/projects/dnsimport.json"), true);
|
||||
expect($imported['user'] === 'root', 'import preserves root account');
|
||||
$res = cli(['add', 'chat2', $chat, '--user', 'nobody', '--mode', 'daemon', '--pid-file', $chat . '/custom.pid', '--json']);
|
||||
expect($res['code'] === 0 && str_contains(file_get_contents("{$work}/units/wm-chat2.service"), 'PIDFile=' . $chat . '/custom.pid'), 'explicit workerman daemon PID');
|
||||
$res = cli(['add', 'escape', $auth, '--entry', '../outside.php', '--user', 'nobody', '--json']);
|
||||
expect($res['code'] !== 0, 'reject path traversal');
|
||||
$special = fixture('special dir #1', 'webman');
|
||||
$res = cli(['add', 'special', $special, '--user', 'nobody', '--json']);
|
||||
expect($res['code'] === 0, 'spaces in directory supported');
|
||||
$unit = file_get_contents("{$work}/units/wm-special.service");
|
||||
expect(str_contains($unit, 'WorkingDirectory=' . str_replace([' ', '#'], ['\\x20', '\\x23'], $special)), 'systemd path escapes');
|
||||
if (is_executable('/usr/bin/systemd-analyze')) {
|
||||
$res = Process::run(['/usr/bin/systemd-analyze', 'verify', "{$work}/units/wm-special.service"]);
|
||||
expect($res['code'] === 0, 'systemd-analyze verify special: ' . $res['stderr']);
|
||||
}
|
||||
// The generated unit can be checked by systemd's own parser.
|
||||
if (is_executable('/usr/bin/systemd-analyze')) {
|
||||
$res = Process::run(['/usr/bin/systemd-analyze', 'verify', "{$work}/units/wm-auth.service"]);
|
||||
expect($res['code'] === 0, 'systemd-analyze verify: ' . $res['stderr']);
|
||||
}
|
||||
echo "PASS: {$assertions} assertions\n";
|
||||
} finally {
|
||||
// Test runner never performs real systemctl operations.
|
||||
$delete = static function (string $dir) use (&$delete): void {
|
||||
foreach (scandir($dir) ?: [] as $file) {
|
||||
if ($file === '.' || $file === '..') {
|
||||
continue;
|
||||
}
|
||||
$path = $dir . '/' . $file;
|
||||
if (is_dir($path) && !is_link($path)) {
|
||||
$delete($path);
|
||||
} else {
|
||||
unlink($path);
|
||||
}
|
||||
}
|
||||
rmdir($dir);
|
||||
};
|
||||
$delete($work);
|
||||
}
|
||||
Reference in New Issue
Block a user