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