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();
1250 std::ofstream file(context->driver->resourcesMonitoringFilename, std::ios::out);
1252 context->driver->metrics, *(context->specs), performanceMetrics,
1253 file);
1254}
1255
1256void dumpRunSummary(DriverServerContext& context, DriverInfo const& driverInfo, DeviceInfos const& infos, DeviceSpecs const& specs)
1257{
1258 if (infos.empty()) {
1259 return;
1260 }
1261 LOGP(info, "## Processes completed. Run summary:");
1262 LOGP(info, "### Devices started: {}", infos.size());
1263 for (size_t di = 0; di < infos.size(); ++di) {
1264 auto& info = infos[di];
1265 auto& spec = specs[di];
1266 if (info.exitStatus) {
1267 LOGP(error, " - Device {}: pid {} (exit {})", spec.name, info.pid, info.exitStatus);
1268 } else {
1269 LOGP(info, " - Device {}: pid {} (exit {})", spec.name, info.pid, info.exitStatus);
1270 }
1271 if (info.exitStatus != 0 && info.firstSevereError.empty() == false) {
1272 LOGP(info, " - First error: {}", info.firstSevereError);
1273 }
1274 if (info.exitStatus != 0 && info.lastError != info.firstSevereError) {
1275 LOGP(info, " - Last error: {}", info.lastError);
1276 }
1277 }
1278 for (auto& summary : *context.summaryCallbacks) {
1279 summary(ServiceMetricsInfo{*context.metrics, *context.specs, *context.infos, context.driver->metrics, driverInfo});
1280 }
1281}
1282
1283auto bindGUIPort = [](DriverInfo& driverInfo, DriverServerContext& serverContext, std::string frameworkId) {
1284 uv_tcp_init(serverContext.loop, &serverContext.serverHandle);
1285
1286 driverInfo.port = 8080 + (getpid() % 30000);
1287
1288 if (getenv("DPL_REMOTE_GUI_PORT")) {
1289 try {
1290 driverInfo.port = stoi(std::string(getenv("DPL_REMOTE_GUI_PORT")));
1291 } catch (std::invalid_argument) {
1292 LOG(error) << "DPL_REMOTE_GUI_PORT not a valid integer";
1293 } catch (std::out_of_range) {
1294 LOG(error) << "DPL_REMOTE_GUI_PORT out of range (integer)";
1295 }
1296 if (driverInfo.port < 1024 || driverInfo.port > 65535) {
1297 LOG(error) << "DPL_REMOTE_GUI_PORT out of range (1024-65535)";
1298 }
1299 }
1300
1301 int result = 0;
1302 struct sockaddr_in* serverAddr = nullptr;
1303
1304 // Do not offer websocket endpoint for devices
1305 // FIXME: this was blocking david's workflows. For now
1306 // there is no point in any case to have devices
1307 // offering a web based API, but it might make sense in
1308 // the future to inspect them via some web based interface.
1309 if (serverContext.isDriver) {
1310 do {
1311 free(serverAddr);
1312 if (driverInfo.port > 64000) {
1313 throw runtime_error_f("Unable to find a free port for the driver. Last attempt returned %d", result);
1314 }
1315 serverAddr = (sockaddr_in*)malloc(sizeof(sockaddr_in));
1316 uv_ip4_addr("0.0.0.0", driverInfo.port, serverAddr);
1317 auto bindResult = uv_tcp_bind(&serverContext.serverHandle, (const struct sockaddr*)serverAddr, 0);
1318 if (bindResult != 0) {
1319 driverInfo.port++;
1320 usleep(1000);
1321 continue;
1322 }
1323 result = uv_listen((uv_stream_t*)&serverContext.serverHandle, 100, ws_connect_callback);
1324 if (result != 0) {
1325 driverInfo.port++;
1326 usleep(1000);
1327 continue;
1328 }
1329 } while (result != 0);
1330 } else if (getenv("DPL_DEVICE_REMOTE_GUI") && !serverContext.isDriver) {
1331 do {
1332 free(serverAddr);
1333 if (driverInfo.port > 64000) {
1334 throw runtime_error_f("Unable to find a free port for the driver. Last attempt returned %d", result);
1335 }
1336 serverAddr = (sockaddr_in*)malloc(sizeof(sockaddr_in));
1337 uv_ip4_addr("0.0.0.0", driverInfo.port, serverAddr);
1338 auto bindResult = uv_tcp_bind(&serverContext.serverHandle, (const struct sockaddr*)serverAddr, 0);
1339 if (bindResult != 0) {
1340 driverInfo.port++;
1341 usleep(1000);
1342 continue;
1343 }
1344 result = uv_listen((uv_stream_t*)&serverContext.serverHandle, 100, ws_connect_callback);
1345 if (result != 0) {
1346 driverInfo.port++;
1347 usleep(1000);
1348 continue;
1349 }
1350 LOG(info) << "Device GUI port: " << driverInfo.port << " " << frameworkId;
1351 } while (result != 0);
1352 }
1353};
1354
1355// This is the handler for the parent inner loop.
1357 WorkflowInfo const& workflowInfo,
1358 DataProcessorInfos const& previousDataProcessorInfos,
1359 CommandInfo const& commandInfo,
1360 DriverControl& driverControl,
1361 DriverInfo& driverInfo,
1362 DriverConfig& driverConfig,
1363 std::vector<DeviceMetricsInfo>& metricsInfos,
1364 std::vector<ConfigParamSpec> const& detectedParams,
1365 boost::program_options::variables_map& varmap,
1366 std::vector<ServiceSpec>& driverServices,
1367 std::string frameworkId)
1368{
1369 RunningWorkflowInfo runningWorkflow{
1370 .uniqueWorkflowId = driverInfo.uniqueWorkflowId,
1371 .shmSegmentId = (int16_t)atoi(varmap["shm-segment-id"].as<std::string>().c_str())};
1372 DeviceInfos infos;
1373 DeviceControls controls;
1374 DataProcessingStatesInfos allStates;
1375 auto* devicesManager = new DevicesManager{.controls = controls, .infos = infos, .specs = runningWorkflow.devices, .messages = {}};
1376 DeviceExecutions deviceExecutions;
1377 DataProcessorInfos dataProcessorInfos = previousDataProcessorInfos;
1378
1379 std::vector<uv_poll_t*> pollHandles;
1380 std::vector<DeviceStdioContext> childFds;
1381
1382 std::vector<ComputingResource> resources;
1383
1384 if (driverInfo.resources != "") {
1385 resources = ComputingResourceHelpers::parseResources(driverInfo.resources);
1386 } else {
1388 }
1389
1390 auto resourceManager = std::make_unique<SimpleResourceManager>(resources);
1391
1392 DebugGUI* debugGUI = nullptr;
1393 void* window = nullptr;
1394 decltype(debugGUI->getGUIDebugger(infos, runningWorkflow.devices, allStates, dataProcessorInfos, metricsInfos, driverInfo, controls, driverControl)) debugGUICallback;
1395
1396 // An empty frameworkId means this is the driver, so we initialise the GUI
1397 auto initDebugGUI = []() -> DebugGUI* {
1398 uv_lib_t supportLib;
1399 int result = 0;
1400#ifdef __APPLE__
1401 result = uv_dlopen("libO2FrameworkGUISupport.dylib", &supportLib);
1402#else
1403 result = uv_dlopen("libO2FrameworkGUISupport.so", &supportLib);
1404#endif
1405 if (result == -1) {
1406 LOG(error) << uv_dlerror(&supportLib);
1407 return nullptr;
1408 }
1409 DPLPluginHandle* (*dpl_plugin_callback)(DPLPluginHandle*);
1410
1411 result = uv_dlsym(&supportLib, "dpl_plugin_callback", (void**)&dpl_plugin_callback);
1412 if (result == -1) {
1413 LOG(error) << uv_dlerror(&supportLib);
1414 return nullptr;
1415 }
1416 DPLPluginHandle* pluginInstance = dpl_plugin_callback(nullptr);
1417 return PluginManager::getByName<DebugGUI>(pluginInstance, "ImGUIDebugGUI");
1418 };
1419
1420 // We initialise this in the driver, because different drivers might have
1421 // different versions of the service
1422 ServiceRegistry serviceRegistry;
1423
1424 if ((driverConfig.batch == false || getenv("DPL_DRIVER_REMOTE_GUI") != nullptr) && frameworkId.empty()) {
1425 debugGUI = initDebugGUI();
1426 if (debugGUI) {
1427 if (driverConfig.batch == false) {
1428 window = debugGUI->initGUI("O2 Framework debug GUI", serviceRegistry);
1429 } else {
1430 window = debugGUI->initGUI(nullptr, serviceRegistry);
1431 }
1432 }
1433 } else if (getenv("DPL_DEVICE_REMOTE_GUI") && !frameworkId.empty()) {
1434 debugGUI = initDebugGUI();
1435 // We never run the GUI on desktop for devices. All
1436 // you can do is to connect to the remote version.
1437 // this is done to avoid having a proliferation of
1438 // GUIs popping up when the variable is set globally.
1439 // FIXME: maybe this is not what we want, but it should
1440 // be ok for now.
1441 if (debugGUI) {
1442 window = debugGUI->initGUI(nullptr, serviceRegistry);
1443 }
1444 }
1445 if (driverConfig.batch == false && window == nullptr && frameworkId.empty()) {
1446 LOG(warn) << "Could not create GUI. Switching to batch mode. Do you have GLFW on your system?";
1447 driverConfig.batch = true;
1448 if (varmap["error-policy"].defaulted()) {
1449 driverInfo.processingPolicies.error = TerminationPolicy::QUIT;
1450 }
1451 }
1452 bool guiQuitRequested = false;
1453 bool hasError = false;
1454
1455 // FIXME: I should really have some way of exiting the
1456 // parent..
1457 DriverState current;
1458 DriverState previous;
1459
1460 uv_loop_t* loop = uv_loop_new();
1461
1462 uv_timer_t* gui_timer = nullptr;
1463
1464 if (!driverConfig.batch) {
1465 gui_timer = (uv_timer_t*)malloc(sizeof(uv_timer_t));
1466 uv_timer_init(loop, gui_timer);
1467 }
1468
1469 std::vector<ServiceMetricHandling> metricProcessingCallbacks;
1470 std::vector<ServiceSummaryHandling> summaryCallbacks;
1471 std::vector<ServicePreSchedule> preScheduleCallbacks;
1472 std::vector<ServicePostSchedule> postScheduleCallbacks;
1473 std::vector<ServiceDriverInit> driverInitCallbacks;
1474 for (auto& service : driverServices) {
1475 if (service.driverStartup == nullptr) {
1476 continue;
1477 }
1478 service.driverStartup(serviceRegistry, DeviceConfig{varmap});
1479 }
1480
1481 ServiceRegistryRef ref{serviceRegistry};
1482 ref.registerService(ServiceRegistryHelpers::handleForService<DevicesManager>(devicesManager));
1483
1484 bool guiTimerExpired = false;
1485 GuiCallbackContext guiContext;
1486 guiContext.plugin = debugGUI;
1487 guiContext.frameLast = uv_hrtime();
1488 guiContext.frameLatency = &driverInfo.frameLatency;
1489 guiContext.frameCost = &driverInfo.frameCost;
1490 guiContext.guiQuitRequested = &guiQuitRequested;
1491 guiContext.guiTimerExpired = &guiTimerExpired;
1492
1493 // This is to make sure we can process metrics, commands, configuration
1494 // changes coming from websocket (or even via any standard uv_stream_t, I guess).
1495 DriverServerContext serverContext{
1496 .registry = {serviceRegistry},
1497 .loop = loop,
1498 .controls = &controls,
1499 .infos = &infos,
1500 .states = &allStates,
1501 .specs = &runningWorkflow.devices,
1502 .metrics = &metricsInfos,
1503 .metricProcessingCallbacks = &metricProcessingCallbacks,
1504 .summaryCallbacks = &summaryCallbacks,
1505 .driver = &driverInfo,
1506 .gui = &guiContext,
1507 .isDriver = frameworkId.empty(),
1508 };
1509
1510 serverContext.serverHandle.data = &serverContext;
1511
1512 uv_timer_t force_step_timer;
1513 uv_timer_init(loop, &force_step_timer);
1514 uv_timer_t force_exit_timer;
1515 uv_timer_init(loop, &force_exit_timer);
1516
1517 bool guiDeployedOnce = false;
1518 bool once = false;
1519
1520 uv_timer_t metricDumpTimer;
1521 metricDumpTimer.data = &serverContext;
1522 bool allChildrenGone = false;
1523 guiContext.allChildrenGone = &allChildrenGone;
1524 O2_SIGNPOST_ID_FROM_POINTER(sid, driver, loop);
1525 O2_SIGNPOST_START(driver, sid, "driver", "Starting driver loop");
1526
1527 // Async callback to process the output of the children, if needed.
1528 serverContext.asyncLogProcessing = (uv_async_t*)malloc(sizeof(uv_async_t));
1529 serverContext.asyncLogProcessing->data = &serverContext;
1530 uv_async_init(loop, serverContext.asyncLogProcessing, [](uv_async_t* handle) {
1531 auto* context = (DriverServerContext*)handle->data;
1532 processChildrenOutput(context->loop, *context->driver, *context->infos, *context->specs, *context->controls);
1533 });
1534
1535 while (true) {
1536 // If control forced some transition on us, we push it to the queue.
1537 if (driverControl.forcedTransitions.empty() == false) {
1538 for (auto transition : driverControl.forcedTransitions) {
1539 driverInfo.states.push_back(transition);
1540 }
1541 driverControl.forcedTransitions.resize(0);
1542 }
1543 // In case a timeout was requested, we check if we are running
1544 // for more than the timeout duration and exit in case that's the case.
1545 {
1546 auto currentTime = uv_hrtime();
1547 uint64_t diff = (currentTime - driverInfo.startTime) / 1000000000LL;
1548 if ((graceful_exit == false) && (driverInfo.timeout > 0) && (diff > driverInfo.timeout)) {
1549 LOG(info) << "Timout ellapsed. Requesting to quit.";
1550 graceful_exit = true;
1551 }
1552 }
1553 // Move to exit loop if sigint was sent we execute this only once.
1554 if (graceful_exit == true && driverInfo.sigintRequested == false) {
1555 driverInfo.sigintRequested = true;
1556 driverInfo.states.resize(0);
1557 driverInfo.states.push_back(DriverState::QUIT_REQUESTED);
1558 }
1559 // If one of the children dies and sigint was not requested
1560 // we should decide what to do.
1561 if (sigchld_requested == true && driverInfo.sigchldRequested == false) {
1562 driverInfo.sigchldRequested = true;
1563 driverInfo.states.push_back(DriverState::HANDLE_CHILDREN);
1564 }
1565 if (driverInfo.states.empty() == false) {
1566 previous = current;
1567 current = driverInfo.states.back();
1568 } else {
1569 current = DriverState::UNKNOWN;
1570 }
1571 driverInfo.states.pop_back();
1572 switch (current) {
1573 case DriverState::BIND_GUI_PORT:
1574 bindGUIPort(driverInfo, serverContext, frameworkId);
1575 break;
1576 case DriverState::INIT:
1577 LOGP(info, "Initialising O2 Data Processing Layer. Driver PID: {}.", getpid());
1578 LOGP(info, "Driver listening on port: {}", driverInfo.port);
1579
1580 // Install signal handler for quitting children.
1581 driverInfo.sa_handle_child.sa_handler = &handle_sigchld;
1582 sigemptyset(&driverInfo.sa_handle_child.sa_mask);
1583 driverInfo.sa_handle_child.sa_flags = SA_RESTART | SA_NOCLDSTOP;
1584 if (sigaction(SIGCHLD, &driverInfo.sa_handle_child, nullptr) == -1) {
1585 perror(nullptr);
1586 exit(1);
1587 }
1588
1591 if (driverInfo.noSHMCleanup) {
1592 LOGP(warning, "Not cleaning up shared memory.");
1593 } else {
1594 cleanupSHM(driverInfo.uniqueWorkflowId);
1595 }
1600 for (auto& callback : driverInitCallbacks) {
1601 callback(serviceRegistry, {varmap});
1602 }
1603 driverInfo.states.push_back(DriverState::RUNNING);
1604 // driverInfo.states.push_back(DriverState::REDEPLOY_GUI);
1605 LOG(info) << "O2 Data Processing Layer initialised. We brake for nobody.";
1606#ifdef NDEBUG
1607 LOGF(info, "Optimised build. O2DEBUG / LOG(debug) / LOGF(debug) / assert statement will not be shown.");
1608#endif
1609 break;
1610 case DriverState::IMPORT_CURRENT_WORKFLOW:
1611 // This state is needed to fill the metadata structure
1612 // which contains how to run the current workflow
1613 dataProcessorInfos = previousDataProcessorInfos;
1614 for (auto const& device : runningWorkflow.devices) {
1615 auto exists = std::find_if(dataProcessorInfos.begin(),
1616 dataProcessorInfos.end(),
1617 [id = device.id](DataProcessorInfo const& info) -> bool { return info.name == id; });
1618 if (exists != dataProcessorInfos.end()) {
1619 continue;
1620 }
1621 std::vector<std::string> channels;
1622 for (auto channel : device.inputChannels) {
1623 channels.push_back(channel.name);
1624 }
1625 for (auto channel : device.outputChannels) {
1626 channels.push_back(channel.name);
1627 }
1628 dataProcessorInfos.push_back(
1630 device.id,
1631 workflowInfo.executable,
1632 workflowInfo.args,
1633 workflowInfo.options,
1634 channels});
1635 }
1636 break;
1637 case DriverState::MATERIALISE_WORKFLOW:
1638 try {
1639 auto workflowState = WorkflowHelpers::verifyWorkflow(workflow);
1640 if (driverConfig.batch == true && varmap["dds"].as<std::string>().empty() && !varmap["dump-workflow"].as<bool>() && workflowState == WorkflowParsingState::Empty) {
1641 LOGP(error, "Empty workflow provided while running in batch mode.");
1642 return 1;
1643 }
1644
1647 auto altered_workflow = workflow;
1648
1649 auto confNameFromParam = [](std::string const& paramName) {
1650 std::regex name_regex(R"(^control:([\w-]+)\/(\w+))");
1651 auto match = std::sregex_token_iterator(paramName.begin(), paramName.end(), name_regex, 0);
1652 if (match == std::sregex_token_iterator()) {
1653 throw runtime_error_f("Malformed process control spec: %s", paramName.c_str());
1654 }
1655 std::string task = std::sregex_token_iterator(paramName.begin(), paramName.end(), name_regex, 1)->str();
1656 std::string conf = std::sregex_token_iterator(paramName.begin(), paramName.end(), name_regex, 2)->str();
1657 return std::pair{task, conf};
1658 };
1659 bool altered = false;
1660 for (auto& device : altered_workflow) {
1661 // ignore internal devices
1662 if (device.name.find("internal") != std::string::npos) {
1663 continue;
1664 }
1665 // ignore devices with no inputs
1666 if (device.inputs.empty() == true) {
1667 continue;
1668 }
1669 // ignore devices with no metadata in inputs
1670 auto hasMetadata = std::any_of(device.inputs.begin(), device.inputs.end(), [](InputSpec const& spec) {
1671 return spec.metadata.empty() == false;
1672 });
1673 if (!hasMetadata) {
1674 continue;
1675 }
1676 // ignore devices with no control options
1677 auto hasControls = std::any_of(device.inputs.begin(), device.inputs.end(), [](InputSpec const& spec) {
1678 return std::any_of(spec.metadata.begin(), spec.metadata.end(), [](ConfigParamSpec const& param) {
1679 return param.type == VariantType::Bool && param.name.find("control:") != std::string::npos;
1680 });
1681 });
1682 if (!hasControls) {
1683 continue;
1684 }
1685
1686 LOGP(debug, "Adjusting device {}", device.name.c_str());
1687
1688 auto configStore = DeviceConfigurationHelpers::getConfiguration(serviceRegistry, device.name.c_str(), device.options);
1689 if (configStore != nullptr) {
1690 auto reg = std::make_unique<ConfigParamRegistry>(std::move(configStore));
1691 for (auto& input : device.inputs) {
1692 for (auto& param : input.metadata) {
1693 if (param.type == VariantType::Bool && param.name.find("control:") != std::string::npos) {
1694 if (param.name != "control:default" && param.name != "control:spawn" && param.name != "control:build" && param.name != "control:define") {
1695 auto confName = confNameFromParam(param.name).second;
1696 param.defaultValue = reg->get<bool>(confName.c_str());
1697 }
1698 }
1699 }
1700 }
1701 }
1703 LOGP(debug, "Original inputs: ");
1704 for (auto& input : device.inputs) {
1705 LOGP(debug, "-> {}", input.binding);
1706 }
1707 auto end = device.inputs.end();
1708 auto new_end = std::remove_if(device.inputs.begin(), device.inputs.end(), [](InputSpec& input) {
1709 auto requested = false;
1710 auto hasControls = false;
1711 for (auto& param : input.metadata) {
1712 if (param.type != VariantType::Bool) {
1713 continue;
1714 }
1715 if (param.name.find("control:") != std::string::npos) {
1716 hasControls = true;
1717 if (param.defaultValue.get<bool>() == true) {
1718 requested = true;
1719 break;
1720 }
1721 }
1722 }
1723 if (hasControls) {
1724 return !requested;
1725 }
1726 return false;
1727 });
1728 device.inputs.erase(new_end, end);
1729 LOGP(debug, "Adjusted inputs: ");
1730 for (auto& input : device.inputs) {
1731 LOGP(debug, "-> {}", input.binding);
1732 }
1733 altered = true;
1734 }
1735 WorkflowHelpers::adjustTopology(altered_workflow, *driverInfo.configContext);
1736 if (altered) {
1737 WorkflowSpecNode node{altered_workflow};
1738 for (auto& service : driverServices) {
1739 if (service.adjustTopology == nullptr) {
1740 continue;
1741 }
1742 service.adjustTopology(node, *driverInfo.configContext);
1743 }
1744 }
1745
1746 // These allow services customization via an environment variable
1747 OverrideServiceSpecs overrides = ServiceSpecHelpers::parseOverrides(getenv("DPL_OVERRIDE_SERVICES"));
1748 DeviceSpecHelpers::validate(altered_workflow);
1750 driverInfo.channelPolicies,
1751 driverInfo.completionPolicies,
1752 driverInfo.dispatchPolicies,
1753 driverInfo.resourcePolicies,
1754 driverInfo.callbacksPolicies,
1755 driverInfo.sendingPolicies,
1756 driverInfo.forwardingPolicies,
1757 runningWorkflow.devices,
1758 *resourceManager,
1759 driverInfo.uniqueWorkflowId,
1760 *driverInfo.configContext,
1761 !varmap["no-IPC"].as<bool>(),
1762 driverInfo.resourcesMonitoringInterval,
1763 varmap["channel-prefix"].as<std::string>(),
1764 overrides);
1765 metricProcessingCallbacks.clear();
1766 std::vector<std::string> matchingServices;
1767
1768 // FIXME: once moving to C++20, we can use templated lambdas.
1769 matchingServices.clear();
1770 for (auto& device : runningWorkflow.devices) {
1771 for (auto& service : device.services) {
1772 // If a service with the same name is already registered, skip it
1773 if (std::find(matchingServices.begin(), matchingServices.end(), service.name) != matchingServices.end()) {
1774 continue;
1775 }
1776 if (service.metricHandling) {
1777 metricProcessingCallbacks.push_back(service.metricHandling);
1778 matchingServices.push_back(service.name);
1779 }
1780 }
1781 }
1782
1783 // FIXME: once moving to C++20, we can use templated lambdas.
1784 matchingServices.clear();
1785 for (auto& device : runningWorkflow.devices) {
1786 for (auto& service : device.services) {
1787 // If a service with the same name is already registered, skip it
1788 if (std::find(matchingServices.begin(), matchingServices.end(), service.name) != matchingServices.end()) {
1789 continue;
1790 }
1791 if (service.summaryHandling) {
1792 summaryCallbacks.push_back(service.summaryHandling);
1793 matchingServices.push_back(service.name);
1794 }
1795 }
1796 }
1797
1798 preScheduleCallbacks.clear();
1799 matchingServices.clear();
1800 for (auto& device : runningWorkflow.devices) {
1801 for (auto& service : device.services) {
1802 // If a service with the same name is already registered, skip it
1803 if (std::find(matchingServices.begin(), matchingServices.end(), service.name) != matchingServices.end()) {
1804 continue;
1805 }
1806 if (service.preSchedule) {
1807 preScheduleCallbacks.push_back(service.preSchedule);
1808 }
1809 }
1810 }
1811 postScheduleCallbacks.clear();
1812 matchingServices.clear();
1813 for (auto& device : runningWorkflow.devices) {
1814 for (auto& service : device.services) {
1815 // If a service with the same name is already registered, skip it
1816 if (std::find(matchingServices.begin(), matchingServices.end(), service.name) != matchingServices.end()) {
1817 continue;
1818 }
1819 if (service.postSchedule) {
1820 postScheduleCallbacks.push_back(service.postSchedule);
1821 }
1822 }
1823 }
1824 driverInitCallbacks.clear();
1825 matchingServices.clear();
1826 for (auto& device : runningWorkflow.devices) {
1827 for (auto& service : device.services) {
1828 // If a service with the same name is already registered, skip it
1829 if (std::find(matchingServices.begin(), matchingServices.end(), service.name) != matchingServices.end()) {
1830 continue;
1831 }
1832 if (service.driverInit) {
1833 driverInitCallbacks.push_back(service.driverInit);
1834 }
1835 }
1836 }
1837
1838 // This should expand nodes so that we can build a consistent DAG.
1839
1840 // This updates the options in the runningWorkflow.devices
1841 for (auto& device : runningWorkflow.devices) {
1842 // ignore internal devices
1843 if (device.name.find("internal") != std::string::npos) {
1844 continue;
1845 }
1846 auto configStore = DeviceConfigurationHelpers::getConfiguration(serviceRegistry, device.name.c_str(), device.options);
1847 if (configStore != nullptr) {
1848 auto reg = std::make_unique<ConfigParamRegistry>(std::move(configStore));
1849 for (auto& option : device.options) {
1850 const char* name = option.name.c_str();
1851 switch (option.type) {
1852 case VariantType::Int:
1853 option.defaultValue = reg->get<int32_t>(name);
1854 break;
1855 case VariantType::Int8:
1856 option.defaultValue = reg->get<int8_t>(name);
1857 break;
1858 case VariantType::Int16:
1859 option.defaultValue = reg->get<int16_t>(name);
1860 break;
1861 case VariantType::UInt8:
1862 option.defaultValue = reg->get<uint8_t>(name);
1863 break;
1864 case VariantType::UInt16:
1865 option.defaultValue = reg->get<uint16_t>(name);
1866 break;
1867 case VariantType::UInt32:
1868 option.defaultValue = reg->get<uint32_t>(name);
1869 break;
1870 case VariantType::UInt64:
1871 option.defaultValue = reg->get<uint64_t>(name);
1872 break;
1873 case VariantType::Int64:
1874 option.defaultValue = reg->get<int64_t>(name);
1875 break;
1876 case VariantType::Float:
1877 option.defaultValue = reg->get<float>(name);
1878 break;
1879 case VariantType::Double:
1880 option.defaultValue = reg->get<double>(name);
1881 break;
1882 case VariantType::String:
1883 option.defaultValue = reg->get<std::string>(name);
1884 break;
1885 case VariantType::Bool:
1886 option.defaultValue = reg->get<bool>(name);
1887 break;
1888 case VariantType::ArrayInt:
1889 option.defaultValue = reg->get<std::vector<int>>(name);
1890 break;
1891 case VariantType::ArrayFloat:
1892 option.defaultValue = reg->get<std::vector<float>>(name);
1893 break;
1894 case VariantType::ArrayDouble:
1895 option.defaultValue = reg->get<std::vector<double>>(name);
1896 break;
1897 case VariantType::ArrayString:
1898 option.defaultValue = reg->get<std::vector<std::string>>(name);
1899 break;
1900 case VariantType::Array2DInt:
1901 option.defaultValue = reg->get<Array2D<int>>(name);
1902 break;
1903 case VariantType::Array2DFloat:
1904 option.defaultValue = reg->get<Array2D<float>>(name);
1905 break;
1906 case VariantType::Array2DDouble:
1907 option.defaultValue = reg->get<Array2D<double>>(name);
1908 break;
1909 case VariantType::LabeledArrayInt:
1910 option.defaultValue = reg->get<LabeledArray<int>>(name);
1911 break;
1912 case VariantType::LabeledArrayFloat:
1913 option.defaultValue = reg->get<LabeledArray<float>>(name);
1914 break;
1915 case VariantType::LabeledArrayDouble:
1916 option.defaultValue = reg->get<LabeledArray<double>>(name);
1917 break;
1918 case VariantType::LabeledArrayString:
1919 option.defaultValue = reg->get<LabeledArray<std::string>>(name);
1920 break;
1921 default:
1922 break;
1923 }
1924 }
1925 }
1926 }
1927 } catch (std::runtime_error& e) {
1928 LOGP(error, "invalid workflow in {}: {}", driverInfo.argv[0], e.what());
1929 return 1;
1932#ifdef DPL_ENABLE_BACKTRACE
1933 BacktraceHelpers::demangled_backtrace_symbols(err.backtrace, err.maxBacktrace, STDERR_FILENO);
1934#endif
1935 LOGP(error, "invalid workflow in {}: {}", driverInfo.argv[0], err.what);
1936 return 1;
1937 } catch (...) {
1938 LOGP(error, "invalid workflow in {}: Unknown error while materialising workflow", driverInfo.argv[0]);
1939 return 1;
1940 }
1941 break;
1942 case DriverState::DO_CHILD:
1943 // We do not start the process if by default we are stopped.
1944 if (driverControl.defaultStopped) {
1945 kill(getpid(), SIGSTOP);
1946 }
1947 for (size_t di = 0; di < runningWorkflow.devices.size(); di++) {
1949 if (runningWorkflow.devices[di].id == frameworkId) {
1950 return doChild(driverInfo.argc, driverInfo.argv,
1951 serviceRegistry,
1952 runningWorkflow, ref,
1953 driverConfig,
1954 driverInfo.processingPolicies,
1955 driverInfo.defaultDriverClient,
1956 loop);
1957 }
1958 }
1959 {
1960 std::ostringstream ss;
1961 for (auto& processor : workflow) {
1962 ss << " - " << processor.name << "\n";
1963 }
1964 for (auto& spec : runningWorkflow.devices) {
1965 ss << " - " << spec.name << "(" << spec.id << ")"
1966 << "\n";
1967 }
1968 driverInfo.lastError = fmt::format(
1969 "Unable to find component with id {}."
1970 " Available options:\n{}",
1971 frameworkId, ss.str());
1972 driverInfo.states.push_back(DriverState::QUIT_REQUESTED);
1973 }
1974 break;
1975 case DriverState::REDEPLOY_GUI:
1976 // The callback for the GUI needs to be recalculated every time
1977 // the deployed configuration changes, e.g. a new device
1978 // has been added to the topology.
1979 // We need to recreate the GUI callback every time we reschedule
1980 // because getGUIDebugger actually recreates the GUI state.
1981 // Notice also that we need the actual gui_timer only for the
1982 // case the GUI runs in interactive mode, however we deploy the
1983 // GUI in both interactive and non-interactive mode, if the
1984 // DPL_DRIVER_REMOTE_GUI environment variable is set.
1985 if (!driverConfig.batch || getenv("DPL_DRIVER_REMOTE_GUI")) {
1986 if (gui_timer) {
1987 uv_timer_stop(gui_timer);
1988 }
1989
1990 auto callback = debugGUI->getGUIDebugger(infos, runningWorkflow.devices, allStates, dataProcessorInfos, metricsInfos, driverInfo, controls, driverControl);
1991 guiContext.callback = [&serviceRegistry, &driverServices, &debugGUI, &infos, &runningWorkflow, &dataProcessorInfos, &metricsInfos, &driverInfo, &controls, &driverControl, callback]() {
1992 callback();
1993 for (auto& service : driverServices) {
1994 if (service.postRenderGUI) {
1995 service.postRenderGUI(serviceRegistry);
1996 }
1997 }
1998 };
1999 guiContext.window = window;
2000
2001 if (gui_timer) {
2002 gui_timer->data = &guiContext;
2003 uv_timer_start(gui_timer, gui_callback, 0, 20);
2004 }
2005 guiDeployedOnce = true;
2006 }
2007 break;
2008 case DriverState::MERGE_CONFIGS: {
2009 try {
2010 controls.resize(runningWorkflow.devices.size());
2013 if (varmap.count("dpl-tracing-flags")) {
2014 for (auto& control : controls) {
2015 auto tracingFlags = DeviceStateHelpers::parseTracingFlags(varmap["dpl-tracing-flags"].as<std::string>());
2016 control.tracingFlags = tracingFlags;
2017 }
2018 }
2019 deviceExecutions.resize(runningWorkflow.devices.size());
2020
2021 // Options which should be uniform across all
2022 // the subworkflow invokations.
2023 const auto uniformOptions = {
2024 "--aod-file",
2025 "--aod-memory-rate-limit",
2026 "--aod-writer-json",
2027 "--aod-writer-ntfmerge",
2028 "--aod-writer-resdir",
2029 "--aod-writer-resfile",
2030 "--aod-writer-resmode",
2031 "--aod-writer-maxfilesize",
2032 "--aod-writer-keep",
2033 "--aod-max-io-rate",
2034 "--aod-parent-access-level",
2035 "--aod-parent-base-path-replacement",
2036 "--driver-client-backend",
2037 "--fairmq-ipc-prefix",
2038 "--readers",
2039 "--resources-monitoring",
2040 "--resources-monitoring-file",
2041 "--resources-monitoring-dump-interval",
2042 "--time-limit",
2043 };
2044
2045 for (auto& option : uniformOptions) {
2046 DeviceSpecHelpers::reworkHomogeneousOption(dataProcessorInfos, option, nullptr);
2047 }
2048
2049 DeviceSpecHelpers::reworkShmSegmentSize(dataProcessorInfos);
2051 driverControl.defaultStopped,
2052 driverInfo.processingPolicies.termination == TerminationPolicy::WAIT,
2053 driverInfo.port,
2054 driverConfig,
2055 dataProcessorInfos,
2056 runningWorkflow.devices,
2057 deviceExecutions,
2058 controls,
2059 detectedParams,
2060 driverInfo.uniqueWorkflowId);
2063 LOGP(error, "unable to merge configurations in {}: {}", driverInfo.argv[0], err.what);
2064#ifdef DPL_ENABLE_BACKTRACE
2065 std::cerr << "\nStacktrace follows:\n\n";
2066 BacktraceHelpers::demangled_backtrace_symbols(err.backtrace, err.maxBacktrace, STDERR_FILENO);
2067#endif
2068 return 1;
2069 }
2070 } break;
2071 case DriverState::SCHEDULE: {
2072 // FIXME: for the moment modifying the topology means we rebuild completely
2073 // all the devices and we restart them. This is also what DDS does at
2074 // a larger scale. In principle one could try to do a delta and only
2075 // restart the data processors which need to be restarted.
2076 LOG(info) << "Redeployment of configuration asked.";
2077 std::ostringstream forwardedStdin;
2078 WorkflowSerializationHelpers::dump(forwardedStdin, workflow, dataProcessorInfos, commandInfo);
2079 infos.reserve(runningWorkflow.devices.size());
2080
2081 // This is guaranteed to be a single CPU.
2082 unsigned parentCPU = -1;
2083 unsigned parentNode = -1;
2084#if defined(__linux__) && __has_include(<sched.h>)
2085 parentCPU = sched_getcpu();
2086#elif __has_include(<linux/getcpu.h>)
2087 getcpu(&parentCPU, &parentNode, nullptr);
2088#elif __has_include(<cpuid.h>) && (__x86_64__ || __i386__)
2089 // FIXME: this is a last resort as it is apparently buggy
2090 // on some Intel CPUs.
2091 GETCPU(parentCPU);
2092#endif
2093 for (auto& callback : preScheduleCallbacks) {
2094 callback(serviceRegistry, {varmap});
2095 }
2096 childFds.resize(runningWorkflow.devices.size());
2097 for (int di = 0; di < (int)runningWorkflow.devices.size(); ++di) {
2098 auto& context = childFds[di];
2099 createPipes(context.childstdin);
2100 createPipes(context.childstdout);
2101 if (driverInfo.mode == DriverMode::EMBEDDED || runningWorkflow.devices[di].resource.hostname != driverInfo.deployHostname) {
2102 spawnRemoteDevice(loop, forwardedStdin.str(),
2103 runningWorkflow.devices[di], controls[di], deviceExecutions[di], infos, allStates);
2104 } else {
2105 DeviceRef ref{di};
2106 spawnDevice(loop,
2107 ref,
2108 runningWorkflow.devices, driverInfo,
2109 controls, deviceExecutions, infos,
2110 allStates,
2111 serviceRegistry, varmap,
2112 childFds, parentCPU, parentNode);
2113 }
2114 }
2115 handleSignals();
2116 handleChildrenStdio(&serverContext, forwardedStdin.str(), childFds, pollHandles);
2117 for (auto& callback : postScheduleCallbacks) {
2118 callback(serviceRegistry, {varmap});
2119 }
2120 assert(infos.empty() == false);
2121
2122 // In case resource monitoring is requested, we dump metrics to disk
2123 // every 3 minutes.
2124 if (driverInfo.resourcesMonitoringDumpInterval && ResourcesMonitoringHelper::isResourcesMonitoringEnabled(driverInfo.resourcesMonitoringInterval)) {
2125 uv_timer_init(loop, &metricDumpTimer);
2126 uv_timer_start(&metricDumpTimer, dumpMetricsCallback,
2127 driverInfo.resourcesMonitoringDumpInterval * 1000,
2128 driverInfo.resourcesMonitoringDumpInterval * 1000);
2129 }
2131 for (const auto& processorInfo : dataProcessorInfos) {
2132 const auto& cmdLineArgs = processorInfo.cmdLineArgs;
2133 if (std::find(cmdLineArgs.begin(), cmdLineArgs.end(), "--severity") != cmdLineArgs.end()) {
2134 for (size_t counter = 0; const auto& spec : runningWorkflow.devices) {
2135 if (spec.name.compare(processorInfo.name) == 0) {
2136 auto& info = infos[counter];
2137 const auto logLevelIt = std::find(cmdLineArgs.begin(), cmdLineArgs.end(), "--severity") + 1;
2138 if ((*logLevelIt).compare("debug") == 0) {
2139 info.logLevel = LogParsingHelpers::LogLevel::Debug;
2140 } else if ((*logLevelIt).compare("detail") == 0) {
2141 info.logLevel = LogParsingHelpers::LogLevel::Debug;
2142 } else if ((*logLevelIt).compare("info") == 0) {
2143 info.logLevel = LogParsingHelpers::LogLevel::Info;
2144 } else if ((*logLevelIt).compare("warning") == 0) {
2145 info.logLevel = LogParsingHelpers::LogLevel::Warning;
2146 } else if ((*logLevelIt).compare("error") == 0) {
2147 info.logLevel = LogParsingHelpers::LogLevel::Error;
2148 } else if ((*logLevelIt).compare("important") == 0) {
2149 info.logLevel = LogParsingHelpers::LogLevel::Info;
2150 } else if ((*logLevelIt).compare("alarm") == 0) {
2151 info.logLevel = LogParsingHelpers::LogLevel::Alarm;
2152 } else if ((*logLevelIt).compare("critical") == 0) {
2153 info.logLevel = LogParsingHelpers::LogLevel::Critical;
2154 } else if ((*logLevelIt).compare("fatal") == 0) {
2155 info.logLevel = LogParsingHelpers::LogLevel::Fatal;
2156 }
2157 break;
2158 }
2159 ++counter;
2160 }
2161 }
2162 }
2163 LOG(info) << "Redeployment of configuration done.";
2164 } break;
2165 case DriverState::RUNNING:
2166 // Run any pending libUV event loop, block if
2167 // any, so that we do not consume CPU time when the driver is
2168 // idle.
2169 devicesManager->flush();
2170 // We print the event loop for the gui only once every
2171 // 6000 iterations (i.e. ~2 minutes). To avoid spamming, while still
2172 // being able to see the event loop in case of a deadlock / systematic failure.
2173 if (guiTimerExpired == false) {
2174 O2_SIGNPOST_EVENT_EMIT(driver, sid, "mainloop", "Entering event loop with %{public}s", once ? "UV_RUN_ONCE" : "UV_RUN_NOWAIT");
2175 }
2176 uv_run(loop, once ? UV_RUN_ONCE : UV_RUN_NOWAIT);
2177 once = true;
2178 // Calculate what we should do next and eventually
2179 // show the GUI
2180 if (guiQuitRequested ||
2181 (driverInfo.processingPolicies.termination == TerminationPolicy::QUIT && (checkIfCanExit(infos) == true))) {
2182 // Something requested to quit. This can be a user
2183 // interaction with the GUI or (if --completion-policy=quit)
2184 // it could mean that the workflow does not have anything else to do.
2185 // Let's update the GUI one more time and then EXIT.
2186 LOG(info) << "Quitting";
2187 driverInfo.states.push_back(DriverState::QUIT_REQUESTED);
2188 } else if (infos.size() != runningWorkflow.devices.size()) {
2189 // If the number of devices is different from
2190 // the DeviceInfos it means the speicification
2191 // does not match what is running, so we need to do
2192 // further scheduling.
2193 driverInfo.states.push_back(DriverState::RUNNING);
2194 driverInfo.states.push_back(DriverState::REDEPLOY_GUI);
2195 driverInfo.states.push_back(DriverState::SCHEDULE);
2196 driverInfo.states.push_back(DriverState::MERGE_CONFIGS);
2197 } else if (runningWorkflow.devices.empty() && driverConfig.batch == true) {
2198 LOG(info) << "No device resulting from the workflow. Quitting.";
2199 // If there are no deviceSpecs, we exit.
2200 driverInfo.states.push_back(DriverState::EXIT);
2201 } else if (runningWorkflow.devices.empty() && driverConfig.batch == false && !guiDeployedOnce) {
2202 // In case of an empty workflow, we need to deploy the GUI at least once.
2203 driverInfo.states.push_back(DriverState::RUNNING);
2204 driverInfo.states.push_back(DriverState::REDEPLOY_GUI);
2205 } else {
2206 driverInfo.states.push_back(DriverState::RUNNING);
2207 }
2208 break;
2209 case DriverState::QUIT_REQUESTED: {
2210 std::time_t result = std::time(nullptr);
2211 char buffer[32];
2212 std::strncpy(buffer, std::ctime(&result), 26);
2213 O2_SIGNPOST_EVENT_EMIT_INFO(driver, sid, "mainloop", "Quit requested at %{public}s", buffer);
2214 guiQuitRequested = true;
2215 // We send SIGCONT to make sure stopped children are resumed
2216 killChildren(infos, SIGCONT);
2217 // We send SIGTERM to make sure we do the STOP transition in FairMQ
2218 killChildren(infos, SIGTERM);
2219 // We have a timer to send SIGUSR1 to make sure we advance all devices
2220 // in a timely manner.
2221 force_step_timer.data = &infos;
2222 uv_timer_start(&force_step_timer, single_step_callback, 0, 300);
2223 driverInfo.states.push_back(DriverState::HANDLE_CHILDREN);
2224 break;
2225 }
2226 case DriverState::HANDLE_CHILDREN: {
2227 // Run any pending libUV event loop, block if
2228 // any, so that we do not consume CPU time when the driver is
2229 // idle.
2230 uv_run(loop, once ? UV_RUN_ONCE : UV_RUN_NOWAIT);
2231 once = true;
2232 // I allow queueing of more sigchld only when
2233 // I process the previous call
2234 if (forceful_exit == true) {
2235 static bool forcefulExitMessage = true;
2236 if (forcefulExitMessage) {
2237 LOG(info) << "Forceful exit requested.";
2238 forcefulExitMessage = false;
2239 }
2240 killChildren(infos, SIGCONT);
2241 killChildren(infos, SIGKILL);
2242 }
2243 sigchld_requested = false;
2244 driverInfo.sigchldRequested = false;
2245 processChildrenOutput(loop, driverInfo, infos, runningWorkflow.devices, controls);
2246 hasError = processSigChild(infos, runningWorkflow.devices);
2247 allChildrenGone = areAllChildrenGone(infos);
2248 bool canExit = checkIfCanExit(infos);
2249 bool supposedToQuit = (guiQuitRequested || canExit || graceful_exit);
2250
2251 if (allChildrenGone && (supposedToQuit || driverInfo.processingPolicies.termination == TerminationPolicy::QUIT)) {
2252 // We move to the exit, regardless of where we were
2253 driverInfo.states.resize(0);
2254 driverInfo.states.push_back(DriverState::EXIT);
2255 } else if (hasError && driverInfo.processingPolicies.error == TerminationPolicy::QUIT && !supposedToQuit) {
2256 graceful_exit = 1;
2257 force_exit_timer.data = &infos;
2258 static bool forceful_timer_started = false;
2259 if (forceful_timer_started == false) {
2260 forceful_timer_started = true;
2261 uv_timer_start(&force_exit_timer, force_exit_callback, 15000, 3000);
2262 }
2263 driverInfo.states.push_back(DriverState::QUIT_REQUESTED);
2264 } else if (allChildrenGone == false && supposedToQuit) {
2265 driverInfo.states.push_back(DriverState::HANDLE_CHILDREN);
2266 } else {
2267 }
2268 } break;
2269 case DriverState::EXIT: {
2270 if (ResourcesMonitoringHelper::isResourcesMonitoringEnabled(driverInfo.resourcesMonitoringInterval)) {
2271 if (driverInfo.resourcesMonitoringDumpInterval) {
2272 uv_timer_stop(&metricDumpTimer);
2273 }
2274 LOGP(info, "Dumping performance metrics to {}.json file", driverInfo.resourcesMonitoringFilename);
2275 dumpMetricsCallback(&metricDumpTimer);
2276 }
2277 dumpRunSummary(serverContext, driverInfo, infos, runningWorkflow.devices);
2278 // This is a clean exit. Before we do so, if required,
2279 // we dump the configuration of all the devices so that
2280 // we can reuse it. Notice we do not dump anything if
2281 // the workflow was not really run.
2282 // NOTE: is this really what we want? should we run
2283 // SCHEDULE and dump the full configuration as well?
2284 if (infos.empty()) {
2285 return 0;
2286 }
2287 boost::property_tree::ptree finalConfig;
2288 assert(infos.size() == runningWorkflow.devices.size());
2289 for (size_t di = 0; di < infos.size(); ++di) {
2290 auto& info = infos[di];
2291 auto& spec = runningWorkflow.devices[di];
2292 finalConfig.put_child(spec.name, info.currentConfig);
2293 }
2294 LOG(info) << "Dumping used configuration in dpl-config.json";
2295
2296 std::ofstream outDPLConfigFile("dpl-config.json", std::ios::out);
2297 if (outDPLConfigFile.is_open()) {
2298 boost::property_tree::write_json(outDPLConfigFile, finalConfig);
2299 } else {
2300 LOGP(warning, "Could not write out final configuration file. Read only run folder?");
2301 }
2302 if (driverInfo.noSHMCleanup) {
2303 LOGP(warning, "Not cleaning up shared memory.");
2304 } else {
2305 cleanupSHM(driverInfo.uniqueWorkflowId);
2306 }
2307 return calculateExitCode(driverInfo, runningWorkflow.devices, infos);
2308 }
2309 case DriverState::PERFORM_CALLBACKS:
2310 for (auto& callback : driverControl.callbacks) {
2311 callback(workflow, runningWorkflow.devices, deviceExecutions, dataProcessorInfos, commandInfo);
2312 }
2313 driverControl.callbacks.clear();
2314 break;
2315 default:
2316 LOG(error) << "Driver transitioned in an unknown state("
2317 << "current: " << (int)current
2318 << ", previous: " << (int)previous
2319 << "). Shutting down.";
2320 driverInfo.states.push_back(DriverState::QUIT_REQUESTED);
2321 }
2322 }
2323 O2_SIGNPOST_END(driver, sid, "driver", "End driver loop");
2324}
2325
2326// Print help
2327void printHelp(bpo::variables_map const& varmap,
2328 bpo::options_description const& executorOptions,
2329 std::vector<DataProcessorSpec> const& physicalWorkflow,
2330 std::vector<ConfigParamSpec> const& currentWorkflowOptions)
2331{
2332 auto mode = varmap["help"].as<std::string>();
2333 bpo::options_description helpOptions;
2334 if (mode == "full" || mode == "short" || mode == "executor") {
2335 helpOptions.add(executorOptions);
2336 }
2337 // this time no veto is applied, so all the options are added for printout
2338 if (mode == "executor") {
2339 // nothing more
2340 } else if (mode == "workflow") {
2341 // executor options and workflow options, skip the actual workflow
2342 o2::framework::WorkflowSpec emptyWorkflow;
2343 helpOptions.add(ConfigParamsHelper::prepareOptionDescriptions(emptyWorkflow, currentWorkflowOptions));
2344 } else if (mode == "full" || mode == "short") {
2345 helpOptions.add(ConfigParamsHelper::prepareOptionDescriptions(physicalWorkflow, currentWorkflowOptions,
2346 bpo::options_description(),
2347 mode));
2348 } else {
2349 helpOptions.add(ConfigParamsHelper::prepareOptionDescriptions(physicalWorkflow, {},
2350 bpo::options_description(),
2351 mode));
2352 }
2353 if (helpOptions.options().size() == 0) {
2354 // the specified argument is invalid, add at leat the executor options
2355 mode += " is an invalid argument, please use correct argument for";
2356 helpOptions.add(executorOptions);
2357 }
2358 std::cout << "ALICE O2 DPL workflow driver" //
2359 << " (" << mode << " help)" << std::endl //
2360 << helpOptions << std::endl; //
2361}
2362
2363// Helper to find out if stdout is actually attached to a pipe.
2365{
2366 struct stat s;
2367 fstat(STDOUT_FILENO, &s);
2368 return ((s.st_mode & S_IFIFO) != 0);
2369}
2370
2372{
2373 struct stat s;
2374 int r = fstat(STDIN_FILENO, &s);
2375 // If stdin cannot be statted, we assume the shell is some sort of
2376 // non-interactive container thing
2377 if (r < 0) {
2378 return false;
2379 }
2380 // If stdin is a pipe or a file, we try to fetch configuration from there
2381 return ((s.st_mode & S_IFIFO) != 0 || (s.st_mode & S_IFREG) != 0);
2382}
2383
2385{
2386 struct CloningSpec {
2387 std::string templateMatcher;
2388 std::string cloneName;
2389 };
2390 auto s = ctx.options().get<std::string>("clone");
2391 std::vector<CloningSpec> specs;
2392 std::string delimiter = ",";
2393
2394 while (s.empty() == false) {
2395 auto newPos = s.find(delimiter);
2396 auto token = s.substr(0, newPos);
2397 auto split = token.find(":");
2398 if (split == std::string::npos) {
2399 throw std::runtime_error("bad clone definition. Syntax <template-processor>:<clone-name>");
2400 }
2401 auto key = token.substr(0, split);
2402 token.erase(0, split + 1);
2403 size_t error;
2404 std::string value = "";
2405 try {
2406 auto numValue = std::stoll(token, &error, 10);
2407 if (token[error] != '\0') {
2408 throw std::runtime_error("bad name for clone:" + token);
2409 }
2410 value = key + "_c" + std::to_string(numValue);
2411 } catch (std::invalid_argument& e) {
2412 value = token;
2413 }
2414 specs.push_back({key, value});
2415 s.erase(0, newPos + (newPos == std::string::npos ? 0 : 1));
2416 }
2417 if (s.empty() == false && specs.empty() == true) {
2418 throw std::runtime_error("bad pipeline definition. Syntax <processor>:<pipeline>");
2419 }
2420
2421 std::vector<DataProcessorSpec> extraSpecs;
2422 for (auto& spec : specs) {
2423 for (auto& processor : workflow) {
2424 if (processor.name == spec.templateMatcher) {
2425 auto clone = processor;
2426 clone.name = spec.cloneName;
2427 extraSpecs.push_back(clone);
2428 }
2429 }
2430 }
2431 workflow.insert(workflow.end(), extraSpecs.begin(), extraSpecs.end());
2432}
2433
2435{
2436 struct PipelineSpec {
2437 std::string matcher;
2438 int64_t pipeline;
2439 };
2440 auto s = ctx.options().get<std::string>("pipeline");
2441 std::vector<PipelineSpec> specs;
2442 std::string delimiter = ",";
2443
2444 while (s.empty() == false) {
2445 auto newPos = s.find(delimiter);
2446 auto token = s.substr(0, newPos);
2447 auto split = token.find(":");
2448 if (split == std::string::npos) {
2449 throw std::runtime_error("bad pipeline definition. Syntax <processor>:<pipeline>");
2450 }
2451 auto key = token.substr(0, split);
2452 token.erase(0, split + 1);
2453 size_t error;
2454 auto value = std::stoll(token, &error, 10);
2455 if (token[error] != '\0') {
2456 throw std::runtime_error("Bad pipeline definition. Expecting integer");
2457 }
2458 specs.push_back({key, value});
2459 s.erase(0, newPos + (newPos == std::string::npos ? 0 : 1));
2460 }
2461 if (s.empty() == false && specs.empty() == true) {
2462 throw std::runtime_error("bad pipeline definition. Syntax <processor>:<pipeline>");
2463 }
2464
2465 for (auto& spec : specs) {
2466 for (auto& processor : workflow) {
2467 if (processor.name == spec.matcher) {
2468 processor.maxInputTimeslices = spec.pipeline;
2469 }
2470 }
2471 }
2472}
2473
2475{
2476 struct LabelsSpec {
2477 std::string_view matcher;
2478 std::vector<std::string> labels;
2479 };
2480 std::vector<LabelsSpec> specs;
2481
2482 auto labelsString = ctx.options().get<std::string>("labels");
2483 if (labelsString.empty()) {
2484 return;
2485 }
2486 std::string_view sv{labelsString};
2487
2488 size_t specStart = 0;
2489 size_t specEnd = 0;
2490 constexpr char specDelim = ',';
2491 constexpr char labelDelim = ':';
2492 do {
2493 specEnd = sv.find(specDelim, specStart);
2494 auto token = sv.substr(specStart, specEnd == std::string_view::npos ? std::string_view::npos : specEnd - specStart);
2495 if (token.empty()) {
2496 throw std::runtime_error("bad labels definition. Syntax <processor>:<label>[:<label>][,<processor>:<label>[:<label>]");
2497 }
2498
2499 size_t labelDelimPos = token.find(labelDelim);
2500 if (labelDelimPos == 0 || labelDelimPos == std::string_view::npos) {
2501 throw std::runtime_error("bad labels definition. Syntax <processor>:<label>[:<label>][,<processor>:<label>[:<label>]");
2502 }
2503 LabelsSpec spec{.matcher = token.substr(0, labelDelimPos), .labels = {}};
2504
2505 size_t labelEnd = labelDelimPos + 1;
2506 do {
2507 size_t labelStart = labelDelimPos + 1;
2508 labelEnd = token.find(labelDelim, labelStart);
2509 auto label = labelEnd == std::string_view::npos ? token.substr(labelStart) : token.substr(labelStart, labelEnd - labelStart);
2510 if (label.empty()) {
2511 throw std::runtime_error("bad labels definition. Syntax <processor>:<label>[:<label>][,<processor>:<label>[:<label>]");
2512 }
2513 spec.labels.emplace_back(label);
2514 labelDelimPos = labelEnd;
2515 } while (labelEnd != std::string_view::npos);
2516
2517 specs.push_back(spec);
2518 specStart = specEnd + 1;
2519 } while (specEnd != std::string_view::npos);
2520
2521 if (labelsString.empty() == false && specs.empty() == true) {
2522 throw std::runtime_error("bad labels definition. Syntax <processor>:<label>[:<label>][,<processor>:<label>[:<label>]");
2523 }
2524
2525 for (auto& spec : specs) {
2526 for (auto& processor : workflow) {
2527 if (processor.name == spec.matcher) {
2528 for (const auto& label : spec.labels) {
2529 if (std::find_if(processor.labels.begin(), processor.labels.end(),
2530 [label](const auto& procLabel) { return procLabel.value == label; }) == processor.labels.end()) {
2531 processor.labels.push_back({label});
2532 }
2533 }
2534 }
2535 }
2536 }
2537}
2538
2540void initialiseDriverControl(bpo::variables_map const& varmap,
2541 DriverInfo& driverInfo,
2542 DriverControl& control)
2543{
2544 // Control is initialised outside the main loop because
2545 // command line options are really affecting control.
2546 control.defaultQuiet = varmap["quiet"].as<bool>();
2547 control.defaultStopped = varmap["stop"].as<bool>();
2548
2549 if (varmap["single-step"].as<bool>()) {
2550 control.state = DriverControlState::STEP;
2551 } else {
2552 control.state = DriverControlState::PLAY;
2553 }
2554
2555 if (varmap["graphviz"].as<bool>()) {
2556 // Dump a graphviz representation of what I will do.
2557 control.callbacks = {[](WorkflowSpec const&,
2558 DeviceSpecs const& specs,
2559 DeviceExecutions const&,
2561 CommandInfo const&) {
2563 }};
2564 control.forcedTransitions = {
2565 DriverState::EXIT, //
2566 DriverState::PERFORM_CALLBACKS, //
2567 DriverState::MERGE_CONFIGS, //
2568 DriverState::IMPORT_CURRENT_WORKFLOW, //
2569 DriverState::MATERIALISE_WORKFLOW //
2570 };
2571 } else if (!varmap["dds"].as<std::string>().empty()) {
2572 // Dump a DDS representation of what I will do.
2573 // Notice that compared to DDS we need to schedule things,
2574 // because DDS needs to be able to have actual Executions in
2575 // order to provide a correct configuration.
2576 control.callbacks = {[filename = varmap["dds"].as<std::string>(),
2577 workflowSuffix = varmap["dds-workflow-suffix"],
2578 driverMode = driverInfo.mode](WorkflowSpec const& workflow,
2579 DeviceSpecs const& specs,
2580 DeviceExecutions const& executions,
2581 DataProcessorInfos& dataProcessorInfos,
2582 CommandInfo const& commandInfo) {
2583 if (filename == "-") {
2584 DDSConfigHelpers::dumpDeviceSpec2DDS(std::cout, driverMode, workflowSuffix.as<std::string>(), workflow, dataProcessorInfos, specs, executions, commandInfo);
2585 } else {
2586 std::ofstream out(filename);
2587 DDSConfigHelpers::dumpDeviceSpec2DDS(out, driverMode, workflowSuffix.as<std::string>(), workflow, dataProcessorInfos, specs, executions, commandInfo);
2588 }
2589 }};
2590 control.forcedTransitions = {
2591 DriverState::EXIT, //
2592 DriverState::PERFORM_CALLBACKS, //
2593 DriverState::MERGE_CONFIGS, //
2594 DriverState::IMPORT_CURRENT_WORKFLOW, //
2595 DriverState::MATERIALISE_WORKFLOW //
2596 };
2597 } else if (!varmap["o2-control"].as<std::string>().empty() or !varmap["mermaid"].as<std::string>().empty()) {
2598 // Dump the workflow in o2-control and/or mermaid format
2599 control.callbacks = {[filename = varmap["mermaid"].as<std::string>(),
2600 workflowName = varmap["o2-control"].as<std::string>()](WorkflowSpec const&,
2601 DeviceSpecs const& specs,
2602 DeviceExecutions const& executions,
2604 CommandInfo const& commandInfo) {
2605 if (!workflowName.empty()) {
2606 dumpDeviceSpec2O2Control(workflowName, specs, executions, commandInfo);
2607 }
2608 if (!filename.empty()) {
2609 if (filename == "-") {
2611 } else {
2612 std::ofstream output(filename);
2614 }
2615 }
2616 }};
2617 control.forcedTransitions = {
2618 DriverState::EXIT, //
2619 DriverState::PERFORM_CALLBACKS, //
2620 DriverState::MERGE_CONFIGS, //
2621 DriverState::IMPORT_CURRENT_WORKFLOW, //
2622 DriverState::MATERIALISE_WORKFLOW //
2623 };
2624
2625 } else if (varmap.count("id")) {
2626 // Add our own stacktrace dumping
2627 if (getenv("O2_NO_CATCHALL_EXCEPTIONS") != nullptr && strcmp(getenv("O2_NO_CATCHALL_EXCEPTIONS"), "0") != 0) {
2628 LOGP(info, "Not instrumenting crash signals because O2_NO_CATCHALL_EXCEPTIONS is set");
2629 gEnv->SetValue("Root.Stacktrace", "no");
2630 gSystem->ResetSignal(kSigSegmentationViolation, kTRUE);
2631 rlimit limit;
2632 if (getrlimit(RLIMIT_CORE, &limit) == 0) {
2633 LOGP(info, "Core limit: {} {}", limit.rlim_cur, limit.rlim_max);
2634 }
2635 }
2636 if (varmap["stacktrace-on-signal"].as<std::string>() == "simple" && (getenv("O2_NO_CATCHALL_EXCEPTIONS") == nullptr || strcmp(getenv("O2_NO_CATCHALL_EXCEPTIONS"), "0") == 0)) {
2637 LOGP(info, "Instrumenting crash signals");
2638 signal(SIGSEGV, handle_crash);
2639 signal(SIGABRT, handle_crash);
2640 signal(SIGBUS, handle_crash);
2641 signal(SIGILL, handle_crash);
2642 signal(SIGFPE, handle_crash);
2643 }
2644 // FIXME: for the time being each child needs to recalculate the workflow,
2645 // so that it can understand what it needs to do. This is obviously
2646 // a bad idea. In the future we should have the client be pushed
2647 // it's own configuration by the driver.
2648 control.forcedTransitions = {
2649 DriverState::DO_CHILD, //
2650 DriverState::BIND_GUI_PORT, //
2651 DriverState::MERGE_CONFIGS, //
2652 DriverState::IMPORT_CURRENT_WORKFLOW, //
2653 DriverState::MATERIALISE_WORKFLOW //
2654 };
2655 } else if ((varmap["dump-workflow"].as<bool>() == true) || (varmap["run"].as<bool>() == false && varmap.count("id") == 0 && isOutputToPipe())) {
2656 control.callbacks = {[filename = varmap["dump-workflow-file"].as<std::string>()](WorkflowSpec const& workflow,
2657 DeviceSpecs const&,
2658 DeviceExecutions const&,
2659 DataProcessorInfos& dataProcessorInfos,
2660 CommandInfo const& commandInfo) {
2661 if (filename == "-") {
2662 WorkflowSerializationHelpers::dump(std::cout, workflow, dataProcessorInfos, commandInfo);
2663 // FIXME: this is to avoid trailing garbage..
2664 exit(0);
2665 } else {
2666 std::ofstream output(filename);
2667 WorkflowSerializationHelpers::dump(output, workflow, dataProcessorInfos, commandInfo);
2668 }
2669 }};
2670 control.forcedTransitions = {
2671 DriverState::EXIT, //
2672 DriverState::PERFORM_CALLBACKS, //
2673 DriverState::MERGE_CONFIGS, //
2674 DriverState::IMPORT_CURRENT_WORKFLOW, //
2675 DriverState::MATERIALISE_WORKFLOW //
2676 };
2677 } else {
2678 // By default we simply start the main loop of the driver.
2679 control.forcedTransitions = {
2680 DriverState::INIT, //
2681 DriverState::BIND_GUI_PORT, //
2682 DriverState::IMPORT_CURRENT_WORKFLOW, //
2683 DriverState::MATERIALISE_WORKFLOW //
2684 };
2685 }
2686}
2687
2689void conflicting_options(const boost::program_options::variables_map& vm,
2690 const std::string& opt1, const std::string& opt2)
2691{
2692 if (vm.count(opt1) && !vm[opt1].defaulted() &&
2693 vm.count(opt2) && !vm[opt2].defaulted()) {
2694 throw std::logic_error(std::string("Conflicting options '") +
2695 opt1 + "' and '" + opt2 + "'.");
2696 }
2697}
2698
2699template <typename T>
2701 std::vector<T>& v,
2702 std::vector<int>& indices)
2703{
2704 using std::swap; // to permit Koenig lookup
2705 for (int i = 0; i < (int)indices.size(); i++) {
2706 auto current = i;
2707 while (i != indices[current]) {
2708 auto next = indices[current];
2709 swap(v[current], v[next]);
2710 indices[current] = current;
2711 current = next;
2712 }
2713 indices[current] = current;
2714 }
2715}
2716
2717// Check if the workflow is resiliant to failures
2718void checkNonResiliency(std::vector<DataProcessorSpec> const& specs,
2719 std::vector<std::pair<int, int>> const& edges)
2720{
2721 auto checkExpendable = [](DataProcessorLabel const& label) {
2722 return label.value == "expendable";
2723 };
2724 auto checkResilient = [](DataProcessorLabel const& label) {
2725 return label.value == "resilient" || label.value == "expendable";
2726 };
2727
2728 for (auto& edge : edges) {
2729 auto& src = specs[edge.first];
2730 auto& dst = specs[edge.second];
2731 if (std::none_of(src.labels.begin(), src.labels.end(), checkExpendable)) {
2732 continue;
2733 }
2734 if (std::any_of(dst.labels.begin(), dst.labels.end(), checkResilient)) {
2735 continue;
2736 }
2737 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.");
2738 }
2739}
2740
2741std::string debugTopoInfo(std::vector<DataProcessorSpec> const& specs,
2742 std::vector<TopoIndexInfo> const& infos,
2743 std::vector<std::pair<int, int>> const& edges)
2744{
2745 std::ostringstream out;
2746
2747 out << "\nTopological info:\n";
2748 for (auto& ti : infos) {
2749 out << specs[ti.index].name << " (index: " << ti.index << ", layer: " << ti.layer << ")\n";
2750 out << " Inputs:\n";
2751 for (auto& ii : specs[ti.index].inputs) {
2752 out << " - " << DataSpecUtils::describe(ii) << "\n";
2753 }
2754 out << "\n Outputs:\n";
2755 for (auto& ii : specs[ti.index].outputs) {
2756 out << " - " << DataSpecUtils::describe(ii) << "\n";
2757 }
2758 }
2759 out << "\nEdges values:\n";
2760 for (auto& e : edges) {
2761 out << specs[e.second].name << " depends on " << specs[e.first].name << "\n";
2762 }
2763 for (auto& d : specs) {
2764 out << "- " << d.name << std::endl;
2765 }
2767 return out.str();
2768}
2769
2770void enableSignposts(std::string const& signpostsToEnable)
2771{
2772 static pid_t pid = getpid();
2773 if (signpostsToEnable.empty() == true) {
2774 auto printAllSignposts = [](char const* name, void* l, void* context) {
2775 auto* log = (_o2_log_t*)l;
2776 LOGP(detail, "Signpost stream {} disabled. Enable it with o2-log -p {} -a {}", name, pid, (void*)&log->stacktrace);
2777 return true;
2778 };
2779 o2_walk_logs(printAllSignposts, nullptr);
2780 return;
2781 }
2782 auto matchingLogEnabler = [](char const* name, void* l, void* context) {
2783 auto* log = (_o2_log_t*)l;
2784 auto* selectedName = (char const*)context;
2785 std::string prefix = "ch.cern.aliceo2.";
2786 auto* last = strchr(selectedName, ':');
2787 int maxDepth = 1;
2788 if (last) {
2789 char* err;
2790 maxDepth = strtol(last + 1, &err, 10);
2791 if (*(last + 1) == '\0' || *err != '\0') {
2792 maxDepth = 1;
2793 }
2794 }
2795
2796 auto fullName = prefix + std::string{selectedName, last ? last - selectedName : strlen(selectedName)};
2797 if (fullName == name) {
2798 LOGP(info, "Enabling signposts for stream \"{}\" with depth {}.", fullName, maxDepth);
2799 _o2_log_set_stacktrace(log, maxDepth);
2800 return false;
2801 } else {
2802 LOGP(info, "Signpost stream \"{}\" disabled. Enable it with o2-log -p {} -a {}", name, pid, (void*)&log->stacktrace);
2803 }
2804 return true;
2805 };
2806 // Split signpostsToEnable by comma using strtok_r
2807 char* saveptr;
2808 char* src = const_cast<char*>(signpostsToEnable.data());
2809 auto* token = strtok_r(src, ",", &saveptr);
2810 while (token) {
2811 o2_walk_logs(matchingLogEnabler, token);
2812 token = strtok_r(nullptr, ",", &saveptr);
2813 }
2814}
2815
2816void overrideAll(o2::framework::ConfigContext& ctx, std::vector<o2::framework::DataProcessorSpec>& workflow)
2817{
2818 overrideCloning(ctx, workflow);
2819 overridePipeline(ctx, workflow);
2820 overrideLabels(ctx, workflow);
2821}
2822
2823o2::framework::ConfigContext createConfigContext(std::unique_ptr<ConfigParamRegistry>& workflowOptionsRegistry,
2824 o2::framework::ServiceRegistry& configRegistry,
2825 std::vector<o2::framework::ConfigParamSpec>& workflowOptions,
2826 std::vector<o2::framework::ConfigParamSpec>& extraOptions, int argc, char** argv)
2827{
2828 std::vector<std::unique_ptr<o2::framework::ParamRetriever>> retrievers;
2829 std::unique_ptr<o2::framework::ParamRetriever> retriever{new o2::framework::BoostOptionsRetriever(true, argc, argv)};
2830 retrievers.emplace_back(std::move(retriever));
2831 auto workflowOptionsStore = std::make_unique<o2::framework::ConfigParamStore>(workflowOptions, std::move(retrievers));
2832 workflowOptionsStore->preload();
2833 workflowOptionsStore->activate();
2834 workflowOptionsRegistry = std::make_unique<ConfigParamRegistry>(std::move(workflowOptionsStore));
2835 extraOptions = o2::framework::ConfigParamDiscovery::discover(*workflowOptionsRegistry, argc, argv);
2836 for (auto& extra : extraOptions) {
2837 workflowOptions.push_back(extra);
2838 }
2839
2840 return o2::framework::ConfigContext(*workflowOptionsRegistry, o2::framework::ServiceRegistryRef{configRegistry}, argc, argv);
2841}
2842
2843std::unique_ptr<o2::framework::ServiceRegistry> createRegistry()
2844{
2845 return std::make_unique<o2::framework::ServiceRegistry>();
2846}
2847
2848// This is a toy executor for the workflow spec
2849// What it needs to do is:
2850//
2851// - Print the properties of each DataProcessorSpec
2852// - Fork one process per DataProcessorSpec
2853// - Parent -> wait for all the children to complete (eventually
2854// killing them all on ctrl-c).
2855// - Child, pick the data-processor ID and start a O2DataProcessorDevice for
2856// each DataProcessorSpec
2857int doMain(int argc, char** argv, o2::framework::WorkflowSpec const& workflow,
2858 std::vector<ChannelConfigurationPolicy> const& channelPolicies,
2859 std::vector<CompletionPolicy> const& completionPolicies,
2860 std::vector<DispatchPolicy> const& dispatchPolicies,
2861 std::vector<ResourcePolicy> const& resourcePolicies,
2862 std::vector<CallbacksPolicy> const& callbacksPolicies,
2863 std::vector<SendingPolicy> const& sendingPolicies,
2864 std::vector<ConfigParamSpec> const& currentWorkflowOptions,
2865 std::vector<ConfigParamSpec> const& detectedParams,
2866 o2::framework::ConfigContext& configContext)
2867{
2868 // Peek very early in the driver options and look for
2869 // signposts, so the we can enable it without going through the whole dance
2870 if (getenv("DPL_DRIVER_SIGNPOSTS")) {
2871 enableSignposts(getenv("DPL_DRIVER_SIGNPOSTS"));
2872 }
2873
2874 std::vector<std::string> currentArgs;
2875 std::vector<PluginInfo> plugins;
2876 std::vector<ForwardingPolicy> forwardingPolicies = ForwardingPolicy::createDefaultPolicies();
2877
2878 for (int ai = 1; ai < argc; ++ai) {
2879 currentArgs.emplace_back(argv[ai]);
2880 }
2881
2882 WorkflowInfo currentWorkflow{
2883 argv[0],
2884 currentArgs,
2885 currentWorkflowOptions};
2886
2887 ProcessingPolicies processingPolicies;
2888 enum LogParsingHelpers::LogLevel minFailureLevel;
2889 bpo::options_description executorOptions("Executor options");
2890 const char* helpDescription = "print help: short, full, executor, or processor name";
2891 enum DriverMode driverMode;
2892 executorOptions.add_options() //
2893 ("help,h", bpo::value<std::string>()->implicit_value("short"), helpDescription) // //
2894 ("quiet,q", bpo::value<bool>()->zero_tokens()->default_value(false), "quiet operation") // //
2895 ("stop,s", bpo::value<bool>()->zero_tokens()->default_value(false), "stop before device start") // //
2896 ("single-step", bpo::value<bool>()->zero_tokens()->default_value(false), "start in single step mode") // //
2897 ("batch,b", bpo::value<std::vector<std::string>>()->zero_tokens()->composing(), "batch processing mode") // //
2898 ("no-batch", bpo::value<bool>()->zero_tokens(), "force gui processing mode") // //
2899 ("no-cleanup", bpo::value<bool>()->zero_tokens()->default_value(false), "do not cleanup the shm segment") // //
2900 ("hostname", bpo::value<std::string>()->default_value("localhost"), "hostname to deploy") // //
2901 ("resources", bpo::value<std::string>()->default_value(""), "resources allocated for the workflow") // //
2902 ("start-port,p", bpo::value<unsigned short>()->default_value(22000), "start port to allocate") // //
2903 ("port-range,pr", bpo::value<unsigned short>()->default_value(1000), "ports in range") // //
2904 ("completion-policy,c", bpo::value<TerminationPolicy>(&processingPolicies.termination)->default_value(TerminationPolicy::QUIT), // //
2905 "what to do when processing is finished: quit, wait") // //
2906 ("error-policy", bpo::value<TerminationPolicy>(&processingPolicies.error)->default_value(TerminationPolicy::QUIT), // //
2907 "what to do when a device has an error: quit, wait") // //
2908 ("min-failure-level", bpo::value<LogParsingHelpers::LogLevel>(&minFailureLevel)->default_value(LogParsingHelpers::LogLevel::Fatal), // //
2909 "minimum message level which will be considered as fatal and exit with 1") // //
2910 ("graphviz,g", bpo::value<bool>()->zero_tokens()->default_value(false), "produce graphviz output") // //
2911 ("mermaid", bpo::value<std::string>()->default_value(""), "produce graph output in mermaid format in file under specified name or on stdout if argument is \"-\"") // //
2912 ("timeout,t", bpo::value<uint64_t>()->default_value(0), "forced exit timeout (in seconds)") // //
2913 ("dds,D", bpo::value<std::string>()->default_value(""), "create DDS configuration") // //
2914 ("dds-workflow-suffix,D", bpo::value<std::string>()->default_value(""), "suffix for DDS names") // //
2915 ("dump-workflow,dump", bpo::value<bool>()->zero_tokens()->default_value(false), "dump workflow as JSON") // //
2916 ("dump-workflow-file", bpo::value<std::string>()->default_value("-"), "file to which do the dump") // //
2917 ("driver-mode", bpo::value<DriverMode>(&driverMode)->default_value(DriverMode::STANDALONE), R"(how to run the driver. default: "standalone". Valid: "embedded")") // //
2918 ("run", bpo::value<bool>()->zero_tokens()->default_value(false), "run workflow merged so far. It implies --batch. Use --no-batch to see the GUI") // //
2919 ("no-IPC", bpo::value<bool>()->zero_tokens()->default_value(false), "disable IPC topology optimization") // //
2920 ("o2-control,o2", bpo::value<std::string>()->default_value(""), "dump O2 Control workflow configuration under the specified name") //
2921 ("resources-monitoring", bpo::value<unsigned short>()->default_value(0), "enable cpu/memory monitoring for provided interval in seconds") //
2922 ("resources-monitoring-file", bpo::value<std::string>()->default_value("performanceMetrics.json"), "file where to dump the metrics") //
2923 ("resources-monitoring-dump-interval", bpo::value<unsigned short>()->default_value(0), "dump monitoring information to disk every provided seconds"); //
2924 // some of the options must be forwarded by default to the device
2925 executorOptions.add(DeviceSpecHelpers::getForwardedDeviceOptions());
2926
2927 gHiddenDeviceOptions.add_options() //
2928 ("id,i", bpo::value<std::string>(), "device id for child spawning") //
2929 ("channel-config", bpo::value<std::vector<std::string>>(), "channel configuration") //
2930 ("control", "control plugin") //
2931 ("log-color", "logging color scheme")("color", "logging color scheme");
2932
2933 bpo::options_description visibleOptions;
2934 visibleOptions.add(executorOptions);
2935
2936 auto physicalWorkflow = workflow;
2937 std::map<std::string, size_t> rankIndex;
2938 // We remove the duplicates because for the moment child get themself twice:
2939 // once from the actual definition in the child, a second time from the
2940 // configuration they get passed by their parents.
2941 // Notice that we do not know in which order we will get the workflows, so
2942 // while we keep the order of DataProcessors we reshuffle them based on
2943 // some hopefully unique hash.
2944 size_t workflowHashA = 0;
2945 std::hash<std::string> hash_fn;
2946
2947 for (auto& dp : workflow) {
2948 workflowHashA += hash_fn(dp.name);
2949 }
2950
2951 for (auto& dp : workflow) {
2952 rankIndex.insert(std::make_pair(dp.name, workflowHashA));
2953 }
2954
2955 std::vector<DataProcessorInfo> dataProcessorInfos;
2956 CommandInfo commandInfo{};
2957
2958 if (isatty(STDIN_FILENO) == false && isInputConfig()) {
2959 std::vector<DataProcessorSpec> importedWorkflow;
2960 bool previousWorked = WorkflowSerializationHelpers::import(std::cin, importedWorkflow, dataProcessorInfos, commandInfo);
2961 if (previousWorked == false) {
2962 exit(1);
2963 }
2964
2965 size_t workflowHashB = 0;
2966 for (auto& dp : importedWorkflow) {
2967 workflowHashB += hash_fn(dp.name);
2968 }
2969
2970 // FIXME: Streamline...
2971 // We remove the duplicates because for the moment child get themself twice:
2972 // once from the actual definition in the child, a second time from the
2973 // configuration they get passed by their parents.
2974 for (auto& dp : importedWorkflow) {
2975 auto found = std::find_if(physicalWorkflow.begin(), physicalWorkflow.end(),
2976 [&name = dp.name](DataProcessorSpec const& spec) { return spec.name == name; });
2977 if (found == physicalWorkflow.end()) {
2978 physicalWorkflow.push_back(dp);
2979 rankIndex.insert(std::make_pair(dp.name, workflowHashB));
2980 }
2981 }
2982 }
2983
2988 for (auto& dp : physicalWorkflow) {
2989 auto isExpendable = [](DataProcessorLabel const& label) { return label.value == "expendable" || label.value == "non-critical"; };
2990 if (std::find_if(dp.labels.begin(), dp.labels.end(), isExpendable) != dp.labels.end()) {
2991 for (auto& output : dp.outputs) {
2992 if (output.lifetime == Lifetime::Timeframe) {
2993 output.lifetime = Lifetime::Sporadic;
2994 }
2995 }
2996 }
2997 }
2998
3000 OverrideServiceSpecs driverServicesOverride = ServiceSpecHelpers::parseOverrides(getenv("DPL_DRIVER_OVERRIDE_SERVICES"));
3002 // We insert the hash for the internal devices.
3003 WorkflowHelpers::injectServiceDevices(physicalWorkflow, configContext);
3004 auto reader = std::find_if(physicalWorkflow.begin(), physicalWorkflow.end(), [](DataProcessorSpec& spec) { return spec.name == "internal-dpl-aod-reader"; });
3005 if (reader != physicalWorkflow.end()) {
3006 driverServices.push_back(ArrowSupport::arrowBackendSpec());
3007 }
3008 for (auto& service : driverServices) {
3009 if (service.injectTopology == nullptr) {
3010 continue;
3011 }
3012 WorkflowSpecNode node{physicalWorkflow};
3013 service.injectTopology(node, configContext);
3014 }
3015 for (auto& dp : physicalWorkflow) {
3016 if (dp.name.rfind("internal-", 0) == 0) {
3017 rankIndex.insert(std::make_pair(dp.name, hash_fn("internal")));
3018 }
3019 }
3020
3021 // We sort dataprocessors and Inputs / outputs by name, so that the edges are
3022 // always in the same order.
3023 std::stable_sort(physicalWorkflow.begin(), physicalWorkflow.end(), [](DataProcessorSpec const& a, DataProcessorSpec const& b) {
3024 return a.name < b.name;
3025 });
3026
3027 for (auto& dp : physicalWorkflow) {
3028 std::stable_sort(dp.inputs.begin(), dp.inputs.end(),
3029 [](InputSpec const& a, InputSpec const& b) { return DataSpecUtils::describe(a) < DataSpecUtils::describe(b); });
3030 std::stable_sort(dp.outputs.begin(), dp.outputs.end(),
3031 [](OutputSpec const& a, OutputSpec const& b) { return DataSpecUtils::describe(a) < DataSpecUtils::describe(b); });
3032 }
3033
3034 // Create a list of all the edges, so that we can do a topological sort
3035 // before we create the graph.
3036 std::vector<std::pair<int, int>> edges;
3037
3038 if (physicalWorkflow.size() > 1) {
3039 edges = TopologyPolicyHelpers::buildEdges(physicalWorkflow);
3040
3041 auto topoInfos = WorkflowHelpers::topologicalSort(physicalWorkflow.size(), &edges[0].first, &edges[0].second, sizeof(std::pair<int, int>), edges.size());
3042 if (topoInfos.size() != physicalWorkflow.size()) {
3043 // Check missing resilincy of one of the tasks
3044 checkNonResiliency(physicalWorkflow, edges);
3045 throw std::runtime_error("Unable to do topological sort of the resulting workflow. Do you have loops?\n" + debugTopoInfo(physicalWorkflow, topoInfos, edges));
3046 }
3047 // Sort by layer and then by name, to ensure stability.
3048 std::stable_sort(topoInfos.begin(), topoInfos.end(), [&workflow = physicalWorkflow](TopoIndexInfo const& a, TopoIndexInfo const& b) {
3049 auto aRank = std::make_tuple(a.layer, -workflow.at(a.index).outputs.size(), workflow.at(a.index).name);
3050 auto bRank = std::make_tuple(b.layer, -workflow.at(b.index).outputs.size(), workflow.at(b.index).name);
3051 return aRank < bRank;
3052 });
3053 // Reverse index and apply the result
3054 std::vector<int> dataProcessorOrder;
3055 dataProcessorOrder.resize(topoInfos.size());
3056 for (size_t i = 0; i < topoInfos.size(); ++i) {
3057 dataProcessorOrder[topoInfos[i].index] = i;
3058 }
3059 std::vector<int> newLocations;
3060 newLocations.resize(dataProcessorOrder.size());
3061 for (size_t i = 0; i < dataProcessorOrder.size(); ++i) {
3062 newLocations[dataProcessorOrder[i]] = i;
3063 }
3064 apply_permutation(physicalWorkflow, newLocations);
3065 }
3066
3067 // Use the hidden options as veto, all config specs matching a definition
3068 // in the hidden options are skipped in order to avoid duplicate definitions
3069 // in the main parser. Note: all config specs are forwarded to devices
3070 visibleOptions.add(ConfigParamsHelper::prepareOptionDescriptions(physicalWorkflow, currentWorkflowOptions, gHiddenDeviceOptions));
3071
3072 bpo::options_description od;
3073 od.add(visibleOptions);
3074 od.add(gHiddenDeviceOptions);
3075
3076 // FIXME: decide about the policy for handling unrecognized arguments
3077 // command_line_parser with option allow_unregistered() can be used
3078 using namespace bpo::command_line_style;
3079 auto style = (allow_short | short_allow_adjacent | short_allow_next | allow_long | long_allow_adjacent | long_allow_next | allow_sticky | allow_dash_for_short);
3080 bpo::variables_map varmap;
3081 try {
3082 bpo::store(
3083 bpo::command_line_parser(argc, argv)
3084 .options(od)
3085 .style(style)
3086 .run(),
3087 varmap);
3088 } catch (std::exception const& e) {
3089 LOGP(error, "error parsing options of {}: {}", argv[0], e.what());
3090 exit(1);
3091 }
3092 conflicting_options(varmap, "dds", "o2-control");
3093 conflicting_options(varmap, "dds", "dump-workflow");
3094 conflicting_options(varmap, "dds", "run");
3095 conflicting_options(varmap, "dds", "graphviz");
3096 conflicting_options(varmap, "o2-control", "dump-workflow");
3097 conflicting_options(varmap, "o2-control", "run");
3098 conflicting_options(varmap, "o2-control", "graphviz");
3099 conflicting_options(varmap, "run", "dump-workflow");
3100 conflicting_options(varmap, "run", "graphviz");
3101 conflicting_options(varmap, "run", "mermaid");
3102 conflicting_options(varmap, "dump-workflow", "graphviz");
3103 conflicting_options(varmap, "no-batch", "batch");
3104
3105 if (varmap.count("help")) {
3106 printHelp(varmap, executorOptions, physicalWorkflow, currentWorkflowOptions);
3107 exit(0);
3108 }
3112 if (varmap.count("severity")) {
3113 auto logLevel = varmap["severity"].as<std::string>();
3114 if (logLevel == "debug") {
3115 fair::Logger::SetConsoleSeverity(fair::Severity::debug);
3116 } else if (logLevel == "detail") {
3117 fair::Logger::SetConsoleSeverity(fair::Severity::detail);
3118 } else if (logLevel == "info") {
3119 fair::Logger::SetConsoleSeverity(fair::Severity::info);
3120 } else if (logLevel == "warning") {
3121 fair::Logger::SetConsoleSeverity(fair::Severity::warning);
3122 } else if (logLevel == "error") {
3123 fair::Logger::SetConsoleSeverity(fair::Severity::error);
3124 } else if (logLevel == "important") {
3125 fair::Logger::SetConsoleSeverity(fair::Severity::important);
3126 } else if (logLevel == "alarm") {
3127 fair::Logger::SetConsoleSeverity(fair::Severity::alarm);
3128 } else if (logLevel == "critical") {
3129 fair::Logger::SetConsoleSeverity(fair::Severity::critical);
3130 } else if (logLevel == "fatal") {
3131 fair::Logger::SetConsoleSeverity(fair::Severity::fatal);
3132 } else {
3133 LOGP(error, "Invalid log level '{}'", logLevel);
3134 exit(1);
3135 }
3136 }
3137
3138 enableSignposts(varmap["signposts"].as<std::string>());
3139
3140 auto evaluateBatchOption = [&varmap]() -> bool {
3141 if (varmap.count("no-batch") > 0) {
3142 return false;
3143 }
3144 if (varmap.count("batch") == 0) {
3145 // default value
3146 return isatty(fileno(stdout)) == 0;
3147 }
3148 // FIXME: should actually use the last value, but for some reason the
3149 // values are not filled into the vector, even if specifying `-b true`
3150 // need to find out why the boost program options example is not working
3151 // in our case. Might depend on the parser options
3152 // auto value = varmap["batch"].as<std::vector<std::string>>();
3153 return true;
3154 };
3155 DriverInfo driverInfo{
3156 .sendingPolicies = sendingPolicies,
3157 .forwardingPolicies = forwardingPolicies,
3158 .callbacksPolicies = callbacksPolicies};
3159 driverInfo.states.reserve(10);
3160 driverInfo.sigintRequested = false;
3161 driverInfo.sigchldRequested = false;
3162 driverInfo.channelPolicies = channelPolicies;
3163 driverInfo.completionPolicies = completionPolicies;
3164 driverInfo.dispatchPolicies = dispatchPolicies;
3165 driverInfo.resourcePolicies = resourcePolicies;
3166 driverInfo.argc = argc;
3167 driverInfo.argv = argv;
3168 driverInfo.noSHMCleanup = varmap["no-cleanup"].as<bool>();
3169 driverInfo.processingPolicies.termination = varmap["completion-policy"].as<TerminationPolicy>();
3170 driverInfo.processingPolicies.earlyForward = varmap["early-forward-policy"].as<EarlyForwardPolicy>();
3171 driverInfo.mode = varmap["driver-mode"].as<DriverMode>();
3172
3173 auto batch = evaluateBatchOption();
3174 DriverConfig driverConfig{
3175 .batch = batch,
3176 .driverHasGUI = (batch == false) || getenv("DPL_DRIVER_REMOTE_GUI") != nullptr,
3177 };
3178
3179 if (varmap["error-policy"].defaulted() && driverConfig.batch == false) {
3180 driverInfo.processingPolicies.error = TerminationPolicy::WAIT;
3181 } else {
3182 driverInfo.processingPolicies.error = varmap["error-policy"].as<TerminationPolicy>();
3183 }
3184 driverInfo.minFailureLevel = varmap["min-failure-level"].as<LogParsingHelpers::LogLevel>();
3185 driverInfo.startTime = uv_hrtime();
3186 driverInfo.startTimeMsFromEpoch = std::chrono::duration_cast<std::chrono::milliseconds>(
3187 std::chrono::system_clock::now().time_since_epoch())
3188 .count();
3189 driverInfo.timeout = varmap["timeout"].as<uint64_t>();
3190 driverInfo.deployHostname = varmap["hostname"].as<std::string>();
3191 driverInfo.resources = varmap["resources"].as<std::string>();
3192 driverInfo.resourcesMonitoringInterval = varmap["resources-monitoring"].as<unsigned short>();
3193 driverInfo.resourcesMonitoringFilename = varmap["resources-monitoring-file"].as<std::string>();
3194 driverInfo.resourcesMonitoringDumpInterval = varmap["resources-monitoring-dump-interval"].as<unsigned short>();
3195
3196 // FIXME: should use the whole dataProcessorInfos, actually...
3197 driverInfo.processorInfo = dataProcessorInfos;
3198 driverInfo.configContext = &configContext;
3199
3200 DriverControl driverControl;
3201 initialiseDriverControl(varmap, driverInfo, driverControl);
3202
3203 commandInfo.merge(CommandInfo(argc, argv));
3204
3205 std::string frameworkId;
3206 // If the id is set, this means this is a device,
3207 // otherwise this is the driver.
3208 if (varmap.count("id")) {
3209 // The framework id does not want to know anything about DDS template expansion
3210 // so we simply drop it. Notice that the "id" Property is still the same as the
3211 // original --id option.
3212 frameworkId = std::regex_replace(varmap["id"].as<std::string>(), std::regex{"_dds.*"}, "");
3213 driverInfo.uniqueWorkflowId = fmt::format("{}", getppid());
3214 driverInfo.defaultDriverClient = "stdout://";
3215 } else {
3216 driverInfo.uniqueWorkflowId = fmt::format("{}", getpid());
3217 driverInfo.defaultDriverClient = "ws://";
3218 }
3219 return runStateMachine(physicalWorkflow,
3220 currentWorkflow,
3221 dataProcessorInfos,
3222 commandInfo,
3223 driverControl,
3224 driverInfo,
3225 driverConfig,
3227 detectedParams,
3228 varmap,
3229 driverServices,
3230 frameworkId);
3231}
3232
3233void doBoostException(boost::exception&, char const* processName)
3234{
3235 LOGP(error, "error while setting up workflow in {}: {}",
3236 processName, boost::current_exception_diagnostic_information(true));
3237}
3238#pragma GCC diagnostic push
std::vector< std::string > labels
struct uv_timer_s uv_timer_t
struct uv_async_s uv_async_t
struct uv_handle_s uv_handle_t
struct uv_poll_s uv_poll_t
struct uv_loop_s uv_loop_t
std::vector< OutputRoute > routes
std::ostringstream debug
std::unique_ptr< expressions::Node > node
int32_t i
int32_t retVal
void output(const std::map< std::string, ChannelStat > &channels)
Definition rawdump.cxx:197
o2::phos::PHOSEnergySlot es
uint16_t pos
Definition RawData.h:3
uint16_t pid
Definition RawData.h:2
#define O2_SIGNPOST_EVENT_EMIT_ERROR(log, id, name, format,...)
Definition Signpost.h:553
o2_log_handle_t * o2_walk_logs(bool(*callback)(char const *name, void *log, void *context), void *context=nullptr)
#define O2_DECLARE_DYNAMIC_LOG(name)
Definition Signpost.h:489
#define O2_SIGNPOST_ID_FROM_POINTER(name, log, pointer)
Definition Signpost.h:505
#define O2_SIGNPOST_EVENT_EMIT_INFO(log, id, name, format,...)
Definition Signpost.h:531
#define O2_SIGNPOST_END(log, id, name, format,...)
Definition Signpost.h:608
void _o2_log_set_stacktrace(_o2_log_t *log, int stacktrace)
#define O2_SIGNPOST_ID_GENERATE(name, log)
Definition Signpost.h:506
#define O2_SIGNPOST_EVENT_EMIT(log, id, name, format,...)
Definition Signpost.h:522
#define O2_SIGNPOST_START(log, id, name, format,...)
Definition Signpost.h:602
o2::monitoring::Monitoring Monitoring
StringRef key
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, std::ostream &out) noexcept
static bool isResourcesMonitoringEnabled(unsigned short interval) noexcept
Information about the running workflow.
void declareService(ServiceSpec const &spec, DeviceState &state, fair::mq::ProgOptions &options, ServiceRegistry::Salt salt=ServiceRegistry::globalDeviceSalt())
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