Migrate topology-manager to OSGi DS
[openflowplugin.git] / applications / topology-manager / src / main / java / org / opendaylight / openflowplugin / applications / topology / manager / FlowCapableTopologyProvider.java
index 7b7071cb910863795d60d26f91d72e78ecbdb0e9..e8b1adf7fe6d8466fad59e9c4a66648a77cb7975 100644 (file)
  */
 package org.opendaylight.openflowplugin.applications.topology.manager;
 
-import java.util.concurrent.ExecutionException;
+import static java.util.Objects.requireNonNull;
 
-import org.opendaylight.controller.md.sal.binding.api.DataBroker;
-import org.opendaylight.controller.md.sal.binding.api.ReadWriteTransaction;
-import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
-import org.opendaylight.controller.sal.binding.api.AbstractBindingAwareProvider;
-import org.opendaylight.controller.sal.binding.api.BindingAwareBroker.ProviderContext;
-import org.opendaylight.controller.sal.binding.api.NotificationProviderService;
+import com.google.common.util.concurrent.Futures;
+import com.google.common.util.concurrent.ListenableFuture;
+import java.util.Optional;
+import java.util.concurrent.ExecutionException;
+import javax.annotation.PreDestroy;
+import javax.inject.Inject;
+import javax.inject.Singleton;
+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;
 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.TopologyBuilder;
 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.TopologyKey;
-import org.opendaylight.yangtools.concepts.ListenerRegistration;
+import org.opendaylight.yangtools.concepts.Registration;
 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
-import org.opendaylight.yangtools.yang.binding.NotificationListener;
-import org.osgi.framework.BundleContext;
+import org.osgi.service.component.annotations.Activate;
+import org.osgi.service.component.annotations.Component;
+import org.osgi.service.component.annotations.Deactivate;
+import org.osgi.service.component.annotations.Reference;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
-public class FlowCapableTopologyProvider extends AbstractBindingAwareProvider implements AutoCloseable {
-    private final static Logger LOG = LoggerFactory.getLogger(FlowCapableTopologyProvider.class);
-    private ListenerRegistration<NotificationListener> listenerRegistration;
-    private Thread thread;
-    private LinkChangeListenerImpl linkChangeListener;
-    private NodeChangeListenerImpl nodeChangeListener;
+@Singleton
+@Component(service = { })
+public final class FlowCapableTopologyProvider implements ClusterSingletonService, AutoCloseable {
+    private static final Logger LOG = LoggerFactory.getLogger(FlowCapableTopologyProvider.class);
+    private static final String TOPOLOGY_PROVIDER = "ofp-topology-manager";
+    static final String TOPOLOGY_ID = "flow:1";
 
-    /**
-     * 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);
+    private final InstanceIdentifier<Topology> topologyPathIID;
+    private final TransactionChainManager transactionChainManager;
+    private final OperationProcessor processor;
 
-        final String name = "flow:1";
-        final TopologyKey key = new TopologyKey(new TopologyId(name));
-        final InstanceIdentifier<Topology> path = InstanceIdentifier
-                .create(NetworkTopology.class)
-                .child(Topology.class, key);
+    private Registration listenerRegistration;
+    private ClusterSingletonServiceRegistration singletonServiceRegistration;
 
-        final OperationProcessor processor = new OperationProcessor(dataBroker);
-        final FlowCapableTopologyExporter listener = new FlowCapableTopologyExporter(processor, path);
-        this.listenerRegistration = notificationService.registerNotificationListener(listener);
-        linkChangeListener = new LinkChangeListenerImpl(dataBroker, processor);
-        nodeChangeListener = new NodeChangeListenerImpl(dataBroker, processor);
+    @Inject
+    @Activate
+    public FlowCapableTopologyProvider(@Reference final DataBroker dataBroker,
+            @Reference final NotificationService notificationService,
+            @Reference final ClusterSingletonServiceProvider clusterSingletonServiceProvider,
+            @Reference final OperationProcessor processor) {
+        this.processor = requireNonNull(processor);
+        final TopologyKey key = new TopologyKey(new TopologyId(TOPOLOGY_ID));
+        topologyPathIID = InstanceIdentifier.create(NetworkTopology.class).child(Topology.class, key);
 
-        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-" + name);
-        thread.start();
+        listenerRegistration = notificationService.registerCompositeListener(
+            new FlowCapableTopologyExporter(processor, topologyPathIID).toListener());
+        transactionChainManager = new TransactionChainManager(dataBroker, TOPOLOGY_PROVIDER);
+        transactionChainManager.activateTransactionManager();
+        transactionChainManager.initialSubmitWriteTransaction();
+        singletonServiceRegistration = clusterSingletonServiceProvider.registerClusterSingletonService(this);
+        LOG.info("Topology Manager service started.");
     }
 
+    @PreDestroy
+    @Deactivate
     @Override
-    public synchronized void close() throws InterruptedException {
-        LOG.info("FlowCapableTopologyProvider stopped.");
-        if (this.listenerRegistration != null) {
-            try {
-                this.listenerRegistration.close();
-            } catch (Exception e) {
-                LOG.error("Failed to close listener registration", e);
-            }
+    public void close() {
+        transactionChainManager.close();
+        if (listenerRegistration != null) {
+            LOG.info("Closing notification listener registration.");
+            listenerRegistration.close();
             listenerRegistration = null;
         }
-        unregisterListener(linkChangeListener);
-        unregisterListener(nodeChangeListener);
-        if (thread != null) {
-            thread.interrupt();
-            thread.join();
-            thread = null;
+
+        if (singletonServiceRegistration != null) {
+            LOG.info("Closing clustering singleton service registration.");
+            singletonServiceRegistration.close();
+            singletonServiceRegistration = null;
         }
+        LOG.info("Topology Manager instance is stopped.");
     }
 
-    private void unregisterListener(final AutoCloseable listenerToClose) {
-        if (listenerToClose != null) {
-            try {
-                listenerToClose.close();
-            } catch (Exception e) {
-                LOG.error("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);
         }
     }
 
-    /**
-     * Gets called during stop bundle
-     *
-     * @param context The execution context of the bundle being stopped.
-     */
     @Override
-    public void stopImpl(final BundleContext context) {
+    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 {
-            this.close();
-        } catch (InterruptedException e) {
-            LOG.error("Failed to stop provider", e);
+            Optional<Topology> ofTopology = transactionChainManager
+                    .readFromTransaction(LogicalDatastoreType.OPERATIONAL, path).get();
+            LOG.debug("OpenFlow topology exist in the operational data store at {}", path);
+            if (ofTopology.isPresent()) {
+                return true;
+            }
+        } catch (InterruptedException | ExecutionException e) {
+            LOG.warn("OpenFlow topology read operation failed!", e);
         }
+        return false;
     }
 }