Refactor create sfc swagger generate logic
[vfc/nfvo/lcm.git] / lcm / ns / sfcs / views.py
1 # Copyright 2016 ZTE Corporation.
2 #
3 # Licensed under the Apache License, Version 2.0 (the "License");
4 # you may not use this file except in compliance with the License.
5 # You may obtain a copy of the License at
6 #
7 #         http://www.apache.org/licenses/LICENSE-2.0
8 #
9 # Unless required by applicable law or agreed to in writing, software
10 # distributed under the License is distributed on an "AS IS" BASIS,
11 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 # See the License for the specific language governing permissions and
13 # limitations under the License.
14
15
16 import json
17 import logging
18 import traceback
19 import uuid
20
21 import time
22 from rest_framework import status
23 from rest_framework.response import Response
24 from rest_framework.views import APIView
25 from drf_yasg.utils import swagger_auto_schema
26
27 from lcm.ns.sfcs.create_flowcla import CreateFlowClassifier
28 from lcm.ns.sfcs.create_port_chain import CreatePortChain
29 from lcm.ns.sfcs.create_portpairgp import CreatePortPairGroup
30 from lcm.ns.sfcs.create_sfc_worker import CreateSfcWorker
31 from lcm.ns.sfcs.sfc_instance import SfcInstance
32 from lcm.ns.sfcs.utils import get_fp_id, ignorcase_get
33 from lcm.ns.sfcs.serializers import CreateSfcInstReqSerializer, CreateSfcInstRespSerializer
34 from lcm.ns.sfcs.serializers import CreateSfcReqSerializer, CreateSfcRespSerializer
35
36 logger = logging.getLogger(__name__)
37
38
39 class SfcInstanceView(APIView):
40     @swagger_auto_schema(
41         request_body=CreateSfcInstReqSerializer(),
42         responses={
43             status.HTTP_200_OK: CreateSfcInstRespSerializer(),
44             status.HTTP_500_INTERNAL_SERVER_ERROR: "Inner error"
45         }
46     )
47     def post(self, request):
48         try:
49             req_serializer = CreateSfcInstReqSerializer(data=request.data)
50             if not req_serializer.is_valid():
51                 raise Exception(req_serializer.errors)
52
53             data = {
54                 'nsinstid': request.data['nsInstanceId'],
55                 "ns_model_data": json.loads(request.data['context']),
56                 'fpindex': request.data['fpindex'],
57                 'fpinstid': str(uuid.uuid4()),
58                 'sdncontrollerid': request.data["sdnControllerId"]}
59             rsp = SfcInstance(data).do_biz()
60
61             resp_serializer = CreateSfcInstRespSerializer(data=rsp)
62             if not resp_serializer.is_valid():
63                 raise Exception(resp_serializer.errors)
64
65             return Response(data=rsp, status=status.HTTP_200_OK)
66         except Exception as e:
67             logger.error(traceback.format_exc())
68             return Response(data={'error': e.message}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)
69
70
71 class PortPairGpView(APIView):
72     def post(self, request):
73         data = {
74             'fpinstid': request.data["fpinstid"],
75             "ns_model_data": json.loads(request.data['context']),
76             'nsinstid': request.data["nsinstanceid"]}
77         CreatePortPairGroup(data).do_biz()
78         return Response(status=status.HTTP_200_OK)
79
80
81 class FlowClaView(APIView):
82     def post(self, request):
83         data = {
84             'fpinstid': request.data["fpinstid"],
85             "ns_model_data": json.loads(request.data['context'])}
86         CreateFlowClassifier(data).do_biz()
87         return Response(status=status.HTTP_200_OK)
88
89
90 class PortChainView(APIView):
91     def post(self, request):
92         data = {
93             'fpinstid': request.data["fpinstid"],
94             "ns_model_data": json.loads(request.data['context'])}
95         CreatePortChain(data).do_biz()
96         return Response(status=status.HTTP_200_OK)
97
98
99 class SfcView(APIView):
100     @swagger_auto_schema(
101         request_body=CreateSfcReqSerializer(),
102         responses={
103             status.HTTP_200_OK: CreateSfcRespSerializer()
104         }
105     )
106     def post(self, request):
107         try:
108             logger.info("Create Service Function Chain start")
109             logger.info("service_function_chain_request: %s" % json.dumps(request.data))
110             logger.info("service_function_chain_context  : %s" % json.dumps(request.data['context']))
111             logger.info("service_function_chain_context  : %s" % request.data['context'])
112             logger.info("service_function_chain_instanceid : %s" % ignorcase_get(request.data, 'nsInstanceId'))
113             logger.info("service_function_chain_sdncontrollerid : %s" % ignorcase_get(request.data, 'sdnControllerId'))
114             logger.info("service_function_chain_fpindex : %s" % ignorcase_get(request.data, 'fpindex'))
115             ns_model_data = request.data['context']
116
117             req_serializer = CreateSfcReqSerializer(data=request.data)
118             if not req_serializer.is_valid():
119                 raise Exception(req_serializer.errors)
120         except Exception as e:
121             logger.error("Exception occurs: %s", e.message)
122             logger.error(traceback.format_exc())
123         data = {
124             'nsinstid': ignorcase_get(request.data, 'nsInstanceId'),
125             "ns_model_data": ns_model_data,
126             'fpindex': get_fp_id(ignorcase_get(request.data, 'fpindex'), ns_model_data),
127             'fpinstid': str(uuid.uuid4()),
128             'sdncontrollerid': ignorcase_get(request.data, 'sdnControllerId')
129         }
130         logger.info("Save FPInstModel start: ")
131         SfcInstance(data).do_biz()
132         logger.info("Save FPInstModel end: ")
133         worker = CreateSfcWorker(data)
134         job_id = worker.init_data()
135         worker.start()
136         logger.info("Service Function Chain Thread Sleep start : %s" % time.ctime())
137         time.sleep(2)
138         logger.info("Service Function Chain Thread Sleep end: %s" % time.ctime())
139         logger.info("Create Service Function Chain end")
140
141         resp_serializer = CreateSfcRespSerializer(data={"jobId": job_id,
142                                                         "sfcInstId": data["fpinstid"]})
143         if not resp_serializer.is_valid():
144             logger.error(resp_serializer.errors)
145
146         return Response(data={"jobId": job_id,
147                               "sfcInstId": data["fpinstid"]},
148                         status=status.HTTP_200_OK)