aboutsummaryrefslogtreecommitdiffstats
path: root/datafile-app-server/src/main/java/org/onap/dcaegen2/collectors/datafile/configuration/CloudConfigParser.java
blob: db811facf125a6810238235c889f6604564f554c (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
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
/*-
 * ============LICENSE_START=======================================================
 * Copyright (C) 2018, 2020-2022 Nokia. All rights reserved.
 * Copyright (C) 2018-2019 Nordix Foundation. 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=========================================================
 */

package org.onap.dcaegen2.collectors.datafile.configuration;

import com.google.gson.JsonElement;
import com.google.gson.JsonObject;

import java.nio.file.Path;
import java.nio.file.Paths;
import java.time.Duration;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Properties;

import javax.validation.constraints.NotNull;

import io.vavr.collection.Stream;
import org.onap.dcaegen2.collectors.datafile.exceptions.DatafileTaskException;
import org.onap.dcaegen2.services.sdk.model.streams.RawDataStream;
import org.onap.dcaegen2.services.sdk.model.streams.dmaap.MessageRouterSource;
import org.onap.dcaegen2.services.sdk.rest.services.cbs.client.api.streams.DataStreams;
import org.onap.dcaegen2.services.sdk.rest.services.cbs.client.api.streams.StreamFromGsonParsers;
import org.onap.dcaegen2.services.sdk.rest.services.dmaap.client.api.DmaapClientFactory;
import org.onap.dcaegen2.services.sdk.rest.services.dmaap.client.api.MessageRouterSubscriber;
import org.onap.dcaegen2.services.sdk.rest.services.dmaap.client.model.ImmutableMessageRouterSubscribeRequest;
import org.onap.dcaegen2.services.sdk.rest.services.dmaap.client.model.MessageRouterSubscribeRequest;
import org.onap.dcaegen2.services.sdk.rest.services.dmaap.client.model.config.ImmutableMessageRouterSubscriberConfig;
import org.onap.dcaegen2.services.sdk.rest.services.dmaap.client.model.config.MessageRouterSubscriberConfig;
import org.onap.dcaegen2.services.sdk.security.ssl.ImmutableSecurityKeys;
import org.onap.dcaegen2.services.sdk.security.ssl.ImmutableSecurityKeysStore;
import org.onap.dcaegen2.services.sdk.security.ssl.Passwords;
import org.onap.dcaegen2.services.sdk.security.ssl.SecurityKeys;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Parses the cloud configuration.
 *
 * @author <a href="mailto:przemyslaw.wasala@nokia.com">Przemysław Wąsala</a> on 9/19/18
 * @author <a href="mailto:henrik.b.andersson@est.tech">Henrik Andersson</a>
 */
public class CloudConfigParser {

    private static final String DMAAP_SECURITY_TRUST_STORE_PATH = "dmaap.security.trustStorePath";
    private static final String DMAAP_SECURITY_TRUST_STORE_PASS_PATH = "dmaap.security.trustStorePasswordPath";
    private static final String DMAAP_SECURITY_KEY_STORE_PATH = "dmaap.security.keyStorePath";
    private static final String DMAAP_SECURITY_KEY_STORE_PASS_PATH = "dmaap.security.keyStorePasswordPath";
    private static final String DMAAP_SECURITY_ENABLE_DMAAP_CERT_AUTH = "dmaap.security.enableDmaapCertAuth";
    private static final String CONFIG = "config";

    private static final String KNOWN_HOSTS_FILE_PATH_ENV_PROPERTY = "KNOWN_HOSTS_FILE_PATH";
    private static final String CBS_PROPERTY_SFTP_SECURITY_STRICT_HOST_KEY_CHECKING =
        "sftp.security.strictHostKeyChecking";

    private static final String DMAAP_CONSUMER_CONFIGURATION_CONSUMER_GROUP = "dmaap.dmaapConsumerConfiguration.consumerGroup";
    private static final String DMAAP_CONSUMER_CONFIGURATION_CONSUMER_ID = "dmaap.dmaapConsumerConfiguration.consumerId";
    private static final String DMAAP_CONSUMER_CONFIGURATION_TIMEOUT_MS = "dmaap.dmaapConsumerConfiguration.timeoutMs";
    private static final int EXPECTED_NUMBER_OF_SOURCE_TOPICS = 1;
    private static final int FIRST_SOURCE_INDEX = 0;

    private static final Logger logger = LoggerFactory.getLogger(CloudConfigParser.class);

    private final Properties systemEnvironment;

    private final JsonObject jsonObject;

    public CloudConfigParser(JsonObject jsonObject, Properties systemEnvironment) {
        this.jsonObject = jsonObject.getAsJsonObject(CONFIG);
        this.systemEnvironment = systemEnvironment;
    }

    /**
     * Get the publisher configurations.
     *
     * @return a map with change identifier as key and the connected publisher configuration as value.
     * @throws DatafileTaskException if a member of the configuration is missing.
     */
    public @NotNull Map<String, PublisherConfiguration> getDmaapPublisherConfigurations() throws DatafileTaskException {
        JsonObject producerCfgs = jsonObject.get("streams_publishes").getAsJsonObject();
        Iterator<String> changeIdentifierList = producerCfgs.keySet().iterator();
        Map<String, PublisherConfiguration> result = new HashMap<>();

        while (changeIdentifierList.hasNext()) {
            String changeIdentifier = changeIdentifierList.next();
            JsonObject producerCfg = getAsJson(producerCfgs, changeIdentifier);
            JsonObject feedConfig = get(producerCfg, "dmaap_info").getAsJsonObject();

            PublisherConfiguration cfg = ImmutablePublisherConfiguration.builder() //
                .publishUrl(getAsString(feedConfig, "publish_url")) //
                .password(getAsString(feedConfig, "password")) //
                .userName(getAsString(feedConfig, "username")) //
                .trustStorePath(getAsOptionalStringOrDefault(jsonObject, DMAAP_SECURITY_TRUST_STORE_PATH,"")) //
                .trustStorePasswordPath(getAsOptionalStringOrDefault(jsonObject, DMAAP_SECURITY_TRUST_STORE_PASS_PATH, "")) //
                .keyStorePath(getAsOptionalStringOrDefault(jsonObject, DMAAP_SECURITY_KEY_STORE_PATH,"")) //
                .keyStorePasswordPath(getAsOptionalStringOrDefault(jsonObject, DMAAP_SECURITY_KEY_STORE_PASS_PATH,"")) //
                .enableDmaapCertAuth(get(jsonObject, DMAAP_SECURITY_ENABLE_DMAAP_CERT_AUTH).getAsBoolean()) //
                .changeIdentifier(changeIdentifier) //
                .logUrl(getAsString(feedConfig, "log_url")) //
                .build();

            result.put(cfg.changeIdentifier(), cfg);
        }
        return result;
    }

    /**
     * Get the consumer configuration.
     *
     * @return the consumer configuration.
     * @throws DatafileTaskException if the configuration is invalid.
     */
    public @NotNull ConsumerConfiguration getConsumerConfiguration() throws DatafileTaskException {
        try {
            MessageRouterSubscriberConfig messageRouterSubscriberConfig = getMessageRouterSubscriberConfig();
            MessageRouterSubscribeRequest messageRouterSubscribeRequest = getMessageRouterSubscribeRequest();
            MessageRouterSubscriber messageRouterSubscriber = DmaapClientFactory.createMessageRouterSubscriber(messageRouterSubscriberConfig);
            return new ConsumerConfiguration(messageRouterSubscriberConfig, messageRouterSubscriber, messageRouterSubscribeRequest);
        } catch (Exception e) {
            throw new DatafileTaskException("Could not parse message router consumer configuration", e);
        }
    }

    private MessageRouterSubscriberConfig getMessageRouterSubscriberConfig() throws DatafileTaskException {
        return ImmutableMessageRouterSubscriberConfig.builder()
            .securityKeys(isDmaapCertAuthEnabled(jsonObject) ? createSecurityKeys() : null)
            .build();
    }

    private SecurityKeys createSecurityKeys() throws DatafileTaskException {
        return ImmutableSecurityKeys.builder()
            .keyStore(ImmutableSecurityKeysStore.of(getAsPath(jsonObject, DMAAP_SECURITY_KEY_STORE_PATH)))
            .keyStorePassword(Passwords.fromPath(getAsPath(jsonObject, DMAAP_SECURITY_KEY_STORE_PASS_PATH)))
            .trustStore(ImmutableSecurityKeysStore.of(getAsPath(jsonObject, DMAAP_SECURITY_TRUST_STORE_PATH)))
            .trustStorePassword(Passwords.fromPath(getAsPath(jsonObject, DMAAP_SECURITY_TRUST_STORE_PASS_PATH)))
            .build();
    }

    private boolean isDmaapCertAuthEnabled(JsonObject config) {
        return config.get(DMAAP_SECURITY_ENABLE_DMAAP_CERT_AUTH).getAsBoolean();
    }

    private MessageRouterSubscribeRequest getMessageRouterSubscribeRequest() throws DatafileTaskException {
        Stream<RawDataStream<JsonObject>> sources = DataStreams.namedSources(jsonObject);
        if (sources.size() != EXPECTED_NUMBER_OF_SOURCE_TOPICS) {
            throw new DatafileTaskException("Invalid configuration, number of topic must be one, config: " + sources);
        }
        RawDataStream<JsonObject> source = sources.get(FIRST_SOURCE_INDEX);
        MessageRouterSource parsedSource = StreamFromGsonParsers.messageRouterSourceParser().unsafeParse(source);

        return ImmutableMessageRouterSubscribeRequest.builder()
            .consumerGroup(getAsString(jsonObject, DMAAP_CONSUMER_CONFIGURATION_CONSUMER_GROUP))
            .sourceDefinition(parsedSource)
            .consumerId(getAsString(jsonObject, DMAAP_CONSUMER_CONFIGURATION_CONSUMER_ID))
            .timeout(Duration.ofMillis(get(jsonObject, DMAAP_CONSUMER_CONFIGURATION_TIMEOUT_MS).getAsLong()))
            .build();
    }

    /**
     * Get the sFTP configuration.
     *
     * @return the sFTP configuration.
     * @throws DatafileTaskException if a member of the configuration is missing.
     */
    public @NotNull SftpConfig getSftpConfig() throws DatafileTaskException {
        String filePath = determineKnownHostsFilePath();
        return new ImmutableSftpConfig.Builder() //
            .strictHostKeyChecking(getAsBoolean(jsonObject, CBS_PROPERTY_SFTP_SECURITY_STRICT_HOST_KEY_CHECKING))
            .knownHostsFilePath(filePath).build();
    }

    /**
     * Get the security configuration for communication with the xNF.
     *
     * @return the xNF communication security configuration.
     * @throws DatafileTaskException if a member of the configuration is missing.
     */
    public @NotNull CertificateConfig getCertificateConfig() throws DatafileTaskException {
        boolean enableCertAuth = getAsBooleanOrDefault(jsonObject, "dmaap.certificateConfig.enableCertAuth",
            Boolean.TRUE);

        String keyCert = "";
        String keyPasswordPath = "";
        String trustedCa = "";
        String trustedCaPasswordPath = "";
        boolean httpsHostnameVerify = true;

        if (enableCertAuth) {
            logger.debug("TlS enabled, attempt to read certificates property");
            try {
                keyCert = getAsString(jsonObject, "dmaap.certificateConfig.keyCert");
                keyPasswordPath = getAsString(jsonObject, "dmaap.certificateConfig.keyPasswordPath");
                trustedCa = getAsString(jsonObject, "dmaap.certificateConfig.trustedCa");
                trustedCaPasswordPath = getAsString(jsonObject, "dmaap.certificateConfig.trustedCaPasswordPath");
                httpsHostnameVerify = getAsBooleanOrDefault(jsonObject, "dmaap.certificateConfig.httpsHostnameVerify",
                    Boolean.TRUE);
            } catch (DatafileTaskException e) {
                throw new DatafileTaskException(
                    "Wrong configuration. External certificate enabled but configs are missing: "
                        + e.getMessage());
            }
        }

        return new ImmutableCertificateConfig.Builder() //
            .keyCert(keyCert)
            .keyPasswordPath(keyPasswordPath)
            .trustedCa(trustedCa)
            .trustedCaPasswordPath(trustedCaPasswordPath) //
            .httpsHostnameVerify(httpsHostnameVerify)
            .enableCertAuth(enableCertAuth)
            .build();
    }

    private String determineKnownHostsFilePath() {
        String filePath = "";
        if (systemEnvironment != null) {
            filePath =
                systemEnvironment.getProperty(KNOWN_HOSTS_FILE_PATH_ENV_PROPERTY, "/home/datafile/.ssh/known_hosts");
        }
        return filePath;
    }

    private static @NotNull JsonElement get(JsonObject obj, String memberName) throws DatafileTaskException {
        JsonElement elem = obj.get(memberName);
        if (elem == null) {
            throw new DatafileTaskException("Could not find member: " + memberName + " in: " + obj);
        }
        return elem;
    }

    private static @NotNull String getAsString(JsonObject obj, String memberName) throws DatafileTaskException {
        return get(obj, memberName).getAsString();
    }

    private static String getAsOptionalStringOrDefault(JsonObject obj, String memberName, String def) {
        try {
            return get(obj, memberName).getAsString();
        } catch (DatafileTaskException e) {
            return def;
        }
    }


    private static @NotNull Boolean getAsBoolean(JsonObject obj, String memberName) throws DatafileTaskException {
        return get(obj, memberName).getAsBoolean();
    }

    private static @NotNull Boolean getAsBooleanOrDefault(JsonObject obj, String memberName, Boolean def) {
        try {
            return get(obj, memberName).getAsBoolean();
        } catch (DatafileTaskException e) {
            return def;
        }
    }

    private static @NotNull JsonObject getAsJson(JsonObject obj, String memberName) throws DatafileTaskException {
        return get(obj, memberName).getAsJsonObject();
    }

    private static @NotNull Path getAsPath(JsonObject obj, String dmaapSecurityKeyStorePath) throws DatafileTaskException {
        return Paths.get(getAsString(obj, dmaapSecurityKeyStorePath));
    }

}