e8b28f32521fd0866b34bc10381e30f6f9b6a088
[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.DOMMountPointService;
28 import org.opendaylight.mdsal.dom.api.DOMRpcException;
29 import org.opendaylight.mdsal.dom.api.DOMRpcResult;
30 import org.opendaylight.mdsal.dom.api.DOMRpcService;
31 import org.opendaylight.mdsal.dom.spi.DefaultDOMRpcResult;
32 import org.opendaylight.restconf.common.context.InstanceIdentifierContext;
33 import org.opendaylight.restconf.common.errors.RestconfDocumentedException;
34 import org.opendaylight.restconf.nb.rfc8040.legacy.NormalizedNodePayload;
35 import org.opendaylight.restconf.nb.rfc8040.rests.services.api.RestconfInvokeOperationsService;
36 import org.opendaylight.restconf.nb.rfc8040.streams.StreamsConfiguration;
37 import org.opendaylight.yang.gen.v1.urn.opendaylight.device.notification.rev221106.SubscribeDeviceNotificationInput;
38 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.md.sal.remote.rev140114.CreateDataChangeEventSubscriptionInput;
39 import org.opendaylight.yangtools.yang.common.ErrorTag;
40 import org.opendaylight.yangtools.yang.common.ErrorType;
41 import org.opendaylight.yangtools.yang.common.QName;
42 import org.opendaylight.yangtools.yang.common.QNameModule;
43 import org.opendaylight.yangtools.yang.common.RpcResultBuilder;
44 import org.opendaylight.yangtools.yang.common.YangConstants;
45 import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode;
46 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
47 import org.opendaylight.yangtools.yang.data.impl.schema.ImmutableNodes;
48 import org.opendaylight.yangtools.yang.model.api.EffectiveModelContext;
49 import org.opendaylight.yangtools.yang.model.api.SchemaNode;
50 import org.slf4j.Logger;
51 import org.slf4j.LoggerFactory;
52
53 /**
54  * Implementation of {@link RestconfInvokeOperationsService}.
55  *
56  */
57 @Path("/")
58 public class RestconfInvokeOperationsServiceImpl implements RestconfInvokeOperationsService {
59     private static final Logger LOG = LoggerFactory.getLogger(RestconfInvokeOperationsServiceImpl.class);
60
61     // FIXME: at some point we do not want to have this here, as this is only used for dispatch
62     private static final QNameModule SAL_REMOTE_NAMESPACE = CreateDataChangeEventSubscriptionInput.QNAME.getModule();
63     private static final QNameModule DEVICE_NOTIFICATION_NAMESPACE = SubscribeDeviceNotificationInput.QNAME.getModule();
64
65     private final DOMRpcService rpcService;
66     private final DOMMountPointService mountPointService;
67     private final SubscribeToStreamUtil streamUtils;
68
69     public RestconfInvokeOperationsServiceImpl(final DOMRpcService rpcService,
70             final DOMMountPointService mountPointService, final StreamsConfiguration configuration) {
71         this.rpcService = requireNonNull(rpcService);
72         this.mountPointService = requireNonNull(mountPointService);
73         streamUtils = configuration.useSSE() ? SubscribeToStreamUtil.serverSentEvents()
74             : SubscribeToStreamUtil.webSockets();
75     }
76
77     @Override
78     public void invokeRpc(final String identifier, final NormalizedNodePayload payload, final UriInfo uriInfo,
79             final AsyncResponse ar) {
80         final InstanceIdentifierContext context = payload.getInstanceIdentifierContext();
81         final EffectiveModelContext schemaContext = context.getSchemaContext();
82         final DOMMountPoint mountPoint = context.getMountPoint();
83         final SchemaNode schema = context.getSchemaNode();
84         final QName rpcName = schema.getQName();
85
86         final ListenableFuture<? extends DOMRpcResult> future;
87         if (mountPoint == null) {
88             // FIXME: this really should be a normal RPC invocation service which has its own interface with JAX-RS,
89             //        except ... we check 'identifier' for .contains() instead of exact RPC name!
90             if (SAL_REMOTE_NAMESPACE.equals(rpcName.getModule())) {
91                 if (identifier.contains("create-data-change-event-subscription")) {
92                     future = Futures.immediateFuture(
93                         CreateStreamUtil.createDataChangeNotifiStream(payload, schemaContext));
94                 } else {
95                     future = Futures.immediateFailedFuture(new RestconfDocumentedException("Unsupported operation",
96                         ErrorType.RPC, ErrorTag.OPERATION_NOT_SUPPORTED));
97                 }
98             } else if (DEVICE_NOTIFICATION_NAMESPACE.equals(rpcName.getModule())) {
99                 // FIXME: this should be a match on RPC QName
100                 final String baseUrl = streamUtils.prepareUriByStreamName(uriInfo, "").toString();
101                 future = Futures.immediateFuture(CreateStreamUtil.createDeviceNotificationListener(baseUrl, payload,
102                     streamUtils, mountPointService));
103             } else {
104                 future = invokeRpc((ContainerNode)payload.getData(), rpcName, rpcService);
105             }
106         } else {
107             future = invokeRpc(payload.getData(), rpcName, mountPoint);
108         }
109
110         Futures.addCallback(future, new FutureCallback<DOMRpcResult>() {
111             @Override
112             public void onSuccess(final DOMRpcResult response) {
113                 final var errors = response.getErrors();
114                 if (!errors.isEmpty()) {
115                     LOG.debug("RpcError message {}", response.getErrors());
116                     ar.resume(new RestconfDocumentedException("RPCerror message ", null, response.getErrors()));
117                     return;
118                 }
119
120                 final NormalizedNode resultData = response.getResult();
121                 if (resultData == null || ((ContainerNode) resultData).isEmpty()) {
122                     ar.resume(new WebApplicationException(Status.NO_CONTENT));
123                 } else {
124                     ar.resume(NormalizedNodePayload.of(context, resultData));
125                 }
126             }
127
128             @Override
129             public void onFailure(final Throwable failure) {
130                 ar.resume(failure);
131             }
132         }, MoreExecutors.directExecutor());
133     }
134
135     /**
136      * Invoking rpc via mount point.
137      *
138      * @param mountPoint mount point
139      * @param data input data
140      * @param rpc RPC type
141      * @return {@link DOMRpcResult}
142      */
143     @VisibleForTesting
144     static ListenableFuture<? extends DOMRpcResult> invokeRpc(final NormalizedNode data, final QName rpc,
145             final DOMMountPoint mountPoint) {
146         return invokeRpc((ContainerNode) data, rpc, mountPoint.getService(DOMRpcService.class).orElseThrow(() -> {
147             final String errmsg = "RPC service is missing.";
148             LOG.debug(errmsg);
149             return new RestconfDocumentedException(errmsg);
150         }));
151     }
152
153     /**
154      * Invoke rpc.
155      *
156      * @param data input data
157      * @param rpc RPC type
158      * @param rpcService rpc service to invoke rpc
159      * @return {@link DOMRpcResult}
160      */
161     @VisibleForTesting
162     static ListenableFuture<? extends DOMRpcResult> invokeRpc(final ContainerNode data, final QName rpc,
163             final DOMRpcService rpcService) {
164         return Futures.catching(rpcService.invokeRpc(rpc, nonnullInput(rpc, data)),
165             DOMRpcException.class,
166             cause -> new DefaultDOMRpcResult(List.of(RpcResultBuilder.newError(ErrorType.RPC, ErrorTag.OPERATION_FAILED,
167                 cause.getMessage()))),
168             MoreExecutors.directExecutor());
169     }
170
171     private static @NonNull ContainerNode nonnullInput(final QName type, final ContainerNode input) {
172         return input != null ? input
173                 : ImmutableNodes.containerNode(YangConstants.operationInputQName(type.getModule()));
174     }
175
176     @Deprecated
177     static <T> T checkedGet(final ListenableFuture<T> future) {
178         try {
179             return future.get();
180         } catch (InterruptedException e) {
181             throw new RestconfDocumentedException("Interrupted while waiting for result of invocation", e);
182         } catch (ExecutionException e) {
183             Throwables.throwIfInstanceOf(e.getCause(), RestconfDocumentedException.class);
184             throw new RestconfDocumentedException("Invocation failed", e);
185         }
186     }
187 }