feat: add restart/toggle actions

This commit is contained in:
FUFSoB committed 2026-09-23 23:52:13 +05:00
1 parent 5f29f30790
commit 11c44deb61
5 files changed
+112 -22

No files matched your search

+2 -1
View File
@@ -128,6 +128,7 @@ See the [options reference](./docs/options/index.md), one page per option group.
```text
Usage: proxy-ctl <group> [verb] [args]
A group without a verb shows its status or list.
Every group with on|off also takes toggle (on if stopped, off if running) and restart.
Secrets and changes need root, or the userControl group.
status [--json] services and routing mode (--tray: deprecated key=value lines)
@@ -182,7 +183,7 @@ Secrets and changes need root, or the userControl group.
zapret cutoff probe probe this line again now
awg [list] AmneziaWG profiles and their state
awg on <profile> | off [profile] | restart [profile]
awg on <profile> | off [profile] | toggle [profile] | restart [profile]
killswitch [status|on|off] reject traffic outside the global tunnel; up with
TUN, TProxy or AWG, lifted only by off here or on them
+39 -10
View File
@@ -50,6 +50,7 @@ RESTART_SERVICES = [
HELP = """\
Usage: proxy-ctl <group> [verb] [args]
A group without a verb shows its status or list.
Every group with on|off also takes toggle (on if stopped, off if running) and restart.
Secrets and changes need root, or the userControl group.
status [--json] services and routing mode (--tray: deprecated key=value lines)
@@ -104,7 +105,7 @@ Secrets and changes need root, or the userControl group.
zapret cutoff probe probe this line again now
awg [list] AmneziaWG profiles and their state
awg on <profile> | off [profile] | restart [profile]
awg on <profile> | off [profile] | toggle [profile] | restart [profile]
killswitch [status|on|off] reject traffic outside the global tunnel; up with
TUN, TProxy or AWG, lifted only by off here or on them
@@ -317,17 +318,27 @@ def _bool(value):
return "true" if value else "false"
def _flip(unit, verb="status"):
"""toggle as on or off, for the state unit is in now; any other verb as it is."""
if verb == "toggle":
return "off" if svc_active(unit) else "on"
return verb
def _toggle(unit, name, verb="status", *_):
if not svc_exists(unit):
die(f"{name} is not enabled in this configuration.")
verb = _flip(unit, verb)
if verb == "status":
systemctl("is-active", unit)
elif verb == "on":
must("start", unit)
elif verb == "off":
must("stop", unit)
elif verb == "restart":
must("restart", unit)
else:
usage(f"{name} [status|on|off]")
usage(f"{name} [status|on|off|toggle|restart]")
def _warp_unit():
@@ -396,8 +407,8 @@ def cmd_tor(verb="status", *args):
_tor_control("SIGNAL NEWNYM")
print("New connections take new circuits (Tor allows this once every 10 seconds).")
return
if verb not in ("status", "on", "off"):
usage("tor [status|on|off|newnym]")
if verb not in ("status", "on", "off", "toggle", "restart"):
usage("tor [status|on|off|toggle|restart|newnym]")
_toggle(unit, "tor", verb, *args)
if verb == "status" and svc_active(unit):
# Extra detail: the unit's state stands without it, for a user outside the group
@@ -437,7 +448,13 @@ def _awg_profiles():
# its words and args until a positional is typed (always, when it repeats), and
# its flags until each is typed.
TOGGLE = {"status": "is it running", "on": "start it", "off": "stop it"}
TOGGLE = {
"status": "is it running",
"on": "start it",
"off": "stop it",
"toggle": "start it if stopped, stop it if running",
"restart": "stop it and start it again",
}
def _outbound_choices():
@@ -588,11 +605,13 @@ COMPLETE = {
"list": "profiles and their state",
"on": "start a profile",
"off": "stop a profile",
"toggle": "start a profile if stopped, stop it if running",
"restart": "restart a profile",
}
},
"awg on": {"args": lambda: _names(_awg_profiles())},
"awg off": {"args": lambda: _names(_awg_profiles())},
"awg toggle": {"args": lambda: _names(_awg_profiles())},
"awg restart": {"args": lambda: _names(_awg_profiles())},
"ssh": {"words": TOGGLE},
"warp": {"words": TOGGLE},
@@ -914,7 +933,8 @@ def cmd_restart(*_):
def cmd_proxy(verb="status", *args):
if verb in ("status", "on"):
verb = _flip("proxy-suite-socks", verb)
if verb in ("status", "on", "restart"):
_toggle("proxy-suite-socks", "proxy", verb)
elif verb == "off":
if not svc_exists("proxy-suite-socks"):
@@ -938,16 +958,17 @@ def cmd_proxy(verb="status", *args):
elif verb == "rulesets":
cmd_rulesets(*args)
elif verb in ("tun", "tproxy"):
_toggle(f"proxy-suite-{verb}", f"proxy {verb}", *args)
action = _flip(f"proxy-suite-{verb}", *args[:1])
_toggle(f"proxy-suite-{verb}", f"proxy {verb}", action)
# A mode stopped on purpose lifts the kill switch; one that fails leaves it up.
if args[:1] == ("off",) and svc_exists(KILL_SWITCH):
if action == "off" and svc_exists(KILL_SWITCH):
systemctl("stop", KILL_SWITCH)
elif verb == "auto":
cmd_proxy_auto(*args)
elif verb in ("probe", "learn", "forget", "relearn", "queue", "learned"):
cmd_proxy_auto(verb, *args)
else:
usage("proxy [status|on|off|outbounds|pin|unpin|mode|subs|rulesets|tun|tproxy|auto|config]")
usage("proxy [status|on|off|toggle|restart|outbounds|pin|unpin|mode|subs|rulesets|tun|tproxy|auto|config]")
def cmd_outbounds(verb="list", *args):
@@ -2787,6 +2808,14 @@ def cmd_awg(verb="list", *args):
profiles = _awg_profiles()
if args and args[0] not in profiles:
die(f"Unknown AmneziaWG profile: {args[0]}")
if verb == "toggle":
# Without a profile there is only something to stop: which one to start is not known.
if args:
verb = _flip(_awg_service(args[0]), verb)
elif _active_awg_profiles():
verb = "off"
else:
usage("awg toggle <profile>")
if verb in ("list", "status"):
if not profiles:
print("No AmneziaWG profiles configured.")
@@ -2808,7 +2837,7 @@ def cmd_awg(verb="list", *args):
if verb == "off" and svc_exists(KILL_SWITCH):
systemctl("stop", KILL_SWITCH)
else:
usage("awg [list] | on <profile> | off [profile] | restart [profile]")
usage("awg [list] | on <profile> | off [profile] | toggle [profile] | restart [profile]")
# --- apps ---------------------------------------------------------------------
+17 -9
View File
@@ -153,13 +153,24 @@ def _awg_profile(row):
return name if row["unit"].startswith(AWG_PREFIX) and name in ctl._awg_profiles() else ""
def toggle_argv(row, *_):
verb = "off" if row["state"] == "active" else "on"
def _unit_argv(row, verb):
if profile := _awg_profile(row):
return ["awg", verb, profile]
return [*TOGGLES[row["unit"]], verb]
def toggle_argv(row, *_):
return _unit_argv(row, "off" if row["state"] == "active" else "on")
def restart_argv(row, *_):
return _unit_argv(row, "restart")
def _controllable(row):
return row["unit"] in TOGGLES or bool(_awg_profile(row))
def service_rows(states):
return [
{"key": u, "unit": u, "name": u.removeprefix("proxy-suite-"), "state": s}
@@ -415,17 +426,13 @@ TABS = [
"space",
"start / stop",
toggle_argv,
when=lambda r: r["unit"] in TOGGLES or bool(_awg_profile(r)),
when=_controllable,
# proxy off takes tun and tproxy down with it.
confirm=lambda r: r["unit"] == "proxy-suite-socks" and r["state"] == "active",
),
Action("l", "follow its logs", lambda r, *_: ["logs", r["unit"]], when=ROW, mode="suspend"),
Action(
"ctrl+r",
"restart it",
lambda r, *_: ["awg", "restart", _awg_profile(r)],
when=lambda r: bool(_awg_profile(r)) and r["state"] == "active",
),
# A failed unit restarts too: that is how it gets another try.
Action("ctrl+r", "restart it", restart_argv, when=lambda r: _controllable(r) and r["state"] in ("active", "failed")),
Action("R", "restart everything running", lambda r, *_: ["restart"], confirm=True),
],
),
@@ -554,6 +561,7 @@ TABS = [
Action("C", "forget all learned hosts", lambda r, *_: ["zapret", "auto", "clear"], confirm=True),
Action("P", "probe the line's cutoff again", lambda r, *_: ["zapret", "cutoff", "probe"], mode="dialog"),
Action("z", "start / stop zapret", _zapret_toggle),
Action("Z", "restart zapret", lambda *_: ["zapret", "restart"]),
],
),
Tab(
+41
View File
@@ -351,6 +351,47 @@ class ServiceManagerTest(EnvTest):
ctl.COMMANDS["killswitch"]("off")
self.assertEqual(stops(), [ctl.KILL_SWITCH])
def test_toggle_and_restart(self):
seen = self.calls()
active = set()
self.patch("svc_active", lambda unit: unit in active)
verbs = lambda: [argv[1:3] for argv in seen if argv[1] in ("start", "stop", "restart")]
ctl.COMMANDS["ssh"]("toggle")
active.add("proxy-suite-ssh-proxy")
ctl.COMMANDS["ssh"]("toggle")
ctl.COMMANDS["ssh"]("restart")
self.assertEqual(verbs(), [["start", "proxy-suite-ssh-proxy"], ["stop", "proxy-suite-ssh-proxy"], ["restart", "proxy-suite-ssh-proxy"]])
# Toggled off, a mode lifts the kill switch as off does; proxy toggled off takes the modes down.
seen.clear()
active.update(["proxy-suite-tun", "proxy-suite-socks"])
ctl.cmd_proxy("tun", "toggle")
ctl.cmd_proxy("toggle")
self.assertEqual(
verbs(),
[["stop", "proxy-suite-tun"], ["stop", ctl.KILL_SWITCH], ["stop", "proxy-suite-tproxy"], ["stop", "proxy-suite-tun"], ["stop", ctl.KILL_SWITCH], ["stop", "proxy-suite-socks"]],
)
seen.clear()
ctl.cmd_proxy("restart")
ctl.cmd_proxy("tproxy", "restart")
ctl.cmd_zapret("restart")
ctl.cmd_tor("restart")
self.assertEqual(verbs(), [["restart", u] for u in ("proxy-suite-socks", "proxy-suite-tproxy", "proxy-suite-zapret", "proxy-suite-tor")])
# awg toggle: a named profile flips; without one, only stopping is possible.
seen.clear()
self.patch("_awg_profiles", lambda: ["p", "q"])
ctl.cmd_awg("toggle", "p")
active.add(ctl._awg_service("q"))
ctl.cmd_awg("toggle")
self.assertEqual(verbs(), [["start", ctl._awg_service("p")], ["stop", ctl._awg_service("q")], ["stop", ctl.KILL_SWITCH]])
active.clear()
with self.assertRaises(SystemExit), contextlib.redirect_stderr(io.StringIO()):
ctl.cmd_awg("toggle")
def test_toggle_completes(self):
for path in ("ssh", "zapret", "proxy", "proxy tun", "tor"):
self.assertLessEqual({"toggle", "restart"}, set(ctl._complete_tree(*path.split())))
self.assertIn("toggle", ctl._complete_tree("awg"))
def test_rulesets_list(self):
self.calls()
with tempfile.TemporaryDirectory() as tmp:
+13 -2
View File
@@ -74,10 +74,21 @@ class ModelTest(unittest.TestCase):
row = model.service_rows({"proxy-suite-awg-warp": "inactive"})[0]
keys = lambda: [a.key for a in model.applicable(tab, {**row, "state": "active"})]
self.assertEqual(model.toggle_argv(row), ["warp", "on"]) # an outbound profile: `awg` does not know it
self.assertNotIn("ctrl+r", keys())
self.assertEqual(model.restart_argv(row), ["warp", "restart"])
self.assertIn("ctrl+r", keys())
self.assertNotIn("ctrl+r", [a.key for a in model.applicable(tab, row)]) # nothing to restart while stopped
with mock.patch.object(ctl, "_awg_profiles", lambda: ["warp"]):
self.assertEqual(model.toggle_argv(row), ["awg", "on", "warp"]) # a global profile named warp
self.assertIn("ctrl+r", keys())
self.assertEqual(model.restart_argv(row), ["awg", "restart", "warp"])
def test_every_toggle_restarts(self):
tab = model.TABS[0]
restart = next(a for a in tab.actions if a.key == "ctrl+r")
for unit, group in model.TOGGLES.items():
for state in ("active", "failed"):
row = {"key": unit, "unit": unit, "name": unit, "state": state}
self.assertIn(restart, model.applicable(tab, row))
self.assertEqual(restart.argv(row), [*group, "restart"])
def test_inbound_amneziawg_actions(self):
tab = next(t for t in model.TABS if t.id == "inbounds")