Add SYNC vSM services

Change-Id: Id428865eb341f6e74af5a0de3df5174bcee288fe
diff --git a/README.md b/README.md
new file mode 100644
index 0000000..e69de29
--- /dev/null
+++ b/README.md
diff --git a/xos/__init__.py b/xos/__init__.py
new file mode 100644
index 0000000..e69de29
--- /dev/null
+++ b/xos/__init__.py
diff --git a/xos/admin.py b/xos/admin.py
new file mode 100644
index 0000000..6f74757
--- /dev/null
+++ b/xos/admin.py
@@ -0,0 +1,112 @@
+from core.admin import ReadOnlyAwareAdmin, SliceInline
+from core.middleware import get_request
+from core.models import User
+
+from django import forms
+from django.contrib import admin
+
+from services.vsm.models import *
+
+class VSMServiceForm(forms.ModelForm):
+
+    class Meta:
+        model = VSMService
+        fields = '__all__'
+
+    def __init__(self, *args, **kwargs):
+        super(VSMServiceForm, self).__init__(*args, **kwargs)
+
+    def save(self, commit=True):
+        return super(VSMServiceForm, self).save(commit=commit)
+
+class VSMServiceAdmin(ReadOnlyAwareAdmin):
+
+    model = VSMService
+    verbose_name = "VSM Service"
+    verbose_name_plural = "VSM Services"
+    form = VSMServiceForm
+    inlines = [SliceInline]
+
+    list_display = ('backend_status_icon', 'name', 'enabled')
+    list_display_links = ('backend_status_icon', 'name')
+
+    fieldsets = [(None, {
+        'fields': ['backend_status_text', 'name', 'enabled', 'versionNumber', 'description',],
+        'classes':['suit-tab suit-tab-general',],
+        })]
+
+    readonly_fields = ('backend_status_text', )
+    user_readonly_fields = ['name', 'enabled', 'versionNumber', 'description',]
+
+    extracontext_registered_admins = True
+
+    suit_form_tabs = (
+        ('general', 'VSM Service Details', ),
+        ('slices', 'Slices',),
+        )
+
+    suit_form_includes = (('mcordadmin.html',
+                           'top',
+                           'administration'),)
+
+    def get_queryset(self, request):
+        return VSMService.get_service_objects_by_user(request.user)
+
+admin.site.register(VSMService, VSMServiceAdmin)
+
+class VSMTenantForm(forms.ModelForm):
+
+    class Meta:
+        model = VSMTenant
+        fields = '__all__'
+
+    creator = forms.ModelChoiceField(queryset=User.objects.all())
+
+    def __init__(self, *args, **kwargs):
+        super(VSMTenantForm, self).__init__(*args, **kwargs)
+
+        self.fields['kind'].widget.attrs['readonly'] = True
+        self.fields['kind'].initial = "vSm"
+
+        self.fields['provider_service'].queryset = VSMService.get_service_objects().all()
+
+        if self.instance:
+            self.fields['creator'].initial = self.instance.creator
+            self.fields['tenant_message'].initial = self.instance.tenant_message
+            self.fields['image_name'].initial = self.instance.image_name
+
+        if (not self.instance) or (not self.instance.pk):
+            self.fields['creator'].initial = get_request().user
+            if VSMService.get_service_objects().exists():
+                self.fields['provider_service'].initial = VSMService.get_service_objects().all()[0]
+
+    def save(self, commit=True):
+        self.instance.creator = self.cleaned_data.get('creator')
+        self.instance.tenant_message = self.cleaned_data.get('tenant_message')
+        self.instance.image_name = self.cleaned_data.get('image_name')
+        return super(VSMTenantForm, self).save(commit=commit)
+
+
+class VSMTenantAdmin(ReadOnlyAwareAdmin):
+
+    verbose_name = "VSM Service Tenant"
+    verbose_name_plural = "VSM Service Tenants"
+
+    list_display = ('id', 'backend_status_icon', 'instance', 'tenant_message', 'image_name')
+    list_display_links = ('backend_status_icon', 'instance', 'tenant_message', 'id', 'image_name')
+
+    fieldsets = [(None, {
+        'fields': ['backend_status_text', 'kind', 'provider_service', 'instance', 'creator', 'tenant_message', 'image_name'],
+        'classes': ['suit-tab suit-tab-general'],
+        })]
+
+    readonly_fields = ('backend_status_text', 'instance',)
+
+    form = VSMTenantForm
+
+    suit_form_tabs = (('general', 'Details'),)
+
+    def get_queryset(self, request):
+        return VSMTenant.get_tenant_objects_by_user(request.user)
+
+admin.site.register(VSMTenant, VSMTenantAdmin)
diff --git a/xos/header.py b/xos/header.py
new file mode 100644
index 0000000..a2f8bd7
--- /dev/null
+++ b/xos/header.py
@@ -0,0 +1,23 @@
+from django.db import models
+from core.models import Service, PlCoreBase, Slice, Instance, Tenant, TenantWithContainer, Node, Image, User, Flavor, 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 *
+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
+from django.contrib.contenttypes.models import ContentType
+from django.contrib.contenttypes.fields import GenericForeignKey
+
+class ConfigurationError(Exception):
+    pass
+
+VSM_KIND = "vEPC"
+
+CORD_USE_VTN = getattr(Config(), "networking_use_vtn", False)
+
diff --git a/xos/make_synchronizer_manifest.sh b/xos/make_synchronizer_manifest.sh
new file mode 100644
index 0000000..061a261
--- /dev/null
+++ b/xos/make_synchronizer_manifest.sh
@@ -0,0 +1,2 @@
+#! /bin/bash
+find synchronizer -type f | cut -b 14- > synchronizer/manifest
\ No newline at end of file
diff --git a/xos/synchronizer/Dockerfile.synchronizer b/xos/synchronizer/Dockerfile.synchronizer
new file mode 100644
index 0000000..b870114
--- /dev/null
+++ b/xos/synchronizer/Dockerfile.synchronizer
@@ -0,0 +1,39 @@
+# xosproject/vsm-synchronizer
+FROM xosproject/xos-synchronizer-base:candidate
+
+COPY . /opt/xos/synchronizers/vsm
+
+ENTRYPOINT []
+
+WORKDIR "/opt/xos/synchronizers/vsm"
+
+# Label image
+ARG org_label_schema_schema_version=1.0
+ARG org_label_schema_name=vsm-synchronizer
+ARG org_label_schema_version=unknown
+ARG org_label_schema_vcs_url=unknown
+ARG org_label_schema_vcs_ref=unknown
+ARG org_label_schema_build_date=unknown
+ARG org_opencord_vcs_commit_date=unknown
+ARG org_opencord_component_chameleon_version=unknown
+ARG org_opencord_component_chameleon_vcs_url=unknown
+ARG org_opencord_component_chameleon_vcs_ref=unknown
+ARG org_opencord_component_xos_version=unknown
+ARG org_opencord_component_xos_vcs_url=unknown
+ARG org_opencord_component_xos_vcs_ref=unknown
+
+LABEL org.label-schema.schema-version=$org_label_schema_schema_version \
+      org.label-schema.name=$org_label_schema_name \
+      org.label-schema.version=$org_label_schema_version \
+      org.label-schema.vcs-url=$org_label_schema_vcs_url \
+      org.label-schema.vcs-ref=$org_label_schema_vcs_ref \
+      org.label-schema.build-date=$org_label_schema_build_date \
+      org.opencord.vcs-commit-date=$org_opencord_vcs_commit_date \
+      org.opencord.component.chameleon.version=$org_opencord_component_chameleon_version \
+      org.opencord.component.chameleon.vcs-url=$org_opencord_component_chameleon_vcs_url \
+      org.opencord.component.chameleon.vcs-ref=$org_opencord_component_chameleon_vcs_ref \
+      org.opencord.component.xos.version=$org_opencord_component_xos_version \
+      org.opencord.component.xos.vcs-url=$org_opencord_component_xos_vcs_url \
+      org.opencord.component.xos.vcs-ref=$org_opencord_component_xos_vcs_ref
+
+CMD bash -c "cd /opt/xos/synchronizers/vsm; ./run-from-api.sh"
diff --git a/xos/synchronizer/manifest b/xos/synchronizer/manifest
new file mode 100644
index 0000000..2493b08
--- /dev/null
+++ b/xos/synchronizer/manifest
@@ -0,0 +1,8 @@
+manifest
+model-deps
+run.sh
+steps/sync_vsmtenant.py
+steps/vsmtenant_playbook.yaml
+stop.sh
+vsm-synchronizer.py
+vsmservice_config
diff --git a/xos/synchronizer/model-deps b/xos/synchronizer/model-deps
new file mode 100644
index 0000000..0967ef4
--- /dev/null
+++ b/xos/synchronizer/model-deps
@@ -0,0 +1 @@
+{}
diff --git a/xos/synchronizer/run-from-api.sh b/xos/synchronizer/run-from-api.sh
new file mode 100755
index 0000000..9991dfa
--- /dev/null
+++ b/xos/synchronizer/run-from-api.sh
@@ -0,0 +1,2 @@
+export XOS_DIR=/opt/xos
+python vsm-synchronizer.py  -C $XOS_DIR/synchronizers/vsm/vsm_from_api_config
diff --git a/xos/synchronizer/steps/sync_vmmetenant.py b/xos/synchronizer/steps/sync_vmmetenant.py
new file mode 100644
index 0000000..cf42ee0
--- /dev/null
+++ b/xos/synchronizer/steps/sync_vmmetenant.py
@@ -0,0 +1,54 @@
+import os
+import sys
+from django.db.models import Q, F
+from synchronizers.new_base.modelaccessor import *
+from synchronizers.new_base.SyncInstanceUsingAnsible import SyncInstanceUsingAnsible
+
+parentdir = os.path.join(os.path.dirname(__file__), "..")
+sys.path.insert(0, parentdir)
+
+class SyncVSMTenant(SyncInstanceUsingAnsible):
+
+    provides = [VSMTenant]
+
+    observes = VSMTenant
+
+    requested_interval = 0
+
+    template_name = "vsmtenant_playbook.yaml"
+
+    service_key_name = "/opt/xos/synchronizers/vsm/vsm_private_key"
+
+    def __init__(self, *args, **kwargs):
+        super(SyncVSMTenant, self).__init__(*args, **kwargs)
+
+    def fetch_pending(self, deleted):
+
+        if (not deleted):
+            objs = VSMTenant.get_tenant_objects().filter(
+                Q(enacted__lt=F('updated')) | Q(enacted=None), Q(lazy_blocked=False))
+        else:
+            # If this is a deletion we get all of the deleted tenants..
+            objs = VSMTenant.get_deleted_tenant_objects()
+
+        return objs
+
+    def get_vsmservice(self, o):
+        if not o.provider_service:
+            return None
+
+        vsmservice = VSMService.get_service_objects().filter(id=o.provider_service.id)
+
+        if not vsmservice:
+            return None
+
+        return vsmservice[0]
+
+    # Gets the attributes that are used by the Ansible template but are not
+    # part of the set of default attributes.
+    def get_extra_attributes(self, o):
+        fields = {}
+        fields['tenant_message'] = o.tenant_message
+        fields['image_name'] = o.image_name
+        return fields
+
diff --git a/xos/synchronizer/steps/vmmetenant_playbook.yaml b/xos/synchronizer/steps/vmmetenant_playbook.yaml
new file mode 100644
index 0000000..c8a74d0
--- /dev/null
+++ b/xos/synchronizer/steps/vmmetenant_playbook.yaml
@@ -0,0 +1,10 @@
+--- 
+- hosts: {{ instance_name }} 
+  gather_facts: False 
+  connection: ssh 
+  user: ubuntu 
+  sudo: yes 
+  tasks: 
+ 
+ # - name: write message
+ #   shell: echo "{{ tenant_message }}" > /var/tmp/index.html
diff --git a/xos/synchronizer/stop.sh b/xos/synchronizer/stop.sh
new file mode 100644
index 0000000..b3f35d6
--- /dev/null
+++ b/xos/synchronizer/stop.sh
@@ -0,0 +1,2 @@
+# Kill the observer
+pkill -9 -f vsm-synchronizer.py
diff --git a/xos/synchronizer/vmm-synchronizer.py b/xos/synchronizer/vmm-synchronizer.py
new file mode 100644
index 0000000..e91f27a
--- /dev/null
+++ b/xos/synchronizer/vmm-synchronizer.py
@@ -0,0 +1,13 @@
+#!/usr/bin/env python
+
+# Runs the standard XOS observer
+
+import importlib
+import os
+import sys
+
+observer_path = os.path.join(os.path.dirname(
+    os.path.realpath(__file__)), "../../synchronizers/new_base")
+sys.path.append(observer_path)
+mod = importlib.import_module("xos-synchronizer")
+mod.main()
diff --git a/xos/synchronizer/vmm_from_api_config b/xos/synchronizer/vmm_from_api_config
new file mode 100644
index 0000000..0bf31f5
--- /dev/null
+++ b/xos/synchronizer/vmm_from_api_config
@@ -0,0 +1,20 @@
+# Sets options for the synchronizer
+[observer]
+name=vsm
+dependency_graph=/opt/xos/synchronizers/vsm/model-deps
+steps_dir=/opt/xos/synchronizers/vsm/steps
+sys_dir=/opt/xos/synchronizers/vsm/sys
+#logfile=/var/log/xos_backend.log
+log_file=console
+log_level=debug
+pretend=False
+backoff_disabled=True
+save_ansible_output=True
+proxy_ssh=True
+proxy_ssh_key=/opt/cord_profile/node_key
+proxy_ssh_user=root
+accessor_kind=api
+accessor_password=@/opt/xos/services/vsm/credentials/xosadmin@opencord.org
+
+[networking]
+use_vtn=True
diff --git a/xos/templates/mcordadmin.html b/xos/templates/mcordadmin.html
new file mode 100644
index 0000000..106be25
--- /dev/null
+++ b/xos/templates/mcordadmin.html
@@ -0,0 +1,9 @@
+<div class = "left-nav">
+  <ul>
+    <li>
+      <a href="/admin/mcordservice/vsmcomponent/">
+        MCORD Service Components
+      </a>
+    </li>
+  </ul>
+</div>
diff --git a/xos/tosca/custom_types/macros.m4 b/xos/tosca/custom_types/macros.m4
new file mode 100644
index 0000000..1f48f10
--- /dev/null
+++ b/xos/tosca/custom_types/macros.m4
@@ -0,0 +1,84 @@
+# Note: Tosca derived_from isn't working the way I think it should, it's not
+#    inheriting from the parent template. Until we get that figured out, use
+#    m4 macros do our inheritance
+
+define(xos_base_props,
+            no-delete:
+                type: boolean
+                default: false
+                description: Do not allow Tosca to delete this object
+            no-create:
+                type: boolean
+                default: false
+                description: Do not allow Tosca to create this object
+            no-update:
+                type: boolean
+                default: false
+                description: Do not allow Tosca to update this object
+            replaces:
+                type: string
+                required: false
+                descrption: Replaces/renames this object)
+# Service
+define(xos_base_service_caps,
+            scalable:
+                type: tosca.capabilities.Scalable
+            service:
+                type: tosca.capabilities.xos.Service)
+define(xos_base_service_props,
+            kind:
+                type: string
+                default: generic
+                description: Type of service.
+            view_url:
+                type: string
+                required: false
+                description: URL to follow when icon is clicked in the Service Directory.
+            icon_url:
+                type: string
+                required: false
+                description: ICON to display in the Service Directory.
+            enabled:
+                type: boolean
+                default: true
+            published:
+                type: boolean
+                default: true
+                description: If True then display this Service in the Service Directory.
+            public_key:
+                type: string
+                required: false
+                description: Public key to install into Instances to allows Services to SSH into them.
+            private_key_fn:
+                type: string
+                required: false
+                description: Location of private key file
+            versionNumber:
+                type: string
+                required: false
+                description: Version number of Service.)
+# Subscriber
+define(xos_base_subscriber_caps,
+            subscriber:
+                type: tosca.capabilities.xos.Subscriber)
+define(xos_base_subscriber_props,
+            kind:
+                type: string
+                default: generic
+                description: Kind of subscriber
+            service_specific_id:
+                type: string
+                required: false
+                description: Service specific ID opaque to XOS but meaningful to service)
+define(xos_base_tenant_props,
+            kind:
+                type: string
+                default: generic
+                description: Kind of tenant
+            service_specific_id:
+                type: string
+                required: false
+                description: Service specific ID opaque to XOS but meaningful to service)
+
+# end m4 macros
+
diff --git a/xos/tosca/custom_types/vsm.m4 b/xos/tosca/custom_types/vsm.m4
new file mode 100644
index 0000000..4589380
--- /dev/null
+++ b/xos/tosca/custom_types/vsm.m4
@@ -0,0 +1,18 @@
+tosca_definitions_version: tosca_simple_yaml_1_0
+
+# compile this with "m4 vsm.m4 > vsm.yaml"
+
+# include macros
+include(macros.m4)
+
+node_types:
+    tosca.nodes.VSMService:
+        derived_from: tosca.nodes.Root
+        description: >
+            VSM Service
+        capabilities:
+            xos_base_service_caps
+        properties:
+            xos_base_props
+            xos_base_service_props
+
diff --git a/xos/tosca/custom_types/vsm.yaml b/xos/tosca/custom_types/vsm.yaml
new file mode 100644
index 0000000..274f1cd
--- /dev/null
+++ b/xos/tosca/custom_types/vsm.yaml
@@ -0,0 +1,81 @@
+tosca_definitions_version: tosca_simple_yaml_1_0
+
+# compile this with "m4 vsm.m4 > vsm.yaml"
+
+# include macros
+# Note: Tosca derived_from isn't working the way I think it should, it's not
+#    inheriting from the parent template. Until we get that figured out, use
+#    m4 macros do our inheritance
+
+
+# Service
+
+
+# Subscriber
+
+
+
+
+# end m4 macros
+
+
+
+node_types:
+    tosca.nodes.VSMService:
+        derived_from: tosca.nodes.Root
+        description: >
+            VSM Service
+        capabilities:
+            scalable:
+                type: tosca.capabilities.Scalable
+            service:
+                type: tosca.capabilities.xos.Service
+        properties:
+            no-delete:
+                type: boolean
+                default: false
+                description: Do not allow Tosca to delete this object
+            no-create:
+                type: boolean
+                default: false
+                description: Do not allow Tosca to create this object
+            no-update:
+                type: boolean
+                default: false
+                description: Do not allow Tosca to update this object
+            replaces:
+                type: string
+                required: false
+                descrption: Replaces/renames this object
+            kind:
+                type: string
+                default: generic
+                description: Type of service.
+            view_url:
+                type: string
+                required: false
+                description: URL to follow when icon is clicked in the Service Directory.
+            icon_url:
+                type: string
+                required: false
+                description: ICON to display in the Service Directory.
+            enabled:
+                type: boolean
+                default: true
+            published:
+                type: boolean
+                default: true
+                description: If True then display this Service in the Service Directory.
+            public_key:
+                type: string
+                required: false
+                description: Public key to install into Instances to allows Services to SSH into them.
+            private_key_fn:
+                type: string
+                required: false
+                description: Location of private key file
+            versionNumber:
+                type: string
+                required: false
+                description: Version number of Service.
+
diff --git a/xos/tosca/resources/vsmservice.py b/xos/tosca/resources/vsmservice.py
new file mode 100644
index 0000000..b702029
--- /dev/null
+++ b/xos/tosca/resources/vsmservice.py
@@ -0,0 +1,7 @@
+from services.vsm.models import VSMService
+from service import XOSService
+
+class XOSVSMService(XOSService):
+	provides = "tosca.nodes.VSMService"
+	xos_model = VSMService
+	copyin_props = ["view_url", "icon_url", "enabled", "published", "public_key", "private_key_fn", "versionNumber"]
\ No newline at end of file
diff --git a/xos/tosca/resources/vsmtenant.py b/xos/tosca/resources/vsmtenant.py
new file mode 100644
index 0000000..56b2472
--- /dev/null
+++ b/xos/tosca/resources/vsmtenant.py
@@ -0,0 +1,30 @@
+from services.vsm.models import VSMTenant, VSMService
+from xosresource import XOSResource
+
+class XOSVSMTenant(XOSResource):
+    provides = "tosca.nodes.VSMTenant"
+    xos_model = VSMTenant
+    copyin_props = ["tenant_message", "image_name"]  
+    name_field = None  
+
+    def get_xos_args(self, throw_exception=True):
+        args = super(XOSVSMTenant, self).get_xos_args()
+
+        provider_name = self.get_requirement("tosca.relationships.MemberOfService", throw_exception=throw_exception)
+        if provider_name:
+            args["provider_service"] = self.get_xos_object(VSMService, throw_exception=throw_exception, name=provider_name)
+
+        return args
+
+    def get_existing_objs(self):
+        args = self.get_xos_args(throw_exception=False)
+        provider_service = args.get("provider", None)
+        if provider_service:
+            return [ self.get_xos_object(provider_service=provider_service) ]
+        return []
+
+    def postprocess(self, obj):
+        pass
+
+    def can_delete(self, obj):
+        return super(XOSVSMTenant, self).can_delete(obj)
diff --git a/xos/vsm-onboard.yaml b/xos/vsm-onboard.yaml
new file mode 100644
index 0000000..bd8463a
--- /dev/null
+++ b/xos/vsm-onboard.yaml
@@ -0,0 +1,24 @@
+tosca_definitions_version: tosca_simple_yaml_1_0
+
+description: Onboard the vSM service
+
+imports:
+  - custom_types/xos.yaml
+
+topology_template:
+  node_templates:
+    servicecontroller#vsm:
+      type: tosca.nodes.ServiceController
+      properties:
+          base_url: file:///opt/xos_services/vsm/xos/
+          # The following will concatenate with base_url automatically, if
+          # base_url is non-null.
+          xproto: ./
+          admin: admin.py
+          admin_template: templates/mcordadmin.html
+          tosca_custom_types: tosca/custom_types/vsm.yaml
+          synchronizer: synchronizer/manifest
+          synchronizer_run: vsm-synchronizer.py
+          tosca_resource: tosca/resources/vsmtenant.py, tosca/resources/vsmservice.py
+          private_key: file:///opt/xos/key_import/mcord_rsa
+          public_key: file:///opt/xos/key_import/mcord_rsa.pub
diff --git a/xos/vsm.xproto b/xos/vsm.xproto
new file mode 100644
index 0000000..179a494
--- /dev/null
+++ b/xos/vsm.xproto
@@ -0,0 +1,15 @@
+option name = "vsm";
+option app_label = "vsm";
+option verbose_name = "vsM Service";
+option kind = "vEPC";
+
+message VSMService (Service){
+    required string service_message = 1 [help_text = "Service Message to Display", max_length = 254, null = False, db_index = False, blank = False];
+}
+
+
+message VSMTenant (TenantWithContainer){
+     option name = "vsmtenant";
+     option verbose_name = "vSM Tenant";
+     required string tenant_message = 1 [help_text = "Tenant Message to Display", max_length = 254, null = False, db_index = False, blank = False];
+}