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.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;
 
  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);
 
  95      * Sends the restconf request using the parameters map and the memory
 
  96      * context. And this method allows the directed graphs to interact with
 
  97      * the restconf api call node
 
  99      * @param paramMap parameters map
 
 100      * @param ctx      service logic context
 
 101      * @throws SvcLogicException when svc logic exception occurs
 
 103     public void sendRequest(Map<String, String> paramMap, SvcLogicContext ctx)
 
 104             throws SvcLogicException {
 
 105         sendRequest(paramMap, ctx, 0);
 
 109      * Sends the restconf request using the parameters map and the memory
 
 110      * context along with the retry count.
 
 112      * @param paramMap   parameters map
 
 113      * @param ctx        service logic context
 
 114      * @param retryCount number of retry counts
 
 115      * @throws SvcLogicException when svc logic exception occurs
 
 117     public void sendRequest(Map<String, String> paramMap, SvcLogicContext ctx,
 
 118                             Integer retryCount) throws SvcLogicException {
 
 119         RestapiCallNode rest = new RestapiCallNode();
 
 120         RetryPolicy retryPolicy = null;
 
 121         HttpResponse r = new HttpResponse();
 
 123             YangParameters p = getYangParameters(paramMap);
 
 124             if (p.partner != null) {
 
 125                 retryPolicy = rest.getRetryPolicyStore()
 
 126                         .getRetryPolicy(p.partner);
 
 129             String pp = p.responsePrefix != null ? p.responsePrefix + '.' : "";
 
 130             Map<String, String> props = new HashMap<>((Map)ctx.toProperties());
 
 131             String uri = parseUrl(p.restapiUrl, p.httpMethod);
 
 132             InstanceIdentifierContext<?> insIdCtx = getInsIdCtx(p, uri);
 
 135             if (p.httpMethod == POST || p.httpMethod == PUT) {
 
 136                 req = serializeRequest(props, p, uri, insIdCtx);
 
 138             if (req == null && p.requestBody != null) {
 
 142             r = rest.sendHttpRequest(req, p);
 
 143             if (p.returnRequestPayload && req != null) {
 
 144                 ctx.setAttribute(pp + HTTP_REQ, req);
 
 147             String response = getResponse(ctx, p, pp, r);
 
 148             if (response != null) {
 
 149                 Map<String, String> resProp = serializeResponse(
 
 150                         p, uri, response, insIdCtx);
 
 151                 for (Map.Entry<String, String> pro : resProp.entrySet()) {
 
 152                     ctx.setAttribute(pro.getKey(), pro.getValue());
 
 155         } catch (SvcLogicException e) {
 
 156             boolean shouldRetry = false;
 
 157             if (e.getCause().getCause() instanceof SocketException) {
 
 161             log.error(REQ_ERR + e.getMessage(), e);
 
 162             String prefix = parseParam(paramMap, RES_PRE, false, null);
 
 163             if (retryPolicy == null || shouldRetry == false) {
 
 164                 setFailureResponseStatus(ctx, prefix, e.getMessage(), r);
 
 166                 if (retryCount == null) {
 
 169                 log.debug(format(ATTEMPTS_MSG, retryCount,
 
 170                                  retryPolicy.getMaximumRetries()));
 
 172                     retryCount = retryCount + 1;
 
 173                     if (retryCount < retryPolicy.getMaximumRetries() + 1) {
 
 174                         setRetryUri(paramMap, retryPolicy);
 
 175                         log.debug(format(RETRY_COUNT, retryCount, retryPolicy
 
 176                                 .getMaximumRetries()));
 
 177                         sendRequest(paramMap, ctx, retryCount);
 
 179                         log.debug(MAX_RETRY_ERR);
 
 180                         setFailureResponseStatus(ctx, prefix,
 
 183                 } catch (Exception ex) {
 
 184                     log.error(NO_MORE_RETRY, ex);
 
 185                     setFailureResponseStatus(ctx, prefix, RETRY_FAIL, r);
 
 190         if (r != null && r.code >= 300) {
 
 191             throw new SvcLogicException(
 
 192                     String.valueOf(r.code) + ": " + r.message);
 
 197      * Serializes the request message to JSON or XML from the properties.
 
 199      * @param properties properties
 
 200      * @param params     YANG parameters
 
 202      * @param insIdCtx   instance identifier context
 
 203      * @return JSON or XML message to be sent
 
 204      * @throws SvcLogicException when serializing the request fails
 
 206      protected String serializeRequest(Map<String, String> properties,
 
 207                                     YangParameters params, String uri,
 
 208                                     InstanceIdentifierContext insIdCtx)
 
 209              throws SvcLogicException {
 
 210         PropertiesNodeSerializer propSer = new MdsalPropertiesNodeSerializer(
 
 211                 insIdCtx.getSchemaNode(), insIdCtx.getSchemaContext(), uri);
 
 212         DataFormatSerializerContext serCtx = new DataFormatSerializerContext(
 
 213                 null, uri, null, propSer);
 
 214         DataFormatSerializer ser = DfSerializerFactory.instance()
 
 215                 .getSerializer(serCtx, params);
 
 216          //TODO: Handling of XML annotations
 
 217         return ser.encode(properties, null);
 
 221      * Serializes the response message from JSON or XML to the properties.
 
 223      * @param params   YANG parameters
 
 225      * @param response response message
 
 226      * @param insIdCtx instance identifier context
 
 227      * @return response message as properties
 
 228      * @throws SvcLogicException when serializing the response fails
 
 230     protected Map<String, String> serializeResponse(YangParameters params,
 
 231                                                   String uri, String response,
 
 232                                                   InstanceIdentifierContext insIdCtx)
 
 233             throws SvcLogicException {
 
 234         PropertiesNodeSerializer propSer = new MdsalPropertiesNodeSerializer(
 
 235                 insIdCtx.getSchemaNode(), insIdCtx.getSchemaContext(), uri);
 
 236         SerializerHelper helper = new MdsalSerializerHelper(
 
 237                 insIdCtx.getSchemaNode(), insIdCtx.getSchemaContext(), uri);
 
 238         Listener listener = instance().getListener(helper, params);
 
 239         DataFormatSerializerContext serCtx = new DataFormatSerializerContext(
 
 240                 listener, uri, null, propSer);
 
 241         DataFormatSerializer ser = DfSerializerFactory.instance()
 
 242                 .getSerializer(serCtx, params);
 
 243         return ser.decode(response);
 
 247      * Returns instance identifier context for a uri using the schema context.
 
 249      * @param params YANG parameters
 
 251      * @return instance identifier context
 
 252      * @throws SvcLogicException when getting schema context fails
 
 254     private InstanceIdentifierContext<?> getInsIdCtx(YangParameters params,
 
 256             throws SvcLogicException {
 
 257         SchemaContext context = getSchemaContext(params);
 
 258         ControllerContext contCtx = ControllerContext.getInstance();
 
 259         contCtx.onGlobalContextUpdated(context);
 
 260         return contCtx.toInstanceIdentifier(uri);
 
 264      * Returns the global schema context or schema context of particular YANG
 
 265      * files present in a directory path.
 
 267      * @param params YANG parameters
 
 268      * @return schema context
 
 269      * @throws SvcLogicException when schema context fetching fails
 
 271     private SchemaContext getSchemaContext(YangParameters params)
 
 272             throws SvcLogicException {
 
 273         if (params.dirPath != null) {
 
 274             return getSchemaCtxFromDir(params.dirPath);
 
 276         BundleContext bc = getBundle(SchemaContext.class).getBundleContext();
 
 277         SchemaContext schemaContext = null;
 
 279             ServiceReference reference = bc.getServiceReference(
 
 280                     SchemaContext.class);
 
 281             if (reference != null) {
 
 282                 schemaContext = (SchemaContext) bc.getService(reference);
 
 285         return schemaContext;
 
 289      * Returns the response message body of a http response message.
 
 291      * @param ctx    svc logic context
 
 292      * @param params parameters
 
 293      * @param pre    prefix to be appended
 
 294      * @param res    http response
 
 295      * @return response message body
 
 297     private String getResponse(SvcLogicContext ctx, YangParameters params,
 
 298                                String pre, HttpResponse res) {
 
 299         ctx.setAttribute(pre + RES_CODE, String.valueOf(res.code));
 
 300         ctx.setAttribute(pre + RES_MSG, res.message);
 
 302         if (params.dumpHeaders && res.headers != null) {
 
 303             for (Map.Entry<String, List<String>> a : res.headers.entrySet()) {
 
 304                 ctx.setAttribute(pre + HEADER + a.getKey(),
 
 305                                  join(a.getValue(), COMMA));
 
 309         if (res.body != null && res.body.trim().length() > 0) {
 
 310             ctx.setAttribute(pre + HTTP_RES, res.body);
 
 317      * Sets the failure response status in the context memory.
 
 319      * @param ctx    service logic context
 
 320      * @param prefix prefix to be added
 
 321      * @param errMsg error message
 
 322      * @param res    http response
 
 324     private void setFailureResponseStatus(SvcLogicContext ctx, String prefix,
 
 325                                           String errMsg, HttpResponse res) {
 
 326         res = new HttpResponse();
 
 328         res.message = errMsg;
 
 329         ctx.setAttribute(prefix + RES_CODE, String.valueOf(res.code));
 
 330         ctx.setAttribute(prefix + RES_MSG, res.message);
 
 334      * Sets the retry URI to the param map from the retry policies different
 
 337      * @param paramMap            parameter map
 
 338      * @param retryPolicy         retry policy
 
 339      * @throws URISyntaxException when new URI creation fails
 
 340      * @throws RetryException     when retry policy cannot give another host
 
 342     private void setRetryUri(Map<String, String> paramMap,
 
 343                              RetryPolicy retryPolicy)
 
 344             throws URISyntaxException, RetryException {
 
 345         URI uri = new URI(paramMap.get(REST_API_URL));
 
 346         String hostName = uri.getHost();
 
 347         String retryString = retryPolicy.getNextHostName(uri.toString());
 
 349         URI uriTwo = new URI(retryString);
 
 350         URI retryUri = UriBuilder.fromUri(uri).host(uriTwo.getHost()).port(
 
 351                 uriTwo.getPort()).scheme(uriTwo.getScheme()).build();
 
 353         paramMap.put(REST_API_URL, retryUri.toString());
 
 354         log.debug(UPDATED_URL + retryUri.toString());
 
 355         log.debug(format(COMM_FAIL, hostName, retryString));