If node joins the cluster after application master instance
[ovsdb.git] / southbound / southbound-impl / src / main / java / org / opendaylight / ovsdb / southbound / SouthboundProvider.java
1 /*
2  * Copyright (c) 2014 Cisco Systems, Inc. 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.southbound;
9
10 import org.opendaylight.controller.md.sal.binding.api.DataBroker;
11 import org.opendaylight.controller.md.sal.binding.api.ReadWriteTransaction;
12 import org.opendaylight.controller.md.sal.common.api.clustering.CandidateAlreadyRegisteredException;
13 import org.opendaylight.controller.md.sal.common.api.clustering.Entity;
14 import org.opendaylight.controller.md.sal.common.api.clustering.EntityOwnershipCandidateRegistration;
15 import org.opendaylight.controller.md.sal.common.api.clustering.EntityOwnershipChange;
16 import org.opendaylight.controller.md.sal.common.api.clustering.EntityOwnershipListener;
17 import org.opendaylight.controller.md.sal.common.api.clustering.EntityOwnershipListenerRegistration;
18 import org.opendaylight.controller.md.sal.common.api.clustering.EntityOwnershipService;
19 import org.opendaylight.controller.md.sal.common.api.clustering.EntityOwnershipState;
20 import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
21 import org.opendaylight.controller.md.sal.common.api.data.ReadFailedException;
22 import org.opendaylight.controller.sal.binding.api.BindingAwareBroker.ProviderContext;
23 import org.opendaylight.controller.sal.binding.api.BindingAwareProvider;
24 import org.opendaylight.ovsdb.lib.OvsdbConnection;
25 import org.opendaylight.ovsdb.lib.impl.OvsdbConnectionService;
26 import org.opendaylight.ovsdb.southbound.transactions.md.TransactionInvoker;
27 import org.opendaylight.ovsdb.southbound.transactions.md.TransactionInvokerImpl;
28 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.NetworkTopology;
29 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.NetworkTopologyBuilder;
30 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.Topology;
31 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.TopologyBuilder;
32 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.TopologyKey;
33 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
34 import org.slf4j.Logger;
35 import org.slf4j.LoggerFactory;
36
37 import com.google.common.base.Optional;
38 import com.google.common.util.concurrent.CheckedFuture;
39
40 public class SouthboundProvider implements BindingAwareProvider, AutoCloseable {
41
42     private static final Logger LOG = LoggerFactory.getLogger(SouthboundProvider.class);
43     private static final String ENTITY_TYPE = "ovsdb-southbound-provider";
44
45     public static DataBroker getDb() {
46         return db;
47     }
48
49     private static DataBroker db;
50     private OvsdbConnectionManager cm;
51     private TransactionInvoker txInvoker;
52     private OvsdbDataChangeListener ovsdbDataChangeListener;
53     private EntityOwnershipService entityOwnershipService;
54     private EntityOwnershipCandidateRegistration registration;
55     private SouthboundPluginInstanceEntityOwnershipListener providerOwnershipChangeListener;
56     private OvsdbConnection ovsdbConnection;
57
58
59     public SouthboundProvider(
60             EntityOwnershipService entityOwnershipServiceDependency) {
61         this.entityOwnershipService = entityOwnershipServiceDependency;
62         registration = null;
63     }
64
65     @Override
66     public void onSessionInitiated(ProviderContext session) {
67         LOG.info("SouthboundProvider Session Initiated");
68         db = session.getSALService(DataBroker.class);
69         this.txInvoker = new TransactionInvokerImpl(db);
70         cm = new OvsdbConnectionManager(db,txInvoker,entityOwnershipService);
71         ovsdbDataChangeListener = new OvsdbDataChangeListener(db,cm);
72
73         //Register listener for entityOnwership changes
74         providerOwnershipChangeListener =
75                 new SouthboundPluginInstanceEntityOwnershipListener(this,this.entityOwnershipService);
76         entityOwnershipService.registerListener(ENTITY_TYPE,providerOwnershipChangeListener);
77
78         //register instance entity to get the ownership of the provider
79         Entity instanceEntity = new Entity(ENTITY_TYPE, ENTITY_TYPE);
80         try {
81             Optional<EntityOwnershipState> ownershipStateOpt = entityOwnershipService.getOwnershipState(instanceEntity);
82             registration = entityOwnershipService.registerCandidate(instanceEntity);
83             if (ownershipStateOpt.isPresent()) {
84                 EntityOwnershipState ownershipState = ownershipStateOpt.get();
85                 if (ownershipState.hasOwner() && !ownershipState.isOwner()) {
86                     if (ovsdbConnection == null) {
87                         ovsdbConnection = new OvsdbConnectionService();
88                         ovsdbConnection.registerConnectionListener(cm);
89                         ovsdbConnection.startOvsdbManager(SouthboundConstants.DEFAULT_OVSDB_PORT);
90                     }
91                 }
92             }
93         } catch (CandidateAlreadyRegisteredException e) {
94             LOG.warn("OVSDB Southbound Provider instance entity {} was already "
95                     + "registered for {} ownership", instanceEntity, e);
96         }
97     }
98
99     @Override
100     public void close() throws Exception {
101         LOG.info("SouthboundProvider Closed");
102         cm.close();
103         ovsdbDataChangeListener.close();
104         registration.close();
105         providerOwnershipChangeListener.close();
106     }
107
108     private void initializeOvsdbTopology(LogicalDatastoreType type) {
109         InstanceIdentifier<Topology> path = InstanceIdentifier
110                 .create(NetworkTopology.class)
111                 .child(Topology.class, new TopologyKey(SouthboundConstants.OVSDB_TOPOLOGY_ID));
112         initializeTopology(type);
113         ReadWriteTransaction transaction = db.newReadWriteTransaction();
114         CheckedFuture<Optional<Topology>, ReadFailedException> ovsdbTp = transaction.read(type, path);
115         try {
116             if (!ovsdbTp.get().isPresent()) {
117                 TopologyBuilder tpb = new TopologyBuilder();
118                 tpb.setTopologyId(SouthboundConstants.OVSDB_TOPOLOGY_ID);
119                 transaction.put(type, path, tpb.build());
120                 transaction.submit();
121             } else {
122                 transaction.cancel();
123             }
124         } catch (Exception e) {
125             LOG.error("Error initializing ovsdb topology", e);
126         }
127     }
128
129     private void initializeTopology(LogicalDatastoreType type) {
130         ReadWriteTransaction transaction = db.newReadWriteTransaction();
131         InstanceIdentifier<NetworkTopology> path = InstanceIdentifier.create(NetworkTopology.class);
132         CheckedFuture<Optional<NetworkTopology>, ReadFailedException> topology = transaction.read(type,path);
133         try {
134             if (!topology.get().isPresent()) {
135                 NetworkTopologyBuilder ntb = new NetworkTopologyBuilder();
136                 transaction.put(type,path,ntb.build());
137                 transaction.submit();
138             } else {
139                 transaction.cancel();
140             }
141         } catch (Exception e) {
142             LOG.error("Error initializing ovsdb topology {}",e);
143         }
144     }
145
146     public void handleOwnershipChange(EntityOwnershipChange ownershipChange) {
147         if (ownershipChange.isOwner()) {
148             LOG.info("*This* instance of OVSDB southbound provider is set as a MASTER instance");
149             LOG.info("Initialize OVSDB topology {} in operational and config data store if not already present"
150                     ,SouthboundConstants.OVSDB_TOPOLOGY_ID);
151             initializeOvsdbTopology(LogicalDatastoreType.OPERATIONAL);
152             initializeOvsdbTopology(LogicalDatastoreType.CONFIGURATION);
153         } else {
154             LOG.info("*This* instance of OVSDB southbound provider is set as a SLAVE instance");
155         }
156         if (ovsdbConnection == null) {
157             ovsdbConnection = new OvsdbConnectionService();
158             ovsdbConnection.registerConnectionListener(cm);
159             ovsdbConnection.startOvsdbManager(SouthboundConstants.DEFAULT_OVSDB_PORT);
160         }
161     }
162
163     private class SouthboundPluginInstanceEntityOwnershipListener implements EntityOwnershipListener {
164         private SouthboundProvider sp;
165         private EntityOwnershipListenerRegistration listenerRegistration;
166
167         SouthboundPluginInstanceEntityOwnershipListener(SouthboundProvider sp,
168                 EntityOwnershipService entityOwnershipService) {
169             this.sp = sp;
170             listenerRegistration = entityOwnershipService.registerListener(ENTITY_TYPE, this);
171         }
172
173         public void close() {
174             this.listenerRegistration.close();
175         }
176         @Override
177         public void ownershipChanged(EntityOwnershipChange ownershipChange) {
178             sp.handleOwnershipChange(ownershipChange);
179         }
180     }
181
182 }