feat: 开源母线电容计算器并接入独立自动部署
整理 Buck 与 PMSM 完整源码、离线构建、校核测试和使用说明,采用 MIT 许可。 增加页首开源链接,支持推送 main 后自动测试、构建并发布到原计算器网址。
This commit is contained in:
@@ -0,0 +1,383 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Build the current main branch and atomically publish a validated release."""
|
||||
|
||||
from contextlib import contextmanager
|
||||
from datetime import datetime, timezone
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path, PurePosixPath
|
||||
import re
|
||||
import shlex
|
||||
import shutil
|
||||
import subprocess
|
||||
import sys
|
||||
import tarfile
|
||||
import tempfile
|
||||
import uuid
|
||||
|
||||
try:
|
||||
import fcntl
|
||||
except ImportError: # Allow cross-platform unit tests; production requires Linux.
|
||||
fcntl = None
|
||||
|
||||
|
||||
DEFAULT_CONFIG = "/srv/bus-capacitor/automation/config.json"
|
||||
SHA_PATTERN = re.compile(r"[0-9a-f]{40}\Z")
|
||||
BUILD_PATTERN = re.compile(r"[0-9a-f]{12}-[a-z0-9_]{8}\Z")
|
||||
ARCHIVE_PATTERN = re.compile(r"archive-[a-z0-9_]{8}\.tar\Z")
|
||||
RELEASE_PATTERN = re.compile(r"[0-9]{8}T[0-9]{12}Z-[0-9a-f]{12}\Z")
|
||||
|
||||
|
||||
def utc_now():
|
||||
return datetime.now(timezone.utc).isoformat(timespec="seconds").replace("+00:00", "Z")
|
||||
|
||||
|
||||
def atomic_json(path, value, mode=0o600):
|
||||
path = Path(path)
|
||||
path.parent.mkdir(mode=0o700, parents=True, exist_ok=True)
|
||||
descriptor, temporary = tempfile.mkstemp(prefix=".state-", dir=path.parent)
|
||||
try:
|
||||
os.chmod(temporary, mode)
|
||||
with os.fdopen(descriptor, "w", encoding="utf-8") as stream:
|
||||
json.dump(value, stream, ensure_ascii=False, indent=2)
|
||||
stream.write("\n")
|
||||
stream.flush()
|
||||
os.fsync(stream.fileno())
|
||||
os.replace(temporary, path)
|
||||
finally:
|
||||
if os.path.exists(temporary):
|
||||
os.unlink(temporary)
|
||||
|
||||
|
||||
def read_json(path, default=None):
|
||||
try:
|
||||
return json.loads(Path(path).read_text(encoding="utf-8"))
|
||||
except FileNotFoundError:
|
||||
return default
|
||||
|
||||
|
||||
@contextmanager
|
||||
def file_lock(path, blocking=True):
|
||||
if fcntl is None:
|
||||
raise RuntimeError("Deployment locking requires Linux fcntl")
|
||||
path = Path(path)
|
||||
path.parent.mkdir(mode=0o700, parents=True, exist_ok=True)
|
||||
descriptor = os.open(path, os.O_CREAT | os.O_RDWR, 0o600)
|
||||
try:
|
||||
operation = fcntl.LOCK_EX | (0 if blocking else fcntl.LOCK_NB)
|
||||
fcntl.flock(descriptor, operation)
|
||||
yield
|
||||
finally:
|
||||
os.close(descriptor)
|
||||
|
||||
|
||||
def consume_pending(state_dir):
|
||||
state_dir = Path(state_dir)
|
||||
with file_lock(state_dir / "queue.lock"):
|
||||
pending = state_dir / "pending.json"
|
||||
event = read_json(pending)
|
||||
if event is not None:
|
||||
pending.unlink()
|
||||
return event
|
||||
|
||||
|
||||
def safe_extract(archive, destination):
|
||||
"""Git archives need only regular files/directories, never filesystem links."""
|
||||
destination = Path(destination).resolve()
|
||||
with tarfile.open(archive, "r:") as bundle:
|
||||
members = bundle.getmembers()
|
||||
for member in members:
|
||||
relative = PurePosixPath(member.name)
|
||||
if relative.is_absolute() or ".." in relative.parts:
|
||||
raise ValueError("Git archive contains an unsafe path")
|
||||
if not (member.isfile() or member.isdir()):
|
||||
raise ValueError("Git archive contains an unsupported link or special file")
|
||||
(destination / member.name).resolve().relative_to(destination)
|
||||
bundle.extractall(destination, members=members, filter="data")
|
||||
|
||||
|
||||
class DeploymentWorker:
|
||||
def __init__(self, config):
|
||||
self.config = config
|
||||
for name in ["state_dir", "cache_dir", "build_dir", "log_dir", "runtime_dir", "webroot"]:
|
||||
value = Path(config[name])
|
||||
if not value.is_absolute():
|
||||
raise ValueError(f"{name} must be absolute")
|
||||
setattr(self, name, value)
|
||||
self.state_dir.mkdir(mode=0o700, parents=True, exist_ok=True)
|
||||
self.build_dir.mkdir(mode=0o700, parents=True, exist_ok=True)
|
||||
self.log_dir.mkdir(mode=0o700, parents=True, exist_ok=True)
|
||||
self.env = os.environ.copy()
|
||||
self.env["PATH"] = os.pathsep.join([
|
||||
str(self.runtime_dir / "node/bin"),
|
||||
str(self.runtime_dir / "pnpm/node_modules/.bin"),
|
||||
self.env.get("PATH", "/usr/bin:/bin"),
|
||||
])
|
||||
self.env["NODE_OPTIONS"] = "--max-old-space-size=2304"
|
||||
self.env["GIT_TERMINAL_PROMPT"] = "0"
|
||||
if config["repo_url"].startswith("ssh://"):
|
||||
for name in ["ssh_key", "known_hosts"]:
|
||||
value = Path(config[name])
|
||||
if not value.is_absolute():
|
||||
raise ValueError(f"{name} must be absolute")
|
||||
setattr(self, name, value)
|
||||
self.env["GIT_SSH_COMMAND"] = shlex.join([
|
||||
"ssh", "-F", "/dev/null", "-i", str(self.ssh_key),
|
||||
"-o", f"UserKnownHostsFile={self.known_hosts}",
|
||||
"-o", "StrictHostKeyChecking=yes",
|
||||
"-o", "BatchMode=yes", "-o", "IdentitiesOnly=yes",
|
||||
])
|
||||
for name in ["GIT_DIR", "GIT_WORK_TREE", "GIT_INDEX_FILE"]:
|
||||
self.env.pop(name, None)
|
||||
|
||||
def notice(self, message):
|
||||
print(f"{utc_now()} {message}", flush=True)
|
||||
|
||||
def command(self, arguments, log, cwd=None, capture=False):
|
||||
log.write("$ " + shlex.join(map(str, arguments)) + "\n")
|
||||
log.flush()
|
||||
result = subprocess.run(
|
||||
list(map(str, arguments)), cwd=cwd, env=self.env,
|
||||
stdout=subprocess.PIPE if capture else log,
|
||||
stderr=log, text=True, check=True,
|
||||
)
|
||||
return result.stdout.strip() if capture else None
|
||||
|
||||
def git(self, arguments, log, capture=False):
|
||||
return self.command(["git", f"--git-dir={self.cache_dir}", *arguments], log, capture=capture)
|
||||
|
||||
def ensure_cache(self, log):
|
||||
if not self.cache_dir.exists():
|
||||
self.cache_dir.parent.mkdir(mode=0o700, parents=True, exist_ok=True)
|
||||
self.command(["git", "init", "--bare", self.cache_dir], log)
|
||||
self.git(["remote", "add", "origin", self.config["repo_url"]], log)
|
||||
if self.git(["rev-parse", "--is-bare-repository"], log, capture=True) != "true":
|
||||
raise ValueError("Configured cache is not a bare repository")
|
||||
remotes = self.git(["remote"], log, capture=True).splitlines()
|
||||
if "origin" not in remotes:
|
||||
self.git(["remote", "add", "origin", self.config["repo_url"]], log)
|
||||
if self.git(["remote", "get-url", "origin"], log, capture=True) != self.config["repo_url"]:
|
||||
raise ValueError("Repository cache origin does not match configuration")
|
||||
|
||||
def fetch_main(self, log):
|
||||
self.git(["fetch", "--no-tags", "origin", "+refs/heads/main:refs/remotes/origin/main"], log)
|
||||
sha = self.git(["rev-parse", "--verify", "refs/remotes/origin/main^{commit}"], log, capture=True)
|
||||
if not SHA_PATTERN.fullmatch(sha):
|
||||
raise ValueError("main did not resolve to a valid commit")
|
||||
return sha
|
||||
|
||||
def materialize(self, sha, log):
|
||||
build = Path(tempfile.mkdtemp(prefix=f"{sha[:12]}-", dir=self.build_dir))
|
||||
archive = None
|
||||
try:
|
||||
descriptor, archive = tempfile.mkstemp(prefix="archive-", suffix=".tar", dir=self.build_dir)
|
||||
with os.fdopen(descriptor, "wb") as stream:
|
||||
subprocess.run([
|
||||
"git", f"--git-dir={self.cache_dir}", "archive", "--format=tar", sha,
|
||||
], env=self.env, stdout=stream, stderr=log, check=True)
|
||||
safe_extract(archive, build)
|
||||
except BaseException:
|
||||
self.remove_generated(build, self.build_dir, BUILD_PATTERN)
|
||||
raise
|
||||
finally:
|
||||
if archive is not None:
|
||||
self.remove_generated(Path(archive), self.build_dir, ARCHIVE_PATTERN, file=True)
|
||||
return build
|
||||
|
||||
def remove_generated(self, path, root, pattern, file=False):
|
||||
"""Remove only an ordinary, generated direct child of the trusted root."""
|
||||
path, root = Path(path), Path(root)
|
||||
try:
|
||||
if (root.is_symlink() or root.resolve() != root.absolute()
|
||||
or path.parent != root or not pattern.fullmatch(path.name)
|
||||
or path.is_symlink() or path.resolve().parent != root.resolve()
|
||||
or path.is_mount()):
|
||||
raise ValueError(f"Refusing cleanup outside generated storage: {path}")
|
||||
if not path.exists():
|
||||
return
|
||||
if file:
|
||||
if not path.is_file():
|
||||
raise ValueError(f"Refusing cleanup of unexpected file type: {path}")
|
||||
path.unlink()
|
||||
else:
|
||||
if not path.is_dir():
|
||||
raise ValueError(f"Refusing cleanup of unexpected directory type: {path}")
|
||||
shutil.rmtree(path)
|
||||
except (OSError, ValueError, RuntimeError) as error:
|
||||
self.notice(f"Cleanup warning: {error}")
|
||||
|
||||
def cleanup_builds(self):
|
||||
# Only called under worker.lock, before this worker creates a build.
|
||||
for path in self.build_dir.iterdir():
|
||||
if BUILD_PATTERN.fullmatch(path.name):
|
||||
self.remove_generated(path, self.build_dir, BUILD_PATTERN)
|
||||
elif ARCHIVE_PATTERN.fullmatch(path.name):
|
||||
self.remove_generated(path, self.build_dir, ARCHIVE_PATTERN, file=True)
|
||||
|
||||
def cleanup_releases(self):
|
||||
releases = self.webroot / "releases"
|
||||
if not releases.exists():
|
||||
return
|
||||
if releases.is_symlink() or releases.resolve() != releases.absolute():
|
||||
raise ValueError("Release storage must not be a filesystem link")
|
||||
protected = set()
|
||||
current = self.webroot / "current"
|
||||
if current.is_symlink():
|
||||
protected.add(current.resolve(strict=True))
|
||||
elif current.exists():
|
||||
raise ValueError("Current publication path is not a symbolic link")
|
||||
previous = read_json(self.state_dir / "last-success.json", {})
|
||||
if not isinstance(previous, dict):
|
||||
raise ValueError("last-success.json must contain a JSON object")
|
||||
for name in ["release", "previous_release"]:
|
||||
if previous.get(name):
|
||||
protected.add(Path(previous[name]).resolve())
|
||||
keep = self.config.get("release_keep", 3)
|
||||
if type(keep) is not int or keep < 1:
|
||||
raise ValueError("release_keep must be a positive integer")
|
||||
candidates = sorted([
|
||||
path for path in releases.iterdir()
|
||||
if RELEASE_PATTERN.fullmatch(path.name) and not path.is_symlink()
|
||||
and path.is_dir() and path.resolve().parent == releases.resolve()
|
||||
], key=lambda path: path.name, reverse=True)
|
||||
protected.update(path.resolve() for path in candidates[:keep])
|
||||
for path in candidates:
|
||||
if path.resolve() not in protected:
|
||||
self.remove_generated(path, releases, RELEASE_PATTERN)
|
||||
|
||||
def cleanup_storage(self, builds=False):
|
||||
# Cleanup problems must never turn a successful publication into failure.
|
||||
try:
|
||||
if builds:
|
||||
self.cleanup_builds()
|
||||
self.cleanup_releases()
|
||||
except (OSError, ValueError, TypeError, RuntimeError) as error:
|
||||
self.notice(f"Cleanup warning: {error}")
|
||||
|
||||
def build(self, directory, log):
|
||||
self.command(["node", "scripts/test.cjs"], log, cwd=directory)
|
||||
self.command(["python3", "-m", "unittest", "discover", "-s", "deploy", "-p", "test_*.py"], log, cwd=directory)
|
||||
self.command(["node", "scripts/build.cjs"], log, cwd=directory)
|
||||
|
||||
def stage_release(self, directory, sha):
|
||||
dist = directory / "dist"
|
||||
if dist.is_symlink() or not dist.is_dir():
|
||||
raise ValueError("Build output is missing or is a filesystem link")
|
||||
for required in ["impedance-calculators.html", "buck-rlc-calculator.html", "motor-impedance-calculator.html", "LICENSE"]:
|
||||
if not (dist / required).is_file():
|
||||
raise ValueError(f"Required build output is missing: {required}")
|
||||
if any(path.is_symlink() for path in dist.rglob("*")):
|
||||
raise ValueError("Build output contains filesystem links")
|
||||
stamp = datetime.now(timezone.utc).strftime("%Y%m%dT%H%M%S%fZ")
|
||||
release = self.webroot / "releases" / f"{stamp}-{sha[:12]}"
|
||||
release.parent.mkdir(parents=True, exist_ok=True)
|
||||
self.webroot.chmod(0o755)
|
||||
release.parent.chmod(0o755)
|
||||
release.mkdir()
|
||||
try:
|
||||
shutil.copytree(dist, release, dirs_exist_ok=True)
|
||||
# The deployment service uses a private umask, while Caddy must be able
|
||||
# to traverse and read the intentionally public static artifact.
|
||||
release.chmod(0o755)
|
||||
for path in release.rglob("*"):
|
||||
path.chmod(0o755 if path.is_dir() else 0o644)
|
||||
atomic_json(release / "deployment.json", {"commit": sha, "built_at": utc_now()}, mode=0o644)
|
||||
except BaseException:
|
||||
self.remove_generated(release, release.parent, RELEASE_PATTERN)
|
||||
raise
|
||||
return release
|
||||
|
||||
def activate(self, release):
|
||||
current = self.webroot / "current"
|
||||
if current.exists() and not current.is_symlink():
|
||||
raise ValueError("Current publication path is not a symbolic link")
|
||||
previous = current.resolve() if current.is_symlink() else None
|
||||
temporary = self.webroot / f".current-{uuid.uuid4().hex}"
|
||||
try:
|
||||
temporary.symlink_to(release, target_is_directory=True)
|
||||
os.replace(temporary, current)
|
||||
finally:
|
||||
if temporary.is_symlink():
|
||||
temporary.unlink()
|
||||
return previous
|
||||
|
||||
def run(self):
|
||||
try:
|
||||
with file_lock(self.state_dir / "worker.lock", blocking=False):
|
||||
self.cleanup_storage(builds=True)
|
||||
return self.drain()
|
||||
except BlockingIOError:
|
||||
self.notice("Another deployment worker is already running")
|
||||
return 0
|
||||
|
||||
def drain(self):
|
||||
carry = None
|
||||
while True:
|
||||
event = carry if carry is not None else consume_pending(self.state_dir)
|
||||
carry = None
|
||||
if event is None:
|
||||
return 0
|
||||
started = utc_now()
|
||||
log_path = self.log_dir / f"{datetime.now(timezone.utc).strftime('%Y%m%dT%H%M%S%fZ')}.log"
|
||||
attempt = {"sha": None, "status": "fetching", "log": str(log_path), "started_at": started}
|
||||
directory = None
|
||||
with log_path.open("w", encoding="utf-8", buffering=1) as log:
|
||||
try:
|
||||
atomic_json(self.state_dir / "last-attempt.json", attempt)
|
||||
self.ensure_cache(log)
|
||||
sha = self.fetch_main(log)
|
||||
attempt["sha"] = sha
|
||||
previous = read_json(self.state_dir / "last-success.json", {})
|
||||
if previous.get("sha") == sha:
|
||||
attempt.update(status="skipped", finished_at=utc_now())
|
||||
atomic_json(self.state_dir / "last-attempt.json", attempt)
|
||||
self.notice(f"main {sha[:12]} is already published")
|
||||
continue
|
||||
self.notice(f"Building main {sha[:12]}; log {log_path.name}")
|
||||
attempt["status"] = "building"
|
||||
atomic_json(self.state_dir / "last-attempt.json", attempt)
|
||||
directory = self.materialize(sha, log)
|
||||
self.build(directory, log)
|
||||
release = self.stage_release(directory, sha)
|
||||
latest = self.fetch_main(log)
|
||||
if latest != sha:
|
||||
attempt.update(status="superseded", finished_at=utc_now(), latest_sha=latest)
|
||||
atomic_json(self.state_dir / "last-attempt.json", attempt)
|
||||
self.notice(f"Skipped outdated candidate {sha[:12]}; main is {latest[:12]}")
|
||||
carry = {"after": latest}
|
||||
continue
|
||||
previous_release = self.activate(release)
|
||||
published = utc_now()
|
||||
try:
|
||||
atomic_json(self.state_dir / "last-success.json", {
|
||||
"sha": sha, "release": str(release), "published_at": published,
|
||||
"previous_release": str(previous_release) if previous_release is not None else None,
|
||||
})
|
||||
except Exception:
|
||||
if previous_release is not None:
|
||||
self.activate(previous_release)
|
||||
raise
|
||||
attempt.update(status="success", finished_at=published, release=str(release))
|
||||
atomic_json(self.state_dir / "last-attempt.json", attempt)
|
||||
self.notice(f"Published main {sha[:12]}")
|
||||
except Exception as error:
|
||||
attempt.update(status="failed", finished_at=utc_now(), error=str(error)[:500])
|
||||
atomic_json(self.state_dir / "last-attempt.json", attempt)
|
||||
log.write(f"Deployment failed: {error}\n")
|
||||
self.notice(f"Deployment failed for {(attempt.get('sha') or 'unknown')[:12]}; see {log_path.name}")
|
||||
return 1
|
||||
finally:
|
||||
if directory is not None:
|
||||
self.remove_generated(directory, self.build_dir, BUILD_PATTERN)
|
||||
self.cleanup_storage()
|
||||
|
||||
|
||||
def main():
|
||||
if fcntl is None:
|
||||
raise SystemExit("Deployment worker requires Linux fcntl")
|
||||
config = json.loads(Path(sys.argv[1] if len(sys.argv) > 1 else DEFAULT_CONFIG).read_text(encoding="utf-8"))
|
||||
return DeploymentWorker(config).run()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
Reference in New Issue
Block a user