Using MD-SAL .exists() API
[ovsdb.git] / southbound / southbound-impl / src / main / java / org / opendaylight / ovsdb / southbound / SouthboundProvider.java
index e1dc95bfa6d4ce8c3e03ad31007ccc5dad2f4276..3d421af7510333c358019c109f4654e9a9a21dd7 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,
@@ -7,32 +7,42 @@
  */
 package org.opendaylight.ovsdb.southbound;
 
-import com.google.common.base.Optional;
-import com.google.common.util.concurrent.CheckedFuture;
+import com.google.common.annotations.VisibleForTesting;
+import com.google.common.util.concurrent.FluentFuture;
 import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
+import java.util.ArrayList;
 import java.util.Collection;
-import java.util.Map;
+import java.util.List;
 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.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.data.LogicalDatastoreType;
-import org.opendaylight.controller.md.sal.common.api.data.ReadFailedException;
+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.infrautils.diagstatus.DiagStatusService;
+import org.opendaylight.infrautils.diagstatus.ServiceState;
+import org.opendaylight.infrautils.ready.SystemReadyMonitor;
+import org.opendaylight.mdsal.binding.api.ClusteredDataTreeChangeListener;
+import org.opendaylight.mdsal.binding.api.DataBroker;
+import org.opendaylight.mdsal.binding.api.DataTreeIdentifier;
+import org.opendaylight.mdsal.binding.api.DataTreeModification;
+import org.opendaylight.mdsal.binding.api.ReadWriteTransaction;
 import org.opendaylight.mdsal.binding.dom.codec.api.BindingNormalizedNodeSerializer;
+import org.opendaylight.mdsal.common.api.LogicalDatastoreType;
 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.southbound.reconciliation.OvsdbUpgradeStateListener;
 import org.opendaylight.ovsdb.southbound.transactions.md.TransactionInvoker;
 import org.opendaylight.ovsdb.southbound.transactions.md.TransactionInvokerImpl;
+import org.opendaylight.serviceutils.upgrade.UpgradeState;
 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.network.topology.Topology;
 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.TopologyBuilder;
