Refactor to support OVS insted of prepopulate tagged interfaces and linux briges
[osm/openvim.git] / onos.py
1 #!/usr/bin/env python
2 # -*- coding: utf-8 -*-
3
4 ##
5 # Copyright 2016, I2T Research Group (UPV/EHU)
6 # This file is part of openvim
7 # All Rights Reserved.
8 #
9 # Licensed under the Apache License, Version 2.0 (the "License"); you may
10 # not use this file except in compliance with the License. You may obtain
11 # a copy of the License at
12 #
13 # http://www.apache.org/licenses/LICENSE-2.0
14 #
15 # Unless required by applicable law or agreed to in writing, software
16 # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
17 # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
18 # License for the specific language governing permissions and limitations
19 # under the License.
20 #
21 # For those usages not covered by the Apache License, Version 2.0 please
22 # contact with: alaitz.mendiola@ehu.eus or alaitz.mendiola@gmail.com
23 ##
24
25 '''
26 ImplementS the pluging for the Open Network Operating System (ONOS) openflow
27 controller. It creates the class OF_conn to create dataplane connections
28 with static rules based on packet destination MAC address
29 '''
30
31 __author__="Alaitz Mendiola"
32 __date__ ="$22-nov-2016$"
33
34
35 import json
36 import requests
37 import base64
38 import logging
39
40 class OF_conn():
41 '''ONOS connector. No MAC learning is used'''
42 def __init__(self, params):
43 ''' Constructor.
44 Params: dictionary with the following keys:
45 of_dpid: DPID to use for this controller ?? Does a controller have a dpid?
46 of_ip: controller IP address
47 of_port: controller TCP port
48 of_user: user credentials, can be missing or None
49 of_password: password credentials
50 of_debug: debug level for logging. Default to ERROR
51 other keys are ignored
52 Raise an exception if same parameter is missing or wrong
53 '''
54 #check params
55
56 if "of_ip" not in params or params["of_ip"]==None or "of_port" not in params or params["of_port"]==None:
57 raise ValueError("IP address and port must be provided")
58 #internal variables
59 self.name = "onos"
60 self.headers = {'content-type':'application/json',
61 'accept':'application/json',
62 }
63
64 self.auth="None"
65 self.pp2ofi={} # From Physical Port to OpenFlow Index
66 self.ofi2pp={} # From OpenFlow Index to Physical Port
67
68 self.dpid = str(params["of_dpid"])
69 self.id = 'of:'+str(self.dpid.replace(':', ''))
70 self.url = "http://%s:%s/onos/v1/" %( str(params["of_ip"]), str(params["of_port"] ) )
71
72 # TODO This may not be straightforward
73 if "of_user" in params and params["of_user"]!=None:
74 if not params.get("of_password"):
75 of_password=""
76 else:
77 of_password=str(params["of_password"])
78 self.auth = base64.b64encode(str(params["of_user"])+":"+of_password)
79 self.headers['authorization'] = 'Basic ' + self.auth
80
81
82 self.logger = logging.getLogger('vim.OF.onos')
83 self.logger.setLevel( getattr(logging, params.get("of_debug", "ERROR")) )
84
85 def get_of_switches(self):
86 ''' Obtain a a list of switches or DPID detected by this controller
87 Return
88 >=0, list: list length, and a list where each element a tuple pair (DPID, IP address)
89 <0, text_error: if fails
90 '''
91 try:
92 self.headers['content-type'] = 'text/plain'
93 of_response = requests.get(self.url + "devices", headers=self.headers)
94 error_text = "Openflow response %d: %s" % (of_response.status_code, of_response.text)
95 if of_response.status_code != 200:
96 self.logger.warning("get_of_switches " + error_text)
97 return -1, error_text
98
99 self.logger.debug("get_of_switches " + error_text)
100 info = of_response.json()
101
102 if type(info) != dict:
103 self.logger.error("get_of_switches. Unexpected response, not a dict: %s", str(info))
104 return -1, "Unexpected response, not a dict. Wrong version?"
105
106 node_list = info.get('devices')
107
108 if type(node_list) is not list:
109 self.logger.error(
110 "get_of_switches. Unexpected response, at 'devices', not found or not a list: %s",
111 str(type(node_list)))
112 return -1, "Unexpected response, at 'devices', not found or not a list. Wrong version?"
113
114 switch_list = []
115 for node in node_list:
116 node_id = node.get('id')
117 if node_id is None:
118 self.logger.error("get_of_switches. Unexpected response at 'device':'id', not found: %s",
119 str(node))
120 return -1, "Unexpected response at 'device':'id', not found . Wrong version?"
121
122 node_ip_address = node.get('annotations').get('managementAddress')
123 if node_ip_address is None:
124 self.logger.error(
125 "get_of_switches. Unexpected response at 'device':'managementAddress', not found: %s",
126 str(node))
127 return -1, "Unexpected response at 'device':'managementAddress', not found. Wrong version?"
128
129 node_id_hex = hex(int(node_id.split(':')[1])).split('x')[1].zfill(16)
130
131 switch_list.append(
132 (':'.join(a + b for a, b in zip(node_id_hex[::2], node_id_hex[1::2])), node_ip_address))
133
134 return len(switch_list), switch_list
135
136 except (requests.exceptions.RequestException, ValueError) as e:
137 # ValueError in the case that JSON can not be decoded
138 error_text = type(e).__name__ + ": " + str(e)
139 self.logger.error("get_of_switches " + error_text)
140 return -1, error_text
141
142
143
144 def obtain_port_correspondence(self):
145 '''Obtain the correspondence between physical and openflow port names
146 return:
147 0, dictionary: with physical name as key, openflow name as value
148 -1, error_text: if fails
149 '''
150 try:
151 self.headers['content-type'] = 'text/plain'
152 of_response = requests.get(self.url + "devices/" + self.id + "/ports", headers=self.headers)
153 error_text = "Openflow response %d: %s" % (of_response.status_code, of_response.text)
154 if of_response.status_code != 200:
155 self.logger.warning("obtain_port_correspondence " + error_text)
156 return -1, error_text
157
158 self.logger.debug("obtain_port_correspondence " + error_text)
159 info = of_response.json()
160
161 node_connector_list = info.get('ports')
162 if type(node_connector_list) is not list:
163 self.logger.error(
164 "obtain_port_correspondence. Unexpected response at 'ports', not found or not a list: %s",
165 str(node_connector_list))
166 return -1, "Unexpected response at 'ports', not found or not a list. Wrong version?"
167
168 for node_connector in node_connector_list:
169 if (node_connector['port'] != "local"):
170 self.pp2ofi[str(node_connector['annotations']['portName'])] = str(node_connector['port'])
171 self.ofi2pp[str(node_connector['port'])] = str(node_connector['annotations']['portName'])
172
173 node_ip_address = info['annotations']['managementAddress']
174 if node_ip_address is None:
175 self.logger.error(
176 "obtain_port_correspondence. Unexpected response at 'managementAddress', not found: %s",
177 str(self.id))
178 return -1, "Unexpected response at 'managementAddress', not found. Wrong version?"
179 self.ip_address = node_ip_address
180
181 # print self.name, ": obtain_port_correspondence ports:", self.pp2ofi
182 return 0, self.pp2ofi
183
184 except (requests.exceptions.RequestException, ValueError) as e:
185 # ValueError in the case that JSON can not be decoded
186 error_text = type(e).__name__ + ": " + str(e)
187 self.logger.error("obtain_port_correspondence " + error_text)
188 return -1, error_text
189
190 def get_of_rules(self, translate_of_ports=True):
191 ''' Obtain the rules inserted at openflow controller
192 Params:
193 translate_of_ports: if True it translates ports from openflow index to physical switch name
194 Return:
195 0, dict if ok: with the rule name as key and value is another dictionary with the following content:
196 priority: rule priority
197 name: rule name (present also as the master dict key)
198 ingress_port: match input port of the rule
199 dst_mac: match destination mac address of the rule, can be missing or None if not apply
200 vlan_id: match vlan tag of the rule, can be missing or None if not apply
201 actions: list of actions, composed by a pair tuples:
202 (vlan, None/int): for stripping/setting a vlan tag
203 (out, port): send to this port
204 switch: DPID, all
205 -1, text_error if fails
206 '''
207
208
209 if len(self.ofi2pp) == 0:
210 r, c = self.obtain_port_correspondence()
211 if r < 0:
212 return r, c
213 # get rules
214 try:
215 of_response = requests.get(self.url + "flows/" + self.id, headers=self.headers)
216 error_text = "Openflow response %d: %s" % (of_response.status_code, of_response.text)
217
218 # The configured page does not exist if there are no rules installed. In that case we return an empty dict
219 if of_response.status_code == 404:
220 return 0, {}
221
222 elif of_response.status_code != 200:
223 self.logger.warning("get_of_rules " + error_text)
224 return -1, error_text
225 self.logger.debug("get_of_rules " + error_text)
226
227 info = of_response.json()
228
229 if type(info) != dict:
230 self.logger.error("get_of_rules. Unexpected response, not a dict: %s", str(info))
231 return -1, "Unexpected openflow response, not a dict. Wrong version?"
232
233 flow_list = info.get('flows')
234
235 if flow_list is None:
236 return 0, {}
237
238 if type(flow_list) is not list:
239 self.logger.error(
240 "get_of_rules. Unexpected response at 'flows', not a list: %s",
241 str(type(flow_list)))
242 return -1, "Unexpected response at 'flows', not a list. Wrong version?"
243
244 rules = dict() # Response dictionary
245
246 for flow in flow_list:
247 if not ('id' in flow and 'selector' in flow and 'treatment' in flow and \
248 'instructions' in flow['treatment'] and 'criteria' in \
249 flow['selector']):
250 return -1, "unexpected openflow response, one or more elements are missing. Wrong version?"
251
252 rule = dict()
253 rule['switch'] = self.dpid
254 rule['priority'] = flow.get('priority')
255 rule['name'] = flow['id']
256
257 for criteria in flow['selector']['criteria']:
258 if criteria['type'] == 'IN_PORT':
259 in_port = str(criteria['port'])
260 if in_port != "CONTROLLER":
261 if not in_port in self.ofi2pp:
262 return -1, "Error: Ingress port " + in_port + " is not in switch port list"
263 if translate_of_ports:
264 in_port = self.ofi2pp[in_port]
265 rule['ingress_port'] = in_port
266
267 elif criteria['type'] == 'VLAN_VID':
268 rule['vlan_id'] = criteria['vlanId']
269
270 elif criteria['type'] == 'ETH_DST':
271 rule['dst_mac'] = str(criteria['mac']).lower()
272
273 actions = []
274 for instruction in flow['treatment']['instructions']:
275 if instruction['type'] == "OUTPUT":
276 out_port = str(instruction['port'])
277 if out_port != "CONTROLLER":
278 if not out_port in self.ofi2pp:
279 return -1, "Error: Output port " + out_port + " is not in switch port list"
280
281 if translate_of_ports:
282 out_port = self.ofi2pp[out_port]
283
284 actions.append( ('out', out_port) )
285
286 if instruction['type'] == "L2MODIFICATION" and instruction['subtype'] == "VLAN_POP":
287 actions.append( ('vlan', 'None') )
288 if instruction['type'] == "L2MODIFICATION" and instruction['subtype'] == "VLAN_ID":
289 actions.append( ('vlan', instruction['vlanId']) )
290
291 rule['actions'] = actions
292 rules[flow['id']] = dict(rule)
293
294 return 0, rules
295
296 except (requests.exceptions.RequestException, ValueError) as e:
297 # ValueError in the case that JSON can not be decoded
298 error_text = type(e).__name__ + ": " + str(e)
299 self.logger.error("get_of_rules " + error_text)
300 return -1, error_text
301
302 def del_flow(self, flow_name):
303 ''' Delete an existing rule
304 Params: flow_name, this is the rule name
305 Return
306 0, None if ok
307 -1, text_error if fails
308 '''
309
310 try:
311 self.headers['content-type'] = None
312 of_response = requests.delete(self.url + "flows/" + self.id + "/" + flow_name, headers=self.headers)
313 error_text = "Openflow response %d: %s" % (of_response.status_code, of_response.text)
314
315 if of_response.status_code != 204:
316 self.logger.warning("del_flow " + error_text)
317 return -1 , error_text
318 self.logger.debug("del_flow OK " + error_text)
319 return 0, None
320
321 except requests.exceptions.RequestException as e:
322 error_text = type(e).__name__ + ": " + str(e)
323 self.logger.error("del_flow " + error_text)
324 return -1, error_text
325
326 def new_flow(self, data):
327 ''' Insert a new static rule
328 Params: data: dictionary with the following content:
329 priority: rule priority
330 name: rule name
331 ingress_port: match input port of the rule
332 dst_mac: match destination mac address of the rule, missing or None if not apply
333 vlan_id: match vlan tag of the rule, missing or None if not apply
334 actions: list of actions, composed by a pair tuples with these posibilities:
335 ('vlan', None/int): for stripping/setting a vlan tag
336 ('out', port): send to this port
337 Return
338 0, None if ok
339 -1, text_error if fails
340 '''
341
342 if len(self.pp2ofi) == 0:
343 r,c = self.obtain_port_correspondence()
344 if r<0:
345 return r,c
346 try:
347 # Build the dictionary with the flow rule information for ONOS
348 flow = dict()
349 #flow['id'] = data['name']
350 flow['tableId'] = 0
351 flow['priority'] = data.get('priority')
352 flow['timeout'] = 0
353 flow['isPermanent'] = "true"
354 flow['appId'] = 10 # FIXME We should create an appId for OSM
355 flow['selector'] = dict()
356 flow['selector']['criteria'] = list()
357
358 # Flow rule matching criteria
359 if not data['ingress_port'] in self.pp2ofi:
360 error_text = 'Error. Port ' + data['ingress_port'] + ' is not present in the switch'
361 self.logger.warning("new_flow " + error_text)
362 return -1, error_text
363
364 ingress_port_criteria = dict()
365 ingress_port_criteria['type'] = "IN_PORT"
366 ingress_port_criteria['port'] = self.pp2ofi[data['ingress_port']]
367 flow['selector']['criteria'].append(ingress_port_criteria)
368
369 if 'dst_mac' in data:
370 dst_mac_criteria = dict()
371 dst_mac_criteria["type"] = "ETH_DST"
372 dst_mac_criteria["mac"] = data['dst_mac']
373 flow['selector']['criteria'].append(dst_mac_criteria)
374
375 if data.get('vlan_id'):
376 vlan_criteria = dict()
377 vlan_criteria["type"] = "VLAN_VID"
378 vlan_criteria["vlanId"] = int(data['vlan_id'])
379 flow['selector']['criteria'].append(vlan_criteria)
380
381 # Flow rule treatment
382 flow['treatment'] = dict()
383 flow['treatment']['instructions'] = list()
384 flow['treatment']['deferred'] = list()
385
386 for action in data['actions']:
387 new_action = dict()
388 if action[0] == "vlan":
389 new_action['type'] = "L2MODIFICATION"
390 if action[1] == None:
391 new_action['subtype'] = "VLAN_POP"
392 else:
393 new_action['subtype'] = "VLAN_ID"
394 new_action['vlanId'] = int(action[1])
395 elif action[0] == 'out':
396 new_action['type'] = "OUTPUT"
397 if not action[1] in self.pp2ofi:
398 error_msj = 'Port '+ action[1] + ' is not present in the switch'
399 return -1, error_msj
400 new_action['port'] = self.pp2ofi[action[1]]
401 else:
402 error_msj = "Unknown item '%s' in action list" % action[0]
403 self.logger.error("new_flow " + error_msj)
404 return -1, error_msj
405
406 flow['treatment']['instructions'].append(new_action)
407
408 self.headers['content-type'] = 'application/json'
409 path = self.url + "flows/" + self.id
410 of_response = requests.post(path, headers=self.headers, data=json.dumps(flow) )
411
412 error_text = "Openflow response %d: %s" % (of_response.status_code, of_response.text)
413 if of_response.status_code != 201:
414 self.logger.warning("new_flow " + error_text)
415 return -1 , error_text
416
417
418 flowId = of_response.headers['location'][path.__len__() + 1:]
419
420 data['name'] = flowId
421
422 self.logger.debug("new_flow OK " + error_text)
423 return 0, None
424
425 except requests.exceptions.RequestException as e:
426 error_text = type(e).__name__ + ": " + str(e)
427 self.logger.error("new_flow " + error_text)
428 return -1, error_text
429
430 def clear_all_flows(self):
431 ''' Delete all existing rules
432 Return:
433 0, None if ok
434 -1, text_error if fails
435 '''
436 try:
437 c, rules = self.get_of_rules(True)
438 if c < 0:
439 return -1, "Error retrieving the flows"
440
441 for rule in rules:
442 self.del_flow(rule)
443
444 self.logger.debug("clear_all_flows OK ")
445 return 0, None
446
447 except requests.exceptions.RequestException as e:
448 error_text = type(e).__name__ + ": " + str(e)
449 self.logger.error("clear_all_flows " + error_text)
450 return -1, error_text
451
452