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