create op_occs 28/83128/1
authormaopengzhang <zhang.maopeng1@zte.com.cn>
Mon, 25 Mar 2019 03:06:25 +0000 (11:06 +0800)
committermaopengzhang <zhang.maopeng1@zte.com.cn>
Mon, 25 Mar 2019 03:06:25 +0000 (11:06 +0800)
create op_occs

Change-Id: Ideea8b353fa1541c157a6138710611fc6ccb22b4
Issue-ID: VFC-1214
Signed-off-by: maopengzhang <zhang.maopeng1@zte.com.cn>
lcm/ns/biz/ns_instant.py
lcm/ns/biz/ns_lcm_op_occ.py [new file with mode: 0644]
lcm/ns/const.py
lcm/ns/views/sol/instantiate_ns_views.py
lcm/pub/utils/fileutil.py
lcm/pub/utils/jobutil.py
lcm/pub/utils/values.py

index 2670e25..c9146ed 100644 (file)
@@ -53,8 +53,9 @@ class InstantNSService(object):
         self.req_data = plan_content
 
     def do_biz(self):
+        job_id = JobUtil.create_job("NS", "NS_INST", self.ns_inst_id)
+
         try:
-            job_id = JobUtil.create_job("NS", "NS_INST", self.ns_inst_id)
             logger.debug('ns-instant(%s) workflow starting...' % self.ns_inst_id)
             logger.debug('req_data=%s' % self.req_data)
             ns_inst = NSInstModel.objects.get(id=self.ns_inst_id)
@@ -152,13 +153,13 @@ class InstantNSService(object):
                                    nsinstid=self.ns_inst_id,
                                    endpointnumber=0).save()
             else:
-                # TODO:
+                # TODO
                 pass
             logger.debug("workflow option: %s" % config.WORKFLOW_OPTION)
             if config.WORKFLOW_OPTION == "wso2":
                 return self.start_wso2_workflow(job_id, ns_inst, plan_input)
             elif config.WORKFLOW_OPTION == "activiti":
-                return self.start_activiti_workflow()
+                return self.start_activiti_workflow(job_id, plan_input)
             elif config.WORKFLOW_OPTION == "grapflow":
                 return self.start_buildin_grapflow(job_id, plan_input)
             else:
diff --git a/lcm/ns/biz/ns_lcm_op_occ.py b/lcm/ns/biz/ns_lcm_op_occ.py
new file mode 100644 (file)
index 0000000..f808cd2
--- /dev/null
@@ -0,0 +1,61 @@
+# Copyright 2019 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 logging
+import datetime
+import uuid
+
+from lcm.pub.database.models import NSLcmOpOccModel
+from lcm.pub.utils.values import update_value
+
+
+logger = logging.getLogger(__name__)
+
+
+class NsLcmOpOcc(object):
+    @staticmethod
+    def create(nsInstanceId, lcmOperationType, operationState, isAutomaticInvocation, operationParams):
+        logger.debug("lcm_op_occ(%s,%s,%s,%s,%s) create begin." % (nsInstanceId, lcmOperationType, operationState, isAutomaticInvocation, operationParams))
+        cur_time = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
+        lcm_op_occ = NSLcmOpOccModel.objects.create(
+            id=str(uuid.uuid4()),
+            operation_state=operationState,
+            state_entered_time=cur_time,
+            start_time=cur_time,
+            ns_instance_id=nsInstanceId,
+            operation=lcmOperationType,
+            is_automatic_invocation=isAutomaticInvocation,
+            operation_params=operationParams,
+            is_cancel_pending=False
+        )
+        logger.debug("lcm_op_occ(%s) create successfully." % lcm_op_occ.id)
+        return lcm_op_occ.id
+
+    @staticmethod
+    def update(occ_id, operationState=None, isCancelPending=None, cancelMode=None, error=None, resourceChanges=None):
+        lcm_op_occ = NSLcmOpOccModel.objects.get(id=occ_id)
+        if operationState:
+            lcm_op_occ.operation_state = operationState
+            lcm_op_occ.state_entered_time = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
+        if isCancelPending:
+            lcm_op_occ.is_cancel_pending = isCancelPending
+        if cancelMode:
+            lcm_op_occ.cancel_mode = cancelMode
+        if error:
+            lcm_op_occ.error = error
+        if resourceChanges:
+            lcm_op_occ.resource_changes = update_value(lcm_op_occ.resourceChanges if lcm_op_occ.resourceChanges else {}, resourceChanges)
+        lcm_op_occ.save()
+        logger.debug("lcm_op_occ(%s) update successfully." % lcm_op_occ.id)
+        return lcm_op_occ.id
index 684c47f..7fd0fc9 100644 (file)
@@ -169,3 +169,4 @@ CHANGE_RESULT = [
 ]
 
 NS_INSTANCE_BASE_URI = MSB_BASE_URL + '/api/nslcm/v1/ns_instances/%s'
