Refactor codes for subscription
[vfc/nfvo/lcm.git] / lcm / ns / views / sol / subscriptions_view.py
1 # Copyright (c) 2019, CMCC Technologies Co., Ltd.
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 ast
16 import json
17 import logging
18
19 from drf_yasg.utils import swagger_auto_schema
20 from lcm.ns.serializers.sol.lccn_subscription import LccnSubscriptionSerializer
21 from lcm.ns.serializers.sol.lccn_subscription import LccnSubscriptionsSerializer
22 from rest_framework import status
23 from rest_framework.response import Response
24 from rest_framework.views import APIView
25
26 from lcm.ns.biz.create_subscription import CreateSubscription
27 from lcm.ns.biz.query_subscription import QuerySubscription
28 from lcm.ns.serializers.sol.lccn_subscription_request import LccnSubscriptionRequestSerializer
29 from lcm.ns.serializers.sol.pub_serializers import ProblemDetailsSerializer
30 from lcm.pub.exceptions import NSLCMException
31 from lcm.pub.exceptions import BadRequestException
32 from .common import view_safe_call_with_log
33
34 logger = logging.getLogger(__name__)
35 VALID_FILTERS = [
36     "operationTypes",
37     "operationStates",
38     "notificationTypes",
39     "nsInstanceId",
40     "nsComponentTypes",
41     "lcmOpNameImpactingNsComponent",
42     "lcmOpOccStatusImpactingNsComponent"
43 ]
44
45
46 def get_problem_details_serializer(status_code, error_message):
47     problem_details = {
48         "status": status_code,
49         "detail": error_message
50     }
51     problem_details_serializer = ProblemDetailsSerializer(data=problem_details)
52     problem_details_serializer.is_valid()
53     return problem_details_serializer
54
55
56 class SubscriptionsView(APIView):
57
58     @swagger_auto_schema(
59         request_body=LccnSubscriptionRequestSerializer(),
60         responses={
61             status.HTTP_201_CREATED: LccnSubscriptionSerializer(),
62             status.HTTP_303_SEE_OTHER: ProblemDetailsSerializer(),
63             status.HTTP_500_INTERNAL_SERVER_ERROR: ProblemDetailsSerializer()
64         }
65     )
66     @view_safe_call_with_log(logger=logger)
67     def post(self, request):
68         logger.debug("SubscribeNotification--post::> %s" % request.data)
69
70         lccn_subscription_request_serializer = LccnSubscriptionRequestSerializer(
71             data=request.data)
72         if not lccn_subscription_request_serializer.is_valid():
73             raise BadRequestException(
74                 lccn_subscription_request_serializer.errors)
75         subscription = CreateSubscription(
76             lccn_subscription_request_serializer.data).do_biz()
77         lccn_notifications_filter = {
78             "notificationTypes": ast.literal_eval(subscription.notification_types),
79             "operationTypes": ast.literal_eval(subscription.operation_types),
80             "operationStates": ast.literal_eval(subscription.operation_states),
81             "nsInstanceSubscriptionFilter": json.loads(subscription.ns_instance_filter),
82             "nsComponentTypes": ast.literal_eval(subscription.ns_component_types),
83             "lcmOpNameImpactingNsComponent": ast.literal_eval(subscription.
84                                                               lcm_opname_impacting_nscomponent),
85             "lcmOpOccStatusImpactingNsComponent": ast.literal_eval(subscription.
86                                                                    lcm_opoccstatus_impacting_nscomponent)
87         }
88         subscription_data = {
89             "id": subscription.subscription_id,
90             "callbackUri": subscription.callback_uri,
91             "_links": json.loads(subscription.links),
92             "filter": lccn_notifications_filter
93         }
94         sub_resp_serializer = LccnSubscriptionSerializer(
95             data=subscription_data)
96         if not sub_resp_serializer.is_valid():
97             raise NSLCMException(sub_resp_serializer.errors)
98         return Response(data=sub_resp_serializer.data, status=status.HTTP_201_CREATED)
99
100     @swagger_auto_schema(
101         responses={
102             status.HTTP_200_OK: LccnSubscriptionsSerializer(),
103             status.HTTP_400_BAD_REQUEST: ProblemDetailsSerializer(),
104             status.HTTP_500_INTERNAL_SERVER_ERROR: ProblemDetailsSerializer()
105         }
106     )
107     @view_safe_call_with_log(logger=logger)
108     def get(self, request):
109         logger.debug("SubscribeNotification--get::> %s" % request.query_params)
110
111         if request.query_params and not set(request.query_params).issubset(set(VALID_FILTERS)):
112             problem_details_serializer = get_problem_details_serializer(
113                 status.HTTP_400_BAD_REQUEST, "Not a valid filter")
114             return Response(data=problem_details_serializer.data, status=status.HTTP_400_BAD_REQUEST)
115         resp_data = QuerySubscription(request.query_params).query_multi_subscriptions()
116         subscriptions_serializer = LccnSubscriptionsSerializer(data=resp_data)
117         if not subscriptions_serializer.is_valid():
118             raise NSLCMException(subscriptions_serializer.errors)
119         logger.debug("SubscribeNotification--get::> Remove default fields if exclude_default is "
120                      "specified")
121         return Response(data=subscriptions_serializer.data, status=status.HTTP_200_OK)