Separate one-time bootstrap, historical deployment examples and local validation. Document final hostname and historical status; exclude credentials and runtime data.
324 lines
17 KiB
Python
324 lines
17 KiB
Python
#!/usr/bin/env python3
|
|
"""Seed ONLY the assigned exhibition via an existing loopback port-forward.
|
|
|
|
Credentials come from the exhibition Secret, never from CLI arguments. This
|
|
tool does not connect to a database, a public URL, or an external calendar.
|
|
"""
|
|
import argparse
|
|
import base64
|
|
from html.parser import HTMLParser
|
|
import json
|
|
import os
|
|
from pathlib import Path
|
|
import re
|
|
import subprocess
|
|
import time
|
|
import urllib.error
|
|
import urllib.parse
|
|
import urllib.request
|
|
import uuid
|
|
|
|
ROOT = Path(__file__).resolve().parents[2]
|
|
NS = "exhibit-anya"
|
|
IMAGE = "git.anya.jp/anya/pageswiki-app@sha256:a999fe16f11ef91dbdb9904c63bb43d9ec3caef93f77cc07b1fe4a80460f67f9"
|
|
CAL = "/_/api/v1/extension/organizer.calendar/"
|
|
DAV = "/_/api/v1/caldav/"
|
|
EXHIBITION_HOST = "pages.anya.jisaba.sh"
|
|
|
|
|
|
def kubectl(*args):
|
|
env = dict(os.environ)
|
|
directory = ROOT / ".deployment-backups/exhibition-session"
|
|
env["PATH"] = str(directory / "tools") + os.pathsep + env.get("PATH", "")
|
|
env["KUBECONFIG"] = str(directory / "config/kubeconfig-keyboard")
|
|
return subprocess.check_output([str(directory / "tools/kubectl"), "--request-timeout=20s", "-n", NS, *args], env=env)
|
|
|
|
|
|
class NoRedirect(urllib.request.HTTPRedirectHandler):
|
|
def redirect_request(self, *args):
|
|
return None
|
|
|
|
|
|
class Forms(HTMLParser):
|
|
def __init__(self):
|
|
super().__init__()
|
|
self.forms, self.current, self.select = {}, None, None
|
|
|
|
def handle_starttag(self, tag, attrs):
|
|
a = dict(attrs)
|
|
if tag == "form":
|
|
self.current = a.get("id")
|
|
form = a.get("form", self.current)
|
|
if tag in ("input", "select") and form and a.get("name") and "disabled" not in a:
|
|
fields = self.forms.setdefault(form, {})
|
|
if tag == "select":
|
|
self.select = (form, a["name"])
|
|
elif a.get("type") not in ("checkbox", "radio") or "checked" in a:
|
|
fields[a["name"]] = a.get("value", "")
|
|
if tag == "option" and self.select:
|
|
form, name = self.select
|
|
if "selected" in a or name not in self.forms[form]:
|
|
self.forms[form][name] = a.get("value", "")
|
|
|
|
def handle_endtag(self, tag):
|
|
if tag == "form":
|
|
self.current = None
|
|
if tag == "select":
|
|
self.select = None
|
|
|
|
|
|
class Client:
|
|
def __init__(self, host):
|
|
deployment = json.loads(kubectl("get", "deployment", "pageswiki", "-o", "json"))
|
|
container = deployment["spec"]["template"]["spec"]["containers"][0]
|
|
if container["image"] != IMAGE:
|
|
raise RuntimeError("Unexpected exhibition deployment image")
|
|
secret = json.loads(kubectl("get", "secret", "pageswiki-exhibition-app", "-o", "json"))
|
|
self.password = base64.b64decode(secret["data"]["owner-password"]).decode()
|
|
self.host, self.token = host, None
|
|
self.opener = urllib.request.build_opener(urllib.request.ProxyHandler({}), NoRedirect())
|
|
|
|
def request(self, method, path, data=None, content_type=None, headers=None, expected=(200,)):
|
|
if not path.startswith("/") or path.startswith("//"):
|
|
raise ValueError("Only origin-relative paths allowed")
|
|
h = {"Host": self.host, "Origin": "http://" + self.host}
|
|
if self.token:
|
|
h["Authorization"] = "Bearer " + self.token
|
|
if content_type:
|
|
h["Content-Type"] = content_type
|
|
h.update(headers or {})
|
|
req = urllib.request.Request("http://127.0.0.1:18381" + urllib.parse.quote(path, safe="/%?=&:"), data=data, headers=h, method=method)
|
|
try:
|
|
response = self.opener.open(req, timeout=45)
|
|
except urllib.error.HTTPError as error:
|
|
response = error
|
|
body = response.read()
|
|
if response.code not in expected:
|
|
# Never print credentials, login bodies, or full config documents.
|
|
detail = ""
|
|
if path.startswith("/_/api/v1/import/"):
|
|
try:
|
|
detail = ": " + str(json.loads(body).get("error", ""))[:300]
|
|
except (ValueError, AttributeError):
|
|
pass
|
|
raise RuntimeError(f"{method} {path}: HTTP {response.code}{detail}")
|
|
return response.code, response.headers, body
|
|
|
|
def json(self, method, path, value=None, expected=(200,)):
|
|
body = None if value is None else json.dumps(value).encode()
|
|
_, _, result = self.request(method, path, body, "application/json", expected=expected)
|
|
return json.loads(result)
|
|
|
|
def form(self, path, value, expected=(302, 303)):
|
|
response = self.request("POST", path, urllib.parse.urlencode(value).encode(), "application/x-www-form-urlencoded", expected=expected)
|
|
if not response[1].get("Location", "").startswith("/-/sys/config"):
|
|
raise RuntimeError("Unexpected configuration redirect")
|
|
return response
|
|
|
|
def login(self):
|
|
_, _, page = self.request("GET", "/_/auth/login")
|
|
fields = {"username": "exhibition-admin", "password": self.password, "display_name": "展示管理者", "email": ""}
|
|
action = "login"
|
|
if b'name="bootstrap_token"' in page:
|
|
logs = kubectl("logs", "deployment/pageswiki", "-c", "pageswiki", "--tail=200").decode()
|
|
tokens = re.findall(r"AUTH BOOTSTRAP TOKEN domain=\S+ token=(\S+)", logs)
|
|
if len(tokens) != 1:
|
|
raise RuntimeError("Expected exactly one new exhibition bootstrap token")
|
|
fields["bootstrap_token"] = tokens[0]
|
|
action = "setup"
|
|
_, _, body = self.request("POST", "/_/auth/" + action, urllib.parse.urlencode(fields).encode(), "application/x-www-form-urlencoded", {"Accept": "application/json"})
|
|
self.token = json.loads(body)["access_token"]
|
|
print("Exhibition owner authenticated; credentials not displayed.")
|
|
|
|
def configure(self):
|
|
_, _, body = self.request("GET", "/-/sys/config?panel=campuses")
|
|
forms = Forms()
|
|
forms.feed(body.decode())
|
|
campuses = [v for k, v in forms.forms.items() if k.startswith("campus-update-")]
|
|
domains = [v for k, v in forms.forms.items() if k.startswith("domain-update-")]
|
|
if len(campuses) != 1 or len(domains) != 1:
|
|
raise RuntimeError("Only a fresh single-campus single-domain exhibition is supported")
|
|
domain, campus = domains[0], campuses[0]
|
|
if campus["campus_fqdn"] not in ("localhost", "pages.jsb.anya.jp", "wiki.pages.jisaba.sh", EXHIBITION_HOST):
|
|
raise RuntimeError("Unexpected campus host")
|
|
domain.update(domain_title="PagesWiki 展示図書館", domain_enabled="1", domain_placement="local")
|
|
self.form("/-/sys/config", domain)
|
|
campus.update(campus_title="PagesWiki 展示キャンパス", campus_default_lang="ja", campus_fqdn=EXHIBITION_HOST, campus_enabled="1")
|
|
self.form("/-/sys/config", campus)
|
|
self.host = EXHIBITION_HOST
|
|
self.request("GET", "/-/sys/config")
|
|
print("Exhibition FQDN and Japanese titles configured.")
|
|
|
|
def update_host(self):
|
|
"""Change only the existing exhibition campus FQDN, preserving its data."""
|
|
_, _, body = self.request("GET", "/-/sys/config?panel=campuses")
|
|
forms = Forms()
|
|
forms.feed(body.decode())
|
|
campuses = [v for k, v in forms.forms.items() if k.startswith("campus-update-")]
|
|
domains = [v for k, v in forms.forms.items() if k.startswith("domain-update-")]
|
|
if len(campuses) != 1 or len(domains) != 1:
|
|
raise RuntimeError("Expected one existing exhibition campus and domain")
|
|
campus = campuses[0]
|
|
if campus.get("campus_fqdn") not in ("pages.jsb.anya.jp", "wiki.pages.jisaba.sh", EXHIBITION_HOST):
|
|
raise RuntimeError("Unexpected campus host; no change made")
|
|
if domains[0].get("domain_host", "").strip():
|
|
raise RuntimeError("Expected default domain with empty hostname; no change made")
|
|
campus["campus_fqdn"] = EXHIBITION_HOST
|
|
self.form("/-/sys/config", campus)
|
|
self.host = EXHIBITION_HOST
|
|
self.request("GET", "/-/sys/config?panel=campuses")
|
|
print("Exhibition campus FQDN updated to " + EXHIBITION_HOST)
|
|
|
|
def wiki(self, folder):
|
|
_, _, listing = self.request("GET", "/v/import")
|
|
sessions = re.findall(r'href="(/v/import/[a-f0-9-]+)"[^>]*>pageswiki-exhibition-demo.zip<', listing.decode())
|
|
if len(sessions) > 1:
|
|
raise RuntimeError("Multiple exhibition import sessions; inspect before continuing")
|
|
if sessions:
|
|
location = sessions[0]
|
|
else:
|
|
boundary = "pageswiki-demo-" + uuid.uuid4().hex
|
|
data = (f"--{boundary}\r\nContent-Disposition: form-data; name=\"target_prefix\"\r\n\r\n/exhibition-demo\r\n"
|
|
f"--{boundary}\r\nContent-Disposition: form-data; name=\"archive\"; filename=\"pageswiki-exhibition-demo.zip\"\r\nContent-Type: application/zip\r\n\r\n").encode()
|
|
data += (folder / "wiki.zip").read_bytes() + f"\r\n--{boundary}--\r\n".encode()
|
|
_, headers, _ = self.request("POST", "/v/import", data, "multipart/form-data; boundary=" + boundary, expected=(303,))
|
|
location = headers["Location"]
|
|
for _ in range(30):
|
|
_, _, body = self.request("GET", location)
|
|
html = body.decode()
|
|
status = re.search(r"<dd><strong>([^<]+)</strong>", html).group(1)
|
|
if status in ("ready", "completed", "failed"):
|
|
break
|
|
time.sleep(1)
|
|
if status == "completed":
|
|
print("Wiki import already completed.")
|
|
return
|
|
if status != "ready":
|
|
raise RuntimeError("Wiki import status: " + status)
|
|
rows = re.findall(r'<tr data-import-item data-sequence="(\d+)">(.*?)</tr>', html, re.S)
|
|
if len(rows) != 27:
|
|
raise RuntimeError("Expected exactly 27 archive entries")
|
|
items = []
|
|
for sequence, row in rows:
|
|
from html import unescape
|
|
target = unescape(re.search(r'data-field="target_path" value="([^"]+)"', row).group(1))
|
|
if not target.startswith("/exhibition-demo/"):
|
|
raise RuntimeError("Import target escaped exhibition prefix")
|
|
# City identifiers are ASCII; Japanese labels are titles. Create
|
|
# the exact directory boundaries separately via the City API.
|
|
items.append(dict(sequence=int(sequence), selected=True, target_path=target, quartier="", street="", spot=""))
|
|
api = "/_/api/v1/import/" + location.rsplit("/", 1)[1]
|
|
self.json("PATCH", api, {"items": items})
|
|
self.json("POST", api, {"conflict": "skip"}, expected=(202,))
|
|
print("Wiki import queued: 26 pages and one CSV; conflict=skip.")
|
|
|
|
def organizers(self, folder):
|
|
calendars = self.json("GET", CAL + "calendars")
|
|
# Only this newly created exhibition account's synthetic collection.
|
|
found = [c for c in calendars["calendars"] if c["pretty_name"] == "exhibition-demo"]
|
|
if len(found) > 1:
|
|
raise RuntimeError("Duplicate exhibition calendars")
|
|
calendar = found[0] if found else self.json("POST", CAL + "calendars", {"name": "展示の予定", "pretty_name": "exhibition-demo"}, expected=(201,))
|
|
if calendar.get("source"):
|
|
raise RuntimeError("External calendar is never used for exhibition seeding")
|
|
task_id = str(uuid.uuid5(uuid.NAMESPACE_URL, "https://example.invalid/pageswiki-exhibition/task-list"))
|
|
task_path = DAV + task_id + "/"
|
|
status, _, _ = self.request("PROPFIND", task_path, headers={"Depth": "0"}, expected=(207, 404))
|
|
if status == 404:
|
|
xml = '<c:mkcalendar xmlns:c="urn:ietf:params:xml:ns:caldav" xmlns:d="DAV:"><d:set><d:prop><d:displayname>展示の準備</d:displayname><c:supported-calendar-component-set><c:comp name="VTODO"/></c:supported-calendar-component-set></d:prop></d:set></c:mkcalendar>'
|
|
self.request("MKCALENDAR", task_path, xml.encode(), "application/xml", expected=(201,))
|
|
card_path = "/_/api/v1/carddav/" + calendars["actor"] + "/contacts/"
|
|
for directory, prefix, media in (("events", DAV + calendar["id"] + "/", "text/calendar"), ("tasks", task_path, "text/calendar"), ("contacts", card_path, "text/vcard")):
|
|
created, skipped = 0, 0
|
|
for file in sorted((folder / directory).iterdir()):
|
|
name = "exhibition-demo-" + file.name
|
|
status, _, _ = self.request("PUT", prefix + name, file.read_bytes(), media, {"If-None-Match": "*"}, expected=(201, 412))
|
|
created += status == 201
|
|
skipped += status == 412
|
|
print(f"{directory}: created={created}, existing={skipped}; no overwrite.")
|
|
self.json("PUT", CAL + "preferences", {"calendars": [calendar["id"]]})
|
|
|
|
def city_labels(self):
|
|
# URL reconciliation keeps the dedicated prefix as the top district.
|
|
# Preserve that topology; change only labels within this dataset.
|
|
model = self.json("GET", "/_/api/v1/city/map")
|
|
desired = []
|
|
for q in model.get("quartiers") or []:
|
|
if q["path_prefix"] != "/exhibition-demo":
|
|
continue
|
|
desired.append(("quartier", q, "展示図書館"))
|
|
for street in q.get("streets") or []:
|
|
desired.append(("street", street, street["path_prefix"].rsplit("/", 1)[-1]))
|
|
for spot in street.get("spots") or []:
|
|
label = spot["path_prefix"].rsplit("/", 1)[-1]
|
|
desired.append(("spot", spot, "案内ページ" if label == "_undefined" else label))
|
|
for kind, node, title in desired:
|
|
if not node["path_prefix"].startswith("/exhibition-demo") or node["title"] == title:
|
|
continue
|
|
current = self.json("GET", "/_/api/v1/city/map")
|
|
endpoint = "spots" if kind == "spot" else "zones"
|
|
self.json("POST", f"/_/api/v1/city/{endpoint}/{node['uuid']}/title", {"kind": kind, "title": title, "base_version": current["version"]})
|
|
print("Generated exhibition City topology retained; Japanese display labels applied.")
|
|
|
|
def verify(self, folder):
|
|
for path in ("/health", "/v/browser", "/v/city", "/v/plan", "/v/plan/tasks", "/v/plan/contacts", "/v/plan/dashboard"):
|
|
status, _, _ = self.request("GET", path, expected=(200,))
|
|
print(f"{path}: {status}")
|
|
manifest = json.loads((folder / "manifest.json").read_text())
|
|
checked = 0
|
|
for name in manifest["files"]:
|
|
if not name.startswith("wiki/"):
|
|
continue
|
|
path = name[5:]
|
|
if path.endswith(".md"):
|
|
path = path[:-3]
|
|
self.request("GET", "/exhibition-demo/" + path)
|
|
checked += 1
|
|
print(f"Wiki documents readable after import: {checked}")
|
|
calendars = self.json("GET", CAL + "calendars")
|
|
calendar = next(c for c in calendars["calendars"] if c["pretty_name"] == "exhibition-demo" and not c.get("source"))
|
|
task_id = str(uuid.uuid5(uuid.NAMESPACE_URL, "https://example.invalid/pageswiki-exhibition/task-list"))
|
|
for directory, prefix in (("events", DAV + calendar["id"] + "/"), ("tasks", DAV + task_id + "/"), ("contacts", "/_/api/v1/carddav/" + calendars["actor"] + "/contacts/")):
|
|
count = 0
|
|
for file in sorted((folder / directory).iterdir()):
|
|
_, headers, body = self.request("GET", prefix + "exhibition-demo-" + file.name)
|
|
expected_uid = file.stem + "@example.invalid"
|
|
if expected_uid.encode() not in body or not headers.get("ETag"):
|
|
raise RuntimeError("Synthetic DAV resource failed UID/ETag verification")
|
|
count += 1
|
|
print(f"{directory}: {count} synthetic resources verified with ETags.")
|
|
|
|
|
|
def main():
|
|
parser = argparse.ArgumentParser(description=__doc__)
|
|
parser.add_argument("step", choices=("configure", "set-host", "wiki", "organizers", "city-labels", "verify"))
|
|
parser.add_argument("--host", choices=("localhost", "pages.jsb.anya.jp", "wiki.pages.jisaba.sh", EXHIBITION_HOST), default=EXHIBITION_HOST)
|
|
parser.add_argument("--data", type=Path, default=Path("/tmp/pageswiki-exhibition-demo"))
|
|
args = parser.parse_args()
|
|
if args.step in ("wiki", "organizers"):
|
|
manifest = json.loads((args.data / "manifest.json").read_text())
|
|
if manifest.get("dataset_id") != "pageswiki-exhibition-fiction-v1" or manifest.get("target_prefix") != "/exhibition-demo":
|
|
raise RuntimeError("Only generated exhibition fixtures are accepted")
|
|
import hashlib
|
|
for name, digest in manifest["files"].items():
|
|
if Path(name).is_absolute() or ".." in Path(name).parts or hashlib.sha256((args.data / name).read_bytes()).hexdigest() != digest:
|
|
raise RuntimeError("Modified or unsafe fixture")
|
|
client = Client(args.host)
|
|
client.login()
|
|
if args.step == "configure":
|
|
client.configure()
|
|
elif args.step == "set-host":
|
|
client.update_host()
|
|
elif args.step == "wiki":
|
|
client.wiki(args.data)
|
|
elif args.step == "organizers":
|
|
client.organizers(args.data)
|
|
elif args.step == "city-labels":
|
|
client.city_labels()
|
|
else:
|
|
client.verify(args.data)
|
|
|
|
|
|
if __name__ == "__main__":
|
|
main()
|