disaggregate CORD into vSG and vOLT and move to onvoarding directory, WIP
diff --git a/xos/onboard/volt/admin.py b/xos/onboard/volt/admin.py
new file mode 100644
index 0000000..cf5dfa6
--- /dev/null
+++ b/xos/onboard/volt/admin.py
@@ -0,0 +1,237 @@
+from django.contrib import admin
+
+from services.volt.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
+
+#-----------------------------------------------------------------------------
+# vOLT
+#-----------------------------------------------------------------------------
+
+class VOLTServiceAdmin(ReadOnlyAwareAdmin):
+ model = VOLTService
+ verbose_name = "vOLT Service"
+ verbose_name_plural = "vOLT 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]
+
+ extracontext_registered_admins = True
+
+ user_readonly_fields = ["name", "enabled", "versionNumber", "description"]
+
+ suit_form_tabs =(('general', 'vOLT Service Details'),
+ ('administration', 'Administration'),
+ #('tools', 'Tools'),
+ ('slices','Slices'),
+ ('serviceattrs','Additional Attributes'),
+ ('serviceprivileges','Privileges'),
+ )
+
+ suit_form_includes = (('voltadmin.html', 'top', 'administration'),
+ ) #('hpctools.html', 'top', 'tools') )
+
+ def queryset(self, request):
+ return VOLTService.get_service_objects_by_user(request.user)
+
+class VOLTTenantForm(forms.ModelForm):
+ s_tag = forms.CharField()
+ c_tag = forms.CharField()
+ creator = forms.ModelChoiceField(queryset=User.objects.all())
+
+ def __init__(self,*args,**kwargs):
+ super (VOLTTenantForm,self ).__init__(*args,**kwargs)
+ self.fields['kind'].widget.attrs['readonly'] = True
+ self.fields['provider_service'].queryset = VOLTService.get_service_objects().all()
+ if self.instance:
+ # fields for the attributes
+ self.fields['c_tag'].initial = self.instance.c_tag
+ self.fields['s_tag'].initial = self.instance.s_tag
+ self.fields['creator'].initial = self.instance.creator
+ if (not self.instance) or (not self.instance.pk):
+ # default fields for an 'add' form
+ self.fields['kind'].initial = VOLT_KIND
+ self.fields['creator'].initial = get_request().user
+ if VOLTService.get_service_objects().exists():
+ self.fields["provider_service"].initial = VOLTService.get_service_objects().all()[0]
+
+ def save(self, commit=True):
+ self.instance.s_tag = self.cleaned_data.get("s_tag")
+ self.instance.c_tag = self.cleaned_data.get("c_tag")
+ self.instance.creator = self.cleaned_data.get("creator")
+ return super(VOLTTenantForm, self).save(commit=commit)
+
+ class Meta:
+ model = VOLTTenant
+
+class VOLTTenantAdmin(ReadOnlyAwareAdmin):
+ list_display = ('backend_status_icon', 'id', 'service_specific_id', 's_tag', 'c_tag', 'subscriber_root' )
+ list_display_links = ('backend_status_icon', 'id')
+ fieldsets = [ (None, {'fields': ['backend_status_text', 'kind', 'provider_service', 'subscriber_root', 'service_specific_id', # 'service_specific_attribute',
+ 's_tag', 'c_tag', 'creator'],
+ 'classes':['suit-tab suit-tab-general']})]
+ readonly_fields = ('backend_status_text', 'service_specific_attribute')
+ form = VOLTTenantForm
+
+ suit_form_tabs = (('general','Details'),)
+
+ def queryset(self, request):
+ return VOLTTenant.get_tenant_objects_by_user(request.user)
+
+class AccessDeviceInline(XOSTabularInline):
+ model = AccessDevice
+ fields = ['volt_device','uplink','vlan']
+ readonly_fields = []
+ extra = 0
+# max_num = 0
+ suit_classes = 'suit-tab suit-tab-accessdevices'
+
+# @property
+# def selflink_reverse_path(self):
+# return "admin:cord_volttenant_change"
+
+class VOLTDeviceAdmin(ReadOnlyAwareAdmin):
+ list_display = ('backend_status_icon', 'name', 'openflow_id', 'driver' )
+ list_display_links = ('backend_status_icon', 'name', 'openflow_id')
+ fieldsets = [ (None, {'fields': ['backend_status_text','name','volt_service','openflow_id','driver','access_agent'],
+ 'classes':['suit-tab suit-tab-general']})]
+ readonly_fields = ('backend_status_text',)
+ inlines = [AccessDeviceInline]
+
+ suit_form_tabs = (('general','Details'), ('accessdevices','Access Devices'))
+
+class AccessDeviceAdmin(ReadOnlyAwareAdmin):
+ list_display = ('backend_status_icon', 'id', 'volt_device', 'uplink', 'vlan' )
+ list_display_links = ('backend_status_icon', 'id')
+ fieldsets = [ (None, {'fields': ['backend_status_text','volt_device','uplink','vlan'],
+ 'classes':['suit-tab suit-tab-general']})]
+ readonly_fields = ('backend_status_text',)
+
+ suit_form_tabs = (('general','Details'),)
+
+class AgentPortMappingInline(XOSTabularInline):
+ model = AgentPortMapping
+ fields = ['access_agent', 'mac', 'port']
+ readonly_fields = []
+ extra = 0
+# max_num = 0
+ suit_classes = 'suit-tab suit-tab-accessportmaps'
+
+# @property
+# def selflink_reverse_path(self):
+# return "admin:cord_volttenant_change"
+
+class AccessAgentAdmin(ReadOnlyAwareAdmin):
+ list_display = ('backend_status_icon', 'name', 'mac' )
+ list_display_links = ('backend_status_icon', 'name')
+ fieldsets = [ (None, {'fields': ['backend_status_text','name','volt_service','mac'],
+ 'classes':['suit-tab suit-tab-general']})]
+ readonly_fields = ('backend_status_text',)
+ inlines= [AgentPortMappingInline]
+
+ suit_form_tabs = (('general','Details'), ('accessportmaps', 'Port Mappings'))
+
+# -------------------------------------------
+# CORDSubscriberRoot
+# -------------------------------------------
+
+class VOLTTenantInline(XOSTabularInline):
+ model = VOLTTenant
+ fields = ['provider_service', 'subscriber_root', 'service_specific_id']
+ readonly_fields = ['provider_service', 'subscriber_root', 'service_specific_id']
+ extra = 0
+ max_num = 0
+ suit_classes = 'suit-tab suit-tab-volttenants'
+ fk_name = 'subscriber_root'
+ verbose_name = 'subscribed tenant'
+ verbose_name_plural = 'subscribed tenants'
+
+ @property
+ def selflink_reverse_path(self):
+ return "admin:cord_volttenant_change"
+
+ def queryset(self, request):
+ qs = super(VOLTTenantInline, self).queryset(request)
+ return qs.filter(kind=VOLT_KIND)
+
+class CordSubscriberRootForm(forms.ModelForm):
+ url_filter_level = forms.CharField(required = False)
+ uplink_speed = forms.CharField(required = False)
+ downlink_speed = forms.CharField(required = False)
+ status = forms.ChoiceField(choices=CordSubscriberRoot.status_choices, required=True)
+ enable_uverse = forms.BooleanField(required=False)
+ cdn_enable = forms.BooleanField(required=False)
+
+ def __init__(self,*args,**kwargs):
+ super (CordSubscriberRootForm,self ).__init__(*args,**kwargs)
+ self.fields['kind'].widget.attrs['readonly'] = True
+ if self.instance:
+ self.fields['url_filter_level'].initial = self.instance.url_filter_level
+ self.fields['uplink_speed'].initial = self.instance.uplink_speed
+ self.fields['downlink_speed'].initial = self.instance.downlink_speed
+ self.fields['status'].initial = self.instance.status
+ self.fields['enable_uverse'].initial = self.instance.enable_uverse
+ self.fields['cdn_enable'].initial = self.instance.cdn_enable
+ if (not self.instance) or (not self.instance.pk):
+ # default fields for an 'add' form
+ self.fields['kind'].initial = CORD_SUBSCRIBER_KIND
+ self.fields['uplink_speed'].initial = CordSubscriberRoot.get_default_attribute("uplink_speed")
+ self.fields['downlink_speed'].initial = CordSubscriberRoot.get_default_attribute("downlink_speed")
+ self.fields['status'].initial = CordSubscriberRoot.get_default_attribute("status")
+ self.fields['enable_uverse'].initial = CordSubscriberRoot.get_default_attribute("enable_uverse")
+ self.fields['cdn_enable'].initial = CordSubscriberRoot.get_default_attribute("cdn_enable")
+
+ def save(self, commit=True):
+ self.instance.url_filter_level = self.cleaned_data.get("url_filter_level")
+ self.instance.uplink_speed = self.cleaned_data.get("uplink_speed")
+ self.instance.downlink_speed = self.cleaned_data.get("downlink_speed")
+ self.instance.status = self.cleaned_data.get("status")
+ self.instance.enable_uverse = self.cleaned_data.get("enable_uverse")
+ self.instance.cdn_enable = self.cleaned_data.get("cdn_enable")
+ return super(CordSubscriberRootForm, self).save(commit=commit)
+
+ class Meta:
+ model = CordSubscriberRoot
+
+class CordSubscriberRootAdmin(ReadOnlyAwareAdmin):
+ list_display = ('backend_status_icon', 'id', 'name', )
+ list_display_links = ('backend_status_icon', 'id', 'name', )
+ fieldsets = [ (None, {'fields': ['backend_status_text', 'kind', 'name', 'service_specific_id', # 'service_specific_attribute',
+ 'url_filter_level', "uplink_speed", "downlink_speed", "status", "enable_uverse", "cdn_enable"],
+ 'classes':['suit-tab suit-tab-general']})]
+ readonly_fields = ('backend_status_text', 'service_specific_attribute',)
+ form = CordSubscriberRootForm
+ inlines = (VOLTTenantInline, TenantRootPrivilegeInline)
+
+ suit_form_tabs =(('general', 'Cord Subscriber Root Details'),
+ ('volttenants','VOLT Tenancy'),
+ ('tenantrootprivileges','Privileges')
+ )
+
+ def queryset(self, request):
+ return CordSubscriberRoot.get_tenant_objects_by_user(request.user)
+
+admin.site.register(VOLTService, VOLTServiceAdmin)
+admin.site.register(VOLTTenant, VOLTTenantAdmin)
+admin.site.register(VOLTDevice, VOLTDeviceAdmin)
+admin.site.register(AccessDevice, AccessDeviceAdmin)
+admin.site.register(AccessAgent, AccessAgentAdmin)
+
+admin.site.register(CordSubscriberRoot, CordSubscriberRootAdmin)
+
diff --git a/xos/api/tenant/cord/subscriber.py b/xos/onboard/volt/api/tenant/cord/subscriber.py
similarity index 100%
rename from xos/api/tenant/cord/subscriber.py
rename to xos/onboard/volt/api/tenant/cord/subscriber.py
diff --git a/xos/api/tenant/cord/volt.py b/xos/onboard/volt/api/tenant/cord/volt.py
similarity index 100%
rename from xos/api/tenant/cord/volt.py
rename to xos/onboard/volt/api/tenant/cord/volt.py
diff --git a/xos/onboard/volt/models.py b/xos/onboard/volt/models.py
new file mode 100644
index 0000000..2127b7d
--- /dev/null
+++ b/xos/onboard/volt/models.py
@@ -0,0 +1,367 @@
+from django.db import models
+from core.models import Service, PlCoreBase, Slice, Instance, Tenant, TenantWithContainer, Node, Image, User, Flavor, Subscriber, NetworkParameter, NetworkParameterType, Port, AddressPool, User
+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
+from services.vrouter.models import VRouterService, VRouterTenant
+import traceback
+from xos.exceptions import *
+from xos.config import Config
+
+class ConfigurationError(Exception):
+ pass
+
+VOLT_KIND = "vOLT"
+CORD_SUBSCRIBER_KIND = "CordSubscriberRoot"
+
+CORD_USE_VTN = getattr(Config(), "networking_use_vtn", False)
+
+# -------------------------------------------
+# CordSubscriberRoot
+# -------------------------------------------
+
+class CordSubscriberRoot(Subscriber):
+ class Meta:
+ proxy = True
+
+ KIND = CORD_SUBSCRIBER_KIND
+
+ status_choices = (("enabled", "Enabled"),
+ ("suspended", "Suspended"),
+ ("delinquent", "Delinquent"),
+ ("copyrightviolation", "Copyright Violation"))
+
+ # 'simple_attributes' will be expanded into properties and setters that
+ # store the attribute using self.set_attribute / self.get_attribute.
+
+ simple_attributes = ( ("firewall_enable", False),
+ ("firewall_rules", "accept all anywhere anywhere"),
+ ("url_filter_enable", False),
+ ("url_filter_rules", "allow all"),
+ ("url_filter_level", "PG"),
+ ("cdn_enable", False),
+ ("devices", []),
+ ("is_demo_user", False),
+
+ ("uplink_speed", 1000000000), # 1 gigabit, a reasonable default?
+ ("downlink_speed", 1000000000),
+ ("enable_uverse", True) )
+
+ default_attributes = {"status": "enabled"}
+
+ sync_attributes = ("firewall_enable",
+ "firewall_rules",
+ "url_filter_enable",
+ "url_filter_rules",
+ "cdn_enable",
+ "uplink_speed",
+ "downlink_speed",
+ "enable_uverse",
+ "status")
+
+ def __init__(self, *args, **kwargs):
+ super(CordSubscriberRoot, self).__init__(*args, **kwargs)
+ self.cached_volt = None
+ self._initial_url_filter_enable = self.url_filter_enable
+
+ @property
+ def volt(self):
+ volt = self.get_newest_subscribed_tenant(VOLTTenant)
+ if not volt:
+ return None
+
+ # always return the same object when possible
+ if (self.cached_volt) and (self.cached_volt.id == volt.id):
+ return self.cached_volt
+
+ #volt.caller = self.creator
+ self.cached_volt = volt
+ return volt
+
+ @property
+ def status(self):
+ return self.get_attribute("status", self.default_attributes["status"])
+
+ @status.setter
+ def status(self, value):
+ if not value in [x[0] for x in self.status_choices]:
+ raise Exception("invalid status %s" % value)
+ self.set_attribute("status", value)
+
+ def find_device(self, mac):
+ for device in self.devices:
+ if device["mac"] == mac:
+ return device
+ return None
+
+ def update_device(self, mac, **kwargs):
+ # kwargs may be "level" or "mac"
+ # Setting one of these to None will cause None to be stored in the db
+ devices = self.devices
+ for device in devices:
+ if device["mac"] == mac:
+ for arg in kwargs.keys():
+ device[arg] = kwargs[arg]
+ self.devices = devices
+ return device
+ raise ValueError("Device with mac %s not found" % mac)
+
+ def create_device(self, **kwargs):
+ if "mac" not in kwargs:
+ raise XOSMissingField("The mac field is required")
+
+ if self.find_device(kwargs['mac']):
+ raise XOSDuplicateKey("Device with mac %s already exists" % kwargs["mac"])
+
+ device = kwargs.copy()
+
+ devices = self.devices
+ devices.append(device)
+ self.devices = devices
+
+ return device
+
+ def delete_device(self, mac):
+ devices = self.devices
+ for device in devices:
+ if device["mac"]==mac:
+ devices.remove(device)
+ self.devices = devices
+ return
+
+ raise ValueError("Device with mac %s not found" % mac)
+
+ #--------------------------------------------------------------------------
+ # Deprecated -- devices used to be called users
+
+ def find_user(self, uid):
+ return self.find_device(uid)
+
+ def update_user(self, uid, **kwargs):
+ return self.update_device(uid, **kwargs)
+
+ def create_user(self, **kwargs):
+ return self.create_device(**kwargs)
+
+ def delete_user(self, uid):
+ return self.delete_user(uid)
+
+ # ------------------------------------------------------------------------
+
+ @property
+ def services(self):
+ return {"cdn": self.cdn_enable,
+ "url_filter": self.url_filter_enable,
+ "firewall": self.firewall_enable}
+
+ @services.setter
+ def services(self, value):
+ pass
+
+ def save(self, *args, **kwargs):
+ self.validate_unique_service_specific_id(none_okay=True)
+ if (not hasattr(self, 'caller') or not self.caller.is_admin):
+ if (self.has_field_changed("service_specific_id")):
+ raise XOSPermissionDenied("You do not have permission to change service_specific_id")
+ super(CordSubscriberRoot, self).save(*args, **kwargs)
+ if (self.volt) and (self.volt.vcpe): # and (self._initial_url_filter_enabled != self.url_filter_enable):
+ # 1) trigger manage_bbs_account to run
+ # 2) trigger vcpe observer to wake up
+ self.volt.vcpe.save()
+
+CordSubscriberRoot.setup_simple_attributes()
+
+# -------------------------------------------
+# VOLT
+# -------------------------------------------
+
+class VOLTService(Service):
+ KIND = VOLT_KIND
+
+ class Meta:
+ app_label = "cord"
+ verbose_name = "vOLT Service"
+
+class VOLTTenant(Tenant):
+ KIND = VOLT_KIND
+
+ class Meta:
+ app_label = "cord"
+ verbose_name = "vOLT Tenant"
+
+ s_tag = models.IntegerField(null=True, blank=True, help_text="s-tag")
+ c_tag = models.IntegerField(null=True, blank=True, help_text="c-tag")
+
+ # at some point, this should probably end up part of Tenant.
+ creator = models.ForeignKey(User, related_name='created_volts', blank=True, null=True)
+
+ def __init__(self, *args, **kwargs):
+ volt_services = VOLTService.get_service_objects().all()
+ if volt_services:
+ self._meta.get_field("provider_service").default = volt_services[0].id
+ super(VOLTTenant, self).__init__(*args, **kwargs)
+ self.cached_vcpe = None
+
+ @property
+ def vcpe(self):
+ from services.vsg import VSGTenant
+ vcpe = self.get_newest_subscribed_tenant(VSGTenant)
+ if not vcpe:
+ return None
+
+ # always return the same object when possible
+ if (self.cached_vcpe) and (self.cached_vcpe.id == vcpe.id):
+ return self.cached_vcpe
+
+ vcpe.caller = self.creator
+ self.cached_vcpe = vcpe
+ return vcpe
+
+ @vcpe.setter
+ def vcpe(self, value):
+ raise XOSConfigurationError("vOLT.vCPE cannot be set this way -- create a new vCPE object and set its subscriber_tenant instead")
+
+ @property
+ def subscriber(self):
+ if not self.subscriber_root:
+ return None
+ subs = CordSubscriberRoot.objects.filter(id=self.subscriber_root.id)
+ if not subs:
+ return None
+ return subs[0]
+
+ def manage_vcpe(self):
+ # Each VOLT object owns exactly one VCPE object
+
+ if self.deleted:
+ return
+
+ if self.vcpe is None:
+ from service.vsg import VSGService, VSGTenant
+ vsgServices = VSGService.get_service_objects().all()
+ if not vsgServices:
+ raise XOSConfigurationError("No VSG Services available")
+
+ vcpe = VSGTenant(provider_service = vsgServices[0],
+ subscriber_tenant = self)
+ vcpe.caller = self.creator
+ vcpe.save()
+
+ def manage_subscriber(self):
+ if (self.subscriber_root is None):
+ # The vOLT is not connected to a Subscriber, so either find an
+ # existing subscriber with the same SSID, or autogenerate a new
+ # subscriber.
+ #
+ # TODO: This probably goes away when we rethink the ONOS-to-XOS
+ # vOLT API.
+
+ subs = CordSubscriberRoot.get_tenant_objects().filter(service_specific_id = self.service_specific_id)
+ if subs:
+ sub = subs[0]
+ else:
+ sub = CordSubscriberRoot(service_specific_id = self.service_specific_id,
+ name = "autogenerated-for-vOLT-%s" % self.id)
+ sub.save()
+ self.subscriber_root = sub
+ self.save()
+
+ def cleanup_vcpe(self):
+ if self.vcpe:
+ # print "XXX cleanup vcpe", self.vcpe
+ self.vcpe.delete()
+
+ def cleanup_orphans(self):
+ from service.vsg import VSGTenant
+ # ensure vOLT only has one vCPE
+ cur_vcpe = self.vcpe
+ for vcpe in list(self.get_subscribed_tenants(VSGTenant)):
+ if (not cur_vcpe) or (vcpe.id != cur_vcpe.id):
+ # print "XXX clean up orphaned vcpe", vcpe
+ vcpe.delete()
+
+ def save(self, *args, **kwargs):
+ # VOLTTenant probably doesn't need a SSID anymore; that will be handled
+ # by CORDSubscriberRoot...
+ # self.validate_unique_service_specific_id()
+
+ if (self.subscriber_root is not None):
+ subs = self.subscriber_root.get_subscribed_tenants(VOLTTenant)
+ if (subs) and (self not in subs):
+ raise XOSDuplicateKey("Subscriber should only be linked to one vOLT")
+
+ if not self.creator:
+ if not getattr(self, "caller", None):
+ # caller must be set when creating a vCPE since it creates a slice
+ raise XOSProgrammingError("VOLTTenant's self.caller was not set")
+ self.creator = self.caller
+ if not self.creator:
+ raise XOSProgrammingError("VOLTTenant's self.creator was not set")
+
+ super(VOLTTenant, self).save(*args, **kwargs)
+ model_policy_volt(self.pk)
+
+ def delete(self, *args, **kwargs):
+ self.cleanup_vcpe()
+ super(VOLTTenant, self).delete(*args, **kwargs)
+
+def model_policy_volt(pk):
+ # TODO: this should be made in to a real model_policy
+ with transaction.atomic():
+ volt = VOLTTenant.objects.select_for_update().filter(pk=pk)
+ if not volt:
+ return
+ volt = volt[0]
+ volt.manage_vcpe()
+ volt.manage_subscriber()
+ volt.cleanup_orphans()
+
+class VOLTDevice(PlCoreBase):
+ class Meta:
+ app_label = "cord"
+
+ name = models.CharField(max_length=254, help_text="name of device", null=False, blank=False)
+ volt_service = models.ForeignKey(VOLTService, related_name='volt_devices')
+ openflow_id = models.CharField(max_length=254, help_text="OpenFlow ID", null=True, blank=True)
+ driver = models.CharField(max_length=254, help_text="driver", null=True, blank=True)
+ access_agent = models.ForeignKey("AccessAgent", related_name='volt_devices', blank=True, null=True)
+
+ def __unicode__(self): return u'%s' % (self.name)
+
+class AccessDevice(PlCoreBase):
+ class Meta:
+ app_label = "cord"
+
+ volt_device = models.ForeignKey(VOLTDevice, related_name='access_devices')
+ uplink = models.IntegerField(null=True, blank=True)
+ vlan = models.IntegerField(null=True, blank=True)
+
+ def __unicode__(self): return u'%s-%d:%d' % (self.volt_device.name,self.uplink,self.vlan)
+
+class AccessAgent(PlCoreBase):
+ class Meta:
+ app_label = "cord"
+
+ name = models.CharField(max_length=254, help_text="name of agent", null=False, blank=False)
+ volt_service = models.ForeignKey(VOLTService, related_name='access_agents')
+ mac = models.CharField(max_length=32, help_text="MAC Address or Access Agent", null=True, blank=True)
+
+ def __unicode__(self): return u'%s' % (self.name)
+
+class AgentPortMapping(PlCoreBase):
+ class Meta:
+ app_label = "cord"
+
+ access_agent = models.ForeignKey(AccessAgent, related_name='port_mappings')
+ mac = models.CharField(max_length=32, help_text="MAC Address", null=True, blank=True)
+ port = models.CharField(max_length=32, help_text="Openflow port ID", null=True, blank=True)
+
+ def __unicode__(self): return u'%s-%s-%s' % (self.access_agent.name, self.port, self.mac)
+
+
+
diff --git a/xos/services/cord/templates/voltadmin.html b/xos/onboard/volt/templates/voltadmin.html
similarity index 100%
rename from xos/services/cord/templates/voltadmin.html
rename to xos/onboard/volt/templates/voltadmin.html
diff --git a/xos/tosca/resources/CORDSubscriber.py b/xos/onboard/volt/tosca/resources/CORDSubscriber.py
similarity index 100%
rename from xos/tosca/resources/CORDSubscriber.py
rename to xos/onboard/volt/tosca/resources/CORDSubscriber.py
diff --git a/xos/tosca/resources/CORDUser.py b/xos/onboard/volt/tosca/resources/CORDUser.py
similarity index 100%
rename from xos/tosca/resources/CORDUser.py
rename to xos/onboard/volt/tosca/resources/CORDUser.py
diff --git a/xos/tosca/resources/VOLTTenant.py b/xos/onboard/volt/tosca/resources/VOLTTenant.py
similarity index 100%
rename from xos/tosca/resources/VOLTTenant.py
rename to xos/onboard/volt/tosca/resources/VOLTTenant.py
diff --git a/xos/tosca/resources/voltdevice.py b/xos/onboard/volt/tosca/resources/voltdevice.py
similarity index 100%
rename from xos/tosca/resources/voltdevice.py
rename to xos/onboard/volt/tosca/resources/voltdevice.py
diff --git a/xos/tosca/resources/voltservice.py b/xos/onboard/volt/tosca/resources/voltservice.py
similarity index 100%
rename from xos/tosca/resources/voltservice.py
rename to xos/onboard/volt/tosca/resources/voltservice.py
diff --git a/xos/onboard/volt/volt-onboard.yaml b/xos/onboard/volt/volt-onboard.yaml
new file mode 100644
index 0000000..cd991f6
--- /dev/null
+++ b/xos/onboard/volt/volt-onboard.yaml
@@ -0,0 +1,25 @@
+tosca_definitions_version: tosca_simple_yaml_1_0
+
+description: Onboard the exampleservice
+
+imports:
+ - custom_types/xos.yaml
+
+topology_template:
+ node_templates:
+ servicecontroller#volt:
+ type: tosca.nodes.ServiceController
+ properties:
+ base_url: file:///opt/xos/onboard/volt/
+ # The following will concatenate with base_url automatically, if
+ # base_url is non-null.
+ models: models.py
+ admin: admin.py
+ synchronizer: synchronizer/manifest
+ #tosca_custom_types: exampleservice.yaml
+ tosca_resource: tosca/resources/voltdevice.py, tosca/resources/voltservice.py, tosca/resources/CORDSubscriber.py, tosca/resources/CORDUser.py, tosca/resources/VOLTTenant.py
+ #rest_service: api/service/exampleservice.py
+ rest_tenant: subdirectory:cord api/tenant/cord/volt.py, subdirectory:cord api/tenant/cord/subscriber.py
+ private_key: file:///opt/xos/key_import/volt_rsa
+ public_key: file:///opt/xos/key_import/volt_rsa.pub
+
diff --git a/xos/onboard/vsg/admin.py b/xos/onboard/vsg/admin.py
new file mode 100644
index 0000000..92fa51d
--- /dev/null
+++ b/xos/onboard/vsg/admin.py
@@ -0,0 +1,150 @@
+from django.contrib import admin
+
+from services.vsg.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
+
+#-----------------------------------------------------------------------------
+# vSG
+#-----------------------------------------------------------------------------
+
+class VSGServiceForm(forms.ModelForm):
+ bbs_api_hostname = forms.CharField(required=False)
+ bbs_api_port = forms.IntegerField(required=False)
+ bbs_server = forms.CharField(required=False)
+ backend_network_label = forms.CharField(required=False)
+ bbs_slice = forms.ModelChoiceField(queryset=Slice.objects.all(), required=False)
+ dns_servers = forms.CharField(required=False)
+ url_filter_kind = forms.ChoiceField(choices=VSGService.URL_FILTER_KIND_CHOICES, required=False)
+ node_label = forms.CharField(required=False)
+
+ def __init__(self,*args,**kwargs):
+ super (VSGServiceForm,self ).__init__(*args,**kwargs)
+ if self.instance:
+ self.fields['bbs_api_hostname'].initial = self.instance.bbs_api_hostname
+ self.fields['bbs_api_port'].initial = self.instance.bbs_api_port
+ self.fields['bbs_server'].initial = self.instance.bbs_server
+ self.fields['backend_network_label'].initial = self.instance.backend_network_label
+ self.fields['bbs_slice'].initial = self.instance.bbs_slice
+ self.fields['dns_servers'].initial = self.instance.dns_servers
+ self.fields['url_filter_kind']. initial = self.instance.url_filter_kind
+ self.fields['node_label'].initial = self.instance.node_label
+
+ def save(self, commit=True):
+ self.instance.bbs_api_hostname = self.cleaned_data.get("bbs_api_hostname")
+ self.instance.bbs_api_port = self.cleaned_data.get("bbs_api_port")
+ self.instance.bbs_server = self.cleaned_data.get("bbs_server")
+ self.instance.backend_network_label = self.cleaned_data.get("backend_network_label")
+ self.instance.bbs_slice = self.cleaned_data.get("bbs_slice")
+ self.instance.dns_servers = self.cleaned_data.get("dns_servers")
+ self.instance.url_filter_kind = self.cleaned_data.get("url_filter_kind")
+ self.instance.node_label = self.cleaned_data.get("node_label")
+ return super(VSGServiceForm, self).save(commit=commit)
+
+ class Meta:
+ model = VSGService
+
+class VSGServiceAdmin(ReadOnlyAwareAdmin):
+ model = VSGService
+ verbose_name = "vSG Service"
+ verbose_name_plural = "vSG 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", "service_specific_attribute", "node_label"],
+ 'classes':['suit-tab suit-tab-general']}),
+ ("backend config", {'fields': [ "backend_network_label", "url_filter_kind", "bbs_api_hostname", "bbs_api_port", "bbs_server", "bbs_slice"],
+ 'classes':['suit-tab suit-tab-backend']}),
+ ("vSG config", {'fields': ["dns_servers"],
+ 'classes':['suit-tab suit-tab-vsg']}) ]
+ readonly_fields = ('backend_status_text', "service_specific_attribute")
+ inlines = [SliceInline,ServiceAttrAsTabInline,ServicePrivilegeInline]
+ form = VSGServiceForm
+
+ extracontext_registered_admins = True
+
+ user_readonly_fields = ["name", "enabled", "versionNumber", "description"]
+
+ suit_form_tabs =(('general', 'Service Details'),
+ ('backend', 'Backend Config'),
+ ('vsg', 'vSG Config'),
+ ('administration', 'Administration'),
+ #('tools', 'Tools'),
+ ('slices','Slices'),
+ ('serviceattrs','Additional Attributes'),
+ ('serviceprivileges','Privileges') ,
+ )
+
+ suit_form_includes = (('vcpeadmin.html', 'top', 'administration'),
+ ) #('hpctools.html', 'top', 'tools') )
+
+ def queryset(self, request):
+ return VSGService.get_service_objects_by_user(request.user)
+
+class VSGTenantForm(forms.ModelForm):
+ bbs_account = forms.CharField(required=False)
+ creator = forms.ModelChoiceField(queryset=User.objects.all())
+ instance = forms.ModelChoiceField(queryset=Instance.objects.all(),required=False)
+ last_ansible_hash = forms.CharField(required=False)
+ wan_container_ip = forms.CharField(required=False)
+ wan_container_mac = forms.CharField(required=False)
+
+ def __init__(self,*args,**kwargs):
+ super (VSGTenantForm,self ).__init__(*args,**kwargs)
+ self.fields['kind'].widget.attrs['readonly'] = True
+ self.fields['provider_service'].queryset = VSGService.get_service_objects().all()
+ if self.instance:
+ # fields for the attributes
+ self.fields['bbs_account'].initial = self.instance.bbs_account
+ self.fields['creator'].initial = self.instance.creator
+ self.fields['instance'].initial = self.instance.instance
+ self.fields['last_ansible_hash'].initial = self.instance.last_ansible_hash
+ self.fields['wan_container_ip'].initial = self.instance.wan_container_ip
+ self.fields['wan_container_mac'].initial = self.instance.wan_container_mac
+ if (not self.instance) or (not self.instance.pk):
+ # default fields for an 'add' form
+ self.fields['kind'].initial = VCPE_KIND
+ self.fields['creator'].initial = get_request().user
+ if VSGService.get_service_objects().exists():
+ self.fields["provider_service"].initial = VSGService.get_service_objects().all()[0]
+
+ def save(self, commit=True):
+ self.instance.creator = self.cleaned_data.get("creator")
+ self.instance.instance = self.cleaned_data.get("instance")
+ self.instance.last_ansible_hash = self.cleaned_data.get("last_ansible_hash")
+ return super(VSGTenantForm, self).save(commit=commit)
+
+ class Meta:
+ model = VSGTenant
+
+class VSGTenantAdmin(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',
+ 'wan_container_ip', 'wan_container_mac', 'bbs_account', 'creator', 'instance', 'last_ansible_hash'],
+ 'classes':['suit-tab suit-tab-general']})]
+ readonly_fields = ('backend_status_text', 'service_specific_attribute', 'bbs_account', 'wan_container_ip', 'wan_container_mac')
+ form = VSGTenantForm
+
+ suit_form_tabs = (('general','Details'),)
+
+ def queryset(self, request):
+ return VSGTenant.get_tenant_objects_by_user(request.user)
+
+
+admin.site.register(VSGService, VSGServiceAdmin)
+admin.site.register(VSGTenant, VSGTenantAdmin)
+
diff --git a/xos/api/service/vsg/vsgservice.py b/xos/onboard/vsg/api/service/vsg/vsgservice.py
similarity index 100%
rename from xos/api/service/vsg/vsgservice.py
rename to xos/onboard/vsg/api/service/vsg/vsgservice.py
diff --git a/xos/api/tenant/cord/vsg.py b/xos/onboard/vsg/api/tenant/cord/vsg.py
similarity index 100%
rename from xos/api/tenant/cord/vsg.py
rename to xos/onboard/vsg/api/tenant/cord/vsg.py
diff --git a/xos/onboard/vsg/models.py b/xos/onboard/vsg/models.py
new file mode 100644
index 0000000..0b56aa6
--- /dev/null
+++ b/xos/onboard/vsg/models.py
@@ -0,0 +1,448 @@
+from django.db import models
+from core.models import Service, PlCoreBase, Slice, Instance, Tenant, TenantWithContainer, Node, Image, User, Flavor, Subscriber, NetworkParameter, NetworkParameterType, Port, AddressPool, User
+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
+from services.vrouter.models import VRouterService, VRouterTenant
+import traceback
+from xos.exceptions import *
+from xos.config import Config
+
+class ConfigurationError(Exception):
+ pass
+
+VCPE_KIND = "vCPE"
+CORD_SUBSCRIBER_KIND = "CordSubscriberRoot"
+
+CORD_USE_VTN = getattr(Config(), "networking_use_vtn", False)
+
+# -------------------------------------------
+# VCPE
+# -------------------------------------------
+
+class VSGService(Service):
+ KIND = VCPE_KIND
+
+ URL_FILTER_KIND_CHOICES = ( (None, "None"), ("safebrowsing", "Safe Browsing"), ("answerx", "AnswerX") )
+
+ simple_attributes = ( ("bbs_api_hostname", None),
+ ("bbs_api_port", None),
+ ("bbs_server", None),
+ ("backend_network_label", "hpc_client"),
+ ("dns_servers", "8.8.8.8"),
+ ("url_filter_kind", None),
+ ("node_label", None) )
+
+ def __init__(self, *args, **kwargs):
+ super(VSGService, self).__init__(*args, **kwargs)
+
+ class Meta:
+ app_label = "cord"
+ verbose_name = "vSG Service"
+ proxy = True
+
+ def allocate_bbs_account(self):
+ vcpes = VSGTenant.get_tenant_objects().all()
+ bbs_accounts = [vcpe.bbs_account for vcpe in vcpes]
+
+ # There's a bit of a race here; some other user could be trying to
+ # allocate a bbs_account at the same time we are.
+
+ for i in range(2,21):
+ account_name = "bbs%02d@onlab.us" % i
+ if (account_name not in bbs_accounts):
+ return account_name
+
+ raise XOSConfigurationError("We've run out of available broadbandshield accounts. Delete some vcpe and try again.")
+
+ @property
+ def bbs_slice(self):
+ bbs_slice_id=self.get_attribute("bbs_slice_id")
+ if not bbs_slice_id:
+ return None
+ bbs_slices=Slice.objects.filter(id=bbs_slice_id)
+ if not bbs_slices:
+ return None
+ return bbs_slices[0]
+
+ @bbs_slice.setter
+ def bbs_slice(self, value):
+ if value:
+ value = value.id
+ self.set_attribute("bbs_slice_id", value)
+
+VSGService.setup_simple_attributes()
+
+class VSGTenant(TenantWithContainer):
+ class Meta:
+ proxy = True
+
+ KIND = VCPE_KIND
+
+ sync_attributes = ("wan_container_ip", "wan_container_mac", "wan_container_netbits",
+ "wan_container_gateway_ip", "wan_container_gateway_mac",
+ "wan_vm_ip", "wan_vm_mac")
+
+ default_attributes = {"instance_id": None,
+ "container_id": None,
+ "users": [],
+ "bbs_account": None,
+ "last_ansible_hash": None,
+ "wan_container_ip": None}
+
+ def __init__(self, *args, **kwargs):
+ super(VSGTenant, self).__init__(*args, **kwargs)
+ self.cached_vrouter=None
+
+ @property
+ def vbng(self):
+ # not supported
+ return None
+
+ @vbng.setter
+ def vbng(self, value):
+ raise XOSConfigurationError("vCPE.vBNG cannot be set this way -- create a new vBNG object and set it's subscriber_tenant instead")
+
+ @property
+ def vrouter(self):
+ vrouter = self.get_newest_subscribed_tenant(VRouterTenant)
+ if not vrouter:
+ return None
+
+ # always return the same object when possible
+ if (self.cached_vrouter) and (self.cached_vrouter.id == vrouter.id):
+ return self.cached_vrouter
+
+ vrouter.caller = self.creator
+ self.cached_vrouter = vrouter
+ return vrouter
+
+ @vrouter.setter
+ def vrouter(self, value):
+ raise XOSConfigurationError("vCPE.vRouter cannot be set this way -- create a new vRuter object and set its subscriber_tenant instead")
+
+ @property
+ def volt(self):
+ from services.volt import VOLTTenant
+ if not self.subscriber_tenant:
+ return None
+ volts = VOLTTenant.objects.filter(id=self.subscriber_tenant.id)
+ if not volts:
+ return None
+ return volts[0]
+
+ @property
+ def bbs_account(self):
+ return self.get_attribute("bbs_account", self.default_attributes["bbs_account"])
+
+ @bbs_account.setter
+ def bbs_account(self, value):
+ return self.set_attribute("bbs_account", value)
+
+ @property
+ def last_ansible_hash(self):
+ return self.get_attribute("last_ansible_hash", self.default_attributes["last_ansible_hash"])
+
+ @last_ansible_hash.setter
+ def last_ansible_hash(self, value):
+ return self.set_attribute("last_ansible_hash", value)
+
+ @property
+ def ssh_command(self):
+ if self.instance:
+ return self.instance.get_ssh_command()
+ else:
+ return "no-instance"
+
+ @ssh_command.setter
+ def ssh_command(self, value):
+ pass
+
+ def get_vrouter_field(self, name, default=None):
+ if self.vrouter:
+ return getattr(self.vrouter, name, default)
+ else:
+ return default
+
+ @property
+ def wan_container_ip(self):
+ return self.get_vrouter_field("public_ip", None)
+
+ @property
+ def wan_container_mac(self):
+ return self.get_vrouter_field("public_mac", None)
+
+ @property
+ def wan_container_netbits(self):
+ return self.get_vrouter_field("netbits", None)
+
+ @property
+ def wan_container_gateway_ip(self):
+ return self.get_vrouter_field("gateway_ip", None)
+
+ @property
+ def wan_container_gateway_mac(self):
+ return self.get_vrouter_field("gateway_mac", None)
+
+ @property
+ def wan_vm_ip(self):
+ tags = Tag.select_by_content_object(self.instance).filter(name="vm_vrouter_tenant")
+ if tags:
+ tenant = VRouterTenant.objects.get(id=tags[0].value)
+ return tenant.public_ip
+ else:
+ raise Exception("no vm_vrouter_tenant tag for instance %s" % o.instance)
+
+ @property
+ def wan_vm_mac(self):
+ tags = Tag.select_by_content_object(self.instance).filter(name="vm_vrouter_tenant")
+ if tags:
+ tenant = VRouterTenant.objects.get(id=tags[0].value)
+ return tenant.public_mac
+ else:
+ raise Exception("no vm_vrouter_tenant tag for instance %s" % o.instance)
+
+ @property
+ def is_synced(self):
+ return (self.enacted is not None) and (self.enacted >= self.updated)
+
+ @is_synced.setter
+ def is_synced(self, value):
+ pass
+
+ def get_vrouter_service(self):
+ vrouterServices = VRouterService.get_service_objects().all()
+ if not vrouterServices:
+ raise XOSConfigurationError("No VROUTER Services available")
+ return vrouterServices[0]
+
+ def manage_vrouter(self):
+ # Each vCPE object owns exactly one vRouterTenant object
+
+ if self.deleted:
+ return
+
+ if self.vrouter is None:
+ vrouter = self.get_vrouter_service().get_tenant(address_pool_name="addresses_vsg", subscriber_tenant = self)
+ vrouter.caller = self.creator
+ vrouter.save()
+
+ def cleanup_vrouter(self):
+ if self.vrouter:
+ # print "XXX cleanup vrouter", self.vrouter
+ self.vrouter.delete()
+
+ def cleanup_orphans(self):
+ # ensure vCPE only has one vRouter
+ cur_vrouter = self.vrouter
+ for vrouter in list(self.get_subscribed_tenants(VRouterTenant)):
+ if (not cur_vrouter) or (vrouter.id != cur_vrouter.id):
+ # print "XXX clean up orphaned vrouter", vrouter
+ vrouter.delete()
+
+ if self.orig_instance_id and (self.orig_instance_id != self.get_attribute("instance_id")):
+ instances=Instance.objects.filter(id=self.orig_instance_id)
+ if instances:
+ # print "XXX clean up orphaned instance", instances[0]
+ instances[0].delete()
+
+ def get_slice(self):
+ if not self.provider_service.slices.count():
+ print self, "dio porco"
+ raise XOSConfigurationError("The service has no slices")
+ slice = self.provider_service.slices.all()[0]
+ return slice
+
+ def get_vsg_service(self):
+ return VSGService.get_service_objects().get(id=self.provider_service.id)
+
+ def find_instance_for_s_tag(self, s_tag):
+ #s_tags = STagBlock.objects.find(s_s_tag)
+ #if s_tags:
+ # return s_tags[0].instance
+
+ tags = Tag.objects.filter(name="s_tag", value=s_tag)
+ if tags:
+ return tags[0].content_object
+
+ return None
+
+ def find_or_make_instance_for_s_tag(self, s_tag):
+ instance = self.find_instance_for_s_tag(self.volt.s_tag)
+ if instance:
+ return instance
+
+ flavors = Flavor.objects.filter(name="m1.small")
+ if not flavors:
+ raise XOSConfigurationError("No m1.small flavor")
+
+ slice = self.provider_service.slices.all()[0]
+
+ if slice.default_isolation == "container_vm":
+ (node, parent) = ContainerVmScheduler(slice).pick()
+ else:
+ (node, parent) = LeastLoadedNodeScheduler(slice, label=self.get_vsg_service().node_label).pick()
+
+ instance = Instance(slice = slice,
+ node = node,
+ image = self.image,
+ creator = self.creator,
+ deployment = node.site_deployment.deployment,
+ flavor = flavors[0],
+ isolation = slice.default_isolation,
+ parent = parent)
+
+ self.save_instance(instance)
+
+ return instance
+
+ def manage_container(self):
+ from core.models import Instance, Flavor
+
+ if self.deleted:
+ return
+
+ # For container or container_vm isolation, use what TenantWithCotnainer
+ # provides us
+ slice = self.get_slice()
+ if slice.default_isolation in ["container_vm", "container"]:
+ super(VSGTenant,self).manage_container()
+ return
+
+ if not self.volt:
+ raise XOSConfigurationError("This vCPE container has no volt")
+
+ if self.instance:
+ # We're good.
+ return
+
+ instance = self.find_or_make_instance_for_s_tag(self.volt.s_tag)
+ self.instance = instance
+ super(TenantWithContainer, self).save()
+
+ def cleanup_container(self):
+ if self.get_slice().default_isolation in ["container_vm", "container"]:
+ super(VSGTenant,self).cleanup_container()
+
+ # To-do: cleanup unused instances
+ pass
+
+ def manage_bbs_account(self):
+ if self.deleted:
+ return
+
+ if self.volt and self.volt.subscriber and self.volt.subscriber.url_filter_enable:
+ if not self.bbs_account:
+ # make sure we use the proxied VSGService object, not the generic Service object
+ vcpe_service = VSGService.objects.get(id=self.provider_service.id)
+ self.bbs_account = vcpe_service.allocate_bbs_account()
+ super(VSGTenant, self).save()
+ else:
+ if self.bbs_account:
+ self.bbs_account = None
+ super(VSGTenant, self).save()
+
+ def find_or_make_port(self, instance, network, **kwargs):
+ port = Port.objects.filter(instance=instance, network=network)
+ if port:
+ port = port[0]
+ else:
+ port = Port(instance=instance, network=network, **kwargs)
+ port.save()
+ return port
+
+ def get_lan_network(self, instance):
+ slice = self.provider_service.slices.all()[0]
+ if CORD_USE_VTN:
+ # there should only be one network private network, and its template should not be the management template
+ lan_networks = [x for x in slice.networks.all() if x.template.visibility=="private" and (not "management" in x.template.name)]
+ if len(lan_networks)>1:
+ raise XOSProgrammingError("The vSG slice should only have one non-management private network")
+ else:
+ lan_networks = [x for x in slice.networks.all() if "lan" in x.name]
+ if not lan_networks:
+ raise XOSProgrammingError("No lan_network")
+ return lan_networks[0]
+
+ def save_instance(self, instance):
+ with transaction.atomic():
+ instance.volumes = "/etc/dnsmasq.d,/etc/ufw"
+ super(VSGTenant, self).save_instance(instance)
+
+ if instance.isolation in ["container", "container_vm"]:
+ lan_network = self.get_lan_network(instance)
+ port = self.find_or_make_port(instance, lan_network, ip="192.168.0.1", port_id="unmanaged")
+ port.set_parameter("c_tag", self.volt.c_tag)
+ port.set_parameter("s_tag", self.volt.s_tag)
+ port.set_parameter("device", "eth1")
+ port.set_parameter("bridge", "br-lan")
+
+ wan_networks = [x for x in instance.slice.networks.all() if "wan" in x.name]
+ if not wan_networks:
+ raise XOSProgrammingError("No wan_network")
+ port = self.find_or_make_port(instance, wan_networks[0])
+ port.set_parameter("next_hop", value="10.0.1.253") # FIX ME
+ port.set_parameter("device", "eth0")
+
+ if instance.isolation in ["vm"]:
+ lan_network = self.get_lan_network(instance)
+ port = self.find_or_make_port(instance, lan_network)
+ port.set_parameter("c_tag", self.volt.c_tag)
+ port.set_parameter("s_tag", self.volt.s_tag)
+ port.set_parameter("neutron_port_name", "stag-%s" % self.volt.s_tag)
+ port.save()
+
+ # tag the instance with the s-tag, so we can easily find the
+ # instance later
+ if self.volt and self.volt.s_tag:
+ tags = Tag.objects.filter(name="s_tag", value=self.volt.s_tag)
+ if not tags:
+ tag = Tag(service=self.provider_service, content_object=instance, name="s_tag", value=self.volt.s_tag)
+ tag.save()
+
+ # VTN-CORD needs a WAN address for the VM, so that the VM can
+ # be configured.
+ if CORD_USE_VTN:
+ tags = Tag.select_by_content_object(instance).filter(name="vm_vrouter_tenant")
+ if not tags:
+ vrouter = self.get_vrouter_service().get_tenant(address_pool_name="addresses_vsg", subscriber_service = self.provider_service)
+ vrouter.set_attribute("tenant_for_instance_id", instance.id)
+ vrouter.save()
+ tag = Tag(service=self.provider_service, content_object=instance, name="vm_vrouter_tenant", value="%d" % vrouter.id)
+ tag.save()
+
+ def save(self, *args, **kwargs):
+ if not self.creator:
+ if not getattr(self, "caller", None):
+ # caller must be set when creating a vCPE since it creates a slice
+ raise XOSProgrammingError("VSGTenant's self.caller was not set")
+ self.creator = self.caller
+ if not self.creator:
+ raise XOSProgrammingError("VSGTenant's self.creator was not set")
+
+ super(VSGTenant, self).save(*args, **kwargs)
+ model_policy_vcpe(self.pk)
+
+ def delete(self, *args, **kwargs):
+ self.cleanup_vrouter()
+ self.cleanup_container()
+ super(VSGTenant, self).delete(*args, **kwargs)
+
+def model_policy_vcpe(pk):
+ # TODO: this should be made in to a real model_policy
+ with transaction.atomic():
+ vcpe = VSGTenant.objects.select_for_update().filter(pk=pk)
+ if not vcpe:
+ return
+ vcpe = vcpe[0]
+ vcpe.manage_container()
+ vcpe.manage_vrouter()
+ vcpe.manage_bbs_account()
+ vcpe.cleanup_orphans()
+
+
diff --git a/xos/services/cord/templates/vcpeadmin.html b/xos/onboard/vsg/templates/vcpeadmin.html
similarity index 100%
rename from xos/services/cord/templates/vcpeadmin.html
rename to xos/onboard/vsg/templates/vcpeadmin.html
diff --git a/xos/tosca/resources/vcpeservice.py b/xos/onboard/vsg/tosca/resources/vcpeservice.py
similarity index 100%
rename from xos/tosca/resources/vcpeservice.py
rename to xos/onboard/vsg/tosca/resources/vcpeservice.py
diff --git a/xos/onboard/vsg/vsg-onboard.yaml b/xos/onboard/vsg/vsg-onboard.yaml
new file mode 100644
index 0000000..b49914e
--- /dev/null
+++ b/xos/onboard/vsg/vsg-onboard.yaml
@@ -0,0 +1,25 @@
+tosca_definitions_version: tosca_simple_yaml_1_0
+
+description: Onboard the exampleservice
+
+imports:
+ - custom_types/xos.yaml
+
+topology_template:
+ node_templates:
+ servicecontroller#vsg:
+ type: tosca.nodes.ServiceController
+ properties:
+ base_url: file:///opt/xos/onboard/vsg/
+ # The following will concatenate with base_url automatically, if
+ # base_url is non-null.
+ models: models.py
+ admin: admin.py
+ synchronizer: synchronizer/manifest
+ #tosca_custom_types: exampleservice.yaml
+ tosca_resource: tosca/resources/vcpeservice.py
+ rest_service: subdirectory:vsg api/service/vsg/vsgservice.py
+ rest_tenant: subdirectory:cord api/tenant/cord/vsg.py
+ private_key: file:///opt/xos/key_import/vsg_rsa
+ public_key: file:///opt/xos/key_import/vsg_rsa.pub
+