@raytrace-cli/cli 0.17.17 → 0.19.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.
@@ -1,9 +1,23 @@
1
- """Run with sudo INSIDE the dedicated Lima VM, never on the Mac.
1
+ """Sets a sandbox host up. Run with sudo on the host (inside the Lima VM locally, never on the Mac).
2
+
3
+ Separate steps, each callable alone, in this order:
4
+
5
+ install runsc, this core's files into --root, the trace config, sysctls
6
+ network the sandbox network and its firewall (network.py)
7
+ services the collector, viewer and resolver units, running from --root
8
+ image the agent image, with the agent versions in agents.json (or given)
9
+ activate services restarted in order (resolver, collector, viewer), then verified
10
+
11
+ `python3 setup.py` runs them all with --root /opt/raytace: a local VM. A host
12
+ layer can run any of them and add its own; each step writes only the core's
13
+ files (/etc/raytace/*.json, resolv.conf, bridge*, image; the raytace-* units;
14
+ --root), never another layer's.
2
15
 
3
16
  Which calls gVisor reports is not written here: trace_config() reads it from
4
17
  the catalog (syscall_catalog.sql, the `capture` column), so what a host
5
18
  subscribes to is what the catalog says, for the architecture it runs on.
6
19
  """
20
+ import argparse
7
21
  import hashlib
8
22
  import json
9
23
  import os
@@ -12,6 +26,8 @@ import platform
12
26
  import shutil
13
27
  import sqlite3
14
28
  import subprocess
29
+ import sys
30
+ import time
15
31
  import urllib.request
16
32
 
17
33
  # The runsc release installed. The catalog's numbers and coverage are generated
@@ -94,10 +110,13 @@ def trace_config(arch, catalog_sql, endpoint, calls=True):
94
110
  'config': {'endpoint': endpoint, 'retries': 8}}]}}
95
111
 
96
112
 
97
- if __name__ == '__main__':
98
- if platform.system() != 'Linux' or os.geteuid() != 0:
99
- raise SystemExit('Run this setup with sudo inside the RayTrace Linux VM.')
100
- arch = {'aarch64': 'aarch64', 'x86_64': 'x86_64'}[platform.machine()]
113
+ SOURCE = Path(__file__).resolve().parent
114
+ # What install copies: everything the host runs, nothing it does not (tests, caches).
115
+ SKIP = ('test_', '__pycache__', '.', 'tests')
116
+ UNITS = ('dns', 'collector', 'viewer') # the restart order: what sandboxes resolve with first
117
+
118
+
119
+ def install(root, arch):
101
120
  base = f'https://storage.googleapis.com/gvisor/releases/release/{RELEASE}/{arch}/'
102
121
  binary = urllib.request.urlopen(base + 'runsc', timeout=120).read()
103
122
  checksum = urllib.request.urlopen(base + 'runsc.sha512', timeout=30).read().decode().split()[0]
@@ -111,13 +130,8 @@ if __name__ == '__main__':
111
130
  staged.replace('/usr/local/bin/runsc')
112
131
  for directory in ['/opt/raytace', '/etc/raytace', '/var/lib/raytace', '/run/raytace']:
113
132
  Path(directory).mkdir(exist_ok=True, mode=0o700)
114
- source = Path(__file__).parent
115
- # The collector's own modules: the fact engine, the catalog it and this
116
- # setup read, the path rules it shares with the initial scan, the resolver.
117
- for name in ['collector.py', 'viewer.py', 'network.py', 'projects.py',
118
- 'engine.py', 'dns_forwarder.py', 'file_scan.py', 'syscall_catalog.sql']:
119
- shutil.copyfile(source / name, Path('/opt/raytace') / name)
120
- config = trace_config(arch, (source / 'syscall_catalog.sql').read_text(), '/run/raytace/events.sock')
133
+ copy_core(root)
134
+ config = trace_config(arch, (root / 'syscall_catalog.sql').read_text(), '/run/raytace/events.sock')
121
135
  Path('/etc/raytace/gvisor.json').write_text(json.dumps(config, indent=2))
122
136
  # The engine watches the folder of every file an owner restricted or watches.
123
137
  # And room for events on their way to the collector, so a burst waits in
@@ -130,6 +144,35 @@ if __name__ == '__main__':
130
144
  run('sysctl', '-q', '-p', '/etc/sysctl.d/60-raytace.conf')
131
145
  run('/usr/local/bin/runsc', 'install', '--runtime=raytace-gvisor', '--',
132
146
  '--pod-init-config=/etc/raytace/gvisor.json')
147
+ # Docker reads its runtimes at start.
148
+ run('systemctl', 'restart', 'docker')
149
+
150
+
151
+ def copy_core(root):
152
+ """This core's files into root (nothing to do when they are already there), with its VERSION."""
153
+ root.mkdir(parents=True, exist_ok=True, mode=0o755)
154
+ if root.resolve() != SOURCE:
155
+ for item in SOURCE.rglob('*'):
156
+ relative = item.relative_to(SOURCE)
157
+ if any(part.startswith(SKIP) for part in relative.parts) or item.suffix in ('.pyc', '.mjs') and 'test' in item.name:
158
+ continue
159
+ if item.is_dir():
160
+ (root / relative).mkdir(exist_ok=True)
161
+ else:
162
+ (root / relative).parent.mkdir(parents=True, exist_ok=True)
163
+ shutil.copyfile(item, root / relative)
164
+ sys.path.insert(0, str(SOURCE))
165
+ from core import version
166
+ # Read from the package it ships in; an installed copy keeps the VERSION it came with.
167
+ if version():
168
+ (root / 'VERSION').write_text(version() + '\n')
169
+
170
+
171
+ def network(root):
172
+ run('python3', str(root / 'network.py'))
173
+
174
+
175
+ def services(root):
133
176
  for name, command in [('collector', 'collector.py --socket /run/raytace/events.sock --database /var/lib/raytace/runtime.db'),
134
177
  ('viewer', 'viewer.py'), ('dns', 'dns_forwarder.py')]:
135
178
  # The resolver is what sandboxes resolve names with: it comes back whatever ended it.
@@ -137,7 +180,7 @@ if __name__ == '__main__':
137
180
  Description=RayTrace {name}
138
181
  After=network.target{' docker.service' if name == 'dns' else ''}
139
182
  [Service]
140
- ExecStart=/usr/bin/python3 /opt/raytace/{command}
183
+ ExecStart=/usr/bin/python3 {root}/{command}
141
184
  Restart={'always' if name == 'dns' else 'on-failure'}
142
185
  RestartSec=2
143
186
  UMask=0077
@@ -157,12 +200,97 @@ WantedBy=multi-user.target
157
200
  Path('/etc/needrestart/conf.d/raytace.conf').write_text(
158
201
  "$nrconf{override_rc}{qr(^raytace-)} = 0;\n")
159
202
  run('systemctl', 'daemon-reload')
160
- run('systemctl', 'restart', 'docker')
161
- run('systemctl', 'enable', '--now', 'raytace-collector', 'raytace-viewer')
162
- run('systemctl', 'restart', 'raytace-collector', 'raytace-viewer')
163
- run('python3', '/opt/raytace/network.py')
164
- # After the sandbox network exists: the resolver listens on its gateway.
165
- run('systemctl', 'enable', 'raytace-dns')
166
- run('systemctl', 'restart', 'raytace-dns')
167
- run('docker', 'build', '-t', 'raytace-gvisor-agent', '-f', str(source / 'Dockerfile'), str(source))
203
+ run('systemctl', 'enable', *(f'raytace-{name}' for name in UNITS))
204
+
205
+
206
+ def agent_versions(claude=None, codex=None):
207
+ """The exact agent versions the image is built with: given, or this core's tested ones (agents.json)."""
208
+ tested = json.loads((SOURCE / 'agents.json').read_text())
209
+ return {'claude_code': claude or tested['claude_code'], 'codex': codex or tested['codex']}
210
+
211
+
212
+ def installed_agents(tag):
213
+ """What `claude --version` and `codex --version` say in an image."""
214
+ def ask(program):
215
+ out = subprocess.run(['docker', 'run', '--rm', '--network=none', '--entrypoint', program, tag, '--version'],
216
+ capture_output=True, text=True, timeout=120)
217
+ return (out.stdout or out.stderr).strip()
218
+ return {'claude_code': ask('claude'), 'codex': ask('codex')}
219
+
220
+
221
+ def image(tag, versions, write_default=True):
222
+ """Builds the agent image with these exact agent versions and checks it has them; its image id."""
223
+ run('docker', 'build', '-t', tag, '--build-arg', f'CLAUDE_CODE_VERSION={versions["claude_code"]}',
224
+ '--build-arg', f'CODEX_VERSION={versions["codex"]}', '-f', str(SOURCE / 'Dockerfile'), str(SOURCE))
225
+ found = installed_agents(tag)
226
+ for key, wanted in versions.items():
227
+ if wanted not in found[key]:
228
+ raise SystemExit(f'The image {tag} has {key} "{found[key]}", not {wanted}.')
229
+ if write_default:
230
+ Path('/etc/raytace/image').write_text(tag + '\n')
231
+ return subprocess.check_output(['docker', 'image', 'inspect', '-f', '{{.Id}}', tag], text=True).strip()
232
+
233
+
234
+ def activate():
235
+ """Restarts the core's services in order and checks they serve."""
236
+ for name in UNITS:
237
+ run('systemctl', 'restart', f'raytace-{name}')
238
+ verify()
239
+
240
+
241
+ def verify(seconds=20):
242
+ """The collector's socket is there and the resolver answers on the gateway, or SystemExit."""
243
+ sys.path.insert(0, str(SOURCE))
244
+ import network as net
245
+ deadline = time.time() + seconds
246
+ while time.time() < deadline:
247
+ active = all(subprocess.run(['systemctl', 'is-active', '--quiet', f'raytace-{name}']).returncode == 0 for name in UNITS)
248
+ if active and Path('/run/raytace/events.sock').exists() and resolves(net.GATEWAY):
249
+ return
250
+ time.sleep(1)
251
+ raise SystemExit('RayTrace: the collector or the sandbox resolver did not come up.')
252
+
253
+
254
+ def resolves(server):
255
+ """Whether a DNS server answers a query for localhost. (A bare query, no library.)"""
256
+ import socket
257
+ import struct
258
+ query = struct.pack('>HHHHHH', 0x5254, 0x0100, 1, 0, 0, 0) + b'\x09localhost\x00' + struct.pack('>HH', 1, 1)
259
+ with socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as sock:
260
+ sock.settimeout(2)
261
+ try:
262
+ sock.sendto(query, (server, 53))
263
+ return sock.recv(512)[:2] == query[:2]
264
+ except OSError:
265
+ return False
266
+
267
+
268
+ STEPS = ['install', 'network', 'services', 'image', 'activate']
269
+
270
+
271
+ if __name__ == '__main__':
272
+ parser = argparse.ArgumentParser(description='Set a RayTrace sandbox host up (all steps by default).')
273
+ parser.add_argument('steps', nargs='*', choices=STEPS, help='only these steps, in the order given')
274
+ parser.add_argument('--root', default='/opt/raytace', help='where the core is installed and its services run from')
275
+ parser.add_argument('--image-tag', help='image: the tag to build (default raytace-gvisor-agent:<core version>)')
276
+ parser.add_argument('--claude-code', help='image: exact @anthropic-ai/claude-code version')
277
+ parser.add_argument('--codex', help='image: exact @openai/codex version')
278
+ opts = parser.parse_args()
279
+ if platform.system() != 'Linux' or os.geteuid() != 0:
280
+ raise SystemExit('Run this setup with sudo on the sandbox host (inside the RayTrace Linux VM locally).')
281
+ arch = {'aarch64': 'aarch64', 'x86_64': 'x86_64'}[platform.machine()]
282
+ root = Path(opts.root)
283
+ for step in opts.steps or STEPS:
284
+ if step == 'install':
285
+ install(root, arch)
286
+ elif step == 'network':
287
+ network(root)
288
+ elif step == 'services':
289
+ services(root)
290
+ elif step == 'image':
291
+ sys.path.insert(0, str(SOURCE))
292
+ from core import version
293
+ image(opts.image_tag or f'raytace-gvisor-agent:{version() or "dev"}', agent_versions(opts.claude_code, opts.codex))
294
+ elif step == 'activate':
295
+ activate()
168
296
  print('Ready.')