You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@cloudstack.apache.org by ah...@apache.org on 2013/12/12 22:01:14 UTC

[14/48] All Checkstyle problems corrected

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/be5e5cc6/plugins/network-elements/ovs/src/com/cloud/network/element/OvsElement.java
----------------------------------------------------------------------
diff --git a/plugins/network-elements/ovs/src/com/cloud/network/element/OvsElement.java b/plugins/network-elements/ovs/src/com/cloud/network/element/OvsElement.java
index 2641d54..ea46f93 100644
--- a/plugins/network-elements/ovs/src/com/cloud/network/element/OvsElement.java
+++ b/plugins/network-elements/ovs/src/com/cloud/network/element/OvsElement.java
@@ -28,6 +28,8 @@ import javax.naming.ConfigurationException;
 
 import org.apache.log4j.Logger;
 
+import com.google.gson.Gson;
+
 import com.cloud.agent.api.StartupCommand;
 import com.cloud.agent.api.StartupOvsCommand;
 import com.cloud.agent.api.to.LoadBalancerTO;
@@ -71,189 +73,188 @@ import com.cloud.vm.NicProfile;
 import com.cloud.vm.ReservationContext;
 import com.cloud.vm.VirtualMachineProfile;
 import com.cloud.vm.dao.DomainRouterDao;
-import com.google.gson.Gson;
 
-@Local(value = { NetworkElement.class, ConnectivityProvider.class,
-		SourceNatServiceProvider.class, StaticNatServiceProvider.class,
-		PortForwardingServiceProvider.class, IpDeployer.class })
+@Local(value = {NetworkElement.class, ConnectivityProvider.class,
+    SourceNatServiceProvider.class, StaticNatServiceProvider.class,
+    PortForwardingServiceProvider.class, IpDeployer.class})
 public class OvsElement extends AdapterBase implements NetworkElement,
