DMAAP Listener support for SDNR OOF PCI
[ccsdk/sli/northbound.git] / dmaap-listener / src / main / java / org / onap / ccsdk / sli / northbound / dmaapclient / ANRChangesFromPolicyToSDNRDmaapConsumer.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * openECOMP : SDN-C
4  * ================================================================================
5  * Copyright (C) 2017 AT&T Intellectual Property. All rights
6  *             reserved.
7  * ================================================================================
8  * Licensed under the Apache License, Version 2.0 (the "License");
9  * you may not use this file except in compliance with the License.
10  * You may obtain a copy of the License at
11  *
12  *      http://www.apache.org/licenses/LICENSE-2.0
13  *
14  * Unless required by applicable law or agreed to in writing, software
15  * distributed under the License is distributed on an "AS IS" BASIS,
16  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17  * See the License for the specific language governing permissions and
18  * limitations under the License.
19  * ============LICENSE_END=========================================================
20  */
21
22 package org.onap.ccsdk.sli.northbound.dmaapclient;
23
24 import java.io.BufferedReader;
25 import java.io.File;
26 import java.io.FileReader;
27 import java.io.IOException;
28 import java.io.StringWriter;
29 import java.io.Writer;
30 import java.time.Instant;
31 import java.util.HashMap;
32 import java.util.Map;
33 import java.util.Properties;
34 import org.apache.velocity.VelocityContext;
35 import org.apache.velocity.app.VelocityEngine;
36 import org.json.JSONArray;
37 import org.json.JSONObject;
38 import org.slf4j.Logger;
39 import org.slf4j.LoggerFactory;
40 import com.fasterxml.jackson.databind.JsonNode;
41 import com.fasterxml.jackson.databind.ObjectMapper;
42
43 public class ANRChangesFromPolicyToSDNRDmaapConsumer extends SdncDmaapConsumerImpl {
44
45     private static final Logger LOG = LoggerFactory.getLogger(ANRChangesFromPolicyToSDNRDmaapConsumer.class);
46     private static final String SDNC_ENDPOINT = "SDNC.endpoint";
47     private static final String TEMPLATE = "SDNC.template";
48     private static final String DMAAPLISTENERROOT = "DMAAPLISTENERROOT";
49
50     private static final String PARAMETER_NAME = "parameter-name";
51     private static final String STRING_VALUE = "string-value";
52     private static final String GENERIC_NEIGHBOR_CONFIGURATION_INPUT = "generic-neighbor-configuration-input.";
53     private static final String GENERIC_NEIGHBOR_CONFIGURATION_INPUT_NEIGHBOR_LIST_IN_USE = GENERIC_NEIGHBOR_CONFIGURATION_INPUT.concat("neighbor-list-in-use");
54     private static final String EVENT_HEADER = "event-header";
55         private static final String ACTION = "Action";
56         private static final String PAYLOAD = "Payload";
57         private static final String CONFIGURATIONS = "Configurations";
58         private static final String MODIFY_CONFIG_ANR = "ModifyConfigANR";
59         private static final String MAP_FILE_NAME = "anr-changes-from-policy-to-sdnr";
60         private static final String DATA = "data";
61         private static final String FAP_SERVICE = "FAPService";
62         private static final String SLI_PARAMETERS = "sli_parameters";
63         private static final String RPC_NAME = "rpc-name";
64         private static final String BODY = "body";
65         private static final String INPUT = "input";
66
67     private String rootDir;
68
69     protected VelocityEngine velocityEngine;
70
71     public ANRChangesFromPolicyToSDNRDmaapConsumer() {
72         velocityEngine = new VelocityEngine();
73         Properties props = new Properties();
74         rootDir = System.getenv(DMAAPLISTENERROOT);
75
76         if ((rootDir == null) || (rootDir.length() == 0)) {
77             rootDir = "/opt/app/dmaap-listener/lib/";
78         }
79         else {
80             rootDir = rootDir + "/lib/";
81         }
82
83         props.put("file.resource.loader.path", rootDir);
84         velocityEngine.init(props);
85     }
86
87     /*
88      * for testing purposes
89      */
90     ANRChangesFromPolicyToSDNRDmaapConsumer(Properties props) {
91         velocityEngine = new VelocityEngine();
92         velocityEngine.init(props);
93     }
94
95     protected String publish(String templatePath, String jsonString, JsonNode dataNode) throws IOException, InvalidMessageException
96     {
97         if (templatePath.contains("anr-pci-changes-from-policy-to-sdnr")){
98             return publishANRChangesFromPolicyToSDNR(templatePath, dataNode);
99         } else {
100             return publishFullMessage(templatePath, jsonString);
101         }
102     }
103
104     private String publishFullMessage(String templatePath, String jsonString) throws IOException
105     {
106         JSONObject jsonObj = new JSONObject(jsonString);
107         VelocityContext context = new VelocityContext();
108         for(Object key : jsonObj.keySet())
109         {
110             context.put((String)key, jsonObj.get((String)key));
111         }
112
113         String id = jsonObj.getJSONObject(EVENT_HEADER).get("id").toString();
114         context.put("req_id", id);
115
116         context.put("curr_time", Instant.now());
117
118         ObjectMapper oMapper = new ObjectMapper();
119
120         String rpcMsgbody = oMapper.writeValueAsString(jsonString);
121         context.put("full_message", rpcMsgbody);
122
123         Writer writer = new StringWriter();
124         velocityEngine.mergeTemplate(templatePath, "UTF-8", context, writer);
125         writer.flush();
126
127         return writer.toString();
128     }
129
130     private String publishANRChangesFromPolicyToSDNR(String templatePath, JsonNode dataNode) throws IOException, InvalidMessageException
131     {
132         VelocityContext context = new VelocityContext();
133                 
134                 String RPC_NAME_KEY_IN_VT = "rpc_name";
135         String RPC_NAME_VALUE_IN_VT = "generic-neighbor-configuration";
136         
137         String CELL_CONFIG = "CellConfig";
138         String ALIAS_LABEL = "alias";
139         String LTE = "LTE";
140         String RAN = "RAN";
141         String LTE_CELL = "LTECell";
142         String NEIGHBOR_LIST_IN_USE = "NeighborListInUse";
143         
144         JSONObject numberOfEntries = new JSONObject();
145         JSONObject alias = new JSONObject();
146         JSONArray sliParametersArray = new JSONArray();
147         
148         String aliasValue =  dataNode.get(DATA).get(FAP_SERVICE).get(ALIAS_LABEL).textValue();
149         
150         JsonNode nbrListInUse = dataNode.get(DATA).get(FAP_SERVICE).get(CELL_CONFIG).get(LTE).get(RAN).get(NEIGHBOR_LIST_IN_USE).get(LTE_CELL);
151         
152         int entryCount = 0;
153         
154         if(nbrListInUse.isArray()) {
155                 for(JsonNode lteCell:nbrListInUse) {
156                         sliParametersArray.put(new JSONObject().put(PARAMETER_NAME, GENERIC_NEIGHBOR_CONFIGURATION_INPUT_NEIGHBOR_LIST_IN_USE+"["+entryCount+"]."+"plmnid")
157                                 .put(STRING_VALUE, lteCell.get("PLMNID")));
158                         sliParametersArray.put(new JSONObject().put(PARAMETER_NAME, GENERIC_NEIGHBOR_CONFIGURATION_INPUT_NEIGHBOR_LIST_IN_USE+"["+entryCount+"]."+"cid")
159                                 .put(STRING_VALUE, lteCell.get("CID")));
160                         sliParametersArray.put(new JSONObject().put(PARAMETER_NAME, GENERIC_NEIGHBOR_CONFIGURATION_INPUT_NEIGHBOR_LIST_IN_USE+"["+entryCount+"]."+"phy-cell-id")
161                                 .put(STRING_VALUE, lteCell.get("PhyCellID")));
162                         sliParametersArray.put(new JSONObject().put(PARAMETER_NAME, GENERIC_NEIGHBOR_CONFIGURATION_INPUT_NEIGHBOR_LIST_IN_USE+"["+entryCount+"]."+"pnf-name")
163                                 .put(STRING_VALUE, lteCell.get("PNFName")));
164                         sliParametersArray.put(new JSONObject().put(PARAMETER_NAME, GENERIC_NEIGHBOR_CONFIGURATION_INPUT_NEIGHBOR_LIST_IN_USE+"["+entryCount+"]."+"blacklisted")
165                                 .put(STRING_VALUE, lteCell.get("Blacklisted")));
166                         
167                         entryCount++;
168                 }
169                 
170                 alias.put(PARAMETER_NAME, GENERIC_NEIGHBOR_CONFIGURATION_INPUT+ALIAS_LABEL);
171             alias.put(STRING_VALUE, aliasValue);
172             
173             numberOfEntries.put(PARAMETER_NAME, GENERIC_NEIGHBOR_CONFIGURATION_INPUT+"number-of-neighbor-cell-entries");
174             numberOfEntries.put(STRING_VALUE, entryCount);
175             
176             sliParametersArray.put(alias);
177             sliParametersArray.put(numberOfEntries);
178             
179             context.put(SLI_PARAMETERS, sliParametersArray);
180             
181             context.put(RPC_NAME_KEY_IN_VT, RPC_NAME_VALUE_IN_VT);
182
183             Writer writer = new StringWriter();
184             velocityEngine.mergeTemplate(templatePath, "UTF-8", context, writer);
185             writer.flush();
186
187             return writer.toString();
188                 
189         }else {
190                 throw new InvalidMessageException("nbrListInUse is not of Type Array. Could not read neighbor list elements");
191         }
192         
193     }
194
195     @Override
196     public void processMsg(String msg) throws InvalidMessageException {
197
198         if (msg == null) {
199             throw new InvalidMessageException("Null message");
200         }
201
202         ObjectMapper oMapper = new ObjectMapper();
203         JsonNode anrChangesRootNode;
204         try {
205                 anrChangesRootNode = oMapper.readTree(msg);
206         } catch (Exception e) {
207             throw new InvalidMessageException("Cannot parse json object", e);
208         }
209
210         JsonNode rpcname = anrChangesRootNode.get(RPC_NAME);
211         if(rpcname == null) {
212                  LOG.info("Missing rpc-name node.");
213                  return;
214         }
215         
216         if(!MODIFY_CONFIG_ANR.toLowerCase().equals(rpcname.textValue())) {
217             LOG.info("Unknown rpc name {}", rpcname);
218             return;
219         }
220         
221         JsonNode body = anrChangesRootNode.get(BODY);
222         if(body == null) {
223                  LOG.info("Missing body node.");
224                  return;
225         }
226         
227         JsonNode input = body.get(INPUT);
228         if(input == null) {
229                  LOG.info("Missing input node.");
230                  return;
231         }
232         
233         JsonNode action = input.get(ACTION);
234         if(action == null) {
235                  LOG.info("Missing action node.");
236                  return;
237         }
238         
239         if(!MODIFY_CONFIG_ANR.equals(action.textValue())) {
240             LOG.info("Unknown Action {}", action);
241             return;
242         }
243         
244         JsonNode payload = input.get(PAYLOAD);
245         if(payload == null) {
246             LOG.info("Missing payload node.");
247             return;
248         }
249
250         String payloadText = payload.asText();
251         
252         if(!payloadText.contains(CONFIGURATIONS)) {
253          LOG.info("Missing configurations node.");
254          return;
255        }
256         
257        JsonNode configurationsJsonNode;
258             try {
259                 configurationsJsonNode = oMapper.readTree(payloadText);
260             } catch (Exception e) {
261                 throw new InvalidMessageException("Cannot parse payload value", e);
262             }
263
264         String mapFilename = rootDir + MAP_FILE_NAME + ".map";
265         Map<String, String> fieldMap = loadMap(mapFilename);
266         if (fieldMap == null) {
267             return;
268         }
269
270         if (!fieldMap.containsKey(SDNC_ENDPOINT)) {
271             return;
272         }
273         String sdncEndpoint = fieldMap.get(SDNC_ENDPOINT);
274
275         if (!fieldMap.containsKey(TEMPLATE)) {
276             throw new InvalidMessageException("No SDNC template known for message ");
277         }
278         String templateName = fieldMap.get(TEMPLATE);
279         
280         JsonNode configurations = configurationsJsonNode.get(CONFIGURATIONS);
281         
282         if(configurations.isArray()) {
283                 for(JsonNode dataNode:configurations) {
284                 if(dataNode.get(DATA).get(FAP_SERVICE) == null) {
285                     LOG.info("Could not make a rpc call. Missing fapService node for dataNode element::", dataNode.textValue());
286                 }else {
287                         try {
288                         
289                         String rpcMsgbody = publish(templateName, msg, dataNode);
290                         String odlUrlBase = getProperty("sdnc.odl.url-base");
291                         String odlUser = getProperty("sdnc.odl.user");
292                         String odlPassword = getProperty("sdnc.odl.password");
293
294                         if ((odlUrlBase != null) && (odlUrlBase.length() > 0)) {
295                             SdncOdlConnection conn = SdncOdlConnection.newInstance(odlUrlBase + "/" + sdncEndpoint, odlUser, odlPassword);
296
297                             conn.send("POST", "application/json", rpcMsgbody);
298                         } else {
299                             LOG.info("POST message body would be:\n" + rpcMsgbody);
300                         }
301                     } catch (Exception e) {
302                         LOG.error("Unable to process message", e);
303                     }
304                 }
305                 }
306         }else {
307                 throw new InvalidMessageException("Configurations is not of Type Array. Could not read configuration changes");
308         }
309     }
310
311     private Map<String, String> loadMap(String mapFilename) {
312         File mapFile = new File(mapFilename);
313
314         if (!mapFile.canRead()) {
315             LOG.error(String.format("Cannot read map file (%s)", mapFilename));
316             return null;
317         }
318
319         Map<String, String> results = new HashMap<>();
320         try (BufferedReader mapReader = new BufferedReader(new FileReader(mapFile))) {
321
322             String curLine;
323
324             while ((curLine = mapReader.readLine()) != null) {
325                 curLine = curLine.trim();
326
327                 if ((curLine.length() > 0) && (!curLine.startsWith("#")) && curLine.contains("=>")) {
328                     String[] entry = curLine.split("=>");
329                     if (entry.length == 2) {
330                         results.put(entry[0].trim(), entry[1].trim());
331                     }
332                 }
333             }
334             mapReader.close();
335         } catch (Exception e) {
336             LOG.error("Caught exception reading map " + mapFilename, e);
337             return null;
338         }
339
340         return results;
341     }
342
343 }