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