-		OvsElementService, ConnectivityProvider, ResourceStateAdapter,
-		PortForwardingServiceProvider, LoadBalancingServiceProvider,
-		StaticNatServiceProvider, IpDeployer {
-	@Inject
-	OvsTunnelManager _ovsTunnelMgr;
-	@Inject
-	NetworkModel _networkModel;
-	@Inject
-	NetworkServiceMapDao _ntwkSrvcDao;
-	@Inject
-	ResourceManager _resourceMgr;
-	@Inject
-	DomainRouterDao _routerDao;
-	@Inject
-	VpcVirtualNetworkApplianceManager _routerMgr;
-
-	private static final Logger s_logger = Logger.getLogger(OvsElement.class);
-	private static final Map<Service, Map<Capability, String>> capabilities = setCapabilities();
-
-	@Override
-	public Map<Service, Map<Capability, String>> getCapabilities() {
-		return capabilities;
-	}
-
-	@Override
-	public Provider getProvider() {
-		return Provider.Ovs;
-	}
-
-	protected boolean canHandle(Network network, Service service) {
-		s_logger.debug("Checking if OvsElement can handle service "
-				+ service.getName() + " on network " + network.getDisplayText());
-		if (network.getBroadcastDomainType() != BroadcastDomainType.Vswitch) {
-			return false;
-		}
-
-		if (!_networkModel.isProviderForNetwork(getProvider(), network.getId())) {
-			s_logger.debug("OvsElement is not a provider for network "
-					+ network.getDisplayText());
-			return false;
-		}
-
-		if (!_ntwkSrvcDao.canProviderSupportServiceInNetwork(network.getId(),
-				service, Network.Provider.Ovs)) {
-			s_logger.debug("OvsElement can't provide the " + service.getName()
-					+ " service on network " + network.getDisplayText());
-			return false;
-		}
-
-		return true;
-	}
-
-	@Override
-	public boolean configure(String name, Map<String, Object> params)
-			throws ConfigurationException {
-		super.configure(name, params);
-		_resourceMgr.registerResourceStateAdapter(name, this);
-		return true;
-	}
-
-	@Override
-	public boolean implement(Network network, NetworkOffering offering,
-			DeployDestination dest, ReservationContext context)
-			throws ConcurrentOperationException, ResourceUnavailableException,
-			InsufficientCapacityException {
-		s_logger.debug("entering OvsElement implement function for network "
-				+ network.getDisplayText() + " (state " + network.getState()
-				+ ")");
-
-		if (!canHandle(network, Service.Connectivity)) {
-			return false;
-		}
-		return true;
-	}
-
-	@Override
-	public boolean prepare(Network network, NicProfile nic,
-			VirtualMachineProfile vm,
-			DeployDestination dest, ReservationContext context)
-			throws ConcurrentOperationException, ResourceUnavailableException,
-			InsufficientCapacityException {
-		if (!canHandle(network, Service.Connectivity)) {
-			return false;
-		}
-
-		if (nic.getBroadcastType() != Networks.BroadcastDomainType.Vswitch) {
-			return false;
-		}
-
-		if (nic.getTrafficType() != Networks.TrafficType.Guest) {
-			return false;
-		}
-
-		_ovsTunnelMgr.VmCheckAndCreateTunnel(vm, network, dest);
-
-		return true;
-	}
-
-	@Override
-	public boolean release(Network network, NicProfile nic,
-			VirtualMachineProfile vm,
-			ReservationContext context) throws ConcurrentOperationException,
-			ResourceUnavailableException {
-		if (!canHandle(network, Service.Connectivity)) {
-			return false;
-		}
-		if (nic.getBroadcastType() != Networks.BroadcastDomainType.Vswitch) {
-			return false;
-		}
-
-		if (nic.getTrafficType() != Networks.TrafficType.Guest) {
-			return false;
-		}
-
-		_ovsTunnelMgr.CheckAndDestroyTunnel(vm.getVirtualMachine(), network);
-		return true;
-	}
-
-	@Override
-	public boolean shutdown(Network network, ReservationContext context,
-			boolean cleanup) throws ConcurrentOperationException,
-			ResourceUnavailableException {
-		if (!canHandle(network, Service.Connectivity)) {
-			return false;
-		}
-		return true;
-	}
-
-	@Override
-	public boolean destroy(Network network, ReservationContext context)
-			throws ConcurrentOperationException, ResourceUnavailableException {
-		if (!canHandle(network, Service.Connectivity)) {
-			return false;
-		}
-		return true;
-	}
-
-	@Override
-	public boolean isReady(PhysicalNetworkServiceProvider provider) {
-		return true;
-	}
-
-	@Override
-	public boolean shutdownProviderInstances(
-			PhysicalNetworkServiceProvider provider, ReservationContext context)
-			throws ConcurrentOperationException, ResourceUnavailableException {
-		return true;
-	}
-
-	@Override
-	public boolean canEnableIndividualServices() {
-		return true;
-	}
-
-	@Override
-	public boolean verifyServicesCombination(Set<Service> services) {
-		if (!services.contains(Service.Connectivity)) {
-			s_logger.warn("Unable to provide services without Connectivity service enabled for this element");
-			return false;
-		}
-
-		return true;
-	}
-
-	private static Map<Service, Map<Capability, String>> setCapabilities() {
-		Map<Service, Map<Capability, String>> capabilities = new HashMap<Service, Map<Capability, String>>();
-
-		// L2 Support : SDN provisioning
-		capabilities.put(Service.Connectivity, null);
-
-		// L3 Support : Port Forwarding
-		 capabilities.put(Service.PortForwarding, null);
-
-		// L3 support : StaticNat
-		capabilities.put(Service.StaticNat, null);
-
-		// L3 support : Load Balancer
+        OvsElementService, ConnectivityProvider, ResourceStateAdapter,
+        PortForwardingServiceProvider, LoadBalancingServiceProvider,
+        StaticNatServiceProvider, IpDeployer {
+    @Inject
+    OvsTunnelManager _ovsTunnelMgr;
+    @Inject
+    NetworkModel _networkModel;
+    @Inject
+    NetworkServiceMapDao _ntwkSrvcDao;
+    @Inject
+    ResourceManager _resourceMgr;
+    @Inject
+    DomainRouterDao _routerDao;
+    @Inject
+    VpcVirtualNetworkApplianceManager _routerMgr;
+
+    private static final Logger s_logger = Logger.getLogger(OvsElement.class);
+    private static final Map<Service, Map<Capability, String>> capabilities = setCapabilities();
+
+    @Override
+    public Map<Service, Map<Capability, String>> getCapabilities() {
+        return capabilities;
+    }
+
+    @Override
+    public Provider getProvider() {
+        return Provider.Ovs;
+    }
+
+    protected boolean canHandle(Network network, Service service) {
+        s_logger.debug("Checking if OvsElement can handle service "
+            + service.getName() + " on network " + network.getDisplayText());
+        if (network.getBroadcastDomainType() != BroadcastDomainType.Vswitch) {
+            return false;
+        }
+
+        if (!_networkModel.isProviderForNetwork(getProvider(), network.getId())) {
+            s_logger.debug("OvsElement is not a provider for network "
+                + network.getDisplayText());
+            return false;
+        }
+
+        if (!_ntwkSrvcDao.canProviderSupportServiceInNetwork(network.getId(),
+            service, Network.Provider.Ovs)) {
+            s_logger.debug("OvsElement can't provide the " + service.getName()
+                + " service on network " + network.getDisplayText());
+            return false;
+        }
+
+        return true;
+    }
+
+    @Override
+    public boolean configure(String name, Map<String, Object> params)
+        throws ConfigurationException {
+        super.configure(name, params);
+        _resourceMgr.registerResourceStateAdapter(name, this);
+        return true;
+    }
+
+    @Override
+    public boolean implement(Network network, NetworkOffering offering,
+        DeployDestination dest, ReservationContext context)
+        throws ConcurrentOperationException, ResourceUnavailableException,
+        InsufficientCapacityException {
+        s_logger.debug("entering OvsElement implement function for network "
+            + network.getDisplayText() + " (state " + network.getState()
+            + ")");
+
+        if (!canHandle(network, Service.Connectivity)) {
+            return false;
+        }
+        return true;
+    }
+
+    @Override
+    public boolean prepare(Network network, NicProfile nic,
+        VirtualMachineProfile vm,
+        DeployDestination dest, ReservationContext context)
+        throws ConcurrentOperationException, ResourceUnavailableException,
+        InsufficientCapacityException {
+        if (!canHandle(network, Service.Connectivity)) {
+            return false;
+        }
+
+        if (nic.getBroadcastType() != Networks.BroadcastDomainType.Vswitch) {
+            return false;
+        }
+
+        if (nic.getTrafficType() != Networks.TrafficType.Guest) {
+            return false;
+        }
+
+        _ovsTunnelMgr.VmCheckAndCreateTunnel(vm, network, dest);
+
+        return true;
+    }
+
+    @Override
+    public boolean release(Network network, NicProfile nic,
+        VirtualMachineProfile vm,
+        ReservationContext context) throws ConcurrentOperationException,
+        ResourceUnavailableException {
+        if (!canHandle(network, Service.Connectivity)) {
+            return false;
+        }
+        if (nic.getBroadcastType() != Networks.BroadcastDomainType.Vswitch) {
+            return false;
+        }
+
+        if (nic.getTrafficType() != Networks.TrafficType.Guest) {
+            return false;
+        }
+
+        _ovsTunnelMgr.CheckAndDestroyTunnel(vm.getVirtualMachine(), network);
+        return true;
+    }
+
+    @Override
+    public boolean shutdown(Network network, ReservationContext context,
+        boolean cleanup) throws ConcurrentOperationException,
+        ResourceUnavailableException {
+        if (!canHandle(network, Service.Connectivity)) {
+            return false;
+        }
+        return true;
+    }
+
+    @Override
+    public boolean destroy(Network network, ReservationContext context)
+        throws ConcurrentOperationException, ResourceUnavailableException {
+        if (!canHandle(network, Service.Connectivity)) {
+            return false;
+        }
+        return true;
+    }
+
+    @Override
+    public boolean isReady(PhysicalNetworkServiceProvider provider) {
+        return true;
+    }
+
+    @Override
+    public boolean shutdownProviderInstances(
+        PhysicalNetworkServiceProvider provider, ReservationContext context)
+        throws ConcurrentOperationException, ResourceUnavailableException {
+        return true;
+    }
+
+    @Override
+    public boolean canEnableIndividualServices() {
+        return true;
+    }
+
+    @Override
+    public boolean verifyServicesCombination(Set<Service> services) {
+        if (!services.contains(Service.Connectivity)) {
+            s_logger.warn("Unable to provide services without Connectivity service enabled for this element");
+            return false;
+        }
+
+        return true;
+    }
+
+    private static Map<Service, Map<Capability, String>> setCapabilities() {
+        Map<Service, Map<Capability, String>> capabilities = new HashMap<Service, Map<Capability, String>>();
+
+        // L2 Support : SDN provisioning
+        capabilities.put(Service.Connectivity, null);
+
+        // L3 Support : Port Forwarding
+        capabilities.put(Service.PortForwarding, null);
+
+        // L3 support : StaticNat
+        capabilities.put(Service.StaticNat, null);
+
+        // L3 support : Load Balancer
         // Set capabilities for LB service
         Map<Capability, String> lbCapabilities = new HashMap<Capability, String>();
         lbCapabilities.put(Capability.SupportedLBAlgorithms, "roundrobin,leastconn,source");
@@ -264,9 +265,9 @@ public class OvsElement extends AdapterBase implements NetworkElement,
 
         capabilities.put(Service.Lb, lbCapabilities);
 
-		return capabilities;
-	}
-	
+        return capabilities;
+    }
+
     public static String getHAProxyStickinessCapability() {
         LbStickinessMethod method;
         List<LbStickinessMethod> methodList = new ArrayList<LbStickinessMethod>(1);
@@ -274,89 +275,90 @@ public class OvsElement extends AdapterBase implements NetworkElement,
         method = new LbStickinessMethod(StickinessMethodType.LBCookieBased, "This is loadbalancer cookie based stickiness method.");
         method.addParam("cookie-name", false, "Cookie name passed in http header by the LB to the client.", false);
         method.addParam("mode", false,
-                "Valid values: insert, rewrite, prefix. Default value: insert.  In the insert mode cookie will be created" +
+            "Valid values: insert, rewrite, prefix. Default value: insert.  In the insert mode cookie will be created" +
                 " by the LB. In other modes, cookie will be created by the server and LB modifies it.", false);
         method.addParam(
-                "nocache",
-                false,
-                "This option is recommended in conjunction with the insert mode when there is a cache between the client" +
+            "nocache",
+            false,
+            "This option is recommended in conjunction with the insert mode when there is a cache between the client" +
                 " and HAProxy, as it ensures that a cacheable response will be tagged non-cacheable if  a cookie needs " +
                 "to be inserted. This is important because if all persistence cookies are added on a cacheable home page" +
                 " for instance, then all customers will then fetch the page from an outer cache and will all share the " +
                 "same persistence cookie, leading to one server receiving much more traffic than others. See also the " +
                 "insert and postonly options. ",
-                true);
+            true);
         method.addParam(
-                "indirect",
-                false,
-                "When this option is specified in insert mode, cookies will only be added when the server was not reached" +
+            "indirect",
+            false,
+            "When this option is specified in insert mode, cookies will only be added when the server was not reached" +
                 " after a direct access, which means that only when a server is elected after applying a load-balancing algorithm," +
                 " or after a redispatch, then the cookie  will be inserted. If the client has all the required information" +
                 " to connect to the same server next time, no further cookie will be inserted. In all cases, when the " +
                 "indirect option is used in insert mode, the cookie is always removed from the requests transmitted to " +
                 "the server. The persistence mechanism then becomes totally transparent from the application point of view.",
-                true);
+            true);
         method.addParam(
-                "postonly",
-                false,
-                "This option ensures that cookie insertion will only be performed on responses to POST requests. It is an" +
+            "postonly",
+            false,
+            "This option ensures that cookie insertion will only be performed on responses to POST requests. It is an" +
                 " alternative to the nocache option, because POST responses are not cacheable, so this ensures that the " +
                 "persistence cookie will never get cached.Since most sites do not need any sort of persistence before the" +
                 " first POST which generally is a login request, this is a very efficient method to optimize caching " +
                 "without risking to find a persistence cookie in the cache. See also the insert and nocache options.",
-                true);
+            true);
         method.addParam(
-                "domain",
-                false,
-                "This option allows to specify the domain at which a cookie is inserted. It requires exactly one parameter:" +
+            "domain",
+            false,
+            "This option allows to specify the domain at which a cookie is inserted. It requires exactly one parameter:" +
                 " a valid domain name. If the domain begins with a dot, the browser is allowed to use it for any host " +
                 "ending with that name. It is also possible to specify several domain names by invoking this option multiple" +
                 " times. Some browsers might have small limits on the number of domains, so be careful when doing that. " +
                 "For the record, sending 10 domains to MSIE 6 or Firefox 2 works as expected.",
-                false);
+            false);
         methodList.add(method);
 
         method = new LbStickinessMethod(StickinessMethodType.AppCookieBased,
-                "This is App session based sticky method. Define session stickiness on an existing application cookie. " +
+            "This is App session based sticky method. Define session stickiness on an existing application cookie. " +
                 "It can be used only for a specific http traffic");
         method.addParam("cookie-name", false, "This is the name of the cookie used by the application and which LB will " +
-        		"have to learn for each new session. Default value: Auto geneared based on ip", false);
+            "have to learn for each new session. Default value: Auto geneared based on ip", false);
         method.addParam("length", false, "This is the max number of characters that will be memorized and checked in " +
-        		"each cookie value. Default value:52", false);
+            "each cookie value. Default value:52", false);
         method.addParam(
-                "holdtime",
-                false,
-                "This is the time after which the cookie will be removed from memory if unused. The value should be in " +
+            "holdtime",
+            false,
+            "This is the time after which the cookie will be removed from memory if unused. The value should be in " +
                 "the format Example : 20s or 30m  or 4h or 5d . only seconds(s), minutes(m) hours(h) and days(d) are valid," +
                 " cannot use th combinations like 20h30m. Default value:3h ",
-                false);
+            false);
         method.addParam(
-                "request-learn",
-                false,
-                "If this option is specified, then haproxy will be able to learn the cookie found in the request in case the server does not specify any in response. This is typically what happens with PHPSESSID cookies, or when haproxy's session expires before the application's session and the correct server is selected. It is recommended to specify this option to improve reliability",
-                true);
+            "request-learn",
+            false,
+            "If this option is specified, then haproxy will be able to learn the cookie found in the request in case the server does not specify any in response. This is typically what happens with PHPSESSID cookies, or when haproxy's session expires before the application's session and the correct server is selected. It is recommended to specify this option to improve reliability",
+            true);
         method.addParam(
-                "prefix",
-                false,
-                "When this option is specified, haproxy will match on the cookie prefix (or URL parameter prefix). " +
+            "prefix",
+            false,
+            "When this option is specified, haproxy will match on the cookie prefix (or URL parameter prefix). "
+                +
                 "The appsession value is the data following this prefix. Example : appsession ASPSESSIONID len 64 timeout 3h prefix  This will match the cookie ASPSESSIONIDXXXX=XXXXX, the appsession value will be XXXX=XXXXX.",
-                true);
+            true);
         method.addParam(
-                "mode",
-                false,
-                "This option allows to change the URL parser mode. 2 modes are currently supported : - path-parameters " +
+            "mode",
+            false,
+            "This option allows to change the URL parser mode. 2 modes are currently supported : - path-parameters " +
                 ": The parser looks for the appsession in the path parameters part (each parameter is separated by a semi-colon), " +
                 "which is convenient for JSESSIONID for example.This is the default mode if the option is not set. - query-string :" +
                 " In this mode, the parser will look for the appsession in the query string.",
-                false);
+            false);
         methodList.add(method);
 
         method = new LbStickinessMethod(StickinessMethodType.SourceBased, "This is source based Stickiness method, " +
-        		"it can be used for any type of protocol.");
+            "it can be used for any type of protocol.");
         method.addParam("tablesize", false, "Size of table to store source ip addresses. example: tablesize=200k or 300m" +
-        		" or 400g. Default value:200k", false);
+            " or 400g. Default value:200k", false);
         method.addParam("expire", false, "Entry in source ip table will expire after expire duration. units can be s,m,h,d ." +
-        		" example: expire=30m 20s 50h 4d. Default value:3h", false);
+            " example: expire=30m 20s 50h 4d. Default value:3h", false);
         methodList.add(method);
 
         Gson gson = new Gson();
@@ -364,287 +366,287 @@ public class OvsElement extends AdapterBase implements NetworkElement,
         return capability;
     }
 
