Merge "Handle AAI Update and Delete events for PMSH"
[dcaegen2/services.git] / components / pm-subscription-handler / pmsh_service / pmsh_service_main.py
1 # ============LICENSE_START===================================================
2 #  Copyright (C) 2019-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 import sys
19 import threading
20
21 import mod.aai_client as aai
22 import mod.pmsh_logging as logger
23 from mod import db, create_app, launch_api_server
24 from mod.aai_event_handler import process_aai_events
25 from mod.config_handler import ConfigHandler
26 from mod.pmsh_utils import AppConfig, PeriodicTask
27 from mod.subscription import Subscription, AdministrativeState
28
29
30 def subscription_processor(config_handler, administrative_state, mr_pub, app,
31                            mr_aai_event_subscriber):
32     """
33     Checks for changes of administrative state in config and proceeds to process
34     the Subscription if a change has occurred
35
36     Args:
37         config_handler (ConfigHandler): Configuration Handler used to get config
38         administrative_state (str): The administrative state
39         mr_pub (_MrPub): MR publisher
40         app (db): DB application
41         mr_aai_event_subscriber (_MrSub): AAI events MR subscriber
42     """
43     app.app_context().push()
44     config = config_handler.get_config()
45     new_administrative_state = config['policy']['subscription']['administrativeState']
46     polling_period = 30.0
47
48     try:
49         if administrative_state == new_administrative_state:
50             logger.debug('Administrative State did not change in the Config')
51         else:
52             logger.debug(f'Administrative State changed from "{administrative_state}" "to '
53                          f'"{new_administrative_state}".')
54             sub, nfs = aai.get_pmsh_subscription_data(config)
55             sub.process_subscription(nfs, mr_pub)
56             aai_event_thread = PeriodicTask(10, process_aai_events, args=(mr_aai_event_subscriber,
57                                                                           sub, mr_pub, app))
58
59             if new_administrative_state == AdministrativeState.UNLOCKED.value:
60                 logger.debug('Listening to AAI-EVENT topic in MR.')
61                 aai_event_thread.start()
62             else:
63                 logger.debug('Stopping to listen to AAI-EVENT topic in MR.')
64                 aai_event_thread.cancel()
65
66     except Exception as err:
67         logger.debug(f'Error occurred during the activation/deactivation process {err}')
68
69     threading.Timer(polling_period, subscription_processor,
70                     [config_handler, new_administrative_state, mr_pub, app,
71                      mr_aai_event_subscriber]).start()
72
73
74 def main():
75     try:
76         config_handler = ConfigHandler()
77         config = config_handler.get_config()
78         app_conf = AppConfig(**config['config'])
79         app = create_app()
80         app.app_context().push()
81         db.create_all(app=app)
82         sub, nfs = aai.get_pmsh_subscription_data(config)
83         mr_pub = app_conf.get_mr_pub('policy_pm_publisher')
84         mr_sub = app_conf.get_mr_sub('policy_pm_subscriber')
85         mr_aai_event_subscriber = app_conf.get_mr_sub('aai_subscriber')
86         initial_start_delay = 5.0
87
88         administrative_state = AdministrativeState.LOCKED.value
89         subscription_in_db = Subscription.get(sub.subscriptionName)
90         if subscription_in_db is not None:
91             administrative_state = subscription_in_db.status
92
93         threading.Timer(initial_start_delay, subscription_processor,
94                         [config_handler, administrative_state, mr_pub,
95                          app, mr_aai_event_subscriber]).start()
96
97         threading.Timer(20.0, mr_sub.poll_policy_topic, [sub.subscriptionName, app]).start()
98
99         launch_api_server(app_conf)
100
101     except Exception as e:
102         logger.debug(f'Failed to Init PMSH: {e}')
103         sys.exit(e)
104
105
106 if __name__ == '__main__':
107     main()