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