Browse Source

Exposition: escape special characters in help and label values.

pull/6/head
Fredrik Ekre 2 years ago
parent
commit
696d9c1864
  1. 19
      src/Prometheus.jl
  2. 15
      test/runtests.jl

19
src/Prometheus.jl

@ -612,8 +612,21 @@ struct Metric @@ -612,8 +612,21 @@ struct Metric
samples::Union{Sample, Vector{Sample}}
end
function print_escaped(io::IO, help::String, esc)
for c in help
if c in esc
c == '\n' ? print(io, "\\n") : print(io, '\\', c)
else
print(io, c)
end
end
return
end
function expose_metric(io::IO, metric::Metric)
println(io, "# HELP ", metric.metric_name, " ", metric.help)
print(io, "# HELP ", metric.metric_name, " ")
print_escaped(io, metric.help, ('\\', '\n'))
println(io)
println(io, "# TYPE ", metric.metric_name, " ", metric.type)
labelnames = metric.labelnames
samples = metric.samples
@ -641,7 +654,9 @@ function expose_metric(io::IO, metric::Metric) @@ -641,7 +654,9 @@ function expose_metric(io::IO, metric::Metric)
print(io, "{")
for (name, value) in zip(labelnames.labelnames, labels.labelvalues)
first || print(io, ",")
print(io, name, "=\"", value, "\"")
print(io, name, "=\"")
print_escaped(io, value, ('\\', '\"', '\n'))
print(io, "\"")
first = false
end
print(io, "}")

15
test/runtests.jl

@ -422,6 +422,21 @@ end @@ -422,6 +422,21 @@ end
end
end
@testset "Character escaping in exposition" begin
counter = Prometheus.Family{Prometheus.Counter}(
"counter_name", "Help with slash \\ and newline \n", ("label_name", );
registry = nothing,
)
Prometheus.inc(Prometheus.labels(counter, ("backslash \\, quote \", newline \n", )))
metric = first(Prometheus.collect(counter))
@test sprint(Prometheus.expose_metric, metric) ==
"""
# HELP counter_name Help with slash \\\\ and newline \\n
# TYPE counter_name counter
counter_name{label_name="backslash \\\\, quote \\", newline \\n"} 1
"""
end
@testset "Prometheus.expose(::Union{String, IO})" begin
r = Prometheus.DEFAULT_REGISTRY
empty!(r.collectors)

Loading…
Cancel
Save