summaryrefslogtreecommitdiffstats
path: root/policyhandler/config.py
blob: ea101679326699f8f04a5817ba7e4b9daa0772b4 (plain)
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
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
"""read and use the config"""

# org.onap.dcae
# ================================================================================
# Copyright (c) 2017 AT&T Intellectual Property. All rights reserved.
# ================================================================================
# 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.
# ============LICENSE_END=========================================================
#
# ECOMP is a trademark and service mark of AT&T Intellectual Property.

import os
import json
import copy
import base64
import logging

from .discovery import DiscoveryClient
from .onap.crypto import Cipher

logging.basicConfig(
    filename='logs/policy_handler.log', \
    format='%(asctime)s.%(msecs)03d %(levelname)+8s ' + \
           '%(threadName)s %(name)s.%(funcName)s: %(message)s', \
    datefmt='%Y%m%d_%H%M%S', level=logging.DEBUG)

class Config(object):
    """main config of the application"""
    CONFIG_FILE_PATH = "etc/config.json"
    LOGGER_CONFIG_FILE_PATH = "etc/common_logger.config"
    UPLOAD_CONFIG_FILE_PATH = "etc_upload/config.json"
    SERVICE_NAME_POLICY_HANDLER = "policy_handler"
    FIELD_SYSTEM = "system"
    FIELD_CONFIG_PWD = "config_pwd"
    FIELD_WSERVICE_PORT = "wservice_port"
    FIELD_POLICY_ENGINE = "policy_engine"
    CRYPTED_FIELDS = ["ClientAuth", "Authorization", "config_pwd"]
    config_pwd = "donottell150&$"
    wservice_port = 25577
    _logger = logging.getLogger("policy_handler.config")
    config = None

    @staticmethod
    def merge(new_config):
        """merge the new_config into current config - override the values"""
        if not new_config:
            return

        if not Config.config:
            Config.config = new_config
            return

        new_config = copy.deepcopy(new_config)
        Config.config.update(new_config)

    @staticmethod
    def decrypt_secret_value(field_name, field_value):
        """decrypt the value of the secret field"""
        if field_name in Config.CRYPTED_FIELDS and isinstance(field_value, basestring):
            return Cipher.decrypt(Config.config_pwd, field_value)
        return field_value

    @staticmethod
    def encrypt_secret_value(field_name, field_value):
        """encrypt the value of the secret field"""
        if field_name in Config.CRYPTED_FIELDS and isinstance(field_value, basestring):
            return Cipher.encrypt(Config.config_pwd, field_value)
        return field_value

    @staticmethod
    def update_tree_leaves(tree_element, func_on_leaf):
        """traverse through json tree and apply function func_on_leaf to each leaf"""
        if not tree_element:
            return

        for field_name in tree_element:
            field_value = func_on_leaf(field_name, tree_element[field_name])
            tree_element[field_name] = field_value
            if isinstance(field_value, dict):
                Config.update_tree_leaves(field_value, func_on_leaf)

    @staticmethod
    def get_system_name():
        """find the name of the policy-handler system
        to be used as the key in consul-kv for config of policy-handler
        """
        system_name = None
        if Config.config:
            system_name = Config.config.get(Config.FIELD_SYSTEM)

        return system_name or Config.SERVICE_NAME_POLICY_HANDLER

    @staticmethod
    def discover():
        """bring and merge the config settings from the discovery service"""
        discovery_key = Config.get_system_name()
        new_config = DiscoveryClient.get_value(discovery_key)

        if not new_config or not isinstance(new_config, dict):
            Config._logger.warn("unexpected config from discovery: %s", new_config)
            return

        Config._logger.debug("loaded config from discovery(%s): %s", \
            discovery_key, json.dumps(new_config))
        Config.update_tree_leaves(new_config, Config.decrypt_secret_value)
        Config._logger.debug("config before merge from discovery: %s", json.dumps(Config.config))
        Config.merge(new_config)
        Config._logger.debug("merged config from discovery: %s", json.dumps(Config.config))

    @staticmethod
    def upload_to_discovery():
        """upload the current config settings to the discovery service"""
        if not Config.config or not isinstance(Config.config, dict):
            Config._logger.error("unexpected config: %s", Config.config)
            return

        latest_config = copy.deepcopy(Config.config)
        Config.update_tree_leaves(latest_config, Config.encrypt_secret_value)

        discovery_key = Config.get_system_name()
        latest_config = json.dumps(latest_config)
        DiscoveryClient.put_kv(discovery_key, latest_config)
        Config._logger.debug("uploaded config to discovery(%s): %s", \
            discovery_key, latest_config)

    @staticmethod
    def load_from_file(file_path=None):
        """read and store the config from config file"""
        if not file_path:
            file_path = Config.CONFIG_FILE_PATH

        loaded_config = None
        if os.access(file_path, os.R_OK):
            with open(file_path, 'r') as config_json:
                loaded_config = json.load(config_json)

        if not loaded_config:
            Config._logger.info("config not loaded from file: %s", file_path)
            return

        Config._logger.info("config loaded from file: %s", file_path)
        logging_config = loaded_config.get("logging")
        if logging_config:
            logging.config.dictConfig(logging_config)

        Config.config_pwd = loaded_config.get(Config.FIELD_CONFIG_PWD, Config.config_pwd)
        Config.wservice_port = loaded_config.get(Config.FIELD_WSERVICE_PORT, Config.wservice_port)
        Config.merge(loaded_config.get(Config.SERVICE_NAME_POLICY_HANDLER))
        return True

class PolicyEngineConfig(object):
    """main config of the application"""
    # PATH_TO_PROPERTIES = r'logs/policy_engine.properties'
    PATH_TO_PROPERTIES = r'tmp/policy_engine.properties'
    PYPDP_URL = "PYPDP_URL = {0}{1}, {2}, {3}\n"
    CLIENT_ID = "CLIENT_ID = {0}\n"
    CLIENT_KEY = "CLIENT_KEY = {0}\n"
    ENVIRONMENT = "ENVIRONMENT = {0}\n"
    _logger = logging.getLogger("policy_handler.pe_config")

    @staticmethod
    def save_to_file():
        """create the policy_engine.properties for policy-engine client"""
        file_path = PolicyEngineConfig.PATH_TO_PROPERTIES

        try:
            config = Config.config[Config.FIELD_POLICY_ENGINE]
            headers = config["headers"]
            client_parts = base64.b64decode(headers["ClientAuth"].split()[1]).split(":")
            auth_parts = base64.b64decode(headers["Authorization"].split()[1]).split(":")

            props = PolicyEngineConfig.PYPDP_URL.format(config["url"], config["path_pdp"],
                                                        auth_parts[0], auth_parts[1])
            props += PolicyEngineConfig.CLIENT_ID.format(client_parts[0])
            props += PolicyEngineConfig.CLIENT_KEY.format(base64.b64encode(client_parts[1]))
            props += PolicyEngineConfig.ENVIRONMENT.format(headers["Environment"])

            with open(file_path, 'w') as prp_file:
                prp_file.write(props)
            PolicyEngineConfig._logger.info("created %s", file_path)
        except IOError:
            PolicyEngineConfig._logger.error("failed to save to %s", file_path)
        except KeyError:
            PolicyEngineConfig._logger.error("unexpected config for %s", Config.FIELD_POLICY_ENGINE)