Last active
May 13, 2019 17:28
-
-
Save AlexAkulov/ee3eeeb59f1da022e6e248309a5f12f5 to your computer and use it in GitHub Desktop.
Diamond Collector for basic monitoring of Hasicorp Vault
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# coding=utf-8 | |
""" | |
Simple collector which get JSON and parse it into flat metrics | |
#### Dependencies | |
* urllib2 | |
""" | |
import urllib2, ssl | |
import json | |
import diamond.collector | |
class VaultCollector(diamond.collector.Collector): | |
def get_default_config_help(self): | |
config_help = super(VaultCollector, self).get_default_config_help() | |
config_help.update({ | |
'url': 'Full URL', | |
'headers': 'Header variable if needed. ' | |
'Will be added to every request', | |
}) | |
return config_help | |
def get_default_config(self): | |
default_config = super(VaultCollector, self).get_default_config() | |
default_config.update({ | |
'path': 'vault', | |
'url': 'https://localhost:8200/v1/sys/health', | |
'headers': {'User-Agent': 'Diamond HTTP collector'}, | |
}) | |
return default_config | |
def _json_to_flat_metrics(self, prefix, data): | |
for key, value in data.items(): | |
if isinstance(value, bool): | |
if value: | |
yield ("%s.%s" % (prefix, key), 1) | |
else: | |
yield ("%s.%s" % (prefix, key), 0) | |
elif isinstance(value, int): | |
try: | |
int(value) | |
except ValueError: | |
value = None | |
finally: | |
yield ("%s.%s" % (prefix, key), value) | |
def collect(self): | |
url = self.config['url'] | |
req = urllib2.Request(url, headers=self.config['headers']) | |
req.add_header('Content-type', 'application/json') | |
try: | |
resp = urllib2.urlopen(req, context=ssl._create_unverified_context()) | |
except urllib2.HTTPError as e: | |
content = e.read() | |
else: | |
content = resp.read() | |
try: | |
data = json.loads(content) | |
except ValueError as e: | |
self.log.error("Can't parse JSON object from %s. %s", url, e) | |
else: | |
for metric_name, metric_value in self._json_to_flat_metrics("", data): | |
self.publish(metric_name, metric_value) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment