Refactor and bug fixes
[dcaegen2/services.git] / components / pm-subscription-handler / pmsh_service / mod / __init__.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 logging as logging
19 import os
20 import pathlib
21 from urllib.parse import quote
22
23 from connexion import App
24 from flask_sqlalchemy import SQLAlchemy
25 from onaplogging import monkey
26 from onaplogging.mdcContext import MDC
27 from ruamel.yaml import YAML
28
29 db = SQLAlchemy()
30 basedir = os.path.abspath(os.path.dirname(__file__))
31 _connexion_app = None
32 logger = logging.getLogger('onap_logger')
33
34
35 def _get_app():
36     global _connexion_app
37     if not _connexion_app:
38         _connexion_app = App(__name__, specification_dir=basedir)
39     return _connexion_app
40
41
42 def launch_api_server(app_config):
43     connex_app = _get_app()
44     connex_app.add_api('api/pmsh_swagger.yml')
45     if app_config.enable_tls:
46         logger.info('Launching secure http API server')
47         connex_app.run(port=os.environ.get('PMSH_API_PORT', '8443'),
48                        ssl_context=app_config.cert_params)
49     else:
50         logger.info('Launching unsecure http API server')
51         connex_app.run(port=os.environ.get('PMSH_API_PORT', '8443'))
52
53
54 def create_app():
55     create_logger()
56     connex_app = _get_app()
57     app = connex_app.app
58     app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
59     app.config['SQLALCHEMY_RECORD_QUERIES'] = True
60     app.config['SQLALCHEMY_DATABASE_URI'] = get_db_connection_url()
61     db.init_app(app)
62     return app
63
64
65 def create_logger():
66     config_file_path = os.getenv('LOGGER_CONFIG')
67     update_logging_config(config_file_path)
68     monkey.patch_loggingYaml()
69     logging.config.yamlConfig(filepath=config_file_path,
70                               watchDog=os.getenv('DYNAMIC_LOGGER_CONFIG', True))
71     old_record = logging.getLogRecordFactory()
72
73     def augment_record(*args, **kwargs):
74         new_record = old_record(*args, **kwargs)
75         new_record.mdc = MDC.result()
76         return new_record
77
78     logging.setLogRecordFactory(augment_record)
79
80
81 def update_logging_config(config_file_path):
82     config_yaml = YAML()
83     config_file = pathlib.Path(config_file_path)
84     data = config_yaml.load(config_file)
85     data['handlers']['onap_log_handler']['filename'] = \
86         f'{os.getenv("LOGS_PATH")}/application.log'
87     config_yaml.dump(data, config_file)
88
89
90 def get_db_connection_url():
91     pg_host = os.getenv('PMSH_PG_URL')
92     pg_user = os.getenv('PMSH_PG_USERNAME')
93     pg_user_pass = os.getenv('PMSH_PG_PASSWORD')
94     pmsh_db_name = os.getenv('PMSH_DB_NAME', 'pmsh')
95     pmsh_db_port = os.getenv('PMSH_PG_PORT', '5432')
96     db_url = f'postgres+psycopg2://{quote(str(pg_user), safe="")}:' \
97         f'{quote(str(pg_user_pass), safe="")}@{pg_host}:{pmsh_db_port}/{pmsh_db_name}'
98     if 'None' in db_url:
99         raise Exception(f'Invalid DB connection URL: {db_url} .. exiting app!')
100     return db_url