Merge "Enable cancel monitoring"
[ovsdb.git] / southbound / southbound-impl / src / main / java / org / opendaylight / ovsdb / southbound / OvsdbConnectionManager.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 java.net.InetAddress;
11 import java.net.UnknownHostException;
12 import java.util.Map;
13 import java.util.concurrent.ConcurrentHashMap;
14
15 import org.opendaylight.controller.md.sal.binding.api.DataBroker;
16 import org.opendaylight.controller.md.sal.binding.api.ReadOnlyTransaction;
17 import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
18 import org.opendaylight.controller.md.sal.common.api.data.ReadFailedException;
19 import org.opendaylight.ovsdb.lib.OvsdbClient;
20 import org.opendaylight.ovsdb.lib.OvsdbConnectionListener;
21 import org.opendaylight.ovsdb.lib.impl.OvsdbConnectionService;
22 import org.opendaylight.ovsdb.southbound.transactions.md.OvsdbNodeRemoveCommand;
23 import org.opendaylight.ovsdb.southbound.transactions.md.TransactionInvoker;
24 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.ovsdb.rev150105.OvsdbBridgeAttributes;
25 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.ovsdb.rev150105.OvsdbBridgeAugmentation;
26 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.ovsdb.rev150105.OvsdbNodeAugmentation;
27 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.ovsdb.rev150105.ovsdb.node.attributes.ConnectionInfo;
28 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.topology.Node;
29 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
30 import org.slf4j.Logger;
31 import org.slf4j.LoggerFactory;
32
33 import com.google.common.base.Optional;
34 import com.google.common.base.Preconditions;
35 import com.google.common.util.concurrent.CheckedFuture;
36
37 public class OvsdbConnectionManager implements OvsdbConnectionListener, AutoCloseable {
38     Map<ConnectionInfo,OvsdbConnectionInstance> clients
39         = new ConcurrentHashMap<ConnectionInfo,OvsdbConnectionInstance>();
40     private static final Logger LOG = LoggerFactory.getLogger(OvsdbConnectionManager.class);
41
42     private DataBroker db;
43     private TransactionInvoker txInvoker;
44     private Map<ConnectionInfo,InstanceIdentifier<Node>> instanceIdentifiers =
45             new ConcurrentHashMap<ConnectionInfo,InstanceIdentifier<Node>>();
46
47     public OvsdbConnectionManager(DataBroker db,TransactionInvoker txInvoker) {
48         this.db = db;
49         this.txInvoker = txInvoker;
50     }
51
52     @Override
53     public void connected(final OvsdbClient externalClient) {
54         OvsdbConnectionInstance client = connectedButCallBacksNotRegistered(externalClient);
55         client.registerCallbacks();
56     }
57
58     public OvsdbConnectionInstance connectedButCallBacksNotRegistered(final OvsdbClient externalClient) {
59         LOG.info("OVSDB Connection from {}:{}",externalClient.getConnectionInfo().getRemoteAddress(),
60                 externalClient.getConnectionInfo().getRemotePort());
61         ConnectionInfo key = SouthboundMapper.createConnectionInfo(externalClient);
62         OvsdbConnectionInstance client = new OvsdbConnectionInstance(key,externalClient,txInvoker,
63                 getInstanceIdentifier(key));
64         putConnectionInstance(key, client);
65         client.createTransactInvokers();
66         return client;
67     }
68
69     @Override
70     public void disconnected(OvsdbClient client) {
71         LOG.info("OVSDB Disconnect from {}:{}",client.getConnectionInfo().getRemoteAddress(),
72                 client.getConnectionInfo().getRemotePort());
73         ConnectionInfo key = SouthboundMapper.createConnectionInfo(client);
74         txInvoker.invoke(new OvsdbNodeRemoveCommand(getConnectionInstance(key),null,null));
75         clients.remove(key);
76         LOG.trace("OvsdbConnectionManager: disconnected exit");
77     }
78
79     public OvsdbClient connect(InstanceIdentifier<Node> iid,
80             OvsdbNodeAugmentation ovsdbNode) throws UnknownHostException {
81         // TODO handle case where we already have a connection
82         // TODO use transaction chains to handle ordering issues between disconnected
83         // and connected when writing to the operational store
84         InetAddress ip = SouthboundMapper.createInetAddress(ovsdbNode.getConnectionInfo().getRemoteIp());
85         OvsdbClient client = OvsdbConnectionService.getService().connect(ip,
86                 ovsdbNode.getConnectionInfo().getRemotePort().getValue().intValue());
87         // For connections from the controller to the ovs instance, the library doesn't call
88         // this method for us
89         if (client != null) {
90             putInstanceIdentifier(ovsdbNode.getConnectionInfo(), iid.firstIdentifierOf(Node.class));
91             connectedButCallBacksNotRegistered(client);
92         } else {
93             LOG.warn("Failed to connect to Ovsdb Node {}", ovsdbNode.getConnectionInfo());
94         }
95         return client;
96     }
97
98     public void disconnect(OvsdbNodeAugmentation ovsdbNode) throws UnknownHostException {
99         OvsdbClient client = getConnectionInstance(ovsdbNode.getConnectionInfo());
100         if (client != null) {
101             client.disconnect();
102         }
103     }
104
105     public void init(ConnectionInfo key) {
106         OvsdbConnectionInstance client = getConnectionInstance(key);
107         if (client != null) {
108             /*
109              *  Note: registerCallbacks() is idemPotent... so if you call it repeatedly all is safe,
110              *  it only registersCallbacks on the *first* call.
111              */
112             client.registerCallbacks();
113         }
114     }
115
116     @Override
117     public void close() throws Exception {
118         for (OvsdbClient client: clients.values()) {
119             client.disconnect();
120         }
121     }
122
123     private void putConnectionInstance(ConnectionInfo key,OvsdbConnectionInstance instance) {
124         ConnectionInfo connectionInfo = SouthboundMapper.suppressLocalIpPort(key);
125         clients.put(connectionInfo, instance);
126     }
127
128     private void putInstanceIdentifier(ConnectionInfo key,InstanceIdentifier<Node> iid) {
129         ConnectionInfo connectionInfo = SouthboundMapper.suppressLocalIpPort(key);
130         instanceIdentifiers.put(connectionInfo, iid);
131     }
132
133     public OvsdbConnectionInstance getConnectionInstance(ConnectionInfo key) {
134         ConnectionInfo connectionInfo = SouthboundMapper.suppressLocalIpPort(key);
135         return clients.get(connectionInfo);
136     }
137
138     public InstanceIdentifier<Node> getInstanceIdentifier(ConnectionInfo key) {
139         ConnectionInfo connectionInfo = SouthboundMapper.suppressLocalIpPort(key);
140         InstanceIdentifier<Node> iid = instanceIdentifiers.get(connectionInfo);
141         return iid;
142     }
143
144     public OvsdbConnectionInstance getConnectionInstance(OvsdbBridgeAttributes mn) {
145         Optional<OvsdbNodeAugmentation> optional = SouthboundUtil.getManagingNode(db, mn);
146         if (optional.isPresent()) {
147             return getConnectionInstance(optional.get().getConnectionInfo());
148         } else {
149             return null;
150         }
151     }
152
153     public OvsdbConnectionInstance getConnectionInstance(Node node) {
154         Preconditions.checkNotNull(node);
155         OvsdbNodeAugmentation ovsdbNode = node.getAugmentation(OvsdbNodeAugmentation.class);
156         OvsdbBridgeAugmentation ovsdbManagedNode = node.getAugmentation(OvsdbBridgeAugmentation.class);
157         if (ovsdbNode != null) {
158             return getConnectionInstance(ovsdbNode.getConnectionInfo());
159         } else if (ovsdbManagedNode != null) {
160             return getConnectionInstance(ovsdbManagedNode);
161         } else {
162             LOG.warn("This is not a node that gives any hint how to find its OVSDB Manager: {}",node);
163             return null;
164         }
165     }
166
167     public OvsdbConnectionInstance getConnectionInstance(InstanceIdentifier<Node> nodePath) {
168         try {
169             ReadOnlyTransaction transaction = db.newReadOnlyTransaction();
170             CheckedFuture<Optional<Node>, ReadFailedException> nodeFuture = transaction.read(
171                     LogicalDatastoreType.OPERATIONAL, nodePath);
172             transaction.close();
173             Optional<Node> optional = nodeFuture.get();
174             if (optional != null && optional.isPresent() && optional.get() instanceof Node) {
175                 return this.getConnectionInstance(optional.get());
176             } else {
177                 LOG.warn("Found non-topological node {} on path {}",optional);
178                 return null;
179             }
180         } catch (Exception e) {
181             LOG.warn("Failed to get Ovsdb Node {}",nodePath, e);
182             return null;
183         }
184     }
185
186     public OvsdbClient getClient(ConnectionInfo connectionInfo) {
187         return getConnectionInstance(connectionInfo);
188     }
189
190     public OvsdbClient getClient(OvsdbBridgeAttributes mn) {
191         return getConnectionInstance(mn);
192     }
193
194     public OvsdbClient getClient(Node node) {
195         return getConnectionInstance(node);
196     }
197 }