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