Matteo Scandolo | a4e6e9a | 2016-08-23 12:04:45 -0700 | [diff] [blame] | 1 | import os |
| 2 | import sys |
| 3 | import requests |
| 4 | import json |
| 5 | from django.db.models import Q, F |
| 6 | from services.vrouter.models import * |
| 7 | from synchronizers.base.syncstep import SyncStep |
| 8 | from xos.logger import Logger, logging |
| 9 | |
| 10 | # from core.models import Service |
| 11 | from requests.auth import HTTPBasicAuth |
| 12 | |
| 13 | parentdir = os.path.join(os.path.dirname(__file__), "..") |
| 14 | sys.path.insert(0, parentdir) |
| 15 | |
| 16 | logger = Logger(level=logging.INFO) |
| 17 | |
| 18 | |
| 19 | class SyncVRouterApp(SyncStep): |
| 20 | provides = [VRouterApp] |
| 21 | |
| 22 | observes = VRouterApp |
| 23 | |
| 24 | requested_interval = 0 |
| 25 | |
| 26 | def __init__(self, *args, **kwargs): |
| 27 | super(SyncVRouterApp, self).__init__(*args, **kwargs) |
| 28 | |
| 29 | def get_onos_fabric_addr(self, app): |
| 30 | vrouter_service = VRouterService.objects.get(id=app.vrouter_service_id) |
| 31 | |
| 32 | return "http://%s:%s/onos/v1/network/configuration/" % (vrouter_service.rest_hostname, vrouter_service.rest_port) |
| 33 | |
| 34 | def get_onos_fabric_auth(self, app): |
| 35 | vrouter_service = VRouterService.objects.get(id=app.vrouter_service_id) |
| 36 | |
| 37 | return HTTPBasicAuth(vrouter_service.rest_user, vrouter_service.rest_pass) |
| 38 | |
| 39 | def sync_record(self, app): |
| 40 | |
| 41 | logger.info("Sync'ing Edited vRouterApps: %s" % app.name) |
| 42 | |
| 43 | onos_addr = self.get_onos_fabric_addr(app) |
| 44 | |
| 45 | data = {} |
| 46 | data["controlPlaneConnectPoint"] = app.control_plane_connect_point |
| 47 | data["ospfEnabled"] = app.ospf_enabled |
| 48 | data["interfaces"] = app.interfaces |
| 49 | |
| 50 | url = onos_addr + "apps/" + app.name + "/router/" |
| 51 | |
| 52 | print "POST %s for app %s" % (url, app.name) |
| 53 | |
| 54 | # XXX fixme - hardcoded auth |
| 55 | auth = self.get_onos_fabric_auth(app) |
| 56 | r = requests.post(url, data=json.dumps(data), auth=auth) |
| 57 | if (r.status_code != 200): |
| 58 | print r |
| 59 | raise Exception("Received error from vrouter app update (%d)" % r.status_code) |
| 60 | |
| 61 | def delete_record(self, app): |
| 62 | |
| 63 | logger.info("Sync'ing Deleted vRouterApps: %s" % app.name) |
| 64 | |
| 65 | onos_addr = self.get_onos_fabric_addr() |
| 66 | |
| 67 | url = onos_addr + "apps/" + app.name + "/" |
| 68 | |
| 69 | print "DELETE %s for app %s" % (url, app.name) |
| 70 | |
| 71 | auth = self.get_onos_fabric_auth(app) |
| 72 | r = requests.delete(url, auth=auth) |
| 73 | if (r.status_code != 204): |
| 74 | print r |
| 75 | raise Exception("Received error from vrouter app deletion (%d)" % r.status_code) |