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