CMSDK 2.0.1
Cross-platform C++ base library and SDK for the Psyclone AIOS platform
Loading...
Searching...
No Matches
PsyAPI.cpp
Go to the documentation of this file.
1
8#include "PsyAPI.h"
9
10namespace cmlabs {
11
12struct PsyType PsyAPI::CTRL_SYSTEM_READY = { { 1,10200,0,0,0,0,0,0,0,0,0,0,0,0,0,0 } };
13struct PsyType PsyAPI::CTRL_PROCESS_INITIALISE = { { 1,10201,0,0,0,0,0,0,0,0,0,0,0,0,0,0 } };
14struct PsyType PsyAPI::CTRL_PROCESS_GREETING = { { 1,10202,0,0,0,0,0,0,0,0,0,0,0,0,0,0 } };
15struct PsyType PsyAPI::CTRL_PROCESS_SHUTDOWN = { { 1,10203,0,0,0,0,0,0,0,0,0,0,0,0,0,0 } };
16struct PsyType PsyAPI::CTRL_CONTEXT_CHANGE = { { 1,10297,0,0,0,0,0,0,0,0,0,0,0,0,0,0 } };
17struct PsyType PsyAPI::CTRL_SYSTEM_SHUTDOWN = { { 1,10298,0,0,0,0,0,0,0,0,0,0,0,0,0,0 } };
18struct PsyType PsyAPI::CTRL_SYSTEM_SHUTTINGDOWN = { { 1,10299,0,0,0,0,0,0,0,0,0,0,0,0,0,0 } };
19struct PsyType PsyAPI::CTRL_TRIGGER = { { 1,10300,0,0,0,0,0,0,0,0,0,0,0,0,0,0 } };
20struct PsyType PsyAPI::CTRL_TRIGGER_GROUP = { { 1,10307,0,0,0,0,0,0,0,0,0,0,0,0,0,0 } };
21struct PsyType PsyAPI::CTRL_QUERY = { { 1,10301,0,0,0,0,0,0,0,0,0,0,0,0,0,0 } };
22struct PsyType PsyAPI::CTRL_QUERY_REPLY = { { 1,10302,0,0,0,0,0,0,0,0,0,0,0,0,0,0 } };
23struct PsyType PsyAPI::CTRL_PULLCOMPONENTDATA = { { 1,10303,0,0,0,0,0,0,0,0,0,0,0,0,0,0 } };
24struct PsyType PsyAPI::CTRL_CREATECUSTOMPAGE = { { 1,10304,0,0,0,0,0,0,0,0,0,0,0,0,0,0 } };
25struct PsyType PsyAPI::CTRL_ADDSUBSCRIPTION = { { 1,10305,0,0,0,0,0,0,0,0,0,0,0,0,0,0 } };
26struct PsyType PsyAPI::CTRL_RETRIEVESYSTEMIDS = { { 1,10306,0,0,0,0,0,0,0,0,0,0,0,0,0,0 } };
27struct PsyType PsyAPI::CTRL_INTERSYSTEM_QUERY = { { 1,10998,0,0,0,0,0,0,0,0,0,0,0,0,0,0 } };
28struct PsyType PsyAPI::CTRL_INTERSYSTEM_QUERY_REPLY = { { 1,10999,0,0,0,0,0,0,0,0,0,0,0,0,0,0 } };
29
31 this->space = space;
32 autoDelete = true;
33 startedRunning = 0;
34 shouldContinueRunning = false;
35 lastPauseCheck = 0;
36 pausedSeen = false;
37 currentCrankID = 0;
38 lastCPUTicks = 0;
39 lastWallTime = 0;
40 chainCPUTicks = 0;
41 chainWallTime = 0;
42 chainCount = 0;
43 currentCompID = 0;
44 msgReceivedCount = 0;
45 msgInputCount = 0;
46 msgSentCount = 0;
47 msgPostedCount = 0;
48 commandlineBasedir[0] = 0;
49 currentTriggerName[0] = 0;
50 currentTriggerMsg = NULL;
51 currentMsg = NULL;
52 currentSignalMsg = NULL;
53 currentTriggerSpec = NULL;
54}
55
57 apiMutex.enter(2000);
58 shouldContinueRunning = false;
59 lastPauseCheck = 0;
60 pausedSeen = false;
61 this->space = NULL;
62 delete(currentTriggerMsg);
63 currentTriggerMsg = NULL;
64 delete(currentMsg);
65 currentMsg = NULL;
66 delete(currentSignalMsg);
67 currentSignalMsg = NULL;
68 // T1.6: free any owned grouped-set member messages.
69 std::map<std::string, DataMessage*>::iterator git, gitEnd;
70 for (git = currentGroupMap.begin(), gitEnd = currentGroupMap.end(); git != gitEnd; git++)
71 if (git->second) delete(git->second);
72 currentGroupMap.clear();
73 apiMutex.leave();
74}
75
76PsyAPI* PsyAPI::fromPython(unsigned long long ptr) {
77 return (PsyAPI*)ptr;
78}
79
80const char* PsyAPI::fromPythonAddressOf(unsigned long long ptr) {
81 return (const char*)ptr;
82}
83
85 if (!apiMutex.enter(1000))
86 return false;
87 if (startedRunning) {
88 apiMutex.leave();
89 return true;
90 }
91 else {
92 apiMutex.leave();
93 return false;
94 }
95}
96
98 if (!apiMutex.enter(1000))
99 return true;
100 // a stopped component (COMPONENT_PAUSED, PsyProbe's component.stop): the crank is told to finish. Read at most
101 // every 100 ms, because cranks call this in their loop and the flag lives behind the component-memory mutex.
102 if (shouldContinueRunning && currentCompID) {
103 uint64 now = GetTimeNow();
104 if (now - lastPauseCheck > 100000) {
105 lastPauseCheck = now;
106 pausedSeen = space->manager->componentMemory->isComponentPaused(currentCompID);
107 }
108 if (pausedSeen) shouldContinueRunning = false;
109 }
110 if (shouldContinueRunning) {
111 apiMutex.leave();
112 return true;
113 }
114 else {
115 apiMutex.leave();
116 return false;
117 }
118}
119
121 return commandlineBasedir;
122}
123
124bool PsyAPI::setCommandlineBasedir(const char* cmdlineBasedir) {
125 utils::strcpyavail(commandlineBasedir, cmdlineBasedir, MAXCOMMANDLINELEN, true);
126 return true;
127}
128
129
130bool PsyAPI::getModuleName(char* name, uint32 maxSize) {
131 return space->manager->componentMemory->getComponentName(currentCompID, name, maxSize);
132}
133
135 return space->manager->componentMemory->getComponentNameString(currentCompID);
136}
137
138std::string PsyAPI::getOtherModuleName(uint32 id) {
139 return space->manager->componentMemory->getComponentNameString(id);
140}
141
142bool PsyAPI::getCurrentScriptLanguage(char* language, uint32 maxSize) {
143 return space->manager->dataMapsMemory->getCrankLanguage(currentCrankID, language, maxSize);
144}
145
147 char* language = new char[1024];
148 if (!space->manager->dataMapsMemory->getCrankLanguage(currentCrankID, language, 1024)) {
149 delete[] language;
150 return "";
151 }
152 std::string lang = language;
153 delete[] language;
154 return lang;
155}
156
157bool PsyAPI::getCurrentScript(char* script, uint32 maxSize) {
158 return space->manager->dataMapsMemory->getCrankScript(currentCrankID, script, 1024);
159}
160
162 char* script = new char[MAXSCRIPTLEN];
163 if (!space->manager->dataMapsMemory->getCrankScript(currentCrankID, script, MAXSCRIPTLEN)) {
164 delete[] script;
165 return "";
166 }
167 std::string scr = script;
168 delete[] script;
169 return scr;
170}
171
172bool PsyAPI::getCurrentScriptFilename(char* file, uint32 maxSize) {
173 return space->manager->dataMapsMemory->getCrankLibraryFilename(currentCrankID, file, 1024);
174}
175
177 char* file = new char[1024];
178 if (!space->manager->dataMapsMemory->getCrankLibraryFilename(currentCrankID, file, 1024)) {
179 delete[] file;
180 return "";
181 }
182 std::string filename = file;
183 delete[] file;
184 return filename;
185}
186
187bool PsyAPI::hasCurrentRetrieveName(const char* name) {
188 if (!apiMutex.enter(1000, __FUNCTION__))
189 return false;
190 if (currentTriggerSpec) {
191 if (currentTriggerSpec->getRetrieveSpec(name)) {
192 apiMutex.leave();
193 return true;
194 }
195 }
196 apiMutex.leave();
197 return false;
198}
199
200bool PsyAPI::hasCurrentSignalName(const char* name) {
201 if (!apiMutex.enter(1000, __FUNCTION__))
202 return false;
203 if (currentTriggerSpec) {
204 if (currentTriggerSpec->getSignalSpec(name)) {
205 apiMutex.leave();
206 return true;
207 }
208 }
209 apiMutex.leave();
210 return false;
211}
212
213
214bool PsyAPI::hasCurrentQueryName(const char* name) {
215 if (!apiMutex.enter(1000, __FUNCTION__))
216 return false;
217 if (currentTriggerSpec) {
218 if (currentTriggerSpec->getQuerySpec(name)) {
219 apiMutex.leave();
220 return true;
221 }
222 }
223 apiMutex.leave();
224 return false;
225}
226
227bool PsyAPI::hasCurrentPostName(const char* name) {
228 if (!apiMutex.enter(1000, __FUNCTION__))
229 return false;
230 if (currentTriggerSpec) {
231 if (currentTriggerSpec->getPostSpec(name)) {
232 apiMutex.leave();
233 return true;
234 }
235 }
236 apiMutex.leave();
237 return false;
238}
239
240std::set<std::string> PsyAPI::getCurrentPostNames() {
241 std::set<std::string> postNames;
242 if (!apiMutex.enter(1000, __FUNCTION__))
243 return postNames;
244 if (currentTriggerSpec) {
245 std::list<PostSpec*>* postSpecs = currentTriggerSpec->getPostSpecs(NULL);
246 if (postSpecs && postSpecs->size()) {
247 std::list<PostSpec*>::iterator it = postSpecs->begin(), itEnd = postSpecs->end();
248 while (it != itEnd) {
249 postNames.insert((*it)->name);
250 it++;
251 }
252 }
253 delete(postSpecs);
254 }
255 apiMutex.leave();
256 return postNames;
257}
258
260 if (!apiMutex.enter(1000, __FUNCTION__))
261 return 0;
262 uint32 qSize = (uint32)inputQueue.size();
263 apiMutex.leave();
264// printf("Pointer: %llu Q: %u\n", (uint64)this, qSize);
265 return qSize;
266}
267
268std::string PsyAPI::typeToText(PsyType type) {
269 return space->manager->typeToText(type);
270}
271
272std::string PsyAPI::contextToText(PsyContext context) {
273 return space->manager->contextToText(context);
274}
275
276bool PsyAPI::begin() {
277 if (!apiMutex.enter(1000))
278 return false;
279
280 shouldContinueRunning = true;
281 lastPauseCheck = 0;
282 pausedSeen = false;
283 startedRunning = GetTimeNow();
284 utils::GetCPUTicks(lastCPUTicks);
285 lastWallTime = startedRunning;
286
288 0, // cpu usage
289 NULL, // no input message here, set in waitForNewMessage
290 NULL, // no output message here
291 1, // run count 1, only incremented at start
292 0 // cycle count 0, only incremented at waitForNewMessage
293 );
294 apiMutex.leave();
295 return true;
296}
297
298bool PsyAPI::finish() {
299
300 if (!apiMutex.enter(1000))
301 return false;
302
303 startedRunning = 0;
304 currentCrankID = 0;
305 // record FINISHED (and the run's CPU time) on the component that ran: currentCompID used to be cleared first, so
306 // the stats went to id 0 and the component showed "running" for ever (PsyProbe component.restart then always
307 // waited its full 5 s for the crank to finish, and on Windows that slow reply was sometimes lost)
308 uint32 finishedCompID = currentCompID;
309 currentCompID = 0;
310
311 uint64 currentCPUTicks;
312 utils::GetCPUTicks(currentCPUTicks);
314 currentCPUTicks - lastCPUTicks, // cpu usage
315 NULL, // no input message here
316 NULL, // no output message here
317 0, // run count 0, only incremented at start
318 0 // cycle count 0, only incremented at waitForMessage
319 );
320 //utils::GetCPUUsage(cpuUsageBefore);
321 lastCPUTicks = currentCPUTicks;
322 lastWallTime = GetTimeNow();
323 apiMutex.leave();
324 return true;
325}
326
327bool PsyAPI::stop() {
328 apiMutex.enter(1000);
329 shouldContinueRunning = false;
330 apiMutex.leave();
331 return true;
332}
333
334
335
336// ***************** PsyProbe plugins *****************
337bool PsyAPI::addPsyProbeCustomView(const char* name, const char* templateURL) {
338 return space->addPsyProbeCustomView(currentCompID, name, templateURL);
339}
340
341
342
343uint64 PsyAPI::checkLastWaitForMessage() {
344 if (!apiMutex.enter(1000))
345 return CRANKAPI_FAILED;
346
347 // If currently running
348 if (startedRunning && currentCrankID) {
349 if (inputQueue.size() && (GetTimeAgeMS(lastWallTime) > 5000)) {
350 apiMutex.leave();
351 return lastWallTime;
352 }
353 }
354 apiMutex.leave();
355 return 0;
356}
357
358uint8 PsyAPI::claimForWake(uint32 crankID, uint32 compID) {
359 if (!apiMutex.enter(1000))
360 return CRANKAPI_FAILED;
361 if (startedRunning && currentCrankID) {
362 uint8 s = crankID == currentCrankID ? CRANKAPI_RUNNING : CRANKAPI_INUSE;
363 apiMutex.leave();
364 return s;
365 }
366 currentCrankID = crankID;
367 currentCompID = compID;
368 startedRunning = GetTimeNow(); // claimed here, as addInputTrigger does
369 apiMutex.leave();
370 return CRANKAPI_IDLE;
371}
372
373uint8 PsyAPI::addInputTrigger(uint32 crankID, uint32 compID, DataMessage* trigger, DataMessage* msg) {
374
375// printf("************ API Add Input Trigger %llu us old, Msg %llu us old...\n", GetTimeAge(trigger->getCreatedTime()), GetTimeAge(msg->getCreatedTime()));
376 if (!apiMutex.enter(1000))
377 return CRANKAPI_FAILED;
378
379 msgReceivedCount++;
380 if (startedRunning && currentCrankID) {
381 if (crankID == currentCrankID) {
382 // just add the trigger and msg and return
383 inputQueue.push(TriggerAndMessage(trigger, msg));
384 inputQueueSemaphore.signal();
385 apiMutex.leave();
386 return CRANKAPI_RUNNING;
387 }
388 else {
389 apiMutex.leave();
390 return CRANKAPI_INUSE;
391 }
392 }
393
394 // reset measurements
395 currentCrankID = crankID;
396 currentCompID = compID;
397 // CLAIM the API here, inside apiMutex, not later in begin(). The caller (the
398 // thread-pool dispatcher) releases its pool lock between this IDLE return and
399 // api->begin(), and the test above is "startedRunning && currentCrankID". If only
400 // begin() set startedRunning, a second pool thread delivering the next message for
401 // the same crank in that gap ALSO got CRANKAPI_IDLE, and two threads then ran the
402 // same crank on the same PsyAPI at once: one thread's waitForNewMessage()
403 // delete(currentMsg) freed the message the other had just popped (ASan:
404 // heap-use-after-free in addComponentStats <- waitForNewMessage, freed at the
405 // delete(currentMsg) line; test=udpservice crashed ~1 in 12 under a UDP burst).
406 // begin() re-stamps the time; finish() still clears it.
407 startedRunning = GetTimeNow();
408
409 // add the trigger and msg
410 inputQueue.push(TriggerAndMessage(trigger, msg));
411 inputQueueSemaphore.signal();
412
413 apiMutex.leave();
414 return CRANKAPI_IDLE;
415}
416
418 const char* triggerName;
419 return waitForNewMessage(ms, triggerName);
420}
421
423 return currentTriggerName;
424}
425
427 if (this->currentTriggerSpec)
428 return this->currentTriggerSpec->context;
429 else
430 return NOCONTEXT;
431}
432
433
434DataMessage* PsyAPI::waitForNewMessage(uint32 ms, const char* &triggerName) {
435
436 DataMessage* msg = NULL;
437 uint32 s;
438 uint64 currentCPUTicks;
439
440// if (!apiMutex.enter(ms ? ms : 10, __FUNCTION__))sig
441 if (!apiMutex.enter(1000, __FUNCTION__))
442 return NULL;
443
444 if (!inputQueue.size()) {
445 apiMutex.leave();
446 // possible queue.size without mutex issue?
447 if (!inputQueueSemaphore.wait(ms) || !inputQueue.size()) {
448 utils::GetCPUTicks(currentCPUTicks);
449 space->manager->componentMemory->addComponentStats(currentCompID, COMPSTATUS_RUNNING,
450 currentCPUTicks - lastCPUTicks, // cpu usage
451 NULL, // input message if any
452 NULL, // no output message here
453 0, // run count 0, only incremented at start
454 1 // cycle count
455 );
456 lastCPUTicks = currentCPUTicks;
457 lastWallTime = GetTimeNow();
458 chainCPUTicks = 0;
459 chainWallTime = 0;
460 chainCount = 0;
461 return NULL;
462 }
463// if (!apiMutex.enter(ms, __FUNCTION__))
464 if (!apiMutex.enter(1000, __FUNCTION__))
465 return NULL;
466 }
467
468 delete(currentMsg);
469 //delete(currentTriggerMsg);
470
471 // COPY, not a reference: the old code bound `TriggerAndMessage& tm` to
472 // inputQueue.front() and then immediately pop()ed, which destroys the element
473 // the reference names - every later read of tm (the while condition, the
474 // tm.first/tm.second extraction below) was a dangling read into a freed queue
475 // slot. ASan reports it as container-overflow. It survived because
476 // std::queue/deque usually leaves the popped slot's bytes intact, so the
477 // pointers still looked valid; under memory pressure or a different allocator
478 // it hands back whatever now occupies the slot and the two DataMessage* are
479 // then freed. TriggerAndMessage is a pair of pointers, so copying costs
480 // nothing. Found by Isaac on macOS.
481 TriggerAndMessage tm = inputQueue.front();
482 inputQueue.pop();
483
484 while ((inputQueue.size() > 100) && (tm.second->getPolicy() & MESSAGE_NON_GUARANTEED)) {
485 delete(tm.first);
486 delete(tm.second);
487 tm = inputQueue.front();
488 inputQueue.pop();
489 }
490
491 DataMessage* msgFirst = tm.first;
492 DataMessage* msgSecond = tm.second;
493
494 // If this message is a trigger message (has tm.first) replace currentTriggerXXX
495 if (msgFirst) {
496 delete(currentTriggerMsg);
497 currentTriggerMsg = msgFirst;
498 currentTriggerSpec = (TriggerSpec*)currentTriggerMsg->getData("TriggerSpec", s);
499 utils::strcpyavail(currentTriggerName, currentTriggerSpec->name, MAXKEYNAMELEN, true);
500 triggerName = currentTriggerName;
501 }
502 else {
503 // this is a temporary query message, keep the previous currentTriggerXXX around
504 triggerName = NULL;
505 }
506
507 //currentTriggerMsg = msgFirst;
508 //if (currentTriggerMsg) {
509 // currentTriggerSpec = (TriggerSpec*) currentTriggerMsg->getData("TriggerSpec", s);
510 // utils::strcpyavail(currentTriggerName, currentTriggerSpec->name, MAXKEYNAMELEN, true);
511 // triggerName = currentTriggerName;
512 //}
513 //else {
514 // triggerName = NULL;
515 // currentTriggerSpec = NULL;
516 //}
517 msg = msgSecond;
518 if (autoDelete)
519 currentMsg = msg;
520
521// printf("************ API Trigger %llu us old, Msg %llu us old...\n", GetTimeAge(currentTriggerMsg->getCreatedTime()), GetTimeAge(msg->getCreatedTime()));
522
523 if (msgFirst && msgSecond) {
524 chainCPUTicks = msgSecond->data->chaincputime;
525 chainWallTime = msgSecond->data->chainwalltime;
526 chainCount = msgSecond->data->chaincount;
527 }
528 else {
529 chainCPUTicks = 0;
530 chainWallTime = 0;
531 chainCount = 0;
532 }
533
534 // calc stats
535 apiMutex.leave();
536
537 // Add stats to component
538 utils::GetCPUTicks(currentCPUTicks);
539 space->manager->componentMemory->addComponentStats(currentCompID, COMPSTATUS_RUNNING,
540 currentCPUTicks - lastCPUTicks, // cpu usage
541 msg, // input message if any
542 NULL, // no output message here
543 0, // run count 0, only incremented at start
544 1 // cycle count
545 );
546 lastCPUTicks = currentCPUTicks;
547 lastWallTime = GetTimeNow();
548
549 msgInputCount++;
550 return msg;
551}
552
553
554// T1.6: wait for a joined <triggergroup> set. Reuses waitForNewMessage() to dequeue
555// (which sets currentTriggerMsg + currentTriggerName), then reads the member map that
556// deliverTriggerGroup() attached under "Members". If the dequeued delivery is not a
557// group activation, returns an empty map (and the group name is empty).
558std::map<std::string, DataMessage*> PsyAPI::waitForNewMessageGroup(uint32 ms, std::string& groupName) {
559 // Free any member messages we own from the previous grouped activation.
560 std::map<std::string, DataMessage*>::iterator git, gitEnd;
561 for (git = currentGroupMap.begin(), gitEnd = currentGroupMap.end(); git != gitEnd; git++)
562 if (git->second) delete(git->second);
563 currentGroupMap.clear();
564 groupName.clear();
565
566 const char* triggerName = NULL;
567 DataMessage* primary = waitForNewMessage(ms, triggerName);
568 // currentTriggerMsg is the delivery wrapper; it persists across timeout polls, so
569 // only treat this as a group delivery when waitForNewMessage() actually dequeued a
570 // fresh trigger this call (triggerName is non-NULL only for a fresh trigger msg).
571 // Without this guard a completed group re-fires on every subsequent timeout poll.
572 if (triggerName && currentTriggerMsg && currentTriggerMsg->getType() == CTRL_TRIGGER_GROUP) {
573 currentGroupMap = currentTriggerMsg->getAttachedMessageMap("Members");
574 groupName = triggerName;
575 }
576 else if (triggerName && primary) {
577 // Not a group delivery: hand back the single message under its trigger name so a
578 // crank calling only waitForNewMessageGroup() still sees something sensible.
579 if (triggerName) groupName = triggerName;
580 // Note: 'primary' is owned by the API (currentMsg); we do NOT copy it into the
581 // owned map to avoid a double free. Callers mixing both APIs should prefer one.
582 }
583 return currentGroupMap;
584}
585
586bool PsyAPI::setAutoDelete(bool autodel) {
587 autoDelete = autodel;
588 return true;
589}
590
591// Get current message receive time
593 uint64 t;
594 if (currentTriggerMsg && (t = currentTriggerMsg->getRecvTime()) )
595 return t;
596 else if (currentMsg)
597 return currentMsg->getRecvTime();
598 else
599 return 0;
600}
601
603 if (msgType == NOTYPE)
604 return postOutputMessage(NULL, msg);
605 if (msg) {
606 msg->setType(msgType);
607 return postOutputMessage(NULL, msg);
608 }
609 DataMessage* newMsg = new DataMessage(msgType, 0);
610 bool result = postOutputMessage("A non-existing postname", newMsg);
611 delete(newMsg);
612 return result;
613}
614
615
616int32 PsyAPI::postOutputMessage(const char* postName, DataMessage* msg) {
617
618 uint64 currentCPUTicks;
619 utils::GetCPUTicks(currentCPUTicks);
620
621 if (!apiMutex.enter(1000))
622 return POST_FAILED;
623
624 if (msg)
625 msg->addTimeUsage((uint32)(currentCPUTicks - lastCPUTicks), (uint32)GetTimeAge(lastWallTime), chainCPUTicks, chainWallTime, chainCount + 1);
626
627 uint32 currentTag = 0;
628 if (currentMsg)
629 currentTag = currentMsg->getTag();
630
631 uint32 to;
632 int32 failed = 0;
633 int32 success = 0;
634 if (!currentTriggerSpec) {
635 if (!msg) {
636 apiMutex.leave();
637 logPrint(1, "Posting none - out of context");
638 return POST_OUTOFCONTEXT;
639 }
640 if (currentTag && !msg->getTag())
641 msg->setTag(currentTag);
642 if ( (to = msg->getTo()) || msg->getType().isValid()) {
643 if (space->postMessage(msg)) {
644 //logPrint(3,"Posted direct message to component %u", to);
645 success++;
646 }
647 else {
648 logPrint(0,"Failed to post direct message to component %u", to);
649 failed++;
650 }
651 }
652 else {
653 apiMutex.leave();
654 logPrint(1,"Posting none - out of context");
655 delete(msg);
656 return POST_OUTOFCONTEXT;
657 }
658 }
659 else {
660 PostSpec* postSpec;
661 std::list<PostSpec*>* postSpecs = currentTriggerSpec->getPostSpecs(postName);
662 if (!postSpecs || !postSpecs->size()) {
663 delete(postSpecs);
664 postSpecs = NULL;
665 if (msg)
666 postSpecs = currentTriggerSpec->getPostSpecs(msg->getType());
667 if (!postSpecs || !postSpecs->size()) {
668 delete(postSpecs);
669 apiMutex.leave();
670 logPrint(2, "Posting nothing - no post specs match for post name '%s'", postName);
671 //logPrint(0, "Posting nothing - no post specs match for post name '%s'\n%s",
672 // postName, currentTriggerSpec->toXML().c_str());
673 delete(msg);
674 return POST_NOSPEC;
675 }
676 }
677
678 uint64 msgTTL = 0;
679 if (!msg) {
680 msg = new DataMessage();
681 msg->addTimeUsage((uint32)(currentCPUTicks - lastCPUTicks), (uint32)GetTimeAge(lastWallTime), chainCPUTicks, chainWallTime, chainCount + 1);
682 }
683 else
684 msgTTL = msg->getTTL();
685
686 if (currentTag && !msg->getTag())
687 msg->setTag(currentTag);
688
689 // uint32 msgTTL = msg->getTTL();
690
691 std::list<PostSpec*>::iterator it = postSpecs->begin(), itEnd = postSpecs->end();
692 while (it != itEnd) {
693 if (postSpec = *it) {
694 if (postSpec->contextchange.isValid()) {
696 msg->setContextChange(postSpec->contextchange);
697 // msg->setData("Context", &postSpec->contextchange, sizeof(PsyContext));
698 }
699 else {
700 msg->setType(postSpec->type);
701 }
702 postSpec->addContentToMsg(msg);
703 //if (strlen(postSpec->contentKey) && !msg->getString(postSpec->contentKey))
704 // msg->setString(postSpec->contentKey, postSpec->content);
705 msg->setMultiple(currentCompID, postSpec->to, postSpec->tag, msgTTL ? msgTTL : postSpec->ttl, postSpec->policy, GetTimeNow());
706
707 if (space->postMessage(msg)) {
708 //logPrint(3,"Posted msg delivered to %u", postSpec->to);
709 success++;
710 }
711 else {
712 logPrint(0,"Failed to deliver posted msg to %u", postSpec->to);
713 failed++;
714 }
715 }
716 it++;
717 }
718 delete(postSpecs);
719 }
720
721 msgPostedCount++;
722 msgSentCount += success;
723
724 if (!success)
725 logPrint(0,"No msgs were delivered at postOutputMessage", success);
726 //else
727 // logPrint(3,"Posted msg was delivered to %u receivers", success);
728
729 // Add stats to component
730 space->manager->componentMemory->addComponentStats(currentCompID, COMPSTATUS_RUNNING,
731 currentCPUTicks - lastCPUTicks, // cpu usage
732 NULL, // no input message here
733 msg, // output message
734 0, // run count 0, only incremented at start
735 0 // cycle count 0, only incremented at waitForNewMessage
736 );
737 // utils::GetCPUUsage(cpuUserBefore, cpuKernelBefore);
738 lastCPUTicks = currentCPUTicks;
739
740 apiMutex.leave();
741 delete(msg);
742 if (!success && failed)
743 return POST_FAILED;
744 else
745 return success;
746}
747
748// ***************** Signals *****************
749bool PsyAPI::emitSignal(const char* name, DataMessage* msg) {
750
751 if (!apiMutex.enter(1000))
752 return false;
753
754 if (!currentTriggerSpec) {
755 apiMutex.leave();
756 delete(msg);
757 return false;
758 }
759
760 SignalSpec* signalSpec = currentTriggerSpec->getSignalSpec(name);
761 if (!signalSpec) {
762 apiMutex.leave();
763 delete(msg);
764 return false;
765 }
766
767 if (!msg)
768 msg = new DataMessage();
769 msg->setType(signalSpec->type);
770 if (space->emitSignal(signalSpec->type, msg)) {
771 apiMutex.leave();
772 return true;
773 }
774 else {
775 apiMutex.leave();
776 delete(msg);
777 return false;
778 }
779}
780
781DataMessage* PsyAPI::waitForSignal(const char* name, uint32 timeout, uint64 lastReceivedTime) {
782
783 apiMutex.enter(3000, __FUNCTION__);
784
785 if (!currentTriggerSpec) {
786 apiMutex.leave();
787 return NULL;
788 }
789
790 SignalSpec* signalSpec = currentTriggerSpec->getSignalSpec(name);
791 if (!signalSpec) {
792 apiMutex.leave();
793 return NULL;
794 }
795
796 apiMutex.leave();
797 DataMessage* msg = space->waitForSignal(signalSpec->type, timeout, lastReceivedTime);
798
799 if (msg) {
800 apiMutex.enter(3000, __FUNCTION__);
801 if (currentSignalMsg)
802 delete(currentSignalMsg);
803 currentSignalMsg = msg;
804 apiMutex.leave();
805 return msg;
806 }
807 else
808 return NULL;
809}
810
811
812
813uint8 PsyAPI::retrieve(std::list<DataMessage*> &result, const char* name, uint32 maxcount, uint32 maxage, uint32 timeout) {
814 if (!apiMutex.enter(1000))
815 return QUERY_FAILED;
816
817 if (!currentTriggerSpec) {
818 apiMutex.leave();
819 return QUERY_FAILED;
820 }
821
822 RetrieveSpec* retrieveSpec = currentTriggerSpec->getRetrieveSpec(name);
823 if (!retrieveSpec) {
824 apiMutex.leave();
825 return QUERY_NAME_UNKNOWN;
826 }
827
828 RetrieveSpec* specCopy = new RetrieveSpec;
829 memcpy(specCopy, retrieveSpec, sizeof(RetrieveSpec));
830
831 if (maxcount)
832 specCopy->maxcount = maxcount;
833 if (maxage)
834 specCopy->maxage = maxage;
835
836 apiMutex.leave();
837 uint8 res = retrieve(result, specCopy, timeout);
838 return res;
839}
840
841uint8 PsyAPI::retrieveTimeParam(std::list<DataMessage*> &result, const char* name, uint64 startTime, uint64 endTime, uint32 maxcount, uint32 maxage, uint32 timeout) {
842 std::list<DataMessage*> list;
843 if (!startTime)
844 return QUERY_FAILED;
845 if (!apiMutex.enter(1000))
846 return QUERY_FAILED;
847
848 if (!currentTriggerSpec) {
849 apiMutex.leave();
850 return QUERY_FAILED;
851 }
852
853 RetrieveSpec* retrieveSpec = currentTriggerSpec->getRetrieveSpec(name);
854 if (!retrieveSpec) {
855 apiMutex.leave();
856 return QUERY_NAME_UNKNOWN;
857 }
858
859 RetrieveSpec* specCopy = new RetrieveSpec;
860 memcpy(specCopy, retrieveSpec, sizeof(RetrieveSpec));
861
862 specCopy->startTime = startTime;
863 if (endTime)
864 specCopy->endTime = endTime;
865 if (maxcount)
866 specCopy->maxcount = maxcount;
867 if (maxage)
868 specCopy->maxage = maxage;
869
870 apiMutex.leave();
871 uint8 res = retrieve(result, specCopy, timeout);
872 return res;
873}
874
875uint8 PsyAPI::retrieveStringParam(std::list<DataMessage*> &result, const char* name, const char* startString, const char* endString, uint32 maxcount, uint32 maxage, uint32 timeout) {
876 std::list<DataMessage*> list;
877 if (!startString || !strlen(startString))
878 return QUERY_FAILED;
879
880 if (!apiMutex.enter(1000))
881 return QUERY_FAILED;
882
883 if (!currentTriggerSpec) {
884 apiMutex.leave();
885 return QUERY_FAILED;
886 }
887
888 RetrieveSpec* retrieveSpec = currentTriggerSpec->getRetrieveSpec(name);
889 if (!retrieveSpec) {
890 apiMutex.leave();
891 return QUERY_NAME_UNKNOWN;
892 }
893
894 RetrieveSpec* specCopy = new RetrieveSpec;
895 memcpy(specCopy, retrieveSpec, sizeof(RetrieveSpec));
896
897 utils::strcpyavail(specCopy->startString, startString, MAXVALUENAMELEN, true);
898 if (endString)
899 utils::strcpyavail(specCopy->endString, endString, MAXVALUENAMELEN, true);
900 if (maxcount)
901 specCopy->maxcount = maxcount;
902 if (maxage)
903 specCopy->maxage = maxage;
904
905 apiMutex.leave();
906 uint8 res = retrieve(result, specCopy, timeout);
907 return res;
908}
909
910uint8 PsyAPI::retrieveIntegerParam(std::list<DataMessage*> &result, const char* name, int64 startInteger, int64 endInteger, uint32 maxcount, uint32 maxage, uint32 timeout) {
911 std::list<DataMessage*> list;
912 if (startInteger == INT64_NOVALUE)
913 return QUERY_FAILED;
914
915 if (!apiMutex.enter(1000))
916 return QUERY_FAILED;
917
918 if (!currentTriggerSpec) {
919 apiMutex.leave();
920 return QUERY_FAILED;
921 }
922
923 RetrieveSpec* retrieveSpec = currentTriggerSpec->getRetrieveSpec(name);
924 if (!retrieveSpec) {
925 apiMutex.leave();
926 return QUERY_NAME_UNKNOWN;
927 }
928
929 RetrieveSpec* specCopy = new RetrieveSpec;
930 memcpy(specCopy, retrieveSpec, sizeof(RetrieveSpec));
931
932 specCopy->startInt = startInteger;
933 if (endInteger != INT64_NOVALUE)
934 specCopy->endInt = endInteger;
935 if (maxcount)
936 specCopy->maxcount = maxcount;
937 if (maxage)
938 specCopy->maxage = maxage;
939
940 apiMutex.leave();
941 uint8 res = retrieve(result, specCopy, timeout);
942 return res;
943}
944
945uint8 PsyAPI::retrieveFloatParam(std::list<DataMessage*> &result, const char* name, float64 startFloat, float64 endFloat, uint32 maxcount, uint32 maxage, uint32 timeout) {
946 std::list<DataMessage*> list;
947 if (startFloat == FLOAT64_NOVALUE)
948 return QUERY_FAILED;
949 if (!apiMutex.enter(1000))
950 return QUERY_FAILED;
951
952 if (!currentTriggerSpec) {
953 apiMutex.leave();
954 return QUERY_FAILED;
955 }
956
957 RetrieveSpec* retrieveSpec = currentTriggerSpec->getRetrieveSpec(name);
958 if (!retrieveSpec) {
959 apiMutex.leave();
960 return QUERY_NAME_UNKNOWN;
961 }
962
963 RetrieveSpec* specCopy = new RetrieveSpec;
964 memcpy(specCopy, retrieveSpec, sizeof(RetrieveSpec));
965
966 specCopy->startFloat = startFloat;
967 if (endFloat != FLOAT64_NOVALUE)
968 specCopy->endFloat = endFloat;
969 if (maxcount)
970 specCopy->maxcount = maxcount;
971 if (maxage)
972 specCopy->maxage = maxage;
973
974 apiMutex.leave();
975 uint8 res = retrieve(result, specCopy, timeout);
976 return res;
977}
978
979uint8 PsyAPI::retrieve(std::list<DataMessage*> &result, RetrieveSpec* spec, uint32 timeout) {
980 if (!spec)
981 return QUERY_FAILED;
982 spec->origin = currentCompID;
983
984 DataMessage* msg = new DataMessage(PsyAPI::CTRL_QUERY, this->currentCompID, spec->source, timeout);
985 msg->setData("RetrieveSpec", (char*)spec, sizeof(RetrieveSpec));
986
987 DataMessage* resultMsg = NULL;
988 uint8 status = space->query(msg, &resultMsg, timeout);
989 delete(msg);
990
991 if (!resultMsg) {
992 if (status == QUERY_FAILED)
993 logPrint(0,"Query failed and did not return a message...");
994 delete(spec);
995 return status;
996 }
997
998 uint32 size;
999 int64 count;
1000 const char* data = resultMsg->getData("ReplyData", size);
1001 if (!data || !resultMsg->getInt("ReplyCount", count)) {
1002 if (!data)
1003 logPrint(0,"Query did not return any ReplyData...");
1004 else
1005 logPrint(0,"Query did not return any ReplyCount...");
1006 delete(resultMsg);
1007 delete(spec);
1008 return QUERY_FAILED;
1009 }
1010
1011 DataMessage* subMsg;
1012 const char* src = data;
1013 for (uint32 n=0; n<(uint32)count; n++) {
1014 if (GetObjID(src) != DATAMESSAGEID)
1015 break;
1016 subMsg = new DataMessage(src);
1017 result.push_back(subMsg);
1018 src += subMsg->getSize();
1019 }
1020
1021 delete(spec);
1022 delete(resultMsg);
1023 return QUERY_SUCCESS;
1024}
1025
1026bool PsyAPI::addSubscription(const char* xml) {
1027 if (!apiMutex.enter(1000))
1028 return false;
1029 DataMessage* msg = new DataMessage(PsyAPI::CTRL_ADDSUBSCRIPTION, this->currentCompID, 0, 5000);
1030 msg->setString("Subscription", xml);
1031
1032 DataMessage* resultMsg = NULL;
1033 uint8 status = space->query(msg, &resultMsg, 5000);
1034 delete(msg);
1035
1036 if (resultMsg)
1037 delete(resultMsg);
1038
1039 apiMutex.leave();
1040 return (status == QUERY_SUCCESS);
1041}
1042
1043
1044uint8 PsyAPI::queryCatalog(DataMessage** resultMsg, const char* name, DataMessage* msg, uint32 timeout) {
1045 *resultMsg = NULL;
1046 if (!msg)
1047 return QUERY_FAILED;
1048 if (!apiMutex.enter(1000))
1049 return QUERY_FAILED;
1050
1051 if (!currentTriggerSpec) {
1052 logPrint(1, "Query '%s' cannot execute before a trigger message has been processed", name);
1053 apiMutex.leave();
1054 return QUERY_FAILED;
1055 }
1056
1057 QuerySpec* querySpec = currentTriggerSpec->getQuerySpec(name);
1058 if (!querySpec) {
1059 logPrint(1, "Query '%s' not found in PsySpec", name);
1060 apiMutex.leave();
1061 return QUERY_NAME_UNKNOWN;
1062 }
1063
1064 if (strlen(querySpec->operation))
1065 msg->setString("Operation", querySpec->operation);
1066 if (strlen(querySpec->type))
1067 msg->setString("Type", querySpec->type);
1068 if (strlen(querySpec->ext))
1069 msg->setString("Ext", querySpec->ext);
1070 if (strlen(querySpec->subdir))
1071 msg->setString("Subdir", querySpec->subdir);
1072 if (strlen(querySpec->key))
1073 msg->setString("Key", querySpec->key);
1074 if (strlen(querySpec->value))
1075 msg->setString("Value", querySpec->value);
1076 if (querySpec->binary)
1077 msg->setString("Binary", "yes");
1078
1079 if (strlen(querySpec->hostName)) {
1080 // This is a query for another system
1081 if (!querySpec->ipHost) {
1082 if (!utils::LookupIPAddress(querySpec->hostName, querySpec->ipHost)) {
1083 apiMutex.leave();
1085 }
1086 }
1087 if (!querySpec->ipPort)
1088 querySpec->ipPort = 10000;
1089 // now we have all the info we need
1091 msg->setFrom(currentCompID);
1092 msg->setTo(0);
1093 msg->setString("INTERSYSTEM_SOURCENAME", querySpec->sourceName);
1094 msg->setInt("INTERSYSTEM_ADDRESS", querySpec->ipHost);
1095 msg->setInt("INTERSYSTEM_PORT", querySpec->ipPort);
1096 }
1097 else {
1099 msg->setFrom(currentCompID);
1100 msg->setTo(querySpec->source);
1101 }
1102
1103 apiMutex.leave();
1104 uint8 status = space->query(msg, resultMsg, timeout);
1105 delete(msg);
1106
1107 return status;
1108}
1109
1110uint8 PsyAPI::queryRemoteCatalog(DataMessage** resultMsg, const char* componentName, const char* ipAddress, uint16 port, DataMessage* msg, uint32 timeout) {
1111 uint32 addr = 0;
1112 if (!utils::LookupIPAddress(ipAddress, addr))
1113 return QUERY_NOT_AVAILABLE;
1114 return queryRemoteCatalog(resultMsg, componentName, addr, port, msg, timeout);
1115}
1116
1117uint8 PsyAPI::queryRemoteCatalog(DataMessage** resultMsg, uint32& chosenAddress, const char* componentName, uint32* ipAddresses, uint32 numAddresses, uint16 port, DataMessage* msg, uint32 timeout) {
1118 if (chosenAddress > numAddresses)
1119 return QUERY_NOT_AVAILABLE;
1120
1121 uint8 result;
1122 if (chosenAddress) {
1123 // try this address first
1124 result = queryRemoteCatalog(resultMsg, componentName, ipAddresses[chosenAddress-1], port, msg, timeout);
1125 if (result != QUERY_NOT_REACHABLE)
1126 return result;
1127 // if it failed, go back and try all again
1128 }
1129
1130 chosenAddress = 0;
1131 for (uint32 n = 0; n < numAddresses; n++) {
1132 result = queryRemoteCatalog(resultMsg, componentName, ipAddresses[n], port, msg, timeout);
1133 if (result != QUERY_NOT_REACHABLE) {
1134 chosenAddress = n + 1;
1135 return result;
1136 }
1137 // else continue trying next address
1138 }
1139 // and give up if none of them connects
1140 return QUERY_NOT_REACHABLE;
1141}
1142
1143uint8 PsyAPI::queryRemoteCatalog(DataMessage** resultMsg, const char* componentName, uint32 ipAddress, uint16 port, DataMessage* msg, uint32 timeout) {
1144 *resultMsg = NULL;
1145 if (!msg)
1146 return QUERY_FAILED;
1147
1148 // This is a query for another system
1149 // we have all the info we need
1151 msg->setFrom(currentCompID);
1152 msg->setTo(0);
1153 msg->setString("INTERSYSTEM_SOURCENAME", componentName);
1154 msg->setInt("INTERSYSTEM_ADDRESS", ipAddress);
1155 msg->setInt("INTERSYSTEM_PORT", port);
1156
1157 uint8 status = space->query(msg, resultMsg, timeout);
1158 delete(msg);
1159
1160 return status;
1161}
1162
1163
1164
1165
1166uint8 PsyAPI::queryCatalog(char** result, uint32 &resultsize, const char* name, const char* query, const char* operation, const char* data, uint32 datasize, uint32 timeout) {
1167 *result = NULL;
1168 if (!apiMutex.enter(1000, "Replying to query"))
1169 return QUERY_FAILED;
1170
1171 if (!currentTriggerSpec) {
1172 apiMutex.leave();
1173 return QUERY_FAILED;
1174 }
1175
1176 QuerySpec* querySpec = currentTriggerSpec->getQuerySpec(name);
1177 if (!querySpec) {
1178 apiMutex.leave();
1179 return QUERY_NAME_UNKNOWN;
1180 }
1181
1182 DataMessage* msg = new DataMessage();
1183
1184 msg->setString("Name", querySpec->name);
1185
1186 if (query && strlen(query))
1187 msg->setString("Query", query);
1188 if (data && datasize)
1189 msg->setData("Data", data, datasize);
1190 if (operation && strlen(operation))
1191 msg->setString("Operation", operation);
1192 else if (strlen(querySpec->operation))
1193 msg->setString("Operation", querySpec->operation);
1194
1195 if (strlen(querySpec->type))
1196 msg->setString("Type", querySpec->type);
1197 if (strlen(querySpec->ext))
1198 msg->setString("Ext", querySpec->ext);
1199 if (strlen(querySpec->subdir))
1200 msg->setString("Subdir", querySpec->subdir);
1201 if (strlen(querySpec->key))
1202 msg->setString("Key", querySpec->key);
1203 if (strlen(querySpec->value))
1204 msg->setString("Value", querySpec->value);
1205 if (querySpec->binary)
1206 msg->setString("Binary", "yes");
1207
1208 if (strlen(querySpec->hostName)) {
1209 // This is a query for another system
1210 if (!querySpec->ipHost) {
1211 if (!utils::LookupIPAddress(querySpec->hostName, querySpec->ipHost)) {
1212 apiMutex.leave();
1214 }
1215 }
1216 if (!querySpec->ipPort)
1217 querySpec->ipPort = 10000;
1218 // now we have all the info we need
1220 msg->setFrom(currentCompID);
1221 msg->setTo(0);
1222 msg->setString("INTERSYSTEM_SOURCENAME", querySpec->sourceName);
1223 msg->setInt("INTERSYSTEM_ADDRESS", querySpec->ipHost);
1224 msg->setInt("INTERSYSTEM_PORT", querySpec->ipPort);
1225 }
1226 else {
1228 msg->setFrom(currentCompID);
1229 msg->setTo(querySpec->source);
1230 }
1231
1232 apiMutex.leave();
1233 DataMessage* resultMsg = NULL;
1234 uint8 status = space->query(msg, &resultMsg, timeout);
1235 delete(msg);
1236
1237 if (resultMsg) {
1238 *result = resultMsg->getDataCopy("ReplyData", resultsize);
1239 delete(resultMsg);
1240 }
1241
1242 return status;
1243}
1244
1245bool PsyAPI::queryReply(uint32 id, uint8 status, char* data, uint32 size, uint32 count) {
1246 DataMessage* msg = NULL;
1247 if (data && size) {
1248 msg = new DataMessage(PsyAPI::CTRL_QUERY_REPLY, currentCompID);
1249 msg->setData("ReplyData", data, size);
1250 msg->setInt("ReplyCount", count);
1251 // decide on EOL ###################
1252 }
1253 bool res = queryReply(id, status, msg);
1254 //delete(msg);
1255 return res;
1256}
1257
1258bool PsyAPI::queryReply(uint32 id, uint8 status, DataMessage* msg) {
1259 if (!apiMutex.enter(1000, "Replying to query"))
1260 return false;
1261 bool res = space->queryReply(id, status, msg);
1262 apiMutex.leave();
1263 return res;
1264}
1265
1266bool PsyAPI::logPrint(int level, const char *formatstring, ... ) {
1267 char* str;
1268 uint32 lenStr;
1269 va_list args;
1270 va_start(args, formatstring);
1271 str = utils::StringFormatVA(lenStr, formatstring, args);
1272 va_end(args);
1273 if (!str || !lenStr) {
1274 free(str);
1275 return false;
1276 }
1277
1278 char* name = new char[256];
1279 if (!space->manager->componentMemory->getComponentName(currentCompID, name, 255)) {
1280 delete [] name;
1281 free(str);
1282 return false;
1283 }
1284
1285 uint32 lenNewStr;
1286 char* newStr = utils::StringFormat(lenNewStr, "[%s] %s", name, str);
1287 // delete[] for `name` (new char[256] at the top of this function), free() for
1288 // `str` and `newStr` (StringFormat returns a vasprintf/malloc'd buffer,
1289 // Utils.cpp:7644). The two allocators sit two lines apart here, which is
1290 // exactly how this function ended up mismatched in the first place.
1291 delete [] name;
1292 free(str);
1293
1294 LogEntry* entry = (LogEntry*) malloc(sizeof(LogEntry)+lenNewStr+1);
1295 entry->size = sizeof(LogEntry)+lenNewStr+1;
1296 entry->cid = LOGENTRYID;
1297 entry->time = GetTimeNow();
1298 entry->source = currentCompID;
1299 entry->subject = LOG_COMPONENT;
1300 entry->level = (uint8)level;
1301 entry->type = LOGPRINT;
1302 entry->setText(newStr, lenNewStr);
1303 free(newStr);
1304
1305 return space->logEntry(entry);
1306// return LogPrint(this->currentCompID, LOG_COMPONENT, level, str);
1307}
1308
1309} // namespace cmlabs
#define COMPSTATUS_STARTING
Component is starting up.
#define COMPSTATUS_FINISHED
Component finished/stopped.
#define COMPSTATUS_RUNNING
Component is executing a run.
#define LOGENTRYID
Definition ObjectIDs.h:55
#define DATAMESSAGEID
Definition ObjectIDs.h:75
#define GetObjID(data)
Extract the cid field from a binary object block: the uint32 at byte offset 4 (after the leading size...
Definition ObjectIDs.h:26
PsyAPI — the component-facing API handle of the CMSDK.
#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 POST_NOSPEC
Posting attempted before any trigger arrived (no active spec).
Definition PsyAPI.h:48
#define POST_FAILED
An error occurred while posting.
Definition PsyAPI.h:47
#define QUERY_NOT_AVAILABLE
The target exists but is not available.
Definition PsyAPI.h:61
#define CRANKAPI_RUNNING
The crank is currently executing.
Definition PsyAPI.h:40
#define QUERY_FAILED
General failure.
Definition PsyAPI.h:55
#define QUERY_COMPONENT_UNKNOWN
The target component is unknown.
Definition PsyAPI.h:58
#define POST_OUTOFCONTEXT
The crank's context is no longer active.
Definition PsyAPI.h:49
#define CRANKAPI_IDLE
The crank is idle, waiting for input.
Definition PsyAPI.h:41
#define LOG_COMPONENT
Log source id used by components when writing entries to the system log.
Definition PsyAPI.h:68
#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_NAME_UNKNOWN
The query name is not defined in the spec.
Definition PsyAPI.h:57
#define MESSAGE_NON_GUARANTEED
Delivery policy flag: message delivery is not guaranteed (may be dropped under load).
static struct PsyType NOTYPE
The empty/unset message type (isValid() == false).
Definition Types.h:436
#define FLOAT64_NOVALUE
Definition Types.h:81
static struct PsyContext NOCONTEXT
The empty/unset context (isValid() == false).
Definition Types.h:437
#define INT64_NOVALUE
Definition Types.h:80
#define LOGPRINT
Definition Utils.h:227
#define MAXKEYNAMELEN
Definition Utils.h:85
#define MAXCOMMANDLINELEN
Definition Utils.h:88
#define MAXSCRIPTLEN
Definition Utils.h:91
#define MAXVALUENAMELEN
Definition Utils.h:86
bool addComponentStats(uint32 cid, uint8 status, uint64 usageCPUTicks, DataMessage *inputMsg, DataMessage *outputMsg, uint32 runCount, uint32 cycleCount)
Fold a run's activity into the component's stats (counters, rings, CPU ticks).
The central Psyclone data container: a self-contained binary message with typed, named user entries.
bool addTimeUsage(uint32 cycleCPUTime, uint32 cycleWallTime, uint32 chainCPUTime=0, uint32 chainWallTime=0, uint32 chainCount=0)
addTimeUsage()
bool setString(const char *key, const char *value)
setString(const char* key, const char* value)
bool getInt(const char *key, int64 &value)
getInt(const char* key, int64& value)
bool setInt(const char *key, int64 value)
setInt(const char* key, int64 value)
bool setTag(uint32 tag)
setTag(uint32 tag)
char * getDataCopy(const char *key, uint32 &size)
getDataCopy(const char* key, uint32& size)
DataMessageHeader * data
Pointer to the message's flat memory block (header + user entries).
PsyType getType()
getType()
const char * getData(const char *key, uint32 &size)
getData(const char* key, uint32& size)
uint32 getSize()
getSize() Get message size Many types of data of any size can be put into a message as user entries; ...
bool setFrom(uint32 from)
setFrom(uint32 from)
bool setTo(uint32 to)
setTo(uint32 to)
bool setType(PsyType &type)
setType(PsyType &type)
uint64 getTTL()
getTTL()
uint32 getTag()
getTag() Retrieve and return message tag id Tags can be used to segment data temporally,...
bool setData(const char *key, const char *value, uint32 size)
setData(const char* key, const char* value, uint32 size)
uint32 getTo()
getTo()
bool setMultiple(uint32 from, uint32 to, uint32 tag, uint64 ttl, uint8 policy, uint64 sendtime)
setMultiple(uint32 from, uint32 to, uint32 tag, uint64 ttl, uint8 policy, uint64 sendtime) Set multip...
bool setContextChange(PsyContext &context)
setContextChange(PsyContext& context)
ComponentMemory * componentMemory
Accessor for the component registry.
The API handle a component (crank) uses to talk to the Psyclone system.
Definition PsyAPI.h:82
bool setAutoDelete(bool autodel)
Internal use only.
Definition PsyAPI.cpp:586
static struct PsyType CTRL_CONTEXT_CHANGE
Announces a system context change.
Definition PsyAPI.h:94
static const char * fromPythonAddressOf(unsigned long long ptr)
Internal use only — debug helper returning a printable address string for a Python-held pointer.
Definition PsyAPI.cpp:80
PsyContext getCurrentTriggerContext()
Get the context of the current trigger, just retrieved using waitForNewMessage().
Definition PsyAPI.cpp:426
PsyAPI(PsySpace *space)
Constructor from a PsySpace.
Definition PsyAPI.cpp:30
uint8 retrieveIntegerParam(std::list< DataMessage * > &result, const char *name, int64 startInteger, int64 endInteger=INT64_NOVALUE, uint32 maxcount=0, uint32 maxage=0, uint32 timeout=5000)
Used by a module to retrieve messages from a whiteboard.
Definition PsyAPI.cpp:910
bool isRunning()
Internal use only.
Definition PsyAPI.cpp:84
std::string contextToText(PsyContext context)
Get textual representation of the context.
Definition PsyAPI.cpp:272
uint8 retrieve(std::list< DataMessage * > &result, const char *name, uint32 maxcount=0, uint32 maxage=0, uint32 timeout=5000)
Retrieve stored messages from a whiteboard, by named <retrieve> spec entry.
Definition PsyAPI.cpp:813
static struct PsyType CTRL_TRIGGER_GROUP
T1.6: wraps a <triggergroup> joined-set delivery (member map) to a component.
Definition PsyAPI.h:98
static PsyAPI * fromPython(unsigned long long ptr)
Internal use only.
Definition PsyAPI.cpp:76
bool addSubscription(const char *xml)
This function adds triggers and posts to an existing registration.
Definition PsyAPI.cpp:1026
bool addPsyProbeCustomView(const char *name, const char *templateURL)
Add a custom module view tab for the PsyProbe 1.x web interface by providing a template file.
Definition PsyAPI.cpp:337
~PsyAPI()
Destructor for the PsyAPI.
Definition PsyAPI.cpp:56
std::string getCommandlineBasedir()
Get the base dir that Psyclone is running from.
Definition PsyAPI.cpp:120
int32 postOutputMessage(const char *postName=NULL, DataMessage *msg=NULL)
Post the crank's output according to the spec's post entries.
Definition PsyAPI.cpp:616
bool shouldContinue()
Check whether the crank should keep running, or exit its loop.
Definition PsyAPI.cpp:97
bool hasCurrentRetrieveName(const char *name)
Check to see if the retrieve name is currently active - i.e.
Definition PsyAPI.cpp:187
bool emitSignal(const char *name, DataMessage *msg=NULL)
Emit a signal by its spec name.
Definition PsyAPI.cpp:749
bool hasCurrentPostName(const char *name)
Check to see if the post name is currently active - i.e.
Definition PsyAPI.cpp:227
bool queryReply(uint32 id, uint8 status, char *data, uint32 size, uint32 count)
Used by a module to reply to an incoming query by id.
Definition PsyAPI.cpp:1245
std::map< std::string, DataMessage * > waitForNewMessageGroup(uint32 ms, std::string &groupName)
T1.6: Wait for the next <triggergroup> joined-set delivery from the input queue.
Definition PsyAPI.cpp:558
std::string getCurrentScript()
Internal use only.
Definition PsyAPI.cpp:161
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
std::string getOtherModuleName(uint32 id)
Get the name of another module by id.
Definition PsyAPI.cpp:138
DataMessage * waitForSignal(const char *name, uint32 timeout, uint64 lastReceivedTime=0)
Wait for a signal (latest-value broadcast) by its spec name.
Definition PsyAPI.cpp:781
uint8 queryCatalog(char **result, uint32 &resultsize, const char *name, const char *query, const char *operation=NULL, const char *data=NULL, uint32 datasize=0, uint32 timeout=5000)
Send a query to another module or catalog by named <query> spec entry, receiving raw bytes back.
Definition PsyAPI.cpp:1166
uint32 getInputQueueSize()
Get the size of the input queue, i.e.
Definition PsyAPI.cpp:259
uint64 getCurrentMessageReceiveTime()
Get the time the current trigger (or, failing that, the current message) was received by the system,...
Definition PsyAPI.cpp:592
uint8 retrieveStringParam(std::list< DataMessage * > &result, const char *name, const char *startString, const char *endString=NULL, uint32 maxcount=0, uint32 maxage=0, uint32 timeout=5000)
Used by a module to retrieve messages from a whiteboard.
Definition PsyAPI.cpp:875
DataMessage * waitForNewMessage(uint32 ms)
Wait for the next trigger message from the component's input queue.
Definition PsyAPI.cpp:417
uint8 queryRemoteCatalog(DataMessage **resultMsg, const char *componentName, const char *ipAddress, uint16 port, DataMessage *msg, uint32 timeout=5000)
Send a query to a component in a different Psyclone system by hostname/IP.
Definition PsyAPI.cpp:1110
bool logPrint(int level, const char *formatstring,...)
Write a printf-style entry to the component's log (and the console when level is below the logging th...
Definition PsyAPI.cpp:1266
static struct PsyType CTRL_QUERY
Carries a query to a component/catalog.
Definition PsyAPI.h:99
std::set< std::string > getCurrentPostNames()
Get a list of post names currently active - i.e.
Definition PsyAPI.cpp:240
static struct PsyType CTRL_ADDSUBSCRIPTION
Adds triggers/posts to a registration at runtime.
Definition PsyAPI.h:103
friend class PsySpace
Definition PsyAPI.h:83
bool hasCurrentQueryName(const char *name)
Check to see if the query name is currently active - i.e.
Definition PsyAPI.cpp:214
std::string getCurrentTriggerName()
Get the name of the current trigger, i.e.
Definition PsyAPI.cpp:422
std::string getCurrentScriptFilename()
Internal use only.
Definition PsyAPI.cpp:176
static struct PsyType CTRL_INTERSYSTEM_QUERY
Query crossing to a different Psyclone system.
Definition PsyAPI.h:105
std::string typeToText(PsyType type)
Get textual representation of the type.
Definition PsyAPI.cpp:268
uint8 retrieveFloatParam(std::list< DataMessage * > &result, const char *name, float64 startFloat, float64 endFloat=FLOAT64_NOVALUE, uint32 maxcount=0, uint32 maxage=0, uint32 timeout=5000)
Used by a module to retrieve messages from a whiteboard.
Definition PsyAPI.cpp:945
std::string getModuleName()
Get the module name.
Definition PsyAPI.cpp:134
uint8 retrieveTimeParam(std::list< DataMessage * > &result, const char *name, uint64 startTime, uint64 endTime=0, uint32 maxcount=0, uint32 maxage=0, uint32 timeout=5000)
Used by a module to retrieve messages from a whiteboard.
Definition PsyAPI.cpp:841
bool hasCurrentSignalName(const char *name)
Check to see if the signal name is currently active - i.e.
Definition PsyAPI.cpp:200
std::string getCurrentScriptLanguage()
Internal use only.
Definition PsyAPI.cpp:146
MemoryManager * manager
The process-local memory manager: entry point to the node's shared-memory fabric. Owned by the space.
Definition PsySpace.h:339
bool leave()
Release the mutex.
Definition Utils.cpp:1704
bool enter()
Block until the mutex is acquired.
Definition Utils.cpp:1512
uint64 GetTimeNow()
Return the current absolute time (µs since year 0) according to the TMC.
Definition PsyTime.cpp:69
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 GetCPUTicks(ThreadHandle hThread, uint64 &ticks)
Get accumulated CPU time of a specific thread.
Definition Utils.cpp:4553
uint32 strcpyavail(char *dst, const char *src, uint32 maxlen, bool copyAvailable)
Bounded strcpy that always NUL-terminates.
Definition Utils.cpp:8491
char * StringFormatVA(uint32 &size, const char *format, va_list args)
va_list core used by the other StringFormat overloads.
Definition Utils.cpp:9001
bool LookupIPAddress(const char *name, uint32 &address)
Resolve a hostname to an IPv4 address.
Definition Utils.cpp:7781
std::string StringFormat(const char *format,...)
printf into a std::string.
Definition Utils.cpp:9061
std::pair< DataMessage *, DataMessage * > TriggerAndMessage
Pairing of a trigger message and its accompanying data message, as queued for a crank's input.
Definition PsyAPI.h:71
Hierarchical execution-context identifier.
Definition Types.h:284
bool isValid()
Definition Types.h:289
Hierarchical message type identifier — the key used for publish/subscribe matching in Psyclone.
Definition Types.h:123
bool isValid()
A type is valid if its root level is non-zero.
Definition Types.h:126
uint32 chaincputime
Accumulated CPU time across the whole causal message chain, in microseconds.
uint32 chainwalltime
Accumulated wall time across the whole causal message chain, in microseconds.
uint32 chaincount
Number of messages in the causal chain leading to (and including) this one.
Wire/storage layout of one log record: fixed header immediately followed by the message text.
Definition Utils.h:245
uint32 source
Definition Utils.h:249
uint32 size
Definition Utils.h:246
uint8 level
Definition Utils.h:251
uint64 time
Definition Utils.h:248
bool setText(char *text, uint32 len)
Copy len bytes of text into the payload area and update size.
Definition Utils.cpp:287
uint8 subject
Definition Utils.h:250
uint8 type
Definition Utils.h:252
uint32 cid
Definition Utils.h:247
Specification of a message to post when a trigger fires (or a crank completes).
uint8 policy
Delivery policy flags (e.g.
PsyType type
Type of the posted message.
uint32 addContentToMsg(DataMessage *msg)
Unpack the inline content entries into msg as typed user entries.
uint32 to
Addressee component id (0 = publish to subscribers).
uint32 tag
Tag for the posted message.
uint64 ttl
Time-to-live of the posted message in microseconds.
PsyContext contextchange
Context switch the posted message announces (NOCONTEXT if none).
Specification of a query against a catalog/service/feed, attached to a TriggerSpec.
char type[MAXKEYNAMELEN+1]
Requested data/content type.
char hostName[MAXKEYNAMELEN+1]
External source: host name (alternative to ipHost).
uint32 ipHost
External source: IPv4 host (as uint32), 0 if not used.
char operation[MAXKEYNAMELEN+1]
Operation to perform (source-specific verb).
char key[MAXKEYNAMELEN+1]
Key to query on.
char value[MAXVALUENAMELEN+1]
Value to match.
char name[MAXKEYNAMELEN+1]
Name of this query, used to reference its results in the crank.
char subdir[MAXKEYNAMELEN+1]
Sub-directory/collection within the source.
char sourceName[MAXKEYNAMELEN+1]
Name of the source component (alternative to numeric id).
bool binary
Request results in binary form rather than text.
uint16 ipPort
External source: TCP/UDP port, 0 if not used.
char ext[MAXKEYNAMELEN+1]
File extension / data format selector.
uint32 source
Component id of the source to query.
Specification of a whiteboard retrieval attached to a TriggerSpec.
uint64 endTime
Range end when keytype == INDEX_TIME (microseconds).
char endString[MAXVALUENAMELEN+1]
Range end when keytype == INDEX_STRING.
char startString[MAXVALUENAMELEN+1]
Range start when keytype == INDEX_STRING.
uint64 startTime
Range start when keytype == INDEX_TIME (microseconds).
uint32 origin
Restrict to messages originating from this component id (0 = any).
int64 endInt
Range end when keytype == INDEX_INTEGER.
int64 startInt
Range start when keytype == INDEX_INTEGER.
uint32 maxcount
Maximum number of messages to return (0 = unlimited).
uint32 source
Component id of the whiteboard to retrieve from.
float64 startFloat
Range start when keytype == INDEX_FLOAT.
float64 endFloat
Range end when keytype == INDEX_FLOAT.
uint64 maxage
Maximum message age in MICROSECONDS (XML gives ms; parser multiplies by 1000).
Specification of a signal (a typed notification without payload) emitted when a trigger fires.
PsyType type
Type of the signal to emit.
A complete trigger definition: what fires a component's crank and what happens then.