Implementation for Restconf api call node
[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 org.onap.ccsdk.sli.core.sli.SvcLogicContext;
24 import org.onap.ccsdk.sli.core.sli.SvcLogicException;
25 import org.onap.ccsdk.sli.core.sli.SvcLogicJavaPlugin;
26 import org.onap.ccsdk.sli.plugins.restapicall.HttpResponse;
27 import org.onap.ccsdk.sli.plugins.restapicall.RestapiCallNode;
28 import org.onap.ccsdk.sli.plugins.restapicall.RetryException;
29 import org.onap.ccsdk.sli.plugins.restapicall.RetryPolicy;
30 import org.onap.ccsdk.sli.plugins.yangserializers.dfserializer.DataFormatSerializer;
31 import org.onap.ccsdk.sli.plugins.yangserializers.dfserializer.DataFormatSerializerContext;
32 import org.onap.ccsdk.sli.plugins.yangserializers.dfserializer.DfSerializerFactory;
33 import org.onap.ccsdk.sli.plugins.yangserializers.dfserializer.Listener;
34 import org.onap.ccsdk.sli.plugins.yangserializers.dfserializer.MdsalSerializerHelper;
35 import org.onap.ccsdk.sli.plugins.yangserializers.dfserializer.SerializerHelper;
36 import org.onap.ccsdk.sli.plugins.yangserializers.dfserializer.YangParameters;
37 import org.onap.ccsdk.sli.plugins.yangserializers.pnserializer.MdsalPropertiesNodeSerializer;
38 import org.onap.ccsdk.sli.plugins.yangserializers.pnserializer.PropertiesNodeSerializer;
39 import org.opendaylight.netconf.sal.restconf.impl.ControllerContext;
40 import org.opendaylight.restconf.common.context.InstanceIdentifierContext;
41 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
42 import org.osgi.framework.BundleContext;
43 import org.osgi.framework.ServiceReference;
44 import org.slf4j.Logger;
45 import org.slf4j.LoggerFactory;
46
47 import javax.ws.rs.core.UriBuilder;
48 import java.net.SocketException;
49 import java.net.URI;
50 import java.net.URISyntaxException;
51 import java.util.HashMap;
52 import java.util.List;
53 import java.util.Map;
54
55 import static java.lang.String.format;
56 import static org.apache.commons.lang3.StringUtils.join;
57 import static org.onap.ccsdk.sli.plugins.restapicall.HttpMethod.POST;
58 import static org.onap.ccsdk.sli.plugins.restapicall.HttpMethod.PUT;
59 import static org.onap.ccsdk.sli.plugins.restapicall.RestapiCallNode.parseParam;
60 import static org.onap.ccsdk.sli.plugins.restconfapicall.RestconfApiUtils.ATTEMPTS_MSG;
61 import static org.onap.ccsdk.sli.plugins.restconfapicall.RestconfApiUtils.COMMA;
62 import static org.onap.ccsdk.sli.plugins.restconfapicall.RestconfApiUtils.COMM_FAIL;
63 import static org.onap.ccsdk.sli.plugins.restconfapicall.RestconfApiUtils.HEADER;
64 import static org.onap.ccsdk.sli.plugins.restconfapicall.RestconfApiUtils.HTTP_REQ;
65 import static org.onap.ccsdk.sli.plugins.restconfapicall.RestconfApiUtils.HTTP_RES;
66 import static org.onap.ccsdk.sli.plugins.restconfapicall.RestconfApiUtils.MAX_RETRY_ERR;
67 import static org.onap.ccsdk.sli.plugins.restconfapicall.RestconfApiUtils.NO_MORE_RETRY;
68 import static org.onap.ccsdk.sli.plugins.restconfapicall.RestconfApiUtils.REQ_ERR;
69 import static org.onap.ccsdk.sli.plugins.restconfapicall.RestconfApiUtils.REST_API_URL;
70 import static org.onap.ccsdk.sli.plugins.restconfapicall.RestconfApiUtils.RES_CODE;
71 import static org.onap.ccsdk.sli.plugins.restconfapicall.RestconfApiUtils.RES_MSG;
72 import static org.onap.ccsdk.sli.plugins.restconfapicall.RestconfApiUtils.RES_PRE;
73 import static org.onap.ccsdk.sli.plugins.restconfapicall.RestconfApiUtils.RETRY_COUNT;
74 import static org.onap.ccsdk.sli.plugins.restconfapicall.RestconfApiUtils.RETRY_FAIL;
75 import static org.onap.ccsdk.sli.plugins.restconfapicall.RestconfApiUtils.UPDATED_URL;
76 import static org.onap.ccsdk.sli.plugins.restconfapicall.RestconfApiUtils.getSchemaCtxFromDir;
77 import static org.onap.ccsdk.sli.plugins.restconfapicall.RestconfApiUtils.getYangParameters;
78 import static org.onap.ccsdk.sli.plugins.restconfapicall.RestconfApiUtils.parseUrl;
79 import static org.onap.ccsdk.sli.plugins.yangserializers.dfserializer.DfListenerFactory.instance;
80 import static org.osgi.framework.FrameworkUtil.getBundle;
81
82 /**
83  * Representation of a plugin to enable RESTCONF based CRUD operations from DG.
84  */
85 public class RestconfApiCallNode implements SvcLogicJavaPlugin {
86
87     /**
88      * Logger for the restconf api call node class.
89      */
90     private static final Logger log = LoggerFactory.getLogger(
91             RestconfApiCallNode.class);
92
93     /**
94      * Creates an instance of restconf api call node.
95      */
96     public RestconfApiCallNode() {
97     }
98
99     /**
100      * Sends the restconf request using the parameters map and the memory
101      * context. And this method allows the directed graphs to interact with
102      * the restconf api call node
103      *
104      * @param paramMap parameters map
105      * @param ctx      service logic context
106      * @throws SvcLogicException when svc logic exception occurs
107      */
108     public void sendRequest(Map<String, String> paramMap, SvcLogicContext ctx)
109             throws SvcLogicException {
110         sendRequest(paramMap, ctx, 0);
111     }
112
113     /**
114      * Sends the restconf request using the parameters map and the memory
115      * context along with the retry count.
116      *
117      * @param paramMap   parameters map
118      * @param ctx        service logic context
119      * @param retryCount number of retry counts
120      * @throws SvcLogicException when svc logic exception occurs
121      */
122     public void sendRequest(Map<String, String> paramMap, SvcLogicContext ctx,
123                             Integer retryCount) throws SvcLogicException {
124         RestapiCallNode rest = new RestapiCallNode();
125         RetryPolicy retryPolicy = null;
126         HttpResponse r = new HttpResponse();
127         try {
128             YangParameters p = getYangParameters(paramMap);
129             if (p.partner != null) {
130                 retryPolicy = rest.getRetryPolicyStore()
131                         .getRetryPolicy(p.partner);
132             }
133
134             String pp = p.responsePrefix != null ? p.responsePrefix + '.' : "";
135             Map<String, String> props = new HashMap<>((Map)ctx.toProperties());
136             String uri = parseUrl(p.restapiUrl, p.httpMethod);
137             InstanceIdentifierContext<?> insIdCtx = getInsIdCtx(p, uri);
138
139             String req = null;
140             if (p.httpMethod == POST || p.httpMethod == PUT) {
141                 req = serializeRequest(props, p, uri, insIdCtx);
142             }
143             if (req == null && p.requestBody != null) {
144                 req = p.requestBody;
145             }
146
147             r = rest.sendHttpRequest(req, p);
148             if (p.returnRequestPayload && req != null) {
149                 ctx.setAttribute(pp + HTTP_REQ, req);
150             }
151
152             String response = getResponse(ctx, p, pp, r);
153             if (response != null) {
154                 Map<String, String> resProp = serializeResponse(
155                         p, uri, response, insIdCtx);
156                 for (Map.Entry<String, String> pro : resProp.entrySet()) {
157                     ctx.setAttribute(pro.getKey(), pro.getValue());
158                 }
159             }
160         } catch (SvcLogicException e) {
161             boolean shouldRetry = false;
162             if (e.getCause().getCause() instanceof SocketException) {
163                 shouldRetry = true;
164             }
165
166             log.error(REQ_ERR + e.getMessage(), e);
167             String prefix = parseParam(paramMap, RES_PRE, false, null);
168             if (retryPolicy == null || shouldRetry == false) {
169                 setFailureResponseStatus(ctx, prefix, e.getMessage(), r);
170             } else {
171                 if (retryCount == null) {
172                     retryCount = 0;
173                 }
174                 log.debug(format(ATTEMPTS_MSG, retryCount,
175                                  retryPolicy.getMaximumRetries()));
176                 try {
177                     retryCount = retryCount + 1;
178                     if (retryCount < retryPolicy.getMaximumRetries() + 1) {
179                         setRetryUri(paramMap, retryPolicy);
180                         log.debug(format(RETRY_COUNT, retryCount, retryPolicy
181                                 .getMaximumRetries()));
182                         sendRequest(paramMap, ctx, retryCount);
183                     } else {
184                         log.debug(MAX_RETRY_ERR);
185                         setFailureResponseStatus(ctx, prefix,
186                                                  e.getMessage(), r);
187                     }
188                 } catch (Exception ex) {
189                     log.error(NO_MORE_RETRY, ex);
190                     setFailureResponseStatus(ctx, prefix, RETRY_FAIL, r);
191                 }
192             }
193         }
194
195         if (r != null && r.code >= 300) {
196             throw new SvcLogicException(
197                     String.valueOf(r.code) + ": " + r.message);
198         }
199     }
200
201     /**
202      * Serializes the request message to JSON or XML from the properties.
203      *
204      * @param properties properties
205      * @param params     YANG parameters
206      * @param uri        URI
207      * @param insIdCtx   instance identifier context
208      * @return JSON or XML message to be sent
209      * @throws SvcLogicException when serializing the request fails
210      */
211      protected String serializeRequest(Map<String, String> properties,
212                                     YangParameters params, String uri,
213                                     InstanceIdentifierContext insIdCtx)
214              throws SvcLogicException {
215         PropertiesNodeSerializer propSer = new MdsalPropertiesNodeSerializer(
216                 insIdCtx.getSchemaNode(), insIdCtx.getSchemaContext(), uri);
217         DataFormatSerializerContext serCtx = new DataFormatSerializerContext(
218                 null, uri, null, propSer);
219         DataFormatSerializer ser = DfSerializerFactory.instance()
220                 .getSerializer(serCtx, params);
221          //TODO: Handling of XML annotations
222         return ser.encode(properties, null);
223     }
224
225     /**
226      * Serializes the response message from JSON or XML to the properties.
227      *
228      * @param params   YANG parameters
229      * @param uri      URI
230      * @param response response message
231      * @param insIdCtx instance identifier context
232      * @return response message as properties
233      * @throws SvcLogicException when serializing the response fails
234      */
235     protected Map<String, String> serializeResponse(YangParameters params,
236                                                   String uri, String response,
237                                                   InstanceIdentifierContext insIdCtx)
238             throws SvcLogicException {
239         PropertiesNodeSerializer propSer = new MdsalPropertiesNodeSerializer(
240                 insIdCtx.getSchemaNode(), insIdCtx.getSchemaContext(), uri);
241         SerializerHelper helper = new MdsalSerializerHelper(
242                 insIdCtx.getSchemaNode(), insIdCtx.getSchemaContext(), uri);
243         Listener listener = instance().getListener(helper, params);
244         DataFormatSerializerContext serCtx = new DataFormatSerializerContext(
245                 listener, uri, null, propSer);
246         DataFormatSerializer ser = DfSerializerFactory.instance()
247                 .getSerializer(serCtx, params);
248         return ser.decode(response);
249     }
250
251     /**
252      * Returns instance identifier context for a uri using the schema context.
253      *
254      * @param params YANG parameters
255      * @param uri    URI
256      * @return instance identifier context
257      * @throws SvcLogicException when getting schema context fails
258      */
259     private InstanceIdentifierContext<?> getInsIdCtx(YangParameters params,
260                                                      String uri)
261             throws SvcLogicException {
262         SchemaContext context = getSchemaContext(params);
263         ControllerContext contCtx = ControllerContext.getInstance();
264         contCtx.onGlobalContextUpdated(context);
265         return contCtx.toInstanceIdentifier(uri);
266     }
267
268     /**
269      * Returns the global schema context or schema context of particular YANG
270      * files present in a directory path.
271      *
272      * @param params YANG parameters
273      * @return schema context
274      * @throws SvcLogicException when schema context fetching fails
275      */
276     private SchemaContext getSchemaContext(YangParameters params)
277             throws SvcLogicException {
278         if (params.dirPath != null) {
279             return getSchemaCtxFromDir(params.dirPath);
280         }
281         BundleContext bc = getBundle(SchemaContext.class).getBundleContext();
282         SchemaContext schemaContext = null;
283         if (bc != null) {
284             ServiceReference reference = bc.getServiceReference(
285                     SchemaContext.class);
286             if (reference != null) {
287                 schemaContext = (SchemaContext) bc.getService(reference);
288             }
289         }
290         return schemaContext;
291     }
292
293     /**
294      * Returns the response message body of a http response message.
295      *
296      * @param ctx    svc logic context
297      * @param params parameters
298      * @param pre    prefix to be appended
299      * @param res    http response
300      * @return response message body
301      */
302     private String getResponse(SvcLogicContext ctx, YangParameters params,
303                                String pre, HttpResponse res) {
304         ctx.setAttribute(pre + RES_CODE, String.valueOf(res.code));
305         ctx.setAttribute(pre + RES_MSG, res.message);
306
307         if (params.dumpHeaders && res.headers != null) {
308             for (Map.Entry<String, List<String>> a : res.headers.entrySet()) {
309                 ctx.setAttribute(pre + HEADER + a.getKey(),
310                                  join(a.getValue(), COMMA));
311             }
312         }
313
314         if (res.body != null && res.body.trim().length() > 0) {
315             ctx.setAttribute(pre + HTTP_RES, res.body);
316             return res.body;
317         }
318         return null;
319     }
320
321     /**
322      * Sets the failure response status in the context memory.
323      *
324      * @param ctx    service logic context
325      * @param prefix prefix to be added
326      * @param errMsg error message
327      * @param res    http response
328      */
329     private void setFailureResponseStatus(SvcLogicContext ctx, String prefix,
330                                           String errMsg, HttpResponse res) {
331         res = new HttpResponse();
332         res.code = 500;
333         res.message = errMsg;
334         ctx.setAttribute(prefix + RES_CODE, String.valueOf(res.code));
335         ctx.setAttribute(prefix + RES_MSG, res.message);
336     }
337
338     /**
339      * Sets the retry URI to the param map from the retry policies different
340      * host.
341      *
342      * @param paramMap            parameter map
343      * @param retryPolicy         retry policy
344      * @throws URISyntaxException when new URI creation fails
345      * @throws RetryException     when retry policy cannot give another host
346      */
347     private void setRetryUri(Map<String, String> paramMap,
348                              RetryPolicy retryPolicy)
349             throws URISyntaxException, RetryException {
350         URI uri = new URI(paramMap.get(REST_API_URL));
351         String hostName = uri.getHost();
352         String retryString = retryPolicy.getNextHostName(uri.toString());
353
354         URI uriTwo = new URI(retryString);
355         URI retryUri = UriBuilder.fromUri(uri).host(uriTwo.getHost()).port(
356                 uriTwo.getPort()).scheme(uriTwo.getScheme()).build();
357
358         paramMap.put(REST_API_URL, retryUri.toString());
359         log.debug(UPDATED_URL + retryUri.toString());
360         log.debug(format(COMM_FAIL, hostName, retryString));
361     }
362 }