OVSDB-458 DiagStatus support for OVSDB
[ovsdb.git] / southbound / southbound-impl / src / main / java / org / opendaylight / ovsdb / southbound / SouthboundProvider.java
index 5bc8e568434ffeae7dcdc67adcab13548f7f68f9..990a0df76f409b417dc32428e3bcbd2874190235 100644 (file)
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2014 Cisco Systems, Inc. and others.  All rights reserved.
+ * Copyright (c) 2014, 2018 Cisco Systems, Inc. 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.southbound;
 
+import com.google.common.base.Optional;
+import com.google.common.util.concurrent.CheckedFuture;
+import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
+import java.util.Collection;
+import java.util.Map;
+import java.util.concurrent.ExecutionException;
+import java.util.concurrent.atomic.AtomicBoolean;
+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.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.infrautils.diagstatus.DiagStatusService;
+import org.opendaylight.infrautils.diagstatus.ServiceState;
+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.lib.OvsdbConnection;
-import org.opendaylight.ovsdb.lib.impl.OvsdbConnectionService;
 import org.opendaylight.ovsdb.southbound.transactions.md.TransactionInvoker;
 import org.opendaylight.ovsdb.southbound.transactions.md.TransactionInvokerImpl;
 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 SouthboundProvider implements BindingAwareProvider, AutoCloseable {
+public class SouthboundProvider implements ClusteredDataTreeChangeListener<Topology>, AutoCloseable {
 
     private static final Logger LOG = LoggerFactory.getLogger(SouthboundProvider.class);
-    private DataBroker db;
+    private static final String ENTITY_TYPE = "ovsdb-southbound-provider";
+
+    public static DataBroker getDb() {
+        return db;
+    }
+
+    // FIXME: get rid of this static
+    @SuppressFBWarnings("ST_WRITE_TO_STATIC_FROM_INSTANCE_METHOD")
+    private static DataBroker db;
     private OvsdbConnectionManager cm;
-//    private OvsdbNodeDataChangeListener ovsdbNodeListener;
-//    private OvsdbManagedNodeDataChangeListener ovsdbManagedNodeListener;
-//    private OvsdbTerminationPointDataChangeListener ovsdbTerminationPointListener;
     private TransactionInvoker txInvoker;
-    private OvsdbDataChangeListener ovsdbDataChangeListener;
+    private OvsdbDataTreeChangeListener ovsdbDataTreeChangeListener;
+    private final EntityOwnershipService entityOwnershipService;
+    private EntityOwnershipCandidateRegistration registration;
+    private SouthboundPluginInstanceEntityOwnershipListener providerOwnershipChangeListener;
+    private final OvsdbConnection ovsdbConnection;
+    private final InstanceIdentifierCodec instanceIdentifierCodec;
+    private static final String SKIP_MONITORING_MANAGER_STATUS_PARAM = "skip-monitoring-manager-status";
+    private final AtomicBoolean registered = new AtomicBoolean(false);
+    private ListenerRegistration<SouthboundProvider> operTopologyRegistration;
+    private final OvsdbDiagStatusProvider ovsdbStatusProvider;
 
+    public SouthboundProvider(final DataBroker dataBroker,
+            final EntityOwnershipService entityOwnershipServiceDependency,
+            final OvsdbConnection ovsdbConnection,
+            final DOMSchemaService schemaService,
+            final BindingNormalizedNodeSerializer bindingNormalizedNodeSerializer,
+            final DiagStatusService diagStatusService) {
 
-    @Override
-    public void onSessionInitiated(ProviderContext session) {
+        this.db = dataBroker;
+        this.entityOwnershipService = entityOwnershipServiceDependency;
+        registration = null;
+        this.ovsdbConnection = ovsdbConnection;
+        ovsdbStatusProvider = new OvsdbDiagStatusProvider(diagStatusService);
+
+        this.instanceIdentifierCodec = new InstanceIdentifierCodec(schemaService,
+                bindingNormalizedNodeSerializer);
+        LOG.info("SouthboundProvider ovsdbConnectionService Initialized");
+    }
+
+    /**
+     * Used by blueprint when starting the container.
+     */
+    public void init() {
         LOG.info("SouthboundProvider Session Initiated");
-        db = session.getSALService(DataBroker.class);
+        ovsdbStatusProvider.reportStatus(ServiceState.STARTING, "OVSDB initialization in progress");
         this.txInvoker = new TransactionInvokerImpl(db);
-        cm = new OvsdbConnectionManager(db,txInvoker);
-        ovsdbDataChangeListener = new OvsdbDataChangeListener(db,cm);
-//        ovsdbNodeListener = new OvsdbNodeDataChangeListener(db, cm);
-//        ovsdbManagedNodeListener = new OvsdbManagedNodeDataChangeListener(db, cm);
-//        ovsdbTerminationPointListener = new OvsdbTerminationPointDataChangeListener(db, cm);
-        initializeOvsdbTopology(LogicalDatastoreType.OPERATIONAL);
-        initializeOvsdbTopology(LogicalDatastoreType.CONFIGURATION);
-        OvsdbConnection ovsdbConnection = new OvsdbConnectionService();
-        ovsdbConnection.registerConnectionListener(cm);
-        ovsdbConnection.startOvsdbManager(SouthboundConstants.DEFAULT_OVSDB_PORT);
+        cm = new OvsdbConnectionManager(db, txInvoker, entityOwnershipService, ovsdbConnection,
+                instanceIdentifierCodec);
+        ovsdbDataTreeChangeListener = new OvsdbDataTreeChangeListener(db, cm, instanceIdentifierCodec);
+
+        //Register listener for entityOnwership changes
+        providerOwnershipChangeListener =
+                new SouthboundPluginInstanceEntityOwnershipListener(this,this.entityOwnershipService);
+
+        //register instance entity to get the ownership of the provider
+        Entity instanceEntity = new Entity(ENTITY_TYPE, ENTITY_TYPE);
+        try {
+            registration = entityOwnershipService.registerCandidate(instanceEntity);
+        } catch (CandidateAlreadyRegisteredException e) {
+            LOG.warn("OVSDB Southbound Provider instance entity {} was already "
+                    + "registered for ownership", instanceEntity, e);
+        }
+        InstanceIdentifier<Topology> path = InstanceIdentifier
+                .create(NetworkTopology.class)
+                .child(Topology.class, new TopologyKey(SouthboundConstants.OVSDB_TOPOLOGY_ID));
+        DataTreeIdentifier<Topology> treeId =
+                new DataTreeIdentifier<>(LogicalDatastoreType.OPERATIONAL, path);
+
+        LOG.trace("Registering listener for path {}", treeId);
+        operTopologyRegistration = db.registerDataTreeChangeListener(treeId, this);
     }
 
     @Override
-    public void close() throws Exception {
+    public void close() {
         LOG.info("SouthboundProvider Closed");
+        try {
+            txInvoker.close();
+        } catch (InterruptedException e) {
+            ovsdbStatusProvider.reportStatus(ServiceState.ERROR, "OVSDB service shutdown error");
+            LOG.debug("SouthboundProvider failed to close TransactionInvoker.");
+        }
         cm.close();
-        ovsdbDataChangeListener.close();
-//        ovsdbNodeListener.close();
-//        ovsdbManagedNodeListener.close();
-//        ovsdbTerminationPointListener.close();
+        ovsdbDataTreeChangeListener.close();
+        registration.close();
+        providerOwnershipChangeListener.close();
+        if (operTopologyRegistration != null) {
+            operTopologyRegistration.close();
+            operTopologyRegistration = null;
+        }
+        ovsdbStatusProvider.reportStatus(ServiceState.UNREGISTERED, "OVSDB Service stopped");
     }
 
     private void initializeOvsdbTopology(LogicalDatastoreType type) {
@@ -73,32 +145,88 @@ public class SouthboundProvider implements BindingAwareProvider, AutoCloseable {
                 .create(NetworkTopology.class)
                 .child(Topology.class, new TopologyKey(SouthboundConstants.OVSDB_TOPOLOGY_ID));
         ReadWriteTransaction transaction = db.newReadWriteTransaction();
-        initializeTopology(transaction,type);
         CheckedFuture<Optional<Topology>, ReadFailedException> ovsdbTp = transaction.read(type, path);
         try {
             if (!ovsdbTp.get().isPresent()) {
                 TopologyBuilder tpb = new TopologyBuilder();
                 tpb.setTopologyId(SouthboundConstants.OVSDB_TOPOLOGY_ID);
-                transaction.put(type, path, tpb.build());
+                transaction.put(type, path, tpb.build(), true);
                 transaction.submit();
             } else {
                 transaction.cancel();
             }
-        } catch (Exception e) {
-            LOG.error("Error initializing ovsdb topology {}",e);
+        } catch (InterruptedException | ExecutionException e) {
+            LOG.error("Error initializing ovsdb topology", e);
         }
     }
 
-    private void initializeTopology(ReadWriteTransaction transaction, LogicalDatastoreType type) {
-        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());
+    public void handleOwnershipChange(EntityOwnershipChange ownershipChange) {
+        if (ownershipChange.getState().isOwner()) {
+            LOG.info("*This* instance of OVSDB southbound provider is set as a MASTER instance");
+            LOG.info("Initialize OVSDB topology {} in operational and config data store if not already present",
+                    SouthboundConstants.OVSDB_TOPOLOGY_ID);
+            initializeOvsdbTopology(LogicalDatastoreType.OPERATIONAL);
+            initializeOvsdbTopology(LogicalDatastoreType.CONFIGURATION);
+        } else {
+            LOG.info("*This* instance of OVSDB southbound provider is set as a SLAVE instance");
+        }
+    }
+
+    @Override
+    public void onDataTreeChanged(Collection<DataTreeModification<Topology>> collection) {
+        if (!registered.getAndSet(true)) {
+            LOG.info("Starting the ovsdb port");
+            ovsdbConnection.registerConnectionListener(cm);
+            ovsdbConnection.startOvsdbManager();
+            //mdsal registration/deregistration in mdsal update callback should be avoided
+            new Thread(() -> {
+                if (operTopologyRegistration != null) {
+                    operTopologyRegistration.close();
+                    operTopologyRegistration = null;
+                }
+            }).start();
+            ovsdbStatusProvider.reportStatus(ServiceState.OPERATIONAL, "OVSDB initialization complete");
+        }
+    }
+
+    private static class SouthboundPluginInstanceEntityOwnershipListener implements EntityOwnershipListener {
+        private final SouthboundProvider sp;
+        private final EntityOwnershipListenerRegistration listenerRegistration;
+
+        SouthboundPluginInstanceEntityOwnershipListener(SouthboundProvider sp,
+                EntityOwnershipService entityOwnershipService) {
+            this.sp = sp;
+            listenerRegistration = entityOwnershipService.registerListener(ENTITY_TYPE, this);
+        }
+
+        public void close() {
+            this.listenerRegistration.close();
+        }
+
+        @Override
+        public void ownershipChanged(EntityOwnershipChange ownershipChange) {
+            sp.handleOwnershipChange(ownershipChange);
+        }
+    }
+
+    public void updateConfigParameter(Map<String, Object> configParameters) {
+        if (configParameters != null && !configParameters.isEmpty()) {
+            LOG.debug("Config parameters received : {}", configParameters.entrySet());
+            for (Map.Entry<String, Object> paramEntry : configParameters.entrySet()) {
+                if (paramEntry.getKey().equalsIgnoreCase(SKIP_MONITORING_MANAGER_STATUS_PARAM)) {
+                    setSkipMonitoringManagerStatus(Boolean.parseBoolean((String)paramEntry.getValue()));
+                    break;
+                }
             }
-        } catch (Exception e) {
-            LOG.error("Error initializing ovsdb topology {}",e);
+        }
+    }
+
+    public void setSkipMonitoringManagerStatus(boolean flag) {
+        LOG.debug("skipManagerStatus set to {}", flag);
+        if (flag) {
+            SouthboundConstants.SKIP_COLUMN_FROM_TABLE.get("Manager").add("status");
+        } else {
+            SouthboundConstants.SKIP_COLUMN_FROM_TABLE.get("Manager").remove("status");
         }
     }
 }