use annotations instead of XML for Blueprint
[ovsdb.git] / hwvtepsouthbound / hwvtepsouthbound-impl / src / main / java / org / opendaylight / ovsdb / hwvtepsouthbound / HwvtepSouthboundProvider.java
index 622ca0364d4fba724d73d68dad5e121a49f4611a..1c9af4e5d3231f3bbaba096e4d42c9e4209bffe6 100644 (file)
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2015 Ericsson India Global Services Pvt Ltd. and others.  All rights reserved.
+ * Copyright © 2015, 2017 Ericsson India Global Services Pvt Ltd. and others.  All rights reserved.
  *
  * This program and the accompanying materials are made available under the
  * terms of the Eclipse Public License v1.0 which accompanies this distribution,
  */
 package org.opendaylight.ovsdb.hwvtepsouthbound;
 
+import com.google.common.base.Optional;
+import com.google.common.util.concurrent.CheckedFuture;
+import java.util.Collection;
+import java.util.concurrent.ExecutionException;
+import java.util.concurrent.atomic.AtomicBoolean;
+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.controller.md.sal.binding.api.ClusteredDataTreeChangeListener;
 import org.opendaylight.controller.md.sal.binding.api.DataBroker;
+import org.opendaylight.controller.md.sal.binding.api.DataTreeIdentifier;
+import org.opendaylight.controller.md.sal.binding.api.DataTreeModification;
 import org.opendaylight.controller.md.sal.binding.api.ReadWriteTransaction;
-import org.opendaylight.controller.md.sal.common.api.clustering.CandidateAlreadyRegisteredException;
-import org.opendaylight.controller.md.sal.common.api.clustering.Entity;
-import org.opendaylight.controller.md.sal.common.api.clustering.EntityOwnershipCandidateRegistration;
-import org.opendaylight.controller.md.sal.common.api.clustering.EntityOwnershipChange;
-import org.opendaylight.controller.md.sal.common.api.clustering.EntityOwnershipListener;
-import org.opendaylight.controller.md.sal.common.api.clustering.EntityOwnershipListenerRegistration;
-import org.opendaylight.controller.md.sal.common.api.clustering.EntityOwnershipService;
-import org.opendaylight.controller.md.sal.common.api.clustering.EntityOwnershipState;
 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.mdsal.binding.dom.codec.api.BindingNormalizedNodeSerializer;
+import org.opendaylight.mdsal.dom.api.DOMSchemaService;
+import org.opendaylight.mdsal.eos.binding.api.Entity;
+import org.opendaylight.mdsal.eos.binding.api.EntityOwnershipCandidateRegistration;
+import org.opendaylight.mdsal.eos.binding.api.EntityOwnershipChange;
+import org.opendaylight.mdsal.eos.binding.api.EntityOwnershipListener;
+import org.opendaylight.mdsal.eos.binding.api.EntityOwnershipListenerRegistration;
+import org.opendaylight.mdsal.eos.binding.api.EntityOwnershipService;
+import org.opendaylight.mdsal.eos.common.api.CandidateAlreadyRegisteredException;
+import org.opendaylight.ovsdb.hwvtepsouthbound.reconciliation.configuration.HwvtepReconciliationManager;
 import org.opendaylight.ovsdb.hwvtepsouthbound.transactions.md.TransactionInvoker;
 import org.opendaylight.ovsdb.hwvtepsouthbound.transactions.md.TransactionInvokerImpl;
 import org.opendaylight.ovsdb.lib.OvsdbConnection;
-import org.opendaylight.ovsdb.lib.impl.OvsdbConnectionService;
 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.NetworkTopologyBuilder;
 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.yang.binding.InstanceIdentifier;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
