Refactor vfc-vnfmgr view.py
[vfc/gvnfm/vnfmgr.git] / mgr / mgr / vnfreg / views.py
1 # Copyright 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 import json
16 import logging
17 import traceback
18
19 from drf_yasg import openapi
20 from drf_yasg.utils import swagger_auto_schema
21 from rest_framework import status
22 from rest_framework.decorators import api_view
23 from rest_framework.response import Response
24 from rest_framework.views import APIView
25
26 from mgr.pub.database.models import VnfRegModel
27 from mgr.pub.utils import restcall
28 from mgr.pub.utils.syscomm import fun_name
29 from mgr.pub.utils.values import ignore_case_get
30 from mgr.vnfreg.serializers import VnfInfoSerializer, ResponseSerializer, VnfConfigSerializer
31
32 logger = logging.getLogger(__name__)
33
34
35 class vnfmgr_addvnf(APIView):
36     @swagger_auto_schema(request_body=VnfInfoSerializer(),
37                          responses={
38                              status.HTTP_201_CREATED: ResponseSerializer(),
39                              status.HTTP_500_INTERNAL_SERVER_ERROR: 'internal error'})
40     def post(self, request):
41         logger.info("Enter %s, data is %s", fun_name(), request.data)
42         request_serializer = VnfInfoSerializer(data=request.data)
43         request_isvalid = request_serializer.is_valid()
44         try:
45             if not request_isvalid:
46                 raise Exception(request_serializer.errors)
47
48             requestData = request_serializer.data
49             vnf_inst_id = ignore_case_get(requestData, "vnfInstId")
50             if VnfRegModel.objects.filter(id=vnf_inst_id):
51                 raise Exception("Vnf(%s) already exists." % vnf_inst_id)
52             VnfRegModel(
53                 id=vnf_inst_id,
54                 ip=ignore_case_get(requestData, "ip"),
55                 port=ignore_case_get(requestData, "port"),
56                 username=ignore_case_get(requestData, "username"),
57                 password=ignore_case_get(requestData, "password")).save()
58
59             response_serializer = ResponseSerializer(data={"vnfInstId": vnf_inst_id})
60             resp_isvalid = response_serializer.is_valid()
61             if not resp_isvalid:
62                 raise Exception(response_serializer.errors)
63
64             return Response(data=response_serializer.data, status=status.HTTP_201_CREATED)
65         except Exception as e:
66             logger.error(e.message)
67             logger.error(traceback.format_exc())
68             return Response(data={'error': e.message}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)
69
70
71 @swagger_auto_schema(method='put',
72                      request_body=VnfInfoSerializer(),
73                      responses={
74                          status.HTTP_202_ACCEPTED: 'successfully',
75                          status.HTTP_500_INTERNAL_SERVER_ERROR: 'internal error'})
76 @swagger_auto_schema(method='delete',
77                      responses={
78                          status.HTTP_204_NO_CONTENT: 'successfully',
79                          status.HTTP_500_INTERNAL_SERVER_ERROR: 'internal error'})
80 @swagger_auto_schema(methods=['get'],
81                      manual_parameters=[
82                          openapi.Parameter('test',
83                                            openapi.IN_QUERY,
84                                            "test manual param",
85                                            type=openapi.TYPE_BOOLEAN
86                                            ), ],
87                      responses={
88                          status.HTTP_200_OK: openapi.Response('response description', VnfInfoSerializer()),
89                          status.HTTP_500_INTERNAL_SERVER_ERROR: 'internal error'})
90 @api_view(http_method_names=['GET', 'PUT', 'DELETE'])
91 def access_vnf(request, *args, **kwargs):
92     vnf_inst_id = ignore_case_get(kwargs, "vnfInstId")
93     logger.info("Enter %s, method is %s, ", fun_name(), request.method)
94     logger.info("vnfInstId is %s, data is %s", vnf_inst_id, request.data)
95     try:
96         vnf = VnfRegModel.objects.filter(id=vnf_inst_id)
97         if not vnf:
98             err_msg = "Vnf(%s) does not exist." % vnf_inst_id
99             return Response(data={'error': err_msg}, status=status.HTTP_404_NOT_FOUND)
100         if request.method == 'GET':
101             resp = {
102                 "vnfInstId": vnf_inst_id,
103                 "ip": vnf[0].ip,
104                 "port": vnf[0].port,
105                 "username": vnf[0].username,
106                 "password": vnf[0].password
107             }
108             response_serializer = VnfInfoSerializer(data=resp)
109             if not response_serializer.is_valid():
110                 raise Exception(response_serializer.errors)
111
112             ret = response_serializer.data
113             normal_status = status.HTTP_200_OK
114         elif request.method == 'PUT':
115             request_serializer = VnfInfoSerializer(data=request.data)
116             request_isvalid = request_serializer.is_valid()
117
118             if not request_isvalid:
119                 raise Exception(request_serializer.errors)
120
121             requestData = request_serializer.data
122             ip = ignore_case_get(requestData, "ip")
123             port = ignore_case_get(requestData, "port")
124             username = ignore_case_get(requestData, "username")
125             password = ignore_case_get(requestData, "password")
126             if ip:
127                 vnf[0].ip = ip
128             if port:
129                 vnf[0].port = port
130             if username:
131                 vnf[0].username = username
132             if password:
133                 vnf[0].password = password
134             vnf[0].save()
135             ret = {}
136             normal_status = status.HTTP_202_ACCEPTED
137         else:
138             vnf.delete()
139             ret = {}
140             normal_status = status.HTTP_204_NO_CONTENT
141
142         return Response(data=ret, status=normal_status)
143     except Exception as e:
144         logger.error(e.message)
145         logger.error(traceback.format_exc())
146         return Response(data={'error': e.message}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)
147
148
149 @swagger_auto_schema(method='post',
150                      request_body=VnfConfigSerializer(),
151                      responses={
152                          status.HTTP_202_ACCEPTED: 'successfully',
153                          status.HTTP_500_INTERNAL_SERVER_ERROR: 'internal error'})
154 @api_view(http_method_names=['POST'])
155 def vnf_config(request, *args, **kwargs):
156     logger.info("Enter %s, data is %s", fun_name(), request.data)
157     try:
158         request_serializer = VnfConfigSerializer(data=request.data)
159         request_isvalid = request_serializer.is_valid()
160         if not request_isvalid:
161             raise Exception(request_serializer.errors)
162
163         requestData = request_serializer.data
164         vnf_inst_id = ignore_case_get(requestData, "vnfInstanceId")
165         vnf = VnfRegModel.objects.filter(id=vnf_inst_id)
166         if not vnf:
167             raise Exception("Vnf(%s) does not exist." % vnf_inst_id)
168         ret = restcall.call_req(
169             base_url="http://%s:%s/" % (vnf[0].ip, vnf[0].port),
170             user=vnf[0].username,
171             passwd=vnf[0].password,
172             auth_type=restcall.rest_no_auth,
173             resource="v1/vnfconfig",
174             method="POST",
175             content=json.dumps(requestData))
176         if ret[0] != 0:
177             raise Exception("Failed to config Vnf(%s): %s" % (vnf_inst_id, ret[1]))
178
179         return Response(data={}, status=status.HTTP_202_ACCEPTED)
180     except Exception as e:
181         logger.error(e.message)
182         logger.error(traceback.format_exc())
183         return Response(data={'error': e.message}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)