2626import threading
2727from http .server import BaseHTTPRequestHandler , HTTPServer
2828from socketserver import ThreadingMixIn
29+ from typing import Dict , List
2930from urllib .parse import parse_qs , urlparse
3031
3132from prometheus_client import REGISTRY
@@ -124,16 +125,33 @@ def generate_latest(registry, emit_help=False):
124125 )
125126 )
126127 output .append ("# TYPE {0} {1}\n " .format (mname , mtype ))
127- for sample in metric .samples :
128- # Get rid of the OpenMetrics specific samples
128+
129+ om_samples = {} # type: Dict[str, List[str]]
130+ for s in metric .samples :
129131 for suffix in ["_created" , "_gsum" , "_gcount" ]:
130- if sample .name .endswith (suffix ):
132+ if s .name == metric .name + suffix :
133+ # OpenMetrics specific sample, put in a gauge at the end.
134+ # (these come from gaugehistograms which don't get renamed,
135+ # so no need to faff with mnewname)
136+ om_samples .setdefault (suffix , []).append (sample_line (s , s .name ))
131137 break
132138 else :
133- newname = sample .name .replace (mnewname , mname )
139+ newname = s .name .replace (mnewname , mname )
134140 if ":" in newname and newname .endswith ("_total" ):
135141 newname = newname [: - len ("_total" )]
136- output .append (sample_line (sample , newname ))
142+ output .append (sample_line (s , newname ))
143+
144+ for suffix , lines in sorted (om_samples .items ()):
145+ if emit_help :
146+ output .append (
147+ "# HELP {0}{1} {2}\n " .format (
148+ metric .name ,
149+ suffix ,
150+ metric .documentation .replace ("\\ " , r"\\" ).replace ("\n " , r"\n" ),
151+ )
152+ )
153+ output .append ("# TYPE {0}{1} gauge\n " .format (metric .name , suffix ))
154+ output .extend (lines )
137155
138156 # Get rid of the weird colon things while we're at it
139157 if mtype == "counter" :
@@ -152,16 +170,16 @@ def generate_latest(registry, emit_help=False):
152170 )
153171 )
154172 output .append ("# TYPE {0} {1}\n " .format (mnewname , mtype ))
155- for sample in metric .samples :
156- # Get rid of the OpenMetrics specific samples
173+
174+ for s in metric .samples :
175+ # Get rid of the OpenMetrics specific samples (we should already have
176+ # dealt with them above anyway.)
157177 for suffix in ["_created" , "_gsum" , "_gcount" ]:
158- if sample .name . endswith ( suffix ) :
178+ if s .name == metric . name + suffix :
159179 break
160180 else :
161181 output .append (
162- sample_line (
163- sample , sample .name .replace (":total" , "" ).replace (":" , "_" )
164- )
182+ sample_line (s , s .name .replace (":total" , "" ).replace (":" , "_" ))
165183 )
166184
167185 return "" .join (output ).encode ("utf-8" )
0 commit comments