Minor fixes and addendums
[netvirt.git] / resources / tools / odl / netvirt / netvirt_utils.py
1 import constants as const
2 import json, pprint, urllib2, base64, sys
3 import optparse
4
5
6 options = None
7 args = None
8
9 def parse_args():
10     global options, args
11     parser = optparse.OptionParser(version="0.1")
12     parser.add_option("-i", "--ip", action="store", type="string", dest="odlIp", default="localhost",
13                       help="opendaylights ip address")
14     parser.add_option("-t", "--port", action="store", type="string", dest="odlPort", default="8080",
15                       help="opendaylights listening tcp port on restconf northbound")
16     parser.add_option("-u", "--user", action="store", type="string", dest="odlUsername", default="admin",
17                       help="opendaylight restconf username")
18     parser.add_option("-p", "--password", action="store", type="string", dest="odlPassword", default="admin",
19                       help="opendaylight restconf password")
20     parser.add_option("-m", "--method", action="store", type="string", dest="callMethod", default=None,
21                       help="method to call")
22     parser.add_option("-d", "--tempdir", action="store", type="string", dest="tempDir", default="/tmp/odl",
23                       help="temp directory to store data")
24     (options, args) = parser.parse_args(sys.argv)
25     return options, args
26
27
28 def get_options():
29     return options
30
31
32 def get_args():
33     return args
34
35
36 def create_url(dsType, path):
37     return 'http://{}:{}/restconf/{}/{}/'.format(options.odlIp, options.odlPort, dsType, path)
38
39
40 def get_temp_path():
41     if options:
42         return options.tempDir
43     return './'
44
45
46 def grabJson(url):
47     data = None
48     try:
49         request = urllib2.Request(url)
50         # You need the replace to handle encodestring adding a trailing newline
51         # (https://docs.python.org/2/library/base64.html#base64.encodestring)
52         base64string = base64.encodestring('{}:{}'.format(options.odlUsername, options.odlPassword)).replace('\n', '')
53         request.add_header('Authorization', 'Basic {}'.format(base64string))
54         result = urllib2.urlopen(request)
55     except urllib2.URLError, e:
56         printError('Unable to send request: {}\n'.format(e))
57         return data
58
59     if (result.code != 200):
60         printError( '{}\n{}\n\nError: unexpected code: {}\n'.format(result.info(), result.read(), result.code) )
61         return data
62
63     data = json.load(result)
64     return data
65
66
67 def nstr(s):
68     if not s:
69         return ''
70     return str(s)
71
72
73 def pretty_print(arg):
74     pp = pprint.PrettyPrinter(indent=2)
75     pp.pprint(arg)
76     print
77
78
79 def printError(msg):
80     sys.stderr.write(msg)
81
82
83 def get_port_name(port):
84     prefix = const.VIF_TYPE_TO_PREFIX.get(port[const.VIF_TYPE])
85     if prefix is None:
86         return None
87     else:
88         return prefix + port['uuid'][:11]
89
90
91 def get_dpn_from_ofnodeid(node_id):
92     return node_id.split(':')[1] if node_id else 'none'
93
94
95 def get_ofport_from_ncid(ncid):
96     return ncid.split(':')[2] if ncid and ncid.startswith('openflow') else 0
97
98
99 def to_hex(data, ele=None):
100     if not ele:
101         data = ("0x%x" % data) if data else None
102         return data
103     elif data.get(ele):
104         data[ele] = "0x%x" % data[ele]
105         return data[ele]
106     else:
107         return data
108
109
110 def sort(data, field):
111     return sorted(data, key=lambda x: x[field])
112
113
114 def filter_flow(flow_dict, filter_list):
115     if not filter_list:
116         return True
117     for flow_filter in filter_list:
118         if flow_dict.get(flow_filter):
119             return True
120     return False
121
122
123 def show_optionals(flow):
124     result = ''
125     lport = flow.get('lport')
126     elantag = flow.get('elan-tag')
127     label = flow.get('mpls')
128     vpnid = flow.get('vpnid')
129     ip = flow.get('iface-ips')
130     smac = flow.get('src-mac')
131     dmac = flow.get('dst-mac')
132     vlanid = flow.get('vlanid')
133     ofport = flow.get('ofport')
134     if lport:
135         result = '{},LportTag:{}/{}'.format(result, lport, to_hex(lport))
136     if ofport:
137         result = '{},OfPort:{}'.format(result, ofport)
138     if vlanid:
139         result = '{},VlanId:{}'.format(result, vlanid)
140     if vpnid:
141         result = '{},VpnId:{}/{}'.format(result, vpnid, to_hex(vpnid*2))
142     if label:
143         result = '{},MplsLabel:{}'.format(result, label)
144     if elantag:
145         result = '{},ElanTag:{}/{}'.format(result, elantag, to_hex(elantag))
146     if smac:
147         result = '{},SrcMac:{}'.format(result, smac)
148     if dmac:
149         result = '{},DstMac:{}'.format(result, dmac)
150     if ip:
151         result = '{},LportIp:{}'.format(result, json.dumps(ip))
152     result = '{},Reason:{}'.format(result, flow.get('reason'))
153     return result
154
155
156 def get_optionals(m_str):
157     if str:
158         return dict(s.split('=',1) for s in m_str.split(','))
159     return None
160