roleforge-core 0.2.2__cp310-abi3-win_amd64.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- roleforge/__init__.py +5 -0
- roleforge/_errors.py +40 -0
- roleforge/_live.py +84 -0
- roleforge/_native.pyd +0 -0
- roleforge/builtin_roles/Tailscale/README.md +86 -0
- roleforge/builtin_roles/Tailscale/bin/linux-amd64/roleforge-tailscale +0 -0
- roleforge/builtin_roles/Tailscale/bin/linux-arm64/roleforge-tailscale +0 -0
- roleforge/builtin_roles/Tailscale/bin/windows-amd64/roleforge-tailscale.exe +0 -0
- roleforge/builtin_roles/Tailscale/main.py +410 -0
- roleforge/builtin_roles/__init__.py +1 -0
- roleforge/core/storage/builtin_roles.json +8 -0
- roleforge/core/storage/dynamic_roles.json +8 -0
- roleforge/roles/Test/main.py +19 -0
- roleforge_core-0.2.2.dist-info/METADATA +90 -0
- roleforge_core-0.2.2.dist-info/RECORD +17 -0
- roleforge_core-0.2.2.dist-info/WHEEL +4 -0
- roleforge_core-0.2.2.dist-info/sboms/roleforge.cyclonedx.json +1012 -0
roleforge/__init__.py
ADDED
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
"""Minimal Python interface to the Rust Core; load() delivers resolved Roles through their receiving entry point."""
|
|
2
|
+
from ._native import PackagePathResolutionFailed, Project, RoleInfo, load
|
|
3
|
+
from ._live import Role
|
|
4
|
+
|
|
5
|
+
__all__ = ["load", "Project", "RoleInfo", "Role", "PackagePathResolutionFailed"]
|
roleforge/_errors.py
ADDED
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
"""Focused Core API errors; preserve built-in exception classes and messages.
|
|
2
|
+
|
|
3
|
+
Each constructor owns its case-specific data. Native Python argument/protocol
|
|
4
|
+
errors and failures in Role methods after receipt propagate unchanged.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
def live_role_not_found(name):
|
|
9
|
+
error = KeyError(f"No successfully delivered Role named {name!r}")
|
|
10
|
+
error.case = "LiveRoleNotFound"
|
|
11
|
+
error.role_name = name
|
|
12
|
+
return error
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
def role_occurrence_not_found(index):
|
|
16
|
+
error = IndexError(f"No live Role occurrence at role_index {index}")
|
|
17
|
+
error.case = "RoleOccurrenceNotFound"
|
|
18
|
+
error.role_index = index
|
|
19
|
+
return error
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def live_role_attribute_not_found(attribute):
|
|
23
|
+
error = AttributeError(f"No live Role attribute {attribute!r}")
|
|
24
|
+
error.case = "LiveRoleAttributeNotFound"
|
|
25
|
+
error.attribute = attribute
|
|
26
|
+
return error
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def ambiguous_role_attribute(attribute, names):
|
|
30
|
+
error = AttributeError(f"Ambiguous Role attribute {attribute!r}; use get_role(exact_name)")
|
|
31
|
+
error.case = "AmbiguousRoleAttribute"
|
|
32
|
+
error.attribute = attribute
|
|
33
|
+
error.role_names = tuple(names)
|
|
34
|
+
return error
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def invalid_role_class():
|
|
38
|
+
error = TypeError("Target Role must subclass roleforge.Role")
|
|
39
|
+
error.case = "InvalidRoleClass"
|
|
40
|
+
return error
|
roleforge/_live.py
ADDED
|
@@ -0,0 +1,84 @@
|
|
|
1
|
+
"""Python representation used by the Python Bridge, independent of Role semantics."""
|
|
2
|
+
import keyword
|
|
3
|
+
import operator
|
|
4
|
+
|
|
5
|
+
from . import _errors
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
def _select(instances, index):
|
|
9
|
+
index = operator.index(index)
|
|
10
|
+
try:
|
|
11
|
+
return instances[index]
|
|
12
|
+
except KeyError:
|
|
13
|
+
raise _errors.role_occurrence_not_found(index) from None
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
class Role:
|
|
17
|
+
"""Base for an optional target-module Role class; initialize state in the receiver."""
|
|
18
|
+
|
|
19
|
+
def __init__(self, role_input):
|
|
20
|
+
self._input = role_input
|
|
21
|
+
self._instances = {role_input.role_index: self}
|
|
22
|
+
|
|
23
|
+
@property
|
|
24
|
+
def name(self):
|
|
25
|
+
return self._input.name
|
|
26
|
+
|
|
27
|
+
@property
|
|
28
|
+
def index(self):
|
|
29
|
+
return self._input.index
|
|
30
|
+
|
|
31
|
+
@property
|
|
32
|
+
def role_index(self):
|
|
33
|
+
return self._input.role_index
|
|
34
|
+
|
|
35
|
+
@property
|
|
36
|
+
def body(self):
|
|
37
|
+
return self._input.body
|
|
38
|
+
|
|
39
|
+
@property
|
|
40
|
+
def source(self):
|
|
41
|
+
return self._input.source
|
|
42
|
+
|
|
43
|
+
@property
|
|
44
|
+
def role_input(self):
|
|
45
|
+
return self._input
|
|
46
|
+
|
|
47
|
+
def __getitem__(self, index):
|
|
48
|
+
return _select(self._instances, index)
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
def _create_role(module, role_input):
|
|
52
|
+
role_type = vars(module).get("Role", Role)
|
|
53
|
+
if not isinstance(role_type, type) or not issubclass(role_type, Role):
|
|
54
|
+
raise _errors.invalid_role_class()
|
|
55
|
+
return role_type(role_input)
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
class _ProjectRoles:
|
|
59
|
+
def __init__(self, delivered):
|
|
60
|
+
self.groups = {}
|
|
61
|
+
self.attributes = {}
|
|
62
|
+
for role in delivered:
|
|
63
|
+
self.groups.setdefault(role.name, {})[role.role_index] = role
|
|
64
|
+
for name, instances in self.groups.items():
|
|
65
|
+
for role in instances.values():
|
|
66
|
+
role._instances = instances
|
|
67
|
+
attribute = name.lower()
|
|
68
|
+
if attribute.isidentifier() and not keyword.iskeyword(attribute):
|
|
69
|
+
self.attributes.setdefault(attribute, []).append(name)
|
|
70
|
+
|
|
71
|
+
def by_name(self, name, index):
|
|
72
|
+
try:
|
|
73
|
+
instances = self.groups[name]
|
|
74
|
+
except KeyError:
|
|
75
|
+
raise _errors.live_role_not_found(name) from None
|
|
76
|
+
return _select(instances, index)
|
|
77
|
+
|
|
78
|
+
def by_attribute(self, attribute):
|
|
79
|
+
names = self.attributes.get(attribute, ())
|
|
80
|
+
if not names:
|
|
81
|
+
raise _errors.live_role_attribute_not_found(attribute)
|
|
82
|
+
if len(names) != 1:
|
|
83
|
+
raise _errors.ambiguous_role_attribute(attribute, names)
|
|
84
|
+
return self.by_name(names[0], 0)
|
roleforge/_native.pyd
ADDED
|
Binary file
|
|
@@ -0,0 +1,86 @@
|
|
|
1
|
+
# Built-in Tailscale Role
|
|
2
|
+
|
|
3
|
+
`Tailscale` is a built-in Python Role that manages one embedded `tsnet` node. It does not turn on or off a computer or a system-wide Tailscale VPN and does not require separately installed `tailscaled` or the Tailscale CLI.
|
|
4
|
+
|
|
5
|
+
## `.rfg` configuration
|
|
6
|
+
|
|
7
|
+
```text
|
|
8
|
+
@role Tailscale
|
|
9
|
+
env_file = "./.env"
|
|
10
|
+
|
|
11
|
+
connect.settings {
|
|
12
|
+
hostname = "home-gallery"
|
|
13
|
+
auth_key = ""
|
|
14
|
+
state_dir = ".roleforge/tailscale"
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
proxy.settings {
|
|
18
|
+
https = true
|
|
19
|
+
target = "http://127.0.0.1:8000"
|
|
20
|
+
listen_port = 443
|
|
21
|
+
}
|
|
22
|
+
```
|
|
23
|
+
|
|
24
|
+
With `https = true`, the Role uses `tsnet.Server.ListenTLS` for an HTTPS listener available only on the tailnet. Enable HTTPS certificates for the tailnet in its Tailscale admin settings, and use the node's `.ts.net` DNS name over port 443. This keeps browser cryptography in a secure context. `https` defaults to `false` for compatibility with existing configurations; do not use that mode for a browser gallery that relies on secure-context APIs.
|
|
25
|
+
|
|
26
|
+
`env_file` is optional. Relative `env_file` and `settings.state_dir` paths are resolved from `role.source.path.parent`. An `.env` file is read with `python-dotenv` without changing the process environment.
|
|
27
|
+
|
|
28
|
+
| `.env` key | `.rfg` setting |
|
|
29
|
+
| --- | --- |
|
|
30
|
+
| `TAILSCALE_HOSTNAME` | `connect.settings.hostname` |
|
|
31
|
+
| `TAILSCALE_AUTH_KEY` | `connect.settings.auth_key` |
|
|
32
|
+
| `TAILSCALE_STATE_DIR` | `connect.settings.state_dir` |
|
|
33
|
+
|
|
34
|
+
Matching `.env` values override direct `.rfg` values. Unrelated environment variables are ignored. `hostname`, `auth_key`, and `state_dir` are required after merging. Proxy settings are `target`, `listen_port`, and optional `https` (default `false`); their `.env` names are `TAILSCALE_PROXY_TARGET`, `TAILSCALE_PROXY_LISTEN_PORT`, and `TAILSCALE_PROXY_HTTPS`.
|
|
35
|
+
|
|
36
|
+
If `env_file` is specified but missing or unreadable, calling `connect()` raises `TailscaleConfigurationError`. Unknown or malformed settings also raise a configuration error identifying the Tailscale Role and line/key. Real auth keys belong only in an ignored `.env` file; never commit or log them.
|
|
37
|
+
|
|
38
|
+
## Python API
|
|
39
|
+
|
|
40
|
+
Loading a `.rfg` file creates the Role object only. Configuration is parsed and validated by the first `connect()` call. Loading does not read the `.env` file or connect:
|
|
41
|
+
|
|
42
|
+
```python
|
|
43
|
+
project = roleforge.load("project.rfg")
|
|
44
|
+
|
|
45
|
+
project.tailscale.connect()
|
|
46
|
+
project.tailscale.proxy.start()
|
|
47
|
+
project.tailscale.status()
|
|
48
|
+
project.tailscale.proxy.stop()
|
|
49
|
+
project.tailscale.disconnect()
|
|
50
|
+
```
|
|
51
|
+
|
|
52
|
+
- `connect()` starts the embedded helper and waits for Tailscale readiness; it does not start the proxy.
|
|
53
|
+
- `proxy.start()` requires the node to be ready and forwards tailnet requests to the configured local target, using HTTPS on the tailnet when `https = true`.
|
|
54
|
+
- `proxy.stop()` stops forwarding but leaves the node connected.
|
|
55
|
+
- `disconnect()` stops the proxy if running and closes the helper; it is safe when already disconnected.
|
|
56
|
+
- `status()` reports connection and proxy state separately without starting a connection.
|
|
57
|
+
|
|
58
|
+
Repeated `connect()` calls are safe. A later `connect()` starts a fresh helper after `disconnect()`.
|
|
59
|
+
|
|
60
|
+
`status()` returns a dictionary with:
|
|
61
|
+
|
|
62
|
+
```python
|
|
63
|
+
{
|
|
64
|
+
"state": "Running",
|
|
65
|
+
"hostname": "example-device",
|
|
66
|
+
"tailscale_ips": ["100.x.y.z"],
|
|
67
|
+
"dns_name": "example-device.tailnet.ts.net",
|
|
68
|
+
"proxy_state": "running",
|
|
69
|
+
"listen_port": 443,
|
|
70
|
+
"proxy_https": true,
|
|
71
|
+
}
|
|
72
|
+
```
|
|
73
|
+
|
|
74
|
+
`proxy_https` reports whether the active listener uses TLS. For a disconnected Role, `tailscale_ips` is empty, `dns_name` is an empty string, `proxy_state` is `stopped`, `listen_port` is `0`, and `proxy_https` is `false`.
|
|
75
|
+
|
|
76
|
+
## State isolation and supported binaries
|
|
77
|
+
|
|
78
|
+
Relative state directories are isolated per Tailscale Role occurrence using RoleForge's global and per-name Role indexes.
|
|
79
|
+
|
|
80
|
+
Precompiled helpers are stored under `bin/`:
|
|
81
|
+
|
|
82
|
+
- `windows-amd64/roleforge-tailscale.exe`
|
|
83
|
+
- `linux-amd64/roleforge-tailscale`
|
|
84
|
+
- `linux-arm64/roleforge-tailscale`
|
|
85
|
+
|
|
86
|
+
The Python Role selects the helper by the current operating system and CPU architecture.
|
|
Binary file
|
|
Binary file
|
|
@@ -0,0 +1,410 @@
|
|
|
1
|
+
import atexit
|
|
2
|
+
import json
|
|
3
|
+
import platform
|
|
4
|
+
import queue
|
|
5
|
+
import subprocess
|
|
6
|
+
import threading
|
|
7
|
+
from pathlib import Path
|
|
8
|
+
from urllib.parse import urlparse
|
|
9
|
+
|
|
10
|
+
from dotenv import dotenv_values
|
|
11
|
+
|
|
12
|
+
from roleforge import Role as BaseRole
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
class TailscaleError(RuntimeError):
|
|
16
|
+
"""Base exception for Tailscale Role failures."""
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
class TailscaleConfigurationError(TailscaleError):
|
|
20
|
+
"""Malformed or incomplete Tailscale configuration."""
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
class TailscaleConnectionError(TailscaleError):
|
|
24
|
+
"""The Tailscale node could not connect or become ready."""
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
class TailscaleProxyError(TailscaleError):
|
|
28
|
+
"""The tailnet proxy could not start or stop safely."""
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
class TailscaleHelperStartupError(TailscaleError):
|
|
32
|
+
"""The Tailscale helper process could not start."""
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
class TailscaleTimeoutError(TailscaleError):
|
|
36
|
+
"""A Tailscale operation timed out."""
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
class TailscaleProtocolError(TailscaleError):
|
|
40
|
+
"""The Tailscale helper returned invalid protocol data."""
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
class TailscaleHelperExitError(TailscaleError):
|
|
44
|
+
"""The Tailscale helper exited unexpectedly."""
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
_ALLOWED_CONNECT_SETTINGS = {"hostname", "auth_key", "state_dir"}
|
|
48
|
+
_ALLOWED_PROXY_SETTINGS = {"target", "listen_port", "https"}
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
def _config_error(role, line, message):
|
|
52
|
+
return TailscaleConfigurationError(
|
|
53
|
+
"Tailscale configuration error at line {}: {}".format(line, message)
|
|
54
|
+
)
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
def _parse_value(text, role, line):
|
|
58
|
+
text = text.strip()
|
|
59
|
+
if text[0:1] in ('"', "'"):
|
|
60
|
+
quote = text[0]
|
|
61
|
+
if len(text) < 2 or text[-1] != quote:
|
|
62
|
+
raise _config_error(role, line, "malformed quoted value")
|
|
63
|
+
return text[1:-1]
|
|
64
|
+
if not text:
|
|
65
|
+
raise _config_error(role, line, "a setting value cannot be empty")
|
|
66
|
+
if " " in text:
|
|
67
|
+
return text
|
|
68
|
+
return text
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
def _parse_body(role):
|
|
72
|
+
connect = {}
|
|
73
|
+
proxy = {}
|
|
74
|
+
env_file = None
|
|
75
|
+
base = role.source.path.resolve().parent
|
|
76
|
+
section = None
|
|
77
|
+
|
|
78
|
+
for offset, raw in enumerate(role.body.splitlines(), start=1):
|
|
79
|
+
line = role.source.declaration_line + offset
|
|
80
|
+
stripped = raw.strip()
|
|
81
|
+
if not stripped or stripped.startswith("#") or stripped == "@end":
|
|
82
|
+
continue
|
|
83
|
+
if stripped == "connect.settings {":
|
|
84
|
+
section = "connect"
|
|
85
|
+
continue
|
|
86
|
+
if stripped == "proxy.settings {":
|
|
87
|
+
section = "proxy"
|
|
88
|
+
continue
|
|
89
|
+
if stripped == "}":
|
|
90
|
+
section = None
|
|
91
|
+
continue
|
|
92
|
+
if "=" not in raw:
|
|
93
|
+
raise _config_error(role, line, "malformed configuration line")
|
|
94
|
+
key, value = (part.strip() for part in raw.split("=", 1))
|
|
95
|
+
value = _parse_value(value, role, line)
|
|
96
|
+
if section is None:
|
|
97
|
+
if key == "env_file":
|
|
98
|
+
env_file = value
|
|
99
|
+
elif key.startswith("settings."):
|
|
100
|
+
setting = key[len("settings."):]
|
|
101
|
+
if setting not in _ALLOWED_CONNECT_SETTINGS:
|
|
102
|
+
raise _config_error(role, line, "unknown settings key {!r}".format(setting))
|
|
103
|
+
connect[setting] = value
|
|
104
|
+
else:
|
|
105
|
+
raise _config_error(role, line, "unknown configuration key {!r}".format(key))
|
|
106
|
+
elif section == "connect":
|
|
107
|
+
if key not in _ALLOWED_CONNECT_SETTINGS:
|
|
108
|
+
raise _config_error(role, line, "unknown connect.settings key {!r}".format(key))
|
|
109
|
+
connect[key] = value
|
|
110
|
+
else:
|
|
111
|
+
if key not in _ALLOWED_PROXY_SETTINGS:
|
|
112
|
+
raise _config_error(role, line, "unknown proxy.settings key {!r}".format(key))
|
|
113
|
+
proxy[key] = value
|
|
114
|
+
|
|
115
|
+
if env_file is not None:
|
|
116
|
+
env_path = Path(env_file)
|
|
117
|
+
if not env_path.is_absolute():
|
|
118
|
+
env_path = base / env_path
|
|
119
|
+
env_path = env_path.resolve()
|
|
120
|
+
try:
|
|
121
|
+
values = dotenv_values(env_path)
|
|
122
|
+
except Exception:
|
|
123
|
+
raise TailscaleConfigurationError(
|
|
124
|
+
"Tailscale configuration error: env_file could not be read: {}".format(env_path)
|
|
125
|
+
) from None
|
|
126
|
+
if not env_path.is_file():
|
|
127
|
+
raise TailscaleConfigurationError(
|
|
128
|
+
"Tailscale configuration error: env_file could not be read: {}".format(env_path)
|
|
129
|
+
)
|
|
130
|
+
mapping = {
|
|
131
|
+
"TAILSCALE_HOSTNAME": ("connect", "hostname"),
|
|
132
|
+
"TAILSCALE_AUTH_KEY": ("connect", "auth_key"),
|
|
133
|
+
"TAILSCALE_STATE_DIR": ("connect", "state_dir"),
|
|
134
|
+
"TAILSCALE_PROXY_TARGET": ("proxy", "target"),
|
|
135
|
+
"TAILSCALE_PROXY_LISTEN_PORT": ("proxy", "listen_port"),
|
|
136
|
+
"TAILSCALE_PROXY_HTTPS": ("proxy", "https"),
|
|
137
|
+
}
|
|
138
|
+
for env_key, (section_name, setting) in mapping.items():
|
|
139
|
+
if values.get(env_key) is not None:
|
|
140
|
+
destination = connect if section_name == "connect" else proxy
|
|
141
|
+
destination[setting] = values[env_key]
|
|
142
|
+
|
|
143
|
+
for required in ("hostname", "auth_key", "state_dir"):
|
|
144
|
+
if not connect.get(required):
|
|
145
|
+
raise TailscaleConfigurationError(
|
|
146
|
+
"Tailscale configuration error: required setting 'connect.settings.{}' is missing".format(required)
|
|
147
|
+
)
|
|
148
|
+
|
|
149
|
+
state = Path(connect["state_dir"])
|
|
150
|
+
if not state.is_absolute():
|
|
151
|
+
state = base / state
|
|
152
|
+
state = state.resolve()
|
|
153
|
+
state = state / "roleforge-instance-{}-{}".format(role.index, role.role_index)
|
|
154
|
+
connect["state_dir"] = str(state)
|
|
155
|
+
|
|
156
|
+
https = proxy.get("https", "false").lower()
|
|
157
|
+
if https not in ("true", "false"):
|
|
158
|
+
raise TailscaleConfigurationError(
|
|
159
|
+
"Tailscale configuration error: 'proxy.settings.https' must be true or false"
|
|
160
|
+
)
|
|
161
|
+
proxy["https"] = https == "true"
|
|
162
|
+
|
|
163
|
+
return {"connect": connect, "proxy": proxy}
|
|
164
|
+
|
|
165
|
+
|
|
166
|
+
class _TailscaleProxy:
|
|
167
|
+
def __init__(self, role):
|
|
168
|
+
self._role = role
|
|
169
|
+
|
|
170
|
+
def start(self):
|
|
171
|
+
with self._role._lock:
|
|
172
|
+
if self._role._process is None or self._role._process.poll() is not None:
|
|
173
|
+
raise TailscaleConnectionError("Tailscale node is not connected and ready")
|
|
174
|
+
if self._role.settings is None:
|
|
175
|
+
self._role.settings = _parse_body(self._role)
|
|
176
|
+
self._role.connect_settings = self._role.settings["connect"]
|
|
177
|
+
self._role.proxy_settings = self._role.settings["proxy"]
|
|
178
|
+
self._role.hostname = self._role.connect_settings["hostname"]
|
|
179
|
+
proxy = self._role.proxy_settings
|
|
180
|
+
target = proxy.get("target")
|
|
181
|
+
if not target:
|
|
182
|
+
raise TailscaleConfigurationError("Tailscale configuration error: required setting 'proxy.settings.target' is missing")
|
|
183
|
+
parsed = urlparse(target)
|
|
184
|
+
if parsed.scheme not in ("http", "https") or not parsed.hostname:
|
|
185
|
+
raise TailscaleConfigurationError("Tailscale configuration error: 'proxy.settings.target' must be a valid HTTP or HTTPS URL")
|
|
186
|
+
try:
|
|
187
|
+
listen_port = int(proxy.get("listen_port", ""))
|
|
188
|
+
except (TypeError, ValueError):
|
|
189
|
+
raise TailscaleConfigurationError("Tailscale configuration error: 'proxy.settings.listen_port' must be an integer") from None
|
|
190
|
+
if listen_port < 1 or listen_port > 65535:
|
|
191
|
+
raise TailscaleConfigurationError("Tailscale configuration error: 'proxy.settings.listen_port' must be between 1 and 65535")
|
|
192
|
+
return self._role._request({
|
|
193
|
+
"command": "proxy_start",
|
|
194
|
+
"target": target,
|
|
195
|
+
"listen_port": listen_port,
|
|
196
|
+
"https": proxy["https"],
|
|
197
|
+
}, timeout=15)
|
|
198
|
+
|
|
199
|
+
def stop(self):
|
|
200
|
+
with self._role._lock:
|
|
201
|
+
if self._role._process is None or self._role._process.poll() is not None:
|
|
202
|
+
return {
|
|
203
|
+
"state": "disconnected", "hostname": self._role.hostname or "",
|
|
204
|
+
"tailscale_ips": [], "dns_name": "",
|
|
205
|
+
"proxy_state": "stopped", "listen_port": 0, "proxy_https": False,
|
|
206
|
+
}
|
|
207
|
+
return self._role._request({"command": "proxy_stop"}, timeout=10)
|
|
208
|
+
|
|
209
|
+
|
|
210
|
+
class Role(BaseRole):
|
|
211
|
+
"""Built-in embedded Tailscale node controlled through a precompiled helper."""
|
|
212
|
+
|
|
213
|
+
def __init__(self, role_input):
|
|
214
|
+
super().__init__(role_input)
|
|
215
|
+
self._process = None
|
|
216
|
+
self._stdout_queue = None
|
|
217
|
+
self._stderr = []
|
|
218
|
+
self._lock = threading.RLock()
|
|
219
|
+
self._closed = True
|
|
220
|
+
self.settings = None
|
|
221
|
+
self.connect_settings = None
|
|
222
|
+
self.proxy_settings = None
|
|
223
|
+
self.hostname = None
|
|
224
|
+
self._proxy = _TailscaleProxy(self)
|
|
225
|
+
atexit.register(self._atexit_disconnect)
|
|
226
|
+
|
|
227
|
+
@property
|
|
228
|
+
def proxy(self):
|
|
229
|
+
return self._proxy
|
|
230
|
+
|
|
231
|
+
def _helper_path(self):
|
|
232
|
+
system = platform.system().lower()
|
|
233
|
+
machine = platform.machine().lower()
|
|
234
|
+
if system == "windows" and machine in ("amd64", "x86_64"):
|
|
235
|
+
directory, name = "windows-amd64", "roleforge-tailscale.exe"
|
|
236
|
+
elif system == "linux" and machine in ("amd64", "x86_64"):
|
|
237
|
+
directory, name = "linux-amd64", "roleforge-tailscale"
|
|
238
|
+
elif system == "linux" and machine in ("arm64", "aarch64"):
|
|
239
|
+
directory, name = "linux-arm64", "roleforge-tailscale"
|
|
240
|
+
else:
|
|
241
|
+
raise TailscaleHelperStartupError(
|
|
242
|
+
"No precompiled Tailscale helper is available for {} {}".format(system, machine)
|
|
243
|
+
)
|
|
244
|
+
helper = Path(__file__).resolve().parent / "bin" / directory / name
|
|
245
|
+
if not helper.is_file():
|
|
246
|
+
raise TailscaleHelperStartupError(
|
|
247
|
+
"The Tailscale helper binary is missing for {} {}".format(system, machine)
|
|
248
|
+
)
|
|
249
|
+
return helper
|
|
250
|
+
|
|
251
|
+
def _reader(self):
|
|
252
|
+
for line in iter(self._process.stdout.readline, ""):
|
|
253
|
+
if line:
|
|
254
|
+
self._stdout_queue.put(line)
|
|
255
|
+
self._stdout_queue.put(None)
|
|
256
|
+
|
|
257
|
+
def _stderr_reader(self):
|
|
258
|
+
for line in iter(self._process.stderr.readline, ""):
|
|
259
|
+
line = line.strip()
|
|
260
|
+
if line:
|
|
261
|
+
self._stderr.append(line[:500])
|
|
262
|
+
|
|
263
|
+
def _start_helper(self):
|
|
264
|
+
helper = self._helper_path()
|
|
265
|
+
try:
|
|
266
|
+
process = subprocess.Popen(
|
|
267
|
+
[str(helper)], stdin=subprocess.PIPE, stdout=subprocess.PIPE,
|
|
268
|
+
stderr=subprocess.PIPE, text=True, bufsize=1,
|
|
269
|
+
)
|
|
270
|
+
except (OSError, subprocess.SubprocessError) as exc:
|
|
271
|
+
raise TailscaleHelperStartupError(
|
|
272
|
+
"Could not start the Tailscale helper: {}".format(exc)
|
|
273
|
+
) from None
|
|
274
|
+
self._process = process
|
|
275
|
+
self._stdout_queue = queue.Queue()
|
|
276
|
+
self._closed = False
|
|
277
|
+
threading.Thread(target=self._reader, daemon=True).start()
|
|
278
|
+
threading.Thread(target=self._stderr_reader, daemon=True).start()
|
|
279
|
+
|
|
280
|
+
def _request(self, command, timeout=70):
|
|
281
|
+
with self._lock:
|
|
282
|
+
if self._process is None:
|
|
283
|
+
raise TailscaleHelperExitError("The Tailscale helper is not running")
|
|
284
|
+
if self._process.poll() is not None:
|
|
285
|
+
self._process = None
|
|
286
|
+
self._closed = True
|
|
287
|
+
raise TailscaleHelperExitError("The Tailscale helper exited unexpectedly")
|
|
288
|
+
try:
|
|
289
|
+
self._process.stdin.write(json.dumps(command, ensure_ascii=False) + "\n")
|
|
290
|
+
self._process.stdin.flush()
|
|
291
|
+
except (BrokenPipeError, OSError):
|
|
292
|
+
self._process = None
|
|
293
|
+
self._closed = True
|
|
294
|
+
raise TailscaleHelperExitError("The Tailscale helper exited unexpectedly") from None
|
|
295
|
+
try:
|
|
296
|
+
line = self._stdout_queue.get(timeout=timeout)
|
|
297
|
+
except queue.Empty:
|
|
298
|
+
raise TailscaleTimeoutError("Timed out waiting for the Tailscale helper") from None
|
|
299
|
+
if line is None:
|
|
300
|
+
self._process = None
|
|
301
|
+
self._closed = True
|
|
302
|
+
raise TailscaleHelperExitError("The Tailscale helper exited unexpectedly")
|
|
303
|
+
try:
|
|
304
|
+
response = json.loads(line)
|
|
305
|
+
except json.JSONDecodeError:
|
|
306
|
+
raise TailscaleProtocolError("The Tailscale helper returned malformed JSON") from None
|
|
307
|
+
if not isinstance(response, dict) or "ok" not in response:
|
|
308
|
+
raise TailscaleProtocolError("The Tailscale helper returned an invalid protocol response")
|
|
309
|
+
if not response["ok"]:
|
|
310
|
+
error = response.get("error")
|
|
311
|
+
if not isinstance(error, str) or not error:
|
|
312
|
+
error = "The Tailscale helper returned an unknown error"
|
|
313
|
+
code = response.get("error_code")
|
|
314
|
+
if code == "invalid_config":
|
|
315
|
+
raise TailscaleConfigurationError(error)
|
|
316
|
+
if code == "connection_failed" or code == "node_not_ready":
|
|
317
|
+
raise TailscaleConnectionError(error)
|
|
318
|
+
if code in ("invalid_proxy_config", "proxy_target_unreachable", "proxy_start_failed"):
|
|
319
|
+
raise TailscaleProxyError(error)
|
|
320
|
+
raise TailscaleProtocolError(error)
|
|
321
|
+
status = response.get("status")
|
|
322
|
+
if not isinstance(status, dict):
|
|
323
|
+
raise TailscaleProtocolError("The Tailscale helper response omitted status")
|
|
324
|
+
return status
|
|
325
|
+
|
|
326
|
+
def connect(self):
|
|
327
|
+
with self._lock:
|
|
328
|
+
if self.settings is None:
|
|
329
|
+
self.settings = _parse_body(self)
|
|
330
|
+
self.connect_settings = self.settings["connect"]
|
|
331
|
+
self.proxy_settings = self.settings["proxy"]
|
|
332
|
+
self.hostname = self.connect_settings["hostname"]
|
|
333
|
+
if self._process is not None and self._process.poll() is None:
|
|
334
|
+
current = self.status()
|
|
335
|
+
if current.get("state") == "Running":
|
|
336
|
+
return current
|
|
337
|
+
self._start_helper()
|
|
338
|
+
try:
|
|
339
|
+
return self._request({
|
|
340
|
+
"command": "connect",
|
|
341
|
+
"hostname": self.connect_settings["hostname"],
|
|
342
|
+
"auth_key": self.connect_settings["auth_key"],
|
|
343
|
+
"state_dir": self.connect_settings["state_dir"],
|
|
344
|
+
}, timeout=70)
|
|
345
|
+
except Exception:
|
|
346
|
+
self.disconnect()
|
|
347
|
+
raise
|
|
348
|
+
|
|
349
|
+
def status(self):
|
|
350
|
+
with self._lock:
|
|
351
|
+
if self._process is None or self._process.poll() is not None:
|
|
352
|
+
return {
|
|
353
|
+
"state": "disconnected",
|
|
354
|
+
"hostname": self.hostname or "",
|
|
355
|
+
"tailscale_ips": [],
|
|
356
|
+
"dns_name": "",
|
|
357
|
+
"proxy_state": "stopped",
|
|
358
|
+
"listen_port": 0,
|
|
359
|
+
"proxy_https": False,
|
|
360
|
+
}
|
|
361
|
+
try:
|
|
362
|
+
return self._request({"command": "status"}, timeout=10)
|
|
363
|
+
except (TailscaleTimeoutError, TailscaleHelperExitError, TailscaleProtocolError):
|
|
364
|
+
raise
|
|
365
|
+
|
|
366
|
+
def disconnect(self):
|
|
367
|
+
with self._lock:
|
|
368
|
+
if self._process is None:
|
|
369
|
+
self._closed = True
|
|
370
|
+
return {
|
|
371
|
+
"state": "disconnected", "hostname": self.hostname or "",
|
|
372
|
+
"tailscale_ips": [], "dns_name": "",
|
|
373
|
+
"proxy_state": "stopped", "listen_port": 0, "proxy_https": False,
|
|
374
|
+
}
|
|
375
|
+
process = self._process
|
|
376
|
+
try:
|
|
377
|
+
self._request({"command": "disconnect"}, timeout=10)
|
|
378
|
+
except Exception:
|
|
379
|
+
pass
|
|
380
|
+
finally:
|
|
381
|
+
try:
|
|
382
|
+
if process.stdin:
|
|
383
|
+
process.stdin.close()
|
|
384
|
+
except Exception:
|
|
385
|
+
pass
|
|
386
|
+
if process.poll() is None:
|
|
387
|
+
process.terminate()
|
|
388
|
+
try:
|
|
389
|
+
process.wait(timeout=5)
|
|
390
|
+
except subprocess.TimeoutExpired:
|
|
391
|
+
process.kill()
|
|
392
|
+
process.wait(timeout=5)
|
|
393
|
+
self._process = None
|
|
394
|
+
self._closed = True
|
|
395
|
+
return {
|
|
396
|
+
"state": "disconnected", "hostname": self.hostname or "",
|
|
397
|
+
"tailscale_ips": [], "dns_name": "",
|
|
398
|
+
"proxy_state": "stopped", "listen_port": 0,
|
|
399
|
+
}
|
|
400
|
+
|
|
401
|
+
def _atexit_disconnect(self):
|
|
402
|
+
try:
|
|
403
|
+
self.disconnect()
|
|
404
|
+
except Exception:
|
|
405
|
+
pass
|
|
406
|
+
|
|
407
|
+
|
|
408
|
+
def roleforge_receive(role):
|
|
409
|
+
# Configuration and helper setup belong to Role.__init__; loading does not connect.
|
|
410
|
+
return None
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"""Base directory for manually registered built-in Role targets."""
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
from roleforge import Role as BaseRole
|
|
2
|
+
|
|
3
|
+
|
|
4
|
+
class Role(BaseRole):
|
|
5
|
+
def hello(self):
|
|
6
|
+
self.calls += 1
|
|
7
|
+
print(f"Hello from {self.name}[{self.role_index}]!")
|
|
8
|
+
return self.body
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
def roleforge_receive(role):
|
|
12
|
+
role.calls = 0
|
|
13
|
+
print("=== ROLEFORGE TEST ROLE ===")
|
|
14
|
+
print("Role received successfully!")
|
|
15
|
+
print(f"name: {role.name}")
|
|
16
|
+
print(f"global index: {role.index}")
|
|
17
|
+
print(f"role index: {role.role_index}")
|
|
18
|
+
print(f"body: {role.body!r}")
|
|
19
|
+
print(f"declaration line: {role.source.declaration_line}")
|