1373 DriverInfo& driverInfo,
1375 std::vector<DeviceMetricsInfo>& metricsInfos,
1376 std::vector<ConfigParamSpec>
const& detectedParams,
1377 boost::program_options::variables_map& varmap,
1378 std::vector<ServiceSpec>& driverServices,
1379 std::string frameworkId)
1383 .shmSegmentId = (int16_t)atoi(varmap[
"shm-segment-id"].as<std::string>().c_str())};
1387 auto* devicesManager =
new DevicesManager{.
controls = controls, .infos = infos, .specs = runningWorkflow.devices, .messages = {}};
1391 std::vector<uv_poll_t*> pollHandles;
1392 std::vector<DeviceStdioContext> childFds;
1394 std::vector<ComputingResource> resources;
1396 if (driverInfo.resources !=
"") {
1402 auto resourceManager = std::make_unique<SimpleResourceManager>(resources);
1405 void* window =
nullptr;
1406 decltype(debugGUI->
getGUIDebugger(infos, runningWorkflow.devices, allStates, dataProcessorInfos, metricsInfos, driverInfo, controls, driverControl)) debugGUICallback;
1409 auto initDebugGUI = []() ->
DebugGUI* {
1410 uv_lib_t supportLib;
1413 result = uv_dlopen(
"libO2FrameworkGUISupport.dylib", &supportLib);
1415 result = uv_dlopen(
"libO2FrameworkGUISupport.so", &supportLib);
1418 LOG(error) << uv_dlerror(&supportLib);
1423 result = uv_dlsym(&supportLib,
"dpl_plugin_callback", (
void**)&dpl_plugin_callback);
1425 LOG(error) << uv_dlerror(&supportLib);
1429 return PluginManager::getByName<DebugGUI>(pluginInstance,
"ImGUIDebugGUI");
1437 if ((driverConfig.
batch ==
false || getenv(
"DPL_DRIVER_REMOTE_GUI") !=
nullptr) && frameworkId.empty()) {
1438 debugGUI = initDebugGUI();
1440 if (driverConfig.
batch ==
false) {
1441 window = debugGUI->
initGUI(
"O2 Framework debug GUI", serviceRegistry);
1443 window = debugGUI->
initGUI(
nullptr, serviceRegistry);
1446 }
else if (getenv(
"DPL_DEVICE_REMOTE_GUI") && !frameworkId.empty()) {
1447 debugGUI = initDebugGUI();
1455 window = debugGUI->
initGUI(
nullptr, serviceRegistry);
1458 if (driverConfig.
batch ==
false && window ==
nullptr && frameworkId.empty()) {
1459 LOG(warn) <<
"Could not create GUI. Switching to batch mode. Do you have GLFW on your system?";
1460 driverConfig.
batch =
true;
1461 if (varmap[
"error-policy"].defaulted()) {
1462 driverInfo.processingPolicies.error = TerminationPolicy::QUIT;
1465 bool guiQuitRequested =
false;
1466 bool hasError =
false;
1470 DriverState current;
1471 DriverState previous;
1477 if (!driverConfig.
batch) {
1479 uv_timer_init(loop, gui_timer);
1482 std::vector<ServiceMetricHandling> metricProcessingCallbacks;
1483 std::vector<ServiceSummaryHandling> summaryCallbacks;
1484 std::vector<ServicePreSchedule> preScheduleCallbacks;
1485 std::vector<ServicePostSchedule> postScheduleCallbacks;
1486 std::vector<ServiceDriverInit> driverInitCallbacks;
1487 for (
auto& service : driverServices) {
1488 if (service.driverStartup ==
nullptr) {
1491 service.driverStartup(serviceRegistry,
DeviceConfig{varmap});
1495 ref.registerService(ServiceRegistryHelpers::handleForService<DevicesManager>(devicesManager));
1497 bool guiTimerExpired =
false;
1499 guiContext.
plugin = debugGUI;
1502 guiContext.
frameCost = &driverInfo.frameCost;
1511 .controls = &controls,
1513 .states = &allStates,
1514 .specs = &runningWorkflow.devices,
1515 .metrics = &metricsInfos,
1516 .metricProcessingCallbacks = &metricProcessingCallbacks,
1517 .summaryCallbacks = &summaryCallbacks,
1518 .driver = &driverInfo,
1520 .isDriver = frameworkId.empty(),
1523 serverContext.serverHandle.data = &serverContext;
1526 uv_timer_init(loop, &force_step_timer);
1528 uv_timer_init(loop, &force_exit_timer);
1530 bool guiDeployedOnce =
false;
1534 metricDumpTimer.data = &serverContext;
1535 bool allChildrenGone =
false;
1542 serverContext.asyncLogProcessing->data = &serverContext;
1543 uv_async_init(loop, serverContext.asyncLogProcessing, [](
uv_async_t* handle) {
1544 auto* context = (DriverServerContext*)handle->data;
1545 processChildrenOutput(context->loop, *context->driver, *context->infos, *context->specs, *context->controls);
1546 for (auto* statusHandler : context->statusHandlers) {
1547 for (size_t di = 0; di < context->infos->size(); ++di) {
1548 statusHandler->sendNewLogs(di);
1555 if (driverControl.forcedTransitions.empty() ==
false) {
1556 for (
auto transition : driverControl.forcedTransitions) {
1557 driverInfo.states.push_back(transition);
1559 driverControl.forcedTransitions.resize(0);
1564 auto currentTime = uv_hrtime();
1565 uint64_t diff = (currentTime - driverInfo.startTime) / 1000000000LL;
1566 if ((
graceful_exit ==
false) && (driverInfo.timeout > 0) && (diff > driverInfo.timeout)) {
1567 LOG(info) <<
"Timout ellapsed. Requesting to quit.";
1572 if (
graceful_exit ==
true && driverInfo.sigintRequested ==
false) {
1573 driverInfo.sigintRequested =
true;
1574 driverInfo.states.resize(0);
1575 driverInfo.states.push_back(DriverState::QUIT_REQUESTED);
1580 driverInfo.sigchldRequested =
true;
1581 driverInfo.states.push_back(DriverState::HANDLE_CHILDREN);
1583 if (driverInfo.states.empty() ==
false) {
1585 current = driverInfo.states.back();
1587 current = DriverState::UNKNOWN;
1589 driverInfo.states.pop_back();
1591 case DriverState::BIND_GUI_PORT:
1592 bindGUIPort(driverInfo, serverContext, frameworkId);
1594 case DriverState::INIT:
1595 LOGP(info,
"Initialising O2 Data Processing Layer. Driver PID: {}.", getpid());
1596 LOGP(info,
"Driver listening on port: {}", driverInfo.port);
1599 driverInfo.sa_handle_child.sa_handler = &handle_sigchld;
1600 sigemptyset(&driverInfo.sa_handle_child.sa_mask);
1601 driverInfo.sa_handle_child.sa_flags = SA_RESTART | SA_NOCLDSTOP;
1602 if (sigaction(SIGCHLD, &driverInfo.sa_handle_child,
nullptr) == -1) {
1609 if (driverInfo.noSHMCleanup) {
1610 LOGP(warning,
"Not cleaning up shared memory.");
1618 for (
auto& callback : driverInitCallbacks) {
1619 callback(serviceRegistry, {varmap});
1621 driverInfo.states.push_back(DriverState::RUNNING);
1623 LOG(info) <<
"O2 Data Processing Layer initialised. We brake for nobody.";
1625 LOGF(info,
"Optimised build. O2DEBUG / LOG(debug) / LOGF(debug) / assert statement will not be shown.");
1628 case DriverState::IMPORT_CURRENT_WORKFLOW:
1631 dataProcessorInfos = previousDataProcessorInfos;
1632 for (
auto const& device : runningWorkflow.devices) {
1633 auto exists = std::find_if(dataProcessorInfos.begin(),
1634 dataProcessorInfos.end(),
1635 [
id = device.id](
DataProcessorInfo const& info) ->
bool { return info.name == id; });
1636 if (exists != dataProcessorInfos.end()) {
1640 for (
auto channel : device.inputChannels) {
1643 for (
auto channel : device.outputChannels) {
1646 dataProcessorInfos.push_back(
1651 workflowInfo.options,
1655 case DriverState::MATERIALISE_WORKFLOW:
1658 if (driverConfig.batch ==
true && varmap[
"dds"].as<std::string>().empty() && !varmap[
"dump-workflow"].as<
bool>() && workflowState == WorkflowParsingState::Empty) {
1659 LOGP(error,
"Empty workflow provided while running in batch mode.");
1665 auto altered_workflow = workflow;
1667 auto confNameFromParam = [](std::string
const& paramName) {
1668 std::regex name_regex(R
"(^control:([\w-]+)\/(\w+))");
1669 auto match = std::sregex_token_iterator(paramName.begin(), paramName.end(), name_regex, 0);
1670 if (
match == std::sregex_token_iterator()) {
1671 throw runtime_error_f(
"Malformed process control spec: %s", paramName.c_str());
1673 std::string task = std::sregex_token_iterator(paramName.begin(), paramName.end(), name_regex, 1)->str();
1674 std::string conf = std::sregex_token_iterator(paramName.begin(), paramName.end(), name_regex, 2)->str();
1675 return std::pair{task, conf};
1677 bool altered =
false;
1678 for (
auto& device : altered_workflow) {
1680 if (device.name.find(
"internal") != std::string::npos) {
1684 if (device.inputs.empty() ==
true) {
1688 auto hasMetadata = std::any_of(device.inputs.begin(), device.inputs.end(), [](
InputSpec const& spec) {
1689 return spec.metadata.empty() == false;
1695 auto hasControls = std::any_of(device.inputs.begin(), device.inputs.end(), [](
InputSpec const& spec) {
1696 return std::any_of(spec.metadata.begin(), spec.metadata.end(), [](ConfigParamSpec const& param) {
1697 return param.type == VariantType::Bool && param.name.find(
"control:") != std::string::npos;
1704 LOGP(
debug,
"Adjusting device {}", device.name.c_str());
1707 if (configStore !=
nullptr) {
1708 auto reg = std::make_unique<ConfigParamRegistry>(std::move(configStore));
1709 for (
auto& input : device.inputs) {
1710 for (
auto&
param : input.metadata) {
1711 if (
param.type == VariantType::Bool &&
param.name.find(
"control:") != std::string::npos) {
1712 if (
param.name !=
"control:default" &&
param.name !=
"control:spawn" &&
param.name !=
"control:build" &&
param.name !=
"control:define") {
1713 auto confName = confNameFromParam(
param.name).second;
1714 param.defaultValue = reg->get<
bool>(confName.c_str());
1721 LOGP(
debug,
"Original inputs: ");
1722 for (
auto& input : device.inputs) {
1723 LOGP(
debug,
"-> {}", input.binding);
1725 auto end = device.inputs.end();
1726 auto new_end = std::remove_if(device.inputs.begin(), device.inputs.end(), [](
InputSpec& input) {
1727 auto requested = false;
1728 auto hasControls = false;
1729 for (auto& param : input.metadata) {
1730 if (param.type != VariantType::Bool) {
1733 if (param.name.find(
"control:") != std::string::npos) {
1735 if (param.defaultValue.get<bool>() == true) {
1746 device.inputs.erase(new_end,
end);
1747 LOGP(
debug,
"Adjusted inputs: ");
1748 for (
auto& input : device.inputs) {
1756 for (
auto& service : driverServices) {
1757 if (service.adjustTopology ==
nullptr) {
1760 service.adjustTopology(
node, *driverInfo.configContext);
1768 driverInfo.channelPolicies,
1769 driverInfo.completionPolicies,
1770 driverInfo.dispatchPolicies,
1771 driverInfo.resourcePolicies,
1772 driverInfo.callbacksPolicies,
1773 driverInfo.sendingPolicies,
1774 driverInfo.forwardingPolicies,
1775 runningWorkflow.devices,
1777 driverInfo.uniqueWorkflowId,
1778 *driverInfo.configContext,
1779 !varmap[
"no-IPC"].as<
bool>(),
1780 driverInfo.resourcesMonitoringInterval,
1781 varmap[
"channel-prefix"].as<std::string>(),
1783 metricProcessingCallbacks.clear();
1784 std::vector<std::string> matchingServices;
1787 matchingServices.clear();
1788 for (
auto& device : runningWorkflow.devices) {
1789 for (
auto& service : device.services) {
1791 if (std::find(matchingServices.begin(), matchingServices.end(), service.name) != matchingServices.end()) {
1794 if (service.metricHandling) {
1795 metricProcessingCallbacks.push_back(service.metricHandling);
1796 matchingServices.push_back(service.name);
1802 matchingServices.clear();
1803 for (
auto& device : runningWorkflow.devices) {
1804 for (
auto& service : device.services) {
1806 if (std::find(matchingServices.begin(), matchingServices.end(), service.name) != matchingServices.end()) {
1809 if (service.summaryHandling) {
1810 summaryCallbacks.push_back(service.summaryHandling);
1811 matchingServices.push_back(service.name);
1816 preScheduleCallbacks.clear();
1817 matchingServices.clear();
1818 for (
auto& device : runningWorkflow.devices) {
1819 for (
auto& service : device.services) {
1821 if (std::find(matchingServices.begin(), matchingServices.end(), service.name) != matchingServices.end()) {
1824 if (service.preSchedule) {
1825 preScheduleCallbacks.push_back(service.preSchedule);
1829 postScheduleCallbacks.clear();
1830 matchingServices.clear();
1831 for (
auto& device : runningWorkflow.devices) {
1832 for (
auto& service : device.services) {
1834 if (std::find(matchingServices.begin(), matchingServices.end(), service.name) != matchingServices.end()) {
1837 if (service.postSchedule) {
1838 postScheduleCallbacks.push_back(service.postSchedule);
1842 driverInitCallbacks.clear();
1843 matchingServices.clear();
1844 for (
auto& device : runningWorkflow.devices) {
1845 for (
auto& service : device.services) {
1847 if (std::find(matchingServices.begin(), matchingServices.end(), service.name) != matchingServices.end()) {
1850 if (service.driverInit) {
1851 driverInitCallbacks.push_back(service.driverInit);
1859 for (
auto& device : runningWorkflow.devices) {
1861 if (device.name.find(
"internal") != std::string::npos) {
1865 if (configStore !=
nullptr) {
1866 auto reg = std::make_unique<ConfigParamRegistry>(std::move(configStore));
1867 for (
auto& option : device.options) {
1868 const char*
name = option.name.c_str();
1869 switch (option.type) {
1870 case VariantType::Int:
1871 option.defaultValue = reg->get<int32_t>(
name);
1873 case VariantType::Int8:
1874 option.defaultValue = reg->get<int8_t>(
name);
1876 case VariantType::Int16:
1877 option.defaultValue = reg->get<int16_t>(
name);
1879 case VariantType::UInt8:
1882 case VariantType::UInt16:
1883 option.defaultValue = reg->get<uint16_t>(
name);
1885 case VariantType::UInt32:
1886 option.defaultValue = reg->get<uint32_t>(
name);
1888 case VariantType::UInt64:
1889 option.defaultValue = reg->get<uint64_t>(
name);
1891 case VariantType::Int64:
1894 case VariantType::Float:
1895 option.defaultValue = reg->get<
float>(
name);
1897 case VariantType::Double:
1898 option.defaultValue = reg->get<
double>(
name);
1900 case VariantType::String:
1901 option.defaultValue = reg->get<std::string>(
name);
1903 case VariantType::Bool:
1904 option.defaultValue = reg->get<
bool>(
name);
1906 case VariantType::ArrayInt:
1907 option.defaultValue = reg->get<std::vector<int>>(
name);
1909 case VariantType::ArrayFloat:
1910 option.defaultValue = reg->get<std::vector<float>>(
name);
1912 case VariantType::ArrayDouble:
1913 option.defaultValue = reg->get<std::vector<double>>(
name);
1915 case VariantType::ArrayString:
1916 option.defaultValue = reg->get<std::vector<std::string>>(
name);
1918 case VariantType::Array2DInt:
1921 case VariantType::Array2DFloat:
1924 case VariantType::Array2DDouble:
1927 case VariantType::LabeledArrayInt:
1930 case VariantType::LabeledArrayFloat:
1933 case VariantType::LabeledArrayDouble:
1936 case VariantType::LabeledArrayString:
1945 }
catch (std::runtime_error& e) {
1946 LOGP(error,
"invalid workflow in {}: {}", driverInfo.argv[0], e.what());
1950#ifdef DPL_ENABLE_BACKTRACE
1953 LOGP(error,
"invalid workflow in {}: {}", driverInfo.argv[0], err.what);
1956 LOGP(error,
"invalid workflow in {}: Unknown error while materialising workflow", driverInfo.argv[0]);
1960 case DriverState::DO_CHILD:
1962 if (driverControl.defaultStopped) {
1963 kill(getpid(), SIGSTOP);
1965 for (
size_t di = 0;
di < runningWorkflow.devices.size();
di++) {
1967 if (runningWorkflow.devices[
di].id == frameworkId) {
1968 return doChild(driverInfo.argc, driverInfo.argv,
1971 runningWorkflow,
ref,
1973 driverInfo.processingPolicies,
1974 driverInfo.defaultDriverClient,
1979 std::ostringstream ss;
1980 for (
auto& processor : workflow) {
1981 ss <<
" - " << processor.name <<
"\n";
1983 for (
auto& spec : runningWorkflow.devices) {
1984 ss <<
" - " << spec.name <<
"(" << spec.id <<
")"
1987 driverInfo.lastError = fmt::format(
1988 "Unable to find component with id {}."
1989 " Available options:\n{}",
1990 frameworkId, ss.str());
1991 driverInfo.states.push_back(DriverState::QUIT_REQUESTED);
1994 case DriverState::REDEPLOY_GUI:
2004 if (!driverConfig.batch || getenv(
"DPL_DRIVER_REMOTE_GUI")) {
2006 uv_timer_stop(gui_timer);
2009 auto callback = debugGUI->getGUIDebugger(infos, runningWorkflow.devices, allStates, dataProcessorInfos, metricsInfos, driverInfo, controls, driverControl);
2010 guiContext.callback = [&serviceRegistry, &driverServices, &debugGUI, &infos, &runningWorkflow, &dataProcessorInfos, &metricsInfos, &driverInfo, &controls, &driverControl, callback]() {
2012 for (
auto& service : driverServices) {
2013 if (service.postRenderGUI) {
2014 service.postRenderGUI(serviceRegistry);
2018 guiContext.window = window;
2021 gui_timer->data = &guiContext;
2024 guiDeployedOnce =
true;
2027 case DriverState::MERGE_CONFIGS: {
2029 controls.resize(runningWorkflow.devices.size());
2032 if (varmap.count(
"dpl-tracing-flags")) {
2033 for (
auto& control : controls) {
2035 control.tracingFlags = tracingFlags;
2038 deviceExecutions.resize(runningWorkflow.devices.size());
2042 const auto uniformOptions = {
2044 "--aod-memory-rate-limit",
2045 "--aod-writer-json",
2046 "--aod-writer-ntfmerge",
2047 "--aod-writer-resdir",
2048 "--aod-writer-resfile",
2049 "--aod-writer-resmode",
2050 "--aod-writer-maxfilesize",
2051 "--aod-writer-keep",
2052 "--aod-max-io-rate",
2053 "--aod-parent-access-level",
2054 "--aod-parent-base-path-replacement",
2055 "--driver-client-backend",
2056 "--fairmq-ipc-prefix",
2059 "--resources-monitoring",
2060 "--resources-monitoring-file",
2061 "--resources-monitoring-dump-interval",
2065 for (
auto& option : uniformOptions) {
2071 driverControl.defaultStopped,
2072 driverInfo.processingPolicies.termination == TerminationPolicy::WAIT,
2076 runningWorkflow.devices,
2080 driverInfo.uniqueWorkflowId);
2083 LOGP(error,
"unable to merge configurations in {}: {}", driverInfo.argv[0], err.what);
2084#ifdef DPL_ENABLE_BACKTRACE
2085 std::cerr <<
"\nStacktrace follows:\n\n";
2091 case DriverState::SCHEDULE: {
2096 LOG(info) <<
"Redeployment of configuration asked.";
2097 std::ostringstream forwardedStdin;
2099 infos.reserve(runningWorkflow.devices.size());
2102 unsigned parentCPU = -1;
2103 unsigned parentNode = -1;
2104#if defined(__linux__) && __has_include(<sched.h>)
2105 parentCPU = sched_getcpu();
2106#elif __has_include(<linux/getcpu.h>)
2107 getcpu(&parentCPU, &parentNode,
nullptr);
2108#elif __has_include(<cpuid.h>) && (__x86_64__ || __i386__)
2113 for (
auto& callback : preScheduleCallbacks) {
2114 callback(serviceRegistry, {varmap});
2116 childFds.resize(runningWorkflow.devices.size());
2117 for (
int di = 0;
di < (
int)runningWorkflow.devices.size(); ++
di) {
2118 auto& context = childFds[
di];
2121 if (driverInfo.mode == DriverMode::EMBEDDED || runningWorkflow.devices[
di].resource.hostname != driverInfo.deployHostname) {
2123 runningWorkflow.devices[
di], controls[
di], deviceExecutions[
di], infos, allStates);
2128 runningWorkflow.devices, driverInfo,
2129 controls, deviceExecutions, infos,
2131 serviceRegistry, varmap,
2132 childFds, parentCPU, parentNode);
2137 for (
auto& callback : postScheduleCallbacks) {
2138 callback(serviceRegistry, {varmap});
2140 assert(infos.empty() ==
false);
2145 uv_timer_init(loop, &metricDumpTimer);
2147 driverInfo.resourcesMonitoringDumpInterval * 1000,
2148 driverInfo.resourcesMonitoringDumpInterval * 1000);
2151 for (
const auto& processorInfo : dataProcessorInfos) {
2152 const auto& cmdLineArgs = processorInfo.cmdLineArgs;
2153 if (std::find(cmdLineArgs.begin(), cmdLineArgs.end(),
"--severity") != cmdLineArgs.end()) {
2154 for (
size_t counter = 0;
const auto& spec : runningWorkflow.devices) {
2155 if (spec.name.compare(processorInfo.name) == 0) {
2157 const auto logLevelIt = std::find(cmdLineArgs.begin(), cmdLineArgs.end(),
"--severity") + 1;
2158 if ((*logLevelIt).compare(
"debug") == 0) {
2159 info.logLevel = LogParsingHelpers::LogLevel::Debug;
2160 }
else if ((*logLevelIt).compare(
"detail") == 0) {
2161 info.logLevel = LogParsingHelpers::LogLevel::Debug;
2162 }
else if ((*logLevelIt).compare(
"info") == 0) {
2163 info.logLevel = LogParsingHelpers::LogLevel::Info;
2164 }
else if ((*logLevelIt).compare(
"warning") == 0) {
2165 info.logLevel = LogParsingHelpers::LogLevel::Warning;
2166 }
else if ((*logLevelIt).compare(
"error") == 0) {
2167 info.logLevel = LogParsingHelpers::LogLevel::Error;
2168 }
else if ((*logLevelIt).compare(
"important") == 0) {
2169 info.logLevel = LogParsingHelpers::LogLevel::Info;
2170 }
else if ((*logLevelIt).compare(
"alarm") == 0) {
2171 info.logLevel = LogParsingHelpers::LogLevel::Alarm;
2172 }
else if ((*logLevelIt).compare(
"critical") == 0) {
2173 info.logLevel = LogParsingHelpers::LogLevel::Critical;
2174 }
else if ((*logLevelIt).compare(
"fatal") == 0) {
2175 info.logLevel = LogParsingHelpers::LogLevel::Fatal;
2183 LOG(info) <<
"Redeployment of configuration done.";
2185 case DriverState::RUNNING:
2189 devicesManager->flush();
2193 if (guiTimerExpired ==
false) {
2194 O2_SIGNPOST_EVENT_EMIT(driver, sid,
"mainloop",
"Entering event loop with %{public}s", once ?
"UV_RUN_ONCE" :
"UV_RUN_NOWAIT");
2196 uv_run(loop, once ? UV_RUN_ONCE : UV_RUN_NOWAIT);
2200 if (guiQuitRequested ||
2201 (driverInfo.processingPolicies.termination == TerminationPolicy::QUIT && (
checkIfCanExit(infos) ==
true))) {
2206 LOG(info) <<
"Quitting";
2207 driverInfo.states.push_back(DriverState::QUIT_REQUESTED);
2208 }
else if (infos.size() != runningWorkflow.devices.size()) {
2213 driverInfo.states.push_back(DriverState::RUNNING);
2214 driverInfo.states.push_back(DriverState::REDEPLOY_GUI);
2215 driverInfo.states.push_back(DriverState::SCHEDULE);
2216 driverInfo.states.push_back(DriverState::MERGE_CONFIGS);
2217 }
else if (runningWorkflow.devices.empty() && driverConfig.batch ==
true) {
2218 LOG(info) <<
"No device resulting from the workflow. Quitting.";
2220 driverInfo.states.push_back(DriverState::EXIT);
2221 }
else if (runningWorkflow.devices.empty() && driverConfig.batch ==
false && !guiDeployedOnce) {
2223 driverInfo.states.push_back(DriverState::RUNNING);
2224 driverInfo.states.push_back(DriverState::REDEPLOY_GUI);
2226 driverInfo.states.push_back(DriverState::RUNNING);
2229 case DriverState::QUIT_REQUESTED: {
2230 std::time_t
result = std::time(
nullptr);
2234 guiQuitRequested =
true;
2241 force_step_timer.data = &infos;
2243 driverInfo.states.push_back(DriverState::HANDLE_CHILDREN);
2246 case DriverState::HANDLE_CHILDREN: {
2250 uv_run(loop, once ? UV_RUN_ONCE : UV_RUN_NOWAIT);
2255 static bool forcefulExitMessage =
true;
2256 if (forcefulExitMessage) {
2257 LOG(info) <<
"Forceful exit requested.";
2258 forcefulExitMessage =
false;
2264 driverInfo.sigchldRequested =
false;
2269 bool supposedToQuit = (guiQuitRequested || canExit ||
graceful_exit);
2271 if (allChildrenGone && (supposedToQuit || driverInfo.processingPolicies.termination == TerminationPolicy::QUIT)) {
2273 driverInfo.states.resize(0);
2274 driverInfo.states.push_back(DriverState::EXIT);
2275 }
else if (hasError && driverInfo.processingPolicies.error == TerminationPolicy::QUIT && !supposedToQuit) {
2277 force_exit_timer.data = &infos;
2278 static bool forceful_timer_started =
false;
2279 if (forceful_timer_started ==
false) {
2280 forceful_timer_started =
true;
2283 driverInfo.states.push_back(DriverState::QUIT_REQUESTED);
2284 }
else if (allChildrenGone ==
false && supposedToQuit) {
2285 driverInfo.states.push_back(DriverState::HANDLE_CHILDREN);
2289 case DriverState::EXIT: {
2291 if (driverInfo.resourcesMonitoringDumpInterval) {
2292 uv_timer_stop(&metricDumpTimer);
2294 LOGP(info,
"Dumping performance metrics to {}.json file", driverInfo.resourcesMonitoringFilename);
2297 dumpRunSummary(serverContext, driverInfo, infos, runningWorkflow.devices);
2304 if (infos.empty()) {
2307 boost::property_tree::ptree finalConfig;
2308 assert(infos.size() == runningWorkflow.devices.size());
2309 for (
size_t di = 0;
di < infos.size(); ++
di) {
2310 auto& info = infos[
di];
2311 auto& spec = runningWorkflow.devices[
di];
2312 finalConfig.put_child(spec.name, info.currentConfig);
2314 LOG(info) <<
"Dumping used configuration in dpl-config.json";
2316 std::ofstream outDPLConfigFile(
"dpl-config.json", std::ios::out);
2317 if (outDPLConfigFile.is_open()) {
2318 boost::property_tree::write_json(outDPLConfigFile, finalConfig);
2320 LOGP(warning,
"Could not write out final configuration file. Read only run folder?");
2322 if (driverInfo.noSHMCleanup) {
2323 LOGP(warning,
"Not cleaning up shared memory.");
2327 return calculateExitCode(driverInfo, runningWorkflow.devices, infos);
2329 case DriverState::PERFORM_CALLBACKS:
2330 for (
auto& callback : driverControl.callbacks) {
2331 callback(workflow, runningWorkflow.devices, deviceExecutions, dataProcessorInfos, commandInfo);
2333 driverControl.callbacks.clear();
2336 LOG(error) <<
"Driver transitioned in an unknown state("
2337 <<
"current: " << (
int)current
2338 <<
", previous: " << (
int)previous
2339 <<
"). Shutting down.";
2340 driverInfo.states.push_back(DriverState::QUIT_REQUESTED);
2878 std::vector<ChannelConfigurationPolicy>
const& channelPolicies,
2879 std::vector<CompletionPolicy>
const& completionPolicies,
2880 std::vector<DispatchPolicy>
const& dispatchPolicies,
2881 std::vector<ResourcePolicy>
const& resourcePolicies,
2882 std::vector<CallbacksPolicy>
const& callbacksPolicies,
2883 std::vector<SendingPolicy>
const& sendingPolicies,
2884 std::vector<ConfigParamSpec>
const& currentWorkflowOptions,
2885 std::vector<ConfigParamSpec>
const& detectedParams,
2890 if (getenv(
"DPL_DRIVER_SIGNPOSTS")) {
2894 std::vector<std::string> currentArgs;
2895 std::vector<PluginInfo> plugins;
2898 for (
int ai = 1; ai < argc; ++ai) {
2899 currentArgs.emplace_back(argv[ai]);
2905 currentWorkflowOptions};
2909 bpo::options_description executorOptions(
"Executor options");
2910 const char* helpDescription =
"print help: short, full, executor, or processor name";
2912 executorOptions.add_options()
2913 (
"help,h", bpo::value<std::string>()->implicit_value(
"short"), helpDescription)
2914 (
"quiet,q", bpo::value<bool>()->zero_tokens()->default_value(
false),
"quiet operation")
2915 (
"stop,s", bpo::value<bool>()->zero_tokens()->default_value(
false),
"stop before device start")
2916 (
"single-step", bpo::value<bool>()->zero_tokens()->default_value(
false),
"start in single step mode")
2917 (
"batch,b", bpo::value<std::vector<std::string>>()->zero_tokens()->composing(),
"batch processing mode")
2918 (
"no-batch", bpo::value<bool>()->zero_tokens(),
"force gui processing mode")
2919 (
"no-cleanup", bpo::value<bool>()->zero_tokens()->default_value(
false),
"do not cleanup the shm segment")
2920 (
"hostname", bpo::value<std::string>()->default_value(
"localhost"),
"hostname to deploy")
2921 (
"resources", bpo::value<std::string>()->default_value(
""),
"resources allocated for the workflow")
2922 (
"start-port,p", bpo::value<unsigned short>()->default_value(22000),
"start port to allocate")
2923 (
"port-range,pr", bpo::value<unsigned short>()->default_value(1000),
"ports in range")
2924 (
"completion-policy,c", bpo::value<TerminationPolicy>(&processingPolicies.
termination)->default_value(TerminationPolicy::QUIT),
2925 "what to do when processing is finished: quit, wait")
2926 (
"error-policy", bpo::value<TerminationPolicy>(&processingPolicies.
error)->default_value(TerminationPolicy::QUIT),
2927 "what to do when a device has an error: quit, wait")
2928 (
"min-failure-level", bpo::value<LogParsingHelpers::LogLevel>(&minFailureLevel)->default_value(LogParsingHelpers::LogLevel::Fatal),
2929 "minimum message level which will be considered as fatal and exit with 1")
2930 (
"graphviz,g", bpo::value<bool>()->zero_tokens()->default_value(
false),
"produce graphviz output")
2931 (
"mermaid", bpo::value<std::string>()->default_value(
""),
"produce graph output in mermaid format in file under specified name or on stdout if argument is \"-\"")
2932 (
"timeout,t", bpo::value<uint64_t>()->default_value(0),
"forced exit timeout (in seconds)")
2933 (
"dds,D", bpo::value<std::string>()->default_value(
""),
"create DDS configuration")
2934 (
"dds-workflow-suffix,D", bpo::value<std::string>()->default_value(
""),
"suffix for DDS names")
2935 (
"dump-workflow,dump", bpo::value<bool>()->zero_tokens()->default_value(
false),
"dump workflow as JSON")
2936 (
"dump-workflow-file", bpo::value<std::string>()->default_value(
"-"),
"file to which do the dump")
2937 (
"driver-mode", bpo::value<DriverMode>(&driverMode)->default_value(DriverMode::STANDALONE), R
"(how to run the driver. default: "standalone". Valid: "embedded")")
2938 (
"run", bpo::value<bool>()->zero_tokens()->default_value(
false),
"run workflow merged so far. It implies --batch. Use --no-batch to see the GUI")
2939 (
"no-IPC", bpo::value<bool>()->zero_tokens()->default_value(
false),
"disable IPC topology optimization")
2940 (
"o2-control,o2", bpo::value<std::string>()->default_value(
""),
"dump O2 Control workflow configuration under the specified name")
2941 (
"resources-monitoring", bpo::value<unsigned short>()->default_value(0),
"enable cpu/memory monitoring for provided interval in seconds")
2942 (
"resources-monitoring-file", bpo::value<std::string>()->default_value(
"performanceMetrics.json"),
"file where to dump the metrics")
2943 (
"resources-monitoring-dump-interval", bpo::value<unsigned short>()->default_value(0),
"dump monitoring information to disk every provided seconds");
2948 (
"id,i", bpo::value<std::string>(),
"device id for child spawning")
2949 (
"channel-config", bpo::value<std::vector<std::string>>(),
"channel configuration")
2950 (
"control",
"control plugin")
2951 (
"log-color",
"logging color scheme")(
"color",
"logging color scheme");
2953 bpo::options_description visibleOptions;
2954 visibleOptions.add(executorOptions);
2956 auto physicalWorkflow = workflow;
2957 std::map<std::string, size_t> rankIndex;
2964 size_t workflowHashA = 0;
2965 std::hash<std::string> hash_fn;
2967 for (
auto& dp : workflow) {
2968 workflowHashA += hash_fn(dp.name);
2971 for (
auto& dp : workflow) {
2972 rankIndex.insert(std::make_pair(dp.name, workflowHashA));
2975 std::vector<DataProcessorInfo> dataProcessorInfos;
2979 std::vector<DataProcessorSpec> importedWorkflow;
2981 if (previousWorked ==
false) {
2985 size_t workflowHashB = 0;
2986 for (
auto& dp : importedWorkflow) {
2987 workflowHashB += hash_fn(dp.name);
2994 for (
auto& dp : importedWorkflow) {
2995 auto found = std::find_if(physicalWorkflow.begin(), physicalWorkflow.end(),
2997 if (found == physicalWorkflow.end()) {
2998 physicalWorkflow.push_back(dp);
2999 rankIndex.insert(std::make_pair(dp.name, workflowHashB));
3008 for (
auto& dp : physicalWorkflow) {
3010 if (std::find_if(dp.labels.begin(), dp.labels.end(), isExpendable) != dp.labels.end()) {
3011 for (
auto&
output : dp.outputs) {
3012 if (
output.lifetime == Lifetime::Timeframe) {
3013 output.lifetime = Lifetime::Sporadic;
3025 if (!(dec.requestedAODs.empty() && dec.requestedDYNs.empty() && dec.requestedIDXs.empty() && dec.requestedTIMs.empty())) {
3028 for (
auto& service : driverServices) {
3029 if (service.injectTopology ==
nullptr) {
3033 service.injectTopology(
node, configContext);
3035 for (
auto& dp : physicalWorkflow) {
3036 if (dp.name.rfind(
"internal-", 0) == 0) {
3037 rankIndex.insert(std::make_pair(dp.name, hash_fn(
"internal")));
3044 return a.name < b.name;
3047 for (
auto& dp : physicalWorkflow) {
3048 std::stable_sort(dp.inputs.begin(), dp.inputs.end(),
3049 [](
InputSpec const&
a,
InputSpec const&
b) { return DataSpecUtils::describe(a) < DataSpecUtils::describe(b); });
3050 std::stable_sort(dp.outputs.begin(), dp.outputs.end(),
3051 [](
OutputSpec const&
a,
OutputSpec const&
b) { return DataSpecUtils::describe(a) < DataSpecUtils::describe(b); });
3056 std::vector<std::pair<int, int>> edges;
3058 if (physicalWorkflow.size() > 1) {
3062 if (topoInfos.size() != physicalWorkflow.size()) {
3065 throw std::runtime_error(
"Unable to do topological sort of the resulting workflow. Do you have loops?\n" +
debugTopoInfo(physicalWorkflow, topoInfos, edges));
3069 auto aRank = std::make_tuple(a.layer, -workflow.at(a.index).outputs.size(), workflow.at(a.index).name);
3070 auto bRank = std::make_tuple(b.layer, -workflow.at(b.index).outputs.size(), workflow.at(b.index).name);
3071 return aRank < bRank;
3074 std::vector<int> dataProcessorOrder;
3075 dataProcessorOrder.resize(topoInfos.size());
3076 for (
size_t i = 0;
i < topoInfos.size(); ++
i) {
3077 dataProcessorOrder[topoInfos[
i].index] =
i;
3079 std::vector<int> newLocations;
3080 newLocations.resize(dataProcessorOrder.size());
3081 for (
size_t i = 0;
i < dataProcessorOrder.size(); ++
i) {
3082 newLocations[dataProcessorOrder[
i]] =
i;
3092 bpo::options_description od;
3093 od.add(visibleOptions);
3098 using namespace bpo::command_line_style;
3099 auto style = (allow_short | short_allow_adjacent | short_allow_next | allow_long | long_allow_adjacent | long_allow_next | allow_sticky | allow_dash_for_short);
3100 bpo::variables_map varmap;
3103 bpo::command_line_parser(argc, argv)
3108 }
catch (std::exception
const& e) {
3109 LOGP(error,
"error parsing options of {}: {}", argv[0], e.what());
3125 if (varmap.count(
"help")) {
3126 printHelp(varmap, executorOptions, physicalWorkflow, currentWorkflowOptions);
3132 if (varmap.count(
"severity")) {
3133 auto logLevel = varmap[
"severity"].as<std::string>();
3134 if (logLevel ==
"debug") {
3135 fair::Logger::SetConsoleSeverity(fair::Severity::debug);
3136 }
else if (logLevel ==
"detail") {
3137 fair::Logger::SetConsoleSeverity(fair::Severity::detail);
3138 }
else if (logLevel ==
"info") {
3139 fair::Logger::SetConsoleSeverity(fair::Severity::info);
3140 }
else if (logLevel ==
"warning") {
3141 fair::Logger::SetConsoleSeverity(fair::Severity::warning);
3142 }
else if (logLevel ==
"error") {
3143 fair::Logger::SetConsoleSeverity(fair::Severity::error);
3144 }
else if (logLevel ==
"important") {
3145 fair::Logger::SetConsoleSeverity(fair::Severity::important);
3146 }
else if (logLevel ==
"alarm") {
3147 fair::Logger::SetConsoleSeverity(fair::Severity::alarm);
3148 }
else if (logLevel ==
"critical") {
3149 fair::Logger::SetConsoleSeverity(fair::Severity::critical);
3150 }
else if (logLevel ==
"fatal") {
3151 fair::Logger::SetConsoleSeverity(fair::Severity::fatal);
3153 LOGP(error,
"Invalid log level '{}'", logLevel);
3160 auto evaluateBatchOption = [&varmap]() ->
bool {
3161 if (varmap.count(
"no-batch") > 0) {
3164 if (varmap.count(
"batch") == 0) {
3166 return isatty(fileno(stdout)) == 0;
3175 DriverInfo driverInfo{
3176 .sendingPolicies = sendingPolicies,
3177 .forwardingPolicies = forwardingPolicies,
3178 .callbacksPolicies = callbacksPolicies};
3179 driverInfo.states.reserve(10);
3180 driverInfo.sigintRequested =
false;
3181 driverInfo.sigchldRequested =
false;
3182 driverInfo.channelPolicies = channelPolicies;
3183 driverInfo.completionPolicies = completionPolicies;
3184 driverInfo.dispatchPolicies = dispatchPolicies;
3185 driverInfo.resourcePolicies = resourcePolicies;
3186 driverInfo.argc = argc;
3187 driverInfo.argv = argv;
3188 driverInfo.noSHMCleanup = varmap[
"no-cleanup"].as<
bool>();
3189 driverInfo.processingPolicies.termination = varmap[
"completion-policy"].as<
TerminationPolicy>();
3190 driverInfo.processingPolicies.earlyForward = varmap[
"early-forward-policy"].as<
EarlyForwardPolicy>();
3191 driverInfo.mode = varmap[
"driver-mode"].as<
DriverMode>();
3193 auto batch = evaluateBatchOption();
3196 .driverHasGUI = (batch ==
false) || getenv(
"DPL_DRIVER_REMOTE_GUI") !=
nullptr,
3199 if (varmap[
"error-policy"].defaulted() && driverConfig.batch ==
false) {
3200 driverInfo.processingPolicies.error = TerminationPolicy::WAIT;
3202 driverInfo.processingPolicies.error = varmap[
"error-policy"].as<
TerminationPolicy>();
3205 driverInfo.startTime = uv_hrtime();
3206 driverInfo.startTimeMsFromEpoch = std::chrono::duration_cast<std::chrono::milliseconds>(
3207 std::chrono::system_clock::now().time_since_epoch())
3209 driverInfo.timeout = varmap[
"timeout"].as<uint64_t>();
3210 driverInfo.deployHostname = varmap[
"hostname"].as<std::string>();
3211 driverInfo.resources = varmap[
"resources"].as<std::string>();
3212 driverInfo.resourcesMonitoringInterval = varmap[
"resources-monitoring"].as<
unsigned short>();
3213 driverInfo.resourcesMonitoringFilename = varmap[
"resources-monitoring-file"].as<std::string>();
3214 driverInfo.resourcesMonitoringDumpInterval = varmap[
"resources-monitoring-dump-interval"].as<
unsigned short>();
3217 driverInfo.processorInfo = dataProcessorInfos;
3218 driverInfo.configContext = &configContext;
3225 std::string frameworkId;
3228 if (varmap.count(
"id")) {
3232 frameworkId = std::regex_replace(varmap[
"id"].as<std::string>(), std::regex{
"_dds.*"},
"");
3233 driverInfo.uniqueWorkflowId = fmt::format(
"{}", getppid());
3234 driverInfo.defaultDriverClient =
"stdout://";
3236 driverInfo.uniqueWorkflowId = fmt::format(
"{}", getpid());
3237 driverInfo.defaultDriverClient =
"ws://";