-
Notifications
You must be signed in to change notification settings - Fork 25
Expand file tree
/
Copy pathdiscovery.py
More file actions
310 lines (259 loc) · 10.5 KB
/
Copy pathdiscovery.py
File metadata and controls
310 lines (259 loc) · 10.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
"""
Zero-config service discovery for Chronicle on Tailscale networks.
Thin wrapper around minidisc-python. Services advertise themselves on the
Tailnet; consumers discover them automatically. Every function is safe to call
even when Tailscale or minidisc is unavailable — they return None gracefully.
Resolution priority (used by resolve_service_url):
1. Explicit environment variable (manual override always wins)
2. Minidisc discovery (automatic if Tailscale available)
3. Default value / disabled
"""
import importlib.util
import logging
import os
import stat
import threading
import time
from typing import Optional
logger = logging.getLogger(__name__)
# ── Service name constants ──────────────────────────────────────────────
CHRONICLE_BACKEND = "chronicle-backend"
CHRONICLE_SPEAKER = "chronicle-speaker"
CHRONICLE_ASR = "chronicle-asr"
CHRONICLE_LLM = "chronicle-llm"
CHRONICLE_TTS = "chronicle-tts"
CHRONICLE_RELAY = "chronicle-relay"
_TAILSCALE_SOCKET = "/var/run/tailscale/tailscaled.sock"
def is_tailscale_available() -> bool:
"""Check whether the Tailscale daemon socket exists on this machine.
Uses stat to verify the path is actually a Unix socket, not just a
directory (Docker creates empty dirs for missing bind-mount sources).
"""
try:
return stat.S_ISSOCK(os.stat(_TAILSCALE_SOCKET).st_mode)
except (OSError, ValueError):
return False
def advertise_service(
port: int,
name: str,
labels: Optional[dict] = None,
):
"""Advertise a service on the local Tailnet.
Returns the registry handle (keep a reference to stay advertised),
or None if Tailscale/minidisc is unavailable.
"""
try:
# Lazy import: optional dependency — this module is imported by consumers
# (e.g. the backend) that don't guarantee minidisc is installed.
import minidisc
# start_registry() blocks on ready.wait() with no timeout.
# If the server thread can't bind (e.g., Docker container without
# Tailscale interfaces), it hangs forever. Run with a timeout.
registry_holder = []
def _try_start():
registry_holder.append(minidisc.start_registry())
t = threading.Thread(target=_try_start, daemon=True)
t.start()
t.join(timeout=5)
if not registry_holder:
logger.debug(
"minidisc registry startup timed out after 5s — skipping advertisement"
)
return None
registry = registry_holder[0]
registry.advertise_service(port, name, labels or {})
logger.info("Advertising '%s' on port %d via minidisc", name, port)
return registry
except ImportError:
logger.debug("minidisc not installed — skipping service advertisement")
except Exception as e:
logger.debug("minidisc advertisement failed (non-fatal): %s", e)
return None
def start_advertising(entries: list, backoff: Optional[list] = None):
"""Advertise multiple services on the Tailnet from a single minidisc registry.
``entries`` is a list of ``(name, port, labels)`` tuples. One registry is
started and every entry advertised through it; the registry handle is
returned and the caller MUST keep a reference to it — minidisc stops
advertising once the handle is garbage-collected.
Returns None (non-fatal) if minidisc is unavailable or the registry could not
bind the Tailscale interface — common on Docker Desktop/WSL2, where it may not
be bindable immediately, hence the retry/backoff. Advertising is best-effort.
NOTE: the containerized edge sidecar (``edge/agent.py``) keeps its own copy of
this start/backoff logic because its Docker build context excludes this module.
"""
try:
# Lazy import: optional dependency — see comment on advertise_service.
import minidisc
except ImportError:
logger.debug("minidisc not installed — skipping advertisement")
return None
# start_registry() blocks on ready.wait() with no timeout; if the server
# thread can't bind the Tailscale interface it hangs forever. Run it with a
# timeout and retry with backoff (the interface may not be bindable yet).
def _try_start_registry():
holder = []
def _go():
holder.append(minidisc.start_registry())
t = threading.Thread(target=_go, daemon=True)
t.start()
t.join(timeout=10)
return holder[0] if holder else None
registry = None
for delay in backoff if backoff is not None else [0, 10, 30, 60]:
if delay:
time.sleep(delay)
try:
registry = _try_start_registry()
except Exception as e: # noqa: BLE001 - advertising is best-effort
logger.debug("minidisc registry start failed (non-fatal): %s", e)
registry = None
if registry:
break
logger.warning(
"minidisc registry startup timed out (Tailscale interface not bindable yet)"
)
if not registry:
logger.warning(
"Could not start minidisc registry — Tailnet advertising disabled"
)
return None
for name, port, labels in entries:
try:
registry.advertise_service(port, name, labels or {})
logger.info("Advertising '%s' on port %d via minidisc", name, port)
except Exception as e: # noqa: BLE001 - one bad entry shouldn't kill the rest
logger.debug("Failed to advertise '%s' (non-fatal): %s", name, e)
return registry
def discover_service(
name: str,
labels: Optional[dict] = None,
timeout: int = 3,
) -> Optional[str]:
"""Discover a service on the Tailnet by name.
Returns ``"http://{addr}:{port}"`` or None if not found.
"""
try:
# Lazy import: optional dependency — see comment on advertise_service.
import minidisc
endpoint = minidisc.find_service(name, labels or {})
if endpoint:
url = f"http://{endpoint}"
logger.info("Discovered '%s' at %s", name, url)
return url
except ImportError:
logger.debug("minidisc not installed — skipping service discovery")
except Exception as e:
logger.debug("minidisc discovery for '%s' failed (non-fatal): %s", name, e)
return None
def resolve_service_url(
env_var: Optional[str],
service_name: str,
labels: Optional[dict] = None,
default: Optional[str] = None,
) -> Optional[str]:
"""Resolve a service URL with graceful fallback.
Priority:
1. Environment variable (if env_var is set and non-empty)
2. Minidisc discovery on Tailnet
3. default
"""
if env_var:
value = os.getenv(env_var)
if value:
return value
discovered = discover_service(service_name, labels)
if discovered:
return discovered
return default
def resolve_backend_url(
env_url: Optional[str],
*,
default: str = "http://localhost:8000",
logger: Optional[logging.Logger] = None,
) -> str:
"""Resolve the Chronicle backend URL, logging *how* the decision was made.
Order of preference: explicit ``env_url`` > minidisc discovery > ``default``.
Every path logs its outcome, and on fallback it explains *why* discovery did not
apply (minidisc missing, no tailscaled socket, or nothing advertised) so the
reason shows up in the app's logs instead of silently landing on localhost.
"""
log = logger or logging.getLogger(__name__)
if env_url:
log.info("Backend URL set explicitly: %s", env_url)
return env_url
minidisc_installed = importlib.util.find_spec("minidisc") is not None
socket_present = is_tailscale_available()
if not minidisc_installed:
log.warning("Auto-discovery off: minidisc-python is not installed")
elif not socket_present:
log.warning(
"Auto-discovery off: tailscaled socket %s is absent "
"(normal with the macOS GUI Tailscale app)",
_TAILSCALE_SOCKET,
)
else:
discovered = discover_service(CHRONICLE_BACKEND)
if discovered:
log.info("Discovered backend via minidisc: %s", discovered)
return discovered
log.warning(
"Auto-discovery found no '%s' service on the tailnet", CHRONICLE_BACKEND
)
log.warning(
"Falling back to %s. Set BACKEND_URL in .env to your server, "
"e.g. https://<your-host>.ts.net",
default,
)
return default
def _parse_endpoint(endpoint: str) -> tuple[str, int]:
"""Parse a minidisc endpoint string like '100.99.62.5:8989' into (address, port)."""
if not endpoint:
return ("", 0)
try:
host, port_str = endpoint.rsplit(":", 1)
return (host, int(port_str))
except (ValueError, AttributeError):
return (endpoint, 0)
def list_all_services() -> list[dict]:
"""List all chronicle-* services on the Tailnet via minidisc.
Returns a list of dicts with keys: name, address, port, labels.
Gracefully returns [] on ImportError or any exception.
"""
try:
# Lazy import: optional dependency — see comment on advertise_service.
import minidisc
raw = minidisc.list_services()
results = []
for svc in raw:
name = getattr(svc, "name", None) or (
svc.get("name") if isinstance(svc, dict) else None
)
if not name or not name.startswith("chronicle-"):
continue
labels = (
getattr(svc, "labels", {})
if not isinstance(svc, dict)
else svc.get("labels", {})
)
# minidisc Service objects use 'endpoint' (e.g. "100.x.x.x:8000"),
# not separate address/port fields.
endpoint = (
getattr(svc, "endpoint", "")
if not isinstance(svc, dict)
else svc.get("endpoint", "")
)
address, port = _parse_endpoint(str(endpoint))
results.append(
{
"name": name,
"address": address,
"port": port,
"labels": labels,
}
)
return results
except ImportError:
logger.debug("minidisc not installed — cannot list services")
except Exception as e:
logger.debug("minidisc list_services failed (non-fatal): %s", e)
return []