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