-	@Override
-	public List<Class<?>> getCommands() {
-		List<Class<?>> cmdList = new ArrayList<Class<?>>();
-		return cmdList;
-	}
-
-	@Override
-	public HostVO createHostVOForConnectedAgent(HostVO host,
-			StartupCommand[] cmd) {
-		return null;
-	}
-
-	@Override
-	public HostVO createHostVOForDirectConnectAgent(HostVO host,
-			StartupCommand[] startup, ServerResource resource,
-			Map<String, String> details, List<String> hostTags) {
-		if (!(startup[0] instanceof StartupOvsCommand)) {
-			return null;
-		}
-		host.setType(Host.Type.L2Networking);
-		return host;
-	}
-
-	@Override
-	public DeleteHostAnswer deleteHost(HostVO host, boolean isForced,
-			boolean isForceDeleteStorage) throws UnableDeleteHostException {
-		if (!(host.getType() == Host.Type.L2Networking)) {
-			return null;
-		}
-		return new DeleteHostAnswer(true);
-	}
-
-	@Override
-	public IpDeployer getIpDeployer(Network network) {
-		return this;
-	}
-
-	@Override
-	public boolean applyIps(Network network,
-			List<? extends PublicIpAddress> ipAddress, Set<Service> services)
-			throws ResourceUnavailableException {
-		boolean canHandle = true;
-		for (Service service : services) {
-			// check if Ovs can handle services except SourceNat & Firewall
-			if (!canHandle(network, service) && service != Service.SourceNat && service != Service.Firewall) {
-				canHandle = false;
-				break;
-			}
-		}
-		if (canHandle) {
-			List<DomainRouterVO> routers = _routerDao.listByNetworkAndRole(
-					network.getId(), Role.VIRTUAL_ROUTER);
-			if (routers == null || routers.isEmpty()) {
-				s_logger.debug("Virtual router element doesn't need to associate ip addresses on the backend; virtual "
-						+ "router doesn't exist in the network "
-						+ network.getId());
-				return true;
-			}
-
-			return _routerMgr.associatePublicIP(network, ipAddress, routers);
-		} else {
-			return false;
-		}
-	}
-
-	@Override
-	public boolean applyStaticNats(Network network, List<? extends StaticNat> rules)
-			throws ResourceUnavailableException {
-		if (!canHandle(network, Service.StaticNat)) {
-			return false;
-		}
-		List<DomainRouterVO> routers = _routerDao.listByNetworkAndRole(
-				network.getId(), Role.VIRTUAL_ROUTER);
-		if (routers == null || routers.isEmpty()) {
-			s_logger.debug("Ovs element doesn't need to apply static nat on the backend; virtual "
-					+ "router doesn't exist in the network " + network.getId());
-			return true;
-		}
-
-		return _routerMgr.applyStaticNats(network, rules, routers);
-	}
-
-	@Override
-	public boolean applyPFRules(Network network, List<PortForwardingRule> rules)
-			throws ResourceUnavailableException {
-		if (!canHandle(network, Service.PortForwarding)) {
-			return false;
-		}
-		List<DomainRouterVO> routers = _routerDao.listByNetworkAndRole(
-				network.getId(), Role.VIRTUAL_ROUTER);
-		if (routers == null || routers.isEmpty()) {
-			s_logger.debug("Ovs element doesn't need to apply firewall rules on the backend; virtual "
-					+ "router doesn't exist in the network " + network.getId());
-			return true;
-		}
-
-		return _routerMgr.applyFirewallRules(network, rules, routers);
-	}
-
-	@Override
-	public boolean applyLBRules(Network network, List<LoadBalancingRule> rules)
-			throws ResourceUnavailableException {
-		if (canHandle(network, Service.Lb)) {
-			if (!canHandleLbRules(rules)) {
-				return false;
-			}
-
-			List<DomainRouterVO> routers = _routerDao.listByNetworkAndRole(
-					network.getId(), Role.VIRTUAL_ROUTER);
-			if (routers == null || routers.isEmpty()) {
-				s_logger.debug("Virtual router elemnt doesn't need to apply firewall rules on the backend; virtual "
-						+ "router doesn't exist in the network "
-						+ network.getId());
-				return true;
-			}
-
-			if (!_routerMgr.applyLoadBalancingRules(network, rules, routers)) {
-				throw new CloudRuntimeException(
-						"Failed to apply load balancing rules in network "
-								+ network.getId());
-			} else {
-				return true;
-			}
-		} else {
-			return false;
-		}
-	}
-
-	@Override
-	public boolean validateLBRule(Network network, LoadBalancingRule rule) {
-		List<LoadBalancingRule> rules = new ArrayList<LoadBalancingRule>();
-		rules.add(rule);
-		if (canHandle(network, Service.Lb) && canHandleLbRules(rules)) {
-			List<DomainRouterVO> routers = _routerDao.listByNetworkAndRole(
-					network.getId(), Role.VIRTUAL_ROUTER);
-			if (routers == null || routers.isEmpty()) {
-				return true;
-			}
-			return validateHAProxyLBRule(rule);
-		}
-		return true;
-	}
-
-	@Override
-	public List<LoadBalancerTO> updateHealthChecks(Network network,
-			List<LoadBalancingRule> lbrules) {
-		// TODO Auto-generated method stub
-		return null;
-	}
-
-	private boolean canHandleLbRules(List<LoadBalancingRule> rules) {
-		Map<Capability, String> lbCaps = this.getCapabilities().get(Service.Lb);
-		if (!lbCaps.isEmpty()) {
-			String schemeCaps = lbCaps.get(Capability.LbSchemes);
-			if (schemeCaps != null) {
-				for (LoadBalancingRule rule : rules) {
-					if (!schemeCaps.contains(rule.getScheme().toString())) {
-						s_logger.debug("Scheme " + rules.get(0).getScheme()
-								+ " is not supported by the provider "
-								+ this.getName());
-						return false;
-					}
-				}
-			}
-		}
-		return true;
-	}
-
-	public static boolean validateHAProxyLBRule(LoadBalancingRule rule) {
-		String timeEndChar = "dhms";
-
-		for (LbStickinessPolicy stickinessPolicy : rule.getStickinessPolicies()) {
-			List<Pair<String, String>> paramsList = stickinessPolicy
-					.getParams();
-
-			if (StickinessMethodType.LBCookieBased.getName().equalsIgnoreCase(
-					stickinessPolicy.getMethodName())) {
-
-			} else if (StickinessMethodType.SourceBased.getName()
-					.equalsIgnoreCase(stickinessPolicy.getMethodName())) {
-				String tablesize = "200k"; // optional
-				String expire = "30m"; // optional
-
-				/* overwrite default values with the stick parameters */
-				for (Pair<String, String> paramKV : paramsList) {
-					String key = paramKV.first();
-					String value = paramKV.second();
-					if ("tablesize".equalsIgnoreCase(key))
-						tablesize = value;
-					if ("expire".equalsIgnoreCase(key))
-						expire = value;
-				}
-				if ((expire != null)
-						&& !containsOnlyNumbers(expire, timeEndChar)) {
-					throw new InvalidParameterValueException(
-							"Failed LB in validation rule id: " + rule.getId()
-									+ " Cause: expire is not in timeformat: "
-									+ expire);
-				}
-				if ((tablesize != null)
-						&& !containsOnlyNumbers(tablesize, "kmg")) {
-					throw new InvalidParameterValueException(
-							"Failed LB in validation rule id: "
-									+ rule.getId()
-									+ " Cause: tablesize is not in size format: "
-									+ tablesize);
-
-				}
-			} else if (StickinessMethodType.AppCookieBased.getName()
-					.equalsIgnoreCase(stickinessPolicy.getMethodName())) {
-				/*
-				 * FORMAT : appsession <cookie> len <length> timeout <holdtime>
-				 * [request-learn] [prefix] [mode
-				 * <path-parameters|query-string>]
-				 */
-				/* example: appsession JSESSIONID len 52 timeout 3h */
-				String cookieName = null; // optional
-				String length = null; // optional
-				String holdTime = null; // optional
-
-				for (Pair<String, String> paramKV : paramsList) {
-					String key = paramKV.first();
-					String value = paramKV.second();
-					if ("cookie-name".equalsIgnoreCase(key))
-						cookieName = value;
-					if ("length".equalsIgnoreCase(key))
-						length = value;
-					if ("holdtime".equalsIgnoreCase(key))
-						holdTime = value;
-				}
-
-				if ((length != null) && (!containsOnlyNumbers(length, null))) {
-					throw new InvalidParameterValueException(
-							"Failed LB in validation rule id: " + rule.getId()
-									+ " Cause: length is not a number: "
-									+ length);
-				}
-				if ((holdTime != null)
-						&& (!containsOnlyNumbers(holdTime, timeEndChar) && !containsOnlyNumbers(
-								holdTime, null))) {
-					throw new InvalidParameterValueException(
-							"Failed LB in validation rule id: " + rule.getId()
-									+ " Cause: holdtime is not in timeformat: "
-									+ holdTime);
-				}
-			}
-		}
-		return true;
-	}
-
-	/*
-	 * This function detects numbers like 12 ,32h ,42m .. etc,. 1) plain number
-	 * like 12 2) time or tablesize like 12h, 34m, 45k, 54m , here last
-	 * character is non-digit but from known characters .
-	 */
-	private static boolean containsOnlyNumbers(String str, String endChar) {
-		if (str == null)
-			return false;
-
-		String number = str;
-		if (endChar != null) {
-			boolean matchedEndChar = false;
-			if (str.length() < 2)
-				return false; // atleast one numeric and one char. example:
-								// 3h
-			char strEnd = str.toCharArray()[str.length() - 1];
-			for (char c : endChar.toCharArray()) {
-				if (strEnd == c) {
-					number = str.substring(0, str.length() - 1);
-					matchedEndChar = true;
-					break;
-				}
-			}
-			if (!matchedEndChar)
-				return false;
-		}
-		try {
-			int i = Integer.parseInt(number);
-		} catch (NumberFormatException e) {
-			return false;
-		}
-		return true;
-	}
+    @Override
+    public List<Class<?>> getCommands() {
+        List<Class<?>> cmdList = new ArrayList<Class<?>>();
+        return cmdList;
+    }
+
+    @Override
+    public HostVO createHostVOForConnectedAgent(HostVO host,
+        StartupCommand[] cmd) {
+        return null;
+    }
+
+    @Override
+    public HostVO createHostVOForDirectConnectAgent(HostVO host,
+        StartupCommand[] startup, ServerResource resource,
+        Map<String, String> details, List<String> hostTags) {
+        if (!(startup[0] instanceof StartupOvsCommand)) {
+            return null;
+        }
+        host.setType(Host.Type.L2Networking);
+        return host;
+    }
+
+    @Override
+    public DeleteHostAnswer deleteHost(HostVO host, boolean isForced,
+        boolean isForceDeleteStorage) throws UnableDeleteHostException {
+        if (!(host.getType() == Host.Type.L2Networking)) {
+            return null;
+        }
+        return new DeleteHostAnswer(true);
+    }
+
+    @Override
+    public IpDeployer getIpDeployer(Network network) {
+        return this;
+    }
+
+    @Override
+    public boolean applyIps(Network network,
+        List<? extends PublicIpAddress> ipAddress, Set<Service> services)
+        throws ResourceUnavailableException {
+        boolean canHandle = true;
+        for (Service service : services) {
+            // check if Ovs can handle services except SourceNat & Firewall
+            if (!canHandle(network, service) && service != Service.SourceNat && service != Service.Firewall) {
+                canHandle = false;
+                break;
+            }
+        }
+        if (canHandle) {
+            List<DomainRouterVO> routers = _routerDao.listByNetworkAndRole(
+                network.getId(), Role.VIRTUAL_ROUTER);
+            if (routers == null || routers.isEmpty()) {
+                s_logger.debug("Virtual router element doesn't need to associate ip addresses on the backend; virtual "
+                    + "router doesn't exist in the network "
+                    + network.getId());
+                return true;
+            }
+
+            return _routerMgr.associatePublicIP(network, ipAddress, routers);
+        } else {
+            return false;
+        }
+    }
+
+    @Override
+    public boolean applyStaticNats(Network network, List<? extends StaticNat> rules)
+        throws ResourceUnavailableException {
+        if (!canHandle(network, Service.StaticNat)) {
+            return false;
+        }
+        List<DomainRouterVO> routers = _routerDao.listByNetworkAndRole(
+            network.getId(), Role.VIRTUAL_ROUTER);
+        if (routers == null || routers.isEmpty()) {
+            s_logger.debug("Ovs element doesn't need to apply static nat on the backend; virtual "
+                + "router doesn't exist in the network " + network.getId());
+            return true;
+        }
+
+        return _routerMgr.applyStaticNats(network, rules, routers);
+    }
+
+    @Override
+    public boolean applyPFRules(Network network, List<PortForwardingRule> rules)
+        throws ResourceUnavailableException {
+        if (!canHandle(network, Service.PortForwarding)) {
+            return false;
+        }
+        List<DomainRouterVO> routers = _routerDao.listByNetworkAndRole(
+            network.getId(), Role.VIRTUAL_ROUTER);
+        if (routers == null || routers.isEmpty()) {
+            s_logger.debug("Ovs element doesn't need to apply firewall rules on the backend; virtual "
+                + "router doesn't exist in the network " + network.getId());
+            return true;
+        }
+
+        return _routerMgr.applyFirewallRules(network, rules, routers);
+    }
+
+    @Override
+    public boolean applyLBRules(Network network, List<LoadBalancingRule> rules)
+        throws ResourceUnavailableException {
+        if (canHandle(network, Service.Lb)) {
+            if (!canHandleLbRules(rules)) {
+                return false;
+            }
+
+            List<DomainRouterVO> routers = _routerDao.listByNetworkAndRole(
+                network.getId(), Role.VIRTUAL_ROUTER);
+            if (routers == null || routers.isEmpty()) {
+                s_logger.debug("Virtual router elemnt doesn't need to apply firewall rules on the backend; virtual "
+                    + "router doesn't exist in the network "
+                    + network.getId());
+                return true;
+            }
+
+            if (!_routerMgr.applyLoadBalancingRules(network, rules, routers)) {
+                throw new CloudRuntimeException(
+                    "Failed to apply load balancing rules in network "
+                        + network.getId());
+            } else {
+                return true;
+            }
+        } else {
+            return false;
+        }
+    }
+
+    @Override
+    public boolean validateLBRule(Network network, LoadBalancingRule rule) {
+        List<LoadBalancingRule> rules = new ArrayList<LoadBalancingRule>();
+        rules.add(rule);
+        if (canHandle(network, Service.Lb) && canHandleLbRules(rules)) {
+            List<DomainRouterVO> routers = _routerDao.listByNetworkAndRole(
+                network.getId(), Role.VIRTUAL_ROUTER);
+            if (routers == null || routers.isEmpty()) {
+                return true;
+            }
+            return validateHAProxyLBRule(rule);
+        }
+        return true;
+    }
+
+    @Override
+    public List<LoadBalancerTO> updateHealthChecks(Network network,
+        List<LoadBalancingRule> lbrules) {
+        // TODO Auto-generated method stub
+        return null;
+    }
+
+    private boolean canHandleLbRules(List<LoadBalancingRule> rules) {
+        Map<Capability, String> lbCaps = this.getCapabilities().get(Service.Lb);
+        if (!lbCaps.isEmpty()) {
+            String schemeCaps = lbCaps.get(Capability.LbSchemes);
+            if (schemeCaps != null) {
+                for (LoadBalancingRule rule : rules) {
+                    if (!schemeCaps.contains(rule.getScheme().toString())) {
+                        s_logger.debug("Scheme " + rules.get(0).getScheme()
+                            + " is not supported by the provider "
+                            + this.getName());
+                        return false;
+                    }
+                }
+            }
+        }
+        return true;
+    }
+
+    public static boolean validateHAProxyLBRule(LoadBalancingRule rule) {
+        String timeEndChar = "dhms";
+
+        for (LbStickinessPolicy stickinessPolicy : rule.getStickinessPolicies()) {
+            List<Pair<String, String>> paramsList = stickinessPolicy
+                .getParams();
+
+            if (StickinessMethodType.LBCookieBased.getName().equalsIgnoreCase(
+                stickinessPolicy.getMethodName())) {
+
+            } else if (StickinessMethodType.SourceBased.getName()
+                .equalsIgnoreCase(stickinessPolicy.getMethodName())) {
+                String tablesize = "200k"; // optional
+                String expire = "30m"; // optional
+
+                /* overwrite default values with the stick parameters */
+                for (Pair<String, String> paramKV : paramsList) {
+                    String key = paramKV.first();
+                    String value = paramKV.second();
+                    if ("tablesize".equalsIgnoreCase(key))
+                        tablesize = value;
+                    if ("expire".equalsIgnoreCase(key))
+                        expire = value;
+                }
+                if ((expire != null)
+                    && !containsOnlyNumbers(expire, timeEndChar)) {
+                    throw new InvalidParameterValueException(
+                        "Failed LB in validation rule id: " + rule.getId()
+                            + " Cause: expire is not in timeformat: "
+                            + expire);
+                }
+                if ((tablesize != null)
+                    && !containsOnlyNumbers(tablesize, "kmg")) {
+                    throw new InvalidParameterValueException(
+                        "Failed LB in validation rule id: "
+                            + rule.getId()
+                            + " Cause: tablesize is not in size format: "
+                            + tablesize);
+
+                }
+            } else if (StickinessMethodType.AppCookieBased.getName()
+                .equalsIgnoreCase(stickinessPolicy.getMethodName())) {
+                /*
+                 * FORMAT : appsession <cookie> len <length> timeout <holdtime>
+                 * [request-learn] [prefix] [mode
+                 * <path-parameters|query-string>]
+                 */
+                /* example: appsession JSESSIONID len 52 timeout 3h */
+                String cookieName = null; // optional
+                String length = null; // optional
+                String holdTime = null; // optional
+
+                for (Pair<String, String> paramKV : paramsList) {
+                    String key = paramKV.first();
+                    String value = paramKV.second();
+                    if ("cookie-name".equalsIgnoreCase(key))
+                        cookieName = value;
+                    if ("length".equalsIgnoreCase(key))
+                        length = value;
+                    if ("holdtime".equalsIgnoreCase(key))
+                        holdTime = value;
+                }
+
+                if ((length != null) && (!containsOnlyNumbers(length, null))) {
+                    throw new InvalidParameterValueException(
+                        "Failed LB in validation rule id: " + rule.getId()
+                            + " Cause: length is not a number: "
+                            + length);
+                }
+                if ((holdTime != null)
+                    && (!containsOnlyNumbers(holdTime, timeEndChar) && !containsOnlyNumbers(
+                        holdTime, null))) {
+                    throw new InvalidParameterValueException(
+                        "Failed LB in validation rule id: " + rule.getId()
+                            + " Cause: holdtime is not in timeformat: "
+                            + holdTime);
+                }
+            }
+        }
+        return true;
+    }
+
+    /*
+     * This function detects numbers like 12 ,32h ,42m .. etc,. 1) plain number
+     * like 12 2) time or tablesize like 12h, 34m, 45k, 54m , here last
+     * character is non-digit but from known characters .
+     */
+    private static boolean containsOnlyNumbers(String str, String endChar) {
+        if (str == null)
+            return false;
+
+        String number = str;
+        if (endChar != null) {
+            boolean matchedEndChar = false;
+            if (str.length() < 2)
+                return false; // atleast one numeric and one char. example:
+                              // 3h
+            char strEnd = str.toCharArray()[str.length() - 1];
+            for (char c : endChar.toCharArray()) {
+                if (strEnd == c) {
+                    number = str.substring(0, str.length() - 1);
+                    matchedEndChar = true;
+                    break;
+                }
+            }
+            if (!matchedEndChar)
+                return false;
+        }
+        try {
+            int i = Integer.parseInt(number);
+        } catch (NumberFormatException e) {
+            return false;
+        }
+        return true;
+    }
 }

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/be5e5cc6/plugins/network-elements/ovs/src/com/cloud/network/guru/OvsGuestNetworkGuru.java
----------------------------------------------------------------------
diff --git a/plugins/network-elements/ovs/src/com/cloud/network/guru/OvsGuestNetworkGuru.java b/plugins/network-elements/ovs/src/com/cloud/network/guru/OvsGuestNetworkGuru.java
index 7a671a0..6aacbb2 100644
--- a/plugins/network-elements/ovs/src/com/cloud/network/guru/OvsGuestNetworkGuru.java
+++ b/plugins/network-elements/ovs/src/com/cloud/network/guru/OvsGuestNetworkGuru.java
@@ -20,9 +20,10 @@ import javax.ejb.Local;
 import javax.inject.Inject;
 
 import org.apache.log4j.Logger;
