mirror of
https://github.com/Niko1221/Strata.git
synced 2026-12-05 15:58:53 +00:00
launch: "One address only" - serve on one address of this computer (a second network card, a VPN) (#5917)
A fifth way to share in the Access step (the last row, so the other rows keep
their keys) and `strata launch --listen ADDRESS` (or `--access address`, which
takes this computer's first address). The address is kept in the preset
("listen") and becomes the server's --host; the URL shown and kept is that
address (127.0.0.1 would not answer; IPv6 in brackets); an API key is on by
default as for the local network. Enter on the row goes to this computer's
next address (IPv4 and IPv6; loopback and link-local left out), n goes on.
An address that is no longer on this computer stops the launch before
anything is done, never a silent fallback to every address: "<address> is no
longer an address of this computer. Its addresses now: <list>. Choose one in
the Access step." Wording approved by the coordinator 11-16 (F1-F4).
Tests: tests/terminal/test_launch_listen.py (8; fail on 756242554):
addresses without loopback/link-local, host and URL, the refusal and that the
launch stops before the engine step, --listen and --access address, the
Access row (Enter cycles, n goes on, a key is made). With test_launch_tui,
test_launch and test_access_cursor_key 201 passed on p2003.
This commit is contained in:
1 parent
ec8a1d12e2
commit
5820ff60de
6 files changed
+201
-16
No files matched your search
@@ -25,13 +25,50 @@ TUNNEL_URL = re.compile(r"https://[a-z0-9-]+\.trycloudflare\.com")
|
||||
WINDOWS = os.name == "nt"
|
||||
|
||||
|
||||
def host_for(kind: str) -> str:
|
||||
"""The address the server listens on: loopback for this computer only, every address for the rest.
|
||||
def host_for(kind: str, listen: str | None = None) -> str:
|
||||
"""The address the server listens on: loopback for this computer only, the one address chosen for "One address only" (#5917),
|
||||
every address for the rest.
|
||||
|
||||
Cloudflare's tunnel connects from the same computer, so it too can stay on loopback."""
|
||||
if kind == "address" and listen:
|
||||
return listen
|
||||
return "127.0.0.1" if kind in ("local", "cloudflare") else "0.0.0.0"
|
||||
|
||||
|
||||
def local_addresses() -> list[str]:
|
||||
"""Every address of this computer a server can listen on for others: the private IPv4 ones first (the default route's first), then the
|
||||
other IPv4 and IPv6 ones (a VPN's included); never loopback or link-local (169.254.x.x, fe80::)."""
|
||||
found = list(lan_ips())
|
||||
try:
|
||||
import psutil
|
||||
for infos in psutil.net_if_addrs().values():
|
||||
for i in infos:
|
||||
if i.family in (socket.AF_INET, socket.AF_INET6):
|
||||
address = str(i.address).split("%", 1)[0]
|
||||
low = address.lower()
|
||||
if address.startswith(("127.", "169.254.", "0.")) or low in ("::1", "::") or low.startswith("fe80:"):
|
||||
continue
|
||||
found.append(address)
|
||||
except Exception: # noqa: BLE001
|
||||
pass
|
||||
return list(dict.fromkeys(found))
|
||||
|
||||
|
||||
def url_host(address: str) -> str:
|
||||
"""An address as it goes into a URL: an IPv6 one in brackets."""
|
||||
return f"[{address}]" if ":" in address and not address.startswith("[") else address
|
||||
|
||||
|
||||
def listen_problem(address: str | None) -> str | None:
|
||||
"""None when `address` is one of this computer's addresses now; else the plain line that stops the launch (#5917: never a silent
|
||||
fallback to every address)."""
|
||||
here = local_addresses()
|
||||
if address and address.split("%", 1)[0] in here:
|
||||
return None
|
||||
return (f"{address} is no longer an address of this computer. Its addresses now: {', '.join(here) or 'none'}. "
|
||||
"Choose one in the Access step.")
|
||||
|
||||
|
||||
def lan_ips() -> list[str]:
|
||||
"""This computer's private IPv4 addresses, the one used for the default route first."""
|
||||
found: list[str] = []
|
||||
@@ -239,10 +276,12 @@ class AccessOption:
|
||||
warn: bool = False
|
||||
|
||||
|
||||
def options(port: int, *, tunnel_url: str | None = None) -> list[AccessOption]:
|
||||
"""The four ways to share, with the address each would give and what is missing for it."""
|
||||
def options(port: int, *, tunnel_url: str | None = None, listen: str | None = None) -> list[AccessOption]:
|
||||
"""The five ways to share, with the address each would give and what is missing for it."""
|
||||
ips = lan_ips()
|
||||
lan = ips[0] if ips else None
|
||||
addresses = local_addresses()
|
||||
one = listen if listen in addresses else (addresses[0] if addresses else None)
|
||||
cf = find_cloudflared()
|
||||
ts = tailscale_status()
|
||||
out = [AccessOption("local", "This computer only", f"http://127.0.0.1:{port}",
|
||||
@@ -260,6 +299,9 @@ def options(port: int, *, tunnel_url: str | None = None) -> list[AccessOption]:
|
||||
out.append(AccessOption("tailscale", "Tailscale", f"http://<tailnet address>:{port}",
|
||||
"Tailscale is not connected" if ts["installed"] else
|
||||
"Tailscale is not installed", False, warn=True))
|
||||
out.append(AccessOption("address", "One address only", f"http://{url_host(one) if one else '<network address>'}:{port}",
|
||||
"listens on one network address of this computer (a second network card or a VPN)" if one else
|
||||
"no network address found on this computer", bool(one), warn=not one))
|
||||
return out
|
||||
|
||||
|
||||
@@ -277,13 +319,15 @@ def missing_helper(kind: str) -> str | None:
|
||||
return "Tailscale is not installed on this computer. " + install_help("tailscale")
|
||||
if not ts["running"]:
|
||||
return "Tailscale is installed but not connected. Run: tailscale up"
|
||||
if kind == "lan" and not lan_ips():
|
||||
if (kind == "lan" and not lan_ips()) or (kind == "address" and not local_addresses()):
|
||||
return "No local network address was found on this computer. Check that it is connected to your network."
|
||||
return None
|
||||
|
||||
|
||||
def urls_for(s: LaunchSettings, *, tunnel_url: str | None = None) -> list[str]:
|
||||
"""The addresses a client can use for these choices (the first is the main one)."""
|
||||
if s.access == "address" and s.listen: # the server listens on that address only: 127.0.0.1 would not answer
|
||||
return [f"http://{url_host(s.listen)}:{s.port}"]
|
||||
base = [f"http://127.0.0.1:{s.port}"]
|
||||
if s.access == "lan":
|
||||
base += [f"http://{ip}:{s.port}" for ip in lan_ips()[:1]]
|
||||
@@ -298,7 +342,7 @@ def urls_for(s: LaunchSettings, *, tunnel_url: str | None = None) -> list[str]:
|
||||
|
||||
def firewall_note(kind: str) -> str | None:
|
||||
"""Windows asks the first time a program listens for other computers: say so before it happens, in plain words."""
|
||||
if WINDOWS and kind in ("lan", "tailscale"):
|
||||
if WINDOWS and kind in ("lan", "address", "tailscale"):
|
||||
return ("Windows may ask whether to allow Strata (python.exe) on your network: choose Allow for private networks. "
|
||||
"If you choose Cancel, the model still works on this computer.")
|
||||
return None
|
||||
|
||||
@@ -125,8 +125,11 @@ def add_parsers(sp: argparse._SubParsersAction) -> list[argparse.ArgumentParser]
|
||||
"lscpu show). The default is one worker per physical core, which the engine's start line names; "
|
||||
"two entries on one core are kept with a warning")
|
||||
a = p.add_argument_group("who can use it")
|
||||
a.add_argument("--access", type=_choice("a way to share Strata", S.ACCESS_KINDS), metavar="local|lan|cloudflare|tailscale",
|
||||
help="local: this computer only; lan: your network; cloudflare: a quick tunnel; tailscale: your tailnet")
|
||||
a.add_argument("--access", type=_choice("a way to share Strata", S.ACCESS_KINDS), metavar="local|lan|address|cloudflare|tailscale",
|
||||
help="local: this computer only; lan: your network; address: one address of this computer (see --listen); "
|
||||
"cloudflare: a quick tunnel; tailscale: your tailnet")
|
||||
a.add_argument("--listen", metavar="ADDRESS",
|
||||
help="serve on this one address of this computer (a second network card or a VPN) instead of all of them")
|
||||
a.add_argument("--port", type=_port, metavar="N", help=f"port (default {S.DEFAULT_PORT})")
|
||||
a.add_argument("--api-key", metavar="KEY", help="the key clients must send (made for you when you share beyond this computer)")
|
||||
a.add_argument("--api-key-env", metavar="NAME", help="read the key from this environment variable")
|
||||
@@ -268,6 +271,12 @@ def settings_from_args(a: argparse.Namespace, catalog=None) -> tuple[S.LaunchSet
|
||||
s.tune_allow_small = True
|
||||
if a.access:
|
||||
s.access = a.access
|
||||
if getattr(a, "listen", None): # #5917: --listen ADDRESS is the "One address only" way to share
|
||||
s.access, s.listen = "address", a.listen.strip()
|
||||
elif s.access == "address" and not s.listen:
|
||||
from strata_cli.launch import access
|
||||
found = access.local_addresses()
|
||||
s.listen = found[0] if found else None
|
||||
if a.port:
|
||||
s.port = a.port
|
||||
if a.api_key:
|
||||
|
||||
@@ -472,7 +472,7 @@ def derive_config(base: dict, s: S.LaunchSettings, *, bool_flags: frozenset[str]
|
||||
launch values, then persisted overrides, then calibrated values, then Auto)."""
|
||||
from strata_control import arg_layers, tune_knobs
|
||||
cfg = json.loads(json.dumps(base))
|
||||
cfg["host"] = acc.host_for(s.access)
|
||||
cfg["host"] = acc.host_for(s.access, s.listen)
|
||||
cfg["port"] = int(s.port)
|
||||
if s.api_key:
|
||||
cfg["api_key"] = s.api_key
|
||||
@@ -1802,7 +1802,7 @@ class Runner:
|
||||
parallel = None # the slots Strata fills in by itself would keep the MTP: DFlash2 answers one request at a time
|
||||
if parallel and self.run_config_owns_slots(config):
|
||||
parallel = None # the all-cards split engine's run config carries its lanes (--batch N, from --parallel N or its default): a profile override would only collide with them
|
||||
sets = [f"host={acc.host_for(self.s.access)}", f"port={int(self.s.port)}"] + ([f"parallel={parallel}"] if parallel else [])
|
||||
sets = [f"host={acc.host_for(self.s.access, self.s.listen)}", f"port={int(self.s.port)}"] + ([f"parallel={parallel}"] if parallel else [])
|
||||
try:
|
||||
current, _rev = profiles.load(name)
|
||||
except profiles.ProfileError:
|
||||
@@ -2545,6 +2545,10 @@ class Runner:
|
||||
self.keep_saved_word() # a restart with no word keeps the saved one (it was written as null before)
|
||||
try:
|
||||
self.check_own_files() # a wrong --model-path is said before the engine is downloaded
|
||||
if start and self.s.access == "address": # #5917: an address that left this computer stops here, never a silent 0.0.0.0
|
||||
problem = acc.listen_problem(self.s.listen)
|
||||
if problem:
|
||||
raise LaunchError(problem, "", 2)
|
||||
if start:
|
||||
reused = self.check_serving() # before anything is downloaded or stopped
|
||||
if reused is not None:
|
||||
|
||||
@@ -1413,7 +1413,8 @@ class AccessScreen(Base):
|
||||
"for you (recommended); press t if you would rather have no key: it still starts, but anyone who can reach it can use it. "
|
||||
"To see the key later: strata launch --show-key. To use a key of your own: strata launch --api-key YOUR-KEY (or --api-key-env NAME).")
|
||||
|
||||
BINDINGS = Base.BINDINGS + [Binding("p", "port", show=False), Binding("k", "newkey", show=False), Binding("t", "keytoggle", show=False)]
|
||||
BINDINGS = Base.BINDINGS + [Binding("p", "port", show=False), Binding("k", "newkey", show=False), Binding("t", "keytoggle", show=False),
|
||||
Binding("n", "go_next", show=False)]
|
||||
|
||||
def body(self) -> ComposeResult:
|
||||
yield Static(Text("Who can use it?", style=f"bold {ACCENT}"), markup=False)
|
||||
@@ -1439,7 +1440,7 @@ class AccessScreen(Base):
|
||||
|
||||
def build(self) -> None:
|
||||
s = self.ctx.settings
|
||||
opts = acc.options(s.port)
|
||||
opts = acc.options(s.port, listen=s.listen)
|
||||
items = []
|
||||
sel = 0
|
||||
for i, o in enumerate(opts):
|
||||
@@ -1475,8 +1476,10 @@ class AccessScreen(Base):
|
||||
out.append(fw + "\n", style=WARN)
|
||||
if cur.key == "cloudflare":
|
||||
out.append("A Cloudflare quick tunnel gives a temporary public address; anyone with it can try to use the server, so an API key keeps others out.", style=MUTE)
|
||||
elif cur.key == "lan":
|
||||
elif cur.key in ("lan", "address"):
|
||||
out.append("Other computers on your network can use it at the address shown. An API key is recommended.", style=MUTE)
|
||||
if cur.key == "address" and len(acc.local_addresses()) > 1:
|
||||
out.append("\nEnter = next address n next", style=MUTE) # #5917
|
||||
elif cur.key == "tailscale":
|
||||
out.append("Only devices signed in to your Tailscale network can reach it.", style=MUTE)
|
||||
else:
|
||||
@@ -1487,6 +1490,9 @@ class AccessScreen(Base):
|
||||
kind = self.menu().current.key
|
||||
s = self.ctx.settings
|
||||
s.access = kind
|
||||
if kind == "address" and s.listen not in acc.local_addresses():
|
||||
found = acc.local_addresses()
|
||||
s.listen = found[0] if found else None
|
||||
if kind == "local" and self.drop_cursor_key():
|
||||
self.say("")
|
||||
elif kind != "local" and not s.api_key and not s.no_key:
|
||||
@@ -1531,6 +1537,18 @@ class AccessScreen(Base):
|
||||
self.paint()
|
||||
|
||||
def action_next(self) -> None:
|
||||
if self.input_open():
|
||||
return
|
||||
s = self.ctx.settings
|
||||
found = acc.local_addresses() if self.menu().current.key == "address" else []
|
||||
if len(found) > 1: # #5917: Enter on "One address only" goes to the next address; n goes on
|
||||
s.listen = found[(found.index(s.listen) + 1) % len(found)] if s.listen in found else found[0]
|
||||
self.build()
|
||||
self.paint()
|
||||
return
|
||||
self.action_go_next()
|
||||
|
||||
def action_go_next(self) -> None:
|
||||
if self.input_open():
|
||||
return
|
||||
self.commit()
|
||||
@@ -1539,6 +1557,9 @@ class AccessScreen(Base):
|
||||
def commit(self) -> None:
|
||||
s = self.ctx.settings
|
||||
s.access = self.menu().current.key
|
||||
if s.access == "address" and not s.listen:
|
||||
found = acc.local_addresses()
|
||||
s.listen = found[0] if found else None
|
||||
if s.access == "local":
|
||||
self.drop_cursor_key()
|
||||
elif not s.api_key and not s.no_key:
|
||||
|
||||
@@ -20,8 +20,8 @@ SCHEMA = "strata.launch/1"
|
||||
#: setup.py's CONTEXTS (kept here only as the fallback when the installer files are not next to this terminal).
|
||||
FALLBACK_CONTEXTS = (8192, 32768, 65536, 131072, 204800, 262144, 393216, 524288)
|
||||
|
||||
ACCESS_KINDS = ("local", "lan", "cloudflare", "tailscale")
|
||||
ACCESS_WORDS = {"local": "This computer only", "lan": "My local network", "cloudflare": "Cloudflare tunnel",
|
||||
ACCESS_KINDS = ("local", "lan", "address", "cloudflare", "tailscale")
|
||||
ACCESS_WORDS = {"local": "This computer only", "lan": "My local network", "address": "One address only", "cloudflare": "Cloudflare tunnel",
|
||||
"tailscale": "Tailscale"}
|
||||
TUNE_MODES = ("quick", "thorough", "skip")
|
||||
VISION_MODES = ("off", "on", "gpu", "cpu")
|
||||
@@ -99,6 +99,7 @@ class LaunchSettings:
|
||||
tune: str = "skip" # quick | thorough | skip
|
||||
tune_allow_small: bool = False # the "answer-changing" tick, off by default, as in the app
|
||||
access: str = "local"
|
||||
listen: str | None = None # access "address" (#5917): the one address of this computer the server listens on
|
||||
port: int = DEFAULT_PORT
|
||||
api_key: str | None = None # never shown whole; stored only in the private preset file
|
||||
no_key: bool = False # served beyond this computer without a key, on purpose (--no-api-key); a warning, never a refusal
|
||||
@@ -313,7 +314,7 @@ def flags_text(s: LaunchSettings, *, preset: str | None = None) -> str:
|
||||
parts.append(f"--tune {s.tune}")
|
||||
if s.tune_allow_small:
|
||||
parts.append("--tune-allow-small")
|
||||
parts.append(f"--access {s.access}")
|
||||
parts.append(f"--listen {s.listen}" if s.access == "address" and s.listen else f"--access {s.access}")
|
||||
parts.append(f"--port {s.port}")
|
||||
if s.gpu_roles:
|
||||
parts.append("--gpu-roles " + ",".join(f"{k}={v}" for k, v in sorted(s.gpu_roles.items(), key=lambda kv: int(kv[0]))))
|
||||
|
||||
@@ -0,0 +1,106 @@
|
||||
"""#5917: "One address only" - the server listens on one address of this computer (a second network card, a VPN), chosen in the Access step
|
||||
or with `strata launch --listen ADDRESS`. Its URL is that address (127.0.0.1 would not answer), a key is on as for the local network, and an
|
||||
address that is no longer on this computer stops the launch with a plain line instead of falling back to every address."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import socket
|
||||
import unittest
|
||||
from types import SimpleNamespace
|
||||
from unittest import mock
|
||||
|
||||
from strata_cli.launch import access as acc
|
||||
from strata_cli.launch import settings as S
|
||||
from tests.terminal.test_launch_tui import Base, press, text_of
|
||||
|
||||
HERE = ["192.168.1.100", "192.168.2.100", "10.8.0.2"]
|
||||
|
||||
|
||||
def nic(address, family=socket.AF_INET):
|
||||
return SimpleNamespace(family=family, address=address)
|
||||
|
||||
|
||||
class Addresses(unittest.TestCase):
|
||||
def test_every_usable_address_and_no_loopback_or_link_local(self):
|
||||
fake = {"eth0": [nic("192.168.1.100"), nic("fe80::1%eth0", socket.AF_INET6), nic("2001:db8::5", socket.AF_INET6)],
|
||||
"lo": [nic("127.0.0.1"), nic("::1", socket.AF_INET6)], "wg0": [nic("10.8.0.2")], "x": [nic("169.254.3.4")]}
|
||||
with mock.patch.object(acc, "lan_ips", return_value=["192.168.1.100", "10.8.0.2"]), \
|
||||
mock.patch("psutil.net_if_addrs", return_value=fake):
|
||||
self.assertEqual(acc.local_addresses(), ["192.168.1.100", "10.8.0.2", "2001:db8::5"])
|
||||
|
||||
def test_the_host_and_the_url_are_that_address(self):
|
||||
self.assertEqual(acc.host_for("address", "192.168.2.100"), "192.168.2.100")
|
||||
self.assertEqual((acc.host_for("lan"), acc.host_for("local"), acc.host_for("cloudflare")), ("0.0.0.0", "127.0.0.1", "127.0.0.1"))
|
||||
s = S.LaunchSettings(access="address", listen="192.168.2.100", port=8080)
|
||||
self.assertEqual(acc.urls_for(s), ["http://192.168.2.100:8080"])
|
||||
self.assertEqual(acc.urls_for(s.copy(listen="2001:db8::5")), ["http://[2001:db8::5]:8080"])
|
||||
self.assertIn("--listen 192.168.2.100", S.flags_text(s))
|
||||
|
||||
def test_an_address_that_left_is_refused_in_plain_words(self):
|
||||
with mock.patch.object(acc, "local_addresses", return_value=HERE):
|
||||
self.assertIsNone(acc.listen_problem("10.8.0.2"))
|
||||
self.assertEqual(acc.listen_problem("192.168.9.9"),
|
||||
"192.168.9.9 is no longer an address of this computer. Its addresses now: 192.168.1.100, 192.168.2.100, "
|
||||
"10.8.0.2. Choose one in the Access step.")
|
||||
|
||||
def test_the_launch_stops_before_anything_is_done(self):
|
||||
from strata_cli.launch.runner import LaunchError, Runner
|
||||
from tests.terminal.launch_support import HW_12, Home, catalog
|
||||
with Home(), mock.patch.object(acc, "local_addresses", return_value=HERE):
|
||||
r = Runner(S.LaunchSettings(family="qwen", model="Q2_0", context=32768, access="address", listen="192.168.9.9"),
|
||||
catalog=catalog(HW_12), emit=lambda e: None)
|
||||
with mock.patch.object(Runner, "ensure_engine", side_effect=AssertionError("must not get here")), \
|
||||
self.assertRaises(LaunchError) as caught:
|
||||
r.run(start=True)
|
||||
self.assertIn("is no longer an address of this computer", caught.exception.text)
|
||||
self.assertEqual(caught.exception.code, 2)
|
||||
|
||||
|
||||
class ListenFlag(unittest.TestCase):
|
||||
def parse(self, *argv):
|
||||
from strata_cli.launch import cmd
|
||||
ap = argparse.ArgumentParser()
|
||||
cmd.add_parsers(ap.add_subparsers(dest="command"))
|
||||
return ap.parse_args(["launch", *argv])
|
||||
|
||||
def test_listen_is_the_one_address_way(self):
|
||||
from strata_cli.launch import cmd
|
||||
from tests.terminal.launch_support import HW_12, Home, catalog
|
||||
with Home():
|
||||
s, _ = cmd.settings_from_args(self.parse("--model", "Q2_0", "--listen", "10.8.0.2"), catalog=catalog(HW_12))
|
||||
self.assertEqual((s.access, s.listen), ("address", "10.8.0.2"))
|
||||
|
||||
def test_access_address_alone_takes_this_computers_first_address(self):
|
||||
from strata_cli.launch import cmd
|
||||
from tests.terminal.launch_support import HW_12, Home, catalog
|
||||
with Home(), mock.patch.object(acc, "local_addresses", return_value=HERE):
|
||||
s, _ = cmd.settings_from_args(self.parse("--model", "Q2_0", "--access", "address"), catalog=catalog(HW_12))
|
||||
self.assertEqual((s.access, s.listen), ("address", "192.168.1.100"))
|
||||
|
||||
|
||||
class AccessStepRow(Base):
|
||||
def test_enter_goes_through_the_addresses_and_n_goes_on(self):
|
||||
async def case(app, pilot, ctx):
|
||||
with mock.patch.object(acc, "local_addresses", return_value=HERE):
|
||||
await press(pilot, *(("enter",) * 7 + ("n",)))
|
||||
self.assertEqual(app.current, "access")
|
||||
app.screen.menu().select("address")
|
||||
app.screen.on_cursor()
|
||||
app.screen.build()
|
||||
app.screen.paint()
|
||||
await press(pilot)
|
||||
self.assertEqual((ctx.settings.access, ctx.settings.listen), ("address", "192.168.1.100"))
|
||||
self.assertIn("One address only", text_of(app))
|
||||
await press(pilot, "enter")
|
||||
self.assertEqual(ctx.settings.listen, "192.168.2.100")
|
||||
self.assertIn("http://192.168.2.100:", text_of(app))
|
||||
self.assertEqual(app.current, "access")
|
||||
await press(pilot, "n")
|
||||
self.assertEqual(app.current, "save")
|
||||
self.assertTrue(ctx.settings.api_key) # beyond this computer: a key, as for the local network
|
||||
self.run_app(case)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
Reference in new issue
Block a user