BUG 1082 Migrate sal-rest-connector to Async Data Broker API
[controller.git] / opendaylight / md-sal / sal-rest-connector / src / main / java / org / opendaylight / controller / sal / streams / listeners / ListenerAdapter.java
1 /*
2  * Copyright (c) 2014 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.controller.sal.streams.listeners;
9
10 import com.google.common.base.Charsets;
11 import com.google.common.base.Preconditions;
12 import com.google.common.eventbus.AsyncEventBus;
13 import com.google.common.eventbus.EventBus;
14 import com.google.common.eventbus.Subscribe;
15 import io.netty.channel.Channel;
16 import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
17 import io.netty.util.internal.ConcurrentSet;
18 import java.io.ByteArrayOutputStream;
19 import java.io.OutputStreamWriter;
20 import java.io.UnsupportedEncodingException;
21 import java.text.SimpleDateFormat;
22 import java.util.Collection;
23 import java.util.Date;
24 import java.util.HashMap;
25 import java.util.Map;
26 import java.util.Map.Entry;
27 import java.util.Random;
28 import java.util.Set;
29 import java.util.concurrent.Executors;
30 import java.util.regex.Pattern;
31 import javax.activation.UnsupportedDataTypeException;
32 import javax.xml.parsers.DocumentBuilder;
33 import javax.xml.parsers.DocumentBuilderFactory;
34 import javax.xml.parsers.ParserConfigurationException;
35 import javax.xml.transform.OutputKeys;
36 import javax.xml.transform.Transformer;
37 import javax.xml.transform.TransformerException;
38 import javax.xml.transform.TransformerFactory;
39 import javax.xml.transform.dom.DOMSource;
40 import javax.xml.transform.stream.StreamResult;
41 import org.opendaylight.controller.md.sal.common.api.data.AsyncDataChangeEvent;
42 import org.opendaylight.controller.md.sal.dom.api.DOMDataChangeListener;
43 import org.opendaylight.controller.sal.rest.impl.XmlMapper;
44 import org.opendaylight.controller.sal.restconf.impl.ControllerContext;
45 import org.opendaylight.yangtools.concepts.ListenerRegistration;
46 import org.opendaylight.yangtools.yang.common.QName;
47 import org.opendaylight.yangtools.yang.data.api.CompositeNode;
48 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
49 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifierWithPredicates;
50 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeWithValue;
51 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
52 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
53 import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
54 import org.slf4j.Logger;
55 import org.slf4j.LoggerFactory;
56 import org.w3c.dom.Document;
57 import org.w3c.dom.Element;
58 import org.w3c.dom.Node;
59
60 /**
61  * {@link ListenerAdapter} is responsible to track events, which occurred by changing data in data source.
62  */
63 public class ListenerAdapter implements DOMDataChangeListener {
64
65     private static final Logger LOG = LoggerFactory.getLogger(ListenerAdapter.class);
66     private static final DocumentBuilderFactory DBF = DocumentBuilderFactory.newInstance();
67     private static final TransformerFactory FACTORY = TransformerFactory.newInstance();
68     private static final Pattern RFC3339_PATTERN = Pattern.compile("(\\d\\d)(\\d\\d)$");
69
70     private final XmlMapper xmlMapper = new XmlMapper();
71     private final SimpleDateFormat rfc3339 = new SimpleDateFormat("yyyy-MM-dd'T'hh:mm:ssZ");
72
73     private final YangInstanceIdentifier path;
74     private ListenerRegistration<DOMDataChangeListener> registration;
75     private final String streamName;
76     private Set<Channel> subscribers = new ConcurrentSet<>();
77     private final EventBus eventBus;
78     private final EventBusChangeRecorder eventBusChangeRecorder;
79
80     /**
81      * Creates new {@link ListenerAdapter} listener specified by path and stream name.
82      *
83      * @param path
84      *            Path to data in data store.
85      * @param streamName
86      *            The name of the stream.
87      */
88     ListenerAdapter(final YangInstanceIdentifier path, final String streamName) {
89         Preconditions.checkNotNull(path);
90         Preconditions.checkArgument(streamName != null && !streamName.isEmpty());
91         this.path = path;
92         this.streamName = streamName;
93         eventBus = new AsyncEventBus(Executors.newSingleThreadExecutor());
94         eventBusChangeRecorder = new EventBusChangeRecorder();
95         eventBus.register(eventBusChangeRecorder);
96     }
97
98     @Override
99     public void onDataChanged(AsyncDataChangeEvent<YangInstanceIdentifier, NormalizedNode<?, ?>> change) {
100         // TODO Auto-generated method stub
101
102         if (!change.getCreatedData().isEmpty() || !change.getUpdatedData().isEmpty()
103                 || !change.getRemovedPaths().isEmpty()) {
104             String xml = prepareXmlFrom(change);
105             Event event = new Event(EventType.NOTIFY);
106             event.setData(xml);
107             eventBus.post(event);
108         }
109     }
110
111     /**
112      * Tracks events of data change by customer.
113      */
114     private final class EventBusChangeRecorder {
115         @Subscribe
116         public void recordCustomerChange(final Event event) {
117             if (event.getType() == EventType.REGISTER) {
118                 Channel subscriber = event.getSubscriber();
119                 if (!subscribers.contains(subscriber)) {
120                     subscribers.add(subscriber);
121                 }
122             } else if (event.getType() == EventType.DEREGISTER) {
123                 subscribers.remove(event.getSubscriber());
124                 Notificator.removeListenerIfNoSubscriberExists(ListenerAdapter.this);
125             } else if (event.getType() == EventType.NOTIFY) {
126                 for (Channel subscriber : subscribers) {
127                     if (subscriber.isActive()) {
128                         LOG.debug("Data are sent to subscriber {}:", subscriber.remoteAddress());
129                         subscriber.writeAndFlush(new TextWebSocketFrame(event.getData()));
130                     } else {
131                         LOG.debug("Subscriber {} is removed - channel is not active yet.", subscriber.remoteAddress());
132                         subscribers.remove(subscriber);
133                     }
134                 }
135             }
136         }
137     }
138
139     /**
140      * Represents event of specific {@link EventType} type, holds data and {@link Channel} subscriber.
141      */
142     private final class Event {
143         private final EventType type;
144         private Channel subscriber;
145         private String data;
146
147         /**
148          * Creates new event specified by {@link EventType} type.
149          *
150          * @param type
151          *            EventType
152          */
153         public Event(final EventType type) {
154             this.type = type;
155         }
156
157         /**
158          * Gets the {@link Channel} subscriber.
159          *
160          * @return Channel
161          */
162         public Channel getSubscriber() {
163             return subscriber;
164         }
165
166         /**
167          * Sets subscriber for event.
168          *
169          * @param subscriber
170          *            Channel
171          */
172         public void setSubscriber(final Channel subscriber) {
173             this.subscriber = subscriber;
174         }
175
176         /**
177          * Gets event data.
178          *
179          * @return String representation of event data.
180          */
181         public String getData() {
182             return data;
183         }
184
185         /**
186          * Sets event data.
187          *
188          * @param String
189          *            data.
190          */
191         public void setData(final String data) {
192             this.data = data;
193         }
194
195         /**
196          * Gets event type.
197          *
198          * @return The type of the event.
199          */
200         public EventType getType() {
201             return type;
202         }
203     }
204
205     /**
206      * Type of the event.
207      */
208     private enum EventType {
209         REGISTER,
210         DEREGISTER,
211         NOTIFY;
212     }
213
214     /**
215      * Prepare data in printable form and transform it to String.
216      *
217      * @param change
218      *            DataChangeEvent
219      * @return Data in printable form.
220      */
221     private String prepareXmlFrom(AsyncDataChangeEvent<YangInstanceIdentifier, NormalizedNode<?, ?>> change) {
222         Document doc = createDocument();
223         Element notificationElement = doc.createElementNS("urn:ietf:params:xml:ns:netconf:notification:1.0",
224                 "notification");
225         doc.appendChild(notificationElement);
226
227         Element eventTimeElement = doc.createElement("eventTime");
228         eventTimeElement.setTextContent(toRFC3339(new Date()));
229         notificationElement.appendChild(eventTimeElement);
230
231         Element dataChangedNotificationEventElement = doc.createElementNS(
232                 "urn:opendaylight:params:xml:ns:yang:controller:md:sal:remote", "data-changed-notification");
233         addValuesToDataChangedNotificationEventElement(doc, dataChangedNotificationEventElement, change);
234         notificationElement.appendChild(dataChangedNotificationEventElement);
235
236         try {
237             ByteArrayOutputStream out = new ByteArrayOutputStream();
238             Transformer transformer = FACTORY.newTransformer();
239             transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no");
240             transformer.setOutputProperty(OutputKeys.METHOD, "xml");
241             transformer.setOutputProperty(OutputKeys.INDENT, "yes");
242             transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
243             transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");
244             transformer.transform(new DOMSource(doc), new StreamResult(new OutputStreamWriter(out, Charsets.UTF_8)));
245             byte[] charData = out.toByteArray();
246             return new String(charData, "UTF-8");
247         } catch (TransformerException | UnsupportedEncodingException e) {
248             String msg = "Error during transformation of Document into String";
249             LOG.error(msg, e);
250             return msg;
251         }
252     }
253
254     /**
255      * Formats data specified by RFC3339.
256      *
257      * @param d
258      *            Date
259      * @return Data specified by RFC3339.
260      */
261     private String toRFC3339(final Date d) {
262         return RFC3339_PATTERN.matcher(rfc3339.format(d)).replaceAll("$1:$2");
263     }
264
265     /**
266      * Creates {@link Document} document.
267      * @return {@link Document} document.
268      */
269     private Document createDocument() {
270         final DocumentBuilder bob;
271         try {
272             bob = DBF.newDocumentBuilder();
273         } catch (ParserConfigurationException e) {
274             return null;
275         }
276         return bob.newDocument();
277     }
278
279     /**
280      * Adds values to data changed notification event element.
281      *
282      * @param doc
283      *            {@link Document}
284      * @param dataChangedNotificationEventElement
285      *            {@link Element}
286      * @param change
287      *            {@link DataChangeEvent}
288      */
289     private void addValuesToDataChangedNotificationEventElement(final Document doc,
290             final Element dataChangedNotificationEventElement,
291             AsyncDataChangeEvent<YangInstanceIdentifier, NormalizedNode<?, ?>> change) {
292         addValuesFromDataToElement(doc, change.getCreatedData().keySet(), dataChangedNotificationEventElement,
293                 Operation.CREATED);
294         if (change.getCreatedData().isEmpty()) {
295             addValuesFromDataToElement(doc, change.getUpdatedData().keySet(), dataChangedNotificationEventElement,
296                     Operation.UPDATED);
297         }
298         addValuesFromDataToElement(doc, change.getRemovedPaths(), dataChangedNotificationEventElement,
299                 Operation.DELETED);
300     }
301
302     /**
303      * Adds values from data to element.
304      *
305      * @param doc
306      *            {@link Document}
307      * @param data
308      *            Set of {@link YangInstanceIdentifier}.
309      * @param element
310      *            {@link Element}
311      * @param store
312      *            {@link Store}
313      * @param operation
314      *            {@link Operation}
315      */
316     private void addValuesFromDataToElement(Document doc, Set<YangInstanceIdentifier> data, Element element,
317             Operation operation) {
318         if (data == null || data.isEmpty()) {
319             return;
320         }
321         for (YangInstanceIdentifier path : data) {
322             Node node = createDataChangeEventElement(doc, path, null, operation);
323             element.appendChild(node);
324         }
325     }
326
327     /**
328      * Adds values from data to element.
329      *
330      * @param doc
331      *            {@link Document}
332      * @param data
333      *            Map of {@link YangInstanceIdentifier} and {@link CompositeNode}.
334      * @param element
335      *            {@link Element}
336      * @param store
337      *            {@link Store}
338      * @param operation
339      *            {@link Operation}
340      */
341     private void addValuesFromDataToElement(Document doc, Map<YangInstanceIdentifier, CompositeNode> data, Element element,
342             Operation operation) {
343         if (data == null || data.isEmpty()) {
344             return;
345         }
346         for (Entry<YangInstanceIdentifier, CompositeNode> entry : data.entrySet()) {
347             Node node = createDataChangeEventElement(doc, entry.getKey(), entry.getValue(), operation);
348             element.appendChild(node);
349         }
350     }
351
352     /**
353      * Creates changed event element from data.
354      *
355      * @param doc
356      *            {@link Document}
357      * @param path
358      *            Path to data in data store.
359      * @param data
360      *            {@link CompositeNode}
361      * @param store
362      *            {@link Store}
363      * @param operation
364      *            {@link Operation}
365      * @return {@link Node} node represented by changed event element.
366      */
367     private Node createDataChangeEventElement(Document doc, YangInstanceIdentifier path, CompositeNode data,
368             Operation operation) {
369         Element dataChangeEventElement = doc.createElement("data-change-event");
370
371         Element pathElement = doc.createElement("path");
372         addPathAsValueToElement(path, pathElement);
373         dataChangeEventElement.appendChild(pathElement);
374
375         // Element storeElement = doc.createElement("store");
376         // storeElement.setTextContent(store.value);
377         // dataChangeEventElement.appendChild(storeElement);
378
379         Element operationElement = doc.createElement("operation");
380         operationElement.setTextContent(operation.value);
381         dataChangeEventElement.appendChild(operationElement);
382
383         if (data != null) {
384             Element dataElement = doc.createElement("data");
385             Node dataAnyXml = translateToXml(path, data);
386             Node adoptedNode = doc.adoptNode(dataAnyXml);
387             dataElement.appendChild(adoptedNode);
388             dataChangeEventElement.appendChild(dataElement);
389         }
390
391         return dataChangeEventElement;
392     }
393
394     /**
395      * Translates {@link CompositeNode} data to XML format.
396      *
397      * @param path
398      *            Path to data in data store.
399      * @param data
400      *            {@link CompositeNode}
401      * @return Data in XML format.
402      */
403     private Node translateToXml(final YangInstanceIdentifier path, final CompositeNode data) {
404         DataNodeContainer schemaNode = ControllerContext.getInstance().getDataNodeContainerFor(path);
405         if (schemaNode == null) {
406             LOG.info(
407                     "Path '{}' contains node with unsupported type (supported type is Container or List) or some node was not found.",
408                     path);
409             return null;
410         }
411         try {
412             Document xml = xmlMapper.write(data, schemaNode);
413             return xml.getFirstChild();
414         } catch (UnsupportedDataTypeException e) {
415             LOG.error("Error occured during translation of notification to XML.", e);
416             return null;
417         }
418     }
419
420     /**
421      * Adds path as value to element.
422      *
423      * @param path
424      *            Path to data in data store.
425      * @param element
426      *            {@link Element}
427      */
428     private void addPathAsValueToElement(final YangInstanceIdentifier path, final Element element) {
429         // Map< key = namespace, value = prefix>
430         Map<String, String> prefixes = new HashMap<>();
431         YangInstanceIdentifier instanceIdentifier = path;
432         StringBuilder textContent = new StringBuilder();
433
434         // FIXME: BUG-1281: this is duplicated code from yangtools (BUG-1275)
435         for (PathArgument pathArgument : instanceIdentifier.getPathArguments()) {
436             textContent.append("/");
437             writeIdentifierWithNamespacePrefix(element, textContent, pathArgument.getNodeType(), prefixes);
438             if (pathArgument instanceof NodeIdentifierWithPredicates) {
439                 Map<QName, Object> predicates = ((NodeIdentifierWithPredicates) pathArgument).getKeyValues();
440                 for (QName keyValue : predicates.keySet()) {
441                     String predicateValue = String.valueOf(predicates.get(keyValue));
442                     textContent.append("[");
443                     writeIdentifierWithNamespacePrefix(element, textContent, keyValue, prefixes);
444                     textContent.append("='");
445                     textContent.append(predicateValue);
446                     textContent.append("'");
447                     textContent.append("]");
448                 }
449             } else if (pathArgument instanceof NodeWithValue) {
450                 textContent.append("[.='");
451                 textContent.append(((NodeWithValue) pathArgument).getValue());
452                 textContent.append("'");
453                 textContent.append("]");
454             }
455         }
456         element.setTextContent(textContent.toString());
457     }
458
459     /**
460      * Writes identifier that consists of prefix and QName.
461      *
462      * @param element
463      *            {@link Element}
464      * @param textContent
465      *            StringBuilder
466      * @param qName
467      *            QName
468      * @param prefixes
469      *            Map of namespaces and prefixes.
470      */
471     private static void writeIdentifierWithNamespacePrefix(final Element element, final StringBuilder textContent,
472             final QName qName, final Map<String, String> prefixes) {
473         String namespace = qName.getNamespace().toString();
474         String prefix = prefixes.get(namespace);
475         if (prefix == null) {
476             prefix = qName.getPrefix();
477             if (prefix == null || prefix.isEmpty() || prefixes.containsValue(prefix)) {
478                 prefix = generateNewPrefix(prefixes.values());
479             }
480         }
481
482         element.setAttribute("xmlns:" + prefix, namespace);
483         textContent.append(prefix);
484         prefixes.put(namespace, prefix);
485
486         textContent.append(":");
487         textContent.append(qName.getLocalName());
488     }
489
490     /**
491      * Generates new prefix which consists of four random characters <a-z>.
492      *
493      * @param prefixes
494      *            Collection of prefixes.
495      * @return New prefix which consists of four random characters <a-z>.
496      */
497     private static String generateNewPrefix(final Collection<String> prefixes) {
498         StringBuilder result = null;
499         Random random = new Random();
500         do {
501             result = new StringBuilder();
502             for (int i = 0; i < 4; i++) {
503                 int randomNumber = 0x61 + (Math.abs(random.nextInt()) % 26);
504                 result.append(Character.toChars(randomNumber));
505             }
506         } while (prefixes.contains(result.toString()));
507
508         return result.toString();
509     }
510
511     /**
512      * Gets path pointed to data in data store.
513      *
514      * @return Path pointed to data in data store.
515      */
516     public YangInstanceIdentifier getPath() {
517         return path;
518     }
519
520     /**
521      * Sets {@link ListenerRegistration} registration.
522      *
523      * @param registration
524      *            ListenerRegistration<DataChangeListener>
525      */
526     public void setRegistration(final ListenerRegistration<DOMDataChangeListener> registration) {
527         this.registration = registration;
528     }
529
530     /**
531      * Gets the name of the stream.
532      *
533      * @return The name of the stream.
534      */
535     public String getStreamName() {
536         return streamName;
537     }
538
539     /**
540      * Removes all subscribers and unregisters event bus change recorder form event bus.
541      */
542     public void close() throws Exception {
543         subscribers = new ConcurrentSet<>();
544         registration.close();
545         registration = null;
546         eventBus.unregister(eventBusChangeRecorder);
547     }
548
549     /**
550      * Checks if {@link ListenerRegistration} registration exist.
551      *
552      * @return True if exist, false otherwise.
553      */
554     public boolean isListening() {
555         return registration == null ? false : true;
556     }
557
558     /**
559      * Creates event of type {@link EventType#REGISTER}, set {@link Channel} subscriber to the event and post event into
560      * event bus.
561      *
562      * @param subscriber
563      *            Channel
564      */
565     public void addSubscriber(final Channel subscriber) {
566         if (!subscriber.isActive()) {
567             LOG.debug("Channel is not active between websocket server and subscriber {}" + subscriber.remoteAddress());
568         }
569         Event event = new Event(EventType.REGISTER);
570         event.setSubscriber(subscriber);
571         eventBus.post(event);
572     }
573
574     /**
575      * Creates event of type {@link EventType#DEREGISTER}, sets {@link Channel} subscriber to the event and posts event
576      * into event bus.
577      *
578      * @param subscriber
579      */
580     public void removeSubscriber(final Channel subscriber) {
581         LOG.debug("Subscriber {} is removed.", subscriber.remoteAddress());
582         Event event = new Event(EventType.DEREGISTER);
583         event.setSubscriber(subscriber);
584         eventBus.post(event);
585     }
586
587     /**
588      * Checks if exists at least one {@link Channel} subscriber.
589      *
590      * @return True if exist at least one {@link Channel} subscriber, false otherwise.
591      */
592     public boolean hasSubscribers() {
593         return !subscribers.isEmpty();
594     }
595
596     /**
597      * Consists of two types {@link Store#CONFIG} and {@link Store#OPERATION}.
598      */
599     private static enum Store {
600         CONFIG("config"),
601         OPERATION("operation");
602
603         private final String value;
604
605         private Store(final String value) {
606             this.value = value;
607         }
608     }
609
610     /**
611      * Consists of three types {@link Operation#CREATED}, {@link Operation#UPDATED} and {@link Operation#DELETED}.
612      */
613     private static enum Operation {
614         CREATED("created"),
615         UPDATED("updated"),
616         DELETED("deleted");
617
618         private final String value;
619
620         private Operation(final String value) {
621             this.value = value;
622         }
623     }
624
625 }