1#!/usr/bin/env python3
2import importlib.util
3import json
4from pathlib import Path
5import sys
6import subprocess
7import os
8import pwd
9import socket
10import struct
11import tempfile
12import threading
13import time
14import unittest
15from unittest.mock import patch
16
17
18spec = importlib.util.spec_from_file_location("dashboard_host", Path(__file__).with_name("dashboard-host.py"))
19host_module = importlib.util.module_from_spec(spec)
20spec.loader.exec_module(host_module)
21
22
23class Boundary(unittest.TestCase):
24 def setUp(self):
25 self.host = host_module.Host("snowglobe-demo")
26
27 @unittest.skipUnless(sys.platform == "linux", "Linux Unix peer credentials")
28 def test_large_json_header_preserves_stream_bytes_and_enforces_limit(self):
29 def exchange(payload, expected=None):
30 client, server = socket.socketpair()
31 client.settimeout(5)
32 handler = unittest.mock.Mock()
33 handler.handle.return_value = True
34 def stream_console(connection, host, request):
35 self.assertEqual(connection.recv(len(expected)), expected)
36 host_module.send_response(connection, {"value": True})
37 with patch.object(host_module, "stream_console", side_effect=stream_console):
38 worker = threading.Thread(target=host_module.serve_connection, args=(server, handler, os.getuid()), daemon=True)
39 worker.start()
40 with client:
41 client.sendall(payload)
42 length = struct.unpack('>I', client.recv(4))[0]
43 response = bytearray()
44 while len(response) < length:
45 response.extend(client.recv(length - len(response)))
46 worker.join(timeout=5)
47 self.assertFalse(worker.is_alive())
48 return json.loads(response), handler
49 message = {"operation": "shale.write", "arguments": {"comment": "\x01" * 240000}}
50 response, handler = exchange(json.dumps(message).encode() + b"\n")
51 self.assertEqual(response, {"value": True})
52 handler.handle.assert_called_once_with(message)
53 tail = b"stream bytes\nnot JSON"
54 response, handler = exchange(b'{"operation":"vm.serial"}\n' + tail, tail)
55 self.assertEqual(response, {"value": True})
56 handler.handle.assert_not_called()
57 response, handler = exchange(b'x' * (host_module.MAX_REQUEST + 1))
58 self.assertEqual(response['status'], 400)
59 handler.handle.assert_not_called()
60
61 def test_rejects_before_executing(self):
62 requests = [None, [], {}, {"operation": []},
63 {"operation": "command", "argv": ["sh", "-c", "id"]},
64 {"operation": "storage.datasets", "pool": "other"},
65 {"operation": "storage.datasets", "env": {"PATH": "/tmp"}},
66 {"operation": "host.sample", "path": "/root/private"},
67 {"operation": "host.usage", "refresh": True, "pid": 1},
68 {"operation": "deploy.managed", "path": "/var/lib/snowglobe/nomad.token"},
69 {"operation": "storage.snapshots"}]
70 for refresh in [None, [], {}, 0, 1, "true"]:
71 requests.append({"operation": "host.usage", "refresh": refresh})
72 for dataset in [None, [], "other", "snowglobe-demo-other", "snowglobe-demo/../other",
73 "snowglobe-demo//child", "snowglobe-demo/child\nother", "-r", "snowglobe-demo/a@snap"]:
74 requests.append({"operation": "storage.snapshots", "dataset": dataset})
75 for snapshot in [None, [], "a%b", "a,b", "a@b", "a\nb", "../other", "a;id"]:
76 requests.append({"operation": "storage.reclaim", "dataset": "snowglobe-demo/a",
77 "from": snapshot, "to": "safe"})
78 with patch.object(host_module, "command") as command:
79 for request in requests:
80 with self.subTest(request=request), self.assertRaises(host_module.Rejected):
81 self.host.handle(request)
82 command.assert_not_called()
83
84 def test_share_management_requires_only_its_declared_context(self):
85 request = {"operation": "copyparty.manage", "action": "state", "payload": {}, "users": []}
86 with patch.object(host_module.copyparty, "handle", return_value={"links": []}) as handle:
87 self.assertEqual(self.host.handle(request), {"links": []})
88 handle.assert_called_once_with(request)
89 for changed in [
90 {key: value for key, value in request.items() if key != "users"},
91 {**request, "root": "/srv/private"},
92 {**request, "env": {"NOMAD_TOKEN": "test"}},
93 ]:
94 with self.assertRaises(host_module.Rejected):
95 self.host.handle(changed)
96 self.assertEqual(handle.call_count, 1)
97
98 def test_reclaim_is_always_a_dry_run(self):
99 with patch.object(host_module, "command", return_value="reclaim\t1024") as command:
100 self.host.handle({"operation": "storage.reclaim", "dataset": "snowglobe-demo/a",
101 "from": "snapshot one", "to": "snapshot two"})
102 command.assert_called_once_with("zfs", "destroy", "-nvp",
103 "snowglobe-demo/a@snapshot one%snapshot two")
104
105 def test_mounts_exclude_other_pools(self):
106 mounts = {"filesystems": [{"source": source, "target": "/srv"}
107 for source in ["snowglobe-demo", "snowglobe-demo/a", "snowglobe-demo-other/a", "other/a", "snowglobe-demo/a@dash-123"]]}
108 with patch.object(host_module, "command", return_value=json.dumps(mounts)):
109 self.assertEqual([m["source"] for m in self.host.handle({"operation": "storage.mounts"})["filesystems"]],
110 ["snowglobe-demo", "snowglobe-demo/a"])
111
112 def test_snapshot_arguments_cannot_be_options(self):
113 with patch.object(host_module, "command", return_value="") as command:
114 self.host.handle({"operation": "storage.removed", "dataset": "snowglobe-demo/a", "snapshot": "snapshot -r"})
115 command.assert_called_once_with("zfs", "diff", "-H", "snowglobe-demo/a@snapshot -r", "snowglobe-demo/a")
116
117 def test_snapshot_mutations_are_scoped(self):
118 requests = []
119 for datasets in [None, {}, [], [None], ["other/private"], ["snowglobe-demo/../escape"], ["-r"]]:
120 requests.append({"operation": "files.snapshot", "datasets": datasets})
121 for snapshot in ["before", "dash-1%after", "dash-1,after", "dash-../other", "dash--r"]:
122 requests.append({"operation": "files.discard", "dataset": "snowglobe-demo/a", "snapshot": snapshot})
123 for value in ["before%after", "-r", "before,after", "before@after"]:
124 requests.append({"operation": "storage.destroy", "dataset": "snowglobe-demo/a", "from": value, "to": "after"})
125 requests.append({"operation": "files.snapshot", "datasets": ["snowglobe-demo/a"], "recursive": True})
126 with patch.object(host_module, "command") as command:
127 for request in requests:
128 with self.subTest(request=request), self.assertRaises(host_module.Rejected):
129 self.host.handle(request)
130 command.assert_not_called()
131
132 def test_file_snapshots_use_only_the_undo_namespace(self):
133 with patch.object(host_module.time, "time_ns", return_value=123), patch.object(host_module, "command", return_value="") as command:
134 name = self.host.handle({"operation": "files.snapshot", "datasets": ["snowglobe-demo/b", "snowglobe-demo/a", "snowglobe-demo/a"]})
135 self.assertEqual(name, "dash-123")
136 command.assert_called_once_with("zfs", "snapshot", "snowglobe-demo/a@dash-123", "snowglobe-demo/b@dash-123")
137 with patch.object(host_module, "command", return_value="snowglobe-demo/a@before\nsnowglobe-demo/a@dash-123\nsnowglobe-demo/a@dash-manual\n"):
138 self.assertEqual(self.host.handle({"operation": "files.snapshots", "datasets": ["snowglobe-demo/a"]}), ["snowglobe-demo/a@dash-123"])
139 with patch.object(host_module, "command", return_value="") as command:
140 self.host.handle({"operation": "files.discard", "dataset": "snowglobe-demo/a", "snapshot": "dash-123"})
141 command.assert_called_once_with("zfs", "destroy", "snowglobe-demo/a@dash-123")
142
143 def test_child_output_is_bounded(self):
144 with patch.object(host_module, "MAX_RESPONSE", 4096):
145 with self.assertRaisesRegex(RuntimeError, "too large"):
146 host_module.command(sys.executable, "-c", "import os; os.write(2, b'x' * 1000000)")
147
148 def test_index_operations_preserve_other_snapshots(self):
149 dataset = "snowglobe-demo/a"
150 with patch.object(host_module, "command") as command:
151 for name in ["manual", "dash-123", "index-fixture", "index-123%manual", "index-../escape"]:
152 for request in [{"operation": "index.discard", "dataset": dataset, "snapshot": name},
153 {"operation": "index.diff", "dataset": dataset, "from": name, "to": "index-456"}]:
154 with self.subTest(request=request), self.assertRaises(host_module.Rejected):
155 self.host.handle(request)
156 command.assert_not_called()
157 with patch.object(host_module.time, "time_ns", return_value=123), patch.object(host_module, "command", return_value="") as command:
158 self.assertEqual(self.host.handle({"operation": "index.snapshot", "dataset": dataset}), dataset + "@index-123")
159 command.assert_called_once_with("zfs", "snapshot", dataset + "@index-123")
160 legacy = "index-123-12345678-1234-1234-1234-123456789abc"
161 with patch.object(host_module, "command", return_value="\n".join(dataset + "@" + name for name in ["manual", "index-123", legacy, "index-fixture"])):
162 self.assertEqual(self.host.handle({"operation": "index.snapshots", "dataset": dataset}),
163 [dataset + "@index-123", dataset + "@" + legacy])
164 with patch.object(host_module, "command", return_value="") as command:
165 self.host.handle({"operation": "index.diff", "dataset": dataset, "from": legacy, "to": "index-456"})
166 command.assert_called_once_with("zfs", "diff", "-FH", dataset + "@" + legacy, dataset + "@index-456")
167 with patch.object(host_module, "command", return_value="") as command:
168 self.host.handle({"operation": "index.discard", "dataset": dataset, "snapshot": legacy})
169 command.assert_called_once_with("zfs", "destroy", "-d", dataset + "@" + legacy)
170
171 def test_nonzero_exit_is_reported(self):
172 with self.assertRaises(subprocess.CalledProcessError) as failed:
173 host_module.command(sys.executable, "-c", "import sys; sys.stderr.write('fixture problem'); sys.exit(1)")
174 self.assertEqual(failed.exception.stderr, "fixture problem")
175
176 def test_child_deadline_is_enforced(self):
177 with self.assertRaises(TimeoutError):
178 host_module.command(sys.executable, "-c", "import time; time.sleep(10)", timeout=.05)
179
180 def test_vm_requests_reject_before_executing(self):
181 spec = {"mode": "iso", "firmware": "bios", "platform": "linux", "name": "fixture", "owner": "fixture-user", "description": "", "image": "blank", "vcpus": 1,
182 "memory": 2**29, "disk": 2**30, "autostart": False, "start": False}
183 with patch.object(host_module.vms, "node", return_value={"cpus": 8, "memory": 8 * 2**30}), patch.object(host_module, "command") as command:
184 for field, value in [("name", "../escape"), ("image", "/root/disk.img"), ("vcpus", True),
185 ("memory", 16 * 2**30), ("disk", 2**64), ("vcpus", 9), ("argv", ["sh"])]:
186 with self.subTest(field=field), self.assertRaises(host_module.Rejected):
187 self.host.handle({"operation": "vm.create", "payload": {**spec, field: value}})
188 for request in [{"operation": "vm.xml", "payload": {}}, {"operation": "vm.node", "payload": {}},
189 {"operation": "vm.act", "payload": {"name": "fixture", "action": []}},
190 {"operation": "vm.update", "payload": {"name": "fixture"}}]:
191 with self.assertRaises(host_module.Rejected):
192 self.host.handle(request)
193 command.assert_not_called()
194
195
196@unittest.skipUnless(sys.platform == 'linux', 'Linux Unix peer credentials')
197class Capacity(unittest.TestCase):
198 def test_recovery_controls_survive_full_ordinary_capacity(self):
199 program = '''
200from importlib import import_module
201import json, sys, time
202from pathlib import Path
203m = import_module('dashboard-host')
204root = Path(sys.argv[1])
205m.vms.DISKS = root / 'vms'
206for name in ['fixture', 'idle', 'managed-mac']:
207 (m.vms.DISKS / name).mkdir(parents=True)
208class Host:
209 def __init__(self, pool): pass
210 def handle(self, request, *, active_snapshot=None):
211 if request['operation'] == 'fixture.long':
212 (root / ('started-' + str(request['index']))).touch()
213 while not (root / 'release').exists(): time.sleep(.01)
214 return {'operation': request['operation'], 'active_snapshot': active_snapshot}
215m.Host = Host
216m.vms.mac_vms.CONFIG = {'vms': [{'name': 'managed-mac'}]}
217with m.vms.computer_lock('fixture', 'exec') as active, m.vms.computer_lock('managed-mac', 'exec'):
218 (root / 'active.json').write_text(json.dumps(active))
219 m.main()
220'''
221 with tempfile.TemporaryDirectory() as directory:
222 root = Path(directory)
223 path = root / 'host.sock'
224 environment = {**os.environ, 'SNOWGLOBE_POOL': 'fixture',
225 'SNOWGLOBE_DASHBOARD_USER': pwd.getpwuid(os.getuid()).pw_name,
226 'SNOWGLOBE_HOST_SOCKET': str(path)}
227 environment.pop('NOTIFY_SOCKET', None)
228 process = subprocess.Popen([sys.executable, '-c', program, str(root)], cwd=Path(__file__).parent, env=environment,
229 stdout=subprocess.DEVNULL, stderr=subprocess.PIPE)
230 held = []
231 def connect(request):
232 connection = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
233 connection.settimeout(2)
234 try:
235 connection.connect(str(path))
236 connection.sendall(json.dumps(request).encode() + b'\n')
237 except BaseException:
238 connection.close()
239 raise
240 return connection
241 def call(request):
242 with connect(request) as connection, connection.makefile('rb') as incoming:
243 length = struct.unpack('!I', incoming.read(4))[0]
244 return json.loads(incoming.read(length))
245 try:
246 deadline = time.monotonic() + 5
247 while not path.exists():
248 self.assertIsNone(process.poll())
249 self.assertLess(time.monotonic(), deadline)
250 time.sleep(.01)
251 for index in range(host_module.WORKERS):
252 held.append(connect({'operation': 'fixture.long', 'index': index}))
253 while len(list(root.glob('started-*'))) != host_module.WORKERS:
254 self.assertLess(time.monotonic(), deadline)
255 time.sleep(.01)
256 active = json.loads((root / 'active.json').read_text())
257 for request in [
258 {'operation': 'vm.owner', 'payload': {'name': 'fixture'}}, {'operation': 'vm.computers'},
259 *({'operation': 'vm.act', 'payload': {'name': 'fixture', 'action': action}} for action in ['reset', 'destroy']),
260 *({'operation': 'vm.computer', 'payload': {'name': 'fixture', 'request': request}} for request in [
261 {'action': 'status'}, {'action': 'process', 'id': active['id'], 'operation': 'status'},
262 {'action': 'process', 'id': active['id'], 'operation': 'stop'}]),
263 ]:
264 self.assertEqual(call(request)['value']['operation'], request['operation'])
265 for request in [
266 {'operation': 'host.sample'}, {'operation': 'vm.act', 'payload': {'name': 'fixture', 'action': 'start'}},
267 {'operation': 'vm.computer', 'payload': {'name': 'idle', 'request': {'action': 'status'}}},
268 {'operation': 'vm.computer', 'payload': {'name': 'managed-mac', 'request': {'action': 'status'}}},
269 {'operation': 'vm.computer', 'payload': {'name': 'idle', 'request': {'action': 'process', 'id': active['id'], 'operation': 'stop'}}},
270 ]:
271 self.assertEqual(call(request)['status'], 503)
272 finally:
273 (root / 'release').touch()
274 for connection in held:
275 connection.close()
276 process.terminate()
277 process.communicate(timeout=5)
278
279
280if __name__ == "__main__":
281 unittest.main()