CMSDK 2.0.1
Cross-platform C++ base library and SDK for the Psyclone AIOS platform
Loading...
Searching...
No Matches
PsySpace.cpp
Go to the documentation of this file.
1
8#include <set>
9#include <mutex>
10#include "PsySpace.h"
11
12namespace cmlabs {
13
14
16 this->interval = interval;
17 this->start = start;
18 this->end = end;
19}
20
23
24
26 timer = new utils::Timer();
27}
28
30 mutex.enter();
31 std::map<uint32, TimeQueueSchedule*>::iterator it, itEnd;
32 for (it = schedules.begin(), itEnd = schedules.end(); it!=itEnd; it++)
33 delete(it->second);
34 delete(timer);
35 mutex.leave();
36}
37
39 mutex.enter();
40 if (schedules[schedule->id]) {
41 mutex.leave();
42 return false;
43 }
44 schedules[schedule->id] = schedule;
45 mutex.leave();
46 return timer->addTimer(schedule->id, schedule->interval, schedule->start, schedule->end);
47}
48
50 mutex.enter();
51 TimeQueueSchedule* schedule = schedules[id];
52 if (!schedule) {
53 mutex.leave();
54 return true;
55 }
56 timer->removeTimer(id);
57 schedules.erase(id);
58 delete(schedule);
59 mutex.leave();
60 return true;
61}
62
64
65 uint32 id;
66 uint64 time;
67 if (!timer->waitForTimer(ms, id, time))
68 return NULL;
69
70 mutex.enter();
71 TimeQueueSchedule* schedule = schedules[id];
72 if (!schedule) {
73 mutex.leave();
74 return NULL;
75 }
76
77 DataMessage* msg = new DataMessage(schedule->msgType, 0);
78 if (schedule->msgTag)
79 msg->setTag(schedule->msgTag);
80 mutex.leave();
81 return msg;
82}
83
84
85
86
87
88
89
90PsySpace::PsySpace(const char* name, bool isAdHoc, uint16 procID, bool isLocal) {
91 isMaster = true;
92 manager = NULL;
93 masterCreatedTime = 0;
94 timeQ = new TimeQueue();
95 this->isAdHoc = isAdHoc;
96 if (name)
97 this->name = utils::TextTrimQuotes(name);
98 else
99 this->name = utils::StringFormat("Unnamed_Space_%u", (uint32)utils::RandomValue(MAXVALUINT32));
100 this->isLocal = isLocal;
101 this->procID = procID;
102 finishedShuttingDown = false;
103
104 memset(waitCounters, 0, 3*sizeof(uint32));
105 memset(procCounters, 0, 3*sizeof(uint32));
106
107 threadPoolWaitLowerThreshold = 5;
108 threadPoolWaitUpperThreshold = 20;
109 threadPoolWaitIncrement = 5;
110 lastThreadPoolCheck = GetTimeNow();
111 threadPoolCheckInterval = 5000;
112
113 internalCranks["Simple"] = Internal_Simple;
114 internalCranks["Ping"] = Internal_Ping;
115 internalCranks["Pong"] = Internal_Pong;
116 internalCranks["Shutdown"] = Internal_Shutdown;
117 internalCranks["Print"] = Internal_Print;
118 internalCranks["Time"] = Internal_Time;
119 internalCranks["SignalPing"] = Internal_SignalPing;
120 internalCranks["SignalPong"] = Internal_SignalPong;
121 internalCranks["RetrieveTest"] = Internal_RetrieveTest;
122 internalCranks["MessageScript"] = Internal_MessageScript;
123 internalCranks["QueryTest"] = Internal_QueryTest;
124 internalCranks["StatsLog"] = Internal_StatsLog;
125 internalCranks["BitmapPoster"] = Internal_BitmapPoster;
126 internalCranks["MessageToggler"] = Internal_MessageToggler;
127 internalCranks["MessageTypeConverter"] = Internal_MessageTypeConverter;
128}
129
131 reset();
132 if (timeQ) delete(timeQ);
133 timeQ = NULL;
134}
135
136bool PsySpace::connect(uint16 systemID, bool isMaster, const char* cmdline) {
137
138 // LogPrint(0, LOG_SPACE, 1, "PsySpace '%s' starting up, connecting to local Node %u...", name.c_str(), systemID);
139
140 this->isMaster = isMaster;
141
142 // Connect to MemoryManager
143 if (manager) delete(manager);
144 manager = new MemoryManager();
145 if (!manager->connect(systemID, isMaster)) {
146 // LogPrint(0, LOG_SPACE, 0, "PsySpace couldn't connect to local Node %u...", systemID);
147 delete(manager);
148 manager = NULL;
149 return false;
150 }
151 finishedShuttingDown = false;
152
153 uint16 checkID;
154 if (!isAdHoc) {
155 if (!manager->processMemory->getProcessID(name.c_str(), checkID)) {
156 LogPrint(0, LOG_SPACE, 0, "Could not find process '%s'...", name.c_str());
157 return false;
158 }
159 if (!procID)
160 procID = checkID;
161 else if (procID != checkID) {
162 LogPrint(0, LOG_SPACE, 0, "Process ID '%u' does not match shared memory id '%u'...", procID, checkID);
163 return false;
164 }
165 }
166 else {
167 if (manager->processMemory->getProcessID(name.c_str(), checkID) && checkID) {
168 procID = checkID;
169 }
170 else {
171 if (!manager->processMemory->createNewProcess(name.c_str(), procID)) {
172 LogPrint(0, LOG_SPACE, 0, "PsySpace couldn't connect to local Node %u...", systemID);
173 return false;
174 }
175 }
176 }
177
178 // Send message on sysQID to inform node that process has started
180 if (!manager->processMemory->addToCmdQ(0, msg)) {
181 LogPrint(procID, LOG_SPACE, 0, "Could not communicate with System Command Queue...");
182 delete(msg);
183 return false;
184 }
185 delete(msg);
186
187 //if (!manager->processMemory->createNewProcess(name.c_str(), procID)) {
188 // LogPrint(0, 0, 0, "Could not create Process Map\n");
189 // return false;
190 //}
191
192 if (cmdline)
193 manager->processMemory->setProcessCommandLine(procID, cmdline);
194 manager->processMemory->setProcessStatus(procID, PSYPROC_INIT);
195
196 // Connect to Node
197 // Send message on sysQID to inform node that process has started
199 if (!manager->processMemory->addToCmdQ(0, msg)) {
200 LogPrint(procID, LOG_SPACE, 0, "Could not communicate with System Command Queue...");
201 delete(msg);
202 return false;
203 }
204 delete(msg);
205
206 if (isMaster) {
207 // Logging will be done via LogPrint directly to the Node as we are in the same process
208 }
209 else {
210 //LogSystem::SetLogReceiver(this);
211 }
212
213 uint64 lastSeen;
214 manager->getNodeStatus(lastSeen, masterCreatedTime);
215
216 // Setup Heartbeat
217 manager->processMemory->setProcessStatus(procID, PSYPROC_READY);
218
219 // Start SpaceThread
221 LogPrint(procID, LOG_SPACE, 0, "Could not start PsySpace thread...");
222 return false;
223 }
224
225 return true;
226}
227
228bool PsySpace::isConnected(uint32 timeoutMS) {
229 if (!manager) return false;
230
231 uint64 lastSeen, createTime;
232 uint8 status = manager->getNodeStatus(lastSeen, createTime);
233 if (masterCreatedTime && (createTime != masterCreatedTime)) {
234 LogPrint(procID, LOG_SPACE, 0, "Psyclone Node process appears to have restarted...");
235 reset();
236 return false;
237 }
238 if (status != PSYCLONE_STATUS_READY) {
239 LogPrint(procID, LOG_SPACE, 0, "Psyclone Node process doesn't appear to be running...");
240 reset();
241 return false;
242 }
243 if (GetTimeAgeMS(lastSeen) > (int32)timeoutMS) {
244 LogPrint(procID, LOG_SPACE, 0, "Psyclone Node process appears to have stopped, resetting connection...");
245 reset();
246 return false;
247 }
248 return true;
249}
250
251// Spaces whose shutdown() is still running (16 Nov 2026): reset() must not free the memory manager while the space's
252// own run thread is still shutting it down and its pool threads still wait on it.
253static std::mutex& ShutdownInProgressMutex() { static std::mutex* m = new std::mutex(); return *m; }
254static std::multiset<PsySpace*>& ShutdownInProgress() { static std::multiset<PsySpace*>* s = new std::multiset<PsySpace*>(); return *s; }
255static bool IsShuttingDown(PsySpace* s) { std::lock_guard<std::mutex> l(ShutdownInProgressMutex()); return ShutdownInProgress().count(s) > 0; }
258 ShutdownInProgressMark(PsySpace* s) : s(s) { std::lock_guard<std::mutex> l(ShutdownInProgressMutex()); ShutdownInProgress().insert(s); }
259 ~ShutdownInProgressMark() { std::lock_guard<std::mutex> l(ShutdownInProgressMutex()); std::multiset<PsySpace*>::iterator i = ShutdownInProgress().find(s); if (i != ShutdownInProgress().end()) ShutdownInProgress().erase(i); }
260};
261
263 if (!isMaster)
265 if (manager)
266 shutdown();
267 // shutdown() returns at once while another thread is still in it: the node's shutdown command makes the space's
268 // own run thread shut it down, and the node deletes the space right after. Wait for that thread and the pool
269 // threads to leave before freeing the memory manager they wait on (Windows: access violation in
270 // ProcessMemory::waitForQ on a freed mutex in psy_sysstatus / supervisorpingpong teardown, 16 Nov 2026).
271 for (uint32 w = 0; manager && w < 600; w++) {
272 threadPoolMutex.enter(1000, __FUNCTION__);
273 size_t left = threadPool.size();
274 threadPoolMutex.leave();
275 if (!left && !isRunning && !IsShuttingDown(this))
276 break;
277 utils::Sleep(25);
278 }
279 if (manager) delete(manager);
280 manager = NULL;
281
282 std::map<std::string, utils::Library*>::iterator it = libraries.begin(), itEnd = libraries.end();
283 while (it != itEnd)
284 delete((it++)->second);
285 libraries.clear();
286
287 std::map<uint32, PsyAPI*>::iterator ait = psyAPIs.begin(), aitEnd = psyAPIs.end();
288 while (ait != aitEnd)
289 delete((ait++)->second);
290 psyAPIs.clear();
291
292 std::map<PsyType, SignalStruct*>::iterator sit = signalList.begin(), sitEnd = signalList.end();
293 while (sit != sitEnd) {
294 delete(sit->second->lastSignalMsg);
295 delete((sit++)->second);
296 }
297 signalList.clear();
298 return true;
299}
300
301bool PsySpace::start(uint16 threadCount) {
302 // Setup Threading Pool
303 LogPrint(procID, LOG_SPACE, 1, "PsySpace '%s' (%u) starting up...", name.c_str(), procID);
304 return setThreadPoolSize(threadCount);
305}
306
308 if (finishedShuttingDown)
309 return true;
310 finishedShuttingDown = true;
311 ShutdownInProgressMark inProgress(this);
312 stop();
313
314 //LogPrint(procID, LOG_SPACE, 1, "Space ID %u shutting down...", procID);
315 LogPrint(procID, LOG_SPACE, 1, "PsySpace '%s' (%u) shutting down...", name.c_str(), procID);
316
318 if (!manager->processMemory->addToCmdQ(0, msg)) {
319 LogPrint(procID, LOG_SPACE, 0, "Could not communicate with System Command Queue...");
320 delete(msg);
321 return false;
322 }
323 delete(msg);
324
325 // shutdown all components
326 std::map<uint32, PsyAPI*>::iterator it, itEnd;
327 for (it=psyAPIs.begin(), itEnd=psyAPIs.end(); it != itEnd; it++)
328 it->second->stop();
329
330 // threadPool is changed by the exiting pool threads under threadPoolMutex: read it under the same lock (ASan:
331 // heap-use-after-free iterating it here while a thread erased itself, 16 Nov 2026)
332 // Pool threads take turns on the delivery-order lock and each waits up to 100 ms on its queue, so a big pool needs
333 // pool size x ~100 ms to drain; 1 s was too short on Windows and the threads were then killed while they still
334 // waited on process memory (the freed-mutex crash). Allow up to 10 s; a normal pool leaves within a few hundred ms.
335 uint32 maxWaitCount = 200;
336 while (true) {
337 threadPoolMutex.enter(1000, __FUNCTION__);
338 size_t left = threadPool.size();
339 threadPoolMutex.leave();
340 if (!left) break;
341 utils::Sleep(50);
342 if (!(--maxWaitCount)) {
343 threadPoolMutex.enter(1000, __FUNCTION__);
344 std::map<uint32, uint8> remaining = threadPool;
345 threadPool.clear();
346 threadPoolMutex.leave();
347 LogPrint(procID, LOG_SPACE, 0, "PsySpace '%s' waited for the last %u threads to terminate, killing threads now...", name.c_str(), (uint32)remaining.size());
348 for (std::map<uint32, uint8>::iterator threadI = remaining.begin(); threadI != remaining.end(); threadI++) {
349 if (!ThreadManager::TerminateThread(threadI->first))
350 LogPrint(procID, LOG_SPACE, 0, "PsySpace '%s' couldn't kill thread %u...", name.c_str(), threadI->first);
351 else
352 LogPrint(procID, LOG_SPACE, 0, "PsySpace '%s' killed thread %u...", name.c_str(), threadI->first);
353 }
354 break;
355 }
356 }
357 while (isRunning) {
358 LogPrint(procID, LOG_SPACE,0,"PsySpace '%s' waiting for the main thread to terminate...", name.c_str());
359 utils::Sleep(50);
360 }
361
362 manager->processMemory->setProcessStatus(procID, PSYPROC_TERMINATED);
363 LogPrint(procID, LOG_SPACE, 0, "PsySpace '%s' has shut down (%u, %p)", name.c_str(), procID, this);
364 return true;
365}
366
368 return finishedShuttingDown;
369}
370
371// ***************** PsyProbe plugins *****************
372bool PsySpace::addPsyProbeCustomView(uint32 compID, const char* name, const char* templateURL) {
374 msg->setString("Name", name);
375 msg->setString("Template", templateURL);
376 manager->processMemory->addToCmdQ(0, msg);
377 delete(msg);
378 return true;
379}
380
381
383 if (!entry)
384 return false;
385
386 DataMessage* msg = new DataMessage(CTRL_LOGPRINT, procID);
387 msg->setData("LogEntry", (char*)entry, entry->size);
388 manager->processMemory->addToCmdQ(0, msg);
389 delete(msg); // DataMessage is new'd above - scalar delete is correct
390 // free(), not delete: LogEntry is a variable-size record malloc'd by its
391 // callers (PsyAPI::logPrint:1238, LogSystemPrint in Utils.cpp:335). Releasing
392 // it with operator delete is an alloc-dealloc mismatch - undefined behaviour.
393 // The two allocators sit on adjacent lines here, which is how it was missed.
394 free(entry);
395 return true;
396}
397
399 return procID;
400}
401
402bool PsySpace::setThreadPoolSize(uint16 threadCount) {
403
404 uint32 id;
405 int32 n;
406 int32 c = threadCount - (uint32)threadPool.size();
407 threadTarget = threadCount;
408// LogPrint(procID, LOG_SPACE,0,"Setting PsySpace thread pool size to %u...", threadTarget);
409 lastThreadPoolCheck = GetTimeNow();
410 if (c > 0) {
411 LogPrint(procID, LOG_SPACE,2,"Creating %u more Pool Threads [%u -> %u]...",
412 c, (uint32)threadPool.size(), threadCount);
413 // create c more threads
414 for (n=0; n<c; n++) {
416 threadPool[id] = 1;
417 else
418 return false;
419 }
420 }
421 return true;
422}
423
424PsyAPI* PsySpace::getCrankAPI(const char* name) {
425 PsyAPI* api;
426 uint16 crankID;
427 if (!manager->dataMapsMemory->getCrankID(name, crankID) || !crankID)
428 return NULL;
429
430 uint32 compID = manager->dataMapsMemory->getCrankCompID(crankID);
431 if (!compID)
432 return NULL;
433
434 uint16 oldCompNodeID = manager->componentMemory->getComponentNodeID(compID);
435 if (!oldCompNodeID)
436 return NULL;
437
438 if (!pullRemoteComponentData(compID, oldCompNodeID))
439 return NULL;
440
441 if (!threadPoolMutex.enter(1000, __FUNCTION__))
442 return NULL;
443 if (!(api = psyAPIs[crankID])) {
444 api = new PsyAPI(this);
446 api->currentCompID = compID;
447 psyAPIs[crankID] = api;
448 }
449 threadPoolMutex.leave();
450 return api;
451}
452
453bool PsySpace::registerCrankCallback(const char* name, CrankFunction func) {
454 uint16 crankID;
455 if (!manager->dataMapsMemory->getCrankID(name, crankID) || !crankID)
456 return false;
457 if (!threadPoolMutex.enter(1000, __FUNCTION__))
458 return false;
459 cranks[crankID] = func;
460 threadPoolMutex.leave();
461 return true;
462}
463
464bool PsySpace::registerInternalCrank(const char* name, CrankFunction func) {
465 if (!name || !*name || !func)
466 return false;
467 if (!threadPoolMutex.enter(1000, __FUNCTION__))
468 return false;
469 internalCranks[name] = func;
470 threadPoolMutex.leave();
471 return true;
472}
473
474uint32 PsySpace::getComponentID(const char* name) {
475 uint32 compID;
476 if (manager->componentMemory->getComponentID(name, compID))
477 return compID;
478 else
479 return 0;
480}
481
482bool PsySpace::pullRemoteComponentData(uint32 compID, uint16 fromNodeID) {
484 msg->setInt("CompID", compID);
485 msg->setInt("ProcID", this->procID);
486 msg->setInt("NodeID", fromNodeID);
487 DataMessage* resultMsg = NULL;
488 uint8 result = query(msg, &resultMsg, 5000);
489 if (resultMsg)
490 delete(resultMsg);
491 delete(msg);
492 return (result >= QUERY_SUCCESS);
493}
494
495
496//PsyAPI* PsySpace::getComponentAPI(const char* name) {
497// return getComponentAPI(getComponentID(name));
498//}
499
500//PsyAPI* PsySpace::getComponentAPI(uint32 compID) {
501// if (!compID)
502// return false;
503//}
504
505//bool PsySpace::registerComponentCallback(const char* name, CrankFunction func) {
506// return registerComponentCallback(getComponentID(name), func);
507//}
508
509//bool PsySpace::registerComponentCallback(uint32 compID, CrankFunction func) {
510// if (!compID)
511// return false;
512//}
513
514
516 // Add datamessage to memory
517 uint64 memID = 0;
518 uint64 eol = msg->getEOL();
519 if (eol && (eol < msg->getCreatedTime() - 10000))
520 return false;
521 if (eol) {
522 if (!manager->insertMessage(msg, memID)) {
523 LogPrint(procID, LOG_SPACE, 0, "Could not add message from %u to shared memory...", msg->getFrom());
524 return false;
525 }
526 msg->data->memid = memID;
527 }
528 if (!manager->processMemory->addToMsgQ(0, msg)) {
529 LogPrint(procID, LOG_SPACE, 0, "Could not communicate with System Message Queue...");
530 return false;
531 }
532 manager->processMemory->addToProcessStats(procID, NULL, msg);
533// printf("************ Space Post Msg %lld us old...\n", GetTimeAge(msg->getCreatedTime()));
534 return true;
535}
536
537
538// ***************** Signals *****************
539bool PsySpace::emitSignal(const PsyType& type, DataMessage* msg) {
540 // Send signal to local signal struct first
541 if (!signalsMutex.enter(3000, __FUNCTION__))
542 return false;
543 SignalStruct* signal = signalList[type];
544 if (!signal) {
545 signal = new SignalStruct;
546 signal->lastSignalMsg = NULL;
547 signalList[type] = signal;
548 }
549 signalsMutex.leave();
550
551 if (signal->mutex.enter(3000, __FUNCTION__)) {
552 if (signal->lastSignalMsg)
553 delete(signal->lastSignalMsg);
554 signal->lastSignalMsg = msg;
555 signal->mutex.leave();
556 signal->event.signal();
557 }
558 else {
559 return false;
560 }
561 // Then to all other procs and the other nodes (via Node proc 0)
562// if (!manager->processMemory->addToAllSignalQs(msg)) {
563 if (!manager->processMemory->addToAllSignalQsExcept(msg, procID)) {
564 LogPrint(procID, LOG_SPACE, 0, "Could not communicate with All Signal Queues...");
565 return false;
566 }
567 manager->processMemory->addToProcessStats(procID, NULL, msg);
568 return true;
569}
570
571DataMessage* PsySpace::waitForSignal(const PsyType& type, uint32 timeout, uint64 lastReceivedTime) {
572
573 if (!signalsMutex.enter(3000, __FUNCTION__))
574 return NULL;
575 SignalStruct* signal = signalList[type];
576 if (!signal) {
577 signal = new SignalStruct;
578 signal->lastSignalMsg = NULL;
579 signalList[type] = signal;
580 }
581 signalsMutex.leave();
582
583 DataMessage* msg = NULL;
584
585 if (lastReceivedTime) {
586 if (signal->mutex.enter(3000, __FUNCTION__)) {
587 if (signal->lastSignalMsg && (signal->lastSignalMsg->getCreatedTime() > lastReceivedTime)) {
588 msg = new DataMessage((char*)signal->lastSignalMsg->data, true);
589 // printf("************ Space NoWait Signal %llu us old...\n", GetTimeAge(msg->getCreatedTime()));
590 signal->mutex.leave();
591 //LogPrint(procID, LOG_SPACE, 0, "Space signal no wait success %s...", PrintTimeString(msg->getCreatedTime()).c_str());
592 manager->processMemory->addToProcessStats(procID, msg, NULL);
593 return msg;
594 }
595 else {
596 //LogPrint(procID, LOG_SPACE, 0, "Not newer %s >= %s", PrintTimeString(lastReceivedTime).c_str(),
597 // PrintTimeString(signal->lastSignalMsg->getCreatedTime()).c_str());
598 //if (lastReceivedTime > signal->lastSignalMsg->getCreatedTime())
599 // LogPrint(procID, LOG_SPACE, 0, "%llu > %llu", lastReceivedTime, signal->lastSignalMsg->getCreatedTime());
600 //else if (lastReceivedTime < signal->lastSignalMsg->getCreatedTime())
601 // LogPrint(procID, LOG_SPACE, 0, "%llu < %llu", lastReceivedTime, signal->lastSignalMsg->getCreatedTime());
602 signal->mutex.leave();
603 }
604 }
605 }
606
607 //if (signal->lastSignalMsg)
608 // LogPrint(procID, LOG_SPACE, 0, "Space signal wait (%s)...", PrintTimeString(signal->lastSignalMsg->getCreatedTime()).c_str());
609 //else
610 // LogPrint(procID, LOG_SPACE, 0, "Space signal wait...");
611
612 if (signal->event.waitNext(timeout)) {
613 //LogPrint(procID, LOG_SPACE, 0, "Space signal wait success...");
614 if (signal->mutex.enter(3000, __FUNCTION__) && signal->lastSignalMsg) {
615 if (lastReceivedTime) {
616 if (signal->lastSignalMsg->getCreatedTime() > lastReceivedTime)
617 msg = new DataMessage((char*)signal->lastSignalMsg->data, true);
618 }
619 else
620 msg = new DataMessage((char*)signal->lastSignalMsg->data, true);
621 //if (msg)
622 //printf("************ Space Wait Signal %llu us old...\n", GetTimeAge(msg->getCreatedTime()));
623 // LogPrint(procID, LOG_SPACE, 0, "Space signal wait success %s...", PrintTimeString(msg->getCreatedTime()).c_str());
624 }
625 signal->mutex.leave();
626 }
627
628 if (msg)
629 manager->processMemory->addToProcessStats(procID, msg, NULL);
630 return msg;
631}
632
633
634uint8 PsySpace::query(DataMessage* msg, DataMessage** result, uint32 timeout) {
635 *result = NULL;
636 if (!msg)
637 return QUERY_FAILED;
638
639 uint32 to = msg->getTo();
640
641 uint32 reqID;
642 if (!manager->dataMapsMemory->createNewRequest(msg->getFrom(), to, 0, reqID))
643 return QUERY_FAILED;
644// LogPrint(procID, LOG_SPACE,0,"Created Request id %u from comp %u...", reqID, msg->getFrom());
645
646 msg->setReference(reqID);
647 manager->processMemory->addToProcessStats(procID, NULL, msg);
648
649 uint16 otherNodeID = 0;
650 uint16 otherProcID = 0;
651 // If to is 0 this request is for the local Node
652 if (!to) {
653 manager->dataMapsMemory->setRequestStatus(reqID, REQ_PROCESSING_LOCAL);
654 if (!manager->processMemory->addToReqQ(0, msg)) {
655 manager->dataMapsMemory->deleteRequest(reqID);
656 return QUERY_FAILED;
657 }
658 }
659 else {
660 if (!manager->componentMemory->getComponentLocation(to, otherNodeID, otherProcID))
661 return QUERY_FAILED;
662
663 if (otherNodeID != manager->getNodeID()) {
664 manager->dataMapsMemory->setRequestStatus(reqID, REQ_PROCESSING_REMOTE);
665 if (!manager->processMemory->addToReqQ(0, msg)) {
666 manager->dataMapsMemory->deleteRequest(reqID);
667 return QUERY_FAILED;
668 }
669 }
670 else {
671 manager->dataMapsMemory->setRequestStatus(reqID, REQ_PROCESSING_LOCAL);
672 otherProcID = manager->componentMemory->getComponentProcessID(to);
673 if (!manager->processMemory->addToReqQ(otherProcID, msg)) {
674 manager->dataMapsMemory->deleteRequest(reqID);
675 return QUERY_FAILED;
676 }
677 }
678 }
679
680 uint8 status = 0;
681 uint64 time = 0;
682 uint64 msgID = 0;
683 uint64 msgEOL = 0;
684 if (!manager->dataMapsMemory->waitForRequestReply(reqID, timeout, status, time, msgID, msgEOL)) {
685 LogPrint(procID, LOG_SPACE,0,"Request reply timeout (%u) from node %u (req %u from comp %u)...",
686 status, otherNodeID, reqID, msg->getFrom());
687 manager->dataMapsMemory->deleteRequest(reqID);
688 return QUERY_TIMEOUT;
689 }
690 manager->dataMapsMemory->deleteRequest(reqID);
691
692 if (status < REQ_SUCCESS) {
693 if (status >= REQ_FAILED)
694 return QUERY_FAILED;
695 if (status == REQ_FAILED_TO_SEND)
696 LogPrint(procID, LOG_SPACE, 0, "Request failed as remote system cannot be reached (req %u from comp %u)...", reqID, msg->getFrom());
697 else
698 LogPrint(procID, LOG_SPACE,0,"Request reply failed (%u) from node %u (req %u from comp %u)...", status, otherNodeID, reqID, msg->getFrom());
699 return QUERY_NOT_REACHABLE;
700 }
701
702 if (!msgID)
703 return QUERY_SUCCESS;
704
705 if (!(*result = manager->temporalMemory->getCopyOfMessage(msgID))) {
706 LogPrint(procID, LOG_SPACE,0,"Couldn't getCopyOfMessage reply from node %u (req %u from comp %u)...", otherNodeID, reqID, msg->getFrom());
707 return QUERY_FAILED;
708 }
709
710 if (*result)
711 manager->processMemory->addToProcessStats(procID, *result, NULL);
712 return QUERY_SUCCESS;
713}
714
715bool PsySpace::queryReply(uint32 id, uint8 status, DataMessage* resultMsg) {
716
717 if (resultMsg)
718 manager->processMemory->addToProcessStats(procID, NULL, resultMsg);
719 // Check if this request was made locally
720 uint32 remoteID;
721 uint32 origin;
722 uint32 source;
723 if (!manager->dataMapsMemory->getRequestInfo(id, origin, source, remoteID)) {
724 LogPrint(procID, LOG_SPACE,0,"Couldn't find request info for local id %u", id);
725 return false;
726 }
727 // could this be a INTERSYSTEM_QUERY_REPLY
728 if (remoteID && !origin) {
729 DataMessage* netMsg = new DataMessage(PsyAPI::CTRL_INTERSYSTEM_QUERY_REPLY, source, origin, 10000);
730 // keep the local request id here, needed by the InterSystemManager
731 netMsg->setReference(id);
732 netMsg->setStatus(status);
733 if (resultMsg)
734 netMsg->setAttachedMessage("DataMessage", resultMsg);
735 manager->processMemory->addToReqQ(0, netMsg);
736 //LogPrint(procID, LOG_SPACE,3,"Replied to remote request %u (local %u) (source %u, origin %u)...", remoteID, id, source, origin);
737 delete(resultMsg);
738 delete(netMsg);
739 // dont delete this: manager->dataMapsMemory->deleteRequest(id);
740 // needed by the InterSystemManager
741 return true;
742 }
743 else if (remoteID) {
744 uint16 otherNodeID = manager->componentMemory->getComponentNodeID(origin);
745 if (otherNodeID && (otherNodeID != manager->getNodeID())) {
746 DataMessage* netMsg = new DataMessage(PsyAPI::CTRL_QUERY_REPLY, source, origin, 10000);
747 netMsg->setReference(remoteID);
748 netMsg->setStatus(status);
749 if (resultMsg)
750 netMsg->setAttachedMessage("DataMessage", resultMsg);
751 manager->processMemory->addToReqQ(0, netMsg);
752 //LogPrint(procID, LOG_SPACE,3,"Replied to remote request %u (local %u) (source %u, origin %u)...", remoteID, id, source, origin);
753 delete(resultMsg);
754 delete(netMsg);
755 return manager->dataMapsMemory->deleteRequest(id);
756 }
757 else {
758 LogPrint(procID, LOG_SPACE,0,"Couldn't find otherNode %u for remote request %u (local %u) (source %u, origin %u)...",
759 otherNodeID, remoteID, id, source, origin);
760 return false;
761 }
762 }
763
764 uint64 msgID = 0;
765 uint64 msgEOL = 0;
766 uint8 reqStatus = 0;
767
768 if (resultMsg) {
769 resultMsg->setTTL(10000000);
770 msgEOL = resultMsg->getEOL();
771 // decide on EOL ###################
772 manager->temporalMemory->insertMessage(resultMsg, msgID);
773 delete(resultMsg);
774 }
775
776 if (status == QUERY_SUCCESS) {
777 if (msgID)
778 reqStatus = REQ_SUCCESS_DATA_EOL;
779 else
780 reqStatus = REQ_SUCCESS;
781 }
782 else {
783 if (msgID)
784 reqStatus = REQ_FAILED_DATA_EOL;
785 else
786 reqStatus = REQ_FAILED;
787 }
788 return manager->dataMapsMemory->setRequestStatus(id, reqStatus, msgID, msgEOL);
789}
790
791
792
793
794
795
796
797
798
799
800
801// Ordered delivery (7 Nov 2026). Several pool threads wait on this process's message queue; each used to take a
802// message off the queue on its own and only then compete for threadPoolMutex, so two messages taken a moment apart
803// reached addInputTrigger() - and so the crank - in whichever order the threads won the lock: one poster's burst
804// arrived shuffled at its subscriber (Mimir: 20 ms voice frames played out of order, ~2% of frames up to 7 places
805// back, on a 2-core box). Now a thread holds DeliveryOrderMutex from taking a message off the queue until
806// addInputTrigger() has queued it on the crank's API (PsyAPI's input queue is FIFO), so cranks see messages in
807// queue order. Only the hand-over is serialised: the crank itself still runs outside it, on the pool thread.
808// One per process (a process runs one PsySpace); heap-allocated and never freed, because pool threads can still
809// be waiting on it while static destructors run at exit.
812 bool held = false;
813 void release() { if (held) { held = false; DeliveryOrderMutex->leave(); } }
815};
816
817bool PsySpace::threadPoolDispatch() {
818 DataMessage* msg, *dmsg;
819 uint32 threadID;
821 uint32 idleCount = 0;
822 uint8 proc;
823 char *crankName = new char[MAXVALUENAMELEN+1];
824 crankName[0] = 0;
825 char *crankFunction = new char[MAXVALUENAMELEN + 1];
826 crankFunction[0] = 0;
827 char *crankLanguage = new char[MAXVALUENAMELEN + 1];
828 crankLanguage[0] = 0;
829 char *libraryFilename = new char[MAXVALUENAMELEN + 1];
830 libraryFilename[0] = 0;
831 CrankFunction crank;
832 uint32 compID;
833 PsyAPI* api;
834 uint32 s;
835 TriggerSpec* trigger;
836
837 while (shouldContinue) {
838// printf(".");
839 DeliveryOrderHold order; // released after the hand-over, or when this iteration ends
840 threadPoolMutex.enter();
841
842// if (GetTimeAgeMS(lastThreadPoolCheck) > threadPoolCheckInterval) {
843 idleCount = waitCounters[PROCMESSAGE] + waitCounters[PROCSIGNAL] + waitCounters[PROCREQUEST];
844 // idleCount = waitCounters[PROCMESSAGE] + waitCounters[PROCSIGNAL];
845 if (idleCount < threadPoolWaitLowerThreshold)
846 setThreadPoolSize((uint16)(threadPool.size() + threadPoolWaitIncrement));
847 // else if (idleCount > threadPoolWaitLowerThreshold)
848 // setThreadPoolSize(threadPool.size() - threadPoolWaitIncrement);
849 else
850 lastThreadPoolCheck = GetTimeNow();
851// }
852
853 if (threadTarget < threadPool.size()) {
854 threadPoolMutex.leave();
855 break;
856 }
857
858 // uint64 t = GetTimeNow();
859 if ( (waitCounters[PROCMESSAGE] <= waitCounters[PROCSIGNAL]) && (waitCounters[PROCMESSAGE] <= waitCounters[PROCREQUEST]) ) {
860 // if (waitCounters[PROCMESSAGE] <= waitCounters[PROCSIGNAL]) {
861 proc = PROCMESSAGE;
862 waitCounters[proc]++;
863 threadPoolMutex.leave();
864 // one thread at a time takes from the queue and hands over (see DeliveryOrderMutex)
865 msg = NULL;
866 // untimed: a timed enter() logs every timeout, and the holder releases within ~100 ms anyway
867 if (DeliveryOrderMutex->enter()) {
868 order.held = true;
869 msg = manager->processMemory->waitForMsgQ(procID, 100);
870 if (!msg) order.release();
871 }
872 // if (msg)
873 // printf("Wait for Msg counter: %llu [%u / %u]\n", GetTimeAge(msg->getCreatedTime()), waitCounters[PROCMESSAGE], waitCounters[PROCSIGNAL]);
874 // printf("************ Space waited %llu...\n", GetTimeAge(t));
875 }
876 else if ( (waitCounters[PROCREQUEST] <= waitCounters[PROCMESSAGE]) && (waitCounters[PROCREQUEST] <= waitCounters[PROCSIGNAL]) ) {
877 proc = PROCREQUEST;
878 waitCounters[proc]++;
879 threadPoolMutex.leave();
880 msg = manager->processMemory->waitForReqQ(procID, 100);
881 //if (msg) LogPrint(procID, LOG_SPACE, 1, "Got request message, processing...");
882 }
883 else {
884 proc = PROCSIGNAL;
885 waitCounters[proc]++;
886 threadPoolMutex.leave();
887 if (msg = manager->processMemory->waitForSigQ(procID, 100)) {
888 manager->processMemory->addToProcessStats(procID, msg, NULL);
889 // printf("Wait for Signal counter: %u [%u / %u]\n", GetTimeAge(msg->getCreatedTime()), waitCounters[PROCMESSAGE], waitCounters[PROCSIGNAL]);
890 if (signalsMutex.enter(3000, __FUNCTION__)) {
891 SignalStruct* signal = signalList[msg->getType()];
892 if (!signal) {
893 signal = new SignalStruct;
894 signal->lastSignalMsg = NULL;
895 signalList[msg->getType()] = signal;
896 }
897 signalsMutex.leave();
898 if (signal->mutex.enter(3000, __FUNCTION__)) {
899 if (signal->lastSignalMsg)
900 delete(signal->lastSignalMsg);
901 signal->lastSignalMsg = msg;
902 signal->mutex.leave();
903 signal->event.signal();
904 LogPrint(procID, LOG_SPACE, 5, "Space signal signal %s...", PrintTimeString(msg->getCreatedTime()).c_str());
905 }
906 else
907 delete(msg);
908 }
909 else
910 delete(msg);
911 msg = NULL;
912 }
913 }
914 //else {
915 // proc = PROCTIMER;
916 // waitCounters[proc]++;
917 // threadPoolMutex.leave();
918 // msg = timeQ->waitForNextEvent(30);
919 //}
920 while (!threadPoolMutex.enter(1000, "Threadpool run with msg")) {
921 }
922
923 waitCounters[proc]--;
924 procCounters[proc]++;
925
926 uint16 crankID;
927 char* compName;
928 if (msg) {
929 crank = NULL;
930 crankID = 0;
931 dmsg = NULL;
932
933// printf("************ Space Deliver to %u (%lld us old) %s...\n",
934// msg->getTo(), GetTimeAge(msg->getCreatedTime()), PrintTimeString(msg->getCreatedTime()).c_str());
935 // ⚠️ BakeLive Anomaly (see BakeLiveBug.md): the four `delete(msg); continue;`
936 // paths below each discard a message that was already accepted into the
937 // component's shared queue, and they log at level 0/1 which the unit-test
938 // framework suppresses. A message lost here is therefore invisible to every
939 // instrument on either side of the process boundary.
940 // These paths were fully traced during that investigation and measured
941 // 0/0/0/0 on failing runs - they are NOT the anomaly - but keep this note:
942 // anyone hunting silent local-delivery loss should instrument here first.
943 if (!(compID = msg->getTo())) {
944 LogPrint(procID, LOG_SPACE, 1, "No compID, deleting...");
945 delete(msg);
946 procCounters[proc]--;
947 threadPoolMutex.leave();
948 continue;
949 }
950
951 manager->processMemory->addToProcessStats(procID, msg, NULL);
952
953 // a stopped component (COMPONENT_PAUSED: PsyProbe's component.stop) gets nothing until it is started again
954 if (manager->componentMemory->isComponentPaused(compID)) {
955 LogPrint(procID, LOG_SPACE, 3, "Component %u is stopped, message dropped", compID);
956 delete(msg);
957 procCounters[proc]--;
958 threadPoolMutex.leave();
959 continue;
960 }
961
962 if (msg->getType() == PsyAPI::CTRL_TRIGGER || msg->getType() == PsyAPI::CTRL_TRIGGER_GROUP) {
963 // T1.6: a CTRL_TRIGGER_GROUP joined activation carries a TriggerSpec and
964 // a primary "Message" just like CTRL_TRIGGER (plus a "Members" map read
965 // by waitForNewMessageGroup()); dispatch it through the same crank path.
966 if (!(trigger = (TriggerSpec*) msg->getData("TriggerSpec", s))) {
967 delete(msg);
968 procCounters[proc]--;
969 threadPoolMutex.leave();
970 continue;
971 }
972 crankID = trigger->crankID;
973 if (!crankID) {
974 //crank = internalCranks["Simple"];
975 LogPrint(procID, LOG_SPACE, 0, "Crank not found for component!");
976 delete (msg);
977 procCounters[proc]--;
978 threadPoolMutex.leave();
979 continue;
980 }
981
982 // Get actual data message (primary; may be absent for an empty-tag group)
983 if (!(dmsg = msg->getAttachedMessageCopy("Message"))) {
984 if (msg->getType() == PsyAPI::CTRL_TRIGGER) {
985 LogPrint(procID, LOG_SPACE, 0, "Couldn't find attached input message");
986 delete (msg);
987 procCounters[proc]--;
988 threadPoolMutex.leave();
989 continue;
990 }
991 // CTRL_TRIGGER_GROUP without a primary message is still valid: the
992 // crank consumes the member map via waitForNewMessageGroup().
993 }
994 }
995 else {
996 //LogPrint(procID, LOG_SPACE, 1, "Looking for crank for direct message to component queue");
997 if (!(crankID = compCrankIDs[compID])) {
998 compName = new char[MAXKEYNAMELEN+1];
999 if (manager->componentMemory->getComponentName(compID, compName, MAXKEYNAMELEN)) {
1000 utils::strcpyavail(compName+strlen(compName), "ComponentCrank", 20, true);
1001 if (manager->dataMapsMemory->getCrankID(compName, crankID)) {
1002 compCrankIDs[compID] = crankID;
1003 }
1004 // a module whose crank has its own name (<crank name="X">) has no "<Name>ComponentCrank":
1005 // direct messages (queries, wake-ups) go to the crank registered for it (16 Nov 2026)
1006 else if ((crankID = manager->dataMapsMemory->getComponentCrankID(compID))) {
1007 compCrankIDs[compID] = crankID;
1008 }
1009 }
1010 else
1011 compName[0] = 0;
1012 if (!crankID) {
1013 LogPrint(procID, LOG_SPACE, 0, "Unknown Component Crank for '%s' (%u)", compName, compID);
1014 delete [] compName;
1015 delete (msg);
1016 procCounters[proc]--;
1017 threadPoolMutex.leave();
1018 continue;
1019 }
1020 delete [] compName;
1021 }
1022 }
1023
1024 // Load function from already loaded cranks
1025 if (!crank && !(crank = cranks[crankID])) {
1026 manager->dataMapsMemory->getCrankName(crankID, crankName, 256);
1027 // Check if this is a scripted module
1028 if (manager->dataMapsMemory->getCrankLanguage(crankID, crankLanguage, MAXVALUENAMELEN) && crankLanguage && strlen(crankLanguage)) {
1029 utils::StringFormatInto(crankFunction, MAXVALUENAMELEN, "%sLink", utils::TextCapitalise(crankLanguage).c_str());
1030 utils::StringFormatInto(libraryFilename, MAXVALUENAMELEN, "Psy%sLink", utils::TextCapitalise(crankLanguage).c_str());
1031 LogPrint(procID, LOG_SPACE, 0, "Scripted language (%s) crank '%s' loading binary library '%s'", crankLanguage, crankName, libraryFilename);
1032 }
1033 else {
1034 // Load function from library
1035 if (!manager->dataMapsMemory->getCrankFunction(crankID, crankFunction, MAXVALUENAMELEN) || !crankFunction) {
1036 LogPrint(procID, LOG_SPACE, 0, "Unknown Crank ID %u in Trigger Message", crankID);
1037 delete (msg);
1038 procCounters[proc]--;
1039 threadPoolMutex.leave();
1040 continue;
1041 }
1042 if (!manager->dataMapsMemory->getCrankLibraryFilename(crankID, libraryFilename, MAXVALUENAMELEN) || !libraryFilename) {
1043 LogPrint(procID, LOG_SPACE, 0, "Crank '%s' doesn't have a valid library specified", crankFunction);
1044 delete (msg);
1045 procCounters[proc]--;
1046 threadPoolMutex.leave();
1047 continue;
1048 }
1049 }
1050
1051 // If crankFunction and/or libraryFilename are not yet set, accept
1052 // as the message will be added to the API queue for when the module
1053 // gets instantiated
1054
1055 if (crankFunction && strlen(crankFunction)) {
1056 if (!(crank = loadCrankFromLibrary(crankFunction, libraryFilename))) {
1057 if (strlen(crankLanguage)) {
1058 LogPrint(procID, LOG_SPACE, 0, "The language library '%s' is unavailable - the language name '%s' may be incorrect", libraryFilename, crankLanguage);
1059 }
1060 else
1061 LogPrint(procID, LOG_SPACE, 0, "Couldn't find crank '%s' in library '%s'", crankFunction, libraryFilename);
1062 delete (msg);
1063 procCounters[proc]--;
1064 threadPoolMutex.leave();
1065 continue;
1066 }
1067 cranks[crankID] = crank;
1068 }
1069 }
1070
1071 //printf("************ Space Trigger %llu us old, Msg %llu us old...\n", GetTimeAge(msg->getCreatedTime()), GetTimeAge(dmsg->getCreatedTime()));
1072
1073 // Is the crank already running
1074 if (!(api = psyAPIs[crankID])) {
1075 api = new PsyAPI(this);
1076 api->setCommandlineBasedir(utils::GetCommandLinePath().c_str());
1077 psyAPIs[crankID] = api;
1078 }
1079
1080 // ⚠️ The wrapper (msg) is a CTRL_TRIGGER envelope with its OWN serial, while the
1081 // subscriber reads getSerial() off the ATTACHED PAYLOAD (dmsg). Any future
1082 // correlation of a queued entry back to the message it carries must use the
1083 // payload's serial, not the wrapper's - conflating the two produced a
1084 // confidently wrong conclusion during the BakeLive Anomaly investigation.
1085 uint8 status;
1086 if (dmsg)
1087 status = api->addInputTrigger(crankID, compID, msg, dmsg);
1088 else if (msg->getType() == PsyAPI::CTRL_TRIGGER_GROUP)
1089 // T1.6: a group activation with no primary (e.g. empty-tag grouping)
1090 // still delivers as a trigger so waitForNewMessageGroup() sees a fresh
1091 // trigger name and reads the "Members" map off the wrapper.
1092 status = api->addInputTrigger(crankID, compID, msg, NULL);
1093 else if (msg->getString("PsyWake")) {
1094 // a started component's wake-up (Node::controlLocalComponent): run its crank once with nothing queued,
1095 // so a crank that loops until told to stop starts its loop again; the message itself is never seen
1096 // (a crank that copies its input, like Simple, would otherwise echo it to itself without end)
1097 status = api->claimForWake(crankID, compID);
1098 delete(msg);
1099 msg = NULL;
1100 if (status != CRANKAPI_IDLE) { procCounters[proc]--; threadPoolMutex.leave(); continue; }
1101 }
1102 else {
1103 //LogPrint(procID, LOG_SPACE, 1, "Added direct message to component queue");
1104 status = api->addInputTrigger(crankID, compID, NULL, msg);
1105 }
1106 // handed over in queue order: the next thread may take the next message (the crank runs below)
1107 order.release();
1108 switch(status) {
1109 case CRANKAPI_RUNNING:
1110 procCounters[proc]--;
1111 threadPoolMutex.leave();
1112 continue;
1113 case CRANKAPI_IDLE:
1114 // threadPoolMutex.leave();
1115 break;
1116 case CRANKAPI_INUSE:
1117 // A DIFFERENT crank is mid-execution on this PsyAPI, so
1118 // addInputTrigger did NOT queue the message (PsyAPI.cpp:353-356).
1119 // This used to fall into `default:` alongside CRANKAPI_FAILED and be
1120 // DELETED - silently destroying an already-delivered message.
1121 //
1122 // ⚠️ Re-queueing it here would BUSY-LOOP: PsyAPI::begin() sets
1123 // startedRunning for the whole crank execution and only finish()
1124 // clears it (PsyAPI.cpp:267/287), so this dispatch thread would pull
1125 // the message straight back off the queue, get INUSE again, and spin
1126 // hot for the entire duration of the other crank - which is worse
1127 // than the drop it replaces. So: re-queue, but yield first so the
1128 // running crank makes progress and the queue is not hammered.
1129 // The re-queue can itself fail (queue full / no growth); if it does we
1130 // ARE dropping, so say so loudly and count it rather than pretend.
1131 {
1132 DataMessage* requeue = dmsg ? dmsg : msg;
1133 DataMessage* discard = dmsg ? msg : NULL;
1134 // Release exactly once, like every other exit from this switch,
1135 // then do the re-queue OUTSIDE the pool lock (addToMsgQ takes the
1136 // process-memory mutex; nesting the two here would invert the
1137 // lock order used elsewhere in this function).
1138 procCounters[proc]--;
1139 threadPoolMutex.leave();
1140 utils::Sleep(1); // yield: do not spin on a busy crank
1141 if (!manager->processMemory->addToMsgQ(procID, requeue)) {
1142 LogPrint(procID, LOG_SPACE, 0, "Crank API busy for crank %u and "
1143 "re-queue FAILED; message DROPPED", crankID);
1144 delete(requeue);
1145 }
1146 delete(discard); // trigger wrapper is ours either way (NULL-safe)
1147 }
1148 continue;
1149 case CRANKAPI_FAILED:
1150 default:
1151 LogPrint(procID, LOG_SPACE, 0, "Couldn't add trigger to Crank API");
1152 delete(msg);
1153 delete(dmsg);
1154 procCounters[proc]--;
1155 threadPoolMutex.leave();
1156 continue;
1157 }
1158
1159 threadPoolMutex.leave();
1160 // Call function
1161 if (crank) {
1162 api->begin();
1163 do {
1164 try {
1165 if (crank(api) < 0)
1166 break;
1167 }
1168 catch (...) {
1169 LogPrint(procID, LOG_SPACE, 0, "Crank %u ('%s') caused an exception", crankID, crankName);
1170 break;
1171 }
1172 } while (api->shouldContinue() && api->getInputQueueSize());
1173 api->finish();
1174 }
1175 else
1176 // No crank yet (module not instantiated): the message stays queued on the
1177 // API for later, but addInputTrigger() CLAIMED the API on the IDLE path -
1178 // release it, or every later message gets CRANKAPI_RUNNING and nobody runs.
1179 api->finish();
1180 threadPoolMutex.enter();
1181 procCounters[proc]--;
1182 }
1183 threadPoolMutex.leave();
1184
1185 }
1186
1187 LogPrint(procID, LOG_SPACE,3,"Thread Pool %u exited, target %u, size: %u", threadID, threadTarget, threadPool.size() - 1);
1188 threadPoolMutex.enter();
1189 std::map<uint32, uint8>::iterator i = threadPool.find(threadID);
1190 if (i != threadPool.end())
1191 threadPool.erase(i);
1192 threadPoolMutex.leave();
1193 delete [] crankName;
1194 delete [] crankFunction;
1195 delete [] libraryFilename;
1196 return true;
1197}
1198
1199CrankFunction PsySpace::loadCrankFromLibrary(const char* crankName, const char* libraryFilename) {
1200 if (!crankName || !libraryFilename)
1201 return NULL;
1202
1203 if (!strlen(libraryFilename)) {
1204 // Internal cranks
1205 return internalCranks[crankName];
1206 }
1207
1208 utils::Library* lib = libraries[libraryFilename];
1209 if (!lib) {
1210 if (!(lib = utils::OpenLibrary(libraryFilename))) {
1211 LogPrint(procID, LOG_SPACE, 0, "Could not find or load library '%s'", libraryFilename);
1212 return NULL;
1213 }
1214 libraries[libraryFilename] = lib;
1215 }
1216
1217 CrankFunction crank = (CrankFunction)lib->getFunction(crankName);
1218 if (!crank) {
1219 LogPrint(procID, LOG_SPACE, 0, "Could not load Crank '%s' from library '%s'", crankName, libraryFilename);
1220 return NULL;
1221 }
1222 return crank;
1223}
1224
1225
1226bool PsySpace::startContinuousComponent(uint32 compID) {
1227
1228 std::map<uint32, uint32>::iterator it = continuousComponentThreads.find(compID);
1229 if (it != continuousComponentThreads.end())
1230 return false;
1231
1232 continuousComponentThreads[threadID] = 0;
1233
1234 uint32 threadID;
1236 return false;
1237
1238 continuousComponentThreads[threadID] = compID;
1239 return true;
1240}
1241
1242bool PsySpace::runContinuousComponent() {
1243 uint32 threadID;
1244 DataMessage* msg = NULL;
1245
1247
1248 uint32 count = 0;
1249 uint32 compID;
1250 while (!(compID = continuousComponentThreads[threadID])) {
1251 if (++count > 10)
1252 return false;
1253 utils::Sleep(50);
1254 }
1255
1256 // Find function name and library to call
1257 // Load function from library
1258 // Check stats
1259 // Call function
1260 // Record stats usage
1261
1262 return true;
1263}
1264
1265
1266bool PsySpace::run() {
1267 // Space Thread
1268 // Update Heartbeat
1269 manager->processMemory->setProcessStatus(procID, PSYPROC_ACTIVE);
1270 // Update Space Stats
1271 uint64 currentCPUTicks;
1272// utils::GetProcessCPUTicks(currentCPUTicks);
1273 uint32 checkCount = 50, c = 0;
1274 uint64 lastMsgCheck;
1275 std::map<uint32, PsyAPI*>::iterator i, e = psyAPIs.end();
1276
1277 DataMessage* cmsg;
1278 while (shouldContinue) {
1279 if (cmsg = manager->processMemory->waitForCmdQ(procID, 100)) {
1280 if (cmsg->getType() == PsyAPI::CTRL_SYSTEM_SHUTDOWN) {
1281 delete(cmsg);
1282 // reset() (the node deleting this space) waits until this thread is done with the space
1283 ShutdownInProgressMark inProgress(this);
1284 shutdown();
1285 isRunning = false;
1286 return true;
1287 }
1288 delete(cmsg);
1289 }
1290 // Update Heartbeat
1291 utils::GetProcessCPUTicks(currentCPUTicks);
1292 manager->processMemory->setProcessStatus(procID, PSYPROC_ACTIVE, currentCPUTicks);
1293
1294 if (++c > 50) {
1295 // check all apis for checkLastWaitForMessage()
1296 i = psyAPIs.begin();
1297 while (i != e) {
1298 if ((i->second) && (lastMsgCheck = i->second->checkLastWaitForMessage())) {
1299 i->second->logPrint(1, "Component has unchecked messages, last check %s ago",
1300 PrintTimeDifString(GetTimeAge(lastMsgCheck)).c_str());
1301 }
1302 i++;
1303 }
1304 c = 0;
1305 }
1306 }
1307
1308 manager->processMemory->setProcessStatus(procID, PSYPROC_SHUTTING_DOWN);
1309 //LogPrint(procID, LOG_SPACE, 1, "PsySpace '%s' shutting down...", name.c_str());
1310 isRunning = false;
1311 return true;
1312}
1313
1315 if (arg == NULL) thread_ret_val(1);
1316 thread_ret_val((int)(((PsySpace*)arg)->run() ? 0 : 1));
1317}
1318
1319
1321 if (arg == NULL) thread_ret_val(1);
1322 thread_ret_val((int)(((PsySpace*)arg)->threadPoolDispatch() ? 0 : 1));
1323}
1324
1326 if (arg == NULL) thread_ret_val(1);
1327 thread_ret_val((int)(((PsySpace*)arg)->runContinuousComponent() ? 0 : 1));
1328}
1329
1330
1331} // namespace cmlabs
#define REQ_PROCESSING_REMOTE
#define REQ_SUCCESS_DATA_EOL
#define REQ_SUCCESS
#define REQ_FAILED_DATA_EOL
#define REQ_FAILED
#define REQ_FAILED_TO_SEND
#define REQ_PROCESSING_LOCAL
#define PSYCLONE_STATUS_READY
Instance is fully operational.
#define PSYPROC_INIT
Process is initialising.
#define PSYPROC_ACTIVE
Process is actively running.
#define PSYPROC_SHUTTING_DOWN
Process is shutting down.
#define PSYPROC_TERMINATED
Process has terminated.
#define PSYPROC_READY
Process is ready to run components.
#define QUERY_NOT_REACHABLE
The target could not be reached (e.g.
Definition PsyAPI.h:62
#define QUERY_SUCCESS
The query succeeded.
Definition PsyAPI.h:60
#define CRANKAPI_RUNNING
The crank is currently executing.
Definition PsyAPI.h:40
#define QUERY_FAILED
General failure.
Definition PsyAPI.h:55
#define CRANKAPI_IDLE
The crank is idle, waiting for input.
Definition PsyAPI.h:41
#define CRANKAPI_FAILED
The API could not be obtained or is invalid.
Definition PsyAPI.h:38
#define CRANKAPI_INUSE
The API is already in use by another thread.
Definition PsyAPI.h:39
#define QUERY_TIMEOUT
No reply within the timeout.
Definition PsyAPI.h:56
The PsySpace process/node context: the runtime container in which Psyclone components (cranks) live a...
#define PROCSIGNAL
Signal processing.
Definition PsySpace.h:141
#define LOG_SPACE
Log source id used by PsySpace when writing entries to the system log.
Definition PsySpace.h:52
#define PROCREQUEST
Query/request processing.
Definition PsySpace.h:142
#define PROCMESSAGE
Ordinary trigger-message processing.
Definition PsySpace.h:140
#define MAXVALUINT32
Definition Types.h:87
#define MAXKEYNAMELEN
Definition Utils.h:85
#define thread_ret_val(ret)
Definition Utils.h:131
#define THREAD_RET
Definition Utils.h:127
#define THREAD_FUNCTION_CALL
Definition Utils.h:129
#define LogPrint
Definition Utils.h:330
#define MAXVALUENAMELEN
Definition Utils.h:86
#define THREAD_ARG
Definition Utils.h:130
The central Psyclone data container: a self-contained binary message with typed, named user entries.
bool setTTL(uint64 ttl)
setTTL(uint64 ttl)
uint32 getFrom()
getFrom() Get the sender id
bool setString(const char *key, const char *value)
setString(const char* key, const char* value)
bool setInt(const char *key, int64 value)
setInt(const char* key, int64 value)
bool setTag(uint32 tag)
setTag(uint32 tag)
DataMessageHeader * data
Pointer to the message's flat memory block (header + user entries).
bool setStatus(uint16 status)
setStatus(uint16 status)
bool setAttachedMessage(const char *key, DataMessage *msg)
setAttachedMessage(const char* key, DataMessage* msg)
bool setReference(uint64 ref)
setReference(uint64 ref) Set message reference
uint64 getEOL()
getEOL()
uint64 getCreatedTime()
getCreatedTime()
bool setData(const char *key, const char *value, uint32 size)
setData(const char* key, const char* value, uint32 size)
uint32 getTo()
getTo()
static bool SetLogReceiver(LogReceiver *rec)
Register a receiver that gets every accepted LogEntry.
Definition Utils.cpp:209
Top-level facade of the shared-memory subsystem for one process.
static struct PsyType CTRL_PROCESS_INITIALISE
Sent to a process to initialise it.
Definition PsyAPI.h:91
static struct PsyType CTRL_PROCESS_SHUTDOWN
Orders a single process to shut down.
Definition PsyAPI.h:93
static struct PsyType CTRL_PULLCOMPONENTDATA
Requests component data from another node.
Definition PsyAPI.h:101
static struct PsyType CTRL_TRIGGER_GROUP
T1.6: wraps a <triggergroup> joined-set delivery (member map) to a component.
Definition PsyAPI.h:98
static struct PsyType CTRL_TRIGGER
Wraps a trigger delivery to a component.
Definition PsyAPI.h:97
static struct PsyType CTRL_PROCESS_GREETING
Handshake from a newly joined process.
Definition PsyAPI.h:92
static struct PsyType CTRL_QUERY_REPLY
Carries a query reply back to the asker.
Definition PsyAPI.h:100
bool setCommandlineBasedir(const char *cmdlineBasedir)
Internal use only.
Definition PsyAPI.cpp:124
static struct PsyType CTRL_INTERSYSTEM_QUERY_REPLY
Reply from a different Psyclone system.
Definition PsyAPI.h:106
static struct PsyType CTRL_SYSTEM_SHUTDOWN
Orders a full system shutdown.
Definition PsyAPI.h:95
static struct PsyType CTRL_CREATECUSTOMPAGE
Registers a custom PsyProbe view.
Definition PsyAPI.h:102
The runtime container (one OS process/node context) hosting Psyclone components.
Definition PsySpace.h:164
bool postMessage(DataMessage *msg)
Post a raw message into the system for distribution to subscribers.
Definition PsySpace.cpp:515
bool reset()
Reset the space's runtime state (counters, queues) without disconnecting.
Definition PsySpace.cpp:262
bool connect(uint16 systemID, bool isMaster=false, const char *cmdline=NULL)
Join a Psyclone system (attach to the node's shared memory).
Definition PsySpace.cpp:136
bool registerInternalCrank(const char *name, CrankFunction func)
Register a built-in ("internal") crank by function name, resolved when a component's <crank function=...
Definition PsySpace.cpp:464
bool shutdown()
Request an orderly shutdown of the space and all its components.
Definition PsySpace.cpp:307
friend THREAD_RET THREAD_FUNCTION_CALL PsySpaceRun(THREAD_ARG arg)
Thread entry for the space's main service thread.
bool start(uint16 threadCount=5)
Start processing: spin up the thread pool and begin dispatching triggers.
Definition PsySpace.cpp:301
uint8 query(DataMessage *msg, DataMessage **result, uint32 timeout)
Send a query message and wait for its reply.
Definition PsySpace.cpp:634
uint32 getComponentID(const char *name)
Look up the numeric component id for a component name.
Definition PsySpace.cpp:474
DataMessage * waitForSignal(const PsyType &type, uint32 timeout, uint64 lastReceivedTime=0)
Block until a signal of the given type arrives (or has already arrived).
Definition PsySpace.cpp:571
friend THREAD_RET THREAD_FUNCTION_CALL PsySpaceContinuousRun(THREAD_ARG arg)
Thread entry for continuously running components.
~PsySpace()
Destructor.
Definition PsySpace.cpp:130
bool isConnected(uint32 timeoutMS=5000)
Wait until the space is fully connected to the system.
Definition PsySpace.cpp:228
MemoryManager * manager
The process-local memory manager: entry point to the node's shared-memory fabric. Owned by the space.
Definition PsySpace.h:339
friend class PsyAPI
Definition PsySpace.h:165
bool registerCrankCallback(const char *name, CrankFunction func)
Register a C/C++ entry function for a crank, to be invoked by the thread pool when the component trig...
Definition PsySpace.cpp:453
bool addPsyProbeCustomView(uint32 compID, const char *name, const char *templateURL)
Add a custom PsyProbe view tab for a component (space-level variant of PsyAPI::addPsyProbeCustomView(...
Definition PsySpace.cpp:372
PsyAPI * getCrankAPI(const char *name)
Get (or create) the PsyAPI handle for a crank hosted in this space.
Definition PsySpace.cpp:424
bool queryReply(uint32 id, uint8 status, DataMessage *result)
Reply to a previously received query.
Definition PsySpace.cpp:715
bool emitSignal(const PsyType &type, DataMessage *msg)
Emit a system-wide signal of the given type.
Definition PsySpace.cpp:539
bool logEntry(LogEntry *entry)
LogReceiver interface: accept a log entry produced within this space.
Definition PsySpace.cpp:382
PsySpace(const char *name=NULL, bool isAdHoc=true, uint16 procID=0, bool isLocal=false)
Create a space (does not yet join a system; call connect()).
Definition PsySpace.cpp:90
bool isRunning
Set by the worker while its loop is active.
virtual bool stop(uint32 timeout=200)
Ask the worker loop to finish and wait for it to do so.
uint32 threadID
ThreadManager slot ID of the worker thread (0 until known).
bool shouldContinue
Loop-continuation flag; cleared by stop().
static bool GetLocalThreadID(uint32 &id)
Look up the manager slot ID of the calling thread.
static bool CreateThread(THREAD_FUNCTION func, void *args, uint32 &newID, uint32 reqID=0)
Create a new native thread and start it immediately.
static bool TerminateThread(uint32 id)
Forcibly terminate the thread and release its slot.
Time-binned activation queue used by a PsySpace to drive time-triggered modules.
Definition PsySpace.h:91
DataMessage * waitForNextEvent(uint32 ms)
Block until the next scheduled event is due, or the timeout expires.
Definition PsySpace.cpp:63
bool removeSchedule(uint32 id)
Remove (and delete) a schedule by id.
Definition PsySpace.cpp:49
bool addSchedule(TimeQueueSchedule *schedule)
Add a schedule to the queue.
Definition PsySpace.cpp:38
~TimeQueue()
Destroy the queue and delete all remaining schedules (owned by the queue).
Definition PsySpace.cpp:29
TimeQueue()
Create an empty time queue with its own timer.
Definition PsySpace.cpp:25
One recurring (or time-bounded) activation schedule managed by a TimeQueue.
Definition PsySpace.h:61
uint32 msgTag
Tag attached to the generated message.
Definition PsySpace.h:80
uint64 start
First-activation time (µs), or 0 for immediate.
Definition PsySpace.h:76
PsyType msgType
Type of the message generated on each activation.
Definition PsySpace.h:79
uint32 interval
Repeat interval in milliseconds.
Definition PsySpace.h:75
TimeQueueSchedule(uint32 interval, uint64 start=0, uint64 end=0)
Create a schedule.
Definition PsySpace.cpp:15
~TimeQueueSchedule()
Destructor.
Definition PsySpace.cpp:21
uint64 end
Expiry time (µs), or 0 for no expiry.
Definition PsySpace.h:77
uint32 id
Unique schedule id, used for removal via TimeQueue::removeSchedule().
Definition PsySpace.h:72
bool waitNext()
Block until the next signal() occurs.
Definition Utils.cpp:2165
bool signal()
Wake all threads currently waiting on this event.
Definition Utils.cpp:2193
Recursive mutual-exclusion lock, optionally named for cross-process use.
Definition Utils.h:480
bool leave()
Release the mutex.
Definition Utils.cpp:1704
bool enter()
Block until the mutex is acquired.
Definition Utils.cpp:1512
Multiplexing timer: schedule many periodic timers and consume their expiries from one queue.
Definition Utils.h:703
std::string PrintTimeString(uint64 t, bool local=true, bool us=true, bool ms=true)
Definition PsyTime.cpp:676
uint64 GetTimeNow()
Return the current absolute time (µs since year 0) according to the TMC.
Definition PsyTime.cpp:69
std::string PrintTimeDifString(uint64 t, bool us=true, bool ms=true)
Definition PsyTime.cpp:722
int32 GetTimeAgeMS(uint64 t)
Age of a timestamp relative to now, in milliseconds.
Definition PsyTime.cpp:35
int64 GetTimeAge(uint64 t)
Age of a timestamp relative to now.
Definition PsyTime.cpp:25
bool Sleep(uint32 ms)
Suspend the calling thread.
Definition Utils.cpp:4078
bool GetProcessCPUTicks(uint64 &ticks)
Get accumulated CPU time of the current process.
Definition Utils.cpp:4711
uint32 strcpyavail(char *dst, const char *src, uint32 maxlen, bool copyAvailable)
Bounded strcpy that always NUL-terminates.
Definition Utils.cpp:8491
std::string GetCommandLinePath()
Get the directory portion of the executable path.
Definition Utils.cpp:6666
double RandomValue()
Uniform random double in [0,1).
Definition Utils.cpp:10131
std::string TextTrimQuotes(const char *text)
Strip a single pair of surrounding quotes if present.
Definition Utils.cpp:8586
bool StringFormatInto(char *dst, uint32 maxsize, const char *format,...)
printf into a caller-supplied buffer with truncation.
Definition Utils.cpp:9031
std::string StringFormat(const char *format,...)
printf into a std::string.
Definition Utils.cpp:9061
Library * OpenLibrary(const char *libName)
Load a library by name, applying platform filename conventions.
Definition Utils.cpp:6912
std::string TextCapitalise(const char *text)
Capitalise the first letter of text.
Definition Utils.cpp:8528
int8 Internal_QueryTest(PsyAPI *api)
Exercises query/queryReply round-trips.
int8 Internal_Pong(PsyAPI *api)
Latency test counterpart: answers pings.
int8(* CrankFunction)(PsyAPI *api)
Signature of a component (crank) entry function.
Definition PsySpace.h:49
static utils::Mutex * DeliveryOrderMutex
Definition PsySpace.cpp:810
int8 Internal_Print(PsyAPI *api)
Prints incoming messages to the console/log.
static struct PsyType CTRL_LOGPRINT
Definition ObjectIDs.h:85
static std::multiset< PsySpace * > & ShutdownInProgress()
Definition PsySpace.cpp:254
int8 Internal_Simple(PsyAPI *api)
Pass-through test crank: copies each incoming message to its posts.
int8 Internal_SignalPong(PsyAPI *api)
Signal-based pong counterpart.
int8 Internal_StatsLog(PsyAPI *api)
Periodically logs system statistics.
int8 Internal_SignalPing(PsyAPI *api)
Signal-based ping test.
THREAD_RET THREAD_FUNCTION_CALL PsySpaceContinuousRun(THREAD_ARG arg)
Continuous-component thread entry: runs PsySpace::runContinuousComponent() for the space passed in ar...
int8 Internal_MessageToggler(PsyAPI *api)
Alternates/toggles message output for testing.
int8 Internal_Shutdown(PsyAPI *api)
Initiates system shutdown when triggered.
THREAD_RET THREAD_FUNCTION_CALL PsySpaceRun(THREAD_ARG arg)
Main service-thread entry: runs PsySpace::run() for the space passed in arg.
static bool IsShuttingDown(PsySpace *s)
Definition PsySpace.cpp:255
int8 Internal_Ping(PsyAPI *api)
Latency test: posts pings, expects pongs.
int8 Internal_Time(PsyAPI *api)
Posts time information/timestamps.
THREAD_RET THREAD_FUNCTION_CALL PsySpacePoolRun(THREAD_ARG arg)
Pool worker-thread entry: runs PsySpace::threadPoolDispatch() for the space passed in arg.
int8 Internal_BitmapPoster(PsyAPI *api)
Posts test bitmap/image messages.
int8 Internal_MessageTypeConverter(PsyAPI *api)
Converts incoming messages to another type before reposting.
int8 Internal_MessageScript(PsyAPI *api)
Plays back scripted TrackPlayerMessage sequences.
int8 Internal_RetrieveTest(PsyAPI *api)
Exercises whiteboard retrieve calls.
static std::mutex & ShutdownInProgressMutex()
Definition PsySpace.cpp:253
Hierarchical message type identifier — the key used for publish/subscribe matching in Psyclone.
Definition Types.h:123
uint64 memid
Shared-memory id assigned when the message is stored in a memory map.
Wire/storage layout of one log record: fixed header immediately followed by the message text.
Definition Utils.h:245
uint32 size
Definition Utils.h:246
Per-signal bookkeeping for PsySpace signal distribution.
Definition PsySpace.h:130
utils::Mutex mutex
Protects lastSignalMsg.
Definition PsySpace.h:133
DataMessage * lastSignalMsg
Most recently emitted message for this signal type (owned by the space).
Definition PsySpace.h:131
utils::Event event
Signalled whenever a new message arrives; wakes waiters.
Definition PsySpace.h:132