Extend Websocket streams for data-less notifications
[netconf.git] / restconf / restconf-nb-rfc8040 / src / main / java / org / opendaylight / restconf / nb / rfc8040 / rests / services / impl / RestconfStreamsSubscriptionServiceImpl.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 com.google.common.base.Preconditions;
11 import java.net.URI;
12 import java.time.Instant;
13 import java.time.format.DateTimeFormatter;
14 import java.time.format.DateTimeFormatterBuilder;
15 import java.time.format.DateTimeParseException;
16 import java.time.temporal.ChronoField;
17 import java.time.temporal.TemporalAccessor;
18 import java.util.ArrayList;
19 import java.util.HashMap;
20 import java.util.List;
21 import java.util.Map;
22 import java.util.Map.Entry;
23 import java.util.Optional;
24 import javax.ws.rs.Path;
25 import javax.ws.rs.core.UriInfo;
26 import org.eclipse.jdt.annotation.NonNull;
27 import org.opendaylight.mdsal.dom.api.DOMDataBroker;
28 import org.opendaylight.mdsal.dom.api.DOMNotificationService;
29 import org.opendaylight.mdsal.dom.api.DOMTransactionChain;
30 import org.opendaylight.restconf.common.context.InstanceIdentifierContext;
31 import org.opendaylight.restconf.common.context.NormalizedNodeContext;
32 import org.opendaylight.restconf.common.errors.RestconfDocumentedException;
33 import org.opendaylight.restconf.nb.rfc8040.handlers.DOMDataBrokerHandler;
34 import org.opendaylight.restconf.nb.rfc8040.handlers.NotificationServiceHandler;
35 import org.opendaylight.restconf.nb.rfc8040.handlers.SchemaContextHandler;
36 import org.opendaylight.restconf.nb.rfc8040.handlers.TransactionChainHandler;
37 import org.opendaylight.restconf.nb.rfc8040.rests.services.api.RestconfStreamsSubscriptionService;
38 import org.opendaylight.restconf.nb.rfc8040.rests.utils.RestconfStreamsConstants;
39 import org.opendaylight.restconf.nb.rfc8040.streams.Configuration;
40 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.types.rev130715.DateAndTime;
41 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
42 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
43 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
44 import org.opendaylight.yangtools.yang.data.api.schema.LeafNode;
45 import org.opendaylight.yangtools.yang.data.impl.schema.builder.api.NormalizedNodeBuilder;
46 import org.opendaylight.yangtools.yang.data.impl.schema.builder.impl.ImmutableLeafNodeBuilder;
47 import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
48 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
49 import org.opendaylight.yangtools.yang.model.api.Module;
50 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
51 import org.opendaylight.yangtools.yang.model.api.SchemaNode;
52 import org.slf4j.Logger;
53 import org.slf4j.LoggerFactory;
54
55 /**
56  * Implementation of {@link RestconfStreamsSubscriptionService}.
57  */
58 @Path("/")
59 public class RestconfStreamsSubscriptionServiceImpl implements RestconfStreamsSubscriptionService {
60     private static final Logger LOG = LoggerFactory.getLogger(RestconfStreamsSubscriptionServiceImpl.class);
61
62     private final SubscribeToStreamUtil streamUtils;
63
64     private HandlersHolder handlersHolder;
65
66     /**
67      * Initialize holder of handlers with holders as parameters.
68      *
69      * @param domDataBrokerHandler
70      *             handler of {@link DOMDataBroker}
71      * @param notificationServiceHandler
72      *             handler of {@link DOMNotificationService}
73      * @param schemaHandler
74      *             handler of {@link SchemaContext}
75      * @param transactionChainHandler
76      *             handler of {@link DOMTransactionChain}
77      * @param configuration
78      *             configuration for restconf {@link Configuration}}
79      */
80     public RestconfStreamsSubscriptionServiceImpl(final DOMDataBrokerHandler domDataBrokerHandler,
81             final NotificationServiceHandler notificationServiceHandler, final SchemaContextHandler schemaHandler,
82             final TransactionChainHandler transactionChainHandler, final Configuration configuration) {
83         this.handlersHolder = new HandlersHolder(domDataBrokerHandler, notificationServiceHandler,
84                 transactionChainHandler, schemaHandler);
85         streamUtils = configuration.isUseSSE() ? SubscribeToStreamUtil.serverSentEvents()
86                 : SubscribeToStreamUtil.webSockets();
87     }
88
89     @Override
90     public synchronized void updateHandlers(final Object... handlers) {
91         for (final Object object : handlers) {
92             if (object instanceof HandlersHolder) {
93                 handlersHolder = (HandlersHolder) object;
94             }
95         }
96     }
97
98     @Override
99     public NormalizedNodeContext subscribeToStream(final String identifier, final UriInfo uriInfo) {
100         final NotificationQueryParams notificationQueryParams = NotificationQueryParams.fromUriInfo(uriInfo);
101
102         final URI response;
103         if (identifier.contains(RestconfStreamsConstants.DATA_SUBSCRIPTION)) {
104             response = streamUtils.subscribeToDataStream(identifier, uriInfo, notificationQueryParams,
105                     this.handlersHolder);
106         } else if (identifier.contains(RestconfStreamsConstants.NOTIFICATION_STREAM)) {
107             response = streamUtils.subscribeToYangStream(identifier, uriInfo, notificationQueryParams,
108                     this.handlersHolder);
109         } else {
110             final String msg = "Bad type of notification of sal-remote";
111             LOG.warn(msg);
112             throw new RestconfDocumentedException(msg);
113         }
114
115         // prepare node with value of location
116         final InstanceIdentifierContext<?> iid = prepareIIDSubsStreamOutput(this.handlersHolder.getSchemaHandler());
117         final NormalizedNodeBuilder<NodeIdentifier, Object, LeafNode<Object>> builder =
118                 ImmutableLeafNodeBuilder.create().withValue(response.toString());
119         builder.withNodeIdentifier(NodeIdentifier.create(RestconfStreamsConstants.LOCATION_QNAME));
120
121         // prepare new header with location
122         final Map<String, Object> headers = new HashMap<>();
123         headers.put("Location", response);
124
125         return new NormalizedNodeContext(iid, builder.build(), headers);
126     }
127
128     /**
129      * Prepare InstanceIdentifierContext for Location leaf.
130      *
131      * @param schemaHandler Schema context handler.
132      * @return InstanceIdentifier of Location leaf.
133      */
134     private static InstanceIdentifierContext<?> prepareIIDSubsStreamOutput(final SchemaContextHandler schemaHandler) {
135         final Optional<Module> module = schemaHandler.get()
136                 .findModule(RestconfStreamsConstants.NOTIFI_QNAME.getModule());
137         Preconditions.checkState(module.isPresent());
138         final Optional<DataSchemaNode> notify = module.get()
139                 .findDataChildByName(RestconfStreamsConstants.NOTIFI_QNAME);
140         Preconditions.checkState(notify.isPresent());
141         final Optional<DataSchemaNode> location = ((ContainerSchemaNode) notify.get())
142                 .findDataChildByName(RestconfStreamsConstants.LOCATION_QNAME);
143         Preconditions.checkState(location.isPresent());
144
145         final List<PathArgument> path = new ArrayList<>();
146         path.add(NodeIdentifier.create(RestconfStreamsConstants.NOTIFI_QNAME));
147         path.add(NodeIdentifier.create(RestconfStreamsConstants.LOCATION_QNAME));
148         return new InstanceIdentifierContext<SchemaNode>(YangInstanceIdentifier.create(path), location.get(),
149                 null, schemaHandler.get());
150     }
151
152     /**
153      * Holder of all handlers for notifications.
154      */
155     public static final class HandlersHolder {
156
157         private final DOMDataBrokerHandler domDataBrokerHandler;
158         private final NotificationServiceHandler notificationServiceHandler;
159         private final TransactionChainHandler transactionChainHandler;
160         private final SchemaContextHandler schemaHandler;
161
162         private HandlersHolder(final DOMDataBrokerHandler domDataBrokerHandler,
163                 final NotificationServiceHandler notificationServiceHandler,
164                 final TransactionChainHandler transactionChainHandler, final SchemaContextHandler schemaHandler) {
165             this.domDataBrokerHandler = domDataBrokerHandler;
166             this.notificationServiceHandler = notificationServiceHandler;
167             this.transactionChainHandler = transactionChainHandler;
168             this.schemaHandler = schemaHandler;
169         }
170
171         /**
172          * Get {@link DOMDataBrokerHandler}.
173          *
174          * @return the domDataBrokerHandler
175          */
176         public DOMDataBrokerHandler getDomDataBrokerHandler() {
177             return this.domDataBrokerHandler;
178         }
179
180         /**
181          * Get {@link NotificationServiceHandler}.
182          *
183          * @return the notificationServiceHandler
184          */
185         public NotificationServiceHandler getNotificationServiceHandler() {
186             return this.notificationServiceHandler;
187         }
188
189         /**
190          * Get {@link TransactionChainHandler}.
191          *
192          * @return the transactionChainHandler
193          */
194         public TransactionChainHandler getTransactionChainHandler() {
195             return this.transactionChainHandler;
196         }
197
198         /**
199          * Get {@link SchemaContextHandler}.
200          *
201          * @return the schemaHandler
202          */
203         public SchemaContextHandler getSchemaHandler() {
204             return this.schemaHandler;
205         }
206     }
207
208     /**
209      * Parser and holder of query paramteres from uriInfo for notifications.
210      */
211     public static final class NotificationQueryParams {
212         private static final DateTimeFormatter FORMATTER = new DateTimeFormatterBuilder()
213                 .appendValue(ChronoField.YEAR, 4).appendLiteral('-')
214                 .appendValue(ChronoField.MONTH_OF_YEAR, 2).appendLiteral('-')
215                 .appendValue(ChronoField.DAY_OF_MONTH, 2).appendLiteral('T')
216                 .appendValue(ChronoField.HOUR_OF_DAY, 2).appendLiteral(':')
217                 .appendValue(ChronoField.MINUTE_OF_HOUR, 2).appendLiteral(':')
218                 .appendValue(ChronoField.SECOND_OF_MINUTE, 2)
219                 .appendFraction(ChronoField.NANO_OF_SECOND, 0, 9, true)
220                 .appendOffset("+HH:MM", "Z").toFormatter();
221
222         private final Instant start;
223         private final Instant stop;
224         private final String filter;
225         private final boolean skipNotificationData;
226
227         private NotificationQueryParams(final Instant start, final Instant stop, final String filter,
228                 final boolean skipNotificationData) {
229             this.start = start == null ? Instant.now() : start;
230             this.stop = stop;
231             this.filter = filter;
232             this.skipNotificationData = skipNotificationData;
233         }
234
235         static NotificationQueryParams fromUriInfo(final UriInfo uriInfo) {
236             Instant start = null;
237             boolean startTimeUsed = false;
238             Instant stop = null;
239             boolean stopTimeUsed = false;
240             String filter = null;
241             boolean filterUsed = false;
242             boolean skipNotificationDataUsed = false;
243             boolean skipNotificationData = false;
244
245             for (final Entry<String, List<String>> entry : uriInfo.getQueryParameters().entrySet()) {
246                 switch (entry.getKey()) {
247                     case "start-time":
248                         if (!startTimeUsed) {
249                             startTimeUsed = true;
250                             start = parseDateFromQueryParam(entry);
251                         } else {
252                             throw new RestconfDocumentedException("Start-time parameter can be used only once.");
253                         }
254                         break;
255                     case "stop-time":
256                         if (!stopTimeUsed) {
257                             stopTimeUsed = true;
258                             stop = parseDateFromQueryParam(entry);
259                         } else {
260                             throw new RestconfDocumentedException("Stop-time parameter can be used only once.");
261                         }
262                         break;
263                     case "filter":
264                         if (!filterUsed) {
265                             filterUsed = true;
266                             filter = entry.getValue().iterator().next();
267                         }
268                         break;
269                     case "odl-skip-notification-data":
270                         if (!skipNotificationDataUsed) {
271                             skipNotificationDataUsed = true;
272                             skipNotificationData = Boolean.parseBoolean(entry.getValue().iterator().next());
273                         } else {
274                             throw new RestconfDocumentedException(
275                                     "Odl-skip-notification-data parameter can be used only once.");
276                         }
277                         break;
278                     default:
279                         throw new RestconfDocumentedException(
280                                 "Bad parameter used with notifications: " + entry.getKey());
281                 }
282             }
283             if (!startTimeUsed && stopTimeUsed) {
284                 throw new RestconfDocumentedException("Stop-time parameter has to be used with start-time parameter.");
285             }
286
287             return new NotificationQueryParams(start, stop, filter, skipNotificationData);
288         }
289
290
291         /**
292          * Parse input of query parameters - start-time or stop-time - from {@link DateAndTime} format
293          * to {@link Instant} format.
294          *
295          * @param entry Start-time or stop-time as string in {@link DateAndTime} format.
296          * @return Parsed {@link Instant} by entry.
297          */
298         private static Instant parseDateFromQueryParam(final Entry<String, List<String>> entry) {
299             final DateAndTime event = new DateAndTime(entry.getValue().iterator().next());
300             final String value = event.getValue();
301             final TemporalAccessor accessor;
302             try {
303                 accessor = FORMATTER.parse(value);
304             } catch (final DateTimeParseException e) {
305                 throw new RestconfDocumentedException("Cannot parse of value in date: " + value, e);
306             }
307             return Instant.from(accessor);
308         }
309
310         /**
311          * Get start-time query parameter.
312          *
313          * @return start-time
314          */
315         public @NonNull Instant getStart() {
316             return start;
317         }
318
319         /**
320          * Get stop-time query parameter.
321          *
322          * @return stop-time
323          */
324         public Optional<Instant> getStop() {
325             return Optional.ofNullable(stop);
326         }
327
328         /**
329          * Get filter query parameter.
330          *
331          * @return filter
332          */
333         public Optional<String> getFilter() {
334             return Optional.ofNullable(filter);
335         }
336
337         /**
338          * Check whether this query should notify changes without data.
339          *
340          * @return true if this query should notify about changes with  data
341          */
342         public boolean isSkipNotificationData() {
343             return skipNotificationData;
344         }
345     }
346 }