Do not use YIID parser for writing
[netconf.git] / restconf / restconf-nb-rfc8040 / src / main / java / org / opendaylight / restconf / nb / rfc8040 / rests / services / impl / SubscribeToStreamUtil.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 com.google.common.base.Preconditions.checkArgument;
11
12 import com.google.common.base.Strings;
13 import java.net.URI;
14 import java.util.HashMap;
15 import java.util.Map;
16 import java.util.Optional;
17 import java.util.concurrent.ExecutionException;
18 import javax.ws.rs.core.UriBuilder;
19 import javax.ws.rs.core.UriInfo;
20 import org.eclipse.jdt.annotation.NonNull;
21 import org.opendaylight.mdsal.common.api.LogicalDatastoreType;
22 import org.opendaylight.mdsal.dom.api.DOMDataBroker;
23 import org.opendaylight.mdsal.dom.api.DOMDataTreeChangeService;
24 import org.opendaylight.mdsal.dom.api.DOMDataTreeIdentifier;
25 import org.opendaylight.mdsal.dom.api.DOMDataTreeReadWriteTransaction;
26 import org.opendaylight.mdsal.dom.api.DOMNotificationListener;
27 import org.opendaylight.mdsal.dom.api.DOMTransactionChain;
28 import org.opendaylight.restconf.common.errors.RestconfDocumentedException;
29 import org.opendaylight.restconf.common.errors.RestconfError.ErrorTag;
30 import org.opendaylight.restconf.common.errors.RestconfError.ErrorType;
31 import org.opendaylight.restconf.common.util.DataChangeScope;
32 import org.opendaylight.restconf.nb.rfc8040.Rfc8040.MonitoringModule;
33 import org.opendaylight.restconf.nb.rfc8040.handlers.NotificationServiceHandler;
34 import org.opendaylight.restconf.nb.rfc8040.rests.services.impl.RestconfStreamsSubscriptionServiceImpl.HandlersHolder;
35 import org.opendaylight.restconf.nb.rfc8040.rests.services.impl.RestconfStreamsSubscriptionServiceImpl.NotificationQueryParams;
36 import org.opendaylight.restconf.nb.rfc8040.rests.utils.ResolveEnumUtil;
37 import org.opendaylight.restconf.nb.rfc8040.rests.utils.RestconfStreamsConstants;
38 import org.opendaylight.restconf.nb.rfc8040.streams.listeners.ListenerAdapter;
39 import org.opendaylight.restconf.nb.rfc8040.streams.listeners.ListenersBroker;
40 import org.opendaylight.restconf.nb.rfc8040.streams.listeners.NotificationListenerAdapter;
41 import org.opendaylight.restconf.nb.rfc8040.utils.RestconfConstants;
42 import org.opendaylight.restconf.nb.rfc8040.utils.mapping.RestconfMappingNodeUtil;
43 import org.opendaylight.restconf.nb.rfc8040.utils.parser.IdentifierCodec;
44 import org.opendaylight.yangtools.concepts.ListenerRegistration;
45 import org.opendaylight.yangtools.yang.data.api.schema.MapEntryNode;
46 import org.opendaylight.yangtools.yang.model.api.EffectiveModelContext;
47 import org.opendaylight.yangtools.yang.model.api.stmt.SchemaNodeIdentifier.Absolute;
48 import org.slf4j.Logger;
49 import org.slf4j.LoggerFactory;
50
51 /**
52  * Subscribe to stream util class.
53  */
54 abstract class SubscribeToStreamUtil {
55     /**
56      * Implementation of SubscribeToStreamUtil for Server-sent events.
57      */
58     private static final class ServerSentEvents extends SubscribeToStreamUtil {
59         static final ServerSentEvents INSTANCE = new ServerSentEvents();
60
61         @Override
62         public URI prepareUriByStreamName(final UriInfo uriInfo, final String streamName) {
63             final UriBuilder uriBuilder = uriInfo.getBaseUriBuilder();
64             return uriBuilder.replacePath(RestconfConstants.BASE_URI_PATTERN + '/'
65                     + RestconfConstants.NOTIF + '/' + streamName).build();
66         }
67     }
68
69     /**
70      * Implementation of SubscribeToStreamUtil for Web sockets.
71      */
72     private static final class WebSockets extends SubscribeToStreamUtil {
73         static final WebSockets INSTANCE = new WebSockets();
74
75         @Override
76         public URI prepareUriByStreamName(final UriInfo uriInfo, final String streamName) {
77             final String scheme = uriInfo.getAbsolutePath().getScheme();
78             final UriBuilder uriBuilder = uriInfo.getBaseUriBuilder();
79             switch (scheme) {
80                 case "https":
81                     // Secured HTTP goes to Secured WebSockets
82                     uriBuilder.scheme("wss");
83                     break;
84                 case "http":
85                 default:
86                     // Unsecured HTTP and others go to unsecured WebSockets
87                     uriBuilder.scheme("ws");
88             }
89             return uriBuilder.replacePath(RestconfConstants.BASE_URI_PATTERN + '/' + streamName).build();
90         }
91     }
92
93
94     private static final Logger LOG = LoggerFactory.getLogger(SubscribeToStreamUtil.class);
95
96     SubscribeToStreamUtil() {
97         // Hidden on purpose
98     }
99
100     static SubscribeToStreamUtil serverSentEvents() {
101         return ServerSentEvents.INSTANCE;
102     }
103
104     static SubscribeToStreamUtil webSockets() {
105         return WebSockets.INSTANCE;
106     }
107
108     /**
109      * Prepare URL from base name and stream name.
110      *
111      * @param uriInfo base URL information
112      * @param streamName name of stream for create
113      * @return final URL
114      */
115     abstract @NonNull URI prepareUriByStreamName(UriInfo uriInfo, String streamName);
116
117     /**
118      * Register listener by streamName in identifier to listen to yang notifications, and put or delete information
119      * about listener to DS according to ietf-restconf-monitoring.
120      *
121      * @param identifier              Name of the stream.
122      * @param uriInfo                 URI information.
123      * @param notificationQueryParams Query parameters of notification.
124      * @param handlersHolder          Holder of handlers for notifications.
125      * @return Stream location for listening.
126      */
127     final @NonNull URI subscribeToYangStream(final String identifier, final UriInfo uriInfo,
128             final NotificationQueryParams notificationQueryParams, final HandlersHolder handlersHolder) {
129         final String streamName = ListenersBroker.createStreamNameFromUri(identifier);
130         if (Strings.isNullOrEmpty(streamName)) {
131             throw new RestconfDocumentedException("Stream name is empty.", ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
132         }
133         final Optional<NotificationListenerAdapter> notificationListenerAdapter =
134                 ListenersBroker.getInstance().getNotificationListenerFor(streamName);
135
136         if (notificationListenerAdapter.isEmpty()) {
137             throw new RestconfDocumentedException(String.format(
138                     "Stream with name %s was not found.", streamName),
139                     ErrorType.PROTOCOL,
140                     ErrorTag.UNKNOWN_ELEMENT);
141         }
142
143         final DOMTransactionChain transactionChain = handlersHolder.getTransactionChainHandler().get();
144         final DOMDataTreeReadWriteTransaction writeTransaction = transactionChain.newReadWriteTransaction();
145         final EffectiveModelContext schemaContext = handlersHolder.getSchemaHandler().get();
146
147         final URI uri = prepareUriByStreamName(uriInfo, streamName);
148         registerToListenNotification(
149                 notificationListenerAdapter.get(), handlersHolder.getNotificationServiceHandler());
150         notificationListenerAdapter.get().setQueryParams(
151                 notificationQueryParams.getStart(),
152                 notificationQueryParams.getStop().orElse(null),
153                 notificationQueryParams.getFilter().orElse(null),
154                 false, notificationQueryParams.isSkipNotificationData());
155         notificationListenerAdapter.get().setCloseVars(
156                 handlersHolder.getTransactionChainHandler(), handlersHolder.getSchemaHandler());
157         final MapEntryNode mapToStreams = RestconfMappingNodeUtil.mapYangNotificationStreamByIetfRestconfMonitoring(
158                     notificationListenerAdapter.get().getSchemaPath().lastNodeIdentifier(),
159                     schemaContext.getNotifications(), notificationQueryParams.getStart(),
160                     notificationListenerAdapter.get().getOutputType(), uri);
161         writeDataToDS(writeTransaction, mapToStreams);
162         submitData(writeTransaction);
163         transactionChain.close();
164         return uri;
165     }
166
167     /**
168      * Register listener by streamName in identifier to listen to data change notifications, and put or delete
169      * information about listener to DS according to ietf-restconf-monitoring.
170      *
171      * @param identifier              Identifier as stream name.
172      * @param uriInfo                 Base URI information.
173      * @param notificationQueryParams Query parameters of notification.
174      * @param handlersHolder          Holder of handlers for notifications.
175      * @return Location for listening.
176      */
177     final URI subscribeToDataStream(final String identifier, final UriInfo uriInfo,
178             final NotificationQueryParams notificationQueryParams, final HandlersHolder handlersHolder) {
179         final Map<String, String> mapOfValues = mapValuesFromUri(identifier);
180         final LogicalDatastoreType datastoreType = parseURIEnum(
181                 LogicalDatastoreType.class,
182                 mapOfValues.get(RestconfStreamsConstants.DATASTORE_PARAM_NAME));
183         if (datastoreType == null) {
184             final String message = "Stream name doesn't contain datastore value (pattern /datastore=)";
185             LOG.debug(message);
186             throw new RestconfDocumentedException(message, ErrorType.APPLICATION, ErrorTag.MISSING_ATTRIBUTE);
187         }
188
189         final DataChangeScope scope = parseURIEnum(
190                 DataChangeScope.class,
191                 mapOfValues.get(RestconfStreamsConstants.SCOPE_PARAM_NAME));
192         if (scope == null) {
193             final String message = "Stream name doesn't contains datastore value (pattern /scope=)";
194             LOG.warn(message);
195             throw new RestconfDocumentedException(message, ErrorType.APPLICATION, ErrorTag.MISSING_ATTRIBUTE);
196         }
197
198         final String streamName = ListenersBroker.createStreamNameFromUri(identifier);
199         final Optional<ListenerAdapter> listener = ListenersBroker.getInstance().getDataChangeListenerFor(streamName);
200         checkArgument(listener.isPresent(), "Listener does not exist : %s", streamName);
201
202         listener.get().setQueryParams(
203                 notificationQueryParams.getStart(),
204                 notificationQueryParams.getStop().orElse(null),
205                 notificationQueryParams.getFilter().orElse(null),
206                 false, notificationQueryParams.isSkipNotificationData());
207         listener.get().setCloseVars(handlersHolder.getTransactionChainHandler(), handlersHolder.getSchemaHandler());
208         registration(datastoreType, listener.get(), handlersHolder.getDomDataBrokerHandler().get());
209
210         final URI uri = prepareUriByStreamName(uriInfo, streamName);
211         final DOMTransactionChain transactionChain = handlersHolder.getTransactionChainHandler().get();
212         final DOMDataTreeReadWriteTransaction writeTransaction = transactionChain.newReadWriteTransaction();
213         final EffectiveModelContext schemaContext = handlersHolder.getSchemaHandler().get();
214
215         final MapEntryNode mapToStreams =
216             RestconfMappingNodeUtil.mapDataChangeNotificationStreamByIetfRestconfMonitoring(listener.get().getPath(),
217                 notificationQueryParams.getStart(), listener.get().getOutputType(), uri, schemaContext,
218                 IdentifierCodec.serialize(listener.get().getPath(), schemaContext));
219         writeDataToDS(writeTransaction, mapToStreams);
220         submitData(writeTransaction);
221         transactionChain.close();
222         return uri;
223     }
224
225     private static void writeDataToDS(final DOMDataTreeReadWriteTransaction readWriteTransaction,
226             final MapEntryNode mapToStreams) {
227         readWriteTransaction.merge(LogicalDatastoreType.OPERATIONAL,
228             MonitoringModule.restconfStateStreamPath(mapToStreams.getIdentifier()), mapToStreams);
229     }
230
231     private static void submitData(final DOMDataTreeReadWriteTransaction readWriteTransaction) {
232         try {
233             readWriteTransaction.commit().get();
234         } catch (final InterruptedException | ExecutionException e) {
235             throw new RestconfDocumentedException("Problem while putting data to DS.", e);
236         }
237     }
238
239     /**
240      * Prepare map of URI parameter-values.
241      *
242      * @param identifier String identification of URI.
243      * @return Map od URI parameters and values.
244      */
245     private static Map<String, String> mapValuesFromUri(final String identifier) {
246         final HashMap<String, String> result = new HashMap<>();
247         for (final String token : RestconfConstants.SLASH_SPLITTER.split(identifier)) {
248             final String[] paramToken = token.split("=");
249             if (paramToken.length == 2) {
250                 result.put(paramToken[0], paramToken[1]);
251             }
252         }
253         return result;
254     }
255
256     /**
257      * Register data change listener in DOM data broker and set it to listener on stream.
258      *
259      * @param datastore     {@link LogicalDatastoreType}
260      * @param listener      listener on specific stream
261      * @param domDataBroker data broker for register data change listener
262      */
263     private static void registration(final LogicalDatastoreType datastore, final ListenerAdapter listener,
264             final DOMDataBroker domDataBroker) {
265         if (listener.isListening()) {
266             return;
267         }
268
269         final DOMDataTreeChangeService changeService = domDataBroker.getExtensions()
270                 .getInstance(DOMDataTreeChangeService.class);
271         if (changeService == null) {
272             throw new UnsupportedOperationException("DOMDataBroker does not support the DOMDataTreeChangeService");
273         }
274
275         final DOMDataTreeIdentifier root = new DOMDataTreeIdentifier(datastore, listener.getPath());
276         final ListenerRegistration<ListenerAdapter> registration =
277                 changeService.registerDataTreeChangeListener(root, listener);
278         listener.setRegistration(registration);
279     }
280
281     private static void registerToListenNotification(final NotificationListenerAdapter listener,
282             final NotificationServiceHandler notificationServiceHandler) {
283         if (listener.isListening()) {
284             return;
285         }
286
287         final Absolute path = listener.getSchemaPath();
288         final ListenerRegistration<DOMNotificationListener> registration =
289                 notificationServiceHandler.get().registerNotificationListener(listener, path);
290         listener.setRegistration(registration);
291     }
292
293     /**
294      * Parse out enumeration from URI.
295      *
296      * @param clazz Target enumeration type.
297      * @param value String representation of enumeration value.
298      * @return Parsed enumeration type.
299      */
300     private static <T> T parseURIEnum(final Class<T> clazz, final String value) {
301         if (value == null || value.equals("")) {
302             return null;
303         }
304         return ResolveEnumUtil.resolveEnum(clazz, value);
305     }
306 }