1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
|
# ============LICENSE_START===================================================
# Copyright (C) 2019-2022 Nordix Foundation.
# ============================================================================
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# SPDX-License-Identifier: Apache-2.0
# ============LICENSE_END=====================================================
import logging
import os
import pathlib
import ssl
from urllib.parse import quote
from connexion import App
from flask_sqlalchemy import SQLAlchemy
from onaplogging import monkey
from onaplogging.mdcContext import MDC
from ruamel.yaml import YAML
import uuid
from functools import wraps
from os import getenv
db = SQLAlchemy()
basedir = os.path.abspath(os.path.dirname(__file__))
_connexion_app = None
logger = logging.getLogger('onap_logger')
def mdc_handler(func):
@wraps(func)
def wrapper(*args, **kwargs):
request_id = str(uuid.uuid1())
invocation_id = str(uuid.uuid1())
MDC.put('ServiceName', getenv('HOSTNAME'))
MDC.put('RequestID', request_id)
MDC.put('InvocationID', invocation_id)
kwargs['request_id'] = request_id
kwargs['invocation_id'] = invocation_id
return func(*args, **kwargs)
return wrapper
def _get_app():
global _connexion_app
if not _connexion_app:
_connexion_app = App(__name__, specification_dir=basedir)
return _connexion_app
def launch_api_server(app_config):
connex_app = _get_app()
connex_app.add_api('api/pmsh_swagger.yml')
if app_config.enable_tls:
logger.info('Launching secure http API server')
ssl_ctx = ssl.create_default_context(ssl.Purpose.CLIENT_AUTH)
ssl_ctx.load_cert_chain(app_config.cert_path, app_config.key_path)
connex_app.run(port=os.environ.get('PMSH_API_PORT', '8443'), ssl_options=ssl_ctx,
server="tornado")
else:
logger.info('Launching unsecure http API server')
connex_app.run(port=os.environ.get('PMSH_API_PORT', '8443'), server="tornado")
def create_app():
create_logger()
connex_app = _get_app()
app = connex_app.app
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
app.config['SQLALCHEMY_RECORD_QUERIES'] = True
app.config['SQLALCHEMY_DATABASE_URI'] = get_db_connection_url()
db.init_app(app)
return app
def create_logger():
config_file_path = os.getenv('LOGGER_CONFIG')
update_logging_config(config_file_path)
monkey.patch_loggingYaml()
logging.config.yamlConfig(filepath=config_file_path,
watchDog=os.getenv('DYNAMIC_LOGGER_CONFIG', True))
old_record = logging.getLogRecordFactory()
def augment_record(*args, **kwargs):
new_record = old_record(*args, **kwargs)
new_record.mdc = MDC.result()
return new_record
logging.setLogRecordFactory(augment_record)
def update_logging_config(config_file_path):
config_yaml = YAML()
config_file = pathlib.Path(config_file_path)
data = config_yaml.load(config_file)
data['handlers']['onap_log_handler']['filename'] = \
f'{os.getenv("LOGS_PATH")}/application.log'
config_yaml.dump(data, config_file)
def get_db_connection_url():
pg_host = os.getenv('PMSH_PG_URL')
pg_user = os.getenv('PMSH_PG_USERNAME')
pg_user_pass = os.getenv('PMSH_PG_PASSWORD')
pmsh_db_name = os.getenv('PMSH_DB_NAME', 'pmsh')
pmsh_db_port = os.getenv('PMSH_PG_PORT', '5432')
db_url = f'postgresql+psycopg2://{quote(str(pg_user), safe="")}:' \
f'{quote(str(pg_user_pass), safe="")}@{pg_host}:{pmsh_db_port}/{pmsh_db_name}'
if 'None' in db_url:
raise Exception(f'Invalid DB connection URL: {db_url} .. exiting app!')
return db_url
|