Matteo Scandolo | a4e6e9a | 2016-08-23 12:04:45 -0700 | [diff] [blame] | 1 | import os |
| 2 | import sys |
| 3 | import requests |
| 4 | import json |
Scott Baker | 1c1c44e | 2017-03-14 10:19:19 -0700 | [diff] [blame] | 5 | from synchronizers.new_base.syncstep import SyncStep |
| 6 | from synchronizers.new_base.modelaccessor import * |
Matteo Scandolo | a4e6e9a | 2016-08-23 12:04:45 -0700 | [diff] [blame] | 7 | from xos.logger import Logger, logging |
| 8 | |
Matteo Scandolo | a4e6e9a | 2016-08-23 12:04:45 -0700 | [diff] [blame] | 9 | from requests.auth import HTTPBasicAuth |
Matteo Scandolo | a4e6e9a | 2016-08-23 12:04:45 -0700 | [diff] [blame] | 10 | logger = Logger(level=logging.INFO) |
| 11 | |
| 12 | |
| 13 | class SyncVRouterDevice(SyncStep): |
| 14 | provides = [VRouterDevice] |
| 15 | |
| 16 | observes = VRouterDevice |
| 17 | |
| 18 | requested_interval = 0 |
| 19 | |
| 20 | def __init__(self, *args, **kwargs): |
| 21 | super(SyncVRouterDevice, self).__init__(*args, **kwargs) |
| 22 | |
| 23 | def get_onos_fabric_addr(self, app): |
| 24 | vrouter_service = VRouterService.objects.get(id=app.vrouter_service_id) |
| 25 | |
| 26 | return "http://%s:%s/onos/v1/network/configuration/" % (vrouter_service.rest_hostname, vrouter_service.rest_port) |
| 27 | |
| 28 | def get_onos_fabric_auth(self, app): |
| 29 | vrouter_service = VRouterService.objects.get(id=app.vrouter_service_id) |
| 30 | |
| 31 | return HTTPBasicAuth(vrouter_service.rest_user, vrouter_service.rest_pass) |
| 32 | |
| 33 | def sync_record(self, device): |
| 34 | |
| 35 | logger.info("Sync'ing Edited vRouterDevice: %s" % device.name) |
| 36 | |
| 37 | onos_addr = self.get_onos_fabric_addr(device) |
| 38 | |
| 39 | data = {} |
| 40 | data["driver"] = device.driver |
| 41 | |
| 42 | url = onos_addr + "devices/" + device.openflow_id + "/" + device.config_key + "/" |
| 43 | |
| 44 | print "POST %s for device %s" % (url, device.name) |
| 45 | |
| 46 | auth = self.get_onos_fabric_auth(device) |
| 47 | r = requests.post(url, data=json.dumps(data), auth=auth) |
| 48 | if (r.status_code != 200): |
| 49 | print r |
| 50 | raise Exception("Received error from vrouter device update (%d)" % r.status_code) |
| 51 | |
| 52 | def delete_record(self, device): |
| 53 | |
| 54 | logger.info("Sync'ing Deleted vRouterDevice: %s" % device.name) |
| 55 | |
| 56 | onos_addr = self.get_onos_fabric_addr() |
| 57 | |
| 58 | url = onos_addr + "devices/" + device.openflow_id + "/" |
| 59 | |
| 60 | print "DELETE %s for device %s" % (url, device.name) |
| 61 | |
| 62 | auth = self.get_onos_fabric_auth(device) |
| 63 | r = requests.delete(url, auth=auth) |
| 64 | if (r.status_code != 204): |
| 65 | print r |
| 66 | raise Exception("Received error from vrouter device deletion (%d)" % r.status_code) |