Repository navigation
Expand file tree
/
Copy pathcorTestClient.c
More file actions
1561 lines (1268 loc) · 51.4 KB
/
Copy pathcorTestClient.c
File metadata and controls
1561 lines (1268 loc) · 51.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//
// FILE corTestClient.c
//
// AUTHOR Ken Zangelin
//
// Copyright 2026 Seamware
// SPDX-License-Identifier: Apache-2.0
//
// Test notification receiver for functional tests.
// Accumulates all incoming requests (e.g. POST /notify) in a global array.
// Provides:
// GET /dump - return the requests received SINCE THE LAST DUMP, and
// consume them. A dump reads; read notifications are gone.
// GET /die - exit the process
// POST /** - accumulate the request (catch-all)
//
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <signal.h>
#include <pthread.h>
#include <mosquitto.h>
#include "corArgs/corArgs.h"
#include "corArgs/corArgsBuiltins.h"
#include "corTree/CorNode.h"
#include "corJson/CorJson.h"
#include "corTree/corTreeBuilder.h"
#include "corTree/corTreeLookup.h"
#include "corJson/corJsonRender.h"
#include "corJson/corJsonRenderSize.h"
#include "corTree/corTreeClone.h"
#include "corTree/corTreeFree.h"
#include "corAlloc/corAlloc.h"
#include "corAlloc/corAlloc.h"
#include "corLog/corLog.h"
#include "corBase/corFileRead.h" // corFileRead
#include "corJson/corJsonParse.h" // corJsonParse
#include "corAlloc/corAllocBufferInit.h" // corAllocBufferInit
#include "corAlloc/corAllocBufferReset.h" // corAllocBufferReset
#include "corJson/corJsonCreate.h" // corJsonCreate
#include "corPlugin/corPlugin.h" // corPluginSetBaseDir, corPluginResolve, corPluginOpen
#include "corBridge/BridgeDriver.h" // BridgeDriver, BridgeRegisterFunc, BRIDGES_MAX
#include "corBridge/BridgeBroker.h" // BridgeBroker, BRIDGE_*
#include "corBridge/BridgeServer.h" // BridgeServer, BridgeServiceRequestFunc
#include "corRest/corRest.h"
// -----------------------------------------------------------------------------
//
// Globals
//
static CorNode* dumpArray = NULL; // accumulates requests (malloc allocator)
static int dumpCount = 0;
static int probeCount = 0; // sourceIdentity discovery probes seen (kept OUT of dumpArray)
//
// dumpMutex - guards dumpArray + dumpCount, on every path that touches them.
//
// corTestClient is thread-per-connection, so two notifications in flight at once run
// dumpAccumulate on two threads and spliced into the same tail unguarded: the
// order of the two entries flipped, and one of them could be lost outright.
// GET /dump rendered the list while it was being appended to, and DELETE /dump
// corTreeFree'd it out from under a writer.
//
// The mutex existed already - as mqttDumpMutex, taken only by the MQTT
// listener, which shares this very array with the HTTP path. It was never
// MQTT's mutex; it guards the accumulator, and it is named for that now.
//
static pthread_mutex_t dumpMutex = PTHREAD_MUTEX_INITIALIZER;
// -----------------------------------------------------------------------------
//
// Programmable response stubs (the mock-reply API)
//
// A test POSTs to /mock/reply to program how corTestClient answers a forwarded
// request — { "verb": "POST", "path": "/attrs/", "status": 207, "body": {...} }.
// On each forwarded request the stub list is consulted (verb match + path
// substring); the first match's status + body is served, else the --status
// fallback applies. Stubs are persistent until DELETE /mock/reply.
//
typedef struct FtStub
{
char* verb; // "POST", "GET", ...
char* path; // substring to find in the request urlPath
int status; // HTTP status to return
int delayMs; // sleep this many ms before responding (per-path timeout injection), 0 = none
char* body; // rendered JSON body to return (malloc), or NULL
struct FtStub* next;
} FtStub;
static FtStub* ftStubs = NULL;
// -----------------------------------------------------------------------------
//
// Command line arguments
//
unsigned short ftPort = 7701;
bool ftFg = true;
unsigned short ftPostStatus = 200; // status returned for accumulate POSTs; override with --status
unsigned int ftDelayMs = 0; // sleep before responding — for timeout tests
bool ftDiscard = false; // POSTs counted, not kept - a benchmark's receiver
//
// ftMqttSubscribed - set when the MQTT SUBACK arrives, read by GET /mqttReady.
//
// Not "the thread started" and not "subscribe was called": a publish that
// reaches the broker before the SUBACK is delivered to nobody and is DISCARDED,
// not queued. So the only readiness that means anything to a test is the
// acknowledgement, which is why this is set in the on-subscribe callback.
//
static volatile bool ftMqttSubscribed = false;
//
// ftMqttFailed - set when the MQTT connection is given up on for good.
//
// The connect loop used to be unbounded ("try forever, the broker may not be up
// yet"), which is right for a broker that is merely slow and wrong for one that
// is never coming: corTestClient span silently, printed nothing, and the only symptom
// was a readiness barrier timing out with an EMPTY log to show for it. A bounded
// retry that says why is strictly better - the failure is reported by the process
// that actually observed it.
//
static volatile bool ftMqttFailed = false;
//
// ftMqttConn - the subscriber's connection, published on by POST /mqtt/publish once it is up
//
static struct mosquitto* volatile ftMqttConn = NULL;
unsigned short ftMqttPort = 0; // 0 = no MQTT subscription
char* ftMqttTopic = (char*) "#"; // default: catch every topic
char* ftMqttUser = NULL; // MQTT username (for an auth-required broker)
char* ftMqttPass = NULL; // MQTT password
bool ftMqttTls = false; // subscribe over TLS (mqtts), insecure
char* ftHttpsKey = NULL; // path to a PEM private key (enables TLS when both set)
char* ftHttpsCert = NULL; // path to a PEM certificate (enables TLS when both set)
//
// Bridge hosting.
//
// corTestClient loads the SAME plugin the broker loads, rather than speaking a
// transport of its own. Two reasons, and the second is the better one:
//
// the plugin is C++ and links 21 MiB of transport libraries, and corTestClient is
// built inside PROJECT(coraine C) - linking that here would put a C++
// compiler and the whole eProsima stack into coraine's own build tree, which
// is exactly what the plugin architecture exists to avoid.
//
// and a test that drives the broker's actual plugin proves the broker's
// actual plugin works. A second, independently written client can be wrong
// in its own way and agree with nothing.
//
// So corTestClient is a bridge HOST: it supplies its own BridgeBroker, whose
// sampleIn records into the dump instead of writing an entity.
//
char* ftBridges = NULL; // comma-separated bridge plugins to load
char* ftBridgeConfig = NULL; // the shared bridge configuration file
static BridgeDriver ftBridgeV[BRIDGES_MAX];
static int ftBridgeCount = 0;
static char* ftTraceLevels = (char*) "0-255";
static CorArg ftArgV[] =
{
{ "--traceLevels", NULL, CorArgString, _vp &ftTraceLevels, CorArgOpt, _vp "0-255", NULL, NULL, "trace levels to log - every one by default (the functests read them); \"\" for none - a benchmark's notification receiver logs a full trace of every request otherwise" },
{ "--port", "-p", CorArgUShort, _vp &ftPort, CorArgOpt, _vp 7701, _vp 1, _vp 65535, "TCP port to listen on" },
{ "--foreground", "-fg", CorArgBool, _vp &ftFg, CorArgOpt, _vp true, _vp false, _vp true, "run in foreground" },
{ "--status", "-s", CorArgUShort, _vp &ftPostStatus, CorArgOpt, _vp 200, _vp 100, _vp 599, "HTTP status for accumulate POSTs (misbehave mode)" },
{ "--delay", NULL, CorArgUInt, _vp &ftDelayMs, CorArgOpt, _vp 0, _vp 0, _vp 600000, "sleep N ms before responding (timeout tests)" },
{ "--discard", NULL, CorArgBool, _vp &ftDiscard, CorArgOpt, _vp false, _vp false, _vp true, "POSTs counted (GET /count), not kept - a benchmark's notification receiver" },
{ "--mqttPort", NULL, CorArgUShort, _vp &ftMqttPort, CorArgOpt, _vp 0, _vp 0, _vp 65535, "MQTT broker port to subscribe to (0 = disabled)" },
{ "--mqttTopic", NULL, CorArgString, _vp &ftMqttTopic, CorArgOpt, _vp "#", NULL, NULL, "MQTT topic to subscribe (default '#')" },
{ "--mqttUser", NULL, CorArgString, _vp &ftMqttUser, CorArgOpt, NULL, NULL, NULL, "MQTT username (auth-required broker)" },
{ "--mqttPassword", NULL, CorArgString, _vp &ftMqttPass, CorArgOpt, NULL, NULL, NULL, "MQTT password" },
{ "--mqttTls", NULL, CorArgBool, _vp &ftMqttTls, CorArgOpt, _vp false, _vp false, _vp true, "subscribe over TLS (mqtts), accept self-signed" },
{ "--httpsKey", "-k", CorArgString, _vp &ftHttpsKey, CorArgOpt, NULL, NULL, NULL, "PEM private key file (serve HTTPS; needs --httpsCertificate)" },
{ "--httpsCertificate","-c", CorArgString, _vp &ftHttpsCert, CorArgOpt, NULL, NULL, NULL, "PEM certificate file (serve HTTPS; needs --httpsKey)" },
{ "--bridges", "-br", CorArgString, _vp &ftBridges, CorArgOpt, NULL, NULL, NULL, "bridge plugins to host (comma-separated)" },
{ "--bridgeConfig", "-brc",CorArgString, _vp &ftBridgeConfig, CorArgOpt, NULL, NULL, NULL, "bridge configuration file (the broker's own)" },
CORARGS_END
};
// -----------------------------------------------------------------------------
//
// dumpInit - create the accumulator array
//
static void dumpInit(void)
{
dumpArray = corTreeArray(NULL, NULL);
dumpCount = 0;
probeCount = 0;
}
// -----------------------------------------------------------------------------
//
// dumpDrain - free the accumulated entries and start a fresh, empty array
//
// Not dumpClear: probeCount counts sourceIdentity probes, which are deliberately
// kept OUT of dumpArray and are not "read" by a dump. Draining the one must not
// reset the other.
//
// Caller holds dumpMutex.
//
static void dumpDrain(void)
{
if (dumpArray != NULL)
corTreeFree(dumpArray);
dumpArray = corTreeArray(NULL, NULL);
dumpCount = 0;
}
// -----------------------------------------------------------------------------
//
// ftBridgeSampleIn - a sample arrived on a transport
//
// ⚠ A PLUGIN THREAD. The entry is built with the malloc allocator, like every
// other dump entry, so it outlives whatever the transport is about to reuse.
//
// This is the whole of corTestClient's side of the seam: the broker's
// implementation stores an attribute, this one writes down that the value
// arrived. Same contract, different job, which is the point of the contract
// being about endpoints and bytes rather than entities.
//
static int ftBridgeSampleIn(const char* bridgeName, const char* endpoint, const char* json, int64_t publishTime)
{
CorNode* entry = corTreeObject(NULL, NULL);
corTreeChildAdd(entry, corTreeString(NULL, "bridge", (bridgeName != NULL) ? bridgeName : "?"));
corTreeChildAdd(entry, corTreeString(NULL, "endpoint", (endpoint != NULL) ? endpoint : "?"));
corTreeChildAdd(entry, corTreeString(NULL, "payload", (json != NULL) ? json : ""));
if (publishTime > 0)
corTreeChildAdd(entry, corTreeInteger(NULL, "publishTime", (long long) publishTime));
//
// dumpMutex, like every other path that touches dumpArray - and this one is
// reached from a transport thread, which is the case it exists for.
//
pthread_mutex_lock(&dumpMutex);
if (dumpArray == NULL)
dumpArray = corTreeArray(NULL, NULL);
corTreeChildAdd(dumpArray, entry);
++dumpCount;
pthread_mutex_unlock(&dumpMutex);
return BRIDGE_OK;
}
//
// Defined below, beside the rest of the bridge plumbing; the service handler
// above it is the one caller that comes first.
//
static BridgeDriver* ftBridgeDriverLookup(const char* alias);
// -----------------------------------------------------------------------------
//
// Canned service replies.
//
// ⭐ corTestClient IS THE PEER, and a peer to a service has to have an answer.
// Computing one is exactly what a context broker cannot do and what a test must
// not have to do either, so the answer is told to corTestClient in advance: the test
// says "when somebody asks this service, say that", then makes the broker ask.
//
// Which also keeps the assertion where it belongs. What the test is checking is
// that the request left the broker and the reply came back into the attribute -
// not that anything clever happened in between.
//
#define FT_SERVICE_MAX 8
typedef struct FtServiceReply
{
char* endpoint;
char* payload; // rendered JSON, malloc'd
} FtServiceReply;
static FtServiceReply ftServiceReplyV[FT_SERVICE_MAX];
static int ftServiceReplyCount = 0;
static pthread_mutex_t ftServiceMutex = PTHREAD_MUTEX_INITIALIZER;
// -----------------------------------------------------------------------------
//
// ftServiceReplyLookup - the answer set for an endpoint, or NULL
//
// Returns a COPY: the caller is on a transport thread and the table can be
// rewritten by a REST thread between this call and the send.
//
static char* ftServiceReplyLookup(const char* endpoint)
{
char* copy = NULL;
pthread_mutex_lock(&ftServiceMutex);
for (int i = 0; i < ftServiceReplyCount; i++)
{
if (strcmp(ftServiceReplyV[i].endpoint, endpoint) == 0)
{
copy = strdup(ftServiceReplyV[i].payload);
break;
}
}
pthread_mutex_unlock(&ftServiceMutex);
return copy;
}
// -----------------------------------------------------------------------------
//
// ftBridgeServiceRequest - the broker asked us something
//
// ⚠ A PLUGIN THREAD, as ftBridgeSampleIn.
//
// Two things happen, and both matter to a test: the request is written down, so
// it can be asserted on exactly as an arriving sample is, and it is answered,
// so the other half of the exchange can be asserted on in the broker.
//
static int ftBridgeServiceRequest(const char* bridgeName,
const char* endpoint,
const char* json,
uint64_t requestId,
int64_t publishTime)
{
CorNode* entry = corTreeObject(NULL, NULL);
corTreeChildAdd(entry, corTreeString(NULL, "bridge", (bridgeName != NULL) ? bridgeName : "?"));
corTreeChildAdd(entry, corTreeString(NULL, "endpoint", (endpoint != NULL) ? endpoint : "?"));
corTreeChildAdd(entry, corTreeString(NULL, "kind", "serviceRequest"));
corTreeChildAdd(entry, corTreeString(NULL, "payload", (json != NULL) ? json : ""));
if (publishTime > 0)
corTreeChildAdd(entry, corTreeInteger(NULL, "publishTime", (long long) publishTime));
pthread_mutex_lock(&dumpMutex);
if (dumpArray == NULL)
dumpArray = corTreeArray(NULL, NULL);
corTreeChildAdd(dumpArray, entry);
++dumpCount;
pthread_mutex_unlock(&dumpMutex);
//
// ⛔ The requestId is NOT written into the dump. It is the transport's own
// counter, it runs across every service in the process, and a test that
// asserted on it would be asserting on how many requests happened to precede
// this one.
//
char* reply = ftServiceReplyLookup(endpoint);
if (reply == NULL)
{
COR_W("corTestClient: asked on '%s' with no answer set - the request stands unanswered", endpoint);
return BRIDGE_OK;
}
BridgeDriver* driverP = ftBridgeDriverLookup((bridgeName != NULL) ? bridgeName : "dds");
const BridgeServer* serverP = ((driverP != NULL) && (driverP->serverIface != NULL)) ? driverP->serverIface() : NULL;
if ((serverP != NULL) && (serverP->serviceReply != NULL))
{
if (serverP->serviceReply(endpoint, requestId, reply) != BRIDGE_OK)
COR_W("corTestClient: could not answer on '%s'", endpoint);
else
COR_T(1, "corTestClient: answered on '%s' with %s", endpoint, reply);
}
free(reply);
return BRIDGE_OK;
}
// -----------------------------------------------------------------------------
//
// ftBridgeLog - the transport library's own log messages
//
static void ftBridgeLog(int severity, const char* fileName, int lineNo, const char* funcName, const char* msg)
{
char sev;
switch (severity)
{
case BRIDGE_LOG_ERROR: sev = 'E'; break;
case BRIDGE_LOG_WARNING: sev = 'W'; break;
case BRIDGE_LOG_INFO: sev = 'I'; break;
default: sev = 'T'; break;
}
corLogOut((char*) fileName, lineNo, (char*) funcName, sev, -1, "%s", msg);
}
// -----------------------------------------------------------------------------
//
// ftBridgeQualifiedIn - a reply, or anything else that is not a plain sample
//
// corTestClient hosts the plugin as the broker does, so it is offered the same
// arrivals. It writes them down with their qualifiers, which is what lets a
// test tell "the answer came back" from "a value arrived".
//
// ⚠ A PLUGIN THREAD, as ftBridgeSampleIn.
//
static int ftBridgeQualifiedIn(const char* bridgeName,
const char* endpoint,
const char* datasetId,
const char* subAttrName,
const char* json,
int64_t publishTime)
{
CorNode* entry = corTreeObject(NULL, NULL);
corTreeChildAdd(entry, corTreeString(NULL, "bridge", (bridgeName != NULL) ? bridgeName : "?"));
corTreeChildAdd(entry, corTreeString(NULL, "endpoint", (endpoint != NULL) ? endpoint : "?"));
corTreeChildAdd(entry, corTreeString(NULL, "payload", (json != NULL) ? json : ""));
if (subAttrName != NULL)
corTreeChildAdd(entry, corTreeString(NULL, "subAttribute", (char*) subAttrName));
if (datasetId != NULL)
corTreeChildAdd(entry, corTreeString(NULL, "datasetId", (char*) datasetId));
if (publishTime > 0)
corTreeChildAdd(entry, corTreeInteger(NULL, "publishTime", (long long) publishTime));
pthread_mutex_lock(&dumpMutex);
if (dumpArray == NULL)
dumpArray = corTreeArray(NULL, NULL);
corTreeChildAdd(dumpArray, entry);
++dumpCount;
pthread_mutex_unlock(&dumpMutex);
return BRIDGE_OK;
}
static BridgeBroker ftBridgeBroker =
{
BRIDGE_ABI_VERSION,
ftBridgeSampleIn,
ftBridgeLog,
ftBridgeQualifiedIn
};
// -----------------------------------------------------------------------------
//
// ftBridgeDriverLookup - which loaded plugin answers to this name
//
static BridgeDriver* ftBridgeDriverLookup(const char* alias)
{
for (int i = 0; i < ftBridgeCount; i++)
{
if ((ftBridgeV[i].alias != NULL) && (strcmp(ftBridgeV[i].alias, alias) == 0))
return &ftBridgeV[i];
}
return (ftBridgeCount > 0) ? &ftBridgeV[0] : NULL; // one bridge is the common case
}
// -----------------------------------------------------------------------------
//
// ftBridgeTopicsCarry - subscribe to every endpoint named in the config file
//
// The same file the broker reads. corTestClient has no Channels and does not want
// any - it is the peer on the other end of the wire, not a second broker - but
// it does need to know which endpoints to listen on, and the file already says.
//
static void ftBridgeTopicsCarry(BridgeDriver* driverP, const char* configFile)
{
char* buf = NULL;
int bufLen = 0;
if ((driverP->channelAdd == NULL) || (configFile == NULL))
return;
if (corFileRead((char*) "", (char*) configFile, &buf, &bufLen) != 0)
return;
//
// Its own buffer. This runs BEFORE corRestInit, so corRest.corJsonP is still
// NULL - parsing into it takes the process down before it serves anything,
// which is a confusing way to be told the order is wrong.
//
char kallocBuffer[8192];
CorAlloc kalloc;
CorJson corJson;
corAllocBufferInit(&kalloc, kallocBuffer, sizeof(kallocBuffer), 8 * 1024, NULL, "ftBridge");
CorJson* corJsonP = corJsonCreate(&corJson, &kalloc);
CorNode* treeP = corJsonParse(corJsonP, buf);
if (treeP == NULL)
{
corAllocBufferReset(&kalloc, true);
return;
}
CorNode* bridgeP = corTreeLookup(treeP, (driverP->alias != NULL) ? driverP->alias : "dds");
CorNode* ngsildP = (bridgeP != NULL) ? corTreeLookup(bridgeP, "ngsild") : NULL;
CorNode* topicsP = (ngsildP != NULL) ? corTreeLookup(ngsildP, "topics") : NULL;
CorNode* servicesP = (ngsildP != NULL) ? corTreeLookup(ngsildP, "services") : NULL;
for (CorNode* entryP = (topicsP != NULL) ? topicsP->value.head : NULL; entryP != NULL; entryP = entryP->next)
{
//
// BOTH directions: corTestClient stands in for whatever is at the far end, and
// the far end both publishes and listens.
//
if (driverP->channelAdd(entryP->name, BridgeChannelTopic, BridgeDirectionBoth) != BRIDGE_OK)
COR_W("corTestClient: bridge '%s' would not carry '%s'", driverP->alias, entryP->name);
}
//
// ⭐ AND THE SERVICES, THE OTHER WAY UP.
//
// A topic is carried; a service is SERVED. The broker reads these same
// entries and becomes the client of each - it is the only thing it can be -
// so for the exchange to exist at all, something has to be the server, and
// that is what corTestClient is for. Without it there is nothing on the domain to
// answer and a service test could only ever assert that nothing happened.
//
const BridgeServer* serverP = (driverP->serverIface != NULL) ? driverP->serverIface() : NULL;
if ((servicesP != NULL) && ((serverP == NULL) || (serverP->serviceServe == NULL)))
COR_W("corTestClient: bridge '%s' has services configured but cannot serve them", driverP->alias);
else if (servicesP != NULL)
{
for (CorNode* entryP = servicesP->value.head; entryP != NULL; entryP = entryP->next)
{
if (serverP->serviceServe(entryP->name, ftBridgeServiceRequest) != BRIDGE_OK)
COR_W("corTestClient: bridge '%s' would not serve '%s'", driverP->alias, entryP->name);
}
}
corAllocBufferReset(&kalloc, true);
}
// -----------------------------------------------------------------------------
//
// ftBridgesLoad - dlopen each named plugin and bring its transport up
//
static void ftBridgesLoad(void)
{
if (ftBridges == NULL)
return;
corPluginSetBaseDir("/opt/seamware/plugins", "SEAMWARE_PLUGIN_DIR");
char buf[512];
strncpy(buf, ftBridges, sizeof(buf) - 1);
buf[sizeof(buf) - 1] = 0;
char* saveptr = NULL;
char* token = strtok_r(buf, ",", &saveptr);
while ((token != NULL) && (ftBridgeCount < BRIDGES_MAX))
{
char path[512];
char openErr[512];
corPluginResolve(corPluginBaseDir(), "bridge", NULL, token, path, sizeof(path));
BridgeRegisterFunc registerFunc = (BridgeRegisterFunc) corPluginOpen(path, "bridgeRegister", openErr, sizeof(openErr));
if (registerFunc == NULL)
{
COR_X(1, "corTestClient: bridge plugin '%s' (%s): %s", token, path, openErr);
return;
}
BridgeDriver* driverP = &ftBridgeV[ftBridgeCount];
memset(driverP, 0, sizeof(BridgeDriver));
//
// What THIS host speaks, so a plugin built against a newer contract knows
// where our struct ends - the same handshake the broker's loader does, and
// for the same reason. See BridgeDriver.h.
//
driverP->abiVersion = BRIDGE_ABI_VERSION;
registerFunc(driverP);
++ftBridgeCount;
if ((driverP->init != NULL) && (driverP->init(ftBridgeConfig, &ftBridgeBroker) != BRIDGE_OK))
COR_X(1, "corTestClient: init failed for bridge '%s'", token);
ftBridgeTopicsCarry(driverP, ftBridgeConfig);
COR_I("corTestClient: hosting bridge '%s'", (driverP->alias != NULL) ? driverP->alias : token);
token = strtok_r(NULL, ",", &saveptr);
}
}
// -----------------------------------------------------------------------------
//
// postBridgePublish - POST /bridge/publish
//
// Body: { "endpoint": "rt/pose", "payload": <any json> }
//
// Puts a value on a transport, which is how a test plays the far end: the
// broker is then supposed to store it, and the test asks the broker.
//
static bool postBridgePublish(void)
{
CorNode* bodyP = corRest.in.requestTree;
if ((ftBridgeCount == 0) || (bodyP == NULL))
{
corRest.out.httpStatusCode = 400;
return true;
}
CorNode* endpointP = corTreeLookup(bodyP, "endpoint");
CorNode* payloadP = corTreeLookup(bodyP, "payload");
if ((endpointP == NULL) || (endpointP->type != CorString) || (payloadP == NULL))
{
corRest.out.httpStatusCode = 400;
return true;
}
//
// The payload goes on the wire as the application's own JSON, so the member
// name and the sibling link come off for the render - see
// bridgeRequestsBeforeWrite in the broker, where the same two things bit.
//
static char rendered[16384];
char* savedName = payloadP->name;
CorNode* savedNext = payloadP->next;
payloadP->name = NULL;
payloadP->next = NULL;
corJsonFastRender(payloadP, rendered);
payloadP->name = savedName;
payloadP->next = savedNext;
BridgeDriver* driverP = ftBridgeDriverLookup("dds");
if ((driverP == NULL) || (driverP->publish == NULL))
{
corRest.out.httpStatusCode = 501;
return true;
}
corRest.out.httpStatusCode = (driverP->publish(endpointP->value.s, rendered) == BRIDGE_OK) ? 204 : 502;
return true;
}
// -----------------------------------------------------------------------------
//
// dumpAccumulate - record an incoming request
//
// Stores: { "verb": "POST", "url": "/notify", "payload": "..." }
// Uses malloc allocator (NULL) so entries persist across requests.
//
static void dumpAccumulate(void)
{
//
// All strings come from per-request allocators that will be freed.
// Use corTreeString with NULL allocator (malloc) — it strdup's the value.
//
CorNode* entry = corTreeObject(NULL, NULL);
corTreeChildAdd(entry, corTreeString(NULL, "verb", corRest.in.verbString ? corRest.in.verbString : "?"));
corTreeChildAdd(entry, corTreeString(NULL, "url", corRest.in.urlPath ? corRest.in.urlPath : "?"));
// Headers
CorNode* hdrs = corTreeObject(NULL, "headers");
for (int i = 0; i < corRest.in.httpHeaderCount; i++)
corTreeChildAdd(hdrs, corTreeString(NULL, corRest.in.httpHeaderV[i].key, corRest.in.httpHeaderV[i].value));
corTreeChildAdd(entry, hdrs);
// URI params
if (corRest.in.uriParamCount > 0)
{
CorNode* params = corTreeObject(NULL, "params");
for (int i = 0; i < corRest.in.uriParamCount; i++)
corTreeChildAdd(params, corTreeString(NULL, corRest.in.uriParamV[i].key, corRest.in.uriParamV[i].value));
corTreeChildAdd(entry, params);
}
// Body — deep-clone the request tree since the original is per-request allocated
if (corRest.in.requestTree != NULL)
{
CorNode* bodyClone = corTreeClone(NULL, corRest.in.requestTree);
if (bodyClone != NULL)
{
bodyClone->name = (char*) "body";
corTreeChildAdd(entry, bodyClone);
}
}
else if (corRest.in.payload != NULL && corRest.in.payloadSize > 0)
corTreeChildAdd(entry, corTreeString(NULL, "body", corRest.in.payload));
pthread_mutex_lock(&dumpMutex);
corTreeChildAdd(dumpArray, entry);
dumpCount++;
pthread_mutex_unlock(&dumpMutex);
}
// -----------------------------------------------------------------------------
//
// getDump - GET /dump — the requests received since the last dump, and consume
//
static bool getDump(void)
{
pthread_mutex_lock(&dumpMutex);
if (dumpArray == NULL || dumpCount == 0)
{
// Return empty array
corRest.out.payload = (char*) "[]";
corRest.out.payloadSize = 2;
pthread_mutex_unlock(&dumpMutex);
return true;
}
//
// Render dumpArray to JSON.
// Use a scratch buffer allocated via malloc so the output survives
// beyond the per-request kalloc lifetime — corRest copies the response
// body (MHD_RESPMEM_MUST_COPY), so we can free this buffer after
// the call returns by using corAlloc from the per-request allocator.
//
int bufSize = corJsonFastRenderSize(dumpArray) + 1;
char* buf = (char*) corAlloc(&corRest.kalloc, bufSize);
corJsonFastRender(dumpArray, buf);
//
// A dump READS the notifications, and read notifications are gone. What the
// accumulator holds from here on is what arrived SINCE - so the next dump in
// the test answers "what did this step produce", not "everything so far".
//
// That is what makes an unexpected notification visible. While a dump was
// cumulative, an extra one silently padded every later expectation, and the
// test that would have caught it was the one that had already passed. It also
// retires DELETE /dump: a test no longer has to throw the accumulator away to
// get a clean read, which was the same error with an explicit verb on it.
//
// buf already holds the rendered text, so freeing the tree here is safe.
//
dumpDrain();
pthread_mutex_unlock(&dumpMutex);
corRest.out.payload = buf;
corRest.out.payloadSize = strlen(buf);
return true;
}
// -----------------------------------------------------------------------------
//
// getCount - GET /count — number of accumulated requests as a bare integer
//
// A parser-free alternative to GET /dump for the (many) tests that only need
// the count of received requests: returns e.g. "3" (or "0" when empty) as plain
// text, never JSON. A caller reads it with plain curl and never has to pipe a
// possibly-empty/invalid body through a JSON parser — which, on an empty dump,
// would throw to stderr and flake the test under parallel load.
//
static bool getCount(void)
{
char* buf = (char*) corAlloc(&corRest.kalloc, 16);
pthread_mutex_lock(&dumpMutex);
snprintf(buf, 16, "%d", dumpCount);
pthread_mutex_unlock(&dumpMutex);
corRest.out.payload = buf;
corRest.out.payloadSize = strlen(buf);
return true;
}
// -----------------------------------------------------------------------------
//
// getMqttReady - GET /mqttReady — 1 once the MQTT SUBACK has arrived.
//
// A bare integer, like /count: the harness polls this from bash and a JSON
// parser has no business in a readiness barrier. Answers 1 when no MQTT was
// asked for, so a caller need not special-case that.
//
// Three answers, not two:
// 1 subscribed, or none was asked for
// 0 not yet - keep polling
// -1 given up on; polling longer cannot help, and the log says why
//
// -1 is what turns a barrier timeout into an immediate, explained failure.
//
static bool getMqttReady(void)
{
char* buf = (char*) corAlloc(&corRest.kalloc, 4);
int state = ((ftMqttPort == 0) || (ftMqttSubscribed == true))? 1 :
(ftMqttFailed == true)? -1 : 0;
snprintf(buf, 4, "%d", state);
corRest.out.payload = buf;
corRest.out.payloadSize = strlen(buf);
return true;
}
// -----------------------------------------------------------------------------
//
// getProbeCount - GET /probeCount — number of sourceIdentity probes seen.
//
// Probes are infrastructure (§ 5.15 alias discovery) and are deliberately kept
// out of the request dump, so a test can't count them there. This bare-integer
// endpoint lets a test assert the probe fired (no contextSourceAlias supplied)
// or did NOT fire (alias supplied in the registration → probe skipped).
//
static bool getProbeCount(void)
{
char* buf = (char*) corAlloc(&corRest.kalloc, 16);
snprintf(buf, 16, "%d", probeCount);
corRest.out.payload = buf;
corRest.out.payloadSize = strlen(buf);
return true;
}
// -----------------------------------------------------------------------------
//
// getDie - GET /die — exit the process
//
static bool getDie(void)
{
corRest.out.httpStatusCode = 200;
corRest.out.payload = (char*) "bye";
corRest.out.payloadSize = 3;
// Schedule exit after the response is sent
// (MHD_RESPMEM_MUST_COPY means corRest copies the buffer before we exit)
_exit(0);
return true; // unreachable
}
// -----------------------------------------------------------------------------
//
// ftStubMatch - first stub matching the verb (exact) and path (substring)
//
static FtStub* ftStubMatch(const char* verb, const char* path)
{
if (verb == NULL || path == NULL)
return NULL;
for (FtStub* s = ftStubs; s != NULL; s = s->next)
if ((strcmp(s->verb, verb) == 0) && (strstr(path, s->path) != NULL))
return s;
return NULL;
}
// -----------------------------------------------------------------------------
//
// stubServe - if a stub matches the current request, serve it (return true)
//
static bool stubServe(void)
{
FtStub* s = ftStubMatch(corRest.in.verbString, corRest.in.urlPath);
if (s == NULL)
return false;
// Per-path delay — lets a test time out ONLY a specific endpoint (e.g. the
// sourceIdentity probe) without the global --delay slowing the forwards too.
if (s->delayMs > 0)
usleep(s->delayMs * 1000);
corRest.out.httpStatusCode = s->status;
if (s->body != NULL)
{
int n = strlen(s->body);
char* buf = (char*) corAlloc(&corRest.kalloc, n + 1);
memcpy(buf, s->body, n + 1);
corRest.out.payload = buf;
corRest.out.payloadSize = n;
}
COR_T(1, "stub served: %s %s -> %d (bodyLen=%d)", s->verb, corRest.in.urlPath, s->status, s->body ? (int) strlen(s->body) : 0);
return true;
}
// -----------------------------------------------------------------------------
//
// postMockReply - POST /mock/reply — program a stubbed response
//
// Body: { "verb": "POST", "path": "/attrs/", "status": 207, "body": {...} }
// verb/path/status default to "POST" / "/" / 200; body is optional.
//
static bool postMockReply(void)
{
CorNode* tree = corRest.in.requestTree;
if (tree == NULL)
{
corRest.out.httpStatusCode = 400;
return true;
}
CorNode* verbP = corTreeLookup(tree, "verb");
CorNode* pathP = corTreeLookup(tree, "path");
CorNode* statusP = corTreeLookup(tree, "status");
CorNode* delayP = corTreeLookup(tree, "delayMs"); // sleep before responding (per-path timeout injection)
CorNode* bodyP = corTreeLookup(tree, "body");
CorNode* rawP = corTreeLookup(tree, "raw"); // verbatim body (e.g. malformed JSON for a 502 test)
FtStub* s = (FtStub*) calloc(1, sizeof(FtStub));
s->verb = strdup(((verbP != NULL) && (verbP->type == CorString)) ? verbP->value.s : "POST");
s->path = strdup(((pathP != NULL) && (pathP->type == CorString)) ? pathP->value.s : "/");
s->status = ((statusP != NULL) && (statusP->type == CorInt)) ? (int) statusP->value.i : 200;
s->delayMs = ((delayP != NULL) && (delayP->type == CorInt)) ? (int) delayP->value.i : 0;
s->body = NULL;
if ((rawP != NULL) && (rawP->type == CorString))
s->body = strdup(rawP->value.s);
else if (bodyP != NULL)
{
bodyP->name = NULL; // render the value alone, not "body": {...}
int n = corJsonFastRenderSize(bodyP) + 1;
s->body = (char*) malloc(n);
corJsonFastRender(bodyP, s->body);
}
s->next = ftStubs;
ftStubs = s;
COR_T(1, "stub programmed: %s <path-contains %s> -> %d", s->verb, s->path, s->status);
corRest.out.httpStatusCode = 201;
return true;
}
// -----------------------------------------------------------------------------
//
// deleteMockReply - DELETE /mock/reply — clear all programmed stubs
//
static bool deleteMockReply(void)
{
while (ftStubs != NULL)