066b1870eaa4b35418f18dfe7372fae57e159122
[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.transactions.md.TransactionInvoker;
45 import org.opendaylight.ovsdb.southbound.transactions.md.TransactionInvokerImpl;
46 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.NetworkTopology;
47 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.Topology;
48 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.TopologyBuilder;
49 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.TopologyKey;
50 import org.opendaylight.yangtools.concepts.ListenerRegistration;
51 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
52 import org.slf4j.Logger;
53 import org.slf4j.LoggerFactory;
54
55 @Singleton
56 public class SouthboundProvider implements ClusteredDataTreeChangeListener<Topology>, AutoCloseable {
57
58     private static final Logger LOG = LoggerFactory.getLogger(SouthboundProvider.class);
59
60     private static final String ENTITY_TYPE = "ovsdb-southbound-provider";
61
62     public static DataBroker getDb() {
63         return db;
64     }
65
66     // FIXME: get rid of this static
67     @SuppressFBWarnings("ST_WRITE_TO_STATIC_FROM_INSTANCE_METHOD")
68     private static DataBroker db;
69     private OvsdbConnectionManager cm;
70     private TransactionInvoker txInvoker;
71     private OvsdbDataTreeChangeListener ovsdbDataTreeChangeListener;
72     private final EntityOwnershipService entityOwnershipService;
73     private EntityOwnershipCandidateRegistration registration;
74     private SouthboundPluginInstanceEntityOwnershipListener providerOwnershipChangeListener;
75     private final OvsdbConnection ovsdbConnection;
76     private final InstanceIdentifierCodec instanceIdentifierCodec;
77     private final SystemReadyMonitor systemReadyMonitor;
78
79     private final AtomicBoolean registered = new AtomicBoolean(false);
80     private ListenerRegistration<SouthboundProvider> operTopologyRegistration;
81     private final OvsdbDiagStatusProvider ovsdbStatusProvider;
82     private static List<String> reconcileBridgeInclusionList = new ArrayList<>();
83     private static List<String> reconcileBridgeExclusionList = new ArrayList<>();
84
85     @Inject
86     public SouthboundProvider(@Reference final DataBroker dataBroker,
87                               @Reference final EntityOwnershipService entityOwnershipServiceDependency,
88                               @Reference final OvsdbConnection ovsdbConnection,
89                               @Reference final DOMSchemaService schemaService,
90                               @Reference final BindingNormalizedNodeSerializer bindingNormalizedNodeSerializer,
91                               @Reference final SystemReadyMonitor systemReadyMonitor,
92                               @Reference final DiagStatusService diagStatusService) {
93         SouthboundProvider.db = dataBroker;
94         this.entityOwnershipService = entityOwnershipServiceDependency;
95         registration = null;
96         this.ovsdbConnection = ovsdbConnection;
97         this.ovsdbStatusProvider = new OvsdbDiagStatusProvider(diagStatusService);
98         this.instanceIdentifierCodec = new InstanceIdentifierCodec(schemaService,
99                 bindingNormalizedNodeSerializer);
100         this.systemReadyMonitor = systemReadyMonitor;
101         LOG.info("SouthboundProvider ovsdbConnectionService Initialized");
102     }
103
104     /**
105      * Used by blueprint when starting the container.
106      */
107     @PostConstruct
108     public void init() {
109         LOG.info("SouthboundProvider Session Initiated");
110         ovsdbStatusProvider.reportStatus(ServiceState.STARTING, "OVSDB initialization in progress");
111         this.txInvoker = new TransactionInvokerImpl(db);
112         cm = new OvsdbConnectionManager(db, txInvoker, entityOwnershipService, ovsdbConnection,
113                 instanceIdentifierCodec);
114         ovsdbDataTreeChangeListener = new OvsdbDataTreeChangeListener(db, cm, instanceIdentifierCodec);
115
116         //Register listener for entityOnwership changes
117         providerOwnershipChangeListener =
118                 new SouthboundPluginInstanceEntityOwnershipListener(this,this.entityOwnershipService);
119
120         //register instance entity to get the ownership of the provider
121         Entity instanceEntity = new Entity(ENTITY_TYPE, ENTITY_TYPE);
122         try {
123             registration = entityOwnershipService.registerCandidate(instanceEntity);
124         } catch (CandidateAlreadyRegisteredException e) {
125             LOG.warn("OVSDB Southbound Provider instance entity {} was already "
126                     + "registered for ownership", instanceEntity, e);
127         }
128         InstanceIdentifier<Topology> path = InstanceIdentifier
129                 .create(NetworkTopology.class)
130                 .child(Topology.class, new TopologyKey(SouthboundConstants.OVSDB_TOPOLOGY_ID));
131         DataTreeIdentifier<Topology> treeId =
132                 new DataTreeIdentifier<>(LogicalDatastoreType.OPERATIONAL, path);
133
134         LOG.trace("Registering listener for path {}", treeId);
135         operTopologyRegistration = db.registerDataTreeChangeListener(treeId, this);
136     }
137
138     @Override
139     @PreDestroy
140     public void close() {
141         LOG.info("SouthboundProvider Closed");
142         try {
143             txInvoker.close();
144         } catch (InterruptedException e) {
145             ovsdbStatusProvider.reportStatus(ServiceState.ERROR, "OVSDB service shutdown error");
146             LOG.debug("SouthboundProvider failed to close TransactionInvoker.");
147         }
148         cm.close();
149         ovsdbDataTreeChangeListener.close();
150         registration.close();
151         providerOwnershipChangeListener.close();
152         if (operTopologyRegistration != null) {
153             operTopologyRegistration.close();
154             operTopologyRegistration = null;
155         }
156         ovsdbStatusProvider.reportStatus(ServiceState.UNREGISTERED, "OVSDB Service stopped");
157     }
158
159     private void initializeOvsdbTopology(final LogicalDatastoreType type) {
160         InstanceIdentifier<Topology> path = InstanceIdentifier
161                 .create(NetworkTopology.class)
162                 .child(Topology.class, new TopologyKey(SouthboundConstants.OVSDB_TOPOLOGY_ID));
163         ReadWriteTransaction transaction = db.newReadWriteTransaction();
164         CheckedFuture<Optional<Topology>, ReadFailedException> ovsdbTp = transaction.read(type, path);
165         try {
166             if (!ovsdbTp.get().isPresent()) {
167                 TopologyBuilder tpb = new TopologyBuilder();
168                 tpb.setTopologyId(SouthboundConstants.OVSDB_TOPOLOGY_ID);
169                 transaction.put(type, path, tpb.build(), true);
170                 transaction.submit();
171             } else {
172                 transaction.cancel();
173             }
174         } catch (InterruptedException | ExecutionException e) {
175             LOG.error("Error initializing ovsdb topology", e);
176         }
177     }
178
179     public void handleOwnershipChange(final EntityOwnershipChange ownershipChange) {
180         if (ownershipChange.getState().isOwner()) {
181             LOG.info("*This* instance of OVSDB southbound provider is set as a MASTER instance");
182             LOG.info("Initialize OVSDB topology {} in operational and config data store if not already present",
183                     SouthboundConstants.OVSDB_TOPOLOGY_ID);
184             initializeOvsdbTopology(LogicalDatastoreType.OPERATIONAL);
185             initializeOvsdbTopology(LogicalDatastoreType.CONFIGURATION);
186         } else {
187             LOG.info("*This* instance of OVSDB southbound provider is set as a SLAVE instance");
188         }
189     }
190
191     @Override
192     public void onDataTreeChanged(final Collection<DataTreeModification<Topology>> collection) {
193         if (!registered.getAndSet(true)) {
194             LOG.info("Starting the ovsdb port");
195             ovsdbConnection.registerConnectionListener(cm);
196             LOG.info("Registering deferred system ready listener to start OVSDB Manager later");
197             systemReadyMonitor.registerListener(() -> {
198                 ovsdbConnection.startOvsdbManager();
199                 LOG.info("Started OVSDB Manager (in system ready listener)");
200             });
201
202             if (operTopologyRegistration != null) {
203                 operTopologyRegistration.close();
204                 operTopologyRegistration = null;
205             }
206             ovsdbStatusProvider.reportStatus(ServiceState.OPERATIONAL, "OVSDB initialization complete");
207         }
208     }
209
210     private static class SouthboundPluginInstanceEntityOwnershipListener implements EntityOwnershipListener {
211         private final SouthboundProvider sp;
212         private final EntityOwnershipListenerRegistration listenerRegistration;
213
214         SouthboundPluginInstanceEntityOwnershipListener(final SouthboundProvider sp,
215                 final EntityOwnershipService entityOwnershipService) {
216             this.sp = sp;
217             listenerRegistration = entityOwnershipService.registerListener(ENTITY_TYPE, this);
218         }
219
220         public void close() {
221             this.listenerRegistration.close();
222         }
223
224         @Override
225         public void ownershipChanged(final EntityOwnershipChange ownershipChange) {
226             sp.handleOwnershipChange(ownershipChange);
227         }
228     }
229
230     public void setSkipMonitoringManagerStatus(final boolean flag) {
231         LOG.debug("skipManagerStatus set to {}", flag);
232         if (flag) {
233             SouthboundConstants.SKIP_COLUMN_FROM_TABLE.get("Manager").add("status");
234         } else {
235             SouthboundConstants.SKIP_COLUMN_FROM_TABLE.get("Manager").remove("status");
236         }
237     }
238
239     public static void setBridgesReconciliationInclusionList(final List<String> bridgeList) {
240         reconcileBridgeInclusionList = bridgeList;
241     }
242
243     public static void setBridgesReconciliationExclusionList(final List<String> bridgeList) {
244         reconcileBridgeExclusionList = bridgeList;
245     }
246
247     public static List<String> getBridgesReconciliationInclusionList() {
248         return reconcileBridgeInclusionList;
249     }
250
251     public static List<String> getBridgesReconciliationExclusionList() {
252         return reconcileBridgeExclusionList;
253     }
254
255     @VisibleForTesting
256     boolean isRegistered() {
257         return registered.get();
258     }
259 }