@raytrace-cli/cli 0.17.16 → 0.18.0

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.
@@ -0,0 +1,90 @@
1
+ """Releases on a sandbox host: which installed release is active, switched
2
+ atomically, and a lock that keeps a switch and a sandbox creation apart.
3
+
4
+ A release is a directory under RELEASES named by its release id, holding the
5
+ installed core and an immutable manifest, release.json:
6
+
7
+ {"id": ..., "image": "raytrace-sandbox:<id>", ...whatever its installer records}
8
+
9
+ CURRENT is a symlink to the active one, and the only record of which is
10
+ active. Activation takes the lock exclusively; anything that must see one
11
+ release from start to end (core.mechanics.create with expect_release) takes
12
+ it shared. A host without releases (a local VM) has no CURRENT: active() is
13
+ None and nothing here is used.
14
+ """
15
+ import contextlib
16
+ import fcntl
17
+ import json
18
+ import os
19
+ from pathlib import Path
20
+ import re
21
+
22
+ RELEASES = Path('/opt/raytace/releases')
23
+ CURRENT = Path('/opt/raytace/current')
24
+ LOCK = Path('/run/raytace/release.lock')
25
+ # The label a sandbox made from a release carries, naming it.
26
+ LABEL = 'io.raytace.release'
27
+ ID = r'[a-f0-9]{12,64}'
28
+
29
+
30
+ @contextlib.contextmanager
31
+ def lock(shared=False, path=None):
32
+ path = Path(path or LOCK)
33
+ path.parent.mkdir(parents=True, exist_ok=True, mode=0o700)
34
+ fd = os.open(path, os.O_RDWR | os.O_CREAT, 0o600)
35
+ try:
36
+ fcntl.flock(fd, fcntl.LOCK_SH if shared else fcntl.LOCK_EX)
37
+ yield
38
+ finally:
39
+ fcntl.flock(fd, fcntl.LOCK_UN)
40
+ os.close(fd)
41
+
42
+
43
+ def manifest(directory):
44
+ """A release directory's release.json, checked to name itself."""
45
+ directory = Path(directory)
46
+ data = json.loads((directory / 'release.json').read_text())
47
+ if data.get('id') != directory.name or not re.fullmatch(ID, data['id']) or not data.get('image'):
48
+ raise ValueError(f'{directory}: release.json does not match its directory')
49
+ return data
50
+
51
+
52
+ def active(current=None):
53
+ """The active release's manifest, or None on a host without releases."""
54
+ current = Path(current or CURRENT)
55
+ if not current.is_symlink():
56
+ return None
57
+ return manifest(current.resolve())
58
+
59
+
60
+ def point(target, current=None):
61
+ """Points CURRENT at a release directory in one rename; the release that was active before, or None."""
62
+ current = Path(current or CURRENT)
63
+ before = current.resolve() if current.is_symlink() else None
64
+ staged = current.with_name(current.name + '.new')
65
+ staged.unlink(missing_ok=True)
66
+ staged.symlink_to(Path(target))
67
+ staged.replace(current)
68
+ return before
69
+
70
+
71
+ def activate(target, restart, check, current=None, lock_path=None):
72
+ """Makes a staged release active: under the exclusive lock, the symlink
73
+ switched, `restart()` run, then `check()`. If restart or check fails, the
74
+ previous release is put back and restarted, and the failure is raised.
75
+ Returns the manifest now active."""
76
+ target = Path(target)
77
+ manifest(target)
78
+ with lock(path=lock_path):
79
+ before = point(target, current)
80
+ try:
81
+ restart()
82
+ check()
83
+ except BaseException:
84
+ if before is not None:
85
+ point(before, current)
86
+ restart()
87
+ else:
88
+ Path(current or CURRENT).unlink(missing_ok=True)
89
+ raise
90
+ return active(current)
@@ -66,6 +66,22 @@ CONTAINERS = Path('/var/lib/raytace/containers')
66
66
  # Each sandbox's restricted and watched files (projects.py guardrails()).
