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