Skip to content

Commit 6e80a8e

Browse files
authored
Keep the sign of a negative OpenMetrics timestamp between -1 and 0 (#1253)
* Test parsing a negative timestamp between -1 and 0 Signed-off-by: Christopher Krah <48338417+chrikrah@users.noreply.github.com> * Keep the sign of a negative timestamp between -1 and 0 in the OpenMetrics parser Signed-off-by: Christopher Krah <48338417+chrikrah@users.noreply.github.com> --------- Signed-off-by: Christopher Krah <48338417+chrikrah@users.noreply.github.com>
1 parent e2f2bf9 commit 6e80a8e

2 files changed

Lines changed: 20 additions & 1 deletion

File tree

‎prometheus_client/openmetrics/parser.py‎

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -91,7 +91,12 @@ def _parse_timestamp(timestamp):
9191
try:
9292
# aaaa.bbbb. Nanosecond resolution supported.
9393
parts = timestamp.split('.', 1)
94-
return Timestamp(int(parts[0]), int(parts[1][:9].ljust(9, "0")))
94+
sec = int(parts[0])
95+
nsec = int(parts[1][:9].ljust(9, "0"))
96+
if sec == 0 and parts[0].startswith('-'):
97+
# int("-0") is 0, so carry the sign the way Timestamp(-0.5, 500000000) does.
98+
return Timestamp(-nsec / 1e9, nsec)
99+
return Timestamp(sec, nsec)
95100
except ValueError:
96101
# Float.
97102
ts = float(timestamp)

‎tests/openmetrics/test_parser.py‎

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -627,6 +627,20 @@ def test_null_byte(self):
627627
metric_family = CounterMetricFamily("a", "he\0lp")
628628
self.assertEqual([metric_family], list(families))
629629

630+
def test_negative_subsecond_timestamps(self):
631+
families = text_string_to_metric_families("""# TYPE a counter
632+
# HELP a help
633+
a_total{foo="1"} 1 -0.500000000
634+
a_total{foo="2"} 1 -1.500000000 # {a="b"} 0.5 -0.250000000
635+
# EOF
636+
""")
637+
a = CounterMetricFamily("a", "help", labels=["foo"])
638+
a.add_metric(["1"], 1, timestamp=Timestamp(-0.5, 500000000))
639+
a.add_metric(["2"], 1, timestamp=Timestamp(-1, 500000000))
640+
a.samples[1] = a.samples[1]._replace(exemplar=Exemplar({"a": "b"}, 0.5, Timestamp(-0.25, 250000000)))
641+
self.assertEqual([a], list(families))
642+
self.assertEqual("-0.500000000", str(a.samples[0].timestamp))
643+
630644
def test_timestamps(self):
631645
families = text_string_to_metric_families("""# TYPE a counter
632646
# HELP a help

0 commit comments

Comments
 (0)