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;
12 import com.google.common.collect.ImmutableSet;
13 import java.util.Collection;
15 import java.util.stream.Collectors;
16 import org.eclipse.jdt.annotation.Nullable;
17 import org.opendaylight.mdsal.common.api.LogicalDatastoreType;
18 import org.opendaylight.mdsal.dom.api.DOMMountPoint;
19 import org.opendaylight.mdsal.dom.api.DOMMountPointService;
20 import org.opendaylight.mdsal.dom.api.DOMNotificationService;
21 import org.opendaylight.mdsal.dom.api.DOMRpcResult;
22 import org.opendaylight.mdsal.dom.api.DOMSchemaService;
23 import org.opendaylight.mdsal.dom.spi.DefaultDOMRpcResult;
24 import org.opendaylight.restconf.common.errors.RestconfDocumentedException;
25 import org.opendaylight.restconf.nb.rfc8040.legacy.NormalizedNodePayload;
26 import org.opendaylight.restconf.nb.rfc8040.rests.utils.RestconfStreamsConstants;
27 import org.opendaylight.restconf.nb.rfc8040.streams.listeners.DeviceNotificationListenerAdaptor;
28 import org.opendaylight.restconf.nb.rfc8040.streams.listeners.ListenersBroker;
29 import org.opendaylight.restconf.nb.rfc8040.streams.listeners.NotificationListenerAdapter;
30 import org.opendaylight.restconf.nb.rfc8040.utils.parser.IdentifierCodec;
31 import org.opendaylight.yang.gen.v1.urn.opendaylight.device.notification.rev221106.SubscribeDeviceNotificationInput;
32 import org.opendaylight.yang.gen.v1.urn.opendaylight.device.notification.rev221106.SubscribeDeviceNotificationOutput;
33 import org.opendaylight.yang.gen.v1.urn.sal.restconf.event.subscription.rev140708.CreateDataChangeEventSubscriptionInput1.Scope;
34 import org.opendaylight.yang.gen.v1.urn.sal.restconf.event.subscription.rev140708.NotificationOutputTypeGrouping;
35 import org.opendaylight.yang.gen.v1.urn.sal.restconf.event.subscription.rev140708.NotificationOutputTypeGrouping.NotificationOutputType;
36 import org.opendaylight.yangtools.yang.common.ErrorTag;
37 import org.opendaylight.yangtools.yang.common.ErrorType;
38 import org.opendaylight.yangtools.yang.common.QName;
39 import org.opendaylight.yangtools.yang.common.QNameModule;
40 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
41 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.AugmentationIdentifier;
42 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
43 import org.opendaylight.yangtools.yang.data.api.schema.AugmentationNode;
44 import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode;
45 import org.opendaylight.yangtools.yang.data.api.schema.DataContainerChild;
46 import org.opendaylight.yangtools.yang.data.api.schema.LeafNode;
47 import org.opendaylight.yangtools.yang.data.impl.schema.Builders;
48 import org.opendaylight.yangtools.yang.data.impl.schema.ImmutableNodes;
49 import org.opendaylight.yangtools.yang.model.api.EffectiveModelContext;
50 import org.opendaylight.yangtools.yang.model.api.Module;
51 import org.opendaylight.yangtools.yang.model.api.NotificationDefinition;
52 import org.opendaylight.yangtools.yang.model.api.stmt.SchemaNodeIdentifier.Absolute;
53 import org.slf4j.Logger;
54 import org.slf4j.LoggerFactory;
57 * Utility class for creation of data-change-event or YANG notification streams.
59 final class CreateStreamUtil {
60 private static final Logger LOG = LoggerFactory.getLogger(CreateStreamUtil.class);
61 private static final QNameModule SAL_REMOTE_AUGMENT = NotificationOutputTypeGrouping.QNAME.getModule();
63 private static final QNameModule DEVICE_NOTIFICATION_MODULE = SubscribeDeviceNotificationInput.QNAME.getModule();
64 private static final QName DATASTORE_QNAME =
65 QName.create(SAL_REMOTE_AUGMENT, RestconfStreamsConstants.DATASTORE_PARAM_NAME).intern();
66 private static final QName SCOPE_QNAME =
67 QName.create(SAL_REMOTE_AUGMENT, RestconfStreamsConstants.SCOPE_PARAM_NAME).intern();
68 private static final QName OUTPUT_TYPE_QNAME =
69 QName.create(SAL_REMOTE_AUGMENT, "notification-output-type").intern();
70 private static final QName DEVICE_NOTIFICATION_PATH_QNAME =
71 QName.create(DEVICE_NOTIFICATION_MODULE, "path").intern();
72 private static final QName DEVICE_NOTIFICATION_STREAM_PATH =
73 QName.create(DEVICE_NOTIFICATION_PATH_QNAME, "stream-path").intern();
74 private static final NodeIdentifier DATASTORE_NODEID = NodeIdentifier.create(DATASTORE_QNAME);
75 private static final NodeIdentifier SCOPE_NODEID = NodeIdentifier.create(SCOPE_QNAME);
76 private static final NodeIdentifier OUTPUT_TYPE_NODEID = NodeIdentifier.create(OUTPUT_TYPE_QNAME);
77 private static final NodeIdentifier DEVICE_NOTIFICATION_PATH_NODEID =
78 NodeIdentifier.create(DEVICE_NOTIFICATION_PATH_QNAME);
79 private static final AugmentationIdentifier SAL_REMOTE_AUG_IDENTIFIER = new AugmentationIdentifier(
80 ImmutableSet.of(SCOPE_QNAME, DATASTORE_QNAME, OUTPUT_TYPE_QNAME));
82 private CreateStreamUtil() {
87 * Create data-change-event or notification stream with POST operation via RPC.
89 * @param payload Input of RPC - example in JSON (data-change-event stream):
94 * "path": "/toaster:toaster/toaster:toasterStatus",
95 * "sal-remote-augment:datastore": "OPERATIONAL",
96 * "sal-remote-augment:scope": "ONE"
101 * @param refSchemaCtx Reference to {@link EffectiveModelContext}.
102 * @return {@link DOMRpcResult} - Output of RPC - example in JSON:
107 * "stream-name": "toaster:toaster/toaster:toasterStatus/datastore=OPERATIONAL/scope=ONE"
113 static DOMRpcResult createDataChangeNotifiStream(final NormalizedNodePayload payload,
114 final EffectiveModelContext refSchemaCtx) {
115 // parsing out of container with settings and path
116 final ContainerNode data = (ContainerNode) requireNonNull(payload).getData();
117 final QName qname = payload.getInstanceIdentifierContext().getSchemaNode().getQName();
118 final YangInstanceIdentifier path = preparePath(data, qname);
120 // building of stream name
121 final StringBuilder streamNameBuilder = new StringBuilder(
122 prepareDataChangeNotifiStreamName(path, requireNonNull(refSchemaCtx), data));
123 final NotificationOutputType outputType = prepareOutputType(data);
124 if (outputType.equals(NotificationOutputType.JSON)) {
125 streamNameBuilder.append('/').append(outputType.getName());
127 final String streamName = streamNameBuilder.toString();
129 // registration of the listener
130 ListenersBroker.getInstance().registerDataChangeListener(path, streamName, outputType);
132 // building of output
133 final QName outputQname = QName.create(qname, "output");
134 final QName streamNameQname = QName.create(qname, "stream-name");
136 return new DefaultDOMRpcResult(Builders.containerBuilder()
137 .withNodeIdentifier(new NodeIdentifier(outputQname))
138 .withChild(ImmutableNodes.leafNode(streamNameQname, streamName))
143 * Create device notification stream.
145 * @param baseUrl base Url
146 * @param payload data
147 * @param refSchemaCtx Reference to {@link EffectiveModelContext}.
148 * @param streamUtil stream utility
149 * @param mountPointService dom mount point service
150 * @return {@link DOMRpcResult} - Output of RPC - example in JSON
152 static DOMRpcResult createDeviceNotificationListener(final String baseUrl, final NormalizedNodePayload payload,
153 final EffectiveModelContext refSchemaCtx, final SubscribeToStreamUtil streamUtil,
154 final DOMMountPointService mountPointService) {
155 // parsing out of container with settings and path
156 final ContainerNode data = (ContainerNode) requireNonNull(payload).getData();
157 final YangInstanceIdentifier value =
158 (YangInstanceIdentifier) data.findChildByArg(DEVICE_NOTIFICATION_PATH_NODEID)
159 .map(DataContainerChild::body)
160 .orElseThrow(() -> new RestconfDocumentedException("Mount point not available", ErrorType.APPLICATION,
161 ErrorTag.OPERATION_FAILED));
163 // FIXME: just beautiful: a ClassCastException if it is something different!
164 final String deviceName =
165 ((YangInstanceIdentifier.NodeIdentifierWithPredicates.Singleton)value.getLastPathArgument())
166 .values().getElement().toString();
168 final DOMMountPoint mountPoint = mountPointService.getMountPoint(value)
169 .orElseThrow(() -> new RestconfDocumentedException("Mount point not available", ErrorType.APPLICATION,
170 ErrorTag.OPERATION_FAILED));
172 final NotificationOutputType outputType = prepareOutputType(data);
174 // FIXME: what is the relationship to the unused refSchemaCtx?
175 final EffectiveModelContext mountModelContext = mountPoint.getService(DOMSchemaService.class)
176 .orElseThrow(() -> new RestconfDocumentedException("Mount point schema not available",
177 ErrorType.APPLICATION, ErrorTag.OPERATION_FAILED))
179 final Collection<? extends NotificationDefinition> notifications = mountModelContext.getNotifications();
180 if (notifications.isEmpty()) {
181 throw new RestconfDocumentedException("Device does not support notification", ErrorType.APPLICATION,
182 ErrorTag.OPERATION_FAILED);
185 final Set<Absolute> absolutes = notifications.stream()
186 .map(notificationDefinition -> Absolute.of(notificationDefinition.getQName()))
187 .collect(Collectors.toUnmodifiableSet());
189 final DeviceNotificationListenerAdaptor notificationListenerAdapter = ListenersBroker.getInstance()
190 .registerDeviceNotificationListener(deviceName, outputType, mountModelContext, mountPointService,
191 mountPoint.getIdentifier());
192 notificationListenerAdapter.listen(mountPoint.getService(DOMNotificationService.class).get(), absolutes);
194 // building of output
195 return new DefaultDOMRpcResult(Builders.containerBuilder()
196 .withNodeIdentifier(new NodeIdentifier(SubscribeDeviceNotificationOutput.QNAME))
197 .withChild(ImmutableNodes.leafNode(DEVICE_NOTIFICATION_STREAM_PATH, baseUrl + deviceName
198 + "?" + RestconfStreamsConstants.NOTIFICATION_TYPE + "=" + RestconfStreamsConstants.DEVICE))
203 * Prepare {@link NotificationOutputType}.
205 * @param data Container with stream settings (RPC create-stream).
206 * @return Parsed {@link NotificationOutputType}.
208 private static NotificationOutputType prepareOutputType(final ContainerNode data) {
209 final String outputName = extractStringLeaf(data, OUTPUT_TYPE_NODEID);
210 return outputName != null ? NotificationOutputType.valueOf(outputName) : NotificationOutputType.XML;
214 * Prepare stream name.
216 * @param path Path of element from which data-change-event notifications are going to be generated.
217 * @param schemaContext Schema context.
218 * @param data Container with stream settings (RPC create-stream).
219 * @return Parsed stream name.
221 private static String prepareDataChangeNotifiStreamName(final YangInstanceIdentifier path,
222 final EffectiveModelContext schemaContext, final ContainerNode data) {
223 final String datastoreName = extractStringLeaf(data, DATASTORE_NODEID);
224 final LogicalDatastoreType datastoreType = datastoreName != null ? LogicalDatastoreType.valueOf(datastoreName)
225 : LogicalDatastoreType.CONFIGURATION;
227 final String scopeName = extractStringLeaf(data, SCOPE_NODEID);
228 // FIXME: this is not really used
229 final Scope scope = scopeName != null ? Scope.ofName(scopeName) : Scope.BASE;
231 return RestconfStreamsConstants.DATA_SUBSCRIPTION
232 + "/" + ListenersBroker.createStreamNameFromUri(IdentifierCodec.serialize(path, schemaContext)
233 + "/" + RestconfStreamsConstants.DATASTORE_PARAM_NAME + "=" + datastoreType
234 + "/" + RestconfStreamsConstants.SCOPE_PARAM_NAME + "=" + scope);
238 * Prepare {@link YangInstanceIdentifier} of stream source.
240 * @param data Container with stream settings (RPC create-stream).
241 * @param qualifiedName QName of the input RPC context (used only in debugging).
242 * @return Parsed {@link YangInstanceIdentifier} of data element from which the data-change-event notifications
243 * are going to be generated.
245 private static YangInstanceIdentifier preparePath(final ContainerNode data, final QName qualifiedName) {
246 final Object pathValue = data.findChildByArg(new NodeIdentifier(QName.create(qualifiedName, "path")))
247 .map(DataContainerChild::body)
249 if (!(pathValue instanceof YangInstanceIdentifier)) {
250 LOG.debug("Instance identifier {} was not normalized correctly", qualifiedName);
251 throw new RestconfDocumentedException(
252 "Instance identifier was not normalized correctly",
253 ErrorType.APPLICATION,
254 ErrorTag.OPERATION_FAILED);
256 return (YangInstanceIdentifier) pathValue;
259 private static @Nullable String extractStringLeaf(final ContainerNode data, final NodeIdentifier childName) {
260 final DataContainerChild augNode = data.childByArg(SAL_REMOTE_AUG_IDENTIFIER);
261 if (augNode instanceof AugmentationNode) {
262 final DataContainerChild enumNode = ((AugmentationNode) augNode).childByArg(childName);
263 if (enumNode instanceof LeafNode) {
264 final Object value = enumNode.body();
265 if (value instanceof String) {
266 return (String) value;
274 * Create YANG notification stream using notification definition in YANG schema.
276 * @param notificationDefinition YANG notification definition.
277 * @param refSchemaCtx Reference to {@link EffectiveModelContext}
278 * @param outputType Output type (XML or JSON).
279 * @return {@link NotificationListenerAdapter}
281 static NotificationListenerAdapter createYangNotifiStream(final NotificationDefinition notificationDefinition,
282 final EffectiveModelContext refSchemaCtx, final NotificationOutputType outputType) {
283 final var streamName = parseNotificationStreamName(requireNonNull(notificationDefinition),
284 requireNonNull(refSchemaCtx), requireNonNull(outputType.getName()));
285 final var listenersBroker = ListenersBroker.getInstance();
287 final var existing = listenersBroker.notificationListenerFor(streamName);
288 return existing != null ? existing
289 : listenersBroker.registerNotificationListener(
290 Absolute.of(notificationDefinition.getQName()), streamName, outputType);
293 private static String parseNotificationStreamName(final NotificationDefinition notificationDefinition,
294 final EffectiveModelContext refSchemaCtx, final String outputType) {
295 final QName notificationDefinitionQName = notificationDefinition.getQName();
296 final Module module = refSchemaCtx.findModule(
297 notificationDefinitionQName.getModule().getNamespace(),
298 notificationDefinitionQName.getModule().getRevision()).orElse(null);
299 requireNonNull(module, String.format("Module for namespace %s does not exist.",
300 notificationDefinitionQName.getModule().getNamespace()));
302 final StringBuilder streamNameBuilder = new StringBuilder();
303 streamNameBuilder.append(RestconfStreamsConstants.NOTIFICATION_STREAM)
305 .append(module.getName())
307 .append(notificationDefinitionQName.getLocalName());
308 if (outputType.equals(NotificationOutputType.JSON.getName())) {
309 streamNameBuilder.append('/').append(NotificationOutputType.JSON.getName());
311 return streamNameBuilder.toString();