blob: 7668b7c20e03025da99595d5eac5b35240f5caa4 [file] [log] [blame]
khenaidoofdbad6e2018-11-06 22:26:38 -05001#
2# Copyright 2016 the original author or authors.
3#
4# Licensed under the Apache License, Version 2.0 (the "License");
5# you may not use this file except in compliance with the License.
6# You may obtain a copy of the License at
7#
8# http://www.apache.org/licenses/LICENSE-2.0
9#
10# Unless required by applicable law or agreed to in writing, software
11# distributed under the License is distributed on an "AS IS" BASIS,
12# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13# See the License for the specific language governing permissions and
14# limitations under the License.
15#
16
17import sys
18
19from google.protobuf.json_format import MessageToDict
20from termcolor import cprint, colored
21
22from table import TablePrinter
23
24
25_printfn = lambda l: sys.stdout.write(l + '\n')
26
27
28def pb2dict(pb_msg):
29 d = MessageToDict(pb_msg, including_default_value_fields=1,
30 preserving_proto_field_name=1)
31 return d
32
33
34def p_cookie(cookie):
35 cookie = '%x' % int(cookie)
36 if len(cookie) > 8:
37 return '~' + cookie[len(cookie)-8:]
38 else:
39 return cookie
40
41'''
42 OFPP_NORMAL = 0x7ffffffa; /* Forward using non-OpenFlow pipeline. */
43 OFPP_FLOOD = 0x7ffffffb; /* Flood using non-OpenFlow pipeline. */
44 OFPP_ALL = 0x7ffffffc; /* All standard ports except input port. */
45 OFPP_CONTROLLER = 0x7ffffffd; /* Send to controller. */
46 OFPP_LOCAL = 0x7ffffffe; /* Local openflow "port". */
47 OFPP_ANY = 0x7fffffff; /* Special value used in some requests when
48'''
49
50
51def p_port(port):
52 if port & 0x7fffffff == 0x7ffffffa:
53 return 'NORMAL'
54 elif port & 0x7fffffff == 0x7ffffffb:
55 return 'FLOOD'
56 elif port & 0x7fffffff == 0x7ffffffc:
57 return 'ALL'
58 elif port & 0x7fffffff == 0x7ffffffd:
59 return 'CONTROLLER'
60 elif port & 0x7fffffff == 0x7ffffffe:
61 return 'LOCAL'
62 elif port & 0x7fffffff == 0x7fffffff:
63 return 'ANY'
64 else:
65 return str(port)
66
67
68def p_vlan_vid(vlan_vid):
69 if vlan_vid == 0:
70 return 'untagged'
71 assert vlan_vid & 4096 == 4096
72 return str(vlan_vid - 4096)
73
74
75def p_ipv4(x):
76 return '.'.join(str(v) for v in [
77 (x >> 24) & 0xff, (x >> 16) & 0xff, (x >> 8) & 0xff, x & 0xff
78 ])
79
80
81field_printers = {
82 'IN_PORT': lambda f: (100, 'in_port', p_port(f['port'])),
83 'VLAN_VID': lambda f: (101, 'vlan_vid', p_vlan_vid(f['vlan_vid'])),
84 'VLAN_PCP': lambda f: (102, 'vlan_pcp', str(f['vlan_pcp'])),
85 'ETH_TYPE': lambda f: (103, 'eth_type', '%X' % f['eth_type']),
86 'IP_PROTO': lambda f: (104, 'ip_proto', str(f['ip_proto'])),
87 'IPV4_DST': lambda f: (105, 'ipv4_dst', p_ipv4(f['ipv4_dst'])),
88 'UDP_SRC': lambda f: (106, 'udp_src', str(f['udp_src'])),
89 'UDP_DST': lambda f: (107, 'udp_dst', str(f['udp_dst'])),
90 'TCP_SRC': lambda f: (108, 'tcp_src', str(f['tcp_src'])),
91 'TCP_DST': lambda f: (109, 'tcp_dst', str(f['tcp_dst'])),
92 'METADATA': lambda f: (110, 'metadata', str(f['table_metadata'])),
Matt Jeanneret802bf362019-04-14 20:33:08 -040093 'TUNNEL_ID': lambda f: (111, 'tunnel_id', str(f['tunnel_id'])),
khenaidoofdbad6e2018-11-06 22:26:38 -050094}
95
96
97def p_field(field):
98 assert field['oxm_class'].endswith('OPENFLOW_BASIC')
99 ofb = field['ofb_field']
100 assert not ofb['has_mask']
101 type = ofb['type'][len('OFPXMT_OFB_'):]
102 weight, field_name, value = field_printers[type](ofb)
103 return 1000 + weight, 'set_' + field_name, value
104
105
106action_printers = {
107 'SET_FIELD': lambda a: p_field(a['set_field']['field']),
108 'POP_VLAN': lambda a: (2000, 'pop_vlan', 'Yes'),
109 'PUSH_VLAN': lambda a: (2001, 'push_vlan', '%x' % a['push']['ethertype']),
110 'GROUP': lambda a: (3000, 'group', p_port(a['group']['group_id'])),
111 'OUTPUT': lambda a: (4000, 'output', p_port(a['output']['port'])),
112}
113
114
115def print_flows(what, id, type, flows, groups, printfn=_printfn):
116
117 header = ''.join([
118 '{} '.format(what),
119 colored(id, color='green', attrs=['bold']),
120 ' (type: ',
121 colored(type, color='blue'),
122 ')'
123 ]) + '\nFlows ({}):'.format(len(flows))
124
125 table = TablePrinter()
126 for i, flow in enumerate(flows):
127
128 table.add_cell(i, 0, 'table_id', value=str(flow['table_id']))
129 table.add_cell(i, 1, 'priority', value=str(flow['priority']))
130 table.add_cell(i, 2, 'cookie', p_cookie(flow['cookie']))
131
132 assert flow['match']['type'] == 'OFPMT_OXM'
133 for field in flow['match']['oxm_fields']:
134 assert field['oxm_class'].endswith('OPENFLOW_BASIC')
135 ofb = field['ofb_field']
136 # see CORD-816 (https://jira.opencord.org/browse/CORD-816)
137 assert not ofb['has_mask'], 'masked match not handled yet'
138 type = ofb['type'][len('OFPXMT_OFB_'):]
139 table.add_cell(i, *field_printers[type](ofb))
140
141 for instruction in flow['instructions']:
142 itype = instruction['type']
Manikkaraj kb1a10922019-07-29 12:10:34 -0400143 if itype == 4 or itype == 3:
khenaidoofdbad6e2018-11-06 22:26:38 -0500144 for action in instruction['actions']['actions']:
145 atype = action['type'][len('OFPAT_'):]
146 table.add_cell(i, *action_printers[atype](action))
147 elif itype == 1:
148 table.add_cell(i, 10000, 'goto-table',
149 instruction['goto_table']['table_id'])
Manikkaraj kb1a10922019-07-29 12:10:34 -0400150 elif itype == 2:
151 table.add_cell(i, 10001, 'write-metadata',
152 instruction['write_metadata']['metadata'])
khenaidoofdbad6e2018-11-06 22:26:38 -0500153 elif itype == 5:
Manikkaraj kb1a10922019-07-29 12:10:34 -0400154 table.add_cell(i, 10002, 'clear-actions', [])
155 elif itype == 6:
156 table.add_cell(i, 10003, 'meter',
157 instruction['meter']['meter_id'])
khenaidoofdbad6e2018-11-06 22:26:38 -0500158 else:
159 raise NotImplementedError(
160 'not handling instruction type {}'.format(itype))
161
162 table.print_table(header, printfn)
163
164
165def print_groups(what, id, type, groups, printfn=_printfn):
166 header = ''.join([
167 '{} '.format(what),
168 colored(id, color='green', attrs=['bold']),
169 ' (type: ',
170 colored(type, color='blue'),
171 ')'
172 ]) + '\nGroups ({}):'.format(len(groups))
173
174 table = TablePrinter()
175 for i, group in enumerate(groups):
176 output_ports = []
177 for bucket in group['desc']['buckets']:
178 for action in bucket['actions']:
179 if action['type'] == 'OFPAT_OUTPUT':
180 output_ports.append(action['output']['port'])
181 table.add_cell(i, 0, 'group_id', value=str(group['desc']['group_id']))
182 table.add_cell(i, 1, 'buckets', value=str(dict(output=output_ports)))
183
184 table.print_table(header, printfn)
185
Manikkaraj kb1a10922019-07-29 12:10:34 -0400186def print_meters(what, id, type, meters, printfn=_printfn):
187 header = ''.join([
188 '{} '.format(what),
189 colored(id, color='green', attrs=['bold']),
190 ' (type: ',
191 colored(type, color='blue'),
192 ')'
193 ]) + '\nMeters ({}):'.format(len(meters))
194
195 table = TablePrinter()
196 for i, meter in enumerate(meters):
197 bands = []
198 for meter_band in meter['config']['bands']:
199 bands.append(meter_band)
200 table.add_cell(i, 0, 'meter_id', value=str(meter['config']['meter_id']))
201 table.add_cell(i, 1, 'meter_bands', value=str(dict(bands=bands)))
202
203 table.print_table(header, printfn)
204
205
khenaidoofdbad6e2018-11-06 22:26:38 -0500206def dict2line(d):
207 assert isinstance(d, dict)
208 return ', '.join('{}: {}'.format(k, v) for k, v in sorted(d.items()))
209
210def enum2name(msg_obj, enum_type, enum_value):
211 descriptor = msg_obj.DESCRIPTOR.enum_types_by_name[enum_type]
212 name = descriptor.values_by_number[enum_value].name
213 return name