Bump odlparent to 5.0.0
[openflowplugin.git] / applications / topology-manager / src / main / java / org / opendaylight / openflowplugin / applications / topology / manager / FlowCapableTopologyProvider.java
index 66168949ff76176ea6b4720a82905c4efd1f1328..83bcb9f81cc9061c03dfe774bcddb3ae24094b0d 100644 (file)
@@ -7,17 +7,23 @@
  */
 package org.opendaylight.openflowplugin.applications.topology.manager;
 
+import com.google.common.util.concurrent.Futures;
+import com.google.common.util.concurrent.ListenableFuture;
+import java.util.Optional;
 import java.util.concurrent.ExecutionException;
-
-import com.google.common.base.Optional;
-import org.opendaylight.controller.md.sal.binding.api.DataBroker;
-import org.opendaylight.controller.md.sal.binding.api.ReadTransaction;
-import org.opendaylight.controller.md.sal.binding.api.ReadWriteTransaction;
-import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
-import org.opendaylight.controller.md.sal.common.api.data.ReadFailedException;
-import org.opendaylight.controller.sal.binding.api.BindingAwareBroker.ProviderContext;
-import org.opendaylight.controller.sal.binding.api.BindingAwareProvider;
-import org.opendaylight.controller.sal.binding.api.NotificationProviderService;
+import javax.annotation.PostConstruct;
+import javax.annotation.PreDestroy;
+import javax.inject.Inject;
+import javax.inject.Singleton;
+import org.apache.aries.blueprint.annotation.service.Reference;
+import org.opendaylight.mdsal.binding.api.DataBroker;
+import org.opendaylight.mdsal.binding.api.NotificationService;
+import org.opendaylight.mdsal.common.api.LogicalDatastoreType;
+import org.opendaylight.mdsal.singleton.common.api.ClusterSingletonService;
+import org.opendaylight.mdsal.singleton.common.api.ClusterSingletonServiceProvider;
+import org.opendaylight.mdsal.singleton.common.api.ClusterSingletonServiceRegistration;
+import org.opendaylight.mdsal.singleton.common.api.ServiceGroupIdentifier;
+import org.opendaylight.openflowplugin.common.txchain.TransactionChainManager;
 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.NetworkTopology;
 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.TopologyId;
 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.Topology;
