Bump upstream versions
[netconf.git] / restconf / restconf-nb-rfc8040 / src / main / java / org / opendaylight / restconf / nb / rfc8040 / rests / services / impl / CreateStreamUtil.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
12 import com.google.common.collect.ImmutableSet;
13 import java.util.Optional;
14 import org.eclipse.jdt.annotation.Nullable;
15 import org.opendaylight.mdsal.common.api.LogicalDatastoreType;
16 import org.opendaylight.mdsal.dom.api.DOMRpcResult;
17 import org.opendaylight.mdsal.dom.spi.DefaultDOMRpcResult;
18 import org.opendaylight.restconf.common.errors.RestconfDocumentedException;
19 import org.opendaylight.restconf.nb.rfc8040.legacy.NormalizedNodePayload;
20 import org.opendaylight.restconf.nb.rfc8040.rests.utils.RestconfStreamsConstants;
21 import org.opendaylight.restconf.nb.rfc8040.streams.listeners.ListenersBroker;
22 import org.opendaylight.restconf.nb.rfc8040.streams.listeners.NotificationListenerAdapter;
23 import org.opendaylight.restconf.nb.rfc8040.utils.parser.IdentifierCodec;
24 import org.opendaylight.yang.gen.v1.urn.sal.restconf.event.subscription.rev140708.CreateDataChangeEventSubscriptionInput1.Scope;
25 import org.opendaylight.yang.gen.v1.urn.sal.restconf.event.subscription.rev140708.NotificationOutputTypeGrouping.NotificationOutputType;
26 import org.opendaylight.yangtools.yang.common.ErrorTag;
27 import org.opendaylight.yangtools.yang.common.ErrorType;
28 import org.opendaylight.yangtools.yang.common.QName;
29 import org.opendaylight.yangtools.yang.common.QNameModule;
30 import org.opendaylight.yangtools.yang.common.Revision;
31 import org.opendaylight.yangtools.yang.common.XMLNamespace;
32 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
33 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.AugmentationIdentifier;
34 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
35 import org.opendaylight.yangtools.yang.data.api.schema.AugmentationNode;
36 import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode;
37 import org.opendaylight.yangtools.yang.data.api.schema.DataContainerChild;
38 import org.opendaylight.yangtools.yang.data.api.schema.LeafNode;
39 import org.opendaylight.yangtools.yang.data.impl.schema.ImmutableNodes;
40 import org.opendaylight.yangtools.yang.data.impl.schema.builder.impl.ImmutableContainerNodeBuilder;
41 import org.opendaylight.yangtools.yang.model.api.EffectiveModelContext;
42 import org.opendaylight.yangtools.yang.model.api.Module;
43 import org.opendaylight.yangtools.yang.model.api.NotificationDefinition;
44 import org.opendaylight.yangtools.yang.model.api.stmt.SchemaNodeIdentifier.Absolute;
45 import org.slf4j.Logger;
46 import org.slf4j.LoggerFactory;
47
48 /**
49  * Utility class for creation of data-change-event or YANG notification streams.
50  */
51 final class CreateStreamUtil {
52     private static final Logger LOG = LoggerFactory.getLogger(CreateStreamUtil.class);
53     private static final QNameModule SAL_REMOTE_AUGMENT = QNameModule.create(
54         XMLNamespace.of("urn:sal:restconf:event:subscription"), Revision.of("2014-07-08"));
55     private static final QName DATASTORE_QNAME =
56         QName.create(SAL_REMOTE_AUGMENT, RestconfStreamsConstants.DATASTORE_PARAM_NAME).intern();
57     private static final QName SCOPE_QNAME =
58         QName.create(SAL_REMOTE_AUGMENT, RestconfStreamsConstants.SCOPE_PARAM_NAME).intern();
59     private static final QName OUTPUT_TYPE_QNAME =
60         QName.create(SAL_REMOTE_AUGMENT, "notification-output-type").intern();
61     private static final NodeIdentifier DATASTORE_NODEID = NodeIdentifier.create(DATASTORE_QNAME);
62     private static final NodeIdentifier SCOPE_NODEID = NodeIdentifier.create(SCOPE_QNAME);
63     private static final NodeIdentifier OUTPUT_TYPE_NODEID = NodeIdentifier.create(OUTPUT_TYPE_QNAME);
64
65     private static final AugmentationIdentifier SAL_REMOTE_AUG_IDENTIFIER = new AugmentationIdentifier(
66         ImmutableSet.of(SCOPE_QNAME, DATASTORE_QNAME, OUTPUT_TYPE_QNAME));
67
68     private CreateStreamUtil() {
69         // Hidden on purpose
70     }
71
72     /**
73      * Create data-change-event or notification stream with POST operation via RPC.
74      *
75      * @param payload      Input of RPC - example in JSON (data-change-event stream):
76      *                     <pre>
77      *                     {@code
78      *                         {
79      *                             "input": {
80      *                                 "path": "/toaster:toaster/toaster:toasterStatus",
81      *                                 "sal-remote-augment:datastore": "OPERATIONAL",
82      *                                 "sal-remote-augment:scope": "ONE"
83      *                             }
84      *                         }
85      *                     }
86      *                     </pre>
87      * @param refSchemaCtx Reference to {@link EffectiveModelContext}.
88      * @return {@link DOMRpcResult} - Output of RPC - example in JSON:
89      *     <pre>
90      *     {@code
91      *         {
92      *             "output": {
93      *                 "stream-name": "toaster:toaster/toaster:toasterStatus/datastore=OPERATIONAL/scope=ONE"
94      *             }
95      *         }
96      *     }
97      *     </pre>
98      */
99     static DOMRpcResult createDataChangeNotifiStream(final NormalizedNodePayload payload,
100             final EffectiveModelContext refSchemaCtx) {
101         // parsing out of container with settings and path
102         final ContainerNode data = (ContainerNode) requireNonNull(payload).getData();
103         final QName qname = payload.getInstanceIdentifierContext().getSchemaNode().getQName();
104         final YangInstanceIdentifier path = preparePath(data, qname);
105
106         // building of stream name
107         final StringBuilder streamNameBuilder = new StringBuilder(
108                 prepareDataChangeNotifiStreamName(path, requireNonNull(refSchemaCtx), data));
109         final NotificationOutputType outputType = prepareOutputType(data);
110         if (outputType.equals(NotificationOutputType.JSON)) {
111             streamNameBuilder.append('/').append(outputType.getName());
112         }
113         final String streamName = streamNameBuilder.toString();
114
115         // registration of the listener
116         ListenersBroker.getInstance().registerDataChangeListener(path, streamName, outputType);
117
118         // building of output
119         final QName outputQname = QName.create(qname, "output");
120         final QName streamNameQname = QName.create(qname, "stream-name");
121
122         final ContainerNode output = ImmutableContainerNodeBuilder.create()
123                 .withNodeIdentifier(new NodeIdentifier(outputQname))
124                 .withChild(ImmutableNodes.leafNode(streamNameQname, streamName)).build();
125         return new DefaultDOMRpcResult(output);
126     }
127
128     /**
129      * Prepare {@link NotificationOutputType}.
130      *
131      * @param data Container with stream settings (RPC create-stream).
132      * @return Parsed {@link NotificationOutputType}.
133      */
134     private static NotificationOutputType prepareOutputType(final ContainerNode data) {
135         final String outputName = extractStringLeaf(data, OUTPUT_TYPE_NODEID);
136         return outputName != null ? NotificationOutputType.valueOf(outputName) : NotificationOutputType.XML;
137     }
138
139     /**
140      * Prepare stream name.
141      *
142      * @param path          Path of element from which data-change-event notifications are going to be generated.
143      * @param schemaContext Schema context.
144      * @param data          Container with stream settings (RPC create-stream).
145      * @return Parsed stream name.
146      */
147     private static String prepareDataChangeNotifiStreamName(final YangInstanceIdentifier path,
148             final EffectiveModelContext schemaContext, final ContainerNode data) {
149         final String datastoreName = extractStringLeaf(data, DATASTORE_NODEID);
150         final LogicalDatastoreType datastoreType = datastoreName != null ? LogicalDatastoreType.valueOf(datastoreName)
151             : LogicalDatastoreType.CONFIGURATION;
152
153         final String scopeName = extractStringLeaf(data, SCOPE_NODEID);
154         // FIXME: this is not really used
155         final Scope scope = scopeName != null ? Scope.ofName(scopeName) : Scope.BASE;
156
157         return RestconfStreamsConstants.DATA_SUBSCRIPTION
158             + "/" + ListenersBroker.createStreamNameFromUri(IdentifierCodec.serialize(path, schemaContext)
159                 + "/" + RestconfStreamsConstants.DATASTORE_PARAM_NAME + "=" + datastoreType
160                 + "/" + RestconfStreamsConstants.SCOPE_PARAM_NAME + "=" + scope);
161     }
162
163     /**
164      * Prepare {@link YangInstanceIdentifier} of stream source.
165      *
166      * @param data          Container with stream settings (RPC create-stream).
167      * @param qualifiedName QName of the input RPC context (used only in debugging).
168      * @return Parsed {@link YangInstanceIdentifier} of data element from which the data-change-event notifications
169      *     are going to be generated.
170      */
171     private static YangInstanceIdentifier preparePath(final ContainerNode data, final QName qualifiedName) {
172         final Object pathValue = data.findChildByArg(new NodeIdentifier(QName.create(qualifiedName, "path")))
173             .map(DataContainerChild::body)
174             .orElse(null);
175         if (!(pathValue instanceof YangInstanceIdentifier)) {
176             LOG.debug("Instance identifier {} was not normalized correctly", qualifiedName);
177             throw new RestconfDocumentedException(
178                     "Instance identifier was not normalized correctly",
179                     ErrorType.APPLICATION,
180                     ErrorTag.OPERATION_FAILED);
181         }
182         return (YangInstanceIdentifier) pathValue;
183     }
184
185     private static @Nullable String extractStringLeaf(final ContainerNode data, final NodeIdentifier childName) {
186         final DataContainerChild augNode = data.childByArg(SAL_REMOTE_AUG_IDENTIFIER);
187         if (augNode instanceof AugmentationNode) {
188             final DataContainerChild enumNode = ((AugmentationNode) augNode).childByArg(childName);
189             if (enumNode instanceof LeafNode) {
190                 final Object value = enumNode.body();
191                 if (value instanceof String) {
192                     return (String) value;
193                 }
194             }
195         }
196         return null;
197     }
198
199     /**
200      * Create YANG notification stream using notification definition in YANG schema.
201      *
202      * @param notificationDefinition YANG notification definition.
203      * @param refSchemaCtx           Reference to {@link EffectiveModelContext}
204      * @param outputType             Output type (XML or JSON).
205      * @return {@link NotificationListenerAdapter}
206      */
207     static NotificationListenerAdapter createYangNotifiStream(final NotificationDefinition notificationDefinition,
208             final EffectiveModelContext refSchemaCtx, final NotificationOutputType outputType) {
209         final String streamName = parseNotificationStreamName(requireNonNull(notificationDefinition),
210                 requireNonNull(refSchemaCtx), requireNonNull(outputType.getName()));
211         final Optional<NotificationListenerAdapter> listenerForStreamName = ListenersBroker.getInstance()
212                 .getNotificationListenerFor(streamName);
213         return listenerForStreamName.orElseGet(() -> ListenersBroker.getInstance().registerNotificationListener(
214                 Absolute.of(notificationDefinition.getQName()), streamName, outputType));
215     }
216
217     private static String parseNotificationStreamName(final NotificationDefinition notificationDefinition,
218             final EffectiveModelContext refSchemaCtx, final String outputType) {
219         final QName notificationDefinitionQName = notificationDefinition.getQName();
220         final Module module = refSchemaCtx.findModule(
221                 notificationDefinitionQName.getModule().getNamespace(),
222                 notificationDefinitionQName.getModule().getRevision()).orElse(null);
223         requireNonNull(module, String.format("Module for namespace %s does not exist.",
224                 notificationDefinitionQName.getModule().getNamespace()));
225
226         final StringBuilder streamNameBuilder = new StringBuilder();
227         streamNameBuilder.append(RestconfStreamsConstants.NOTIFICATION_STREAM)
228                 .append('/')
229                 .append(module.getName())
230                 .append(':')
231                 .append(notificationDefinitionQName.getLocalName());
232         if (outputType.equals(NotificationOutputType.JSON.getName())) {
233             streamNameBuilder.append('/').append(NotificationOutputType.JSON.getName());
234         }
235         return streamNameBuilder.toString();
236     }
237 }