-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathexposition.py
More file actions
71 lines (57 loc) · 2.13 KB
/
exposition.py
File metadata and controls
71 lines (57 loc) · 2.13 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
import json
import threading
from socket import gethostname
from typing import Any, Dict, List, Tuple, Sequence
from http.server import HTTPServer
from prometheus_client.exposition import MetricsHandler
from .types import QueueName, WorkerNumber
from .app_settings import app_settings
def get_config_response(
worker_queue_and_counts: Sequence[Tuple[QueueName, WorkerNumber]],
) -> List[Dict[str, Any]]:
"""
This is designed to be used by Prometheus, to direct it to scrape the
correct ports and assign the correct labels to pull in data from all the
running queue workers.
"""
return [
{
"targets": [
"{}:{}".format(
gethostname(),
app_settings.PROMETHEUS_START_PORT + index,
),
],
"labels": {
"django_lightweight_queue_worker_queue": queue,
"django_lightweight_queue_worker_num": str(worker_num),
},
}
for index, (queue, worker_num) in enumerate(worker_queue_and_counts, start=1)
]
def metrics_http_server(
worker_queue_and_counts: Sequence[Tuple[QueueName, WorkerNumber]],
) -> threading.Thread:
config_response = json.dumps(
get_config_response(worker_queue_and_counts),
sort_keys=True,
indent=4,
).encode('utf-8')
class RequestHandler(MetricsHandler, object):
def do_GET(self):
if self.path == "/worker_config":
self.send_response(200)
self.end_headers()
return self.wfile.write(config_response)
return super(RequestHandler, self).do_GET()
class MetricsServer(threading.Thread):
def __init__(self, *args, **kwargs):
super(MetricsServer, self).__init__(*args, **kwargs)
def run(self):
httpd = HTTPServer(('0.0.0.0', app_settings.PROMETHEUS_START_PORT), RequestHandler)
httpd.timeout = 2
try:
httpd.serve_forever()
except KeyboardInterrupt:
pass
return MetricsServer(name="Master Prometheus metrics server", daemon=True)