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