Initial commit
9
.gitignore
vendored
Normal file
@@ -0,0 +1,9 @@
|
||||
__pycache__/
|
||||
*.pyc
|
||||
.venv/
|
||||
build/
|
||||
dist/
|
||||
build-next/
|
||||
dist-next/
|
||||
*.spec
|
||||
.test-data/
|
||||
78
README.md
Normal file
@@ -0,0 +1,78 @@
|
||||
# AutoDeploy 自动部署工作台
|
||||
|
||||
Windows 桌面工具,通过 SSH/SFTP 将 Java 前后端分离项目的 `ROOT.war` 和 `dist` 发布到 Linux 服务器,并可安全更新 HTTPS 证书或单独重启 Nginx。深色界面,支持多套服务器与项目配置、实时日志、历史记录及回滚。
|
||||
|
||||
## 直接使用
|
||||
|
||||
打开 `dist/AutoDeploy/AutoDeploy.exe`。分发时复制整个 `AutoDeploy` 文件夹,不能只复制 EXE。也可解压交付的 ZIP 后运行。目标电脑无需安装 Python。
|
||||
|
||||
1. 点击「添加服务器」,填写服务器地址、SSH 端口、账号和密码。
|
||||
2. 在「部署路径」中确认前端目录、WAR 文件、Tomcat 实例、停启脚本、临时目录及备份目录。
|
||||
3. 点击「测试连接」。测试验证 SSH 认证和远端 Python;部署时另行检查路径、权限及磁盘空间。
|
||||
4. 选择本地 WAR、dist 文件夹或 ZIP,选择前端、后端或一起发布。
|
||||
5. 点击「开始部署」,查看进度与实时日志。
|
||||
6. 在「历史与回滚」中选择记录,点击「恢复此备份」恢复到这次操作之前的文件。已被清理的备份会在执行前报告不存在。
|
||||
|
||||
在“编辑配置 → Nginx 设置”中填写服务器证书和私钥文件名。证书目录默认 `/home/ssl`,文件名必须与现有 Nginx 配置一致。随后进入独立的“Nginx 管理”标签页,选择本地证书及私钥后可执行“上传证书并重启”,也可以不选择文件直接执行“仅重启 Nginx”。
|
||||
|
||||
默认目标:前端 `/home/dist`,后端 `/usr/local/tomcat/webapps/ROOT.war`。前端目标目录直接包含 `index.html`;ZIP 可包含顶层 `dist` 文件夹。应用发布不会修改 Nginx;证书操作仅替换指定的证书和私钥,不修改 Nginx 配置文件。
|
||||
|
||||
## 服务器运行条件
|
||||
|
||||
- Linux、SSH/SFTP、Python **3.6+**;工具不在服务器上安装常驻服务。
|
||||
- 登录账号需要能够写入目标、临时、备份目录及 Tomcat 实例的锁文件,并有权停止/启动目标进程。不自动调用 sudo。
|
||||
- Nginx 功能要求服务器安装 `openssl`、`systemctl`,登录账号能够写入 `/home/ssl`、执行 `nginx -t` 和重启配置的 Nginx 服务;同样不自动调用 sudo。
|
||||
- Tomcat 使用标准 Bootstrap 进程和 `-Dcatalina.base=配置路径`,默认调用 `shutdown.sh` / `startup.sh`。先正常停止,超时后仅对核对过的目标 PID 发送 TERM / KILL。
|
||||
- 如果由 systemd 托管,请填写实际服务名,例如 `tomcat.service`。此时通过 `systemctl` 停启,停止失败就中止操作。
|
||||
- SSH 的非交互环境可能不包含 Java 环境变量,可在「运行设置」填写 `JAVA_HOME`。
|
||||
- 部署目标及其父目录使用真实目录,不接受软链接。若使用 Tomcat 软链接,请填写真实路径,并与进程的 `catalina.base` 完全对应。
|
||||
- 可选填写文件属主(例如 `tomcat:tomcat`),该选项需要 root;不填写则保留复制文件的属主,新上传文件使用 SSH 账号的属主。
|
||||
- HTTP 健康检查在服务器上发起,配置后要求响应为 2xx。留空时仅确认目标 Tomcat 进程连续运行 5 秒,**不代表业务接口一定正常**。
|
||||
|
||||
## 发布与恢复
|
||||
|
||||
先检查并上传、校验 SHA-256,之后停止 Tomcat、备份当前文件、移除旧 ROOT 解压目录并替换 WAR、替换 dist、启动并验证。仅发布前端时不停止 Tomcat。前端文件以整目录替换,不保留旧构建文件。
|
||||
|
||||
每次备份有独立清单,包含本次发布范围内的旧文件和“原文件不存在”的状态。按前端及 WAR 目标组合分组;每次成功后保留最近 **2 次**完整备份。失败时不清理备份,所以连续失败可能临时超过 2 次。手动回滚也会先备份当前版本,成功后同样保留 2 次。
|
||||
|
||||
自动恢复默认开启:替换或启动验证失败时恢复部署前文件,原本运行的 Tomcat 会尝试重新启动。若恢复也失败,会在日志中明确报告并留下备份路径。对于连接中断,远端结果可能未知,请重新连接检查服务和备份,勿仅根据本地报错判断服务器版本。
|
||||
|
||||
更新证书时先使用 OpenSSL 检查证书、有效期及公私钥匹配,再备份旧证书并原子替换。`nginx -t` 或重启失败时自动恢复旧证书;单独重启 Nginx 时也会先检查配置。证书和私钥目标不接受软链接,私钥权限设置为 `0600`,证书权限设置为 `0644`。
|
||||
|
||||
停止成功之后才做备份,保证旧应用目录的一致性,因此停机时间包含备份时间。路径锁防止同一目标或 Tomcat 实例被多个发布任务同时修改。
|
||||
|
||||
回滚仅覆盖部署文件,不回滚数据库。`dist` 与 `webapps/ROOT` 都按应用构建目录整体替换;上传文件、业务数据或独立配置应存放在这些目录之外。
|
||||
|
||||
## 本地数据
|
||||
|
||||
数据存放在 `%LOCALAPPDATA%\AutoDeploy`:
|
||||
|
||||
- `config.db`:多套服务器配置、**直接保存的账号密码**、发布历史;不使用 Windows 凭据管理器。
|
||||
- `known_hosts`:首次连接记住 SSH 主机公钥,再次连接时校验;公钥变化将拒绝连接。
|
||||
- `logs/`:运行日志,密码会被隐藏,历史配置不重复保存密码。
|
||||
|
||||
同一服务器的不同项目可以分别新增配置。启动时不填充演示服务器,也不会自动连接或发布。可以通过 `AUTODEPLOY_DATA` 环境变量指定独立的数据目录。
|
||||
|
||||
## 源码运行与构建
|
||||
|
||||
```powershell
|
||||
python -m pip install -r requirements.txt
|
||||
python main.py
|
||||
```
|
||||
|
||||
```powershell
|
||||
python -m pip install pyinstaller==6.13.0
|
||||
python tools/make_icon.py
|
||||
powershell -ExecutionPolicy Bypass -File build.ps1
|
||||
```
|
||||
|
||||
源码分工:`ui.py` 界面、`store.py` 配置与历史、`engine.py` SSH/上传工作线程、`remote.py` Linux 部署执行器。远端执行器作为源文件随 EXE 一起打包,无需在服务器安装 Paramiko 或 PySide6。
|
||||
|
||||
## 验证
|
||||
|
||||
```powershell
|
||||
python -m unittest discover -s tests -v
|
||||
python main.py --screenshot
|
||||
```
|
||||
|
||||
测试覆盖路径校验、压缩包校验、目录替换、备份与恢复、失败恢复、锁冲突、备份保留数量、SQLite 多配置,以及本机真实 SSH 密码认证。文件事务测试使用临时目录,Tomcat 停启及 Linux flock 由测试替身模拟;不等于已经在阿里云和真实 Tomcat 上验收。
|
||||
1
autodeploy/__init__.py
Normal file
@@ -0,0 +1 @@
|
||||
"""AutoDeploy desktop application."""
|
||||
BIN
autodeploy/app.ico
Normal file
|
After Width: | Height: | Size: 264 KiB |
262
autodeploy/engine.py
Normal file
@@ -0,0 +1,262 @@
|
||||
import base64
|
||||
import hashlib
|
||||
import json
|
||||
from pathlib import Path
|
||||
import posixpath
|
||||
import shlex
|
||||
import tarfile
|
||||
import tempfile
|
||||
import time
|
||||
import uuid
|
||||
import zipfile
|
||||
|
||||
import paramiko
|
||||
from PySide6.QtCore import QThread, Signal
|
||||
|
||||
from . import remote
|
||||
from .store import data_dir
|
||||
|
||||
|
||||
def validate_config(config):
|
||||
remote.validate(config)
|
||||
|
||||
|
||||
def package_front(source, output):
|
||||
source = Path(source)
|
||||
with tempfile.TemporaryDirectory() as scratch:
|
||||
root = source
|
||||
if source.is_file() and source.suffix.lower() == '.zip':
|
||||
root = Path(scratch)
|
||||
with zipfile.ZipFile(source) as z:
|
||||
for entry in z.infolist():
|
||||
path = Path(entry.filename.replace('\\', '/'))
|
||||
if path.is_absolute() or '..' in path.parts or ':' in entry.filename or (entry.external_attr >> 16) & 0o170000 == 0o120000:
|
||||
raise ValueError('ZIP 包包含不安全条目')
|
||||
z.extractall(root)
|
||||
if not (root / 'index.html').is_file() and (root / 'dist/index.html').is_file():
|
||||
root = root / 'dist'
|
||||
if not root.is_dir() or not (root / 'index.html').is_file():
|
||||
raise ValueError('请选择包含 index.html 的 dist 文件夹或 ZIP 压缩包')
|
||||
with tarfile.open(output, 'w:gz') as archive:
|
||||
for p in root.rglob('*'):
|
||||
if p.is_symlink():
|
||||
raise ValueError('前端目录不能包含软链接')
|
||||
if p.is_file():
|
||||
info = archive.gettarinfo(str(p), p.relative_to(root).as_posix())
|
||||
info.mode = 0o644
|
||||
with p.open('rb') as f:
|
||||
archive.addfile(info, f)
|
||||
|
||||
|
||||
class RememberHost(paramiko.MissingHostKeyPolicy):
|
||||
def missing_host_key(self, client, hostname, key):
|
||||
client.get_host_keys().add(hostname, key.get_name(), key)
|
||||
client.save_host_keys(str(data_dir() / 'known_hosts'))
|
||||
|
||||
|
||||
class Worker(QThread):
|
||||
message = Signal(str)
|
||||
progress = Signal(int)
|
||||
completed = Signal(bool, str, str)
|
||||
|
||||
def __init__(self, config, action='deploy', mode='all', backup='', parent=None):
|
||||
super().__init__(parent)
|
||||
self.config, self.action, self.mode = dict(config), action, mode
|
||||
self.restore_backup = backup
|
||||
self.backup = ''
|
||||
self.logs = []
|
||||
self.client = None
|
||||
self.remote_result = ''
|
||||
|
||||
def log(self, message):
|
||||
password = self.config.get('password')
|
||||
text = str(message).replace(password, '••••••') if password else str(message)
|
||||
line = time.strftime('%H:%M:%S') + ' ' + text
|
||||
self.logs.append(line)
|
||||
self.message.emit(line)
|
||||
|
||||
def run_remote(self, script, payload):
|
||||
encoded = base64.b64encode(json.dumps(payload).encode()).decode()
|
||||
command = 'python3 -u ' + shlex.quote(script) + ' ' + shlex.quote(encoded)
|
||||
channel = self.client.get_transport().open_session(timeout=15)
|
||||
channel.set_combine_stderr(True)
|
||||
channel.exec_command(command)
|
||||
channel.shutdown_write()
|
||||
buffer = b''
|
||||
# A silent, large backup can take a while. Socket liveness is still checked.
|
||||
last = time.monotonic()
|
||||
try:
|
||||
while True:
|
||||
if channel.recv_ready():
|
||||
chunk = channel.recv(65536)
|
||||
buffer += chunk
|
||||
last = time.monotonic()
|
||||
while b'\n' in buffer:
|
||||
line, buffer = buffer.split(b'\n', 1)
|
||||
self.consume(line)
|
||||
elif channel.exit_status_ready():
|
||||
break
|
||||
else:
|
||||
if not self.client.get_transport().is_active():
|
||||
raise ConnectionError('SSH 连接断开;远端操作结果未知,请重新连接检查服务和备份')
|
||||
if time.monotonic() - last > 7200:
|
||||
raise TimeoutError('远程任务长时间无响应;结果未知,请检查服务器')
|
||||
time.sleep(.05)
|
||||
if buffer:
|
||||
self.consume(buffer)
|
||||
code = channel.recv_exit_status()
|
||||
if code != 0:
|
||||
raise RuntimeError('远端任务失败,详见上方日志')
|
||||
finally:
|
||||
channel.close()
|
||||
|
||||
def consume(self, raw):
|
||||
line = raw.decode('utf-8', errors='replace')
|
||||
try:
|
||||
item = json.loads(line)
|
||||
except ValueError:
|
||||
self.log(line)
|
||||
return
|
||||
if not isinstance(item, dict) or 'message' not in item:
|
||||
self.log(line)
|
||||
return
|
||||
self.log(item['message'])
|
||||
if item.get('progress') is not None:
|
||||
self.progress.emit(item['progress'])
|
||||
if item.get('backup'):
|
||||
self.backup = item['backup']
|
||||
if item.get('result'):
|
||||
self.remote_result = item['result']
|
||||
|
||||
def run(self):
|
||||
ok = False
|
||||
sftp = None
|
||||
stage = None
|
||||
script = None
|
||||
dispatched = False
|
||||
try:
|
||||
c = self.config
|
||||
if not c['host'].strip() or not c['username'].strip():
|
||||
raise ValueError('请填写服务器地址和登录账号')
|
||||
if self.action != 'test':
|
||||
remote.validate(c)
|
||||
self.log('正在连接 {}:{} …'.format(c['host'], c['port']))
|
||||
self.progress.emit(3)
|
||||
self.client = paramiko.SSHClient()
|
||||
known = data_dir() / 'known_hosts'
|
||||
if known.exists():
|
||||
self.client.load_host_keys(str(known))
|
||||
self.client.set_missing_host_key_policy(RememberHost())
|
||||
self.client.connect(c['host'], port=int(c['port']), username=c['username'], password=c['password'],
|
||||
timeout=15, auth_timeout=20, banner_timeout=20, look_for_keys=False, allow_agent=False)
|
||||
self.client.get_transport().set_keepalive(15)
|
||||
self.log('SSH 连接成功')
|
||||
stdin, stdout, stderr = self.client.exec_command('python3 --version', timeout=15)
|
||||
version = stdout.read().decode().strip()
|
||||
error = stderr.read().decode().strip()
|
||||
if stdout.channel.recv_exit_status() != 0:
|
||||
raise RuntimeError('服务器需要 Python 3.8 或更新版本:' + error)
|
||||
try:
|
||||
version_parts = tuple(int(p) for p in version.split()[-1].split('.')[:2])
|
||||
except (ValueError, IndexError):
|
||||
raise RuntimeError('无法识别远端 Python 版本:' + version)
|
||||
if version_parts < (3, 6):
|
||||
raise RuntimeError('服务器需要 Python 3.6 或更新版本,当前为 ' + version)
|
||||
self.log(version)
|
||||
if self.action == 'test':
|
||||
self.progress.emit(100)
|
||||
ok = True
|
||||
return
|
||||
sftp = self.client.open_sftp()
|
||||
with tempfile.TemporaryDirectory(prefix='autodeploy-') as local:
|
||||
files = {}
|
||||
size = 0
|
||||
if self.action == 'deploy':
|
||||
if self.mode != 'frontend':
|
||||
war = Path(c['local_war'])
|
||||
if not war.is_file() or war.suffix.lower() != '.war' or not zipfile.is_zipfile(war):
|
||||
raise ValueError('请选择有效的 WAR 文件')
|
||||
with zipfile.ZipFile(war) as z:
|
||||
if z.testzip():
|
||||
raise ValueError('WAR 压缩包已损坏')
|
||||
size += sum(entry.file_size for entry in z.infolist())
|
||||
files['ROOT.war'] = war
|
||||
size += war.stat().st_size
|
||||
if self.mode != 'backend':
|
||||
self.log('正在打包前端文件…')
|
||||
archive = Path(local) / 'dist.tar.gz'
|
||||
package_front(c['local_front'], archive)
|
||||
files['dist.tar.gz'] = archive
|
||||
with tarfile.open(archive) as tf:
|
||||
size += sum(m.size for m in tf.getmembers())
|
||||
elif self.action == 'cert_deploy':
|
||||
cert = Path(c.get('local_cert', ''))
|
||||
key = Path(c.get('local_key', ''))
|
||||
if not cert.is_file() or not key.is_file():
|
||||
raise ValueError('请选择有效的证书文件和私钥文件')
|
||||
if cert.stat().st_size > 10 * 1024 * 1024 or key.stat().st_size > 10 * 1024 * 1024:
|
||||
raise ValueError('证书或私钥文件不能超过 10 MB')
|
||||
files['certificate.pem'] = cert
|
||||
files['private.key'] = key
|
||||
size = cert.stat().st_size + key.stat().st_size
|
||||
elif self.action not in ('rollback', 'nginx_restart'):
|
||||
raise ValueError('未知操作')
|
||||
# Bootstrap script goes to SFTP home, before configurable directories exist.
|
||||
script = posixpath.join(sftp.normalize('.'), '.autodeploy-runner-' + uuid.uuid4().hex + '.py')
|
||||
with sftp.file(script, 'w') as f:
|
||||
f.write(Path(remote.__file__).with_name('remote.py').read_bytes())
|
||||
sftp.chmod(script, 0o600)
|
||||
safe_config = {k: v for k, v in c.items()
|
||||
if k not in ('password', 'local_war', 'local_front', 'local_cert', 'local_key')}
|
||||
payload = dict(config=safe_config, mode=self.mode, size=size, operation=self.action)
|
||||
self.run_remote(script, dict(payload, action='preflight'))
|
||||
if self.action == 'nginx_restart':
|
||||
dispatched = True
|
||||
self.run_remote(script, dict(payload, action=self.action))
|
||||
ok = True
|
||||
return
|
||||
stage = posixpath.join(c['temp'], 'autodeploy-' + uuid.uuid4().hex)
|
||||
sftp.mkdir(stage, 0o700)
|
||||
total = sum(p.stat().st_size for p in files.values()) or 1
|
||||
transferred = 0
|
||||
hashes = {}
|
||||
for name, path in files.items():
|
||||
self.log('正在上传 ' + name)
|
||||
h = hashlib.sha256()
|
||||
with path.open('rb') as f:
|
||||
for block in iter(lambda: f.read(1024 * 1024), b''):
|
||||
h.update(block)
|
||||
hashes[name] = h.hexdigest()
|
||||
sftp.put(str(path), posixpath.join(stage, name),
|
||||
callback=lambda current, amount: self.progress.emit(15 + int(20 * (transferred + current) / total)))
|
||||
transferred += path.stat().st_size
|
||||
dispatched = True
|
||||
self.run_remote(script, dict(payload, action=self.action, stage=stage, hashes=hashes, backup=self.restore_backup))
|
||||
ok = True
|
||||
except Exception as exc:
|
||||
self.log(str(exc))
|
||||
finally:
|
||||
if sftp:
|
||||
if stage and not dispatched:
|
||||
for name in ('ROOT.war', 'dist.tar.gz', 'certificate.pem', 'private.key'):
|
||||
try:
|
||||
sftp.remove(posixpath.join(stage, name))
|
||||
except Exception:
|
||||
pass
|
||||
try:
|
||||
sftp.rmdir(stage)
|
||||
except Exception:
|
||||
pass
|
||||
# Only remove known uploaded files; never delete a remote running transaction.
|
||||
if script:
|
||||
try:
|
||||
sftp.remove(script)
|
||||
except Exception:
|
||||
pass
|
||||
try:
|
||||
sftp.close()
|
||||
except Exception:
|
||||
pass
|
||||
if self.client:
|
||||
self.client.close()
|
||||
self.completed.emit(ok, '\n'.join(self.logs), self.backup)
|
||||
701
autodeploy/remote.py
Normal file
@@ -0,0 +1,701 @@
|
||||
"""Self-contained Python 3 deployment runner, executed on the Linux server.
|
||||
|
||||
Only paths in the supplied deployment configuration are mutated. Credentials never
|
||||
leave the SSH client. JSON line events form the desktop/runner protocol.
|
||||
"""
|
||||
import base64
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path, PurePosixPath
|
||||
import re
|
||||
import shutil
|
||||
import signal
|
||||
import subprocess
|
||||
import sys
|
||||
import tarfile
|
||||
import time
|
||||
import urllib.request
|
||||
import uuid
|
||||
|
||||
|
||||
def event(message, progress=None, **extra):
|
||||
try:
|
||||
print(json.dumps(dict(message=message, progress=progress, **extra), ensure_ascii=False), flush=True)
|
||||
except BrokenPipeError:
|
||||
# SSH may disappear mid-transaction. Do not let a logging failure stop recovery.
|
||||
sys.stdout = open(os.devnull, 'w')
|
||||
|
||||
|
||||
def validate(c):
|
||||
keys = ('front', 'war', 'tomcat', 'startup', 'shutdown', 'temp', 'backups')
|
||||
for key in keys:
|
||||
value = c[key]
|
||||
p = PurePosixPath(value)
|
||||
if not p.is_absolute() or '..' in p.parts or '\x00' in value or '\n' in value or str(p) in ('/', '/home', '/usr', '/usr/local', '/tmp', '/var', '/etc', '/root'):
|
||||
raise ValueError('路径必须为明确的绝对路径,不能是系统根目录:' + key)
|
||||
# Reject symlink parents too: backups and renames must stay in the configured tree.
|
||||
if os.name == 'posix' and any(Path(x).is_symlink() for x in [p, *p.parents]):
|
||||
raise ValueError('部署路径不能包含软链接:' + value)
|
||||
if PurePosixPath(c['war']).name != 'ROOT.war':
|
||||
raise ValueError('后端目标文件名必须为 ROOT.war')
|
||||
roots = [PurePosixPath(c[k]) for k in ('front', 'temp', 'backups')] + [PurePosixPath(c['war']).parent]
|
||||
for i, a in enumerate(roots):
|
||||
for b in roots[i + 1:]:
|
||||
if a == b or a in b.parents or b in a.parents:
|
||||
raise ValueError('前端、webapps、临时目录和备份目录不能相互包含')
|
||||
front = PurePosixPath(c['front'])
|
||||
tc = PurePosixPath(c['tomcat'])
|
||||
if front == tc or front in tc.parents or tc in front.parents:
|
||||
raise ValueError('前端目录不能与 Tomcat 实例目录重叠')
|
||||
for key in ('stop_timeout', 'start_timeout'):
|
||||
if not 1 <= int(c[key]) <= 3600:
|
||||
raise ValueError('超时必须介于 1 到 3600 秒')
|
||||
if c.get('service') and not re.fullmatch(r'[A-Za-z0-9_@.:-]+', c['service']):
|
||||
raise ValueError('systemd 服务名格式无效')
|
||||
if c.get('health') and not c['health'].startswith(('http://', 'https://')):
|
||||
raise ValueError('健康检查地址必须为 HTTP 或 HTTPS')
|
||||
validate_nginx(c)
|
||||
|
||||
|
||||
def validate_nginx(c, require_files=False):
|
||||
service = c.get('nginx_service', 'nginx.service')
|
||||
if not service or not re.fullmatch(r'[A-Za-z0-9_@.:-]+', service):
|
||||
raise ValueError('Nginx systemd 服务名格式无效')
|
||||
for key, default in (('nginx_binary', '/usr/sbin/nginx'), ('nginx_cert_dir', '/home/ssl')):
|
||||
value = c.get(key, default)
|
||||
p = PurePosixPath(value)
|
||||
if not p.is_absolute() or '..' in p.parts or '\x00' in value or '\n' in value or str(p) in ('/', '/home', '/usr', '/etc', '/root'):
|
||||
raise ValueError('Nginx 路径必须为明确的绝对路径:' + key)
|
||||
names = (c.get('nginx_cert_name', ''), c.get('nginx_key_name', ''))
|
||||
if require_files and not all(names):
|
||||
raise ValueError('请填写服务器证书和私钥文件名')
|
||||
for name in names:
|
||||
if name and (PurePosixPath(name).name != name or not re.fullmatch(r'[A-Za-z0-9._-]+', name) or name in ('.', '..')):
|
||||
raise ValueError('证书和私钥只能填写安全的文件名,不能包含路径')
|
||||
if all(names) and names[0] == names[1]:
|
||||
raise ValueError('证书和私钥不能使用同一个目标文件名')
|
||||
|
||||
|
||||
def project_key(c):
|
||||
return hashlib.sha256((c['front'] + '\n' + c['war']).encode()).hexdigest()[:16]
|
||||
|
||||
|
||||
def time_nonce():
|
||||
"""Return a nanosecond-style suffix on Python 3.6 and newer."""
|
||||
clock = getattr(time, 'time_ns', None)
|
||||
now = clock() if clock else int(time.time() * 1000000000)
|
||||
return now % 1000000000
|
||||
|
||||
|
||||
def pids(c):
|
||||
result = []
|
||||
expected = '-Dcatalina.base=' + c['tomcat'].rstrip('/')
|
||||
for p in Path('/proc').glob('[0-9]*/cmdline'):
|
||||
try:
|
||||
args = p.read_bytes().decode(errors='replace').split('\0')
|
||||
if expected in args and 'org.apache.catalina.startup.Bootstrap' in args and 'start' in args:
|
||||
result.append(int(p.parent.name))
|
||||
except (OSError, ValueError):
|
||||
pass
|
||||
return result
|
||||
|
||||
|
||||
def script(c, start):
|
||||
env = os.environ.copy()
|
||||
env['CATALINA_BASE'] = c['tomcat']
|
||||
env['CATALINA_HOME'] = c['tomcat']
|
||||
if c.get('java_home'):
|
||||
env['JAVA_HOME'] = c['java_home']
|
||||
cmd = ['systemctl', 'start' if start else 'stop', c['service']] if c.get('service') else ['sh', c['startup' if start else 'shutdown']]
|
||||
# Files instead of pipes: a daemon inheriting stdout must not keep communicate() open.
|
||||
import tempfile
|
||||
with tempfile.TemporaryFile() as output:
|
||||
proc = subprocess.Popen(cmd, cwd=c['tomcat'], env=env, stdout=output, stderr=output,
|
||||
stdin=subprocess.DEVNULL, start_new_session=True)
|
||||
try:
|
||||
proc.wait(timeout=int(c['start_timeout' if start else 'stop_timeout']))
|
||||
except subprocess.TimeoutExpired:
|
||||
proc.kill()
|
||||
proc.wait()
|
||||
raise RuntimeError('启动/停止命令执行超时')
|
||||
output.seek(0)
|
||||
msg = output.read(16000).decode(errors='replace').strip()
|
||||
if msg:
|
||||
event(msg)
|
||||
if proc.returncode:
|
||||
raise RuntimeError('命令退出码:' + str(proc.returncode))
|
||||
|
||||
|
||||
def command(args, timeout=60, error='命令执行失败'):
|
||||
proc = subprocess.run(args, stdout=subprocess.PIPE, stderr=subprocess.STDOUT,
|
||||
stdin=subprocess.DEVNULL, timeout=timeout)
|
||||
output = proc.stdout.decode(errors='replace').strip()
|
||||
if output:
|
||||
event(output)
|
||||
if proc.returncode:
|
||||
raise RuntimeError('{}(退出码 {}){}'.format(error, proc.returncode,
|
||||
':' + output if output else ''))
|
||||
return proc.stdout
|
||||
|
||||
|
||||
def nginx_test(c, progress=70):
|
||||
event('正在检查 Nginx 配置…', progress)
|
||||
command([c.get('nginx_binary', '/usr/sbin/nginx'), '-t'], error='Nginx 配置检查失败')
|
||||
event('Nginx 配置检查通过')
|
||||
|
||||
|
||||
def nginx_active(c):
|
||||
proc = subprocess.run(['systemctl', 'is-active', '--quiet', c.get('nginx_service', 'nginx.service')],
|
||||
stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL,
|
||||
stdin=subprocess.DEVNULL, timeout=30)
|
||||
return proc.returncode == 0
|
||||
|
||||
|
||||
def restart_nginx(c, progress=85):
|
||||
event('正在重启 Nginx…', progress)
|
||||
command(['systemctl', 'restart', c.get('nginx_service', 'nginx.service')],
|
||||
timeout=int(c.get('start_timeout', 120)), error='Nginx 重启失败')
|
||||
if not nginx_active(c):
|
||||
raise RuntimeError('Nginx 重启后未处于 active 状态')
|
||||
event('Nginx 已正常运行')
|
||||
|
||||
|
||||
def wait_stopped(c, timeout):
|
||||
end = time.monotonic() + timeout
|
||||
while time.monotonic() < end:
|
||||
if not pids(c):
|
||||
return True
|
||||
time.sleep(.5)
|
||||
return not pids(c)
|
||||
|
||||
|
||||
def stop(c):
|
||||
event('正在停止目标 Tomcat…', 55)
|
||||
try:
|
||||
script(c, False)
|
||||
except Exception as exc:
|
||||
if c.get('service'):
|
||||
raise # Never fight a service manager's automatic restart policy.
|
||||
event('停止脚本未成功,继续核对进程:' + str(exc))
|
||||
if not wait_stopped(c, int(c['stop_timeout'])):
|
||||
for sig, seconds in ((signal.SIGTERM, 5), (signal.SIGKILL, 5)):
|
||||
for pid in pids(c):
|
||||
try:
|
||||
os.kill(pid, sig)
|
||||
event('终止 Tomcat PID {}({})'.format(pid, sig.name))
|
||||
except ProcessLookupError:
|
||||
pass
|
||||
if wait_stopped(c, seconds):
|
||||
break
|
||||
if pids(c):
|
||||
raise RuntimeError('Tomcat 未完全停止,已中止文件替换')
|
||||
|
||||
|
||||
def start(c):
|
||||
event('正在启动 Tomcat…', 85)
|
||||
script(c, True)
|
||||
end = time.monotonic() + int(c['start_timeout'])
|
||||
stable = 0
|
||||
while time.monotonic() < end:
|
||||
if pids(c):
|
||||
if c.get('health'):
|
||||
try:
|
||||
with urllib.request.urlopen(c['health'], timeout=3) as response:
|
||||
if 200 <= response.status < 300:
|
||||
event('Tomcat 进程与 HTTP 健康检查通过', 96)
|
||||
return
|
||||
except Exception:
|
||||
pass
|
||||
else:
|
||||
stable += 1
|
||||
if stable >= 5:
|
||||
event('Tomcat 进程已连续运行 5 秒;未配置 HTTP 检查', 96)
|
||||
return
|
||||
else:
|
||||
stable = 0
|
||||
time.sleep(1)
|
||||
log = Path(c['tomcat']) / 'logs/catalina.out'
|
||||
if log.is_file():
|
||||
with log.open('rb') as f:
|
||||
f.seek(max(0, log.stat().st_size - 12000))
|
||||
event(f.read().decode(errors='replace'))
|
||||
raise RuntimeError('Tomcat 启动验证超时')
|
||||
|
||||
|
||||
def remove(p):
|
||||
if p.is_symlink() or p.is_file():
|
||||
p.unlink()
|
||||
elif p.exists():
|
||||
shutil.rmtree(p)
|
||||
|
||||
|
||||
def copy(src, dst):
|
||||
if src.is_symlink():
|
||||
raise RuntimeError('发布文件不能是软链接:' + str(src))
|
||||
if src.is_dir():
|
||||
shutil.copytree(src, dst, symlinks=True)
|
||||
else:
|
||||
shutil.copy2(src, dst)
|
||||
if os.name == 'posix' and os.geteuid() == 0:
|
||||
for p in [src] + (list(src.rglob('*')) if src.is_dir() else []):
|
||||
dest = dst if p == src else dst / p.relative_to(src)
|
||||
stat = p.lstat()
|
||||
os.chown(str(dest), stat.st_uid, stat.st_gid, follow_symlinks=False)
|
||||
|
||||
|
||||
def tree_size(p):
|
||||
if not p.exists():
|
||||
return 0
|
||||
if p.is_file():
|
||||
return p.stat().st_size
|
||||
return sum(x.stat().st_size for x in p.rglob('*') if x.is_file() and not x.is_symlink())
|
||||
|
||||
|
||||
def targets(c, mode):
|
||||
entries = {}
|
||||
if mode in ('all', 'backend'):
|
||||
entries.update(war=c['war'], root=str(Path(c['war']).with_suffix('')))
|
||||
if mode in ('all', 'frontend'):
|
||||
entries['front'] = c['front']
|
||||
return entries
|
||||
|
||||
|
||||
def preflight(c, mode, size=0):
|
||||
validate(c)
|
||||
if mode not in ('all', 'backend', 'frontend'):
|
||||
raise ValueError('未知部署模式')
|
||||
for target in targets(c, mode).values():
|
||||
path = Path(target)
|
||||
if any(p.is_symlink() for p in [path, *path.parents]):
|
||||
raise ValueError('目标路径不能包含软链接:' + target)
|
||||
if mode != 'frontend':
|
||||
if not Path(c['tomcat']).is_dir():
|
||||
raise RuntimeError('Tomcat 目录不存在')
|
||||
if not c.get('service'):
|
||||
for k in ('startup', 'shutdown'):
|
||||
if not Path(c[k]).is_file():
|
||||
raise RuntimeError('脚本不存在:' + c[k])
|
||||
paths = [Path(c['temp']), Path(c['backups'])] + [Path(p).parent for p in targets(c, mode).values()]
|
||||
old_size = sum(tree_size(Path(p)) for p in targets(c, mode).values())
|
||||
for path in paths:
|
||||
path.mkdir(parents=True, exist_ok=True)
|
||||
probe = path / ('.autodeploy-probe-' + uuid.uuid4().hex)
|
||||
probe.write_text('ok')
|
||||
probe.unlink()
|
||||
if shutil.disk_usage(path).free < old_size * 2 + int(size) * 3 + 32 * 1024 * 1024:
|
||||
raise RuntimeError('磁盘可用空间不足:' + str(path))
|
||||
if c.get('owner'):
|
||||
import pwd
|
||||
import grp
|
||||
user, _, group = c['owner'].partition(':')
|
||||
pwd.getpwnam(user)
|
||||
if group:
|
||||
grp.getgrnam(group)
|
||||
if os.geteuid() != 0:
|
||||
raise RuntimeError('配置文件属主需要 root 权限')
|
||||
event('路径、权限与磁盘检查通过', 12)
|
||||
|
||||
|
||||
def nginx_targets(c):
|
||||
root = Path(c.get('nginx_cert_dir', '/home/ssl'))
|
||||
return {'certificate': str(root / c['nginx_cert_name']),
|
||||
'private_key': str(root / c['nginx_key_name'])}
|
||||
|
||||
|
||||
def nginx_preflight(c, certificate=False, size=0):
|
||||
validate_nginx(c, require_files=certificate)
|
||||
binary = Path(c.get('nginx_binary', '/usr/sbin/nginx'))
|
||||
if not binary.is_file() or not os.access(str(binary), os.X_OK):
|
||||
raise RuntimeError('Nginx 可执行文件不存在或不可执行:' + str(binary))
|
||||
if not shutil.which('systemctl'):
|
||||
raise RuntimeError('服务器缺少 systemctl,当前版本只支持 systemd 管理的 Nginx')
|
||||
if certificate:
|
||||
if not shutil.which('openssl'):
|
||||
raise RuntimeError('服务器缺少 openssl,无法校验证书和私钥')
|
||||
root = Path(c.get('nginx_cert_dir', '/home/ssl'))
|
||||
backup_root = nginx_backup_root(c)
|
||||
for directory, caption in ((root, '证书目录'), (backup_root, '证书备份目录')):
|
||||
if any(p.is_symlink() for p in [directory, *directory.parents]):
|
||||
raise ValueError(caption + '不能包含软链接:' + str(directory))
|
||||
directory.mkdir(parents=True, exist_ok=True)
|
||||
probe = directory / ('.autodeploy-probe-' + uuid.uuid4().hex)
|
||||
probe.write_text('ok')
|
||||
probe.unlink()
|
||||
if shutil.disk_usage(directory).free < int(size) * 3 + 1024 * 1024:
|
||||
raise RuntimeError(caption + '可用空间不足:' + str(directory))
|
||||
for target in nginx_targets(c).values():
|
||||
path = Path(target)
|
||||
if path.is_symlink():
|
||||
raise ValueError('证书目标不能是软链接:' + target)
|
||||
if path.exists() and not path.is_file():
|
||||
raise ValueError('证书目标不是普通文件:' + target)
|
||||
event('Nginx、路径与权限检查通过', 12)
|
||||
|
||||
|
||||
def snapshot(c, mode):
|
||||
root = Path(c['backups']) / project_key(c)
|
||||
root.mkdir(parents=True, exist_ok=True)
|
||||
backup = root / (time.strftime('%Y%m%d-%H%M%S') + '-{:09d}-'.format(time_nonce()) + uuid.uuid4().hex[:8])
|
||||
backup.mkdir()
|
||||
manifest = dict(mode=mode, targets=targets(c, mode), present={}, complete=False)
|
||||
for name, path in manifest['targets'].items():
|
||||
src = Path(path)
|
||||
manifest['present'][name] = src.exists()
|
||||
if src.exists():
|
||||
copy(src, backup / name)
|
||||
manifest['complete'] = True
|
||||
(backup / 'manifest.json').write_text(json.dumps(manifest), encoding='utf-8')
|
||||
event('已备份当前版本', 48, backup=str(backup))
|
||||
return backup
|
||||
|
||||
|
||||
def load_backup(c, path):
|
||||
p = Path(path)
|
||||
expected = Path(c['backups']) / project_key(c)
|
||||
if p.parent != expected or p.is_symlink() or p.resolve().parent != expected.resolve():
|
||||
raise ValueError('备份不属于当前项目')
|
||||
m = json.loads((p / 'manifest.json').read_text(encoding='utf-8'))
|
||||
if not m.get('complete') or m['targets'] != targets(c, m['mode']):
|
||||
raise ValueError('备份不完整或目标路径不匹配')
|
||||
for name, present in m['present'].items():
|
||||
if present and not (p / name).exists():
|
||||
raise ValueError('备份文件缺失:' + name)
|
||||
return m
|
||||
|
||||
|
||||
def restore(c, backup):
|
||||
m = load_backup(c, str(backup))
|
||||
for name, path in m['targets'].items():
|
||||
dst = Path(path)
|
||||
remove(dst)
|
||||
if m['present'][name]:
|
||||
copy(backup / name, dst)
|
||||
ownership(c, dst)
|
||||
|
||||
|
||||
def ownership(c, path):
|
||||
if not c.get('owner'):
|
||||
return
|
||||
import pwd
|
||||
import grp
|
||||
user, _, group = c['owner'].partition(':')
|
||||
account = pwd.getpwnam(user)
|
||||
uid, gid = account.pw_uid, grp.getgrnam(group).gr_gid if group else account.pw_gid
|
||||
for p in [path] + (list(path.rglob('*')) if path.is_dir() else []):
|
||||
os.chown(str(p), uid, gid, follow_symlinks=False)
|
||||
|
||||
|
||||
def unpack(archive, destination):
|
||||
destination.mkdir()
|
||||
with tarfile.open(archive, 'r:gz') as tf:
|
||||
for member in tf.getmembers():
|
||||
p = Path(member.name)
|
||||
if p.is_absolute() or '..' in p.parts or not (member.isfile() or member.isdir()):
|
||||
raise ValueError('前端压缩包包含不安全条目')
|
||||
tf.extractall(destination)
|
||||
if not (destination / 'index.html').is_file():
|
||||
raise ValueError('前端目录中找不到 index.html')
|
||||
|
||||
|
||||
def install(src, dst, c):
|
||||
staged = dst.parent / ('.autodeploy-new-' + uuid.uuid4().hex)
|
||||
try:
|
||||
copy(src, staged)
|
||||
ownership(c, staged)
|
||||
remove(dst)
|
||||
os.replace(staged, dst)
|
||||
finally:
|
||||
remove(staged)
|
||||
|
||||
|
||||
def prune(c):
|
||||
root = Path(c['backups']) / project_key(c)
|
||||
completed = sorted(p for p in root.iterdir() if p.is_dir() and not p.is_symlink() and (p / 'manifest.json').is_file())
|
||||
for p in completed[:-2]:
|
||||
remove(p)
|
||||
event('备份已保留最近 2 次')
|
||||
|
||||
|
||||
def nginx_backup_root(c):
|
||||
targets = nginx_targets(c)
|
||||
key = hashlib.sha256((targets['certificate'] + '\n' + targets['private_key']).encode()).hexdigest()[:16]
|
||||
return Path(c['backups']) / ('nginx-' + key)
|
||||
|
||||
|
||||
def nginx_snapshot(c):
|
||||
root = nginx_backup_root(c)
|
||||
root.mkdir(parents=True, exist_ok=True)
|
||||
backup = root / (time.strftime('%Y%m%d-%H%M%S') + '-{:09d}-'.format(time_nonce()) + uuid.uuid4().hex[:8])
|
||||
backup.mkdir()
|
||||
manifest = dict(kind='nginx-certificate', targets=nginx_targets(c), present={}, complete=False)
|
||||
for name, path in manifest['targets'].items():
|
||||
src = Path(path)
|
||||
manifest['present'][name] = src.exists()
|
||||
if src.exists():
|
||||
copy(src, backup / name)
|
||||
manifest['complete'] = True
|
||||
(backup / 'manifest.json').write_text(json.dumps(manifest), encoding='utf-8')
|
||||
event('已备份当前证书', 48, backup=str(backup))
|
||||
return backup
|
||||
|
||||
|
||||
def load_nginx_backup(c, backup):
|
||||
path = Path(backup)
|
||||
expected = nginx_backup_root(c)
|
||||
if path.parent != expected or path.is_symlink() or path.resolve().parent != expected.resolve():
|
||||
raise ValueError('证书备份不属于当前配置')
|
||||
manifest = json.loads((path / 'manifest.json').read_text(encoding='utf-8'))
|
||||
if (not manifest.get('complete') or manifest.get('kind') != 'nginx-certificate' or
|
||||
manifest.get('targets') != nginx_targets(c)):
|
||||
raise ValueError('证书备份不完整或目标路径不匹配')
|
||||
for name, present in manifest['present'].items():
|
||||
if present and not (path / name).is_file():
|
||||
raise ValueError('证书备份文件缺失:' + name)
|
||||
return manifest
|
||||
|
||||
|
||||
def replace_secure(src, dst, mode, preserve_from=None):
|
||||
if dst.is_symlink() or any(p.is_symlink() for p in dst.parents):
|
||||
raise ValueError('证书目标不能包含软链接:' + str(dst))
|
||||
staged = dst.parent / ('.autodeploy-new-' + uuid.uuid4().hex)
|
||||
try:
|
||||
shutil.copy2(str(src), str(staged))
|
||||
os.chmod(str(staged), mode)
|
||||
reference = preserve_from if preserve_from and preserve_from.exists() else (dst if dst.exists() else None)
|
||||
if reference is not None and os.name == 'posix' and os.geteuid() == 0:
|
||||
stat = reference.stat()
|
||||
os.chown(str(staged), stat.st_uid, stat.st_gid)
|
||||
os.replace(str(staged), str(dst))
|
||||
finally:
|
||||
if staged.exists():
|
||||
staged.unlink()
|
||||
|
||||
|
||||
def restore_nginx_certificate(c, backup):
|
||||
manifest = load_nginx_backup(c, backup)
|
||||
for name, target in manifest['targets'].items():
|
||||
dst = Path(target)
|
||||
if manifest['present'][name]:
|
||||
source = Path(backup) / name
|
||||
replace_secure(source, dst, source.stat().st_mode & 0o777, source)
|
||||
elif dst.exists():
|
||||
dst.unlink()
|
||||
|
||||
|
||||
def prune_nginx(c):
|
||||
root = nginx_backup_root(c)
|
||||
completed = sorted(p for p in root.iterdir() if p.is_dir() and not p.is_symlink() and (p / 'manifest.json').is_file())
|
||||
for path in completed[:-2]:
|
||||
remove(path)
|
||||
event('证书备份已保留最近 2 次')
|
||||
|
||||
|
||||
def openssl_output(args, error):
|
||||
proc = subprocess.run(['openssl'] + args, stdout=subprocess.PIPE, stderr=subprocess.PIPE,
|
||||
stdin=subprocess.DEVNULL, timeout=30)
|
||||
if proc.returncode:
|
||||
detail = proc.stderr.decode(errors='replace').strip()
|
||||
raise ValueError(error + (':' + detail if detail else ''))
|
||||
return proc.stdout
|
||||
|
||||
|
||||
def validate_certificate_pair(cert, key):
|
||||
openssl_output(['x509', '-in', str(cert), '-noout'], '证书格式无效')
|
||||
openssl_output(['pkey', '-in', str(key), '-noout'], '私钥格式无效或私钥已加密')
|
||||
if openssl_output(['x509', '-in', str(cert), '-pubkey', '-noout'], '无法读取证书公钥').strip() != \
|
||||
openssl_output(['pkey', '-in', str(key), '-pubout'], '无法读取私钥公钥').strip():
|
||||
raise ValueError('证书与私钥不匹配')
|
||||
openssl_output(['x509', '-in', str(cert), '-checkend', '0', '-noout'], '证书已经过期')
|
||||
details = openssl_output(['x509', '-in', str(cert), '-subject', '-issuer', '-dates', '-noout'],
|
||||
'无法读取证书信息').decode(errors='replace').strip()
|
||||
event('证书与私钥校验通过' + (':\n' + details if details else ''), 40)
|
||||
|
||||
|
||||
def nginx_lock_path(c):
|
||||
name = c.get('nginx_service', 'nginx.service') + '\n' + c.get('nginx_cert_dir', '/home/ssl')
|
||||
return Path('/tmp') / ('.autodeploy-nginx-' + hashlib.sha256(name.encode()).hexdigest()[:16] + '.lock')
|
||||
|
||||
|
||||
def nginx_restart_transaction(c):
|
||||
import fcntl
|
||||
with nginx_lock_path(c).open('a') as lock:
|
||||
fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB)
|
||||
nginx_test(c, 45)
|
||||
restart_nginx(c, 75)
|
||||
event('Nginx 重启成功', 100, result='success')
|
||||
|
||||
|
||||
def certificate_transaction(c, stage):
|
||||
import fcntl
|
||||
cert = stage / 'certificate.pem'
|
||||
key = stage / 'private.key'
|
||||
validate_certificate_pair(cert, key)
|
||||
backup = None
|
||||
touched = False
|
||||
was_active = nginx_active(c)
|
||||
with nginx_lock_path(c).open('a') as lock:
|
||||
fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB)
|
||||
try:
|
||||
backup = nginx_snapshot(c)
|
||||
touched = True
|
||||
targets = nginx_targets(c)
|
||||
event('正在原子替换证书和私钥…', 62)
|
||||
replace_secure(cert, Path(targets['certificate']), 0o644)
|
||||
replace_secure(key, Path(targets['private_key']), 0o600)
|
||||
nginx_test(c, 72)
|
||||
restart_nginx(c, 86)
|
||||
event('证书更新并重启 Nginx 成功', 100, result='success')
|
||||
try:
|
||||
prune_nginx(c)
|
||||
except Exception as exc:
|
||||
event('证书更新已完成,旧备份清理失败:' + str(exc))
|
||||
except Exception as exc:
|
||||
event('证书更新失败:' + str(exc))
|
||||
if touched and backup:
|
||||
try:
|
||||
event('正在恢复更新前的证书…')
|
||||
restore_nginx_certificate(c, backup)
|
||||
if was_active:
|
||||
nginx_test(c)
|
||||
restart_nginx(c)
|
||||
event('已恢复更新前的证书' + (',Nginx 已恢复' if was_active else ''), result='rolled_back')
|
||||
except Exception as restore_error:
|
||||
event('证书自动恢复失败,请查看备份:{};{}'.format(backup, restore_error), result='recovery_failed')
|
||||
raise
|
||||
|
||||
|
||||
def transaction(c, mode, stage, rollback=None):
|
||||
import fcntl
|
||||
# Lock by each target AND instance, so overlapping profiles cannot deploy together.
|
||||
lock_paths = [Path(p).parent / ('.autodeploy-' + Path(p).name + '.lock') for p in targets(c, mode).values()]
|
||||
if mode != 'frontend':
|
||||
lock_paths.append(Path(c['tomcat']) / '.autodeploy.lock')
|
||||
locks = []
|
||||
backup = None
|
||||
touched = False
|
||||
stopped = False
|
||||
was_running = bool(pids(c)) if mode != 'frontend' else False
|
||||
try:
|
||||
for path in sorted(set(lock_paths)):
|
||||
handle = path.open('a')
|
||||
locks.append(handle)
|
||||
fcntl.flock(handle, fcntl.LOCK_EX | fcntl.LOCK_NB)
|
||||
if mode != 'frontend':
|
||||
stopped = True
|
||||
stop(c)
|
||||
# Snapshot after shutdown so the exploded application is consistent.
|
||||
backup = snapshot(c, mode)
|
||||
touched = True
|
||||
event('正在替换部署文件…', 68)
|
||||
if rollback:
|
||||
restore(c, Path(rollback))
|
||||
else:
|
||||
if mode != 'frontend':
|
||||
remove(Path(c['war']).with_suffix(''))
|
||||
install(stage / 'ROOT.war', Path(c['war']), c)
|
||||
if mode != 'backend':
|
||||
install(stage / 'dist', Path(c['front']), c)
|
||||
if mode != 'frontend':
|
||||
start(c)
|
||||
event('回滚成功' if rollback else '部署成功', 100, result='success')
|
||||
try:
|
||||
prune(c)
|
||||
except Exception as exc:
|
||||
event('发布已完成,旧备份清理失败:' + str(exc))
|
||||
except Exception as exc:
|
||||
event('操作失败:' + str(exc))
|
||||
if touched and backup and c.get('auto_rollback', True):
|
||||
try:
|
||||
event('正在自动恢复部署前版本…')
|
||||
if mode != 'frontend':
|
||||
stop(c)
|
||||
restore(c, backup)
|
||||
if mode != 'frontend' and was_running:
|
||||
start(c)
|
||||
event('已恢复部署前文件' + (',服务已恢复' if was_running else ''), result='rolled_back')
|
||||
except Exception as restore_error:
|
||||
event('自动恢复失败,请查看备份:{};{}'.format(backup, restore_error), result='recovery_failed')
|
||||
elif stopped and not touched and was_running:
|
||||
try:
|
||||
if not pids(c):
|
||||
start(c)
|
||||
except Exception as restart_error:
|
||||
event('恢复原服务失败:' + str(restart_error))
|
||||
raise
|
||||
finally:
|
||||
for handle in locks:
|
||||
handle.close()
|
||||
|
||||
|
||||
def main():
|
||||
if hasattr(signal, 'SIGHUP'):
|
||||
signal.signal(signal.SIGHUP, signal.SIG_IGN)
|
||||
args = json.loads(base64.b64decode(sys.argv[1]))
|
||||
c, action = args['config'], args['action']
|
||||
mode = args.get('mode', 'all')
|
||||
if action == 'preflight':
|
||||
if args.get('operation') in ('cert_deploy', 'nginx_restart'):
|
||||
nginx_preflight(c, args.get('operation') == 'cert_deploy', args.get('size', 0))
|
||||
else:
|
||||
preflight(c, mode, args.get('size', 0))
|
||||
return
|
||||
if action == 'nginx_restart':
|
||||
nginx_preflight(c)
|
||||
nginx_restart_transaction(c)
|
||||
return
|
||||
if action == 'cert_deploy':
|
||||
validate_nginx(c, require_files=True)
|
||||
else:
|
||||
validate(c)
|
||||
stage = Path(args['stage'])
|
||||
if stage.parent != Path(c['temp']) or not re.fullmatch(r'autodeploy-[a-f0-9]{32}', stage.name) or stage.is_symlink():
|
||||
raise ValueError('临时目录无效')
|
||||
try:
|
||||
if action == 'cert_deploy':
|
||||
expected = {'certificate.pem', 'private.key'}
|
||||
if set(args.get('hashes', {})) != expected:
|
||||
raise ValueError('证书上传文件不完整')
|
||||
for filename, digest in args['hashes'].items():
|
||||
h = hashlib.sha256()
|
||||
with (stage / filename).open('rb') as f:
|
||||
for chunk in iter(lambda: f.read(1024 * 1024), b''):
|
||||
h.update(chunk)
|
||||
if h.hexdigest() != digest:
|
||||
raise ValueError('上传文件校验失败:' + filename)
|
||||
nginx_preflight(c, True, args.get('size', 0))
|
||||
event('上传内容校验通过', 36)
|
||||
certificate_transaction(c, stage)
|
||||
elif action == 'rollback':
|
||||
mode = load_backup(c, args['backup'])['mode']
|
||||
elif action == 'deploy':
|
||||
for filename, digest in args['hashes'].items():
|
||||
if filename not in ('ROOT.war', 'dist.tar.gz'):
|
||||
raise ValueError('未知部署文件')
|
||||
h = hashlib.sha256()
|
||||
with (stage / filename).open('rb') as f:
|
||||
for chunk in iter(lambda: f.read(1024 * 1024), b''):
|
||||
h.update(chunk)
|
||||
if h.hexdigest() != digest:
|
||||
raise ValueError('上传文件校验失败:' + filename)
|
||||
if mode != 'backend':
|
||||
unpack(stage / 'dist.tar.gz', stage / 'dist')
|
||||
else:
|
||||
raise ValueError('未知操作')
|
||||
if action in ('deploy', 'rollback'):
|
||||
preflight(c, mode, args.get('size', 0))
|
||||
event('上传内容校验通过', 40)
|
||||
transaction(c, mode, stage, args.get('backup') if action == 'rollback' else None)
|
||||
finally:
|
||||
try:
|
||||
remove(stage)
|
||||
except OSError as exc:
|
||||
event('临时文件清理失败:' + str(exc))
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
try:
|
||||
main()
|
||||
except Exception as error:
|
||||
event(str(error), result='failed')
|
||||
sys.exit(1)
|
||||
71
autodeploy/store.py
Normal file
@@ -0,0 +1,71 @@
|
||||
import json
|
||||
import os
|
||||
import sqlite3
|
||||
from contextlib import contextmanager
|
||||
from pathlib import Path
|
||||
from datetime import datetime
|
||||
|
||||
|
||||
def data_dir():
|
||||
root = Path(os.environ.get('AUTODEPLOY_DATA', str(Path(os.environ.get('LOCALAPPDATA', str(Path.home()))) / 'AutoDeploy')))
|
||||
root.mkdir(parents=True, exist_ok=True)
|
||||
return root
|
||||
|
||||
|
||||
DEFAULTS = dict(name='新服务器', host='', port=22, username='root', password='',
|
||||
front='/home/dist', war='/usr/local/tomcat/webapps/ROOT.war',
|
||||
tomcat='/usr/local/tomcat', startup='/usr/local/tomcat/bin/startup.sh',
|
||||
shutdown='/usr/local/tomcat/bin/shutdown.sh', temp='/home/deploy/tmp',
|
||||
backups='/home/deploy/backups', health='', stop_timeout=30,
|
||||
start_timeout=120, java_home='', service='', owner='', auto_rollback=True,
|
||||
nginx_service='nginx.service', nginx_binary='/usr/sbin/nginx',
|
||||
nginx_cert_dir='/home/ssl', nginx_cert_name='', nginx_key_name='',
|
||||
local_war='', local_front='', local_cert='', local_key='')
|
||||
|
||||
|
||||
class Store:
|
||||
def __init__(self, path=None):
|
||||
self.path = path or data_dir() / 'config.db'
|
||||
with self.connect() as db:
|
||||
db.executescript('''
|
||||
CREATE TABLE IF NOT EXISTS profiles(id INTEGER PRIMARY KEY, config TEXT NOT NULL);
|
||||
CREATE TABLE IF NOT EXISTS runs(id INTEGER PRIMARY KEY, profile_id INTEGER,
|
||||
created TEXT, action TEXT, status TEXT, log TEXT, backup TEXT, config TEXT);
|
||||
''')
|
||||
|
||||
@contextmanager
|
||||
def connect(self):
|
||||
db = sqlite3.connect(self.path)
|
||||
db.row_factory = sqlite3.Row
|
||||
try:
|
||||
with db:
|
||||
yield db
|
||||
finally:
|
||||
db.close()
|
||||
|
||||
def profiles(self):
|
||||
with self.connect() as db:
|
||||
return [(r['id'], {**DEFAULTS, **json.loads(r['config'])}) for r in db.execute('SELECT * FROM profiles ORDER BY id')]
|
||||
|
||||
def save(self, pid, config):
|
||||
with self.connect() as db:
|
||||
raw = json.dumps(config, ensure_ascii=False)
|
||||
if pid:
|
||||
db.execute('UPDATE profiles SET config=? WHERE id=?', (raw, pid))
|
||||
return pid
|
||||
return db.execute('INSERT INTO profiles(config) VALUES(?)', (raw,)).lastrowid
|
||||
|
||||
def delete(self, pid):
|
||||
with self.connect() as db:
|
||||
db.execute('DELETE FROM profiles WHERE id=?', (pid,))
|
||||
|
||||
def record(self, pid, action, status, log, backup, config):
|
||||
safe = {k: v for k, v in config.items() if k != 'password'}
|
||||
with self.connect() as db:
|
||||
db.execute('INSERT INTO runs(profile_id,created,action,status,log,backup,config) VALUES(?,?,?,?,?,?,?)',
|
||||
(pid, datetime.now().strftime('%Y-%m-%d %H:%M:%S'), action, status, log, backup,
|
||||
json.dumps(safe, ensure_ascii=False)))
|
||||
|
||||
def history(self, pid):
|
||||
with self.connect() as db:
|
||||
return [dict(r) for r in db.execute('SELECT * FROM runs WHERE profile_id=? ORDER BY id DESC LIMIT 100', (pid,))]
|
||||
747
autodeploy/ui.py
Normal file
@@ -0,0 +1,747 @@
|
||||
import json
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
from PySide6.QtCore import Qt, QTimer
|
||||
from PySide6.QtGui import QColor, QFont, QIcon, QPainter, QPixmap
|
||||
from PySide6.QtWidgets import (QApplication, QCheckBox, QComboBox, QDialog, QDialogButtonBox,
|
||||
QFileDialog, QFormLayout, QFrame, QGridLayout, QHBoxLayout, QLabel, QLineEdit,
|
||||
QListWidget, QListWidgetItem, QMainWindow, QMessageBox, QPlainTextEdit,
|
||||
QPushButton, QScrollArea, QSpinBox, QSplitter, QTabWidget, QVBoxLayout, QWidget,
|
||||
QProgressBar, QTableWidget, QTableWidgetItem, QHeaderView)
|
||||
|
||||
from .store import Store, DEFAULTS, data_dir
|
||||
from .engine import Worker
|
||||
|
||||
|
||||
STYLE = '''
|
||||
QWidget { background: #0c111b; color: #e2e8f0; font-family: "Microsoft YaHei UI"; font-size: 12px; }
|
||||
QMainWindow { background: #0c111b; }
|
||||
QFrame#sidebar { background: #101723; border-right: 1px solid #253044; }
|
||||
QFrame#card { background: #141d2b; border: 1px solid #273448; border-radius: 12px; }
|
||||
QFrame#card QLabel, QFrame#card QWidget#transparent { background: transparent; }
|
||||
QLabel#muted { color: #8191aa; background: transparent; }
|
||||
QLabel#title { font-size: 27px; font-weight: 700; background: transparent; }
|
||||
QLabel#section { font-size: 16px; font-weight: 600; background: transparent; }
|
||||
QLabel#badge { color: #7ce6ca; background: #18352f; border-radius: 8px; padding: 6px 12px; }
|
||||
QPushButton { background: #1b2739; border: 1px solid #34445d; padding: 9px 16px; border-radius: 7px; font-weight: 600; }
|
||||
QPushButton:hover { background: #263950; border-color: #637c9c; }
|
||||
QPushButton:pressed { background: #334966; }
|
||||
QPushButton#primary { background: #73e0c2; color: #102722; border: none; }
|
||||
QPushButton#primary:hover { background: #9cf0d8; }
|
||||
QPushButton:disabled { background: #1b2431; color: #566479; border-color: #253044; }
|
||||
QPushButton#primary:disabled { background: #24453e; color: #628d81; }
|
||||
QPushButton#danger { color: #f6a2a6; }
|
||||
QLineEdit, QSpinBox, QComboBox { background: #0e1623; border: 1px solid #2d3c52; border-radius: 6px; padding: 9px; selection-background-color: #277c6a; }
|
||||
QLineEdit:focus, QSpinBox:focus, QComboBox:focus { border: 1px solid #73e0c2; }
|
||||
QComboBox QAbstractItemView { background: #172235; selection-background-color: #29483f; }
|
||||
QListWidget { background: transparent; border: none; outline: none; }
|
||||
QListWidget::item { padding: 15px 12px; margin: 4px 0; border-radius: 9px; color: #a3b2c8; }
|
||||
QListWidget::item:selected { background: #213d39; color: #9ef2d9; border: 1px solid #3c6c5e; }
|
||||
QListWidget::item:hover { background: #1c2939; }
|
||||
QTabWidget::pane { border: none; padding-top: 12px; }
|
||||
QTabBar::tab { color: #899bb4; padding: 12px 20px; background: transparent; border-bottom: 2px solid transparent; }
|
||||
QTabBar::tab:selected { color: #87e6ce; border-bottom: 2px solid #73e0c2; }
|
||||
QPlainTextEdit { background: #0a1019; color: #a9bdd4; border: 1px solid #243248; border-radius: 8px; padding: 10px; font-family: Consolas, "Microsoft YaHei UI"; font-size: 12px; }
|
||||
QProgressBar { background: #253146; border: none; height: 6px; border-radius: 3px; color: transparent; }
|
||||
QProgressBar::chunk { background: #73e0c2; border-radius: 3px; }
|
||||
QTableWidget { background: #101925; border: 1px solid #29374c; gridline-color: #253044; selection-background-color: #244b40; }
|
||||
QHeaderView::section { background: #1a2638; color: #9bacc2; padding: 10px; border: none; }
|
||||
QScrollArea { border: none; }
|
||||
QScrollBar:vertical { background: #111a28; width: 8px; }
|
||||
QScrollBar::handle:vertical { background: #34435a; border-radius: 4px; min-height: 25px; }
|
||||
QScrollBar::add-line:vertical, QScrollBar::sub-line:vertical { height: 0; }
|
||||
QCheckBox { spacing: 8px; }
|
||||
QToolTip { background: #25334a; color: #edf4fb; border: 1px solid #4c637f; }
|
||||
'''
|
||||
|
||||
|
||||
def label(text, name=None):
|
||||
w = QLabel(text)
|
||||
if name:
|
||||
w.setObjectName(name)
|
||||
return w
|
||||
|
||||
|
||||
def button(text, callback, primary=False):
|
||||
b = QPushButton(text)
|
||||
b.setCursor(Qt.PointingHandCursor)
|
||||
if primary:
|
||||
b.setObjectName('primary')
|
||||
b.clicked.connect(callback)
|
||||
return b
|
||||
|
||||
|
||||
def card():
|
||||
frame = QFrame()
|
||||
frame.setObjectName('card')
|
||||
layout = QVBoxLayout(frame)
|
||||
layout.setContentsMargins(22, 20, 22, 20)
|
||||
layout.setSpacing(14)
|
||||
return frame, layout
|
||||
|
||||
|
||||
class ProfileDialog(QDialog):
|
||||
def __init__(self, config, parent=None):
|
||||
super().__init__(parent)
|
||||
self.setWindowTitle('服务器与部署配置')
|
||||
self.resize(730, 720)
|
||||
self.config = dict(config)
|
||||
self.fields = {}
|
||||
layout = QVBoxLayout(self)
|
||||
layout.addWidget(label('服务器与部署配置', 'section'))
|
||||
layout.addWidget(label('每个配置独立保存账号与部署路径,可为同一服务器创建多个项目。', 'muted'))
|
||||
tabs = QTabWidget()
|
||||
layout.addWidget(tabs)
|
||||
groups = [
|
||||
('SSH 连接', [('name','配置名称'), ('host','服务器 IP / 域名'), ('port','SSH 端口'),
|
||||
('username','登录账号'), ('password','登录密码')]),
|
||||
('部署路径', [('front','前端目标目录'), ('war','后端目标文件'), ('tomcat','Tomcat 实例目录'),
|
||||
('startup','启动脚本'), ('shutdown','停止脚本'), ('temp','临时上传目录'), ('backups','备份目录')]),
|
||||
('运行设置', [('service','systemd 服务名(可选)'), ('java_home','JAVA_HOME(可选)'),
|
||||
('owner','文件属主 user:group(可选)'), ('health','HTTP 健康检查地址(可选)'),
|
||||
('stop_timeout','停止超时(秒)'), ('start_timeout','启动超时(秒)')]),
|
||||
('Nginx 设置', [('nginx_service','systemd 服务名'), ('nginx_binary','Nginx 可执行文件'),
|
||||
('nginx_cert_dir','证书目录'), ('nginx_cert_name','服务器证书文件名'),
|
||||
('nginx_key_name','服务器私钥文件名')])]
|
||||
for title, fields in groups:
|
||||
page = QWidget()
|
||||
form = QFormLayout(page)
|
||||
form.setContentsMargins(18, 24, 18, 20)
|
||||
form.setVerticalSpacing(20)
|
||||
form.setFieldGrowthPolicy(QFormLayout.AllNonFixedFieldsGrow)
|
||||
for key, caption in fields:
|
||||
if key in ('port', 'stop_timeout', 'start_timeout'):
|
||||
field = QSpinBox()
|
||||
field.setRange(1, 65535 if key == 'port' else 3600)
|
||||
field.setValue(int(config[key]))
|
||||
else:
|
||||
field = QLineEdit(str(config[key]))
|
||||
if key == 'password':
|
||||
field.setEchoMode(QLineEdit.Password)
|
||||
if key in ('service', 'java_home', 'owner', 'health'):
|
||||
field.setPlaceholderText('留空使用默认行为')
|
||||
elif key == 'nginx_cert_name':
|
||||
field.setPlaceholderText('例如 fullchain.pem')
|
||||
elif key == 'nginx_key_name':
|
||||
field.setPlaceholderText('例如 private.key')
|
||||
self.fields[key] = field
|
||||
form.addRow(caption, field)
|
||||
if title == 'SSH 连接':
|
||||
self.show_password = QCheckBox('显示密码')
|
||||
self.show_password.toggled.connect(lambda show: self.fields['password'].setEchoMode(QLineEdit.Normal if show else QLineEdit.Password))
|
||||
form.addRow('', self.show_password)
|
||||
note = label('账号密码直接保存在本机配置数据库中。', 'muted')
|
||||
form.addRow('', note)
|
||||
if title == '部署路径':
|
||||
form.addRow('', label('前端目录应直接包含 index.html。备份保留最近 2 次。', 'muted'))
|
||||
if title == '运行设置':
|
||||
self.auto = QCheckBox('部署失败时自动恢复部署前版本')
|
||||
self.auto.setChecked(config.get('auto_rollback', True))
|
||||
form.addRow('', self.auto)
|
||||
note = label('配置 systemd 服务名后,通过 systemctl 停启。\n健康检查从服务器发起,留空仅检查 Tomcat 进程。', 'muted')
|
||||
note.setWordWrap(True)
|
||||
form.addRow('', note)
|
||||
if title == 'Nginx 设置':
|
||||
note = label('证书默认上传到 /home/ssl。证书和私钥文件名必须与现有 Nginx 配置一致。\n只支持由 systemd 管理的 Nginx,不自动调用 sudo。', 'muted')
|
||||
note.setWordWrap(True)
|
||||
form.addRow('', note)
|
||||
tabs.addTab(page, title)
|
||||
row = QHBoxLayout()
|
||||
row.addStretch()
|
||||
row.addWidget(button('取消', self.reject))
|
||||
row.addWidget(button('保存配置', self.save, True))
|
||||
layout.addLayout(row)
|
||||
|
||||
def save(self):
|
||||
for key, field in self.fields.items():
|
||||
self.config[key] = field.value() if isinstance(field, QSpinBox) else (field.text() if key == 'password' else field.text().strip())
|
||||
self.config['auto_rollback'] = self.auto.isChecked()
|
||||
if not all(self.config[k] for k in ('name', 'host', 'username')):
|
||||
QMessageBox.warning(self, '信息未填写完整', '请填写配置名称、服务器地址和登录账号。')
|
||||
return
|
||||
try:
|
||||
# POSIX paths must be checked as POSIX even on Windows.
|
||||
from .engine import validate_config
|
||||
validate_config(self.config)
|
||||
except Exception as exc:
|
||||
QMessageBox.warning(self, '配置需要修改', str(exc))
|
||||
return
|
||||
self.accept()
|
||||
|
||||
|
||||
class MainWindow(QMainWindow):
|
||||
def __init__(self):
|
||||
super().__init__()
|
||||
self.store = Store()
|
||||
self.pid = None
|
||||
self.config = dict(DEFAULTS)
|
||||
self.worker = None
|
||||
self.setWindowTitle('AutoDeploy · 自动部署工作台')
|
||||
screen = QApplication.primaryScreen().availableGeometry()
|
||||
self.resize(min(1280, screen.width() - 50), min(920, screen.height() - 60))
|
||||
self.setMinimumSize(940, 620)
|
||||
root = QWidget()
|
||||
self.setCentralWidget(root)
|
||||
outer = QHBoxLayout(root)
|
||||
outer.setContentsMargins(0, 0, 0, 0)
|
||||
outer.setSpacing(0)
|
||||
side = QFrame()
|
||||
side.setObjectName('sidebar')
|
||||
side.setFixedWidth(248)
|
||||
sl = QVBoxLayout(side)
|
||||
sl.setContentsMargins(20, 28, 20, 24)
|
||||
sl.setSpacing(16)
|
||||
logo = label('◈ AutoDeploy')
|
||||
logo.setStyleSheet('font-size: 23px; font-weight: 700; color: #90eed3; background: transparent;')
|
||||
sl.addWidget(logo)
|
||||
sl.addWidget(label('让每一次发布,都井然有序。', 'muted'))
|
||||
sl.addSpacing(28)
|
||||
heading = QHBoxLayout()
|
||||
heading.addWidget(label('服务器 / 项目', 'muted'))
|
||||
heading.addStretch()
|
||||
self.count = label('0', 'muted')
|
||||
heading.addWidget(self.count)
|
||||
sl.addLayout(heading)
|
||||
self.servers = QListWidget()
|
||||
self.servers.currentItemChanged.connect(self.select_profile)
|
||||
sl.addWidget(self.servers, 1)
|
||||
self.add_btn = button('+ 添加服务器', self.add_profile)
|
||||
sl.addWidget(self.add_btn)
|
||||
foot = label('SSH / SFTP\n本地配置 · 最近 2 次备份', 'muted')
|
||||
foot.setStyleSheet('color: #71839d; background: transparent; line-height: 1.5;')
|
||||
sl.addSpacing(16)
|
||||
sl.addWidget(foot)
|
||||
outer.addWidget(side)
|
||||
content = QWidget()
|
||||
main = QVBoxLayout(content)
|
||||
main.setContentsMargins(30, 26, 30, 24)
|
||||
main.setSpacing(18)
|
||||
outer.addWidget(content, 1)
|
||||
header = QHBoxLayout()
|
||||
titles = QVBoxLayout()
|
||||
titles.addWidget(label('部署工作台', 'title'))
|
||||
titles.addWidget(label('从本地构建到云端上线,一处完成。', 'muted'))
|
||||
header.addLayout(titles)
|
||||
header.addStretch()
|
||||
self.badge = label('等待连接', 'badge')
|
||||
self.badge.setFixedHeight(34)
|
||||
header.addWidget(self.badge)
|
||||
main.addLayout(header)
|
||||
|
||||
self.server_card, sc = card()
|
||||
line = QHBoxLayout()
|
||||
box = QVBoxLayout()
|
||||
self.server_title = label('添加你的第一台服务器', 'section')
|
||||
self.server_info = label('配置 SSH 连接,即可开始部署', 'muted')
|
||||
box.addWidget(self.server_title)
|
||||
box.addWidget(self.server_info)
|
||||
line.addLayout(box, 1)
|
||||
self.edit_btn = button('编辑配置', self.edit_profile)
|
||||
self.test_btn = button('测试连接', lambda: self.launch('test'))
|
||||
line.addWidget(self.edit_btn)
|
||||
line.addWidget(self.test_btn)
|
||||
sc.addLayout(line)
|
||||
self.dest = label('前端 /home/dist 后端 /usr/local/tomcat/webapps/ROOT.war', 'muted')
|
||||
self.dest.setWordWrap(True)
|
||||
self.dest.setTextInteractionFlags(Qt.TextSelectableByMouse)
|
||||
sc.addWidget(self.dest)
|
||||
main.addWidget(self.server_card)
|
||||
|
||||
self.tabs = QTabWidget()
|
||||
main.addWidget(self.tabs, 1)
|
||||
deploy_page = QWidget()
|
||||
deploy = QVBoxLayout(deploy_page)
|
||||
deploy.setContentsMargins(0, 0, 0, 0)
|
||||
deploy.setSpacing(16)
|
||||
scroll = QScrollArea()
|
||||
scroll.setWidgetResizable(True)
|
||||
deploy_page.setMinimumHeight(660)
|
||||
scroll.setWidget(deploy_page)
|
||||
deploy_container = QWidget()
|
||||
deploy_outer = QVBoxLayout(deploy_container)
|
||||
deploy_outer.setContentsMargins(0, 0, 0, 0)
|
||||
deploy_outer.setSpacing(14)
|
||||
deploy_outer.addWidget(scroll, 1)
|
||||
self.tabs.addTab(deploy_container, '发布部署')
|
||||
artifact_card, ac = card()
|
||||
top = QHBoxLayout()
|
||||
top.addWidget(label('部署文件', 'section'))
|
||||
top.addStretch()
|
||||
top.addWidget(label('发布范围', 'muted'))
|
||||
self.mode = QComboBox()
|
||||
self.mode.addItem('前端 + 后端', 'all')
|
||||
self.mode.addItem('仅前端 dist', 'frontend')
|
||||
self.mode.addItem('仅后端 WAR', 'backend')
|
||||
self.mode.currentIndexChanged.connect(self.mode_changed)
|
||||
top.addWidget(self.mode)
|
||||
ac.addLayout(top)
|
||||
grid = QGridLayout()
|
||||
grid.setVerticalSpacing(12)
|
||||
self.war = QLineEdit()
|
||||
self.war.setPlaceholderText('选择本地 ROOT.war 文件')
|
||||
self.front = QLineEdit()
|
||||
self.front.setPlaceholderText('选择 dist 文件夹或 ZIP 压缩包')
|
||||
self.war_btn = button('选择 WAR', self.pick_war)
|
||||
self.front_btn = button('选择目录', self.pick_front)
|
||||
self.zip_btn = button('选择 ZIP', self.pick_zip)
|
||||
grid.addWidget(label('后端 WAR', 'muted'), 0, 0)
|
||||
grid.addWidget(self.war, 0, 1)
|
||||
grid.addWidget(self.war_btn, 0, 2, 1, 2)
|
||||
grid.addWidget(label('前端 DIST', 'muted'), 1, 0)
|
||||
grid.addWidget(self.front, 1, 1)
|
||||
grid.addWidget(self.front_btn, 1, 2)
|
||||
grid.addWidget(self.zip_btn, 1, 3)
|
||||
ac.addLayout(grid)
|
||||
self.mode_note = label('完整发布:上传 → 停服备份 → 替换文件 → 启动验证', 'muted')
|
||||
ac.addWidget(self.mode_note)
|
||||
deploy.addWidget(artifact_card)
|
||||
progress_card, pc = card()
|
||||
row = QHBoxLayout()
|
||||
self.phase = label('准备就绪', 'section')
|
||||
row.addWidget(self.phase)
|
||||
row.addStretch()
|
||||
self.percent = label('0%', 'muted')
|
||||
row.addWidget(self.percent)
|
||||
pc.addLayout(row)
|
||||
self.progress = QProgressBar()
|
||||
self.progress.setTextVisible(False)
|
||||
self.progress.setValue(0)
|
||||
self.progress.setFixedHeight(6)
|
||||
pc.addWidget(self.progress)
|
||||
self.steps = label('01 连接检查 / 02 上传文件 / 03 备份替换 / 04 启动验证', 'muted')
|
||||
pc.addWidget(self.steps)
|
||||
deploy.addWidget(progress_card)
|
||||
log_header = QHBoxLayout()
|
||||
log_header.addWidget(label('运行日志', 'section'))
|
||||
log_header.addStretch()
|
||||
log_header.addWidget(button('导出日志', self.export_log))
|
||||
deploy.addLayout(log_header)
|
||||
self.log = QPlainTextEdit()
|
||||
self.log.setReadOnly(True)
|
||||
self.log.setPlaceholderText('部署步骤与服务器输出将在这里实时显示。')
|
||||
self.log.setMinimumHeight(100)
|
||||
deploy.addWidget(self.log, 1)
|
||||
bottom = QHBoxLayout()
|
||||
self.status = label('准备好文件,选择目标服务器后开始。', 'muted')
|
||||
self.status.setWordWrap(True)
|
||||
bottom.addWidget(self.status, 1)
|
||||
self.deploy_btn = button('开始部署 →', lambda: self.launch('deploy'), True)
|
||||
self.deploy_btn.setMinimumWidth(164)
|
||||
bottom.addWidget(self.deploy_btn)
|
||||
deploy_outer.addLayout(bottom)
|
||||
self.build_nginx()
|
||||
self.build_history()
|
||||
self.refresh_profiles()
|
||||
|
||||
def build_nginx(self):
|
||||
page = QWidget()
|
||||
layout = QVBoxLayout(page)
|
||||
layout.setContentsMargins(0, 0, 0, 0)
|
||||
layout.setSpacing(16)
|
||||
page.setMinimumHeight(680)
|
||||
scroll = QScrollArea()
|
||||
scroll.setWidgetResizable(True)
|
||||
scroll.setWidget(page)
|
||||
container = QWidget()
|
||||
outer = QVBoxLayout(container)
|
||||
outer.setContentsMargins(0, 0, 0, 0)
|
||||
outer.addWidget(scroll)
|
||||
self.nginx_tab_index = self.tabs.addTab(container, 'Nginx 管理')
|
||||
|
||||
nginx_card, nc = card()
|
||||
nginx_card.setMinimumHeight(285)
|
||||
nginx_top = QHBoxLayout()
|
||||
title_box = QVBoxLayout()
|
||||
title_box.addWidget(label('Nginx 与 HTTPS 证书', 'section'))
|
||||
self.nginx_server_info = label('选择服务器后即可管理 Nginx', 'muted')
|
||||
title_box.addWidget(self.nginx_server_info)
|
||||
nginx_top.addLayout(title_box, 1)
|
||||
self.nginx_dest = label('远端目录 /home/ssl', 'muted')
|
||||
self.nginx_dest.setTextInteractionFlags(Qt.TextSelectableByMouse)
|
||||
nginx_top.addWidget(self.nginx_dest)
|
||||
nc.addLayout(nginx_top)
|
||||
|
||||
nginx_grid = QGridLayout()
|
||||
nginx_grid.setVerticalSpacing(12)
|
||||
self.cert = QLineEdit()
|
||||
self.cert.setPlaceholderText('选择本地 PEM / CRT 证书文件')
|
||||
self.key = QLineEdit()
|
||||
self.key.setPlaceholderText('选择本地 KEY / PEM 私钥文件')
|
||||
self.cert_file_btn = button('选择证书', self.pick_cert)
|
||||
self.key_file_btn = button('选择私钥', self.pick_key)
|
||||
for field in (self.cert, self.key):
|
||||
field.setMinimumHeight(42)
|
||||
for pick in (self.cert_file_btn, self.key_file_btn):
|
||||
pick.setMinimumSize(118, 42)
|
||||
nginx_grid.setColumnStretch(1, 1)
|
||||
nginx_grid.setColumnMinimumWidth(2, 118)
|
||||
nginx_grid.addWidget(label('证书文件', 'muted'), 0, 0)
|
||||
nginx_grid.addWidget(self.cert, 0, 1)
|
||||
nginx_grid.addWidget(self.cert_file_btn, 0, 2)
|
||||
nginx_grid.addWidget(label('私钥文件', 'muted'), 1, 0)
|
||||
nginx_grid.addWidget(self.key, 1, 1)
|
||||
nginx_grid.addWidget(self.key_file_btn, 1, 2)
|
||||
nc.addLayout(nginx_grid)
|
||||
|
||||
nginx_actions = QHBoxLayout()
|
||||
nginx_actions.addWidget(label('先检查 nginx -t;证书更新失败会自动恢复旧文件。', 'muted'), 1)
|
||||
self.nginx_restart_btn = button('仅重启 Nginx', self.confirm_nginx_restart)
|
||||
self.cert_deploy_btn = button('上传证书并重启', self.confirm_cert_deploy, True)
|
||||
self.nginx_restart_btn.setMinimumSize(145, 44)
|
||||
self.cert_deploy_btn.setMinimumSize(160, 44)
|
||||
nginx_actions.addWidget(self.nginx_restart_btn)
|
||||
nginx_actions.addWidget(self.cert_deploy_btn)
|
||||
nc.addLayout(nginx_actions)
|
||||
layout.addWidget(nginx_card)
|
||||
|
||||
progress_card, pc = card()
|
||||
row = QHBoxLayout()
|
||||
self.nginx_phase = label('准备就绪', 'section')
|
||||
row.addWidget(self.nginx_phase)
|
||||
row.addStretch()
|
||||
self.nginx_percent = label('0%', 'muted')
|
||||
row.addWidget(self.nginx_percent)
|
||||
pc.addLayout(row)
|
||||
self.nginx_progress = QProgressBar()
|
||||
self.nginx_progress.setTextVisible(False)
|
||||
self.nginx_progress.setValue(0)
|
||||
self.nginx_progress.setFixedHeight(6)
|
||||
pc.addWidget(self.nginx_progress)
|
||||
self.nginx_steps = label('01 连接检查 / 02 校验证书 / 03 原子替换 / 04 重启验证', 'muted')
|
||||
pc.addWidget(self.nginx_steps)
|
||||
layout.addWidget(progress_card)
|
||||
|
||||
log_header = QHBoxLayout()
|
||||
log_header.addWidget(label('Nginx 运行日志', 'section'))
|
||||
log_header.addStretch()
|
||||
log_header.addWidget(button('导出日志', self.export_log))
|
||||
layout.addLayout(log_header)
|
||||
self.nginx_log = QPlainTextEdit()
|
||||
self.nginx_log.setReadOnly(True)
|
||||
self.nginx_log.setPlaceholderText('证书校验、备份、Nginx 配置检查及重启结果将在这里显示。')
|
||||
self.nginx_log.setMinimumHeight(140)
|
||||
layout.addWidget(self.nginx_log, 1)
|
||||
self.nginx_status = label('选择目标服务器,可上传证书并重启或单独重启 Nginx。', 'muted')
|
||||
self.nginx_status.setWordWrap(True)
|
||||
layout.addWidget(self.nginx_status)
|
||||
|
||||
def build_history(self):
|
||||
page = QWidget()
|
||||
layout = QVBoxLayout(page)
|
||||
layout.setContentsMargins(0, 0, 0, 0)
|
||||
layout.addWidget(label('发布记录与版本恢复', 'section'))
|
||||
layout.addWidget(label('选择一条发布记录,恢复该次发布前的文件。服务器仅保留最近 2 次备份。', 'muted'))
|
||||
self.history = QTableWidget(0, 4)
|
||||
self.history.setHorizontalHeaderLabels(['时间', '操作', '结果', '备份'])
|
||||
self.history.horizontalHeader().setSectionResizeMode(QHeaderView.Stretch)
|
||||
self.history.setSelectionBehavior(QTableWidget.SelectRows)
|
||||
self.history.setSelectionMode(QTableWidget.SingleSelection)
|
||||
self.history.setEditTriggers(QTableWidget.NoEditTriggers)
|
||||
self.history.verticalHeader().hide()
|
||||
self.history.itemSelectionChanged.connect(self.history_selected)
|
||||
layout.addWidget(self.history, 1)
|
||||
self.history_log = QPlainTextEdit()
|
||||
self.history_log.setReadOnly(True)
|
||||
layout.addWidget(self.history_log, 1)
|
||||
row = QHBoxLayout()
|
||||
self.delete_btn = button('删除当前配置', self.delete_profile)
|
||||
self.delete_btn.setObjectName('danger')
|
||||
row.addWidget(self.delete_btn)
|
||||
row.addStretch()
|
||||
self.rollback_btn = button('恢复此备份', self.rollback)
|
||||
row.addWidget(self.rollback_btn)
|
||||
layout.addLayout(row)
|
||||
self.tabs.addTab(page, '历史与回滚')
|
||||
|
||||
def refresh_profiles(self, selected=None):
|
||||
self.servers.blockSignals(True)
|
||||
self.servers.clear()
|
||||
profiles = self.store.profiles()
|
||||
chosen = None
|
||||
for pid, cfg in profiles:
|
||||
item = QListWidgetItem('● ' + cfg['name'] + '\n ' + cfg['host'])
|
||||
item.setData(Qt.UserRole, (pid, cfg))
|
||||
self.servers.addItem(item)
|
||||
if pid == selected:
|
||||
chosen = item
|
||||
self.count.setText(str(len(profiles)))
|
||||
self.servers.blockSignals(False)
|
||||
if profiles:
|
||||
self.servers.setCurrentItem(chosen or self.servers.item(0))
|
||||
else:
|
||||
self.pid = None
|
||||
self.config = dict(DEFAULTS)
|
||||
self.server_title.setText('添加你的第一台服务器')
|
||||
self.server_info.setText('配置 SSH 连接,即可开始部署')
|
||||
self.dest.setText('支持 ROOT.war + dist · 路径自由配置')
|
||||
self.war.clear()
|
||||
self.front.clear()
|
||||
self.cert.clear()
|
||||
self.key.clear()
|
||||
self.nginx_server_info.setText('选择服务器后即可管理 Nginx')
|
||||
self.nginx_dest.setText('远端目录 /home/ssl')
|
||||
self.refresh_history()
|
||||
self.busy(False)
|
||||
|
||||
def select_profile(self, current, previous):
|
||||
if not current:
|
||||
return
|
||||
if self.pid:
|
||||
self.persist_files()
|
||||
self.pid, self.config = current.data(Qt.UserRole)
|
||||
# Reload to include recently persisted local paths.
|
||||
self.config = dict(next(c for p, c in self.store.profiles() if p == self.pid))
|
||||
self.server_title.setText(self.config['name'])
|
||||
self.server_info.setText('{}@{} · SSH {}'.format(self.config['username'], self.config['host'], self.config['port']))
|
||||
self.dest.setText('前端 {}\n后端 {}'.format(self.config['front'], self.config['war']))
|
||||
self.war.setText(self.config['local_war'])
|
||||
self.front.setText(self.config['local_front'])
|
||||
self.cert.setText(self.config['local_cert'])
|
||||
self.key.setText(self.config['local_key'])
|
||||
self.nginx_dest.setText('远端目录 ' + self.config.get('nginx_cert_dir', '/home/ssl'))
|
||||
self.nginx_server_info.setText('{}@{} · {}'.format(
|
||||
self.config['username'], self.config['host'], self.config.get('nginx_service', 'nginx.service')))
|
||||
self.badge.setText('尚未连接')
|
||||
self.refresh_history()
|
||||
|
||||
def persist_files(self):
|
||||
if self.pid:
|
||||
self.config.update(local_war=self.war.text().strip(), local_front=self.front.text().strip(),
|
||||
local_cert=self.cert.text().strip(), local_key=self.key.text().strip())
|
||||
self.store.save(self.pid, self.config)
|
||||
|
||||
def add_profile(self):
|
||||
self.persist_files()
|
||||
d = ProfileDialog(DEFAULTS, self)
|
||||
if d.exec():
|
||||
pid = self.store.save(None, d.config)
|
||||
self.refresh_profiles(pid)
|
||||
|
||||
def edit_profile(self):
|
||||
self.persist_files()
|
||||
d = ProfileDialog(self.config, self)
|
||||
if d.exec():
|
||||
self.config = d.config
|
||||
self.store.save(self.pid, self.config)
|
||||
self.refresh_profiles(self.pid)
|
||||
|
||||
def delete_profile(self):
|
||||
if QMessageBox.question(self, '删除配置', '删除“{}”的本地配置?服务器上的文件不受影响。'.format(self.config['name'])) == QMessageBox.Yes:
|
||||
self.store.delete(self.pid)
|
||||
self.pid = None
|
||||
self.refresh_profiles()
|
||||
|
||||
def pick_war(self):
|
||||
path, _ = QFileDialog.getOpenFileName(self, '选择后端 WAR', '', 'WAR 文件 (*.war)')
|
||||
if path:
|
||||
self.war.setText(path)
|
||||
|
||||
def pick_front(self):
|
||||
path = QFileDialog.getExistingDirectory(self, '选择 dist 文件夹')
|
||||
if path:
|
||||
self.front.setText(path)
|
||||
|
||||
def pick_zip(self):
|
||||
path, _ = QFileDialog.getOpenFileName(self, '选择前端 ZIP', '', 'ZIP 文件 (*.zip)')
|
||||
if path:
|
||||
self.front.setText(path)
|
||||
|
||||
def pick_cert(self):
|
||||
path, _ = QFileDialog.getOpenFileName(self, '选择 HTTPS 证书', '', '证书文件 (*.pem *.crt *.cer);;所有文件 (*)')
|
||||
if path:
|
||||
self.cert.setText(path)
|
||||
|
||||
def pick_key(self):
|
||||
path, _ = QFileDialog.getOpenFileName(self, '选择 HTTPS 私钥', '', '私钥文件 (*.key *.pem);;所有文件 (*)')
|
||||
if path:
|
||||
self.key.setText(path)
|
||||
|
||||
def confirm_cert_deploy(self):
|
||||
cert = self.config.get('nginx_cert_name', '')
|
||||
key = self.config.get('nginx_key_name', '')
|
||||
if not cert or not key:
|
||||
QMessageBox.warning(self, '请配置服务器文件名', '请在“编辑配置 → Nginx 设置”中填写服务器证书和私钥文件名。')
|
||||
return
|
||||
target = '{}/{}\n{}/{}'.format(self.config.get('nginx_cert_dir', '/home/ssl'), cert,
|
||||
self.config.get('nginx_cert_dir', '/home/ssl'), key)
|
||||
if QMessageBox.question(self, '更新 HTTPS 证书',
|
||||
'将替换服务器上的证书和私钥,然后重启 Nginx:\n{}\n\n是否继续?'.format(target)) == QMessageBox.Yes:
|
||||
self.launch('cert_deploy')
|
||||
|
||||
def confirm_nginx_restart(self):
|
||||
if QMessageBox.question(self, '重启 Nginx',
|
||||
'将在 {} 上检查配置并重启 Nginx,是否继续?'.format(self.config.get('host', ''))) == QMessageBox.Yes:
|
||||
self.launch('nginx_restart')
|
||||
|
||||
def mode_changed(self):
|
||||
mode = self.mode.currentData()
|
||||
for w in (self.war, self.war_btn):
|
||||
w.setEnabled(mode != 'frontend')
|
||||
for w in (self.front, self.front_btn, self.zip_btn):
|
||||
w.setEnabled(mode != 'backend')
|
||||
if hasattr(self, 'mode_note'):
|
||||
self.mode_note.setText({'all':'完整发布:上传 → 停服备份 → 替换文件 → 启动验证',
|
||||
'frontend':'仅替换 dist 文件夹,Tomcat 保持运行,Nginx 无需调整。',
|
||||
'backend':'仅更新 ROOT.war,停止指定 Tomcat 后替换并重新启动。'}[mode])
|
||||
|
||||
def busy(self, running):
|
||||
for w in (self.servers, self.add_btn, self.mode, self.war, self.front, self.war_btn, self.front_btn,
|
||||
self.zip_btn, self.cert, self.key, self.cert_file_btn, self.key_file_btn):
|
||||
w.setEnabled(not running)
|
||||
for w in (self.edit_btn, self.test_btn, self.deploy_btn, self.delete_btn,
|
||||
self.nginx_restart_btn, self.cert_deploy_btn):
|
||||
w.setEnabled(not running and self.pid is not None)
|
||||
self.rollback_btn.setEnabled(not running and self.history.currentRow() >= 0)
|
||||
if not running:
|
||||
self.mode_changed()
|
||||
|
||||
def launch(self, action, backup='', override=None, mode=None):
|
||||
if not self.pid or (self.worker and self.worker.isRunning()):
|
||||
return
|
||||
self.persist_files()
|
||||
config = dict(override or self.config)
|
||||
actual_mode = mode or self.mode.currentData()
|
||||
if action == 'deploy':
|
||||
if actual_mode != 'frontend' and not Path(config['local_war']).is_file():
|
||||
QMessageBox.warning(self, '请选择部署文件', '请选择本地 ROOT.war 文件。')
|
||||
return
|
||||
if actual_mode != 'backend' and not Path(config['local_front']).exists():
|
||||
QMessageBox.warning(self, '请选择部署文件', '请选择本地 dist 文件夹或 ZIP。')
|
||||
return
|
||||
elif action == 'cert_deploy':
|
||||
if not Path(config.get('local_cert', '')).is_file() or not Path(config.get('local_key', '')).is_file():
|
||||
QMessageBox.warning(self, '请选择证书文件', '请选择本地证书文件和私钥文件。')
|
||||
return
|
||||
if not config.get('nginx_cert_name') or not config.get('nginx_key_name'):
|
||||
QMessageBox.warning(self, '请配置服务器文件名', '请在“编辑配置 → Nginx 设置”中填写服务器证书和私钥文件名。')
|
||||
return
|
||||
nginx_action = action in ('cert_deploy', 'nginx_restart')
|
||||
self.tabs.setCurrentIndex(self.nginx_tab_index if nginx_action else 0)
|
||||
self.active_log = self.nginx_log if nginx_action else self.log
|
||||
self.active_progress = self.nginx_progress if nginx_action else self.progress
|
||||
self.active_percent = self.nginx_percent if nginx_action else self.percent
|
||||
self.active_phase = self.nginx_phase if nginx_action else self.phase
|
||||
self.active_status = self.nginx_status if nginx_action else self.status
|
||||
self.active_steps = self.nginx_steps if nginx_action else self.steps
|
||||
self.active_log.clear()
|
||||
self.active_progress.setValue(0)
|
||||
self.active_percent.setText('0%')
|
||||
self.active_phase.setText('正在连接…')
|
||||
self.badge.setText('执行中')
|
||||
self.active_status.setText('正在执行,请保持工具运行。')
|
||||
if action == 'cert_deploy':
|
||||
self.active_steps.setText('01 连接检查 / 02 校验证书 / 03 原子替换 / 04 重启验证')
|
||||
elif action == 'nginx_restart':
|
||||
self.active_steps.setText('01 连接检查 / 02 nginx -t / 03 重启服务 / 04 状态确认')
|
||||
else:
|
||||
self.active_steps.setText('01 连接检查 / 02 上传文件 / 03 备份替换 / 04 启动验证')
|
||||
self.busy(True)
|
||||
self.worker = Worker(config, action, actual_mode, backup, self)
|
||||
self.worker.message.connect(self.active_log.appendPlainText)
|
||||
self.worker.progress.connect(self.on_progress)
|
||||
self.worker.completed.connect(self.on_complete)
|
||||
self.worker.finished.connect(lambda: self.busy(False))
|
||||
self.worker.start()
|
||||
|
||||
def on_progress(self, value):
|
||||
value = max(self.active_progress.value(), value)
|
||||
self.active_progress.setValue(value)
|
||||
self.active_percent.setText(str(value) + '%')
|
||||
if self.worker and self.worker.action in ('cert_deploy', 'nginx_restart'):
|
||||
if self.worker.action == 'nginx_restart':
|
||||
self.active_phase.setText('连接与检查' if value < 15 else '校验 Nginx 配置' if value < 70 else
|
||||
'重启与状态验证' if value < 100 else '操作完成')
|
||||
else:
|
||||
self.active_phase.setText('连接与检查' if value < 15 else '上传并校验证书' if value < 45 else
|
||||
'更新证书文件' if value < 75 else '重启与状态验证' if value < 100 else '操作完成')
|
||||
else:
|
||||
self.active_phase.setText('连接与检查' if value < 15 else '正在上传文件' if value < 40 else '备份与文件替换' if value < 85 else '启动与验证' if value < 100 else '操作完成')
|
||||
|
||||
def on_complete(self, ok, log, backup):
|
||||
self.badge.setText('操作成功' if ok else '需要处理')
|
||||
self.active_phase.setText('操作完成' if ok else '操作未完成 · 请查看日志')
|
||||
self.active_status.setText('连接测试通过。' if ok and self.worker.action == 'test' else
|
||||
'Nginx 操作完成,可在历史中查看记录。' if ok and self.worker.action in ('cert_deploy', 'nginx_restart') else
|
||||
'部署操作完成,可在历史中查看记录。' if ok else '操作失败,详细原因及恢复结果见运行日志。')
|
||||
if self.worker.action != 'test':
|
||||
if self.worker.action == 'cert_deploy':
|
||||
action = '证书更新 / Nginx 重启'
|
||||
elif self.worker.action == 'nginx_restart':
|
||||
action = 'Nginx 重启'
|
||||
else:
|
||||
action = {'deploy':'部署', 'rollback':'回滚'}[self.worker.action] + ' / ' + {'all':'前后端', 'frontend':'前端', 'backend':'后端'}[self.worker.mode]
|
||||
self.store.record(self.pid, action, '成功' if ok else '失败', log, backup, self.worker.config)
|
||||
log_dir = data_dir() / 'logs'
|
||||
log_dir.mkdir(exist_ok=True)
|
||||
import datetime
|
||||
(log_dir / (datetime.datetime.now().strftime('%Y%m%d-%H%M%S-%f') + '.log')).write_text(log, encoding='utf-8')
|
||||
self.refresh_history()
|
||||
|
||||
def refresh_history(self):
|
||||
self.runs = self.store.history(self.pid) if self.pid else []
|
||||
self.history.setRowCount(len(self.runs))
|
||||
self.history_log.clear()
|
||||
for row, run in enumerate(self.runs):
|
||||
for col, text in enumerate((run['created'], run['action'], run['status'], '有备份 · 连接后核验' if run['backup'] else '无')):
|
||||
item = QTableWidgetItem(text)
|
||||
if col == 2:
|
||||
item.setForeground(QColor('#83e4c9' if text == '成功' else '#f7a3aa'))
|
||||
self.history.setItem(row, col, item)
|
||||
self.rollback_btn.setEnabled(False)
|
||||
|
||||
def history_selected(self):
|
||||
row = self.history.currentRow()
|
||||
if row >= 0 and row < len(self.runs):
|
||||
self.history_log.setPlainText(self.runs[row]['log'])
|
||||
is_app_backup = self.runs[row]['action'].startswith(('部署 /', '回滚 /'))
|
||||
self.rollback_btn.setEnabled(is_app_backup and bool(self.runs[row]['backup']) and not (self.worker and self.worker.isRunning()))
|
||||
|
||||
def rollback(self):
|
||||
row = self.history.currentRow()
|
||||
if row < 0 or not self.runs[row]['backup']:
|
||||
return
|
||||
run = self.runs[row]
|
||||
config = json.loads(run['config'])
|
||||
if (config['host'], config['port'], config['username']) != (self.config['host'], self.config['port'], self.config['username']):
|
||||
QMessageBox.warning(self, '连接配置已变化', '当前账号或服务器与历史记录不同,请先恢复对应的连接配置。')
|
||||
return
|
||||
config['password'] = self.config['password']
|
||||
mode = 'frontend' if run['action'].endswith('/ 前端') else 'backend' if run['action'].endswith('/ 后端') else 'all'
|
||||
question = '将 {} 恢复到 {} 这次操作之前的文件。\n备份:{}\n\n是否继续?'.format(config['host'], run['created'], run['backup'])
|
||||
if QMessageBox.question(self, '恢复历史版本', question) == QMessageBox.Yes:
|
||||
self.launch('rollback', run['backup'], config, mode)
|
||||
|
||||
def export_log(self):
|
||||
path, _ = QFileDialog.getSaveFileName(self, '导出运行日志', 'AutoDeploy.log', '日志文件 (*.log)')
|
||||
if path:
|
||||
source = self.nginx_log if self.tabs.currentIndex() == self.nginx_tab_index else self.log
|
||||
Path(path).write_text(source.toPlainText(), encoding='utf-8')
|
||||
|
||||
def closeEvent(self, event):
|
||||
if self.worker and self.worker.isRunning():
|
||||
QMessageBox.information(self, '任务正在执行', '部署或连接任务正在执行,请等待完成后再关闭。')
|
||||
event.ignore()
|
||||
else:
|
||||
self.persist_files()
|
||||
event.accept()
|
||||
|
||||
|
||||
def main():
|
||||
app = QApplication(sys.argv)
|
||||
app.setApplicationName('AutoDeploy')
|
||||
app.setStyle('Fusion')
|
||||
app.setStyleSheet(STYLE)
|
||||
app.setFont(QFont('Microsoft YaHei UI', 10))
|
||||
window = MainWindow()
|
||||
icon_path = Path(__file__).with_name('app.ico')
|
||||
if icon_path.exists():
|
||||
app.setWindowIcon(QIcon(str(icon_path)))
|
||||
window.setWindowIcon(QIcon(str(icon_path)))
|
||||
window.show()
|
||||
if '--screenshot' in sys.argv:
|
||||
def capture():
|
||||
window.grab().save(str(Path.cwd() / 'preview.png'))
|
||||
app.quit()
|
||||
QTimer.singleShot(800, capture)
|
||||
sys.exit(app.exec())
|
||||
13
build.ps1
Normal file
@@ -0,0 +1,13 @@
|
||||
$ErrorActionPreference = 'Stop'
|
||||
Set-Location -LiteralPath $PSScriptRoot
|
||||
$deployPython = (Get-Command python).Source
|
||||
$deployOriginalPath = $env:PATH
|
||||
try {
|
||||
# Keep unrelated native runtimes (e.g. Poppler ICU) out of DLL discovery.
|
||||
$env:PATH = @((Split-Path -Parent $deployPython), "$env:SystemRoot\System32", $env:SystemRoot) -join ';'
|
||||
& $deployPython -m PyInstaller --noconfirm --clean --windowed --name AutoDeploy --icon autodeploy/app.ico --add-data 'autodeploy/remote.py;autodeploy' --add-data 'autodeploy/app.ico;autodeploy' main.py
|
||||
if ($LASTEXITCODE -ne 0) { throw 'EXE 打包失败' }
|
||||
} finally {
|
||||
$env:PATH = $deployOriginalPath
|
||||
}
|
||||
Write-Host '完成:dist\AutoDeploy\AutoDeploy.exe'
|
||||
4
main.py
Normal file
@@ -0,0 +1,4 @@
|
||||
from autodeploy.ui import main
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
BIN
preview-nginx-fixed.png
Normal file
|
After Width: | Height: | Size: 107 KiB |
BIN
preview-nginx.png
Normal file
|
After Width: | Height: | Size: 97 KiB |
BIN
preview-tab-0.png
Normal file
|
After Width: | Height: | Size: 106 KiB |
BIN
preview-tab-1.png
Normal file
|
After Width: | Height: | Size: 105 KiB |
BIN
preview-tab-2.png
Normal file
|
After Width: | Height: | Size: 81 KiB |
BIN
preview.png
Normal file
|
After Width: | Height: | Size: 106 KiB |
2
requirements.txt
Normal file
@@ -0,0 +1,2 @@
|
||||
PySide6==6.11.1
|
||||
paramiko==5.0.0
|
||||
4
run.bat
Normal file
@@ -0,0 +1,4 @@
|
||||
@echo off
|
||||
cd /d "%~dp0"
|
||||
python main.py
|
||||
if errorlevel 1 pause
|
||||
355
tests/test_core.py
Normal file
@@ -0,0 +1,355 @@
|
||||
import base64
|
||||
import io
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import socket
|
||||
import sys
|
||||
import tarfile
|
||||
import tempfile
|
||||
import threading
|
||||
import types
|
||||
import unittest
|
||||
from unittest.mock import patch
|
||||
import zipfile
|
||||
|
||||
import paramiko
|
||||
|
||||
from autodeploy import remote
|
||||
from autodeploy.engine import package_front, Worker
|
||||
from autodeploy.store import Store, DEFAULTS
|
||||
|
||||
|
||||
class ConfigTests(unittest.TestCase):
|
||||
def test_time_nonce_falls_back_on_python_36(self):
|
||||
with patch.object(remote.time, 'time_ns', None), patch.object(remote.time, 'time', return_value=123.456789):
|
||||
self.assertEqual(remote.time_nonce(), int(123.456789 * 1000000000) % 1000000000)
|
||||
|
||||
def test_pid_matching_is_exact_and_excludes_other_instances(self):
|
||||
def process(pid, args):
|
||||
return types.SimpleNamespace(parent=types.SimpleNamespace(name=str(pid)), read_bytes=lambda: '\0'.join(args).encode())
|
||||
candidates = [
|
||||
process(101, ['java', '-Dcatalina.base=/usr/local/tomcat', 'org.apache.catalina.startup.Bootstrap', 'start']),
|
||||
process(102, ['java', '-Dcatalina.base=/usr/local/tomcat-other', 'org.apache.catalina.startup.Bootstrap', 'start']),
|
||||
process(103, ['java', '-Dcatalina.base=/usr/local/tomcat', 'org.apache.catalina.startup.Bootstrap', 'stop']),
|
||||
process(104, ['sh', 'java -Dcatalina.base=/usr/local/tomcat org.apache.catalina.startup.Bootstrap start'])]
|
||||
with patch.object(remote.Path, 'glob', return_value=candidates):
|
||||
self.assertEqual(remote.pids(DEFAULTS), [101])
|
||||
|
||||
def test_defaults_valid_on_windows(self):
|
||||
remote.validate(DEFAULTS)
|
||||
|
||||
def test_dangerous_paths_rejected(self):
|
||||
for path in ('/', '/home', '/home/../etc', 'relative/dist', 'C:\\dist'):
|
||||
with self.subTest(path=path), self.assertRaises(ValueError):
|
||||
remote.validate(dict(DEFAULTS, front=path))
|
||||
|
||||
def test_overlapping_paths_rejected(self):
|
||||
for key, value in [('temp','/home/dist/tmp'), ('front','/usr/local/tomcat'), ('backups','/usr/local/tomcat/webapps/backups')]:
|
||||
with self.subTest(key=key), self.assertRaises(ValueError):
|
||||
remote.validate(dict(DEFAULTS, **{key: value}))
|
||||
|
||||
def test_service_injection_rejected(self):
|
||||
with self.assertRaises(ValueError):
|
||||
remote.validate(dict(DEFAULTS, service='tomcat; reboot'))
|
||||
|
||||
def test_nginx_service_and_certificate_names_are_safe(self):
|
||||
with self.assertRaises(ValueError):
|
||||
remote.validate_nginx(dict(DEFAULTS, nginx_service='nginx; reboot'))
|
||||
with self.assertRaises(ValueError):
|
||||
remote.validate_nginx(dict(DEFAULTS, nginx_cert_name='../server.pem', nginx_key_name='server.key'), True)
|
||||
with self.assertRaises(ValueError):
|
||||
remote.validate_nginx(dict(DEFAULTS, nginx_cert_name='same.pem', nginx_key_name='same.pem'), True)
|
||||
|
||||
|
||||
class FilesTests(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.tmp = tempfile.TemporaryDirectory()
|
||||
self.root = Path(self.tmp.name)
|
||||
|
||||
def tearDown(self):
|
||||
self.tmp.cleanup()
|
||||
|
||||
def test_corrupted_upload_fails_before_stopping_service(self):
|
||||
stage = self.root / ('autodeploy-' + 'a' * 32)
|
||||
stage.mkdir()
|
||||
(stage / 'ROOT.war').write_bytes(b'corrupted upload')
|
||||
payload = dict(config=dict(DEFAULTS, temp=str(self.root)), action='deploy', mode='backend',
|
||||
stage=str(stage), hashes={'ROOT.war': '0' * 64})
|
||||
encoded = base64.b64encode(json.dumps(payload).encode()).decode()
|
||||
with patch.object(sys, 'argv', ['remote.py', encoded]), patch.object(remote, 'validate'), patch.object(remote, 'stop') as stop:
|
||||
with self.assertRaisesRegex(ValueError, '校验失败'):
|
||||
remote.main()
|
||||
stop.assert_not_called()
|
||||
self.assertFalse(stage.exists())
|
||||
|
||||
def test_front_directory_roundtrip_and_stale_file_removed(self):
|
||||
dist = self.root / 'source'
|
||||
dist.mkdir()
|
||||
(dist / 'index.html').write_text('new')
|
||||
(dist / '中文.js').write_text('js', encoding='utf-8')
|
||||
archive = self.root / 'dist.tar.gz'
|
||||
package_front(dist, archive)
|
||||
remote.unpack(archive, self.root / 'unpacked')
|
||||
target = self.root / 'target'
|
||||
target.mkdir()
|
||||
(target / 'stale.js').write_text('old')
|
||||
remote.install(self.root / 'unpacked', target, {})
|
||||
self.assertEqual((target / 'index.html').read_text(), 'new')
|
||||
self.assertFalse((target / 'stale.js').exists())
|
||||
self.assertTrue((target / '中文.js').exists())
|
||||
|
||||
def test_zip_dist_wrapper_supported(self):
|
||||
source = self.root / 'source.zip'
|
||||
with zipfile.ZipFile(source, 'w') as z:
|
||||
z.writestr('dist/index.html', 'hello')
|
||||
package_front(source, self.root / 'out.tgz')
|
||||
with tarfile.open(self.root / 'out.tgz') as tf:
|
||||
self.assertEqual(tf.getnames(), ['index.html'])
|
||||
|
||||
def test_zip_traversal_rejected(self):
|
||||
source = self.root / 'bad.zip'
|
||||
with zipfile.ZipFile(source, 'w') as z:
|
||||
z.writestr('../escape.txt', 'bad')
|
||||
with self.assertRaises(ValueError):
|
||||
package_front(source, self.root / 'out.tgz')
|
||||
self.assertFalse((self.root / 'escape.txt').exists())
|
||||
|
||||
def test_tar_traversal_and_links_rejected(self):
|
||||
for link in (False, True):
|
||||
archive = self.root / 'bad.tar.gz'
|
||||
with tarfile.open(archive, 'w:gz') as tf:
|
||||
info = tarfile.TarInfo('link' if link else '../escape.txt')
|
||||
if link:
|
||||
info.type = tarfile.SYMTYPE
|
||||
info.linkname = '/etc/passwd'
|
||||
tf.addfile(info)
|
||||
with self.assertRaises(ValueError):
|
||||
remote.unpack(archive, self.root / ('out' + str(link)))
|
||||
|
||||
def test_missing_index_rejected(self):
|
||||
source = self.root / 'empty'
|
||||
source.mkdir()
|
||||
with self.assertRaises(ValueError):
|
||||
package_front(source, self.root / 'out.tgz')
|
||||
|
||||
|
||||
class TransactionTests(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.tmp = tempfile.TemporaryDirectory()
|
||||
self.root = Path(self.tmp.name)
|
||||
self.c = dict(DEFAULTS, front=str(self.root / 'dist'), war=str(self.root / 'tomcat/webapps/ROOT.war'),
|
||||
tomcat=str(self.root / 'tomcat'), backups=str(self.root / 'backups'))
|
||||
self.stage = self.root / 'stage'
|
||||
self.stage.mkdir()
|
||||
(self.stage / 'dist').mkdir()
|
||||
(self.stage / 'dist/index.html').write_text('new-front')
|
||||
(self.stage / 'ROOT.war').write_text('new-war')
|
||||
Path(self.c['front']).mkdir()
|
||||
(Path(self.c['front']) / 'index.html').write_text('old-front')
|
||||
Path(self.c['war']).parent.mkdir(parents=True)
|
||||
Path(self.c['war']).write_text('old-war')
|
||||
Path(self.c['war']).with_suffix('').mkdir()
|
||||
(Path(self.c['war']).with_suffix('') / 'old.txt').write_text('old-expanded')
|
||||
self.events = []
|
||||
self.event_patch = patch.object(remote, 'event', side_effect=lambda msg, progress=None, **extra: self.events.append((msg, extra)))
|
||||
self.event_patch.start()
|
||||
self.fcntl = patch.dict(sys.modules, fcntl=types.SimpleNamespace(LOCK_EX=2, LOCK_NB=4, flock=lambda *args: None))
|
||||
self.fcntl.start()
|
||||
|
||||
def tearDown(self):
|
||||
self.fcntl.stop()
|
||||
self.event_patch.stop()
|
||||
self.tmp.cleanup()
|
||||
|
||||
def test_frontend_does_not_stop_tomcat(self):
|
||||
with patch.object(remote, 'stop') as stop, patch.object(remote, 'start') as start:
|
||||
remote.transaction(self.c, 'frontend', self.stage)
|
||||
stop.assert_not_called()
|
||||
start.assert_not_called()
|
||||
self.assertEqual((Path(self.c['front']) / 'index.html').read_text(), 'new-front')
|
||||
self.assertEqual(Path(self.c['war']).read_text(), 'old-war')
|
||||
|
||||
def test_success_replaces_both_and_removes_expanded_root(self):
|
||||
with patch.object(remote, 'pids', return_value=[42]), patch.object(remote, 'stop'), patch.object(remote, 'start'):
|
||||
remote.transaction(self.c, 'all', self.stage)
|
||||
self.assertEqual(Path(self.c['war']).read_text(), 'new-war')
|
||||
self.assertFalse(Path(self.c['war']).with_suffix('').exists())
|
||||
|
||||
def test_failed_start_restores_both_and_restarts_old_service(self):
|
||||
with patch.object(remote, 'pids', return_value=[42]), patch.object(remote, 'stop') as stop, patch.object(remote, 'start', side_effect=[RuntimeError('health failed'), None]) as start:
|
||||
with self.assertRaises(RuntimeError):
|
||||
remote.transaction(self.c, 'all', self.stage)
|
||||
self.assertEqual(stop.call_count, 2)
|
||||
self.assertEqual(start.call_count, 2)
|
||||
self.assertEqual(Path(self.c['war']).read_text(), 'old-war')
|
||||
self.assertEqual((Path(self.c['front']) / 'index.html').read_text(), 'old-front')
|
||||
self.assertTrue((Path(self.c['war']).with_suffix('') / 'old.txt').exists())
|
||||
|
||||
def test_stop_failure_never_replaces_files(self):
|
||||
with patch.object(remote, 'pids', return_value=[42]), patch.object(remote, 'stop', side_effect=RuntimeError('cannot stop')):
|
||||
with self.assertRaises(RuntimeError):
|
||||
remote.transaction(self.c, 'all', self.stage)
|
||||
self.assertEqual(Path(self.c['war']).read_text(), 'old-war')
|
||||
|
||||
def test_lock_conflict_never_stops_service(self):
|
||||
with patch.dict(sys.modules, fcntl=types.SimpleNamespace(LOCK_EX=2, LOCK_NB=4, flock=lambda *args: (_ for _ in ()).throw(BlockingIOError('locked')))):
|
||||
with patch.object(remote, 'pids', return_value=[42]), patch.object(remote, 'stop') as stop:
|
||||
with self.assertRaises(BlockingIOError):
|
||||
remote.transaction(self.c, 'all', self.stage)
|
||||
stop.assert_not_called()
|
||||
|
||||
def test_manual_restore_and_two_backup_retention(self):
|
||||
backup = remote.snapshot(self.c, 'all')
|
||||
Path(self.c['war']).write_text('changed')
|
||||
remote.restore(self.c, backup)
|
||||
self.assertEqual(Path(self.c['war']).read_text(), 'old-war')
|
||||
for _ in range(3):
|
||||
remote.snapshot(self.c, 'frontend')
|
||||
remote.prune(self.c)
|
||||
kept = list((Path(self.c['backups']) / remote.project_key(self.c)).iterdir())
|
||||
self.assertEqual(len(kept), 2)
|
||||
|
||||
def test_missing_and_foreign_backup_rejected(self):
|
||||
with self.assertRaises(ValueError):
|
||||
remote.load_backup(self.c, str(self.root / 'foreign'))
|
||||
missing = Path(self.c['backups']) / remote.project_key(self.c) / 'missing'
|
||||
with self.assertRaises(FileNotFoundError):
|
||||
remote.load_backup(self.c, str(missing))
|
||||
|
||||
def test_first_deploy_restore_absence(self):
|
||||
remote.remove(Path(self.c['front']))
|
||||
backup = remote.snapshot(self.c, 'frontend')
|
||||
remote.copy(self.stage / 'dist', Path(self.c['front']))
|
||||
remote.restore(self.c, backup)
|
||||
self.assertFalse(Path(self.c['front']).exists())
|
||||
|
||||
|
||||
class StoreTests(unittest.TestCase):
|
||||
def test_multiple_profiles_plain_password_and_password_free_history(self):
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
store = Store(Path(tmp) / 'db.sqlite')
|
||||
a = store.save(None, dict(DEFAULTS, name='A', password='secret-A'))
|
||||
b = store.save(None, dict(DEFAULTS, name='B', password='secret-B'))
|
||||
self.assertNotEqual(a, b)
|
||||
self.assertEqual(store.profiles()[0][1]['password'], 'secret-A')
|
||||
store.record(a, '部署', '成功', 'ok', '/backup', dict(DEFAULTS, password='secret-A'))
|
||||
self.assertNotIn('secret-A', store.history(a)[0]['config'])
|
||||
store.delete(a)
|
||||
self.assertEqual(len(store.profiles()), 1)
|
||||
|
||||
|
||||
class NginxTests(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.tmp = tempfile.TemporaryDirectory()
|
||||
self.root = Path(self.tmp.name)
|
||||
self.cert_dir = self.root / 'ssl'
|
||||
self.cert_dir.mkdir()
|
||||
self.backups = self.root / 'backups'
|
||||
self.stage = self.root / 'stage'
|
||||
self.stage.mkdir()
|
||||
(self.stage / 'certificate.pem').write_text('new-cert')
|
||||
(self.stage / 'private.key').write_text('new-key')
|
||||
self.c = dict(DEFAULTS, backups=str(self.backups), nginx_cert_dir=str(self.cert_dir),
|
||||
nginx_cert_name='server.pem', nginx_key_name='server.key')
|
||||
(self.cert_dir / 'server.pem').write_text('old-cert')
|
||||
(self.cert_dir / 'server.key').write_text('old-key')
|
||||
self.fcntl = patch.dict(sys.modules, fcntl=types.SimpleNamespace(LOCK_EX=2, LOCK_NB=4, flock=lambda *args: None))
|
||||
self.fcntl.start()
|
||||
self.lock = patch.object(remote, 'nginx_lock_path', return_value=self.root / 'nginx.lock')
|
||||
self.lock.start()
|
||||
self.events = patch.object(remote, 'event')
|
||||
self.events.start()
|
||||
|
||||
def tearDown(self):
|
||||
self.events.stop()
|
||||
self.lock.stop()
|
||||
self.fcntl.stop()
|
||||
self.tmp.cleanup()
|
||||
|
||||
def test_certificate_transaction_replaces_pair_and_keeps_backup(self):
|
||||
with patch.object(remote, 'validate_certificate_pair'), patch.object(remote, 'nginx_active', return_value=True), \
|
||||
patch.object(remote, 'nginx_test') as test, patch.object(remote, 'restart_nginx') as restart:
|
||||
remote.certificate_transaction(self.c, self.stage)
|
||||
self.assertEqual((self.cert_dir / 'server.pem').read_text(), 'new-cert')
|
||||
self.assertEqual((self.cert_dir / 'server.key').read_text(), 'new-key')
|
||||
self.assertEqual(test.call_count, 1)
|
||||
self.assertEqual(restart.call_count, 1)
|
||||
self.assertEqual(len(list(remote.nginx_backup_root(self.c).iterdir())), 1)
|
||||
|
||||
def test_failed_nginx_test_restores_old_pair_and_service(self):
|
||||
with patch.object(remote, 'validate_certificate_pair'), patch.object(remote, 'nginx_active', return_value=True), \
|
||||
patch.object(remote, 'nginx_test', side_effect=[RuntimeError('bad config'), None]) as test, \
|
||||
patch.object(remote, 'restart_nginx') as restart:
|
||||
with self.assertRaisesRegex(RuntimeError, 'bad config'):
|
||||
remote.certificate_transaction(self.c, self.stage)
|
||||
self.assertEqual((self.cert_dir / 'server.pem').read_text(), 'old-cert')
|
||||
self.assertEqual((self.cert_dir / 'server.key').read_text(), 'old-key')
|
||||
self.assertEqual(test.call_count, 2)
|
||||
self.assertEqual(restart.call_count, 1)
|
||||
|
||||
def test_standalone_restart_stops_when_config_test_fails(self):
|
||||
with patch.object(remote, 'nginx_test', side_effect=RuntimeError('bad config')), \
|
||||
patch.object(remote, 'restart_nginx') as restart:
|
||||
with self.assertRaisesRegex(RuntimeError, 'bad config'):
|
||||
remote.nginx_restart_transaction(self.c)
|
||||
restart.assert_not_called()
|
||||
|
||||
def test_mismatched_certificate_pair_is_rejected(self):
|
||||
outputs = [b'', b'', b'certificate-public-key', b'private-public-key']
|
||||
with patch.object(remote, 'openssl_output', side_effect=outputs):
|
||||
with self.assertRaisesRegex(ValueError, '不匹配'):
|
||||
remote.validate_certificate_pair(self.stage / 'certificate.pem', self.stage / 'private.key')
|
||||
|
||||
|
||||
class SSHTests(unittest.TestCase):
|
||||
def test_real_ssh_password_auth_and_host_key_persist(self):
|
||||
class Server(paramiko.ServerInterface):
|
||||
def check_auth_password(self, username, password):
|
||||
return paramiko.AUTH_SUCCESSFUL if (username, password) == ('test', 'secret') else paramiko.AUTH_FAILED
|
||||
def get_allowed_auths(self, username):
|
||||
return 'password'
|
||||
def check_channel_request(self, kind, chanid):
|
||||
return paramiko.OPEN_SUCCEEDED
|
||||
def check_channel_exec_request(self, channel, command):
|
||||
def respond():
|
||||
channel.send(b'Python 3.6.8\n')
|
||||
channel.send_exit_status(0)
|
||||
channel.shutdown_write()
|
||||
threading.Timer(.1, respond).start()
|
||||
return True
|
||||
listener = socket.socket()
|
||||
listener.bind(('127.0.0.1', 0))
|
||||
listener.listen(1)
|
||||
key = paramiko.RSAKey.generate(2048)
|
||||
transports = []
|
||||
def serve():
|
||||
connection, _ = listener.accept()
|
||||
transport = paramiko.Transport(connection)
|
||||
transports.append(transport)
|
||||
transport.add_server_key(key)
|
||||
transport.start_server(server=Server())
|
||||
channel = transport.accept(10)
|
||||
if channel:
|
||||
channel.closed_event.wait(10) if hasattr(channel, 'closed_event') else threading.Event().wait(.5)
|
||||
thread = threading.Thread(target=serve, daemon=True)
|
||||
thread.start()
|
||||
try:
|
||||
with tempfile.TemporaryDirectory() as tmp, patch.dict(os.environ, AUTODEPLOY_DATA=tmp):
|
||||
c = dict(DEFAULTS, host='127.0.0.1', port=listener.getsockname()[1], username='test', password='secret')
|
||||
worker = Worker(c, 'test')
|
||||
results = []
|
||||
worker.completed.connect(lambda ok, log, backup: results.append(ok))
|
||||
worker.run()
|
||||
self.assertEqual(results, [True])
|
||||
self.assertTrue((Path(tmp) / 'known_hosts').exists())
|
||||
self.assertNotIn('secret', '\n'.join(worker.logs))
|
||||
finally:
|
||||
for transport in transports:
|
||||
transport.close()
|
||||
listener.close()
|
||||
thread.join(2)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
74
tests/test_ui.py
Normal file
@@ -0,0 +1,74 @@
|
||||
import os
|
||||
import tempfile
|
||||
import unittest
|
||||
from unittest.mock import patch
|
||||
|
||||
from PySide6.QtWidgets import QApplication
|
||||
from autodeploy.store import Store, DEFAULTS
|
||||
from autodeploy.ui import MainWindow, ProfileDialog, STYLE
|
||||
|
||||
|
||||
class UITests(unittest.TestCase):
|
||||
@classmethod
|
||||
def setUpClass(cls):
|
||||
cls.app = QApplication.instance() or QApplication([])
|
||||
cls.app.setStyleSheet(STYLE)
|
||||
|
||||
def setUp(self):
|
||||
self.tmp = tempfile.TemporaryDirectory()
|
||||
self.env = patch.dict(os.environ, AUTODEPLOY_DATA=self.tmp.name)
|
||||
self.env.start()
|
||||
self.window = MainWindow()
|
||||
|
||||
def tearDown(self):
|
||||
self.window.close()
|
||||
self.window.deleteLater()
|
||||
self.app.processEvents()
|
||||
self.env.stop()
|
||||
self.tmp.cleanup()
|
||||
|
||||
def test_empty_state_and_switching_profiles_preserves_files(self):
|
||||
self.assertEqual([self.window.tabs.tabText(i) for i in range(self.window.tabs.count())],
|
||||
['发布部署', 'Nginx 管理', '历史与回滚'])
|
||||
self.assertFalse(self.window.tabs.isAncestorOf(self.window.server_card))
|
||||
self.assertFalse(self.window.deploy_btn.isEnabled())
|
||||
a = self.window.store.save(None, dict(DEFAULTS, host='192.0.2.10', name='A'))
|
||||
b = self.window.store.save(None, dict(DEFAULTS, host='192.0.2.11', name='B'))
|
||||
self.window.refresh_profiles(a)
|
||||
self.assertTrue(self.window.deploy_btn.isEnabled())
|
||||
self.window.war.setText('C:/build/ROOT.war')
|
||||
self.window.cert.setText('C:/cert/server.pem')
|
||||
self.window.servers.setCurrentRow(1)
|
||||
self.assertEqual(self.window.pid, b)
|
||||
self.window.servers.setCurrentRow(0)
|
||||
self.assertEqual(self.window.war.text(), 'C:/build/ROOT.war')
|
||||
self.assertEqual(self.window.cert.text(), 'C:/cert/server.pem')
|
||||
self.assertTrue(self.window.tabs.widget(self.window.nginx_tab_index).isAncestorOf(self.window.cert))
|
||||
self.assertFalse(self.window.tabs.widget(0).isAncestorOf(self.window.cert))
|
||||
self.assertGreaterEqual(self.window.cert.minimumHeight(), 42)
|
||||
self.assertGreaterEqual(self.window.cert_file_btn.minimumWidth(), 118)
|
||||
|
||||
def test_frontend_mode_and_busy_lock(self):
|
||||
a = self.window.store.save(None, dict(DEFAULTS, host='192.0.2.10'))
|
||||
self.window.refresh_profiles(a)
|
||||
self.window.mode.setCurrentIndex(1)
|
||||
self.assertFalse(self.window.war.isEnabled())
|
||||
self.assertTrue(self.window.front.isEnabled())
|
||||
self.window.busy(True)
|
||||
self.assertFalse(self.window.front.isEnabled())
|
||||
self.assertFalse(self.window.cert_deploy_btn.isEnabled())
|
||||
self.assertFalse(self.window.servers.isEnabled())
|
||||
self.window.busy(False)
|
||||
self.assertFalse(self.window.war.isEnabled())
|
||||
|
||||
def test_configuration_dialog_accepts_posix_paths(self):
|
||||
dialog = ProfileDialog(dict(DEFAULTS, host='192.0.2.10'), self.window)
|
||||
dialog.fields['password'].setText('plain password')
|
||||
dialog.save()
|
||||
self.assertEqual(dialog.result(), dialog.DialogCode.Accepted)
|
||||
self.assertEqual(dialog.config['password'], 'plain password')
|
||||
dialog.deleteLater()
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
20
tools/make_icon.py
Normal file
@@ -0,0 +1,20 @@
|
||||
from pathlib import Path
|
||||
from PySide6.QtCore import Qt, QRectF
|
||||
from PySide6.QtGui import QImage, QPainter, QColor, QPen, QPolygonF
|
||||
from PySide6.QtCore import QPointF
|
||||
from PySide6.QtWidgets import QApplication
|
||||
|
||||
app = QApplication([])
|
||||
image = QImage(256, 256, QImage.Format_ARGB32)
|
||||
image.fill(Qt.transparent)
|
||||
p = QPainter(image)
|
||||
p.setRenderHint(QPainter.Antialiasing)
|
||||
p.setPen(Qt.NoPen)
|
||||
p.setBrush(QColor('#10241f'))
|
||||
p.drawRoundedRect(QRectF(8, 8, 240, 240), 54, 54)
|
||||
p.setPen(QPen(QColor('#81e8cc'), 17, Qt.SolidLine, Qt.RoundCap, Qt.RoundJoin))
|
||||
p.drawPolyline(QPolygonF([QPointF(61, 164), QPointF(61, 190), QPointF(195, 190), QPointF(195, 164)]))
|
||||
p.drawLine(128, 65, 128, 151)
|
||||
p.drawPolyline(QPolygonF([QPointF(89, 104), QPointF(128, 65), QPointF(167, 104)]))
|
||||
p.end()
|
||||
image.save(str(Path(__file__).resolve().parents[1] / 'autodeploy/app.ico'))
|
||||