Notification stuffs.
[vfc/gvnfm/vnflcm.git] / lcm / lcm / pub / utils / notificationsutil.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 json
16 import logging
17 import requests
18
19 from rest_framework import status
20 from requests.auth import HTTPBasicAuth
21
22 from lcm.nf import const
23 from lcm.pub.database.models import SubscriptionModel
24
25 logger = logging.getLogger(__name__)
26
27
28 class NotificationsUtil(object):
29     def __init__(self):
30         pass
31
32     def send_notification(self, notification):
33         logger.info("Send Notifications to the callbackUri")
34         filters = {
35             "vnfInstanceId": "vnf_instance_filter",
36             "operationState": "operation_states",
37             "operation": "operation_types"
38         }
39         subscriptions_filter = {v + "__contains": notification[k] for k, v in filters.iteritems()}
40
41         subscriptions = SubscriptionModel.objects.filter(**subscriptions_filter)
42         if not subscriptions.exists():
43             logger.info("No subscriptions created for the filters %s" % notification)
44             return
45         logger.info("Start sending notifications")
46         for subscription in subscriptions:
47             # set subscription id
48             notification["subscriptionId"] = subscription.subscription_id
49             notification['_links']['subscription'] = {'href': '/api/vnflcm/v1/subscriptions/%s' % subscription.subscription_id}
50             callbackUri = subscription.callback_uri
51             auth_info = json.loads(subscription.auth_info)
52             if auth_info["authType"] == const.OAUTH2_CLIENT_CREDENTIALS:
53                 pass
54             self.post_notification(callbackUri, auth_info, notification)
55
56     def post_notification(self, callbackUri, auth_info, notification):
57         params = auth_info.get("paramsBasic", {})
58         username = params.get("userName")
59         password = params.get("password")
60         logger.info("Sending notification to %s", callbackUri)
61         resp = requests.post(callbackUri, data=notification, auth=HTTPBasicAuth(username, password))
62         if resp.status_code != status.HTTP_204_NO_CONTENT:
63             raise Exception("Unable to send the notification to %s, due to %s" % (callbackUri, resp.text))
64         return