9466ebeb400a9e6cacd61cbfd6ed6fadf57b43b4
[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         requestSerializer = VnfInfoSerializer(data=request.data)
43         request_isValid = requestSerializer.is_valid()
44         try:
45             if not request_isValid:
46                 raise Exception(requestSerializer.errors)
47
48             requestData = requestSerializer.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             responseSerializer = ResponseSerializer(data={"vnfInstId": vnf_inst_id})
60             isValid = responseSerializer.is_valid()
61             if not isValid:
62                 raise Exception(responseSerializer.errors)
63         except Exception as e:
64             logger.error(e.message)
65             logger.error(traceback.format_exc())
66             return Response(data={'error': e.message}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)
67
68         return Response(data=responseSerializer.data, status=status.HTTP_201_CREATED)
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     requestSerializer = VnfInfoSerializer(data=request.data)
93     request_isValid = requestSerializer.is_valid()
94     vnf_inst_id = ignore_case_get(kwargs, "vnfInstId")
95     logger.info("Enter %s, method is %s, ", fun_name(), request.method)
96     logger.info("vnfInstId is %s, data is %s", vnf_inst_id, request.data)
97     try:
98         vnf = VnfRegModel.objects.filter(id=vnf_inst_id)
99         if not vnf:
100             err_msg = "Vnf(%s) does not exist." % vnf_inst_id
101             return Response(data={'error': err_msg}, status=status.HTTP_404_NOT_FOUND)
102         if request.method == 'GET':
103             resp = {
104                 "vnfInstId": vnf_inst_id,
105                 "ip": vnf[0].ip,
106                 "port": vnf[0].port,
107                 "username": vnf[0].username,
108                 "password": vnf[0].password
109             }
110             responseSerializer = VnfInfoSerializer(data=resp)
111             if not responseSerializer.is_valid():
112                 raise Exception(responseSerializer.errors)
113             ret = responseSerializer.data
114             normal_status = status.HTTP_200_OK
115         elif request.method == 'PUT':
116             if not request_isValid:
117                 raise Exception(requestSerializer.errors)
118
119             requestData = requestSerializer.data
120             ip = ignore_case_get(requestData, "ip")
121             port = ignore_case_get(requestData, "port")
122             username = ignore_case_get(requestData, "username")
123             password = ignore_case_get(requestData, "password")
124             if ip:
125                 vnf[0].ip = ip
126             if port:
127                 vnf[0].port = port
128             if username:
129                 vnf[0].username = username
130             if password:
131                 vnf[0].password = password
132             vnf[0].save()
133             ret = {}
134             normal_status = status.HTTP_202_ACCEPTED
135         else:
136             vnf.delete()
137             ret = {}
138             normal_status = status.HTTP_204_NO_CONTENT
139     except Exception as e:
140         logger.error(e.message)
141         logger.error(traceback.format_exc())
142         return Response(data={'error': e.message}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)
143     return Response(data=ret, status=normal_status)
144
145
146 @swagger_auto_schema(method='post',
147                      request_body=VnfConfigSerializer(),
148                      responses={
149                          status.HTTP_202_ACCEPTED: 'successfully',
150                          status.HTTP_500_INTERNAL_SERVER_ERROR: 'internal error'})
151 @api_view(http_method_names=['POST'])
152 def vnf_config(request, *args, **kwargs):
153     logger.info("Enter %s, data is %s", fun_name(), request.data)
154     requestSerializer = VnfConfigSerializer(data=request.data)
155     request_isValid = requestSerializer.is_valid()
156     try:
157         if not request_isValid:
158             raise Exception(requestSerializer.errors)
159
160         requestData = requestSerializer.data
161         vnf_inst_id = ignore_case_get(requestData, "vnfInstanceId")
162         vnf = VnfRegModel.objects.filter(id=vnf_inst_id)
163         if not vnf:
164             raise Exception("Vnf(%s) does not exist." % vnf_inst_id)
165         ret = restcall.call_req(
166             base_url="http://%s:%s/" % (vnf[0].ip, vnf[0].port),
167             user=vnf[0].username,
168             passwd=vnf[0].password,
169             auth_type=restcall.rest_no_auth,
170             resource="v1/vnfconfig",
171             method="POST",
172             content=json.dumps(requestData))
173         if ret[0] != 0:
174             raise Exception("Failed to config Vnf(%s): %s" % (vnf_inst_id, ret[1]))
175     except Exception as e:
176         logger.error(e.message)
177         logger.error(traceback.format_exc())
178         return Response(data={'error': e.message}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)
179     return Response(data={}, status=status.HTTP_202_ACCEPTED)