+NS_OCC_BASE_URI = MSB_BASE_URL + '/api/nslcm/v1/ns_lcm_op_occs/%s'
index c19bece..b258233 100644 (file)
 # limitations under the License.
 
 import logging
+from drf_yasg.utils import swagger_auto_schema
+from rest_framework import status
+from rest_framework.response import Response
 from rest_framework.views import APIView
 
+from lcm.ns.biz.ns_instant import InstantNSService
+from lcm.ns.serializers.sol.inst_ns_serializers import InstantNsReqSerializer
+from lcm.pub.exceptions import BadRequestException
+from lcm.ns.const import NS_OCC_BASE_URI
+
 logger = logging.getLogger(__name__)
 
 
 class InstantiateNsView(APIView):
+    @swagger_auto_schema(
+        request_body=InstantNsReqSerializer(),
+        responses={
+            status.HTTP_202_ACCEPTED: None,
+            status.HTTP_500_INTERNAL_SERVER_ERROR: "Inner error"
+        }
+    )
     def post(self, request, ns_instance_id):
-        # todo
-        return
+        logger.debug("Enter NSInstView::post::ns_instance_id=%s", ns_instance_id)
+        logger.debug("request.data=%s", request.data)
+        try:
+            req_serializer = InstantNsReqSerializer(data=request.data)
+            if not req_serializer.is_valid():
+                logger.debug("request.data is not valid,error: %s" % req_serializer.errors)
+                raise BadRequestException(req_serializer.errors)
+            ack = InstantNSService(ns_instance_id, request.data).do_biz()
+            nsLcmOpOccId = ack['nsLcmOpOccId']
+            response = Response(data={}, status=status.HTTP_202_ACCEPTED)
+            logger.debug("Location: %s" % ack['nsLcmOpOccId'])
+            response["Location"] = NS_OCC_BASE_URI % nsLcmOpOccId
+            logger.debug("Leave NSInstView::post::ack=%s", ack)
+            return response
+        except BadRequestException as e:
+            logger.error("Exception in CreateNS: %s", e.message)
+            data = {'status': status.HTTP_400_BAD_REQUEST, 'detail': e.message}
+            return Response(data=data, status=status.HTTP_400_BAD_REQUEST)
+        except Exception as e:
+            logger.error("Exception in CreateNS: %s", e.message)
+            data = {'status': status.HTTP_500_INTERNAL_SERVER_ERROR, 'detail': e.message}
+            return Response(data=data, status=status.HTTP_500_INTERNAL_SERVER_ERROR)
index 3568e5e..87cdfd9 100644 (file)
@@ -22,7 +22,7 @@ logger = logging.getLogger(__name__)
 
 def make_dirs(path):
     if not os.path.exists(path):
-        os.makedirs(path, 0777)
+        os.makedirs(path, 0o777)
 
 
 def delete_dirs(path):
index 89a3af0..3aa5635 100644 (file)
@@ -18,6 +18,7 @@ import traceback
 
 from lcm.pub.database.models import JobStatusModel, JobModel
 from lcm.pub.utils import idutil
+from functools import reduce
 
 logger = logging.getLogger(__name__)
 
index 10700d0..fbb75f6 100644 (file)
 # See the License for the specific language governing permissions and
 # limitations under the License.
 
+import logging
+
+logger = logging.getLogger(__name__)
+
 
 def ignore_case_get(args, key, def_val=""):
     if not key:
@@ -22,3 +26,22 @@ def ignore_case_get(args, key, def_val=""):
         if old_key.upper() == key.upper():
             return args[old_key]
     return def_val
+
+
+def update_value(origin_data, new_data):
+    logger.debug(origin_data)
+    if not isinstance(origin_data, dict):
+        str_data = origin_data.encode('utf-8')
+        logger.debug(str_data)
+        origin_data = eval(str_data)
+    logger.debug(isinstance(origin_data, dict))
+    logger.debug(new_data)
+    for k, v in new_data.iteritems():
+        if k not in origin_data:
+            origin_data[k] = v
+        else:
+            if isinstance(origin_data[k], list):
+                origin_data[k] = origin_data[k].extend(v)
+            else:
+                origin_data[k] = v
+    return origin_data