@@ -29,93 +35,98 @@ import org.opendaylight.yangtools.yang.binding.NotificationListener;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
-public class FlowCapableTopologyProvider implements BindingAwareProvider, AutoCloseable {
+@Singleton
+public class FlowCapableTopologyProvider implements ClusterSingletonService, AutoCloseable {
     private static final Logger LOG = LoggerFactory.getLogger(FlowCapableTopologyProvider.class);
-    private ListenerRegistration<NotificationListener> listenerRegistration;
-    private Thread thread;
-    private TerminationPointChangeListenerImpl terminationPointChangeListener;
-    private NodeChangeListenerImpl nodeChangeListener;
+    private static final String TOPOLOGY_PROVIDER = "ofp-topology-manager";
     static final String TOPOLOGY_ID = "flow:1";
 
+    private final DataBroker dataBroker;
+    private final NotificationService notificationService;
+    private final OperationProcessor processor;
+    private final ClusterSingletonServiceProvider clusterSingletonServiceProvider;
+    private InstanceIdentifier<Topology> topologyPathIID;
+    private TransactionChainManager transactionChainManager;
+    private ListenerRegistration<NotificationListener> listenerRegistration;
+    private ClusterSingletonServiceRegistration singletonServiceRegistration;
+
+    @Inject
+    public FlowCapableTopologyProvider(@Reference final DataBroker dataBroker,
+                                       @Reference final NotificationService notificationService,
+                                       final OperationProcessor processor,
+                                       @Reference final ClusterSingletonServiceProvider
+                                               clusterSingletonServiceProvider) {
+        this.dataBroker = dataBroker;
+        this.notificationService = notificationService;
+        this.processor = processor;
+        this.clusterSingletonServiceProvider = clusterSingletonServiceProvider;
+    }
+
     /**
      * Gets called on start of a bundle.
-     *
-     * @param session
      */
-    @Override
-    public synchronized void onSessionInitiated(final ProviderContext session) {
-        final DataBroker dataBroker = session.getSALService(DataBroker.class);
-        final NotificationProviderService notificationService = session.getSALService(NotificationProviderService.class);
-
+    @PostConstruct
+    public void start() {
         final TopologyKey key = new TopologyKey(new TopologyId(TOPOLOGY_ID));
-        final InstanceIdentifier<Topology> path = InstanceIdentifier
-                .create(NetworkTopology.class)
-                .child(Topology.class, key);
+        this.topologyPathIID = InstanceIdentifier.create(NetworkTopology.class).child(Topology.class, key);
 
-        final OperationProcessor processor = new OperationProcessor(dataBroker);
-        final FlowCapableTopologyExporter listener = new FlowCapableTopologyExporter(processor, path);
+        final FlowCapableTopologyExporter listener = new FlowCapableTopologyExporter(processor, topologyPathIID);
         this.listenerRegistration = notificationService.registerNotificationListener(listener);
-        this.terminationPointChangeListener = new TerminationPointChangeListenerImpl(dataBroker, processor);
-        nodeChangeListener = new NodeChangeListenerImpl(dataBroker, processor);
-
-        if(!isFlowTopologyExist(dataBroker, path)){
-            final ReadWriteTransaction tx = dataBroker.newReadWriteTransaction();
-            tx.put(LogicalDatastoreType.OPERATIONAL, path, new TopologyBuilder().setKey(key).build(), true);
-            try {
-                tx.submit().get();
-            } catch (InterruptedException | ExecutionException e) {
-                LOG.warn("Initial topology export failed, continuing anyway", e);
-            }
-        }
-
-        thread = new Thread(processor);
-        thread.setDaemon(true);
-        thread.setName("FlowCapableTopologyExporter-" + TOPOLOGY_ID);
-        thread.start();
+        this.transactionChainManager = new TransactionChainManager(dataBroker, TOPOLOGY_PROVIDER);
+        this.transactionChainManager.activateTransactionManager();
+        this.transactionChainManager.initialSubmitWriteTransaction();
+        this.singletonServiceRegistration = this.clusterSingletonServiceProvider.registerClusterSingletonService(this);
+        LOG.info("Topology Manager service started.");
     }
 
     @Override
-    public synchronized void close() throws InterruptedException {
-        LOG.info("FlowCapableTopologyProvider stopped.");
+    @PreDestroy
+    public void close() {
+        this.transactionChainManager.close();
         if (this.listenerRegistration != null) {
-            try {
-                this.listenerRegistration.close();
-            } catch (Exception e) {
-                LOG.warn("Failed to close listener registration: {}", e.getMessage());
-                LOG.debug("Failed to close listener registration.. ", e);
-            }
-            listenerRegistration = null;
+            LOG.info("Closing notification listener registration.");
+            this.listenerRegistration.close();
+            this.listenerRegistration = null;
         }
-        unregisterListener(terminationPointChangeListener);
-        unregisterListener(nodeChangeListener);
-        if (thread != null) {
-            thread.interrupt();
-            thread.join();
-            thread = null;
+
+        if (this.singletonServiceRegistration != null) {
+            LOG.info("Closing clustering singleton service registration.");
+            this.singletonServiceRegistration.close();
+            this.singletonServiceRegistration = null;
         }
+        LOG.debug("Topology Manager instance is stopped.");
     }
 
-    private static void unregisterListener(final AutoCloseable listenerToClose) {
-        if (listenerToClose != null) {
-            try {
-                listenerToClose.close();
-            } catch (Exception e) {
-                LOG.warn("Failed to close listener registration: {}", e.getMessage());
-                LOG.debug("Failed to close listener registration.. ", e);
-            }
+    @Override
+    public void instantiateServiceInstance() {
+        LOG.debug("Topology Manager instance is elected as an active instance.");
+        if (!isFlowTopologyExist(topologyPathIID)) {
+            transactionChainManager.writeToTransaction(LogicalDatastoreType.OPERATIONAL, topologyPathIID,
+                    new TopologyBuilder().withKey(new TopologyKey(new TopologyId(TOPOLOGY_ID))).build(), true);
+            transactionChainManager.submitTransaction();
+            LOG.info("Topology node {} is successfully written to the operational datastore.", TOPOLOGY_ID);
         }
     }
 
-    private boolean isFlowTopologyExist(final DataBroker dataBroker,
-                                        final InstanceIdentifier<Topology> path) {
-        final ReadTransaction tx = dataBroker.newReadOnlyTransaction();
+    @Override
+    public ListenableFuture<? extends Object> closeServiceInstance() {
+        return Futures.immediateFuture(null);
+    }
+
+    @Override
+    public ServiceGroupIdentifier getIdentifier() {
+        return ServiceGroupIdentifier.create(TOPOLOGY_PROVIDER);
+    }
+
+    private boolean isFlowTopologyExist(final InstanceIdentifier<Topology> path) {
         try {
-            Optional<Topology> ofTopology = tx.read(LogicalDatastoreType.OPERATIONAL, path).checkedGet();
-            LOG.debug("OpenFlow topology exist in the operational data store at {}",path);
-            if(ofTopology.isPresent()){
+            Optional<Topology> ofTopology = this.transactionChainManager
+                    .readFromTransaction(LogicalDatastoreType.OPERATIONAL, path).get();
+            LOG.debug("OpenFlow topology exist in the operational data store at {}", path);
+            if (ofTopology.isPresent()) {
                 return true;
             }
-        } catch (ReadFailedException e) {
+        } catch (InterruptedException | ExecutionException e) {
             LOG.warn("OpenFlow topology read operation failed!", e);
         }
         return false;