-import org.apache.cloudstack.context.CallContext;
 import org.springframework.stereotype.Component;
 
+import org.apache.cloudstack.context.CallContext;
+
 import com.cloud.dc.DataCenter;
 import com.cloud.dc.DataCenter.NetworkType;
 import com.cloud.deploy.DeployDestination;
@@ -48,175 +49,174 @@ import com.cloud.offerings.dao.NetworkOfferingServiceMapDao;
 import com.cloud.user.Account;
 import com.cloud.vm.NicProfile;
 import com.cloud.vm.ReservationContext;
-import com.cloud.vm.VirtualMachine;
 import com.cloud.vm.VirtualMachineProfile;
 
 @Component
 @Local(value = NetworkGuru.class)
 public class OvsGuestNetworkGuru extends GuestNetworkGuru {
-	private static final Logger s_logger = Logger
-			.getLogger(OvsGuestNetworkGuru.class);
-
-	@Inject
-	OvsTunnelManager _ovsTunnelMgr;
-	@Inject
-	NetworkOfferingServiceMapDao _ntwkOfferingSrvcDao;
-
-	OvsGuestNetworkGuru() {
-		super();
-		_isolationMethods = new IsolationMethod[] { IsolationMethod.GRE,
-				IsolationMethod.L3, IsolationMethod.VLAN };
-	}
-
-	@Override
-	protected boolean canHandle(NetworkOffering offering,
-			final NetworkType networkType, final PhysicalNetwork physicalNetwork) {
-		// This guru handles only Guest Isolated network that supports Source
-		// nat service
-		if (networkType == NetworkType.Advanced
-				&& isMyTrafficType(offering.getTrafficType())
-				&& offering.getGuestType() == Network.GuestType.Isolated
-				&& isMyIsolationMethod(physicalNetwork)
-				&& _ntwkOfferingSrvcDao.areServicesSupportedByNetworkOffering(
-						offering.getId(), Service.Connectivity)) {
-			return true;
-		} else {
-			s_logger.trace("We only take care of Guest networks of type   "
-					+ GuestType.Isolated + " in zone of type "
-					+ NetworkType.Advanced);
-			return false;
-		}
-	}
-
-	@Override
-	public Network design(NetworkOffering offering, DeploymentPlan plan,
-			Network userSpecified, Account owner) {
-
-		PhysicalNetworkVO physnet = _physicalNetworkDao.findById(plan
-				.getPhysicalNetworkId());
-		DataCenter dc = _dcDao.findById(plan.getDataCenterId());
-		if (!canHandle(offering, dc.getNetworkType(), physnet)) {
-			s_logger.debug("Refusing to design this network");
-			return null;
-		}
-		NetworkVO config = (NetworkVO) super.design(offering, plan,
-				userSpecified, owner);
-		if (config == null) {
-			return null;
-		}
-
-		config.setBroadcastDomainType(BroadcastDomainType.Vswitch);
-
-		return config;
-	}
-
-	@Override
-	public Network implement(Network network, NetworkOffering offering,
-			DeployDestination dest, ReservationContext context)
-			throws InsufficientVirtualNetworkCapcityException {
-		assert (network.getState() == State.Implementing) : "Why are we implementing "
-				+ network;
-
-		long dcId = dest.getDataCenter().getId();
-		NetworkType nwType = dest.getDataCenter().getNetworkType();
-		// get physical network id
-		Long physicalNetworkId = network.getPhysicalNetworkId();
-		// physical network id can be null in Guest Network in Basic zone, so
-		// locate the physical network
-		if (physicalNetworkId == null) {
-			physicalNetworkId = _networkModel.findPhysicalNetworkId(dcId,
-					offering.getTags(), offering.getTrafficType());
-		}
-		PhysicalNetworkVO physnet = _physicalNetworkDao
-				.findById(physicalNetworkId);
-
-		if (!canHandle(offering, nwType, physnet)) {
-			s_logger.debug("Refusing to design this network");
-			return null;
-		}
-		NetworkVO implemented = (NetworkVO) super.implement(network, offering,
-				dest, context);
-
-		if (network.getGateway() != null) {
-			implemented.setGateway(network.getGateway());
-		}
-
-		if (network.getCidr() != null) {
-			implemented.setCidr(network.getCidr());
-		}
-		String name = network.getName();
-		if (name == null || name.isEmpty()) {
-			name = ((NetworkVO) network).getUuid();
-		}
-
-		// do we need to create switch right now?
-
-		implemented.setBroadcastDomainType(BroadcastDomainType.Vswitch);
-
-		return implemented;
-	}
-
-	@Override
-	public void reserve(NicProfile nic, Network network,
-			VirtualMachineProfile vm,
-			DeployDestination dest, ReservationContext context)
-			throws InsufficientVirtualNetworkCapcityException,
-			InsufficientAddressCapacityException {
-		// TODO Auto-generated method stub
-		super.reserve(nic, network, vm, dest, context);
-	}
-
-	@Override
-	public boolean release(NicProfile nic,
-			VirtualMachineProfile vm,
-			String reservationId) {
-		// TODO Auto-generated method stub
-		return super.release(nic, vm, reservationId);
-	}
-
-	@Override
-	public void shutdown(NetworkProfile profile, NetworkOffering offering) {
-		NetworkVO networkObject = _networkDao.findById(profile.getId());
-		if (networkObject.getBroadcastDomainType() != BroadcastDomainType.Vswitch
-				|| networkObject.getBroadcastUri() == null) {
-			s_logger.warn("BroadcastUri is empty or incorrect for guestnetwork "
-					+ networkObject.getDisplayText());
-			return;
-		}
-
-		super.shutdown(profile, offering);
-	}
-
-	@Override
-	public boolean trash(Network network, NetworkOffering offering) {
-		return super.trash(network, offering);
-	}
-
-	@Override
-	protected void allocateVnet(Network network, NetworkVO implemented,
-			long dcId, long physicalNetworkId, String reservationId)
-			throws InsufficientVirtualNetworkCapcityException {
-		if (network.getBroadcastUri() == null) {
-			String vnet = _dcDao.allocateVnet(dcId, physicalNetworkId,
-					network.getAccountId(), reservationId,
-					UseSystemGuestVlans.valueIn(network.getAccountId()));
-			if (vnet == null) {
-				throw new InsufficientVirtualNetworkCapcityException(
-						"Unable to allocate vnet as a part of network "
-								+ network + " implement ", DataCenter.class,
-						dcId);
-			}
-			implemented
-					.setBroadcastUri(BroadcastDomainType.Vswitch.toUri(vnet));
-			ActionEventUtils.onCompletedActionEvent(
-					CallContext.current().getCallingUserId(),
-					network.getAccountId(),
-					EventVO.LEVEL_INFO,
-					EventTypes.EVENT_ZONE_VLAN_ASSIGN,
-					"Assigned Zone Vlan: " + vnet + " Network Id: "
-							+ network.getId(), 0);
-		} else {
-			implemented.setBroadcastUri(network.getBroadcastUri());
-		}
-	}
+    private static final Logger s_logger = Logger
+        .getLogger(OvsGuestNetworkGuru.class);
+
+    @Inject
+    OvsTunnelManager _ovsTunnelMgr;
+    @Inject
+    NetworkOfferingServiceMapDao _ntwkOfferingSrvcDao;
+
+    OvsGuestNetworkGuru() {
+        super();
+        _isolationMethods = new IsolationMethod[] {IsolationMethod.GRE,
+            IsolationMethod.L3, IsolationMethod.VLAN};
+    }
+
+    @Override
+    protected boolean canHandle(NetworkOffering offering,
+        final NetworkType networkType, final PhysicalNetwork physicalNetwork) {
+        // This guru handles only Guest Isolated network that supports Source
+        // nat service
+        if (networkType == NetworkType.Advanced
+            && isMyTrafficType(offering.getTrafficType())
+            && offering.getGuestType() == Network.GuestType.Isolated
+            && isMyIsolationMethod(physicalNetwork)
+            && _ntwkOfferingSrvcDao.areServicesSupportedByNetworkOffering(
+                offering.getId(), Service.Connectivity)) {
+            return true;
+        } else {
+            s_logger.trace("We only take care of Guest networks of type   "
+                + GuestType.Isolated + " in zone of type "
+                + NetworkType.Advanced);
+            return false;
+        }
+    }
+
+    @Override
+    public Network design(NetworkOffering offering, DeploymentPlan plan,
+        Network userSpecified, Account owner) {
+
+        PhysicalNetworkVO physnet = _physicalNetworkDao.findById(plan
+            .getPhysicalNetworkId());
+        DataCenter dc = _dcDao.findById(plan.getDataCenterId());
+        if (!canHandle(offering, dc.getNetworkType(), physnet)) {
+            s_logger.debug("Refusing to design this network");
+            return null;
+        }
+        NetworkVO config = (NetworkVO)super.design(offering, plan,
+            userSpecified, owner);
+        if (config == null) {
+            return null;
+        }
+
+        config.setBroadcastDomainType(BroadcastDomainType.Vswitch);
+
+        return config;
+    }
+
+    @Override
+    public Network implement(Network network, NetworkOffering offering,
+        DeployDestination dest, ReservationContext context)
+        throws InsufficientVirtualNetworkCapcityException {
+        assert (network.getState() == State.Implementing) : "Why are we implementing "
+            + network;
+
+        long dcId = dest.getDataCenter().getId();
+        NetworkType nwType = dest.getDataCenter().getNetworkType();
+        // get physical network id
+        Long physicalNetworkId = network.getPhysicalNetworkId();
+        // physical network id can be null in Guest Network in Basic zone, so
+        // locate the physical network
+        if (physicalNetworkId == null) {
+            physicalNetworkId = _networkModel.findPhysicalNetworkId(dcId,
+                offering.getTags(), offering.getTrafficType());
+        }
+        PhysicalNetworkVO physnet = _physicalNetworkDao
+            .findById(physicalNetworkId);
+
+        if (!canHandle(offering, nwType, physnet)) {
+            s_logger.debug("Refusing to design this network");
+            return null;
+        }
+        NetworkVO implemented = (NetworkVO)super.implement(network, offering,
+            dest, context);
+
+        if (network.getGateway() != null) {
+            implemented.setGateway(network.getGateway());
+        }
+
+        if (network.getCidr() != null) {
+            implemented.setCidr(network.getCidr());
+        }
+        String name = network.getName();
+        if (name == null || name.isEmpty()) {
+            name = ((NetworkVO)network).getUuid();
+        }
+
+        // do we need to create switch right now?
+
+        implemented.setBroadcastDomainType(BroadcastDomainType.Vswitch);
+
+        return implemented;
+    }
+
+    @Override
+    public void reserve(NicProfile nic, Network network,
+        VirtualMachineProfile vm,
+        DeployDestination dest, ReservationContext context)
+        throws InsufficientVirtualNetworkCapcityException,
+        InsufficientAddressCapacityException {
+        // TODO Auto-generated method stub
+        super.reserve(nic, network, vm, dest, context);
+    }
+
+    @Override
+    public boolean release(NicProfile nic,
+        VirtualMachineProfile vm,
+        String reservationId) {
+        // TODO Auto-generated method stub
+        return super.release(nic, vm, reservationId);
+    }
+
+    @Override
+    public void shutdown(NetworkProfile profile, NetworkOffering offering) {
+        NetworkVO networkObject = _networkDao.findById(profile.getId());
+        if (networkObject.getBroadcastDomainType() != BroadcastDomainType.Vswitch
+            || networkObject.getBroadcastUri() == null) {
+            s_logger.warn("BroadcastUri is empty or incorrect for guestnetwork "
+                + networkObject.getDisplayText());
+            return;
+        }
+
+        super.shutdown(profile, offering);
+    }
+
+    @Override
+    public boolean trash(Network network, NetworkOffering offering) {
+        return super.trash(network, offering);
+    }
+
+    @Override
+    protected void allocateVnet(Network network, NetworkVO implemented,
+        long dcId, long physicalNetworkId, String reservationId)
+        throws InsufficientVirtualNetworkCapcityException {
+        if (network.getBroadcastUri() == null) {
+            String vnet = _dcDao.allocateVnet(dcId, physicalNetworkId,
+                network.getAccountId(), reservationId,
+                UseSystemGuestVlans.valueIn(network.getAccountId()));
+            if (vnet == null) {
+                throw new InsufficientVirtualNetworkCapcityException(
+                    "Unable to allocate vnet as a part of network "
+                        + network + " implement ", DataCenter.class,
+                    dcId);
+            }
+            implemented
+                .setBroadcastUri(BroadcastDomainType.Vswitch.toUri(vnet));
+            ActionEventUtils.onCompletedActionEvent(
+                CallContext.current().getCallingUserId(),
+                network.getAccountId(),
+                EventVO.LEVEL_INFO,
+                EventTypes.EVENT_ZONE_VLAN_ASSIGN,
+                "Assigned Zone Vlan: " + vnet + " Network Id: "
+                    + network.getId(), 0);
+        } else {
+            implemented.setBroadcastUri(network.getBroadcastUri());
+        }
+    }
 }

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/be5e5cc6/plugins/network-elements/ovs/src/com/cloud/network/ovs/OvsTunnelManagerImpl.java
----------------------------------------------------------------------
diff --git a/plugins/network-elements/ovs/src/com/cloud/network/ovs/OvsTunnelManagerImpl.java b/plugins/network-elements/ovs/src/com/cloud/network/ovs/OvsTunnelManagerImpl.java
index 553d645..aa0f42e 100644
--- a/plugins/network-elements/ovs/src/com/cloud/network/ovs/OvsTunnelManagerImpl.java
+++ b/plugins/network-elements/ovs/src/com/cloud/network/ovs/OvsTunnelManagerImpl.java
@@ -29,6 +29,7 @@ import javax.persistence.EntityExistsException;
 
 import org.apache.log4j.Logger;
 import org.springframework.stereotype.Component;
