Check for the SHARD Status before opening the OVSDB port/HwvtepSouthboundProvider...
[ovsdb.git] / hwvtepsouthbound / hwvtepsouthbound-impl / src / main / java / org / opendaylight / ovsdb / hwvtepsouthbound / HwvtepSouthboundProvider.java
1 /*
2  * Copyright © 2015, 2017 Ericsson India Global Services Pvt Ltd. 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.hwvtepsouthbound;
9
10 import com.google.common.base.Optional;
11 import com.google.common.util.concurrent.CheckedFuture;
12 import java.util.Collection;
13 import java.util.concurrent.ExecutionException;
14 import java.util.concurrent.atomic.AtomicBoolean;
15 import javax.annotation.PostConstruct;
16 import javax.annotation.PreDestroy;
17 import javax.inject.Inject;
18 import javax.inject.Singleton;
19 import org.apache.aries.blueprint.annotation.service.Reference;
20 import org.apache.aries.blueprint.annotation.service.Service;
21 import org.opendaylight.controller.md.sal.binding.api.ClusteredDataTreeChangeListener;
22 import org.opendaylight.controller.md.sal.binding.api.DataBroker;
23 import org.opendaylight.controller.md.sal.binding.api.DataTreeIdentifier;
24 import org.opendaylight.controller.md.sal.binding.api.DataTreeModification;
25 import org.opendaylight.controller.md.sal.binding.api.ReadWriteTransaction;
26 import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
27 import org.opendaylight.controller.md.sal.common.api.data.ReadFailedException;
28 import org.opendaylight.mdsal.binding.dom.codec.api.BindingNormalizedNodeSerializer;
29 import org.opendaylight.mdsal.dom.api.DOMSchemaService;
30 import org.opendaylight.mdsal.eos.binding.api.Entity;
31 import org.opendaylight.mdsal.eos.binding.api.EntityOwnershipCandidateRegistration;
32 import org.opendaylight.mdsal.eos.binding.api.EntityOwnershipChange;
33 import org.opendaylight.mdsal.eos.binding.api.EntityOwnershipListener;
34 import org.opendaylight.mdsal.eos.binding.api.EntityOwnershipListenerRegistration;
35 import org.opendaylight.mdsal.eos.binding.api.EntityOwnershipService;
36 import org.opendaylight.mdsal.eos.common.api.CandidateAlreadyRegisteredException;
37 import org.opendaylight.ovsdb.hwvtepsouthbound.reconciliation.configuration.HwvtepReconciliationManager;
38 import org.opendaylight.ovsdb.hwvtepsouthbound.transactions.md.TransactionInvoker;
39 import org.opendaylight.ovsdb.hwvtepsouthbound.transactions.md.TransactionInvokerImpl;
40 import org.opendaylight.ovsdb.lib.OvsdbConnection;
41 import org.opendaylight.ovsdb.utils.mdsal.utils.ShardStatusMonitor;
42 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.NetworkTopology;
43 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.Topology;
44 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.TopologyBuilder;
45 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.TopologyKey;
46 import org.opendaylight.yangtools.concepts.ListenerRegistration;
47 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
48 import org.slf4j.Logger;
49 import org.slf4j.LoggerFactory;
50
51 @Singleton
52 @Service(classes = HwvtepSouthboundProvider.class) // only because HwvtepCacheDisplayCmd needs a @Reference to this
53 public class HwvtepSouthboundProvider implements ClusteredDataTreeChangeListener<Topology>, AutoCloseable {
54
55     private static final Logger LOG = LoggerFactory.getLogger(HwvtepSouthboundProvider.class);
56     private static final String ENTITY_TYPE = "ovsdb-hwvtepsouthbound-provider";
57
58     private final DataBroker dataBroker;
59     private final EntityOwnershipService entityOwnershipService;
60     private final OvsdbConnection ovsdbConnection;
61
62     private HwvtepConnectionManager cm;
63     private TransactionInvoker txInvoker;
64     private EntityOwnershipCandidateRegistration registration;
65     private HwvtepsbPluginInstanceEntityOwnershipListener providerOwnershipChangeListener;
66     private HwvtepDataChangeListener hwvtepDTListener;
67     private HwvtepReconciliationManager hwvtepReconciliationManager;
68     private final AtomicBoolean registered = new AtomicBoolean(false);
69     private ListenerRegistration<HwvtepSouthboundProvider> operTopologyRegistration;
70     private int shardStatusCheckRetryCount = 1000;
71
72     @Inject
73     public HwvtepSouthboundProvider(@Reference final DataBroker dataBroker,
74             @Reference final EntityOwnershipService entityOwnershipServiceDependency,
75             @Reference final OvsdbConnection ovsdbConnection,
76             @Reference final DOMSchemaService schemaService,
77             @Reference final BindingNormalizedNodeSerializer bindingNormalizedNodeSerializer) {
78         this.dataBroker = dataBroker;
79         this.entityOwnershipService = entityOwnershipServiceDependency;
80         registration = null;
81         this.ovsdbConnection = ovsdbConnection;
82         HwvtepSouthboundUtil.setInstanceIdentifierCodec(new InstanceIdentifierCodec(schemaService,
83                 bindingNormalizedNodeSerializer));
84         LOG.info("HwvtepSouthboundProvider ovsdbConnectionService: {}", ovsdbConnection);
85     }
86
87     /**
88      * Used by blueprint when starting the container.
89      */
90     @PostConstruct
91     public void init() {
92         boolean isDatastoreAvailable = false;
93         int retryCount = 0;
94         try {
95             while (retryCount < shardStatusCheckRetryCount) {
96                 isDatastoreAvailable = ShardStatusMonitor.getShardStatus(ShardStatusMonitor.TOPOLOGY_SHARDS);
97                 if (isDatastoreAvailable) {
98                     break;
99                 }
100                 LOG.warn("Hwvtep: retrying shard status check for the {} time", ++retryCount);
101                 Thread.sleep(2000);
102             }
103             if (isDatastoreAvailable) {
104                 LOG.info("Hwvtep is UP");
105                 init2();
106             }
107         } catch (InterruptedException e) {
108             LOG.error("Error in intializing the Hwvtep Southbound ", e);
109         }
110     }
111
112     private void init2() {
113         LOG.info("HwvtepSouthboundProvider Session Initiated");
114         txInvoker = new TransactionInvokerImpl(dataBroker);
115         cm = new HwvtepConnectionManager(dataBroker, txInvoker, entityOwnershipService, ovsdbConnection);
116         hwvtepDTListener = new HwvtepDataChangeListener(dataBroker, cm);
117         hwvtepReconciliationManager = new HwvtepReconciliationManager(dataBroker, cm);
118         //Register listener for entityOnwership changes
119         providerOwnershipChangeListener =
120                 new HwvtepsbPluginInstanceEntityOwnershipListener(this,this.entityOwnershipService);
121
122         //register instance entity to get the ownership of the provider
123         Entity instanceEntity = new Entity(ENTITY_TYPE, ENTITY_TYPE);
124         try {
125             registration = entityOwnershipService.registerCandidate(instanceEntity);
126         } catch (CandidateAlreadyRegisteredException e) {
127             LOG.warn("HWVTEP Southbound Provider instance entity {} was already "
128                     + "registered for ownership", instanceEntity, e);
129         }
130         InstanceIdentifier<Topology> path = InstanceIdentifier
131                 .create(NetworkTopology.class)
132                 .child(Topology.class, new TopologyKey(HwvtepSouthboundConstants.HWVTEP_TOPOLOGY_ID));
133         DataTreeIdentifier<Topology> treeId =
134                 new DataTreeIdentifier<>(LogicalDatastoreType.OPERATIONAL, path);
135
136         LOG.trace("Registering listener for path {}", treeId);
137         operTopologyRegistration = dataBroker.registerDataTreeChangeListener(treeId, this);
138     }
139
140     @Override
141     @PreDestroy
142     @SuppressWarnings("checkstyle:IllegalCatch")
143     public void close() throws Exception {
144         LOG.info("HwvtepSouthboundProvider Closed");
145         if (txInvoker != null) {
146             try {
147                 txInvoker.close();
148                 txInvoker = null;
149             } catch (Exception e) {
150                 LOG.error("HWVTEP Southbound Provider failed to close TransactionInvoker", e);
151             }
152         }
153         if (cm != null) {
154             cm.close();
155             cm = null;
156         }
157         if (registration != null) {
158             registration.close();
159             registration = null;
160         }
161         if (providerOwnershipChangeListener != null) {
162             providerOwnershipChangeListener.close();
163             providerOwnershipChangeListener = null;
164         }
165         if (hwvtepDTListener != null) {
166             hwvtepDTListener.close();
167             hwvtepDTListener = null;
168         }
169         if (operTopologyRegistration != null) {
170             operTopologyRegistration.close();
171             operTopologyRegistration = null;
172         }
173     }
174
175     private void initializeHwvtepTopology(final LogicalDatastoreType type) {
176         InstanceIdentifier<Topology> path = InstanceIdentifier
177                 .create(NetworkTopology.class)
178                 .child(Topology.class, new TopologyKey(HwvtepSouthboundConstants.HWVTEP_TOPOLOGY_ID));
179         ReadWriteTransaction transaction = dataBroker.newReadWriteTransaction();
180         CheckedFuture<Optional<Topology>, ReadFailedException> hwvtepTp = transaction.read(type, path);
181         try {
182             if (!hwvtepTp.get().isPresent()) {
183                 TopologyBuilder tpb = new TopologyBuilder();
184                 tpb.setTopologyId(HwvtepSouthboundConstants.HWVTEP_TOPOLOGY_ID);
185                 transaction.put(type, path, tpb.build(), true);
186                 transaction.submit();
187             } else {
188                 transaction.cancel();
189             }
190         } catch (InterruptedException | ExecutionException e) {
191             LOG.error("Error initializing hwvtep topology", e);
192         }
193     }
194
195     public void handleOwnershipChange(final EntityOwnershipChange ownershipChange) {
196         if (ownershipChange.getState().isOwner()) {
197             LOG.info("*This* instance of HWVTEP southbound provider is set as a MASTER instance");
198             LOG.info("Initialize HWVTEP topology {} in operational and config data store if not already present",
199                     HwvtepSouthboundConstants.HWVTEP_TOPOLOGY_ID);
200             initializeHwvtepTopology(LogicalDatastoreType.OPERATIONAL);
201             initializeHwvtepTopology(LogicalDatastoreType.CONFIGURATION);
202         } else {
203             LOG.info("*This* instance of HWVTEP southbound provider is set as a SLAVE instance");
204         }
205     }
206
207
208     @Override
209     public void onDataTreeChanged(final Collection<DataTreeModification<Topology>> collection) {
210         if (!registered.getAndSet(true)) {
211             LOG.info("Starting the ovsdb port");
212             ovsdbConnection.registerConnectionListener(cm);
213             ovsdbConnection.startOvsdbManager();
214         }
215
216         if (operTopologyRegistration != null) {
217             operTopologyRegistration.close();
218             operTopologyRegistration = null;
219         }
220     }
221
222     public void setShardStatusCheckRetryCount(int retryCount) {
223         this.shardStatusCheckRetryCount = retryCount;
224     }
225
226     private static class HwvtepsbPluginInstanceEntityOwnershipListener implements EntityOwnershipListener {
227         private final HwvtepSouthboundProvider hsp;
228         private final EntityOwnershipListenerRegistration listenerRegistration;
229
230         HwvtepsbPluginInstanceEntityOwnershipListener(final HwvtepSouthboundProvider hsp,
231                 final EntityOwnershipService entityOwnershipService) {
232             this.hsp = hsp;
233             listenerRegistration = entityOwnershipService.registerListener(ENTITY_TYPE, this);
234         }
235
236         public void close() {
237             this.listenerRegistration.close();
238         }
239
240         @Override
241         public void ownershipChanged(final EntityOwnershipChange ownershipChange) {
242             hsp.handleOwnershipChange(ownershipChange);
243         }
244     }
245
246     public HwvtepConnectionManager getHwvtepConnectionManager() {
247         return cm;
248     }
249 }