0a3b965798101a0b7c2b30f4ad8c01e9cf8b1dfe
[dcaegen2/services/sdk.git] / rest-services / cbs-client / src / main / java / org / onap / dcaegen2 / services / sdk / rest / services / cbs / client / model / CbsClientConfiguration.java
1 /*
2  * ============LICENSE_START====================================
3  * DCAEGEN2-SERVICES-SDK
4  * =========================================================
5  * Copyright (C) 2019-2021 Nokia. All rights reserved.
6  * =========================================================
7  * Licensed under the Apache License, Version 2.0 (the "License");
8  * you may not use this file except in compliance with the License.
9  * You may obtain a copy of the License at
10  *
11  *       http://www.apache.org/licenses/LICENSE-2.0
12  *
13  * Unless required by applicable law or agreed to in writing, software
14  * distributed under the License is distributed on an "AS IS" BASIS,
15  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16  * See the License for the specific language governing permissions and
17  * limitations under the License.
18  * ============LICENSE_END=====================================
19  */
20
21 package org.onap.dcaegen2.services.sdk.rest.services.cbs.client.model;
22
23 import org.immutables.value.Value;
24 import org.jetbrains.annotations.Nullable;
25 import org.onap.dcaegen2.services.sdk.rest.services.cbs.client.api.exceptions.CbsClientConfigurationException;
26 import org.onap.dcaegen2.services.sdk.security.ssl.ImmutableTrustStoreKeys;
27 import org.onap.dcaegen2.services.sdk.security.ssl.Passwords;
28 import org.onap.dcaegen2.services.sdk.security.ssl.SecurityKeysStore;
29 import org.onap.dcaegen2.services.sdk.security.ssl.TrustStoreKeys;
30 import org.slf4j.Logger;
31 import org.slf4j.LoggerFactory;
32
33 import java.nio.file.Files;
34 import java.nio.file.Paths;
35 import java.util.Optional;
36
37 /**
38  * Immutable object which helps with construction of cloudRequestObject for specified Client. For usage take a look in
39  * CloudConfigurationClient.class
40  *
41  * @author <a href="mailto:przemyslaw.wasala@nokia.com">Przemysław Wąsala</a> on 11/16/18
42  * @version 1.0.0 can be passed to ReactiveCloudConfigurationProvider, can be constructed out of
43  * org.onap.dcaegen2.services.sdk library.
44  * @since 1.0.0
45  */
46 @Value.Immutable(prehash = true)
47 public interface CbsClientConfiguration {
48     Logger LOGGER = LoggerFactory.getLogger(CbsClientConfiguration.class);
49
50     String TRUST_JKS = "trust.jks";
51     String TRUST_PASS = "trust.pass";
52     Integer PORT_FOR_CBS_OVER_TLS = 10443;
53
54     /**
55      * Name of environment variable containing path to the cacert.pem file.
56      */
57     String DCAE_CA_CERT_PATH = "DCAE_CA_CERTPATH";
58
59     /**
60      * Name of environment variable containing Config Binding Service network hostname.
61      */
62     String ENV_CBS_HOSTNAME = "CONFIG_BINDING_SERVICE";
63
64     /**
65      * Name of environment variable containing Config Binding Service network port.
66      */
67     String ENV_CBS_PORT = "CONFIG_BINDING_SERVICE_SERVICE_PORT";
68
69     /**
70      * Name of environment variable containing current application name.
71      */
72     String ENV_APP_NAME = "HOSTNAME";
73
74
75     /**
76      * Name of environment variable containing Consul host name.
77      *
78      * @deprecated CBS lookup in Consul service should not be needed,
79      * instead {@link #ENV_CBS_HOSTNAME} should be used directly.
80      */
81     @Deprecated
82     String ENV_CONSUL_HOST = "CONSUL_HOST";
83
84     /**
85      * Name of environment variable containing Config Binding Service <em>service name</em> as registered in Consul
86      * services API.
87      *
88      * @deprecated CBS lookup in Consul service should not be needed,
89      * instead {@link #ENV_CBS_HOSTNAME} should be used directly.
90      */
91     @Deprecated
92     String ENV_CBS_NAME = "CONFIG_BINDING_SERVICE";
93
94     @Value.Parameter
95     @Nullable
96     String hostname();
97
98     @Value.Parameter
99     @Nullable
100     Integer port();
101
102     @Value.Parameter
103     String appName();
104
105     @Value.Parameter
106     @Nullable
107     String protocol();
108
109     @Value.Default
110     default @Nullable TrustStoreKeys trustStoreKeys() {
111         return null;
112     }
113
114     @Value.Default
115     @Deprecated
116     default String consulHost() {
117         return "consul-server";
118     }
119     @Value.Default
120     @Deprecated
121     default Integer consulPort() {
122         return 8500;
123     }
124     @Value.Default
125     @Deprecated
126     default String cbsName() {
127         return "config-binding-service";
128     }
129     @Value.Default
130     default String configMapFilePath() {
131         return "/app-config/application_config.yaml";
132     }
133
134     /**
135      * Creates CbsClientConfiguration from system environment variables.
136      *
137      * @return an instance of CbsClientConfiguration
138      * @throws CbsClientConfigurationException when at least one of required parameters is missing
139      */
140     static CbsClientConfiguration fromEnvironment() {
141         String pathToCaCert = System.getenv(DCAE_CA_CERT_PATH);
142
143         ImmutableCbsClientConfiguration.Builder configBuilder = ImmutableCbsClientConfiguration.builder()
144                 .hostname(getEnv(ENV_CBS_HOSTNAME))
145                 .appName(getEnv(ENV_APP_NAME));
146         return Optional.ofNullable(pathToCaCert).filter(certPath -> !"".equals(certPath))
147                 .map(certPath -> createSslHttpConfig(configBuilder, certPath))
148                 .orElseGet(() -> createPlainHttpConfig(configBuilder));
149     }
150
151     static CbsClientConfiguration createPlainHttpConfig(ImmutableCbsClientConfiguration.Builder configBuilder) {
152         LOGGER.info("CBS client will use plain http protocol.");
153         return configBuilder
154                 .protocol("http")
155                 .port(Integer.valueOf(getEnv(ENV_CBS_PORT)))
156                 .build();
157     }
158
159     static CbsClientConfiguration createSslHttpConfig(ImmutableCbsClientConfiguration.Builder configBuilder,
160                                                       String pathToCaCert) {
161         LOGGER.info("CBS client will use http over TLS.");
162         return configBuilder
163                 .trustStoreKeys(crateSecurityKeysFromEnvironment(createPathToJksFile(pathToCaCert)))
164                 .port(PORT_FOR_CBS_OVER_TLS)
165                 .protocol("https")
166                 .build();
167     }
168
169     static TrustStoreKeys crateSecurityKeysFromEnvironment(String pathToCerts) {
170         LOGGER.info("Path to cert files: {}", pathToCerts + "/");
171         validateIfFilesExist(pathToCerts);
172         return ImmutableTrustStoreKeys.builder()
173                 .trustStore(SecurityKeysStore.fromPath(Paths.get(pathToCerts + "/" + TRUST_JKS)))
174                 .trustStorePassword(Passwords.fromPath(Paths.get(pathToCerts + "/" + TRUST_PASS)))
175                 .build();
176     }
177
178     static String createPathToJksFile(String pathToCaCertPemFile) {
179         return pathToCaCertPemFile.substring(0, pathToCaCertPemFile.lastIndexOf("/"));
180     }
181
182     static String getEnv(String envName) {
183         String envValue = System.getenv(envName);
184         validateEnv(envName, envValue);
185         return envValue;
186     }
187
188     static void validateEnv(String envName, String envValue) {
189         if (envValue == null || "".equals(envValue)) {
190             throw new CbsClientConfigurationException("Cannot read " + envName + " from environment.");
191         }
192     }
193
194     static void validateIfFilesExist(String pathToFile) {
195         boolean areFilesExist = Files.exists(Paths.get(pathToFile + "/" + TRUST_JKS)) &&
196                 Files.exists(Paths.get(pathToFile + "/" + TRUST_PASS));
197
198         if (!areFilesExist) {
199             throw new CbsClientConfigurationException("Required files do not exist in " + pathToFile + " directory.");
200         }
201     }
202 }