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.STREAMS_PATH;
15 import static org.opendaylight.restconf.nb.rfc8040.rests.utils.RestconfStreamsConstants.STREAM_ACCESS_PATH_PART;
16 import static org.opendaylight.restconf.nb.rfc8040.rests.utils.RestconfStreamsConstants.STREAM_LOCATION_PATH_PART;
17 import static org.opendaylight.restconf.nb.rfc8040.rests.utils.RestconfStreamsConstants.STREAM_PATH;
18 import static org.opendaylight.restconf.nb.rfc8040.rests.utils.RestconfStreamsConstants.STREAM_PATH_PART;
20 import com.google.common.collect.ImmutableList;
22 import java.time.Clock;
23 import java.time.LocalDateTime;
24 import java.time.format.DateTimeFormatter;
25 import java.util.List;
26 import java.util.Map.Entry;
27 import java.util.Optional;
28 import java.util.concurrent.ExecutionException;
29 import javax.ws.rs.Path;
30 import javax.ws.rs.WebApplicationException;
31 import javax.ws.rs.core.Response;
32 import javax.ws.rs.core.UriInfo;
33 import org.eclipse.jdt.annotation.Nullable;
34 import org.opendaylight.mdsal.common.api.LogicalDatastoreType;
35 import org.opendaylight.mdsal.dom.api.DOMActionResult;
36 import org.opendaylight.mdsal.dom.api.DOMMountPoint;
37 import org.opendaylight.mdsal.dom.api.DOMSchemaService;
38 import org.opendaylight.restconf.common.context.InstanceIdentifierContext;
39 import org.opendaylight.restconf.common.context.NormalizedNodeContext;
40 import org.opendaylight.restconf.common.context.WriterParameters;
41 import org.opendaylight.restconf.common.errors.RestconfDocumentedException;
42 import org.opendaylight.restconf.common.errors.RestconfError;
43 import org.opendaylight.restconf.common.errors.RestconfError.ErrorTag;
44 import org.opendaylight.restconf.common.errors.RestconfError.ErrorType;
45 import org.opendaylight.restconf.common.patch.PatchContext;
46 import org.opendaylight.restconf.common.patch.PatchStatusContext;
47 import org.opendaylight.restconf.nb.rfc8040.Rfc8040;
48 import org.opendaylight.restconf.nb.rfc8040.handlers.ActionServiceHandler;
49 import org.opendaylight.restconf.nb.rfc8040.handlers.DOMMountPointServiceHandler;
50 import org.opendaylight.restconf.nb.rfc8040.handlers.SchemaContextHandler;
51 import org.opendaylight.restconf.nb.rfc8040.handlers.TransactionChainHandler;
52 import org.opendaylight.restconf.nb.rfc8040.rests.services.api.RestconfDataService;
53 import org.opendaylight.restconf.nb.rfc8040.rests.services.api.RestconfStreamsSubscriptionService;
54 import org.opendaylight.restconf.nb.rfc8040.rests.transactions.MdsalRestconfStrategy;
55 import org.opendaylight.restconf.nb.rfc8040.rests.transactions.RestconfStrategy;
56 import org.opendaylight.restconf.nb.rfc8040.rests.transactions.RestconfTransaction;
57 import org.opendaylight.restconf.nb.rfc8040.rests.utils.DeleteDataTransactionUtil;
58 import org.opendaylight.restconf.nb.rfc8040.rests.utils.PatchDataTransactionUtil;
59 import org.opendaylight.restconf.nb.rfc8040.rests.utils.PlainPatchDataTransactionUtil;
60 import org.opendaylight.restconf.nb.rfc8040.rests.utils.PostDataTransactionUtil;
61 import org.opendaylight.restconf.nb.rfc8040.rests.utils.PutDataTransactionUtil;
62 import org.opendaylight.restconf.nb.rfc8040.rests.utils.ReadDataTransactionUtil;
63 import org.opendaylight.restconf.nb.rfc8040.rests.utils.RestconfDataServiceConstant;
64 import org.opendaylight.restconf.nb.rfc8040.rests.utils.RestconfDataServiceConstant.PostPutQueryParameters.Insert;
65 import org.opendaylight.restconf.nb.rfc8040.rests.utils.RestconfInvokeOperationsUtil;
66 import org.opendaylight.restconf.nb.rfc8040.streams.Configuration;
67 import org.opendaylight.restconf.nb.rfc8040.streams.listeners.NotificationListenerAdapter;
68 import org.opendaylight.restconf.nb.rfc8040.utils.mapping.RestconfMappingNodeUtil;
69 import org.opendaylight.restconf.nb.rfc8040.utils.parser.IdentifierCodec;
70 import org.opendaylight.restconf.nb.rfc8040.utils.parser.ParserIdentifier;
71 import org.opendaylight.yang.gen.v1.urn.sal.restconf.event.subscription.rev140708.NotificationOutputTypeGrouping.NotificationOutputType;
72 import org.opendaylight.yangtools.concepts.Immutable;
73 import org.opendaylight.yangtools.yang.common.QName;
74 import org.opendaylight.yangtools.yang.common.Revision;
75 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
76 import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode;
77 import org.opendaylight.yangtools.yang.data.api.schema.MapEntryNode;
78 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
79 import org.opendaylight.yangtools.yang.model.api.ActionDefinition;
80 import org.opendaylight.yangtools.yang.model.api.EffectiveModelContext;
81 import org.opendaylight.yangtools.yang.model.api.NotificationDefinition;
82 import org.opendaylight.yangtools.yang.model.api.SchemaNode;
83 import org.opendaylight.yangtools.yang.model.api.stmt.SchemaNodeIdentifier.Absolute;
84 import org.slf4j.Logger;
85 import org.slf4j.LoggerFactory;
88 * Implementation of {@link RestconfDataService}.
91 public class RestconfDataServiceImpl implements RestconfDataService {
92 // FIXME: we should be able to interpret 'point' and refactor this class into a behavior
93 private static final class QueryParams implements Immutable {
94 final @Nullable String point;
95 final @Nullable Insert insert;
97 QueryParams(final @Nullable Insert insert, final @Nullable String point) {
103 private static final Logger LOG = LoggerFactory.getLogger(RestconfDataServiceImpl.class);
104 private static final DateTimeFormatter FORMATTER = DateTimeFormatter.ofPattern("yyyy-MMM-dd HH:mm:ss");
106 private final RestconfStreamsSubscriptionService delegRestconfSubscrService;
107 private final SubscribeToStreamUtil streamUtils;
109 // FIXME: evaluate thread-safety of updates (synchronized) vs. access (mostly unsynchronized) here
110 private SchemaContextHandler schemaContextHandler;
111 private TransactionChainHandler transactionChainHandler;
112 private DOMMountPointServiceHandler mountPointServiceHandler;
113 private volatile ActionServiceHandler actionServiceHandler;
115 public RestconfDataServiceImpl(final SchemaContextHandler schemaContextHandler,
116 final TransactionChainHandler transactionChainHandler,
117 final DOMMountPointServiceHandler mountPointServiceHandler,
118 final RestconfStreamsSubscriptionService delegRestconfSubscrService,
119 final ActionServiceHandler actionServiceHandler,
120 final Configuration configuration) {
121 this.actionServiceHandler = requireNonNull(actionServiceHandler);
122 this.schemaContextHandler = requireNonNull(schemaContextHandler);
123 this.transactionChainHandler = requireNonNull(transactionChainHandler);
124 this.mountPointServiceHandler = requireNonNull(mountPointServiceHandler);
125 this.delegRestconfSubscrService = requireNonNull(delegRestconfSubscrService);
126 streamUtils = configuration.isUseSSE() ? SubscribeToStreamUtil.serverSentEvents()
127 : SubscribeToStreamUtil.webSockets();
131 public synchronized void updateHandlers(final Object... handlers) {
132 for (final Object object : handlers) {
133 if (object instanceof SchemaContextHandler) {
134 schemaContextHandler = (SchemaContextHandler) object;
135 } else if (object instanceof ActionServiceHandler) {
136 actionServiceHandler = (ActionServiceHandler) object;
137 } else if (object instanceof DOMMountPointServiceHandler) {
138 mountPointServiceHandler = (DOMMountPointServiceHandler) object;
139 } else if (object instanceof TransactionChainHandler) {
140 transactionChainHandler = (TransactionChainHandler) object;
146 public Response readData(final UriInfo uriInfo) {
147 return readData(null, uriInfo);
151 public Response readData(final String identifier, final UriInfo uriInfo) {
152 final EffectiveModelContext schemaContextRef = this.schemaContextHandler.get();
153 final InstanceIdentifierContext<?> instanceIdentifier = ParserIdentifier.toInstanceIdentifier(
154 identifier, schemaContextRef, Optional.of(this.mountPointServiceHandler.get()));
155 final WriterParameters parameters = ReadDataTransactionUtil.parseUriParameters(instanceIdentifier, uriInfo);
157 final DOMMountPoint mountPoint = instanceIdentifier.getMountPoint();
158 final RestconfStrategy strategy = getRestconfStrategy(mountPoint);
159 final NormalizedNode<?, ?> node;
160 if (parameters.getFieldPaths() != null && !parameters.getFieldPaths().isEmpty()) {
161 node = ReadDataTransactionUtil.readData(parameters.getContent(), instanceIdentifier.getInstanceIdentifier(),
162 strategy, parameters.getWithDefault(), schemaContextRef, parameters.getFieldPaths());
164 node = readData(identifier, parameters.getContent(), instanceIdentifier.getInstanceIdentifier(), strategy,
165 parameters.getWithDefault(), schemaContextRef, uriInfo);
167 if (identifier != null && identifier.contains(STREAM_PATH) && identifier.contains(STREAM_ACCESS_PATH_PART)
168 && identifier.contains(STREAM_LOCATION_PATH_PART)) {
169 final String value = (String) node.getValue();
170 final String streamName = value.substring(value.indexOf(NOTIFICATION_STREAM + '/'));
171 this.delegRestconfSubscrService.subscribeToStream(streamName, uriInfo);
174 throw new RestconfDocumentedException(
175 "Request could not be completed because the relevant data model content does not exist",
176 RestconfError.ErrorType.PROTOCOL,
177 RestconfError.ErrorTag.DATA_MISSING);
180 if (parameters.getContent().equals(RestconfDataServiceConstant.ReadData.ALL)
181 || parameters.getContent().equals(RestconfDataServiceConstant.ReadData.CONFIG)) {
182 final QName type = node.getNodeType();
183 return Response.status(200)
184 .entity(new NormalizedNodeContext(instanceIdentifier, node, parameters))
185 .header("ETag", '"' + type.getModule().getRevision().map(Revision::toString).orElse(null)
186 + "-" + type.getLocalName() + '"')
187 .header("Last-Modified", FORMATTER.format(LocalDateTime.now(Clock.systemUTC())))
191 return Response.status(200).entity(new NormalizedNodeContext(instanceIdentifier, node, parameters)).build();
195 * Read specific type of data from data store via transaction and if identifier read data from
196 * streams then put streams from actual schema context to datastore.
198 * @param identifier identifier of data to read
199 * @param content type of data to read (config, state, all)
200 * @param strategy {@link RestconfStrategy} - object that perform the actual DS operations
201 * @param withDefa value of with-defaults parameter
202 * @param schemaContext schema context
203 * @param uriInfo uri info
204 * @return {@link NormalizedNode}
206 private NormalizedNode<?, ?> readData(final String identifier, final String content,
207 final YangInstanceIdentifier path, final RestconfStrategy strategy, final String withDefa,
208 final EffectiveModelContext schemaContext, final UriInfo uriInfo) {
209 if (identifier != null && identifier.contains(STREAMS_PATH) && !identifier.contains(STREAM_PATH_PART)) {
210 createAllYangNotificationStreams(strategy, schemaContext, uriInfo);
212 return ReadDataTransactionUtil.readData(content, path, strategy, withDefa, schemaContext);
215 private void createAllYangNotificationStreams(final RestconfStrategy strategy,
216 final EffectiveModelContext schemaContext, final UriInfo uriInfo) {
217 final RestconfTransaction transaction = strategy.prepareWriteExecution();
218 final boolean exist = checkExist(schemaContext, strategy);
220 for (final NotificationDefinition notificationDefinition : schemaContext.getNotifications()) {
221 final NotificationListenerAdapter notifiStreamXML =
222 CreateStreamUtil.createYangNotifiStream(notificationDefinition, schemaContext,
223 NotificationOutputType.XML);
224 final NotificationListenerAdapter notifiStreamJSON =
225 CreateStreamUtil.createYangNotifiStream(notificationDefinition, schemaContext,
226 NotificationOutputType.JSON);
227 writeNotificationStreamToDatastore(schemaContext, uriInfo, transaction, exist, notifiStreamXML);
228 writeNotificationStreamToDatastore(schemaContext, uriInfo, transaction, exist, notifiStreamJSON);
231 transaction.commit().get();
232 } catch (final InterruptedException | ExecutionException e) {
233 throw new RestconfDocumentedException("Problem while putting data to DS.", e);
237 private void writeNotificationStreamToDatastore(final EffectiveModelContext schemaContext,
238 final UriInfo uriInfo, final RestconfTransaction transaction, final boolean exist,
239 final NotificationListenerAdapter listener) {
240 final URI uri = streamUtils.prepareUriByStreamName(uriInfo, listener.getStreamName());
241 final MapEntryNode mapToStreams = RestconfMappingNodeUtil.mapYangNotificationStreamByIetfRestconfMonitoring(
242 listener.getSchemaPath().lastNodeIdentifier(), schemaContext.getNotifications(), null,
243 listener.getOutputType(), uri, SubscribeToStreamUtil.getMonitoringModule(schemaContext));
245 final String name = listener.getSchemaPath().lastNodeIdentifier().getLocalName();
248 pathId = Rfc8040.MonitoringModule.PATH_TO_STREAM_WITHOUT_KEY + name;
250 pathId = Rfc8040.MonitoringModule.PATH_TO_STREAMS;
252 transaction.merge(LogicalDatastoreType.OPERATIONAL, IdentifierCodec.deserialize(pathId, schemaContext),
256 private static boolean checkExist(final EffectiveModelContext schemaContext, final RestconfStrategy strategy) {
258 return strategy.exists(LogicalDatastoreType.OPERATIONAL,
259 IdentifierCodec.deserialize(Rfc8040.MonitoringModule.PATH_TO_STREAMS, schemaContext)).get();
260 } catch (final InterruptedException | ExecutionException exception) {
261 throw new RestconfDocumentedException("Problem while checking data if exists", exception);
266 public Response putData(final String identifier, final NormalizedNodeContext payload, final UriInfo uriInfo) {
267 requireNonNull(payload);
269 final QueryParams checkedParms = checkQueryParameters(uriInfo);
271 final InstanceIdentifierContext<? extends SchemaNode> iid = payload.getInstanceIdentifierContext();
273 PutDataTransactionUtil.validInputData(iid.getSchemaNode(), payload);
274 PutDataTransactionUtil.validTopLevelNodeName(iid.getInstanceIdentifier(), payload);
275 PutDataTransactionUtil.validateListKeysEqualityInPayloadAndUri(payload);
277 final DOMMountPoint mountPoint = payload.getInstanceIdentifierContext().getMountPoint();
278 final EffectiveModelContext ref = mountPoint == null
279 ? this.schemaContextHandler.get() : modelContext(mountPoint);
281 final RestconfStrategy strategy = getRestconfStrategy(mountPoint);
282 return PutDataTransactionUtil.putData(payload, ref, strategy, checkedParms.insert, checkedParms.point);
285 private static QueryParams checkQueryParameters(final UriInfo uriInfo) {
286 boolean insertUsed = false;
287 boolean pointUsed = false;
288 Insert insert = null;
291 for (final Entry<String, List<String>> entry : uriInfo.getQueryParameters().entrySet()) {
292 switch (entry.getKey()) {
295 throw new RestconfDocumentedException("Insert parameter can be used only once.",
296 RestconfError.ErrorType.PROTOCOL, RestconfError.ErrorTag.BAD_ELEMENT);
300 final String str = entry.getValue().get(0);
301 insert = Insert.forValue(str);
302 if (insert == null) {
303 throw new RestconfDocumentedException("Unrecognized insert parameter value '" + str + "'",
304 RestconfError.ErrorType.PROTOCOL, RestconfError.ErrorTag.BAD_ELEMENT);
309 throw new RestconfDocumentedException("Point parameter can be used only once.",
310 RestconfError.ErrorType.PROTOCOL, RestconfError.ErrorTag.BAD_ELEMENT);
314 point = entry.getValue().get(0);
317 throw new RestconfDocumentedException("Bad parameter for post: " + entry.getKey(),
318 RestconfError.ErrorType.PROTOCOL, RestconfError.ErrorTag.BAD_ELEMENT);
322 checkQueryParams(insertUsed, pointUsed, insert);
323 return new QueryParams(insert, point);
326 private static void checkQueryParams(final boolean insertUsed, final boolean pointUsed, final Insert insert) {
329 throw new RestconfDocumentedException("Point parameter can't be used without Insert parameter.",
330 RestconfError.ErrorType.PROTOCOL, RestconfError.ErrorTag.BAD_ELEMENT);
333 if (insert != Insert.BEFORE && insert != Insert.AFTER) {
334 throw new RestconfDocumentedException(
335 "Point parameter can be used only with 'after' or 'before' values of Insert parameter.",
336 RestconfError.ErrorType.PROTOCOL, RestconfError.ErrorTag.BAD_ELEMENT);
342 public Response postData(final String identifier, final NormalizedNodeContext payload, final UriInfo uriInfo) {
343 return postData(payload, uriInfo);
347 public Response postData(final NormalizedNodeContext payload, final UriInfo uriInfo) {
348 requireNonNull(payload);
349 if (payload.getInstanceIdentifierContext().getSchemaNode() instanceof ActionDefinition) {
350 return invokeAction(payload);
353 final QueryParams checkedParms = checkQueryParameters(uriInfo);
354 final DOMMountPoint mountPoint = payload.getInstanceIdentifierContext().getMountPoint();
355 final RestconfStrategy strategy = getRestconfStrategy(mountPoint);
356 return PostDataTransactionUtil.postData(uriInfo, payload, strategy,
357 getSchemaContext(mountPoint), checkedParms.insert, checkedParms.point);
361 public Response deleteData(final String identifier) {
362 final InstanceIdentifierContext<?> instanceIdentifier = ParserIdentifier.toInstanceIdentifier(
363 identifier, this.schemaContextHandler.get(), Optional.of(this.mountPointServiceHandler.get()));
365 final DOMMountPoint mountPoint = instanceIdentifier.getMountPoint();
366 final RestconfStrategy strategy = getRestconfStrategy(mountPoint);
367 return DeleteDataTransactionUtil.deleteData(strategy, instanceIdentifier.getInstanceIdentifier());
371 public PatchStatusContext patchData(final String identifier, final PatchContext context, final UriInfo uriInfo) {
372 return patchData(context, uriInfo);
376 public PatchStatusContext patchData(final PatchContext context, final UriInfo uriInfo) {
377 final DOMMountPoint mountPoint = requireNonNull(context).getInstanceIdentifierContext().getMountPoint();
378 final RestconfStrategy strategy = getRestconfStrategy(mountPoint);
379 return PatchDataTransactionUtil.patchData(context, strategy, getSchemaContext(mountPoint));
383 public Response patchData(final String identifier, final NormalizedNodeContext payload, final UriInfo uriInfo) {
384 requireNonNull(payload);
386 final InstanceIdentifierContext<? extends SchemaNode> iid = payload
387 .getInstanceIdentifierContext();
389 PutDataTransactionUtil.validInputData(iid.getSchemaNode(), payload);
390 PutDataTransactionUtil.validTopLevelNodeName(iid.getInstanceIdentifier(), payload);
391 PutDataTransactionUtil.validateListKeysEqualityInPayloadAndUri(payload);
393 final DOMMountPoint mountPoint = payload.getInstanceIdentifierContext().getMountPoint();
394 final EffectiveModelContext ref = mountPoint == null
395 ? this.schemaContextHandler.get() : modelContext(mountPoint);
396 final RestconfStrategy strategy = getRestconfStrategy(mountPoint);
398 return PlainPatchDataTransactionUtil.patchData(payload, strategy, ref);
401 private EffectiveModelContext getSchemaContext(final DOMMountPoint mountPoint) {
402 return mountPoint == null ? schemaContextHandler.get() : modelContext(mountPoint);
405 // FIXME: why is this synchronized?
406 public synchronized RestconfStrategy getRestconfStrategy(final DOMMountPoint mountPoint) {
407 if (mountPoint == null) {
408 return new MdsalRestconfStrategy(transactionChainHandler);
411 return RestconfStrategy.forMountPoint(mountPoint).orElseThrow(() -> {
412 LOG.warn("Mount point {} does not expose a suitable access interface", mountPoint.getIdentifier());
413 return new RestconfDocumentedException("Could not find a supported access interface in mount point "
414 + mountPoint.getIdentifier());
419 * Invoke Action operation.
421 * @param payload {@link NormalizedNodeContext} - the body of the operation
422 * @return {@link NormalizedNodeContext} wrapped in {@link Response}
424 public Response invokeAction(final NormalizedNodeContext payload) {
425 final InstanceIdentifierContext<?> context = payload.getInstanceIdentifierContext();
426 final DOMMountPoint mountPoint = context.getMountPoint();
427 final Absolute schemaPath = Absolute.of(ImmutableList.copyOf(context.getSchemaNode().getPath()
428 .getPathFromRoot()));
429 final YangInstanceIdentifier yangIIdContext = context.getInstanceIdentifier();
430 final NormalizedNode<?, ?> data = payload.getData();
432 if (yangIIdContext.isEmpty() && !RestconfDataServiceConstant.NETCONF_BASE_QNAME.equals(data.getNodeType())) {
433 throw new RestconfDocumentedException("Instance identifier need to contain at least one path argument",
434 ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE);
437 final DOMActionResult response;
438 final EffectiveModelContext schemaContextRef;
439 if (mountPoint != null) {
440 response = RestconfInvokeOperationsUtil.invokeActionViaMountPoint(mountPoint, (ContainerNode) data,
441 schemaPath, yangIIdContext);
442 schemaContextRef = modelContext(mountPoint);
444 response = RestconfInvokeOperationsUtil.invokeAction((ContainerNode) data, schemaPath,
445 this.actionServiceHandler, yangIIdContext);
446 schemaContextRef = this.schemaContextHandler.get();
448 final DOMActionResult result = RestconfInvokeOperationsUtil.checkActionResponse(response);
450 ActionDefinition resultNodeSchema = null;
451 ContainerNode resultData = null;
452 if (result != null) {
453 final Optional<ContainerNode> optOutput = result.getOutput();
454 if (optOutput.isPresent()) {
455 resultData = optOutput.get();
456 resultNodeSchema = (ActionDefinition) context.getSchemaNode();
460 if (resultData != null && resultData.getValue().isEmpty()) {
461 throw new WebApplicationException(Response.Status.NO_CONTENT);
464 return Response.status(200).entity(new NormalizedNodeContext(new InstanceIdentifierContext<>(yangIIdContext,
465 resultNodeSchema, mountPoint, schemaContextRef), resultData)).build();
468 private static EffectiveModelContext modelContext(final DOMMountPoint mountPoint) {
469 return mountPoint.getService(DOMSchemaService.class)
470 .flatMap(svc -> Optional.ofNullable(svc.getGlobalContext()))