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