Moved OF-Controller helper routines to ConnectionService and starting to use the... 25/2925/2
authorMadhu Venugopal <mavenugo@gmail.com>
Wed, 20 Nov 2013 22:41:20 +0000 (14:41 -0800)
committerMadhu Venugopal <mavenugo@gmail.com>
Wed, 20 Nov 2013 23:14:11 +0000 (15:14 -0800)
Also moved some verbose debugs to traces.

Change-Id: I7c68dc599bb193af3905d3cd709381f2fae72b31
Signed-off-by: Madhu Venugopal <mavenugo@gmail.com>
ovsdb/src/main/java/org/opendaylight/ovsdb/lib/jsonrpc/JsonRpcDecoder.java
ovsdb/src/main/java/org/opendaylight/ovsdb/lib/jsonrpc/JsonRpcEndpoint.java
ovsdb/src/main/java/org/opendaylight/ovsdb/plugin/Activator.java
ovsdb/src/main/java/org/opendaylight/ovsdb/plugin/ConfigurationService.java
ovsdb/src/main/java/org/opendaylight/ovsdb/plugin/ConnectionService.java
ovsdb/src/main/java/org/opendaylight/ovsdb/plugin/IConnectionServiceInternal.java

index d76cd84308fb910f3aa6949e04e05bdb5b5eb49d..59b39787034fe25f89486fbae9647e02ee5de3da 100644 (file)
@@ -1,25 +1,27 @@
 package org.opendaylight.ovsdb.lib.jsonrpc;
 
 
