|
4 | 4 | from . import exposition |
5 | 5 | from . import process_collector |
6 | 6 |
|
| 7 | +try: |
| 8 | + from urllib2 import urlopen, quote |
| 9 | +except ImportError: |
| 10 | + # Python 3 |
| 11 | + from urllib.request import urlopen |
| 12 | + from urllib.parse import quote |
| 13 | + |
| 14 | + |
7 | 15 | __all__ = ['Counter', 'Gauge', 'Summary', 'Histogram'] |
8 | 16 | # http://stackoverflow.com/questions/19913653/no-unicode-in-all-for-a-packages-init |
9 | 17 | __all__ = [n.encode('ascii') for n in __all__] |
|
22 | 30 | start_http_server = exposition.start_http_server |
23 | 31 | write_to_textfile = exposition.write_to_textfile |
24 | 32 |
|
| 33 | + |
| 34 | +def build_pushgateway_url(job, instance=None, host='localhost', port=9091): |
| 35 | + ''' |
| 36 | + Build a valid pushgateway url |
| 37 | + ''' |
| 38 | + |
| 39 | + if instance: |
| 40 | + instancestr = '/instances/{}'.format(instance) |
| 41 | + else: |
| 42 | + instancestr = '' |
| 43 | + |
| 44 | + url = 'http://{}:{}/metrics/jobs/{}{}'.format(host, port, |
| 45 | + quote(job), |
| 46 | + quote(instancestr)) |
| 47 | + return url |
| 48 | + |
| 49 | + |
| 50 | +def push_to_gateway_url(url, registry, timeout=None): |
| 51 | + '''Push metrics to the given url''' |
| 52 | + |
| 53 | + resp = urlopen(url, data=generate_latest(registry), timeout=timeout) |
| 54 | + if resp.code >= 400: |
| 55 | + raise IOError("error pushing to pushgateway: {0} {1}".format( |
| 56 | + resp.code, resp.msg)) |
| 57 | + |
| 58 | + |
| 59 | +def push_to_gateway(registry, job, instance=None, host='localhost', port=9091, timeout=None): |
| 60 | + '''Push metrics to a pushgateway''' |
| 61 | + |
| 62 | + url = build_pushgateway_url(job, instance, host, port) |
| 63 | + push_to_gateway_url(url, registry, timeout) |
| 64 | + |
25 | 65 | ProcessCollector = process_collector.ProcessCollector |
26 | 66 | PROCESS_COLLECTOR = process_collector.PROCESS_COLLECTOR |
27 | 67 |
|
|
0 commit comments