Add vfc-vnfmgr addvnf auto-swagger
[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 logging
16 import json
17 import traceback
18
19 from drf_yasg.utils import swagger_auto_schema
20 from rest_framework import status
21 from rest_framework.decorators import api_view
22 from rest_framework.response import Response
23 from rest_framework.views import APIView
24
25 from mgr.pub.utils.values import ignore_case_get
26 from mgr.pub.utils.syscomm import fun_name
27 from mgr.pub.database.models import VnfRegModel
28 from mgr.pub.utils import restcall
29 from mgr.vnfreg.serializers import ErrorSerializer, VnfInfoSerializer, ResponseSerializer
30
31 logger = logging.getLogger(__name__)
32
33
34 def handler_exception(e):
35     logger.error(e.message)
36     logger.error(traceback.format_exc())
37     errorSerializer = ErrorSerializer(data={'error': e.message})
38     errorSerializer.is_valid()
39     return errorSerializer.data
40
41
42 class vnfmgr_addvnf(APIView):
43     @swagger_auto_schema(request_body=VnfInfoSerializer(),
44                          responses={
45                              201: ResponseSerializer(),
46                              500: ErrorSerializer()})
47     def post(self, request):
48         logger.info("Enter %s, data is %s", fun_name(), request.data)
49         requestSerializer = VnfInfoSerializer(data=request.data)
50         request_isValid = requestSerializer.is_valid()
51         try:
52             if not request_isValid:
53                 raise Exception(requestSerializer.errors)
54
55             requestData = requestSerializer.data
56             vnf_inst_id = ignore_case_get(requestData, "vnfInstId")
57             if VnfRegModel.objects.filter(id=vnf_inst_id):
58                 raise Exception("Vnf(%s) already exists." % vnf_inst_id)
59             VnfRegModel(
60                 id=vnf_inst_id,
61                 ip=ignore_case_get(requestData, "ip"),
62                 port=ignore_case_get(requestData, "port"),
63                 username=ignore_case_get(requestData, "username"),
64                 password=ignore_case_get(requestData, "password")).save()
65
66             responseSerializer = ResponseSerializer(data={"vnfInstId": vnf_inst_id})
67             isValid = responseSerializer.is_valid()
68             if not isValid:
69                 raise Exception(responseSerializer.errors)
70         except Exception as e:
71             errorData = handler_exception(e)
72             return Response(data=errorData, status=status.HTTP_500_INTERNAL_SERVER_ERROR)
73
74         return Response(data=responseSerializer.data, status=status.HTTP_201_CREATED)
75
76
77 @api_view(http_method_names=['GET', 'PUT', 'DELETE'])
78 def access_vnf(request, *args, **kwargs):
79     vnf_inst_id = ignore_case_get(kwargs, "vnfInstId")
80     logger.info("Enter %s, method is %s, ", fun_name(), request.method)
81     logger.info("vnfInstId is %s, data is %s", vnf_inst_id, request.data)
82     try:
83         vnf = VnfRegModel.objects.filter(id=vnf_inst_id)
84         if not vnf:
85             err_msg = "Vnf(%s) does not exist." % vnf_inst_id
86             return Response(data={'error': err_msg}, status=status.HTTP_404_NOT_FOUND)
87         if request.method == 'GET':
88             ret = {
89                 "vnfInstId": vnf_inst_id,
90                 "ip": vnf[0].ip,
91                 "port": vnf[0].port,
92                 "username": vnf[0].username,
93                 "password": vnf[0].password
94             }
95             normal_status = status.HTTP_200_OK
96         elif request.method == 'PUT':
97             ip = ignore_case_get(request.data, "ip")
98             port = ignore_case_get(request.data, "port")
99             username = ignore_case_get(request.data, "username")
100             password = ignore_case_get(request.data, "password")
101             if ip:
102                 vnf[0].ip = ip
103             if port:
104                 vnf[0].port = port
105             if username:
106                 vnf[0].username = username
107             if password:
108                 vnf[0].password = password
109             vnf[0].save()
110             ret = {}
111             normal_status = status.HTTP_202_ACCEPTED
112         else:
113             vnf.delete()
114             ret = {}
115             normal_status = status.HTTP_204_NO_CONTENT
116     except Exception as e:
117         logger.error(e.message)
118         logger.error(traceback.format_exc())
119         return Response(data={'error': e.message}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)
120     return Response(data=ret, status=normal_status)
121
122
123 @api_view(http_method_names=['POST'])
124 def vnf_config(request, *args, **kwargs):
125     logger.info("Enter %s, data is %s", fun_name(), request.data)
126     vnf_inst_id = ignore_case_get(request.data, "vnfInstanceId")
127     try:
128         vnf = VnfRegModel.objects.filter(id=vnf_inst_id)
129         if not vnf:
130             raise Exception("Vnf(%s) does not exist." % vnf_inst_id)
131         ret = restcall.call_req(
132             base_url="http://%s:%s/" % (vnf[0].ip, vnf[0].port),
133             user=vnf[0].username,
134             passwd=vnf[0].password,
135             auth_type=restcall.rest_no_auth,
136             resource="v1/vnfconfig",
137             method="POST",
138             content=json.dumps(request.data))
139         if ret[0] != 0:
140             raise Exception("Failed to config Vnf(%s): %s" % (vnf_inst_id, ret[1]))
141     except Exception as e:
142         logger.error(e.message)
143         logger.error(traceback.format_exc())
144         return Response(data={'error': e.message}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)
145     return Response(data={}, status=status.HTTP_202_ACCEPTED)