-import com.fasterxml.jackson.core.JsonEncoding;
-import com.fasterxml.jackson.core.JsonFactory;
-import com.fasterxml.jackson.core.JsonParser;
-import com.fasterxml.jackson.core.io.IOContext;
-import com.fasterxml.jackson.core.json.ByteSourceJsonBootstrapper;
-import com.fasterxml.jackson.core.util.BufferRecycler;
-import com.fasterxml.jackson.databind.JsonNode;
-import com.fasterxml.jackson.databind.MappingJsonFactory;
 import io.netty.buffer.ByteBuf;
 import io.netty.buffer.ByteBufInputStream;
 import io.netty.channel.ChannelHandlerContext;
 import io.netty.handler.codec.ByteToMessageDecoder;
 import io.netty.handler.codec.TooLongFrameException;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
 
 import java.io.IOException;
 import java.util.List;
 
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import com.fasterxml.jackson.core.JsonEncoding;
+import com.fasterxml.jackson.core.JsonFactory;
+import com.fasterxml.jackson.core.JsonParser;
+import com.fasterxml.jackson.core.io.IOContext;
+import com.fasterxml.jackson.core.json.ByteSourceJsonBootstrapper;
+import com.fasterxml.jackson.core.util.BufferRecycler;
+import com.fasterxml.jackson.databind.JsonNode;
+import com.fasterxml.jackson.databind.MappingJsonFactory;
+
 /**
  * JSON RPC 1.0 compatible decoder capable of decoding JSON messages from a TCP stream.
  * The stream is framed first by inspecting the json for valid end marker (left curly)
@@ -55,7 +57,7 @@ public class JsonRpcDecoder extends ByteToMessageDecoder {
     @Override
     protected void decode(ChannelHandlerContext ctx, ByteBuf buf, List<Object> out) throws Exception {
 
-        logger.debug("readable bytes {}, records read {}, incomplete record bytes {}",
+        logger.trace("readable bytes {}, records read {}, incomplete record bytes {}",
                 buf.readableBytes(), recordsRead, lastRecordBytes);
 
         if (lastRecordBytes == 0) {
@@ -118,7 +120,7 @@ public class JsonRpcDecoder extends ByteToMessageDecoder {
 
     private static void skipSpaces(ByteBuf b) throws IOException {
         while (b.isReadable()) {
-            int ch = (int) b.getByte(b.readerIndex()) & 0xFF;
+            int ch = b.getByte(b.readerIndex()) & 0xFF;
             if (!(ch == ' ' || ch == '\r' || ch == '\n' || ch == '\t')) {
                 return;
             } else {
@@ -135,11 +137,11 @@ public class JsonRpcDecoder extends ByteToMessageDecoder {
     private void print(ByteBuf buf, int startPos, int chars, String message) {
         if (null == message) message = "";
         if (startPos > buf.writerIndex()) {
-            logger.debug("startPos out of bounds");
+            logger.trace("startPos out of bounds");
         }
         byte[] b = new byte[startPos + chars <= buf.writerIndex() ? chars : buf.writerIndex() - startPos];
         buf.getBytes(startPos, b);
-        logger.debug("{} ={}", message, new String(b));
+        logger.trace("{} ={}", message, new String(b));
     }
 
     // copied from Netty decoder
index b92a233b2b19d7cb32d4c9180444199be5f73b38..a1345883d2ea49c91f5dc8f0ea99d0b57411aa23 100644 (file)
@@ -1,5 +1,18 @@
 package org.opendaylight.ovsdb.lib.jsonrpc;
 
+import io.netty.channel.Channel;
+
+import java.lang.reflect.InvocationHandler;
+import java.lang.reflect.Method;
+import java.util.List;
+import java.util.Map;
+import java.util.UUID;
+
+import org.opendaylight.controller.sal.core.Node;
+import org.opendaylight.ovsdb.lib.message.OvsdbRPC;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
 import com.fasterxml.jackson.core.JsonProcessingException;
 import com.fasterxml.jackson.databind.JavaType;
 import com.fasterxml.jackson.databind.JsonNode;
@@ -11,18 +24,6 @@ import com.google.common.reflect.TypeToken;
 import com.google.common.util.concurrent.ListenableFuture;
 import com.google.common.util.concurrent.SettableFuture;
 
-import org.opendaylight.controller.sal.core.Node;
-import org.opendaylight.ovsdb.lib.message.OvsdbRPC;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import java.lang.reflect.InvocationHandler;
-import java.lang.reflect.Method;
-import java.util.List;
-import java.util.Map;
-import java.util.UUID;
-import io.netty.channel.Channel;
-
 public class JsonRpcEndpoint {
 
     protected static final Logger logger = LoggerFactory.getLogger(JsonRpcEndpoint.class);
@@ -93,7 +94,7 @@ public class JsonRpcEndpoint {
                 }
 
                 String s = objectMapper.writeValueAsString(request);
-                logger.debug("{}", s);
+                logger.trace("{}", s);
 
                 SettableFuture<Object> sf = SettableFuture.create();
                 methodContext.put(request.getId(), new CallContext(request, method, sf));
@@ -118,12 +119,12 @@ public class JsonRpcEndpoint {
             JavaType javaType =  TypeFactory.defaultInstance().constructType (retType.getType());
 
             JsonNode result = response.get("result");
-            logger.debug("Response : {}", result.toString());
+            logger.trace("Response : {}", result.toString());
 
             Object result1 = objectMapper.convertValue(result, javaType);
             JsonNode error = response.get("error");
             if (error != null) {
-                logger.debug("Error : {}", error.toString());
+                logger.error("Error : {}", error.toString());
             }
 
             returnCtxt.getFuture().set(result1);
@@ -136,7 +137,7 @@ public class JsonRpcEndpoint {
     public void processRequest(Node node, JsonNode requestJson) {
         JsonRpc10Request request = new JsonRpc10Request(requestJson.get("id").asText());
         request.setMethod(requestJson.get("method").asText());
-        logger.debug("Request : {} {}", requestJson.get("method"), requestJson.get("params"));
+        logger.trace("Request : {} {}", requestJson.get("method"), requestJson.get("params"));
         OvsdbRPC.Callback callback = requestCallbacks.get(node);
         if (callback != null) {
             Method[] methods = callback.getClass().getDeclaredMethods();
index c8f81f67d8b7cf33f6af17b0736f2948c39b42a7..1c8b4a159b274a659fb8fef6ffde8c84f27f136e 100755 (executable)
@@ -74,10 +74,6 @@ public class Activator extends ComponentActivatorAbstractBase {
                     .setService(InventoryServiceInternal.class)
                     .setCallbacks("setInventoryServiceInternal", "unsetInventoryServiceInternal")
                     .setRequired(true));
-            c.add(createServiceDependency()
-                    .setService(IClusterGlobalServices.class)
-                    .setCallbacks("setClusterServices", "unsetClusterServices")
-                    .setRequired(false));
         }
 
         if (imp.equals(ConnectionService.class)) {
@@ -93,6 +89,10 @@ public class Activator extends ComponentActivatorAbstractBase {
                     .setService(InventoryServiceInternal.class)
                     .setCallbacks("setInventoryServiceInternal", "unsetInventoryServiceInternal")
                     .setRequired(true));
+            c.add(createServiceDependency()
+                    .setService(IClusterGlobalServices.class)
+                    .setCallbacks("setClusterServices", "unsetClusterServices")
+                    .setRequired(false));
         }
 
         if (imp.equals(InventoryService.class)) {
index c01f3c55c8d2f064f3d3efe1b8e703aaa721ab46..65ee98651222b4df46b0ef01093f3a3bfa7489e2 100755 (executable)
@@ -2,12 +2,8 @@ package org.opendaylight.ovsdb.plugin;
 
 import java.math.BigInteger;
 import java.net.InetAddress;
-import java.net.NetworkInterface;
-import java.net.SocketException;
 import java.util.ArrayList;
 import java.util.Arrays;
-import java.util.Collections;
-import java.util.Enumeration;
 import java.util.HashMap;
 import java.util.LinkedHashMap;
 import java.util.List;
@@ -15,13 +11,11 @@ import java.util.Map;
 
 import org.eclipse.osgi.framework.console.CommandInterpreter;
 import org.eclipse.osgi.framework.console.CommandProvider;
-import org.opendaylight.controller.clustering.services.IClusterGlobalServices;
 import org.opendaylight.controller.sal.connection.ConnectionConstants;
 import org.opendaylight.controller.sal.core.Node;
 import org.opendaylight.controller.sal.core.NodeConnector;
 import org.opendaylight.controller.sal.networkconfig.bridgedomain.ConfigConstants;
 import org.opendaylight.controller.sal.networkconfig.bridgedomain.IPluginInBridgeDomainConfigService;
-import org.opendaylight.controller.sal.utils.NetUtils;
 import org.opendaylight.controller.sal.utils.Status;
 import org.opendaylight.controller.sal.utils.StatusCode;
 import org.opendaylight.ovsdb.lib.database.OVSInstance;
@@ -69,7 +63,6 @@ public class ConfigurationService implements IPluginInBridgeDomainConfigService,
 
     IConnectionServiceInternal connectionService;
     InventoryServiceInternal inventoryServiceInternal;
-    private IClusterGlobalServices clusterServices;
     boolean forceConnect = false;
 
     void init() {
@@ -129,16 +122,6 @@ public class ConfigurationService implements IPluginInBridgeDomainConfigService,
         }
     }
 
-    public void setClusterServices(IClusterGlobalServices i) {
-        this.clusterServices = i;
-    }
-
-    public void unsetClusterServices(IClusterGlobalServices i) {
-        if (this.clusterServices == i) {
-            this.clusterServices = null;
-        }
-    }
-
     private Connection getConnection (Node node) {
         Connection connection = connectionService.getConnection(node);
         if (connection == null || !connection.getChannel().isActive()) {
@@ -677,160 +660,24 @@ public class ConfigurationService implements IPluginInBridgeDomainConfigService,
         return null;
     }
 
-    private short getControllerOFPort() {
-        Short defaultOpenFlowPort = 6633;
-        Short openFlowPort = defaultOpenFlowPort;
-        String portString = System.getProperty("of.listenPort");
-        if (portString != null) {
-            try {
-                openFlowPort = Short.decode(portString).shortValue();
-            } catch (NumberFormatException e) {
-                logger.warn("Invalid port:{}, use default({})", portString,
-                        openFlowPort);
-            }
-        }
-        return openFlowPort;
-    }
-
-    private List<InetAddress> getControllerIPAddresses() {
-        List<InetAddress> controllers = null;
-        if (clusterServices != null) {
-            controllers = clusterServices.getClusteredControllers();
-            if (controllers != null && controllers.size() > 0) {
-                if (controllers.size() == 1) {
-                    InetAddress controller = controllers.get(0);
-                    if (!controller.equals(InetAddress.getLoopbackAddress())) {
-                        return controllers;
-                    }
-                } else {
-                    return controllers;
-                }
-            }
-        }
-
-        controllers = new ArrayList<InetAddress>();
-        String addressString = System.getProperty("of.address");
-        if (addressString != null) {
-            InetAddress controllerIP = null;
-            try {
-                controllerIP = InetAddress.getByName(addressString);
-                if (controllerIP != null) {
-                    controllers.add(controllerIP);
-                    return controllers;
-                }
-            } catch (Exception e) {
-                logger.debug("Invalid IP: {}, use wildcard *", addressString);
-            }
-        }
-
-        Enumeration<NetworkInterface> nets;
-        try {
-            nets = NetworkInterface.getNetworkInterfaces();
-            for (NetworkInterface netint : Collections.list(nets)) {
-                Enumeration<InetAddress> inetAddresses = netint.getInetAddresses();
-                for (InetAddress inetAddress : Collections.list(inetAddresses)) {
-                    if (!inetAddress.isLoopbackAddress() &&
-                            NetUtils.isIPv4AddressValid(inetAddress.getHostAddress())) {
-                        controllers.add(inetAddress);
-                    }
-                }
-            }
-        } catch (SocketException e) {
-            controllers.add(InetAddress.getLoopbackAddress());
+    Boolean setBridgeOFController(Node node, String bridgeIdentifier) {
+        if (connectionService == null) {
+            logger.error("Couldn't refer to the ConnectionService");
+            return false;
         }
-        return controllers;
-    }
 
-    public Boolean setBridgeOFController(Node node, String bridgeIdentifier) {
         try{
-            if (connectionService == null) {
-                logger.error("Couldn't refer to the ConnectionService");
-                return false;
-            }
-            Connection connection = this.getConnection(node);
-            if (connection == null) {
-                return false;
-            }
-
-            if (connection != null) {
-                List<InetAddress> ofControllerAddrs = getControllerIPAddresses();
-                short ofControllerPort = getControllerOFPort();
-                OvsDBSet<UUID> controllerUUIDs = new OvsDBSet<UUID>();
-                List<Operation> controllerInsertOperations = new ArrayList<Operation>();
-                Map<String, Table<?>> controllerCache = inventoryServiceInternal.getTableCache(node, Controller.NAME.getName());
-
-                int count = 0;
-                for (InetAddress ofControllerAddress : ofControllerAddrs) {
-                    String cntrlUuid = null;
-                    String newController = "tcp:"+ofControllerAddress.getHostAddress()+":"+ofControllerPort;
-                    if (controllerCache != null) {
-                        for (String uuid : controllerCache.keySet()) {
-                            Controller controller = (Controller)controllerCache.get(uuid);
-                            if (controller.getTarget().equals(newController)) {
-                                cntrlUuid = uuid;
-                                controllerUUIDs.add(new UUID(uuid));
-                                break;
-                            }
-                        }
-                    }
-                    if (cntrlUuid == null) {
-                        count++;
-                        String uuid_name = "new_controller_"+count;
-                        controllerUUIDs.add(new UUID(uuid_name));
-                        Controller controllerRow = new Controller();
-                        controllerRow.setTarget(newController);
-                        InsertOperation addCtlRequest = new InsertOperation(Controller.NAME.getName(), uuid_name, controllerRow);
-                        controllerInsertOperations.add(addCtlRequest);
-                    }
-                }
-                String brCntrlUuid = null;
-                Map<String, Table<?>> brTableCache = inventoryServiceInternal.getTableCache(node, Bridge.NAME.getName());
-                for (String uuid : brTableCache.keySet()) {
-                    Bridge bridge = (Bridge)brTableCache.get(uuid);
-                    if (bridge.getName().contains(bridgeIdentifier)) {
-                        brCntrlUuid = uuid;
-                    }
-                }
-                Operation addControlRequest = null;
-                Mutation bm = new Mutation("controller", Mutator.INSERT, controllerUUIDs);
-                List<Mutation> mutations = new ArrayList<Mutation>();
-                mutations.add(bm);
-
-                UUID uuid = new UUID(brCntrlUuid);
-                Condition condition = new Condition("_uuid", Function.EQUALS, uuid);
-                List<Condition> where = new ArrayList<Condition>();
-                where.add(condition);
-                addControlRequest = new MutateOperation(Bridge.NAME.getName(), where, mutations);
-
-                TransactBuilder transaction = new TransactBuilder();
-                transaction.addOperations(controllerInsertOperations);
-                transaction.addOperation(addControlRequest);
-
-                ListenableFuture<List<OperationResult>> transResponse = connection.getRpc().transact(transaction);
-                List<OperationResult> tr = transResponse.get();
-                List<Operation> requests = transaction.getRequests();
-                Status status = new Status(StatusCode.SUCCESS);
-                for (int i = 0; i < tr.size() ; i++) {
-                    if (i < requests.size()) requests.get(i).setResult(tr.get(i));
-                    if (tr.get(i) != null && tr.get(i).getError() != null && tr.get(i).getError().trim().length() > 0) {
-                        OperationResult result = tr.get(i);
-                        status = new Status(StatusCode.BADREQUEST, result.getError() + " : " + result.getDetails());
-                    }
-                }
-
-                if (tr.size() > requests.size()) {
-                    OperationResult result = tr.get(tr.size()-1);
-                    logger.error("Error creating Bridge : {}\n Error : {}\n Details : {}", bridgeIdentifier,
-                            result.getError(),
-                            result.getDetails());
-                    status = new Status(StatusCode.BADREQUEST, result.getError() + " : " + result.getDetails());
-
+            Map<String, Table<?>> brTableCache = inventoryServiceInternal.getTableCache(node, Bridge.NAME.getName());
+            for (String uuid : brTableCache.keySet()) {
+                Bridge bridge = (Bridge)brTableCache.get(uuid);
+                if (bridge.getName().contains(bridgeIdentifier)) {
+                    return connectionService.setOFController(node, uuid);
                 }
             }
-        }catch(Exception e){
+        } catch(Exception e) {
             e.printStackTrace();
         }
-        return true;
+        return false;
     }
 
     @Override
@@ -1283,8 +1130,23 @@ public class ConfigurationService implements IPluginInBridgeDomainConfigService,
             if (brTable == null ||  brTable.get(bridge_uuid) == null) {
                 return new Status(StatusCode.NOTFOUND, "Bridge with UUID "+bridge_uuid+" Not found");
             }
-            String newController = "new_controller";
-            UUID controllerUUID = new UUID(newController);
+
+            Map<String, Table<?>> controllerCache = inventoryServiceInternal.getTableCache(node, Controller.NAME.getName());
+
+            String uuid_name = "new_controller";
+            boolean controllerExists = false;
+            if (controllerCache != null) {
+                for (String uuid : controllerCache.keySet()) {
+                    Controller controller = (Controller)controllerCache.get(uuid);
+                    if (controller.getTarget().equals(row.getTarget())) {
+                        uuid_name = uuid;
+                        controllerExists = true;
+                        break;
+                    }
+                }
+            }
+
+            UUID controllerUUID = new UUID(uuid_name);
             Mutation bm = new Mutation("controller", Mutator.INSERT, controllerUUID);
             List<Mutation> mutations = new ArrayList<Mutation>();
             mutations.add(bm);
@@ -1294,13 +1156,17 @@ public class ConfigurationService implements IPluginInBridgeDomainConfigService,
             List<Condition> where = new ArrayList<Condition>();
             where.add(condition);
             Operation addBrMutRequest = new MutateOperation(Bridge.NAME.getName(), where, mutations);
-
-            InsertOperation addControllerRequest = new InsertOperation(Controller.NAME.getName(), newController, row);
+            InsertOperation addControllerRequest = null;
 
             TransactBuilder transaction = new TransactBuilder();
-            transaction.addOperations(new ArrayList<Operation>
-            (Arrays.asList(addBrMutRequest, addControllerRequest)));
-            int portInsertIndex = transaction.getRequests().indexOf(addControllerRequest);
+            transaction.addOperation(addBrMutRequest);
+            int portInsertIndex = -1;
+            if (!controllerExists) {
+                addControllerRequest = new InsertOperation(Controller.NAME.getName(), uuid_name, row);
+                transaction.addOperation(addControllerRequest);
+                portInsertIndex = transaction.getRequests().indexOf(addControllerRequest);
+            }
+
             ListenableFuture<List<OperationResult>> transResponse = connection.getRpc().transact(transaction);
             List<OperationResult> tr = transResponse.get();
             List<Operation> requests = transaction.getRequests();
@@ -1321,10 +1187,13 @@ public class ConfigurationService implements IPluginInBridgeDomainConfigService,
                 status = new Status(StatusCode.BADREQUEST, result.getError() + " : " + result.getDetails());
             }
             if (status.isSuccess()) {
-                uuid = tr.get(portInsertIndex).getUuid();
-                status = new Status(StatusCode.SUCCESS, uuid.toString());
+                if (controllerExists) {
+                    status = new Status(StatusCode.SUCCESS, uuid_name);
+                } else {
+                    uuid = tr.get(portInsertIndex).getUuid();
+                    status = new Status(StatusCode.SUCCESS, uuid.toString());
+                }
             }
-
             return status;
         } catch (Exception e) {
             e.printStackTrace();
index 61f64b65f04c719ada181f696147b71dcefea4d9..00deaa6514a15036637a91c62819595e6d86736a 100755 (executable)
@@ -20,7 +20,12 @@ import io.netty.util.CharsetUtil;
 
 import java.net.InetAddress;
 import java.net.InetSocketAddress;
+import java.net.NetworkInterface;
+import java.net.SocketException;
+import java.util.ArrayList;
 import java.util.Arrays;
+import java.util.Collections;
+import java.util.Enumeration;
 import java.util.HashSet;
 import java.util.List;
 import java.util.Map;
@@ -29,10 +34,13 @@ import java.util.concurrent.ConcurrentHashMap;
 import java.util.concurrent.ConcurrentMap;
 import java.util.concurrent.ExecutionException;
 
+import org.opendaylight.controller.clustering.services.IClusterGlobalServices;
 import org.opendaylight.controller.sal.connection.ConnectionConstants;
 import org.opendaylight.controller.sal.connection.IPluginInConnectionService;
 import org.opendaylight.controller.sal.core.Node;
 import org.opendaylight.controller.sal.core.Property;
+import org.opendaylight.controller.sal.utils.NetUtils;
+import org.opendaylight.controller.sal.utils.ServiceHelper;
 import org.opendaylight.controller.sal.utils.Status;
 import org.opendaylight.controller.sal.utils.StatusCode;
 import org.opendaylight.ovsdb.lib.database.DatabaseSchema;
@@ -43,6 +51,8 @@ import org.opendaylight.ovsdb.lib.message.MonitorRequestBuilder;
 import org.opendaylight.ovsdb.lib.message.OvsdbRPC;
 import org.opendaylight.ovsdb.lib.message.TableUpdates;
 import org.opendaylight.ovsdb.lib.message.UpdateNotification;
+import org.opendaylight.ovsdb.lib.table.Bridge;
+import org.opendaylight.ovsdb.lib.table.Controller;
 import org.opendaylight.ovsdb.lib.table.Open_vSwitch;
 import org.opendaylight.ovsdb.lib.table.internal.Table;
 import org.opendaylight.ovsdb.lib.table.internal.Tables;
@@ -294,6 +304,8 @@ public class ConnectionService implements IPluginInConnectionService, IConnectio
         UpdateNotification monitor = new UpdateNotification();
         monitor.setUpdate(updates);
         this.update(connection.getNode(), monitor);
+        // With the existing bridges learnt, now it is time to update the OF Controller connections.
+        this.updateOFControllers(connection.getNode());
     }
 
     private void startOvsdbManager() {
@@ -346,6 +358,118 @@ public class ConnectionService implements IPluginInConnectionService, IConnectio
         }
     }
 
+    private IClusterGlobalServices clusterServices;
+
+    public void setClusterServices(IClusterGlobalServices i) {
+        this.clusterServices = i;
+    }
+
+    public void unsetClusterServices(IClusterGlobalServices i) {
+        if (this.clusterServices == i) {
+            this.clusterServices = null;
+        }
+    }
+
+    private List<InetAddress> getControllerIPAddresses() {
+        List<InetAddress> controllers = null;
+        if (clusterServices != null) {
+            controllers = clusterServices.getClusteredControllers();
+            if (controllers != null && controllers.size() > 0) {
+                if (controllers.size() == 1) {
+                    InetAddress controller = controllers.get(0);
+                    if (!controller.equals(InetAddress.getLoopbackAddress())) {
+                        return controllers;
+                    }
+                } else {
+                    return controllers;
+                }
+            }
+        }
+
+        controllers = new ArrayList<InetAddress>();
+        String addressString = System.getProperty("ovsdb.controller.address");
+        if (addressString == null) addressString = System.getProperty("of.address");
+
+        if (addressString != null) {
+            InetAddress controllerIP = null;
+            try {
+                controllerIP = InetAddress.getByName(addressString);
+                if (controllerIP != null) {
+                    controllers.add(controllerIP);
+                    return controllers;
+                }
+            } catch (Exception e) {
+                logger.debug("Invalid IP: {}, use wildcard *", addressString);
+            }
+        }
+
+        Enumeration<NetworkInterface> nets;
+        try {
+            nets = NetworkInterface.getNetworkInterfaces();
+            for (NetworkInterface netint : Collections.list(nets)) {
+                Enumeration<InetAddress> inetAddresses = netint.getInetAddresses();
+                for (InetAddress inetAddress : Collections.list(inetAddresses)) {
+                    if (!inetAddress.isLoopbackAddress() &&
+                            NetUtils.isIPv4AddressValid(inetAddress.getHostAddress())) {
+                        controllers.add(inetAddress);
+                    }
+                }
+            }
+        } catch (SocketException e) {
+            controllers.add(InetAddress.getLoopbackAddress());
+        }
+        return controllers;
+    }
+
+    private short getControllerOFPort() {
+        Short defaultOpenFlowPort = 6633;
+        Short openFlowPort = defaultOpenFlowPort;
+        String portString = System.getProperty("of.listenPort");
+        if (portString != null) {
+            try {
+                openFlowPort = Short.decode(portString).shortValue();
+            } catch (NumberFormatException e) {
+                logger.warn("Invalid port:{}, use default({})", portString,
+                        openFlowPort);
+            }
+        }
+        return openFlowPort;
+    }
+
+    @Override
+    public Boolean setOFController(Node node, String bridgeUUID) throws InterruptedException, ExecutionException {
+        Connection connection = this.getConnection(node);
+        if (connection == null) {
+            return false;
+        }
+
+        if (connection != null) {
+            List<InetAddress> ofControllerAddrs = this.getControllerIPAddresses();
+            short ofControllerPort = getControllerOFPort();
+            for (InetAddress ofControllerAddress : ofControllerAddrs) {
+                String newController = "tcp:"+ofControllerAddress.getHostAddress()+":"+ofControllerPort;
+                Controller controllerRow = new Controller();
+                controllerRow.setTarget(newController);
+                OVSDBConfigService ovsdbTable = (OVSDBConfigService)ServiceHelper.getGlobalInstance(OVSDBConfigService.class, this);
+                if (ovsdbTable != null) {
+                    ovsdbTable.insertRow(node, Controller.NAME.getName(), bridgeUUID, controllerRow);
+                }
+            }
+        }
+        return true;
+    }
+
+    private void updateOFControllers (Node node) {
+        Map<String, Table<?>> bridges = inventoryServiceInternal.getTableCache(node, Bridge.NAME.getName());
+        for (String bridgeUUID : bridges.keySet()) {
+            try {
+                this.setOFController(node, bridgeUUID);
+            } catch (Exception e) {
+                e.printStackTrace();
+            }
+        }
+    }
+
     @Override
     public void update(Node node, UpdateNotification updateNotification) {
         if (updateNotification == null) return;
index 9d84100f30decb5f7c695a27172bc8abb01f7791..3aa0294af298b74f69f7751cc60d3bd0c4c98591 100755 (executable)
@@ -1,6 +1,7 @@
 package org.opendaylight.ovsdb.plugin;
 
 import java.util.Map;
+import java.util.concurrent.ExecutionException;
 
 import org.opendaylight.controller.sal.connection.ConnectionConstants;
 import org.opendaylight.controller.sal.core.Node;
@@ -8,4 +9,5 @@ import org.opendaylight.controller.sal.core.Node;
 public interface IConnectionServiceInternal {
     public Connection getConnection(Node node);
     public Node connect(String identifier, Map<ConnectionConstants, String> params);
+    public Boolean setOFController(Node node, String bridgeUUID) throws InterruptedException, ExecutionException;
 }