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