DMAAP Listener support for SDNR OOF PCI
[ccsdk/sli/northbound.git] / dmaap-listener / src / main / java / org / onap / ccsdk / sli / northbound / dmaapclient / PciChangesFromPolicyToSDNRDmaapConsumer.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 PciChangesFromPolicyToSDNRDmaapConsumer extends SdncDmaapConsumerImpl {
44
45     private static final Logger LOG = LoggerFactory.getLogger(PciChangesFromPolicyToSDNRDmaapConsumer.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 PHYSICAL_CELL_ID_INPUT_FAP_SERVICE = "configuration-phy-cell-id-input.fap-service";
53     private static final String EVENT_HEADER = "event-header";
54         private static final String ACTION = "Action";
55         private static final String PAYLOAD = "Payload";
56         private static final String CONFIGURATIONS = "Configurations";
57         private static final String MODIFY_CONFIG = "ModifyConfig";
58         private static final String MAP_FILE_NAME = "pci-changes-from-policy-to-sdnr";
59         private static final String DATA = "data";
60         private static final String FAP_SERVICE = "FAPService";
61         private static final String SLI_PARAMETERS = "sli_parameters";
62         private static final String RPC_NAME = "rpc-name";
63         private static final String BODY = "body";
64         private static final String INPUT = "input";
65
66     private String rootDir;
67
68     protected VelocityEngine velocityEngine;
69
70     public PciChangesFromPolicyToSDNRDmaapConsumer() {
71         velocityEngine = new VelocityEngine();
72         Properties props = new Properties();
73         rootDir = System.getenv(DMAAPLISTENERROOT);
74
75         if ((rootDir == null) || (rootDir.length() == 0)) {
76             rootDir = "/opt/app/dmaap-listener/lib/";
77         }
78         else {
79             rootDir = rootDir + "/lib/";
80         }
81
82         props.put("file.resource.loader.path", rootDir);
83         velocityEngine.init(props);
84     }
85
86     /*
87      * for testing purposes
88      */
89     PciChangesFromPolicyToSDNRDmaapConsumer(Properties props) {
90         velocityEngine = new VelocityEngine();
91         velocityEngine.init(props);
92     }
93
94     protected String publish(String templatePath, String jsonString, JsonNode configurationsJsonNode) throws IOException, InvalidMessageException
95     {
96         if (templatePath.contains("anr-pci-changes-from-policy-to-sdnr")){
97             return publishPciChangesFromPolicyToSDNR(templatePath, configurationsJsonNode);
98         } else {
99             return publishFullMessage(templatePath, jsonString);
100         }
101     }
102
103     private String publishFullMessage(String templatePath, String jsonString) throws IOException
104     {
105         JSONObject jsonObj = new JSONObject(jsonString);
106         VelocityContext context = new VelocityContext();
107         for(Object key : jsonObj.keySet())
108         {
109             context.put((String)key, jsonObj.get((String)key));
110         }
111
112         String id = jsonObj.getJSONObject(EVENT_HEADER).get("id").toString();
113         context.put("req_id", id);
114
115         context.put("curr_time", Instant.now());
116
117         ObjectMapper oMapper = new ObjectMapper();
118
119         String rpcMsgbody = oMapper.writeValueAsString(jsonString);
120         context.put("full_message", rpcMsgbody);
121
122         Writer writer = new StringWriter();
123         velocityEngine.mergeTemplate(templatePath, "UTF-8", context, writer);
124         writer.flush();
125
126         return writer.toString();
127     }
128
129     private String publishPciChangesFromPolicyToSDNR(String templatePath, JsonNode configurationsJsonNode) throws IOException, InvalidMessageException
130     {
131         String RPC_NAME_KEY_IN_VT = "rpc_name";
132         String RPC_NAME_VALUE_IN_VT = "configuration-phy-cell-id";
133         String ALIAS = "alias";
134         String X0005b9Lte = "X0005b9Lte";
135         
136         VelocityContext context = new VelocityContext();
137         
138         JSONObject numberOfEntries = new JSONObject();
139         JSONArray sliParametersArray = new JSONArray();
140         
141         JsonNode configurations = configurationsJsonNode.get(CONFIGURATIONS);
142         
143         int entryCount = 0;
144         
145         if(configurations.isArray()) {
146                 for(JsonNode dataNode:configurations) {
147                         sliParametersArray.put(new JSONObject().put(PARAMETER_NAME, PHYSICAL_CELL_ID_INPUT_FAP_SERVICE+"["+entryCount+"]."+ALIAS)
148                                 .put(STRING_VALUE, dataNode.get(DATA).get(FAP_SERVICE).get(ALIAS)));
149                         sliParametersArray.put(new JSONObject().put(PARAMETER_NAME, PHYSICAL_CELL_ID_INPUT_FAP_SERVICE+"["+entryCount+"]."+"cid")
150                                 .put(STRING_VALUE, dataNode.get(DATA).get(FAP_SERVICE).get("CellConfig").get("LTE").get("RAN").get("Common").get("CellIdentity")));
151                         sliParametersArray.put(new JSONObject().put(PARAMETER_NAME, PHYSICAL_CELL_ID_INPUT_FAP_SERVICE+"["+entryCount+"]."+"phy-cell-id-in-use")
152                                 .put(STRING_VALUE, dataNode.get(DATA).get(FAP_SERVICE).get(X0005b9Lte).get("phyCellIdInUse")));
153                         sliParametersArray.put(new JSONObject().put(PARAMETER_NAME, PHYSICAL_CELL_ID_INPUT_FAP_SERVICE+"["+entryCount+"]."+"pnf-name")
154                                 .put(STRING_VALUE, dataNode.get(DATA).get(FAP_SERVICE).get(X0005b9Lte).get("pnfName")));
155                         entryCount++;
156                 }
157             
158             numberOfEntries.put(PARAMETER_NAME, PHYSICAL_CELL_ID_INPUT_FAP_SERVICE+"-number-of-entries");
159             numberOfEntries.put(STRING_VALUE, entryCount);
160             
161             sliParametersArray.put(numberOfEntries);
162             
163             context.put(SLI_PARAMETERS, sliParametersArray);
164             
165             context.put(RPC_NAME_KEY_IN_VT, RPC_NAME_VALUE_IN_VT);
166
167             Writer writer = new StringWriter();
168             velocityEngine.mergeTemplate(templatePath, "UTF-8", context, writer);
169             writer.flush();
170
171             return writer.toString();
172                 
173         }else {
174                 throw new InvalidMessageException("Configurations is not of Type Array. Could not read configuration changes");
175         }
176         
177     }
178
179     @Override
180     public void processMsg(String msg) throws InvalidMessageException {
181
182         if (msg == null) {
183             throw new InvalidMessageException("Null message");
184         }
185
186         ObjectMapper oMapper = new ObjectMapper();
187         JsonNode pciChangesRootNode;
188         try {
189                 pciChangesRootNode = oMapper.readTree(msg);
190         } catch (Exception e) {
191             throw new InvalidMessageException("Cannot parse json object", e);
192         }
193
194         JsonNode rpcname = pciChangesRootNode.get(RPC_NAME);
195         if(rpcname == null) {
196                  LOG.info("Missing rpc-name node.");
197                  return;
198         }
199         
200         if(!MODIFY_CONFIG.toLowerCase().equals(rpcname.textValue())) {
201             LOG.info("Unknown rpc name {}", rpcname);
202             return;
203         }
204         
205         JsonNode body = pciChangesRootNode.get(BODY);
206         if(body == null) {
207                  LOG.info("Missing body node.");
208                  return;
209         }
210         
211         JsonNode input = body.get(INPUT);
212         if(input == null) {
213                  LOG.info("Missing input node.");
214                  return;
215         }
216         
217         JsonNode action = input.get(ACTION);
218         if(action == null) {
219                  LOG.info("Missing action node.");
220                  return;
221         }
222         
223         if(!MODIFY_CONFIG.equals(action.textValue())) {
224             LOG.info("Unknown Action {}", action);
225             return;
226         }
227         
228         JsonNode payload = input.get(PAYLOAD);
229         if(payload == null) {
230             LOG.info("Missing payload node.");
231             return;
232         }
233
234         String configurations = payload.asText();
235         
236         if(!configurations.contains(CONFIGURATIONS)) {
237          LOG.info("Missing configurations node.");
238          return;
239        }
240         
241        JsonNode configurationsJsonNode;
242             try {
243                 configurationsJsonNode = oMapper.readTree(configurations);
244             } catch (Exception e) {
245                 throw new InvalidMessageException("Cannot parse payload value", e);
246             }
247
248         String mapFilename = rootDir + MAP_FILE_NAME + ".map";
249         Map<String, String> fieldMap = loadMap(mapFilename);
250         if (fieldMap == null) {
251             return;
252         }
253
254         if (!fieldMap.containsKey(SDNC_ENDPOINT)) {
255             return;
256         }
257         String sdncEndpoint = fieldMap.get(SDNC_ENDPOINT);
258
259         if (!fieldMap.containsKey(TEMPLATE)) {
260             throw new InvalidMessageException("No SDNC template known for message ");
261         }
262         String templateName = fieldMap.get(TEMPLATE);
263
264         try {
265             String rpcMsgbody = publish(templateName, msg, configurationsJsonNode);
266             String odlUrlBase = getProperty("sdnc.odl.url-base");
267             String odlUser = getProperty("sdnc.odl.user");
268             String odlPassword = getProperty("sdnc.odl.password");
269
270             if ((odlUrlBase != null) && (odlUrlBase.length() > 0)) {
271                 SdncOdlConnection conn = SdncOdlConnection.newInstance(odlUrlBase + "/" + sdncEndpoint, odlUser, odlPassword);
272
273                 conn.send("POST", "application/json", rpcMsgbody);
274             } else {
275                 LOG.info("POST message body would be:\n" + rpcMsgbody);
276             }
277         } catch (Exception e) {
278             LOG.error("Unable to process message", e);
279         }
280     }
281
282     private Map<String, String> loadMap(String mapFilename) {
283         File mapFile = new File(mapFilename);
284
285         if (!mapFile.canRead()) {
286             LOG.error(String.format("Cannot read map file (%s)", mapFilename));
287             return null;
288         }
289
290         Map<String, String> results = new HashMap<>();
291         try (BufferedReader mapReader = new BufferedReader(new FileReader(mapFile))) {
292
293             String curLine;
294
295             while ((curLine = mapReader.readLine()) != null) {
296                 curLine = curLine.trim();
297
298                 if ((curLine.length() > 0) && (!curLine.startsWith("#")) && curLine.contains("=>")) {
299                     String[] entry = curLine.split("=>");
300                     if (entry.length == 2) {
301                         results.put(entry[0].trim(), entry[1].trim());
302                     }
303                 }
304             }
305             mapReader.close();
306         } catch (Exception e) {
307             LOG.error("Caught exception reading map " + mapFilename, e);
308             return null;
309         }
310
311         return results;
312     }
313
314 }