2  * ============LICENSE_START=======================================================
 
   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
 
  11  *      http://www.apache.org/licenses/LICENSE-2.0
 
  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=========================================================
 
  21 package org.onap.ccsdk.sli.plugins.restconfapicall;
 
  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.restconf.common.context.InstanceIdentifierContext;
 
  40 import org.opendaylight.restconf.nb.rfc8040.utils.parser.ParserIdentifier;
 
  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;
 
  47 import javax.ws.rs.core.UriBuilder;
 
  48 import java.net.SocketException;
 
  50 import java.net.URISyntaxException;
 
  51 import java.util.HashMap;
 
  52 import java.util.List;
 
  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;
 
  83  * Representation of a plugin to enable RESTCONF based CRUD operations from DG.
 
  85 public class RestconfApiCallNode implements SvcLogicJavaPlugin {
 
  88      * Logger for the restconf api call node class.
 
  90     private static final Logger log = LoggerFactory.getLogger(
 
  91             RestconfApiCallNode.class);
 
  94      * Rest api call node service instance
 
  96     private RestapiCallNode restapiCallNode;
 
  99      * Creates an instance of restconf api call node with restapi call node.
 
 101      * @param r restapi call node
 
 103     public RestconfApiCallNode(RestapiCallNode r) {
 
 104         this.restapiCallNode = r;
 
 108      * Returns the restapi call node instance.
 
 111     public RestapiCallNode getRestapiCallNode() {
 
 112         return restapiCallNode;
 
 116      * Sends the restconf request using the parameters map and the memory
 
 117      * context. And this method allows the directed graphs to interact with
 
 118      * the restconf api call node
 
 120      * @param paramMap parameters map
 
 121      * @param ctx      service logic context
 
 122      * @throws SvcLogicException when svc logic exception occurs
 
 124     public void sendRequest(Map<String, String> paramMap, SvcLogicContext ctx)
 
 125             throws SvcLogicException {
 
 126         sendRequest(paramMap, ctx, 0);
 
 130      * Sends the restconf request using the parameters map and the memory
 
 131      * context along with the retry count.
 
 133      * @param paramMap   parameters map
 
 134      * @param ctx        service logic context
 
 135      * @param retryCount number of retry counts
 
 136      * @throws SvcLogicException when svc logic exception occurs
 
 138     public void sendRequest(Map<String, String> paramMap, SvcLogicContext ctx,
 
 139                             Integer retryCount) throws SvcLogicException {
 
 140         RestapiCallNode rest = getRestapiCallNode();
 
 141         RetryPolicy retryPolicy = null;
 
 142         HttpResponse r = new HttpResponse();
 
 144             YangParameters p = getYangParameters(paramMap);
 
 145             if (p.partner != null) {
 
 146                 retryPolicy = rest.getRetryPolicyStore()
 
 147                         .getRetryPolicy(p.partner);
 
 150             String pp = p.responsePrefix != null ? p.responsePrefix + '.' : "";
 
 151             Map<String, String> props = new HashMap<>((Map)ctx.toProperties());
 
 152             String uri = parseUrl(p.restapiUrl, p.httpMethod);
 
 153             InstanceIdentifierContext<?> insIdCtx = getInsIdCtx(p, uri);
 
 156             if (p.httpMethod == POST || p.httpMethod == PUT) {
 
 157                 req = serializeRequest(props, p, uri, insIdCtx);
 
 159             if (req == null && p.requestBody != null) {
 
 163             r = rest.sendHttpRequest(req, p);
 
 164             if (p.returnRequestPayload && req != null) {
 
 165                 ctx.setAttribute(pp + HTTP_REQ, req);
 
 168             String response = getResponse(ctx, p, pp, r);
 
 169             if (response != null) {
 
 170                 Map<String, String> resProp = serializeResponse(
 
 171                         p, uri, response, insIdCtx);
 
 172                 for (Map.Entry<String, String> pro : resProp.entrySet()) {
 
 173                     ctx.setAttribute(pro.getKey(), pro.getValue());
 
 176         } catch (SvcLogicException e) {
 
 177             boolean shouldRetry = false;
 
 178             if (e.getCause().getCause() instanceof SocketException) {
 
 182             log.error(REQ_ERR + e.getMessage(), e);
 
 183             String prefix = parseParam(paramMap, RES_PRE, false, null);
 
 184             if (retryPolicy == null || shouldRetry == false) {
 
 185                 setFailureResponseStatus(ctx, prefix, e.getMessage(), r);
 
 187                 if (retryCount == null) {
 
 190                 log.debug(format(ATTEMPTS_MSG, retryCount,
 
 191                                  retryPolicy.getMaximumRetries()));
 
 193                     retryCount = retryCount + 1;
 
 194                     if (retryCount < retryPolicy.getMaximumRetries() + 1) {
 
 195                         setRetryUri(paramMap, retryPolicy);
 
 196                         log.debug(format(RETRY_COUNT, retryCount, retryPolicy
 
 197                                 .getMaximumRetries()));
 
 198                         sendRequest(paramMap, ctx, retryCount);
 
 200                         log.debug(MAX_RETRY_ERR);
 
 201                         setFailureResponseStatus(ctx, prefix,
 
 204                 } catch (Exception ex) {
 
 205                     log.error(NO_MORE_RETRY, ex);
 
 206                     setFailureResponseStatus(ctx, prefix, RETRY_FAIL, r);
 
 211         if (r != null && r.code >= 300) {
 
 212             throw new SvcLogicException(
 
 213                     String.valueOf(r.code) + ": " + r.message);
 
 218      * Serializes the request message to JSON or XML from the properties.
 
 220      * @param properties properties
 
 221      * @param params     YANG parameters
 
 223      * @param insIdCtx   instance identifier context
 
 224      * @return JSON or XML message to be sent
 
 225      * @throws SvcLogicException when serializing the request fails
 
 227      public String serializeRequest(Map<String, String> properties,
 
 228                                     YangParameters params, String uri,
 
 229                                     InstanceIdentifierContext insIdCtx)
 
 230              throws SvcLogicException {
 
 231         PropertiesNodeSerializer propSer = new MdsalPropertiesNodeSerializer(
 
 232                 insIdCtx.getSchemaNode(), insIdCtx.getSchemaContext(), uri);
 
 233         DataFormatSerializerContext serCtx = new DataFormatSerializerContext(
 
 234                 null, uri, null, propSer);
 
 235         DataFormatSerializer ser = DfSerializerFactory.instance()
 
 236                 .getSerializer(serCtx, params);
 
 237          //TODO: Handling of XML annotations
 
 238         return ser.encode(properties, null);
 
 242      * Serializes the response message from JSON or XML to the properties.
 
 244      * @param params   YANG parameters
 
 246      * @param response response message
 
 247      * @param insIdCtx instance identifier context
 
 248      * @return response message as properties
 
 249      * @throws SvcLogicException when serializing the response fails
 
 251     public Map<String, String> serializeResponse(YangParameters params,
 
 252                                                  String uri, String response,
 
 253                                                  InstanceIdentifierContext insIdCtx)
 
 254             throws SvcLogicException {
 
 255         PropertiesNodeSerializer propSer = new MdsalPropertiesNodeSerializer(
 
 256                 insIdCtx.getSchemaNode(), insIdCtx.getSchemaContext(), uri);
 
 257         SerializerHelper helper = new MdsalSerializerHelper(
 
 258                 insIdCtx.getSchemaNode(), insIdCtx.getSchemaContext(), uri);
 
 259         Listener listener = instance().getListener(helper, params);
 
 260         DataFormatSerializerContext serCtx = new DataFormatSerializerContext(
 
 261                 listener, uri, null, propSer);
 
 262         DataFormatSerializer ser = DfSerializerFactory.instance()
 
 263                 .getSerializer(serCtx, params);
 
 264         return ser.decode(response);
 
 268      * Returns instance identifier context for a uri using the schema context.
 
 270      * @param params YANG parameters
 
 272      * @return instance identifier context
 
 273      * @throws SvcLogicException when getting schema context fails
 
 275     private InstanceIdentifierContext<?> getInsIdCtx(YangParameters params,
 
 277             throws SvcLogicException {
 
 278         SchemaContext context = getSchemaContext(params);
 
 279         return ParserIdentifier.toInstanceIdentifier(uri, context, null);
 
 283      * Returns the global schema context or schema context of particular YANG
 
 284      * files present in a directory path.
 
 286      * @param params YANG parameters
 
 287      * @return schema context
 
 288      * @throws SvcLogicException when schema context fetching fails
 
 290     private SchemaContext getSchemaContext(YangParameters params)
 
 291             throws SvcLogicException {
 
 292         if (params.dirPath != null) {
 
 293             return getSchemaCtxFromDir(params.dirPath);
 
 295         BundleContext bc = getBundle(SchemaContext.class).getBundleContext();
 
 296         SchemaContext schemaContext = null;
 
 298             ServiceReference reference = bc.getServiceReference(
 
 299                     SchemaContext.class);
 
 300             if (reference != null) {
 
 301                 schemaContext = (SchemaContext) bc.getService(reference);
 
 304         return schemaContext;
 
 308      * Returns the response message body of a http response message.
 
 310      * @param ctx    svc logic context
 
 311      * @param params parameters
 
 312      * @param pre    prefix to be appended
 
 313      * @param res    http response
 
 314      * @return response message body
 
 316     public String getResponse(SvcLogicContext ctx, YangParameters params,
 
 317                                String pre, HttpResponse res) {
 
 318         ctx.setAttribute(pre + RES_CODE, String.valueOf(res.code));
 
 319         ctx.setAttribute(pre + RES_MSG, res.message);
 
 321         if (params.dumpHeaders && res.headers != null) {
 
 322             for (Map.Entry<String, List<String>> a : res.headers.entrySet()) {
 
 323                 ctx.setAttribute(pre + HEADER + a.getKey(),
 
 324                                  join(a.getValue(), COMMA));
 
 328         if (res.body != null && res.body.trim().length() > 0) {
 
 329             ctx.setAttribute(pre + HTTP_RES, res.body);
 
 336      * Sets the failure response status in the context memory.
 
 338      * @param ctx    service logic context
 
 339      * @param prefix prefix to be added
 
 340      * @param errMsg error message
 
 341      * @param res    http response
 
 343     private void setFailureResponseStatus(SvcLogicContext ctx, String prefix,
 
 344                                           String errMsg, HttpResponse res) {
 
 345         res = new HttpResponse();
 
 347         res.message = errMsg;
 
 348         ctx.setAttribute(prefix + RES_CODE, String.valueOf(res.code));
 
 349         ctx.setAttribute(prefix + RES_MSG, res.message);
 
 353      * Sets the retry URI to the param map from the retry policies different
 
 356      * @param paramMap            parameter map
 
 357      * @param retryPolicy         retry policy
 
 358      * @throws URISyntaxException when new URI creation fails
 
 359      * @throws RetryException     when retry policy cannot give another host
 
 361     private void setRetryUri(Map<String, String> paramMap,
 
 362                              RetryPolicy retryPolicy)
 
 363             throws URISyntaxException, RetryException {
 
 364         URI uri = new URI(paramMap.get(REST_API_URL));
 
 365         String hostName = uri.getHost();
 
 366         String retryString = retryPolicy.getNextHostName(uri.toString());
 
 368         URI uriTwo = new URI(retryString);
 
 369         URI retryUri = UriBuilder.fromUri(uri).host(uriTwo.getHost()).port(
 
 370                 uriTwo.getPort()).scheme(uriTwo.getScheme()).build();
 
 372         paramMap.put(REST_API_URL, retryUri.toString());
 
 373         log.debug(UPDATED_URL + retryUri.toString());
 
 374         log.debug(format(COMM_FAIL, hostName, retryString));