Project
Loading...
Searching...
No Matches
runDataProcessing.cxx
Go to the documentation of this file.
1// Copyright 2019-2020 CERN and copyright holders of ALICE O2.
2// See https://alice-o2.web.cern.ch/copyright for details of the copyright holders.
3// All rights not expressly granted are reserved.
4//
5// This software is distributed under the terms of the GNU General Public
6// License v3 (GPL Version 3), copied verbatim in the file "COPYING".
7//
8// In applying this license CERN does not waive the privileges and immunities
9// granted to it by virtue of its status as an Intergovernmental Organization
10// or submit itself to any jurisdiction.
11#include <memory>
14#define BOOST_BIND_GLOBAL_PLACEHOLDERS
15#include <stdexcept>
39#include "DeviceStateHelpers.h"
42#include "Framework/DebugGUI.h"
45#include "Framework/Logger.h"
49#include "Framework/Signpost.h"
70#include "DriverServerContext.h"
71#include "HTTPParser.h"
72#include "DPLWebSocket.h"
73#include "ArrowSupport.h"
75
78#include "DDSConfigHelpers.h"
79#include "O2ControlHelpers.h"
80#include "DeviceSpecHelpers.h"
81#include "GraphvizHelpers.h"
82#include "MermaidHelpers.h"
83#include "PropertyTreeHelpers.h"
86
87#include <Configuration/ConfigurationInterface.h>
88#include <Configuration/ConfigurationFactory.h>
89#include <Monitoring/MonitoringFactory.h>
91
92#include <fairmq/Device.h>
93#include <fairmq/DeviceRunner.h>
94#include <fairmq/shmem/Monitor.h>
95#include <fairmq/ProgOptions.h>
96
97#include <boost/program_options.hpp>
98#include <boost/program_options/options_description.hpp>
99#include <boost/program_options/variables_map.hpp>
100#include <boost/exception/diagnostic_information.hpp>
101#include <boost/property_tree/json_parser.hpp>
102
103#include <uv.h>
104#include <TEnv.h>
105#include <TSystem.h>
106
107#include <cinttypes>
108#include <cstdint>
109#include <cstdio>
110#include <cstdlib>
111#include <cstring>
112#include <csignal>
113#include <iostream>
114#include <map>
115#include <regex>
116#include <set>
117#include <string>
118#include <type_traits>
119#include <tuple>
120#include <chrono>
121#include <utility>
122#include <numeric>
123#include <functional>
124
125#include <fcntl.h>
126#include <netinet/ip.h>
127#include <sys/resource.h>
128#include <sys/select.h>
129#include <sys/socket.h>
130#include <sys/stat.h>
131#include <sys/time.h>
132#include <sys/types.h>
133#include <sys/un.h>
134#include <sys/wait.h>
135#include <unistd.h>
136#include <execinfo.h>
137#include <cfenv>
138#if defined(__linux__) && __has_include(<sched.h>)
139#include <sched.h>
140#elif __has_include(<linux/getcpu.h>)
141#include <linux/getcpu.h>
142#elif __has_include(<cpuid.h>) && (__x86_64__ || __i386__)
143#include <cpuid.h>
144#define CPUID(INFO, LEAF, SUBLEAF) __cpuid_count(LEAF, SUBLEAF, INFO[0], INFO[1], INFO[2], INFO[3])
145#define GETCPU(CPU) \
146 { \
147 uint32_t CPUInfo[4]; \
148 CPUID(CPUInfo, 1, 0); \
149 /* CPUInfo[1] is EBX, bits 24-31 are APIC ID */ \
150 if ((CPUInfo[3] & (1 << 9)) == 0) { \
151 CPU = -1; /* no APIC on chip */ \
152 } else { \
153 CPU = (unsigned)CPUInfo[1] >> 24; \
154 } \
155 if (CPU < 0) \
156 CPU = 0; \
157 }
158#endif
159
160using namespace o2::monitoring;
161using namespace o2::configuration;
162
163using namespace o2::framework;
164namespace bpo = boost::program_options;
165using DataProcessorInfos = std::vector<DataProcessorInfo>;
166using DeviceExecutions = std::vector<DeviceExecution>;
167using DeviceSpecs = std::vector<DeviceSpec>;
168using DeviceInfos = std::vector<DeviceInfo>;
169using DataProcessingStatesInfos = std::vector<DataProcessingStates>;
170using DeviceControls = std::vector<DeviceControl>;
171using DataProcessorSpecs = std::vector<DataProcessorSpec>;
172
173std::vector<DeviceMetricsInfo> gDeviceMetricsInfos;
174
175// FIXME: probably find a better place
176// these are the device options added by the framework, but they can be
177// overloaded in the config spec
178bpo::options_description gHiddenDeviceOptions("Hidden child options");
179
182
183void doBoostException(boost::exception& e, const char*);
185void doUnknownException(std::string const& s, char const*);
186
187char* getIdString(int argc, char** argv)
188{
189 for (int argi = 0; argi < argc; argi++) {
190 if (strcmp(argv[argi], "--id") == 0 && argi + 1 < argc) {
191 return argv[argi + 1];
192 }
193 }
194 return nullptr;
195}
196
197int callMain(int argc, char** argv, int (*mainNoCatch)(int, char**))
198{
199 static bool noCatch = getenv("O2_NO_CATCHALL_EXCEPTIONS") && strcmp(getenv("O2_NO_CATCHALL_EXCEPTIONS"), "0");
200 int result = 1;
201 if (noCatch) {
202 try {
203 result = mainNoCatch(argc, argv);
205 doDPLException(ref, argv[0]);
206 throw;
207 }
208 } else {
209 try {
210 // The 0 here is an int, therefore having the template matching in the
211 // SFINAE expression above fit better the version which invokes user code over
212 // the default one.
213 // The default policy is a catch all pub/sub setup to be consistent with the past.
214 result = mainNoCatch(argc, argv);
215 } catch (boost::exception& e) {
216 doBoostException(e, argv[0]);
217 throw;
218 } catch (std::exception const& error) {
219 doUnknownException(error.what(), argv[0]);
220 throw;
222 doDPLException(ref, argv[0]);
223 throw;
224 } catch (...) {
225 doUnknownException("", argv[0]);
226 throw;
227 }
228 }
229 return result;
230}
231
232// Read from a given fd and print it.
233// return true if we can still read from it,
234// return false if we need to close the input pipe.
235//
236// FIXME: We should really print full lines.
237void getChildData(int infd, DeviceInfo& outinfo)
238{
239 char buffer[1024 * 16];
240 int bytes_read;
241 // NOTE: do not quite understand read ends up blocking if I read more than
242 // once. Oh well... Good enough for now.
243 int64_t total_bytes_read = 0;
244 int64_t count = 0;
245 bool once = false;
246 while (true) {
247 bytes_read = read(infd, buffer, 1024 * 16);
248 if (bytes_read == 0) {
249 return;
250 }
251 if (!once) {
252 once = true;
253 }
254 if (bytes_read < 0) {
255 return;
256 }
257 assert(bytes_read > 0);
258 outinfo.unprinted.append(buffer, bytes_read);
259 count++;
260 }
261}
262
266bool checkIfCanExit(std::vector<DeviceInfo> const& infos)
267{
268 if (infos.empty()) {
269 return false;
270 }
271 for (auto& info : infos) {
272 if (info.readyToQuit == false) {
273 return false;
274 }
275 }
276 return true;
277}
278
279// Kill all the active children. Exit code
280// is != 0 if any of the children had an error.
281void killChildren(std::vector<DeviceInfo>& infos, int sig)
282{
283 for (auto& info : infos) {
284 if (info.active == true) {
285 kill(info.pid, sig);
286 }
287 }
288}
289
291bool areAllChildrenGone(std::vector<DeviceInfo>& infos)
292{
293 for (auto& info : infos) {
294 if ((info.pid != 0) && info.active) {
295 return false;
296 }
297 }
298 return true;
299}
300
302namespace
303{
304int calculateExitCode(DriverInfo& driverInfo, DeviceSpecs& deviceSpecs, DeviceInfos& infos)
305{
306 std::regex regexp(R"(^\[([\d+:]*)\]\[\w+\] )");
307 if (!driverInfo.lastError.empty()) {
308 LOGP(error, "SEVERE: DPL driver encountered an error while running.\n{}",
309 driverInfo.lastError);
310 return 1;
311 }
312 for (size_t di = 0; di < deviceSpecs.size(); ++di) {
313 auto& info = infos[di];
314 auto& spec = deviceSpecs[di];
315 if (info.maxLogLevel >= driverInfo.minFailureLevel) {
316 LOGP(error, "SEVERE: Device {} ({}) had at least one message above severity {}: {}",
317 spec.name,
318 info.pid,
319 (int)info.minFailureLevel,
320 std::regex_replace(info.firstSevereError, regexp, ""));
321 return 1;
322 }
323 if (info.exitStatus != 0) {
324 LOGP(error, "SEVERE: Device {} ({}) returned with {}",
325 spec.name,
326 info.pid,
327 info.exitStatus);
328 return info.exitStatus;
329 }
330 }
331 return 0;
332}
333} // namespace
334
335void createPipes(int* pipes)
336{
337 auto p = pipe(pipes);
338
339 if (p == -1) {
340 std::cerr << "Unable to create PIPE: ";
341 switch (errno) {
342 case EFAULT:
343 assert(false && "EFAULT while reading from pipe");
344 break;
345 case EMFILE:
346 std::cerr << "Too many active descriptors";
347 break;
348 case ENFILE:
349 std::cerr << "System file table is full";
350 break;
351 default:
352 std::cerr << "Unknown PIPE" << std::endl;
353 };
354 // Kill immediately both the parent and all the children
355 kill(-1 * getpid(), SIGKILL);
356 }
357}
358
359// We don't do anything in the signal handler but
360// we simply note down the fact a signal arrived.
361// All the processing is done by the state machine.
362volatile sig_atomic_t graceful_exit = false;
363volatile sig_atomic_t forceful_exit = false;
364volatile sig_atomic_t sigchld_requested = false;
365volatile sig_atomic_t double_sigint = false;
366
367static void handle_sigint(int)
368{
369 if (graceful_exit == false) {
370 graceful_exit = true;
371 } else {
372 forceful_exit = true;
373 // We keep track about forceful exiting via
374 // a double SIGINT, so that we do not print
375 // any extra message. This means that if the
376 // forceful_exit is set by the timer, we will
377 // get an error message about each child which
378 // did not gracefully exited.
379 double_sigint = true;
380 }
381}
382
384void cleanupSHM(std::string const& uniqueWorkflowId)
385{
386 using namespace fair::mq::shmem;
387 fair::mq::shmem::Monitor::Cleanup(SessionId{"dpl_" + uniqueWorkflowId}, false);
388}
389
390static void handle_sigchld(int) { sigchld_requested = true; }
391
393 std::string const&,
394 DeviceSpec const& spec,
397 DeviceInfos& deviceInfos,
398 DataProcessingStatesInfos& allStates)
399{
400 LOG(info) << "Starting " << spec.id << " as remote device";
401 DeviceInfo info{
402 .pid = 0,
403 .historyPos = 0,
404 .historySize = 1000,
405 .maxLogLevel = LogParsingHelpers::LogLevel::Debug,
406 .active = true,
407 .readyToQuit = false,
408 .inputChannelMetricsViewIndex = Metric2DViewIndex{"oldest_possible_timeslice", 0, 0, {}},
409 .outputChannelMetricsViewIndex = Metric2DViewIndex{"oldest_possible_output", 0, 0, {}},
410 .lastSignal = uv_hrtime() - 10000000};
411
412 deviceInfos.emplace_back(info);
413 timespec now;
414 clock_gettime(CLOCK_REALTIME, &now);
415 uint64_t offset = now.tv_sec * 1000 - uv_now(loop);
416 allStates.emplace_back(TimingHelpers::defaultRealtimeBaseConfigurator(offset, loop),
418 // Let's add also metrics information for the given device
420}
421
427
428void log_callback(uv_poll_t* handle, int status, int events)
429{
430 O2_SIGNPOST_ID_FROM_POINTER(sid, driver, handle->loop);
431 auto* logContext = reinterpret_cast<DeviceLogContext*>(handle->data);
432 std::vector<DeviceInfo>* infos = logContext->serverContext->infos;
433 DeviceInfo& info = infos->at(logContext->index);
434
435 if (status < 0) {
436 info.active = false;
437 }
438 if (events & UV_READABLE) {
439 getChildData(logContext->fd, info);
440 }
441 if (events & UV_DISCONNECT) {
442 info.active = false;
443 }
444 O2_SIGNPOST_EVENT_EMIT(driver, sid, "loop", "log_callback invoked by poller for device %{xcode:pid}d which is %{public}s%{public}s",
445 info.pid, info.active ? "active" : "inactive",
446 info.active ? " and still has data to read." : ".");
447 if (info.active == false) {
448 uv_poll_stop(handle);
449 }
450 uv_async_send(logContext->serverContext->asyncLogProcessing);
451}
452
454{
455 O2_SIGNPOST_ID_FROM_POINTER(sid, driver, handle->loop);
456 O2_SIGNPOST_EVENT_EMIT(driver, sid, "mainloop", "close_websocket");
457 delete (WSDPLHandler*)handle->data;
458}
459
460void websocket_callback(uv_stream_t* stream, ssize_t nread, const uv_buf_t* buf)
461{
462 O2_SIGNPOST_ID_FROM_POINTER(sid, driver, stream->loop);
463 O2_SIGNPOST_EVENT_EMIT(driver, sid, "mainloop", "websocket_callback");
464 auto* handler = (WSDPLHandler*)stream->data;
465 if (nread == 0) {
466 return;
467 }
468 if (nread == UV_EOF) {
469 if (buf->base) {
470 free(buf->base);
471 }
472 uv_read_stop(stream);
474 return;
475 }
476 if (nread < 0) {
477 // FIXME: should I close?
478 LOG(error) << "websocket_callback: Error while reading from websocket";
479 if (buf->base) {
480 free(buf->base);
481 }
482 uv_read_stop(stream);
484 return;
485 }
486 try {
487 LOG(debug3) << "Parsing request with " << handler << " with " << nread << " bytes";
488 parse_http_request(buf->base, nread, handler);
489 if (buf->base) {
490 free(buf->base);
491 }
492 } catch (WSError& e) {
493 LOG(error) << "Error while parsing request: " << e.message;
494 handler->error(e.code, e.message.c_str());
495 free(buf->base);
496 }
497}
498
499static void my_alloc_cb(uv_handle_t*, size_t suggested_size, uv_buf_t* buf)
500{
501 buf->base = (char*)malloc(suggested_size);
502 buf->len = suggested_size;
503}
504
506void ws_connect_callback(uv_stream_t* server, int status)
507{
508 O2_SIGNPOST_ID_FROM_POINTER(sid, driver, server->loop);
509 O2_SIGNPOST_EVENT_EMIT(driver, sid, "mainloop", "websocket_callback");
510 auto* serverContext = reinterpret_cast<DriverServerContext*>(server->data);
511 if (status < 0) {
512 LOGF(error, "New connection error %s\n", uv_strerror(status));
513 // error!
514 return;
515 }
516
517 auto* client = (uv_tcp_t*)malloc(sizeof(uv_tcp_t));
518 uv_tcp_init(serverContext->loop, client);
519 if (uv_accept(server, (uv_stream_t*)client) == 0) {
520 client->data = new WSDPLHandler((uv_stream_t*)client, serverContext);
521 uv_read_start((uv_stream_t*)client, (uv_alloc_cb)my_alloc_cb, websocket_callback);
522 } else {
523 uv_close((uv_handle_t*)client, nullptr);
524 }
525}
526
528 std::string configuration;
529 int fd;
530};
531
532void stream_config(uv_work_t* req)
533{
534 auto* context = (StreamConfigContext*)req->data;
535 size_t result = write(context->fd, context->configuration.data(), context->configuration.size());
536 if (result != context->configuration.size()) {
537 LOG(error) << "Unable to pass configuration to children";
538 }
539 {
540 auto error = fsync(context->fd);
541 switch (error) {
542 case EBADF:
543 LOGP(error, "EBADF while flushing child stdin");
544 break;
545 case EINVAL:
546 LOGP(error, "EINVAL while flushing child stdin");
547 break;
548 case EINTR:
549 LOGP(error, "EINTR while flushing child stdin");
550 break;
551 case EIO:
552 LOGP(error, "EIO while flushing child stdin");
553 break;
554 default:;
555 }
556 }
557 {
558 auto error = close(context->fd); // Not allowing further communication...
559 switch (error) {
560 case EBADF:
561 LOGP(error, "EBADF while closing child stdin");
562 break;
563 case EINTR:
564 LOGP(error, "EINTR while closing child stdin");
565 break;
566 case EIO:
567 LOGP(error, "EIO while closing child stdin");
568 break;
569 default:;
570 }
571 }
572}
573
574struct DeviceRef {
575 int index;
576};
577
581};
582
584{
585 struct sigaction sa_handle_int;
586 sa_handle_int.sa_handler = handle_sigint;
587 sigemptyset(&sa_handle_int.sa_mask);
588 sa_handle_int.sa_flags = SA_RESTART;
589 if (sigaction(SIGINT, &sa_handle_int, nullptr) == -1) {
590 perror("Unable to install signal handler");
591 exit(1);
592 }
593 struct sigaction sa_handle_term;
594 sa_handle_term.sa_handler = handle_sigint;
595 sigemptyset(&sa_handle_term.sa_mask);
596 sa_handle_term.sa_flags = SA_RESTART;
597 if (sigaction(SIGTERM, &sa_handle_int, nullptr) == -1) {
598 perror("Unable to install signal handler");
599 exit(1);
600 }
601}
602
604 std::string const& forwardedStdin,
605 std::vector<DeviceStdioContext>& childFds,
606 std::vector<uv_poll_t*>& handles)
607{
608 for (size_t i = 0; i < childFds.size(); ++i) {
609 auto& childstdin = childFds[i].childstdin;
610 auto& childstdout = childFds[i].childstdout;
611
612 auto* req = (uv_work_t*)malloc(sizeof(uv_work_t));
613 req->data = new StreamConfigContext{forwardedStdin, childstdin[1]};
614 uv_queue_work(serverContext->loop, req, stream_config, nullptr);
615
616 // Setting them to non-blocking to avoid haing the driver hang when
617 // reading from child.
618 int resultCode = fcntl(childstdout[0], F_SETFL, O_NONBLOCK);
619 if (resultCode == -1) {
620 LOGP(error, "Error while setting the socket to non-blocking: {}", strerror(errno));
621 }
622
624 auto addPoller = [&handles, &serverContext](int index, int fd) {
625 auto* context = new DeviceLogContext{};
626 context->index = index;
627 context->fd = fd;
628 context->serverContext = serverContext;
629 handles.push_back((uv_poll_t*)malloc(sizeof(uv_poll_t)));
630 auto handle = handles.back();
631 handle->data = context;
632 uv_poll_init(serverContext->loop, handle, fd);
633 uv_poll_start(handle, UV_READABLE, log_callback);
634 };
635
636 addPoller(i, childstdout[0]);
637 }
638}
639
640void handle_crash(int sig)
641{
642 // dump demangled stack trace
643 void* array[1024];
644 int size = backtrace(array, 1024);
645
646 {
647 char buffer[1024];
648 char const* msg = "*** Program crashed (%s)\nBacktrace by DPL:\n";
649 snprintf(buffer, 1024, msg, strsignal(sig));
650 if (sig == SIGFPE) {
651 if (std::fetestexcept(FE_DIVBYZERO)) {
652 snprintf(buffer, 1024, msg, "FLOATING POINT EXCEPTION - DIVISION BY ZERO");
653 } else if (std::fetestexcept(FE_INVALID)) {
654 snprintf(buffer, 1024, msg, "FLOATING POINT EXCEPTION - INVALID RESULT");
655 } else {
656 snprintf(buffer, 1024, msg, "FLOATING POINT EXCEPTION - UNKNOWN REASON");
657 }
658 }
659 auto retVal = write(STDERR_FILENO, buffer, strlen(buffer));
660 (void)retVal;
661 }
663 {
664 char const* msg = "Backtrace complete.\n";
665 int len = strlen(msg); /* the byte length of the string */
666
667 auto retVal = write(STDERR_FILENO, msg, len);
668 (void)retVal;
669 fsync(STDERR_FILENO);
670 }
671 _exit(1);
672}
673
678 std::vector<DeviceSpec> const& specs,
679 DriverInfo& driverInfo,
680 std::vector<DeviceControl>&,
681 std::vector<DeviceExecution>& executions,
682 std::vector<DeviceInfo>& deviceInfos,
683 std::vector<DataProcessingStates>& allStates,
684 ServiceRegistryRef serviceRegistry,
685 boost::program_options::variables_map& varmap,
686 std::vector<DeviceStdioContext>& childFds,
687 unsigned parentCPU,
688 unsigned parentNode)
689{
690 // FIXME: this might not work when more than one DPL driver on the same
691 // machine. Hopefully we do not care.
692 // Not how the first port is actually used to broadcast clients.
693 auto& spec = specs[ref.index];
694 auto& execution = executions[ref.index];
695
696 for (auto& service : spec.services) {
697 if (service.preFork != nullptr) {
698 service.preFork(serviceRegistry, DeviceConfig{varmap});
699 }
700 }
701 // If we have a framework id, it means we have already been respawned
702 // and that we are in a child. If not, we need to fork and re-exec, adding
703 // the framework-id as one of the options.
704 pid_t id = 0;
705 id = fork();
706 // We are the child: prepare options and reexec.
707 if (id == 0) {
708 // We allow being debugged and do not terminate on SIGTRAP
709 signal(SIGTRAP, SIG_IGN);
710 // We immediately ignore SIGUSR1 and SIGUSR2 so that we do not
711 // get killed by the parent trying to force stepping children.
712 // We will re-enable them later on, when it is actually safe to
713 // do so.
714 signal(SIGUSR1, SIG_IGN);
715 signal(SIGUSR2, SIG_IGN);
716
717 // This is the child.
718 // For stdout / stderr, we close the read part of the pipe, the
719 // old descriptor, and then replace it with the write part of the pipe.
720 // For stdin, we close the write part of the pipe, the old descriptor,
721 // and then we replace it with the read part of the pipe.
722 // We also close all the filedescriptors for our sibilings.
723 struct rlimit rlim;
724 getrlimit(RLIMIT_NOFILE, &rlim);
725 // We close all FD, but the one which are actually
726 // used to communicate with the driver. This is a bad
727 // idea in the first place, because rlim_cur could be huge
728 // FIXME: I should understand which one is really to be closed and use
729 // CLOEXEC on it.
730 int rlim_cur = std::min((int)rlim.rlim_cur, 10000);
731 for (int i = 0; i < rlim_cur; ++i) {
732 if (childFds[ref.index].childstdin[0] == i) {
733 continue;
734 }
735 if (childFds[ref.index].childstdout[1] == i) {
736 continue;
737 }
738 close(i);
739 }
740 dup2(childFds[ref.index].childstdin[0], STDIN_FILENO);
741 dup2(childFds[ref.index].childstdout[1], STDOUT_FILENO);
742 dup2(childFds[ref.index].childstdout[1], STDERR_FILENO);
743
744 for (auto& service : spec.services) {
745 if (service.postForkChild != nullptr) {
746 service.postForkChild(serviceRegistry);
747 }
748 }
749 for (auto& env : execution.environ) {
750 putenv(strdup(DeviceSpecHelpers::reworkTimeslicePlaceholder(env, spec).data()));
751 }
752 int err = execvp(execution.args[0], execution.args.data());
753 if (err) {
754 perror("Unable to start child process");
755 exit(1);
756 }
757 } else {
758 O2_SIGNPOST_ID_GENERATE(sid, driver);
759 O2_SIGNPOST_EVENT_EMIT(driver, sid, "spawnDevice", "New child at %{pid}d", id);
760 }
761 close(childFds[ref.index].childstdin[0]);
762 close(childFds[ref.index].childstdout[1]);
763 if (varmap.count("post-fork-command")) {
764 auto templateCmd = varmap["post-fork-command"];
765 auto cmd = fmt::format(fmt::runtime(templateCmd.as<std::string>()),
766 fmt::arg("pid", id),
767 fmt::arg("id", spec.id),
768 fmt::arg("cpu", parentCPU),
769 fmt::arg("node", parentNode),
770 fmt::arg("name", spec.name),
771 fmt::arg("timeslice0", spec.inputTimesliceId),
772 fmt::arg("timeslice1", spec.inputTimesliceId + 1),
773 fmt::arg("rank0", spec.rank),
774 fmt::arg("maxRank0", spec.nSlots));
775 int err = system(cmd.c_str());
776 if (err) {
777 LOG(error) << "Post fork command `" << cmd << "` returned with status " << err;
778 }
779 LOG(debug) << "Successfully executed `" << cmd;
780 }
781 // This is the parent. We close the write end of
782 // the child pipe and and keep track of the fd so
783 // that we can later select on it.
784 for (auto& service : spec.services) {
785 if (service.postForkParent != nullptr) {
786 service.postForkParent(serviceRegistry);
787 }
788 }
789
790 LOG(info) << "Starting " << spec.id << " on pid " << id;
791 deviceInfos.push_back({.pid = id,
792 .historyPos = 0,
793 .historySize = 1000,
794 .maxLogLevel = LogParsingHelpers::LogLevel::Debug,
795 .minFailureLevel = driverInfo.minFailureLevel,
796 .active = true,
797 .readyToQuit = false,
798 .inputChannelMetricsViewIndex = Metric2DViewIndex{"oldest_possible_timeslice", 0, 0, {}},
799 .outputChannelMetricsViewIndex = Metric2DViewIndex{"oldest_possible_output", 0, 0, {}},
800 .lastSignal = uv_hrtime() - 10000000});
801 // create the offset using uv_hrtime
802 timespec now;
803 clock_gettime(CLOCK_REALTIME, &now);
804 uint64_t offset = now.tv_sec * 1000 - uv_now(loop);
805 allStates.emplace_back(
808
809 allStates.back().registerState(DataProcessingStates::StateSpec{
810 .name = "data_queries",
811 .stateId = (short)ProcessingStateId::DATA_QUERIES,
812 .sendInitialValue = true,
813 });
814 allStates.back().registerState(DataProcessingStates::StateSpec{
815 .name = "output_matchers",
816 .stateId = (short)ProcessingStateId::OUTPUT_MATCHERS,
817 .sendInitialValue = true,
818 });
819
820 for (size_t i = 0; i < DefaultsHelpers::pipelineLength(); ++i) {
821 allStates.back().registerState(DataProcessingStates::StateSpec{
822 .name = fmt::format("matcher_variables/{}", i),
823 .stateId = static_cast<short>((short)(ProcessingStateId::CONTEXT_VARIABLES_BASE) + i),
824 .minPublishInterval = 200, // if we publish too often we flood the GUI and we are not able to read it in any case
825 .sendInitialValue = true,
826 });
827 }
828
829 for (size_t i = 0; i < DefaultsHelpers::pipelineLength(); ++i) {
830 allStates.back().registerState(DataProcessingStates::StateSpec{
831 .name = fmt::format("data_relayer/{}", i),
832 .stateId = static_cast<short>((short)(ProcessingStateId::DATA_RELAYER_BASE) + i),
833 .minPublishInterval = 200, // if we publish too often we flood the GUI and we are not able to read it in any case
834 .sendInitialValue = true,
835 });
836 }
837
838 // Let's add also metrics information for the given device
840}
841
843 DriverInfo& driverInfo,
844 DeviceInfos& infos,
845 DeviceSpecs const& specs,
846 DeviceControls& controls)
847{
848 // Display part. All you need to display should actually be in
849 // `infos`.
850 // TODO: split at \n
851 // TODO: update this only once per 1/60 of a second or
852 // things like this.
853 // TODO: have multiple display modes
854 // TODO: graphical view of the processing?
855 assert(infos.size() == controls.size());
856 ParsedMetricMatch metricMatch;
857
858 int processed = 0;
859 for (size_t di = 0, de = infos.size(); di < de; ++di) {
860 DeviceInfo& info = infos[di];
861 DeviceControl& control = controls[di];
862 assert(specs.size() == infos.size());
863 DeviceSpec const& spec = specs[di];
864
865 if (info.unprinted.empty()) {
866 continue;
867 }
868 processed++;
869
870 O2_SIGNPOST_ID_FROM_POINTER(sid, driver, &info);
871 O2_SIGNPOST_START(driver, sid, "bytes_processed", "bytes processed by %{xcode:pid}d", info.pid);
872
873 std::string_view s = info.unprinted;
874 size_t pos = 0;
875 info.history.resize(info.historySize);
876 info.historyLevel.resize(info.historySize);
877
878 while ((pos = s.find("\n")) != std::string::npos) {
879 std::string_view token{s.substr(0, pos)};
880 auto logLevel = LogParsingHelpers::parseTokenLevel(token);
881
882 // Check if the token is a metric from SimpleMetricsService
883 // if yes, we do not print it out and simply store it to be displayed
884 // in the GUI.
885 // Then we check if it is part of our Poor man control system
886 // if yes, we execute the associated command.
887 if (!control.quiet && (token.find(control.logFilter) != std::string::npos) && logLevel >= info.logLevel) {
888 assert(info.historyPos >= 0);
889 assert(info.historyPos < info.history.size());
890 info.history[info.historyPos] = token;
891 info.historyLevel[info.historyPos] = logLevel;
892 info.historyPos = (info.historyPos + 1) % info.history.size();
893 fmt::print("[{}:{}]: {}\n", info.pid, spec.id, token);
894 }
895 // We keep track of the maximum log error a
896 // device has seen.
897 bool maxLogLevelIncreased = false;
898 if (logLevel > info.maxLogLevel && logLevel > LogParsingHelpers::LogLevel::Info &&
899 logLevel != LogParsingHelpers::LogLevel::Unknown) {
900 info.maxLogLevel = logLevel;
901 maxLogLevelIncreased = true;
902 }
903 if (logLevel >= driverInfo.minFailureLevel) {
904 info.lastError = token;
905 if (info.firstSevereError.empty() || maxLogLevelIncreased) {
906 info.firstSevereError = token;
907 }
908 }
909 // +1 is to skip the \n
910 s.remove_prefix(pos + 1);
911 }
912 size_t oldSize = info.unprinted.size();
913 info.unprinted = std::string(s);
914 int64_t bytesProcessed = oldSize - info.unprinted.size();
915 O2_SIGNPOST_END(driver, sid, "bytes_processed", "bytes processed by %{xcode:network-size-in-bytes}" PRIi64, bytesProcessed);
916 }
917 if (processed == 0) {
918 O2_SIGNPOST_ID_FROM_POINTER(lid, driver, loop);
919 O2_SIGNPOST_EVENT_EMIT(driver, lid, "mainloop", "processChildrenOutput invoked for nothing!");
920 }
921}
922
923// Process all the sigchld which are pending
924// @return wether or not a given child exited with an error condition.
926{
927 bool hasError = false;
928 while (true) {
929 int status;
930 pid_t pid = waitpid((pid_t)(-1), &status, WNOHANG);
931 if (pid > 0) {
932 // Normal exit
933 int es = WEXITSTATUS(status);
934 if (WIFEXITED(status) == false || es != 0) {
935 // Look for the name associated to the pid in the infos
936 std::string id = "unknown";
937 assert(specs.size() == infos.size());
938 for (size_t ii = 0; ii < infos.size(); ++ii) {
939 if (infos[ii].pid == pid) {
940 id = specs[ii].id;
941 }
942 }
943 // No need to print anything if the user
944 // force quitted doing a double Ctrl-C.
945 if (double_sigint) {
946 } else if (forceful_exit) {
947 LOGP(error, "pid {} ({}) was forcefully terminated after being requested to quit", pid, id);
948 } else {
949 if (WIFSIGNALED(status)) {
950 int exitSignal = WTERMSIG(status);
951 es = exitSignal + 128;
952 LOGP(error, "Workflow crashed - PID {} ({}) was killed abnormally with {} and exited code was set to {}.", pid, id, strsignal(exitSignal), es);
953 } else {
954 es = 128;
955 LOGP(error, "Workflow crashed - PID {} ({}) did not exit correctly however it's not clear why. Exit code forced to {}.", pid, id, es);
956 }
957 }
958 hasError |= true;
959 }
960 for (auto& info : infos) {
961 if (info.pid == pid) {
962 info.active = false;
963 info.exitStatus = es;
964 }
965 }
966 continue;
967 } else {
968 break;
969 }
970 }
971 return hasError;
972}
973
974void doDPLException(RuntimeErrorRef& e, char const* processName)
975{
976 auto& err = o2::framework::error_from_ref(e);
977 if (err.maxBacktrace != 0) {
978 LOGP(fatal,
979 "Unhandled o2::framework::runtime_error reached the top of main of {}, device shutting down."
980 " Reason: {}",
981 processName, err.what);
982 LOGP(error, "Backtrace follow:");
983 BacktraceHelpers::demangled_backtrace_symbols(err.backtrace, err.maxBacktrace, STDERR_FILENO);
984 } else {
985 LOGP(fatal,
986 "Unhandled o2::framework::runtime_error reached the top of main of {}, device shutting down."
987 " Reason: {}",
988 processName, err.what);
989 LOGP(error, "Recompile with DPL_ENABLE_BACKTRACE=1 to get more information.");
990 }
991}
992
993void doUnknownException(std::string const& s, char const* processName)
994{
995 if (s.empty()) {
996 LOGP(fatal, "unknown error while setting up workflow in {}.", processName);
997 } else {
998 LOGP(fatal, "error while setting up workflow in {}: {}", processName, s);
999 }
1000}
1001
1002[[maybe_unused]] AlgorithmSpec dryRun(DeviceSpec const& spec)
1003{
1005 [&routes = spec.outputs](DataAllocator& outputs) {
1006 LOG(info) << "Dry run enforced. Creating dummy messages to simulate computation happended";
1007 for (auto& route : routes) {
1008 auto concrete = DataSpecUtils::asConcreteDataMatcher(route.matcher);
1009 outputs.make<int>(Output{concrete.origin, concrete.description, concrete.subSpec}, 2);
1010 }
1011 })};
1012}
1013
1015{
1016 // LOG(info) << "Process " << getpid() << " is exiting.";
1017}
1018
1019int doChild(int argc, char** argv, ServiceRegistry& serviceRegistry,
1020 DanglingEdgesContext& danglingEdgesContext,
1021 RunningWorkflowInfo const& runningWorkflow,
1023 DriverConfig const& driverConfig,
1024 ProcessingPolicies processingPolicies,
1025 std::string const& defaultDriverClient,
1026 uv_loop_t* loop)
1027{
1028 fair::Logger::SetConsoleColor(false);
1029 fair::Logger::OnFatal([]() { throw runtime_error("Fatal error"); });
1030 DeviceSpec const& spec = runningWorkflow.devices[ref.index];
1031 LOG(info) << "Spawning new device " << spec.id << " in process with pid " << getpid();
1032
1033 fair::mq::DeviceRunner runner{argc, argv};
1034
1035 // Populate options from the command line. Notice that only the options
1036 // declared in the workflow definition are allowed.
1037 runner.AddHook<fair::mq::hooks::SetCustomCmdLineOptions>([&spec, driverConfig, defaultDriverClient](fair::mq::DeviceRunner& r) {
1038 std::string defaultExitTransitionTimeout = "0";
1039 std::string defaultDataProcessingTimeout = "0";
1040 std::string defaultInfologgerMode = "";
1042 if (deploymentMode == o2::framework::DeploymentMode::OnlineDDS) {
1043 defaultExitTransitionTimeout = "40";
1044 defaultDataProcessingTimeout = "20";
1045 defaultInfologgerMode = "infoLoggerD";
1046 } else if (deploymentMode == o2::framework::DeploymentMode::OnlineECS) {
1047 defaultExitTransitionTimeout = "40";
1048 defaultDataProcessingTimeout = "20";
1049 }
1050 boost::program_options::options_description optsDesc;
1052 char const* defaultSignposts = getenv("DPL_SIGNPOSTS");
1053 optsDesc.add_options()("monitoring-backend", bpo::value<std::string>()->default_value("default"), "monitoring backend info") //
1054 ("dpl-stats-min-online-publishing-interval", bpo::value<std::string>()->default_value("0"), "minimum flushing interval for online metrics (in s)") //
1055 ("driver-client-backend", bpo::value<std::string>()->default_value(defaultDriverClient), "backend for device -> driver communicataon: stdout://: use stdout, ws://: use websockets") //
1056 ("infologger-severity", bpo::value<std::string>()->default_value(""), "minimum FairLogger severity to send to InfoLogger") //
1057 ("dpl-tracing-flags", bpo::value<std::string>()->default_value(""), "pipe `|` separate list of events to be traced") //
1058 ("signposts", bpo::value<std::string>()->default_value(defaultSignposts ? defaultSignposts : ""), "comma separated list of signposts to enable") //
1059 ("expected-region-callbacks", bpo::value<std::string>()->default_value("0"), "how many region callbacks we are expecting") //
1060 ("exit-transition-timeout", bpo::value<std::string>()->default_value(defaultExitTransitionTimeout), "how many second to wait before switching from RUN to READY") //
1061 ("error-on-exit-transition-timeout", bpo::value<bool>()->zero_tokens()->default_value(false), "print error instead of warning when exit transition timer expires") //
1062 ("data-processing-timeout", bpo::value<std::string>()->default_value(defaultDataProcessingTimeout), "how many second to wait before stopping data processing and allowing data calibration") //
1063 ("timeframes-rate-limit", bpo::value<std::string>()->default_value("0"), "how many timeframe can be in fly at the same moment (0 disables)") //
1064 ("configuration,cfg", bpo::value<std::string>()->default_value("command-line"), "configuration backend") //
1065 ("infologger-mode", bpo::value<std::string>()->default_value(defaultInfologgerMode), "O2_INFOLOGGER_MODE override");
1066 r.fConfig.AddToCmdLineOptions(optsDesc, true);
1067 });
1068
1069 // This is to control lifetime. All these services get destroyed
1070 // when the runner is done.
1071 std::unique_ptr<SimpleRawDeviceService> simpleRawDeviceService;
1072 std::unique_ptr<DeviceState> deviceState;
1073 std::unique_ptr<ComputingQuotaEvaluator> quotaEvaluator;
1074 std::unique_ptr<FairMQDeviceProxy> deviceProxy;
1075 std::unique_ptr<DeviceContext> deviceContext;
1076
1077 auto afterConfigParsingCallback = [&simpleRawDeviceService,
1078 &runningWorkflow,
1079 ref,
1080 &spec,
1081 &quotaEvaluator,
1082 &serviceRegistry,
1083 &danglingEdgesContext,
1084 &deviceState,
1085 &deviceProxy,
1086 &processingPolicies,
1087 &deviceContext,
1088 &driverConfig,
1089 &loop](fair::mq::DeviceRunner& r) {
1090 ServiceRegistryRef serviceRef = {serviceRegistry};
1091 simpleRawDeviceService = std::make_unique<SimpleRawDeviceService>(nullptr, spec);
1092 serviceRef.registerService(ServiceRegistryHelpers::handleForService<RawDeviceService>(simpleRawDeviceService.get()));
1093
1094 deviceState = std::make_unique<DeviceState>();
1095 deviceState->loop = loop;
1096 deviceState->tracingFlags = DeviceStateHelpers::parseTracingFlags(r.fConfig.GetPropertyAsString("dpl-tracing-flags"));
1097 serviceRef.registerService(ServiceRegistryHelpers::handleForService<DeviceState>(deviceState.get()));
1098
1099 quotaEvaluator = std::make_unique<ComputingQuotaEvaluator>(serviceRef);
1100 serviceRef.registerService(ServiceRegistryHelpers::handleForService<ComputingQuotaEvaluator>(quotaEvaluator.get()));
1101
1102 deviceContext = std::make_unique<DeviceContext>(DeviceContext{.processingPolicies = processingPolicies});
1103 serviceRef.registerService(ServiceRegistryHelpers::handleForService<DeviceSpec const>(&spec));
1104 serviceRef.registerService(ServiceRegistryHelpers::handleForService<RunningWorkflowInfo const>(&runningWorkflow));
1105 serviceRef.registerService(ServiceRegistryHelpers::handleForService<DeviceContext>(deviceContext.get()));
1106 serviceRef.registerService(ServiceRegistryHelpers::handleForService<DriverConfig const>(&driverConfig));
1107 serviceRef.registerService(ServiceRegistryHelpers::handleForService<DanglingEdgesContext>(&danglingEdgesContext));
1108
1109 auto device = std::make_unique<DataProcessingDevice>(ref, serviceRegistry);
1110
1111 serviceRef.get<RawDeviceService>().setDevice(device.get());
1112 r.fDevice = std::move(device);
1113 fair::Logger::SetConsoleColor(false);
1114
1116 for (auto& service : spec.services) {
1117 LOG(debug) << "Declaring service " << service.name;
1118 serviceRegistry.declareService(service, *deviceState.get(), r.fConfig);
1119 }
1120 if (ResourcesMonitoringHelper::isResourcesMonitoringEnabled(spec.resourceMonitoringInterval)) {
1121 serviceRef.get<Monitoring>().enableProcessMonitoring(spec.resourceMonitoringInterval, {PmMeasurement::Cpu, PmMeasurement::Mem, PmMeasurement::Smaps});
1122 }
1123 };
1124
1125 runner.AddHook<fair::mq::hooks::InstantiateDevice>(afterConfigParsingCallback);
1126
1127 auto result = runner.Run();
1128 ServiceRegistryRef serviceRef = {serviceRegistry};
1129 auto& context = serviceRef.get<DataProcessorContext>();
1130 DataProcessorContext::preExitCallbacks(context.preExitHandles, serviceRef);
1131 return result;
1132}
1133
1135 std::string executable;
1136 std::vector<std::string> args;
1137 std::vector<ConfigParamSpec> options;
1138};
1139
1140void gui_callback(uv_timer_s* ctx)
1141{
1142 auto* gui = reinterpret_cast<GuiCallbackContext*>(ctx->data);
1143 if (gui->plugin == nullptr) {
1144 // The gui is not there. Why are we here?
1145 O2_SIGNPOST_ID_FROM_POINTER(sid, driver, ctx->loop);
1146 O2_SIGNPOST_EVENT_EMIT_ERROR(driver, sid, "gui", "GUI timer callback invoked without a GUI plugin.");
1147 uv_timer_stop(ctx);
1148 return;
1149 }
1150 *gui->guiTimerExpired = true;
1151 static int counter = 0;
1152 if ((counter++ % 6000) == 0) {
1153 O2_SIGNPOST_ID_FROM_POINTER(sid, driver, ctx->loop);
1154 O2_SIGNPOST_EVENT_EMIT(driver, sid, "gui", "The GUI callback got called %d times.", counter);
1155 *gui->guiTimerExpired = false;
1156 }
1157 // One interval per GUI invocation, using the loop as anchor.
1158 O2_SIGNPOST_ID_FROM_POINTER(sid, gui, ctx->loop);
1159 O2_SIGNPOST_START(gui, sid, "gui", "gui_callback");
1160
1161 // New version which allows deferred closure of windows
1162 if (gui->plugin->supportsDeferredClose()) {
1163 // For now, there is nothing for which we want to defer the close
1164 // so if the flag is set, we simply exit
1165 if (*(gui->guiQuitRequested)) {
1166 O2_SIGNPOST_END(gui, sid, "gui", "Quit requested by the GUI.");
1167 return;
1168 }
1169 void* draw_data = nullptr;
1170 uint64_t frameStart = uv_hrtime();
1171 uint64_t frameLatency = frameStart - gui->frameLast;
1172
1173 // if less than 15ms have passed reuse old frame
1174 if (frameLatency / 1000000 <= 15) {
1175 draw_data = gui->lastFrame;
1176 O2_SIGNPOST_END(gui, sid, "gui", "Reusing old frame.");
1177 return;
1178 }
1179 // The result of the pollGUIPreRender is used to determine if we
1180 // should quit the GUI, however, the rendering is started in any
1181 // case, so we should complete it.
1182 if (!gui->plugin->pollGUIPreRender(gui->window, (float)frameLatency / 1000000000.0f)) {
1183 *(gui->guiQuitRequested) = true;
1184 }
1185 draw_data = gui->plugin->pollGUIRender(gui->callback);
1186 gui->plugin->pollGUIPostRender(gui->window, draw_data);
1187
1188 uint64_t frameEnd = uv_hrtime();
1189 *(gui->frameCost) = (frameEnd - frameStart) / 1000000.f;
1190 *(gui->frameLatency) = frameLatency / 1000000.f;
1191 gui->frameLast = frameStart;
1192 } else {
1193 void* draw_data = nullptr;
1194
1195 uint64_t frameStart = uv_hrtime();
1196 uint64_t frameLatency = frameStart - gui->frameLast;
1197
1198 // if less than 15ms have passed reuse old frame
1199 if (frameLatency / 1000000 > 15) {
1200 if (!gui->plugin->pollGUIPreRender(gui->window, (float)frameLatency / 1000000000.0f)) {
1201 *(gui->guiQuitRequested) = true;
1202 O2_SIGNPOST_END(gui, sid, "gui", "Reusing old frame.");
1203 return;
1204 }
1205 draw_data = gui->plugin->pollGUIRender(gui->callback);
1206 gui->plugin->pollGUIPostRender(gui->window, draw_data);
1207 } else {
1208 draw_data = gui->lastFrame;
1209 }
1210
1211 if (frameLatency / 1000000 > 15) {
1212 uint64_t frameEnd = uv_hrtime();
1213 *(gui->frameCost) = (frameEnd - frameStart) / 1000000.f;
1214 *(gui->frameLatency) = frameLatency / 1000000.f;
1215 gui->frameLast = frameStart;
1216 }
1217 }
1218 O2_SIGNPOST_END(gui, sid, "gui", "Gui redrawn.");
1219}
1220
1222void single_step_callback(uv_timer_s* ctx)
1223{
1224 auto* infos = reinterpret_cast<DeviceInfos*>(ctx->data);
1225 killChildren(*infos, SIGUSR1);
1226}
1227
1228void force_exit_callback(uv_timer_s* ctx)
1229{
1230 auto* infos = reinterpret_cast<DeviceInfos*>(ctx->data);
1231 killChildren(*infos, SIGKILL);
1232}
1233
1234std::vector<std::regex> getDumpableMetrics()
1235{
1236 auto performanceMetrics = o2::monitoring::ProcessMonitor::getAvailableMetricsNames();
1237 auto dumpableMetrics = std::vector<std::regex>{};
1238 for (const auto& metric : performanceMetrics) {
1239 dumpableMetrics.emplace_back(metric);
1240 }
1241 dumpableMetrics.emplace_back("^arrow-bytes-delta$");
1242 dumpableMetrics.emplace_back("^aod-bytes-read-uncompressed$");
1243 dumpableMetrics.emplace_back("^aod-bytes-read-compressed$");
1244 dumpableMetrics.emplace_back("^aod-file-read-info$");
1245 dumpableMetrics.emplace_back("^aod-largest-object-written$");
1246 dumpableMetrics.emplace_back("^table-bytes-.*");
1247 dumpableMetrics.emplace_back("^total-timeframes.*");
1248 dumpableMetrics.emplace_back("^device_state.*");
1249 dumpableMetrics.emplace_back("^total_wall_time_ms$");
1250 return dumpableMetrics;
1251}
1252
1254{
1255 auto* context = (DriverServerContext*)handle->data;
1256
1257 static auto performanceMetrics = getDumpableMetrics();
1258 std::ofstream file(context->driver->resourcesMonitoringFilename, std::ios::out);
1260 context->driver->metrics, *(context->specs), performanceMetrics,
1261 file);
1262}
1263
1264void dumpRunSummary(DriverServerContext& context, DriverInfo const& driverInfo, DeviceInfos const& infos, DeviceSpecs const& specs)
1265{
1266 if (infos.empty()) {
1267 return;
1268 }
1269 LOGP(info, "## Processes completed. Run summary:");
1270 LOGP(info, "### Devices started: {}", infos.size());
1271 for (size_t di = 0; di < infos.size(); ++di) {
1272 auto& info = infos[di];
1273 auto& spec = specs[di];
1274 if (info.exitStatus) {
1275 LOGP(error, " - Device {}: pid {} (exit {})", spec.name, info.pid, info.exitStatus);
1276 } else {
1277 LOGP(info, " - Device {}: pid {} (exit {})", spec.name, info.pid, info.exitStatus);
1278 }
1279 if (info.exitStatus != 0 && info.firstSevereError.empty() == false) {
1280 LOGP(info, " - First error: {}", info.firstSevereError);
1281 }
1282 if (info.exitStatus != 0 && info.lastError != info.firstSevereError) {
1283 LOGP(info, " - Last error: {}", info.lastError);
1284 }
1285 }
1286 for (auto& summary : *context.summaryCallbacks) {
1287 summary(ServiceMetricsInfo{*context.metrics, *context.specs, *context.infos, context.driver->metrics, driverInfo});
1288 }
1289}
1290
1291auto bindGUIPort = [](DriverInfo& driverInfo, DriverServerContext& serverContext, std::string frameworkId) {
1292 uv_tcp_init(serverContext.loop, &serverContext.serverHandle);
1293
1294 driverInfo.port = 8080 + (getpid() % 30000);
1295
1296 if (getenv("DPL_REMOTE_GUI_PORT")) {
1297 try {
1298 driverInfo.port = stoi(std::string(getenv("DPL_REMOTE_GUI_PORT")));
1299 } catch (std::invalid_argument) {
1300 LOG(error) << "DPL_REMOTE_GUI_PORT not a valid integer";
1301 } catch (std::out_of_range) {
1302 LOG(error) << "DPL_REMOTE_GUI_PORT out of range (integer)";
1303 }
1304 if (driverInfo.port < 1024 || driverInfo.port > 65535) {
1305 LOG(error) << "DPL_REMOTE_GUI_PORT out of range (1024-65535)";
1306 }
1307 }
1308
1309 int result = 0;
1310 struct sockaddr_in* serverAddr = nullptr;
1311
1312 // Do not offer websocket endpoint for devices
1313 // FIXME: this was blocking david's workflows. For now
1314 // there is no point in any case to have devices
1315 // offering a web based API, but it might make sense in
1316 // the future to inspect them via some web based interface.
1317 if (serverContext.isDriver) {
1318 do {
1319 free(serverAddr);
1320 if (driverInfo.port > 64000) {
1321 throw runtime_error_f("Unable to find a free port for the driver. Last attempt returned %d", result);
1322 }
1323 serverAddr = (sockaddr_in*)malloc(sizeof(sockaddr_in));
1324 uv_ip4_addr("0.0.0.0", driverInfo.port, serverAddr);
1325 auto bindResult = uv_tcp_bind(&serverContext.serverHandle, (const struct sockaddr*)serverAddr, 0);
1326 if (bindResult != 0) {
1327 driverInfo.port++;
1328 usleep(1000);
1329 continue;
1330 }
1331 result = uv_listen((uv_stream_t*)&serverContext.serverHandle, 100, ws_connect_callback);
1332 if (result != 0) {
1333 driverInfo.port++;
1334 usleep(1000);
1335 continue;
1336 }
1337 } while (result != 0);
1338 } else if (getenv("DPL_DEVICE_REMOTE_GUI") && !serverContext.isDriver) {
1339 do {
1340 free(serverAddr);
1341 if (driverInfo.port > 64000) {
1342 throw runtime_error_f("Unable to find a free port for the driver. Last attempt returned %d", result);
1343 }
1344 serverAddr = (sockaddr_in*)malloc(sizeof(sockaddr_in));
1345 uv_ip4_addr("0.0.0.0", driverInfo.port, serverAddr);
1346 auto bindResult = uv_tcp_bind(&serverContext.serverHandle, (const struct sockaddr*)serverAddr, 0);
1347 if (bindResult != 0) {
1348 driverInfo.port++;
1349 usleep(1000);
1350 continue;
1351 }
1352 result = uv_listen((uv_stream_t*)&serverContext.serverHandle, 100, ws_connect_callback);
1353 if (result != 0) {
1354 driverInfo.port++;
1355 usleep(1000);
1356 continue;
1357 }
1358 LOG(info) << "Device GUI port: " << driverInfo.port << " " << frameworkId;
1359 } while (result != 0);
1360 }
1361};
1362
1363// This is the handler for the parent inner loop.
1365 WorkflowInfo const& workflowInfo,
1366 DataProcessorInfos const& previousDataProcessorInfos,
1367 CommandInfo const& commandInfo,
1368 DriverControl& driverControl,
1369 DriverInfo& driverInfo,
1370 DriverConfig& driverConfig,
1371 std::vector<DeviceMetricsInfo>& metricsInfos,
1372 std::vector<ConfigParamSpec> const& detectedParams,
1373 boost::program_options::variables_map& varmap,
1374 std::vector<ServiceSpec>& driverServices,
1375 std::string frameworkId)
1376{
1377 RunningWorkflowInfo runningWorkflow{
1378 .uniqueWorkflowId = driverInfo.uniqueWorkflowId,
1379 .shmSegmentId = (int16_t)atoi(varmap["shm-segment-id"].as<std::string>().c_str())};
1380 DeviceInfos infos;
1381 DeviceControls controls;
1382 DataProcessingStatesInfos allStates;
1383 auto* devicesManager = new DevicesManager{.controls = controls, .infos = infos, .specs = runningWorkflow.devices, .messages = {}};
1384 DeviceExecutions deviceExecutions;
1385 DataProcessorInfos dataProcessorInfos = previousDataProcessorInfos;
1386
1387 std::vector<uv_poll_t*> pollHandles;
1388 std::vector<DeviceStdioContext> childFds;
1389
1390 std::vector<ComputingResource> resources;
1391
1392 if (driverInfo.resources != "") {
1393 resources = ComputingResourceHelpers::parseResources(driverInfo.resources);
1394 } else {
1396 }
1397
1398 auto resourceManager = std::make_unique<SimpleResourceManager>(resources);
1399
1400 DebugGUI* debugGUI = nullptr;
1401 void* window = nullptr;
1402 decltype(debugGUI->getGUIDebugger(infos, runningWorkflow.devices, allStates, dataProcessorInfos, metricsInfos, driverInfo, controls, driverControl)) debugGUICallback;
1403
1404 // An empty frameworkId means this is the driver, so we initialise the GUI
1405 auto initDebugGUI = []() -> DebugGUI* {
1406 uv_lib_t supportLib;
1407 int result = 0;
1408#ifdef __APPLE__
1409 result = uv_dlopen("libO2FrameworkGUISupport.dylib", &supportLib);
1410#else
1411 result = uv_dlopen("libO2FrameworkGUISupport.so", &supportLib);
1412#endif
1413 if (result == -1) {
1414 LOG(error) << uv_dlerror(&supportLib);
1415 return nullptr;
1416 }
1417 DPLPluginHandle* (*dpl_plugin_callback)(DPLPluginHandle*);
1418
1419 result = uv_dlsym(&supportLib, "dpl_plugin_callback", (void**)&dpl_plugin_callback);
1420 if (result == -1) {
1421 LOG(error) << uv_dlerror(&supportLib);
1422 return nullptr;
1423 }
1424 DPLPluginHandle* pluginInstance = dpl_plugin_callback(nullptr);
1425 return PluginManager::getByName<DebugGUI>(pluginInstance, "ImGUIDebugGUI");
1426 };
1427
1428 // We initialise this in the driver, because different drivers might have
1429 // different versions of the service
1430 ServiceRegistry serviceRegistry;
1431
1432 if ((driverConfig.batch == false || getenv("DPL_DRIVER_REMOTE_GUI") != nullptr) && frameworkId.empty()) {
1433 debugGUI = initDebugGUI();
1434 if (debugGUI) {
1435 if (driverConfig.batch == false) {
1436 window = debugGUI->initGUI("O2 Framework debug GUI", serviceRegistry);
1437 } else {
1438 window = debugGUI->initGUI(nullptr, serviceRegistry);
1439 }
1440 }
1441 } else if (getenv("DPL_DEVICE_REMOTE_GUI") && !frameworkId.empty()) {
1442 debugGUI = initDebugGUI();
1443 // We never run the GUI on desktop for devices. All
1444 // you can do is to connect to the remote version.
1445 // this is done to avoid having a proliferation of
1446 // GUIs popping up when the variable is set globally.
1447 // FIXME: maybe this is not what we want, but it should
1448 // be ok for now.
1449 if (debugGUI) {
1450 window = debugGUI->initGUI(nullptr, serviceRegistry);
1451 }
1452 }
1453 if (driverConfig.batch == false && window == nullptr && frameworkId.empty()) {
1454 LOG(warn) << "Could not create GUI. Switching to batch mode. Do you have GLFW on your system?";
1455 driverConfig.batch = true;
1456 if (varmap["error-policy"].defaulted()) {
1457 driverInfo.processingPolicies.error = TerminationPolicy::QUIT;
1458 }
1459 }
1460 bool guiQuitRequested = false;
1461 bool hasError = false;
1462
1463 // FIXME: I should really have some way of exiting the
1464 // parent..
1465 DriverState current;
1466 DriverState previous;
1467
1468 uv_loop_t* loop = uv_loop_new();
1469
1470 uv_timer_t* gui_timer = nullptr;
1471
1472 if (!driverConfig.batch) {
1473 gui_timer = (uv_timer_t*)malloc(sizeof(uv_timer_t));
1474 uv_timer_init(loop, gui_timer);
1475 }
1476
1477 std::vector<ServiceMetricHandling> metricProcessingCallbacks;
1478 std::vector<ServiceSummaryHandling> summaryCallbacks;
1479 std::vector<ServicePreSchedule> preScheduleCallbacks;
1480 std::vector<ServicePostSchedule> postScheduleCallbacks;
1481 std::vector<ServiceDriverInit> driverInitCallbacks;
1482 for (auto& service : driverServices) {
1483 if (service.driverStartup == nullptr) {
1484 continue;
1485 }
1486 service.driverStartup(serviceRegistry, DeviceConfig{varmap});
1487 }
1488
1489 ServiceRegistryRef ref{serviceRegistry};
1490 ref.registerService(ServiceRegistryHelpers::handleForService<DevicesManager>(devicesManager));
1491
1492 bool guiTimerExpired = false;
1493 GuiCallbackContext guiContext;
1494 guiContext.plugin = debugGUI;
1495 guiContext.frameLast = uv_hrtime();
1496 guiContext.frameLatency = &driverInfo.frameLatency;
1497 guiContext.frameCost = &driverInfo.frameCost;
1498 guiContext.guiQuitRequested = &guiQuitRequested;
1499 guiContext.guiTimerExpired = &guiTimerExpired;
1500
1501 // This is to make sure we can process metrics, commands, configuration
1502 // changes coming from websocket (or even via any standard uv_stream_t, I guess).
1503 DriverServerContext serverContext{
1504 .registry = {serviceRegistry},
1505 .loop = loop,
1506 .controls = &controls,
1507 .infos = &infos,
1508 .states = &allStates,
1509 .specs = &runningWorkflow.devices,
1510 .metrics = &metricsInfos,
1511 .metricProcessingCallbacks = &metricProcessingCallbacks,
1512 .summaryCallbacks = &summaryCallbacks,
1513 .driver = &driverInfo,
1514 .gui = &guiContext,
1515 .isDriver = frameworkId.empty(),
1516 };
1517
1518 serverContext.serverHandle.data = &serverContext;
1519
1520 uv_timer_t force_step_timer;
1521 uv_timer_init(loop, &force_step_timer);
1522 uv_timer_t force_exit_timer;
1523 uv_timer_init(loop, &force_exit_timer);
1524
1525 bool guiDeployedOnce = false;
1526 bool once = false;
1527
1528 uv_timer_t metricDumpTimer;
1529 metricDumpTimer.data = &serverContext;
1530 bool allChildrenGone = false;
1531 guiContext.allChildrenGone = &allChildrenGone;
1532 O2_SIGNPOST_ID_FROM_POINTER(sid, driver, loop);
1533 O2_SIGNPOST_START(driver, sid, "driver", "Starting driver loop");
1534
1535 // Async callback to process the output of the children, if needed.
1536 serverContext.asyncLogProcessing = (uv_async_t*)malloc(sizeof(uv_async_t));
1537 serverContext.asyncLogProcessing->data = &serverContext;
1538 uv_async_init(loop, serverContext.asyncLogProcessing, [](uv_async_t* handle) {
1539 auto* context = (DriverServerContext*)handle->data;
1540 processChildrenOutput(context->loop, *context->driver, *context->infos, *context->specs, *context->controls);
1541 });
1542
1543 while (true) {
1544 // If control forced some transition on us, we push it to the queue.
1545 if (driverControl.forcedTransitions.empty() == false) {
1546 for (auto transition : driverControl.forcedTransitions) {
1547 driverInfo.states.push_back(transition);
1548 }
1549 driverControl.forcedTransitions.resize(0);
1550 }
1551 // In case a timeout was requested, we check if we are running
1552 // for more than the timeout duration and exit in case that's the case.
1553 {
1554 auto currentTime = uv_hrtime();
1555 uint64_t diff = (currentTime - driverInfo.startTime) / 1000000000LL;
1556 if ((graceful_exit == false) && (driverInfo.timeout > 0) && (diff > driverInfo.timeout)) {
1557 LOG(info) << "Timout ellapsed. Requesting to quit.";
1558 graceful_exit = true;
1559 }
1560 }
1561 // Move to exit loop if sigint was sent we execute this only once.
1562 if (graceful_exit == true && driverInfo.sigintRequested == false) {
1563 driverInfo.sigintRequested = true;
1564 driverInfo.states.resize(0);
1565 driverInfo.states.push_back(DriverState::QUIT_REQUESTED);
1566 }
1567 // If one of the children dies and sigint was not requested
1568 // we should decide what to do.
1569 if (sigchld_requested == true && driverInfo.sigchldRequested == false) {
1570 driverInfo.sigchldRequested = true;
1571 driverInfo.states.push_back(DriverState::HANDLE_CHILDREN);
1572 }
1573 if (driverInfo.states.empty() == false) {
1574 previous = current;
1575 current = driverInfo.states.back();
1576 } else {
1577 current = DriverState::UNKNOWN;
1578 }
1579 driverInfo.states.pop_back();
1580 switch (current) {
1581 case DriverState::BIND_GUI_PORT:
1582 bindGUIPort(driverInfo, serverContext, frameworkId);
1583 break;
1584 case DriverState::INIT:
1585 LOGP(info, "Initialising O2 Data Processing Layer. Driver PID: {}.", getpid());
1586 LOGP(info, "Driver listening on port: {}", driverInfo.port);
1587
1588 // Install signal handler for quitting children.
1589 driverInfo.sa_handle_child.sa_handler = &handle_sigchld;
1590 sigemptyset(&driverInfo.sa_handle_child.sa_mask);
1591 driverInfo.sa_handle_child.sa_flags = SA_RESTART | SA_NOCLDSTOP;
1592 if (sigaction(SIGCHLD, &driverInfo.sa_handle_child, nullptr) == -1) {
1593 perror(nullptr);
1594 exit(1);
1595 }
1596
1599 if (driverInfo.noSHMCleanup) {
1600 LOGP(warning, "Not cleaning up shared memory.");
1601 } else {
1602 cleanupSHM(driverInfo.uniqueWorkflowId);
1603 }
1608 for (auto& callback : driverInitCallbacks) {
1609 callback(serviceRegistry, {varmap});
1610 }
1611 driverInfo.states.push_back(DriverState::RUNNING);
1612 // driverInfo.states.push_back(DriverState::REDEPLOY_GUI);
1613 LOG(info) << "O2 Data Processing Layer initialised. We brake for nobody.";
1614#ifdef NDEBUG
1615 LOGF(info, "Optimised build. O2DEBUG / LOG(debug) / LOGF(debug) / assert statement will not be shown.");
1616#endif
1617 break;
1618 case DriverState::IMPORT_CURRENT_WORKFLOW:
1619 // This state is needed to fill the metadata structure
1620 // which contains how to run the current workflow
1621 dataProcessorInfos = previousDataProcessorInfos;
1622 for (auto const& device : runningWorkflow.devices) {
1623 auto exists = std::find_if(dataProcessorInfos.begin(),
1624 dataProcessorInfos.end(),
1625 [id = device.id](DataProcessorInfo const& info) -> bool { return info.name == id; });
1626 if (exists != dataProcessorInfos.end()) {
1627 continue;
1628 }
1629 std::vector<std::string> channels;
1630 for (auto channel : device.inputChannels) {
1631 channels.push_back(channel.name);
1632 }
1633 for (auto channel : device.outputChannels) {
1634 channels.push_back(channel.name);
1635 }
1636 dataProcessorInfos.push_back(
1638 device.id,
1639 workflowInfo.executable,
1640 workflowInfo.args,
1641 workflowInfo.options,
1642 channels});
1643 }
1644 break;
1645 case DriverState::MATERIALISE_WORKFLOW:
1646 try {
1647 auto workflowState = WorkflowHelpers::verifyWorkflow(workflow);
1648 if (driverConfig.batch == true && varmap["dds"].as<std::string>().empty() && !varmap["dump-workflow"].as<bool>() && workflowState == WorkflowParsingState::Empty) {
1649 LOGP(error, "Empty workflow provided while running in batch mode.");
1650 return 1;
1651 }
1652
1655 auto altered_workflow = workflow;
1656
1657 auto confNameFromParam = [](std::string const& paramName) {
1658 std::regex name_regex(R"(^control:([\w-]+)\/(\w+))");
1659 auto match = std::sregex_token_iterator(paramName.begin(), paramName.end(), name_regex, 0);
1660 if (match == std::sregex_token_iterator()) {
1661 throw runtime_error_f("Malformed process control spec: %s", paramName.c_str());
1662 }
1663 std::string task = std::sregex_token_iterator(paramName.begin(), paramName.end(), name_regex, 1)->str();
1664 std::string conf = std::sregex_token_iterator(paramName.begin(), paramName.end(), name_regex, 2)->str();
1665 return std::pair{task, conf};
1666 };
1667 bool altered = false;
1668 for (auto& device : altered_workflow) {
1669 // ignore internal devices
1670 if (device.name.find("internal") != std::string::npos) {
1671 continue;
1672 }
1673 // ignore devices with no inputs
1674 if (device.inputs.empty() == true) {
1675 continue;
1676 }
1677 // ignore devices with no metadata in inputs
1678 auto hasMetadata = std::any_of(device.inputs.begin(), device.inputs.end(), [](InputSpec const& spec) {
1679 return spec.metadata.empty() == false;
1680 });
1681 if (!hasMetadata) {
1682 continue;
1683 }
1684 // ignore devices with no control options
1685 auto hasControls = std::any_of(device.inputs.begin(), device.inputs.end(), [](InputSpec const& spec) {
1686 return std::any_of(spec.metadata.begin(), spec.metadata.end(), [](ConfigParamSpec const& param) {
1687 return param.type == VariantType::Bool && param.name.find("control:") != std::string::npos;
1688 });
1689 });
1690 if (!hasControls) {
1691 continue;
1692 }
1693
1694 LOGP(debug, "Adjusting device {}", device.name.c_str());
1695
1696 auto configStore = DeviceConfigurationHelpers::getConfiguration(serviceRegistry, device.name.c_str(), device.options);
1697 if (configStore != nullptr) {
1698 auto reg = std::make_unique<ConfigParamRegistry>(std::move(configStore));
1699 for (auto& input : device.inputs) {
1700 for (auto& param : input.metadata) {
1701 if (param.type == VariantType::Bool && param.name.find("control:") != std::string::npos) {
1702 if (param.name != "control:default" && param.name != "control:spawn" && param.name != "control:build" && param.name != "control:define") {
1703 auto confName = confNameFromParam(param.name).second;
1704 param.defaultValue = reg->get<bool>(confName.c_str());
1705 }
1706 }
1707 }
1708 }
1709 }
1711 LOGP(debug, "Original inputs: ");
1712 for (auto& input : device.inputs) {
1713 LOGP(debug, "-> {}", input.binding);
1714 }
1715 auto end = device.inputs.end();
1716 auto new_end = std::remove_if(device.inputs.begin(), device.inputs.end(), [](InputSpec& input) {
1717 auto requested = false;
1718 auto hasControls = false;
1719 for (auto& param : input.metadata) {
1720 if (param.type != VariantType::Bool) {
1721 continue;
1722 }
1723 if (param.name.find("control:") != std::string::npos) {
1724 hasControls = true;
1725 if (param.defaultValue.get<bool>() == true) {
1726 requested = true;
1727 break;
1728 }
1729 }
1730 }
1731 if (hasControls) {
1732 return !requested;
1733 }
1734 return false;
1735 });
1736 device.inputs.erase(new_end, end);
1737 LOGP(debug, "Adjusted inputs: ");
1738 for (auto& input : device.inputs) {
1739 LOGP(debug, "-> {}", input.binding);
1740 }
1741 altered = true;
1742 }
1743 WorkflowHelpers::adjustTopology(altered_workflow, *driverInfo.configContext);
1744 if (altered) {
1745 WorkflowSpecNode node{altered_workflow};
1746 for (auto& service : driverServices) {
1747 if (service.adjustTopology == nullptr) {
1748 continue;
1749 }
1750 service.adjustTopology(node, *driverInfo.configContext);
1751 }
1752 }
1753
1754 // These allow services customization via an environment variable
1755 OverrideServiceSpecs overrides = ServiceSpecHelpers::parseOverrides(getenv("DPL_OVERRIDE_SERVICES"));
1756 DeviceSpecHelpers::validate(altered_workflow);
1758 driverInfo.channelPolicies,
1759 driverInfo.completionPolicies,
1760 driverInfo.dispatchPolicies,
1761 driverInfo.resourcePolicies,
1762 driverInfo.callbacksPolicies,
1763 driverInfo.sendingPolicies,
1764 driverInfo.forwardingPolicies,
1765 runningWorkflow.devices,
1766 *resourceManager,
1767 driverInfo.uniqueWorkflowId,
1768 *driverInfo.configContext,
1769 !varmap["no-IPC"].as<bool>(),
1770 driverInfo.resourcesMonitoringInterval,
1771 varmap["channel-prefix"].as<std::string>(),
1772 overrides);
1773 metricProcessingCallbacks.clear();
1774 std::vector<std::string> matchingServices;
1775
1776 // FIXME: once moving to C++20, we can use templated lambdas.
1777 matchingServices.clear();
1778 for (auto& device : runningWorkflow.devices) {
1779 for (auto& service : device.services) {
1780 // If a service with the same name is already registered, skip it
1781 if (std::find(matchingServices.begin(), matchingServices.end(), service.name) != matchingServices.end()) {
1782 continue;
1783 }
1784 if (service.metricHandling) {
1785 metricProcessingCallbacks.push_back(service.metricHandling);
1786 matchingServices.push_back(service.name);
1787 }
1788 }
1789 }
1790
1791 // FIXME: once moving to C++20, we can use templated lambdas.
1792 matchingServices.clear();
1793 for (auto& device : runningWorkflow.devices) {
1794 for (auto& service : device.services) {
1795 // If a service with the same name is already registered, skip it
1796 if (std::find(matchingServices.begin(), matchingServices.end(), service.name) != matchingServices.end()) {
1797 continue;
1798 }
1799 if (service.summaryHandling) {
1800 summaryCallbacks.push_back(service.summaryHandling);
1801 matchingServices.push_back(service.name);
1802 }
1803 }
1804 }
1805
1806 preScheduleCallbacks.clear();
1807 matchingServices.clear();
1808 for (auto& device : runningWorkflow.devices) {
1809 for (auto& service : device.services) {
1810 // If a service with the same name is already registered, skip it
1811 if (std::find(matchingServices.begin(), matchingServices.end(), service.name) != matchingServices.end()) {
1812 continue;
1813 }
1814 if (service.preSchedule) {
1815 preScheduleCallbacks.push_back(service.preSchedule);
1816 }
1817 }
1818 }
1819 postScheduleCallbacks.clear();
1820 matchingServices.clear();
1821 for (auto& device : runningWorkflow.devices) {
1822 for (auto& service : device.services) {
1823 // If a service with the same name is already registered, skip it
1824 if (std::find(matchingServices.begin(), matchingServices.end(), service.name) != matchingServices.end()) {
1825 continue;
1826 }
1827 if (service.postSchedule) {
1828 postScheduleCallbacks.push_back(service.postSchedule);
1829 }
1830 }
1831 }
1832 driverInitCallbacks.clear();
1833 matchingServices.clear();
1834 for (auto& device : runningWorkflow.devices) {
1835 for (auto& service : device.services) {
1836 // If a service with the same name is already registered, skip it
1837 if (std::find(matchingServices.begin(), matchingServices.end(), service.name) != matchingServices.end()) {
1838 continue;
1839 }
1840 if (service.driverInit) {
1841 driverInitCallbacks.push_back(service.driverInit);
1842 }
1843 }
1844 }
1845
1846 // This should expand nodes so that we can build a consistent DAG.
1847
1848 // This updates the options in the runningWorkflow.devices
1849 for (auto& device : runningWorkflow.devices) {
1850 // ignore internal devices
1851 if (device.name.find("internal") != std::string::npos) {
1852 continue;
1853 }
1854 auto configStore = DeviceConfigurationHelpers::getConfiguration(serviceRegistry, device.name.c_str(), device.options);
1855 if (configStore != nullptr) {
1856 auto reg = std::make_unique<ConfigParamRegistry>(std::move(configStore));
1857 for (auto& option : device.options) {
1858 const char* name = option.name.c_str();
1859 switch (option.type) {
1860 case VariantType::Int:
1861 option.defaultValue = reg->get<int32_t>(name);
1862 break;
1863 case VariantType::Int8:
1864 option.defaultValue = reg->get<int8_t>(name);
1865 break;
1866 case VariantType::Int16:
1867 option.defaultValue = reg->get<int16_t>(name);
1868 break;
1869 case VariantType::UInt8:
1870 option.defaultValue = reg->get<uint8_t>(name);
1871 break;
1872 case VariantType::UInt16:
1873 option.defaultValue = reg->get<uint16_t>(name);
1874 break;
1875 case VariantType::UInt32:
1876 option.defaultValue = reg->get<uint32_t>(name);
1877 break;
1878 case VariantType::UInt64:
1879 option.defaultValue = reg->get<uint64_t>(name);
1880 break;
1881 case VariantType::Int64:
1882 option.defaultValue = reg->get<int64_t>(name);
1883 break;
1884 case VariantType::Float:
1885 option.defaultValue = reg->get<float>(name);
1886 break;
1887 case VariantType::Double:
1888 option.defaultValue = reg->get<double>(name);
1889 break;
1890 case VariantType::String:
1891 option.defaultValue = reg->get<std::string>(name);
1892 break;
1893 case VariantType::Bool:
1894 option.defaultValue = reg->get<bool>(name);
1895 break;
1896 case VariantType::ArrayInt:
1897 option.defaultValue = reg->get<std::vector<int>>(name);
1898 break;
1899 case VariantType::ArrayFloat:
1900 option.defaultValue = reg->get<std::vector<float>>(name);
1901 break;
1902 case VariantType::ArrayDouble:
1903 option.defaultValue = reg->get<std::vector<double>>(name);
1904 break;
1905 case VariantType::ArrayString:
1906 option.defaultValue = reg->get<std::vector<std::string>>(name);
1907 break;
1908 case VariantType::Array2DInt:
1909 option.defaultValue = reg->get<Array2D<int>>(name);
1910 break;
1911 case VariantType::Array2DFloat:
1912 option.defaultValue = reg->get<Array2D<float>>(name);
1913 break;
1914 case VariantType::Array2DDouble:
1915 option.defaultValue = reg->get<Array2D<double>>(name);
1916 break;
1917 case VariantType::LabeledArrayInt:
1918 option.defaultValue = reg->get<LabeledArray<int>>(name);
1919 break;
1920 case VariantType::LabeledArrayFloat:
1921 option.defaultValue = reg->get<LabeledArray<float>>(name);
1922 break;
1923 case VariantType::LabeledArrayDouble:
1924 option.defaultValue = reg->get<LabeledArray<double>>(name);
1925 break;
1926 case VariantType::LabeledArrayString:
1927 option.defaultValue = reg->get<LabeledArray<std::string>>(name);
1928 break;
1929 default:
1930 break;
1931 }
1932 }
1933 }
1934 }
1935 } catch (std::runtime_error& e) {
1936 LOGP(error, "invalid workflow in {}: {}", driverInfo.argv[0], e.what());
1937 return 1;
1940#ifdef DPL_ENABLE_BACKTRACE
1941 BacktraceHelpers::demangled_backtrace_symbols(err.backtrace, err.maxBacktrace, STDERR_FILENO);
1942#endif
1943 LOGP(error, "invalid workflow in {}: {}", driverInfo.argv[0], err.what);
1944 return 1;
1945 } catch (...) {
1946 LOGP(error, "invalid workflow in {}: Unknown error while materialising workflow", driverInfo.argv[0]);
1947 return 1;
1948 }
1949 break;
1950 case DriverState::DO_CHILD:
1951 // We do not start the process if by default we are stopped.
1952 if (driverControl.defaultStopped) {
1953 kill(getpid(), SIGSTOP);
1954 }
1955 for (size_t di = 0; di < runningWorkflow.devices.size(); di++) {
1957 if (runningWorkflow.devices[di].id == frameworkId) {
1958 return doChild(driverInfo.argc, driverInfo.argv,
1959 serviceRegistry,
1960 driverInfo.configContext->services().get<DanglingEdgesContext>(),
1961 runningWorkflow, ref,
1962 driverConfig,
1963 driverInfo.processingPolicies,
1964 driverInfo.defaultDriverClient,
1965 loop);
1966 }
1967 }
1968 {
1969 std::ostringstream ss;
1970 for (auto& processor : workflow) {
1971 ss << " - " << processor.name << "\n";
1972 }
1973 for (auto& spec : runningWorkflow.devices) {
1974 ss << " - " << spec.name << "(" << spec.id << ")"
1975 << "\n";
1976 }
1977 driverInfo.lastError = fmt::format(
1978 "Unable to find component with id {}."
1979 " Available options:\n{}",
1980 frameworkId, ss.str());
1981 driverInfo.states.push_back(DriverState::QUIT_REQUESTED);
1982 }
1983 break;
1984 case DriverState::REDEPLOY_GUI:
1985 // The callback for the GUI needs to be recalculated every time
1986 // the deployed configuration changes, e.g. a new device
1987 // has been added to the topology.
1988 // We need to recreate the GUI callback every time we reschedule
1989 // because getGUIDebugger actually recreates the GUI state.
1990 // Notice also that we need the actual gui_timer only for the
1991 // case the GUI runs in interactive mode, however we deploy the
1992 // GUI in both interactive and non-interactive mode, if the
1993 // DPL_DRIVER_REMOTE_GUI environment variable is set.
1994 if (!driverConfig.batch || getenv("DPL_DRIVER_REMOTE_GUI")) {
1995 if (gui_timer) {
1996 uv_timer_stop(gui_timer);
1997 }
1998
1999 auto callback = debugGUI->getGUIDebugger(infos, runningWorkflow.devices, allStates, dataProcessorInfos, metricsInfos, driverInfo, controls, driverControl);
2000 guiContext.callback = [&serviceRegistry, &driverServices, &debugGUI, &infos, &runningWorkflow, &dataProcessorInfos, &metricsInfos, &driverInfo, &controls, &driverControl, callback]() {
2001 callback();
2002 for (auto& service : driverServices) {
2003 if (service.postRenderGUI) {
2004 service.postRenderGUI(serviceRegistry);
2005 }
2006 }
2007 };
2008 guiContext.window = window;
2009
2010 if (gui_timer) {
2011 gui_timer->data = &guiContext;
2012 uv_timer_start(gui_timer, gui_callback, 0, 20);
2013 }
2014 guiDeployedOnce = true;
2015 }
2016 break;
2017 case DriverState::MERGE_CONFIGS: {
2018 try {
2019 controls.resize(runningWorkflow.devices.size());
2022 if (varmap.count("dpl-tracing-flags")) {
2023 for (auto& control : controls) {
2024 auto tracingFlags = DeviceStateHelpers::parseTracingFlags(varmap["dpl-tracing-flags"].as<std::string>());
2025 control.tracingFlags = tracingFlags;
2026 }
2027 }
2028 deviceExecutions.resize(runningWorkflow.devices.size());
2029
2030 // Options which should be uniform across all
2031 // the subworkflow invokations.
2032 const auto uniformOptions = {
2033 "--aod-file",
2034 "--aod-memory-rate-limit",
2035 "--aod-writer-json",
2036 "--aod-writer-ntfmerge",
2037 "--aod-writer-resdir",
2038 "--aod-writer-resfile",
2039 "--aod-writer-resmode",
2040 "--aod-writer-maxfilesize",
2041 "--aod-writer-keep",
2042 "--aod-max-io-rate",
2043 "--aod-parent-access-level",
2044 "--aod-parent-base-path-replacement",
2045 "--driver-client-backend",
2046 "--fairmq-ipc-prefix",
2047 "--readers",
2048 "--resources-monitoring",
2049 "--resources-monitoring-file",
2050 "--resources-monitoring-dump-interval",
2051 "--time-limit",
2052 };
2053
2054 for (auto& option : uniformOptions) {
2055 DeviceSpecHelpers::reworkHomogeneousOption(dataProcessorInfos, option, nullptr);
2056 }
2057
2058 DeviceSpecHelpers::reworkShmSegmentSize(dataProcessorInfos);
2060 driverControl.defaultStopped,
2061 driverInfo.processingPolicies.termination == TerminationPolicy::WAIT,
2062 driverInfo.port,
2063 driverConfig,
2064 dataProcessorInfos,
2065 runningWorkflow.devices,
2066 deviceExecutions,
2067 controls,
2068 detectedParams,
2069 driverInfo.uniqueWorkflowId);
2072 LOGP(error, "unable to merge configurations in {}: {}", driverInfo.argv[0], err.what);
2073#ifdef DPL_ENABLE_BACKTRACE
2074 std::cerr << "\nStacktrace follows:\n\n";
2075 BacktraceHelpers::demangled_backtrace_symbols(err.backtrace, err.maxBacktrace, STDERR_FILENO);
2076#endif
2077 return 1;
2078 }
2079 } break;
2080 case DriverState::SCHEDULE: {
2081 // FIXME: for the moment modifying the topology means we rebuild completely
2082 // all the devices and we restart them. This is also what DDS does at
2083 // a larger scale. In principle one could try to do a delta and only
2084 // restart the data processors which need to be restarted.
2085 LOG(info) << "Redeployment of configuration asked.";
2086 std::ostringstream forwardedStdin;
2087 WorkflowSerializationHelpers::dump(forwardedStdin, workflow, dataProcessorInfos, commandInfo);
2088 infos.reserve(runningWorkflow.devices.size());
2089
2090 // This is guaranteed to be a single CPU.
2091 unsigned parentCPU = -1;
2092 unsigned parentNode = -1;
2093#if defined(__linux__) && __has_include(<sched.h>)
2094 parentCPU = sched_getcpu();
2095#elif __has_include(<linux/getcpu.h>)
2096 getcpu(&parentCPU, &parentNode, nullptr);
2097#elif __has_include(<cpuid.h>) && (__x86_64__ || __i386__)
2098 // FIXME: this is a last resort as it is apparently buggy
2099 // on some Intel CPUs.
2100 GETCPU(parentCPU);
2101#endif
2102 for (auto& callback : preScheduleCallbacks) {
2103 callback(serviceRegistry, {varmap});
2104 }
2105 childFds.resize(runningWorkflow.devices.size());
2106 for (int di = 0; di < (int)runningWorkflow.devices.size(); ++di) {
2107 auto& context = childFds[di];
2108 createPipes(context.childstdin);
2109 createPipes(context.childstdout);
2110 if (driverInfo.mode == DriverMode::EMBEDDED || runningWorkflow.devices[di].resource.hostname != driverInfo.deployHostname) {
2111 spawnRemoteDevice(loop, forwardedStdin.str(),
2112 runningWorkflow.devices[di], controls[di], deviceExecutions[di], infos, allStates);
2113 } else {
2114 DeviceRef ref{di};
2115 spawnDevice(loop,
2116 ref,
2117 runningWorkflow.devices, driverInfo,
2118 controls, deviceExecutions, infos,
2119 allStates,
2120 serviceRegistry, varmap,
2121 childFds, parentCPU, parentNode);
2122 }
2123 }
2124 handleSignals();
2125 handleChildrenStdio(&serverContext, forwardedStdin.str(), childFds, pollHandles);
2126 for (auto& callback : postScheduleCallbacks) {
2127 callback(serviceRegistry, {varmap});
2128 }
2129 assert(infos.empty() == false);
2130
2131 // In case resource monitoring is requested, we dump metrics to disk
2132 // every 3 minutes.
2133 if (driverInfo.resourcesMonitoringDumpInterval && ResourcesMonitoringHelper::isResourcesMonitoringEnabled(driverInfo.resourcesMonitoringInterval)) {
2134 uv_timer_init(loop, &metricDumpTimer);
2135 uv_timer_start(&metricDumpTimer, dumpMetricsCallback,
2136 driverInfo.resourcesMonitoringDumpInterval * 1000,
2137 driverInfo.resourcesMonitoringDumpInterval * 1000);
2138 }
2140 for (const auto& processorInfo : dataProcessorInfos) {
2141 const auto& cmdLineArgs = processorInfo.cmdLineArgs;
2142 if (std::find(cmdLineArgs.begin(), cmdLineArgs.end(), "--severity") != cmdLineArgs.end()) {
2143 for (size_t counter = 0; const auto& spec : runningWorkflow.devices) {
2144 if (spec.name.compare(processorInfo.name) == 0) {
2145 auto& info = infos[counter];
2146 const auto logLevelIt = std::find(cmdLineArgs.begin(), cmdLineArgs.end(), "--severity") + 1;
2147 if ((*logLevelIt).compare("debug") == 0) {
2148 info.logLevel = LogParsingHelpers::LogLevel::Debug;
2149 } else if ((*logLevelIt).compare("detail") == 0) {
2150 info.logLevel = LogParsingHelpers::LogLevel::Debug;
2151 } else if ((*logLevelIt).compare("info") == 0) {
2152 info.logLevel = LogParsingHelpers::LogLevel::Info;
2153 } else if ((*logLevelIt).compare("warning") == 0) {
2154 info.logLevel = LogParsingHelpers::LogLevel::Warning;
2155 } else if ((*logLevelIt).compare("error") == 0) {
2156 info.logLevel = LogParsingHelpers::LogLevel::Error;
2157 } else if ((*logLevelIt).compare("important") == 0) {
2158 info.logLevel = LogParsingHelpers::LogLevel::Info;
2159 } else if ((*logLevelIt).compare("alarm") == 0) {
2160 info.logLevel = LogParsingHelpers::LogLevel::Alarm;
2161 } else if ((*logLevelIt).compare("critical") == 0) {
2162 info.logLevel = LogParsingHelpers::LogLevel::Critical;
2163 } else if ((*logLevelIt).compare("fatal") == 0) {
2164 info.logLevel = LogParsingHelpers::LogLevel::Fatal;
2165 }
2166 break;
2167 }
2168 ++counter;
2169 }
2170 }
2171 }
2172 LOG(info) << "Redeployment of configuration done.";
2173 } break;
2174 case DriverState::RUNNING:
2175 // Run any pending libUV event loop, block if
2176 // any, so that we do not consume CPU time when the driver is
2177 // idle.
2178 devicesManager->flush();
2179 // We print the event loop for the gui only once every
2180 // 6000 iterations (i.e. ~2 minutes). To avoid spamming, while still
2181 // being able to see the event loop in case of a deadlock / systematic failure.
2182 if (guiTimerExpired == false) {
2183 O2_SIGNPOST_EVENT_EMIT(driver, sid, "mainloop", "Entering event loop with %{public}s", once ? "UV_RUN_ONCE" : "UV_RUN_NOWAIT");
2184 }
2185 uv_run(loop, once ? UV_RUN_ONCE : UV_RUN_NOWAIT);
2186 once = true;
2187 // Calculate what we should do next and eventually
2188 // show the GUI
2189 if (guiQuitRequested ||
2190 (driverInfo.processingPolicies.termination == TerminationPolicy::QUIT && (checkIfCanExit(infos) == true))) {
2191 // Something requested to quit. This can be a user
2192 // interaction with the GUI or (if --completion-policy=quit)
2193 // it could mean that the workflow does not have anything else to do.
2194 // Let's update the GUI one more time and then EXIT.
2195 LOG(info) << "Quitting";
2196 driverInfo.states.push_back(DriverState::QUIT_REQUESTED);
2197 } else if (infos.size() != runningWorkflow.devices.size()) {
2198 // If the number of devices is different from
2199 // the DeviceInfos it means the speicification
2200 // does not match what is running, so we need to do
2201 // further scheduling.
2202 driverInfo.states.push_back(DriverState::RUNNING);
2203 driverInfo.states.push_back(DriverState::REDEPLOY_GUI);
2204 driverInfo.states.push_back(DriverState::SCHEDULE);
2205 driverInfo.states.push_back(DriverState::MERGE_CONFIGS);
2206 } else if (runningWorkflow.devices.empty() && driverConfig.batch == true) {
2207 LOG(info) << "No device resulting from the workflow. Quitting.";
2208 // If there are no deviceSpecs, we exit.
2209 driverInfo.states.push_back(DriverState::EXIT);
2210 } else if (runningWorkflow.devices.empty() && driverConfig.batch == false && !guiDeployedOnce) {
2211 // In case of an empty workflow, we need to deploy the GUI at least once.
2212 driverInfo.states.push_back(DriverState::RUNNING);
2213 driverInfo.states.push_back(DriverState::REDEPLOY_GUI);
2214 } else {
2215 driverInfo.states.push_back(DriverState::RUNNING);
2216 }
2217 break;
2218 case DriverState::QUIT_REQUESTED: {
2219 std::time_t result = std::time(nullptr);
2220 char buffer[32];
2221 std::strncpy(buffer, std::ctime(&result), 26);
2222 O2_SIGNPOST_EVENT_EMIT_INFO(driver, sid, "mainloop", "Quit requested at %{public}s", buffer);
2223 guiQuitRequested = true;
2224 // We send SIGCONT to make sure stopped children are resumed
2225 killChildren(infos, SIGCONT);
2226 // We send SIGTERM to make sure we do the STOP transition in FairMQ
2227 killChildren(infos, SIGTERM);
2228 // We have a timer to send SIGUSR1 to make sure we advance all devices
2229 // in a timely manner.
2230 force_step_timer.data = &infos;
2231 uv_timer_start(&force_step_timer, single_step_callback, 0, 300);
2232 driverInfo.states.push_back(DriverState::HANDLE_CHILDREN);
2233 break;
2234 }
2235 case DriverState::HANDLE_CHILDREN: {
2236 // Run any pending libUV event loop, block if
2237 // any, so that we do not consume CPU time when the driver is
2238 // idle.
2239 uv_run(loop, once ? UV_RUN_ONCE : UV_RUN_NOWAIT);
2240 once = true;
2241 // I allow queueing of more sigchld only when
2242 // I process the previous call
2243 if (forceful_exit == true) {
2244 static bool forcefulExitMessage = true;
2245 if (forcefulExitMessage) {
2246 LOG(info) << "Forceful exit requested.";
2247 forcefulExitMessage = false;
2248 }
2249 killChildren(infos, SIGCONT);
2250 killChildren(infos, SIGKILL);
2251 }
2252 sigchld_requested = false;
2253 driverInfo.sigchldRequested = false;
2254 processChildrenOutput(loop, driverInfo, infos, runningWorkflow.devices, controls);
2255 hasError = processSigChild(infos, runningWorkflow.devices);
2256 allChildrenGone = areAllChildrenGone(infos);
2257 bool canExit = checkIfCanExit(infos);
2258 bool supposedToQuit = (guiQuitRequested || canExit || graceful_exit);
2259
2260 if (allChildrenGone && (supposedToQuit || driverInfo.processingPolicies.termination == TerminationPolicy::QUIT)) {
2261 // We move to the exit, regardless of where we were
2262 driverInfo.states.resize(0);
2263 driverInfo.states.push_back(DriverState::EXIT);
2264 } else if (hasError && driverInfo.processingPolicies.error == TerminationPolicy::QUIT && !supposedToQuit) {
2265 graceful_exit = 1;
2266 force_exit_timer.data = &infos;
2267 static bool forceful_timer_started = false;
2268 if (forceful_timer_started == false) {
2269 forceful_timer_started = true;
2270 uv_timer_start(&force_exit_timer, force_exit_callback, 15000, 3000);
2271 }
2272 driverInfo.states.push_back(DriverState::QUIT_REQUESTED);
2273 } else if (allChildrenGone == false && supposedToQuit) {
2274 driverInfo.states.push_back(DriverState::HANDLE_CHILDREN);
2275 } else {
2276 }
2277 } break;
2278 case DriverState::EXIT: {
2279 if (ResourcesMonitoringHelper::isResourcesMonitoringEnabled(driverInfo.resourcesMonitoringInterval)) {
2280 if (driverInfo.resourcesMonitoringDumpInterval) {
2281 uv_timer_stop(&metricDumpTimer);
2282 }
2283 LOGP(info, "Dumping performance metrics to {}.json file", driverInfo.resourcesMonitoringFilename);
2284 dumpMetricsCallback(&metricDumpTimer);
2285 }
2286 dumpRunSummary(serverContext, driverInfo, infos, runningWorkflow.devices);
2287 // This is a clean exit. Before we do so, if required,
2288 // we dump the configuration of all the devices so that
2289 // we can reuse it. Notice we do not dump anything if
2290 // the workflow was not really run.
2291 // NOTE: is this really what we want? should we run
2292 // SCHEDULE and dump the full configuration as well?
2293 if (infos.empty()) {
2294 return 0;
2295 }
2296 boost::property_tree::ptree finalConfig;
2297 assert(infos.size() == runningWorkflow.devices.size());
2298 for (size_t di = 0; di < infos.size(); ++di) {
2299 auto& info = infos[di];
2300 auto& spec = runningWorkflow.devices[di];
2301 finalConfig.put_child(spec.name, info.currentConfig);
2302 }
2303 LOG(info) << "Dumping used configuration in dpl-config.json";
2304
2305 std::ofstream outDPLConfigFile("dpl-config.json", std::ios::out);
2306 if (outDPLConfigFile.is_open()) {
2307 boost::property_tree::write_json(outDPLConfigFile, finalConfig);
2308 } else {
2309 LOGP(warning, "Could not write out final configuration file. Read only run folder?");
2310 }
2311 if (driverInfo.noSHMCleanup) {
2312 LOGP(warning, "Not cleaning up shared memory.");
2313 } else {
2314 cleanupSHM(driverInfo.uniqueWorkflowId);
2315 }
2316 return calculateExitCode(driverInfo, runningWorkflow.devices, infos);
2317 }
2318 case DriverState::PERFORM_CALLBACKS:
2319 for (auto& callback : driverControl.callbacks) {
2320 callback(workflow, runningWorkflow.devices, deviceExecutions, dataProcessorInfos, commandInfo);
2321 }
2322 driverControl.callbacks.clear();
2323 break;
2324 default:
2325 LOG(error) << "Driver transitioned in an unknown state("
2326 << "current: " << (int)current
2327 << ", previous: " << (int)previous
2328 << "). Shutting down.";
2329 driverInfo.states.push_back(DriverState::QUIT_REQUESTED);
2330 }
2331 }
2332 O2_SIGNPOST_END(driver, sid, "driver", "End driver loop");
2333}
2334
2335// Print help
2336void printHelp(bpo::variables_map const& varmap,
2337 bpo::options_description const& executorOptions,
2338 std::vector<DataProcessorSpec> const& physicalWorkflow,
2339 std::vector<ConfigParamSpec> const& currentWorkflowOptions)
2340{
2341 auto mode = varmap["help"].as<std::string>();
2342 bpo::options_description helpOptions;
2343 if (mode == "full" || mode == "short" || mode == "executor") {
2344 helpOptions.add(executorOptions);
2345 }
2346 // this time no veto is applied, so all the options are added for printout
2347 if (mode == "executor") {
2348 // nothing more
2349 } else if (mode == "workflow") {
2350 // executor options and workflow options, skip the actual workflow
2351 o2::framework::WorkflowSpec emptyWorkflow;
2352 helpOptions.add(ConfigParamsHelper::prepareOptionDescriptions(emptyWorkflow, currentWorkflowOptions));
2353 } else if (mode == "full" || mode == "short") {
2354 helpOptions.add(ConfigParamsHelper::prepareOptionDescriptions(physicalWorkflow, currentWorkflowOptions,
2355 bpo::options_description(),
2356 mode));
2357 } else {
2358 helpOptions.add(ConfigParamsHelper::prepareOptionDescriptions(physicalWorkflow, {},
2359 bpo::options_description(),
2360 mode));
2361 }
2362 if (helpOptions.options().size() == 0) {
2363 // the specified argument is invalid, add at leat the executor options
2364 mode += " is an invalid argument, please use correct argument for";
2365 helpOptions.add(executorOptions);
2366 }
2367 std::cout << "ALICE O2 DPL workflow driver" //
2368 << " (" << mode << " help)" << std::endl //
2369 << helpOptions << std::endl; //
2370}
2371
2372// Helper to find out if stdout is actually attached to a pipe.
2374{
2375 struct stat s;
2376 fstat(STDOUT_FILENO, &s);
2377 return ((s.st_mode & S_IFIFO) != 0);
2378}
2379
2381{
2382 struct stat s;
2383 int r = fstat(STDIN_FILENO, &s);
2384 // If stdin cannot be statted, we assume the shell is some sort of
2385 // non-interactive container thing
2386 if (r < 0) {
2387 return false;
2388 }
2389 // If stdin is a pipe or a file, we try to fetch configuration from there
2390 return ((s.st_mode & S_IFIFO) != 0 || (s.st_mode & S_IFREG) != 0);
2391}
2392
2394{
2395 struct CloningSpec {
2396 std::string templateMatcher;
2397 std::string cloneName;
2398 };
2399 auto s = ctx.options().get<std::string>("clone");
2400 std::vector<CloningSpec> specs;
2401 std::string delimiter = ",";
2402
2403 while (s.empty() == false) {
2404 auto newPos = s.find(delimiter);
2405 auto token = s.substr(0, newPos);
2406 auto split = token.find(":");
2407 if (split == std::string::npos) {
2408 throw std::runtime_error("bad clone definition. Syntax <template-processor>:<clone-name>");
2409 }
2410 auto key = token.substr(0, split);
2411 token.erase(0, split + 1);
2412 size_t error;
2413 std::string value = "";
2414 try {
2415 auto numValue = std::stoll(token, &error, 10);
2416 if (token[error] != '\0') {
2417 throw std::runtime_error("bad name for clone:" + token);
2418 }
2419 value = key + "_c" + std::to_string(numValue);
2420 } catch (std::invalid_argument& e) {
2421 value = token;
2422 }
2423 specs.push_back({key, value});
2424 s.erase(0, newPos + (newPos == std::string::npos ? 0 : 1));
2425 }
2426 if (s.empty() == false && specs.empty() == true) {
2427 throw std::runtime_error("bad pipeline definition. Syntax <processor>:<pipeline>");
2428 }
2429
2430 std::vector<DataProcessorSpec> extraSpecs;
2431 for (auto& spec : specs) {
2432 for (auto& processor : workflow) {
2433 if (processor.name == spec.templateMatcher) {
2434 auto clone = processor;
2435 clone.name = spec.cloneName;
2436 extraSpecs.push_back(clone);
2437 }
2438 }
2439 }
2440 workflow.insert(workflow.end(), extraSpecs.begin(), extraSpecs.end());
2441}
2442
2444{
2445 struct PipelineSpec {
2446 std::string matcher;
2447 int64_t pipeline;
2448 };
2449 auto s = ctx.options().get<std::string>("pipeline");
2450 std::vector<PipelineSpec> specs;
2451 std::string delimiter = ",";
2452
2453 while (s.empty() == false) {
2454 auto newPos = s.find(delimiter);
2455 auto token = s.substr(0, newPos);
2456 auto split = token.find(":");
2457 if (split == std::string::npos) {
2458 throw std::runtime_error("bad pipeline definition. Syntax <processor>:<pipeline>");
2459 }
2460 auto key = token.substr(0, split);
2461 token.erase(0, split + 1);
2462 size_t error;
2463 auto value = std::stoll(token, &error, 10);
2464 if (token[error] != '\0') {
2465 throw std::runtime_error("Bad pipeline definition. Expecting integer");
2466 }
2467 specs.push_back({key, value});
2468 s.erase(0, newPos + (newPos == std::string::npos ? 0 : 1));
2469 }
2470 if (s.empty() == false && specs.empty() == true) {
2471 throw std::runtime_error("bad pipeline definition. Syntax <processor>:<pipeline>");
2472 }
2473
2474 for (auto& spec : specs) {
2475 for (auto& processor : workflow) {
2476 if (processor.name == spec.matcher) {
2477 processor.maxInputTimeslices = spec.pipeline;
2478 }
2479 }
2480 }
2481}
2482
2484{
2485 struct LabelsSpec {
2486 std::string_view matcher;
2487 std::vector<std::string> labels;
2488 };
2489 std::vector<LabelsSpec> specs;
2490
2491 auto labelsString = ctx.options().get<std::string>("labels");
2492 if (labelsString.empty()) {
2493 return;
2494 }
2495 std::string_view sv{labelsString};
2496
2497 size_t specStart = 0;
2498 size_t specEnd = 0;
2499 constexpr char specDelim = ',';
2500 constexpr char labelDelim = ':';
2501 do {
2502 specEnd = sv.find(specDelim, specStart);
2503 auto token = sv.substr(specStart, specEnd == std::string_view::npos ? std::string_view::npos : specEnd - specStart);
2504 if (token.empty()) {
2505 throw std::runtime_error("bad labels definition. Syntax <processor>:<label>[:<label>][,<processor>:<label>[:<label>]");
2506 }
2507
2508 size_t labelDelimPos = token.find(labelDelim);
2509 if (labelDelimPos == 0 || labelDelimPos == std::string_view::npos) {
2510 throw std::runtime_error("bad labels definition. Syntax <processor>:<label>[:<label>][,<processor>:<label>[:<label>]");
2511 }
2512 LabelsSpec spec{.matcher = token.substr(0, labelDelimPos), .labels = {}};
2513
2514 size_t labelEnd = labelDelimPos + 1;
2515 do {
2516 size_t labelStart = labelDelimPos + 1;
2517 labelEnd = token.find(labelDelim, labelStart);
2518 auto label = labelEnd == std::string_view::npos ? token.substr(labelStart) : token.substr(labelStart, labelEnd - labelStart);
2519 if (label.empty()) {
2520 throw std::runtime_error("bad labels definition. Syntax <processor>:<label>[:<label>][,<processor>:<label>[:<label>]");
2521 }
2522 spec.labels.emplace_back(label);
2523 labelDelimPos = labelEnd;
2524 } while (labelEnd != std::string_view::npos);
2525
2526 specs.push_back(spec);
2527 specStart = specEnd + 1;
2528 } while (specEnd != std::string_view::npos);
2529
2530 if (labelsString.empty() == false && specs.empty() == true) {
2531 throw std::runtime_error("bad labels definition. Syntax <processor>:<label>[:<label>][,<processor>:<label>[:<label>]");
2532 }
2533
2534 for (auto& spec : specs) {
2535 for (auto& processor : workflow) {
2536 if (processor.name == spec.matcher) {
2537 for (const auto& label : spec.labels) {
2538 if (std::find_if(processor.labels.begin(), processor.labels.end(),
2539 [label](const auto& procLabel) { return procLabel.value == label; }) == processor.labels.end()) {
2540 processor.labels.push_back({label});
2541 }
2542 }
2543 }
2544 }
2545 }
2546}
2547
2549void initialiseDriverControl(bpo::variables_map const& varmap,
2550 DriverInfo& driverInfo,
2551 DriverControl& control)
2552{
2553 // Control is initialised outside the main loop because
2554 // command line options are really affecting control.
2555 control.defaultQuiet = varmap["quiet"].as<bool>();
2556 control.defaultStopped = varmap["stop"].as<bool>();
2557
2558 if (varmap["single-step"].as<bool>()) {
2559 control.state = DriverControlState::STEP;
2560 } else {
2561 control.state = DriverControlState::PLAY;
2562 }
2563
2564 if (varmap["graphviz"].as<bool>()) {
2565 // Dump a graphviz representation of what I will do.
2566 control.callbacks = {[](WorkflowSpec const&,
2567 DeviceSpecs const& specs,
2568 DeviceExecutions const&,
2570 CommandInfo const&) {
2572 }};
2573 control.forcedTransitions = {
2574 DriverState::EXIT, //
2575 DriverState::PERFORM_CALLBACKS, //
2576 DriverState::MERGE_CONFIGS, //
2577 DriverState::IMPORT_CURRENT_WORKFLOW, //
2578 DriverState::MATERIALISE_WORKFLOW //
2579 };
2580 } else if (!varmap["dds"].as<std::string>().empty()) {
2581 // Dump a DDS representation of what I will do.
2582 // Notice that compared to DDS we need to schedule things,
2583 // because DDS needs to be able to have actual Executions in
2584 // order to provide a correct configuration.
2585 control.callbacks = {[filename = varmap["dds"].as<std::string>(),
2586 workflowSuffix = varmap["dds-workflow-suffix"],
2587 driverMode = driverInfo.mode](WorkflowSpec const& workflow,
2588 DeviceSpecs const& specs,
2589 DeviceExecutions const& executions,
2590 DataProcessorInfos& dataProcessorInfos,
2591 CommandInfo const& commandInfo) {
2592 if (filename == "-") {
2593 DDSConfigHelpers::dumpDeviceSpec2DDS(std::cout, driverMode, workflowSuffix.as<std::string>(), workflow, dataProcessorInfos, specs, executions, commandInfo);
2594 } else {
2595 std::ofstream out(filename);
2596 DDSConfigHelpers::dumpDeviceSpec2DDS(out, driverMode, workflowSuffix.as<std::string>(), workflow, dataProcessorInfos, specs, executions, commandInfo);
2597 }
2598 }};
2599 control.forcedTransitions = {
2600 DriverState::EXIT, //
2601 DriverState::PERFORM_CALLBACKS, //
2602 DriverState::MERGE_CONFIGS, //
2603 DriverState::IMPORT_CURRENT_WORKFLOW, //
2604 DriverState::MATERIALISE_WORKFLOW //
2605 };
2606 } else if (!varmap["o2-control"].as<std::string>().empty() or !varmap["mermaid"].as<std::string>().empty()) {
2607 // Dump the workflow in o2-control and/or mermaid format
2608 control.callbacks = {[filename = varmap["mermaid"].as<std::string>(),
2609 workflowName = varmap["o2-control"].as<std::string>()](WorkflowSpec const&,
2610 DeviceSpecs const& specs,
2611 DeviceExecutions const& executions,
2613 CommandInfo const& commandInfo) {
2614 if (!workflowName.empty()) {
2615 dumpDeviceSpec2O2Control(workflowName, specs, executions, commandInfo);
2616 }
2617 if (!filename.empty()) {
2618 if (filename == "-") {
2620 } else {
2621 std::ofstream output(filename);
2623 }
2624 }
2625 }};
2626 control.forcedTransitions = {
2627 DriverState::EXIT, //
2628 DriverState::PERFORM_CALLBACKS, //
2629 DriverState::MERGE_CONFIGS, //
2630 DriverState::IMPORT_CURRENT_WORKFLOW, //
2631 DriverState::MATERIALISE_WORKFLOW //
2632 };
2633
2634 } else if (varmap.count("id")) {
2635 // Add our own stacktrace dumping
2636 if (getenv("O2_NO_CATCHALL_EXCEPTIONS") != nullptr && strcmp(getenv("O2_NO_CATCHALL_EXCEPTIONS"), "0") != 0) {
2637 LOGP(info, "Not instrumenting crash signals because O2_NO_CATCHALL_EXCEPTIONS is set");
2638 gEnv->SetValue("Root.Stacktrace", "no");
2639 gSystem->ResetSignal(kSigSegmentationViolation, kTRUE);
2640 rlimit limit;
2641 if (getrlimit(RLIMIT_CORE, &limit) == 0) {
2642 LOGP(info, "Core limit: {} {}", limit.rlim_cur, limit.rlim_max);
2643 }
2644 }
2645 if (varmap["stacktrace-on-signal"].as<std::string>() == "simple" && (getenv("O2_NO_CATCHALL_EXCEPTIONS") == nullptr || strcmp(getenv("O2_NO_CATCHALL_EXCEPTIONS"), "0") == 0)) {
2646 LOGP(info, "Instrumenting crash signals");
2647 signal(SIGSEGV, handle_crash);
2648 signal(SIGABRT, handle_crash);
2649 signal(SIGBUS, handle_crash);
2650 signal(SIGILL, handle_crash);
2651 signal(SIGFPE, handle_crash);
2652 }
2653 // FIXME: for the time being each child needs to recalculate the workflow,
2654 // so that it can understand what it needs to do. This is obviously
2655 // a bad idea. In the future we should have the client be pushed
2656 // it's own configuration by the driver.
2657 control.forcedTransitions = {
2658 DriverState::DO_CHILD, //
2659 DriverState::BIND_GUI_PORT, //
2660 DriverState::MERGE_CONFIGS, //
2661 DriverState::IMPORT_CURRENT_WORKFLOW, //
2662 DriverState::MATERIALISE_WORKFLOW //
2663 };
2664 } else if ((varmap["dump-workflow"].as<bool>() == true) || (varmap["run"].as<bool>() == false && varmap.count("id") == 0 && isOutputToPipe())) {
2665 control.callbacks = {[filename = varmap["dump-workflow-file"].as<std::string>()](WorkflowSpec const& workflow,
2666 DeviceSpecs const&,
2667 DeviceExecutions const&,
2668 DataProcessorInfos& dataProcessorInfos,
2669 CommandInfo const& commandInfo) {
2670 if (filename == "-") {
2671 WorkflowSerializationHelpers::dump(std::cout, workflow, dataProcessorInfos, commandInfo);
2672 // FIXME: this is to avoid trailing garbage..
2673 exit(0);
2674 } else {
2675 std::ofstream output(filename);
2676 WorkflowSerializationHelpers::dump(output, workflow, dataProcessorInfos, commandInfo);
2677 }
2678 }};
2679 control.forcedTransitions = {
2680 DriverState::EXIT, //
2681 DriverState::PERFORM_CALLBACKS, //
2682 DriverState::MERGE_CONFIGS, //
2683 DriverState::IMPORT_CURRENT_WORKFLOW, //
2684 DriverState::MATERIALISE_WORKFLOW //
2685 };
2686 } else {
2687 // By default we simply start the main loop of the driver.
2688 control.forcedTransitions = {
2689 DriverState::INIT, //
2690 DriverState::BIND_GUI_PORT, //
2691 DriverState::IMPORT_CURRENT_WORKFLOW, //
2692 DriverState::MATERIALISE_WORKFLOW //
2693 };
2694 }
2695}
2696
2698void conflicting_options(const boost::program_options::variables_map& vm,
2699 const std::string& opt1, const std::string& opt2)
2700{
2701 if (vm.count(opt1) && !vm[opt1].defaulted() &&
2702 vm.count(opt2) && !vm[opt2].defaulted()) {
2703 throw std::logic_error(std::string("Conflicting options '") +
2704 opt1 + "' and '" + opt2 + "'.");
2705 }
2706}
2707
2708template <typename T>
2710 std::vector<T>& v,
2711 std::vector<int>& indices)
2712{
2713 using std::swap; // to permit Koenig lookup
2714 for (int i = 0; i < (int)indices.size(); i++) {
2715 auto current = i;
2716 while (i != indices[current]) {
2717 auto next = indices[current];
2718 swap(v[current], v[next]);
2719 indices[current] = current;
2720 current = next;
2721 }
2722 indices[current] = current;
2723 }
2724}
2725
2726// Check if the workflow is resiliant to failures
2727void checkNonResiliency(std::vector<DataProcessorSpec> const& specs,
2728 std::vector<std::pair<int, int>> const& edges)
2729{
2730 auto checkExpendable = [](DataProcessorLabel const& label) {
2731 return label.value == "expendable";
2732 };
2733 auto checkResilient = [](DataProcessorLabel const& label) {
2734 return label.value == "resilient" || label.value == "expendable";
2735 };
2736
2737 for (auto& edge : edges) {
2738 auto& src = specs[edge.first];
2739 auto& dst = specs[edge.second];
2740 if (std::none_of(src.labels.begin(), src.labels.end(), checkExpendable)) {
2741 continue;
2742 }
2743 if (std::any_of(dst.labels.begin(), dst.labels.end(), checkResilient)) {
2744 continue;
2745 }
2746 throw std::runtime_error("Workflow is not resiliant to failures. Processor " + dst.name + " gets inputs from expendable devices, but is not marked as expendable or resilient itself.");
2747 }
2748}
2749
2750std::string debugTopoInfo(std::vector<DataProcessorSpec> const& specs,
2751 std::vector<TopoIndexInfo> const& infos,
2752 std::vector<std::pair<int, int>> const& edges)
2753{
2754 std::ostringstream out;
2755
2756 out << "\nTopological info:\n";
2757 for (auto& ti : infos) {
2758 out << specs[ti.index].name << " (index: " << ti.index << ", layer: " << ti.layer << ")\n";
2759 out << " Inputs:\n";
2760 for (auto& ii : specs[ti.index].inputs) {
2761 out << " - " << DataSpecUtils::describe(ii) << "\n";
2762 }
2763 out << "\n Outputs:\n";
2764 for (auto& ii : specs[ti.index].outputs) {
2765 out << " - " << DataSpecUtils::describe(ii) << "\n";
2766 }
2767 }
2768 out << "\nEdges values:\n";
2769 for (auto& e : edges) {
2770 out << specs[e.second].name << " depends on " << specs[e.first].name << "\n";
2771 }
2772 for (auto& d : specs) {
2773 out << "- " << d.name << std::endl;
2774 }
2776 return out.str();
2777}
2778
2779void enableSignposts(std::string const& signpostsToEnable)
2780{
2781 static pid_t pid = getpid();
2782 if (signpostsToEnable.empty() == true) {
2783 auto printAllSignposts = [](char const* name, void* l, void* context) {
2784 auto* log = (_o2_log_t*)l;
2785 LOGP(detail, "Signpost stream {} disabled. Enable it with o2-log -p {} -a {}", name, pid, (void*)&log->stacktrace);
2786 return true;
2787 };
2788 o2_walk_logs(printAllSignposts, nullptr);
2789 return;
2790 }
2791 auto matchingLogEnabler = [](char const* name, void* l, void* context) {
2792 auto* log = (_o2_log_t*)l;
2793 auto* selectedName = (char const*)context;
2794 std::string prefix = "ch.cern.aliceo2.";
2795 auto* last = strchr(selectedName, ':');
2796 int maxDepth = 1;
2797 if (last) {
2798 char* err;
2799 maxDepth = strtol(last + 1, &err, 10);
2800 if (*(last + 1) == '\0' || *err != '\0') {
2801 maxDepth = 1;
2802 }
2803 }
2804
2805 auto fullName = prefix + std::string{selectedName, last ? last - selectedName : strlen(selectedName)};
2806 if (fullName == name) {
2807 LOGP(info, "Enabling signposts for stream \"{}\" with depth {}.", fullName, maxDepth);
2808 _o2_log_set_stacktrace(log, maxDepth);
2809 return false;
2810 } else {
2811 LOGP(info, "Signpost stream \"{}\" disabled. Enable it with o2-log -p {} -a {}", name, pid, (void*)&log->stacktrace);
2812 }
2813 return true;
2814 };
2815 // Split signpostsToEnable by comma using strtok_r
2816 char* saveptr;
2817 char* src = const_cast<char*>(signpostsToEnable.data());
2818 auto* token = strtok_r(src, ",", &saveptr);
2819 while (token) {
2820 o2_walk_logs(matchingLogEnabler, token);
2821 token = strtok_r(nullptr, ",", &saveptr);
2822 }
2823}
2824
2825void overrideAll(o2::framework::ConfigContext& ctx, std::vector<o2::framework::DataProcessorSpec>& workflow)
2826{
2827 overrideCloning(ctx, workflow);
2828 overridePipeline(ctx, workflow);
2829 overrideLabels(ctx, workflow);
2830}
2831
2832o2::framework::ConfigContext createConfigContext(std::unique_ptr<ConfigParamRegistry>& workflowOptionsRegistry,
2833 o2::framework::ServiceRegistry& configRegistry,
2834 std::vector<o2::framework::ConfigParamSpec>& workflowOptions,
2835 std::vector<o2::framework::ConfigParamSpec>& extraOptions, int argc, char** argv)
2836{
2837 std::vector<std::unique_ptr<o2::framework::ParamRetriever>> retrievers;
2838 std::unique_ptr<o2::framework::ParamRetriever> retriever{new o2::framework::BoostOptionsRetriever(true, argc, argv)};
2839 retrievers.emplace_back(std::move(retriever));
2840 auto workflowOptionsStore = std::make_unique<o2::framework::ConfigParamStore>(workflowOptions, std::move(retrievers));
2841 workflowOptionsStore->preload();
2842 workflowOptionsStore->activate();
2843 workflowOptionsRegistry = std::make_unique<ConfigParamRegistry>(std::move(workflowOptionsStore));
2844 extraOptions = o2::framework::ConfigParamDiscovery::discover(*workflowOptionsRegistry, argc, argv);
2845 for (auto& extra : extraOptions) {
2846 workflowOptions.push_back(extra);
2847 }
2848
2849 return o2::framework::ConfigContext(*workflowOptionsRegistry, o2::framework::ServiceRegistryRef{configRegistry}, argc, argv);
2850}
2851
2852std::unique_ptr<o2::framework::ServiceRegistry> createRegistry()
2853{
2854 return std::make_unique<o2::framework::ServiceRegistry>();
2855}
2856
2857// This is a toy executor for the workflow spec
2858// What it needs to do is:
2859//
2860// - Print the properties of each DataProcessorSpec
2861// - Fork one process per DataProcessorSpec
2862// - Parent -> wait for all the children to complete (eventually
2863// killing them all on ctrl-c).
2864// - Child, pick the data-processor ID and start a O2DataProcessorDevice for
2865// each DataProcessorSpec
2866int doMain(int argc, char** argv, o2::framework::WorkflowSpec const& workflow,
2867 std::vector<ChannelConfigurationPolicy> const& channelPolicies,
2868 std::vector<CompletionPolicy> const& completionPolicies,
2869 std::vector<DispatchPolicy> const& dispatchPolicies,
2870 std::vector<ResourcePolicy> const& resourcePolicies,
2871 std::vector<CallbacksPolicy> const& callbacksPolicies,
2872 std::vector<SendingPolicy> const& sendingPolicies,
2873 std::vector<ConfigParamSpec> const& currentWorkflowOptions,
2874 std::vector<ConfigParamSpec> const& detectedParams,
2875 o2::framework::ConfigContext& configContext)
2876{
2877 // Peek very early in the driver options and look for
2878 // signposts, so the we can enable it without going through the whole dance
2879 if (getenv("DPL_DRIVER_SIGNPOSTS")) {
2880 enableSignposts(getenv("DPL_DRIVER_SIGNPOSTS"));
2881 }
2882
2883 std::vector<std::string> currentArgs;
2884 std::vector<PluginInfo> plugins;
2885 std::vector<ForwardingPolicy> forwardingPolicies = ForwardingPolicy::createDefaultPolicies();
2886
2887 for (int ai = 1; ai < argc; ++ai) {
2888 currentArgs.emplace_back(argv[ai]);
2889 }
2890
2891 WorkflowInfo currentWorkflow{
2892 argv[0],
2893 currentArgs,
2894 currentWorkflowOptions};
2895
2896 ProcessingPolicies processingPolicies;
2897 enum LogParsingHelpers::LogLevel minFailureLevel;
2898 bpo::options_description executorOptions("Executor options");
2899 const char* helpDescription = "print help: short, full, executor, or processor name";
2900 enum DriverMode driverMode;
2901 executorOptions.add_options() //
2902 ("help,h", bpo::value<std::string>()->implicit_value("short"), helpDescription) // //
2903 ("quiet,q", bpo::value<bool>()->zero_tokens()->default_value(false), "quiet operation") // //
2904 ("stop,s", bpo::value<bool>()->zero_tokens()->default_value(false), "stop before device start") // //
2905 ("single-step", bpo::value<bool>()->zero_tokens()->default_value(false), "start in single step mode") // //
2906 ("batch,b", bpo::value<std::vector<std::string>>()->zero_tokens()->composing(), "batch processing mode") // //
2907 ("no-batch", bpo::value<bool>()->zero_tokens(), "force gui processing mode") // //
2908 ("no-cleanup", bpo::value<bool>()->zero_tokens()->default_value(false), "do not cleanup the shm segment") // //
2909 ("hostname", bpo::value<std::string>()->default_value("localhost"), "hostname to deploy") // //
2910 ("resources", bpo::value<std::string>()->default_value(""), "resources allocated for the workflow") // //
2911 ("start-port,p", bpo::value<unsigned short>()->default_value(22000), "start port to allocate") // //
2912 ("port-range,pr", bpo::value<unsigned short>()->default_value(1000), "ports in range") // //
2913 ("completion-policy,c", bpo::value<TerminationPolicy>(&processingPolicies.termination)->default_value(TerminationPolicy::QUIT), // //
2914 "what to do when processing is finished: quit, wait") // //
2915 ("error-policy", bpo::value<TerminationPolicy>(&processingPolicies.error)->default_value(TerminationPolicy::QUIT), // //
2916 "what to do when a device has an error: quit, wait") // //
2917 ("min-failure-level", bpo::value<LogParsingHelpers::LogLevel>(&minFailureLevel)->default_value(LogParsingHelpers::LogLevel::Fatal), // //
2918 "minimum message level which will be considered as fatal and exit with 1") // //
2919 ("graphviz,g", bpo::value<bool>()->zero_tokens()->default_value(false), "produce graphviz output") // //
2920 ("mermaid", bpo::value<std::string>()->default_value(""), "produce graph output in mermaid format in file under specified name or on stdout if argument is \"-\"") // //
2921 ("timeout,t", bpo::value<uint64_t>()->default_value(0), "forced exit timeout (in seconds)") // //
2922 ("dds,D", bpo::value<std::string>()->default_value(""), "create DDS configuration") // //
2923 ("dds-workflow-suffix,D", bpo::value<std::string>()->default_value(""), "suffix for DDS names") // //
2924 ("dump-workflow,dump", bpo::value<bool>()->zero_tokens()->default_value(false), "dump workflow as JSON") // //
2925 ("dump-workflow-file", bpo::value<std::string>()->default_value("-"), "file to which do the dump") // //
2926 ("driver-mode", bpo::value<DriverMode>(&driverMode)->default_value(DriverMode::STANDALONE), R"(how to run the driver. default: "standalone". Valid: "embedded")") // //
2927 ("run", bpo::value<bool>()->zero_tokens()->default_value(false), "run workflow merged so far. It implies --batch. Use --no-batch to see the GUI") // //
2928 ("no-IPC", bpo::value<bool>()->zero_tokens()->default_value(false), "disable IPC topology optimization") // //
2929 ("o2-control,o2", bpo::value<std::string>()->default_value(""), "dump O2 Control workflow configuration under the specified name") //
2930 ("resources-monitoring", bpo::value<unsigned short>()->default_value(0), "enable cpu/memory monitoring for provided interval in seconds") //
2931 ("resources-monitoring-file", bpo::value<std::string>()->default_value("performanceMetrics.json"), "file where to dump the metrics") //
2932 ("resources-monitoring-dump-interval", bpo::value<unsigned short>()->default_value(0), "dump monitoring information to disk every provided seconds"); //
2933 // some of the options must be forwarded by default to the device
2934 executorOptions.add(DeviceSpecHelpers::getForwardedDeviceOptions());
2935
2936 gHiddenDeviceOptions.add_options() //
2937 ("id,i", bpo::value<std::string>(), "device id for child spawning") //
2938 ("channel-config", bpo::value<std::vector<std::string>>(), "channel configuration") //
2939 ("control", "control plugin") //
2940 ("log-color", "logging color scheme")("color", "logging color scheme");
2941
2942 bpo::options_description visibleOptions;
2943 visibleOptions.add(executorOptions);
2944
2945 auto physicalWorkflow = workflow;
2946 std::map<std::string, size_t> rankIndex;
2947 // We remove the duplicates because for the moment child get themself twice:
2948 // once from the actual definition in the child, a second time from the
2949 // configuration they get passed by their parents.
2950 // Notice that we do not know in which order we will get the workflows, so
2951 // while we keep the order of DataProcessors we reshuffle them based on
2952 // some hopefully unique hash.
2953 size_t workflowHashA = 0;
2954 std::hash<std::string> hash_fn;
2955
2956 for (auto& dp : workflow) {
2957 workflowHashA += hash_fn(dp.name);
2958 }
2959
2960 for (auto& dp : workflow) {
2961 rankIndex.insert(std::make_pair(dp.name, workflowHashA));
2962 }
2963
2964 std::vector<DataProcessorInfo> dataProcessorInfos;
2965 CommandInfo commandInfo{};
2966
2967 if (isatty(STDIN_FILENO) == false && isInputConfig()) {
2968 std::vector<DataProcessorSpec> importedWorkflow;
2969 bool previousWorked = WorkflowSerializationHelpers::import(std::cin, importedWorkflow, dataProcessorInfos, commandInfo);
2970 if (previousWorked == false) {
2971 exit(1);
2972 }
2973
2974 size_t workflowHashB = 0;
2975 for (auto& dp : importedWorkflow) {
2976 workflowHashB += hash_fn(dp.name);
2977 }
2978
2979 // FIXME: Streamline...
2980 // We remove the duplicates because for the moment child get themself twice:
2981 // once from the actual definition in the child, a second time from the
2982 // configuration they get passed by their parents.
2983 for (auto& dp : importedWorkflow) {
2984 auto found = std::find_if(physicalWorkflow.begin(), physicalWorkflow.end(),
2985 [&name = dp.name](DataProcessorSpec const& spec) { return spec.name == name; });
2986 if (found == physicalWorkflow.end()) {
2987 physicalWorkflow.push_back(dp);
2988 rankIndex.insert(std::make_pair(dp.name, workflowHashB));
2989 }
2990 }
2991 }
2992
2997 for (auto& dp : physicalWorkflow) {
2998 auto isExpendable = [](DataProcessorLabel const& label) { return label.value == "expendable" || label.value == "non-critical"; };
2999 if (std::find_if(dp.labels.begin(), dp.labels.end(), isExpendable) != dp.labels.end()) {
3000 for (auto& output : dp.outputs) {
3001 if (output.lifetime == Lifetime::Timeframe) {
3002 output.lifetime = Lifetime::Sporadic;
3003 }
3004 }
3005 }
3006 }
3007
3009 OverrideServiceSpecs driverServicesOverride = ServiceSpecHelpers::parseOverrides(getenv("DPL_DRIVER_OVERRIDE_SERVICES"));
3011 // We insert the hash for the internal devices.
3012 WorkflowHelpers::injectServiceDevices(physicalWorkflow, configContext);
3013 auto& dec = configContext.services().get<DanglingEdgesContext>();
3014 if (!(dec.requestedAODs.empty() && dec.requestedDYNs.empty() && dec.requestedIDXs.empty() && dec.requestedTIMs.empty())) {
3015 driverServices.push_back(ArrowSupport::arrowBackendSpec());
3016 }
3017 for (auto& service : driverServices) {
3018 if (service.injectTopology == nullptr) {
3019 continue;
3020 }
3021 WorkflowSpecNode node{physicalWorkflow};
3022 service.injectTopology(node, configContext);
3023 }
3024 for (auto& dp : physicalWorkflow) {
3025 if (dp.name.rfind("internal-", 0) == 0) {
3026 rankIndex.insert(std::make_pair(dp.name, hash_fn("internal")));
3027 }
3028 }
3029
3030 // We sort dataprocessors and Inputs / outputs by name, so that the edges are
3031 // always in the same order.
3032 std::stable_sort(physicalWorkflow.begin(), physicalWorkflow.end(), [](DataProcessorSpec const& a, DataProcessorSpec const& b) {
3033 return a.name < b.name;
3034 });
3035
3036 for (auto& dp : physicalWorkflow) {
3037 std::stable_sort(dp.inputs.begin(), dp.inputs.end(),
3038 [](InputSpec const& a, InputSpec const& b) { return DataSpecUtils::describe(a) < DataSpecUtils::describe(b); });
3039 std::stable_sort(dp.outputs.begin(), dp.outputs.end(),
3040 [](OutputSpec const& a, OutputSpec const& b) { return DataSpecUtils::describe(a) < DataSpecUtils::describe(b); });
3041 }
3042
3043 // Create a list of all the edges, so that we can do a topological sort
3044 // before we create the graph.
3045 std::vector<std::pair<int, int>> edges;
3046
3047 if (physicalWorkflow.size() > 1) {
3048 edges = TopologyPolicyHelpers::buildEdges(physicalWorkflow);
3049
3050 auto topoInfos = WorkflowHelpers::topologicalSort(physicalWorkflow.size(), &edges[0].first, &edges[0].second, sizeof(std::pair<int, int>), edges.size());
3051 if (topoInfos.size() != physicalWorkflow.size()) {
3052 // Check missing resilincy of one of the tasks
3053 checkNonResiliency(physicalWorkflow, edges);
3054 throw std::runtime_error("Unable to do topological sort of the resulting workflow. Do you have loops?\n" + debugTopoInfo(physicalWorkflow, topoInfos, edges));
3055 }
3056 // Sort by layer and then by name, to ensure stability.
3057 std::stable_sort(topoInfos.begin(), topoInfos.end(), [&workflow = physicalWorkflow](TopoIndexInfo const& a, TopoIndexInfo const& b) {
3058 auto aRank = std::make_tuple(a.layer, -workflow.at(a.index).outputs.size(), workflow.at(a.index).name);
3059 auto bRank = std::make_tuple(b.layer, -workflow.at(b.index).outputs.size(), workflow.at(b.index).name);
3060 return aRank < bRank;
3061 });
3062 // Reverse index and apply the result
3063 std::vector<int> dataProcessorOrder;
3064 dataProcessorOrder.resize(topoInfos.size());
3065 for (size_t i = 0; i < topoInfos.size(); ++i) {
3066 dataProcessorOrder[topoInfos[i].index] = i;
3067 }
3068 std::vector<int> newLocations;
3069 newLocations.resize(dataProcessorOrder.size());
3070 for (size_t i = 0; i < dataProcessorOrder.size(); ++i) {
3071 newLocations[dataProcessorOrder[i]] = i;
3072 }
3073 apply_permutation(physicalWorkflow, newLocations);
3074 }
3075
3076 // Use the hidden options as veto, all config specs matching a definition
3077 // in the hidden options are skipped in order to avoid duplicate definitions
3078 // in the main parser. Note: all config specs are forwarded to devices
3079 visibleOptions.add(ConfigParamsHelper::prepareOptionDescriptions(physicalWorkflow, currentWorkflowOptions, gHiddenDeviceOptions));
3080
3081 bpo::options_description od;
3082 od.add(visibleOptions);
3083 od.add(gHiddenDeviceOptions);
3084
3085 // FIXME: decide about the policy for handling unrecognized arguments
3086 // command_line_parser with option allow_unregistered() can be used
3087 using namespace bpo::command_line_style;
3088 auto style = (allow_short | short_allow_adjacent | short_allow_next | allow_long | long_allow_adjacent | long_allow_next | allow_sticky | allow_dash_for_short);
3089 bpo::variables_map varmap;
3090 try {
3091 bpo::store(
3092 bpo::command_line_parser(argc, argv)
3093 .options(od)
3094 .style(style)
3095 .run(),
3096 varmap);
3097 } catch (std::exception const& e) {
3098 LOGP(error, "error parsing options of {}: {}", argv[0], e.what());
3099 exit(1);
3100 }
3101 conflicting_options(varmap, "dds", "o2-control");
3102 conflicting_options(varmap, "dds", "dump-workflow");
3103 conflicting_options(varmap, "dds", "run");
3104 conflicting_options(varmap, "dds", "graphviz");
3105 conflicting_options(varmap, "o2-control", "dump-workflow");
3106 conflicting_options(varmap, "o2-control", "run");
3107 conflicting_options(varmap, "o2-control", "graphviz");
3108 conflicting_options(varmap, "run", "dump-workflow");
3109 conflicting_options(varmap, "run", "graphviz");
3110 conflicting_options(varmap, "run", "mermaid");
3111 conflicting_options(varmap, "dump-workflow", "graphviz");
3112 conflicting_options(varmap, "no-batch", "batch");
3113
3114 if (varmap.count("help")) {
3115 printHelp(varmap, executorOptions, physicalWorkflow, currentWorkflowOptions);
3116 exit(0);
3117 }
3121 if (varmap.count("severity")) {
3122 auto logLevel = varmap["severity"].as<std::string>();
3123 if (logLevel == "debug") {
3124 fair::Logger::SetConsoleSeverity(fair::Severity::debug);
3125 } else if (logLevel == "detail") {
3126 fair::Logger::SetConsoleSeverity(fair::Severity::detail);
3127 } else if (logLevel == "info") {
3128 fair::Logger::SetConsoleSeverity(fair::Severity::info);
3129 } else if (logLevel == "warning") {
3130 fair::Logger::SetConsoleSeverity(fair::Severity::warning);
3131 } else if (logLevel == "error") {
3132 fair::Logger::SetConsoleSeverity(fair::Severity::error);
3133 } else if (logLevel == "important") {
3134 fair::Logger::SetConsoleSeverity(fair::Severity::important);
3135 } else if (logLevel == "alarm") {
3136 fair::Logger::SetConsoleSeverity(fair::Severity::alarm);
3137 } else if (logLevel == "critical") {
3138 fair::Logger::SetConsoleSeverity(fair::Severity::critical);
3139 } else if (logLevel == "fatal") {
3140 fair::Logger::SetConsoleSeverity(fair::Severity::fatal);
3141 } else {
3142 LOGP(error, "Invalid log level '{}'", logLevel);
3143 exit(1);
3144 }
3145 }
3146
3147 enableSignposts(varmap["signposts"].as<std::string>());
3148
3149 auto evaluateBatchOption = [&varmap]() -> bool {
3150 if (varmap.count("no-batch") > 0) {
3151 return false;
3152 }
3153 if (varmap.count("batch") == 0) {
3154 // default value
3155 return isatty(fileno(stdout)) == 0;
3156 }
3157 // FIXME: should actually use the last value, but for some reason the
3158 // values are not filled into the vector, even if specifying `-b true`
3159 // need to find out why the boost program options example is not working
3160 // in our case. Might depend on the parser options
3161 // auto value = varmap["batch"].as<std::vector<std::string>>();
3162 return true;
3163 };
3164 DriverInfo driverInfo{
3165 .sendingPolicies = sendingPolicies,
3166 .forwardingPolicies = forwardingPolicies,
3167 .callbacksPolicies = callbacksPolicies};
3168 driverInfo.states.reserve(10);
3169 driverInfo.sigintRequested = false;
3170 driverInfo.sigchldRequested = false;
3171 driverInfo.channelPolicies = channelPolicies;
3172 driverInfo.completionPolicies = completionPolicies;
3173 driverInfo.dispatchPolicies = dispatchPolicies;
3174 driverInfo.resourcePolicies = resourcePolicies;
3175 driverInfo.argc = argc;
3176 driverInfo.argv = argv;
3177 driverInfo.noSHMCleanup = varmap["no-cleanup"].as<bool>();
3178 driverInfo.processingPolicies.termination = varmap["completion-policy"].as<TerminationPolicy>();
3179 driverInfo.processingPolicies.earlyForward = varmap["early-forward-policy"].as<EarlyForwardPolicy>();
3180 driverInfo.mode = varmap["driver-mode"].as<DriverMode>();
3181
3182 auto batch = evaluateBatchOption();
3183 DriverConfig driverConfig{
3184 .batch = batch,
3185 .driverHasGUI = (batch == false) || getenv("DPL_DRIVER_REMOTE_GUI") != nullptr,
3186 };
3187
3188 if (varmap["error-policy"].defaulted() && driverConfig.batch == false) {
3189 driverInfo.processingPolicies.error = TerminationPolicy::WAIT;
3190 } else {
3191 driverInfo.processingPolicies.error = varmap["error-policy"].as<TerminationPolicy>();
3192 }
3193 driverInfo.minFailureLevel = varmap["min-failure-level"].as<LogParsingHelpers::LogLevel>();
3194 driverInfo.startTime = uv_hrtime();
3195 driverInfo.startTimeMsFromEpoch = std::chrono::duration_cast<std::chrono::milliseconds>(
3196 std::chrono::system_clock::now().time_since_epoch())
3197 .count();
3198 driverInfo.timeout = varmap["timeout"].as<uint64_t>();
3199 driverInfo.deployHostname = varmap["hostname"].as<std::string>();
3200 driverInfo.resources = varmap["resources"].as<std::string>();
3201 driverInfo.resourcesMonitoringInterval = varmap["resources-monitoring"].as<unsigned short>();
3202 driverInfo.resourcesMonitoringFilename = varmap["resources-monitoring-file"].as<std::string>();
3203 driverInfo.resourcesMonitoringDumpInterval = varmap["resources-monitoring-dump-interval"].as<unsigned short>();
3204
3205 // FIXME: should use the whole dataProcessorInfos, actually...
3206 driverInfo.processorInfo = dataProcessorInfos;
3207 driverInfo.configContext = &configContext;
3208
3209 DriverControl driverControl;
3210 initialiseDriverControl(varmap, driverInfo, driverControl);
3211
3212 commandInfo.merge(CommandInfo(argc, argv));
3213
3214 std::string frameworkId;
3215 // If the id is set, this means this is a device,
3216 // otherwise this is the driver.
3217 if (varmap.count("id")) {
3218 // The framework id does not want to know anything about DDS template expansion
3219 // so we simply drop it. Notice that the "id" Property is still the same as the
3220 // original --id option.
3221 frameworkId = std::regex_replace(varmap["id"].as<std::string>(), std::regex{"_dds.*"}, "");
3222 driverInfo.uniqueWorkflowId = fmt::format("{}", getppid());
3223 driverInfo.defaultDriverClient = "stdout://";
3224 } else {
3225 driverInfo.uniqueWorkflowId = fmt::format("{}", getpid());
3226 driverInfo.defaultDriverClient = "ws://";
3227 }
3228 return runStateMachine(physicalWorkflow,
3229 currentWorkflow,
3230 dataProcessorInfos,
3231 commandInfo,
3232 driverControl,
3233 driverInfo,
3234 driverConfig,
3236 detectedParams,
3237 varmap,
3238 driverServices,
3239 frameworkId);
3240}
3241
3242void doBoostException(boost::exception&, char const* processName)
3243{
3244 LOGP(error, "error while setting up workflow in {}: {}",
3245 processName, boost::current_exception_diagnostic_information(true));
3246}
3247#pragma GCC diagnostic push
std::vector< std::string > labels
struct uv_timer_s uv_timer_t
struct uv_async_s uv_async_t
struct uv_handle_s uv_handle_t
struct uv_poll_s uv_poll_t
struct uv_loop_s uv_loop_t
std::vector< OutputRoute > routes
std::ostringstream debug
std::unique_ptr< expressions::Node > node
int32_t i
int32_t retVal
void output(const std::map< std::string, ChannelStat > &channels)
Definition rawdump.cxx:197
o2::phos::PHOSEnergySlot es
uint16_t pos
Definition RawData.h:3
uint16_t pid
Definition RawData.h:2
#define O2_SIGNPOST_EVENT_EMIT_ERROR(log, id, name, format,...)
Definition Signpost.h:553
o2_log_handle_t * o2_walk_logs(bool(*callback)(char const *name, void *log, void *context), void *context=nullptr)
#define O2_DECLARE_DYNAMIC_LOG(name)
Definition Signpost.h:489
#define O2_SIGNPOST_ID_FROM_POINTER(name, log, pointer)
Definition Signpost.h:505
#define O2_SIGNPOST_EVENT_EMIT_INFO(log, id, name, format,...)
Definition Signpost.h:531
#define O2_SIGNPOST_END(log, id, name, format,...)
Definition Signpost.h:608
void _o2_log_set_stacktrace(_o2_log_t *log, int stacktrace)
#define O2_SIGNPOST_ID_GENERATE(name, log)
Definition Signpost.h:506
#define O2_SIGNPOST_EVENT_EMIT(log, id, name, format,...)
Definition Signpost.h:522
#define O2_SIGNPOST_START(log, id, name, format,...)
Definition Signpost.h:602
o2::monitoring::Monitoring Monitoring
StringRef key
ServiceRegistryRef services() const
ConfigParamRegistry & options() const
T get(uint32_t y, uint32_t x) const
Definition Array2D.h:199
void registerService(ServiceTypeHash typeHash, void *service, ServiceKind kind, char const *name=nullptr) const
bool match(const std::vector< std::string > &queries, const char *pattern)
Definition dcs-ccdb.cxx:229
GLenum mode
Definition glcorearb.h:266
GLenum src
Definition glcorearb.h:1767
GLint GLsizei count
Definition glcorearb.h:399
GLuint64EXT * result
Definition glcorearb.h:5662
GLuint buffer
Definition glcorearb.h:655
GLsizeiptr size
Definition glcorearb.h:659
GLuint GLuint end
Definition glcorearb.h:469
const GLdouble * v
Definition glcorearb.h:832
GLenum array
Definition glcorearb.h:4274
GLuint index
Definition glcorearb.h:781
GLuint const GLchar * name
Definition glcorearb.h:781
GLboolean GLboolean GLboolean b
Definition glcorearb.h:1233
GLsizei const GLfloat * value
Definition glcorearb.h:819
GLenum GLenum dst
Definition glcorearb.h:1767
GLboolean * data
Definition glcorearb.h:298
GLintptr offset
Definition glcorearb.h:660
GLuint GLsizei const GLchar * label
Definition glcorearb.h:2519
GLsizei GLenum const void * indices
Definition glcorearb.h:400
typedef void(APIENTRYP PFNGLCULLFACEPROC)(GLenum mode)
GLboolean r
Definition glcorearb.h:1233
GLenum GLenum GLsizei len
Definition glcorearb.h:4232
GLenum GLfloat param
Definition glcorearb.h:271
GLboolean GLboolean GLboolean GLboolean a
Definition glcorearb.h:1233
GLuint GLuint stream
Definition glcorearb.h:1806
GLint ref
Definition glcorearb.h:291
GLenum GLuint GLenum GLsizei const GLchar * buf
Definition glcorearb.h:2514
GLuint id
Definition glcorearb.h:650
GLuint counter
Definition glcorearb.h:3987
Defining PrimaryVertex explicitly as messageable.
std::vector< ServiceSpec > ServiceSpecs
RuntimeErrorRef runtime_error(const char *)
EarlyForwardPolicy
When to enable the early forwarding optimization:
std::vector< OverrideServiceSpec > OverrideServiceSpecs
void parse_http_request(char *start, size_t size, HTTPParser *parser)
RuntimeError & error_from_ref(RuntimeErrorRef)
std::vector< DataProcessorSpec > WorkflowSpec
AlgorithmSpec::ProcessCallback adaptStateless(LAMBDA l)
RuntimeErrorRef runtime_error_f(const char *,...)
void dumpDeviceSpec2O2Control(std::string workflowName, std::vector< DeviceSpec > const &specs, std::vector< DeviceExecution > const &executions, CommandInfo const &commandInfo)
Dumps the AliECS compatible workflow and task templates for a DPL workflow.
std::string to_string(gsl::span< T, Size > span)
Definition common.h:52
std::string filename()
void empty(int)
std::vector< std::string > split(const std::string &str, char delimiter=',')
int runStateMachine(DataProcessorSpecs const &workflow, WorkflowInfo const &workflowInfo, DataProcessorInfos const &previousDataProcessorInfos, CommandInfo const &commandInfo, DriverControl &driverControl, DriverInfo &driverInfo, DriverConfig &driverConfig, std::vector< DeviceMetricsInfo > &metricsInfos, std::vector< ConfigParamSpec > const &detectedParams, boost::program_options::variables_map &varmap, std::vector< ServiceSpec > &driverServices, std::string frameworkId)
AlgorithmSpec dryRun(DeviceSpec const &spec)
auto bindGUIPort
void getChildData(int infd, DeviceInfo &outinfo)
void overrideLabels(ConfigContext &ctx, WorkflowSpec &workflow)
void apply_permutation(std::vector< T > &v, std::vector< int > &indices)
int doMain(int argc, char **argv, o2::framework::WorkflowSpec const &workflow, std::vector< ChannelConfigurationPolicy > const &channelPolicies, std::vector< CompletionPolicy > const &completionPolicies, std::vector< DispatchPolicy > const &dispatchPolicies, std::vector< ResourcePolicy > const &resourcePolicies, std::vector< CallbacksPolicy > const &callbacksPolicies, std::vector< SendingPolicy > const &sendingPolicies, std::vector< ConfigParamSpec > const &currentWorkflowOptions, std::vector< ConfigParamSpec > const &detectedParams, o2::framework::ConfigContext &configContext)
void overridePipeline(ConfigContext &ctx, WorkflowSpec &workflow)
void enableSignposts(std::string const &signpostsToEnable)
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)
void killChildren(std::vector< DeviceInfo > &infos, int sig)
void ws_connect_callback(uv_stream_t *server, int status)
A callback for the rest engine.
std::vector< DataProcessingStates > DataProcessingStatesInfos
void createPipes(int *pipes)
void doDPLException(o2::framework::RuntimeErrorRef &ref, char const *)
std::vector< DeviceExecution > DeviceExecutions
void overrideAll(o2::framework::ConfigContext &ctx, std::vector< o2::framework::DataProcessorSpec > &workflow)
std::vector< DeviceMetricsInfo > gDeviceMetricsInfos
void force_exit_callback(uv_timer_s *ctx)
std::string debugTopoInfo(std::vector< DataProcessorSpec > const &specs, std::vector< TopoIndexInfo > const &infos, std::vector< std::pair< int, int > > const &edges)
void overrideCloning(ConfigContext &ctx, WorkflowSpec &workflow)
void doBoostException(boost::exception &e, const char *)
bool processSigChild(DeviceInfos &infos, DeviceSpecs &specs)
void checkNonResiliency(std::vector< DataProcessorSpec > const &specs, std::vector< std::pair< int, int > > const &edges)
std::vector< std::regex > getDumpableMetrics()
void stream_config(uv_work_t *req)
std::vector< DataProcessorSpec > DataProcessorSpecs
void dumpRunSummary(DriverServerContext &context, DriverInfo const &driverInfo, DeviceInfos const &infos, DeviceSpecs const &specs)
void conflicting_options(const boost::program_options::variables_map &vm, const std::string &opt1, const std::string &opt2)
Helper to to detect conflicting options.
void doDefaultWorkflowTerminationHook()
bool checkIfCanExit(std::vector< DeviceInfo > const &infos)
volatile sig_atomic_t sigchld_requested
bool isOutputToPipe()
void handleSignals()
std::vector< DeviceSpec > DeviceSpecs
std::vector< DataProcessorInfo > DataProcessorInfos
volatile sig_atomic_t forceful_exit
bool areAllChildrenGone(std::vector< DeviceInfo > &infos)
Check the state of the children.
std::vector< DeviceControl > DeviceControls
volatile sig_atomic_t double_sigint
void close_websocket(uv_handle_t *handle)
void handleChildrenStdio(DriverServerContext *serverContext, std::string const &forwardedStdin, std::vector< DeviceStdioContext > &childFds, std::vector< uv_poll_t * > &handles)
char * getIdString(int argc, char **argv)
bool isInputConfig()
std::unique_ptr< o2::framework::ServiceRegistry > createRegistry()
void log_callback(uv_poll_t *handle, int status, int events)
void processChildrenOutput(uv_loop_t *loop, DriverInfo &driverInfo, DeviceInfos &infos, DeviceSpecs const &specs, DeviceControls &controls)
volatile sig_atomic_t graceful_exit
void single_step_callback(uv_timer_s *ctx)
Force single stepping of the children.
bpo::options_description gHiddenDeviceOptions("Hidden child options")
void doUnknownException(std::string const &s, char const *)
int doChild(int argc, char **argv, ServiceRegistry &serviceRegistry, DanglingEdgesContext &danglingEdgesContext, RunningWorkflowInfo const &runningWorkflow, RunningDeviceRef ref, DriverConfig const &driverConfig, ProcessingPolicies processingPolicies, std::string const &defaultDriverClient, uv_loop_t *loop)
o2::framework::ConfigContext createConfigContext(std::unique_ptr< ConfigParamRegistry > &workflowOptionsRegistry, o2::framework::ServiceRegistry &configRegistry, std::vector< o2::framework::ConfigParamSpec > &workflowOptions, std::vector< o2::framework::ConfigParamSpec > &extraOptions, int argc, char **argv)
int callMain(int argc, char **argv, int(*mainNoCatch)(int, char **))
void handle_crash(int sig)
void dumpMetricsCallback(uv_timer_t *handle)
void cleanupSHM(std::string const &uniqueWorkflowId)
Helper to invoke shared memory cleanup.
void initialiseDriverControl(bpo::variables_map const &varmap, DriverInfo &driverInfo, DriverControl &control)
Helper function to initialise the controller from the command line options.
void gui_callback(uv_timer_s *ctx)
std::vector< DeviceInfo > DeviceInfos
void printHelp(bpo::variables_map const &varmap, bpo::options_description const &executorOptions, std::vector< DataProcessorSpec > const &physicalWorkflow, std::vector< ConfigParamSpec > const &currentWorkflowOptions)
void spawnRemoteDevice(uv_loop_t *loop, std::string const &, DeviceSpec const &spec, DeviceControl &, DeviceExecution &, DeviceInfos &deviceInfos, DataProcessingStatesInfos &allStates)
void websocket_callback(uv_stream_t *stream, ssize_t nread, const uv_buf_t *buf)
int mainNoCatch(int argc, char **argv)
DriverServerContext * serverContext
std::vector< ConfigParamSpec > options
std::vector< std::string > args
static ServiceSpec arrowBackendSpec()
static void demangled_backtrace_symbols(void **backtrace, unsigned int total, int fd)
static std::vector< ServiceSpec > defaultServices()
static std::vector< ComputingResource > parseResources(std::string const &resourceString)
static std::vector< ConfigParamSpec > discover(ConfigParamRegistry &, int, char **)
static boost::program_options::options_description prepareOptionDescriptions(ContainerType const &workflow, std::vector< ConfigParamSpec > const &currentWorkflowOptions, options_description vetos=options_description(), std::string mode="full")
populate boost program options for a complete workflow
static void populateBoostProgramOptions(options_description &options, const std::vector< ConfigParamSpec > &specs, options_description vetos=options_description())
static void dumpDeviceSpec2DDS(std::ostream &out, DriverMode mode, std::string const &workflowSuffix, std::vector< DataProcessorSpec > const &workflow, std::vector< DataProcessorInfo > const &metadata, std::vector< DeviceSpec > const &specs, std::vector< DeviceExecution > const &executions, CommandInfo const &commandInfo)
static void preExitCallbacks(std::vector< ServiceExitHandle >, ServiceRegistryRef)
Invoke callback to be executed on exit, in reverse order.
A label that can be associated to a DataProcessorSpec.
static std::string describe(InputSpec const &spec)
Plugin interface for DPL GUIs.
Definition DebugGUI.h:30
virtual void * initGUI(char const *windowTitle, ServiceRegistry &registry)=0
virtual std::function< void(void)> getGUIDebugger(std::vector< o2::framework::DeviceInfo > const &infos, std::vector< o2::framework::DeviceSpec > const &devices, std::vector< o2::framework::DataProcessingStates > const &allStates, std::vector< o2::framework::DataProcessorInfo > const &metadata, std::vector< o2::framework::DeviceMetricsInfo > const &metricsInfos, o2::framework::DriverInfo const &driverInfo, std::vector< o2::framework::DeviceControl > &controls, o2::framework::DriverControl &driverControl)=0
static DeploymentMode deploymentMode()
static unsigned int pipelineLength()
get max number of timeslices in the queue
static std::unique_ptr< ConfigParamStore > getConfiguration(ServiceRegistryRef registry, const char *name, std::vector< ConfigParamSpec > const &options)
ProcessingPolicies & processingPolicies
char logFilter[MAX_USER_FILTER_SIZE]
Lines in the log should match this to be displayed.
bool quiet
wether we should be capturing device output.
std::vector< std::string > history
Definition DeviceInfo.h:56
bool active
Whether the device is active (running) or not.
Definition DeviceInfo.h:65
size_t historySize
The size of the history circular buffer.
Definition DeviceInfo.h:45
std::vector< LogParsingHelpers::LogLevel > historyLevel
Definition DeviceInfo.h:59
pid_t pid
The pid of the device associated to this device.
Definition DeviceInfo.h:36
std::string unprinted
An unterminated string which is not ready to be printed yet.
Definition DeviceInfo.h:63
LogParsingHelpers::LogLevel logLevel
The minimum log level for log messages sent/displayed by this device.
Definition DeviceInfo.h:49
LogParsingHelpers::LogLevel maxLogLevel
The maximum log level ever seen by this device.
Definition DeviceInfo.h:47
size_t historyPos
The position inside the history circular buffer of this device.
Definition DeviceInfo.h:43
std::string firstSevereError
Definition DeviceInfo.h:60
static void validate(WorkflowSpec const &workflow)
static boost::program_options::options_description getForwardedDeviceOptions()
define the options which are forwarded to every child
static std::string reworkTimeslicePlaceholder(std::string const &str, DeviceSpec const &spec)
static void prepareArguments(bool defaultQuiet, bool defaultStopped, bool intereactive, unsigned short driverPort, DriverConfig const &driverConfig, std::vector< DataProcessorInfo > const &processorInfos, std::vector< DeviceSpec > const &deviceSpecs, std::vector< DeviceExecution > &deviceExecutions, std::vector< DeviceControl > &deviceControls, std::vector< ConfigParamSpec > const &detectedOptions, std::string const &uniqueWorkflowId)
static void reworkShmSegmentSize(std::vector< DataProcessorInfo > &infos)
static void reworkHomogeneousOption(std::vector< DataProcessorInfo > &infos, char const *name, char const *defaultValue)
static void dataProcessorSpecs2DeviceSpecs(const WorkflowSpec &workflow, std::vector< ChannelConfigurationPolicy > const &channelPolicies, std::vector< CompletionPolicy > const &completionPolicies, std::vector< DispatchPolicy > const &dispatchPolicies, std::vector< ResourcePolicy > const &resourcePolicies, std::vector< CallbacksPolicy > const &callbacksPolicies, std::vector< SendingPolicy > const &sendingPolicy, std::vector< ForwardingPolicy > const &forwardingPolicies, std::vector< DeviceSpec > &devices, ResourceManager &resourceManager, std::string const &uniqueWorkflowId, ConfigContext const &configContext, bool optimizeTopology=false, unsigned short resourcesMonitoringInterval=0, std::string const &channelPrefix="", OverrideServiceSpecs const &overrideServices={})
std::vector< OutputRoute > outputs
Definition DeviceSpec.h:63
std::string id
The id of the device, including time-pipelining and suffix.
Definition DeviceSpec.h:52
static int parseTracingFlags(std::string const &events)
std::vector< DeviceControl > & controls
bool batch
Whether the driver was started in batch mode or not.
std::vector< DriverState > forcedTransitions
std::vector< Callback > callbacks
DriverControlState state
Current state of the state machine player.
std::vector< DeviceSpec > * specs
std::vector< ServiceSummaryHandling > * summaryCallbacks
std::vector< DeviceMetricsInfo > * metrics
std::vector< DeviceInfo > * infos
static std::vector< ForwardingPolicy > createDefaultPolicies()
static void dumpDeviceSpec2Graphviz(std::ostream &, const Devices &specs)
Helper to dump a set of devices as a graphviz file.
static void dumpDataProcessorSpec2Graphviz(std::ostream &, const WorkflowSpec &specs, std::vector< std::pair< int, int > > const &edges={})
Helper to dump a workflow as a graphviz file.
std::function< void(void)> callback
LogLevel
Possible log levels for device log entries.
static LogLevel parseTokenLevel(std::string_view const s)
static void dumpDeviceSpec2Mermaid(std::ostream &, const Devices &specs)
Helper to dump a set of devices as a mermaid file.
Temporary struct to hold a metric after it has been parsed.
static bool dumpMetricsToJSON(std::vector< DeviceMetricsInfo > const &metrics, DeviceMetricsInfo const &driverMetrics, std::vector< DeviceSpec > const &specs, std::vector< std::regex > const &metricsToDump, std::ostream &out) noexcept
static bool isResourcesMonitoringEnabled(unsigned short interval) noexcept
Information about the running workflow.
void declareService(ServiceSpec const &spec, DeviceState &state, fair::mq::ProgOptions &options, ServiceRegistry::Salt salt=ServiceRegistry::globalDeviceSalt())
void * get(ServiceTypeHash typeHash, Salt salt, ServiceKind kind, char const *name=nullptr) const
static OverrideServiceSpecs parseOverrides(char const *overrideString)
static ServiceSpecs filterDisabled(ServiceSpecs originals, OverrideServiceSpecs const &overrides)
static std::function< int64_t(int64_t base, int64_t offset)> defaultCPUTimeConfigurator(uv_loop_t *loop)
static std::function< void(int64_t &base, int64_t &offset)> defaultRealtimeBaseConfigurator(uint64_t offset, uv_loop_t *loop)
Helper struct to keep track of the results of the topological sort.
static auto buildEdges(WorkflowSpec &physicalWorkflow) -> std::vector< std::pair< int, int > >
static void adjustTopology(WorkflowSpec &workflow, ConfigContext const &ctx)
static void injectServiceDevices(WorkflowSpec &workflow, ConfigContext &ctx)
static WorkflowParsingState verifyWorkflow(const WorkflowSpec &workflow)
static std::vector< TopoIndexInfo > topologicalSort(size_t nodeCount, int const *edgeIn, int const *edgeOut, size_t byteStride, size_t edgesCount)
static void dump(std::ostream &o, std::vector< DataProcessorSpec > const &workflow, std::vector< DataProcessorInfo > const &metadata, CommandInfo const &commandInfo)
static bool import(std::istream &s, std::vector< DataProcessorSpec > &workflow, std::vector< DataProcessorInfo > &metadata, CommandInfo &command)
uint16_t de
LOG(info)<< "Compressed in "<< sw.CpuTime()<< " s"
std::vector< ChannelData > channels
uint64_t const void const *restrict const msg
Definition x9.h:153