Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
68 changes: 48 additions & 20 deletions bootstrap.sh
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,11 @@ while (($#)); do
esac
done

if [[ $(uname -m) != aarch64 ]]; then
echo "SparkRing installs on DGX Spark (ARM64) hosts; this host is $(uname -m)." >&2
exit 1
fi

for command_name in git python3 ssh ssh-keygen ssh-keyscan ssh-copy-id; do
if ! command -v "$command_name" >/dev/null 2>&1; then
echo "missing required command: $command_name" >&2
Expand All @@ -54,7 +59,12 @@ done
if ! python3 -c 'import yaml' >/dev/null 2>&1; then
echo "PyYAML is required (Ubuntu package: python3-yaml)."
if ((ASSUME_YES == 0)); then
read -r -p "Install python3-yaml with apt? Type yes: " answer
if ! { : </dev/tty; } 2>/dev/null; then
echo "Cannot prompt for confirmation without a terminal; re-run with --yes or install python3-yaml first." >&2
exit 1
fi
answer=""
read -r -p "Install python3-yaml with apt? Type yes: " answer </dev/tty || true
if [[ ${answer,,} != yes ]]; then
echo "installation cancelled" >&2
exit 1
Expand Down Expand Up @@ -99,34 +109,52 @@ fi

mkdir -p "$BIN_DIR"
launcher="$BIN_DIR/sparkring"
if [[ -L "$launcher" ]]; then
if [[ $(readlink "$launcher") == "$INSTALL_DIR/scripts/sparkring.py" ]]; then
rm "$launcher"
else
if [[ -x /usr/bin/sparkring ]]; then
echo "Warning: /usr/bin/sparkring (installed Debian package) is already present." >&2
if [[ -L "$launcher" ]] && [[ $(readlink "$launcher") == "$INSTALL_DIR/scripts/sparkring.py" ]]; then
rm -f "$launcher"
echo "Removed $launcher so it does not shadow /usr/bin/sparkring." >&2
elif [[ -f "$launcher" ]] && grep -Fq "$INSTALL_DIR/scripts/sparkring.py" "$launcher" 2>/dev/null; then
rm -f "$launcher"
echo "Removed $launcher so it does not shadow /usr/bin/sparkring." >&2
elif [[ -e "$launcher" || -L "$launcher" ]]; then
echo "Warning: $launcher exists and may shadow /usr/bin/sparkring when $BIN_DIR precedes /usr/bin in PATH." >&2
fi
echo "Skipping $launcher creation; use /usr/bin/sparkring (or 'sparkring') for the installed package." >&2
else
if [[ -L "$launcher" ]]; then
if [[ $(readlink "$launcher") == "$INSTALL_DIR/scripts/sparkring.py" ]]; then
rm "$launcher"
else
backup="$launcher.before-sparkring-bootstrap-$(date -u +%Y%m%dT%H%M%SZ)"
mv "$launcher" "$backup"
echo "backed up existing launcher symlink to $backup"
fi
elif [[ -e "$launcher" ]]; then
backup="$launcher.before-sparkring-bootstrap-$(date -u +%Y%m%dT%H%M%SZ)"
mv "$launcher" "$backup"
echo "backed up existing launcher symlink to $backup"
echo "backed up existing launcher to $backup"
fi
elif [[ -e "$launcher" ]]; then
backup="$launcher.before-sparkring-bootstrap-$(date -u +%Y%m%dT%H%M%SZ)"
mv "$launcher" "$backup"
echo "backed up existing launcher to $backup"
# The launcher runs the tracked script through python3, so the checkout keeps
# its committed file modes and stays clean for later --ref updates.
printf '#!/usr/bin/env bash\nexec python3 %q "$@"\n' \
"$INSTALL_DIR/scripts/sparkring.py" > "$launcher"
chmod 0755 "$launcher"
fi
# The launcher runs the tracked script through python3, so the checkout keeps
# its committed file modes and stays clean for later --ref updates.
printf '#!/usr/bin/env bash\nexec python3 %q "$@"\n' \
"$INSTALL_DIR/scripts/sparkring.py" > "$launcher"
chmod 0755 "$launcher"

echo
echo "SparkRing installed at $INSTALL_DIR"
echo "Checkout revision: $(git -C "$INSTALL_DIR" rev-parse HEAD)"
echo "Run repository commands from: cd $INSTALL_DIR"
echo "Command installed at $launcher"
case ":${PATH}:" in
*":${BIN_DIR}:"*) ;;
*) echo "Add this to your shell profile: export PATH=\"${BIN_DIR}:\$PATH\"" ;;
esac
if [[ -x /usr/bin/sparkring ]]; then
echo "Packaged command in use: /usr/bin/sparkring"
else
echo "Command installed at $launcher"
case ":${PATH}:" in
*":${BIN_DIR}:"*) ;;
*) echo "Add this to your shell profile: export PATH=\"${BIN_DIR}:\$PATH\"" ;;
esac
fi
echo
echo "Check this Spark first:"
echo " sparkring host check"
Expand Down
10 changes: 9 additions & 1 deletion install.sh
Original file line number Diff line number Diff line change
Expand Up @@ -226,7 +226,13 @@ say "Source revision: $revision"
say "Building the SparkRing package"
python3 "$WORK/source/scripts/build_deb.py" --output "$WORK/dist" "${BUILD_ARGS[@]}" >/dev/null \
|| stop failed build "Could not build the SparkRing package from $revision."
package=$(echo "$WORK"/dist/sparkring_*_arm64.deb)
shopt -s nullglob
packages=("$WORK"/dist/sparkring_*_arm64.deb)
shopt -u nullglob
if ((${#packages[@]} != 1)); then
stop failed build "Expected one SparkRing Debian package in $WORK/dist, found ${#packages[@]}."
fi
package=${packages[0]}
chmod 0644 "$package"
version=$(dpkg-deb --field "$package" Version)

Expand Down Expand Up @@ -280,6 +286,8 @@ else
fi
fi
say "Installing $(basename "$package")"
"${SUDO[@]}" apt-get update >&2 \
|| stop failed package "apt-get update failed before installing $(basename "$package")."
"${SUDO[@]}" apt-get install --yes --allow-downgrades "$package" >&2 \
|| stop failed package "apt could not install $(basename "$package")."
fi
Expand Down
10 changes: 9 additions & 1 deletion packaging/debian/sparkring-access.service
Original file line number Diff line number Diff line change
Expand Up @@ -12,9 +12,17 @@ ConditionPathExists=/sys/class/net/sr-control
[Service]
Type=simple
ExecStartPre=/usr/bin/mkdir -p /run/sshd
ExecStart=/usr/sbin/sshd -D -e -f /etc/sparkring/sshd_config
ExecStart=/usr/sbin/sshd -D -e -f /etc/sparkring/sshd_config -o AllowTcpForwarding=no -o PermitTunnel=no -o GatewayPorts=no
Restart=on-failure
RestartSec=5
ProtectKernelModules=yes
ProtectKernelLogs=yes
ProtectClock=yes
ProtectHostname=yes
LockPersonality=yes
RestrictRealtime=yes
RestrictAddressFamilies=AF_INET AF_INET6 AF_UNIX
SystemCallArchitectures=native

[Install]
WantedBy=multi-user.target
9 changes: 6 additions & 3 deletions packaging/debian/sparkring-dashboard.service
Original file line number Diff line number Diff line change
Expand Up @@ -10,15 +10,18 @@ ConditionPathExists=!/etc/sparkring/dashboard.disabled

[Service]
Type=simple
ExecStart=/usr/bin/sparkring dashboard serve
# Safe default: bind to loopback only unless an operator drop-in supplies
# --password-file /etc/sparkring/dashboard.password (or --allow-unauthenticated-lan).
ExecStart=/usr/bin/sparkring dashboard serve --bind 127.0.0.1
# systemctl reload: re-read the fabric document and the site file at once. sparkring dashboard
# export, install, up, down and automatic recovery reload it after they write the site file.
ExecReload=/bin/kill -HUP $MAINPID
Restart=on-failure
RestartSec=30
# Unprivileged: the fabric document, the site file, the host-agent status and the recovery
# record it reads are mode 0644. It holds no SSH key and starts no process.
# Unprivileged: runs as a dynamic user in the sparkring group to read mode 0640
# status, recovery, site and node-report files. It holds no SSH key and starts no process.
DynamicUser=yes
SupplementaryGroups=sparkring
RuntimeDirectory=sparkring-dashboard
RuntimeDirectoryMode=0755
CapabilityBoundingSet=
Expand Down
2 changes: 2 additions & 0 deletions packaging/debian/sparkring-helper.socket
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,8 @@ ListenStream=/run/sparkring/helper.sock
SocketGroup=sparkring
SocketMode=0660
Accept=yes
MaxConnections=16
MaxConnectionsPerSource=4
RemoveOnStop=yes

[Install]
Expand Down
10 changes: 9 additions & 1 deletion packaging/debian/sparkring-seed.service
Original file line number Diff line number Diff line change
Expand Up @@ -7,9 +7,17 @@ ConditionPathExists=/etc/sparkring/seed_sshd_config
[Service]
Type=simple
ExecStartPre=/usr/bin/mkdir -p /run/sshd
ExecStart=/usr/sbin/sshd -D -e -f /etc/sparkring/seed_sshd_config
ExecStart=/usr/sbin/sshd -D -e -f /etc/sparkring/seed_sshd_config -o AllowTcpForwarding=no -o PermitTunnel=no -o GatewayPorts=no
Restart=on-failure
RestartSec=5
ProtectKernelModules=yes
ProtectKernelLogs=yes
ProtectClock=yes
ProtectHostname=yes
LockPersonality=yes
RestrictRealtime=yes
RestrictAddressFamilies=AF_INET6 AF_UNIX
SystemCallArchitectures=native

[Install]
WantedBy=multi-user.target
38 changes: 17 additions & 21 deletions runtime/host/control_node.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,10 +21,8 @@
def write(path, text, *, root="/", mode=0o600):
destination = node.location(root, path)
destination.parent.mkdir(parents=True, exist_ok=True)
temporary = node.location(root, str(destination.relative_to(root)) + ".writing")
temporary.write_text(text, encoding="utf-8", newline="\n")
temporary.chmod(mode)
temporary.replace(destination)
node.write_text_atomic(destination, text, mode=mode)
return destination


def public_key(*, root="/", run=subprocess.run):
Expand Down Expand Up @@ -327,7 +325,10 @@ def configure(document, *, root="/", run=subprocess.run):
AllowUsers root
UsePAM yes
AllowAgentForwarding no
AllowTcpForwarding yes
AllowTcpForwarding no
AllowStreamLocalForwarding no
GatewayPorts no
PermitTunnel no
X11Forwarding no
PermitUserRC no
Subsystem sftp internal-sftp
Expand All @@ -354,19 +355,13 @@ def configure(document, *, root="/", run=subprocess.run):
def _write_private(name, text, *, root):
"""Write a root-only file (0600) below a root-only directory (0700); return its path.

The file is created with its final mode, so the private key it carries is
never readable by another user.
The file is created with its final mode before any secret byte is written,
so the private key it carries is never readable by another user.
"""
destination = node.location(root, name)
destination.parent.mkdir(parents=True, exist_ok=True)
destination.parent.mkdir(parents=True, exist_ok=True, mode=0o700)
os.chmod(destination.parent, 0o700)
temporary = node.location(root, name + ".writing")
descriptor = os.open(temporary, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600)
with os.fdopen(descriptor, "w", encoding="utf-8", newline="\n") as stream:
stream.write(text)
os.chmod(temporary, 0o600)
os.replace(temporary, destination)
return destination
return node.write_text_atomic(destination, text, mode=0o600)


def up(*, root="/", run=subprocess.run, now=time.time, contact=probe, say=None):
Expand Down Expand Up @@ -467,8 +462,7 @@ def ssh_config(configs, keys, identity_file, *, home=None):
for path, text in ((include, "\n".join(rows) + "\nHost *\n"), (known, "\n".join(hosts) + "\n")):
if path.is_symlink() or path.exists() and path.read_text() != text:
raise ValueError("Another controller SSH configuration exists: " + str(path))
path.write_text(text)
path.chmod(0o600)
node.write_text_atomic(path, text, mode=0o600)
settings = directory / "config"
if settings.is_symlink():
raise ValueError("SSH config is a symlink; add the SparkRing include explicitly")
Expand All @@ -477,8 +471,10 @@ def ssh_config(configs, keys, identity_file, *, home=None):
if not text.startswith(line):
if settings.exists():
backup = directory / ("config.before-sparkring-" + str(os.getpid()))
with backup.open("x") as stream:
flags = os.O_WRONLY | os.O_CREAT | os.O_EXCL | getattr(os, "O_NOFOLLOW", 0)
descriptor = os.open(backup, flags, 0o600)
if hasattr(os, "fchmod"):
os.fchmod(descriptor, 0o600)
with os.fdopen(descriptor, "w", encoding="utf-8", newline="\n") as stream:
stream.write(text)
backup.chmod(0o600)
settings.write_text(line + text)
settings.chmod(0o600)
node.write_text_atomic(settings, line + text, mode=0o600)
60 changes: 48 additions & 12 deletions runtime/host/dashboard.py
Original file line number Diff line number Diff line change
Expand Up @@ -88,6 +88,7 @@
from functools import lru_cache
import gzip
import hashlib
import hmac
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
import ipaddress
import json
Expand Down Expand Up @@ -2014,7 +2015,8 @@ def make_handler(collector: Collector, page: bytes, csp: str, names=frozenset(),
manager=None):
headers = {"Cache-Control": "no-store", "X-Content-Type-Options": "nosniff", "Referrer-Policy": "no-referrer",
"X-Frame-Options": "DENY"}
expected = None if password is None else "Basic " + base64.b64encode(f"sparkring:{password}".encode()).decode()
expected = (None if password is None
else ("Basic " + base64.b64encode(f"sparkring:{password}".encode("utf-8")).decode("ascii")).encode("utf-8"))

class Handler(BaseHTTPRequestHandler):
server_version = "sparkring-dashboard"
Expand All @@ -2023,7 +2025,10 @@ def do_GET(self):
if not host_allowed(self.headers.get("Host"), names):
return self._send(421, b"This dashboard answers to its IP address or a name given with --name.\n",
"text/plain; charset=utf-8")
if (expected is not None and self.headers.get("Authorization") != expected
auth_header = self.headers.get("Authorization")
auth_ok = (auth_header is not None
and hmac.compare_digest(auth_header.encode("utf-8", "replace"), expected)) if expected is not None else True
if (expected is not None and not auth_ok
and not (manager and manager.authenticated(self.headers))):
self.send_response(401)
self.send_header("WWW-Authenticate", 'Basic realm="SparkRing dashboard", charset="UTF-8"')
Expand Down Expand Up @@ -2110,22 +2115,39 @@ def log_message(self, *args):
return Handler


def default_bind(source: Source) -> str:
"""On Node A, its LAN address from the fabric document (where its model API serves; else its
management address); on any other host, loopback. ``listen_addresses`` adds loopback to it."""
def is_loopback_bind(bind: str) -> bool:
"""Whether ``bind`` names a loopback interface (``127.0.0.0/8``, ``::1``, or ``localhost``)."""
text = bind.strip()
if text.lower() == "localhost":
return True
try:
return ipaddress.ip_address(text).is_loopback
except ValueError:
return False


def default_bind(source: Source, *, authenticated: bool = False,
allow_unauthenticated_lan: bool = False) -> str:
"""Default listen address: ``127.0.0.1`` unless authentication (``--password-file``) or
``--allow-unauthenticated-lan`` is enabled, in which case Node A uses its LAN address
from the fabric document (else its management address)."""
if not authenticated and not allow_unauthenticated_lan:
return "127.0.0.1"
rows = (source.fabric or {}).get("positions") or []
if rows and socket.gethostname() == rows[0]["hostname"]:
return rows[0].get("lan_address") or rows[0].get("address") or "127.0.0.1"
return "127.0.0.1"


def service_url(fabric_path: Path = FABRIC_PATH) -> str:
def service_url(fabric_path: Path = FABRIC_PATH, *, authenticated: bool = False,
allow_unauthenticated_lan: bool = False) -> str:
"""The address of the dashboard service on this Spark, by the service's default bind rule
(``default_bind``): Node A's LAN address, else loopback. A ``--bind`` given to the service
is not visible here."""
(``default_bind``): loopback by default, or Node A's LAN address when authenticated or
explicitly opted in."""
source = Source(fabric_path, SITE_PATH)
source.refresh()
bind = default_bind(source)
bind = default_bind(source, authenticated=authenticated,
allow_unauthenticated_lan=allow_unauthenticated_lan)
literal = f"[{bind}]" if ":" in bind else bind
return f"http://{literal}:{DEFAULT_PORT}"

Expand Down Expand Up @@ -2201,7 +2223,18 @@ def serve(args) -> int:
password = Path(args.password_file).read_text(encoding="utf-8").strip()
if not password:
raise ValueError(f"{args.password_file} is empty")
bind = args.bind or default_bind(sources[0])
allow_unauthenticated_lan = bool(getattr(args, "allow_unauthenticated_lan", False))
requested_bind = getattr(args, "bind", None) or getattr(args, "host", None)
if requested_bind:
if not is_loopback_bind(requested_bind) and password is None and not allow_unauthenticated_lan:
raise ValueError(
f"Refusing to bind unauthenticated dashboard to non-loopback address {requested_bind!r}; "
"configure --password-file PATH or opt in explicitly with --allow-unauthenticated-lan"
)
bind = requested_bind
else:
bind = default_bind(sources[0], authenticated=password is not None,
allow_unauthenticated_lan=allow_unauthenticated_lan)
page, csp = page_bytes()
names = frozenset(name.lower() for name in args.name or ())
servers = open_servers(listen_addresses(bind), args.port, make_handler(collector, page, csp, names, password, manager))
Expand Down Expand Up @@ -2318,13 +2351,16 @@ def main(argv=None) -> int:
"no SSH."))
commands = parser.add_subparsers(dest="command", required=True)
run = commands.add_parser("serve", help="collect and serve the page")
run.add_argument("--bind", help="listen address (default: Node A's LAN address, else 127.0.0.1); 127.0.0.1 "
"is added unless the address is loopback or a wildcard")
run.add_argument("--bind", "--host", dest="bind",
help="listen address (default: 127.0.0.1; with --password-file or --allow-unauthenticated-lan, "
"Node A's LAN address); 127.0.0.1 is added unless the address is loopback or a wildcard")
run.add_argument("--port", type=int, default=DEFAULT_PORT)
run.add_argument("--fabric", action="append", type=Path, help="fabric document (repeat with --site per fabric)")
run.add_argument("--site", action="append", type=Path, help="site file written by export")
run.add_argument("--name", action="append", help="a host name browsers may use for this page")
run.add_argument("--password-file", help="require HTTP Basic authentication (user sparkring) with this password")
run.add_argument("--allow-unauthenticated-lan", action="store_true",
help="opt in to binding the dashboard on a non-loopback address without --password-file")
run.add_argument("--manage", action="store_true", help="opt in to authenticated actions through the privileged helper")
run.add_argument("--manage-token-file", help="file containing the management bearer token (at least 32 characters)")
run.add_argument("--cpus", help="CPU list to run on, such as 0-4,10-14 (default: the efficiency cores)")
Expand Down
Loading
Loading