1365 DriverInfo& driverInfo,
1367 std::vector<DeviceMetricsInfo>& metricsInfos,
1368 std::vector<ConfigParamSpec>
const& detectedParams,
1369 boost::program_options::variables_map& varmap,
1370 std::vector<ServiceSpec>& driverServices,
1371 std::string frameworkId)
1375 .shmSegmentId = (int16_t)atoi(varmap[
"shm-segment-id"].as<std::string>().c_str())};
1379 auto* devicesManager =
new DevicesManager{.
controls = controls, .infos = infos, .specs = runningWorkflow.devices, .messages = {}};
1383 std::vector<uv_poll_t*> pollHandles;
1384 std::vector<DeviceStdioContext> childFds;
1386 std::vector<ComputingResource> resources;
1388 if (driverInfo.resources !=
"") {
1394 auto resourceManager = std::make_unique<SimpleResourceManager>(resources);
1397 void* window =
nullptr;
1398 decltype(debugGUI->
getGUIDebugger(infos, runningWorkflow.devices, allStates, dataProcessorInfos, metricsInfos, driverInfo, controls, driverControl)) debugGUICallback;
1401 auto initDebugGUI = []() ->
DebugGUI* {
1402 uv_lib_t supportLib;
1405 result = uv_dlopen(
"libO2FrameworkGUISupport.dylib", &supportLib);
1407 result = uv_dlopen(
"libO2FrameworkGUISupport.so", &supportLib);
1410 LOG(error) << uv_dlerror(&supportLib);
1415 result = uv_dlsym(&supportLib,
"dpl_plugin_callback", (
void**)&dpl_plugin_callback);
1417 LOG(error) << uv_dlerror(&supportLib);
1421 return PluginManager::getByName<DebugGUI>(pluginInstance,
"ImGUIDebugGUI");
1428 if ((driverConfig.
batch ==
false || getenv(
"DPL_DRIVER_REMOTE_GUI") !=
nullptr) && frameworkId.empty()) {
1429 debugGUI = initDebugGUI();
1431 if (driverConfig.
batch ==
false) {
1432 window = debugGUI->
initGUI(
"O2 Framework debug GUI", serviceRegistry);
1434 window = debugGUI->
initGUI(
nullptr, serviceRegistry);
1437 }
else if (getenv(
"DPL_DEVICE_REMOTE_GUI") && !frameworkId.empty()) {
1438 debugGUI = initDebugGUI();
1446 window = debugGUI->
initGUI(
nullptr, serviceRegistry);
1449 if (driverConfig.
batch ==
false && window ==
nullptr && frameworkId.empty()) {
1450 LOG(warn) <<
"Could not create GUI. Switching to batch mode. Do you have GLFW on your system?";
1451 driverConfig.
batch =
true;
1452 if (varmap[
"error-policy"].defaulted()) {
1453 driverInfo.processingPolicies.error = TerminationPolicy::QUIT;
1456 bool guiQuitRequested =
false;
1457 bool hasError =
false;
1461 DriverState current;
1462 DriverState previous;
1468 if (!driverConfig.
batch) {
1470 uv_timer_init(loop, gui_timer);
1473 std::vector<ServiceMetricHandling> metricProcessingCallbacks;
1474 std::vector<ServiceSummaryHandling> summaryCallbacks;
1475 std::vector<ServicePreSchedule> preScheduleCallbacks;
1476 std::vector<ServicePostSchedule> postScheduleCallbacks;
1477 std::vector<ServiceDriverInit> driverInitCallbacks;
1478 for (
auto& service : driverServices) {
1479 if (service.driverStartup ==
nullptr) {
1482 service.driverStartup(serviceRegistry,
DeviceConfig{varmap});
1486 ref.registerService(ServiceRegistryHelpers::handleForService<DevicesManager>(devicesManager));
1488 bool guiTimerExpired =
false;
1490 guiContext.
plugin = debugGUI;
1493 guiContext.
frameCost = &driverInfo.frameCost;
1502 .controls = &controls,
1504 .states = &allStates,
1505 .specs = &runningWorkflow.devices,
1506 .metrics = &metricsInfos,
1507 .metricProcessingCallbacks = &metricProcessingCallbacks,
1508 .summaryCallbacks = &summaryCallbacks,
1509 .driver = &driverInfo,
1511 .isDriver = frameworkId.empty(),
1514 serverContext.serverHandle.data = &serverContext;
1517 uv_timer_init(loop, &force_step_timer);
1519 uv_timer_init(loop, &force_exit_timer);
1521 bool guiDeployedOnce =
false;
1525 metricDumpTimer.data = &serverContext;
1526 bool allChildrenGone =
false;
1533 serverContext.asyncLogProcessing->data = &serverContext;
1534 uv_async_init(loop, serverContext.asyncLogProcessing, [](
uv_async_t* handle) {
1535 auto* context = (DriverServerContext*)handle->data;
1536 processChildrenOutput(context->loop, *context->driver, *context->infos, *context->specs, *context->controls);
1543 driverInfo.states.push_back(transition);
1550 auto currentTime = uv_hrtime();
1551 uint64_t diff = (currentTime - driverInfo.startTime) / 1000000000LL;
1552 if ((
graceful_exit ==
false) && (driverInfo.timeout > 0) && (diff > driverInfo.timeout)) {
1553 LOG(info) <<
"Timout ellapsed. Requesting to quit.";
1558 if (
graceful_exit ==
true && driverInfo.sigintRequested ==
false) {
1559 driverInfo.sigintRequested =
true;
1560 driverInfo.states.resize(0);
1561 driverInfo.states.push_back(DriverState::QUIT_REQUESTED);
1566 driverInfo.sigchldRequested =
true;
1567 driverInfo.states.push_back(DriverState::HANDLE_CHILDREN);
1569 if (driverInfo.states.empty() ==
false) {
1571 current = driverInfo.states.back();
1573 current = DriverState::UNKNOWN;
1575 driverInfo.states.pop_back();
1577 case DriverState::BIND_GUI_PORT:
1578 bindGUIPort(driverInfo, serverContext, frameworkId);
1580 case DriverState::INIT:
1581 LOGP(info,
"Initialising O2 Data Processing Layer. Driver PID: {}.", getpid());
1582 LOGP(info,
"Driver listening on port: {}", driverInfo.port);
1585 driverInfo.sa_handle_child.sa_handler = &handle_sigchld;
1586 sigemptyset(&driverInfo.sa_handle_child.sa_mask);
1587 driverInfo.sa_handle_child.sa_flags = SA_RESTART | SA_NOCLDSTOP;
1588 if (sigaction(SIGCHLD, &driverInfo.sa_handle_child,
nullptr) == -1) {
1595 if (driverInfo.noSHMCleanup) {
1596 LOGP(warning,
"Not cleaning up shared memory.");
1604 for (
auto& callback : driverInitCallbacks) {
1605 callback(serviceRegistry, {varmap});
1607 driverInfo.states.push_back(DriverState::RUNNING);
1609 LOG(info) <<
"O2 Data Processing Layer initialised. We brake for nobody.";
1611 LOGF(info,
"Optimised build. O2DEBUG / LOG(debug) / LOGF(debug) / assert statement will not be shown.");
1614 case DriverState::IMPORT_CURRENT_WORKFLOW:
1617 dataProcessorInfos = previousDataProcessorInfos;
1618 for (
auto const& device : runningWorkflow.devices) {
1619 auto exists = std::find_if(dataProcessorInfos.begin(),
1620 dataProcessorInfos.end(),
1621 [
id = device.id](
DataProcessorInfo const& info) ->
bool { return info.name == id; });
1622 if (exists != dataProcessorInfos.end()) {
1626 for (
auto channel : device.inputChannels) {
1629 for (
auto channel : device.outputChannels) {
1632 dataProcessorInfos.push_back(
1641 case DriverState::MATERIALISE_WORKFLOW:
1644 if (driverConfig.
batch ==
true && varmap[
"dds"].as<std::string>().empty() && !varmap[
"dump-workflow"].as<
bool>() && workflowState == WorkflowParsingState::Empty) {
1645 LOGP(error,
"Empty workflow provided while running in batch mode.");
1651 auto altered_workflow = workflow;
1653 auto confNameFromParam = [](std::string
const& paramName) {
1654 std::regex name_regex(R
"(^control:([\w-]+)\/(\w+))");
1655 auto match = std::sregex_token_iterator(paramName.begin(), paramName.end(), name_regex, 0);
1656 if (
match == std::sregex_token_iterator()) {
1657 throw runtime_error_f(
"Malformed process control spec: %s", paramName.c_str());
1659 std::string task = std::sregex_token_iterator(paramName.begin(), paramName.end(), name_regex, 1)->str();
1660 std::string conf = std::sregex_token_iterator(paramName.begin(), paramName.end(), name_regex, 2)->str();
1661 return std::pair{task, conf};
1663 bool altered =
false;
1664 for (
auto& device : altered_workflow) {
1666 if (device.name.find(
"internal") != std::string::npos) {
1670 if (device.inputs.empty() ==
true) {
1674 auto hasMetadata = std::any_of(device.inputs.begin(), device.inputs.end(), [](
InputSpec const& spec) {
1675 return spec.metadata.empty() == false;
1681 auto hasControls = std::any_of(device.inputs.begin(), device.inputs.end(), [](
InputSpec const& spec) {
1682 return std::any_of(spec.metadata.begin(), spec.metadata.end(), [](ConfigParamSpec const& param) {
1683 return param.type == VariantType::Bool && param.name.find(
"control:") != std::string::npos;
1690 LOGP(
debug,
"Adjusting device {}", device.name.c_str());
1693 if (configStore !=
nullptr) {
1694 auto reg = std::make_unique<ConfigParamRegistry>(std::move(configStore));
1695 for (
auto& input : device.inputs) {
1696 for (
auto&
param : input.metadata) {
1697 if (
param.type == VariantType::Bool &&
param.name.find(
"control:") != std::string::npos) {
1698 if (
param.name !=
"control:default" &&
param.name !=
"control:spawn" &&
param.name !=
"control:build" &&
param.name !=
"control:define") {
1699 auto confName = confNameFromParam(
param.name).second;
1700 param.defaultValue = reg->get<
bool>(confName.c_str());
1707 LOGP(
debug,
"Original inputs: ");
1708 for (
auto& input : device.inputs) {
1709 LOGP(
debug,
"-> {}", input.binding);
1711 auto end = device.inputs.end();
1712 auto new_end = std::remove_if(device.inputs.begin(), device.inputs.end(), [](
InputSpec& input) {
1713 auto requested = false;
1714 auto hasControls = false;
1715 for (auto& param : input.metadata) {
1716 if (param.type != VariantType::Bool) {
1719 if (param.name.find(
"control:") != std::string::npos) {
1721 if (param.defaultValue.get<bool>() == true) {
1732 device.inputs.erase(new_end,
end);
1733 LOGP(
debug,
"Adjusted inputs: ");
1734 for (
auto& input : device.inputs) {
1735 LOGP(
debug,
"-> {}", input.binding);
1742 for (
auto& service : driverServices) {
1743 if (service.adjustTopology ==
nullptr) {
1746 service.adjustTopology(
node, *driverInfo.configContext);
1754 driverInfo.channelPolicies,
1755 driverInfo.completionPolicies,
1756 driverInfo.dispatchPolicies,
1757 driverInfo.resourcePolicies,
1758 driverInfo.callbacksPolicies,
1759 driverInfo.sendingPolicies,
1760 driverInfo.forwardingPolicies,
1761 runningWorkflow.devices,
1763 driverInfo.uniqueWorkflowId,
1764 *driverInfo.configContext,
1765 !varmap[
"no-IPC"].as<
bool>(),
1766 driverInfo.resourcesMonitoringInterval,
1767 varmap[
"channel-prefix"].as<std::string>(),
1769 metricProcessingCallbacks.clear();
1770 std::vector<std::string> matchingServices;
1773 matchingServices.clear();
1774 for (
auto& device : runningWorkflow.devices) {
1775 for (
auto& service : device.services) {
1777 if (std::find(matchingServices.begin(), matchingServices.end(), service.name) != matchingServices.end()) {
1780 if (service.metricHandling) {
1781 metricProcessingCallbacks.push_back(service.metricHandling);
1782 matchingServices.push_back(service.name);
1788 matchingServices.clear();
1789 for (
auto& device : runningWorkflow.devices) {
1790 for (
auto& service : device.services) {
1792 if (std::find(matchingServices.begin(), matchingServices.end(), service.name) != matchingServices.end()) {
1795 if (service.summaryHandling) {
1796 summaryCallbacks.push_back(service.summaryHandling);
1797 matchingServices.push_back(service.name);
1802 preScheduleCallbacks.clear();
1803 matchingServices.clear();
1804 for (
auto& device : runningWorkflow.devices) {
1805 for (
auto& service : device.services) {
1807 if (std::find(matchingServices.begin(), matchingServices.end(), service.name) != matchingServices.end()) {
1810 if (service.preSchedule) {
1811 preScheduleCallbacks.push_back(service.preSchedule);
1815 postScheduleCallbacks.clear();
1816 matchingServices.clear();
1817 for (
auto& device : runningWorkflow.devices) {
1818 for (
auto& service : device.services) {
1820 if (std::find(matchingServices.begin(), matchingServices.end(), service.name) != matchingServices.end()) {
1823 if (service.postSchedule) {
1824 postScheduleCallbacks.push_back(service.postSchedule);
1828 driverInitCallbacks.clear();
1829 matchingServices.clear();
1830 for (
auto& device : runningWorkflow.devices) {
1831 for (
auto& service : device.services) {
1833 if (std::find(matchingServices.begin(), matchingServices.end(), service.name) != matchingServices.end()) {
1836 if (service.driverInit) {
1837 driverInitCallbacks.push_back(service.driverInit);
1845 for (
auto& device : runningWorkflow.devices) {
1847 if (device.name.find(
"internal") != std::string::npos) {
1851 if (configStore !=
nullptr) {
1852 auto reg = std::make_unique<ConfigParamRegistry>(std::move(configStore));
1853 for (
auto& option : device.options) {
1854 const char*
name = option.name.c_str();
1855 switch (option.type) {
1856 case VariantType::Int:
1857 option.defaultValue = reg->get<int32_t>(
name);
1859 case VariantType::Int8:
1860 option.defaultValue = reg->get<int8_t>(
name);
1862 case VariantType::Int16:
1863 option.defaultValue = reg->get<int16_t>(
name);
1865 case VariantType::UInt8:
1866 option.defaultValue = reg->get<uint8_t>(
name);
1868 case VariantType::UInt16:
1869 option.defaultValue = reg->get<uint16_t>(
name);
1871 case VariantType::UInt32:
1872 option.defaultValue = reg->get<uint32_t>(
name);
1874 case VariantType::UInt64:
1875 option.defaultValue = reg->get<uint64_t>(
name);
1877 case VariantType::Int64:
1878 option.defaultValue = reg->get<int64_t>(
name);
1880 case VariantType::Float:
1881 option.defaultValue = reg->get<
float>(
name);
1883 case VariantType::Double:
1884 option.defaultValue = reg->get<
double>(
name);
1886 case VariantType::String:
1887 option.defaultValue = reg->get<std::string>(
name);
1889 case VariantType::Bool:
1890 option.defaultValue = reg->get<
bool>(
name);
1892 case VariantType::ArrayInt:
1893 option.defaultValue = reg->get<std::vector<int>>(
name);
1895 case VariantType::ArrayFloat:
1896 option.defaultValue = reg->get<std::vector<float>>(
name);
1898 case VariantType::ArrayDouble:
1899 option.defaultValue = reg->get<std::vector<double>>(
name);
1901 case VariantType::ArrayString:
1902 option.defaultValue = reg->get<std::vector<std::string>>(
name);
1904 case VariantType::Array2DInt:
1907 case VariantType::Array2DFloat:
1910 case VariantType::Array2DDouble:
1913 case VariantType::LabeledArrayInt:
1916 case VariantType::LabeledArrayFloat:
1919 case VariantType::LabeledArrayDouble:
1922 case VariantType::LabeledArrayString:
1931 }
catch (std::runtime_error& e) {
1932 LOGP(error,
"invalid workflow in {}: {}", driverInfo.argv[0], e.what());
1936#ifdef DPL_ENABLE_BACKTRACE
1939 LOGP(error,
"invalid workflow in {}: {}", driverInfo.argv[0], err.what);
1942 LOGP(error,
"invalid workflow in {}: Unknown error while materialising workflow", driverInfo.argv[0]);
1946 case DriverState::DO_CHILD:
1949 kill(getpid(), SIGSTOP);
1951 for (
size_t di = 0;
di < runningWorkflow.devices.size();
di++) {
1953 if (runningWorkflow.devices[
di].id == frameworkId) {
1954 return doChild(driverInfo.argc, driverInfo.argv,
1956 runningWorkflow,
ref,
1958 driverInfo.processingPolicies,
1959 driverInfo.defaultDriverClient,
1964 std::ostringstream ss;
1965 for (
auto& processor : workflow) {
1966 ss <<
" - " << processor.name <<
"\n";
1968 for (
auto& spec : runningWorkflow.devices) {
1969 ss <<
" - " << spec.name <<
"(" << spec.id <<
")"
1972 driverInfo.lastError = fmt::format(
1973 "Unable to find component with id {}."
1974 " Available options:\n{}",
1975 frameworkId, ss.str());
1976 driverInfo.states.push_back(DriverState::QUIT_REQUESTED);
1979 case DriverState::REDEPLOY_GUI:
1989 if (!driverConfig.
batch || getenv(
"DPL_DRIVER_REMOTE_GUI")) {
1991 uv_timer_stop(gui_timer);
1994 auto callback = debugGUI->
getGUIDebugger(infos, runningWorkflow.devices, allStates, dataProcessorInfos, metricsInfos, driverInfo, controls, driverControl);
1995 guiContext.
callback = [&serviceRegistry, &driverServices, &debugGUI, &infos, &runningWorkflow, &dataProcessorInfos, &metricsInfos, &driverInfo, &controls, &driverControl, callback]() {
1997 for (
auto& service : driverServices) {
1998 if (service.postRenderGUI) {
1999 service.postRenderGUI(serviceRegistry);
2003 guiContext.
window = window;
2006 gui_timer->data = &guiContext;
2009 guiDeployedOnce =
true;
2012 case DriverState::MERGE_CONFIGS: {
2014 controls.resize(runningWorkflow.devices.size());
2017 if (varmap.count(
"dpl-tracing-flags")) {
2018 for (
auto& control : controls) {
2020 control.tracingFlags = tracingFlags;
2023 deviceExecutions.resize(runningWorkflow.devices.size());
2027 const auto uniformOptions = {
2029 "--aod-memory-rate-limit",
2030 "--aod-writer-json",
2031 "--aod-writer-ntfmerge",
2032 "--aod-writer-resdir",
2033 "--aod-writer-resfile",
2034 "--aod-writer-resmode",
2035 "--aod-writer-maxfilesize",
2036 "--aod-writer-keep",
2037 "--aod-max-io-rate",
2038 "--aod-parent-access-level",
2039 "--aod-parent-base-path-replacement",
2040 "--driver-client-backend",
2041 "--fairmq-ipc-prefix",
2043 "--resources-monitoring",
2044 "--resources-monitoring-file",
2045 "--resources-monitoring-dump-interval",
2049 for (
auto& option : uniformOptions) {
2056 driverInfo.processingPolicies.termination == TerminationPolicy::WAIT,
2060 runningWorkflow.devices,
2064 driverInfo.uniqueWorkflowId);
2067 LOGP(error,
"unable to merge configurations in {}: {}", driverInfo.argv[0], err.what);
2068#ifdef DPL_ENABLE_BACKTRACE
2069 std::cerr <<
"\nStacktrace follows:\n\n";
2075 case DriverState::SCHEDULE: {
2080 LOG(info) <<
"Redeployment of configuration asked.";
2081 std::ostringstream forwardedStdin;
2083 infos.reserve(runningWorkflow.devices.size());
2086 unsigned parentCPU = -1;
2087 unsigned parentNode = -1;
2088#if defined(__linux__) && __has_include(<sched.h>)
2089 parentCPU = sched_getcpu();
2090#elif __has_include(<linux/getcpu.h>)
2091 getcpu(&parentCPU, &parentNode,
nullptr);
2092#elif __has_include(<cpuid.h>) && (__x86_64__ || __i386__)
2097 for (
auto& callback : preScheduleCallbacks) {
2098 callback(serviceRegistry, {varmap});
2100 childFds.resize(runningWorkflow.devices.size());
2101 for (
int di = 0;
di < (
int)runningWorkflow.devices.size(); ++
di) {
2102 auto& context = childFds[
di];
2105 if (driverInfo.mode == DriverMode::EMBEDDED || runningWorkflow.devices[
di].resource.hostname != driverInfo.deployHostname) {
2107 runningWorkflow.devices[
di], controls[
di], deviceExecutions[
di], infos, allStates);
2112 runningWorkflow.devices, driverInfo,
2113 controls, deviceExecutions, infos,
2115 serviceRegistry, varmap,
2116 childFds, parentCPU, parentNode);
2121 for (
auto& callback : postScheduleCallbacks) {
2122 callback(serviceRegistry, {varmap});
2124 assert(infos.empty() ==
false);
2129 uv_timer_init(loop, &metricDumpTimer);
2131 driverInfo.resourcesMonitoringDumpInterval * 1000,
2132 driverInfo.resourcesMonitoringDumpInterval * 1000);
2135 for (
const auto& processorInfo : dataProcessorInfos) {
2136 const auto& cmdLineArgs = processorInfo.cmdLineArgs;
2137 if (std::find(cmdLineArgs.begin(), cmdLineArgs.end(),
"--severity") != cmdLineArgs.end()) {
2138 for (
size_t counter = 0;
const auto& spec : runningWorkflow.devices) {
2139 if (spec.name.compare(processorInfo.name) == 0) {
2141 const auto logLevelIt = std::find(cmdLineArgs.begin(), cmdLineArgs.end(),
"--severity") + 1;
2142 if ((*logLevelIt).compare(
"debug") == 0) {
2143 info.logLevel = LogParsingHelpers::LogLevel::Debug;
2144 }
else if ((*logLevelIt).compare(
"detail") == 0) {
2145 info.logLevel = LogParsingHelpers::LogLevel::Debug;
2146 }
else if ((*logLevelIt).compare(
"info") == 0) {
2147 info.logLevel = LogParsingHelpers::LogLevel::Info;
2148 }
else if ((*logLevelIt).compare(
"warning") == 0) {
2149 info.logLevel = LogParsingHelpers::LogLevel::Warning;
2150 }
else if ((*logLevelIt).compare(
"error") == 0) {
2151 info.logLevel = LogParsingHelpers::LogLevel::Error;
2152 }
else if ((*logLevelIt).compare(
"important") == 0) {
2153 info.logLevel = LogParsingHelpers::LogLevel::Info;
2154 }
else if ((*logLevelIt).compare(
"alarm") == 0) {
2155 info.logLevel = LogParsingHelpers::LogLevel::Alarm;
2156 }
else if ((*logLevelIt).compare(
"critical") == 0) {
2157 info.logLevel = LogParsingHelpers::LogLevel::Critical;
2158 }
else if ((*logLevelIt).compare(
"fatal") == 0) {
2159 info.logLevel = LogParsingHelpers::LogLevel::Fatal;
2167 LOG(info) <<
"Redeployment of configuration done.";
2169 case DriverState::RUNNING:
2173 devicesManager->flush();
2177 if (guiTimerExpired ==
false) {
2178 O2_SIGNPOST_EVENT_EMIT(driver, sid,
"mainloop",
"Entering event loop with %{public}s", once ?
"UV_RUN_ONCE" :
"UV_RUN_NOWAIT");
2180 uv_run(loop, once ? UV_RUN_ONCE : UV_RUN_NOWAIT);
2184 if (guiQuitRequested ||
2185 (driverInfo.processingPolicies.termination == TerminationPolicy::QUIT && (
checkIfCanExit(infos) ==
true))) {
2190 LOG(info) <<
"Quitting";
2191 driverInfo.states.push_back(DriverState::QUIT_REQUESTED);
2192 }
else if (infos.size() != runningWorkflow.devices.size()) {
2197 driverInfo.states.push_back(DriverState::RUNNING);
2198 driverInfo.states.push_back(DriverState::REDEPLOY_GUI);
2199 driverInfo.states.push_back(DriverState::SCHEDULE);
2200 driverInfo.states.push_back(DriverState::MERGE_CONFIGS);
2201 }
else if (runningWorkflow.devices.empty() && driverConfig.
batch ==
true) {
2202 LOG(info) <<
"No device resulting from the workflow. Quitting.";
2204 driverInfo.states.push_back(DriverState::EXIT);
2205 }
else if (runningWorkflow.devices.empty() && driverConfig.
batch ==
false && !guiDeployedOnce) {
2207 driverInfo.states.push_back(DriverState::RUNNING);
2208 driverInfo.states.push_back(DriverState::REDEPLOY_GUI);
2210 driverInfo.states.push_back(DriverState::RUNNING);
2213 case DriverState::QUIT_REQUESTED: {
2214 std::time_t
result = std::time(
nullptr);
2218 guiQuitRequested =
true;
2225 force_step_timer.data = &infos;
2227 driverInfo.states.push_back(DriverState::HANDLE_CHILDREN);
2230 case DriverState::HANDLE_CHILDREN: {
2234 uv_run(loop, once ? UV_RUN_ONCE : UV_RUN_NOWAIT);
2239 static bool forcefulExitMessage =
true;
2240 if (forcefulExitMessage) {
2241 LOG(info) <<
"Forceful exit requested.";
2242 forcefulExitMessage =
false;
2248 driverInfo.sigchldRequested =
false;
2253 bool supposedToQuit = (guiQuitRequested || canExit ||
graceful_exit);
2255 if (allChildrenGone && (supposedToQuit || driverInfo.processingPolicies.termination == TerminationPolicy::QUIT)) {
2257 driverInfo.states.resize(0);
2258 driverInfo.states.push_back(DriverState::EXIT);
2259 }
else if (hasError && driverInfo.processingPolicies.error == TerminationPolicy::QUIT && !supposedToQuit) {
2261 force_exit_timer.data = &infos;
2262 static bool forceful_timer_started =
false;
2263 if (forceful_timer_started ==
false) {
2264 forceful_timer_started =
true;
2267 driverInfo.states.push_back(DriverState::QUIT_REQUESTED);
2268 }
else if (allChildrenGone ==
false && supposedToQuit) {
2269 driverInfo.states.push_back(DriverState::HANDLE_CHILDREN);
2273 case DriverState::EXIT: {
2275 if (driverInfo.resourcesMonitoringDumpInterval) {
2276 uv_timer_stop(&metricDumpTimer);
2278 LOGP(info,
"Dumping performance metrics to {}.json file", driverInfo.resourcesMonitoringFilename);
2281 dumpRunSummary(serverContext, driverInfo, infos, runningWorkflow.devices);
2288 if (infos.empty()) {
2291 boost::property_tree::ptree finalConfig;
2292 assert(infos.size() == runningWorkflow.devices.size());
2293 for (
size_t di = 0;
di < infos.size(); ++
di) {
2294 auto& info = infos[
di];
2295 auto& spec = runningWorkflow.devices[
di];
2296 finalConfig.put_child(spec.name, info.currentConfig);
2298 LOG(info) <<
"Dumping used configuration in dpl-config.json";
2300 std::ofstream outDPLConfigFile(
"dpl-config.json", std::ios::out);
2301 if (outDPLConfigFile.is_open()) {
2302 boost::property_tree::write_json(outDPLConfigFile, finalConfig);
2304 LOGP(warning,
"Could not write out final configuration file. Read only run folder?");
2306 if (driverInfo.noSHMCleanup) {
2307 LOGP(warning,
"Not cleaning up shared memory.");
2311 return calculateExitCode(driverInfo, runningWorkflow.devices, infos);
2313 case DriverState::PERFORM_CALLBACKS:
2314 for (
auto& callback : driverControl.
callbacks) {
2315 callback(workflow, runningWorkflow.devices, deviceExecutions, dataProcessorInfos, commandInfo);
2320 LOG(error) <<
"Driver transitioned in an unknown state("
2321 <<
"current: " << (
int)current
2322 <<
", previous: " << (
int)previous
2323 <<
"). Shutting down.";
2324 driverInfo.states.push_back(DriverState::QUIT_REQUESTED);
2862 std::vector<ChannelConfigurationPolicy>
const& channelPolicies,
2863 std::vector<CompletionPolicy>
const& completionPolicies,
2864 std::vector<DispatchPolicy>
const& dispatchPolicies,
2865 std::vector<ResourcePolicy>
const& resourcePolicies,
2866 std::vector<CallbacksPolicy>
const& callbacksPolicies,
2867 std::vector<SendingPolicy>
const& sendingPolicies,
2868 std::vector<ConfigParamSpec>
const& currentWorkflowOptions,
2869 std::vector<ConfigParamSpec>
const& detectedParams,
2874 if (getenv(
"DPL_DRIVER_SIGNPOSTS")) {
2878 std::vector<std::string> currentArgs;
2879 std::vector<PluginInfo> plugins;
2882 for (
int ai = 1; ai < argc; ++ai) {
2883 currentArgs.emplace_back(argv[ai]);
2889 currentWorkflowOptions};
2893 bpo::options_description executorOptions(
"Executor options");
2894 const char* helpDescription =
"print help: short, full, executor, or processor name";
2896 executorOptions.add_options()
2897 (
"help,h", bpo::value<std::string>()->implicit_value(
"short"), helpDescription)
2898 (
"quiet,q", bpo::value<bool>()->zero_tokens()->default_value(
false),
"quiet operation")
2899 (
"stop,s", bpo::value<bool>()->zero_tokens()->default_value(
false),
"stop before device start")
2900 (
"single-step", bpo::value<bool>()->zero_tokens()->default_value(
false),
"start in single step mode")
2901 (
"batch,b", bpo::value<std::vector<std::string>>()->zero_tokens()->composing(),
"batch processing mode")
2902 (
"no-batch", bpo::value<bool>()->zero_tokens(),
"force gui processing mode")
2903 (
"no-cleanup", bpo::value<bool>()->zero_tokens()->default_value(
false),
"do not cleanup the shm segment")
2904 (
"hostname", bpo::value<std::string>()->default_value(
"localhost"),
"hostname to deploy")
2905 (
"resources", bpo::value<std::string>()->default_value(
""),
"resources allocated for the workflow")
2906 (
"start-port,p", bpo::value<unsigned short>()->default_value(22000),
"start port to allocate")
2907 (
"port-range,pr", bpo::value<unsigned short>()->default_value(1000),
"ports in range")
2908 (
"completion-policy,c", bpo::value<TerminationPolicy>(&processingPolicies.
termination)->default_value(TerminationPolicy::QUIT),
2909 "what to do when processing is finished: quit, wait")
2910 (
"error-policy", bpo::value<TerminationPolicy>(&processingPolicies.
error)->default_value(TerminationPolicy::QUIT),
2911 "what to do when a device has an error: quit, wait")
2912 (
"min-failure-level", bpo::value<LogParsingHelpers::LogLevel>(&minFailureLevel)->default_value(LogParsingHelpers::LogLevel::Fatal),
2913 "minimum message level which will be considered as fatal and exit with 1")
2914 (
"graphviz,g", bpo::value<bool>()->zero_tokens()->default_value(
false),
"produce graphviz output")
2915 (
"mermaid", bpo::value<std::string>()->default_value(
""),
"produce graph output in mermaid format in file under specified name or on stdout if argument is \"-\"")
2916 (
"timeout,t", bpo::value<uint64_t>()->default_value(0),
"forced exit timeout (in seconds)")
2917 (
"dds,D", bpo::value<std::string>()->default_value(
""),
"create DDS configuration")
2918 (
"dds-workflow-suffix,D", bpo::value<std::string>()->default_value(
""),
"suffix for DDS names")
2919 (
"dump-workflow,dump", bpo::value<bool>()->zero_tokens()->default_value(
false),
"dump workflow as JSON")
2920 (
"dump-workflow-file", bpo::value<std::string>()->default_value(
"-"),
"file to which do the dump")
2921 (
"driver-mode", bpo::value<DriverMode>(&driverMode)->default_value(DriverMode::STANDALONE), R
"(how to run the driver. default: "standalone". Valid: "embedded")")
2922 (
"run", bpo::value<bool>()->zero_tokens()->default_value(
false),
"run workflow merged so far. It implies --batch. Use --no-batch to see the GUI")
2923 (
"no-IPC", bpo::value<bool>()->zero_tokens()->default_value(
false),
"disable IPC topology optimization")
2924 (
"o2-control,o2", bpo::value<std::string>()->default_value(
""),
"dump O2 Control workflow configuration under the specified name")
2925 (
"resources-monitoring", bpo::value<unsigned short>()->default_value(0),
"enable cpu/memory monitoring for provided interval in seconds")
2926 (
"resources-monitoring-file", bpo::value<std::string>()->default_value(
"performanceMetrics.json"),
"file where to dump the metrics")
2927 (
"resources-monitoring-dump-interval", bpo::value<unsigned short>()->default_value(0),
"dump monitoring information to disk every provided seconds");
2932 (
"id,i", bpo::value<std::string>(),
"device id for child spawning")
2933 (
"channel-config", bpo::value<std::vector<std::string>>(),
"channel configuration")
2934 (
"control",
"control plugin")
2935 (
"log-color",
"logging color scheme")(
"color",
"logging color scheme");
2937 bpo::options_description visibleOptions;
2938 visibleOptions.add(executorOptions);
2940 auto physicalWorkflow = workflow;
2941 std::map<std::string, size_t> rankIndex;
2948 size_t workflowHashA = 0;
2949 std::hash<std::string> hash_fn;
2951 for (
auto& dp : workflow) {
2952 workflowHashA += hash_fn(dp.name);
2955 for (
auto& dp : workflow) {
2956 rankIndex.insert(std::make_pair(dp.name, workflowHashA));
2959 std::vector<DataProcessorInfo> dataProcessorInfos;
2963 std::vector<DataProcessorSpec> importedWorkflow;
2965 if (previousWorked ==
false) {
2969 size_t workflowHashB = 0;
2970 for (
auto& dp : importedWorkflow) {
2971 workflowHashB += hash_fn(dp.name);
2978 for (
auto& dp : importedWorkflow) {
2979 auto found = std::find_if(physicalWorkflow.begin(), physicalWorkflow.end(),
2981 if (found == physicalWorkflow.end()) {
2982 physicalWorkflow.push_back(dp);
2983 rankIndex.insert(std::make_pair(dp.name, workflowHashB));
2992 for (
auto& dp : physicalWorkflow) {
2994 if (std::find_if(dp.labels.begin(), dp.labels.end(), isExpendable) != dp.labels.end()) {
2995 for (
auto&
output : dp.outputs) {
2996 if (
output.lifetime == Lifetime::Timeframe) {
2997 output.lifetime = Lifetime::Sporadic;
3008 auto reader = std::find_if(physicalWorkflow.begin(), physicalWorkflow.end(), [](
DataProcessorSpec& spec) { return spec.name ==
"internal-dpl-aod-reader"; });
3009 if (reader != physicalWorkflow.end()) {
3012 for (
auto& service : driverServices) {
3013 if (service.injectTopology ==
nullptr) {
3017 service.injectTopology(
node, configContext);
3019 for (
auto& dp : physicalWorkflow) {
3020 if (dp.name.rfind(
"internal-", 0) == 0) {
3021 rankIndex.insert(std::make_pair(dp.name, hash_fn(
"internal")));
3028 return a.name < b.name;
3031 for (
auto& dp : physicalWorkflow) {
3032 std::stable_sort(dp.inputs.begin(), dp.inputs.end(),
3033 [](
InputSpec const&
a,
InputSpec const&
b) { return DataSpecUtils::describe(a) < DataSpecUtils::describe(b); });
3034 std::stable_sort(dp.outputs.begin(), dp.outputs.end(),
3035 [](
OutputSpec const&
a,
OutputSpec const&
b) { return DataSpecUtils::describe(a) < DataSpecUtils::describe(b); });
3040 std::vector<std::pair<int, int>> edges;
3042 if (physicalWorkflow.size() > 1) {
3046 if (topoInfos.size() != physicalWorkflow.size()) {
3049 throw std::runtime_error(
"Unable to do topological sort of the resulting workflow. Do you have loops?\n" +
debugTopoInfo(physicalWorkflow, topoInfos, edges));
3053 auto aRank = std::make_tuple(a.layer, -workflow.at(a.index).outputs.size(), workflow.at(a.index).name);
3054 auto bRank = std::make_tuple(b.layer, -workflow.at(b.index).outputs.size(), workflow.at(b.index).name);
3055 return aRank < bRank;
3058 std::vector<int> dataProcessorOrder;
3059 dataProcessorOrder.resize(topoInfos.size());
3060 for (
size_t i = 0;
i < topoInfos.size(); ++
i) {
3061 dataProcessorOrder[topoInfos[
i].index] =
i;
3063 std::vector<int> newLocations;
3064 newLocations.resize(dataProcessorOrder.size());
3065 for (
size_t i = 0;
i < dataProcessorOrder.size(); ++
i) {
3066 newLocations[dataProcessorOrder[
i]] =
i;
3076 bpo::options_description od;
3077 od.add(visibleOptions);
3082 using namespace bpo::command_line_style;
3083 auto style = (allow_short | short_allow_adjacent | short_allow_next | allow_long | long_allow_adjacent | long_allow_next | allow_sticky | allow_dash_for_short);
3084 bpo::variables_map varmap;
3087 bpo::command_line_parser(argc, argv)
3092 }
catch (std::exception
const& e) {
3093 LOGP(error,
"error parsing options of {}: {}", argv[0], e.what());
3109 if (varmap.count(
"help")) {
3110 printHelp(varmap, executorOptions, physicalWorkflow, currentWorkflowOptions);
3116 if (varmap.count(
"severity")) {
3117 auto logLevel = varmap[
"severity"].as<std::string>();
3118 if (logLevel ==
"debug") {
3119 fair::Logger::SetConsoleSeverity(fair::Severity::debug);
3120 }
else if (logLevel ==
"detail") {
3121 fair::Logger::SetConsoleSeverity(fair::Severity::detail);
3122 }
else if (logLevel ==
"info") {
3123 fair::Logger::SetConsoleSeverity(fair::Severity::info);
3124 }
else if (logLevel ==
"warning") {
3125 fair::Logger::SetConsoleSeverity(fair::Severity::warning);
3126 }
else if (logLevel ==
"error") {
3127 fair::Logger::SetConsoleSeverity(fair::Severity::error);
3128 }
else if (logLevel ==
"important") {
3129 fair::Logger::SetConsoleSeverity(fair::Severity::important);
3130 }
else if (logLevel ==
"alarm") {
3131 fair::Logger::SetConsoleSeverity(fair::Severity::alarm);
3132 }
else if (logLevel ==
"critical") {
3133 fair::Logger::SetConsoleSeverity(fair::Severity::critical);
3134 }
else if (logLevel ==
"fatal") {
3135 fair::Logger::SetConsoleSeverity(fair::Severity::fatal);
3137 LOGP(error,
"Invalid log level '{}'", logLevel);
3144 auto evaluateBatchOption = [&varmap]() ->
bool {
3145 if (varmap.count(
"no-batch") > 0) {
3148 if (varmap.count(
"batch") == 0) {
3150 return isatty(fileno(stdout)) == 0;
3159 DriverInfo driverInfo{
3160 .sendingPolicies = sendingPolicies,
3161 .forwardingPolicies = forwardingPolicies,
3162 .callbacksPolicies = callbacksPolicies};
3163 driverInfo.states.reserve(10);
3164 driverInfo.sigintRequested =
false;
3165 driverInfo.sigchldRequested =
false;
3166 driverInfo.channelPolicies = channelPolicies;
3167 driverInfo.completionPolicies = completionPolicies;
3168 driverInfo.dispatchPolicies = dispatchPolicies;
3169 driverInfo.resourcePolicies = resourcePolicies;
3170 driverInfo.argc = argc;
3171 driverInfo.argv = argv;
3172 driverInfo.noSHMCleanup = varmap[
"no-cleanup"].as<
bool>();
3173 driverInfo.processingPolicies.termination = varmap[
"completion-policy"].as<
TerminationPolicy>();
3174 driverInfo.processingPolicies.earlyForward = varmap[
"early-forward-policy"].as<
EarlyForwardPolicy>();
3175 driverInfo.mode = varmap[
"driver-mode"].as<
DriverMode>();
3177 auto batch = evaluateBatchOption();
3180 .driverHasGUI = (batch ==
false) || getenv(
"DPL_DRIVER_REMOTE_GUI") !=
nullptr,
3183 if (varmap[
"error-policy"].defaulted() && driverConfig.batch ==
false) {
3184 driverInfo.processingPolicies.error = TerminationPolicy::WAIT;
3186 driverInfo.processingPolicies.error = varmap[
"error-policy"].as<
TerminationPolicy>();
3189 driverInfo.startTime = uv_hrtime();
3190 driverInfo.startTimeMsFromEpoch = std::chrono::duration_cast<std::chrono::milliseconds>(
3191 std::chrono::system_clock::now().time_since_epoch())
3193 driverInfo.timeout = varmap[
"timeout"].as<uint64_t>();
3194 driverInfo.deployHostname = varmap[
"hostname"].as<std::string>();
3195 driverInfo.resources = varmap[
"resources"].as<std::string>();
3196 driverInfo.resourcesMonitoringInterval = varmap[
"resources-monitoring"].as<
unsigned short>();
3197 driverInfo.resourcesMonitoringFilename = varmap[
"resources-monitoring-file"].as<std::string>();
3198 driverInfo.resourcesMonitoringDumpInterval = varmap[
"resources-monitoring-dump-interval"].as<
unsigned short>();
3201 driverInfo.processorInfo = dataProcessorInfos;
3202 driverInfo.configContext = &configContext;
3209 std::string frameworkId;
3212 if (varmap.count(
"id")) {
3216 frameworkId = std::regex_replace(varmap[
"id"].as<std::string>(), std::regex{
"_dds.*"},
"");
3217 driverInfo.uniqueWorkflowId = fmt::format(
"{}", getppid());
3218 driverInfo.defaultDriverClient =
"stdout://";
3220 driverInfo.uniqueWorkflowId = fmt::format(
"{}", getpid());
3221 driverInfo.defaultDriverClient =
"ws://";