Fix create subsctiption bugs
[vfc/gvnfm/vnflcm.git] / lcm / lcm / nf / biz / create_subscription.py
1 # Copyright (C) 2018 Verizon. All Rights Reserved
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.nf import const
26 from lcm.pub.database.models import SubscriptionModel
27 from lcm.pub.exceptions import NFLCMException
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     def __init__(self, data):
39         self.data = data
40         self.filter = ignore_case_get(self.data, "filter", {})
41         self.callback_uri = ignore_case_get(self.data, "callbackUri")
42         self.authentication = ignore_case_get(self.data, "authentication", {})
43         self.notification_types = ignore_case_get(self.filter, "notificationTypes", [])
44         self.operation_types = ignore_case_get(self.filter, "operationTypes", [])
45         self.operation_states = ignore_case_get(self.filter, "operationStates", [])
46         self.vnf_filter = \
47             ignore_case_get(self.filter, "vnfInstanceSubscriptionFilter", {})
48
49     def check_callbackuri_connection(self):
50         logger.debug("SubscribeNotification-post::> Sending GET request "
51                      "to %s" % self.callback_uri)
52         try:
53             response = requests.get(self.callback_uri, timeout=2)
54             if response.status_code != status.HTTP_204_NO_CONTENT:
55                 raise NFLCMException("callbackUri %s returns %s status "
56                                      "code." % (self.callback_uri, response.status_code))
57         except Exception:
58             raise NFLCMException("callbackUri %s didn't return 204 status"
59                                  "code." % self.callback_uri)
60
61     def do_biz(self):
62         self.subscription_id = str(uuid.uuid4())
63         # self.check_callbackuri_connection()
64         self.check_valid_auth_info()
65         self.check_filter_types()
66         self.check_valid()
67         self.save_db()
68         subscription = SubscriptionModel.objects.get(subscription_id=self.subscription_id)
69         return subscription
70
71     def check_filter_types(self):
72         logger.debug("SubscribeNotification--post::> Validating "
73                      "operationTypes  and operationStates if exists")
74         if self.operation_types and \
75                 const.LCCNNOTIFICATION not in self.notification_types:
76             raise NFLCMException("If you are setting operationTypes,"
77                                  "then notificationTypes "
78                                  "must be " + const.LCCNNOTIFICATION)
79         if self.operation_states and \
80                 const.LCCNNOTIFICATION not in self.notification_types:
81             raise NFLCMException("If you are setting operationStates,"
82                                  "then notificationTypes "
83                                  "must be " + const.LCCNNOTIFICATION)
84
85     def check_valid_auth_info(self):
86         logger.debug("SubscribeNotification--post::> Validating Auth "
87                      "details if provided")
88         if self.authentication.get("paramsBasic", {}) and \
89                 const.BASIC not in self.authentication.get("authType"):
90             raise NFLCMException('Auth type should be ' + const.BASIC)
91         if self.authentication.get("paramsOauth2ClientCredentials", {}) and \
92                 const.OAUTH2_CLIENT_CREDENTIALS not in self.authentication.get("authType"):
93             raise NFLCMException('Auth type should be ' + const.OAUTH2_CLIENT_CREDENTIALS)
94
95     def check_filter_exists(self, sub):
96         # Check the notificationTypes, operationTypes, operationStates
97         for filter_type in ["operation_types",
98                             "notification_types", "operation_states"]:
99             if not is_filter_type_equal(getattr(self, filter_type),
100                                         ast.literal_eval(getattr(sub, filter_type))):
101                 return False
102         # If all the above types are same then check vnf instance filters
103         nf_filter = json.loads(sub.vnf_instance_filter)
104         for vnf_filter_type in ["vnfdIds", "vnfInstanceIds",
105                                 "vnfInstanceNames"]:
106             if not is_filter_type_equal(self.vnf_filter.get(vnf_filter_type, []),
107                                         nf_filter.get(vnf_filter_type, [])):
108                 return False
109         return True
110
111     def check_valid(self):
112         logger.debug("SubscribeNotification--post::> Checking DB if "
113                      "callbackUri already exists")
114         subscriptions = SubscriptionModel.objects.filter(callback_uri=self.callback_uri)
115         if not subscriptions.exists():
116             return True
117         for subscription in subscriptions:
118             if self.check_filter_exists(subscription):
119                 raise NFLCMException("Already Subscription exists with the "
120                                      "same callbackUri and filter")
121         return False
122
123     def save_db(self):
124         logger.debug("SubscribeNotification--post::> Saving the subscription "
125                      "%s to the database" % self.subscription_id)
126         links = {
127             "self": {
128                 "href": const.ROOT_URI + self.subscription_id
129             }
130         }
131         SubscriptionModel.objects.create(subscription_id=self.subscription_id,
132                                          callback_uri=self.callback_uri,
133                                          auth_info=self.authentication,
134                                          notification_types=json.dumps(self.notification_types),
135                                          operation_types=json.dumps(self.operation_types),
136                                          operation_states=json.dumps(self.operation_states),
137                                          vnf_instance_filter=json.dumps(self.vnf_filter),
138                                          links=json.dumps(links))
139         logger.debug('Create Subscription[%s] success', self.subscription_id)