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 com.google.common.base.Preconditions;
11 import com.google.common.base.Strings;
13 import java.util.HashMap;
15 import java.util.Optional;
16 import java.util.concurrent.ExecutionException;
17 import javax.ws.rs.core.UriBuilder;
18 import javax.ws.rs.core.UriInfo;
19 import org.eclipse.jdt.annotation.NonNull;
20 import org.opendaylight.mdsal.common.api.LogicalDatastoreType;
21 import org.opendaylight.mdsal.dom.api.DOMDataBroker;
22 import org.opendaylight.mdsal.dom.api.DOMDataTreeChangeService;
23 import org.opendaylight.mdsal.dom.api.DOMDataTreeIdentifier;
24 import org.opendaylight.mdsal.dom.api.DOMDataTreeReadOperations;
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.NormalizedNode;
46 import org.opendaylight.yangtools.yang.model.api.EffectiveModelContext;
47 import org.opendaylight.yangtools.yang.model.api.Module;
48 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
49 import org.opendaylight.yangtools.yang.model.api.SchemaPath;
50 import org.slf4j.Logger;
51 import org.slf4j.LoggerFactory;
54 * Subscribe to stream util class.
56 abstract class SubscribeToStreamUtil {
58 * Implementation of {@link UrlResolver} for Server-sent events.
60 private static final class ServerSentEvents extends SubscribeToStreamUtil {
61 static final ServerSentEvents INSTANCE = new ServerSentEvents();
64 public URI prepareUriByStreamName(final UriInfo uriInfo, final String streamName) {
65 final UriBuilder uriBuilder = uriInfo.getBaseUriBuilder();
66 return uriBuilder.replacePath(RestconfConstants.BASE_URI_PATTERN + '/'
67 + RestconfConstants.NOTIF + '/' + streamName).build();
72 * Implementation of {@link UrlResolver} for Web sockets.
74 private static final class WebSockets extends SubscribeToStreamUtil {
75 static final WebSockets INSTANCE = new WebSockets();
78 public URI prepareUriByStreamName(final UriInfo uriInfo, final String streamName) {
79 final String scheme = uriInfo.getAbsolutePath().getScheme();
80 final UriBuilder uriBuilder = uriInfo.getBaseUriBuilder();
83 // Secured HTTP goes to Secured WebSockets
84 uriBuilder.scheme("wss");
88 // Unsecured HTTP and others go to unsecured WebSockets
89 uriBuilder.scheme("ws");
91 return uriBuilder.replacePath(RestconfConstants.BASE_URI_PATTERN + '/' + streamName).build();
96 private static final Logger LOG = LoggerFactory.getLogger(SubscribeToStreamUtil.class);
98 SubscribeToStreamUtil() {
102 static SubscribeToStreamUtil serverSentEvents() {
103 return ServerSentEvents.INSTANCE;
106 static SubscribeToStreamUtil webSockets() {
107 return WebSockets.INSTANCE;
111 * Prepare URL from base name and stream name.
113 * @param uriInfo base URL information
114 * @param streamName name of stream for create
117 abstract @NonNull URI prepareUriByStreamName(UriInfo uriInfo, String streamName);
120 * Register listener by streamName in identifier to listen to yang notifications, and put or delete information
121 * about listener to DS according to ietf-restconf-monitoring.
123 * @param identifier Name of the stream.
124 * @param uriInfo URI information.
125 * @param notificationQueryParams Query parameters of notification.
126 * @param handlersHolder Holder of handlers for notifications.
127 * @param urlResolver Resolver for proper implementation. Possibilities is WS or SSE.
128 * @return Stream location for listening.
130 final @NonNull URI subscribeToYangStream(final String identifier, final UriInfo uriInfo,
131 final NotificationQueryParams notificationQueryParams, final HandlersHolder handlersHolder) {
132 final String streamName = ListenersBroker.createStreamNameFromUri(identifier);
133 if (Strings.isNullOrEmpty(streamName)) {
134 throw new RestconfDocumentedException("Stream name is empty.", ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
136 final Optional<NotificationListenerAdapter> notificationListenerAdapter =
137 ListenersBroker.getInstance().getNotificationListenerFor(streamName);
139 if (!notificationListenerAdapter.isPresent()) {
140 throw new RestconfDocumentedException(String.format(
141 "Stream with name %s was not found.", streamName),
143 ErrorTag.UNKNOWN_ELEMENT);
146 final DOMTransactionChain transactionChain = handlersHolder.getTransactionChainHandler().get();
147 final DOMDataTreeReadWriteTransaction writeTransaction = transactionChain.newReadWriteTransaction();
148 final SchemaContext schemaContext = handlersHolder.getSchemaHandler().get();
149 final boolean exist = checkExist(schemaContext, writeTransaction);
151 final URI uri = prepareUriByStreamName(uriInfo, streamName);
152 registerToListenNotification(
153 notificationListenerAdapter.get(), handlersHolder.getNotificationServiceHandler());
154 notificationListenerAdapter.get().setQueryParams(
155 notificationQueryParams.getStart(),
156 notificationQueryParams.getStop().orElse(null),
157 notificationQueryParams.getFilter().orElse(null),
158 false, notificationQueryParams.isSkipNotificationData());
159 notificationListenerAdapter.get().setCloseVars(
160 handlersHolder.getTransactionChainHandler(), handlersHolder.getSchemaHandler());
161 final NormalizedNode<?, ?> mapToStreams =
162 RestconfMappingNodeUtil.mapYangNotificationStreamByIetfRestconfMonitoring(
163 notificationListenerAdapter.get().getSchemaPath().getLastComponent(),
164 schemaContext.getNotifications(), notificationQueryParams.getStart(),
165 notificationListenerAdapter.get().getOutputType(), uri, getMonitoringModule(schemaContext), exist);
166 writeDataToDS(schemaContext,
167 notificationListenerAdapter.get().getSchemaPath().getLastComponent().getLocalName(), writeTransaction,
168 exist, mapToStreams);
169 submitData(writeTransaction);
170 transactionChain.close();
175 * Register listener by streamName in identifier to listen to data change notifications, and put or delete
176 * information about listener to DS according to ietf-restconf-monitoring.
178 * @param identifier Identifier as stream name.
179 * @param uriInfo Base URI information.
180 * @param notificationQueryParams Query parameters of notification.
181 * @param handlersHolder Holder of handlers for notifications.
182 * @return Location for listening.
184 final URI subscribeToDataStream(final String identifier, final UriInfo uriInfo,
185 final NotificationQueryParams notificationQueryParams, final HandlersHolder handlersHolder) {
186 final Map<String, String> mapOfValues = mapValuesFromUri(identifier);
187 final LogicalDatastoreType datastoreType = parseURIEnum(
188 LogicalDatastoreType.class,
189 mapOfValues.get(RestconfStreamsConstants.DATASTORE_PARAM_NAME));
190 if (datastoreType == null) {
191 final String message = "Stream name doesn't contain datastore value (pattern /datastore=)";
193 throw new RestconfDocumentedException(message, ErrorType.APPLICATION, ErrorTag.MISSING_ATTRIBUTE);
196 final DataChangeScope scope = parseURIEnum(
197 DataChangeScope.class,
198 mapOfValues.get(RestconfStreamsConstants.SCOPE_PARAM_NAME));
200 final String message = "Stream name doesn't contains datastore value (pattern /scope=)";
202 throw new RestconfDocumentedException(message, ErrorType.APPLICATION, ErrorTag.MISSING_ATTRIBUTE);
205 final String streamName = ListenersBroker.createStreamNameFromUri(identifier);
206 final Optional<ListenerAdapter> listener = ListenersBroker.getInstance().getDataChangeListenerFor(streamName);
207 Preconditions.checkArgument(listener.isPresent(), "Listener doesn't exist : " + streamName);
209 listener.get().setQueryParams(
210 notificationQueryParams.getStart(),
211 notificationQueryParams.getStop().orElse(null),
212 notificationQueryParams.getFilter().orElse(null),
213 false, notificationQueryParams.isSkipNotificationData());
214 listener.get().setCloseVars(handlersHolder.getTransactionChainHandler(), handlersHolder.getSchemaHandler());
215 registration(datastoreType, listener.get(), handlersHolder.getDomDataBrokerHandler().get());
217 final URI uri = prepareUriByStreamName(uriInfo, streamName);
218 final DOMTransactionChain transactionChain = handlersHolder.getTransactionChainHandler().get();
219 final DOMDataTreeReadWriteTransaction writeTransaction = transactionChain.newReadWriteTransaction();
220 final EffectiveModelContext schemaContext = handlersHolder.getSchemaHandler().get();
221 final boolean exist = checkExist(schemaContext, writeTransaction);
223 final NormalizedNode<?, ?> mapToStreams = RestconfMappingNodeUtil
224 .mapDataChangeNotificationStreamByIetfRestconfMonitoring(listener.get().getPath(),
225 notificationQueryParams.getStart(), listener.get().getOutputType(), uri,
226 getMonitoringModule(schemaContext), exist, schemaContext);
227 writeDataToDS(schemaContext, listener.get().getPath().getLastPathArgument().getNodeType().getLocalName(),
228 writeTransaction, exist, mapToStreams);
229 submitData(writeTransaction);
230 transactionChain.close();
234 static Module getMonitoringModule(final SchemaContext schemaContext) {
235 return schemaContext.findModule(MonitoringModule.MODULE_QNAME).orElse(null);
238 private static void writeDataToDS(final SchemaContext schemaContext, final String name,
239 final DOMDataTreeReadWriteTransaction readWriteTransaction, final boolean exist,
240 final NormalizedNode<?, ?> mapToStreams) {
243 pathId = MonitoringModule.PATH_TO_STREAM_WITHOUT_KEY + name;
245 pathId = MonitoringModule.PATH_TO_STREAMS;
247 readWriteTransaction.merge(LogicalDatastoreType.OPERATIONAL,
248 IdentifierCodec.deserialize(pathId, schemaContext), mapToStreams);
251 private static void submitData(final DOMDataTreeReadWriteTransaction readWriteTransaction) {
253 readWriteTransaction.commit().get();
254 } catch (final InterruptedException | ExecutionException e) {
255 throw new RestconfDocumentedException("Problem while putting data to DS.", e);
260 * Prepare map of URI parameter-values.
262 * @param identifier String identification of URI.
263 * @return Map od URI parameters and values.
265 private static Map<String, String> mapValuesFromUri(final String identifier) {
266 final HashMap<String, String> result = new HashMap<>();
267 for (final String token : RestconfConstants.SLASH_SPLITTER.split(identifier)) {
268 final String[] paramToken = token.split("=");
269 if (paramToken.length == 2) {
270 result.put(paramToken[0], paramToken[1]);
277 * Register data change listener in DOM data broker and set it to listener on stream.
279 * @param datastore {@link LogicalDatastoreType}
280 * @param listener listener on specific stream
281 * @param domDataBroker data broker for register data change listener
283 private static void registration(final LogicalDatastoreType datastore, final ListenerAdapter listener,
284 final DOMDataBroker domDataBroker) {
285 if (listener.isListening()) {
289 final DOMDataTreeChangeService changeService = domDataBroker.getExtensions()
290 .getInstance(DOMDataTreeChangeService.class);
291 if (changeService == null) {
292 throw new UnsupportedOperationException("DOMDataBroker does not support the DOMDataTreeChangeService");
295 final DOMDataTreeIdentifier root = new DOMDataTreeIdentifier(datastore, listener.getPath());
296 final ListenerRegistration<ListenerAdapter> registration =
297 changeService.registerDataTreeChangeListener(root, listener);
298 listener.setRegistration(registration);
301 private static boolean checkExist(final SchemaContext schemaContext,
302 final DOMDataTreeReadOperations readWriteTransaction) {
304 return readWriteTransaction.exists(LogicalDatastoreType.OPERATIONAL,
305 IdentifierCodec.deserialize(MonitoringModule.PATH_TO_STREAMS, schemaContext)).get();
306 } catch (final InterruptedException | ExecutionException exception) {
307 throw new RestconfDocumentedException("Problem while checking data if exists", exception);
311 private static void registerToListenNotification(final NotificationListenerAdapter listener,
312 final NotificationServiceHandler notificationServiceHandler) {
313 if (listener.isListening()) {
317 final SchemaPath path = listener.getSchemaPath();
318 final ListenerRegistration<DOMNotificationListener> registration =
319 notificationServiceHandler.get().registerNotificationListener(listener, path);
320 listener.setRegistration(registration);
324 * Parse out enumeration from URI.
326 * @param clazz Target enumeration type.
327 * @param value String representation of enumeration value.
328 * @return Parsed enumeration type.
330 private static <T> T parseURIEnum(final Class<T> clazz, final String value) {
331 if (value == null || value.equals("")) {
334 return ResolveEnumUtil.resolveEnum(clazz, value);