* Copyright (c) 2025-2026 IB-Robot Group & openEuler Embedded SIG & openharmony-robot sig_RoboFrame.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "doctor_command.h"
#include <charconv>
#include <chrono>
#include <cmath>
#include <exception>
#include <iomanip>
#include <iostream>
#include <iterator>
#include <stdexcept>
#include <string>
#include <vector>
#include "cli/command.h"
#include "discovery_options.h"
#include "engine/discovery/registry_discovery_provider.h"
#include "topic_check.h"
#include "qos_check.h"
#include "log_doctor.h"
#include "module_doctor.h"
namespace ibmw::cli::doctor {
namespace {
std::chrono::milliseconds ParseTimeout(const Invocation& invocation)
{
const auto value = invocation.OptionValue("--timeout", "2");
double seconds = 0;
const auto [end, error] = std::from_chars(value.data(), value.data() + value.size(), seconds);
if (error != std::errc{} || end != value.data() + value.size() || !std::isfinite(seconds) || seconds < 0.01 ||
seconds > 60) {
throw std::invalid_argument("--timeout must be between 0.01 and 60 seconds.");
}
return std::chrono::milliseconds(static_cast<int64_t>(seconds * 1000));
}
discovery::DiscoverySnapshot CollectTopics(const std::vector<discovery::DiscoveryOptions>& options,
std::chrono::milliseconds timeout)
{
discovery::DiscoverySnapshot snapshot;
std::vector<discovery::DiscoveryOptions> network;
for (const auto& option : options) {
if (option.backend != discovery::DiscoveryBackend::kRegistry) {
network.push_back(option);
continue;
}
try {
discovery::RegistryDiscoveryProvider provider;
provider.Start(option);
snapshot = provider.QueryReadOnly();
provider.Stop();
} catch (const std::exception& error) {
snapshot.sources.push_back({.source = discovery::DescribeSource(option),
.status = discovery::DiscoveryStatus::kError,
.message = error.what()});
}
}
if (!network.empty()) {
auto remote = discovery::Discover(network, timeout);
snapshot.sources.insert(snapshot.sources.end(), std::make_move_iterator(remote.sources.begin()),
std::make_move_iterator(remote.sources.end()));
snapshot.endpoints.insert(snapshot.endpoints.end(), std::make_move_iterator(remote.endpoints.begin()),
std::make_move_iterator(remote.endpoints.end()));
}
return snapshot;
}
const char* StatusName(CheckStatus status)
{
switch (status) {
case CheckStatus::kOk:
return "OK";
case CheckStatus::kWarning:
return "WARN";
case CheckStatus::kUnknown:
return "UNKNOWN";
case CheckStatus::kSkipped:
return "SKIP";
}
return "UNKNOWN";
}
void PrintResult(const TopicCheckResult& result, bool details)
{
std::cout << '[' << StatusName(result.status) << "] topic";
if (!result.topic.empty()) {
std::cout << ' ' << std::quoted(result.topic);
}
std::cout << " source=" << discovery::BackendName(result.source.backend);
if (!result.source.domain.empty()) {
std::cout << " domain=" << std::quoted(result.source.domain);
}
if (!result.source.instance_id.empty()) {
std::cout << " instance=" << std::quoted(result.source.instance_id);
}
if (!result.topic.empty()) {
std::cout << " type=" << std::quoted(result.type.empty() ? "<unknown>" : result.type);
std::cout << " publishers=" << result.publishers << " subscribers=" << result.subscribers;
}
std::cout << '\n' << " " << result.message << '\n';
if (details && result.status == CheckStatus::kWarning) {
std::cout << " Suggestion: check the expected subscriber, selected source/domain, and discovery window.\n";
}
}
struct StatusCounts {
size_t ok = 0;
size_t warnings = 0;
size_t unknown = 0;
size_t skipped = 0;
void Add(CheckStatus status)
{
switch (status) {
case CheckStatus::kOk:
++ok;
break;
case CheckStatus::kWarning:
++warnings;
break;
case CheckStatus::kUnknown:
++unknown;
break;
case CheckStatus::kSkipped:
++skipped;
break;
}
}
};
bool NeedsAttention(CheckStatus status)
{
return status == CheckStatus::kWarning || status == CheckStatus::kUnknown;
}
void ValidateDoctorOptions(const Invocation& invocation)
{
for (const auto& [name, values] : invocation.options) {
if (name != "--expect-level" && values.size() != 1) {
throw std::invalid_argument(name + " must be specified once.");
}
}
if (invocation.HasOption("--report") && invocation.HasOption("--report-failed")) {
throw std::invalid_argument("--report and --report-failed are mutually exclusive.");
}
}
StatusCounts PrintTopicResults(const std::vector<TopicCheckResult>& results, bool report, bool details)
{
StatusCounts counts;
for (const auto& result : results) {
counts.Add(result.status);
if (report || NeedsAttention(result.status)) {
PrintResult(result, details);
}
}
if (!report && counts.ok == 0 && counts.warnings == 0 && counts.unknown == 0) {
std::cout << "[SKIP] topic: no visible publisher endpoints to check in the selected sources.\n";
}
return counts;
}
void PrintDiscoveryScope(const discovery::DiscoverySnapshot& snapshot, std::chrono::milliseconds timeout)
{
for (const auto& source : snapshot.sources) {
if (!source.observed_at) {
continue;
}
const auto observedMs =
std::chrono::duration_cast<std::chrono::milliseconds>(source.observed_at->time_since_epoch()).count();
std::cout << "Observed source=" << discovery::BackendName(source.source.backend);
std::cout << " domain=" << std::quoted(source.source.domain);
std::cout << " instance=" << std::quoted(source.source.instance_id) << " at_unix_ms=" << observedMs << '\n';
}
std::cout << "Network discovery window: " << timeout.count() << " ms (registry is a local snapshot).\n";
std::cout << "Scope: selected sources only; topic presence and per-policy QoS checks do not prove delivery.\n";
}
void PrintQosResult(const QosCheckResult& result)
{
std::cout << '[' << StatusName(result.status) << "] qos topic=" << std::quoted(result.topic);
std::cout << " source=" << discovery::BackendName(result.source.backend);
std::cout << " domain=" << std::quoted(result.source.domain);
std::cout << " instance=" << std::quoted(result.source.instance_id) << " driver=" << std::quoted(result.driver);
std::cout << " type=" << std::quoted(result.type) << " policy=" << result.policy << '\n';
if (!result.publisher.empty()) {
std::cout << " publisher=" << std::quoted(result.publisher) << '\n';
}
if (!result.subscriber.empty()) {
std::cout << " subscriber=" << std::quoted(result.subscriber) << '\n';
}
if (!result.offered.empty()) {
if (!result.publisher.empty() && !result.subscriber.empty()) {
std::cout << " offered=" << std::quoted(result.offered) << " requested=" << std::quoted(result.requested);
std::cout << '\n';
} else {
std::cout << " value=" << std::quoted(result.offered) << '\n';
}
}
std::cout << " " << result.message << '\n';
}
StatusCounts PrintQosResults(const std::vector<QosCheckResult>& results, bool report)
{
StatusCounts counts;
for (const auto& result : results) {
counts.Add(result.status);
if (report || NeedsAttention(result.status)) {
PrintQosResult(result);
}
}
std::cout << "QoS policy checks: " << counts.ok << " OK, " << counts.warnings << " WARN, " << counts.unknown;
std::cout << " UNKNOWN, " << counts.skipped << " SKIP\n";
return counts;
}
int Run(const Invocation& invocation)
{
ValidateDoctorOptions(invocation);
const auto timeout = ParseTimeout(invocation);
const auto options = topic::ParseDiscoveryOptions(invocation);
const auto logOptions = PrepareLogCheck(invocation, true);
const auto moduleOptions = PrepareModuleCheck(invocation);
const auto snapshot = CollectTopics(options, timeout);
const auto results = CheckTopics(snapshot, invocation.HasOption("--include-hidden-topics"));
const auto qosResults = CheckQos(snapshot, invocation.HasOption("--include-hidden-topics"));
const bool report = invocation.HasOption("--report");
const bool details = report || invocation.HasOption("--report-failed");
const StatusCounts topics = PrintTopicResults(results, report, details);
if (details) {
PrintDiscoveryScope(snapshot, timeout);
}
std::cout << "Topic checks: " << topics.ok << " OK, " << topics.warnings << " WARN, " << topics.unknown;
std::cout << " UNKNOWN, " << topics.skipped << " SKIP\n";
const StatusCounts qos = PrintQosResults(qosResults, report);
size_t unknown = topics.unknown + qos.unknown;
size_t warnings = topics.warnings + qos.warnings;
const auto modules = RunModuleChecks(moduleOptions, invocation);
warnings += modules.warnings;
const auto logs = RunLogChecks(logOptions, invocation);
unknown += logs.unknown;
warnings += logs.warnings;
std::cout << "Doctor checks: " << warnings << " WARN, " << unknown << " UNKNOWN";
if (modules.query_errors) {
std::cout << "; module query errors: " << modules.query_errors;
}
std::cout << '\n';
if (logs.interrupted) {
return logs.interrupted;
}
if (unknown != 0 || modules.query_errors != 0) {
return 2;
}
return warnings != 0 && invocation.HasOption("--include-warnings") ? 1 : 0;
}
void AddDoctorOptions(Command& command)
{
topic::AddDiscoveryOptions(command);
command.AddOption(
"--timeout", {}, "seconds",
"Topic discovery window (default: 2), 0.01..60 seconds; explicit value also sets log RPC deadline",
OptionValueMode::REQUIRED);
command.AddOption("--report", {}, {}, "Print all topic, QoS, module and log results, including coverage gaps");
command.AddOption("--report-failed", {}, {}, "Print details for warnings and incomplete checks");
command.AddOption("--include-warnings", {}, {},
"Return failure (1) when topic, QoS, module or log warnings are found");
command.AddOption("--include-hidden-topics", {}, {}, "Consider hidden topics as well");
AddLogDoctorOptions(command, true);
AddModuleDoctorOptions(command, true);
}
void AddDoctorSubcommands(Command& command, bool& invoked)
{
auto& module = command.AddSubcommand("module", "Check only recorded module initialization/start results");
AddModuleDoctorOptions(module, false);
module.SetHandler([&invoked](const Invocation& invocation) {
invoked = true;
return RunModuleDoctor(invocation);
});
auto& log = command.AddSubcommand("log", "Check only runtime logger levels through the existing log service");
AddLogDoctorOptions(log, false);
log.SetHandler([&invoked](const Invocation& invocation) {
invoked = true;
return RunLogDoctor(invocation);
});
}
int RunWithArguments(Command& command, int argc, const char* const * argv)
{
std::vector<std::string> arguments;
for (int index = 0; index < argc; ++index) {
arguments.emplace_back(argv[index]);
}
std::vector<char*> mutableArgv;
for (auto& argument : arguments) {
mutableArgv.push_back(argument.data());
}
return command.Run(static_cast<int>(mutableArgv.size()), mutableArgv.data());
}
}
}
int RunDoctorCommand(int argc, const char* const * argv)
{
using namespace ibmw::cli;
try {
Command command("ibmw doctor", "Check topics, DDS/ROS 2 QoS, module lifecycle results and runtime log levels");
bool invoked = false;
command.SetHandler([&invoked](const Invocation& invocation) {
invoked = true;
return doctor::Run(invocation);
});
doctor::AddDoctorOptions(command);
doctor::AddDoctorSubcommands(command, invoked);
if (argc <= 1) {
return doctor::Run({});
}
const auto code = doctor::RunWithArguments(command, argc, argv);
return !invoked && code != 0 ? 2 : code;
} catch (const std::exception& error) {
std::cerr << "ibmw doctor: error: " << error.what() << '\n';
} catch (...) {
std::cerr << "ibmw doctor: error: Unknown failure.\n";
}
return 2;
}