8fa4ba77fac31334c56d4bcec2aa186432e7df7f
[vfc/nfvo/lcm.git] / lcm / ns / views.py
1 # Copyright 2016-2017 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 import json
15 import logging
16 import os
17 import traceback
18
19 from rest_framework import status
20 from rest_framework.response import Response
21 from rest_framework.views import APIView
22
23 from lcm.ns.ns_create import CreateNSService
24 from lcm.ns.ns_get import GetNSInfoService
25 from lcm.ns.ns_instant import InstantNSService
26 from lcm.ns.ns_manual_scale import NSManualScaleService
27 from lcm.ns.ns_heal import NSHealService
28 from lcm.ns.ns_terminate import TerminateNsService, DeleteNsService
29 from lcm.pub.database.models import NSInstModel, ServiceBaseInfoModel
30 from lcm.pub.utils.jobutil import JobUtil, JOB_TYPE
31 from lcm.pub.utils.values import ignore_case_get
32 from lcm.pub.utils.restcall import req_by_msb
33 from lcm.pub.exceptions import NSLCMException
34
35 logger = logging.getLogger(__name__)
36
37
38 class CreateNSView(APIView):
39     def get(self, request):
40         logger.debug("CreateNSView::get")
41         ret = GetNSInfoService().get_ns_info()
42         logger.debug("CreateNSView::get::ret=%s", ret)
43         return Response(data=ret, status=status.HTTP_200_OK)
44
45     def post(self, request):
46         logger.debug("Enter CreateNS: %s", request.data)
47         nsd_id = ignore_case_get(request.data, 'nsdId')
48         ns_name = ignore_case_get(request.data, 'nsName')
49         description = ignore_case_get(request.data, 'description')
50         try:
51             ns_inst_id = CreateNSService(nsd_id, ns_name, description).do_biz()
52         except Exception as e:
53             logger.error("Exception in CreateNS: %s", e.message)
54             return Response(data={'error': e.message}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)
55         logger.debug("CreateNSView::post::ret={'nsInstanceId':%s}", ns_inst_id)
56         return Response(data={'nsInstanceId': ns_inst_id}, status=status.HTTP_201_CREATED)
57
58
59 class NSInstView(APIView):
60     def post(self, request, ns_instance_id):
61         ack = InstantNSService(ns_instance_id, request.data).do_biz()
62         logger.debug("Leave NSInstView::post::ack=%s", ack)
63         return Response(data=ack['data'], status=ack['status'])
64
65
66 class TerminateNSView(APIView):
67     def post(self, request, ns_instance_id):
68         logger.debug("Enter TerminateNSView::post %s", request.data)
69         termination_type = ignore_case_get(request.data, 'terminationType')
70         graceful_termination_timeout = ignore_case_get(request.data, 'gracefulTerminationTimeout')
71         job_id = JobUtil.create_job("VNF", JOB_TYPE.TERMINATE_VNF, ns_instance_id)
72         try:
73             TerminateNsService(ns_instance_id, termination_type, graceful_termination_timeout, job_id).start()
74         except Exception as e:
75             logger.error("Exception in CreateNS: %s", e.message)
76             return Response(data={'error': e.message}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)
77         ret = {'jobId': job_id}
78         logger.debug("Leave TerminateNSView::post ret=%s", ret)
79         return Response(data=ret, status=status.HTTP_202_ACCEPTED)
80
81
82 class NSHealView(APIView):
83     def post(self, request, ns_instance_id):
84         logger.debug("Enter HealNSView::post %s", request.data)
85         job_id = JobUtil.create_job("VNF", JOB_TYPE.HEAL_VNF, ns_instance_id)
86         try:
87             NSHealService(ns_instance_id, request.data, job_id).start()
88         except Exception as e:
89             logger.error("Exception in HealNSView: %s", e.message)
90             return Response(data={'error': e.message}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)
91         ret = {'jobId': job_id}
92         logger.debug("Leave HealNSView::post ret=%s", ret)
93         return Response(data=ret, status=status.HTTP_202_ACCEPTED)
94
95
96 class NSDetailView(APIView):
97     def get(self, request, ns_instance_id):
98         logger.debug("Enter NSDetailView::get ns(%s)", ns_instance_id)
99         ret = GetNSInfoService(ns_instance_id).get_ns_info()
100         if not ret:
101             return Response(status=status.HTTP_404_NOT_FOUND)
102         logger.debug("Leave NSDetailView::get::ret=%s", ret)
103         return Response(data=ret, status=status.HTTP_200_OK)
104
105     def delete(self, request, ns_instance_id):
106         logger.debug("Enter NSDetailView::delete ns(%s)", ns_instance_id)
107         DeleteNsService(ns_instance_id).do_biz()
108         return Response(data={}, status=status.HTTP_204_NO_CONTENT)
109
110
111 class SwaggerJsonView(APIView):
112     def get(self, request):
113         json_file = os.path.join(os.path.dirname(__file__), 'swagger.json')
114         f = open(json_file)
115         json_data = json.JSONDecoder().decode(f.read())
116         f.close()
117         return Response(json_data)
118
119
120 class NSInstPostDealView(APIView):
121
122
123     def post(self, request, ns_instance_id):
124         logger.debug("Enter NSInstPostDealView::post %s, %s", request.data, ns_instance_id)
125         ns_post_status = ignore_case_get(request.data, 'status')
126         ns_status = 'ACTIVE' if ns_post_status == 'true' else 'FAILED'
127         ns_opr_status = 'success' if ns_post_status == 'true' else 'failed'
128         try:
129             NSInstModel.objects.filter(id=ns_instance_id).update(status=ns_status)
130             ServiceBaseInfoModel.objects.filter(service_id=ns_instance_id).update(
131                 active_status=ns_status, status=ns_opr_status)
132             nsd_info = NSInstModel.objects.filter(id=ns_instance_id)
133             nsd_id = nsd_info[0].nsd_id
134             nsd_model = json.loads(nsd_info[0].nsd_model)
135             if "policies" in nsd_model and nsd_model["policies"]:
136                 policy = nsd_model["policies"][0]
137                 if "properties" in policy and policy["properties"]:
138                     file_url = ignore_case_get(policy["properties"][0], "drl_file_url")
139                 else:
140                     file_url = ""
141                 self.send_policy_request(ns_instance_id, nsd_id, file_url)
142         except:
143             logger.error(traceback.format_exc())
144             return Response(data={'error': 'Failed to update status of NS(%s)' % ns_instance_id},
145                             status=status.HTTP_500_INTERNAL_SERVER_ERROR)
146         logger.debug("*****NS INST %s, %s******", ns_status, ns_opr_status)
147         return Response(data={'success': 'Update status of NS(%s) to %s' % (ns_instance_id, ns_status)},
148                         status=status.HTTP_202_ACCEPTED)
149
150     def send_policy_request(self,ns_instance_id, nsd_id, file_url):
151         input_data = {
152             "nsid": ns_instance_id,
153             "nsdid": nsd_id,
154             "fileUri":file_url
155         }
156         req_param = json.JSONEncoder().encode(input_data)
157         policy_engine_url = 'api/polengine/v1/policyinfo'
158         ret = req_by_msb(policy_engine_url, "POST", req_param)
159         if ret[0] != 0:
160             logger.error("Failed to send ns policy req")
161             #raise NSLCMException('Failed to send ns policy req)')
162
163
164 class NSManualScaleView(APIView):
165     def post(self, request, ns_instance_id):
166         logger.debug("Enter NSManualScaleView::post %s, %s", request.data, ns_instance_id)
167         job_id = JobUtil.create_job("NS", JOB_TYPE.MANUAL_SCALE_VNF, ns_instance_id)
168         try:
169             NSManualScaleService(ns_instance_id, request.data, job_id).start()
170         except Exception as e:
171             logger.error(traceback.format_exc())
172             JobUtil.add_job_status(job_id, 255, 'NS scale failed: %s' % e.message)
173             return Response(data={'error': 'NS scale failed: %s' % ns_instance_id},
174                             status=status.HTTP_500_INTERNAL_SERVER_ERROR)
175         return Response(data={'jobId': job_id}, status=status.HTTP_202_ACCEPTED)