322fa4eb86ed988ba2a81ab82a2d790ed0a1e9a3
[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.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.NetworkTopology;
42 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.Topology;
43 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.TopologyBuilder;
44 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.TopologyKey;
45 import org.opendaylight.yangtools.concepts.ListenerRegistration;
46 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
47 import org.slf4j.Logger;
48 import org.slf4j.LoggerFactory;
49
50 @Singleton
51 @Service(classes = HwvtepSouthboundProvider.class) // only because HwvtepCacheDisplayCmd needs a @Reference to this
52 public class HwvtepSouthboundProvider implements ClusteredDataTreeChangeListener<Topology>, AutoCloseable {
53
54     private static final Logger LOG = LoggerFactory.getLogger(HwvtepSouthboundProvider.class);
55     private static final String ENTITY_TYPE = "ovsdb-hwvtepsouthbound-provider";
56
57     private final DataBroker dataBroker;
58     private final EntityOwnershipService entityOwnershipService;
59     private final OvsdbConnection ovsdbConnection;
60
61     private HwvtepConnectionManager cm;
62     private TransactionInvoker txInvoker;
63     private EntityOwnershipCandidateRegistration registration;
64     private HwvtepsbPluginInstanceEntityOwnershipListener providerOwnershipChangeListener;
65     private HwvtepDataChangeListener hwvtepDTListener;
66     private HwvtepReconciliationManager hwvtepReconciliationManager;
67     private final AtomicBoolean registered = new AtomicBoolean(false);
68     private ListenerRegistration<HwvtepSouthboundProvider> operTopologyRegistration;
69
70     @Inject
71     public HwvtepSouthboundProvider(@Reference final DataBroker dataBroker,
72             @Reference final EntityOwnershipService entityOwnershipServiceDependency,
73             @Reference final OvsdbConnection ovsdbConnection,
74             @Reference final DOMSchemaService schemaService,
75             @Reference final BindingNormalizedNodeSerializer bindingNormalizedNodeSerializer) {
76         this.dataBroker = dataBroker;
77         this.entityOwnershipService = entityOwnershipServiceDependency;
78         registration = null;
79         this.ovsdbConnection = ovsdbConnection;
80         HwvtepSouthboundUtil.setInstanceIdentifierCodec(new InstanceIdentifierCodec(schemaService,
81                 bindingNormalizedNodeSerializer));
82         LOG.info("HwvtepSouthboundProvider ovsdbConnectionService: {}", ovsdbConnection);
83     }
84
85     /**
86      * Used by blueprint when starting the container.
87      */
88     @PostConstruct
89     public void init() {
90         LOG.info("HwvtepSouthboundProvider Session Initiated");
91         txInvoker = new TransactionInvokerImpl(dataBroker);
92         cm = new HwvtepConnectionManager(dataBroker, txInvoker, entityOwnershipService, ovsdbConnection);
93         hwvtepDTListener = new HwvtepDataChangeListener(dataBroker, cm);
94         hwvtepReconciliationManager = new HwvtepReconciliationManager(dataBroker, cm);
95         //Register listener for entityOnwership changes
96         providerOwnershipChangeListener =
97                 new HwvtepsbPluginInstanceEntityOwnershipListener(this,this.entityOwnershipService);
98
99         //register instance entity to get the ownership of the provider
100         Entity instanceEntity = new Entity(ENTITY_TYPE, ENTITY_TYPE);
101         try {
102             registration = entityOwnershipService.registerCandidate(instanceEntity);
103         } catch (CandidateAlreadyRegisteredException e) {
104             LOG.warn("HWVTEP Southbound Provider instance entity {} was already "
105                     + "registered for ownership", instanceEntity, e);
106         }
107         InstanceIdentifier<Topology> path = InstanceIdentifier
108                 .create(NetworkTopology.class)
109                 .child(Topology.class, new TopologyKey(HwvtepSouthboundConstants.HWVTEP_TOPOLOGY_ID));
110         DataTreeIdentifier<Topology> treeId =
111                 new DataTreeIdentifier<>(LogicalDatastoreType.OPERATIONAL, path);
112
113         LOG.trace("Registering listener for path {}", treeId);
114         operTopologyRegistration = dataBroker.registerDataTreeChangeListener(treeId, this);
115     }
116
117     @Override
118     @PreDestroy
119     @SuppressWarnings("checkstyle:IllegalCatch")
120     public void close() throws Exception {
121         LOG.info("HwvtepSouthboundProvider Closed");
122         if (txInvoker != null) {
123             try {
124                 txInvoker.close();
125                 txInvoker = null;
126             } catch (Exception e) {
127                 LOG.error("HWVTEP Southbound Provider failed to close TransactionInvoker", e);
128             }
129         }
130         if (cm != null) {
131             cm.close();
132             cm = null;
133         }
134         if (registration != null) {
135             registration.close();
136             registration = null;
137         }
138         if (providerOwnershipChangeListener != null) {
139             providerOwnershipChangeListener.close();
140             providerOwnershipChangeListener = null;
141         }
142         if (hwvtepDTListener != null) {
143             hwvtepDTListener.close();
144             hwvtepDTListener = null;
145         }
146         if (operTopologyRegistration != null) {
147             operTopologyRegistration.close();
148             operTopologyRegistration = null;
149         }
150     }
151
152     private void initializeHwvtepTopology(final LogicalDatastoreType type) {
153         InstanceIdentifier<Topology> path = InstanceIdentifier
154                 .create(NetworkTopology.class)
155                 .child(Topology.class, new TopologyKey(HwvtepSouthboundConstants.HWVTEP_TOPOLOGY_ID));
156         ReadWriteTransaction transaction = dataBroker.newReadWriteTransaction();
157         CheckedFuture<Optional<Topology>, ReadFailedException> hwvtepTp = transaction.read(type, path);
158         try {
159             if (!hwvtepTp.get().isPresent()) {
160                 TopologyBuilder tpb = new TopologyBuilder();
161                 tpb.setTopologyId(HwvtepSouthboundConstants.HWVTEP_TOPOLOGY_ID);
162                 transaction.put(type, path, tpb.build(), true);
163                 transaction.submit();
164             } else {
165                 transaction.cancel();
166             }
167         } catch (InterruptedException | ExecutionException e) {
168             LOG.error("Error initializing hwvtep topology", e);
169         }
170     }
171
172     public void handleOwnershipChange(final EntityOwnershipChange ownershipChange) {
173         if (ownershipChange.getState().isOwner()) {
174             LOG.info("*This* instance of HWVTEP southbound provider is set as a MASTER instance");
175             LOG.info("Initialize HWVTEP topology {} in operational and config data store if not already present",
176                     HwvtepSouthboundConstants.HWVTEP_TOPOLOGY_ID);
177             initializeHwvtepTopology(LogicalDatastoreType.OPERATIONAL);
178             initializeHwvtepTopology(LogicalDatastoreType.CONFIGURATION);
179         } else {
180             LOG.info("*This* instance of HWVTEP southbound provider is set as a SLAVE instance");
181         }
182     }
183
184
185     @Override
186     public void onDataTreeChanged(final Collection<DataTreeModification<Topology>> collection) {
187         if (!registered.getAndSet(true)) {
188             LOG.info("Starting the ovsdb port");
189             ovsdbConnection.registerConnectionListener(cm);
190             ovsdbConnection.startOvsdbManager();
191         }
192
193         if (operTopologyRegistration != null) {
194             operTopologyRegistration.close();
195             operTopologyRegistration = null;
196         }
197     }
198
199     private static class HwvtepsbPluginInstanceEntityOwnershipListener implements EntityOwnershipListener {
200         private final HwvtepSouthboundProvider hsp;
201         private final EntityOwnershipListenerRegistration listenerRegistration;
202
203         HwvtepsbPluginInstanceEntityOwnershipListener(final HwvtepSouthboundProvider hsp,
204                 final EntityOwnershipService entityOwnershipService) {
205             this.hsp = hsp;
206             listenerRegistration = entityOwnershipService.registerListener(ENTITY_TYPE, this);
207         }
208
209         public void close() {
210             this.listenerRegistration.close();
211         }
212
213         @Override
214         public void ownershipChanged(final EntityOwnershipChange ownershipChange) {
215             hsp.handleOwnershipChange(ownershipChange);
216         }
217     }
218
219     public HwvtepConnectionManager getHwvtepConnectionManager() {
220         return cm;
221     }
222 }