907353a9e9e163681207f0aaec6dbdac3f322788
[vfc/nfvo/lcm.git] / lcm / ns / biz / create_subscription.py
1 # Copyright (c) 2019, 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 ast
16 import json
17 import logging
18 import requests
19 import uuid
20
21 from collections import Counter
22
23 from rest_framework import status
24
25 from lcm.ns import const
26 from lcm.pub.database.models import SubscriptionModel
27 from lcm.pub.exceptions import NSLCMException
28 from lcm.pub.utils.values import ignore_case_get
29
30 logger = logging.getLogger(__name__)
31
32
33 def is_filter_type_equal(new_filter, existing_filter):
34     return Counter(new_filter) == Counter(existing_filter)
35
36
37 class CreateSubscription:
38
39     def __init__(self, data):
40         self.data = data
41         self.filter = ignore_case_get(self.data, "filter", {})
42         self.callback_uri = ignore_case_get(self.data, "callbackUri")
43         self.authentication = ignore_case_get(self.data, "authentication", {})
44         self.notification_types = ignore_case_get(
45             self.filter, "notificationTypes", [])
46         self.operation_types = ignore_case_get(
47             self.filter, "operationTypes", [])
48         self.operation_states = ignore_case_get(
49             self.filter, "notificationStates", [])
50         self.ns_component_types = ignore_case_get(
51             self.filter, "nsComponentTypes", [])
52         self.lcm_opname_impacting_nscomponent = ignore_case_get(
53             self.filter, "lcmOpNameImpactingNsComponent", [])
54         self.lcm_opoccstatus_impacting_nscomponent = ignore_case_get(
55             self.filter, "lcmOpOccStatusImpactingNsComponent", [])
56         self.ns_filter = ignore_case_get(
57             self.filter, "nsInstanceSubscriptionFilter", {})
58
59     def check_callbackuri_connection(self):
60         logger.debug("SubscribeNotification-post::> Sending GET request "
61                      "to %s" % self.callback_uri)
62         try:
63             response = requests.get(self.callback_uri, timeout=2)
64             if response.status_code != status.HTTP_204_NO_CONTENT:
65                 raise NSLCMException("callbackUri %s returns %s status "
66                                      "code." % (self.callback_uri, response.status_code))
67         except Exception:
68             raise NSLCMException("callbackUri %s didn't return 204 status"
69                                  "code." % self.callback_uri)
70
71     def do_biz(self):
72         self.subscription_id = str(uuid.uuid4())
73         # self.check_callbackuri_connection()
74         self.check_valid_auth_info()
75         self.check_filter_types()
76         self.check_valid()
77         self.save_db()
78         subscription = SubscriptionModel.objects.get(
79             subscription_id=self.subscription_id)
80         return subscription
81
82     def check_filter_types(self):
83         logger.debug("SubscribeNotification--post::> Validating "
84                      "operationTypes  and operationStates if exists")
85         if self.operation_types and \
86                 const.LCCNNOTIFICATION not in self.notification_types:
87             raise NSLCMException("If you are setting operationTypes,"
88                                  "then notificationTypes "
89                                  "must be " + const.LCCNNOTIFICATION)
90         if self.operation_states and \
91                 const.LCCNNOTIFICATION not in self.notification_types:
92             raise NSLCMException("If you are setting operationStates,"
93                                  "then notificationTypes "
94                                  "must be " + const.LCCNNOTIFICATION)
95
96     def check_valid_auth_info(self):
97         logger.debug("SubscribeNotification--post::> Validating Auth "
98                      "details if provided")
99         if self.authentication.get("paramsBasic", {}) and \
100                 const.BASIC not in self.authentication.get("authType"):
101             raise NSLCMException('Auth type should be ' + const.BASIC)
102         if self.authentication.get("paramsOauth2ClientCredentials", {}) and \
103                 const.OAUTH2_CLIENT_CREDENTIALS not in self.authentication.get("authType"):
104             raise NSLCMException('Auth type should be ' + const.OAUTH2_CLIENT_CREDENTIALS)
105
106     def check_filter_exists(self, sub):
107         # Check the notificationTypes, operationTypes, operationStates
108         for filter_type in ["operation_types", "ns_component_types", "lcm_opname_impacting_nscomponent",
109                             "lcm_opoccstatus_impacting_nscomponent", "notification_types",
110                             "operation_states"]:
111             if not is_filter_type_equal(getattr(self, filter_type),
112                                         ast.literal_eval(getattr(sub, filter_type))):
113                 return False
114         # If all the above types are same then check ns instance filters
115         ns_filter = json.loads(sub.ns_instance_filter)
116         for ns_filter_type in ["nsdIds", "nsInstanceIds", "vnfdIds", "pnfdIds", "nsInstanceNames"]:
117             if not is_filter_type_equal(self.ns_filter.get(ns_filter_type, []),
118                                         ns_filter.get(ns_filter_type, [])):
119                 return False
120         return True
121
122     def check_valid(self):
123         logger.debug("SubscribeNotification--post::> Checking DB if callbackUri already exists")
124         subscriptions = SubscriptionModel.objects.filter(
125             callback_uri=self.callback_uri)
126         if not subscriptions.exists():
127             return True
128         for subscription in subscriptions:
129             if self.check_filter_exists(subscription):
130                 raise NSLCMException("Already Subscription exists with the same callbackUri and filter")
131         return False
132
133     def save_db(self):
134         logger.debug("SubscribeNotification--post::> Saving the subscription "
135                      "%s to the database" % self.subscription_id)
136         links = {
137             "self": {
138                 "href": const.ROOT_URI + self.subscription_id
139             }
140         }
141         SubscriptionModel.objects.create(subscription_id=self.subscription_id,
142                                          callback_uri=self.callback_uri,
143                                          auth_info=self.authentication,
144                                          notification_types=json.dumps(
145                                              self.notification_types),
146                                          operation_types=json.dumps(
147                                              self.operation_types),
148                                          operation_states=json.dumps(
149                                              self.operation_states),
150                                          ns_instance_filter=json.dumps(
151                                              self.ns_filter),
152                                          ns_component_types=json.dumps(
153                                              self.ns_component_types),
154                                          lcm_opname_impacting_nscomponent=json.dumps(
155                                              self.lcm_opname_impacting_nscomponent),
156                                          lcm_opoccstatus_impacting_nscomponent=json.dumps(
157                                              self.lcm_opoccstatus_impacting_nscomponent),
158                                          links=json.dumps(links))
159         logger.debug('Create Subscription[%s] success', self.subscription_id)