ad1cf20969a488889aa66f8ce8e4f671663f7268
[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
13 import java.util.Collection;
14 import java.util.concurrent.atomic.AtomicBoolean;
15
16 import org.opendaylight.controller.md.sal.binding.api.ClusteredDataTreeChangeListener;
17 import org.opendaylight.controller.md.sal.binding.api.DataBroker;
18 import org.opendaylight.controller.md.sal.binding.api.DataTreeIdentifier;
19 import org.opendaylight.controller.md.sal.binding.api.DataTreeModification;
20 import org.opendaylight.controller.md.sal.binding.api.ReadWriteTransaction;
21 import org.opendaylight.controller.md.sal.common.api.clustering.CandidateAlreadyRegisteredException;
22 import org.opendaylight.controller.md.sal.common.api.clustering.Entity;
23 import org.opendaylight.controller.md.sal.common.api.clustering.EntityOwnershipCandidateRegistration;
24 import org.opendaylight.controller.md.sal.common.api.clustering.EntityOwnershipChange;
25 import org.opendaylight.controller.md.sal.common.api.clustering.EntityOwnershipListener;
26 import org.opendaylight.controller.md.sal.common.api.clustering.EntityOwnershipListenerRegistration;
27 import org.opendaylight.controller.md.sal.common.api.clustering.EntityOwnershipService;
28 import org.opendaylight.controller.md.sal.common.api.clustering.EntityOwnershipState;
29 import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
30 import org.opendaylight.controller.md.sal.common.api.data.ReadFailedException;
31 import org.opendaylight.mdsal.binding.dom.codec.api.BindingNormalizedNodeSerializer;
32 import org.opendaylight.mdsal.dom.api.DOMSchemaService;
33 import org.opendaylight.ovsdb.hwvtepsouthbound.reconciliation.configuration.HwvtepReconciliationManager;
34 import org.opendaylight.ovsdb.hwvtepsouthbound.transactions.md.TransactionInvoker;
35 import org.opendaylight.ovsdb.hwvtepsouthbound.transactions.md.TransactionInvokerImpl;
36 import org.opendaylight.ovsdb.lib.OvsdbConnection;
37 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.NetworkTopology;
38 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.Topology;
39 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.TopologyBuilder;
40 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.TopologyKey;
41 import org.opendaylight.yangtools.concepts.ListenerRegistration;
42 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
43 import org.slf4j.Logger;
44 import org.slf4j.LoggerFactory;
45
46 public class HwvtepSouthboundProvider implements ClusteredDataTreeChangeListener<Topology>, AutoCloseable {
47
48     private static final Logger LOG = LoggerFactory.getLogger(HwvtepSouthboundProvider.class);
49     private static final String ENTITY_TYPE = "ovsdb-hwvtepsouthbound-provider";
50
51     public static DataBroker getDb() {
52         return db;
53     }
54
55     private static DataBroker db;
56     private final EntityOwnershipService entityOwnershipService;
57     private final OvsdbConnection ovsdbConnection;
58
59     private HwvtepConnectionManager cm;
60     private TransactionInvoker txInvoker;
61     private EntityOwnershipCandidateRegistration registration;
62     private HwvtepsbPluginInstanceEntityOwnershipListener providerOwnershipChangeListener;
63     private HwvtepDataChangeListener hwvtepDTListener;
64     private HwvtepReconciliationManager hwvtepReconciliationManager;
65     private AtomicBoolean registered = new AtomicBoolean(false);
66     private ListenerRegistration<HwvtepSouthboundProvider> operTopologyRegistration;
67
68     public HwvtepSouthboundProvider(final DataBroker dataBroker,
69             final EntityOwnershipService entityOwnershipServiceDependency,
70             final OvsdbConnection ovsdbConnection,
71             final DOMSchemaService schemaService,
72             final BindingNormalizedNodeSerializer bindingNormalizedNodeSerializer) {
73         this.db = dataBroker;
74         this.entityOwnershipService = entityOwnershipServiceDependency;
75         registration = null;
76         this.ovsdbConnection = ovsdbConnection;
77         HwvtepSouthboundUtil.setInstanceIdentifierCodec(new InstanceIdentifierCodec(schemaService,
78                 bindingNormalizedNodeSerializer));
79         LOG.info("HwvtepSouthboundProvider ovsdbConnectionService: {}", ovsdbConnection);
80     }
81
82     /**
83      * Used by blueprint when starting the container.
84      */
85     public void init() {
86         LOG.info("HwvtepSouthboundProvider Session Initiated");
87         txInvoker = new TransactionInvokerImpl(db);
88         cm = new HwvtepConnectionManager(db, txInvoker, entityOwnershipService);
89         hwvtepDTListener = new HwvtepDataChangeListener(db, cm);
90         hwvtepReconciliationManager = new HwvtepReconciliationManager(db, cm);
91         //Register listener for entityOnwership changes
92         providerOwnershipChangeListener =
93                 new HwvtepsbPluginInstanceEntityOwnershipListener(this,this.entityOwnershipService);
94
95         //register instance entity to get the ownership of the provider
96         Entity instanceEntity = new Entity(ENTITY_TYPE, ENTITY_TYPE);
97         try {
98             Optional<EntityOwnershipState> ownershipStateOpt = entityOwnershipService.getOwnershipState(instanceEntity);
99             registration = entityOwnershipService.registerCandidate(instanceEntity);
100         } catch (CandidateAlreadyRegisteredException e) {
101             LOG.warn("HWVTEP Southbound Provider instance entity {} was already "
102                     + "registered for ownership", instanceEntity, e);
103         }
104         InstanceIdentifier<Topology> path = InstanceIdentifier
105                 .create(NetworkTopology.class)
106                 .child(Topology.class, new TopologyKey(HwvtepSouthboundConstants.HWVTEP_TOPOLOGY_ID));
107         DataTreeIdentifier<Topology> treeId =
108                 new DataTreeIdentifier<Topology>(LogicalDatastoreType.OPERATIONAL, path);
109
110         LOG.trace("Registering listener for path {}", treeId);
111         operTopologyRegistration = db.registerDataTreeChangeListener(treeId, this);
112     }
113
114     @Override
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 (Exception 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 HwvtepSouthboundProvider hsp;
198         private 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         @Override
210         public void ownershipChanged(EntityOwnershipChange ownershipChange) {
211             hsp.handleOwnershipChange(ownershipChange);
212         }
213     }
214
215 }