diff --git a/lan-ups/.gitignore b/lan-ups/.gitignore
index 1bbf9e3..ccb3ba9 100644
--- a/lan-ups/.gitignore
+++ b/lan-ups/.gitignore
@@ -1,4 +1,6 @@
/.dotnet/
/artifacts/
+/dist/
**/bin/
**/obj/
+__pycache__/
diff --git a/lan-ups/AGENTS.md b/lan-ups/AGENTS.md
new file mode 100644
index 0000000..d3d4dae
--- /dev/null
+++ b/lan-ups/AGENTS.md
@@ -0,0 +1,3 @@
+# Versioning
+
+Bump the patch version in `VERSION` once for each change to LanUps, unless the user specifies a different version. Use that file as the version source for builds and packages.
diff --git a/lan-ups/VERSION b/lan-ups/VERSION
new file mode 100644
index 0000000..d917d3e
--- /dev/null
+++ b/lan-ups/VERSION
@@ -0,0 +1 @@
+0.1.2
diff --git a/lan-ups/desktop/Directory.Build.props b/lan-ups/desktop/Directory.Build.props
new file mode 100644
index 0000000..3ae52f8
--- /dev/null
+++ b/lan-ups/desktop/Directory.Build.props
@@ -0,0 +1,5 @@
+
+
+ $([System.IO.File]::ReadAllText('$(MSBuildThisFileDirectory)../VERSION').Trim())
+
+
diff --git a/lan-ups/desktop/README.md b/lan-ups/desktop/README.md
index 864170b..7b548a2 100644
--- a/lan-ups/desktop/README.md
+++ b/lan-ups/desktop/README.md
@@ -27,20 +27,33 @@ dotnet run --project src/LanUps.Agent
### 安装包
-项目根目录下的 `artifacts/native-installers-optimized/` 包含精简版原生安装包及 `SHA256SUMS`。Linux 使用 Native AOT,Windows 和 macOS 使用裁剪后的自包含发布。目标设备均无需单独安装 .NET。旧安装包保留在 `artifacts/native-installers/`。
+所有最终安装包及校验文件 `SHA256SUMS` 都写入项目根目录的 `dist/`。发布中间文件仍保存在 `artifacts/`。两个目录都由 Git 忽略。目标设备无需单独安装 .NET。
+
+Windows EXE 使用 Inno Setup 安装向导,可浏览或输入安装目录。默认安装到 `Program Files\LanUps`,升级时优先使用现有服务的安装目录。应用和后台服务使用同一目录,因此目标目录需要位于本机固定磁盘并限制普通用户写入。安装完成前会检查本地后台服务。可在 Windows「已安装的应用」卸载程序,卸载时会移除服务和登录启动任务,并保留数据目录。
+
+桌面程序在当前 Windows 用户会话或当前 Linux、macOS 用户范围内仅运行一个实例。从快捷方式再次打开时,会恢复已运行的窗口。
+
+设置页的「收到关机指令后立即关机」由后台服务保存。启用后,后台收到新的 FSD 信号会直接执行关机流程,跳过弹窗与 60 秒倒计时。默认仍使用确认和倒计时,模拟模式只记录模拟关机。
### 构建精简版
在已安装目标平台工具链的**构建机**上运行 `desktop/deploy/package.ps1 -Mode Aot -Targets `,或者通过 `dotnet publish -c Release -r --self-contained true -p:PublishAot=true -p:OptimizationPreference=Size` 分别发布 Agent 和 Desktop。Windows 需要 MSVC 原生链接工具,macOS 需要 Xcode 命令行工具,Linux 需要 Clang 和对应架构的系统库。用 `-Mode Trimmed` 可构建同样无需外置运行时的裁剪版本。把各目标的发布结果分别放在 `artifacts/installer-payload-optimized//Agent` 和 `Desktop` 后,运行 `desktop/deploy/package.ps1 -Mode Pack` 可一次打包所有平台。DEB 会从实际 ELF 产物记录最低 glibc 版本。
+Windows 打包机还需安装 Inno Setup 6.7,或通过环境变量 `LANUPS_ISCC` 指向已有的 `ISCC.exe`。编译器的 `Languages` 目录包含 `ChineseSimplified.isl` 时,安装包同时提供简体中文界面。用户电脑只需要生成的 EXE。
+
+Linux 构建机安装 `rpmbuild` 后,可以在已有发布产物的基础上运行 `python3 desktop/deploy/native_packages.py --rpm linux-x64`,一次生成 DEB 和 RPM。ARM64 使用 `linux-arm64`,也可以在 PowerShell 中使用 `desktop/deploy/package.ps1 -Mode Pack -Targets linux-x64 -Rpm`。RPM 面向 Fedora 系发行版,通过 `dnf install ./lanups-<版本>-1.<架构>.rpm` 安装。目标系统需满足构建产物要求的 glibc 版本。
+
+在镜像网络模式的 WSL 中同时运行 Windows 与 Linux 后台服务时,默认端口 `47183` 可能冲突。可为 Linux systemd 服务设置独立的 `LANUPS_AGENT_PORT`,并用相同变量启动 Linux 桌面端。
+
| 平台 | 安装入口 | 自动配置 |
| --- | --- | --- |
-| OpenWrt / LEDE | `opkg install ./lanups-router_0.1.0-1_all.ipk` | 安装 NUT 依赖,安装后配置 H1000M、LAN 监听和服务自启。UPS 暂不可读时,在下一次 USB 接入时自动重试 |
-| Windows x64 | 双击 `LanUps-Setup-win-x64.exe` 并确认管理员提示 | 安装到 Program Files,注册 Windows 服务、自启任务和桌面快捷方式 |
-| Debian / Ubuntu x64 或 ARM64 | 用软件安装器打开 `.deb`,或用 `sudo apt install ./lanups_0.1.0-1_<架构>.deb` | 安装后启用 systemd 服务和应用启动项,授权桌面账户读取本机凭据。首次安装后重新登录使用户组生效 |
+| OpenWrt / LEDE | `opkg install ./lanups-router_<版本>-1_all.ipk` | 安装 NUT 依赖,安装后配置 H1000M、LAN 监听和服务自启。UPS 暂不可读时,在下一次 USB 接入时自动重试 |
+| Windows x64 | 双击 `LanUps-Setup-win-x64.exe` 并确认管理员提示 | 按向导选择目录,注册 Windows 服务、自启任务和桌面快捷方式 |
+| Debian / Ubuntu x64 或 ARM64 | 用软件安装器打开 `.deb`,或用 `sudo apt install ./lanups_<版本>-1_<架构>.deb` | 安装后启用 systemd 服务和应用启动项,授权桌面账户读取本机凭据。首次安装后重新登录使用户组生效 |
+| Fedora 系 Linux x64 或 ARM64 | 用 `sudo dnf install ./lanups-<版本>-1.<架构>.rpm` | 安装后启用 systemd 服务和应用启动项。升级保留数据和服务,最终卸载时停用服务 |
| macOS Intel / Apple Silicon | 双击对应架构的 `.pkg`,由 macOS 安装器运行安装流程 | 安装 `.app` 和 LaunchDaemon,并为当前已登录用户配置 LaunchAgent。发布包未签名或公证 |
-首次安装默认模拟关机。确认流程后,Windows 可用 `-EnableShutdown` 重新运行 EXE,Linux 和 macOS 可通过服务配置加 `--enable-shutdown`。路由器执行 `lanups-router --enable-fsd` 才启用低电量联动。该模式只在读到 `OB` 和 `LB` 时发布 `FSD`,通信中断不会发布。策略不会主动关闭路由器或切断 UPS 输出。若 UPS 已发出 `FSD`,市电持续恢复约两分钟后,策略会重启 NUT 服务清除锁存状态。启用前应确认电池剩余时间足够覆盖客户端的 60 秒倒计时和关机时间。
+首次安装默认模拟关机。确认流程后,Windows 可用 `/ENABLESHUTDOWN=1` 重新运行 EXE,Linux 和 macOS 可通过服务配置加 `--enable-shutdown`。路由器执行 `lanups-router --enable-fsd` 才启用低电量联动。该模式只在读到 `OB` 和 `LB` 时发布 `FSD`,通信中断不会发布。策略不会主动关闭路由器或切断 UPS 输出。若 UPS 已发出 `FSD`,市电持续恢复约两分钟后,策略会重启 NUT 服务清除锁存状态。启用前应确认电池剩余时间足够覆盖客户端的 60 秒倒计时和关机时间。
### 手动部署
diff --git a/lan-ups/desktop/deploy/linux/configure-agent b/lan-ups/desktop/deploy/linux/configure-agent
new file mode 100644
index 0000000..bfbf377
--- /dev/null
+++ b/lan-ups/desktop/deploy/linux/configure-agent
@@ -0,0 +1,14 @@
+#!/bin/sh
+set -eu
+data=/etc/LanUps
+token=$data/agent.token
+group=lanups-operators
+install -d -m 0755 -o root -g root "$data"
+getent group "$group" >/dev/null || groupadd --system "$group"
+if [ ! -f "$token" ]; then LANUPS_AGENT_TOKEN="$token" /opt/lanups/agent/LanUps.Agent --provision; fi
+chown root:"$group" "$token"
+chmod 0640 "$token"
+
+operator=${SUDO_USER:-}
+if [ -z "$operator" ] || [ "$operator" = root ]; then operator=$(getent passwd 1000 | cut -d: -f1); fi
+if [ -n "$operator" ] && [ "$(id -u "$operator")" -ge 1000 ]; then usermod -a -G "$group" "$operator"; fi
diff --git a/lan-ups/desktop/deploy/linux/lanups.spec b/lan-ups/desktop/deploy/linux/lanups.spec
new file mode 100644
index 0000000..707fa72
--- /dev/null
+++ b/lan-ups/desktop/deploy/linux/lanups.spec
@@ -0,0 +1,51 @@
+%global debug_package %{nil}
+%global _build_id_links none
+%global __strip /bin/true
+%global __provides_exclude_from ^/opt/lanups/
+
+Name: lanups
+Version: %{lanups_version}
+Release: 1
+Summary: LAN UPS Agent and desktop monitor
+License: Unspecified
+Source0: lanups-payload.tar.gz
+Requires(post): coreutils, glibc-common, shadow-utils, systemd
+Requires(preun): systemd
+Requires(postun): systemd
+Requires: openssl-libs, libicu, libX11, libX11-xcb, libxcb, libXext, libXi, libXrandr, libICE, libSM, fontconfig, libglvnd-glx
+
+%description
+LanUps monitors a network UPS and provides a local desktop application and system service.
+
+%install
+mkdir -p "%{buildroot}/usr/lib/systemd/system"
+tar -xzf "%{SOURCE0}" -C "%{buildroot}"
+mv "%{buildroot}/lib/systemd/system/lanups-agent.service" "%{buildroot}/usr/lib/systemd/system/"
+
+%post
+set -e
+/usr/lib/lanups/configure-agent
+if [ -d /run/systemd/system ]; then
+ systemctl daemon-reload
+ systemctl enable lanups-agent.service
+ systemctl restart lanups-agent.service
+else
+ systemctl --root=/ enable lanups-agent.service
+fi
+
+%preun
+if [ "$1" -eq 0 ]; then
+ if [ -d /run/systemd/system ]; then systemctl stop lanups-agent.service || :; fi
+ systemctl --root=/ disable lanups-agent.service || :
+fi
+
+%postun
+if [ "$1" -eq 0 ] && [ -d /run/systemd/system ]; then systemctl daemon-reload || :; fi
+
+%files
+/opt/lanups
+/usr/lib/lanups
+/usr/lib/systemd/system/lanups-agent.service
+/etc/xdg/autostart/lanups-desktop.desktop
+/usr/share/applications/lanups-desktop.desktop
+/usr/share/icons/hicolor/256x256/apps/lanups.png
diff --git a/lan-ups/desktop/deploy/linux/postinst b/lan-ups/desktop/deploy/linux/postinst
index 2889d1c..6741f15 100644
--- a/lan-ups/desktop/deploy/linux/postinst
+++ b/lan-ups/desktop/deploy/linux/postinst
@@ -1,18 +1,7 @@
#!/bin/sh
set -eu
[ "${1:-}" = configure ] || exit 0
-data=/etc/LanUps
-token=$data/agent.token
-group=lanups-operators
-install -d -m 0755 -o root -g root "$data"
-getent group "$group" >/dev/null || groupadd --system "$group"
-if [ ! -f "$token" ]; then LANUPS_AGENT_TOKEN="$token" /opt/lanups/agent/LanUps.Agent --provision; fi
-chown root:"$group" "$token"
-chmod 0640 "$token"
-
-operator=${SUDO_USER:-}
-if [ -z "$operator" ] || [ "$operator" = root ]; then operator=$(getent passwd 1000 | cut -d: -f1); fi
-if [ -n "$operator" ] && [ "$(id -u "$operator")" -ge 1000 ]; then usermod -a -G "$group" "$operator"; fi
+/usr/lib/lanups/configure-agent
if command -v systemctl >/dev/null; then
systemctl enable lanups-agent.service
diff --git a/lan-ups/desktop/deploy/native/macos/main.go b/lan-ups/desktop/deploy/native/macos/main.go
index 5950207..2a7078c 100644
--- a/lan-ups/desktop/deploy/native/macos/main.go
+++ b/lan-ups/desktop/deploy/native/macos/main.go
@@ -11,10 +11,10 @@ import (
)
func main() {
- if len(os.Args) != 6 {
- log.Fatal("usage: macpack payload preinstall postinstall architecture output.pkg")
+ if len(os.Args) != 7 {
+ log.Fatal("usage: macpack payload preinstall postinstall architecture output.pkg version")
}
- root, prePath, postPath, architecture, output := os.Args[1], os.Args[2], os.Args[3], os.Args[4], os.Args[5]
+ root, prePath, postPath, architecture, output, version := os.Args[1], os.Args[2], os.Args[3], os.Args[4], os.Args[5], os.Args[6]
if architecture != pkg.ArchARM64 && architecture != pkg.ArchX8664 {
log.Fatal("invalid macOS architecture")
}
@@ -22,7 +22,7 @@ func main() {
check(err)
post, err := os.ReadFile(postPath)
check(err)
- component := pkg.NewPackage().WithIdentifier("local.lanups").WithName("LanUps").WithVersion("0.1.0").
+ component := pkg.NewPackage().WithIdentifier("local.lanups").WithName("LanUps").WithVersion(version).
WithPreInstallScript(pre).WithPostInstallScript(post)
check(filepath.WalkDir(root, func(path string, entry fs.DirEntry, err error) error {
if err != nil || entry.IsDir() {
@@ -40,7 +40,7 @@ func main() {
component.WithFileFromPath("/"+name, path).WithMode(mode).Add()
return nil
}))
- product, err := pkg.NewProduct().WithTitle("LanUps").WithIdentifier("local.lanups.product").WithVersion("0.1.0").
+ product, err := pkg.NewProduct().WithTitle("LanUps").WithIdentifier("local.lanups.product").WithVersion(version).
WithHostArchitectures(architecture).WithMinOSVersion("15.0").WithComponent(component).Build()
check(err)
file, err := os.Create(output)
diff --git a/lan-ups/desktop/deploy/native/windows/main.go b/lan-ups/desktop/deploy/native/windows/main.go
deleted file mode 100644
index 8dca24b..0000000
--- a/lan-ups/desktop/deploy/native/windows/main.go
+++ /dev/null
@@ -1,77 +0,0 @@
-//go:build windows
-
-package main
-
-import (
- "archive/zip"
- "fmt"
- "io"
- "io/fs"
- "os"
- "os/exec"
- "path/filepath"
-)
-
-func main() {
- if err := run(); err != nil {
- fmt.Fprintln(os.Stderr, "LanUps installation failed:", err)
- os.Exit(1)
- }
-}
-
-func run() error {
- self, err := os.Executable()
- if err != nil {
- return err
- }
- archive, err := zip.OpenReader(self)
- if err != nil {
- return err
- }
- defer archive.Close()
- stage, err := os.MkdirTemp("", "LanUps-Setup-")
- if err != nil {
- return err
- }
- defer os.RemoveAll(stage)
- for _, entry := range archive.File {
- path := filepath.FromSlash(entry.Name)
- if !fs.ValidPath(entry.Name) || !filepath.IsLocal(path) || !entry.Mode().IsRegular() {
- return fmt.Errorf("invalid installer entry: %q", entry.Name)
- }
- if err := extract(filepath.Join(stage, path), entry); err != nil {
- return err
- }
- }
- if len(os.Args) == 2 && os.Args[1] == "--verify" {
- fmt.Printf("Verified %d installer files\n", len(archive.File))
- return nil
- }
- setup := filepath.Join(stage, "Setup.ps1")
- args := append([]string{"-NoProfile", "-ExecutionPolicy", "Bypass", "-File", setup}, os.Args[1:]...)
- powershell := filepath.Join(os.Getenv("SystemRoot"), "System32", "WindowsPowerShell", "v1.0", "powershell.exe")
- command := exec.Command(powershell, args...)
- command.Stdout, command.Stderr = os.Stdout, os.Stderr
- return command.Run()
-}
-
-func extract(path string, entry *zip.File) error {
- if err := os.MkdirAll(filepath.Dir(path), 0o700); err != nil {
- return err
- }
- input, err := entry.Open()
- if err != nil {
- return err
- }
- defer input.Close()
- output, err := os.OpenFile(path, os.O_CREATE|os.O_EXCL|os.O_WRONLY, 0o600)
- if err != nil {
- return err
- }
- _, err = io.Copy(output, input)
- closeErr := output.Close()
- if err != nil {
- return err
- }
- return closeErr
-}
diff --git a/lan-ups/desktop/deploy/native_packages.py b/lan-ups/desktop/deploy/native_packages.py
index 09ff65f..a6d69b2 100644
--- a/lan-ups/desktop/deploy/native_packages.py
+++ b/lan-ups/desktop/deploy/native_packages.py
@@ -1,6 +1,6 @@
"""Build native system installers from the LanUps publish payloads."""
-import hashlib
+import argparse
import io
import os
from pathlib import Path
@@ -14,10 +14,10 @@ import tarfile
import tempfile
sys.dont_write_bytecode = True
-from package import DEPLOY, ICON, ROOT, binaries, tar_bytes, windows_package
+from package import DEPLOY, DIST, ICON, PAYLOAD, ROOT, VERSION, binaries, tar_bytes, write_checksums
NATIVE = DEPLOY / 'native'
-OUTPUT = Path(os.environ.get('LANUPS_INSTALLER_OUTPUT', ROOT / 'artifacts' / 'native-installers-optimized')).resolve()
+OUTPUT = DIST
def script(path):
@@ -41,7 +41,10 @@ def router_package():
control, data = io.BytesIO(), io.BytesIO()
with tarfile.open(fileobj=control, mode='w:gz') as archive:
for name in ('control', 'postinst', 'prerm'):
- tar_bytes(archive, './' + name, script(source / name), 0o644 if name == 'control' else 0o755)
+ content = script(source / name)
+ if name == 'control':
+ content += f'Version: {VERSION}-1\n'.encode('ascii')
+ tar_bytes(archive, './' + name, content, 0o644 if name == 'control' else 0o755)
with tarfile.open(fileobj=data, mode='w:gz') as archive:
directories = set()
for source_name, name in {
@@ -53,7 +56,7 @@ def router_package():
}.items():
tar_parents(archive, name, directories)
tar_bytes(archive, name, script(source / source_name), 0o755)
- path = OUTPUT / 'lanups-router_0.1.0-1_all.ipk'
+ path = OUTPUT / f'lanups-router_{VERSION}-1_all.ipk'
with tarfile.open(path, 'w:gz') as archive:
for name, value in (('debian-binary', b'2.0\n'), ('control.tar.gz', control.getvalue()), ('data.tar.gz', data.getvalue())):
tar_bytes(archive, './' + name, value, 0o644)
@@ -72,10 +75,8 @@ def write_ar_member(output, name, data):
output.write(b'\n')
-def linux_package(rid, stage):
+def linux_payload(rid, data):
source = DEPLOY / 'linux'
- architecture = {'linux-x64': 'amd64', 'linux-arm64': 'arm64'}[rid]
- control, data = stage / 'control.tar.gz', stage / 'data.tar.gz'
libc_version = (0, 0, 0)
with tarfile.open(data, 'w:gz', compresslevel=5) as archive:
directories = set()
@@ -97,17 +98,25 @@ def linux_package(rid, stage):
('./lib/systemd/system/lanups-agent.service', script(source / 'lanups-agent.service'), 0o644),
('./etc/xdg/autostart/lanups-desktop.desktop', launcher.replace(b'/opt/lanups/desktop/LanUps.Desktop --tray', b'/usr/lib/lanups/start-desktop'), 0o644),
('./usr/lib/lanups/start-desktop', script(source/'start-desktop'), 0o755),
+ ('./usr/lib/lanups/configure-agent', script(source/'configure-agent'), 0o755),
('./usr/share/applications/lanups-desktop.desktop', launcher.replace(b' --tray', b''), 0o644),
('./usr/share/icons/hicolor/256x256/apps/lanups.png', ICON.read_bytes(), 0o644),
):
tar_parents(archive, name, directories)
tar_bytes(archive, name, content, mode)
+ return libc_version
+
+
+def linux_deb(rid, stage, data, libc_version):
+ source = DEPLOY / 'linux'
+ architecture = {'linux-x64': 'amd64', 'linux-arm64': 'arm64'}[rid]
+ control = stage / 'control.tar.gz'
libc = 'libc6'
if libc_version[0]:
version = '.'.join(str(part) for part in (libc_version if libc_version[2] else libc_version[:2]))
libc = f'libc6 (>= {version})'
metadata = (
- 'Package: lanups\nVersion: 0.1.0-1\n' f'Architecture: {architecture}\n'
+ f'Package: lanups\nVersion: {VERSION}-1\nArchitecture: {architecture}\n'
'Maintainer: LanUps Project\nSection: utils\nPriority: optional\n'
f'Depends: adduser, passwd, init-system-helpers, {libc}, libgcc-s1, libstdc++6, libssl3 | libssl3t64, libx11-6, libx11-xcb1, libxcb1, libxext6, libxi6, libxrandr2, libice6, libsm6, libfontconfig1, libgl1, libicu72 | libicu74 | libicu76 | libicu77 | libicu78\n'
'Description: LAN UPS Agent and desktop monitor\n'
@@ -116,16 +125,32 @@ def linux_package(rid, stage):
tar_bytes(archive, './control', metadata.encode(), 0o644)
for name in ('postinst', 'prerm', 'postrm'):
tar_bytes(archive, './'+name, script(source / name), 0o755)
- path = OUTPUT / f'lanups_0.1.0-1_{architecture}.deb'
+ path = OUTPUT / f'lanups_{VERSION}-1_{architecture}.deb'
with path.open('wb') as output:
output.write(b'!\n')
for name, payload in (('debian-binary', b'2.0\n'), ('control.tar.gz', control), ('data.tar.gz', data)):
write_ar_member(output, name, payload)
control.unlink()
- data.unlink()
return path
+def linux_rpm(rid, data):
+ compiler = shutil.which('rpmbuild')
+ if not compiler:
+ raise RuntimeError('Install rpmbuild on the Linux packaging host to build RPM packages.')
+ architecture = {'linux-x64': 'x86_64', 'linux-arm64': 'aarch64'}[rid]
+ with tempfile.TemporaryDirectory(prefix='lanups-rpm-') as root:
+ top = Path(root)
+ sources = top / 'SOURCES'
+ sources.mkdir()
+ shutil.copyfile(data, sources / 'lanups-payload.tar.gz')
+ subprocess.run([compiler, '-bb', '--target', architecture,
+ '--define', f'_topdir {top}', '--define', f'lanups_version {VERSION}',
+ str(DEPLOY / 'linux' / 'lanups.spec')], check=True)
+ name = f'lanups-{VERSION}-1.{architecture}.rpm'
+ return Path(shutil.copyfile(top / 'RPMS' / architecture / name, OUTPUT / name))
+
+
def mac_package(rid, stage, builder):
source = DEPLOY / 'macos'
payload = stage / rid
@@ -139,7 +164,7 @@ def mac_package(rid, stage, builder):
(bundle / 'Resources').mkdir()
plist = dict(CFBundleExecutable='LanUps.Desktop', CFBundleIdentifier='local.lanups.desktop',
CFBundleName='LanUps', CFBundleDisplayName='局域网 UPS', CFBundlePackageType='APPL',
- CFBundleIconFile='ups.icns', CFBundleVersion='1', CFBundleShortVersionString='0.1.0')
+ CFBundleIconFile='ups.icns', CFBundleVersion=VERSION, CFBundleShortVersionString=VERSION)
(bundle / 'Info.plist').write_bytes(plistlib.dumps(plist))
icon = ICON.read_bytes()
(bundle / 'Resources/ups.icns').write_bytes(b'icns' + struct.pack('>I', len(icon)+16) + b'ic08' + struct.pack('>I', len(icon)+8) + icon)
@@ -151,11 +176,31 @@ def mac_package(rid, stage, builder):
(stage / name).write_bytes(script(source / name))
output = OUTPUT / f'LanUps-{rid}.pkg'
subprocess.run([str(builder), str(payload), str(stage/'preinstall'), str(stage/'postinstall'),
- 'arm64' if rid == 'osx-arm64' else 'x86_64', str(output)], check=True)
+ 'arm64' if rid == 'osx-arm64' else 'x86_64', str(output), VERSION], check=True)
return output
-def main(targets):
+def windows_package(rid):
+ compiler = os.environ.get('LANUPS_ISCC') or shutil.which('ISCC.exe')
+ if not compiler:
+ for env in ('ProgramFiles(x86)', 'ProgramFiles', 'LOCALAPPDATA'):
+ if root := os.environ.get(env):
+ candidate = Path(root) / 'Inno Setup 6' / 'ISCC.exe'
+ if candidate.is_file():
+ compiler = str(candidate)
+ break
+ if not compiler:
+ raise RuntimeError('Install Inno Setup 6 on the Windows build host or set LANUPS_ISCC to ISCC.exe.')
+ for kind in ('Agent', 'Desktop'):
+ next(binaries(rid, kind))
+ languages = Path(compiler).parent / 'Languages'
+ options = ['/DChineseMessages=1'] if (languages / 'ChineseSimplified.isl').is_file() else []
+ subprocess.run([compiler, *options, f'/DAppVersion={VERSION}', f'/DPayloadDir={PAYLOAD / rid}', f'/O{OUTPUT}',
+ f'/FLanUps-Setup-{rid}', str(DEPLOY / 'windows' / 'LanUps.iss')], check=True)
+ return OUTPUT / f'LanUps-Setup-{rid}.exe'
+
+
+def main(targets, rpm=False):
OUTPUT.mkdir(parents=True, exist_ok=True)
packages = [router_package()]
with tempfile.TemporaryDirectory(dir=OUTPUT.parent) as temp:
@@ -166,32 +211,26 @@ def main(targets):
subprocess.run(['go','build','-mod=readonly','-trimpath','-o',str(builder),'.'],cwd=NATIVE/'macos',check=True)
for rid in targets:
if rid.startswith('linux-'):
- output = linux_package(rid, stage)
+ data = stage / f'{rid}.tar.gz'
+ libc_version = linux_payload(rid, data)
+ output = linux_deb(rid, stage, data, libc_version)
+ if rpm:
+ print(linux_rpm(rid, data).name, flush=True)
elif rid.startswith('osx-'):
output = mac_package(rid, stage, builder)
elif rid == 'win-x64':
- stub = stage / 'setup.exe'
- env = dict(os.environ, GOOS='windows', GOARCH='amd64', CGO_ENABLED='0')
- subprocess.run(['go','build','-trimpath','-ldflags=-s -w','-o',str(stub),str(NATIVE/'windows/main.go')],cwd=ROOT,env=env,check=True)
- payload = windows_package(rid, stage / 'windows-payload.zip')
- output = OUTPUT / 'LanUps-Setup-win-x64.exe'
- with output.open('wb') as stream:
- for part in (stub,payload):
- with part.open('rb') as file:
- shutil.copyfileobj(file, stream)
- if os.name == 'nt':
- subprocess.run([str(output),'--verify'],check=True)
+ output = windows_package(rid)
else:
raise ValueError(f'Unsupported target: {rid}')
packages.append(output)
print(output.name, flush=True)
- archives = [path for path in OUTPUT.iterdir() if path.suffix in {'.exe', '.deb', '.pkg', '.ipk'}]
- with (OUTPUT / 'SHA256SUMS').open('w', encoding='ascii', newline='\n') as sums:
- for path in sorted(archives):
- with path.open('rb') as stream:
- sums.write(f"{hashlib.file_digest(stream, 'sha256').hexdigest()} {path.name}\n")
+ write_checksums()
print(packages[0].name, flush=True)
if __name__ == '__main__':
- main(sys.argv[1:])
+ parser = argparse.ArgumentParser(description=__doc__)
+ parser.add_argument('--rpm', action='store_true', help='Also build RPM installers for Linux targets')
+ parser.add_argument('targets', nargs='*', help='Desktop targets. Omit to build only the router package.')
+ args = parser.parse_args()
+ main(args.targets, args.rpm)
diff --git a/lan-ups/desktop/deploy/package.ps1 b/lan-ups/desktop/deploy/package.ps1
index 044f273..bca452f 100644
--- a/lan-ups/desktop/deploy/package.ps1
+++ b/lan-ups/desktop/deploy/package.ps1
@@ -1,10 +1,13 @@
param(
[string[]]$Targets = @('win-x64','linux-x64','linux-arm64','osx-x64','osx-arm64'),
- [ValidateSet('Aot','Trimmed','Pack')][string]$Mode = 'Pack'
+ [ValidateSet('Aot','Trimmed','Pack')][string]$Mode = 'Pack',
+ [switch]$Rpm
)
$ErrorActionPreference = 'Stop'
$root = (Resolve-Path (Join-Path $PSScriptRoot '..\..')).Path
-$localDotnet = Join-Path $root '.dotnet\dotnet.exe'
+$onWindows = $IsWindows -or $env:OS -eq 'Windows_NT'
+$dotnetFilename = if ($onWindows) { 'dotnet.exe' } else { 'dotnet' }
+$localDotnet = Join-Path (Join-Path $root '.dotnet') $dotnetFilename
$dotnet = if (Test-Path -LiteralPath $localDotnet) { $localDotnet } else { (Get-Command dotnet -ErrorAction Stop).Source }
if (Test-Path -LiteralPath $localDotnet) {
$env:DOTNET_CLI_HOME = Join-Path $root '.dotnet'
@@ -36,5 +39,7 @@ foreach ($rid in $Targets) {
} else { Move-Item -LiteralPath $temporary -Destination $output }
}
}
-& python (Join-Path $PSScriptRoot 'native_packages.py') @Targets
+$packageArguments = if ($Rpm) { @('--rpm') + $Targets } else { $Targets }
+$python = if ($onWindows) { 'python' } else { 'python3' }
+& $python (Join-Path $PSScriptRoot 'native_packages.py') @packageArguments
exit $LASTEXITCODE
diff --git a/lan-ups/desktop/deploy/package.py b/lan-ups/desktop/deploy/package.py
index 9876d80..e842279 100644
--- a/lan-ups/desktop/deploy/package.py
+++ b/lan-ups/desktop/deploy/package.py
@@ -8,12 +8,12 @@ import plistlib
import struct
import sys
import tarfile
-import zipfile
DEPLOY = Path(__file__).resolve().parent
ROOT = DEPLOY.parent.parent
+VERSION = (ROOT / 'VERSION').read_text(encoding='ascii').strip()
PAYLOAD = Path(os.environ.get('LANUPS_INSTALLER_PAYLOAD', ROOT / 'artifacts' / 'installer-payload-optimized')).resolve()
-DIST = ROOT / 'artifacts' / 'installers'
+DIST = ROOT / 'dist'
ICON = DEPLOY.parent / 'src' / 'LanUps.Desktop' / 'Assets' / 'ups.png'
@@ -42,6 +42,8 @@ def unix_package(rid):
tar_bytes(archive, 'architecture', rid.split('-', 1)[1].encode() + b'\n', 0o644)
folder = DEPLOY / ('macos' if mac else 'linux')
for sidecar in sorted(folder.iterdir()):
+ if sidecar.suffix == '.spec':
+ continue
tar_bytes(archive, sidecar.name, sidecar.read_bytes(), 0o644)
for kind in ('Agent', 'Desktop'):
prefix = 'LanUps.app/Contents/MacOS' if mac and kind == 'Desktop' else kind.lower()
@@ -54,7 +56,7 @@ def unix_package(rid):
if mac:
info = dict(CFBundleExecutable='LanUps.Desktop', CFBundleIdentifier='local.lanups.desktop',
CFBundleName='LanUps', CFBundleDisplayName='局域网 UPS', CFBundlePackageType='APPL',
- CFBundleIconFile='ups.icns', CFBundleVersion='1', CFBundleShortVersionString='0.1.0')
+ CFBundleIconFile='ups.icns', CFBundleVersion=VERSION, CFBundleShortVersionString=VERSION)
tar_bytes(archive, 'LanUps.app/Contents/Info.plist', plistlib.dumps(info), 0o644)
png = ICON.read_bytes()
image = b'icns' + struct.pack('>I', len(png) + 16) + b'ic08' + struct.pack('>I', len(png) + 8) + png
@@ -64,20 +66,18 @@ def unix_package(rid):
return path
-def windows_package(rid, path=None):
- path = path or DIST / f'LanUps-{rid}.zip'
- path.parent.mkdir(parents=True, exist_ok=True)
- with zipfile.ZipFile(path, 'w', zipfile.ZIP_DEFLATED, compresslevel=5) as archive:
- for filename in ('Setup.cmd', 'Setup.ps1', 'install.ps1'):
- script = (DEPLOY / 'windows' / filename).read_text(encoding='utf-8-sig')
- archive.writestr(filename, script.replace('\n', '\r\n').encode('utf-8-sig' if filename.endswith('.ps1') else 'ascii'))
- for kind in ('Agent', 'Desktop'):
- for source, filename, _ in binaries(rid, kind):
- archive.write(source, f'{kind}/{filename}')
- return path
+def write_checksums():
+ extensions = ('.exe', '.deb', '.rpm', '.pkg', '.ipk', '.tar.gz')
+ with (DIST / 'SHA256SUMS').open('w', encoding='ascii', newline='\n') as sums:
+ for path in sorted(DIST.iterdir()):
+ if path.is_file() and path.name.endswith(extensions):
+ with path.open('rb') as stream:
+ sums.write(f"{hashlib.file_digest(stream, 'sha256').hexdigest()} {path.name}\n")
def main(targets):
+ if any(rid.startswith('win-') for rid in targets):
+ raise ValueError('Use package.ps1 to build the Windows Inno Setup installer.')
DIST.mkdir(parents=True, exist_ok=True)
router = DIST / 'LanUps-openwrt.tar.gz'
with tarfile.open(router, 'w:gz') as archive:
@@ -85,13 +85,9 @@ def main(targets):
tar_bytes(archive, source.name, source.read_bytes().replace(b'\r\n', b'\n'), 0o755)
print(router.name, flush=True)
for rid in targets:
- path = windows_package(rid) if rid.startswith('win-') else unix_package(rid)
+ path = unix_package(rid)
print(path.name, flush=True)
- archives = sorted([*DIST.glob('LanUps-*.zip'), *DIST.glob('LanUps-*.tar.gz')])
- with (DIST / 'SHA256SUMS').open('w', encoding='ascii', newline='\n') as sums:
- for path in archives:
- with path.open('rb') as stream:
- sums.write(f"{hashlib.file_digest(stream, 'sha256').hexdigest()} {path.name}\n")
+ write_checksums()
if __name__ == '__main__':
diff --git a/lan-ups/desktop/deploy/router/control b/lan-ups/desktop/deploy/router/control
index a92e35b..7a6ee55 100644
--- a/lan-ups/desktop/deploy/router/control
+++ b/lan-ups/desktop/deploy/router/control
@@ -1,5 +1,4 @@
Package: lanups-router
-Version: 0.1.0-1
Architecture: all
Maintainer: LanUps Project
Section: utils
diff --git a/lan-ups/desktop/deploy/router/lanups-hotplug b/lan-ups/desktop/deploy/router/lanups-hotplug
index 7890343..4cddb61 100644
--- a/lan-ups/desktop/deploy/router/lanups-hotplug
+++ b/lan-ups/desktop/deploy/router/lanups-hotplug
@@ -2,13 +2,31 @@
# Sourced by OpenWrt hotplug. A separate process owns the retry lock.
case "${ACTION:-}:${PRODUCT:-}" in
add:665/5161/*|add:0665/5161/*)
- if [ -f /etc/lanups/pending ] && [ -n "${DEVNAME:-}" ]; then
+ if [ -n "${DEVNAME:-}" ]; then
(
lock=/var/run/lanups-router-setup.lock
mkdir "$lock" 2>/dev/null || exit 0
trap 'rmdir "$lock"' EXIT
- sleep 2
- LANUPS_SKIP_PACKAGES=1 /usr/sbin/lanups-router 2>&1 | logger -t lanups-router
+ sleep 3
+ if [ -f /etc/lanups/pending ]; then
+ LANUPS_SKIP_PACKAGES=1 /usr/sbin/lanups-router 2>&1 | logger -t lanups-router
+ exit
+ fi
+ [ ! -e /var/run/killpower ] && [ ! -e /var/run/nut/disable-hotplug ] || exit 0
+ case "$(uci -q get nut_server.h1000m.driver)" in
+ blazer_usb|nutdrv_qx) ;;
+ *) exit 0 ;;
+ esac
+ case "$DEVNAME" in bus/usb/*) ;; *) exit 0 ;; esac
+ [ -c "/dev/$DEVNAME" ] || exit 0
+ chown nut:nut "/dev/$DEVNAME" && chmod 0660 "/dev/$DEVNAME" || exit 1
+ for check in 1 2 3; do
+ upsc h1000m@127.0.0.1 ups.status >/dev/null 2>&1 && exit 0
+ sleep 2
+ done
+ [ ! -e /var/run/killpower ] && [ ! -e /var/run/nut/disable-hotplug ] || exit 0
+ logger -t lanups-router 'H1000M reconnected but NUT is offline; restarting nut-server'
+ /etc/init.d/nut-server restart
) /dev/null 2>&1 &
fi
;;
diff --git a/lan-ups/desktop/deploy/windows/LanUps.iss b/lan-ups/desktop/deploy/windows/LanUps.iss
new file mode 100644
index 0000000..d4b32b0
--- /dev/null
+++ b/lan-ups/desktop/deploy/windows/LanUps.iss
@@ -0,0 +1,105 @@
+[Setup]
+AppId=LanUps.Desktop
+AppName=LanUps
+AppVersion={#AppVersion}
+VersionInfoVersion={#AppVersion}
+AppPublisher=LanUps Project
+DefaultDirName={code:DefaultInstallDirectory}
+DefaultGroupName=LanUps
+DisableWelcomePage=no
+DisableDirPage=no
+DisableProgramGroupPage=yes
+ArchitecturesAllowed=x64compatible
+ArchitecturesInstallIn64BitMode=x64compatible
+PrivilegesRequired=admin
+WizardStyle=modern
+SetupIconFile=..\..\src\LanUps.Desktop\Assets\ups.ico
+Compression=lzma2
+SolidCompression=yes
+UninstallDisplayIcon={app}\Desktop\LanUps.Desktop.exe
+SetupLogging=yes
+
+[Languages]
+Name: "en"; MessagesFile: "compiler:Default.isl"
+#ifdef ChineseMessages
+Name: "zhcn"; MessagesFile: "compiler:Languages\ChineseSimplified.isl"
+#endif
+
+[Files]
+Source: "deployment.ps1"; Flags: dontcopy
+Source: "{#PayloadDir}\Agent\*"; DestDir: "{app}\Agent"; Excludes: "*.pdb,*.dbg"; Flags: ignoreversion recursesubdirs createallsubdirs
+Source: "{#PayloadDir}\Desktop\*"; DestDir: "{app}\Desktop"; Excludes: "*.pdb,*.dbg"; Flags: ignoreversion recursesubdirs createallsubdirs
+Source: "deployment.ps1"; DestDir: "{app}"; Flags: ignoreversion
+Source: "install.ps1"; DestDir: "{app}"; Flags: ignoreversion
+
+[Icons]
+Name: "{autoprograms}\LanUps"; Filename: "{app}\Desktop\LanUps.Desktop.exe"; WorkingDir: "{app}\Desktop"
+Name: "{autodesktop}\局域网 UPS"; Filename: "{app}\Desktop\LanUps.Desktop.exe"; WorkingDir: "{app}\Desktop"
+
+[CustomMessages]
+en.DeploymentFailed=LanUps service deployment failed. See %%ProgramData%%\LanUps\setup.log for details.
+#ifdef ChineseMessages
+zhcn.DeploymentFailed=LanUps 后台服务部署失败。详细信息见 %%ProgramData%%\LanUps\setup.log。
+#endif
+
+[Code]
+function DefaultInstallDirectory(Param: String): String;
+var
+ Command, Suffix: String;
+ Ending: Integer;
+begin
+ Result := ExpandConstant('{autopf}\LanUps');
+ Suffix := '\Agent\LanUps.Agent.exe"';
+ if RegQueryStringValue(HKLM, 'SYSTEM\CurrentControlSet\Services\LanUps.Agent', 'ImagePath', Command) then
+ begin
+ Ending := Pos(Lowercase(Suffix), Lowercase(Command));
+ if (Ending > 4) and (Copy(Command, 1, 1) = '"') then
+ Result := Copy(Command, 2, Ending - 2);
+ end;
+end;
+
+function RunDeployment(const Script, Mode: String): Boolean;
+var
+ Arguments, Operator: String;
+ ExitCode: Integer;
+begin
+ Arguments := '-NoProfile -NonInteractive -ExecutionPolicy Bypass -File ' + AddQuotes(Script) +
+ ' -Mode ' + Mode + ' -AppRoot ' + AddQuotes(ExpandConstant('{app}'));
+ if Mode = 'Install' then
+ begin
+ Operator := ExpandConstant('{param:OPERATOR|}');
+ if (Pos('"', Operator) > 0) or (Pos(#13, Operator) > 0) or (Pos(#10, Operator) > 0) then
+ RaiseException('Invalid /OPERATOR value.');
+ if Operator <> '' then
+ Arguments := Arguments + ' -Operator ' + AddQuotes(Operator);
+ if ExpandConstant('{param:ENABLESHUTDOWN|0}') = '1' then
+ Arguments := Arguments + ' -EnableShutdown';
+ end;
+ ExitCode := -1;
+ Result := Exec(ExpandConstant('{sys}\WindowsPowerShell\v1.0\powershell.exe'),
+ Arguments, ExpandConstant('{sys}'), SW_HIDE, ewWaitUntilTerminated, ExitCode);
+ Log(Format('LanUps deployment %s: launched=%d, code=%d', [Mode, Ord(Result), ExitCode]));
+ Result := Result and (ExitCode = 0);
+end;
+
+function PrepareToInstall(var NeedsRestart: Boolean): String;
+begin
+ Result := '';
+ ExtractTemporaryFile('deployment.ps1');
+ if not RunDeployment(ExpandConstant('{tmp}\deployment.ps1'), 'Prepare') then
+ Result := CustomMessage('DeploymentFailed');
+end;
+
+procedure CurStepChanged(CurStep: TSetupStep);
+begin
+ if CurStep = ssPostInstall then
+ if not RunDeployment(ExpandConstant('{app}\deployment.ps1'), 'Install') then
+ RaiseException(CustomMessage('DeploymentFailed'));
+end;
+
+procedure CurUninstallStepChanged(CurUninstallStep: TUninstallStep);
+begin
+ if CurUninstallStep = usUninstall then
+ if not RunDeployment(ExpandConstant('{app}\deployment.ps1'), 'Uninstall') then
+ RaiseException(CustomMessage('DeploymentFailed'));
+end;
diff --git a/lan-ups/desktop/deploy/windows/Setup.cmd b/lan-ups/desktop/deploy/windows/Setup.cmd
deleted file mode 100644
index 55cec72..0000000
--- a/lan-ups/desktop/deploy/windows/Setup.cmd
+++ /dev/null
@@ -1,4 +0,0 @@
-@echo off
-setlocal
-powershell.exe -NoProfile -ExecutionPolicy Bypass -File "%~dp0Setup.ps1" %*
-if errorlevel 1 pause
diff --git a/lan-ups/desktop/deploy/windows/Setup.ps1 b/lan-ups/desktop/deploy/windows/Setup.ps1
deleted file mode 100644
index 8c36e24..0000000
--- a/lan-ups/desktop/deploy/windows/Setup.ps1
+++ /dev/null
@@ -1,57 +0,0 @@
-param([string]$Operator = [Security.Principal.WindowsIdentity]::GetCurrent().Name, [switch]$EnableShutdown)
-
-$ErrorActionPreference = 'Stop'
-$identity = [Security.Principal.WindowsIdentity]::GetCurrent()
-if (!([Security.Principal.WindowsPrincipal]::new($identity)).IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)) {
- if ($Operator -match '["\r\n]') { throw 'Invalid operator account' }
- $arguments = '-NoProfile -ExecutionPolicy Bypass -File "{0}" -Operator "{1}"' -f $PSCommandPath, $Operator
- if ($EnableShutdown) { $arguments += ' -EnableShutdown' }
- $process = Start-Process powershell.exe -Verb RunAs -ArgumentList $arguments -Wait -PassThru -WindowStyle Hidden
- exit $process.ExitCode
-}
-
-$destination = Join-Path $env:ProgramFiles 'LanUps'
-$logDirectory = Join-Path ([Environment]::GetFolderPath('CommonApplicationData')) 'LanUps'
-New-Item -ItemType Directory -Path $logDirectory -Force | Out-Null
-$log = Join-Path $logDirectory 'setup.log'
-Start-Transcript -Path $log -Append | Out-Null
-try {
- foreach ($kind in @('Agent', 'Desktop')) {
- if (!(Test-Path -LiteralPath (Join-Path $PSScriptRoot "$kind\LanUps.$kind.exe") -PathType Leaf)) {
- throw "Extract the entire installer archive before running Setup.cmd: missing $kind"
- }
- }
- $service = Get-Service 'LanUps.Agent' -ErrorAction SilentlyContinue
- if ($service -and $service.Status -ne 'Stopped') { Stop-Service $service }
- $task = Get-ScheduledTask -TaskName 'LanUps Desktop' -ErrorAction SilentlyContinue
- if ($task -and $task.State -eq 'Running') { Stop-ScheduledTask $task }
- $existingDesktop = Join-Path $destination 'Desktop\LanUps.Desktop.exe'
- Get-Process LanUps.Desktop -ErrorAction SilentlyContinue | Where-Object Path -EQ $existingDesktop |
- ForEach-Object { Stop-Process -Id $_.Id; $_.WaitForExit() }
-
- foreach ($kind in @('Agent', 'Desktop')) {
- $target = Join-Path $destination $kind
- New-Item -ItemType Directory -Path $target -Force | Out-Null
- Copy-Item -Path (Join-Path $PSScriptRoot "$kind\*") -Destination $target -Recurse -Force
- }
- & (Join-Path $PSScriptRoot 'install.ps1') -Operator $Operator -EnableShutdown:$EnableShutdown
- $shell = New-Object -ComObject WScript.Shell
- $shortcut = $shell.CreateShortcut((Join-Path ([Environment]::GetFolderPath('CommonDesktopDirectory')) '局域网 UPS.lnk'))
- $shortcut.TargetPath = $existingDesktop
- $shortcut.WorkingDirectory = (Split-Path -Parent $existingDesktop)
- $shortcut.IconLocation = "$existingDesktop,0"
- $shortcut.Save()
- if ($identity.Name -ieq $Operator) {
- $personalPath = Join-Path ([Environment]::GetFolderPath('DesktopDirectory')) '局域网 UPS.lnk'
- if (Test-Path -LiteralPath $personalPath) {
- $personal = $shell.CreateShortcut($personalPath)
- if ((Split-Path -Leaf $personal.TargetPath) -ieq 'LanUps.Desktop.exe') {
- $personal.TargetPath = $existingDesktop
- $personal.WorkingDirectory = (Split-Path -Parent $existingDesktop)
- $personal.IconLocation = "$existingDesktop,0"
- $personal.Save()
- }
- }
- }
- Write-Host "Installed: $destination"
-} finally { Stop-Transcript | Out-Null }
diff --git a/lan-ups/desktop/deploy/windows/deployment.ps1 b/lan-ups/desktop/deploy/windows/deployment.ps1
new file mode 100644
index 0000000..34a4593
--- /dev/null
+++ b/lan-ups/desktop/deploy/windows/deployment.ps1
@@ -0,0 +1,147 @@
+#Requires -RunAsAdministrator
+param(
+ [Parameter(Mandatory)][ValidateSet('Prepare', 'Install', 'Uninstall')][string]$Mode,
+ [Parameter(Mandatory)][string]$AppRoot,
+ [string]$Operator,
+ [switch]$EnableShutdown
+)
+
+$ErrorActionPreference = 'Stop'
+$serviceName = 'LanUps.Agent'
+$taskName = 'LanUps Desktop'
+$serviceKey = 'HKLM:\SYSTEM\CurrentControlSet\Services\LanUps.Agent'
+
+function Confirm-InstallDirectory([string]$Path) {
+ if ($Path -notmatch '^[A-Za-z]:\\[^"\r\n]+$' -or $Path.Substring(2).Contains(':')) {
+ throw 'Select a local installation directory.'
+ }
+ $fullPath = [IO.Path]::GetFullPath($Path).TrimEnd('\')
+ $root = [IO.Path]::GetPathRoot($fullPath)
+ if ($fullPath.Length -le 3 -or [IO.DriveInfo]::new($root).DriveType -ne 'Fixed') {
+ throw 'Select a directory on a fixed local disk.'
+ }
+ $admins = 'S-1-5-32-544'
+ $system = 'S-1-5-18'
+ $installer = 'S-1-5-80-956008885-3418522649-1831038044-1853292631-2271478464'
+ $trusted = @($admins, $system, $installer)
+ $sidType = [Security.Principal.SecurityIdentifier]
+ $directoryAcl = [Security.AccessControl.DirectorySecurity]::new()
+ $directoryAcl.SetAccessRuleProtection($true, $false)
+ $directoryAcl.SetOwner($sidType::new($admins))
+ foreach ($account in $trusted[0..1]) {
+ $directoryAcl.AddAccessRule([Security.AccessControl.FileSystemAccessRule]::new($sidType::new($account), 'FullControl', 'ContainerInherit,ObjectInherit', 'None', 'Allow'))
+ }
+ $directoryAcl.AddAccessRule([Security.AccessControl.FileSystemAccessRule]::new($sidType::new('S-1-5-32-545'), 'ReadAndExecute', 'ContainerInherit,ObjectInherit', 'None', 'Allow'))
+
+ function Assert-ProtectedItem($item, [bool]$volumeRoot) {
+ if ($item.Attributes -band [IO.FileAttributes]::ReparsePoint) { throw "Choose a directory without junctions or symbolic links: $($item.FullName)" }
+ $acl = Get-Acl -LiteralPath $item.FullName
+ if ($acl.GetOwner($sidType).Value -notin $trusted) { throw "The installation path must be owned by administrators or Windows: $($item.FullName)" }
+ # Volume roots can permit creating new folders, but must protect existing children.
+ $unsafeRights = if ($volumeRoot) { 0x100C0040 } else { 0x500D0156 }
+ foreach ($rule in $acl.GetAccessRules($true, $true, $sidType)) {
+ if ($rule.AccessControlType -eq 'Allow' -and $rule.IdentityReference.Value -notin $trusted -and
+ !($rule.PropagationFlags -band [Security.AccessControl.PropagationFlags]::InheritOnly) -and
+ ($rule.FileSystemRights -band $unsafeRights)) {
+ throw "Ordinary users can modify this installation path: $($item.FullName)"
+ }
+ }
+ }
+ Assert-ProtectedItem (Get-Item -LiteralPath $root -Force) $true
+ $pathToCheck = $root
+ foreach ($part in $fullPath.Substring(3).Split('\')) {
+ $pathToCheck = Join-Path $pathToCheck $part
+ if (!(Test-Path -LiteralPath $pathToCheck)) { [void][IO.Directory]::CreateDirectory($pathToCheck, $directoryAcl) }
+ Assert-ProtectedItem (Get-Item -LiteralPath $pathToCheck -Force) $false
+ }
+ foreach ($kind in 'Agent', 'Desktop') {
+ $existing = Join-Path $fullPath $kind
+ if (Test-Path -LiteralPath $existing) {
+ Assert-ProtectedItem (Get-Item -LiteralPath $existing -Force) $false
+ Get-ChildItem -LiteralPath $existing -Recurse -Force | ForEach-Object { Assert-ProtectedItem $_ $false }
+ }
+ }
+ foreach ($filename in 'deployment.ps1', 'install.ps1') {
+ $file = Join-Path $fullPath $filename
+ if (Test-Path -LiteralPath $file) { Assert-ProtectedItem (Get-Item -LiteralPath $file -Force) $false }
+ }
+ return $fullPath
+}
+
+function Stop-LanUps {
+ $task = Get-ScheduledTask -TaskName $taskName -ErrorAction SilentlyContinue
+ if ($task -and $task.State -eq 'Running') { Stop-ScheduledTask -InputObject $task }
+ $service = Get-Service -Name $serviceName -ErrorAction SilentlyContinue
+ if ($service -and $service.Status -ne 'Stopped') {
+ Stop-Service -InputObject $service
+ $service.WaitForStatus('Stopped', [TimeSpan]::FromSeconds(30))
+ }
+ $oldPath = (Get-ItemProperty -LiteralPath $serviceKey -Name ImagePath -ErrorAction SilentlyContinue).ImagePath
+ $desktopPaths = @(Join-Path $AppRoot 'Desktop\LanUps.Desktop.exe')
+ if ($oldPath -match '^"([A-Za-z]:\\[^"]+)\\Agent\\LanUps\.Agent\.exe"(?:\s|$)') {
+ $desktopPaths += Join-Path $Matches[1] 'Desktop\LanUps.Desktop.exe'
+ }
+ Get-Process LanUps.Desktop -ErrorAction SilentlyContinue | Where-Object { $_.Path -in $desktopPaths } |
+ ForEach-Object {
+ Stop-Process -Id $_.Id -ErrorAction SilentlyContinue
+ if (!$_.WaitForExit(10000)) { throw "LanUps desktop process $($_.Id) did not stop" }
+ }
+}
+
+$distributionLog = Join-Path ([Environment]::GetFolderPath('CommonApplicationData')) 'LanUps\setup.log'
+New-Item -ItemType Directory -Path (Split-Path -Parent $distributionLog) -Force | Out-Null
+Start-Transcript -LiteralPath $distributionLog -Append | Out-Null
+try {
+ switch ($Mode) {
+ 'Prepare' {
+ $AppRoot = Confirm-InstallDirectory $AppRoot
+ Stop-LanUps
+ }
+ 'Install' {
+ if (!$Operator) {
+ $sessionId = (Get-Process -Id $PID).SessionId
+ $shell = Get-CimInstance Win32_Process -Filter "Name='explorer.exe' AND SessionId=$sessionId" | Select-Object -First 1
+ if ($shell) {
+ $owner = Invoke-CimMethod -InputObject $shell -MethodName GetOwner
+ if (!$owner.ReturnValue -and $owner.User) { $Operator = "$($owner.Domain)\$($owner.User)" }
+ }
+ if (!$Operator) {
+ $Operator = (Get-ScheduledTask -TaskName $taskName -ErrorAction SilentlyContinue).Principal.UserId
+ }
+ if (!$Operator) {
+ $identity = [Security.Principal.WindowsIdentity]::GetCurrent()
+ if ($identity.IsSystem) { throw 'Specify /OPERATOR="DOMAIN\User" when running unattended as SYSTEM.' }
+ $Operator = $identity.Name
+ }
+ }
+ $oldPath = (Get-ItemProperty -LiteralPath $serviceKey -Name ImagePath -ErrorAction SilentlyContinue).ImagePath
+ $enable = $EnableShutdown -or $oldPath -match '(?i)\s--enable-shutdown\s*$'
+ & (Join-Path $PSScriptRoot 'install.ps1') -AppRoot $AppRoot -Operator $Operator -EnableShutdown:$enable
+ }
+ 'Uninstall' {
+ $registered = (Get-ItemProperty -LiteralPath $serviceKey -Name ImagePath -ErrorAction SilentlyContinue).ImagePath
+ $expected = '"' + (Join-Path $AppRoot 'Agent\LanUps.Agent.exe') + '"'
+ if ($registered -and $registered -ine $expected -and $registered -ine "$expected --enable-shutdown") { break }
+ Stop-LanUps
+ $task = Get-ScheduledTask -TaskName $taskName -ErrorAction SilentlyContinue
+ if ($task) { Unregister-ScheduledTask -InputObject $task -Confirm:$false }
+ if (Get-Service -Name $serviceName -ErrorAction SilentlyContinue) {
+ & (Join-Path $env:SystemRoot 'System32\sc.exe') delete $serviceName
+ if ($LASTEXITCODE) { throw "Could not remove $serviceName service." }
+ }
+ }
+ }
+} catch {
+ Write-Host ($_ | Out-String)
+ throw
+} finally {
+ Stop-Transcript | Out-Null
+ if ($Operator) {
+ try {
+ $account = [Security.Principal.NTAccount]::new($Operator)
+ $acl = Get-Acl -LiteralPath $distributionLog
+ $acl.SetAccessRule([Security.AccessControl.FileSystemAccessRule]::new($account, 'Read', 'Allow'))
+ Set-Acl -LiteralPath $distributionLog -AclObject $acl
+ } catch { Write-Warning "Unable to grant access to the setup log: $($_.Exception.Message)" }
+ }
+}
diff --git a/lan-ups/desktop/deploy/windows/install.ps1 b/lan-ups/desktop/deploy/windows/install.ps1
index 4ae2bbe..9cef31a 100644
--- a/lan-ups/desktop/deploy/windows/install.ps1
+++ b/lan-ups/desktop/deploy/windows/install.ps1
@@ -1,11 +1,11 @@
#Requires -RunAsAdministrator
param(
[Parameter(Mandatory)][string]$Operator,
+ [string]$AppRoot = (Join-Path $env:ProgramFiles 'LanUps'),
[switch]$EnableShutdown
)
$ErrorActionPreference = 'Stop'
-$appRoot = Join-Path $env:ProgramFiles 'LanUps'
$agent = Join-Path $appRoot 'Agent\LanUps.Agent.exe'
$desktop = Join-Path $appRoot 'Desktop\LanUps.Desktop.exe'
foreach ($app in @($agent, $desktop)) {
@@ -47,8 +47,44 @@ if ($installed) {
} else {
New-Service -Name 'LanUps.Agent' -BinaryPathName $command -DisplayName 'LAN UPS Agent' -StartupType Automatic | Out-Null
}
+$sc = Join-Path $env:SystemRoot 'System32\sc.exe'
+& $sc failure 'LanUps.Agent' reset= 86400 actions= 'restart/5000/restart/15000/restart/60000'
+if ($LASTEXITCODE) { throw 'Cannot configure Agent service recovery' }
+& $sc failureflag 'LanUps.Agent' 1
+if ($LASTEXITCODE) { throw 'Cannot enable Agent service recovery' }
Start-Service -Name 'LanUps.Agent'
+# The SCM can report Running before Kestrel is listening.
+Add-Type -AssemblyName System.Net.Http
+$handler = [Net.Http.HttpClientHandler]::new()
+$handler.UseProxy = $false
+$client = [Net.Http.HttpClient]::new($handler)
+$client.Timeout = [TimeSpan]::FromSeconds(2)
+$port = 47183
+$configuredPort = 0
+$machinePort = [Environment]::GetEnvironmentVariable('LANUPS_AGENT_PORT', 'Machine')
+if ([int]::TryParse($machinePort, [ref]$configuredPort) -and $configuredPort -in 1..65535) { $port = $configuredPort }
+$address = "http://127.0.0.1:$port/status"
+$client.DefaultRequestHeaders.Add('X-LanUps-Token', [IO.File]::ReadAllText($token).Trim())
+$deadline = [DateTime]::UtcNow.AddSeconds(25)
+$ready = $false
+try {
+ do {
+ try {
+ $status = $client.GetStringAsync($address).GetAwaiter().GetResult() | ConvertFrom-Json
+ if (!$status.endpoint -or !$status.update) { throw 'Unexpected Agent status response' }
+ $ready = $true
+ } catch {
+ $reason = $_.Exception.GetBaseException().Message
+ Start-Sleep -Milliseconds 300
+ }
+ } until ($ready -or [DateTime]::UtcNow -ge $deadline)
+} finally { $client.Dispose() }
+if (!$ready) {
+ $state = (Get-Service 'LanUps.Agent').Status
+ throw "Agent service did not respond at $address (service state: $state). $reason"
+}
+
$action = New-ScheduledTaskAction -Execute $desktop -Argument '--tray' -WorkingDirectory (Split-Path -Parent $desktop)
$trigger = New-ScheduledTaskTrigger -AtLogOn -User $Operator
$principal = New-ScheduledTaskPrincipal -UserId $Operator -LogonType Interactive -RunLevel Limited
diff --git a/lan-ups/desktop/src/LanUps.Agent/Coordinator.cs b/lan-ups/desktop/src/LanUps.Agent/Coordinator.cs
index 0474cdb..1a2a83c 100644
--- a/lan-ups/desktop/src/LanUps.Agent/Coordinator.cs
+++ b/lan-ups/desktop/src/LanUps.Agent/Coordinator.cs
@@ -16,6 +16,7 @@ internal sealed class Coordinator
private readonly CancellationToken _stopping;
private readonly string _shutdownStatePath;
private NutEndpoint _endpoint;
+ private bool _shutdownImmediately;
private UpsUpdate _update = new(null, null, false);
private ShutdownNotice? _pending;
private string? _lastAction;
@@ -30,7 +31,14 @@ internal sealed class Coordinator
_dryRun = dryRun;
_log = log;
_stopping = stopping;
- _endpoint = LoadEndpoint();
+ _endpoint = NutEndpoint.Default;
+ if (File.Exists(_settingsPath))
+ {
+ var settings = JsonSerializer.Deserialize(File.ReadAllText(_settingsPath), AgentJson.Default.AgentSettings);
+ if (settings is null || !NutEndpoint.TryParse(settings.Host, settings.Port.ToString(), settings.Name, out _endpoint))
+ throw new InvalidDataException("Invalid saved NUT endpoint");
+ _shutdownImmediately = settings.ShutdownImmediately;
+ }
if (File.Exists(_shutdownStatePath))
{
var saved = JsonSerializer.Deserialize(File.ReadAllText(_shutdownStatePath), ShutdownJson.Default.ShutdownState);
@@ -54,16 +62,20 @@ internal sealed class Coordinator
public AgentState Snapshot()
{
- lock (_gate) return new(_endpoint, _update, _pending, _lastAction, _dryRun);
+ lock (_gate) return new(_endpoint, _update, _pending, _lastAction, _dryRun, _shutdownImmediately);
}
- public bool SetEndpoint(NutEndpoint endpoint)
+ public bool SetSettings(NutEndpoint endpoint, bool? shutdownImmediately = null)
{
lock (_gate)
{
- if (endpoint == _endpoint) return true;
- if (_pending is not null) return false;
- WriteJson(_settingsPath, endpoint, AgentJson.Default.NutEndpoint);
+ var endpointChanged = endpoint != _endpoint;
+ var immediate = shutdownImmediately ?? _shutdownImmediately;
+ if (!endpointChanged && immediate == _shutdownImmediately) return true;
+ if (endpointChanged && _pending is not null) return false;
+ WriteJson(_settingsPath, new AgentSettings(endpoint.Host, endpoint.Port, endpoint.Name, immediate), AgentJson.Default.AgentSettings);
+ _shutdownImmediately = immediate;
+ if (!endpointChanged) return true;
_endpoint = endpoint;
_update = new(null, null, false);
_signalLatched = false;
@@ -76,14 +88,6 @@ internal sealed class Coordinator
public bool Respond(Guid id, bool confirm) => Finish(id, confirm ? "用户确认" : "用户取消", confirm);
- private NutEndpoint LoadEndpoint()
- {
- if (!File.Exists(_settingsPath)) return NutEndpoint.Default;
- var saved = JsonSerializer.Deserialize(File.ReadAllText(_settingsPath), AgentJson.Default.NutEndpoint);
- if (saved is not null && NutEndpoint.TryParse(saved.Host, saved.Port.ToString(), saved.Name, out var endpoint)) return endpoint;
- throw new InvalidDataException("Invalid saved NUT endpoint");
- }
-
private void StartMonitor()
{
_monitor?.Cancel();
@@ -125,6 +129,11 @@ internal sealed class Coordinator
if (_signalLatched) return;
_signalLatched = true;
if (_pending is not null) { SaveShutdownState(); return; }
+ if (_shutdownImmediately)
+ {
+ CompleteShutdown("收到关机指令,立即执行", true);
+ return;
+ }
var pending = new ShutdownNotice(Guid.NewGuid(), DateTimeOffset.UtcNow + Countdown);
_pending = pending;
_lastAction = null;
@@ -150,15 +159,20 @@ internal sealed class Coordinator
lock (_gate)
{
if (_pending?.Id != id) return false;
- _pending = null;
- _lastAction = shutdown ? $"{reason} · {(_dryRun ? "已模拟关机" : "已提交关机")}" : reason;
- SaveShutdownState();
- _log.LogWarning("{Result}", _lastAction);
- if (shutdown && !_dryRun) _ = Task.Run(ExecuteShutdownAsync);
+ CompleteShutdown(reason, shutdown);
return true;
}
}
+ private void CompleteShutdown(string reason, bool shutdown)
+ {
+ _pending = null;
+ _lastAction = shutdown ? $"{reason} · {(_dryRun ? "已模拟关机" : "已提交关机")}" : reason;
+ SaveShutdownState();
+ _log.LogWarning("{Result}", _lastAction);
+ if (shutdown && !_dryRun) _ = Task.Run(ExecuteShutdownAsync);
+ }
+
private async Task ExecuteShutdownAsync()
{
try
diff --git a/lan-ups/desktop/src/LanUps.Agent/Program.cs b/lan-ups/desktop/src/LanUps.Agent/Program.cs
index b2c760d..a2a346d 100644
--- a/lan-ups/desktop/src/LanUps.Agent/Program.cs
+++ b/lan-ups/desktop/src/LanUps.Agent/Program.cs
@@ -58,7 +58,19 @@ app.MapPut("/endpoint", ([FromBody] NutEndpoint proposed) =>
{
if (!NutEndpoint.TryParse(proposed.Host, proposed.Port.ToString(), proposed.Name, out var endpoint))
return Results.BadRequest("请输入有效的 NUT 配置");
- try { return agent.SetEndpoint(endpoint) ? Results.Ok(endpoint) : Results.Conflict("关机倒计时正在执行"); }
+ try { return agent.SetSettings(endpoint) ? Results.Ok(endpoint) : Results.Conflict("关机倒计时正在执行"); }
+ catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) { return Results.Text("保存后台配置失败", statusCode: 500); }
+});
+app.MapPut("/settings", ([FromBody] AgentSettings proposed) =>
+{
+ if (!NutEndpoint.TryParse(proposed.Host, proposed.Port.ToString(), proposed.Name, out var endpoint))
+ return Results.BadRequest("请输入有效的 NUT 配置");
+ try
+ {
+ return agent.SetSettings(endpoint, proposed.ShutdownImmediately)
+ ? Results.Ok(new AgentSettings(endpoint.Host, endpoint.Port, endpoint.Name, proposed.ShutdownImmediately))
+ : Results.Conflict("关机倒计时正在执行");
+ }
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) { return Results.Text("保存后台配置失败", statusCode: 500); }
});
app.MapGet("/ups", async (string host, int port, CancellationToken cancellation) =>
diff --git a/lan-ups/desktop/src/LanUps.Core/AgentClient.cs b/lan-ups/desktop/src/LanUps.Core/AgentClient.cs
index ac5d8dd..ef4ff25 100644
--- a/lan-ups/desktop/src/LanUps.Core/AgentClient.cs
+++ b/lan-ups/desktop/src/LanUps.Core/AgentClient.cs
@@ -4,7 +4,9 @@ using System.Text.Json.Serialization.Metadata;
namespace LanUps.Core;
public sealed record ShutdownNotice(Guid Id, DateTimeOffset Deadline);
-public sealed record AgentState(NutEndpoint Endpoint, UpsUpdate Update, ShutdownNotice? Pending, string? LastAction, bool DryRun);
+public sealed record AgentState(NutEndpoint Endpoint, UpsUpdate Update, ShutdownNotice? Pending, string? LastAction, bool DryRun,
+ bool? ShutdownImmediately = null);
+public sealed record AgentSettings(string Host, int Port, string Name, bool ShutdownImmediately = false);
public static class AgentLocation
{
@@ -24,6 +26,9 @@ public sealed class AgentClient : IDisposable
public Task StatusAsync(CancellationToken token) => SendAsync(HttpMethod.Get, "status", null, AgentJson.Default.AgentState, token);
public Task SaveAsync(NutEndpoint endpoint, CancellationToken token) =>
SendAsync(HttpMethod.Put, "endpoint", JsonContent.Create(endpoint, AgentJson.Default.NutEndpoint), AgentJson.Default.NutEndpoint, token);
+
+ public Task SaveSettingsAsync(AgentSettings settings, CancellationToken token) =>
+ SendAsync(HttpMethod.Put, "settings", JsonContent.Create(settings, AgentJson.Default.AgentSettings), AgentJson.Default.AgentSettings, token);
public Task DiscoverAsync(string host, int port, CancellationToken token) =>
SendAsync(HttpMethod.Get, $"ups?host={Uri.EscapeDataString(host)}&port={port}", null, AgentJson.Default.StringArray, token);
public Task RespondAsync(Guid id, bool confirm, CancellationToken token) =>
diff --git a/lan-ups/desktop/src/LanUps.Core/AgentJson.cs b/lan-ups/desktop/src/LanUps.Core/AgentJson.cs
index 731a62a..70e55f1 100644
--- a/lan-ups/desktop/src/LanUps.Core/AgentJson.cs
+++ b/lan-ups/desktop/src/LanUps.Core/AgentJson.cs
@@ -5,6 +5,7 @@ namespace LanUps.Core;
[JsonSourceGenerationOptions(JsonSerializerDefaults.Web)]
[JsonSerializable(typeof(AgentState))]
+[JsonSerializable(typeof(AgentSettings))]
[JsonSerializable(typeof(NutEndpoint))]
[JsonSerializable(typeof(string[]))]
[JsonSerializable(typeof(string))]
diff --git a/lan-ups/desktop/src/LanUps.Core/NutMonitor.cs b/lan-ups/desktop/src/LanUps.Core/NutMonitor.cs
index 41f7cd6..8e0b05b 100644
--- a/lan-ups/desktop/src/LanUps.Core/NutMonitor.cs
+++ b/lan-ups/desktop/src/LanUps.Core/NutMonitor.cs
@@ -36,7 +36,7 @@ public sealed record UpsReading(DateTimeOffset At, IReadOnlyDictionary (Get("ups.status") ?? "").Split(' ', StringSplitOptions.RemoveEmptyEntries).Contains(flag, StringComparer.Ordinal);
}
-public sealed record UpsUpdate(UpsReading? LastReading, string? Error, bool NewShutdownSignal);
+public sealed record UpsUpdate(UpsReading? LastReading, string? Error, bool NewShutdownSignal, bool? NutServerOnline = null);
public static class NutMonitor
{
@@ -48,9 +48,10 @@ public static class NutMonitor
{
string? error = null;
var newSignal = false;
+ var serverOnline = false;
try
{
- lastReading = await ReadAsync(endpoint, cancellation).ConfigureAwait(false);
+ lastReading = await ReadAsync(endpoint, () => serverOnline = true, cancellation).ConfigureAwait(false);
var hasSignal = lastReading.Has("FSD");
newSignal = hasSignal && !shutdownSignalSeen;
shutdownSignalSeen = hasSignal;
@@ -61,7 +62,7 @@ public static class NutMonitor
error = ex is OperationCanceledException ? "连接或读取超时" : ex.Message;
}
cancellation.ThrowIfCancellationRequested();
- publish(new(lastReading, error, newSignal));
+ publish(new(lastReading, error, newSignal, serverOnline));
await Task.Delay(TimeSpan.FromSeconds(3), cancellation).ConfigureAwait(false);
}
}
@@ -81,9 +82,9 @@ public static class NutMonitor
return names.Distinct(StringComparer.Ordinal).ToArray();
}
- private static async Task ReadAsync(NutEndpoint endpoint, CancellationToken cancellation)
+ private static async Task ReadAsync(NutEndpoint endpoint, Action onServerResponse, CancellationToken cancellation)
{
- var rows = await ListAsync(endpoint.Host, endpoint.Port, $"LIST VAR {endpoint.Name}", cancellation).ConfigureAwait(false);
+ var rows = await ListAsync(endpoint.Host, endpoint.Port, $"LIST VAR {endpoint.Name}", cancellation, onServerResponse).ConfigureAwait(false);
var values = new Dictionary(StringComparer.Ordinal);
var prefix = $"VAR {endpoint.Name} ";
foreach (var line in rows)
@@ -100,7 +101,8 @@ public static class NutMonitor
return new(DateTimeOffset.Now, values);
}
- private static async Task> ListAsync(string host, int port, string request, CancellationToken cancellation)
+ private static async Task> ListAsync(string host, int port, string request, CancellationToken cancellation,
+ Action? onServerResponse = null)
{
using var timeout = CancellationTokenSource.CreateLinkedTokenSource(cancellation);
timeout.CancelAfter(TimeSpan.FromSeconds(3));
@@ -112,7 +114,10 @@ public static class NutMonitor
using var reader = new StreamReader(stream, Encoding.UTF8);
var header = await reader.ReadLineAsync(token).ConfigureAwait(false);
- if (header != $"BEGIN {request}")
+ var expected = $"BEGIN {request}";
+ if (header == expected || header?.StartsWith("ERR ", StringComparison.Ordinal) == true)
+ onServerResponse?.Invoke();
+ if (header != expected)
throw new IOException(header ?? "NUT 服务端关闭了连接");
var rows = new List();
diff --git a/lan-ups/desktop/src/LanUps.Desktop/App.axaml.cs b/lan-ups/desktop/src/LanUps.Desktop/App.axaml.cs
index 7a50951..b6b4390 100644
--- a/lan-ups/desktop/src/LanUps.Desktop/App.axaml.cs
+++ b/lan-ups/desktop/src/LanUps.Desktop/App.axaml.cs
@@ -11,11 +11,26 @@ public sealed partial class App : Application
public override void OnFrameworkInitializationCompleted()
{
if (ApplicationLifetime is IClassicDesktopStyleApplicationLifetime desktop)
+ {
desktop.MainWindow = new MainWindow(desktop.Args?.Contains("--tray", StringComparer.Ordinal) == true);
+ if (Program.ActivationPipeName is { } pipe)
+ {
+ var stopping = new CancellationTokenSource();
+ var listener = Program.ListenAsync(pipe, ShowDashboard, stopping.Token);
+ desktop.Exit += (_, _) =>
+ {
+ stopping.Cancel();
+ listener.GetAwaiter().GetResult();
+ stopping.Dispose();
+ };
+ }
+ }
base.OnFrameworkInitializationCompleted();
}
- private void ShowDashboard(object? sender, EventArgs args)
+ private void ShowDashboard(object? sender, EventArgs args) => ShowDashboard();
+
+ internal void ShowDashboard()
{
if (ApplicationLifetime is IClassicDesktopStyleApplicationLifetime { MainWindow: MainWindow window })
window.Restore();
diff --git a/lan-ups/desktop/src/LanUps.Desktop/MainWindow.axaml b/lan-ups/desktop/src/LanUps.Desktop/MainWindow.axaml
index 3df43ac..23209af 100644
--- a/lan-ups/desktop/src/LanUps.Desktop/MainWindow.axaml
+++ b/lan-ups/desktop/src/LanUps.Desktop/MainWindow.axaml
@@ -1,12 +1,12 @@
+ Width="760" SizeToContent="Height" CanResize="False" WindowStartupLocation="CenterScreen">
-
-
+
+
-
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
@@ -70,6 +87,13 @@
+
+
+
+
+
+
+
diff --git a/lan-ups/desktop/src/LanUps.Desktop/MainWindow.axaml.cs b/lan-ups/desktop/src/LanUps.Desktop/MainWindow.axaml.cs
index 1508e68..8eb65cb 100644
--- a/lan-ups/desktop/src/LanUps.Desktop/MainWindow.axaml.cs
+++ b/lan-ups/desktop/src/LanUps.Desktop/MainWindow.axaml.cs
@@ -1,11 +1,16 @@
using Avalonia.Controls;
using Avalonia.Interactivity;
+using Avalonia.Media;
+using Avalonia.Controls.Shapes;
using LanUps.Core;
namespace LanUps.Desktop;
public sealed partial class MainWindow : Window
{
+ private static readonly IBrush OnlineColor = new SolidColorBrush(Color.Parse("#2E9B52"));
+ private static readonly IBrush OfflineColor = new SolidColorBrush(Color.Parse("#D94141"));
+ private static readonly IBrush UnknownColor = new SolidColorBrush(Color.Parse("#8B919B"));
private readonly AgentClient _agent = new();
private readonly CancellationTokenSource _lifetime = new();
private CancellationTokenSource? _discovery;
@@ -110,6 +115,8 @@ public sealed partial class MainWindow : Window
AskOnClose.IsChecked = _options.CloseAction is null;
MinimizeOnClose.IsChecked = _options.CloseAction == CloseAction.Minimize;
ExitOnClose.IsChecked = _options.CloseAction == CloseAction.Exit;
+ ShutdownImmediately.IsEnabled = _agentState?.ShutdownImmediately is not null;
+ ShutdownImmediately.IsChecked = _agentState?.ShutdownImmediately == true;
SettingsStatus.IsVisible = false;
DiscoveredUps.IsVisible = false;
LogWarning.IsVisible = _logFailed;
@@ -140,7 +147,10 @@ public sealed partial class MainWindow : Window
_savingSettings = true;
try
{
- await _agent.SaveAsync(endpoint, _lifetime.Token);
+ if (ShutdownImmediately.IsEnabled)
+ await _agent.SaveSettingsAsync(new(endpoint.Host, endpoint.Port, endpoint.Name, ShutdownImmediately.IsChecked == true), _lifetime.Token);
+ else
+ await _agent.SaveAsync(endpoint, _lifetime.Token);
DesktopSettings.Save(options);
_options = options;
WriteLog("已保存桌面端和后台服务设置");
@@ -228,15 +238,23 @@ public sealed partial class MainWindow : Window
var state = await _agent.StatusAsync(_lifetime.Token);
_agentState = state;
var endpoint = state.Endpoint;
- CurrentEndpoint.Text = $"{endpoint.Name} @ {endpoint.Host}:{endpoint.Port}";
- ShutdownModeLabel.Text = state.DryRun ? "关机信号 · 模拟模式" : "关机信号";
+ var host = endpoint.Host.Contains(':') ? $"[{endpoint.Host}]" : endpoint.Host;
+ NutEndpointLabel.Text = $"NUT 服务器 · {host}:{endpoint.Port}";
+ UpsEndpointLabel.Text = $"UPS · {endpoint.Name}";
+ if (SettingsPage.IsVisible && !ShutdownImmediately.IsEnabled && state.ShutdownImmediately is { } immediate)
+ {
+ ShutdownImmediately.IsChecked = immediate;
+ ShutdownImmediately.IsEnabled = true;
+ }
+ var behavior = state.ShutdownImmediately == true ? " · 立即关机" : "";
+ ShutdownModeLabel.Text = $"关机信号{behavior}{(state.DryRun ? " · 模拟模式" : "")}";
ShutdownSignal.Text = state.Pending is not null ? "关机倒计时进行中" : state.LastAction ?? "尚未收到关机信号";
Render(state.Update);
UpdateShutdownDialog(state.Pending, state.DryRun);
}
catch (Exception ex) when (IsAgentError(ex) && !_lifetime.IsCancellationRequested)
{
- Render(new(_agentState?.Update.LastReading, $"本机后台服务不可用:{ex.Message}", false));
+ Render(_agentState?.Update ?? new(null, null, false), ex.Message);
}
await Task.Delay(TimeSpan.FromSeconds(1), _lifetime.Token);
}
@@ -259,10 +277,21 @@ public sealed partial class MainWindow : Window
_ = dialog.ShowDialog(this);
}
- private void Render(UpsUpdate update)
+ private void Render(UpsUpdate update, string? agentError = null)
{
var reading = update.LastReading;
- if (reading is null && update.Error is null)
+ var live = agentError is null && update.Error is null && reading is not null;
+ // Older agents omit NutServerOnline. A valid reading or a NUT error still confirms the server replied.
+ bool? serverOnline = agentError is null
+ ? update.NutServerOnline ?? (live || update.Error?.StartsWith("ERR ", StringComparison.Ordinal) == true ? true : null)
+ : null;
+ var waiting = agentError is null && reading is null && update.Error is null;
+ ShowAvailability(NutIndicator, NutAvailability, serverOnline, waiting ? "检测中" : "无法检测");
+ ShowAvailability(UpsIndicator, UpsAvailability, serverOnline == true ? live : null,
+ waiting ? "检测中" : "无法检测");
+ var error = agentError is not null ? $"本机后台服务不可用:{agentError}" :
+ update.Error is null ? null : $"{(serverOnline == true ? "UPS" : "NUT 服务器")}:{update.Error}";
+ if (waiting)
{
Supply.Text = "等待后台服务读取 UPS";
Updated.Text = "等待首次读数";
@@ -270,16 +299,15 @@ public sealed partial class MainWindow : Window
ShowMetrics(null);
return;
}
- var live = update.Error is null && reading is not null;
Supply.Text = !live ? "通讯中断" : reading!.Has("FSD") ? "收到关机信号" :
reading.Has("LB") ? "电池电量低" : reading.Has("OB") ? "电池供电" :
reading.Has("OL") ? "市电供电" : $"UPS 状态 {reading.Get("ups.status")}";
Updated.Text = reading is null ? "等待首次读数" :
$"{(live ? "更新时间" : "历史读数 · 最后读取")} {reading.At.LocalDateTime:G}";
- ConnectionError.Text = update.Error;
- ConnectionError.IsVisible = update.Error is not null;
+ ConnectionError.Text = error;
+ ConnectionError.IsVisible = error is not null;
ShowMetrics(reading);
- var status = live ? $"UPS 状态 {reading!.Get("ups.status")}" : $"通讯中断 {update.Error}";
+ var status = live ? $"UPS 状态 {reading!.Get("ups.status")}" : $"通讯中断 {error}";
if (status != _previousStatus)
{
WriteLog(status);
@@ -287,6 +315,12 @@ public sealed partial class MainWindow : Window
}
}
+ private static void ShowAvailability(Ellipse indicator, TextBlock label, bool? online, string unknown)
+ {
+ indicator.Fill = online switch { true => OnlineColor, false => OfflineColor, null => UnknownColor };
+ label.Text = online switch { true => "在线", false => "离线", null => unknown };
+ }
+
private void WriteLog(string message)
{
_logFailed = !DesktopSettings.Log(message);
diff --git a/lan-ups/desktop/src/LanUps.Desktop/Program.cs b/lan-ups/desktop/src/LanUps.Desktop/Program.cs
index cd45c69..fdd02ee 100644
--- a/lan-ups/desktop/src/LanUps.Desktop/Program.cs
+++ b/lan-ups/desktop/src/LanUps.Desktop/Program.cs
@@ -1,9 +1,69 @@
using Avalonia;
+using Avalonia.Threading;
+using System.Diagnostics;
+using System.IO.Pipes;
+using System.Security.Cryptography;
+using System.Text;
namespace LanUps.Desktop;
internal static class Program
{
+ internal static string? ActivationPipeName { get; private set; }
+
[STAThread]
- public static void Main(string[] args) => AppBuilder.Configure().UsePlatformDetect().StartWithClassicDesktopLifetime(args);
+ public static void Main(string[] args)
+ {
+ var scope = Environment.UserName;
+ if (OperatingSystem.IsWindows())
+ {
+ using var process = Process.GetCurrentProcess();
+ scope = $"{Environment.UserDomainName}\\{scope}:{process.SessionId}";
+ }
+ var name = "LanUps.Desktop." + Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes(scope)).AsSpan(0, 8));
+ using var instance = new Mutex(false, name + ".lock");
+ if (!TryAcquire(instance))
+ {
+ if (!args.Contains("--tray", StringComparer.Ordinal))
+ {
+ using var client = new NamedPipeClientStream(".", name, PipeDirection.In, PipeOptions.CurrentUserOnly);
+ try { client.Connect(2000); }
+ catch (Exception ex) when (ex is IOException or TimeoutException or UnauthorizedAccessException) { }
+ }
+ return;
+ }
+
+ ActivationPipeName = name;
+ try
+ {
+ AppBuilder.Configure().UsePlatformDetect().StartWithClassicDesktopLifetime(args);
+ }
+ finally
+ {
+ instance.ReleaseMutex();
+ }
+ }
+
+ private static bool TryAcquire(Mutex instance)
+ {
+ try { return instance.WaitOne(0); }
+ catch (AbandonedMutexException) { return true; }
+ }
+
+ internal static async Task ListenAsync(string name, Action activate, CancellationToken stopping)
+ {
+ var dispatcher = Dispatcher.UIThread;
+ try
+ {
+ while (!stopping.IsCancellationRequested)
+ {
+ using var pipe = new NamedPipeServerStream(name, PipeDirection.Out, 1,
+ PipeTransmissionMode.Byte, PipeOptions.Asynchronous | PipeOptions.CurrentUserOnly);
+ await pipe.WaitForConnectionAsync(stopping).ConfigureAwait(false);
+ dispatcher.Post(activate);
+ }
+ }
+ catch (OperationCanceledException) when (stopping.IsCancellationRequested) { }
+ catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) { Trace.WriteLine(ex); }
+ }
}
diff --git a/lan-ups/desktop/tests/agent_integration.py b/lan-ups/desktop/tests/agent_integration.py
index 2294581..520bc20 100644
--- a/lan-ups/desktop/tests/agent_integration.py
+++ b/lan-ups/desktop/tests/agent_integration.py
@@ -27,7 +27,8 @@ def main(*command):
request = reader.readline()
if request == b'LIST VAR h1000m\n':
body = f'BEGIN LIST VAR h1000m\nVAR h1000m ups.status "{mode}"\nEND LIST VAR h1000m\n'
- conn.sendall(b'ERR DATA-STALE\n' if mode == 'stale' else body.encode())
+ errors = {'stale': b'ERR DATA-STALE\n', 'disconnected': b'ERR DRIVER-NOT-CONNECTED\n'}
+ conn.sendall(errors.get(mode, body.encode()))
elif request == b'LIST UPS\n':
conn.sendall(b'BEGIN LIST UPS\nUPS h1000m "Test UPS"\nEND LIST UPS\n')
@@ -38,6 +39,8 @@ def main(*command):
env = dict(os.environ, LANUPS_AGENT_PORT=str(port), LANUPS_AGENT_TOKEN=str(token_path))
subprocess.run([*command, '--provision'], env=env, check=True)
token = token_path.read_text().strip()
+ endpoint = {'host': '127.0.0.1', 'port': nut.getsockname()[1], 'name': 'h1000m'}
+ token_path.with_suffix('.json').write_text(json.dumps(endpoint)) # Config written by older agents.
def call(path, method='GET', body=None, auth=True):
headers = {'X-LanUps-Token': token} if auth else {}
@@ -80,14 +83,23 @@ def main(*command):
process = start()
try:
- wait(lambda state: state['dryRun'])
+ assert wait(lambda state: state['dryRun'])['shutdownImmediately'] is False
denied('status', 401, auth=False)
- endpoint = {'host': '127.0.0.1', 'port': nut.getsockname()[1], 'name': 'h1000m'}
assert call('endpoint', 'PUT', endpoint) == endpoint
assert call(f"ups?host=127.0.0.1&port={endpoint['port']}") == ['h1000m']
- wait(lambda state: flag(state) == 'OL')
+ assert wait(lambda state: flag(state) == 'OL')['update']['nutServerOnline'] is True
+ mode = 'disconnected'
+ disconnected = wait(lambda state: state['update']['error'] == 'ERR DRIVER-NOT-CONNECTED')
+ assert disconnected['update']['nutServerOnline'] is True
+ with socket.socket() as offline:
+ offline.bind(('127.0.0.1', 0)) # Reserve a port without starting a listener.
+ call('endpoint', 'PUT', dict(endpoint, port=offline.getsockname()[1]))
+ unavailable = wait(lambda state: state['update']['nutServerOnline'] is False)
+ assert unavailable['update']['error'] and unavailable['update']['lastReading'] is None
+ call('endpoint', 'PUT', endpoint)
mode = 'stale'
- wait(lambda state: state['update']['error'] and not state['pending'])
+ assert wait(lambda state: state['update']['error'] == 'ERR DATA-STALE')['update']['nutServerOnline'] is True
+ print('PASS: separate NUT server and UPS connection status', flush=True)
mode = 'OB FSD'
first = wait(lambda state: state['pending'])['pending']['id']
denied('endpoint', 409, 'PUT', dict(endpoint, port=1))
@@ -102,6 +114,20 @@ def main(*command):
assert call(f'shutdown/{second}/confirm', 'POST') == 'confirm'
wait(lambda state: '已模拟关机' in (state['lastAction'] or ''))
+ mode = 'OL'
+ wait(lambda state: flag(state) == 'OL')
+ immediate = dict(endpoint, shutdownImmediately=True)
+ assert call('settings', 'PUT', immediate) == immediate
+ process.terminate()
+ process.wait()
+ process = start()
+ assert wait(lambda state: flag(state) == 'OL')['shutdownImmediately'] is True
+ mode = 'OB FSD'
+ result = wait(lambda state: (state['lastAction'] or '').startswith('收到关机指令,立即执行'), 7)
+ assert result['pending'] is None and '已模拟关机' in result['lastAction']
+ print('PASS: immediate shutdown preference persists and bypasses countdown in dry-run mode', flush=True)
+ call('settings', 'PUT', dict(endpoint, shutdownImmediately=False))
+
mode = 'OL'
wait(lambda state: flag(state) == 'OL')
mode = 'OB FSD'