| """ |
| SPDX-FileCopyrightText: 2020-present Intel Corporation |
| SPDX-FileCopyrightText: 2020-present Open Networking Foundation <info@opennetworking.org> |
| SPDX-License-Identifier: LicenseRef-ONF-Member-1.01 |
| """ |
| |
| import sys |
| import json |
| import logging as log |
| |
| import pyaml |
| import requests |
| |
| PROMETHEUS = "https://rancher.aetherproject.org/k8s/clusters/c-xp25p/api/v1/namespaces/cattle-monitoring-system" \ |
| "/services/http:rancher-monitoring-prometheus:9090/proxy/api/v1/query" |
| AUTH = ('token-m44n6', 'sgnxmckznp5kl6wqqxxk5pzd5ptc8qx9bqtfkfqxfx29qvqr8gld2f') |
| |
| |
| class Prometheus(object): |
| |
| def __init__(self, key, token): |
| self.key = key |
| self.token = token |
| |
| def get_ips(self): |
| ips = {} |
| params = ( |
| ('query', 'subscribers_info>0'), |
| ) |
| try: |
| response = requests.get(PROMETHEUS, params=params, auth=(self.key, self.token), timeout=10) |
| except requests.ReadTimeout as e: |
| log.error("Rancher/Prometheus request timeout, error={}".format(e)) |
| sys.exit() |
| if response.status_code != 200: |
| log.error("get_subscriberinfo() failed, status_code: {}".format(response.status_code)) |
| return None |
| metrics = json.loads(response.text)['data']['result'] |
| for metric in metrics: |
| device = metric['metric'] |
| if 'imsi' in device and 'mobile_ip' in device: |
| ips[device['imsi']] = device['mobile_ip'] |
| return ips |
| |
| def update_devices(self, devices): |
| params = ( |
| ('query', 'subscribers_info'), |
| ) |
| |
| try: |
| response = requests.get(PROMETHEUS, params=params, auth=(self.key, self.token), timeout=10) |
| except requests.ReadTimeout as e: |
| log.error("Rancher/Prometheus request timeout, error={}".format(e)) |
| sys.exit() |
| if response.status_code != 200: |
| log.error("get_subscriberinfo() failed, status_code: {}".format(response.status_code)) |
| sys.exit() |
| |
| metrics = json.loads(response.text)['data']['result'] |
| |
| # log.debug(pyaml.dump(metrics)) |
| |
| for elem in metrics: |
| metric = elem['metric'] |
| if 'imsi' in metric and 'mobile_ip' in metric: |
| imsi = metric['imsi'] |
| for k in devices: |
| if devices[k].imsi == imsi: |
| devices[k].ip = metric['mobile_ip'] |
| else: |
| log.error("Ignoring device as imsi or mobile-ip not found - {}".format(metric)) |
| |
| return devices |
| |
| def dump(self): |
| print(pyaml.dump(self.get_ips())) |
| |
| |
| if __name__ == '__main__': |
| log.basicConfig() |
| log.getLogger().setLevel(log.DEBUG) |
| requests_log = log.getLogger("requests.packages.urllib3") |
| requests_log.setLevel(log.DEBUG) |
| requests_log.propagate = True |
| |
| # use Rancher secret-key:bearer-token |
| prom = Prometheus("secret-key", "bearer-token") |
| |
| # prom.get_ips() |
| prom.dump() |