284 lines
9.2 KiB
Python
284 lines
9.2 KiB
Python
#!/usr/bin/env python3
|
|
"""
|
|
Promote manually uploaded YumiNail jars on production hosts.
|
|
|
|
Recommended manual upload location:
|
|
/opt/app/upload/YumiNail-Core.jar
|
|
/opt/app/upload/YumiNail-Gateway.jar
|
|
|
|
The script keeps the server-side convention:
|
|
current: /opt/app/<App>.jar
|
|
backup: /opt/app/backups/<App>.jar.bak-YYYYMMDD-HHMMSS
|
|
release: /opt/app/releases/<App>-YYYYMMDD-HHMMSS.jar
|
|
"""
|
|
|
|
import argparse
|
|
import glob
|
|
import re
|
|
import sys
|
|
import time
|
|
import zipfile
|
|
import xml.etree.ElementTree as ET
|
|
|
|
import paramiko
|
|
|
|
|
|
NS = {"m": "http://schemas.openxmlformats.org/spreadsheetml/2006/main"}
|
|
SERVICES = {
|
|
"core": {
|
|
"app": "YumiNail-Core",
|
|
"pattern": re.compile(r"^YumiNail-Core0[1-3]$", re.I),
|
|
},
|
|
"gateway": {
|
|
"app": "YumiNail-Gateway",
|
|
"pattern": re.compile(r"^YumiNail-Gateway0[1-3]$", re.I),
|
|
},
|
|
}
|
|
|
|
|
|
def cell_index(ref):
|
|
match = re.match(r"[A-Z]+", ref or "A1")
|
|
if not match:
|
|
return 0
|
|
value = 0
|
|
for letter in match.group(0):
|
|
value = value * 26 + ord(letter) - ord("A") + 1
|
|
return value - 1
|
|
|
|
|
|
def default_workbook():
|
|
candidates = glob.glob("Y:/code/*.xlsx")
|
|
if not candidates:
|
|
candidates = glob.glob("E:/code/xiaowang/*.xlsx")
|
|
if not candidates:
|
|
raise RuntimeError("No server workbook found. Pass --server-info explicitly.")
|
|
return sorted(candidates)[0]
|
|
|
|
|
|
def workbook_rows(path):
|
|
with zipfile.ZipFile(path) as archive:
|
|
shared = []
|
|
root = ET.fromstring(archive.read("xl/sharedStrings.xml"))
|
|
for item in root.findall("m:si", NS):
|
|
shared.append("".join(node.text or "" for node in item.findall(".//m:t", NS)))
|
|
|
|
workbook = ET.fromstring(archive.read("xl/workbook.xml"))
|
|
relationships = ET.fromstring(archive.read("xl/_rels/workbook.xml.rels"))
|
|
relmap = {rel.attrib["Id"]: rel.attrib["Target"] for rel in relationships}
|
|
sheet = workbook.find(
|
|
"{http://schemas.openxmlformats.org/spreadsheetml/2006/main}sheets/"
|
|
"{http://schemas.openxmlformats.org/spreadsheetml/2006/main}sheet"
|
|
)
|
|
sheet_id = sheet.attrib["{http://schemas.openxmlformats.org/officeDocument/2006/relationships}id"]
|
|
sheet_root = ET.fromstring(archive.read("xl/" + relmap[sheet_id].lstrip("/")))
|
|
|
|
for row in sheet_root.findall(".//m:row", NS):
|
|
values = []
|
|
for cell in row.findall("m:c", NS):
|
|
index = cell_index(cell.attrib.get("r", "A1"))
|
|
while len(values) <= index:
|
|
values.append("")
|
|
node = cell.find("m:v", NS)
|
|
value = "" if node is None or node.text is None else node.text
|
|
if cell.attrib.get("t") == "s" and value:
|
|
value = shared[int(value)]
|
|
values[index] = value
|
|
values += [""] * 8
|
|
if values[0].strip():
|
|
try:
|
|
port = int(values[2] or 22)
|
|
except ValueError:
|
|
continue
|
|
yield {
|
|
"name": values[0].strip(),
|
|
"host": values[1].strip(),
|
|
"port": port,
|
|
"user": values[3].strip(),
|
|
"password": values[4],
|
|
}
|
|
|
|
|
|
def select_targets(rows, service, target_names):
|
|
wanted = set()
|
|
if target_names:
|
|
wanted = {item.strip().lower() for item in ",".join(target_names).split(",") if item.strip()}
|
|
selected = []
|
|
pattern = SERVICES[service]["pattern"]
|
|
for row in rows:
|
|
name = row["name"]
|
|
if wanted:
|
|
if name.lower() in wanted:
|
|
selected.append(row)
|
|
elif pattern.match(name):
|
|
selected.append(row)
|
|
if not selected:
|
|
raise RuntimeError("No matching targets found.")
|
|
return selected
|
|
|
|
|
|
def shell_quote(value):
|
|
return "'" + str(value).replace("'", "'\"'\"'") + "'"
|
|
|
|
|
|
def open_ssh(server):
|
|
client = paramiko.SSHClient()
|
|
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
|
|
client.connect(
|
|
hostname=server["host"],
|
|
port=server["port"],
|
|
username=server["user"],
|
|
password=server["password"],
|
|
timeout=20,
|
|
banner_timeout=20,
|
|
auth_timeout=20,
|
|
)
|
|
return client
|
|
|
|
|
|
def run_remote(server, command, dry_run=False):
|
|
print(f"==> {server['name']} ({server['host']})")
|
|
if dry_run:
|
|
print(command)
|
|
return 0
|
|
client = open_ssh(server)
|
|
try:
|
|
_, stdout, stderr = client.exec_command(command, timeout=240)
|
|
out = stdout.read().decode(errors="replace")
|
|
err = stderr.read().decode(errors="replace")
|
|
code = stdout.channel.recv_exit_status()
|
|
if out:
|
|
print(out, end="" if out.endswith("\n") else "\n")
|
|
if err:
|
|
print(err, end="" if err.endswith("\n") else "\n", file=sys.stderr)
|
|
if code != 0:
|
|
print(f"remote command failed with exit code {code}", file=sys.stderr)
|
|
return code
|
|
finally:
|
|
client.close()
|
|
|
|
|
|
def promote_command(app, remote_app_dir, upload_dir, uploaded_jar_name, timestamp, restart):
|
|
app_q = shell_quote(app)
|
|
app_dir_q = shell_quote(remote_app_dir)
|
|
upload_dir_q = shell_quote(upload_dir)
|
|
upload_name_q = shell_quote(uploaded_jar_name)
|
|
ts_q = shell_quote(timestamp)
|
|
restart_part = ""
|
|
if restart:
|
|
restart_part = """
|
|
echo "-- restart --"
|
|
cd "$APP_DIR"
|
|
NO_TAIL=1 ./start.sh restart
|
|
"""
|
|
return f"""set -e
|
|
APP={app_q}
|
|
APP_DIR={app_dir_q}
|
|
UPLOAD_DIR={upload_dir_q}
|
|
UPLOAD_NAME={upload_name_q}
|
|
TS={ts_q}
|
|
CURRENT="$APP_DIR/$APP.jar"
|
|
UPLOADED="$UPLOAD_DIR/$UPLOAD_NAME"
|
|
BACKUP="$APP_DIR/backups/$APP.jar.bak-$TS"
|
|
RELEASE="$APP_DIR/releases/$APP-$TS.jar"
|
|
mkdir -p "$APP_DIR/backups" "$APP_DIR/releases" "$UPLOAD_DIR"
|
|
if [ ! -f "$UPLOADED" ]; then
|
|
echo "Uploaded jar not found: $UPLOADED"
|
|
echo "Upload the jar there first, then rerun this script."
|
|
exit 41
|
|
fi
|
|
if [ -f "$CURRENT" ]; then
|
|
cp -p "$CURRENT" "$BACKUP"
|
|
echo "backup: $BACKUP"
|
|
else
|
|
echo "current jar missing, no backup created: $CURRENT"
|
|
fi
|
|
cp -p "$UPLOADED" "$RELEASE"
|
|
mv -f "$UPLOADED" "$CURRENT"
|
|
chmod 644 "$CURRENT"
|
|
echo "release: $RELEASE"
|
|
echo "current: $CURRENT"
|
|
ls -lh "$CURRENT" "$RELEASE" 2>/dev/null
|
|
{restart_part}"""
|
|
|
|
|
|
def install_tail_command(remote_app_dir):
|
|
app_dir_q = shell_quote(remote_app_dir)
|
|
return f"""set -e
|
|
APP_DIR={app_dir_q}
|
|
FILE="$APP_DIR/start.sh"
|
|
TS=$(date +%Y%m%d-%H%M%S)
|
|
test -f "$FILE"
|
|
cp -p "$FILE" "$FILE.bak-tail-$TS"
|
|
python - "$FILE" <<'PY'
|
|
from __future__ import print_function
|
|
import io
|
|
import sys
|
|
|
|
path = sys.argv[1]
|
|
text = io.open(path, encoding="utf-8", errors="replace").read()
|
|
marker = "# BEGIN YUMINAIL START TAIL"
|
|
needle = ' echo "Logs: $LOG_PATH"\\n'
|
|
block = ''' echo "Logs: $LOG_PATH"
|
|
# BEGIN YUMINAIL START TAIL
|
|
if [ "${{NO_TAIL:-0}}" != "1" ] && [ -t 1 ]; then
|
|
echo "Tailing logs. Press Ctrl+C to stop tail; the service keeps running."
|
|
tail -f "$LOG_PATH"
|
|
else
|
|
echo "Tail logs: tail -f $LOG_PATH"
|
|
fi
|
|
# END YUMINAIL START TAIL
|
|
'''
|
|
if marker not in text:
|
|
if needle not in text:
|
|
raise SystemExit("Cannot find log echo line in start.sh")
|
|
text = text.replace(needle, block, 1)
|
|
io.open(path, "w", encoding="utf-8").write(text)
|
|
PY
|
|
chmod +x "$FILE"
|
|
echo "patched: $FILE"
|
|
echo "backup: $FILE.bak-tail-$TS"
|
|
grep -n "YUMINAIL START TAIL\\|tail -f" "$FILE" || true
|
|
"""
|
|
|
|
|
|
def main():
|
|
parser = argparse.ArgumentParser(description="Promote manually uploaded YumiNail jars on multiple servers.")
|
|
parser.add_argument("--service", choices=sorted(SERVICES), required=True)
|
|
parser.add_argument("--action", choices=["promote", "install-start-tail"], default="promote")
|
|
parser.add_argument("--server-info", default="")
|
|
parser.add_argument("--targets", nargs="*", help="Exact workbook target names, comma-separated or repeated.")
|
|
parser.add_argument("--remote-app-dir", default="/opt/app")
|
|
parser.add_argument("--upload-dir", default="/opt/app/upload")
|
|
parser.add_argument("--uploaded-jar-name", default="")
|
|
parser.add_argument("--timestamp", default=time.strftime("%Y%m%d-%H%M%S"))
|
|
parser.add_argument("--restart", action="store_true", help="Restart service after promote with NO_TAIL=1.")
|
|
parser.add_argument("--dry-run", action="store_true")
|
|
args = parser.parse_args()
|
|
|
|
workbook = args.server_info or default_workbook()
|
|
rows = list(workbook_rows(workbook))
|
|
targets = select_targets(rows, args.service, args.targets)
|
|
app = SERVICES[args.service]["app"]
|
|
uploaded_name = args.uploaded_jar_name or f"{app}.jar"
|
|
|
|
print(f"workbook: {workbook}")
|
|
print(f"service: {app}")
|
|
print("targets: " + ", ".join(target["name"] for target in targets))
|
|
if args.action == "promote":
|
|
print(f"expected upload: {args.upload_dir}/{uploaded_name}")
|
|
command = promote_command(app, args.remote_app_dir, args.upload_dir, uploaded_name, args.timestamp, args.restart)
|
|
else:
|
|
command = install_tail_command(args.remote_app_dir)
|
|
|
|
failures = []
|
|
for target in targets:
|
|
code = run_remote(target, command, args.dry_run)
|
|
if code != 0:
|
|
failures.append(target["name"])
|
|
if failures:
|
|
raise SystemExit("failed targets: " + ", ".join(failures))
|
|
|
|
|
|
if __name__ == "__main__":
|
|
main()
|