+
 import org.apache.cloudstack.framework.config.dao.ConfigurationDao;
 
 import com.cloud.agent.AgentManager;
@@ -78,74 +79,74 @@ import com.cloud.vm.dao.UserVmDao;
 public class OvsTunnelManagerImpl extends ManagerBase implements OvsTunnelManager {
     public static final Logger s_logger = Logger.getLogger(OvsTunnelManagerImpl.class.getName());
 
-	// boolean _isEnabled;
-	ScheduledExecutorService _executorPool;
-	ScheduledExecutorService _cleanupExecutor;
-
-	@Inject
-	ConfigurationDao _configDao;
-	@Inject
-	NicDao _nicDao;
-	@Inject
-	HostDao _hostDao;
-	@Inject
-	PhysicalNetworkTrafficTypeDao _physNetTTDao;
-	@Inject
-	UserVmDao _userVmDao;
-	@Inject
-	DomainRouterDao _routerDao;
-	@Inject
-	OvsTunnelNetworkDao _tunnelNetworkDao;
-	@Inject
-	OvsTunnelInterfaceDao _tunnelInterfaceDao;
-	@Inject
-	AgentManager _agentMgr;
-
-	@Override
-	public boolean configure(String name, Map<String, Object> params)
-			throws ConfigurationException {
+    // boolean _isEnabled;
+    ScheduledExecutorService _executorPool;
+    ScheduledExecutorService _cleanupExecutor;
+
+    @Inject
+    ConfigurationDao _configDao;
+    @Inject
+    NicDao _nicDao;
+    @Inject
+    HostDao _hostDao;
+    @Inject
+    PhysicalNetworkTrafficTypeDao _physNetTTDao;
+    @Inject
+    UserVmDao _userVmDao;
+    @Inject
+    DomainRouterDao _routerDao;
+    @Inject
+    OvsTunnelNetworkDao _tunnelNetworkDao;
+    @Inject
+    OvsTunnelInterfaceDao _tunnelInterfaceDao;
+    @Inject
+    AgentManager _agentMgr;
+
+    @Override
+    public boolean configure(String name, Map<String, Object> params)
+        throws ConfigurationException {
         _executorPool = Executors.newScheduledThreadPool(10, new NamedThreadFactory("OVS"));
         _cleanupExecutor = Executors.newScheduledThreadPool(1, new NamedThreadFactory("OVS-Cleanup"));
 
         return true;
     }
 
-	@DB
-	protected OvsTunnelInterfaceVO createInterfaceRecord(String ip,
-			String netmask, String mac, long hostId, String label) {
-		OvsTunnelInterfaceVO ti = null;
-		try {
-			ti = new OvsTunnelInterfaceVO(ip, netmask, mac, hostId, label);
-			// TODO: Is locking really necessary here?
-			OvsTunnelInterfaceVO lock = _tunnelInterfaceDao
-					.acquireInLockTable(Long.valueOf(1));
-			if (lock == null) {
-				s_logger.warn("Cannot lock table ovs_tunnel_account");
-				return null;
-			}
-			_tunnelInterfaceDao.persist(ti);
-			_tunnelInterfaceDao.releaseFromLockTable(lock.getId());
-		} catch (EntityExistsException e) {
-			s_logger.debug("A record for the interface for network " + label
-					+ " on host id " + hostId + " already exists");
-		}
-		return ti;
-	}
-
-	private String handleFetchInterfaceAnswer(Answer[] answers, Long hostId) {
-		OvsFetchInterfaceAnswer ans = (OvsFetchInterfaceAnswer) answers[0];
-		if (ans.getResult()) {
-			if (ans.getIp() != null && !("".equals(ans.getIp()))) {
-				OvsTunnelInterfaceVO ti = createInterfaceRecord(ans.getIp(),
-						ans.getNetmask(), ans.getMac(), hostId, ans.getLabel());
-				return ti.getIp();
-			}
-		}
-		// Fetch interface failed!
-		s_logger.warn("Unable to fetch the IP address for the GRE tunnel endpoint"
-				+ ans.getDetails());
-		return null;
-	}
+    @DB
+    protected OvsTunnelInterfaceVO createInterfaceRecord(String ip,
+        String netmask, String mac, long hostId, String label) {
+        OvsTunnelInterfaceVO ti = null;
+        try {
+            ti = new OvsTunnelInterfaceVO(ip, netmask, mac, hostId, label);
+            // TODO: Is locking really necessary here?
+            OvsTunnelInterfaceVO lock = _tunnelInterfaceDao
+                .acquireInLockTable(Long.valueOf(1));
+            if (lock == null) {
+                s_logger.warn("Cannot lock table ovs_tunnel_account");
+                return null;
+            }
+            _tunnelInterfaceDao.persist(ti);
+            _tunnelInterfaceDao.releaseFromLockTable(lock.getId());
+        } catch (EntityExistsException e) {
+            s_logger.debug("A record for the interface for network " + label
+                + " on host id " + hostId + " already exists");
+        }
+        return ti;
+    }
+
+    private String handleFetchInterfaceAnswer(Answer[] answers, Long hostId) {
+        OvsFetchInterfaceAnswer ans = (OvsFetchInterfaceAnswer)answers[0];
+        if (ans.getResult()) {
+            if (ans.getIp() != null && !("".equals(ans.getIp()))) {
+                OvsTunnelInterfaceVO ti = createInterfaceRecord(ans.getIp(),
+                    ans.getNetmask(), ans.getMac(), hostId, ans.getLabel());
+                return ti.getIp();
+            }
+        }
+        // Fetch interface failed!
+        s_logger.warn("Unable to fetch the IP address for the GRE tunnel endpoint"
+            + ans.getDetails());
+        return null;
+    }
 
     @DB
     protected OvsTunnelNetworkVO createTunnelRecord(long from, long to, long networkId, int key) {
@@ -165,7 +166,6 @@ public class OvsTunnelManagerImpl extends ManagerBase implements OvsTunnelManage
         return ta;
     }
 
-
     private void handleCreateTunnelAnswer(Answer[] answers) {
         OvsCreateTunnelAnswer r = (OvsCreateTunnelAnswer)answers[0];
         String s =
@@ -177,66 +177,66 @@ public class OvsTunnelManagerImpl extends ManagerBase implements OvsTunnelManage
         OvsTunnelNetworkVO tunnel = _tunnelNetworkDao.getByFromToNetwork(from, to, networkId);
         if (tunnel == null) {
             throw new CloudRuntimeException(
-            		String.format("Unable find tunnelNetwork record" +
-            					  "(from=%1$s,to=%2$s, account=%3$s",
-            					  from, to, networkId));
-		}
-		if (!r.getResult()) {
-			tunnel.setState("FAILED");
-			s_logger.warn("Create GRE tunnel failed due to " + r.getDetails()
-					+ s);
-		} else {
-			tunnel.setState("SUCCESS");
-			tunnel.setPortName(r.getInPortName());
-			s_logger.warn("Create GRE tunnel " + r.getDetails() + s);
-		}
-		_tunnelNetworkDao.update(tunnel.getId(), tunnel);
-	}
-
-	private String getGreEndpointIP(Host host, Network nw)
-			throws AgentUnavailableException, OperationTimedoutException {
-		String endpointIp = null;
-		// Fetch fefault name for network label from configuration
-		String physNetLabel = _configDao.getValue(Config.OvsTunnelNetworkDefaultLabel.key());
+                String.format("Unable find tunnelNetwork record" +
+                    "(from=%1$s,to=%2$s, account=%3$s",
+                    from, to, networkId));
+        }
+        if (!r.getResult()) {
+            tunnel.setState("FAILED");
+            s_logger.warn("Create GRE tunnel failed due to " + r.getDetails()
+                + s);
+        } else {
+            tunnel.setState("SUCCESS");
+            tunnel.setPortName(r.getInPortName());
+            s_logger.warn("Create GRE tunnel " + r.getDetails() + s);
+        }
+        _tunnelNetworkDao.update(tunnel.getId(), tunnel);
+    }
+
+    private String getGreEndpointIP(Host host, Network nw)
+        throws AgentUnavailableException, OperationTimedoutException {
+        String endpointIp = null;
+        // Fetch fefault name for network label from configuration
+        String physNetLabel = _configDao.getValue(Config.OvsTunnelNetworkDefaultLabel.key());
         Long physNetId = nw.getPhysicalNetworkId();
         PhysicalNetworkTrafficType physNetTT =
-        		_physNetTTDao.findBy(physNetId, TrafficType.Guest);
+            _physNetTTDao.findBy(physNetId, TrafficType.Guest);
         HypervisorType hvType = host.getHypervisorType();
 
         String label = null;
         switch (hvType) {
-        	case XenServer:
-        		label = physNetTT.getXenNetworkLabel();
-        		if ((label!=null) && (!label.equals(""))) {
-        			physNetLabel = label;
-        		}
-        		break;
-			case KVM:
-				label = physNetTT.getKvmNetworkLabel();
-				if ((label != null) && (!label.equals(""))) {
-					physNetLabel = label;
-				}
-				break;
-        	default:
-        		throw new CloudRuntimeException("Hypervisor " +
-        				hvType.toString() +
-        				" unsupported by OVS Tunnel Manager");
+            case XenServer:
+                label = physNetTT.getXenNetworkLabel();
+                if ((label != null) && (!label.equals(""))) {
+                    physNetLabel = label;
+                }
+                break;
+            case KVM:
+                label = physNetTT.getKvmNetworkLabel();
+                if ((label != null) && (!label.equals(""))) {
+                    physNetLabel = label;
+                }
+                break;
+            default:
+                throw new CloudRuntimeException("Hypervisor " +
+                    hvType.toString() +
+                    " unsupported by OVS Tunnel Manager");
         }
 
         // Try to fetch GRE endpoint IP address for cloud db
         // If not found, then find it on the hypervisor
         OvsTunnelInterfaceVO tunnelIface =
-                _tunnelInterfaceDao.getByHostAndLabel(host.getId(),
-                        physNetLabel);
+            _tunnelInterfaceDao.getByHostAndLabel(host.getId(),
+                physNetLabel);
         if (tunnelIface == null) {
             //Now find and fetch configuration for physical interface
-        	//for network with label on target host
-			Commands fetchIfaceCmds =
-					new Commands(new OvsFetchInterfaceCommand(physNetLabel));
-			s_logger.debug("Ask host " + host.getId() +
-						   " to retrieve interface for phy net with label:" +
-						   physNetLabel);
-			Answer[] fetchIfaceAnswers = _agentMgr.send(host.getId(), fetchIfaceCmds);
+            //for network with label on target host
+            Commands fetchIfaceCmds =
+                new Commands(new OvsFetchInterfaceCommand(physNetLabel));
+            s_logger.debug("Ask host " + host.getId() +
+                " to retrieve interface for phy net with label:" +
+                physNetLabel);
+            Answer[] fetchIfaceAnswers = _agentMgr.send(host.getId(), fetchIfaceCmds);
             //And finally save it for future use
             endpointIp = handleFetchInterfaceAnswer(fetchIfaceAnswers, host.getId());
         } else {
@@ -245,56 +245,56 @@ public class OvsTunnelManagerImpl extends ManagerBase implements OvsTunnelManage
         return endpointIp;
     }
 
-	private int getGreKey(Network network) {
-		int key = 0;
-		try {
-		//The GRE key is actually in the host part of the URI
+    private int getGreKey(Network network) {
+        int key = 0;
+        try {
+            //The GRE key is actually in the host part of the URI
             // this is not true for lswitch/NiciraNvp!
             String keyStr = BroadcastDomainType.getValue(network.getBroadcastUri());
             // The key is most certainly and int if network is a vlan.
             // !! not in the case of lswitch/pvlan/(possibly)vswitch
             // So we now feel quite safe in converting it into a string
             // by calling the appropriate BroadcastDomainType method
-    		key = Integer.valueOf(keyStr);
-    		return key;
-		} catch (NumberFormatException e) {
-			s_logger.debug("Well well, how did '" + key
-					+ "' end up in the broadcast URI for the network?");
-			throw new CloudRuntimeException(String.format(
-					"Invalid GRE key parsed from"
-							+ "network broadcast URI (%s)", network
-							.getBroadcastUri().toString()));
-		}
-	}
-
-	@DB
+            key = Integer.valueOf(keyStr);
+            return key;
+        } catch (NumberFormatException e) {
+            s_logger.debug("Well well, how did '" + key
+                + "' end up in the broadcast URI for the network?");
+            throw new CloudRuntimeException(String.format(
+                "Invalid GRE key parsed from"
+                    + "network broadcast URI (%s)", network
+                    .getBroadcastUri().toString()));
+        }
+    }
+
+    @DB
     protected void CheckAndCreateTunnel(VirtualMachine instance, Network nw, DeployDestination dest) {
 
-		s_logger.debug("Creating tunnels with OVS tunnel manager");
-		if (instance.getType() != VirtualMachine.Type.User
-				&& instance.getType() != VirtualMachine.Type.DomainRouter) {
-			s_logger.debug("Will not work if you're not"
-					+ "an instance or a virtual router");
-			return;
-		}
-
-		long hostId = dest.getHost().getId();
-		int key = getGreKey(nw);
-		// Find active VMs with a NIC on the target network
-		List<UserVmVO> vms = _userVmDao.listByNetworkIdAndStates(nw.getId(),
-				State.Running, State.Starting, State.Stopping, State.Unknown,
-				State.Migrating);
-		// Find routers for the network
-		List<DomainRouterVO> routers = _routerDao.findByNetwork(nw.getId());
-		List<VMInstanceVO> ins = new ArrayList<VMInstanceVO>();
-		if (vms != null) {
-			ins.addAll(vms);
-		}
-		if (routers.size() != 0) {
-			ins.addAll(routers);
-		}
-		List<Long> toHostIds = new ArrayList<Long>();
-		List<Long> fromHostIds = new ArrayList<Long>();
+        s_logger.debug("Creating tunnels with OVS tunnel manager");
+        if (instance.getType() != VirtualMachine.Type.User
+            && instance.getType() != VirtualMachine.Type.DomainRouter) {
+            s_logger.debug("Will not work if you're not"
+                + "an instance or a virtual router");
+            return;
+        }
+
+        long hostId = dest.getHost().getId();
+        int key = getGreKey(nw);
+        // Find active VMs with a NIC on the target network
+        List<UserVmVO> vms = _userVmDao.listByNetworkIdAndStates(nw.getId(),
+            State.Running, State.Starting, State.Stopping, State.Unknown,
+            State.Migrating);
+        // Find routers for the network
+        List<DomainRouterVO> routers = _routerDao.findByNetwork(nw.getId());
+        List<VMInstanceVO> ins = new ArrayList<VMInstanceVO>();
+        if (vms != null) {
+            ins.addAll(vms);
+        }
+        if (routers.size() != 0) {
+            ins.addAll(routers);
+        }
+        List<Long> toHostIds = new ArrayList<Long>();
+        List<Long> fromHostIds = new ArrayList<Long>();
         for (VMInstanceVO v : ins) {
             Long rh = v.getHostId();
             if (rh == null || rh.longValue() == hostId) {
@@ -305,7 +305,7 @@ public class OvsTunnelManagerImpl extends ManagerBase implements OvsTunnelManage
             if (ta == null || ta.getState().equals("FAILED")) {
                 s_logger.debug("Attempting to create tunnel from:" + hostId + " to:" + rh.longValue());
                 if (ta == null) {
-                    this.createTunnelRecord(hostId, rh.longValue(), nw.getId(), key);
+                    createTunnelRecord(hostId, rh.longValue(), nw.getId(), key);
                 }
                 if (!toHostIds.contains(rh)) {
                     toHostIds.add(rh);
@@ -313,15 +313,15 @@ public class OvsTunnelManagerImpl extends ManagerBase implements OvsTunnelManage
             }
 
             ta = _tunnelNetworkDao.getByFromToNetwork(rh.longValue(),
-            		hostId, nw.getId());
+                hostId, nw.getId());
             // Try and create the tunnel even if a previous attempt failed
             if (ta == null || ta.getState().equals("FAILED")) {
-            	s_logger.debug("Attempting to create tunnel from:" +
-            			rh.longValue() + " to:" + hostId);
-            	if (ta == null) {
-            		this.createTunnelRecord(rh.longValue(), hostId,
-            				nw.getId(), key);
-            	}
+                s_logger.debug("Attempting to create tunnel from:" +
+                    rh.longValue() + " to:" + hostId);
+                if (ta == null) {
+                    createTunnelRecord(rh.longValue(), hostId,
+                        nw.getId(), key);
+                }
                 if (!fromHostIds.contains(rh)) {
                     fromHostIds.add(rh);
                 }
@@ -333,89 +333,88 @@ public class OvsTunnelManagerImpl extends ManagerBase implements OvsTunnelManage
             if (myIp == null)
                 throw new GreTunnelException("Unable to retrieve the source " + "endpoint for the GRE tunnel." + "Failure is on host:" + dest.getHost().getId());
             boolean noHost = true;
-			for (Long i : toHostIds) {
-				HostVO rHost = _hostDao.findById(i);
-				String otherIp = getGreEndpointIP(rHost, nw);
-				if (otherIp == null)
-					throw new GreTunnelException(
-							"Unable to retrieve the remote "
-									+ "endpoint for the GRE tunnel."
-									+ "Failure is on host:" + rHost.getId());
-				Commands cmds = new Commands(
-						new OvsCreateTunnelCommand(otherIp, key,
-								Long.valueOf(hostId), i, nw.getId(), myIp));
-				s_logger.debug("Ask host " + hostId
-						+ " to create gre tunnel to " + i);
-				Answer[] answers = _agentMgr.send(hostId, cmds);
-				handleCreateTunnelAnswer(answers);
-				noHost = false;
-			}
-
-			for (Long i : fromHostIds) {
-				HostVO rHost = _hostDao.findById(i);
-				String otherIp = getGreEndpointIP(rHost, nw);
-				Commands cmds = new Commands(new OvsCreateTunnelCommand(myIp,
-						key, i, Long.valueOf(hostId), nw.getId(), otherIp));
-				s_logger.debug("Ask host " + i + " to create gre tunnel to "
-						+ hostId);
-				Answer[] answers = _agentMgr.send(i, cmds);
-				handleCreateTunnelAnswer(answers);
-				noHost = false;
-			}
-			// If no tunnels have been configured, perform the bridge setup
-			// anyway
-			// This will ensure VIF rules will be triggered
-			if (noHost) {
-				Commands cmds = new Commands(new OvsSetupBridgeCommand(key,
-						hostId, nw.getId()));
-				s_logger.debug("Ask host " + hostId
-						+ " to configure bridge for network:" + nw.getId());
-				Answer[] answers = _agentMgr.send(hostId, cmds);
-				handleSetupBridgeAnswer(answers);
-			}
-		} catch (Exception e) {
-			// I really thing we should do a better handling of these exceptions
-			s_logger.warn("Ovs Tunnel network created tunnel failed", e);
-		}
-	}
-
-	@Override
-	public boolean isOvsTunnelEnabled() {
-		return true;
-	}
+            for (Long i : toHostIds) {
+                HostVO rHost = _hostDao.findById(i);
+                String otherIp = getGreEndpointIP(rHost, nw);
+                if (otherIp == null)
+                    throw new GreTunnelException(
+                        "Unable to retrieve the remote "
+                            + "endpoint for the GRE tunnel."
+                            + "Failure is on host:" + rHost.getId());
+                Commands cmds = new Commands(
+                    new OvsCreateTunnelCommand(otherIp, key,
+                        Long.valueOf(hostId), i, nw.getId(), myIp));
+                s_logger.debug("Ask host " + hostId
+                    + " to create gre tunnel to " + i);
+                Answer[] answers = _agentMgr.send(hostId, cmds);
+                handleCreateTunnelAnswer(answers);
+                noHost = false;
+            }
+
+            for (Long i : fromHostIds) {
+                HostVO rHost = _hostDao.findById(i);
+                String otherIp = getGreEndpointIP(rHost, nw);
+                Commands cmds = new Commands(new OvsCreateTunnelCommand(myIp,
+                    key, i, Long.valueOf(hostId), nw.getId(), otherIp));
+                s_logger.debug("Ask host " + i + " to create gre tunnel to "
+                    + hostId);
+                Answer[] answers = _agentMgr.send(i, cmds);
+                handleCreateTunnelAnswer(answers);
+                noHost = false;
+            }
+            // If no tunnels have been configured, perform the bridge setup
+            // anyway
+            // This will ensure VIF rules will be triggered
+            if (noHost) {
+                Commands cmds = new Commands(new OvsSetupBridgeCommand(key,
+                    hostId, nw.getId()));
+                s_logger.debug("Ask host " + hostId
+                    + " to configure bridge for network:" + nw.getId());
+                Answer[] answers = _agentMgr.send(hostId, cmds);
+                handleSetupBridgeAnswer(answers);
+            }
+        } catch (Exception e) {
+            // I really thing we should do a better handling of these exceptions
+            s_logger.warn("Ovs Tunnel network created tunnel failed", e);
+        }
+    }
+
+    @Override
+    public boolean isOvsTunnelEnabled() {
+        return true;
+    }
 
     @Override
     public void VmCheckAndCreateTunnel(VirtualMachineProfile vm,
-    		Network nw, DeployDestination dest) {
+        Network nw, DeployDestination dest) {
         CheckAndCreateTunnel(vm.getVirtualMachine(), nw, dest);
     }
 
     @DB
-    private void handleDestroyTunnelAnswer(Answer ans, long from, long to, long network_id) {
+    private void handleDestroyTunnelAnswer(Answer ans, long from, long to, long networkId) {
         if (ans.getResult()) {
             OvsTunnelNetworkVO lock = _tunnelNetworkDao.acquireInLockTable(Long.valueOf(1));
             if (lock == null) {
                 s_logger.warn(String.format("failed to lock" +
-                		"ovs_tunnel_account, remove record of " +
-                         "tunnel(from=%1$s, to=%2$s account=%3$s) failed",
-                         from, to, network_id));
+                    "ovs_tunnel_account, remove record of " +
+                    "tunnel(from=%1$s, to=%2$s account=%3$s) failed",
+                    from, to, networkId));
                 return;
             }
 
-            _tunnelNetworkDao.removeByFromToNetwork(from, to, network_id);
+            _tunnelNetworkDao.removeByFromToNetwork(from, to, networkId);
             _tunnelNetworkDao.releaseFromLockTable(lock.getId());
 
             s_logger.debug(String.format("Destroy tunnel(account:%1$s," +
-            		"from:%2$s, to:%3$s) successful",
-            		network_id, from, to));
+                "from:%2$s, to:%3$s) successful",
+                networkId, from, to));
         } else {
-            s_logger.debug(String.format("Destroy tunnel(account:%1$s," + "from:%2$s, to:%3$s) failed", network_id, from, to));
+            s_logger.debug(String.format("Destroy tunnel(account:%1$s," + "from:%2$s, to:%3$s) failed", networkId, from, to));
         }
     }
 
     @DB
