forked from AliceO2Group/AliceO2
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrunDataProcessing.cxx
More file actions
3227 lines (3013 loc) · 138 KB
/
runDataProcessing.cxx
File metadata and controls
3227 lines (3013 loc) · 138 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 <memory>
#include "Framework/TopologyPolicyHelpers.h"
#define BOOST_BIND_GLOBAL_PLACEHOLDERS
#include <stdexcept>
#include "Framework/BoostOptionsRetriever.h"
#include "Framework/BacktraceHelpers.h"
#include "Framework/CallbacksPolicy.h"
#include "Framework/ChannelConfigurationPolicy.h"
#include "Framework/ChannelMatching.h"
#include "Framework/ConfigParamsHelper.h"
#include "Framework/ConfigParamSpec.h"
#include "Framework/ConfigContext.h"
#include "Framework/ComputingQuotaEvaluator.h"
#include "CommonDriverServices.h"
#include "Framework/DataProcessingDevice.h"
#include "Framework/DataProcessingContext.h"
#include "Framework/DataProcessorSpec.h"
#include "Framework/PluginManager.h"
#include "Framework/DeviceControl.h"
#include "Framework/DeviceExecution.h"
#include "Framework/DeviceInfo.h"
#include "Framework/DeviceMetricsInfo.h"
#include "Framework/DeviceMetricsHelper.h"
#include "Framework/DeviceConfigInfo.h"
#include "Framework/DeviceSpec.h"
#include "Framework/DeviceState.h"
#include "Framework/DeviceConfig.h"
#include "DeviceStateHelpers.h"
#include "Framework/ServiceRegistryHelpers.h"
#include "Framework/DevicesManager.h"
#include "Framework/DebugGUI.h"
#include "Framework/LocalRootFileService.h"
#include "Framework/LogParsingHelpers.h"
#include "Framework/Logger.h"
#include "Framework/ParallelContext.h"
#include "Framework/RawDeviceService.h"
#include "Framework/SimpleRawDeviceService.h"
#include "Framework/Signpost.h"
#include "Framework/ControlService.h"
#include "Framework/CallbackService.h"
#include "Framework/WorkflowSpec.h"
#include "Framework/Monitoring.h"
#include "Framework/DataProcessorInfo.h"
#include "Framework/DriverInfo.h"
#include "Framework/DriverConfig.h"
#include "Framework/DriverControl.h"
#include "Framework/DataTakingContext.h"
#include "Framework/CommandInfo.h"
#include "Framework/RunningWorkflowInfo.h"
#include "Framework/TopologyPolicy.h"
#include "Framework/WorkflowSpecNode.h"
#include "Framework/GuiCallbackContext.h"
#include "Framework/DeviceContext.h"
#include "Framework/ServiceMetricsInfo.h"
#include "Framework/DataTakingContext.h"
#include "Framework/CommonServices.h"
#include "Framework/DefaultsHelpers.h"
#include "ProcessingPoliciesHelpers.h"
#include "DriverServerContext.h"
#include "HTTPParser.h"
#include "DPLWebSocket.h"
#include "ArrowSupport.h"
#include "Framework/ConfigParamDiscovery.h"
#include "ComputingResourceHelpers.h"
#include "DataProcessingStatus.h"
#include "DDSConfigHelpers.h"
#include "O2ControlHelpers.h"
#include "DeviceSpecHelpers.h"
#include "GraphvizHelpers.h"
#include "MermaidHelpers.h"
#include "PropertyTreeHelpers.h"
#include "SimpleResourceManager.h"
#include "WorkflowSerializationHelpers.h"
#include <Configuration/ConfigurationInterface.h>
#include <Configuration/ConfigurationFactory.h>
#include <Monitoring/MonitoringFactory.h>
#include "ResourcesMonitoringHelper.h"
#include <fairmq/Device.h>
#include <fairmq/DeviceRunner.h>
#include <fairmq/shmem/Monitor.h>
#include <fairmq/ProgOptions.h>
#include <boost/program_options.hpp>
#include <boost/program_options/options_description.hpp>
#include <boost/program_options/variables_map.hpp>
#include <boost/exception/diagnostic_information.hpp>
#include <boost/property_tree/json_parser.hpp>
#include <uv.h>
#include <TEnv.h>
#include <TSystem.h>
#include <cinttypes>
#include <cstdint>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <csignal>
#include <iostream>
#include <map>
#include <regex>
#include <set>
#include <string>
#include <type_traits>
#include <tuple>
#include <chrono>
#include <utility>
#include <numeric>
#include <functional>
#include <fcntl.h>
#include <netinet/ip.h>
#include <sys/resource.h>
#include <sys/select.h>
#include <sys/socket.h>
#include <sys/stat.h>
#include <sys/time.h>
#include <sys/types.h>
#include <sys/un.h>
#include <sys/wait.h>
#include <unistd.h>
#include <execinfo.h>
#include <cfenv>
#if defined(__linux__) && __has_include(<sched.h>)
#include <sched.h>
#elif __has_include(<linux/getcpu.h>)
#include <linux/getcpu.h>
#elif __has_include(<cpuid.h>) && (__x86_64__ || __i386__)
#include <cpuid.h>
#define CPUID(INFO, LEAF, SUBLEAF) __cpuid_count(LEAF, SUBLEAF, INFO[0], INFO[1], INFO[2], INFO[3])
#define GETCPU(CPU) \
{ \
uint32_t CPUInfo[4]; \
CPUID(CPUInfo, 1, 0); \
/* CPUInfo[1] is EBX, bits 24-31 are APIC ID */ \
if ((CPUInfo[3] & (1 << 9)) == 0) { \
CPU = -1; /* no APIC on chip */ \
} else { \
CPU = (unsigned)CPUInfo[1] >> 24; \
} \
if (CPU < 0) \
CPU = 0; \
}
#endif
using namespace o2::monitoring;
using namespace o2::configuration;
using namespace o2::framework;
namespace bpo = boost::program_options;
using DataProcessorInfos = std::vector<DataProcessorInfo>;
using DeviceExecutions = std::vector<DeviceExecution>;
using DeviceSpecs = std::vector<DeviceSpec>;
using DeviceInfos = std::vector<DeviceInfo>;
using DataProcessingStatesInfos = std::vector<DataProcessingStates>;
using DeviceControls = std::vector<DeviceControl>;
using DataProcessorSpecs = std::vector<DataProcessorSpec>;
std::vector<DeviceMetricsInfo> gDeviceMetricsInfos;
// FIXME: probably find a better place
// these are the device options added by the framework, but they can be
// overloaded in the config spec
bpo::options_description gHiddenDeviceOptions("Hidden child options");
O2_DECLARE_DYNAMIC_LOG(driver);
O2_DECLARE_DYNAMIC_LOG(gui);
void doBoostException(boost::exception& e, const char*);
void doDPLException(o2::framework::RuntimeErrorRef& ref, char const*);
void doUnknownException(std::string const& s, char const*);
char* getIdString(int argc, char** argv)
{
for (int argi = 0; argi < argc; argi++) {
if (strcmp(argv[argi], "--id") == 0 && argi + 1 < argc) {
return argv[argi + 1];
}
}
return nullptr;
}
int callMain(int argc, char** argv, int (*mainNoCatch)(int, char**))
{
static bool noCatch = getenv("O2_NO_CATCHALL_EXCEPTIONS") && strcmp(getenv("O2_NO_CATCHALL_EXCEPTIONS"), "0");
int result = 1;
if (noCatch) {
try {
result = mainNoCatch(argc, argv);
} catch (o2::framework::RuntimeErrorRef& ref) {
doDPLException(ref, argv[0]);
throw;
}
} else {
try {
// The 0 here is an int, therefore having the template matching in the
// SFINAE expression above fit better the version which invokes user code over
// the default one.
// The default policy is a catch all pub/sub setup to be consistent with the past.
result = mainNoCatch(argc, argv);
} catch (boost::exception& e) {
doBoostException(e, argv[0]);
throw;
} catch (std::exception const& error) {
doUnknownException(error.what(), argv[0]);
throw;
} catch (o2::framework::RuntimeErrorRef& ref) {
doDPLException(ref, argv[0]);
throw;
} catch (...) {
doUnknownException("", argv[0]);
throw;
}
}
return result;
}
// Read from a given fd and print it.
// return true if we can still read from it,
// return false if we need to close the input pipe.
//
// FIXME: We should really print full lines.
void getChildData(int infd, DeviceInfo& outinfo)
{
char buffer[1024 * 16];
int bytes_read;
// NOTE: do not quite understand read ends up blocking if I read more than
// once. Oh well... Good enough for now.
int64_t total_bytes_read = 0;
int64_t count = 0;
bool once = false;
while (true) {
bytes_read = read(infd, buffer, 1024 * 16);
if (bytes_read == 0) {
return;
}
if (!once) {
once = true;
}
if (bytes_read < 0) {
return;
}
assert(bytes_read > 0);
outinfo.unprinted.append(buffer, bytes_read);
count++;
}
}
/// Return true if all the DeviceInfo in \a infos are
/// ready to quit. false otherwise.
/// FIXME: move to an helper class
bool checkIfCanExit(std::vector<DeviceInfo> const& infos)
{
if (infos.empty()) {
return false;
}
for (auto& info : infos) {
if (info.readyToQuit == false) {
return false;
}
}
return true;
}
// Kill all the active children. Exit code
// is != 0 if any of the children had an error.
void killChildren(std::vector<DeviceInfo>& infos, int sig)
{
for (auto& info : infos) {
if (info.active == true) {
kill(info.pid, sig);
}
}
}
/// Check the state of the children
bool areAllChildrenGone(std::vector<DeviceInfo>& infos)
{
for (auto& info : infos) {
if ((info.pid != 0) && info.active) {
return false;
}
}
return true;
}
/// Calculate exit code
namespace
{
int calculateExitCode(DriverInfo& driverInfo, DeviceSpecs& deviceSpecs, DeviceInfos& infos)
{
std::regex regexp(R"(^\[([\d+:]*)\]\[\w+\] )");
if (!driverInfo.lastError.empty()) {
LOGP(error, "SEVERE: DPL driver encountered an error while running.\n{}",
driverInfo.lastError);
return 1;
}
for (size_t di = 0; di < deviceSpecs.size(); ++di) {
auto& info = infos[di];
auto& spec = deviceSpecs[di];
if (info.maxLogLevel >= driverInfo.minFailureLevel) {
LOGP(error, "SEVERE: Device {} ({}) had at least one message above severity {}: {}",
spec.name,
info.pid,
(int)info.minFailureLevel,
std::regex_replace(info.firstSevereError, regexp, ""));
return 1;
}
if (info.exitStatus != 0) {
LOGP(error, "SEVERE: Device {} ({}) returned with {}",
spec.name,
info.pid,
info.exitStatus);
return info.exitStatus;
}
}
return 0;
}
} // namespace
void createPipes(int* pipes)
{
auto p = pipe(pipes);
if (p == -1) {
std::cerr << "Unable to create PIPE: ";
switch (errno) {
case EFAULT:
assert(false && "EFAULT while reading from pipe");
break;
case EMFILE:
std::cerr << "Too many active descriptors";
break;
case ENFILE:
std::cerr << "System file table is full";
break;
default:
std::cerr << "Unknown PIPE" << std::endl;
};
// Kill immediately both the parent and all the children
kill(-1 * getpid(), SIGKILL);
}
}
// We don't do anything in the signal handler but
// we simply note down the fact a signal arrived.
// All the processing is done by the state machine.
volatile sig_atomic_t graceful_exit = false;
volatile sig_atomic_t forceful_exit = false;
volatile sig_atomic_t sigchld_requested = false;
volatile sig_atomic_t double_sigint = false;
static void handle_sigint(int)
{
if (graceful_exit == false) {
graceful_exit = true;
} else {
forceful_exit = true;
// We keep track about forceful exiting via
// a double SIGINT, so that we do not print
// any extra message. This means that if the
// forceful_exit is set by the timer, we will
// get an error message about each child which
// did not gracefully exited.
double_sigint = true;
}
}
/// Helper to invoke shared memory cleanup
void cleanupSHM(std::string const& uniqueWorkflowId)
{
using namespace fair::mq::shmem;
fair::mq::shmem::Monitor::Cleanup(SessionId{"dpl_" + uniqueWorkflowId}, false);
}
static void handle_sigchld(int) { sigchld_requested = true; }
void spawnRemoteDevice(uv_loop_t* loop,
std::string const&,
DeviceSpec const& spec,
DeviceControl&,
DeviceExecution&,
DeviceInfos& deviceInfos,
DataProcessingStatesInfos& allStates)
{
LOG(info) << "Starting " << spec.id << " as remote device";
DeviceInfo info{
.pid = 0,
.historyPos = 0,
.historySize = 1000,
.maxLogLevel = LogParsingHelpers::LogLevel::Debug,
.active = true,
.readyToQuit = false,
.inputChannelMetricsViewIndex = Metric2DViewIndex{"oldest_possible_timeslice", 0, 0, {}},
.outputChannelMetricsViewIndex = Metric2DViewIndex{"oldest_possible_output", 0, 0, {}},
.lastSignal = uv_hrtime() - 10000000};
deviceInfos.emplace_back(info);
timespec now;
clock_gettime(CLOCK_REALTIME, &now);
uint64_t offset = now.tv_sec * 1000 - uv_now(loop);
allStates.emplace_back(TimingHelpers::defaultRealtimeBaseConfigurator(offset, loop),
TimingHelpers::defaultCPUTimeConfigurator(loop));
// Let's add also metrics information for the given device
gDeviceMetricsInfos.emplace_back(DeviceMetricsInfo{});
}
struct DeviceLogContext {
int fd;
int index;
DriverServerContext* serverContext;
};
void log_callback(uv_poll_t* handle, int status, int events)
{
O2_SIGNPOST_ID_FROM_POINTER(sid, driver, handle->loop);
auto* logContext = reinterpret_cast<DeviceLogContext*>(handle->data);
std::vector<DeviceInfo>* infos = logContext->serverContext->infos;
DeviceInfo& info = infos->at(logContext->index);
if (status < 0) {
info.active = false;
}
if (events & UV_READABLE) {
getChildData(logContext->fd, info);
}
if (events & UV_DISCONNECT) {
info.active = false;
}
O2_SIGNPOST_EVENT_EMIT(driver, sid, "loop", "log_callback invoked by poller for device %{xcode:pid}d which is %{public}s%{public}s",
info.pid, info.active ? "active" : "inactive",
info.active ? " and still has data to read." : ".");
if (info.active == false) {
uv_poll_stop(handle);
}
uv_async_send(logContext->serverContext->asyncLogProcessing);
}
void close_websocket(uv_handle_t* handle)
{
O2_SIGNPOST_ID_FROM_POINTER(sid, driver, handle->loop);
O2_SIGNPOST_EVENT_EMIT(driver, sid, "mainloop", "close_websocket");
delete (WSDPLHandler*)handle->data;
}
void websocket_callback(uv_stream_t* stream, ssize_t nread, const uv_buf_t* buf)
{
O2_SIGNPOST_ID_FROM_POINTER(sid, driver, stream->loop);
O2_SIGNPOST_EVENT_EMIT(driver, sid, "mainloop", "websocket_callback");
auto* handler = (WSDPLHandler*)stream->data;
if (nread == 0) {
return;
}
if (nread == UV_EOF) {
if (buf->base) {
free(buf->base);
}
uv_read_stop(stream);
uv_close((uv_handle_t*)stream, close_websocket);
return;
}
if (nread < 0) {
// FIXME: should I close?
LOG(error) << "websocket_callback: Error while reading from websocket";
if (buf->base) {
free(buf->base);
}
uv_read_stop(stream);
uv_close((uv_handle_t*)stream, close_websocket);
return;
}
try {
LOG(debug3) << "Parsing request with " << handler << " with " << nread << " bytes";
parse_http_request(buf->base, nread, handler);
if (buf->base) {
free(buf->base);
}
} catch (WSError& e) {
LOG(error) << "Error while parsing request: " << e.message;
handler->error(e.code, e.message.c_str());
free(buf->base);
}
}
static void my_alloc_cb(uv_handle_t*, size_t suggested_size, uv_buf_t* buf)
{
buf->base = (char*)malloc(suggested_size);
buf->len = suggested_size;
}
/// A callback for the rest engine
void ws_connect_callback(uv_stream_t* server, int status)
{
O2_SIGNPOST_ID_FROM_POINTER(sid, driver, server->loop);
O2_SIGNPOST_EVENT_EMIT(driver, sid, "mainloop", "websocket_callback");
auto* serverContext = reinterpret_cast<DriverServerContext*>(server->data);
if (status < 0) {
LOGF(error, "New connection error %s\n", uv_strerror(status));
// error!
return;
}
auto* client = (uv_tcp_t*)malloc(sizeof(uv_tcp_t));
uv_tcp_init(serverContext->loop, client);
if (uv_accept(server, (uv_stream_t*)client) == 0) {
client->data = new WSDPLHandler((uv_stream_t*)client, serverContext);
uv_read_start((uv_stream_t*)client, (uv_alloc_cb)my_alloc_cb, websocket_callback);
} else {
uv_close((uv_handle_t*)client, nullptr);
}
}
struct StreamConfigContext {
std::string configuration;
int fd;
};
void stream_config(uv_work_t* req)
{
auto* context = (StreamConfigContext*)req->data;
size_t result = write(context->fd, context->configuration.data(), context->configuration.size());
if (result != context->configuration.size()) {
LOG(error) << "Unable to pass configuration to children";
}
{
auto error = fsync(context->fd);
switch (error) {
case EBADF:
LOGP(error, "EBADF while flushing child stdin");
break;
case EINVAL:
LOGP(error, "EINVAL while flushing child stdin");
break;
case EINTR:
LOGP(error, "EINTR while flushing child stdin");
break;
case EIO:
LOGP(error, "EIO while flushing child stdin");
break;
default:;
}
}
{
auto error = close(context->fd); // Not allowing further communication...
switch (error) {
case EBADF:
LOGP(error, "EBADF while closing child stdin");
break;
case EINTR:
LOGP(error, "EINTR while closing child stdin");
break;
case EIO:
LOGP(error, "EIO while closing child stdin");
break;
default:;
}
}
}
struct DeviceRef {
int index;
};
struct DeviceStdioContext {
int childstdin[2];
int childstdout[2];
};
void handleSignals()
{
struct sigaction sa_handle_int;
sa_handle_int.sa_handler = handle_sigint;
sigemptyset(&sa_handle_int.sa_mask);
sa_handle_int.sa_flags = SA_RESTART;
if (sigaction(SIGINT, &sa_handle_int, nullptr) == -1) {
perror("Unable to install signal handler");
exit(1);
}
struct sigaction sa_handle_term;
sa_handle_term.sa_handler = handle_sigint;
sigemptyset(&sa_handle_term.sa_mask);
sa_handle_term.sa_flags = SA_RESTART;
if (sigaction(SIGTERM, &sa_handle_int, nullptr) == -1) {
perror("Unable to install signal handler");
exit(1);
}
}
void handleChildrenStdio(DriverServerContext* serverContext,
std::string const& forwardedStdin,
std::vector<DeviceStdioContext>& childFds,
std::vector<uv_poll_t*>& handles)
{
for (size_t i = 0; i < childFds.size(); ++i) {
auto& childstdin = childFds[i].childstdin;
auto& childstdout = childFds[i].childstdout;
auto* req = (uv_work_t*)malloc(sizeof(uv_work_t));
req->data = new StreamConfigContext{forwardedStdin, childstdin[1]};
uv_queue_work(serverContext->loop, req, stream_config, nullptr);
// Setting them to non-blocking to avoid haing the driver hang when
// reading from child.
int resultCode = fcntl(childstdout[0], F_SETFL, O_NONBLOCK);
if (resultCode == -1) {
LOGP(error, "Error while setting the socket to non-blocking: {}", strerror(errno));
}
/// Add pollers for stdout and stderr
auto addPoller = [&handles, &serverContext](int index, int fd) {
auto* context = new DeviceLogContext{};
context->index = index;
context->fd = fd;
context->serverContext = serverContext;
handles.push_back((uv_poll_t*)malloc(sizeof(uv_poll_t)));
auto handle = handles.back();
handle->data = context;
uv_poll_init(serverContext->loop, handle, fd);
uv_poll_start(handle, UV_READABLE, log_callback);
};
addPoller(i, childstdout[0]);
}
}
void handle_crash(int sig)
{
// dump demangled stack trace
void* array[1024];
int size = backtrace(array, 1024);
{
char buffer[1024];
char const* msg = "*** Program crashed (%s)\nBacktrace by DPL:\n";
snprintf(buffer, 1024, msg, strsignal(sig));
if (sig == SIGFPE) {
if (std::fetestexcept(FE_DIVBYZERO)) {
snprintf(buffer, 1024, msg, "FLOATING POINT EXCEPTION - DIVISION BY ZERO");
} else if (std::fetestexcept(FE_INVALID)) {
snprintf(buffer, 1024, msg, "FLOATING POINT EXCEPTION - INVALID RESULT");
} else {
snprintf(buffer, 1024, msg, "FLOATING POINT EXCEPTION - UNKNOWN REASON");
}
}
auto retVal = write(STDERR_FILENO, buffer, strlen(buffer));
(void)retVal;
}
BacktraceHelpers::demangled_backtrace_symbols(array, size, STDERR_FILENO);
{
char const* msg = "Backtrace complete.\n";
int len = strlen(msg); /* the byte length of the string */
auto retVal = write(STDERR_FILENO, msg, len);
(void)retVal;
fsync(STDERR_FILENO);
}
_exit(1);
}
/// This will start a new device by forking and executing a
/// new child
void spawnDevice(uv_loop_t* loop,
DeviceRef ref,
std::vector<DeviceSpec> const& specs,
DriverInfo& driverInfo,
std::vector<DeviceControl>&,
std::vector<DeviceExecution>& executions,
std::vector<DeviceInfo>& deviceInfos,
std::vector<DataProcessingStates>& allStates,
ServiceRegistryRef serviceRegistry,
boost::program_options::variables_map& varmap,
std::vector<DeviceStdioContext>& childFds,
unsigned parentCPU,
unsigned parentNode)
{
// FIXME: this might not work when more than one DPL driver on the same
// machine. Hopefully we do not care.
// Not how the first port is actually used to broadcast clients.
auto& spec = specs[ref.index];
auto& execution = executions[ref.index];
for (auto& service : spec.services) {
if (service.preFork != nullptr) {
service.preFork(serviceRegistry, DeviceConfig{varmap});
}
}
// If we have a framework id, it means we have already been respawned
// and that we are in a child. If not, we need to fork and re-exec, adding
// the framework-id as one of the options.
pid_t id = 0;
id = fork();
// We are the child: prepare options and reexec.
if (id == 0) {
// We allow being debugged and do not terminate on SIGTRAP
signal(SIGTRAP, SIG_IGN);
// We immediately ignore SIGUSR1 and SIGUSR2 so that we do not
// get killed by the parent trying to force stepping children.
// We will re-enable them later on, when it is actually safe to
// do so.
signal(SIGUSR1, SIG_IGN);
signal(SIGUSR2, SIG_IGN);
// This is the child.
// For stdout / stderr, we close the read part of the pipe, the
// old descriptor, and then replace it with the write part of the pipe.
// For stdin, we close the write part of the pipe, the old descriptor,
// and then we replace it with the read part of the pipe.
// We also close all the filedescriptors for our sibilings.
struct rlimit rlim;
getrlimit(RLIMIT_NOFILE, &rlim);
// We close all FD, but the one which are actually
// used to communicate with the driver. This is a bad
// idea in the first place, because rlim_cur could be huge
// FIXME: I should understand which one is really to be closed and use
// CLOEXEC on it.
int rlim_cur = std::min((int)rlim.rlim_cur, 10000);
for (int i = 0; i < rlim_cur; ++i) {
if (childFds[ref.index].childstdin[0] == i) {
continue;
}
if (childFds[ref.index].childstdout[1] == i) {
continue;
}
close(i);
}
dup2(childFds[ref.index].childstdin[0], STDIN_FILENO);
dup2(childFds[ref.index].childstdout[1], STDOUT_FILENO);
dup2(childFds[ref.index].childstdout[1], STDERR_FILENO);
for (auto& service : spec.services) {
if (service.postForkChild != nullptr) {
service.postForkChild(serviceRegistry);
}
}
for (auto& env : execution.environ) {
putenv(strdup(DeviceSpecHelpers::reworkTimeslicePlaceholder(env, spec).data()));
}
execvp(execution.args[0], execution.args.data());
} else {
O2_SIGNPOST_ID_GENERATE(sid, driver);
O2_SIGNPOST_EVENT_EMIT(driver, sid, "spawnDevice", "New child at %{pid}d", id);
}
close(childFds[ref.index].childstdin[0]);
close(childFds[ref.index].childstdout[1]);
if (varmap.count("post-fork-command")) {
auto templateCmd = varmap["post-fork-command"];
auto cmd = fmt::format(fmt::runtime(templateCmd.as<std::string>()),
fmt::arg("pid", id),
fmt::arg("id", spec.id),
fmt::arg("cpu", parentCPU),
fmt::arg("node", parentNode),
fmt::arg("name", spec.name),
fmt::arg("timeslice0", spec.inputTimesliceId),
fmt::arg("timeslice1", spec.inputTimesliceId + 1),
fmt::arg("rank0", spec.rank),
fmt::arg("maxRank0", spec.nSlots));
int err = system(cmd.c_str());
if (err) {
LOG(error) << "Post fork command `" << cmd << "` returned with status " << err;
}
LOG(debug) << "Successfully executed `" << cmd;
}
// This is the parent. We close the write end of
// the child pipe and and keep track of the fd so
// that we can later select on it.
for (auto& service : spec.services) {
if (service.postForkParent != nullptr) {
service.postForkParent(serviceRegistry);
}
}
LOG(info) << "Starting " << spec.id << " on pid " << id;
deviceInfos.push_back({.pid = id,
.historyPos = 0,
.historySize = 1000,
.maxLogLevel = LogParsingHelpers::LogLevel::Debug,
.minFailureLevel = driverInfo.minFailureLevel,
.active = true,
.readyToQuit = false,
.inputChannelMetricsViewIndex = Metric2DViewIndex{"oldest_possible_timeslice", 0, 0, {}},
.outputChannelMetricsViewIndex = Metric2DViewIndex{"oldest_possible_output", 0, 0, {}},
.lastSignal = uv_hrtime() - 10000000});
// create the offset using uv_hrtime
timespec now;
clock_gettime(CLOCK_REALTIME, &now);
uint64_t offset = now.tv_sec * 1000 - uv_now(loop);
allStates.emplace_back(
TimingHelpers::defaultRealtimeBaseConfigurator(offset, loop),
TimingHelpers::defaultCPUTimeConfigurator(loop));
allStates.back().registerState(DataProcessingStates::StateSpec{
.name = "data_queries",
.stateId = (short)ProcessingStateId::DATA_QUERIES,
.sendInitialValue = true,
});
allStates.back().registerState(DataProcessingStates::StateSpec{
.name = "output_matchers",
.stateId = (short)ProcessingStateId::OUTPUT_MATCHERS,
.sendInitialValue = true,
});
for (size_t i = 0; i < DefaultsHelpers::pipelineLength(); ++i) {
allStates.back().registerState(DataProcessingStates::StateSpec{
.name = fmt::format("matcher_variables/{}", i),
.stateId = static_cast<short>((short)(ProcessingStateId::CONTEXT_VARIABLES_BASE) + i),
.minPublishInterval = 200, // if we publish too often we flood the GUI and we are not able to read it in any case
.sendInitialValue = true,
});
}
for (size_t i = 0; i < DefaultsHelpers::pipelineLength(); ++i) {
allStates.back().registerState(DataProcessingStates::StateSpec{
.name = fmt::format("data_relayer/{}", i),
.stateId = static_cast<short>((short)(ProcessingStateId::DATA_RELAYER_BASE) + i),
.minPublishInterval = 200, // if we publish too often we flood the GUI and we are not able to read it in any case
.sendInitialValue = true,
});
}
// Let's add also metrics information for the given device
gDeviceMetricsInfos.emplace_back(DeviceMetricsInfo{});
}
void processChildrenOutput(uv_loop_t* loop,
DriverInfo& driverInfo,
DeviceInfos& infos,
DeviceSpecs const& specs,
DeviceControls& controls)
{
// Display part. All you need to display should actually be in
// `infos`.
// TODO: split at \n
// TODO: update this only once per 1/60 of a second or
// things like this.
// TODO: have multiple display modes
// TODO: graphical view of the processing?
assert(infos.size() == controls.size());
ParsedMetricMatch metricMatch;
int processed = 0;
for (size_t di = 0, de = infos.size(); di < de; ++di) {
DeviceInfo& info = infos[di];
DeviceControl& control = controls[di];
assert(specs.size() == infos.size());
DeviceSpec const& spec = specs[di];
if (info.unprinted.empty()) {
continue;
}
processed++;
O2_SIGNPOST_ID_FROM_POINTER(sid, driver, &info);
O2_SIGNPOST_START(driver, sid, "bytes_processed", "bytes processed by %{xcode:pid}d", info.pid);
std::string_view s = info.unprinted;
size_t pos = 0;
info.history.resize(info.historySize);
info.historyLevel.resize(info.historySize);
while ((pos = s.find("\n")) != std::string::npos) {
std::string_view token{s.substr(0, pos)};
auto logLevel = LogParsingHelpers::parseTokenLevel(token);
// Check if the token is a metric from SimpleMetricsService
// if yes, we do not print it out and simply store it to be displayed
// in the GUI.
// Then we check if it is part of our Poor man control system
// if yes, we execute the associated command.
if (!control.quiet && (token.find(control.logFilter) != std::string::npos) && logLevel >= info.logLevel) {
assert(info.historyPos >= 0);
assert(info.historyPos < info.history.size());
info.history[info.historyPos] = token;
info.historyLevel[info.historyPos] = logLevel;
info.historyPos = (info.historyPos + 1) % info.history.size();
fmt::print("[{}:{}]: {}\n", info.pid, spec.id, token);
}
// We keep track of the maximum log error a
// device has seen.
bool maxLogLevelIncreased = false;
if (logLevel > info.maxLogLevel && logLevel > LogParsingHelpers::LogLevel::Info &&
logLevel != LogParsingHelpers::LogLevel::Unknown) {
info.maxLogLevel = logLevel;
maxLogLevelIncreased = true;
}
if (logLevel >= driverInfo.minFailureLevel) {
info.lastError = token;
if (info.firstSevereError.empty() || maxLogLevelIncreased) {
info.firstSevereError = token;
}
}
// +1 is to skip the \n
s.remove_prefix(pos + 1);
}
size_t oldSize = info.unprinted.size();
info.unprinted = std::string(s);
int64_t bytesProcessed = oldSize - info.unprinted.size();
O2_SIGNPOST_END(driver, sid, "bytes_processed", "bytes processed by %{xcode:network-size-in-bytes}" PRIi64, bytesProcessed);
}
if (processed == 0) {
O2_SIGNPOST_ID_FROM_POINTER(lid, driver, loop);
O2_SIGNPOST_EVENT_EMIT(driver, lid, "mainloop", "processChildrenOutput invoked for nothing!");
}
}
// Process all the sigchld which are pending
// @return wether or not a given child exited with an error condition.
bool processSigChild(DeviceInfos& infos, DeviceSpecs& specs)
{
bool hasError = false;
while (true) {
int status;
pid_t pid = waitpid((pid_t)(-1), &status, WNOHANG);
if (pid > 0) {
// Normal exit
int es = WEXITSTATUS(status);
if (WIFEXITED(status) == false || es != 0) {
// Look for the name associated to the pid in the infos
std::string id = "unknown";
assert(specs.size() == infos.size());
for (size_t ii = 0; ii < infos.size(); ++ii) {
if (infos[ii].pid == pid) {
id = specs[ii].id;
}
}
// No need to print anything if the user
// force quitted doing a double Ctrl-C.
if (double_sigint) {
} else if (forceful_exit) {
LOGP(error, "pid {} ({}) was forcefully terminated after being requested to quit", pid, id);
} else {
if (WIFSIGNALED(status)) {
int exitSignal = WTERMSIG(status);
es = exitSignal + 128;
LOGP(error, "Workflow crashed - PID {} ({}) was killed abnormally with {} and exited code was set to {}.", pid, id, strsignal(exitSignal), es);
} else {
es = 128;
LOGP(error, "Workflow crashed - PID {} ({}) did not exit correctly however it's not clear why. Exit code forced to {}.", pid, id, es);
}
}
hasError |= true;
}
for (auto& info : infos) {
if (info.pid == pid) {
info.active = false;
info.exitStatus = es;
}
}
continue;
} else {
break;
}
}
return hasError;
}
void doDPLException(RuntimeErrorRef& e, char const* processName)
{
auto& err = o2::framework::error_from_ref(e);
if (err.maxBacktrace != 0) {
LOGP(fatal,
"Unhandled o2::framework::runtime_error reached the top of main of {}, device shutting down."
" Reason: {}",
processName, err.what);
LOGP(error, "Backtrace follow:");
BacktraceHelpers::demangled_backtrace_symbols(err.backtrace, err.maxBacktrace, STDERR_FILENO);
} else {
LOGP(fatal,
"Unhandled o2::framework::runtime_error reached the top of main of {}, device shutting down."
" Reason: {}",
processName, err.what);
LOGP(error, "Recompile with DPL_ENABLE_BACKTRACE=1 to get more information.");
}
}
void doUnknownException(std::string const& s, char const* processName)
{
if (s.empty()) {
LOGP(fatal, "unknown error while setting up workflow in {}.", processName);
} else {
LOGP(fatal, "error while setting up workflow in {}: {}", processName, s);
}
}
[[maybe_unused]] AlgorithmSpec dryRun(DeviceSpec const& spec)
{
return AlgorithmSpec{adaptStateless(
[&routes = spec.outputs](DataAllocator& outputs) {