Merge "Clean up L2ForwardingService"
[netvirt.git] / openstack / net-virt-it / src / test / java / org / opendaylight / ovsdb / openstack / netvirt / it / NetvirtIT.java
1 /*
2  * Copyright (c) 2015 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 package org.opendaylight.ovsdb.openstack.netvirt.it;
9
10 import static org.junit.Assert.assertEquals;
11 import static org.junit.Assert.assertNotEquals;
12 import static org.junit.Assert.assertNotNull;
13 import static org.junit.Assert.assertTrue;
14 import static org.junit.Assert.fail;
15 import static org.ops4j.pax.exam.CoreOptions.composite;
16 import static org.ops4j.pax.exam.CoreOptions.maven;
17 import static org.ops4j.pax.exam.CoreOptions.mavenBundle;
18 import static org.ops4j.pax.exam.CoreOptions.propagateSystemProperties;
19 import static org.ops4j.pax.exam.CoreOptions.vmOption;
20 import static org.ops4j.pax.exam.CoreOptions.wrappedBundle;
21 import static org.ops4j.pax.exam.MavenUtils.asInProject;
22 import static org.ops4j.pax.exam.karaf.options.KarafDistributionOption.configureConsole;
23 import static org.ops4j.pax.exam.karaf.options.KarafDistributionOption.editConfigurationFilePut;
24 import static org.ops4j.pax.exam.karaf.options.KarafDistributionOption.keepRuntimeFolder;
25
26 import com.google.common.collect.ImmutableBiMap;
27 import com.google.common.collect.Lists;
28
29 import java.net.InetAddress;
30 import java.net.NetworkInterface;
31 import java.net.UnknownHostException;
32 import java.util.ArrayList;
33 import java.util.Enumeration;
34 import java.util.List;
35 import java.util.Map;
36 import java.util.Properties;
37 import java.util.concurrent.atomic.AtomicBoolean;
38 import org.junit.Assert;
39 import org.junit.Before;
40 import org.junit.Ignore;
41 import org.junit.Test;
42 import org.junit.runner.RunWith;
43 import org.opendaylight.controller.md.sal.binding.api.DataBroker;
44 import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
45 import org.opendaylight.controller.mdsal.it.base.AbstractMdsalTestBase;
46 import org.opendaylight.controller.sal.binding.api.BindingAwareBroker;
47 import org.opendaylight.ovsdb.openstack.netvirt.api.Constants;
48 import org.opendaylight.ovsdb.openstack.netvirt.api.SecurityServicesManager;
49 import org.opendaylight.ovsdb.openstack.netvirt.api.Southbound;
50 import org.opendaylight.ovsdb.openstack.netvirt.providers.openflow13.AbstractServiceInstance;
51 import org.opendaylight.ovsdb.openstack.netvirt.providers.openflow13.PipelineOrchestrator;
52 import org.opendaylight.ovsdb.openstack.netvirt.providers.openflow13.Service;
53 import org.opendaylight.ovsdb.utils.config.ConfigProperties;
54 import org.opendaylight.ovsdb.utils.mdsal.openflow.FlowUtils;
55 import org.opendaylight.ovsdb.utils.servicehelper.ServiceHelper;
56 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev100924.IpAddress;
57 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev100924.PortNumber;
58 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev100924.Uri;
59 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.tables.table.Flow;
60 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.tables.table.FlowBuilder;
61 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.ovsdb.rev150105.*;
62 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.ovsdb.rev150105.ovsdb.bridge.attributes.BridgeExternalIds;
63 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.ovsdb.rev150105.ovsdb.bridge.attributes.BridgeOtherConfigs;
64 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.ovsdb.rev150105.ovsdb.bridge.attributes.ControllerEntry;
65 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.ovsdb.rev150105.ovsdb.bridge.attributes.ProtocolEntry;
66 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.ovsdb.rev150105.ovsdb.bridge.attributes.ProtocolEntryBuilder;
67 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.ovsdb.rev150105.ovsdb.node.attributes.ConnectionInfo;
68 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.ovsdb.rev150105.ovsdb.node.attributes.ConnectionInfoBuilder;
69 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.ovsdb.rev150105.ovsdb.node.attributes.InterfaceTypeEntryBuilder;
70 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.ovsdb.rev150105.ovsdb.node.attributes.ManagerEntry;
71 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.ovsdb.rev150105.ovsdb.node.attributes.OpenvswitchOtherConfigs;
72 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.NetworkTopology;
73 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.NodeId;
74 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.TopologyId;
75 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.TpId;
76 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.Topology;
77 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.TopologyKey;
78 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.topology.Node;
79 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.topology.NodeBuilder;
80 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.topology.node.TerminationPointBuilder;
81 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.topology.node.TerminationPointKey;
82 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
83 import org.ops4j.pax.exam.Configuration;
84 import org.ops4j.pax.exam.Option;
85 import org.ops4j.pax.exam.junit.PaxExam;
86 import org.ops4j.pax.exam.karaf.options.LogLevelOption;
87 import org.ops4j.pax.exam.options.MavenUrlReference;
88 import org.ops4j.pax.exam.spi.reactors.ExamReactorStrategy;
89 import org.ops4j.pax.exam.spi.reactors.PerClass;
90 import org.slf4j.Logger;
91 import org.slf4j.LoggerFactory;
92
93 /**
94  * Integration tests for netvirt
95  *
96  * @author Sam Hague (shague@redhat.com)
97  */
98 @RunWith(PaxExam.class)
99 @ExamReactorStrategy(PerClass.class)
100 public class NetvirtIT extends AbstractMdsalTestBase {
101     private static final Logger LOG = LoggerFactory.getLogger(NetvirtIT.class);
102     private static final int OVSDB_UPDATE_TIMEOUT = 1000;
103     private static DataBroker dataBroker = null;
104     private static String addressStr;
105     private static String portStr;
106     private static String connectionType;
107     private static String controllerStr;
108     private static AtomicBoolean setup = new AtomicBoolean(false);
109     private static MdsalUtils mdsalUtils = null;
110     private static Southbound southbound = null;
111     private static final String NETVIRT_TOPOLOGY_ID = "netvirt:1";
112
113     @Override
114     public String getModuleName() {
115         return "netvirt-providers-impl";
116     }
117
118     @Override
119     public String getInstanceName() {
120         return "netvirt-providers-default";
121     }
122
123     @Override
124     public MavenUrlReference getFeatureRepo() {
125         return maven()
126                 .groupId("org.opendaylight.ovsdb")
127                 .artifactId("features-ovsdb")
128                 .classifier("features")
129                 .type("xml")
130                 .versionAsInProject();
131     }
132
133     @Override
134     public String getFeatureName() {
135         return "odl-ovsdb-openstack";
136     }
137
138     @Configuration
139     @Override
140     public Option[] config() {
141         Option[] parentOptions = super.config();
142         Option[] propertiesOptions = getPropertiesOptions();
143         Option[] otherOptions = getOtherOptions();
144         Option[] options = new Option[parentOptions.length + propertiesOptions.length + otherOptions.length];
145         System.arraycopy(parentOptions, 0, options, 0, parentOptions.length);
146         System.arraycopy(propertiesOptions, 0, options, parentOptions.length, propertiesOptions.length);
147         System.arraycopy(otherOptions, 0, options, parentOptions.length + propertiesOptions.length,
148                 otherOptions.length);
149         return options;
150     }
151
152     private Option[] getOtherOptions() {
153         return new Option[] {
154                 wrappedBundle(
155                         mavenBundle("org.opendaylight.ovsdb", "utils.mdsal-openflow")
156                                 .version(asInProject())
157                                 .type("jar")),
158                 wrappedBundle(
159                         mavenBundle("org.opendaylight.ovsdb", "utils.config")
160                                 .version(asInProject())
161                                 .type("jar")),
162                 configureConsole().startLocalConsole(),
163                 vmOption("-javaagent:../jars/org.jacoco.agent.jar=destfile=../../jacoco-it.exec"),
164                 keepRuntimeFolder()
165         };
166     }
167
168     public Option[] getPropertiesOptions() {
169         return new Option[] {
170                 propagateSystemProperties(NetvirtITConstants.SERVER_IPADDRESS,
171                         NetvirtITConstants.SERVER_PORT, NetvirtITConstants.CONNECTION_TYPE,
172                         NetvirtITConstants.CONTROLLER_IPADDRESS),
173         };
174     }
175
176     @Override
177     public Option getLoggingOption() {
178         return composite(
179                 editConfigurationFilePut(NetvirtITConstants.ORG_OPS4J_PAX_LOGGING_CFG,
180                         "log4j.logger.org.opendaylight.ovsdb",
181                         LogLevelOption.LogLevel.TRACE.name()),
182                 editConfigurationFilePut(ORG_OPS4J_PAX_LOGGING_CFG,
183                         logConfiguration(NetvirtIT.class),
184                         LogLevelOption.LogLevel.INFO.name()),
185                 //editConfigurationFilePut(NetvirtITConstants.ORG_OPS4J_PAX_LOGGING_CFG,
186                 //        "log4j.logger.org.opendaylight.ovsdb.lib",
187                 //        LogLevelOption.LogLevel.INFO.name()),
188                 super.getLoggingOption());
189     }
190
191     protected String usage() {
192         return "Integration Test needs a valid connection configuration as follows :\n"
193                 + "active connection : mvn -Dovsdbserver.ipaddress=x.x.x.x -Dovsdbserver.port=yyyy verify\n"
194                 + "passive connection : mvn -Dovsdbserver.connection=passive verify\n";
195     }
196
197     private void getProperties() {
198         Properties props = System.getProperties();
199         addressStr = props.getProperty(NetvirtITConstants.SERVER_IPADDRESS);
200         portStr = props.getProperty(NetvirtITConstants.SERVER_PORT, NetvirtITConstants.DEFAULT_SERVER_PORT);
201         connectionType = props.getProperty(NetvirtITConstants.CONNECTION_TYPE, "active");
202         controllerStr = props.getProperty(NetvirtITConstants.CONTROLLER_IPADDRESS);
203         LOG.info("setUp: Using the following properties: mode= {}, ip:port= {}:{}, controller ip: {}",
204                 connectionType, addressStr, portStr, controllerStr);
205         if (connectionType.equalsIgnoreCase(NetvirtITConstants.CONNECTION_TYPE_ACTIVE)) {
206             if (addressStr == null) {
207                 fail(usage());
208             }
209         }
210     }
211
212     @Before
213     @Override
214     public void setup() throws InterruptedException {
215         if (setup.get()) {
216             LOG.info("Skipping setUp, already initialized");
217             return;
218         }
219
220         try {
221             super.setup();
222         } catch (Exception e) {
223             e.printStackTrace();
224         }
225
226         getProperties();
227
228         if (connectionType.equalsIgnoreCase(NetvirtITConstants.CONNECTION_TYPE_ACTIVE)) {
229             if (addressStr == null) {
230                 fail(usage());
231             }
232         }
233
234         dataBroker = getDatabroker(getProviderContext());
235         mdsalUtils = new MdsalUtils(dataBroker);
236         assertNotNull("mdsalUtils should not be null", mdsalUtils);
237         assertTrue("Did not find " + NETVIRT_TOPOLOGY_ID, getNetvirtTopology());
238         southbound = (Southbound) ServiceHelper.getGlobalInstance(Southbound.class, this);
239         assertNotNull("southbound should not be null", southbound);
240         setup.set(true);
241     }
242
243     private BindingAwareBroker.ProviderContext getProviderContext() {
244         BindingAwareBroker.ProviderContext providerContext = null;
245         for (int i=0; i < 60; i++) {
246             providerContext = getSession();
247             if (providerContext != null) {
248                 break;
249             } else {
250                 try {
251                     Thread.sleep(1000);
252                 } catch (InterruptedException e) {
253                     e.printStackTrace();
254                 }
255             }
256         }
257         assertNotNull("providercontext should not be null", providerContext);
258         /* One more second to let the provider finish initialization */
259         try {
260             Thread.sleep(1000);
261         } catch (InterruptedException e) {
262             e.printStackTrace();
263         }
264         return providerContext;
265     }
266
267     private DataBroker getDatabroker(BindingAwareBroker.ProviderContext providerContext) {
268         DataBroker dataBroker = providerContext.getSALService(DataBroker.class);
269         assertNotNull("dataBroker should not be null", dataBroker);
270         return dataBroker;
271     }
272
273     private Boolean getNetvirtTopology() {
274         LOG.info("getNetvirtTopology: looking for {}...", NETVIRT_TOPOLOGY_ID);
275         Boolean found = false;
276         final TopologyId topologyId = new TopologyId(new Uri(NETVIRT_TOPOLOGY_ID));
277         InstanceIdentifier<Topology> path =
278                 InstanceIdentifier.create(NetworkTopology.class).child(Topology.class, new TopologyKey(topologyId));
279         for (int i = 0; i < 60; i++) {
280             Topology topology = mdsalUtils.read(LogicalDatastoreType.OPERATIONAL, path);
281             if (topology != null) {
282                 LOG.info("getNetvirtTopology: found {}...", NETVIRT_TOPOLOGY_ID);
283                 found = true;
284                 break;
285             } else {
286                 LOG.info("getNetvirtTopology: still looking ({})...", i);
287                 try {
288                     Thread.sleep(1000);
289                 } catch (InterruptedException e) {
290                     e.printStackTrace();
291                 }
292             }
293         }
294         return found;
295     }
296
297     /**
298      * Test passive connection mode. The southbound starts in a listening mode waiting for connections on port
299      * 6640. This test will wait for incoming connections for {@link NetvirtITConstants.CONNECTION_INIT_TIMEOUT} ms.
300      *
301      * @throws InterruptedException
302      */
303     @Ignore
304     @Test
305     public void testPassiveNode() throws InterruptedException {
306         if (connectionType.equalsIgnoreCase(NetvirtITConstants.CONNECTION_TYPE_PASSIVE)) {
307             //Wait for CONNECTION_INIT_TIMEOUT for the Passive connection to be initiated by the ovsdb-server.
308             Thread.sleep(NetvirtITConstants.CONNECTION_INIT_TIMEOUT);
309         }
310     }
311
312     private ConnectionInfo getConnectionInfo(final String addressStr, final String portStr) {
313         InetAddress inetAddress = null;
314         try {
315             inetAddress = InetAddress.getByName(addressStr);
316         } catch (UnknownHostException e) {
317             fail("Could not allocate InetAddress: " + e);
318         }
319
320         IpAddress address = SouthboundMapper.createIpAddress(inetAddress);
321         PortNumber port = new PortNumber(Integer.parseInt(portStr));
322
323         LOG.info("connectionInfo: {}", new ConnectionInfoBuilder()
324                 .setRemoteIp(address)
325                 .setRemotePort(port)
326                 .build());
327         return new ConnectionInfoBuilder()
328                        .setRemoteIp(address)
329                        .setRemotePort(port)
330                        .build();
331     }
332
333     private String connectionInfoToString(final ConnectionInfo connectionInfo) {
334         return new String(connectionInfo.getRemoteIp().getValue()) + ":" + connectionInfo.getRemotePort().getValue();
335     }
336
337     private boolean addOvsdbNode(final ConnectionInfo connectionInfo) throws InterruptedException {
338         boolean result = mdsalUtils.put(LogicalDatastoreType.CONFIGURATION,
339                 SouthboundMapper.createInstanceIdentifier(connectionInfo),
340                 SouthboundMapper.createNode(connectionInfo));
341         Thread.sleep(OVSDB_UPDATE_TIMEOUT);
342         return result;
343     }
344
345     private Node getOvsdbNode(final ConnectionInfo connectionInfo) {
346         return mdsalUtils.read(LogicalDatastoreType.OPERATIONAL,
347                 SouthboundMapper.createInstanceIdentifier(connectionInfo));
348     }
349
350     private boolean deleteOvsdbNode(final ConnectionInfo connectionInfo) throws InterruptedException {
351         boolean result = mdsalUtils.delete(LogicalDatastoreType.CONFIGURATION,
352                 SouthboundMapper.createInstanceIdentifier(connectionInfo));
353         Thread.sleep(OVSDB_UPDATE_TIMEOUT);
354         return result;
355     }
356
357     private Node connectOvsdbNode(final ConnectionInfo connectionInfo) throws InterruptedException {
358         Assert.assertTrue(addOvsdbNode(connectionInfo));
359         Node node = getOvsdbNode(connectionInfo);
360         Assert.assertNotNull("Should find OVSDB node after connect", node);
361         LOG.info("Connected to {}", connectionInfoToString(connectionInfo));
362         return node;
363     }
364
365     private boolean disconnectOvsdbNode(final ConnectionInfo connectionInfo) throws InterruptedException {
366         Assert.assertTrue(deleteOvsdbNode(connectionInfo));
367         Node node = getOvsdbNode(connectionInfo);
368         Assert.assertNull("Should not find OVSDB node after disconnect", node);
369         //Assume.assumeNotNull(node); // Using assumeNotNull because there is no assumeNull
370         LOG.info("Disconnected from {}", connectionInfoToString(connectionInfo));
371         return true;
372     }
373
374     private String getControllerIPAddress() {
375         String addressString = ConfigProperties.getProperty(this.getClass(), "ovsdb.controller.address");
376         if (addressString != null) {
377             try {
378                 if (InetAddress.getByName(addressString) != null) {
379                     return addressString;
380                 }
381             } catch (UnknownHostException e) {
382                 LOG.error("Host {} is invalid", addressString);
383             }
384         }
385
386         addressString = ConfigProperties.getProperty(this.getClass(), "of.address");
387         if (addressString != null) {
388             try {
389                 if (InetAddress.getByName(addressString) != null) {
390                     return addressString;
391                 }
392             } catch (UnknownHostException e) {
393                 LOG.error("Host {} is invalid", addressString);
394             }
395         }
396
397         return null;
398     }
399
400     private short getControllerOFPort() {
401         short openFlowPort = Constants.OPENFLOW_PORT;
402         String portString = ConfigProperties.getProperty(this.getClass(), "of.listenPort");
403         if (portString != null) {
404             try {
405                 openFlowPort = Short.parseShort(portString);
406             } catch (NumberFormatException e) {
407                 LOG.warn("Invalid port:{}, use default({})", portString,
408                         openFlowPort);
409             }
410         }
411         return openFlowPort;
412     }
413
414     private List<String> getControllersFromOvsdbNode(Node node) {
415         List<String> controllersStr = new ArrayList<>();
416
417         String controllerIpStr = getControllerIPAddress();
418         if (controllerIpStr != null) {
419             // If codepath makes it here, the ip address to be used was explicitly provided.
420             // Being so, also fetch openflowPort provided via ConfigProperties.
421             controllersStr.add(Constants.OPENFLOW_CONNECTION_PROTOCOL
422                     + ":" + controllerIpStr + ":" + getControllerOFPort());
423         } else {
424             // Check if ovsdb node has manager entries
425             OvsdbNodeAugmentation ovsdbNodeAugmentation = southbound.extractOvsdbNode(node);
426             if (ovsdbNodeAugmentation != null) {
427                 List<ManagerEntry> managerEntries = ovsdbNodeAugmentation.getManagerEntry();
428                 if (managerEntries != null && !managerEntries.isEmpty()) {
429                     for (ManagerEntry managerEntry : managerEntries) {
430                         if (managerEntry == null || managerEntry.getTarget() == null) {
431                             continue;
432                         }
433                         String[] tokens = managerEntry.getTarget().getValue().split(":");
434                         if (tokens.length == 3 && tokens[0].equalsIgnoreCase("tcp")) {
435                             controllersStr.add(Constants.OPENFLOW_CONNECTION_PROTOCOL
436                                     + ":" + tokens[1] + ":" + getControllerOFPort());
437                         } else if (tokens[0].equalsIgnoreCase("ptcp")) {
438                             ConnectionInfo connectionInfo = ovsdbNodeAugmentation.getConnectionInfo();
439                             if (connectionInfo != null && connectionInfo.getLocalIp() != null) {
440                                 controllerIpStr = new String(connectionInfo.getLocalIp().getValue());
441                                 controllersStr.add(Constants.OPENFLOW_CONNECTION_PROTOCOL
442                                         + ":" + controllerIpStr + ":" + Constants.OPENFLOW_PORT);
443                             } else {
444                                 LOG.warn("Ovsdb Node does not contain connection info: {}", node);
445                             }
446                         } else {
447                             LOG.trace("Skipping manager entry {} for node {}",
448                                     managerEntry.getTarget(), node.getNodeId().getValue());
449                         }
450                     }
451                 } else {
452                     LOG.warn("Ovsdb Node does not contain manager entries : {}", node);
453                 }
454             }
455         }
456
457         if (controllersStr.isEmpty()) {
458             // Neither user provided ip nor ovsdb node has manager entries. Lets use local machine ip address.
459             LOG.debug("Use local machine ip address as a OpenFlow Controller ip address");
460             controllerIpStr = getLocalControllerHostIpAddress();
461             if (controllerIpStr != null) {
462                 controllersStr.add(Constants.OPENFLOW_CONNECTION_PROTOCOL
463                         + ":" + controllerIpStr + ":" + Constants.OPENFLOW_PORT);
464             }
465         }
466
467         if (controllersStr.isEmpty()) {
468             LOG.warn("Failed to determine OpenFlow controller ip address");
469         } else if (LOG.isDebugEnabled()) {
470             controllerIpStr = "";
471             for (String currControllerIpStr : controllersStr) {
472                 controllerIpStr += " " + currControllerIpStr;
473             }
474             LOG.debug("Found {} OpenFlow Controller(s) :{}", controllersStr.size(), controllerIpStr);
475         }
476
477         return controllersStr;
478     }
479
480     private String getLocalControllerHostIpAddress() {
481         String ipaddress = null;
482         try{
483             for (Enumeration<NetworkInterface> ifaces = NetworkInterface.getNetworkInterfaces();ifaces.hasMoreElements();){
484                 NetworkInterface iface = ifaces.nextElement();
485
486                 for (Enumeration<InetAddress> inetAddrs = iface.getInetAddresses(); inetAddrs.hasMoreElements();) {
487                     InetAddress inetAddr = inetAddrs.nextElement();
488                     if (!inetAddr.isLoopbackAddress() && inetAddr.isSiteLocalAddress()) {
489                         ipaddress = inetAddr.getHostAddress();
490                         break;
491                     }
492                 }
493             }
494         }catch (Exception e){
495             LOG.warn("Exception while fetching local host ip address ", e);
496         }
497         return ipaddress;
498     }
499
500     private String getControllerTarget(Node ovsdbNode) {
501         return getControllersFromOvsdbNode(ovsdbNode).get(0);
502     }
503
504     @Test
505     public void testAddDeleteOvsdbNode() throws InterruptedException {
506         ConnectionInfo connectionInfo = getConnectionInfo(addressStr, portStr);
507         connectOvsdbNode(connectionInfo);
508         ControllerEntry controllerEntry;
509         for (int i = 0; i < 10; i++) {
510             Node ovsdbNode = getOvsdbNode(connectionInfo);
511             Assert.assertNotNull("ovsdb node not found", ovsdbNode);
512             String controllerTarget = getControllerTarget(ovsdbNode);
513             Assert.assertNotNull("Failed to get controller target", controllerTarget);
514             OvsdbBridgeAugmentation bridge = getBridge(connectionInfo, NetvirtITConstants.INTEGRATION_BRIDGE_NAME);
515             Assert.assertNotNull(bridge);
516             Assert.assertNotNull(bridge.getControllerEntry());
517             controllerEntry = bridge.getControllerEntry().iterator().next();
518             Assert.assertEquals(controllerTarget, controllerEntry.getTarget().getValue());
519             if (controllerEntry.isIsConnected()) {
520                 Assert.assertTrue(controllerEntry.isIsConnected());
521                 break;
522             }
523             Thread.sleep(1000);
524         }
525
526         Assert.assertTrue(deleteBridge(connectionInfo, NetvirtITConstants.INTEGRATION_BRIDGE_NAME));
527         Thread.sleep(1000);
528         Assert.assertTrue(disconnectOvsdbNode(connectionInfo));
529     }
530
531     @Ignore
532     @Test
533     public void testOpenVSwitchOtherConfig() throws InterruptedException {
534         ConnectionInfo connectionInfo = getConnectionInfo(addressStr, portStr);
535         Node ovsdbNode = connectOvsdbNode(connectionInfo);
536         OvsdbNodeAugmentation ovsdbNodeAugmentation = ovsdbNode.getAugmentation(OvsdbNodeAugmentation.class);
537         Assert.assertNotNull(ovsdbNodeAugmentation);
538         List<OpenvswitchOtherConfigs> otherConfigsList = ovsdbNodeAugmentation.getOpenvswitchOtherConfigs();
539         if (otherConfigsList != null) {
540             for (OpenvswitchOtherConfigs otherConfig : otherConfigsList) {
541                 if (otherConfig.getOtherConfigKey().equals("local_ip")) {
542                     LOG.info("local_ip: {}", otherConfig.getOtherConfigValue());
543                     break;
544                 } else {
545                     LOG.info("other_config {}:{}", otherConfig.getOtherConfigKey(), otherConfig.getOtherConfigValue());
546                 }
547             }
548         } else {
549             LOG.info("other_config is not present");
550         }
551         Assert.assertTrue(disconnectOvsdbNode(connectionInfo));
552         //Assume.assumeTrue(disconnectOvsdbNode(connectionInfo));
553     }
554
555     private void setManagedBy(final OvsdbBridgeAugmentationBuilder ovsdbBridgeAugmentationBuilder,
556                               final ConnectionInfo connectionInfo) {
557         InstanceIdentifier<Node> connectionNodePath = SouthboundMapper.createInstanceIdentifier(connectionInfo);
558         ovsdbBridgeAugmentationBuilder.setManagedBy(new OvsdbNodeRef(connectionNodePath));
559     }
560
561     private List<ProtocolEntry> createMdsalProtocols() {
562         List<ProtocolEntry> protocolList = new ArrayList<>();
563         ImmutableBiMap<String, Class<? extends OvsdbBridgeProtocolBase>> mapper =
564                 SouthboundConstants.OVSDB_PROTOCOL_MAP.inverse();
565         protocolList.add(new ProtocolEntryBuilder().
566                 setProtocol(mapper.get("OpenFlow13")).build());
567         return protocolList;
568     }
569
570     private OvsdbTerminationPointAugmentationBuilder createGenericOvsdbTerminationPointAugmentationBuilder() {
571         OvsdbTerminationPointAugmentationBuilder ovsdbTerminationPointAugmentationBuilder =
572                 new OvsdbTerminationPointAugmentationBuilder();
573         ovsdbTerminationPointAugmentationBuilder.setInterfaceType(
574                 new InterfaceTypeEntryBuilder()
575                         .setInterfaceType(
576                                 SouthboundMapper.createInterfaceType("internal"))
577                         .build().getInterfaceType());
578         return ovsdbTerminationPointAugmentationBuilder;
579     }
580
581     private boolean addTerminationPoint(final NodeId bridgeNodeId, final String portName,
582             final OvsdbTerminationPointAugmentationBuilder ovsdbTerminationPointAugmentationBuilder)
583         throws InterruptedException {
584
585         InstanceIdentifier<Node> portIid = SouthboundMapper.createInstanceIdentifier(bridgeNodeId);
586         NodeBuilder portNodeBuilder = new NodeBuilder();
587         NodeId portNodeId = SouthboundMapper.createManagedNodeId(portIid);
588         portNodeBuilder.setNodeId(portNodeId);
589         TerminationPointBuilder entry = new TerminationPointBuilder();
590         entry.setKey(new TerminationPointKey(new TpId(portName)));
591         entry.addAugmentation(
592                 OvsdbTerminationPointAugmentation.class,
593                 ovsdbTerminationPointAugmentationBuilder.build());
594         portNodeBuilder.setTerminationPoint(Lists.newArrayList(entry.build()));
595         boolean result = mdsalUtils.merge(LogicalDatastoreType.CONFIGURATION,
596                 portIid, portNodeBuilder.build());
597         Thread.sleep(OVSDB_UPDATE_TIMEOUT);
598         return result;
599     }
600
601     /*
602      * base method for adding test bridges.  Other helper methods used to create bridges should utilize this method.
603      *
604      * @param connectionInfo
605      * @param bridgeIid if passed null, one is created
606      * @param bridgeName cannot be null
607      * @param bridgeNodeId if passed null, one is created based on <code>bridgeIid</code>
608      * @param setProtocolEntries toggles whether default protocol entries are set for the bridge
609      * @param failMode toggles whether default fail mode is set for the bridge
610      * @param setManagedBy toggles whether to setManagedBy for the bridge
611      * @param dpType if passed null, this parameter is ignored
612      * @param externalIds if passed null, this parameter is ignored
613      * @param otherConfig if passed null, this parameter is ignored
614      * @return success of bridge addition
615      * @throws InterruptedException
616      */
617     private boolean addBridge(final ConnectionInfo connectionInfo, InstanceIdentifier<Node> bridgeIid,
618             final String bridgeName, NodeId bridgeNodeId, final boolean setProtocolEntries,
619             final Class<? extends OvsdbFailModeBase> failMode, final boolean setManagedBy,
620             final Class<? extends DatapathTypeBase> dpType,
621             final List<BridgeExternalIds> externalIds,
622             final List<BridgeOtherConfigs> otherConfigs) throws InterruptedException {
623
624         NodeBuilder bridgeNodeBuilder = new NodeBuilder();
625         if (bridgeIid == null) {
626             bridgeIid = SouthboundMapper.createInstanceIdentifier(connectionInfo, new OvsdbBridgeName(bridgeName));
627         }
628         if (bridgeNodeId == null) {
629             bridgeNodeId = SouthboundMapper.createManagedNodeId(bridgeIid);
630         }
631         bridgeNodeBuilder.setNodeId(bridgeNodeId);
632         OvsdbBridgeAugmentationBuilder ovsdbBridgeAugmentationBuilder = new OvsdbBridgeAugmentationBuilder();
633         ovsdbBridgeAugmentationBuilder.setBridgeName(new OvsdbBridgeName(bridgeName));
634         if (setProtocolEntries) {
635             ovsdbBridgeAugmentationBuilder.setProtocolEntry(createMdsalProtocols());
636         }
637         if (failMode != null) {
638             ovsdbBridgeAugmentationBuilder.setFailMode(failMode);
639         }
640         if (setManagedBy) {
641             setManagedBy(ovsdbBridgeAugmentationBuilder, connectionInfo);
642         }
643         if (dpType != null) {
644             ovsdbBridgeAugmentationBuilder.setDatapathType(dpType);
645         }
646         if (externalIds != null) {
647             ovsdbBridgeAugmentationBuilder.setBridgeExternalIds(externalIds);
648         }
649         if (otherConfigs != null) {
650             ovsdbBridgeAugmentationBuilder.setBridgeOtherConfigs(otherConfigs);
651         }
652         bridgeNodeBuilder.addAugmentation(OvsdbBridgeAugmentation.class, ovsdbBridgeAugmentationBuilder.build());
653         LOG.debug("Built with the intent to store bridge data {}",
654                 ovsdbBridgeAugmentationBuilder.toString());
655         boolean result = mdsalUtils.merge(LogicalDatastoreType.CONFIGURATION,
656                 bridgeIid, bridgeNodeBuilder.build());
657         Thread.sleep(OVSDB_UPDATE_TIMEOUT);
658         return result;
659     }
660
661     private boolean addBridge(final ConnectionInfo connectionInfo, final String bridgeName)
662         throws InterruptedException {
663
664         return addBridge(connectionInfo, null, bridgeName, null, true,
665                 SouthboundConstants.OVSDB_FAIL_MODE_MAP.inverse().get("secure"), true, null, null, null);
666     }
667
668     private OvsdbBridgeAugmentation getBridge(ConnectionInfo connectionInfo) {
669         return getBridge(connectionInfo, NetvirtITConstants.BRIDGE_NAME);
670     }
671
672     /**
673      * Extract the <code>store</code> type data store contents for the particular bridge identified by
674      * <code>bridgeName</code>.
675      *
676      * @param connectionInfo
677      * @param bridgeName
678      * @param store defined by the <code>LogicalDatastoreType</code> enumeration
679      * @return <code>store</code> type data store contents
680      */
681     private OvsdbBridgeAugmentation getBridge(ConnectionInfo connectionInfo, String bridgeName,
682             LogicalDatastoreType store) {
683         Node bridgeNode = getBridgeNode(connectionInfo, bridgeName, store);
684         Assert.assertNotNull(bridgeNode);
685         OvsdbBridgeAugmentation ovsdbBridgeAugmentation = bridgeNode.getAugmentation(OvsdbBridgeAugmentation.class);
686         Assert.assertNotNull(ovsdbBridgeAugmentation);
687         return ovsdbBridgeAugmentation;
688     }
689
690     /**
691      * extract the <code>LogicalDataStoreType.OPERATIONAL</code> type data store contents for the particular bridge
692      * identified by <code>bridgeName</code>
693      *
694      * @param connectionInfo
695      * @param bridgeName
696      * @see <code>NetvirtIT.getBridge(ConnectionInfo, String, LogicalDatastoreType)</code>
697      * @return <code>LogicalDatastoreType.OPERATIONAL</code> type data store contents
698      */
699     private OvsdbBridgeAugmentation getBridge(ConnectionInfo connectionInfo, String bridgeName) {
700         return getBridge(connectionInfo, bridgeName, LogicalDatastoreType.OPERATIONAL);
701     }
702
703     /**
704      * Extract the node contents from <code>store</code> type data store for the
705      * bridge identified by <code>bridgeName</code>
706      *
707      * @param connectionInfo
708      * @param bridgeName
709      * @param store defined by the <code>LogicalDatastoreType</code> enumeration
710      * @return <code>store</code> type data store contents
711      */
712     private Node getBridgeNode(ConnectionInfo connectionInfo, String bridgeName, LogicalDatastoreType store) {
713         InstanceIdentifier<Node> bridgeIid =
714                 SouthboundMapper.createInstanceIdentifier(connectionInfo,
715                     new OvsdbBridgeName(bridgeName));
716         return mdsalUtils.read(store, bridgeIid);
717     }
718
719     /**
720      * Extract the node contents from <code>LogicalDataStoreType.OPERATIONAL</code> data store for the
721      * bridge identified by <code>bridgeName</code>
722      *
723      * @param connectionInfo
724      * @param bridgeName
725      * @return <code>LogicalDatastoreType.OPERATIONAL</code> type data store contents
726      */
727     private Node getBridgeNode(ConnectionInfo connectionInfo, String bridgeName) {
728         return getBridgeNode(connectionInfo, bridgeName, LogicalDatastoreType.OPERATIONAL);
729     }
730
731     private boolean deleteBridge(ConnectionInfo connectionInfo) throws InterruptedException {
732         return deleteBridge(connectionInfo, NetvirtITConstants.BRIDGE_NAME);
733     }
734
735     private boolean deleteBridge(final ConnectionInfo connectionInfo, final String bridgeName)
736         throws InterruptedException {
737
738         boolean result = mdsalUtils.delete(LogicalDatastoreType.CONFIGURATION,
739                 SouthboundMapper.createInstanceIdentifier(connectionInfo,
740                         new OvsdbBridgeName(bridgeName)));
741         Thread.sleep(OVSDB_UPDATE_TIMEOUT);
742         return result;
743     }
744
745     private InstanceIdentifier<Node> getTpIid(ConnectionInfo connectionInfo, OvsdbBridgeAugmentation bridge) {
746         return SouthboundMapper.createInstanceIdentifier(connectionInfo,
747             bridge.getBridgeName());
748     }
749
750     private void netVirtAddPort(ConnectionInfo connectionInfo) throws InterruptedException {
751         OvsdbBridgeAugmentation bridge = getBridge(connectionInfo, NetvirtITConstants.INTEGRATION_BRIDGE_NAME);
752         Assert.assertNotNull(bridge);
753         NodeId nodeId = SouthboundMapper.createManagedNodeId(SouthboundMapper.createInstanceIdentifier(
754                 connectionInfo, bridge.getBridgeName()));
755         OvsdbTerminationPointAugmentationBuilder ovsdbTerminationBuilder =
756                 createGenericOvsdbTerminationPointAugmentationBuilder();
757         String portName = NetvirtITConstants.PORT_NAME;
758         ovsdbTerminationBuilder.setName(portName);
759         Assert.assertTrue(addTerminationPoint(nodeId, portName, ovsdbTerminationBuilder));
760         InstanceIdentifier<Node> terminationPointIid = getTpIid(connectionInfo, bridge);
761         Node terminationPointNode = mdsalUtils.read(LogicalDatastoreType.OPERATIONAL, terminationPointIid);
762         Assert.assertNotNull(terminationPointNode);
763     }
764
765     /**
766      * Test for basic southbound events to netvirt.
767      * <pre>The test will:
768      * - connect to an OVSDB node and verify it is added to operational
769      * - then verify that br-int was created on the node and stored in operational
770      * - a port is then added to the bridge to verify that it is ignored by netvirt
771      * - remove the bridge
772      * - remove the node and verify it is not in operational
773      * </pre>
774      * @throws InterruptedException
775      */
776     @Ignore
777     @Test
778     public void testNetVirt() throws InterruptedException {
779         ConnectionInfo connectionInfo = getConnectionInfo(addressStr, portStr);
780         Node ovsdbNode = connectOvsdbNode(connectionInfo);
781
782         Thread.sleep(30000);
783         // Verify the pipeline flows were installed
784         PipelineOrchestrator pipelineOrchestrator =
785                 (PipelineOrchestrator) ServiceHelper.getGlobalInstance(PipelineOrchestrator.class, this);
786         assertNotNull("Could not find PipelineOrchestrator Service", pipelineOrchestrator);
787         Node bridgeNode = southbound.getBridgeNode(ovsdbNode, NetvirtITConstants.INTEGRATION_BRIDGE_NAME);
788         assertNotNull("bridge " + NetvirtITConstants.INTEGRATION_BRIDGE_NAME + " was not found", bridgeNode);
789         LOG.info("testNetVirt: bridgeNode: {}", bridgeNode);
790         long datapathId = southbound.getDataPathId(bridgeNode);
791         assertNotEquals("datapathId was not found", datapathId, 0);
792         org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.nodes.NodeBuilder nodeBuilder =
793                 FlowUtils.createNodeBuilder(datapathId);
794
795         List<Service> staticPipeline = pipelineOrchestrator.getStaticPipeline();
796         List<Service> staticPipelineFound = Lists.newArrayList();
797         for (Service service : pipelineOrchestrator.getServiceRegistry().keySet()) {
798             if (staticPipeline.contains(service)) {
799                 staticPipelineFound.add(service);
800             }
801             FlowBuilder flowBuilder = FlowUtils.getPipelineFlow(service.getTable(), (short)0);
802             Flow flow = getFlow(flowBuilder, nodeBuilder, LogicalDatastoreType.CONFIGURATION);
803             assertNotNull("Could not find flow in config", flow);
804             flow = getFlow(flowBuilder, nodeBuilder, LogicalDatastoreType.OPERATIONAL);
805             assertNotNull("Could not find flow in operational", flow);
806         }
807         assertEquals("did not find all expected flows in static pipeline",
808                 staticPipeline.size(), staticPipelineFound.size());
809
810         netVirtAddPort(connectionInfo);
811         Thread.sleep(10000);
812         Assert.assertTrue(deleteBridge(connectionInfo, NetvirtITConstants.INTEGRATION_BRIDGE_NAME));
813         Thread.sleep(10000);
814         Assert.assertTrue(disconnectOvsdbNode(connectionInfo));
815     }
816
817     @Ignore
818     @Test
819     public void testNetVirt2() throws InterruptedException {
820         Thread.sleep(60000);
821     }
822
823     @Ignore
824     @Test
825     public void testReadOvsdbTopologyNodes() throws InterruptedException {
826         Thread.sleep(10000);
827         List<Node> ovsdbNodes = southbound.readOvsdbTopologyNodes();
828         for (Node node : ovsdbNodes) {
829             LOG.info(">>>>> node: {}", node);
830         }
831     }
832
833     private Flow getFlow (
834             FlowBuilder flowBuilder,
835             org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.nodes.NodeBuilder nodeBuilder,
836             LogicalDatastoreType store)
837             throws InterruptedException {
838
839         Flow flow = null;
840         for (int i = 0; i < 10; i++) {
841             flow = FlowUtils.getFlow(flowBuilder, nodeBuilder, dataBroker.newReadOnlyTransaction(), store);
842             if (flow != null) {
843                 LOG.info("getFlow: flow({}): {}", store, flow);
844                 break;
845             }
846             Thread.sleep(1000);
847         }
848         return flow;
849     }
850 }