Added Controller configuration
[nonrtric.git] / policy-agent / src / main / java / org / oransc / policyagent / configuration / ApplicationConfigParser.java
1 /*-
2  * ========================LICENSE_START=================================
3  * O-RAN-SC
4  * %%
5  * Copyright (C) 2019 Nordix Foundation
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.oransc.policyagent.configuration;
22
23 import com.google.gson.JsonArray;
24 import com.google.gson.JsonElement;
25 import com.google.gson.JsonObject;
26
27 import java.net.MalformedURLException;
28 import java.net.URL;
29 import java.util.ArrayList;
30 import java.util.HashMap;
31 import java.util.HashSet;
32 import java.util.Iterator;
33 import java.util.List;
34 import java.util.Map;
35 import java.util.Map.Entry;
36 import java.util.Properties;
37 import java.util.Set;
38
39 import javax.validation.constraints.NotNull;
40
41 import org.immutables.gson.Gson;
42 import org.immutables.value.Value;
43 import org.onap.dmaap.mr.test.clients.ProtocolTypeConstants;
44 import org.oransc.policyagent.exceptions.ServiceException;
45 import org.springframework.http.MediaType;
46
47 /**
48  * Parser for the Json representing of the component configuration.
49  */
50 public class ApplicationConfigParser {
51
52     private static final String CONFIG = "config";
53     private static final String CONTROLLER = "controller";
54
55     @Value.Immutable
56     @Gson.TypeAdapters
57     public interface ConfigParserResult {
58         List<RicConfig> ricConfigs();
59
60         Properties dmaapPublisherConfig();
61
62         Properties dmaapConsumerConfig();
63
64         Map<String, ControllerConfig> controllerConfigs();
65     }
66
67     public ConfigParserResult parse(JsonObject root) throws ServiceException {
68
69         Properties dmaapPublisherConfig = new Properties();
70         Properties dmaapConsumerConfig = new Properties();
71
72         JsonObject agentConfigJson = root.getAsJsonObject(CONFIG);
73         List<RicConfig> ricConfigs = parseRics(agentConfigJson);
74         Map<String, ControllerConfig> controllerConfigs = parseControllerConfigs(agentConfigJson);
75
76         JsonObject json = agentConfigJson.getAsJsonObject("streams_publishes");
77         if (json != null) {
78             dmaapPublisherConfig = parseDmaapConfig(json);
79         }
80
81         json = agentConfigJson.getAsJsonObject("streams_subscribes");
82         if (json != null) {
83             dmaapConsumerConfig = parseDmaapConfig(json);
84         }
85
86         checkConfigurationConsistency(ricConfigs, controllerConfigs);
87
88         return ImmutableConfigParserResult.builder() //
89             .dmaapConsumerConfig(dmaapConsumerConfig) //
90             .dmaapPublisherConfig(dmaapPublisherConfig) //
91             .ricConfigs(ricConfigs) //
92             .controllerConfigs(controllerConfigs) //
93             .build();
94     }
95
96     private void checkConfigurationConsistency(List<RicConfig> ricConfigs,
97         Map<String, ControllerConfig> controllerConfigs) throws ServiceException {
98         Set<String> ricUrls = new HashSet<>();
99         Set<String> ricNames = new HashSet<>();
100         for (RicConfig ric : ricConfigs) {
101             if (!ricUrls.add(ric.baseUrl())) {
102                 throw new ServiceException("Configuration error, more than one RIC URL: " + ric.baseUrl());
103             }
104             if (!ricNames.add(ric.name())) {
105                 throw new ServiceException("Configuration error, more than one RIC with name: " + ric.name());
106             }
107             if (!ric.controllerName().isEmpty() && controllerConfigs.get(ric.controllerName()) == null) {
108                 throw new ServiceException(
109                     "Configuration error, controller configuration not found: " + ric.controllerName());
110             }
111
112         }
113
114     }
115
116     private List<RicConfig> parseRics(JsonObject config) throws ServiceException {
117         List<RicConfig> result = new ArrayList<>();
118         for (JsonElement ricElem : getAsJsonArray(config, "ric")) {
119             JsonObject ricAsJson = ricElem.getAsJsonObject();
120             JsonElement controllerNameElement = ricAsJson.get(CONTROLLER);
121             ImmutableRicConfig ricConfig = ImmutableRicConfig.builder() //
122                 .name(ricAsJson.get("name").getAsString()) //
123                 .baseUrl(ricAsJson.get("baseUrl").getAsString()) //
124                 .managedElementIds(parseManagedElementIds(ricAsJson.get("managedElementIds").getAsJsonArray())) //
125                 .controllerName(controllerNameElement != null ? controllerNameElement.getAsString() : "") //
126                 .build();
127             result.add(ricConfig);
128         }
129         return result;
130     }
131
132     Map<String, ControllerConfig> parseControllerConfigs(JsonObject config) throws ServiceException {
133         if (config.get(CONTROLLER) == null) {
134             return new HashMap<>();
135         }
136         Map<String, ControllerConfig> result = new HashMap<>();
137         for (JsonElement element : getAsJsonArray(config, CONTROLLER)) {
138             JsonObject controllerAsJson = element.getAsJsonObject();
139             ImmutableControllerConfig controllerConfig = ImmutableControllerConfig.builder() //
140                 .name(controllerAsJson.get("name").getAsString()) //
141                 .baseUrl(controllerAsJson.get("baseUrl").getAsString()) //
142                 .password(controllerAsJson.get("password").getAsString()) //
143                 .userName(controllerAsJson.get("userName").getAsString()) // )
144                 .build();
145
146             if (result.put(controllerConfig.name(), controllerConfig) != null) {
147                 throw new ServiceException(
148                     "Configuration error, more than one controller with name: " + controllerConfig.name());
149             }
150         }
151         return result;
152     }
153
154     private List<String> parseManagedElementIds(JsonArray asJsonObject) {
155         Iterator<JsonElement> iterator = asJsonObject.iterator();
156         List<String> managedElementIds = new ArrayList<>();
157         while (iterator.hasNext()) {
158             managedElementIds.add(iterator.next().getAsString());
159
160         }
161         return managedElementIds;
162     }
163
164     private static JsonElement get(JsonObject obj, String memberName) throws ServiceException {
165         JsonElement elem = obj.get(memberName);
166         if (elem == null) {
167             throw new ServiceException("Could not find member: " + memberName + " in: " + obj);
168         }
169         return elem;
170     }
171
172     private JsonArray getAsJsonArray(JsonObject obj, String memberName) throws ServiceException {
173         return get(obj, memberName).getAsJsonArray();
174     }
175
176     private Properties parseDmaapConfig(JsonObject streamCfg) throws ServiceException {
177         Set<Entry<String, JsonElement>> streamConfigEntries = streamCfg.entrySet();
178         if (streamConfigEntries.size() != 1) {
179             throw new ServiceException(
180                 "Invalid configuration. Number of streams must be one, config: " + streamConfigEntries);
181         }
182         JsonObject streamConfigEntry = streamConfigEntries.iterator().next().getValue().getAsJsonObject();
183         JsonObject dmaapInfo = get(streamConfigEntry, "dmaap_info").getAsJsonObject();
184         String topicUrl = getAsString(dmaapInfo, "topic_url");
185
186         try {
187             Properties dmaapProps = new Properties();
188             URL url = new URL(topicUrl);
189             String passwd = "";
190             String userName = "";
191             if (url.getUserInfo() != null) {
192                 String[] userInfo = url.getUserInfo().split(":");
193                 userName = userInfo[0];
194                 passwd = userInfo[1];
195             }
196             String urlPath = url.getPath();
197             DmaapUrlPath path = parseDmaapUrlPath(urlPath);
198
199             dmaapProps.put("ServiceName", url.getHost() + ":" + url.getPort() + "/events");
200             dmaapProps.put("topic", path.dmaapTopicName);
201             dmaapProps.put("host", url.getHost() + ":" + url.getPort());
202             dmaapProps.put("contenttype", MediaType.APPLICATION_JSON.toString());
203             dmaapProps.put("userName", userName);
204             dmaapProps.put("password", passwd);
205             dmaapProps.put("group", path.consumerGroup);
206             dmaapProps.put("id", path.consumerId);
207             dmaapProps.put("TransportType", ProtocolTypeConstants.HTTPNOAUTH.toString());
208             dmaapProps.put("timeout", 15000);
209             dmaapProps.put("limit", 100);
210             dmaapProps.put("maxBatchSize", "10");
211             dmaapProps.put("maxAgeMs", "10000");
212             dmaapProps.put("compress", true);
213             dmaapProps.put("MessageSentThreadOccurance", "2");
214             return dmaapProps;
215         } catch (MalformedURLException e) {
216             throw new ServiceException("Could not parse the URL", e);
217         }
218
219     }
220
221     private static @NotNull String getAsString(JsonObject obj, String memberName) throws ServiceException {
222         return get(obj, memberName).getAsString();
223     }
224
225     private class DmaapUrlPath {
226         final String dmaapTopicName;
227         final String consumerGroup;
228         final String consumerId;
229
230         DmaapUrlPath(String dmaapTopicName, String consumerGroup, String consumerId) {
231             this.dmaapTopicName = dmaapTopicName;
232             this.consumerGroup = consumerGroup;
233             this.consumerId = consumerId;
234         }
235     }
236
237     private DmaapUrlPath parseDmaapUrlPath(String urlPath) throws ServiceException {
238         String[] tokens = urlPath.split("/"); // /events/A1-P/users/sdnc1
239         if (!(tokens.length == 3 ^ tokens.length == 5)) {
240             throw new ServiceException("The path has incorrect syntax: " + urlPath);
241         }
242
243         final String dmaapTopicName = tokens[2]; // /events/A1-P
244         String consumerGroup = ""; // users
245         String consumerId = ""; // sdnc1
246         if (tokens.length == 5) {
247             consumerGroup = tokens[3];
248             consumerId = tokens[4];
249         }
250         return new DmaapUrlPath(dmaapTopicName, consumerGroup, consumerId);
251     }
252 }