Bump upstreams for 2022.09 Chlorine
[ovsdb.git] / utils / southbound-utils / src / main / java / org / opendaylight / ovsdb / utils / southbound / utils / SouthboundUtils.java
1 /*
2  * Copyright (c) 2015, 2018 Red Hat, 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
9 package org.opendaylight.ovsdb.utils.southbound.utils;
10
11 import static java.util.Objects.requireNonNull;
12
13 import com.google.common.collect.ImmutableBiMap;
14 import com.google.common.collect.ImmutableMap;
15 import java.math.BigInteger;
16 import java.net.Inet4Address;
17 import java.net.Inet6Address;
18 import java.net.InetAddress;
19 import java.net.UnknownHostException;
20 import java.security.InvalidParameterException;
21 import java.util.ArrayList;
22 import java.util.Collections;
23 import java.util.HashMap;
24 import java.util.List;
25 import java.util.Locale;
26 import java.util.Map;
27 import java.util.regex.Matcher;
28 import java.util.regex.Pattern;
29 import java.util.stream.Collectors;
30 import org.opendaylight.mdsal.common.api.LogicalDatastoreType;
31 import org.opendaylight.ovsdb.utils.config.ConfigProperties;
32 import org.opendaylight.ovsdb.utils.mdsal.utils.MdsalUtils;
33 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.IetfInetUtil;
34 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.IpAddress;
35 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.Ipv6Address;
36 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.PortNumber;
37 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.Uri;
38 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.ovsdb.rev150105.DatapathId;
39 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.ovsdb.rev150105.DatapathTypeBase;
40 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.ovsdb.rev150105.DatapathTypeNetdev;
41 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.ovsdb.rev150105.InterfaceTypeBase;
42 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.ovsdb.rev150105.InterfaceTypeDpdk;
43 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.ovsdb.rev150105.InterfaceTypeDpdkr;
44 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.ovsdb.rev150105.InterfaceTypeDpdkvhost;
45 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.ovsdb.rev150105.InterfaceTypeDpdkvhostuser;
46 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.ovsdb.rev150105.InterfaceTypeDpdkvhostuserclient;
47 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.ovsdb.rev150105.InterfaceTypeGeneve;
48 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.ovsdb.rev150105.InterfaceTypeGre;
49 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.ovsdb.rev150105.InterfaceTypeGre64;
50 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.ovsdb.rev150105.InterfaceTypeInternal;
51 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.ovsdb.rev150105.InterfaceTypeIpsecGre;
52 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.ovsdb.rev150105.InterfaceTypeIpsecGre64;
53 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.ovsdb.rev150105.InterfaceTypeLisp;
54 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.ovsdb.rev150105.InterfaceTypePatch;
55 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.ovsdb.rev150105.InterfaceTypeSystem;
56 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.ovsdb.rev150105.InterfaceTypeTap;
57 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.ovsdb.rev150105.InterfaceTypeVxlan;
58 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.ovsdb.rev150105.InterfaceTypeVxlanGpe;
59 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.ovsdb.rev150105.OvsdbBridgeAugmentation;
60 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.ovsdb.rev150105.OvsdbBridgeAugmentationBuilder;
61 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.ovsdb.rev150105.OvsdbBridgeName;
62 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.ovsdb.rev150105.OvsdbBridgeProtocolBase;
63 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.ovsdb.rev150105.OvsdbBridgeProtocolOpenflow10;
64 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.ovsdb.rev150105.OvsdbBridgeProtocolOpenflow11;
65 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.ovsdb.rev150105.OvsdbBridgeProtocolOpenflow12;
66 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.ovsdb.rev150105.OvsdbBridgeProtocolOpenflow13;
67 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.ovsdb.rev150105.OvsdbBridgeProtocolOpenflow14;
68 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.ovsdb.rev150105.OvsdbBridgeProtocolOpenflow15;
69 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.ovsdb.rev150105.OvsdbFailModeBase;
70 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.ovsdb.rev150105.OvsdbFailModeSecure;
71 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.ovsdb.rev150105.OvsdbFailModeStandalone;
72 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.ovsdb.rev150105.OvsdbNodeAugmentation;
73 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.ovsdb.rev150105.OvsdbNodeAugmentationBuilder;
74 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.ovsdb.rev150105.OvsdbNodeRef;
75 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.ovsdb.rev150105.OvsdbTerminationPointAugmentation;
76 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.ovsdb.rev150105.OvsdbTerminationPointAugmentationBuilder;
77 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.ovsdb.rev150105.ovsdb.bridge.attributes.BridgeExternalIds;
78 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.ovsdb.rev150105.ovsdb.bridge.attributes.BridgeExternalIdsBuilder;
79 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.ovsdb.rev150105.ovsdb.bridge.attributes.BridgeExternalIdsKey;
80 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.ovsdb.rev150105.ovsdb.bridge.attributes.BridgeOtherConfigs;
81 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.ovsdb.rev150105.ovsdb.bridge.attributes.BridgeOtherConfigsBuilder;
82 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.ovsdb.rev150105.ovsdb.bridge.attributes.BridgeOtherConfigsKey;
83 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.ovsdb.rev150105.ovsdb.bridge.attributes.ControllerEntry;
84 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.ovsdb.rev150105.ovsdb.bridge.attributes.ControllerEntryBuilder;
85 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.ovsdb.rev150105.ovsdb.bridge.attributes.ControllerEntryKey;
86 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.ovsdb.rev150105.ovsdb.bridge.attributes.ProtocolEntry;
87 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.ovsdb.rev150105.ovsdb.bridge.attributes.ProtocolEntryBuilder;
88 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.ovsdb.rev150105.ovsdb.bridge.attributes.ProtocolEntryKey;
89 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.ovsdb.rev150105.ovsdb.node.attributes.ConnectionInfo;
90 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.ovsdb.rev150105.ovsdb.node.attributes.ConnectionInfoBuilder;
91 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.ovsdb.rev150105.ovsdb.node.attributes.InterfaceTypeEntry;
92 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.ovsdb.rev150105.ovsdb.node.attributes.InterfaceTypeEntryKey;
93 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.ovsdb.rev150105.ovsdb.node.attributes.ManagedNodeEntry;
94 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.ovsdb.rev150105.ovsdb.node.attributes.ManagedNodeEntryKey;
95 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.ovsdb.rev150105.ovsdb.node.attributes.ManagerEntry;
96 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.ovsdb.rev150105.ovsdb.node.attributes.ManagerEntryKey;
97 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.ovsdb.rev150105.ovsdb.node.attributes.OpenvswitchOtherConfigs;
98 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.ovsdb.rev150105.ovsdb.node.attributes.OpenvswitchOtherConfigsKey;
99 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.ovsdb.rev150105.ovsdb.port._interface.attributes.InterfaceExternalIds;
100 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.ovsdb.rev150105.ovsdb.port._interface.attributes.InterfaceExternalIdsBuilder;
101 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.ovsdb.rev150105.ovsdb.port._interface.attributes.InterfaceExternalIdsKey;
102 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.ovsdb.rev150105.ovsdb.port._interface.attributes.Options;
103 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.ovsdb.rev150105.ovsdb.port._interface.attributes.OptionsBuilder;
104 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.ovsdb.rev150105.ovsdb.port._interface.attributes.OptionsKey;
105 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.NetworkTopology;
106 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.NodeId;
107 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.TopologyId;
108 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.TpId;
109 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.Topology;
110 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.TopologyKey;
111 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.topology.Node;
112 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.topology.NodeBuilder;
113 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.topology.NodeKey;
114 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.topology.node.TerminationPoint;
115 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.topology.node.TerminationPointBuilder;
116 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.topology.node.TerminationPointKey;
117 import org.opendaylight.yangtools.yang.binding.DataObject;
118 import org.opendaylight.yangtools.yang.binding.Identifier;
119 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
120 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier.IdentifiableItem;
121 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier.Item;
122 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier.PathArgument;
123 import org.opendaylight.yangtools.yang.binding.util.BindingMap;
124 import org.opendaylight.yangtools.yang.common.Uint16;
125 import org.opendaylight.yangtools.yang.common.Uint32;
126 import org.slf4j.Logger;
127 import org.slf4j.LoggerFactory;
128
129 public class SouthboundUtils {
130     private abstract static class UtilsProvider {
131
132         abstract <T extends DataObject> T read(LogicalDatastoreType store, InstanceIdentifier<T> path);
133
134         abstract boolean delete(LogicalDatastoreType store, InstanceIdentifier<?> path);
135
136         abstract <T extends DataObject> boolean put(LogicalDatastoreType store, InstanceIdentifier<T> path,
137                 T createNode);
138
139         abstract <T extends DataObject> boolean merge(LogicalDatastoreType store, InstanceIdentifier<T> path, T data);
140     }
141
142     private static final class MdsalUtilsProvider extends UtilsProvider {
143         private final MdsalUtils mdsalUtils;
144
145         MdsalUtilsProvider(final MdsalUtils mdsalUtils) {
146             this.mdsalUtils = requireNonNull(mdsalUtils);
147         }
148
149         @Override
150         <T extends DataObject> T read(LogicalDatastoreType store, InstanceIdentifier<T> path) {
151             return mdsalUtils.read(store, path);
152         }
153
154         @Override
155         <T extends DataObject> boolean put(LogicalDatastoreType store, InstanceIdentifier<T> path, T data) {
156             return mdsalUtils.put(store, path, data);
157         }
158
159         @Override
160         boolean delete(LogicalDatastoreType store, InstanceIdentifier<?> path) {
161             return mdsalUtils.delete(store, path);
162         }
163
164         @Override
165         <T extends DataObject> boolean merge(LogicalDatastoreType store, InstanceIdentifier<T> path, T data) {
166             return mdsalUtils.merge(store, path, data);
167         }
168     }
169
170     private static final Logger LOG = LoggerFactory.getLogger(SouthboundUtils.class);
171     private static final int OVSDB_UPDATE_TIMEOUT = 1000;
172     public static final TopologyId OVSDB_TOPOLOGY_ID = new TopologyId(new Uri("ovsdb:1"));
173     public static final String OPENFLOW_CONNECTION_PROTOCOL = "tcp";
174     public static final String OPENFLOW_SECURE_PROTOCOL = "ssl";
175     public static final short OPENFLOW_PORT = 6653;
176     public static final String OVSDB_URI_PREFIX = "ovsdb";
177     public static final String BRIDGE_URI_PREFIX = "bridge";
178     private static final String DISABLE_IN_BAND = "disable-in-band";
179     private static final String PATCH_PORT_TYPE = "patch";
180     // External ID key used for mapping between an OVSDB port and an interface name
181     private static final InterfaceExternalIdsKey EXTERNAL_INTERFACE_ID_KEY = new InterfaceExternalIdsKey("iface-id");
182     private static final String CREATED_BY = "created_by";
183     private static final String ODL = "odl";
184     private static final String FORMAT = "(\\d+)\\.(\\d+)\\.(\\d+)";
185     private static final Pattern PATTERN = Pattern.compile(FORMAT);
186     // DPDK interface type
187     private static final InterfaceTypeEntryKey DPDK_IFACE_KEY = new InterfaceTypeEntryKey(InterfaceTypeDpdk.VALUE);
188
189     private final UtilsProvider provider;
190
191     public SouthboundUtils(MdsalUtils mdsalUtils) {
192         provider = new MdsalUtilsProvider(mdsalUtils);
193     }
194
195     public static final ImmutableBiMap<String, InterfaceTypeBase> OVSDB_INTERFACE_TYPE_MAP =
196         ImmutableBiMap.<String, InterfaceTypeBase>builder()
197             .put("internal", InterfaceTypeInternal.VALUE)
198             .put("vxlan", InterfaceTypeVxlan.VALUE)
199             .put("vxlan-gpe", InterfaceTypeVxlanGpe.VALUE)
200             .put("patch", InterfaceTypePatch.VALUE)
201             .put("system", InterfaceTypeSystem.VALUE)
202             .put("tap", InterfaceTypeTap.VALUE)
203             .put("geneve", InterfaceTypeGeneve.VALUE)
204             .put("gre", InterfaceTypeGre.VALUE)
205             .put("ipsec_gre", InterfaceTypeIpsecGre.VALUE)
206             .put("gre64", InterfaceTypeGre64.VALUE)
207             .put("ipsec_gre64", InterfaceTypeIpsecGre64.VALUE)
208             .put("lisp", InterfaceTypeLisp.VALUE)
209             .put("dpdk", InterfaceTypeDpdk.VALUE)
210             .put("dpdkr", InterfaceTypeDpdkr.VALUE)
211             .put("dpdkvhost", InterfaceTypeDpdkvhost.VALUE)
212             .put("dpdkvhostuser", InterfaceTypeDpdkvhostuser.VALUE)
213             .put("dpdkvhostuserclient", InterfaceTypeDpdkvhostuserclient.VALUE)
214             .build();
215
216     public static final ImmutableBiMap<OvsdbBridgeProtocolBase, String> OVSDB_PROTOCOL_MAP =
217         ImmutableBiMap.<OvsdbBridgeProtocolBase, String>builder()
218             .put(OvsdbBridgeProtocolOpenflow10.VALUE, "OpenFlow10")
219             .put(OvsdbBridgeProtocolOpenflow11.VALUE, "OpenFlow11")
220             .put(OvsdbBridgeProtocolOpenflow12.VALUE, "OpenFlow12")
221             .put(OvsdbBridgeProtocolOpenflow13.VALUE, "OpenFlow13")
222             .put(OvsdbBridgeProtocolOpenflow14.VALUE, "OpenFlow14")
223             .put(OvsdbBridgeProtocolOpenflow15.VALUE, "OpenFlow15")
224             .build();
225
226     private static final ImmutableBiMap<OvsdbFailModeBase, String> OVSDB_FAIL_MODE_MAP =
227         ImmutableBiMap.<OvsdbFailModeBase, String>builder()
228             .put(OvsdbFailModeStandalone.VALUE, "standalone")
229             .put(OvsdbFailModeSecure.VALUE, "secure")
230             .build();
231
232     private static final BridgeOtherConfigs OTHER_CONFIG_DISABLE_INBAND = new BridgeOtherConfigsBuilder()
233                 .setBridgeOtherConfigKey(DISABLE_IN_BAND)
234                 .setBridgeOtherConfigValue("true")
235                 .build();
236     private static final Map<BridgeOtherConfigsKey, BridgeOtherConfigs> DEFAULT_OTHER_CONFIGS =
237         BindingMap.of(OTHER_CONFIG_DISABLE_INBAND);
238
239     public static NodeId createNodeId(IpAddress ip, PortNumber port) {
240         String uriString = OVSDB_URI_PREFIX + "://" + ip.stringValue() + ":" + port.getValue();
241         Uri uri = new Uri(uriString);
242         return new NodeId(uri);
243     }
244
245     public static Node createNode(ConnectionInfo key) {
246         return new NodeBuilder()
247                 .setNodeId(createNodeId(key.getRemoteIp(), key.getRemotePort()))
248                 .addAugmentation(createOvsdbAugmentation(key))
249                 .build();
250     }
251
252     public static OvsdbNodeAugmentation createOvsdbAugmentation(ConnectionInfo key) {
253         return new OvsdbNodeAugmentationBuilder().setConnectionInfo(key).build();
254     }
255
256     public static InstanceIdentifier<Node> createInstanceIdentifier(NodeId nodeId) {
257         return InstanceIdentifier
258                 .create(NetworkTopology.class)
259                 .child(Topology.class, new TopologyKey(OVSDB_TOPOLOGY_ID))
260                 .child(Node.class,new NodeKey(nodeId));
261     }
262
263     public static InstanceIdentifier<Node> createInstanceIdentifier(NodeKey ovsdbNodeKey, String bridgeName) {
264         return createInstanceIdentifier(createManagedNodeId(ovsdbNodeKey.getNodeId(), bridgeName));
265     }
266
267     public static InstanceIdentifier<Node> createInstanceIdentifier(ConnectionInfo key) {
268         return createInstanceIdentifier(key.getRemoteIp(), key.getRemotePort());
269     }
270
271     public static InstanceIdentifier<Node> createInstanceIdentifier(IpAddress ip, PortNumber port) {
272         InstanceIdentifier<Node> path = InstanceIdentifier
273                 .create(NetworkTopology.class)
274                 .child(Topology.class, new TopologyKey(OVSDB_TOPOLOGY_ID))
275                 .child(Node.class,createNodeKey(ip,port));
276         LOG.debug("Created ovsdb path: {}",path);
277         return path;
278     }
279
280     public static InstanceIdentifier<Node> createInstanceIdentifier(ConnectionInfo key, OvsdbBridgeName bridgeName) {
281         return createInstanceIdentifier(createManagedNodeId(key, bridgeName));
282     }
283
284     public static InstanceIdentifier<Node> createInstanceIdentifier(ConnectionInfo key, String bridgeName) {
285         return createInstanceIdentifier(key, new OvsdbBridgeName(bridgeName));
286     }
287
288     public InstanceIdentifier<TerminationPoint> createTerminationPointInstanceIdentifier(Node node, String portName) {
289
290         InstanceIdentifier<TerminationPoint> terminationPointPath = InstanceIdentifier
291                 .create(NetworkTopology.class)
292                 .child(Topology.class, new TopologyKey(OVSDB_TOPOLOGY_ID))
293                 .child(Node.class,node.key())
294                 .child(TerminationPoint.class, new TerminationPointKey(new TpId(portName)));
295
296         LOG.debug("Termination point InstanceIdentifier generated : {}",terminationPointPath);
297         return terminationPointPath;
298     }
299
300     public static NodeKey createNodeKey(IpAddress ip, PortNumber port) {
301         return new NodeKey(createNodeId(ip, port));
302     }
303
304     public static NodeId createManagedNodeId(NodeId ovsdbNodeId, String bridgeName) {
305         return new NodeId(ovsdbNodeId.getValue()
306                 + "/" + BRIDGE_URI_PREFIX + "/" + bridgeName);
307     }
308
309     public static NodeId createManagedNodeId(ConnectionInfo key, OvsdbBridgeName bridgeName) {
310         return createManagedNodeId(key.getRemoteIp(), key.getRemotePort(), bridgeName);
311     }
312
313     public static NodeId createManagedNodeId(IpAddress ip, PortNumber port, OvsdbBridgeName bridgeName) {
314         return new NodeId(createNodeId(ip,port).getValue()
315                 + "/" + BRIDGE_URI_PREFIX + "/" + bridgeName.getValue());
316     }
317
318     public static NodeId createManagedNodeId(InstanceIdentifier<Node> iid) {
319         NodeKey nodeKey = iid.firstKeyOf(Node.class);
320         return nodeKey.getNodeId();
321     }
322
323     public OvsdbNodeAugmentation extractOvsdbNode(Node node) {
324         return node.augmentation(OvsdbNodeAugmentation.class);
325     }
326
327     public static IpAddress createIpAddress(InetAddress address) {
328         IpAddress ip = null;
329         if (address instanceof Inet4Address) {
330             ip = createIpAddress((Inet4Address)address);
331         } else if (address instanceof Inet6Address) {
332             ip = createIpAddress((Inet6Address)address);
333         }
334         return ip;
335     }
336
337     public static IpAddress createIpAddress(Inet4Address address) {
338         return IetfInetUtil.INSTANCE.ipAddressFor(address);
339     }
340
341     public static IpAddress createIpAddress(Inet6Address address) {
342         Ipv6Address ipv6 = new Ipv6Address(address.getHostAddress());
343         return new IpAddress(ipv6);
344     }
345
346     public ConnectionInfo getConnectionInfo(Node ovsdbNode) {
347         ConnectionInfo connectionInfo = null;
348         OvsdbNodeAugmentation ovsdbNodeAugmentation = extractOvsdbNode(ovsdbNode);
349         if (ovsdbNodeAugmentation != null) {
350             connectionInfo = ovsdbNodeAugmentation.getConnectionInfo();
351         }
352         return connectionInfo;
353     }
354
355     public static ConnectionInfo getConnectionInfo(final String addressStr, final String portStr) {
356         InetAddress inetAddress = null;
357         try {
358             inetAddress = InetAddress.getByName(addressStr);
359         } catch (UnknownHostException e) {
360             LOG.warn("Could not allocate InetAddress", e);
361         }
362
363         IpAddress address = createIpAddress(inetAddress);
364         PortNumber port = new PortNumber(Uint16.valueOf(portStr));
365
366         LOG.info("connectionInfo: {}", new ConnectionInfoBuilder()
367                 .setRemoteIp(address)
368                 .setRemotePort(port)
369                 .build());
370         return new ConnectionInfoBuilder()
371                 .setRemoteIp(address)
372                 .setRemotePort(port)
373                 .build();
374     }
375
376     public static String connectionInfoToString(final ConnectionInfo connectionInfo) {
377         return connectionInfo.getRemoteIp().stringValue() + ":" + connectionInfo.getRemotePort().getValue();
378     }
379
380     public boolean addOvsdbNode(final ConnectionInfo connectionInfo) {
381         return addOvsdbNode(connectionInfo, OVSDB_UPDATE_TIMEOUT);
382     }
383
384     public boolean addOvsdbNode(final ConnectionInfo connectionInfo, long timeout) {
385         boolean result = provider.put(LogicalDatastoreType.CONFIGURATION,
386                 createInstanceIdentifier(connectionInfo),
387                 createNode(connectionInfo));
388         if (timeout != 0) {
389             try {
390                 Thread.sleep(timeout);
391             } catch (InterruptedException e) {
392                 LOG.warn("Interrupted while waiting after adding OVSDB node {}",
393                         connectionInfoToString(connectionInfo), e);
394             }
395         }
396         return result;
397     }
398
399     public Node getOvsdbNode(final ConnectionInfo connectionInfo) {
400         return provider.read(LogicalDatastoreType.OPERATIONAL,
401                 createInstanceIdentifier(connectionInfo));
402     }
403
404     public boolean deleteOvsdbNode(final ConnectionInfo connectionInfo) {
405         return deleteOvsdbNode(connectionInfo, OVSDB_UPDATE_TIMEOUT);
406     }
407
408     public boolean deleteOvsdbNode(final ConnectionInfo connectionInfo, long timeout) {
409         boolean result = provider.delete(LogicalDatastoreType.CONFIGURATION,
410                 createInstanceIdentifier(connectionInfo));
411         if (timeout != 0) {
412             try {
413                 Thread.sleep(timeout);
414             } catch (InterruptedException e) {
415                 LOG.warn("Interrupted while waiting after deleting OVSDB node {}",
416                         connectionInfoToString(connectionInfo), e);
417             }
418         }
419         return result;
420     }
421
422     public Node connectOvsdbNode(final ConnectionInfo connectionInfo) {
423         return connectOvsdbNode(connectionInfo, OVSDB_UPDATE_TIMEOUT);
424     }
425
426     public Node connectOvsdbNode(final ConnectionInfo connectionInfo, long timeout) {
427         addOvsdbNode(connectionInfo, timeout);
428         Node node = getOvsdbNode(connectionInfo);
429         LOG.info("Connected to {}", connectionInfoToString(connectionInfo));
430         return node;
431     }
432
433     public boolean disconnectOvsdbNode(final ConnectionInfo connectionInfo) {
434         return disconnectOvsdbNode(connectionInfo, OVSDB_UPDATE_TIMEOUT);
435     }
436
437     public boolean disconnectOvsdbNode(final ConnectionInfo connectionInfo, long timeout) {
438         deleteOvsdbNode(connectionInfo, timeout);
439         LOG.info("Disconnected from {}", connectionInfoToString(connectionInfo));
440         return true;
441     }
442
443     public List<ControllerEntry> createControllerEntry(String controllerTarget) {
444         List<ControllerEntry> controllerEntriesList = new ArrayList<>();
445         controllerEntriesList.add(new ControllerEntryBuilder()
446                 .setTarget(new Uri(controllerTarget))
447                 .build());
448         return controllerEntriesList;
449     }
450
451     /**
452      * Extract the <code>store</code> type data store contents for the particular bridge identified by
453      * <code>bridgeName</code>.
454      *
455      * @param connectionInfo address for the node
456      * @param bridgeName name of the bridge
457      * @param store defined by the <code>LogicalDatastoreType</code> enumeration
458      * @return <code>store</code> type data store contents
459      */
460     public OvsdbBridgeAugmentation getBridge(ConnectionInfo connectionInfo, String bridgeName,
461                                               LogicalDatastoreType store) {
462         OvsdbBridgeAugmentation ovsdbBridgeAugmentation = null;
463         Node bridgeNode = getBridgeNode(connectionInfo, bridgeName, store);
464         if (bridgeNode != null) {
465             ovsdbBridgeAugmentation = bridgeNode.augmentation(OvsdbBridgeAugmentation.class);
466         }
467         return ovsdbBridgeAugmentation;
468     }
469
470     /**
471      * Extract the <code>LogicalDataStoreType.OPERATIONAL</code> type data store contents for the particular bridge
472      * identified by <code>bridgeName</code>.
473      *
474      * @param connectionInfo address for the node
475      * @param bridgeName name of the bridge
476      * @see <code>NetvirtIT.getBridge(ConnectionInfo, String, LogicalDatastoreType)</code>
477      * @return <code>LogicalDatastoreType.OPERATIONAL</code> type data store contents
478      */
479     public OvsdbBridgeAugmentation getBridge(ConnectionInfo connectionInfo, String bridgeName) {
480         return getBridge(connectionInfo, bridgeName, LogicalDatastoreType.OPERATIONAL);
481     }
482
483     /**
484      * Extract the node contents from <code>store</code> type data store for the
485      * bridge identified by <code>bridgeName</code>.
486      *
487      * @param connectionInfo address for the node
488      * @param bridgeName name of the bridge
489      * @param store defined by the <code>LogicalDatastoreType</code> enumeration
490      * @return <code>store</code> type data store contents
491      */
492     public Node getBridgeNode(ConnectionInfo connectionInfo, String bridgeName, LogicalDatastoreType store) {
493         InstanceIdentifier<Node> bridgeIid = createInstanceIdentifier(connectionInfo, new OvsdbBridgeName(bridgeName));
494         return provider.read(store, bridgeIid);
495     }
496
497     public Node getBridgeNode(Node node, String bridgeName) {
498         OvsdbBridgeAugmentation bridge = extractBridgeAugmentation(node);
499         if (bridge != null && bridge.getBridgeName().getValue().equals(bridgeName)) {
500             return node;
501         } else {
502             return readBridgeNode(node, bridgeName);
503         }
504     }
505
506     public Node readBridgeNode(Node node, String name) {
507         Node ovsdbNode = node;
508         if (extractNodeAugmentation(ovsdbNode) == null) {
509             ovsdbNode = readOvsdbNode(node);
510             if (ovsdbNode == null) {
511                 return null;
512             }
513         }
514         Node bridgeNode = null;
515         ConnectionInfo connectionInfo = getConnectionInfo(ovsdbNode);
516         if (connectionInfo != null) {
517             InstanceIdentifier<Node> bridgeIid =
518                     createInstanceIdentifier(node.key(), name);
519             bridgeNode = provider.read(LogicalDatastoreType.OPERATIONAL, bridgeIid);
520         }
521         return bridgeNode;
522     }
523
524     public OvsdbNodeAugmentation extractNodeAugmentation(Node node) {
525         return node.augmentation(OvsdbNodeAugmentation.class);
526     }
527
528     public OvsdbBridgeAugmentation extractBridgeAugmentation(Node node) {
529         if (node == null) {
530             return null;
531         }
532         return node.augmentation(OvsdbBridgeAugmentation.class);
533     }
534
535     public Node readOvsdbNode(Node bridgeNode) {
536         Node ovsdbNode = null;
537         OvsdbBridgeAugmentation bridgeAugmentation = extractBridgeAugmentation(bridgeNode);
538         if (bridgeAugmentation != null) {
539             InstanceIdentifier<Node> ovsdbNodeIid =
540                     (InstanceIdentifier<Node>) bridgeAugmentation.getManagedBy().getValue();
541             ovsdbNode = provider.read(LogicalDatastoreType.OPERATIONAL, ovsdbNodeIid);
542         } else {
543             LOG.debug("readOvsdbNode: Provided node is not a bridge node : {}",bridgeNode);
544         }
545         return ovsdbNode;
546     }
547
548     public boolean deleteBridge(final ConnectionInfo connectionInfo, final String bridgeName) {
549         return deleteBridge(connectionInfo, bridgeName, OVSDB_UPDATE_TIMEOUT);
550     }
551
552     public boolean deleteBridge(final ConnectionInfo connectionInfo, final String bridgeName, long timeout) {
553         boolean result = provider.delete(LogicalDatastoreType.CONFIGURATION,
554                 createInstanceIdentifier(connectionInfo, new OvsdbBridgeName(bridgeName)));
555         if (timeout != 0) {
556             try {
557                 Thread.sleep(timeout);
558             } catch (InterruptedException e) {
559                 LOG.warn("Interrupted while waiting after deleting bridge {}", bridgeName, e);
560             }
561         }
562         return result;
563     }
564
565     public Map<ProtocolEntryKey, ProtocolEntry> createMdsalProtocols() {
566         final ProtocolEntry entry = new ProtocolEntryBuilder()
567                 .setProtocol(OVSDB_PROTOCOL_MAP.inverse().get("OpenFlow13"))
568                 .build();
569         return Map.of(entry.key(), entry);
570     }
571
572     /*
573      * base method for adding test bridges.  Other helper methods used to create bridges should utilize this method.
574      *
575      * @param connectionInfo
576      * @param bridgeIid if passed null, one is created
577      * @param bridgeName cannot be null
578      * @param bridgeNodeId if passed null, one is created based on <code>bridgeIid</code>
579      * @param setProtocolEntries toggles whether default protocol entries are set for the bridge
580      * @param failMode toggles whether default fail mode is set for the bridge
581      * @param setManagedBy toggles whether to setManagedBy for the bridge
582      * @param dpType if passed null, this parameter is ignored
583      * @param externalIds if passed null, this parameter is ignored
584      * @param otherConfig if passed null, this parameter is ignored
585      * @return success of bridge addition
586      * @throws InterruptedException
587      */
588     public boolean addBridge(final ConnectionInfo connectionInfo, InstanceIdentifier<Node> bridgeIid,
589                              final String bridgeName, NodeId bridgeNodeId, final boolean setProtocolEntries,
590                              final OvsdbFailModeBase failMode, final boolean setManagedBy,
591                              final DatapathTypeBase dpType,
592                              final Map<BridgeExternalIdsKey, BridgeExternalIds> externalIds,
593                              final Map<ControllerEntryKey, ControllerEntry> controllerEntries,
594                              final Map<BridgeOtherConfigsKey, BridgeOtherConfigs> otherConfigs,
595                              final String dpid, long timeout) throws InterruptedException {
596
597         NodeBuilder bridgeNodeBuilder = new NodeBuilder();
598         if (bridgeIid == null) {
599             bridgeIid = createInstanceIdentifier(connectionInfo, new OvsdbBridgeName(bridgeName));
600         }
601         if (bridgeNodeId == null) {
602             bridgeNodeId = createManagedNodeId(bridgeIid);
603         }
604         bridgeNodeBuilder.setNodeId(bridgeNodeId);
605         OvsdbBridgeAugmentationBuilder ovsdbBridgeAugmentationBuilder = new OvsdbBridgeAugmentationBuilder();
606         ovsdbBridgeAugmentationBuilder.setBridgeName(new OvsdbBridgeName(bridgeName));
607         if (setProtocolEntries) {
608             ovsdbBridgeAugmentationBuilder.setProtocolEntry(createMdsalProtocols());
609         }
610         if (failMode != null) {
611             ovsdbBridgeAugmentationBuilder.setFailMode(failMode);
612         }
613         if (setManagedBy) {
614             setManagedBy(ovsdbBridgeAugmentationBuilder, connectionInfo);
615         }
616         if (dpType != null) {
617             ovsdbBridgeAugmentationBuilder.setDatapathType(dpType);
618         }
619         if (externalIds != null) {
620             ovsdbBridgeAugmentationBuilder.setBridgeExternalIds(externalIds);
621         }
622         if (controllerEntries != null) {
623             ovsdbBridgeAugmentationBuilder.setControllerEntry(controllerEntries);
624         }
625         if (otherConfigs != null) {
626             ovsdbBridgeAugmentationBuilder.setBridgeOtherConfigs(otherConfigs);
627         }
628         if (dpid != null && !dpid.isEmpty()) {
629             DatapathId datapathId = new DatapathId(dpid);
630             ovsdbBridgeAugmentationBuilder.setDatapathId(datapathId);
631         }
632         bridgeNodeBuilder.addAugmentation(ovsdbBridgeAugmentationBuilder.build());
633         LOG.debug("Built with the intent to store bridge data {}",
634                 ovsdbBridgeAugmentationBuilder.toString());
635         boolean result = provider.merge(LogicalDatastoreType.CONFIGURATION,
636                 bridgeIid, bridgeNodeBuilder.build());
637         if (timeout != 0) {
638             Thread.sleep(OVSDB_UPDATE_TIMEOUT);
639         }
640         return result;
641     }
642
643     public boolean addBridge(Node ovsdbNode, String bridgeName, List<String> controllersStr, DatapathTypeBase dpType,
644             String mac) {
645         return addBridge(ovsdbNode, bridgeName, controllersStr, dpType, mac, null, null);
646     }
647
648     public boolean addBridge(Node ovsdbNode, String bridgeName, List<String> controllersStr, DatapathTypeBase dpType,
649                              String mac, Long maxBackoff, Long inactivityProbe) {
650         List<BridgeOtherConfigs> otherConfigs = new ArrayList<>();
651         if (mac != null) {
652             otherConfigs.add(new BridgeOtherConfigsBuilder()
653                 .setBridgeOtherConfigKey("hwaddr")
654                 .setBridgeOtherConfigValue(mac).build());
655         }
656
657         return addBridge(ovsdbNode, bridgeName, controllersStr, dpType, otherConfigs, null, null);
658     }
659
660     public boolean addBridge(Node ovsdbNode, String bridgeName, List<String> controllersStr, DatapathTypeBase dpType,
661             List<BridgeOtherConfigs> otherConfigs, Uint32 maxBackoff, Uint32 inactivityProbe) {
662         LOG.info("addBridge: node: {}, bridgeName: {}, controller(s): {}", ovsdbNode, bridgeName, controllersStr);
663         ConnectionInfo connectionInfo = getConnectionInfo(ovsdbNode);
664         if (connectionInfo == null) {
665             throw new InvalidParameterException("Could not find ConnectionInfo");
666         }
667
668         OvsdbBridgeAugmentationBuilder ovsdbBridgeAugmentationBuilder = new OvsdbBridgeAugmentationBuilder()
669             .setControllerEntry(createControllerEntries(controllersStr, maxBackoff, inactivityProbe))
670             .setBridgeName(new OvsdbBridgeName(bridgeName))
671             .setProtocolEntry(createMdsalProtocols())
672             .setFailMode(OVSDB_FAIL_MODE_MAP.inverse().get("secure"))
673             .setBridgeExternalIds(setBridgeExternalIds())
674             .setManagedBy(new OvsdbNodeRef(createInstanceIdentifier(ovsdbNode.key().getNodeId())))
675             // TODO: Currently netvirt relies on this function to set disabled-in-band=true. However,
676             // TODO (cont): a better design would be to have netvirt pass that in. That way this function
677             // TODO (cont): can take a null otherConfigs to erase other_configs.
678             .setBridgeOtherConfigs(disableInBand(otherConfigs));
679
680
681         if (dpType != null) {
682             ovsdbBridgeAugmentationBuilder.setDatapathType(dpType);
683         }
684         if (isOvsdbNodeDpdk(ovsdbNode)) {
685             ovsdbBridgeAugmentationBuilder.setDatapathType(DatapathTypeNetdev.VALUE);
686         }
687
688         InstanceIdentifier<Node> bridgeIid = createInstanceIdentifier(ovsdbNode.key(), bridgeName);
689         Node node = new NodeBuilder()
690             .addAugmentation(ovsdbBridgeAugmentationBuilder.build())
691             .setNodeId(createManagedNodeId(bridgeIid))
692             .build();
693         boolean result = provider.put(LogicalDatastoreType.CONFIGURATION, bridgeIid, node);
694         LOG.info("addBridge: result: {}", result);
695         return result;
696     }
697
698     private static Map<BridgeOtherConfigsKey, BridgeOtherConfigs> disableInBand(List<BridgeOtherConfigs> otherConfigs) {
699         return otherConfigs == null || otherConfigs.isEmpty() ? DEFAULT_OTHER_CONFIGS
700             : BindingMap.<BridgeOtherConfigsKey, BridgeOtherConfigs>orderedBuilder(otherConfigs.size() + 1)
701                 .addAll(otherConfigs)
702                 .add(OTHER_CONFIG_DISABLE_INBAND)
703                 .build();
704     }
705
706     /**
707      * Set the controllers of an existing bridge node.
708      *
709      * @param ovsdbNode where the bridge is
710      * @param bridgeName Name of the bridge
711      * @param controllers controller strings
712      * @return success if the write to md-sal was successful
713      */
714     public boolean setBridgeController(Node ovsdbNode, String bridgeName, List<String> controllers) {
715         return setBridgeController(ovsdbNode, bridgeName, controllers, null, null);
716     }
717
718     /**
719      * Set the controllers of an existing bridge node.
720      *
721      * @param ovsdbNode where the bridge is
722      * @param bridgeName Name of the bridge
723      * @param controllers controller strings
724      * @param maxBackoff Max backoff in milliseconds
725      * @param inactivityProbe inactivity probe in milliseconds
726      * @return success if the write to md-sal was successful
727      */
728     public boolean setBridgeController(Node ovsdbNode, String bridgeName, List<String> controllers,
729             Uint32 maxBackoff, Uint32 inactivityProbe) {
730         LOG.debug("setBridgeController: ovsdbNode: {}, bridgeNode: {}, controller(s): {}",
731                 ovsdbNode, bridgeName, controllers);
732
733         InstanceIdentifier<Node> bridgeNodeIid = createInstanceIdentifier(ovsdbNode.key(), bridgeName);
734         Node bridgeNode = provider.read(LogicalDatastoreType.CONFIGURATION, bridgeNodeIid);
735         if (bridgeNode == null) {
736             LOG.info("setBridgeController could not find bridge in configuration {}", bridgeNodeIid);
737             return false;
738         }
739
740         OvsdbBridgeAugmentation bridgeAug = extractBridgeAugmentation(bridgeNode);
741
742         Map<ControllerEntryKey, ControllerEntry> currentControllerEntries =
743             createControllerEntries(controllers, maxBackoff, inactivityProbe);
744
745         final Map<ControllerEntryKey, ControllerEntry> newControllerEntries;
746         // Only add controller entries that do not already exist on this bridge
747         Map<ControllerEntryKey, ControllerEntry> existingControllerEntries = bridgeAug.getControllerEntry();
748         if (existingControllerEntries != null) {
749             newControllerEntries = currentControllerEntries.values().stream()
750                 .filter(entry -> !existingControllerEntries.containsKey(new ControllerEntryKey(entry.getTarget())))
751                 .collect(BindingMap.toOrderedMap());
752         } else {
753             newControllerEntries = currentControllerEntries;
754         }
755
756         if (newControllerEntries.isEmpty()) {
757             return true;
758         }
759
760         InstanceIdentifier<Node> bridgeIid = createInstanceIdentifier(ovsdbNode.key(), bridgeName);
761         return provider.merge(LogicalDatastoreType.CONFIGURATION, bridgeIid, new NodeBuilder(bridgeNode)
762             .addAugmentation(new OvsdbBridgeAugmentationBuilder(bridgeAug)
763                 .setControllerEntry(newControllerEntries)
764                 .build())
765             .build());
766     }
767
768     private static void setManagedBy(final OvsdbBridgeAugmentationBuilder ovsdbBridgeAugmentationBuilder,
769                               final ConnectionInfo connectionInfo) {
770         InstanceIdentifier<Node> connectionNodePath = createInstanceIdentifier(connectionInfo);
771         ovsdbBridgeAugmentationBuilder.setManagedBy(new OvsdbNodeRef(connectionNodePath));
772     }
773
774     public boolean addTerminationPoint(
775             Node bridgeNode, String portName, String type, Map<String, String> options,
776             Map<String, String> externalIds) {
777         return addTerminationPoint(bridgeNode, portName, type, options, externalIds, null);
778     }
779
780     public boolean addTerminationPoint(
781             Node bridgeNode, String portName, String type, Map<String, String> options, Map<String, String> externalIds,
782             Uint32 ofPort) {
783         OvsdbTerminationPointAugmentationBuilder tpAugmentationBuilder = new OvsdbTerminationPointAugmentationBuilder();
784
785         tpAugmentationBuilder.setName(portName);
786         tpAugmentationBuilder.setOfport(ofPort);
787         if (type != null) {
788             tpAugmentationBuilder.setInterfaceType(OVSDB_INTERFACE_TYPE_MAP.get(type));
789         }
790
791         if (options != null && options.size() > 0) {
792             tpAugmentationBuilder.setOptions(buildOptions(options));
793         }
794
795         if (externalIds != null && externalIds.size() > 0) {
796             final ImmutableMap.Builder<InterfaceExternalIdsKey, InterfaceExternalIds> builder =
797                     ImmutableMap.builderWithExpectedSize(externalIds.size());
798             for (Map.Entry<String, String> entry : externalIds.entrySet()) {
799                 final InterfaceExternalIdsKey key = new InterfaceExternalIdsKey(entry.getKey());
800                 builder.put(key, new InterfaceExternalIdsBuilder()
801                     .withKey(key)
802                     .setExternalIdValue(entry.getValue())
803                     .build());
804             }
805             tpAugmentationBuilder.setInterfaceExternalIds(builder.build());
806         }
807
808         InstanceIdentifier<TerminationPoint> tpIid = createTerminationPointInstanceIdentifier(bridgeNode, portName);
809         return provider.merge(LogicalDatastoreType.CONFIGURATION, tpIid, new TerminationPointBuilder()
810             .withKey(InstanceIdentifier.keyOf(tpIid))
811             .addAugmentation(tpAugmentationBuilder.build())
812             .build());
813     }
814
815     public Boolean addTerminationPoint(Node bridgeNode, String portName, String type) {
816         return addTerminationPoint(bridgeNode, portName, type, Collections.emptyMap(), null);
817     }
818
819     public Boolean addTerminationPoint(Node bridgeNode, String bridgeName, String portName,
820                                        String type, Map<String, String> options) {
821         OvsdbTerminationPointAugmentationBuilder tpAugmentationBuilder = new OvsdbTerminationPointAugmentationBuilder();
822
823         tpAugmentationBuilder.setName(portName);
824         if (type != null) {
825             tpAugmentationBuilder.setInterfaceType(OVSDB_INTERFACE_TYPE_MAP.get(type));
826         }
827
828         tpAugmentationBuilder.setOptions(buildOptions(options));
829
830         InstanceIdentifier<TerminationPoint> tpIid = createTerminationPointInstanceIdentifier(bridgeNode, portName);
831         return provider.merge(LogicalDatastoreType.CONFIGURATION, tpIid, new TerminationPointBuilder()
832             .withKey(InstanceIdentifier.keyOf(tpIid))
833             .addAugmentation(tpAugmentationBuilder.build())
834             .build());
835     }
836
837     public Boolean addTerminationPoint(Node bridgeNode, String bridgeName, String portName, String type) {
838         InstanceIdentifier<TerminationPoint> tpIid = createTerminationPointInstanceIdentifier(bridgeNode, portName);
839         OvsdbTerminationPointAugmentationBuilder tpAugmentationBuilder =
840                 new OvsdbTerminationPointAugmentationBuilder();
841
842         tpAugmentationBuilder.setName(portName);
843         if (type != null) {
844             tpAugmentationBuilder.setInterfaceType(OVSDB_INTERFACE_TYPE_MAP.get(type));
845         }
846         return provider.merge(LogicalDatastoreType.CONFIGURATION, tpIid, new TerminationPointBuilder()
847             .withKey(InstanceIdentifier.keyOf(tpIid))
848             .addAugmentation(tpAugmentationBuilder.build())
849             .build());
850     }
851
852     public Boolean addPatchTerminationPoint(Node node, String bridgeName, String portName, String peerPortName) {
853         Map<String, String> option = new HashMap<>();
854         option.put("peer", peerPortName);
855         return addTerminationPoint(node, bridgeName, portName, PATCH_PORT_TYPE, option);
856     }
857
858     private String getControllerIPAddress() {
859         String addressString = ConfigProperties.getProperty(this.getClass(), "ovsdb.controller.address");
860         if (addressString != null) {
861             try {
862                 if (InetAddress.getByName(addressString) != null) {
863                     return addressString;
864                 }
865             } catch (UnknownHostException e) {
866                 LOG.error("Host {} is invalid", addressString, e);
867             }
868         }
869
870         addressString = ConfigProperties.getProperty(this.getClass(), "of.address");
871         if (addressString != null) {
872             try {
873                 if (InetAddress.getByName(addressString) != null) {
874                     return addressString;
875                 }
876             } catch (UnknownHostException e) {
877                 LOG.error("Host {} is invalid", addressString, e);
878             }
879         }
880
881         return null;
882     }
883
884     private short getControllerOFPort() {
885         short openFlowPort = OPENFLOW_PORT;
886         String portString = ConfigProperties.getProperty(this.getClass(), "of.listenPort");
887         if (portString != null) {
888             try {
889                 openFlowPort = Short.parseShort(portString);
890             } catch (NumberFormatException e) {
891                 LOG.warn("Invalid port:{}, use default({})", portString, openFlowPort, e);
892             }
893         }
894         return openFlowPort;
895     }
896
897     public List<String> getControllersFromOvsdbNode(Node node) {
898         List<String> controllersStr = new ArrayList<>();
899
900         String controllerIpStr = getControllerIPAddress();
901         if (controllerIpStr != null) {
902             // If codepath makes it here, the ip address to be used was explicitly provided.
903             // Being so, also fetch openflowPort provided via ConfigProperties.
904             controllersStr.add(OPENFLOW_CONNECTION_PROTOCOL
905                     + ":" + controllerIpStr + ":" + getControllerOFPort());
906         } else {
907             // Check if ovsdb node has manager entries
908             OvsdbNodeAugmentation ovsdbNodeAugmentation = extractOvsdbNode(node);
909             if (ovsdbNodeAugmentation != null) {
910                 Map<ManagerEntryKey, ManagerEntry> managerEntries = ovsdbNodeAugmentation.getManagerEntry();
911                 if (managerEntries != null && !managerEntries.isEmpty()) {
912                     for (ManagerEntry managerEntry : managerEntries.values()) {
913                         if (managerEntry == null || managerEntry.getTarget() == null) {
914                             continue;
915                         }
916                         String managerStr = managerEntry.getTarget().getValue().toLowerCase(Locale.ROOT);
917                         int firstColonIdx = managerStr.indexOf(':');
918                         int lastColonIdx = managerStr.lastIndexOf(':');
919                         if (lastColonIdx <= firstColonIdx) {
920                             continue;
921                         }
922                         controllerIpStr = managerStr.substring(firstColonIdx + 1, lastColonIdx);
923                         if (managerStr.startsWith("tcp")) {
924                             controllersStr.add(OPENFLOW_CONNECTION_PROTOCOL + ":" + controllerIpStr + ":"
925                                 + getControllerOFPort());
926                         } else if (managerStr.startsWith("ssl")) {
927                             controllersStr.add(OPENFLOW_SECURE_PROTOCOL + ":" + controllerIpStr + ":"
928                                 + getControllerOFPort());
929                         } else if (managerStr.startsWith("ptcp")) {
930                             ConnectionInfo connectionInfo = ovsdbNodeAugmentation.getConnectionInfo();
931                             /* If we're connected to switch ptcp, only then use connection info
932                                 to configure controller. Ptcp is configured as:
933                                 Manager "ptcp:<port>:<ip>"
934                                 ip is optional
935                              */
936                             String managerPortStr =  managerStr.split(":", 3)[1];
937                             if (connectionInfo != null && connectionInfo.getLocalIp() != null
938                                     && connectionInfo.getRemotePort() != null
939                                     && managerPortStr.equals(connectionInfo.getRemotePort().toString())) {
940                                 IpAddress controllerIp = connectionInfo.getLocalIp();
941                                 if (controllerIp.getIpv6Address() != null) {
942                                     controllerIpStr = "[" + connectionInfo.getLocalIp().stringValue() + "]";
943                                 } else {
944                                     controllerIpStr = connectionInfo.getLocalIp().stringValue();
945                                 }
946                                 controllersStr.add(OPENFLOW_CONNECTION_PROTOCOL
947                                     + ":" + controllerIpStr + ":" + OPENFLOW_PORT);
948                             } else {
949                                 LOG.warn("Ovsdb Node does not contain connection info: {}", node);
950                             }
951                         } else if (managerStr.startsWith("pssl")) {
952                             ConnectionInfo connectionInfo = ovsdbNodeAugmentation.getConnectionInfo();
953                             if (connectionInfo != null && connectionInfo.getLocalIp() != null) {
954                                 controllerIpStr = connectionInfo.getLocalIp().stringValue();
955                                 controllersStr.add(OPENFLOW_SECURE_PROTOCOL
956                                     + ":" + controllerIpStr + ":" + OPENFLOW_PORT);
957                             } else {
958                                 LOG.warn("Ovsdb Node does not contain connection info: {}", node);
959                             }
960                         } else {
961                             LOG.trace("Skipping manager entry {} for node {}",
962                                     managerEntry.getTarget(), node.getNodeId().getValue());
963                         }
964                     }
965                 } else {
966                     LOG.warn("Ovsdb Node does not contain manager entries : {}", node);
967                 }
968             }
969         }
970
971         if (controllersStr.isEmpty()) {
972             LOG.warn("Failed to determine OpenFlow controller ip address");
973         } else if (LOG.isDebugEnabled()) {
974             LOG.debug("Found {} OpenFlow Controller(s) :{}", controllersStr.size(),
975                     controllersStr.stream().collect(Collectors.joining(" ")));
976         }
977         return controllersStr;
978     }
979
980     public long getDataPathId(Node node) {
981         long dpid = 0L;
982         String datapathId = getDatapathId(node);
983         if (datapathId != null) {
984             dpid = new BigInteger(datapathId.replace(":", ""), 16).longValue();
985         }
986         return dpid;
987     }
988
989     public String getDataPathIdStr(final Node node) {
990         if (node != null) {
991             long dpId = getDataPathId(node);
992             if (dpId != 0) {
993                 return String.valueOf(dpId);
994             }
995         }
996
997         return null;
998     }
999
1000     public String getDatapathId(Node node) {
1001         OvsdbBridgeAugmentation ovsdbBridgeAugmentation = node.augmentation(OvsdbBridgeAugmentation.class);
1002         return getDatapathId(ovsdbBridgeAugmentation);
1003     }
1004
1005     public String getDatapathId(OvsdbBridgeAugmentation ovsdbBridgeAugmentation) {
1006         String datapathId = null;
1007         if (ovsdbBridgeAugmentation != null && ovsdbBridgeAugmentation.getDatapathId() != null) {
1008             datapathId = ovsdbBridgeAugmentation.getDatapathId().getValue();
1009         }
1010         return datapathId;
1011     }
1012
1013     public String extractBridgeName(Node node) {
1014         return node.augmentation(OvsdbBridgeAugmentation.class).getBridgeName().getValue();
1015     }
1016
1017     public boolean isBridgeOnOvsdbNode(Node ovsdbNode, String bridgeName) {
1018         OvsdbNodeAugmentation ovsdbNodeAugmentation = extractNodeAugmentation(ovsdbNode);
1019         if (ovsdbNodeAugmentation != null) {
1020             Map<ManagedNodeEntryKey, ManagedNodeEntry> managedNodes = ovsdbNodeAugmentation.getManagedNodeEntry();
1021             if (managedNodes != null) {
1022                 for (ManagedNodeEntry managedNode : managedNodes.values()) {
1023                     if (matchesBridgeName(managedNode, bridgeName)) {
1024                         return true;
1025                     }
1026                 }
1027             }
1028         }
1029         return false;
1030     }
1031
1032     // see OVSDB-470 for background
1033     private static boolean matchesBridgeName(ManagedNodeEntry managedNode, String bridgeName) {
1034         InstanceIdentifier<?> bridgeIid = managedNode.getBridgeRef().getValue();
1035         for (PathArgument bridgeIidPathArg : bridgeIid.getPathArguments()) {
1036             if (bridgeIidPathArg instanceof IdentifiableItem<?, ?> identifiableItem) {
1037                 Identifier<?> key = identifiableItem.getKey();
1038                 if (key instanceof NodeKey nodeKey) {
1039                     if (nodeKey.getNodeId().getValue().contains(bridgeName)) {
1040                         return true;
1041                     }
1042                 } else if (key.toString().contains(bridgeName)) {
1043                     return true;
1044                 }
1045             } else if (bridgeIidPathArg instanceof Item<?>) {
1046                 if (((Item<?>) bridgeIidPathArg).getType().getName().contains(bridgeName)) {
1047                     return true;
1048                 }
1049             } else {
1050                 throw new IllegalArgumentException("Unknown kind of PathArgument: " + bridgeIidPathArg);
1051             }
1052         }
1053         return false;
1054     }
1055
1056     public OvsdbBridgeAugmentation getBridgeFromConfig(Node node, String bridge) {
1057         OvsdbBridgeAugmentation ovsdbBridgeAugmentation = null;
1058         InstanceIdentifier<Node> bridgeIid =
1059                 createInstanceIdentifier(node.key(), bridge);
1060         Node bridgeNode = provider.read(LogicalDatastoreType.CONFIGURATION, bridgeIid);
1061         if (bridgeNode != null) {
1062             ovsdbBridgeAugmentation = bridgeNode.augmentation(OvsdbBridgeAugmentation.class);
1063         }
1064         return ovsdbBridgeAugmentation;
1065     }
1066
1067     public boolean isOvsdbNodeDpdk(Node ovsdbNode) {
1068         OvsdbNodeAugmentation ovsdbNodeAugmentation = extractNodeAugmentation(ovsdbNode);
1069         if (ovsdbNodeAugmentation != null) {
1070             Map<InterfaceTypeEntryKey, InterfaceTypeEntry> ifTypes = ovsdbNodeAugmentation.getInterfaceTypeEntry();
1071             if (ifTypes != null) {
1072                 if (ifTypes.containsKey(DPDK_IFACE_KEY)) {
1073                     return true;
1074                 }
1075             }
1076         }
1077         return false;
1078     }
1079
1080     private static Map<ControllerEntryKey, ControllerEntry> createControllerEntries(List<String> controllersStr,
1081             Uint32 maxBackoff, Uint32 inactivityProbe) {
1082         if (controllersStr == null) {
1083             return Map.of();
1084         }
1085
1086         BindingMap.Builder<ControllerEntryKey, ControllerEntry> controllerEntries =
1087             BindingMap.orderedBuilder(controllersStr.size());
1088         for (String controllerStr : controllersStr) {
1089             controllerEntries.add(new ControllerEntryBuilder()
1090                 .setTarget(new Uri(controllerStr))
1091                 .setMaxBackoff(maxBackoff)
1092                 .setInactivityProbe(inactivityProbe)
1093                 .build());
1094         }
1095         return controllerEntries.build();
1096     }
1097
1098     public OvsdbTerminationPointAugmentation extractTerminationPointAugmentation(Node bridgeNode, String portName) {
1099         if (bridgeNode.augmentation(OvsdbBridgeAugmentation.class) != null) {
1100             List<OvsdbTerminationPointAugmentation> tpAugmentations = extractTerminationPointAugmentations(bridgeNode);
1101             for (OvsdbTerminationPointAugmentation ovsdbTerminationPointAugmentation : tpAugmentations) {
1102                 if (ovsdbTerminationPointAugmentation.getName().equals(portName)) {
1103                     return ovsdbTerminationPointAugmentation;
1104                 }
1105             }
1106         }
1107         return null;
1108     }
1109
1110     public List<OvsdbTerminationPointAugmentation> extractTerminationPointAugmentations(Node node) {
1111         List<OvsdbTerminationPointAugmentation> tpAugmentations = new ArrayList<>();
1112         if (node == null) {
1113             LOG.error("extractTerminationPointAugmentations: Node value is null");
1114             return Collections.emptyList();
1115         }
1116         Map<TerminationPointKey, TerminationPoint> terminationPoints = node.getTerminationPoint();
1117         if (terminationPoints != null && !terminationPoints.isEmpty()) {
1118             for (TerminationPoint tp : terminationPoints.values()) {
1119                 OvsdbTerminationPointAugmentation ovsdbTerminationPointAugmentation =
1120                         tp.augmentation(OvsdbTerminationPointAugmentation.class);
1121                 if (ovsdbTerminationPointAugmentation != null) {
1122                     tpAugmentations.add(ovsdbTerminationPointAugmentation);
1123                 }
1124             }
1125         }
1126         return tpAugmentations;
1127     }
1128
1129     /**
1130      * Extract the <code>OvsdbTerminationPointAugmentation</code> for the particular <code>node</code> identified by
1131      * <code>portName</code>.
1132      */
1133     public OvsdbTerminationPointAugmentation getTerminationPointOfBridge(Node node, String portName) {
1134         OvsdbTerminationPointAugmentation tpAugmentation = extractTerminationPointAugmentation(node,portName);
1135         if (tpAugmentation == null) {
1136             List<OvsdbTerminationPointAugmentation> tpAugmentations = readTerminationPointAugmentations(node);
1137             if (tpAugmentations != null) {
1138                 for (OvsdbTerminationPointAugmentation ovsdbTpAugmentation : tpAugmentations) {
1139                     if (ovsdbTpAugmentation.getName().equals(portName)) {
1140                         return ovsdbTpAugmentation;
1141                     }
1142                 }
1143             }
1144         }
1145         return tpAugmentation;
1146     }
1147
1148     /**
1149      * Read the list of <code>OvsdbTerminationPointAugmentation</code> for the particular <code>node</code>.
1150      */
1151     public List<OvsdbTerminationPointAugmentation> readTerminationPointAugmentations(Node node) {
1152         if (node == null) {
1153             LOG.error("readTerminationPointAugmentations: Node value is null");
1154             return Collections.emptyList();
1155         }
1156         Node operNode = provider.read(LogicalDatastoreType.OPERATIONAL, InstanceIdentifier
1157                 .create(NetworkTopology.class)
1158                 .child(Topology.class, new TopologyKey(OVSDB_TOPOLOGY_ID))
1159                 .child(Node.class, new NodeKey(node.getNodeId())));
1160         if (operNode != null) {
1161             return extractTerminationPointAugmentations(operNode);
1162         }
1163         return new ArrayList<>();
1164     }
1165
1166     /**
1167      * Get all OVSDB nodes from topology.
1168      * @return a list of nodes or null if the topology could not found
1169      */
1170     public Map<NodeKey, Node> getOvsdbNodes() {
1171         InstanceIdentifier<Topology> inst = InstanceIdentifier.create(NetworkTopology.class).child(Topology.class,
1172                 new TopologyKey(OVSDB_TOPOLOGY_ID));
1173         Topology topology = provider.read(LogicalDatastoreType.OPERATIONAL, inst);
1174         return topology != null ? topology.getNode() : null;
1175     }
1176
1177     /**
1178      * Get OpenvSwitch other-config by key.
1179      * @param node OVSDB node
1180      * @param key key to extract from other-config
1181      * @return the value for key or null if key not found
1182      */
1183     public String getOpenvswitchOtherConfig(Node node, String key) {
1184         OvsdbNodeAugmentation ovsdbNode = node.augmentation(OvsdbNodeAugmentation.class);
1185         if (ovsdbNode == null) {
1186             Node nodeFromReadOvsdbNode = readOvsdbNode(node);
1187             if (nodeFromReadOvsdbNode != null) {
1188                 ovsdbNode = nodeFromReadOvsdbNode.augmentation(OvsdbNodeAugmentation.class);
1189             }
1190         }
1191
1192         if (ovsdbNode != null) {
1193             final OpenvswitchOtherConfigs found = ovsdbNode.nonnullOpenvswitchOtherConfigs()
1194                     .get(new OpenvswitchOtherConfigsKey(key));
1195             if (found != null) {
1196                 return found.getOtherConfigValue();
1197             }
1198         }
1199
1200         return null;
1201     }
1202
1203     public static TerminationPoint getTerminationPointByExternalId(final Node bridgeNode, final String interfaceName) {
1204         final Map<TerminationPointKey, TerminationPoint> tps = bridgeNode.getTerminationPoint();
1205         if (tps != null) {
1206             for (TerminationPoint tp : tps.values()) {
1207                 OvsdbTerminationPointAugmentation ovsdbTp = tp.augmentation(OvsdbTerminationPointAugmentation.class);
1208                 String externalIdValue = getExternalInterfaceIdValue(ovsdbTp);
1209                 if (externalIdValue != null && externalIdValue.equals(interfaceName)) {
1210                     LOG.debug("Found matching termination point with iface-id {} on bridgeNode {}, returning tp {}",
1211                             interfaceName, bridgeNode, tp);
1212                     return tp;
1213                 }
1214             }
1215         }
1216         return null;
1217     }
1218
1219     // This utility shouldn't be called often, as it reads all OVSDB nodes each time - not good for scale
1220     public Node getNodeByTerminationPointExternalId(final String interfaceName) {
1221         Map<NodeKey, Node> nodes = getOvsdbNodes();
1222         if (nodes != null) {
1223             for (Node node : nodes.values()) {
1224                 TerminationPoint tp = getTerminationPointByExternalId(node, interfaceName);
1225                 if (tp != null) {
1226                     return node;
1227                 }
1228             }
1229         }
1230         return null;
1231     }
1232
1233     public static String getExternalInterfaceIdValue(final OvsdbTerminationPointAugmentation ovsdbTp) {
1234         if (ovsdbTp != null) {
1235             Map<InterfaceExternalIdsKey, InterfaceExternalIds> ifaceExtIds = ovsdbTp.getInterfaceExternalIds();
1236             if (ifaceExtIds != null) {
1237                 final InterfaceExternalIds entry = ifaceExtIds.get(EXTERNAL_INTERFACE_ID_KEY);
1238                 if (entry != null) {
1239                     return entry.getExternalIdValue();
1240                 }
1241             }
1242         }
1243         return null;
1244     }
1245
1246     public String getDatapathIdFromNodeInstanceId(InstanceIdentifier<Node> nodeInstanceId) {
1247         Node node = provider.read(LogicalDatastoreType.OPERATIONAL, nodeInstanceId);
1248         String dpId = node != null ? getDataPathIdStr(node) : null;
1249         if (dpId != null) {
1250             return dpId;
1251         }
1252         return null;
1253     }
1254
1255     public static boolean compareDbVersionToMinVersion(final String dbVersion, final String minVersion) {
1256         if (dbVersion == null || minVersion == null) {
1257             LOG.error("Invalid DB version {} or minVersion {}", dbVersion, minVersion);
1258             return false;
1259         }
1260         final Matcher dbVersionMatcher = PATTERN.matcher(dbVersion);
1261         final Matcher minVersionMatcher = PATTERN.matcher(minVersion);
1262         LOG.debug("dbVersion {}, minVersion {}", dbVersion, minVersion);
1263         if (!dbVersionMatcher.find()) {
1264             LOG.error("Invalid DB version format {}", dbVersion);
1265             return false;
1266         }
1267         if (!minVersionMatcher.find()) {
1268             LOG.error("Invalid Min DB version format {}", minVersion);
1269             return false;
1270         }
1271
1272         if (dbVersion != null && !dbVersion.isEmpty() && minVersion != null && !minVersion.isEmpty()) {
1273             final int dbVersionMatch1 = Integer.parseInt(dbVersionMatcher.group(1));
1274             final int dbVersionMatch2 = Integer.parseInt(dbVersionMatcher.group(2));
1275             final int dbVersionMatch3 = Integer.parseInt(dbVersionMatcher.group(3));
1276             final int minVersionMatch1 = Integer.parseInt(minVersionMatcher.group(1));
1277             final int minVersionMatch2 = Integer.parseInt(minVersionMatcher.group(2));
1278             final int minVersionMatch3 = Integer.parseInt(minVersionMatcher.group(3));
1279             if (dbVersionMatch1 == minVersionMatch1 && dbVersionMatch2 == minVersionMatch2
1280                     && dbVersionMatch3 == minVersionMatch3) {
1281                 return true;
1282             }
1283
1284             if (dbVersionMatch1 > minVersionMatch1) {
1285                 return true;
1286             }
1287
1288             if (dbVersionMatch1 < minVersionMatch1) {
1289                 return false;
1290             }
1291
1292             // major version is equal
1293             if (dbVersionMatch2 > minVersionMatch2) {
1294                 return true;
1295             }
1296
1297             if (dbVersionMatch2 < minVersionMatch2) {
1298                 return false;
1299             }
1300
1301             if (dbVersionMatch3 > minVersionMatch3) {
1302                 return true;
1303             }
1304         }
1305         return false;
1306     }
1307
1308     private static Map<BridgeExternalIdsKey, BridgeExternalIds> setBridgeExternalIds() {
1309         final BridgeExternalIds ids = new BridgeExternalIdsBuilder()
1310                 .setBridgeExternalIdKey(CREATED_BY)
1311                 .setBridgeExternalIdValue(ODL)
1312                 .build();
1313         return Map.of(ids.key(), ids);
1314     }
1315
1316     private static Map<OptionsKey, Options> buildOptions(final Map<String, String> options) {
1317         final ImmutableMap.Builder<OptionsKey, Options> builder = ImmutableMap.builderWithExpectedSize(options.size());
1318         for (Map.Entry<String, String> entry : options.entrySet()) {
1319             final OptionsKey key = new OptionsKey(entry.getKey());
1320             builder.put(key, new OptionsBuilder().withKey(key).setValue(entry.getValue()).build());
1321         }
1322         return builder.build();
1323     }
1324 }