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