2 * Copyright (c) 2016 Cisco Systems, Inc. and others. All rights reserved.
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
8 package org.opendaylight.restconf.nb.rfc8040.rests.services.impl;
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;
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;
73 * Implementation of {@link RestconfDataService}.
76 public class RestconfDataServiceImpl implements RestconfDataService {
77 private static final class QueryParams implements Immutable {
78 final @Nullable String point;
79 final @Nullable String insert;
81 QueryParams(final @Nullable String insert, final @Nullable String point) {
87 private static final Logger LOG = LoggerFactory.getLogger(RestconfDataServiceImpl.class);
88 private static final DateTimeFormatter FORMATTER = DateTimeFormatter.ofPattern("yyyy-MMM-dd HH:mm:ss");
90 private final RestconfStreamsSubscriptionService delegRestconfSubscrService;
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;
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);
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;
126 public Response readData(final UriInfo uriInfo) {
127 return readData(null, uriInfo);
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()));
136 boolean withDefaUsed = false;
137 String withDefa = null;
139 for (final Entry<String, List<String>> entry : uriInfo.getQueryParameters().entrySet()) {
140 switch (entry.getKey()) {
141 case "with-defaults":
144 withDefa = entry.getValue().iterator().next();
146 throw new RestconfDocumentedException("With-defaults parameter can be used only once.");
150 LOG.info("Unknown key : {}.", entry.getKey());
154 boolean tagged = false;
156 if ("report-all-tagged".equals(withDefa)) {
160 if ("report-all".equals(withDefa)) {
165 final WriterParameters parameters = ReadDataTransactionUtil.parseUriParameters(
166 instanceIdentifier, uriInfo, tagged);
168 final DOMMountPoint mountPoint = instanceIdentifier.getMountPoint();
169 final TransactionChainHandler localTransactionChainHandler;
170 if (mountPoint == null) {
171 localTransactionChainHandler = this.transactionChainHandler;
173 localTransactionChainHandler = transactionChainOfMountPoint(mountPoint);
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);
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);
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())))
206 return Response.status(200).entity(new NormalizedNodeContext(instanceIdentifier, node, parameters)).build();
210 public Response putData(final String identifier, final NormalizedNodeContext payload, final UriInfo uriInfo) {
211 requireNonNull(payload);
213 final QueryParams checkedParms = checkQueryParameters(uriInfo);
215 final InstanceIdentifierContext<? extends SchemaNode> iid = payload
216 .getInstanceIdentifierContext();
218 PutDataTransactionUtil.validInputData(iid.getSchemaNode(), payload);
219 PutDataTransactionUtil.validTopLevelNodeName(iid.getInstanceIdentifier(), payload);
220 PutDataTransactionUtil.validateListKeysEqualityInPayloadAndUri(payload);
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());
229 localTransactionChainHandler = transactionChainOfMountPoint(mountPoint);
230 ref = new SchemaContextRef(mountPoint.getSchemaContext());
233 final TransactionVarsWrapper transactionNode = new TransactionVarsWrapper(
234 payload.getInstanceIdentifierContext(), mountPoint, localTransactionChainHandler);
235 return PutDataTransactionUtil.putData(payload, ref, transactionNode, checkedParms.insert, checkedParms.point);
238 private static QueryParams checkQueryParameters(final UriInfo uriInfo) {
239 boolean insertUsed = false;
240 boolean pointUsed = false;
241 String insert = null;
244 for (final Entry<String, List<String>> entry : uriInfo.getQueryParameters().entrySet()) {
245 switch (entry.getKey()) {
249 insert = entry.getValue().get(0);
251 throw new RestconfDocumentedException("Insert parameter can be used only once.",
252 RestconfError.ErrorType.PROTOCOL, RestconfError.ErrorTag.BAD_ELEMENT);
258 point = entry.getValue().get(0);
260 throw new RestconfDocumentedException("Point parameter can be used only once.",
261 RestconfError.ErrorType.PROTOCOL, RestconfError.ErrorTag.BAD_ELEMENT);
265 throw new RestconfDocumentedException("Bad parameter for post: " + entry.getKey(),
266 RestconfError.ErrorType.PROTOCOL, RestconfError.ErrorTag.BAD_ELEMENT);
270 checkQueryParams(insertUsed, pointUsed, insert);
271 return new QueryParams(insert, point);
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);
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);
287 public Response postData(final String identifier, final NormalizedNodeContext payload, final UriInfo uriInfo) {
288 return postData(payload, uriInfo);
292 public Response postData(final NormalizedNodeContext payload, final UriInfo uriInfo) {
293 requireNonNull(payload);
294 if (payload.getInstanceIdentifierContext().getSchemaNode() instanceof ActionDefinition) {
295 return invokeAction(payload);
298 final QueryParams checkedParms = checkQueryParameters(uriInfo);
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());
307 localTransactionChainHandler = transactionChainOfMountPoint(mountPoint);
308 ref = new SchemaContextRef(mountPoint.getSchemaContext());
310 final TransactionVarsWrapper transactionNode = new TransactionVarsWrapper(
311 payload.getInstanceIdentifierContext(), mountPoint, localTransactionChainHandler);
312 return PostDataTransactionUtil.postData(uriInfo, payload, transactionNode, ref, checkedParms.insert,
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()));
322 final DOMMountPoint mountPoint = instanceIdentifier.getMountPoint();
323 final TransactionChainHandler localTransactionChainHandler;
324 if (mountPoint == null) {
325 localTransactionChainHandler = this.transactionChainHandler;
327 localTransactionChainHandler = transactionChainOfMountPoint(mountPoint);
330 final TransactionVarsWrapper transactionNode = new TransactionVarsWrapper(instanceIdentifier, mountPoint,
331 localTransactionChainHandler);
332 return DeleteDataTransactionUtil.deleteData(transactionNode);
336 public PatchStatusContext patchData(final String identifier, final PatchContext context, final UriInfo uriInfo) {
337 return patchData(context, uriInfo);
341 public PatchStatusContext patchData(final PatchContext context, final UriInfo uriInfo) {
342 final DOMMountPoint mountPoint = requireNonNull(context).getInstanceIdentifierContext().getMountPoint();
344 final TransactionChainHandler localTransactionChainHandler;
345 final SchemaContextRef ref;
346 if (mountPoint == null) {
347 localTransactionChainHandler = this.transactionChainHandler;
348 ref = new SchemaContextRef(this.schemaContextHandler.get());
350 localTransactionChainHandler = transactionChainOfMountPoint(mountPoint);
351 ref = new SchemaContextRef(mountPoint.getSchemaContext());
354 final TransactionVarsWrapper transactionNode = new TransactionVarsWrapper(
355 context.getInstanceIdentifierContext(), mountPoint, localTransactionChainHandler);
357 return PatchDataTransactionUtil.patchData(context, transactionNode, ref);
361 public Response patchData(final String identifier, final NormalizedNodeContext payload, final UriInfo uriInfo) {
362 requireNonNull(payload);
364 final InstanceIdentifierContext<? extends SchemaNode> iid = payload
365 .getInstanceIdentifierContext();
367 PutDataTransactionUtil.validInputData(iid.getSchemaNode(), payload);
368 PutDataTransactionUtil.validTopLevelNodeName(iid.getInstanceIdentifier(), payload);
369 PutDataTransactionUtil.validateListKeysEqualityInPayloadAndUri(payload);
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());
378 localTransactionChainHandler = transactionChainOfMountPoint(mountPoint);
379 ref = new SchemaContextRef(mountPoint.getSchemaContext());
382 final TransactionVarsWrapper transactionNode = new TransactionVarsWrapper(
383 payload.getInstanceIdentifierContext(), mountPoint, localTransactionChainHandler);
385 return PlainPatchDataTransactionUtil.patchData(payload, transactionNode, ref);
389 * Prepare transaction chain to access data of mount point.
391 * mount point reference
392 * @return {@link TransactionChainHandler}
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());
400 final String errMsg = "DOM data broker service isn't available for mount point " + mountPoint.getIdentifier();
402 throw new RestconfDocumentedException(errMsg);
406 * Invoke Action operation.
408 * @param payload {@link NormalizedNodeContext} - the body of the operation
409 * @return {@link NormalizedNodeContext} wrapped in {@link Response}
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();
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);
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());
430 response = RestconfInvokeOperationsUtil.invokeAction((ContainerNode) data, schemaPath,
431 this.actionServiceHandler, yangIIdContext);
432 schemaContextRef = new SchemaContextRef(this.schemaContextHandler.get());
434 final DOMActionResult result = RestconfInvokeOperationsUtil.checkActionResponse(response);
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();
446 if (resultData != null && resultData.getValue().isEmpty()) {
447 throw new WebApplicationException(Response.Status.NO_CONTENT);
450 return Response.status(200).entity(new NormalizedNodeContext(new InstanceIdentifierContext<>(yangIIdContext,
451 resultNodeSchema, mountPoint, schemaContextRef.get()), resultData)).build();