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