Using MD-SAL .exists() API
[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.util.concurrent.FluentFuture;
11 import java.util.Collection;
12 import java.util.concurrent.ExecutionException;
13 import java.util.concurrent.TimeUnit;
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.mdsal.binding.api.ClusteredDataTreeChangeListener;
22 import org.opendaylight.mdsal.binding.api.DataBroker;
23 import org.opendaylight.mdsal.binding.api.DataTreeIdentifier;
24 import org.opendaylight.mdsal.binding.api.DataTreeModification;
25 import org.opendaylight.mdsal.binding.api.ReadWriteTransaction;
26 import org.opendaylight.mdsal.binding.dom.codec.api.BindingNormalizedNodeSerializer;
27 import org.opendaylight.mdsal.common.api.LogicalDatastoreType;
28 import org.opendaylight.mdsal.dom.api.DOMSchemaService;
29 import org.opendaylight.mdsal.eos.binding.api.Entity;
30 import org.opendaylight.mdsal.eos.binding.api.EntityOwnershipCandidateRegistration;
31 import org.opendaylight.mdsal.eos.binding.api.EntityOwnershipChange;
32 import org.opendaylight.mdsal.eos.binding.api.EntityOwnershipListener;
33 import org.opendaylight.mdsal.eos.binding.api.EntityOwnershipListenerRegistration;
34 import org.opendaylight.mdsal.eos.binding.api.EntityOwnershipService;
35 import org.opendaylight.mdsal.eos.common.api.CandidateAlreadyRegisteredException;
36 import org.opendaylight.ovsdb.hwvtepsouthbound.reconciliation.configuration.HwvtepReconciliationManager;
37 import org.opendaylight.ovsdb.hwvtepsouthbound.transactions.md.TransactionInvoker;
38 import org.opendaylight.ovsdb.hwvtepsouthbound.transactions.md.TransactionInvokerImpl;
39 import org.opendaylight.ovsdb.lib.OvsdbConnection;
40 import org.opendaylight.ovsdb.utils.mdsal.utils.Scheduler;
41 import org.opendaylight.ovsdb.utils.mdsal.utils.ShardStatusMonitor;
42 import org.opendaylight.serviceutils.upgrade.UpgradeState;
43 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.NetworkTopology;
44 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.Topology;
45 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.TopologyBuilder;
46 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.TopologyKey;
47 import org.opendaylight.yangtools.concepts.ListenerRegistration;
48 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
49 import org.slf4j.Logger;
50 import org.slf4j.LoggerFactory;
51
52 @Singleton
53 @Service(classes = HwvtepSouthboundProvider.class) // only because HwvtepCacheDisplayCmd needs a @Reference to this
54 public class HwvtepSouthboundProvider implements ClusteredDataTreeChangeListener<Topology>, AutoCloseable {
55
56     private static final Logger LOG = LoggerFactory.getLogger(HwvtepSouthboundProvider.class);
57     private static final String ENTITY_TYPE = "ovsdb-hwvtepsouthbound-provider";
58
59     private final DataBroker dataBroker;
60     private final EntityOwnershipService entityOwnershipService;
61     private final OvsdbConnection ovsdbConnection;
62
63     private HwvtepConnectionManager cm;
64     private TransactionInvoker txInvoker;
65     private EntityOwnershipCandidateRegistration registration;
66     private HwvtepsbPluginInstanceEntityOwnershipListener providerOwnershipChangeListener;
67     private HwvtepDataChangeListener hwvtepDTListener;
68     private HwvtepReconciliationManager hwvtepReconciliationManager;
69     private final AtomicBoolean registered = new AtomicBoolean(false);
70     private ListenerRegistration<HwvtepSouthboundProvider> operTopologyRegistration;
71     private int shardStatusCheckRetryCount = 1000;
72     private UpgradeState upgradeState;
73
74     @Inject
75     public HwvtepSouthboundProvider(@Reference final DataBroker dataBroker,
76             @Reference final EntityOwnershipService entityOwnershipServiceDependency,
77             @Reference final OvsdbConnection ovsdbConnection,
78             @Reference final DOMSchemaService schemaService,
79             @Reference final BindingNormalizedNodeSerializer bindingNormalizedNodeSerializer,
80             @Reference final UpgradeState upgradeState) {
81         this.dataBroker = dataBroker;
82         this.entityOwnershipService = entityOwnershipServiceDependency;
83         registration = null;
84         this.ovsdbConnection = ovsdbConnection;
85         this.upgradeState = upgradeState;
86         HwvtepSouthboundUtil.setInstanceIdentifierCodec(new InstanceIdentifierCodec(schemaService,
87                 bindingNormalizedNodeSerializer));
88         LOG.info("HwvtepSouthboundProvider ovsdbConnectionService: {}", ovsdbConnection);
89     }
90
91     /**
92      * Used by blueprint when starting the container.
93      */
94     @PostConstruct
95     public void init() {
96         boolean isDatastoreAvailable = false;
97         int retryCount = 0;
98         try {
99             while (retryCount < shardStatusCheckRetryCount) {
100                 isDatastoreAvailable = ShardStatusMonitor.getShardStatus(ShardStatusMonitor.TOPOLOGY_SHARDS);
101                 if (isDatastoreAvailable) {
102                     break;
103                 }
104                 LOG.warn("Hwvtep: retrying shard status check for the {} time", ++retryCount);
105                 Thread.sleep(2000);
106             }
107             if (isDatastoreAvailable) {
108                 LOG.info("Hwvtep is UP");
109                 init2();
110             }
111         } catch (InterruptedException e) {
112             LOG.error("Error in intializing the Hwvtep Southbound ", e);
113         }
114     }
115
116     private void init2() {
117         LOG.info("HwvtepSouthboundProvider Session Initiated");
118         txInvoker = new TransactionInvokerImpl(dataBroker);
119         cm = new HwvtepConnectionManager(dataBroker, txInvoker, entityOwnershipService, ovsdbConnection);
120         registerConfigListenerPostUpgrade();
121         //Register listener for entityOnwership changes
122         providerOwnershipChangeListener =
123                 new HwvtepsbPluginInstanceEntityOwnershipListener(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("HWVTEP 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(HwvtepSouthboundConstants.HWVTEP_TOPOLOGY_ID));
136         DataTreeIdentifier<Topology> treeId =
137                 DataTreeIdentifier.create(LogicalDatastoreType.OPERATIONAL, path);
138
139         LOG.trace("Registering listener for path {}", treeId);
140         operTopologyRegistration = dataBroker.registerDataTreeChangeListener(treeId, this);
141         Scheduler.getScheduledExecutorService().schedule(() -> {
142             if (!registered.get()) {
143                 openOvsdbPort();
144                 LOG.error("Timed out to get eos notification opening the port now");
145             }
146         }, HwvtepSouthboundConstants.PORT_OPEN_MAX_DELAY_IN_MINS, TimeUnit.MINUTES);
147     }
148
149     private void registerConfigListenerPostUpgrade() {
150         if (upgradeState.isUpgradeInProgress()) {
151             LOG.error("Upgrade is in progress delay config data change listener registration");
152             Scheduler.getScheduledExecutorService().schedule(() -> registerConfigListenerPostUpgrade(),
153                     60, TimeUnit.SECONDS);
154             return;
155         }
156         hwvtepDTListener = new HwvtepDataChangeListener(dataBroker, cm);
157         hwvtepReconciliationManager = new HwvtepReconciliationManager(dataBroker, cm);
158     }
159
160     @Override
161     @PreDestroy
162     @SuppressWarnings("checkstyle:IllegalCatch")
163     public void close() throws Exception {
164         LOG.info("HwvtepSouthboundProvider Closed");
165         if (txInvoker != null) {
166             try {
167                 txInvoker.close();
168                 txInvoker = null;
169             } catch (Exception e) {
170                 LOG.error("HWVTEP Southbound Provider failed to close TransactionInvoker", e);
171             }
172         }
173         if (cm != null) {
174             cm.close();
175             cm = null;
176         }
177         if (registration != null) {
178             registration.close();
179             registration = null;
180         }
181         if (providerOwnershipChangeListener != null) {
182             providerOwnershipChangeListener.close();
183             providerOwnershipChangeListener = null;
184         }
185         if (hwvtepDTListener != null) {
186             hwvtepDTListener.close();
187             hwvtepDTListener = null;
188         }
189         if (operTopologyRegistration != null) {
190             operTopologyRegistration.close();
191             operTopologyRegistration = null;
192         }
193     }
194
195     private void initializeHwvtepTopology(final LogicalDatastoreType type) {
196         InstanceIdentifier<Topology> path = InstanceIdentifier
197                 .create(NetworkTopology.class)
198                 .child(Topology.class, new TopologyKey(HwvtepSouthboundConstants.HWVTEP_TOPOLOGY_ID));
199         ReadWriteTransaction transaction = dataBroker.newReadWriteTransaction();
200         FluentFuture<Boolean> hwvtepTp = transaction.exists(type, path);
201         try {
202             if (!hwvtepTp.get().booleanValue()) {
203                 TopologyBuilder tpb = new TopologyBuilder();
204                 tpb.setTopologyId(HwvtepSouthboundConstants.HWVTEP_TOPOLOGY_ID);
205                 transaction.mergeParentStructurePut(type, path, tpb.build());
206                 transaction.commit();
207             } else {
208                 transaction.cancel();
209             }
210         } catch (InterruptedException | ExecutionException e) {
211             LOG.error("Error initializing hwvtep topology", e);
212         }
213     }
214
215     public void handleOwnershipChange(final EntityOwnershipChange ownershipChange) {
216         if (ownershipChange.getState().isOwner()) {
217             LOG.info("*This* instance of HWVTEP southbound provider is set as a MASTER instance");
218             LOG.info("Initialize HWVTEP topology {} in operational and config data store if not already present",
219                     HwvtepSouthboundConstants.HWVTEP_TOPOLOGY_ID);
220             initializeHwvtepTopology(LogicalDatastoreType.OPERATIONAL);
221             initializeHwvtepTopology(LogicalDatastoreType.CONFIGURATION);
222         } else {
223             LOG.info("*This* instance of HWVTEP southbound provider is set as a SLAVE instance");
224         }
225     }
226
227
228     @Override
229     public void onDataTreeChanged(final Collection<DataTreeModification<Topology>> collection) {
230         openOvsdbPort();
231
232         if (operTopologyRegistration != null) {
233             operTopologyRegistration.close();
234             operTopologyRegistration = null;
235         }
236     }
237
238
239
240     private void openOvsdbPort() {
241         if (!registered.getAndSet(true)) {
242             LOG.info("Starting the ovsdb port");
243             ovsdbConnection.registerConnectionListener(cm);
244             ovsdbConnection.startOvsdbManager();
245         }
246     }
247
248     public void setShardStatusCheckRetryCount(int retryCount) {
249         this.shardStatusCheckRetryCount = retryCount;
250     }
251
252     private static class HwvtepsbPluginInstanceEntityOwnershipListener implements EntityOwnershipListener {
253         private final HwvtepSouthboundProvider hsp;
254         private final EntityOwnershipListenerRegistration listenerRegistration;
255
256         HwvtepsbPluginInstanceEntityOwnershipListener(final HwvtepSouthboundProvider hsp,
257                 final EntityOwnershipService entityOwnershipService) {
258             this.hsp = hsp;
259             listenerRegistration = entityOwnershipService.registerListener(ENTITY_TYPE, this);
260         }
261
262         public void close() {
263             this.listenerRegistration.close();
264         }
265
266         @Override
267         public void ownershipChanged(final EntityOwnershipChange ownershipChange) {
268             hsp.handleOwnershipChange(ownershipChange);
269         }
270     }
271
272     public HwvtepConnectionManager getHwvtepConnectionManager() {
273         return cm;
274     }
275 }