-
Notifications
You must be signed in to change notification settings - Fork 496
Expand file tree
/
Copy pathDataProcessingDevice.cxx
More file actions
2571 lines (2380 loc) · 119 KB
/
DataProcessingDevice.cxx
File metadata and controls
2571 lines (2380 loc) · 119 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
// Copyright 2019-2020 CERN and copyright holders of ALICE O2.
// See https://alice-o2.web.cern.ch/copyright for details of the copyright holders.
// All rights not expressly granted are reserved.
//
// This software is distributed under the terms of the GNU General Public
// License v3 (GPL Version 3), copied verbatim in the file "COPYING".
//
// In applying this license CERN does not waive the privileges and immunities
// granted to it by virtue of its status as an Intergovernmental Organization
// or submit itself to any jurisdiction.
#include "Framework/AsyncQueue.h"
#include "Framework/DataProcessingDevice.h"
#include <atomic>
#include "Framework/ControlService.h"
#include "Framework/ComputingQuotaEvaluator.h"
#include "Framework/DataProcessingHeader.h"
#include "Framework/DataProcessingStates.h"
#include "Framework/DataProcessor.h"
#include "Framework/DataSpecUtils.h"
#include "Framework/DeviceState.h"
#include "Framework/DeviceStateEnums.h"
#include "Framework/DispatchPolicy.h"
#include "Framework/DispatchControl.h"
#include "Framework/DanglingContext.h"
#include "Framework/DomainInfoHeader.h"
#include "Framework/DriverClient.h"
#include "Framework/EndOfStreamContext.h"
#include "Framework/FairOptionsRetriever.h"
#include "ConfigurationOptionsRetriever.h"
#include "Framework/FairMQDeviceProxy.h"
#include "Framework/CallbackService.h"
#include "Framework/InputRecord.h"
#include "Framework/InputSpan.h"
#if defined(__APPLE__) || defined(NDEBUG)
#define O2_SIGNPOST_IMPLEMENTATION
#endif
#include "Framework/Signpost.h"
#include "Framework/TimingHelpers.h"
#include "Framework/SourceInfoHeader.h"
#include "Framework/DriverClient.h"
#include "Framework/TimesliceIndex.h"
#include "Framework/VariableContextHelpers.h"
#include "Framework/DataProcessingContext.h"
#include "Framework/DataProcessingHeader.h"
#include "Framework/DeviceContext.h"
#include "Framework/RawDeviceService.h"
#include "Framework/StreamContext.h"
#include "Framework/DefaultsHelpers.h"
#include "Framework/ServiceRegistryRef.h"
#include "DecongestionService.h"
#include "Framework/DataProcessingHelpers.h"
#include "Framework/DataModelViews.h"
#include "DataRelayerHelpers.h"
#include "Headers/DataHeader.h"
#include "Headers/DataHeaderHelpers.h"
#include <Framework/Tracing.h>
#include <fairmq/Parts.h>
#include <fairmq/Socket.h>
#include <fairmq/ProgOptions.h>
#include <fairmq/shmem/Message.h>
#include <Configuration/ConfigurationInterface.h>
#include <Configuration/ConfigurationFactory.h>
#include <Monitoring/Monitoring.h>
#include <TMessage.h>
#include <TClonesArray.h>
#include <fmt/ostream.h>
#include <algorithm>
#include <vector>
#include <numeric>
#include <memory>
#include <uv.h>
#include <execinfo.h>
#include <sstream>
#include <boost/property_tree/json_parser.hpp>
// Formatter to avoid having to rewrite the ostream operator for the enum
namespace fmt
{
template <>
struct formatter<o2::framework::CompletionPolicy::CompletionOp> : ostream_formatter {
};
} // namespace fmt
// A log to use for general device logging
O2_DECLARE_DYNAMIC_LOG(device);
// A log to use for general device logging
O2_DECLARE_DYNAMIC_LOG(sockets);
// Special log to keep track of the lifetime of the parts
O2_DECLARE_DYNAMIC_LOG(parts);
// Stream which keeps track of the calibration lifetime logic
O2_DECLARE_DYNAMIC_LOG(calibration);
// Special log to track the async queue behavior
O2_DECLARE_DYNAMIC_LOG(async_queue);
// Special log to track the forwarding requests
O2_DECLARE_DYNAMIC_LOG(forwarding);
// Special log to track CCDB related requests
O2_DECLARE_DYNAMIC_LOG(ccdb);
// Special log to track task scheduling
O2_DECLARE_DYNAMIC_LOG(scheduling);
using namespace o2::framework;
using ConfigurationInterface = o2::configuration::ConfigurationInterface;
using DataHeader = o2::header::DataHeader;
constexpr int DEFAULT_MAX_CHANNEL_AHEAD = 128;
namespace o2::framework
{
template <>
struct ServiceKindExtractor<ConfigurationInterface> {
constexpr static ServiceKind kind = ServiceKind::Global;
};
/// We schedule a timer to reduce CPU usage.
/// Watching stdin for commands probably a better approach.
void on_idle_timer(uv_timer_t* handle)
{
auto* state = (DeviceState*)handle->data;
state->loopReason |= DeviceState::TIMER_EXPIRED;
}
void on_communication_requested(uv_async_t* s)
{
auto* state = (DeviceState*)s->data;
state->loopReason |= DeviceState::METRICS_MUST_FLUSH;
}
DeviceSpec const& getRunningDevice(RunningDeviceRef const& running, ServiceRegistryRef const& services)
{
auto& devices = services.get<o2::framework::RunningWorkflowInfo const>().devices;
return devices[running.index];
}
struct locked_execution {
ServiceRegistryRef& ref;
locked_execution(ServiceRegistryRef& ref_) : ref(ref_) { ref.lock(); }
~locked_execution() { ref.unlock(); }
};
DataProcessingDevice::DataProcessingDevice(RunningDeviceRef running, ServiceRegistry& registry)
: mRunningDevice{running},
mConfigRegistry{nullptr},
mServiceRegistry{registry}
{
GetConfig()->Subscribe<std::string>("dpl", [®istry = mServiceRegistry](const std::string& key, std::string value) {
if (key == "cleanup") {
auto ref = ServiceRegistryRef{registry, ServiceRegistry::globalDeviceSalt()};
auto& deviceState = ref.get<DeviceState>();
int64_t cleanupCount = deviceState.cleanupCount.load();
int64_t newCleanupCount = std::stoll(value);
if (newCleanupCount <= cleanupCount) {
return;
}
deviceState.cleanupCount.store(newCleanupCount);
for (auto& info : deviceState.inputChannelInfos) {
fair::mq::Parts parts;
while (info.channel->Receive(parts, 0)) {
LOGP(debug, "Dropping {} parts", parts.Size());
if (parts.Size() == 0) {
break;
}
}
}
}
});
std::function<void(const fair::mq::State)> stateWatcher = [this, ®istry = mServiceRegistry](const fair::mq::State state) -> void {
auto ref = ServiceRegistryRef{registry, ServiceRegistry::globalDeviceSalt()};
auto& deviceState = ref.get<DeviceState>();
auto& control = ref.get<ControlService>();
auto& callbacks = ref.get<CallbackService>();
control.notifyDeviceState(fair::mq::GetStateName(state));
callbacks.call<CallbackService::Id::DeviceStateChanged>(ServiceRegistryRef{ref}, (int)state);
if (deviceState.nextFairMQState.empty() == false) {
auto state = deviceState.nextFairMQState.back();
(void)this->ChangeState(state);
deviceState.nextFairMQState.pop_back();
}
};
// 99 is to execute DPL callbacks last
this->SubscribeToStateChange("99-dpl", stateWatcher);
// One task for now.
mStreams.resize(1);
mHandles.resize(1);
ServiceRegistryRef ref{mServiceRegistry};
mAwakeHandle = (uv_async_t*)malloc(sizeof(uv_async_t));
auto& state = ref.get<DeviceState>();
assert(state.loop);
int res = uv_async_init(state.loop, mAwakeHandle, on_communication_requested);
mAwakeHandle->data = &state;
if (res < 0) {
LOG(error) << "Unable to initialise subscription";
}
/// This should post a message on the queue...
SubscribeToNewTransition("dpl", [wakeHandle = mAwakeHandle](fair::mq::Transition t) {
int res = uv_async_send(wakeHandle);
if (res < 0) {
LOG(error) << "Unable to notify subscription";
}
LOG(debug) << "State transition requested";
});
}
// Callback to execute the processing. Notice how the data is
// is a vector of DataProcessorContext so that we can index the correct
// one with the thread id. For the moment we simply use the first one.
void run_callback(uv_work_t* handle)
{
auto* task = (TaskStreamInfo*)handle->data;
auto ref = ServiceRegistryRef{*task->registry, ServiceRegistry::globalStreamSalt(task->id.index + 1)};
// We create a new signpost interval for this specific data processor. Same id, same data processor.
auto& dataProcessorContext = ref.get<DataProcessorContext>();
O2_SIGNPOST_ID_FROM_POINTER(sid, device, &dataProcessorContext);
O2_SIGNPOST_START(device, sid, "run_callback", "Starting run callback on stream %d", task->id.index);
DataProcessingDevice::doPrepare(ref);
DataProcessingDevice::doRun(ref);
O2_SIGNPOST_END(device, sid, "run_callback", "Done processing data for stream %d", task->id.index);
}
// Once the processing in a thread is done, this is executed on the main thread.
void run_completion(uv_work_t* handle, int status)
{
auto* task = (TaskStreamInfo*)handle->data;
// Notice that the completion, while running on the main thread, still
// has a salt which is associated to the actual stream which was doing the computation
auto ref = ServiceRegistryRef{*task->registry, ServiceRegistry::globalStreamSalt(task->id.index + 1)};
auto& state = ref.get<DeviceState>();
auto& quotaEvaluator = ref.get<ComputingQuotaEvaluator>();
using o2::monitoring::Metric;
using o2::monitoring::Monitoring;
using o2::monitoring::tags::Key;
using o2::monitoring::tags::Value;
static std::function<void(ComputingQuotaOffer const&, ComputingQuotaStats&)> reportConsumedOffer = [ref](ComputingQuotaOffer const& accumulatedConsumed, ComputingQuotaStats& stats) {
auto& dpStats = ref.get<DataProcessingStats>();
stats.totalConsumedBytes += accumulatedConsumed.sharedMemory;
// For now we give back the offer if we did not use it completely.
// In principle we should try to run until the offer is fully consumed.
stats.totalConsumedTimeslices += std::min<int64_t>(accumulatedConsumed.timeslices, 1);
dpStats.updateStats({static_cast<short>(ProcessingStatsId::SHM_OFFER_BYTES_CONSUMED), DataProcessingStats::Op::Set, stats.totalConsumedBytes});
dpStats.updateStats({static_cast<short>(ProcessingStatsId::TIMESLICE_OFFER_NUMBER_CONSUMED), DataProcessingStats::Op::Set, stats.totalConsumedTimeslices});
dpStats.processCommandQueue();
assert(stats.totalConsumedBytes == dpStats.metrics[(short)ProcessingStatsId::SHM_OFFER_BYTES_CONSUMED]);
assert(stats.totalConsumedTimeslices == dpStats.metrics[(short)ProcessingStatsId::TIMESLICE_OFFER_NUMBER_CONSUMED]);
};
static std::function<void(ComputingQuotaOffer const&, ComputingQuotaStats const&)> reportExpiredOffer = [ref](ComputingQuotaOffer const& offer, ComputingQuotaStats const& stats) {
auto& dpStats = ref.get<DataProcessingStats>();
dpStats.updateStats({static_cast<short>(ProcessingStatsId::RESOURCE_OFFER_EXPIRED), DataProcessingStats::Op::Set, stats.totalExpiredOffers});
dpStats.updateStats({static_cast<short>(ProcessingStatsId::ARROW_BYTES_EXPIRED), DataProcessingStats::Op::Set, stats.totalExpiredBytes});
dpStats.updateStats({static_cast<short>(ProcessingStatsId::TIMESLICE_NUMBER_EXPIRED), DataProcessingStats::Op::Set, stats.totalExpiredTimeslices});
dpStats.processCommandQueue();
};
for (auto& consumer : state.offerConsumers) {
quotaEvaluator.consume(task->id.index, consumer, reportConsumedOffer);
}
state.offerConsumers.clear();
quotaEvaluator.handleExpired(reportExpiredOffer);
quotaEvaluator.dispose(task->id.index);
task->running = false;
}
// Context for polling
struct PollerContext {
enum struct PollerState : char { Stopped,
Disconnected,
Connected,
Suspended };
char const* name = nullptr;
uv_loop_t* loop = nullptr;
DataProcessingDevice* device = nullptr;
DeviceState* state = nullptr;
fair::mq::Socket* socket = nullptr;
InputChannelInfo* channelInfo = nullptr;
int fd = -1;
bool read = true;
PollerState pollerState = PollerState::Stopped;
};
void on_socket_polled(uv_poll_t* poller, int status, int events)
{
auto* context = (PollerContext*)poller->data;
assert(context);
O2_SIGNPOST_ID_FROM_POINTER(sid, sockets, poller);
context->state->loopReason |= DeviceState::DATA_SOCKET_POLLED;
switch (events) {
case UV_READABLE: {
O2_SIGNPOST_EVENT_EMIT(sockets, sid, "socket_state", "Data pending on socket for channel %{public}s", context->name);
context->state->loopReason |= DeviceState::DATA_INCOMING;
} break;
case UV_WRITABLE: {
O2_SIGNPOST_END(sockets, sid, "socket_state", "Socket connected for channel %{public}s", context->name);
if (context->read) {
O2_SIGNPOST_START(sockets, sid, "socket_state", "Socket connected for read in context %{public}s", context->name);
uv_poll_start(poller, UV_READABLE | UV_DISCONNECT | UV_PRIORITIZED, &on_socket_polled);
context->state->loopReason |= DeviceState::DATA_CONNECTED;
} else {
O2_SIGNPOST_START(sockets, sid, "socket_state", "Socket connected for write for channel %{public}s", context->name);
context->state->loopReason |= DeviceState::DATA_OUTGOING;
// If the socket is writable, fairmq will handle the rest, so we can stop polling and
// just wait for the disconnect.
uv_poll_start(poller, UV_DISCONNECT | UV_PRIORITIZED, &on_socket_polled);
}
context->pollerState = PollerContext::PollerState::Connected;
} break;
case UV_DISCONNECT: {
O2_SIGNPOST_END(sockets, sid, "socket_state", "Socket disconnected in context %{public}s", context->name);
} break;
case UV_PRIORITIZED: {
O2_SIGNPOST_EVENT_EMIT(sockets, sid, "socket_state", "Socket prioritized for context %{public}s", context->name);
} break;
}
// We do nothing, all the logic for now stays in DataProcessingDevice::doRun()
}
void on_out_of_band_polled(uv_poll_t* poller, int status, int events)
{
O2_SIGNPOST_ID_FROM_POINTER(sid, sockets, poller);
auto* context = (PollerContext*)poller->data;
context->state->loopReason |= DeviceState::OOB_ACTIVITY;
if (status < 0) {
LOGP(fatal, "Error while polling {}: {}", context->name, status);
uv_poll_start(poller, UV_WRITABLE, &on_out_of_band_polled);
}
switch (events) {
case UV_READABLE: {
O2_SIGNPOST_EVENT_EMIT(sockets, sid, "socket_state", "Data pending on socket for channel %{public}s", context->name);
context->state->loopReason |= DeviceState::DATA_INCOMING;
assert(context->channelInfo);
context->channelInfo->readPolled = true;
} break;
case UV_WRITABLE: {
O2_SIGNPOST_END(sockets, sid, "socket_state", "OOB socket connected for channel %{public}s", context->name);
if (context->read) {
O2_SIGNPOST_START(sockets, sid, "socket_state", "OOB socket connected for read in context %{public}s", context->name);
uv_poll_start(poller, UV_READABLE | UV_DISCONNECT | UV_PRIORITIZED, &on_out_of_band_polled);
} else {
O2_SIGNPOST_START(sockets, sid, "socket_state", "OOB socket connected for write for channel %{public}s", context->name);
context->state->loopReason |= DeviceState::DATA_OUTGOING;
}
} break;
case UV_DISCONNECT: {
O2_SIGNPOST_END(sockets, sid, "socket_state", "OOB socket disconnected in context %{public}s", context->name);
uv_poll_start(poller, UV_WRITABLE, &on_out_of_band_polled);
} break;
case UV_PRIORITIZED: {
O2_SIGNPOST_EVENT_EMIT(sockets, sid, "socket_state", "OOB socket prioritized for context %{public}s", context->name);
} break;
}
// We do nothing, all the logic for now stays in DataProcessingDevice::doRun()
}
/// This takes care of initialising the device from its specification. In
/// particular it needs to:
///
/// * Fetch parameters from configuration
/// * Materialize the correct callbacks for expiring records. We need to do it
/// here because the configuration is available only at this point.
/// * Invoke the actual init callback, which returns the processing callback.
void DataProcessingDevice::Init()
{
auto ref = ServiceRegistryRef{mServiceRegistry};
auto& context = ref.get<DataProcessorContext>();
auto& spec = getRunningDevice(mRunningDevice, ref);
O2_SIGNPOST_ID_FROM_POINTER(cid, device, &context);
O2_SIGNPOST_START(device, cid, "Init", "Entering Init callback.");
context.statelessProcess = spec.algorithm.onProcess;
context.statefulProcess = nullptr;
context.error = spec.algorithm.onError;
context.initError = spec.algorithm.onInitError;
auto configStore = DeviceConfigurationHelpers::getConfiguration(mServiceRegistry, spec.name.c_str(), spec.options);
if (configStore == nullptr) {
std::vector<std::unique_ptr<ParamRetriever>> retrievers;
retrievers.emplace_back(std::make_unique<FairOptionsRetriever>(GetConfig()));
configStore = std::make_unique<ConfigParamStore>(spec.options, std::move(retrievers));
configStore->preload();
configStore->activate();
}
using boost::property_tree::ptree;
/// Dump the configuration so that we can get it from the driver.
for (auto& entry : configStore->store()) {
std::stringstream ss;
std::string str;
if (entry.second.empty() == false) {
boost::property_tree::json_parser::write_json(ss, entry.second, false);
str = ss.str();
str.pop_back(); // remove EoL
} else {
str = entry.second.get_value<std::string>();
}
std::string configString = fmt::format("[CONFIG] {}={} 1 {}", entry.first, str, configStore->provenance(entry.first.c_str())).c_str();
mServiceRegistry.get<DriverClient>(ServiceRegistry::globalDeviceSalt()).tell(configString.c_str());
}
mConfigRegistry = std::make_unique<ConfigParamRegistry>(std::move(configStore));
// Setup the error handlers for init
if (context.initError) {
context.initErrorHandling = [&errorCallback = context.initError,
&serviceRegistry = mServiceRegistry](RuntimeErrorRef e) {
/// FIXME: we should pass the salt in, so that the message
/// can access information which were stored in the stream.
ServiceRegistryRef ref{serviceRegistry, ServiceRegistry::globalDeviceSalt()};
auto& context = ref.get<DataProcessorContext>();
auto& err = error_from_ref(e);
O2_SIGNPOST_ID_FROM_POINTER(cid, device, &context);
O2_SIGNPOST_EVENT_EMIT_ERROR(device, cid, "Init", "Exception caught while in Init: %{public}s. Invoking errorCallback.", err.what);
BacktraceHelpers::demangled_backtrace_symbols(err.backtrace, err.maxBacktrace, STDERR_FILENO);
auto& stats = ref.get<DataProcessingStats>();
stats.updateStats({(int)ProcessingStatsId::EXCEPTION_COUNT, DataProcessingStats::Op::Add, 1});
InitErrorContext errorContext{ref, e};
errorCallback(errorContext);
};
} else {
context.initErrorHandling = [&serviceRegistry = mServiceRegistry](RuntimeErrorRef e) {
auto& err = error_from_ref(e);
/// FIXME: we should pass the salt in, so that the message
/// can access information which were stored in the stream.
ServiceRegistryRef ref{serviceRegistry, ServiceRegistry::globalDeviceSalt()};
auto& context = ref.get<DataProcessorContext>();
O2_SIGNPOST_ID_FROM_POINTER(cid, device, &context);
O2_SIGNPOST_EVENT_EMIT_ERROR(device, cid, "Init", "Exception caught while in Init: %{public}s. Exiting with 1.", err.what);
BacktraceHelpers::demangled_backtrace_symbols(err.backtrace, err.maxBacktrace, STDERR_FILENO);
auto& stats = ref.get<DataProcessingStats>();
stats.updateStats({(int)ProcessingStatsId::EXCEPTION_COUNT, DataProcessingStats::Op::Add, 1});
exit(1);
};
}
context.expirationHandlers.clear();
context.init = spec.algorithm.onInit;
if (context.init) {
static bool noCatch = getenv("O2_NO_CATCHALL_EXCEPTIONS") && strcmp(getenv("O2_NO_CATCHALL_EXCEPTIONS"), "0");
InitContext initContext{*mConfigRegistry, mServiceRegistry};
if (noCatch) {
try {
context.statefulProcess = context.init(initContext);
} catch (o2::framework::RuntimeErrorRef e) {
if (context.initErrorHandling) {
(context.initErrorHandling)(e);
}
}
} else {
try {
context.statefulProcess = context.init(initContext);
} catch (std::exception& ex) {
/// Convert a standard exception to a RuntimeErrorRef
/// Notice how this will lose the backtrace information
/// and report the exception coming from here.
auto e = runtime_error(ex.what());
(context.initErrorHandling)(e);
} catch (o2::framework::RuntimeErrorRef e) {
(context.initErrorHandling)(e);
}
}
}
auto& state = ref.get<DeviceState>();
state.inputChannelInfos.resize(spec.inputChannels.size());
/// Internal channels which will never create an actual message
/// should be considered as in "Pull" mode, since we do not
/// expect them to create any data.
int validChannelId = 0;
for (size_t ci = 0; ci < spec.inputChannels.size(); ++ci) {
auto& name = spec.inputChannels[ci].name;
if (name.find(spec.channelPrefix + "from_internal-dpl-clock") == 0) {
state.inputChannelInfos[ci].state = InputChannelState::Pull;
state.inputChannelInfos[ci].id = {ChannelIndex::INVALID};
validChannelId++;
} else {
state.inputChannelInfos[ci].id = {validChannelId++};
}
}
// Invoke the callback policy for this device.
if (spec.callbacksPolicy.policy != nullptr) {
InitContext initContext{*mConfigRegistry, mServiceRegistry};
spec.callbacksPolicy.policy(mServiceRegistry.get<CallbackService>(ServiceRegistry::globalDeviceSalt()), initContext);
}
// Services which are stream should be initialised now
auto* options = GetConfig();
for (size_t si = 0; si < mStreams.size(); ++si) {
ServiceRegistry::Salt streamSalt = ServiceRegistry::streamSalt(si + 1, ServiceRegistry::globalDeviceSalt().dataProcessorId);
mServiceRegistry.lateBindStreamServices(state, *options, streamSalt);
}
O2_SIGNPOST_END(device, cid, "Init", "Exiting Init callback.");
}
void on_signal_callback(uv_signal_t* handle, int signum)
{
O2_SIGNPOST_ID_FROM_POINTER(sid, device, handle);
O2_SIGNPOST_START(device, sid, "signal_state", "Signal %d received.", signum);
auto* registry = (ServiceRegistry*)handle->data;
if (!registry) {
O2_SIGNPOST_END(device, sid, "signal_state", "No registry active. Ignoring signal.");
return;
}
ServiceRegistryRef ref{*registry};
auto& state = ref.get<DeviceState>();
auto& quotaEvaluator = ref.get<ComputingQuotaEvaluator>();
auto& stats = ref.get<DataProcessingStats>();
state.loopReason |= DeviceState::SIGNAL_ARRIVED;
size_t ri = 0;
while (ri != quotaEvaluator.mOffers.size()) {
auto& offer = quotaEvaluator.mOffers[ri];
// We were already offered some sharedMemory, so we
// do not consider the offer.
// FIXME: in principle this should account for memory
// available and being offered, however we
// want to get out of the woods for now.
if (offer.valid && offer.sharedMemory != 0) {
O2_SIGNPOST_END(device, sid, "signal_state", "Memory already offered.");
return;
}
ri++;
}
// Find the first empty offer and have 1GB of shared memory there
for (auto& offer : quotaEvaluator.mOffers) {
if (offer.valid == false) {
offer.cpu = 0;
offer.memory = 0;
offer.sharedMemory = 1000000000;
offer.valid = true;
offer.user = -1;
break;
}
}
stats.updateStats({(int)ProcessingStatsId::TOTAL_SIGUSR1, DataProcessingStats::Op::Add, 1});
O2_SIGNPOST_END(device, sid, "signal_state", "Done processing signals.");
}
struct DecongestionContext {
ServiceRegistryRef ref;
TimesliceIndex::OldestOutputInfo oldestTimeslice;
};
auto decongestionCallbackLate = [](AsyncTask& task, size_t aid) -> void {
auto& oldestTimeslice = task.user<DecongestionContext>().oldestTimeslice;
auto& ref = task.user<DecongestionContext>().ref;
auto& decongestion = ref.get<DecongestionService>();
auto& proxy = ref.get<FairMQDeviceProxy>();
if (oldestTimeslice.timeslice.value <= decongestion.lastTimeslice) {
LOG(debug) << "Not sending already sent oldest possible timeslice " << oldestTimeslice.timeslice.value;
return;
}
for (int fi = 0; fi < proxy.getNumForwardChannels(); fi++) {
auto& info = proxy.getForwardChannelInfo(ChannelIndex{fi});
auto& state = proxy.getForwardChannelState(ChannelIndex{fi});
O2_SIGNPOST_ID_GENERATE(aid, async_queue);
// TODO: this we could cache in the proxy at the bind moment.
if (info.channelType != ChannelAccountingType::DPL) {
O2_SIGNPOST_EVENT_EMIT(async_queue, aid, "forwardInputsCallback", "Skipping channel %{public}s because it's not a DPL channel",
info.name.c_str());
continue;
}
if (DataProcessingHelpers::sendOldestPossibleTimeframe(ref, info, state, oldestTimeslice.timeslice.value)) {
O2_SIGNPOST_EVENT_EMIT(async_queue, aid, "forwardInputsCallback", "Forwarding to channel %{public}s oldest possible timeslice %zu, prio 20",
info.name.c_str(), oldestTimeslice.timeslice.value);
}
}
};
// This is how we do the forwarding, i.e. we push
// the inputs which are shared between this device and others
// to the next one in the daisy chain.
// FIXME: do it in a smarter way than O(N^2)
static auto forwardInputs = [](ServiceRegistryRef registry, TimesliceSlot slot, std::vector<std::vector<fair::mq::MessagePtr>>& currentSetOfInputs,
TimesliceIndex::OldestOutputInfo oldestTimeslice, bool copy, bool consume = true) {
auto& proxy = registry.get<FairMQDeviceProxy>();
O2_SIGNPOST_ID_GENERATE(sid, forwarding);
O2_SIGNPOST_START(forwarding, sid, "forwardInputs", "Starting forwarding for slot %zu with oldestTimeslice %zu %{public}s%{public}s%{public}s",
slot.index, oldestTimeslice.timeslice.value, copy ? "with copy" : "", copy && consume ? " and " : "", consume ? "with consume" : "");
auto forwardedParts = DataProcessingHelpers::routeForwardedMessageSet(proxy, currentSetOfInputs, copy, consume);
for (int fi = 0; fi < proxy.getNumForwardChannels(); fi++) {
if (forwardedParts[fi].Size() == 0) {
continue;
}
ForwardChannelInfo info = proxy.getForwardChannelInfo(ChannelIndex{fi});
auto& parts = forwardedParts[fi];
if (info.policy == nullptr) {
O2_SIGNPOST_EVENT_EMIT_ERROR(forwarding, sid, "forwardInputs", "Forwarding to %{public}s %d has no policy.", info.name.c_str(), fi);
continue;
}
O2_SIGNPOST_EVENT_EMIT(forwarding, sid, "forwardInputs", "Forwarding to %{public}s %d", info.name.c_str(), fi);
info.policy->forward(parts, ChannelIndex{fi}, registry);
}
auto& asyncQueue = registry.get<AsyncQueue>();
auto& decongestion = registry.get<DecongestionService>();
O2_SIGNPOST_ID_GENERATE(aid, async_queue);
O2_SIGNPOST_EVENT_EMIT(async_queue, aid, "forwardInputs", "Queuing forwarding oldestPossible %zu", oldestTimeslice.timeslice.value);
AsyncQueueHelpers::post(asyncQueue, AsyncTask{.timeslice = oldestTimeslice.timeslice, .id = decongestion.oldestPossibleTimesliceTask, .debounce = -1, .callback = decongestionCallbackLate}
.user<DecongestionContext>({.ref = registry, .oldestTimeslice = oldestTimeslice}));
O2_SIGNPOST_END(forwarding, sid, "forwardInputs", "Forwarding done");
};
static auto cleanEarlyForward = [](ServiceRegistryRef registry, TimesliceSlot slot, std::vector<std::vector<fair::mq::MessagePtr>>& currentSetOfInputs,
TimesliceIndex::OldestOutputInfo oldestTimeslice, bool copy, bool consume = true) {
auto& proxy = registry.get<FairMQDeviceProxy>();
O2_SIGNPOST_ID_GENERATE(sid, forwarding);
O2_SIGNPOST_START(forwarding, sid, "forwardInputs", "Cleaning up slot %zu with oldestTimeslice %zu %{public}s%{public}s%{public}s",
slot.index, oldestTimeslice.timeslice.value, copy ? "with copy" : "", copy && consume ? " and " : "", consume ? "with consume" : "");
// Always copy them, because we do not want to actually send them.
// We merely need the side effect of the consume, if applicable.
for (size_t ii = 0, ie = currentSetOfInputs.size(); ii < ie; ++ii) {
auto span = std::span<fair::mq::MessagePtr>(currentSetOfInputs[ii]);
DataProcessingHelpers::cleanForwardedMessages(span, consume);
}
O2_SIGNPOST_END(forwarding, sid, "forwardInputs", "Cleaning done");
};
extern volatile int region_read_global_dummy_variable;
volatile int region_read_global_dummy_variable;
/// Invoke the callbacks for the mPendingRegionInfos
void handleRegionCallbacks(ServiceRegistryRef registry, std::vector<fair::mq::RegionInfo>& infos)
{
if (infos.empty() == false) {
std::vector<fair::mq::RegionInfo> toBeNotified;
toBeNotified.swap(infos); // avoid any MT issue.
static bool dummyRead = getenv("DPL_DEBUG_MAP_ALL_SHM_REGIONS") && atoi(getenv("DPL_DEBUG_MAP_ALL_SHM_REGIONS"));
for (auto const& info : toBeNotified) {
if (dummyRead) {
for (size_t i = 0; i < info.size / sizeof(region_read_global_dummy_variable); i += 4096 / sizeof(region_read_global_dummy_variable)) {
region_read_global_dummy_variable = ((int*)info.ptr)[i];
}
}
registry.get<CallbackService>().call<CallbackService::Id::RegionInfoCallback>(info);
}
}
}
namespace
{
void on_awake_main_thread(uv_async_t* handle)
{
auto* state = (DeviceState*)handle->data;
state->loopReason |= DeviceState::ASYNC_NOTIFICATION;
}
} // namespace
void DataProcessingDevice::initPollers()
{
auto ref = ServiceRegistryRef{mServiceRegistry};
auto& deviceContext = ref.get<DeviceContext>();
auto& context = ref.get<DataProcessorContext>();
auto& spec = ref.get<DeviceSpec const>();
auto& state = ref.get<DeviceState>();
// We add a timer only in case a channel poller is not there.
if ((context.statefulProcess != nullptr) || (context.statelessProcess != nullptr)) {
for (auto& [channelName, channel] : GetChannels()) {
InputChannelInfo* channelInfo;
for (size_t ci = 0; ci < spec.inputChannels.size(); ++ci) {
auto& channelSpec = spec.inputChannels[ci];
channelInfo = &state.inputChannelInfos[ci];
if (channelSpec.name != channelName) {
continue;
}
channelInfo->channel = &this->GetChannel(channelName, 0);
break;
}
if ((channelName.rfind("from_internal-dpl", 0) == 0) &&
(channelName.rfind("from_internal-dpl-aod", 0) != 0) &&
(channelName.rfind("from_internal-dpl-ccdb-backend", 0) != 0) &&
(channelName.rfind("from_internal-dpl-injected", 0)) != 0) {
LOGP(detail, "{} is an internal channel. Skipping as no input will come from there.", channelName);
continue;
}
// We only watch receiving sockets.
if (channelName.rfind("from_" + spec.name + "_", 0) == 0) {
LOGP(detail, "{} is to send data. Not polling.", channelName);
continue;
}
if (channelName.rfind("from_", 0) != 0) {
LOGP(detail, "{} is not a DPL socket. Not polling.", channelName);
continue;
}
// We assume there is always a ZeroMQ socket behind.
int zmq_fd = 0;
size_t zmq_fd_len = sizeof(zmq_fd);
// FIXME: I should probably save those somewhere... ;-)
auto* poller = (uv_poll_t*)malloc(sizeof(uv_poll_t));
channel[0].GetSocket().GetOption("fd", &zmq_fd, &zmq_fd_len);
if (zmq_fd == 0) {
LOG(error) << "Cannot get file descriptor for channel." << channelName;
continue;
}
LOGP(detail, "Polling socket for {}", channelName);
auto* pCtx = (PollerContext*)malloc(sizeof(PollerContext));
pCtx->name = strdup(channelName.c_str());
pCtx->loop = state.loop;
pCtx->device = this;
pCtx->state = &state;
pCtx->fd = zmq_fd;
assert(channelInfo != nullptr);
pCtx->channelInfo = channelInfo;
pCtx->socket = &channel[0].GetSocket();
pCtx->read = true;
poller->data = pCtx;
uv_poll_init(state.loop, poller, zmq_fd);
if (channelName.rfind("from_", 0) != 0) {
LOGP(detail, "{} is an out of band channel.", channelName);
state.activeOutOfBandPollers.push_back(poller);
} else {
channelInfo->pollerIndex = state.activeInputPollers.size();
state.activeInputPollers.push_back(poller);
}
}
// In case we do not have any input channel and we do not have
// any timers or signal watchers we still wake up whenever we can send data to downstream
// devices to allow for enumerations.
if (state.activeInputPollers.empty() &&
state.activeOutOfBandPollers.empty() &&
state.activeTimers.empty() &&
state.activeSignals.empty()) {
// FIXME: this is to make sure we do not reset the output timer
// for readout proxies or similar. In principle this should go once
// we move to OutOfBand InputSpec.
if (state.inputChannelInfos.empty()) {
LOGP(detail, "No input channels. Setting exit transition timeout to 0.");
deviceContext.exitTransitionTimeout = 0;
}
for (auto& [channelName, channel] : GetChannels()) {
if (channelName.rfind(spec.channelPrefix + "from_internal-dpl", 0) == 0) {
LOGP(detail, "{} is an internal channel. Not polling.", channelName);
continue;
}
if (channelName.rfind(spec.channelPrefix + "from_" + spec.name + "_", 0) == 0) {
LOGP(detail, "{} is an out of band channel. Not polling for output.", channelName);
continue;
}
// We assume there is always a ZeroMQ socket behind.
int zmq_fd = 0;
size_t zmq_fd_len = sizeof(zmq_fd);
// FIXME: I should probably save those somewhere... ;-)
auto* poller = (uv_poll_t*)malloc(sizeof(uv_poll_t));
channel[0].GetSocket().GetOption("fd", &zmq_fd, &zmq_fd_len);
if (zmq_fd == 0) {
LOGP(error, "Cannot get file descriptor for channel {}", channelName);
continue;
}
LOG(detail) << "Polling socket for " << channel[0].GetName();
// FIXME: leak
auto* pCtx = (PollerContext*)malloc(sizeof(PollerContext));
pCtx->name = strdup(channelName.c_str());
pCtx->loop = state.loop;
pCtx->device = this;
pCtx->state = &state;
pCtx->fd = zmq_fd;
pCtx->read = false;
poller->data = pCtx;
uv_poll_init(state.loop, poller, zmq_fd);
state.activeOutputPollers.push_back(poller);
}
}
} else {
LOGP(detail, "This is a fake device so we exit after the first iteration.");
deviceContext.exitTransitionTimeout = 0;
// This is a fake device, so we can request to exit immediately
ServiceRegistryRef ref{mServiceRegistry};
ref.get<ControlService>().readyToQuit(QuitRequest::Me);
// A two second timer to stop internal devices which do not want to
auto* timer = (uv_timer_t*)malloc(sizeof(uv_timer_t));
uv_timer_init(state.loop, timer);
timer->data = &state;
uv_update_time(state.loop);
uv_timer_start(timer, on_idle_timer, 2000, 2000);
state.activeTimers.push_back(timer);
}
}
void DataProcessingDevice::startPollers()
{
auto ref = ServiceRegistryRef{mServiceRegistry};
auto& deviceContext = ref.get<DeviceContext>();
auto& state = ref.get<DeviceState>();
for (auto* poller : state.activeInputPollers) {
O2_SIGNPOST_ID_FROM_POINTER(sid, device, poller);
O2_SIGNPOST_START(device, sid, "socket_state", "Input socket waiting for connection.");
uv_poll_start(poller, UV_WRITABLE, &on_socket_polled);
((PollerContext*)poller->data)->pollerState = PollerContext::PollerState::Disconnected;
}
for (auto& poller : state.activeOutOfBandPollers) {
uv_poll_start(poller, UV_WRITABLE, &on_out_of_band_polled);
((PollerContext*)poller->data)->pollerState = PollerContext::PollerState::Disconnected;
}
for (auto* poller : state.activeOutputPollers) {
O2_SIGNPOST_ID_FROM_POINTER(sid, device, poller);
O2_SIGNPOST_START(device, sid, "socket_state", "Output socket waiting for connection.");
uv_poll_start(poller, UV_WRITABLE, &on_socket_polled);
((PollerContext*)poller->data)->pollerState = PollerContext::PollerState::Disconnected;
}
deviceContext.gracePeriodTimer = (uv_timer_t*)malloc(sizeof(uv_timer_t));
deviceContext.gracePeriodTimer->data = new ServiceRegistryRef(mServiceRegistry);
uv_timer_init(state.loop, deviceContext.gracePeriodTimer);
deviceContext.dataProcessingGracePeriodTimer = (uv_timer_t*)malloc(sizeof(uv_timer_t));
deviceContext.dataProcessingGracePeriodTimer->data = new ServiceRegistryRef(mServiceRegistry);
uv_timer_init(state.loop, deviceContext.dataProcessingGracePeriodTimer);
}
void DataProcessingDevice::stopPollers()
{
auto ref = ServiceRegistryRef{mServiceRegistry};
auto& deviceContext = ref.get<DeviceContext>();
auto& state = ref.get<DeviceState>();
LOGP(detail, "Stopping {} input pollers", state.activeInputPollers.size());
for (auto* poller : state.activeInputPollers) {
O2_SIGNPOST_ID_FROM_POINTER(sid, device, poller);
O2_SIGNPOST_END(device, sid, "socket_state", "Output socket closed.");
uv_poll_stop(poller);
((PollerContext*)poller->data)->pollerState = PollerContext::PollerState::Stopped;
}
LOGP(detail, "Stopping {} out of band pollers", state.activeOutOfBandPollers.size());
for (auto* poller : state.activeOutOfBandPollers) {
uv_poll_stop(poller);
((PollerContext*)poller->data)->pollerState = PollerContext::PollerState::Stopped;
}
LOGP(detail, "Stopping {} output pollers", state.activeOutOfBandPollers.size());
for (auto* poller : state.activeOutputPollers) {
O2_SIGNPOST_ID_FROM_POINTER(sid, device, poller);
O2_SIGNPOST_END(device, sid, "socket_state", "Output socket closed.");
uv_poll_stop(poller);
((PollerContext*)poller->data)->pollerState = PollerContext::PollerState::Stopped;
}
uv_timer_stop(deviceContext.gracePeriodTimer);
delete (ServiceRegistryRef*)deviceContext.gracePeriodTimer->data;
free(deviceContext.gracePeriodTimer);
deviceContext.gracePeriodTimer = nullptr;
uv_timer_stop(deviceContext.dataProcessingGracePeriodTimer);
delete (ServiceRegistryRef*)deviceContext.dataProcessingGracePeriodTimer->data;
free(deviceContext.dataProcessingGracePeriodTimer);
deviceContext.dataProcessingGracePeriodTimer = nullptr;
}
void DataProcessingDevice::InitTask()
{
auto ref = ServiceRegistryRef{mServiceRegistry};
auto& deviceContext = ref.get<DeviceContext>();
auto& context = ref.get<DataProcessorContext>();
O2_SIGNPOST_ID_FROM_POINTER(cid, device, &context);
O2_SIGNPOST_START(device, cid, "InitTask", "Entering InitTask callback.");
auto& spec = getRunningDevice(mRunningDevice, mServiceRegistry);
auto distinct = DataRelayerHelpers::createDistinctRouteIndex(spec.inputs);
auto& state = ref.get<DeviceState>();
int i = 0;
for (auto& di : distinct) {
auto& route = spec.inputs[di];
if (route.configurator.has_value() == false) {
i++;
continue;
}
ExpirationHandler handler{
.name = route.configurator->name,
.routeIndex = RouteIndex{i++},
.lifetime = route.matcher.lifetime,
.creator = route.configurator->creatorConfigurator(state, mServiceRegistry, *mConfigRegistry),
.checker = route.configurator->danglingConfigurator(state, *mConfigRegistry),
.handler = route.configurator->expirationConfigurator(state, *mConfigRegistry)};
context.expirationHandlers.emplace_back(std::move(handler));
}
if (state.awakeMainThread == nullptr) {
state.awakeMainThread = (uv_async_t*)malloc(sizeof(uv_async_t));
state.awakeMainThread->data = &state;
uv_async_init(state.loop, state.awakeMainThread, on_awake_main_thread);
}
deviceContext.expectedRegionCallbacks = std::stoi(fConfig->GetValue<std::string>("expected-region-callbacks"));
deviceContext.exitTransitionTimeout = std::stoi(fConfig->GetValue<std::string>("exit-transition-timeout"));
deviceContext.dataProcessingTimeout = std::stoi(fConfig->GetValue<std::string>("data-processing-timeout"));
for (auto& channel : GetChannels()) {
channel.second.at(0).Transport()->SubscribeToRegionEvents([&context = deviceContext,
®istry = mServiceRegistry,
&pendingRegionInfos = mPendingRegionInfos,
®ionInfoMutex = mRegionInfoMutex](fair::mq::RegionInfo info) {
std::lock_guard<std::mutex> lock(regionInfoMutex);
LOG(detail) << ">>> Region info event" << info.event;
LOG(detail) << "id: " << info.id;
LOG(detail) << "ptr: " << info.ptr;
LOG(detail) << "size: " << info.size;
LOG(detail) << "flags: " << info.flags;
// Now we check for pending events with the mutex,
// so the lines below are atomic.
pendingRegionInfos.push_back(info);
context.expectedRegionCallbacks -= 1;
// We always want to handle these on the main loop,
// so we awake it.
ServiceRegistryRef ref{registry};
uv_async_send(ref.get<DeviceState>().awakeMainThread);
});
}
// Add a signal manager for SIGUSR1 so that we can force
// an event from the outside, making sure that the event loop can
// be unblocked (e.g. by a quitting DPL driver) even when there
// is no data pending to be processed.
if (deviceContext.sigusr1Handle == nullptr) {
deviceContext.sigusr1Handle = (uv_signal_t*)malloc(sizeof(uv_signal_t));
deviceContext.sigusr1Handle->data = &mServiceRegistry;
uv_signal_init(state.loop, deviceContext.sigusr1Handle);
uv_signal_start(deviceContext.sigusr1Handle, on_signal_callback, SIGUSR1);
}
// If there is any signal, we want to make sure they are active
for (auto& handle : state.activeSignals) {
handle->data = &state;
}
// When we start, we must make sure that we do listen to the signal
deviceContext.sigusr1Handle->data = &mServiceRegistry;
/// Initialise the pollers
DataProcessingDevice::initPollers();
// Whenever we InitTask, we consider as if the previous iteration
// was successful, so that even if there is no timer or receiving
// channel, we can still start an enumeration.
DataProcessorContext* initialContext = nullptr;
bool idle = state.lastActiveDataProcessor.compare_exchange_strong(initialContext, (DataProcessorContext*)-1);
if (!idle) {
LOG(error) << "DataProcessor " << state.lastActiveDataProcessor.load()->spec->name << " was unexpectedly active";
}
// We should be ready to run here. Therefore we copy all the
// required parts in the DataProcessorContext. Eventually we should
// do so on a per thread basis, with fine grained locks.
// FIXME: this should not use ServiceRegistry::threadSalt, but
// more a ServiceRegistry::globalDataProcessorSalt(N) where
// N is the number of the multiplexed data processor.
// We will get there.
this->fillContext(mServiceRegistry.get<DataProcessorContext>(ServiceRegistry::globalDeviceSalt()), deviceContext);
O2_SIGNPOST_END(device, cid, "InitTask", "Exiting InitTask callback waiting for the remaining region callbacks.");
auto hasPendingEvents = [&mutex = mRegionInfoMutex, &pendingRegionInfos = mPendingRegionInfos](DeviceContext& deviceContext) {
std::lock_guard<std::mutex> lock(mutex);
return (pendingRegionInfos.empty() == false) || deviceContext.expectedRegionCallbacks > 0;
};
O2_SIGNPOST_START(device, cid, "InitTask", "Waiting for registation events.");
/// We now run an event loop also in InitTask. This is needed to:
/// * Make sure region registration callbacks are invoked
/// on the main thread.
/// * Wait for enough callbacks to be delivered before moving to START
while (hasPendingEvents(deviceContext)) {
// Wait for the callback to signal its done, so that we do not busy wait.
uv_run(state.loop, UV_RUN_ONCE);
// Handle callbacks if any
{
O2_SIGNPOST_EVENT_EMIT(device, cid, "InitTask", "Memory registration event received.");
std::lock_guard<std::mutex> lock(mRegionInfoMutex);
handleRegionCallbacks(mServiceRegistry, mPendingRegionInfos);
}
}
O2_SIGNPOST_END(device, cid, "InitTask", "Done waiting for registration events.");
}
void DataProcessingDevice::fillContext(DataProcessorContext& context, DeviceContext& deviceContext)
{
context.isSink = false;
// If nothing is a sink, the rate limiting simply does not trigger.
bool enableRateLimiting = std::stoi(fConfig->GetValue<std::string>("timeframes-rate-limit"));
auto ref = ServiceRegistryRef{mServiceRegistry};
auto& spec = ref.get<DeviceSpec const>();
// The policy is now allowed to state the default.
context.balancingInputs = spec.completionPolicy.balanceChannels;