67
67
  GUARDRAILS = Path('/var/lib/raytace/guardrails')
68
68
  BRIDGE = Path('/etc/raytace/bridge')
69
+ # Behind a front (network.py write_bridge), BRIDGE names the front and this the
70
+ # bridge itself, which sandboxes made before the front still call directly.
71
+ BRIDGE_UPSTREAM = Path('/etc/raytace/bridge-upstream')
72
+
73
+
74
+ def bridge_addresses():
75
+ """Every address:port a sandbox reaches RayTrace's own bridge at."""
76
+ found = set()
77
+ for path in (BRIDGE, BRIDGE_UPSTREAM):
78
+ try:
79
+ written = path.read_text().strip().removeprefix('http://')
80
+ except OSError:
81
+ continue
82
+ if written:
83
+ found.add(written)
84
+ return frozenset(found)
69
85
  WORKSPACE = '/workspace/'
70
86
  # Large, regenerable folders: the same ones the sandbox hook leaves out of its snapshots.
71
87
  SKIPPED = frozenset(['node_modules', '.git', '.next', '.vinext', 'dist', 'build', 'out', 'coverage', '.cache', '.turbo',
@@ -370,7 +386,7 @@ class Engine(threading.Thread):
370
386
  self.numbered = frozenset(number for number, (_, rule) in self.calls.items() if rule in ('remove', 'rename', 'resize', 'mkdir', 'metadata'))
371
387
  self.inbox = queue.Queue(maxsize=200_000)
372
388
  self.overflowed = float('-inf')
373
- self.bridge = ('', float('-inf')) # RayTrace's own bridge as sandboxes reach it, and when that was read
389
+ self.bridge = (frozenset(), float('-inf')) # RayTrace's own bridge as sandboxes reach it, and when that was read
374
390
  self.boxes = {}
375
391
  self.facts = {} # fact id -> the fact, while it may still grow
376
392
  self.dirty = {} # fact ids to write
@@ -1127,10 +1143,7 @@ class Engine(threading.Thread):
1127
1143
  return
1128
1144
  now = self.clock()
1129
1145
  if now - self.bridge[1] > 30:
1130
- try:
1131
- self.bridge = (BRIDGE.read_text().strip().removeprefix('http://'), now)
1132
- except OSError:
1133
- self.bridge = ('', now)
1146
+ self.bridge = (bridge_addresses(), now)
1134
1147
  if f'{ip}:{port}' == f'{network.GATEWAY}:53':
1135
1148
  # The resolver: dns_forwarder.py records the lookup itself, and names
1136
1149
  # its process from this, the connection the lookup was sent on.
@@ -1139,8 +1152,8 @@ class Engine(threading.Thread):
1139
1152
  self.resolver.append((box.container, at_ns, who.get('pid'), who.get('start_ns'), who.get('name'),
1140
1153
  ' '.join(who.get('argv') or [])[:160] or None, who.get('call_id')))
1141
1154
  return
1142
- if f'{ip}:{port}' == self.bridge[0]:
1143
- return # RayTrace's own: the model and transcript bridge
1155
+ if f'{ip}:{port}' in self.bridge[0]:
1156
+ return # RayTrace's own: the model and transcript bridge, or a front before it (network.py)
1144
1157
  who = self.who(box, event)
1145
1158
  if listening:
1146
1159
  outcome = 'failed' if errno else 'listening'
@@ -20,6 +20,13 @@ REJECTED = ['0.0.0.0/8', '10.0.0.0/8', '100.64.0.0/10', '127.0.0.0/8',
20
20
  '169.254.0.0/16', '172.16.0.0/12', '192.168.0.0/16', '224.0.0.0/4']
21
21
  # The manager's bridge as sandboxes address it; projects.py puts it in their env.
22
22
  BRIDGE = Path('/etc/raytace/bridge')
23
+ # A host layer may put a front before the bridge on the gateway (a port that
24
+ # forwards to it): it writes the front's port here, and sandboxes then address
25
+ # the front, while the bridge itself is kept in BRIDGE_UPSTREAM. engine.py
26
+ # counts both as RayTrace's own. The direct way stays open, for sandboxes
27
+ # made before the front.
28
+ BRIDGE_FRONT = Path('/etc/raytace/bridge-front')
29
+ BRIDGE_UPSTREAM = Path('/etc/raytace/bridge-upstream')
23
30
 
24
31
 
25
32
  def run(*args):
@@ -47,10 +54,32 @@ def private_bridge():
47
54
  (RAYTACE_BRIDGE, set once at setup like RAYTACE_DNS, then kept in BRIDGE)."""
48
55
  if os.environ.get('RAYTACE_BRIDGE'):
49
56
  return os.environ['RAYTACE_BRIDGE']
50
- written = BRIDGE.read_text().strip().removeprefix('http://') if BRIDGE.exists() else ''
57
+ source = BRIDGE_UPSTREAM if BRIDGE_UPSTREAM.exists() else BRIDGE
58
+ written = source.read_text().strip().removeprefix('http://') if source.exists() else ''
51
59
  return written if written and not written.startswith((LIMA_HOST + ':', GATEWAY + ':')) else None
52
60
 
53
61
 
62
+ def front_port():
63
+ """The port of the front before the bridge, or None without one."""
64
+ try:
65
+ port = int(BRIDGE_FRONT.read_text().strip())
66
+ except (OSError, ValueError):
67
+ return None
68
+ return port if 0 < port < 65536 and port != 53 else None
69
+
70
+
71
+ def write_bridge(direct):
72
+ """Writes where sandboxes reach the bridge; the front's port when they reach it through one."""
73
+ port = front_port()
74
+ if port:
75
+ BRIDGE_UPSTREAM.write_text(direct + '\n')
76
+ BRIDGE.write_text(f'http://{GATEWAY}:{port}\n')
77
+ return port
78
+ BRIDGE_UPSTREAM.unlink(missing_ok=True)
79
+ BRIDGE.write_text(f'http://{direct}\n')
80
+ return None
81
+
82
+
54
83
  if __name__ == '__main__':
55
84
  dns = resolver()
56
85
  UPSTREAM.write_text(dns + '\n')
@@ -79,12 +108,15 @@ if __name__ == '__main__':
79
108
  # Above the private-range rejects: this one address and port, nothing else on the VPC.
80
109
  address, port = bridge.rsplit(':', 1)
81
110
  rule('DOCKER-USER', '-i', 'br-raytace', '-d', address, '-p', 'tcp', '--dport', port, '-j', 'ACCEPT')
82
- BRIDGE.write_text(f'http://{bridge}\n')
111
+ direct = bridge
83
112
  elif dns == LIMA_HOST:
84
113
  rule('DOCKER-USER', '-i', 'br-raytace', '-d', LIMA_HOST,
85
114
  '-p', 'tcp', '--dport', '8799', '-j', 'ACCEPT')
86
- BRIDGE.write_text(f'http://{LIMA_HOST}:8799\n')
115
+ direct = f'{LIMA_HOST}:8799'
87
116
  else:
88
117
  rule('INPUT', '-i', 'br-raytace', '-d', GATEWAY,
89
118
  '-p', 'tcp', '--dport', '8799', '-j', 'ACCEPT')
90
- BRIDGE.write_text(f'http://{GATEWAY}:8799\n')
119
+ direct = f'{GATEWAY}:8799'
120
+ front = write_bridge(direct)
121
+ if front:
122
+ rule('INPUT', '-i', 'br-raytace', '-d', GATEWAY, '-p', 'tcp', '--dport', str(front), '-j', 'ACCEPT')