1359 DriverInfo& driverInfo,
1361 std::vector<DeviceMetricsInfo>& metricsInfos,
1362 std::vector<ConfigParamSpec>
const& detectedParams,
1363 boost::program_options::variables_map& varmap,
1364 std::vector<ServiceSpec>& driverServices,
1365 std::string frameworkId)
1369 .shmSegmentId = (int16_t)atoi(varmap[
"shm-segment-id"].as<std::string>().c_str())};
1373 auto* devicesManager =
new DevicesManager{.
controls = controls, .infos = infos, .specs = runningWorkflow.devices, .messages = {}};
1377 std::vector<uv_poll_t*> pollHandles;
1378 std::vector<DeviceStdioContext> childFds;
1380 std::vector<ComputingResource> resources;
1382 if (driverInfo.resources !=
"") {
1388 auto resourceManager = std::make_unique<SimpleResourceManager>(resources);
1391 void* window =
nullptr;
1392 decltype(debugGUI->
getGUIDebugger(infos, runningWorkflow.devices, allStates, dataProcessorInfos, metricsInfos, driverInfo, controls, driverControl)) debugGUICallback;
1395 auto initDebugGUI = []() ->
DebugGUI* {
1396 uv_lib_t supportLib;
1399 result = uv_dlopen(
"libO2FrameworkGUISupport.dylib", &supportLib);
1401 result = uv_dlopen(
"libO2FrameworkGUISupport.so", &supportLib);
1404 LOG(error) << uv_dlerror(&supportLib);
1409 result = uv_dlsym(&supportLib,
"dpl_plugin_callback", (
void**)&dpl_plugin_callback);
1411 LOG(error) << uv_dlerror(&supportLib);
1415 return PluginManager::getByName<DebugGUI>(pluginInstance,
"ImGUIDebugGUI");
1422 if ((driverConfig.
batch ==
false || getenv(
"DPL_DRIVER_REMOTE_GUI") !=
nullptr) && frameworkId.empty()) {
1423 debugGUI = initDebugGUI();
1425 if (driverConfig.
batch ==
false) {
1426 window = debugGUI->
initGUI(
"O2 Framework debug GUI", serviceRegistry);
1428 window = debugGUI->
initGUI(
nullptr, serviceRegistry);
1431 }
else if (getenv(
"DPL_DEVICE_REMOTE_GUI") && !frameworkId.empty()) {
1432 debugGUI = initDebugGUI();
1440 window = debugGUI->
initGUI(
nullptr, serviceRegistry);
1443 if (driverConfig.
batch ==
false && window ==
nullptr && frameworkId.empty()) {
1444 LOG(warn) <<
"Could not create GUI. Switching to batch mode. Do you have GLFW on your system?";
1445 driverConfig.
batch =
true;
1446 if (varmap[
"error-policy"].defaulted()) {
1447 driverInfo.processingPolicies.error = TerminationPolicy::QUIT;
1450 bool guiQuitRequested =
false;
1451 bool hasError =
false;
1455 DriverState current;
1456 DriverState previous;
1462 if (!driverConfig.
batch) {
1464 uv_timer_init(loop, gui_timer);
1467 std::vector<ServiceMetricHandling> metricProcessingCallbacks;
1468 std::vector<ServiceSummaryHandling> summaryCallbacks;
1469 std::vector<ServicePreSchedule> preScheduleCallbacks;
1470 std::vector<ServicePostSchedule> postScheduleCallbacks;
1471 std::vector<ServiceDriverInit> driverInitCallbacks;
1472 for (
auto& service : driverServices) {
1473 if (service.driverStartup ==
nullptr) {
1476 service.driverStartup(serviceRegistry,
DeviceConfig{varmap});
1480 ref.registerService(ServiceRegistryHelpers::handleForService<DevicesManager>(devicesManager));
1482 bool guiTimerExpired =
false;
1484 guiContext.
plugin = debugGUI;
1487 guiContext.
frameCost = &driverInfo.frameCost;
1496 .controls = &controls,
1498 .states = &allStates,
1499 .specs = &runningWorkflow.devices,
1500 .metrics = &metricsInfos,
1501 .metricProcessingCallbacks = &metricProcessingCallbacks,
1502 .summaryCallbacks = &summaryCallbacks,
1503 .driver = &driverInfo,
1505 .isDriver = frameworkId.empty(),
1508 serverContext.serverHandle.data = &serverContext;
1511 uv_timer_init(loop, &force_step_timer);
1513 uv_timer_init(loop, &force_exit_timer);
1515 bool guiDeployedOnce =
false;
1519 metricDumpTimer.data = &serverContext;
1520 bool allChildrenGone =
false;
1527 serverContext.asyncLogProcessing->data = &serverContext;
1528 uv_async_init(loop, serverContext.asyncLogProcessing, [](
uv_async_t* handle) {
1529 auto* context = (DriverServerContext*)handle->data;
1530 processChildrenOutput(context->loop, *context->driver, *context->infos, *context->specs, *context->controls);
1537 driverInfo.states.push_back(transition);
1544 auto currentTime = uv_hrtime();
1545 uint64_t diff = (currentTime - driverInfo.startTime) / 1000000000LL;
1546 if ((
graceful_exit ==
false) && (driverInfo.timeout > 0) && (diff > driverInfo.timeout)) {
1547 LOG(info) <<
"Timout ellapsed. Requesting to quit.";
1552 if (
graceful_exit ==
true && driverInfo.sigintRequested ==
false) {
1553 driverInfo.sigintRequested =
true;
1554 driverInfo.states.resize(0);
1555 driverInfo.states.push_back(DriverState::QUIT_REQUESTED);
1560 driverInfo.sigchldRequested =
true;
1561 driverInfo.states.push_back(DriverState::HANDLE_CHILDREN);
1563 if (driverInfo.states.empty() ==
false) {
1565 current = driverInfo.states.back();
1567 current = DriverState::UNKNOWN;
1569 driverInfo.states.pop_back();
1571 case DriverState::BIND_GUI_PORT:
1572 bindGUIPort(driverInfo, serverContext, frameworkId);
1574 case DriverState::INIT:
1575 LOGP(info,
"Initialising O2 Data Processing Layer. Driver PID: {}.", getpid());
1576 LOGP(info,
"Driver listening on port: {}", driverInfo.port);
1579 driverInfo.sa_handle_child.sa_handler = &handle_sigchld;
1580 sigemptyset(&driverInfo.sa_handle_child.sa_mask);
1581 driverInfo.sa_handle_child.sa_flags = SA_RESTART | SA_NOCLDSTOP;
1582 if (sigaction(SIGCHLD, &driverInfo.sa_handle_child,
nullptr) == -1) {
1589 if (driverInfo.noSHMCleanup) {
1590 LOGP(warning,
"Not cleaning up shared memory.");
1598 for (
auto& callback : driverInitCallbacks) {
1599 callback(serviceRegistry, {varmap});
1601 driverInfo.states.push_back(DriverState::RUNNING);
1603 LOG(info) <<
"O2 Data Processing Layer initialised. We brake for nobody.";
1605 LOGF(info,
"Optimised build. O2DEBUG / LOG(debug) / LOGF(debug) / assert statement will not be shown.");
1608 case DriverState::IMPORT_CURRENT_WORKFLOW:
1611 dataProcessorInfos = previousDataProcessorInfos;
1612 for (
auto const& device : runningWorkflow.devices) {
1613 auto exists = std::find_if(dataProcessorInfos.begin(),
1614 dataProcessorInfos.end(),
1615 [
id = device.id](
DataProcessorInfo const& info) ->
bool { return info.name == id; });
1616 if (exists != dataProcessorInfos.end()) {
1620 for (
auto channel : device.inputChannels) {
1623 for (
auto channel : device.outputChannels) {
1626 dataProcessorInfos.push_back(
1635 case DriverState::MATERIALISE_WORKFLOW:
1638 if (driverConfig.
batch ==
true && varmap[
"dds"].as<std::string>().empty() && !varmap[
"dump-workflow"].as<
bool>() && workflowState == WorkflowParsingState::Empty) {
1639 LOGP(error,
"Empty workflow provided while running in batch mode.");
1645 auto altered_workflow = workflow;
1647 auto confNameFromParam = [](std::string
const& paramName) {
1648 std::regex name_regex(R
"(^control:([\w-]+)\/(\w+))");
1649 auto match = std::sregex_token_iterator(paramName.begin(), paramName.end(), name_regex, 0);
1650 if (
match == std::sregex_token_iterator()) {
1651 throw runtime_error_f(
"Malformed process control spec: %s", paramName.c_str());
1653 std::string task = std::sregex_token_iterator(paramName.begin(), paramName.end(), name_regex, 1)->str();
1654 std::string conf = std::sregex_token_iterator(paramName.begin(), paramName.end(), name_regex, 2)->str();
1655 return std::pair{task, conf};
1657 bool altered =
false;
1658 for (
auto& device : altered_workflow) {
1660 if (device.name.find(
"internal") != std::string::npos) {
1664 if (device.inputs.empty() ==
true) {
1668 auto hasMetadata = std::any_of(device.inputs.begin(), device.inputs.end(), [](
InputSpec const& spec) {
1669 return spec.metadata.empty() == false;
1675 auto hasControls = std::any_of(device.inputs.begin(), device.inputs.end(), [](
InputSpec const& spec) {
1676 return std::any_of(spec.metadata.begin(), spec.metadata.end(), [](ConfigParamSpec const& param) {
1677 return param.type == VariantType::Bool && param.name.find(
"control:") != std::string::npos;
1684 LOGP(
debug,
"Adjusting device {}", device.name.c_str());
1687 if (configStore !=
nullptr) {
1688 auto reg = std::make_unique<ConfigParamRegistry>(std::move(configStore));
1689 for (
auto& input : device.inputs) {
1690 for (
auto&
param : input.metadata) {
1691 if (
param.type == VariantType::Bool &&
param.name.find(
"control:") != std::string::npos) {
1692 if (
param.name !=
"control:default" &&
param.name !=
"control:spawn" &&
param.name !=
"control:build" &&
param.name !=
"control:define") {
1693 auto confName = confNameFromParam(
param.name).second;
1694 param.defaultValue = reg->get<
bool>(confName.c_str());
1701 LOGP(
debug,
"Original inputs: ");
1702 for (
auto& input : device.inputs) {
1703 LOGP(
debug,
"-> {}", input.binding);
1705 auto end = device.inputs.end();
1706 auto new_end = std::remove_if(device.inputs.begin(), device.inputs.end(), [](
InputSpec& input) {
1707 auto requested = false;
1708 auto hasControls = false;
1709 for (auto& param : input.metadata) {
1710 if (param.type != VariantType::Bool) {
1713 if (param.name.find(
"control:") != std::string::npos) {
1715 if (param.defaultValue.get<bool>() == true) {
1726 device.inputs.erase(new_end,
end);
1727 LOGP(
debug,
"Adjusted inputs: ");
1728 for (
auto& input : device.inputs) {
1729 LOGP(
debug,
"-> {}", input.binding);
1736 for (
auto& service : driverServices) {
1737 if (service.adjustTopology ==
nullptr) {
1740 service.adjustTopology(node, *driverInfo.configContext);
1748 driverInfo.channelPolicies,
1749 driverInfo.completionPolicies,
1750 driverInfo.dispatchPolicies,
1751 driverInfo.resourcePolicies,
1752 driverInfo.callbacksPolicies,
1753 driverInfo.sendingPolicies,
1754 driverInfo.forwardingPolicies,
1755 runningWorkflow.devices,
1757 driverInfo.uniqueWorkflowId,
1758 *driverInfo.configContext,
1759 !varmap[
"no-IPC"].as<
bool>(),
1760 driverInfo.resourcesMonitoringInterval,
1761 varmap[
"channel-prefix"].as<std::string>(),
1763 metricProcessingCallbacks.clear();
1764 std::vector<std::string> matchingServices;
1767 matchingServices.clear();
1768 for (
auto& device : runningWorkflow.devices) {
1769 for (
auto& service : device.services) {
1771 if (std::find(matchingServices.begin(), matchingServices.end(), service.name) != matchingServices.end()) {
1774 if (service.metricHandling) {
1775 metricProcessingCallbacks.push_back(service.metricHandling);
1776 matchingServices.push_back(service.name);
1782 matchingServices.clear();
1783 for (
auto& device : runningWorkflow.devices) {
1784 for (
auto& service : device.services) {
1786 if (std::find(matchingServices.begin(), matchingServices.end(), service.name) != matchingServices.end()) {
1789 if (service.summaryHandling) {
1790 summaryCallbacks.push_back(service.summaryHandling);
1791 matchingServices.push_back(service.name);
1796 preScheduleCallbacks.clear();
1797 matchingServices.clear();
1798 for (
auto& device : runningWorkflow.devices) {
1799 for (
auto& service : device.services) {
1801 if (std::find(matchingServices.begin(), matchingServices.end(), service.name) != matchingServices.end()) {
1804 if (service.preSchedule) {
1805 preScheduleCallbacks.push_back(service.preSchedule);
1809 postScheduleCallbacks.clear();
1810 matchingServices.clear();
1811 for (
auto& device : runningWorkflow.devices) {
1812 for (
auto& service : device.services) {
1814 if (std::find(matchingServices.begin(), matchingServices.end(), service.name) != matchingServices.end()) {
1817 if (service.postSchedule) {
1818 postScheduleCallbacks.push_back(service.postSchedule);
1822 driverInitCallbacks.clear();
1823 matchingServices.clear();
1824 for (
auto& device : runningWorkflow.devices) {
1825 for (
auto& service : device.services) {
1827 if (std::find(matchingServices.begin(), matchingServices.end(), service.name) != matchingServices.end()) {
1830 if (service.driverInit) {
1831 driverInitCallbacks.push_back(service.driverInit);
1839 for (
auto& device : runningWorkflow.devices) {
1841 if (device.name.find(
"internal") != std::string::npos) {
1845 if (configStore !=
nullptr) {
1846 auto reg = std::make_unique<ConfigParamRegistry>(std::move(configStore));
1847 for (
auto& option : device.options) {
1848 const char*
name = option.name.c_str();
1849 switch (option.type) {
1850 case VariantType::Int:
1851 option.defaultValue = reg->get<int32_t>(
name);
1853 case VariantType::Int8:
1854 option.defaultValue = reg->get<int8_t>(
name);
1856 case VariantType::Int16:
1857 option.defaultValue = reg->get<int16_t>(
name);
1859 case VariantType::UInt8:
1860 option.defaultValue = reg->get<uint8_t>(
name);
1862 case VariantType::UInt16:
1863 option.defaultValue = reg->get<uint16_t>(
name);
1865 case VariantType::UInt32:
1866 option.defaultValue = reg->get<uint32_t>(
name);
1868 case VariantType::UInt64:
1869 option.defaultValue = reg->get<uint64_t>(
name);
1871 case VariantType::Int64:
1872 option.defaultValue = reg->get<int64_t>(
name);
1874 case VariantType::Float:
1875 option.defaultValue = reg->get<
float>(
name);
1877 case VariantType::Double:
1878 option.defaultValue = reg->get<
double>(
name);
1880 case VariantType::String:
1881 option.defaultValue = reg->get<std::string>(
name);
1883 case VariantType::Bool:
1884 option.defaultValue = reg->get<
bool>(
name);
1886 case VariantType::ArrayInt:
1887 option.defaultValue = reg->get<std::vector<int>>(
name);
1889 case VariantType::ArrayFloat:
1890 option.defaultValue = reg->get<std::vector<float>>(
name);
1892 case VariantType::ArrayDouble:
1893 option.defaultValue = reg->get<std::vector<double>>(
name);
1895 case VariantType::ArrayString:
1896 option.defaultValue = reg->get<std::vector<std::string>>(
name);
1898 case VariantType::Array2DInt:
1901 case VariantType::Array2DFloat:
1904 case VariantType::Array2DDouble:
1907 case VariantType::LabeledArrayInt:
1910 case VariantType::LabeledArrayFloat:
1913 case VariantType::LabeledArrayDouble:
1916 case VariantType::LabeledArrayString:
1925 }
catch (std::runtime_error& e) {
1926 LOGP(error,
"invalid workflow in {}: {}", driverInfo.argv[0], e.what());
1930#ifdef DPL_ENABLE_BACKTRACE
1933 LOGP(error,
"invalid workflow in {}: {}", driverInfo.argv[0], err.what);
1936 LOGP(error,
"invalid workflow in {}: Unknown error while materialising workflow", driverInfo.argv[0]);
1940 case DriverState::DO_CHILD:
1943 kill(getpid(), SIGSTOP);
1945 for (
size_t di = 0;
di < runningWorkflow.devices.size();
di++) {
1947 if (runningWorkflow.devices[
di].id == frameworkId) {
1948 return doChild(driverInfo.argc, driverInfo.argv,
1950 runningWorkflow,
ref,
1952 driverInfo.processingPolicies,
1953 driverInfo.defaultDriverClient,
1958 std::ostringstream ss;
1959 for (
auto& processor : workflow) {
1960 ss <<
" - " << processor.name <<
"\n";
1962 for (
auto& spec : runningWorkflow.devices) {
1963 ss <<
" - " << spec.name <<
"(" << spec.id <<
")"
1966 driverInfo.lastError = fmt::format(
1967 "Unable to find component with id {}."
1968 " Available options:\n{}",
1969 frameworkId, ss.str());
1970 driverInfo.states.push_back(DriverState::QUIT_REQUESTED);
1973 case DriverState::REDEPLOY_GUI:
1983 if (!driverConfig.
batch || getenv(
"DPL_DRIVER_REMOTE_GUI")) {
1985 uv_timer_stop(gui_timer);
1988 auto callback = debugGUI->
getGUIDebugger(infos, runningWorkflow.devices, allStates, dataProcessorInfos, metricsInfos, driverInfo, controls, driverControl);
1989 guiContext.
callback = [&serviceRegistry, &driverServices, &debugGUI, &infos, &runningWorkflow, &dataProcessorInfos, &metricsInfos, &driverInfo, &controls, &driverControl, callback]() {
1991 for (
auto& service : driverServices) {
1992 if (service.postRenderGUI) {
1993 service.postRenderGUI(serviceRegistry);
1997 guiContext.
window = window;
2000 gui_timer->data = &guiContext;
2003 guiDeployedOnce =
true;
2006 case DriverState::MERGE_CONFIGS: {
2008 controls.resize(runningWorkflow.devices.size());
2011 if (varmap.count(
"dpl-tracing-flags")) {
2012 for (
auto& control : controls) {
2014 control.tracingFlags = tracingFlags;
2017 deviceExecutions.resize(runningWorkflow.devices.size());
2021 const auto uniformOptions = {
2023 "--aod-memory-rate-limit",
2024 "--aod-writer-json",
2025 "--aod-writer-ntfmerge",
2026 "--aod-writer-resdir",
2027 "--aod-writer-resfile",
2028 "--aod-writer-resmode",
2029 "--aod-writer-maxfilesize",
2030 "--aod-writer-keep",
2031 "--aod-max-io-rate",
2032 "--aod-parent-access-level",
2033 "--aod-parent-base-path-replacement",
2034 "--driver-client-backend",
2035 "--fairmq-ipc-prefix",
2037 "--resources-monitoring",
2038 "--resources-monitoring-dump-interval",
2042 for (
auto& option : uniformOptions) {
2049 driverInfo.processingPolicies.termination == TerminationPolicy::WAIT,
2053 runningWorkflow.devices,
2057 driverInfo.uniqueWorkflowId);
2060 LOGP(error,
"unable to merge configurations in {}: {}", driverInfo.argv[0], err.what);
2061#ifdef DPL_ENABLE_BACKTRACE
2062 std::cerr <<
"\nStacktrace follows:\n\n";
2068 case DriverState::SCHEDULE: {
2073 LOG(info) <<
"Redeployment of configuration asked.";
2074 std::ostringstream forwardedStdin;
2076 infos.reserve(runningWorkflow.devices.size());
2079 unsigned parentCPU = -1;
2080 unsigned parentNode = -1;
2081#if defined(__linux__) && __has_include(<sched.h>)
2082 parentCPU = sched_getcpu();
2083#elif __has_include(<linux/getcpu.h>)
2084 getcpu(&parentCPU, &parentNode,
nullptr);
2085#elif __has_include(<cpuid.h>) && (__x86_64__ || __i386__)
2090 for (
auto& callback : preScheduleCallbacks) {
2091 callback(serviceRegistry, {varmap});
2093 childFds.resize(runningWorkflow.devices.size());
2094 for (
int di = 0;
di < (
int)runningWorkflow.devices.size(); ++
di) {
2095 auto& context = childFds[
di];
2098 if (driverInfo.mode == DriverMode::EMBEDDED || runningWorkflow.devices[
di].resource.hostname != driverInfo.deployHostname) {
2100 runningWorkflow.devices[
di], controls[
di], deviceExecutions[
di], infos, allStates);
2105 runningWorkflow.devices, driverInfo,
2106 controls, deviceExecutions, infos,
2108 serviceRegistry, varmap,
2109 childFds, parentCPU, parentNode);
2114 for (
auto& callback : postScheduleCallbacks) {
2115 callback(serviceRegistry, {varmap});
2117 assert(infos.empty() ==
false);
2122 uv_timer_init(loop, &metricDumpTimer);
2124 driverInfo.resourcesMonitoringDumpInterval * 1000,
2125 driverInfo.resourcesMonitoringDumpInterval * 1000);
2128 for (
const auto& processorInfo : dataProcessorInfos) {
2129 const auto& cmdLineArgs = processorInfo.cmdLineArgs;
2130 if (std::find(cmdLineArgs.begin(), cmdLineArgs.end(),
"--severity") != cmdLineArgs.end()) {
2131 for (
size_t counter = 0;
const auto& spec : runningWorkflow.devices) {
2132 if (spec.name.compare(processorInfo.name) == 0) {
2134 const auto logLevelIt = std::find(cmdLineArgs.begin(), cmdLineArgs.end(),
"--severity") + 1;
2135 if ((*logLevelIt).compare(
"debug") == 0) {
2136 info.logLevel = LogParsingHelpers::LogLevel::Debug;
2137 }
else if ((*logLevelIt).compare(
"detail") == 0) {
2138 info.logLevel = LogParsingHelpers::LogLevel::Debug;
2139 }
else if ((*logLevelIt).compare(
"info") == 0) {
2140 info.logLevel = LogParsingHelpers::LogLevel::Info;
2141 }
else if ((*logLevelIt).compare(
"warning") == 0) {
2142 info.logLevel = LogParsingHelpers::LogLevel::Warning;
2143 }
else if ((*logLevelIt).compare(
"error") == 0) {
2144 info.logLevel = LogParsingHelpers::LogLevel::Error;
2145 }
else if ((*logLevelIt).compare(
"important") == 0) {
2146 info.logLevel = LogParsingHelpers::LogLevel::Info;
2147 }
else if ((*logLevelIt).compare(
"alarm") == 0) {
2148 info.logLevel = LogParsingHelpers::LogLevel::Alarm;
2149 }
else if ((*logLevelIt).compare(
"critical") == 0) {
2150 info.logLevel = LogParsingHelpers::LogLevel::Critical;
2151 }
else if ((*logLevelIt).compare(
"fatal") == 0) {
2152 info.logLevel = LogParsingHelpers::LogLevel::Fatal;
2160 LOG(info) <<
"Redeployment of configuration done.";
2162 case DriverState::RUNNING:
2166 devicesManager->flush();
2170 if (guiTimerExpired ==
false) {
2171 O2_SIGNPOST_EVENT_EMIT(driver, sid,
"mainloop",
"Entering event loop with %{public}s", once ?
"UV_RUN_ONCE" :
"UV_RUN_NOWAIT");
2173 uv_run(loop, once ? UV_RUN_ONCE : UV_RUN_NOWAIT);
2177 if (guiQuitRequested ||
2178 (driverInfo.processingPolicies.termination == TerminationPolicy::QUIT && (
checkIfCanExit(infos) ==
true))) {
2183 LOG(info) <<
"Quitting";
2184 driverInfo.states.push_back(DriverState::QUIT_REQUESTED);
2185 }
else if (infos.size() != runningWorkflow.devices.size()) {
2190 driverInfo.states.push_back(DriverState::RUNNING);
2191 driverInfo.states.push_back(DriverState::REDEPLOY_GUI);
2192 driverInfo.states.push_back(DriverState::SCHEDULE);
2193 driverInfo.states.push_back(DriverState::MERGE_CONFIGS);
2194 }
else if (runningWorkflow.devices.empty() && driverConfig.
batch ==
true) {
2195 LOG(info) <<
"No device resulting from the workflow. Quitting.";
2197 driverInfo.states.push_back(DriverState::EXIT);
2198 }
else if (runningWorkflow.devices.empty() && driverConfig.
batch ==
false && !guiDeployedOnce) {
2200 driverInfo.states.push_back(DriverState::RUNNING);
2201 driverInfo.states.push_back(DriverState::REDEPLOY_GUI);
2203 driverInfo.states.push_back(DriverState::RUNNING);
2206 case DriverState::QUIT_REQUESTED: {
2207 std::time_t
result = std::time(
nullptr);
2211 guiQuitRequested =
true;
2218 force_step_timer.data = &infos;
2220 driverInfo.states.push_back(DriverState::HANDLE_CHILDREN);
2223 case DriverState::HANDLE_CHILDREN: {
2227 uv_run(loop, once ? UV_RUN_ONCE : UV_RUN_NOWAIT);
2232 static bool forcefulExitMessage =
true;
2233 if (forcefulExitMessage) {
2234 LOG(info) <<
"Forceful exit requested.";
2235 forcefulExitMessage =
false;
2241 driverInfo.sigchldRequested =
false;
2246 bool supposedToQuit = (guiQuitRequested || canExit ||
graceful_exit);
2248 if (allChildrenGone && (supposedToQuit || driverInfo.processingPolicies.termination == TerminationPolicy::QUIT)) {
2250 driverInfo.states.resize(0);
2251 driverInfo.states.push_back(DriverState::EXIT);
2252 }
else if (hasError && driverInfo.processingPolicies.error == TerminationPolicy::QUIT && !supposedToQuit) {
2254 force_exit_timer.data = &infos;
2255 static bool forceful_timer_started =
false;
2256 if (forceful_timer_started ==
false) {
2257 forceful_timer_started =
true;
2260 driverInfo.states.push_back(DriverState::QUIT_REQUESTED);
2261 }
else if (allChildrenGone ==
false && supposedToQuit) {
2262 driverInfo.states.push_back(DriverState::HANDLE_CHILDREN);
2266 case DriverState::EXIT: {
2268 if (driverInfo.resourcesMonitoringDumpInterval) {
2269 uv_timer_stop(&metricDumpTimer);
2271 LOG(info) <<
"Dumping performance metrics to performanceMetrics.json file";
2274 dumpRunSummary(serverContext, driverInfo, infos, runningWorkflow.devices);
2281 if (infos.empty()) {
2284 boost::property_tree::ptree finalConfig;
2285 assert(infos.size() == runningWorkflow.devices.size());
2286 for (
size_t di = 0;
di < infos.size(); ++
di) {
2287 auto& info = infos[
di];
2288 auto& spec = runningWorkflow.devices[
di];
2289 finalConfig.put_child(spec.name, info.currentConfig);
2291 LOG(info) <<
"Dumping used configuration in dpl-config.json";
2293 std::ofstream outDPLConfigFile(
"dpl-config.json", std::ios::out);
2294 if (outDPLConfigFile.is_open()) {
2295 boost::property_tree::write_json(outDPLConfigFile, finalConfig);
2297 LOGP(warning,
"Could not write out final configuration file. Read only run folder?");
2299 if (driverInfo.noSHMCleanup) {
2300 LOGP(warning,
"Not cleaning up shared memory.");
2304 return calculateExitCode(driverInfo, runningWorkflow.devices, infos);
2306 case DriverState::PERFORM_CALLBACKS:
2307 for (
auto& callback : driverControl.
callbacks) {
2308 callback(workflow, runningWorkflow.devices, deviceExecutions, dataProcessorInfos, commandInfo);
2313 LOG(error) <<
"Driver transitioned in an unknown state("
2314 <<
"current: " << (
int)current
2315 <<
", previous: " << (
int)previous
2316 <<
"). Shutting down.";
2317 driverInfo.states.push_back(DriverState::QUIT_REQUESTED);
2855 std::vector<ChannelConfigurationPolicy>
const& channelPolicies,
2856 std::vector<CompletionPolicy>
const& completionPolicies,
2857 std::vector<DispatchPolicy>
const& dispatchPolicies,
2858 std::vector<ResourcePolicy>
const& resourcePolicies,
2859 std::vector<CallbacksPolicy>
const& callbacksPolicies,
2860 std::vector<SendingPolicy>
const& sendingPolicies,
2861 std::vector<ConfigParamSpec>
const& currentWorkflowOptions,
2862 std::vector<ConfigParamSpec>
const& detectedParams,
2867 if (getenv(
"DPL_DRIVER_SIGNPOSTS")) {
2871 std::vector<std::string> currentArgs;
2872 std::vector<PluginInfo> plugins;
2875 for (
int ai = 1; ai < argc; ++ai) {
2876 currentArgs.emplace_back(argv[ai]);
2882 currentWorkflowOptions};
2886 bpo::options_description executorOptions(
"Executor options");
2887 const char* helpDescription =
"print help: short, full, executor, or processor name";
2889 executorOptions.add_options()
2890 (
"help,h", bpo::value<std::string>()->implicit_value(
"short"), helpDescription)
2891 (
"quiet,q", bpo::value<bool>()->zero_tokens()->default_value(
false),
"quiet operation")
2892 (
"stop,s", bpo::value<bool>()->zero_tokens()->default_value(
false),
"stop before device start")
2893 (
"single-step", bpo::value<bool>()->zero_tokens()->default_value(
false),
"start in single step mode")
2894 (
"batch,b", bpo::value<std::vector<std::string>>()->zero_tokens()->composing(),
"batch processing mode")
2895 (
"no-batch", bpo::value<bool>()->zero_tokens(),
"force gui processing mode")
2896 (
"no-cleanup", bpo::value<bool>()->zero_tokens()->default_value(
false),
"do not cleanup the shm segment")
2897 (
"hostname", bpo::value<std::string>()->default_value(
"localhost"),
"hostname to deploy")
2898 (
"resources", bpo::value<std::string>()->default_value(
""),
"resources allocated for the workflow")
2899 (
"start-port,p", bpo::value<unsigned short>()->default_value(22000),
"start port to allocate")
2900 (
"port-range,pr", bpo::value<unsigned short>()->default_value(1000),
"ports in range")
2901 (
"completion-policy,c", bpo::value<TerminationPolicy>(&processingPolicies.
termination)->default_value(TerminationPolicy::QUIT),
2902 "what to do when processing is finished: quit, wait")
2903 (
"error-policy", bpo::value<TerminationPolicy>(&processingPolicies.
error)->default_value(TerminationPolicy::QUIT),
2904 "what to do when a device has an error: quit, wait")
2905 (
"min-failure-level", bpo::value<LogParsingHelpers::LogLevel>(&minFailureLevel)->default_value(LogParsingHelpers::LogLevel::Fatal),
2906 "minimum message level which will be considered as fatal and exit with 1")
2907 (
"graphviz,g", bpo::value<bool>()->zero_tokens()->default_value(
false),
"produce graphviz output")
2908 (
"mermaid", bpo::value<std::string>()->default_value(
""),
"produce graph output in mermaid format in file under specified name or on stdout if argument is \"-\"")
2909 (
"timeout,t", bpo::value<uint64_t>()->default_value(0),
"forced exit timeout (in seconds)")
2910 (
"dds,D", bpo::value<std::string>()->default_value(
""),
"create DDS configuration")
2911 (
"dds-workflow-suffix,D", bpo::value<std::string>()->default_value(
""),
"suffix for DDS names")
2912 (
"dump-workflow,dump", bpo::value<bool>()->zero_tokens()->default_value(
false),
"dump workflow as JSON")
2913 (
"dump-workflow-file", bpo::value<std::string>()->default_value(
"-"),
"file to which do the dump")
2914 (
"driver-mode", bpo::value<DriverMode>(&driverMode)->default_value(DriverMode::STANDALONE), R
"(how to run the driver. default: "standalone". Valid: "embedded")")
2915 (
"run", bpo::value<bool>()->zero_tokens()->default_value(
false),
"run workflow merged so far. It implies --batch. Use --no-batch to see the GUI")
2916 (
"no-IPC", bpo::value<bool>()->zero_tokens()->default_value(
false),
"disable IPC topology optimization")
2917 (
"o2-control,o2", bpo::value<std::string>()->default_value(
""),
"dump O2 Control workflow configuration under the specified name")
2918 (
"resources-monitoring", bpo::value<unsigned short>()->default_value(0),
"enable cpu/memory monitoring for provided interval in seconds")
2919 (
"resources-monitoring-dump-interval", bpo::value<unsigned short>()->default_value(0),
"dump monitoring information to disk every provided seconds");
2924 (
"id,i", bpo::value<std::string>(),
"device id for child spawning")
2925 (
"channel-config", bpo::value<std::vector<std::string>>(),
"channel configuration")
2926 (
"control",
"control plugin")
2927 (
"log-color",
"logging color scheme")(
"color",
"logging color scheme");
2929 bpo::options_description visibleOptions;
2930 visibleOptions.add(executorOptions);
2932 auto physicalWorkflow = workflow;
2933 std::map<std::string, size_t> rankIndex;
2940 size_t workflowHashA = 0;
2941 std::hash<std::string> hash_fn;
2943 for (
auto& dp : workflow) {
2944 workflowHashA += hash_fn(dp.name);
2947 for (
auto& dp : workflow) {
2948 rankIndex.insert(std::make_pair(dp.name, workflowHashA));
2951 std::vector<DataProcessorInfo> dataProcessorInfos;
2955 std::vector<DataProcessorSpec> importedWorkflow;
2957 if (previousWorked ==
false) {
2961 size_t workflowHashB = 0;
2962 for (
auto& dp : importedWorkflow) {
2963 workflowHashB += hash_fn(dp.name);
2970 for (
auto& dp : importedWorkflow) {
2971 auto found = std::find_if(physicalWorkflow.begin(), physicalWorkflow.end(),
2973 if (found == physicalWorkflow.end()) {
2974 physicalWorkflow.push_back(dp);
2975 rankIndex.insert(std::make_pair(dp.name, workflowHashB));
2984 for (
auto& dp : physicalWorkflow) {
2986 if (std::find_if(dp.labels.begin(), dp.labels.end(), isExpendable) != dp.labels.end()) {
2987 for (
auto&
output : dp.outputs) {
2988 if (
output.lifetime == Lifetime::Timeframe) {
2989 output.lifetime = Lifetime::Sporadic;
3000 auto reader = std::find_if(physicalWorkflow.begin(), physicalWorkflow.end(), [](
DataProcessorSpec& spec) { return spec.name ==
"internal-dpl-aod-reader"; });
3001 if (reader != physicalWorkflow.end()) {
3004 for (
auto& service : driverServices) {
3005 if (service.injectTopology ==
nullptr) {
3009 service.injectTopology(node, configContext);
3011 for (
auto& dp : physicalWorkflow) {
3012 if (dp.name.rfind(
"internal-", 0) == 0) {
3013 rankIndex.insert(std::make_pair(dp.name, hash_fn(
"internal")));
3020 return a.name < b.name;
3023 for (
auto& dp : physicalWorkflow) {
3024 std::stable_sort(dp.inputs.begin(), dp.inputs.end(),
3025 [](
InputSpec const&
a,
InputSpec const&
b) { return DataSpecUtils::describe(a) < DataSpecUtils::describe(b); });
3026 std::stable_sort(dp.outputs.begin(), dp.outputs.end(),
3027 [](
OutputSpec const&
a,
OutputSpec const&
b) { return DataSpecUtils::describe(a) < DataSpecUtils::describe(b); });
3032 std::vector<std::pair<int, int>> edges;
3034 if (physicalWorkflow.size() > 1) {
3038 if (topoInfos.size() != physicalWorkflow.size()) {
3041 throw std::runtime_error(
"Unable to do topological sort of the resulting workflow. Do you have loops?\n" +
debugTopoInfo(physicalWorkflow, topoInfos, edges));
3045 auto aRank = std::make_tuple(a.layer, -workflow.at(a.index).outputs.size(), workflow.at(a.index).name);
3046 auto bRank = std::make_tuple(b.layer, -workflow.at(b.index).outputs.size(), workflow.at(b.index).name);
3047 return aRank < bRank;
3050 std::vector<int> dataProcessorOrder;
3051 dataProcessorOrder.resize(topoInfos.size());
3052 for (
size_t i = 0;
i < topoInfos.size(); ++
i) {
3053 dataProcessorOrder[topoInfos[
i].index] =
i;
3055 std::vector<int> newLocations;
3056 newLocations.resize(dataProcessorOrder.size());
3057 for (
size_t i = 0;
i < dataProcessorOrder.size(); ++
i) {
3058 newLocations[dataProcessorOrder[
i]] =
i;
3068 bpo::options_description od;
3069 od.add(visibleOptions);
3074 using namespace bpo::command_line_style;
3075 auto style = (allow_short | short_allow_adjacent | short_allow_next | allow_long | long_allow_adjacent | long_allow_next | allow_sticky | allow_dash_for_short);
3076 bpo::variables_map varmap;
3079 bpo::command_line_parser(argc, argv)
3084 }
catch (std::exception
const& e) {
3085 LOGP(error,
"error parsing options of {}: {}", argv[0], e.what());
3101 if (varmap.count(
"help")) {
3102 printHelp(varmap, executorOptions, physicalWorkflow, currentWorkflowOptions);
3108 if (varmap.count(
"severity")) {
3109 auto logLevel = varmap[
"severity"].as<std::string>();
3110 if (logLevel ==
"debug") {
3111 fair::Logger::SetConsoleSeverity(fair::Severity::debug);
3112 }
else if (logLevel ==
"detail") {
3113 fair::Logger::SetConsoleSeverity(fair::Severity::detail);
3114 }
else if (logLevel ==
"info") {
3115 fair::Logger::SetConsoleSeverity(fair::Severity::info);
3116 }
else if (logLevel ==
"warning") {
3117 fair::Logger::SetConsoleSeverity(fair::Severity::warning);
3118 }
else if (logLevel ==
"error") {
3119 fair::Logger::SetConsoleSeverity(fair::Severity::error);
3120 }
else if (logLevel ==
"important") {
3121 fair::Logger::SetConsoleSeverity(fair::Severity::important);
3122 }
else if (logLevel ==
"alarm") {
3123 fair::Logger::SetConsoleSeverity(fair::Severity::alarm);
3124 }
else if (logLevel ==
"critical") {
3125 fair::Logger::SetConsoleSeverity(fair::Severity::critical);
3126 }
else if (logLevel ==
"fatal") {
3127 fair::Logger::SetConsoleSeverity(fair::Severity::fatal);
3129 LOGP(error,
"Invalid log level '{}'", logLevel);
3136 auto evaluateBatchOption = [&varmap]() ->
bool {
3137 if (varmap.count(
"no-batch") > 0) {
3140 if (varmap.count(
"batch") == 0) {
3142 return isatty(fileno(stdout)) == 0;
3151 DriverInfo driverInfo{
3152 .sendingPolicies = sendingPolicies,
3153 .forwardingPolicies = forwardingPolicies,
3154 .callbacksPolicies = callbacksPolicies};
3155 driverInfo.states.reserve(10);
3156 driverInfo.sigintRequested =
false;
3157 driverInfo.sigchldRequested =
false;
3158 driverInfo.channelPolicies = channelPolicies;
3159 driverInfo.completionPolicies = completionPolicies;
3160 driverInfo.dispatchPolicies = dispatchPolicies;
3161 driverInfo.resourcePolicies = resourcePolicies;
3162 driverInfo.argc = argc;
3163 driverInfo.argv = argv;
3164 driverInfo.noSHMCleanup = varmap[
"no-cleanup"].as<
bool>();
3165 driverInfo.processingPolicies.termination = varmap[
"completion-policy"].as<
TerminationPolicy>();
3166 driverInfo.processingPolicies.earlyForward = varmap[
"early-forward-policy"].as<
EarlyForwardPolicy>();
3167 driverInfo.mode = varmap[
"driver-mode"].as<
DriverMode>();
3169 auto batch = evaluateBatchOption();
3172 .driverHasGUI = (batch ==
false) || getenv(
"DPL_DRIVER_REMOTE_GUI") !=
nullptr,
3175 if (varmap[
"error-policy"].defaulted() && driverConfig.batch ==
false) {
3176 driverInfo.processingPolicies.error = TerminationPolicy::WAIT;
3178 driverInfo.processingPolicies.error = varmap[
"error-policy"].as<
TerminationPolicy>();
3181 driverInfo.startTime = uv_hrtime();
3182 driverInfo.startTimeMsFromEpoch = std::chrono::duration_cast<std::chrono::milliseconds>(
3183 std::chrono::system_clock::now().time_since_epoch())
3185 driverInfo.timeout = varmap[
"timeout"].as<uint64_t>();
3186 driverInfo.deployHostname = varmap[
"hostname"].as<std::string>();
3187 driverInfo.resources = varmap[
"resources"].as<std::string>();
3188 driverInfo.resourcesMonitoringInterval = varmap[
"resources-monitoring"].as<
unsigned short>();
3189 driverInfo.resourcesMonitoringDumpInterval = varmap[
"resources-monitoring-dump-interval"].as<
unsigned short>();
3192 driverInfo.processorInfo = dataProcessorInfos;
3193 driverInfo.configContext = &configContext;
3200 std::string frameworkId;
3203 if (varmap.count(
"id")) {
3207 frameworkId = std::regex_replace(varmap[
"id"].as<std::string>(), std::regex{
"_dds.*"},
"");
3208 driverInfo.uniqueWorkflowId = fmt::format(
"{}", getppid());
3209 driverInfo.defaultDriverClient =
"stdout://";
3211 driverInfo.uniqueWorkflowId = fmt::format(
"{}", getpid());
3212 driverInfo.defaultDriverClient =
"ws://";