d3230bcdcd7d7f99736326058ec381463430310a
[dcaegen2/platform/cli.git] / dcae-cli / dcae_cli / util / config.py
1 # ============LICENSE_START=======================================================
2 # org.onap.dcae
3 # ================================================================================
4 # Copyright (c) 2017 AT&T Intellectual Property. All rights reserved.
5 # ================================================================================
6 # Licensed under the Apache License, Version 2.0 (the "License");
7 # you may not use this file except in compliance with the License.
8 # You may obtain a copy of the License at
9 #
10 #      http://www.apache.org/licenses/LICENSE-2.0
11 #
12 # Unless required by applicable law or agreed to in writing, software
13 # distributed under the License is distributed on an "AS IS" BASIS,
14 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15 # See the License for the specific language governing permissions and
16 # limitations under the License.
17 # ============LICENSE_END=========================================================
18 #
19 # ECOMP is a trademark and service mark of AT&T Intellectual Property.
20
21 # -*- coding: utf-8 -*-
22 """
23 Provides dcae cli config utilities
24 """
25 import os, re
26
27 import click
28 import six
29
30 from dcae_cli import util
31 from dcae_cli import _version
32 from dcae_cli.util import get_app_dir, get_pref, update_pref, write_pref, pref_exists
33
34
35 class ConfigurationInitError(RuntimeError):
36     pass
37
38 def get_config_path():
39     '''Returns the absolute configuration file path'''
40     return os.path.join(get_app_dir(), 'config.json')
41
42
43 def _init_config_user():
44     while True:
45         user = click.prompt('Please enter your user id', type=str).strip()
46
47         # There should be no special characters
48         if re.match("(?:\w*)\Z", user):
49             return user
50         else:
51             click.echo("Invalid user id. Please try again.")
52
53
54 def _init_config():
55     '''Returns an initial dict for populating the config'''
56     # Grab the remote config and merge it in
57     try:
58         new_config = util.fetch_file_from_nexus("/dcae-cli/config.json")
59     except:
60         # REVIEW: Should we allow users to manually setup their config if not
61         # able to pull from remote server?
62         raise ConfigurationInitError("Could not download configuration from remote server")
63
64     new_config["user"] = _init_config_user()
65     new_config["cli_version"] = _version.__version__
66
67     if "db_url" not in new_config or not new_config["db_url"]:
68         # Really you should never get to this point because the remote config
69         # should have a postgres db url.
70         fallback = ''.join(('sqlite:///', os.path.join(get_app_dir(), 'dcae_cli.db')))
71         new_config["db_url"] = fallback
72
73     return new_config
74
75
76 def should_force_reinit(config):
77     """Configs older than 2.0.0 should be replaced"""
78     ver = config.get("cli_version", "0.0.0")
79     return int(ver.split(".")[0]) < 2
80
81 def get_config():
82     '''Returns the configuration dictionary'''
83     return get_pref(get_config_path(), _init_config)
84
85
86 # These functions are used to fetch the configurable path to the various json
87 # schema files used in validation.
88
89 def get_path_component_spec():
90     return get_config().get("path_component_spec",
91             "/schemas/component-specification/dcae-cli-v3/component-spec-schema.json")
92
93 def get_path_data_format():
94     return get_config().get("path_data_format",
95             "/schemas/data-format/dcae-cli-v1/data-format-schema.json")
96
97 def get_active_profile():
98     return get_config().get("active_profile", None)
99
100
101 def update_config(**kwargs):
102     '''Updates and returns the configuration dictionary'''
103     return update_pref(path=get_config_path(), init_func=get_config, **kwargs)
104
105
106 def _reinit_config(init_func):
107     new_config = init_func()
108     config_path = get_config_path()
109
110     if  pref_exists(config_path):
111         existing_config = get_config()
112         # Make sure to clobber existing values and not other way
113         existing_config.update(new_config)
114         new_config = existing_config
115
116     write_pref(new_config, config_path)
117     return new_config
118
119 def reinit_config():
120     return _reinit_config(_init_config)