Replacing ":" by "_" for parameters
[ccsdk/sli/plugins.git] / restconf-client / provider / src / main / java / org / onap / ccsdk / sli / plugins / restconfapicall / RestconfApiCallNode.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * ONAP - CCSDK
4  * ================================================================================
5  * Copyright (C) 2018 Huawei Technologies Co., Ltd. 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.ccsdk.sli.plugins.restconfapicall;
22
23 import com.google.gson.Gson;
24 import com.google.gson.JsonElement;
25 import com.google.gson.JsonObject;
26 import com.google.gson.JsonParser;
27 import com.google.gson.stream.JsonWriter;
28
29 import javax.ws.rs.core.UriBuilder;
30 import java.io.StringWriter;
31 import java.io.Writer;
32 import java.net.SocketException;
33 import java.net.URI;
34 import java.net.URISyntaxException;
35 import java.util.HashMap;
36 import java.util.Iterator;
37 import java.util.List;
38 import java.util.Map;
39
40 import org.dom4j.Document;
41 import org.dom4j.DocumentException;
42 import org.dom4j.DocumentHelper;
43 import org.onap.ccsdk.sli.core.sli.SvcLogicContext;
44 import org.onap.ccsdk.sli.core.sli.SvcLogicException;
45 import org.onap.ccsdk.sli.core.sli.SvcLogicJavaPlugin;
46 import org.onap.ccsdk.sli.plugins.restapicall.HttpResponse;
47 import org.onap.ccsdk.sli.plugins.restapicall.RestapiCallNode;
48 import org.onap.ccsdk.sli.plugins.restapicall.RetryException;
49 import org.onap.ccsdk.sli.plugins.restapicall.RetryPolicy;
50 import org.onap.ccsdk.sli.plugins.yangserializers.dfserializer.DataFormatSerializer;
51 import org.onap.ccsdk.sli.plugins.yangserializers.dfserializer.DataFormatSerializerContext;
52 import org.onap.ccsdk.sli.plugins.yangserializers.dfserializer.DfSerializerFactory;
53 import org.onap.ccsdk.sli.plugins.yangserializers.dfserializer.Listener;
54 import org.onap.ccsdk.sli.plugins.yangserializers.dfserializer.MdsalSerializerHelper;
55 import org.onap.ccsdk.sli.plugins.yangserializers.dfserializer.SerializerHelper;
56 import org.onap.ccsdk.sli.plugins.yangserializers.dfserializer.YangParameters;
57 import org.onap.ccsdk.sli.plugins.yangserializers.pnserializer.MdsalPropertiesNodeSerializer;
58 import org.onap.ccsdk.sli.plugins.yangserializers.pnserializer.Namespace;
59 import org.onap.ccsdk.sli.plugins.yangserializers.pnserializer.PropertiesNodeSerializer;
60 import org.opendaylight.restconf.common.context.InstanceIdentifierContext;
61 import org.opendaylight.restconf.nb.rfc8040.utils.parser.ParserIdentifier;
62 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
63 import org.opendaylight.yangtools.yang.model.api.SchemaNode;
64 import org.osgi.framework.BundleContext;
65 import org.osgi.framework.ServiceReference;
66 import org.slf4j.Logger;
67 import org.slf4j.LoggerFactory;
68
69 import static com.google.common.base.Strings.repeat;
70 import static java.lang.String.format;
71 import static java.lang.String.valueOf;
72 import static org.apache.commons.lang3.StringUtils.join;
73 import static org.onap.ccsdk.sli.plugins.restapicall.HttpMethod.DELETE;
74 import static org.onap.ccsdk.sli.plugins.restapicall.HttpMethod.GET;
75 import static org.onap.ccsdk.sli.plugins.restapicall.HttpMethod.PATCH;
76 import static org.onap.ccsdk.sli.plugins.restapicall.HttpMethod.PUT;
77 import static org.onap.ccsdk.sli.plugins.restapicall.RestapiCallNode.parseParam;
78 import static org.onap.ccsdk.sli.plugins.restconfapicall.RestconfApiUtils.ATTEMPTS_MSG;
79 import static org.onap.ccsdk.sli.plugins.restconfapicall.RestconfApiUtils.COLON;
80 import static org.onap.ccsdk.sli.plugins.restconfapicall.RestconfApiUtils.COMMA;
81 import static org.onap.ccsdk.sli.plugins.restconfapicall.RestconfApiUtils.COMM_FAIL;
82 import static org.onap.ccsdk.sli.plugins.restconfapicall.RestconfApiUtils.HEADER;
83 import static org.onap.ccsdk.sli.plugins.restconfapicall.RestconfApiUtils.HTTP_REQ;
84 import static org.onap.ccsdk.sli.plugins.restconfapicall.RestconfApiUtils.HTTP_RES;
85 import static org.onap.ccsdk.sli.plugins.restconfapicall.RestconfApiUtils.MAX_RETRY_ERR;
86 import static org.onap.ccsdk.sli.plugins.restconfapicall.RestconfApiUtils.NO_MORE_RETRY;
87 import static org.onap.ccsdk.sli.plugins.restconfapicall.RestconfApiUtils.REQ_ERR;
88 import static org.onap.ccsdk.sli.plugins.restconfapicall.RestconfApiUtils.REST_API_URL;
89 import static org.onap.ccsdk.sli.plugins.restconfapicall.RestconfApiUtils.RES_CODE;
90 import static org.onap.ccsdk.sli.plugins.restconfapicall.RestconfApiUtils.RES_MSG;
91 import static org.onap.ccsdk.sli.plugins.restconfapicall.RestconfApiUtils.RES_PRE;
92 import static org.onap.ccsdk.sli.plugins.restconfapicall.RestconfApiUtils.RETRY_COUNT;
93 import static org.onap.ccsdk.sli.plugins.restconfapicall.RestconfApiUtils.RETRY_FAIL;
94 import static org.onap.ccsdk.sli.plugins.restconfapicall.RestconfApiUtils.UPDATED_URL;
95 import static org.onap.ccsdk.sli.plugins.restconfapicall.RestconfApiUtils.getSchemaCtxFromDir;
96 import static org.onap.ccsdk.sli.plugins.restconfapicall.RestconfApiUtils.getUpdatedXmlReq;
97 import static org.onap.ccsdk.sli.plugins.restconfapicall.RestconfApiUtils.getYangParameters;
98 import static org.onap.ccsdk.sli.plugins.restconfapicall.RestconfApiUtils.parseUrl;
99 import static org.onap.ccsdk.sli.plugins.yangserializers.dfserializer.DfListenerFactory.instance;
100 import static org.onap.ccsdk.sli.plugins.yangserializers.dfserializer.DfSerializerUtil.FORMAT_ERR;
101 import static org.onap.ccsdk.sli.plugins.yangserializers.dfserializer.DfSerializerUtil.UTF_HEADER;
102 import static org.onap.ccsdk.sli.plugins.yangserializers.dfserializer.DfSerializerUtil.XML_TREE_ERR;
103 import static org.onap.ccsdk.sli.plugins.yangserializers.dfserializer.DfSerializerUtil.getXmlWriter;
104 import static org.onap.ccsdk.sli.plugins.yangserializers.pnserializer.MdsalPropertiesNodeUtils.getModuleNamespace;
105 import static org.osgi.framework.FrameworkUtil.getBundle;
106
107 /**
108  * Representation of a plugin to enable RESTCONF based CRUD operations from DG.
109  */
110 public class RestconfApiCallNode implements SvcLogicJavaPlugin {
111
112     /**
113      * Logger for the restconf api call node class.
114      */
115     private static final Logger log = LoggerFactory.getLogger(
116             RestconfApiCallNode.class);
117
118     /**
119      * Rest api call node service instance
120      */
121     private RestapiCallNode restapiCallNode;
122
123     /**
124      * Creates an instance of restconf api call node with restapi call node.
125      *
126      * @param r restapi call node
127      */
128     public RestconfApiCallNode(RestapiCallNode r) {
129         this.restapiCallNode = r;
130     }
131
132     /**
133      * Returns the restapi call node instance.
134      * @return
135      */
136     public RestapiCallNode getRestapiCallNode() {
137         return restapiCallNode;
138     }
139
140     /**
141      * Sends the restconf request using the parameters map and the memory
142      * context. And this method allows the directed graphs to interact with
143      * the restconf api call node
144      *
145      * @param paramMap parameters map
146      * @param ctx      service logic context
147      * @throws SvcLogicException when svc logic exception occurs
148      */
149     public void sendRequest(Map<String, String> paramMap, SvcLogicContext ctx)
150             throws SvcLogicException {
151         sendRequest(paramMap, ctx, 0);
152     }
153
154     /**
155      * Sends the restconf request using the parameters map and the memory
156      * context along with the retry count.
157      *
158      * @param paramMap   parameters map
159      * @param ctx        service logic context
160      * @param retryCount number of retry counts
161      * @throws SvcLogicException when svc logic exception occurs
162      */
163     public void sendRequest(Map<String, String> paramMap, SvcLogicContext ctx,
164                             Integer retryCount) throws SvcLogicException {
165         RestapiCallNode rest = getRestapiCallNode();
166         RetryPolicy retryPolicy = null;
167         HttpResponse r = new HttpResponse();
168         try {
169             YangParameters p = getYangParameters(paramMap);
170             if (p.partner != null) {
171                 retryPolicy = rest.getRetryPolicyStore()
172                         .getRetryPolicy(p.partner);
173             }
174
175             String pp = p.responsePrefix != null ? p.responsePrefix + '.' : "";
176             Map<String, String> props = new HashMap<>((Map)ctx.toProperties());
177             String uri = parseUrl(p.restapiUrl, p.httpMethod);
178             InstanceIdentifierContext<?> insIdCtx = getInsIdCtx(p, uri);
179
180             String req = null;
181             if (p.httpMethod != GET && p.httpMethod != DELETE) {
182                 req = serializeRequest(props, p, uri, insIdCtx);
183                 if (p.httpMethod == PUT || p.httpMethod == PATCH) {
184                     updateReq(req, p, insIdCtx);
185                 }
186             }
187             if (req == null && p.requestBody != null) {
188                 req = p.requestBody;
189             }
190
191             r = rest.sendHttpRequest(req, p);
192             if (p.returnRequestPayload && req != null) {
193                 ctx.setAttribute(pp + HTTP_REQ, req);
194             }
195
196             String response = getResponse(ctx, p, pp, r);
197             if (response != null) {
198                 Map<String, String> resProp = serializeResponse(
199                         p, uri, response, insIdCtx);
200                 for (Map.Entry<String, String> pro : resProp.entrySet()) {
201                     ctx.setAttribute(pro.getKey(), pro.getValue());
202                 }
203             }
204         } catch (SvcLogicException e) {
205             boolean shouldRetry = false;
206             if (e.getCause().getCause() instanceof SocketException) {
207                 shouldRetry = true;
208             }
209
210             log.error(REQ_ERR + e.getMessage(), e);
211             String prefix = parseParam(paramMap, RES_PRE, false, null);
212             if (retryPolicy == null || !shouldRetry) {
213                 setFailureResponseStatus(ctx, prefix, e.getMessage());
214             } else {
215                 if (retryCount == null) {
216                     retryCount = 0;
217                 }
218                 log.debug(format(ATTEMPTS_MSG, retryCount,
219                                  retryPolicy.getMaximumRetries()));
220                 try {
221                     retryCount = retryCount + 1;
222                     if (retryCount < retryPolicy.getMaximumRetries() + 1) {
223                         setRetryUri(paramMap, retryPolicy);
224                         log.debug(format(RETRY_COUNT, retryCount, retryPolicy
225                                 .getMaximumRetries()));
226                         sendRequest(paramMap, ctx, retryCount);
227                     } else {
228                         log.debug(MAX_RETRY_ERR);
229                         setFailureResponseStatus(ctx, prefix, e.getMessage());
230                     }
231                 } catch (Exception ex) {
232                     log.error(NO_MORE_RETRY, ex);
233                     setFailureResponseStatus(ctx, prefix, RETRY_FAIL);
234                 }
235             }
236         }
237
238         if (r != null && r.code >= 300) {
239             throw new SvcLogicException(valueOf(r.code) +
240                                                 COLON + " " + r.message);
241         }
242     }
243
244     /**
245      * Serializes the request message to JSON or XML from the properties.
246      *
247      * @param properties properties
248      * @param params     YANG parameters
249      * @param uri        URI
250      * @param insIdCtx   instance identifier context
251      * @return JSON or XML message to be sent
252      * @throws SvcLogicException when serializing the request fails
253      */
254      public String serializeRequest(Map<String, String> properties,
255                                     YangParameters params, String uri,
256                                     InstanceIdentifierContext insIdCtx)
257              throws SvcLogicException {
258         PropertiesNodeSerializer propSer = new MdsalPropertiesNodeSerializer(
259                 insIdCtx.getSchemaNode(), insIdCtx.getSchemaContext(), uri);
260         DataFormatSerializerContext serCtx = new DataFormatSerializerContext(
261                 null, uri, null, propSer);
262         DataFormatSerializer ser = DfSerializerFactory.instance()
263                 .getSerializer(serCtx, params);
264          //TODO: Handling of XML annotations
265         return ser.encode(properties, null);
266     }
267
268     /**
269      * Serializes the response message from JSON or XML to the properties.
270      *
271      * @param params   YANG parameters
272      * @param uri      URI
273      * @param response response message
274      * @param insIdCtx instance identifier context
275      * @return response message as properties
276      * @throws SvcLogicException when serializing the response fails
277      */
278     public Map<String, String> serializeResponse(YangParameters params,
279                                                  String uri, String response,
280                                                  InstanceIdentifierContext insIdCtx)
281             throws SvcLogicException {
282         PropertiesNodeSerializer propSer = new MdsalPropertiesNodeSerializer(
283                 insIdCtx.getSchemaNode(), insIdCtx.getSchemaContext(), uri);
284         SerializerHelper helper = new MdsalSerializerHelper(
285                 insIdCtx.getSchemaNode(), insIdCtx.getSchemaContext(), uri);
286         Listener listener = instance().getListener(helper, params);
287         DataFormatSerializerContext serCtx = new DataFormatSerializerContext(
288                 listener, uri, null, propSer);
289         DataFormatSerializer ser = DfSerializerFactory.instance()
290                 .getSerializer(serCtx, params);
291         return ser.decode(response);
292     }
293
294     /**
295      * Returns instance identifier context for a uri using the schema context.
296      *
297      * @param params YANG parameters
298      * @param uri    URI
299      * @return instance identifier context
300      * @throws SvcLogicException when getting schema context fails
301      */
302     private InstanceIdentifierContext<?> getInsIdCtx(YangParameters params,
303                                                      String uri)
304             throws SvcLogicException {
305         SchemaContext context = getSchemaContext(params);
306         return ParserIdentifier.toInstanceIdentifier(uri, context, null);
307     }
308
309     /**
310      * Returns the global schema context or schema context of particular YANG
311      * files present in a directory path.
312      *
313      * @param params YANG parameters
314      * @return schema context
315      * @throws SvcLogicException when schema context fetching fails
316      */
317     private SchemaContext getSchemaContext(YangParameters params)
318             throws SvcLogicException {
319         if (params.dirPath != null) {
320             return getSchemaCtxFromDir(params.dirPath);
321         }
322         BundleContext bc = getBundle(SchemaContext.class).getBundleContext();
323         SchemaContext schemaContext = null;
324         if (bc != null) {
325             ServiceReference reference = bc.getServiceReference(
326                     SchemaContext.class);
327             if (reference != null) {
328                 schemaContext = (SchemaContext) bc.getService(reference);
329             }
330         }
331         return schemaContext;
332     }
333
334     /**
335      * Returns the response message body of a http response message.
336      *
337      * @param ctx    svc logic context
338      * @param params parameters
339      * @param pre    prefix to be appended
340      * @param res    http response
341      * @return response message body
342      */
343     public String getResponse(SvcLogicContext ctx, YangParameters params,
344                                String pre, HttpResponse res) {
345         ctx.setAttribute(pre + RES_CODE, valueOf(res.code));
346         ctx.setAttribute(pre + RES_MSG, res.message);
347
348         if (params.dumpHeaders && res.headers != null) {
349             for (Map.Entry<String, List<String>> a : res.headers.entrySet()) {
350                 ctx.setAttribute(pre + HEADER + a.getKey(),
351                                  join(a.getValue(), COMMA));
352             }
353         }
354
355         if (res.body != null && res.body.trim().length() > 0) {
356             ctx.setAttribute(pre + HTTP_RES, res.body);
357             return res.body;
358         }
359         return null;
360     }
361
362     /**
363      * Sets the failure response status in the context memory.
364      *
365      * @param ctx    service logic context
366      * @param prefix prefix to be added
367      * @param errMsg error message
368      */
369     private void setFailureResponseStatus(SvcLogicContext ctx, String prefix,
370                                           String errMsg) {
371         HttpResponse res = new HttpResponse();
372         res.code = 500;
373         res.message = errMsg;
374         ctx.setAttribute(prefix + RES_CODE, valueOf(res.code));
375         ctx.setAttribute(prefix + RES_MSG, res.message);
376     }
377
378     /**
379      * Sets the retry URI to the param map from the retry policies different
380      * host.
381      *
382      * @param paramMap            parameter map
383      * @param retryPolicy         retry policy
384      * @throws URISyntaxException when new URI creation fails
385      * @throws RetryException     when retry policy cannot give another host
386      */
387     private void setRetryUri(Map<String, String> paramMap,
388                              RetryPolicy retryPolicy)
389             throws URISyntaxException, RetryException {
390         URI uri = new URI(paramMap.get(REST_API_URL));
391         String hostName = uri.getHost();
392         String retryString = retryPolicy.getNextHostName(uri.toString());
393
394         URI uriTwo = new URI(retryString);
395         URI retryUri = UriBuilder.fromUri(uri).host(uriTwo.getHost()).port(
396                 uriTwo.getPort()).scheme(uriTwo.getScheme()).build();
397
398         paramMap.put(REST_API_URL, retryUri.toString());
399         log.debug(UPDATED_URL + retryUri.toString());
400         log.debug(format(COMM_FAIL, hostName, retryString));
401     }
402
403     /**
404      * Updates request message for JSON and XML data format, when the HTTP
405      * method points it as PUT or PATCH.
406      *
407      * @param req      current request message
408      * @param p        YANG parameters
409      * @param insIdCtx instance identifier context
410      * @return update request message
411      * @throws SvcLogicException when the data format type is wrong
412      */
413     public String updateReq(String req, YangParameters p,
414                              InstanceIdentifierContext<?> insIdCtx)
415             throws SvcLogicException {
416
417         SchemaNode schemaNode = insIdCtx.getSchemaNode();
418         Namespace modNs = getModuleNamespace(schemaNode.getQName(),
419                                              insIdCtx.getSchemaContext());
420         String nodeName = schemaNode.getQName().getLocalName();
421
422         switch (p.format) {
423             case JSON:
424                 return getUpdatedJsonReq(req, nodeName, modNs.moduleName());
425
426             case XML:
427                 return getXmlReqForPutOp(req, nodeName, modNs.moduleNs());
428
429             default:
430                 throw new SvcLogicException(format(FORMAT_ERR, p.format));
431         }
432     }
433
434     /**
435      * Returns the updated JSON request message, when the HTTP method
436      * points to PUT or PATCH.
437      *
438      * @param req      current JSON request message
439      * @param nodeName root node name
440      * @param modName  module name of the root node
441      * @return update JSON request message
442      */
443     private String getUpdatedJsonReq(String req, String nodeName,
444                                      String modName) {
445         Writer writer = new StringWriter();
446         JsonWriter jsonWriter = new JsonWriter(writer);
447         jsonWriter.setIndent(repeat(" ", 4));
448
449         JsonParser jsonParser = new JsonParser();
450         JsonObject oldJson = (JsonObject)jsonParser.parse(req);
451         oldJson = remChildModName(oldJson, modName);
452         JsonObject newJson = new JsonObject();
453         newJson.add(modName + COLON + nodeName, oldJson.deepCopy());
454
455         Gson gson= new Gson();
456         gson.toJson(newJson, jsonWriter);
457         return writer.toString();
458     }
459
460     /**
461      * Removes module name from all the updated first level child node, if it
462      * is same as the root node added.
463      *
464      * @param oldJson JSON object for old request
465      * @param modName module name of root node
466      * @return JSON object for old request with updated child module name
467      */
468     private JsonObject remChildModName(JsonObject oldJson, String modName) {
469         Iterator<Map.Entry<String, JsonElement>> it = oldJson.entrySet().iterator();
470         Map<String, JsonElement> m = new HashMap<>();
471         while (it.hasNext()) {
472             Map.Entry<String, JsonElement> jNode = it.next();
473             if (jNode.getKey().contains(COLON)) {
474                 String[] modArr = jNode.getKey().split(COLON);
475                 if (modArr[0].equals(modName)) {
476                     it.remove();
477                     m.put(modArr[1], jNode.getValue());
478                 }
479             }
480         }
481         if (!m.isEmpty()) {
482             for (Map.Entry<String, JsonElement> element : m.entrySet()) {
483                 oldJson.add(element.getKey(), element.getValue());
484             }
485         }
486         return oldJson;
487     }
488
489     /**
490      * Returns the updated XML request message, when the HTTP method points
491      * to PUT or PATCH.
492      *
493      * @param req      current JSON request message
494      * @param nodeName root node name
495      * @param modNs    module namespace of the root node
496      * @return update JSON request message
497      * @throws SvcLogicException when XML parsing fails
498      */
499     private String getXmlReqForPutOp(String req, String nodeName,
500                                      URI modNs) throws SvcLogicException {
501         req = getUpdatedXmlReq(req, nodeName, modNs.toString());
502         Document oldDoc;
503         try {
504             oldDoc = DocumentHelper.parseText(req);
505         } catch (DocumentException e) {
506             throw new SvcLogicException(XML_TREE_ERR, e);
507         }
508         Writer writer = getXmlWriter(
509                 UTF_HEADER + oldDoc.getRootElement().asXML(), "4");
510         return writer.toString();
511     }
512 }