Initial commit

This commit is contained in:
王鹏
2026-10-30 11:07:49 +08:00
commit b6a2711b2b
21 changed files with 2341 additions and 0 deletions

1
autodeploy/__init__.py Normal file
View File

@@ -0,0 +1 @@
"""AutoDeploy desktop application."""

BIN
autodeploy/app.ico Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 264 KiB

262
autodeploy/engine.py Normal file
View 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
View 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
View 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
View 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())