f2c70e8e268ea0f89fb03c986413b737ed0898da
[netconf.git] / restconf / restconf-nb-rfc8040 / 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.collect.ImmutableList;
15 import com.google.common.util.concurrent.FutureCallback;
16 import com.google.common.util.concurrent.Futures;
17 import com.google.common.util.concurrent.ListenableFuture;
18 import com.google.common.util.concurrent.MoreExecutors;
19 import java.util.Optional;
20 import java.util.concurrent.ExecutionException;
21 import javax.ws.rs.Path;
22 import javax.ws.rs.WebApplicationException;
23 import javax.ws.rs.container.AsyncResponse;
24 import javax.ws.rs.core.Response.Status;
25 import javax.ws.rs.core.UriInfo;
26 import org.eclipse.jdt.annotation.NonNull;
27 import org.opendaylight.mdsal.dom.api.DOMMountPoint;
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.api.DOMSchemaService;
32 import org.opendaylight.mdsal.dom.spi.DefaultDOMRpcResult;
33 import org.opendaylight.restconf.common.context.InstanceIdentifierContext;
34 import org.opendaylight.restconf.common.context.NormalizedNodeContext;
35 import org.opendaylight.restconf.common.errors.RestconfDocumentedException;
36 import org.opendaylight.restconf.nb.rfc8040.handlers.SchemaContextHandler;
37 import org.opendaylight.restconf.nb.rfc8040.legacy.NormalizedNodePayload;
38 import org.opendaylight.restconf.nb.rfc8040.rests.services.api.RestconfInvokeOperationsService;
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.RpcError;
43 import org.opendaylight.yangtools.yang.common.RpcResultBuilder;
44 import org.opendaylight.yangtools.yang.common.XMLNamespace;
45 import org.opendaylight.yangtools.yang.common.YangConstants;
46 import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode;
47 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
48 import org.opendaylight.yangtools.yang.data.impl.schema.ImmutableNodes;
49 import org.opendaylight.yangtools.yang.model.api.EffectiveModelContext;
50 import org.opendaylight.yangtools.yang.model.api.RpcDefinition;
51 import org.opendaylight.yangtools.yang.model.api.SchemaNode;
52 import org.slf4j.Logger;
53 import org.slf4j.LoggerFactory;
54
55 /**
56  * Implementation of {@link RestconfInvokeOperationsService}.
57  *
58  */
59 @Path("/")
60 public class RestconfInvokeOperationsServiceImpl implements RestconfInvokeOperationsService {
61     private static final Logger LOG = LoggerFactory.getLogger(RestconfInvokeOperationsServiceImpl.class);
62
63     // FIXME: at some point we do not want to have this here
64     private static final XMLNamespace SAL_REMOTE_NAMESPACE =
65         XMLNamespace.of("urn:opendaylight:params:xml:ns:yang:controller:md:sal:remote");
66
67     private final DOMRpcService rpcService;
68     private final SchemaContextHandler schemaContextHandler;
69
70     public RestconfInvokeOperationsServiceImpl(final DOMRpcService rpcService,
71             final SchemaContextHandler schemaContextHandler) {
72         this.rpcService = requireNonNull(rpcService);
73         this.schemaContextHandler = requireNonNull(schemaContextHandler);
74     }
75
76     @Override
77     public void invokeRpc(final String identifier, final NormalizedNodePayload payload, final UriInfo uriInfo,
78             final AsyncResponse ar) {
79         final SchemaNode schema = payload.getInstanceIdentifierContext().getSchemaNode();
80         final QName rpcName = schema.getQName();
81         final DOMMountPoint mountPoint = payload.getInstanceIdentifierContext().getMountPoint();
82
83         final ListenableFuture<? extends DOMRpcResult> future;
84         final EffectiveModelContext schemaContextRef;
85         if (mountPoint == null) {
86             schemaContextRef = schemaContextHandler.get();
87
88             // FIXME: this really should be a normal RPC invocation service which has its own interface with JAX-RS
89             if (SAL_REMOTE_NAMESPACE.equals(rpcName.getNamespace())) {
90                 if (identifier.contains("create-data-change-event-subscription")) {
91                     future = Futures.immediateFuture(
92                         CreateStreamUtil.createDataChangeNotifiStream(payload, schemaContextRef));
93                 } else {
94                     future = Futures.immediateFailedFuture(new RestconfDocumentedException("Unsupported operation",
95                         ErrorType.RPC, ErrorTag.OPERATION_NOT_SUPPORTED));
96                 }
97             } else {
98                 future = invokeRpc(payload.getData(), rpcName, rpcService);
99             }
100         } else {
101             schemaContextRef = modelContext(mountPoint);
102             future = invokeRpc(payload.getData(), rpcName, mountPoint);
103         }
104
105         Futures.addCallback(future, new FutureCallback<DOMRpcResult>() {
106             @Override
107             public void onSuccess(final DOMRpcResult response) {
108                 final var errors = response.getErrors();
109                 if (!errors.isEmpty()) {
110                     LOG.debug("RpcError message {}", response.getErrors());
111                     ar.resume(new RestconfDocumentedException("RPCerror message ", null, response.getErrors()));
112                     return;
113                 }
114
115                 final NormalizedNode resultData = response.getResult();
116                 if (resultData == null || ((ContainerNode) resultData).isEmpty()) {
117                     ar.resume(new WebApplicationException(Status.NO_CONTENT));
118                 } else {
119                     ar.resume(new NormalizedNodeContext(new InstanceIdentifierContext<>(null, (RpcDefinition) schema,
120                         mountPoint, schemaContextRef), resultData));
121                 }
122             }
123
124             @Override
125             public void onFailure(final Throwable failure) {
126                 ar.resume(failure);
127             }
128         }, MoreExecutors.directExecutor());
129     }
130
131     /**
132      * Invoking rpc via mount point.
133      *
134      * @param mountPoint mount point
135      * @param data input data
136      * @param rpc RPC type
137      * @return {@link DOMRpcResult}
138      */
139     @VisibleForTesting
140     static ListenableFuture<? extends DOMRpcResult> invokeRpc(final NormalizedNode data, final QName rpc,
141             final DOMMountPoint mountPoint) {
142         return invokeRpc(data, rpc, mountPoint.getService(DOMRpcService.class).orElseThrow(() -> {
143             final String errmsg = "RPC service is missing.";
144             LOG.debug(errmsg);
145             return new RestconfDocumentedException(errmsg);
146         }));
147     }
148
149     /**
150      * Invoke rpc.
151      *
152      * @param data input data
153      * @param rpc RPC type
154      * @param rpcService rpc service to invoke rpc
155      * @return {@link DOMRpcResult}
156      */
157     @VisibleForTesting
158     static ListenableFuture<? extends DOMRpcResult> invokeRpc(final NormalizedNode data, final QName rpc,
159             final DOMRpcService rpcService) {
160         return Futures.catching(rpcService.invokeRpc(rpc, nonnullInput(rpc, data)),
161             DOMRpcException.class,
162             cause -> new DefaultDOMRpcResult(ImmutableList.of(RpcResultBuilder.newError(
163                 RpcError.ErrorType.RPC, "operation-failed", cause.getMessage()))),
164             MoreExecutors.directExecutor());
165     }
166
167     private static @NonNull NormalizedNode nonnullInput(final QName type, final NormalizedNode input) {
168         return input != null ? input
169                 : ImmutableNodes.containerNode(YangConstants.operationInputQName(type.getModule()));
170     }
171
172     @Deprecated
173     static <T> T checkedGet(final ListenableFuture<T> future) {
174         try {
175             return future.get();
176         } catch (InterruptedException e) {
177             throw new RestconfDocumentedException("Interrupted while waiting for result of invocation", e);
178         } catch (ExecutionException e) {
179             Throwables.throwIfInstanceOf(e.getCause(), RestconfDocumentedException.class);
180             throw new RestconfDocumentedException("Invocation failed", e);
181         }
182     }
183
184     private static EffectiveModelContext modelContext(final DOMMountPoint mountPoint) {
185         return mountPoint.getService(DOMSchemaService.class)
186             .flatMap(svc -> Optional.ofNullable(svc.getGlobalContext()))
187             .orElse(null);
188     }
189 }