f9936c3c9c7a1b4c04d76d7c3170acb68ddd928c
[dcaegen2/platform.git] / mod / onboardingapi / dcae_cli / util / config.py
1 # ============LICENSE_START=======================================================
2 # org.onap.dcae
3 # ================================================================================
4 # Copyright (c) 2017-2018 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 def _init_config_server_url():
54     return click.prompt("Please enter the remote server url", type=str).strip()
55
56 def _init_config_db_url():
57     click.echo("Now we need to set up access to the onboarding catalog")
58     hostname = click.prompt("Please enter the onboarding catalog hostname").strip()
59     user = click.prompt("Please enter the onboarding catalog user").strip()
60     password = click.prompt("Please enter the onboarding catalog password").strip()
61     return "postgresql://{user}:{password}@{hostname}:5432/dcae_onboarding_db".format(
62             hostname=hostname, user=user, password=password)
63
64 def _init_config():
65     '''Returns an initial dict for populating the config'''
66     # Grab the remote config and merge it in
67     new_config = {}
68
69     try:
70         server_url = _init_config_server_url()
71         new_config = util.fetch_file_from_web(server_url, "/dcae-cli/config.json")
72     except:
73         # Failing to pull seed configuration from remote server is not considered
74         # a problem. Just continue and give user the option to set it up
75         # themselves.
76         if not click.confirm("Could not download initial configuration from remote server. Attempt manually setting up?"):
77             raise ConfigurationInitError("Could not setup dcae-cli configuration")
78
79     # UPDATE: Keeping the server url even though the config was not found there.
80     new_config["server_url"] = server_url
81     new_config["user"] = _init_config_user()
82     new_config["cli_version"] = _version.__version__
83
84     if "db_url" not in new_config or not new_config["db_url"]:
85         # The seed configuration was not provided so manually set up the db
86         # connection
87         new_config["db_url"] = _init_config_db_url()
88
89     if "active_profile" not in new_config:
90         # The seed configuration was not provided which means the profiles will
91         # be the same. The profile will be hardcoded to a an empty default.
92         new_config["active_profile"] = "default"
93
94     return new_config
95
96
97 def should_force_reinit(config):
98     """Configs older than 2.0.0 should be replaced"""
99     ver = config.get("cli_version", "0.0.0")
100     return int(ver.split(".")[0]) < 2
101
102 def get_config():
103     '''Returns the configuration dictionary'''
104     return get_pref(get_config_path(), _init_config)
105
106 def get_server_url():
107     """Returns the remote server url
108
109     The remote server holds the artifacts that the dcae-cli requires like the
110     seed config json and seed profiles json, and json schemas.
111     """
112     return get_config().get("server_url")
113
114 def get_docker_logins_key():
115     """Returns the Consul key that Docker logins are stored under
116
117     Default is "docker_plugin/docker_logins" which matches up with the docker
118     plugin default.
119     """
120     return get_config().get("docker_logins_key", "docker_plugin/docker_logins")
121
122 # These functions are used to fetch the configurable path to the various json
123 # schema files used in validation.
124
125 def get_path_component_spec():
126     return get_config().get("path_component_spec",
127             "/schemas/component-specification/dcae-cli-v2/component-spec-schema.json")
128
129 def get_path_data_format():
130     return get_config().get("path_data_format",
131             "/schemas/data-format/dcae-cli-v1/data-format-schema.json")
132
133 def get_active_profile():
134     return get_config().get("active_profile", None)
135
136
137 def update_config(**kwargs):
138     '''Updates and returns the configuration dictionary'''
139     return update_pref(path=get_config_path(), init_func=get_config, **kwargs)
140
141
142 def _reinit_config(init_func):
143     new_config = init_func()
144     config_path = get_config_path()
145
146     if  pref_exists(config_path):
147         existing_config = get_config()
148         # Make sure to clobber existing values and not other way
149         existing_config.update(new_config)
150         new_config = existing_config
151
152     write_pref(new_config, config_path)
153     return new_config
154
155 def reinit_config():
156     return _reinit_config(_init_config)