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