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