implement generic retry and partners in restapicallnode
[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.Format;
47 import org.onap.ccsdk.sli.plugins.restapicall.HttpResponse;
48 import org.onap.ccsdk.sli.plugins.restapicall.RestapiCallNode;
49 import org.onap.ccsdk.sli.plugins.restapicall.XmlParser;
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         HttpResponse r = new HttpResponse();
167         try {
168             YangParameters p = getYangParameters(paramMap);
169
170             String pp = p.responsePrefix != null ? p.responsePrefix + '.' : "";
171             Map<String, String> props = new HashMap<>((Map)ctx.toProperties());
172             String uri = parseUrl(p.restapiUrl, p.httpMethod);
173             InstanceIdentifierContext<?> insIdCtx = getInsIdCtx(p, uri);
174
175             String req = null;
176             if (p.httpMethod != GET && p.httpMethod != DELETE) {
177                 req = serializeRequest(props, p, uri, insIdCtx);
178                 if (p.httpMethod == PUT || p.httpMethod == PATCH) {
179                     updateReq(req, p, insIdCtx);
180                 }
181             }
182             if (req == null && p.requestBody != null) {
183                 req = p.requestBody;
184             }
185
186             r = rest.sendHttpRequest(req, p);
187             if (p.returnRequestPayload && req != null) {
188                 ctx.setAttribute(pp + HTTP_REQ, req);
189             }
190
191             String response = getResponse(ctx, p, pp, r);
192             if (response != null) {
193                 try {
194                     Map<String, String> resProp = serializeResponse(
195                             p, uri, response, insIdCtx);
196                     for (Map.Entry<String, String> pro : resProp.entrySet()) {
197                         ctx.setAttribute(pro.getKey(), pro.getValue());
198                     }
199                 } catch (SvcLogicException e) {
200                     convertToNormalRes(ctx, p, pp, response);
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             setFailureResponseStatus(ctx, prefix, e.getMessage());
212         }
213
214         if (r != null && r.code >= 300) {
215             throw new SvcLogicException(valueOf(r.code) +
216                                                 COLON + " " + r.message);
217         }
218     }
219
220     private void convertToNormalRes(SvcLogicContext ctx ,
221                                     YangParameters p, String pp, String body)
222             throws SvcLogicException {
223         if (p.convertResponse) {
224             Map<String, String> mm = null;
225             if (p.format == Format.XML) {
226                 mm = XmlParser.convertToProperties(body, p.listNameList);
227             } else if (p.format == Format.JSON) {
228                 mm = org.onap.ccsdk.sli.plugins.restapicall.JsonParser
229                         .convertToProperties(body);
230             }
231
232             if (mm != null) {
233                 for (Map.Entry<String, String> entry : mm.entrySet()) {
234                     ctx.setAttribute(pp + entry.getKey(),
235                                      entry.getValue());
236                 }
237             }
238         }
239     }
240
241     /**
242      * Serializes the request message to JSON or XML from the properties.
243      *
244      * @param properties properties
245      * @param params     YANG parameters
246      * @param uri        URI
247      * @param insIdCtx   instance identifier context
248      * @return JSON or XML message to be sent
249      * @throws SvcLogicException when serializing the request fails
250      */
251      public String serializeRequest(Map<String, String> properties,
252                                     YangParameters params, String uri,
253                                     InstanceIdentifierContext insIdCtx)
254              throws SvcLogicException {
255         PropertiesNodeSerializer propSer = new MdsalPropertiesNodeSerializer(
256                 insIdCtx.getSchemaNode(), insIdCtx.getSchemaContext(), uri);
257         DataFormatSerializerContext serCtx = new DataFormatSerializerContext(
258                 null, uri, null, propSer);
259         DataFormatSerializer ser = DfSerializerFactory.instance()
260                 .getSerializer(serCtx, params);
261          //TODO: Handling of XML annotations
262         return ser.encode(properties, null);
263     }
264
265     /**
266      * Serializes the response message from JSON or XML to the properties.
267      *
268      * @param params   YANG parameters
269      * @param uri      URI
270      * @param response response message
271      * @param insIdCtx instance identifier context
272      * @return response message as properties
273      * @throws SvcLogicException when serializing the response fails
274      */
275     public Map<String, String> serializeResponse(YangParameters params,
276                                                  String uri, String response,
277                                                  InstanceIdentifierContext insIdCtx)
278             throws SvcLogicException {
279         PropertiesNodeSerializer propSer = new MdsalPropertiesNodeSerializer(
280                 insIdCtx.getSchemaNode(), insIdCtx.getSchemaContext(), uri);
281         SerializerHelper helper = new MdsalSerializerHelper(
282                 insIdCtx.getSchemaNode(), insIdCtx.getSchemaContext(), uri);
283         Listener listener = instance().getListener(helper, params);
284         DataFormatSerializerContext serCtx = new DataFormatSerializerContext(
285                 listener, uri, null, propSer);
286         DataFormatSerializer ser = DfSerializerFactory.instance()
287                 .getSerializer(serCtx, params);
288         return ser.decode(response);
289     }
290
291     /**
292      * Returns instance identifier context for a uri using the schema context.
293      *
294      * @param params YANG parameters
295      * @param uri    URI
296      * @return instance identifier context
297      * @throws SvcLogicException when getting schema context fails
298      */
299     private InstanceIdentifierContext<?> getInsIdCtx(YangParameters params,
300                                                      String uri)
301             throws SvcLogicException {
302         SchemaContext context = getSchemaContext(params);
303         return ParserIdentifier.toInstanceIdentifier(uri, context, null);
304     }
305
306     /**
307      * Returns the global schema context or schema context of particular YANG
308      * files present in a directory path.
309      *
310      * @param params YANG parameters
311      * @return schema context
312      * @throws SvcLogicException when schema context fetching fails
313      */
314     private SchemaContext getSchemaContext(YangParameters params)
315             throws SvcLogicException {
316         if (params.dirPath != null) {
317             return getSchemaCtxFromDir(params.dirPath);
318         }
319         BundleContext bc = getBundle(SchemaContext.class).getBundleContext();
320         SchemaContext schemaContext = null;
321         if (bc != null) {
322             ServiceReference reference = bc.getServiceReference(
323                     SchemaContext.class);
324             if (reference != null) {
325                 schemaContext = (SchemaContext) bc.getService(reference);
326             }
327         }
328         return schemaContext;
329     }
330
331     /**
332      * Returns the response message body of a http response message.
333      *
334      * @param ctx    svc logic context
335      * @param params parameters
336      * @param pre    prefix to be appended
337      * @param res    http response
338      * @return response message body
339      */
340     public String getResponse(SvcLogicContext ctx, YangParameters params,
341                                String pre, HttpResponse res) {
342         ctx.setAttribute(pre + RES_CODE, valueOf(res.code));
343         ctx.setAttribute(pre + RES_MSG, res.message);
344
345         if (params.dumpHeaders && res.headers != null) {
346             for (Map.Entry<String, List<String>> a : res.headers.entrySet()) {
347                 ctx.setAttribute(pre + HEADER + a.getKey(),
348                                  join(a.getValue(), COMMA));
349             }
350         }
351
352         if (res.body != null && res.body.trim().length() > 0) {
353             ctx.setAttribute(pre + HTTP_RES, res.body);
354             return res.body;
355         }
356         return null;
357     }
358
359     /**
360      * Sets the failure response status in the context memory.
361      *
362      * @param ctx    service logic context
363      * @param prefix prefix to be added
364      * @param errMsg error message
365      */
366     private void setFailureResponseStatus(SvcLogicContext ctx, String prefix,
367                                           String errMsg) {
368         HttpResponse res = new HttpResponse();
369         res.code = 500;
370         res.message = errMsg;
371         ctx.setAttribute(prefix + RES_CODE, valueOf(res.code));
372         ctx.setAttribute(prefix + RES_MSG, res.message);
373     }
374
375     /**
376      * Updates request message for JSON and XML data format, when the HTTP
377      * method points it as PUT or PATCH.
378      *
379      * @param req      current request message
380      * @param p        YANG parameters
381      * @param insIdCtx instance identifier context
382      * @return update request message
383      * @throws SvcLogicException when the data format type is wrong
384      */
385     public String updateReq(String req, YangParameters p,
386                              InstanceIdentifierContext<?> insIdCtx)
387             throws SvcLogicException {
388
389         SchemaNode schemaNode = insIdCtx.getSchemaNode();
390         Namespace modNs = getModuleNamespace(schemaNode.getQName(),
391                                              insIdCtx.getSchemaContext());
392         String nodeName = schemaNode.getQName().getLocalName();
393
394         switch (p.format) {
395             case JSON:
396                 return getUpdatedJsonReq(req, nodeName, modNs.moduleName());
397
398             case XML:
399                 return getXmlReqForPutOp(req, nodeName, modNs.moduleNs());
400
401             default:
402                 throw new SvcLogicException(format(FORMAT_ERR, p.format));
403         }
404     }
405
406     /**
407      * Returns the updated JSON request message, when the HTTP method
408      * points to PUT or PATCH.
409      *
410      * @param req      current JSON request message
411      * @param nodeName root node name
412      * @param modName  module name of the root node
413      * @return update JSON request message
414      */
415     private String getUpdatedJsonReq(String req, String nodeName,
416                                      String modName) {
417         Writer writer = new StringWriter();
418         JsonWriter jsonWriter = new JsonWriter(writer);
419         jsonWriter.setIndent(repeat(" ", 4));
420
421         JsonParser jsonParser = new JsonParser();
422         JsonObject oldJson = (JsonObject)jsonParser.parse(req);
423         oldJson = remChildModName(oldJson, modName);
424         JsonObject newJson = new JsonObject();
425         newJson.add(modName + COLON + nodeName, oldJson.deepCopy());
426
427         Gson gson= new Gson();
428         gson.toJson(newJson, jsonWriter);
429         return writer.toString();
430     }
431
432     /**
433      * Removes module name from all the updated first level child node, if it
434      * is same as the root node added.
435      *
436      * @param oldJson JSON object for old request
437      * @param modName module name of root node
438      * @return JSON object for old request with updated child module name
439      */
440     private JsonObject remChildModName(JsonObject oldJson, String modName) {
441         Iterator<Map.Entry<String, JsonElement>> it = oldJson.entrySet().iterator();
442         Map<String, JsonElement> m = new HashMap<>();
443         while (it.hasNext()) {
444             Map.Entry<String, JsonElement> jNode = it.next();
445             if (jNode.getKey().contains(COLON)) {
446                 String[] modArr = jNode.getKey().split(COLON);
447                 if (modArr[0].equals(modName)) {
448                     it.remove();
449                     m.put(modArr[1], jNode.getValue());
450                 }
451             }
452         }
453         if (!m.isEmpty()) {
454             for (Map.Entry<String, JsonElement> element : m.entrySet()) {
455                 oldJson.add(element.getKey(), element.getValue());
456             }
457         }
458         return oldJson;
459     }
460
461     /**
462      * Returns the updated XML request message, when the HTTP method points
463      * to PUT or PATCH.
464      *
465      * @param req      current JSON request message
466      * @param nodeName root node name
467      * @param modNs    module namespace of the root node
468      * @return update JSON request message
469      * @throws SvcLogicException when XML parsing fails
470      */
471     private String getXmlReqForPutOp(String req, String nodeName,
472                                      URI modNs) throws SvcLogicException {
473         req = getUpdatedXmlReq(req, nodeName, modNs.toString());
474         Document oldDoc;
475         try {
476             oldDoc = DocumentHelper.parseText(req);
477         } catch (DocumentException e) {
478             throw new SvcLogicException(XML_TREE_ERR, e);
479         }
480         Writer writer = getXmlWriter(
481                 UTF_HEADER + oldDoc.getRootElement().asXML(), "4");
482         return writer.toString();
483     }
484 }