5b7011b81d23b1086131644768e5539dfb122728
[netconf.git] / restconf / restconf-nb / src / main / java / org / opendaylight / restconf / nb / rfc8040 / rests / services / impl / RestconfInvokeOperationsServiceImpl.java
1 /*
2  * Copyright (c) 2016 Cisco Systems, Inc. and others.  All rights reserved.
3  *
4  * This program and the accompanying materials are made available under the
5  * terms of the Eclipse Public License v1.0 which accompanies this distribution,
6  * and is available at http://www.eclipse.org/legal/epl-v10.html
7  */
8 package org.opendaylight.restconf.nb.rfc8040.rests.services.impl;
9
10 import static java.util.Objects.requireNonNull;
11
12 import com.google.common.annotations.VisibleForTesting;
13 import com.google.common.base.Throwables;
14 import com.google.common.util.concurrent.FutureCallback;
15 import com.google.common.util.concurrent.Futures;
16 import com.google.common.util.concurrent.ListenableFuture;
17 import com.google.common.util.concurrent.MoreExecutors;
18 import java.util.List;
19 import java.util.concurrent.ExecutionException;
20 import javax.ws.rs.Path;
21 import javax.ws.rs.WebApplicationException;
22 import javax.ws.rs.container.AsyncResponse;
23 import javax.ws.rs.core.Response.Status;
24 import javax.ws.rs.core.UriInfo;
25 import org.eclipse.jdt.annotation.NonNull;
26 import org.opendaylight.mdsal.dom.api.DOMMountPoint;
27 import org.opendaylight.mdsal.dom.api.DOMRpcException;
28 import org.opendaylight.mdsal.dom.api.DOMRpcResult;
29 import org.opendaylight.mdsal.dom.api.DOMRpcService;
30 import org.opendaylight.mdsal.dom.spi.DefaultDOMRpcResult;
31 import org.opendaylight.restconf.common.context.InstanceIdentifierContext;
32 import org.opendaylight.restconf.common.errors.RestconfDocumentedException;
33 import org.opendaylight.restconf.nb.rfc8040.legacy.NormalizedNodePayload;
34 import org.opendaylight.restconf.nb.rfc8040.rests.services.api.RestconfInvokeOperationsService;
35 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.md.sal.remote.rev140114.CreateDataChangeEventSubscriptionInput;
36 import org.opendaylight.yangtools.yang.common.ErrorTag;
37 import org.opendaylight.yangtools.yang.common.ErrorType;
38 import org.opendaylight.yangtools.yang.common.QName;
39 import org.opendaylight.yangtools.yang.common.QNameModule;
40 import org.opendaylight.yangtools.yang.common.RpcResultBuilder;
41 import org.opendaylight.yangtools.yang.common.YangConstants;
42 import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode;
43 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
44 import org.opendaylight.yangtools.yang.data.impl.schema.ImmutableNodes;
45 import org.opendaylight.yangtools.yang.model.api.EffectiveModelContext;
46 import org.opendaylight.yangtools.yang.model.api.SchemaNode;
47 import org.slf4j.Logger;
48 import org.slf4j.LoggerFactory;
49
50 /**
51  * Implementation of {@link RestconfInvokeOperationsService}.
52  *
53  */
54 @Path("/")
55 public class RestconfInvokeOperationsServiceImpl implements RestconfInvokeOperationsService {
56     private static final Logger LOG = LoggerFactory.getLogger(RestconfInvokeOperationsServiceImpl.class);
57
58     // FIXME: at some point we do not want to have this here, as this is only used for dispatch
59     private static final QNameModule SAL_REMOTE_NAMESPACE = CreateDataChangeEventSubscriptionInput.QNAME.getModule();
60
61     private final DOMRpcService rpcService;
62
63     public RestconfInvokeOperationsServiceImpl(final DOMRpcService rpcService) {
64         this.rpcService = requireNonNull(rpcService);
65     }
66
67     @Override
68     public void invokeRpc(final String identifier, final NormalizedNodePayload payload, final UriInfo uriInfo,
69             final AsyncResponse ar) {
70         final InstanceIdentifierContext context = payload.getInstanceIdentifierContext();
71         final EffectiveModelContext schemaContext = context.getSchemaContext();
72         final DOMMountPoint mountPoint = context.getMountPoint();
73         final SchemaNode schema = context.getSchemaNode();
74         final QName rpcName = schema.getQName();
75
76         final ListenableFuture<? extends DOMRpcResult> future;
77         if (mountPoint == null) {
78             // FIXME: this really should be a normal RPC invocation service which has its own interface with JAX-RS,
79             //        except ... we check 'identifier' for .contains() instead of exact RPC name!
80             if (SAL_REMOTE_NAMESPACE.equals(rpcName.getModule())) {
81                 if (identifier.contains("create-data-change-event-subscription")) {
82                     future = Futures.immediateFuture(
83                         CreateStreamUtil.createDataChangeNotifiStream(payload, schemaContext));
84                 } else {
85                     future = Futures.immediateFailedFuture(new RestconfDocumentedException("Unsupported operation",
86                         ErrorType.RPC, ErrorTag.OPERATION_NOT_SUPPORTED));
87                 }
88             } else {
89                 future = invokeRpc(payload.getData(), rpcName, rpcService);
90             }
91         } else {
92             future = invokeRpc(payload.getData(), rpcName, mountPoint);
93         }
94
95         Futures.addCallback(future, new FutureCallback<DOMRpcResult>() {
96             @Override
97             public void onSuccess(final DOMRpcResult response) {
98                 final var errors = response.getErrors();
99                 if (!errors.isEmpty()) {
100                     LOG.debug("RpcError message {}", response.getErrors());
101                     ar.resume(new RestconfDocumentedException("RPCerror message ", null, response.getErrors()));
102                     return;
103                 }
104
105                 final NormalizedNode resultData = response.getResult();
106                 if (resultData == null || ((ContainerNode) resultData).isEmpty()) {
107                     ar.resume(new WebApplicationException(Status.NO_CONTENT));
108                 } else {
109                     ar.resume(NormalizedNodePayload.of(context, resultData));
110                 }
111             }
112
113             @Override
114             public void onFailure(final Throwable failure) {
115                 ar.resume(failure);
116             }
117         }, MoreExecutors.directExecutor());
118     }
119
120     /**
121      * Invoking rpc via mount point.
122      *
123      * @param mountPoint mount point
124      * @param data input data
125      * @param rpc RPC type
126      * @return {@link DOMRpcResult}
127      */
128     @VisibleForTesting
129     static ListenableFuture<? extends DOMRpcResult> invokeRpc(final NormalizedNode data, final QName rpc,
130             final DOMMountPoint mountPoint) {
131         return invokeRpc(data, rpc, mountPoint.getService(DOMRpcService.class).orElseThrow(() -> {
132             final String errmsg = "RPC service is missing.";
133             LOG.debug(errmsg);
134             return new RestconfDocumentedException(errmsg);
135         }));
136     }
137
138     /**
139      * Invoke rpc.
140      *
141      * @param data input data
142      * @param rpc RPC type
143      * @param rpcService rpc service to invoke rpc
144      * @return {@link DOMRpcResult}
145      */
146     @VisibleForTesting
147     static ListenableFuture<? extends DOMRpcResult> invokeRpc(final NormalizedNode data, final QName rpc,
148             final DOMRpcService rpcService) {
149         return Futures.catching(rpcService.invokeRpc(rpc, nonnullInput(rpc, data)),
150             DOMRpcException.class,
151             cause -> new DefaultDOMRpcResult(List.of(RpcResultBuilder.newError(ErrorType.RPC, ErrorTag.OPERATION_FAILED,
152                 cause.getMessage()))),
153             MoreExecutors.directExecutor());
154     }
155
156     private static @NonNull NormalizedNode nonnullInput(final QName type, final NormalizedNode input) {
157         return input != null ? input
158                 : ImmutableNodes.containerNode(YangConstants.operationInputQName(type.getModule()));
159     }
160
161     @Deprecated
162     static <T> T checkedGet(final ListenableFuture<T> future) {
163         try {
164             return future.get();
165         } catch (InterruptedException e) {
166             throw new RestconfDocumentedException("Interrupted while waiting for result of invocation", e);
167         } catch (ExecutionException e) {
168             Throwables.throwIfInstanceOf(e.getCause(), RestconfDocumentedException.class);
169             throw new RestconfDocumentedException("Invocation failed", e);
170         }
171     }
172 }