@@ -12,11 +12,13 @@ class CollectorRegistry(object):
12
12
exposition formats.
13
13
"""
14
14
15
- def __init__ (self , auto_describe = False ):
15
+ def __init__ (self , auto_describe = False , target_info = None ):
16
16
self ._collector_to_names = {}
17
17
self ._names_to_collectors = {}
18
18
self ._auto_describe = auto_describe
19
19
self ._lock = Lock ()
20
+ self ._target_info = {}
21
+ self .set_target_info (target_info )
20
22
21
23
def register (self , collector ):
22
24
"""Add a collector to the registry."""
@@ -69,8 +71,13 @@ def _get_names(self, collector):
69
71
def collect (self ):
70
72
"""Yields metrics from the collectors in the registry."""
71
73
collectors = None
74
+ ti = None
72
75
with self ._lock :
73
76
collectors = copy .copy (self ._collector_to_names )
77
+ if self ._target_info :
78
+ ti = self ._target_info_metric ()
79
+ if ti :
80
+ yield ti
74
81
for collector in collectors :
75
82
for metric in collector .collect ():
76
83
yield metric
@@ -87,11 +94,13 @@ def restricted_registry(self, names):
87
94
Experimental."""
88
95
names = set (names )
89
96
collectors = set ()
97
+ metrics = []
90
98
with self ._lock :
91
99
for name in names :
92
100
if name in self ._names_to_collectors :
93
101
collectors .add (self ._names_to_collectors [name ])
94
- metrics = []
102
+ if 'target_info' in names and self ._target_info :
103
+ metrics .append (self ._target_info_metric ())
95
104
for collector in collectors :
96
105
for metric in collector .collect ():
97
106
samples = [s for s in metric .samples if s [0 ] in names ]
@@ -106,6 +115,25 @@ def collect(self):
106
115
107
116
return RestrictedRegistry ()
108
117
118
+ def set_target_info (self , labels ):
119
+ with self ._lock :
120
+ if labels :
121
+ if not self ._target_info and 'target_info' in self ._names_to_collectors :
122
+ raise ValueError ('CollectorRegistry already contains a target_info metric' )
123
+ self ._names_to_collectors ['target_info' ] = None
124
+ elif self ._target_info :
125
+ self ._names_to_collectors .pop ('target_info' , None )
126
+ self ._target_info = labels
127
+
128
+ def get_target_info (self ):
129
+ with self ._lock :
130
+ return self ._target_info
131
+
132
+ def _target_info_metric (self ):
133
+ m = Metric ('target' , 'Target metadata' , 'info' )
134
+ m .add_sample ('target_info' , self ._target_info , 1 )
135
+ return m
136
+
109
137
def get_sample_value (self , name , labels = None ):
110
138
"""Returns the sample value, or None if not found.
111
139
0 commit comments