Teach RFC8040 restconf about actions
[netconf.git] / restconf / restconf-nb-rfc8040 / src / main / java / org / opendaylight / restconf / nb / rfc8040 / rests / services / impl / RestconfDataServiceImpl.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 import static org.opendaylight.restconf.nb.rfc8040.rests.utils.RestconfStreamsConstants.CREATE_NOTIFICATION_STREAM;
12 import static org.opendaylight.restconf.nb.rfc8040.rests.utils.RestconfStreamsConstants.STREAM_ACCESS_PATH_PART;
13 import static org.opendaylight.restconf.nb.rfc8040.rests.utils.RestconfStreamsConstants.STREAM_LOCATION_PATH_PART;
14 import static org.opendaylight.restconf.nb.rfc8040.rests.utils.RestconfStreamsConstants.STREAM_PATH;
15
16 import java.time.Clock;
17 import java.time.LocalDateTime;
18 import java.time.format.DateTimeFormatter;
19 import java.util.List;
20 import java.util.Map.Entry;
21 import java.util.Optional;
22 import javax.ws.rs.Path;
23 import javax.ws.rs.WebApplicationException;
24 import javax.ws.rs.core.Response;
25 import javax.ws.rs.core.UriInfo;
26 import org.eclipse.jdt.annotation.NonNull;
27 import org.opendaylight.mdsal.dom.api.DOMActionResult;
28 import org.opendaylight.mdsal.dom.api.DOMDataBroker;
29 import org.opendaylight.mdsal.dom.api.DOMMountPoint;
30 import org.opendaylight.restconf.common.context.InstanceIdentifierContext;
31 import org.opendaylight.restconf.common.context.NormalizedNodeContext;
32 import org.opendaylight.restconf.common.context.WriterParameters;
33 import org.opendaylight.restconf.common.errors.RestconfDocumentedException;
34 import org.opendaylight.restconf.common.errors.RestconfError;
35 import org.opendaylight.restconf.common.errors.RestconfError.ErrorTag;
36 import org.opendaylight.restconf.common.errors.RestconfError.ErrorType;
37 import org.opendaylight.restconf.common.patch.PatchContext;
38 import org.opendaylight.restconf.common.patch.PatchStatusContext;
39 import org.opendaylight.restconf.nb.rfc8040.handlers.ActionServiceHandler;
40 import org.opendaylight.restconf.nb.rfc8040.handlers.DOMMountPointServiceHandler;
41 import org.opendaylight.restconf.nb.rfc8040.handlers.SchemaContextHandler;
42 import org.opendaylight.restconf.nb.rfc8040.handlers.TransactionChainHandler;
43 import org.opendaylight.restconf.nb.rfc8040.references.SchemaContextRef;
44 import org.opendaylight.restconf.nb.rfc8040.rests.services.api.RestconfDataService;
45 import org.opendaylight.restconf.nb.rfc8040.rests.services.api.RestconfStreamsSubscriptionService;
46 import org.opendaylight.restconf.nb.rfc8040.rests.transactions.TransactionVarsWrapper;
47 import org.opendaylight.restconf.nb.rfc8040.rests.utils.DeleteDataTransactionUtil;
48 import org.opendaylight.restconf.nb.rfc8040.rests.utils.PatchDataTransactionUtil;
49 import org.opendaylight.restconf.nb.rfc8040.rests.utils.PostDataTransactionUtil;
50 import org.opendaylight.restconf.nb.rfc8040.rests.utils.PutDataTransactionUtil;
51 import org.opendaylight.restconf.nb.rfc8040.rests.utils.ReadDataTransactionUtil;
52 import org.opendaylight.restconf.nb.rfc8040.rests.utils.RestconfDataServiceConstant;
53 import org.opendaylight.restconf.nb.rfc8040.rests.utils.RestconfInvokeOperationsUtil;
54 import org.opendaylight.restconf.nb.rfc8040.utils.RestconfConstants;
55 import org.opendaylight.restconf.nb.rfc8040.utils.parser.ParserIdentifier;
56 import org.opendaylight.yangtools.yang.common.QName;
57 import org.opendaylight.yangtools.yang.common.Revision;
58 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
59 import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode;
60 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
61 import org.opendaylight.yangtools.yang.model.api.ActionDefinition;
62 import org.opendaylight.yangtools.yang.model.api.SchemaNode;
63 import org.opendaylight.yangtools.yang.model.api.SchemaPath;
64 import org.slf4j.Logger;
65 import org.slf4j.LoggerFactory;
66
67 /**
68  * Implementation of {@link RestconfDataService}.
69  */
70 @Path("/")
71 public class RestconfDataServiceImpl implements RestconfDataService {
72
73     private static final Logger LOG = LoggerFactory.getLogger(RestconfDataServiceImpl.class);
74     private static final DateTimeFormatter FORMATTER = DateTimeFormatter.ofPattern("yyyy-MMM-dd HH:mm:ss");
75
76     private final RestconfStreamsSubscriptionService delegRestconfSubscrService;
77
78     // FIXME: evaluate thread-safety of updates (synchronized) vs. access (mostly unsynchronized) here
79     private SchemaContextHandler schemaContextHandler;
80     private TransactionChainHandler transactionChainHandler;
81     private DOMMountPointServiceHandler mountPointServiceHandler;
82     private volatile ActionServiceHandler actionServiceHandler;
83
84     public RestconfDataServiceImpl(final SchemaContextHandler schemaContextHandler,
85             final TransactionChainHandler transactionChainHandler,
86             final DOMMountPointServiceHandler mountPointServiceHandler,
87             final RestconfStreamsSubscriptionService delegRestconfSubscrService,
88             final ActionServiceHandler actionServiceHandler) {
89         this.actionServiceHandler = requireNonNull(actionServiceHandler);
90         this.schemaContextHandler = requireNonNull(schemaContextHandler);
91         this.transactionChainHandler = requireNonNull(transactionChainHandler);
92         this.mountPointServiceHandler = requireNonNull(mountPointServiceHandler);
93         this.delegRestconfSubscrService = requireNonNull(delegRestconfSubscrService);
94     }
95
96     @Override
97     public synchronized void updateHandlers(final Object... handlers) {
98         for (final Object object : handlers) {
99             if (object instanceof SchemaContextHandler) {
100                 schemaContextHandler = (SchemaContextHandler) object;
101             } else if (object instanceof ActionServiceHandler) {
102                 actionServiceHandler = (ActionServiceHandler) object;
103             } else if (object instanceof DOMMountPointServiceHandler) {
104                 mountPointServiceHandler = (DOMMountPointServiceHandler) object;
105             } else if (object instanceof TransactionChainHandler) {
106                 transactionChainHandler = (TransactionChainHandler) object;
107             }
108         }
109     }
110
111     @Override
112     public Response readData(final UriInfo uriInfo) {
113         return readData(null, uriInfo);
114     }
115
116     @Override
117     public Response readData(final String identifier, final UriInfo uriInfo) {
118         final SchemaContextRef schemaContextRef = new SchemaContextRef(this.schemaContextHandler.get());
119         final InstanceIdentifierContext<?> instanceIdentifier = ParserIdentifier.toInstanceIdentifier(
120                 identifier, schemaContextRef.get(), Optional.of(this.mountPointServiceHandler.get()));
121         final WriterParameters parameters = ReadDataTransactionUtil.parseUriParameters(instanceIdentifier, uriInfo);
122
123         final DOMMountPoint mountPoint = instanceIdentifier.getMountPoint();
124         final TransactionVarsWrapper transactionNode = new TransactionVarsWrapper(
125                 instanceIdentifier, mountPoint, getTransactionChainHandler(mountPoint));
126         final NormalizedNode<?, ?> node = ReadDataTransactionUtil.readData(identifier, parameters.getContent(),
127                 transactionNode, parameters.getWithDefault(), schemaContextRef, uriInfo);
128         if (identifier != null && identifier.contains(STREAM_PATH) && identifier.contains(STREAM_ACCESS_PATH_PART)
129                 && identifier.contains(STREAM_LOCATION_PATH_PART)) {
130             final String value = (String) node.getValue();
131             final String streamName = value.substring(
132                     value.indexOf(CREATE_NOTIFICATION_STREAM + RestconfConstants.SLASH));
133             this.delegRestconfSubscrService.subscribeToStream(streamName, uriInfo);
134         }
135         if (node == null) {
136             throw new RestconfDocumentedException(
137                     "Request could not be completed because the relevant data model content does not exist",
138                     RestconfError.ErrorType.PROTOCOL,
139                     RestconfError.ErrorTag.DATA_MISSING);
140         }
141
142         if (parameters.getContent().equals(RestconfDataServiceConstant.ReadData.ALL)
143                     || parameters.getContent().equals(RestconfDataServiceConstant.ReadData.CONFIG)) {
144             final QName type = node.getNodeType();
145             return Response.status(200)
146                     .entity(new NormalizedNodeContext(instanceIdentifier, node, parameters))
147                     .header("ETag", '"' + type.getModule().getRevision().map(Revision::toString).orElse(null)
148                         + type.getLocalName() + '"')
149                     .header("Last-Modified", FORMATTER.format(LocalDateTime.now(Clock.systemUTC())))
150                     .build();
151         }
152
153         return Response.status(200).entity(new NormalizedNodeContext(instanceIdentifier, node, parameters)).build();
154     }
155
156     @Override
157     public Response putData(final String identifier, final NormalizedNodeContext payload, final UriInfo uriInfo) {
158         requireNonNull(payload);
159
160         boolean insertUsed = false;
161         boolean pointUsed = false;
162         String insert = null;
163         String point = null;
164
165         for (final Entry<String, List<String>> entry : uriInfo.getQueryParameters().entrySet()) {
166             switch (entry.getKey()) {
167                 case "insert":
168                     if (!insertUsed) {
169                         insertUsed = true;
170                         insert = entry.getValue().iterator().next();
171                     } else {
172                         throw new RestconfDocumentedException("Insert parameter can be used only once.",
173                                 RestconfError.ErrorType.PROTOCOL, RestconfError.ErrorTag.BAD_ELEMENT);
174                     }
175                     break;
176                 case "point":
177                     if (!pointUsed) {
178                         pointUsed = true;
179                         point = entry.getValue().iterator().next();
180                     } else {
181                         throw new RestconfDocumentedException("Point parameter can be used only once.",
182                                 RestconfError.ErrorType.PROTOCOL, RestconfError.ErrorTag.BAD_ELEMENT);
183                     }
184                     break;
185                 default:
186                     throw new RestconfDocumentedException("Bad parameter for post: " + entry.getKey(),
187                             RestconfError.ErrorType.PROTOCOL, RestconfError.ErrorTag.BAD_ELEMENT);
188             }
189         }
190
191         checkQueryParams(insertUsed, pointUsed, insert);
192
193         final InstanceIdentifierContext<? extends SchemaNode> iid = payload
194                 .getInstanceIdentifierContext();
195
196         PutDataTransactionUtil.validInputData(iid.getSchemaNode(), payload);
197         PutDataTransactionUtil.validTopLevelNodeName(iid.getInstanceIdentifier(), payload);
198         PutDataTransactionUtil.validateListKeysEqualityInPayloadAndUri(payload);
199
200         final DOMMountPoint mountPoint = payload.getInstanceIdentifierContext().getMountPoint();
201         final TransactionChainHandler localTransactionChainHandler;
202         final SchemaContextRef ref;
203         if (mountPoint == null) {
204             localTransactionChainHandler = this.transactionChainHandler;
205             ref = new SchemaContextRef(this.schemaContextHandler.get());
206         } else {
207             localTransactionChainHandler = transactionChainOfMountPoint(mountPoint);
208             ref = new SchemaContextRef(mountPoint.getSchemaContext());
209         }
210
211         final TransactionVarsWrapper transactionNode = new TransactionVarsWrapper(
212                 payload.getInstanceIdentifierContext(), mountPoint, localTransactionChainHandler);
213         return PutDataTransactionUtil.putData(payload, ref, transactionNode, insert, point);
214     }
215
216     private static void checkQueryParams(final boolean insertUsed, final boolean pointUsed, final String insert) {
217         if (pointUsed && !insertUsed) {
218             throw new RestconfDocumentedException("Point parameter can't be used without Insert parameter.",
219                     RestconfError.ErrorType.PROTOCOL, RestconfError.ErrorTag.BAD_ELEMENT);
220         }
221         if (pointUsed && (insert.equals("first") || insert.equals("last"))) {
222             throw new RestconfDocumentedException(
223                     "Point parameter can be used only with 'after' or 'before' values of Insert parameter.",
224                     RestconfError.ErrorType.PROTOCOL, RestconfError.ErrorTag.BAD_ELEMENT);
225         }
226     }
227
228     @Override
229     public Response postData(final String identifier, final NormalizedNodeContext payload, final UriInfo uriInfo) {
230         return postData(payload, uriInfo);
231     }
232
233     @Override
234     public Response postData(final NormalizedNodeContext payload, final UriInfo uriInfo) {
235         requireNonNull(payload);
236         if (payload.getInstanceIdentifierContext().getSchemaNode() instanceof ActionDefinition) {
237             return invokeAction(payload, uriInfo);
238         }
239         boolean insertUsed = false;
240         boolean pointUsed = false;
241         String insert = null;
242         String point = null;
243
244         for (final Entry<String, List<String>> entry : uriInfo.getQueryParameters().entrySet()) {
245             switch (entry.getKey()) {
246                 case "insert":
247                     if (!insertUsed) {
248                         insertUsed = true;
249                         insert = entry.getValue().iterator().next();
250                     } else {
251                         throw new RestconfDocumentedException("Insert parameter can be used only once.",
252                                 RestconfError.ErrorType.PROTOCOL, RestconfError.ErrorTag.BAD_ELEMENT);
253                     }
254                     break;
255                 case "point":
256                     if (!pointUsed) {
257                         pointUsed = true;
258                         point = entry.getValue().iterator().next();
259                     } else {
260                         throw new RestconfDocumentedException("Point parameter can be used only once.",
261                                 RestconfError.ErrorType.PROTOCOL, RestconfError.ErrorTag.BAD_ELEMENT);
262                     }
263                     break;
264                 default:
265                     throw new RestconfDocumentedException("Bad parameter for post: " + entry.getKey(),
266                             RestconfError.ErrorType.PROTOCOL, RestconfError.ErrorTag.BAD_ELEMENT);
267             }
268         }
269
270         checkQueryParams(insertUsed, pointUsed, insert);
271
272         final DOMMountPoint mountPoint = payload.getInstanceIdentifierContext().getMountPoint();
273         final TransactionVarsWrapper transactionNode = new TransactionVarsWrapper(
274                 payload.getInstanceIdentifierContext(), mountPoint, getTransactionChainHandler(mountPoint));
275         return PostDataTransactionUtil.postData(uriInfo, payload, transactionNode,
276                 getSchemaContext(mountPoint), insert, point);
277     }
278
279     @Override
280     public Response deleteData(final String identifier) {
281         final SchemaContextRef schemaContextRef = new SchemaContextRef(this.schemaContextHandler.get());
282         final InstanceIdentifierContext<?> instanceIdentifier = ParserIdentifier.toInstanceIdentifier(
283                 identifier, schemaContextRef.get(), Optional.of(this.mountPointServiceHandler.get()));
284
285         final DOMMountPoint mountPoint = instanceIdentifier.getMountPoint();
286         final TransactionChainHandler localTransactionChainHandler;
287         if (mountPoint == null) {
288             localTransactionChainHandler = this.transactionChainHandler;
289         } else {
290             localTransactionChainHandler = transactionChainOfMountPoint(mountPoint);
291         }
292
293         final TransactionVarsWrapper transactionNode = new TransactionVarsWrapper(instanceIdentifier, mountPoint,
294                 localTransactionChainHandler);
295         return DeleteDataTransactionUtil.deleteData(transactionNode);
296     }
297
298     @Override
299     public PatchStatusContext patchData(final String identifier, final PatchContext context, final UriInfo uriInfo) {
300         return patchData(context, uriInfo);
301     }
302
303     @Override
304     public PatchStatusContext patchData(final PatchContext context, final UriInfo uriInfo) {
305         final DOMMountPoint mountPoint = requireNonNull(context).getInstanceIdentifierContext().getMountPoint();
306         final TransactionVarsWrapper transactionNode = new TransactionVarsWrapper(
307                 context.getInstanceIdentifierContext(), mountPoint, getTransactionChainHandler(mountPoint));
308         return PatchDataTransactionUtil.patchData(context, transactionNode, getSchemaContext(mountPoint));
309     }
310
311     private TransactionChainHandler getTransactionChainHandler(final DOMMountPoint mountPoint) {
312         return mountPoint == null ? transactionChainHandler : transactionChainOfMountPoint(mountPoint);
313     }
314
315     private SchemaContextRef getSchemaContext(final DOMMountPoint mountPoint) {
316         return mountPoint == null ? new SchemaContextRef(schemaContextHandler.get())
317                 : new SchemaContextRef(mountPoint.getSchemaContext());
318     }
319
320     /**
321      * Prepare transaction chain to access data of mount point.
322      * @param mountPoint
323      *            mount point reference
324      * @return {@link TransactionChainHandler}
325      */
326     private static TransactionChainHandler transactionChainOfMountPoint(final @NonNull DOMMountPoint mountPoint) {
327         final Optional<DOMDataBroker> domDataBrokerService = mountPoint.getService(DOMDataBroker.class);
328         if (domDataBrokerService.isPresent()) {
329             return new TransactionChainHandler(domDataBrokerService.get());
330         }
331
332         final String errMsg = "DOM data broker service isn't available for mount point " + mountPoint.getIdentifier();
333         LOG.warn(errMsg);
334         throw new RestconfDocumentedException(errMsg);
335     }
336
337     /**
338      * Invoke Action operation.
339      *
340      * @param payload
341      *             {@link NormalizedNodeContext} - the body of the operation
342      * @param uriInfo
343      *             URI info
344      * @return {@link NormalizedNodeContext} wrapped in {@link Response}
345      */
346     public Response invokeAction(final NormalizedNodeContext payload, final UriInfo uriInfo) {
347         final InstanceIdentifierContext<?> context = payload.getInstanceIdentifierContext();
348         final DOMMountPoint mountPoint = context.getMountPoint();
349         final SchemaPath schemaPath = context.getSchemaNode().getPath();
350         final YangInstanceIdentifier yangIIdContext = context.getInstanceIdentifier();
351         final NormalizedNode<?, ?> data = payload.getData();
352
353         if (yangIIdContext.isEmpty() && !RestconfDataServiceConstant.NETCONF_BASE_QNAME.equals(data.getNodeType())) {
354             throw new RestconfDocumentedException("Instance identifier need to contain at least one path argument",
355                 ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE);
356         }
357
358         final DOMActionResult response;
359         final SchemaContextRef schemaContextRef;
360         if (mountPoint != null) {
361             response = RestconfInvokeOperationsUtil.invokeActionViaMountPoint(mountPoint, (ContainerNode) data,
362                 schemaPath, yangIIdContext);
363             schemaContextRef = new SchemaContextRef(mountPoint.getSchemaContext());
364         } else {
365             response = RestconfInvokeOperationsUtil.invokeAction((ContainerNode) data, schemaPath,
366                 this.actionServiceHandler, yangIIdContext);
367             schemaContextRef = new SchemaContextRef(this.schemaContextHandler.get());
368         }
369         final DOMActionResult result = RestconfInvokeOperationsUtil.checkActionResponse(response);
370
371         ActionDefinition resultNodeSchema = null;
372         ContainerNode resultData = null;
373         if (result != null) {
374             final Optional<ContainerNode> optOutput = result.getOutput();
375             if (optOutput.isPresent()) {
376                 resultData = optOutput.get();
377                 resultNodeSchema = (ActionDefinition) context.getSchemaNode();
378             }
379         }
380
381         if (resultData != null && resultData.getValue().isEmpty()) {
382             throw new WebApplicationException(Response.Status.NO_CONTENT);
383         }
384
385         return Response.status(200).entity(new NormalizedNodeContext(new InstanceIdentifierContext<>(yangIIdContext,
386                 resultNodeSchema, mountPoint, schemaContextRef.get()), resultData)).build();
387     }
388 }