Add Init codes of sdc_ns_pkg 55/7555/1
authorfujinhua <fu.jinhua@zte.com.cn>
Tue, 15 Aug 2017 06:41:28 +0000 (14:41 +0800)
committerfujinhua <fu.jinhua@zte.com.cn>
Tue, 15 Aug 2017 06:41:28 +0000 (14:41 +0800)
Change-Id: I1ff33e4bbeb1565320d83bbd24a70c10ce676db9
Issue-Id: VFC-93
Signed-off-by: fujinhua <fu.jinhua@zte.com.cn>
lcm/packages/sdc_ns_package.py [new file with mode: 0644]
lcm/packages/urls.py
lcm/packages/views.py
lcm/pub/msapi/sdc.py [new file with mode: 0644]

diff --git a/lcm/packages/sdc_ns_package.py b/lcm/packages/sdc_ns_package.py
new file mode 100644 (file)
index 0000000..f51ae85
--- /dev/null
@@ -0,0 +1,135 @@
+# Copyright 2016 ZTE Corporation.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+#         http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+import json
+import logging
+
+import traceback
+import sys
+
+from lcm.pub.database.models import NSDModel, NSInstModel
+from lcm.pub.utils.values import ignore_case_get
+from lcm.pub.exceptions import NSLCMException
+from lcm.pub.msapi import sdc
+
+logger = logging.getLogger(__name__)
+
+STATUS_SUCCESS, STATUS_FAILED = "success", "failed"
+
+
+def fmt_ns_pkg_rsp(status, desc, error_code="500"):
+    return [0, {"status": status, "statusDescription": desc, "errorCode": error_code}]
+
+
+def ns_common_call(fun, csar_id, operation=""):
+    ret = None
+    try:
+        if operation == "":
+            ret = fun(csar_id)
+        else:
+            ret = fun(csar_id, operation)
+
+        if ret[0] != 0:
+            return fmt_ns_pkg_rsp(STATUS_FAILED, ret[1])
+    except NSLCMException as e:
+        return fmt_ns_pkg_rsp(STATUS_FAILED, e.message)
+    except:
+        logger.error(traceback.format_exc())
+        return fmt_ns_pkg_rsp(STATUS_FAILED, str(sys.exc_info()))
+    return fmt_ns_pkg_rsp(STATUS_SUCCESS, ret[1], "")
+
+def ns_on_distribute(csar_id):
+    return ns_common_call(SdcNsPackage().on_distribute, csar_id)
+
+
+def ns_delete_csar(csar_id):
+    return ns_common_call(SdcNsPackage().delete_csar, csar_id)
+
+
+def ns_get_csar(csar_id):
+    ret = None
+    try:
+        ret = SdcNsPackage().get_csar(csar_id)
+    except NSLCMException as e:
+        return [1, e.message]
+    except:
+        logger.error(traceback.format_exc())
+        return [1, str(sys.exc_info())]
+    return ret
+
+
+###############################################################################################################
+
+class SdcNsPackage(object):
+    """
+    Actions for sdc ns package.
+    """
+
+    def __init__(self):
+        pass
+
+    def on_distribute(self, csar_id):
+        if NSDModel.objects.filter(id=csar_id):
+            raise NSLCMException("NS CSAR(%s) already exists." % csar_id)
+        artifact = sdc.get_artifact(sdc.ASSETTYPE_SERVICES, csar_id)
+        download_artifacts(artifact["toscaModelURL"], "TODO:Local Path")
+
+        NSDModel(
+            id=csar_id,
+            nsd_id="TODO",
+            name="TODO",
+            vendor="TODO",
+            description="TODO",
+            version="TODO",
+            nsd_model="TODO",
+            nsd_path="TODO").save()
+
+    def delete_csar(self, csar_id, force_delete):
+        if force_delete:
+            NSInstModel.objects.filter(nspackage_id=csar_id).delete()
+        else:
+            if NSInstModel.objects.filter(nspackage_id=csar_id):
+                raise NSLCMException("CSAR(%s) is in using, cannot be deleted." % csar_id)
+        NSDModel.objects.filter(id=csar_id).delete()
+
+
+    def get_csars(self):
+        ret = {"csars": []}
+        nss = NSDModel.objects.filter()
+        for ns in nss:
+            ret["csars"].append({
+                "csarId": ns.id,
+                "nsdId": ns.nsd_id
+            })
+        return ret
+
+    def get_csar(self, csar_id):
+        package_info = {}
+        csars = NSDModel.objects.filter(id=csar_id)
+        if csars:
+            package_info["nsdId"] = csars[0].nsd_id
+            package_info["nsdProvider"] = csars[0].vendor
+            package_info["nsdVersion"] = csars[0].version
+
+        nss = NSInstModel.objects.filter(nspackage_id=csar_id)
+        ns_instance_info = [{
+            "nsInstanceId": ns.id, 
+            "nsInstanceName": ns.name} for ns in nss]
+
+        return [0, {"csarId": csar_id, 
+            "packageInfo": package_info, 
+            "nsInstanceInfo": ns_instance_info}]
+
+
+       
\ No newline at end of file
index b2fd0ee..86af427 100644 (file)
@@ -17,6 +17,8 @@ from rest_framework.urlpatterns import format_suffix_patterns
 from lcm.packages import views
 
 urlpatterns = [
+    url(r'^api/nslcm/v1/nspackage$', views.ns_distribute, name='ns_distribute'),
+    #########################################################################################
     url(r'^api/nslcm/v0/nspackage/(?P<csarId>[0-9a-zA-Z\-\_]+)$', views.ns_access_csar, name='ns_access_csar'),
     url(r'^api/nslcm/v0/nspackage$', views.ns_on_boarding, name='ns_on_boarding'),
     url(r'^api/nslcm/v0/nspackage/(?P<csarId>[0-9a-zA-Z\-\_]+)/deletionpending$',
index c50c741..dd29d76 100644 (file)
@@ -21,10 +21,21 @@ from rest_framework.response import Response
 
 from lcm.pub.utils.values import ignore_case_get
 from lcm.pub.utils.syscomm import fun_name
-from lcm.packages import ns_package, nf_package
+from lcm.packages import ns_package, nf_package, sdc_ns_package
 
 logger = logging.getLogger(__name__)
 
+@api_view(http_method_names=['POST'])
+def ns_distribute(request, *args, **kwargs):
+    csar_id = ignore_case_get(request.data, "csarId")
+    logger.info("Enter %s, method is %s, csar_id is %s", fun_name(), request.method, csar_id)
+    ret = sdc_ns_package.ns_on_distribute(csar_id)
+    logger.info("Leave %s, Return value is %s", fun_name(), ret)
+    if ret[0] != 0:
+        return Response(data={'error': ret[1]}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)
+    return Response(data=ret[1], status=status.HTTP_202_ACCEPTED)
+
+####################################################################################################    
 
 @api_view(http_method_names=['POST'])
 def ns_on_boarding(request, *args, **kwargs):
diff --git a/lcm/pub/msapi/sdc.py b/lcm/pub/msapi/sdc.py
new file mode 100644 (file)
index 0000000..263c6cb
--- /dev/null
@@ -0,0 +1,72 @@
+# Copyright 2017 ZTE Corporation.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+#         http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+import json
+import logging
+
+from lcm.pub.exceptions import NSLCMException
+from lcm.pub.utils.restcall import call_req
+
+logger = logging.getLogger(__name__)
+
+ASSETTYPE_RESOURCES = "resources" 
+ASSETTYPE_SERVICES = "services"
+
+def call_sdc(resource, method, content=''):
+    base_url = "TODO: SDC Base URL"
+    sdc_user = "TODO: sdc user"
+    sdc_passwd = "TODO: sdc passwd"
+    sdc_auth_type = "TODO: sdc auth type"
+    return call_req(base_url, sdc_user, sdc_passwd, sdc_auth_type, resource, method, content)
+
+def get_artifacts(asset_type):
+    resource = "/sdc/v1/catalog/{assetType}"
+    resource = resource.format(assetType=asset_type)
+    ret = call_sdc(resource, "GET")
+    if ret[0] != 0:
+        logger.error("Status code is %s, detail is %s.", ret[2], ret[1])
+        raise NSLCMException("Failed to query artifacts(%s) from sdc." % asset_type)
+    return json.JSONDecoder().decode(ret[1])
+
+def get_artifact(asset_type, csar_id):
+    artifacts = get_artifacts(asset_type)
+    for artifact in artifacts:
+        if artifact["uuid"] == csar_id:
+            return artifact
+    raise NSLCMException("Failed to query artifact(%s,%s) from sdc." % (asset_type, csar_id))
+
+def delete_artifact(asset_type, asset_id, artifact_id):
+    resource = "/sdc/v1/catalog/{assetType}/{uuid}/artifacts/{artifactUUID}"
+    resource = resource.format(assetType=asset_type, uuid=asset_id, artifactUUID=artifact_id)
+    ret = call_sdc(resource, "DELETE")
+    if ret[0] != 0:
+        logger.error("Status code is %s, detail is %s.", ret[2], ret[1])
+        raise NSLCMException("Failed to delete artifacts(%s) from sdc." % artifact_id)
+    return json.JSONDecoder().decode(ret[1])
+
+def download_artifacts(download_url, local_path):
+    sdc_user = "TODO: sdc user"
+    sdc_passwd = "TODO: sdc passwd"
+    sdc_auth_type = "TODO: sdc auth type"
+    ret = call_req(download_url, sdc_user, sdc_passwd, sdc_auth_type, "", "GET")
+    
+
+    
+
+
+   
+
+
+
+