CMSDK 2.0.1
Cross-platform C++ base library and SDK for the Psyclone AIOS platform
Loading...
Searching...
No Matches
test_remote_module.py
Go to the documentation of this file.
1"""RemoteModule tests (Psyclone 2.3.2 remote modules).
2
3Local: the key proof and the reply/trigger routing against a stand-in host. Live (PSYCLONE_BIN=<bin/linux64/Psyclone>):
4a real Psyclone with declared remote modules on a key-auth host (TCP, WebSocket, UDP) and a token-auth host with a
5short lease, mirroring the engine test test=remotemodule: attach (contract from the server, Ready once), triggers by
6name, posts, named retrieve and query, takeover by the same device, detach, lease expiry with re-attach, a bad key
7refused. API keys are made through PsyProbe 2 (first-run setup, machine accounts with modules.attach.*)."""
8import hashlib
9import hmac
10import json
11import os
12import re
13import shutil
14import socket
15import subprocess
16import sys
17import tempfile
18import threading
19import time
20import unittest
21import urllib.request
22
23sys.path.insert(0, os.path.join(os.path.dirname(__file__), "..", "src"))
24from psyclone_client import (ATTACHED, DETACHED, Auth, DataMessage, PsycloneClient, RemoteModule, # noqa: E402
25 RemoteModuleError)
26from psyclone_client.remote_module import _proof # noqa: E402
27
28BIN = os.environ.get("PSYCLONE_BIN", "")
29NODE, MOD, WS, LEASE, FEED = 18770, 18771, 18772, 18773, 18774
30
31
32def wait_for(sec, cond):
33 end = time.time() + sec
34 while not cond():
35 if time.time() > end:
36 return False
37 time.sleep(0.01)
38 return True
39
40
41class Local(unittest.TestCase):
42 def test_proof(self):
43 key_id, proof = _proof("psy_abc123_" + "s" * 40, "Asr", "dev-1", "n0nce")
44 self.assertEqual(key_id, "abc123")
45 k = hashlib.sha256(("s" * 40).encode()).hexdigest().encode()
46 self.assertEqual(proof, hmac.new(k, b"Asr|dev-1|n0nce", hashlib.sha256).hexdigest())
47 with self.assertRaises(ValueError):
48 Auth.key("not-a-key")
49
51 """A TCP stand-in answers attach and a 3-result retrieve; results arrive in order before the status."""
52 srv = socket.socket()
53 srv.bind(("127.0.0.1", 0))
54 srv.listen(1)
55 port = srv.getsockname()[1]
56
57 def host():
58 c, _ = srv.accept()
59 buf = b""
60 while True:
61 try:
62 d = c.recv(65536)
63 except OSError:
64 return
65 if not d:
66 return
67 buf += d
68 while len(buf) >= 4:
69 n = int.from_bytes(buf[:4], "little")
70 if len(buf) < n:
71 break
72 m, buf = DataMessage.from_bytes(buf[:n]), buf[n:]
73 op = m.get_string("PsyOp")
74 if m.get_string("PsyPost") != "PsyModule" or op is None:
75 continue
76
77 def reply(extra=None, status="ok"):
78 r = DataMessage().set_string("PsyOp", op).set_string("PsyOpID", m.get_string("PsyOpID"))
79 r.set_int("PsyOpReply", 1).set_string("PsyModule", "Asr")
80 if status:
81 r.set_string("PsyStatus", status)
82 for k, v in (extra or {}).items():
83 r.set_int(k, v) if isinstance(v, int) else r.set_string(k, v)
84 c.sendall(r.to_bytes())
85 if op == "attach":
86 reply({"PsySession": "f" * 32, "Lease": 30000, "Posts": "Text", "Triggers": "Audio=RM.Audio"})
87 t = DataMessage().set_string("PsyTrigger", "Audio").set_string("PsyModule", "Asr").set_int("PsySeq", 1)
88 c.sendall(t.to_bytes())
89 elif op == "retrieve":
90 for i in range(3):
91 reply({"PsyResultIndex": i, "PsyResultCount": 3, "N": i}, status=None)
92 reply({"PsyResultCount": 3})
93 threading.Thread(target=host, daemon=True).start()
94 psy = PsycloneClient.tcp("127.0.0.1", port, "py-stand-in", keepalive_interval=0)
95 try:
96 asr = RemoteModule.attach(psy, "Asr", Auth.token("x"))
97 self.assertEqual(asr.state, ATTACHED)
98 self.assertEqual(asr.posts, ["Text"])
99 self.assertEqual(asr.triggers, {"Audio": "RM.Audio"})
100 m = asr.wait_for_new_message(3)
101 self.assertIsNotNone(m)
102 self.assertEqual(asr.current_trigger_name, "Audio")
103 got = asr.retrieve("Recent")
104 self.assertEqual([g.get_int("N") for g in got], [0, 1, 2])
105 finally:
106 psy.close()
107 srv.close()
108
109
110SPEC = """<psyspec name="PyRemoteModuleTest" port="%(NODE)d">
111 <psyprobe datadir="%(DIR)s" />
112 <service name="Modules"><modules auth="key" udp="yes"/></service>
113 <service name="LeaseMods"><modules auth="token" token="py-lease-token" lease="1500"/></service>
114 <service name="Feed"><post name="Audio" type="Py.RM.Audio"/></service>
115 <interface name="ModTCP" port="%(MOD)d" protocol="Message" service="Modules"/>
116 <interface name="ModUDP" port="%(MOD)d" ip="UDP" protocol="Message" service="Modules"/>
117 <interface name="ModWS" port="%(WS)d" protocol="HTTP" service="Modules"/>
118 <interface name="LeaseTCP" port="%(LEASE)d" protocol="Message" service="LeaseMods"/>
119 <interface name="FeedTCP" port="%(FEED)d" protocol="Message" service="Feed"/>
120 <module name="Asr" type="remote" service="Modules">
121 <trigger name="Audio" type="Py.RM.Audio"/><trigger name="Go" type="Psyclone.Ready"/>
122 <post name="Note" type="Py.RM.Note"/>
123 <retrieve name="Recent" source="PyWB" type="Py.RM.Note" maxcount="10"/>
124 <query name="Notes" source="PyStore"/>
125 <parameter name="Language" value="en-GB"/>
126 </module>
127 <module name="Tts" type="remote" service="Modules"><trigger name="Note" type="Py.RM.Note"/></module>
128 <module name="Vad" type="remote" service="Modules"><trigger name="Audio" type="Py.RM.Audio"/></module>
129 <module name="Short" type="remote" service="LeaseMods"><trigger name="Audio" type="Py.RM.Audio"/></module>
130 <whiteboard name="PyWB"><trigger name="All" type="Py.RM.*"/></whiteboard>
131 <catalog name="PyStore" type="RequestStore"><trigger name="Note" type="Py.RM.Note"/>
132 <setup><store name="Note" trigger="Note" key="note" mimetype="text"/></setup></catalog>
133</psyspec>
134"""
135
136
137class Probe:
138 """The PsyProbe 2 API, just enough to make API keys (cookie session + CSRF header)."""
139
140 def __init__(self, base):
141 self.base, self.cookie, self.csrf = base, "", ""
142
143 def post(self, path, body):
144 req = urllib.request.Request(self.base + path, data=json.dumps(body).encode(), method="POST",
145 headers={"Content-Type": "application/json"})
146 if self.cookie:
147 req.add_header("Cookie", "psy_session=" + self.cookie)
148 if self.csrf:
149 req.add_header("X-Psy-CSRF", self.csrf)
150 try:
151 with urllib.request.urlopen(req, timeout=8) as r:
152 text, sc = r.read().decode(), r.headers.get("Set-Cookie") or ""
153 except urllib.error.HTTPError as e:
154 text, sc = e.read().decode(), ""
155 m = re.search(r"psy_session=([^;]+)", sc)
156 if m:
157 self.cookie = m.group(1)
158 m = re.search(r'"csrf":"([^"]+)"', text)
159 if m:
160 self.csrf = m.group(1)
161 return text
162
163 def machine_key(self, ident, allow):
164 self.post("api/v2/accounts", {"id": ident, "kind": "machine", "role": "monitoring", "allow": allow})
165 m = re.search(r'"key":"([^"]+)"', self.post("api/v2/accounts/%s/keys" % ident, {"label": "py"}))
166 return m.group(1) if m else ""
167
168
170 try:
171 with socket.create_connection(("127.0.0.1", p), 0.3):
172 return True
173 except OSError:
174 return False
175
176
177@unittest.skipUnless(BIN and os.access(BIN, os.X_OK), "PSYCLONE_BIN=<bin/linux64/Psyclone> runs a real Psyclone")
178class Live(unittest.TestCase):
179 @classmethod
180 def setUpClass(cls):
181 cls.dir = tempfile.mkdtemp(prefix="py-remotemodule-", dir=os.environ.get("PSY_TEST_DIR"))
182 spec = os.path.join(cls.dir, "spec.xml")
183 with open(spec, "w") as f:
184 f.write(SPEC % dict(NODE=NODE, MOD=MOD, WS=WS, LEASE=LEASE, FEED=FEED, DIR=os.path.join(cls.dir, "probe")))
185 cls.log = open(os.path.join(cls.dir, "psyclone.log"), "w")
186 cls.proc = subprocess.Popen([BIN, "spec=" + spec, "port=%d" % NODE], cwd=os.path.dirname(os.path.abspath(BIN)),
187 stdout=cls.log, stderr=subprocess.STDOUT)
188 ok = wait_for(60, lambda: all(port_open(p) for p in (NODE, MOD, WS, LEASE, FEED)) and
189 os.path.exists(os.path.join(cls.dir, "probe", "setup-code.txt")))
190 if not ok:
191 cls.tearDownClass()
192 raise RuntimeError("Psyclone did not start (see %s)" % cls.dir)
193 time.sleep(1)
194 probe = Probe("http://127.0.0.1:%d/" % NODE)
195 with open(os.path.join(cls.dir, "probe", "setup-code.txt")) as f:
196 code = f.read().strip()
197 probe.post("api/v2/auth/setup", {"code": code, "user": "boss", "password": "longpassword1"})
198 cls.key = probe.machine_key("pybot", "modules.attach.Asr,modules.attach.Tts,modules.attach.Vad")
199 cls.tts_key = probe.machine_key("pytts", "modules.attach.Tts")
200 assert cls.key.startswith("psy_") and cls.tts_key.startswith("psy_"), (cls.key, cls.tts_key)
201
202 @classmethod
204 cls.proc.terminate()
205 try:
206 cls.proc.wait(10)
207 except subprocess.TimeoutExpired:
208 cls.proc.kill()
209 cls.log.close()
210 if not os.environ.get("PSY_KEEP"):
211 shutil.rmtree(cls.dir, ignore_errors=True)
212
213 def setUp(self):
214 self.clients = []
215
216 def tearDown(self):
217 for c in self.clients:
218 c.close()
219
220 def keep(self, c):
221 self.clients.append(c)
222 return c
223
224 def runner(self):
225 """Handlers off the reader thread, so they may call the blocking operations."""
226 return lambda fn: threading.Thread(target=fn, daemon=True).start()
227
228 def feed(self, n, base):
229 f = self.keep(PsycloneClient.tcp("127.0.0.1", FEED, "py-feed"))
230 self.assertTrue(f.wait_connected(5))
231 for i in range(n):
232 f.post("Audio", DataMessage().set_int("N", base + i))
233
235 c = self.keep(PsycloneClient.tcp("127.0.0.1", MOD, "py-asr"))
236 self.assertTrue(c.wait_server(5))
237 self.assertIn("modules/1", c.server_features)
238 asr = RemoteModule.attach(c, "Asr", Auth.key(self.key))
239 self.assertEqual(asr.posts, ["Note"])
240 self.assertEqual(asr.triggers.get("Audio"), "Py.RM.Audio")
241 self.assertIn("en-GB", asr.contract_xml)
242 self.assertIsNotNone(asr.wait_for_new_message(3), "no Ready trigger")
243 self.assertEqual(asr.current_trigger_name, "Go")
244 got = []
245 asr.on_trigger("Audio", got.append)
246 self.feed(5, 100)
247 self.assertTrue(wait_for(5, lambda: len(got) == 5), len(got))
248 self.assertEqual(got[0].get_string("PsyTypeName"), "Py.RM.Audio")
249 self.assertEqual(got[0].get_string("PsyFromName"), "Feed")
250 for i in range(12):
251 asr.post("Note", DataMessage().set_int("I", i))
252 asr.post_confirmed("Note", DataMessage().set_int("I", 12))
253 recent = []
254 end = time.time() + 5
255 while len(recent) != 10 and time.time() < end:
256 recent = asr.retrieve("Recent")
257 self.assertEqual(len(recent), 10)
258 self.assertTrue(all(m.get_string("PsyFromName") == "Asr" for m in recent))
259 self.assertEqual(len(asr.retrieve("Recent", max_count=3)), 3)
260 q = asr.query("Notes", DataMessage().set_string("List", "1"))
261 self.assertIn('"Note"', q.get_string("JSON", ""))
262 with self.assertRaises(RemoteModuleError) as e:
263 asr.query("Missing")
264 self.assertEqual(e.exception.status, "unknown")
265 with self.assertRaises(RemoteModuleError) as e:
266 asr.post_confirmed("Nope")
267 self.assertEqual(e.exception.status, "unknown")
268 asr.close()
269
271 c = self.keep(PsycloneClient.tcp("127.0.0.1", MOD, "py-bad"))
272 for auth, status in ((Auth.key(self.key[:-4] + "zzzz"), "denied"), (Auth.key(self.tts_key), "denied"),
273 (None, "denied")):
274 with self.assertRaises(RemoteModuleError) as e:
275 RemoteModule.attach(c, "Asr", auth)
276 self.assertEqual(e.exception.status, status)
277 with self.assertRaises(RemoteModuleError) as e:
278 RemoteModule.attach(c, "Nope", Auth.key(self.key))
279 self.assertEqual(e.exception.status, "unknown")
280
282 asr = RemoteModule.attach(self.keep(PsycloneClient.tcp("127.0.0.1", MOD, "py-asr2")), "Asr", Auth.key(self.key))
283 tts = RemoteModule.attach(self.keep(PsycloneClient.websocket("ws://127.0.0.1:%d/modules" % WS, "py-tts")), "Tts",
284 Auth.key(self.tts_key))
285 vad = RemoteModule.attach(self.keep(PsycloneClient.udp("127.0.0.1", MOD, "py-vad")), "Vad", Auth.key(self.key))
286 notes, audio = [], []
287 tts.on_trigger("Note", notes.append)
288 vad.on_trigger("Audio", audio.append)
289 asr.post("Note", DataMessage().set_string("Text", "over the wire"))
290 self.assertTrue(wait_for(5, lambda: len(notes) == 1), len(notes))
291 self.assertEqual(notes[0].get_string("PsyFromName"), "Asr")
292 self.assertEqual(notes[0].get_string("Text"), "over the wire")
293 self.feed(3, 200)
294 self.assertTrue(wait_for(5, lambda: len(audio) == 3), len(audio))
295 for m in (asr, tts, vad):
296 m.close()
297
299 m1 = RemoteModule.attach(self.keep(PsycloneClient.tcp("127.0.0.1", MOD, "py-asr-box")), "Asr", Auth.key(self.key))
300 reasons = []
301 m1.on_detached(reasons.append)
302 with self.assertRaises(RemoteModuleError) as e:
303 RemoteModule.attach(self.keep(PsycloneClient.tcp("127.0.0.1", MOD, "py-other-box")), "Asr", Auth.key(self.key))
304 self.assertEqual(e.exception.status, "busy")
305 m2 = RemoteModule.attach(self.keep(PsycloneClient.tcp("127.0.0.1", MOD, "py-asr-box")), "Asr", Auth.key(self.key))
306 self.assertTrue(wait_for(3, lambda: "takeover" in reasons), reasons)
307 self.assertEqual(m1.state, DETACHED)
308 n1, n2 = [], []
309 m1.on_trigger("Audio", n1.append)
310 m2.on_trigger("Audio", n2.append)
311 self.feed(2, 300)
312 self.assertTrue(wait_for(5, lambda: len(n2) == 2))
313 self.assertEqual(len(n1), 0)
314 m2.detach()
315 self.assertEqual(m2.state, DETACHED)
316 self.feed(1, 400)
317 time.sleep(0.3)
318 self.assertEqual(len(n2), 2)
319
321 c = self.keep(PsycloneClient.tcp("127.0.0.1", LEASE, "py-short", keepalive_interval=60.0))
322 with self.assertRaises(RemoteModuleError) as e:
323 RemoteModule.attach(c, "Short", Auth.token("wrong-token"))
324 self.assertEqual(e.exception.status, "denied")
325 m = RemoteModule.attach(c, "Short", Auth.token("py-lease-token"))
326 self.assertEqual(m.lease_ms, 1500)
327 reasons = []
328 m.on_detached(reasons.append)
329 self.assertTrue(wait_for(6, lambda: "lease" in reasons), reasons)
330 self.assertTrue(wait_for(5, lambda: m.attaches >= 2 and m.state == ATTACHED), m.attaches)
331 m.close()
332
333
334if __name__ == "__main__":
335 unittest.main()
test_attach_and_retrieve_against_a_stand_in_host(self)
machine_key(self, ident, allow)