68abd9dc92aa0b9fef45f98e3ecdeb4fe1549bb0
[vfc/nfvo/lcm.git] / lcm / ns_sfcs / views / 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 import json
16 import logging
17 import time
18 import traceback
19 import uuid
20
21 from drf_yasg.utils import swagger_auto_schema
22 from lcm.ns_sfcs.biz.create_flowcla import CreateFlowClassifier
23 from lcm.ns_sfcs.biz.create_port_chain import CreatePortChain
24 from lcm.ns_sfcs.biz.create_portpairgp import CreatePortPairGroup
25 from lcm.ns_sfcs.biz.create_sfc_worker import CreateSfcWorker
26 from lcm.ns_sfcs.serializers.serializers import CreateFlowClaSerializer
27 from lcm.ns_sfcs.serializers.serializers import CreatePortChainSerializer
28 from lcm.ns_sfcs.serializers.serializers import CreatePortPairGpSerializer
29 from lcm.ns_sfcs.serializers.serializers import CreateSfcInstReqSerializer, CreateSfcInstRespSerializer
30 from lcm.ns_sfcs.serializers.serializers import CreateSfcReqSerializer, CreateSfcRespSerializer
31 from lcm.ns_sfcs.biz.sfc_instance import SfcInstance
32 from rest_framework import status
33 from rest_framework.response import Response
34 from rest_framework.views import APIView
35 from lcm.pub.exceptions import BadRequestException, NSLCMException
36
37 from lcm.ns_sfcs.biz.utils import get_fp_id, ignorcase_get
38
39 logger = logging.getLogger(__name__)
40
41
42 def view_safe_call_with_log(logger):
43     def view_safe_call(func):
44         def wrapper(*args, **kwargs):
45             try:
46                 return func(*args, **kwargs)
47             except BadRequestException as e:
48                 logger.error(e.args[0])
49                 return make_error_resp(
50                     detail=e.args[0],
51                     status=status.HTTP_400_BAD_REQUEST
52                 )
53             except NSLCMException as e:
54                 logger.error(e.args[0])
55                 return make_error_resp(
56                     detail=e.args[0],
57                     status=status.HTTP_500_INTERNAL_SERVER_ERROR
58                 )
59             except Exception as e:
60                 logger.error(e.args[0])
61                 logger.error(traceback.format_exc())
62                 return make_error_resp(
63                     detail='Unexpected exception',
64                     status=status.HTTP_500_INTERNAL_SERVER_ERROR
65                 )
66         return wrapper
67     return view_safe_call
68
69
70 def make_error_resp(status, detail):
71     return Response(
72         data={
73             'error': detail
74         },
75         status=status
76     )
77
78
79 class SfcInstanceView(APIView):
80     @swagger_auto_schema(
81         request_body=CreateSfcInstReqSerializer(),
82         responses={
83             status.HTTP_200_OK: CreateSfcInstRespSerializer(),
84             status.HTTP_500_INTERNAL_SERVER_ERROR: "Inner error"
85         }
86     )
87     @view_safe_call_with_log(logger)
88     def post(self, request):
89         try:
90             req_serializer = CreateSfcInstReqSerializer(data=request.data)
91             if not req_serializer.is_valid():
92                 raise BadRequestException(req_serializer.errors)
93
94             data = {
95                 'nsinstid': request.data['nsInstanceId'],
96                 "ns_model_data": json.loads(request.data['context']),
97                 'fpindex': request.data['fpindex'],
98                 'fpinstid': str(uuid.uuid4()),
99                 'sdncontrollerid': request.data["sdnControllerId"]}
100             rsp = SfcInstance(data).do_biz()
101
102             resp_serializer = CreateSfcInstRespSerializer(data=rsp)
103             if not resp_serializer.is_valid():
104                 raise NSLCMException(resp_serializer.errors)
105
106             return Response(data=rsp, status=status.HTTP_200_OK)
107         except Exception as e:
108             logger.error(traceback.format_exc())
109             return Response(data={'error': e.args[0]}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)
110
111
112 class PortPairGpView(APIView):
113     @swagger_auto_schema(
114         request_body=CreatePortPairGpSerializer(),
115         responses={
116             status.HTTP_200_OK: 'successful'
117         }
118     )
119     def post(self, request):
120         req_serializer = CreatePortPairGpSerializer(data=request.data)
121         if not req_serializer.is_valid():
122             logger.error(req_serializer.errors)
123
124         data = {
125             'fpinstid': request.data["fpinstid"],
126             "ns_model_data": json.loads(request.data['context']),
127             'nsinstid': request.data["nsinstanceid"]}
128         CreatePortPairGroup(data).do_biz()
129         return Response(status=status.HTTP_200_OK)
130
131
132 class FlowClaView(APIView):
133     @swagger_auto_schema(
134         request_body=CreateFlowClaSerializer(),
135         responses={
136             status.HTTP_200_OK: 'successful'
137         }
138     )
139     def post(self, request):
140         req_serializer = CreateFlowClaSerializer(data=request.data)
141         if not req_serializer.is_valid():
142             logger.error(req_serializer.errors)
143
144         data = {
145             'fpinstid': request.data["fpinstid"],
146             "ns_model_data": json.loads(request.data['context'])}
147         CreateFlowClassifier(data).do_biz()
148         return Response(status=status.HTTP_200_OK)
149
150
151 class PortChainView(APIView):
152     @swagger_auto_schema(
153         request_body=CreatePortChainSerializer(),
154         responses={
155             status.HTTP_200_OK: 'successful'
156         }
157     )
158     def post(self, request):
159         req_serializer = CreatePortChainSerializer(data=request.data)
160         if not req_serializer.is_valid():
161             logger.error(req_serializer.errors)
162
163         data = {
164             'fpinstid': request.data["fpinstid"],
165             "ns_model_data": json.loads(request.data['context'])}
166         CreatePortChain(data).do_biz()
167         return Response(status=status.HTTP_200_OK)
168
169
170 class SfcView(APIView):
171     @swagger_auto_schema(
172         request_body=CreateSfcReqSerializer(),
173         responses={
174             status.HTTP_200_OK: CreateSfcRespSerializer()
175         }
176     )
177     @view_safe_call_with_log(logger)
178     def post(self, request):
179         try:
180             logger.info("Create Service Function Chain start")
181             logger.info("service_function_chain_request: %s" % json.dumps(request.data))
182             logger.info("service_function_chain_context  : %s" % json.dumps(request.data['context']))
183             logger.info("service_function_chain_context  : %s" % request.data['context'])
184             logger.info("service_function_chain_instanceid : %s" % ignorcase_get(request.data, 'nsInstanceId'))
185             logger.info("service_function_chain_sdncontrollerid : %s" % ignorcase_get(request.data, 'sdnControllerId'))
186             logger.info("service_function_chain_fpindex : %s" % ignorcase_get(request.data, 'fpindex'))
187             ns_model_data = json.loads(request.data['context'])
188
189             req_serializer = CreateSfcReqSerializer(data=request.data)
190             if not req_serializer.is_valid():
191                 raise BadRequestException(req_serializer.errors)
192         except Exception as e:
193             logger.error("Exception occurs: %s", e.args[0])
194             logger.error(traceback.format_exc())
195         data = {
196             'nsinstid': ignorcase_get(request.data, 'nsInstanceId'),
197             "ns_model_data": ns_model_data,
198             'fpindex': get_fp_id(ignorcase_get(request.data, 'fpindex'), ns_model_data),
199             'fpinstid': str(uuid.uuid4()),
200             'sdncontrollerid': ignorcase_get(request.data, 'sdnControllerId')
201         }
202         logger.info("Save FPInstModel start: ")
203         SfcInstance(data).do_biz()
204         logger.info("Save FPInstModel end: ")
205         worker = CreateSfcWorker(data)
206         job_id = worker.init_data()
207         worker.start()
208         logger.info("Service Function Chain Thread Sleep start : %s" % time.ctime())
209         time.sleep(2)
210         logger.info("Service Function Chain Thread Sleep end: %s" % time.ctime())
211         logger.info("Create Service Function Chain end")
212
213         resp_serializer = CreateSfcRespSerializer(data={"jobId": job_id, "sfcInstId": data["fpinstid"]})
214         if not resp_serializer.is_valid():
215             logger.error(resp_serializer.errors)
216
217         return Response(data={"jobId": job_id, "sfcInstId": data["fpinstid"]}, status=status.HTTP_200_OK)