Update MRI projects for Aluminium
[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.util.concurrent.FluentFuture;
12 import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
13 import java.util.ArrayList;
14 import java.util.Collection;
15 import java.util.List;
16 import java.util.Optional;
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.infrautils.diagstatus.DiagStatusService;
25 import org.opendaylight.infrautils.diagstatus.ServiceState;
26 import org.opendaylight.infrautils.ready.SystemReadyMonitor;
27 import org.opendaylight.mdsal.binding.api.ClusteredDataTreeChangeListener;
28 import org.opendaylight.mdsal.binding.api.DataBroker;
29 import org.opendaylight.mdsal.binding.api.DataTreeIdentifier;
30 import org.opendaylight.mdsal.binding.api.DataTreeModification;
31 import org.opendaylight.mdsal.binding.api.ReadWriteTransaction;
32 import org.opendaylight.mdsal.binding.dom.codec.api.BindingNormalizedNodeSerializer;
33 import org.opendaylight.mdsal.common.api.LogicalDatastoreType;
34 import org.opendaylight.mdsal.dom.api.DOMSchemaService;
35 import org.opendaylight.mdsal.eos.binding.api.Entity;
36 import org.opendaylight.mdsal.eos.binding.api.EntityOwnershipCandidateRegistration;
37 import org.opendaylight.mdsal.eos.binding.api.EntityOwnershipChange;
38 import org.opendaylight.mdsal.eos.binding.api.EntityOwnershipListener;
39 import org.opendaylight.mdsal.eos.binding.api.EntityOwnershipListenerRegistration;
40 import org.opendaylight.mdsal.eos.binding.api.EntityOwnershipService;
41 import org.opendaylight.mdsal.eos.common.api.CandidateAlreadyRegisteredException;
42 import org.opendaylight.ovsdb.lib.OvsdbConnection;
43 import org.opendaylight.ovsdb.southbound.reconciliation.OvsdbUpgradeStateListener;
44 import org.opendaylight.ovsdb.southbound.transactions.md.TransactionInvoker;
45 import org.opendaylight.ovsdb.southbound.transactions.md.TransactionInvokerImpl;
46 import org.opendaylight.serviceutils.upgrade.UpgradeState;
47 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.NetworkTopology;
48 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.Topology;
49 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.TopologyBuilder;
50 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.TopologyKey;
51 import org.opendaylight.yangtools.concepts.ListenerRegistration;
52 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
53 import org.slf4j.Logger;
54 import org.slf4j.LoggerFactory;
55
56 @Singleton
57 public class SouthboundProvider implements ClusteredDataTreeChangeListener<Topology>, AutoCloseable {
58     private static final Logger LOG = LoggerFactory.getLogger(SouthboundProvider.class);
59     private static final String ENTITY_TYPE = "ovsdb-southbound-provider";
60
61     // FIXME: get rid of this static
62     @SuppressFBWarnings("ST_WRITE_TO_STATIC_FROM_INSTANCE_METHOD")
63     private static DataBroker db;
64
65     public static DataBroker getDb() {
66         return db;
67     }
68
69     private OvsdbConnectionManager cm;
70     private TransactionInvoker txInvoker;
71     private OvsdbDataTreeChangeListener ovsdbDataTreeChangeListener;
72     private OvsdbOperGlobalListener ovsdbOperGlobalListener;
73     private final EntityOwnershipService entityOwnershipService;
74     private EntityOwnershipCandidateRegistration registration;
75     private SouthboundPluginInstanceEntityOwnershipListener providerOwnershipChangeListener;
76     private final OvsdbConnection ovsdbConnection;
77     private final InstanceIdentifierCodec instanceIdentifierCodec;
78     private final SystemReadyMonitor systemReadyMonitor;
79     private final UpgradeState upgradeState;
80     private final AtomicBoolean registered = new AtomicBoolean(false);
81     private ListenerRegistration<SouthboundProvider> operTopologyRegistration;
82     private final OvsdbDiagStatusProvider ovsdbStatusProvider;
83     private static List<String> reconcileBridgeInclusionList = new ArrayList<>();
84     private static List<String> reconcileBridgeExclusionList = new ArrayList<>();
85     private OvsdbUpgradeStateListener ovsdbUpgradeStateListener;
86
87     @Inject
88     public SouthboundProvider(@Reference final DataBroker dataBroker,
89                               @Reference final EntityOwnershipService entityOwnershipServiceDependency,
90                               @Reference final OvsdbConnection ovsdbConnection,
91                               @Reference final DOMSchemaService schemaService,
92                               @Reference final BindingNormalizedNodeSerializer bindingNormalizedNodeSerializer,
93                               @Reference final SystemReadyMonitor systemReadyMonitor,
94                               @Reference final DiagStatusService diagStatusService,
95                               @Reference final UpgradeState upgradeState) {
96         SouthboundProvider.db = dataBroker;
97         this.entityOwnershipService = entityOwnershipServiceDependency;
98         registration = null;
99         this.ovsdbConnection = ovsdbConnection;
100         this.ovsdbStatusProvider = new OvsdbDiagStatusProvider(diagStatusService);
101         this.instanceIdentifierCodec = new InstanceIdentifierCodec(schemaService,
102                 bindingNormalizedNodeSerializer);
103         this.systemReadyMonitor = systemReadyMonitor;
104         this.upgradeState = upgradeState;
105         LOG.info("SouthboundProvider ovsdbConnectionService Initialized");
106     }
107
108     /**
109      * Used by blueprint when starting the container.
110      */
111     @PostConstruct
112     public void init() {
113         LOG.info("SouthboundProvider Session Initiated");
114         ovsdbStatusProvider.reportStatus(ServiceState.STARTING, "OVSDB initialization in progress");
115         this.txInvoker = new TransactionInvokerImpl(db);
116         cm = new OvsdbConnectionManager(db, txInvoker, entityOwnershipService, ovsdbConnection,
117                 instanceIdentifierCodec, upgradeState);
118         ovsdbDataTreeChangeListener = new OvsdbDataTreeChangeListener(db, cm, instanceIdentifierCodec);
119         ovsdbOperGlobalListener = new OvsdbOperGlobalListener(db, cm, txInvoker);
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                 DataTreeIdentifier.create(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         ovsdbOperGlobalListener.close();
157         registration.close();
158         providerOwnershipChangeListener.close();
159         if (operTopologyRegistration != null) {
160             operTopologyRegistration.close();
161             operTopologyRegistration = null;
162         }
163         ovsdbStatusProvider.reportStatus(ServiceState.UNREGISTERED, "OVSDB Service stopped");
164         if (ovsdbUpgradeStateListener != null) {
165             ovsdbUpgradeStateListener.close();
166         }
167     }
168
169     private void initializeOvsdbTopology(final LogicalDatastoreType type) {
170         InstanceIdentifier<Topology> path = InstanceIdentifier
171                 .create(NetworkTopology.class)
172                 .child(Topology.class, new TopologyKey(SouthboundConstants.OVSDB_TOPOLOGY_ID));
173         ReadWriteTransaction transaction = db.newReadWriteTransaction();
174         FluentFuture<Optional<Topology>> ovsdbTp = transaction.read(type, path);
175         try {
176             if (!ovsdbTp.get().isPresent()) {
177                 TopologyBuilder tpb = new TopologyBuilder();
178                 tpb.setTopologyId(SouthboundConstants.OVSDB_TOPOLOGY_ID);
179                 transaction.mergeParentStructurePut(type, path, tpb.build());
180                 transaction.commit();
181             } else {
182                 transaction.cancel();
183             }
184         } catch (InterruptedException | ExecutionException e) {
185             LOG.error("Error initializing ovsdb topology", e);
186         }
187     }
188
189     public void handleOwnershipChange(final EntityOwnershipChange ownershipChange) {
190         if (ownershipChange.getState().isOwner()) {
191             LOG.info("*This* instance of OVSDB southbound provider is set as a MASTER instance");
192             LOG.info("Initialize OVSDB topology {} in operational and config data store if not already present",
193                     SouthboundConstants.OVSDB_TOPOLOGY_ID);
194             initializeOvsdbTopology(LogicalDatastoreType.OPERATIONAL);
195             initializeOvsdbTopology(LogicalDatastoreType.CONFIGURATION);
196         } else {
197             LOG.info("*This* instance of OVSDB southbound provider is set as a SLAVE instance");
198         }
199     }
200
201     @Override
202     public void onDataTreeChanged(final Collection<DataTreeModification<Topology>> collection) {
203         if (!registered.getAndSet(true)) {
204             LOG.info("Starting the ovsdb port");
205             ovsdbConnection.registerConnectionListener(cm);
206             LOG.info("Registering deferred system ready listener to start OVSDB Manager later");
207             systemReadyMonitor.registerListener(() -> {
208                 ovsdbConnection.startOvsdbManager();
209                 LOG.info("Started OVSDB Manager (in system ready listener)");
210             });
211
212             if (operTopologyRegistration != null) {
213                 operTopologyRegistration.close();
214                 operTopologyRegistration = null;
215             }
216             ovsdbStatusProvider.reportStatus(ServiceState.OPERATIONAL, "OVSDB initialization complete");
217         }
218     }
219
220     private static class SouthboundPluginInstanceEntityOwnershipListener implements EntityOwnershipListener {
221         private final SouthboundProvider sp;
222         private final EntityOwnershipListenerRegistration listenerRegistration;
223
224         SouthboundPluginInstanceEntityOwnershipListener(final SouthboundProvider sp,
225                 final EntityOwnershipService entityOwnershipService) {
226             this.sp = sp;
227             listenerRegistration = entityOwnershipService.registerListener(ENTITY_TYPE, this);
228         }
229
230         public void close() {
231             this.listenerRegistration.close();
232         }
233
234         @Override
235         public void ownershipChanged(final EntityOwnershipChange ownershipChange) {
236             sp.handleOwnershipChange(ownershipChange);
237         }
238     }
239
240     public void setSkipMonitoringManagerStatus(final boolean flag) {
241         LOG.debug("skipManagerStatus set to {}", flag);
242         if (flag) {
243             SouthboundConstants.SKIP_COLUMN_FROM_TABLE.get("Manager").add("status");
244         } else {
245             SouthboundConstants.SKIP_COLUMN_FROM_TABLE.get("Manager").remove("status");
246         }
247     }
248
249     public static void setBridgesReconciliationInclusionList(final List<String> bridgeList) {
250         reconcileBridgeInclusionList = bridgeList;
251     }
252
253     public static void setBridgesReconciliationExclusionList(final List<String> bridgeList) {
254         reconcileBridgeExclusionList = bridgeList;
255     }
256
257     public static List<String> getBridgesReconciliationInclusionList() {
258         return reconcileBridgeInclusionList;
259     }
260
261     public static List<String> getBridgesReconciliationExclusionList() {
262         return reconcileBridgeExclusionList;
263     }
264
265     @VisibleForTesting
266     boolean isRegistered() {
267         return registered.get();
268     }
269
270     public UpgradeState getUpgradeState() {
271         return upgradeState;
272     }
273 }