daily pastebin goal
5%
SHARE
TWEET

Untitled

a guest Feb 13th, 2018 230 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. #!/usr/bin/python
  2.  
  3. # 1.0 basic version
  4. # 1.1 --delete added
  5.  
  6. __author__ = "Mykola Yakovliev"
  7. __credits__ = ["Mykola Yakovliev"]
  8. __license__ = "GPLv3"
  9. __version__ = "1.1"
  10. __maintainer__ = "Mykola Yakovliev"
  11. __email__ = "vegasq@gmail.com"
  12. __status__ = "Production"
  13.  
  14. import argparse
  15. from pprint import pprint
  16. import requests
  17. import json
  18. from simplejson.scanner import JSONDecodeError
  19.  
  20. from prettytable import PrettyTable
  21. from keystoneclient.v2_0 import client
  22.  
  23.  
  24. class ContrailAPIWrap(object):
  25.     """Generic wrapper that handles requests to Contrail VIP.
  26.  
  27.     Requires working keystone v2
  28.     """
  29.     def __init__(self, contrail_ep, keystone_ep, user, password, tenant):
  30.         self.contrail_ep = contrail_ep
  31.         self.keystone_ep = keystone_ep
  32.         self.user = user
  33.         self.password = password
  34.         self.tenant = tenant
  35.  
  36.     def _get_token(self):
  37.         kc = client.Client(
  38.             username=self.user, password=self.password,
  39.             auth_url=self.keystone_ep, tenant_name=self.tenant)
  40.  
  41.         k = kc.service_catalog.get_token()
  42.         return k['id']
  43.  
  44.     def get(self, cmd=""):
  45.         token = self._get_token()
  46.         data = requests.get(
  47.             "%s%s" % (self.contrail_ep, cmd),
  48.             headers={'X-Auth-Token': token})
  49.         try:
  50.             return data.json()
  51.         except JSONDecodeError:
  52.             print(data.text)
  53.  
  54.     def delete(self, cmd=""):
  55.         token = self._get_token()
  56.         data = requests.delete(
  57.             "%s%s" % (self.contrail_ep, cmd),
  58.             headers={'X-Auth-Token': token})
  59.         try:
  60.             return data.json()
  61.         except JSONDecodeError:
  62.             print(data.text)
  63.  
  64.  
  65.  
  66. class PyContrailBackend(object):
  67.     def __init__(self, contrail_ep, keystone_ep, user, password, tenant):
  68.         self.conn = ContrailAPIWrap(
  69.                 contrail_ep, keystone_ep, user, password, tenant)
  70.  
  71.         self.multiple_key = None
  72.         self.single_key = None
  73.  
  74.     def prnt(self, t):
  75.         print(self.header)
  76.         print(t)
  77.  
  78.     def display(self):
  79.         t = PrettyTable(['Name', 'IP', 'UUID'])
  80.         for node in self.get_nodes():
  81.             t.add_row(node)
  82.         self.prnt(t)
  83.  
  84.     def get_nodes(self):
  85.         nodes = []
  86.  
  87.         nodes_resp = self.conn.get(self.multiple_key)
  88.         for n in nodes_resp[self.multiple_key]:
  89.             # Remove full path since we handle it on higher level
  90.             item_href = n['href'].replace(self.conn.contrail_ep, '')
  91.             info = self.conn.get(item_href)[self.single_key]
  92.  
  93.             ip = None
  94.             if 'virtual_router_ip_address' in info:
  95.                 ip = info['virtual_router_ip_address']
  96.             elif 'analytics_node_ip_address' in info:
  97.                 ip = info['analytics_node_ip_address']
  98.             elif 'config_node_ip_address' in info:
  99.                 ip = info['config_node_ip_address']
  100.             elif 'database_node_ip_address' in info:
  101.                 ip = info['database_node_ip_address']
  102.             else:
  103.                 for k in info.keys():
  104.                     if "_ip_" in k:
  105.                         ip = info[k]
  106.             if ip is None:
  107.                 ip = json.dumps(info['fq_name'])
  108.  
  109.             nodes.append((info['display_name'], ip, info['uuid']))
  110.         return nodes
  111.  
  112.  
  113. class AnalyticsNodes(PyContrailBackend):
  114.     def __init__(self, *args, **kwargs):
  115.         super(AnalyticsNodes, self).__init__(*args, **kwargs)
  116.  
  117.         self.header = "Analytics nodes"
  118.         self.multiple_key = 'analytics-nodes'
  119.         self.single_key = 'analytics-node'
  120.  
  121.  
  122. class ConfigNodes(PyContrailBackend):
  123.     def __init__(self, *args, **kwargs):
  124.         super(ConfigNodes, self).__init__(*args, **kwargs)
  125.  
  126.         self.header = "Config nodes"
  127.         self.multiple_key = 'config-nodes'
  128.         self.single_key = 'config-node'
  129.  
  130.  
  131. class DatabaseNodes(PyContrailBackend):
  132.     def __init__(self, *args, **kwargs):
  133.         super(DatabaseNodes, self).__init__(*args, **kwargs)
  134.  
  135.         self.header = "Database nodes"
  136.         self.multiple_key = 'database-nodes'
  137.         self.single_key = 'database-node'
  138.  
  139.  
  140. class PhysicalRouters(PyContrailBackend):
  141.     def __init__(self, *args, **kwargs):
  142.         super(PhysicalRouters, self).__init__(*args, **kwargs)
  143.  
  144.         self.header = "Physical Routers"
  145.         self.multiple_key = 'physical-routers'
  146.         self.single_key = 'physical-router'
  147.  
  148.  
  149. class VirtualRouters(PyContrailBackend):
  150.     def __init__(self, *args, **kwargs):
  151.         super(VirtualRouters, self).__init__(*args, **kwargs)
  152.  
  153.         self.header = "Virtual routers"
  154.         self.multiple_key = 'virtual-routers'
  155.         self.single_key = 'virtual-router'
  156.  
  157.  
  158. class NodesFacade(object):
  159.     def __init__(self):
  160.         parser = argparse.ArgumentParser(description='Display Contrail nodes')
  161.         parser.add_argument(
  162.             '--username', type=str, metavar='USERNAME',
  163.             help="Username", required=True)
  164.         parser.add_argument(
  165.             '--password', type=str, metavar='PASSWORD',
  166.             help="Password", required=True)
  167.         parser.add_argument(
  168.             '--tenant', type=str, metavar='tenant',
  169.             help="tenant", required=True)
  170.         parser.add_argument(
  171.             '--contrail-ep', type=str, metavar='CONTRAILEP',
  172.             help="Contrail endpoint", required=True)
  173.         parser.add_argument(
  174.             '--keystone-ep', type=str, metavar='KEYSTONEEP',
  175.             help="Keystone endpoint", required=True)
  176.         parser.add_argument(
  177.             '--get', type=str, metavar="HREF", help="Get object")
  178.         parser.add_argument(
  179.             '--delete', type=str, metavar="HREF", help="Delete object")
  180.  
  181.         parsed_args = parser.parse_args()
  182.  
  183.         if parsed_args.get:
  184.             if parsed_args.get == '/':
  185.                 parsed_args.get = ''
  186.             v = ContrailAPIWrap(
  187.                 parsed_args.contrail_ep, parsed_args.keystone_ep,
  188.                 parsed_args.username, parsed_args.password,
  189.                 parsed_args.tenant).get(parsed_args.get)
  190.             pprint(v)
  191.         elif parsed_args.delete:
  192.             if parsed_args.get == '/':
  193.                 parsed_args.get = ''
  194.             v = ContrailAPIWrap(
  195.                 parsed_args.contrail_ep, parsed_args.keystone_ep,
  196.                 parsed_args.username, parsed_args.password,
  197.                 parsed_args.tenant).delete(parsed_args.delete)
  198.             pprint(v)
  199.         else:
  200.             monitor = [ConfigNodes, DatabaseNodes, AnalyticsNodes,
  201.                        VirtualRouters, PhysicalRouters]
  202.             for object_type in monitor:
  203.                 object_type(
  204.                     parsed_args.contrail_ep, parsed_args.keystone_ep,
  205.                     parsed_args.username, parsed_args.password,
  206.                     parsed_args.tenant).display()
  207.  
  208.  
  209. if __name__ == '__main__':
  210.     NodesFacade()
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top