-import com.google.common.base.Optional;
-import com.google.common.util.concurrent.CheckedFuture;
-
-public class HwvtepSouthboundProvider implements BindingAwareProvider, AutoCloseable {
+@Singleton
+public class HwvtepSouthboundProvider implements ClusteredDataTreeChangeListener<Topology>, AutoCloseable {
 
     private static final Logger LOG = LoggerFactory.getLogger(HwvtepSouthboundProvider.class);
     private static final String ENTITY_TYPE = "ovsdb-hwvtepsouthbound-provider";
 
-    public static DataBroker getDb() {
-        return db;
-    }
+    private final DataBroker dataBroker;
+    private final EntityOwnershipService entityOwnershipService;
+    private final OvsdbConnection ovsdbConnection;
 
-    private static DataBroker db;
     private HwvtepConnectionManager cm;
-    private OvsdbConnection ovsdbConnection;
     private TransactionInvoker txInvoker;
-    private EntityOwnershipService entityOwnershipService;
     private EntityOwnershipCandidateRegistration registration;
     private HwvtepsbPluginInstanceEntityOwnershipListener providerOwnershipChangeListener;
     private HwvtepDataChangeListener hwvtepDTListener;
-
-    public HwvtepSouthboundProvider(
-            EntityOwnershipService entityOwnershipServiceDependency) {
+    private HwvtepReconciliationManager hwvtepReconciliationManager;
+    private final AtomicBoolean registered = new AtomicBoolean(false);
+    private ListenerRegistration<HwvtepSouthboundProvider> operTopologyRegistration;
+
+    @Inject
+    public HwvtepSouthboundProvider(@Reference final DataBroker dataBroker,
+            @Reference final EntityOwnershipService entityOwnershipServiceDependency,
+            @Reference final OvsdbConnection ovsdbConnection,
+            @Reference final DOMSchemaService schemaService,
+            @Reference final BindingNormalizedNodeSerializer bindingNormalizedNodeSerializer) {
+        this.dataBroker = dataBroker;
         this.entityOwnershipService = entityOwnershipServiceDependency;
         registration = null;
+        this.ovsdbConnection = ovsdbConnection;
+        HwvtepSouthboundUtil.setInstanceIdentifierCodec(new InstanceIdentifierCodec(schemaService,
+                bindingNormalizedNodeSerializer));
+        LOG.info("HwvtepSouthboundProvider ovsdbConnectionService: {}", ovsdbConnection);
     }
 
-    @Override
-    public void onSessionInitiated(ProviderContext session) {
+    /**
+     * Used by blueprint when starting the container.
+     */
+    @PostConstruct
+    public void init() {
         LOG.info("HwvtepSouthboundProvider Session Initiated");
-        db = session.getSALService(DataBroker.class);
-        txInvoker = new TransactionInvokerImpl(db);
-        cm = new HwvtepConnectionManager(db, txInvoker, entityOwnershipService);
-        hwvtepDTListener = new HwvtepDataChangeListener(db, cm);
-
+        txInvoker = new TransactionInvokerImpl(dataBroker);
+        cm = new HwvtepConnectionManager(dataBroker, txInvoker, entityOwnershipService, ovsdbConnection);
+        hwvtepDTListener = new HwvtepDataChangeListener(dataBroker, cm);
+        hwvtepReconciliationManager = new HwvtepReconciliationManager(dataBroker, cm);
         //Register listener for entityOnwership changes
         providerOwnershipChangeListener =
                 new HwvtepsbPluginInstanceEntityOwnershipListener(this,this.entityOwnershipService);
-        entityOwnershipService.registerListener(ENTITY_TYPE,providerOwnershipChangeListener);
 
         //register instance entity to get the ownership of the provider
         Entity instanceEntity = new Entity(ENTITY_TYPE, ENTITY_TYPE);
         try {
-            Optional<EntityOwnershipState> ownershipStateOpt = entityOwnershipService.getOwnershipState(instanceEntity);
             registration = entityOwnershipService.registerCandidate(instanceEntity);
-            if (ownershipStateOpt.isPresent()) {
-                EntityOwnershipState ownershipState = ownershipStateOpt.get();
-                if (ownershipState.hasOwner() && !ownershipState.isOwner()) {
-                    if (ovsdbConnection == null) {
-                        ovsdbConnection = new OvsdbConnectionService();
-                        ovsdbConnection.registerConnectionListener(cm);
-                        ovsdbConnection.startOvsdbManager(HwvtepSouthboundConstants.DEFAULT_OVSDB_PORT);
-                    }
-                }
-            }
         } catch (CandidateAlreadyRegisteredException e) {
             LOG.warn("HWVTEP Southbound Provider instance entity {} was already "
-                    + "registered for {} ownership", instanceEntity, e);
+                    + "registered for ownership", instanceEntity, e);
         }
+        InstanceIdentifier<Topology> path = InstanceIdentifier
+                .create(NetworkTopology.class)
+                .child(Topology.class, new TopologyKey(HwvtepSouthboundConstants.HWVTEP_TOPOLOGY_ID));
+        DataTreeIdentifier<Topology> treeId =
+                new DataTreeIdentifier<>(LogicalDatastoreType.OPERATIONAL, path);
+
+        LOG.trace("Registering listener for path {}", treeId);
+        operTopologyRegistration = dataBroker.registerDataTreeChangeListener(treeId, this);
     }
 
     @Override
+    @PreDestroy
+    @SuppressWarnings("checkstyle:IllegalCatch")
     public void close() throws Exception {
         LOG.info("HwvtepSouthboundProvider Closed");
-        if(cm != null){
+        if (txInvoker != null) {
+            try {
+                txInvoker.close();
+                txInvoker = null;
+            } catch (Exception e) {
+                LOG.error("HWVTEP Southbound Provider failed to close TransactionInvoker", e);
+            }
+        }
+        if (cm != null) {
             cm.close();
             cm = null;
         }
-        if(registration != null) {
+        if (registration != null) {
             registration.close();
             registration = null;
         }
-        if(providerOwnershipChangeListener != null) {
+        if (providerOwnershipChangeListener != null) {
             providerOwnershipChangeListener.close();
             providerOwnershipChangeListener = null;
         }
-        if(hwvtepDTListener != null) {
+        if (hwvtepDTListener != null) {
             hwvtepDTListener.close();
             hwvtepDTListener = null;
         }
+        if (operTopologyRegistration != null) {
+            operTopologyRegistration.close();
+            operTopologyRegistration = null;
+        }
     }
 
     private void initializeHwvtepTopology(LogicalDatastoreType type) {
         InstanceIdentifier<Topology> path = InstanceIdentifier
                 .create(NetworkTopology.class)
                 .child(Topology.class, new TopologyKey(HwvtepSouthboundConstants.HWVTEP_TOPOLOGY_ID));
-        initializeTopology(type);
-        ReadWriteTransaction transaction = db.newReadWriteTransaction();
+        ReadWriteTransaction transaction = dataBroker.newReadWriteTransaction();
         CheckedFuture<Optional<Topology>, ReadFailedException> hwvtepTp = transaction.read(type, path);
         try {
             if (!hwvtepTp.get().isPresent()) {
                 TopologyBuilder tpb = new TopologyBuilder();
                 tpb.setTopologyId(HwvtepSouthboundConstants.HWVTEP_TOPOLOGY_ID);
-                transaction.put(type, path, tpb.build());
+                transaction.put(type, path, tpb.build(), true);
                 transaction.submit();
             } else {
                 transaction.cancel();
             }
-        } catch (Exception e) {
+        } catch (InterruptedException | ExecutionException e) {
             LOG.error("Error initializing hwvtep topology", e);
         }
     }
 
-    private void initializeTopology(LogicalDatastoreType type) {
-        ReadWriteTransaction transaction = db.newReadWriteTransaction();
-        InstanceIdentifier<NetworkTopology> path = InstanceIdentifier.create(NetworkTopology.class);
-        CheckedFuture<Optional<NetworkTopology>, ReadFailedException> topology = transaction.read(type,path);
-        try {
-            if (!topology.get().isPresent()) {
-                NetworkTopologyBuilder ntb = new NetworkTopologyBuilder();
-                transaction.put(type,path,ntb.build());
-                transaction.submit();
-            } else {
-                transaction.cancel();
-            }
-        } catch (Exception e) {
-            LOG.error("Error initializing hwvtep topology {}",e);
-        }
-    }
-
     public void handleOwnershipChange(EntityOwnershipChange ownershipChange) {
-        if (ownershipChange.isOwner()) {
+        if (ownershipChange.getState().isOwner()) {
             LOG.info("*This* instance of HWVTEP southbound provider is set as a MASTER instance");
-            LOG.info("Initialize HWVTEP topology {} in operational and config data store if not already present"
-                    ,HwvtepSouthboundConstants.HWVTEP_TOPOLOGY_ID);
+            LOG.info("Initialize HWVTEP topology {} in operational and config data store if not already present",
+                    HwvtepSouthboundConstants.HWVTEP_TOPOLOGY_ID);
             initializeHwvtepTopology(LogicalDatastoreType.OPERATIONAL);
             initializeHwvtepTopology(LogicalDatastoreType.CONFIGURATION);
         } else {
             LOG.info("*This* instance of HWVTEP southbound provider is set as a SLAVE instance");
         }
-        //TODO: How to make this co-exist with OvsdbSouthbound?
-        if (ovsdbConnection == null) {
-            ovsdbConnection = new OvsdbConnectionService();
+    }
+
+
+    @Override
+    public void onDataTreeChanged(Collection<DataTreeModification<Topology>> collection) {
+        if (!registered.getAndSet(true)) {
+            LOG.info("Starting the ovsdb port");
             ovsdbConnection.registerConnectionListener(cm);
-            ovsdbConnection.startOvsdbManager(HwvtepSouthboundConstants.DEFAULT_OVSDB_PORT);
+            ovsdbConnection.startOvsdbManager();
         }
+        //mdsal registration/deregistration in mdsal update callback should be avoided
+        new Thread(() -> {
+            if (operTopologyRegistration != null) {
+                operTopologyRegistration.close();
+                operTopologyRegistration = null;
+            }
+        }).start();
     }
 
-    private class HwvtepsbPluginInstanceEntityOwnershipListener implements EntityOwnershipListener {
-        private HwvtepSouthboundProvider hsp;
-        private EntityOwnershipListenerRegistration listenerRegistration;
+    private static class HwvtepsbPluginInstanceEntityOwnershipListener implements EntityOwnershipListener {
+        private final HwvtepSouthboundProvider hsp;
+        private final EntityOwnershipListenerRegistration listenerRegistration;
 
         HwvtepsbPluginInstanceEntityOwnershipListener(HwvtepSouthboundProvider hsp,
                 EntityOwnershipService entityOwnershipService) {
@@ -185,10 +209,14 @@ public class HwvtepSouthboundProvider implements BindingAwareProvider, AutoClose
         public void close() {
             this.listenerRegistration.close();
         }
+
         @Override
         public void ownershipChanged(EntityOwnershipChange ownershipChange) {
             hsp.handleOwnershipChange(ownershipChange);
         }
     }
 
+    public HwvtepConnectionManager getHwvtepConnectionManager() {
+        return cm;
+    }
 }