vnfmgr upgrade from python2 to python3
[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         try:
43             request_serializer = VnfInfoSerializer(data=request.data)
44             if not request_serializer.is_valid():
45                 raise Exception(request_serializer.errors)
46
47             requestData = request_serializer.data
48             vnf_inst_id = ignore_case_get(requestData, "vnfInstId")
49             if VnfRegModel.objects.filter(id=vnf_inst_id):
50                 raise Exception("Vnf(%s) already exists." % vnf_inst_id)
51             VnfRegModel(
52                 id=vnf_inst_id,
53                 ip=ignore_case_get(requestData, "ip"),
54                 port=ignore_case_get(requestData, "port"),
55                 username=ignore_case_get(requestData, "username"),
56                 password=ignore_case_get(requestData, "password")).save()
57
58             response_serializer = ResponseSerializer(data={"vnfInstId": vnf_inst_id})
59             if not response_serializer.is_valid():
60                 raise Exception(response_serializer.errors)
61
62             return Response(data=response_serializer.data, status=status.HTTP_201_CREATED)
63         except Exception as e:
64             logger.error(e.args[0])
65             logger.error(traceback.format_exc())
66             return Response(data={'error': e.args[0]}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)
67
68
69 @swagger_auto_schema(method='put',
70                      request_body=VnfInfoSerializer(),
71                      responses={
72                          status.HTTP_202_ACCEPTED: 'successfully',
73                          status.HTTP_500_INTERNAL_SERVER_ERROR: 'internal error'})
74 @swagger_auto_schema(method='delete',
75                      responses={
76                          status.HTTP_204_NO_CONTENT: 'successfully',
77                          status.HTTP_500_INTERNAL_SERVER_ERROR: 'internal error'})
78 @swagger_auto_schema(methods=['get'],
79                      manual_parameters=[
80                          openapi.Parameter('test',
81                                            openapi.IN_QUERY,
82                                            "test manual param",
83                                            type=openapi.TYPE_BOOLEAN
84                                            ), ],
85                      responses={
86                          status.HTTP_200_OK: openapi.Response('response description', VnfInfoSerializer()),
87                          status.HTTP_500_INTERNAL_SERVER_ERROR: 'internal error'})
88 @api_view(http_method_names=['GET', 'PUT', 'DELETE'])
89 def access_vnf(request, *args, **kwargs):
90     vnf_inst_id = ignore_case_get(kwargs, "vnfInstId")
91     logger.info("Enter %s, method is %s, ", fun_name(), request.method)
92     logger.info("vnfInstId is %s, data is %s", vnf_inst_id, request.data)
93     try:
94         vnf = VnfRegModel.objects.filter(id=vnf_inst_id)
95         if not vnf:
96             err_msg = "Vnf(%s) does not exist." % vnf_inst_id
97             return Response(data={'error': err_msg}, status=status.HTTP_404_NOT_FOUND)
98         if request.method == 'GET':
99             resp = {
100                 "vnfInstId": vnf_inst_id,
101                 "ip": vnf[0].ip,
102                 "port": vnf[0].port,
103                 "username": vnf[0].username,
104                 "password": vnf[0].password
105             }
106             response_serializer = VnfInfoSerializer(data=resp)
107             if not response_serializer.is_valid():
108                 raise Exception(response_serializer.errors)
109
110             return Response(data=response_serializer.data, status=status.HTTP_200_OK)
111         elif request.method == 'PUT':
112             request_serializer = VnfInfoSerializer(data=request.data)
113             if not request_serializer.is_valid():
114                 raise Exception(request_serializer.errors)
115
116             requestData = request_serializer.data
117             ip = ignore_case_get(requestData, "ip")
118             port = ignore_case_get(requestData, "port")
119             username = ignore_case_get(requestData, "username")
120             password = ignore_case_get(requestData, "password")
121             if ip:
122                 vnf[0].ip = ip
123             if port:
124                 vnf[0].port = port
125             if username:
126                 vnf[0].username = username
127             if password:
128                 vnf[0].password = password
129             vnf[0].save()
130             return Response(data={}, status=status.HTTP_202_ACCEPTED)
131         else:
132             vnf.delete()
133             return Response(data={}, status=status.HTTP_204_NO_CONTENT)
134
135     except Exception as e:
136         logger.error(e.args[0])
137         logger.error(traceback.format_exc())
138         return Response(data={'error': e.args[0]}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)
139
140
141 @swagger_auto_schema(method='post',
142                      request_body=VnfConfigSerializer(),
143                      responses={
144                          status.HTTP_202_ACCEPTED: 'successfully',
145                          status.HTTP_500_INTERNAL_SERVER_ERROR: 'internal error'})
146 @api_view(http_method_names=['POST'])
147 def vnf_config(request, *args, **kwargs):
148     logger.info("Enter %s, data is %s", fun_name(), request.data)
149     try:
150         request_serializer = VnfConfigSerializer(data=request.data)
151         if not request_serializer.is_valid():
152             raise Exception(request_serializer.errors)
153
154         requestData = request_serializer.data
155         vnf_inst_id = ignore_case_get(requestData, "vnfInstanceId")
156         vnf = VnfRegModel.objects.filter(id=vnf_inst_id)
157         if not vnf:
158             raise Exception("Vnf(%s) does not exist." % vnf_inst_id)
159         ret = restcall.call_req(
160             base_url="http://%s:%s/" % (vnf[0].ip, vnf[0].port),
161             user=vnf[0].username,
162             passwd=vnf[0].password,
163             auth_type=restcall.rest_no_auth,
164             resource="v1/vnfconfig",
165             method="POST",
166             content=json.dumps(requestData))
167         if ret[0] != 0:
168             raise Exception("Failed to config Vnf(%s): %s" % (vnf_inst_id, ret[1]))
169
170         return Response(data={}, status=status.HTTP_202_ACCEPTED)
171     except Exception as e:
172         logger.error(e.args[0])
173         logger.error(traceback.format_exc())
174         return Response(data={'error': e.args[0]}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)