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.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;
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;
68 * Implementation of {@link RestconfDataService}.
71 public class RestconfDataServiceImpl implements RestconfDataService {
73 private static final Logger LOG = LoggerFactory.getLogger(RestconfDataServiceImpl.class);
74 private static final DateTimeFormatter FORMATTER = DateTimeFormatter.ofPattern("yyyy-MMM-dd HH:mm:ss");
76 private final RestconfStreamsSubscriptionService delegRestconfSubscrService;
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;
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);
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;
112 public Response readData(final UriInfo uriInfo) {
113 return readData(null, uriInfo);
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);
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);
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);
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())))
153 return Response.status(200).entity(new NormalizedNodeContext(instanceIdentifier, node, parameters)).build();
157 public Response putData(final String identifier, final NormalizedNodeContext payload, final UriInfo uriInfo) {
158 requireNonNull(payload);
160 boolean insertUsed = false;
161 boolean pointUsed = false;
162 String insert = null;
165 for (final Entry<String, List<String>> entry : uriInfo.getQueryParameters().entrySet()) {
166 switch (entry.getKey()) {
170 insert = entry.getValue().iterator().next();
172 throw new RestconfDocumentedException("Insert parameter can be used only once.",
173 RestconfError.ErrorType.PROTOCOL, RestconfError.ErrorTag.BAD_ELEMENT);
179 point = entry.getValue().iterator().next();
181 throw new RestconfDocumentedException("Point parameter can be used only once.",
182 RestconfError.ErrorType.PROTOCOL, RestconfError.ErrorTag.BAD_ELEMENT);
186 throw new RestconfDocumentedException("Bad parameter for post: " + entry.getKey(),
187 RestconfError.ErrorType.PROTOCOL, RestconfError.ErrorTag.BAD_ELEMENT);
191 checkQueryParams(insertUsed, pointUsed, insert);
193 final InstanceIdentifierContext<? extends SchemaNode> iid = payload
194 .getInstanceIdentifierContext();
196 PutDataTransactionUtil.validInputData(iid.getSchemaNode(), payload);
197 PutDataTransactionUtil.validTopLevelNodeName(iid.getInstanceIdentifier(), payload);
198 PutDataTransactionUtil.validateListKeysEqualityInPayloadAndUri(payload);
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());
207 localTransactionChainHandler = transactionChainOfMountPoint(mountPoint);
208 ref = new SchemaContextRef(mountPoint.getSchemaContext());
211 final TransactionVarsWrapper transactionNode = new TransactionVarsWrapper(
212 payload.getInstanceIdentifierContext(), mountPoint, localTransactionChainHandler);
213 return PutDataTransactionUtil.putData(payload, ref, transactionNode, insert, point);
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);
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);
229 public Response postData(final String identifier, final NormalizedNodeContext payload, final UriInfo uriInfo) {
230 return postData(payload, uriInfo);
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);
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().iterator().next();
251 throw new RestconfDocumentedException("Insert parameter can be used only once.",
252 RestconfError.ErrorType.PROTOCOL, RestconfError.ErrorTag.BAD_ELEMENT);
258 point = entry.getValue().iterator().next();
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);
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);
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()));
285 final DOMMountPoint mountPoint = instanceIdentifier.getMountPoint();
286 final TransactionChainHandler localTransactionChainHandler;
287 if (mountPoint == null) {
288 localTransactionChainHandler = this.transactionChainHandler;
290 localTransactionChainHandler = transactionChainOfMountPoint(mountPoint);
293 final TransactionVarsWrapper transactionNode = new TransactionVarsWrapper(instanceIdentifier, mountPoint,
294 localTransactionChainHandler);
295 return DeleteDataTransactionUtil.deleteData(transactionNode);
299 public PatchStatusContext patchData(final String identifier, final PatchContext context, final UriInfo uriInfo) {
300 return patchData(context, uriInfo);
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));
311 private TransactionChainHandler getTransactionChainHandler(final DOMMountPoint mountPoint) {
312 return mountPoint == null ? transactionChainHandler : transactionChainOfMountPoint(mountPoint);
315 private SchemaContextRef getSchemaContext(final DOMMountPoint mountPoint) {
316 return mountPoint == null ? new SchemaContextRef(schemaContextHandler.get())
317 : new SchemaContextRef(mountPoint.getSchemaContext());
321 * Prepare transaction chain to access data of mount point.
323 * mount point reference
324 * @return {@link TransactionChainHandler}
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());
332 final String errMsg = "DOM data broker service isn't available for mount point " + mountPoint.getIdentifier();
334 throw new RestconfDocumentedException(errMsg);
338 * Invoke Action operation.
341 * {@link NormalizedNodeContext} - the body of the operation
344 * @return {@link NormalizedNodeContext} wrapped in {@link Response}
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();
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);
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());
365 response = RestconfInvokeOperationsUtil.invokeAction((ContainerNode) data, schemaPath,
366 this.actionServiceHandler, yangIIdContext);
367 schemaContextRef = new SchemaContextRef(this.schemaContextHandler.get());
369 final DOMActionResult result = RestconfInvokeOperationsUtil.checkActionResponse(response);
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();
381 if (resultData != null && resultData.getValue().isEmpty()) {
382 throw new WebApplicationException(Response.Status.NO_CONTENT);
385 return Response.status(200).entity(new NormalizedNodeContext(new InstanceIdentifierContext<>(yangIIdContext,
386 resultNodeSchema, mountPoint, schemaContextRef.get()), resultData)).build();