vRouter service WIP
diff --git a/xos/services/vrouter/__init__.py b/xos/services/vrouter/__init__.py
new file mode 100644
index 0000000..8b13789
--- /dev/null
+++ b/xos/services/vrouter/__init__.py
@@ -0,0 +1 @@
+
diff --git a/xos/services/vrouter/admin.py b/xos/services/vrouter/admin.py
new file mode 100644
index 0000000..046b897
--- /dev/null
+++ b/xos/services/vrouter/admin.py
@@ -0,0 +1,110 @@
+from django.contrib import admin
+
+from services.vrouter.models import *
+from django import forms
+from django.utils.safestring import mark_safe
+from django.contrib.auth.admin import UserAdmin
+from django.contrib.admin.widgets import FilteredSelectMultiple
+from django.contrib.auth.forms import ReadOnlyPasswordHashField
+from django.contrib.auth.signals import user_logged_in
+from django.utils import timezone
+from django.contrib.contenttypes import generic
+from suit.widgets import LinkedSelect
+from core.admin import ServiceAppAdmin,SliceInline,ServiceAttrAsTabInline, ReadOnlyAwareAdmin, XOSTabularInline, ServicePrivilegeInline, TenantRootTenantInline, TenantRootPrivilegeInline
+from core.middleware import get_request
+
+from functools import update_wrapper
+from django.contrib.admin.views.main import ChangeList
+from django.core.urlresolvers import reverse
+from django.contrib.admin.utils import quote
+
+class VRouterServiceForm(forms.ModelForm):
+    def __init__(self,*args,**kwargs):
+        super (VRouterServiceForm,self ).__init__(*args,**kwargs)
+
+    def save(self, commit=True):
+        return super(VRouterServiceForm, self).save(commit=commit)
+
+    class Meta:
+        model = VRouterService
+
+class VRouterServiceAdmin(ReadOnlyAwareAdmin):
+    model = VRouterService
+    verbose_name = "vRouter Service"
+    verbose_name_plural = "vRouter Service"
+    list_display = ("backend_status_icon", "name", "enabled")
+    list_display_links = ('backend_status_icon', 'name', )
+    fieldsets = [(None, {'fields': ['backend_status_text', 'name','enabled','versionNumber', 'description', "view_url", "icon_url", ],
+                         'classes':['suit-tab suit-tab-general']})]
+    readonly_fields = ('backend_status_text', )
+    inlines = [SliceInline,ServiceAttrAsTabInline,ServicePrivilegeInline]
+    form = VRouterServiceForm
+
+    extracontext_registered_admins = True
+
+    user_readonly_fields = ["name", "enabled", "versionNumber", "description"]
+
+    suit_form_tabs =(('general', 'vRouter Service Details'),
+        ('administration', 'Administration'),
+        #('tools', 'Tools'),
+        ('slices','Slices'),
+        ('serviceattrs','Additional Attributes'),
+        ('serviceprivileges','Privileges'),
+    )
+
+    suit_form_includes = (('vrouteradmin.html', 'top', 'administration'),
+                           ) #('hpctools.html', 'top', 'tools') )
+
+    def queryset(self, request):
+        return VRouterService.get_service_objects_by_user(request.user)
+
+class VRouterTenantForm(forms.ModelForm):
+    public_ip = forms.CharField(required=True)
+    public_mac = forms.CharField(required=True)
+    gateway_ip = forms.CharField(required=False)
+    gateway_mac = forms.CharField(required=False)
+    address_pool_name = forms.CharField(required=True)
+
+    def __init__(self,*args,**kwargs):
+        super (VRouterTenantForm,self ).__init__(*args,**kwargs)
+        self.fields['kind'].widget.attrs['readonly'] = True
+        self.fields['provider_service'].queryset = VRouterService.get_service_objects().all()
+        if self.instance:
+            # fields for the attributes
+            self.fields['address_pool_name'].initial = self.instance.address_pool_name
+            self.fields['public_ip'].initial = self.instance.public_ip
+            self.fields['public_mac'].initial = self.instance.public_mac
+            self.fields['gateway_ip'].initial = self.instance.gateway_ip
+            self.fields['gateway_mac'].initial = self.instance.gateway_mac
+        if (not self.instance) or (not self.instance.pk):
+            # default fields for an 'add' form
+            self.fields['kind'].initial = VROUTER_KIND
+            if VRouterService.get_service_objects().exists():
+               self.fields["provider_service"].initial = VRouterService.get_service_objects().all()[0]
+
+    def save(self, commit=True):
+        self.instance.public_ip = self.cleaned_data.get("public_ip")
+        self.instance.public_mac = self.cleaned_data.get("public_mac")
+        self.instance.address_pool_name = self.cleaned_data.get("address_pool_name")
+        return super(VRouterTenantForm, self).save(commit=commit)
+
+    class Meta:
+        model = VRouterTenant
+
+class VRouterTenantAdmin(ReadOnlyAwareAdmin):
+    list_display = ('backend_status_icon', 'id', 'subscriber_tenant' )
+    list_display_links = ('backend_status_icon', 'id')
+    fieldsets = [ (None, {'fields': ['backend_status_text', 'kind', 'provider_service', 'subscriber_tenant', 'service_specific_id', # 'service_specific_attribute',
+                                     'address_pool_name', 'public_ip', 'public_mac', 'gateway_ip', 'gateway_mac'],
+                          'classes':['suit-tab suit-tab-general']})]
+    readonly_fields = ('backend_status_text', 'service_specific_attribute', 'gateway_ip', 'gateway_mac')
+    form = VRouterTenantForm
+
+    suit_form_tabs = (('general','Details'),)
+
+    def queryset(self, request):
+        return VRouterTenant.get_tenant_objects_by_user(request.user)
+
+admin.site.register(VRouterService, VRouterServiceAdmin)
+admin.site.register(VRouterTenant, VRouterTenantAdmin)
+
diff --git a/xos/services/vrouter/models.py b/xos/services/vrouter/models.py
new file mode 100644
index 0000000..d7d7387
--- /dev/null
+++ b/xos/services/vrouter/models.py
@@ -0,0 +1,86 @@
+from django.db import models
+from core.models import Service, PlCoreBase, Slice, Instance, Tenant, TenantWithContainer, Node, Image, User, Flavor, Subscriber, NetworkParameter, NetworkParameterType, Port, AddressPool
+from core.models.plcorebase import StrippedCharField
+import os
+from django.db import models, transaction
+from django.forms.models import model_to_dict
+from django.db.models import Q
+from operator import itemgetter, attrgetter, methodcaller
+from core.models import Tag
+from core.models.service import LeastLoadedNodeScheduler
+import traceback
+from xos.exceptions import *
+from xos.config import Config
+
+class ConfigurationError(Exception):
+    pass
+
+VROUTER_KIND = "vROUTER"
+
+CORD_USE_VTN = getattr(Config(), "networking_use_vtn", False)
+
+class VRouterService(Service):
+    KIND = VROUTER_KIND
+
+    class Meta:
+        app_label = "cord"
+        verbose_name = "vRouter Service"
+        proxy = True
+
+    def ip_to_mac(self, ip):
+        (a, b, c, d) = ip.split('.')
+        return "02:42:%02x:%02x:%02x:%02x" % (int(a), int(b), int(c), int(d))
+
+    def get_gateways(self):
+        gateways=[]
+
+        aps = self.addresspools.all()
+        for ap in aps:
+            gateways.append( {"gateway_ip": ap.gateway_ip, "gateway_mac": ap.gateway_mac} )
+
+        return gateways
+
+    def get_address_pool(self, name):
+        ap = AddressPool.objects.filter(name=name, service=self)
+        if not ap:
+            raise Exception("vRouter unable to find addresspool %s" % name)
+        return ap[0]
+
+    def get_tenant(self, **kwargs):
+        address_pool_name = kwargs.pop("address_pool_name")
+
+        ap = self.get_address_pool(address_pool_name)
+
+        ip = ap.get_address()
+        if not ip:
+            raise Exception("AddressPool '%s' has run out of addresses." % ap.name)
+
+        t = VRouterTenant(**kwargs)
+        t.public_ip = ip
+        t.public_mac = self.ip_to_mac(ip)
+        t.address_pool_name = ap.name
+        t.save()
+
+        return t
+
+VRouterService.setup_simple_attributes()
+
+class VRouterTenant(Tenant):
+    class Meta:
+        proxy = True
+
+    KIND = VROUTER_KIND
+
+    simple_attributes = ( ("public_ip", None),
+                          ("public_mac", None),
+                          ("address_pool_name", None),
+                          )
+
+    @property
+    def gateway_ip(self):
+        return self.address_pool.gateway_ip
+
+    @property
+    def gateway_mac(self):
+        return self.address_pool.gateway_mac
+