OVSDB-458 DiagStatus support for OVSDB
[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.base.Optional;
11 import com.google.common.util.concurrent.CheckedFuture;
12 import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
13 import java.util.Collection;
14 import java.util.Map;
15 import java.util.concurrent.ExecutionException;
16 import java.util.concurrent.atomic.AtomicBoolean;
17 import org.opendaylight.controller.md.sal.binding.api.ClusteredDataTreeChangeListener;
18 import org.opendaylight.controller.md.sal.binding.api.DataBroker;
19 import org.opendaylight.controller.md.sal.binding.api.DataTreeIdentifier;
20 import org.opendaylight.controller.md.sal.binding.api.DataTreeModification;
21 import org.opendaylight.controller.md.sal.binding.api.ReadWriteTransaction;
22 import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
23 import org.opendaylight.controller.md.sal.common.api.data.ReadFailedException;
24 import org.opendaylight.infrautils.diagstatus.DiagStatusService;
25 import org.opendaylight.infrautils.diagstatus.ServiceState;
26 import org.opendaylight.mdsal.binding.dom.codec.api.BindingNormalizedNodeSerializer;
27 import org.opendaylight.mdsal.dom.api.DOMSchemaService;
28 import org.opendaylight.mdsal.eos.binding.api.Entity;
29 import org.opendaylight.mdsal.eos.binding.api.EntityOwnershipCandidateRegistration;
30 import org.opendaylight.mdsal.eos.binding.api.EntityOwnershipChange;
31 import org.opendaylight.mdsal.eos.binding.api.EntityOwnershipListener;
32 import org.opendaylight.mdsal.eos.binding.api.EntityOwnershipListenerRegistration;
33 import org.opendaylight.mdsal.eos.binding.api.EntityOwnershipService;
34 import org.opendaylight.mdsal.eos.common.api.CandidateAlreadyRegisteredException;
35 import org.opendaylight.ovsdb.lib.OvsdbConnection;
36 import org.opendaylight.ovsdb.southbound.transactions.md.TransactionInvoker;
37 import org.opendaylight.ovsdb.southbound.transactions.md.TransactionInvokerImpl;
38 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.NetworkTopology;
39 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.Topology;
40 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.TopologyBuilder;
41 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.TopologyKey;
42 import org.opendaylight.yangtools.concepts.ListenerRegistration;
43 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
44 import org.slf4j.Logger;
45 import org.slf4j.LoggerFactory;
46
47 public class SouthboundProvider implements ClusteredDataTreeChangeListener<Topology>, AutoCloseable {
48
49     private static final Logger LOG = LoggerFactory.getLogger(SouthboundProvider.class);
50     private static final String ENTITY_TYPE = "ovsdb-southbound-provider";
51
52     public static DataBroker getDb() {
53         return db;
54     }
55
56     // FIXME: get rid of this static
57     @SuppressFBWarnings("ST_WRITE_TO_STATIC_FROM_INSTANCE_METHOD")
58     private static DataBroker db;
59     private OvsdbConnectionManager cm;
60     private TransactionInvoker txInvoker;
61     private OvsdbDataTreeChangeListener ovsdbDataTreeChangeListener;
62     private final EntityOwnershipService entityOwnershipService;
63     private EntityOwnershipCandidateRegistration registration;
64     private SouthboundPluginInstanceEntityOwnershipListener providerOwnershipChangeListener;
65     private final OvsdbConnection ovsdbConnection;
66     private final InstanceIdentifierCodec instanceIdentifierCodec;
67     private static final String SKIP_MONITORING_MANAGER_STATUS_PARAM = "skip-monitoring-manager-status";
68     private final AtomicBoolean registered = new AtomicBoolean(false);
69     private ListenerRegistration<SouthboundProvider> operTopologyRegistration;
70     private final OvsdbDiagStatusProvider ovsdbStatusProvider;
71
72     public SouthboundProvider(final DataBroker dataBroker,
73             final EntityOwnershipService entityOwnershipServiceDependency,
74             final OvsdbConnection ovsdbConnection,
75             final DOMSchemaService schemaService,
76             final BindingNormalizedNodeSerializer bindingNormalizedNodeSerializer,
77             final DiagStatusService diagStatusService) {
78
79         this.db = dataBroker;
80         this.entityOwnershipService = entityOwnershipServiceDependency;
81         registration = null;
82         this.ovsdbConnection = ovsdbConnection;
83         ovsdbStatusProvider = new OvsdbDiagStatusProvider(diagStatusService);
84
85         this.instanceIdentifierCodec = new InstanceIdentifierCodec(schemaService,
86                 bindingNormalizedNodeSerializer);
87         LOG.info("SouthboundProvider ovsdbConnectionService Initialized");
88     }
89
90     /**
91      * Used by blueprint when starting the container.
92      */
93     public void init() {
94         LOG.info("SouthboundProvider Session Initiated");
95         ovsdbStatusProvider.reportStatus(ServiceState.STARTING, "OVSDB initialization in progress");
96         this.txInvoker = new TransactionInvokerImpl(db);
97         cm = new OvsdbConnectionManager(db, txInvoker, entityOwnershipService, ovsdbConnection,
98                 instanceIdentifierCodec);
99         ovsdbDataTreeChangeListener = new OvsdbDataTreeChangeListener(db, cm, instanceIdentifierCodec);
100
101         //Register listener for entityOnwership changes
102         providerOwnershipChangeListener =
103                 new SouthboundPluginInstanceEntityOwnershipListener(this,this.entityOwnershipService);
104
105         //register instance entity to get the ownership of the provider
106         Entity instanceEntity = new Entity(ENTITY_TYPE, ENTITY_TYPE);
107         try {
108             registration = entityOwnershipService.registerCandidate(instanceEntity);
109         } catch (CandidateAlreadyRegisteredException e) {
110             LOG.warn("OVSDB Southbound Provider instance entity {} was already "
111                     + "registered for ownership", instanceEntity, e);
112         }
113         InstanceIdentifier<Topology> path = InstanceIdentifier
114                 .create(NetworkTopology.class)
115                 .child(Topology.class, new TopologyKey(SouthboundConstants.OVSDB_TOPOLOGY_ID));
116         DataTreeIdentifier<Topology> treeId =
117                 new DataTreeIdentifier<>(LogicalDatastoreType.OPERATIONAL, path);
118
119         LOG.trace("Registering listener for path {}", treeId);
120         operTopologyRegistration = db.registerDataTreeChangeListener(treeId, this);
121     }
122
123     @Override
124     public void close() {
125         LOG.info("SouthboundProvider Closed");
126         try {
127             txInvoker.close();
128         } catch (InterruptedException e) {
129             ovsdbStatusProvider.reportStatus(ServiceState.ERROR, "OVSDB service shutdown error");
130             LOG.debug("SouthboundProvider failed to close TransactionInvoker.");
131         }
132         cm.close();
133         ovsdbDataTreeChangeListener.close();
134         registration.close();
135         providerOwnershipChangeListener.close();
136         if (operTopologyRegistration != null) {
137             operTopologyRegistration.close();
138             operTopologyRegistration = null;
139         }
140         ovsdbStatusProvider.reportStatus(ServiceState.UNREGISTERED, "OVSDB Service stopped");
141     }
142
143     private void initializeOvsdbTopology(LogicalDatastoreType type) {
144         InstanceIdentifier<Topology> path = InstanceIdentifier
145                 .create(NetworkTopology.class)
146                 .child(Topology.class, new TopologyKey(SouthboundConstants.OVSDB_TOPOLOGY_ID));
147         ReadWriteTransaction transaction = db.newReadWriteTransaction();
148         CheckedFuture<Optional<Topology>, ReadFailedException> ovsdbTp = transaction.read(type, path);
149         try {
150             if (!ovsdbTp.get().isPresent()) {
151                 TopologyBuilder tpb = new TopologyBuilder();
152                 tpb.setTopologyId(SouthboundConstants.OVSDB_TOPOLOGY_ID);
153                 transaction.put(type, path, tpb.build(), true);
154                 transaction.submit();
155             } else {
156                 transaction.cancel();
157             }
158         } catch (InterruptedException | ExecutionException e) {
159             LOG.error("Error initializing ovsdb topology", e);
160         }
161     }
162
163     public void handleOwnershipChange(EntityOwnershipChange ownershipChange) {
164         if (ownershipChange.getState().isOwner()) {
165             LOG.info("*This* instance of OVSDB southbound provider is set as a MASTER instance");
166             LOG.info("Initialize OVSDB topology {} in operational and config data store if not already present",
167                     SouthboundConstants.OVSDB_TOPOLOGY_ID);
168             initializeOvsdbTopology(LogicalDatastoreType.OPERATIONAL);
169             initializeOvsdbTopology(LogicalDatastoreType.CONFIGURATION);
170         } else {
171             LOG.info("*This* instance of OVSDB southbound provider is set as a SLAVE instance");
172         }
173     }
174
175     @Override
176     public void onDataTreeChanged(Collection<DataTreeModification<Topology>> collection) {
177         if (!registered.getAndSet(true)) {
178             LOG.info("Starting the ovsdb port");
179             ovsdbConnection.registerConnectionListener(cm);
180             ovsdbConnection.startOvsdbManager();
181             //mdsal registration/deregistration in mdsal update callback should be avoided
182             new Thread(() -> {
183                 if (operTopologyRegistration != null) {
184                     operTopologyRegistration.close();
185                     operTopologyRegistration = null;
186                 }
187             }).start();
188             ovsdbStatusProvider.reportStatus(ServiceState.OPERATIONAL, "OVSDB initialization complete");
189         }
190     }
191
192     private static class SouthboundPluginInstanceEntityOwnershipListener implements EntityOwnershipListener {
193         private final SouthboundProvider sp;
194         private final EntityOwnershipListenerRegistration listenerRegistration;
195
196         SouthboundPluginInstanceEntityOwnershipListener(SouthboundProvider sp,
197                 EntityOwnershipService entityOwnershipService) {
198             this.sp = sp;
199             listenerRegistration = entityOwnershipService.registerListener(ENTITY_TYPE, this);
200         }
201
202         public void close() {
203             this.listenerRegistration.close();
204         }
205
206         @Override
207         public void ownershipChanged(EntityOwnershipChange ownershipChange) {
208             sp.handleOwnershipChange(ownershipChange);
209         }
210     }
211
212     public void updateConfigParameter(Map<String, Object> configParameters) {
213         if (configParameters != null && !configParameters.isEmpty()) {
214             LOG.debug("Config parameters received : {}", configParameters.entrySet());
215             for (Map.Entry<String, Object> paramEntry : configParameters.entrySet()) {
216                 if (paramEntry.getKey().equalsIgnoreCase(SKIP_MONITORING_MANAGER_STATUS_PARAM)) {
217                     setSkipMonitoringManagerStatus(Boolean.parseBoolean((String)paramEntry.getValue()));
218                     break;
219                 }
220             }
221         }
222     }
223
224     public void setSkipMonitoringManagerStatus(boolean flag) {
225         LOG.debug("skipManagerStatus set to {}", flag);
226         if (flag) {
227             SouthboundConstants.SKIP_COLUMN_FROM_TABLE.get("Manager").add("status");
228         } else {
229             SouthboundConstants.SKIP_COLUMN_FROM_TABLE.get("Manager").remove("status");
230         }
231     }
232 }