[PMSH] Improve Failure Handling
[dcaegen2/services.git] / components / pm-subscription-handler / pmsh_service / mod / policy_response_handler.py
1 # ============LICENSE_START===================================================
2 #  Copyright (C) 2020 Nordix Foundation.
3 # ============================================================================
4 # Licensed under the Apache License, Version 2.0 (the "License");
5 # you may not use this file except in compliance with the License.
6 # You may obtain a copy of the License at
7 #
8 #      http://www.apache.org/licenses/LICENSE-2.0
9 #
10 # Unless required by applicable law or agreed to in writing, software
11 # distributed under the License is distributed on an "AS IS" BASIS,
12 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 # See the License for the specific language governing permissions and
14 # limitations under the License.
15 #
16 # SPDX-License-Identifier: Apache-2.0
17 # ============LICENSE_END=====================================================
18
19 import json
20
21 from mod import logger
22 from mod.network_function import NetworkFunction
23 from mod.subscription import Subscription, AdministrativeState, subscription_nf_states
24
25 policy_response_handle_functions = {
26     AdministrativeState.LOCKED.value: {
27         'success': NetworkFunction.delete,
28         'failed': Subscription.update_sub_nf_status
29     },
30     AdministrativeState.UNLOCKED.value: {
31         'success': Subscription.update_sub_nf_status,
32         'failed': Subscription.update_sub_nf_status
33     }
34 }
35
36
37 class PolicyResponseHandler:
38     def __init__(self, mr_sub, app_conf, app):
39         self.mr_sub = mr_sub
40         self.app_conf = app_conf
41         self.app = app
42
43     def poll_policy_topic(self):
44         """
45         This method polls MR for response from policy. It checks whether the message is for the
46         relevant subscription and then handles the response
47         """
48         self.app.app_context().push()
49         administrative_state = self.app_conf.subscription.administrativeState
50         logger.info('Polling MR started for XNF activation/deactivation policy response events.')
51         try:
52             response_data = self.mr_sub.get_from_topic('policy_response_consumer')
53             for data in response_data:
54                 data = json.loads(data)
55                 if data['status']['subscriptionName'] \
56                         == self.app_conf.subscription.subscriptionName:
57                     nf_name = data['status']['nfName']
58                     response_message = data['status']['message']
59                     self._handle_response(self.app_conf.subscription.subscriptionName,
60                                           administrative_state, nf_name, response_message)
61         except Exception as err:
62             logger.error(f'Error trying to poll policy response topic on MR: {err}')
63
64     @staticmethod
65     def _handle_response(subscription_name, administrative_state, nf_name, response_message):
66         """
67         Handles the response from Policy, updating the DB
68
69         Args:
70             subscription_name (str): The subscription name
71             administrative_state (str): The administrative state of the subscription
72             nf_name (str): The network function name
73             response_message (str): The message in the response regarding the state (success|failed)
74         """
75         logger.info(f'Response from MR: Sub: {subscription_name} for '
76                     f'NF: {nf_name} received, updating the DB')
77         try:
78             sub_nf_status = subscription_nf_states[administrative_state][response_message].value
79             policy_response_handle_functions[administrative_state][response_message](
80                 subscription_name=subscription_name, status=sub_nf_status, nf_name=nf_name)
81         except Exception as err:
82             logger.error(f'Error changing nf_sub status in the DB: {err}')
83             raise