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