-    private void handleDestroyBridgeAnswer(Answer ans,
-    		long host_id, long network_id) {
+    private void handleDestroyBridgeAnswer(Answer ans, long hostId, long networkId) {
 
         if (ans.getResult()) {
             OvsTunnelNetworkVO lock = _tunnelNetworkDao.acquireInLockTable(Long.valueOf(1));
@@ -424,14 +423,14 @@ public class OvsTunnelManagerImpl extends ManagerBase implements OvsTunnelManage
                 return;
             }
 
-            _tunnelNetworkDao.removeByFromNetwork(host_id, network_id);
+            _tunnelNetworkDao.removeByFromNetwork(hostId, networkId);
             _tunnelNetworkDao.releaseFromLockTable(lock.getId());
 
             s_logger.debug(String.format("Destroy bridge for" +
-            		"network %1$s successful", network_id));
+                "network %1$s successful", networkId));
         } else {
-        	s_logger.debug(String.format("Destroy bridge for" +
-        			"network %1$s failed", network_id));
+            s_logger.debug(String.format("Destroy bridge for" +
+                "network %1$s failed", networkId));
         }
     }
 
@@ -442,9 +441,9 @@ public class OvsTunnelManagerImpl extends ManagerBase implements OvsTunnelManage
 
     @Override
     public void CheckAndDestroyTunnel(VirtualMachine vm, Network nw) {
-		// if (!_isEnabled) {
-		// return;
-		// }
+        // if (!_isEnabled) {
+        // return;
+        // }
 
         List<UserVmVO> userVms = _userVmDao.listByAccountIdAndHostId(vm.getAccountId(), vm.getHostId());
         if (vm.getType() == VirtualMachine.Type.User) {
@@ -472,19 +471,19 @@ public class OvsTunnelManagerImpl extends ManagerBase implements OvsTunnelManage
 
             /* Then ask hosts have peer tunnel with me to destroy them */
             List<OvsTunnelNetworkVO> peers =
-            		_tunnelNetworkDao.listByToNetwork(vm.getHostId(),
-            				nw.getId());
+                _tunnelNetworkDao.listByToNetwork(vm.getHostId(),
+                    nw.getId());
             for (OvsTunnelNetworkVO p : peers) {
-            	// If the tunnel was not successfully created don't bother to remove it
-            	if (p.getState().equals("SUCCESS")) {
-	                cmd = new OvsDestroyTunnelCommand(p.getNetworkId(), key,
-	                		p.getPortName());
-	                s_logger.debug("Destroying tunnel to " + vm.getHostId() +
-	                		" from " + p.getFrom());
-	                ans = _agentMgr.send(p.getFrom(), cmd);
-	                handleDestroyTunnelAnswer(ans, p.getFrom(),
-	                		p.getTo(), p.getNetworkId());
-            	}
+                // If the tunnel was not successfully created don't bother to remove it
+                if (p.getState().equals("SUCCESS")) {
+                    cmd = new OvsDestroyTunnelCommand(p.getNetworkId(), key,
+                        p.getPortName());
+                    s_logger.debug("Destroying tunnel to " + vm.getHostId() +
+                        " from " + p.getFrom());
+                    ans = _agentMgr.send(p.getFrom(), cmd);
+                    handleDestroyTunnelAnswer(ans, p.getFrom(),
+                        p.getTo(), p.getNetworkId());
+                }
             }
         } catch (Exception e) {
             s_logger.warn(String.format("Destroy tunnel(account:%1$s," + "hostId:%2$s) failed", vm.getAccountId(), vm.getHostId()), e);

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/be5e5cc6/plugins/network-elements/palo-alto/src/com/cloud/network/element/PaloAltoExternalFirewallElement.java
----------------------------------------------------------------------
diff --git a/plugins/network-elements/palo-alto/src/com/cloud/network/element/PaloAltoExternalFirewallElement.java b/plugins/network-elements/palo-alto/src/com/cloud/network/element/PaloAltoExternalFirewallElement.java
index be9a0b8..cfb64b8 100644
--- a/plugins/network-elements/palo-alto/src/com/cloud/network/element/PaloAltoExternalFirewallElement.java
+++ b/plugins/network-elements/palo-alto/src/com/cloud/network/element/PaloAltoExternalFirewallElement.java
@@ -27,7 +27,6 @@ import javax.inject.Inject;
 
 import org.apache.log4j.Logger;
 
-import org.apache.cloudstack.api.response.ExternalFirewallResponse;
 import org.apache.cloudstack.framework.config.dao.ConfigurationDao;
 import org.apache.cloudstack.network.ExternalNetworkDeviceManager.NetworkDevice;
 
@@ -42,7 +41,6 @@ import com.cloud.configuration.Config;
 import com.cloud.configuration.ConfigurationManager;
 import com.cloud.dc.DataCenter;
 import com.cloud.dc.DataCenter.NetworkType;
-import com.cloud.dc.DataCenterVO;
 import com.cloud.dc.dao.DataCenterDao;
 import com.cloud.deploy.DeployDestination;
 import com.cloud.exception.ConcurrentOperationException;
@@ -51,7 +49,6 @@ import com.cloud.exception.InsufficientNetworkCapacityException;
 import com.cloud.exception.InvalidParameterValueException;
 import com.cloud.exception.ResourceUnavailableException;
 import com.cloud.host.Host;
-import com.cloud.host.HostVO;
 import com.cloud.host.dao.HostDao;
 import com.cloud.host.dao.HostDetailsDao;
 import com.cloud.network.ExternalFirewallDeviceManagerImpl;

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/be5e5cc6/plugins/network-elements/palo-alto/src/com/cloud/network/element/PaloAltoFirewallElementService.java
----------------------------------------------------------------------
diff --git a/plugins/network-elements/palo-alto/src/com/cloud/network/element/PaloAltoFirewallElementService.java b/plugins/network-elements/palo-alto/src/com/cloud/network/element/PaloAltoFirewallElementService.java
index 12f0407..d30baca 100644
--- a/plugins/network-elements/palo-alto/src/com/cloud/network/element/PaloAltoFirewallElementService.java
+++ b/plugins/network-elements/palo-alto/src/com/cloud/network/element/PaloAltoFirewallElementService.java
@@ -18,15 +18,12 @@ package com.cloud.network.element;
 
 import java.util.List;
 
-import org.apache.cloudstack.api.response.ExternalFirewallResponse;
-
 import com.cloud.api.commands.AddPaloAltoFirewallCmd;
 import com.cloud.api.commands.ConfigurePaloAltoFirewallCmd;
 import com.cloud.api.commands.DeletePaloAltoFirewallCmd;
 import com.cloud.api.commands.ListPaloAltoFirewallNetworksCmd;
 import com.cloud.api.commands.ListPaloAltoFirewallsCmd;
 import com.cloud.api.response.PaloAltoFirewallResponse;
-import com.cloud.host.Host;
 import com.cloud.network.Network;
 import com.cloud.network.dao.ExternalFirewallDeviceVO;
 import com.cloud.utils.component.PluggableService;