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