@@ -42,53 +52,70 @@ import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
+@Singleton
 public class SouthboundProvider implements ClusteredDataTreeChangeListener<Topology>, AutoCloseable {
-
     private static final Logger LOG = LoggerFactory.getLogger(SouthboundProvider.class);
     private static final String ENTITY_TYPE = "ovsdb-southbound-provider";
 
+    // FIXME: get rid of this static
+    @SuppressFBWarnings("ST_WRITE_TO_STATIC_FROM_INSTANCE_METHOD")
+    private static DataBroker db;
+
     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 TransactionInvoker txInvoker;
     private OvsdbDataTreeChangeListener ovsdbDataTreeChangeListener;
+    private OvsdbOperGlobalListener ovsdbOperGlobalListener;
     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 SystemReadyMonitor systemReadyMonitor;
+    private final UpgradeState upgradeState;
     private final AtomicBoolean registered = new AtomicBoolean(false);
     private ListenerRegistration<SouthboundProvider> operTopologyRegistration;
+    private final OvsdbDiagStatusProvider ovsdbStatusProvider;
+    private static List<String> reconcileBridgeInclusionList = new ArrayList<>();
+    private static List<String> reconcileBridgeExclusionList = new ArrayList<>();
+    private OvsdbUpgradeStateListener ovsdbUpgradeStateListener;
 
-    public SouthboundProvider(final DataBroker dataBroker,
-            final EntityOwnershipService entityOwnershipServiceDependency,
-            final OvsdbConnection ovsdbConnection,
-            final DOMSchemaService schemaService,
-            final BindingNormalizedNodeSerializer bindingNormalizedNodeSerializer) {
-        this.db = dataBroker;
+    @Inject
+    public SouthboundProvider(@Reference final DataBroker dataBroker,
+                              @Reference final EntityOwnershipService entityOwnershipServiceDependency,
+                              @Reference final OvsdbConnection ovsdbConnection,
+                              @Reference final DOMSchemaService schemaService,
+                              @Reference final BindingNormalizedNodeSerializer bindingNormalizedNodeSerializer,
+                              @Reference final SystemReadyMonitor systemReadyMonitor,
+                              @Reference final DiagStatusService diagStatusService,
+                              @Reference final UpgradeState upgradeState) {
+        SouthboundProvider.db = dataBroker;
         this.entityOwnershipService = entityOwnershipServiceDependency;
         registration = null;
         this.ovsdbConnection = ovsdbConnection;
-
+        this.ovsdbStatusProvider = new OvsdbDiagStatusProvider(diagStatusService);
         this.instanceIdentifierCodec = new InstanceIdentifierCodec(schemaService,
                 bindingNormalizedNodeSerializer);
+        this.systemReadyMonitor = systemReadyMonitor;
+        this.upgradeState = upgradeState;
         LOG.info("SouthboundProvider ovsdbConnectionService Initialized");
     }
 
     /**
      * Used by blueprint when starting the container.
      */
+    @PostConstruct
     public void init() {
         LOG.info("SouthboundProvider Session Initiated");
+        ovsdbStatusProvider.reportStatus(ServiceState.STARTING, "OVSDB initialization in progress");
         this.txInvoker = new TransactionInvokerImpl(db);
-        cm = new OvsdbConnectionManager(db,txInvoker,entityOwnershipService, ovsdbConnection, instanceIdentifierCodec);
+        cm = new OvsdbConnectionManager(db, txInvoker, entityOwnershipService, ovsdbConnection,
+                instanceIdentifierCodec, upgradeState);
         ovsdbDataTreeChangeListener = new OvsdbDataTreeChangeListener(db, cm, instanceIdentifierCodec);
+        ovsdbOperGlobalListener = new OvsdbOperGlobalListener(db, cm, txInvoker);
 
         //Register listener for entityOnwership changes
         providerOwnershipChangeListener =
@@ -106,42 +133,50 @@ public class SouthboundProvider implements ClusteredDataTreeChangeListener<Topol
                 .create(NetworkTopology.class)
                 .child(Topology.class, new TopologyKey(SouthboundConstants.OVSDB_TOPOLOGY_ID));
         DataTreeIdentifier<Topology> treeId =
-                new DataTreeIdentifier<>(LogicalDatastoreType.OPERATIONAL, path);
+                DataTreeIdentifier.create(LogicalDatastoreType.OPERATIONAL, path);
 
         LOG.trace("Registering listener for path {}", treeId);
         operTopologyRegistration = db.registerDataTreeChangeListener(treeId, this);
+        ovsdbUpgradeStateListener = new OvsdbUpgradeStateListener(db, cm);
     }
 
     @Override
+    @PreDestroy
     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();
         ovsdbDataTreeChangeListener.close();
+        ovsdbOperGlobalListener.close();
         registration.close();
         providerOwnershipChangeListener.close();
         if (operTopologyRegistration != null) {
             operTopologyRegistration.close();
             operTopologyRegistration = null;
         }
+        ovsdbStatusProvider.reportStatus(ServiceState.UNREGISTERED, "OVSDB Service stopped");
+        if (ovsdbUpgradeStateListener != null) {
+            ovsdbUpgradeStateListener.close();
+        }
     }
 
-    private void initializeOvsdbTopology(LogicalDatastoreType type) {
+    private void initializeOvsdbTopology(final LogicalDatastoreType type) {
         InstanceIdentifier<Topology> path = InstanceIdentifier
                 .create(NetworkTopology.class)
                 .child(Topology.class, new TopologyKey(SouthboundConstants.OVSDB_TOPOLOGY_ID));
         ReadWriteTransaction transaction = db.newReadWriteTransaction();
-        CheckedFuture<Optional<Topology>, ReadFailedException> ovsdbTp = transaction.read(type, path);
+        FluentFuture<Boolean> ovsdbTp = transaction.exists(type, path);
         try {
-            if (!ovsdbTp.get().isPresent()) {
+            if (!ovsdbTp.get().booleanValue()) {
                 TopologyBuilder tpb = new TopologyBuilder();
                 tpb.setTopologyId(SouthboundConstants.OVSDB_TOPOLOGY_ID);
-                transaction.put(type, path, tpb.build(), true);
-                transaction.submit();
+                transaction.mergeParentStructurePut(type, path, tpb.build());
+                transaction.commit();
             } else {
                 transaction.cancel();
             }
@@ -150,8 +185,8 @@ public class SouthboundProvider implements ClusteredDataTreeChangeListener<Topol
         }
     }
 
-    public void handleOwnershipChange(EntityOwnershipChange ownershipChange) {
-        if (ownershipChange.isOwner()) {
+    public void handleOwnershipChange(final 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);
@@ -163,18 +198,21 @@ public class SouthboundProvider implements ClusteredDataTreeChangeListener<Topol
     }
 
     @Override
-    public void onDataTreeChanged(Collection<DataTreeModification<Topology>> collection) {
+    public void onDataTreeChanged(final 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();
+            LOG.info("Registering deferred system ready listener to start OVSDB Manager later");
+            systemReadyMonitor.registerListener(() -> {
+                ovsdbConnection.startOvsdbManager();
+                LOG.info("Started OVSDB Manager (in system ready listener)");
+            });
+
+            if (operTopologyRegistration != null) {
+                operTopologyRegistration.close();
+                operTopologyRegistration = null;
+            }
+            ovsdbStatusProvider.reportStatus(ServiceState.OPERATIONAL, "OVSDB initialization complete");
         }
     }
 
@@ -182,8 +220,8 @@ public class SouthboundProvider implements ClusteredDataTreeChangeListener<Topol
         private final SouthboundProvider sp;
         private final EntityOwnershipListenerRegistration listenerRegistration;
 
-        SouthboundPluginInstanceEntityOwnershipListener(SouthboundProvider sp,
-                EntityOwnershipService entityOwnershipService) {
+        SouthboundPluginInstanceEntityOwnershipListener(final SouthboundProvider sp,
+                final EntityOwnershipService entityOwnershipService) {
             this.sp = sp;
             listenerRegistration = entityOwnershipService.registerListener(ENTITY_TYPE, this);
         }
@@ -193,24 +231,12 @@ public class SouthboundProvider implements ClusteredDataTreeChangeListener<Topol
         }
 
         @Override
-        public void ownershipChanged(EntityOwnershipChange ownershipChange) {
+        public void ownershipChanged(final 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;
-                }
-            }
-        }
-    }
-
-    public void setSkipMonitoringManagerStatus(boolean flag) {
+    public void setSkipMonitoringManagerStatus(final boolean flag) {
         LOG.debug("skipManagerStatus set to {}", flag);
         if (flag) {
             SouthboundConstants.SKIP_COLUMN_FROM_TABLE.get("Manager").add("status");
@@ -218,4 +244,29 @@ public class SouthboundProvider implements ClusteredDataTreeChangeListener<Topol
             SouthboundConstants.SKIP_COLUMN_FROM_TABLE.get("Manager").remove("status");
         }
     }
+
+    public static void setBridgesReconciliationInclusionList(final List<String> bridgeList) {
+        reconcileBridgeInclusionList = bridgeList;
+    }
+
+    public static void setBridgesReconciliationExclusionList(final List<String> bridgeList) {
+        reconcileBridgeExclusionList = bridgeList;
+    }
+
+    public static List<String> getBridgesReconciliationInclusionList() {
+        return reconcileBridgeInclusionList;
+    }
+
+    public static List<String> getBridgesReconciliationExclusionList() {
+        return reconcileBridgeExclusionList;
+    }
+
+    @VisibleForTesting
+    boolean isRegistered() {
+        return registered.get();
+    }
+
+    public UpgradeState getUpgradeState() {
+        return upgradeState;
+    }
 }