feat: port tiers actions (link, chown, useradd)
This commit is contained in:
1 parent
f7fc0eb697
commit
b9c80b0212
3 files changed
+201
No files matched your search
@@ -0,0 +1,61 @@
|
||||
# actions/tiers/chown.py
|
||||
"""Port of tiers/chown — ownership: {tier}/{proj} -> uid:gid; {tier}/shared/{proj} ->
|
||||
uid:shared_gid (+sticky); base/node-infra -> root:root. Reads APEX_UID/GID from each .env."""
|
||||
import os
|
||||
from engine.descriptor import Meta, Arg
|
||||
|
||||
METADATA = Meta(summary="Apply tier ownership/permissions from each project's APEX_UID/GID/.env.",
|
||||
args=[Arg("tier1_path", "Path to tier 1", required=False),
|
||||
Arg("tier2_path", "Path to tier 2", required=False),
|
||||
Arg("tier3_path", "Path to tier 3", required=False)])
|
||||
SHARED_GROUP = "noroot-shared"
|
||||
|
||||
def _env_val(path, key):
|
||||
if not os.path.exists(path):
|
||||
return ""
|
||||
for line in open(os.path.realpath(path)):
|
||||
line = line.strip()
|
||||
if line.startswith(key + "="):
|
||||
return line.split("=", 1)[1].strip()
|
||||
return ""
|
||||
|
||||
def run(ctx, args):
|
||||
log, s = ctx.log, ctx.sys
|
||||
comp = ctx.paths.compositions
|
||||
tiers = [os.path.realpath(args.tier1_path or ctx.paths.tier1),
|
||||
os.path.realpath(args.tier2_path or ctx.paths.tier2),
|
||||
os.path.realpath(args.tier3_path or ctx.paths.tier3)]
|
||||
|
||||
cp = s.run(["getent", "group", SHARED_GROUP], check=False, capture=True)
|
||||
if cp.returncode != 0:
|
||||
log.error(f"Shared group '{SHARED_GROUP}' not found. Run tiers/useradd first."); raise SystemExit(1)
|
||||
|
||||
log.info("Ensuring base structures owned by root...")
|
||||
for tp in tiers:
|
||||
s.sudo(["chown", "root:root", tp])
|
||||
for sub in ("shared", "node-infra"):
|
||||
p = os.path.join(tp, sub)
|
||||
if os.path.isdir(p):
|
||||
s.sudo(["chown", "-R", "root:root", p])
|
||||
|
||||
for proj in sorted(os.listdir(comp)):
|
||||
full = os.path.join(comp, proj)
|
||||
if not os.path.isdir(full) or proj.startswith(".") or proj.startswith("@"):
|
||||
continue
|
||||
env_path = os.path.join(full, ".env")
|
||||
uid = _env_val(env_path, "APEX_UID")
|
||||
gid = _env_val(env_path, "APEX_GID")
|
||||
sgid = _env_val(env_path, "APEX_SHARED_GID")
|
||||
if not (uid and gid and sgid):
|
||||
log.warn(f"Incomplete APEX_UID/GID/SHARED_GID for {proj}. Run tiers/useradd first. Skipping.")
|
||||
continue
|
||||
log.info(f"Applying permissions for {proj} (UID={uid} GID={gid} SHARED_GID={sgid})")
|
||||
for tp in tiers:
|
||||
pdir = os.path.join(tp, proj)
|
||||
sdir = os.path.join(tp, "shared", proj)
|
||||
if os.path.isdir(pdir):
|
||||
s.sudo(["chown", "-R", f"{uid}:{gid}", pdir]); log.success(f" Owned {pdir}")
|
||||
if os.path.isdir(sdir):
|
||||
s.sudo(["chown", "-R", f"{uid}:{sgid}", sdir])
|
||||
s.sudo(["chmod", "+t", sdir]); log.success(f" Owned {sdir} (sticky)")
|
||||
log.success("Permissions applied.")
|
||||
@@ -0,0 +1,66 @@
|
||||
# actions/tiers/link.py
|
||||
"""Port of tiers/link — @tier symlink structure for the node + each composition project."""
|
||||
import os
|
||||
from engine.descriptor import Meta, Arg
|
||||
|
||||
METADATA = Meta(summary="Create @tier symlink structure for the node + each composition project.",
|
||||
args=[Arg("tier1_path", "Path to tier 1 storage root"),
|
||||
Arg("tier2_path", "Path to tier 2 storage root"),
|
||||
Arg("tier3_path", "Path to tier 3 storage root")])
|
||||
|
||||
def run(ctx, args):
|
||||
log, s = ctx.log, ctx.sys
|
||||
comp = ctx.paths.compositions
|
||||
tiers = [os.path.realpath(args.tier1_path),
|
||||
os.path.realpath(args.tier2_path),
|
||||
os.path.realpath(args.tier3_path)]
|
||||
|
||||
def confirm(msg):
|
||||
return input(f"{msg} [y/N]: ").strip().lower() in ("y", "yes")
|
||||
|
||||
def safe_remove(link, desc):
|
||||
if os.path.islink(link):
|
||||
s.sudo(["rm", link]); return True
|
||||
if os.path.exists(link):
|
||||
log.warn(f"Path exists but is not a symlink: {link}")
|
||||
if confirm(f"Remove existing {desc} (NOT a symlink)?"):
|
||||
s.sudo(["rm", "-rf", link]); return True
|
||||
return False
|
||||
return True
|
||||
|
||||
def mklink(target, link, desc):
|
||||
s.sudo(["ln", "-snf", target, link])
|
||||
log.success(f"Created {desc} symlink: {link} -> {target}")
|
||||
|
||||
log.info("Starting @tier setup...")
|
||||
for t in tiers:
|
||||
s.sudo(["mkdir", "-p", t])
|
||||
# node-level @tierN -> tier roots
|
||||
for i, n in enumerate((1, 2, 3)):
|
||||
link = os.path.join(comp, f"@tier{n}")
|
||||
if safe_remove(link, f"node-@tier{n}"):
|
||||
mklink(tiers[i], link, f"node-@tier{n}")
|
||||
# per-project (every composition subdir except dot/@)
|
||||
for proj in sorted(os.listdir(comp)):
|
||||
full = os.path.join(comp, proj)
|
||||
if not os.path.isdir(full) or proj.startswith(".") or proj.startswith("@"):
|
||||
continue
|
||||
log.info(f"Processing project: {proj}")
|
||||
for i, n in enumerate((1, 2, 3)):
|
||||
base = tiers[i]
|
||||
s.sudo(["mkdir", "-p", os.path.join(base, "shared")])
|
||||
s.sudo(["mkdir", "-p", os.path.join(base, "shared", proj)])
|
||||
s.sudo(["mkdir", "-p", os.path.join(base, proj)])
|
||||
shared_link = os.path.join(base, proj, "shared")
|
||||
if safe_remove(shared_link, "shared-internal"):
|
||||
s.sudo(["ln", "-snf", "../shared", shared_link])
|
||||
link = os.path.join(full, f"@tier{n}")
|
||||
if safe_remove(link, f"@tier{n}"):
|
||||
mklink(os.path.join(base, proj), link, f"@tier{n}")
|
||||
env_link = os.path.join(full, ".env")
|
||||
env_target = os.path.join(tiers[0], proj, ".env")
|
||||
if safe_remove(env_link, ".env"):
|
||||
if not os.path.isfile(env_target):
|
||||
s.sudo(["touch", env_target])
|
||||
mklink(env_target, env_link, ".env")
|
||||
log.success("@tier setup completed.")
|
||||
@@ -0,0 +1,74 @@
|
||||
# actions/tiers/useradd.py
|
||||
"""Port of tiers/useradd — one noroot system user per composition project; inject the
|
||||
APEX_UID/APEX_GID/APEX_SHARED_GID block into each project .env."""
|
||||
import os, re
|
||||
from engine.descriptor import Meta
|
||||
|
||||
METADATA = Meta(summary="Create a noroot system user per composition project; write APEX_UID/GID into .env.")
|
||||
SHARED_GROUP = "noroot-shared"
|
||||
START = "# START AUTO GENERATED APEX-NOROOT-USERS"
|
||||
END = "# END AUTO GENERATED APEX-NOROOT-USERS"
|
||||
|
||||
def _sanitize(raw):
|
||||
s = re.sub(r"-+$", "", re.sub(r"^-+", "", re.sub(r"[^a-z0-9]+", "-", raw.lower())))
|
||||
s = re.sub(r"-+", "-", s) or "project"
|
||||
return re.sub(r"-+$", "", s[:24])
|
||||
|
||||
def run(ctx, args):
|
||||
log, sysx = ctx.log, ctx.sys
|
||||
comp = ctx.paths.compositions
|
||||
|
||||
def getent_group(name):
|
||||
cp = sysx.run(["getent", "group", name], check=False, capture=True)
|
||||
return cp.stdout.split(":")[2].strip() if cp.returncode == 0 else ""
|
||||
|
||||
shared_gid = getent_group(SHARED_GROUP)
|
||||
if not shared_gid:
|
||||
log.info(f"Creating shared group: {SHARED_GROUP}")
|
||||
sysx.sudo(["groupadd", "-r", SHARED_GROUP])
|
||||
shared_gid = getent_group(SHARED_GROUP)
|
||||
log.info(f"Shared group {SHARED_GROUP} (GID {shared_gid})")
|
||||
|
||||
used = {}
|
||||
for proj in sorted(os.listdir(comp)):
|
||||
full = os.path.join(comp, proj)
|
||||
if not os.path.isdir(full) or proj.startswith(".") or proj.startswith("@"):
|
||||
continue
|
||||
base = f"noroot-{_sanitize(proj)}"
|
||||
cand, i = base, 1
|
||||
while cand in used:
|
||||
cand = f"{base}-{i}"; i += 1
|
||||
used[cand] = proj
|
||||
exists = sysx.run(["getent", "passwd", cand], check=False, capture=True)
|
||||
if exists.returncode != 0:
|
||||
sysx.sudo(["useradd", "-r", "-M", "-d", "/nonexistent", "-s", "/usr/sbin/nologin",
|
||||
"-c", f"System user for project {proj}", "-U", cand])
|
||||
sysx.run(["bash", "-c", f"sudo passwd -l {cand} >/dev/null 2>&1 || true"])
|
||||
log.success(f"Created system user {cand} (project {proj})")
|
||||
else:
|
||||
log.info(f"User {cand} exists (project {proj})")
|
||||
if not sysx.ok(["bash", "-c", f"groups {cand} 2>/dev/null | grep -q '\\b{SHARED_GROUP}\\b'"]):
|
||||
sysx.sudo(["usermod", "-aG", SHARED_GROUP, cand])
|
||||
pw = sysx.run(["getent", "passwd", cand], check=False, capture=True)
|
||||
parts = pw.stdout.split(":") if pw.returncode == 0 else []
|
||||
uid, gid = (parts[2], parts[3]) if len(parts) >= 4 else ("", "")
|
||||
env_path = os.path.join(full, ".env")
|
||||
if uid and gid and shared_gid and os.path.exists(env_path):
|
||||
_inject_env(ctx, env_path, uid, gid, shared_gid)
|
||||
elif os.path.exists(env_path):
|
||||
log.warn(f"Could not determine UID/GID for {cand}; skipping .env update")
|
||||
else:
|
||||
log.info(f"No .env present for project {proj}")
|
||||
log.success("noroot user provisioning completed.")
|
||||
|
||||
def _inject_env(ctx, env_path, uid, gid, shared_gid):
|
||||
actual = os.path.realpath(env_path)
|
||||
with open(actual) as f:
|
||||
text = f.read()
|
||||
block = f"{START}\nAPEX_UID={uid}\nAPEX_GID={gid}\nAPEX_SHARED_GID={shared_gid}\n{END}\n"
|
||||
if START in text:
|
||||
new = re.sub(re.escape(START) + r".*?" + re.escape(END) + r"\n", block, text, flags=re.S)
|
||||
else:
|
||||
new = block + "\n" + text
|
||||
ctx.host.write_file(actual, new, backup=True, sudo=True)
|
||||
ctx.log.success(f"Updated {actual} with APEX_UID/GID/SHARED_GID")
|
||||
Reference in new issue
Block a user