-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrestconf_parser.py
60 lines (42 loc) · 2.84 KB
/
restconf_parser.py
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
import requests
from lxml import etree
from requests.auth import HTTPBasicAuth
odl_ns = {'i': 'urn:opendaylight:inventory', 'f': 'urn:opendaylight:flow:inventory',
't': 'urn:TBD:params:xml:ns:yang:network-topology', 'o': 'urn:opendaylight:params:xml:ns:yang:ovsdb',
's': 'urn:opendaylight:flow:statistics'}
def request_tree(url, username, psw):
""" Returns etree from url """
tree_req = requests.get(url,
auth=HTTPBasicAuth(username, psw),
headers={'Accept': 'text/xml'}, stream=True)
tree_req.raw.decode_content = True
return etree.parse(tree_req.raw)
def xpath_query(tree, query):
""" Uses 'default' namespaces to wrap xpath query """
global odl_ns
return tree.xpath(query, namespaces=odl_ns)
def get_virtual_machines_info():
""" Returns ip, mac, floating ip, connected swtich id, ofport, ofport's mac for all VMs """
nodes = request_tree(url='http://130.234.169.76:8181/restconf/operational/opendaylight-inventory:nodes', username='admin', psw='admin')
topology = request_tree(url='http://130.234.169.76:8181/restconf/operational/network-topology:network-topology', username='admin', psw='admin')
# Queries to extract:
# - IP and MAC address pair from matches
ip_mac_pairs = xpath_query(nodes, '//f:match[./f:ipv4-source and ././f:ethernet-match/f:ethernet-source/f:address]')
virtual_machines = list()
for ip_mac_pair in ip_mac_pairs:
ip_address = xpath_query(ip_mac_pair, './f:ipv4-source')[0].text
mac_address = xpath_query(ip_mac_pair, './f:ethernet-match/f:ethernet-source/f:address')[0].text
switch_id = xpath_query(ip_mac_pair, './ancestor::i:node/i:id')[0].text
# Find floating IP:
# - IP and floating IP pair from matches
floating_ip_node = xpath_query(nodes, '//f:match[./f:ipv4-source = "' + ip_address + '" and .././f:instructions/f:instruction/f:apply-actions/f:action/f:set-field/f:ipv4-source]')
floating_ip_address = xpath_query(floating_ip_node[0], '../f:instructions/f:instruction/f:apply-actions/f:action/f:set-field/f:ipv4-source')[0].text
# Find switch info
# - MAC address and Switch Info pair from termination points external ids
switch_info_node = xpath_query(topology, '//o:external-id-value[. = "' + mac_address + '"]')
ofport = xpath_query(switch_info_node[0], './ancestor::t:termination-point/o:ofport')[0].text
mac_in_use = xpath_query(switch_info_node[0], './ancestor::t:termination-point/o:mac-in-use')[0].text
virtual_machines.append({'IP': ip_address.split('/')[0], 'floating_IP': floating_ip_address.split('/')[0], 'MAC': mac_address, 'switch_id': switch_id, 'ofport': ofport, 'ofport_MAC': mac_in_use})
return virtual_machines
if __name__ == '__main__':
virtual_machines_info = get_virtual_machines_info()