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