Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,8 @@
#ifndef DIAGNOSTIC_REMOTE_LOGGING__INFLUX_LINE_PROTOCOL_HPP_
#define DIAGNOSTIC_REMOTE_LOGGING__INFLUX_LINE_PROTOCOL_HPP_

#include <cmath>
#include <sstream>
#include <string>
#include <tuple>
#include <utility>
Expand Down Expand Up @@ -74,11 +76,71 @@ std::string escapeSpace(const std::string & input)
return result;
}

// Escape the characters that are special in a measurement name (comma and
// space). Newlines are dropped: InfluxDB uses '\n' to separate points, so a
// newline inside a diagnostic string would split or corrupt the written line.
std::string escapeMeasurement(const std::string & input)
{
std::string result;
for (char c : input) {
if (c == '\n') {
continue;
}
if (c == ',' || c == ' ') {
result += '\\';
}
result += c;
}
return result;
}

// Escape the characters that are special in tag keys and tag values as well
// as in field keys (comma, equals sign and space). Newlines are dropped as
// in escapeMeasurement.
std::string escapeTag(const std::string & input)
{
std::string result;
for (char c : input) {
if (c == '\n') {
continue;
}
if (c == ',' || c == '=' || c == ' ') {
result += '\\';
}
result += c;
}
return result;
}

// Escape the characters that are special inside a quoted string field value
// (backslash and double quote). Newlines are dropped as in escapeMeasurement.
std::string escapeStringFieldValue(const std::string & input)
{
std::string result;
for (char c : input) {
if (c == '\n') {
continue;
}
if (c == '\\' || c == '"') {
result += '\\';
}
result += c;
}
return result;
}

bool is_number(const std::string & s)
{
std::istringstream iss(s);
double d;
return iss >> std::noskipws >> d && iss.eof();
if (!(iss >> std::noskipws >> d) || !iss.eof()) {
return false;
}
// Depending on the standard library, "nan" and "inf" either fail to parse
// as doubles or yield a non-finite value; either way they are not valid
// line-protocol float literals, so anything non-finite must be written as
// a string.
return std::isfinite(d);
}

std::string formatValues(const std::vector<diagnostic_msgs::msg::KeyValue> & values)
Expand All @@ -91,12 +153,12 @@ std::string formatValues(const std::vector<diagnostic_msgs::msg::KeyValue> & val
continue;
}

formatted += escapeSpace(kv.key) + "=";
formatted += escapeTag(kv.key) + "=";

if (is_number(kv.value)) {
formatted += kv.value;
} else {
formatted += "\"" + kv.value + "\"";
formatted += "\"" + escapeStringFieldValue(kv.value) + "\"";
}
formatted += ",";
}
Expand Down Expand Up @@ -138,20 +200,20 @@ void statusToInfluxLineProtocol(
const std::string & timestamp_str)
{
auto [ns, node, name] = splitName(status.name);
output += escapeSpace(node);
output += escapeMeasurement(node);
if (!ns.empty()) {
output += ",ns=" + escapeSpace(ns);
output += ",ns=" + escapeTag(ns);
}
if (!name.empty()) {
output += ",name=" + escapeSpace(name);
output += ",name=" + escapeTag(name);
}
if (!status.hardware_id.empty()) {
output += ",hardware_id=" + escapeSpace(status.hardware_id);
output += ",hardware_id=" + escapeTag(status.hardware_id);
}
output += " level=" + std::to_string(status.level);

if (!status.message.empty()) {
output += ",message=\"" + status.message + "\"";
output += ",message=\"" + escapeStringFieldValue(status.message) + "\"";
}

auto formatted_key_values = formatValues(status.values);
Expand Down
71 changes: 71 additions & 0 deletions diagnostic_remote_logging/test/influx_line_protocol.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -70,6 +70,26 @@ TEST(EscapeSpaceTests, HandlesSpaces)
EXPECT_EQ(escapeSpace("multiple spaces here"), "multiple\\ spaces\\ here");
}

// Regression: line-protocol special characters in diagnostic text must be
// escaped so that they cannot corrupt the points written to the database.
TEST(EscapeTests, MeasurementEscapesCommasAndSpaces)
{
EXPECT_EQ(escapeMeasurement("node,x=1 y"), "node\\,x=1\\ y");
EXPECT_EQ(escapeMeasurement("first\nsecond,x=1"), "firstsecond\\,x=1");
}

TEST(EscapeTests, TagEscapesCommasEqualsAndSpaces)
{
EXPECT_EQ(escapeTag("a,b=c d"), "a\\,b\\=c\\ d");
EXPECT_EQ(escapeTag("line1\nline2"), "line1line2");
}

TEST(EscapeTests, StringFieldValueEscapesQuotesAndBackslashes)
{
EXPECT_EQ(escapeStringFieldValue("say \"hi\", ok\\no"), "say \\\"hi\\\", ok\\\\no");
EXPECT_EQ(escapeStringFieldValue("line1\nline2"), "line1line2");
}

// Test is_number
TEST(IsNumberTests, ValidatesNumbers)
{
Expand All @@ -81,6 +101,16 @@ TEST(IsNumberTests, ValidatesNumbers)
EXPECT_FALSE(is_number(""));
}

// Regression: depending on the standard library, "nan" and "inf" either fail
// to parse as doubles or parse as non-finite values; either way they are not
// valid line-protocol float literals and must be written as quoted strings.
TEST(IsNumberTests, RejectsNonFinite)
{
EXPECT_FALSE(is_number("nan"));
EXPECT_FALSE(is_number("inf"));
EXPECT_FALSE(is_number("-inf"));
}

// Test formatValues
TEST(FormatValuesTests, FormatsKeyValuePairs)
{
Expand Down Expand Up @@ -189,3 +219,44 @@ TEST(TopLevelStatusTests, HandlesTopLevelStatus)
std::string expected = "toplevel_state level=1 1672531200123456789\n";
EXPECT_EQ(output, expected);
}

// Regression: a message containing a quote and a newline must stay inside
// one point instead of splitting the line.
TEST(StatusToInfluxLineProtocolTests, MessageWithQuoteAndNewlineStaysOnOneLine)
{
diagnostic_msgs::msg::DiagnosticStatus status;
status.name = "sensor_node: Temperature";
status.message = "ok\",a=\"b\"\nsecond,t=1 f=1";

std::string output;
statusToInfluxLineProtocol(output, status, "1672531200123456789");

// Exactly one line: the only newline is the trailing one.
EXPECT_EQ(output.back(), '\n');
EXPECT_EQ(output.find('\n'), output.size() - 1);
EXPECT_EQ(
output,
"sensor_node,name=Temperature level=0,message=\"ok\\\",a=\\\"b\\\""
"second,t=1 f=1\" 1672531200123456789\n");
}

// Regression: ordinary punctuation in diagnostic text must
// not make the line invalid — commas/equals in identifying strings are
// escaped, and non-finite numeric-looking values are written as strings.
TEST(StatusToInfluxLineProtocolTests, BenignSpecialCharactersStayValid)
{
diagnostic_msgs::msg::DiagnosticStatus status;
status.name = "/ns/node";
status.hardware_id = "device,rev=2";
status.message = "Voltage: 11.1V";
status.values.push_back(createKeyValue("v,key", "NaN"));

std::string output;
statusToInfluxLineProtocol(output, status, "1672531200123456789");

EXPECT_EQ(output.find('\n'), output.size() - 1);
EXPECT_EQ(
output,
"node,ns=ns,hardware_id=device\\,rev\\=2 level=0,message=\"Voltage: 11.1V\","
"v\\,key=\"NaN\" 1672531200123456789\n");
}