Defined Models and REST APIs
TOSCA specs
Synchronizer

Change-Id: Icd9dde1b456711ca7e5f0c69ae547072ff5b3120
diff --git a/xos/synchronizer/curl_sample.md b/xos/synchronizer/curl_sample.md
new file mode 100644
index 0000000..4675fd8
--- /dev/null
+++ b/xos/synchronizer/curl_sample.md
@@ -0,0 +1,13 @@
+# vRouter App
+
+## Configure vRouter App in ONOS
+`curl -H "Content-Type: application/json" -X POST -d '{"controlPlaneConnectPoint":"of:001/1", "ospfEnabled": "true", "interfaces": ["b1-1"]}' --user onos:rocks http://onos-fabric:8181/onos/v1/network/configuration/apps/org.onosproject.router/router/`
+
+## Delete vRotuer App config
+`curl -X DELETE --user onos:rocks http://onos-fabric:8181/onos/v1/network/configuration/apps/org.onosproject.router/router/`
+
+## Check vRotuer App config
+`curl --user onos:rocks http://onos-fabric:8181/onos/v1/network/configuration/apps/org.onosproject.router/router/`
+
+## Add Port
+`curl --user onos:rocks -H "Content-Type: application/json" -X POST -d {"of:000000000001/1": {"interfaces": [{"ips": ["10.0.4.2/24"], "mac": "00:00:00:00:00:01", "vlan": "100", "name": "b1-1"}]}} http://onos-fabric:8181/onos/v1/network/configuration/ports/`
\ No newline at end of file
diff --git a/xos/synchronizer/manifest b/xos/synchronizer/manifest
new file mode 100644
index 0000000..e2483ed
--- /dev/null
+++ b/xos/synchronizer/manifest
@@ -0,0 +1,8 @@
+manifest
+model_deps
+run.sh
+steps/sync_vrouterapp.py
+steps/sync_vrouterdevice.py
+steps/sync_vrouterports.py
+vrouter-synchronizer.py
+vrouter_config
diff --git a/xos/synchronizer/model_deps b/xos/synchronizer/model_deps
new file mode 100644
index 0000000..9e26dfe
--- /dev/null
+++ b/xos/synchronizer/model_deps
@@ -0,0 +1 @@
+{}
\ No newline at end of file
diff --git a/xos/synchronizer/run.sh b/xos/synchronizer/run.sh
new file mode 100644
index 0000000..64600d6
--- /dev/null
+++ b/xos/synchronizer/run.sh
@@ -0,0 +1,2 @@
+export XOS_DIR=/opt/xos
+python vrouter-synchronizer.py  -C $XOS_DIR/synchronizers/vrouter/vrouter_config
\ No newline at end of file
diff --git a/xos/synchronizer/steps/sync_vrouterapp.py b/xos/synchronizer/steps/sync_vrouterapp.py
new file mode 100644
index 0000000..b7d3576
--- /dev/null
+++ b/xos/synchronizer/steps/sync_vrouterapp.py
@@ -0,0 +1,75 @@
+import os
+import sys
+import requests
+import json
+from django.db.models import Q, F
+from services.vrouter.models import *
+from synchronizers.base.syncstep import SyncStep
+from xos.logger import Logger, logging
+
+# from core.models import Service
+from requests.auth import HTTPBasicAuth
+
+parentdir = os.path.join(os.path.dirname(__file__), "..")
+sys.path.insert(0, parentdir)
+
+logger = Logger(level=logging.INFO)
+
+
+class SyncVRouterApp(SyncStep):
+    provides = [VRouterApp]
+
+    observes = VRouterApp
+
+    requested_interval = 0
+
+    def __init__(self, *args, **kwargs):
+        super(SyncVRouterApp, self).__init__(*args, **kwargs)
+
+    def get_onos_fabric_addr(self, app):
+        vrouter_service = VRouterService.objects.get(id=app.vrouter_service_id)
+
+        return "http://%s:%s/onos/v1/network/configuration/" % (vrouter_service.rest_hostname, vrouter_service.rest_port)
+
+    def get_onos_fabric_auth(self, app):
+        vrouter_service = VRouterService.objects.get(id=app.vrouter_service_id)
+
+        return HTTPBasicAuth(vrouter_service.rest_user, vrouter_service.rest_pass)
+
+    def sync_record(self, app):
+
+        logger.info("Sync'ing Edited vRouterApps: %s" % app.name)
+
+        onos_addr = self.get_onos_fabric_addr(app)
+
+        data = {}
+        data["controlPlaneConnectPoint"] = app.control_plane_connect_point
+        data["ospfEnabled"] = app.ospf_enabled
+        data["interfaces"] = app.interfaces
+
+        url = onos_addr + "apps/" + app.name + "/router/"
+
+        print "POST %s for app %s" % (url, app.name)
+
+        # XXX fixme - hardcoded auth
+        auth = self.get_onos_fabric_auth(app)
+        r = requests.post(url, data=json.dumps(data), auth=auth)
+        if (r.status_code != 200):
+            print r
+            raise Exception("Received error from vrouter app update (%d)" % r.status_code)
+
+    def delete_record(self, app):
+
+        logger.info("Sync'ing Deleted vRouterApps: %s" % app.name)
+
+        onos_addr = self.get_onos_fabric_addr()
+
+        url = onos_addr + "apps/" + app.name + "/"
+
+        print "DELETE %s for app %s" % (url, app.name)
+
+        auth = self.get_onos_fabric_auth(app)
+        r = requests.delete(url, auth=auth)
+        if (r.status_code != 204):
+            print r
+            raise Exception("Received error from vrouter app deletion (%d)" % r.status_code)
\ No newline at end of file
diff --git a/xos/synchronizer/steps/sync_vrouterdevice.py b/xos/synchronizer/steps/sync_vrouterdevice.py
new file mode 100644
index 0000000..36e00db
--- /dev/null
+++ b/xos/synchronizer/steps/sync_vrouterdevice.py
@@ -0,0 +1,72 @@
+import os
+import sys
+import requests
+import json
+from django.db.models import Q, F
+from services.vrouter.models import *
+from synchronizers.base.syncstep import SyncStep
+from xos.logger import Logger, logging
+
+# from core.models import Service
+from requests.auth import HTTPBasicAuth
+
+parentdir = os.path.join(os.path.dirname(__file__), "..")
+sys.path.insert(0, parentdir)
+
+logger = Logger(level=logging.INFO)
+
+
+class SyncVRouterDevice(SyncStep):
+    provides = [VRouterDevice]
+
+    observes = VRouterDevice
+
+    requested_interval = 0
+
+    def __init__(self, *args, **kwargs):
+        super(SyncVRouterDevice, self).__init__(*args, **kwargs)
+
+    def get_onos_fabric_addr(self, app):
+        vrouter_service = VRouterService.objects.get(id=app.vrouter_service_id)
+
+        return "http://%s:%s/onos/v1/network/configuration/" % (vrouter_service.rest_hostname, vrouter_service.rest_port)
+
+    def get_onos_fabric_auth(self, app):
+        vrouter_service = VRouterService.objects.get(id=app.vrouter_service_id)
+
+        return HTTPBasicAuth(vrouter_service.rest_user, vrouter_service.rest_pass)
+
+    def sync_record(self, device):
+
+        logger.info("Sync'ing Edited vRouterDevice: %s" % device.name)
+
+        onos_addr = self.get_onos_fabric_addr(device)
+
+        data = {}
+        data["driver"] = device.driver
+
+        url = onos_addr + "devices/" + device.openflow_id + "/" + device.config_key + "/"
+
+        print "POST %s for device %s" % (url, device.name)
+
+        auth = self.get_onos_fabric_auth(device)
+        r = requests.post(url, data=json.dumps(data), auth=auth)
+        if (r.status_code != 200):
+            print r
+            raise Exception("Received error from vrouter device update (%d)" % r.status_code)
+
+    def delete_record(self, device):
+
+        logger.info("Sync'ing Deleted vRouterDevice: %s" % device.name)
+
+        onos_addr = self.get_onos_fabric_addr()
+
+        url = onos_addr + "devices/" + device.openflow_id + "/"
+
+        print "DELETE %s for device %s" % (url, device.name)
+
+        auth = self.get_onos_fabric_auth(device)
+        r = requests.delete(url, auth=auth)
+        if (r.status_code != 204):
+            print r
+            raise Exception("Received error from vrouter device deletion (%d)" % r.status_code)
\ No newline at end of file
diff --git a/xos/synchronizer/steps/sync_vrouterports.py b/xos/synchronizer/steps/sync_vrouterports.py
new file mode 100644
index 0000000..e19c51e
--- /dev/null
+++ b/xos/synchronizer/steps/sync_vrouterports.py
@@ -0,0 +1,95 @@
+import os
+import sys
+import requests
+import json
+import urllib
+from django.db.models import Q, F
+from services.vrouter.models import *
+from synchronizers.base.syncstep import SyncStep
+from xos.logger import Logger, logging
+
+# from core.models import Service
+from requests.auth import HTTPBasicAuth
+
+parentdir = os.path.join(os.path.dirname(__file__), "..")
+sys.path.insert(0, parentdir)
+
+logger = Logger(level=logging.INFO)
+
+
+class SyncVRouterPort(SyncStep):
+    provides = [VRouterPort]
+
+    observes = VRouterPort
+
+    requested_interval = 0
+
+    def __init__(self, *args, **kwargs):
+        super(SyncVRouterPort, self).__init__(*args, **kwargs)
+
+    def get_onos_fabric_addr(self, app):
+        vrouter_service = VRouterService.objects.get(id=app.vrouter_service_id)
+
+        return "http://%s:%s/onos/v1/network/configuration/" % (vrouter_service.rest_hostname, vrouter_service.rest_port)
+
+    def get_onos_fabric_auth(self, app):
+        vrouter_service = VRouterService.objects.get(id=app.vrouter_service_id)
+
+        return HTTPBasicAuth(vrouter_service.rest_user, vrouter_service.rest_pass)
+
+    def sync_record(self, port):
+
+        logger.info("Sync'ing Edited vRouterPort: %s" % port.name)
+
+        # NOTE port is now related to service,
+        # probably it makes more sense to relate them to a device (and device is related to service)
+        onos_addr = self.get_onos_fabric_addr(port)
+
+        # NOTE
+        # from a port read all interfaces
+        # from interfaces read all ips
+
+        ifaces = []
+        for interface in port.interfaces.all():
+            iface = {
+                'name': interface.name,
+                'mac': interface.mac,
+                'vlan': interface.vlan,
+                'ips': []
+            }
+
+            for ip in interface.ips.all():
+                iface["ips"].append(ip.ip)
+
+            ifaces.append(iface)
+
+        data = {}
+        data[port.openflow_id] = {
+            'interfaces': ifaces
+        }
+
+        url = onos_addr + "ports/"
+
+        print "POST %s for port %s" % (url, port.name)
+
+        auth = self.get_onos_fabric_auth(port)
+        r = requests.post(url, data=json.dumps(data), auth=auth)
+        if (r.status_code != 200):
+            print r
+            raise Exception("Received error from vrouter port update (%d)" % r.status_code)
+
+    def delete_record(self, port):
+
+        logger.info("Sync'ing Deleted vRouterPort: %s" % port.name)
+
+        onos_addr = self.get_onos_fabric_addr()
+
+        url = onos_addr + "ports/" + urllib.quote(port.openflow_id, safe='') + "/"
+
+        print "DELETE %s for port %s" % (url, port.name)
+
+        auth = self.get_onos_fabric_auth(port)
+        r = requests.delete(url, auth=auth)
+        if (r.status_code != 204):
+            print r
+            raise Exception("Received error from vrouter port deletion (%d)" % r.status_code)
\ No newline at end of file
diff --git a/xos/synchronizer/vrouter-synchronizer.py b/xos/synchronizer/vrouter-synchronizer.py
new file mode 100644
index 0000000..93dcb72
--- /dev/null
+++ b/xos/synchronizer/vrouter-synchronizer.py
@@ -0,0 +1,13 @@
+#!/usr/bin/env python
+
+# Runs the standard XOS synchronizer
+
+import importlib
+import os
+import sys
+
+synchronizer_path = os.path.join(os.path.dirname(
+    os.path.realpath(__file__)), "../../synchronizers/base")
+sys.path.append(synchronizer_path)
+mod = importlib.import_module("xos-synchronizer")
+mod.main()
diff --git a/xos/synchronizer/vrouter_config b/xos/synchronizer/vrouter_config
new file mode 100644
index 0000000..2af1700
--- /dev/null
+++ b/xos/synchronizer/vrouter_config
@@ -0,0 +1,23 @@
+# Required by XOS
+[db]
+name=xos
+user=postgres
+password=password
+host=localhost
+port=5432
+ 
+# Required by XOS
+[api]
+nova_enabled=True
+ 
+# Sets options for the synchronizer
+[observer]
+name=vrouter
+dependency_graph=/opt/xos/synchronizers/vrouter/model_deps
+steps_dir=/opt/xos/synchronizers/vrouter/steps
+sys_dir=/opt/xos/synchronizers/vrouter/sys
+logfile=/var/log/xos_backend.log
+pretend=False
+backoff_disabled=True
+save_ansible_output=True
+proxy_ssh=False
\ No newline at end of file