Merge "Reverting Overriding in_port in table0 with Zero value"
[genius.git] / mdsalutil / mdsalutil-api / src / main / java / org / opendaylight / genius / datastoreutils / AsyncDataTreeChangeListenerBase.java
1 /*
2  * Copyright (c) 2016 Ericsson India Global Services Pvt Ltd. 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
9 package org.opendaylight.genius.datastoreutils;
10
11 import com.google.common.base.Preconditions;
12 import java.util.Collection;
13 import java.util.concurrent.LinkedBlockingQueue;
14 import java.util.concurrent.ThreadPoolExecutor;
15 import java.util.concurrent.TimeUnit;
16 import javax.annotation.PostConstruct;
17 import javax.annotation.PreDestroy;
18 import org.opendaylight.controller.md.sal.binding.api.DataBroker;
19 import org.opendaylight.controller.md.sal.binding.api.DataObjectModification;
20 import org.opendaylight.controller.md.sal.binding.api.DataTreeChangeListener;
21 import org.opendaylight.controller.md.sal.binding.api.DataTreeIdentifier;
22 import org.opendaylight.controller.md.sal.binding.api.DataTreeModification;
23 import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
24 import org.opendaylight.yangtools.concepts.ListenerRegistration;
25 import org.opendaylight.yangtools.yang.binding.DataObject;
26 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
27 import org.slf4j.Logger;
28 import org.slf4j.LoggerFactory;
29
30 public abstract class AsyncDataTreeChangeListenerBase<T extends DataObject, K extends DataTreeChangeListener>
31         implements DataTreeChangeListener<T>, AutoCloseable {
32
33     private static final Logger LOG = LoggerFactory.getLogger(AsyncDataTreeChangeListenerBase.class);
34
35     private static final int DATATREE_CHANGE_HANDLER_THREAD_POOL_CORE_SIZE = 1;
36     private static final int DATATREE_CHANGE_HANDLER_THREAD_POOL_MAX_SIZE = 1;
37     private static final int DATATREE_CHANGE_HANDLER_THREAD_POOL_KEEP_ALIVE_TIME_SECS = 300;
38     private static final int STARTUP_LOOP_TICK = 500;
39     private static final int STARTUP_LOOP_MAX_RETRIES = 8;
40
41     private ListenerRegistration<K> listenerRegistration;
42
43     private static ThreadPoolExecutor dataTreeChangeHandlerExecutor = new ThreadPoolExecutor(
44             DATATREE_CHANGE_HANDLER_THREAD_POOL_CORE_SIZE,
45             DATATREE_CHANGE_HANDLER_THREAD_POOL_MAX_SIZE,
46             DATATREE_CHANGE_HANDLER_THREAD_POOL_KEEP_ALIVE_TIME_SECS,
47             TimeUnit.SECONDS,
48             new LinkedBlockingQueue<Runnable>());
49
50     protected final Class<T> clazz;
51     private final Class<K> eventClazz;
52
53     public AsyncDataTreeChangeListenerBase(Class<T> clazz, Class<K> eventClazz) {
54         this.clazz = Preconditions.checkNotNull(clazz, "Class can not be null!");
55         this.eventClazz = Preconditions.checkNotNull(eventClazz, "eventClazz can not be null!");
56     }
57
58     @Override
59     public void onDataTreeChanged(Collection<DataTreeModification<T>> changes) {
60         if (changes == null || changes.isEmpty()) {
61             return;
62         }
63
64         DataTreeChangeHandler dataTreeChangeHandler = new DataTreeChangeHandler(changes);
65         dataTreeChangeHandlerExecutor.execute(dataTreeChangeHandler);
66     }
67
68     public void registerListener(LogicalDatastoreType dsType, final DataBroker db) {
69         final DataTreeIdentifier<T> treeId = new DataTreeIdentifier<>(dsType, getWildCardPath());
70         try {
71             TaskRetryLooper looper = new TaskRetryLooper(STARTUP_LOOP_TICK, STARTUP_LOOP_MAX_RETRIES);
72             listenerRegistration = looper.loopUntilNoException(() -> db.registerDataTreeChangeListener(treeId, getDataTreeChangeListener()));
73         } catch (final Exception e) {
74             LOG.warn("{}: Data Tree Change listener registration failed.", eventClazz.getName());
75             LOG.debug("{}: Data Tree Change listener registration failed: {}", eventClazz.getName(), e);
76             throw new IllegalStateException( eventClazz.getName() + "{}startup failed. System needs restart.", e);
77         }
78     }
79
80     /**
81      * Subclasses override this and place initialization logic here, notably
82      * calls to registerListener(). Note that the overriding method MUST repeat
83      * the PostConstruct annotation, because JSR 250 specifies that lifecycle
84      * methods "are called unless a subclass of the declaring class overrides
85      * the method without repeating the annotation".  (The blueprint-maven-plugin
86      * would gen. XML which calls PostConstruct annotated methods even if they are
87      * in a subclass without repeating the annotation, but this is wrong and not
88      * JSR 250 compliant, and while working in BP, then causes issues e.g. when
89      * wiring with Guice for tests, so do always repeat it.)
90      */
91     @PostConstruct
92     protected void init() {
93     }
94
95     @Override
96     @PreDestroy
97     public void close() throws Exception {
98         if (listenerRegistration != null) {
99             try {
100                 listenerRegistration.close();
101             } catch (final Exception e) {
102                 LOG.error("Error when cleaning up DataTreeChangeListener.", e);
103             }
104             listenerRegistration = null;
105         }
106     }
107
108     protected abstract InstanceIdentifier<T> getWildCardPath();
109     protected abstract void remove(InstanceIdentifier<T> key, T dataObjectModification);
110     protected abstract void update(InstanceIdentifier<T> key, T dataObjectModificationBefore, T dataObjectModificationAfter);
111     protected abstract void add(InstanceIdentifier<T> key, T dataObjectModification);
112     protected abstract K getDataTreeChangeListener();
113
114     public class DataTreeChangeHandler implements Runnable {
115         Collection<DataTreeModification<T>> changes;
116
117         public DataTreeChangeHandler(Collection<DataTreeModification<T>> changes) {
118             this.changes = changes;
119         }
120
121         @Override
122         public void run() {
123             for (DataTreeModification<T> change : changes) {
124                 final InstanceIdentifier<T> key = change.getRootPath().getRootIdentifier();
125                 final DataObjectModification<T> mod = change.getRootNode();
126
127                 switch (mod.getModificationType()) {
128                     case DELETE:
129                         remove(key, mod.getDataBefore());
130                         break;
131                     case SUBTREE_MODIFIED:
132                         update(key, mod.getDataBefore(), mod.getDataAfter());
133                         break;
134                     case WRITE:
135                         if (mod.getDataBefore() == null) {
136                             add(key, mod.getDataAfter());
137                         } else {
138                             update(key, mod.getDataBefore(), mod.getDataAfter());
139                         }
140                         break;
141                     default:
142                         // FIXME: May be not a good idea to throw.
143                         throw new IllegalArgumentException("Unhandled modification type " + mod.getModificationType());
144                 }
145             }
146         }
147     }
148 }