refactor: remove duplication
This commit is contained in:
109 files changed
+2206
-3078
No files matched your search
+22
-27
@@ -162,6 +162,21 @@ def read_json(path):
|
||||
return json.load(f)
|
||||
|
||||
|
||||
def require_enabled(variable, feature):
|
||||
"""Refuses when the module did not build this feature in."""
|
||||
if env(variable) != "1":
|
||||
die(f"{feature} is not enabled in this configuration.")
|
||||
|
||||
|
||||
def read_json_or(path, fallback):
|
||||
"""The JSON at path, or fallback when it is missing, unreadable or not JSON."""
|
||||
try:
|
||||
value = read_json(path)
|
||||
except (OSError, ValueError):
|
||||
return fallback
|
||||
return value if isinstance(value, type(fallback)) else fallback
|
||||
|
||||
|
||||
def read_text(path):
|
||||
with open(path, encoding="utf-8", errors="replace") as f:
|
||||
return f.read()
|
||||
@@ -396,10 +411,7 @@ def _emit(text, qr):
|
||||
|
||||
|
||||
def _json_list(path):
|
||||
try:
|
||||
return [_s(x) for x in read_json(path)]
|
||||
except (OSError, ValueError, TypeError):
|
||||
return []
|
||||
return [_s(x) for x in read_json_or(path, [])]
|
||||
|
||||
|
||||
def _sub_tags():
|
||||
@@ -948,14 +960,7 @@ def _outbound_inventory():
|
||||
|
||||
Empty until the proxy has started once.
|
||||
"""
|
||||
path = env("OUTBOUND_INVENTORY_FILE")
|
||||
if not readable(path):
|
||||
return {}
|
||||
try:
|
||||
inventory = read_json(path)
|
||||
except (OSError, ValueError):
|
||||
return {}
|
||||
return inventory if isinstance(inventory, dict) else {}
|
||||
return read_json_or(env("OUTBOUND_INVENTORY_FILE"), {})
|
||||
|
||||
|
||||
def _outbound_tags():
|
||||
@@ -2032,10 +2037,7 @@ def cmd_proxy_probe(*args):
|
||||
|
||||
def _backend_tags():
|
||||
"""User outbound tag -> the backend's tag, which probe exits and their reputation are keyed by."""
|
||||
try:
|
||||
return read_json(_runtime_file("outbound-test.json")).get("outbounds") or {}
|
||||
except (OSError, ValueError, AttributeError):
|
||||
return {}
|
||||
return read_json_or(_runtime_file("outbound-test.json"), {}).get("outbounds") or {}
|
||||
|
||||
|
||||
def _backend_tag(tag, backend=None):
|
||||
@@ -2061,8 +2063,7 @@ def _autoproxy_dir():
|
||||
|
||||
|
||||
def _require_autoproxy():
|
||||
if env("AUTOPROXY_ENABLED") != "1":
|
||||
die("proxy.autoProxy is not enabled in this configuration.")
|
||||
require_enabled("AUTOPROXY_ENABLED", "proxy.autoProxy")
|
||||
|
||||
|
||||
def _autoproxy_unreadable(path):
|
||||
@@ -2089,11 +2090,7 @@ def _require_autoproxy_readable(path):
|
||||
|
||||
|
||||
def _autoproxy_state(path):
|
||||
try:
|
||||
state = read_json(os.path.join(path, "state.json"))
|
||||
except (OSError, ValueError):
|
||||
return {}
|
||||
return state if isinstance(state, dict) else {}
|
||||
return read_json_or(os.path.join(path, "state.json"), {})
|
||||
|
||||
|
||||
def cmd_proxy_auto(verb="list", *args):
|
||||
@@ -2729,8 +2726,7 @@ def _per_app_profiles():
|
||||
|
||||
|
||||
def _ensure_app_routing():
|
||||
if env("PER_APP_ROUTING_ENABLED") != "1":
|
||||
die("perAppRouting is not enabled in this configuration.")
|
||||
require_enabled("PER_APP_ROUTING_ENABLED", "perAppRouting")
|
||||
|
||||
|
||||
def _check_no_global_proxy(route):
|
||||
@@ -3081,8 +3077,7 @@ def _inbound_subscriptions(*args):
|
||||
|
||||
|
||||
def cmd_inbounds(verb="list", *args):
|
||||
if env("INBOUNDS_ENABLED") != "1":
|
||||
die("inbounds is not enabled in this configuration.")
|
||||
require_enabled("INBOUNDS_ENABLED", "inbounds")
|
||||
if verb == "list":
|
||||
state = svc_state("proxy-suite-inbounds")
|
||||
row = " {:<24} {:<16} {:<14} {:<8} {}"
|
||||
|
||||
@@ -188,38 +188,45 @@ class Unit:
|
||||
self.done.notify_all()
|
||||
|
||||
|
||||
class Timer:
|
||||
class Activator:
|
||||
"""A .timer or .path unit: it is active or not, and it starts one service."""
|
||||
|
||||
section = ""
|
||||
suffix = ""
|
||||
|
||||
def __init__(self, name, definition):
|
||||
self.name = name
|
||||
self.definition = definition
|
||||
self.active = False
|
||||
|
||||
@property
|
||||
def config(self):
|
||||
return self.definition.get(self.section) or {}
|
||||
|
||||
def target(self):
|
||||
return self.config.get("Unit") or self.name.replace(self.suffix, ".service")
|
||||
|
||||
|
||||
class Timer(Activator):
|
||||
section = "Timer"
|
||||
suffix = ".timer"
|
||||
|
||||
def __init__(self, name, definition):
|
||||
super().__init__(name, definition)
|
||||
self.activated = None
|
||||
self.fired = set()
|
||||
self.last = None
|
||||
self.jitter = 0.0
|
||||
|
||||
@property
|
||||
def config(self):
|
||||
return self.definition.get("Timer") or {}
|
||||
|
||||
def target(self):
|
||||
return (self.definition.get("Timer") or {}).get("Unit") or self.name.replace(".timer", ".service")
|
||||
class PathWatch(Activator):
|
||||
section = "Path"
|
||||
suffix = ".path"
|
||||
|
||||
|
||||
class PathWatch:
|
||||
def __init__(self, name, definition):
|
||||
self.name = name
|
||||
self.definition = definition
|
||||
self.active = False
|
||||
super().__init__(name, definition)
|
||||
self.seen = {}
|
||||
|
||||
@property
|
||||
def config(self):
|
||||
return self.definition.get("Path") or {}
|
||||
|
||||
def target(self):
|
||||
return self.config.get("Unit") or self.name.replace(".path", ".service")
|
||||
|
||||
|
||||
def signature(path):
|
||||
try:
|
||||
@@ -570,24 +577,34 @@ class Supervisor:
|
||||
|
||||
# timers and paths
|
||||
|
||||
def start_timer(self, name):
|
||||
name = full_name(name, "timer")
|
||||
def _activator(self, registry, kind, cls, name):
|
||||
"""The unit's Timer/PathWatch, made or replaced when its definition changed."""
|
||||
name = full_name(name, kind)
|
||||
definition = self.definition(name)
|
||||
if definition is None:
|
||||
return 5
|
||||
return None
|
||||
current = registry.get(name)
|
||||
if current is None or current.definition is not definition:
|
||||
current = registry[name] = cls(name, definition)
|
||||
return current
|
||||
|
||||
def start_timer(self, name):
|
||||
with self.guard:
|
||||
timer = self.timers.get(name)
|
||||
if timer is None or timer.definition is not definition:
|
||||
timer = self.timers[name] = Timer(name, definition)
|
||||
timer = self._activator(self.timers, "timer", Timer, name)
|
||||
if timer is None:
|
||||
return 5
|
||||
if not timer.active:
|
||||
timer.active, timer.activated, timer.fired = True, time.time(), set()
|
||||
timer.jitter = self.jitter(timer)
|
||||
return 0
|
||||
|
||||
def stop_timer(self, name):
|
||||
timer = self.timers.get(full_name(name, "timer"))
|
||||
if timer:
|
||||
timer.active = False
|
||||
return self._stop_activator(self.timers, "timer", name)
|
||||
|
||||
def _stop_activator(self, registry, kind, name):
|
||||
unit = registry.get(full_name(name, kind))
|
||||
if unit:
|
||||
unit.active = False
|
||||
return 0
|
||||
|
||||
@staticmethod
|
||||
@@ -611,24 +628,17 @@ class Supervisor:
|
||||
return at + timer.jitter, {base for base, when in candidates if when <= at}
|
||||
|
||||
def start_path(self, name):
|
||||
name = full_name(name, "path")
|
||||
definition = self.definition(name)
|
||||
if definition is None:
|
||||
return 5
|
||||
with self.guard:
|
||||
watch = self.paths.get(name)
|
||||
if watch is None or watch.definition is not definition:
|
||||
watch = self.paths[name] = PathWatch(name, definition)
|
||||
watch = self._activator(self.paths, "path", PathWatch, name)
|
||||
if watch is None:
|
||||
return 5
|
||||
if not watch.active:
|
||||
watch.active = True
|
||||
watch.seen = {p: signature(p) for key in ("PathChanged", "PathModified") for p in as_list(watch.config.get(key))}
|
||||
return 0
|
||||
|
||||
def stop_path(self, name):
|
||||
watch = self.paths.get(full_name(name, "path"))
|
||||
if watch:
|
||||
watch.active = False
|
||||
return 0
|
||||
return self._stop_activator(self.paths, "path", name)
|
||||
|
||||
def in_background(self, fn, *args):
|
||||
threading.Thread(target=fn, args=args, daemon=True).start()
|
||||
|
||||
@@ -81,6 +81,10 @@ class SupervisorTest(unittest.TestCase):
|
||||
"Unit": {"Description": "timer job"},
|
||||
"Service": {"Type": "oneshot", "ExecStart": sh(f"echo tick >> {out}/ticks")},
|
||||
},
|
||||
"proxy-suite-watched": {
|
||||
"Unit": {"Description": "path job"},
|
||||
"Service": {"Type": "oneshot", "ExecStart": sh(f"echo changed >> {out}/watched")},
|
||||
},
|
||||
"proxy-suite-pin@": {
|
||||
"Unit": {"Description": "template"},
|
||||
"Service": {"Type": "oneshot", "ExecStart": sh(f"echo '%I' >> {out}/pins")},
|
||||
@@ -93,7 +97,13 @@ class SupervisorTest(unittest.TestCase):
|
||||
"Install": {"WantedBy": ["timers.target"]},
|
||||
},
|
||||
},
|
||||
"paths": {},
|
||||
"paths": {
|
||||
"proxy-suite-watched": {
|
||||
"Unit": {"Description": "watch a file"},
|
||||
"Path": {"PathChanged": [os.path.join(self.tmp, "trigger")]},
|
||||
"Install": {"WantedBy": ["paths.target"]},
|
||||
},
|
||||
},
|
||||
"tmpfiles": [f"d {self.run_dir} 0700 - - -"],
|
||||
}
|
||||
with open(self.manifest + ".tmp", "w") as f:
|
||||
@@ -168,5 +178,25 @@ class SupervisorTest(unittest.TestCase):
|
||||
self.assertEqual(self.read("once"), ["ran"])
|
||||
|
||||
|
||||
def test_path_unit_starts_its_service_when_the_file_changes(self):
|
||||
trigger = os.path.join(self.tmp, "trigger")
|
||||
# boot brings up the .path unit with the rest of paths.target.
|
||||
self.assertEqual(self.ctl("boot")[0], 0)
|
||||
# A .path unit is active itself, and quiet until the file it watches appears.
|
||||
self.assertEqual(self.ctl("is-active", "--quiet", "proxy-suite-watched.path")[0], 0)
|
||||
self.assertEqual(self.read("watched"), [])
|
||||
|
||||
with open(trigger, "w") as f:
|
||||
f.write("one")
|
||||
wait_for(lambda: self.read("watched") == ["changed"])
|
||||
|
||||
# Stopped, further changes are ignored.
|
||||
self.assertEqual(self.ctl("stop", "proxy-suite-watched.path")[0], 0)
|
||||
with open(trigger, "w") as f:
|
||||
f.write("two")
|
||||
time.sleep(1)
|
||||
self.assertEqual(self.read("watched"), ["changed"])
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
Reference in new issue
Block a user