blob: e8b3178e8637d921abc876cd0c5a13e92e51a7ee [file] [log] [blame]
Zsolt Harasztia8789e02016-12-14 01:55:43 -08001import os
2import sys
3import requests
4from termcolor import cprint, colored
5from os.path import join as pjoin
6
7
8def p_cookie(cookie):
9 cookie = str(cookie)
10 if len(cookie) > 8:
11 return cookie[:6] + '...'
12 else:
13 return cookie
14
15'''
16 OFPP_NORMAL = 0x7ffffffa; /* Forward using non-OpenFlow pipeline. */
17 OFPP_FLOOD = 0x7ffffffb; /* Flood using non-OpenFlow pipeline. */
18 OFPP_ALL = 0x7ffffffc; /* All standard ports except input port. */
19 OFPP_CONTROLLER = 0x7ffffffd; /* Send to controller. */
20 OFPP_LOCAL = 0x7ffffffe; /* Local openflow "port". */
21 OFPP_ANY = 0x7fffffff; /* Special value used in some requests when
22'''
23
24
25def p_port(port):
26 if port & 0x7fffffff == 0x7ffffffa:
27 return 'NORMAL'
28 elif port & 0x7fffffff == 0x7ffffffb:
29 return 'FLOOD'
30 elif port & 0x7fffffff == 0x7ffffffc:
31 return 'ALL'
32 elif port & 0x7fffffff == 0x7ffffffd:
33 return 'CONTROLLER'
34 elif port & 0x7fffffff == 0x7ffffffe:
35 return 'LOCAL'
36 elif port & 0x7fffffff == 0x7fffffff:
37 return 'ANY'
38 else:
39 return str(port)
40
41
42def p_vlan_vid(vlan_vid):
43 if vlan_vid == 0:
44 return 'untagged'
45 assert vlan_vid & 4096 == 4096
46 return str(vlan_vid - 4096)
47
48
49def p_ipv4(x):
50 return '.'.join(str(v) for v in [
51 (x >> 24) & 0xff, (x >> 16) & 0xff, (x >> 8) & 0xff, x & 0xff
52 ])
53
54
55field_printers = {
56 'IN_PORT': lambda f: (100, 'in_port', p_port(f['port'])),
57 'VLAN_VID': lambda f: (101, 'vlan_vid', p_vlan_vid(f['vlan_vid'])),
58 'VLAN_PCP': lambda f: (102, 'vlan_pcp', str(f['vlan_pcp'])),
59 'ETH_TYPE': lambda f: (103, 'eth_type', '%X' % f['eth_type']),
60 'IPV4_DST': lambda f: (104, 'ipv4_dst', p_ipv4(f['ipv4_dst'])),
61 'IP_PROTO': lambda f: (105, 'ip_proto', str(f['ip_proto']))
62}
63
64
65def p_field(field):
66 assert field['oxm_class'].endswith('OPENFLOW_BASIC')
67 ofb = field['ofb_field']
68 assert not ofb['has_mask']
69 type = ofb['type'][len('OFPXMT_OFB_'):]
70 weight, field_name, value = field_printers[type](ofb)
71 return 1000 + weight, 'set_' + field_name, value
72
73
74action_printers = {
75 'SET_FIELD': lambda a: p_field(a['set_field']['field']),
76 'POP_VLAN': lambda a: (2000, 'pop_vlan', 'Yes'),
77 'PUSH_VLAN': lambda a: (2001, 'push_vlan', '%x' % a['push']['ethertype']),
78 'GROUP': lambda a: (3000, 'group', p_port(a['group']['group_id'])),
79 'OUTPUT': lambda a: (4000, 'output', p_port(a['output']['port'])),
80}
81
82
83class ScriptBase(object):
84
85 usage = 'To be filled by derived class'
86 deep_header = {'get-depth': '-1'}
87
88 def __init__(self):
89 self.voltha_base_url = os.environ.get('VOLTHA_BASE_URL')
90 if self.voltha_base_url is None:
91 self.err(1)
92
93 def err(self, code, msg=None):
94 if msg is None:
95 msg = self.usage
96 print >> sys.stderr, msg
97 sys.exit(code)
98
99 def fetch_logical_device_info(self, base_url, logical_device_id):
100 url = pjoin(base_url, 'logical_devices', logical_device_id)
101 res = requests.get(url, headers=self.deep_header)
102 if res.ok:
103 return res.json()
104 else:
105 self.err('could not fetch logical device at {}: {}'.format(
106 url, res.text))
107
108 def fetch_device_info(self, base_url, device_id):
109 url = pjoin(base_url, 'devices', device_id)
110 res = requests.get(url, headers=self.deep_header)
111 if res.ok:
112 return res.json()
113 else:
114 self.err('could not fetch device at {}: {}'.format(url, res.text))
115
116 def print_flows(self, what, id, type, flows, groups):
117
118 print
119 print ''.join([
120 '{} '.format(what),
121 colored(id, color='green', attrs=['bold']),
122 ' (type: ',
123 colored(type, color='blue'),
124 ')'
125 ])
126 print 'Flows:'
127
128 max_field_lengths = {}
129 field_names = {}
130
131 def update_max_length(field_key, string):
132 length = len(string)
133 if length > max_field_lengths.get(field_key, 0):
134 max_field_lengths[field_key] = length
135
136 def add_field_type(field_key, field_name):
137 if field_key not in field_names:
138 field_names[field_key] = field_name
139 update_max_length(field_key, field_name)
140 else:
141 assert field_names[field_key] == field_name
142
143 cell_values = {}
144
145 # preprocess data
146 for i, flow in enumerate(flows):
147
148 def add_field(field_key, field_name, value):
149 add_field_type(field_key, field_name)
150 row = cell_values.setdefault(i, {})
151 row[field_key] = value
152 update_max_length(field_key, value)
153
154 add_field(0, 'table_id', value=str(flow['table_id']))
155 add_field(1, 'priority', value=str(flow['priority']))
156 add_field(2, 'cookie', p_cookie(flow['cookie']))
157
158 assert flow['match']['type'] == 'OFPMT_OXM'
159 for field in flow['match']['oxm_fields']:
160 assert field['oxm_class'].endswith('OPENFLOW_BASIC')
161 ofb = field['ofb_field']
162 assert not ofb['has_mask'], 'masked match not handled yet' # TODO
163 type = ofb['type'][len('OFPXMT_OFB_'):]
164 add_field(*field_printers[type](ofb))
165
166 for instruction in flow['instructions']:
167 if instruction['type'] == 4:
168 for action in instruction['actions']['actions']:
169 type = action['type'][len('OFPAT_'):]
170 add_field(*action_printers[type](action))
171
172 # print header
173 field_keys = sorted(field_names.keys())
174 def p_sep():
175 print '+' + '+'.join(
176 [(max_field_lengths[k] + 2) * '-' for k in field_keys]) + '+'
177
178 p_sep()
179 print '| ' + ' | '.join(
180 '%%%ds' % max_field_lengths[k] % field_names[k]
181 for k in field_keys) + ' |'
182 p_sep()
183
184 # print values
185 for i in xrange(len(flows)):
186 row = cell_values[i]
187 cprint('| ' + ' | '.join(
188 '%%%ds' % max_field_lengths[k] % row.get(k, '')
189 for k in field_keys
190 ) + ' |')
191 if not ((i + 1) % 3):
192 p_sep()
193
194 if ((i + 1) % 3):
195 p_sep()
196
197 # TODO groups TBF
198 assert len(groups) == 0
199
200