Upgrade support of ovsdb reconciliation
[ovsdb.git] / southbound / southbound-impl / src / main / java / org / opendaylight / ovsdb / southbound / SouthboundProvider.java
1 /*
2  * Copyright (c) 2014, 2018 Cisco Systems, Inc. and others.  All rights reserved.
3  *
4  * This program and the accompanying materials are made available under the
5  * terms of the Eclipse Public License v1.0 which accompanies this distribution,
6  * and is available at http://www.eclipse.org/legal/epl-v10.html
7  */
8 package org.opendaylight.ovsdb.southbound;
9
10 import com.google.common.annotations.VisibleForTesting;
11 import com.google.common.base.Optional;
12 import com.google.common.util.concurrent.CheckedFuture;
13 import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
14 import java.util.ArrayList;
15 import java.util.Collection;
16 import java.util.List;
17 import java.util.concurrent.ExecutionException;
18 import java.util.concurrent.atomic.AtomicBoolean;
19 import javax.annotation.PostConstruct;
20 import javax.annotation.PreDestroy;
21 import javax.inject.Inject;
22 import javax.inject.Singleton;
23 import org.apache.aries.blueprint.annotation.service.Reference;
24 import org.opendaylight.controller.md.sal.binding.api.ClusteredDataTreeChangeListener;
25 import org.opendaylight.controller.md.sal.binding.api.DataBroker;
26 import org.opendaylight.controller.md.sal.binding.api.DataTreeIdentifier;
27 import org.opendaylight.controller.md.sal.binding.api.DataTreeModification;
28 import org.opendaylight.controller.md.sal.binding.api.ReadWriteTransaction;
29 import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
30 import org.opendaylight.controller.md.sal.common.api.data.ReadFailedException;
31 import org.opendaylight.infrautils.diagstatus.DiagStatusService;
32 import org.opendaylight.infrautils.diagstatus.ServiceState;
33 import org.opendaylight.infrautils.ready.SystemReadyMonitor;
34 import org.opendaylight.mdsal.binding.dom.codec.api.BindingNormalizedNodeSerializer;
35 import org.opendaylight.mdsal.dom.api.DOMSchemaService;
36 import org.opendaylight.mdsal.eos.binding.api.Entity;
37 import org.opendaylight.mdsal.eos.binding.api.EntityOwnershipCandidateRegistration;
38 import org.opendaylight.mdsal.eos.binding.api.EntityOwnershipChange;
39 import org.opendaylight.mdsal.eos.binding.api.EntityOwnershipListener;
40 import org.opendaylight.mdsal.eos.binding.api.EntityOwnershipListenerRegistration;
41 import org.opendaylight.mdsal.eos.binding.api.EntityOwnershipService;
42 import org.opendaylight.mdsal.eos.common.api.CandidateAlreadyRegisteredException;
43 import org.opendaylight.ovsdb.lib.OvsdbConnection;
44 import org.opendaylight.ovsdb.southbound.reconciliation.OvsdbUpgradeStateListener;
45 import org.opendaylight.ovsdb.southbound.transactions.md.TransactionInvoker;
46 import org.opendaylight.ovsdb.southbound.transactions.md.TransactionInvokerImpl;
47 import org.opendaylight.serviceutils.upgrade.UpgradeState;
48 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.NetworkTopology;
49 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.Topology;
50 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.TopologyBuilder;
51 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.TopologyKey;
52 import org.opendaylight.yangtools.concepts.ListenerRegistration;
53 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
54 import org.slf4j.Logger;
55 import org.slf4j.LoggerFactory;
56
57 @Singleton
58 public class SouthboundProvider implements ClusteredDataTreeChangeListener<Topology>, AutoCloseable {
59
60     private static final Logger LOG = LoggerFactory.getLogger(SouthboundProvider.class);
61
62     private static final String ENTITY_TYPE = "ovsdb-southbound-provider";
63
64     public static DataBroker getDb() {
65         return db;
66     }
67
68     // FIXME: get rid of this static
69     @SuppressFBWarnings("ST_WRITE_TO_STATIC_FROM_INSTANCE_METHOD")
70     private static DataBroker db;
71     private OvsdbConnectionManager cm;
72     private TransactionInvoker txInvoker;
73     private OvsdbDataTreeChangeListener ovsdbDataTreeChangeListener;
74     private final EntityOwnershipService entityOwnershipService;
75     private EntityOwnershipCandidateRegistration registration;
76     private SouthboundPluginInstanceEntityOwnershipListener providerOwnershipChangeListener;
77     private final OvsdbConnection ovsdbConnection;
78     private final InstanceIdentifierCodec instanceIdentifierCodec;
79     private final SystemReadyMonitor systemReadyMonitor;
80     private final UpgradeState upgradeState;
81     private final AtomicBoolean registered = new AtomicBoolean(false);
82     private ListenerRegistration<SouthboundProvider> operTopologyRegistration;
83     private final OvsdbDiagStatusProvider ovsdbStatusProvider;
84     private static List<String> reconcileBridgeInclusionList = new ArrayList<>();
85     private static List<String> reconcileBridgeExclusionList = new ArrayList<>();
86     private OvsdbUpgradeStateListener ovsdbUpgradeStateListener;
87
88     @Inject
89     public SouthboundProvider(@Reference final DataBroker dataBroker,
90                               @Reference final EntityOwnershipService entityOwnershipServiceDependency,
91                               @Reference final OvsdbConnection ovsdbConnection,
92                               @Reference final DOMSchemaService schemaService,
93                               @Reference final BindingNormalizedNodeSerializer bindingNormalizedNodeSerializer,
94                               @Reference final SystemReadyMonitor systemReadyMonitor,
95                               @Reference final DiagStatusService diagStatusService,
96                               @Reference final UpgradeState upgradeState) {
97         SouthboundProvider.db = dataBroker;
98         this.entityOwnershipService = entityOwnershipServiceDependency;
99         registration = null;
100         this.ovsdbConnection = ovsdbConnection;
101         this.ovsdbStatusProvider = new OvsdbDiagStatusProvider(diagStatusService);
102         this.instanceIdentifierCodec = new InstanceIdentifierCodec(schemaService,
103                 bindingNormalizedNodeSerializer);
104         this.systemReadyMonitor = systemReadyMonitor;
105         this.upgradeState = upgradeState;
106         LOG.info("SouthboundProvider ovsdbConnectionService Initialized");
107     }
108
109     /**
110      * Used by blueprint when starting the container.
111      */
112     @PostConstruct
113     public void init() {
114         LOG.info("SouthboundProvider Session Initiated");
115         ovsdbStatusProvider.reportStatus(ServiceState.STARTING, "OVSDB initialization in progress");
116         this.txInvoker = new TransactionInvokerImpl(db);
117         cm = new OvsdbConnectionManager(db, txInvoker, entityOwnershipService, ovsdbConnection,
118                 instanceIdentifierCodec, upgradeState);
119         ovsdbDataTreeChangeListener = new OvsdbDataTreeChangeListener(db, cm, instanceIdentifierCodec);
120
121         //Register listener for entityOnwership changes
122         providerOwnershipChangeListener =
123                 new SouthboundPluginInstanceEntityOwnershipListener(this,this.entityOwnershipService);
124
125         //register instance entity to get the ownership of the provider
126         Entity instanceEntity = new Entity(ENTITY_TYPE, ENTITY_TYPE);
127         try {
128             registration = entityOwnershipService.registerCandidate(instanceEntity);
129         } catch (CandidateAlreadyRegisteredException e) {
130             LOG.warn("OVSDB Southbound Provider instance entity {} was already "
131                     + "registered for ownership", instanceEntity, e);
132         }
133         InstanceIdentifier<Topology> path = InstanceIdentifier
134                 .create(NetworkTopology.class)
135                 .child(Topology.class, new TopologyKey(SouthboundConstants.OVSDB_TOPOLOGY_ID));
136         DataTreeIdentifier<Topology> treeId =
137                 new DataTreeIdentifier<>(LogicalDatastoreType.OPERATIONAL, path);
138
139         LOG.trace("Registering listener for path {}", treeId);
140         operTopologyRegistration = db.registerDataTreeChangeListener(treeId, this);
141         ovsdbUpgradeStateListener = new OvsdbUpgradeStateListener(db, cm);
142     }
143
144     @Override
145     @PreDestroy
146     public void close() {
147         LOG.info("SouthboundProvider Closed");
148         try {
149             txInvoker.close();
150         } catch (InterruptedException e) {
151             ovsdbStatusProvider.reportStatus(ServiceState.ERROR, "OVSDB service shutdown error");
152             LOG.debug("SouthboundProvider failed to close TransactionInvoker.");
153         }
154         cm.close();
155         ovsdbDataTreeChangeListener.close();
156         registration.close();
157         providerOwnershipChangeListener.close();
158         if (operTopologyRegistration != null) {
159             operTopologyRegistration.close();
160             operTopologyRegistration = null;
161         }
162         ovsdbStatusProvider.reportStatus(ServiceState.UNREGISTERED, "OVSDB Service stopped");
163         if (ovsdbUpgradeStateListener != null) {
164             ovsdbUpgradeStateListener.close();
165         }
166     }
167
168     private void initializeOvsdbTopology(final LogicalDatastoreType type) {
169         InstanceIdentifier<Topology> path = InstanceIdentifier
170                 .create(NetworkTopology.class)
171                 .child(Topology.class, new TopologyKey(SouthboundConstants.OVSDB_TOPOLOGY_ID));
172         ReadWriteTransaction transaction = db.newReadWriteTransaction();
173         CheckedFuture<Optional<Topology>, ReadFailedException> ovsdbTp = transaction.read(type, path);
174         try {
175             if (!ovsdbTp.get().isPresent()) {
176                 TopologyBuilder tpb = new TopologyBuilder();
177                 tpb.setTopologyId(SouthboundConstants.OVSDB_TOPOLOGY_ID);
178                 transaction.put(type, path, tpb.build(), true);
179                 transaction.submit();
180             } else {
181                 transaction.cancel();
182             }
183         } catch (InterruptedException | ExecutionException e) {
184             LOG.error("Error initializing ovsdb topology", e);
185         }
186     }
187
188     public void handleOwnershipChange(final EntityOwnershipChange ownershipChange) {
189         if (ownershipChange.getState().isOwner()) {
190             LOG.info("*This* instance of OVSDB southbound provider is set as a MASTER instance");
191             LOG.info("Initialize OVSDB topology {} in operational and config data store if not already present",
192                     SouthboundConstants.OVSDB_TOPOLOGY_ID);
193             initializeOvsdbTopology(LogicalDatastoreType.OPERATIONAL);
194             initializeOvsdbTopology(LogicalDatastoreType.CONFIGURATION);
195         } else {
196             LOG.info("*This* instance of OVSDB southbound provider is set as a SLAVE instance");
197         }
198     }
199
200     @Override
201     public void onDataTreeChanged(final Collection<DataTreeModification<Topology>> collection) {
202         if (!registered.getAndSet(true)) {
203             LOG.info("Starting the ovsdb port");
204             ovsdbConnection.registerConnectionListener(cm);
205             LOG.info("Registering deferred system ready listener to start OVSDB Manager later");
206             systemReadyMonitor.registerListener(() -> {
207                 ovsdbConnection.startOvsdbManager();
208                 LOG.info("Started OVSDB Manager (in system ready listener)");
209             });
210
211             if (operTopologyRegistration != null) {
212                 operTopologyRegistration.close();
213                 operTopologyRegistration = null;
214             }
215             ovsdbStatusProvider.reportStatus(ServiceState.OPERATIONAL, "OVSDB initialization complete");
216         }
217     }
218
219     private static class SouthboundPluginInstanceEntityOwnershipListener implements EntityOwnershipListener {
220         private final SouthboundProvider sp;
221         private final EntityOwnershipListenerRegistration listenerRegistration;
222
223         SouthboundPluginInstanceEntityOwnershipListener(final SouthboundProvider sp,
224                 final EntityOwnershipService entityOwnershipService) {
225             this.sp = sp;
226             listenerRegistration = entityOwnershipService.registerListener(ENTITY_TYPE, this);
227         }
228
229         public void close() {
230             this.listenerRegistration.close();
231         }
232
233         @Override
234         public void ownershipChanged(final EntityOwnershipChange ownershipChange) {
235             sp.handleOwnershipChange(ownershipChange);
236         }
237     }
238
239     public void setSkipMonitoringManagerStatus(final boolean flag) {
240         LOG.debug("skipManagerStatus set to {}", flag);
241         if (flag) {
242             SouthboundConstants.SKIP_COLUMN_FROM_TABLE.get("Manager").add("status");
243         } else {
244             SouthboundConstants.SKIP_COLUMN_FROM_TABLE.get("Manager").remove("status");
245         }
246     }
247
248     public static void setBridgesReconciliationInclusionList(final List<String> bridgeList) {
249         reconcileBridgeInclusionList = bridgeList;
250     }
251
252     public static void setBridgesReconciliationExclusionList(final List<String> bridgeList) {
253         reconcileBridgeExclusionList = bridgeList;
254     }
255
256     public static List<String> getBridgesReconciliationInclusionList() {
257         return reconcileBridgeInclusionList;
258     }
259
260     public static List<String> getBridgesReconciliationExclusionList() {
261         return reconcileBridgeExclusionList;
262     }
263
264     @VisibleForTesting
265     boolean isRegistered() {
266         return registered.get();
267     }
268
269     public UpgradeState getUpgradeState() {
270         return upgradeState;
271     }
272 }