blob: e19c51e431baf7988c6b28f6b65a71709d7eb06a [file] [log] [blame]
Matteo Scandoloa4e6e9a2016-08-23 12:04:45 -07001import os
2import sys
3import requests
4import json
5import urllib
6from django.db.models import Q, F
7from services.vrouter.models import *
8from synchronizers.base.syncstep import SyncStep
9from xos.logger import Logger, logging
10
11# from core.models import Service
12from requests.auth import HTTPBasicAuth
13
14parentdir = os.path.join(os.path.dirname(__file__), "..")
15sys.path.insert(0, parentdir)
16
17logger = Logger(level=logging.INFO)
18
19
20class SyncVRouterPort(SyncStep):
21 provides = [VRouterPort]
22
23 observes = VRouterPort
24
25 requested_interval = 0
26
27 def __init__(self, *args, **kwargs):
28 super(SyncVRouterPort, self).__init__(*args, **kwargs)
29
30 def get_onos_fabric_addr(self, app):
31 vrouter_service = VRouterService.objects.get(id=app.vrouter_service_id)
32
33 return "http://%s:%s/onos/v1/network/configuration/" % (vrouter_service.rest_hostname, vrouter_service.rest_port)
34
35 def get_onos_fabric_auth(self, app):
36 vrouter_service = VRouterService.objects.get(id=app.vrouter_service_id)
37
38 return HTTPBasicAuth(vrouter_service.rest_user, vrouter_service.rest_pass)
39
40 def sync_record(self, port):
41
42 logger.info("Sync'ing Edited vRouterPort: %s" % port.name)
43
44 # NOTE port is now related to service,
45 # probably it makes more sense to relate them to a device (and device is related to service)
46 onos_addr = self.get_onos_fabric_addr(port)
47
48 # NOTE
49 # from a port read all interfaces
50 # from interfaces read all ips
51
52 ifaces = []
53 for interface in port.interfaces.all():
54 iface = {
55 'name': interface.name,
56 'mac': interface.mac,
57 'vlan': interface.vlan,
58 'ips': []
59 }
60
61 for ip in interface.ips.all():
62 iface["ips"].append(ip.ip)
63
64 ifaces.append(iface)
65
66 data = {}
67 data[port.openflow_id] = {
68 'interfaces': ifaces
69 }
70
71 url = onos_addr + "ports/"
72
73 print "POST %s for port %s" % (url, port.name)
74
75 auth = self.get_onos_fabric_auth(port)
76 r = requests.post(url, data=json.dumps(data), auth=auth)
77 if (r.status_code != 200):
78 print r
79 raise Exception("Received error from vrouter port update (%d)" % r.status_code)
80
81 def delete_record(self, port):
82
83 logger.info("Sync'ing Deleted vRouterPort: %s" % port.name)
84
85 onos_addr = self.get_onos_fabric_addr()
86
87 url = onos_addr + "ports/" + urllib.quote(port.openflow_id, safe='') + "/"
88
89 print "DELETE %s for port %s" % (url, port.name)
90
91 auth = self.get_onos_fabric_auth(port)
92 r = requests.delete(url, auth=auth)
93 if (r.status_code != 204):
94 print r
95 raise Exception("Received error from vrouter port deletion (%d)" % r.status_code)