mirror of
https://github.com/bytedance/deer-flow.git
synced 2026-12-06 04:18:35 +08:00
* ci(website): release deerflow.tech to veFaaS from main behind a required review * ci(website): reject dangling links and keep the smoke failure when a rollback fails
406 lines
19 KiB
Python
406 lines
19 KiB
Python
#!/usr/bin/env python3
|
|
"""Package the static website build and release it to a BytePlus veFaaS function.
|
|
|
|
``.github/workflows/website-deploy.yml`` runs ``package`` in a job that holds no
|
|
secrets, then ``release`` in a job of the ``website-production`` environment,
|
|
which waits for a required reviewer before GitHub hands it the BytePlus key.
|
|
|
|
``package`` zips the standalone output of ``make build-static`` under a top-level
|
|
``standalone/`` directory, because the functions start with
|
|
``cd standalone && HOSTNAME=0.0.0.0 PORT=3000 node server.js``. Symlinks are
|
|
stored as links, the way ``zip -y`` stores them, and a link that points outside
|
|
the build is rejected because it would dangle on veFaaS.
|
|
|
|
``release`` uploads the package, publishes it as a new revision and waits for the
|
|
rollout. veFaaS keeps the previous revision serving when a rollout fails. When the
|
|
rollout succeeds but the site fails the smoke check, ``release`` publishes the
|
|
previous stable revision again and exits non-zero. The function configuration,
|
|
including its environment variables, is never changed.
|
|
|
|
``smoke`` checks a live site against a package: the home page and one of its
|
|
``/_next/static`` scripts, the docs, a showcase thread and its demo fixture, and
|
|
the package's own build manifest, which only the new revision can serve.
|
|
|
|
Standard library only: the release job installs nothing, so no dependency can
|
|
read the key. Credentials come from ``BYTEPLUS_ACCESS_KEY`` and
|
|
``BYTEPLUS_SECRET_KEY`` and are never printed.
|
|
Regression coverage: backend/tests/test_deploy_website.py.
|
|
|
|
Usage:
|
|
python scripts/deploy_website.py package --standalone DIR --output site.zip
|
|
python scripts/deploy_website.py release --function-id ID --package site.zip --site-url URL
|
|
python scripts/deploy_website.py smoke --package site.zip --site-url URL
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
import argparse
|
|
import datetime
|
|
import hashlib
|
|
import hmac
|
|
import http.client
|
|
import json
|
|
import os
|
|
import re
|
|
import stat
|
|
import sys
|
|
import time
|
|
import urllib.error
|
|
import urllib.parse
|
|
import urllib.request
|
|
import zipfile
|
|
from collections.abc import Callable
|
|
from dataclasses import dataclass
|
|
from pathlib import Path
|
|
|
|
ARCHIVE_ROOT = "standalone"
|
|
DEFAULT_REGION = "ap-southeast-1"
|
|
API_VERSION = "2024-06-06"
|
|
# veFaaS serves CodeUploadCallback only under its 2021 API version.
|
|
CALLBACK_API_VERSION = "2021-03-03"
|
|
USER_AGENT = "deerflow-website-deploy"
|
|
DEMO_THREAD = re.compile(rf"^{ARCHIVE_ROOT}/public/demo/threads/([0-9a-f-]+)/thread\.json$")
|
|
STATIC_SCRIPT = re.compile(r"""["'](/_next/static/[^"'?#]+\.js)["'?#]""")
|
|
|
|
|
|
class DeployError(Exception):
|
|
"""A packaging, release or smoke failure with a message safe to print in CI logs."""
|
|
|
|
|
|
# --- package -----------------------------------------------------------------
|
|
|
|
|
|
def _require(path: Path, description: str) -> None:
|
|
if not path.exists():
|
|
raise DeployError(f"{description} is missing: {path}")
|
|
|
|
|
|
def package(standalone: Path, output: Path) -> int:
|
|
"""Zip the standalone build under ``standalone/`` and return the number of entries."""
|
|
standalone = standalone.resolve()
|
|
_require(standalone / "server.js", "server.js")
|
|
_require(standalone / ".next" / "BUILD_ID", "the build ID")
|
|
static_dir = standalone / ".next" / "static"
|
|
if not static_dir.is_dir() or not any(static_dir.iterdir()):
|
|
raise DeployError(f"{static_dir} is empty; build with `make build-static`, which copies the static assets")
|
|
if not any((standalone / "public" / "demo" / "threads").glob("*/thread.json")):
|
|
raise DeployError(f"{standalone / 'public'} has no demo thread; build with `make build-static`, which copies public/")
|
|
|
|
output.parent.mkdir(parents=True, exist_ok=True)
|
|
count = 0
|
|
with zipfile.ZipFile(output, "w", compression=zipfile.ZIP_DEFLATED, compresslevel=6) as archive:
|
|
for directory, subdirectories, files in os.walk(standalone):
|
|
subdirectories.sort()
|
|
current = Path(directory)
|
|
for name in sorted(files) + [entry for entry in subdirectories if (current / entry).is_symlink()]:
|
|
path = current / name
|
|
if name == ".DS_Store":
|
|
continue
|
|
arcname = f"{ARCHIVE_ROOT}/{path.relative_to(standalone).as_posix()}"
|
|
if path.is_symlink():
|
|
target = os.readlink(path)
|
|
resolved = (path.parent / target).resolve()
|
|
if os.path.isabs(target) or not resolved.is_relative_to(standalone):
|
|
raise DeployError(f"{arcname} links outside the build ({target}) and would dangle on veFaaS")
|
|
if not resolved.exists():
|
|
raise DeployError(f"{arcname} links to {target}, which is not in the build")
|
|
info = zipfile.ZipInfo(arcname, date_time=time.localtime(path.lstat().st_mtime)[:6])
|
|
info.create_system = 3
|
|
info.external_attr = (stat.S_IFLNK | 0o777) << 16
|
|
archive.writestr(info, target)
|
|
else:
|
|
archive.write(path, arcname)
|
|
count += 1
|
|
subdirectories[:] = [entry for entry in subdirectories if not (current / entry).is_symlink()]
|
|
return count
|
|
|
|
|
|
@dataclass(frozen=True)
|
|
class PackageFacts:
|
|
build_id: str
|
|
demo_thread: str
|
|
|
|
|
|
def read_package(path: Path) -> PackageFacts:
|
|
"""Read the build ID and a demo thread ID from a package made by ``package``."""
|
|
with zipfile.ZipFile(path) as archive:
|
|
names = set(archive.namelist())
|
|
build_id_name = f"{ARCHIVE_ROOT}/.next/BUILD_ID"
|
|
if build_id_name not in names or f"{ARCHIVE_ROOT}/server.js" not in names:
|
|
raise DeployError(f"{path} is not a website package: server.js or BUILD_ID is missing")
|
|
build_id = archive.read(build_id_name).decode("utf-8").strip()
|
|
threads = sorted(match.group(1) for name in names if (match := DEMO_THREAD.match(name)))
|
|
if not threads:
|
|
raise DeployError(f"{path} contains no demo thread")
|
|
return PackageFacts(build_id=build_id, demo_thread=threads[0])
|
|
|
|
|
|
# --- veFaaS API --------------------------------------------------------------
|
|
|
|
|
|
class VefaasClient:
|
|
"""Signs and sends veFaaS OpenAPI calls with BytePlus HMAC-SHA256 request signing."""
|
|
|
|
service = "vefaas"
|
|
|
|
def __init__(self, access_key: str, secret_key: str, region: str, urlopen: Callable = urllib.request.urlopen) -> None:
|
|
self._access_key = access_key
|
|
self._secret_key = secret_key
|
|
self.region = region
|
|
self.host = f"vefaas.{region}.byteplusapi.com"
|
|
self._urlopen = urlopen
|
|
|
|
def signed_headers(self, action: str, version: str, body: bytes, now: datetime.datetime) -> tuple[str, dict[str, str]]:
|
|
x_date = now.strftime("%Y%m%dT%H%M%SZ")
|
|
short_date = now.strftime("%Y%m%d")
|
|
query = urllib.parse.urlencode(sorted([("Action", action), ("Version", version)]))
|
|
payload_hash = hashlib.sha256(body).hexdigest()
|
|
canonical_headers = f"content-type:application/json\nhost:{self.host}\nx-content-sha256:{payload_hash}\nx-date:{x_date}\n"
|
|
signed = "content-type;host;x-content-sha256;x-date"
|
|
canonical_request = f"POST\n/\n{query}\n{canonical_headers}\n{signed}\n{payload_hash}"
|
|
scope = f"{short_date}/{self.region}/{self.service}/request"
|
|
string_to_sign = f"HMAC-SHA256\n{x_date}\n{scope}\n{hashlib.sha256(canonical_request.encode()).hexdigest()}"
|
|
key = hmac.new(self._secret_key.encode(), short_date.encode(), hashlib.sha256).digest()
|
|
for part in (self.region, self.service, "request"):
|
|
key = hmac.new(key, part.encode(), hashlib.sha256).digest()
|
|
signature = hmac.new(key, string_to_sign.encode(), hashlib.sha256).hexdigest()
|
|
return query, {
|
|
"Content-Type": "application/json",
|
|
"Host": self.host,
|
|
"X-Date": x_date,
|
|
"X-Content-Sha256": payload_hash,
|
|
"Authorization": f"HMAC-SHA256 Credential={self._access_key}/{scope}, SignedHeaders={signed}, Signature={signature}",
|
|
}
|
|
|
|
def call(self, action: str, body: dict, version: str = API_VERSION) -> dict:
|
|
payload = json.dumps(body, separators=(",", ":")).encode()
|
|
# timezone.utc rather than datetime.UTC keeps manual runs working on macOS's Python 3.9.
|
|
query, headers = self.signed_headers(action, version, payload, datetime.datetime.now(datetime.timezone.utc)) # noqa: UP017
|
|
request = urllib.request.Request(f"https://{self.host}/?{query}", data=payload, method="POST", headers=headers)
|
|
try:
|
|
with self._urlopen(request, timeout=60) as response:
|
|
document = json.loads(response.read().decode("utf-8"))
|
|
except urllib.error.HTTPError as error:
|
|
raw = error.read().decode("utf-8", errors="replace")
|
|
try:
|
|
document = json.loads(raw)
|
|
except ValueError:
|
|
raise DeployError(f"{action} failed with HTTP {error.code}") from None
|
|
except (urllib.error.URLError, TimeoutError, ValueError) as error:
|
|
raise DeployError(f"{action} failed: {error}") from None
|
|
failure = (document.get("ResponseMetadata") or {}).get("Error")
|
|
if failure:
|
|
raise DeployError(f"{action} failed: {failure.get('Code')}: {failure.get('Message')}")
|
|
return document.get("Result") or {}
|
|
|
|
def upload(self, url: str, data: bytes) -> None:
|
|
request = urllib.request.Request(url, data=data, method="PUT", headers={"Content-Length": str(len(data))})
|
|
try:
|
|
with self._urlopen(request, timeout=600) as response:
|
|
status = response.status
|
|
except urllib.error.HTTPError as error:
|
|
status = error.code
|
|
except (urllib.error.URLError, TimeoutError) as error:
|
|
raise DeployError(f"code upload failed: {error}") from None
|
|
if status != 200:
|
|
raise DeployError(f"code upload failed with HTTP {status}")
|
|
|
|
|
|
# --- smoke -------------------------------------------------------------------
|
|
|
|
|
|
def fetch(url: str, urlopen: Callable = urllib.request.urlopen) -> tuple[int, bytes]:
|
|
request = urllib.request.Request(url, headers={"User-Agent": USER_AGENT, "Cache-Control": "no-cache"})
|
|
try:
|
|
with urlopen(request, timeout=30) as response:
|
|
return response.status, response.read()
|
|
except urllib.error.HTTPError as error:
|
|
return error.code, b""
|
|
except (urllib.error.URLError, http.client.HTTPException, OSError) as error:
|
|
raise DeployError(f"GET {url} failed: {type(error).__name__}: {error}") from None
|
|
|
|
|
|
def smoke(site_url: str, facts: PackageFacts, urlopen: Callable = urllib.request.urlopen) -> list[str]:
|
|
"""Return the failed checks; an empty list means the site serves this package."""
|
|
base = site_url.rstrip("/")
|
|
failures: list[str] = []
|
|
|
|
def expect_ok(path: str) -> bytes | None:
|
|
try:
|
|
status, body = fetch(base + path, urlopen)
|
|
except DeployError as error:
|
|
failures.append(str(error))
|
|
return None
|
|
if status != 200:
|
|
failures.append(f"GET {path} returned {status}")
|
|
return None
|
|
return body
|
|
|
|
home = expect_ok("/")
|
|
if home is not None:
|
|
script = STATIC_SCRIPT.search(home.decode("utf-8", errors="replace"))
|
|
if script is None:
|
|
failures.append("the home page references no /_next/static script")
|
|
else:
|
|
expect_ok(script.group(1))
|
|
expect_ok(f"/_next/static/{facts.build_id}/_buildManifest.js")
|
|
expect_ok("/en/docs")
|
|
expect_ok(f"/showcase/{facts.demo_thread}")
|
|
fixture = expect_ok(f"/demo/threads/{facts.demo_thread}/thread.json")
|
|
if fixture is not None:
|
|
try:
|
|
json.loads(fixture)
|
|
except ValueError:
|
|
failures.append(f"/demo/threads/{facts.demo_thread}/thread.json is not JSON")
|
|
return failures
|
|
|
|
|
|
def smoke_with_retries(site_url: str, facts: PackageFacts, attempts: int, interval: float, log: Callable[[str], None], urlopen: Callable = urllib.request.urlopen, sleep: Callable[[float], None] = time.sleep) -> list[str]:
|
|
failures: list[str] = []
|
|
for attempt in range(1, attempts + 1):
|
|
try:
|
|
failures = smoke(site_url, facts, urlopen)
|
|
# Any smoke error has to end in a rollback, never in a crash that skips it.
|
|
except Exception as error:
|
|
failures = [f"the smoke check raised {type(error).__name__}: {error}"]
|
|
if not failures:
|
|
log(f"smoke check passed on {site_url}")
|
|
return []
|
|
log(f"smoke check attempt {attempt}/{attempts} failed: {'; '.join(failures)}")
|
|
if attempt < attempts:
|
|
sleep(interval)
|
|
return failures
|
|
|
|
|
|
# --- release -----------------------------------------------------------------
|
|
|
|
|
|
def wait_for_release(client: VefaasClient, function_id: str, timeout: float, interval: float, log: Callable[[str], None], sleep: Callable[[float], None] = time.sleep) -> dict:
|
|
deadline = time.monotonic() + timeout
|
|
while True:
|
|
status = client.call("GetReleaseStatus", {"FunctionId": function_id})
|
|
state = status.get("Status")
|
|
log(f"release status={state} new={status.get('NewRevisionNumber')} stable={status.get('StableRevisionNumber')} weight={status.get('CurrentTrafficWeight')}")
|
|
if state != "inprogress":
|
|
return status
|
|
if time.monotonic() >= deadline:
|
|
raise DeployError(f"the release of {function_id} did not finish within {int(timeout)} seconds")
|
|
sleep(interval)
|
|
|
|
|
|
@dataclass
|
|
class ReleaseSettings:
|
|
function_id: str
|
|
package: Path
|
|
site_url: str
|
|
description: str
|
|
release_timeout: float = 900
|
|
poll_interval: float = 5
|
|
smoke_attempts: int = 6
|
|
smoke_interval: float = 10
|
|
|
|
|
|
def release(client: VefaasClient, settings: ReleaseSettings, log: Callable[[str], None] = print, urlopen: Callable = urllib.request.urlopen, sleep: Callable[[float], None] = time.sleep) -> int:
|
|
"""Publish the package as a new revision and return its number, rolling back on a failed smoke check."""
|
|
facts = read_package(settings.package)
|
|
function_id = settings.function_id
|
|
current = client.call("GetReleaseStatus", {"FunctionId": function_id})
|
|
if current.get("Status") == "inprogress":
|
|
raise DeployError(f"{function_id} already has a release in progress; wait for it or abort it in the console")
|
|
previous = current.get("StableRevisionNumber")
|
|
log(f"{function_id}: stable revision {previous}, uploading build {facts.build_id}")
|
|
|
|
data = settings.package.read_bytes()
|
|
address = client.call("GetCodeUploadAddress", {"FunctionId": function_id, "ContentLength": len(data)})
|
|
if not address.get("UploadAddress"):
|
|
raise DeployError("GetCodeUploadAddress returned no upload address")
|
|
client.upload(address["UploadAddress"], data)
|
|
client.call("CodeUploadCallback", {"FunctionId": function_id}, version=CALLBACK_API_VERSION)
|
|
|
|
started = client.call("Release", {"FunctionId": function_id, "RevisionNumber": 0, "Description": settings.description[:255]})
|
|
revision = started.get("NewRevisionNumber")
|
|
log(f"{function_id}: releasing revision {revision}")
|
|
final = wait_for_release(client, function_id, settings.release_timeout, settings.poll_interval, log, sleep)
|
|
if final.get("Status") != "done":
|
|
raise DeployError(f"revision {revision} ended {final.get('Status')}: {final.get('StatusMessage')}; veFaaS keeps revision {final.get('StableRevisionNumber')} serving")
|
|
|
|
failures = smoke_with_retries(settings.site_url, facts, settings.smoke_attempts, settings.smoke_interval, log, urlopen, sleep)
|
|
if not failures:
|
|
return revision
|
|
if previous is None:
|
|
raise DeployError(f"revision {revision} failed the smoke check and there is no earlier revision to restore")
|
|
smoke_failure = f"revision {revision} failed the smoke check ({'; '.join(failures)})"
|
|
log(f"{function_id}: restoring revision {previous}")
|
|
try:
|
|
client.call("Release", {"FunctionId": function_id, "RevisionNumber": previous, "Description": f"Rollback: revision {revision} failed the smoke check"})
|
|
restored = wait_for_release(client, function_id, settings.release_timeout, settings.poll_interval, log, sleep)
|
|
except DeployError as error:
|
|
raise DeployError(f"{smoke_failure}; restoring revision {previous} failed: {error}") from None
|
|
outcome = "restored" if restored.get("Status") == "done" else f"could not be restored ({restored.get('Status')}: {restored.get('StatusMessage')})"
|
|
raise DeployError(f"{smoke_failure}; revision {previous} {outcome}")
|
|
|
|
|
|
# --- CLI ---------------------------------------------------------------------
|
|
|
|
|
|
def _client_from_env(region: str) -> VefaasClient:
|
|
access_key = os.environ.get("BYTEPLUS_ACCESS_KEY", "").strip()
|
|
secret_key = os.environ.get("BYTEPLUS_SECRET_KEY", "").strip()
|
|
if not access_key or not secret_key:
|
|
raise DeployError("set BYTEPLUS_ACCESS_KEY and BYTEPLUS_SECRET_KEY")
|
|
return VefaasClient(access_key, secret_key, region)
|
|
|
|
|
|
def _summary(line: str) -> None:
|
|
path = os.environ.get("GITHUB_STEP_SUMMARY")
|
|
if path:
|
|
with open(path, "a", encoding="utf-8") as summary:
|
|
summary.write(line + "\n")
|
|
|
|
|
|
def main(argv: list[str] | None = None) -> int:
|
|
for stream in (sys.stdout, sys.stderr):
|
|
if hasattr(stream, "reconfigure"):
|
|
stream.reconfigure(encoding="utf-8", errors="replace")
|
|
parser = argparse.ArgumentParser(description=__doc__.split("\n", 1)[0])
|
|
commands = parser.add_subparsers(dest="command", required=True)
|
|
|
|
package_parser = commands.add_parser("package", help="zip a standalone build for veFaaS")
|
|
package_parser.add_argument("--standalone", type=Path, required=True, help="the .next/standalone directory of `make build-static`")
|
|
package_parser.add_argument("--output", type=Path, required=True)
|
|
|
|
for name, text in (("release", "publish a package to a veFaaS function"), ("smoke", "check that a live site serves a package")):
|
|
sub = commands.add_parser(name, help=text)
|
|
sub.add_argument("--package", type=Path, required=True)
|
|
sub.add_argument("--site-url", required=True, help="the public URL the function serves")
|
|
if name == "release":
|
|
sub.add_argument("--function-id", required=True)
|
|
sub.add_argument("--region", default=os.environ.get("VEFAAS_REGION") or DEFAULT_REGION)
|
|
sub.add_argument("--description", default="DeerFlow website")
|
|
|
|
args = parser.parse_args(argv)
|
|
try:
|
|
if args.command == "package":
|
|
count = package(args.standalone, args.output)
|
|
facts = read_package(args.output)
|
|
print(f"packaged {count} entries into {args.output} ({args.output.stat().st_size} bytes, build {facts.build_id})")
|
|
elif args.command == "smoke":
|
|
failures = smoke(args.site_url, read_package(args.package))
|
|
if failures:
|
|
raise DeployError("; ".join(failures))
|
|
print(f"smoke check passed on {args.site_url}")
|
|
else:
|
|
settings = ReleaseSettings(function_id=args.function_id, package=args.package, site_url=args.site_url, description=args.description)
|
|
revision = release(_client_from_env(args.region), settings)
|
|
print(f"{args.function_id}: revision {revision} serves {args.site_url}")
|
|
_summary(f"- `{args.function_id}`: revision {revision} serves {args.site_url}")
|
|
except DeployError as error:
|
|
print(f"error: {error}", file=sys.stderr)
|
|
_summary(f"- failed: {error}")
|
|
return 1
|
|
return 0
|
|
|
|
|
|
if __name__ == "__main__":
|
|
sys.exit(main())
|