From 43bebcd0500832254a935a30267c466e51d85580 Mon Sep 17 00:00:00 2001 From: alena Date: Mon, 10 Oct 2011 10:51:21 -0700 Subject: [PATCH 001/159] Fixed regression bug in listNetworks call (introduced during Project feature implementation) --- server/src/com/cloud/network/NetworkManagerImpl.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/server/src/com/cloud/network/NetworkManagerImpl.java b/server/src/com/cloud/network/NetworkManagerImpl.java index f0c1a1af16e..56808f7df76 100755 --- a/server/src/com/cloud/network/NetworkManagerImpl.java +++ b/server/src/com/cloud/network/NetworkManagerImpl.java @@ -2008,7 +2008,7 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag //account level networks SearchCriteria accountSC = _networksDao.createSearchCriteria(); if (!permittedAccounts.isEmpty()) { - accountSC.addAnd("accountId", SearchCriteria.Op.IN, permittedAccounts); + accountSC.addAnd("accountId", SearchCriteria.Op.IN, permittedAccounts.toArray()); } accountSC.addAnd("isShared", SearchCriteria.Op.EQ, false); From 0121c0516d5b6d7baeb326e0029d25742ce6e538 Mon Sep 17 00:00:00 2001 From: Sheng Yang Date: Fri, 7 Oct 2011 18:07:35 -0700 Subject: [PATCH 002/159] Network: Add Service providers In the past, the NetworkElement would cover almost all the functionality that e.g. virtual router can cover: firewall, source NAT, static NAT, password, VPN... So anyone want to implement the NetworkElement would have to implement these service's specific methods, even it wouldn't support it. Also, if we want to find a e.g. FirewallServiceProvider, we have to proceed all the current network service providers, to call a method to know if it support such service. That's neither elegant nor scaling way to do it. As the first step, this patch separates each ServiceProvider from NetworkElement (there are some interface already out of NetworkElement, so this patch slightly modifies them too), and only the class would implement the correlated interface, would have the ability to do these services. --- .../element/FirewallServiceProvider.java | 19 ++++++ .../cloud/network/element/NetworkElement.java | 33 ---------- .../element/PasswordServiceProvider.java | 12 ++++ .../RemoteAccessVPNServiceProvider.java | 18 ++++++ .../element/SourceNATServiceProvider.java | 20 ++++++ .../element/StaticNATServiceProvider.java | 20 ++++++ .../network/vpn/PasswordResetElement.java | 30 --------- .../network/vpn/RemoteAccessVpnElement.java | 34 ---------- .../src/com/cloud/network/NetworkManager.java | 8 +-- .../com/cloud/network/NetworkManagerImpl.java | 62 +++++++++++++++---- .../network/element/BareMetalElement.java | 16 ----- .../element/CloudZonesNetworkElement.java | 25 +------- .../cloud/network/element/DhcpElement.java | 20 ++---- .../element/ElasticLoadBalancerElement.java | 13 ++-- .../network/element/ExternalDhcpElement.java | 24 +------ .../element/ExternalFirewallElement.java | 17 +++-- .../F5ExternalLoadBalancerElement.java | 14 ++--- .../NetscalerExternalLoadBalancerElement.java | 14 ++--- .../com/cloud/network/element/OvsElement.java | 20 ------ .../network/element/VirtualRouterElement.java | 23 ++++++- .../vpn/RemoteAccessVpnManagerImpl.java | 13 ++-- .../src/com/cloud/vm/UserVmManagerImpl.java | 6 +- 22 files changed, 204 insertions(+), 257 deletions(-) create mode 100644 api/src/com/cloud/network/element/FirewallServiceProvider.java create mode 100644 api/src/com/cloud/network/element/PasswordServiceProvider.java create mode 100644 api/src/com/cloud/network/element/RemoteAccessVPNServiceProvider.java create mode 100644 api/src/com/cloud/network/element/SourceNATServiceProvider.java create mode 100644 api/src/com/cloud/network/element/StaticNATServiceProvider.java delete mode 100644 api/src/com/cloud/network/vpn/PasswordResetElement.java delete mode 100644 api/src/com/cloud/network/vpn/RemoteAccessVpnElement.java diff --git a/api/src/com/cloud/network/element/FirewallServiceProvider.java b/api/src/com/cloud/network/element/FirewallServiceProvider.java new file mode 100644 index 00000000000..9d00da94949 --- /dev/null +++ b/api/src/com/cloud/network/element/FirewallServiceProvider.java @@ -0,0 +1,19 @@ +package com.cloud.network.element; + +import java.util.List; + +import com.cloud.exception.ResourceUnavailableException; +import com.cloud.network.Network; +import com.cloud.network.rules.FirewallRule; + +public interface FirewallServiceProvider extends NetworkElement { + /** + * Apply rules + * @param network + * @param rules + * @return + * @throws ResourceUnavailableException + */ + boolean applyRules(Network network, List rules) throws ResourceUnavailableException; + boolean isFirewallServiceProvider(); +} diff --git a/api/src/com/cloud/network/element/NetworkElement.java b/api/src/com/cloud/network/element/NetworkElement.java index bf9ca329b8e..8ff75971b09 100644 --- a/api/src/com/cloud/network/element/NetworkElement.java +++ b/api/src/com/cloud/network/element/NetworkElement.java @@ -21,7 +21,6 @@ */ package com.cloud.network.element; -import java.util.List; import java.util.Map; import com.cloud.deploy.DeployDestination; @@ -33,9 +32,6 @@ import com.cloud.network.Network; import com.cloud.network.Network.Capability; import com.cloud.network.Network.Provider; import com.cloud.network.Network.Service; -import com.cloud.network.PublicIpAddress; -import com.cloud.network.rules.FirewallRule; -import com.cloud.network.rules.StaticNat; import com.cloud.offering.NetworkOffering; import com.cloud.utils.component.Adapter; import com.cloud.vm.NicProfile; @@ -115,33 +111,4 @@ public interface NetworkElement extends Adapter { * @throws ConcurrentOperationException */ boolean destroy(Network network) throws ConcurrentOperationException, ResourceUnavailableException; - - - /** - * Apply ip addresses to this network - * @param network - * @param ipAddress - * @return - * @throws ResourceUnavailableException - */ - boolean applyIps(Network network, List ipAddress) throws ResourceUnavailableException; - - /** - * Apply rules - * @param network - * @param rules - * @return - * @throws ResourceUnavailableException - */ - boolean applyRules(Network network, List rules) throws ResourceUnavailableException; - - /** - * Creates static nat rule (public IP to private IP mapping) on the network element - * @param config - * @param rules - * @return - * @throws ResourceUnavailableException - */ - boolean applyStaticNats(Network config, List rules) throws ResourceUnavailableException; - } diff --git a/api/src/com/cloud/network/element/PasswordServiceProvider.java b/api/src/com/cloud/network/element/PasswordServiceProvider.java new file mode 100644 index 00000000000..092c3590b72 --- /dev/null +++ b/api/src/com/cloud/network/element/PasswordServiceProvider.java @@ -0,0 +1,12 @@ +package com.cloud.network.element; + +import com.cloud.exception.ResourceUnavailableException; +import com.cloud.network.Network; +import com.cloud.vm.NicProfile; +import com.cloud.vm.VirtualMachine; +import com.cloud.vm.VirtualMachineProfile; + +public interface PasswordServiceProvider extends NetworkElement { + boolean savePassword(Network network, NicProfile nic, VirtualMachineProfile vm) throws ResourceUnavailableException; + boolean isPasswordServiceProvider(); +} diff --git a/api/src/com/cloud/network/element/RemoteAccessVPNServiceProvider.java b/api/src/com/cloud/network/element/RemoteAccessVPNServiceProvider.java new file mode 100644 index 00000000000..31026bfbe5c --- /dev/null +++ b/api/src/com/cloud/network/element/RemoteAccessVPNServiceProvider.java @@ -0,0 +1,18 @@ +package com.cloud.network.element; + +import java.util.List; + +import com.cloud.exception.ResourceUnavailableException; +import com.cloud.network.Network; +import com.cloud.network.RemoteAccessVpn; +import com.cloud.network.VpnUser; + +public interface RemoteAccessVPNServiceProvider extends NetworkElement { + String[] applyVpnUsers(RemoteAccessVpn vpn, List users) throws ResourceUnavailableException; + + boolean startVpn(Network network, RemoteAccessVpn vpn) throws ResourceUnavailableException; + + boolean stopVpn(Network network, RemoteAccessVpn vpn) throws ResourceUnavailableException; + + boolean isRemoteAccessVPNServiceProvider(); +} diff --git a/api/src/com/cloud/network/element/SourceNATServiceProvider.java b/api/src/com/cloud/network/element/SourceNATServiceProvider.java new file mode 100644 index 00000000000..2d1d9761de0 --- /dev/null +++ b/api/src/com/cloud/network/element/SourceNATServiceProvider.java @@ -0,0 +1,20 @@ +package com.cloud.network.element; + +import java.util.List; + +import com.cloud.exception.ResourceUnavailableException; +import com.cloud.network.Network; +import com.cloud.network.PublicIpAddress; + +public interface SourceNATServiceProvider extends NetworkElement { + /** + * Apply ip addresses to this network + * @param network + * @param ipAddress + * @return + * @throws ResourceUnavailableException + */ + boolean applyIps(Network network, List ipAddress) throws ResourceUnavailableException; + + boolean isSourceNATServiceProvider(); +} diff --git a/api/src/com/cloud/network/element/StaticNATServiceProvider.java b/api/src/com/cloud/network/element/StaticNATServiceProvider.java new file mode 100644 index 00000000000..91ea72406ad --- /dev/null +++ b/api/src/com/cloud/network/element/StaticNATServiceProvider.java @@ -0,0 +1,20 @@ +package com.cloud.network.element; + +import java.util.List; + +import com.cloud.exception.ResourceUnavailableException; +import com.cloud.network.Network; +import com.cloud.network.rules.StaticNat; + +public interface StaticNATServiceProvider extends NetworkElement { + /** + * Creates static nat rule (public IP to private IP mapping) on the network element + * @param config + * @param rules + * @return + * @throws ResourceUnavailableException + */ + boolean applyStaticNats(Network config, List rules) throws ResourceUnavailableException; + + boolean isStaticNATServiceProvider(); +} diff --git a/api/src/com/cloud/network/vpn/PasswordResetElement.java b/api/src/com/cloud/network/vpn/PasswordResetElement.java deleted file mode 100644 index ab362b451eb..00000000000 --- a/api/src/com/cloud/network/vpn/PasswordResetElement.java +++ /dev/null @@ -1,30 +0,0 @@ -/** - * Copyright (C) 2010 Cloud.com, Inc. All rights reserved. - * - * This software is licensed under the GNU General Public License v3 or later. - * - * It is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or any later version. - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - * - */ - -package com.cloud.network.vpn; - -import com.cloud.exception.ResourceUnavailableException; -import com.cloud.network.Network; -import com.cloud.vm.NicProfile; -import com.cloud.vm.VirtualMachine; -import com.cloud.vm.VirtualMachineProfile; - -public interface PasswordResetElement { - - boolean savePassword(Network network, NicProfile nic, VirtualMachineProfile vm) throws ResourceUnavailableException; -} diff --git a/api/src/com/cloud/network/vpn/RemoteAccessVpnElement.java b/api/src/com/cloud/network/vpn/RemoteAccessVpnElement.java deleted file mode 100644 index 0a1dfbfd379..00000000000 --- a/api/src/com/cloud/network/vpn/RemoteAccessVpnElement.java +++ /dev/null @@ -1,34 +0,0 @@ -/** - * Copyright (C) 2010 Cloud.com, Inc. All rights reserved. - * - * This software is licensed under the GNU General Public License v3 or later. - * - * It is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or any later version. - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - * - */ -package com.cloud.network.vpn; - -import java.util.List; - -import com.cloud.exception.ResourceUnavailableException; -import com.cloud.network.Network; -import com.cloud.network.RemoteAccessVpn; -import com.cloud.network.VpnUser; -import com.cloud.utils.component.Adapter; - -public interface RemoteAccessVpnElement extends Adapter { - String[] applyVpnUsers(RemoteAccessVpn vpn, List users) throws ResourceUnavailableException; - - boolean startVpn(Network network, RemoteAccessVpn vpn) throws ResourceUnavailableException; - - boolean stopVpn(Network network, RemoteAccessVpn vpn) throws ResourceUnavailableException; -} diff --git a/server/src/com/cloud/network/NetworkManager.java b/server/src/com/cloud/network/NetworkManager.java index 1fe3c6371f8..582b884f850 100644 --- a/server/src/com/cloud/network/NetworkManager.java +++ b/server/src/com/cloud/network/NetworkManager.java @@ -33,11 +33,11 @@ import com.cloud.network.Network.GuestIpType; import com.cloud.network.Network.Service; import com.cloud.network.Networks.TrafficType; import com.cloud.network.addr.PublicIp; +import com.cloud.network.element.PasswordServiceProvider; +import com.cloud.network.element.RemoteAccessVPNServiceProvider; import com.cloud.network.guru.NetworkGuru; import com.cloud.network.rules.FirewallRule; import com.cloud.network.rules.StaticNat; -import com.cloud.network.vpn.PasswordResetElement; -import com.cloud.network.vpn.RemoteAccessVpnElement; import com.cloud.offerings.NetworkOfferingVO; import com.cloud.user.Account; import com.cloud.user.AccountVO; @@ -142,7 +142,7 @@ public interface NetworkManager extends NetworkService { boolean applyRules(List rules, boolean continueOnError) throws ResourceUnavailableException; - List getRemoteAccessVpnElements(); + List getRemoteAccessVpnElements(); PublicIpAddress getPublicIpAddress(long ipAddressId); @@ -186,7 +186,7 @@ public interface NetworkManager extends NetworkService { Nic getDefaultNic(long vmId); - List getPasswordResetElements(); + List getPasswordResetElements(); boolean zoneIsConfiguredForExternalNetworking(long zoneId); diff --git a/server/src/com/cloud/network/NetworkManagerImpl.java b/server/src/com/cloud/network/NetworkManagerImpl.java index 56808f7df76..acc8a091de0 100755 --- a/server/src/com/cloud/network/NetworkManagerImpl.java +++ b/server/src/com/cloud/network/NetworkManagerImpl.java @@ -97,7 +97,12 @@ import com.cloud.network.dao.FirewallRulesDao; import com.cloud.network.dao.IPAddressDao; import com.cloud.network.dao.NetworkDao; import com.cloud.network.dao.NetworkDomainDao; +import com.cloud.network.element.FirewallServiceProvider; import com.cloud.network.element.NetworkElement; +import com.cloud.network.element.PasswordServiceProvider; +import com.cloud.network.element.RemoteAccessVPNServiceProvider; +import com.cloud.network.element.SourceNATServiceProvider; +import com.cloud.network.element.StaticNATServiceProvider; import com.cloud.network.guru.NetworkGuru; import com.cloud.network.lb.LoadBalancingRulesManager; import com.cloud.network.rules.FirewallManager; @@ -106,8 +111,6 @@ import com.cloud.network.rules.FirewallRule.Purpose; import com.cloud.network.rules.FirewallRuleVO; import com.cloud.network.rules.RulesManager; import com.cloud.network.rules.StaticNat; -import com.cloud.network.vpn.PasswordResetElement; -import com.cloud.network.vpn.RemoteAccessVpnElement; import com.cloud.network.vpn.RemoteAccessVpnService; import com.cloud.offering.NetworkOffering; import com.cloud.offering.NetworkOffering.Availability; @@ -493,10 +496,19 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag } boolean success = true; + int found = 0; for (NetworkElement element : _networkElements) { try { + if (!(element instanceof SourceNATServiceProvider)) { + continue; + } + SourceNATServiceProvider e = (SourceNATServiceProvider)element; + if (!e.isSourceNATServiceProvider()) { + continue; + } + found ++; s_logger.trace("Asking " + element + " to apply ip associations"); - element.applyIps(network, publicIps); + e.applyIps(network, publicIps); } catch (ResourceUnavailableException e) { success = false; if (!continueOnError) { @@ -1478,11 +1490,14 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag } @Override - public List getRemoteAccessVpnElements() { - List elements = new ArrayList(); + public List getRemoteAccessVpnElements() { + List elements = new ArrayList(); for (NetworkElement element : _networkElements) { - if (element instanceof RemoteAccessVpnElement) { - elements.add((RemoteAccessVpnElement) element); + if (element instanceof RemoteAccessVPNServiceProvider) { + RemoteAccessVPNServiceProvider e = (RemoteAccessVPNServiceProvider) element; + if (e.isRemoteAccessVPNServiceProvider()) { + elements.add(e); + } } } @@ -2303,9 +2318,18 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag boolean success = true; Network network = _networksDao.findById(rules.get(0).getNetworkId()); + int found = 0; for (NetworkElement ne : _networkElements) { try { - boolean handled = ne.applyRules(network, rules); + if (!(ne instanceof FirewallServiceProvider)) { + continue; + } + FirewallServiceProvider e = (FirewallServiceProvider)ne; + if (!e.isFirewallServiceProvider()) { + continue; + } + found ++; + boolean handled = e.applyRules(network, rules); s_logger.debug("Network Rules for network " + network.getId() + " were " + (handled ? "" : " not") + " handled by " + ne.getName()); } catch (ResourceUnavailableException e) { if (!continueOnError) { @@ -2810,11 +2834,14 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag } @Override - public List getPasswordResetElements() { - List elements = new ArrayList(); + public List getPasswordResetElements() { + List elements = new ArrayList(); for (NetworkElement element : _networkElements) { - if (element instanceof PasswordResetElement) { - elements.add((PasswordResetElement) element); + if (element instanceof PasswordServiceProvider) { + PasswordServiceProvider e = (PasswordServiceProvider)element; + if (e.isPasswordServiceProvider()) { + elements.add(e); + } } } return elements; @@ -3267,9 +3294,18 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag boolean success = true; Network network = _networksDao.findById(staticNats.get(0).getNetworkId()); + int found = 0; for (NetworkElement ne : _networkElements) { try { - boolean handled = ne.applyStaticNats(network, staticNats); + if (!(ne instanceof StaticNATServiceProvider)) { + continue; + } + StaticNATServiceProvider e = (StaticNATServiceProvider)ne; + if (!e.isStaticNATServiceProvider()) { + continue; + } + found ++; + boolean handled = e.applyStaticNats(network, staticNats); s_logger.debug("Static Nat for network " + network.getId() + " were " + (handled ? "" : " not") + " handled by " + ne.getName()); } catch (ResourceUnavailableException e) { if (!continueOnError) { diff --git a/server/src/com/cloud/network/element/BareMetalElement.java b/server/src/com/cloud/network/element/BareMetalElement.java index fae74d8fbb3..9fc1d60e7a1 100644 --- a/server/src/com/cloud/network/element/BareMetalElement.java +++ b/server/src/com/cloud/network/element/BareMetalElement.java @@ -116,20 +116,4 @@ public class BareMetalElement extends AdapterBase implements NetworkElement { public boolean destroy(Network network) throws ConcurrentOperationException, ResourceUnavailableException { return true; } - - @Override - public boolean applyIps(Network network, List ipAddress) throws ResourceUnavailableException { - return true; - } - - @Override - public boolean applyRules(Network network, List rules) throws ResourceUnavailableException { - return true; - } - - @Override - public boolean applyStaticNats(Network config, List rules) throws ResourceUnavailableException { - return false; - } - } diff --git a/server/src/com/cloud/network/element/CloudZonesNetworkElement.java b/server/src/com/cloud/network/element/CloudZonesNetworkElement.java index 39259eec57d..f9d778b41eb 100644 --- a/server/src/com/cloud/network/element/CloudZonesNetworkElement.java +++ b/server/src/com/cloud/network/element/CloudZonesNetworkElement.java @@ -74,7 +74,6 @@ import com.cloud.network.router.VirtualNetworkApplianceManager; import com.cloud.network.router.VirtualRouter; import com.cloud.network.rules.FirewallRule; import com.cloud.network.rules.StaticNat; -import com.cloud.network.vpn.PasswordResetElement; import com.cloud.offering.NetworkOffering; import com.cloud.service.dao.ServiceOfferingDao; import com.cloud.uservm.UserVm; @@ -96,7 +95,7 @@ import com.cloud.vm.dao.UserVmDao; @Local(value=NetworkElement.class) -public class CloudZonesNetworkElement extends AdapterBase implements NetworkElement, PasswordResetElement{ +public class CloudZonesNetworkElement extends AdapterBase implements NetworkElement { private static final Logger s_logger = Logger.getLogger(CloudZonesNetworkElement.class); private static final Map> capabilities = setCapabilities(); @@ -194,22 +193,6 @@ public class CloudZonesNetworkElement extends AdapterBase implements NetworkElem return false; //assume that the agent will remove userdata etc } - @Override - public boolean applyRules(Network network, List rules) throws ResourceUnavailableException { - return false; - } - - @Override - public boolean applyIps(Network network, List ipAddress) throws ResourceUnavailableException { - return false; - } - - @Override - public boolean applyStaticNats(Network config, List rules) throws ResourceUnavailableException { - return false; - } - - @Override public Provider getProvider() { return Provider.ExternalDhcpServer; @@ -236,12 +219,6 @@ public class CloudZonesNetworkElement extends AdapterBase implements NetworkElem } - @Override - public boolean savePassword(Network network, NicProfile nic, VirtualMachineProfile vm) throws ResourceUnavailableException{ - s_logger.trace("Cloudzones element doesn't handle saving passwords for " + network); - return true; - } - private VmDataCommand generateVmDataCommand( String vmPrivateIpAddress, String userData, String serviceOffering, String zoneName, String guestIpAddress, String vmName, String vmInstanceName, long vmId, String publicKey) { VmDataCommand cmd = new VmDataCommand(vmPrivateIpAddress, vmName); diff --git a/server/src/com/cloud/network/element/DhcpElement.java b/server/src/com/cloud/network/element/DhcpElement.java index 179f266ab1e..a8a51631f60 100644 --- a/server/src/com/cloud/network/element/DhcpElement.java +++ b/server/src/com/cloud/network/element/DhcpElement.java @@ -49,7 +49,6 @@ import com.cloud.network.router.VirtualRouter; import com.cloud.network.router.VirtualRouter.Role; import com.cloud.network.rules.FirewallRule; import com.cloud.network.rules.StaticNat; -import com.cloud.network.vpn.PasswordResetElement; import com.cloud.offering.NetworkOffering; import com.cloud.org.Cluster; import com.cloud.user.AccountManager; @@ -68,7 +67,7 @@ import com.cloud.vm.dao.UserVmDao; @Local(value=NetworkElement.class) -public class DhcpElement extends AdapterBase implements NetworkElement, PasswordResetElement{ +public class DhcpElement extends AdapterBase implements PasswordServiceProvider { private static final Logger s_logger = Logger.getLogger(DhcpElement.class); private static final Map> capabilities = setCapabilities(); @@ -176,17 +175,6 @@ public class DhcpElement extends AdapterBase implements NetworkElement, Password return result; } - @Override - public boolean applyRules(Network network, List rules) throws ResourceUnavailableException { - return false; - } - - @Override - public boolean applyIps(Network network, List ipAddress) throws ResourceUnavailableException { - return false; - } - - @Override public Provider getProvider() { return Provider.DhcpServer; @@ -268,9 +256,9 @@ public class DhcpElement extends AdapterBase implements NetworkElement, Password return _routerMgr.savePasswordToRouter(network, nic, uservm, routers); } - + @Override - public boolean applyStaticNats(Network config, List rules) throws ResourceUnavailableException { - return false; + public boolean isPasswordServiceProvider() { + return true; } } diff --git a/server/src/com/cloud/network/element/ElasticLoadBalancerElement.java b/server/src/com/cloud/network/element/ElasticLoadBalancerElement.java index 535cea4fd9d..b814d959b8a 100644 --- a/server/src/com/cloud/network/element/ElasticLoadBalancerElement.java +++ b/server/src/com/cloud/network/element/ElasticLoadBalancerElement.java @@ -54,7 +54,7 @@ import com.cloud.vm.VirtualMachineProfile; @Local(value=NetworkElement.class) -public class ElasticLoadBalancerElement extends AdapterBase implements NetworkElement{ +public class ElasticLoadBalancerElement extends AdapterBase implements FirewallServiceProvider { private static final Logger s_logger = Logger.getLogger(ElasticLoadBalancerElement.class); private static final Map> capabilities = setCapabilities(); @Inject NetworkManager _networkManager; @@ -135,11 +135,6 @@ public class ElasticLoadBalancerElement extends AdapterBase implements NetworkEl return false; } - @Override - public boolean applyIps(Network network, List ipAddress) throws ResourceUnavailableException { - return true; - } - @Override public boolean applyRules(Network network, List rules) throws ResourceUnavailableException { if (!canHandle(network)) { @@ -167,9 +162,9 @@ public class ElasticLoadBalancerElement extends AdapterBase implements NetworkEl } return true; } - + @Override - public boolean applyStaticNats(Network config, List rules) throws ResourceUnavailableException { - return false; + public boolean isFirewallServiceProvider() { + return true; } } diff --git a/server/src/com/cloud/network/element/ExternalDhcpElement.java b/server/src/com/cloud/network/element/ExternalDhcpElement.java index e8c19817863..777f4af7b41 100644 --- a/server/src/com/cloud/network/element/ExternalDhcpElement.java +++ b/server/src/com/cloud/network/element/ExternalDhcpElement.java @@ -45,7 +45,6 @@ import com.cloud.network.Network.Service; import com.cloud.network.Networks.TrafficType; import com.cloud.network.rules.FirewallRule; import com.cloud.network.rules.StaticNat; -import com.cloud.network.vpn.PasswordResetElement; import com.cloud.offering.NetworkOffering; import com.cloud.utils.component.AdapterBase; import com.cloud.utils.component.Inject; @@ -56,7 +55,7 @@ import com.cloud.vm.VirtualMachine; import com.cloud.vm.VirtualMachineProfile; @Local(value=NetworkElement.class) -public class ExternalDhcpElement extends AdapterBase implements NetworkElement, PasswordResetElement { +public class ExternalDhcpElement extends AdapterBase implements NetworkElement { private static final Logger s_logger = Logger.getLogger(ExternalDhcpElement.class); @Inject ExternalDhcpManager _dhcpMgr; private boolean canHandle(GuestIpType ipType, DeployDestination dest, TrafficType trafficType) { @@ -72,11 +71,6 @@ public class ExternalDhcpElement extends AdapterBase implements NetworkElement, return false; } - @Override - public boolean savePassword(Network network, NicProfile nic, VirtualMachineProfile vm) throws ResourceUnavailableException { - return true; - } - @Override public Map> getCapabilities() { return null; @@ -129,20 +123,4 @@ public class ExternalDhcpElement extends AdapterBase implements NetworkElement, public boolean destroy(Network network) throws ConcurrentOperationException, ResourceUnavailableException { return true; } - - @Override - public boolean applyIps(Network network, List ipAddress) throws ResourceUnavailableException { - return true; - } - - @Override - public boolean applyRules(Network network, List rules) throws ResourceUnavailableException { - return true; - } - - @Override - public boolean applyStaticNats(Network config, List rules) throws ResourceUnavailableException { - return false; - } - } diff --git a/server/src/com/cloud/network/element/ExternalFirewallElement.java b/server/src/com/cloud/network/element/ExternalFirewallElement.java index 0d0db524b17..1a848b05aff 100644 --- a/server/src/com/cloud/network/element/ExternalFirewallElement.java +++ b/server/src/com/cloud/network/element/ExternalFirewallElement.java @@ -48,7 +48,6 @@ import com.cloud.network.VpnUser; import com.cloud.network.dao.NetworkDao; import com.cloud.network.rules.FirewallRule; import com.cloud.network.rules.StaticNat; -import com.cloud.network.vpn.RemoteAccessVpnElement; import com.cloud.offering.NetworkOffering; import com.cloud.offerings.NetworkOfferingVO; import com.cloud.offerings.dao.NetworkOfferingDao; @@ -60,7 +59,7 @@ import com.cloud.vm.VirtualMachine; import com.cloud.vm.VirtualMachineProfile; @Local(value=NetworkElement.class) -public class ExternalFirewallElement extends AdapterBase implements NetworkElement, RemoteAccessVpnElement { +public class ExternalFirewallElement extends AdapterBase implements SourceNATServiceProvider, FirewallServiceProvider, RemoteAccessVPNServiceProvider { private static final Logger s_logger = Logger.getLogger(ExternalFirewallElement.class); @@ -239,8 +238,18 @@ public class ExternalFirewallElement extends AdapterBase implements NetworkEleme } @Override - public boolean applyStaticNats(Network config, List rules) throws ResourceUnavailableException { - return false; + public boolean isSourceNATServiceProvider() { + return true; + } + + @Override + public boolean isFirewallServiceProvider() { + return true; + } + + @Override + public boolean isRemoteAccessVPNServiceProvider() { + return true; } } diff --git a/server/src/com/cloud/network/element/F5ExternalLoadBalancerElement.java b/server/src/com/cloud/network/element/F5ExternalLoadBalancerElement.java index 51ab184c9ef..af105990747 100644 --- a/server/src/com/cloud/network/element/F5ExternalLoadBalancerElement.java +++ b/server/src/com/cloud/network/element/F5ExternalLoadBalancerElement.java @@ -53,7 +53,7 @@ import com.cloud.vm.VirtualMachine; import com.cloud.vm.VirtualMachineProfile; @Local(value=NetworkElement.class) -public class F5ExternalLoadBalancerElement extends AdapterBase implements NetworkElement { +public class F5ExternalLoadBalancerElement extends AdapterBase implements FirewallServiceProvider { private static final Logger s_logger = Logger.getLogger(F5ExternalLoadBalancerElement.class); @@ -106,11 +106,6 @@ public class F5ExternalLoadBalancerElement extends AdapterBase implements Networ return true; } - @Override - public boolean applyIps(Network network, List ipAddress) throws ResourceUnavailableException { - return true; - } - @Override public boolean applyRules(Network config, List rules) throws ResourceUnavailableException { if (!canHandle(config)) { @@ -153,10 +148,9 @@ public class F5ExternalLoadBalancerElement extends AdapterBase implements Networ public boolean restart(Network network, ReservationContext context, boolean cleanup) throws ConcurrentOperationException, ResourceUnavailableException, InsufficientCapacityException{ return true; } - + @Override - public boolean applyStaticNats(Network config, List rules) throws ResourceUnavailableException { - return false; + public boolean isFirewallServiceProvider() { + return true; } - } diff --git a/server/src/com/cloud/network/element/NetscalerExternalLoadBalancerElement.java b/server/src/com/cloud/network/element/NetscalerExternalLoadBalancerElement.java index 4fe36ae2d09..fed4aac022f 100644 --- a/server/src/com/cloud/network/element/NetscalerExternalLoadBalancerElement.java +++ b/server/src/com/cloud/network/element/NetscalerExternalLoadBalancerElement.java @@ -53,7 +53,7 @@ import com.cloud.vm.VirtualMachine; import com.cloud.vm.VirtualMachineProfile; @Local(value=NetworkElement.class) -public class NetscalerExternalLoadBalancerElement extends AdapterBase implements NetworkElement { +public class NetscalerExternalLoadBalancerElement extends AdapterBase implements FirewallServiceProvider { private static final Logger s_logger = Logger.getLogger(NetscalerExternalLoadBalancerElement.class); @@ -106,11 +106,6 @@ public class NetscalerExternalLoadBalancerElement extends AdapterBase implements return true; } - @Override - public boolean applyIps(Network network, List ipAddress) throws ResourceUnavailableException { - return true; - } - @Override public boolean applyRules(Network config, List rules) throws ResourceUnavailableException { if (!canHandle(config)) { @@ -153,10 +148,9 @@ public class NetscalerExternalLoadBalancerElement extends AdapterBase implements public boolean restart(Network network, ReservationContext context, boolean cleanup) throws ConcurrentOperationException, ResourceUnavailableException, InsufficientCapacityException{ return true; } - + @Override - public boolean applyStaticNats(Network config, List rules) throws ResourceUnavailableException { - return false; + public boolean isFirewallServiceProvider() { + return true; } - } diff --git a/server/src/com/cloud/network/element/OvsElement.java b/server/src/com/cloud/network/element/OvsElement.java index 4dca5bf9234..1b928578533 100644 --- a/server/src/com/cloud/network/element/OvsElement.java +++ b/server/src/com/cloud/network/element/OvsElement.java @@ -52,20 +52,6 @@ public class OvsElement extends AdapterBase implements NetworkElement { @Inject OvsNetworkManager _ovsVlanMgr; @Inject OvsTunnelManager _ovsTunnelMgr; - @Override - public boolean applyIps(Network network, - List ipAddress) - throws ResourceUnavailableException { - return true; - } - - @Override - public boolean applyRules(Network network, - List rules) - throws ResourceUnavailableException { - return true; - } - @Override public boolean destroy(Network network) throws ConcurrentOperationException, ResourceUnavailableException { @@ -143,10 +129,4 @@ public class OvsElement extends AdapterBase implements NetworkElement { throws ConcurrentOperationException, ResourceUnavailableException { return true; } - - @Override - public boolean applyStaticNats(Network config, List rules) throws ResourceUnavailableException { - return false; - } - } diff --git a/server/src/com/cloud/network/element/VirtualRouterElement.java b/server/src/com/cloud/network/element/VirtualRouterElement.java index eb77ad262b5..ef73c1bd5b8 100644 --- a/server/src/com/cloud/network/element/VirtualRouterElement.java +++ b/server/src/com/cloud/network/element/VirtualRouterElement.java @@ -51,7 +51,6 @@ import com.cloud.network.router.VirtualRouter.Role; import com.cloud.network.rules.FirewallRule; import com.cloud.network.rules.RulesManager; import com.cloud.network.rules.StaticNat; -import com.cloud.network.vpn.RemoteAccessVpnElement; import com.cloud.offering.NetworkOffering; import com.cloud.offerings.NetworkOfferingVO; import com.cloud.offerings.dao.NetworkOfferingDao; @@ -71,7 +70,7 @@ import com.cloud.vm.dao.UserVmDao; @Local(value=NetworkElement.class) -public class VirtualRouterElement extends DhcpElement implements NetworkElement, RemoteAccessVpnElement { +public class VirtualRouterElement extends DhcpElement implements SourceNATServiceProvider, FirewallServiceProvider, StaticNATServiceProvider, RemoteAccessVPNServiceProvider { private static final Logger s_logger = Logger.getLogger(VirtualRouterElement.class); private static final Map> capabilities = setCapabilities(); @@ -381,4 +380,24 @@ public class VirtualRouterElement extends DhcpElement implements NetworkElement, return _routerMgr.savePasswordToRouter(network, nic, uservm, routers); } + + @Override + public boolean isSourceNATServiceProvider() { + return true; + } + + @Override + public boolean isFirewallServiceProvider() { + return true; + } + + @Override + public boolean isStaticNATServiceProvider() { + return true; + } + + @Override + public boolean isRemoteAccessVPNServiceProvider() { + return true; + } } diff --git a/server/src/com/cloud/network/vpn/RemoteAccessVpnManagerImpl.java b/server/src/com/cloud/network/vpn/RemoteAccessVpnManagerImpl.java index 2fee27513d3..bcfd0889587 100755 --- a/server/src/com/cloud/network/vpn/RemoteAccessVpnManagerImpl.java +++ b/server/src/com/cloud/network/vpn/RemoteAccessVpnManagerImpl.java @@ -50,6 +50,7 @@ import com.cloud.network.dao.FirewallRulesDao; import com.cloud.network.dao.IPAddressDao; import com.cloud.network.dao.RemoteAccessVpnDao; import com.cloud.network.dao.VpnUserDao; +import com.cloud.network.element.RemoteAccessVPNServiceProvider; import com.cloud.network.router.VirtualNetworkApplianceManager; import com.cloud.network.rules.FirewallManager; import com.cloud.network.rules.FirewallRule; @@ -221,10 +222,10 @@ public class RemoteAccessVpnManagerImpl implements RemoteAccessVpnService, Manag _remoteAccessVpnDao.update(vpn.getServerAddressId(), vpn); - List elements = _networkMgr.getRemoteAccessVpnElements(); + List elements = _networkMgr.getRemoteAccessVpnElements(); boolean success = false; try { - for (RemoteAccessVpnElement element : elements) { + for (RemoteAccessVPNServiceProvider element : elements) { if (element.stopVpn(network, vpn)) { success = true; break; @@ -349,7 +350,7 @@ public class RemoteAccessVpnManagerImpl implements RemoteAccessVpnService, Manag Network network = _networkMgr.getNetwork(vpn.getNetworkId()); - List elements = _networkMgr.getRemoteAccessVpnElements(); + List elements = _networkMgr.getRemoteAccessVpnElements(); boolean started = false; try { boolean firewallOpened = true; @@ -358,7 +359,7 @@ public class RemoteAccessVpnManagerImpl implements RemoteAccessVpnService, Manag } if (firewallOpened) { - for (RemoteAccessVpnElement element : elements) { + for (RemoteAccessVPNServiceProvider element : elements) { if (element.startVpn(network, vpn)) { started = true; break; @@ -395,12 +396,12 @@ public class RemoteAccessVpnManagerImpl implements RemoteAccessVpnService, Manag } } - List elements = _networkMgr.getRemoteAccessVpnElements(); + List elements = _networkMgr.getRemoteAccessVpnElements(); boolean success = true; boolean[] finals = new boolean[users.size()]; - for (RemoteAccessVpnElement element : elements) { + for (RemoteAccessVPNServiceProvider element : elements) { s_logger.debug("Applying vpn access to " + element.getName()); for (RemoteAccessVpnVO vpn : vpns) { try { diff --git a/server/src/com/cloud/vm/UserVmManagerImpl.java b/server/src/com/cloud/vm/UserVmManagerImpl.java index 864ec1611c8..8880c8d2254 100755 --- a/server/src/com/cloud/vm/UserVmManagerImpl.java +++ b/server/src/com/cloud/vm/UserVmManagerImpl.java @@ -127,6 +127,7 @@ import com.cloud.network.dao.IPAddressDao; import com.cloud.network.dao.LoadBalancerDao; import com.cloud.network.dao.LoadBalancerVMMapDao; import com.cloud.network.dao.NetworkDao; +import com.cloud.network.element.PasswordServiceProvider; import com.cloud.network.lb.LoadBalancingRulesManager; import com.cloud.network.router.VirtualNetworkApplianceManager; import com.cloud.network.rules.FirewallManager; @@ -134,7 +135,6 @@ import com.cloud.network.rules.RulesManager; import com.cloud.network.security.SecurityGroup; import com.cloud.network.security.SecurityGroupManager; import com.cloud.network.security.dao.SecurityGroupDao; -import com.cloud.network.vpn.PasswordResetElement; import com.cloud.offering.NetworkOffering; import com.cloud.offering.NetworkOffering.Availability; import com.cloud.offering.ServiceOffering; @@ -424,10 +424,10 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, Manager VirtualMachineProfile vmProfile = new VirtualMachineProfileImpl(vmInstance); vmProfile.setParameter(VirtualMachineProfile.Param.VmPassword, password); - List elements = _networkMgr.getPasswordResetElements(); + List elements = _networkMgr.getPasswordResetElements(); boolean result = true; - for (PasswordResetElement element : elements) { + for (PasswordServiceProvider element : elements) { if (!element.savePassword(defaultNetwork, defaultNicProfile, vmProfile)) { result = false; } From 30d48c40b349eb8081f991fd5ae9680163034995 Mon Sep 17 00:00:00 2001 From: Sheng Yang Date: Mon, 10 Oct 2011 15:26:21 -0700 Subject: [PATCH 003/159] Network as a service(NaaS): Separate redundant virtual router as a standalone element Since we would introduce a way to specify each service provider in the network offering, it's better for redundant virtual router as a separate service provider. Also isRedundant() flag in the network offering would be removed. Redundant virtual router temporality won't work from now. Until we're able to add different network elements/service providers in network_offering. --- .../com/cloud/offering/NetworkOffering.java | 2 - .../src/com/cloud/api/ApiResponseHelper.java | 2 +- .../ConfigurationManagerImpl.java | 2 +- .../com/cloud/network/NetworkManagerImpl.java | 15 +--- .../RedundantVirtualRouterElement.java | 76 +++++++++++++++++++ .../network/element/VirtualRouterElement.java | 6 +- .../cloud/offerings/NetworkOfferingVO.java | 17 +---- .../cloud/server/ConfigurationServerImpl.java | 6 +- setup/db/create-schema.sql | 1 - 9 files changed, 88 insertions(+), 39 deletions(-) create mode 100644 server/src/com/cloud/network/element/RedundantVirtualRouterElement.java diff --git a/api/src/com/cloud/offering/NetworkOffering.java b/api/src/com/cloud/offering/NetworkOffering.java index f43b9943297..394e1d9ce37 100644 --- a/api/src/com/cloud/offering/NetworkOffering.java +++ b/api/src/com/cloud/offering/NetworkOffering.java @@ -101,6 +101,4 @@ public interface NetworkOffering { GuestIpType getGuestType(); String getUniqueName(); - - boolean getRedundantRouter(); } diff --git a/server/src/com/cloud/api/ApiResponseHelper.java b/server/src/com/cloud/api/ApiResponseHelper.java index 25f9aae5d4c..24d0c8fc032 100755 --- a/server/src/com/cloud/api/ApiResponseHelper.java +++ b/server/src/com/cloud/api/ApiResponseHelper.java @@ -2110,7 +2110,7 @@ public class ApiResponseHelper implements ResponseGenerator { response.setSpecifyVlan(offering.getSpecifyVlan()); response.setAvailability(offering.getAvailability().toString()); response.setNetworkRate(ApiDBUtils.getNetworkRate(offering.getId())); - response.setRedundantRouter(offering.getRedundantRouter()); + response.setRedundantRouter(false); if (offering.getGuestType() != null) { response.setGuestIpType(offering.getGuestType().toString()); diff --git a/server/src/com/cloud/configuration/ConfigurationManagerImpl.java b/server/src/com/cloud/configuration/ConfigurationManagerImpl.java index 226054359e2..6475d72d78a 100755 --- a/server/src/com/cloud/configuration/ConfigurationManagerImpl.java +++ b/server/src/com/cloud/configuration/ConfigurationManagerImpl.java @@ -2909,7 +2909,7 @@ public class ConfigurationManagerImpl implements ConfigurationManager, Configura } NetworkOfferingVO offering = new NetworkOfferingVO(name, displayText, trafficType, false, specifyVlan, networkRate, multicastRate, maxConnections, false, availability, true, true, true, - gatewayService, firewallService, lbService, vpnService, guestIpType, redundantRouter); + gatewayService, firewallService, lbService, vpnService, guestIpType); if ((offering = _networkOfferingDao.persist(offering)) != null) { UserContext.current().setEventDetails(" Id: "+offering.getId()+" Name: "+name); diff --git a/server/src/com/cloud/network/NetworkManagerImpl.java b/server/src/com/cloud/network/NetworkManagerImpl.java index acc8a091de0..a3b56e463b2 100755 --- a/server/src/com/cloud/network/NetworkManagerImpl.java +++ b/server/src/com/cloud/network/NetworkManagerImpl.java @@ -783,20 +783,20 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag NetworkOfferingVO guestNetworkOffering = new NetworkOfferingVO(NetworkOffering.SystemGuestNetwork, "System Offering for System-Guest-Network", TrafficType.Guest, true, false, null, null, null, true, Availability.Required, // services - all true except for firewall/lb/vpn and gateway services - true, true, true, false, false, false, false, GuestIpType.Direct, false); + true, true, true, false, false, false, false, GuestIpType.Direct); guestNetworkOffering = _networkOfferingDao.persistDefaultNetworkOffering(guestNetworkOffering); _systemNetworks.put(NetworkOfferingVO.SystemGuestNetwork, guestNetworkOffering); NetworkOfferingVO defaultGuestNetworkOffering = new NetworkOfferingVO(NetworkOffering.DefaultVirtualizedNetworkOffering, "Virtual Vlan", TrafficType.Guest, false, false, null, null, null, true, Availability.Required, // services - true, true, true, true, true, true, true, GuestIpType.Virtual, false); + true, true, true, true, true, true, true, GuestIpType.Virtual); defaultGuestNetworkOffering = _networkOfferingDao.persistDefaultNetworkOffering(defaultGuestNetworkOffering); NetworkOfferingVO defaultGuestDirectNetworkOffering = new NetworkOfferingVO(NetworkOffering.DefaultDirectNetworkOffering, "Direct", TrafficType.Guest, false, true, null, null, null, true, Availability.Optional, // services - all true except for firewall/lb/vpn and gateway services - true, true, true, false, false, false, false, GuestIpType.Direct, false); + true, true, true, false, false, false, false, GuestIpType.Direct); defaultGuestDirectNetworkOffering = _networkOfferingDao.persistDefaultNetworkOffering(defaultGuestDirectNetworkOffering); AccountsUsingNetworkSearch = _accountDao.createSearchBuilder(); @@ -1185,15 +1185,6 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag } NetworkOfferingVO offering = _networkOfferingDao.findById(network.getNetworkOfferingId()); - // Check if we can provide the required capability - if (offering.getRedundantRouter()) { - DataCenter dc = dest.getDataCenter(); - Map> capabilities = getZoneCapabilities(dc.getId()); - Map gatewayCap = capabilities.get(Service.Gateway); - if (!gatewayCap.get(Capability.Redundancy).equalsIgnoreCase("true")) { - throw new InsufficientNetworkCapacityException("Zone lacks the feature that required by NetworkOffering: Redundant Virtual Router", dc.getClass(), dc.getId()); - } - } network.setReservationId(context.getReservationId()); network.setState(Network.State.Implementing); diff --git a/server/src/com/cloud/network/element/RedundantVirtualRouterElement.java b/server/src/com/cloud/network/element/RedundantVirtualRouterElement.java new file mode 100644 index 00000000000..21ca386da72 --- /dev/null +++ b/server/src/com/cloud/network/element/RedundantVirtualRouterElement.java @@ -0,0 +1,76 @@ +package com.cloud.network.element; + +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import javax.ejb.Local; + +import org.apache.log4j.Logger; + +import com.cloud.dc.DataCenter; +import com.cloud.deploy.DeployDestination; +import com.cloud.exception.ConcurrentOperationException; +import com.cloud.exception.InsufficientCapacityException; +import com.cloud.exception.ResourceUnavailableException; +import com.cloud.network.Network; +import com.cloud.network.Network.GuestIpType; +import com.cloud.network.Network.Provider; +import com.cloud.network.router.VirtualRouter; +import com.cloud.offering.NetworkOffering; +import com.cloud.uservm.UserVm; +import com.cloud.vm.DomainRouterVO; +import com.cloud.vm.NicProfile; +import com.cloud.vm.ReservationContext; +import com.cloud.vm.VirtualMachine; +import com.cloud.vm.VirtualMachineProfile; + +@Local(value=NetworkElement.class) +public class RedundantVirtualRouterElement extends VirtualRouterElement { + private static final Logger s_logger = Logger.getLogger(RedundantVirtualRouterElement.class); + + private boolean canHandle(GuestIpType ipType, DataCenter dc) { + String provider = dc.getGatewayProvider(); + boolean result = (provider != null && ipType == GuestIpType.Virtual && provider.equals(Provider.VirtualRouter.getName())); + if (!result) { + s_logger.trace("Virtual router element only takes care of guest ip type " + GuestIpType.Virtual + " for provider " + Provider.VirtualRouter.getName()); + } + return result; + } + + + @Override + public boolean implement(Network guestConfig, NetworkOffering offering, DeployDestination dest, ReservationContext context) throws ResourceUnavailableException, ConcurrentOperationException, InsufficientCapacityException { + if (!canHandle(guestConfig.getGuestType(), dest.getDataCenter())) { + return false; + } + + Map params = new HashMap(1); + params.put(VirtualMachineProfile.Param.RestartNetwork, true); + + _routerMgr.deployVirtualRouter(guestConfig, dest, _accountMgr.getAccount(guestConfig.getAccountId()), params, true); + + return true; + } + + + @Override + public boolean prepare(Network network, NicProfile nic, VirtualMachineProfile vm, DeployDestination dest, ReservationContext context) throws ConcurrentOperationException, InsufficientCapacityException, ResourceUnavailableException { + if (canHandle(network.getGuestType(), dest.getDataCenter())) { + if (vm.getType() != VirtualMachine.Type.User) { + return false; + } + + @SuppressWarnings("unchecked") + VirtualMachineProfile uservm = (VirtualMachineProfile)vm; + List routers = _routerMgr.deployVirtualRouter(network, dest, _accountMgr.getAccount(network.getAccountId()), uservm.getParameters(), true); + if ((routers == null) || (routers.size() == 0)) { + throw new ResourceUnavailableException("Can't find at least one running router!", this.getClass(), 0); + } + List rets = _routerMgr.addVirtualMachineIntoNetwork(network, nic, uservm, dest, context, routers); + return (rets != null) && (!rets.isEmpty()); + } else { + return false; + } + } +} diff --git a/server/src/com/cloud/network/element/VirtualRouterElement.java b/server/src/com/cloud/network/element/VirtualRouterElement.java index ef73c1bd5b8..963757a7b7e 100644 --- a/server/src/com/cloud/network/element/VirtualRouterElement.java +++ b/server/src/com/cloud/network/element/VirtualRouterElement.java @@ -107,7 +107,7 @@ public class VirtualRouterElement extends DhcpElement implements SourceNATServic Map params = new HashMap(1); params.put(VirtualMachineProfile.Param.RestartNetwork, true); - _routerMgr.deployVirtualRouter(guestConfig, dest, _accountMgr.getAccount(guestConfig.getAccountId()), params, offering.getRedundantRouter()); + _routerMgr.deployVirtualRouter(guestConfig, dest, _accountMgr.getAccount(guestConfig.getAccountId()), params, false); return true; } @@ -122,9 +122,7 @@ public class VirtualRouterElement extends DhcpElement implements SourceNATServic @SuppressWarnings("unchecked") VirtualMachineProfile uservm = (VirtualMachineProfile)vm; - NetworkOfferingVO offering = _networkOfferingDao.findById(network.getNetworkOfferingId()); - boolean isRedundant = offering.getRedundantRouter(); - List routers = _routerMgr.deployVirtualRouter(network, dest, _accountMgr.getAccount(network.getAccountId()), uservm.getParameters(), isRedundant); + List routers = _routerMgr.deployVirtualRouter(network, dest, _accountMgr.getAccount(network.getAccountId()), uservm.getParameters(), false); if ((routers == null) || (routers.size() == 0)) { throw new ResourceUnavailableException("Can't find at least one running router!", this.getClass(), 0); } diff --git a/server/src/com/cloud/offerings/NetworkOfferingVO.java b/server/src/com/cloud/offerings/NetworkOfferingVO.java index da6c2a8a696..dacef41abb0 100644 --- a/server/src/com/cloud/offerings/NetworkOfferingVO.java +++ b/server/src/com/cloud/offerings/NetworkOfferingVO.java @@ -116,9 +116,6 @@ public class NetworkOfferingVO implements NetworkOffering { @Column(name="guest_type") GuestIpType guestType; - @Column(name="redundant_router") - boolean redundantRouter; - @Override public String getDisplayText() { return displayText; @@ -332,16 +329,7 @@ public class NetworkOfferingVO implements NetworkOffering { this.uniqueName = uniqueName; } - @Override - public boolean getRedundantRouter() { - return this.redundantRouter; - } - - public void setRedundantRouter(boolean redundantRouter) { - this.redundantRouter = redundantRouter; - } - - public NetworkOfferingVO(String name, String displayText, TrafficType trafficType, boolean systemOnly, boolean specifyVlan, Integer rateMbps, Integer multicastRateMbps, Integer concurrentConnections, boolean isDefault, Availability availability, boolean dhcpService, boolean dnsService, boolean userDataService, boolean gatewayService, boolean firewallService, boolean lbService, boolean vpnService, GuestIpType guestIpType, boolean isRedundantRouterEnabled) { + public NetworkOfferingVO(String name, String displayText, TrafficType trafficType, boolean systemOnly, boolean specifyVlan, Integer rateMbps, Integer multicastRateMbps, Integer concurrentConnections, boolean isDefault, Availability availability, boolean dhcpService, boolean dnsService, boolean userDataService, boolean gatewayService, boolean firewallService, boolean lbService, boolean vpnService, GuestIpType guestIpType) { this.name = name; this.displayText = displayText; this.rateMbps = rateMbps; @@ -360,7 +348,6 @@ public class NetworkOfferingVO implements NetworkOffering { this.lbService = lbService; this.vpnService = vpnService; this.guestType = guestIpType; - this.redundantRouter = isRedundantRouterEnabled; this.uniqueName = name; } @@ -370,7 +357,7 @@ public class NetworkOfferingVO implements NetworkOffering { * @param trafficType */ public NetworkOfferingVO(String name, TrafficType trafficType) { - this(name, "System Offering for " + name, trafficType, true, false, 0, 0, null, true, Availability.Required, false, false, false, false, false, false, false, null, false); + this(name, "System Offering for " + name, trafficType, true, false, 0, 0, null, true, Availability.Required, false, false, false, false, false, false, false, null); } @Override diff --git a/server/src/com/cloud/server/ConfigurationServerImpl.java b/server/src/com/cloud/server/ConfigurationServerImpl.java index 257fcf8bb75..a7aaaea3fec 100644 --- a/server/src/com/cloud/server/ConfigurationServerImpl.java +++ b/server/src/com/cloud/server/ConfigurationServerImpl.java @@ -829,7 +829,7 @@ public class ConfigurationServerImpl implements ConfigurationServer { true, false, null, null, null, true, Availability.Required, true, true, true, //services - all true except for lb/vpn and gateway - false, true, false, false, GuestIpType.Direct, false); + false, true, false, false, GuestIpType.Direct); guestNetworkOffering = _networkOfferingDao.persistDefaultNetworkOffering(guestNetworkOffering); @@ -840,7 +840,7 @@ public class ConfigurationServerImpl implements ConfigurationServer { false, false, null, null, null, true, Availability.Required, true, true, true, //services - true, true, true, true, GuestIpType.Virtual, false); + true, true, true, true, GuestIpType.Virtual); defaultGuestNetworkOffering = _networkOfferingDao.persistDefaultNetworkOffering(defaultGuestNetworkOffering); NetworkOfferingVO defaultGuestDirectNetworkOffering = new NetworkOfferingVO( NetworkOffering.DefaultDirectNetworkOffering, @@ -849,7 +849,7 @@ public class ConfigurationServerImpl implements ConfigurationServer { false, true, null, null, null, true, Availability.Optional, true, true, true, //services - all true except for firewall/lb/vpn and gateway - false, false, false, false, GuestIpType.Direct, false); + false, false, false, false, GuestIpType.Direct); defaultGuestNetworkOffering = _networkOfferingDao.persistDefaultNetworkOffering(defaultGuestDirectNetworkOffering); } diff --git a/setup/db/create-schema.sql b/setup/db/create-schema.sql index 1ae24aa8a68..9214a322b35 100755 --- a/setup/db/create-schema.sql +++ b/setup/db/create-schema.sql @@ -270,7 +270,6 @@ CREATE TABLE `cloud`.`network_offerings` ( `dhcp_service` int(1) unsigned NOT NULL DEFAULT 0 COMMENT 'true if network offering provides dhcp service', `shared_source_nat_service` int(1) unsigned NOT NULL DEFAULT 0 COMMENT 'true if the network offering provides the shared source nat service', `guest_type` char(32) COMMENT 'guest ip type of network offering', - `redundant_router` int(1) unsigned NOT NULL DEFAULT 0 COMMENT 'true if network offering provides redundant routers', PRIMARY KEY (`id`), INDEX `i_network_offerings__system_only`(`system_only`), INDEX `i_network_offerings__removed`(`removed`) From b2a007dc3cf5a5c614cb4f923e2fb610544a4e7b Mon Sep 17 00:00:00 2001 From: Sheng Yang Date: Tue, 11 Oct 2011 14:02:46 -0700 Subject: [PATCH 004/159] NaaS: Remove IsServiceProvider() functions If the element is the service provider for this network, then can be tell from network offering. We don't need these functions in the interface. --- .../element/FirewallServiceProvider.java | 1 - .../element/PasswordServiceProvider.java | 1 - .../RemoteAccessVPNServiceProvider.java | 2 -- .../element/SourceNATServiceProvider.java | 2 -- .../element/StaticNATServiceProvider.java | 2 -- .../com/cloud/network/NetworkManagerImpl.java | 17 ++-------------- .../cloud/network/element/DhcpElement.java | 5 ----- .../element/ElasticLoadBalancerElement.java | 5 ----- .../element/ExternalFirewallElement.java | 15 -------------- .../F5ExternalLoadBalancerElement.java | 5 ----- .../NetscalerExternalLoadBalancerElement.java | 5 ----- .../network/element/VirtualRouterElement.java | 20 ------------------- 12 files changed, 2 insertions(+), 78 deletions(-) diff --git a/api/src/com/cloud/network/element/FirewallServiceProvider.java b/api/src/com/cloud/network/element/FirewallServiceProvider.java index 9d00da94949..51818c5bdbb 100644 --- a/api/src/com/cloud/network/element/FirewallServiceProvider.java +++ b/api/src/com/cloud/network/element/FirewallServiceProvider.java @@ -15,5 +15,4 @@ public interface FirewallServiceProvider extends NetworkElement { * @throws ResourceUnavailableException */ boolean applyRules(Network network, List rules) throws ResourceUnavailableException; - boolean isFirewallServiceProvider(); } diff --git a/api/src/com/cloud/network/element/PasswordServiceProvider.java b/api/src/com/cloud/network/element/PasswordServiceProvider.java index 092c3590b72..f933aa9202f 100644 --- a/api/src/com/cloud/network/element/PasswordServiceProvider.java +++ b/api/src/com/cloud/network/element/PasswordServiceProvider.java @@ -8,5 +8,4 @@ import com.cloud.vm.VirtualMachineProfile; public interface PasswordServiceProvider extends NetworkElement { boolean savePassword(Network network, NicProfile nic, VirtualMachineProfile vm) throws ResourceUnavailableException; - boolean isPasswordServiceProvider(); } diff --git a/api/src/com/cloud/network/element/RemoteAccessVPNServiceProvider.java b/api/src/com/cloud/network/element/RemoteAccessVPNServiceProvider.java index 31026bfbe5c..522a4593a5d 100644 --- a/api/src/com/cloud/network/element/RemoteAccessVPNServiceProvider.java +++ b/api/src/com/cloud/network/element/RemoteAccessVPNServiceProvider.java @@ -13,6 +13,4 @@ public interface RemoteAccessVPNServiceProvider extends NetworkElement { boolean startVpn(Network network, RemoteAccessVpn vpn) throws ResourceUnavailableException; boolean stopVpn(Network network, RemoteAccessVpn vpn) throws ResourceUnavailableException; - - boolean isRemoteAccessVPNServiceProvider(); } diff --git a/api/src/com/cloud/network/element/SourceNATServiceProvider.java b/api/src/com/cloud/network/element/SourceNATServiceProvider.java index 2d1d9761de0..1f395953d0b 100644 --- a/api/src/com/cloud/network/element/SourceNATServiceProvider.java +++ b/api/src/com/cloud/network/element/SourceNATServiceProvider.java @@ -15,6 +15,4 @@ public interface SourceNATServiceProvider extends NetworkElement { * @throws ResourceUnavailableException */ boolean applyIps(Network network, List ipAddress) throws ResourceUnavailableException; - - boolean isSourceNATServiceProvider(); } diff --git a/api/src/com/cloud/network/element/StaticNATServiceProvider.java b/api/src/com/cloud/network/element/StaticNATServiceProvider.java index 91ea72406ad..a134be39d91 100644 --- a/api/src/com/cloud/network/element/StaticNATServiceProvider.java +++ b/api/src/com/cloud/network/element/StaticNATServiceProvider.java @@ -15,6 +15,4 @@ public interface StaticNATServiceProvider extends NetworkElement { * @throws ResourceUnavailableException */ boolean applyStaticNats(Network config, List rules) throws ResourceUnavailableException; - - boolean isStaticNATServiceProvider(); } diff --git a/server/src/com/cloud/network/NetworkManagerImpl.java b/server/src/com/cloud/network/NetworkManagerImpl.java index a3b56e463b2..7a56b5e5326 100755 --- a/server/src/com/cloud/network/NetworkManagerImpl.java +++ b/server/src/com/cloud/network/NetworkManagerImpl.java @@ -503,9 +503,6 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag continue; } SourceNATServiceProvider e = (SourceNATServiceProvider)element; - if (!e.isSourceNATServiceProvider()) { - continue; - } found ++; s_logger.trace("Asking " + element + " to apply ip associations"); e.applyIps(network, publicIps); @@ -1486,9 +1483,7 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag for (NetworkElement element : _networkElements) { if (element instanceof RemoteAccessVPNServiceProvider) { RemoteAccessVPNServiceProvider e = (RemoteAccessVPNServiceProvider) element; - if (e.isRemoteAccessVPNServiceProvider()) { - elements.add(e); - } + elements.add(e); } } @@ -2316,9 +2311,6 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag continue; } FirewallServiceProvider e = (FirewallServiceProvider)ne; - if (!e.isFirewallServiceProvider()) { - continue; - } found ++; boolean handled = e.applyRules(network, rules); s_logger.debug("Network Rules for network " + network.getId() + " were " + (handled ? "" : " not") + " handled by " + ne.getName()); @@ -2830,9 +2822,7 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag for (NetworkElement element : _networkElements) { if (element instanceof PasswordServiceProvider) { PasswordServiceProvider e = (PasswordServiceProvider)element; - if (e.isPasswordServiceProvider()) { - elements.add(e); - } + elements.add(e); } } return elements; @@ -3292,9 +3282,6 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag continue; } StaticNATServiceProvider e = (StaticNATServiceProvider)ne; - if (!e.isStaticNATServiceProvider()) { - continue; - } found ++; boolean handled = e.applyStaticNats(network, staticNats); s_logger.debug("Static Nat for network " + network.getId() + " were " + (handled ? "" : " not") + " handled by " + ne.getName()); diff --git a/server/src/com/cloud/network/element/DhcpElement.java b/server/src/com/cloud/network/element/DhcpElement.java index a8a51631f60..e9dde7e4127 100644 --- a/server/src/com/cloud/network/element/DhcpElement.java +++ b/server/src/com/cloud/network/element/DhcpElement.java @@ -256,9 +256,4 @@ public class DhcpElement extends AdapterBase implements PasswordServiceProvider return _routerMgr.savePasswordToRouter(network, nic, uservm, routers); } - - @Override - public boolean isPasswordServiceProvider() { - return true; - } } diff --git a/server/src/com/cloud/network/element/ElasticLoadBalancerElement.java b/server/src/com/cloud/network/element/ElasticLoadBalancerElement.java index b814d959b8a..2a09a83ada3 100644 --- a/server/src/com/cloud/network/element/ElasticLoadBalancerElement.java +++ b/server/src/com/cloud/network/element/ElasticLoadBalancerElement.java @@ -162,9 +162,4 @@ public class ElasticLoadBalancerElement extends AdapterBase implements FirewallS } return true; } - - @Override - public boolean isFirewallServiceProvider() { - return true; - } } diff --git a/server/src/com/cloud/network/element/ExternalFirewallElement.java b/server/src/com/cloud/network/element/ExternalFirewallElement.java index 1a848b05aff..07b9a377ec7 100644 --- a/server/src/com/cloud/network/element/ExternalFirewallElement.java +++ b/server/src/com/cloud/network/element/ExternalFirewallElement.java @@ -236,21 +236,6 @@ public class ExternalFirewallElement extends AdapterBase implements SourceNATSer public boolean restart(Network network, ReservationContext context, boolean cleanup) throws ConcurrentOperationException, ResourceUnavailableException, InsufficientCapacityException{ return true; } - - @Override - public boolean isSourceNATServiceProvider() { - return true; - } - - @Override - public boolean isFirewallServiceProvider() { - return true; - } - - @Override - public boolean isRemoteAccessVPNServiceProvider() { - return true; - } } diff --git a/server/src/com/cloud/network/element/F5ExternalLoadBalancerElement.java b/server/src/com/cloud/network/element/F5ExternalLoadBalancerElement.java index af105990747..e80ed7f0c73 100644 --- a/server/src/com/cloud/network/element/F5ExternalLoadBalancerElement.java +++ b/server/src/com/cloud/network/element/F5ExternalLoadBalancerElement.java @@ -148,9 +148,4 @@ public class F5ExternalLoadBalancerElement extends AdapterBase implements Firewa public boolean restart(Network network, ReservationContext context, boolean cleanup) throws ConcurrentOperationException, ResourceUnavailableException, InsufficientCapacityException{ return true; } - - @Override - public boolean isFirewallServiceProvider() { - return true; - } } diff --git a/server/src/com/cloud/network/element/NetscalerExternalLoadBalancerElement.java b/server/src/com/cloud/network/element/NetscalerExternalLoadBalancerElement.java index fed4aac022f..287419348fc 100644 --- a/server/src/com/cloud/network/element/NetscalerExternalLoadBalancerElement.java +++ b/server/src/com/cloud/network/element/NetscalerExternalLoadBalancerElement.java @@ -148,9 +148,4 @@ public class NetscalerExternalLoadBalancerElement extends AdapterBase implements public boolean restart(Network network, ReservationContext context, boolean cleanup) throws ConcurrentOperationException, ResourceUnavailableException, InsufficientCapacityException{ return true; } - - @Override - public boolean isFirewallServiceProvider() { - return true; - } } diff --git a/server/src/com/cloud/network/element/VirtualRouterElement.java b/server/src/com/cloud/network/element/VirtualRouterElement.java index 963757a7b7e..7c3fef2b358 100644 --- a/server/src/com/cloud/network/element/VirtualRouterElement.java +++ b/server/src/com/cloud/network/element/VirtualRouterElement.java @@ -378,24 +378,4 @@ public class VirtualRouterElement extends DhcpElement implements SourceNATServic return _routerMgr.savePasswordToRouter(network, nic, uservm, routers); } - - @Override - public boolean isSourceNATServiceProvider() { - return true; - } - - @Override - public boolean isFirewallServiceProvider() { - return true; - } - - @Override - public boolean isStaticNATServiceProvider() { - return true; - } - - @Override - public boolean isRemoteAccessVPNServiceProvider() { - return true; - } } From 8570b25506d0ce612ca82c19c7cc111458600cc0 Mon Sep 17 00:00:00 2001 From: prachi Date: Tue, 11 Oct 2011 17:34:32 -0700 Subject: [PATCH 005/159] NAAS: APIServer changes to introduce framework to read commands from pluggable components having separate commands.properties file Changes: - Added a new interface 'PluggableService' - Any component that can be packaged separately from cloudstack, can implement this interface and provide its own property file listing the API commands the component supports - As an example have made VirtualNetworkApplianceService pluggable and a new configureRouter command is added - ComponentLocator reads all the pluggable service from componentLibrary or from components.xml and instantiates the services. - As an example, DefaultComponentLibrary adds the pluggable service 'VirtualNetworkApplianceService' - Also components.xml.in has an entry to show how a pluggable service can be added, but it is commented out. - APIServer now reads the commands for each pluggable service and when a command for such a service is called, APIServer sets the required instance of the pluggable service in the coomand. - To do this a new annotation '@PlugService' is added that is processed by APIServer. This eliminates the dependency on the BaseCmd to instantiate the service instances. --- .../AgentComponentLibraryBase.java | 14 +- api/src/com/cloud/api/PlugService.java | 32 +++++ .../api/commands/ConfigureRouterCmd.java | 120 ++++++++++++++++++ .../VirtualNetworkApplianceService.java | 3 +- client/tomcatconf/components.xml.in | 1 + .../virtualrouter_commands.properties.in | 5 + server/src/com/cloud/api/ApiDispatcher.java | 43 +++++++ server/src/com/cloud/api/ApiServer.java | 51 +++++++- .../DefaultComponentLibrary.java | 14 ++ .../VirtualNetworkApplianceManagerImpl.java | 6 + .../utils/component/ComponentLibrary.java | 5 + .../utils/component/ComponentLibraryBase.java | 14 +- .../utils/component/ComponentLocator.java | 64 +++++++++- .../utils/component/PluggableService.java | 31 +++++ .../utils/component/MockComponentLocator.java | 12 +- 15 files changed, 402 insertions(+), 13 deletions(-) create mode 100644 api/src/com/cloud/api/PlugService.java create mode 100644 api/src/com/cloud/api/commands/ConfigureRouterCmd.java create mode 100644 client/tomcatconf/virtualrouter_commands.properties.in create mode 100644 utils/src/com/cloud/utils/component/PluggableService.java diff --git a/agent/src/com/cloud/agent/configuration/AgentComponentLibraryBase.java b/agent/src/com/cloud/agent/configuration/AgentComponentLibraryBase.java index 31e0f95145c..b481f438684 100755 --- a/agent/src/com/cloud/agent/configuration/AgentComponentLibraryBase.java +++ b/agent/src/com/cloud/agent/configuration/AgentComponentLibraryBase.java @@ -25,7 +25,7 @@ import com.cloud.utils.component.Adapter; import com.cloud.utils.component.ComponentLibraryBase; import com.cloud.utils.component.ComponentLocator.ComponentInfo; import com.cloud.utils.component.Manager; -import com.cloud.utils.component.SystemIntegrityChecker; +import com.cloud.utils.component.PluggableService; import com.cloud.utils.db.GenericDao; @@ -63,5 +63,17 @@ public class AgentComponentLibraryBase extends ComponentLibraryBase { protected void populateAdapters() { } + + protected void populateServices() { + + } + + @Override + public Map> getPluggableServices() { + if (_pluggableServices.size() == 0) { + populateServices(); + } + return _pluggableServices; + } } diff --git a/api/src/com/cloud/api/PlugService.java b/api/src/com/cloud/api/PlugService.java new file mode 100644 index 00000000000..0722b62a0c8 --- /dev/null +++ b/api/src/com/cloud/api/PlugService.java @@ -0,0 +1,32 @@ +/** + * Copyright (C) 2010 Cloud.com, Inc. All rights reserved. + * + * This software is licensed under the GNU General Public License v3 or later. + * + * It is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or any later version. + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + */ +package com.cloud.api; + +import static java.lang.annotation.ElementType.FIELD; +import static java.lang.annotation.RetentionPolicy.RUNTIME; + +import java.lang.annotation.Retention; +import java.lang.annotation.Target; + +import com.cloud.utils.component.PluggableService; + +@Target(FIELD) +@Retention(RUNTIME) +public @interface PlugService { + Class pluggableService() default PluggableService.class; +} diff --git a/api/src/com/cloud/api/commands/ConfigureRouterCmd.java b/api/src/com/cloud/api/commands/ConfigureRouterCmd.java new file mode 100644 index 00000000000..235f4622690 --- /dev/null +++ b/api/src/com/cloud/api/commands/ConfigureRouterCmd.java @@ -0,0 +1,120 @@ +/** + * Copyright (C) 2010 Cloud.com, Inc. All rights reserved. + * + * This software is licensed under the GNU General Public License v3 or later. + * + * It is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or any later version. + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + */ + +package com.cloud.api.commands; + +import org.apache.log4j.Logger; + +import com.cloud.api.ApiConstants; +import com.cloud.api.BaseAsyncCmd; +import com.cloud.api.BaseCmd; +import com.cloud.api.Implementation; +import com.cloud.api.Parameter; +import com.cloud.api.PlugService; +import com.cloud.api.ServerApiException; +import com.cloud.api.response.DomainRouterResponse; +import com.cloud.async.AsyncJob; +import com.cloud.event.EventTypes; +import com.cloud.exception.ConcurrentOperationException; +import com.cloud.exception.InsufficientCapacityException; +import com.cloud.exception.ResourceUnavailableException; +import com.cloud.network.VirtualNetworkApplianceService; +import com.cloud.network.router.VirtualRouter; +import com.cloud.user.Account; +import com.cloud.user.UserContext; + + + +@Implementation(responseObject=DomainRouterResponse.class, description="Configures a router.") +public class ConfigureRouterCmd extends BaseAsyncCmd { + public static final Logger s_logger = Logger.getLogger(ConfigureRouterCmd.class.getName()); + private static final String s_name = "configurerouterresponse"; + + @PlugService + private static VirtualNetworkApplianceService _myrouterService; + + ///////////////////////////////////////////////////// + //////////////// API parameters ///////////////////// + ///////////////////////////////////////////////////// + + @Parameter(name=ApiConstants.ID, type=CommandType.LONG, required=true, description="the ID of the router") + private Long id; + + ///////////////////////////////////////////////////// + /////////////////// Accessors /////////////////////// + ///////////////////////////////////////////////////// + + public Long getId() { + return id; + } + + ///////////////////////////////////////////////////// + /////////////// API Implementation/////////////////// + ///////////////////////////////////////////////////// + + @Override + public String getCommandName() { + return s_name; + } + + public static String getResultObjectName() { + return "router"; + } + + @Override + public long getEntityOwnerId() { + VirtualRouter router = _entityMgr.findById(VirtualRouter.class, getId()); + if (router != null) { + return router.getAccountId(); + } + + return Account.ACCOUNT_ID_SYSTEM; // no account info given, parent this command to SYSTEM so ERROR events are tracked + } + + @Override + public String getEventType() { + return EventTypes.EVENT_ROUTER_START; + } + + @Override + public String getEventDescription() { + return "configuring router: " + getId(); + } + + public AsyncJob.Type getInstanceType() { + return AsyncJob.Type.DomainRouter; + } + + public Long getInstanceId() { + return getId(); + } + + @Override + public void execute() throws ConcurrentOperationException, ResourceUnavailableException, InsufficientCapacityException{ + UserContext.current().setEventDetails("Router Id: "+getId()); + //This should call the configure API. Calling startRouter for now. + VirtualRouter result = _myrouterService.startRouter(id); + if (result != null){ + DomainRouterResponse routerResponse = _responseGenerator.createDomainRouterResponse(result); + routerResponse.setResponseName(getCommandName()); + this.setResponseObject(routerResponse); + } else { + throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to start router"); + } + } +} diff --git a/api/src/com/cloud/network/VirtualNetworkApplianceService.java b/api/src/com/cloud/network/VirtualNetworkApplianceService.java index 581ae727ddf..03935fcc0e0 100644 --- a/api/src/com/cloud/network/VirtualNetworkApplianceService.java +++ b/api/src/com/cloud/network/VirtualNetworkApplianceService.java @@ -22,8 +22,9 @@ import com.cloud.exception.ConcurrentOperationException; import com.cloud.exception.InsufficientCapacityException; import com.cloud.exception.ResourceUnavailableException; import com.cloud.network.router.VirtualRouter; +import com.cloud.utils.component.PluggableService; -public interface VirtualNetworkApplianceService{ +public interface VirtualNetworkApplianceService extends PluggableService{ /** * Starts domain router * @param cmd the command specifying router's id diff --git a/client/tomcatconf/components.xml.in b/client/tomcatconf/components.xml.in index 5e536df7cdf..b8a673d37d2 100755 --- a/client/tomcatconf/components.xml.in +++ b/client/tomcatconf/components.xml.in @@ -107,6 +107,7 @@ + diff --git a/client/tomcatconf/virtualrouter_commands.properties.in b/client/tomcatconf/virtualrouter_commands.properties.in new file mode 100644 index 00000000000..55ecb396567 --- /dev/null +++ b/client/tomcatconf/virtualrouter_commands.properties.in @@ -0,0 +1,5 @@ +### bitmap of permissions at the end of each classname, 1 = ADMIN, 2 = RESOURCE_DOMAIN_ADMIN, 4 = DOMAIN_ADMIN, 8 = USER +### Please standardize naming conventions to camel-case (even for acronyms). + +#### router commands +configureRouter=com.cloud.api.commands.ConfigureRouterCmd;7 \ No newline at end of file diff --git a/server/src/com/cloud/api/ApiDispatcher.java b/server/src/com/cloud/api/ApiDispatcher.java index a3f455d8d37..b96dd0b68fa 100755 --- a/server/src/com/cloud/api/ApiDispatcher.java +++ b/server/src/com/cloud/api/ApiDispatcher.java @@ -45,6 +45,7 @@ import com.cloud.user.Account; import com.cloud.user.UserContext; import com.cloud.utils.DateUtil; import com.cloud.utils.component.ComponentLocator; +import com.cloud.utils.component.PluggableService; import com.cloud.utils.exception.CloudRuntimeException; /** @@ -71,6 +72,7 @@ public class ApiDispatcher { public void dispatchCreateCmd(BaseAsyncCreateCmd cmd, Map params) { setupParameters(cmd, params); + plugService(cmd); try { UserContext ctx = UserContext.current(); @@ -113,6 +115,7 @@ public class ApiDispatcher { public void dispatch(BaseCmd cmd, Map params) { setupParameters(cmd, params); + ApiDispatcher.plugService(cmd); try { UserContext ctx = UserContext.current(); ctx.setAccountId(cmd.getEntityOwnerId()); @@ -329,4 +332,44 @@ public class ApiDispatcher { cal.set(Calendar.SECOND, second); return cal.getTime(); } + + public static void plugService(BaseCmd cmd) { + + if(!ApiServer.isPluggableServiceCommand(cmd.getClass().getName())){ + return; + } + Class clazz = cmd.getClass(); + ComponentLocator locator = ComponentLocator.getLocator(ManagementServer.Name); + do { + Field[] fields = clazz.getDeclaredFields(); + for (Field field : fields) { + PlugService plugService = field.getAnnotation(PlugService.class); + if (plugService == null) { + continue; + } + Class fc = field.getType(); + Object instance = null; + if (PluggableService.class.isAssignableFrom(fc)) { + instance = locator.getPluggableService(fc); + } + + if (instance == null) { + throw new CloudRuntimeException("Unable to plug service " + fc.getSimpleName() + " in command " + clazz.getSimpleName()); + } + + try { + field.setAccessible(true); + field.set(cmd, instance); + } catch (IllegalArgumentException e) { + s_logger.error("IllegalArgumentException at plugService for command " + cmd.getCommandName() + ", field " + field.getName()); + throw new CloudRuntimeException("Internal error at plugService for command " + cmd.getCommandName() + " [Illegal argumet at field " + field.getName() + "]"); + } catch (IllegalAccessException e) { + s_logger.error("Error at plugService for command " + cmd.getCommandName() + ", field " + field.getName() + " is not accessible."); + throw new CloudRuntimeException("Internal error at plugService for command " + cmd.getCommandName() + " [field " + field.getName() + " is not accessible]"); + } + } + clazz = clazz.getSuperclass(); + } while (clazz != Object.class && clazz != null); + + } } diff --git a/server/src/com/cloud/api/ApiServer.java b/server/src/com/cloud/api/ApiServer.java index ea2e7990497..a0257e9c1af 100755 --- a/server/src/com/cloud/api/ApiServer.java +++ b/server/src/com/cloud/api/ApiServer.java @@ -107,6 +107,7 @@ import com.cloud.user.UserContext; import com.cloud.utils.Pair; import com.cloud.utils.PropertiesUtil; import com.cloud.utils.component.ComponentLocator; +import com.cloud.utils.component.PluggableService; import com.cloud.utils.concurrency.NamedThreadFactory; import com.cloud.utils.db.SearchCriteria; import com.cloud.utils.db.Transaction; @@ -138,6 +139,7 @@ public class ApiServer implements HttpRequestHandler { private static List s_adminCommands = null; private static List s_resourceDomainAdminCommands = null; private static List s_allCommands = null; + private static List s_pluggableServiceCommands = null; private static final DateFormat _dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ"); private static ExecutorService _executor = new ThreadPoolExecutor(10, 150, 60, TimeUnit.SECONDS, new LinkedBlockingQueue(), new NamedThreadFactory("ApiServer")); @@ -148,6 +150,7 @@ public class ApiServer implements HttpRequestHandler { s_adminCommands = new ArrayList(); s_resourceDomainAdminCommands = new ArrayList(); s_allCommands = new ArrayList(); + s_pluggableServiceCommands = new ArrayList(); } private ApiServer() { @@ -168,12 +171,32 @@ public class ApiServer implements HttpRequestHandler { public Properties get_apiCommands() { return _apiCommands; } + + public static boolean isPluggableServiceCommand(String cmdClassName){ + if(s_pluggableServiceCommands != null){ + if(s_pluggableServiceCommands.contains(cmdClassName)){ + return true; + } + } + return false; + } - public void init(String[] apiConfig) { - try { - BaseCmd.setComponents(new ApiResponseHelper()); - BaseListCmd.configure(); - _apiCommands = new Properties(); + private String[] getPluggableServicesApiConfigs(){ + List pluggableServicesApiConfigs = new ArrayList(); + + ComponentLocator locator = ComponentLocator.getLocator(ManagementServer.Name); + List services = locator.getAllPluggableServices(); + for(PluggableService service : services){ + pluggableServicesApiConfigs.add(service.getPropertiesFile()); + } + return pluggableServicesApiConfigs.toArray(new String[0]); + } + + private void processConfigFiles(String[] apiConfig, boolean pluggableServicesConfig){ + try{ + if(_apiCommands == null){ + _apiCommands = new Properties(); + } Properties preProcessedCommands = new Properties(); if (apiConfig != null) { for (String configFile : apiConfig) { @@ -184,6 +207,11 @@ public class ApiServer implements HttpRequestHandler { String preProcessedCommand = preProcessedCommands.getProperty((String) key); String[] commandParts = preProcessedCommand.split(";"); _apiCommands.put(key, commandParts[0]); + + if(pluggableServicesConfig){ + s_pluggableServiceCommands.add(commandParts[0]); + } + if (commandParts.length > 1) { try { short cmdPermissions = Short.parseShort(commandParts[1]); @@ -204,7 +232,7 @@ public class ApiServer implements HttpRequestHandler { } } } - + s_allCommands.addAll(s_adminCommands); s_allCommands.addAll(s_resourceDomainAdminCommands); s_allCommands.addAll(s_userCommands); @@ -215,6 +243,16 @@ public class ApiServer implements HttpRequestHandler { } catch (IOException ioex) { s_logger.error("Exception loading properties file", ioex); } + } + + public void init(String[] apiConfig) { + BaseCmd.setComponents(new ApiResponseHelper()); + BaseListCmd.configure(); + processConfigFiles(apiConfig, false); + + //get commands for all pluggable services + String[] pluggableServicesApiConfigs = getPluggableServicesApiConfigs(); + processConfigFiles(pluggableServicesApiConfigs, true); ComponentLocator locator = ComponentLocator.getLocator(ManagementServer.Name); _accountMgr = locator.getManager(AccountManager.class); @@ -400,6 +438,7 @@ public class ApiServer implements HttpRequestHandler { params.put("id", objectId.toString()); } else { ApiDispatcher.setupParameters(cmdObj, params); + ApiDispatcher.plugService(cmdObj); } BaseAsyncCmd asyncCmd = (BaseAsyncCmd) cmdObj; diff --git a/server/src/com/cloud/configuration/DefaultComponentLibrary.java b/server/src/com/cloud/configuration/DefaultComponentLibrary.java index 0c299e2b290..406dbf4e3e9 100755 --- a/server/src/com/cloud/configuration/DefaultComponentLibrary.java +++ b/server/src/com/cloud/configuration/DefaultComponentLibrary.java @@ -70,6 +70,7 @@ import com.cloud.keystore.KeystoreManagerImpl; import com.cloud.maint.UpgradeManagerImpl; import com.cloud.maint.dao.AgentUpgradeDaoImpl; import com.cloud.network.NetworkManagerImpl; +import com.cloud.network.VirtualNetworkApplianceService; import com.cloud.network.dao.FirewallRulesCidrsDaoImpl; import com.cloud.network.dao.FirewallRulesDaoImpl; import com.cloud.network.dao.IPAddressDaoImpl; @@ -153,6 +154,7 @@ import com.cloud.utils.component.ComponentLibrary; import com.cloud.utils.component.ComponentLibraryBase; import com.cloud.utils.component.ComponentLocator.ComponentInfo; import com.cloud.utils.component.Manager; +import com.cloud.utils.component.PluggableService; import com.cloud.utils.db.GenericDao; import com.cloud.vm.ClusteredVirtualMachineManagerImpl; import com.cloud.vm.ItWorkDaoImpl; @@ -363,4 +365,16 @@ public class DefaultComponentLibrary extends ComponentLibraryBase implements Com factories.put(EntityManager.class, EntityManagerImpl.class); return factories; } + + protected void populateServices() { + addService("VirtualRouterService", VirtualNetworkApplianceService.class, VirtualNetworkApplianceManagerImpl.class); + } + + @Override + public synchronized Map> getPluggableServices() { + if (_pluggableServices.size() == 0) { + populateServices(); + } + return _pluggableServices; + } } diff --git a/server/src/com/cloud/network/router/VirtualNetworkApplianceManagerImpl.java b/server/src/com/cloud/network/router/VirtualNetworkApplianceManagerImpl.java index 0d2011e5be7..96d0c720693 100755 --- a/server/src/com/cloud/network/router/VirtualNetworkApplianceManagerImpl.java +++ b/server/src/com/cloud/network/router/VirtualNetworkApplianceManagerImpl.java @@ -2742,4 +2742,10 @@ public class VirtualNetworkApplianceManagerImpl implements VirtualNetworkApplian public boolean processTimeout(long agentId, long seq) { return false; } + + @Override + public String getPropertiesFile() { + return "virtualrouter_commands.properties"; + } + } diff --git a/utils/src/com/cloud/utils/component/ComponentLibrary.java b/utils/src/com/cloud/utils/component/ComponentLibrary.java index 18aed723996..3f4d86efada 100755 --- a/utils/src/com/cloud/utils/component/ComponentLibrary.java +++ b/utils/src/com/cloud/utils/component/ComponentLibrary.java @@ -51,4 +51,9 @@ public interface ComponentLibrary { Map, Class> getFactories(); + /** + * @return all the services + * + */ + Map> getPluggableServices(); } diff --git a/utils/src/com/cloud/utils/component/ComponentLibraryBase.java b/utils/src/com/cloud/utils/component/ComponentLibraryBase.java index 45492b87fda..9358130ef48 100644 --- a/utils/src/com/cloud/utils/component/ComponentLibraryBase.java +++ b/utils/src/com/cloud/utils/component/ComponentLibraryBase.java @@ -45,6 +45,7 @@ public abstract class ComponentLibraryBase implements ComponentLibrary { protected Map> _managers = new LinkedHashMap>(); protected Map>> _adapters = new LinkedHashMap>>(); + protected Map> _pluggableServices = new LinkedHashMap>(); protected ComponentInfo addManager(String name, Class clazz, List> params, boolean singleton) { ComponentInfo info = new ComponentInfo(name, clazz, params, singleton); @@ -85,4 +86,15 @@ public abstract class ComponentLibraryBase implements ComponentLibrary { adapters.add(new Pair>(name, adapterClass)); return addAdapterChain(interphace, adapters).get(0); } -} + + + protected ComponentInfo addService(String name, Class serviceInterphace, Class clazz, List> params, boolean singleton) { + ComponentInfo info = new ComponentInfo(name, clazz, params, singleton); + _pluggableServices.put(serviceInterphace.getName(), info); + return info; + } + + protected ComponentInfo addService(String name, Class serviceInterphace, Class clazz) { + return addService(name, serviceInterphace, clazz, new ArrayList>(), true); + } + } diff --git a/utils/src/com/cloud/utils/component/ComponentLocator.java b/utils/src/com/cloud/utils/component/ComponentLocator.java index 489b2619bd3..008617b6ccc 100755 --- a/utils/src/com/cloud/utils/component/ComponentLocator.java +++ b/utils/src/com/cloud/utils/component/ComponentLocator.java @@ -64,7 +64,6 @@ import org.xml.sax.helpers.DefaultHandler; import com.cloud.utils.Pair; import com.cloud.utils.PropertiesUtil; -import com.cloud.utils.Ternary; import com.cloud.utils.db.DatabaseCallback; import com.cloud.utils.db.DatabaseCallbackFilter; import com.cloud.utils.db.GenericDao; @@ -100,6 +99,7 @@ public class ComponentLocator implements ComponentLocatorMBean { protected String _serverName; protected Object _component; protected HashMap, Class> _factories; + protected HashMap> _pluggableServicesMap; static { if (s_janitor == null) { @@ -134,6 +134,7 @@ public class ComponentLocator implements ComponentLocatorMBean { _checkerMap = new HashMap>(); _adapterMap = new HashMap>(); _factories = new HashMap, Class>(); + _pluggableServicesMap = new LinkedHashMap>(); File file = PropertiesUtil.findConfigFile(filename); if (file == null) { s_logger.info("Unable to find " + filename); @@ -157,6 +158,7 @@ public class ComponentLocator implements ComponentLocatorMBean { _daoMap.putAll(parentLocator._daoMap); _managerMap.putAll(parentLocator._managerMap); _factories.putAll(parentLocator._factories); + _pluggableServicesMap.putAll(parentLocator._pluggableServicesMap); } ComponentLibrary library = null; @@ -167,12 +169,14 @@ public class ComponentLocator implements ComponentLocatorMBean { _managerMap.putAll(library.getManagers()); adapters.putAll(library.getAdapters()); _factories.putAll(library.getFactories()); + _pluggableServicesMap.putAll(library.getPluggableServices()); } _daoMap.putAll(handler.daos); _managerMap.putAll(handler.managers); _checkerMap.putAll(handler.checkers); adapters.putAll(handler.adapters); + _pluggableServicesMap.putAll(handler.pluggableServices); return new Pair>>>(handler, adapters); } catch (ParserConfigurationException e) { @@ -215,6 +219,9 @@ public class ComponentLocator implements ComponentLocatorMBean { configureAdapters(); startManagers(); startAdapters(); + //TODO do we need to follow the instantiate -> inject -> configure -> start -> stop flow of singletons like managers/adapters? + //TODO do we need to expose pluggableServices to MBean (provide getNames?) + instantiatePluggableServices(); } catch (CloudRuntimeException e) { s_logger.error("Unable to load configuration for " + _serverName + " from " + filename, e); System.exit(1); @@ -634,6 +641,47 @@ public class ComponentLocator implements ComponentLocatorMBean { } } + protected void instantiatePluggableServices() { + Set>> entries = _pluggableServicesMap.entrySet(); + for (Map.Entry> entry : entries) { + ComponentInfo info = entry.getValue(); + if (info.instance == null) { + s_logger.info("Instantiating PluggableService: " + info.name); + info.instance = (PluggableService)createInstance(info.clazz, false, info.singleton); + } + } + } + + protected ComponentInfo getPluggableService(String name) { + ComponentInfo mgr = _pluggableServicesMap.get(name); + return mgr; + } + + public T getPluggableService(Class clazz) { + ComponentInfo info = getPluggableService(clazz.getName()); + if (info == null) { + return null; + } + if (info.instance == null) { + info.instance = (PluggableService)createInstance(info.clazz, false, info.singleton); + } + return (T)info.instance; + } + + public List getAllPluggableServices() { + List services = new ArrayList(); + Set>> entries = _pluggableServicesMap.entrySet(); + for (Map.Entry> entry : entries) { + ComponentInfo info = entry.getValue(); + if (info.instance == null) { + s_logger.info("Instantiating PluggableService: " + info.name); + info.instance = (PluggableService)createInstance(info.clazz, false, info.singleton); + } + services.add((T) info.instance); + } + return services; + } + public static T inject(Class clazz) { return (T)createInstance(clazz, true, false); } @@ -868,6 +916,7 @@ public class ComponentLocator implements ComponentLocatorMBean { public HashMap> managers; public HashMap> checkers; public LinkedHashMap>> daos; + public HashMap> pluggableServices; public String parent; public String library; @@ -886,6 +935,7 @@ public class ComponentLocator implements ComponentLocatorMBean { managers = new HashMap>(); checkers = new HashMap>(); daos = new LinkedHashMap>>(); + pluggableServices = new HashMap>(); value = null; parent = null; } @@ -992,6 +1042,17 @@ public class ComponentLocator implements ComponentLocatorMBean { checkers.put(info.name, info); s_logger.info("Adding system integrity checker: " + info.name); currentInfo = info; + } else if (qName.equals("pluggableservice")) { + ComponentInfo info = new ComponentInfo(); + fillInfo(atts, PluggableService.class, info); + s_logger.info("Adding PluggableService: " + info.name); + String key = getAttribute(atts, "key"); + if (key == null) { + throw new CloudRuntimeException("Missing key attribute for pluggableservice: "+info.name); + } + s_logger.info("Linking " + key + " to " + info.name); + pluggableServices.put(key, info); + currentInfo = info; } else { // ignore } @@ -1019,6 +1080,7 @@ public class ComponentLocator implements ComponentLocatorMBean { } else if (qName.equals("adapter")) { } else if (qName.equals("manager")) { } else if (qName.equals("dao")) { + } else if (qName.equals("pluggableservice")) { } else if (qName.equals("param")) { currentInfo.params.put(paramName, value.toString()); paramName = null; diff --git a/utils/src/com/cloud/utils/component/PluggableService.java b/utils/src/com/cloud/utils/component/PluggableService.java new file mode 100644 index 00000000000..8edee64c5ca --- /dev/null +++ b/utils/src/com/cloud/utils/component/PluggableService.java @@ -0,0 +1,31 @@ +/** + * Copyright (C) 2010 Cloud.com, Inc. All rights reserved. + * + * This software is licensed under the GNU General Public License v3 or later. + * + * It is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or any later version. + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + */ +package com.cloud.utils.component; + + +/** + * This interface defines methods for pluggable code within the Cloud Stack. + */ +public interface PluggableService { + + /** + * The config file name that lists API commands supported by this pluggable service + */ + String getPropertiesFile(); + +} diff --git a/utils/test/com/cloud/utils/component/MockComponentLocator.java b/utils/test/com/cloud/utils/component/MockComponentLocator.java index a74b3833bd2..33ff73cba8e 100755 --- a/utils/test/com/cloud/utils/component/MockComponentLocator.java +++ b/utils/test/com/cloud/utils/component/MockComponentLocator.java @@ -18,7 +18,6 @@ package com.cloud.utils.component; import java.io.Serializable; -import java.util.ArrayList; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.List; @@ -28,8 +27,6 @@ import net.sf.cglib.proxy.Callback; import net.sf.cglib.proxy.NoOp; import com.cloud.utils.Pair; -import com.cloud.utils.Ternary; -import com.cloud.utils.component.ComponentLocator.ComponentInfo; import com.cloud.utils.db.DatabaseCallback; import com.cloud.utils.db.DatabaseCallbackFilter; import com.cloud.utils.db.GenericDao; @@ -62,6 +59,10 @@ public class MockComponentLocator extends ComponentLocator { return _library.addAdapterChain(interphace, adapters); } + public ComponentInfo addService(String name, Class service) { + return _library.addService(name, service); + } + @Override protected Pair>>> parse2(String filename) { Pair>>> result = new Pair>>>(new XmlHandler("fake"), new HashMap>>()); @@ -110,5 +111,10 @@ public class MockComponentLocator extends ComponentLocator { public Map> getManagers() { return _managers; } + + @Override + public Map> getPluggableServices() { + return _pluggableServices; + } } } From 7433d5314aa897c06f935b1c0d5577eb2f0ad354 Mon Sep 17 00:00:00 2001 From: alena Date: Wed, 12 Oct 2011 16:35:56 -0700 Subject: [PATCH 006/159] 1) Refactored networkOfferings: * moved all services to the separate table, map them to the network_offering+provider. * added state/securityGroupEnabled properties for the networkOffering * added ability to list by state/securityGroupEnabled in listNetworkOfferings api command 2) New service: SourceNat --- api/src/com/cloud/api/ApiConstants.java | 10 + .../commands/CreateNetworkOfferingCmd.java | 86 +++++++- .../api/commands/ListNetworkOfferingsCmd.java | 15 ++ .../api/commands/RegisterTemplateCmd.java | 3 - .../api/response/NetworkOfferingResponse.java | 103 +++------- .../cloud/api/response/ServiceResponse.java | 12 +- api/src/com/cloud/network/Network.java | 27 ++- api/src/com/cloud/network/NetworkService.java | 2 + .../com/cloud/offering/NetworkOffering.java | 28 ++- client/tomcatconf/commands.properties.in | 2 +- client/tomcatconf/components.xml.in | 1 + server/src/com/cloud/api/ApiDBUtils.java | 4 + .../src/com/cloud/api/ApiResponseHelper.java | 15 +- .../api/commands/AddExternalFirewallCmd.java | 1 - .../baremetal/BareMetalVmManagerImpl.java | 1 + .../configuration/ConfigurationManager.java | 7 +- .../ConfigurationManagerImpl.java | 98 +++++++--- .../DefaultComponentLibrary.java | 2 + .../com/cloud/network/NetworkManagerImpl.java | 95 +++++---- .../network/element/BareMetalElement.java | 4 - .../network/element/VirtualRouterElement.java | 5 +- .../NetworkOfferingServiceMapVO.java | 92 +++++++++ .../cloud/offerings/NetworkOfferingVO.java | 185 ++++-------------- .../offerings/dao/NetworkOfferingDaoImpl.java | 5 - .../dao/NetworkOfferingServiceMapDao.java | 43 ++++ .../dao/NetworkOfferingServiceMapDaoImpl.java | 115 +++++++++++ .../cloud/server/ConfigurationServerImpl.java | 67 +++++-- setup/db/create-schema.sql | 22 ++- 28 files changed, 701 insertions(+), 349 deletions(-) create mode 100644 server/src/com/cloud/offerings/NetworkOfferingServiceMapVO.java create mode 100644 server/src/com/cloud/offerings/dao/NetworkOfferingServiceMapDao.java create mode 100644 server/src/com/cloud/offerings/dao/NetworkOfferingServiceMapDaoImpl.java diff --git a/api/src/com/cloud/api/ApiConstants.java b/api/src/com/cloud/api/ApiConstants.java index f95c3d889df..3df3ab46b91 100755 --- a/api/src/com/cloud/api/ApiConstants.java +++ b/api/src/com/cloud/api/ApiConstants.java @@ -267,5 +267,15 @@ public class ApiConstants { public static final String USER = "user"; public static final String ACTIVE_ONLY = "activeonly"; public static final String TOKEN = "token"; + public static final String DHCP_SERVICE = "dhcpservice"; + public static final String DNS_SERVICE = "dnsservice"; + public static final String SOURCE_NAT_SERVICE = "sourcenatservice"; + public static final String VPN_SERVICE = "vpnservice"; + public static final String USERDATA_SERVICE = "userdataservice"; + public static final String LB_SERVICE = "lbservice"; + public static final String FIREWALL_SERVICE = "firewallservice"; + public static final String GATEWAY_SERVICE = "gatewayservice"; + public static final String SERVICE_PROVIDER_LIST = "serviceproviderlist"; + public static final String PROVIDER = "provider"; } diff --git a/api/src/com/cloud/api/commands/CreateNetworkOfferingCmd.java b/api/src/com/cloud/api/commands/CreateNetworkOfferingCmd.java index 0d072a0b8e5..2b523a09c73 100644 --- a/api/src/com/cloud/api/commands/CreateNetworkOfferingCmd.java +++ b/api/src/com/cloud/api/commands/CreateNetworkOfferingCmd.java @@ -18,6 +18,8 @@ package com.cloud.api.commands; +import java.util.Map; + import org.apache.log4j.Logger; import com.cloud.api.ApiConstants; @@ -65,9 +67,36 @@ public class CreateNetworkOfferingCmd extends BaseCmd { @Parameter(name=ApiConstants.NETWORKRATE, type=CommandType.INTEGER, description="data transfer rate in megabits per second allowed.") private Integer networkRate; - - @Parameter(name=ApiConstants.REDUNDANT_ROUTER, type=CommandType.BOOLEAN, description="if network offering supports redundant router.") - private Boolean redundantRouter; + + @Parameter(name=ApiConstants.DHCP_SERVICE, type=CommandType.BOOLEAN, description="true is network offering supports dhcp service") + private Boolean dhcpService; + + @Parameter(name=ApiConstants.DNS_SERVICE, type=CommandType.BOOLEAN, description="true is network offering supports dns service") + private Boolean dnsService; + + @Parameter(name=ApiConstants.GATEWAY_SERVICE, type=CommandType.BOOLEAN, description="true is network offering supports gateway service") + private Boolean gatewayService; + + @Parameter(name=ApiConstants.FIREWALL_SERVICE, type=CommandType.BOOLEAN, description="true is network offering supports firewall service") + private Boolean firewallService; + + @Parameter(name=ApiConstants.LB_SERVICE, type=CommandType.BOOLEAN, description="true is network offering supports lb service") + private Boolean lbService; + + @Parameter(name=ApiConstants.USERDATA_SERVICE, type=CommandType.BOOLEAN, description="true is network offering supports user data service") + private Boolean userdataService; + + @Parameter(name=ApiConstants.SOURCE_NAT_SERVICE, type=CommandType.BOOLEAN, description="true is network offering supports source nat service") + private Boolean sourceNatService; + + @Parameter(name=ApiConstants.VPN_SERVICE, type=CommandType.BOOLEAN, description="true is network offering supports vpn service") + private Boolean vpnService; + + @Parameter(name = ApiConstants.SERVICE_PROVIDER_LIST, type = CommandType.MAP, description = "provider to service mapping. If not specified, the provider for the service will be mapped to the default provider on the physical network") + private Map serviceProviderList; + + @Parameter(name=ApiConstants.SECURITY_GROUP_EANBLED, type=CommandType.BOOLEAN, description="true is security group is enabled for the network offering") + private Boolean securityGroupEnabled; ///////////////////////////////////////////////////// /////////////////// Accessors /////////////////////// @@ -98,7 +127,6 @@ public class CreateNetworkOfferingCmd extends BaseCmd { } public String getAvailability() { - //Verify availability return availability == null ? Availability.Required.toString() : availability; } @@ -109,9 +137,53 @@ public class CreateNetworkOfferingCmd extends BaseCmd { public String getGuestIpType() { return guestIpType; } - - public Boolean getRedundantRouter() { - return redundantRouter == null ? false : redundantRouter; + + public static String getName() { + return _name; + } + + public Integer getMaxConnections() { + return maxConnections; + } + + public Boolean getDhcpService() { + return dhcpService; + } + + public Boolean getDnsService() { + return dnsService; + } + + public Boolean getGatewayService() { + return gatewayService; + } + + public Boolean getFirewallService() { + return firewallService; + } + + public Boolean getLbService() { + return lbService; + } + + public Boolean getUserdataService() { + return userdataService; + } + + public Boolean getSourceNatService() { + return sourceNatService; + } + + public Boolean getVpnService() { + return vpnService; + } + + public Map getServiceProviderList() { + return serviceProviderList; + } + + public Boolean getSecurityGroupEnabled() { + return securityGroupEnabled; } ///////////////////////////////////////////////////// diff --git a/api/src/com/cloud/api/commands/ListNetworkOfferingsCmd.java b/api/src/com/cloud/api/commands/ListNetworkOfferingsCmd.java index 078b1cd85e4..eb2ff70f329 100644 --- a/api/src/com/cloud/api/commands/ListNetworkOfferingsCmd.java +++ b/api/src/com/cloud/api/commands/ListNetworkOfferingsCmd.java @@ -27,6 +27,7 @@ import com.cloud.api.ApiConstants; import com.cloud.api.BaseListCmd; import com.cloud.api.Implementation; import com.cloud.api.Parameter; +import com.cloud.api.BaseCmd.CommandType; import com.cloud.api.response.ListResponse; import com.cloud.api.response.NetworkOfferingResponse; import com.cloud.offering.NetworkOffering; @@ -69,6 +70,12 @@ public class ListNetworkOfferingsCmd extends BaseListCmd { @Parameter(name=ApiConstants.ZONE_ID, type=CommandType.LONG, description="list netowrk offerings available for network creation in specific zone") private Long zoneId; + + @Parameter(name=ApiConstants.SECURITY_GROUP_EANBLED, type=CommandType.BOOLEAN, description="list network offerings that have security group feature enabled") + private Boolean securityGroupEnabled; + + @Parameter(name=ApiConstants.STATE, type=CommandType.STRING, description="list network offerings by state") + private String state; ///////////////////////////////////////////////////// /////////////////// Accessors /////////////////////// @@ -114,6 +121,14 @@ public class ListNetworkOfferingsCmd extends BaseListCmd { return zoneId; } + public Boolean getSecurityGroupEnabled() { + return securityGroupEnabled; + } + + public String getState() { + return state; + } + ///////////////////////////////////////////////////// /////////////// API Implementation/////////////////// ///////////////////////////////////////////////////// diff --git a/api/src/com/cloud/api/commands/RegisterTemplateCmd.java b/api/src/com/cloud/api/commands/RegisterTemplateCmd.java index b0b9073772d..98413d967b1 100755 --- a/api/src/com/cloud/api/commands/RegisterTemplateCmd.java +++ b/api/src/com/cloud/api/commands/RegisterTemplateCmd.java @@ -27,14 +27,11 @@ import com.cloud.api.BaseCmd; import com.cloud.api.Implementation; import com.cloud.api.Parameter; import com.cloud.api.ServerApiException; -import com.cloud.api.BaseCmd.CommandType; import com.cloud.api.response.ListResponse; import com.cloud.api.response.TemplateResponse; import com.cloud.async.AsyncJob; -import com.cloud.exception.InvalidParameterValueException; import com.cloud.exception.ResourceAllocationException; import com.cloud.template.VirtualMachineTemplate; -import com.cloud.user.Account; import com.cloud.user.UserContext; @Implementation(description="Registers an existing template into the Cloud.com cloud. ", responseObject=TemplateResponse.class) diff --git a/api/src/com/cloud/api/response/NetworkOfferingResponse.java b/api/src/com/cloud/api/response/NetworkOfferingResponse.java index fadce919991..2c5c41574f3 100644 --- a/api/src/com/cloud/api/response/NetworkOfferingResponse.java +++ b/api/src/com/cloud/api/response/NetworkOfferingResponse.java @@ -19,40 +19,44 @@ package com.cloud.api.response; import java.util.Date; +import java.util.List; + +import javax.persistence.Column; import com.cloud.api.ApiConstants; import com.cloud.serializer.Param; import com.google.gson.annotations.SerializedName; +@SuppressWarnings("unused") public class NetworkOfferingResponse extends BaseResponse{ - @SerializedName("id") @Param(description="the id of the network offering") + @SerializedName(ApiConstants.ID) @Param(description="the id of the network offering") private Long id; - @SerializedName("name") @Param(description="the name of the network offering") + @SerializedName(ApiConstants.NAME) @Param(description="the name of the network offering") private String name; - @SerializedName("displaytext") @Param(description="an alternate display text of the network offering.") + @SerializedName(ApiConstants.DISPLAY_TEXT) @Param(description="an alternate display text of the network offering.") private String displayText; - @SerializedName("tags") @Param(description="the tags for the network offering") + @SerializedName(ApiConstants.TAGS) @Param(description="the tags for the network offering") private String tags; - @SerializedName("created") @Param(description="the date this network offering was created") + @SerializedName(ApiConstants.CREATED) @Param(description="the date this network offering was created") private Date created; - @SerializedName("maxconnections") @Param(description="the max number of concurrent connection the network offering supports") + @SerializedName(ApiConstants.MAX_CONNECTIONS) @Param(description="the max number of concurrent connection the network offering supports") private Integer maxConnections; - @SerializedName("traffictype") @Param(description="the traffic type for the network offering, supported types are Public, Management, Control, Guest, Vlan or Storage.") + @SerializedName(ApiConstants.TRAFFIC_TYPE) @Param(description="the traffic type for the network offering, supported types are Public, Management, Control, Guest, Vlan or Storage.") private String trafficType; - @SerializedName("isdefault") @Param(description="true if network offering is default, false otherwise") + @SerializedName(ApiConstants.IS_DEFAULT) @Param(description="true if network offering is default, false otherwise") private Boolean isDefault; - @SerializedName("specifyvlan") @Param(description="true if network offering supports vlans, false otherwise") + @SerializedName(ApiConstants.SPECIFY_VLAN) @Param(description="true if network offering supports vlans, false otherwise") private Boolean specifyVlan; - @SerializedName("availability") @Param(description="availability of the network offering") + @SerializedName(ApiConstants.AVAILABILITY) @Param(description="availability of the network offering") private String availability; @SerializedName(ApiConstants.GUEST_IP_TYPE) @Param(description="guest ip type of the network offering") @@ -60,120 +64,77 @@ public class NetworkOfferingResponse extends BaseResponse{ @SerializedName(ApiConstants.NETWORKRATE) @Param(description="data transfer rate in megabits per second allowed.") private Integer networkRate; - - @SerializedName(ApiConstants.REDUNDANT_ROUTER) @Param(description="true if redundant router would be enabled, false otherwise") - private Boolean redundantRouter; - public Long getId() { - return id; - } - + @SerializedName(ApiConstants.SECURITY_GROUP_EANBLED) @Param(description="true if security group is enabled, false otherwise") + private Boolean isSecurityGroupEnabled; + + @SerializedName(ApiConstants.STATE) @Param(description="state of the network offering. Can be Disabled/Enabled/Inactive") + private String state; + + @SerializedName("service") @Param(description="the list of supported services", responseObject = ServiceResponse.class) + private List services; + public void setId(Long id) { this.id = id; } - public String getName() { - return name; - } - public void setName(String name) { this.name = name; } - public String getDisplayText() { - return displayText; - } - public void setDisplayText(String displayText) { this.displayText = displayText; } - - public String getTags() { - return tags; - } - + public void setTags(String tags) { this.tags = tags; } - public Date getCreated() { - return created; - } - public void setCreated(Date created) { this.created = created; } - public Integer getMaxconnections() { - return maxConnections; - } - public void setMaxconnections(Integer maxConnections) { this.maxConnections = maxConnections; } - public String getTrafficType() { - return trafficType; - } - public void setTrafficType(String trafficType) { this.trafficType = trafficType; } - public Boolean getIsDefault() { - return isDefault; - } - public void setIsDefault(Boolean isDefault) { this.isDefault = isDefault; } - public Integer getMaxConnections() { - return maxConnections; - } - public void setMaxConnections(Integer maxConnections) { this.maxConnections = maxConnections; } - public Boolean getSpecifyVlan() { - return specifyVlan; - } - public void setSpecifyVlan(Boolean specifyVlan) { this.specifyVlan = specifyVlan; } - public String getAvailability() { - return availability; - } - public void setAvailability(String availability) { this.availability = availability; } - public Integer getNetworkRate() { - return networkRate; - } - public void setNetworkRate(Integer networkRate) { this.networkRate = networkRate; } - public String getGuestIpType() { - return guestIpType; - } - public void setGuestIpType(String guestIpType) { this.guestIpType = guestIpType; } - - public Boolean getRedundantRouter() { - return redundantRouter; + + public void setIsSecurityGroupEnabled(Boolean isSecurityGroupEnabled) { + this.isSecurityGroupEnabled = isSecurityGroupEnabled; } - public void setRedundantRouter(Boolean redundantRouter) { - this.redundantRouter = redundantRouter; + public void setServices(List services) { + this.services = services; } + public void setState(String state) { + this.state = state; + } } diff --git a/api/src/com/cloud/api/response/ServiceResponse.java b/api/src/com/cloud/api/response/ServiceResponse.java index 2f75de3529b..e32fed76396 100644 --- a/api/src/com/cloud/api/response/ServiceResponse.java +++ b/api/src/com/cloud/api/response/ServiceResponse.java @@ -23,11 +23,15 @@ import com.cloud.api.ApiConstants; import com.cloud.serializer.Param; import com.google.gson.annotations.SerializedName; +@SuppressWarnings("unused") public class ServiceResponse extends BaseResponse { @SerializedName(ApiConstants.NAME) @Param(description="the service name") private String name; + @SerializedName(ApiConstants.PROVIDER) @Param(description="the service provider name") + private String provider; + @SerializedName("capability") @Param(description="the list of capabilities", responseObject = CapabilityResponse.class) private List capabilities; @@ -39,11 +43,11 @@ public class ServiceResponse extends BaseResponse { this.name = name; } - public List getCapabilities() { - return capabilities; - } - public void setCapabilities(List capabilities) { this.capabilities = capabilities; } + + public void setProvider(String provider) { + this.provider = provider; + } } \ No newline at end of file diff --git a/api/src/com/cloud/network/Network.java b/api/src/com/cloud/network/Network.java index 3495a3e5c23..d1603f88bb8 100644 --- a/api/src/com/cloud/network/Network.java +++ b/api/src/com/cloud/network/Network.java @@ -22,6 +22,7 @@ package com.cloud.network; import java.net.URI; +import java.util.ArrayList; import java.util.List; import java.util.Set; @@ -44,14 +45,16 @@ public interface Network extends ControlledEntity { } public static class Service { + private static List supportedServices = new ArrayList(); public static final Service Vpn = new Service("Vpn", Capability.SupportedVpnTypes); public static final Service Dhcp = new Service("Dhcp"); public static final Service Dns = new Service("Dns", Capability.AllowDnsSuffixModification); - public static final Service Gateway = new Service("Gateway", Capability.Redundancy); + public static final Service Gateway = new Service("Gateway"); public static final Service Firewall = new Service("Firewall", Capability.PortForwarding, Capability.StaticNat, Capability.SupportedProtocols, Capability.MultipleIps, Capability.SupportedSourceNatTypes, Capability.TrafficStatistics); public static final Service Lb = new Service("Lb", Capability.SupportedLBAlgorithms, Capability.SupportedProtocols, Capability.TrafficStatistics, Capability.LoadBalancingSupportedIps); public static final Service UserData = new Service("UserData"); + public static final Service SourceNat = new Service("SourceNat"); private String name; private Capability[] caps; @@ -59,6 +62,7 @@ public interface Network extends ControlledEntity { public Service(String name, Capability... caps) { this.name = name; this.caps = caps; + supportedServices.add(this); } public String getName() { @@ -83,9 +87,19 @@ public interface Network extends ControlledEntity { return success; } + + public static Service getService(String serviceName) { + for (Service service : supportedServices) { + if (service.getName().equalsIgnoreCase(serviceName)) { + return service; + } + } + return null; + } } public static class Provider { + private static List supportedProviders = new ArrayList(); public static final Provider VirtualRouter = new Provider("VirtualRouter"); public static final Provider DhcpServer = new Provider("DhcpServer"); @@ -102,11 +116,21 @@ public interface Network extends ControlledEntity { public Provider(String name) { this.name = name; + supportedProviders.add(this); } public String getName() { return name; } + + public static Provider getProvider(String providerName) { + for (Provider provider : supportedProviders) { + if (provider.getName().equalsIgnoreCase(providerName)) { + return provider; + } + } + return null; + } } public static class Capability { @@ -121,7 +145,6 @@ public interface Network extends ControlledEntity { public static final Capability TrafficStatistics = new Capability("TrafficStatistics"); public static final Capability LoadBalancingSupportedIps = new Capability("LoadBalancingSupportedIps"); public static final Capability AllowDnsSuffixModification = new Capability("AllowDnsSuffixModification"); - public static final Capability Redundancy = new Capability("Redundancy"); private String name; diff --git a/api/src/com/cloud/network/NetworkService.java b/api/src/com/cloud/network/NetworkService.java index 2d21f52af65..807efee15e0 100644 --- a/api/src/com/cloud/network/NetworkService.java +++ b/api/src/com/cloud/network/NetworkService.java @@ -85,4 +85,6 @@ public interface NetworkService { Integer getNetworkRate(long networkId, Long vmId); Network getSystemNetworkByZoneAndTrafficType(long zoneId, TrafficType trafficType); + + Map listNetworkOfferingServices(long networkOfferingId); } diff --git a/api/src/com/cloud/offering/NetworkOffering.java b/api/src/com/cloud/offering/NetworkOffering.java index 394e1d9ce37..2b0ea43ef95 100644 --- a/api/src/com/cloud/offering/NetworkOffering.java +++ b/api/src/com/cloud/offering/NetworkOffering.java @@ -32,6 +32,12 @@ public interface NetworkOffering { Unavailable; } + public enum State { + Disabled, + Enabled, + Inactive + } + public final static String SystemPublicNetwork = "System-Public-Network"; public final static String SystemControlNetwork = "System-Control-Network"; public final static String SystemManagementNetwork = "System-Management-Network"; @@ -40,7 +46,6 @@ public interface NetworkOffering { public final static String DefaultVirtualizedNetworkOffering = "DefaultVirtualizedNetworkOffering"; public final static String DefaultDirectNetworkOffering = "DefaultDirectNetworkOffering"; - public final static String DefaultDirectChooseVlanNetworkOffering = "DefaultDirectChooseVlanNetworkOffering"; long getId(); @@ -81,24 +86,15 @@ public interface NetworkOffering { Availability getAvailability(); - - boolean isDnsService(); - - boolean isGatewayService(); - - boolean isFirewallService(); - - boolean isLbService(); - - boolean isUserdataService(); - - boolean isVpnService(); - - boolean isDhcpService(); - boolean isSharedSourceNatService(); GuestIpType getGuestType(); String getUniqueName(); + + boolean isSecurityGroupEnabled(); + + void setState(State state); + + State getState(); } diff --git a/client/tomcatconf/commands.properties.in b/client/tomcatconf/commands.properties.in index 778c8ff71d2..c9b6485ebc2 100755 --- a/client/tomcatconf/commands.properties.in +++ b/client/tomcatconf/commands.properties.in @@ -249,7 +249,7 @@ listVpnUsers=com.cloud.api.commands.ListVpnUsersCmd;15 #### network offering commands createNetworkOffering=com.cloud.api.commands.CreateNetworkOfferingCmd;1 updateNetworkOffering=com.cloud.api.commands.UpdateNetworkOfferingCmd;1 -#### deleteNetworkOffering=com.cloud.api.commands.DeleteNetworkOfferingCmd;1 +deleteNetworkOffering=com.cloud.api.commands.DeleteNetworkOfferingCmd;1 listNetworkOfferings=com.cloud.api.commands.ListNetworkOfferingsCmd;15 #### network commands diff --git a/client/tomcatconf/components.xml.in b/client/tomcatconf/components.xml.in index b8a673d37d2..8999e9651e4 100755 --- a/client/tomcatconf/components.xml.in +++ b/client/tomcatconf/components.xml.in @@ -128,5 +128,6 @@ + diff --git a/server/src/com/cloud/api/ApiDBUtils.java b/server/src/com/cloud/api/ApiDBUtils.java index 047b7380f25..0ac2249cd91 100755 --- a/server/src/com/cloud/api/ApiDBUtils.java +++ b/server/src/com/cloud/api/ApiDBUtils.java @@ -648,4 +648,8 @@ public class ApiDBUtils { public static long getProjectOwnwerId(long projectId) { return _projectMgr.getProjectOwner(projectId).getId(); } + + public static Map listNetworkOfferingServices(long networkOfferingId) { + return _networkMgr.listNetworkOfferingServices(networkOfferingId); + } } diff --git a/server/src/com/cloud/api/ApiResponseHelper.java b/server/src/com/cloud/api/ApiResponseHelper.java index 24d0c8fc032..5cdf3dd3873 100755 --- a/server/src/com/cloud/api/ApiResponseHelper.java +++ b/server/src/com/cloud/api/ApiResponseHelper.java @@ -2110,12 +2110,23 @@ public class ApiResponseHelper implements ResponseGenerator { response.setSpecifyVlan(offering.getSpecifyVlan()); response.setAvailability(offering.getAvailability().toString()); response.setNetworkRate(ApiDBUtils.getNetworkRate(offering.getId())); - response.setRedundantRouter(false); + response.setIsSecurityGroupEnabled(offering.isSecurityGroupEnabled()); if (offering.getGuestType() != null) { response.setGuestIpType(offering.getGuestType().toString()); } - + + response.setState(offering.getState().name()); + + Map serviceProviderMap = ApiDBUtils.listNetworkOfferingServices(offering.getId()); + List serviceResponses = new ArrayList(); + for (String service : serviceProviderMap.keySet()) { + ServiceResponse svcRsp = new ServiceResponse(); + svcRsp.setName(service); + svcRsp.setProvider(serviceProviderMap.get(service)); + serviceResponses.add(svcRsp); + } + response.setServices(serviceResponses); response.setObjectName("networkoffering"); return response; } diff --git a/server/src/com/cloud/api/commands/AddExternalFirewallCmd.java b/server/src/com/cloud/api/commands/AddExternalFirewallCmd.java index c42a2f988b1..3ecfbce1b72 100644 --- a/server/src/com/cloud/api/commands/AddExternalFirewallCmd.java +++ b/server/src/com/cloud/api/commands/AddExternalFirewallCmd.java @@ -26,7 +26,6 @@ import com.cloud.api.BaseCmd; import com.cloud.api.Implementation; import com.cloud.api.Parameter; import com.cloud.api.ServerApiException; -import com.cloud.api.BaseCmd.CommandType; import com.cloud.exception.InvalidParameterValueException; import com.cloud.host.Host; import com.cloud.network.ExternalNetworkManager; diff --git a/server/src/com/cloud/baremetal/BareMetalVmManagerImpl.java b/server/src/com/cloud/baremetal/BareMetalVmManagerImpl.java index ef1e7684e31..78dfe31da9d 100755 --- a/server/src/com/cloud/baremetal/BareMetalVmManagerImpl.java +++ b/server/src/com/cloud/baremetal/BareMetalVmManagerImpl.java @@ -310,6 +310,7 @@ public class BareMetalVmManagerImpl extends UserVmManagerImpl implements BareMet throw new InvalidParameterValueException("Unable to find a default network to start a vm"); } + networkList = new ArrayList(); networkList.add(defaultNetwork.getId()); diff --git a/server/src/com/cloud/configuration/ConfigurationManager.java b/server/src/com/cloud/configuration/ConfigurationManager.java index c5a446bbcaa..d89c0cf89f9 100644 --- a/server/src/com/cloud/configuration/ConfigurationManager.java +++ b/server/src/com/cloud/configuration/ConfigurationManager.java @@ -18,6 +18,7 @@ package com.cloud.configuration; import java.util.List; +import java.util.Map; import com.cloud.dc.ClusterVO; import com.cloud.dc.DataCenter; @@ -30,6 +31,7 @@ import com.cloud.exception.ConcurrentOperationException; import com.cloud.exception.InsufficientCapacityException; import com.cloud.exception.InvalidParameterValueException; import com.cloud.exception.PermissionDeniedException; +import com.cloud.network.Network; import com.cloud.network.Network.GuestIpType; import com.cloud.network.Networks.TrafficType; import com.cloud.offering.DiskOffering; @@ -173,12 +175,15 @@ public interface ConfigurationManager extends ConfigurationService, Manager { * @param maxConnections * @param guestIpType TODO * @param networkRate TODO + * @param serviceProviderMap TODO + * @param isDefault TODO + * @param isSecurityGroupEnabled TODO * @param id * @param specifyVlan; * @return network offering object */ - NetworkOfferingVO createNetworkOffering(long userId, String name, String displayText, TrafficType trafficType, String tags, Integer maxConnections, boolean specifyVlan, Availability availability, GuestIpType guestIpType, boolean redundantRouter, Integer networkRate); + NetworkOfferingVO createNetworkOffering(long userId, String name, String displayText, TrafficType trafficType, String tags, Integer maxConnections, boolean specifyVlan, Availability availability, GuestIpType guestIpType, Integer networkRate, Map serviceProviderMap, boolean isDefault, boolean isSecurityGroupEnabled); Vlan createVlanAndPublicIpRange(Long userId, Long zoneId, Long podId, String startIP, String endIP, String vlanGateway, String vlanNetmask, boolean forVirtualNetwork, String vlanId, Account account, Long networkId) throws InsufficientCapacityException, ConcurrentOperationException, InvalidParameterValueException; diff --git a/server/src/com/cloud/configuration/ConfigurationManagerImpl.java b/server/src/com/cloud/configuration/ConfigurationManagerImpl.java index 6475d72d78a..26634a9a9f8 100755 --- a/server/src/com/cloud/configuration/ConfigurationManagerImpl.java +++ b/server/src/com/cloud/configuration/ConfigurationManagerImpl.java @@ -107,8 +107,10 @@ import com.cloud.offering.DiskOffering; import com.cloud.offering.NetworkOffering; import com.cloud.offering.NetworkOffering.Availability; import com.cloud.offering.ServiceOffering; +import com.cloud.offerings.NetworkOfferingServiceMapVO; import com.cloud.offerings.NetworkOfferingVO; import com.cloud.offerings.dao.NetworkOfferingDao; +import com.cloud.offerings.dao.NetworkOfferingServiceMapDao; import com.cloud.org.Grouping; import com.cloud.projects.Project; import com.cloud.projects.ProjectManager; @@ -206,6 +208,8 @@ public class ConfigurationManagerImpl implements ConfigurationManager, Configura ResourceLimitService _resourceLimitMgr; @Inject ProjectManager _projectMgr; + @Inject + NetworkOfferingServiceMapDao _ntwkOffServiceMapDao; // FIXME - why don't we have interface for DataCenterLinkLocalIpAddressDao? protected static final DataCenterLinkLocalIpAddressDaoImpl _LinkLocalIpAllocDao = ComponentLocator.inject(DataCenterLinkLocalIpAddressDaoImpl.class); @@ -2841,7 +2845,7 @@ public class ConfigurationManagerImpl implements ConfigurationManager, Configura Boolean specifyVlan = cmd.getSpecifyVlan(); String availabilityStr = cmd.getAvailability(); String guestIpTypeString = cmd.getGuestIpType(); - Boolean redundantRouter = cmd.getRedundantRouter(); + Boolean isSecurityGroupEnabled = cmd.getSecurityGroupEnabled(); Integer networkRate = cmd.getNetworkRate(); @@ -2884,39 +2888,77 @@ public class ConfigurationManagerImpl implements ConfigurationManager, Configura } Integer maxConnections = cmd.getMaxconnections(); - - return createNetworkOffering(userId, name, displayText, trafficType, tags, maxConnections, specifyVlan, availability, guestIpType, redundantRouter, networkRate); + + //configure service provider map + Map serviceProviderMap = new HashMap(); + //populate all services first + if (cmd.getDhcpService()) { + serviceProviderMap.put(Network.Service.Dhcp, null); + } else if (cmd.getDnsService()) { + serviceProviderMap.put(Network.Service.Dns, null); + } else if (cmd.getFirewallService()) { + serviceProviderMap.put(Network.Service.Firewall, null); + } else if (cmd.getGatewayService()) { + serviceProviderMap.put(Network.Service.Gateway, null); + } else if (cmd.getLbService()) { + serviceProviderMap.put(Network.Service.Lb, null); + } else if (cmd.getSourceNatService()) { + serviceProviderMap.put(Network.Service.SourceNat, null); + } else if (cmd.getUserdataService()) { + serviceProviderMap.put(Network.Service.UserData, null); + } else if (cmd.getVpnService()) { + serviceProviderMap.put(Network.Service.Vpn, null); + } + + //populate providers + Map svcPrv = (Map)cmd.getServiceProviderList(); + for (String serviceStr : svcPrv.keySet()) { + if (serviceProviderMap.containsKey(serviceStr)) { + Network.Service service = Network.Service.getService(serviceStr); + //check if provider is supported + Network.Provider provider; + String prvNameStr = svcPrv.get(serviceStr); + provider = Network.Provider.getProvider(prvNameStr); + if (provider == null) { + throw new InvalidParameterValueException("Invalid service provider: " + prvNameStr); + } + serviceProviderMap.put(service, provider); + } else { + throw new InvalidParameterValueException("Service " + serviceStr + " is not enabled for the network offering, can't add a provider to it"); + } + } + return createNetworkOffering(userId, name, displayText, trafficType, tags, maxConnections, specifyVlan, availability, guestIpType, networkRate, serviceProviderMap, false, isSecurityGroupEnabled); } - @Override + @Override @DB public NetworkOfferingVO createNetworkOffering(long userId, String name, String displayText, TrafficType trafficType, String tags, Integer maxConnections, boolean specifyVlan, - Availability availability, GuestIpType guestIpType, boolean redundantRouter, Integer networkRate) { + Availability availability, GuestIpType guestIpType, Integer networkRate, Map serviceProviderMap, boolean isDefault, boolean isSecurityGroupEnabled) { String multicastRateStr = _configDao.getValue("multicast.throttling.rate"); int multicastRate = ((multicastRateStr == null) ? 10 : Integer.parseInt(multicastRateStr)); tags = cleanupTags(tags); - boolean firewallService = false; - boolean lbService = false; - boolean vpnService = false; - boolean gatewayService = false; - if (trafficType == TrafficType.Guest) { - firewallService = true; - lbService = true; - vpnService = true; - gatewayService = true; + NetworkOfferingVO offering = new NetworkOfferingVO(name, displayText, trafficType, false, specifyVlan, networkRate, multicastRate, maxConnections, isDefault, availability,guestIpType, tags, isSecurityGroupEnabled); + + Transaction txn = Transaction.currentTxn(); + txn.start(); + //create network offering object + s_logger.debug("Adding network offering " + offering); + offering = _networkOfferingDao.persist(offering); + //populate services and providers + if (serviceProviderMap != null) { + for (Network.Service service : serviceProviderMap.keySet()) { + NetworkOfferingServiceMapVO offService = new NetworkOfferingServiceMapVO(offering.getId(), service, serviceProviderMap.get(service)); + _ntwkOffServiceMapDao.persist(offService); + s_logger.trace("Added service for the network offering: " + offService); + } } - NetworkOfferingVO offering = new NetworkOfferingVO(name, displayText, trafficType, false, specifyVlan, networkRate, multicastRate, maxConnections, false, availability, true, true, true, - gatewayService, firewallService, lbService, vpnService, guestIpType); - - if ((offering = _networkOfferingDao.persist(offering)) != null) { - UserContext.current().setEventDetails(" Id: "+offering.getId()+" Name: "+name); - return offering; - } else { - return null; - } + txn.commit(); + + UserContext.current().setEventDetails(" Id: "+offering.getId()+" Name: "+name); + return offering; } @Override @@ -2933,6 +2975,8 @@ public class ConfigurationManagerImpl implements ConfigurationManager, Configura Object isShared = cmd.getIsShared(); Object availability = cmd.getAvailability(); Object guestIpType = cmd.getGuestIpType(); + Object sgEnabled = cmd.getSecurityGroupEnabled(); + Object state = cmd.getState(); Long zoneId = cmd.getZoneId(); DataCenter zone = null; @@ -2984,6 +3028,14 @@ public class ConfigurationManagerImpl implements ConfigurationManager, Configura if (availability != null) { sc.addAnd("availability", SearchCriteria.Op.EQ, availability); } + + if (state != null) { + sc.addAnd("state", SearchCriteria.Op.EQ, state); + } + + if (sgEnabled != null) { + sc.addAnd("securityGroupEnabled", SearchCriteria.Op.EQ, sgEnabled); + } if (zone != null) { if (zone.getNetworkType() == NetworkType.Basic) { diff --git a/server/src/com/cloud/configuration/DefaultComponentLibrary.java b/server/src/com/cloud/configuration/DefaultComponentLibrary.java index 406dbf4e3e9..598071804f6 100755 --- a/server/src/com/cloud/configuration/DefaultComponentLibrary.java +++ b/server/src/com/cloud/configuration/DefaultComponentLibrary.java @@ -107,6 +107,7 @@ import com.cloud.network.security.dao.SecurityGroupWorkDaoImpl; import com.cloud.network.security.dao.VmRulesetLogDaoImpl; import com.cloud.network.vpn.RemoteAccessVpnManagerImpl; import com.cloud.offerings.dao.NetworkOfferingDaoImpl; +import com.cloud.offerings.dao.NetworkOfferingServiceMapDaoImpl; import com.cloud.projects.ProjectManagerImpl; import com.cloud.projects.dao.ProjectAccountDaoImpl; import com.cloud.projects.dao.ProjectDaoImpl; @@ -280,6 +281,7 @@ public class DefaultComponentLibrary extends ComponentLibraryBase implements Com addDao("ElasticLbVmMap", ElasticLbVmMapDaoImpl.class); addDao("ProjectsAccountDao", ProjectAccountDaoImpl.class); addDao("ProjectInvitationDao", ProjectInvitationDaoImpl.class); + addDao("NetworkOfferingServiceMapDao", NetworkOfferingServiceMapDaoImpl.class); info = addDao("HypervisorCapabilitiesDao",HypervisorCapabilitiesDaoImpl.class); info.addParameter("cache.size", "100"); info.addParameter("cache.time.to.live", "600"); diff --git a/server/src/com/cloud/network/NetworkManagerImpl.java b/server/src/com/cloud/network/NetworkManagerImpl.java index 7a56b5e5326..c7d905de1fc 100755 --- a/server/src/com/cloud/network/NetworkManagerImpl.java +++ b/server/src/com/cloud/network/NetworkManagerImpl.java @@ -79,7 +79,6 @@ import com.cloud.exception.AccountLimitException; import com.cloud.exception.ConcurrentOperationException; import com.cloud.exception.InsufficientAddressCapacityException; import com.cloud.exception.InsufficientCapacityException; -import com.cloud.exception.InsufficientNetworkCapacityException; import com.cloud.exception.InvalidParameterValueException; import com.cloud.exception.PermissionDeniedException; import com.cloud.exception.ResourceAllocationException; @@ -88,6 +87,7 @@ import com.cloud.exception.UnsupportedServiceException; import com.cloud.network.IpAddress.State; import com.cloud.network.Network.Capability; import com.cloud.network.Network.GuestIpType; +import com.cloud.network.Network.Provider; import com.cloud.network.Network.Service; import com.cloud.network.Networks.AddressFormat; import com.cloud.network.Networks.BroadcastDomainType; @@ -114,8 +114,10 @@ import com.cloud.network.rules.StaticNat; import com.cloud.network.vpn.RemoteAccessVpnService; import com.cloud.offering.NetworkOffering; import com.cloud.offering.NetworkOffering.Availability; +import com.cloud.offerings.NetworkOfferingServiceMapVO; import com.cloud.offerings.NetworkOfferingVO; import com.cloud.offerings.dao.NetworkOfferingDao; +import com.cloud.offerings.dao.NetworkOfferingServiceMapDao; import com.cloud.org.Grouping; import com.cloud.projects.Project; import com.cloud.projects.ProjectManager; @@ -234,6 +236,7 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag @Inject DomainRouterDao _routerDao; @Inject DomainManager _domainMgr; @Inject ProjectManager _projectMgr; + @Inject NetworkOfferingServiceMapDao _ntwkOfferingSrvcDao; private final HashMap _systemNetworks = new HashMap(5); @@ -752,7 +755,7 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag return success; } - @Override + @Override @DB public boolean configure(final String name, final Map params) throws ConfigurationException { _name = name; @@ -777,24 +780,47 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag NetworkOfferingVO storageNetworkOffering = new NetworkOfferingVO(NetworkOfferingVO.SystemStorageNetwork, TrafficType.Storage); storageNetworkOffering = _networkOfferingDao.persistDefaultNetworkOffering(storageNetworkOffering); _systemNetworks.put(NetworkOfferingVO.SystemStorageNetwork, storageNetworkOffering); - NetworkOfferingVO guestNetworkOffering = new NetworkOfferingVO(NetworkOffering.SystemGuestNetwork, "System Offering for System-Guest-Network", TrafficType.Guest, true, false, null, null, - null, true, Availability.Required, - // services - all true except for firewall/lb/vpn and gateway services - true, true, true, false, false, false, false, GuestIpType.Direct); - guestNetworkOffering = _networkOfferingDao.persistDefaultNetworkOffering(guestNetworkOffering); - _systemNetworks.put(NetworkOfferingVO.SystemGuestNetwork, guestNetworkOffering); + + //populate providers + Map defaultDirectNetworkOfferingProviders = new HashMap(); + defaultDirectNetworkOfferingProviders.put(Service.Dhcp, Provider.DhcpServer); + defaultDirectNetworkOfferingProviders.put(Service.Dns, Provider.DhcpServer); + defaultDirectNetworkOfferingProviders.put(Service.UserData, Provider.DhcpServer); + + Map defaultVirtualNetworkOfferingProviders = new HashMap(); + defaultVirtualNetworkOfferingProviders.put(Service.Dhcp, Provider.VirtualRouter); + defaultVirtualNetworkOfferingProviders.put(Service.Dns, Provider.VirtualRouter); + defaultVirtualNetworkOfferingProviders.put(Service.UserData, Provider.VirtualRouter); + defaultVirtualNetworkOfferingProviders.put(Service.Firewall, Provider.VirtualRouter); + defaultVirtualNetworkOfferingProviders.put(Service.Gateway, Provider.VirtualRouter); + defaultVirtualNetworkOfferingProviders.put(Service.Lb, Provider.VirtualRouter); + defaultVirtualNetworkOfferingProviders.put(Service.SourceNat, Provider.VirtualRouter); + defaultVirtualNetworkOfferingProviders.put(Service.Vpn, Provider.VirtualRouter); + + Transaction txn = Transaction.currentTxn(); + txn.start(); + //there is only 1 diff between offering #1 and #3 - securityGroup is enabled for the first, and disabled for the third + //check that offering already exists + NetworkOfferingVO offering = null; + if (_networkOfferingDao.findByUniqueName(NetworkOffering.SystemGuestNetwork) == null) { + offering = _configMgr.createNetworkOffering(Account.ACCOUNT_ID_SYSTEM, NetworkOffering.SystemGuestNetwork, "System Offering for System-Guest-Network", TrafficType.Guest, null, null, false, Availability.Optional, GuestIpType.Direct, null, defaultDirectNetworkOfferingProviders, true, true); + offering.setState(NetworkOffering.State.Enabled); + _networkOfferingDao.update(offering.getId(), offering); + } + + if (_networkOfferingDao.findByUniqueName(NetworkOffering.DefaultVirtualizedNetworkOffering) == null) { + offering = _configMgr.createNetworkOffering(Account.ACCOUNT_ID_SYSTEM,NetworkOffering.DefaultVirtualizedNetworkOffering, "Virtual Vlan", TrafficType.Guest, null, null, false, Availability.Required, GuestIpType.Virtual, null, defaultVirtualNetworkOfferingProviders, true, false); + offering.setState(NetworkOffering.State.Enabled); + _networkOfferingDao.update(offering.getId(), offering); + } - NetworkOfferingVO defaultGuestNetworkOffering = new NetworkOfferingVO(NetworkOffering.DefaultVirtualizedNetworkOffering, "Virtual Vlan", TrafficType.Guest, false, false, null, null, null, - true, Availability.Required, - // services - true, true, true, true, true, true, true, GuestIpType.Virtual); - - defaultGuestNetworkOffering = _networkOfferingDao.persistDefaultNetworkOffering(defaultGuestNetworkOffering); - NetworkOfferingVO defaultGuestDirectNetworkOffering = new NetworkOfferingVO(NetworkOffering.DefaultDirectNetworkOffering, "Direct", TrafficType.Guest, false, true, null, null, null, true, - Availability.Optional, - // services - all true except for firewall/lb/vpn and gateway services - true, true, true, false, false, false, false, GuestIpType.Direct); - defaultGuestDirectNetworkOffering = _networkOfferingDao.persistDefaultNetworkOffering(defaultGuestDirectNetworkOffering); + if (_networkOfferingDao.findByUniqueName(NetworkOffering.DefaultDirectNetworkOffering) == null) { + offering = _configMgr.createNetworkOffering(Account.ACCOUNT_ID_SYSTEM, NetworkOffering.DefaultDirectNetworkOffering, "Direct", TrafficType.Guest, null, null, true, Availability.Optional, GuestIpType.Direct, null, defaultDirectNetworkOfferingProviders, true, false); + offering.setState(NetworkOffering.State.Enabled); + _networkOfferingDao.update(offering.getId(), offering); + } + + txn.commit(); AccountsUsingNetworkSearch = _accountDao.createSearchBuilder(); SearchBuilder networkAccountSearch = _networksDao.createSearchBuilderForAccount(); @@ -2850,24 +2876,7 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag @Override public boolean isServiceSupported(long networkOfferingId, Network.Service service) { - NetworkOffering offering = _configMgr.getNetworkOffering(networkOfferingId); - if (service == Service.Lb) { - return offering.isLbService(); - } else if (service == Service.Dhcp) { - return offering.isDhcpService(); - } else if (service == Service.Dns) { - return offering.isDnsService(); - } else if (service == Service.Firewall) { - return offering.isFirewallService(); - } else if (service == Service.UserData) { - return offering.isUserdataService(); - } else if (service == Service.Vpn) { - return offering.isVpnService(); - } else if (service == Service.Gateway) { - return offering.isGatewayService(); - } - - return false; + return (_ntwkOfferingSrvcDao.isServiceSupported(networkOfferingId, service)); } private boolean cleanupIpResources(long ipId, long userId, Account caller) { @@ -3306,4 +3315,16 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag return podVlanMaps.getPodId(); } } + + @Override + public Map listNetworkOfferingServices(long networkOfferingId) { + Map serviceProviderMap = new HashMap(); + List map = _ntwkOfferingSrvcDao.getServices(networkOfferingId); + + for (NetworkOfferingServiceMapVO instance : map) { + serviceProviderMap.put(instance.getService(), instance.getProvider()); + } + + return serviceProviderMap; + } } diff --git a/server/src/com/cloud/network/element/BareMetalElement.java b/server/src/com/cloud/network/element/BareMetalElement.java index 9fc1d60e7a1..37fa43b2d3e 100644 --- a/server/src/com/cloud/network/element/BareMetalElement.java +++ b/server/src/com/cloud/network/element/BareMetalElement.java @@ -19,7 +19,6 @@ package com.cloud.network.element; -import java.util.List; import java.util.Map; import javax.ejb.Local; @@ -37,9 +36,6 @@ import com.cloud.network.Network; import com.cloud.network.Network.Capability; import com.cloud.network.Network.Provider; import com.cloud.network.Network.Service; -import com.cloud.network.PublicIpAddress; -import com.cloud.network.rules.FirewallRule; -import com.cloud.network.rules.StaticNat; import com.cloud.offering.NetworkOffering; import com.cloud.utils.component.AdapterBase; import com.cloud.utils.component.Inject; diff --git a/server/src/com/cloud/network/element/VirtualRouterElement.java b/server/src/com/cloud/network/element/VirtualRouterElement.java index 7c3fef2b358..38b7cd19501 100644 --- a/server/src/com/cloud/network/element/VirtualRouterElement.java +++ b/server/src/com/cloud/network/element/VirtualRouterElement.java @@ -314,10 +314,7 @@ public class VirtualRouterElement extends DhcpElement implements SourceNATServic capabilities.put(Service.UserData, null); capabilities.put(Service.Dhcp, null); - - Map gatewayCapabilities = new HashMap(); - gatewayCapabilities.put(Capability.Redundancy, "true"); - capabilities.put(Service.Gateway, gatewayCapabilities); + capabilities.put(Service.Gateway, null); return capabilities; } diff --git a/server/src/com/cloud/offerings/NetworkOfferingServiceMapVO.java b/server/src/com/cloud/offerings/NetworkOfferingServiceMapVO.java new file mode 100644 index 00000000000..13b32fa0a6b --- /dev/null +++ b/server/src/com/cloud/offerings/NetworkOfferingServiceMapVO.java @@ -0,0 +1,92 @@ +/** + * Copyright (C) 2010 Cloud.com, Inc. All rights reserved. + * + * This software is licensed under the GNU General Public License v3 or later. + * + * It is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or any later version. + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + */ +package com.cloud.offerings; + +import java.util.Date; + +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; +import javax.persistence.Table; + +import com.cloud.network.Network.Provider; +import com.cloud.network.Network.Service; +import com.cloud.utils.db.GenericDao; + +@Entity +@Table(name="ntwk_offering_service_map") +public class NetworkOfferingServiceMapVO { + + @Id + @GeneratedValue(strategy=GenerationType.IDENTITY) + @Column(name="id") + long id; + + @Column(name="network_offering_id") + long networkOfferingId; + + @Column(name="service") + String service; + + @Column(name="provider") + String provider; + + @Column(name=GenericDao.CREATED_COLUMN) + Date created; + + public long getId() { + return id; + } + + public long getNetworkOfferingId() { + return networkOfferingId; + } + + public String getService() { + return service; + } + + public String getProvider() { + return provider; + } + + public Date getCreated() { + return created; + } + + public NetworkOfferingServiceMapVO() { + } + + public NetworkOfferingServiceMapVO(long networkOfferingId, Service service, Provider provider) { + this.networkOfferingId = networkOfferingId; + this.service = service.getName(); + this.provider = provider.getName(); + } + + public String toString() { + StringBuilder buf = new StringBuilder("[Network Offering Service["); + return buf.append(networkOfferingId).append("-").append(service).append("-").append(provider).append("]").toString(); + } +} + + + + + diff --git a/server/src/com/cloud/offerings/NetworkOfferingVO.java b/server/src/com/cloud/offerings/NetworkOfferingVO.java index dacef41abb0..fab3211db65 100644 --- a/server/src/com/cloud/offerings/NetworkOfferingVO.java +++ b/server/src/com/cloud/offerings/NetworkOfferingVO.java @@ -29,6 +29,7 @@ import javax.persistence.Id; import javax.persistence.Table; import com.cloud.network.Network.GuestIpType; +import com.cloud.network.Network.State; import com.cloud.network.Networks.TrafficType; import com.cloud.offering.NetworkOffering; import com.cloud.utils.db.GenericDao; @@ -70,51 +71,34 @@ public class NetworkOfferingVO implements NetworkOffering { @Column(name="system_only") boolean systemOnly; - @Column(name="service_offering_id") - Long serviceOfferingId; - @Column(name="tags", length=4096) String tags; @Column(name="default") boolean isDefault; + @Column(name="availability") + @Enumerated(value=EnumType.STRING) + Availability availability; + + @Column(name="guest_type") + GuestIpType guestType; + + @Column(name="state") + @Enumerated(value=EnumType.STRING) + State state = State.Disabled; + @Column(name=GenericDao.REMOVED_COLUMN) Date removed; @Column(name=GenericDao.CREATED_COLUMN) Date created; - @Column(name="availability") - @Enumerated(value=EnumType.STRING) - Availability availability; - - @Column(name="dns_service") - boolean dnsService; - - @Column(name="gateway_service") - boolean gatewayService; - - @Column(name="firewall_service") - boolean firewallService; - - @Column(name="lb_service") - boolean lbService; - - @Column(name="userdata_service") - boolean userdataService; - - @Column(name="vpn_service") - boolean vpnService; - - @Column(name="dhcp_service") - boolean dhcpService; - @Column(name="shared_source_nat_service") boolean sharedSourceNatService; - @Column(name="guest_type") - GuestIpType guestType; + @Column(name="is_security_group_enabled") + boolean securityGroupEnabled; @Override public String getDisplayText() { @@ -168,13 +152,6 @@ public class NetworkOfferingVO implements NetworkOffering { return tags; } - public void setTags(String tags) { - this.tags = tags; - } - - public NetworkOfferingVO() { - } - public void setName(String name) { this.name = name; } @@ -190,31 +167,6 @@ public class NetworkOfferingVO implements NetworkOffering { public void setMulticastRateMbps(Integer multicastRateMbps) { this.multicastRateMbps = multicastRateMbps; } - - public void setConcurrentConnections(Integer concurrentConnections) { - this.concurrentConnections = concurrentConnections; - } - - public void setTrafficType(TrafficType trafficType) { - this.trafficType = trafficType; - } - - public void setSystemOnly(boolean systemOnly) { - this.systemOnly = systemOnly; - } - - - public void setRemoved(Date removed) { - this.removed = removed; - } - - public Long getServiceOfferingId() { - return serviceOfferingId; - } - - public void setServiceOfferingId(long serviceOfferingId) { - this.serviceOfferingId = serviceOfferingId; - } @Override public boolean isDefault() { @@ -225,10 +177,6 @@ public class NetworkOfferingVO implements NetworkOffering { public boolean getSpecifyVlan() { return specifyVlan; } - - public void setCreated(Date created) { - this.created = created; - } @Override public Availability getAvailability() { @@ -239,97 +187,37 @@ public class NetworkOfferingVO implements NetworkOffering { this.availability = availability; } - @Override - public boolean isDnsService() { - return dnsService; - } - - public void setDnsService(boolean dnsService) { - this.dnsService = dnsService; - } - - @Override - public boolean isGatewayService() { - return gatewayService; - } - - public void setGatewayService(boolean gatewayService) { - this.gatewayService = gatewayService; - } - - @Override - public boolean isFirewallService() { - return firewallService; - } - - public void setFirewallService(boolean firewallService) { - this.firewallService = firewallService; - } - - @Override - public boolean isLbService() { - return lbService; - } - - public void setLbService(boolean lbService) { - this.lbService = lbService; - } - - @Override - public boolean isUserdataService() { - return userdataService; - } - - public void setUserdataService(boolean userdataService) { - this.userdataService = userdataService; - } - - @Override - public boolean isVpnService() { - return vpnService; - } - - public void setVpnService(boolean vpnService) { - this.vpnService = vpnService; - } - - @Override - public boolean isDhcpService() { - return dhcpService; - } - - public void setDhcpService(boolean dhcpService) { - this.dhcpService = dhcpService; - } - @Override public boolean isSharedSourceNatService() { return sharedSourceNatService; } - public void setSharedSourceNatService(boolean sharedSourceNatService) { - this.sharedSourceNatService = sharedSourceNatService; - } - @Override public GuestIpType getGuestType() { return guestType; } - - public void setGuestType(GuestIpType guestType) { - this.guestType = guestType; - } @Override public String getUniqueName() { return uniqueName; } - public void setUniqueName(String uniqueName) { - this.uniqueName = uniqueName; + @Override + public boolean isSecurityGroupEnabled() { + return securityGroupEnabled; + } + + @Override + public void setState(State state) { + this.state = state; + } + + @Override + public State getState() { + return state; } - public NetworkOfferingVO(String name, String displayText, TrafficType trafficType, boolean systemOnly, boolean specifyVlan, Integer rateMbps, Integer multicastRateMbps, Integer concurrentConnections, boolean isDefault, Availability availability, boolean dhcpService, boolean dnsService, boolean userDataService, boolean gatewayService, boolean firewallService, boolean lbService, boolean vpnService, GuestIpType guestIpType) { + public NetworkOfferingVO(String name, String displayText, TrafficType trafficType, boolean systemOnly, boolean specifyVlan, Integer rateMbps, Integer multicastRateMbps, Integer concurrentConnections, boolean isDefault, Availability availability, GuestIpType guestIpType, String tags, boolean isSecurityGroupEnabled) { this.name = name; this.displayText = displayText; this.rateMbps = rateMbps; @@ -340,15 +228,13 @@ public class NetworkOfferingVO implements NetworkOffering { this.specifyVlan = specifyVlan; this.isDefault = isDefault; this.availability = availability; - this.dnsService = dnsService; - this.dhcpService = dhcpService; - this.userdataService = userDataService; - this.gatewayService = gatewayService; - this.firewallService = firewallService; - this.lbService = lbService; - this.vpnService = vpnService; - this.guestType = guestIpType; this.uniqueName = name; + this.tags = tags; + this.guestType = guestIpType; + this.securityGroupEnabled = isSecurityGroupEnabled; + } + + public NetworkOfferingVO() { } /** @@ -357,7 +243,8 @@ public class NetworkOfferingVO implements NetworkOffering { * @param trafficType */ public NetworkOfferingVO(String name, TrafficType trafficType) { - this(name, "System Offering for " + name, trafficType, true, false, 0, 0, null, true, Availability.Required, false, false, false, false, false, false, false, null); + this(name, "System Offering for " + name, trafficType, true, false, 0, 0, null, true, Availability.Required, null, null, false); + this.state = State.Enabled; } @Override diff --git a/server/src/com/cloud/offerings/dao/NetworkOfferingDaoImpl.java b/server/src/com/cloud/offerings/dao/NetworkOfferingDaoImpl.java index a36e6d1b4d9..33d24135058 100644 --- a/server/src/com/cloud/offerings/dao/NetworkOfferingDaoImpl.java +++ b/server/src/com/cloud/offerings/dao/NetworkOfferingDaoImpl.java @@ -27,8 +27,6 @@ import java.util.List; import javax.ejb.Local; import javax.persistence.EntityExistsException; -import org.apache.log4j.Logger; - import com.cloud.network.Network.GuestIpType; import com.cloud.network.Networks.TrafficType; import com.cloud.offering.NetworkOffering.Availability; @@ -40,9 +38,6 @@ import com.cloud.utils.db.SearchCriteria; @Local(value=NetworkOfferingDao.class) @DB(txn=false) public class NetworkOfferingDaoImpl extends GenericDaoBase implements NetworkOfferingDao { - - private final static Logger s_logger = Logger.getLogger(NetworkOfferingDaoImpl.class); - final SearchBuilder NameSearch; final SearchBuilder SystemOfferingSearch; final SearchBuilder AvailabilitySearch; diff --git a/server/src/com/cloud/offerings/dao/NetworkOfferingServiceMapDao.java b/server/src/com/cloud/offerings/dao/NetworkOfferingServiceMapDao.java new file mode 100644 index 00000000000..f835f8b2d16 --- /dev/null +++ b/server/src/com/cloud/offerings/dao/NetworkOfferingServiceMapDao.java @@ -0,0 +1,43 @@ +/** + * Copyright (C) 2011 Citrix Systems, Inc. All rights reserved + * + * This software is licensed under the GNU General Public License v3 or later. + * + * It is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or any later version. + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + */ +package com.cloud.offerings.dao; + +import java.util.List; + +import com.cloud.network.Network.Provider; +import com.cloud.network.Network.Service; +import com.cloud.offerings.NetworkOfferingServiceMapVO; +import com.cloud.utils.db.GenericDao; + +/** + * NetworkOfferingServiceDao deals with searches and operations done on the + * ntwk_offering_service_map table. + * + */ +public interface NetworkOfferingServiceMapDao extends GenericDao { + boolean isServiceSupported(long networkOfferingId, Service service); + boolean isProviderSupported(long networkOfferingId, Service service, Provider provider); + List getServicesForProvider(long networkOfferingId, Provider provider); + List getProvidersForService(long networkOfferingid, Service service); + List getServices(long networkOfferingId); +} + + + + + diff --git a/server/src/com/cloud/offerings/dao/NetworkOfferingServiceMapDaoImpl.java b/server/src/com/cloud/offerings/dao/NetworkOfferingServiceMapDaoImpl.java new file mode 100644 index 00000000000..d990b53e0fc --- /dev/null +++ b/server/src/com/cloud/offerings/dao/NetworkOfferingServiceMapDaoImpl.java @@ -0,0 +1,115 @@ +/** + * Copyright (C) 2010 Cloud.com, Inc. All rights reserved. + * + * This software is licensed under the GNU General Public License v3 or later. + * + * It is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or any later version. + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + */ + +/** + * + */ +package com.cloud.offerings.dao; + + +import java.util.ArrayList; +import java.util.List; + +import javax.ejb.Local; + +import com.cloud.exception.UnsupportedServiceException; +import com.cloud.network.Network.Provider; +import com.cloud.network.Network.Service; +import com.cloud.offerings.NetworkOfferingServiceMapVO; +import com.cloud.utils.db.DB; +import com.cloud.utils.db.GenericDaoBase; +import com.cloud.utils.db.SearchBuilder; +import com.cloud.utils.db.SearchCriteria; + +@Local(value=NetworkOfferingServiceMapDao.class) @DB(txn=false) +public class NetworkOfferingServiceMapDaoImpl extends GenericDaoBase implements NetworkOfferingServiceMapDao { + final SearchBuilder AllFieldsSearch; + + protected NetworkOfferingServiceMapDaoImpl() { + super(); + AllFieldsSearch = createSearchBuilder(); + AllFieldsSearch.and("networkOfferingId", AllFieldsSearch.entity().getNetworkOfferingId(), SearchCriteria.Op.EQ); + AllFieldsSearch.and("service", AllFieldsSearch.entity().getService(), SearchCriteria.Op.EQ); + AllFieldsSearch.and("provider", AllFieldsSearch.entity().getProvider(), SearchCriteria.Op.EQ); + AllFieldsSearch.done(); + } + + @Override + public boolean isServiceSupported(long networkOfferingId, Service service) { + SearchCriteria sc = AllFieldsSearch.create(); + sc.setParameters("networkOfferingId", networkOfferingId); + sc.setParameters("service", service.getName()); + if (findOneBy(sc) != null) { + return true; + } else { + return false; + } + } + + @Override + public boolean isProviderSupported(long networkOfferingId, Service service, Provider provider) { + SearchCriteria sc = AllFieldsSearch.create(); + sc.setParameters("networkOfferingId", networkOfferingId); + sc.setParameters("service", service.getName()); + sc.setParameters("provider", provider.getName()); + if (findOneBy(sc) != null) { + return true; + } else { + return false; + } + } + + @Override + public List getServicesForProvider(long networkOfferingId, Provider provider) { + List services = new ArrayList(); + SearchCriteria sc = AllFieldsSearch.create(); + sc.setParameters("networkOfferingId", networkOfferingId); + sc.setParameters("provider", provider.getName()); + List map = listBy(sc); + for (NetworkOfferingServiceMapVO instance : map) { + services.add(instance.getService()); + } + + return services; + } + + @Override + public List getProvidersForService(long networkOfferingId, Service service) { + List providers = new ArrayList(); + SearchCriteria sc = AllFieldsSearch.create(); + sc.setParameters("networkOfferingId", networkOfferingId); + sc.setParameters("service", service.getName()); + List map = listBy(sc); + if (map.isEmpty()) { + throw new UnsupportedServiceException("Service " + service + " is not supported by the network offering id=" + networkOfferingId); + } + + for (NetworkOfferingServiceMapVO instance : map) { + providers.add(instance.getProvider()); + } + + return providers; + } + + @Override + public List getServices(long networkOfferingId) { + SearchCriteria sc = AllFieldsSearch.create(); + sc.setParameters("networkOfferingId", networkOfferingId); + return listBy(sc); + } +} diff --git a/server/src/com/cloud/server/ConfigurationServerImpl.java b/server/src/com/cloud/server/ConfigurationServerImpl.java index a7aaaea3fec..649eba8b4fa 100644 --- a/server/src/com/cloud/server/ConfigurationServerImpl.java +++ b/server/src/com/cloud/server/ConfigurationServerImpl.java @@ -36,6 +36,7 @@ import java.sql.SQLException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; +import java.util.Map; import java.util.Properties; import java.util.UUID; import java.util.regex.Pattern; @@ -65,7 +66,10 @@ import com.cloud.domain.DomainVO; import com.cloud.domain.dao.DomainDao; import com.cloud.exception.InternalErrorException; import com.cloud.exception.InvalidParameterValueException; +import com.cloud.network.Network; import com.cloud.network.Network.GuestIpType; +import com.cloud.network.Network.Provider; +import com.cloud.network.Network.Service; import com.cloud.network.Network.State; import com.cloud.network.NetworkVO; import com.cloud.network.Networks.BroadcastDomainType; @@ -78,8 +82,10 @@ import com.cloud.network.guru.PodBasedNetworkGuru; import com.cloud.network.guru.PublicNetworkGuru; import com.cloud.offering.NetworkOffering; import com.cloud.offering.NetworkOffering.Availability; +import com.cloud.offerings.NetworkOfferingServiceMapVO; import com.cloud.offerings.NetworkOfferingVO; import com.cloud.offerings.dao.NetworkOfferingDao; +import com.cloud.offerings.dao.NetworkOfferingServiceMapDao; import com.cloud.service.ServiceOfferingVO; import com.cloud.service.dao.ServiceOfferingDao; import com.cloud.storage.DiskOfferingVO; @@ -114,6 +120,7 @@ public class ConfigurationServerImpl implements ConfigurationServer { private final DomainDao _domainDao; private final AccountDao _accountDao; private final ResourceCountDao _resourceCountDao; + private final NetworkOfferingServiceMapDao _offeringServiceMapDao; public ConfigurationServerImpl() { @@ -130,6 +137,7 @@ public class ConfigurationServerImpl implements ConfigurationServer { _domainDao = locator.getDao(DomainDao.class); _accountDao = locator.getDao(AccountDao.class); _resourceCountDao = locator.getDao(ResourceCountDao.class); + _offeringServiceMapDao = locator.getDao(NetworkOfferingServiceMapDao.class); } @@ -822,35 +830,72 @@ public class ConfigurationServerImpl implements ConfigurationServer { controlNetworkOffering = _networkOfferingDao.persistDefaultNetworkOffering(controlNetworkOffering); NetworkOfferingVO storageNetworkOffering = new NetworkOfferingVO(NetworkOfferingVO.SystemStorageNetwork, TrafficType.Storage); storageNetworkOffering = _networkOfferingDao.persistDefaultNetworkOffering(storageNetworkOffering); + + //populate providers + Map defaultDirectNetworkOfferingProviders = new HashMap(); + defaultDirectNetworkOfferingProviders.put(Service.Dhcp, Provider.DhcpServer); + defaultDirectNetworkOfferingProviders.put(Service.Dns, Provider.DhcpServer); + defaultDirectNetworkOfferingProviders.put(Service.UserData, Provider.DhcpServer); + + Map defaultVirtualNetworkOfferingProviders = new HashMap(); + defaultVirtualNetworkOfferingProviders.put(Service.Dhcp, Provider.VirtualRouter); + defaultVirtualNetworkOfferingProviders.put(Service.Dns, Provider.VirtualRouter); + defaultVirtualNetworkOfferingProviders.put(Service.UserData, Provider.VirtualRouter); + defaultVirtualNetworkOfferingProviders.put(Service.Firewall, Provider.VirtualRouter); + defaultVirtualNetworkOfferingProviders.put(Service.Gateway, Provider.VirtualRouter); + defaultVirtualNetworkOfferingProviders.put(Service.Lb, Provider.VirtualRouter); + defaultVirtualNetworkOfferingProviders.put(Service.SourceNat, Provider.VirtualRouter); + defaultVirtualNetworkOfferingProviders.put(Service.Vpn, Provider.VirtualRouter); + NetworkOfferingVO guestNetworkOffering = new NetworkOfferingVO( NetworkOffering.SystemGuestNetwork, "System-Guest-Network", TrafficType.Guest, - true, false, null, null, null, true, - Availability.Required, - true, true, true, //services - all true except for lb/vpn and gateway - false, true, false, false, GuestIpType.Direct); + false, false, null, null, null, true, + Availability.Optional, GuestIpType.Direct, null, true); + + guestNetworkOffering.setState(NetworkOffering.State.Enabled); guestNetworkOffering = _networkOfferingDao.persistDefaultNetworkOffering(guestNetworkOffering); + for (Service service : defaultDirectNetworkOfferingProviders.keySet()) { + NetworkOfferingServiceMapVO offService = new NetworkOfferingServiceMapVO(guestNetworkOffering.getId(), service, defaultDirectNetworkOfferingProviders.get(service)); + _offeringServiceMapDao.persist(offService); + s_logger.trace("Added service for the network offering: " + offService); + } + NetworkOfferingVO defaultGuestNetworkOffering = new NetworkOfferingVO( NetworkOffering.DefaultVirtualizedNetworkOffering, "Virtual Vlan", TrafficType.Guest, false, false, null, null, null, true, - Availability.Required, - true, true, true, //services - true, true, true, true, GuestIpType.Virtual); + Availability.Required, GuestIpType.Virtual, null, false); + + defaultGuestNetworkOffering.setState(NetworkOffering.State.Enabled); defaultGuestNetworkOffering = _networkOfferingDao.persistDefaultNetworkOffering(defaultGuestNetworkOffering); + + + for (Service service : defaultVirtualNetworkOfferingProviders.keySet()) { + NetworkOfferingServiceMapVO offService = new NetworkOfferingServiceMapVO(defaultGuestNetworkOffering.getId(), service, defaultVirtualNetworkOfferingProviders.get(service)); + _offeringServiceMapDao.persist(offService); + s_logger.trace("Added service for the network offering: " + offService); + } + NetworkOfferingVO defaultGuestDirectNetworkOffering = new NetworkOfferingVO( NetworkOffering.DefaultDirectNetworkOffering, "Direct", TrafficType.Guest, false, true, null, null, null, true, - Availability.Optional, - true, true, true, //services - all true except for firewall/lb/vpn and gateway - false, false, false, false, GuestIpType.Direct); - defaultGuestNetworkOffering = _networkOfferingDao.persistDefaultNetworkOffering(defaultGuestDirectNetworkOffering); + Availability.Optional, GuestIpType.Direct, null, false); + + defaultGuestDirectNetworkOffering.setState(NetworkOffering.State.Enabled); + defaultGuestDirectNetworkOffering = _networkOfferingDao.persistDefaultNetworkOffering(defaultGuestDirectNetworkOffering); + + for (Service service : defaultDirectNetworkOfferingProviders.keySet()) { + NetworkOfferingServiceMapVO offService = new NetworkOfferingServiceMapVO(defaultGuestDirectNetworkOffering.getId(), service, defaultDirectNetworkOfferingProviders.get(service)); + _offeringServiceMapDao.persist(offService); + s_logger.trace("Added service for the network offering: " + offService); + } } private void createDefaultNetworks() { diff --git a/setup/db/create-schema.sql b/setup/db/create-schema.sql index 9214a322b35..98dbcb495b5 100755 --- a/setup/db/create-schema.sql +++ b/setup/db/create-schema.sql @@ -256,20 +256,14 @@ CREATE TABLE `cloud`.`network_offerings` ( `tags` varchar(4096) COMMENT 'tags supported by this offering', `system_only` int(1) unsigned NOT NULL DEFAULT 0 COMMENT 'Is this network offering for system use only', `specify_vlan` int(1) unsigned NOT NULL DEFAULT 0 COMMENT 'Should the user specify vlan', - `service_offering_id` bigint unsigned UNIQUE COMMENT 'service offering id that this network offering is tied to', `created` datetime NOT NULL COMMENT 'time the entry was created', `removed` datetime DEFAULT NULL COMMENT 'time the entry was removed', `default` int(1) unsigned NOT NULL DEFAULT 0 COMMENT '1 if network offering is default', `availability` varchar(255) NOT NULL COMMENT 'availability of the network', - `dns_service` int(1) unsigned NOT NULL DEFAULT 0 COMMENT 'true if network offering provides dns service', - `gateway_service` int(1) unsigned NOT NULL DEFAULT 0 COMMENT 'true if network offering provides gateway service', - `firewall_service` int(1) unsigned NOT NULL DEFAULT 0 COMMENT 'true if network offering provides firewall service', - `lb_service` int(1) unsigned NOT NULL DEFAULT 0 COMMENT 'true if network offering provides lb service', - `userdata_service` int(1) unsigned NOT NULL DEFAULT 0 COMMENT 'true if network offering provides user data service', - `vpn_service` int(1) unsigned NOT NULL DEFAULT 0 COMMENT 'true if network offering provides vpn service', - `dhcp_service` int(1) unsigned NOT NULL DEFAULT 0 COMMENT 'true if network offering provides dhcp service', `shared_source_nat_service` int(1) unsigned NOT NULL DEFAULT 0 COMMENT 'true if the network offering provides the shared source nat service', `guest_type` char(32) COMMENT 'guest ip type of network offering', + `is_security_group_enabled` tinyint NOT NULL DEFAULT 0 COMMENT '1: enabled, 0: not', + `state` char(32) COMMENT 'state of the network offering; has Disabled value by default', PRIMARY KEY (`id`), INDEX `i_network_offerings__system_only`(`system_only`), INDEX `i_network_offerings__removed`(`removed`) @@ -1727,4 +1721,16 @@ CREATE TABLE `cloud`.`elastic_lb_vm_map` ( ) ENGINE=InnoDB DEFAULT CHARSET=utf8; +CREATE TABLE `ntwk_offering_service_map` ( + `id` bigint unsigned NOT NULL auto_increment, + `network_offering_id` bigint unsigned NOT NULL COMMENT 'network_offering_id', + `service` varchar(255) NOT NULL COMMENT 'service', + `provider` varchar(255) COMMENT 'service provider', + `created` datetime COMMENT 'date created', + PRIMARY KEY (`id`), + CONSTRAINT `fk_ntwk_offering_service_map__network_offering_id` FOREIGN KEY(`network_offering_id`) REFERENCES `network_offerings`(`id`) ON DELETE CASCADE, + UNIQUE (`network_offering_id`, `service`, `provider`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8; + + SET foreign_key_checks = 1; From 2d228dfcbb006440fd4ac332a9166d29020cf133 Mon Sep 17 00:00:00 2001 From: alena Date: Wed, 12 Oct 2011 17:14:51 -0700 Subject: [PATCH 007/159] Default service provider to VirtualRouter (should make this parameter configurable in the future) --- .../commands/CreateNetworkOfferingCmd.java | 41 +++++++---- api/src/com/cloud/network/Network.java | 1 + .../ConfigurationManagerImpl.java | 71 ++++++++++++------- .../offerings/dao/NetworkOfferingDaoImpl.java | 7 ++ 4 files changed, 81 insertions(+), 39 deletions(-) diff --git a/api/src/com/cloud/api/commands/CreateNetworkOfferingCmd.java b/api/src/com/cloud/api/commands/CreateNetworkOfferingCmd.java index 2b523a09c73..b4487f374cf 100644 --- a/api/src/com/cloud/api/commands/CreateNetworkOfferingCmd.java +++ b/api/src/com/cloud/api/commands/CreateNetworkOfferingCmd.java @@ -18,6 +18,9 @@ package com.cloud.api.commands; +import java.util.Collection; +import java.util.HashMap; +import java.util.Iterator; import java.util.Map; import org.apache.log4j.Logger; @@ -28,6 +31,7 @@ import com.cloud.api.Implementation; import com.cloud.api.Parameter; import com.cloud.api.ServerApiException; import com.cloud.api.response.NetworkOfferingResponse; +import com.cloud.exception.InvalidParameterValueException; import com.cloud.offering.NetworkOffering; import com.cloud.offering.NetworkOffering.Availability; import com.cloud.user.Account; @@ -127,7 +131,7 @@ public class CreateNetworkOfferingCmd extends BaseCmd { } public String getAvailability() { - return availability == null ? Availability.Required.toString() : availability; + return availability == null ? Availability.Optional.toString() : availability; } public Integer getNetworkRate() { @@ -147,43 +151,56 @@ public class CreateNetworkOfferingCmd extends BaseCmd { } public Boolean getDhcpService() { - return dhcpService; + return dhcpService == null ? false : dhcpService; } public Boolean getDnsService() { - return dnsService; + return dnsService == null ? false : dnsService; } public Boolean getGatewayService() { - return gatewayService; + return gatewayService == null ? false : gatewayService; } public Boolean getFirewallService() { - return firewallService; + return firewallService == null ? false : firewallService; } public Boolean getLbService() { - return lbService; + return lbService == null ? false : lbService; } public Boolean getUserdataService() { - return userdataService; + return userdataService == null ? false : userdataService; } public Boolean getSourceNatService() { - return sourceNatService; + return sourceNatService == null ? false : sourceNatService; } public Boolean getVpnService() { - return vpnService; + return vpnService == null ? false : vpnService; } - public Map getServiceProviderList() { - return serviceProviderList; + public Map getServiceProviderList() { + Map serviceProviderMap = null; + if (serviceProviderList != null && !serviceProviderList.isEmpty()) { + serviceProviderMap = new HashMap(); + Collection servicesCollection = serviceProviderList.values(); + Iterator iter = servicesCollection.iterator(); + while (iter.hasNext()) { + HashMap services = (HashMap) iter.next(); + String service = (String)services.get("service"); + String provider = (String) services.get("provider"); + serviceProviderMap.put(service, provider); + } + } + + return serviceProviderMap; } public Boolean getSecurityGroupEnabled() { - return securityGroupEnabled; + return securityGroupEnabled == null ? false : securityGroupEnabled; } ///////////////////////////////////////////////////// diff --git a/api/src/com/cloud/network/Network.java b/api/src/com/cloud/network/Network.java index d1603f88bb8..653229728c8 100644 --- a/api/src/com/cloud/network/Network.java +++ b/api/src/com/cloud/network/Network.java @@ -109,6 +109,7 @@ public interface Network extends ControlledEntity { public static final Provider ExternalDhcpServer = new Provider("ExternalDhcpServer"); public static final Provider ExternalGateWay = new Provider("ExternalGateWay"); public static final Provider ElasticLoadBalancerVm = new Provider("ElasticLoadBalancerVm"); + public static final Provider defaultProvider = VirtualRouter; public static final Provider None = new Provider("None"); diff --git a/server/src/com/cloud/configuration/ConfigurationManagerImpl.java b/server/src/com/cloud/configuration/ConfigurationManagerImpl.java index 26634a9a9f8..f24e4c61b04 100755 --- a/server/src/com/cloud/configuration/ConfigurationManagerImpl.java +++ b/server/src/com/cloud/configuration/ConfigurationManagerImpl.java @@ -2893,40 +2893,57 @@ public class ConfigurationManagerImpl implements ConfigurationManager, Configura Map serviceProviderMap = new HashMap(); //populate all services first if (cmd.getDhcpService()) { - serviceProviderMap.put(Network.Service.Dhcp, null); - } else if (cmd.getDnsService()) { - serviceProviderMap.put(Network.Service.Dns, null); - } else if (cmd.getFirewallService()) { - serviceProviderMap.put(Network.Service.Firewall, null); - } else if (cmd.getGatewayService()) { - serviceProviderMap.put(Network.Service.Gateway, null); - } else if (cmd.getLbService()) { - serviceProviderMap.put(Network.Service.Lb, null); - } else if (cmd.getSourceNatService()) { - serviceProviderMap.put(Network.Service.SourceNat, null); - } else if (cmd.getUserdataService()) { - serviceProviderMap.put(Network.Service.UserData, null); - } else if (cmd.getVpnService()) { - serviceProviderMap.put(Network.Service.Vpn, null); + serviceProviderMap.put(Network.Service.Dhcp, Network.Provider.defaultProvider); + } + + if (cmd.getDnsService()) { + serviceProviderMap.put(Network.Service.Dns, Network.Provider.defaultProvider); + } + + if (cmd.getFirewallService()) { + serviceProviderMap.put(Network.Service.Firewall, Network.Provider.defaultProvider); + } + + if (cmd.getGatewayService()) { + serviceProviderMap.put(Network.Service.Gateway, Network.Provider.defaultProvider); + } + + if (cmd.getLbService()) { + serviceProviderMap.put(Network.Service.Lb, Network.Provider.defaultProvider); + } + + if (cmd.getSourceNatService()) { + serviceProviderMap.put(Network.Service.SourceNat, Network.Provider.defaultProvider); + } + + if (cmd.getUserdataService()) { + serviceProviderMap.put(Network.Service.UserData, Network.Provider.defaultProvider); + } + + if (cmd.getVpnService()) { + serviceProviderMap.put(Network.Service.Vpn, Network.Provider.defaultProvider); } //populate providers Map svcPrv = (Map)cmd.getServiceProviderList(); - for (String serviceStr : svcPrv.keySet()) { - if (serviceProviderMap.containsKey(serviceStr)) { + if (svcPrv != null) { + for (String serviceStr : svcPrv.keySet()) { Network.Service service = Network.Service.getService(serviceStr); - //check if provider is supported - Network.Provider provider; - String prvNameStr = svcPrv.get(serviceStr); - provider = Network.Provider.getProvider(prvNameStr); - if (provider == null) { - throw new InvalidParameterValueException("Invalid service provider: " + prvNameStr); - } - serviceProviderMap.put(service, provider); - } else { - throw new InvalidParameterValueException("Service " + serviceStr + " is not enabled for the network offering, can't add a provider to it"); + if (serviceProviderMap.containsKey(service)) { + //check if provider is supported + Network.Provider provider; + String prvNameStr = svcPrv.get(serviceStr); + provider = Network.Provider.getProvider(prvNameStr); + if (provider == null) { + throw new InvalidParameterValueException("Invalid service provider: " + prvNameStr); + } + serviceProviderMap.put(service, provider); + } else { + throw new InvalidParameterValueException("Service " + serviceStr + " is not enabled for the network offering, can't add a provider to it"); + } } } + return createNetworkOffering(userId, name, displayText, trafficType, tags, maxConnections, specifyVlan, availability, guestIpType, networkRate, serviceProviderMap, false, isSecurityGroupEnabled); } diff --git a/server/src/com/cloud/offerings/dao/NetworkOfferingDaoImpl.java b/server/src/com/cloud/offerings/dao/NetworkOfferingDaoImpl.java index 33d24135058..fe190f70ab5 100644 --- a/server/src/com/cloud/offerings/dao/NetworkOfferingDaoImpl.java +++ b/server/src/com/cloud/offerings/dao/NetworkOfferingDaoImpl.java @@ -124,4 +124,11 @@ public class NetworkOfferingDaoImpl extends GenericDaoBase Date: Thu, 13 Oct 2011 17:33:41 -0700 Subject: [PATCH 008/159] Added type (Shared/Isolated) to the networkOffering/networks --- .../cloud/api/commands/CreateNetworkCmd.java | 9 - .../commands/CreateNetworkOfferingCmd.java | 25 ++- .../api/commands/ListNetworkOfferingsCmd.java | 1 - .../cloud/api/commands/ListNetworksCmd.java | 1 - .../commands/UpdateNetworkOfferingCmd.java | 107 ++++++++- .../api/response/NetworkOfferingResponse.java | 7 + .../cloud/api/response/NetworkResponse.java | 1 + .../cloud/api/response/ProviderResponse.java | 35 +++ .../cloud/api/response/ServiceResponse.java | 6 +- api/src/com/cloud/network/Network.java | 9 +- api/src/com/cloud/network/NetworkProfile.java | 20 +- api/src/com/cloud/network/NetworkService.java | 3 +- .../com/cloud/offering/NetworkOffering.java | 7 + server/src/com/cloud/api/ApiDBUtils.java | 3 +- .../src/com/cloud/api/ApiResponseHelper.java | 18 +- .../baremetal/BareMetalVmManagerImpl.java | 2 +- .../configuration/ConfigurationManager.java | 6 +- .../ConfigurationManagerImpl.java | 205 ++++++++++++++---- .../consoleproxy/ConsoleProxyManagerImpl.java | 4 +- .../src/com/cloud/network/NetworkManager.java | 13 +- .../com/cloud/network/NetworkManagerImpl.java | 133 +++++++----- server/src/com/cloud/network/NetworkVO.java | 28 ++- .../src/com/cloud/network/dao/NetworkDao.java | 2 + .../com/cloud/network/dao/NetworkDaoImpl.java | 28 ++- .../element/CloudZonesNetworkElement.java | 7 +- .../cloud/network/element/DhcpElement.java | 26 +-- .../element/ElasticLoadBalancerElement.java | 8 +- .../network/element/ExternalDhcpElement.java | 14 +- .../element/ExternalFirewallElement.java | 4 +- .../F5ExternalLoadBalancerElement.java | 4 +- .../NetscalerExternalLoadBalancerElement.java | 4 +- .../RedundantVirtualRouterElement.java | 16 +- .../network/element/VirtualRouterElement.java | 28 ++- .../cloud/network/guru/DirectNetworkGuru.java | 6 +- .../cloud/network/guru/PublicNetworkGuru.java | 3 +- .../lb/ElasticLoadBalancerManagerImpl.java | 8 +- .../VirtualNetworkApplianceManagerImpl.java | 14 +- .../cloud/offerings/NetworkOfferingVO.java | 21 +- .../dao/NetworkOfferingServiceMapDao.java | 1 + .../dao/NetworkOfferingServiceMapDaoImpl.java | 7 + .../cloud/server/ConfigurationServerImpl.java | 8 +- .../SecondaryStorageManagerImpl.java | 4 +- .../src/com/cloud/vm/UserVmManagerImpl.java | 20 +- .../cloud/network/MockNetworkManagerImpl.java | 31 +-- .../com/cloud/network/dao/NetworkDaoTest.java | 2 +- setup/db/create-schema.sql | 2 + 46 files changed, 634 insertions(+), 277 deletions(-) create mode 100644 api/src/com/cloud/api/response/ProviderResponse.java diff --git a/api/src/com/cloud/api/commands/CreateNetworkCmd.java b/api/src/com/cloud/api/commands/CreateNetworkCmd.java index b07a24cb838..d3df5426941 100644 --- a/api/src/com/cloud/api/commands/CreateNetworkCmd.java +++ b/api/src/com/cloud/api/commands/CreateNetworkCmd.java @@ -27,12 +27,10 @@ import com.cloud.api.BaseCmd; import com.cloud.api.Implementation; import com.cloud.api.Parameter; import com.cloud.api.ServerApiException; -import com.cloud.api.BaseCmd.CommandType; import com.cloud.api.response.NetworkResponse; import com.cloud.exception.ConcurrentOperationException; import com.cloud.exception.InsufficientCapacityException; import com.cloud.network.Network; -import com.cloud.user.Account; import com.cloud.user.UserContext; @Implementation(description="Creates a network", responseObject=NetworkResponse.class) @@ -81,9 +79,6 @@ public class CreateNetworkCmd extends BaseCmd { @Parameter(name=ApiConstants.DOMAIN_ID, type=CommandType.LONG, description="domain ID of the account owning a network") private Long domainId; - @Parameter(name=ApiConstants.IS_SHARED, type=CommandType.BOOLEAN, description="true is network is shared across accounts in the Zone") - private Boolean isShared; - @Parameter(name=ApiConstants.IS_DEFAULT, type=CommandType.BOOLEAN, description="true if network is default, false otherwise") private Boolean isDefault; @@ -144,10 +139,6 @@ public class CreateNetworkCmd extends BaseCmd { return displayText; } - public boolean getIsShared() { - return isShared == null ? false : isShared; - } - public Boolean isDefault() { return isDefault; } diff --git a/api/src/com/cloud/api/commands/CreateNetworkOfferingCmd.java b/api/src/com/cloud/api/commands/CreateNetworkOfferingCmd.java index b4487f374cf..4636b9d0c27 100644 --- a/api/src/com/cloud/api/commands/CreateNetworkOfferingCmd.java +++ b/api/src/com/cloud/api/commands/CreateNetworkOfferingCmd.java @@ -18,9 +18,11 @@ package com.cloud.api.commands; +import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.Iterator; +import java.util.List; import java.util.Map; import org.apache.log4j.Logger; @@ -31,7 +33,6 @@ import com.cloud.api.Implementation; import com.cloud.api.Parameter; import com.cloud.api.ServerApiException; import com.cloud.api.response.NetworkOfferingResponse; -import com.cloud.exception.InvalidParameterValueException; import com.cloud.offering.NetworkOffering; import com.cloud.offering.NetworkOffering.Availability; import com.cloud.user.Account; @@ -101,6 +102,9 @@ public class CreateNetworkOfferingCmd extends BaseCmd { @Parameter(name=ApiConstants.SECURITY_GROUP_EANBLED, type=CommandType.BOOLEAN, description="true is security group is enabled for the network offering") private Boolean securityGroupEnabled; + + @Parameter(name=ApiConstants.TYPE, type=CommandType.STRING, required=true, description="type of the network offering: Shared or Isolated") + private String type; ///////////////////////////////////////////////////// /////////////////// Accessors /////////////////////// @@ -182,17 +186,28 @@ public class CreateNetworkOfferingCmd extends BaseCmd { return vpnService == null ? false : vpnService; } - public Map getServiceProviderList() { - Map serviceProviderMap = null; + public String getType() { + return type; + } + + public Map> getServiceProviders() { + Map> serviceProviderMap = null; if (serviceProviderList != null && !serviceProviderList.isEmpty()) { - serviceProviderMap = new HashMap(); + serviceProviderMap = new HashMap>(); Collection servicesCollection = serviceProviderList.values(); Iterator iter = servicesCollection.iterator(); while (iter.hasNext()) { HashMap services = (HashMap) iter.next(); String service = (String)services.get("service"); String provider = (String) services.get("provider"); - serviceProviderMap.put(service, provider); + List providerList = null; + if (serviceProviderMap.containsKey(service)) { + providerList = serviceProviderMap.get(service); + } else { + providerList = new ArrayList(); + } + providerList.add(provider); + serviceProviderMap.put(service, providerList); } } diff --git a/api/src/com/cloud/api/commands/ListNetworkOfferingsCmd.java b/api/src/com/cloud/api/commands/ListNetworkOfferingsCmd.java index eb2ff70f329..e9cedb86d82 100644 --- a/api/src/com/cloud/api/commands/ListNetworkOfferingsCmd.java +++ b/api/src/com/cloud/api/commands/ListNetworkOfferingsCmd.java @@ -27,7 +27,6 @@ import com.cloud.api.ApiConstants; import com.cloud.api.BaseListCmd; import com.cloud.api.Implementation; import com.cloud.api.Parameter; -import com.cloud.api.BaseCmd.CommandType; import com.cloud.api.response.ListResponse; import com.cloud.api.response.NetworkOfferingResponse; import com.cloud.offering.NetworkOffering; diff --git a/api/src/com/cloud/api/commands/ListNetworksCmd.java b/api/src/com/cloud/api/commands/ListNetworksCmd.java index a198a044148..9f660b35f95 100644 --- a/api/src/com/cloud/api/commands/ListNetworksCmd.java +++ b/api/src/com/cloud/api/commands/ListNetworksCmd.java @@ -27,7 +27,6 @@ import com.cloud.api.ApiConstants; import com.cloud.api.BaseListCmd; import com.cloud.api.Implementation; import com.cloud.api.Parameter; -import com.cloud.api.BaseCmd.CommandType; import com.cloud.api.response.ListResponse; import com.cloud.api.response.NetworkResponse; import com.cloud.network.Network; diff --git a/api/src/com/cloud/api/commands/UpdateNetworkOfferingCmd.java b/api/src/com/cloud/api/commands/UpdateNetworkOfferingCmd.java index 23c9425803b..db6e1a9b58c 100644 --- a/api/src/com/cloud/api/commands/UpdateNetworkOfferingCmd.java +++ b/api/src/com/cloud/api/commands/UpdateNetworkOfferingCmd.java @@ -18,6 +18,13 @@ package com.cloud.api.commands; +import java.util.ArrayList; +import java.util.Collection; +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; +import java.util.Map; + import org.apache.log4j.Logger; import com.cloud.api.ApiConstants; @@ -25,6 +32,7 @@ import com.cloud.api.BaseCmd; import com.cloud.api.Implementation; import com.cloud.api.Parameter; import com.cloud.api.ServerApiException; +import com.cloud.api.BaseCmd.CommandType; import com.cloud.api.response.NetworkOfferingResponse; import com.cloud.offering.NetworkOffering; import com.cloud.offering.NetworkOffering.Availability; @@ -49,7 +57,40 @@ public class UpdateNetworkOfferingCmd extends BaseCmd { private String displayText; @Parameter(name=ApiConstants.AVAILABILITY, type=CommandType.STRING, description="the availability of network offering. Default value is Required for Guest Virtual network offering; Optional for Guest Direct network offering") - private String availability; + private String availability; + + @Parameter(name=ApiConstants.DHCP_SERVICE, type=CommandType.BOOLEAN, description="true is network offering supports dhcp service") + private Boolean dhcpService; + + @Parameter(name=ApiConstants.DNS_SERVICE, type=CommandType.BOOLEAN, description="true is network offering supports dns service") + private Boolean dnsService; + + @Parameter(name=ApiConstants.GATEWAY_SERVICE, type=CommandType.BOOLEAN, description="true is network offering supports gateway service") + private Boolean gatewayService; + + @Parameter(name=ApiConstants.FIREWALL_SERVICE, type=CommandType.BOOLEAN, description="true is network offering supports firewall service") + private Boolean firewallService; + + @Parameter(name=ApiConstants.LB_SERVICE, type=CommandType.BOOLEAN, description="true is network offering supports lb service") + private Boolean lbService; + + @Parameter(name=ApiConstants.USERDATA_SERVICE, type=CommandType.BOOLEAN, description="true is network offering supports user data service") + private Boolean userdataService; + + @Parameter(name=ApiConstants.SOURCE_NAT_SERVICE, type=CommandType.BOOLEAN, description="true is network offering supports source nat service") + private Boolean sourceNatService; + + @Parameter(name=ApiConstants.VPN_SERVICE, type=CommandType.BOOLEAN, description="true is network offering supports vpn service") + private Boolean vpnService; + + @Parameter(name = ApiConstants.SERVICE_PROVIDER_LIST, type = CommandType.MAP, description = "provider to service mapping. If not specified, the provider for the service will be mapped to the default provider on the physical network") + private Map serviceProviderList; + + @Parameter(name=ApiConstants.STATE, type=CommandType.STRING, description="list network offerings by state") + private String state; + + @Parameter(name=ApiConstants.SECURITY_GROUP_EANBLED, type=CommandType.BOOLEAN, description="true is security group is enabled for the network offering") + private Boolean securityGroupEnabled; ///////////////////////////////////////////////////// /////////////////// Accessors /////////////////////// @@ -69,6 +110,70 @@ public class UpdateNetworkOfferingCmd extends BaseCmd { public String getAvailability() { return availability == null ? Availability.Required.toString() : availability; + } + + public Boolean getDhcpService() { + return dhcpService; + } + + public Boolean getDnsService() { + return dnsService; + } + + public Boolean getGatewayService() { + return gatewayService; + } + + public Boolean getFirewallService() { + return firewallService; + } + + public Boolean getLbService() { + return lbService; + } + + public Boolean getUserdataService() { + return userdataService; + } + + public Boolean getSourceNatService() { + return sourceNatService; + } + + public Boolean getVpnService() { + return vpnService; + } + + public Map> getServiceProviders() { + Map> serviceProviderMap = null; + if (serviceProviderList != null && !serviceProviderList.isEmpty()) { + serviceProviderMap = new HashMap>(); + Collection servicesCollection = serviceProviderList.values(); + Iterator iter = servicesCollection.iterator(); + while (iter.hasNext()) { + HashMap services = (HashMap) iter.next(); + String service = (String)services.get("service"); + String provider = (String) services.get("provider"); + List providerList = null; + if (serviceProviderMap.containsKey(service)) { + providerList = serviceProviderMap.get(service); + } else { + providerList = new ArrayList(); + } + providerList.add(provider); + serviceProviderMap.put(service, providerList); + } + } + + return serviceProviderMap; + } + + public String getState() { + return state; + } + + public Boolean getSecurityGroupEnabled() { + return securityGroupEnabled; } ///////////////////////////////////////////////////// diff --git a/api/src/com/cloud/api/response/NetworkOfferingResponse.java b/api/src/com/cloud/api/response/NetworkOfferingResponse.java index 2c5c41574f3..26b3833ee73 100644 --- a/api/src/com/cloud/api/response/NetworkOfferingResponse.java +++ b/api/src/com/cloud/api/response/NetworkOfferingResponse.java @@ -70,6 +70,9 @@ public class NetworkOfferingResponse extends BaseResponse{ @SerializedName(ApiConstants.STATE) @Param(description="state of the network offering. Can be Disabled/Enabled/Inactive") private String state; + + @SerializedName(ApiConstants.TYPE) @Param(description="type of the network offering, can be Shared or Isolated") + private String type; @SerializedName("service") @Param(description="the list of supported services", responseObject = ServiceResponse.class) private List services; @@ -137,4 +140,8 @@ public class NetworkOfferingResponse extends BaseResponse{ public void setState(String state) { this.state = state; } + + public void setType(String type) { + this.type = type; + } } diff --git a/api/src/com/cloud/api/response/NetworkResponse.java b/api/src/com/cloud/api/response/NetworkResponse.java index f998cfc706b..f4f4a272551 100644 --- a/api/src/com/cloud/api/response/NetworkResponse.java +++ b/api/src/com/cloud/api/response/NetworkResponse.java @@ -69,6 +69,7 @@ public class NetworkResponse extends BaseResponse implements ControlledEntityRes @SerializedName("networkofferingavailability") @Param(description="availability of the network offering the network is created from") private String networkOfferingAvailability; + @Deprecated @SerializedName(ApiConstants.IS_SHARED) @Param(description="true if network is shared, false otherwise") private Boolean isShared; diff --git a/api/src/com/cloud/api/response/ProviderResponse.java b/api/src/com/cloud/api/response/ProviderResponse.java new file mode 100644 index 00000000000..a3cdf811aa6 --- /dev/null +++ b/api/src/com/cloud/api/response/ProviderResponse.java @@ -0,0 +1,35 @@ +/** + * Copyright (C) 2011 Citrix Systems, Inc. All rights reserved + * + * This software is licensed under the GNU General Public License v3 or later. + * + * It is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or any later version. + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + */ +package com.cloud.api.response; + +import java.util.List; + +import com.cloud.api.ApiConstants; +import com.cloud.serializer.Param; +import com.google.gson.annotations.SerializedName; + +@SuppressWarnings("unused") +public class ProviderResponse extends BaseResponse { + + @SerializedName(ApiConstants.NAME) @Param(description="the provider name") + private String name; + + public void setName(String name) { + this.name = name; + } +} diff --git a/api/src/com/cloud/api/response/ServiceResponse.java b/api/src/com/cloud/api/response/ServiceResponse.java index e32fed76396..d3ce9198c7d 100644 --- a/api/src/com/cloud/api/response/ServiceResponse.java +++ b/api/src/com/cloud/api/response/ServiceResponse.java @@ -30,7 +30,7 @@ public class ServiceResponse extends BaseResponse { private String name; @SerializedName(ApiConstants.PROVIDER) @Param(description="the service provider name") - private String provider; + private List providers; @SerializedName("capability") @Param(description="the list of capabilities", responseObject = CapabilityResponse.class) private List capabilities; @@ -47,7 +47,7 @@ public class ServiceResponse extends BaseResponse { this.capabilities = capabilities; } - public void setProvider(String provider) { - this.provider = provider; + public void setProviders(List providers) { + this.providers = providers; } } \ No newline at end of file diff --git a/api/src/com/cloud/network/Network.java b/api/src/com/cloud/network/Network.java index 653229728c8..b13c8683744 100644 --- a/api/src/com/cloud/network/Network.java +++ b/api/src/com/cloud/network/Network.java @@ -43,6 +43,11 @@ public interface Network extends ControlledEntity { Virtual, Direct, } + + public enum Type { + Shared, + Isolated + } public static class Service { private static List supportedServices = new ArrayList(); @@ -247,8 +252,6 @@ public interface Network extends ControlledEntity { String getDisplayText(); - boolean getIsShared(); - String getReservationId(); boolean isDefault(); @@ -259,4 +262,6 @@ public interface Network extends ControlledEntity { List getTags(); + Type getType(); + } diff --git a/api/src/com/cloud/network/NetworkProfile.java b/api/src/com/cloud/network/NetworkProfile.java index 64da475b91d..c03435f1472 100644 --- a/api/src/com/cloud/network/NetworkProfile.java +++ b/api/src/com/cloud/network/NetworkProfile.java @@ -43,14 +43,14 @@ public class NetworkProfile implements Network { private String cidr; private long networkOfferingId; private long related; - private GuestIpType guestIpType; private String displayText; - private boolean isShared; private String reservationId; private boolean isDefault; private String networkDomain; private boolean isSecurityGroupEnabled; private List tags; + private Network.Type type; + private GuestIpType guestIpType; public NetworkProfile(Network network) { this.id = network.getId(); @@ -66,14 +66,14 @@ public class NetworkProfile implements Network { this.cidr = network.getCidr(); this.networkOfferingId = network.getNetworkOfferingId(); this.related = network.getRelated(); - this.guestIpType = network.getGuestType(); this.displayText = network.getDisplayText(); - this.isShared = network.getIsShared(); this.reservationId = network.getReservationId(); this.isDefault = network.isDefault(); this.networkDomain = network.getNetworkDomain(); this.domainId = network.getDomainId(); this.isSecurityGroupEnabled = network.isSecurityGroupEnabled(); + this.type = network.getType(); + this.guestIpType = network.getGuestType(); } @Override @@ -175,12 +175,7 @@ public class NetworkProfile implements Network { public String getDisplayText() { return displayText; } - - @Override - public boolean getIsShared() { - return isShared; - } - + @Override public String getReservationId() { return reservationId; @@ -205,4 +200,9 @@ public class NetworkProfile implements Network { public boolean isSecurityGroupEnabled() { return isSecurityGroupEnabled; } + + @Override + public Network.Type getType(){ + return type; + } } diff --git a/api/src/com/cloud/network/NetworkService.java b/api/src/com/cloud/network/NetworkService.java index 807efee15e0..8cfce0ad783 100644 --- a/api/src/com/cloud/network/NetworkService.java +++ b/api/src/com/cloud/network/NetworkService.java @@ -19,6 +19,7 @@ package com.cloud.network; import java.util.List; import java.util.Map; +import java.util.Set; import com.cloud.api.commands.AssociateIPAddrCmd; import com.cloud.api.commands.CreateNetworkCmd; @@ -86,5 +87,5 @@ public interface NetworkService { Network getSystemNetworkByZoneAndTrafficType(long zoneId, TrafficType trafficType); - Map listNetworkOfferingServices(long networkOfferingId); + Map> listNetworkOfferingServices(long networkOfferingId); } diff --git a/api/src/com/cloud/offering/NetworkOffering.java b/api/src/com/cloud/offering/NetworkOffering.java index 2b0ea43ef95..81c2e141c5c 100644 --- a/api/src/com/cloud/offering/NetworkOffering.java +++ b/api/src/com/cloud/offering/NetworkOffering.java @@ -18,6 +18,9 @@ package com.cloud.offering; import com.cloud.network.Network.GuestIpType; +import com.cloud.network.Network.Provider; +import com.cloud.network.Network.Service; +import com.cloud.network.Network.Type; import com.cloud.network.Networks.TrafficType; /** @@ -97,4 +100,8 @@ public interface NetworkOffering { void setState(State state); State getState(); + + void setSecurityGroupEnabled(boolean securityGroupEnabled); + + Type getType(); } diff --git a/server/src/com/cloud/api/ApiDBUtils.java b/server/src/com/cloud/api/ApiDBUtils.java index 0ac2249cd91..d3659751f47 100755 --- a/server/src/com/cloud/api/ApiDBUtils.java +++ b/server/src/com/cloud/api/ApiDBUtils.java @@ -21,6 +21,7 @@ package com.cloud.api; import java.util.Hashtable; import java.util.List; import java.util.Map; +import java.util.Set; import com.cloud.agent.AgentManager; import com.cloud.async.AsyncJobManager; @@ -649,7 +650,7 @@ public class ApiDBUtils { return _projectMgr.getProjectOwner(projectId).getId(); } - public static Map listNetworkOfferingServices(long networkOfferingId) { + public static Map> listNetworkOfferingServices(long networkOfferingId) { return _networkMgr.listNetworkOfferingServices(networkOfferingId); } } diff --git a/server/src/com/cloud/api/ApiResponseHelper.java b/server/src/com/cloud/api/ApiResponseHelper.java index 5cdf3dd3873..e49dabaa923 100755 --- a/server/src/com/cloud/api/ApiResponseHelper.java +++ b/server/src/com/cloud/api/ApiResponseHelper.java @@ -66,6 +66,7 @@ import com.cloud.api.response.PodResponse; import com.cloud.api.response.ProjectAccountResponse; import com.cloud.api.response.ProjectInvitationResponse; import com.cloud.api.response.ProjectResponse; +import com.cloud.api.response.ProviderResponse; import com.cloud.api.response.RemoteAccessVpnResponse; import com.cloud.api.response.ResourceCountResponse; import com.cloud.api.response.ResourceLimitResponse; @@ -2111,6 +2112,9 @@ public class ApiResponseHelper implements ResponseGenerator { response.setAvailability(offering.getAvailability().toString()); response.setNetworkRate(ApiDBUtils.getNetworkRate(offering.getId())); response.setIsSecurityGroupEnabled(offering.isSecurityGroupEnabled()); + if (offering.getType() != null) { + response.setType(offering.getType().toString()); + } if (offering.getGuestType() != null) { response.setGuestIpType(offering.getGuestType().toString()); @@ -2118,12 +2122,18 @@ public class ApiResponseHelper implements ResponseGenerator { response.setState(offering.getState().name()); - Map serviceProviderMap = ApiDBUtils.listNetworkOfferingServices(offering.getId()); + Map> serviceProviderMap = ApiDBUtils.listNetworkOfferingServices(offering.getId()); List serviceResponses = new ArrayList(); for (String service : serviceProviderMap.keySet()) { ServiceResponse svcRsp = new ServiceResponse(); svcRsp.setName(service); - svcRsp.setProvider(serviceProviderMap.get(service)); + List providers = new ArrayList(); + for (String provider : serviceProviderMap.get(service)) { + ProviderResponse providerRsp = new ProviderResponse(); + providerRsp.setName(provider); + providers.add(providerRsp); + } + svcRsp.setProviders(providers); serviceResponses.add(svcRsp); } response.setServices(serviceResponses); @@ -2179,7 +2189,9 @@ public class ApiResponseHelper implements ResponseGenerator { response.setNetworkOfferingAvailability(networkOffering.getAvailability().toString()); } - response.setIsShared(network.getIsShared()); + if (network.getType() != null && network.getType() == Network.Type.Shared) { + response.setIsShared(true); + } response.setIsDefault(network.isDefault()); response.setState(network.getState().toString()); response.setRelated(network.getRelated()); diff --git a/server/src/com/cloud/baremetal/BareMetalVmManagerImpl.java b/server/src/com/cloud/baremetal/BareMetalVmManagerImpl.java index 78dfe31da9d..bcbbdf166b2 100755 --- a/server/src/com/cloud/baremetal/BareMetalVmManagerImpl.java +++ b/server/src/com/cloud/baremetal/BareMetalVmManagerImpl.java @@ -321,7 +321,7 @@ public class BareMetalVmManagerImpl extends UserVmManagerImpl implements BareMet if (network == null) { throw new InvalidParameterValueException("Unable to find network by id " + networkId); } else { - if (!network.getIsShared()) { + if (network.getType() != Network.Type.Shared) { //Check account permissions List networkMap = _networkDao.listBy(accountId, networkId); if (networkMap == null || networkMap.isEmpty()) { diff --git a/server/src/com/cloud/configuration/ConfigurationManager.java b/server/src/com/cloud/configuration/ConfigurationManager.java index d89c0cf89f9..add65a754bb 100644 --- a/server/src/com/cloud/configuration/ConfigurationManager.java +++ b/server/src/com/cloud/configuration/ConfigurationManager.java @@ -19,6 +19,7 @@ package com.cloud.configuration; import java.util.List; import java.util.Map; +import java.util.Set; import com.cloud.dc.ClusterVO; import com.cloud.dc.DataCenter; @@ -33,6 +34,8 @@ import com.cloud.exception.InvalidParameterValueException; import com.cloud.exception.PermissionDeniedException; import com.cloud.network.Network; import com.cloud.network.Network.GuestIpType; +import com.cloud.network.Network.Provider; +import com.cloud.network.Network.Service; import com.cloud.network.Networks.TrafficType; import com.cloud.offering.DiskOffering; import com.cloud.offering.NetworkOffering.Availability; @@ -178,12 +181,13 @@ public interface ConfigurationManager extends ConfigurationService, Manager { * @param serviceProviderMap TODO * @param isDefault TODO * @param isSecurityGroupEnabled TODO + * @param type TODO * @param id * @param specifyVlan; * @return network offering object */ - NetworkOfferingVO createNetworkOffering(long userId, String name, String displayText, TrafficType trafficType, String tags, Integer maxConnections, boolean specifyVlan, Availability availability, GuestIpType guestIpType, Integer networkRate, Map serviceProviderMap, boolean isDefault, boolean isSecurityGroupEnabled); + NetworkOfferingVO createNetworkOffering(long userId, String name, String displayText, TrafficType trafficType, String tags, Integer maxConnections, boolean specifyVlan, Availability availability, GuestIpType guestIpType, Integer networkRate, Map> serviceProviderMap, boolean isDefault, boolean isSecurityGroupEnabled, Network.Type type); Vlan createVlanAndPublicIpRange(Long userId, Long zoneId, Long podId, String startIP, String endIP, String vlanGateway, String vlanNetmask, boolean forVirtualNetwork, String vlanId, Account account, Long networkId) throws InsufficientCapacityException, ConcurrentOperationException, InvalidParameterValueException; diff --git a/server/src/com/cloud/configuration/ConfigurationManagerImpl.java b/server/src/com/cloud/configuration/ConfigurationManagerImpl.java index f24e4c61b04..c26c4a5e5b1 100755 --- a/server/src/com/cloud/configuration/ConfigurationManagerImpl.java +++ b/server/src/com/cloud/configuration/ConfigurationManagerImpl.java @@ -97,6 +97,8 @@ import com.cloud.host.dao.HostDetailsDao; import com.cloud.hypervisor.Hypervisor.HypervisorType; import com.cloud.network.Network; import com.cloud.network.Network.GuestIpType; +import com.cloud.network.Network.Provider; +import com.cloud.network.Network.Service; import com.cloud.network.NetworkManager; import com.cloud.network.NetworkVO; import com.cloud.network.Networks.BroadcastDomainType; @@ -1523,7 +1525,7 @@ public class ConfigurationManagerImpl implements ConfigurationManager, Configura } userNetwork.setBroadcastDomainType(broadcastDomainType); userNetwork.setNetworkDomain(networkDomain); - _networkMgr.setupNetwork(systemAccount, offering, userNetwork, plan, null, null, true, isNetworkDefault, false, null, null); + _networkMgr.setupNetwork(systemAccount, offering, userNetwork, plan, null, null, isNetworkDefault, false, null, null); } } } @@ -1998,7 +2000,7 @@ public class ConfigurationManagerImpl implements ConfigurationManager, Configura if (network == null) { // find default public network in the zone networkId = _networkMgr.getSystemNetworkByZoneAndTrafficType(zoneId, TrafficType.Public).getId(); - } else if (network.getGuestType() != null || network.getTrafficType() != TrafficType.Public) { + } else if (network.getType() != null || network.getTrafficType() != TrafficType.Public) { throw new InvalidParameterValueException("Can't find Public network by id=" + networkId); } } else { @@ -2012,8 +2014,8 @@ public class ConfigurationManagerImpl implements ConfigurationManager, Configura } networkId = network.getId(); } - } else if (network.getGuestType() == null || network.getGuestType() == GuestIpType.Virtual) { - throw new InvalidParameterValueException("Can't create direct vlan for network id=" + networkId + " with GuestType: " + network.getGuestType()); + } else if (network.getType() == null || network.getType()== Network.Type.Isolated) { + throw new InvalidParameterValueException("Can't create direct vlan for network id=" + networkId + " with type: " + network.getType()); } } @@ -2852,6 +2854,7 @@ public class ConfigurationManagerImpl implements ConfigurationManager, Configura TrafficType trafficType = null; GuestIpType guestIpType = null; Availability availability = null; + Network.Type type = null; // Verify traffic type for (TrafficType tType : TrafficType.values()) { @@ -2875,6 +2878,18 @@ public class ConfigurationManagerImpl implements ConfigurationManager, Configura if (guestIpType == null) { throw new InvalidParameterValueException("Invalid guest IP type; can have Direct or Virtual value"); } + + //Verify offering type + for (Network.Type offType : Network.Type.values()) { + if (offType.name().equalsIgnoreCase(cmd.getType())){ + type = offType; + break; + } + } + + if (type == null) { + throw new InvalidParameterValueException("Invalid type is given; can have Shared and Isolated values"); + } // Verify availability for (Availability avlb : Availability.values()) { @@ -2890,73 +2905,79 @@ public class ConfigurationManagerImpl implements ConfigurationManager, Configura Integer maxConnections = cmd.getMaxconnections(); //configure service provider map - Map serviceProviderMap = new HashMap(); + Map> serviceProviderMap = new HashMap>(); + Set defaultProviders = new HashSet(); + defaultProviders.add(Network.Provider.defaultProvider); //populate all services first if (cmd.getDhcpService()) { - serviceProviderMap.put(Network.Service.Dhcp, Network.Provider.defaultProvider); + serviceProviderMap.put(Network.Service.Dhcp, defaultProviders); } if (cmd.getDnsService()) { - serviceProviderMap.put(Network.Service.Dns, Network.Provider.defaultProvider); + serviceProviderMap.put(Network.Service.Dns, defaultProviders); } if (cmd.getFirewallService()) { - serviceProviderMap.put(Network.Service.Firewall, Network.Provider.defaultProvider); + serviceProviderMap.put(Network.Service.Firewall, defaultProviders); } if (cmd.getGatewayService()) { - serviceProviderMap.put(Network.Service.Gateway, Network.Provider.defaultProvider); + serviceProviderMap.put(Network.Service.Gateway, defaultProviders); } if (cmd.getLbService()) { - serviceProviderMap.put(Network.Service.Lb, Network.Provider.defaultProvider); + serviceProviderMap.put(Network.Service.Lb, defaultProviders); } if (cmd.getSourceNatService()) { - serviceProviderMap.put(Network.Service.SourceNat, Network.Provider.defaultProvider); + serviceProviderMap.put(Network.Service.SourceNat, defaultProviders); } if (cmd.getUserdataService()) { - serviceProviderMap.put(Network.Service.UserData, Network.Provider.defaultProvider); + serviceProviderMap.put(Network.Service.UserData, defaultProviders); } if (cmd.getVpnService()) { - serviceProviderMap.put(Network.Service.Vpn, Network.Provider.defaultProvider); + serviceProviderMap.put(Network.Service.Vpn, defaultProviders); } //populate providers - Map svcPrv = (Map)cmd.getServiceProviderList(); + Map> svcPrv = (Map>)cmd.getServiceProviders(); if (svcPrv != null) { for (String serviceStr : svcPrv.keySet()) { Network.Service service = Network.Service.getService(serviceStr); if (serviceProviderMap.containsKey(service)) { - //check if provider is supported - Network.Provider provider; - String prvNameStr = svcPrv.get(serviceStr); - provider = Network.Provider.getProvider(prvNameStr); - if (provider == null) { - throw new InvalidParameterValueException("Invalid service provider: " + prvNameStr); - } - serviceProviderMap.put(service, provider); + serviceProviderMap.clear(); + Set providers = new HashSet(); + for (String prvNameStr : svcPrv.get(serviceStr)) { + //check if provider is supported + Network.Provider provider; + provider = Network.Provider.getProvider(prvNameStr); + if (provider == null) { + throw new InvalidParameterValueException("Invalid service provider: " + prvNameStr); + } + providers.add(provider); + } + serviceProviderMap.put(service, providers); } else { throw new InvalidParameterValueException("Service " + serviceStr + " is not enabled for the network offering, can't add a provider to it"); } } } - return createNetworkOffering(userId, name, displayText, trafficType, tags, maxConnections, specifyVlan, availability, guestIpType, networkRate, serviceProviderMap, false, isSecurityGroupEnabled); + return createNetworkOffering(userId, name, displayText, trafficType, tags, maxConnections, specifyVlan, availability, guestIpType, networkRate, serviceProviderMap, false, isSecurityGroupEnabled, type); } @Override @DB public NetworkOfferingVO createNetworkOffering(long userId, String name, String displayText, TrafficType trafficType, String tags, Integer maxConnections, boolean specifyVlan, - Availability availability, GuestIpType guestIpType, Integer networkRate, Map serviceProviderMap, boolean isDefault, boolean isSecurityGroupEnabled) { + Availability availability, GuestIpType guestIpType, Integer networkRate, Map> serviceProviderMap, boolean isDefault, boolean isSecurityGroupEnabled, Network.Type type) { String multicastRateStr = _configDao.getValue("multicast.throttling.rate"); int multicastRate = ((multicastRateStr == null) ? 10 : Integer.parseInt(multicastRateStr)); tags = cleanupTags(tags); - NetworkOfferingVO offering = new NetworkOfferingVO(name, displayText, trafficType, false, specifyVlan, networkRate, multicastRate, maxConnections, isDefault, availability,guestIpType, tags, isSecurityGroupEnabled); + NetworkOfferingVO offering = new NetworkOfferingVO(name, displayText, trafficType, false, specifyVlan, networkRate, multicastRate, maxConnections, isDefault, availability,guestIpType, tags, isSecurityGroupEnabled, type); Transaction txn = Transaction.currentTxn(); txn.start(); @@ -2966,9 +2987,11 @@ public class ConfigurationManagerImpl implements ConfigurationManager, Configura //populate services and providers if (serviceProviderMap != null) { for (Network.Service service : serviceProviderMap.keySet()) { - NetworkOfferingServiceMapVO offService = new NetworkOfferingServiceMapVO(offering.getId(), service, serviceProviderMap.get(service)); - _ntwkOffServiceMapDao.persist(offService); - s_logger.trace("Added service for the network offering: " + offService); + for (Network.Provider provider : serviceProviderMap.get(service)) { + NetworkOfferingServiceMapVO offService = new NetworkOfferingServiceMapVO(offering.getId(), service, provider); + _ntwkOffServiceMapDao.persist(offService); + s_logger.trace("Added service for the network offering: " + offService); + } } } @@ -3095,12 +3118,15 @@ public class ConfigurationManagerImpl implements ConfigurationManager, Configura } @Override @ActionEvent(eventType = EventTypes.EVENT_NETWORK_OFFERING_EDIT, eventDescription = "updating network offering") + @DB public NetworkOffering updateNetworkOffering(UpdateNetworkOfferingCmd cmd) { String displayText = cmd.getDisplayText(); Long id = cmd.getId(); String name = cmd.getNetworkOfferingName(); String availabilityStr = cmd.getAvailability(); Availability availability = null; + Boolean sgEnabled = cmd.getSecurityGroupEnabled(); + String state = cmd.getState(); UserContext.current().setEventDetails(" Id: "+id); // Verify input parameters @@ -3114,11 +3140,6 @@ public class ConfigurationManagerImpl implements ConfigurationManager, Configura throw new InvalidParameterValueException("Can't update system network offerings"); } - // Don't allow to update default Direct network offering - if (offeringToUpdate.isDefault() && offeringToUpdate.getGuestType() == GuestIpType.Direct) { - throw new InvalidParameterValueException("Can't update Default Direct network offering"); - } - NetworkOfferingVO offering = _networkOfferingDao.createForUpdate(id); if (name != null) { @@ -3128,6 +3149,19 @@ public class ConfigurationManagerImpl implements ConfigurationManager, Configura if (displayText != null) { offering.setDisplayText(displayText); } + + if (state != null) { + boolean validState = false; + for (NetworkOffering.State st : NetworkOffering.State.values()) { + if (st.name().equalsIgnoreCase(state)) { + validState = true; + offering.setState(st); + } + } + if (!validState) { + throw new InvalidParameterValueException("Incorrect state value: " + state); + } + } // Verify availability if (availabilityStr != null) { @@ -3142,10 +3176,107 @@ public class ConfigurationManagerImpl implements ConfigurationManager, Configura offering.setAvailability(availability); } } - - if (_networkOfferingDao.update(id, offering)) { - offering = _networkOfferingDao.findById(id); - return offering; + + //All parameters below can be updated only when there are no networks using this offering + Long networks = _networkDao.getNetworkCountByOfferingId(id); + boolean networksExist = (networks != null && networks.longValue() > 0); + + if (sgEnabled != null) { + if (networksExist) { + throw new InvalidParameterValueException("Unable to reset securityGroupEnabled property as there are existing networks using this network offering"); + } + offering.setSecurityGroupEnabled(sgEnabled); + } + + //configure service provider map + Map> serviceProviderMap = new HashMap>(); + Set defaultProviders = new HashSet(); + defaultProviders.add(Network.Provider.defaultProvider); + //populate all services first + if (cmd.getDhcpService()) { + serviceProviderMap.put(Network.Service.Dhcp, defaultProviders); + } + + if (cmd.getDnsService()) { + serviceProviderMap.put(Network.Service.Dns, defaultProviders); + } + + if (cmd.getFirewallService()) { + serviceProviderMap.put(Network.Service.Firewall, defaultProviders); + } + + if (cmd.getGatewayService()) { + serviceProviderMap.put(Network.Service.Gateway, defaultProviders); + } + + if (cmd.getLbService()) { + serviceProviderMap.put(Network.Service.Lb, defaultProviders); + } + + if (cmd.getSourceNatService()) { + serviceProviderMap.put(Network.Service.SourceNat, defaultProviders); + } + + if (cmd.getUserdataService()) { + serviceProviderMap.put(Network.Service.UserData, defaultProviders); + } + + if (cmd.getVpnService()) { + serviceProviderMap.put(Network.Service.Vpn, defaultProviders); + } + + //populate providers + Map> svcPrv = (Map>)cmd.getServiceProviders(); + if (svcPrv != null) { + for (String serviceStr : svcPrv.keySet()) { + Network.Service service = Network.Service.getService(serviceStr); + if (serviceProviderMap.containsKey(service)) { + serviceProviderMap.clear(); + Set providers = new HashSet(); + for (String prvNameStr : svcPrv.get(serviceStr)) { + //check if provider is supported + Network.Provider provider; + provider = Network.Provider.getProvider(prvNameStr); + if (provider == null) { + throw new InvalidParameterValueException("Invalid service provider: " + prvNameStr); + } + providers.add(provider); + } + serviceProviderMap.put(service, providers); + } else { + throw new InvalidParameterValueException("Service " + serviceStr + " is not enabled for the network offering, can't add a provider to it"); + } + } + } + + if (svcPrv != null && !svcPrv.isEmpty()) { + if (networksExist) { + throw new InvalidParameterValueException("Unable to reset service providers as there are existing networks using this network offering"); + } + } + + + boolean success = true; + Transaction txn = Transaction.currentTxn(); + txn.start(); + //update network offering + success = success && _networkOfferingDao.update(id, offering); + _ntwkOffServiceMapDao.deleteByOfferingId(id); + //update services/providers - delete old ones, insert new ones + if (serviceProviderMap != null) { + for (Network.Service service : serviceProviderMap.keySet()) { + for (Network.Provider provider : serviceProviderMap.get(service)) { + NetworkOfferingServiceMapVO offService = new NetworkOfferingServiceMapVO(offering.getId(), service, provider); + _ntwkOffServiceMapDao.persist(offService); + s_logger.trace("Added service for the network offering: " + offService); + } + } + } + + txn.commit(); + + if (success) { + return _networkOfferingDao.findById(id); } else { return null; } diff --git a/server/src/com/cloud/consoleproxy/ConsoleProxyManagerImpl.java b/server/src/com/cloud/consoleproxy/ConsoleProxyManagerImpl.java index b155abf42b3..2d9285fc4ad 100644 --- a/server/src/com/cloud/consoleproxy/ConsoleProxyManagerImpl.java +++ b/server/src/com/cloud/consoleproxy/ConsoleProxyManagerImpl.java @@ -558,9 +558,9 @@ public class ConsoleProxyManagerImpl implements ConsoleProxyManager, ConsoleProx NicProfile defaultNic = new NicProfile(); defaultNic.setDefaultNic(true); defaultNic.setDeviceId(2); - networks.add(new Pair(_networkMgr.setupNetwork(systemAcct, defaultOffering.get(0), plan, null, null, false, false).get(0), defaultNic)); + networks.add(new Pair(_networkMgr.setupNetwork(systemAcct, defaultOffering.get(0), plan, null, null, false).get(0), defaultNic)); for (NetworkOfferingVO offering : offerings) { - networks.add(new Pair(_networkMgr.setupNetwork(systemAcct, offering, plan, null, null, false, false).get(0), null)); + networks.add(new Pair(_networkMgr.setupNetwork(systemAcct, offering, plan, null, null, false).get(0), null)); } VMTemplateVO template = _templateDao.findSystemVMTemplate(dataCenterId, desiredHyp); diff --git a/server/src/com/cloud/network/NetworkManager.java b/server/src/com/cloud/network/NetworkManager.java index 582b884f850..d9438c3de08 100644 --- a/server/src/com/cloud/network/NetworkManager.java +++ b/server/src/com/cloud/network/NetworkManager.java @@ -30,6 +30,7 @@ import com.cloud.exception.InsufficientCapacityException; import com.cloud.exception.ResourceUnavailableException; import com.cloud.network.Network.Capability; import com.cloud.network.Network.GuestIpType; +import com.cloud.network.Network.Provider; import com.cloud.network.Network.Service; import com.cloud.network.Networks.TrafficType; import com.cloud.network.addr.PublicIp; @@ -107,11 +108,11 @@ public interface NetworkManager extends NetworkService { */ List listPublicIpAddressesInVirtualNetwork(long accountId, long dcId, Boolean sourceNat, Long associatedNetworkId); - List setupNetwork(Account owner, NetworkOfferingVO offering, DeploymentPlan plan, String name, String displayText, boolean isShared, boolean isDefault) + List setupNetwork(Account owner, NetworkOfferingVO offering, DeploymentPlan plan, String name, String displayText, boolean isDefault) throws ConcurrentOperationException; - List setupNetwork(Account owner, NetworkOfferingVO offering, Network predefined, DeploymentPlan plan, String name, String displayText, boolean isShared, boolean isDefault, - boolean errorIfAlreadySetup, Long domainId, List tags) throws ConcurrentOperationException; + List setupNetwork(Account owner, NetworkOfferingVO offering, Network predefined, DeploymentPlan plan, String name, String displayText, boolean isDefault, boolean errorIfAlreadySetup, + Long domainId, List tags) throws ConcurrentOperationException; List getSystemAccountNetworkOfferings(String... offeringNames); @@ -159,8 +160,8 @@ public interface NetworkManager extends NetworkService { boolean destroyNetwork(long networkId, ReservationContext context); - Network createNetwork(long networkOfferingId, String name, String displayText, Boolean isShared, Boolean isDefault, Long zoneId, String gateway, String cidr, String vlanId, String networkDomain, - Account owner, boolean isSecurityGroupEnabled, Long domainId, List tags) throws ConcurrentOperationException, InsufficientCapacityException; + Network createNetwork(long networkOfferingId, String name, String displayText, Boolean isDefault, Long zoneId, String gateway, String cidr, String vlanId, String networkDomain, Account owner, + boolean isSecurityGroupEnabled, Long domainId, List tags) throws ConcurrentOperationException, InsufficientCapacityException; /** * @throws InsufficientCapacityException @@ -219,5 +220,7 @@ public interface NetworkManager extends NetworkService { String getIpInNetworkIncludingRemoved(long vmId, long networkId); Long getPodIdForVlan(long vlanDbId); + + boolean isProviderSupported(long networkOfferingId, Service service, Provider provider); } diff --git a/server/src/com/cloud/network/NetworkManagerImpl.java b/server/src/com/cloud/network/NetworkManagerImpl.java index c7d905de1fc..5de0ecf2b54 100755 --- a/server/src/com/cloud/network/NetworkManagerImpl.java +++ b/server/src/com/cloud/network/NetworkManagerImpl.java @@ -637,7 +637,7 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag // First IP address should be source nat when it's being associated with Guest Virtual network List addrs = listPublicIpAddressesInVirtualNetwork(ownerId, zoneId, true, networkId); - if (addrs.isEmpty() && network.getGuestType() == GuestIpType.Virtual) { + if (addrs.isEmpty() && network.getType() == Network.Type.Isolated) { isSourceNat = true; } } @@ -782,20 +782,24 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag _systemNetworks.put(NetworkOfferingVO.SystemStorageNetwork, storageNetworkOffering); //populate providers - Map defaultDirectNetworkOfferingProviders = new HashMap(); - defaultDirectNetworkOfferingProviders.put(Service.Dhcp, Provider.DhcpServer); - defaultDirectNetworkOfferingProviders.put(Service.Dns, Provider.DhcpServer); - defaultDirectNetworkOfferingProviders.put(Service.UserData, Provider.DhcpServer); + Map> defaultDirectNetworkOfferingProviders = new HashMap>(); + Set defaultProviders = new HashSet(); + defaultProviders.add(Network.Provider.DhcpServer); + defaultDirectNetworkOfferingProviders.put(Service.Dhcp, defaultProviders); + defaultDirectNetworkOfferingProviders.put(Service.Dns, defaultProviders); + defaultDirectNetworkOfferingProviders.put(Service.UserData, defaultProviders); - Map defaultVirtualNetworkOfferingProviders = new HashMap(); - defaultVirtualNetworkOfferingProviders.put(Service.Dhcp, Provider.VirtualRouter); - defaultVirtualNetworkOfferingProviders.put(Service.Dns, Provider.VirtualRouter); - defaultVirtualNetworkOfferingProviders.put(Service.UserData, Provider.VirtualRouter); - defaultVirtualNetworkOfferingProviders.put(Service.Firewall, Provider.VirtualRouter); - defaultVirtualNetworkOfferingProviders.put(Service.Gateway, Provider.VirtualRouter); - defaultVirtualNetworkOfferingProviders.put(Service.Lb, Provider.VirtualRouter); - defaultVirtualNetworkOfferingProviders.put(Service.SourceNat, Provider.VirtualRouter); - defaultVirtualNetworkOfferingProviders.put(Service.Vpn, Provider.VirtualRouter); + Map> defaultVirtualNetworkOfferingProviders = new HashMap>(); + defaultProviders.clear(); + defaultProviders.add(Network.Provider.VirtualRouter); + defaultVirtualNetworkOfferingProviders.put(Service.Dhcp, defaultProviders); + defaultVirtualNetworkOfferingProviders.put(Service.Dns, defaultProviders); + defaultVirtualNetworkOfferingProviders.put(Service.UserData, defaultProviders); + defaultVirtualNetworkOfferingProviders.put(Service.Firewall, defaultProviders); + defaultVirtualNetworkOfferingProviders.put(Service.Gateway, defaultProviders); + defaultVirtualNetworkOfferingProviders.put(Service.Lb, defaultProviders); + defaultVirtualNetworkOfferingProviders.put(Service.SourceNat, defaultProviders); + defaultVirtualNetworkOfferingProviders.put(Service.Vpn, defaultProviders); Transaction txn = Transaction.currentTxn(); txn.start(); @@ -803,19 +807,19 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag //check that offering already exists NetworkOfferingVO offering = null; if (_networkOfferingDao.findByUniqueName(NetworkOffering.SystemGuestNetwork) == null) { - offering = _configMgr.createNetworkOffering(Account.ACCOUNT_ID_SYSTEM, NetworkOffering.SystemGuestNetwork, "System Offering for System-Guest-Network", TrafficType.Guest, null, null, false, Availability.Optional, GuestIpType.Direct, null, defaultDirectNetworkOfferingProviders, true, true); + offering = _configMgr.createNetworkOffering(Account.ACCOUNT_ID_SYSTEM, NetworkOffering.SystemGuestNetwork, "System Offering for System-Guest-Network", TrafficType.Guest, null, null, false, Availability.Optional, GuestIpType.Direct, null, defaultDirectNetworkOfferingProviders, true, true, Network.Type.Shared); offering.setState(NetworkOffering.State.Enabled); _networkOfferingDao.update(offering.getId(), offering); } if (_networkOfferingDao.findByUniqueName(NetworkOffering.DefaultVirtualizedNetworkOffering) == null) { - offering = _configMgr.createNetworkOffering(Account.ACCOUNT_ID_SYSTEM,NetworkOffering.DefaultVirtualizedNetworkOffering, "Virtual Vlan", TrafficType.Guest, null, null, false, Availability.Required, GuestIpType.Virtual, null, defaultVirtualNetworkOfferingProviders, true, false); + offering = _configMgr.createNetworkOffering(Account.ACCOUNT_ID_SYSTEM,NetworkOffering.DefaultVirtualizedNetworkOffering, "Virtual Vlan", TrafficType.Guest, null, null, false, Availability.Required, GuestIpType.Virtual, null, defaultVirtualNetworkOfferingProviders, true, false, Network.Type.Isolated); offering.setState(NetworkOffering.State.Enabled); _networkOfferingDao.update(offering.getId(), offering); } if (_networkOfferingDao.findByUniqueName(NetworkOffering.DefaultDirectNetworkOffering) == null) { - offering = _configMgr.createNetworkOffering(Account.ACCOUNT_ID_SYSTEM, NetworkOffering.DefaultDirectNetworkOffering, "Direct", TrafficType.Guest, null, null, true, Availability.Optional, GuestIpType.Direct, null, defaultDirectNetworkOfferingProviders, true, false); + offering = _configMgr.createNetworkOffering(Account.ACCOUNT_ID_SYSTEM, NetworkOffering.DefaultDirectNetworkOffering, "Direct", TrafficType.Guest, null, null, true, Availability.Optional, GuestIpType.Direct, null, defaultDirectNetworkOfferingProviders, true, false, Network.Type.Shared); offering.setState(NetworkOffering.State.Enabled); _networkOfferingDao.update(offering.getId(), offering); } @@ -913,15 +917,15 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag } @Override - public List setupNetwork(Account owner, NetworkOfferingVO offering, DeploymentPlan plan, String name, String displayText, boolean isShared, boolean isDefault) + public List setupNetwork(Account owner, NetworkOfferingVO offering, DeploymentPlan plan, String name, String displayText, boolean isDefault) throws ConcurrentOperationException { - return setupNetwork(owner, offering, null, plan, name, displayText, isShared, isDefault, false, null, null); + return setupNetwork(owner, offering, null, plan, name, displayText, isDefault, false, null, null); } @Override @DB - public List setupNetwork(Account owner, NetworkOfferingVO offering, Network predefined, DeploymentPlan plan, String name, String displayText, boolean isShared, boolean isDefault, - boolean errorIfAlreadySetup, Long domainId, List tags) throws ConcurrentOperationException { + public List setupNetwork(Account owner, NetworkOfferingVO offering, Network predefined, DeploymentPlan plan, String name, String displayText, boolean isDefault, boolean errorIfAlreadySetup, + Long domainId, List tags) throws ConcurrentOperationException { Account locked = _accountDao.acquireInLockTable(owner.getId()); if (locked == null) { throw new ConcurrentOperationException("Unable to acquire lock on " + owner); @@ -980,8 +984,8 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag related = id; } - NetworkVO vo = new NetworkVO(id, network, offering.getId(), plan.getDataCenterId(), guru.getName(), owner.getDomainId(), owner.getId(), related, name, displayText, isShared, isDefault, - predefined.isSecurityGroupEnabled(), (domainId != null), predefined.getNetworkDomain()); + NetworkVO vo = new NetworkVO(id, network, offering.getId(), plan.getDataCenterId(), guru.getName(), owner.getDomainId(), owner.getId(), related, name, displayText, isDefault, + predefined.isSecurityGroupEnabled(), (domainId != null), predefined.getNetworkDomain(), offering.getType()); vo.setTags(tags); networks.add(_networksDao.persist(vo, vo.getGuestType() != null)); @@ -1223,13 +1227,13 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag // If this is a guest virtual network and the network offering does not support a shared source NAT rule, // associate a source NAT IP (if one isn't already associated with the network) - if (network.getGuestType() == GuestIpType.Virtual && !offering.isSharedSourceNatService()) { + if (network.getType() == Network.Type.Isolated && !offering.isSharedSourceNatService()) { List ips = _ipAddressDao.listByAssociatedNetwork(networkId, true); if (ips.isEmpty()) { s_logger.debug("Creating a source nat ip for " + network); Account owner = _accountMgr.getAccount(network.getAccountId()); - PublicIp sourceNatIp = assignSourceNatIpAddress(owner, network, context.getCaller().getId()); + assignSourceNatIpAddress(owner, network, context.getCaller().getId()); } } @@ -1556,7 +1560,6 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag String vlanId = cmd.getVlan(); String name = cmd.getNetworkName(); String displayText = cmd.getDisplayText(); - Boolean isShared = cmd.getIsShared(); Boolean isDefault = cmd.isDefault(); Long userId = UserContext.current().getCallerUserId(); Account caller = UserContext.current().getCaller(); @@ -1574,12 +1577,21 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag if (networkOffering == null || networkOffering.isSystemOnly()) { throw new InvalidParameterValueException("Unable to find network offeirng by id " + networkOfferingId); } + + if (networkOffering.getState() != NetworkOffering.State.Enabled) { + throw new InvalidParameterValueException("Can't use network offering id=" + networkOfferingId + " as its state is not " + NetworkOffering.State.Enabled); + } + + boolean isShared = false; + if (networkOffering.getType() == Network.Type.Shared) { + isShared = true; + } // Check if the network is domain specific if (cmd.getDomainId() != null && cmd.getAccountName() == null) { - if (networkOffering.getTrafficType() != TrafficType.Guest || networkOffering.getGuestType() != GuestIpType.Direct) { - throw new InvalidParameterValueException("Domain level networks are supported just for traffic type " + TrafficType.Guest + " and guest Ip type " + GuestIpType.Direct); - } else if (isShared == null || !isShared) { + if (networkOffering.getTrafficType() != TrafficType.Guest || networkOffering.getType() != Network.Type.Shared) { + throw new InvalidParameterValueException("Domain level networks are supported just for traffic type " + TrafficType.Guest + " and only for type " + Network.Type.Shared); + } else if (!isShared) { throw new InvalidParameterValueException("Network dedicated to domain should be shared"); } else { DomainVO domain = _domainDao.findById(cmd.getDomainId()); @@ -1679,15 +1691,15 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag domainId = cmd.getDomainId(); } - Network network = createNetwork(networkOfferingId, name, displayText, isShared, isDefault, zoneId, gateway, cidr, vlanId, networkDomain, owner, false, domainId, tags); + Network network = createNetwork(networkOfferingId, name, displayText, isDefault, zoneId, gateway, cidr, vlanId, networkDomain, owner, false, domainId, tags); - // Don't pass owner to create vlan when network offering is of type Direct - done to prevent accountVlanMap entry + // Don't pass owner to create vlan when network offering is of type Shared - done to prevent accountVlanMap entry // creation when vlan is mapped to network - if (network.getGuestType() == GuestIpType.Direct) { + if (network.getType() == Network.Type.Shared) { owner = null; } - if (caller.getType() == Account.ACCOUNT_TYPE_ADMIN && network.getGuestType() == GuestIpType.Direct && defineNetworkConfig) { + if (caller.getType() == Account.ACCOUNT_TYPE_ADMIN && network.getType() == Network.Type.Shared && defineNetworkConfig) { // Create vlan ip range _configMgr.createVlanAndPublicIpRange(userId, zoneId, null, startIP, endIP, gateway, netmask, false, vlanId, owner, network.getId()); } @@ -1699,38 +1711,30 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag @Override @DB - public Network createNetwork(long networkOfferingId, String name, String displayText, Boolean isShared, Boolean isDefault, Long zoneId, String gateway, String cidr, String vlanId, - String networkDomain, Account owner, boolean isSecurityGroupEnabled, Long domainId, List tags) throws ConcurrentOperationException, InsufficientCapacityException { + public Network createNetwork(long networkOfferingId, String name, String displayText, Boolean isDefault, Long zoneId, String gateway, String cidr, String vlanId, String networkDomain, + Account owner, boolean isSecurityGroupEnabled, Long domainId, List tags) throws ConcurrentOperationException, InsufficientCapacityException { NetworkOfferingVO networkOffering = _networkOfferingDao.findById(networkOfferingId); DataCenterVO zone = _dcDao.findById(zoneId); - // Only Direct Account specific networks can be created in Advanced Security Group enabled zone - if (zone.isSecurityGroupEnabled() && (networkOffering.getGuestType() == GuestIpType.Virtual || (isShared != null && isShared))) { - throw new InvalidParameterValueException("Virtual Network and Direct Shared Network creation is not allowed if zone is security group enabled"); - } - - if (zone.getNetworkType() == NetworkType.Basic) { - throw new InvalidParameterValueException("Network creation is not allowed in zone with network type " + NetworkType.Basic); - } - - // allow isDefault/isShared to be set only for Direct network - if (networkOffering.getGuestType() == GuestIpType.Virtual) { + // allow isDefault to be set only for Shared network + if (networkOffering.getType() == Network.Type.Isolated) { if (isDefault != null && !isDefault) { throw new InvalidParameterValueException("Can specify isDefault parameter only for Direct network."); } else { isDefault = true; } - if (isShared != null && isShared) { - throw new InvalidParameterValueException("Can specify isShared parameter for Direct networks only"); - } } else { if (isDefault == null) { isDefault = false; } } - // if network is shared, defult its owner to be system + // if network is shared, default its owner to be system + boolean isShared = false; + if (networkOffering.getType() == Network.Type.Shared) { + isShared = true; + } if (isShared) { owner = _accountMgr.getSystemAccount(); } @@ -1824,13 +1828,13 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag } } - List networks = setupNetwork(owner, networkOffering, userNetwork, plan, name, displayText, isShared, isDefault, true, domainId, tags); + List networks = setupNetwork(owner, networkOffering, userNetwork, plan, name, displayText, isDefault, true, domainId, tags); Network network = null; if (networks == null || networks.isEmpty()) { throw new CloudRuntimeException("Fail to create a network"); } else { - if (networks.size() > 0 && networks.get(0).getGuestType() == GuestIpType.Virtual && networks.get(0).getTrafficType() == TrafficType.Guest) { + if (networks.size() > 0 && networks.get(0).getType()== Network.Type.Isolated && networks.get(0).getTrafficType() == TrafficType.Guest) { Network defaultGuestNetwork = networks.get(0); for (Network nw : networks) { if (nw.getCidr() != null && nw.getCidr().equals(zone.getGuestNetworkCidr())) { @@ -2745,7 +2749,7 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag // create new Virtual network for the user if it doesn't exist if (createNetwork) { List offerings = _configMgr.listNetworkOfferings(TrafficType.Guest, false); - network = createNetwork(offerings.get(0).getId(), owner.getAccountName() + "-network", owner.getAccountName() + "-network", false, null, zoneId, null, null, null, null, owner, false, null, null); + network = createNetwork(offerings.get(0).getId(), owner.getAccountName() + "-network", owner.getAccountName() + "-network", null, zoneId, null, null, null, null, owner, false, null, null); if (network == null) { s_logger.warn("Failed to create default Virtual network for the account " + accountId + "in zone " + zoneId); @@ -2957,7 +2961,7 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag for (NetworkVO network : zoneNetworks) { NetworkOfferingVO no = _networkOfferingDao.findById(network.getNetworkOfferingId()); if (!no.isSystemOnly()) { - if (network.getIsShared() || !_networksDao.listBy(accountId, network.getId()).isEmpty()) { + if (network.getType() == Network.Type.Shared || !_networksDao.listBy(accountId, network.getId()).isEmpty()) { if ((guestType == null || guestType == network.getGuestType()) && (isDefault == null || isDefault.booleanValue() == network.isDefault)) { accountNetworks.add(network); } @@ -3013,7 +3017,7 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag public boolean isNetworkAvailableInDomain(long networkId, long domainId) { Long networkDomainId = null; Network network = getNetwork(networkId); - if (!network.getIsShared()) { + if (network.getType() != Network.Type.Shared) { s_logger.trace("Network id=" + networkId + " is not shared"); return false; } @@ -3317,14 +3321,27 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag } @Override - public Map listNetworkOfferingServices(long networkOfferingId) { - Map serviceProviderMap = new HashMap(); + public Map> listNetworkOfferingServices(long networkOfferingId) { + Map> serviceProviderMap = new HashMap>(); List map = _ntwkOfferingSrvcDao.getServices(networkOfferingId); for (NetworkOfferingServiceMapVO instance : map) { - serviceProviderMap.put(instance.getService(), instance.getProvider()); + String service = instance.getService(); + Set providers; + if (serviceProviderMap.containsKey(service)) { + providers = serviceProviderMap.get(service); + } else { + providers = new HashSet(); + } + providers.add(instance.getProvider()); + serviceProviderMap.put(service, providers); } return serviceProviderMap; } + + @Override + public boolean isProviderSupported(long networkOfferingId, Service service, Provider provider){ + return _ntwkOfferingSrvcDao.isProviderSupported(networkOfferingId, service, provider); + } } diff --git a/server/src/com/cloud/network/NetworkVO.java b/server/src/com/cloud/network/NetworkVO.java index 94bc3f003df..4a67c19a43b 100644 --- a/server/src/com/cloud/network/NetworkVO.java +++ b/server/src/com/cloud/network/NetworkVO.java @@ -150,6 +150,10 @@ public class NetworkVO implements Network { @Column(name="tag") @CollectionTable(name="network_tags", joinColumns=@JoinColumn(name="network_id")) List tags; + + @Column(name="type") + @Enumerated(value=EnumType.STRING) + Network.Type type; public NetworkVO() { } @@ -178,8 +182,8 @@ public class NetworkVO implements Network { this.guestType = guestType; } - public NetworkVO(long id, Network that, long offeringId, long dataCenterId, String guruName, long domainId, long accountId, long related, String name, String displayText, Boolean isShared, boolean isDefault, boolean isSecurityGroupEnabled, boolean isDomainSpecific, String networkDomain) { - this(id, that.getTrafficType(), that.getGuestType(), that.getMode(), that.getBroadcastDomainType(), offeringId, dataCenterId, domainId, accountId, related, name, displayText, isShared, isDefault, isDomainSpecific, networkDomain); + public NetworkVO(long id, Network that, long offeringId, long dataCenterId, String guruName, long domainId, long accountId, long related, String name, String displayText, boolean isDefault, boolean isSecurityGroupEnabled, boolean isDomainSpecific, String networkDomain, Type type) { + this(id, that.getTrafficType(), that.getGuestType(), that.getMode(), that.getBroadcastDomainType(), offeringId, dataCenterId, domainId, accountId, related, name, displayText,isDefault, isDomainSpecific, networkDomain, type); this.gateway = that.getGateway(); this.cidr = that.getCidr(); this.broadcastUri = that.getBroadcastUri(); @@ -207,8 +211,9 @@ public class NetworkVO implements Network { * @param isDefault * @param isDomainSpecific * @param networkDomain + * @param type TODO */ - public NetworkVO(long id, TrafficType trafficType, GuestIpType guestType, Mode mode, BroadcastDomainType broadcastDomainType, long networkOfferingId, long dataCenterId, long domainId, long accountId, long related, String name, String displayText, Boolean isShared, boolean isDefault, boolean isDomainSpecific, String networkDomain) { + public NetworkVO(long id, TrafficType trafficType, GuestIpType guestType, Mode mode, BroadcastDomainType broadcastDomainType, long networkOfferingId, long dataCenterId, long domainId, long accountId, long related, String name, String displayText, boolean isDefault, boolean isDomainSpecific, String networkDomain, Type type) { this(trafficType, guestType, mode, broadcastDomainType, networkOfferingId, dataCenterId, State.Allocated); this.domainId = domainId; this.accountId = accountId; @@ -216,10 +221,15 @@ public class NetworkVO implements Network { this.id = id; this.name = name; this.displayText = displayText; - this.isShared = isShared; + if (type == Network.Type.Shared) { + this.isShared = true; + } else if (type == Network.Type.Isolated) { + this.isShared = false; + } this.isDefault = isDefault; this.isDomainSpecific = isDomainSpecific; this.networkDomain = networkDomain; + this.type = type; } @Override @@ -413,11 +423,6 @@ public class NetworkVO implements Network { this.displayText = displayText; } - @Override - public boolean getIsShared() { - return isShared; - } - @Override public boolean isDefault() { return isDefault; @@ -455,6 +460,11 @@ public class NetworkVO implements Network { public boolean isDomainSpecific() { return isDomainSpecific; } + + @Override + public Network.Type getType() { + return type; + } @Override public boolean equals(Object obj) { diff --git a/server/src/com/cloud/network/dao/NetworkDao.java b/server/src/com/cloud/network/dao/NetworkDao.java index 94c2831095b..8f912ff5502 100644 --- a/server/src/com/cloud/network/dao/NetworkDao.java +++ b/server/src/com/cloud/network/dao/NetworkDao.java @@ -64,4 +64,6 @@ public interface NetworkDao extends GenericDao { List listNetworksBy(boolean isShared); List listByZoneIncludingRemoved(long zoneId); + + Long getNetworkCountByOfferingId(long offeringId); } diff --git a/server/src/com/cloud/network/dao/NetworkDaoImpl.java b/server/src/com/cloud/network/dao/NetworkDaoImpl.java index dac59335d41..4ffd6c077ca 100644 --- a/server/src/com/cloud/network/dao/NetworkDaoImpl.java +++ b/server/src/com/cloud/network/dao/NetworkDaoImpl.java @@ -24,6 +24,7 @@ import javax.ejb.Local; import javax.persistence.TableGenerator; import com.cloud.network.Network.GuestIpType; +import com.cloud.network.Network; import com.cloud.network.NetworkAccountDaoImpl; import com.cloud.network.NetworkAccountVO; import com.cloud.network.NetworkDomainVO; @@ -31,13 +32,16 @@ import com.cloud.network.NetworkVO; import com.cloud.network.Networks.BroadcastDomainType; import com.cloud.network.Networks.Mode; import com.cloud.network.Networks.TrafficType; +import com.cloud.storage.dao.VolumeDaoImpl.SumCount; import com.cloud.utils.component.ComponentLocator; import com.cloud.utils.db.DB; import com.cloud.utils.db.GenericDaoBase; +import com.cloud.utils.db.GenericSearchBuilder; import com.cloud.utils.db.JoinBuilder; import com.cloud.utils.db.JoinBuilder.JoinType; import com.cloud.utils.db.SearchBuilder; import com.cloud.utils.db.SearchCriteria; +import com.cloud.utils.db.SearchCriteria.Func; import com.cloud.utils.db.SearchCriteria.Op; import com.cloud.utils.db.SequenceFetcher; import com.cloud.utils.db.Transaction; @@ -51,6 +55,7 @@ public class NetworkDaoImpl extends GenericDaoBase implements N final SearchBuilder AccountNetworkSearch; final SearchBuilder ZoneBroadcastUriSearch; final SearchBuilder ZoneSecurityGroupSearch; + final GenericSearchBuilder CountByOfferingId; NetworkAccountDaoImpl _accountsDao = ComponentLocator.inject(NetworkAccountDaoImpl.class); NetworkDomainDaoImpl _domainsDao = ComponentLocator.inject(NetworkDomainDaoImpl.class); @@ -72,7 +77,7 @@ public class NetworkDaoImpl extends GenericDaoBase implements N AllFieldsSearch.and("account", AllFieldsSearch.entity().getAccountId(), Op.EQ); AllFieldsSearch.and("guesttype", AllFieldsSearch.entity().getGuestType(), Op.EQ); AllFieldsSearch.and("related", AllFieldsSearch.entity().getRelated(), Op.EQ); - AllFieldsSearch.and("isShared", AllFieldsSearch.entity().getIsShared(), Op.EQ); + AllFieldsSearch.and("type", AllFieldsSearch.entity().getType(), Op.EQ); AllFieldsSearch.done(); AccountSearch = createSearchBuilder(); @@ -109,6 +114,12 @@ public class NetworkDaoImpl extends GenericDaoBase implements N ZoneSecurityGroupSearch.and("dataCenterId", ZoneSecurityGroupSearch.entity().getDataCenterId(), Op.EQ); ZoneSecurityGroupSearch.and("securityGroup", ZoneSecurityGroupSearch.entity().isSecurityGroupEnabled(), Op.EQ); ZoneSecurityGroupSearch.done(); + + CountByOfferingId = createSearchBuilder(Long.class); + CountByOfferingId.select(null, Func.COUNT, CountByOfferingId.entity().getId()); + CountByOfferingId.and("offeringId", CountByOfferingId.entity().getNetworkOfferingId(), Op.EQ); + CountByOfferingId.and("removed", CountByOfferingId.entity().getRemoved(), Op.NULL); + CountByOfferingId.done(); _tgMacAddress = _tgs.get("macAddress"); @@ -297,7 +308,12 @@ public class NetworkDaoImpl extends GenericDaoBase implements N @Override public List listNetworksBy(boolean isShared) { SearchCriteria sc = AllFieldsSearch.create(); - sc.setParameters("isShared", isShared); + if (isShared) { + sc.setParameters("type", Network.Type.Shared); + } else { + sc.setParameters("type", Network.Type.Isolated); + } + return listBy(sc); } @@ -307,4 +323,12 @@ public class NetworkDaoImpl extends GenericDaoBase implements N sc.setParameters("dataCenterId", zoneId); return listIncludingRemovedBy(sc); } + + @Override + public Long getNetworkCountByOfferingId(long offeringId) { + SearchCriteria sc = CountByOfferingId.create(); + sc.setParameters("offering", offeringId); + List results = customSearch(sc, null); + return results.get(0); + } } diff --git a/server/src/com/cloud/network/element/CloudZonesNetworkElement.java b/server/src/com/cloud/network/element/CloudZonesNetworkElement.java index f9d778b41eb..824f328f102 100644 --- a/server/src/com/cloud/network/element/CloudZonesNetworkElement.java +++ b/server/src/com/cloud/network/element/CloudZonesNetworkElement.java @@ -63,7 +63,6 @@ import com.cloud.exception.ResourceUnavailableException; import com.cloud.network.Network; import com.cloud.network.NetworkVO; import com.cloud.network.Network.Capability; -import com.cloud.network.Network.GuestIpType; import com.cloud.network.Network.Provider; import com.cloud.network.Network.Service; import com.cloud.network.NetworkManager; @@ -111,7 +110,7 @@ public class CloudZonesNetworkElement extends AdapterBase implements NetworkElem @Inject AgentManager _agentManager; @Inject ServiceOfferingDao _serviceOfferingDao; - private boolean canHandle(GuestIpType ipType, DeployDestination dest, TrafficType trafficType) { + private boolean canHandle(DeployDestination dest, TrafficType trafficType) { DataCenterVO dc = (DataCenterVO)dest.getDataCenter(); if (dc.getDhcpProvider().equalsIgnoreCase(Provider.ExternalDhcpServer.getName())){ @@ -127,7 +126,7 @@ public class CloudZonesNetworkElement extends AdapterBase implements NetworkElem @Override public boolean implement(Network network, NetworkOffering offering, DeployDestination dest, ReservationContext context) throws ResourceUnavailableException, ConcurrentOperationException, InsufficientCapacityException { - if (!canHandle(network.getGuestType(), dest, offering.getTrafficType())) { + if (!canHandle(dest, offering.getTrafficType())) { return false; } @@ -136,7 +135,7 @@ public class CloudZonesNetworkElement extends AdapterBase implements NetworkElem @Override public boolean prepare(Network network, NicProfile nic, VirtualMachineProfile vmProfile, DeployDestination dest, ReservationContext context) throws ConcurrentOperationException, InsufficientCapacityException, ResourceUnavailableException { - if (canHandle(network.getGuestType(), dest, network.getTrafficType())) { + if (canHandle(dest, network.getTrafficType())) { if (vmProfile.getType() != VirtualMachine.Type.User) { return false; diff --git a/server/src/com/cloud/network/element/DhcpElement.java b/server/src/com/cloud/network/element/DhcpElement.java index e9dde7e4127..c1d23b29ba6 100644 --- a/server/src/com/cloud/network/element/DhcpElement.java +++ b/server/src/com/cloud/network/element/DhcpElement.java @@ -27,8 +27,8 @@ import org.apache.log4j.Logger; import com.cloud.configuration.ConfigurationManager; import com.cloud.dc.DataCenter; -import com.cloud.dc.Pod; import com.cloud.dc.DataCenter.NetworkType; +import com.cloud.dc.Pod; import com.cloud.dc.dao.HostPodDao; import com.cloud.deploy.DeployDestination; import com.cloud.exception.ConcurrentOperationException; @@ -37,18 +37,15 @@ import com.cloud.exception.ResourceUnavailableException; import com.cloud.host.dao.HostDao; import com.cloud.network.Network; import com.cloud.network.Network.Capability; -import com.cloud.network.Network.GuestIpType; import com.cloud.network.Network.Provider; import com.cloud.network.Network.Service; +import com.cloud.network.Network.Type; import com.cloud.network.NetworkManager; import com.cloud.network.Networks.TrafficType; -import com.cloud.network.PublicIpAddress; import com.cloud.network.dao.NetworkDao; import com.cloud.network.router.VirtualNetworkApplianceManager; import com.cloud.network.router.VirtualRouter; import com.cloud.network.router.VirtualRouter.Role; -import com.cloud.network.rules.FirewallRule; -import com.cloud.network.rules.StaticNat; import com.cloud.offering.NetworkOffering; import com.cloud.org.Cluster; import com.cloud.user.AccountManager; @@ -83,27 +80,20 @@ public class DhcpElement extends AdapterBase implements PasswordServiceProvider @Inject AccountManager _accountMgr; @Inject HostDao _hostDao; - private boolean canHandle(GuestIpType ipType, DeployDestination dest, TrafficType trafficType) { - DataCenter dc = dest.getDataCenter(); - String provider = dc.getGatewayProvider(); - - if (provider != null && provider.equalsIgnoreCase(Provider.JuniperSRX.getName()) && ipType == GuestIpType.Virtual) { + private boolean canHandle(DeployDestination dest, TrafficType trafficType, Type networkType, long offeringId) { + if (_networkMgr.isProviderSupported(offeringId, Service.Gateway, Provider.JuniperSRX) && networkType == Network.Type.Isolated) { return true; } else if (dest.getPod() != null && dest.getPod().getExternalDhcp()){ //This pod is using external DHCP server return false; } else { - if (dc.getNetworkType() == NetworkType.Basic) { - return (ipType == GuestIpType.Direct && trafficType == TrafficType.Guest); - } else { - return (ipType == GuestIpType.Direct); - } + return (networkType == Network.Type.Shared); } } @Override public boolean implement(Network network, NetworkOffering offering, DeployDestination dest, ReservationContext context) throws ResourceUnavailableException, ConcurrentOperationException, InsufficientCapacityException { - if (!canHandle(network.getGuestType(), dest, offering.getTrafficType())) { + if (!canHandle(dest, offering.getTrafficType(), network.getType(), network.getNetworkOfferingId())) { return false; } @@ -115,7 +105,7 @@ public class DhcpElement extends AdapterBase implements PasswordServiceProvider @Override public boolean prepare(Network network, NicProfile nic, VirtualMachineProfile vm, DeployDestination dest, ReservationContext context) throws ConcurrentOperationException, InsufficientCapacityException, ResourceUnavailableException { - if (canHandle(network.getGuestType(), dest, network.getTrafficType())) { + if (canHandle(dest, network.getTrafficType(), network.getType(), network.getNetworkOfferingId())) { if (vm.getType() != VirtualMachine.Type.User) { return false; @@ -204,7 +194,7 @@ public class DhcpElement extends AdapterBase implements PasswordServiceProvider DeployDestination dest = new DeployDestination(dc, null, null, null); NetworkOffering offering = _configMgr.getNetworkOffering(network.getNetworkOfferingId()); - if (!canHandle(network.getGuestType(), dest, offering.getTrafficType())) { + if (!canHandle(dest, offering.getTrafficType(), network.getType(), network.getNetworkOfferingId())) { s_logger.trace("Dhcp element doesn't handle network restart for the network " + network); return false; } diff --git a/server/src/com/cloud/network/element/ElasticLoadBalancerElement.java b/server/src/com/cloud/network/element/ElasticLoadBalancerElement.java index 2a09a83ada3..3da9c705c62 100644 --- a/server/src/com/cloud/network/element/ElasticLoadBalancerElement.java +++ b/server/src/com/cloud/network/element/ElasticLoadBalancerElement.java @@ -34,15 +34,13 @@ import com.cloud.exception.InsufficientCapacityException; import com.cloud.exception.ResourceUnavailableException; import com.cloud.network.Network; import com.cloud.network.Network.Capability; -import com.cloud.network.Network.Provider; +import com.cloud.network.Network.Provider; import com.cloud.network.Network.Service; import com.cloud.network.NetworkManager; import com.cloud.network.Networks.TrafficType; -import com.cloud.network.PublicIpAddress; import com.cloud.network.dao.NetworkDao; import com.cloud.network.lb.ElasticLoadBalancerManager; import com.cloud.network.rules.FirewallRule; -import com.cloud.network.rules.StaticNat; import com.cloud.offering.NetworkOffering; import com.cloud.offerings.dao.NetworkOfferingDao; import com.cloud.utils.component.AdapterBase; @@ -67,8 +65,8 @@ public class ElasticLoadBalancerElement extends AdapterBase implements FirewallS TrafficType _frontEndTrafficType = TrafficType.Guest; private boolean canHandle(Network network) { - if (network.getGuestType() != Network.GuestIpType.Direct || network.getTrafficType() != TrafficType.Guest) { - s_logger.debug("Not handling network with guest Type " + network.getGuestType() + " and traffic type " + network.getTrafficType()); + if (network.getType() != Network.Type.Shared|| network.getTrafficType() != TrafficType.Guest) { + s_logger.debug("Not handling network with type " + network.getType() + " and traffic type " + network.getTrafficType()); return false; } diff --git a/server/src/com/cloud/network/element/ExternalDhcpElement.java b/server/src/com/cloud/network/element/ExternalDhcpElement.java index 777f4af7b41..3524c04cb66 100644 --- a/server/src/com/cloud/network/element/ExternalDhcpElement.java +++ b/server/src/com/cloud/network/element/ExternalDhcpElement.java @@ -19,7 +19,6 @@ package com.cloud.network.element; -import java.util.List; import java.util.Map; import javax.ejb.Local; @@ -37,18 +36,15 @@ import com.cloud.exception.ResourceUnavailableException; import com.cloud.host.Host; import com.cloud.hypervisor.Hypervisor.HypervisorType; import com.cloud.network.Network; -import com.cloud.network.PublicIpAddress; import com.cloud.network.Network.Capability; import com.cloud.network.Network.GuestIpType; import com.cloud.network.Network.Provider; import com.cloud.network.Network.Service; +import com.cloud.network.Network.Type; import com.cloud.network.Networks.TrafficType; -import com.cloud.network.rules.FirewallRule; -import com.cloud.network.rules.StaticNat; import com.cloud.offering.NetworkOffering; import com.cloud.utils.component.AdapterBase; import com.cloud.utils.component.Inject; -import com.cloud.utils.exception.CloudRuntimeException; import com.cloud.vm.NicProfile; import com.cloud.vm.ReservationContext; import com.cloud.vm.VirtualMachine; @@ -58,12 +54,12 @@ import com.cloud.vm.VirtualMachineProfile; public class ExternalDhcpElement extends AdapterBase implements NetworkElement { private static final Logger s_logger = Logger.getLogger(ExternalDhcpElement.class); @Inject ExternalDhcpManager _dhcpMgr; - private boolean canHandle(GuestIpType ipType, DeployDestination dest, TrafficType trafficType) { + private boolean canHandle(DeployDestination dest, TrafficType trafficType, Type networkType) { DataCenter dc = dest.getDataCenter(); Pod pod = dest.getPod(); if (pod.getExternalDhcp() && dc.getNetworkType() == NetworkType.Basic && trafficType == TrafficType.Guest - && ipType == GuestIpType.Direct) { + && networkType == Network.Type.Shared) { s_logger.debug("External DHCP can handle"); return true; } @@ -84,7 +80,7 @@ public class ExternalDhcpElement extends AdapterBase implements NetworkElement { @Override public boolean implement(Network network, NetworkOffering offering, DeployDestination dest, ReservationContext context) throws ConcurrentOperationException, ResourceUnavailableException, InsufficientCapacityException { - if (!canHandle(network.getGuestType(), dest, offering.getTrafficType())) { + if (!canHandle(dest, offering.getTrafficType(), network.getType())) { return false; } return true; @@ -94,7 +90,7 @@ public class ExternalDhcpElement extends AdapterBase implements NetworkElement { public boolean prepare(Network network, NicProfile nic, VirtualMachineProfile vm, DeployDestination dest, ReservationContext context) throws ConcurrentOperationException, ResourceUnavailableException, InsufficientCapacityException { Host host = dest.getHost(); - if (host.getHypervisorType() == HypervisorType.BareMetal || !canHandle(network.getGuestType(), dest, network.getTrafficType())) { + if (host.getHypervisorType() == HypervisorType.BareMetal || !canHandle(dest, network.getTrafficType(), network.getType())) { //BareMetalElement or DhcpElement handle this return false; } diff --git a/server/src/com/cloud/network/element/ExternalFirewallElement.java b/server/src/com/cloud/network/element/ExternalFirewallElement.java index 07b9a377ec7..f8aa16c6068 100644 --- a/server/src/com/cloud/network/element/ExternalFirewallElement.java +++ b/server/src/com/cloud/network/element/ExternalFirewallElement.java @@ -74,8 +74,8 @@ public class ExternalFirewallElement extends AdapterBase implements SourceNATSer private boolean canHandle(Network config) { DataCenter zone = _configMgr.getZone(config.getDataCenterId()); - if ((zone.getNetworkType() == NetworkType.Advanced && config.getGuestType() != Network.GuestIpType.Virtual) || (zone.getNetworkType() == NetworkType.Basic && config.getGuestType() != Network.GuestIpType.Direct)) { - s_logger.trace("Not handling guest ip type = " + config.getGuestType()); + if ((zone.getNetworkType() == NetworkType.Advanced && config.getType() != Network.Type.Isolated) || (zone.getNetworkType() == NetworkType.Basic && config.getType() != Network.Type.Shared)) { + s_logger.trace("Not handling network type = " + config.getType()); return false; } diff --git a/server/src/com/cloud/network/element/F5ExternalLoadBalancerElement.java b/server/src/com/cloud/network/element/F5ExternalLoadBalancerElement.java index e80ed7f0c73..e2dc5dc2f0f 100644 --- a/server/src/com/cloud/network/element/F5ExternalLoadBalancerElement.java +++ b/server/src/com/cloud/network/element/F5ExternalLoadBalancerElement.java @@ -63,8 +63,8 @@ public class F5ExternalLoadBalancerElement extends AdapterBase implements Firewa private boolean canHandle(Network config) { DataCenter zone = _configMgr.getZone(config.getDataCenterId()); - if (config.getGuestType() != Network.GuestIpType.Virtual || config.getTrafficType() != TrafficType.Guest) { - s_logger.trace("Not handling network with guest Type " + config.getGuestType() + " and traffic type " + config.getTrafficType()); + if (config.getType() != Network.Type.Isolated || config.getTrafficType() != TrafficType.Guest) { + s_logger.trace("Not handling network with Type " + config.getType() + " and traffic type " + config.getTrafficType()); return false; } diff --git a/server/src/com/cloud/network/element/NetscalerExternalLoadBalancerElement.java b/server/src/com/cloud/network/element/NetscalerExternalLoadBalancerElement.java index 287419348fc..2a177f7054b 100644 --- a/server/src/com/cloud/network/element/NetscalerExternalLoadBalancerElement.java +++ b/server/src/com/cloud/network/element/NetscalerExternalLoadBalancerElement.java @@ -63,8 +63,8 @@ public class NetscalerExternalLoadBalancerElement extends AdapterBase implements private boolean canHandle(Network config) { DataCenter zone = _configMgr.getZone(config.getDataCenterId()); - if (config.getGuestType() != Network.GuestIpType.Virtual || config.getTrafficType() != TrafficType.Guest) { - s_logger.trace("Not handling network with guest Type " + config.getGuestType() + " and traffic type " + config.getTrafficType()); + if (config.getType() != Network.Type.Isolated || config.getTrafficType() != TrafficType.Guest) { + s_logger.trace("Not handling network with Type " + config.getType() + " and traffic type " + config.getTrafficType()); return false; } diff --git a/server/src/com/cloud/network/element/RedundantVirtualRouterElement.java b/server/src/com/cloud/network/element/RedundantVirtualRouterElement.java index 21ca386da72..6f63bd1e627 100644 --- a/server/src/com/cloud/network/element/RedundantVirtualRouterElement.java +++ b/server/src/com/cloud/network/element/RedundantVirtualRouterElement.java @@ -8,7 +8,6 @@ import javax.ejb.Local; import org.apache.log4j.Logger; -import com.cloud.dc.DataCenter; import com.cloud.deploy.DeployDestination; import com.cloud.exception.ConcurrentOperationException; import com.cloud.exception.InsufficientCapacityException; @@ -16,9 +15,13 @@ import com.cloud.exception.ResourceUnavailableException; import com.cloud.network.Network; import com.cloud.network.Network.GuestIpType; import com.cloud.network.Network.Provider; +import com.cloud.network.Network.Service; +import com.cloud.network.Network.Type; +import com.cloud.network.NetworkManager; import com.cloud.network.router.VirtualRouter; import com.cloud.offering.NetworkOffering; import com.cloud.uservm.UserVm; +import com.cloud.utils.component.Inject; import com.cloud.vm.DomainRouterVO; import com.cloud.vm.NicProfile; import com.cloud.vm.ReservationContext; @@ -29,9 +32,10 @@ import com.cloud.vm.VirtualMachineProfile; public class RedundantVirtualRouterElement extends VirtualRouterElement { private static final Logger s_logger = Logger.getLogger(RedundantVirtualRouterElement.class); - private boolean canHandle(GuestIpType ipType, DataCenter dc) { - String provider = dc.getGatewayProvider(); - boolean result = (provider != null && ipType == GuestIpType.Virtual && provider.equals(Provider.VirtualRouter.getName())); + @Inject NetworkManager _networkMgr; + + private boolean canHandle(Type networkType, long offeringId) { + boolean result = (networkType == Network.Type.Isolated && _networkMgr.isProviderSupported(offeringId, Service.Gateway, Provider.VirtualRouter)); if (!result) { s_logger.trace("Virtual router element only takes care of guest ip type " + GuestIpType.Virtual + " for provider " + Provider.VirtualRouter.getName()); } @@ -41,7 +45,7 @@ public class RedundantVirtualRouterElement extends VirtualRouterElement { @Override public boolean implement(Network guestConfig, NetworkOffering offering, DeployDestination dest, ReservationContext context) throws ResourceUnavailableException, ConcurrentOperationException, InsufficientCapacityException { - if (!canHandle(guestConfig.getGuestType(), dest.getDataCenter())) { + if (!canHandle(guestConfig.getType(), offering.getId())) { return false; } @@ -56,7 +60,7 @@ public class RedundantVirtualRouterElement extends VirtualRouterElement { @Override public boolean prepare(Network network, NicProfile nic, VirtualMachineProfile vm, DeployDestination dest, ReservationContext context) throws ConcurrentOperationException, InsufficientCapacityException, ResourceUnavailableException { - if (canHandle(network.getGuestType(), dest.getDataCenter())) { + if (canHandle(network.getType(), network.getNetworkOfferingId())) { if (vm.getType() != VirtualMachine.Type.User) { return false; } diff --git a/server/src/com/cloud/network/element/VirtualRouterElement.java b/server/src/com/cloud/network/element/VirtualRouterElement.java index 38b7cd19501..201ca58f20e 100644 --- a/server/src/com/cloud/network/element/VirtualRouterElement.java +++ b/server/src/com/cloud/network/element/VirtualRouterElement.java @@ -35,9 +35,9 @@ import com.cloud.exception.ResourceUnavailableException; import com.cloud.host.dao.HostDao; import com.cloud.network.Network; import com.cloud.network.Network.Capability; -import com.cloud.network.Network.GuestIpType; import com.cloud.network.Network.Provider; import com.cloud.network.Network.Service; +import com.cloud.network.Network.Type; import com.cloud.network.NetworkManager; import com.cloud.network.PublicIpAddress; import com.cloud.network.RemoteAccessVpn; @@ -52,7 +52,6 @@ import com.cloud.network.rules.FirewallRule; import com.cloud.network.rules.RulesManager; import com.cloud.network.rules.StaticNat; import com.cloud.offering.NetworkOffering; -import com.cloud.offerings.NetworkOfferingVO; import com.cloud.offerings.dao.NetworkOfferingDao; import com.cloud.org.Cluster; import com.cloud.uservm.UserVm; @@ -89,18 +88,17 @@ public class VirtualRouterElement extends DhcpElement implements SourceNATServic @Inject HostDao _hostDao; @Inject ConfigurationDao _configDao; - private boolean canHandle(GuestIpType ipType, DataCenter dc) { - String provider = dc.getGatewayProvider(); - boolean result = (provider != null && ipType == GuestIpType.Virtual && provider.equals(Provider.VirtualRouter.getName())); + private boolean canHandle(Type networkType, long offeringId) { + boolean result = (networkType == Network.Type.Isolated && _networkMgr.isProviderSupported(offeringId, Service.Gateway, Provider.VirtualRouter)); if (!result) { - s_logger.trace("Virtual router element only takes care of guest ip type " + GuestIpType.Virtual + " for provider " + Provider.VirtualRouter.getName()); + s_logger.trace("Virtual router element only takes care of type " + Network.Type.Isolated + " for provider " + Provider.VirtualRouter.getName()); } return result; } @Override public boolean implement(Network guestConfig, NetworkOffering offering, DeployDestination dest, ReservationContext context) throws ResourceUnavailableException, ConcurrentOperationException, InsufficientCapacityException { - if (!canHandle(guestConfig.getGuestType(), dest.getDataCenter())) { + if (!canHandle(guestConfig.getType(), offering.getId())) { return false; } @@ -115,7 +113,7 @@ public class VirtualRouterElement extends DhcpElement implements SourceNATServic @Override public boolean prepare(Network network, NicProfile nic, VirtualMachineProfile vm, DeployDestination dest, ReservationContext context) throws ConcurrentOperationException, InsufficientCapacityException, ResourceUnavailableException { - if (canHandle(network.getGuestType(), dest.getDataCenter())) { + if (canHandle(network.getType(), network.getNetworkOfferingId())) { if (vm.getType() != VirtualMachine.Type.User) { return false; } @@ -136,7 +134,7 @@ public class VirtualRouterElement extends DhcpElement implements SourceNATServic @Override public boolean restart(Network network, ReservationContext context, boolean cleanup) throws ConcurrentOperationException, ResourceUnavailableException, InsufficientCapacityException{ DataCenter dc = _configMgr.getZone(network.getDataCenterId()); - if (!canHandle(network.getGuestType(), dc)) { + if (!canHandle(network.getType(), network.getNetworkOfferingId())) { s_logger.trace("Virtual router element doesn't handle network restart for the network " + network); return false; } @@ -182,7 +180,7 @@ public class VirtualRouterElement extends DhcpElement implements SourceNATServic public boolean applyRules(Network config, List rules) throws ResourceUnavailableException { DataCenter dc = _configMgr.getZone(config.getDataCenterId()); - if (canHandle(config.getGuestType(),dc)) { + if (canHandle(config.getType(), config.getNetworkOfferingId())) { List routers = _routerDao.listByNetworkAndRole(config.getId(), Role.DHCP_FIREWALL_LB_PASSWD_USERDATA); 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 " + config.getId()); @@ -211,7 +209,7 @@ public class VirtualRouterElement extends DhcpElement implements SourceNATServic return null; } - if (canHandle(network.getGuestType(),dc)) { + if (canHandle(network.getType(), network.getNetworkOfferingId())) { return _routerMgr.applyVpnUsers(network, users, routers); } else { s_logger.debug("Element " + this.getName() + " doesn't handle applyVpnUsers command"); @@ -229,7 +227,7 @@ public class VirtualRouterElement extends DhcpElement implements SourceNATServic return true; } - if (canHandle(network.getGuestType(),dc)) { + if (canHandle(network.getType(), network.getNetworkOfferingId())) { return _routerMgr.startRemoteAccessVpn(network, vpn, routers); } else { s_logger.debug("Element " + this.getName() + " doesn't handle createVpn command"); @@ -247,7 +245,7 @@ public class VirtualRouterElement extends DhcpElement implements SourceNATServic return true; } - if (canHandle(network.getGuestType(),dc)) { + if (canHandle(network.getType(), network.getNetworkOfferingId())) { return _routerMgr.deleteRemoteAccessVpn(network, vpn, routers); } else { s_logger.debug("Element " + this.getName() + " doesn't handle removeVpn command"); @@ -258,7 +256,7 @@ public class VirtualRouterElement extends DhcpElement implements SourceNATServic @Override public boolean applyIps(Network network, List ipAddress) throws ResourceUnavailableException { DataCenter dc = _configMgr.getZone(network.getDataCenterId()); - if (canHandle(network.getGuestType(),dc)) { + if (canHandle(network.getType(), network.getNetworkOfferingId())) { List routers = _routerDao.listByNetworkAndRole(network.getId(), Role.DHCP_FIREWALL_LB_PASSWD_USERDATA); if (routers == null || routers.isEmpty()) { @@ -322,7 +320,7 @@ public class VirtualRouterElement extends DhcpElement implements SourceNATServic @Override public boolean applyStaticNats(Network config, List rules) throws ResourceUnavailableException { DataCenter dc = _configMgr.getZone(config.getDataCenterId()); - if (canHandle(config.getGuestType(),dc)) { + if (canHandle(config.getType(), config.getNetworkOfferingId())) { List routers = _routerDao.listByNetworkAndRole(config.getId(), Role.DHCP_FIREWALL_LB_PASSWD_USERDATA); if (routers == null || routers.isEmpty()) { s_logger.debug("Virtual router elemnt doesn't need to apply static nat on the backend; virtual router doesn't exist in the network " + config.getId()); diff --git a/server/src/com/cloud/network/guru/DirectNetworkGuru.java b/server/src/com/cloud/network/guru/DirectNetworkGuru.java index a942c3ea935..e6f31cdb5b1 100644 --- a/server/src/com/cloud/network/guru/DirectNetworkGuru.java +++ b/server/src/com/cloud/network/guru/DirectNetworkGuru.java @@ -34,7 +34,6 @@ import com.cloud.exception.InsufficientVirtualNetworkCapcityException; import com.cloud.exception.InvalidParameterValueException; import com.cloud.network.IPAddressVO; import com.cloud.network.Network; -import com.cloud.network.Network.GuestIpType; import com.cloud.network.Network.State; import com.cloud.network.NetworkManager; import com.cloud.network.NetworkProfile; @@ -76,8 +75,9 @@ public class DirectNetworkGuru extends AdapterBase implements NetworkGuru { protected boolean canHandle(NetworkOffering offering, DataCenter dc) { // this guru handles only non-system network with guestIpType = Direct - if (dc.getNetworkType() == NetworkType.Advanced && offering.getGuestType() == GuestIpType.Direct && offering.getTrafficType() == TrafficType.Guest) { - if (dc.isSecurityGroupEnabled()) { + //TODO - after broadCastDomainType + physical network are introduced, don't rely on network type of the dc + if (dc.getNetworkType() == NetworkType.Advanced && offering.getType() == Network.Type.Shared && offering.getTrafficType() == TrafficType.Guest) { + if (offering.isSecurityGroupEnabled()) { return true; } else if (!offering.isSystemOnly()) { return true; diff --git a/server/src/com/cloud/network/guru/PublicNetworkGuru.java b/server/src/com/cloud/network/guru/PublicNetworkGuru.java index b896256afff..150be147b98 100644 --- a/server/src/com/cloud/network/guru/PublicNetworkGuru.java +++ b/server/src/com/cloud/network/guru/PublicNetworkGuru.java @@ -26,7 +26,6 @@ import javax.ejb.Local; import org.apache.log4j.Logger; import com.cloud.dc.DataCenter; -import com.cloud.dc.DataCenter.NetworkType; import com.cloud.dc.Vlan.VlanType; import com.cloud.dc.dao.DataCenterDao; import com.cloud.dc.dao.VlanDao; @@ -78,7 +77,7 @@ public class PublicNetworkGuru extends AdapterBase implements NetworkGuru { NetworkOfferingDao _networkOfferingDao; protected boolean canHandle(NetworkOffering offering, DataCenter dc) { - if (((dc.getNetworkType() == NetworkType.Advanced && !dc.isSecurityGroupEnabled()) || dc.getNetworkType() == NetworkType.Basic) && offering.getTrafficType() == TrafficType.Public && offering.isSystemOnly()) { + if (!offering.isSecurityGroupEnabled() && offering.getTrafficType() == TrafficType.Public && offering.isSystemOnly()) { return true; } else { s_logger.trace("We only take care of System only Public Virtual Network"); diff --git a/server/src/com/cloud/network/lb/ElasticLoadBalancerManagerImpl.java b/server/src/com/cloud/network/lb/ElasticLoadBalancerManagerImpl.java index 6f60a310959..cd0a385e2a7 100644 --- a/server/src/com/cloud/network/lb/ElasticLoadBalancerManagerImpl.java +++ b/server/src/com/cloud/network/lb/ElasticLoadBalancerManagerImpl.java @@ -461,7 +461,7 @@ public class ElasticLoadBalancerManagerImpl implements try { NetworkOffering offering = _networkOfferingDao.findByIdIncludingRemoved(guestNetwork.getNetworkOfferingId()); - if (offering.isSystemOnly() || guestNetwork.getIsShared()) { + if (offering.isSystemOnly() || guestNetwork.getType() == Network.Type.Shared) { owner = _accountService.getSystemAccount(); } @@ -486,7 +486,7 @@ public class ElasticLoadBalancerManagerImpl implements List offerings = _networkMgr.getSystemAccountNetworkOfferings(NetworkOfferingVO.SystemControlNetwork); NetworkOfferingVO controlOffering = offerings.get(0); - NetworkVO controlConfig = _networkMgr.setupNetwork(_systemAcct, controlOffering, plan, null, null, false, false).get(0); + NetworkVO controlConfig = _networkMgr.setupNetwork(_systemAcct, controlOffering, plan, null, null, false).get(0); List> networks = new ArrayList>(2); NicProfile guestNic = new NicProfile(); @@ -613,8 +613,8 @@ public class ElasticLoadBalancerManagerImpl implements NetworkVO network=_networkDao.findById(networkId); - if (network.getGuestType() != GuestIpType.Direct) { - s_logger.info("ELB: not handling guest traffic of type " + network.getGuestType()); + if (network.getType() != Network.Type.Shared) { + s_logger.info("ELB: not handling traffic for network of type " + network.getType()); return null; } return network; diff --git a/server/src/com/cloud/network/router/VirtualNetworkApplianceManagerImpl.java b/server/src/com/cloud/network/router/VirtualNetworkApplianceManagerImpl.java index 96d0c720693..c1a70f1c911 100755 --- a/server/src/com/cloud/network/router/VirtualNetworkApplianceManagerImpl.java +++ b/server/src/com/cloud/network/router/VirtualNetworkApplianceManagerImpl.java @@ -1063,11 +1063,11 @@ public class VirtualNetworkApplianceManagerImpl implements VirtualNetworkApplian List offerings = _networkMgr.getSystemAccountNetworkOfferings(NetworkOfferingVO.SystemControlNetwork); NetworkOfferingVO controlOffering = offerings.get(0); - NetworkVO controlConfig = _networkMgr.setupNetwork(_systemAcct, controlOffering, plan, null, null, false, false).get(0); + NetworkVO controlConfig = _networkMgr.setupNetwork(_systemAcct, controlOffering, plan, null, null, false).get(0); List> networks = new ArrayList>(3); NetworkOfferingVO publicOffering = _networkMgr.getSystemAccountNetworkOfferings(NetworkOfferingVO.SystemPublicNetwork).get(0); - List publicNetworks = _networkMgr.setupNetwork(_systemAcct, publicOffering, plan, null, null, false, false); + List publicNetworks = _networkMgr.setupNetwork(_systemAcct, publicOffering, plan, null, null, false); networks.add(new Pair(publicNetworks.get(0), defaultNic)); NicProfile gatewayNic = new NicProfile(); if (isRedundant) { @@ -1253,7 +1253,7 @@ public class VirtualNetworkApplianceManagerImpl implements VirtualNetworkApplian List offerings = _networkMgr.getSystemAccountNetworkOfferings(NetworkOfferingVO.SystemControlNetwork); NetworkOfferingVO controlOffering = offerings.get(0); - NetworkVO controlConfig = _networkMgr.setupNetwork(_systemAcct, controlOffering, plan, null, null, false, false).get(0); + NetworkVO controlConfig = _networkMgr.setupNetwork(_systemAcct, controlOffering, plan, null, null, false).get(0); List> networks = new ArrayList>(3); @@ -1304,7 +1304,7 @@ public class VirtualNetworkApplianceManagerImpl implements VirtualNetworkApplian public List deployDhcp(Network guestNetwork, DeployDestination dest, Account owner, Map params) throws InsufficientCapacityException, StorageUnavailableException, ConcurrentOperationException, ResourceUnavailableException { NetworkOffering offering = _networkOfferingDao.findByIdIncludingRemoved(guestNetwork.getNetworkOfferingId()); - if (offering.isSystemOnly() || guestNetwork.getIsShared()) { + if (offering.isSystemOnly() || guestNetwork.getType() == Network.Type.Shared) { owner = _accountMgr.getAccount(Account.ACCOUNT_ID_SYSTEM); } @@ -1461,11 +1461,11 @@ public class VirtualNetworkApplianceManagerImpl implements VirtualNetworkApplian buf.append(" dnssearchorder=").append(domain_suffix); } - if (!network.isDefault() && network.getGuestType() == GuestIpType.Direct) { + if (!network.isDefault() && network.getType() == Network.Type.Shared) { buf.append(" defaultroute=false"); String virtualNetworkElementNicIP = _networkMgr.getIpOfNetworkElementInVirtualNetwork(network.getAccountId(), network.getDataCenterId()); - if (!network.getIsShared() && virtualNetworkElementNicIP != null) { + if (network.getType() != Network.Type.Shared && virtualNetworkElementNicIP != null) { defaultDns1 = virtualNetworkElementNicIP; } else { s_logger.debug("No Virtual network found for account id=" + network.getAccountId() + " so setting dns to the dns of the network id=" + network.getId()); @@ -1908,7 +1908,7 @@ public class VirtualNetworkApplianceManagerImpl implements VirtualNetworkApplian if (cmds.size() > 0) { boolean podLevelException = false; //for user vm in Basic zone we should try to re-deploy vm in a diff pod if it fails to deploy in original pod; so throwing exception with Pod scope - if (isZoneBasic && podId != null && profile.getVirtualMachine().getType() == VirtualMachine.Type.User && network.getTrafficType() == TrafficType.Guest && network.getGuestType() == GuestIpType.Direct) { + if (isZoneBasic && podId != null && profile.getVirtualMachine().getType() == VirtualMachine.Type.User && network.getTrafficType() == TrafficType.Guest && network.getType() == Network.Type.Shared) { podLevelException = true; } try { diff --git a/server/src/com/cloud/offerings/NetworkOfferingVO.java b/server/src/com/cloud/offerings/NetworkOfferingVO.java index fab3211db65..6b09cc52de6 100644 --- a/server/src/com/cloud/offerings/NetworkOfferingVO.java +++ b/server/src/com/cloud/offerings/NetworkOfferingVO.java @@ -28,8 +28,8 @@ import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.Table; +import com.cloud.network.Network; import com.cloud.network.Network.GuestIpType; -import com.cloud.network.Network.State; import com.cloud.network.Networks.TrafficType; import com.cloud.offering.NetworkOffering; import com.cloud.utils.db.GenericDao; @@ -100,6 +100,10 @@ public class NetworkOfferingVO implements NetworkOffering { @Column(name="is_security_group_enabled") boolean securityGroupEnabled; + @Column(name="type") + @Enumerated(value=EnumType.STRING) + Network.Type type; + @Override public String getDisplayText() { return displayText; @@ -216,8 +220,18 @@ public class NetworkOfferingVO implements NetworkOffering { public State getState() { return state; } + + @Override + public void setSecurityGroupEnabled(boolean securityGroupEnabled) { + this.securityGroupEnabled = securityGroupEnabled; + } + + @Override + public Network.Type getType() { + return type; + } - public NetworkOfferingVO(String name, String displayText, TrafficType trafficType, boolean systemOnly, boolean specifyVlan, Integer rateMbps, Integer multicastRateMbps, Integer concurrentConnections, boolean isDefault, Availability availability, GuestIpType guestIpType, String tags, boolean isSecurityGroupEnabled) { + public NetworkOfferingVO(String name, String displayText, TrafficType trafficType, boolean systemOnly, boolean specifyVlan, Integer rateMbps, Integer multicastRateMbps, Integer concurrentConnections, boolean isDefault, Availability availability, GuestIpType guestIpType, String tags, boolean isSecurityGroupEnabled, Network.Type type) { this.name = name; this.displayText = displayText; this.rateMbps = rateMbps; @@ -232,6 +246,7 @@ public class NetworkOfferingVO implements NetworkOffering { this.tags = tags; this.guestType = guestIpType; this.securityGroupEnabled = isSecurityGroupEnabled; + this.type = type; } public NetworkOfferingVO() { @@ -243,7 +258,7 @@ public class NetworkOfferingVO implements NetworkOffering { * @param trafficType */ public NetworkOfferingVO(String name, TrafficType trafficType) { - this(name, "System Offering for " + name, trafficType, true, false, 0, 0, null, true, Availability.Required, null, null, false); + this(name, "System Offering for " + name, trafficType, true, false, 0, 0, null, true, Availability.Required, null, null, false, null); this.state = State.Enabled; } diff --git a/server/src/com/cloud/offerings/dao/NetworkOfferingServiceMapDao.java b/server/src/com/cloud/offerings/dao/NetworkOfferingServiceMapDao.java index f835f8b2d16..323ce374d1e 100644 --- a/server/src/com/cloud/offerings/dao/NetworkOfferingServiceMapDao.java +++ b/server/src/com/cloud/offerings/dao/NetworkOfferingServiceMapDao.java @@ -35,6 +35,7 @@ public interface NetworkOfferingServiceMapDao extends GenericDao getServicesForProvider(long networkOfferingId, Provider provider); List getProvidersForService(long networkOfferingid, Service service); List getServices(long networkOfferingId); + void deleteByOfferingId(long networkOfferingId); } diff --git a/server/src/com/cloud/offerings/dao/NetworkOfferingServiceMapDaoImpl.java b/server/src/com/cloud/offerings/dao/NetworkOfferingServiceMapDaoImpl.java index d990b53e0fc..5aa825bc9f1 100644 --- a/server/src/com/cloud/offerings/dao/NetworkOfferingServiceMapDaoImpl.java +++ b/server/src/com/cloud/offerings/dao/NetworkOfferingServiceMapDaoImpl.java @@ -112,4 +112,11 @@ public class NetworkOfferingServiceMapDaoImpl extends GenericDaoBase sc = AllFieldsSearch.create(); + sc.setParameters("networkOfferingId", networkOfferingId); + remove(sc); + } } diff --git a/server/src/com/cloud/server/ConfigurationServerImpl.java b/server/src/com/cloud/server/ConfigurationServerImpl.java index 649eba8b4fa..e32158e7ce9 100644 --- a/server/src/com/cloud/server/ConfigurationServerImpl.java +++ b/server/src/com/cloud/server/ConfigurationServerImpl.java @@ -852,7 +852,7 @@ public class ConfigurationServerImpl implements ConfigurationServer { "System-Guest-Network", TrafficType.Guest, false, false, null, null, null, true, - Availability.Optional, GuestIpType.Direct, null, true); + Availability.Optional, GuestIpType.Direct, null, true, Network.Type.Shared); guestNetworkOffering.setState(NetworkOffering.State.Enabled); @@ -869,7 +869,7 @@ public class ConfigurationServerImpl implements ConfigurationServer { "Virtual Vlan", TrafficType.Guest, false, false, null, null, null, true, - Availability.Required, GuestIpType.Virtual, null, false); + Availability.Required, GuestIpType.Virtual, null, false, Network.Type.Isolated); defaultGuestNetworkOffering.setState(NetworkOffering.State.Enabled); defaultGuestNetworkOffering = _networkOfferingDao.persistDefaultNetworkOffering(defaultGuestNetworkOffering); @@ -886,7 +886,7 @@ public class ConfigurationServerImpl implements ConfigurationServer { "Direct", TrafficType.Guest, false, true, null, null, null, true, - Availability.Optional, GuestIpType.Direct, null, false); + Availability.Optional, GuestIpType.Direct, null, false, Network.Type.Shared); defaultGuestDirectNetworkOffering.setState(NetworkOffering.State.Enabled); defaultGuestDirectNetworkOffering = _networkOfferingDao.persistDefaultNetworkOffering(defaultGuestDirectNetworkOffering); @@ -953,7 +953,7 @@ public class ConfigurationServerImpl implements ConfigurationServer { } if (broadcastDomainType != null) { - NetworkVO network = new NetworkVO(id, trafficType, null, mode, broadcastDomainType, networkOfferingId, zoneId, domainId, accountId, related, null, null, true, isNetworkDefault, false, networkDomain); + NetworkVO network = new NetworkVO(id, trafficType, null, mode, broadcastDomainType, networkOfferingId, zoneId, domainId, accountId, related, null, null, isNetworkDefault, false, networkDomain, Network.Type.Shared); network.setGuruName(guruNames.get(network.getTrafficType())); network.setDns1(zone.getDns1()); network.setDns2(zone.getDns2()); diff --git a/server/src/com/cloud/storage/secondary/SecondaryStorageManagerImpl.java b/server/src/com/cloud/storage/secondary/SecondaryStorageManagerImpl.java index d18aecf8c28..b042e574533 100644 --- a/server/src/com/cloud/storage/secondary/SecondaryStorageManagerImpl.java +++ b/server/src/com/cloud/storage/secondary/SecondaryStorageManagerImpl.java @@ -504,9 +504,9 @@ public class SecondaryStorageManagerImpl implements SecondaryStorageVmManager, V defaultNic.setDefaultNic(true); defaultNic.setDeviceId(2); try { - networks.add(new Pair(_networkMgr.setupNetwork(systemAcct, defaultOffering.get(0), plan, null, null, false, false).get(0), defaultNic)); + networks.add(new Pair(_networkMgr.setupNetwork(systemAcct, defaultOffering.get(0), plan, null, null, false).get(0), defaultNic)); for (NetworkOfferingVO offering : offerings) { - networks.add(new Pair(_networkMgr.setupNetwork(systemAcct, offering, plan, null, null, false, false).get(0), null)); + networks.add(new Pair(_networkMgr.setupNetwork(systemAcct, offering, plan, null, null, false).get(0), null)); } } catch (ConcurrentOperationException e) { s_logger.info("Unable to setup due to concurrent operation. " + e); diff --git a/server/src/com/cloud/vm/UserVmManagerImpl.java b/server/src/com/cloud/vm/UserVmManagerImpl.java index 8880c8d2254..f30c8f97377 100755 --- a/server/src/com/cloud/vm/UserVmManagerImpl.java +++ b/server/src/com/cloud/vm/UserVmManagerImpl.java @@ -2096,12 +2096,12 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, Manager throw new InvalidParameterValueException("Can't create a vm with multiple networks one of which is Security Group enabled"); } - if (network.getTrafficType() != TrafficType.Guest || network.getGuestType() != GuestIpType.Direct || (network.getIsShared() && !network.isSecurityGroupEnabled())) { + if (network.getTrafficType() != TrafficType.Guest || network.getType() != Network.Type.Shared || (network.getType() == Network.Type.Shared && !network.isSecurityGroupEnabled())) { throw new InvalidParameterValueException("Can specify only Direct Guest Account specific networks when deploy vm in Security Group enabled zone"); } // Perform account permission check - if (!network.getIsShared()) { + if (network.getType() != Network.Type.Shared) { // Check account permissions List networkMap = _networkDao.listBy(owner.getId(), network.getId()); if (networkMap == null || networkMap.isEmpty()) { @@ -2177,8 +2177,8 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, Manager if (virtualNetworks.isEmpty()) { s_logger.debug("Creating default Virtual network for account " + owner + " as a part of deployVM process"); - Network newNetwork = _networkMgr.createNetwork(defaultVirtualOffering.get(0).getId(), owner.getAccountName() + "-network", owner.getAccountName() + "-network", false, null, - zone.getId(), null, null, null, null, owner, false, null, null); + Network newNetwork = _networkMgr.createNetwork(defaultVirtualOffering.get(0).getId(), owner.getAccountName() + "-network", owner.getAccountName() + "-network", null, zone.getId(), + null, null, null, null, owner, false, null, null); defaultNetwork = _networkDao.findById(newNetwork.getId()); } else if (virtualNetworks.size() > 1) { throw new InvalidParameterValueException("More than 1 default Virtaul networks are found for account " + owner + "; please specify networkIds"); @@ -2190,8 +2190,8 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, Manager if (defaultNetworks.isEmpty()) { if (defaultVirtualOffering.get(0).getAvailability() == Availability.Optional) { s_logger.debug("Creating default Virtual network for account " + owner + " as a part of deployVM process"); - Network newNetwork = _networkMgr.createNetwork(defaultVirtualOffering.get(0).getId(), owner.getAccountName() + "-network", owner.getAccountName() + "-network", false, null, - zone.getId(), null, null, null, null, owner, false, null, null); + Network newNetwork = _networkMgr.createNetwork(defaultVirtualOffering.get(0).getId(), owner.getAccountName() + "-network", owner.getAccountName() + "-network", null, zone.getId(), + null, null, null, null, owner, false, null, null); defaultNetwork = _networkDao.findById(newNetwork.getId()); } else { throw new InvalidParameterValueException("Unable to find default networks for account " + owner); @@ -2231,7 +2231,7 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, Manager } // Perform account permission check - if (!network.getIsShared()) { + if (network.getType() != Network.Type.Shared) { List networkMap = _networkDao.listBy(owner.getId(), network.getId()); if (networkMap == null || networkMap.isEmpty()) { throw new PermissionDeniedException("Unable to create a vm using network with id " + network.getId() + ", permission denied"); @@ -3324,7 +3324,7 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, Manager for (NetworkVO network : zoneNetworks) { // get the default networks for the account NetworkOfferingVO no = _networkOfferingDao.findById(network.getNetworkOfferingId()); if (!no.isSystemOnly()) { - if (network.getIsShared() || !_networkDao.listBy(oldAccount.getId(), network.getId()).isEmpty()) { + if (network.getType() == Network.Type.Shared || !_networkDao.listBy(oldAccount.getId(), network.getId()).isEmpty()) { if (network.isDefault()) { oldNetworks.add(network); } @@ -3335,8 +3335,8 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, Manager long networkOffering = oldNet.getNetworkOfferingId(); List virtualNetworks = _networkMgr.listNetworksForAccount(newAccount.getId(), zone.getId(), GuestIpType.Virtual, true); if (virtualNetworks.isEmpty()) { - Network newNetwork = _networkMgr.createNetwork(networkOffering, newAccount.getAccountName() + "-network", newAccount.getAccountName() + "-network", false, null, - vm.getDataCenterIdToDeployIn(), null, null, null, null, newAccount, false, null, null); + Network newNetwork = _networkMgr.createNetwork(networkOffering, newAccount.getAccountName() + "-network", newAccount.getAccountName() + "-network", null, vm.getDataCenterIdToDeployIn(), + null, null, null, null, newAccount, false, null, null); defaultNetwork = _networkDao.findById(newNetwork.getId()); } else if (virtualNetworks.size() > 1) { throw new InvalidParameterValueException("More than 1 default Virtaul networks are found for account " + newAccount + "; please specify networkIds"); diff --git a/server/test/com/cloud/network/MockNetworkManagerImpl.java b/server/test/com/cloud/network/MockNetworkManagerImpl.java index fa661458be1..5e1f5bb6a0e 100644 --- a/server/test/com/cloud/network/MockNetworkManagerImpl.java +++ b/server/test/com/cloud/network/MockNetworkManagerImpl.java @@ -9,7 +9,6 @@ import javax.naming.ConfigurationException; import com.cloud.api.commands.AssociateIPAddrCmd; import com.cloud.api.commands.CreateNetworkCmd; import com.cloud.api.commands.ListNetworksCmd; -import com.cloud.api.commands.RestartNetworkCmd; import com.cloud.dc.Vlan; import com.cloud.dc.Vlan.VlanType; import com.cloud.deploy.DeployDestination; @@ -27,8 +26,6 @@ import com.cloud.network.addr.PublicIp; import com.cloud.network.guru.NetworkGuru; import com.cloud.network.rules.FirewallRule; import com.cloud.network.rules.StaticNat; -import com.cloud.network.vpn.PasswordResetElement; -import com.cloud.network.vpn.RemoteAccessVpnElement; import com.cloud.offering.NetworkOffering; import com.cloud.offerings.NetworkOfferingVO; import com.cloud.user.Account; @@ -93,12 +90,6 @@ public class MockNetworkManagerImpl implements NetworkManager, Manager, NetworkS return false; } - @Override - public boolean restartNetwork(RestartNetworkCmd cmd) throws ConcurrentOperationException, ResourceUnavailableException, InsufficientCapacityException { - // TODO Auto-generated method stub - return false; - } - @Override public int getActiveNicsInNetwork(long networkId) { // TODO Auto-generated method stub @@ -202,15 +193,15 @@ public class MockNetworkManagerImpl implements NetworkManager, Manager, NetworkS } @Override - public List setupNetwork(Account owner, NetworkOfferingVO offering, DeploymentPlan plan, String name, String displayText, boolean isShared, boolean isDefault) + public List setupNetwork(Account owner, NetworkOfferingVO offering, DeploymentPlan plan, String name, String displayText, boolean isDefault) throws ConcurrentOperationException { // TODO Auto-generated method stub return null; } @Override - public List setupNetwork(Account owner, NetworkOfferingVO offering, Network predefined, DeploymentPlan plan, String name, String displayText, boolean isShared, boolean isDefault, - boolean errorIfAlreadySetup, Long domainId, List tags) throws ConcurrentOperationException { + public List setupNetwork(Account owner, NetworkOfferingVO offering, Network predefined, DeploymentPlan plan, String name, String displayText, boolean isDefault, boolean errorIfAlreadySetup, + Long domainId, List tags) throws ConcurrentOperationException { // TODO Auto-generated method stub return null; } @@ -344,8 +335,8 @@ public class MockNetworkManagerImpl implements NetworkManager, Manager, NetworkS } @Override - public Network createNetwork(long networkOfferingId, String name, String displayText, Boolean isShared, Boolean isDefault, Long zoneId, String gateway, String cidr, String vlanId, - String networkDomain, Account owner, boolean isSecurityGroupEnabled, Long domainId, List tags) throws ConcurrentOperationException, InsufficientCapacityException { + public Network createNetwork(long networkOfferingId, String name, String displayText, Boolean isDefault, Long zoneId, String gateway, String cidr, String vlanId, String networkDomain, + Account owner, boolean isSecurityGroupEnabled, Long domainId, List tags) throws ConcurrentOperationException, InsufficientCapacityException { // TODO Auto-generated method stub return null; } @@ -387,12 +378,6 @@ public class MockNetworkManagerImpl implements NetworkManager, Manager, NetworkS return null; } - @Override - public List getPasswordResetElements() { - // TODO Auto-generated method stub - return null; - } - @Override public boolean zoneIsConfiguredForExternalNetworking(long zoneId) { // TODO Auto-generated method stub @@ -453,12 +438,6 @@ public class MockNetworkManagerImpl implements NetworkManager, Manager, NetworkS return null; } - @Override - public List getRemoteAccessVpnElements() { - // TODO Auto-generated method stub - return null; - } - @Override public String acquireGuestIpAddress(Network network, String requestedIp) { // TODO Auto-generated method stub diff --git a/server/test/com/cloud/network/dao/NetworkDaoTest.java b/server/test/com/cloud/network/dao/NetworkDaoTest.java index b7ad959bb68..81b95246319 100644 --- a/server/test/com/cloud/network/dao/NetworkDaoTest.java +++ b/server/test/com/cloud/network/dao/NetworkDaoTest.java @@ -19,7 +19,7 @@ public class NetworkDaoTest extends TestCase { NetworkDaoImpl dao = ComponentLocator.inject(NetworkDaoImpl.class); dao.expunge(1001l); - NetworkVO network = new NetworkVO(1001, TrafficType.Control, GuestIpType.Direct, Mode.Dhcp, BroadcastDomainType.Native, 1, 1, 1, 1, 1001, "Name", "DisplayText", false, true, true, null); + NetworkVO network = new NetworkVO(1001, TrafficType.Control, GuestIpType.Direct, Mode.Dhcp, BroadcastDomainType.Native, 1, 1, 1, 1, 1001, "Name", "DisplayText", false, true, true, null, null); network.setGuruName("guru_name"); List tags = new ArrayList(); diff --git a/setup/db/create-schema.sql b/setup/db/create-schema.sql index 98dbcb495b5..b38ca8ae320 100755 --- a/setup/db/create-schema.sql +++ b/setup/db/create-schema.sql @@ -187,6 +187,7 @@ CREATE TABLE `cloud`.`networks` ( `created` datetime NOT NULL COMMENT 'date created', `removed` datetime COMMENT 'date removed if not null', `is_security_group_enabled` tinyint NOT NULL DEFAULT 0 COMMENT '1: enabled, 0: not', + `type` char(32) COMMENT 'type of the network, can be Shared or Isolated', PRIMARY KEY (`id`), CONSTRAINT `fk_networks__network_offering_id` FOREIGN KEY (`network_offering_id`) REFERENCES `network_offerings`(`id`), CONSTRAINT `fk_networks__data_center_id` FOREIGN KEY (`data_center_id`) REFERENCES `data_center`(`id`) ON DELETE CASCADE, @@ -264,6 +265,7 @@ CREATE TABLE `cloud`.`network_offerings` ( `guest_type` char(32) COMMENT 'guest ip type of network offering', `is_security_group_enabled` tinyint NOT NULL DEFAULT 0 COMMENT '1: enabled, 0: not', `state` char(32) COMMENT 'state of the network offering; has Disabled value by default', + `type` char(32) COMMENT 'type of the network offering, can be Shared or Isolated', PRIMARY KEY (`id`), INDEX `i_network_offerings__system_only`(`system_only`), INDEX `i_network_offerings__removed`(`removed`) From 4cb9e309902c40d24963146a9bc3b7f8b1a10626 Mon Sep 17 00:00:00 2001 From: alena Date: Fri, 14 Oct 2011 11:36:41 -0700 Subject: [PATCH 009/159] Network offering upgrade implementation --- .../com/cloud/api/commands/DeployVMCmd.java | 8 -- .../cloud/api/commands/UpdateNetworkCmd.java | 2 +- .../com/cloud/network/NetworkManagerImpl.java | 82 +++++++++++++++---- .../guru/DirectPodBasedNetworkGuru.java | 3 +- .../guru/ExternalGuestNetworkGuru.java | 1 - .../cloud/offerings/NetworkOfferingVO.java | 2 + 6 files changed, 70 insertions(+), 28 deletions(-) diff --git a/api/src/com/cloud/api/commands/DeployVMCmd.java b/api/src/com/cloud/api/commands/DeployVMCmd.java index 2d86dbcb759..9803f4fcaa5 100644 --- a/api/src/com/cloud/api/commands/DeployVMCmd.java +++ b/api/src/com/cloud/api/commands/DeployVMCmd.java @@ -230,14 +230,6 @@ public class DeployVMCmd extends BaseAsyncCreateCmd { return hostId; } - private String getIpAddress() { - return ipAddress; - } - - private String getKeyboard() { - return keyboard; - } - private Map getIpToNetworkMap() { if ((networkIds != null || ipAddress != null) && ipToNetworkList != null) { throw new InvalidParameterValueException("NetworkIds and ipAddress can't be specified along with ipToNetworkMap parameter"); diff --git a/api/src/com/cloud/api/commands/UpdateNetworkCmd.java b/api/src/com/cloud/api/commands/UpdateNetworkCmd.java index 142beb1c383..a431de207f7 100644 --- a/api/src/com/cloud/api/commands/UpdateNetworkCmd.java +++ b/api/src/com/cloud/api/commands/UpdateNetworkCmd.java @@ -60,7 +60,7 @@ public class UpdateNetworkCmd extends BaseAsyncCmd { @Parameter(name=ApiConstants.NETWORK_DOMAIN, type=CommandType.STRING, description="network domain") private String networkDomain; - @Parameter(name=ApiConstants.NETWORK_OFFERING_ID, type=CommandType.LONG, description="network offering ID") + @Parameter(name=ApiConstants.NETWORK_OFFERING_ID, type=CommandType.LONG, description="network offering ID - upgrade network to the new network offering") private Long networkOfferingId; ///////////////////////////////////////////////////// diff --git a/server/src/com/cloud/network/NetworkManagerImpl.java b/server/src/com/cloud/network/NetworkManagerImpl.java index 5de0ecf2b54..d7e003502f2 100755 --- a/server/src/com/cloud/network/NetworkManagerImpl.java +++ b/server/src/com/cloud/network/NetworkManagerImpl.java @@ -147,7 +147,6 @@ import com.cloud.utils.db.Transaction; import com.cloud.utils.exception.CloudRuntimeException; import com.cloud.utils.net.Ip; import com.cloud.utils.net.NetUtils; -import com.cloud.vm.DomainRouterVO; import com.cloud.vm.Nic; import com.cloud.vm.NicProfile; import com.cloud.vm.NicVO; @@ -3071,9 +3070,9 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag } _accountMgr.checkAccess(caller, null, network); - // Don't allow to update system network - make an exception for the Guest network in Basic zone + // Don't allow to update system network NetworkOffering offering = _networkOfferingDao.findByIdIncludingRemoved(network.getNetworkOfferingId()); - if (offering.isSystemOnly() && network.getTrafficType() != TrafficType.Guest) { + if (offering.isSystemOnly()) { throw new InvalidParameterValueException("Can't update system networks"); } @@ -3093,12 +3092,9 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag throw new InvalidParameterValueException("Domain name change is not supported for network id=" + network.getNetworkOfferingId() + " in zone id=" + network.getDataCenterId()); } - //restart network if it has active network elements - List routers = _routerDao.listActive(networkId); - if (!routers.isEmpty()) { - restartNetwork = true; - } network.setNetworkDomain(domainSuffix); + //have to restart the network + restartNetwork = true; } if (name != null) { @@ -3119,15 +3115,19 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag if (networkOffering == null || networkOffering.isSystemOnly()) { throw new InvalidParameterValueException("Unable to find network offering by id " + networkOfferingId); } - if (networkOffering.getAvailability() == Availability.Unavailable) { - throw new InvalidParameterValueException("Can't update network; network offering id=" + networkOfferingId + " is " + networkOffering.getAvailability()); + if (networkOffering.getAvailability() == Availability.Unavailable || networkOffering.getState() == NetworkOffering.State.Disabled || networkOffering.getState() == NetworkOffering.State.Inactive) { + throw new InvalidParameterValueException("Can't update network; network offering id=" + networkOfferingId + " is " + networkOffering.getAvailability() + " and " + networkOffering.getState()); } - network.setNetworkOfferingId(networkOfferingId); - } - - if ((networkOfferingId != 0) && (networkOfferingId != oldNetworkOfferingId)) { - restartNetwork = true; - } + + if (networkOfferingId != oldNetworkOfferingId) { + //check if the network is upgradable + if (!canUpgrade(oldNetworkOfferingId, networkOfferingId)) { + throw new InvalidParameterValueException("Can't upgrade from network offering " + oldNetworkOfferingId + " to " + networkOfferingId + "; check logs for more information"); + } + network.setNetworkOfferingId(networkOfferingId); + restartNetwork = true; + } + } boolean success = _networksDao.update(networkId, network); @@ -3344,4 +3344,54 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag public boolean isProviderSupported(long networkOfferingId, Service service, Provider provider){ return _ntwkOfferingSrvcDao.isProviderSupported(networkOfferingId, service, provider); } + + protected boolean canUpgrade(long oldNetworkOfferingId, long newNetworkOfferingId) { + NetworkOffering oldNetworkOffering = _networkOfferingDao.findByIdIncludingRemoved(oldNetworkOfferingId); + NetworkOffering newNetworkOffering = _networkOfferingDao.findById(newNetworkOfferingId); + + //security group property should be the same + if (oldNetworkOffering.isSecurityGroupEnabled() != newNetworkOffering.isSecurityGroupEnabled()) { + s_logger.debug("Offerings " + newNetworkOfferingId + " and " + oldNetworkOfferingId + " have different securityGroupProperty, can't upgrade"); + return false; + } + + //Type of the network should be the same + if (oldNetworkOffering.getType() != newNetworkOffering.getType()){ + s_logger.debug("Network offerings " + newNetworkOfferingId + " and " + oldNetworkOfferingId + " are of different types, can't upgrade"); + return false; + } + + //Traffic types should be the same + if (oldNetworkOffering.getTrafficType() != newNetworkOffering.getTrafficType()) { + s_logger.debug("Network offerings " + newNetworkOfferingId + " and " + oldNetworkOfferingId + " have different traffic types, can't upgrade"); + return false; + } + + //list of services and providers should be the same + Map> newServices = listNetworkOfferingServices(newNetworkOfferingId); + Map> oldServices = listNetworkOfferingServices(oldNetworkOfferingId); + + if (newServices.size() != oldServices.size()) { + s_logger.debug("Number of supported services is not the same for offering " + newNetworkOfferingId + " and " + oldNetworkOfferingId); + return false; + } + + for (String service : newServices.keySet()) { + Set newProviders = newServices.get(service); + Set oldProviders = oldServices.get(service); + if (newProviders.size() != oldProviders.size()) { + s_logger.debug("Number of providers for the service " + service + " is not the same for offering " + newNetworkOfferingId + " and " + oldNetworkOfferingId); + return false; + } + + for (String provider : newProviders) { + if (!oldProviders.contains(provider)) { + s_logger.debug("Providers are different for the " + service + " is not the same for offering " + newNetworkOfferingId + " and " + oldNetworkOfferingId); + return false; + } + } + } + + return true; + } } diff --git a/server/src/com/cloud/network/guru/DirectPodBasedNetworkGuru.java b/server/src/com/cloud/network/guru/DirectPodBasedNetworkGuru.java index a7ee89f211f..4c8fd1daac2 100644 --- a/server/src/com/cloud/network/guru/DirectPodBasedNetworkGuru.java +++ b/server/src/com/cloud/network/guru/DirectPodBasedNetworkGuru.java @@ -19,7 +19,6 @@ package com.cloud.network.guru; import java.net.URI; -import java.util.List; import javax.ejb.Local; @@ -80,7 +79,7 @@ public class DirectPodBasedNetworkGuru extends DirectNetworkGuru { @Override protected boolean canHandle(NetworkOffering offering, DataCenter dc) { // this guru handles system Direct pod based network - if (dc.getNetworkType() == NetworkType.Basic && offering.getTrafficType() == TrafficType.Guest && offering.isSystemOnly()) { + if (dc.getNetworkType() == NetworkType.Basic && offering.getTrafficType() == TrafficType.Guest && offering.isSecurityGroupEnabled()) { return true; } else { s_logger.trace("We only take care of Guest Direct Pod based networks"); diff --git a/server/src/com/cloud/network/guru/ExternalGuestNetworkGuru.java b/server/src/com/cloud/network/guru/ExternalGuestNetworkGuru.java index 9e16c53eada..b2e91f71f83 100644 --- a/server/src/com/cloud/network/guru/ExternalGuestNetworkGuru.java +++ b/server/src/com/cloud/network/guru/ExternalGuestNetworkGuru.java @@ -246,7 +246,6 @@ public class ExternalGuestNetworkGuru extends GuestNetworkGuru { } else { super.reserve(nic, config, vm, dest, context); } - } @Override diff --git a/server/src/com/cloud/offerings/NetworkOfferingVO.java b/server/src/com/cloud/offerings/NetworkOfferingVO.java index 6b09cc52de6..27823837b3f 100644 --- a/server/src/com/cloud/offerings/NetworkOfferingVO.java +++ b/server/src/com/cloud/offerings/NetworkOfferingVO.java @@ -30,6 +30,7 @@ import javax.persistence.Table; import com.cloud.network.Network; import com.cloud.network.Network.GuestIpType; +import com.cloud.network.Network.Type; import com.cloud.network.Networks.TrafficType; import com.cloud.offering.NetworkOffering; import com.cloud.utils.db.GenericDao; @@ -260,6 +261,7 @@ public class NetworkOfferingVO implements NetworkOffering { public NetworkOfferingVO(String name, TrafficType trafficType) { this(name, "System Offering for " + name, trafficType, true, false, 0, 0, null, true, Availability.Required, null, null, false, null); this.state = State.Enabled; + this.type = Type.Shared; } @Override From ceda05298e6389c01c62bdc8360facd82324b867 Mon Sep 17 00:00:00 2001 From: alena Date: Wed, 19 Oct 2011 16:38:39 -0700 Subject: [PATCH 010/159] Deprecate guestIpType in networkOffering api. Use type (Shared/Isolated) instead --- .../cloud/api/commands/CreateNetworkCmd.java | 8 +++- .../commands/CreateNetworkOfferingCmd.java | 23 +++++++--- .../cloud/api/response/NetworkResponse.java | 1 - api/src/com/cloud/network/Network.java | 3 +- api/src/com/cloud/network/NetworkProfile.java | 7 +++ .../src/com/cloud/api/ApiResponseHelper.java | 5 +-- .../configuration/ConfigurationManager.java | 4 +- .../ConfigurationManagerImpl.java | 23 +++------- .../consoleproxy/ConsoleProxyManagerImpl.java | 4 +- .../src/com/cloud/network/NetworkManager.java | 6 +-- .../com/cloud/network/NetworkManagerImpl.java | 44 ++++++++----------- server/src/com/cloud/network/NetworkVO.java | 20 +++++---- .../lb/ElasticLoadBalancerManagerImpl.java | 2 +- .../VirtualNetworkApplianceManagerImpl.java | 6 +-- .../cloud/offerings/NetworkOfferingVO.java | 10 +++-- .../cloud/server/ConfigurationServerImpl.java | 9 ++-- .../SecondaryStorageManagerImpl.java | 4 +- .../src/com/cloud/vm/UserVmManagerImpl.java | 6 +-- .../cloud/network/MockNetworkManagerImpl.java | 43 ++++++++++++++++-- 19 files changed, 136 insertions(+), 92 deletions(-) diff --git a/api/src/com/cloud/api/commands/CreateNetworkCmd.java b/api/src/com/cloud/api/commands/CreateNetworkCmd.java index d3df5426941..273b23f0979 100644 --- a/api/src/com/cloud/api/commands/CreateNetworkCmd.java +++ b/api/src/com/cloud/api/commands/CreateNetworkCmd.java @@ -85,6 +85,9 @@ public class CreateNetworkCmd extends BaseCmd { @Parameter(name=ApiConstants.NETWORK_DOMAIN, type=CommandType.STRING, description="network domain") private String networkDomain; + @Parameter(name=ApiConstants.IS_SHARED, type=CommandType.BOOLEAN, description="true is network is shared across accounts in the Zone") + private Boolean isShared; + @Parameter(name=ApiConstants.TAGS, type=CommandType.LIST, collectionType=CommandType.STRING, description="Tag the network") private List tags; @@ -151,10 +154,13 @@ public class CreateNetworkCmd extends BaseCmd { return projectId; } + public Boolean getIsShared() { + return isShared == null ? false : isShared; + } + ///////////////////////////////////////////////////// /////////////// API Implementation/////////////////// ///////////////////////////////////////////////////// - @Override public String getCommandName() { return s_name; diff --git a/api/src/com/cloud/api/commands/CreateNetworkOfferingCmd.java b/api/src/com/cloud/api/commands/CreateNetworkOfferingCmd.java index 4636b9d0c27..5ff1018f685 100644 --- a/api/src/com/cloud/api/commands/CreateNetworkOfferingCmd.java +++ b/api/src/com/cloud/api/commands/CreateNetworkOfferingCmd.java @@ -33,6 +33,7 @@ import com.cloud.api.Implementation; import com.cloud.api.Parameter; import com.cloud.api.ServerApiException; import com.cloud.api.response.NetworkOfferingResponse; +import com.cloud.network.Network.GuestIpType; import com.cloud.offering.NetworkOffering; import com.cloud.offering.NetworkOffering.Availability; import com.cloud.user.Account; @@ -55,7 +56,9 @@ public class CreateNetworkOfferingCmd extends BaseCmd { @Parameter(name=ApiConstants.TRAFFIC_TYPE, type=CommandType.STRING, required=true, description="the traffic type for the network offering, supported types are Public, Management, Control, Guest, Vlan or Storage.") private String traffictype; - @Parameter(name=ApiConstants.GUEST_IP_TYPE, type=CommandType.STRING, required=true, description="the guest ip type for the network offering, supported types are Direct and Virtual.") + @Deprecated + //this parameter is deprecated, we have to use "type" parameter instead + @Parameter(name=ApiConstants.GUEST_IP_TYPE, type=CommandType.STRING, description="the guest ip type for the network offering, supported types are Direct and Virtual.") private String guestIpType; @Parameter(name=ApiConstants.MAX_CONNECTIONS, type=CommandType.INTEGER, description="maximum number of concurrent connections supported by the network offering") @@ -142,10 +145,6 @@ public class CreateNetworkOfferingCmd extends BaseCmd { return networkRate; } - public String getGuestIpType() { - return guestIpType; - } - public static String getName() { return _name; } @@ -187,7 +186,19 @@ public class CreateNetworkOfferingCmd extends BaseCmd { } public String getType() { - return type; + if (type != null) { + return type; + } + + if (guestIpType != null) { + // Verify guest ip type + for (GuestIpType gType : GuestIpType.values()) { + if (gType.name().equalsIgnoreCase(guestIpType)) { + return guestIpType; + } + } + } + return null; } public Map> getServiceProviders() { diff --git a/api/src/com/cloud/api/response/NetworkResponse.java b/api/src/com/cloud/api/response/NetworkResponse.java index f4f4a272551..f998cfc706b 100644 --- a/api/src/com/cloud/api/response/NetworkResponse.java +++ b/api/src/com/cloud/api/response/NetworkResponse.java @@ -69,7 +69,6 @@ public class NetworkResponse extends BaseResponse implements ControlledEntityRes @SerializedName("networkofferingavailability") @Param(description="availability of the network offering the network is created from") private String networkOfferingAvailability; - @Deprecated @SerializedName(ApiConstants.IS_SHARED) @Param(description="true if network is shared, false otherwise") private Boolean isShared; diff --git a/api/src/com/cloud/network/Network.java b/api/src/com/cloud/network/Network.java index b13c8683744..14d333dd7a5 100644 --- a/api/src/com/cloud/network/Network.java +++ b/api/src/com/cloud/network/Network.java @@ -263,5 +263,6 @@ public interface Network extends ControlledEntity { List getTags(); Type getType(); - + + boolean getIsShared(); } diff --git a/api/src/com/cloud/network/NetworkProfile.java b/api/src/com/cloud/network/NetworkProfile.java index c03435f1472..2360058801c 100644 --- a/api/src/com/cloud/network/NetworkProfile.java +++ b/api/src/com/cloud/network/NetworkProfile.java @@ -51,6 +51,7 @@ public class NetworkProfile implements Network { private List tags; private Network.Type type; private GuestIpType guestIpType; + private boolean isShared; public NetworkProfile(Network network) { this.id = network.getId(); @@ -74,6 +75,7 @@ public class NetworkProfile implements Network { this.isSecurityGroupEnabled = network.isSecurityGroupEnabled(); this.type = network.getType(); this.guestIpType = network.getGuestType(); + this.isShared = network.getIsShared(); } @Override @@ -205,4 +207,9 @@ public class NetworkProfile implements Network { public Network.Type getType(){ return type; } + + @Override + public boolean getIsShared() { + return isShared; + } } diff --git a/server/src/com/cloud/api/ApiResponseHelper.java b/server/src/com/cloud/api/ApiResponseHelper.java index e49dabaa923..58818fb0b53 100755 --- a/server/src/com/cloud/api/ApiResponseHelper.java +++ b/server/src/com/cloud/api/ApiResponseHelper.java @@ -2189,9 +2189,8 @@ public class ApiResponseHelper implements ResponseGenerator { response.setNetworkOfferingAvailability(networkOffering.getAvailability().toString()); } - if (network.getType() != null && network.getType() == Network.Type.Shared) { - response.setIsShared(true); - } + response.setIsShared(network.getIsShared()); + response.setIsDefault(network.isDefault()); response.setState(network.getState().toString()); response.setRelated(network.getRelated()); diff --git a/server/src/com/cloud/configuration/ConfigurationManager.java b/server/src/com/cloud/configuration/ConfigurationManager.java index add65a754bb..4627f4eed20 100644 --- a/server/src/com/cloud/configuration/ConfigurationManager.java +++ b/server/src/com/cloud/configuration/ConfigurationManager.java @@ -33,7 +33,6 @@ import com.cloud.exception.InsufficientCapacityException; import com.cloud.exception.InvalidParameterValueException; import com.cloud.exception.PermissionDeniedException; import com.cloud.network.Network; -import com.cloud.network.Network.GuestIpType; import com.cloud.network.Network.Provider; import com.cloud.network.Network.Service; import com.cloud.network.Networks.TrafficType; @@ -176,7 +175,6 @@ public interface ConfigurationManager extends ConfigurationService, Manager { * @param trafficType * @param tags * @param maxConnections - * @param guestIpType TODO * @param networkRate TODO * @param serviceProviderMap TODO * @param isDefault TODO @@ -187,7 +185,7 @@ public interface ConfigurationManager extends ConfigurationService, Manager { * @return network offering object */ - NetworkOfferingVO createNetworkOffering(long userId, String name, String displayText, TrafficType trafficType, String tags, Integer maxConnections, boolean specifyVlan, Availability availability, GuestIpType guestIpType, Integer networkRate, Map> serviceProviderMap, boolean isDefault, boolean isSecurityGroupEnabled, Network.Type type); + NetworkOfferingVO createNetworkOffering(long userId, String name, String displayText, TrafficType trafficType, String tags, Integer maxConnections, boolean specifyVlan, Availability availability, Integer networkRate, Map> serviceProviderMap, boolean isDefault, boolean isSecurityGroupEnabled, Network.Type type); Vlan createVlanAndPublicIpRange(Long userId, Long zoneId, Long podId, String startIP, String endIP, String vlanGateway, String vlanNetmask, boolean forVirtualNetwork, String vlanId, Account account, Long networkId) throws InsufficientCapacityException, ConcurrentOperationException, InvalidParameterValueException; diff --git a/server/src/com/cloud/configuration/ConfigurationManagerImpl.java b/server/src/com/cloud/configuration/ConfigurationManagerImpl.java index c26c4a5e5b1..379c5e643ee 100755 --- a/server/src/com/cloud/configuration/ConfigurationManagerImpl.java +++ b/server/src/com/cloud/configuration/ConfigurationManagerImpl.java @@ -1525,7 +1525,7 @@ public class ConfigurationManagerImpl implements ConfigurationManager, Configura } userNetwork.setBroadcastDomainType(broadcastDomainType); userNetwork.setNetworkDomain(networkDomain); - _networkMgr.setupNetwork(systemAccount, offering, userNetwork, plan, null, null, isNetworkDefault, false, null, null); + _networkMgr.setupNetwork(systemAccount, offering, userNetwork, plan, null, null, isNetworkDefault, false, null, null, true); } } } @@ -2846,13 +2846,11 @@ public class ConfigurationManagerImpl implements ConfigurationManager, Configura String trafficTypeString = cmd.getTraffictype(); Boolean specifyVlan = cmd.getSpecifyVlan(); String availabilityStr = cmd.getAvailability(); - String guestIpTypeString = cmd.getGuestIpType(); Boolean isSecurityGroupEnabled = cmd.getSecurityGroupEnabled(); Integer networkRate = cmd.getNetworkRate(); TrafficType trafficType = null; - GuestIpType guestIpType = null; Availability availability = null; Network.Type type = null; @@ -2867,17 +2865,6 @@ public class ConfigurationManagerImpl implements ConfigurationManager, Configura throw new InvalidParameterValueException("Invalid value for traffictype. Supported traffic types: Public, Management, Control, Guest, Vlan or Storage"); } - // Verify guest ip type - for (GuestIpType gType : GuestIpType.values()) { - if (gType.name().equalsIgnoreCase(guestIpTypeString)) { - guestIpType = gType; - break; - } - } - - if (guestIpType == null) { - throw new InvalidParameterValueException("Invalid guest IP type; can have Direct or Virtual value"); - } //Verify offering type for (Network.Type offType : Network.Type.values()) { @@ -2888,7 +2875,7 @@ public class ConfigurationManagerImpl implements ConfigurationManager, Configura } if (type == null) { - throw new InvalidParameterValueException("Invalid type is given; can have Shared and Isolated values"); + throw new InvalidParameterValueException("Invalid \"type\" parameter is given; can have Shared and Isolated values"); } // Verify availability @@ -2965,19 +2952,19 @@ public class ConfigurationManagerImpl implements ConfigurationManager, Configura } } - return createNetworkOffering(userId, name, displayText, trafficType, tags, maxConnections, specifyVlan, availability, guestIpType, networkRate, serviceProviderMap, false, isSecurityGroupEnabled, type); + return createNetworkOffering(userId, name, displayText, trafficType, tags, maxConnections, specifyVlan, availability, networkRate, serviceProviderMap, false, isSecurityGroupEnabled, type); } @Override @DB public NetworkOfferingVO createNetworkOffering(long userId, String name, String displayText, TrafficType trafficType, String tags, Integer maxConnections, boolean specifyVlan, - Availability availability, GuestIpType guestIpType, Integer networkRate, Map> serviceProviderMap, boolean isDefault, boolean isSecurityGroupEnabled, Network.Type type) { + Availability availability, Integer networkRate, Map> serviceProviderMap, boolean isDefault, boolean isSecurityGroupEnabled, Network.Type type) { String multicastRateStr = _configDao.getValue("multicast.throttling.rate"); int multicastRate = ((multicastRateStr == null) ? 10 : Integer.parseInt(multicastRateStr)); tags = cleanupTags(tags); - NetworkOfferingVO offering = new NetworkOfferingVO(name, displayText, trafficType, false, specifyVlan, networkRate, multicastRate, maxConnections, isDefault, availability,guestIpType, tags, isSecurityGroupEnabled, type); + NetworkOfferingVO offering = new NetworkOfferingVO(name, displayText, trafficType, false, specifyVlan, networkRate, multicastRate, maxConnections, isDefault, availability, tags, isSecurityGroupEnabled, type); Transaction txn = Transaction.currentTxn(); txn.start(); diff --git a/server/src/com/cloud/consoleproxy/ConsoleProxyManagerImpl.java b/server/src/com/cloud/consoleproxy/ConsoleProxyManagerImpl.java index 2d9285fc4ad..b155abf42b3 100644 --- a/server/src/com/cloud/consoleproxy/ConsoleProxyManagerImpl.java +++ b/server/src/com/cloud/consoleproxy/ConsoleProxyManagerImpl.java @@ -558,9 +558,9 @@ public class ConsoleProxyManagerImpl implements ConsoleProxyManager, ConsoleProx NicProfile defaultNic = new NicProfile(); defaultNic.setDefaultNic(true); defaultNic.setDeviceId(2); - networks.add(new Pair(_networkMgr.setupNetwork(systemAcct, defaultOffering.get(0), plan, null, null, false).get(0), defaultNic)); + networks.add(new Pair(_networkMgr.setupNetwork(systemAcct, defaultOffering.get(0), plan, null, null, false, false).get(0), defaultNic)); for (NetworkOfferingVO offering : offerings) { - networks.add(new Pair(_networkMgr.setupNetwork(systemAcct, offering, plan, null, null, false).get(0), null)); + networks.add(new Pair(_networkMgr.setupNetwork(systemAcct, offering, plan, null, null, false, false).get(0), null)); } VMTemplateVO template = _templateDao.findSystemVMTemplate(dataCenterId, desiredHyp); diff --git a/server/src/com/cloud/network/NetworkManager.java b/server/src/com/cloud/network/NetworkManager.java index d9438c3de08..13e1add9adb 100644 --- a/server/src/com/cloud/network/NetworkManager.java +++ b/server/src/com/cloud/network/NetworkManager.java @@ -108,11 +108,11 @@ public interface NetworkManager extends NetworkService { */ List listPublicIpAddressesInVirtualNetwork(long accountId, long dcId, Boolean sourceNat, Long associatedNetworkId); - List setupNetwork(Account owner, NetworkOfferingVO offering, DeploymentPlan plan, String name, String displayText, boolean isDefault) + List setupNetwork(Account owner, NetworkOfferingVO offering, DeploymentPlan plan, String name, String displayText, boolean isDefault, boolean isShared) throws ConcurrentOperationException; List setupNetwork(Account owner, NetworkOfferingVO offering, Network predefined, DeploymentPlan plan, String name, String displayText, boolean isDefault, boolean errorIfAlreadySetup, - Long domainId, List tags) throws ConcurrentOperationException; + Long domainId, List tags, boolean isShared) throws ConcurrentOperationException; List getSystemAccountNetworkOfferings(String... offeringNames); @@ -161,7 +161,7 @@ public interface NetworkManager extends NetworkService { boolean destroyNetwork(long networkId, ReservationContext context); Network createNetwork(long networkOfferingId, String name, String displayText, Boolean isDefault, Long zoneId, String gateway, String cidr, String vlanId, String networkDomain, Account owner, - boolean isSecurityGroupEnabled, Long domainId, List tags) throws ConcurrentOperationException, InsufficientCapacityException; + boolean isSecurityGroupEnabled, Long domainId, List tags, Boolean isShared) throws ConcurrentOperationException, InsufficientCapacityException; /** * @throws InsufficientCapacityException diff --git a/server/src/com/cloud/network/NetworkManagerImpl.java b/server/src/com/cloud/network/NetworkManagerImpl.java index d7e003502f2..210c159e114 100755 --- a/server/src/com/cloud/network/NetworkManagerImpl.java +++ b/server/src/com/cloud/network/NetworkManagerImpl.java @@ -806,19 +806,19 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag //check that offering already exists NetworkOfferingVO offering = null; if (_networkOfferingDao.findByUniqueName(NetworkOffering.SystemGuestNetwork) == null) { - offering = _configMgr.createNetworkOffering(Account.ACCOUNT_ID_SYSTEM, NetworkOffering.SystemGuestNetwork, "System Offering for System-Guest-Network", TrafficType.Guest, null, null, false, Availability.Optional, GuestIpType.Direct, null, defaultDirectNetworkOfferingProviders, true, true, Network.Type.Shared); + offering = _configMgr.createNetworkOffering(Account.ACCOUNT_ID_SYSTEM, NetworkOffering.SystemGuestNetwork, "System Offering for System-Guest-Network", TrafficType.Guest, null, null, false, Availability.Optional, null, defaultDirectNetworkOfferingProviders, true, true, Network.Type.Shared); offering.setState(NetworkOffering.State.Enabled); _networkOfferingDao.update(offering.getId(), offering); } if (_networkOfferingDao.findByUniqueName(NetworkOffering.DefaultVirtualizedNetworkOffering) == null) { - offering = _configMgr.createNetworkOffering(Account.ACCOUNT_ID_SYSTEM,NetworkOffering.DefaultVirtualizedNetworkOffering, "Virtual Vlan", TrafficType.Guest, null, null, false, Availability.Required, GuestIpType.Virtual, null, defaultVirtualNetworkOfferingProviders, true, false, Network.Type.Isolated); + offering = _configMgr.createNetworkOffering(Account.ACCOUNT_ID_SYSTEM,NetworkOffering.DefaultVirtualizedNetworkOffering, "Virtual Vlan", TrafficType.Guest, null, null, false, Availability.Required, null, defaultVirtualNetworkOfferingProviders, true, false, Network.Type.Isolated); offering.setState(NetworkOffering.State.Enabled); _networkOfferingDao.update(offering.getId(), offering); } if (_networkOfferingDao.findByUniqueName(NetworkOffering.DefaultDirectNetworkOffering) == null) { - offering = _configMgr.createNetworkOffering(Account.ACCOUNT_ID_SYSTEM, NetworkOffering.DefaultDirectNetworkOffering, "Direct", TrafficType.Guest, null, null, true, Availability.Optional, GuestIpType.Direct, null, defaultDirectNetworkOfferingProviders, true, false, Network.Type.Shared); + offering = _configMgr.createNetworkOffering(Account.ACCOUNT_ID_SYSTEM, NetworkOffering.DefaultDirectNetworkOffering, "Direct", TrafficType.Guest, null, null, true, Availability.Optional, null, defaultDirectNetworkOfferingProviders, true, false, Network.Type.Shared); offering.setState(NetworkOffering.State.Enabled); _networkOfferingDao.update(offering.getId(), offering); } @@ -916,15 +916,15 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag } @Override - public List setupNetwork(Account owner, NetworkOfferingVO offering, DeploymentPlan plan, String name, String displayText, boolean isDefault) + public List setupNetwork(Account owner, NetworkOfferingVO offering, DeploymentPlan plan, String name, String displayText, boolean isDefault, boolean isShared) throws ConcurrentOperationException { - return setupNetwork(owner, offering, null, plan, name, displayText, isDefault, false, null, null); + return setupNetwork(owner, offering, null, plan, name, displayText, isDefault, false, null, null, isShared); } @Override @DB public List setupNetwork(Account owner, NetworkOfferingVO offering, Network predefined, DeploymentPlan plan, String name, String displayText, boolean isDefault, boolean errorIfAlreadySetup, - Long domainId, List tags) throws ConcurrentOperationException { + Long domainId, List tags, boolean isShared) throws ConcurrentOperationException { Account locked = _accountDao.acquireInLockTable(owner.getId()); if (locked == null) { throw new ConcurrentOperationException("Unable to acquire lock on " + owner); @@ -984,7 +984,7 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag } NetworkVO vo = new NetworkVO(id, network, offering.getId(), plan.getDataCenterId(), guru.getName(), owner.getDomainId(), owner.getId(), related, name, displayText, isDefault, - predefined.isSecurityGroupEnabled(), (domainId != null), predefined.getNetworkDomain(), offering.getType()); + predefined.isSecurityGroupEnabled(), (domainId != null), predefined.getNetworkDomain(), offering.getType(), isShared); vo.setTags(tags); networks.add(_networksDao.persist(vo, vo.getGuestType() != null)); @@ -1564,6 +1564,7 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag Account caller = UserContext.current().getCaller(); List tags = cmd.getTags(); boolean isDomainSpecific = false; + Boolean isShared = cmd.getIsShared(); if (tags != null && tags.size() > 1) { throw new InvalidParameterException("Only one tag can be specified for a network at this time"); @@ -1580,17 +1581,12 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag if (networkOffering.getState() != NetworkOffering.State.Enabled) { throw new InvalidParameterValueException("Can't use network offering id=" + networkOfferingId + " as its state is not " + NetworkOffering.State.Enabled); } - - boolean isShared = false; - if (networkOffering.getType() == Network.Type.Shared) { - isShared = true; - } // Check if the network is domain specific if (cmd.getDomainId() != null && cmd.getAccountName() == null) { if (networkOffering.getTrafficType() != TrafficType.Guest || networkOffering.getType() != Network.Type.Shared) { - throw new InvalidParameterValueException("Domain level networks are supported just for traffic type " + TrafficType.Guest + " and only for type " + Network.Type.Shared); - } else if (!isShared) { + throw new InvalidParameterValueException("Domain level networks are supported just for traffic type " + TrafficType.Guest + " and type " + Network.Type.Shared); + } else if (isShared == null || !isShared) { throw new InvalidParameterValueException("Network dedicated to domain should be shared"); } else { DomainVO domain = _domainDao.findById(cmd.getDomainId()); @@ -1690,7 +1686,7 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag domainId = cmd.getDomainId(); } - Network network = createNetwork(networkOfferingId, name, displayText, isDefault, zoneId, gateway, cidr, vlanId, networkDomain, owner, false, domainId, tags); + Network network = createNetwork(networkOfferingId, name, displayText, isDefault, zoneId, gateway, cidr, vlanId, networkDomain, owner, false, domainId, tags, isShared); // Don't pass owner to create vlan when network offering is of type Shared - done to prevent accountVlanMap entry // creation when vlan is mapped to network @@ -1711,7 +1707,7 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag @Override @DB public Network createNetwork(long networkOfferingId, String name, String displayText, Boolean isDefault, Long zoneId, String gateway, String cidr, String vlanId, String networkDomain, - Account owner, boolean isSecurityGroupEnabled, Long domainId, List tags) throws ConcurrentOperationException, InsufficientCapacityException { + Account owner, boolean isSecurityGroupEnabled, Long domainId, List tags, Boolean isShared) throws ConcurrentOperationException, InsufficientCapacityException { NetworkOfferingVO networkOffering = _networkOfferingDao.findById(networkOfferingId); DataCenterVO zone = _dcDao.findById(zoneId); @@ -1719,21 +1715,19 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag // allow isDefault to be set only for Shared network if (networkOffering.getType() == Network.Type.Isolated) { if (isDefault != null && !isDefault) { - throw new InvalidParameterValueException("Can specify isDefault parameter only for Direct network."); + throw new InvalidParameterValueException("Can specify isDefault parameter only for network of type " + Network.Type.Shared); } else { isDefault = true; } + if (isShared != null && isShared) { + throw new InvalidParameterValueException("Can specify isShared parameter for Direct networks only"); + } } else { if (isDefault == null) { isDefault = false; } } - - // if network is shared, default its owner to be system - boolean isShared = false; - if (networkOffering.getType() == Network.Type.Shared) { - isShared = true; - } + if (isShared) { owner = _accountMgr.getSystemAccount(); } @@ -1827,7 +1821,7 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag } } - List networks = setupNetwork(owner, networkOffering, userNetwork, plan, name, displayText, isDefault, true, domainId, tags); + List networks = setupNetwork(owner, networkOffering, userNetwork, plan, name, displayText, isDefault, true, domainId, tags, isShared); Network network = null; if (networks == null || networks.isEmpty()) { @@ -2748,7 +2742,7 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag // create new Virtual network for the user if it doesn't exist if (createNetwork) { List offerings = _configMgr.listNetworkOfferings(TrafficType.Guest, false); - network = createNetwork(offerings.get(0).getId(), owner.getAccountName() + "-network", owner.getAccountName() + "-network", null, zoneId, null, null, null, null, owner, false, null, null); + network = createNetwork(offerings.get(0).getId(), owner.getAccountName() + "-network", owner.getAccountName() + "-network", null, zoneId, null, null, null, null, owner, false, null, null, false); if (network == null) { s_logger.warn("Failed to create default Virtual network for the account " + accountId + "in zone " + zoneId); diff --git a/server/src/com/cloud/network/NetworkVO.java b/server/src/com/cloud/network/NetworkVO.java index 4a67c19a43b..3a749471403 100644 --- a/server/src/com/cloud/network/NetworkVO.java +++ b/server/src/com/cloud/network/NetworkVO.java @@ -182,8 +182,8 @@ public class NetworkVO implements Network { this.guestType = guestType; } - public NetworkVO(long id, Network that, long offeringId, long dataCenterId, String guruName, long domainId, long accountId, long related, String name, String displayText, boolean isDefault, boolean isSecurityGroupEnabled, boolean isDomainSpecific, String networkDomain, Type type) { - this(id, that.getTrafficType(), that.getGuestType(), that.getMode(), that.getBroadcastDomainType(), offeringId, dataCenterId, domainId, accountId, related, name, displayText,isDefault, isDomainSpecific, networkDomain, type); + public NetworkVO(long id, Network that, long offeringId, long dataCenterId, String guruName, long domainId, long accountId, long related, String name, String displayText, boolean isDefault, boolean isSecurityGroupEnabled, boolean isDomainSpecific, String networkDomain, Type type, boolean isShared) { + this(id, that.getTrafficType(), that.getGuestType(), that.getMode(), that.getBroadcastDomainType(), offeringId, dataCenterId, domainId, accountId, related, name, displayText,isDefault, isDomainSpecific, networkDomain, type, isShared); this.gateway = that.getGateway(); this.cidr = that.getCidr(); this.broadcastUri = that.getBroadcastUri(); @@ -207,13 +207,14 @@ public class NetworkVO implements Network { * @param accountId * @param name * @param displayText - * @param isShared * @param isDefault * @param isDomainSpecific * @param networkDomain * @param type TODO + * @param isShared TODO + * @param isShared */ - public NetworkVO(long id, TrafficType trafficType, GuestIpType guestType, Mode mode, BroadcastDomainType broadcastDomainType, long networkOfferingId, long dataCenterId, long domainId, long accountId, long related, String name, String displayText, boolean isDefault, boolean isDomainSpecific, String networkDomain, Type type) { + public NetworkVO(long id, TrafficType trafficType, GuestIpType guestType, Mode mode, BroadcastDomainType broadcastDomainType, long networkOfferingId, long dataCenterId, long domainId, long accountId, long related, String name, String displayText, boolean isDefault, boolean isDomainSpecific, String networkDomain, Type type, boolean isShared) { this(trafficType, guestType, mode, broadcastDomainType, networkOfferingId, dataCenterId, State.Allocated); this.domainId = domainId; this.accountId = accountId; @@ -221,15 +222,11 @@ public class NetworkVO implements Network { this.id = id; this.name = name; this.displayText = displayText; - if (type == Network.Type.Shared) { - this.isShared = true; - } else if (type == Network.Type.Isolated) { - this.isShared = false; - } this.isDefault = isDefault; this.isDomainSpecific = isDomainSpecific; this.networkDomain = networkDomain; this.type = type; + this.isShared = isShared; } @Override @@ -493,4 +490,9 @@ public class NetworkVO implements Network { buf.append(id).append("|").append(trafficType.toString()).append("|").append(networkOfferingId).append("]"); return buf.toString(); } + + @Override + public boolean getIsShared() { + return isShared; + } } diff --git a/server/src/com/cloud/network/lb/ElasticLoadBalancerManagerImpl.java b/server/src/com/cloud/network/lb/ElasticLoadBalancerManagerImpl.java index cd0a385e2a7..790bf05bd24 100644 --- a/server/src/com/cloud/network/lb/ElasticLoadBalancerManagerImpl.java +++ b/server/src/com/cloud/network/lb/ElasticLoadBalancerManagerImpl.java @@ -486,7 +486,7 @@ public class ElasticLoadBalancerManagerImpl implements List offerings = _networkMgr.getSystemAccountNetworkOfferings(NetworkOfferingVO.SystemControlNetwork); NetworkOfferingVO controlOffering = offerings.get(0); - NetworkVO controlConfig = _networkMgr.setupNetwork(_systemAcct, controlOffering, plan, null, null, false).get(0); + NetworkVO controlConfig = _networkMgr.setupNetwork(_systemAcct, controlOffering, plan, null, null, false, false).get(0); List> networks = new ArrayList>(2); NicProfile guestNic = new NicProfile(); diff --git a/server/src/com/cloud/network/router/VirtualNetworkApplianceManagerImpl.java b/server/src/com/cloud/network/router/VirtualNetworkApplianceManagerImpl.java index c1a70f1c911..d56ad569fe5 100755 --- a/server/src/com/cloud/network/router/VirtualNetworkApplianceManagerImpl.java +++ b/server/src/com/cloud/network/router/VirtualNetworkApplianceManagerImpl.java @@ -1063,11 +1063,11 @@ public class VirtualNetworkApplianceManagerImpl implements VirtualNetworkApplian List offerings = _networkMgr.getSystemAccountNetworkOfferings(NetworkOfferingVO.SystemControlNetwork); NetworkOfferingVO controlOffering = offerings.get(0); - NetworkVO controlConfig = _networkMgr.setupNetwork(_systemAcct, controlOffering, plan, null, null, false).get(0); + NetworkVO controlConfig = _networkMgr.setupNetwork(_systemAcct, controlOffering, plan, null, null, false, false).get(0); List> networks = new ArrayList>(3); NetworkOfferingVO publicOffering = _networkMgr.getSystemAccountNetworkOfferings(NetworkOfferingVO.SystemPublicNetwork).get(0); - List publicNetworks = _networkMgr.setupNetwork(_systemAcct, publicOffering, plan, null, null, false); + List publicNetworks = _networkMgr.setupNetwork(_systemAcct, publicOffering, plan, null, null, false, false); networks.add(new Pair(publicNetworks.get(0), defaultNic)); NicProfile gatewayNic = new NicProfile(); if (isRedundant) { @@ -1253,7 +1253,7 @@ public class VirtualNetworkApplianceManagerImpl implements VirtualNetworkApplian List offerings = _networkMgr.getSystemAccountNetworkOfferings(NetworkOfferingVO.SystemControlNetwork); NetworkOfferingVO controlOffering = offerings.get(0); - NetworkVO controlConfig = _networkMgr.setupNetwork(_systemAcct, controlOffering, plan, null, null, false).get(0); + NetworkVO controlConfig = _networkMgr.setupNetwork(_systemAcct, controlOffering, plan, null, null, false, false).get(0); List> networks = new ArrayList>(3); diff --git a/server/src/com/cloud/offerings/NetworkOfferingVO.java b/server/src/com/cloud/offerings/NetworkOfferingVO.java index 27823837b3f..ff6b75111f2 100644 --- a/server/src/com/cloud/offerings/NetworkOfferingVO.java +++ b/server/src/com/cloud/offerings/NetworkOfferingVO.java @@ -232,7 +232,7 @@ public class NetworkOfferingVO implements NetworkOffering { return type; } - public NetworkOfferingVO(String name, String displayText, TrafficType trafficType, boolean systemOnly, boolean specifyVlan, Integer rateMbps, Integer multicastRateMbps, Integer concurrentConnections, boolean isDefault, Availability availability, GuestIpType guestIpType, String tags, boolean isSecurityGroupEnabled, Network.Type type) { + public NetworkOfferingVO(String name, String displayText, TrafficType trafficType, boolean systemOnly, boolean specifyVlan, Integer rateMbps, Integer multicastRateMbps, Integer concurrentConnections, boolean isDefault, Availability availability, String tags, boolean isSecurityGroupEnabled, Network.Type type) { this.name = name; this.displayText = displayText; this.rateMbps = rateMbps; @@ -245,9 +245,13 @@ public class NetworkOfferingVO implements NetworkOffering { this.availability = availability; this.uniqueName = name; this.tags = tags; - this.guestType = guestIpType; this.securityGroupEnabled = isSecurityGroupEnabled; this.type = type; + if (type == Type.Isolated) { + this.guestType = GuestIpType.Virtual; + } else if (type == Type.Shared){ + this.guestType = GuestIpType.Direct; + } } public NetworkOfferingVO() { @@ -259,7 +263,7 @@ public class NetworkOfferingVO implements NetworkOffering { * @param trafficType */ public NetworkOfferingVO(String name, TrafficType trafficType) { - this(name, "System Offering for " + name, trafficType, true, false, 0, 0, null, true, Availability.Required, null, null, false, null); + this(name, "System Offering for " + name, trafficType, true, false, 0, 0, null, true, Availability.Required, null, false, null); this.state = State.Enabled; this.type = Type.Shared; } diff --git a/server/src/com/cloud/server/ConfigurationServerImpl.java b/server/src/com/cloud/server/ConfigurationServerImpl.java index e32158e7ce9..01cc278697d 100644 --- a/server/src/com/cloud/server/ConfigurationServerImpl.java +++ b/server/src/com/cloud/server/ConfigurationServerImpl.java @@ -67,7 +67,6 @@ import com.cloud.domain.dao.DomainDao; import com.cloud.exception.InternalErrorException; import com.cloud.exception.InvalidParameterValueException; import com.cloud.network.Network; -import com.cloud.network.Network.GuestIpType; import com.cloud.network.Network.Provider; import com.cloud.network.Network.Service; import com.cloud.network.Network.State; @@ -852,7 +851,7 @@ public class ConfigurationServerImpl implements ConfigurationServer { "System-Guest-Network", TrafficType.Guest, false, false, null, null, null, true, - Availability.Optional, GuestIpType.Direct, null, true, Network.Type.Shared); + Availability.Optional, null, true, Network.Type.Shared); guestNetworkOffering.setState(NetworkOffering.State.Enabled); @@ -869,7 +868,7 @@ public class ConfigurationServerImpl implements ConfigurationServer { "Virtual Vlan", TrafficType.Guest, false, false, null, null, null, true, - Availability.Required, GuestIpType.Virtual, null, false, Network.Type.Isolated); + Availability.Required, null, false, Network.Type.Isolated); defaultGuestNetworkOffering.setState(NetworkOffering.State.Enabled); defaultGuestNetworkOffering = _networkOfferingDao.persistDefaultNetworkOffering(defaultGuestNetworkOffering); @@ -886,7 +885,7 @@ public class ConfigurationServerImpl implements ConfigurationServer { "Direct", TrafficType.Guest, false, true, null, null, null, true, - Availability.Optional, GuestIpType.Direct, null, false, Network.Type.Shared); + Availability.Optional, null, false, Network.Type.Shared); defaultGuestDirectNetworkOffering.setState(NetworkOffering.State.Enabled); defaultGuestDirectNetworkOffering = _networkOfferingDao.persistDefaultNetworkOffering(defaultGuestDirectNetworkOffering); @@ -953,7 +952,7 @@ public class ConfigurationServerImpl implements ConfigurationServer { } if (broadcastDomainType != null) { - NetworkVO network = new NetworkVO(id, trafficType, null, mode, broadcastDomainType, networkOfferingId, zoneId, domainId, accountId, related, null, null, isNetworkDefault, false, networkDomain, Network.Type.Shared); + NetworkVO network = new NetworkVO(id, trafficType, null, mode, broadcastDomainType, networkOfferingId, zoneId, domainId, accountId, related, null, null, isNetworkDefault, false, networkDomain, Network.Type.Shared, true); network.setGuruName(guruNames.get(network.getTrafficType())); network.setDns1(zone.getDns1()); network.setDns2(zone.getDns2()); diff --git a/server/src/com/cloud/storage/secondary/SecondaryStorageManagerImpl.java b/server/src/com/cloud/storage/secondary/SecondaryStorageManagerImpl.java index b042e574533..d18aecf8c28 100644 --- a/server/src/com/cloud/storage/secondary/SecondaryStorageManagerImpl.java +++ b/server/src/com/cloud/storage/secondary/SecondaryStorageManagerImpl.java @@ -504,9 +504,9 @@ public class SecondaryStorageManagerImpl implements SecondaryStorageVmManager, V defaultNic.setDefaultNic(true); defaultNic.setDeviceId(2); try { - networks.add(new Pair(_networkMgr.setupNetwork(systemAcct, defaultOffering.get(0), plan, null, null, false).get(0), defaultNic)); + networks.add(new Pair(_networkMgr.setupNetwork(systemAcct, defaultOffering.get(0), plan, null, null, false, false).get(0), defaultNic)); for (NetworkOfferingVO offering : offerings) { - networks.add(new Pair(_networkMgr.setupNetwork(systemAcct, offering, plan, null, null, false).get(0), null)); + networks.add(new Pair(_networkMgr.setupNetwork(systemAcct, offering, plan, null, null, false, false).get(0), null)); } } catch (ConcurrentOperationException e) { s_logger.info("Unable to setup due to concurrent operation. " + e); diff --git a/server/src/com/cloud/vm/UserVmManagerImpl.java b/server/src/com/cloud/vm/UserVmManagerImpl.java index f30c8f97377..0da715ac0ff 100755 --- a/server/src/com/cloud/vm/UserVmManagerImpl.java +++ b/server/src/com/cloud/vm/UserVmManagerImpl.java @@ -2178,7 +2178,7 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, Manager if (virtualNetworks.isEmpty()) { s_logger.debug("Creating default Virtual network for account " + owner + " as a part of deployVM process"); Network newNetwork = _networkMgr.createNetwork(defaultVirtualOffering.get(0).getId(), owner.getAccountName() + "-network", owner.getAccountName() + "-network", null, zone.getId(), - null, null, null, null, owner, false, null, null); + null, null, null, null, owner, false, null, null, false); defaultNetwork = _networkDao.findById(newNetwork.getId()); } else if (virtualNetworks.size() > 1) { throw new InvalidParameterValueException("More than 1 default Virtaul networks are found for account " + owner + "; please specify networkIds"); @@ -2191,7 +2191,7 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, Manager if (defaultVirtualOffering.get(0).getAvailability() == Availability.Optional) { s_logger.debug("Creating default Virtual network for account " + owner + " as a part of deployVM process"); Network newNetwork = _networkMgr.createNetwork(defaultVirtualOffering.get(0).getId(), owner.getAccountName() + "-network", owner.getAccountName() + "-network", null, zone.getId(), - null, null, null, null, owner, false, null, null); + null, null, null, null, owner, false, null, null, false); defaultNetwork = _networkDao.findById(newNetwork.getId()); } else { throw new InvalidParameterValueException("Unable to find default networks for account " + owner); @@ -3336,7 +3336,7 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, Manager List virtualNetworks = _networkMgr.listNetworksForAccount(newAccount.getId(), zone.getId(), GuestIpType.Virtual, true); if (virtualNetworks.isEmpty()) { Network newNetwork = _networkMgr.createNetwork(networkOffering, newAccount.getAccountName() + "-network", newAccount.getAccountName() + "-network", null, vm.getDataCenterIdToDeployIn(), - null, null, null, null, newAccount, false, null, null); + null, null, null, null, newAccount, false, null, null, false); defaultNetwork = _networkDao.findById(newNetwork.getId()); } else if (virtualNetworks.size() > 1) { throw new InvalidParameterValueException("More than 1 default Virtaul networks are found for account " + newAccount + "; please specify networkIds"); diff --git a/server/test/com/cloud/network/MockNetworkManagerImpl.java b/server/test/com/cloud/network/MockNetworkManagerImpl.java index 5e1f5bb6a0e..a9127b6ab20 100644 --- a/server/test/com/cloud/network/MockNetworkManagerImpl.java +++ b/server/test/com/cloud/network/MockNetworkManagerImpl.java @@ -2,6 +2,7 @@ package com.cloud.network; import java.util.List; import java.util.Map; +import java.util.Set; import javax.ejb.Local; import javax.naming.ConfigurationException; @@ -9,6 +10,7 @@ import javax.naming.ConfigurationException; import com.cloud.api.commands.AssociateIPAddrCmd; import com.cloud.api.commands.CreateNetworkCmd; import com.cloud.api.commands.ListNetworksCmd; +import com.cloud.api.commands.RestartNetworkCmd; import com.cloud.dc.Vlan; import com.cloud.dc.Vlan.VlanType; import com.cloud.deploy.DeployDestination; @@ -20,9 +22,12 @@ import com.cloud.exception.ResourceAllocationException; import com.cloud.exception.ResourceUnavailableException; import com.cloud.network.Network.Capability; import com.cloud.network.Network.GuestIpType; +import com.cloud.network.Network.Provider; import com.cloud.network.Network.Service; import com.cloud.network.Networks.TrafficType; import com.cloud.network.addr.PublicIp; +import com.cloud.network.element.PasswordServiceProvider; +import com.cloud.network.element.RemoteAccessVPNServiceProvider; import com.cloud.network.guru.NetworkGuru; import com.cloud.network.rules.FirewallRule; import com.cloud.network.rules.StaticNat; @@ -193,7 +198,7 @@ public class MockNetworkManagerImpl implements NetworkManager, Manager, NetworkS } @Override - public List setupNetwork(Account owner, NetworkOfferingVO offering, DeploymentPlan plan, String name, String displayText, boolean isDefault) + public List setupNetwork(Account owner, NetworkOfferingVO offering, DeploymentPlan plan, String name, String displayText, boolean isDefault, boolean isShared) throws ConcurrentOperationException { // TODO Auto-generated method stub return null; @@ -201,7 +206,7 @@ public class MockNetworkManagerImpl implements NetworkManager, Manager, NetworkS @Override public List setupNetwork(Account owner, NetworkOfferingVO offering, Network predefined, DeploymentPlan plan, String name, String displayText, boolean isDefault, boolean errorIfAlreadySetup, - Long domainId, List tags) throws ConcurrentOperationException { + Long domainId, List tags, boolean isShared) throws ConcurrentOperationException { // TODO Auto-generated method stub return null; } @@ -336,7 +341,7 @@ public class MockNetworkManagerImpl implements NetworkManager, Manager, NetworkS @Override public Network createNetwork(long networkOfferingId, String name, String displayText, Boolean isDefault, Long zoneId, String gateway, String cidr, String vlanId, String networkDomain, - Account owner, boolean isSecurityGroupEnabled, Long domainId, List tags) throws ConcurrentOperationException, InsufficientCapacityException { + Account owner, boolean isSecurityGroupEnabled, Long domainId, List tags, Boolean isShared) throws ConcurrentOperationException, InsufficientCapacityException { // TODO Auto-generated method stub return null; } @@ -479,5 +484,37 @@ public class MockNetworkManagerImpl implements NetworkManager, Manager, NetworkS // TODO Auto-generated method stub return null; } + + @Override + public Map> listNetworkOfferingServices(long networkOfferingId) { + return null; + } + + @Override + public boolean restartNetwork(RestartNetworkCmd cmd, boolean cleanup) throws ConcurrentOperationException, ResourceUnavailableException, InsufficientCapacityException { + return false; + } + + @Override + public List getRemoteAccessVpnElements() { + return null; + } + @Override + public List getPasswordResetElements() { + // TODO Auto-generated method stub + return null; + } + + @Override + public Long getPodIdForVlan(long vlanDbId) { + // TODO Auto-generated method stub + return null; + } + + @Override + public boolean isProviderSupported(long networkOfferingId, Service service, Provider provider) { + // TODO Auto-generated method stub + return false; + } } From c5acad39d9d22a2664aa0176d1296454afd6f737 Mon Sep 17 00:00:00 2001 From: alena Date: Wed, 19 Oct 2011 17:34:21 -0700 Subject: [PATCH 011/159] Make Guest Direct security group enabled network offering system by default - we'll make it non-system after getting rid of Basic/Advance zone concepts --- .../api/commands/AssociateIPAddrCmd.java | 1 - .../src/com/cloud/api/ApiResponseHelper.java | 19 +++++++------------ .../configuration/ConfigurationManager.java | 3 ++- .../ConfigurationManagerImpl.java | 6 +++--- .../com/cloud/network/NetworkManagerImpl.java | 7 ++++--- .../cloud/server/ConfigurationServerImpl.java | 2 +- 6 files changed, 17 insertions(+), 21 deletions(-) diff --git a/api/src/com/cloud/api/commands/AssociateIPAddrCmd.java b/api/src/com/cloud/api/commands/AssociateIPAddrCmd.java index 6a94b3e02cb..da6ced1b3ce 100644 --- a/api/src/com/cloud/api/commands/AssociateIPAddrCmd.java +++ b/api/src/com/cloud/api/commands/AssociateIPAddrCmd.java @@ -106,7 +106,6 @@ public class AssociateIPAddrCmd extends BaseAsyncCreateCmd { return networks.get(0).getId(); } else { Network defaultGuestNetwork = _networkService.getSystemNetworkByZoneAndTrafficType(zone.getId(), TrafficType.Guest); - if (defaultGuestNetwork == null) { throw new InvalidParameterValueException("Unable to find a default Guest network for account " + getAccountName() + " in domain id=" + getDomainId()); } else { diff --git a/server/src/com/cloud/api/ApiResponseHelper.java b/server/src/com/cloud/api/ApiResponseHelper.java index 58818fb0b53..d7b0f62e485 100755 --- a/server/src/com/cloud/api/ApiResponseHelper.java +++ b/server/src/com/cloud/api/ApiResponseHelper.java @@ -99,7 +99,6 @@ import com.cloud.configuration.ResourceCount; import com.cloud.configuration.ResourceLimit; import com.cloud.dc.ClusterVO; import com.cloud.dc.DataCenter; -import com.cloud.dc.DataCenter.NetworkType; import com.cloud.dc.DataCenterVO; import com.cloud.dc.HostPodVO; import com.cloud.dc.Pod; @@ -1231,17 +1230,8 @@ public class ApiResponseHelper implements ResponseGenerator { List nicProfiles = ApiDBUtils.getNics(vm); for (NicProfile singleNicProfile : nicProfiles) { Network network = ApiDBUtils.findNetworkById(singleNicProfile.getNetworkId()); - if (network != null) { - TrafficType trafficType = TrafficType.Public; - if (zone.getNetworkType() == NetworkType.Basic || zone.isSecurityGroupEnabled()) { - trafficType = TrafficType.Guest; - } - if (network.getTrafficType() == trafficType) { - vmResponse.setPublicIp(singleNicProfile.getIp4Address()); - vmResponse.setPublicMacAddress(singleNicProfile.getMacAddress()); - vmResponse.setPublicNetmask(singleNicProfile.getNetmask()); - vmResponse.setGateway(singleNicProfile.getGateway()); - } else if (network.getTrafficType() == TrafficType.Management) { + if (network != null) { + if (network.getTrafficType() == TrafficType.Management) { vmResponse.setPrivateIp(singleNicProfile.getIp4Address()); vmResponse.setPrivateMacAddress(singleNicProfile.getMacAddress()); vmResponse.setPrivateNetmask(singleNicProfile.getNetmask()); @@ -1249,6 +1239,11 @@ public class ApiResponseHelper implements ResponseGenerator { vmResponse.setLinkLocalIp(singleNicProfile.getIp4Address()); vmResponse.setLinkLocalMacAddress(singleNicProfile.getMacAddress()); vmResponse.setLinkLocalNetmask(singleNicProfile.getNetmask()); + } else { + vmResponse.setPublicIp(singleNicProfile.getIp4Address()); + vmResponse.setPublicMacAddress(singleNicProfile.getMacAddress()); + vmResponse.setPublicNetmask(singleNicProfile.getNetmask()); + vmResponse.setGateway(singleNicProfile.getGateway()); } } } diff --git a/server/src/com/cloud/configuration/ConfigurationManager.java b/server/src/com/cloud/configuration/ConfigurationManager.java index 4627f4eed20..be55e52abbf 100644 --- a/server/src/com/cloud/configuration/ConfigurationManager.java +++ b/server/src/com/cloud/configuration/ConfigurationManager.java @@ -180,12 +180,13 @@ public interface ConfigurationManager extends ConfigurationService, Manager { * @param isDefault TODO * @param isSecurityGroupEnabled TODO * @param type TODO + * @param systemOnly TODO * @param id * @param specifyVlan; * @return network offering object */ - NetworkOfferingVO createNetworkOffering(long userId, String name, String displayText, TrafficType trafficType, String tags, Integer maxConnections, boolean specifyVlan, Availability availability, Integer networkRate, Map> serviceProviderMap, boolean isDefault, boolean isSecurityGroupEnabled, Network.Type type); + NetworkOfferingVO createNetworkOffering(long userId, String name, String displayText, TrafficType trafficType, String tags, Integer maxConnections, boolean specifyVlan, Availability availability, Integer networkRate, Map> serviceProviderMap, boolean isDefault, boolean isSecurityGroupEnabled, Network.Type type, boolean systemOnly); Vlan createVlanAndPublicIpRange(Long userId, Long zoneId, Long podId, String startIP, String endIP, String vlanGateway, String vlanNetmask, boolean forVirtualNetwork, String vlanId, Account account, Long networkId) throws InsufficientCapacityException, ConcurrentOperationException, InvalidParameterValueException; diff --git a/server/src/com/cloud/configuration/ConfigurationManagerImpl.java b/server/src/com/cloud/configuration/ConfigurationManagerImpl.java index 379c5e643ee..e41b95a7cc0 100755 --- a/server/src/com/cloud/configuration/ConfigurationManagerImpl.java +++ b/server/src/com/cloud/configuration/ConfigurationManagerImpl.java @@ -2952,19 +2952,19 @@ public class ConfigurationManagerImpl implements ConfigurationManager, Configura } } - return createNetworkOffering(userId, name, displayText, trafficType, tags, maxConnections, specifyVlan, availability, networkRate, serviceProviderMap, false, isSecurityGroupEnabled, type); + return createNetworkOffering(userId, name, displayText, trafficType, tags, maxConnections, specifyVlan, availability, networkRate, serviceProviderMap, false, isSecurityGroupEnabled, type, false); } @Override @DB public NetworkOfferingVO createNetworkOffering(long userId, String name, String displayText, TrafficType trafficType, String tags, Integer maxConnections, boolean specifyVlan, - Availability availability, Integer networkRate, Map> serviceProviderMap, boolean isDefault, boolean isSecurityGroupEnabled, Network.Type type) { + Availability availability, Integer networkRate, Map> serviceProviderMap, boolean isDefault, boolean isSecurityGroupEnabled, Network.Type type, boolean systemOnly) { String multicastRateStr = _configDao.getValue("multicast.throttling.rate"); int multicastRate = ((multicastRateStr == null) ? 10 : Integer.parseInt(multicastRateStr)); tags = cleanupTags(tags); - NetworkOfferingVO offering = new NetworkOfferingVO(name, displayText, trafficType, false, specifyVlan, networkRate, multicastRate, maxConnections, isDefault, availability, tags, isSecurityGroupEnabled, type); + NetworkOfferingVO offering = new NetworkOfferingVO(name, displayText, trafficType, systemOnly, specifyVlan, networkRate, multicastRate, maxConnections, isDefault, availability, tags, isSecurityGroupEnabled, type); Transaction txn = Transaction.currentTxn(); txn.start(); diff --git a/server/src/com/cloud/network/NetworkManagerImpl.java b/server/src/com/cloud/network/NetworkManagerImpl.java index 210c159e114..654b5c0c8e6 100755 --- a/server/src/com/cloud/network/NetworkManagerImpl.java +++ b/server/src/com/cloud/network/NetworkManagerImpl.java @@ -803,22 +803,23 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag Transaction txn = Transaction.currentTxn(); txn.start(); //there is only 1 diff between offering #1 and #3 - securityGroup is enabled for the first, and disabled for the third + //TODO - networkOffering 1 should probably become non-system //check that offering already exists NetworkOfferingVO offering = null; if (_networkOfferingDao.findByUniqueName(NetworkOffering.SystemGuestNetwork) == null) { - offering = _configMgr.createNetworkOffering(Account.ACCOUNT_ID_SYSTEM, NetworkOffering.SystemGuestNetwork, "System Offering for System-Guest-Network", TrafficType.Guest, null, null, false, Availability.Optional, null, defaultDirectNetworkOfferingProviders, true, true, Network.Type.Shared); + offering = _configMgr.createNetworkOffering(Account.ACCOUNT_ID_SYSTEM, NetworkOffering.SystemGuestNetwork, "System Offering for System-Guest-Network", TrafficType.Guest, null, null, false, Availability.Optional, null, defaultDirectNetworkOfferingProviders, true, true, Network.Type.Shared, true); offering.setState(NetworkOffering.State.Enabled); _networkOfferingDao.update(offering.getId(), offering); } if (_networkOfferingDao.findByUniqueName(NetworkOffering.DefaultVirtualizedNetworkOffering) == null) { - offering = _configMgr.createNetworkOffering(Account.ACCOUNT_ID_SYSTEM,NetworkOffering.DefaultVirtualizedNetworkOffering, "Virtual Vlan", TrafficType.Guest, null, null, false, Availability.Required, null, defaultVirtualNetworkOfferingProviders, true, false, Network.Type.Isolated); + offering = _configMgr.createNetworkOffering(Account.ACCOUNT_ID_SYSTEM,NetworkOffering.DefaultVirtualizedNetworkOffering, "Virtual Vlan", TrafficType.Guest, null, null, false, Availability.Required, null, defaultVirtualNetworkOfferingProviders, true, false, Network.Type.Isolated, false); offering.setState(NetworkOffering.State.Enabled); _networkOfferingDao.update(offering.getId(), offering); } if (_networkOfferingDao.findByUniqueName(NetworkOffering.DefaultDirectNetworkOffering) == null) { - offering = _configMgr.createNetworkOffering(Account.ACCOUNT_ID_SYSTEM, NetworkOffering.DefaultDirectNetworkOffering, "Direct", TrafficType.Guest, null, null, true, Availability.Optional, null, defaultDirectNetworkOfferingProviders, true, false, Network.Type.Shared); + offering = _configMgr.createNetworkOffering(Account.ACCOUNT_ID_SYSTEM, NetworkOffering.DefaultDirectNetworkOffering, "Direct", TrafficType.Guest, null, null, true, Availability.Optional, null, defaultDirectNetworkOfferingProviders, true, false, Network.Type.Shared, false); offering.setState(NetworkOffering.State.Enabled); _networkOfferingDao.update(offering.getId(), offering); } diff --git a/server/src/com/cloud/server/ConfigurationServerImpl.java b/server/src/com/cloud/server/ConfigurationServerImpl.java index 01cc278697d..e3d7d57dc77 100644 --- a/server/src/com/cloud/server/ConfigurationServerImpl.java +++ b/server/src/com/cloud/server/ConfigurationServerImpl.java @@ -850,7 +850,7 @@ public class ConfigurationServerImpl implements ConfigurationServer { NetworkOffering.SystemGuestNetwork, "System-Guest-Network", TrafficType.Guest, - false, false, null, null, null, true, + true, false, null, null, null, true, Availability.Optional, null, true, Network.Type.Shared); guestNetworkOffering.setState(NetworkOffering.State.Enabled); From 654eaec6632b379c5ded9f8eb250ae9c184ebd49 Mon Sep 17 00:00:00 2001 From: prachi Date: Wed, 19 Oct 2011 22:39:55 -0700 Subject: [PATCH 012/159] NAAS: Configuring Zone - Create Zone changes and changes to data_center table to remove vlan, securityGroup fields - Physical Network lifecycle APIs - Physical Network Service Provider APIs - DB schema changes --- api/src/com/cloud/api/ApiConstants.java | 7 + api/src/com/cloud/api/ResponseGenerator.java | 15 + .../AddNetworkServiceProviderCmd.java | 92 ++++ .../commands/CreatePhysicalNetworkCmd.java | 121 +++++ .../com/cloud/api/commands/CreateZoneCmd.java | 17 - .../DeleteNetworkServiceProviderCmd.java | 78 +++ .../commands/DeletePhysicalNetworkCmd.java | 78 +++ .../ListNetworkServiceProvidersCmd.java | 89 ++++ .../api/commands/ListNetworkServicesCmd.java | 75 +++ .../api/commands/ListPhysicalNetworksCmd.java | 97 ++++ ...stSupportedNetworkServiceProvidersCmd.java | 88 ++++ .../UpdateNetworkServiceProviderCmd.java | 89 ++++ .../commands/UpdatePhysicalNetworkCmd.java | 116 +++++ .../com/cloud/api/commands/UpdateZoneCmd.java | 7 - .../api/response/PhysicalNetworkResponse.java | 148 ++++++ .../cloud/api/response/ProviderResponse.java | 48 +- api/src/com/cloud/dc/DataCenter.java | 1 - api/src/com/cloud/network/Network.java | 6 + api/src/com/cloud/network/NetworkProfile.java | 7 + api/src/com/cloud/network/NetworkService.java | 21 + .../com/cloud/network/PhysicalNetwork.java | 68 +++ .../PhysicalNetworkServiceProvider.java | 48 ++ client/tomcatconf/commands.properties.in | 16 +- .../src/com/cloud/api/ApiResponseHelper.java | 68 ++- .../configuration/ConfigurationManager.java | 5 +- .../ConfigurationManagerImpl.java | 144 +----- .../DefaultComponentLibrary.java | 4 + server/src/com/cloud/dc/DataCenterVO.java | 26 +- server/src/com/cloud/dc/DataCenterVnetVO.java | 12 +- .../src/com/cloud/dc/dao/DataCenterDao.java | 14 +- .../com/cloud/dc/dao/DataCenterDaoImpl.java | 40 +- .../cloud/dc/dao/DataCenterVnetDaoImpl.java | 43 +- .../cloud/network/ExternalNetworkManager.java | 3 +- .../network/ExternalNetworkManagerImpl.java | 16 +- .../com/cloud/network/NetworkManagerImpl.java | 482 +++++++++++++++++- server/src/com/cloud/network/NetworkVO.java | 31 ++ .../com/cloud/network/PhysicalNetworkVO.java | 207 ++++++++ .../src/com/cloud/network/dao/NetworkDao.java | 4 + .../com/cloud/network/dao/NetworkDaoImpl.java | 31 +- .../cloud/network/dao/PhysicalNetworkDao.java | 28 + .../network/dao/PhysicalNetworkDaoImpl.java | 58 +++ ...PhysicalNetworkIsolationMethodDaoImpl.java | 69 +++ .../dao/PhysicalNetworkIsolationMethodVO.java | 68 +++ .../PhysicalNetworkServiceProviderDao.java | 26 + ...PhysicalNetworkServiceProviderDaoImpl.java | 49 ++ .../dao/PhysicalNetworkServiceProviderVO.java | 96 ++++ .../dao/PhysicalNetworkTagDaoImpl.java | 62 +++ .../network/dao/PhysicalNetworkTagVO.java | 68 +++ .../guru/ExternalGuestNetworkGuru.java | 4 +- .../cloud/network/guru/GuestNetworkGuru.java | 4 +- .../cloud/server/ManagementServerImpl.java | 4 +- server/src/com/cloud/test/DatabaseConfig.java | 28 +- server/src/com/cloud/test/PodZoneConfig.java | 55 +- setup/db/create-schema.sql | 60 ++- setup/db/server-setup.xml | 10 +- 55 files changed, 2885 insertions(+), 266 deletions(-) create mode 100644 api/src/com/cloud/api/commands/AddNetworkServiceProviderCmd.java create mode 100644 api/src/com/cloud/api/commands/CreatePhysicalNetworkCmd.java create mode 100644 api/src/com/cloud/api/commands/DeleteNetworkServiceProviderCmd.java create mode 100644 api/src/com/cloud/api/commands/DeletePhysicalNetworkCmd.java create mode 100644 api/src/com/cloud/api/commands/ListNetworkServiceProvidersCmd.java create mode 100644 api/src/com/cloud/api/commands/ListNetworkServicesCmd.java create mode 100644 api/src/com/cloud/api/commands/ListPhysicalNetworksCmd.java create mode 100644 api/src/com/cloud/api/commands/ListSupportedNetworkServiceProvidersCmd.java create mode 100644 api/src/com/cloud/api/commands/UpdateNetworkServiceProviderCmd.java create mode 100644 api/src/com/cloud/api/commands/UpdatePhysicalNetworkCmd.java create mode 100644 api/src/com/cloud/api/response/PhysicalNetworkResponse.java create mode 100644 api/src/com/cloud/network/PhysicalNetwork.java create mode 100644 api/src/com/cloud/network/PhysicalNetworkServiceProvider.java create mode 100644 server/src/com/cloud/network/PhysicalNetworkVO.java create mode 100644 server/src/com/cloud/network/dao/PhysicalNetworkDao.java create mode 100644 server/src/com/cloud/network/dao/PhysicalNetworkDaoImpl.java create mode 100644 server/src/com/cloud/network/dao/PhysicalNetworkIsolationMethodDaoImpl.java create mode 100644 server/src/com/cloud/network/dao/PhysicalNetworkIsolationMethodVO.java create mode 100644 server/src/com/cloud/network/dao/PhysicalNetworkServiceProviderDao.java create mode 100644 server/src/com/cloud/network/dao/PhysicalNetworkServiceProviderDaoImpl.java create mode 100644 server/src/com/cloud/network/dao/PhysicalNetworkServiceProviderVO.java create mode 100644 server/src/com/cloud/network/dao/PhysicalNetworkTagDaoImpl.java create mode 100644 server/src/com/cloud/network/dao/PhysicalNetworkTagVO.java diff --git a/api/src/com/cloud/api/ApiConstants.java b/api/src/com/cloud/api/ApiConstants.java index 3df3ab46b91..d8fb58579c6 100755 --- a/api/src/com/cloud/api/ApiConstants.java +++ b/api/src/com/cloud/api/ApiConstants.java @@ -277,5 +277,12 @@ public class ApiConstants { public static final String GATEWAY_SERVICE = "gatewayservice"; public static final String SERVICE_PROVIDER_LIST = "serviceproviderlist"; public static final String PROVIDER = "provider"; + public static final String NETWORK_SPEED = "networkspeed"; + public static final String BROADCAST_DOMAIN_RANGE = "broadcastdomainrange"; + public static final String ISOLATION_METHODS = "isolationmethods"; + public static final String PHYSICAL_NETWORK_ID = "physicalnetworkid"; + public static final String DEST_PHYSICAL_NETWORK_ID = "destinationphysicalnetworkid"; + public static final String ENABLED = "enabled"; + public static final String SERVICE_NAME = "servicename"; } diff --git a/api/src/com/cloud/api/ResponseGenerator.java b/api/src/com/cloud/api/ResponseGenerator.java index 69f4628b84a..45dad8fad8b 100755 --- a/api/src/com/cloud/api/ResponseGenerator.java +++ b/api/src/com/cloud/api/ResponseGenerator.java @@ -43,15 +43,18 @@ import com.cloud.api.response.ListResponse; import com.cloud.api.response.LoadBalancerResponse; import com.cloud.api.response.NetworkOfferingResponse; import com.cloud.api.response.NetworkResponse; +import com.cloud.api.response.PhysicalNetworkResponse; import com.cloud.api.response.PodResponse; import com.cloud.api.response.ProjectAccountResponse; import com.cloud.api.response.ProjectInvitationResponse; import com.cloud.api.response.ProjectResponse; +import com.cloud.api.response.ProviderResponse; import com.cloud.api.response.RemoteAccessVpnResponse; import com.cloud.api.response.ResourceCountResponse; import com.cloud.api.response.ResourceLimitResponse; import com.cloud.api.response.SecurityGroupResponse; import com.cloud.api.response.ServiceOfferingResponse; +import com.cloud.api.response.ServiceResponse; import com.cloud.api.response.SnapshotPolicyResponse; import com.cloud.api.response.SnapshotResponse; import com.cloud.api.response.StoragePoolResponse; @@ -79,6 +82,10 @@ import com.cloud.host.Host; import com.cloud.hypervisor.HypervisorCapabilities; import com.cloud.network.IpAddress; import com.cloud.network.Network; +import com.cloud.network.Network.Provider; +import com.cloud.network.Network.Service; +import com.cloud.network.PhysicalNetwork; +import com.cloud.network.PhysicalNetworkServiceProvider; import com.cloud.network.RemoteAccessVpn; import com.cloud.network.VpnUser; import com.cloud.network.router.VirtualRouter; @@ -233,4 +240,12 @@ public interface ResponseGenerator { SystemVmInstanceResponse createSystemVmInstanceResponse(VirtualMachine systemVM); + PhysicalNetworkResponse createPhysicalNetworkResponse(PhysicalNetwork result); + + ServiceResponse createNetworkServiceResponse(Service service); + + ProviderResponse createNetworkServiceProviderResponse(Provider serviceProvider); + + ProviderResponse createNetworkServiceProviderResponse(PhysicalNetworkServiceProvider result); + } diff --git a/api/src/com/cloud/api/commands/AddNetworkServiceProviderCmd.java b/api/src/com/cloud/api/commands/AddNetworkServiceProviderCmd.java new file mode 100644 index 00000000000..fd27e0ca3cc --- /dev/null +++ b/api/src/com/cloud/api/commands/AddNetworkServiceProviderCmd.java @@ -0,0 +1,92 @@ +/** + * Copyright (C) 2011 Citrix Systems, Inc. All rights reserved. + * + * This software is licensed under the GNU General Public License v3 or later. + * + * It is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or any later version. + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + */ + +package com.cloud.api.commands; + +import org.apache.log4j.Logger; + +import com.cloud.api.ApiConstants; +import com.cloud.api.BaseCmd; +import com.cloud.api.Implementation; +import com.cloud.api.Parameter; +import com.cloud.api.ServerApiException; +import com.cloud.api.response.ProviderResponse; +import com.cloud.network.PhysicalNetworkServiceProvider; +import com.cloud.user.Account; + +@Implementation(description="Adds a network serviceProvider to a physical network", responseObject=ProviderResponse.class) +public class AddNetworkServiceProviderCmd extends BaseCmd { + public static final Logger s_logger = Logger.getLogger(AddNetworkServiceProviderCmd.class.getName()); + + private static final String s_name = "addnetworkserviceproviderresponse"; + + ///////////////////////////////////////////////////// + //////////////// API parameters ///////////////////// + ///////////////////////////////////////////////////// + + @Parameter(name=ApiConstants.PHYSICAL_NETWORK_ID, type=CommandType.LONG, required=true, description="the Physical Network ID to add the provider to") + private Long physicalNetworkId; + + @Parameter(name=ApiConstants.DEST_PHYSICAL_NETWORK_ID, type=CommandType.LONG, description="the destination Physical Network ID to bridge to") + private Long destinationPhysicalNetworkId; + + @Parameter(name=ApiConstants.NAME, type=CommandType.STRING, required=true, description="the name for the physical network service provider") + private String name; + + ///////////////////////////////////////////////////// + /////////////////// Accessors /////////////////////// + ///////////////////////////////////////////////////// + + public Long getPhysicalNetworkId() { + return physicalNetworkId; + } + + public String getProviderName() { + return name; + } + + public Long getDestinationPhysicalNetworkId() { + return destinationPhysicalNetworkId; + } + + ///////////////////////////////////////////////////// + /////////////// API Implementation/////////////////// + ///////////////////////////////////////////////////// + + @Override + public String getCommandName() { + return s_name; + } + + @Override + public long getEntityOwnerId() { + return Account.ACCOUNT_ID_SYSTEM; + } + + @Override + public void execute(){ + PhysicalNetworkServiceProvider result = _networkService.addProviderToPhysicalNetwork(getPhysicalNetworkId(), getProviderName(), getDestinationPhysicalNetworkId()); + if (result != null) { + ProviderResponse response = _responseGenerator.createNetworkServiceProviderResponse(result); + response.setResponseName(getCommandName()); + this.setResponseObject(response); + }else { + throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to add service provider to physical network"); + } + } +} diff --git a/api/src/com/cloud/api/commands/CreatePhysicalNetworkCmd.java b/api/src/com/cloud/api/commands/CreatePhysicalNetworkCmd.java new file mode 100644 index 00000000000..47e2b8dc2f3 --- /dev/null +++ b/api/src/com/cloud/api/commands/CreatePhysicalNetworkCmd.java @@ -0,0 +1,121 @@ +/** + * Copyright (C) 2011 Citrix Systems, Inc. All rights reserved. + * + * This software is licensed under the GNU General Public License v3 or later. + * + * It is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or any later version. + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + */ + +package com.cloud.api.commands; + +import java.util.List; + +import org.apache.log4j.Logger; + +import com.cloud.api.ApiConstants; +import com.cloud.api.BaseCmd; +import com.cloud.api.Implementation; +import com.cloud.api.Parameter; +import com.cloud.api.ServerApiException; +import com.cloud.api.response.PhysicalNetworkResponse; +import com.cloud.network.PhysicalNetwork; +import com.cloud.user.Account; + +@Implementation(description="Creates a physical network", responseObject=PhysicalNetworkResponse.class) +public class CreatePhysicalNetworkCmd extends BaseCmd { + public static final Logger s_logger = Logger.getLogger(CreatePhysicalNetworkCmd.class.getName()); + + private static final String s_name = "createphysicalnetworkresponse"; + + ///////////////////////////////////////////////////// + //////////////// API parameters ///////////////////// + ///////////////////////////////////////////////////// + + @Parameter(name=ApiConstants.ZONE_ID, type=CommandType.LONG, required=true, description="the Zone ID for the physical network") + private Long zoneId; + + @Parameter(name=ApiConstants.VLAN, type=CommandType.STRING, description="the VLAN for the physical network") + private String vlan; + + @Parameter(name=ApiConstants.NETWORK_SPEED, type=CommandType.STRING, description="the speed for the physical network[1G/10G]") + private String speed; + + @Parameter(name=ApiConstants.DOMAIN_ID, type=CommandType.LONG, description="domain ID of the account owning a physical network") + private Long domainId; + + @Parameter(name=ApiConstants.BROADCAST_DOMAIN_RANGE, type=CommandType.STRING, description="the broadcast domain range for the physical network[Pod or Zone]") + private String broadcastDomainRange; + + @Parameter(name=ApiConstants.TAGS, type=CommandType.LIST, collectionType=CommandType.STRING, description="Tag the physical network") + private List tags; + + @Parameter(name=ApiConstants.ISOLATION_METHODS, type=CommandType.LIST, collectionType=CommandType.STRING, description="the isolation method for the physical network[VLAN/L3/GRE]") + private List isolationMethods; + ///////////////////////////////////////////////////// + /////////////////// Accessors /////////////////////// + ///////////////////////////////////////////////////// + + public List getTags() { + return tags; + } + + public Long getZoneId() { + return zoneId; + } + + public String getVlan() { + return vlan; + } + + public Long getDomainId() { + return domainId; + } + + public String getBroadcastDomainRange() { + return broadcastDomainRange; + } + + public List getIsolationMethods() { + return isolationMethods; + } + + public String getNetworkSpeed() { + return speed; + } + + ///////////////////////////////////////////////////// + /////////////// API Implementation/////////////////// + ///////////////////////////////////////////////////// + + @Override + public String getCommandName() { + return s_name; + } + + @Override + public long getEntityOwnerId() { + return Account.ACCOUNT_ID_SYSTEM; + } + + @Override + public void execute(){ + PhysicalNetwork result = _networkService.createPhysicalNetwork(getZoneId(),getVlan(),getNetworkSpeed(), getIsolationMethods(),getBroadcastDomainRange(),getDomainId(), getTags()); + if (result != null) { + PhysicalNetworkResponse response = _responseGenerator.createPhysicalNetworkResponse(result); + response.setResponseName(getCommandName()); + this.setResponseObject(response); + }else { + throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to create physical network"); + } + } +} diff --git a/api/src/com/cloud/api/commands/CreateZoneCmd.java b/api/src/com/cloud/api/commands/CreateZoneCmd.java index 8363e67723d..67577b8ef00 100755 --- a/api/src/com/cloud/api/commands/CreateZoneCmd.java +++ b/api/src/com/cloud/api/commands/CreateZoneCmd.java @@ -57,9 +57,6 @@ public class CreateZoneCmd extends BaseCmd { @Parameter(name=ApiConstants.NAME, type=CommandType.STRING, required=true, description="the name of the Zone") private String zoneName; - @Parameter(name=ApiConstants.VLAN, type=CommandType.STRING, description="the VLAN for the Zone") - private String vlan; - @Parameter(name=ApiConstants.DOMAIN, type=CommandType.STRING, description="Network domain name for the networks in the zone") private String domain; @@ -69,9 +66,6 @@ public class CreateZoneCmd extends BaseCmd { @Parameter(name=ApiConstants.NETWORK_TYPE, type=CommandType.STRING, required=true, description="network type of the zone, can be Basic or Advanced") private String networkType; - @Parameter(name=ApiConstants.SECURITY_GROUP_EANBLED, type=CommandType.BOOLEAN, description="true if network is security group enabled, false otherwise") - private Boolean securitygroupenabled; - @Parameter(name=ApiConstants.ALLOCATION_STATE, type=CommandType.STRING, description="Allocation state of this Zone for allocation of new resources") private String allocationState; @@ -103,10 +97,6 @@ public class CreateZoneCmd extends BaseCmd { return zoneName; } - public String getVlan() { - return vlan; - } - public String getDomain() { return domain; } @@ -119,13 +109,6 @@ public class CreateZoneCmd extends BaseCmd { return networkType; } - public Boolean isSecurityGroupEnabled() { - if (securitygroupenabled == null) { - return false; - } - return securitygroupenabled; - } - public String getAllocationState() { return allocationState; } diff --git a/api/src/com/cloud/api/commands/DeleteNetworkServiceProviderCmd.java b/api/src/com/cloud/api/commands/DeleteNetworkServiceProviderCmd.java new file mode 100644 index 00000000000..2de6acac328 --- /dev/null +++ b/api/src/com/cloud/api/commands/DeleteNetworkServiceProviderCmd.java @@ -0,0 +1,78 @@ +/** + * Copyright (C) 2011 Citrix Systems, Inc. All rights reserved. + * + * This software is licensed under the GNU General Public License v3 or later. + * + * It is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or any later version. + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + */ + +package com.cloud.api.commands; + +import org.apache.log4j.Logger; + +import com.cloud.api.ApiConstants; +import com.cloud.api.BaseCmd; +import com.cloud.api.Implementation; +import com.cloud.api.Parameter; +import com.cloud.api.ServerApiException; +import com.cloud.api.response.SuccessResponse; +import com.cloud.user.Account; + +@Implementation(description="Deletes a Network Service Provider.", responseObject=SuccessResponse.class) +public class DeleteNetworkServiceProviderCmd extends BaseCmd { + public static final Logger s_logger = Logger.getLogger(DeleteNetworkServiceProviderCmd.class.getName()); + + private static final String s_name = "deletenetworkserviceproviderresponse"; + + ///////////////////////////////////////////////////// + //////////////// API parameters ///////////////////// + ///////////////////////////////////////////////////// + + @Parameter(name=ApiConstants.ID, type=CommandType.LONG, required=true, description="the ID of the network service provider") + private Long id; + + + ///////////////////////////////////////////////////// + /////////////////// Accessors /////////////////////// + ///////////////////////////////////////////////////// + + public Long getId() { + return id; + } + + + ///////////////////////////////////////////////////// + /////////////// API Implementation/////////////////// + ///////////////////////////////////////////////////// + + @Override + public String getCommandName() { + return s_name; + } + + @Override + public long getEntityOwnerId() { + return Account.ACCOUNT_ID_SYSTEM; + } + + @Override + public void execute(){ + boolean result = _networkService.deleteNetworkServiceProvider(getId()); + if (result) { + SuccessResponse response = new SuccessResponse(getCommandName()); + this.setResponseObject(response); + } else { + throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to delete network service provider"); + } + } +} diff --git a/api/src/com/cloud/api/commands/DeletePhysicalNetworkCmd.java b/api/src/com/cloud/api/commands/DeletePhysicalNetworkCmd.java new file mode 100644 index 00000000000..4477d279a1e --- /dev/null +++ b/api/src/com/cloud/api/commands/DeletePhysicalNetworkCmd.java @@ -0,0 +1,78 @@ +/** + * Copyright (C) 2011 Citrix Systems, Inc. All rights reserved. + * + * This software is licensed under the GNU General Public License v3 or later. + * + * It is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or any later version. + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + */ + +package com.cloud.api.commands; + +import org.apache.log4j.Logger; + +import com.cloud.api.ApiConstants; +import com.cloud.api.BaseCmd; +import com.cloud.api.Implementation; +import com.cloud.api.Parameter; +import com.cloud.api.ServerApiException; +import com.cloud.api.response.SuccessResponse; +import com.cloud.user.Account; + +@Implementation(description="Deletes a Physical Network.", responseObject=SuccessResponse.class) +public class DeletePhysicalNetworkCmd extends BaseCmd { + public static final Logger s_logger = Logger.getLogger(DeletePhysicalNetworkCmd.class.getName()); + + private static final String s_name = "deletephysicalnetworkresponse"; + + ///////////////////////////////////////////////////// + //////////////// API parameters ///////////////////// + ///////////////////////////////////////////////////// + + @Parameter(name=ApiConstants.ID, type=CommandType.LONG, required=true, description="the ID of the Physical network") + private Long id; + + + ///////////////////////////////////////////////////// + /////////////////// Accessors /////////////////////// + ///////////////////////////////////////////////////// + + public Long getId() { + return id; + } + + + ///////////////////////////////////////////////////// + /////////////// API Implementation/////////////////// + ///////////////////////////////////////////////////// + + @Override + public String getCommandName() { + return s_name; + } + + @Override + public long getEntityOwnerId() { + return Account.ACCOUNT_ID_SYSTEM; + } + + @Override + public void execute(){ + boolean result = _networkService.deletePhysicalNetwork(getId()); + if (result) { + SuccessResponse response = new SuccessResponse(getCommandName()); + this.setResponseObject(response); + } else { + throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to delete physical network"); + } + } +} diff --git a/api/src/com/cloud/api/commands/ListNetworkServiceProvidersCmd.java b/api/src/com/cloud/api/commands/ListNetworkServiceProvidersCmd.java new file mode 100644 index 00000000000..f152566a0ee --- /dev/null +++ b/api/src/com/cloud/api/commands/ListNetworkServiceProvidersCmd.java @@ -0,0 +1,89 @@ +/** + * Copyright (C) 2011 Citrix Systems, Inc. All rights reserved. + * + * This software is licensed under the GNU General Public License v3 or later. + * + * It is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or any later version. + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + */ + +package com.cloud.api.commands; + +import java.util.ArrayList; +import java.util.List; + +import org.apache.log4j.Logger; + +import com.cloud.api.ApiConstants; +import com.cloud.api.BaseListCmd; +import com.cloud.api.Implementation; +import com.cloud.api.Parameter; +import com.cloud.api.response.ListResponse; +import com.cloud.api.response.ProviderResponse; +import com.cloud.network.PhysicalNetworkServiceProvider; +import com.cloud.user.Account; + + +@Implementation(description="Lists network serviceproviders for a given physical network.", responseObject=ProviderResponse.class) +public class ListNetworkServiceProvidersCmd extends BaseListCmd { + public static final Logger s_logger = Logger.getLogger(ListNetworkServiceProvidersCmd.class.getName()); + private static final String _name = "listnetworkserviceprovidersresponse"; + + ///////////////////////////////////////////////////// + //////////////// API parameters ///////////////////// + ///////////////////////////////////////////////////// + + @Parameter(name=ApiConstants.PHYSICAL_NETWORK_ID, type=CommandType.LONG, required=true, description="the Physical Network ID to add the provider to") + private Long physicalNetworkId; + + ///////////////////////////////////////////////////// + /////////////////// Accessors /////////////////////// + ///////////////////////////////////////////////////// + + public void setPhysicalNetworkId(Long physicalNetworkId) { + this.physicalNetworkId = physicalNetworkId; + } + + public Long getPhysicalNetworkId() { + return physicalNetworkId; + } + + ///////////////////////////////////////////////////// + /////////////// API Implementation/////////////////// + ///////////////////////////////////////////////////// + @Override + public String getCommandName() { + return _name; + } + + @Override + public long getEntityOwnerId() { + return Account.ACCOUNT_ID_SYSTEM; + } + + @Override + public void execute(){ + List serviceProviders = _networkService.listNetworkServiceProviders(getPhysicalNetworkId()); + ListResponse response = new ListResponse(); + List serviceProvidersResponses = new ArrayList(); + for (PhysicalNetworkServiceProvider serviceProvider : serviceProviders) { + ProviderResponse serviceProviderResponse = _responseGenerator.createNetworkServiceProviderResponse(serviceProvider); + serviceProvidersResponses.add(serviceProviderResponse); + } + + response.setResponses(serviceProvidersResponses); + response.setResponseName(getCommandName()); + this.setResponseObject(response); + } + + +} diff --git a/api/src/com/cloud/api/commands/ListNetworkServicesCmd.java b/api/src/com/cloud/api/commands/ListNetworkServicesCmd.java new file mode 100644 index 00000000000..aaf260fa861 --- /dev/null +++ b/api/src/com/cloud/api/commands/ListNetworkServicesCmd.java @@ -0,0 +1,75 @@ +/** + * Copyright (C) 2011 Citrix Systems, Inc. All rights reserved. + * + * This software is licensed under the GNU General Public License v3 or later. + * + * It is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or any later version. + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + */ + +package com.cloud.api.commands; + +import java.util.ArrayList; +import java.util.List; + +import org.apache.log4j.Logger; + +import com.cloud.api.BaseListCmd; +import com.cloud.api.Implementation; +import com.cloud.api.response.ListResponse; +import com.cloud.api.response.ServiceResponse; +import com.cloud.network.Network; +import com.cloud.user.Account; + + +@Implementation(description="Lists all network services provided by CloudStack.", responseObject=ServiceResponse.class) +public class ListNetworkServicesCmd extends BaseListCmd { + public static final Logger s_logger = Logger.getLogger(ListNetworkServicesCmd.class.getName()); + private static final String _name = "listnetworkservicesresponse"; + + ///////////////////////////////////////////////////// + //////////////// API parameters ///////////////////// + ///////////////////////////////////////////////////// + + ///////////////////////////////////////////////////// + /////////////////// Accessors /////////////////////// + ///////////////////////////////////////////////////// + + + ///////////////////////////////////////////////////// + /////////////// API Implementation/////////////////// + ///////////////////////////////////////////////////// + @Override + public String getCommandName() { + return _name; + } + + @Override + public long getEntityOwnerId() { + return Account.ACCOUNT_ID_SYSTEM; + } + + @Override + public void execute(){ + List services = _networkService.listNetworkServices(); + ListResponse response = new ListResponse(); + List servicesResponses = new ArrayList(); + for (Network.Service service : services) { + ServiceResponse serviceResponse = _responseGenerator.createNetworkServiceResponse(service); + servicesResponses.add(serviceResponse); + } + + response.setResponses(servicesResponses); + response.setResponseName(getCommandName()); + this.setResponseObject(response); + } +} diff --git a/api/src/com/cloud/api/commands/ListPhysicalNetworksCmd.java b/api/src/com/cloud/api/commands/ListPhysicalNetworksCmd.java new file mode 100644 index 00000000000..fe5f931fc2b --- /dev/null +++ b/api/src/com/cloud/api/commands/ListPhysicalNetworksCmd.java @@ -0,0 +1,97 @@ +/** + * Copyright (C) 2011 Citrix Systems, Inc. All rights reserved. + * + * This software is licensed under the GNU General Public License v3 or later. + * + * It is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or any later version. + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + */ + +package com.cloud.api.commands; + +import java.util.ArrayList; +import java.util.List; + +import org.apache.log4j.Logger; + +import com.cloud.api.ApiConstants; +import com.cloud.api.BaseCmd; +import com.cloud.api.BaseListCmd; +import com.cloud.api.Implementation; +import com.cloud.api.Parameter; +import com.cloud.api.ServerApiException; +import com.cloud.api.response.ListResponse; +import com.cloud.api.response.PhysicalNetworkResponse; +import com.cloud.network.PhysicalNetwork; +import com.cloud.user.Account; + +@Implementation(description="Lists physical networks", responseObject=PhysicalNetworkResponse.class) +public class ListPhysicalNetworksCmd extends BaseListCmd { + public static final Logger s_logger = Logger.getLogger(ListPhysicalNetworksCmd.class.getName()); + + private static final String s_name = "listphysicalnetworksresponse"; + + ///////////////////////////////////////////////////// + //////////////// API parameters ///////////////////// + ///////////////////////////////////////////////////// + + @Parameter(name=ApiConstants.ID, type=CommandType.LONG, description="list physical network by id") + private Long id; + + @Parameter(name=ApiConstants.ZONE_ID, type=CommandType.LONG, description="the Zone ID for the physical network") + private Long zoneId; + + + ///////////////////////////////////////////////////// + /////////////////// Accessors /////////////////////// + ///////////////////////////////////////////////////// + + public Long getId() { + return id; + } + + public Long getZoneId() { + return zoneId; + } + + ///////////////////////////////////////////////////// + /////////////// API Implementation/////////////////// + ///////////////////////////////////////////////////// + + @Override + public String getCommandName() { + return s_name; + } + + @Override + public long getEntityOwnerId() { + return Account.ACCOUNT_ID_SYSTEM; + } + + @Override + public void execute(){ + List result = _networkService.searchPhysicalNetworks(getId(),getZoneId(), this.getKeyword(), this.getStartIndex(), this.getPageSizeVal()); + if (result != null) { + ListResponse response = new ListResponse(); + List networkResponses = new ArrayList(); + for (PhysicalNetwork network : result) { + PhysicalNetworkResponse networkResponse = _responseGenerator.createPhysicalNetworkResponse(network); + networkResponses.add(networkResponse); + } + response.setResponses(networkResponses); + response.setResponseName(getCommandName()); + this.setResponseObject(response); + }else { + throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to search for physical networks"); + } + } +} diff --git a/api/src/com/cloud/api/commands/ListSupportedNetworkServiceProvidersCmd.java b/api/src/com/cloud/api/commands/ListSupportedNetworkServiceProvidersCmd.java new file mode 100644 index 00000000000..b061997a60d --- /dev/null +++ b/api/src/com/cloud/api/commands/ListSupportedNetworkServiceProvidersCmd.java @@ -0,0 +1,88 @@ +/** + * Copyright (C) 2011 Citrix Systems, Inc. All rights reserved. + * + * This software is licensed under the GNU General Public License v3 or later. + * + * It is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or any later version. + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + */ + +package com.cloud.api.commands; + +import java.util.ArrayList; +import java.util.List; + +import org.apache.log4j.Logger; + +import com.cloud.api.ApiConstants; +import com.cloud.api.BaseListCmd; +import com.cloud.api.Implementation; +import com.cloud.api.Parameter; +import com.cloud.api.response.ListResponse; +import com.cloud.api.response.ProviderResponse; +import com.cloud.network.Network; +import com.cloud.user.Account; + + +@Implementation(description="Lists all network serviceproviders supported by CloudStack.", responseObject=ProviderResponse.class) +public class ListSupportedNetworkServiceProvidersCmd extends BaseListCmd { + public static final Logger s_logger = Logger.getLogger(ListSupportedNetworkServiceProvidersCmd.class.getName()); + private static final String _name = "listsupportednetworkserviceprovidersresponse"; + + ///////////////////////////////////////////////////// + //////////////// API parameters ///////////////////// + ///////////////////////////////////////////////////// + + @Parameter(name=ApiConstants.SERVICE_NAME, type=CommandType.STRING, description="network service name") + private String serviceName; + + ///////////////////////////////////////////////////// + /////////////////// Accessors /////////////////////// + ///////////////////////////////////////////////////// + + + public void setServiceName(String serviceName) { + this.serviceName = serviceName; + } + + public String getServiceName() { + return serviceName; + } + + ///////////////////////////////////////////////////// + /////////////// API Implementation/////////////////// + ///////////////////////////////////////////////////// + @Override + public String getCommandName() { + return _name; + } + + @Override + public long getEntityOwnerId() { + return Account.ACCOUNT_ID_SYSTEM; + } + + @Override + public void execute(){ + List serviceProviders = _networkService.listSupportedNetworkServiceProviders(getServiceName()); + ListResponse response = new ListResponse(); + List serviceProvidersResponses = new ArrayList(); + for (Network.Provider serviceProvider : serviceProviders) { + ProviderResponse serviceProviderResponse = _responseGenerator.createNetworkServiceProviderResponse(serviceProvider); + serviceProvidersResponses.add(serviceProviderResponse); + } + + response.setResponses(serviceProvidersResponses); + response.setResponseName(getCommandName()); + this.setResponseObject(response); + } +} diff --git a/api/src/com/cloud/api/commands/UpdateNetworkServiceProviderCmd.java b/api/src/com/cloud/api/commands/UpdateNetworkServiceProviderCmd.java new file mode 100644 index 00000000000..10f2bed556b --- /dev/null +++ b/api/src/com/cloud/api/commands/UpdateNetworkServiceProviderCmd.java @@ -0,0 +1,89 @@ +/** + * Copyright (C) 2011 Citrix Systems, Inc. All rights reserved. + * + * This software is licensed under the GNU General Public License v3 or later. + * + * It is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or any later version. + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + */ + +package com.cloud.api.commands; + +import org.apache.log4j.Logger; + +import com.cloud.api.ApiConstants; +import com.cloud.api.BaseCmd; +import com.cloud.api.Implementation; +import com.cloud.api.Parameter; +import com.cloud.api.ServerApiException; +import com.cloud.api.response.ProviderResponse; +import com.cloud.network.PhysicalNetworkServiceProvider; +import com.cloud.user.Account; + +@Implementation(description="Updates a network serviceProvider of a physical network", responseObject=ProviderResponse.class) +public class UpdateNetworkServiceProviderCmd extends BaseCmd { + public static final Logger s_logger = Logger.getLogger(UpdateNetworkServiceProviderCmd.class.getName()); + + private static final String s_name = "updatenetworkserviceproviderresponse"; + + ///////////////////////////////////////////////////// + //////////////// API parameters ///////////////////// + ///////////////////////////////////////////////////// + @Parameter(name=ApiConstants.ENABLED, type=CommandType.BOOLEAN, description="true/false enable/disable the physical network service provider") + private Boolean enabled; + + @Parameter(name=ApiConstants.ID, type=CommandType.LONG, required=true, description="network service provider id") + private Long id; + + ///////////////////////////////////////////////////// + /////////////////// Accessors /////////////////////// + ///////////////////////////////////////////////////// + + public Boolean isEnabled() { + return enabled; + } + + private Long getId() { + return id; + } + + ///////////////////////////////////////////////////// + /////////////// API Implementation/////////////////// + ///////////////////////////////////////////////////// + + @Override + public String getCommandName() { + return s_name; + } + + @Override + public long getEntityOwnerId() { + return Account.ACCOUNT_ID_SYSTEM; + } + + @Override + public void execute(){ + PhysicalNetworkServiceProvider result = _networkService.updateNetworkServiceProvider(getId(), isEnabled()); + if (result != null) { + ProviderResponse response = _responseGenerator.createNetworkServiceProviderResponse(result); + response.setResponseName(getCommandName()); + this.setResponseObject(response); + }else { + throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to add service provider to physical network"); + } + } + + + + + +} diff --git a/api/src/com/cloud/api/commands/UpdatePhysicalNetworkCmd.java b/api/src/com/cloud/api/commands/UpdatePhysicalNetworkCmd.java new file mode 100644 index 00000000000..5fedbb8e667 --- /dev/null +++ b/api/src/com/cloud/api/commands/UpdatePhysicalNetworkCmd.java @@ -0,0 +1,116 @@ +/** + * Copyright (C) 2011 Citrix Systems, Inc. All rights reserved. + * + * This software is licensed under the GNU General Public License v3 or later. + * + * It is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or any later version. + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + */ + +package com.cloud.api.commands; + +import java.util.List; + +import org.apache.log4j.Logger; + +import com.cloud.api.ApiConstants; +import com.cloud.api.BaseCmd; +import com.cloud.api.Implementation; +import com.cloud.api.Parameter; +import com.cloud.api.ServerApiException; +import com.cloud.api.response.PhysicalNetworkResponse; +import com.cloud.network.PhysicalNetwork; +import com.cloud.user.Account; + +@Implementation(description="Updates a physical network", responseObject=PhysicalNetworkResponse.class) +public class UpdatePhysicalNetworkCmd extends BaseCmd { + public static final Logger s_logger = Logger.getLogger(UpdatePhysicalNetworkCmd.class.getName()); + + private static final String s_name = "updatephysicalnetworkresponse"; + + ///////////////////////////////////////////////////// + //////////////// API parameters ///////////////////// + ///////////////////////////////////////////////////// + + @Parameter(name=ApiConstants.ID, type=CommandType.LONG, required=true, description="physical network id") + private Long id; + + @Parameter(name=ApiConstants.NETWORK_SPEED, type=CommandType.STRING, description="the speed for the physical network[1G/10G]") + private String speed; + + @Parameter(name=ApiConstants.TAGS, type=CommandType.LIST, collectionType=CommandType.STRING, description="Tag the physical network") + private List tags; + + @Parameter(name=ApiConstants.ISOLATION_METHODS, type=CommandType.LIST, collectionType=CommandType.STRING, description="the isolation method for the physical network[VLAN/L3/GRE]") + private List isolationMethods; + + @Parameter(name=ApiConstants.STATE, type=CommandType.STRING, description="Enabled/Disabled") + private String state; + + @Parameter(name=ApiConstants.VLAN, type=CommandType.STRING, description="the VLAN for the physical network") + private String vlan; + + ///////////////////////////////////////////////////// + /////////////////// Accessors /////////////////////// + ///////////////////////////////////////////////////// + + public List getTags() { + return tags; + } + + public List getIsolationMethods() { + return isolationMethods; + } + + public String getNetworkSpeed() { + return speed; + } + + public String getState() { + return state; + } + + public Long getId() { + return id; + } + + public String getVlan() { + return vlan; + } + + ///////////////////////////////////////////////////// + /////////////// API Implementation/////////////////// + ///////////////////////////////////////////////////// + + @Override + public String getCommandName() { + return s_name; + } + + @Override + public long getEntityOwnerId() { + return Account.ACCOUNT_ID_SYSTEM; + } + + @Override + public void execute(){ + PhysicalNetwork result = _networkService.updatePhysicalNetwork(getId(),getNetworkSpeed(), getIsolationMethods(), getTags(), getVlan(), getState()); + if (result != null) { + PhysicalNetworkResponse response = _responseGenerator.createPhysicalNetworkResponse(result); + response.setResponseName(getCommandName()); + this.setResponseObject(response); + }else { + throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to create physical network"); + } + } + +} diff --git a/api/src/com/cloud/api/commands/UpdateZoneCmd.java b/api/src/com/cloud/api/commands/UpdateZoneCmd.java index 9c09cd1ceeb..8826d3cb042 100755 --- a/api/src/com/cloud/api/commands/UpdateZoneCmd.java +++ b/api/src/com/cloud/api/commands/UpdateZoneCmd.java @@ -63,9 +63,6 @@ public class UpdateZoneCmd extends BaseCmd { @Parameter(name=ApiConstants.NAME, type=CommandType.STRING, description="the name of the Zone") private String zoneName; - @Parameter(name=ApiConstants.VLAN, type=CommandType.STRING, description="the VLAN for the Zone") - private String vlan; - @Parameter(name=ApiConstants.IS_PUBLIC, type=CommandType.BOOLEAN, description="updates a private zone to public if set, but not vice-versa") private Boolean isPublic; @@ -116,10 +113,6 @@ public class UpdateZoneCmd extends BaseCmd { return zoneName; } - public String getVlan() { - return vlan; - } - public Boolean isPublic() { return isPublic; } diff --git a/api/src/com/cloud/api/response/PhysicalNetworkResponse.java b/api/src/com/cloud/api/response/PhysicalNetworkResponse.java new file mode 100644 index 00000000000..e61a8348a4c --- /dev/null +++ b/api/src/com/cloud/api/response/PhysicalNetworkResponse.java @@ -0,0 +1,148 @@ +/** + * Copyright (C) 2011 Citrix Systems, Inc. All rights reserved. + * + * This software is licensed under the GNU General Public License v3 or later. + * + * It is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or any later version. + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + */ + +package com.cloud.api.response; + +import java.util.List; + +import com.cloud.api.ApiConstants; +import com.cloud.serializer.Param; +import com.google.gson.annotations.SerializedName; + +public class PhysicalNetworkResponse extends BaseResponse{ + + @SerializedName(ApiConstants.ID) @Param(description="the id of the physical network") + private Long id; + + @SerializedName(ApiConstants.BROADCAST_DOMAIN_RANGE) @Param(description="Broadcast domain range of the physical network") + private String broadcastDomainRange; + + @SerializedName(ApiConstants.ZONE_ID) @Param(description="zone id of the physical network") + private Long zoneId; + + @SerializedName(ApiConstants.STATE) @Param(description="state of the physical network") + private String state; + + @SerializedName(ApiConstants.VLAN) @Param(description="the vlan of the physical network") + private String vlan; + + @SerializedName(ApiConstants.DOMAIN_ID) @Param(description="the domain id of the physical network owner") + private Long domainId; + + @SerializedName(ApiConstants.TAGS) @Param(description="comma separated tag") + private String tags; + + @SerializedName(ApiConstants.ISOLATION_METHODS) @Param(description="isolation methods") + private String isolationMethods; + + @SerializedName(ApiConstants.NETWORK_SPEED) @Param(description="the speed of the physical network") + private String networkSpeed; + + public void setId(Long id) { + this.id = id; + } + + public Long getId() { + return this.id; + } + + public void setZoneId(Long zoneId) { + this.zoneId = zoneId; + } + + public Long getZoneId() { + return this.zoneId; + } + + public void setState(String state) { + this.state = state; + } + + public String getState() { + return this.state; + } + + + public void setDomainId(Long domainId) { + this.domainId = domainId; + } + + public Long getDomainId() { + return this.domainId; + } + + public void setVlan(String vlan) { + this.vlan = vlan; + } + + public String getVlan() { + return this.vlan; + } + + + public void setTags(List tags) { + if (tags == null || tags.size() == 0) { + return; + } + + StringBuilder buf = new StringBuilder(); + for (String tag : tags) { + buf.append(tag).append(","); + } + + this.tags = buf.delete(buf.length()-1, buf.length()).toString(); + } + + public String getTags() { + return tags; + } + + public void setBroadcastDomainRange(String broadcastDomainRange) { + this.broadcastDomainRange = broadcastDomainRange; + } + + public String getBroadcastDomainRange() { + return broadcastDomainRange; + } + + public void setNetworkSpeed(String networkSpeed) { + this.networkSpeed = networkSpeed; + } + + public String getNetworkSpeed() { + return networkSpeed; + } + + public void setIsolationMethods(List isolationMethods) { + if (isolationMethods == null || isolationMethods.size() == 0) { + return; + } + + StringBuilder buf = new StringBuilder(); + for (String isolationMethod : isolationMethods) { + buf.append(isolationMethod).append(","); + } + + this.isolationMethods = buf.delete(buf.length()-1, buf.length()).toString(); + } + + public String getIsolationMethods() { + return isolationMethods; + } + +} diff --git a/api/src/com/cloud/api/response/ProviderResponse.java b/api/src/com/cloud/api/response/ProviderResponse.java index a3cdf811aa6..caf9686d0f4 100644 --- a/api/src/com/cloud/api/response/ProviderResponse.java +++ b/api/src/com/cloud/api/response/ProviderResponse.java @@ -17,8 +17,6 @@ */ package com.cloud.api.response; -import java.util.List; - import com.cloud.api.ApiConstants; import com.cloud.serializer.Param; import com.google.gson.annotations.SerializedName; @@ -29,7 +27,53 @@ public class ProviderResponse extends BaseResponse { @SerializedName(ApiConstants.NAME) @Param(description="the provider name") private String name; + @SerializedName(ApiConstants.PHYSICAL_NETWORK_ID) @Param(description="the physical network this belongs to") + private Long physicalNetworkId; + + @SerializedName(ApiConstants.DEST_PHYSICAL_NETWORK_ID) @Param(description="the destination physical network") + private Long destinationPhysicalNetworkId; + + @SerializedName(ApiConstants.STATE) @Param(description="state of the network provider") + private String state; + + @SerializedName(ApiConstants.ID) @Param(description="id of the network provider") + private Long id; + + public void setName(String name) { this.name = name; } + + public void setPhysicalNetworkId(long physicalNetworkId) { + this.physicalNetworkId = physicalNetworkId; + } + + public long getphysicalNetworkId() { + return physicalNetworkId; + } + + public void setDestinationPhysicalNetworkId(long destPhysicalNetworkId) { + this.destinationPhysicalNetworkId = destPhysicalNetworkId; + } + + public long getDestinationPhysicalNetworkId() { + return destinationPhysicalNetworkId; + } + + public void setState(String state) { + this.state = state; + } + + public String getState() { + return this.state; + } + + public void setId(Long id) { + this.id = id; + } + + public Long getId() { + return this.id; + } + } diff --git a/api/src/com/cloud/dc/DataCenter.java b/api/src/com/cloud/dc/DataCenter.java index 7f90940855a..8ed3bfa8b09 100644 --- a/api/src/com/cloud/dc/DataCenter.java +++ b/api/src/com/cloud/dc/DataCenter.java @@ -41,7 +41,6 @@ public interface DataCenter extends Grouping { Long getDomainId(); String getDescription(); String getDomain(); - String getVnet(); NetworkType getNetworkType(); String getInternalDns1(); diff --git a/api/src/com/cloud/network/Network.java b/api/src/com/cloud/network/Network.java index 14d333dd7a5..9906d8c190e 100644 --- a/api/src/com/cloud/network/Network.java +++ b/api/src/com/cloud/network/Network.java @@ -101,6 +101,10 @@ public interface Network extends ControlledEntity { } return null; } + + public static List listAllServices(){ + return supportedServices; + } } public static class Provider { @@ -265,4 +269,6 @@ public interface Network extends ControlledEntity { Type getType(); boolean getIsShared(); + + long getPhysicalNetworkId(); } diff --git a/api/src/com/cloud/network/NetworkProfile.java b/api/src/com/cloud/network/NetworkProfile.java index 2360058801c..cef307db5ba 100644 --- a/api/src/com/cloud/network/NetworkProfile.java +++ b/api/src/com/cloud/network/NetworkProfile.java @@ -52,6 +52,7 @@ public class NetworkProfile implements Network { private Network.Type type; private GuestIpType guestIpType; private boolean isShared; + private long physicalNetworkId; public NetworkProfile(Network network) { this.id = network.getId(); @@ -76,6 +77,7 @@ public class NetworkProfile implements Network { this.type = network.getType(); this.guestIpType = network.getGuestType(); this.isShared = network.getIsShared(); + this.physicalNetworkId = network.getPhysicalNetworkId(); } @Override @@ -212,4 +214,9 @@ public class NetworkProfile implements Network { public boolean getIsShared() { return isShared; } + + @Override + public long getPhysicalNetworkId() { + return physicalNetworkId; + } } diff --git a/api/src/com/cloud/network/NetworkService.java b/api/src/com/cloud/network/NetworkService.java index 8cfce0ad783..c72e5a2678b 100644 --- a/api/src/com/cloud/network/NetworkService.java +++ b/api/src/com/cloud/network/NetworkService.java @@ -31,6 +31,7 @@ import com.cloud.exception.InsufficientCapacityException; import com.cloud.exception.ResourceAllocationException; import com.cloud.exception.ResourceUnavailableException; import com.cloud.network.Network.Capability; +import com.cloud.network.Network.Provider; import com.cloud.network.Network.Service; import com.cloud.network.Networks.TrafficType; import com.cloud.offering.NetworkOffering; @@ -88,4 +89,24 @@ public interface NetworkService { Network getSystemNetworkByZoneAndTrafficType(long zoneId, TrafficType trafficType); Map> listNetworkOfferingServices(long networkOfferingId); + + PhysicalNetwork createPhysicalNetwork(Long zoneId, String vnetRange, String networkSpeed, List isolationMethods, String broadcastDomainRange, Long domainId, List tags); + + List searchPhysicalNetworks(Long id, Long zoneId, String keyword, Long startIndex, Long pageSize); + + PhysicalNetwork updatePhysicalNetwork(Long id, String networkSpeed, List isolationMethods, List tags, String newVnetRangeString, String state); + + boolean deletePhysicalNetwork(Long id); + + List listNetworkServices(); + + List listSupportedNetworkServiceProviders(String serviceName); + + PhysicalNetworkServiceProvider addProviderToPhysicalNetwork(Long physicalNetworkId, String providerName, Long destinationPhysicalNetworkId); + + List listNetworkServiceProviders(Long physicalNetworkId); + + PhysicalNetworkServiceProvider updateNetworkServiceProvider(Long id, Boolean enabled); + + boolean deleteNetworkServiceProvider(Long id); } diff --git a/api/src/com/cloud/network/PhysicalNetwork.java b/api/src/com/cloud/network/PhysicalNetwork.java new file mode 100644 index 00000000000..f9307f5c1da --- /dev/null +++ b/api/src/com/cloud/network/PhysicalNetwork.java @@ -0,0 +1,68 @@ +/** + * Copyright (C) 2011 Citrix Systems, Inc. All rights reserved. + * + * This software is licensed under the GNU General Public License v3 or later. + * + * It is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or any later version. + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + */ + +/** + * + */ +package com.cloud.network; + +import java.util.List; + +/** + * This defines the specifics of a physical network present in a data center + * + */ +public interface PhysicalNetwork { + + public enum State { + Disabled, + Enabled; + } + + public enum IsolationMethod { + VLAN, + L3, + GRE; + } + + public enum BroadcastDomainRange { + Pod, + Zone; + } + + long getId(); + + BroadcastDomainRange getBroadcastDomainRange(); + + //TrafficType getTrafficType(); + + long getDataCenterId(); + + State getState(); + + List getTags(); + + List getIsolationMethods(); + + Long getDomainId(); + + String getVnet(); + + String getSpeed(); + +} diff --git a/api/src/com/cloud/network/PhysicalNetworkServiceProvider.java b/api/src/com/cloud/network/PhysicalNetworkServiceProvider.java new file mode 100644 index 00000000000..6eb4458c2fc --- /dev/null +++ b/api/src/com/cloud/network/PhysicalNetworkServiceProvider.java @@ -0,0 +1,48 @@ +/** + * Copyright (C) 2011 Citrix Systems, Inc. All rights reserved. + * + * This software is licensed under the GNU General Public License v3 or later. + * + * It is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or any later version. + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + */ + +/** + * + */ +package com.cloud.network; + + + +/** + * This defines the specifics of a physical network service provider + * + */ +public interface PhysicalNetworkServiceProvider { + + public enum State { + Disabled, + Enabled; + } + + long getId(); + + State getState(); + + long getPhysicalNetworkId(); + + String getProviderName(); + + long getDestinationPhysicalNetworkId(); + + void setState(State state); +} diff --git a/client/tomcatconf/commands.properties.in b/client/tomcatconf/commands.properties.in index c9b6485ebc2..45a74b945f5 100755 --- a/client/tomcatconf/commands.properties.in +++ b/client/tomcatconf/commands.properties.in @@ -286,4 +286,18 @@ listFirewallRules=com.cloud.api.commands.ListFirewallRulesCmd;15 #### hypervisor capabilities commands updateHypervisorCapabilities=com.cloud.api.commands.UpdateHypervisorCapabilitiesCmd;1 -listHypervisorCapabilities=com.cloud.api.commands.ListHypervisorCapabilitiesCmd;1 +listHypervisorCapabilities=com.cloud.api.commands.ListHypervisorCapabilitiesCmd;1 + +#### Physical Network commands +createPhysicalNetwork=com.cloud.api.commands.CreatePhysicalNetworkCmd;1 +deletePhysicalNetwork=com.cloud.api.commands.DeletePhysicalNetworkCmd;1 +listPhysicalNetworks=com.cloud.api.commands.ListPhysicalNetworksCmd;1 +updatePhysicalNetwork=com.cloud.api.commands.UpdatePhysicalNetworkCmd;1 + +#### Physical Network Service Provider commands +listNetworkServices=com.cloud.api.commands.ListNetworkServicesCmd;1 +listSupportedNetworkServiceProviders=com.cloud.api.commands.ListSupportedNetworkServiceProvidersCmd;1 +addNetworkServiceProvider=com.cloud.api.commands.AddNetworkServiceProviderCmd;1 +deleteNetworkServiceProvider=com.cloud.api.commands.DeleteNetworkServiceProviderCmd;1 +listNetworkServiceProviders=com.cloud.api.commands.ListNetworkServiceProvidersCmd;1 +updateNetworkServiceProvider=com.cloud.api.commands.UpdateNetworkServiceProviderCmd;1 diff --git a/server/src/com/cloud/api/ApiResponseHelper.java b/server/src/com/cloud/api/ApiResponseHelper.java index d7b0f62e485..3dbbbc56d38 100755 --- a/server/src/com/cloud/api/ApiResponseHelper.java +++ b/server/src/com/cloud/api/ApiResponseHelper.java @@ -62,6 +62,7 @@ import com.cloud.api.response.LoadBalancerResponse; import com.cloud.api.response.NetworkOfferingResponse; import com.cloud.api.response.NetworkResponse; import com.cloud.api.response.NicResponse; +import com.cloud.api.response.PhysicalNetworkResponse; import com.cloud.api.response.PodResponse; import com.cloud.api.response.ProjectAccountResponse; import com.cloud.api.response.ProjectInvitationResponse; @@ -116,9 +117,12 @@ import com.cloud.network.IPAddressVO; import com.cloud.network.IpAddress; import com.cloud.network.Network; import com.cloud.network.Network.Capability; +import com.cloud.network.Network.Provider; import com.cloud.network.Network.Service; import com.cloud.network.NetworkProfile; import com.cloud.network.Networks.TrafficType; +import com.cloud.network.PhysicalNetwork; +import com.cloud.network.PhysicalNetworkServiceProvider; import com.cloud.network.RemoteAccessVpn; import com.cloud.network.VpnUser; import com.cloud.network.router.VirtualRouter; @@ -786,7 +790,6 @@ public class ApiResponseHelper implements ResponseGenerator { zoneResponse.setDns2(dataCenter.getDns2()); zoneResponse.setInternalDns1(dataCenter.getInternalDns1()); zoneResponse.setInternalDns2(dataCenter.getInternalDns2()); - zoneResponse.setVlan(dataCenter.getVnet()); zoneResponse.setGuestCidrAddress(dataCenter.getGuestNetworkCidr()); } @@ -2529,6 +2532,69 @@ public class ApiResponseHelper implements ResponseGenerator { vmResponse.setRole(router.getRole().toString()); } } + vmResponse.setObjectName("systemvminstance"); return vmResponse; } + + @Override + public PhysicalNetworkResponse createPhysicalNetworkResponse(PhysicalNetwork result) { + PhysicalNetworkResponse response = new PhysicalNetworkResponse(); + + response.setZoneId(result.getDataCenterId()); + response.setNetworkSpeed(result.getSpeed()); + response.setVlan(result.getVnet()); + response.setDomainId(result.getDomainId()); + response.setId(result.getId()); + if(result.getBroadcastDomainRange() != null){ + response.setBroadcastDomainRange(result.getBroadcastDomainRange().toString()); + } + response.setIsolationMethods(result.getIsolationMethods()); + response.setTags(result.getTags()); + if(result.getState() != null){ + response.setState(result.getState().toString()); + } + response.setObjectName("physicalnetwork"); + return response; + } + + @Override + public ServiceResponse createNetworkServiceResponse(Service service){ + ServiceResponse response = new ServiceResponse(); + response.setName(service.getName()); + + // set list of capabilities required for the service + List capabilityResponses = new ArrayList(); + Capability[] capabilities = service.getCapabilities(); + for(Capability cap : capabilities){ + CapabilityResponse capabilityResponse = new CapabilityResponse(); + capabilityResponse.setName(cap.getName()); + capabilityResponse.setObjectName("capability"); + capabilityResponses.add(capabilityResponse); + } + response.setCapabilities(capabilityResponses); + + response.setObjectName("networkservice"); + return response; + + } + + @Override + public ProviderResponse createNetworkServiceProviderResponse(Provider serviceProvider) { + ProviderResponse response = new ProviderResponse(); + response.setName(serviceProvider.getName()); + response.setObjectName("networkserviceprovider"); + return response; + } + + @Override + public ProviderResponse createNetworkServiceProviderResponse(PhysicalNetworkServiceProvider result){ + ProviderResponse response = new ProviderResponse(); + response.setId(result.getId()); + response.setName(result.getProviderName()); + response.setPhysicalNetworkId(result.getPhysicalNetworkId()); + response.setDestinationPhysicalNetworkId(result.getDestinationPhysicalNetworkId()); + response.setState(result.getState().toString()); + response.setObjectName("networkserviceprovider"); + return response; + } } diff --git a/server/src/com/cloud/configuration/ConfigurationManager.java b/server/src/com/cloud/configuration/ConfigurationManager.java index be55e52abbf..c951493f1d6 100644 --- a/server/src/com/cloud/configuration/ConfigurationManager.java +++ b/server/src/com/cloud/configuration/ConfigurationManager.java @@ -113,7 +113,6 @@ public interface ConfigurationManager extends ConfigurationService, Manager { * @param dns2 * @param internalDns1 * @param internalDns2 - * @param vnetRange * @param guestCidr * @param zoneType * @param allocationState @@ -122,7 +121,7 @@ public interface ConfigurationManager extends ConfigurationService, Manager { * @throws * @throws */ - DataCenterVO createZone(long userId, String zoneName, String dns1, String dns2, String internalDns1, String internalDns2, String vnetRange, String guestCidr, String domain, Long domainId, NetworkType zoneType, boolean isSecurityGroupEnabled, String allocationState, String networkDomain); + DataCenterVO createZone(long userId, String zoneName, String dns1, String dns2, String internalDns1, String internalDns2, String guestCidr, String domain, Long domainId, NetworkType zoneType, String allocationState, String networkDomain); /** * Deletes a VLAN from the database, along with all of its IP addresses. Will not delete VLANs that have allocated IP addresses. @@ -190,7 +189,7 @@ public interface ConfigurationManager extends ConfigurationService, Manager { Vlan createVlanAndPublicIpRange(Long userId, Long zoneId, Long podId, String startIP, String endIP, String vlanGateway, String vlanNetmask, boolean forVirtualNetwork, String vlanId, Account account, Long networkId) throws InsufficientCapacityException, ConcurrentOperationException, InvalidParameterValueException; - void createDefaultNetworks(long zoneId, boolean isSecurityGroupEnabled) throws ConcurrentOperationException; + void createDefaultNetworks(long zoneId) throws ConcurrentOperationException; HostPodVO getPod(long id); diff --git a/server/src/com/cloud/configuration/ConfigurationManagerImpl.java b/server/src/com/cloud/configuration/ConfigurationManagerImpl.java index e41b95a7cc0..691ecf367b8 100755 --- a/server/src/com/cloud/configuration/ConfigurationManagerImpl.java +++ b/server/src/com/cloud/configuration/ConfigurationManagerImpl.java @@ -129,7 +129,6 @@ import com.cloud.user.UserContext; import com.cloud.user.dao.AccountDao; import com.cloud.user.dao.UserDao; import com.cloud.utils.NumbersUtil; -import com.cloud.utils.Pair; import com.cloud.utils.StringUtils; import com.cloud.utils.component.Adapters; import com.cloud.utils.component.ComponentLocator; @@ -962,10 +961,6 @@ public class ConfigurationManagerImpl implements ConfigurationManager, Configura return !vmInstances.isEmpty(); } - private boolean zoneHasAllocatedVnets(long zoneId) { - return !_zoneDao.listAllocatedVnets(zoneId).isEmpty(); - } - @DB protected void checkIfZoneIsDeletable(long zoneId) { List> tablesToCheck = new ArrayList>(); @@ -1185,7 +1180,6 @@ public class ConfigurationManagerImpl implements ConfigurationManager, Configura String dns2 = cmd.getDns2(); String internalDns1 = cmd.getInternalDns1(); String internalDns2 = cmd.getInternalDns2(); - String newVnetRangeString = cmd.getVlan(); String guestCidr = cmd.getGuestCidrAddress(); List dnsSearchOrder = cmd.getDnsSearchOrder(); Boolean isPublic = cmd.isPublic(); @@ -1234,15 +1228,6 @@ public class ConfigurationManagerImpl implements ConfigurationManager, Configura zoneName = zone.getName(); } - // if zone is of Basic type, don't allow to add vnet range and cidr - if (zone.getNetworkType() == NetworkType.Basic) { - if (newVnetRangeString != null) { - throw new InvalidParameterValueException("Can't add vnet range for the zone that supports " + zone.getNetworkType() + " network"); - } else if (guestCidr != null) { - throw new InvalidParameterValueException("Can't add cidr for the zone that supports " + zone.getNetworkType() + " network"); - } - } - if ((guestCidr != null) && !NetUtils.validateGuestCidr(guestCidr)) { throw new InvalidParameterValueException("Please enter a valid guest cidr"); } @@ -1252,63 +1237,6 @@ public class ConfigurationManagerImpl implements ConfigurationManager, Configura throw new InvalidParameterValueException("A zone with ID: " + zoneId + " does not exist."); } - // Vnet range can be extended only - boolean replaceVnet = false; - ArrayList> vnetsToAdd = new ArrayList>(2); - - if (newVnetRangeString != null) { - Integer newStartVnet = 0; - Integer newEndVnet = 0; - String[] newVnetRange = newVnetRangeString.split("-"); - - if (newVnetRange.length < 2) { - throw new InvalidParameterValueException("Please provide valid vnet range between 0-4096"); - } - - if (newVnetRange[0] == null || newVnetRange[1] == null) { - throw new InvalidParameterValueException("Please provide valid vnet range between 0-4096"); - } - - try { - newStartVnet = Integer.parseInt(newVnetRange[0]); - newEndVnet = Integer.parseInt(newVnetRange[1]); - } catch (NumberFormatException e) { - s_logger.warn("Unable to parse vnet range:", e); - throw new InvalidParameterValueException("Please provide valid vnet range between 0-4096"); - } - - if (newStartVnet < 0 || newEndVnet > 4096) { - throw new InvalidParameterValueException("Vnet range has to be between 0-4096"); - } - - if (newStartVnet > newEndVnet) { - throw new InvalidParameterValueException("Vnet range has to be between 0-4096 and start range should be lesser than or equal to stop range"); - } - - if (zoneHasAllocatedVnets(zoneId)) { - String[] existingRange = zone.getVnet().split("-"); - int existingStartVnet = Integer.parseInt(existingRange[0]); - int existingEndVnet = Integer.parseInt(existingRange[1]); - - //check if vnet is being extended - if (!(newStartVnet.intValue() <= existingStartVnet && newEndVnet.intValue() >= existingEndVnet)) { - throw new InvalidParameterValueException("Can's shrink existing vnet range as it the range has vnets allocated. Only extending existing vnet is supported"); - } - - if (newStartVnet < existingStartVnet) { - vnetsToAdd.add(new Pair(newStartVnet, existingStartVnet - 1)); - } - - if (newEndVnet > existingEndVnet) { - vnetsToAdd.add(new Pair(existingEndVnet + 1, newEndVnet)); - } - - } else { - vnetsToAdd.add(new Pair(newStartVnet, newEndVnet)); - replaceVnet = true; - } - } - String oldZoneName = zone.getName(); if (zoneName == null) { @@ -1362,10 +1290,6 @@ public class ConfigurationManagerImpl implements ConfigurationManager, Configura zone.setGuestNetworkCidr(guestCidr); zone.setDomain(networkDomain); - if (newVnetRangeString != null) { - zone.setVnet(newVnetRangeString); - } - // update a private zone to public; not vice versa if (isPublic != null && isPublic) { zone.setDomainId(null); @@ -1396,44 +1320,14 @@ public class ConfigurationManagerImpl implements ConfigurationManager, Configura throw new CloudRuntimeException("Failed to edit zone. Please contact Cloud Support."); } - if (replaceVnet) { - s_logger.debug("Deleting existing vnet range for the zone id=" + zoneId + " as a part of updateZone call"); - _zoneDao.deleteVnet(zoneId); - } - - for (Pair vnetToAdd : vnetsToAdd) { - s_logger.debug("Adding vnet range " + vnetToAdd.first() + "-" + vnetToAdd.second() + " for the zone id=" + zoneId + " as a part of updateZone call"); - _zoneDao.addVnet(zone.getId(), vnetToAdd.first(), vnetToAdd.second()); - } - txn.commit(); return zone; } @Override @DB - public DataCenterVO createZone(long userId, String zoneName, String dns1, String dns2, String internalDns1, String internalDns2, String vnetRange, String guestCidr, String domain, Long domainId, - NetworkType zoneType, boolean isSecurityGroupEnabled, String allocationStateStr, String networkDomain) { - int vnetStart = 0; - int vnetEnd = 0; - if (vnetRange != null) { - String[] tokens = vnetRange.split("-"); - try { - vnetStart = Integer.parseInt(tokens[0]); - if (tokens.length == 1) { - vnetEnd = vnetStart; - } else { - vnetEnd = Integer.parseInt(tokens[1]); - } - } catch (NumberFormatException e) { - throw new InvalidParameterValueException("Please specify valid integers for the vlan range."); - } - - if ((vnetStart > vnetEnd) || (vnetStart < 0) || (vnetEnd > 4096)) { - s_logger.warn("Invalid vnet range: start range:" + vnetStart + " end range:" + vnetEnd); - throw new InvalidParameterValueException("Vnet range should be between 0-4096 and start range should be lesser than or equal to end range"); - } - } + public DataCenterVO createZone(long userId, String zoneName, String dns1, String dns2, String internalDns1, String internalDns2, String guestCidr, String domain, Long domainId, + NetworkType zoneType, String allocationStateStr, String networkDomain) { // checking the following params outside checkzoneparams method as we do not use these params for updatezone // hence the method below is generic to check for common params @@ -1458,20 +1352,15 @@ public class ConfigurationManagerImpl implements ConfigurationManager, Configura try { txn.start(); // Create the new zone in the database - DataCenterVO zone = new DataCenterVO(zoneName, null, dns1, dns2, internalDns1, internalDns2, vnetRange, guestCidr, domain, domainId, zoneType, isSecurityGroupEnabled, zoneToken, networkDomain); + DataCenterVO zone = new DataCenterVO(zoneName, null, dns1, dns2, internalDns1, internalDns2, guestCidr, domain, domainId, zoneType, zoneToken, networkDomain); if (allocationStateStr != null && !allocationStateStr.isEmpty()) { Grouping.AllocationState allocationState = Grouping.AllocationState.valueOf(allocationStateStr); zone.setAllocationState(allocationState); } zone = _zoneDao.persist(zone); - // Add vnet entries for the new zone if zone type is Advanced - if (vnetRange != null) { - _zoneDao.addVnet(zone.getId(), vnetStart, vnetEnd); - } - // Create deafult networks - createDefaultNetworks(zone.getId(), isSecurityGroupEnabled); + createDefaultNetworks(zone.getId()); txn.commit(); return zone; } catch (Exception ex) { @@ -1484,7 +1373,7 @@ public class ConfigurationManagerImpl implements ConfigurationManager, Configura } @Override - public void createDefaultNetworks(long zoneId, boolean isSecurityGroupEnabled) throws ConcurrentOperationException { + public void createDefaultNetworks(long zoneId) throws ConcurrentOperationException { DataCenterVO zone = _zoneDao.findById(zoneId); String networkDomain = null; // Create public, management, control and storage networks as a part of the zone creation @@ -1509,7 +1398,7 @@ public class ConfigurationManagerImpl implements ConfigurationManager, Configura } else { continue; } - } else if (offering.getTrafficType() == TrafficType.Guest) { + } /*else if (offering.getTrafficType() == TrafficType.Guest) { if (zone.getNetworkType() == NetworkType.Basic) { isNetworkDefault = true; broadcastDomainType = BroadcastDomainType.Native; @@ -1522,7 +1411,7 @@ public class ConfigurationManagerImpl implements ConfigurationManager, Configura } networkDomain = "cs" + Long.toHexString(Account.ACCOUNT_ID_SYSTEM) + _networkMgr.getGlobalGuestDomainSuffix(); - } + }*/ userNetwork.setBroadcastDomainType(broadcastDomainType); userNetwork.setNetworkDomain(networkDomain); _networkMgr.setupNetwork(systemAccount, offering, userNetwork, plan, null, null, isNetworkDefault, false, null, null, true); @@ -1539,7 +1428,6 @@ public class ConfigurationManagerImpl implements ConfigurationManager, Configura String dns2 = cmd.getDns2(); String internalDns1 = cmd.getInternalDns1(); String internalDns2 = cmd.getInternalDns2(); - String vnetRange = cmd.getVlan(); String guestCidr = cmd.getGuestCidrAddress(); Long domainId = cmd.getDomainId(); String type = cmd.getNetworkType(); @@ -1557,16 +1445,14 @@ public class ConfigurationManagerImpl implements ConfigurationManager, Configura isBasic = true; } - Boolean securityGroupEnabled = cmd.isSecurityGroupEnabled(); - NetworkType zoneType = isBasic ? NetworkType.Basic : NetworkType.Advanced; - // Guest cidr is required for Advanced zone creation; error out when the parameter specified for Basic zone + /*Guest cidr is required for Advanced zone creation; error out when the parameter specified for Basic zone if (zoneType == NetworkType.Advanced && guestCidr == null && !securityGroupEnabled) { throw new InvalidParameterValueException("guestCidrAddress parameter is required for Advanced zone creation"); } else if (zoneType == NetworkType.Basic && guestCidr != null) { throw new InvalidParameterValueException("guestCidrAddress parameter is not supported for Basic zone"); - } + }*/ DomainVO domainVO = null; @@ -1578,17 +1464,16 @@ public class ConfigurationManagerImpl implements ConfigurationManager, Configura domainVO = _domainDao.findById(domainId); } - // Verify zone type + /* Verify zone type if (zoneType == NetworkType.Basic && vnetRange != null) { vnetRange = null; } if (zoneType == NetworkType.Basic) { securityGroupEnabled = true; - } + }*/ - return createZone(userId, zoneName, dns1, dns2, internalDns1, internalDns2, vnetRange, guestCidr, domainVO != null ? domainVO.getName() : null, domainId, zoneType, securityGroupEnabled, - allocationState, networkDomain); + return createZone(userId, zoneName, dns1, dns2, internalDns1, internalDns2, guestCidr, domainVO != null ? domainVO.getName() : null, domainId, zoneType, allocationState, networkDomain); } @Override @@ -2149,10 +2034,11 @@ public class ConfigurationManagerImpl implements ConfigurationManager, Configura throw new InvalidParameterValueException("Only Direct Untagged and Virtual networks are supported in the zone " + zone.getId() + " of type " + zone.getNetworkType()); } - // don't allow to create a virtual vlan when zone's vnet is NULL in Advanced zone + //TODO + /* don't allow to create a virtual vlan when zone's vnet is NULL in Advanced zone if ((zone.getNetworkType() == NetworkType.Advanced && zone.getVnet() == null) && forVirtualNetwork) { throw new InvalidParameterValueException("Can't add virtual network to the zone id=" + zone.getId() + " as zone doesn't have guest vlan configured"); - } + }*/ VlanType vlanType = forVirtualNetwork ? VlanType.VirtualNetwork : VlanType.DirectAttached; diff --git a/server/src/com/cloud/configuration/DefaultComponentLibrary.java b/server/src/com/cloud/configuration/DefaultComponentLibrary.java index 598071804f6..1806dfebd5d 100755 --- a/server/src/com/cloud/configuration/DefaultComponentLibrary.java +++ b/server/src/com/cloud/configuration/DefaultComponentLibrary.java @@ -80,6 +80,8 @@ import com.cloud.network.dao.LoadBalancerVMMapDaoImpl; import com.cloud.network.dao.NetworkDaoImpl; import com.cloud.network.dao.NetworkDomainDaoImpl; import com.cloud.network.dao.NetworkRuleConfigDaoImpl; +import com.cloud.network.dao.PhysicalNetworkDaoImpl; +import com.cloud.network.dao.PhysicalNetworkServiceProviderDaoImpl; import com.cloud.network.dao.RemoteAccessVpnDaoImpl; import com.cloud.network.dao.VpnUserDaoImpl; import com.cloud.network.firewall.FirewallManagerImpl; @@ -285,6 +287,8 @@ public class DefaultComponentLibrary extends ComponentLibraryBase implements Com info = addDao("HypervisorCapabilitiesDao",HypervisorCapabilitiesDaoImpl.class); info.addParameter("cache.size", "100"); info.addParameter("cache.time.to.live", "600"); + addDao("PhysicalNetworkDao", PhysicalNetworkDaoImpl.class); + addDao("PhysicalNetworkServiceProviderDao", PhysicalNetworkServiceProviderDaoImpl.class); } @Override diff --git a/server/src/com/cloud/dc/DataCenterVO.java b/server/src/com/cloud/dc/DataCenterVO.java index d8900b9460d..45b9491cd84 100644 --- a/server/src/com/cloud/dc/DataCenterVO.java +++ b/server/src/com/cloud/dc/DataCenterVO.java @@ -67,9 +67,6 @@ public class DataCenterVO implements DataCenter { @Column(name="router_mac_address", updatable = false, nullable=false) private String routerMacAddress = "02:00:00:00:00:01"; - @Column(name="vnet") - private String vnet = null; - @Column(name="guest_network_cidr") private String guestNetworkCidr = null; @@ -104,9 +101,6 @@ public class DataCenterVO implements DataCenter { @Column(name="firewall_provider") private String firewallProvider; - @Column(name="is_security_group_enabled") - boolean securityGroupEnabled; - @Column(name="mac_address", updatable = false, nullable=false) @TableGenerator(name="mac_address_sq", table="data_center", pkColumnName="id", valueColumnName="mac_address", allocationSize=1) private long macAddress = 1; @@ -172,26 +166,24 @@ public class DataCenterVO implements DataCenter { this.firewallProvider = firewallProvider; } - public DataCenterVO(long id, String name, String description, String dns1, String dns2, String dns3, String dns4, String vnet, String guestCidr, String domain, Long domainId, NetworkType zoneType, String zoneToken, String domainSuffix) { - this(name, description, dns1, dns2, dns3, dns4, vnet, guestCidr, domain, domainId, zoneType, false, zoneToken, domainSuffix); + public DataCenterVO(long id, String name, String description, String dns1, String dns2, String dns3, String dns4, String guestCidr, String domain, Long domainId, NetworkType zoneType, String zoneToken, String domainSuffix) { + this(name, description, dns1, dns2, dns3, dns4, guestCidr, domain, domainId, zoneType, zoneToken, domainSuffix); this.id = id; this.allocationState = Grouping.AllocationState.Enabled; } - public DataCenterVO(String name, String description, String dns1, String dns2, String dns3, String dns4, String vnet, String guestCidr, String domain, Long domainId, NetworkType zoneType, boolean securityGroupEnabled, String zoneToken, String domainSuffix) { + public DataCenterVO(String name, String description, String dns1, String dns2, String dns3, String dns4, String guestCidr, String domain, Long domainId, NetworkType zoneType, String zoneToken, String domainSuffix) { this.name = name; this.description = description; this.dns1 = dns1; this.dns2 = dns2; this.internalDns1 = dns3; this.internalDns2 = dns4; - this.vnet = vnet; this.guestNetworkCidr = guestCidr; this.domain = domain; this.domainId = domainId; this.networkType = zoneType; this.allocationState = Grouping.AllocationState.Enabled; - this.securityGroupEnabled = securityGroupEnabled; if (zoneType == NetworkType.Advanced) { loadBalancerProvider = Provider.VirtualRouter.getName(); @@ -248,20 +240,11 @@ public class DataCenterVO implements DataCenter { return routerMacAddress; } - public void setVnet(String vnet) { - this.vnet = vnet; - } - @Override public String getDns1() { return dns1; } - @Override - public String getVnet() { - return vnet; - } - @Override public String getDns2() { return dns2; @@ -345,11 +328,10 @@ public class DataCenterVO implements DataCenter { @Override public boolean isSecurityGroupEnabled() { - return securityGroupEnabled; + return false; } public void setSecurityGroupEnabled(boolean enabled) { - this.securityGroupEnabled = enabled; } @Override diff --git a/server/src/com/cloud/dc/DataCenterVnetVO.java b/server/src/com/cloud/dc/DataCenterVnetVO.java index 6b926f5baf7..8a8db549037 100755 --- a/server/src/com/cloud/dc/DataCenterVnetVO.java +++ b/server/src/com/cloud/dc/DataCenterVnetVO.java @@ -43,7 +43,10 @@ public class DataCenterVnetVO { @Column(name="vnet", updatable=false, nullable=false) protected String vnet; - + + @Column(name="physical_network_id", updatable=false, nullable=false) + protected long physicalNetworkId; + @Column(name="data_center_id", updatable=false, nullable=false) protected long dataCenterId; @@ -61,9 +64,10 @@ public class DataCenterVnetVO { this.takenAt = taken; } - public DataCenterVnetVO(String vnet, long dcId) { + public DataCenterVnetVO(String vnet, long dcId, long physicalNetworkId) { this.vnet = vnet; this.dataCenterId = dcId; + this.physicalNetworkId = physicalNetworkId; this.takenAt = null; } @@ -94,6 +98,10 @@ public class DataCenterVnetVO { public long getDataCenterId() { return dataCenterId; } + + public long getPhysicalNetworkId() { + return physicalNetworkId; + } protected DataCenterVnetVO() { } diff --git a/server/src/com/cloud/dc/dao/DataCenterDao.java b/server/src/com/cloud/dc/dao/DataCenterDao.java index ec8588dfbbf..c5bed6aaa80 100644 --- a/server/src/com/cloud/dc/dao/DataCenterDao.java +++ b/server/src/com/cloud/dc/dao/DataCenterDao.java @@ -36,9 +36,9 @@ public interface DataCenterDao extends GenericDao { String[] getNextAvailableMacAddressPair(long id, long mask); Pair allocatePrivateIpAddress(long id, long podId, long instanceId, String reservationId); String allocateLinkLocalIpAddress(long id, long podId, long instanceId, String reservationId); - String allocateVnet(long dcId, long accountId, String reservationId); + String allocateVnet(long dcId, long physicalNetworkId, long accountId, String reservationId); - void releaseVnet(String vnet, long dcId, long accountId, String reservationId); + void releaseVnet(String vnet, long dcId, long physicalNetworkId, long accountId, String reservationId); void releasePrivateIpAddress(String ipAddress, long dcId, Long instanceId); void releasePrivateIpAddress(long nicId, String reservationId); void releaseLinkLocalIpAddress(String ipAddress, long dcId, Long instanceId); @@ -52,11 +52,7 @@ public interface DataCenterDao extends GenericDao { List findVnet(long dcId, String vnet); - void addVnet(long dcId, int start, int end); - void deleteVnet(long dcId); - - List listAllocatedVnets(long dcId); String allocatePodVlan(long podId, long accountId); @@ -66,8 +62,6 @@ public interface DataCenterDao extends GenericDao { List findChildZones(Object[] ids); - List listSecurityGroupEnabledZones(); - void loadDetails(DataCenterVO zone); void saveDetails(DataCenterVO zone); @@ -75,4 +69,8 @@ public interface DataCenterDao extends GenericDao { List listEnabledZones(); DataCenterVO findByToken(String zoneToken); DataCenterVO findByTokenOrIdOrName(String tokenIdOrName); + + void addVnet(long dcId, long physicalNetworkId, int start, int end); + void deleteVnet(long dcId, long physicalNetworkId); + List listAllocatedVnets(long dcId, long physicalNetworkId); } diff --git a/server/src/com/cloud/dc/dao/DataCenterDaoImpl.java b/server/src/com/cloud/dc/dao/DataCenterDaoImpl.java index 1cca111a85c..1e6cec93d89 100644 --- a/server/src/com/cloud/dc/dao/DataCenterDaoImpl.java +++ b/server/src/com/cloud/dc/dao/DataCenterDaoImpl.java @@ -32,7 +32,6 @@ import com.cloud.dc.DataCenterIpAddressVO; import com.cloud.dc.DataCenterLinkLocalIpAddressVO; import com.cloud.dc.DataCenterVO; import com.cloud.dc.DataCenterVnetVO; -import com.cloud.dc.HostPodVO; import com.cloud.dc.PodVlanVO; import com.cloud.org.Grouping; import com.cloud.utils.NumbersUtil; @@ -61,7 +60,6 @@ public class DataCenterDaoImpl extends GenericDaoBase implem protected SearchBuilder ListZonesByDomainIdSearch; protected SearchBuilder PublicZonesSearch; protected SearchBuilder ChildZonesSearch; - protected SearchBuilder securityGroupSearch; protected SearchBuilder DisabledZonesSearch; protected SearchBuilder TokenSearch; @@ -112,15 +110,8 @@ public class DataCenterDaoImpl extends GenericDaoBase implem } @Override - public List listSecurityGroupEnabledZones() { - SearchCriteria sc = securityGroupSearch.create(); - sc.setParameters("isSgEnabled", true); - return listBy(sc); - } - - @Override - public void releaseVnet(String vnet, long dcId, long accountId, String reservationId) { - _vnetAllocDao.release(vnet, dcId, accountId, reservationId); + public void releaseVnet(String vnet, long dcId, long physicalNetworkId, long accountId, String reservationId) { + _vnetAllocDao.release(vnet, dcId, physicalNetworkId, accountId, reservationId); } @Override @@ -159,8 +150,8 @@ public class DataCenterDaoImpl extends GenericDaoBase implem } @Override - public String allocateVnet(long dataCenterId, long accountId, String reservationId) { - DataCenterVnetVO vo = _vnetAllocDao.take(dataCenterId, accountId, reservationId); + public String allocateVnet(long dataCenterId, long physicalNetworkId, long accountId, String reservationId) { + DataCenterVnetVO vo = _vnetAllocDao.take(dataCenterId, physicalNetworkId, accountId, reservationId); if (vo == null) { return null; } @@ -214,21 +205,28 @@ public class DataCenterDaoImpl extends GenericDaoBase implem return vo.getIpAddress(); } - @Override - public void addVnet(long dcId, int start, int end) { - _vnetAllocDao.add(dcId, start, end); - } @Override public void deleteVnet(long dcId) { _vnetAllocDao.delete(dcId); } + @Override - public List listAllocatedVnets(long dcId) { - return _vnetAllocDao.listAllocatedVnets(dcId); + public void addVnet(long dcId, long physicalNetworkId, int start, int end) { + _vnetAllocDao.add(dcId, physicalNetworkId, start, end); } + @Override + public void deleteVnet(long dcId, long physicalNetworkId) { + _vnetAllocDao.delete(dcId, physicalNetworkId); + } + + @Override + public List listAllocatedVnets(long dcId, long physicalNetworkId) { + return _vnetAllocDao.listAllocatedVnets(dcId, physicalNetworkId); + } + @Override public void addPrivateIpAddress(long dcId,long podId, String start, String end) { _ipAllocDao.addIpRange(dcId, podId, start, end); @@ -276,10 +274,6 @@ public class DataCenterDaoImpl extends GenericDaoBase implem ChildZonesSearch.and("domainid", ChildZonesSearch.entity().getDomainId(), SearchCriteria.Op.IN); ChildZonesSearch.done(); - securityGroupSearch = createSearchBuilder(); - securityGroupSearch.and("isSgEnabled", securityGroupSearch.entity().isSecurityGroupEnabled(), SearchCriteria.Op.EQ); - securityGroupSearch.done(); - DisabledZonesSearch = createSearchBuilder(); DisabledZonesSearch.and("allocationState", DisabledZonesSearch.entity().getAllocationState(), SearchCriteria.Op.EQ); DisabledZonesSearch.done(); diff --git a/server/src/com/cloud/dc/dao/DataCenterVnetDaoImpl.java b/server/src/com/cloud/dc/dao/DataCenterVnetDaoImpl.java index efd1248b5f8..0c833a8a9c6 100755 --- a/server/src/com/cloud/dc/dao/DataCenterVnetDaoImpl.java +++ b/server/src/com/cloud/dc/dao/DataCenterVnetDaoImpl.java @@ -33,7 +33,7 @@ import com.cloud.utils.exception.CloudRuntimeException; /** * DataCenterVnetDaoImpl maintains the one-to-many relationship between - * data center and the vnet that appears within its network. + * data center/physical_network and the vnet that appears within the physical network. */ @DB(txn=false) public class DataCenterVnetDaoImpl extends GenericDaoBase implements GenericDao { @@ -47,7 +47,14 @@ public class DataCenterVnetDaoImpl extends GenericDaoBase listAllocatedVnets(long dcId, long physicalNetworkId) { + SearchCriteria sc = DcSearchAllocated.create(); + sc.setParameters("dc", dcId); + sc.setParameters("physicalNetworkId", physicalNetworkId); + return listBy(sc); + } + public List findVnet(long dcId, String vnet) { SearchCriteria sc = VnetDcSearch.create();; sc.setParameters("dc", dcId); @@ -55,9 +62,18 @@ public class DataCenterVnetDaoImpl extends GenericDaoBase findVnet(long dcId, long physicalNetworkId, String vnet) { + SearchCriteria sc = VnetDcSearch.create(); + sc.setParameters("dc", dcId); + sc.setParameters("physicalNetworkId", physicalNetworkId); + sc.setParameters("vnet", vnet); + + return listBy(sc); + } + @DB - public void add(long dcId, int start, int end) { - String insertVnet = "INSERT INTO `cloud`.`op_dc_vnet_alloc` (vnet, data_center_id) VALUES ( ?, ?)"; + public void add(long dcId, long physicalNetworkId, int start, int end) { + String insertVnet = "INSERT INTO `cloud`.`op_dc_vnet_alloc` (vnet, data_center_id, physical_network_id) VALUES ( ?, ?, ?)"; Transaction txn = Transaction.currentTxn(); try { @@ -66,6 +82,7 @@ public class DataCenterVnetDaoImpl extends GenericDaoBase sc = VnetDcSearch.create(); sc.setParameters("dc", dcId); + remove(sc); + } + + public void delete(long dcId, long physicalNetworkId) { + SearchCriteria sc = VnetDcSearch.create(); + sc.setParameters("dc", dcId); + sc.setParameters("physicalNetworkId", physicalNetworkId); remove(sc); } @DB - public DataCenterVnetVO take(long dcId, long accountId, String reservationId) { + public DataCenterVnetVO take(long dcId, long physicalNetworkId, long accountId, String reservationId) { SearchCriteria sc = FreeVnetSearch.create(); sc.setParameters("dc", dcId); + sc.setParameters("physicalNetworkId", physicalNetworkId); Date now = new Date(); Transaction txn = Transaction.currentTxn(); txn.start(); @@ -102,10 +127,11 @@ public class DataCenterVnetDaoImpl extends GenericDaoBase sc = VnetDcSearchAllocated.create(); sc.setParameters("vnet", vnet); sc.setParameters("dc", dcId); + sc.setParameters("physicalNetworkId", physicalNetworkId); sc.setParameters("account", accountId); sc.setParameters("reservation", reservationId); @@ -124,25 +150,30 @@ public class DataCenterVnetDaoImpl extends GenericDaoBase _systemNetworks = new HashMap(5); @@ -3389,4 +3398,475 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag return true; } + + @Override + @DB + public PhysicalNetwork createPhysicalNetwork(Long zoneId, String vnetRange, String networkSpeed, List isolationMethods, String broadcastDomainRangeStr, Long domainId, List tags) { + // Check if zone exists + if (zoneId == null) { + throw new InvalidParameterValueException("Please specify a valid zone."); + } + + DataCenterVO zone = _dcDao.findById(zoneId); + if (zone == null) { + throw new InvalidParameterValueException("Please specify a valid zone."); + } + + if (tags != null && tags.size() > 1) { + throw new InvalidParameterException("Only one tag can be specified for a physical network at this time"); + } + + if (isolationMethods != null && isolationMethods.size() > 1) { + throw new InvalidParameterException("Only one isolationMethod can be specified for a physical network at this time"); + } + + int vnetStart = 0; + int vnetEnd = 0; + if (vnetRange != null) { + String[] tokens = vnetRange.split("-"); + try { + vnetStart = Integer.parseInt(tokens[0]); + if (tokens.length == 1) { + vnetEnd = vnetStart; + } else { + vnetEnd = Integer.parseInt(tokens[1]); + } + } catch (NumberFormatException e) { + throw new InvalidParameterValueException("Please specify valid integers for the vlan range."); + } + + if ((vnetStart > vnetEnd) || (vnetStart < 0) || (vnetEnd > 4096)) { + s_logger.warn("Invalid vnet range: start range:" + vnetStart + " end range:" + vnetEnd); + throw new InvalidParameterValueException("Vnet range should be between 0-4096 and start range should be lesser than or equal to end range"); + } + } + + BroadcastDomainRange broadcastDomainRange = null; + if (broadcastDomainRangeStr != null && !broadcastDomainRangeStr.isEmpty()) { + try { + broadcastDomainRange = PhysicalNetwork.BroadcastDomainRange.valueOf(broadcastDomainRangeStr); + } catch (IllegalArgumentException ex) { + throw new InvalidParameterValueException("Unable to resolve broadcastDomainRange '" + broadcastDomainRangeStr + "' to a supported value {Pod or Zone}"); + } + } + + + Transaction txn = Transaction.currentTxn(); + try { + txn.start(); + // Create the new physical network in the database + PhysicalNetworkVO pNetwork = new PhysicalNetworkVO(zoneId, vnetRange, networkSpeed, domainId, broadcastDomainRange); + pNetwork.setTags(tags); + pNetwork.setIsolationMethods(isolationMethods); + + pNetwork = _physicalNetworkDao.persist(pNetwork); + + // Add vnet entries for the new zone if zone type is Advanced + if (vnetRange != null) { + _dcDao.addVnet(zone.getId(), pNetwork.getId(), vnetStart, vnetEnd); + } + + txn.commit(); + return pNetwork; + } catch (Exception ex) { + txn.rollback(); + s_logger.warn("Exception: ", ex); + throw new CloudRuntimeException("Fail to create a physical network"); + } finally { + txn.close(); + } + } + + @Override + public List searchPhysicalNetworks(Long id, Long zoneId, String keyword, Long startIndex, Long pageSize){ + Filter searchFilter = new Filter(PhysicalNetworkVO.class, "id", Boolean.TRUE, startIndex, pageSize); + SearchCriteria sc = _physicalNetworkDao.createSearchCriteria(); + + if (id != null) { + sc.addAnd("id", SearchCriteria.Op.EQ, id); + } + + if (zoneId != null) { + sc.addAnd("dataCenterId", SearchCriteria.Op.EQ, zoneId); + } + return _physicalNetworkDao.search(sc, searchFilter); + } + + @Override + @DB + public PhysicalNetwork updatePhysicalNetwork(Long id, String networkSpeed, List isolationMethods, List tags, String newVnetRangeString, String state) { + + // verify input parameters + PhysicalNetworkVO network = _physicalNetworkDao.findById(id); + if (network == null) { + throw new InvalidParameterValueException("Network id=" + id + "doesn't exist in the system"); + } + + if (tags != null && tags.size() > 1) { + throw new InvalidParameterException("Unable to support more than one tag on network yet"); + } + + if (isolationMethods != null && isolationMethods.size() > 1) { + throw new InvalidParameterException("Only one isolationMethod can be specified for a physical network at this time"); + } + + PhysicalNetwork.State networkState = null; + if (state != null && !state.isEmpty()) { + try { + networkState = PhysicalNetwork.State.valueOf(state); + } catch (IllegalArgumentException ex) { + throw new InvalidParameterValueException("Unable to resolve state '" + state + "' to a supported value {Enabled or Disabled}"); + } + } + + if(state != null){ + network.setState(networkState); + } + + if (tags != null) { + network.setTags(tags); + } + + if (isolationMethods != null) { + for(String isMethod : isolationMethods){ + PhysicalNetwork.IsolationMethod isolationMethodVal = null; + if (isMethod != null && !isMethod.isEmpty()) { + try { + isolationMethodVal = PhysicalNetwork.IsolationMethod.valueOf(isMethod); + } catch (IllegalArgumentException ex) { + throw new InvalidParameterValueException("Unable to resolve IsolationMethod '" + isMethod + "' to a supported value {VLAN or L3 or GRE}"); + } + } + } + + network.setIsolationMethods(isolationMethods); + } + + if(networkSpeed != null){ + network.setSpeed(networkSpeed); + } + + // Vnet range can be extended only + boolean replaceVnet = false; + ArrayList> vnetsToAdd = new ArrayList>(2); + + if (newVnetRangeString != null) { + Integer newStartVnet = 0; + Integer newEndVnet = 0; + String[] newVnetRange = newVnetRangeString.split("-"); + + if (newVnetRange.length < 2) { + throw new InvalidParameterValueException("Please provide valid vnet range between 0-4096"); + } + + if (newVnetRange[0] == null || newVnetRange[1] == null) { + throw new InvalidParameterValueException("Please provide valid vnet range between 0-4096"); + } + + try { + newStartVnet = Integer.parseInt(newVnetRange[0]); + newEndVnet = Integer.parseInt(newVnetRange[1]); + } catch (NumberFormatException e) { + s_logger.warn("Unable to parse vnet range:", e); + throw new InvalidParameterValueException("Please provide valid vnet range between 0-4096"); + } + + if (newStartVnet < 0 || newEndVnet > 4096) { + throw new InvalidParameterValueException("Vnet range has to be between 0-4096"); + } + + if (newStartVnet > newEndVnet) { + throw new InvalidParameterValueException("Vnet range has to be between 0-4096 and start range should be lesser than or equal to stop range"); + } + + if (physicalNetworkHasAllocatedVnets(network.getDataCenterId(), network.getId())) { + String[] existingRange = network.getVnet().split("-"); + int existingStartVnet = Integer.parseInt(existingRange[0]); + int existingEndVnet = Integer.parseInt(existingRange[1]); + + //check if vnet is being extended + if (!(newStartVnet.intValue() > existingStartVnet && newEndVnet.intValue() < existingEndVnet)) { + throw new InvalidParameterValueException("Can's shrink existing vnet range as it the range has vnets allocated. Only extending existing vnet is supported"); + } + + if (newStartVnet < existingStartVnet) { + vnetsToAdd.add(new Pair(newStartVnet, existingStartVnet - 1)); + } + + if (newEndVnet > existingEndVnet) { + vnetsToAdd.add(new Pair(existingEndVnet + 1, newEndVnet)); + } + + } else { + vnetsToAdd.add(new Pair(newStartVnet, newEndVnet)); + replaceVnet = true; + } + } + + if (newVnetRangeString != null) { + network.setVnet(newVnetRangeString); + } + + + _physicalNetworkDao.update(id, network); + + if (replaceVnet) { + s_logger.debug("Deleting existing vnet range for the physicalNetwork id= "+id +" and zone id=" + network.getDataCenterId() + " as a part of updatePhysicalNetwork call"); + _dcDao.deleteVnet(network.getDataCenterId(), network.getId()); + } + + for (Pair vnetToAdd : vnetsToAdd) { + s_logger.debug("Adding vnet range " + vnetToAdd.first() + "-" + vnetToAdd.second() + " for the physicalNetwork id= "+id +" and zone id=" + network.getDataCenterId() + " as a part of updatePhysicalNetwork call"); + _dcDao.addVnet(network.getDataCenterId(), network.getId(), vnetToAdd.first(), vnetToAdd.second()); + } + + return network; + } + + private boolean physicalNetworkHasAllocatedVnets(long zoneId, long physicalNetworkId) { + return !_dcDao.listAllocatedVnets(zoneId, physicalNetworkId).isEmpty(); + } + + @Override + public boolean deletePhysicalNetwork(Long physicalNetworkId) { + + // verify input parameters + PhysicalNetworkVO network = _physicalNetworkDao.findById(physicalNetworkId); + if (network == null) { + throw new InvalidParameterValueException("Network id=" + physicalNetworkId + "doesn't exist in the system"); + } + + //delete physical network only if no network is associated to it + List networks = _networksDao.listByPhysicalNetwork(physicalNetworkId); + + if(networks != null && !networks.isEmpty()){ + s_logger.debug("Unable to remove the physical network id=" + physicalNetworkId + " as it has active networks associated."); + return false; + } + + List allocatedVnets = _dcDao.listAllocatedVnets(network.getDataCenterId(), physicalNetworkId); + + if(allocatedVnets != null && !allocatedVnets.isEmpty()){ + s_logger.debug("Unable to remove the physical network id=" + physicalNetworkId + " as it has active vnets associated."); + return false; + } + //checkIfPhysicalNetworkIsDeletable(physicalNetworkId); + + return _physicalNetworkDao.remove(physicalNetworkId); + } + + @DB + private void checkIfPhysicalNetworkIsDeletable(Long physicalNetworkId) { + List> tablesToCheck = new ArrayList>(); + + List networks = new ArrayList(); + networks.add(0, "networks"); + networks.add(1, "physical_network_id"); + networks.add(2, "there are networks associated to this physical network"); + tablesToCheck.add(networks); + + /*List privateIP = new ArrayList(); + privateIP.add(0, "op_dc_ip_address_alloc"); + privateIP.add(1, "data_center_id"); + privateIP.add(2, "there are private IP addresses allocated for this zone"); + tablesToCheck.add(privateIP); + + List publicIP = new ArrayList(); + publicIP.add(0, "user_ip_address"); + publicIP.add(1, "data_center_id"); + publicIP.add(2, "there are public IP addresses allocated for this zone"); + tablesToCheck.add(publicIP); + + List vmInstance = new ArrayList(); + vmInstance.add(0, "vm_instance"); + vmInstance.add(1, "data_center_id"); + vmInstance.add(2, "there are virtual machines running in this zone"); + tablesToCheck.add(vmInstance); + + List volumes = new ArrayList(); + volumes.add(0, "volumes"); + volumes.add(1, "data_center_id"); + volumes.add(2, "there are storage volumes for this zone"); + tablesToCheck.add(volumes);*/ + + List vnet = new ArrayList(); + vnet.add(0, "op_dc_vnet_alloc"); + vnet.add(1, "physical_network_id"); + vnet.add(2, "there are allocated vnets for this physical network"); + tablesToCheck.add(vnet); + + for (List table : tablesToCheck) { + String tableName = table.get(0); + String column = table.get(1); + String errorMsg = table.get(2); + + String dbName = "cloud"; + + String selectSql = "SELECT * FROM `" + dbName + "`.`" + tableName + "` WHERE " + column + " = ?"; + + if (tableName.equals("op_dc_vnet_alloc")) { + selectSql += " AND taken IS NOT NULL"; + } + + if (tableName.equals("user_ip_address")) { + selectSql += " AND state!='Free'"; + } + + if (tableName.equals("op_dc_ip_address_alloc")) { + selectSql += " AND taken IS NOT NULL"; + } + + if (tableName.equals("host_pod_ref") || tableName.equals("host") || tableName.equals("volumes")) { + selectSql += " AND removed is NULL"; + } + + if (tableName.equals("vm_instance")) { + selectSql += " AND state != '" + VirtualMachine.State.Expunging.toString() + "'"; + } + + Transaction txn = Transaction.currentTxn(); + try { + PreparedStatement stmt = txn.prepareAutoCloseStatement(selectSql); + stmt.setLong(1, physicalNetworkId); + ResultSet rs = stmt.executeQuery(); + if (rs != null && rs.next()) { + throw new CloudRuntimeException("The Physical Network is not deletable because " + errorMsg); + } + } catch (SQLException ex) { + throw new CloudRuntimeException("The Management Server failed to detect if physical network is deletable. Please contact Cloud Support."); + } + } + + } + + @Override + public List listNetworkServices(){ + return Service.listAllServices(); + } + + @Override + public List listSupportedNetworkServiceProviders(String serviceName){ + Network.Service service = null; + if(serviceName != null){ + service = Network.Service.getService(serviceName); + if(service == null){ + throw new InvalidParameterValueException("Invalid Network Service=" + serviceName); + } + } + + List supportedProviders = new ArrayList(); + for (NetworkElement element : _networkElements) { + if(element.getProvider() != null){ + if(service != null){ + //chk if this serviceprovider supports this service + if(isServiceProvided(element, service)){ + supportedProviders.add(element.getProvider()); + } + }else{ + supportedProviders.add(element.getProvider()); + } + } + } + return supportedProviders; + } + + private boolean isServiceProvided(NetworkElement element, Service service){ + if(element.getCapabilities() != null){ + return element.getCapabilities().containsKey(service); + } + return false; + } + + @Override + @DB + public PhysicalNetworkServiceProvider addProviderToPhysicalNetwork(Long physicalNetworkId, String providerName, Long destinationPhysicalNetworkId) { + + // verify input parameters + PhysicalNetworkVO network = _physicalNetworkDao.findById(physicalNetworkId); + if (network == null) { + throw new InvalidParameterValueException("Physical Network id=" + physicalNetworkId + "doesn't exist in the system"); + } + + // verify input parameters + if(destinationPhysicalNetworkId != null){ + PhysicalNetworkVO destNetwork = _physicalNetworkDao.findById(destinationPhysicalNetworkId); + if (destNetwork == null) { + throw new InvalidParameterValueException("Destination Physical Network id=" + destinationPhysicalNetworkId + "doesn't exist in the system"); + } + } + + if(providerName != null){ + Provider provider = Network.Provider.getProvider(providerName); + if(provider == null){ + throw new InvalidParameterValueException("Invalid Network Service Provider=" + providerName); + } + } + + Transaction txn = Transaction.currentTxn(); + try { + txn.start(); + // Create the new physical network in the database + PhysicalNetworkServiceProviderVO nsp = new PhysicalNetworkServiceProviderVO(physicalNetworkId, providerName); + if(destinationPhysicalNetworkId != null){ + nsp.setDestinationPhysicalNetworkId(destinationPhysicalNetworkId); + } + nsp = _pNSPDao.persist(nsp); + + txn.commit(); + return nsp; + } catch (Exception ex) { + txn.rollback(); + s_logger.warn("Exception: ", ex); + throw new CloudRuntimeException("Fail to add a provider to physical network"); + } finally { + txn.close(); + } + + } + + @Override + public List listNetworkServiceProviders(Long physicalNetworkId) { + PhysicalNetworkVO network = _physicalNetworkDao.findById(physicalNetworkId); + if (network == null) { + throw new InvalidParameterValueException("Physical Network id=" + physicalNetworkId + "doesn't exist in the system"); + } + + return _pNSPDao.listBy(physicalNetworkId); + } + + @Override + public PhysicalNetworkServiceProvider updateNetworkServiceProvider(Long id, Boolean enabled) { + + PhysicalNetworkServiceProviderVO provider = _pNSPDao.findById(id); + + if(provider == null){ + throw new InvalidParameterValueException("Network Service Provider id=" + id + "doesn't exist in the system"); + } + + if(enabled){ + //TODO: need to check if the provider is ready for the physical network. + provider.setState(PhysicalNetworkServiceProvider.State.Enabled); + }else{ + //do we need to do anything for the provider instances before disabling? + provider.setState(PhysicalNetworkServiceProvider.State.Disabled); + } + + _pNSPDao.update(id, provider); + + return provider; + } + + @Override + public boolean deleteNetworkServiceProvider(Long id) { + PhysicalNetworkServiceProviderVO provider = _pNSPDao.findById(id); + + if(provider == null){ + throw new InvalidParameterValueException("Network Service Provider id=" + id + "doesn't exist in the system"); + } + + //TODO provider instances? + + return _pNSPDao.remove(id); + } + } diff --git a/server/src/com/cloud/network/NetworkVO.java b/server/src/com/cloud/network/NetworkVO.java index 3a749471403..7c9739d5080 100644 --- a/server/src/com/cloud/network/NetworkVO.java +++ b/server/src/com/cloud/network/NetworkVO.java @@ -87,6 +87,9 @@ public class NetworkVO implements Network { @Column(name="network_offering_id") long networkOfferingId; + @Column(name="physical_network_id") + long physicalNetworkId; + @Column(name="data_center_id") long dataCenterId; @@ -181,6 +184,20 @@ public class NetworkVO implements Network { this.id = -1; this.guestType = guestType; } + /** + * Constructor to be used for the adapters because it only initializes what's needed. + * @param trafficType + * @param mode + * @param broadcastDomainType + * @param networkOfferingId + * @param dataCenterId + * @param state TODO + * @param physicalNetworkId + */ + public NetworkVO(TrafficType trafficType, GuestIpType guestType, Mode mode, BroadcastDomainType broadcastDomainType, long networkOfferingId, long dataCenterId, State state, long physicalNetworkId) { + this(trafficType, guestType, mode, broadcastDomainType, networkOfferingId, dataCenterId, state); + this.physicalNetworkId = physicalNetworkId; + } public NetworkVO(long id, Network that, long offeringId, long dataCenterId, String guruName, long domainId, long accountId, long related, String name, String displayText, boolean isDefault, boolean isSecurityGroupEnabled, boolean isDomainSpecific, String networkDomain, Type type, boolean isShared) { this(id, that.getTrafficType(), that.getGuestType(), that.getMode(), that.getBroadcastDomainType(), offeringId, dataCenterId, domainId, accountId, related, name, displayText,isDefault, isDomainSpecific, networkDomain, type, isShared); @@ -196,6 +213,11 @@ public class NetworkVO implements Network { } } + public NetworkVO(long id, Network that, long offeringId, long dataCenterId, String guruName, long domainId, long accountId, long related, String name, String displayText, Boolean isShared, boolean isDefault, boolean isSecurityGroupEnabled, boolean isDomainSpecific, String networkDomain, Type type, long physicalNetworkId) { + this(id, that, offeringId, dataCenterId, guruName, domainId, accountId, related, name, displayText, isDefault, isSecurityGroupEnabled, isDomainSpecific, networkDomain, type); + this.physicalNetworkId = physicalNetworkId; + } + /** * Constructor for the actual DAO object. * @param trafficType @@ -381,6 +403,15 @@ public class NetworkVO implements Network { return NumbersUtil.hash(id); } + @Override + public long getPhysicalNetworkId() { + return physicalNetworkId; + } + + public void setPhysicalNetworkId(long physicalNetworkId) { + this.physicalNetworkId = physicalNetworkId; + } + @Override public long getDataCenterId() { return dataCenterId; diff --git a/server/src/com/cloud/network/PhysicalNetworkVO.java b/server/src/com/cloud/network/PhysicalNetworkVO.java new file mode 100644 index 00000000000..921f9c9c646 --- /dev/null +++ b/server/src/com/cloud/network/PhysicalNetworkVO.java @@ -0,0 +1,207 @@ +/** + * Copyright (C) 2011 Citrix Systems, Inc. All rights reserved. + * + * This software is licensed under the GNU General Public License v3 or later. + * + * It is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or any later version. + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + */ +package com.cloud.network; + +import java.util.ArrayList; +import java.util.Date; +import java.util.List; + +import javax.persistence.CollectionTable; +import javax.persistence.Column; +import javax.persistence.ElementCollection; +import javax.persistence.Entity; +import javax.persistence.EnumType; +import javax.persistence.Enumerated; +import javax.persistence.FetchType; +import javax.persistence.Id; +import javax.persistence.JoinColumn; +import javax.persistence.Table; +import javax.persistence.TableGenerator; + +import com.cloud.utils.NumbersUtil; +import com.cloud.utils.db.GenericDao; + +/** + * NetworkConfigurationVO contains information about a specific physical network. + * + */ +@Entity +@Table(name="physical_network") +public class PhysicalNetworkVO implements PhysicalNetwork { + @Id + @TableGenerator(name="physical_networks_sq", table="sequence", pkColumnName="name", valueColumnName="value", pkColumnValue="physical_networks_seq", allocationSize=1) + @Column(name="id") + long id; + + @Column(name="data_center_id") + long dataCenterId; + + @Column(name="vnet") + private String vnet = null; + + @Column(name="speed") + private String speed = null; + + @Column(name="domain_id") + Long domainId = null; + + @Column(name="broadcast_domain_range") + @Enumerated(value=EnumType.STRING) + BroadcastDomainRange broadcastDomainRange; + + @Column(name="state") + @Enumerated(value=EnumType.STRING) + State state; + + @Column(name=GenericDao.REMOVED_COLUMN) + Date removed; + + @Column(name=GenericDao.CREATED_COLUMN) + Date created; + + @ElementCollection(targetClass = String.class, fetch=FetchType.EAGER) + @Column(name="tag") + @CollectionTable(name="physical_network_tags", joinColumns=@JoinColumn(name="physical_network_id")) + List tags; + + @ElementCollection(targetClass = String.class, fetch=FetchType.EAGER) + @Column(name="isolation_method") + @CollectionTable(name="physical_network_isolation_methods", joinColumns=@JoinColumn(name="physical_network_id")) + List isolationMethods; + + public PhysicalNetworkVO(){ + + } + + public PhysicalNetworkVO(long dataCenterId, String vnet, String speed, Long domainId, BroadcastDomainRange broadcastDomainRange) { + this.dataCenterId = dataCenterId; + this.setVnet(vnet); + this.setSpeed(speed); + this.domainId = domainId; + if(broadcastDomainRange != null){ + this.broadcastDomainRange = broadcastDomainRange; + }else{ + this.broadcastDomainRange = BroadcastDomainRange.Pod; + } + this.state = State.Disabled; + } + + @Override + public State getState() { + return state; + } + + public void setState(State state) { + this.state = state; + } + + @Override + public long getId() { + return id; + } + + @Override + public List getTags() { + return tags != null ? tags : new ArrayList(); + } + + public void addTag(String tag) { + if (tags == null) { + tags = new ArrayList(); + } + tags.add(tag); + } + + public void setTags(List tags) { + this.tags = tags; + } + + @Override + public Long getDomainId() { + return domainId; + } + + @Override + public BroadcastDomainRange getBroadcastDomainRange() { + return broadcastDomainRange; + } + + public void setBroadcastDomainRange(BroadcastDomainRange broadcastDomainRange) { + this.broadcastDomainRange = broadcastDomainRange; + } + + @Override + public int hashCode() { + return NumbersUtil.hash(id); + } + + @Override + public long getDataCenterId() { + return dataCenterId; + } + + public Date getRemoved() { + return removed; + } + + public void setRemoved(Date removed) { + this.removed = removed; + } + + public Date getCreated() { + return created; + } + + public void setCreated(Date created) { + this.created = created; + } + + @Override + public List getIsolationMethods() { + return isolationMethods != null ? isolationMethods : new ArrayList(); + } + + public void addIsolationMethod(String isolationMethod) { + if (isolationMethods == null) { + isolationMethods = new ArrayList(); + } + isolationMethods.add(isolationMethod); + } + + public void setIsolationMethods(List isolationMethods) { + this.isolationMethods = isolationMethods; + } + + public void setVnet(String vnet) { + this.vnet = vnet; + } + + @Override + public String getVnet() { + return vnet; + } + + public void setSpeed(String speed) { + this.speed = speed; + } + + @Override + public String getSpeed() { + return speed; + } +} diff --git a/server/src/com/cloud/network/dao/NetworkDao.java b/server/src/com/cloud/network/dao/NetworkDao.java index 8f912ff5502..e27a8fb58e4 100644 --- a/server/src/com/cloud/network/dao/NetworkDao.java +++ b/server/src/com/cloud/network/dao/NetworkDao.java @@ -66,4 +66,8 @@ public interface NetworkDao extends GenericDao { List listByZoneIncludingRemoved(long zoneId); Long getNetworkCountByOfferingId(long offeringId); + + List listByPhysicalNetwork(long physicalNetworkId); + + List listSecurityGroupEnabledNetworks(); } diff --git a/server/src/com/cloud/network/dao/NetworkDaoImpl.java b/server/src/com/cloud/network/dao/NetworkDaoImpl.java index 4ffd6c077ca..c50c4ec15b0 100644 --- a/server/src/com/cloud/network/dao/NetworkDaoImpl.java +++ b/server/src/com/cloud/network/dao/NetworkDaoImpl.java @@ -23,8 +23,8 @@ import java.util.Random; import javax.ejb.Local; import javax.persistence.TableGenerator; -import com.cloud.network.Network.GuestIpType; import com.cloud.network.Network; +import com.cloud.network.Network.GuestIpType; import com.cloud.network.NetworkAccountDaoImpl; import com.cloud.network.NetworkAccountVO; import com.cloud.network.NetworkDomainVO; @@ -32,7 +32,6 @@ import com.cloud.network.NetworkVO; import com.cloud.network.Networks.BroadcastDomainType; import com.cloud.network.Networks.Mode; import com.cloud.network.Networks.TrafficType; -import com.cloud.storage.dao.VolumeDaoImpl.SumCount; import com.cloud.utils.component.ComponentLocator; import com.cloud.utils.db.DB; import com.cloud.utils.db.GenericDaoBase; @@ -56,7 +55,9 @@ public class NetworkDaoImpl extends GenericDaoBase implements N final SearchBuilder ZoneBroadcastUriSearch; final SearchBuilder ZoneSecurityGroupSearch; final GenericSearchBuilder CountByOfferingId; - + final SearchBuilder PhysicalNetworkSearch; + final SearchBuilder securityGroupSearch; + NetworkAccountDaoImpl _accountsDao = ComponentLocator.inject(NetworkAccountDaoImpl.class); NetworkDomainDaoImpl _domainsDao = ComponentLocator.inject(NetworkDomainDaoImpl.class); NetworkOpDaoImpl _opDao = ComponentLocator.inject(NetworkOpDaoImpl.class); @@ -78,6 +79,7 @@ public class NetworkDaoImpl extends GenericDaoBase implements N AllFieldsSearch.and("guesttype", AllFieldsSearch.entity().getGuestType(), Op.EQ); AllFieldsSearch.and("related", AllFieldsSearch.entity().getRelated(), Op.EQ); AllFieldsSearch.and("type", AllFieldsSearch.entity().getType(), Op.EQ); + AllFieldsSearch.and("physicalNetwork", AllFieldsSearch.entity().getPhysicalNetworkId(), Op.EQ); AllFieldsSearch.done(); AccountSearch = createSearchBuilder(); @@ -121,6 +123,15 @@ public class NetworkDaoImpl extends GenericDaoBase implements N CountByOfferingId.and("removed", CountByOfferingId.entity().getRemoved(), Op.NULL); CountByOfferingId.done(); + + PhysicalNetworkSearch = createSearchBuilder(); + PhysicalNetworkSearch.and("physicalNetworkId", PhysicalNetworkSearch.entity().getPhysicalNetworkId(), Op.EQ); + PhysicalNetworkSearch.done(); + + securityGroupSearch = createSearchBuilder(); + securityGroupSearch.and("isSgEnabled", securityGroupSearch.entity().isSecurityGroupEnabled(), SearchCriteria.Op.EQ); + securityGroupSearch.done(); + _tgMacAddress = _tgs.get("macAddress"); } @@ -331,4 +342,18 @@ public class NetworkDaoImpl extends GenericDaoBase implements N List results = customSearch(sc, null); return results.get(0); } + + public List listByPhysicalNetwork(long physicalNetworkId){ + SearchCriteria sc = PhysicalNetworkSearch.create(); + sc.setParameters("physicalNetworkId", physicalNetworkId); + return listBy(sc); + } + + @Override + public List listSecurityGroupEnabledNetworks() { + SearchCriteria sc = securityGroupSearch.create(); + sc.setParameters("isSgEnabled", true); + return listBy(sc); + } + } diff --git a/server/src/com/cloud/network/dao/PhysicalNetworkDao.java b/server/src/com/cloud/network/dao/PhysicalNetworkDao.java new file mode 100644 index 00000000000..c2c1a04ecfc --- /dev/null +++ b/server/src/com/cloud/network/dao/PhysicalNetworkDao.java @@ -0,0 +1,28 @@ +/** + * Copyright (C) 2011 Citrix Systems, Inc. All rights reserved. + * + * This software is licensed under the GNU General Public License v3 or later. + * + * It is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or any later version. + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + */ +package com.cloud.network.dao; + +import java.util.List; + +import com.cloud.network.PhysicalNetworkVO; +import com.cloud.utils.db.GenericDao; + +public interface PhysicalNetworkDao extends GenericDao { + List listByZone(long zoneId); + List listByZoneIncludingRemoved(long zoneId); +} diff --git a/server/src/com/cloud/network/dao/PhysicalNetworkDaoImpl.java b/server/src/com/cloud/network/dao/PhysicalNetworkDaoImpl.java new file mode 100644 index 00000000000..d49c3830876 --- /dev/null +++ b/server/src/com/cloud/network/dao/PhysicalNetworkDaoImpl.java @@ -0,0 +1,58 @@ +/** + * Copyright (C) 2011 Citrix Systems, Inc. All rights reserved. + * + * This software is licensed under the GNU General Public License v3 or later. + * + * It is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or any later version. + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + */ +package com.cloud.network.dao; + +import java.util.List; + +import javax.ejb.Local; + +import com.cloud.network.PhysicalNetworkVO; +import com.cloud.utils.db.DB; +import com.cloud.utils.db.GenericDaoBase; +import com.cloud.utils.db.SearchBuilder; +import com.cloud.utils.db.SearchCriteria; +import com.cloud.utils.db.SearchCriteria.Op; + +@Local(value=PhysicalNetworkDao.class) @DB(txn=false) +public class PhysicalNetworkDaoImpl extends GenericDaoBase implements PhysicalNetworkDao { + final SearchBuilder ZoneSearch; + + protected PhysicalNetworkDaoImpl() { + super(); + ZoneSearch = createSearchBuilder(); + ZoneSearch.and("dataCenterId", ZoneSearch.entity().getDataCenterId(), Op.EQ); + ZoneSearch.done(); + + } + + @Override + public List listByZone(long zoneId) { + SearchCriteria sc = ZoneSearch.create(); + sc.setParameters("dataCenterId", zoneId); + return search(sc, null); + } + + @Override + public List listByZoneIncludingRemoved(long zoneId) { + SearchCriteria sc = ZoneSearch.create(); + sc.setParameters("dataCenterId", zoneId); + return listIncludingRemovedBy(sc); + } + + +} diff --git a/server/src/com/cloud/network/dao/PhysicalNetworkIsolationMethodDaoImpl.java b/server/src/com/cloud/network/dao/PhysicalNetworkIsolationMethodDaoImpl.java new file mode 100644 index 00000000000..c9e292ef24c --- /dev/null +++ b/server/src/com/cloud/network/dao/PhysicalNetworkIsolationMethodDaoImpl.java @@ -0,0 +1,69 @@ +/** + * Copyright (C) 2011 Citrix Systems, Inc. All rights reserved. + * + * This software is licensed under the GNU General Public License v3 or later. + * + * It is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or any later version. + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + */ +package com.cloud.network.dao; + +import java.util.List; + +import com.cloud.utils.db.GenericDao; +import com.cloud.utils.db.GenericDaoBase; +import com.cloud.utils.db.GenericSearchBuilder; +import com.cloud.utils.db.SearchBuilder; +import com.cloud.utils.db.SearchCriteria; +import com.cloud.utils.db.SearchCriteria.Op; + + +public class PhysicalNetworkIsolationMethodDaoImpl extends GenericDaoBase implements GenericDao { + private final GenericSearchBuilder IsolationMethodSearch; + private final SearchBuilder AllFieldsSearch; + + protected PhysicalNetworkIsolationMethodDaoImpl() { + super(); + IsolationMethodSearch = createSearchBuilder(String.class); + IsolationMethodSearch.selectField(IsolationMethodSearch.entity().getIsolationMethod()); + IsolationMethodSearch.and("physicalNetworkId", IsolationMethodSearch.entity().getPhysicalNetworkId(), Op.EQ); + IsolationMethodSearch.done(); + + AllFieldsSearch = createSearchBuilder(); + AllFieldsSearch.and("id", AllFieldsSearch.entity().getId(), Op.EQ); + AllFieldsSearch.and("physicalNetworkId", AllFieldsSearch.entity().getPhysicalNetworkId(), Op.EQ); + AllFieldsSearch.and("isolationMethod", AllFieldsSearch.entity().getIsolationMethod(), Op.EQ); + AllFieldsSearch.done(); + } + + public List getAllIsolationMethod(long physicalNetworkId) { + SearchCriteria sc = IsolationMethodSearch.create(); + sc.setParameters("physicalNetworkId", physicalNetworkId); + + return customSearch(sc, null); + } + + public String getIsolationMethod(long physicalNetworkId) { + SearchCriteria sc = IsolationMethodSearch.create(); + sc.setParameters("physicalNetworkId", physicalNetworkId); + + return customSearch(sc, null).get(0); + } + + public int clearIsolationMethods(long physicalNetworkId) { + SearchCriteria sc = AllFieldsSearch.create(); + sc.setParameters("physicalNetworkId", physicalNetworkId); + + return remove(sc); + } + +} diff --git a/server/src/com/cloud/network/dao/PhysicalNetworkIsolationMethodVO.java b/server/src/com/cloud/network/dao/PhysicalNetworkIsolationMethodVO.java new file mode 100644 index 00000000000..7698308b528 --- /dev/null +++ b/server/src/com/cloud/network/dao/PhysicalNetworkIsolationMethodVO.java @@ -0,0 +1,68 @@ +/** + * Copyright (C) 2011 Citrix Systems, Inc. All rights reserved. + * + * This software is licensed under the GNU General Public License v3 or later. + * + * It is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or any later version. + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + */ +package com.cloud.network.dao; + +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; +import javax.persistence.Table; + +/** + * This class is just used to work with the DAO. It shouldn't be used anywhere. + * + */ +@Entity +@Table(name = "physical_network_isolation_methods") +public class PhysicalNetworkIsolationMethodVO { + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + @Column(name = "id") + private long id; + + @Column(name = "physical_network_id") + private long physicalNetworkId; + + @Column(name = "isolation_method") + private String isolationMethod; + + /** + * There should never be a public constructor for this class. Since it's + * only here to define the table for the DAO class. + */ + protected PhysicalNetworkIsolationMethodVO() { + } + + protected PhysicalNetworkIsolationMethodVO(long physicalNetworkId, String isolationMethod) { + this.physicalNetworkId = physicalNetworkId; + this.isolationMethod = isolationMethod; + } + + public long getId() { + return id; + } + + public long getPhysicalNetworkId() { + return physicalNetworkId; + } + + public String getIsolationMethod() { + return isolationMethod; + } +} diff --git a/server/src/com/cloud/network/dao/PhysicalNetworkServiceProviderDao.java b/server/src/com/cloud/network/dao/PhysicalNetworkServiceProviderDao.java new file mode 100644 index 00000000000..b41e022c7aa --- /dev/null +++ b/server/src/com/cloud/network/dao/PhysicalNetworkServiceProviderDao.java @@ -0,0 +1,26 @@ +/** + * Copyright (C) 2011 Citrix Systems, Inc. All rights reserved. + * + * This software is licensed under the GNU General Public License v3 or later. + * + * It is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or any later version. + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + */ +package com.cloud.network.dao; + +import java.util.List; + +import com.cloud.utils.db.GenericDao; + +public interface PhysicalNetworkServiceProviderDao extends GenericDao { + List listBy(long physicalNetworkId); +} diff --git a/server/src/com/cloud/network/dao/PhysicalNetworkServiceProviderDaoImpl.java b/server/src/com/cloud/network/dao/PhysicalNetworkServiceProviderDaoImpl.java new file mode 100644 index 00000000000..0bb9b24fcec --- /dev/null +++ b/server/src/com/cloud/network/dao/PhysicalNetworkServiceProviderDaoImpl.java @@ -0,0 +1,49 @@ +/** + * Copyright (C) 2011 Citrix Systems, Inc. All rights reserved. + * + * This software is licensed under the GNU General Public License v3 or later. + * + * It is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or any later version. + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + */ +package com.cloud.network.dao; + +import java.util.List; + +import javax.ejb.Local; + +import com.cloud.utils.db.DB; +import com.cloud.utils.db.GenericDaoBase; +import com.cloud.utils.db.SearchBuilder; +import com.cloud.utils.db.SearchCriteria; +import com.cloud.utils.db.SearchCriteria.Op; + +@Local(value=PhysicalNetworkServiceProviderDao.class) @DB(txn=false) +public class PhysicalNetworkServiceProviderDaoImpl extends GenericDaoBase implements PhysicalNetworkServiceProviderDao { + final SearchBuilder physicalNetworkSearch; + + protected PhysicalNetworkServiceProviderDaoImpl() { + super(); + physicalNetworkSearch = createSearchBuilder(); + physicalNetworkSearch.and("physicalNetworkId", physicalNetworkSearch.entity().getPhysicalNetworkId(), Op.EQ); + physicalNetworkSearch.done(); + + } + + @Override + public List listBy(long physicalNetworkId) { + SearchCriteria sc = physicalNetworkSearch.create(); + sc.setParameters("physicalNetworkId", physicalNetworkId); + return search(sc, null); + } + +} diff --git a/server/src/com/cloud/network/dao/PhysicalNetworkServiceProviderVO.java b/server/src/com/cloud/network/dao/PhysicalNetworkServiceProviderVO.java new file mode 100644 index 00000000000..a731596be2a --- /dev/null +++ b/server/src/com/cloud/network/dao/PhysicalNetworkServiceProviderVO.java @@ -0,0 +1,96 @@ +/** + * Copyright (C) 2011 Citrix Systems, Inc. All rights reserved. + * + * This software is licensed under the GNU General Public License v3 or later. + * + * It is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or any later version. + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + */ +package com.cloud.network.dao; + +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.EnumType; +import javax.persistence.Enumerated; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; +import javax.persistence.Table; + +import com.cloud.network.PhysicalNetworkServiceProvider; + +@Entity +@Table(name = "physical_network_service_providers") +public class PhysicalNetworkServiceProviderVO implements PhysicalNetworkServiceProvider { + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + @Column(name = "id") + private long id; + + @Column(name = "physical_network_id") + private long physicalNetworkId; + + @Column(name = "destination_physical_network_id") + private long destPhysicalNetworkId; + + + @Column(name = "provider_name") + private String providerName; + + @Column(name="state") + @Enumerated(value=EnumType.STRING) + State state; + + public PhysicalNetworkServiceProviderVO() { + } + + public PhysicalNetworkServiceProviderVO(long physicalNetworkId, String name) { + this.physicalNetworkId = physicalNetworkId; + this.providerName = name; + this.state = State.Disabled; + } + + @Override + public long getId() { + return id; + } + + @Override + public long getPhysicalNetworkId() { + return physicalNetworkId; + } + + + @Override + public State getState() { + return state; + } + + @Override + public void setState(State state) { + this.state = state; + } + + @Override + public String getProviderName() { + return providerName; + } + + public void setDestinationPhysicalNetworkId(long destPhysicalNetworkId) { + this.destPhysicalNetworkId = destPhysicalNetworkId; + } + + @Override + public long getDestinationPhysicalNetworkId() { + return destPhysicalNetworkId; + } +} diff --git a/server/src/com/cloud/network/dao/PhysicalNetworkTagDaoImpl.java b/server/src/com/cloud/network/dao/PhysicalNetworkTagDaoImpl.java new file mode 100644 index 00000000000..a90e4d00c59 --- /dev/null +++ b/server/src/com/cloud/network/dao/PhysicalNetworkTagDaoImpl.java @@ -0,0 +1,62 @@ +/** + * Copyright (C) 2011 Citrix Systems, Inc. All rights reserved. + * + * This software is licensed under the GNU General Public License v3 or later. + * + * It is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or any later version. + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + */ +package com.cloud.network.dao; + +import java.util.List; + +import com.cloud.utils.db.GenericDao; +import com.cloud.utils.db.GenericDaoBase; +import com.cloud.utils.db.GenericSearchBuilder; +import com.cloud.utils.db.SearchBuilder; +import com.cloud.utils.db.SearchCriteria; +import com.cloud.utils.db.SearchCriteria.Op; + + +public class PhysicalNetworkTagDaoImpl extends GenericDaoBase implements GenericDao { + private final GenericSearchBuilder TagSearch; + private final SearchBuilder AllFieldsSearch; + + protected PhysicalNetworkTagDaoImpl() { + super(); + TagSearch = createSearchBuilder(String.class); + TagSearch.selectField(TagSearch.entity().getTag()); + TagSearch.and("physicalNetworkId", TagSearch.entity().getPhysicalNetworkId(), Op.EQ); + TagSearch.done(); + + AllFieldsSearch = createSearchBuilder(); + AllFieldsSearch.and("id", AllFieldsSearch.entity().getId(), Op.EQ); + AllFieldsSearch.and("physicalNetworkId", AllFieldsSearch.entity().getPhysicalNetworkId(), Op.EQ); + AllFieldsSearch.and("tag", AllFieldsSearch.entity().getTag(), Op.EQ); + AllFieldsSearch.done(); + } + + public List getTags(long physicalNetworkId) { + SearchCriteria sc = TagSearch.create(); + sc.setParameters("physicalNetworkId", physicalNetworkId); + + return customSearch(sc, null); + } + + public int clearTags(long physicalNetworkId) { + SearchCriteria sc = AllFieldsSearch.create(); + sc.setParameters("physicalNetworkId", physicalNetworkId); + + return remove(sc); + } + +} diff --git a/server/src/com/cloud/network/dao/PhysicalNetworkTagVO.java b/server/src/com/cloud/network/dao/PhysicalNetworkTagVO.java new file mode 100644 index 00000000000..d34c7b41171 --- /dev/null +++ b/server/src/com/cloud/network/dao/PhysicalNetworkTagVO.java @@ -0,0 +1,68 @@ +/** + * Copyright (C) 2011 Citrix Systems, Inc. All rights reserved. + * + * This software is licensed under the GNU General Public License v3 or later. + * + * It is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or any later version. + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + */ +package com.cloud.network.dao; + +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; +import javax.persistence.Table; + +/** + * This class is just used to work with the DAO. It shouldn't be used anywhere. + * + */ +@Entity +@Table(name = "physical_network_tags") +public class PhysicalNetworkTagVO { + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + @Column(name = "id") + private long id; + + @Column(name = "physical_network_id") + private long physicalNetworkId; + + @Column(name = "tag") + private String tag; + + /** + * There should never be a public constructor for this class. Since it's + * only here to define the table for the DAO class. + */ + protected PhysicalNetworkTagVO() { + } + + protected PhysicalNetworkTagVO(long physicalNetworkId, String tag) { + this.physicalNetworkId = physicalNetworkId; + this.tag = tag; + } + + public long getId() { + return id; + } + + public long getPhysicalNetworkId() { + return physicalNetworkId; + } + + public String getTag() { + return tag; + } +} diff --git a/server/src/com/cloud/network/guru/ExternalGuestNetworkGuru.java b/server/src/com/cloud/network/guru/ExternalGuestNetworkGuru.java index b2e91f71f83..c468666f1e9 100644 --- a/server/src/com/cloud/network/guru/ExternalGuestNetworkGuru.java +++ b/server/src/com/cloud/network/guru/ExternalGuestNetworkGuru.java @@ -114,7 +114,7 @@ public class ExternalGuestNetworkGuru extends GuestNetworkGuru { // Get a vlan tag int vlanTag; if (config.getBroadcastUri() == null) { - String vnet = _dcDao.allocateVnet(zone.getId(), config.getAccountId(), context.getReservationId()); + String vnet = _dcDao.allocateVnet(zone.getId(), config.getPhysicalNetworkId(), config.getAccountId(), context.getReservationId()); try { vlanTag = Integer.parseInt(vnet); @@ -130,7 +130,7 @@ public class ExternalGuestNetworkGuru extends GuestNetworkGuru { } // Determine the offset from the lowest vlan tag - int offset = _externalNetworkMgr.getVlanOffset(zone, vlanTag); + int offset = _externalNetworkMgr.getVlanOffset(config.getPhysicalNetworkId(), vlanTag); // Determine the new gateway and CIDR String[] oldCidr = config.getCidr().split("/"); diff --git a/server/src/com/cloud/network/guru/GuestNetworkGuru.java b/server/src/com/cloud/network/guru/GuestNetworkGuru.java index 61cb7f981bb..1bb13ffaacd 100644 --- a/server/src/com/cloud/network/guru/GuestNetworkGuru.java +++ b/server/src/com/cloud/network/guru/GuestNetworkGuru.java @@ -144,7 +144,7 @@ public class GuestNetworkGuru extends AdapterBase implements NetworkGuru { network.getDataCenterId(), State.Allocated); if (network.getBroadcastUri() == null) { - String vnet = _dcDao.allocateVnet(dcId, network.getAccountId(), context.getReservationId()); + String vnet = _dcDao.allocateVnet(dcId, network.getPhysicalNetworkId(), network.getAccountId(), context.getReservationId()); if (vnet == null) { throw new InsufficientVirtualNetworkCapcityException("Unable to allocate vnet as a part of network " + network + " implement ", DataCenter.class, dcId); } @@ -235,7 +235,7 @@ public class GuestNetworkGuru extends AdapterBase implements NetworkGuru { public void shutdown(NetworkProfile profile, NetworkOffering offering) { s_logger.debug("Releasing vnet for the network id=" + profile.getId()); if (profile.getBroadcastUri() != null) { - _dcDao.releaseVnet(profile.getBroadcastUri().getHost(), profile.getDataCenterId(), profile.getAccountId(), profile.getReservationId()); + _dcDao.releaseVnet(profile.getBroadcastUri().getHost(), profile.getDataCenterId(), profile.getPhysicalNetworkId(), profile.getAccountId(), profile.getReservationId()); EventUtils.saveEvent(UserContext.current().getCallerUserId(), profile.getAccountId(), EventVO.LEVEL_INFO, EventTypes.EVENT_ZONE_VLAN_RELEASE, "Released Zone Vlan: " +profile.getBroadcastUri().getHost()+" for Network: "+profile.getId(), 0); profile.setBroadcastUri(null); diff --git a/server/src/com/cloud/server/ManagementServerImpl.java b/server/src/com/cloud/server/ManagementServerImpl.java index 6f81f3813cc..70bdca07858 100755 --- a/server/src/com/cloud/server/ManagementServerImpl.java +++ b/server/src/com/cloud/server/ManagementServerImpl.java @@ -3322,8 +3322,8 @@ public class ManagementServerImpl implements ManagementServer { boolean securityGroupsEnabled = false; boolean elasticLoadBalancerEnabled = false; String supportELB = "false"; - List dc = _dcDao.listSecurityGroupEnabledZones(); - if (dc != null && !dc.isEmpty()) { + List networks = _networkDao.listSecurityGroupEnabledNetworks(); + if (networks != null && !networks.isEmpty()) { securityGroupsEnabled = true; String elbEnabled = _configDao.getValue(Config.ElasticLoadBalancerEnabled.key()); elasticLoadBalancerEnabled = elbEnabled==null?false:Boolean.parseBoolean(elbEnabled); diff --git a/server/src/com/cloud/test/DatabaseConfig.java b/server/src/com/cloud/test/DatabaseConfig.java index 8458d49302f..a0ec7c97698 100755 --- a/server/src/com/cloud/test/DatabaseConfig.java +++ b/server/src/com/cloud/test/DatabaseConfig.java @@ -91,6 +91,7 @@ public class DatabaseConfig { static { // initialize the objectNames ArrayList objectNames.add("zone"); + objectNames.add("physicalNetwork"); objectNames.add("vlan"); objectNames.add("pod"); objectNames.add("cluster"); @@ -154,7 +155,6 @@ public class DatabaseConfig { fieldNames.add("tags"); fieldNames.add("networktype"); fieldNames.add("clusterId"); - s_configurationDescriptions.put("host.stats.interval", "the interval in milliseconds when host stats are retrieved from agents"); @@ -431,6 +431,8 @@ public class DatabaseConfig { private void saveCurrentObject() { if ("zone".equals(_currentObjectName)) { saveZone(); + } else if ("physicalNetwork".equals(_currentObjectName)) { + savePhysicalNetwork(); } else if ("vlan".equals(_currentObjectName)) { saveVlan(); } else if ("pod".equals(_currentObjectName)) { @@ -618,7 +620,7 @@ public class DatabaseConfig { String dns2 = _currentObjectParams.get("dns2"); String internalDns1 = _currentObjectParams.get("internalDns1"); String internalDns2 = _currentObjectParams.get("internalDns2"); - String vnetRange = _currentObjectParams.get("vnet"); + //String vnetRange = _currentObjectParams.get("vnet"); String guestNetworkCidr = _currentObjectParams.get("guestNetworkCidr"); String networkType = _currentObjectParams.get("networktype"); @@ -639,17 +641,27 @@ public class DatabaseConfig { if (!IPRangeConfig.validCIDR(guestNetworkCidr)) { printError("Please enter a valid value for guestNetworkCidr"); } - int vnetStart = -1; - int vnetEnd = -1; - if (vnetRange != null) { + + pzc.saveZone(false, id, name, dns1, dns2, internalDns1, internalDns2, guestNetworkCidr, networkType); + + } + + private void savePhysicalNetwork() { + long id = Long.parseLong(_currentObjectParams.get("id")); + String zoneId = _currentObjectParams.get("zoneId"); + String vnetRange = _currentObjectParams.get("vnet"); + + int vnetStart = -1; + int vnetEnd = -1; + if (vnetRange != null) { String[] tokens = vnetRange.split("-"); vnetStart = Integer.parseInt(tokens[0]); vnetEnd = Integer.parseInt(tokens[1]); } - - pzc.saveZone(false, id, name, dns1, dns2, internalDns1, internalDns2, vnetStart, vnetEnd, guestNetworkCidr, networkType); + long zoneDbId = Long.parseLong(zoneId); + pzc.savePhysicalNetwork(false, id, zoneDbId, vnetStart, vnetEnd); - } + } private void saveVlan() { String zoneId = _currentObjectParams.get("zoneId"); diff --git a/server/src/com/cloud/test/PodZoneConfig.java b/server/src/com/cloud/test/PodZoneConfig.java index a7cc4b70298..3262cdd8deb 100644 --- a/server/src/com/cloud/test/PodZoneConfig.java +++ b/server/src/com/cloud/test/PodZoneConfig.java @@ -254,7 +254,7 @@ public class PodZoneConfig { } @DB - public void saveZone(boolean printOutput, long id, String name, String dns1, String dns2, String dns3, String dns4, int vnetStart, int vnetEnd, String guestNetworkCidr, String networkType) { + public void saveZone(boolean printOutput, long id, String name, String dns1, String dns2, String dns3, String dns4, String guestNetworkCidr, String networkType) { if (printOutput) System.out.println("Saving zone, please wait..."); @@ -299,10 +299,6 @@ public class PodZoneConfig { values += ",'" + networkType + "'"; } - //save vnet information - columns += ", vnet"; - values += ",'" + vnetStart + "-" + vnetEnd + "'"; - columns += ")"; values += ")"; @@ -311,18 +307,46 @@ public class PodZoneConfig { DatabaseConfig.saveSQL(sql, "Failed to save zone due to exception. Please contact Cloud Support."); - // Hardcode the vnet range to be the full range - int begin = 0x64; + if (printOutput) System.out.println("Successfully saved zone."); + } + + @DB + public void savePhysicalNetwork(boolean printOutput, long id, long dcId, int vnetStart, int vnetEnd) { + + if (printOutput) System.out.println("Saving physical network, please wait..."); + + String columns = null; + String values = null; + + columns = "(id "; + values = "('" + id + "'"; + + columns += ", data_center_id "; + values += ",'" + dcId + "'"; + + //save vnet information + columns += ", vnet"; + values += ",'" + vnetStart + "-" + vnetEnd + "'"; + + + columns += ")"; + values += ")"; + + String sql = "INSERT INTO `cloud`.`physical_network` " + columns + " VALUES " + values; + + DatabaseConfig.saveSQL(sql, "Failed to save physical network due to exception. Please contact Cloud Support."); + + // Hardcode the vnet range to be the full range + int begin = 0x64; int end = 64000; // If vnet arguments were passed in, use them if (vnetStart != -1 && vnetEnd != -1) { - begin = vnetStart; - end = vnetEnd; + begin = vnetStart; + end = vnetEnd; } - long dcId = getZoneId(name); - String insertVnet = "INSERT INTO `cloud`.`op_dc_vnet_alloc` (vnet, data_center_id) VALUES ( ?, ?)"; + String insertVnet = "INSERT INTO `cloud`.`op_dc_vnet_alloc` (vnet, data_center_id, physical_network_id) VALUES ( ?, ?, ?)"; Transaction txn = Transaction.currentTxn(); try { @@ -330,15 +354,16 @@ public class PodZoneConfig { for (int i = begin; i <= end; i++) { stmt.setString(1, Integer.toString(i)); stmt.setLong(2, dcId); + stmt.setLong(3, id); stmt.addBatch(); } stmt.executeBatch(); } catch (SQLException ex) { - printError("Error creating vnet for the data center. Please contact Cloud Support."); + printError("Error creating vnet for the physical network. Please contact Cloud Support."); } - - if (printOutput) System.out.println("Successfully saved zone."); - } + + if (printOutput) System.out.println("Successfully saved physical network."); + } public void deleteZone(String name) { String sql = "DELETE FROM `cloud`.`data_center` WHERE name=\"" + name + "\""; diff --git a/setup/db/create-schema.sql b/setup/db/create-schema.sql index b38ca8ae320..f76d564741c 100755 --- a/setup/db/create-schema.sql +++ b/setup/db/create-schema.sql @@ -117,6 +117,7 @@ DROP TABLE IF EXISTS `cloud`.`data_center_details`; DROP TABLE IF EXISTS `cloud`.`network_tags`; DROP TABLE IF EXISTS `cloud`.`op_host_transfer`; DROP TABLE IF EXISTS `cloud`.`projects`; +DROP TABLE IF EXISTS `cloud`.`physical_network`; CREATE TABLE `cloud`.`version` ( `id` bigint unsigned NOT NULL UNIQUE AUTO_INCREMENT COMMENT 'id', @@ -168,6 +169,7 @@ CREATE TABLE `cloud`.`networks` ( `cidr` varchar(18) COMMENT 'network cidr', `mode` varchar(32) COMMENT 'How to retrieve ip address in this network', `network_offering_id` bigint unsigned NOT NULL COMMENT 'network offering id that this configuration is created from', + `physical_network_id` bigint unsigned COMMENT 'physical network id that this configuration is based on', `data_center_id` bigint unsigned NOT NULL COMMENT 'data center id that this configuration is used in', `guru_name` varchar(255) NOT NULL COMMENT 'who is responsible for this type of network configuration', `state` varchar(32) NOT NULL COMMENT 'what state is this configuration in', @@ -189,7 +191,7 @@ CREATE TABLE `cloud`.`networks` ( `is_security_group_enabled` tinyint NOT NULL DEFAULT 0 COMMENT '1: enabled, 0: not', `type` char(32) COMMENT 'type of the network, can be Shared or Isolated', PRIMARY KEY (`id`), - CONSTRAINT `fk_networks__network_offering_id` FOREIGN KEY (`network_offering_id`) REFERENCES `network_offerings`(`id`), + CONSTRAINT `fk_networks__network_offering_id` FOREIGN KEY (`network_offering_id`) REFERENCES `network_offerings`(`id`), CONSTRAINT `fk_networks__data_center_id` FOREIGN KEY (`data_center_id`) REFERENCES `data_center`(`id`) ON DELETE CASCADE, CONSTRAINT `fk_networks__related` FOREIGN KEY(`related`) REFERENCES `networks`(`id`) ON DELETE CASCADE, CONSTRAINT `fk_networks__account_id` FOREIGN KEY(`account_id`) REFERENCES `account`(`id`), @@ -371,6 +373,7 @@ INSERT INTO `cloud`.`sequence` (name, value) VALUES ('storage_pool_seq', 200); INSERT INTO `cloud`.`sequence` (name, value) VALUES ('volume_seq', 1); INSERT INTO `cloud`.`sequence` (name, value) VALUES ('networks_seq', 200); INSERT INTO `cloud`.`sequence` (name, value) VALUES ('checkpoint_seq', 1); +INSERT INTO `cloud`.`sequence` (name, value) VALUES ('physical_networks_seq', 200); CREATE TABLE `cloud`.`volumes` ( `id` bigint unsigned NOT NULL AUTO_INCREMENT COMMENT 'Primary Key', @@ -483,7 +486,6 @@ CREATE TABLE `cloud`.`data_center` ( `internal_dns2` varchar(255), `gateway` varchar(15), `netmask` varchar(15), - `vnet` varchar(255), `router_mac_address` varchar(17) NOT NULL DEFAULT '02:00:00:00:00:01' COMMENT 'mac address for the router within the domain', `mac_address` bigint unsigned NOT NULL DEFAULT '1' COMMENT 'Next available mac address for the ethernet card interacting with public internet', `guest_network_cidr` varchar(18), @@ -497,7 +499,6 @@ CREATE TABLE `cloud`.`data_center` ( `lb_provider` char(64) DEFAULT 'VirtualRouter', `vpn_provider` char(64) DEFAULT 'VirtualRouter', `userdata_provider` char(64) DEFAULT 'VirtualRouter', - `is_security_group_enabled` tinyint NOT NULL DEFAULT 0 COMMENT '1: enabled, 0: not', `allocation_state` varchar(32) NOT NULL DEFAULT 'Enabled' COMMENT 'Is this data center enabled for allocation for new resources', `zone_token` varchar(255), `removed` datetime COMMENT 'date removed if not null', @@ -562,6 +563,7 @@ CREATE TABLE `cloud`.`host_pod_ref` ( CREATE TABLE `cloud`.`op_dc_vnet_alloc` ( `id` bigint unsigned NOT NULL AUTO_INCREMENT COMMENT 'primary id', `vnet` varchar(18) NOT NULL COMMENT 'vnet', + `physical_network_id` bigint unsigned NOT NULL COMMENT 'physical network the vnet belongs to', `data_center_id` bigint unsigned NOT NULL COMMENT 'data center the vnet belongs to', `reservation_id` char(40) NULL COMMENT 'reservation id', `account_id` bigint unsigned NULL COMMENT 'account the vnet belongs to right now', @@ -1734,5 +1736,57 @@ CREATE TABLE `ntwk_offering_service_map` ( UNIQUE (`network_offering_id`, `service`, `provider`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8; +CREATE TABLE `cloud`.`physical_network` ( + `id` bigint unsigned NOT NULL AUTO_INCREMENT COMMENT 'id', + `data_center_id` bigint unsigned NOT NULL COMMENT 'data center id that this physical network belongs to', + `vnet` varchar(255), + `speed` varchar(32), + `domain_id` bigint unsigned COMMENT 'foreign key to domain id', + `broadcast_domain_range` varchar(32) NOT NULL DEFAULT 'Pod' COMMENT 'range of broadcast domain : Pod/Zone', + `state` varchar(32) NOT NULL DEFAULT 'Disabled' COMMENT 'what state is this configuration in', + `created` datetime COMMENT 'date created', + `removed` datetime COMMENT 'date removed if not null', + PRIMARY KEY (`id`), + CONSTRAINT `fk_physical_network__data_center_id` FOREIGN KEY (`data_center_id`) REFERENCES `data_center`(`id`) ON DELETE CASCADE, + CONSTRAINT `fk_physical_network__domain_id` FOREIGN KEY(`domain_id`) REFERENCES `domain`(`id`), + INDEX `i_physical_network__removed`(`removed`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8; + +CREATE TABLE `cloud`.`physical_network_tags` ( + `id` bigint unsigned NOT NULL AUTO_INCREMENT COMMENT 'id', + `physical_network_id` bigint unsigned NOT NULL COMMENT 'id of the physical network', + `tag` varchar(255) NOT NULL COMMENT 'tag', + PRIMARY KEY (`id`), + CONSTRAINT `fk_physical_network_tags__physical_network_id` FOREIGN KEY (`physical_network_id`) REFERENCES `physical_network`(`id`) ON DELETE CASCADE, + UNIQUE KEY(`physical_network_id`, `tag`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8; + +CREATE TABLE `cloud`.`physical_network_isolation_methods` ( + `id` bigint unsigned NOT NULL AUTO_INCREMENT COMMENT 'id', + `physical_network_id` bigint unsigned NOT NULL COMMENT 'id of the physical network', + `isolation_method` varchar(255) NOT NULL COMMENT 'isolation method(VLAN, L3 or GRE)', + PRIMARY KEY (`id`), + CONSTRAINT `fk_physical_network_imethods__physical_network_id` FOREIGN KEY (`physical_network_id`) REFERENCES `physical_network`(`id`) ON DELETE CASCADE, + UNIQUE KEY(`physical_network_id`, `isolation_method`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8; + +CREATE TABLE `cloud`.`physical_network_traffic_types` ( + `id` bigint unsigned NOT NULL AUTO_INCREMENT COMMENT 'id', + `physical_network_id` bigint unsigned NOT NULL COMMENT 'id of the physical network', + `traffic_type` varchar(32) NOT NULL COMMENT 'type of traffic going through this network', + PRIMARY KEY (`id`), + CONSTRAINT `fk_physical_network_traffic_types__physical_network_id` FOREIGN KEY (`physical_network_id`) REFERENCES `physical_network`(`id`) ON DELETE CASCADE, + UNIQUE KEY(`physical_network_id`, `traffic_type`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8; + +CREATE TABLE `cloud`.`physical_network_service_providers` ( + `id` bigint unsigned NOT NULL AUTO_INCREMENT COMMENT 'id', + `physical_network_id` bigint unsigned NOT NULL COMMENT 'id of the physical network', + `provider_name` varchar(255) NOT NULL COMMENT 'Service Provider name', + `state` varchar(32) NOT NULL DEFAULT 'Disabled' COMMENT 'provider state', + `destination_physical_network_id` bigint unsigned COMMENT 'id of the physical network to bridge to', + PRIMARY KEY (`id`), + CONSTRAINT `fk_pnetwork_service_providers__physical_network_id` FOREIGN KEY (`physical_network_id`) REFERENCES `physical_network`(`id`) ON DELETE CASCADE +) ENGINE=InnoDB DEFAULT CHARSET=utf8; SET foreign_key_checks = 1; diff --git a/setup/db/server-setup.xml b/setup/db/server-setup.xml index bc30986065e..b917c519666 100755 --- a/setup/db/server-setup.xml +++ b/setup/db/server-setup.xml @@ -22,8 +22,16 @@ 560-579 10.1.1.0/24 - --> + + + + 200 + 1 + 1075-1089 + + --> + + + + diff --git a/client/tomcatconf/virtualrouter_commands.properties.in b/client/tomcatconf/virtualrouter_commands.properties.in index 55ecb396567..7fc0cdcd809 100644 --- a/client/tomcatconf/virtualrouter_commands.properties.in +++ b/client/tomcatconf/virtualrouter_commands.properties.in @@ -2,4 +2,6 @@ ### Please standardize naming conventions to camel-case (even for acronyms). #### router commands -configureRouter=com.cloud.api.commands.ConfigureRouterCmd;7 \ No newline at end of file +configureDhcpElement=com.cloud.api.commands.ConfigureDhcpElementCmd;7 +configureVirtualRouterElement=com.cloud.api.commands.ConfigureVirtualRouterElementCmd;7 +configureRedundantVirtualRouterElement=com.cloud.api.commands.ConfigureRedundantVirtualRouterElementCmd;7 diff --git a/server/src/com/cloud/configuration/DefaultComponentLibrary.java b/server/src/com/cloud/configuration/DefaultComponentLibrary.java index 1806dfebd5d..efc6ba312f1 100755 --- a/server/src/com/cloud/configuration/DefaultComponentLibrary.java +++ b/server/src/com/cloud/configuration/DefaultComponentLibrary.java @@ -84,6 +84,12 @@ import com.cloud.network.dao.PhysicalNetworkDaoImpl; import com.cloud.network.dao.PhysicalNetworkServiceProviderDaoImpl; import com.cloud.network.dao.RemoteAccessVpnDaoImpl; import com.cloud.network.dao.VpnUserDaoImpl; +import com.cloud.network.element.DhcpElement; +import com.cloud.network.element.RedundantVirtualRouterElement; +import com.cloud.network.element.VirtualRouterElement; +import com.cloud.network.element.DhcpElementService; +import com.cloud.network.element.RedundantVirtualRouterElementService; +import com.cloud.network.element.VirtualRouterElementService; import com.cloud.network.firewall.FirewallManagerImpl; import com.cloud.network.lb.ElasticLoadBalancerManagerImpl; import com.cloud.network.lb.LoadBalancingRulesManagerImpl; @@ -373,7 +379,9 @@ public class DefaultComponentLibrary extends ComponentLibraryBase implements Com } protected void populateServices() { - addService("VirtualRouterService", VirtualNetworkApplianceService.class, VirtualNetworkApplianceManagerImpl.class); + addService("DhcpElementService", DhcpElementService.class, DhcpElement.class); + addService("VirtualRouterElementService", VirtualRouterElementService.class, VirtualRouterElement.class); + addService("RedundantVirtualRouterElementService", RedundantVirtualRouterElementService.class, RedundantVirtualRouterElement.class); } @Override diff --git a/server/src/com/cloud/network/element/DhcpElement.java b/server/src/com/cloud/network/element/DhcpElement.java index c1d23b29ba6..c147a839246 100644 --- a/server/src/com/cloud/network/element/DhcpElement.java +++ b/server/src/com/cloud/network/element/DhcpElement.java @@ -46,6 +46,7 @@ import com.cloud.network.dao.NetworkDao; import com.cloud.network.router.VirtualNetworkApplianceManager; import com.cloud.network.router.VirtualRouter; import com.cloud.network.router.VirtualRouter.Role; +import com.cloud.network.element.DhcpElementService; import com.cloud.offering.NetworkOffering; import com.cloud.org.Cluster; import com.cloud.user.AccountManager; @@ -64,7 +65,7 @@ import com.cloud.vm.dao.UserVmDao; @Local(value=NetworkElement.class) -public class DhcpElement extends AdapterBase implements PasswordServiceProvider { +public class DhcpElement extends AdapterBase implements DhcpElementService, PasswordServiceProvider { private static final Logger s_logger = Logger.getLogger(DhcpElement.class); private static final Map> capabilities = setCapabilities(); @@ -246,4 +247,16 @@ public class DhcpElement extends AdapterBase implements PasswordServiceProvider return _routerMgr.savePasswordToRouter(network, nic, uservm, routers); } + + @Override + public boolean configure() { + // TODO Auto-generated method stub + return false; + } + + @Override + public String getPropertiesFile() { + return "virtualrouter_commands.properties"; + } + } diff --git a/server/src/com/cloud/network/element/RedundantVirtualRouterElement.java b/server/src/com/cloud/network/element/RedundantVirtualRouterElement.java index 6f63bd1e627..eb8a5011d48 100644 --- a/server/src/com/cloud/network/element/RedundantVirtualRouterElement.java +++ b/server/src/com/cloud/network/element/RedundantVirtualRouterElement.java @@ -19,6 +19,7 @@ import com.cloud.network.Network.Service; import com.cloud.network.Network.Type; import com.cloud.network.NetworkManager; import com.cloud.network.router.VirtualRouter; +import com.cloud.network.element.RedundantVirtualRouterElementService; import com.cloud.offering.NetworkOffering; import com.cloud.uservm.UserVm; import com.cloud.utils.component.Inject; @@ -29,7 +30,7 @@ import com.cloud.vm.VirtualMachine; import com.cloud.vm.VirtualMachineProfile; @Local(value=NetworkElement.class) -public class RedundantVirtualRouterElement extends VirtualRouterElement { +public class RedundantVirtualRouterElement extends VirtualRouterElement implements RedundantVirtualRouterElementService { private static final Logger s_logger = Logger.getLogger(RedundantVirtualRouterElement.class); @Inject NetworkManager _networkMgr; @@ -77,4 +78,15 @@ public class RedundantVirtualRouterElement extends VirtualRouterElement { return false; } } + + @Override + public String getPropertiesFile() { + return "virtualrouter_commands.properties"; + } + + @Override + public boolean configure() { + // TODO Auto-generated method stub + return false; + } } diff --git a/server/src/com/cloud/network/element/VirtualRouterElement.java b/server/src/com/cloud/network/element/VirtualRouterElement.java index 201ca58f20e..421086c7521 100644 --- a/server/src/com/cloud/network/element/VirtualRouterElement.java +++ b/server/src/com/cloud/network/element/VirtualRouterElement.java @@ -51,6 +51,7 @@ import com.cloud.network.router.VirtualRouter.Role; import com.cloud.network.rules.FirewallRule; import com.cloud.network.rules.RulesManager; import com.cloud.network.rules.StaticNat; +import com.cloud.network.element.VirtualRouterElementService; import com.cloud.offering.NetworkOffering; import com.cloud.offerings.dao.NetworkOfferingDao; import com.cloud.org.Cluster; @@ -69,7 +70,7 @@ import com.cloud.vm.dao.UserVmDao; @Local(value=NetworkElement.class) -public class VirtualRouterElement extends DhcpElement implements SourceNATServiceProvider, FirewallServiceProvider, StaticNATServiceProvider, RemoteAccessVPNServiceProvider { +public class VirtualRouterElement extends DhcpElement implements VirtualRouterElementService, SourceNATServiceProvider, FirewallServiceProvider, StaticNATServiceProvider, RemoteAccessVPNServiceProvider { private static final Logger s_logger = Logger.getLogger(VirtualRouterElement.class); private static final Map> capabilities = setCapabilities(); @@ -373,4 +374,15 @@ public class VirtualRouterElement extends DhcpElement implements SourceNATServic return _routerMgr.savePasswordToRouter(network, nic, uservm, routers); } + + @Override + public String getPropertiesFile() { + return "virtualrouter_commands.properties"; + } + + @Override + public boolean configure() { + // TODO Auto-generated method stub + return false; + } } diff --git a/server/src/com/cloud/network/router/VirtualNetworkApplianceManagerImpl.java b/server/src/com/cloud/network/router/VirtualNetworkApplianceManagerImpl.java index d56ad569fe5..8ed21ce4e43 100755 --- a/server/src/com/cloud/network/router/VirtualNetworkApplianceManagerImpl.java +++ b/server/src/com/cloud/network/router/VirtualNetworkApplianceManagerImpl.java @@ -2742,10 +2742,4 @@ public class VirtualNetworkApplianceManagerImpl implements VirtualNetworkApplian public boolean processTimeout(long agentId, long seq) { return false; } - - @Override - public String getPropertiesFile() { - return "virtualrouter_commands.properties"; - } - } From fdc354adb5e930703df18708b28e24ef998f692c Mon Sep 17 00:00:00 2001 From: Sheng Yang Date: Thu, 20 Oct 2011 13:48:21 -0700 Subject: [PATCH 016/159] NaaS: Add VirtualRouterElements table It would cover the configuration of DHCPElement, VirtualRouterElement and RedundantVirtualRouterElement. Also add foreign key in domain_router table to reflect the domain_router is created from which element and use what configuration. --- core/src/com/cloud/vm/DomainRouterVO.java | 17 +- .../network/dao/VirtualRouterElementsDao.java | 29 +++ .../dao/VirtualRouterElementsDaoImpl.java | 58 +++++ .../element/VirtualRouterElements.java | 28 +++ .../element/VirtualRouterElementsVO.java | 230 ++++++++++++++++++ .../lb/ElasticLoadBalancerManagerImpl.java | 4 +- .../VirtualNetworkApplianceManagerImpl.java | 8 +- setup/db/create-schema.sql | 29 +++ 8 files changed, 393 insertions(+), 10 deletions(-) create mode 100644 server/src/com/cloud/network/dao/VirtualRouterElementsDao.java create mode 100644 server/src/com/cloud/network/dao/VirtualRouterElementsDaoImpl.java create mode 100644 server/src/com/cloud/network/element/VirtualRouterElements.java create mode 100644 server/src/com/cloud/network/element/VirtualRouterElementsVO.java diff --git a/core/src/com/cloud/vm/DomainRouterVO.java b/core/src/com/cloud/vm/DomainRouterVO.java index d6e0153672b..b34bf0d15f7 100755 --- a/core/src/com/cloud/vm/DomainRouterVO.java +++ b/core/src/com/cloud/vm/DomainRouterVO.java @@ -36,6 +36,9 @@ import com.cloud.network.router.VirtualRouter; @PrimaryKeyJoinColumn(name="id") @DiscriminatorValue(value="DomainRouter") public class DomainRouterVO extends VMInstanceVO implements VirtualRouter { + @Column(name="element_id") + private long elementId; + @Column(name="public_ip_address") private String publicIpAddress; @@ -79,6 +82,7 @@ public class DomainRouterVO extends VMInstanceVO implements VirtualRouter { public DomainRouterVO(long id, long serviceOfferingId, + long elementId, String name, long templateId, HypervisorType hypervisorType, @@ -90,9 +94,9 @@ public class DomainRouterVO extends VMInstanceVO implements VirtualRouter { int priority, boolean isPriorityBumpUp, RedundantState redundantState, - boolean haEnabled, - boolean stopPending) { + boolean haEnabled, boolean stopPending) { super(id, serviceOfferingId, name, name, Type.DomainRouter, templateId, hypervisorType, guestOSId, domainId, accountId, haEnabled); + this.elementId = elementId; this.networkId = networkId; this.isRedundantRouter = isRedundantRouter; this.priority = priority; @@ -103,6 +107,7 @@ public class DomainRouterVO extends VMInstanceVO implements VirtualRouter { public DomainRouterVO(long id, long serviceOfferingId, + long elementId, String name, long templateId, HypervisorType hypervisorType, @@ -115,9 +120,9 @@ public class DomainRouterVO extends VMInstanceVO implements VirtualRouter { boolean isPriorityBumpUp, RedundantState redundantState, boolean haEnabled, - boolean stopPending, - VirtualMachine.Type vmType) { + boolean stopPending, VirtualMachine.Type vmType) { super(id, serviceOfferingId, name, name, vmType, templateId, hypervisorType, guestOSId, domainId, accountId, haEnabled); + this.elementId = elementId; this.networkId = networkId; this.isRedundantRouter = isRedundantRouter; this.priority = priority; @@ -126,6 +131,10 @@ public class DomainRouterVO extends VMInstanceVO implements VirtualRouter { this.stopPending = stopPending; } + public long getElementId() { + return elementId; + } + public void setPublicIpAddress(String publicIpAddress) { this.publicIpAddress = publicIpAddress; } diff --git a/server/src/com/cloud/network/dao/VirtualRouterElementsDao.java b/server/src/com/cloud/network/dao/VirtualRouterElementsDao.java new file mode 100644 index 00000000000..648ddae1a9f --- /dev/null +++ b/server/src/com/cloud/network/dao/VirtualRouterElementsDao.java @@ -0,0 +1,29 @@ +/** + * Copyright (C) 2011 Citrix Systems, Inc. All rights reserved + * + * This software is licensed under the GNU General Public License v3 or later. + * + * It is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or any later version. + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + */ +package com.cloud.network.dao; + +import java.util.List; + +import com.cloud.network.element.VirtualRouterElementsVO; +import com.cloud.network.element.VirtualRouterElements.VirtualRouterElementsType; +import com.cloud.utils.db.GenericDao; + +public interface VirtualRouterElementsDao extends GenericDao { + public List findByNspIdAndType(long nspId, VirtualRouterElementsType type); + public VirtualRouterElementsVO findByUUID(String uuid); +} diff --git a/server/src/com/cloud/network/dao/VirtualRouterElementsDaoImpl.java b/server/src/com/cloud/network/dao/VirtualRouterElementsDaoImpl.java new file mode 100644 index 00000000000..93972ef4830 --- /dev/null +++ b/server/src/com/cloud/network/dao/VirtualRouterElementsDaoImpl.java @@ -0,0 +1,58 @@ +/** + * Copyright (C) 2011 Citrix Systems, Inc. All rights reserved. + * + * This software is licensed under the GNU General Public License v3 or later. + * + * It is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or any later version. + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + */ +package com.cloud.network.dao; + +import java.util.List; + +import javax.ejb.Local; + +import com.cloud.network.element.VirtualRouterElementsVO; +import com.cloud.network.element.VirtualRouterElements.VirtualRouterElementsType; +import com.cloud.utils.db.DB; +import com.cloud.utils.db.GenericDaoBase; +import com.cloud.utils.db.SearchBuilder; +import com.cloud.utils.db.SearchCriteria; + +@Local(value=VirtualRouterElementsDao.class) @DB(txn=false) +public class VirtualRouterElementsDaoImpl extends GenericDaoBase implements VirtualRouterElementsDao { + final SearchBuilder AllFieldsSearch; + + public VirtualRouterElementsDaoImpl() { + super(); + AllFieldsSearch = createSearchBuilder(); + AllFieldsSearch.and("nsp_id", AllFieldsSearch.entity().getNspId(), SearchCriteria.Op.EQ); + AllFieldsSearch.and("uuid", AllFieldsSearch.entity().getUUID(), SearchCriteria.Op.EQ); + AllFieldsSearch.and("type", AllFieldsSearch.entity().getType(), SearchCriteria.Op.EQ); + AllFieldsSearch.done(); + } + + @Override + public List findByNspIdAndType(long nspId, VirtualRouterElementsType type) { + SearchCriteria sc = AllFieldsSearch.create(); + sc.setParameters("nsp_id", nspId); + sc.setParameters("type", type); + return listBy(sc); + } + + @Override + public VirtualRouterElementsVO findByUUID(String uuid) { + SearchCriteria sc = AllFieldsSearch.create(); + sc.setParameters("uuid", uuid); + return findOneBy(sc); + } +} diff --git a/server/src/com/cloud/network/element/VirtualRouterElements.java b/server/src/com/cloud/network/element/VirtualRouterElements.java new file mode 100644 index 00000000000..3cb21796808 --- /dev/null +++ b/server/src/com/cloud/network/element/VirtualRouterElements.java @@ -0,0 +1,28 @@ +/** + * Copyright (C) 2011 Citrix Systems, Inc. All rights reserved + * + * This software is licensed under the GNU General Public License v3 or later. + * + * It is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or any later version. + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + */ + +package com.cloud.network.element; + +public interface VirtualRouterElements { + public enum VirtualRouterElementsType { + DhcpElement, + VirtualRouterElement, + RedundantVirtualRouterElement, + } + public VirtualRouterElementsType getType(); +} diff --git a/server/src/com/cloud/network/element/VirtualRouterElementsVO.java b/server/src/com/cloud/network/element/VirtualRouterElementsVO.java new file mode 100644 index 00000000000..c2720748de5 --- /dev/null +++ b/server/src/com/cloud/network/element/VirtualRouterElementsVO.java @@ -0,0 +1,230 @@ +/** + * Copyright (C) 2011 Citrix Systems, Inc. All rights reserved + * + * This software is licensed under the GNU General Public License v3 or later. + * + * It is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or any later version. + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + */ +package com.cloud.network.element; + +import java.util.Date; + +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.EnumType; +import javax.persistence.Enumerated; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; +import javax.persistence.Table; + +import com.cloud.utils.db.GenericDao; + +@Entity +@Table(name=("virtual_router_elements")) +public class VirtualRouterElementsVO implements VirtualRouterElements { + @Id + @GeneratedValue(strategy=GenerationType.IDENTITY) + @Column(name="id") + long id; + + @Column(name="type") + @Enumerated(EnumType.STRING) + private VirtualRouterElementsType type; + + @Column(name="ready") + private boolean isReady; + + @Column(name="nsp_id") + private long nspId; + + @Column(name="uuid") + private String uuid; + + @Column(name="dhcp_provided") + private boolean isDhcpProvided; + + @Column(name="dns_provided") + private boolean isDnsProvided; + + @Column(name="gateway_provided") + private boolean isGatewayProvided; + + @Column(name="firewall_provided") + private boolean isFirewallProvided; + + @Column(name="source_nat_provided") + private boolean isSourceNatProvided; + + @Column(name="load_balance_provided") + private boolean isLoadBalanceProvided; + + @Column(name="vpn_provided") + private boolean isVpnProvided; + + @Column(name="dhcp_range") + private String dhcpRange; + + @Column(name="default_domain_name") + private String defaultDomainName; + + @Column(name="dns1") + private String dns1; + + @Column(name="dns2") + private String dns2; + + @Column(name="internal_dns1") + private String internalDns1; + + @Column(name="internal_dns2") + private String internalDns2; + + @Column(name="gateway_ip") + private String gatewayIp; + + @Column(name=GenericDao.REMOVED_COLUMN) + Date removed; + + public VirtualRouterElementsVO(long nspId, String uuid, boolean isReady, VirtualRouterElementsType type, boolean isDhcpProvided, boolean isDnsProvided, + boolean isGatewayProvided, boolean isFirewallProvided, boolean isSourceNatProvided, boolean isLoadBalanceProvided, boolean isVpnProvided) { + this.nspId = nspId; + this.uuid = uuid; + this.isReady = isReady; + this.type = type; + this.isDhcpProvided = isDhcpProvided; + this.isDnsProvided = isDnsProvided; + this.isGatewayProvided = isGatewayProvided; + this.isFirewallProvided = isFirewallProvided; + this.isSourceNatProvided = isSourceNatProvided; + this.isLoadBalanceProvided = isLoadBalanceProvided; + this.isVpnProvided = isVpnProvided; + } + + public long getNspId() { + return nspId; + } + + public String getUUID() { + return uuid; + } + + public long getId() { + return id; + } + + public String getDhcpRange() { + return dhcpRange; + } + + public void setDhcpRange(String dhcpRange) { + this.dhcpRange = dhcpRange; + } + + public String getDefaultDomainName() { + return defaultDomainName; + } + + public void setDefaultDomainName(String defaultDomainName) { + this.defaultDomainName = defaultDomainName; + } + + public String getDns1() { + return dns1; + } + + public void setDns1(String dns1) { + this.dns1 = dns1; + } + + public String getDns2() { + return dns2; + } + + public void setDns2(String dns2) { + this.dns2 = dns2; + } + + public String getInternalDns1() { + return internalDns1; + } + + public void setInternalDns1(String internalDns1) { + this.internalDns1 = internalDns1; + } + + public String getInternalDns2() { + return internalDns2; + } + + public void setInternalDns2(String internalDns2) { + this.internalDns2 = internalDns2; + } + + public boolean isDhcpProvided() { + return isDhcpProvided; + } + + public boolean isDnsProvided() { + return isDnsProvided; + } + + public boolean isGatewayProvided() { + return isGatewayProvided; + } + + public boolean isFirewallProvided() { + return isFirewallProvided; + } + + public boolean isSourceNatProvided() { + return isSourceNatProvided; + } + + public boolean isLoadBalanceProvided() { + return isLoadBalanceProvided; + } + + public boolean isVpnProvided() { + return isVpnProvided; + } + + @Override + public VirtualRouterElementsType getType() { + return this.type; + } + + public String getGatewayIp() { + return gatewayIp; + } + + public void setGatewayIp(String gatewayIp) { + this.gatewayIp = gatewayIp; + } + + public Date getRemoved() { + return removed; + } + + public void setRemoved(Date removed) { + this.removed = removed; + } + + public void setReady(boolean isReady) { + this.isReady = isReady; + } + + public boolean isReady() { + return isReady; + } +} diff --git a/server/src/com/cloud/network/lb/ElasticLoadBalancerManagerImpl.java b/server/src/com/cloud/network/lb/ElasticLoadBalancerManagerImpl.java index 790bf05bd24..0fefd4de425 100644 --- a/server/src/com/cloud/network/lb/ElasticLoadBalancerManagerImpl.java +++ b/server/src/com/cloud/network/lb/ElasticLoadBalancerManagerImpl.java @@ -497,8 +497,8 @@ public class ElasticLoadBalancerManagerImpl implements VMTemplateVO template = _templateDao.findSystemVMTemplate(dcId); - elbVm = new DomainRouterVO(id, _elasticLbVmOffering.getId(), VirtualMachineName.getSystemVmName(id, _instance, _elbVmNamePrefix), template.getId(), template.getHypervisorType(), template.getGuestOSId(), - owner.getDomainId(), owner.getId(), guestNetwork.getId(), false, 0, false, RedundantState.UNKNOWN, _elasticLbVmOffering.getOfferHA(), false, VirtualMachine.Type.ElasticLoadBalancerVm); + elbVm = new DomainRouterVO(id, _elasticLbVmOffering.getId(), 0, VirtualMachineName.getSystemVmName(id, _instance, _elbVmNamePrefix), template.getId(), template.getHypervisorType(), + template.getGuestOSId(), owner.getDomainId(), owner.getId(), guestNetwork.getId(), false, 0, false, RedundantState.UNKNOWN, _elasticLbVmOffering.getOfferHA(), false, VirtualMachine.Type.ElasticLoadBalancerVm); elbVm.setRole(Role.LB); elbVm = _itMgr.allocate(elbVm, template, _elasticLbVmOffering, networks, plan, null, owner); //TODO: create usage stats diff --git a/server/src/com/cloud/network/router/VirtualNetworkApplianceManagerImpl.java b/server/src/com/cloud/network/router/VirtualNetworkApplianceManagerImpl.java index 8ed21ce4e43..f278ed10ac1 100755 --- a/server/src/com/cloud/network/router/VirtualNetworkApplianceManagerImpl.java +++ b/server/src/com/cloud/network/router/VirtualNetworkApplianceManagerImpl.java @@ -1090,8 +1090,8 @@ public class VirtualNetworkApplianceManagerImpl implements VirtualNetworkApplian if (routers.size() >= 5) { s_logger.error("Too much redundant routers!"); } - router = new DomainRouterVO(id, _offering.getId(), VirtualMachineName.getRouterName(id, _instance), template.getId(), template.getHypervisorType(), template.getGuestOSId(), - owner.getDomainId(), owner.getId(), guestNetwork.getId(), isRedundant, 0, false, RedundantState.UNKNOWN, _offering.getOfferHA(), false); + router = new DomainRouterVO(id, _offering.getId(), 0, VirtualMachineName.getRouterName(id, _instance), template.getId(), template.getHypervisorType(), + template.getGuestOSId(), owner.getDomainId(), owner.getId(), guestNetwork.getId(), isRedundant, 0, false, RedundantState.UNKNOWN, _offering.getOfferHA(), false); router = _itMgr.allocate(router, template, _offering, networks, plan, null, owner); // Creating stats entry for router UserStatisticsVO stats = _userStatsDao.findBy(owner.getId(), dcId, router.getNetworkId(), null, router.getId(), router.getType().toString()); @@ -1275,8 +1275,8 @@ public class VirtualNetworkApplianceManagerImpl implements VirtualNetworkApplian /* Before starting router, already know the hypervisor type */ VMTemplateVO template = _templateDao.findRoutingTemplate(dest.getCluster().getHypervisorType()); - router = new DomainRouterVO(id, _offering.getId(), VirtualMachineName.getRouterName(id, _instance), template.getId(), template.getHypervisorType(), template.getGuestOSId(), - owner.getDomainId(), owner.getId(), guestNetwork.getId(), false, 0, false, RedundantState.UNKNOWN, _offering.getOfferHA(), false); + router = new DomainRouterVO(id, _offering.getId(), 0, VirtualMachineName.getRouterName(id, _instance), template.getId(), template.getHypervisorType(), + template.getGuestOSId(), owner.getDomainId(), owner.getId(), guestNetwork.getId(), false, 0, false, RedundantState.UNKNOWN, _offering.getOfferHA(), false); router.setRole(Role.DHCP_USERDATA); router = _itMgr.allocate(router, template, _offering, networks, plan, null, owner); routers.add(router); diff --git a/setup/db/create-schema.sql b/setup/db/create-schema.sql index f76d564741c..ad6f682b1f1 100755 --- a/setup/db/create-schema.sql +++ b/setup/db/create-schema.sql @@ -118,6 +118,7 @@ DROP TABLE IF EXISTS `cloud`.`network_tags`; DROP TABLE IF EXISTS `cloud`.`op_host_transfer`; DROP TABLE IF EXISTS `cloud`.`projects`; DROP TABLE IF EXISTS `cloud`.`physical_network`; +DROP TABLE IF EXISTS `cloud`.`virtual_router_elements`; CREATE TABLE `cloud`.`version` ( `id` bigint unsigned NOT NULL UNIQUE AUTO_INCREMENT COMMENT 'id', @@ -929,6 +930,7 @@ CREATE TABLE `cloud`.`user_vm_details` ( CREATE TABLE `cloud`.`domain_router` ( `id` bigint unsigned UNIQUE NOT NULL COMMENT 'Primary Key', + `element_id` bigint unsigned NOT NULL COMMENT 'correlated virtual router element ID', `public_mac_address` varchar(17) COMMENT 'mac address of the public facing network card', `public_ip_address` char(40) COMMENT 'public ip address used for source net', `public_netmask` varchar(15) COMMENT 'netmask used for the domR', @@ -945,6 +947,7 @@ CREATE TABLE `cloud`.`domain_router` ( `scripts_version` varchar(100) COMMENT 'scripts version', PRIMARY KEY (`id`), CONSTRAINT `fk_domain_router__id` FOREIGN KEY `fk_domain_router__id` (`id`) REFERENCES `vm_instance`(`id`) ON DELETE CASCADE + #CONSTRAINT `fk_domain_router__element_id` FOREIGN KEY `fk_domain_router__element_id` (`element_id`) REFERENCES `virtual_router_elements`(`id`) ) ENGINE = InnoDB DEFAULT CHARSET=utf8 COMMENT = 'information about the domR instance'; CREATE TABLE `cloud`.`upload` ( @@ -1724,6 +1727,32 @@ CREATE TABLE `cloud`.`elastic_lb_vm_map` ( CONSTRAINT `fk_elastic_lb_vm_map__lb_id` FOREIGN KEY `fk_elastic_lb_vm_map__lb_id` (`lb_id`) REFERENCES `load_balancing_rules` (`id`) ON DELETE CASCADE ) ENGINE=InnoDB DEFAULT CHARSET=utf8; +CREATE TABLE `cloud`.`virtual_router_elements` ( + `id` bigint unsigned NOT NULL auto_increment, + `nsp_id` bigint unsigned NOT NULL, + `uuid` varchar(255) UNIQUE, + `ready` int(1) NOT NULL, + `type` varchar(255) NOT NULL, + `dhcp_provided` int(1) NOT NULL, + `dns_provided` int(1) NOT NULL, + `gateway_provided` int(1) NOT NULL, + `firewall_provided` int(1) NOT NULL, + `source_nat_provided` int(1) NOT NULL, + `load_balance_provided` int(1) NOT NULL, + `vpn_provided` int(1) NOT NULL, + `service_offering_id` bigint unsigned NOT NULL, + `dhcp_range` varchar(255), + `default_domain_name` varchar(255), + `dns1` varchar(255), + `dns2` varchar(255), + `internal_dns1` varchar(255), + `internal_dns2` varchar(255), + `gateway_ip` varchar(255), + `removed` datetime COMMENT 'date removed if not null', + PRIMARY KEY (`id`), + CONSTRAINT `fk_virtual_router_elements__service_offering_id` FOREIGN KEY `fk_virtual_router_elements__service_offering_id` (`service_offering_id`) REFERENCES `service_offering`(`id`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8; + CREATE TABLE `ntwk_offering_service_map` ( `id` bigint unsigned NOT NULL auto_increment, From 2ebb719aba583e7667bb7293cb955afe0d48f97f Mon Sep 17 00:00:00 2001 From: Sheng Yang Date: Fri, 14 Oct 2011 11:46:05 -0700 Subject: [PATCH 017/159] NaaS: Add configuration for virtual router elements --- api/src/com/cloud/api/ApiConstants.java | 3 +- .../api/commands/ConfigureDhcpElementCmd.java | 79 +++++++++-- ...igureRedundantVirtualRouterElementCmd.java | 123 ++++++++++++++++-- .../ConfigureVirtualRouterElementCmd.java | 121 +++++++++++++++-- .../network/element/DhcpElementService.java | 5 +- .../RedundantVirtualRouterElementService.java | 6 +- .../element/VirtualRouterElementService.java | 6 +- client/tomcatconf/components-premium.xml.in | 1 + client/tomcatconf/components.xml.in | 1 + .../DefaultComponentLibrary.java | 2 + .../network/dao/VirtualRouterElementsDao.java | 2 +- .../dao/VirtualRouterElementsDaoImpl.java | 2 +- .../cloud/network/element/DhcpElement.java | 69 +++++++++- .../RedundantVirtualRouterElement.java | 60 ++++++++- .../network/element/VirtualRouterElement.java | 60 ++++++++- .../element/VirtualRouterElementsVO.java | 83 ++++++++++-- .../VirtualNetworkApplianceManager.java | 3 +- .../VirtualNetworkApplianceManagerImpl.java | 8 ++ .../cloud/server/ConfigurationServerImpl.java | 4 +- 19 files changed, 576 insertions(+), 62 deletions(-) diff --git a/api/src/com/cloud/api/ApiConstants.java b/api/src/com/cloud/api/ApiConstants.java index d8fb58579c6..e754dfcdac4 100755 --- a/api/src/com/cloud/api/ApiConstants.java +++ b/api/src/com/cloud/api/ApiConstants.java @@ -284,5 +284,6 @@ public class ApiConstants { public static final String DEST_PHYSICAL_NETWORK_ID = "destinationphysicalnetworkid"; public static final String ENABLED = "enabled"; public static final String SERVICE_NAME = "servicename"; - + public static final String DHCP_RANGE = "dhcprange"; + public static final String UUID = "uuid"; } diff --git a/api/src/com/cloud/api/commands/ConfigureDhcpElementCmd.java b/api/src/com/cloud/api/commands/ConfigureDhcpElementCmd.java index 5fd11f733e0..e0bb937553d 100644 --- a/api/src/com/cloud/api/commands/ConfigureDhcpElementCmd.java +++ b/api/src/com/cloud/api/commands/ConfigureDhcpElementCmd.java @@ -49,15 +49,78 @@ public class ConfigureDhcpElementCmd extends BaseAsyncCmd { //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// - @Parameter(name=ApiConstants.ID, type=CommandType.LONG, required=true, description="the ID of the dhcp element") - private Long id; + @Parameter(name=ApiConstants.UUID, type=CommandType.STRING, required=true, description="the UUID of the virtual router element") + private String uuid; + @Parameter(name=ApiConstants.DHCP_SERVICE, type=CommandType.BOOLEAN, required=true, description="true is dhcp service would be enabled") + private Boolean dhcpService; + + @Parameter(name=ApiConstants.DNS_SERVICE, type=CommandType.BOOLEAN, required=true, description="true is dns service would be enabled") + private Boolean dnsService; + + @Parameter(name=ApiConstants.USERDATA_SERVICE, type=CommandType.BOOLEAN, required=true, description="true is user data service would be enabled") + private Boolean userdataService; + + @Parameter(name=ApiConstants.DHCP_RANGE, type=CommandType.STRING, description="the dhcp range for the DHCP service ") + private String dhcpRange; + + @Parameter(name=ApiConstants.DNS1, type=CommandType.STRING, description="the first DNS") + private String dns1; + + @Parameter(name=ApiConstants.DNS2, type=CommandType.STRING, description="the second DNS") + private String dns2; + + @Parameter(name=ApiConstants.INTERNAL_DNS1, type=CommandType.STRING, description="the first internal DNS") + private String internalDns1; + + @Parameter(name=ApiConstants.INTERNAL_DNS2, type=CommandType.STRING, description="the second internal DNS") + private String internalDns2; + + @Parameter(name=ApiConstants.DOMAIN, type=CommandType.STRING, description="the gateway ip") + private String domainName; + ///////////////////////////////////////////////////// /////////////////// Accessors /////////////////////// ///////////////////////////////////////////////////// - public Long getId() { - return id; + public String getUUID() { + return uuid; + } + + public Boolean getDhcpService() { + return dhcpService; + } + + public Boolean getDnsService() { + return dnsService; + } + + public Boolean getUserdataService() { + return userdataService; + } + + public String getDomainName() { + return domainName; + } + + public String getDhcpRange() { + return dhcpRange; + } + + public String getDns1() { + return dns1; + } + + public String getDns2() { + return dns2; + } + + public String getInternalDns1() { + return internalDns1; + } + + public String getInternalDns2() { + return internalDns2; } ///////////////////////////////////////////////////// @@ -85,7 +148,7 @@ public class ConfigureDhcpElementCmd extends BaseAsyncCmd { @Override public String getEventDescription() { - return "configuring dhcp element: " + getId(); + return "configuring dhcp element: " + getUUID(); } public AsyncJob.Type getInstanceType() { @@ -93,13 +156,13 @@ public class ConfigureDhcpElementCmd extends BaseAsyncCmd { } public Long getInstanceId() { - return getId(); + return _service.getIdByUUID(uuid); } @Override public void execute() throws ConcurrentOperationException, ResourceUnavailableException, InsufficientCapacityException{ - UserContext.current().setEventDetails("Dhcp element Id: " + getId()); - Boolean result = _service.configure(); + UserContext.current().setEventDetails("Dhcp element: " + getUUID()); + Boolean result = _service.configure(this); if (result){ SuccessResponse response = new SuccessResponse(); response.setResponseName(getCommandName()); diff --git a/api/src/com/cloud/api/commands/ConfigureRedundantVirtualRouterElementCmd.java b/api/src/com/cloud/api/commands/ConfigureRedundantVirtualRouterElementCmd.java index e31acd8705b..405cb7c113b 100644 --- a/api/src/com/cloud/api/commands/ConfigureRedundantVirtualRouterElementCmd.java +++ b/api/src/com/cloud/api/commands/ConfigureRedundantVirtualRouterElementCmd.java @@ -49,17 +49,122 @@ public class ConfigureRedundantVirtualRouterElementCmd extends BaseAsyncCmd { //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// - @Parameter(name=ApiConstants.ID, type=CommandType.LONG, required=true, description="the ID of the redundant virtual router element") - private Long id; + @Parameter(name=ApiConstants.UUID, type=CommandType.STRING, required=true, description="the UUID of the virtual router element") + private String uuid; - ///////////////////////////////////////////////////// + @Parameter(name=ApiConstants.DHCP_SERVICE, type=CommandType.BOOLEAN, required=true, description="true is dhcp service would be enabled") + private Boolean dhcpService; + + @Parameter(name=ApiConstants.DNS_SERVICE, type=CommandType.BOOLEAN, required=true, description="true is dns service would be enabled") + private Boolean dnsService; + + @Parameter(name=ApiConstants.GATEWAY_SERVICE, type=CommandType.BOOLEAN, required=true, description="true is gateway service would be enabled") + private Boolean gatewayService; + + @Parameter(name=ApiConstants.FIREWALL_SERVICE, type=CommandType.BOOLEAN, required=true, description="true is firewall service would be enabled") + private Boolean firewallService; + + @Parameter(name=ApiConstants.LB_SERVICE, type=CommandType.BOOLEAN, required=true, description="true is lb service would be enabled") + private Boolean lbService; + + @Parameter(name=ApiConstants.USERDATA_SERVICE, type=CommandType.BOOLEAN, required=true, description="true is user data service would be enabled") + private Boolean userdataService; + + @Parameter(name=ApiConstants.SOURCE_NAT_SERVICE, type=CommandType.BOOLEAN, required=true, description="true is source nat service would be enabled") + private Boolean sourceNatService; + + @Parameter(name=ApiConstants.VPN_SERVICE, type=CommandType.BOOLEAN, required=true, description="true is vpn service would be enabled") + private Boolean vpnService; + + @Parameter(name=ApiConstants.DHCP_RANGE, type=CommandType.STRING, description="the dhcp range for the DHCP service ") + private String dhcpRange; + + @Parameter(name=ApiConstants.DNS1, type=CommandType.STRING, description="the first DNS") + private String dns1; + + @Parameter(name=ApiConstants.DNS2, type=CommandType.STRING, description="the second DNS") + private String dns2; + + @Parameter(name=ApiConstants.INTERNAL_DNS1, type=CommandType.STRING, description="the first internal DNS") + private String internalDns1; + + @Parameter(name=ApiConstants.INTERNAL_DNS2, type=CommandType.STRING, description="the second internal DNS") + private String internalDns2; + + @Parameter(name=ApiConstants.GATEWAY, type=CommandType.STRING, description="the gateway ip") + private String gateway; + + @Parameter(name=ApiConstants.DOMAIN, type=CommandType.STRING, description="the gateway ip") + private String domainName; + /////////////////// Accessors /////////////////////// ///////////////////////////////////////////////////// - public Long getId() { - return id; + public String getUUID() { + return uuid; } + public Boolean getDhcpService() { + return dhcpService; + } + + public Boolean getDnsService() { + return dnsService; + } + + public Boolean getGatewayService() { + return gatewayService; + } + + public Boolean getFirewallService() { + return firewallService; + } + + public Boolean getLbService() { + return lbService; + } + + public Boolean getUserdataService() { + return userdataService; + } + + public Boolean getSourceNatService() { + return sourceNatService; + } + + public Boolean getVpnService() { + return vpnService; + } + + public String getDomainName() { + return domainName; + } + + public String getDhcpRange() { + return dhcpRange; + } + + public String getDns1() { + return dns1; + } + + public String getDns2() { + return dns2; + } + + public String getInternalDns1() { + return internalDns1; + } + + public String getInternalDns2() { + return internalDns2; + } + + public String getGateway() { + return gateway; + } + + ///////////////////////////////////////////////////// /////////////// API Implementation/////////////////// ///////////////////////////////////////////////////// @@ -85,7 +190,7 @@ public class ConfigureRedundantVirtualRouterElementCmd extends BaseAsyncCmd { @Override public String getEventDescription() { - return "configuring redundant virtual router element: " + getId(); + return "configuring redundant virtual router element: " + getUUID(); } public AsyncJob.Type getInstanceType() { @@ -93,13 +198,13 @@ public class ConfigureRedundantVirtualRouterElementCmd extends BaseAsyncCmd { } public Long getInstanceId() { - return getId(); + return _service.getIdByUUID(uuid); } @Override public void execute() throws ConcurrentOperationException, ResourceUnavailableException, InsufficientCapacityException{ - UserContext.current().setEventDetails("Redundant virtual router element Id: " + getId()); - Boolean result = _service.configure(); + UserContext.current().setEventDetails("Redundant virtual router element: " + getUUID()); + Boolean result = _service.configure(this); if (result){ SuccessResponse response = new SuccessResponse(); response.setResponseName(getCommandName()); diff --git a/api/src/com/cloud/api/commands/ConfigureVirtualRouterElementCmd.java b/api/src/com/cloud/api/commands/ConfigureVirtualRouterElementCmd.java index 487a15421ca..af8e3297417 100644 --- a/api/src/com/cloud/api/commands/ConfigureVirtualRouterElementCmd.java +++ b/api/src/com/cloud/api/commands/ConfigureVirtualRouterElementCmd.java @@ -49,15 +49,120 @@ public class ConfigureVirtualRouterElementCmd extends BaseAsyncCmd { //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// - @Parameter(name=ApiConstants.ID, type=CommandType.LONG, required=true, description="the ID of the virtual router element") - private Long id; + @Parameter(name=ApiConstants.UUID, type=CommandType.STRING, required=true, description="the UUID of the virtual router element") + private String uuid; + @Parameter(name=ApiConstants.DHCP_SERVICE, type=CommandType.BOOLEAN, required=true, description="true is dhcp service would be enabled") + private Boolean dhcpService; + + @Parameter(name=ApiConstants.DNS_SERVICE, type=CommandType.BOOLEAN, required=true, description="true is dns service would be enabled") + private Boolean dnsService; + + @Parameter(name=ApiConstants.GATEWAY_SERVICE, type=CommandType.BOOLEAN, required=true, description="true is gateway service would be enabled") + private Boolean gatewayService; + + @Parameter(name=ApiConstants.FIREWALL_SERVICE, type=CommandType.BOOLEAN, required=true, description="true is firewall service would be enabled") + private Boolean firewallService; + + @Parameter(name=ApiConstants.LB_SERVICE, type=CommandType.BOOLEAN, required=true, description="true is lb service would be enabled") + private Boolean lbService; + + @Parameter(name=ApiConstants.USERDATA_SERVICE, type=CommandType.BOOLEAN, required=true, description="true is user data service would be enabled") + private Boolean userdataService; + + @Parameter(name=ApiConstants.SOURCE_NAT_SERVICE, type=CommandType.BOOLEAN, required=true, description="true is source nat service would be enabled") + private Boolean sourceNatService; + + @Parameter(name=ApiConstants.VPN_SERVICE, type=CommandType.BOOLEAN, required=true, description="true is vpn service would be enabled") + private Boolean vpnService; + + @Parameter(name=ApiConstants.DHCP_RANGE, type=CommandType.STRING, description="the dhcp range for the DHCP service ") + private String dhcpRange; + + @Parameter(name=ApiConstants.DNS1, type=CommandType.STRING, description="the first DNS") + private String dns1; + + @Parameter(name=ApiConstants.DNS2, type=CommandType.STRING, description="the second DNS") + private String dns2; + + @Parameter(name=ApiConstants.INTERNAL_DNS1, type=CommandType.STRING, description="the first internal DNS") + private String internalDns1; + + @Parameter(name=ApiConstants.INTERNAL_DNS2, type=CommandType.STRING, description="the second internal DNS") + private String internalDns2; + + @Parameter(name=ApiConstants.GATEWAY, type=CommandType.STRING, description="the gateway ip") + private String gateway; + + @Parameter(name=ApiConstants.DOMAIN, type=CommandType.STRING, description="the gateway ip") + private String domainName; + ///////////////////////////////////////////////////// /////////////////// Accessors /////////////////////// ///////////////////////////////////////////////////// - public Long getId() { - return id; + public String getUUID() { + return uuid; + } + + public Boolean getDhcpService() { + return dhcpService; + } + + public Boolean getDnsService() { + return dnsService; + } + + public Boolean getGatewayService() { + return gatewayService; + } + + public Boolean getFirewallService() { + return firewallService; + } + + public Boolean getLbService() { + return lbService; + } + + public Boolean getUserdataService() { + return userdataService; + } + + public Boolean getSourceNatService() { + return sourceNatService; + } + + public Boolean getVpnService() { + return vpnService; + } + + public String getDomainName() { + return domainName; + } + + public String getDhcpRange() { + return dhcpRange; + } + + public String getDns1() { + return dns1; + } + + public String getDns2() { + return dns2; + } + + public String getInternalDns1() { + return internalDns1; + } + + public String getInternalDns2() { + return internalDns2; + } + + public String getGateway() { + return gateway; } ///////////////////////////////////////////////////// @@ -85,7 +190,7 @@ public class ConfigureVirtualRouterElementCmd extends BaseAsyncCmd { @Override public String getEventDescription() { - return "configuring virtual router element: " + getId(); + return "configuring virtual router element: " + getUUID(); } public AsyncJob.Type getInstanceType() { @@ -93,13 +198,13 @@ public class ConfigureVirtualRouterElementCmd extends BaseAsyncCmd { } public Long getInstanceId() { - return getId(); + return _service.getIdByUUID(uuid); } @Override public void execute() throws ConcurrentOperationException, ResourceUnavailableException, InsufficientCapacityException{ - UserContext.current().setEventDetails("Virtual router element Id: " + getId()); - Boolean result = _service.configure(); + UserContext.current().setEventDetails("Virtual router element: " + getUUID()); + Boolean result = _service.configure(this); if (result){ SuccessResponse response = new SuccessResponse(); response.setResponseName(getCommandName()); diff --git a/api/src/com/cloud/network/element/DhcpElementService.java b/api/src/com/cloud/network/element/DhcpElementService.java index 848c79841b5..4871130feef 100644 --- a/api/src/com/cloud/network/element/DhcpElementService.java +++ b/api/src/com/cloud/network/element/DhcpElementService.java @@ -1,7 +1,10 @@ package com.cloud.network.element; +import com.cloud.api.commands.ConfigureDhcpElementCmd; import com.cloud.utils.component.PluggableService; public interface DhcpElementService extends PluggableService{ - boolean configure(); + boolean configure(ConfigureDhcpElementCmd cmd); + boolean addElement(Long nspId, String uuid); + Long getIdByUUID(String uuid); } diff --git a/api/src/com/cloud/network/element/RedundantVirtualRouterElementService.java b/api/src/com/cloud/network/element/RedundantVirtualRouterElementService.java index ec54099fd35..1b4d8a2cf66 100644 --- a/api/src/com/cloud/network/element/RedundantVirtualRouterElementService.java +++ b/api/src/com/cloud/network/element/RedundantVirtualRouterElementService.java @@ -1,7 +1,7 @@ package com.cloud.network.element; -import com.cloud.utils.component.PluggableService; +import com.cloud.api.commands.ConfigureRedundantVirtualRouterElementCmd; -public interface RedundantVirtualRouterElementService extends PluggableService{ - boolean configure(); +public interface RedundantVirtualRouterElementService extends VirtualRouterElementService { + boolean configure(ConfigureRedundantVirtualRouterElementCmd cmd); } diff --git a/api/src/com/cloud/network/element/VirtualRouterElementService.java b/api/src/com/cloud/network/element/VirtualRouterElementService.java index 705fc8b168c..a5ca60335c0 100644 --- a/api/src/com/cloud/network/element/VirtualRouterElementService.java +++ b/api/src/com/cloud/network/element/VirtualRouterElementService.java @@ -1,7 +1,7 @@ package com.cloud.network.element; -import com.cloud.utils.component.PluggableService; +import com.cloud.api.commands.ConfigureVirtualRouterElementCmd; -public interface VirtualRouterElementService extends PluggableService{ - boolean configure(); +public interface VirtualRouterElementService extends DhcpElementService { + boolean configure(ConfigureVirtualRouterElementCmd cmd); } diff --git a/client/tomcatconf/components-premium.xml.in b/client/tomcatconf/components-premium.xml.in index 9472e76744d..cc032d99ed7 100755 --- a/client/tomcatconf/components-premium.xml.in +++ b/client/tomcatconf/components-premium.xml.in @@ -24,6 +24,7 @@ + diff --git a/client/tomcatconf/components.xml.in b/client/tomcatconf/components.xml.in index b7288f8b5bf..14fea2bc226 100755 --- a/client/tomcatconf/components.xml.in +++ b/client/tomcatconf/components.xml.in @@ -131,5 +131,6 @@ + diff --git a/server/src/com/cloud/configuration/DefaultComponentLibrary.java b/server/src/com/cloud/configuration/DefaultComponentLibrary.java index efc6ba312f1..251c163bdbe 100755 --- a/server/src/com/cloud/configuration/DefaultComponentLibrary.java +++ b/server/src/com/cloud/configuration/DefaultComponentLibrary.java @@ -83,6 +83,7 @@ import com.cloud.network.dao.NetworkRuleConfigDaoImpl; import com.cloud.network.dao.PhysicalNetworkDaoImpl; import com.cloud.network.dao.PhysicalNetworkServiceProviderDaoImpl; import com.cloud.network.dao.RemoteAccessVpnDaoImpl; +import com.cloud.network.dao.VirtualRouterElementsDaoImpl; import com.cloud.network.dao.VpnUserDaoImpl; import com.cloud.network.element.DhcpElement; import com.cloud.network.element.RedundantVirtualRouterElement; @@ -295,6 +296,7 @@ public class DefaultComponentLibrary extends ComponentLibraryBase implements Com info.addParameter("cache.time.to.live", "600"); addDao("PhysicalNetworkDao", PhysicalNetworkDaoImpl.class); addDao("PhysicalNetworkServiceProviderDao", PhysicalNetworkServiceProviderDaoImpl.class); + addDao("VirtualRouterElementsDao", VirtualRouterElementsDaoImpl.class); } @Override diff --git a/server/src/com/cloud/network/dao/VirtualRouterElementsDao.java b/server/src/com/cloud/network/dao/VirtualRouterElementsDao.java index 648ddae1a9f..ff750cdb742 100644 --- a/server/src/com/cloud/network/dao/VirtualRouterElementsDao.java +++ b/server/src/com/cloud/network/dao/VirtualRouterElementsDao.java @@ -23,7 +23,7 @@ import com.cloud.network.element.VirtualRouterElementsVO; import com.cloud.network.element.VirtualRouterElements.VirtualRouterElementsType; import com.cloud.utils.db.GenericDao; -public interface VirtualRouterElementsDao extends GenericDao { +public interface VirtualRouterElementsDao extends GenericDao { public List findByNspIdAndType(long nspId, VirtualRouterElementsType type); public VirtualRouterElementsVO findByUUID(String uuid); } diff --git a/server/src/com/cloud/network/dao/VirtualRouterElementsDaoImpl.java b/server/src/com/cloud/network/dao/VirtualRouterElementsDaoImpl.java index 93972ef4830..2ebda6338ac 100644 --- a/server/src/com/cloud/network/dao/VirtualRouterElementsDaoImpl.java +++ b/server/src/com/cloud/network/dao/VirtualRouterElementsDaoImpl.java @@ -36,7 +36,7 @@ public class VirtualRouterElementsDaoImpl extends GenericDaoBase rules, List routers) throws ResourceUnavailableException; - + + long getDefaultVirtualRouterServiceOfferingId(); } diff --git a/server/src/com/cloud/network/router/VirtualNetworkApplianceManagerImpl.java b/server/src/com/cloud/network/router/VirtualNetworkApplianceManagerImpl.java index f278ed10ac1..cd30210133b 100755 --- a/server/src/com/cloud/network/router/VirtualNetworkApplianceManagerImpl.java +++ b/server/src/com/cloud/network/router/VirtualNetworkApplianceManagerImpl.java @@ -2742,4 +2742,12 @@ public class VirtualNetworkApplianceManagerImpl implements VirtualNetworkApplian public boolean processTimeout(long agentId, long seq) { return false; } + + @Override + public long getDefaultVirtualRouterServiceOfferingId() { + if (_offering != null) { + return _offering.getId(); + } + return 0; + } } diff --git a/server/src/com/cloud/server/ConfigurationServerImpl.java b/server/src/com/cloud/server/ConfigurationServerImpl.java index e3d7d57dc77..1bfbcd07017 100644 --- a/server/src/com/cloud/server/ConfigurationServerImpl.java +++ b/server/src/com/cloud/server/ConfigurationServerImpl.java @@ -75,6 +75,7 @@ import com.cloud.network.Networks.BroadcastDomainType; import com.cloud.network.Networks.Mode; import com.cloud.network.Networks.TrafficType; import com.cloud.network.dao.NetworkDao; +import com.cloud.network.dao.VirtualRouterElementsDao; import com.cloud.network.guru.ControlNetworkGuru; import com.cloud.network.guru.DirectPodBasedNetworkGuru; import com.cloud.network.guru.PodBasedNetworkGuru; @@ -120,6 +121,7 @@ public class ConfigurationServerImpl implements ConfigurationServer { private final AccountDao _accountDao; private final ResourceCountDao _resourceCountDao; private final NetworkOfferingServiceMapDao _offeringServiceMapDao; + private final VirtualRouterElementsDao _virtualRouterElementsDao; public ConfigurationServerImpl() { @@ -137,7 +139,7 @@ public class ConfigurationServerImpl implements ConfigurationServer { _accountDao = locator.getDao(AccountDao.class); _resourceCountDao = locator.getDao(ResourceCountDao.class); _offeringServiceMapDao = locator.getDao(NetworkOfferingServiceMapDao.class); - + _virtualRouterElementsDao = locator.getDao(VirtualRouterElementsDao.class); } @Override @DB From 21344e3c36f8a7cc63abb9dc8974622eadf05ffe Mon Sep 17 00:00:00 2001 From: Sheng Yang Date: Thu, 20 Oct 2011 15:18:07 -0700 Subject: [PATCH 018/159] NaaS: Remove some API test code --- server/src/com/cloud/network/element/DhcpElement.java | 1 - .../com/cloud/network/element/RedundantVirtualRouterElement.java | 1 - server/src/com/cloud/network/element/VirtualRouterElement.java | 1 - 3 files changed, 3 deletions(-) diff --git a/server/src/com/cloud/network/element/DhcpElement.java b/server/src/com/cloud/network/element/DhcpElement.java index 76ea1db465f..c04878b1675 100644 --- a/server/src/com/cloud/network/element/DhcpElement.java +++ b/server/src/com/cloud/network/element/DhcpElement.java @@ -259,7 +259,6 @@ public class DhcpElement extends AdapterBase implements DhcpElementService, Pass @Override public boolean configure(ConfigureDhcpElementCmd cmd) { - addElement(new Long(3), cmd.getUUID()); VirtualRouterElementsVO element = _vrElementsDao.findByUUID(cmd.getUUID()); if (element == null) { s_logger.trace("Can't find element with UUID " + cmd.getUUID()); diff --git a/server/src/com/cloud/network/element/RedundantVirtualRouterElement.java b/server/src/com/cloud/network/element/RedundantVirtualRouterElement.java index 962d3133e12..72adee1fc9d 100644 --- a/server/src/com/cloud/network/element/RedundantVirtualRouterElement.java +++ b/server/src/com/cloud/network/element/RedundantVirtualRouterElement.java @@ -90,7 +90,6 @@ public class RedundantVirtualRouterElement extends VirtualRouterElement implemen @Override public boolean configure(ConfigureRedundantVirtualRouterElementCmd cmd) { - addElement(new Long(2), cmd.getUUID()); VirtualRouterElementsVO element = _vrElementsDao.findByUUID(cmd.getUUID()); if (element == null) { s_logger.trace("Can't find element with UUID " + cmd.getUUID()); diff --git a/server/src/com/cloud/network/element/VirtualRouterElement.java b/server/src/com/cloud/network/element/VirtualRouterElement.java index aeb3295439a..7ee1841a9b7 100644 --- a/server/src/com/cloud/network/element/VirtualRouterElement.java +++ b/server/src/com/cloud/network/element/VirtualRouterElement.java @@ -386,7 +386,6 @@ public class VirtualRouterElement extends DhcpElement implements VirtualRouterEl @Override public boolean configure(ConfigureVirtualRouterElementCmd cmd) { - addElement(new Long(1), cmd.getUUID()); VirtualRouterElementsVO element = _vrElementsDao.findByUUID(cmd.getUUID()); if (element == null) { s_logger.trace("Can't find element with UUID " + cmd.getUUID()); From 0d7ddb5d5857b7e4af4d68fa4677655b4434eaac Mon Sep 17 00:00:00 2001 From: prachi Date: Thu, 20 Oct 2011 17:10:00 -0700 Subject: [PATCH 019/159] Changes: - Make all API commands Async and add events - Make BroadcatsDomainRange case insensitive - Process all _networkElements to build the Service -> Provider map during NetworkMgr::configure() --- .../AddNetworkServiceProviderCmd.java | 29 ++++++- .../commands/CreatePhysicalNetworkCmd.java | 40 ++++++++- .../DeleteNetworkServiceProviderCmd.java | 16 +++- .../commands/DeletePhysicalNetworkCmd.java | 17 +++- .../UpdateNetworkServiceProviderCmd.java | 14 +++- .../commands/UpdatePhysicalNetworkCmd.java | 16 +++- api/src/com/cloud/event/EventTypes.java | 11 +++ api/src/com/cloud/network/NetworkService.java | 8 ++ .../com/cloud/network/PhysicalNetwork.java | 4 +- .../com/cloud/network/NetworkManagerImpl.java | 82 ++++++++++++++----- .../com/cloud/network/PhysicalNetworkVO.java | 2 +- .../network/element/ExternalDhcpElement.java | 12 ++- setup/db/create-schema.sql | 2 +- 13 files changed, 214 insertions(+), 39 deletions(-) diff --git a/api/src/com/cloud/api/commands/AddNetworkServiceProviderCmd.java b/api/src/com/cloud/api/commands/AddNetworkServiceProviderCmd.java index fd27e0ca3cc..0b78f9c83e0 100644 --- a/api/src/com/cloud/api/commands/AddNetworkServiceProviderCmd.java +++ b/api/src/com/cloud/api/commands/AddNetworkServiceProviderCmd.java @@ -21,16 +21,20 @@ package com.cloud.api.commands; import org.apache.log4j.Logger; import com.cloud.api.ApiConstants; +import com.cloud.api.BaseAsyncCreateCmd; import com.cloud.api.BaseCmd; import com.cloud.api.Implementation; import com.cloud.api.Parameter; import com.cloud.api.ServerApiException; import com.cloud.api.response.ProviderResponse; +import com.cloud.event.EventTypes; +import com.cloud.exception.ResourceAllocationException; import com.cloud.network.PhysicalNetworkServiceProvider; import com.cloud.user.Account; +import com.cloud.user.UserContext; @Implementation(description="Adds a network serviceProvider to a physical network", responseObject=ProviderResponse.class) -public class AddNetworkServiceProviderCmd extends BaseCmd { +public class AddNetworkServiceProviderCmd extends BaseAsyncCreateCmd { public static final Logger s_logger = Logger.getLogger(AddNetworkServiceProviderCmd.class.getName()); private static final String s_name = "addnetworkserviceproviderresponse"; @@ -80,7 +84,8 @@ public class AddNetworkServiceProviderCmd extends BaseCmd { @Override public void execute(){ - PhysicalNetworkServiceProvider result = _networkService.addProviderToPhysicalNetwork(getPhysicalNetworkId(), getProviderName(), getDestinationPhysicalNetworkId()); + UserContext.current().setEventDetails("Network ServiceProvider Id: "+getEntityId()); + PhysicalNetworkServiceProvider result = _networkService.getCreatedPhysicalNetworkServiceProvider(getEntityId()); if (result != null) { ProviderResponse response = _responseGenerator.createNetworkServiceProviderResponse(result); response.setResponseName(getCommandName()); @@ -89,4 +94,24 @@ public class AddNetworkServiceProviderCmd extends BaseCmd { throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to add service provider to physical network"); } } + + @Override + public void create() throws ResourceAllocationException { + PhysicalNetworkServiceProvider result = _networkService.addProviderToPhysicalNetwork(getPhysicalNetworkId(), getProviderName(), getDestinationPhysicalNetworkId()); + if (result != null) { + setEntityId(result.getId()); + } else { + throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to add service provider entity to physical network"); + } + } + + @Override + public String getEventType() { + return EventTypes.EVENT_SERVICE_PROVIDER_CREATE; + } + + @Override + public String getEventDescription() { + return "Adding physical network ServiceProvider: " + getEntityId(); + } } diff --git a/api/src/com/cloud/api/commands/CreatePhysicalNetworkCmd.java b/api/src/com/cloud/api/commands/CreatePhysicalNetworkCmd.java index 47e2b8dc2f3..908e61df151 100644 --- a/api/src/com/cloud/api/commands/CreatePhysicalNetworkCmd.java +++ b/api/src/com/cloud/api/commands/CreatePhysicalNetworkCmd.java @@ -23,16 +23,20 @@ import java.util.List; import org.apache.log4j.Logger; import com.cloud.api.ApiConstants; +import com.cloud.api.BaseAsyncCreateCmd; import com.cloud.api.BaseCmd; import com.cloud.api.Implementation; import com.cloud.api.Parameter; import com.cloud.api.ServerApiException; import com.cloud.api.response.PhysicalNetworkResponse; +import com.cloud.event.EventTypes; +import com.cloud.exception.ResourceAllocationException; import com.cloud.network.PhysicalNetwork; import com.cloud.user.Account; +import com.cloud.user.UserContext; @Implementation(description="Creates a physical network", responseObject=PhysicalNetworkResponse.class) -public class CreatePhysicalNetworkCmd extends BaseCmd { +public class CreatePhysicalNetworkCmd extends BaseAsyncCreateCmd { public static final Logger s_logger = Logger.getLogger(CreatePhysicalNetworkCmd.class.getName()); private static final String s_name = "createphysicalnetworkresponse"; @@ -107,9 +111,30 @@ public class CreatePhysicalNetworkCmd extends BaseCmd { return Account.ACCOUNT_ID_SYSTEM; } + @Override + public String getEventType() { + return EventTypes.EVENT_PHYSICAL_NETWORK_CREATE; + } + + @Override + public String getCreateEventType() { + return EventTypes.EVENT_PHYSICAL_NETWORK_CREATE; + } + + @Override + public String getCreateEventDescription() { + return "creating Physical Network"; + } + + @Override + public String getEventDescription() { + return "creating Physical Network. Id: "+getEntityId(); + } + @Override public void execute(){ - PhysicalNetwork result = _networkService.createPhysicalNetwork(getZoneId(),getVlan(),getNetworkSpeed(), getIsolationMethods(),getBroadcastDomainRange(),getDomainId(), getTags()); + UserContext.current().setEventDetails("Physical Network Id: "+getEntityId()); + PhysicalNetwork result = _networkService.getCreatedPhysicalNetwork(getEntityId()); if (result != null) { PhysicalNetworkResponse response = _responseGenerator.createPhysicalNetworkResponse(result); response.setResponseName(getCommandName()); @@ -118,4 +143,15 @@ public class CreatePhysicalNetworkCmd extends BaseCmd { throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to create physical network"); } } + + @Override + public void create() throws ResourceAllocationException { + PhysicalNetwork result = _networkService.createPhysicalNetwork(getZoneId(),getVlan(),getNetworkSpeed(), getIsolationMethods(),getBroadcastDomainRange(),getDomainId(), getTags()); + if (result != null) { + setEntityId(result.getId()); + } else { + throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to create physical network entity"); + } + } + } diff --git a/api/src/com/cloud/api/commands/DeleteNetworkServiceProviderCmd.java b/api/src/com/cloud/api/commands/DeleteNetworkServiceProviderCmd.java index 2de6acac328..98b719b6756 100644 --- a/api/src/com/cloud/api/commands/DeleteNetworkServiceProviderCmd.java +++ b/api/src/com/cloud/api/commands/DeleteNetworkServiceProviderCmd.java @@ -21,15 +21,17 @@ package com.cloud.api.commands; import org.apache.log4j.Logger; import com.cloud.api.ApiConstants; +import com.cloud.api.BaseAsyncCmd; import com.cloud.api.BaseCmd; import com.cloud.api.Implementation; import com.cloud.api.Parameter; import com.cloud.api.ServerApiException; import com.cloud.api.response.SuccessResponse; +import com.cloud.event.EventTypes; import com.cloud.user.Account; @Implementation(description="Deletes a Network Service Provider.", responseObject=SuccessResponse.class) -public class DeleteNetworkServiceProviderCmd extends BaseCmd { +public class DeleteNetworkServiceProviderCmd extends BaseAsyncCmd { public static final Logger s_logger = Logger.getLogger(DeleteNetworkServiceProviderCmd.class.getName()); private static final String s_name = "deletenetworkserviceproviderresponse"; @@ -75,4 +77,16 @@ public class DeleteNetworkServiceProviderCmd extends BaseCmd { throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to delete network service provider"); } } + + + @Override + public String getEventType() { + return EventTypes.EVENT_SERVICE_PROVIDER_DELETE; + } + + + @Override + public String getEventDescription() { + return "Deleting Physical network ServiceProvider: " + getId(); + } } diff --git a/api/src/com/cloud/api/commands/DeletePhysicalNetworkCmd.java b/api/src/com/cloud/api/commands/DeletePhysicalNetworkCmd.java index 4477d279a1e..ad671f66ee6 100644 --- a/api/src/com/cloud/api/commands/DeletePhysicalNetworkCmd.java +++ b/api/src/com/cloud/api/commands/DeletePhysicalNetworkCmd.java @@ -21,15 +21,18 @@ package com.cloud.api.commands; import org.apache.log4j.Logger; import com.cloud.api.ApiConstants; +import com.cloud.api.BaseAsyncCmd; import com.cloud.api.BaseCmd; import com.cloud.api.Implementation; import com.cloud.api.Parameter; import com.cloud.api.ServerApiException; import com.cloud.api.response.SuccessResponse; +import com.cloud.event.EventTypes; import com.cloud.user.Account; +import com.cloud.user.UserContext; @Implementation(description="Deletes a Physical Network.", responseObject=SuccessResponse.class) -public class DeletePhysicalNetworkCmd extends BaseCmd { +public class DeletePhysicalNetworkCmd extends BaseAsyncCmd { public static final Logger s_logger = Logger.getLogger(DeletePhysicalNetworkCmd.class.getName()); private static final String s_name = "deletephysicalnetworkresponse"; @@ -67,6 +70,7 @@ public class DeletePhysicalNetworkCmd extends BaseCmd { @Override public void execute(){ + UserContext.current().setEventDetails("Physical Network Id: " + id); boolean result = _networkService.deletePhysicalNetwork(getId()); if (result) { SuccessResponse response = new SuccessResponse(getCommandName()); @@ -75,4 +79,15 @@ public class DeletePhysicalNetworkCmd extends BaseCmd { throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to delete physical network"); } } + + + @Override + public String getEventDescription() { + return "Deleting Physical network: " + getId(); + } + + @Override + public String getEventType() { + return EventTypes.EVENT_PHYSICAL_NETWORK_DELETE; + } } diff --git a/api/src/com/cloud/api/commands/UpdateNetworkServiceProviderCmd.java b/api/src/com/cloud/api/commands/UpdateNetworkServiceProviderCmd.java index 10f2bed556b..47dc2373099 100644 --- a/api/src/com/cloud/api/commands/UpdateNetworkServiceProviderCmd.java +++ b/api/src/com/cloud/api/commands/UpdateNetworkServiceProviderCmd.java @@ -21,16 +21,18 @@ package com.cloud.api.commands; import org.apache.log4j.Logger; import com.cloud.api.ApiConstants; +import com.cloud.api.BaseAsyncCmd; import com.cloud.api.BaseCmd; import com.cloud.api.Implementation; import com.cloud.api.Parameter; import com.cloud.api.ServerApiException; import com.cloud.api.response.ProviderResponse; +import com.cloud.event.EventTypes; import com.cloud.network.PhysicalNetworkServiceProvider; import com.cloud.user.Account; @Implementation(description="Updates a network serviceProvider of a physical network", responseObject=ProviderResponse.class) -public class UpdateNetworkServiceProviderCmd extends BaseCmd { +public class UpdateNetworkServiceProviderCmd extends BaseAsyncCmd { public static final Logger s_logger = Logger.getLogger(UpdateNetworkServiceProviderCmd.class.getName()); private static final String s_name = "updatenetworkserviceproviderresponse"; @@ -82,8 +84,14 @@ public class UpdateNetworkServiceProviderCmd extends BaseCmd { } } + @Override + public String getEventType() { + return EventTypes.EVENT_SERVICE_PROVIDER_UPDATE; + } - - + @Override + public String getEventDescription() { + return "Updating physical network ServiceProvider: " + getId(); + } } diff --git a/api/src/com/cloud/api/commands/UpdatePhysicalNetworkCmd.java b/api/src/com/cloud/api/commands/UpdatePhysicalNetworkCmd.java index 5fedbb8e667..9bf826d4fcd 100644 --- a/api/src/com/cloud/api/commands/UpdatePhysicalNetworkCmd.java +++ b/api/src/com/cloud/api/commands/UpdatePhysicalNetworkCmd.java @@ -23,16 +23,18 @@ import java.util.List; import org.apache.log4j.Logger; import com.cloud.api.ApiConstants; +import com.cloud.api.BaseAsyncCmd; import com.cloud.api.BaseCmd; import com.cloud.api.Implementation; import com.cloud.api.Parameter; import com.cloud.api.ServerApiException; import com.cloud.api.response.PhysicalNetworkResponse; +import com.cloud.event.EventTypes; import com.cloud.network.PhysicalNetwork; import com.cloud.user.Account; @Implementation(description="Updates a physical network", responseObject=PhysicalNetworkResponse.class) -public class UpdatePhysicalNetworkCmd extends BaseCmd { +public class UpdatePhysicalNetworkCmd extends BaseAsyncCmd { public static final Logger s_logger = Logger.getLogger(UpdatePhysicalNetworkCmd.class.getName()); private static final String s_name = "updatephysicalnetworkresponse"; @@ -109,8 +111,18 @@ public class UpdatePhysicalNetworkCmd extends BaseCmd { response.setResponseName(getCommandName()); this.setResponseObject(response); }else { - throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to create physical network"); + throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to update physical network"); } } + @Override + public String getEventDescription() { + return "Updating Physical network: " + getId(); + } + + @Override + public String getEventType() { + return EventTypes.EVENT_PHYSICAL_NETWORK_UPDATE; + } + } diff --git a/api/src/com/cloud/event/EventTypes.java b/api/src/com/cloud/event/EventTypes.java index d928806c946..5840842a594 100755 --- a/api/src/com/cloud/event/EventTypes.java +++ b/api/src/com/cloud/event/EventTypes.java @@ -214,4 +214,15 @@ public class EventTypes { //Network as a Service public static final String EVENT_NETWORK_ELEMENT_CONFIGURE = "NETWORK.ELEMENT.CONFIGURE"; + + //Physical Network Events + public static final String EVENT_PHYSICAL_NETWORK_CREATE = "PHYSICAL.NETWORK.CREATE"; + public static final String EVENT_PHYSICAL_NETWORK_DELETE = "PHYSICAL.NETWORK.DELETE"; + public static final String EVENT_PHYSICAL_NETWORK_UPDATE = "PHYSICAL.NETWORK.UPDATE"; + + //Physical Network Service Provider Events + public static final String EVENT_SERVICE_PROVIDER_CREATE = "SERVICE.PROVIDER.CREATE"; + public static final String EVENT_SERVICE_PROVIDER_DELETE = "SERVICE.PROVIDER.DELETE"; + public static final String EVENT_SERVICE_PROVIDER_UPDATE = "SERVICE.PROVIDER.UPDATE"; + } diff --git a/api/src/com/cloud/network/NetworkService.java b/api/src/com/cloud/network/NetworkService.java index c72e5a2678b..db8334140e7 100644 --- a/api/src/com/cloud/network/NetworkService.java +++ b/api/src/com/cloud/network/NetworkService.java @@ -109,4 +109,12 @@ public interface NetworkService { PhysicalNetworkServiceProvider updateNetworkServiceProvider(Long id, Boolean enabled); boolean deleteNetworkServiceProvider(Long id); + + PhysicalNetwork getPhysicalNetwork(Long physicalNetworkId); + + PhysicalNetwork getCreatedPhysicalNetwork(Long physicalNetworkId); + + PhysicalNetworkServiceProvider getPhysicalNetworkServiceProvider(Long providerId); + + PhysicalNetworkServiceProvider getCreatedPhysicalNetworkServiceProvider(Long providerId); } diff --git a/api/src/com/cloud/network/PhysicalNetwork.java b/api/src/com/cloud/network/PhysicalNetwork.java index f9307f5c1da..b2e17cd94f1 100644 --- a/api/src/com/cloud/network/PhysicalNetwork.java +++ b/api/src/com/cloud/network/PhysicalNetwork.java @@ -41,8 +41,8 @@ public interface PhysicalNetwork { } public enum BroadcastDomainRange { - Pod, - Zone; + POD, + ZONE; } long getId(); diff --git a/server/src/com/cloud/network/NetworkManagerImpl.java b/server/src/com/cloud/network/NetworkManagerImpl.java index 4caf7244ce6..973ea0a3305 100755 --- a/server/src/com/cloud/network/NetworkManagerImpl.java +++ b/server/src/com/cloud/network/NetworkManagerImpl.java @@ -267,6 +267,8 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag HashMap _lastNetworkIdsToFree = new HashMap(); + + private static HashMap> s_serviceToImplementedProvidersMap = new HashMap>(); @Override public PublicIp assignPublicIpAddress(long dcId, Long podId, Account owner, VlanType type, Long networkId, String requestedIp) throws InsufficientAddressCapacityException { @@ -883,6 +885,24 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag _executor = Executors.newScheduledThreadPool(1, new NamedThreadFactory("Network-Scavenger")); _allowSubdomainNetworkAccess = Boolean.valueOf(_configs.get(Config.SubDomainNetworkAccess.key())); + + //populate s_serviceToImplementedProvidersMap with current _networkElements + for (NetworkElement element : _networkElements) { + Map> capabilities = element.getCapabilities(); + Provider implementedProvider = element.getProvider(); + if(capabilities != null && implementedProvider != null){ + for(Service service : capabilities.keySet()){ + if(s_serviceToImplementedProvidersMap.containsKey(service)){ + List providers = s_serviceToImplementedProvidersMap.get(service); + providers.add(implementedProvider); + }else{ + List providers = new ArrayList(); + providers.add(implementedProvider); + s_serviceToImplementedProvidersMap.put(service, providers); + } + } + } + } s_logger.info("Network Manager is configured."); @@ -3403,6 +3423,7 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag @Override @DB + @ActionEvent(eventType = EventTypes.EVENT_PHYSICAL_NETWORK_CREATE, eventDescription = "Creating Physical Network", create = true) public PhysicalNetwork createPhysicalNetwork(Long zoneId, String vnetRange, String networkSpeed, List isolationMethods, String broadcastDomainRangeStr, Long domainId, List tags) { // Check if zone exists if (zoneId == null) { @@ -3446,7 +3467,7 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag BroadcastDomainRange broadcastDomainRange = null; if (broadcastDomainRangeStr != null && !broadcastDomainRangeStr.isEmpty()) { try { - broadcastDomainRange = PhysicalNetwork.BroadcastDomainRange.valueOf(broadcastDomainRangeStr); + broadcastDomainRange = PhysicalNetwork.BroadcastDomainRange.valueOf(broadcastDomainRangeStr.toUpperCase()); } catch (IllegalArgumentException ex) { throw new InvalidParameterValueException("Unable to resolve broadcastDomainRange '" + broadcastDomainRangeStr + "' to a supported value {Pod or Zone}"); } @@ -3496,6 +3517,7 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag @Override @DB + @ActionEvent(eventType = EventTypes.EVENT_PHYSICAL_NETWORK_UPDATE, eventDescription = "updating physical network", async = true) public PhysicalNetwork updatePhysicalNetwork(Long id, String networkSpeed, List isolationMethods, List tags, String newVnetRangeString, String state) { // verify input parameters @@ -3534,7 +3556,7 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag PhysicalNetwork.IsolationMethod isolationMethodVal = null; if (isMethod != null && !isMethod.isEmpty()) { try { - isolationMethodVal = PhysicalNetwork.IsolationMethod.valueOf(isMethod); + isolationMethodVal = PhysicalNetwork.IsolationMethod.valueOf(isMethod.toUpperCase()); } catch (IllegalArgumentException ex) { throw new InvalidParameterValueException("Unable to resolve IsolationMethod '" + isMethod + "' to a supported value {VLAN or L3 or GRE}"); } @@ -3630,6 +3652,7 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag } @Override + @ActionEvent(eventType = EventTypes.EVENT_PHYSICAL_NETWORK_DELETE, eventDescription = "deleting physical network", async = true) public boolean deletePhysicalNetwork(Long physicalNetworkId) { // verify input parameters @@ -3637,7 +3660,7 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag if (network == null) { throw new InvalidParameterValueException("Network id=" + physicalNetworkId + "doesn't exist in the system"); } - + //for all networks associated, check if they can be deleted. //delete physical network only if no network is associated to it List networks = _networksDao.listByPhysicalNetwork(physicalNetworkId); @@ -3756,31 +3779,22 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag } } - List supportedProviders = new ArrayList(); - for (NetworkElement element : _networkElements) { - if(element.getProvider() != null){ - if(service != null){ - //chk if this serviceprovider supports this service - if(isServiceProvided(element, service)){ - supportedProviders.add(element.getProvider()); - } - }else{ - supportedProviders.add(element.getProvider()); - } + Set supportedProviders = new HashSet(); + + if(service != null){ + supportedProviders.addAll(s_serviceToImplementedProvidersMap.get(service)); + }else{ + for(List pList : s_serviceToImplementedProvidersMap.values()){ + supportedProviders.addAll(pList); } } - return supportedProviders; + + return new ArrayList(supportedProviders); } - private boolean isServiceProvided(NetworkElement element, Service service){ - if(element.getCapabilities() != null){ - return element.getCapabilities().containsKey(service); - } - return false; - } - @Override @DB + @ActionEvent(eventType = EventTypes.EVENT_SERVICE_PROVIDER_CREATE, eventDescription = "Creating Physical Network ServiceProvider", create = true) public PhysicalNetworkServiceProvider addProviderToPhysicalNetwork(Long physicalNetworkId, String providerName, Long destinationPhysicalNetworkId) { // verify input parameters @@ -3837,6 +3851,7 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag } @Override + @ActionEvent(eventType = EventTypes.EVENT_SERVICE_PROVIDER_UPDATE, eventDescription = "Updating physical network ServiceProvider", async = true) public PhysicalNetworkServiceProvider updateNetworkServiceProvider(Long id, Boolean enabled) { PhysicalNetworkServiceProviderVO provider = _pNSPDao.findById(id); @@ -3859,6 +3874,7 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag } @Override + @ActionEvent(eventType = EventTypes.EVENT_SERVICE_PROVIDER_DELETE, eventDescription = "Deleting physical network ServiceProvider", async = true) public boolean deleteNetworkServiceProvider(Long id) { PhysicalNetworkServiceProviderVO provider = _pNSPDao.findById(id); @@ -3870,5 +3886,27 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag return _pNSPDao.remove(id); } + + @Override + public PhysicalNetwork getPhysicalNetwork(Long physicalNetworkId){ + return _physicalNetworkDao.findById(physicalNetworkId); + } + + @Override + @ActionEvent(eventType = EventTypes.EVENT_PHYSICAL_NETWORK_CREATE, eventDescription = "Creating Physical Network", async = true) + public PhysicalNetwork getCreatedPhysicalNetwork(Long physicalNetworkId) { + return getPhysicalNetwork(physicalNetworkId); + } + + @Override + public PhysicalNetworkServiceProvider getPhysicalNetworkServiceProvider(Long providerId) { + return _pNSPDao.findById(providerId); + } + + @Override + @ActionEvent(eventType = EventTypes.EVENT_SERVICE_PROVIDER_CREATE, eventDescription = "Creating Physical Network ServiceProvider", async = true) + public PhysicalNetworkServiceProvider getCreatedPhysicalNetworkServiceProvider(Long providerId) { + return getPhysicalNetworkServiceProvider(providerId); + } } diff --git a/server/src/com/cloud/network/PhysicalNetworkVO.java b/server/src/com/cloud/network/PhysicalNetworkVO.java index 921f9c9c646..178f68c1f74 100644 --- a/server/src/com/cloud/network/PhysicalNetworkVO.java +++ b/server/src/com/cloud/network/PhysicalNetworkVO.java @@ -96,7 +96,7 @@ public class PhysicalNetworkVO implements PhysicalNetwork { if(broadcastDomainRange != null){ this.broadcastDomainRange = broadcastDomainRange; }else{ - this.broadcastDomainRange = BroadcastDomainRange.Pod; + this.broadcastDomainRange = BroadcastDomainRange.ZONE; } this.state = State.Disabled; } diff --git a/server/src/com/cloud/network/element/ExternalDhcpElement.java b/server/src/com/cloud/network/element/ExternalDhcpElement.java index 3524c04cb66..e5ebf8731b5 100644 --- a/server/src/com/cloud/network/element/ExternalDhcpElement.java +++ b/server/src/com/cloud/network/element/ExternalDhcpElement.java @@ -19,6 +19,7 @@ package com.cloud.network.element; +import java.util.HashMap; import java.util.Map; import javax.ejb.Local; @@ -37,7 +38,6 @@ import com.cloud.host.Host; import com.cloud.hypervisor.Hypervisor.HypervisorType; import com.cloud.network.Network; import com.cloud.network.Network.Capability; -import com.cloud.network.Network.GuestIpType; import com.cloud.network.Network.Provider; import com.cloud.network.Network.Service; import com.cloud.network.Network.Type; @@ -54,6 +54,8 @@ import com.cloud.vm.VirtualMachineProfile; public class ExternalDhcpElement extends AdapterBase implements NetworkElement { private static final Logger s_logger = Logger.getLogger(ExternalDhcpElement.class); @Inject ExternalDhcpManager _dhcpMgr; + private static final Map> capabilities = setCapabilities(); + private boolean canHandle(DeployDestination dest, TrafficType trafficType, Type networkType) { DataCenter dc = dest.getDataCenter(); Pod pod = dest.getPod(); @@ -67,9 +69,15 @@ public class ExternalDhcpElement extends AdapterBase implements NetworkElement { return false; } + private static Map> setCapabilities() { + Map> capabilities = new HashMap>(); + capabilities.put(Service.Dhcp, null); + return capabilities; + } + @Override public Map> getCapabilities() { - return null; + return capabilities; } @Override diff --git a/setup/db/create-schema.sql b/setup/db/create-schema.sql index ad6f682b1f1..077819b9da2 100755 --- a/setup/db/create-schema.sql +++ b/setup/db/create-schema.sql @@ -1771,7 +1771,7 @@ CREATE TABLE `cloud`.`physical_network` ( `vnet` varchar(255), `speed` varchar(32), `domain_id` bigint unsigned COMMENT 'foreign key to domain id', - `broadcast_domain_range` varchar(32) NOT NULL DEFAULT 'Pod' COMMENT 'range of broadcast domain : Pod/Zone', + `broadcast_domain_range` varchar(32) NOT NULL DEFAULT 'ZONE' COMMENT 'range of broadcast domain : POD/ZONE', `state` varchar(32) NOT NULL DEFAULT 'Disabled' COMMENT 'what state is this configuration in', `created` datetime COMMENT 'date created', `removed` datetime COMMENT 'date removed if not null', From 219978a9be93371bc18291bab2193e14735e255e Mon Sep 17 00:00:00 2001 From: alena Date: Thu, 20 Oct 2011 18:24:05 -0700 Subject: [PATCH 020/159] Create network using physical network id --- .../cloud/api/commands/CreateNetworkCmd.java | 20 +++-- .../cloud/api/commands/ListNetworksCmd.java | 7 ++ .../cloud/api/response/NetworkResponse.java | 10 ++- .../cloud/deploy/DataCenterDeployment.java | 11 ++- api/src/com/cloud/deploy/DeploymentPlan.java | 2 + api/src/com/cloud/network/Network.java | 4 +- api/src/com/cloud/network/NetworkProfile.java | 5 +- api/src/com/cloud/network/NetworkService.java | 2 + .../com/cloud/offering/NetworkOffering.java | 3 +- .../allocator/impl/RecreateHostAllocator.java | 2 +- .../src/com/cloud/api/ApiResponseHelper.java | 25 +++--- .../ConfigurationManagerImpl.java | 16 ++-- .../src/com/cloud/dc/dao/DataCenterDao.java | 6 +- .../com/cloud/dc/dao/DataCenterDaoImpl.java | 19 ++--- .../cloud/dc/dao/DataCenterVnetDaoImpl.java | 25 +----- .../src/com/cloud/deploy/FirstFitPlanner.java | 6 +- .../src/com/cloud/network/NetworkManager.java | 4 +- .../com/cloud/network/NetworkManagerImpl.java | 80 ++++++++++++------- server/src/com/cloud/network/NetworkVO.java | 38 +++------ .../network/guru/ControlNetworkGuru.java | 2 +- .../cloud/network/guru/DirectNetworkGuru.java | 2 +- .../guru/ExternalGuestNetworkGuru.java | 2 +- .../cloud/network/guru/GuestNetworkGuru.java | 4 +- .../network/guru/PodBasedNetworkGuru.java | 2 +- .../cloud/network/guru/PublicNetworkGuru.java | 2 +- .../lb/ElasticLoadBalancerManagerImpl.java | 2 +- .../VirtualNetworkApplianceManagerImpl.java | 4 +- .../cloud/offerings/NetworkOfferingVO.java | 1 + .../cloud/server/ConfigurationServerImpl.java | 2 +- .../cloud/server/ManagementServerImpl.java | 2 +- .../AbstractStoragePoolAllocator.java | 2 +- .../src/com/cloud/vm/UserVmManagerImpl.java | 14 ++-- .../cloud/vm/VirtualMachineManagerImpl.java | 8 +- .../src/com/cloud/vm/dao/UserVmDaoImpl.java | 7 +- .../cloud/network/MockNetworkManagerImpl.java | 4 +- 35 files changed, 182 insertions(+), 163 deletions(-) diff --git a/api/src/com/cloud/api/commands/CreateNetworkCmd.java b/api/src/com/cloud/api/commands/CreateNetworkCmd.java index 273b23f0979..ad986bf3cec 100644 --- a/api/src/com/cloud/api/commands/CreateNetworkCmd.java +++ b/api/src/com/cloud/api/commands/CreateNetworkCmd.java @@ -30,6 +30,7 @@ import com.cloud.api.ServerApiException; import com.cloud.api.response.NetworkResponse; import com.cloud.exception.ConcurrentOperationException; import com.cloud.exception.InsufficientCapacityException; +import com.cloud.exception.InvalidParameterValueException; import com.cloud.network.Network; import com.cloud.user.UserContext; @@ -52,7 +53,7 @@ public class CreateNetworkCmd extends BaseCmd { @Parameter(name=ApiConstants.NETWORK_OFFERING_ID, type=CommandType.LONG, required=true, description="the network offering id") private Long networkOfferingId; - @Parameter(name=ApiConstants.ZONE_ID, type=CommandType.LONG, required=true, description="the Zone ID for the network") + @Parameter(name=ApiConstants.ZONE_ID, type=CommandType.LONG, description="the Zone ID for the network") private Long zoneId; @Parameter(name=ApiConstants.GATEWAY, type=CommandType.STRING, description="the gateway of the network") @@ -90,6 +91,9 @@ public class CreateNetworkCmd extends BaseCmd { @Parameter(name=ApiConstants.TAGS, type=CommandType.LIST, collectionType=CommandType.STRING, description="Tag the network") private List tags; + + @Parameter(name=ApiConstants.PHYSICAL_NETWORK_ID, type=CommandType.LONG, description="the Physical Network ID the network belongs to") + private Long physicalNetworkId; ///////////////////////////////////////////////////// /////////////////// Accessors /////////////////////// @@ -102,10 +106,6 @@ public class CreateNetworkCmd extends BaseCmd { return tags; } - public Long getZoneId() { - return zoneId; - } - public String getGateway() { return gateway; } @@ -158,6 +158,16 @@ public class CreateNetworkCmd extends BaseCmd { return isShared == null ? false : isShared; } + public Long getPhysicalNetworkId() { + if (physicalNetworkId != null) { + return physicalNetworkId; + } else if (zoneId != null) { + return _networkService.translateZoneToPhysicalNetwork(zoneId); + } else { + throw new InvalidParameterValueException("Either zoneId or physicalNetworkId have to be specified"); + } + } + ///////////////////////////////////////////////////// /////////////// API Implementation/////////////////// ///////////////////////////////////////////////////// diff --git a/api/src/com/cloud/api/commands/ListNetworksCmd.java b/api/src/com/cloud/api/commands/ListNetworksCmd.java index 9f660b35f95..7ea6e9fbbd0 100644 --- a/api/src/com/cloud/api/commands/ListNetworksCmd.java +++ b/api/src/com/cloud/api/commands/ListNetworksCmd.java @@ -69,6 +69,9 @@ public class ListNetworksCmd extends BaseListCmd { @Parameter(name=ApiConstants.PROJECT_ID, type=CommandType.LONG, description="list networks by project id") private Long projectId; + + @Parameter(name=ApiConstants.PHYSICAL_NETWORK_ID, type=CommandType.LONG, description="list networks by physical network id") + private Long physicalNetworkId; ///////////////////////////////////////////////////// /////////////////// Accessors /////////////////////// @@ -114,6 +117,10 @@ public class ListNetworksCmd extends BaseListCmd { return projectId; } + public Long getPhysicalNetworkId() { + return physicalNetworkId; + } + ///////////////////////////////////////////////////// /////////////// API Implementation/////////////////// ///////////////////////////////////////////////////// diff --git a/api/src/com/cloud/api/response/NetworkResponse.java b/api/src/com/cloud/api/response/NetworkResponse.java index f998cfc706b..f780b998ec2 100644 --- a/api/src/com/cloud/api/response/NetworkResponse.java +++ b/api/src/com/cloud/api/response/NetworkResponse.java @@ -125,6 +125,10 @@ public class NetworkResponse extends BaseResponse implements ControlledEntityRes @SerializedName(ApiConstants.TAGS) @Param(description="comma separated tag") private String tags; + + @SerializedName(ApiConstants.PHYSICAL_NETWORK_ID) @Param(description="the physical network id") + private Long physicalNetworkId; + public void setId(Long id) { this.id = id; @@ -268,7 +272,9 @@ public class NetworkResponse extends BaseResponse implements ControlledEntityRes public void setProjectName(String projectName) { this.projectName = projectName; } - - + + public void setPhysicalNetworkId(Long physicalNetworkId) { + this.physicalNetworkId = physicalNetworkId; + } } diff --git a/api/src/com/cloud/deploy/DataCenterDeployment.java b/api/src/com/cloud/deploy/DataCenterDeployment.java index 5be0247c2fc..2d65994fa4e 100644 --- a/api/src/com/cloud/deploy/DataCenterDeployment.java +++ b/api/src/com/cloud/deploy/DataCenterDeployment.java @@ -25,19 +25,21 @@ public class DataCenterDeployment implements DeploymentPlan { Long _clusterId; Long _poolId; Long _hostId; + Long _physicalNetworkId; ExcludeList _avoids = null; boolean _recreateDisks; public DataCenterDeployment(long dataCenterId) { - this(dataCenterId, null, null, null, null); + this(dataCenterId, null, null, null, null, null); } - public DataCenterDeployment(long dataCenterId, Long podId, Long clusterId, Long hostId, Long poolId) { + public DataCenterDeployment(long dataCenterId, Long podId, Long clusterId, Long hostId, Long poolId, Long physicalNetworkId) { _dcId = dataCenterId; _podId = podId; _clusterId = clusterId; _hostId = hostId; _poolId = poolId; + _physicalNetworkId = physicalNetworkId; } @Override @@ -74,4 +76,9 @@ public class DataCenterDeployment implements DeploymentPlan { public void setAvoids(ExcludeList avoids) { _avoids = avoids; } + + @Override + public Long getPhysicalNetworkId() { + return _physicalNetworkId; + } } diff --git a/api/src/com/cloud/deploy/DeploymentPlan.java b/api/src/com/cloud/deploy/DeploymentPlan.java index 0881f7bd50c..5f7144d49c3 100644 --- a/api/src/com/cloud/deploy/DeploymentPlan.java +++ b/api/src/com/cloud/deploy/DeploymentPlan.java @@ -63,4 +63,6 @@ public interface DeploymentPlan { * the ExcludeList to avoid for deployment */ public ExcludeList getAvoids(); + + Long getPhysicalNetworkId(); } diff --git a/api/src/com/cloud/network/Network.java b/api/src/com/cloud/network/Network.java index 9906d8c190e..1154efece57 100644 --- a/api/src/com/cloud/network/Network.java +++ b/api/src/com/cloud/network/Network.java @@ -39,6 +39,7 @@ import com.cloud.utils.fsm.StateMachine; */ public interface Network extends ControlledEntity { + @Deprecated public enum GuestIpType { Virtual, Direct, @@ -252,6 +253,7 @@ public interface Network extends ControlledEntity { URI getBroadcastUri(); + @Deprecated GuestIpType getGuestType(); String getDisplayText(); @@ -270,5 +272,5 @@ public interface Network extends ControlledEntity { boolean getIsShared(); - long getPhysicalNetworkId(); + Long getPhysicalNetworkId(); } diff --git a/api/src/com/cloud/network/NetworkProfile.java b/api/src/com/cloud/network/NetworkProfile.java index cef307db5ba..b6f85994440 100644 --- a/api/src/com/cloud/network/NetworkProfile.java +++ b/api/src/com/cloud/network/NetworkProfile.java @@ -50,9 +50,10 @@ public class NetworkProfile implements Network { private boolean isSecurityGroupEnabled; private List tags; private Network.Type type; + @Deprecated private GuestIpType guestIpType; private boolean isShared; - private long physicalNetworkId; + private Long physicalNetworkId; public NetworkProfile(Network network) { this.id = network.getId(); @@ -216,7 +217,7 @@ public class NetworkProfile implements Network { } @Override - public long getPhysicalNetworkId() { + public Long getPhysicalNetworkId() { return physicalNetworkId; } } diff --git a/api/src/com/cloud/network/NetworkService.java b/api/src/com/cloud/network/NetworkService.java index db8334140e7..1faba4ccc00 100644 --- a/api/src/com/cloud/network/NetworkService.java +++ b/api/src/com/cloud/network/NetworkService.java @@ -117,4 +117,6 @@ public interface NetworkService { PhysicalNetworkServiceProvider getPhysicalNetworkServiceProvider(Long providerId); PhysicalNetworkServiceProvider getCreatedPhysicalNetworkServiceProvider(Long providerId); + + long translateZoneToPhysicalNetwork(long zoneId); } diff --git a/api/src/com/cloud/offering/NetworkOffering.java b/api/src/com/cloud/offering/NetworkOffering.java index 81c2e141c5c..530e8ac5016 100644 --- a/api/src/com/cloud/offering/NetworkOffering.java +++ b/api/src/com/cloud/offering/NetworkOffering.java @@ -18,8 +18,6 @@ package com.cloud.offering; import com.cloud.network.Network.GuestIpType; -import com.cloud.network.Network.Provider; -import com.cloud.network.Network.Service; import com.cloud.network.Network.Type; import com.cloud.network.Networks.TrafficType; @@ -91,6 +89,7 @@ public interface NetworkOffering { boolean isSharedSourceNatService(); + @Deprecated GuestIpType getGuestType(); String getUniqueName(); diff --git a/server/src/com/cloud/agent/manager/allocator/impl/RecreateHostAllocator.java b/server/src/com/cloud/agent/manager/allocator/impl/RecreateHostAllocator.java index a4db693d755..ab1765b3a62 100644 --- a/server/src/com/cloud/agent/manager/allocator/impl/RecreateHostAllocator.java +++ b/server/src/com/cloud/agent/manager/allocator/impl/RecreateHostAllocator.java @@ -130,7 +130,7 @@ public class RecreateHostAllocator extends FirstFitRoutingAllocator { } continue; } - DataCenterDeployment newPlan = new DataCenterDeployment(plan.getDataCenterId(), p.getPod().getId(), clusterId, null, null); + DataCenterDeployment newPlan = new DataCenterDeployment(plan.getDataCenterId(), p.getPod().getId(), clusterId, null, null, null); hosts = super.allocateTo(vm, newPlan, type, avoid, returnUpTo); if (hosts != null && !hosts.isEmpty()) { return hosts; diff --git a/server/src/com/cloud/api/ApiResponseHelper.java b/server/src/com/cloud/api/ApiResponseHelper.java index 3dbbbc56d38..8bfd99dc72f 100755 --- a/server/src/com/cloud/api/ApiResponseHelper.java +++ b/server/src/com/cloud/api/ApiResponseHelper.java @@ -2176,6 +2176,7 @@ public class ApiResponseHelper implements ResponseGenerator { } response.setZoneId(network.getDataCenterId()); + response.setPhysicalNetworkId(network.getPhysicalNetworkId()); // populate network offering information NetworkOffering networkOffering = ApiDBUtils.findNetworkOfferingById(network.getNetworkOfferingId()); @@ -2381,17 +2382,19 @@ public class ApiResponseHelper implements ResponseGenerator { Set securityGroupResponse = new HashSet(); for (SecurityGroupData sgd: userVmData.getSecurityGroupList()){ - SecurityGroupResponse sgr = new SecurityGroupResponse(); - sgr.setId(sgd.getId()); - sgr.setName(sgd.getName()); - sgr.setDescription(sgd.getDescription()); - - Account account = ApiDBUtils.findAccountByNameDomain(sgd.getAccountName(), sgd.getDomainId()); - populateAccount(sgr, account.getId()); - populateDomain(sgr, sgd.getDomainId()); - - sgr.setObjectName(sgd.getObjectName()); - securityGroupResponse.add(sgr); + if (sgd.getId() != null) { + SecurityGroupResponse sgr = new SecurityGroupResponse(); + sgr.setId(sgd.getId()); + sgr.setName(sgd.getName()); + sgr.setDescription(sgd.getDescription()); + + Account account = ApiDBUtils.findAccountByNameDomain(sgd.getAccountName(), sgd.getDomainId()); + populateAccount(sgr, account.getId()); + populateDomain(sgr, sgd.getDomainId()); + + sgr.setObjectName(sgd.getObjectName()); + securityGroupResponse.add(sgr); + } } userVmResponse.setSecurityGroupList(new ArrayList(securityGroupResponse)); diff --git a/server/src/com/cloud/configuration/ConfigurationManagerImpl.java b/server/src/com/cloud/configuration/ConfigurationManagerImpl.java index 691ecf367b8..04972a6c241 100755 --- a/server/src/com/cloud/configuration/ConfigurationManagerImpl.java +++ b/server/src/com/cloud/configuration/ConfigurationManagerImpl.java @@ -956,11 +956,7 @@ public class ConfigurationManagerImpl implements ConfigurationManager, Configura return pod; } - private boolean zoneHasVMs(long zoneId) { - List vmInstances = _vmInstanceDao.listByZoneId(zoneId); - return !vmInstances.isEmpty(); - } - + @DB protected void checkIfZoneIsDeletable(long zoneId) { List> tablesToCheck = new ArrayList>(); @@ -1001,6 +997,7 @@ public class ConfigurationManagerImpl implements ConfigurationManager, Configura volumes.add(2, "there are storage volumes for this zone"); tablesToCheck.add(volumes); + //FIXME - move this part of verification to deletePhysicalNetwork code List vnet = new ArrayList(); vnet.add(0, "op_dc_vnet_alloc"); vnet.add(1, "data_center_id"); @@ -1142,9 +1139,6 @@ public class ConfigurationManagerImpl implements ConfigurationManager, Configura txn.start(); - // Delete vNet - _zoneDao.deleteVnet(zoneId); - // delete vlans for this zone List vlans = _vlanDao.listByZone(zoneId); for (VlanVO vlan : vlans) { @@ -1152,12 +1146,16 @@ public class ConfigurationManagerImpl implements ConfigurationManager, Configura } // Delete networks + //FIXME - move this part to deletePhysicalNetwork List networks = _networkDao.listByZoneIncludingRemoved(zoneId); if (networks != null && !networks.isEmpty()) { for (NetworkVO network : networks) { _networkDao.remove(network.getId()); } } + + //FIXME - Delete physical networks belonging to the zone + success = _zoneDao.remove(zoneId); if (success) { @@ -1381,7 +1379,7 @@ public class ConfigurationManagerImpl implements ConfigurationManager, Configura List ntwkOff = _networkOfferingDao.listSystemNetworkOfferings(); for (NetworkOfferingVO offering : ntwkOff) { - DataCenterDeployment plan = new DataCenterDeployment(zone.getId(), null, null, null, null); + DataCenterDeployment plan = new DataCenterDeployment(zone.getId(), null, null, null, null, null); NetworkVO userNetwork = new NetworkVO(); Account systemAccount = _accountDao.findById(Account.ACCOUNT_ID_SYSTEM); diff --git a/server/src/com/cloud/dc/dao/DataCenterDao.java b/server/src/com/cloud/dc/dao/DataCenterDao.java index c5bed6aaa80..5ba0d5b4a07 100644 --- a/server/src/com/cloud/dc/dao/DataCenterDao.java +++ b/server/src/com/cloud/dc/dao/DataCenterDao.java @@ -51,8 +51,6 @@ public interface DataCenterDao extends GenericDao { void addLinkLocalIpAddress(long dcId,long podId, String start, String end); List findVnet(long dcId, String vnet); - - void deleteVnet(long dcId); String allocatePodVlan(long podId, long accountId); @@ -71,6 +69,6 @@ public interface DataCenterDao extends GenericDao { DataCenterVO findByTokenOrIdOrName(String tokenIdOrName); void addVnet(long dcId, long physicalNetworkId, int start, int end); - void deleteVnet(long dcId, long physicalNetworkId); - List listAllocatedVnets(long dcId, long physicalNetworkId); + void deleteVnet(long physicalNetworkId); + List listAllocatedVnets(long physicalNetworkId); } diff --git a/server/src/com/cloud/dc/dao/DataCenterDaoImpl.java b/server/src/com/cloud/dc/dao/DataCenterDaoImpl.java index 1e6cec93d89..7f063f516b9 100644 --- a/server/src/com/cloud/dc/dao/DataCenterDaoImpl.java +++ b/server/src/com/cloud/dc/dao/DataCenterDaoImpl.java @@ -111,7 +111,7 @@ public class DataCenterDaoImpl extends GenericDaoBase implem @Override public void releaseVnet(String vnet, long dcId, long physicalNetworkId, long accountId, String reservationId) { - _vnetAllocDao.release(vnet, dcId, physicalNetworkId, accountId, reservationId); + _vnetAllocDao.release(vnet, physicalNetworkId, accountId, reservationId); } @Override @@ -151,7 +151,7 @@ public class DataCenterDaoImpl extends GenericDaoBase implem @Override public String allocateVnet(long dataCenterId, long physicalNetworkId, long accountId, String reservationId) { - DataCenterVnetVO vo = _vnetAllocDao.take(dataCenterId, physicalNetworkId, accountId, reservationId); + DataCenterVnetVO vo = _vnetAllocDao.take(physicalNetworkId, accountId, reservationId); if (vo == null) { return null; } @@ -204,13 +204,6 @@ public class DataCenterDaoImpl extends GenericDaoBase implem } return vo.getIpAddress(); } - - - @Override - public void deleteVnet(long dcId) { - _vnetAllocDao.delete(dcId); - } - @Override public void addVnet(long dcId, long physicalNetworkId, int start, int end) { @@ -218,13 +211,13 @@ public class DataCenterDaoImpl extends GenericDaoBase implem } @Override - public void deleteVnet(long dcId, long physicalNetworkId) { - _vnetAllocDao.delete(dcId, physicalNetworkId); + public void deleteVnet(long physicalNetworkId) { + _vnetAllocDao.delete(physicalNetworkId); } @Override - public List listAllocatedVnets(long dcId, long physicalNetworkId) { - return _vnetAllocDao.listAllocatedVnets(dcId, physicalNetworkId); + public List listAllocatedVnets(long physicalNetworkId) { + return _vnetAllocDao.listAllocatedVnets(physicalNetworkId); } @Override diff --git a/server/src/com/cloud/dc/dao/DataCenterVnetDaoImpl.java b/server/src/com/cloud/dc/dao/DataCenterVnetDaoImpl.java index 0c833a8a9c6..3d0ef09a85f 100755 --- a/server/src/com/cloud/dc/dao/DataCenterVnetDaoImpl.java +++ b/server/src/com/cloud/dc/dao/DataCenterVnetDaoImpl.java @@ -41,16 +41,9 @@ public class DataCenterVnetDaoImpl extends GenericDaoBase VnetDcSearch; private final SearchBuilder VnetDcSearchAllocated; private final SearchBuilder DcSearchAllocated; - - public List listAllocatedVnets(long dcId) { - SearchCriteria sc = DcSearchAllocated.create(); - sc.setParameters("dc", dcId); - return listBy(sc); - } - public List listAllocatedVnets(long dcId, long physicalNetworkId) { + public List listAllocatedVnets(long physicalNetworkId) { SearchCriteria sc = DcSearchAllocated.create(); - sc.setParameters("dc", dcId); sc.setParameters("physicalNetworkId", physicalNetworkId); return listBy(sc); } @@ -92,24 +85,15 @@ public class DataCenterVnetDaoImpl extends GenericDaoBase sc = VnetDcSearch.create(); - sc.setParameters("dc", dcId); - remove(sc); - } - - public void delete(long dcId, long physicalNetworkId) { - SearchCriteria sc = VnetDcSearch.create(); - sc.setParameters("dc", dcId); sc.setParameters("physicalNetworkId", physicalNetworkId); - remove(sc); } @DB - public DataCenterVnetVO take(long dcId, long physicalNetworkId, long accountId, String reservationId) { + public DataCenterVnetVO take(long physicalNetworkId, long accountId, String reservationId) { SearchCriteria sc = FreeVnetSearch.create(); - sc.setParameters("dc", dcId); sc.setParameters("physicalNetworkId", physicalNetworkId); Date now = new Date(); Transaction txn = Transaction.currentTxn(); @@ -127,10 +111,9 @@ public class DataCenterVnetDaoImpl extends GenericDaoBase sc = VnetDcSearchAllocated.create(); sc.setParameters("vnet", vnet); - sc.setParameters("dc", dcId); sc.setParameters("physicalNetworkId", physicalNetworkId); sc.setParameters("account", accountId); sc.setParameters("reservation", reservationId); diff --git a/server/src/com/cloud/deploy/FirstFitPlanner.java b/server/src/com/cloud/deploy/FirstFitPlanner.java index bd302c05196..60ba05da82b 100755 --- a/server/src/com/cloud/deploy/FirstFitPlanner.java +++ b/server/src/com/cloud/deploy/FirstFitPlanner.java @@ -141,7 +141,7 @@ public class FirstFitPlanner extends PlannerBase implements DeploymentPlanner { } //search for storage under the zone, pod, cluster of the host. - DataCenterDeployment lastPlan = new DataCenterDeployment(host.getDataCenterId(), host.getPodId(), host.getClusterId(), hostIdSpecified, plan.getPoolId()); + DataCenterDeployment lastPlan = new DataCenterDeployment(host.getDataCenterId(), host.getPodId(), host.getClusterId(), hostIdSpecified, plan.getPoolId(), null); Pair>, List> result = findSuitablePoolsForVolumes(vmProfile, lastPlan, avoid, HostAllocator.RETURN_UPTO_ALL); Map> suitableVolumeStoragePools = result.first(); @@ -182,7 +182,7 @@ public class FirstFitPlanner extends PlannerBase implements DeploymentPlanner { s_logger.debug("The last host of this VM is UP and has enough capacity"); s_logger.debug("Now checking for suitable pools under zone: "+host.getDataCenterId() +", pod: "+ host.getPodId()+", cluster: "+ host.getClusterId()); //search for storage under the zone, pod, cluster of the last host. - DataCenterDeployment lastPlan = new DataCenterDeployment(host.getDataCenterId(), host.getPodId(), host.getClusterId(), host.getId(), plan.getPoolId()); + DataCenterDeployment lastPlan = new DataCenterDeployment(host.getDataCenterId(), host.getPodId(), host.getClusterId(), host.getId(), plan.getPoolId(), null); Pair>, List> result = findSuitablePoolsForVolumes(vmProfile, lastPlan, avoid, HostAllocator.RETURN_UPTO_ALL); Map> suitableVolumeStoragePools = result.first(); List readyAndReusedVolumes = result.second(); @@ -358,7 +358,7 @@ public class FirstFitPlanner extends PlannerBase implements DeploymentPlanner { s_logger.debug("Checking resources in Cluster: "+clusterId + " under Pod: "+clusterVO.getPodId()); //search for resources(hosts and storage) under this zone, pod, cluster. - DataCenterDeployment potentialPlan = new DataCenterDeployment(plan.getDataCenterId(), clusterVO.getPodId(), clusterVO.getId(), null, plan.getPoolId()); + DataCenterDeployment potentialPlan = new DataCenterDeployment(plan.getDataCenterId(), clusterVO.getPodId(), clusterVO.getId(), null, plan.getPoolId(), null); //find suitable hosts under this cluster, need as many hosts as we get. List suitableHosts = findSuitableHosts(vmProfile, potentialPlan, avoid, HostAllocator.RETURN_UPTO_ALL); diff --git a/server/src/com/cloud/network/NetworkManager.java b/server/src/com/cloud/network/NetworkManager.java index 13e1add9adb..9270616e3ba 100644 --- a/server/src/com/cloud/network/NetworkManager.java +++ b/server/src/com/cloud/network/NetworkManager.java @@ -160,8 +160,8 @@ public interface NetworkManager extends NetworkService { boolean destroyNetwork(long networkId, ReservationContext context); - Network createNetwork(long networkOfferingId, String name, String displayText, Boolean isDefault, Long zoneId, String gateway, String cidr, String vlanId, String networkDomain, Account owner, - boolean isSecurityGroupEnabled, Long domainId, List tags, Boolean isShared) throws ConcurrentOperationException, InsufficientCapacityException; + Network createNetwork(long networkOfferingId, String name, String displayText, Boolean isDefault, String gateway, String cidr, String vlanId, String networkDomain, Account owner, boolean isSecurityGroupEnabled, + Long domainId, List tags, Boolean isShared, PhysicalNetwork physicalNetwork) throws ConcurrentOperationException, InsufficientCapacityException; /** * @throws InsufficientCapacityException diff --git a/server/src/com/cloud/network/NetworkManagerImpl.java b/server/src/com/cloud/network/NetworkManagerImpl.java index 973ea0a3305..a7cfb6488db 100755 --- a/server/src/com/cloud/network/NetworkManagerImpl.java +++ b/server/src/com/cloud/network/NetworkManagerImpl.java @@ -1012,9 +1012,9 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag if (related == -1) { related = id; } - - NetworkVO vo = new NetworkVO(id, network, offering.getId(), plan.getDataCenterId(), guru.getName(), owner.getDomainId(), owner.getId(), related, name, displayText, isDefault, - predefined.isSecurityGroupEnabled(), (domainId != null), predefined.getNetworkDomain(), offering.getType(), isShared); + + NetworkVO vo = new NetworkVO(id, network, offering.getId(), guru.getName(), owner.getDomainId(), owner.getId(), related, name, displayText, isDefault, + predefined.isSecurityGroupEnabled(), (domainId != null), predefined.getNetworkDomain(), offering.getType(), isShared, plan.getDataCenterId(), plan.getPhysicalNetworkId()); vo.setTags(tags); networks.add(_networksDao.persist(vo, vo.getGuestType() != null)); @@ -1580,7 +1580,6 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag @ActionEvent(eventType = EventTypes.EVENT_NETWORK_CREATE, eventDescription = "creating network") public Network createNetwork(CreateNetworkCmd cmd) throws InsufficientCapacityException, ConcurrentOperationException { Long networkOfferingId = cmd.getNetworkOfferingId(); - Long zoneId = cmd.getZoneId(); String gateway = cmd.getGateway(); String startIP = cmd.getStartIp(); String endIP = cmd.getEndIp(); @@ -1595,6 +1594,7 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag List tags = cmd.getTags(); boolean isDomainSpecific = false; Boolean isShared = cmd.getIsShared(); + long physicalNetworkId = cmd.getPhysicalNetworkId(); if (tags != null && tags.size() > 1) { throw new InvalidParameterException("Only one tag can be specified for a network at this time"); @@ -1642,18 +1642,21 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag endIP = startIP; } - // Check if zone exists - if (zoneId == null) { - throw new InvalidParameterValueException("Please specify a valid zone."); + // Check if physical network exists + PhysicalNetwork pNtwk = _physicalNetworkDao.findById(physicalNetworkId); + if (pNtwk == null) { + throw new InvalidParameterValueException("Unable to find physical network by id " + physicalNetworkId); } - - DataCenterVO zone = _dcDao.findById(zoneId); - if (zone == null) { - throw new InvalidParameterValueException("Please specify a valid zone."); + + //check that the physical network is enabled + if (pNtwk.getState() != PhysicalNetwork.State.Enabled) { + throw new InvalidParameterValueException("Physical network id " + physicalNetworkId + " is in incorrect state: " + pNtwk.getState()); } + + DataCenter zone = _dcDao.findById(pNtwk.getDataCenterId()); if (Grouping.AllocationState.Disabled == zone.getAllocationState() && !_accountMgr.isRootAdmin(caller.getType())) { - throw new PermissionDeniedException("Cannot perform this operation, Zone is currently disabled: " + zoneId); + throw new PermissionDeniedException("Cannot perform this operation, Zone is currently disabled: " + zone.getId()); } // Check if network offering is Available @@ -1716,7 +1719,7 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag domainId = cmd.getDomainId(); } - Network network = createNetwork(networkOfferingId, name, displayText, isDefault, zoneId, gateway, cidr, vlanId, networkDomain, owner, false, domainId, tags, isShared); + Network network = createNetwork(networkOfferingId, name, displayText, isDefault, gateway, cidr, vlanId, networkDomain, owner, false, domainId, tags, isShared, pNtwk); // Don't pass owner to create vlan when network offering is of type Shared - done to prevent accountVlanMap entry // creation when vlan is mapped to network @@ -1726,7 +1729,7 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag if (caller.getType() == Account.ACCOUNT_TYPE_ADMIN && network.getType() == Network.Type.Shared && defineNetworkConfig) { // Create vlan ip range - _configMgr.createVlanAndPublicIpRange(userId, zoneId, null, startIP, endIP, gateway, netmask, false, vlanId, owner, network.getId()); + _configMgr.createVlanAndPublicIpRange(userId, pNtwk.getDataCenterId(), null, startIP, endIP, gateway, netmask, false, vlanId, owner, network.getId()); } txn.commit(); @@ -1736,11 +1739,12 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag @Override @DB - public Network createNetwork(long networkOfferingId, String name, String displayText, Boolean isDefault, Long zoneId, String gateway, String cidr, String vlanId, String networkDomain, - Account owner, boolean isSecurityGroupEnabled, Long domainId, List tags, Boolean isShared) throws ConcurrentOperationException, InsufficientCapacityException { + public Network createNetwork(long networkOfferingId, String name, String displayText, Boolean isDefault, String gateway, String cidr, String vlanId, String networkDomain, Account owner, + boolean isSecurityGroupEnabled, Long domainId, List tags, Boolean isShared, PhysicalNetwork physicalNetwork) throws ConcurrentOperationException, InsufficientCapacityException { NetworkOfferingVO networkOffering = _networkOfferingDao.findById(networkOfferingId); - DataCenterVO zone = _dcDao.findById(zoneId); + DataCenterVO zone = _dcDao.findById(physicalNetwork.getDataCenterId()); + long zoneId = zone.getId(); // allow isDefault to be set only for Shared network if (networkOffering.getType() == Network.Type.Isolated) { @@ -1750,7 +1754,7 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag isDefault = true; } if (isShared != null && isShared) { - throw new InvalidParameterValueException("Can specify isShared parameter for Direct networks only"); + throw new InvalidParameterValueException("Can specify isShared parameter for " + Network.Type.Shared + " networks only"); } } else { if (isDefault == null) { @@ -1832,7 +1836,7 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag Transaction txn = Transaction.currentTxn(); txn.start(); - DataCenterDeployment plan = new DataCenterDeployment(zoneId, null, null, null, null); + DataCenterDeployment plan = new DataCenterDeployment(zoneId, null, null, null, null, physicalNetwork.getId()); NetworkVO userNetwork = new NetworkVO(); userNetwork.setNetworkDomain(networkDomain); userNetwork.setSecurityGroupEnabled(isSecurityGroupEnabled); @@ -1892,6 +1896,7 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag List permittedAccounts = new ArrayList(); String path = null; Long sharedNetworkDomainId = null; + Long physicalNetworkId = cmd.getPhysicalNetworkId(); //1) default is system to false if not specified //2) reset parameter to false if it's specified by the regular user @@ -1981,27 +1986,27 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag List networksToReturn = new ArrayList(); if (sharedNetworkDomainId != null) { - networksToReturn.addAll(listDomainLevelNetworks(buildNetworkSearchCriteria(sb, keyword, id, isSystem, zoneId, type, isDefault, trafficType, isShared), searchFilter, sharedNetworkDomainId)); + networksToReturn.addAll(listDomainLevelNetworks(buildNetworkSearchCriteria(sb, keyword, id, isSystem, zoneId, type, isDefault, trafficType, isShared, physicalNetworkId), searchFilter, sharedNetworkDomainId)); } else { SearchBuilder domainSearch = _domainDao.createSearchBuilder(); domainSearch.and("path", domainSearch.entity().getPath(), SearchCriteria.Op.LIKE); sb.join("domainSearch", domainSearch, sb.entity().getDomainId(), domainSearch.entity().getId(), JoinBuilder.JoinType.INNER); - networksToReturn.addAll(listDomainSpecificNetworks(buildNetworkSearchCriteria(sb, keyword, id, isSystem, zoneId, type, isDefault, trafficType, isShared), searchFilter, path)); + networksToReturn.addAll(listDomainSpecificNetworks(buildNetworkSearchCriteria(sb, keyword, id, isSystem, zoneId, type, isDefault, trafficType, isShared, physicalNetworkId), searchFilter, path)); } //if user requested only domain specific networks, don't return account/zone wide networks if (!permittedAccounts.isEmpty() || (domainId == null && accountName == null && projectId == null)) { - networksToReturn.addAll(listAccountSpecificAndZoneLevelNetworks(buildNetworkSearchCriteria(sb, keyword, id, isSystem, zoneId, type, isDefault, trafficType, isShared), searchFilter, path, permittedAccounts)); + networksToReturn.addAll(listAccountSpecificAndZoneLevelNetworks(buildNetworkSearchCriteria(sb, keyword, id, isSystem, zoneId, type, isDefault, trafficType, isShared, physicalNetworkId), searchFilter, path, permittedAccounts)); } return networksToReturn; } else { - return _networksDao.search(buildNetworkSearchCriteria(sb, keyword, id, isSystem, zoneId, type, isDefault, trafficType, isShared), searchFilter); + return _networksDao.search(buildNetworkSearchCriteria(sb, keyword, id, isSystem, zoneId, type, isDefault, trafficType, isShared, physicalNetworkId), searchFilter); } } - private SearchCriteria buildNetworkSearchCriteria(SearchBuilder sb, String keyword, Long id, Boolean isSystem, Long zoneId, String type, Boolean isDefault, String trafficType, Boolean isShared) { + private SearchCriteria buildNetworkSearchCriteria(SearchBuilder sb, String keyword, Long id, Boolean isSystem, Long zoneId, String type, Boolean isDefault, String trafficType, Boolean isShared, Long physicalNetworkId) { SearchCriteria sc = sb.create(); if (isSystem != null) { @@ -2037,6 +2042,10 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag if (isShared != null) { sc.addAnd("isShared", SearchCriteria.Op.EQ, isShared); } + + if (physicalNetworkId != null) { + sc.addAnd("physicalNetworkId", SearchCriteria.Op.EQ, physicalNetworkId); + } return sc; } @@ -2772,7 +2781,7 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag // create new Virtual network for the user if it doesn't exist if (createNetwork) { List offerings = _configMgr.listNetworkOfferings(TrafficType.Guest, false); - network = createNetwork(offerings.get(0).getId(), owner.getAccountName() + "-network", owner.getAccountName() + "-network", null, zoneId, null, null, null, null, owner, false, null, null, false); + network = createNetwork(offerings.get(0).getId(), owner.getAccountName() + "-network", owner.getAccountName() + "-network", null, null, null, null, null, owner, false, null, null, false, null); if (network == null) { s_logger.warn("Failed to create default Virtual network for the account " + accountId + "in zone " + zoneId); @@ -3636,7 +3645,7 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag if (replaceVnet) { s_logger.debug("Deleting existing vnet range for the physicalNetwork id= "+id +" and zone id=" + network.getDataCenterId() + " as a part of updatePhysicalNetwork call"); - _dcDao.deleteVnet(network.getDataCenterId(), network.getId()); + _dcDao.deleteVnet(network.getId()); } for (Pair vnetToAdd : vnetsToAdd) { @@ -3648,7 +3657,7 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag } private boolean physicalNetworkHasAllocatedVnets(long zoneId, long physicalNetworkId) { - return !_dcDao.listAllocatedVnets(zoneId, physicalNetworkId).isEmpty(); + return !_dcDao.listAllocatedVnets(physicalNetworkId).isEmpty(); } @Override @@ -3669,7 +3678,7 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag return false; } - List allocatedVnets = _dcDao.listAllocatedVnets(network.getDataCenterId(), physicalNetworkId); + List allocatedVnets = _dcDao.listAllocatedVnets(physicalNetworkId); if(allocatedVnets != null && !allocatedVnets.isEmpty()){ s_logger.debug("Unable to remove the physical network id=" + physicalNetworkId + " as it has active vnets associated."); @@ -3909,4 +3918,19 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag return getPhysicalNetworkServiceProvider(providerId); } + + @Override + public long translateZoneToPhysicalNetwork(long zoneId) { + List pNtwks = _physicalNetworkDao.listByZone(zoneId); + if (pNtwks.isEmpty()) { + throw new InvalidParameterValueException("Unable to find physical network in zone id=" + zoneId); + } + + if (pNtwks.size() > 1) { + throw new InvalidParameterValueException("More than one physical networks exist in zone id=" + zoneId); + } + + return pNtwks.get(0).getId(); + } + } diff --git a/server/src/com/cloud/network/NetworkVO.java b/server/src/com/cloud/network/NetworkVO.java index 875b9b5eb95..2af1f1a555e 100644 --- a/server/src/com/cloud/network/NetworkVO.java +++ b/server/src/com/cloud/network/NetworkVO.java @@ -66,6 +66,7 @@ public class NetworkVO implements Network { @Enumerated(value=EnumType.STRING) TrafficType trafficType; + @Deprecated @Column(name="guest_type") GuestIpType guestType; @@ -88,7 +89,7 @@ public class NetworkVO implements Network { long networkOfferingId; @Column(name="physical_network_id") - long physicalNetworkId; + Long physicalNetworkId; @Column(name="data_center_id") long dataCenterId; @@ -167,15 +168,17 @@ public class NetworkVO implements Network { * @param mode * @param broadcastDomainType * @param networkOfferingId - * @param dataCenterId * @param state TODO + * @param dataCenterId + * @param physicalNetworkId TODO */ - public NetworkVO(TrafficType trafficType, GuestIpType guestType, Mode mode, BroadcastDomainType broadcastDomainType, long networkOfferingId, long dataCenterId, State state) { + public NetworkVO(TrafficType trafficType, GuestIpType guestType, Mode mode, BroadcastDomainType broadcastDomainType, long networkOfferingId, State state, long dataCenterId, Long physicalNetworkId) { this.trafficType = trafficType; this.mode = mode; this.broadcastDomainType = broadcastDomainType; this.networkOfferingId = networkOfferingId; this.dataCenterId = dataCenterId; + this.physicalNetworkId = physicalNetworkId; if (state == null) { state = State.Allocated; } else { @@ -184,23 +187,9 @@ public class NetworkVO implements Network { this.id = -1; this.guestType = guestType; } - /** - * Constructor to be used for the adapters because it only initializes what's needed. - * @param trafficType - * @param mode - * @param broadcastDomainType - * @param networkOfferingId - * @param dataCenterId - * @param state TODO - * @param physicalNetworkId - */ - public NetworkVO(TrafficType trafficType, GuestIpType guestType, Mode mode, BroadcastDomainType broadcastDomainType, long networkOfferingId, long dataCenterId, State state, long physicalNetworkId) { - this(trafficType, guestType, mode, broadcastDomainType, networkOfferingId, dataCenterId, state); - this.physicalNetworkId = physicalNetworkId; - } - public NetworkVO(long id, Network that, long offeringId, long dataCenterId, String guruName, long domainId, long accountId, long related, String name, String displayText, boolean isDefault, boolean isSecurityGroupEnabled, boolean isDomainSpecific, String networkDomain, Type type, boolean isShared) { - this(id, that.getTrafficType(), that.getGuestType(), that.getMode(), that.getBroadcastDomainType(), offeringId, dataCenterId, domainId, accountId, related, name, displayText,isDefault, isDomainSpecific, networkDomain, type, isShared); + public NetworkVO(long id, Network that, long offeringId, String guruName, long domainId, long accountId, long related, String name, String displayText, boolean isDefault, boolean isSecurityGroupEnabled, boolean isDomainSpecific, String networkDomain, Type type, boolean isShared, long dcId, Long physicalNetworkId) { + this(id, that.getTrafficType(), that.getGuestType(), that.getMode(), that.getBroadcastDomainType(), offeringId, domainId, accountId, related, name, displayText,isDefault, isDomainSpecific, networkDomain, type, isShared, dcId, physicalNetworkId); this.gateway = that.getGateway(); this.cidr = that.getCidr(); this.broadcastUri = that.getBroadcastUri(); @@ -213,11 +202,6 @@ public class NetworkVO implements Network { } } - public NetworkVO(long id, Network that, long offeringId, long dataCenterId, String guruName, long domainId, long accountId, long related, String name, String displayText, boolean isDefault, boolean isSecurityGroupEnabled, boolean isDomainSpecific, String networkDomain, Type type, boolean isShared, long physicalNetworkId) { - this(id, that, offeringId, dataCenterId, guruName, domainId, accountId, related, name, displayText, isDefault, isSecurityGroupEnabled, isDomainSpecific, networkDomain, type, isShared); - this.physicalNetworkId = physicalNetworkId; - } - /** * Constructor for the actual DAO object. * @param trafficType @@ -236,8 +220,8 @@ public class NetworkVO implements Network { * @param isShared TODO * @param isShared */ - public NetworkVO(long id, TrafficType trafficType, GuestIpType guestType, Mode mode, BroadcastDomainType broadcastDomainType, long networkOfferingId, long dataCenterId, long domainId, long accountId, long related, String name, String displayText, boolean isDefault, boolean isDomainSpecific, String networkDomain, Type type, boolean isShared) { - this(trafficType, guestType, mode, broadcastDomainType, networkOfferingId, dataCenterId, State.Allocated); + public NetworkVO(long id, TrafficType trafficType, GuestIpType guestType, Mode mode, BroadcastDomainType broadcastDomainType, long networkOfferingId, long domainId, long accountId, long related, String name, String displayText, boolean isDefault, boolean isDomainSpecific, String networkDomain, Type type, boolean isShared, long dcId, Long physicalNetworkId) { + this(trafficType, guestType, mode, broadcastDomainType, networkOfferingId, State.Allocated, dcId, physicalNetworkId); this.domainId = domainId; this.accountId = accountId; this.related = related; @@ -404,7 +388,7 @@ public class NetworkVO implements Network { } @Override - public long getPhysicalNetworkId() { + public Long getPhysicalNetworkId() { return physicalNetworkId; } diff --git a/server/src/com/cloud/network/guru/ControlNetworkGuru.java b/server/src/com/cloud/network/guru/ControlNetworkGuru.java index 32a3ba772db..6d40fe00016 100644 --- a/server/src/com/cloud/network/guru/ControlNetworkGuru.java +++ b/server/src/com/cloud/network/guru/ControlNetworkGuru.java @@ -77,7 +77,7 @@ public class ControlNetworkGuru extends PodBasedNetworkGuru implements NetworkGu return null; } - NetworkVO config = new NetworkVO(offering.getTrafficType(), offering.getGuestType(), Mode.Static, BroadcastDomainType.LinkLocal, offering.getId(), plan.getDataCenterId(), Network.State.Setup); + NetworkVO config = new NetworkVO(offering.getTrafficType(), offering.getGuestType(), Mode.Static, BroadcastDomainType.LinkLocal, offering.getId(), Network.State.Setup, plan.getDataCenterId(), plan.getPhysicalNetworkId()); config.setCidr(_cidr); config.setGateway(_gateway); diff --git a/server/src/com/cloud/network/guru/DirectNetworkGuru.java b/server/src/com/cloud/network/guru/DirectNetworkGuru.java index e6f31cdb5b1..72c5e6ba6a5 100644 --- a/server/src/com/cloud/network/guru/DirectNetworkGuru.java +++ b/server/src/com/cloud/network/guru/DirectNetworkGuru.java @@ -102,7 +102,7 @@ public class DirectNetworkGuru extends AdapterBase implements NetworkGuru { state = State.Setup; } - NetworkVO config = new NetworkVO(offering.getTrafficType(), offering.getGuestType(), Mode.Dhcp, BroadcastDomainType.Vlan, offering.getId(), plan.getDataCenterId(), state); + NetworkVO config = new NetworkVO(offering.getTrafficType(), offering.getGuestType(), Mode.Dhcp, BroadcastDomainType.Vlan, offering.getId(), state, plan.getDataCenterId(), plan.getPhysicalNetworkId()); if (userSpecified != null) { if ((userSpecified.getCidr() == null && userSpecified.getGateway() != null) || (userSpecified.getCidr() != null && userSpecified.getGateway() == null)) { diff --git a/server/src/com/cloud/network/guru/ExternalGuestNetworkGuru.java b/server/src/com/cloud/network/guru/ExternalGuestNetworkGuru.java index c468666f1e9..2130c22f562 100644 --- a/server/src/com/cloud/network/guru/ExternalGuestNetworkGuru.java +++ b/server/src/com/cloud/network/guru/ExternalGuestNetworkGuru.java @@ -109,7 +109,7 @@ public class ExternalGuestNetworkGuru extends GuestNetworkGuru { DataCenter zone = dest.getDataCenter(); NetworkVO implemented = new NetworkVO(config.getTrafficType(), config.getGuestType(), config.getMode(), config.getBroadcastDomainType(), config.getNetworkOfferingId(), - config.getDataCenterId(), State.Allocated); + State.Allocated, config.getDataCenterId(), config.getPhysicalNetworkId()); // Get a vlan tag int vlanTag; diff --git a/server/src/com/cloud/network/guru/GuestNetworkGuru.java b/server/src/com/cloud/network/guru/GuestNetworkGuru.java index 1bb13ffaacd..ad5fc13cd1b 100644 --- a/server/src/com/cloud/network/guru/GuestNetworkGuru.java +++ b/server/src/com/cloud/network/guru/GuestNetworkGuru.java @@ -95,7 +95,7 @@ public class GuestNetworkGuru extends AdapterBase implements NetworkGuru { return null; } - NetworkVO network = new NetworkVO(offering.getTrafficType(), offering.getGuestType(), Mode.Dhcp, BroadcastDomainType.Vlan, offering.getId(), plan.getDataCenterId(), State.Allocated); + NetworkVO network = new NetworkVO(offering.getTrafficType(), offering.getGuestType(), Mode.Dhcp, BroadcastDomainType.Vlan, offering.getId(), State.Allocated, plan.getDataCenterId(), plan.getPhysicalNetworkId()); if (userSpecified != null) { if ((userSpecified.getCidr() == null && userSpecified.getGateway() != null) || (userSpecified.getCidr() != null && userSpecified.getGateway() == null)) { throw new InvalidParameterValueException("cidr and gateway must be specified together."); @@ -141,7 +141,7 @@ public class GuestNetworkGuru extends AdapterBase implements NetworkGuru { long dcId = dest.getDataCenter().getId(); NetworkVO implemented = new NetworkVO(network.getTrafficType(), network.getGuestType(), network.getMode(), network.getBroadcastDomainType(), network.getNetworkOfferingId(), - network.getDataCenterId(), State.Allocated); + State.Allocated, network.getDataCenterId(), network.getPhysicalNetworkId()); if (network.getBroadcastUri() == null) { String vnet = _dcDao.allocateVnet(dcId, network.getPhysicalNetworkId(), network.getAccountId(), context.getReservationId()); diff --git a/server/src/com/cloud/network/guru/PodBasedNetworkGuru.java b/server/src/com/cloud/network/guru/PodBasedNetworkGuru.java index 7dbf6653009..c7505c1d969 100644 --- a/server/src/com/cloud/network/guru/PodBasedNetworkGuru.java +++ b/server/src/com/cloud/network/guru/PodBasedNetworkGuru.java @@ -69,7 +69,7 @@ public class PodBasedNetworkGuru extends AdapterBase implements NetworkGuru { return null; } - NetworkVO config = new NetworkVO(type, null, Mode.Static, BroadcastDomainType.Native, offering.getId(), plan.getDataCenterId(), Network.State.Setup); + NetworkVO config = new NetworkVO(type, null, Mode.Static, BroadcastDomainType.Native, offering.getId(), Network.State.Setup, plan.getDataCenterId(), plan.getPhysicalNetworkId()); return config; } diff --git a/server/src/com/cloud/network/guru/PublicNetworkGuru.java b/server/src/com/cloud/network/guru/PublicNetworkGuru.java index 150be147b98..0c175dee09a 100644 --- a/server/src/com/cloud/network/guru/PublicNetworkGuru.java +++ b/server/src/com/cloud/network/guru/PublicNetworkGuru.java @@ -94,7 +94,7 @@ public class PublicNetworkGuru extends AdapterBase implements NetworkGuru { } if (offering.getTrafficType() == TrafficType.Public) { - NetworkVO ntwk = new NetworkVO(offering.getTrafficType(), null, Mode.Static, BroadcastDomainType.Vlan, offering.getId(), plan.getDataCenterId(), State.Setup); + NetworkVO ntwk = new NetworkVO(offering.getTrafficType(), null, Mode.Static, BroadcastDomainType.Vlan, offering.getId(), State.Setup, plan.getDataCenterId(), plan.getPhysicalNetworkId()); return ntwk; } else { return null; diff --git a/server/src/com/cloud/network/lb/ElasticLoadBalancerManagerImpl.java b/server/src/com/cloud/network/lb/ElasticLoadBalancerManagerImpl.java index 0fefd4de425..7efb0b1da92 100644 --- a/server/src/com/cloud/network/lb/ElasticLoadBalancerManagerImpl.java +++ b/server/src/com/cloud/network/lb/ElasticLoadBalancerManagerImpl.java @@ -476,7 +476,7 @@ public class ElasticLoadBalancerManagerImpl implements DataCenterDeployment plan = null; DomainRouterVO elbVm = null; - plan = new DataCenterDeployment(dcId, dest.getPod().getId(), null, null, null); + plan = new DataCenterDeployment(dcId, dest.getPod().getId(), null, null, null, null); if (elbVm == null) { long id = _routerDao.getNextInSequence(Long.class, "id"); diff --git a/server/src/com/cloud/network/router/VirtualNetworkApplianceManagerImpl.java b/server/src/com/cloud/network/router/VirtualNetworkApplianceManagerImpl.java index cd30210133b..311a1ced2b4 100755 --- a/server/src/com/cloud/network/router/VirtualNetworkApplianceManagerImpl.java +++ b/server/src/com/cloud/network/router/VirtualNetworkApplianceManagerImpl.java @@ -1123,7 +1123,7 @@ public class VirtualNetworkApplianceManagerImpl implements VirtualNetworkApplian return router; } - DataCenterDeployment plan = new DataCenterDeployment(0, null, null, null, null); + DataCenterDeployment plan = new DataCenterDeployment(0, null, null, null, null, null); DomainRouterVO result = null; assert router.getIsRedundantRouter(); List routerList = _routerDao.findBy(router.getAccountId(), router.getDataCenterIdToDeployIn()); @@ -1236,7 +1236,7 @@ public class VirtualNetworkApplianceManagerImpl implements VirtualNetworkApplian // In Basic zone and Guest network we have to start domR per pod, not per network if (isPodBased) { routers = _routerDao.listByNetworkAndPodAndRole(guestNetwork.getId(), podId, Role.DHCP_USERDATA); - plan = new DataCenterDeployment(dcId, podId, null, null, null); + plan = new DataCenterDeployment(dcId, podId, null, null, null, null); } else { routers = _routerDao.listByNetworkAndRole(guestNetwork.getId(), Role.DHCP_USERDATA); plan = new DataCenterDeployment(dcId); diff --git a/server/src/com/cloud/offerings/NetworkOfferingVO.java b/server/src/com/cloud/offerings/NetworkOfferingVO.java index ff6b75111f2..ae4ede64c55 100644 --- a/server/src/com/cloud/offerings/NetworkOfferingVO.java +++ b/server/src/com/cloud/offerings/NetworkOfferingVO.java @@ -82,6 +82,7 @@ public class NetworkOfferingVO implements NetworkOffering { @Enumerated(value=EnumType.STRING) Availability availability; + @Deprecated @Column(name="guest_type") GuestIpType guestType; diff --git a/server/src/com/cloud/server/ConfigurationServerImpl.java b/server/src/com/cloud/server/ConfigurationServerImpl.java index 1bfbcd07017..15e02578067 100644 --- a/server/src/com/cloud/server/ConfigurationServerImpl.java +++ b/server/src/com/cloud/server/ConfigurationServerImpl.java @@ -954,7 +954,7 @@ public class ConfigurationServerImpl implements ConfigurationServer { } if (broadcastDomainType != null) { - NetworkVO network = new NetworkVO(id, trafficType, null, mode, broadcastDomainType, networkOfferingId, zoneId, domainId, accountId, related, null, null, isNetworkDefault, false, networkDomain, Network.Type.Shared, true); + NetworkVO network = new NetworkVO(id, trafficType, null, mode, broadcastDomainType, networkOfferingId, domainId, accountId, related, null, null, isNetworkDefault, false, networkDomain, Network.Type.Shared, true, zoneId, null); network.setGuruName(guruNames.get(network.getTrafficType())); network.setDns1(zone.getDns1()); network.setDns2(zone.getDns2()); diff --git a/server/src/com/cloud/server/ManagementServerImpl.java b/server/src/com/cloud/server/ManagementServerImpl.java index 70bdca07858..59793e77eef 100755 --- a/server/src/com/cloud/server/ManagementServerImpl.java +++ b/server/src/com/cloud/server/ManagementServerImpl.java @@ -1022,7 +1022,7 @@ public class ManagementServerImpl implements ManagementServer { VirtualMachineProfile vmProfile = new VirtualMachineProfileImpl(vm); - DataCenterDeployment plan = new DataCenterDeployment(srcHost.getDataCenterId(), srcHost.getPodId(), srcHost.getClusterId(), null, null); + DataCenterDeployment plan = new DataCenterDeployment(srcHost.getDataCenterId(), srcHost.getPodId(), srcHost.getClusterId(), null, null, null); ExcludeList excludes = new ExcludeList(); excludes.addHost(srcHostId); while (enHost.hasMoreElements()) { diff --git a/server/src/com/cloud/storage/allocator/AbstractStoragePoolAllocator.java b/server/src/com/cloud/storage/allocator/AbstractStoragePoolAllocator.java index 29c6647e726..2713fd82ddd 100755 --- a/server/src/com/cloud/storage/allocator/AbstractStoragePoolAllocator.java +++ b/server/src/com/cloud/storage/allocator/AbstractStoragePoolAllocator.java @@ -278,7 +278,7 @@ public abstract class AbstractStoragePoolAllocator extends AdapterBase implement avoid.addPool(pool.getId()); } - DataCenterDeployment plan = new DataCenterDeployment(dcId, podId, clusterId, null, null); + DataCenterDeployment plan = new DataCenterDeployment(dcId, podId, clusterId, null, null, null); return allocateToPool(dskCh, VMtemplate, plan, avoid, returnUpTo); } diff --git a/server/src/com/cloud/vm/UserVmManagerImpl.java b/server/src/com/cloud/vm/UserVmManagerImpl.java index 0da715ac0ff..7eef0305235 100755 --- a/server/src/com/cloud/vm/UserVmManagerImpl.java +++ b/server/src/com/cloud/vm/UserVmManagerImpl.java @@ -2177,8 +2177,8 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, Manager if (virtualNetworks.isEmpty()) { s_logger.debug("Creating default Virtual network for account " + owner + " as a part of deployVM process"); - Network newNetwork = _networkMgr.createNetwork(defaultVirtualOffering.get(0).getId(), owner.getAccountName() + "-network", owner.getAccountName() + "-network", null, zone.getId(), - null, null, null, null, owner, false, null, null, false); + Network newNetwork = _networkMgr.createNetwork(defaultVirtualOffering.get(0).getId(), owner.getAccountName() + "-network", owner.getAccountName() + "-network", null, null, + null, null, null, owner, false, null, null, false, null); defaultNetwork = _networkDao.findById(newNetwork.getId()); } else if (virtualNetworks.size() > 1) { throw new InvalidParameterValueException("More than 1 default Virtaul networks are found for account " + owner + "; please specify networkIds"); @@ -2190,8 +2190,8 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, Manager if (defaultNetworks.isEmpty()) { if (defaultVirtualOffering.get(0).getAvailability() == Availability.Optional) { s_logger.debug("Creating default Virtual network for account " + owner + " as a part of deployVM process"); - Network newNetwork = _networkMgr.createNetwork(defaultVirtualOffering.get(0).getId(), owner.getAccountName() + "-network", owner.getAccountName() + "-network", null, zone.getId(), - null, null, null, null, owner, false, null, null, false); + Network newNetwork = _networkMgr.createNetwork(defaultVirtualOffering.get(0).getId(), owner.getAccountName() + "-network", owner.getAccountName() + "-network", null, null, + null, null, null, owner, false, null, null, false, null); defaultNetwork = _networkDao.findById(newNetwork.getId()); } else { throw new InvalidParameterValueException("Unable to find default networks for account " + owner); @@ -2574,7 +2574,7 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, Manager DataCenterDeployment plan = null; if (destinationHost != null) { s_logger.debug("Destination Host to deploy the VM is specified, specifying a deployment plan to deploy the VM"); - plan = new DataCenterDeployment(vm.getDataCenterIdToDeployIn(), destinationHost.getPodId(), destinationHost.getClusterId(), destinationHost.getId(), null); + plan = new DataCenterDeployment(vm.getDataCenterIdToDeployIn(), destinationHost.getPodId(), destinationHost.getClusterId(), destinationHost.getId(), null, null); } vm = _itMgr.start(vm, params, caller, owner, plan); @@ -3335,8 +3335,8 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, Manager long networkOffering = oldNet.getNetworkOfferingId(); List virtualNetworks = _networkMgr.listNetworksForAccount(newAccount.getId(), zone.getId(), GuestIpType.Virtual, true); if (virtualNetworks.isEmpty()) { - Network newNetwork = _networkMgr.createNetwork(networkOffering, newAccount.getAccountName() + "-network", newAccount.getAccountName() + "-network", null, vm.getDataCenterIdToDeployIn(), - null, null, null, null, newAccount, false, null, null, false); + Network newNetwork = _networkMgr.createNetwork(networkOffering, newAccount.getAccountName() + "-network", newAccount.getAccountName() + "-network", null, null, + null, null, null, newAccount, false, null, null, false, null); defaultNetwork = _networkDao.findById(newNetwork.getId()); } else if (virtualNetworks.size() > 1) { throw new InvalidParameterValueException("More than 1 default Virtaul networks are found for account " + newAccount + "; please specify networkIds"); diff --git a/server/src/com/cloud/vm/VirtualMachineManagerImpl.java b/server/src/com/cloud/vm/VirtualMachineManagerImpl.java index 87944f14db6..b42747555c0 100755 --- a/server/src/com/cloud/vm/VirtualMachineManagerImpl.java +++ b/server/src/com/cloud/vm/VirtualMachineManagerImpl.java @@ -607,7 +607,7 @@ public class VirtualMachineManagerImpl implements VirtualMachineManager, Listene if (s_logger.isDebugEnabled()) { s_logger.debug("Trying to deploy VM, vm has dcId: "+vm.getDataCenterIdToDeployIn()+" and podId: "+vm.getPodIdToDeployIn() ); } - DataCenterDeployment plan = new DataCenterDeployment(vm.getDataCenterIdToDeployIn(), vm.getPodIdToDeployIn(), null, null, null); + DataCenterDeployment plan = new DataCenterDeployment(vm.getDataCenterIdToDeployIn(), vm.getPodIdToDeployIn(), null, null, null, null); if(planToDeploy != null && planToDeploy.getDataCenterId() != 0){ if (s_logger.isDebugEnabled()) { s_logger.debug("advanceStart: DeploymentPlan is provided, using dcId:"+planToDeploy.getDataCenterId() + ", podId: "+ planToDeploy.getPodId() @@ -670,9 +670,9 @@ public class VirtualMachineManagerImpl implements VirtualMachineManager, Listene throw new ResourceUnavailableException("Root volume is ready in different cluster, Deployment plan provided cannot be satisfied, unable to create a deployment for " + vm, Cluster.class, clusterIdSpecified); } } - plan = new DataCenterDeployment(planToDeploy.getDataCenterId(), planToDeploy.getPodId(), planToDeploy.getClusterId(), planToDeploy.getHostId(), vol.getPoolId()); + plan = new DataCenterDeployment(planToDeploy.getDataCenterId(), planToDeploy.getPodId(), planToDeploy.getClusterId(), planToDeploy.getHostId(), vol.getPoolId(), null); }else{ - plan = new DataCenterDeployment(rootVolDcId, rootVolPodId, rootVolClusterId, null, vol.getPoolId()); + plan = new DataCenterDeployment(rootVolDcId, rootVolPodId, rootVolClusterId, null, vol.getPoolId(), null); if (s_logger.isDebugEnabled()) { s_logger.debug(vol + " is READY, changing deployment plan to use this pool's dcId: " + rootVolDcId + " , podId: " + rootVolPodId + " , and clusterId: " + rootVolClusterId); } @@ -1378,7 +1378,7 @@ public class VirtualMachineManagerImpl implements VirtualMachineManager, Listene Host host = _hostDao.findById(hostId); - DataCenterDeployment plan = new DataCenterDeployment(host.getDataCenterId(), host.getPodId(), host.getClusterId(), null, null); + DataCenterDeployment plan = new DataCenterDeployment(host.getDataCenterId(), host.getPodId(), host.getClusterId(), null, null, null); ExcludeList excludes = new ExcludeList(); excludes.addHost(hostId); diff --git a/server/src/com/cloud/vm/dao/UserVmDaoImpl.java b/server/src/com/cloud/vm/dao/UserVmDaoImpl.java index 691839d9903..5323aa5e181 100755 --- a/server/src/com/cloud/vm/dao/UserVmDaoImpl.java +++ b/server/src/com/cloud/vm/dao/UserVmDaoImpl.java @@ -77,7 +77,7 @@ public class UserVmDaoImpl extends GenericDaoBase implements Use private static final int VM_DETAILS_BATCH_SIZE=100; private static final String VM_DETAILS = "select vm_instance.id, " + "account.id, account.account_name, account.type, domain.name, instance_group.id, instance_group.name," + - "data_center.id, data_center.name, data_center.is_security_group_enabled, host.id, host.name, " + + "data_center.id, data_center.name, host.id, host.name, " + "vm_template.id, vm_template.name, vm_template.display_text, iso.id, iso.name, " + "vm_template.enable_password, service_offering.id, disk_offering.name, storage_pool.id, storage_pool.pool_type, " + "service_offering.cpu, service_offering.speed, service_offering.ram_size, volumes.id, volumes.device_id, volumes.volume_type, security_group.id, security_group.name, " + @@ -482,9 +482,8 @@ public class UserVmDaoImpl extends GenericDaoBase implements Use } - boolean is_data_center_security_group_enabled = rs.getBoolean("data_center.is_security_group_enabled"); - //security_group.id, security_group.name, security_group.description, , data_center.is_security_group_enabled - if (is_data_center_security_group_enabled){ + Long securityGroupId = rs.getLong("security_group.id"); + if (securityGroupId != null && securityGroupId.longValue() != 0){ SecurityGroupData resp = userVmData.newSecurityGroupData(); resp.setId(rs.getLong("security_group.id")); resp.setName(rs.getString("security_group.name")); diff --git a/server/test/com/cloud/network/MockNetworkManagerImpl.java b/server/test/com/cloud/network/MockNetworkManagerImpl.java index a9127b6ab20..6db0ad752fc 100644 --- a/server/test/com/cloud/network/MockNetworkManagerImpl.java +++ b/server/test/com/cloud/network/MockNetworkManagerImpl.java @@ -340,8 +340,8 @@ public class MockNetworkManagerImpl implements NetworkManager, Manager, NetworkS } @Override - public Network createNetwork(long networkOfferingId, String name, String displayText, Boolean isDefault, Long zoneId, String gateway, String cidr, String vlanId, String networkDomain, - Account owner, boolean isSecurityGroupEnabled, Long domainId, List tags, Boolean isShared) throws ConcurrentOperationException, InsufficientCapacityException { + public Network createNetwork(long networkOfferingId, String name, String displayText, Boolean isDefault, String gateway, String cidr, String vlanId, String networkDomain, Account owner, + boolean isSecurityGroupEnabled, Long domainId, List tags, Boolean isShared, PhysicalNetwork physicalNetwork) throws ConcurrentOperationException, InsufficientCapacityException { // TODO Auto-generated method stub return null; } From aa808f568577eb06e19d4714fe9e4ec038383c69 Mon Sep 17 00:00:00 2001 From: Murali Reddy Date: Fri, 21 Oct 2011 18:15:36 +0530 Subject: [PATCH 021/159] -Added LB serive provider (seperating it out from Firewall service provider) -Bringing add/delete/list of all external network devices under one unified API's (addNetworkDevice, deleteNetworkDevice, listNetworkDevice) -Refactoring External network manager to work from both sets of API's add/delete/list NetworkDevice and add/delete/list External Firewall/LoadBalancer --- .../element/LoadBalancingServiceProvider.java | 18 +++ client/tomcatconf/components-premium.xml.in | 2 +- .../api/commands/AddExternalFirewallCmd.java | 22 ++-- .../commands/AddExternalLoadBalancerCmd.java | 15 ++- .../api/commands/AddNetworkDeviceCmd.java | 2 +- .../commands/DeleteExternalFirewallCmd.java | 4 +- .../DeleteExternalLoadBalancerCmd.java | 4 +- .../commands/ListExternalFirewallsCmd.java | 18 ++- .../ListExternalLoadBalancersCmd.java | 18 ++- .../api/commands/ListNetworkDeviceCmd.java | 2 +- .../PremiumComponentLibrary.java | 4 +- ...java => ExternalNetworkDeviceManager.java} | 38 +++--- ... => ExternalNetworkDeviceManagerImpl.java} | 116 +++++++++++++----- .../cloud/network/NetworkDeviceManager.java | 7 +- .../network/NetworkDeviceManagerImpl.java | 49 ++++++-- .../com/cloud/network/NetworkManagerImpl.java | 14 ++- .../element/ElasticLoadBalancerElement.java | 2 +- .../F5ExternalLoadBalancerElement.java | 6 +- ...=> JuniperSRXExternalFirewallElement.java} | 8 +- .../NetscalerExternalLoadBalancerElement.java | 6 +- .../network/element/VirtualRouterElement.java | 2 +- .../guru/ExternalGuestNetworkGuru.java | 4 +- 22 files changed, 259 insertions(+), 102 deletions(-) create mode 100644 api/src/com/cloud/network/element/LoadBalancingServiceProvider.java rename server/src/com/cloud/network/{ExternalNetworkManager.java => ExternalNetworkDeviceManager.java} (79%) rename server/src/com/cloud/network/{ExternalNetworkManagerImpl.java => ExternalNetworkDeviceManagerImpl.java} (92%) rename server/src/com/cloud/network/element/{ExternalFirewallElement.java => JuniperSRXExternalFirewallElement.java} (96%) diff --git a/api/src/com/cloud/network/element/LoadBalancingServiceProvider.java b/api/src/com/cloud/network/element/LoadBalancingServiceProvider.java new file mode 100644 index 00000000000..5bc81d39895 --- /dev/null +++ b/api/src/com/cloud/network/element/LoadBalancingServiceProvider.java @@ -0,0 +1,18 @@ +package com.cloud.network.element; + +import java.util.List; + +import com.cloud.exception.ResourceUnavailableException; +import com.cloud.network.Network; +import com.cloud.network.rules.FirewallRule; + +public interface LoadBalancingServiceProvider extends NetworkElement { + /** + * Apply rules + * @param network + * @param rules + * @return + * @throws ResourceUnavailableException + */ + boolean applyRules(Network network, List rules) throws ResourceUnavailableException; +} diff --git a/client/tomcatconf/components-premium.xml.in b/client/tomcatconf/components-premium.xml.in index cc032d99ed7..7306853c636 100755 --- a/client/tomcatconf/components-premium.xml.in +++ b/client/tomcatconf/components-premium.xml.in @@ -20,7 +20,7 @@ - + diff --git a/server/src/com/cloud/api/commands/AddExternalFirewallCmd.java b/server/src/com/cloud/api/commands/AddExternalFirewallCmd.java index 3ecfbce1b72..bec96596d27 100644 --- a/server/src/com/cloud/api/commands/AddExternalFirewallCmd.java +++ b/server/src/com/cloud/api/commands/AddExternalFirewallCmd.java @@ -26,9 +26,10 @@ import com.cloud.api.BaseCmd; import com.cloud.api.Implementation; import com.cloud.api.Parameter; import com.cloud.api.ServerApiException; +import com.cloud.api.BaseCmd.CommandType; import com.cloud.exception.InvalidParameterValueException; import com.cloud.host.Host; -import com.cloud.network.ExternalNetworkManager; +import com.cloud.network.ExternalNetworkDeviceManager; import com.cloud.server.ManagementService; import com.cloud.server.api.response.ExternalFirewallResponse; import com.cloud.user.Account; @@ -46,7 +47,10 @@ public class AddExternalFirewallCmd extends BaseCmd { @Parameter(name=ApiConstants.ZONE_ID, type=CommandType.LONG, required = true, description="Zone in which to add the external firewall appliance.") private Long zoneId; - + + @Parameter(name=ApiConstants.NETWORK_ID, type=CommandType.LONG, required = false, description="Pyshical network in the zone to which external firewall appliance will be added.") + private Long networkId; + @Parameter(name=ApiConstants.URL, type=CommandType.STRING, required = true, description="URL of the external firewall appliance.") private String url; @@ -56,7 +60,7 @@ public class AddExternalFirewallCmd extends BaseCmd { @Parameter(name=ApiConstants.PASSWORD, type=CommandType.STRING, required = true, description="Password of the external firewall appliance.") private String password; - @Parameter(name=ApiConstants.EXTERNAL_FIREWALL_TYPE, type=CommandType.STRING, description="External firewall type. Now supports JuniperSRX.") + @Parameter(name=ApiConstants.NETWORK_DEVICE_TYPE, type=CommandType.STRING, required = false, description="External firewall type. Now supports JuniperSRXFirewall.") private String type; /////////////////////////////////////////////////// /////////////////// Accessors /////////////////////// @@ -65,7 +69,11 @@ public class AddExternalFirewallCmd extends BaseCmd { public Long getZoneId() { return zoneId; } - + + public Long getNetworkId() { + return networkId; + } + public String getUrl() { return url; } @@ -78,7 +86,7 @@ public class AddExternalFirewallCmd extends BaseCmd { return password; } - public String getType() { + public String getDeviceType() { return type; } @@ -99,8 +107,8 @@ public class AddExternalFirewallCmd extends BaseCmd { @Override public void execute(){ try { - ComponentLocator locator = ComponentLocator.getLocator(ManagementService.Name); - ExternalNetworkManager externalNetworkMgr = locator.getManager(ExternalNetworkManager.class); + ComponentLocator locator = ComponentLocator.getLocator(ManagementService.Name); + ExternalNetworkDeviceManager externalNetworkMgr = locator.getManager(ExternalNetworkDeviceManager.class); Host externalFirewall = externalNetworkMgr.addExternalFirewall(this); ExternalFirewallResponse response = externalNetworkMgr.createExternalFirewallResponse(externalFirewall); response.setObjectName("externalfirewall"); diff --git a/server/src/com/cloud/api/commands/AddExternalLoadBalancerCmd.java b/server/src/com/cloud/api/commands/AddExternalLoadBalancerCmd.java index 5ec3ace41e7..7fae6e9ab88 100644 --- a/server/src/com/cloud/api/commands/AddExternalLoadBalancerCmd.java +++ b/server/src/com/cloud/api/commands/AddExternalLoadBalancerCmd.java @@ -28,7 +28,7 @@ import com.cloud.api.Parameter; import com.cloud.api.ServerApiException; import com.cloud.exception.InvalidParameterValueException; import com.cloud.host.Host; -import com.cloud.network.ExternalNetworkManager; +import com.cloud.network.ExternalNetworkDeviceManager; import com.cloud.server.ManagementService; import com.cloud.server.api.response.ExternalLoadBalancerResponse; import com.cloud.user.Account; @@ -46,6 +46,9 @@ public class AddExternalLoadBalancerCmd extends BaseCmd { @Parameter(name=ApiConstants.ZONE_ID, type=CommandType.LONG, required = true, description="Zone in which to add the external load balancer appliance.") private Long zoneId; + + @Parameter(name=ApiConstants.NETWORK_ID, type=CommandType.LONG, required = false, description="Pyshical network in the zone to which external load balancer appliance will be added.") + private Long networkId; @Parameter(name=ApiConstants.URL, type=CommandType.STRING, required = true, description="URL of the external load balancer appliance.") private String url; @@ -56,7 +59,7 @@ public class AddExternalLoadBalancerCmd extends BaseCmd { @Parameter(name=ApiConstants.PASSWORD, type=CommandType.STRING, required = true, description="Password of the external load balancer appliance.") private String password; - @Parameter(name=ApiConstants.EXTERNAL_LB_TYPE, type=CommandType.STRING, description="External load balancer type. Now supports F5BigIP.") + @Parameter(name=ApiConstants.NETWORK_DEVICE_TYPE, type=CommandType.STRING, required = false, description="External load balancer type. Now supports NetscalerLoadBalancer, F5BigIpLoadBalancer.") private String type; /////////////////////////////////////////////////// @@ -67,6 +70,10 @@ public class AddExternalLoadBalancerCmd extends BaseCmd { return zoneId; } + public Long getNetworkId() { + return networkId; + } + public String getUrl() { return url; } @@ -79,7 +86,7 @@ public class AddExternalLoadBalancerCmd extends BaseCmd { return password; } - public String getType() { + public String getDeviceType() { return type; } @@ -101,7 +108,7 @@ public class AddExternalLoadBalancerCmd extends BaseCmd { public void execute(){ try { ComponentLocator locator = ComponentLocator.getLocator(ManagementService.Name); - ExternalNetworkManager externalNetworkMgr = locator.getManager(ExternalNetworkManager.class); + ExternalNetworkDeviceManager externalNetworkMgr = locator.getManager(ExternalNetworkDeviceManager.class); Host externalLoadBalancer = externalNetworkMgr.addExternalLoadBalancer(this); ExternalLoadBalancerResponse response = externalNetworkMgr.createExternalLoadBalancerResponse(externalLoadBalancer); response.setObjectName("externalloadbalancer"); diff --git a/server/src/com/cloud/api/commands/AddNetworkDeviceCmd.java b/server/src/com/cloud/api/commands/AddNetworkDeviceCmd.java index 77b0f3ea4e3..24ec2d79cd1 100644 --- a/server/src/com/cloud/api/commands/AddNetworkDeviceCmd.java +++ b/server/src/com/cloud/api/commands/AddNetworkDeviceCmd.java @@ -30,7 +30,7 @@ public class AddNetworkDeviceCmd extends BaseCmd { // ////////////// API parameters ///////////////////// // /////////////////////////////////////////////////// - @Parameter(name = ApiConstants.NETWORK_DEVICE_TYPE, type = CommandType.STRING, description = "Network device type, now supports ExternalDhcp, ExternalFirewall, ExternalLoadBalancer, PxeServer") + @Parameter(name = ApiConstants.NETWORK_DEVICE_TYPE, type = CommandType.STRING, description = "Network device type, now supports ExternalDhcp, PxeServer, NetscalerLoadBalancer, F5BigIpLoadBalancer, JuniperSRXFirewall") private String type; @Parameter(name = ApiConstants.NETWORK_DEVICE_PARAMETER_LIST, type = CommandType.MAP, description = "parameters for network device") diff --git a/server/src/com/cloud/api/commands/DeleteExternalFirewallCmd.java b/server/src/com/cloud/api/commands/DeleteExternalFirewallCmd.java index 330870d7841..882ae6b4587 100644 --- a/server/src/com/cloud/api/commands/DeleteExternalFirewallCmd.java +++ b/server/src/com/cloud/api/commands/DeleteExternalFirewallCmd.java @@ -28,7 +28,7 @@ import com.cloud.api.Parameter; import com.cloud.api.ServerApiException; import com.cloud.api.response.SuccessResponse; import com.cloud.exception.InvalidParameterValueException; -import com.cloud.network.ExternalNetworkManager; +import com.cloud.network.ExternalNetworkDeviceManager; import com.cloud.server.ManagementService; import com.cloud.user.Account; import com.cloud.utils.component.ComponentLocator; @@ -71,7 +71,7 @@ public class DeleteExternalFirewallCmd extends BaseCmd { public void execute(){ try { ComponentLocator locator = ComponentLocator.getLocator(ManagementService.Name); - ExternalNetworkManager externalNetworkMgr = locator.getManager(ExternalNetworkManager.class); + ExternalNetworkDeviceManager externalNetworkMgr = locator.getManager(ExternalNetworkDeviceManager.class); boolean result = externalNetworkMgr.deleteExternalFirewall(this); if (result) { SuccessResponse response = new SuccessResponse(getCommandName()); diff --git a/server/src/com/cloud/api/commands/DeleteExternalLoadBalancerCmd.java b/server/src/com/cloud/api/commands/DeleteExternalLoadBalancerCmd.java index 6e751f6d3aa..50d63053059 100644 --- a/server/src/com/cloud/api/commands/DeleteExternalLoadBalancerCmd.java +++ b/server/src/com/cloud/api/commands/DeleteExternalLoadBalancerCmd.java @@ -28,7 +28,7 @@ import com.cloud.api.Parameter; import com.cloud.api.ServerApiException; import com.cloud.api.response.SuccessResponse; import com.cloud.exception.InvalidParameterValueException; -import com.cloud.network.ExternalNetworkManager; +import com.cloud.network.ExternalNetworkDeviceManager; import com.cloud.server.ManagementService; import com.cloud.user.Account; import com.cloud.utils.component.ComponentLocator; @@ -71,7 +71,7 @@ public class DeleteExternalLoadBalancerCmd extends BaseCmd { public void execute(){ try { ComponentLocator locator = ComponentLocator.getLocator(ManagementService.Name); - ExternalNetworkManager externalNetworkMgr = locator.getManager(ExternalNetworkManager.class); + ExternalNetworkDeviceManager externalNetworkMgr = locator.getManager(ExternalNetworkDeviceManager.class); boolean result = externalNetworkMgr.deleteExternalLoadBalancer(this); if (result) { SuccessResponse response = new SuccessResponse(getCommandName()); diff --git a/server/src/com/cloud/api/commands/ListExternalFirewallsCmd.java b/server/src/com/cloud/api/commands/ListExternalFirewallsCmd.java index dfa20209f5d..ada40918c0c 100644 --- a/server/src/com/cloud/api/commands/ListExternalFirewallsCmd.java +++ b/server/src/com/cloud/api/commands/ListExternalFirewallsCmd.java @@ -28,9 +28,10 @@ import com.cloud.api.ApiConstants; import com.cloud.api.BaseListCmd; import com.cloud.api.Implementation; import com.cloud.api.Parameter; +import com.cloud.api.BaseCmd.CommandType; import com.cloud.api.response.ListResponse; import com.cloud.host.Host; -import com.cloud.network.ExternalNetworkManager; +import com.cloud.network.ExternalNetworkDeviceManager; import com.cloud.server.ManagementService; import com.cloud.server.api.response.ExternalFirewallResponse; import com.cloud.utils.component.ComponentLocator; @@ -47,6 +48,11 @@ public class ListExternalFirewallsCmd extends BaseListCmd { @Parameter(name=ApiConstants.ZONE_ID, type=CommandType.LONG, required = true, description="zone Id") private long zoneId; + @Parameter(name=ApiConstants.NETWORK_ID, type=CommandType.LONG, description="Pyshical network in the zone from which which external load balancer appliance will be listed.") + private Long networkId; + + @Parameter(name=ApiConstants.NETWORK_DEVICE_TYPE, type=CommandType.STRING, description="External firewall type. Now supports only JuniperSRXFirewall.") + private String type; ///////////////////////////////////////////////////// /////////////////// Accessors /////////////////////// @@ -56,6 +62,14 @@ public class ListExternalFirewallsCmd extends BaseListCmd { return zoneId; } + public Long getNetworkId() { + return networkId; + } + + public String getDeviceType() { + return type; + } + ///////////////////////////////////////////////////// /////////////// API Implementation/////////////////// ///////////////////////////////////////////////////// @@ -68,7 +82,7 @@ public class ListExternalFirewallsCmd extends BaseListCmd { @Override public void execute(){ ComponentLocator locator = ComponentLocator.getLocator(ManagementService.Name); - ExternalNetworkManager externalNetworkMgr = locator.getManager(ExternalNetworkManager.class); + ExternalNetworkDeviceManager externalNetworkMgr = locator.getManager(ExternalNetworkDeviceManager.class); List externalFirewalls = externalNetworkMgr.listExternalFirewalls(this); ListResponse listResponse = new ListResponse(); diff --git a/server/src/com/cloud/api/commands/ListExternalLoadBalancersCmd.java b/server/src/com/cloud/api/commands/ListExternalLoadBalancersCmd.java index 069f61deddc..d25ba9d7d43 100644 --- a/server/src/com/cloud/api/commands/ListExternalLoadBalancersCmd.java +++ b/server/src/com/cloud/api/commands/ListExternalLoadBalancersCmd.java @@ -28,10 +28,11 @@ import com.cloud.api.ApiConstants; import com.cloud.api.BaseListCmd; import com.cloud.api.Implementation; import com.cloud.api.Parameter; +import com.cloud.api.BaseCmd.CommandType; import com.cloud.api.response.HostResponse; import com.cloud.api.response.ListResponse; import com.cloud.host.Host; -import com.cloud.network.ExternalNetworkManager; +import com.cloud.network.ExternalNetworkDeviceManager; import com.cloud.server.ManagementService; import com.cloud.server.api.response.ExternalLoadBalancerResponse; import com.cloud.utils.component.ComponentLocator; @@ -48,6 +49,11 @@ public class ListExternalLoadBalancersCmd extends BaseListCmd { @Parameter(name=ApiConstants.ZONE_ID, type=CommandType.LONG, description="zone Id") private long zoneId; + @Parameter(name=ApiConstants.NETWORK_ID, type=CommandType.LONG, description="Pyshical network in the zone from which which external load balancer appliance will be listed.") + private Long networkId; + + @Parameter(name=ApiConstants.NETWORK_DEVICE_TYPE, type=CommandType.STRING, description="External load balancer type. Now supports NetscalerLoadBalancer, F5BigIpLoadBalancer.") + private String type; ///////////////////////////////////////////////////// /////////////////// Accessors /////////////////////// @@ -57,6 +63,14 @@ public class ListExternalLoadBalancersCmd extends BaseListCmd { return zoneId; } + public Long getNetworkId() { + return networkId; + } + + public String getDeviceType() { + return type; + } + ///////////////////////////////////////////////////// /////////////// API Implementation/////////////////// ///////////////////////////////////////////////////// @@ -69,7 +83,7 @@ public class ListExternalLoadBalancersCmd extends BaseListCmd { @Override public void execute(){ ComponentLocator locator = ComponentLocator.getLocator(ManagementService.Name); - ExternalNetworkManager externalNetworkMgr = locator.getManager(ExternalNetworkManager.class); + ExternalNetworkDeviceManager externalNetworkMgr = locator.getManager(ExternalNetworkDeviceManager.class); List externalLoadBalancers = externalNetworkMgr.listExternalLoadBalancers(this); ListResponse listResponse = new ListResponse(); diff --git a/server/src/com/cloud/api/commands/ListNetworkDeviceCmd.java b/server/src/com/cloud/api/commands/ListNetworkDeviceCmd.java index 0d8b9b35b1a..57fdcc72ee9 100644 --- a/server/src/com/cloud/api/commands/ListNetworkDeviceCmd.java +++ b/server/src/com/cloud/api/commands/ListNetworkDeviceCmd.java @@ -34,7 +34,7 @@ public class ListNetworkDeviceCmd extends BaseListCmd { //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// - @Parameter(name = ApiConstants.NETWORK_DEVICE_TYPE, type = CommandType.STRING, description = "Network device type, now supports ExternalDhcp, ExternalFirewall, ExternalLoadBalancer, PxeServer") + @Parameter(name = ApiConstants.NETWORK_DEVICE_TYPE, type = CommandType.STRING, description = "Network device type, now supports ExternalDhcp, PxeServer, NetscalerLoadBalancer, F5BigIpLoadBalancer, JuniperSRXFirewall") private String type; @Parameter(name = ApiConstants.NETWORK_DEVICE_PARAMETER_LIST, type = CommandType.MAP, description = "parameters for network device") diff --git a/server/src/com/cloud/configuration/PremiumComponentLibrary.java b/server/src/com/cloud/configuration/PremiumComponentLibrary.java index 4462fa174b8..a0a758952fe 100755 --- a/server/src/com/cloud/configuration/PremiumComponentLibrary.java +++ b/server/src/com/cloud/configuration/PremiumComponentLibrary.java @@ -34,7 +34,7 @@ import com.cloud.netapp.NetappManagerImpl; import com.cloud.netapp.dao.LunDaoImpl; import com.cloud.netapp.dao.PoolDaoImpl; import com.cloud.netapp.dao.VolumeDaoImpl; -import com.cloud.network.ExternalNetworkManagerImpl; +import com.cloud.network.ExternalNetworkDeviceManagerImpl; import com.cloud.network.NetworkDeviceManagerImpl; import com.cloud.network.NetworkUsageManagerImpl; import com.cloud.secstorage.CommandExecLogDaoImpl; @@ -66,7 +66,7 @@ public class PremiumComponentLibrary extends DefaultComponentLibrary { addManager("HA Manager", HighAvailabilityManagerExtImpl.class); addManager("VMWareManager", VmwareManagerImpl.class); - addManager("ExternalNetworkManager", ExternalNetworkManagerImpl.class); + addManager("ExternalNetworkManager", ExternalNetworkDeviceManagerImpl.class); addManager("BareMetalVmManager", BareMetalVmManagerImpl.class); addManager("ExternalDhcpManager", ExternalDhcpManagerImpl.class); addManager("PxeServerManager", PxeServerManagerImpl.class); diff --git a/server/src/com/cloud/network/ExternalNetworkManager.java b/server/src/com/cloud/network/ExternalNetworkDeviceManager.java similarity index 79% rename from server/src/com/cloud/network/ExternalNetworkManager.java rename to server/src/com/cloud/network/ExternalNetworkDeviceManager.java index bdf2f6c5ddb..262f3c6c6f4 100644 --- a/server/src/com/cloud/network/ExternalNetworkManager.java +++ b/server/src/com/cloud/network/ExternalNetworkDeviceManager.java @@ -20,6 +20,7 @@ package com.cloud.network; import java.util.List; +import java.util.Map; import com.cloud.api.commands.AddExternalFirewallCmd; import com.cloud.api.commands.AddExternalLoadBalancerCmd; @@ -30,38 +31,29 @@ import com.cloud.api.commands.ListExternalLoadBalancersCmd; import com.cloud.exception.ResourceUnavailableException; import com.cloud.host.Host; import com.cloud.host.HostVO; +import com.cloud.network.NetworkDeviceManager.NetworkDeviceType; import com.cloud.network.rules.FirewallRule; import com.cloud.offering.NetworkOffering; import com.cloud.server.api.response.ExternalFirewallResponse; import com.cloud.server.api.response.ExternalLoadBalancerResponse; import com.cloud.utils.component.Manager; -public interface ExternalNetworkManager extends Manager { - - public static class ExternalNetworkDeviceType { - private String _name; - - public static final ExternalNetworkDeviceType F5BigIP = new ExternalNetworkDeviceType("F5BigIP"); - public static final ExternalNetworkDeviceType JuniperSRX = new ExternalNetworkDeviceType("JuniperSRX"); - public static final ExternalNetworkDeviceType NetscalerMPX = new ExternalNetworkDeviceType("NetscalerMPX"); - - public ExternalNetworkDeviceType(String name) { - _name = name; - } - - public String getName() { - return _name; - } - } +public interface ExternalNetworkDeviceManager extends Manager { // External Firewall methods public Host addExternalFirewall(AddExternalFirewallCmd cmd); - + + public Host addExternalFirewall(Long zoneId, Long physicalNetworkId, String deviceType, Map deviceParamList); + public boolean deleteExternalFirewall(DeleteExternalFirewallCmd cmd); - public List listExternalFirewalls(ListExternalFirewallsCmd cmd); + public boolean deleteExternalFirewall(Long hostId); + public List listExternalFirewalls(ListExternalFirewallsCmd cmd); + + public List listExternalFirewalls(Long zoneId, Long networkId, String deviceType); + public ExternalFirewallResponse createExternalFirewallResponse(Host externalFirewall); public boolean manageGuestNetworkWithExternalFirewall(boolean add, Network network, NetworkOffering offering) throws ResourceUnavailableException; @@ -78,9 +70,15 @@ public interface ExternalNetworkManager extends Manager { public Host addExternalLoadBalancer(AddExternalLoadBalancerCmd cmd); + public Host addExternalLoadBalancer(Long zoneId, Long physicalNetworkId, String deviceType, Map deviceParamList); + public boolean deleteExternalLoadBalancer(DeleteExternalLoadBalancerCmd cmd); + + public boolean deleteExternalLoadBalancer(Long hostId); - public List listExternalLoadBalancers(ListExternalLoadBalancersCmd cmd); + public List listExternalLoadBalancers(ListExternalLoadBalancersCmd cmd); + + public List listExternalLoadBalancers(Long zoneId, Long networkId, String deviceType); public ExternalLoadBalancerResponse createExternalLoadBalancerResponse(Host externalLoadBalancer); diff --git a/server/src/com/cloud/network/ExternalNetworkManagerImpl.java b/server/src/com/cloud/network/ExternalNetworkDeviceManagerImpl.java similarity index 92% rename from server/src/com/cloud/network/ExternalNetworkManagerImpl.java rename to server/src/com/cloud/network/ExternalNetworkDeviceManagerImpl.java index 058b698b156..83bfa1d1359 100644 --- a/server/src/com/cloud/network/ExternalNetworkManagerImpl.java +++ b/server/src/com/cloud/network/ExternalNetworkDeviceManagerImpl.java @@ -48,6 +48,7 @@ import com.cloud.agent.api.to.IpAddressTO; import com.cloud.agent.api.to.LoadBalancerTO; import com.cloud.agent.api.to.PortForwardingRuleTO; import com.cloud.agent.api.to.StaticNatRuleTO; +import com.cloud.api.ApiConstants; import com.cloud.api.commands.AddExternalFirewallCmd; import com.cloud.api.commands.AddExternalLoadBalancerCmd; import com.cloud.api.commands.DeleteExternalFirewallCmd; @@ -71,6 +72,7 @@ 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.NetworkDeviceManager.NetworkDeviceType; import com.cloud.network.Networks.TrafficType; import com.cloud.network.dao.IPAddressDao; import com.cloud.network.dao.InlineLoadBalancerNicMapDao; @@ -121,8 +123,8 @@ import com.cloud.vm.NicVO; import com.cloud.vm.dao.DomainRouterDao; import com.cloud.vm.dao.NicDao; -@Local(value = {ExternalNetworkManager.class}) -public class ExternalNetworkManagerImpl implements ExternalNetworkManager { +@Local(value = {ExternalNetworkDeviceManager.class}) +public class ExternalNetworkDeviceManagerImpl implements ExternalNetworkDeviceManager { public enum ExternalNetworkResourceName { JuniperSrx, F5BigIp, @@ -153,7 +155,7 @@ public class ExternalNetworkManagerImpl implements ExternalNetworkManager { ScheduledExecutorService _executor; int _externalNetworkStatsInterval; - private static final org.apache.log4j.Logger s_logger = Logger.getLogger(ExternalNetworkManagerImpl.class); + private static final org.apache.log4j.Logger s_logger = Logger.getLogger(ExternalNetworkDeviceManagerImpl.class); protected String _name; @Override @@ -205,10 +207,24 @@ public class ExternalNetworkManagerImpl implements ExternalNetworkManager { @Override public Host addExternalLoadBalancer(AddExternalLoadBalancerCmd cmd) { - long zoneId = cmd.getZoneId(); + Long zoneId = cmd.getZoneId(); + Long networkId = cmd.getNetworkId(); + String deviceType = cmd.getDeviceType(); + Map deviceParams = new HashMap(); + deviceParams.put(ApiConstants.USERNAME, cmd.getUsername()); + deviceParams.put(ApiConstants.PASSWORD, cmd.getPassword()); + deviceParams.put(ApiConstants.URL, cmd.getUrl()); + return addExternalLoadBalancer(zoneId, networkId, deviceType, deviceParams); + } + + @Override + public Host addExternalLoadBalancer(Long zoneId, Long networkId, String deviceType, Map deviceParamList) { + ServerResource resource =null; String guid; - String deviceType; + String url = (String) deviceParamList.get(ApiConstants.URL); + String username = (String) deviceParamList.get(ApiConstants.USERNAME); + String password = (String) deviceParamList.get(ApiConstants.PASSWORD); DataCenterVO zone = _dcDao.findById(zoneId); String zoneName; @@ -225,15 +241,14 @@ public class ExternalNetworkManagerImpl implements ExternalNetworkManager { URI uri; try { - uri = new URI(cmd.getUrl()); + uri = new URI(url); } catch (Exception e) { s_logger.debug(e); throw new InvalidParameterValueException(e.getMessage()); } String ipAddress = uri.getHost(); - String username = cmd.getUsername(); - String password = cmd.getPassword(); + Map params = new HashMap(); UrlUtil.parseQueryParameters(uri.getQuery(), true, params); String publicInterface = params.get("publicinterface"); @@ -253,15 +268,14 @@ public class ExternalNetworkManagerImpl implements ExternalNetworkManager { numRetries = "1"; } - deviceType = cmd.getType(); if (deviceType ==null) { - deviceType = ExternalNetworkDeviceType.NetscalerMPX.getName(); //TODO: default it to NetscalerMPX for now, till UI support Netscaler & F5 + deviceType = NetworkDeviceType.NetscalerLoadBalancer.getName(); //TODO: default it to Netscaler LB for now, till UI support Netscaler & F5 } - if (deviceType.equalsIgnoreCase(ExternalNetworkDeviceType.F5BigIP.getName())) { + if (deviceType.equalsIgnoreCase(NetworkDeviceType.F5BigIpLoadBalancer.getName())) { resource = new F5BigIpResource(); guid = getExternalNetworkResourceGuid(zoneId, ExternalNetworkResourceName.F5BigIp, ipAddress); - } else if (deviceType.equalsIgnoreCase(ExternalNetworkDeviceType.NetscalerMPX.getName())) { + } else if (deviceType.equalsIgnoreCase(NetworkDeviceType.NetscalerLoadBalancer.getName())) { resource = new NetscalerMPXResource(); guid = getExternalNetworkResourceGuid(zoneId, ExternalNetworkResourceName.NetscalerMPX, ipAddress); } else { @@ -289,9 +303,9 @@ public class ExternalNetworkManagerImpl implements ExternalNetworkManager { Host host = _agentMgr.addHost(zoneId, resource, Host.Type.ExternalLoadBalancer, hostDetails); if (host != null) { - if (deviceType.equalsIgnoreCase(ExternalNetworkDeviceType.F5BigIP.getName())) { + if (deviceType.equalsIgnoreCase(NetworkDeviceType.F5BigIpLoadBalancer.getName())) { zone.setLoadBalancerProvider(Network.Provider.F5BigIp.getName()); - } else if (deviceType.equalsIgnoreCase(ExternalNetworkDeviceType.NetscalerMPX.getName())) { + } else if (deviceType.equalsIgnoreCase(NetworkDeviceType.NetscalerLoadBalancer.getName())) { zone.setLoadBalancerProvider(Network.Provider.NetscalerMPX.getName()); } _dcDao.update(zone.getId(), zone); @@ -303,7 +317,11 @@ public class ExternalNetworkManagerImpl implements ExternalNetworkManager { @Override public boolean deleteExternalLoadBalancer(DeleteExternalLoadBalancerCmd cmd) { - long hostId = cmd.getId(); + return deleteExternalLoadBalancer(cmd.getId()); + } + + @Override + public boolean deleteExternalLoadBalancer(Long hostId) { User caller = _accountMgr.getActiveUser(UserContext.current().getCallerUserId()); HostVO externalLoadBalancer = _hostDao.findById(hostId); if (externalLoadBalancer == null) { @@ -331,9 +349,21 @@ public class ExternalNetworkManagerImpl implements ExternalNetworkManager { } @Override - public List listExternalLoadBalancers(ListExternalLoadBalancersCmd cmd) { - long zoneId = cmd.getZoneId(); - return _hostDao.listByTypeDataCenter(Host.Type.ExternalLoadBalancer, zoneId); + public List listExternalLoadBalancers(ListExternalLoadBalancersCmd cmd) { + List lbHosts = new ArrayList(); + if (NetworkDeviceType.NetscalerLoadBalancer.getName().equalsIgnoreCase(cmd.getDeviceType())) { + lbHosts.addAll(listExternalLoadBalancers(cmd.getZoneId(), cmd.getNetworkId(), NetworkDeviceType.NetscalerLoadBalancer.getName())); + } else if (NetworkDeviceType.F5BigIpLoadBalancer.getName().equalsIgnoreCase(cmd.getDeviceType())) { + lbHosts.addAll(listExternalLoadBalancers(cmd.getZoneId(), cmd.getNetworkId(), NetworkDeviceType.F5BigIpLoadBalancer.getName())); + } + return lbHosts; + } + + @Override + public List listExternalLoadBalancers(Long zoneId, Long networkId, String type) { + List lbHosts = new ArrayList(); + lbHosts.addAll(_hostDao.listByTypeDataCenter(Host.Type.ExternalLoadBalancer, zoneId)); + return lbHosts; } @Override @@ -524,10 +554,24 @@ public class ExternalNetworkManagerImpl implements ExternalNetworkManager { @Override public Host addExternalFirewall(AddExternalFirewallCmd cmd) { - long zoneId = cmd.getZoneId(); - String deviceType; + Long zoneId = cmd.getZoneId(); + Long networkId = cmd.getNetworkId(); + String deviceType = cmd.getDeviceType(); + Map deviceParams = new HashMap(); + deviceParams.put(ApiConstants.USERNAME, cmd.getUsername()); + deviceParams.put(ApiConstants.URL, cmd.getUrl()); + deviceParams.put(ApiConstants.PASSWORD, cmd.getPassword()); + return addExternalFirewall(zoneId, networkId, deviceType, deviceParams); + } + + @Override + public Host addExternalFirewall(Long zoneId, Long networkId, String deviceType, Map deviceParamList) { DataCenterVO zone = _dcDao.findById(zoneId); + String url = (String) deviceParamList.get(ApiConstants.URL); + String username = (String) deviceParamList.get(ApiConstants.USERNAME); + String password = (String) deviceParamList.get(ApiConstants.PASSWORD); + String zoneName; if (zone == null) { throw new InvalidParameterValueException("Could not find zone with ID: " + zoneId); @@ -542,15 +586,13 @@ public class ExternalNetworkManagerImpl implements ExternalNetworkManager { URI uri; try { - uri = new URI(cmd.getUrl()); + uri = new URI(url); } catch (Exception e) { s_logger.debug(e); throw new InvalidParameterValueException(e.getMessage()); } String ipAddress = uri.getHost(); - String username = cmd.getUsername(); - String password = cmd.getPassword(); Map params = new HashMap(); UrlUtil.parseQueryParameters(uri.getQuery(), true, params); String publicInterface = params.get("publicinterface"); @@ -597,11 +639,10 @@ public class ExternalNetworkManagerImpl implements ExternalNetworkManager { timeout = "300"; } - deviceType = cmd.getType(); if (deviceType ==null) { - deviceType = ExternalNetworkDeviceType.JuniperSRX.getName(); //default it to Juniper for now + deviceType = NetworkDeviceType.JuniperSRXFirewall.getName(); //default it to Juniper for now } - if (deviceType.equalsIgnoreCase(ExternalNetworkDeviceType.JuniperSRX.getName())) { + if (deviceType.equalsIgnoreCase(NetworkDeviceType.JuniperSRXFirewall.getName())) { resource = new JuniperSrxResource(); guid = getExternalNetworkResourceGuid(zoneId, ExternalNetworkResourceName.JuniperSrx, ipAddress); } else { @@ -663,7 +704,11 @@ public class ExternalNetworkManagerImpl implements ExternalNetworkManager { @Override public boolean deleteExternalFirewall(DeleteExternalFirewallCmd cmd) { - long hostId = cmd.getId(); + return deleteExternalFirewall(cmd.getId()); + } + + @Override + public boolean deleteExternalFirewall(Long hostId) { User caller = _accountMgr.getActiveUser(UserContext.current().getCallerUserId()); HostVO externalFirewall = _hostDao.findById(hostId); if (externalFirewall == null) { @@ -708,11 +753,22 @@ public class ExternalNetworkManagerImpl implements ExternalNetworkManager { } @Override - public List listExternalFirewalls(ListExternalFirewallsCmd cmd) { - long zoneId = cmd.getZoneId(); - return _hostDao.listByTypeDataCenter(Host.Type.ExternalFirewall, zoneId); + public List listExternalFirewalls(ListExternalFirewallsCmd cmd) { + List firewallHosts = new ArrayList(); + if (NetworkDeviceType.JuniperSRXFirewall.getName().equalsIgnoreCase(cmd.getDeviceType())) { + firewallHosts.addAll(listExternalFirewalls(cmd.getZoneId(), cmd.getNetworkId(), NetworkDeviceType.JuniperSRXFirewall.getName())); + } + return firewallHosts; + } + @Override + public List listExternalFirewalls(Long zoneId, Long networkId, String type) { + List firewallHosts = new ArrayList(); + firewallHosts.addAll(_hostDao.listByTypeDataCenter(Host.Type.ExternalFirewall, zoneId)); + return firewallHosts; + } + @Override public ExternalFirewallResponse createExternalFirewallResponse(Host externalFirewall) { Map fwDetails = _detailsDao.findDetails(externalFirewall.getId()); diff --git a/server/src/com/cloud/network/NetworkDeviceManager.java b/server/src/com/cloud/network/NetworkDeviceManager.java index 666bc10b1d4..0920d4d5881 100644 --- a/server/src/com/cloud/network/NetworkDeviceManager.java +++ b/server/src/com/cloud/network/NetworkDeviceManager.java @@ -15,6 +15,9 @@ public interface NetworkDeviceManager extends Manager { public static final NetworkDeviceType ExternalDhcp = new NetworkDeviceType("ExternalDhcp"); public static final NetworkDeviceType PxeServer = new NetworkDeviceType("PxeServer"); + public static final NetworkDeviceType NetscalerLoadBalancer = new NetworkDeviceType("NetscalerLoadBalancer"); + public static final NetworkDeviceType F5BigIpLoadBalancer = new NetworkDeviceType("F5BigIpLoadBalancer"); + public static final NetworkDeviceType JuniperSRXFirewall = new NetworkDeviceType("JuniperSRXFirewall"); public NetworkDeviceType(String name) { _name = name; @@ -24,12 +27,12 @@ public interface NetworkDeviceManager extends Manager { return _name; } } - + public Host addNetworkDevice(AddNetworkDeviceCmd cmd); public NetworkDeviceResponse getApiResponse(Host device); - public List listNetworkDevice(ListNetworkDeviceCmd cmd); + public List listNetworkDevice(ListNetworkDeviceCmd cmd); public boolean deleteNetworkDevice(DeleteNetworkDeviceCmd cmd); } diff --git a/server/src/com/cloud/network/NetworkDeviceManagerImpl.java b/server/src/com/cloud/network/NetworkDeviceManagerImpl.java index 222c6f2f3a6..6a9ae8acf64 100644 --- a/server/src/com/cloud/network/NetworkDeviceManagerImpl.java +++ b/server/src/com/cloud/network/NetworkDeviceManagerImpl.java @@ -24,6 +24,7 @@ import com.cloud.baremetal.PxeServerProfile; import com.cloud.exception.InvalidParameterValueException; import com.cloud.host.Host; import com.cloud.host.HostVO; +import com.cloud.host.Host.Type; import com.cloud.host.dao.HostDao; import com.cloud.server.api.response.NetworkDeviceResponse; import com.cloud.server.api.response.NwDeviceDhcpResponse; @@ -38,7 +39,7 @@ public class NetworkDeviceManagerImpl implements NetworkDeviceManager { @Inject ExternalDhcpManager _dhcpMgr; @Inject PxeServerManager _pxeMgr; @Inject HostDao _hostDao; - + @Inject ExternalNetworkDeviceManager _externalNetworkDeviceMgr; @Override public boolean configure(String name, Map params) throws ConfigurationException { _name = name; @@ -93,7 +94,16 @@ public class NetworkDeviceManagerImpl implements NetworkDeviceManager { PxeServerProfile profile = new PxeServerProfile(zoneId, podId, url, username, password, type, pingStorageServerIp, pingDir, tftpDir, pingCifsUsername, pingCifsPassword); return _pxeMgr.addPxeServer(profile); - + } else if (cmd.getType().equalsIgnoreCase(NetworkDeviceType.JuniperSRXFirewall.getName())) { + Long zoneId = Long.parseLong((String) params.get(ApiConstants.ZONE_ID)); + Long networkId = (params.get(ApiConstants.NETWORK_ID)==null)?Long.parseLong((String)params.get(ApiConstants.NETWORK_ID)):null; + return _externalNetworkDeviceMgr.addExternalFirewall(zoneId, networkId, NetworkDeviceType.JuniperSRXFirewall.getName(), cmd.getParamList()); + } else if (cmd.getType().equalsIgnoreCase(NetworkDeviceType.NetscalerLoadBalancer.getName())) { + Long zoneId = Long.parseLong((String) params.get(ApiConstants.ZONE_ID)); + return _externalNetworkDeviceMgr.addExternalLoadBalancer(zoneId, null, NetworkDeviceType.NetscalerLoadBalancer.getName(), cmd.getParamList()); + } else if (cmd.getType().equalsIgnoreCase(NetworkDeviceType.F5BigIpLoadBalancer.getName())) { + Long zoneId = Long.parseLong((String) params.get(ApiConstants.ZONE_ID)); + return _externalNetworkDeviceMgr.addExternalLoadBalancer(zoneId, null, NetworkDeviceType.F5BigIpLoadBalancer.getName(), cmd.getParamList()); } else { throw new CloudRuntimeException("Unsupported network device type:" + cmd.getType()); } @@ -169,15 +179,31 @@ public class NetworkDeviceManagerImpl implements NetworkDeviceManager { Long zoneId = Long.parseLong((String) params.get(ApiConstants.ZONE_ID)); Long podId = Long.parseLong((String)params.get(ApiConstants.POD_ID)); res = listNetworkDevice(zoneId, podId, Host.Type.PxeServer); + } else if (NetworkDeviceType.F5BigIpLoadBalancer.getName().equalsIgnoreCase(cmd.getType())) { + Long zoneId = Long.parseLong((String) params.get(ApiConstants.ZONE_ID)); + Long networkId = Long.parseLong((String) params.get(ApiConstants.NETWORK_ID)); + return _externalNetworkDeviceMgr.listExternalLoadBalancers(zoneId, networkId, NetworkDeviceType.F5BigIpLoadBalancer.getName()); + } else if (NetworkDeviceType.NetscalerLoadBalancer.getName().equalsIgnoreCase(cmd.getType())) { + Long zoneId = Long.parseLong((String) params.get(ApiConstants.ZONE_ID)); + Long networkId = Long.parseLong((String) params.get(ApiConstants.NETWORK_ID)); + return _externalNetworkDeviceMgr.listExternalLoadBalancers(zoneId, networkId, NetworkDeviceType.NetscalerLoadBalancer.getName()); + } else if (NetworkDeviceType.JuniperSRXFirewall.getName().equalsIgnoreCase(cmd.getType())) { + Long zoneId = Long.parseLong((String) params.get(ApiConstants.ZONE_ID)); + Long networkId = Long.parseLong((String) params.get(ApiConstants.NETWORK_ID)); + return _externalNetworkDeviceMgr.listExternalFirewalls(zoneId, networkId, NetworkDeviceType.JuniperSRXFirewall.getName()); } else if (cmd.getType() == null){ Long zoneId = Long.parseLong((String) params.get(ApiConstants.ZONE_ID)); Long podId = Long.parseLong((String)params.get(ApiConstants.POD_ID)); List res1 = listNetworkDevice(zoneId, podId, Host.Type.PxeServer); List res2 = listNetworkDevice(zoneId, podId, Host.Type.ExternalDhcp); - List res3 = new ArrayList(); - res3.addAll(res1); - res3.addAll(res2); - res = res3; + List res3 = listNetworkDevice(zoneId, podId, Host.Type.ExternalLoadBalancer); + List res4 = listNetworkDevice(zoneId, podId, Host.Type.ExternalFirewall); + List deviceAll = new ArrayList(); + deviceAll.addAll(res1); + deviceAll.addAll(res2); + deviceAll.addAll(res3); + deviceAll.addAll(res4); + res = deviceAll; } else { throw new CloudRuntimeException("Unknown network device type:" + cmd.getType()); } @@ -187,7 +213,12 @@ public class NetworkDeviceManagerImpl implements NetworkDeviceManager { @Override public boolean deleteNetworkDevice(DeleteNetworkDeviceCmd cmd) { - // TODO Auto-generated method stub - return true; + HostVO device = _hostDao.findById(cmd.getId()); + if (device.getType() == Type.ExternalLoadBalancer) { + return _externalNetworkDeviceMgr.deleteExternalLoadBalancer(cmd.getId()); + } else if (device.getType() == Type.ExternalLoadBalancer) { + return _externalNetworkDeviceMgr.deleteExternalFirewall(cmd.getId()); + } + return true; } -} +} \ No newline at end of file diff --git a/server/src/com/cloud/network/NetworkManagerImpl.java b/server/src/com/cloud/network/NetworkManagerImpl.java index a7cfb6488db..b136f50d1d7 100755 --- a/server/src/com/cloud/network/NetworkManagerImpl.java +++ b/server/src/com/cloud/network/NetworkManagerImpl.java @@ -106,6 +106,7 @@ import com.cloud.network.dao.PhysicalNetworkDao; import com.cloud.network.dao.PhysicalNetworkServiceProviderDao; import com.cloud.network.dao.PhysicalNetworkServiceProviderVO; import com.cloud.network.element.FirewallServiceProvider; +import com.cloud.network.element.LoadBalancingServiceProvider; import com.cloud.network.element.NetworkElement; import com.cloud.network.element.PasswordServiceProvider; import com.cloud.network.element.RemoteAccessVPNServiceProvider; @@ -2369,12 +2370,19 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag int found = 0; for (NetworkElement ne : _networkElements) { try { - if (!(ne instanceof FirewallServiceProvider)) { + if (!(ne instanceof FirewallServiceProvider) && !(ne instanceof LoadBalancingServiceProvider)) { continue; } - FirewallServiceProvider e = (FirewallServiceProvider)ne; found ++; - boolean handled = e.applyRules(network, rules); + boolean handled; + if (ne instanceof FirewallServiceProvider) { + FirewallServiceProvider e = (FirewallServiceProvider)ne; + handled = e.applyRules(network, rules); + } else { + LoadBalancingServiceProvider e = (LoadBalancingServiceProvider) ne; + handled = e.applyRules(network, rules); + } + s_logger.debug("Network Rules for network " + network.getId() + " were " + (handled ? "" : " not") + " handled by " + ne.getName()); } catch (ResourceUnavailableException e) { if (!continueOnError) { diff --git a/server/src/com/cloud/network/element/ElasticLoadBalancerElement.java b/server/src/com/cloud/network/element/ElasticLoadBalancerElement.java index 3da9c705c62..2f9dc6812ee 100644 --- a/server/src/com/cloud/network/element/ElasticLoadBalancerElement.java +++ b/server/src/com/cloud/network/element/ElasticLoadBalancerElement.java @@ -52,7 +52,7 @@ import com.cloud.vm.VirtualMachineProfile; @Local(value=NetworkElement.class) -public class ElasticLoadBalancerElement extends AdapterBase implements FirewallServiceProvider { +public class ElasticLoadBalancerElement extends AdapterBase implements LoadBalancingServiceProvider { private static final Logger s_logger = Logger.getLogger(ElasticLoadBalancerElement.class); private static final Map> capabilities = setCapabilities(); @Inject NetworkManager _networkManager; diff --git a/server/src/com/cloud/network/element/F5ExternalLoadBalancerElement.java b/server/src/com/cloud/network/element/F5ExternalLoadBalancerElement.java index e2dc5dc2f0f..4208556386e 100644 --- a/server/src/com/cloud/network/element/F5ExternalLoadBalancerElement.java +++ b/server/src/com/cloud/network/element/F5ExternalLoadBalancerElement.java @@ -34,7 +34,7 @@ import com.cloud.exception.ConcurrentOperationException; import com.cloud.exception.InsufficientCapacityException; import com.cloud.exception.InsufficientNetworkCapacityException; import com.cloud.exception.ResourceUnavailableException; -import com.cloud.network.ExternalNetworkManager; +import com.cloud.network.ExternalNetworkDeviceManager; import com.cloud.network.Network; import com.cloud.network.Network.Capability; import com.cloud.network.Network.Provider; @@ -53,12 +53,12 @@ import com.cloud.vm.VirtualMachine; import com.cloud.vm.VirtualMachineProfile; @Local(value=NetworkElement.class) -public class F5ExternalLoadBalancerElement extends AdapterBase implements FirewallServiceProvider { +public class F5ExternalLoadBalancerElement extends AdapterBase implements LoadBalancingServiceProvider { private static final Logger s_logger = Logger.getLogger(F5ExternalLoadBalancerElement.class); @Inject NetworkManager _networkManager; - @Inject ExternalNetworkManager _externalNetworkManager; + @Inject ExternalNetworkDeviceManager _externalNetworkManager; @Inject ConfigurationManager _configMgr; private boolean canHandle(Network config) { diff --git a/server/src/com/cloud/network/element/ExternalFirewallElement.java b/server/src/com/cloud/network/element/JuniperSRXExternalFirewallElement.java similarity index 96% rename from server/src/com/cloud/network/element/ExternalFirewallElement.java rename to server/src/com/cloud/network/element/JuniperSRXExternalFirewallElement.java index f8aa16c6068..537454c26fa 100644 --- a/server/src/com/cloud/network/element/ExternalFirewallElement.java +++ b/server/src/com/cloud/network/element/JuniperSRXExternalFirewallElement.java @@ -36,7 +36,7 @@ import com.cloud.exception.InsufficientCapacityException; import com.cloud.exception.InsufficientNetworkCapacityException; import com.cloud.exception.ResourceUnavailableException; import com.cloud.host.dao.HostDao; -import com.cloud.network.ExternalNetworkManager; +import com.cloud.network.ExternalNetworkDeviceManager; import com.cloud.network.Network; import com.cloud.network.Network.Capability; import com.cloud.network.Network.Provider; @@ -59,14 +59,14 @@ import com.cloud.vm.VirtualMachine; import com.cloud.vm.VirtualMachineProfile; @Local(value=NetworkElement.class) -public class ExternalFirewallElement extends AdapterBase implements SourceNATServiceProvider, FirewallServiceProvider, RemoteAccessVPNServiceProvider { +public class JuniperSRXExternalFirewallElement extends AdapterBase implements SourceNATServiceProvider, FirewallServiceProvider, RemoteAccessVPNServiceProvider { - private static final Logger s_logger = Logger.getLogger(ExternalFirewallElement.class); + private static final Logger s_logger = Logger.getLogger(JuniperSRXExternalFirewallElement.class); private static final Map> capabilities = setCapabilities(); @Inject NetworkManager _networkManager; - @Inject ExternalNetworkManager _externalNetworkManager; + @Inject ExternalNetworkDeviceManager _externalNetworkManager; @Inject HostDao _hostDao; @Inject ConfigurationManager _configMgr; @Inject NetworkOfferingDao _networkOfferingDao; diff --git a/server/src/com/cloud/network/element/NetscalerExternalLoadBalancerElement.java b/server/src/com/cloud/network/element/NetscalerExternalLoadBalancerElement.java index 2a177f7054b..e1393694428 100644 --- a/server/src/com/cloud/network/element/NetscalerExternalLoadBalancerElement.java +++ b/server/src/com/cloud/network/element/NetscalerExternalLoadBalancerElement.java @@ -34,7 +34,7 @@ import com.cloud.exception.ConcurrentOperationException; import com.cloud.exception.InsufficientCapacityException; import com.cloud.exception.InsufficientNetworkCapacityException; import com.cloud.exception.ResourceUnavailableException; -import com.cloud.network.ExternalNetworkManager; +import com.cloud.network.ExternalNetworkDeviceManager; import com.cloud.network.Network; import com.cloud.network.Network.Capability; import com.cloud.network.Network.Provider; @@ -53,12 +53,12 @@ import com.cloud.vm.VirtualMachine; import com.cloud.vm.VirtualMachineProfile; @Local(value=NetworkElement.class) -public class NetscalerExternalLoadBalancerElement extends AdapterBase implements FirewallServiceProvider { +public class NetscalerExternalLoadBalancerElement extends AdapterBase implements LoadBalancingServiceProvider { private static final Logger s_logger = Logger.getLogger(NetscalerExternalLoadBalancerElement.class); @Inject NetworkManager _networkManager; - @Inject ExternalNetworkManager _externalNetworkManager; + @Inject ExternalNetworkDeviceManager _externalNetworkManager; @Inject ConfigurationManager _configMgr; private boolean canHandle(Network config) { diff --git a/server/src/com/cloud/network/element/VirtualRouterElement.java b/server/src/com/cloud/network/element/VirtualRouterElement.java index 7ee1841a9b7..782e856e921 100644 --- a/server/src/com/cloud/network/element/VirtualRouterElement.java +++ b/server/src/com/cloud/network/element/VirtualRouterElement.java @@ -73,7 +73,7 @@ import com.cloud.vm.dao.UserVmDao; @Local(value=NetworkElement.class) -public class VirtualRouterElement extends DhcpElement implements VirtualRouterElementService, SourceNATServiceProvider, FirewallServiceProvider, StaticNATServiceProvider, RemoteAccessVPNServiceProvider { +public class VirtualRouterElement extends DhcpElement implements VirtualRouterElementService, SourceNATServiceProvider, FirewallServiceProvider, LoadBalancingServiceProvider, StaticNATServiceProvider, RemoteAccessVPNServiceProvider { private static final Logger s_logger = Logger.getLogger(VirtualRouterElement.class); private static final Map> capabilities = setCapabilities(); diff --git a/server/src/com/cloud/network/guru/ExternalGuestNetworkGuru.java b/server/src/com/cloud/network/guru/ExternalGuestNetworkGuru.java index 2130c22f562..9d811ea05c1 100644 --- a/server/src/com/cloud/network/guru/ExternalGuestNetworkGuru.java +++ b/server/src/com/cloud/network/guru/ExternalGuestNetworkGuru.java @@ -33,7 +33,7 @@ import com.cloud.event.EventUtils; import com.cloud.event.EventVO; import com.cloud.exception.InsufficientAddressCapacityException; import com.cloud.exception.InsufficientVirtualNetworkCapcityException; -import com.cloud.network.ExternalNetworkManager; +import com.cloud.network.ExternalNetworkDeviceManager; import com.cloud.network.Network; import com.cloud.network.Network.State; import com.cloud.network.NetworkManager; @@ -64,7 +64,7 @@ public class ExternalGuestNetworkGuru extends GuestNetworkGuru { @Inject NetworkManager _networkMgr; @Inject - ExternalNetworkManager _externalNetworkMgr; + ExternalNetworkDeviceManager _externalNetworkMgr; @Inject NetworkDao _networkDao; @Inject From abca3dda9dfbff412bb3d9d551ae62d3c89b1829 Mon Sep 17 00:00:00 2001 From: alena Date: Fri, 21 Oct 2011 15:33:57 -0700 Subject: [PATCH 022/159] Added ability to list network offerings availabe for network upgrade using listNetworkOfferings command with "networkId" parameter. Limitations: * can't upgrade to the network offering with lesser number of services * can upgrade only when the service provider of the original offering is not external (domR, dhcp, elb) to the external type of the provider --- .../api/commands/ListNetworkOfferingsCmd.java | 8 + .../api/commands/ListServiceOfferingsCmd.java | 1 - .../commands/UpdateNetworkOfferingCmd.java | 16 +- api/src/com/cloud/network/Network.java | 27 ++-- .../ConfigurationManagerImpl.java | 39 ++++- .../src/com/cloud/network/NetworkManager.java | 2 + .../com/cloud/network/NetworkManagerImpl.java | 149 +++++++++++------- .../com/cloud/network/dao/NetworkDaoImpl.java | 2 +- .../guru/DirectPodBasedNetworkGuru.java | 2 +- .../lb/ElasticLoadBalancerManagerImpl.java | 1 - .../offerings/dao/NetworkOfferingDao.java | 3 + .../offerings/dao/NetworkOfferingDaoImpl.java | 37 +++++ .../cloud/server/ManagementServerImpl.java | 7 +- 13 files changed, 206 insertions(+), 88 deletions(-) diff --git a/api/src/com/cloud/api/commands/ListNetworkOfferingsCmd.java b/api/src/com/cloud/api/commands/ListNetworkOfferingsCmd.java index e9cedb86d82..a1cefb5a70a 100644 --- a/api/src/com/cloud/api/commands/ListNetworkOfferingsCmd.java +++ b/api/src/com/cloud/api/commands/ListNetworkOfferingsCmd.java @@ -27,6 +27,7 @@ import com.cloud.api.ApiConstants; import com.cloud.api.BaseListCmd; import com.cloud.api.Implementation; import com.cloud.api.Parameter; +import com.cloud.api.BaseCmd.CommandType; import com.cloud.api.response.ListResponse; import com.cloud.api.response.NetworkOfferingResponse; import com.cloud.offering.NetworkOffering; @@ -75,6 +76,9 @@ public class ListNetworkOfferingsCmd extends BaseListCmd { @Parameter(name=ApiConstants.STATE, type=CommandType.STRING, description="list network offerings by state") private String state; + + @Parameter(name=ApiConstants.NETWORK_ID, type=CommandType.LONG, description="the ID of the network. Pass this in if you want to see the available network offering that a network can be changed to.") + private Long networkId; ///////////////////////////////////////////////////// /////////////////// Accessors /////////////////////// @@ -128,6 +132,10 @@ public class ListNetworkOfferingsCmd extends BaseListCmd { return state; } + public Long getNetworkId() { + return networkId; + } + ///////////////////////////////////////////////////// /////////////// API Implementation/////////////////// ///////////////////////////////////////////////////// diff --git a/api/src/com/cloud/api/commands/ListServiceOfferingsCmd.java b/api/src/com/cloud/api/commands/ListServiceOfferingsCmd.java index 0387ed835da..4883366e18d 100644 --- a/api/src/com/cloud/api/commands/ListServiceOfferingsCmd.java +++ b/api/src/com/cloud/api/commands/ListServiceOfferingsCmd.java @@ -26,7 +26,6 @@ import com.cloud.api.ApiConstants; import com.cloud.api.BaseListCmd; import com.cloud.api.Implementation; import com.cloud.api.Parameter; -import com.cloud.api.BaseCmd.CommandType; import com.cloud.api.response.ListResponse; import com.cloud.api.response.ServiceOfferingResponse; import com.cloud.offering.ServiceOffering; diff --git a/api/src/com/cloud/api/commands/UpdateNetworkOfferingCmd.java b/api/src/com/cloud/api/commands/UpdateNetworkOfferingCmd.java index db6e1a9b58c..435bcbabe89 100644 --- a/api/src/com/cloud/api/commands/UpdateNetworkOfferingCmd.java +++ b/api/src/com/cloud/api/commands/UpdateNetworkOfferingCmd.java @@ -113,35 +113,35 @@ public class UpdateNetworkOfferingCmd extends BaseCmd { } public Boolean getDhcpService() { - return dhcpService; + return dhcpService == null ? false : dhcpService; } public Boolean getDnsService() { - return dnsService; + return dnsService == null ? false : dnsService; } public Boolean getGatewayService() { - return gatewayService; + return gatewayService == null ? false : gatewayService; } public Boolean getFirewallService() { - return firewallService; + return firewallService == null ? false : firewallService; } public Boolean getLbService() { - return lbService; + return lbService == null ? false : lbService; } public Boolean getUserdataService() { - return userdataService; + return userdataService == null ? false : userdataService; } public Boolean getSourceNatService() { - return sourceNatService; + return sourceNatService == null ? false : sourceNatService; } public Boolean getVpnService() { - return vpnService; + return vpnService == null ? false : vpnService; } public Map> getServiceProviders() { diff --git a/api/src/com/cloud/network/Network.java b/api/src/com/cloud/network/Network.java index 1154efece57..99f3f18250c 100644 --- a/api/src/com/cloud/network/Network.java +++ b/api/src/com/cloud/network/Network.java @@ -111,22 +111,25 @@ public interface Network extends ControlledEntity { public static class Provider { private static List supportedProviders = new ArrayList(); - public static final Provider VirtualRouter = new Provider("VirtualRouter"); - public static final Provider DhcpServer = new Provider("DhcpServer"); - public static final Provider JuniperSRX = new Provider("JuniperSRX"); - public static final Provider F5BigIp = new Provider("F5BigIp"); - public static final Provider NetscalerMPX = new Provider("NetscalerMPX"); - public static final Provider ExternalDhcpServer = new Provider("ExternalDhcpServer"); - public static final Provider ExternalGateWay = new Provider("ExternalGateWay"); - public static final Provider ElasticLoadBalancerVm = new Provider("ElasticLoadBalancerVm"); + public static final Provider VirtualRouter = new Provider("VirtualRouter", false); + public static final Provider DhcpServer = new Provider("DhcpServer", false); + public static final Provider JuniperSRX = new Provider("JuniperSRX", true); + public static final Provider F5BigIp = new Provider("F5BigIp", true); + public static final Provider NetscalerMPX = new Provider("NetscalerMPX", true); + public static final Provider ExternalDhcpServer = new Provider("ExternalDhcpServer", true); + public static final Provider ExternalGateWay = new Provider("ExternalGateWay", true); + public static final Provider ElasticLoadBalancerVm = new Provider("ElasticLoadBalancerVm", false); + public static final Provider defaultProvider = VirtualRouter; - public static final Provider None = new Provider("None"); + public static final Provider None = new Provider("None", false); private String name; + private boolean isExternal; - public Provider(String name) { + public Provider(String name, boolean isExternal) { this.name = name; + this.isExternal = isExternal; supportedProviders.add(this); } @@ -134,6 +137,10 @@ public interface Network extends ControlledEntity { return name; } + public boolean isExternal() { + return isExternal; + } + public static Provider getProvider(String providerName) { for (Provider provider : supportedProviders) { if (provider.getName().equalsIgnoreCase(providerName)) { diff --git a/server/src/com/cloud/configuration/ConfigurationManagerImpl.java b/server/src/com/cloud/configuration/ConfigurationManagerImpl.java index 04972a6c241..52c262d11d1 100755 --- a/server/src/com/cloud/configuration/ConfigurationManagerImpl.java +++ b/server/src/com/cloud/configuration/ConfigurationManagerImpl.java @@ -139,7 +139,6 @@ import com.cloud.utils.db.SearchCriteria; import com.cloud.utils.db.Transaction; import com.cloud.utils.exception.CloudRuntimeException; import com.cloud.utils.net.NetUtils; -import com.cloud.vm.VMInstanceVO; import com.cloud.vm.VirtualMachine; import com.cloud.vm.dao.ConsoleProxyDao; import com.cloud.vm.dao.DomainRouterDao; @@ -2874,10 +2873,11 @@ public class ConfigurationManagerImpl implements ConfigurationManager, Configura @Override public List searchForNetworkOfferings(ListNetworkOfferingsCmd cmd) { + Account caller = UserContext.current().getCaller(); Filter searchFilter = new Filter(NetworkOfferingVO.class, "created", false, cmd.getStartIndex(), cmd.getPageSizeVal()); SearchCriteria sc = _networkOfferingDao.createSearchCriteria(); - Object id = cmd.getId(); + Long id = cmd.getId(); Object name = cmd.getNetworkOfferingName(); Object displayText = cmd.getDisplayText(); Object trafficType = cmd.getTrafficType(); @@ -2890,6 +2890,7 @@ public class ConfigurationManagerImpl implements ConfigurationManager, Configura Object state = cmd.getState(); Long zoneId = cmd.getZoneId(); DataCenter zone = null; + Long networkId = cmd.getNetworkId(); if (zoneId != null) { zone = getZone(zoneId); @@ -2905,10 +2906,6 @@ public class ConfigurationManagerImpl implements ConfigurationManager, Configura sc.addAnd("name", SearchCriteria.Op.SC, ssc); } - if (id != null) { - sc.addAnd("id", SearchCriteria.Op.EQ, id); - } - if (guestIpType != null) { sc.addAnd("guestType", SearchCriteria.Op.EQ, guestIpType); } @@ -2956,9 +2953,37 @@ public class ConfigurationManagerImpl implements ConfigurationManager, Configura sc.addAnd("guestType", SearchCriteria.Op.EQ, GuestIpType.Direct); } } - + // Don't return system network offerings to the user sc.addAnd("systemOnly", SearchCriteria.Op.EQ, false); + + //list offerings available for upgrade only + if (networkId != null) { + //check if network exists and the caller can operate with it + Network network = _networkMgr.getNetwork(networkId); + if (network == null) { + throw new InvalidParameterValueException("Unable to find the network by id=" + networkId); + } + // Don't allow to update system network + NetworkOffering offering = _networkOfferingDao.findByIdIncludingRemoved(network.getNetworkOfferingId()); + if (offering.isSystemOnly()) { + throw new InvalidParameterValueException("Can't update system networks"); + } + + _accountMgr.checkAccess(caller, null, network); + + List offeringIds = _networkMgr.listNetworkOfferingsForUpgrade(networkId); + + if (!offeringIds.isEmpty()) { + sc.addAnd("id", SearchCriteria.Op.IN, offeringIds.toArray()); + } else { + return new ArrayList(); + } + } + + if (id != null) { + sc.addAnd("id", SearchCriteria.Op.EQ, id); + } return _networkOfferingDao.search(sc, searchFilter); } diff --git a/server/src/com/cloud/network/NetworkManager.java b/server/src/com/cloud/network/NetworkManager.java index 9270616e3ba..5fc88d1f594 100644 --- a/server/src/com/cloud/network/NetworkManager.java +++ b/server/src/com/cloud/network/NetworkManager.java @@ -222,5 +222,7 @@ public interface NetworkManager extends NetworkService { Long getPodIdForVlan(long vlanDbId); boolean isProviderSupported(long networkOfferingId, Service service, Provider provider); + + List listNetworkOfferingsForUpgrade(long networkId); } diff --git a/server/src/com/cloud/network/NetworkManagerImpl.java b/server/src/com/cloud/network/NetworkManagerImpl.java index b136f50d1d7..90f9d51c1ed 100755 --- a/server/src/com/cloud/network/NetworkManagerImpl.java +++ b/server/src/com/cloud/network/NetworkManagerImpl.java @@ -1787,36 +1787,38 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag } // If networkDomain is not specified, take it from the global configuration - Map dnsCapabilities = getServiceCapabilities(zoneId, networkOfferingId, Service.Dns); - String isUpdateDnsSupported = dnsCapabilities.get(Capability.AllowDnsSuffixModification); - if (isUpdateDnsSupported == null || !Boolean.valueOf(isUpdateDnsSupported)) { - if (networkDomain != null) { - throw new InvalidParameterValueException("Domain name change is not supported by network offering id=" + networkOfferingId + " in zone id=" + zoneId); - } - } else { - if (networkDomain == null) { - //1) Get networkDomain from the corresponding account/domain/zone - if (isShared) { - if (domainId != null) { - networkDomain = getDomainNetworkDomain(domainId, zoneId); - } else { - networkDomain = getZoneNetworkDomain(zoneId); - } - } else { - networkDomain = getAccountNetworkDomain(owner.getId(), zoneId); + if (isServiceSupported(networkOfferingId, Service.Dns)) { + Map dnsCapabilities = getServiceCapabilities(zoneId, networkOfferingId, Service.Dns); + String isUpdateDnsSupported = dnsCapabilities.get(Capability.AllowDnsSuffixModification); + if (isUpdateDnsSupported == null || !Boolean.valueOf(isUpdateDnsSupported)) { + if (networkDomain != null) { + throw new InvalidParameterValueException("Domain name change is not supported by network offering id=" + networkOfferingId + " in zone id=" + zoneId); } - - //2) If null, generate networkDomain using domain suffix from the global config variables - if (networkDomain == null) { - networkDomain = "cs" + Long.toHexString(owner.getId()) + _networkDomain; - } - } else { - // validate network domain - if (!NetUtils.verifyDomainName(networkDomain)) { - throw new InvalidParameterValueException( - "Invalid network domain. Total length shouldn't exceed 190 chars. Each domain label must be between 1 and 63 characters long, can contain ASCII letters 'a' through 'z', the digits '0' through '9', " - + "and the hyphen ('-'); can't start or end with \"-\""); + if (networkDomain == null) { + //1) Get networkDomain from the corresponding account/domain/zone + if (isShared) { + if (domainId != null) { + networkDomain = getDomainNetworkDomain(domainId, zoneId); + } else { + networkDomain = getZoneNetworkDomain(zoneId); + } + } else { + networkDomain = getAccountNetworkDomain(owner.getId(), zoneId); + } + + //2) If null, generate networkDomain using domain suffix from the global config variables + if (networkDomain == null) { + networkDomain = "cs" + Long.toHexString(owner.getId()) + _networkDomain; + } + + } else { + // validate network domain + if (!NetUtils.verifyDomainName(networkDomain)) { + throw new InvalidParameterValueException( + "Invalid network domain. Total length shouldn't exceed 190 chars. Each domain label must be between 1 and 63 characters long, can contain ASCII letters 'a' through 'z', the digits '0' through '9', " + + "and the hyphen ('-'); can't start or end with \"-\""); + } } } } @@ -2661,7 +2663,7 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag public Map getServiceCapabilities(long zoneId, Long networkOfferingId, Service service) { if (!isServiceSupported(networkOfferingId, service)) { - throw new UnsupportedServiceException("Service " + service.getName() + " is not by the network offering id=" + networkOfferingId); + throw new UnsupportedServiceException("Service " + service.getName() + " is not supported by the network offering id=" + networkOfferingId); } Map> networkCapabilities = getZoneCapabilities(zoneId); @@ -3156,6 +3158,12 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag if (networkOffering == null || networkOffering.isSystemOnly()) { throw new InvalidParameterValueException("Unable to find network offering by id " + networkOfferingId); } + + //network offering should be in Enabled state + if (networkOffering.getState() != NetworkOffering.State.Enabled) { + throw new InvalidParameterValueException("Network offering " + networkOffering + " is not in " + NetworkOffering.State.Enabled + " state, can't upgrade to it"); + } + if (networkOffering.getAvailability() == Availability.Unavailable || networkOffering.getState() == NetworkOffering.State.Disabled || networkOffering.getState() == NetworkOffering.State.Inactive) { throw new InvalidParameterValueException("Can't update network; network offering id=" + networkOfferingId + " is " + networkOffering.getAvailability() + " and " + networkOffering.getState()); } @@ -3410,31 +3418,47 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag return false; } -// //list of services and providers should be the same -// Map> newServices = listNetworkOfferingServices(newNetworkOfferingId); -// Map> oldServices = listNetworkOfferingServices(oldNetworkOfferingId); -// -// if (newServices.size() != oldServices.size()) { -// s_logger.debug("Number of supported services is not the same for offering " + newNetworkOfferingId + " and " + oldNetworkOfferingId); -// return false; -// } -// -// for (String service : newServices.keySet()) { -// Set newProviders = newServices.get(service); -// Set oldProviders = oldServices.get(service); -// if (newProviders.size() != oldProviders.size()) { -// s_logger.debug("Number of providers for the service " + service + " is not the same for offering " + newNetworkOfferingId + " and " + oldNetworkOfferingId); -// return false; -// } -// -// for (String provider : newProviders) { -// if (!oldProviders.contains(provider)) { -// s_logger.debug("Providers are different for the " + service + " is not the same for offering " + newNetworkOfferingId + " and " + oldNetworkOfferingId); -// return false; -// } -// } -// } + //compare providers + return canUpgradeProviders(oldNetworkOfferingId, newNetworkOfferingId); + } + + + protected boolean canUpgradeProviders(long oldNetworkOfferingId, long newNetworkOfferingId) { + //list of services and providers should be the same + Map> newServices = listNetworkOfferingServices(newNetworkOfferingId); + Map> oldServices = listNetworkOfferingServices(oldNetworkOfferingId); + if (newServices.size() < oldServices.size()) { + s_logger.debug("Network offering downgrade is not allowed: number of supported services for the new offering " + newNetworkOfferingId + " is less than the old offering " + oldNetworkOfferingId); + return false; + } + + for (String service : oldServices.keySet()) { + + //1)check that all old services are present in the new network offering + if (!newServices.containsKey(service)) { + s_logger.debug("New service offering doesn't have " + service + " service present in the old service offering, downgrade is not allowed"); + return false; + } + + Set newProviders = newServices.get(service); + Set oldProviders = oldServices.get(service); + + //2) Can upgrade only from internal provider to external provider. Any other combinations are not allowed + for (String oldProvider : oldProviders) { + if (newProviders.contains(oldProvider)) { + s_logger.trace("New list of providers contains provider " + oldProvider); + continue; + } + //iterate through new providers and check that the old provider can upgrade + for (String newProvider : newProviders) { + if (!(!Provider.getProvider(oldProvider).isExternal() && Provider.getProvider(newProvider).isExternal())) { + s_logger.debug("Can't downgrade from network offering " + oldNetworkOfferingId + " to the new networkOffering " + newNetworkOfferingId); + return false; + } + } + } + } return true; } @@ -3489,7 +3513,6 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag throw new InvalidParameterValueException("Unable to resolve broadcastDomainRange '" + broadcastDomainRangeStr + "' to a supported value {Pod or Zone}"); } } - Transaction txn = Transaction.currentTxn(); try { @@ -3940,5 +3963,23 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag return pNtwks.get(0).getId(); } + + @Override + public List listNetworkOfferingsForUpgrade(long networkId) { + List offeringIdsToReturn = new ArrayList(); + + NetworkOffering originalOffering = _configMgr.getNetworkOffering(getNetwork(networkId).getNetworkOfferingId()); + + List offerings = _networkOfferingDao.getOfferingIdsToUpgradeFrom(originalOffering); + + //check if providers are upgradable + for (Long offering : offerings) { + if (canUpgradeProviders(originalOffering.getId(), offering.longValue())) { + offeringIdsToReturn.add(offering); + } + } + + return offeringIdsToReturn; + } } diff --git a/server/src/com/cloud/network/dao/NetworkDaoImpl.java b/server/src/com/cloud/network/dao/NetworkDaoImpl.java index c50c4ec15b0..129b6b114c9 100644 --- a/server/src/com/cloud/network/dao/NetworkDaoImpl.java +++ b/server/src/com/cloud/network/dao/NetworkDaoImpl.java @@ -338,7 +338,7 @@ public class NetworkDaoImpl extends GenericDaoBase implements N @Override public Long getNetworkCountByOfferingId(long offeringId) { SearchCriteria sc = CountByOfferingId.create(); - sc.setParameters("offering", offeringId); + sc.setParameters("offeringId", offeringId); List results = customSearch(sc, null); return results.get(0); } diff --git a/server/src/com/cloud/network/guru/DirectPodBasedNetworkGuru.java b/server/src/com/cloud/network/guru/DirectPodBasedNetworkGuru.java index 4c8fd1daac2..42db8901983 100644 --- a/server/src/com/cloud/network/guru/DirectPodBasedNetworkGuru.java +++ b/server/src/com/cloud/network/guru/DirectPodBasedNetworkGuru.java @@ -79,7 +79,7 @@ public class DirectPodBasedNetworkGuru extends DirectNetworkGuru { @Override protected boolean canHandle(NetworkOffering offering, DataCenter dc) { // this guru handles system Direct pod based network - if (dc.getNetworkType() == NetworkType.Basic && offering.getTrafficType() == TrafficType.Guest && offering.isSecurityGroupEnabled()) { + if (dc.getNetworkType() == NetworkType.Basic && offering.getTrafficType() == TrafficType.Guest) { return true; } else { s_logger.trace("We only take care of Guest Direct Pod based networks"); diff --git a/server/src/com/cloud/network/lb/ElasticLoadBalancerManagerImpl.java b/server/src/com/cloud/network/lb/ElasticLoadBalancerManagerImpl.java index 7efb0b1da92..72092171a2d 100644 --- a/server/src/com/cloud/network/lb/ElasticLoadBalancerManagerImpl.java +++ b/server/src/com/cloud/network/lb/ElasticLoadBalancerManagerImpl.java @@ -686,7 +686,6 @@ public class ElasticLoadBalancerManagerImpl implements s_logger.warn("Failed to deploy a new ELB vm for ip " + ipAddr + " in network " + network + "lb name=" + lb.getName()); if (newIp) releaseIp(ipId, UserContext.current().getCallerUserId(), account); - } } diff --git a/server/src/com/cloud/offerings/dao/NetworkOfferingDao.java b/server/src/com/cloud/offerings/dao/NetworkOfferingDao.java index e58b5f41a0b..40dae489f9b 100644 --- a/server/src/com/cloud/offerings/dao/NetworkOfferingDao.java +++ b/server/src/com/cloud/offerings/dao/NetworkOfferingDao.java @@ -25,6 +25,7 @@ import java.util.List; import com.cloud.network.Network.GuestIpType; import com.cloud.network.Networks.TrafficType; +import com.cloud.offering.NetworkOffering; import com.cloud.offering.NetworkOffering.Availability; import com.cloud.offerings.NetworkOfferingVO; import com.cloud.utils.db.GenericDao; @@ -59,5 +60,7 @@ public interface NetworkOfferingDao extends GenericDao List listByAvailability(Availability availability, boolean isSystem); List listByTrafficTypeAndGuestType(boolean isSystem, TrafficType trafficType, GuestIpType guestType); + + List getOfferingIdsToUpgradeFrom(NetworkOffering originalOffering); } diff --git a/server/src/com/cloud/offerings/dao/NetworkOfferingDaoImpl.java b/server/src/com/cloud/offerings/dao/NetworkOfferingDaoImpl.java index fe190f70ab5..79ba402391c 100644 --- a/server/src/com/cloud/offerings/dao/NetworkOfferingDaoImpl.java +++ b/server/src/com/cloud/offerings/dao/NetworkOfferingDaoImpl.java @@ -29,12 +29,15 @@ import javax.persistence.EntityExistsException; import com.cloud.network.Network.GuestIpType; import com.cloud.network.Networks.TrafficType; +import com.cloud.offering.NetworkOffering; import com.cloud.offering.NetworkOffering.Availability; import com.cloud.offerings.NetworkOfferingVO; import com.cloud.utils.db.DB; import com.cloud.utils.db.GenericDaoBase; +import com.cloud.utils.db.GenericSearchBuilder; import com.cloud.utils.db.SearchBuilder; import com.cloud.utils.db.SearchCriteria; +import com.cloud.utils.db.SearchCriteria.Op; @Local(value=NetworkOfferingDao.class) @DB(txn=false) public class NetworkOfferingDaoImpl extends GenericDaoBase implements NetworkOfferingDao { @@ -42,6 +45,7 @@ public class NetworkOfferingDaoImpl extends GenericDaoBase SystemOfferingSearch; final SearchBuilder AvailabilitySearch; final SearchBuilder TrafficTypeGuestTypeSearch; + private final GenericSearchBuilder UpgradeSearch; protected NetworkOfferingDaoImpl() { super(); @@ -65,6 +69,16 @@ public class NetworkOfferingDaoImpl extends GenericDaoBase getOfferingIdsToUpgradeFrom(NetworkOffering originalOffering) { + SearchCriteria sc = UpgradeSearch.create(); + //exclude original offering + sc.addAnd("id", SearchCriteria.Op.NEQ, originalOffering.getId()); + + //list only non-system offerings + sc.addAnd("systemOnly", SearchCriteria.Op.EQ, false); + + //security group property should be the same + sc.addAnd("securityGroupEnabled", SearchCriteria.Op.EQ, originalOffering.isSecurityGroupEnabled()); + + //Type of the network should be the same + sc.addAnd("type", SearchCriteria.Op.EQ, originalOffering.getType()); + + //Traffic types should be the same + sc.addAnd("trafficType", SearchCriteria.Op.EQ, originalOffering.getTrafficType()); + + sc.addAnd("state", SearchCriteria.Op.EQ, NetworkOffering.State.Enabled); + + return customSearch(sc, null); + } } diff --git a/server/src/com/cloud/server/ManagementServerImpl.java b/server/src/com/cloud/server/ManagementServerImpl.java index 59793e77eef..ff5e7ea8406 100755 --- a/server/src/com/cloud/server/ManagementServerImpl.java +++ b/server/src/com/cloud/server/ManagementServerImpl.java @@ -768,11 +768,8 @@ public class ManagementServerImpl implements ManagementServer { if ((vmInstance == null) || (vmInstance.getRemoved() != null)) { throw new InvalidParameterValueException("unable to find a virtual machine with id " + vmId); } - if ((caller != null) && !isAdmin(caller.getType())) { - if (caller.getId() != vmInstance.getAccountId()) { - throw new PermissionDeniedException("unable to find a virtual machine with id " + vmId + " for this account"); - } - } + + _accountMgr.checkAccess(caller, null, vmInstance); ServiceOfferingVO offering = _offeringsDao.findByIdIncludingRemoved(vmInstance.getServiceOfferingId()); sc.addAnd("id", SearchCriteria.Op.NEQ, offering.getId()); From 75c8e33226982ff33d22883f550b2eab4a5d97a9 Mon Sep 17 00:00:00 2001 From: alena Date: Mon, 24 Oct 2011 17:05:00 -0700 Subject: [PATCH 023/159] Removed guestIpType from network/networkOffering --- api/src/com/cloud/api/ApiConstants.java | 1 - .../commands/CreateNetworkOfferingCmd.java | 20 +----- .../api/commands/ListNetworkOfferingsCmd.java | 14 ++--- .../api/response/NetworkOfferingResponse.java | 7 --- .../com/cloud/api/response/NicResponse.java | 62 +++---------------- api/src/com/cloud/network/Network.java | 9 --- api/src/com/cloud/network/NetworkProfile.java | 8 --- .../com/cloud/offering/NetworkOffering.java | 4 -- .../cloud/event/dao/UsageEventDaoImpl.java | 4 +- .../src/com/cloud/api/ApiResponseHelper.java | 8 --- .../ConfigurationManagerImpl.java | 23 +++---- .../migration/Db20to21MigrationUtil.java | 13 ++-- .../cloud/migration/ServiceOffering20VO.java | 37 +++++------ .../cloud/migration/ServiceOffering21VO.java | 34 ++++------ .../ExternalNetworkDeviceManagerImpl.java | 2 +- .../src/com/cloud/network/NetworkManager.java | 3 +- .../com/cloud/network/NetworkManagerImpl.java | 50 +++++++-------- .../network/NetworkUsageManagerImpl.java | 5 +- server/src/com/cloud/network/NetworkVO.java | 20 ++---- .../src/com/cloud/network/dao/NetworkDao.java | 4 +- .../com/cloud/network/dao/NetworkDaoImpl.java | 12 +--- .../RedundantVirtualRouterElement.java | 6 +- .../network/guru/ControlNetworkGuru.java | 2 +- .../cloud/network/guru/DirectNetworkGuru.java | 2 +- .../guru/ExternalGuestNetworkGuru.java | 4 +- .../cloud/network/guru/GuestNetworkGuru.java | 11 ++-- .../network/guru/PodBasedNetworkGuru.java | 2 +- .../cloud/network/guru/PublicNetworkGuru.java | 2 +- .../lb/ElasticLoadBalancerManagerImpl.java | 4 +- .../VirtualNetworkApplianceManagerImpl.java | 3 +- .../cloud/offerings/NetworkOfferingVO.java | 15 ----- .../offerings/dao/NetworkOfferingDao.java | 4 +- .../offerings/dao/NetworkOfferingDaoImpl.java | 8 +-- .../cloud/server/ConfigurationServerImpl.java | 2 +- .../src/com/cloud/vm/UserVmManagerImpl.java | 7 +-- .../src/com/cloud/vm/dao/DomainRouterDao.java | 4 +- .../com/cloud/vm/dao/DomainRouterDaoImpl.java | 14 ++--- .../src/com/cloud/vm/dao/UserVmDaoImpl.java | 7 +-- setup/db/create-schema.sql | 2 - 39 files changed, 137 insertions(+), 302 deletions(-) diff --git a/api/src/com/cloud/api/ApiConstants.java b/api/src/com/cloud/api/ApiConstants.java index e754dfcdac4..ea2fd64111f 100755 --- a/api/src/com/cloud/api/ApiConstants.java +++ b/api/src/com/cloud/api/ApiConstants.java @@ -209,7 +209,6 @@ public class ApiConstants { public static final String IS_SYSTEM = "issystem"; public static final String AVAILABILITY = "availability"; public static final String NETWORKRATE = "networkrate"; - public static final String GUEST_IP_TYPE = "guestiptype"; public static final String HOST_TAGS = "hosttags"; public static final String SSH_KEYPAIR = "keypair"; public static final String HOST_CPU_CAPACITY = "hostcpucapacity"; diff --git a/api/src/com/cloud/api/commands/CreateNetworkOfferingCmd.java b/api/src/com/cloud/api/commands/CreateNetworkOfferingCmd.java index 5ff1018f685..2799cc6a05b 100644 --- a/api/src/com/cloud/api/commands/CreateNetworkOfferingCmd.java +++ b/api/src/com/cloud/api/commands/CreateNetworkOfferingCmd.java @@ -33,7 +33,6 @@ import com.cloud.api.Implementation; import com.cloud.api.Parameter; import com.cloud.api.ServerApiException; import com.cloud.api.response.NetworkOfferingResponse; -import com.cloud.network.Network.GuestIpType; import com.cloud.offering.NetworkOffering; import com.cloud.offering.NetworkOffering.Availability; import com.cloud.user.Account; @@ -56,11 +55,6 @@ public class CreateNetworkOfferingCmd extends BaseCmd { @Parameter(name=ApiConstants.TRAFFIC_TYPE, type=CommandType.STRING, required=true, description="the traffic type for the network offering, supported types are Public, Management, Control, Guest, Vlan or Storage.") private String traffictype; - @Deprecated - //this parameter is deprecated, we have to use "type" parameter instead - @Parameter(name=ApiConstants.GUEST_IP_TYPE, type=CommandType.STRING, description="the guest ip type for the network offering, supported types are Direct and Virtual.") - private String guestIpType; - @Parameter(name=ApiConstants.MAX_CONNECTIONS, type=CommandType.INTEGER, description="maximum number of concurrent connections supported by the network offering") private Integer maxConnections; @@ -186,19 +180,7 @@ public class CreateNetworkOfferingCmd extends BaseCmd { } public String getType() { - if (type != null) { - return type; - } - - if (guestIpType != null) { - // Verify guest ip type - for (GuestIpType gType : GuestIpType.values()) { - if (gType.name().equalsIgnoreCase(guestIpType)) { - return guestIpType; - } - } - } - return null; + return type; } public Map> getServiceProviders() { diff --git a/api/src/com/cloud/api/commands/ListNetworkOfferingsCmd.java b/api/src/com/cloud/api/commands/ListNetworkOfferingsCmd.java index a1cefb5a70a..1fcd3a4de35 100644 --- a/api/src/com/cloud/api/commands/ListNetworkOfferingsCmd.java +++ b/api/src/com/cloud/api/commands/ListNetworkOfferingsCmd.java @@ -65,9 +65,6 @@ public class ListNetworkOfferingsCmd extends BaseListCmd { @Parameter(name=ApiConstants.AVAILABILITY, type=CommandType.STRING, description="the availability of network offering. Default value is Required") private String availability; - @Parameter(name=ApiConstants.GUEST_IP_TYPE, type=CommandType.STRING, description="the guest ip type for the network offering, supported types are Direct and Virtual.") - private String guestIpType; - @Parameter(name=ApiConstants.ZONE_ID, type=CommandType.LONG, description="list netowrk offerings available for network creation in specific zone") private Long zoneId; @@ -79,6 +76,9 @@ public class ListNetworkOfferingsCmd extends BaseListCmd { @Parameter(name=ApiConstants.NETWORK_ID, type=CommandType.LONG, description="the ID of the network. Pass this in if you want to see the available network offering that a network can be changed to.") private Long networkId; + + @Parameter(name=ApiConstants.TYPE, type=CommandType.STRING, description="list network offerings by type: Shared or Isolated") + private String type; ///////////////////////////////////////////////////// /////////////////// Accessors /////////////////////// @@ -116,10 +116,6 @@ public class ListNetworkOfferingsCmd extends BaseListCmd { return availability; } - public String getGuestIpType() { - return guestIpType; - } - public Long getZoneId() { return zoneId; } @@ -136,6 +132,10 @@ public class ListNetworkOfferingsCmd extends BaseListCmd { return networkId; } + public String getType() { + return type; + } + ///////////////////////////////////////////////////// /////////////// API Implementation/////////////////// ///////////////////////////////////////////////////// diff --git a/api/src/com/cloud/api/response/NetworkOfferingResponse.java b/api/src/com/cloud/api/response/NetworkOfferingResponse.java index 26b3833ee73..5e6f8505c94 100644 --- a/api/src/com/cloud/api/response/NetworkOfferingResponse.java +++ b/api/src/com/cloud/api/response/NetworkOfferingResponse.java @@ -59,9 +59,6 @@ public class NetworkOfferingResponse extends BaseResponse{ @SerializedName(ApiConstants.AVAILABILITY) @Param(description="availability of the network offering") private String availability; - @SerializedName(ApiConstants.GUEST_IP_TYPE) @Param(description="guest ip type of the network offering") - private String guestIpType; - @SerializedName(ApiConstants.NETWORKRATE) @Param(description="data transfer rate in megabits per second allowed.") private Integer networkRate; @@ -125,10 +122,6 @@ public class NetworkOfferingResponse extends BaseResponse{ this.networkRate = networkRate; } - public void setGuestIpType(String guestIpType) { - this.guestIpType = guestIpType; - } - public void setIsSecurityGroupEnabled(Boolean isSecurityGroupEnabled) { this.isSecurityGroupEnabled = isSecurityGroupEnabled; } diff --git a/api/src/com/cloud/api/response/NicResponse.java b/api/src/com/cloud/api/response/NicResponse.java index 9e73aaa60fb..49e8aa07ec6 100755 --- a/api/src/com/cloud/api/response/NicResponse.java +++ b/api/src/com/cloud/api/response/NicResponse.java @@ -17,24 +17,26 @@ */ package com.cloud.api.response; +import com.cloud.api.ApiConstants; import com.cloud.serializer.Param; import com.google.gson.annotations.SerializedName; +@SuppressWarnings("unused") public class NicResponse extends BaseResponse { - @SerializedName("id") @Param(description="the ID of the nic") + @SerializedName(ApiConstants.ID) @Param(description="the ID of the nic") private Long id; - @SerializedName("networkid") @Param(description="the ID of the corresponding network") + @SerializedName(ApiConstants.NETWORK_ID) @Param(description="the ID of the corresponding network") private Long networkid; - @SerializedName("netmask") @Param(description="the netmask of the nic") + @SerializedName(ApiConstants.NETMASK) @Param(description="the netmask of the nic") private String netmask; - @SerializedName("gateway") @Param(description="the gateway of the nic") + @SerializedName(ApiConstants.GATEWAY) @Param(description="the gateway of the nic") private String gateway; - @SerializedName("ipaddress") @Param(description="the ip address of the nic") + @SerializedName(ApiConstants.IP_ADDRESS) @Param(description="the ip address of the nic") private String ipaddress; @SerializedName("isolationuri") @Param(description="the isolation uri of the nic") @@ -43,102 +45,58 @@ public class NicResponse extends BaseResponse { @SerializedName("broadcasturi") @Param(description="the broadcast uri of the nic") private String broadcastUri; - @SerializedName("traffictype") @Param(description="the traffic type of the nic") + @SerializedName(ApiConstants.TRAFFIC_TYPE) @Param(description="the traffic type of the nic") private String trafficType; - @SerializedName("type") @Param(description="the type of the nic") + @SerializedName(ApiConstants.TYPE) @Param(description="the type of the nic") private String type; - @SerializedName("isdefault") @Param(description="true if nic is default, false otherwise") + @SerializedName(ApiConstants.IS_DEFAULT) @Param(description="true if nic is default, false otherwise") private Boolean isDefault; @SerializedName("macaddress") @Param(description="true if nic is default, false otherwise") private String macAddress; - public Long getId() { - return id; - } - public void setId(Long id) { this.id = id; } - public Long getNetworkid() { - return networkid; - } - public void setNetworkid(Long networkid) { this.networkid = networkid; } - public String getNetmask() { - return netmask; - } - public void setNetmask(String netmask) { this.netmask = netmask; } - public String getGateway() { - return gateway; - } - public void setGateway(String gateway) { this.gateway = gateway; } - public String getIpaddress() { - return ipaddress; - } - public void setIpaddress(String ipaddress) { this.ipaddress = ipaddress; } - public String getIsolationUri() { - return isolationUri; - } - public void setIsolationUri(String isolationUri) { this.isolationUri = isolationUri; } - public String getBroadcastUri() { - return broadcastUri; - } - public void setBroadcastUri(String broadcastUri) { this.broadcastUri = broadcastUri; } - public String getTrafficType() { - return trafficType; - } - public void setTrafficType(String trafficType) { this.trafficType = trafficType; } - public String getType() { - return type; - } - public void setType(String type) { this.type = type; } - public Boolean getIsDefault() { - return isDefault; - } - public void setIsDefault(Boolean isDefault) { this.isDefault = isDefault; } - public String getMacAddress() { - return macAddress; - } - public void setMacAddress(String macAddress) { this.macAddress = macAddress; } diff --git a/api/src/com/cloud/network/Network.java b/api/src/com/cloud/network/Network.java index 99f3f18250c..e020d2a4c75 100644 --- a/api/src/com/cloud/network/Network.java +++ b/api/src/com/cloud/network/Network.java @@ -38,12 +38,6 @@ import com.cloud.utils.fsm.StateMachine; * owned by an account. */ public interface Network extends ControlledEntity { - - @Deprecated - public enum GuestIpType { - Virtual, - Direct, - } public enum Type { Shared, @@ -260,9 +254,6 @@ public interface Network extends ControlledEntity { URI getBroadcastUri(); - @Deprecated - GuestIpType getGuestType(); - String getDisplayText(); String getReservationId(); diff --git a/api/src/com/cloud/network/NetworkProfile.java b/api/src/com/cloud/network/NetworkProfile.java index b6f85994440..be243997683 100644 --- a/api/src/com/cloud/network/NetworkProfile.java +++ b/api/src/com/cloud/network/NetworkProfile.java @@ -50,8 +50,6 @@ public class NetworkProfile implements Network { private boolean isSecurityGroupEnabled; private List tags; private Network.Type type; - @Deprecated - private GuestIpType guestIpType; private boolean isShared; private Long physicalNetworkId; @@ -76,7 +74,6 @@ public class NetworkProfile implements Network { this.domainId = network.getDomainId(); this.isSecurityGroupEnabled = network.isSecurityGroupEnabled(); this.type = network.getType(); - this.guestIpType = network.getGuestType(); this.isShared = network.getIsShared(); this.physicalNetworkId = network.getPhysicalNetworkId(); } @@ -171,11 +168,6 @@ public class NetworkProfile implements Network { return related; } - @Override - public GuestIpType getGuestType() { - return guestIpType; - } - @Override public String getDisplayText() { return displayText; diff --git a/api/src/com/cloud/offering/NetworkOffering.java b/api/src/com/cloud/offering/NetworkOffering.java index 530e8ac5016..8a5fe3a9195 100644 --- a/api/src/com/cloud/offering/NetworkOffering.java +++ b/api/src/com/cloud/offering/NetworkOffering.java @@ -17,7 +17,6 @@ */ package com.cloud.offering; -import com.cloud.network.Network.GuestIpType; import com.cloud.network.Network.Type; import com.cloud.network.Networks.TrafficType; @@ -88,9 +87,6 @@ public interface NetworkOffering { Availability getAvailability(); boolean isSharedSourceNatService(); - - @Deprecated - GuestIpType getGuestType(); String getUniqueName(); diff --git a/core/src/com/cloud/event/dao/UsageEventDaoImpl.java b/core/src/com/cloud/event/dao/UsageEventDaoImpl.java index ebc04b97981..99aa5177272 100644 --- a/core/src/com/cloud/event/dao/UsageEventDaoImpl.java +++ b/core/src/com/cloud/event/dao/UsageEventDaoImpl.java @@ -28,10 +28,10 @@ import javax.ejb.Local; import org.apache.log4j.Logger; +import com.cloud.dc.Vlan; import com.cloud.event.EventTypes; import com.cloud.event.UsageEventVO; import com.cloud.exception.UsageServerException; -import com.cloud.network.Network.GuestIpType; import com.cloud.utils.DateUtil; import com.cloud.utils.db.DB; import com.cloud.utils.db.Filter; @@ -180,7 +180,7 @@ public class UsageEventDaoImpl extends GenericDaoBase implem sc.setParameters("assignEvent", EventTypes.EVENT_NET_IP_ASSIGN); sc.setParameters("releaseEvent", EventTypes.EVENT_NET_IP_RELEASE); sc.setParameters("zoneid", zoneId); - sc.setParameters("networktype", GuestIpType.Direct.toString()); + sc.setParameters("networktype", Vlan.VlanType.DirectAttached.toString()); return listBy(sc, filter); } diff --git a/server/src/com/cloud/api/ApiResponseHelper.java b/server/src/com/cloud/api/ApiResponseHelper.java index 8bfd99dc72f..d80d375eeb7 100755 --- a/server/src/com/cloud/api/ApiResponseHelper.java +++ b/server/src/com/cloud/api/ApiResponseHelper.java @@ -2113,10 +2113,6 @@ public class ApiResponseHelper implements ResponseGenerator { if (offering.getType() != null) { response.setType(offering.getType().toString()); } - - if (offering.getGuestType() != null) { - response.setGuestIpType(offering.getGuestType().toString()); - } response.setState(offering.getState().name()); @@ -2158,10 +2154,6 @@ public class ApiResponseHelper implements ResponseGenerator { response.setTrafficType(network.getTrafficType().name()); } - if (network.getGuestType() != null) { - response.setType(network.getGuestType().name()); - } - // get start ip and end ip of corresponding vlan List vlan = ApiDBUtils.listVlanByNetworkId(network.getId()); if (vlan != null && !vlan.isEmpty()) { diff --git a/server/src/com/cloud/configuration/ConfigurationManagerImpl.java b/server/src/com/cloud/configuration/ConfigurationManagerImpl.java index 52c262d11d1..9110515ca02 100755 --- a/server/src/com/cloud/configuration/ConfigurationManagerImpl.java +++ b/server/src/com/cloud/configuration/ConfigurationManagerImpl.java @@ -96,7 +96,6 @@ import com.cloud.exception.ResourceUnavailableException; import com.cloud.host.dao.HostDetailsDao; import com.cloud.hypervisor.Hypervisor.HypervisorType; import com.cloud.network.Network; -import com.cloud.network.Network.GuestIpType; import com.cloud.network.Network.Provider; import com.cloud.network.Network.Service; import com.cloud.network.NetworkManager; @@ -1395,20 +1394,17 @@ public class ConfigurationManagerImpl implements ConfigurationManager, Configura } else { continue; } - } /*else if (offering.getTrafficType() == TrafficType.Guest) { + } else if (offering.getTrafficType() == TrafficType.Guest) { if (zone.getNetworkType() == NetworkType.Basic) { isNetworkDefault = true; broadcastDomainType = BroadcastDomainType.Native; - userNetwork.setSecurityGroupEnabled(isSecurityGroupEnabled); - } else if (offering.getGuestType() == GuestIpType.Direct && isSecurityGroupEnabled) { - isNetworkDefault = true; - userNetwork.setSecurityGroupEnabled(isSecurityGroupEnabled); + userNetwork.setSecurityGroupEnabled(offering.isSecurityGroupEnabled()); } else { continue; } networkDomain = "cs" + Long.toHexString(Account.ACCOUNT_ID_SYSTEM) + _networkMgr.getGlobalGuestDomainSuffix(); - }*/ + } userNetwork.setBroadcastDomainType(broadcastDomainType); userNetwork.setNetworkDomain(networkDomain); _networkMgr.setupNetwork(systemAccount, offering, userNetwork, plan, null, null, isNetworkDefault, false, null, null, true); @@ -2885,12 +2881,12 @@ public class ConfigurationManagerImpl implements ConfigurationManager, Configura Object specifyVlan = cmd.getSpecifyVlan(); Object isShared = cmd.getIsShared(); Object availability = cmd.getAvailability(); - Object guestIpType = cmd.getGuestIpType(); Object sgEnabled = cmd.getSecurityGroupEnabled(); Object state = cmd.getState(); Long zoneId = cmd.getZoneId(); DataCenter zone = null; Long networkId = cmd.getNetworkId(); + String type = cmd.getType(); if (zoneId != null) { zone = getZone(zoneId); @@ -2906,13 +2902,14 @@ public class ConfigurationManagerImpl implements ConfigurationManager, Configura sc.addAnd("name", SearchCriteria.Op.SC, ssc); } - if (guestIpType != null) { - sc.addAnd("guestType", SearchCriteria.Op.EQ, guestIpType); - } - if (name != null) { sc.addAnd("name", SearchCriteria.Op.LIKE, "%" + name + "%"); } + + if (type != null) { + sc.addAnd("type", SearchCriteria.Op.EQ, type); + } + if (displayText != null) { sc.addAnd("displayText", SearchCriteria.Op.LIKE, "%" + displayText + "%"); } @@ -2949,8 +2946,6 @@ public class ConfigurationManagerImpl implements ConfigurationManager, Configura if (zone.getNetworkType() == NetworkType.Basic) { // return empty list as we don't allow to create networks in basic zone, and shouldn't display networkOfferings return new ArrayList(); - } else if (zone.isSecurityGroupEnabled()) { - sc.addAnd("guestType", SearchCriteria.Op.EQ, GuestIpType.Direct); } } diff --git a/server/src/com/cloud/migration/Db20to21MigrationUtil.java b/server/src/com/cloud/migration/Db20to21MigrationUtil.java index e3b752dee2a..014f2a32c3d 100644 --- a/server/src/com/cloud/migration/Db20to21MigrationUtil.java +++ b/server/src/com/cloud/migration/Db20to21MigrationUtil.java @@ -56,7 +56,6 @@ import com.cloud.host.Host; import com.cloud.host.HostVO; import com.cloud.host.dao.HostDao; import com.cloud.migration.DiskOffering21VO.Type; -import com.cloud.network.Network; import com.cloud.storage.Storage.StoragePoolType; import com.cloud.storage.StoragePoolVO; import com.cloud.storage.Volume; @@ -305,8 +304,8 @@ public class Db20to21MigrationUtil { List oldServiceOfferings = _serviceOffering20Dao.listAllIncludingRemoved(); for(ServiceOffering20VO so20 : oldServiceOfferings) { ServiceOffering21VO so21 = new ServiceOffering21VO(so20.getName(), so20.getCpu(), so20.getRamSize(), so20.getSpeed(), so20.getRateMbps(), - so20.getMulticastRateMbps(), so20.getOfferHA(), so20.getDisplayText(), so20.getGuestIpType(), - so20.getUseLocalStorage(), false, null); + so20.getMulticastRateMbps(), so20.getOfferHA(), so20.getDisplayText(), so20.getUseLocalStorage(), + false, null); so21.setId(seq++); so21.setDiskSize(0); so21 = _serviceOffering21Dao.persist(so21); @@ -324,8 +323,8 @@ public class Db20to21MigrationUtil { _configDao.getValue(Config.ConsoleProxyRamSize.key()), ConsoleProxyManager.DEFAULT_PROXY_VM_RAMSIZE); ServiceOffering21VO soConsoleProxy = new ServiceOffering21VO("Fake Offering For DomP", 1, - proxyRamSize, 0, 0, 0, false, null, Network.GuestIpType.Virtual, - useLocalStorage, true, null); + proxyRamSize, 0, 0, 0, false, null, useLocalStorage, + true, null); soConsoleProxy.setId(seq++); soConsoleProxy.setUniqueName("Cloud.com-ConsoleProxy"); soConsoleProxy = _serviceOffering21Dao.persist(soConsoleProxy); @@ -335,7 +334,7 @@ public class Db20to21MigrationUtil { _configDao.getValue(Config.SecStorageVmRamSize.key()), SecondaryStorageVmManager.DEFAULT_SS_VM_RAMSIZE); ServiceOffering21VO soSecondaryVm = new ServiceOffering21VO("Fake Offering For Secondary Storage VM", 1, - secStorageVmRamSize, 0, 0, 0, false, null, Network.GuestIpType.Virtual, useLocalStorage, true, null); + secStorageVmRamSize, 0, 0, 0, false, null, useLocalStorage, true, null); soSecondaryVm.setId(seq++); soSecondaryVm.setUniqueName("Cloud.com-SecondaryStorage"); soSecondaryVm = _serviceOffering21Dao.persist(soSecondaryVm); @@ -343,7 +342,7 @@ public class Db20to21MigrationUtil { int routerRamSize = NumbersUtil.parseInt(_configDao.getValue("router.ram.size"), 128); ServiceOffering21VO soDomainRouter = new ServiceOffering21VO("Fake Offering For DomR", 1, - routerRamSize, 0, 0, 0, false, null, Network.GuestIpType.Virtual, useLocalStorage, true, null); + routerRamSize, 0, 0, 0, false, null, useLocalStorage, true, null); soDomainRouter.setId(seq++); soDomainRouter.setUniqueName("Cloud.Com-SoftwareRouter"); soDomainRouter = _serviceOffering21Dao.persist(soDomainRouter); diff --git a/server/src/com/cloud/migration/ServiceOffering20VO.java b/server/src/com/cloud/migration/ServiceOffering20VO.java index 32af408537e..2189dc12f22 100644 --- a/server/src/com/cloud/migration/ServiceOffering20VO.java +++ b/server/src/com/cloud/migration/ServiceOffering20VO.java @@ -18,19 +18,20 @@ package com.cloud.migration; -import java.util.Date; - -import javax.persistence.Column; -import javax.persistence.Entity; -import javax.persistence.EnumType; -import javax.persistence.Enumerated; -import javax.persistence.GeneratedValue; -import javax.persistence.GenerationType; -import javax.persistence.Id; -import javax.persistence.Table; - -import com.cloud.network.Network; -import com.cloud.utils.db.GenericDao; +import java.util.Date; + +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.EnumType; +import javax.persistence.Enumerated; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; +import javax.persistence.Table; + +import com.cloud.dc.Vlan; +import com.cloud.dc.Vlan.VlanType; +import com.cloud.utils.db.GenericDao; @Entity @Table(name="service_offering") @@ -69,7 +70,7 @@ public class ServiceOffering20VO { @Column(name="guest_ip_type") @Enumerated(EnumType.STRING) - private Network.GuestIpType guestIpType = Network.GuestIpType.Virtual; + private Vlan.VlanType guestIpType = Vlan.VlanType.VirtualNetwork; @Column(name="use_local_storage") private boolean useLocalStorage; @@ -84,10 +85,10 @@ public class ServiceOffering20VO { } public ServiceOffering20VO(Long id, String name, int cpu, int ramSize, int speed, int rateMbps, int multicastRateMbps, boolean offerHA, String displayText, boolean localStorageRequired) { - this(id, name, cpu, ramSize, speed, rateMbps, multicastRateMbps, offerHA, displayText, Network.GuestIpType.Virtual, localStorageRequired); + this(id, name, cpu, ramSize, speed, rateMbps, multicastRateMbps, offerHA, displayText, Vlan.VlanType.VirtualNetwork, localStorageRequired); } - public ServiceOffering20VO(Long id, String name, int cpu, int ramSize, int speed, int rateMbps, int multicastRateMbps, boolean offerHA, String displayText, Network.GuestIpType guestIpType, boolean useLocalStorage) { + public ServiceOffering20VO(Long id, String name, int cpu, int ramSize, int speed, int rateMbps, int multicastRateMbps, boolean offerHA, String displayText, VlanType guestIpType, boolean useLocalStorage) { this.id = id; this.name = name; this.cpu = cpu; @@ -185,11 +186,11 @@ public class ServiceOffering20VO { return multicastRateMbps; } - public void setGuestIpType(Network.GuestIpType guestIpType) { + public void setGuestIpType(Vlan.VlanType guestIpType) { this.guestIpType = guestIpType; } - public Network.GuestIpType getGuestIpType() { + public Vlan.VlanType getGuestIpType() { return guestIpType; } diff --git a/server/src/com/cloud/migration/ServiceOffering21VO.java b/server/src/com/cloud/migration/ServiceOffering21VO.java index 37b34fc0c60..345d3929caf 100644 --- a/server/src/com/cloud/migration/ServiceOffering21VO.java +++ b/server/src/com/cloud/migration/ServiceOffering21VO.java @@ -18,17 +18,14 @@ package com.cloud.migration; -import javax.persistence.Column; -import javax.persistence.DiscriminatorValue; -import javax.persistence.Entity; -import javax.persistence.EnumType; -import javax.persistence.Enumerated; -import javax.persistence.PrimaryKeyJoinColumn; -import javax.persistence.Table; -import javax.persistence.Transient; - -import com.cloud.network.Network; -import com.cloud.offering.ServiceOffering; +import javax.persistence.Column; +import javax.persistence.DiscriminatorValue; +import javax.persistence.Entity; +import javax.persistence.PrimaryKeyJoinColumn; +import javax.persistence.Table; +import javax.persistence.Transient; + +import com.cloud.offering.ServiceOffering; @Entity @Table(name="service_offering_21") @@ -53,10 +50,6 @@ public class ServiceOffering21VO extends DiskOffering21VO implements ServiceOffe @Column(name="ha_enabled") private boolean offerHA; - @Column(name="guest_ip_type") - @Enumerated(EnumType.STRING) - private Network.GuestIpType guestIpType; - @Column(name="host_tag") private String hostTag; @@ -64,7 +57,7 @@ public class ServiceOffering21VO extends DiskOffering21VO implements ServiceOffe super(); } - public ServiceOffering21VO(String name, int cpu, int ramSize, int speed, Integer rateMbps, Integer multicastRateMbps, boolean offerHA, String displayText, Network.GuestIpType guestIpType, boolean useLocalStorage, boolean recreatable, String tags) { + public ServiceOffering21VO(String name, int cpu, int ramSize, int speed, Integer rateMbps, Integer multicastRateMbps, boolean offerHA, String displayText, boolean useLocalStorage, boolean recreatable, String tags) { super(name, displayText, false, tags, recreatable, useLocalStorage); this.cpu = cpu; this.ramSize = ramSize; @@ -72,11 +65,10 @@ public class ServiceOffering21VO extends DiskOffering21VO implements ServiceOffe this.rateMbps = rateMbps; this.multicastRateMbps = multicastRateMbps; this.offerHA = offerHA; - this.guestIpType = guestIpType; } - public ServiceOffering21VO(String name, int cpu, int ramSize, int speed, Integer rateMbps, Integer multicastRateMbps, boolean offerHA, String displayText, Network.GuestIpType guestIpType, boolean useLocalStorage, boolean recreatable, String tags, String hostTag) { - this(name, cpu, ramSize, speed, rateMbps, multicastRateMbps, offerHA, displayText, guestIpType, useLocalStorage, recreatable, tags); + public ServiceOffering21VO(String name, int cpu, int ramSize, int speed, Integer rateMbps, Integer multicastRateMbps, boolean offerHA, String displayText, boolean useLocalStorage, boolean recreatable, String tags, String hostTag) { + this(name, cpu, ramSize, speed, rateMbps, multicastRateMbps, offerHA, displayText, useLocalStorage, recreatable, tags); this.hostTag = hostTag; } @@ -151,10 +143,6 @@ public class ServiceOffering21VO extends DiskOffering21VO implements ServiceOffe return multicastRateMbps; } - public void setGuestIpType(Network.GuestIpType guestIpType) { - this.guestIpType = guestIpType; - } - public String gethypervisorType() { return null; } diff --git a/server/src/com/cloud/network/ExternalNetworkDeviceManagerImpl.java b/server/src/com/cloud/network/ExternalNetworkDeviceManagerImpl.java index 83bfa1d1359..e3688fae8cb 100644 --- a/server/src/com/cloud/network/ExternalNetworkDeviceManagerImpl.java +++ b/server/src/com/cloud/network/ExternalNetworkDeviceManagerImpl.java @@ -1204,7 +1204,7 @@ public class ExternalNetworkDeviceManagerImpl implements ExternalNetworkDeviceMa try { txn.start(); - List networksForAccount = _networkDao.listBy(accountId, zoneId, Network.GuestIpType.Virtual); + List networksForAccount = _networkDao.listBy(accountId, zoneId, Network.Type.Isolated); for (NetworkVO network : networksForAccount) { String networkErrorMsg = accountErrorMsg + ", network ID = " + network.getId(); diff --git a/server/src/com/cloud/network/NetworkManager.java b/server/src/com/cloud/network/NetworkManager.java index 5fc88d1f594..3f2c9951739 100644 --- a/server/src/com/cloud/network/NetworkManager.java +++ b/server/src/com/cloud/network/NetworkManager.java @@ -29,7 +29,6 @@ import com.cloud.exception.InsufficientAddressCapacityException; import com.cloud.exception.InsufficientCapacityException; import com.cloud.exception.ResourceUnavailableException; import com.cloud.network.Network.Capability; -import com.cloud.network.Network.GuestIpType; import com.cloud.network.Network.Provider; import com.cloud.network.Network.Service; import com.cloud.network.Networks.TrafficType; @@ -203,7 +202,7 @@ public interface NetworkManager extends NetworkService { String getIpOfNetworkElementInVirtualNetwork(long accountId, long dataCenterId); - List listNetworksForAccount(long accountId, long zoneId, GuestIpType guestType, Boolean isDefault); + List listNetworksForAccount(long accountId, long zoneId, Network.Type type, Boolean isDefault); IPAddressVO markIpAsUnavailable(long addrId); diff --git a/server/src/com/cloud/network/NetworkManagerImpl.java b/server/src/com/cloud/network/NetworkManagerImpl.java index 90f9d51c1ed..142db9a8bac 100755 --- a/server/src/com/cloud/network/NetworkManagerImpl.java +++ b/server/src/com/cloud/network/NetworkManagerImpl.java @@ -90,7 +90,6 @@ import com.cloud.exception.ResourceUnavailableException; import com.cloud.exception.UnsupportedServiceException; import com.cloud.network.IpAddress.State; import com.cloud.network.Network.Capability; -import com.cloud.network.Network.GuestIpType; import com.cloud.network.Network.Provider; import com.cloud.network.Network.Service; import com.cloud.network.Networks.AddressFormat; @@ -367,12 +366,10 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag // Save usage event if (owner.getAccountId() != Account.ACCOUNT_ID_SYSTEM) { - long networkId = addr.getSourceNetworkId(); - NetworkVO network = _networksDao.findByIdIncludingRemoved(networkId); - String guestType = ""; - if( (network != null) && (network.getGuestType() != null) ){ - guestType = network.getGuestType().toString(); - } + VlanVO vlan = _vlanDao.findById(addr.getVlanId()); + + String guestType = vlan.getVlanType().toString(); + UsageEventVO usageEvent = new UsageEventVO(EventTypes.EVENT_NET_IP_ASSIGN, owner.getId(), addr.getDataCenterId(), addr.getId(), addr.getAddress().toString(), isSourceNat, guestType); _usageEventDao.persist(usageEvent); // don't increment resource count for direct ip addresses @@ -556,7 +553,7 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag @Override public List getVirtualNetworksOwnedByAccountInZone(long zoneId, Account owner) { - return _networksDao.listBy(owner.getId(), zoneId, GuestIpType.Virtual); + return _networksDao.listBy(owner.getId(), zoneId, Network.Type.Isolated); } @Override @@ -1017,7 +1014,7 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag NetworkVO vo = new NetworkVO(id, network, offering.getId(), guru.getName(), owner.getDomainId(), owner.getId(), related, name, displayText, isDefault, predefined.isSecurityGroupEnabled(), (domainId != null), predefined.getNetworkDomain(), offering.getType(), isShared, plan.getDataCenterId(), plan.getPhysicalNetworkId()); vo.setTags(tags); - networks.add(_networksDao.persist(vo, vo.getGuestType() != null)); + networks.add(_networksDao.persist(vo, vo.getType() == Network.Type.Isolated)); if (domainId != null) { _networksDao.addDomainToNetwork(id, domainId); @@ -1691,10 +1688,10 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag cidr = NetUtils.ipAndNetMaskToCidr(gateway, netmask); } - // Regular user can create guest virtual network only - if (caller.getType() == Account.ACCOUNT_TYPE_NORMAL && (networkOffering.getTrafficType() != TrafficType.Guest || networkOffering.getGuestType() != GuestIpType.Virtual)) { - throw new InvalidParameterValueException("Regular user can create a network only from the network offering having traffic type " + TrafficType.Guest + " and Guest Ip type " - + GuestIpType.Virtual); + // Regular user can create Guest Isolated network only + if (caller.getType() == Account.ACCOUNT_TYPE_NORMAL && (networkOffering.getTrafficType() != TrafficType.Guest || networkOffering.getType() != Network.Type.Isolated)) { + throw new InvalidParameterValueException("Regular user can create a network only from the network offering having traffic type " + TrafficType.Guest + " and network type " + + Network.Type.Isolated); } // Don't allow to specify cidr if the caller is a regular user @@ -1781,9 +1778,9 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag throw new InvalidParameterValueException("Can't specify vlan because network offering doesn't support it"); } - // Don't allow to create guest virtual network with Vlan specified - if (networkOffering.getGuestType() == GuestIpType.Virtual && vlanId != null) { - throw new InvalidParameterValueException("Can't specify vlan when create network with Guest IP Type " + GuestIpType.Virtual); + // Don't allow to create guest isolated network with Vlan specified + if (networkOffering.getType() == Network.Type.Isolated && vlanId != null) { + throw new InvalidParameterValueException("Can't specify vlan when create " + Network.Type.Isolated + " network"); } // If networkDomain is not specified, take it from the global configuration @@ -1825,12 +1822,12 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag // Cidr for Direct network can't be NULL - 2.2.x limitation, remove after we introduce support for multiple ip ranges // with different Cidrs for the same Shared network - if (cidr == null && networkOffering.getTrafficType() == TrafficType.Guest && networkOffering.getGuestType() == GuestIpType.Direct) { + if (cidr == null && networkOffering.getTrafficType() == TrafficType.Guest && networkOffering.getType() == Network.Type.Shared) { throw new InvalidParameterValueException("StartIp/endIp/gateway/netmask are required for Direct network creation"); } - // Check if cidr is RFC1918 compliant if the network is Guest Virtual - if (cidr != null && networkOffering.getGuestType() == GuestIpType.Virtual && networkOffering.getTrafficType() == TrafficType.Guest) { + // Check if cidr is RFC1918 compliant if the network is Guest Isolated + if (cidr != null && networkOffering.getType() == Network.Type.Isolated && networkOffering.getTrafficType() == TrafficType.Guest) { if (!NetUtils.validateGuestCidr(cidr)) { throw new InvalidParameterValueException("Virtual Guest Cidr " + cidr + " is not RFC1918 compliant"); } @@ -2976,7 +2973,7 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag @Override public String getIpOfNetworkElementInVirtualNetwork(long accountId, long dataCenterId) { - List virtualNetworks = _networksDao.listBy(accountId, dataCenterId, GuestIpType.Virtual); + List virtualNetworks = _networksDao.listBy(accountId, dataCenterId, Network.Type.Isolated); if (virtualNetworks.isEmpty()) { s_logger.trace("Unable to find default Virtual network account id=" + accountId); @@ -2996,7 +2993,7 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag } @Override - public List listNetworksForAccount(long accountId, long zoneId, GuestIpType guestType, Boolean isDefault) { + public List listNetworksForAccount(long accountId, long zoneId, Network.Type type, Boolean isDefault) { List accountNetworks = new ArrayList(); List zoneNetworks = _networksDao.listByZone(zoneId); @@ -3004,7 +3001,7 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag NetworkOfferingVO no = _networkOfferingDao.findById(network.getNetworkOfferingId()); if (!no.isSystemOnly()) { if (network.getType() == Network.Type.Shared || !_networksDao.listBy(accountId, network.getId()).isEmpty()) { - if ((guestType == null || guestType == network.getGuestType()) && (isDefault == null || isDefault.booleanValue() == network.isDefault)) { + if ((type == null || type == network.getType()) && (isDefault == null || isDefault.booleanValue() == network.isDefault)) { accountNetworks.add(network); } } @@ -3038,10 +3035,9 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag // Save usage event if (ip.getAccountId() != Account.ACCOUNT_ID_SYSTEM) { NetworkVO network = _networksDao.findByIdIncludingRemoved(ip.getSourceNetworkId()); - String guestType = ""; - if( (network != null) && (network.getGuestType() != null)){ - guestType = network.getGuestType().toString(); - } + VlanVO vlan = _vlanDao.findById(ip.getVlanId()); + + String guestType = vlan.getVlanType().toString(); UsageEventVO usageEvent = new UsageEventVO(EventTypes.EVENT_NET_IP_RELEASE, ip.getAccountId(), ip.getDataCenterId(), addrId, ip.getAddress().addr(), isSourceNat, guestType); _usageEventDao.persist(usageEvent); @@ -3217,7 +3213,7 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag if (vm != null) { if (vm.getType() == Type.User && network.isDefault()) { isUserVmsDefaultNetwork = true; - } else if (vm.getType() == Type.DomainRouter && ((ntwkOff.getTrafficType() == TrafficType.Public && ntwkOff.getGuestType() == null) || (ntwkOff.getGuestType() != null && ntwkOff.getTrafficType() == TrafficType.Guest))) { + } else if (vm.getType() == Type.DomainRouter && (ntwkOff.getTrafficType() == TrafficType.Public || ntwkOff.getTrafficType() == TrafficType.Guest)) { isDomRGuestOrPublicNetwork = true; } } diff --git a/server/src/com/cloud/network/NetworkUsageManagerImpl.java b/server/src/com/cloud/network/NetworkUsageManagerImpl.java index d2a98f4caf5..664e9f7a8c1 100644 --- a/server/src/com/cloud/network/NetworkUsageManagerImpl.java +++ b/server/src/com/cloud/network/NetworkUsageManagerImpl.java @@ -62,7 +62,6 @@ import com.cloud.host.HostVO; import com.cloud.host.Status; import com.cloud.host.dao.HostDao; import com.cloud.host.dao.HostDetailsDao; -import com.cloud.network.Network.GuestIpType; import com.cloud.network.dao.IPAddressDao; import com.cloud.network.dao.NetworkDao; import com.cloud.network.resource.TrafficSentinelResource; @@ -215,7 +214,7 @@ public class NetworkUsageManagerImpl implements NetworkUsageManager { AllocatedIpSearch.and("allocated", AllocatedIpSearch.entity().getAllocatedTime(), Op.NNULL); AllocatedIpSearch.and("dc", AllocatedIpSearch.entity().getDataCenterId(), Op.EQ); SearchBuilder networkJoin = _networksDao.createSearchBuilder(); - networkJoin.and("guestType", networkJoin.entity().getGuestType(), Op.EQ); + networkJoin.and("type", networkJoin.entity().getType(), Op.EQ); AllocatedIpSearch.join("network", networkJoin, AllocatedIpSearch.entity().getSourceNetworkId(), networkJoin.entity().getId(), JoinBuilder.JoinType.INNER); AllocatedIpSearch.done(); @@ -243,7 +242,7 @@ public class NetworkUsageManagerImpl implements NetworkUsageManager { public List listAllocatedDirectIps(long zoneId) { SearchCriteria sc = AllocatedIpSearch.create(); sc.setParameters("dc", zoneId); - sc.setJoinParameters("network", "guestType", GuestIpType.Direct); + sc.setJoinParameters("network", "type", Network.Type.Shared); return _ipAddressDao.search(sc, null); } diff --git a/server/src/com/cloud/network/NetworkVO.java b/server/src/com/cloud/network/NetworkVO.java index 2af1f1a555e..9928ec673b9 100644 --- a/server/src/com/cloud/network/NetworkVO.java +++ b/server/src/com/cloud/network/NetworkVO.java @@ -66,10 +66,6 @@ public class NetworkVO implements Network { @Enumerated(value=EnumType.STRING) TrafficType trafficType; - @Deprecated - @Column(name="guest_type") - GuestIpType guestType; - @Column(name="name") String name; @@ -172,7 +168,7 @@ public class NetworkVO implements Network { * @param dataCenterId * @param physicalNetworkId TODO */ - public NetworkVO(TrafficType trafficType, GuestIpType guestType, Mode mode, BroadcastDomainType broadcastDomainType, long networkOfferingId, State state, long dataCenterId, Long physicalNetworkId) { + public NetworkVO(TrafficType trafficType, Mode mode, BroadcastDomainType broadcastDomainType, long networkOfferingId, State state, long dataCenterId, Long physicalNetworkId) { this.trafficType = trafficType; this.mode = mode; this.broadcastDomainType = broadcastDomainType; @@ -185,11 +181,10 @@ public class NetworkVO implements Network { this.state = state; } this.id = -1; - this.guestType = guestType; } public NetworkVO(long id, Network that, long offeringId, String guruName, long domainId, long accountId, long related, String name, String displayText, boolean isDefault, boolean isSecurityGroupEnabled, boolean isDomainSpecific, String networkDomain, Type type, boolean isShared, long dcId, Long physicalNetworkId) { - this(id, that.getTrafficType(), that.getGuestType(), that.getMode(), that.getBroadcastDomainType(), offeringId, domainId, accountId, related, name, displayText,isDefault, isDomainSpecific, networkDomain, type, isShared, dcId, physicalNetworkId); + this(id, that.getTrafficType(), that.getMode(), that.getBroadcastDomainType(), offeringId, domainId, accountId, related, name, displayText, isDefault,isDomainSpecific, networkDomain, type, isShared, dcId, physicalNetworkId); this.gateway = that.getGateway(); this.cidr = that.getCidr(); this.broadcastUri = that.getBroadcastUri(); @@ -208,7 +203,6 @@ public class NetworkVO implements Network { * @param mode * @param broadcastDomainType * @param networkOfferingId - * @param dataCenterId * @param domainId * @param accountId * @param name @@ -219,9 +213,10 @@ public class NetworkVO implements Network { * @param type TODO * @param isShared TODO * @param isShared + * @param dataCenterId */ - public NetworkVO(long id, TrafficType trafficType, GuestIpType guestType, Mode mode, BroadcastDomainType broadcastDomainType, long networkOfferingId, long domainId, long accountId, long related, String name, String displayText, boolean isDefault, boolean isDomainSpecific, String networkDomain, Type type, boolean isShared, long dcId, Long physicalNetworkId) { - this(trafficType, guestType, mode, broadcastDomainType, networkOfferingId, State.Allocated, dcId, physicalNetworkId); + public NetworkVO(long id, TrafficType trafficType, Mode mode, BroadcastDomainType broadcastDomainType, long networkOfferingId, long domainId, long accountId, long related, String name, String displayText, boolean isDefault, boolean isDomainSpecific, String networkDomain, Type type, boolean isShared, long dcId, Long physicalNetworkId) { + this(trafficType, mode, broadcastDomainType, networkOfferingId, State.Allocated, dcId, physicalNetworkId); this.domainId = domainId; this.accountId = accountId; this.related = related; @@ -279,11 +274,6 @@ public class NetworkVO implements Network { this.tags = tags; } - @Override - public GuestIpType getGuestType() { - return guestType; - } - @Override public Mode getMode() { return mode; diff --git a/server/src/com/cloud/network/dao/NetworkDao.java b/server/src/com/cloud/network/dao/NetworkDao.java index e27a8fb58e4..001df77b9f7 100644 --- a/server/src/com/cloud/network/dao/NetworkDao.java +++ b/server/src/com/cloud/network/dao/NetworkDao.java @@ -19,7 +19,7 @@ package com.cloud.network.dao; import java.util.List; -import com.cloud.network.Network.GuestIpType; +import com.cloud.network.Network; import com.cloud.network.NetworkAccountVO; import com.cloud.network.NetworkVO; import com.cloud.utils.db.GenericDao; @@ -30,7 +30,7 @@ public interface NetworkDao extends GenericDao { List listByOwner(long ownerId); List listBy(long accountId, long offeringId, long dataCenterId); List listBy(long accountId, long offeringId, long dataCenterId, String cidr); - List listBy(long accountId, long dataCenterId, GuestIpType type); + List listBy(long accountId, long dataCenterId, Network.Type type); NetworkVO persist(NetworkVO network, boolean gc); void addAccountToNetwork(long networkId, long accountId); SearchBuilder createSearchBuilderForAccount(); diff --git a/server/src/com/cloud/network/dao/NetworkDaoImpl.java b/server/src/com/cloud/network/dao/NetworkDaoImpl.java index 129b6b114c9..ba708971189 100644 --- a/server/src/com/cloud/network/dao/NetworkDaoImpl.java +++ b/server/src/com/cloud/network/dao/NetworkDaoImpl.java @@ -24,7 +24,6 @@ import javax.ejb.Local; import javax.persistence.TableGenerator; import com.cloud.network.Network; -import com.cloud.network.Network.GuestIpType; import com.cloud.network.NetworkAccountDaoImpl; import com.cloud.network.NetworkAccountVO; import com.cloud.network.NetworkDomainVO; @@ -76,7 +75,6 @@ public class NetworkDaoImpl extends GenericDaoBase implements N AllFieldsSearch.and("offering", AllFieldsSearch.entity().getNetworkOfferingId(), Op.EQ); AllFieldsSearch.and("datacenter", AllFieldsSearch.entity().getDataCenterId(), Op.EQ); AllFieldsSearch.and("account", AllFieldsSearch.entity().getAccountId(), Op.EQ); - AllFieldsSearch.and("guesttype", AllFieldsSearch.entity().getGuestType(), Op.EQ); AllFieldsSearch.and("related", AllFieldsSearch.entity().getRelated(), Op.EQ); AllFieldsSearch.and("type", AllFieldsSearch.entity().getType(), Op.EQ); AllFieldsSearch.and("physicalNetwork", AllFieldsSearch.entity().getPhysicalNetworkId(), Op.EQ); @@ -137,12 +135,12 @@ public class NetworkDaoImpl extends GenericDaoBase implements N } @Override - public List listBy(long accountId, long dataCenterId, GuestIpType type) { + public List listBy(long accountId, long dataCenterId, Network.Type type) { SearchCriteria sc = AllFieldsSearch.create(); sc.setParameters("datacenter", dataCenterId); sc.setParameters("account", accountId); if (type != null) { - sc.setParameters("guesttype", type); + sc.setParameters("type", type); } return listBy(sc, null); } @@ -166,12 +164,6 @@ public class NetworkDaoImpl extends GenericDaoBase implements N return listBy(sc); } - // @Override - // public void loadTags(NetworkVO network) { - // network.setTags(_tagDao.getTags(network.getId())); - // } - - @Override public List listBy(long accountId, long offeringId, long dataCenterId) { SearchCriteria sc = AccountSearch.create(); diff --git a/server/src/com/cloud/network/element/RedundantVirtualRouterElement.java b/server/src/com/cloud/network/element/RedundantVirtualRouterElement.java index 72adee1fc9d..4e5ae3ad771 100644 --- a/server/src/com/cloud/network/element/RedundantVirtualRouterElement.java +++ b/server/src/com/cloud/network/element/RedundantVirtualRouterElement.java @@ -14,15 +14,13 @@ import com.cloud.exception.ConcurrentOperationException; import com.cloud.exception.InsufficientCapacityException; import com.cloud.exception.ResourceUnavailableException; import com.cloud.network.Network; -import com.cloud.network.Network.GuestIpType; import com.cloud.network.Network.Provider; import com.cloud.network.Network.Service; import com.cloud.network.Network.Type; import com.cloud.network.NetworkManager; -import com.cloud.network.router.VirtualRouter; import com.cloud.network.dao.VirtualRouterElementsDao; -import com.cloud.network.element.RedundantVirtualRouterElementService; import com.cloud.network.element.VirtualRouterElements.VirtualRouterElementsType; +import com.cloud.network.router.VirtualRouter; import com.cloud.offering.NetworkOffering; import com.cloud.uservm.UserVm; import com.cloud.utils.component.Inject; @@ -42,7 +40,7 @@ public class RedundantVirtualRouterElement extends VirtualRouterElement implemen private boolean canHandle(Type networkType, long offeringId) { boolean result = (networkType == Network.Type.Isolated && _networkMgr.isProviderSupported(offeringId, Service.Gateway, Provider.VirtualRouter)); if (!result) { - s_logger.trace("Virtual router element only takes care of guest ip type " + GuestIpType.Virtual + " for provider " + Provider.VirtualRouter.getName()); + s_logger.trace("Virtual router element only takes care of networktype " + Network.Type.Isolated + " for provider " + Provider.VirtualRouter.getName()); } return result; } diff --git a/server/src/com/cloud/network/guru/ControlNetworkGuru.java b/server/src/com/cloud/network/guru/ControlNetworkGuru.java index 6d40fe00016..9e29f328eec 100644 --- a/server/src/com/cloud/network/guru/ControlNetworkGuru.java +++ b/server/src/com/cloud/network/guru/ControlNetworkGuru.java @@ -77,7 +77,7 @@ public class ControlNetworkGuru extends PodBasedNetworkGuru implements NetworkGu return null; } - NetworkVO config = new NetworkVO(offering.getTrafficType(), offering.getGuestType(), Mode.Static, BroadcastDomainType.LinkLocal, offering.getId(), Network.State.Setup, plan.getDataCenterId(), plan.getPhysicalNetworkId()); + NetworkVO config = new NetworkVO(offering.getTrafficType(), Mode.Static, BroadcastDomainType.LinkLocal, offering.getId(), Network.State.Setup, plan.getDataCenterId(), plan.getPhysicalNetworkId()); config.setCidr(_cidr); config.setGateway(_gateway); diff --git a/server/src/com/cloud/network/guru/DirectNetworkGuru.java b/server/src/com/cloud/network/guru/DirectNetworkGuru.java index 72c5e6ba6a5..0d5219ec8c8 100644 --- a/server/src/com/cloud/network/guru/DirectNetworkGuru.java +++ b/server/src/com/cloud/network/guru/DirectNetworkGuru.java @@ -102,7 +102,7 @@ public class DirectNetworkGuru extends AdapterBase implements NetworkGuru { state = State.Setup; } - NetworkVO config = new NetworkVO(offering.getTrafficType(), offering.getGuestType(), Mode.Dhcp, BroadcastDomainType.Vlan, offering.getId(), state, plan.getDataCenterId(), plan.getPhysicalNetworkId()); + NetworkVO config = new NetworkVO(offering.getTrafficType(), Mode.Dhcp, BroadcastDomainType.Vlan, offering.getId(), state, plan.getDataCenterId(), plan.getPhysicalNetworkId()); if (userSpecified != null) { if ((userSpecified.getCidr() == null && userSpecified.getGateway() != null) || (userSpecified.getCidr() != null && userSpecified.getGateway() == null)) { diff --git a/server/src/com/cloud/network/guru/ExternalGuestNetworkGuru.java b/server/src/com/cloud/network/guru/ExternalGuestNetworkGuru.java index 9d811ea05c1..5bca18cecaa 100644 --- a/server/src/com/cloud/network/guru/ExternalGuestNetworkGuru.java +++ b/server/src/com/cloud/network/guru/ExternalGuestNetworkGuru.java @@ -108,8 +108,8 @@ public class ExternalGuestNetworkGuru extends GuestNetworkGuru { } DataCenter zone = dest.getDataCenter(); - NetworkVO implemented = new NetworkVO(config.getTrafficType(), config.getGuestType(), config.getMode(), config.getBroadcastDomainType(), config.getNetworkOfferingId(), - State.Allocated, config.getDataCenterId(), config.getPhysicalNetworkId()); + NetworkVO implemented = new NetworkVO(config.getTrafficType(), config.getMode(), config.getBroadcastDomainType(), config.getNetworkOfferingId(), State.Allocated, + config.getDataCenterId(), config.getPhysicalNetworkId()); // Get a vlan tag int vlanTag; diff --git a/server/src/com/cloud/network/guru/GuestNetworkGuru.java b/server/src/com/cloud/network/guru/GuestNetworkGuru.java index ad5fc13cd1b..de424c36e9e 100644 --- a/server/src/com/cloud/network/guru/GuestNetworkGuru.java +++ b/server/src/com/cloud/network/guru/GuestNetworkGuru.java @@ -34,7 +34,6 @@ import com.cloud.exception.InsufficientAddressCapacityException; import com.cloud.exception.InsufficientVirtualNetworkCapcityException; import com.cloud.exception.InvalidParameterValueException; import com.cloud.network.Network; -import com.cloud.network.Network.GuestIpType; import com.cloud.network.Network.State; import com.cloud.network.NetworkManager; import com.cloud.network.NetworkProfile; @@ -79,8 +78,8 @@ public class GuestNetworkGuru extends AdapterBase implements NetworkGuru { } protected boolean canHandle(NetworkOffering offering, DataCenter dc) { - // This guru handles only non-system Guest network - if (dc.getNetworkType() == NetworkType.Advanced && offering.getTrafficType() == TrafficType.Guest && offering.getGuestType() == GuestIpType.Virtual && !offering.isSystemOnly()) { + // This guru handles only non-system Guest Isolated network + if (dc.getNetworkType() == NetworkType.Advanced && offering.getTrafficType() == TrafficType.Guest && offering.getType() == Network.Type.Isolated && !offering.isSystemOnly()) { return true; } else { s_logger.trace("We only take care of Guest Virtual networks in zone of type " + NetworkType.Advanced); @@ -95,7 +94,7 @@ public class GuestNetworkGuru extends AdapterBase implements NetworkGuru { return null; } - NetworkVO network = new NetworkVO(offering.getTrafficType(), offering.getGuestType(), Mode.Dhcp, BroadcastDomainType.Vlan, offering.getId(), State.Allocated, plan.getDataCenterId(), plan.getPhysicalNetworkId()); + NetworkVO network = new NetworkVO(offering.getTrafficType(), Mode.Dhcp, BroadcastDomainType.Vlan, offering.getId(), State.Allocated, plan.getDataCenterId(), plan.getPhysicalNetworkId()); if (userSpecified != null) { if ((userSpecified.getCidr() == null && userSpecified.getGateway() != null) || (userSpecified.getCidr() != null && userSpecified.getGateway() == null)) { throw new InvalidParameterValueException("cidr and gateway must be specified together."); @@ -140,8 +139,8 @@ public class GuestNetworkGuru extends AdapterBase implements NetworkGuru { long dcId = dest.getDataCenter().getId(); - NetworkVO implemented = new NetworkVO(network.getTrafficType(), network.getGuestType(), network.getMode(), network.getBroadcastDomainType(), network.getNetworkOfferingId(), - State.Allocated, network.getDataCenterId(), network.getPhysicalNetworkId()); + NetworkVO implemented = new NetworkVO(network.getTrafficType(), network.getMode(), network.getBroadcastDomainType(), network.getNetworkOfferingId(), State.Allocated, + network.getDataCenterId(), network.getPhysicalNetworkId()); if (network.getBroadcastUri() == null) { String vnet = _dcDao.allocateVnet(dcId, network.getPhysicalNetworkId(), network.getAccountId(), context.getReservationId()); diff --git a/server/src/com/cloud/network/guru/PodBasedNetworkGuru.java b/server/src/com/cloud/network/guru/PodBasedNetworkGuru.java index c7505c1d969..837b76ad208 100644 --- a/server/src/com/cloud/network/guru/PodBasedNetworkGuru.java +++ b/server/src/com/cloud/network/guru/PodBasedNetworkGuru.java @@ -69,7 +69,7 @@ public class PodBasedNetworkGuru extends AdapterBase implements NetworkGuru { return null; } - NetworkVO config = new NetworkVO(type, null, Mode.Static, BroadcastDomainType.Native, offering.getId(), Network.State.Setup, plan.getDataCenterId(), plan.getPhysicalNetworkId()); + NetworkVO config = new NetworkVO(type, Mode.Static, BroadcastDomainType.Native, offering.getId(), Network.State.Setup, plan.getDataCenterId(), plan.getPhysicalNetworkId()); return config; } diff --git a/server/src/com/cloud/network/guru/PublicNetworkGuru.java b/server/src/com/cloud/network/guru/PublicNetworkGuru.java index 0c175dee09a..a4a1bb7a832 100644 --- a/server/src/com/cloud/network/guru/PublicNetworkGuru.java +++ b/server/src/com/cloud/network/guru/PublicNetworkGuru.java @@ -94,7 +94,7 @@ public class PublicNetworkGuru extends AdapterBase implements NetworkGuru { } if (offering.getTrafficType() == TrafficType.Public) { - NetworkVO ntwk = new NetworkVO(offering.getTrafficType(), null, Mode.Static, BroadcastDomainType.Vlan, offering.getId(), State.Setup, plan.getDataCenterId(), plan.getPhysicalNetworkId()); + NetworkVO ntwk = new NetworkVO(offering.getTrafficType(), Mode.Static, BroadcastDomainType.Vlan, offering.getId(), State.Setup, plan.getDataCenterId(), plan.getPhysicalNetworkId()); return ntwk; } else { return null; diff --git a/server/src/com/cloud/network/lb/ElasticLoadBalancerManagerImpl.java b/server/src/com/cloud/network/lb/ElasticLoadBalancerManagerImpl.java index 72092171a2d..caaf3d0ce16 100644 --- a/server/src/com/cloud/network/lb/ElasticLoadBalancerManagerImpl.java +++ b/server/src/com/cloud/network/lb/ElasticLoadBalancerManagerImpl.java @@ -75,7 +75,6 @@ import com.cloud.network.ElasticLbVmMapVO; import com.cloud.network.IPAddressVO; import com.cloud.network.LoadBalancerVO; import com.cloud.network.Network; -import com.cloud.network.Network.GuestIpType; import com.cloud.network.NetworkManager; import com.cloud.network.NetworkVO; import com.cloud.network.Networks.TrafficType; @@ -119,7 +118,6 @@ import com.cloud.vm.NicProfile; import com.cloud.vm.ReservationContext; import com.cloud.vm.VMInstanceVO; import com.cloud.vm.VirtualMachine; -import com.cloud.vm.VirtualMachineGuru; import com.cloud.vm.VirtualMachine.State; import com.cloud.vm.VirtualMachineGuru; import com.cloud.vm.VirtualMachineManager; @@ -574,7 +572,7 @@ public class ElasticLoadBalancerManagerImpl implements @DB public PublicIp allocIp(CreateLoadBalancerRuleCmd lb, Account account) throws InsufficientAddressCapacityException { //TODO: this only works in the guest network. Handle the public network case also. - List offerings = _networkOfferingDao.listByTrafficTypeAndGuestType(true, _frontendTrafficType, GuestIpType.Direct); + List offerings = _networkOfferingDao.listByTrafficTypeAndType(true, _frontendTrafficType, Network.Type.Shared); if (offerings == null || offerings.size() == 0) { s_logger.warn("ELB: Could not find system offering for direct networks of type " + _frontendTrafficType); return null; diff --git a/server/src/com/cloud/network/router/VirtualNetworkApplianceManagerImpl.java b/server/src/com/cloud/network/router/VirtualNetworkApplianceManagerImpl.java index 311a1ced2b4..8d595b1197f 100755 --- a/server/src/com/cloud/network/router/VirtualNetworkApplianceManagerImpl.java +++ b/server/src/com/cloud/network/router/VirtualNetworkApplianceManagerImpl.java @@ -116,7 +116,6 @@ import com.cloud.network.IPAddressVO; import com.cloud.network.IpAddress; import com.cloud.network.LoadBalancerVO; import com.cloud.network.Network; -import com.cloud.network.Network.GuestIpType; import com.cloud.network.NetworkManager; import com.cloud.network.NetworkVO; import com.cloud.network.Networks.BroadcastDomainType; @@ -723,7 +722,7 @@ public class VirtualNetworkApplianceManagerImpl implements VirtualNetworkApplian @Override public void run() { - final List routers = _routerDao.listByStateAndNetworkType(State.Running, GuestIpType.Virtual, mgmtSrvrId); + final List routers = _routerDao.listByStateAndNetworkType(State.Running, Network.Type.Isolated, mgmtSrvrId); s_logger.debug("Found " + routers.size() + " running routers. "); for (DomainRouterVO router : routers) { diff --git a/server/src/com/cloud/offerings/NetworkOfferingVO.java b/server/src/com/cloud/offerings/NetworkOfferingVO.java index ae4ede64c55..c9458b7f4f9 100644 --- a/server/src/com/cloud/offerings/NetworkOfferingVO.java +++ b/server/src/com/cloud/offerings/NetworkOfferingVO.java @@ -29,7 +29,6 @@ import javax.persistence.Id; import javax.persistence.Table; import com.cloud.network.Network; -import com.cloud.network.Network.GuestIpType; import com.cloud.network.Network.Type; import com.cloud.network.Networks.TrafficType; import com.cloud.offering.NetworkOffering; @@ -82,10 +81,6 @@ public class NetworkOfferingVO implements NetworkOffering { @Enumerated(value=EnumType.STRING) Availability availability; - @Deprecated - @Column(name="guest_type") - GuestIpType guestType; - @Column(name="state") @Enumerated(value=EnumType.STRING) State state = State.Disabled; @@ -198,11 +193,6 @@ public class NetworkOfferingVO implements NetworkOffering { return sharedSourceNatService; } - @Override - public GuestIpType getGuestType() { - return guestType; - } - @Override public String getUniqueName() { return uniqueName; @@ -248,11 +238,6 @@ public class NetworkOfferingVO implements NetworkOffering { this.tags = tags; this.securityGroupEnabled = isSecurityGroupEnabled; this.type = type; - if (type == Type.Isolated) { - this.guestType = GuestIpType.Virtual; - } else if (type == Type.Shared){ - this.guestType = GuestIpType.Direct; - } } public NetworkOfferingVO() { diff --git a/server/src/com/cloud/offerings/dao/NetworkOfferingDao.java b/server/src/com/cloud/offerings/dao/NetworkOfferingDao.java index 40dae489f9b..48bac473689 100644 --- a/server/src/com/cloud/offerings/dao/NetworkOfferingDao.java +++ b/server/src/com/cloud/offerings/dao/NetworkOfferingDao.java @@ -23,7 +23,7 @@ package com.cloud.offerings.dao; import java.util.List; -import com.cloud.network.Network.GuestIpType; +import com.cloud.network.Network; import com.cloud.network.Networks.TrafficType; import com.cloud.offering.NetworkOffering; import com.cloud.offering.NetworkOffering.Availability; @@ -59,7 +59,7 @@ public interface NetworkOfferingDao extends GenericDao List listByAvailability(Availability availability, boolean isSystem); - List listByTrafficTypeAndGuestType(boolean isSystem, TrafficType trafficType, GuestIpType guestType); + List listByTrafficTypeAndType(boolean isSystem, TrafficType trafficType, Network.Type type); List getOfferingIdsToUpgradeFrom(NetworkOffering originalOffering); diff --git a/server/src/com/cloud/offerings/dao/NetworkOfferingDaoImpl.java b/server/src/com/cloud/offerings/dao/NetworkOfferingDaoImpl.java index 79ba402391c..c1eb059cd70 100644 --- a/server/src/com/cloud/offerings/dao/NetworkOfferingDaoImpl.java +++ b/server/src/com/cloud/offerings/dao/NetworkOfferingDaoImpl.java @@ -27,7 +27,7 @@ import java.util.List; import javax.ejb.Local; import javax.persistence.EntityExistsException; -import com.cloud.network.Network.GuestIpType; +import com.cloud.network.Network; import com.cloud.network.Networks.TrafficType; import com.cloud.offering.NetworkOffering; import com.cloud.offering.NetworkOffering.Availability; @@ -66,7 +66,7 @@ public class NetworkOfferingDaoImpl extends GenericDaoBase listByTrafficTypeAndGuestType(boolean isSystem, TrafficType trafficType, GuestIpType guestType) { + public List listByTrafficTypeAndType(boolean isSystem, TrafficType trafficType, Network.Type type) { SearchCriteria sc = TrafficTypeGuestTypeSearch.create(); sc.setParameters("trafficType", trafficType); - sc.setParameters("guestType", guestType); + sc.setParameters("type", type); sc.setParameters("isSystem", isSystem); return listBy(sc, null); } diff --git a/server/src/com/cloud/server/ConfigurationServerImpl.java b/server/src/com/cloud/server/ConfigurationServerImpl.java index 15e02578067..8f5289c2bf9 100644 --- a/server/src/com/cloud/server/ConfigurationServerImpl.java +++ b/server/src/com/cloud/server/ConfigurationServerImpl.java @@ -954,7 +954,7 @@ public class ConfigurationServerImpl implements ConfigurationServer { } if (broadcastDomainType != null) { - NetworkVO network = new NetworkVO(id, trafficType, null, mode, broadcastDomainType, networkOfferingId, domainId, accountId, related, null, null, isNetworkDefault, false, networkDomain, Network.Type.Shared, true, zoneId, null); + NetworkVO network = new NetworkVO(id, trafficType, mode, broadcastDomainType, networkOfferingId, domainId, accountId, related, null, null, isNetworkDefault, false, networkDomain, Network.Type.Shared, true, zoneId, null); network.setGuruName(guruNames.get(network.getTrafficType())); network.setDns1(zone.getDns1()); network.setDns2(zone.getDns2()); diff --git a/server/src/com/cloud/vm/UserVmManagerImpl.java b/server/src/com/cloud/vm/UserVmManagerImpl.java index 7eef0305235..8fd9ac2144d 100755 --- a/server/src/com/cloud/vm/UserVmManagerImpl.java +++ b/server/src/com/cloud/vm/UserVmManagerImpl.java @@ -117,7 +117,6 @@ import com.cloud.hypervisor.Hypervisor.HypervisorType; import com.cloud.hypervisor.dao.HypervisorCapabilitiesDao; import com.cloud.network.IPAddressVO; import com.cloud.network.Network; -import com.cloud.network.Network.GuestIpType; import com.cloud.network.Network.Provider; import com.cloud.network.NetworkManager; import com.cloud.network.NetworkVO; @@ -2170,10 +2169,10 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, Manager // 2) If Availability=Optional, search for default networks for the account. If it's more than 1, throw an error. // If it's 0, and there are no default direct networks, create default Guest Virtual network - List defaultVirtualOffering = _networkOfferingDao.listByTrafficTypeAndGuestType(false, TrafficType.Guest, GuestIpType.Virtual); + List defaultVirtualOffering = _networkOfferingDao.listByTrafficTypeAndType(false, TrafficType.Guest, Network.Type.Isolated); if (defaultVirtualOffering.get(0).getAvailability() == Availability.Required) { // get Virtual netowrks - List virtualNetworks = _networkMgr.listNetworksForAccount(owner.getId(), zone.getId(), GuestIpType.Virtual, true); + List virtualNetworks = _networkMgr.listNetworksForAccount(owner.getId(), zone.getId(), Network.Type.Isolated, true); if (virtualNetworks.isEmpty()) { s_logger.debug("Creating default Virtual network for account " + owner + " as a part of deployVM process"); @@ -3333,7 +3332,7 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, Manager } for (NetworkVO oldNet: oldNetworks){ long networkOffering = oldNet.getNetworkOfferingId(); - List virtualNetworks = _networkMgr.listNetworksForAccount(newAccount.getId(), zone.getId(), GuestIpType.Virtual, true); + List virtualNetworks = _networkMgr.listNetworksForAccount(newAccount.getId(), zone.getId(), Network.Type.Isolated, true); if (virtualNetworks.isEmpty()) { Network newNetwork = _networkMgr.createNetwork(networkOffering, newAccount.getAccountName() + "-network", newAccount.getAccountName() + "-network", null, null, null, null, null, newAccount, false, null, null, false, null); diff --git a/server/src/com/cloud/vm/dao/DomainRouterDao.java b/server/src/com/cloud/vm/dao/DomainRouterDao.java index 564d1e50cc3..f51a8347a61 100755 --- a/server/src/com/cloud/vm/dao/DomainRouterDao.java +++ b/server/src/com/cloud/vm/dao/DomainRouterDao.java @@ -19,7 +19,7 @@ package com.cloud.vm.dao; import java.util.List; -import com.cloud.network.Network.GuestIpType; +import com.cloud.network.Network; import com.cloud.network.router.VirtualRouter.Role; import com.cloud.utils.db.GenericDao; import com.cloud.vm.DomainRouterVO; @@ -97,7 +97,7 @@ public interface DomainRouterDao extends GenericDao { * List domain routers by state and network type which reside on Host managed by the specified management server * @return */ - List listByStateAndNetworkType(State state, GuestIpType ipType, long mgmtSrvrId); + List listByStateAndNetworkType(State state, Network.Type type, long mgmtSrvrId); List findByNetworkOutsideThePod(long networkId, long podId, State state, Role role); diff --git a/server/src/com/cloud/vm/dao/DomainRouterDaoImpl.java b/server/src/com/cloud/vm/dao/DomainRouterDaoImpl.java index 31405a04eeb..bb627744522 100755 --- a/server/src/com/cloud/vm/dao/DomainRouterDaoImpl.java +++ b/server/src/com/cloud/vm/dao/DomainRouterDaoImpl.java @@ -25,7 +25,7 @@ import org.apache.log4j.Logger; import com.cloud.host.HostVO; import com.cloud.host.dao.HostDaoImpl; -import com.cloud.network.Network.GuestIpType; +import com.cloud.network.Network; import com.cloud.network.NetworkVO; import com.cloud.network.dao.NetworkDaoImpl; import com.cloud.network.router.VirtualRouter.Role; @@ -75,14 +75,14 @@ public class DomainRouterDaoImpl extends GenericDaoBase im HostUpSearch.and("host", HostUpSearch.entity().getHostId(), Op.EQ); HostUpSearch.and("states", HostUpSearch.entity().getState(), Op.NIN); SearchBuilder joinNetwork = _networksDao.createSearchBuilder(); - joinNetwork.and("guestType", joinNetwork.entity().getGuestType(), Op.EQ); + joinNetwork.and("type", joinNetwork.entity().getType(), Op.EQ); HostUpSearch.join("network", joinNetwork, joinNetwork.entity().getId(), HostUpSearch.entity().getNetworkId(), JoinType.INNER); HostUpSearch.done(); StateNetworkTypeSearch = createSearchBuilder(); StateNetworkTypeSearch.and("state", StateNetworkTypeSearch.entity().getState(), Op.EQ); SearchBuilder joinStateNetwork = _networksDao.createSearchBuilder(); - joinStateNetwork.and("guestType", joinStateNetwork.entity().getGuestType(), Op.EQ); + joinStateNetwork.and("type", joinStateNetwork.entity().getType(), Op.EQ); StateNetworkTypeSearch.join("network", joinStateNetwork, joinStateNetwork.entity().getId(), StateNetworkTypeSearch.entity().getNetworkId(), JoinType.INNER); SearchBuilder joinHost = _hostsDao.createSearchBuilder(); joinHost.and("mgmtServerId", joinHost.entity().getManagementServerId(), Op.EQ); @@ -158,7 +158,7 @@ public class DomainRouterDaoImpl extends GenericDaoBase im if (hostId != null) { sc.setParameters("host", hostId); } - sc.setJoinParameters("network", "guestType", GuestIpType.Virtual); + sc.setJoinParameters("network", "type", Network.Type.Isolated); return listBy(sc); } @@ -169,7 +169,7 @@ public class DomainRouterDaoImpl extends GenericDaoBase im sc.setParameters("host", hostId); } sc.setParameters("states", State.Destroyed, State.Stopped, State.Expunging); - sc.setJoinParameters("network", "guestType", GuestIpType.Virtual); + sc.setJoinParameters("network", "type", Network.Type.Isolated); return listBy(sc); } @@ -204,10 +204,10 @@ public class DomainRouterDaoImpl extends GenericDaoBase im } @Override - public List listByStateAndNetworkType(State state, GuestIpType ipType, long mgmtSrvrId) { + public List listByStateAndNetworkType(State state, Network.Type type, long mgmtSrvrId) { SearchCriteria sc = StateNetworkTypeSearch.create(); sc.setParameters("state", state); - sc.setJoinParameters("network", "guestType", ipType); + sc.setJoinParameters("network", "type", type); sc.setJoinParameters("host", "mgmtServerId", mgmtSrvrId); return listBy(sc); } diff --git a/server/src/com/cloud/vm/dao/UserVmDaoImpl.java b/server/src/com/cloud/vm/dao/UserVmDaoImpl.java index 5323aa5e181..a0a2be6f4c3 100755 --- a/server/src/com/cloud/vm/dao/UserVmDaoImpl.java +++ b/server/src/com/cloud/vm/dao/UserVmDaoImpl.java @@ -82,7 +82,7 @@ public class UserVmDaoImpl extends GenericDaoBase implements Use "vm_template.enable_password, service_offering.id, disk_offering.name, storage_pool.id, storage_pool.pool_type, " + "service_offering.cpu, service_offering.speed, service_offering.ram_size, volumes.id, volumes.device_id, volumes.volume_type, security_group.id, security_group.name, " + "security_group.description, nics.id, nics.ip4_address, nics.gateway, nics.network_id, nics.netmask, nics.mac_address, nics.broadcast_uri, nics.isolation_uri, " + - "networks.traffic_type, networks.guest_type, networks.is_default from vm_instance " + + "networks.traffic_type, networks.type, networks.is_default from vm_instance " + "left join account on vm_instance.account_id=account.id " + "left join domain on vm_instance.domain_id=domain.id " + "left join instance_group_vm_map on vm_instance.id=instance_group_vm_map.instance_id " + @@ -492,9 +492,6 @@ public class UserVmDaoImpl extends GenericDaoBase implements Use userVmData.addSecurityGroup(resp); } - - //nics.id, nics.ip4_address, nics.gateway, nics.network_id, nics.netmask, nics. mac_address, nics.broadcast_uri, nics.isolation_uri, " + - //"networks.traffic_type, networks.guest_type, networks.is_default from vm_instance, " long nic_id = rs.getLong("nics.id"); if (nic_id > 0){ NicData nicResponse = userVmData.newNicData(); @@ -513,7 +510,7 @@ public class UserVmDaoImpl extends GenericDaoBase implements Use nicResponse.setTrafficType(rs.getString("networks.traffic_type")); - nicResponse.setType(rs.getString("networks.guest_type")); + nicResponse.setType(rs.getString("networks.type")); nicResponse.setIsDefault(rs.getBoolean("networks.is_default")); nicResponse.setObjectName("nic"); userVmData.addNic(nicResponse); diff --git a/setup/db/create-schema.sql b/setup/db/create-schema.sql index 077819b9da2..eaa3f727fd3 100755 --- a/setup/db/create-schema.sql +++ b/setup/db/create-schema.sql @@ -181,7 +181,6 @@ CREATE TABLE `cloud`.`networks` ( `dns2` varchar(255) COMMENT 'comma separated DNS list', `guru_data` varchar(1024) COMMENT 'data stored by the network guru that setup this network', `set_fields` bigint unsigned NOT NULL DEFAULT 0 COMMENT 'which fields are set already', - `guest_type` char(32) COMMENT 'type of guest network', `shared` int(1) unsigned NOT NULL DEFAULT 0 COMMENT '0 if network is shared, 1 if network dedicated', `is_domain_specific` int(1) unsigned NOT NULL DEFAULT 0 COMMENT '1 if network is domain specific, 0 false otherwise', `network_domain` varchar(255) COMMENT 'domain', @@ -265,7 +264,6 @@ CREATE TABLE `cloud`.`network_offerings` ( `default` int(1) unsigned NOT NULL DEFAULT 0 COMMENT '1 if network offering is default', `availability` varchar(255) NOT NULL COMMENT 'availability of the network', `shared_source_nat_service` int(1) unsigned NOT NULL DEFAULT 0 COMMENT 'true if the network offering provides the shared source nat service', - `guest_type` char(32) COMMENT 'guest ip type of network offering', `is_security_group_enabled` tinyint NOT NULL DEFAULT 0 COMMENT '1: enabled, 0: not', `state` char(32) COMMENT 'state of the network offering; has Disabled value by default', `type` char(32) COMMENT 'type of the network offering, can be Shared or Isolated', From f6717e0a2368e8ba0a8558faffea8a293251ff66 Mon Sep 17 00:00:00 2001 From: alena Date: Mon, 24 Oct 2011 17:30:14 -0700 Subject: [PATCH 024/159] 1) Method name change 2) Rely on SourceNatService when decide if DirectNetworkGuru and GuestNetworkGuru should handle the network --- server/src/com/cloud/network/NetworkManager.java | 2 +- server/src/com/cloud/network/NetworkManagerImpl.java | 8 ++++---- server/src/com/cloud/network/guru/DirectNetworkGuru.java | 5 +++-- .../com/cloud/network/guru/DirectPodBasedNetworkGuru.java | 1 + server/src/com/cloud/network/guru/GuestNetworkGuru.java | 5 +++-- server/src/com/cloud/network/guru/PublicNetworkGuru.java | 4 ++-- .../cloud/network/lb/LoadBalancingRulesManagerImpl.java | 2 +- server/src/com/cloud/network/rules/RulesManagerImpl.java | 2 +- .../com/cloud/network/vpn/RemoteAccessVpnManagerImpl.java | 2 +- server/test/com/cloud/network/MockNetworkManagerImpl.java | 2 +- 10 files changed, 18 insertions(+), 15 deletions(-) diff --git a/server/src/com/cloud/network/NetworkManager.java b/server/src/com/cloud/network/NetworkManager.java index 3f2c9951739..b9d41423359 100644 --- a/server/src/com/cloud/network/NetworkManager.java +++ b/server/src/com/cloud/network/NetworkManager.java @@ -194,7 +194,7 @@ public interface NetworkManager extends NetworkService { boolean applyIpAssociations(Network network, boolean continueOnError) throws ResourceUnavailableException; - boolean isServiceSupported(long networkId, Network.Service service); + boolean isServiceSupportedByNetworkOffering(long networkOfferingId, Network.Service service); NetworkVO getNetworkWithSecurityGroupEnabled(Long zoneId); diff --git a/server/src/com/cloud/network/NetworkManagerImpl.java b/server/src/com/cloud/network/NetworkManagerImpl.java index 142db9a8bac..791ea649fd3 100755 --- a/server/src/com/cloud/network/NetworkManagerImpl.java +++ b/server/src/com/cloud/network/NetworkManagerImpl.java @@ -1784,7 +1784,7 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag } // If networkDomain is not specified, take it from the global configuration - if (isServiceSupported(networkOfferingId, Service.Dns)) { + if (isServiceSupportedByNetworkOffering(networkOfferingId, Service.Dns)) { Map dnsCapabilities = getServiceCapabilities(zoneId, networkOfferingId, Service.Dns); String isUpdateDnsSupported = dnsCapabilities.get(Capability.AllowDnsSuffixModification); if (isUpdateDnsSupported == null || !Boolean.valueOf(isUpdateDnsSupported)) { @@ -2648,7 +2648,7 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag Map> networkCapabilities = new HashMap>(); for (Service service : zoneCapabilities.keySet()) { - if (isServiceSupported(networkOfferingId, service)) { + if (isServiceSupportedByNetworkOffering(networkOfferingId, service)) { networkCapabilities.put(service, zoneCapabilities.get(service)); } } @@ -2659,7 +2659,7 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag @Override public Map getServiceCapabilities(long zoneId, Long networkOfferingId, Service service) { - if (!isServiceSupported(networkOfferingId, service)) { + if (!isServiceSupportedByNetworkOffering(networkOfferingId, service)) { throw new UnsupportedServiceException("Service " + service.getName() + " is not supported by the network offering id=" + networkOfferingId); } @@ -2918,7 +2918,7 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag } @Override - public boolean isServiceSupported(long networkOfferingId, Network.Service service) { + public boolean isServiceSupportedByNetworkOffering(long networkOfferingId, Network.Service service) { return (_ntwkOfferingSrvcDao.isServiceSupported(networkOfferingId, service)); } diff --git a/server/src/com/cloud/network/guru/DirectNetworkGuru.java b/server/src/com/cloud/network/guru/DirectNetworkGuru.java index 0d5219ec8c8..d0d226847c2 100644 --- a/server/src/com/cloud/network/guru/DirectNetworkGuru.java +++ b/server/src/com/cloud/network/guru/DirectNetworkGuru.java @@ -34,6 +34,7 @@ import com.cloud.exception.InsufficientVirtualNetworkCapcityException; import com.cloud.exception.InvalidParameterValueException; import com.cloud.network.IPAddressVO; import com.cloud.network.Network; +import com.cloud.network.Network.Service; import com.cloud.network.Network.State; import com.cloud.network.NetworkManager; import com.cloud.network.NetworkProfile; @@ -74,9 +75,9 @@ public class DirectNetworkGuru extends AdapterBase implements NetworkGuru { NetworkOfferingDao _networkOfferingDao; protected boolean canHandle(NetworkOffering offering, DataCenter dc) { - // this guru handles only non-system network with guestIpType = Direct + // this guru handles only non-system network with type=Shared and serviceNat service disabled //TODO - after broadCastDomainType + physical network are introduced, don't rely on network type of the dc - if (dc.getNetworkType() == NetworkType.Advanced && offering.getType() == Network.Type.Shared && offering.getTrafficType() == TrafficType.Guest) { + if (dc.getNetworkType() == NetworkType.Advanced && offering.getType() == Network.Type.Shared && !_networkMgr.isServiceSupportedByNetworkOffering(offering.getId(), Service.SourceNat)&& offering.getTrafficType() == TrafficType.Guest) { if (offering.isSecurityGroupEnabled()) { return true; } else if (!offering.isSystemOnly()) { diff --git a/server/src/com/cloud/network/guru/DirectPodBasedNetworkGuru.java b/server/src/com/cloud/network/guru/DirectPodBasedNetworkGuru.java index 42db8901983..acceec4b7e4 100644 --- a/server/src/com/cloud/network/guru/DirectPodBasedNetworkGuru.java +++ b/server/src/com/cloud/network/guru/DirectPodBasedNetworkGuru.java @@ -79,6 +79,7 @@ public class DirectPodBasedNetworkGuru extends DirectNetworkGuru { @Override protected boolean canHandle(NetworkOffering offering, DataCenter dc) { // this guru handles system Direct pod based network + //FIXME - verify broadcast domain type here if (dc.getNetworkType() == NetworkType.Basic && offering.getTrafficType() == TrafficType.Guest) { return true; } else { diff --git a/server/src/com/cloud/network/guru/GuestNetworkGuru.java b/server/src/com/cloud/network/guru/GuestNetworkGuru.java index de424c36e9e..471647eca05 100644 --- a/server/src/com/cloud/network/guru/GuestNetworkGuru.java +++ b/server/src/com/cloud/network/guru/GuestNetworkGuru.java @@ -34,6 +34,7 @@ import com.cloud.exception.InsufficientAddressCapacityException; import com.cloud.exception.InsufficientVirtualNetworkCapcityException; import com.cloud.exception.InvalidParameterValueException; import com.cloud.network.Network; +import com.cloud.network.Network.Service; import com.cloud.network.Network.State; import com.cloud.network.NetworkManager; import com.cloud.network.NetworkProfile; @@ -78,8 +79,8 @@ public class GuestNetworkGuru extends AdapterBase implements NetworkGuru { } protected boolean canHandle(NetworkOffering offering, DataCenter dc) { - // This guru handles only non-system Guest Isolated network - if (dc.getNetworkType() == NetworkType.Advanced && offering.getTrafficType() == TrafficType.Guest && offering.getType() == Network.Type.Isolated && !offering.isSystemOnly()) { + // This guru handles only non-system Guest Isolated network that supports Source nat service + if (dc.getNetworkType() == NetworkType.Advanced && offering.getTrafficType() == TrafficType.Guest && offering.getType() == Network.Type.Isolated && _networkMgr.isServiceSupportedByNetworkOffering(offering.getId(), Service.SourceNat) && !offering.isSystemOnly()) { return true; } else { s_logger.trace("We only take care of Guest Virtual networks in zone of type " + NetworkType.Advanced); diff --git a/server/src/com/cloud/network/guru/PublicNetworkGuru.java b/server/src/com/cloud/network/guru/PublicNetworkGuru.java index a4a1bb7a832..002d778b8fb 100644 --- a/server/src/com/cloud/network/guru/PublicNetworkGuru.java +++ b/server/src/com/cloud/network/guru/PublicNetworkGuru.java @@ -77,10 +77,10 @@ public class PublicNetworkGuru extends AdapterBase implements NetworkGuru { NetworkOfferingDao _networkOfferingDao; protected boolean canHandle(NetworkOffering offering, DataCenter dc) { - if (!offering.isSecurityGroupEnabled() && offering.getTrafficType() == TrafficType.Public && offering.isSystemOnly()) { + if (offering.getTrafficType() == TrafficType.Public && offering.isSystemOnly()) { return true; } else { - s_logger.trace("We only take care of System only Public Virtual Network"); + s_logger.trace("We take care only of System Public Virtual Network"); return false; } } diff --git a/server/src/com/cloud/network/lb/LoadBalancingRulesManagerImpl.java b/server/src/com/cloud/network/lb/LoadBalancingRulesManagerImpl.java index d31734a5370..ba4741dde60 100755 --- a/server/src/com/cloud/network/lb/LoadBalancingRulesManagerImpl.java +++ b/server/src/com/cloud/network/lb/LoadBalancingRulesManagerImpl.java @@ -421,7 +421,7 @@ public class LoadBalancingRulesManagerImpl implements LoadBalancingRulesManager, _accountMgr.checkAccess(caller.getCaller(), null, ipAddr); // verify that lb service is supported by the network - if (!_networkMgr.isServiceSupported(network.getNetworkOfferingId(), Service.Lb)) { + if (!_networkMgr.isServiceSupportedByNetworkOffering(network.getNetworkOfferingId(), Service.Lb)) { throw new InvalidParameterValueException("LB service is not supported in network id= " + networkId); } diff --git a/server/src/com/cloud/network/rules/RulesManagerImpl.java b/server/src/com/cloud/network/rules/RulesManagerImpl.java index c358a184315..a17dc0a0079 100755 --- a/server/src/com/cloud/network/rules/RulesManagerImpl.java +++ b/server/src/com/cloud/network/rules/RulesManagerImpl.java @@ -343,7 +343,7 @@ public class RulesManagerImpl implements RulesManager, RulesService, Manager { } Network network = _networkMgr.getNetwork(networkId); - if (!_networkMgr.isServiceSupported(network.getNetworkOfferingId(), Service.Firewall)) { + if (!_networkMgr.isServiceSupportedByNetworkOffering(network.getNetworkOfferingId(), Service.Firewall)) { throw new InvalidParameterValueException("Unable to create static nat rule; Firewall service is not supported in network id=" + networkId); } diff --git a/server/src/com/cloud/network/vpn/RemoteAccessVpnManagerImpl.java b/server/src/com/cloud/network/vpn/RemoteAccessVpnManagerImpl.java index bcfd0889587..27cd65674c6 100755 --- a/server/src/com/cloud/network/vpn/RemoteAccessVpnManagerImpl.java +++ b/server/src/com/cloud/network/vpn/RemoteAccessVpnManagerImpl.java @@ -139,7 +139,7 @@ public class RemoteAccessVpnManagerImpl implements RemoteAccessVpnService, Manag //Verify that vpn service is enabled for the network Network network = _networkMgr.getNetwork(ipAddr.getAssociatedWithNetworkId()); - if (!_networkMgr.isServiceSupported(network.getNetworkOfferingId(), Service.Vpn)) { + if (!_networkMgr.isServiceSupportedByNetworkOffering(network.getNetworkOfferingId(), Service.Vpn)) { throw new InvalidParameterValueException("Vpn service is not supported in network id=" + ipAddr.getAssociatedWithNetworkId()); } diff --git a/server/test/com/cloud/network/MockNetworkManagerImpl.java b/server/test/com/cloud/network/MockNetworkManagerImpl.java index 6db0ad752fc..2e4030ad1d7 100644 --- a/server/test/com/cloud/network/MockNetworkManagerImpl.java +++ b/server/test/com/cloud/network/MockNetworkManagerImpl.java @@ -402,7 +402,7 @@ public class MockNetworkManagerImpl implements NetworkManager, Manager, NetworkS } @Override - public boolean isServiceSupported(long networkId, Service service) { + public boolean isServiceSupportedByNetworkOffering(long networkOfferingId, Service service) { // TODO Auto-generated method stub return false; } From 6379c9c61ea3010925c8af21573f9828a46f80e1 Mon Sep 17 00:00:00 2001 From: alena Date: Mon, 24 Oct 2011 17:55:04 -0700 Subject: [PATCH 025/159] Return false when failed to apply the rules on the backend --- .../com/cloud/network/firewall/FirewallManagerImpl.java | 5 ++--- server/src/com/cloud/network/rules/RulesManagerImpl.java | 7 ++++--- 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/server/src/com/cloud/network/firewall/FirewallManagerImpl.java b/server/src/com/cloud/network/firewall/FirewallManagerImpl.java index a17c4e4b7c7..a35fd5956ed 100644 --- a/server/src/com/cloud/network/firewall/FirewallManagerImpl.java +++ b/server/src/com/cloud/network/firewall/FirewallManagerImpl.java @@ -420,7 +420,6 @@ public class FirewallManagerImpl implements FirewallService, FirewallManager, Ma // load cidrs if any rule.setSourceCidrList(_firewallCidrsDao.getSourceCidrs(rule.getId())); } - if (caller != null) { _accountMgr.checkAccess(caller, null, rules.toArray(new FirewallRuleVO[rules.size()])); @@ -566,7 +565,7 @@ public class FirewallManagerImpl implements FirewallService, FirewallManager, Ma // now send everything to the backend List rulesToApply = _firewallDao.listByNetworkAndPurpose(networkId, Purpose.Firewall); - applyFirewallRules(rulesToApply, true, caller); + boolean success = applyFirewallRules(rulesToApply, true, caller); // Now we check again in case more rules have been inserted. rules.addAll(_firewallDao.listByNetworkAndPurposeAndNotRevoked(networkId, Purpose.Firewall)); @@ -575,7 +574,7 @@ public class FirewallManagerImpl implements FirewallService, FirewallManager, Ma s_logger.debug("Successfully released firewall rules for network id=" + networkId + " and # of rules now = " + rules.size()); } - return rules.size() == 0; + return success && rules.size() == 0; } @Override diff --git a/server/src/com/cloud/network/rules/RulesManagerImpl.java b/server/src/com/cloud/network/rules/RulesManagerImpl.java index a17dc0a0079..a6c1046b1ce 100755 --- a/server/src/com/cloud/network/rules/RulesManagerImpl.java +++ b/server/src/com/cloud/network/rules/RulesManagerImpl.java @@ -917,11 +917,12 @@ public class RulesManagerImpl implements RulesManager, RulesService, Manager { revokeStaticNatRuleInternal(rule.getId(), caller, userId, false); } + boolean success = true; // revoke all PF rules for the network - applyPortForwardingRulesForNetwork(networkId, true, caller); + success = success && applyPortForwardingRulesForNetwork(networkId, true, caller); // revoke all all static nat rules for the network - applyStaticNatRulesForNetwork(networkId, true, caller); + success = success && applyStaticNatRulesForNetwork(networkId, true, caller); // Now we check again in case more rules have been inserted. rules.addAll(_forwardingDao.listByNetworkAndNotRevoked(networkId)); @@ -931,7 +932,7 @@ public class RulesManagerImpl implements RulesManager, RulesService, Manager { s_logger.debug("Successfully released rules for network id=" + networkId + " and # of rules now = " + rules.size()); } - return rules.size() == 0; + return success && rules.size() == 0; } @Override From 345b1421c8c3353a74d263f1c7bfbb29dcff1e42 Mon Sep 17 00:00:00 2001 From: alena Date: Mon, 24 Oct 2011 17:56:34 -0700 Subject: [PATCH 026/159] Allow network offering upgrade for any combination of services --- .../src/com/cloud/network/NetworkManagerImpl.java | 13 ++----------- 1 file changed, 2 insertions(+), 11 deletions(-) diff --git a/server/src/com/cloud/network/NetworkManagerImpl.java b/server/src/com/cloud/network/NetworkManagerImpl.java index 791ea649fd3..b3e0819c98a 100755 --- a/server/src/com/cloud/network/NetworkManagerImpl.java +++ b/server/src/com/cloud/network/NetworkManagerImpl.java @@ -3414,8 +3414,7 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag return false; } - //compare providers - return canUpgradeProviders(oldNetworkOfferingId, newNetworkOfferingId); + return true; } @@ -3962,20 +3961,12 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag @Override public List listNetworkOfferingsForUpgrade(long networkId) { - List offeringIdsToReturn = new ArrayList(); NetworkOffering originalOffering = _configMgr.getNetworkOffering(getNetwork(networkId).getNetworkOfferingId()); List offerings = _networkOfferingDao.getOfferingIdsToUpgradeFrom(originalOffering); - //check if providers are upgradable - for (Long offering : offerings) { - if (canUpgradeProviders(originalOffering.getId(), offering.longValue())) { - offeringIdsToReturn.add(offering); - } - } - - return offeringIdsToReturn; + return offerings; } } From 766c898504cb1a9aea009299eccd4fe89d1fee4f Mon Sep 17 00:00:00 2001 From: prachi Date: Fri, 21 Oct 2011 16:04:56 -0700 Subject: [PATCH 027/159] Changes: DeletePhysicalNetwork changes and Configuring NetworkMgr to hold map of providers -> elements --- api/src/com/cloud/network/Network.java | 6 +- .../cloud/network/element/NetworkElement.java | 4 + .../ConfigurationManagerImpl.java | 26 ++-- .../com/cloud/network/NetworkManagerImpl.java | 113 +++++++++--------- .../src/com/cloud/network/dao/NetworkDao.java | 2 + .../com/cloud/network/dao/NetworkDaoImpl.java | 7 ++ .../PhysicalNetworkServiceProviderDao.java | 2 + ...PhysicalNetworkServiceProviderDaoImpl.java | 7 ++ .../network/element/BareMetalElement.java | 2 +- .../RedundantVirtualRouterElement.java | 5 + 10 files changed, 96 insertions(+), 78 deletions(-) diff --git a/api/src/com/cloud/network/Network.java b/api/src/com/cloud/network/Network.java index e020d2a4c75..eeb3b3a709c 100644 --- a/api/src/com/cloud/network/Network.java +++ b/api/src/com/cloud/network/Network.java @@ -102,9 +102,13 @@ public interface Network extends ControlledEntity { } } + /** + * Provider -> NetworkElement must always be one-to-one mapping. Thus for each NetworkElement we need a separate Provider added in here. + */ public static class Provider { private static List supportedProviders = new ArrayList(); + public static final Provider VirtualRouter = new Provider("VirtualRouter", false); public static final Provider DhcpServer = new Provider("DhcpServer", false); public static final Provider JuniperSRX = new Provider("JuniperSRX", true); @@ -113,7 +117,7 @@ public interface Network extends ControlledEntity { public static final Provider ExternalDhcpServer = new Provider("ExternalDhcpServer", true); public static final Provider ExternalGateWay = new Provider("ExternalGateWay", true); public static final Provider ElasticLoadBalancerVm = new Provider("ElasticLoadBalancerVm", false); - + public static final Provider RedundantVirtualRouter = new Provider("RedundantVirtualRouter", false); public static final Provider defaultProvider = VirtualRouter; public static final Provider None = new Provider("None", false); diff --git a/api/src/com/cloud/network/element/NetworkElement.java b/api/src/com/cloud/network/element/NetworkElement.java index 8ff75971b09..d85b36c22c8 100644 --- a/api/src/com/cloud/network/element/NetworkElement.java +++ b/api/src/com/cloud/network/element/NetworkElement.java @@ -46,6 +46,10 @@ public interface NetworkElement extends Adapter { Map> getCapabilities(); + /** + * NOTE: + * NetworkElement -> Network.Provider is a one-to-one mapping. While adding a new NetworkElement, one must add a new Provider name to Network.Provider. + */ Provider getProvider(); /** diff --git a/server/src/com/cloud/configuration/ConfigurationManagerImpl.java b/server/src/com/cloud/configuration/ConfigurationManagerImpl.java index 9110515ca02..4691eca4e16 100755 --- a/server/src/com/cloud/configuration/ConfigurationManagerImpl.java +++ b/server/src/com/cloud/configuration/ConfigurationManagerImpl.java @@ -995,13 +995,12 @@ public class ConfigurationManagerImpl implements ConfigurationManager, Configura volumes.add(2, "there are storage volumes for this zone"); tablesToCheck.add(volumes); - //FIXME - move this part of verification to deletePhysicalNetwork code - List vnet = new ArrayList(); - vnet.add(0, "op_dc_vnet_alloc"); - vnet.add(1, "data_center_id"); - vnet.add(2, "there are allocated vnets for this zone"); - tablesToCheck.add(vnet); - + List physicalNetworks = new ArrayList(); + physicalNetworks.add(0, "physical_network"); + physicalNetworks.add(1, "data_center_id"); + physicalNetworks.add(2, "there are physical networks in this zone"); + tablesToCheck.add(physicalNetworks); + for (List table : tablesToCheck) { String tableName = table.get(0); String column = table.get(1); @@ -1023,7 +1022,7 @@ public class ConfigurationManagerImpl implements ConfigurationManager, Configura selectSql += " AND taken IS NOT NULL"; } - if (tableName.equals("host_pod_ref") || tableName.equals("host") || tableName.equals("volumes")) { + if (tableName.equals("host_pod_ref") || tableName.equals("host") || tableName.equals("volumes") || tableName.equals("physical_network")) { selectSql += " AND removed is NULL"; } @@ -1143,17 +1142,6 @@ public class ConfigurationManagerImpl implements ConfigurationManager, Configura _vlanDao.remove(vlan.getId()); } - // Delete networks - //FIXME - move this part to deletePhysicalNetwork - List networks = _networkDao.listByZoneIncludingRemoved(zoneId); - if (networks != null && !networks.isEmpty()) { - for (NetworkVO network : networks) { - _networkDao.remove(network.getId()); - } - } - - //FIXME - Delete physical networks belonging to the zone - success = _zoneDao.remove(zoneId); if (success) { diff --git a/server/src/com/cloud/network/NetworkManagerImpl.java b/server/src/com/cloud/network/NetworkManagerImpl.java index b3e0819c98a..57a1cc25be6 100755 --- a/server/src/com/cloud/network/NetworkManagerImpl.java +++ b/server/src/com/cloud/network/NetworkManagerImpl.java @@ -59,7 +59,6 @@ import com.cloud.dc.AccountVlanMapVO; import com.cloud.dc.DataCenter; import com.cloud.dc.DataCenter.NetworkType; import com.cloud.dc.DataCenterVO; -import com.cloud.dc.DataCenterVnetVO; import com.cloud.dc.Pod; import com.cloud.dc.PodVlanMapVO; import com.cloud.dc.Vlan; @@ -269,6 +268,7 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag HashMap _lastNetworkIdsToFree = new HashMap(); private static HashMap> s_serviceToImplementedProvidersMap = new HashMap>(); + private static HashMap s_providerToNetworkElementMap = new HashMap(); @Override public PublicIp assignPublicIpAddress(long dcId, Long podId, Account owner, VlanType type, Long networkId, String requestedIp) throws InsufficientAddressCapacityException { @@ -884,10 +884,31 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag _allowSubdomainNetworkAccess = Boolean.valueOf(_configs.get(Config.SubDomainNetworkAccess.key())); - //populate s_serviceToImplementedProvidersMap with current _networkElements + s_logger.info("Network Manager is configured."); + + return true; + } + + @Override + public String getName() { + return _name; + } + + @Override + public boolean start() { + + //populate s_serviceToImplementedProvidersMap & s_providerToNetworkElementMap with current _networkElements + //Need to do this in start() since _networkElements are not completely configured until then. for (NetworkElement element : _networkElements) { Map> capabilities = element.getCapabilities(); Provider implementedProvider = element.getProvider(); + if(implementedProvider != null){ + if(s_providerToNetworkElementMap.containsKey(implementedProvider.getName())){ + s_logger.error("Cannot start NetworkManager: Provider <-> NetworkElement must be a one-to-one map, multiple NetworkElements found for Provider: "+implementedProvider.getName()); + return false; + } + s_providerToNetworkElementMap.put(implementedProvider.getName(), element.getName()); + } if(capabilities != null && implementedProvider != null){ for(Service service : capabilities.keySet()){ if(s_serviceToImplementedProvidersMap.containsKey(service)){ @@ -901,19 +922,7 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag } } } - - s_logger.info("Network Manager is configured."); - - return true; - } - - @Override - public String getName() { - return _name; - } - - @Override - public boolean start() { + _executor.scheduleWithFixedDelay(new NetworkGarbageCollector(), _networkGcInterval, _networkGcInterval, TimeUnit.SECONDS); return true; } @@ -3688,30 +3697,31 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag @Override @ActionEvent(eventType = EventTypes.EVENT_PHYSICAL_NETWORK_DELETE, eventDescription = "deleting physical network", async = true) + @DB public boolean deletePhysicalNetwork(Long physicalNetworkId) { // verify input parameters - PhysicalNetworkVO network = _physicalNetworkDao.findById(physicalNetworkId); - if (network == null) { + PhysicalNetworkVO pNetwork = _physicalNetworkDao.findById(physicalNetworkId); + if (pNetwork == null) { throw new InvalidParameterValueException("Network id=" + physicalNetworkId + "doesn't exist in the system"); } - //for all networks associated, check if they can be deleted. - //delete physical network only if no network is associated to it - List networks = _networksDao.listByPhysicalNetwork(physicalNetworkId); - if(networks != null && !networks.isEmpty()){ - s_logger.debug("Unable to remove the physical network id=" + physicalNetworkId + " as it has active networks associated."); - return false; + checkIfPhysicalNetworkIsDeletable(physicalNetworkId); + + // Delete networks + List networks = _networksDao.listByPhysicalNetworkIncludingRemoved(physicalNetworkId); + if (networks != null && !networks.isEmpty()) { + for (NetworkVO network : networks) { + _networksDao.remove(network.getId()); + } } - List allocatedVnets = _dcDao.listAllocatedVnets(physicalNetworkId); - - if(allocatedVnets != null && !allocatedVnets.isEmpty()){ - s_logger.debug("Unable to remove the physical network id=" + physicalNetworkId + " as it has active vnets associated."); - return false; - } - //checkIfPhysicalNetworkIsDeletable(physicalNetworkId); + //delete vnets + _dcDao.deleteVnet(physicalNetworkId); + //delete service providers + _pNSPDao.deleteProviders(physicalNetworkId); + return _physicalNetworkDao.remove(physicalNetworkId); } @@ -3719,6 +3729,12 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag private void checkIfPhysicalNetworkIsDeletable(Long physicalNetworkId) { List> tablesToCheck = new ArrayList>(); + List vnet = new ArrayList(); + vnet.add(0, "op_dc_vnet_alloc"); + vnet.add(1, "physical_network_id"); + vnet.add(2, "there are allocated vnets for this physical network"); + tablesToCheck.add(vnet); + List networks = new ArrayList(); networks.add(0, "networks"); networks.add(1, "physical_network_id"); @@ -3736,24 +3752,8 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag publicIP.add(1, "data_center_id"); publicIP.add(2, "there are public IP addresses allocated for this zone"); tablesToCheck.add(publicIP); - - List vmInstance = new ArrayList(); - vmInstance.add(0, "vm_instance"); - vmInstance.add(1, "data_center_id"); - vmInstance.add(2, "there are virtual machines running in this zone"); - tablesToCheck.add(vmInstance); - - List volumes = new ArrayList(); - volumes.add(0, "volumes"); - volumes.add(1, "data_center_id"); - volumes.add(2, "there are storage volumes for this zone"); - tablesToCheck.add(volumes);*/ - - List vnet = new ArrayList(); - vnet.add(0, "op_dc_vnet_alloc"); - vnet.add(1, "physical_network_id"); - vnet.add(2, "there are allocated vnets for this physical network"); - tablesToCheck.add(vnet); + */ + for (List table : tablesToCheck) { String tableName = table.get(0); @@ -3764,6 +3764,10 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag String selectSql = "SELECT * FROM `" + dbName + "`.`" + tableName + "` WHERE " + column + " = ?"; + if (tableName.equals("networks")) { + selectSql += " AND removed is NULL"; + } + if (tableName.equals("op_dc_vnet_alloc")) { selectSql += " AND taken IS NOT NULL"; } @@ -3776,14 +3780,6 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag selectSql += " AND taken IS NOT NULL"; } - if (tableName.equals("host_pod_ref") || tableName.equals("host") || tableName.equals("volumes")) { - selectSql += " AND removed is NULL"; - } - - if (tableName.equals("vm_instance")) { - selectSql += " AND state != '" + VirtualMachine.State.Expunging.toString() + "'"; - } - Transaction txn = Transaction.currentTxn(); try { PreparedStatement stmt = txn.prepareAutoCloseStatement(selectSql); @@ -3896,7 +3892,10 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag } if(enabled){ - //TODO: need to check if the provider is ready for the physical network. + //TODO: need to check if the provider element is ready for the physical network. + String elementName = s_providerToNetworkElementMap.get(provider.getProviderName()); + NetworkElement element = _networkElements.get(elementName); + //element.isReady(); provider.setState(PhysicalNetworkServiceProvider.State.Enabled); }else{ //do we need to do anything for the provider instances before disabling? diff --git a/server/src/com/cloud/network/dao/NetworkDao.java b/server/src/com/cloud/network/dao/NetworkDao.java index 001df77b9f7..d2cdb39799b 100644 --- a/server/src/com/cloud/network/dao/NetworkDao.java +++ b/server/src/com/cloud/network/dao/NetworkDao.java @@ -69,5 +69,7 @@ public interface NetworkDao extends GenericDao { List listByPhysicalNetwork(long physicalNetworkId); + List listByPhysicalNetworkIncludingRemoved(long physicalNetworkId); + List listSecurityGroupEnabledNetworks(); } diff --git a/server/src/com/cloud/network/dao/NetworkDaoImpl.java b/server/src/com/cloud/network/dao/NetworkDaoImpl.java index ba708971189..c77d93b32c3 100644 --- a/server/src/com/cloud/network/dao/NetworkDaoImpl.java +++ b/server/src/com/cloud/network/dao/NetworkDaoImpl.java @@ -347,5 +347,12 @@ public class NetworkDaoImpl extends GenericDaoBase implements N sc.setParameters("isSgEnabled", true); return listBy(sc); } + + @Override + public List listByPhysicalNetworkIncludingRemoved(long physicalNetworkId) { + SearchCriteria sc = PhysicalNetworkSearch.create(); + sc.setParameters("physicalNetworkId", physicalNetworkId); + return listIncludingRemovedBy(sc); + } } diff --git a/server/src/com/cloud/network/dao/PhysicalNetworkServiceProviderDao.java b/server/src/com/cloud/network/dao/PhysicalNetworkServiceProviderDao.java index b41e022c7aa..128add7718d 100644 --- a/server/src/com/cloud/network/dao/PhysicalNetworkServiceProviderDao.java +++ b/server/src/com/cloud/network/dao/PhysicalNetworkServiceProviderDao.java @@ -23,4 +23,6 @@ import com.cloud.utils.db.GenericDao; public interface PhysicalNetworkServiceProviderDao extends GenericDao { List listBy(long physicalNetworkId); + + void deleteProviders(long physicalNetworkId); } diff --git a/server/src/com/cloud/network/dao/PhysicalNetworkServiceProviderDaoImpl.java b/server/src/com/cloud/network/dao/PhysicalNetworkServiceProviderDaoImpl.java index 0bb9b24fcec..0a373510a48 100644 --- a/server/src/com/cloud/network/dao/PhysicalNetworkServiceProviderDaoImpl.java +++ b/server/src/com/cloud/network/dao/PhysicalNetworkServiceProviderDaoImpl.java @@ -45,5 +45,12 @@ public class PhysicalNetworkServiceProviderDaoImpl extends GenericDaoBase sc = physicalNetworkSearch.create(); + sc.setParameters("physicalNetworkId", physicalNetworkId); + remove(sc); + } } diff --git a/server/src/com/cloud/network/element/BareMetalElement.java b/server/src/com/cloud/network/element/BareMetalElement.java index 37fa43b2d3e..23c8f7ecdc2 100644 --- a/server/src/com/cloud/network/element/BareMetalElement.java +++ b/server/src/com/cloud/network/element/BareMetalElement.java @@ -61,7 +61,7 @@ public class BareMetalElement extends AdapterBase implements NetworkElement { @Override public Provider getProvider() { - return Provider.ExternalDhcpServer; + return null; } @Override diff --git a/server/src/com/cloud/network/element/RedundantVirtualRouterElement.java b/server/src/com/cloud/network/element/RedundantVirtualRouterElement.java index 4e5ae3ad771..b1d5811e24f 100644 --- a/server/src/com/cloud/network/element/RedundantVirtualRouterElement.java +++ b/server/src/com/cloud/network/element/RedundantVirtualRouterElement.java @@ -37,6 +37,11 @@ public class RedundantVirtualRouterElement extends VirtualRouterElement implemen @Inject NetworkManager _networkMgr; @Inject VirtualRouterElementsDao _vrElementsDao; + @Override + public Provider getProvider() { + return Provider.RedundantVirtualRouter; + } + private boolean canHandle(Type networkType, long offeringId) { boolean result = (networkType == Network.Type.Isolated && _networkMgr.isProviderSupported(offeringId, Service.Gateway, Provider.VirtualRouter)); if (!result) { From 780e0efe79fa5eda6faedfc556e99acd54c291e1 Mon Sep 17 00:00:00 2001 From: prachi Date: Mon, 24 Oct 2011 17:59:52 -0700 Subject: [PATCH 028/159] Removing references to DataCenter - providers, using the networkoffering -> providers map instead. TODO: - Still leaving the provider columns in data_center schema as-is for CloudKit and BareMetal - ExternalNetworkDeviceMgrImpl still needs to fix the dataCenter.setProviders calls and externalNetworkApplicance usage checks to see if zone has external networking. --- api/src/com/cloud/network/NetworkService.java | 2 - server/src/com/cloud/dc/DataCenterVO.java | 4 +- .../ExternalNetworkDeviceManagerImpl.java | 43 ++++-- .../src/com/cloud/network/NetworkManager.java | 7 +- .../com/cloud/network/NetworkManagerImpl.java | 140 ++++++++++-------- .../F5ExternalLoadBalancerElement.java | 8 +- .../JuniperSRXExternalFirewallElement.java | 3 +- .../NetscalerExternalLoadBalancerElement.java | 8 +- .../network/firewall/FirewallManagerImpl.java | 4 +- .../guru/ExternalGuestNetworkGuru.java | 12 +- .../dao/NetworkOfferingServiceMapDaoImpl.java | 1 + .../src/com/cloud/vm/UserVmManagerImpl.java | 9 +- 12 files changed, 135 insertions(+), 106 deletions(-) diff --git a/api/src/com/cloud/network/NetworkService.java b/api/src/com/cloud/network/NetworkService.java index 1faba4ccc00..9e99c60bdf2 100644 --- a/api/src/com/cloud/network/NetworkService.java +++ b/api/src/com/cloud/network/NetworkService.java @@ -74,8 +74,6 @@ public interface NetworkService { NetworkProfile convertNetworkToNetworkProfile(long networkId); - Map> getZoneCapabilities(long zoneId); - Map> getNetworkCapabilities(long networkId, long zoneId); boolean isNetworkAvailableInDomain(long networkId, long domainId); diff --git a/server/src/com/cloud/dc/DataCenterVO.java b/server/src/com/cloud/dc/DataCenterVO.java index 45b9491cd84..8732e0c737e 100644 --- a/server/src/com/cloud/dc/DataCenterVO.java +++ b/server/src/com/cloud/dc/DataCenterVO.java @@ -165,7 +165,7 @@ public class DataCenterVO implements DataCenter { public void setFirewallProvider(String firewallProvider) { this.firewallProvider = firewallProvider; } - + public DataCenterVO(long id, String name, String description, String dns1, String dns2, String dns3, String dns4, String guestCidr, String domain, Long domainId, NetworkType zoneType, String zoneToken, String domainSuffix) { this(name, description, dns1, dns2, dns3, dns4, guestCidr, domain, domainId, zoneType, zoneToken, domainSuffix); this.id = id; @@ -221,7 +221,7 @@ public class DataCenterVO implements DataCenter { public void setUserDataProvider(String userDataProvider) { this.userDataProvider = userDataProvider; } - + @Override public Long getDomainId() { return domainId; diff --git a/server/src/com/cloud/network/ExternalNetworkDeviceManagerImpl.java b/server/src/com/cloud/network/ExternalNetworkDeviceManagerImpl.java index e3688fae8cb..2e96eb6ec2a 100644 --- a/server/src/com/cloud/network/ExternalNetworkDeviceManagerImpl.java +++ b/server/src/com/cloud/network/ExternalNetworkDeviceManagerImpl.java @@ -190,9 +190,9 @@ public class ExternalNetworkDeviceManagerImpl implements ExternalNetworkDeviceMa return zoneId + "-" + name + "-" + ip; } - protected HostVO getExternalNetworkAppliance(long zoneId, Host.Type type) { + protected HostVO getExternalNetworkAppliance(long zoneId, long networkOfferingId, Host.Type type) { DataCenterVO zone = _dcDao.findById(zoneId); - if (!_networkMgr.zoneIsConfiguredForExternalNetworking(zoneId)) { + if (!_networkMgr.networkIsConfiguredForExternalNetworking(zoneId, networkOfferingId)) { s_logger.debug("Zone " + zone.getName() + " is not configured for external networking."); return null; } else { @@ -389,7 +389,7 @@ public class ExternalNetworkDeviceManagerImpl implements ExternalNetworkDeviceMa // Find the external load balancer in this zone long zoneId = guestConfig.getDataCenterId(); DataCenterVO zone = _dcDao.findById(zoneId); - HostVO externalLoadBalancer = getExternalNetworkAppliance(zoneId, Host.Type.ExternalLoadBalancer); + HostVO externalLoadBalancer = getExternalNetworkAppliance(zoneId, guestConfig.getNetworkOfferingId(), Host.Type.ExternalLoadBalancer); if (externalLoadBalancer == null) { return false; @@ -433,7 +433,7 @@ public class ExternalNetworkDeviceManagerImpl implements ExternalNetworkDeviceMa // Find the external load balancer in this zone long zoneId = network.getDataCenterId(); DataCenterVO zone = _dcDao.findById(zoneId); - HostVO externalLoadBalancer = getExternalNetworkAppliance(zoneId, Host.Type.ExternalLoadBalancer); + HostVO externalLoadBalancer = getExternalNetworkAppliance(zoneId, network.getNetworkOfferingId(), Host.Type.ExternalLoadBalancer); if (externalLoadBalancer == null) { return false; @@ -443,7 +443,7 @@ public class ExternalNetworkDeviceManagerImpl implements ExternalNetworkDeviceMa boolean externalLoadBalancerIsInline = externalLoadBalancerIsInline(externalLoadBalancer); HostVO externalFirewall = null; if (externalLoadBalancerIsInline) { - externalFirewall = getExternalNetworkAppliance(zoneId, Host.Type.ExternalFirewall); + externalFirewall = getExternalNetworkAppliance(zoneId, network.getNetworkOfferingId(), Host.Type.ExternalFirewall); if (externalFirewall == null) { String msg = "External load balancer in zone " + zone.getName() + " is inline, but no external firewall in this zone."; s_logger.error(msg); @@ -675,7 +675,9 @@ public class ExternalNetworkDeviceManagerImpl implements ExternalNetworkDeviceMa Host externalFirewall = _agentMgr.addHost(zoneId, resource, Host.Type.ExternalFirewall, hostDetails); if (externalFirewall != null) { - zone.setFirewallProvider(Network.Provider.JuniperSRX.getName()); + /* With NAAS, we no longer store default global providers with Zone. + * + zone.setFirewallProvider(Network.Provider.JuniperSRX.getName()); zone.setUserDataProvider(Network.Provider.DhcpServer.getName()); zone.setVpnProvider(null); @@ -695,7 +697,7 @@ public class ExternalNetworkDeviceManagerImpl implements ExternalNetworkDeviceMa zone.setLoadBalancerProvider(Network.Provider.None.getName()); } - _dcDao.update(zone.getId(), zone); + _dcDao.update(zone.getId(), zone);*/ return externalFirewall; } else { return null; @@ -717,7 +719,9 @@ public class ExternalNetworkDeviceManagerImpl implements ExternalNetworkDeviceMa try { if (_agentMgr.maintain(hostId) && _agentMgr.deleteHost(hostId, false, false, caller)) { - DataCenterVO zone = _dcDao.findById(externalFirewall.getDataCenterId()); + /* With NAAS, we do not have the concept of global providers stored with Zone + * + * DataCenterVO zone = _dcDao.findById(externalFirewall.getDataCenterId()); zone.setFirewallProvider(Network.Provider.VirtualRouter.getName()); zone.setUserDataProvider(Network.Provider.VirtualRouter.getName()); zone.setVpnProvider(Network.Provider.VirtualRouter.getName()); @@ -742,7 +746,8 @@ public class ExternalNetworkDeviceManagerImpl implements ExternalNetworkDeviceMa } } - return _dcDao.update(zone.getId(), zone); + return _dcDao.update(zone.getId(), zone);*/ + return true; } else { return false; } @@ -796,7 +801,7 @@ public class ExternalNetworkDeviceManagerImpl implements ExternalNetworkDeviceMa // Find the external firewall in this zone long zoneId = network.getDataCenterId(); DataCenterVO zone = _dcDao.findById(zoneId); - HostVO externalFirewall = getExternalNetworkAppliance(zoneId, Host.Type.ExternalFirewall); + HostVO externalFirewall = getExternalNetworkAppliance(zoneId, network.getNetworkOfferingId(), Host.Type.ExternalFirewall); if (externalFirewall == null) { return false; @@ -877,7 +882,7 @@ public class ExternalNetworkDeviceManagerImpl implements ExternalNetworkDeviceMa // Find the external firewall in this zone long zoneId = network.getDataCenterId(); DataCenterVO zone = _dcDao.findById(zoneId); - HostVO externalFirewall = getExternalNetworkAppliance(zoneId, Host.Type.ExternalFirewall); + HostVO externalFirewall = getExternalNetworkAppliance(zoneId, network.getNetworkOfferingId(), Host.Type.ExternalFirewall); if (externalFirewall == null) { return false; @@ -947,7 +952,7 @@ public class ExternalNetworkDeviceManagerImpl implements ExternalNetworkDeviceMa public boolean manageRemoteAccessVpn(boolean create, Network network, RemoteAccessVpn vpn) throws ResourceUnavailableException { - HostVO externalFirewall = getExternalNetworkAppliance(network.getDataCenterId(), Host.Type.ExternalFirewall); + HostVO externalFirewall = getExternalNetworkAppliance(network.getDataCenterId(), network.getNetworkOfferingId(), Host.Type.ExternalFirewall); if (externalFirewall == null) { return false; @@ -986,7 +991,7 @@ public class ExternalNetworkDeviceManagerImpl implements ExternalNetworkDeviceMa } public boolean manageRemoteAccessVpnUsers(Network network, RemoteAccessVpn vpn, List vpnUsers) throws ResourceUnavailableException { - HostVO externalFirewall = getExternalNetworkAppliance(network.getDataCenterId(), Host.Type.ExternalFirewall); + HostVO externalFirewall = getExternalNetworkAppliance(network.getDataCenterId(), network.getNetworkOfferingId(), Host.Type.ExternalFirewall); if (externalFirewall == null) { return false; @@ -1271,14 +1276,20 @@ public class ExternalNetworkDeviceManagerImpl implements ExternalNetworkDeviceMa s_logger.debug("External network stats collector is running..."); for (DataCenterVO zone : _dcDao.listAll()) { // Make sure the zone is configured for external networking - if (!_networkMgr.zoneIsConfiguredForExternalNetworking(zone.getId())) { + + //FIXME: add another way to check if zone has external networking. + + if (!_networkMgr.zoneIsConfiguredForExternalNetworking(zone.getId())) { s_logger.debug("Zone " + zone.getName() + " is not configured for external networking, so skipping usage check."); continue; } // Only collect stats if there is an external firewall in this zone - HostVO externalFirewall = getExternalNetworkAppliance(zone.getId(), Host.Type.ExternalFirewall); - HostVO externalLoadBalancer = getExternalNetworkAppliance(zone.getId(), Host.Type.ExternalLoadBalancer); + + //FIXME: add another way to check if zone has external networking. + + HostVO externalFirewall = getExternalNetworkAppliance(zone.getId(), 0, Host.Type.ExternalFirewall); + HostVO externalLoadBalancer = getExternalNetworkAppliance(zone.getId(), 0, Host.Type.ExternalLoadBalancer); if (externalFirewall == null) { s_logger.debug("Skipping usage check for zone " + zone.getName()); diff --git a/server/src/com/cloud/network/NetworkManager.java b/server/src/com/cloud/network/NetworkManager.java index b9d41423359..38285f1ee28 100644 --- a/server/src/com/cloud/network/NetworkManager.java +++ b/server/src/com/cloud/network/NetworkManager.java @@ -187,10 +187,13 @@ public interface NetworkManager extends NetworkService { Nic getDefaultNic(long vmId); List getPasswordResetElements(); - + + @Deprecated boolean zoneIsConfiguredForExternalNetworking(long zoneId); + + boolean networkIsConfiguredForExternalNetworking(long zoneId, long networkOfferingId); - Map getServiceCapabilities(long zoneId, Long networkOfferingId, Service service); + Map getServiceCapabilities(Long networkOfferingId, Service service); boolean applyIpAssociations(Network network, boolean continueOnError) throws ResourceUnavailableException; diff --git a/server/src/com/cloud/network/NetworkManagerImpl.java b/server/src/com/cloud/network/NetworkManagerImpl.java index 57a1cc25be6..212df37fe69 100755 --- a/server/src/com/cloud/network/NetworkManagerImpl.java +++ b/server/src/com/cloud/network/NetworkManagerImpl.java @@ -28,7 +28,6 @@ import java.util.Comparator; import java.util.Date; import java.util.HashMap; import java.util.HashSet; -import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Random; @@ -270,6 +269,12 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag private static HashMap> s_serviceToImplementedProvidersMap = new HashMap>(); private static HashMap s_providerToNetworkElementMap = new HashMap(); + private NetworkElement getElementImplementingProvider(String providerName){ + String elementName = s_providerToNetworkElementMap.get(providerName); + NetworkElement element = _networkElements.get(elementName); + return element; + } + @Override public PublicIp assignPublicIpAddress(long dcId, Long podId, Account owner, VlanType type, Long networkId, String requestedIp) throws InsufficientAddressCapacityException { return fetchNewPublicIp(dcId, podId, null, owner, type, networkId, false, true, requestedIp); @@ -1794,7 +1799,7 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag // If networkDomain is not specified, take it from the global configuration if (isServiceSupportedByNetworkOffering(networkOfferingId, Service.Dns)) { - Map dnsCapabilities = getServiceCapabilities(zoneId, networkOfferingId, Service.Dns); + Map dnsCapabilities = getServiceCapabilities(networkOfferingId, Service.Dns); String isUpdateDnsSupported = dnsCapabilities.get(Capability.AllowDnsSuffixModification); if (isUpdateDnsSupported == null || !Boolean.valueOf(isUpdateDnsSupported)) { if (networkDomain != null) { @@ -2600,65 +2605,30 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag return _networksDao.getActiveNicsIn(networkId); } - @Override - public Map> getZoneCapabilities(long zoneId) { - DataCenterVO dc = _dcDao.findById(zoneId); - if (dc == null) { - throw new InvalidParameterValueException("Zone id=" + zoneId + " doesn't exist in the system."); - } - - // Get all service providers from the datacenter - Map providers = new HashMap(); - providers.put(Service.Firewall, dc.getFirewallProvider()); - providers.put(Service.Lb, dc.getLoadBalancerProvider()); - providers.put(Service.Vpn, dc.getVpnProvider()); - providers.put(Service.Dns, dc.getDnsProvider()); - providers.put(Service.Gateway, dc.getGatewayProvider()); - providers.put(Service.UserData, dc.getUserDataProvider()); - providers.put(Service.Dhcp, dc.getDhcpProvider()); - - Map> zoneCapabilities = new HashMap>(); - - for (NetworkElement element : _networkElements) { - if (providers.isEmpty()) { - break; - } - Map> elementCapabilities = element.getCapabilities(); - if (elementCapabilities != null) { - Iterator it = providers.keySet().iterator(); - while (it.hasNext()) { - Service service = it.next(); - String zoneProvider = providers.get(service); - if (zoneProvider != null) { - if (zoneProvider.equalsIgnoreCase(element.getProvider().getName())) { - if (elementCapabilities.containsKey(service)) { - Map capabilities = elementCapabilities.get(service); - // Verify if Service support capability - if (capabilities != null) { - for (Capability capability : capabilities.keySet()) { - assert (service.containsCapability(capability)) : "Capability " + capability.getName() + " is not supported by the service " + service.getName(); - } - } - zoneCapabilities.put(service, capabilities); - it.remove(); - } - } - } - } - } - } - return zoneCapabilities; - } - + @Override public Map> getNetworkCapabilities(long networkOfferingId, long zoneId) { - Map> zoneCapabilities = getZoneCapabilities(zoneId); Map> networkCapabilities = new HashMap>(); - for (Service service : zoneCapabilities.keySet()) { - if (isServiceSupportedByNetworkOffering(networkOfferingId, service)) { - networkCapabilities.put(service, zoneCapabilities.get(service)); + //list all services of this networkOffering + List servicesMap = _ntwkOfferingSrvcDao.getServices(networkOfferingId); + for(NetworkOfferingServiceMapVO instance : servicesMap ){ + Service service = Service.getService(instance.getService()); + //FIXME what if a service has multiple providers in the same networkOffering? + if(networkCapabilities.containsKey(service)){ + if(s_logger.isDebugEnabled()){ + s_logger.debug("Network Offering: "+ networkOfferingId +" has multiple Providers associated for this Service:"+service.getName()); + s_logger.debug("Returning the capabilities of the first Provider"); + } + continue; + } + NetworkElement element = getElementImplementingProvider(instance.getProvider()); + if(element != null){ + Map> elementCapabilities = element.getCapabilities();; + if (elementCapabilities != null && elementCapabilities.get(service) != null) { + networkCapabilities.put(service, elementCapabilities.get(instance.getService())); + } } } @@ -2666,18 +2636,35 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag } @Override - public Map getServiceCapabilities(long zoneId, Long networkOfferingId, Service service) { + public Map getServiceCapabilities(Long networkOfferingId, Service service) { if (!isServiceSupportedByNetworkOffering(networkOfferingId, service)) { throw new UnsupportedServiceException("Service " + service.getName() + " is not supported by the network offering id=" + networkOfferingId); } + + Map serviceCapabilities = new HashMap(); - Map> networkCapabilities = getZoneCapabilities(zoneId); - if (networkCapabilities.get(service) == null) { - throw new UnsupportedServiceException("Service " + service.getName() + " is not supported in zone id=" + zoneId); + //get the Provider for this Service for this offering + List serviceProviderNames = _ntwkOfferingSrvcDao.getProvidersForService(networkOfferingId, service); + + //FIXME we return the capabilities of the first provider of the service - what if we have multiple providers for same Service? + if(serviceProviderNames != null && !serviceProviderNames.isEmpty()){ + NetworkElement element = getElementImplementingProvider(serviceProviderNames.get(0)); + if(element != null){ + Map> elementCapabilities = element.getCapabilities();; + + if (elementCapabilities == null || elementCapabilities.get(service) == null) { + throw new UnsupportedServiceException("Service " + service.getName() + " is not supported by the element=" + element.getName() + " implementing Provider=" + serviceProviderNames.get(0)); + } + serviceCapabilities = elementCapabilities.get(service); + } + }else{ + if(s_logger.isDebugEnabled()){ + s_logger.debug("Network Offering: "+ networkOfferingId +" does not have any Providers associated for this Service:"+service.getName()); + } } - - return networkCapabilities.get(service); + + return serviceCapabilities; } @Override @@ -2907,6 +2894,8 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag } @Override + @Deprecated + // try to use the method networkIsConfiguredForExternalNetworking instead public boolean zoneIsConfiguredForExternalNetworking(long zoneId) { DataCenterVO zone = _dcDao.findById(zoneId); @@ -2925,6 +2914,28 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag } } + + @Override + public boolean networkIsConfiguredForExternalNetworking(long zoneId, long networkOfferingId) { + DataCenterVO zone = _dcDao.findById(zoneId); + + boolean usesJuniperForGatewayService = _ntwkOfferingSrvcDao.isProviderSupported(networkOfferingId, Service.Gateway, Network.Provider.JuniperSRX); + boolean usesJuniperForFirewallService = _ntwkOfferingSrvcDao.isProviderSupported(networkOfferingId, Service.Firewall, Network.Provider.JuniperSRX); + boolean usesNetscalarForLBService = _ntwkOfferingSrvcDao.isProviderSupported(networkOfferingId, Service.Lb, Network.Provider.NetscalerMPX); + + if (zone.getNetworkType() == NetworkType.Advanced) { + if (usesJuniperForGatewayService && usesJuniperForFirewallService) { + return true; + } else if (_ntwkOfferingSrvcDao.isServiceSupported(networkOfferingId, Service.Gateway) && usesNetscalarForLBService) { + return true; + } else { + return false; + } + } else { + return usesJuniperForFirewallService; + } + + } @Override public boolean isServiceSupportedByNetworkOffering(long networkOfferingId, Network.Service service) { @@ -3134,7 +3145,7 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag } - Map dnsCapabilities = getServiceCapabilities(network.getDataCenterId(), network.getNetworkOfferingId(), Service.Dns); + Map dnsCapabilities = getServiceCapabilities(network.getNetworkOfferingId(), Service.Dns); String isUpdateDnsSupported = dnsCapabilities.get(Capability.AllowDnsSuffixModification); if (isUpdateDnsSupported == null || !Boolean.valueOf(isUpdateDnsSupported)) { throw new InvalidParameterValueException("Domain name change is not supported for network id=" + network.getNetworkOfferingId() + " in zone id=" + network.getDataCenterId()); @@ -3893,8 +3904,7 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag if(enabled){ //TODO: need to check if the provider element is ready for the physical network. - String elementName = s_providerToNetworkElementMap.get(provider.getProviderName()); - NetworkElement element = _networkElements.get(elementName); + NetworkElement element = getElementImplementingProvider(provider.getProviderName()); //element.isReady(); provider.setState(PhysicalNetworkServiceProvider.State.Enabled); }else{ diff --git a/server/src/com/cloud/network/element/F5ExternalLoadBalancerElement.java b/server/src/com/cloud/network/element/F5ExternalLoadBalancerElement.java index 4208556386e..9a9c62d8018 100644 --- a/server/src/com/cloud/network/element/F5ExternalLoadBalancerElement.java +++ b/server/src/com/cloud/network/element/F5ExternalLoadBalancerElement.java @@ -41,10 +41,9 @@ import com.cloud.network.Network.Provider; import com.cloud.network.Network.Service; import com.cloud.network.NetworkManager; import com.cloud.network.Networks.TrafficType; -import com.cloud.network.PublicIpAddress; import com.cloud.network.rules.FirewallRule; -import com.cloud.network.rules.StaticNat; import com.cloud.offering.NetworkOffering; +import com.cloud.offerings.dao.NetworkOfferingServiceMapDao; import com.cloud.utils.component.AdapterBase; import com.cloud.utils.component.Inject; import com.cloud.vm.NicProfile; @@ -60,6 +59,7 @@ public class F5ExternalLoadBalancerElement extends AdapterBase implements LoadBa @Inject NetworkManager _networkManager; @Inject ExternalNetworkDeviceManager _externalNetworkManager; @Inject ConfigurationManager _configMgr; + @Inject NetworkOfferingServiceMapDao _ntwkOfferingSrvcDao; private boolean canHandle(Network config) { DataCenter zone = _configMgr.getZone(config.getDataCenterId()); @@ -68,8 +68,8 @@ public class F5ExternalLoadBalancerElement extends AdapterBase implements LoadBa return false; } - return (_networkManager.zoneIsConfiguredForExternalNetworking(zone.getId()) && - zone.getLoadBalancerProvider() != null && zone.getLoadBalancerProvider().equals(Network.Provider.F5BigIp.getName())); + return (_networkManager.networkIsConfiguredForExternalNetworking(zone.getId(), config.getNetworkOfferingId()) && + _ntwkOfferingSrvcDao.isProviderSupported(config.getNetworkOfferingId(), Service.Lb, Network.Provider.F5BigIp)); } @Override diff --git a/server/src/com/cloud/network/element/JuniperSRXExternalFirewallElement.java b/server/src/com/cloud/network/element/JuniperSRXExternalFirewallElement.java index 537454c26fa..feea82cd6d0 100644 --- a/server/src/com/cloud/network/element/JuniperSRXExternalFirewallElement.java +++ b/server/src/com/cloud/network/element/JuniperSRXExternalFirewallElement.java @@ -47,7 +47,6 @@ import com.cloud.network.RemoteAccessVpn; import com.cloud.network.VpnUser; import com.cloud.network.dao.NetworkDao; import com.cloud.network.rules.FirewallRule; -import com.cloud.network.rules.StaticNat; import com.cloud.offering.NetworkOffering; import com.cloud.offerings.NetworkOfferingVO; import com.cloud.offerings.dao.NetworkOfferingDao; @@ -79,7 +78,7 @@ public class JuniperSRXExternalFirewallElement extends AdapterBase implements So return false; } - return _networkManager.zoneIsConfiguredForExternalNetworking(zone.getId()); + return _networkManager.networkIsConfiguredForExternalNetworking(zone.getId(),config.getNetworkOfferingId()); } @Override diff --git a/server/src/com/cloud/network/element/NetscalerExternalLoadBalancerElement.java b/server/src/com/cloud/network/element/NetscalerExternalLoadBalancerElement.java index e1393694428..352c26a48fe 100644 --- a/server/src/com/cloud/network/element/NetscalerExternalLoadBalancerElement.java +++ b/server/src/com/cloud/network/element/NetscalerExternalLoadBalancerElement.java @@ -41,10 +41,9 @@ import com.cloud.network.Network.Provider; import com.cloud.network.Network.Service; import com.cloud.network.NetworkManager; import com.cloud.network.Networks.TrafficType; -import com.cloud.network.PublicIpAddress; import com.cloud.network.rules.FirewallRule; -import com.cloud.network.rules.StaticNat; import com.cloud.offering.NetworkOffering; +import com.cloud.offerings.dao.NetworkOfferingServiceMapDao; import com.cloud.utils.component.AdapterBase; import com.cloud.utils.component.Inject; import com.cloud.vm.NicProfile; @@ -60,6 +59,7 @@ public class NetscalerExternalLoadBalancerElement extends AdapterBase implements @Inject NetworkManager _networkManager; @Inject ExternalNetworkDeviceManager _externalNetworkManager; @Inject ConfigurationManager _configMgr; + @Inject NetworkOfferingServiceMapDao _ntwkOfferingSrvcDao; private boolean canHandle(Network config) { DataCenter zone = _configMgr.getZone(config.getDataCenterId()); @@ -68,8 +68,8 @@ public class NetscalerExternalLoadBalancerElement extends AdapterBase implements return false; } - return (_networkManager.zoneIsConfiguredForExternalNetworking(zone.getId()) && - zone.getLoadBalancerProvider() != null && zone.getLoadBalancerProvider().equals(Network.Provider.NetscalerMPX.getName())); + return (_networkManager.networkIsConfiguredForExternalNetworking(zone.getId(), config.getNetworkOfferingId()) && + _ntwkOfferingSrvcDao.isProviderSupported(config.getNetworkOfferingId(), Service.Lb, Network.Provider.NetscalerMPX)); } @Override diff --git a/server/src/com/cloud/network/firewall/FirewallManagerImpl.java b/server/src/com/cloud/network/firewall/FirewallManagerImpl.java index a35fd5956ed..69e26bc42d1 100644 --- a/server/src/com/cloud/network/firewall/FirewallManagerImpl.java +++ b/server/src/com/cloud/network/firewall/FirewallManagerImpl.java @@ -358,10 +358,10 @@ public class FirewallManagerImpl implements FirewallService, FirewallManager, Ma if (purpose == Purpose.LoadBalancing) { if (!_elbEnabled) { - protocolCapabilities = _networkMgr.getServiceCapabilities(network.getDataCenterId(), network.getNetworkOfferingId(), Service.Lb); + protocolCapabilities = _networkMgr.getServiceCapabilities(network.getNetworkOfferingId(), Service.Lb); } } else { - protocolCapabilities = _networkMgr.getServiceCapabilities(network.getDataCenterId(), network.getNetworkOfferingId(), Service.Firewall); + protocolCapabilities = _networkMgr.getServiceCapabilities(network.getNetworkOfferingId(), Service.Firewall); } if (protocolCapabilities != null) { diff --git a/server/src/com/cloud/network/guru/ExternalGuestNetworkGuru.java b/server/src/com/cloud/network/guru/ExternalGuestNetworkGuru.java index 5bca18cecaa..1760f20f36d 100644 --- a/server/src/com/cloud/network/guru/ExternalGuestNetworkGuru.java +++ b/server/src/com/cloud/network/guru/ExternalGuestNetworkGuru.java @@ -88,7 +88,7 @@ public class ExternalGuestNetworkGuru extends GuestNetworkGuru { NetworkVO config = (NetworkVO) super.design(offering, plan, userSpecified, owner); if (config == null) { return null; - } else if (_networkMgr.zoneIsConfiguredForExternalNetworking(plan.getDataCenterId())) { + } else if (_networkMgr.networkIsConfiguredForExternalNetworking(plan.getDataCenterId(), config.getNetworkOfferingId())) { config.setState(State.Allocated); } @@ -103,7 +103,7 @@ public class ExternalGuestNetworkGuru extends GuestNetworkGuru { return null; } - if (!_networkMgr.zoneIsConfiguredForExternalNetworking(config.getDataCenterId())) { + if (!_networkMgr.networkIsConfiguredForExternalNetworking(config.getDataCenterId(), config.getNetworkOfferingId())) { return super.implement(config, offering, dest, context); } @@ -176,7 +176,7 @@ public class ExternalGuestNetworkGuru extends GuestNetworkGuru { public NicProfile allocate(Network config, NicProfile nic, VirtualMachineProfile vm) throws InsufficientVirtualNetworkCapcityException, InsufficientAddressCapacityException { - if (_networkMgr.zoneIsConfiguredForExternalNetworking(config.getDataCenterId()) && nic != null && nic.getRequestedIp() != null) { + if (_networkMgr.networkIsConfiguredForExternalNetworking(config.getDataCenterId(), config.getNetworkOfferingId()) && nic != null && nic.getRequestedIp() != null) { throw new CloudRuntimeException("Does not support custom ip allocation at this time: " + nic); } @@ -204,7 +204,7 @@ public class ExternalGuestNetworkGuru extends GuestNetworkGuru { return; } - if (_networkMgr.zoneIsConfiguredForExternalNetworking(config.getDataCenterId())) { + if (_networkMgr.networkIsConfiguredForExternalNetworking(config.getDataCenterId(), config.getNetworkOfferingId())) { nic.setIp4Address(null); nic.setGateway(null); nic.setNetmask(null); @@ -221,7 +221,7 @@ public class ExternalGuestNetworkGuru extends GuestNetworkGuru { return; } DataCenter dc = _dcDao.findById(config.getDataCenterId()); - if (_networkMgr.zoneIsConfiguredForExternalNetworking(config.getDataCenterId())) { + if (_networkMgr.networkIsConfiguredForExternalNetworking(config.getDataCenterId(), config.getNetworkOfferingId())) { nic.setBroadcastUri(config.getBroadcastUri()); nic.setIsolationUri(config.getBroadcastUri()); nic.setDns1(dc.getDns1()); @@ -255,7 +255,7 @@ public class ExternalGuestNetworkGuru extends GuestNetworkGuru { } NetworkVO network = _networkDao.findById(nic.getNetworkId()); - if (network != null && _networkMgr.zoneIsConfiguredForExternalNetworking(network.getDataCenterId())) { + if (network != null && _networkMgr.networkIsConfiguredForExternalNetworking(network.getDataCenterId(), network.getNetworkOfferingId())) { return true; } else { return super.release(nic, vm, reservationId); diff --git a/server/src/com/cloud/offerings/dao/NetworkOfferingServiceMapDaoImpl.java b/server/src/com/cloud/offerings/dao/NetworkOfferingServiceMapDaoImpl.java index 5aa825bc9f1..b033bd89993 100644 --- a/server/src/com/cloud/offerings/dao/NetworkOfferingServiceMapDaoImpl.java +++ b/server/src/com/cloud/offerings/dao/NetworkOfferingServiceMapDaoImpl.java @@ -74,6 +74,7 @@ public class NetworkOfferingServiceMapDaoImpl extends GenericDaoBase getServicesForProvider(long networkOfferingId, Provider provider) { List services = new ArrayList(); diff --git a/server/src/com/cloud/vm/UserVmManagerImpl.java b/server/src/com/cloud/vm/UserVmManagerImpl.java index 8fd9ac2144d..22185fa8ba4 100755 --- a/server/src/com/cloud/vm/UserVmManagerImpl.java +++ b/server/src/com/cloud/vm/UserVmManagerImpl.java @@ -118,6 +118,7 @@ import com.cloud.hypervisor.dao.HypervisorCapabilitiesDao; import com.cloud.network.IPAddressVO; import com.cloud.network.Network; import com.cloud.network.Network.Provider; +import com.cloud.network.Network.Service; import com.cloud.network.NetworkManager; import com.cloud.network.NetworkVO; import com.cloud.network.Networks.TrafficType; @@ -139,6 +140,7 @@ import com.cloud.offering.NetworkOffering.Availability; import com.cloud.offering.ServiceOffering; import com.cloud.offerings.NetworkOfferingVO; import com.cloud.offerings.dao.NetworkOfferingDao; +import com.cloud.offerings.dao.NetworkOfferingServiceMapDao; import com.cloud.org.Cluster; import com.cloud.org.Grouping; import com.cloud.projects.Project; @@ -346,6 +348,8 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, Manager protected FirewallManager _firewallMgr; @Inject protected ProjectManager _projectMgr; + @Inject + protected NetworkOfferingServiceMapDao _ntwkOfferingSrvcDao; protected ScheduledExecutorService _executor = null; protected int _expungeInterval; @@ -2691,6 +2695,7 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, Manager List nics = _nicDao.listByVmId(vm.getId()); NicVO guestNic = null; + NetworkVO guestNetwork = null; for (NicVO nic : nics) { NetworkVO network = _networkDao.findById(nic.getNetworkId()); long isDefault = (nic.isDefaultNic()) ? 1 : 0; @@ -2699,6 +2704,7 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, Manager if (network.getTrafficType() == TrafficType.Guest) { originalIp = nic.getIp4Address(); guestNic = nic; + guestNetwork = network; } } boolean ipChanged = false; @@ -2717,7 +2723,8 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, Manager if (ipChanged) { DataCenterVO dc = _dcDao.findById(vm.getDataCenterIdToDeployIn()); UserVmVO userVm = profile.getVirtualMachine(); - if (dc.getDhcpProvider().equalsIgnoreCase(Provider.ExternalDhcpServer.getName())){ + //dc.getDhcpProvider().equalsIgnoreCase(Provider.ExternalDhcpServer.getName()) + if (_ntwkOfferingSrvcDao.isProviderSupported(guestNetwork.getNetworkOfferingId(), Service.Dhcp, Provider.ExternalDhcpServer)){ _nicDao.update(guestNic.getId(), guestNic); userVm.setPrivateIpAddress(guestNic.getIp4Address()); _vmDao.update(userVm.getId(), userVm); From 07591807af75e42ffd7d689602ffd3a7b295f19c Mon Sep 17 00:00:00 2001 From: prachi Date: Tue, 25 Oct 2011 11:39:41 -0700 Subject: [PATCH 029/159] Removing isolationMethods from UpdatePhysicalNetwork API. --- .../api/commands/CreateVlanIpRangeCmd.java | 15 +++++++++++++ .../commands/UpdatePhysicalNetworkCmd.java | 9 +------- api/src/com/cloud/network/NetworkService.java | 2 +- .../com/cloud/network/NetworkManagerImpl.java | 21 +------------------ setup/db/create-schema.sql | 9 ++++++++ 5 files changed, 27 insertions(+), 29 deletions(-) diff --git a/api/src/com/cloud/api/commands/CreateVlanIpRangeCmd.java b/api/src/com/cloud/api/commands/CreateVlanIpRangeCmd.java index 3353af834f6..aa23f51262a 100644 --- a/api/src/com/cloud/api/commands/CreateVlanIpRangeCmd.java +++ b/api/src/com/cloud/api/commands/CreateVlanIpRangeCmd.java @@ -29,6 +29,7 @@ import com.cloud.api.response.VlanIpRangeResponse; import com.cloud.dc.Vlan; import com.cloud.exception.ConcurrentOperationException; import com.cloud.exception.InsufficientCapacityException; +import com.cloud.exception.InvalidParameterValueException; import com.cloud.exception.ResourceUnavailableException; import com.cloud.user.Account; @@ -78,6 +79,20 @@ public class CreateVlanIpRangeCmd extends BaseCmd { @Parameter(name=ApiConstants.NETWORK_ID, type=CommandType.LONG, description="the network id") private Long networkID; + @Parameter(name=ApiConstants.PHYSICAL_NETWORK_ID, type=CommandType.LONG, description="the Physical Network ID") + private Long physicalNetworkId; + + public Long getPhysicalNetworkId() { + if (physicalNetworkId != null) { + return physicalNetworkId; + } else if (zoneId != null) { + return _networkService.translateZoneToPhysicalNetwork(zoneId); + } else { + throw new InvalidParameterValueException("Either zoneId or physicalNetworkId have to be specified"); + } + } + + ///////////////////////////////////////////////////// /////////////////// Accessors /////////////////////// ///////////////////////////////////////////////////// diff --git a/api/src/com/cloud/api/commands/UpdatePhysicalNetworkCmd.java b/api/src/com/cloud/api/commands/UpdatePhysicalNetworkCmd.java index 9bf826d4fcd..74398b20a42 100644 --- a/api/src/com/cloud/api/commands/UpdatePhysicalNetworkCmd.java +++ b/api/src/com/cloud/api/commands/UpdatePhysicalNetworkCmd.java @@ -52,9 +52,6 @@ public class UpdatePhysicalNetworkCmd extends BaseAsyncCmd { @Parameter(name=ApiConstants.TAGS, type=CommandType.LIST, collectionType=CommandType.STRING, description="Tag the physical network") private List tags; - @Parameter(name=ApiConstants.ISOLATION_METHODS, type=CommandType.LIST, collectionType=CommandType.STRING, description="the isolation method for the physical network[VLAN/L3/GRE]") - private List isolationMethods; - @Parameter(name=ApiConstants.STATE, type=CommandType.STRING, description="Enabled/Disabled") private String state; @@ -69,10 +66,6 @@ public class UpdatePhysicalNetworkCmd extends BaseAsyncCmd { return tags; } - public List getIsolationMethods() { - return isolationMethods; - } - public String getNetworkSpeed() { return speed; } @@ -105,7 +98,7 @@ public class UpdatePhysicalNetworkCmd extends BaseAsyncCmd { @Override public void execute(){ - PhysicalNetwork result = _networkService.updatePhysicalNetwork(getId(),getNetworkSpeed(), getIsolationMethods(), getTags(), getVlan(), getState()); + PhysicalNetwork result = _networkService.updatePhysicalNetwork(getId(),getNetworkSpeed(), getTags(), getVlan(), getState()); if (result != null) { PhysicalNetworkResponse response = _responseGenerator.createPhysicalNetworkResponse(result); response.setResponseName(getCommandName()); diff --git a/api/src/com/cloud/network/NetworkService.java b/api/src/com/cloud/network/NetworkService.java index 9e99c60bdf2..fa01ffaaa04 100644 --- a/api/src/com/cloud/network/NetworkService.java +++ b/api/src/com/cloud/network/NetworkService.java @@ -92,7 +92,7 @@ public interface NetworkService { List searchPhysicalNetworks(Long id, Long zoneId, String keyword, Long startIndex, Long pageSize); - PhysicalNetwork updatePhysicalNetwork(Long id, String networkSpeed, List isolationMethods, List tags, String newVnetRangeString, String state); + PhysicalNetwork updatePhysicalNetwork(Long id, String networkSpeed, List tags, String newVnetRangeString, String state); boolean deletePhysicalNetwork(Long id); diff --git a/server/src/com/cloud/network/NetworkManagerImpl.java b/server/src/com/cloud/network/NetworkManagerImpl.java index 212df37fe69..30627f3eba8 100755 --- a/server/src/com/cloud/network/NetworkManagerImpl.java +++ b/server/src/com/cloud/network/NetworkManagerImpl.java @@ -3573,7 +3573,7 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag @Override @DB @ActionEvent(eventType = EventTypes.EVENT_PHYSICAL_NETWORK_UPDATE, eventDescription = "updating physical network", async = true) - public PhysicalNetwork updatePhysicalNetwork(Long id, String networkSpeed, List isolationMethods, List tags, String newVnetRangeString, String state) { + public PhysicalNetwork updatePhysicalNetwork(Long id, String networkSpeed, List tags, String newVnetRangeString, String state) { // verify input parameters PhysicalNetworkVO network = _physicalNetworkDao.findById(id); @@ -3585,10 +3585,6 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag throw new InvalidParameterException("Unable to support more than one tag on network yet"); } - if (isolationMethods != null && isolationMethods.size() > 1) { - throw new InvalidParameterException("Only one isolationMethod can be specified for a physical network at this time"); - } - PhysicalNetwork.State networkState = null; if (state != null && !state.isEmpty()) { try { @@ -3606,21 +3602,6 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag network.setTags(tags); } - if (isolationMethods != null) { - for(String isMethod : isolationMethods){ - PhysicalNetwork.IsolationMethod isolationMethodVal = null; - if (isMethod != null && !isMethod.isEmpty()) { - try { - isolationMethodVal = PhysicalNetwork.IsolationMethod.valueOf(isMethod.toUpperCase()); - } catch (IllegalArgumentException ex) { - throw new InvalidParameterValueException("Unable to resolve IsolationMethod '" + isMethod + "' to a supported value {VLAN or L3 or GRE}"); - } - } - } - - network.setIsolationMethods(isolationMethods); - } - if(networkSpeed != null){ network.setSpeed(networkSpeed); } diff --git a/setup/db/create-schema.sql b/setup/db/create-schema.sql index eaa3f727fd3..5332553ec0d 100755 --- a/setup/db/create-schema.sql +++ b/setup/db/create-schema.sql @@ -1806,6 +1806,15 @@ CREATE TABLE `cloud`.`physical_network_traffic_types` ( UNIQUE KEY(`physical_network_id`, `traffic_type`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8; +CREATE TABLE `cloud`.`traffic_type_details` ( + `id` bigint unsigned NOT NULL auto_increment, + `traffic_type_id` bigint unsigned NOT NULL COMMENT 'traffic_type id', + `name` varchar(255) NOT NULL, + `value` varchar(255) NOT NULL, + PRIMARY KEY (`id`), + CONSTRAINT `fk_traffic_type_details__traffic_type_id` FOREIGN KEY (`traffic_type_id`) REFERENCES `physical_network_traffic_types`(`id`) ON DELETE CASCADE +) ENGINE=InnoDB DEFAULT CHARSET=utf8; + CREATE TABLE `cloud`.`physical_network_service_providers` ( `id` bigint unsigned NOT NULL AUTO_INCREMENT COMMENT 'id', `physical_network_id` bigint unsigned NOT NULL COMMENT 'id of the physical network', From 1c430aad44b477df5fe87d9ccad0d940d6df93db Mon Sep 17 00:00:00 2001 From: alena Date: Tue, 25 Oct 2011 09:57:46 -0700 Subject: [PATCH 030/159] Check if source nat service is enabled before acquiring the source nat ip address --- .../com/cloud/network/NetworkManagerImpl.java | 4 +-- .../VirtualNetworkApplianceManagerImpl.java | 27 +++++++++++-------- 2 files changed, 18 insertions(+), 13 deletions(-) diff --git a/server/src/com/cloud/network/NetworkManagerImpl.java b/server/src/com/cloud/network/NetworkManagerImpl.java index 30627f3eba8..498010a855f 100755 --- a/server/src/com/cloud/network/NetworkManagerImpl.java +++ b/server/src/com/cloud/network/NetworkManagerImpl.java @@ -1266,9 +1266,9 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag network.setMode(result.getMode()); _networksDao.update(networkId, network); - // If this is a guest virtual network and the network offering does not support a shared source NAT rule, + // If this is a 1) guest virtual network 2) network has sourceNat service 3) network offering does not support a Shared source NAT rule, // associate a source NAT IP (if one isn't already associated with the network) - if (network.getType() == Network.Type.Isolated && !offering.isSharedSourceNatService()) { + if (network.getType() == Network.Type.Isolated && isServiceSupportedByNetworkOffering(network.getNetworkOfferingId(), Service.SourceNat) && !offering.isSharedSourceNatService()) { List ips = _ipAddressDao.listByAssociatedNetwork(networkId, true); if (ips.isEmpty()) { diff --git a/server/src/com/cloud/network/router/VirtualNetworkApplianceManagerImpl.java b/server/src/com/cloud/network/router/VirtualNetworkApplianceManagerImpl.java index 8d595b1197f..c607f6eca23 100755 --- a/server/src/com/cloud/network/router/VirtualNetworkApplianceManagerImpl.java +++ b/server/src/com/cloud/network/router/VirtualNetworkApplianceManagerImpl.java @@ -118,6 +118,7 @@ import com.cloud.network.LoadBalancerVO; import com.cloud.network.Network; import com.cloud.network.NetworkManager; import com.cloud.network.NetworkVO; +import com.cloud.network.Network.Service; import com.cloud.network.Networks.BroadcastDomainType; import com.cloud.network.Networks.IsolationType; import com.cloud.network.Networks.TrafficType; @@ -1038,18 +1039,22 @@ public class VirtualNetworkApplianceManagerImpl implements VirtualNetworkApplian if (routers.size() >= routerCount) { return routers; } - - PublicIp sourceNatIp = _networkMgr.assignSourceNatIpAddress(owner, guestNetwork, _accountService.getSystemUser().getId()); + NicProfile defaultNic = new NicProfile(); - defaultNic.setDefaultNic(true); - defaultNic.setIp4Address(sourceNatIp.getAddress().addr()); - defaultNic.setGateway(sourceNatIp.getGateway()); - defaultNic.setNetmask(sourceNatIp.getNetmask()); - defaultNic.setMacAddress(sourceNatIp.getMacAddress()); - defaultNic.setBroadcastType(BroadcastDomainType.Vlan); - defaultNic.setBroadcastUri(BroadcastDomainType.Vlan.toUri(sourceNatIp.getVlanTag())); - defaultNic.setIsolationUri(IsolationType.Vlan.toUri(sourceNatIp.getVlanTag())); - defaultNic.setDeviceId(2); + //if source nat service is supported by the network, get the source nat ip address + if (_networkMgr.isServiceSupportedByNetworkOffering(guestNetwork.getNetworkOfferingId(), Service.SourceNat)) { + PublicIp sourceNatIp = _networkMgr.assignSourceNatIpAddress(owner, guestNetwork, _accountService.getSystemUser().getId()); + defaultNic.setDefaultNic(true); + defaultNic.setIp4Address(sourceNatIp.getAddress().addr()); + defaultNic.setGateway(sourceNatIp.getGateway()); + defaultNic.setNetmask(sourceNatIp.getNetmask()); + defaultNic.setMacAddress(sourceNatIp.getMacAddress()); + defaultNic.setBroadcastType(BroadcastDomainType.Vlan); + defaultNic.setBroadcastUri(BroadcastDomainType.Vlan.toUri(sourceNatIp.getVlanTag())); + defaultNic.setIsolationUri(IsolationType.Vlan.toUri(sourceNatIp.getVlanTag())); + defaultNic.setDeviceId(2); + } + int count = routerCount - routers.size(); for (int i = 0; i < count; i++) { From 525a0a7675297973f929547c63e58e2010691fcf Mon Sep 17 00:00:00 2001 From: alena Date: Tue, 25 Oct 2011 18:00:30 -0700 Subject: [PATCH 031/159] 1)Changed implementation for restart network: call shutdown/implement methods as a part of it 2)Re-apply all existing firewall rules as a part of implement call. TODO: Cleanup all existing rules from the backend (leave them in the DB) as a part of shutdown call --- .../api/commands/AssociateIPAddrCmd.java | 2 +- .../cloud/api/commands/CreateNetworkCmd.java | 2 +- .../api/commands/CreateVlanIpRangeCmd.java | 2 +- .../cloud/api/commands/UpdateNetworkCmd.java | 2 +- api/src/com/cloud/network/NetworkService.java | 11 +- .../VirtualNetworkApplianceService.java | 4 +- .../cloud/network/element/NetworkElement.java | 14 +- .../com/cloud/resource/ResourceService.java | 3 + .../com/cloud/vm/VirtualMachineProfile.java | 2 +- server/src/com/cloud/api/ApiDBUtils.java | 2 +- .../ConfigurationManagerImpl.java | 2 +- .../src/com/cloud/network/NetworkManager.java | 8 +- .../com/cloud/network/NetworkManagerImpl.java | 130 ++++++++++-------- .../network/element/BareMetalElement.java | 8 +- .../element/CloudZonesNetworkElement.java | 25 +--- .../cloud/network/element/DhcpElement.java | 50 +------ .../element/ElasticLoadBalancerElement.java | 8 +- .../network/element/ExternalDhcpElement.java | 13 +- .../F5ExternalLoadBalancerElement.java | 8 +- .../JuniperSRXExternalFirewallElement.java | 6 +- .../NetscalerExternalLoadBalancerElement.java | 8 +- .../com/cloud/network/element/OvsElement.java | 12 +- .../RedundantVirtualRouterElement.java | 1 - .../network/element/VirtualRouterElement.java | 92 ++++++------- .../network/firewall/FirewallManagerImpl.java | 30 ++-- .../lb/ElasticLoadBalancerManagerImpl.java | 2 +- .../lb/LoadBalancingRulesManagerImpl.java | 69 +++++----- .../VirtualNetworkApplianceManagerImpl.java | 95 +++++++++---- .../cloud/network/rules/FirewallManager.java | 2 +- .../com/cloud/network/rules/RulesManager.java | 2 +- .../cloud/network/rules/RulesManagerImpl.java | 10 +- .../com/cloud/resource/ResourceManager.java | 3 +- .../cloud/resource/ResourceManagerImpl.java | 12 ++ .../src/com/cloud/vm/UserVmManagerImpl.java | 12 +- .../cloud/network/MockNetworkManagerImpl.java | 6 +- 35 files changed, 304 insertions(+), 354 deletions(-) diff --git a/api/src/com/cloud/api/commands/AssociateIPAddrCmd.java b/api/src/com/cloud/api/commands/AssociateIPAddrCmd.java index da6ced1b3ce..29b0b4af249 100644 --- a/api/src/com/cloud/api/commands/AssociateIPAddrCmd.java +++ b/api/src/com/cloud/api/commands/AssociateIPAddrCmd.java @@ -97,7 +97,7 @@ public class AssociateIPAddrCmd extends BaseAsyncCreateCmd { DataCenter zone = _configService.getZone(getZoneId()); if (zone.getNetworkType() == NetworkType.Advanced) { - List networks = _networkService.getVirtualNetworksOwnedByAccountInZone(getZoneId(), _accountService.getAccount(getEntityOwnerId())); + List networks = _networkService.getIsolatedNetworksOwnedByAccountInZone(getZoneId(), _accountService.getAccount(getEntityOwnerId())); if (networks.size() == 0) { String domain = _domainService.getDomain(getDomainId()).getName(); throw new InvalidParameterValueException("Account name=" + getAccountName() + " domain=" + domain + " doesn't have virtual networks in zone=" + zone.getName()); diff --git a/api/src/com/cloud/api/commands/CreateNetworkCmd.java b/api/src/com/cloud/api/commands/CreateNetworkCmd.java index ad986bf3cec..126b5f7bc86 100644 --- a/api/src/com/cloud/api/commands/CreateNetworkCmd.java +++ b/api/src/com/cloud/api/commands/CreateNetworkCmd.java @@ -162,7 +162,7 @@ public class CreateNetworkCmd extends BaseCmd { if (physicalNetworkId != null) { return physicalNetworkId; } else if (zoneId != null) { - return _networkService.translateZoneToPhysicalNetwork(zoneId); + return _networkService.translateZoneIdToPhysicalNetworkId(zoneId); } else { throw new InvalidParameterValueException("Either zoneId or physicalNetworkId have to be specified"); } diff --git a/api/src/com/cloud/api/commands/CreateVlanIpRangeCmd.java b/api/src/com/cloud/api/commands/CreateVlanIpRangeCmd.java index aa23f51262a..be52e05a8a8 100644 --- a/api/src/com/cloud/api/commands/CreateVlanIpRangeCmd.java +++ b/api/src/com/cloud/api/commands/CreateVlanIpRangeCmd.java @@ -86,7 +86,7 @@ public class CreateVlanIpRangeCmd extends BaseCmd { if (physicalNetworkId != null) { return physicalNetworkId; } else if (zoneId != null) { - return _networkService.translateZoneToPhysicalNetwork(zoneId); + return _networkService.translateZoneIdToPhysicalNetworkId(zoneId); } else { throw new InvalidParameterValueException("Either zoneId or physicalNetworkId have to be specified"); } diff --git a/api/src/com/cloud/api/commands/UpdateNetworkCmd.java b/api/src/com/cloud/api/commands/UpdateNetworkCmd.java index a431de207f7..c949241dd0c 100644 --- a/api/src/com/cloud/api/commands/UpdateNetworkCmd.java +++ b/api/src/com/cloud/api/commands/UpdateNetworkCmd.java @@ -88,7 +88,7 @@ public class UpdateNetworkCmd extends BaseAsyncCmd { } private Long getNetworkOfferingId() { - return networkOfferingId == null ? 0 : networkOfferingId; + return networkOfferingId; } ///////////////////////////////////////////////////// diff --git a/api/src/com/cloud/network/NetworkService.java b/api/src/com/cloud/network/NetworkService.java index fa01ffaaa04..e42c9c5b32f 100644 --- a/api/src/com/cloud/network/NetworkService.java +++ b/api/src/com/cloud/network/NetworkService.java @@ -34,14 +34,11 @@ import com.cloud.network.Network.Capability; import com.cloud.network.Network.Provider; import com.cloud.network.Network.Service; import com.cloud.network.Networks.TrafficType; -import com.cloud.offering.NetworkOffering; import com.cloud.user.Account; public interface NetworkService { - List getVirtualNetworksOwnedByAccountInZone(long zoneId, Account owner); - - List listNetworkOfferings(); + List getIsolatedNetworksOwnedByAccountInZone(long zoneId, Account owner); IpAddress allocateIP(AssociateIPAddrCmd cmd) throws ResourceAllocationException, InsufficientAddressCapacityException, ConcurrentOperationException; @@ -74,13 +71,13 @@ public interface NetworkService { NetworkProfile convertNetworkToNetworkProfile(long networkId); - Map> getNetworkCapabilities(long networkId, long zoneId); + Map> getNetworkCapabilities(long networkId); boolean isNetworkAvailableInDomain(long networkId, long domainId); Long getDedicatedNetworkDomain(long networkId); - Network updateNetwork(long networkId, String name, String displayText, List tags, Account caller, String domainSuffix, long networkOfferingId); + Network updateNetwork(long networkId, String name, String displayText, List tags, Account caller, String domainSuffix, Long networkOfferingId); Integer getNetworkRate(long networkId, Long vmId); @@ -116,5 +113,5 @@ public interface NetworkService { PhysicalNetworkServiceProvider getCreatedPhysicalNetworkServiceProvider(Long providerId); - long translateZoneToPhysicalNetwork(long zoneId); + long translateZoneIdToPhysicalNetworkId(long zoneId); } diff --git a/api/src/com/cloud/network/VirtualNetworkApplianceService.java b/api/src/com/cloud/network/VirtualNetworkApplianceService.java index 84259da2a21..4d370a1adea 100644 --- a/api/src/com/cloud/network/VirtualNetworkApplianceService.java +++ b/api/src/com/cloud/network/VirtualNetworkApplianceService.java @@ -30,14 +30,14 @@ public interface VirtualNetworkApplianceService { * @param cmd the command specifying router's id * @return DomainRouter object */ - VirtualRouter startRouter(long routerId, boolean restartNetwork) throws ConcurrentOperationException, ResourceUnavailableException, InsufficientCapacityException; + VirtualRouter startRouter(long routerId, boolean reprogramNetwork) throws ConcurrentOperationException, ResourceUnavailableException, InsufficientCapacityException; /** * Reboots domain router * @param cmd the command specifying router's id * @return router if successful */ - VirtualRouter rebootRouter(long routerId, boolean restartNetwork) throws ConcurrentOperationException, ResourceUnavailableException, InsufficientCapacityException; + VirtualRouter rebootRouter(long routerId, boolean reprogramNetwork) throws ConcurrentOperationException, ResourceUnavailableException, InsufficientCapacityException; VirtualRouter upgradeRouter(UpgradeRouterCmd cmd); diff --git a/api/src/com/cloud/network/element/NetworkElement.java b/api/src/com/cloud/network/element/NetworkElement.java index d85b36c22c8..edd0042f590 100644 --- a/api/src/com/cloud/network/element/NetworkElement.java +++ b/api/src/com/cloud/network/element/NetworkElement.java @@ -91,22 +91,12 @@ public interface NetworkElement extends Adapter { * The network is being shutdown. * @param network * @param context + * @param cleanup TODO * @return * @throws ConcurrentOperationException * @throws ResourceUnavailableException */ - boolean shutdown(Network network, ReservationContext context) throws ConcurrentOperationException, ResourceUnavailableException; - - /** - * The network is being restarted. - * @param network - * @param context - * @param cleanup If need to clean up old network elements - * @return - * @throws ConcurrentOperationException - * @throws ResourceUnavailableException - */ - boolean restart(Network network, ReservationContext context, boolean cleanup) throws ConcurrentOperationException, ResourceUnavailableException, InsufficientCapacityException; + boolean shutdown(Network network, ReservationContext context, boolean cleanup) throws ConcurrentOperationException, ResourceUnavailableException; /** * The network is being destroyed. diff --git a/api/src/com/cloud/resource/ResourceService.java b/api/src/com/cloud/resource/ResourceService.java index d6e5ca9aa8e..09ea1ee776a 100644 --- a/api/src/com/cloud/resource/ResourceService.java +++ b/api/src/com/cloud/resource/ResourceService.java @@ -32,6 +32,7 @@ import com.cloud.exception.AgentUnavailableException; import com.cloud.exception.DiscoveryException; import com.cloud.exception.InvalidParameterValueException; import com.cloud.host.Host; +import com.cloud.hypervisor.Hypervisor.HypervisorType; import com.cloud.org.Cluster; public interface ResourceService { @@ -86,4 +87,6 @@ public interface ResourceService { Host getHost(long hostId); Cluster getCluster(Long clusterId); + + List getSupportedHypervisorTypes(long zoneId); } diff --git a/api/src/com/cloud/vm/VirtualMachineProfile.java b/api/src/com/cloud/vm/VirtualMachineProfile.java index 707f921c046..0ff762507e4 100644 --- a/api/src/com/cloud/vm/VirtualMachineProfile.java +++ b/api/src/com/cloud/vm/VirtualMachineProfile.java @@ -46,7 +46,7 @@ public interface VirtualMachineProfile { public static final Param VmPassword = new Param("VmPassword"); public static final Param ControlNic = new Param("ControlNic"); - public static final Param RestartNetwork = new Param("RestartNetwork"); + public static final Param ReProgramNetwork = new Param("RestartNetwork"); public static final Param PxeSeverType = new Param("PxeSeverType"); private String name; diff --git a/server/src/com/cloud/api/ApiDBUtils.java b/server/src/com/cloud/api/ApiDBUtils.java index d3659751f47..979ed3dba13 100755 --- a/server/src/com/cloud/api/ApiDBUtils.java +++ b/server/src/com/cloud/api/ApiDBUtils.java @@ -575,7 +575,7 @@ public class ApiDBUtils { } public static Map> getNetworkCapabilities(long networkOfferingId, long zoneId) { - return _networkMgr.getNetworkCapabilities(networkOfferingId, zoneId); + return _networkMgr.getNetworkCapabilities(networkOfferingId); } public static long getPublicNetworkIdByZone(long zoneId) { diff --git a/server/src/com/cloud/configuration/ConfigurationManagerImpl.java b/server/src/com/cloud/configuration/ConfigurationManagerImpl.java index 4691eca4e16..e9661946e8b 100755 --- a/server/src/com/cloud/configuration/ConfigurationManagerImpl.java +++ b/server/src/com/cloud/configuration/ConfigurationManagerImpl.java @@ -1962,7 +1962,7 @@ public class ConfigurationManagerImpl implements ConfigurationManager, Configura if (associateIpRangeToAccount) { _networkMgr.associateIpAddressListToAccount(userId, account.getId(), zoneId, vlan.getId(), network); if (network == null) { - List networks = _networkMgr.getVirtualNetworksOwnedByAccountInZone(zoneId, account); + List networks = _networkMgr.getIsolatedNetworksOwnedByAccountInZone(zoneId, account); network = networks.get(0); } if (network == null) { diff --git a/server/src/com/cloud/network/NetworkManager.java b/server/src/com/cloud/network/NetworkManager.java index 38285f1ee28..229cabc1e59 100644 --- a/server/src/com/cloud/network/NetworkManager.java +++ b/server/src/com/cloud/network/NetworkManager.java @@ -128,12 +128,8 @@ public interface NetworkManager extends NetworkService { List getNics(long vmId); - List getNicsIncludingRemoved(VirtualMachine vm); - List getNicProfiles(VirtualMachine vm); - List getAccountsUsingNetwork(long configurationId); - AccountVO getNetworkOwner(long configurationId); List getNetworksforOffering(long offeringId, long dataCenterId, long accountId); @@ -225,6 +221,8 @@ public interface NetworkManager extends NetworkService { boolean isProviderSupported(long networkOfferingId, Service service, Provider provider); - List listNetworkOfferingsForUpgrade(long networkId); + List listNetworkOfferingsForUpgrade(long networkId); + + PhysicalNetwork translateZoneIdToPhysicalNetwork(long zoneId); } diff --git a/server/src/com/cloud/network/NetworkManagerImpl.java b/server/src/com/cloud/network/NetworkManagerImpl.java index 498010a855f..17bd4d6875b 100755 --- a/server/src/com/cloud/network/NetworkManagerImpl.java +++ b/server/src/com/cloud/network/NetworkManagerImpl.java @@ -556,7 +556,7 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag } @Override - public List getVirtualNetworksOwnedByAccountInZone(long zoneId, Account owner) { + public List getIsolatedNetworksOwnedByAccountInZone(long zoneId, Account owner) { return _networksDao.listBy(owner.getId(), zoneId, Network.Type.Isolated); } @@ -1286,11 +1286,11 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag } // reapply all the firewall/staticNat/lb rules - s_logger.debug("Applying network rules as a part of network " + network + " implement..."); - if (!restartNetwork(networkId, false, true, context.getAccount())) { - s_logger.warn("Failed to reapply network rules as a part of network " + network + " implement"); + s_logger.debug("Reprogramming network " + network + " as a part of network implement"); + if (!reprogramNetwork(networkId, UserContext.current().getCaller(), network)) { + s_logger.warn("Failed to re-program the network as a part of network " + network + " implement"); throw new ResourceUnavailableException("Unable to apply network rules as a part of network " + network + " implement", DataCenter.class, network.getDataCenterId()); - } + } network.setState(Network.State.Implemented); _networksDao.update(network.getId(), network); @@ -1442,11 +1442,6 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag return _nicDao.listByVmId(vmId); } - @Override - public List getNicsIncludingRemoved(VirtualMachine vm) { - return _nicDao.listByVmIdIncludingRemoved(vm.getId()); - } - @Override public List getNicProfiles(VirtualMachine vm) { List nics = _nicDao.listByVmId(vm.getId()); @@ -1506,13 +1501,6 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag return releasePublicIpAddress(ipAddressId, userId, caller); } - @Override - public List getAccountsUsingNetwork(long networkId) { - SearchCriteria sc = AccountsUsingNetworkSearch.create(); - sc.setJoinParameters("nc", "config", networkId); - return _accountDao.search(sc, null); - } - @Override public AccountVO getNetworkOwner(long networkId) { SearchCriteria sc = AccountsUsingNetworkSearch.create(); @@ -1527,11 +1515,6 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag return _networksDao.getNetworksForOffering(offeringId, dataCenterId, accountId); } - @Override - public List listNetworkOfferings() { - return _networkOfferingDao.listNonSystemNetworkOfferings(); - } - @Override public String getNextAvailableMacAddressInNetwork(long networkId) throws InsufficientAddressCapacityException { String mac = _networksDao.getNextAvailableMacAddress(networkId); @@ -2168,6 +2151,9 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag _networksDao.update(network.getId(), network); txn.commit(); + //1) FIXME - Cleanup all the rules for the network + + //2) Shutdown all the network elements boolean success = true; for (NetworkElement element : _networkElements) { try { @@ -2175,7 +2161,7 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag s_logger.debug("Sending network shutdown to " + element.getName()); } - element.shutdown(network, context); + element.shutdown(network, context, false); } catch (ResourceUnavailableException e) { s_logger.warn("Unable to complete shutdown of the network due to element: " + element.getName(), e); success = false; @@ -2305,7 +2291,7 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag // remove all PF/Static Nat rules for the network try { - if (_rulesMgr.revokeAllRulesForNetwork(networkId, callerUserId, caller)) { + if (_rulesMgr.revokeAllPFStaticNatRulesForNetwork(networkId, callerUserId, caller)) { s_logger.debug("Successfully cleaned up portForwarding/staticNat rules for network id=" + networkId); } else { success = false; @@ -2486,10 +2472,7 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag _accountMgr.checkAccess(callerAccount, null, network); - boolean success = true; - - // Restart network - network elements restart is required - success = restartNetwork(networkId, true, cleanup, callerAccount); + boolean success = restartNetwork(networkId, callerAccount, null); if (success) { s_logger.debug("Network id=" + networkId + " is restarted successfully."); @@ -2520,34 +2503,49 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag } } - private boolean restartNetwork(long networkId, boolean restartElements, boolean cleanup, Account caller) throws ConcurrentOperationException, ResourceUnavailableException, InsufficientCapacityException { - boolean success = true; + private boolean restartNetwork(long networkId, Account caller, Long newNetworkOfferingId) throws ConcurrentOperationException, ResourceUnavailableException, InsufficientCapacityException { NetworkVO network = _networksDao.findById(networkId); s_logger.debug("Restarting network " + networkId + "..."); - + + //shutdown the network ReservationContext context = new ReservationContextImpl(null, null, null, caller); - if (restartElements) { - s_logger.debug("Restarting network elements for the network " + network); - for (NetworkElement element : _networkElements) { - // stop and start the network element - try { - boolean supported = element.restart(network, context, cleanup); - if (!supported) { - s_logger.trace("Network element(s) " + element.getName() + " doesn't support network id" + networkId + " restart"); - } - } catch (Exception ex) { - s_logger.warn("Failed to restart network element" + element.getName() + " as a part of network id" + networkId + " restart", ex); - success = false; - } - } - } - - if (!success) { + s_logger.debug("Shutting down the network id=" + networkId + " as a part of network restart"); + + shutdownNetwork(networkId, context); + + //check that the network was shutdown properly + network = _networksDao.findById(networkId); + if (network.getState() != Network.State.Allocated && network.getState() != Network.State.Setup) { + s_logger.debug("Failed to shutdown the network as a part of network restart: " + network.getState()); return false; } + + if (newNetworkOfferingId != null) { + s_logger.debug("Updating network " + network + " with the new network offering id=" + newNetworkOfferingId + " as a part of network restart"); + network.setNetworkOfferingId(newNetworkOfferingId); + _networksDao.update(networkId, network); + } + + //implement the network again + DeployDestination dest = new DeployDestination(_dcDao.findById(network.getDataCenterId()), null, null, null); + + s_logger.debug("Implementing the network " + network + " as a part of network restart"); + Pair implemented = implementNetwork(networkId, dest, context); + + if (implemented.first() == null) { + s_logger.warn("Failed to implement the network " + network + " as a part of network restart"); + return false; + } else { + return true; + } + } + + //This method re-programs the rules/ips for existing network + protected boolean reprogramNetwork(long networkId, Account caller, NetworkVO network) throws ResourceUnavailableException { + boolean success = true; // associate all ip addresses if (!applyIpAssociations(network, false)) { s_logger.warn("Failed to apply ip addresses as a part of network id" + networkId + " restart"); @@ -2596,7 +2594,6 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag } } } - return success; } @@ -2607,7 +2604,7 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag @Override - public Map> getNetworkCapabilities(long networkOfferingId, long zoneId) { + public Map> getNetworkCapabilities(long networkOfferingId) { Map> networkCapabilities = new HashMap>(); @@ -2773,7 +2770,7 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag txn.start(); if (network == null) { - List networks = getVirtualNetworksOwnedByAccountInZone(zoneId, owner); + List networks = getIsolatedNetworksOwnedByAccountInZone(zoneId, owner); if (networks.size() == 0) { createNetwork = true; } else { @@ -2784,7 +2781,8 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag // create new Virtual network for the user if it doesn't exist if (createNetwork) { List offerings = _configMgr.listNetworkOfferings(TrafficType.Guest, false); - network = createNetwork(offerings.get(0).getId(), owner.getAccountName() + "-network", owner.getAccountName() + "-network", null, null, null, null, null, owner, false, null, null, false, null); + PhysicalNetwork physicalNetwork = translateZoneIdToPhysicalNetwork(zoneId); + network = createNetwork(offerings.get(0).getId(), owner.getAccountName() + "-network", owner.getAccountName() + "-network", null, null, null, null, null, owner, false, null, null, false, physicalNetwork); if (network == null) { s_logger.warn("Failed to create default Virtual network for the account " + accountId + "in zone " + zoneId); @@ -3115,7 +3113,7 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag @Override @ActionEvent(eventType = EventTypes.EVENT_NETWORK_UPDATE, eventDescription = "updating network", async = true) - public Network updateNetwork(long networkId, String name, String displayText, List tags, Account caller, String domainSuffix, long networkOfferingId) { + public Network updateNetwork(long networkId, String name, String displayText, List tags, Account caller, String domainSuffix, Long networkOfferingId) { boolean restartNetwork = false; // verify input parameters @@ -3169,7 +3167,7 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag } long oldNetworkOfferingId = network.getNetworkOfferingId(); - if (networkOfferingId != 0) { + if (networkOfferingId != null) { NetworkOfferingVO networkOffering = _networkOfferingDao.findById(networkOfferingId); if (networkOffering == null || networkOffering.isSystemOnly()) { throw new InvalidParameterValueException("Unable to find network offering by id " + networkOfferingId); @@ -3189,9 +3187,7 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag if (!canUpgrade(oldNetworkOfferingId, networkOfferingId)) { throw new InvalidParameterValueException("Can't upgrade from network offering " + oldNetworkOfferingId + " to " + networkOfferingId + "; check logs for more information"); } - - //TODO - need to find the way how to cleanup the rules on the old provider - network.setNetworkOfferingId(networkOfferingId); + restartNetwork = true; } } @@ -3202,7 +3198,7 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag s_logger.info("Restarting network " + network + " as a part of update network call"); try { - success = restartNetwork(networkId, true, true, caller); + success = restartNetwork(networkId, caller, networkOfferingId); } catch (Exception e) { success = false; } @@ -3936,7 +3932,7 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag @Override - public long translateZoneToPhysicalNetwork(long zoneId) { + public long translateZoneIdToPhysicalNetworkId(long zoneId) { List pNtwks = _physicalNetworkDao.listByZone(zoneId); if (pNtwks.isEmpty()) { throw new InvalidParameterValueException("Unable to find physical network in zone id=" + zoneId); @@ -3949,6 +3945,22 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag return pNtwks.get(0).getId(); } + @Override + public PhysicalNetwork translateZoneIdToPhysicalNetwork(long zoneId) { + List pNtwks = _physicalNetworkDao.listByZone(zoneId); + if (pNtwks.isEmpty()) { + throw new InvalidParameterValueException("Unable to find physical network in zone id=" + zoneId); + } + + if (pNtwks.size() > 1) { + throw new InvalidParameterValueException("More than one physical networks exist in zone id=" + zoneId); + } + + return pNtwks.get(0); + } + + + @Override public List listNetworkOfferingsForUpgrade(long networkId) { diff --git a/server/src/com/cloud/network/element/BareMetalElement.java b/server/src/com/cloud/network/element/BareMetalElement.java index 23c8f7ecdc2..f92e87985ed 100644 --- a/server/src/com/cloud/network/element/BareMetalElement.java +++ b/server/src/com/cloud/network/element/BareMetalElement.java @@ -98,13 +98,7 @@ public class BareMetalElement extends AdapterBase implements NetworkElement { } @Override - public boolean shutdown(Network network, ReservationContext context) throws ConcurrentOperationException, ResourceUnavailableException { - return true; - } - - @Override - public boolean restart(Network network, ReservationContext context, boolean cleanup) throws ConcurrentOperationException, ResourceUnavailableException, - InsufficientCapacityException { + public boolean shutdown(Network network, ReservationContext context, boolean cleanup) throws ConcurrentOperationException, ResourceUnavailableException { return true; } diff --git a/server/src/com/cloud/network/element/CloudZonesNetworkElement.java b/server/src/com/cloud/network/element/CloudZonesNetworkElement.java index 824f328f102..b0ed1b8f3ca 100644 --- a/server/src/com/cloud/network/element/CloudZonesNetworkElement.java +++ b/server/src/com/cloud/network/element/CloudZonesNetworkElement.java @@ -33,7 +33,6 @@ package com.cloud.network.element; import java.util.HashMap; -import java.util.List; import java.util.Map; import javax.ejb.Local; @@ -43,16 +42,11 @@ import org.apache.log4j.Logger; import com.cloud.agent.AgentManager; import com.cloud.agent.AgentManager.OnError; import com.cloud.agent.api.Answer; -import com.cloud.agent.api.StartAnswer; -import com.cloud.agent.api.routing.DhcpEntryCommand; -import com.cloud.agent.api.routing.NetworkElementCommand; import com.cloud.agent.api.routing.SavePasswordCommand; import com.cloud.agent.api.routing.VmDataCommand; import com.cloud.agent.manager.Commands; import com.cloud.configuration.ConfigurationManager; import com.cloud.configuration.ZoneConfig; -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; @@ -61,33 +55,24 @@ import com.cloud.exception.InsufficientCapacityException; import com.cloud.exception.OperationTimedoutException; import com.cloud.exception.ResourceUnavailableException; import com.cloud.network.Network; -import com.cloud.network.NetworkVO; import com.cloud.network.Network.Capability; import com.cloud.network.Network.Provider; import com.cloud.network.Network.Service; import com.cloud.network.NetworkManager; import com.cloud.network.Networks.TrafficType; -import com.cloud.network.PublicIpAddress; import com.cloud.network.dao.NetworkDao; import com.cloud.network.router.VirtualNetworkApplianceManager; -import com.cloud.network.router.VirtualRouter; -import com.cloud.network.rules.FirewallRule; -import com.cloud.network.rules.StaticNat; import com.cloud.offering.NetworkOffering; import com.cloud.service.dao.ServiceOfferingDao; import com.cloud.uservm.UserVm; import com.cloud.utils.PasswordGenerator; import com.cloud.utils.component.AdapterBase; import com.cloud.utils.component.Inject; -import com.cloud.vm.DomainRouterVO; import com.cloud.vm.NicProfile; -import com.cloud.vm.NicVO; import com.cloud.vm.ReservationContext; import com.cloud.vm.UserVmManager; import com.cloud.vm.UserVmVO; import com.cloud.vm.VirtualMachine; -import com.cloud.vm.Nic.ReservationStrategy; -import com.cloud.vm.VirtualMachine.State; import com.cloud.vm.VirtualMachineProfile; import com.cloud.vm.dao.DomainRouterDao; import com.cloud.vm.dao.UserVmDao; @@ -183,7 +168,7 @@ public class CloudZonesNetworkElement extends AdapterBase implements NetworkElem } @Override - public boolean shutdown(Network network, ReservationContext context) throws ConcurrentOperationException, ResourceUnavailableException { + public boolean shutdown(Network network, ReservationContext context, boolean cleanup) throws ConcurrentOperationException, ResourceUnavailableException { return false; //assume that the agent will remove userdata etc } @@ -210,14 +195,6 @@ public class CloudZonesNetworkElement extends AdapterBase implements NetworkElem return capabilities; } - @Override - public boolean restart(Network network, ReservationContext context, boolean cleanup) throws ConcurrentOperationException, ResourceUnavailableException, InsufficientCapacityException{ - - s_logger.trace("Cloudzones element doesn't handle network restart for the network " + network); - return true; - - } - private VmDataCommand generateVmDataCommand( String vmPrivateIpAddress, String userData, String serviceOffering, String zoneName, String guestIpAddress, String vmName, String vmInstanceName, long vmId, String publicKey) { VmDataCommand cmd = new VmDataCommand(vmPrivateIpAddress, vmName); diff --git a/server/src/com/cloud/network/element/DhcpElement.java b/server/src/com/cloud/network/element/DhcpElement.java index c04878b1675..8ea35b98080 100644 --- a/server/src/com/cloud/network/element/DhcpElement.java +++ b/server/src/com/cloud/network/element/DhcpElement.java @@ -103,7 +103,7 @@ public class DhcpElement extends AdapterBase implements DhcpElementService, Pass } Map params = new HashMap(1); - params.put(VirtualMachineProfile.Param.RestartNetwork, true); + params.put(VirtualMachineProfile.Param.ReProgramNetwork, true); _routerMgr.deployDhcp(network, dest, _accountMgr.getAccount(network.getAccountId()), params); return true; } @@ -119,7 +119,7 @@ public class DhcpElement extends AdapterBase implements DhcpElementService, Pass @SuppressWarnings("unchecked") VirtualMachineProfile uservm = (VirtualMachineProfile)vm; Map params = new HashMap(1); - params.put(VirtualMachineProfile.Param.RestartNetwork, true); + params.put(VirtualMachineProfile.Param.ReProgramNetwork, true); List routers = _routerMgr.deployDhcp(network, dest, _accountMgr.getAccount(network.getAccountId()), uservm.getParameters()); @@ -145,7 +145,7 @@ public class DhcpElement extends AdapterBase implements DhcpElementService, Pass } @Override - public boolean shutdown(Network network, ReservationContext context) throws ConcurrentOperationException, ResourceUnavailableException { + public boolean shutdown(Network network, ReservationContext context, boolean cleanup) throws ConcurrentOperationException, ResourceUnavailableException { List routers = _routerDao.listByNetworkAndRole(network.getId(), Role.DHCP_USERDATA); if (routers == null || routers.isEmpty()) { return true; @@ -193,50 +193,6 @@ public class DhcpElement extends AdapterBase implements DhcpElementService, Pass return capabilities; } - @Override - public boolean restart(Network network, ReservationContext context, boolean cleanup) throws ConcurrentOperationException, ResourceUnavailableException, InsufficientCapacityException{ - DataCenter dc = _configMgr.getZone(network.getDataCenterId()); - DeployDestination dest = new DeployDestination(dc, null, null, null); - NetworkOffering offering = _configMgr.getNetworkOffering(network.getNetworkOfferingId()); - - if (!canHandle(dest, offering.getTrafficType(), network.getType(), network.getNetworkOfferingId())) { - s_logger.trace("Dhcp element doesn't handle network restart for the network " + network); - return false; - } - - List routers = _routerDao.listByNetworkAndRole(network.getId(), Role.DHCP_USERDATA); - if (routers == null || routers.isEmpty()) { - s_logger.trace("Can't find dhcp element in network " + network.getId()); - return true; - } - - /* Get the host_id in order to find the cluster */ - Long host_id = new Long(0); - for (DomainRouterVO router : routers) { - if (host_id == null || host_id == 0) { - host_id = (router.getHostId() != null ? router.getHostId() : router.getLastHostId()); - } - if (cleanup) { - /* FIXME it's not completely safe to ignore these failure, but we would try to push on now */ - if (router.getState() != State.Stopped && _routerMgr.stopRouter(router.getId(), false) == null) { - s_logger.warn("Failed to stop dhcp element " + router + " as a part of network " + network + " restart"); - } - if (_routerMgr.destroyRouter(router.getId()) == null) { - s_logger.warn("Failed to destroy dhcp element " + router + " as a part of network " + network + " restart"); - } - } - } - if (host_id == null || host_id == 0) { - throw new ResourceUnavailableException("Fail to locate dhcp element in network " + network.getId(), this.getClass(), 0); - } - - /* The cluster here is only used to determine hypervisor type, not the real deployment */ - Cluster cluster = _configMgr.getCluster(_hostDao.findById(host_id).getClusterId()); - Pod pod = _configMgr.getPod(_hostDao.findById(host_id).getPodId()); - dest = new DeployDestination(dc, pod, cluster, null); - return implement(network, offering, dest, context); - } - @Override public boolean savePassword(Network network, NicProfile nic, VirtualMachineProfile vm) throws ResourceUnavailableException{ diff --git a/server/src/com/cloud/network/element/ElasticLoadBalancerElement.java b/server/src/com/cloud/network/element/ElasticLoadBalancerElement.java index 2f9dc6812ee..212e346b33d 100644 --- a/server/src/com/cloud/network/element/ElasticLoadBalancerElement.java +++ b/server/src/com/cloud/network/element/ElasticLoadBalancerElement.java @@ -116,17 +116,11 @@ public class ElasticLoadBalancerElement extends AdapterBase implements LoadBalan } @Override - public boolean shutdown(Network network, ReservationContext context) throws ConcurrentOperationException, ResourceUnavailableException { + public boolean shutdown(Network network, ReservationContext context, boolean cleanup) throws ConcurrentOperationException, ResourceUnavailableException { // TODO kill all loadbalancer vms by calling the ElasticLoadBalancerManager return false; } - @Override - public boolean restart(Network network, ReservationContext context, boolean cleanup) throws ConcurrentOperationException, ResourceUnavailableException, InsufficientCapacityException { - // TODO restart all loadbalancer vms by calling the ElasticLoadBalancerManager - return false; - } - @Override public boolean destroy(Network network) throws ConcurrentOperationException, ResourceUnavailableException { // TODO kill all loadbalancer vms by calling the ElasticLoadBalancerManager diff --git a/server/src/com/cloud/network/element/ExternalDhcpElement.java b/server/src/com/cloud/network/element/ExternalDhcpElement.java index e5ebf8731b5..7032ab38689 100644 --- a/server/src/com/cloud/network/element/ExternalDhcpElement.java +++ b/server/src/com/cloud/network/element/ExternalDhcpElement.java @@ -60,7 +60,7 @@ public class ExternalDhcpElement extends AdapterBase implements NetworkElement { DataCenter dc = dest.getDataCenter(); Pod pod = dest.getPod(); - if (pod.getExternalDhcp() && dc.getNetworkType() == NetworkType.Basic && trafficType == TrafficType.Guest + if ((pod != null && pod.getExternalDhcp()) && dc.getNetworkType() == NetworkType.Basic && trafficType == TrafficType.Guest && networkType == Network.Type.Shared) { s_logger.debug("External DHCP can handle"); return true; @@ -113,16 +113,11 @@ public class ExternalDhcpElement extends AdapterBase implements NetworkElement { } @Override - public boolean shutdown(Network network, ReservationContext context) throws ConcurrentOperationException, ResourceUnavailableException { + public boolean shutdown(Network network, ReservationContext context, boolean cleanup) throws ConcurrentOperationException, ResourceUnavailableException { return true; } - - @Override - public boolean restart(Network network, ReservationContext context, boolean cleanup) throws ConcurrentOperationException, ResourceUnavailableException, - InsufficientCapacityException { - return true; - } - + + @Override public boolean destroy(Network network) throws ConcurrentOperationException, ResourceUnavailableException { return true; diff --git a/server/src/com/cloud/network/element/F5ExternalLoadBalancerElement.java b/server/src/com/cloud/network/element/F5ExternalLoadBalancerElement.java index 9a9c62d8018..db8339306f9 100644 --- a/server/src/com/cloud/network/element/F5ExternalLoadBalancerElement.java +++ b/server/src/com/cloud/network/element/F5ExternalLoadBalancerElement.java @@ -93,7 +93,7 @@ public class F5ExternalLoadBalancerElement extends AdapterBase implements LoadBa } @Override - public boolean shutdown(Network guestConfig, ReservationContext context) throws ResourceUnavailableException, ConcurrentOperationException { + public boolean shutdown(Network guestConfig, ReservationContext context, boolean cleanup) throws ResourceUnavailableException, ConcurrentOperationException { if (!canHandle(guestConfig)) { return false; } @@ -143,9 +143,5 @@ public class F5ExternalLoadBalancerElement extends AdapterBase implements LoadBa public Provider getProvider() { return Provider.F5BigIp; } - - @Override - public boolean restart(Network network, ReservationContext context, boolean cleanup) throws ConcurrentOperationException, ResourceUnavailableException, InsufficientCapacityException{ - return true; - } + } diff --git a/server/src/com/cloud/network/element/JuniperSRXExternalFirewallElement.java b/server/src/com/cloud/network/element/JuniperSRXExternalFirewallElement.java index feea82cd6d0..88530899fe7 100644 --- a/server/src/com/cloud/network/element/JuniperSRXExternalFirewallElement.java +++ b/server/src/com/cloud/network/element/JuniperSRXExternalFirewallElement.java @@ -109,7 +109,7 @@ public class JuniperSRXExternalFirewallElement extends AdapterBase implements So } @Override - public boolean shutdown(Network network, ReservationContext context) throws ResourceUnavailableException, ConcurrentOperationException { + public boolean shutdown(Network network, ReservationContext context, boolean cleanup) throws ResourceUnavailableException, ConcurrentOperationException { DataCenter zone = _configMgr.getZone(network.getDataCenterId()); NetworkOfferingVO offering = _networkOfferingDao.findById(network.getNetworkOfferingId()); @@ -231,10 +231,6 @@ public class JuniperSRXExternalFirewallElement extends AdapterBase implements So return capabilities; } - @Override - public boolean restart(Network network, ReservationContext context, boolean cleanup) throws ConcurrentOperationException, ResourceUnavailableException, InsufficientCapacityException{ - return true; - } } diff --git a/server/src/com/cloud/network/element/NetscalerExternalLoadBalancerElement.java b/server/src/com/cloud/network/element/NetscalerExternalLoadBalancerElement.java index 352c26a48fe..2bb3fb9b58e 100644 --- a/server/src/com/cloud/network/element/NetscalerExternalLoadBalancerElement.java +++ b/server/src/com/cloud/network/element/NetscalerExternalLoadBalancerElement.java @@ -31,7 +31,6 @@ import com.cloud.configuration.ConfigurationManager; import com.cloud.dc.DataCenter; import com.cloud.deploy.DeployDestination; import com.cloud.exception.ConcurrentOperationException; -import com.cloud.exception.InsufficientCapacityException; import com.cloud.exception.InsufficientNetworkCapacityException; import com.cloud.exception.ResourceUnavailableException; import com.cloud.network.ExternalNetworkDeviceManager; @@ -93,7 +92,7 @@ public class NetscalerExternalLoadBalancerElement extends AdapterBase implements } @Override - public boolean shutdown(Network guestConfig, ReservationContext context) throws ResourceUnavailableException, ConcurrentOperationException { + public boolean shutdown(Network guestConfig, ReservationContext context, boolean cleanup) throws ResourceUnavailableException, ConcurrentOperationException { if (!canHandle(guestConfig)) { return false; } @@ -143,9 +142,4 @@ public class NetscalerExternalLoadBalancerElement extends AdapterBase implements public Provider getProvider() { return Provider.NetscalerMPX; } - - @Override - public boolean restart(Network network, ReservationContext context, boolean cleanup) throws ConcurrentOperationException, ResourceUnavailableException, InsufficientCapacityException{ - return true; - } } diff --git a/server/src/com/cloud/network/element/OvsElement.java b/server/src/com/cloud/network/element/OvsElement.java index 1b928578533..da3c9eca230 100644 --- a/server/src/com/cloud/network/element/OvsElement.java +++ b/server/src/com/cloud/network/element/OvsElement.java @@ -116,16 +116,10 @@ public class OvsElement extends AdapterBase implements NetworkElement { _ovsTunnelMgr.CheckAndDestroyTunnel(vm.getVirtualMachine()); return true; } - + + @Override - public boolean restart(Network network, ReservationContext context, boolean cleanup) - throws ConcurrentOperationException, ResourceUnavailableException, - InsufficientCapacityException { - return true; - } - - @Override - public boolean shutdown(Network network, ReservationContext context) + public boolean shutdown(Network network, ReservationContext context, boolean cleanup) throws ConcurrentOperationException, ResourceUnavailableException { return true; } diff --git a/server/src/com/cloud/network/element/RedundantVirtualRouterElement.java b/server/src/com/cloud/network/element/RedundantVirtualRouterElement.java index b1d5811e24f..85eabbe6898 100644 --- a/server/src/com/cloud/network/element/RedundantVirtualRouterElement.java +++ b/server/src/com/cloud/network/element/RedundantVirtualRouterElement.java @@ -58,7 +58,6 @@ public class RedundantVirtualRouterElement extends VirtualRouterElement implemen } Map params = new HashMap(1); - params.put(VirtualMachineProfile.Param.RestartNetwork, true); _routerMgr.deployVirtualRouter(guestConfig, dest, _accountMgr.getAccount(guestConfig.getAccountId()), params, true); diff --git a/server/src/com/cloud/network/element/VirtualRouterElement.java b/server/src/com/cloud/network/element/VirtualRouterElement.java index 782e856e921..1b350a3268d 100644 --- a/server/src/com/cloud/network/element/VirtualRouterElement.java +++ b/server/src/com/cloud/network/element/VirtualRouterElement.java @@ -46,6 +46,7 @@ import com.cloud.network.VpnUser; import com.cloud.network.dao.LoadBalancerDao; import com.cloud.network.dao.NetworkDao; import com.cloud.network.dao.VirtualRouterElementsDao; +import com.cloud.network.element.VirtualRouterElements.VirtualRouterElementsType; import com.cloud.network.lb.LoadBalancingRulesManager; import com.cloud.network.router.VirtualNetworkApplianceManager; import com.cloud.network.router.VirtualRouter; @@ -53,11 +54,8 @@ import com.cloud.network.router.VirtualRouter.Role; import com.cloud.network.rules.FirewallRule; import com.cloud.network.rules.RulesManager; import com.cloud.network.rules.StaticNat; -import com.cloud.network.element.VirtualRouterElementService; -import com.cloud.network.element.VirtualRouterElements.VirtualRouterElementsType; import com.cloud.offering.NetworkOffering; import com.cloud.offerings.dao.NetworkOfferingDao; -import com.cloud.org.Cluster; import com.cloud.uservm.UserVm; import com.cloud.utils.component.Inject; import com.cloud.utils.exception.CloudRuntimeException; @@ -66,7 +64,6 @@ import com.cloud.vm.NicProfile; import com.cloud.vm.ReservationContext; import com.cloud.vm.UserVmManager; import com.cloud.vm.VirtualMachine; -import com.cloud.vm.VirtualMachine.State; import com.cloud.vm.VirtualMachineProfile; import com.cloud.vm.dao.DomainRouterDao; import com.cloud.vm.dao.UserVmDao; @@ -108,7 +105,6 @@ public class VirtualRouterElement extends DhcpElement implements VirtualRouterEl } Map params = new HashMap(1); - params.put(VirtualMachineProfile.Param.RestartNetwork, true); _routerMgr.deployVirtualRouter(guestConfig, dest, _accountMgr.getAccount(guestConfig.getAccountId()), params, false); @@ -136,50 +132,45 @@ public class VirtualRouterElement extends DhcpElement implements VirtualRouterEl } } - @Override - public boolean restart(Network network, ReservationContext context, boolean cleanup) throws ConcurrentOperationException, ResourceUnavailableException, InsufficientCapacityException{ - DataCenter dc = _configMgr.getZone(network.getDataCenterId()); - if (!canHandle(network.getType(), network.getNetworkOfferingId())) { - s_logger.trace("Virtual router element doesn't handle network restart for the network " + network); - return false; - } - - DeployDestination dest = new DeployDestination(dc, null, null, null); - - NetworkOffering networkOffering = _networkOfferingDao.findById(network.getNetworkOfferingId()); - - // We need to re-implement the network since the redundancy capability may changed - List routers = _routerDao.listByNetworkAndRole(network.getId(), Role.DHCP_FIREWALL_LB_PASSWD_USERDATA); - if (routers == null || routers.isEmpty()) { - s_logger.trace("Can't find virtual router element in network " + network.getId()); - return true; - } - - /* Get the host_id in order to find the cluster */ - Long host_id = new Long(0); - for (DomainRouterVO router : routers) { - if (host_id == null || host_id == 0) { - host_id = (router.getHostId() != null ? router.getHostId() : router.getLastHostId()); - } - if (cleanup) { - /* FIXME it's not completely safe to ignore these failure, but we would try to push on now */ - if (router.getState() != State.Stopped && _routerMgr.stopRouter(router.getId(), false) == null) { - s_logger.warn("Failed to stop virtual router element " + router + " as a part of network " + network + " restart"); - } - if (_routerMgr.destroyRouter(router.getId()) == null) { - s_logger.warn("Failed to destroy virtual router element " + router + " as a part of network " + network + " restart"); - } - } - } - if (host_id == null || host_id == 0) { - throw new ResourceUnavailableException("Fail to locate virtual router element in network " + network.getId(), this.getClass(), 0); - } - - /* The cluster here is only used to determine hypervisor type, not the real deployment */ - Cluster cluster = _configMgr.getCluster(_hostDao.findById(host_id).getClusterId()); - dest = new DeployDestination(dc, null, cluster, null); - return implement(network, networkOffering, dest, context); - } +// @Override +// public boolean restart(Network network, ReservationContext context, boolean cleanup) throws ConcurrentOperationException, ResourceUnavailableException, InsufficientCapacityException{ +// DataCenter dc = _configMgr.getZone(network.getDataCenterId()); +// if (!canHandle(network.getType(), network.getNetworkOfferingId())) { +// s_logger.trace("Virtual router element doesn't handle network restart for the network " + network); +// return false; +// } +// +// DeployDestination dest = new DeployDestination(dc, null, null, null); +// +// NetworkOffering networkOffering = _networkOfferingDao.findById(network.getNetworkOfferingId()); +// +// // We need to re-implement the network since the redundancy capability may changed +// List routers = _routerDao.listByNetworkAndRole(network.getId(), Role.DHCP_FIREWALL_LB_PASSWD_USERDATA); +// if (routers == null || routers.isEmpty()) { +// s_logger.trace("Can't find virtual router element in network " + network.getId()); +// return true; +// } +// +// /* Get the host_id in order to find the cluster */ +// Long host_id = new Long(0); +// for (DomainRouterVO router : routers) { +// if (host_id == null || host_id == 0) { +// host_id = (router.getHostId() != null ? router.getHostId() : router.getLastHostId()); +// } +// if (cleanup) { +// /* FIXME it's not completely safe to ignore these failure, but we would try to push on now */ +// if (router.getState() != State.Stopped && _routerMgr.stopRouter(router.getId(), false) == null) { +// s_logger.warn("Failed to stop virtual router element " + router + " as a part of network " + network + " restart"); +// } +// if (_routerMgr.destroyRouter(router.getId()) == null) { +// s_logger.warn("Failed to destroy virtual router element " + router + " as a part of network " + network + " restart"); +// } +// } +// } +// if (host_id == null || host_id == 0) { +// throw new ResourceUnavailableException("Fail to locate virtual router element in network " + network.getId(), this.getClass(), 0); +// } +// } @Override public boolean applyRules(Network config, List rules) throws ResourceUnavailableException { @@ -339,13 +330,14 @@ public class VirtualRouterElement extends DhcpElement implements VirtualRouterEl } @Override - public boolean shutdown(Network network, ReservationContext context) throws ConcurrentOperationException, ResourceUnavailableException { + public boolean shutdown(Network network, ReservationContext context, boolean cleanup) throws ConcurrentOperationException, ResourceUnavailableException { List routers = _routerDao.listByNetworkAndRole(network.getId(), Role.DHCP_FIREWALL_LB_PASSWD_USERDATA); if (routers == null || routers.isEmpty()) { return true; } boolean result = true; for (DomainRouterVO router : routers) { + //FIXME - Sheng, for your redundant router you have to destroy the domR here if clenaup=true - just the way you did in restart() method result = result && _routerMgr.stop(router, false, context.getCaller(), context.getAccount()) != null; } return result; diff --git a/server/src/com/cloud/network/firewall/FirewallManagerImpl.java b/server/src/com/cloud/network/firewall/FirewallManagerImpl.java index 69e26bc42d1..204a36ff19f 100644 --- a/server/src/com/cloud/network/firewall/FirewallManagerImpl.java +++ b/server/src/com/cloud/network/firewall/FirewallManagerImpl.java @@ -375,25 +375,27 @@ public class FirewallManagerImpl implements FirewallService, FirewallManager, Ma } @Override - public boolean applyRules(List rules, boolean continueOnError) throws ResourceUnavailableException { + public boolean applyRules(List rules, boolean continueOnError, boolean updateRulesInDB) throws ResourceUnavailableException { boolean success = true; if (!_networkMgr.applyRules(rules, continueOnError)) { s_logger.warn("Rules are not completely applied"); return false; } else { - for (FirewallRule rule : rules) { - if (rule.getState() == FirewallRule.State.Revoke) { - FirewallRuleVO relatedRule = _firewallDao.findByRelatedId(rule.getId()); - if (relatedRule != null) { - s_logger.warn("Can't remove the firewall rule id=" + rule.getId() + " as it has related firewall rule id=" + relatedRule.getId() + "; leaving it in Revoke state"); - success = false; - } else { - _firewallDao.remove(rule.getId()); + if (updateRulesInDB) { + for (FirewallRule rule : rules) { + if (rule.getState() == FirewallRule.State.Revoke) { + FirewallRuleVO relatedRule = _firewallDao.findByRelatedId(rule.getId()); + if (relatedRule != null) { + s_logger.warn("Can't remove the firewall rule id=" + rule.getId() + " as it has related firewall rule id=" + relatedRule.getId() + "; leaving it in Revoke state"); + success = false; + } else { + _firewallDao.remove(rule.getId()); + } + } else if (rule.getState() == FirewallRule.State.Add) { + FirewallRuleVO ruleVO = _firewallDao.findById(rule.getId()); + ruleVO.setState(FirewallRule.State.Active); + _firewallDao.update(ruleVO.getId(), ruleVO); } - } else if (rule.getState() == FirewallRule.State.Add) { - FirewallRuleVO ruleVO = _firewallDao.findById(rule.getId()); - ruleVO.setState(FirewallRule.State.Active); - _firewallDao.update(ruleVO.getId(), ruleVO); } } } @@ -426,7 +428,7 @@ public class FirewallManagerImpl implements FirewallService, FirewallManager, Ma } try { - if (!applyRules(rules, continueOnError)) { + if (!applyRules(rules, continueOnError, true)) { return false; } } catch (ResourceUnavailableException ex) { diff --git a/server/src/com/cloud/network/lb/ElasticLoadBalancerManagerImpl.java b/server/src/com/cloud/network/lb/ElasticLoadBalancerManagerImpl.java index caaf3d0ce16..3e303b4c3ca 100644 --- a/server/src/com/cloud/network/lb/ElasticLoadBalancerManagerImpl.java +++ b/server/src/com/cloud/network/lb/ElasticLoadBalancerManagerImpl.java @@ -217,7 +217,7 @@ public class ElasticLoadBalancerManagerImpl implements Pod pod = podId == null?null:_podDao.findById(podId); Map params = new HashMap( 1); - params.put(VirtualMachineProfile.Param.RestartNetwork, true); + params.put(VirtualMachineProfile.Param.ReProgramNetwork, true); Account owner = _accountService.getActiveAccountByName("system", new Long(1)); DeployDestination dest = new DeployDestination(dc, pod, null, null); s_logger.debug("About to deploy ELB vm "); diff --git a/server/src/com/cloud/network/lb/LoadBalancingRulesManagerImpl.java b/server/src/com/cloud/network/lb/LoadBalancingRulesManagerImpl.java index ba4741dde60..784a89f1572 100755 --- a/server/src/com/cloud/network/lb/LoadBalancingRulesManagerImpl.java +++ b/server/src/com/cloud/network/lb/LoadBalancingRulesManagerImpl.java @@ -475,14 +475,14 @@ public class LoadBalancingRulesManagerImpl implements LoadBalancingRulesManager, public boolean applyLoadBalancerConfig(long lbRuleId) throws ResourceUnavailableException { List lbs = new ArrayList(1); lbs.add(_lbDao.findById(lbRuleId)); - return applyLoadBalancerRules(lbs); + return applyLoadBalancerRules(lbs, true); } @Override public boolean applyLoadBalancersForNetwork(long networkId) throws ResourceUnavailableException { List lbs = _lbDao.listByNetworkId(networkId); if (lbs != null) { - return applyLoadBalancerRules(lbs); + return applyLoadBalancerRules(lbs, true); } else { s_logger.info("Network id=" + networkId + " doesn't have load balancer rules, nothing to apply"); return true; @@ -490,7 +490,7 @@ public class LoadBalancingRulesManagerImpl implements LoadBalancingRulesManager, } @DB - protected boolean applyLoadBalancerRules(List lbs) throws ResourceUnavailableException { + protected boolean applyLoadBalancerRules(List lbs, boolean updateRulesInDB) throws ResourceUnavailableException { Transaction txn = Transaction.currentTxn(); List rules = new ArrayList(); for (LoadBalancerVO lb : lbs) { @@ -505,38 +505,41 @@ public class LoadBalancingRulesManagerImpl implements LoadBalancingRulesManager, return false; } - for (LoadBalancerVO lb : lbs) { - txn.start(); - if (lb.getState() == FirewallRule.State.Revoke) { - _lbDao.remove(lb.getId()); - s_logger.warn("LB " + lb.getId() + " is successfully removed"); - } else if (lb.getState() == FirewallRule.State.Add) { - lb.setState(FirewallRule.State.Active); - s_logger.warn("LB rule " + lb.getId() + " state is set to Active"); - _lbDao.persist(lb); + if (updateRulesInDB) { + for (LoadBalancerVO lb : lbs) { + txn.start(); + if (lb.getState() == FirewallRule.State.Revoke) { + _lbDao.remove(lb.getId()); + s_logger.warn("LB " + lb.getId() + " is successfully removed"); + } else if (lb.getState() == FirewallRule.State.Add) { + lb.setState(FirewallRule.State.Active); + s_logger.warn("LB rule " + lb.getId() + " state is set to Active"); + _lbDao.persist(lb); + } + + // remove LB-Vm mappings that were state to revoke + List lbVmMaps = _lb2VmMapDao.listByLoadBalancerId(lb.getId(), true); + List instanceIds = new ArrayList(); + + for (LoadBalancerVMMapVO lbVmMap : lbVmMaps) { + instanceIds.add(lbVmMap.getInstanceId()); + } + + if (!instanceIds.isEmpty()) { + _lb2VmMapDao.remove(lb.getId(), instanceIds, null); + s_logger.debug("Load balancer rule id " + lb.getId() + " is removed for vms " + instanceIds); + } + + if (_lb2VmMapDao.listByLoadBalancerId(lb.getId()).isEmpty()) { + lb.setState(FirewallRule.State.Add); + _lbDao.persist(lb); + s_logger.debug("LB rule " + lb.getId() + " state is set to Add as there are no more active LB-VM mappings"); + } + + txn.commit(); } - - // remove LB-Vm mappings that were state to revoke - List lbVmMaps = _lb2VmMapDao.listByLoadBalancerId(lb.getId(), true); - List instanceIds = new ArrayList(); - - for (LoadBalancerVMMapVO lbVmMap : lbVmMaps) { - instanceIds.add(lbVmMap.getInstanceId()); - } - - if (!instanceIds.isEmpty()) { - _lb2VmMapDao.remove(lb.getId(), instanceIds, null); - s_logger.debug("Load balancer rule id " + lb.getId() + " is removed for vms " + instanceIds); - } - - if (_lb2VmMapDao.listByLoadBalancerId(lb.getId()).isEmpty()) { - lb.setState(FirewallRule.State.Add); - _lbDao.persist(lb); - s_logger.debug("LB rule " + lb.getId() + " state is set to Add as there are no more active LB-VM mappings"); - } - - txn.commit(); } + return true; } diff --git a/server/src/com/cloud/network/router/VirtualNetworkApplianceManagerImpl.java b/server/src/com/cloud/network/router/VirtualNetworkApplianceManagerImpl.java index c607f6eca23..991cd31466d 100755 --- a/server/src/com/cloud/network/router/VirtualNetworkApplianceManagerImpl.java +++ b/server/src/com/cloud/network/router/VirtualNetworkApplianceManagerImpl.java @@ -116,9 +116,9 @@ import com.cloud.network.IPAddressVO; import com.cloud.network.IpAddress; import com.cloud.network.LoadBalancerVO; import com.cloud.network.Network; +import com.cloud.network.Network.Service; import com.cloud.network.NetworkManager; import com.cloud.network.NetworkVO; -import com.cloud.network.Network.Service; import com.cloud.network.Networks.BroadcastDomainType; import com.cloud.network.Networks.IsolationType; import com.cloud.network.Networks.TrafficType; @@ -155,6 +155,7 @@ import com.cloud.offering.NetworkOffering; import com.cloud.offering.ServiceOffering; import com.cloud.offerings.NetworkOfferingVO; import com.cloud.offerings.dao.NetworkOfferingDao; +import com.cloud.resource.ResourceManager; import com.cloud.service.ServiceOfferingVO; import com.cloud.service.dao.ServiceOfferingDao; import com.cloud.storage.StorageManager; @@ -314,6 +315,8 @@ public class VirtualNetworkApplianceManagerImpl implements VirtualNetworkApplian FirewallRulesCidrsDao _firewallCidrsDao; @Inject UserVmDetailsDao _vmDetailsDao; + @Inject + ResourceManager _resourceMgr; int _routerRamSize; int _routerCpuMHz; @@ -551,7 +554,7 @@ public class VirtualNetworkApplianceManagerImpl implements VirtualNetworkApplian } @Override @ActionEvent(eventType = EventTypes.EVENT_ROUTER_REBOOT, eventDescription = "rebooting router Vm", async = true) - public VirtualRouter rebootRouter(long routerId, boolean restartNetwork) throws ConcurrentOperationException, ResourceUnavailableException, InsufficientCapacityException { + public VirtualRouter rebootRouter(long routerId, boolean reprogramNetwork) throws ConcurrentOperationException, ResourceUnavailableException, InsufficientCapacityException { Account caller = UserContext.current().getCaller(); // verify parameters @@ -572,7 +575,7 @@ public class VirtualNetworkApplianceManagerImpl implements VirtualNetworkApplian s_logger.debug("Stopping and starting router " + router + " as a part of router reboot"); if (stop(router, false, user, caller) != null) { - return startRouter(routerId, restartNetwork); + return startRouter(routerId, reprogramNetwork); } else { throw new CloudRuntimeException("Failed to reboot router " + router); } @@ -1040,6 +1043,10 @@ public class VirtualNetworkApplianceManagerImpl implements VirtualNetworkApplian return routers; } + if (routers.size() >= 5) { + s_logger.error("Too much redundant routers!"); + } + NicProfile defaultNic = new NicProfile(); //if source nat service is supported by the network, get the source nat ip address if (_networkMgr.isServiceSupportedByNetworkOffering(guestNetwork.getNetworkOfferingId(), Service.SourceNat)) { @@ -1088,15 +1095,32 @@ public class VirtualNetworkApplianceManagerImpl implements VirtualNetworkApplian networks.add(new Pair((NetworkVO) guestNetwork, gatewayNic)); networks.add(new Pair(controlConfig, null)); - - /* Before starting router, already know the hypervisor type */ - VMTemplateVO template = _templateDao.findRoutingTemplate(dest.getCluster().getHypervisorType()); - if (routers.size() >= 5) { - s_logger.error("Too much redundant routers!"); + + //Router is the network element, we don't know the hypervisor type yet. + //Try to allocate the domR twice using diff hypervisors, and when failed both times, throw the exception up + List supportedHypervisors = _resourceMgr.getSupportedHypervisorTypes(dest.getDataCenter().getId()); + int retry = 0; + for (HypervisorType hType : supportedHypervisors) { + try { + s_logger.debug("Allocating the domR with the hypervisor type " + hType); + VMTemplateVO template = _templateDao.findRoutingTemplate(hType); + + router = new DomainRouterVO(id, _offering.getId(), 0, VirtualMachineName.getRouterName(id, _instance), template.getId(), template.getHypervisorType(), + template.getGuestOSId(), owner.getDomainId(), owner.getId(), guestNetwork.getId(), isRedundant, 0, false, RedundantState.UNKNOWN, _offering.getOfferHA(), false); + router = _itMgr.allocate(router, template, _offering, networks, plan, null, owner); + break; + } catch (InsufficientCapacityException ex) { + if (retry < 2) { + s_logger.debug("Failed to allocate the domR with hypervisor type " + hType + ", retrying one more time"); + } else { + throw ex; + } + } finally { + retry++; + } } - router = new DomainRouterVO(id, _offering.getId(), 0, VirtualMachineName.getRouterName(id, _instance), template.getId(), template.getHypervisorType(), - template.getGuestOSId(), owner.getDomainId(), owner.getId(), guestNetwork.getId(), isRedundant, 0, false, RedundantState.UNKNOWN, _offering.getOfferHA(), false); - router = _itMgr.allocate(router, template, _offering, networks, plan, null, owner); + routers.add(router); + // Creating stats entry for router UserStatisticsVO stats = _userStatsDao.findBy(owner.getId(), dcId, router.getNetworkId(), null, router.getId(), router.getType().toString()); if (stats == null) { @@ -1106,7 +1130,7 @@ public class VirtualNetworkApplianceManagerImpl implements VirtualNetworkApplian stats = new UserStatisticsVO(owner.getId(), dcId, null, router.getId(), router.getType().toString(), guestNetwork.getId()); _userStatsDao.persist(stats); } - routers.add(router); + } } finally { if (network != null) { @@ -1276,13 +1300,32 @@ public class VirtualNetworkApplianceManagerImpl implements VirtualNetworkApplian networks.add(new Pair((NetworkVO) guestNetwork, gatewayNic)); networks.add(new Pair(controlConfig, null)); - /* Before starting router, already know the hypervisor type */ - VMTemplateVO template = _templateDao.findRoutingTemplate(dest.getCluster().getHypervisorType()); + //Router is the network element, we don't know the hypervisor type yet. + //Try to allocate the domR twice using diff hypervisors, and when failed both times, throw the exception up + List supportedHypervisors = _resourceMgr.getSupportedHypervisorTypes(dest.getDataCenter().getId()); + int retry = 0; + for (HypervisorType hType : supportedHypervisors) { + try { + s_logger.debug("Allocating the domR with the hypervisor type " + hType); + /* Before starting router, already know the hypervisor type */ + VMTemplateVO template = _templateDao.findRoutingTemplate(hType); - router = new DomainRouterVO(id, _offering.getId(), 0, VirtualMachineName.getRouterName(id, _instance), template.getId(), template.getHypervisorType(), - template.getGuestOSId(), owner.getDomainId(), owner.getId(), guestNetwork.getId(), false, 0, false, RedundantState.UNKNOWN, _offering.getOfferHA(), false); - router.setRole(Role.DHCP_USERDATA); - router = _itMgr.allocate(router, template, _offering, networks, plan, null, owner); + router = new DomainRouterVO(id, _offering.getId(), 0, VirtualMachineName.getRouterName(id, _instance), template.getId(), template.getHypervisorType(), + template.getGuestOSId(), owner.getDomainId(), owner.getId(), guestNetwork.getId(), false, 0, false, RedundantState.UNKNOWN, _offering.getOfferHA(), false); + router.setRole(Role.DHCP_USERDATA); + router = _itMgr.allocate(router, template, _offering, networks, plan, null, owner); + break; + } catch (InsufficientCapacityException ex) { + if (retry < 2) { + s_logger.debug("Failed to allocate the domR with hypervisor type " + hType + ", retrying one more time"); + } else { + throw ex; + } + } finally { + retry++; + } + } + routers.add(router); // Creating stats entry for router @@ -1556,12 +1599,12 @@ public class VirtualNetworkApplianceManagerImpl implements VirtualNetworkApplian cmds.addCommand("networkUsage", new NetworkUsageCommand(controlNic.getIp4Address(), router.getHostName(), "create")); // restart network if restartNetwork = false is not specified in profile parameters - boolean restartNetwork = true; - if (profile.getParameter(Param.RestartNetwork) != null && (Boolean) profile.getParameter(Param.RestartNetwork) == false) { - restartNetwork = false; + boolean reprogramNetwork = true; + if (profile.getParameter(Param.ReProgramNetwork) != null && (Boolean) profile.getParameter(Param.ReProgramNetwork) == false) { + reprogramNetwork = false; } // The commands should be sent for domR only, skip for DHCP - if (router.getRole() == VirtualRouter.Role.DHCP_FIREWALL_LB_PASSWD_USERDATA && restartNetwork) { + if (router.getRole() == VirtualRouter.Role.DHCP_FIREWALL_LB_PASSWD_USERDATA && reprogramNetwork) { s_logger.debug("Resending ipAssoc, port forwarding, load balancing rules as a part of Virtual router start"); long networkId = router.getNetworkId(); long ownerId = router.getAccountId(); @@ -2057,7 +2100,7 @@ public class VirtualNetworkApplianceManagerImpl implements VirtualNetworkApplian } @Override - public VirtualRouter startRouter(long routerId, boolean restartNetwork) throws ResourceUnavailableException, InsufficientCapacityException, ConcurrentOperationException { + public VirtualRouter startRouter(long routerId, boolean reprogramNetwork) throws ResourceUnavailableException, InsufficientCapacityException, ConcurrentOperationException { Account caller = UserContext.current().getCaller(); User callerUser = _accountMgr.getActiveUser(UserContext.current().getCallerUserId()); @@ -2091,10 +2134,10 @@ public class VirtualNetworkApplianceManagerImpl implements VirtualNetworkApplian UserVO user = _userDao.findById(UserContext.current().getCallerUserId()); Map params = new HashMap(); - if (restartNetwork) { - params.put(Param.RestartNetwork, true); + if (reprogramNetwork) { + params.put(Param.ReProgramNetwork, true); } else { - params.put(Param.RestartNetwork, false); + params.put(Param.ReProgramNetwork, false); } return startVirtualRouter(router, user, caller, params); } diff --git a/server/src/com/cloud/network/rules/FirewallManager.java b/server/src/com/cloud/network/rules/FirewallManager.java index 13a24e4b54b..fd747ea1606 100644 --- a/server/src/com/cloud/network/rules/FirewallManager.java +++ b/server/src/com/cloud/network/rules/FirewallManager.java @@ -49,7 +49,7 @@ public interface FirewallManager extends FirewallService{ void validateFirewallRule(Account caller, IPAddressVO ipAddress, Integer portStart, Integer portEnd, String proto, Purpose purpose); - boolean applyRules(List rules, boolean continueOnError) throws ResourceUnavailableException; + boolean applyRules(List rules, boolean continueOnError, boolean updateRulesInDB) throws ResourceUnavailableException; boolean applyFirewallRules(List rules, boolean continueOnError, Account caller); diff --git a/server/src/com/cloud/network/rules/RulesManager.java b/server/src/com/cloud/network/rules/RulesManager.java index 04ea5829a75..2edcbbe8278 100644 --- a/server/src/com/cloud/network/rules/RulesManager.java +++ b/server/src/com/cloud/network/rules/RulesManager.java @@ -44,7 +44,7 @@ public interface RulesManager extends RulesService { boolean revokeAllPFAndStaticNatRulesForIp(long ipId, long userId, Account caller) throws ResourceUnavailableException; - boolean revokeAllRulesForNetwork(long networkId, long userId, Account caller) throws ResourceUnavailableException; + boolean revokeAllPFStaticNatRulesForNetwork(long networkId, long userId, Account caller) throws ResourceUnavailableException; List listFirewallRulesByIp(long ipAddressId); diff --git a/server/src/com/cloud/network/rules/RulesManagerImpl.java b/server/src/com/cloud/network/rules/RulesManagerImpl.java index a6c1046b1ce..02ade29b14b 100755 --- a/server/src/com/cloud/network/rules/RulesManagerImpl.java +++ b/server/src/com/cloud/network/rules/RulesManagerImpl.java @@ -616,7 +616,7 @@ public class RulesManagerImpl implements RulesManager, RulesService, Manager { } try { - if (!_firewallMgr.applyRules(rules, continueOnError)) { + if (!_firewallMgr.applyRules(rules, continueOnError, true)) { return false; } } catch (ResourceUnavailableException ex) { @@ -664,7 +664,7 @@ public class RulesManagerImpl implements RulesManager, RulesService, Manager { } try { - if (!_firewallMgr.applyRules(staticNatRules, continueOnError)) { + if (!_firewallMgr.applyRules(staticNatRules, continueOnError, true)) { return false; } } catch (ResourceUnavailableException ex) { @@ -688,7 +688,7 @@ public class RulesManagerImpl implements RulesManager, RulesService, Manager { } try { - if (!_firewallMgr.applyRules(rules, continueOnError)) { + if (!_firewallMgr.applyRules(rules, continueOnError, true)) { return false; } } catch (ResourceUnavailableException ex) { @@ -718,7 +718,7 @@ public class RulesManagerImpl implements RulesManager, RulesService, Manager { } try { - if (!_firewallMgr.applyRules(staticNatRules, continueOnError)) { + if (!_firewallMgr.applyRules(staticNatRules, continueOnError, true)) { return false; } } catch (ResourceUnavailableException ex) { @@ -894,7 +894,7 @@ public class RulesManagerImpl implements RulesManager, RulesService, Manager { } @Override - public boolean revokeAllRulesForNetwork(long networkId, long userId, Account caller) throws ResourceUnavailableException { + public boolean revokeAllPFStaticNatRulesForNetwork(long networkId, long userId, Account caller) throws ResourceUnavailableException { List rules = new ArrayList(); List pfRules = _forwardingDao.listByNetwork(networkId); diff --git a/server/src/com/cloud/resource/ResourceManager.java b/server/src/com/cloud/resource/ResourceManager.java index 526c22bb642..874c287cf91 100755 --- a/server/src/com/cloud/resource/ResourceManager.java +++ b/server/src/com/cloud/resource/ResourceManager.java @@ -17,13 +17,12 @@ */ package com.cloud.resource; -import com.cloud.host.Host; /** * ResourceManager manages how physical resources are organized within the * CloudStack. It also manages the life cycle of the physical resources. */ -public interface ResourceManager { +public interface ResourceManager extends ResourceService{ /** * Register a listener for different types of resource life cycle events. * There can only be one type of listener per type of host. diff --git a/server/src/com/cloud/resource/ResourceManagerImpl.java b/server/src/com/cloud/resource/ResourceManagerImpl.java index 64dd5e1a924..015473181aa 100755 --- a/server/src/com/cloud/resource/ResourceManagerImpl.java +++ b/server/src/com/cloud/resource/ResourceManagerImpl.java @@ -972,5 +972,17 @@ public class ResourceManagerImpl implements ResourceManager, ResourceService, Ma public String getName() { return _name; } + + @Override + public List getSupportedHypervisorTypes(long zoneId) { + List hypervisorTypes = new ArrayList(); + + List clustersForZone = _clusterDao.listByZoneId(zoneId); + for (ClusterVO cluster : clustersForZone) { + hypervisorTypes.add(cluster.getHypervisorType()); + } + + return hypervisorTypes; + } } diff --git a/server/src/com/cloud/vm/UserVmManagerImpl.java b/server/src/com/cloud/vm/UserVmManagerImpl.java index 22185fa8ba4..13da1a6ae10 100755 --- a/server/src/com/cloud/vm/UserVmManagerImpl.java +++ b/server/src/com/cloud/vm/UserVmManagerImpl.java @@ -122,6 +122,7 @@ import com.cloud.network.Network.Service; import com.cloud.network.NetworkManager; import com.cloud.network.NetworkVO; import com.cloud.network.Networks.TrafficType; +import com.cloud.network.PhysicalNetwork; import com.cloud.network.dao.FirewallRulesDao; import com.cloud.network.dao.IPAddressDao; import com.cloud.network.dao.LoadBalancerDao; @@ -2174,14 +2175,16 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, Manager // If it's 0, and there are no default direct networks, create default Guest Virtual network List defaultVirtualOffering = _networkOfferingDao.listByTrafficTypeAndType(false, TrafficType.Guest, Network.Type.Isolated); + PhysicalNetwork physicalNetwork = _networkMgr.translateZoneIdToPhysicalNetwork(zone.getId()); if (defaultVirtualOffering.get(0).getAvailability() == Availability.Required) { // get Virtual netowrks List virtualNetworks = _networkMgr.listNetworksForAccount(owner.getId(), zone.getId(), Network.Type.Isolated, true); + if (virtualNetworks.isEmpty()) { s_logger.debug("Creating default Virtual network for account " + owner + " as a part of deployVM process"); Network newNetwork = _networkMgr.createNetwork(defaultVirtualOffering.get(0).getId(), owner.getAccountName() + "-network", owner.getAccountName() + "-network", null, null, - null, null, null, owner, false, null, null, false, null); + null, null, null, owner, false, null, null, false, physicalNetwork); defaultNetwork = _networkDao.findById(newNetwork.getId()); } else if (virtualNetworks.size() > 1) { throw new InvalidParameterValueException("More than 1 default Virtaul networks are found for account " + owner + "; please specify networkIds"); @@ -2194,7 +2197,7 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, Manager if (defaultVirtualOffering.get(0).getAvailability() == Availability.Optional) { s_logger.debug("Creating default Virtual network for account " + owner + " as a part of deployVM process"); Network newNetwork = _networkMgr.createNetwork(defaultVirtualOffering.get(0).getId(), owner.getAccountName() + "-network", owner.getAccountName() + "-network", null, null, - null, null, null, owner, false, null, null, false, null); + null, null, null, owner, false, null, null, false, physicalNetwork); defaultNetwork = _networkDao.findById(newNetwork.getId()); } else { throw new InvalidParameterValueException("Unable to find default networks for account " + owner); @@ -3338,11 +3341,12 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, Manager } } for (NetworkVO oldNet: oldNetworks){ - long networkOffering = oldNet.getNetworkOfferingId(); + long networkOffering = oldNet.getNetworkOfferingId(); + PhysicalNetwork physicalNetwork = _networkMgr.translateZoneIdToPhysicalNetwork(zone.getId()); List virtualNetworks = _networkMgr.listNetworksForAccount(newAccount.getId(), zone.getId(), Network.Type.Isolated, true); if (virtualNetworks.isEmpty()) { Network newNetwork = _networkMgr.createNetwork(networkOffering, newAccount.getAccountName() + "-network", newAccount.getAccountName() + "-network", null, null, - null, null, null, newAccount, false, null, null, false, null); + null, null, null, newAccount, false, null, null, false, physicalNetwork); defaultNetwork = _networkDao.findById(newNetwork.getId()); } else if (virtualNetworks.size() > 1) { throw new InvalidParameterValueException("More than 1 default Virtaul networks are found for account " + newAccount + "; please specify networkIds"); diff --git a/server/test/com/cloud/network/MockNetworkManagerImpl.java b/server/test/com/cloud/network/MockNetworkManagerImpl.java index 2e4030ad1d7..7b4bf33deab 100644 --- a/server/test/com/cloud/network/MockNetworkManagerImpl.java +++ b/server/test/com/cloud/network/MockNetworkManagerImpl.java @@ -48,7 +48,7 @@ import com.cloud.vm.VirtualMachineProfile; public class MockNetworkManagerImpl implements NetworkManager, Manager, NetworkService { @Override - public List getVirtualNetworksOwnedByAccountInZone(long zoneId, Account owner) { + public List getIsolatedNetworksOwnedByAccountInZone(long zoneId, Account owner) { // TODO Auto-generated method stub return null; } @@ -126,7 +126,7 @@ public class MockNetworkManagerImpl implements NetworkManager, Manager, NetworkS } @Override - public Map> getNetworkCapabilities(long networkId, long zoneId) { + public Map> getNetworkCapabilities(long networkId) { // TODO Auto-generated method stub return null; } @@ -480,7 +480,7 @@ public class MockNetworkManagerImpl implements NetworkManager, Manager, NetworkS } @Override - public Network updateNetwork(long networkId, String name, String displayText, List tags, Account caller, String domainSuffix, long networkOfferingId) { + public Network updateNetwork(long networkId, String name, String displayText, List tags, Account caller, String domainSuffix, Long networkOfferingId) { // TODO Auto-generated method stub return null; } From 96843be30a409db0a504aa75ea0c8ad18284cfda Mon Sep 17 00:00:00 2001 From: alena Date: Tue, 25 Oct 2011 18:48:59 -0700 Subject: [PATCH 032/159] Pass cleanup parametet to shutdown() method of the networkElement. Based on this parameter, the element can decide if it wants to destroy the instances, or just shut them down --- .../src/com/cloud/network/NetworkManager.java | 2 +- .../com/cloud/network/NetworkManagerImpl.java | 18 +++++++++--------- .../cloud/network/MockNetworkManagerImpl.java | 2 +- 3 files changed, 11 insertions(+), 11 deletions(-) diff --git a/server/src/com/cloud/network/NetworkManager.java b/server/src/com/cloud/network/NetworkManager.java index 229cabc1e59..99dd28c75de 100644 --- a/server/src/com/cloud/network/NetworkManager.java +++ b/server/src/com/cloud/network/NetworkManager.java @@ -151,7 +151,7 @@ public interface NetworkManager extends NetworkService { void prepareNicForMigration(VirtualMachineProfile vm, DeployDestination dest); - void shutdownNetwork(long networkId, ReservationContext context); + void shutdownNetwork(long networkId, ReservationContext context, boolean cleanupElements); boolean destroyNetwork(long networkId, ReservationContext context); diff --git a/server/src/com/cloud/network/NetworkManagerImpl.java b/server/src/com/cloud/network/NetworkManagerImpl.java index 17bd4d6875b..cdcf3fdf4a6 100755 --- a/server/src/com/cloud/network/NetworkManagerImpl.java +++ b/server/src/com/cloud/network/NetworkManagerImpl.java @@ -1302,7 +1302,7 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag network.setState(Network.State.Shutdown); _networksDao.update(networkId, network); - shutdownNetwork(networkId, context); + shutdownNetwork(networkId, context, false); } _networksDao.releaseFromLockTable(networkId); } @@ -2133,7 +2133,7 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag @Override @DB - public void shutdownNetwork(long networkId, ReservationContext context) { + public void shutdownNetwork(long networkId, ReservationContext context, boolean cleanupElements) { Transaction txn = Transaction.currentTxn(); txn.start(); @@ -2161,7 +2161,7 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag s_logger.debug("Sending network shutdown to " + element.getName()); } - element.shutdown(network, context, false); + element.shutdown(network, context, cleanupElements); } catch (ResourceUnavailableException e) { s_logger.warn("Unable to complete shutdown of the network due to element: " + element.getName(), e); success = false; @@ -2225,7 +2225,7 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag } // Shutdown network first - shutdownNetwork(networkId, context); + shutdownNetwork(networkId, context, false); // get updated state for the network network = _networksDao.findById(networkId); @@ -2438,7 +2438,7 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag ReservationContext context = new ReservationContextImpl(null, null, caller, owner); - shutdownNetwork(networkId, context); + shutdownNetwork(networkId, context, false); } catch (Exception e) { s_logger.warn("Unable to shutdown network: " + networkId); } @@ -2472,7 +2472,7 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag _accountMgr.checkAccess(callerAccount, null, network); - boolean success = restartNetwork(networkId, callerAccount, null); + boolean success = restartNetwork(networkId, callerAccount, null, cleanup); if (success) { s_logger.debug("Network id=" + networkId + " is restarted successfully."); @@ -2503,7 +2503,7 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag } } - private boolean restartNetwork(long networkId, Account caller, Long newNetworkOfferingId) throws ConcurrentOperationException, ResourceUnavailableException, InsufficientCapacityException { + private boolean restartNetwork(long networkId, Account caller, Long newNetworkOfferingId, boolean cleanup) throws ConcurrentOperationException, ResourceUnavailableException, InsufficientCapacityException { NetworkVO network = _networksDao.findById(networkId); @@ -2513,7 +2513,7 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag ReservationContext context = new ReservationContextImpl(null, null, null, caller); s_logger.debug("Shutting down the network id=" + networkId + " as a part of network restart"); - shutdownNetwork(networkId, context); + shutdownNetwork(networkId, context, cleanup); //check that the network was shutdown properly network = _networksDao.findById(networkId); @@ -3198,7 +3198,7 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag s_logger.info("Restarting network " + network + " as a part of update network call"); try { - success = restartNetwork(networkId, caller, networkOfferingId); + success = restartNetwork(networkId, caller, networkOfferingId, true); } catch (Exception e) { success = false; } diff --git a/server/test/com/cloud/network/MockNetworkManagerImpl.java b/server/test/com/cloud/network/MockNetworkManagerImpl.java index 7b4bf33deab..aab5b9f170d 100644 --- a/server/test/com/cloud/network/MockNetworkManagerImpl.java +++ b/server/test/com/cloud/network/MockNetworkManagerImpl.java @@ -328,7 +328,7 @@ public class MockNetworkManagerImpl implements NetworkManager, Manager, NetworkS } @Override - public void shutdownNetwork(long networkId, ReservationContext context) { + public void shutdownNetwork(long networkId, ReservationContext context, boolean cleanupElements) { // TODO Auto-generated method stub } From 809f9d965e46b90e2f316e2f25214d6a7683ef04 Mon Sep 17 00:00:00 2001 From: prachi Date: Tue, 25 Oct 2011 18:48:50 -0700 Subject: [PATCH 033/159] Fixed NetworkMgr: getNetworkCapabilities. The key used to get the capabilities from the provider capabilities map was wrong. --- .../src/com/cloud/configuration/ConfigurationManagerImpl.java | 1 + server/src/com/cloud/network/NetworkManagerImpl.java | 4 ++-- 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/server/src/com/cloud/configuration/ConfigurationManagerImpl.java b/server/src/com/cloud/configuration/ConfigurationManagerImpl.java index e9661946e8b..1a44e8feebe 100755 --- a/server/src/com/cloud/configuration/ConfigurationManagerImpl.java +++ b/server/src/com/cloud/configuration/ConfigurationManagerImpl.java @@ -1808,6 +1808,7 @@ public class ConfigurationManagerImpl implements ConfigurationManager, Configura Boolean forVirtualNetwork = cmd.isForVirtualNetwork(); Long networkId = cmd.getNetworkID(); String networkVlanId = null; + Long physicalNetworkId = cmd.getPhysicalNetworkId(); //projectId and accountName can't be specified together String accountName = cmd.getAccountName(); diff --git a/server/src/com/cloud/network/NetworkManagerImpl.java b/server/src/com/cloud/network/NetworkManagerImpl.java index cdcf3fdf4a6..08ceb40dc4d 100755 --- a/server/src/com/cloud/network/NetworkManagerImpl.java +++ b/server/src/com/cloud/network/NetworkManagerImpl.java @@ -2623,8 +2623,8 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag NetworkElement element = getElementImplementingProvider(instance.getProvider()); if(element != null){ Map> elementCapabilities = element.getCapabilities();; - if (elementCapabilities != null && elementCapabilities.get(service) != null) { - networkCapabilities.put(service, elementCapabilities.get(instance.getService())); + if (elementCapabilities != null) { + networkCapabilities.put(service, elementCapabilities.get(service)); } } } From a48ee9c568b36a0c60ad62689c7682b993aa7419 Mon Sep 17 00:00:00 2001 From: Murali Reddy Date: Thu, 27 Oct 2011 03:07:30 +0530 Subject: [PATCH 034/159] add support for multiple provider instanes per physical network refactor NetworkDevicemanager and ExternalnetworkdeviceManager in to one single manager --- api/src/com/cloud/api/ApiConstants.java | 2 - api/src/com/cloud/network/Network.java | 2 +- ...PXResource.java => NetscalerResource.java} | 6 +- .../api/commands/AddExternalFirewallCmd.java | 12 - .../commands/AddExternalLoadBalancerCmd.java | 14 - .../api/commands/AddNetworkDeviceCmd.java | 6 +- .../api/commands/DeleteNetworkDeviceCmd.java | 6 +- .../commands/ListExternalFirewallsCmd.java | 14 - .../ListExternalLoadBalancersCmd.java | 14 - .../api/commands/ListNetworkDeviceCmd.java | 6 +- .../PremiumComponentLibrary.java | 2 - .../network/ExternalNetworkDeviceManager.java | 124 +- .../ExternalNetworkDeviceManagerImpl.java | 1415 ++++++++++------- .../cloud/network/NetworkDeviceManager.java | 38 - .../network/NetworkDeviceManagerImpl.java | 224 --- .../com/cloud/network/NetworkManagerImpl.java | 7 +- .../PhysicalNetworkExternalDeviceVO.java | 64 + .../dao/PhysicalNetworkExternalDeviceDao.java | 29 + .../PhysicalNetworkExternalDeviceDaoImpl.java | 49 + .../PhysicalNetworkServiceProviderDao.java | 2 +- ...PhysicalNetworkServiceProviderDaoImpl.java | 13 + .../NetscalerExternalLoadBalancerElement.java | 4 +- setup/db/create-schema.sql | 9 + 23 files changed, 1089 insertions(+), 973 deletions(-) rename core/src/com/cloud/network/resource/{NetscalerMPXResource.java => NetscalerResource.java} (99%) delete mode 100644 server/src/com/cloud/network/NetworkDeviceManager.java delete mode 100644 server/src/com/cloud/network/NetworkDeviceManagerImpl.java create mode 100644 server/src/com/cloud/network/PhysicalNetworkExternalDeviceVO.java create mode 100644 server/src/com/cloud/network/dao/PhysicalNetworkExternalDeviceDao.java create mode 100644 server/src/com/cloud/network/dao/PhysicalNetworkExternalDeviceDaoImpl.java diff --git a/api/src/com/cloud/api/ApiConstants.java b/api/src/com/cloud/api/ApiConstants.java index ea2fd64111f..603f178df68 100755 --- a/api/src/com/cloud/api/ApiConstants.java +++ b/api/src/com/cloud/api/ApiConstants.java @@ -238,8 +238,6 @@ public class ApiConstants { public static final String PING_CIFS_PASSWORD = "pingcifspassword"; public static final String CHECKSUM="checksum"; public static final String NETWORK_DEVICE_TYPE = "networkdevicetype"; - public static final String EXTERNAL_LB_TYPE = "externallbtype"; - public static final String EXTERNAL_FIREWALL_TYPE = "externalfirewalltype"; public static final String NETWORK_DEVICE_PARAMETER_LIST = "networkdeviceparameterlist"; public static final String ZONE_TOKEN = "zonetoken"; public static final String DHCP_PROVIDER = "dhcpprovider"; diff --git a/api/src/com/cloud/network/Network.java b/api/src/com/cloud/network/Network.java index eeb3b3a709c..e9b5c1250ea 100644 --- a/api/src/com/cloud/network/Network.java +++ b/api/src/com/cloud/network/Network.java @@ -113,7 +113,7 @@ public interface Network extends ControlledEntity { public static final Provider DhcpServer = new Provider("DhcpServer", false); public static final Provider JuniperSRX = new Provider("JuniperSRX", true); public static final Provider F5BigIp = new Provider("F5BigIp", true); - public static final Provider NetscalerMPX = new Provider("NetscalerMPX", true); + public static final Provider Netscaler = new Provider("Netscaler", true); public static final Provider ExternalDhcpServer = new Provider("ExternalDhcpServer", true); public static final Provider ExternalGateWay = new Provider("ExternalGateWay", true); public static final Provider ElasticLoadBalancerVm = new Provider("ElasticLoadBalancerVm", false); diff --git a/core/src/com/cloud/network/resource/NetscalerMPXResource.java b/core/src/com/cloud/network/resource/NetscalerResource.java similarity index 99% rename from core/src/com/cloud/network/resource/NetscalerMPXResource.java rename to core/src/com/cloud/network/resource/NetscalerResource.java index 3c25a83feb1..231e1f29e2c 100644 --- a/core/src/com/cloud/network/resource/NetscalerMPXResource.java +++ b/core/src/com/cloud/network/resource/NetscalerResource.java @@ -74,7 +74,7 @@ class NitroError { static final int NS_NO_SERIVCE = 344; } -public class NetscalerMPXResource implements ServerResource { +public class NetscalerResource implements ServerResource { // deployment configuration private String _name; @@ -88,7 +88,7 @@ public class NetscalerMPXResource implements ServerResource { private String _guid; private boolean _inline; - private static final Logger s_logger = Logger.getLogger(NetscalerMPXResource.class); + private static final Logger s_logger = Logger.getLogger(NetscalerResource.class); protected Gson _gson; private String _objectNamePathSep = "-"; @@ -96,7 +96,7 @@ public class NetscalerMPXResource implements ServerResource { Long timeout = new Long(100000); base_response apiCallResult; - public NetscalerMPXResource () { + public NetscalerResource () { _gson = GsonHelper.getGsonLogger(); } diff --git a/server/src/com/cloud/api/commands/AddExternalFirewallCmd.java b/server/src/com/cloud/api/commands/AddExternalFirewallCmd.java index bec96596d27..323b6989c5f 100644 --- a/server/src/com/cloud/api/commands/AddExternalFirewallCmd.java +++ b/server/src/com/cloud/api/commands/AddExternalFirewallCmd.java @@ -48,9 +48,6 @@ public class AddExternalFirewallCmd extends BaseCmd { @Parameter(name=ApiConstants.ZONE_ID, type=CommandType.LONG, required = true, description="Zone in which to add the external firewall appliance.") private Long zoneId; - @Parameter(name=ApiConstants.NETWORK_ID, type=CommandType.LONG, required = false, description="Pyshical network in the zone to which external firewall appliance will be added.") - private Long networkId; - @Parameter(name=ApiConstants.URL, type=CommandType.STRING, required = true, description="URL of the external firewall appliance.") private String url; @@ -60,8 +57,6 @@ public class AddExternalFirewallCmd extends BaseCmd { @Parameter(name=ApiConstants.PASSWORD, type=CommandType.STRING, required = true, description="Password of the external firewall appliance.") private String password; - @Parameter(name=ApiConstants.NETWORK_DEVICE_TYPE, type=CommandType.STRING, required = false, description="External firewall type. Now supports JuniperSRXFirewall.") - private String type; /////////////////////////////////////////////////// /////////////////// Accessors /////////////////////// ///////////////////////////////////////////////////// @@ -70,10 +65,6 @@ public class AddExternalFirewallCmd extends BaseCmd { return zoneId; } - public Long getNetworkId() { - return networkId; - } - public String getUrl() { return url; } @@ -86,9 +77,6 @@ public class AddExternalFirewallCmd extends BaseCmd { return password; } - public String getDeviceType() { - return type; - } ///////////////////////////////////////////////////// /////////////// API Implementation/////////////////// diff --git a/server/src/com/cloud/api/commands/AddExternalLoadBalancerCmd.java b/server/src/com/cloud/api/commands/AddExternalLoadBalancerCmd.java index 7fae6e9ab88..33deff71524 100644 --- a/server/src/com/cloud/api/commands/AddExternalLoadBalancerCmd.java +++ b/server/src/com/cloud/api/commands/AddExternalLoadBalancerCmd.java @@ -47,9 +47,6 @@ public class AddExternalLoadBalancerCmd extends BaseCmd { @Parameter(name=ApiConstants.ZONE_ID, type=CommandType.LONG, required = true, description="Zone in which to add the external load balancer appliance.") private Long zoneId; - @Parameter(name=ApiConstants.NETWORK_ID, type=CommandType.LONG, required = false, description="Pyshical network in the zone to which external load balancer appliance will be added.") - private Long networkId; - @Parameter(name=ApiConstants.URL, type=CommandType.STRING, required = true, description="URL of the external load balancer appliance.") private String url; @@ -59,9 +56,6 @@ public class AddExternalLoadBalancerCmd extends BaseCmd { @Parameter(name=ApiConstants.PASSWORD, type=CommandType.STRING, required = true, description="Password of the external load balancer appliance.") private String password; - @Parameter(name=ApiConstants.NETWORK_DEVICE_TYPE, type=CommandType.STRING, required = false, description="External load balancer type. Now supports NetscalerLoadBalancer, F5BigIpLoadBalancer.") - private String type; - /////////////////////////////////////////////////// /////////////////// Accessors /////////////////////// ///////////////////////////////////////////////////// @@ -70,10 +64,6 @@ public class AddExternalLoadBalancerCmd extends BaseCmd { return zoneId; } - public Long getNetworkId() { - return networkId; - } - public String getUrl() { return url; } @@ -86,10 +76,6 @@ public class AddExternalLoadBalancerCmd extends BaseCmd { return password; } - public String getDeviceType() { - return type; - } - ///////////////////////////////////////////////////// /////////////// API Implementation/////////////////// ///////////////////////////////////////////////////// diff --git a/server/src/com/cloud/api/commands/AddNetworkDeviceCmd.java b/server/src/com/cloud/api/commands/AddNetworkDeviceCmd.java index 24ec2d79cd1..fa0b4756b15 100644 --- a/server/src/com/cloud/api/commands/AddNetworkDeviceCmd.java +++ b/server/src/com/cloud/api/commands/AddNetworkDeviceCmd.java @@ -15,7 +15,7 @@ import com.cloud.exception.InvalidParameterValueException; import com.cloud.exception.ResourceAllocationException; import com.cloud.exception.ResourceUnavailableException; import com.cloud.host.Host; -import com.cloud.network.NetworkDeviceManager; +import com.cloud.network.ExternalNetworkDeviceManager; import com.cloud.server.ManagementService; import com.cloud.server.api.response.NetworkDeviceResponse; import com.cloud.utils.component.ComponentLocator; @@ -49,9 +49,9 @@ public class AddNetworkDeviceCmd extends BaseCmd { public void execute() throws ResourceUnavailableException, InsufficientCapacityException, ServerApiException, ConcurrentOperationException, ResourceAllocationException { try { - NetworkDeviceManager nwDeviceMgr; + ExternalNetworkDeviceManager nwDeviceMgr; ComponentLocator locator = ComponentLocator.getLocator(ManagementService.Name); - nwDeviceMgr = locator.getManager(NetworkDeviceManager.class); + nwDeviceMgr = locator.getManager(ExternalNetworkDeviceManager.class); Host device = nwDeviceMgr.addNetworkDevice(this); NetworkDeviceResponse response = nwDeviceMgr.getApiResponse(device); response.setObjectName("networkdevice"); diff --git a/server/src/com/cloud/api/commands/DeleteNetworkDeviceCmd.java b/server/src/com/cloud/api/commands/DeleteNetworkDeviceCmd.java index 6aa071fc78d..654e3953750 100644 --- a/server/src/com/cloud/api/commands/DeleteNetworkDeviceCmd.java +++ b/server/src/com/cloud/api/commands/DeleteNetworkDeviceCmd.java @@ -13,7 +13,7 @@ import com.cloud.exception.InsufficientCapacityException; import com.cloud.exception.InvalidParameterValueException; import com.cloud.exception.ResourceAllocationException; import com.cloud.exception.ResourceUnavailableException; -import com.cloud.network.NetworkDeviceManager; +import com.cloud.network.ExternalNetworkDeviceManager; import com.cloud.server.ManagementService; import com.cloud.utils.component.ComponentLocator; import com.cloud.utils.exception.CloudRuntimeException; @@ -39,9 +39,9 @@ public class DeleteNetworkDeviceCmd extends BaseCmd { public void execute() throws ResourceUnavailableException, InsufficientCapacityException, ServerApiException, ConcurrentOperationException, ResourceAllocationException { try { - NetworkDeviceManager nwDeviceMgr; + ExternalNetworkDeviceManager nwDeviceMgr; ComponentLocator locator = ComponentLocator.getLocator(ManagementService.Name); - nwDeviceMgr = locator.getManager(NetworkDeviceManager.class); + nwDeviceMgr = locator.getManager(ExternalNetworkDeviceManager.class); boolean result = nwDeviceMgr.deleteNetworkDevice(this); if (result) { SuccessResponse response = new SuccessResponse(getCommandName()); diff --git a/server/src/com/cloud/api/commands/ListExternalFirewallsCmd.java b/server/src/com/cloud/api/commands/ListExternalFirewallsCmd.java index ada40918c0c..c3beaf4b230 100644 --- a/server/src/com/cloud/api/commands/ListExternalFirewallsCmd.java +++ b/server/src/com/cloud/api/commands/ListExternalFirewallsCmd.java @@ -48,12 +48,6 @@ public class ListExternalFirewallsCmd extends BaseListCmd { @Parameter(name=ApiConstants.ZONE_ID, type=CommandType.LONG, required = true, description="zone Id") private long zoneId; - @Parameter(name=ApiConstants.NETWORK_ID, type=CommandType.LONG, description="Pyshical network in the zone from which which external load balancer appliance will be listed.") - private Long networkId; - - @Parameter(name=ApiConstants.NETWORK_DEVICE_TYPE, type=CommandType.STRING, description="External firewall type. Now supports only JuniperSRXFirewall.") - private String type; - ///////////////////////////////////////////////////// /////////////////// Accessors /////////////////////// ///////////////////////////////////////////////////// @@ -62,14 +56,6 @@ public class ListExternalFirewallsCmd extends BaseListCmd { return zoneId; } - public Long getNetworkId() { - return networkId; - } - - public String getDeviceType() { - return type; - } - ///////////////////////////////////////////////////// /////////////// API Implementation/////////////////// ///////////////////////////////////////////////////// diff --git a/server/src/com/cloud/api/commands/ListExternalLoadBalancersCmd.java b/server/src/com/cloud/api/commands/ListExternalLoadBalancersCmd.java index d25ba9d7d43..ecc566ecf6b 100644 --- a/server/src/com/cloud/api/commands/ListExternalLoadBalancersCmd.java +++ b/server/src/com/cloud/api/commands/ListExternalLoadBalancersCmd.java @@ -49,12 +49,6 @@ public class ListExternalLoadBalancersCmd extends BaseListCmd { @Parameter(name=ApiConstants.ZONE_ID, type=CommandType.LONG, description="zone Id") private long zoneId; - @Parameter(name=ApiConstants.NETWORK_ID, type=CommandType.LONG, description="Pyshical network in the zone from which which external load balancer appliance will be listed.") - private Long networkId; - - @Parameter(name=ApiConstants.NETWORK_DEVICE_TYPE, type=CommandType.STRING, description="External load balancer type. Now supports NetscalerLoadBalancer, F5BigIpLoadBalancer.") - private String type; - ///////////////////////////////////////////////////// /////////////////// Accessors /////////////////////// ///////////////////////////////////////////////////// @@ -63,14 +57,6 @@ public class ListExternalLoadBalancersCmd extends BaseListCmd { return zoneId; } - public Long getNetworkId() { - return networkId; - } - - public String getDeviceType() { - return type; - } - ///////////////////////////////////////////////////// /////////////// API Implementation/////////////////// ///////////////////////////////////////////////////// diff --git a/server/src/com/cloud/api/commands/ListNetworkDeviceCmd.java b/server/src/com/cloud/api/commands/ListNetworkDeviceCmd.java index 57fdcc72ee9..a66ae433d2a 100644 --- a/server/src/com/cloud/api/commands/ListNetworkDeviceCmd.java +++ b/server/src/com/cloud/api/commands/ListNetworkDeviceCmd.java @@ -19,7 +19,7 @@ import com.cloud.exception.InvalidParameterValueException; import com.cloud.exception.ResourceAllocationException; import com.cloud.exception.ResourceUnavailableException; import com.cloud.host.Host; -import com.cloud.network.NetworkDeviceManager; +import com.cloud.network.ExternalNetworkDeviceManager; import com.cloud.server.ManagementService; import com.cloud.server.api.response.NetworkDeviceResponse; import com.cloud.utils.component.ComponentLocator; @@ -52,9 +52,9 @@ public class ListNetworkDeviceCmd extends BaseListCmd { public void execute() throws ResourceUnavailableException, InsufficientCapacityException, ServerApiException, ConcurrentOperationException, ResourceAllocationException { try { - NetworkDeviceManager nwDeviceMgr; + ExternalNetworkDeviceManager nwDeviceMgr; ComponentLocator locator = ComponentLocator.getLocator(ManagementService.Name); - nwDeviceMgr = locator.getManager(NetworkDeviceManager.class); + nwDeviceMgr = locator.getManager(ExternalNetworkDeviceManager.class); List devices = nwDeviceMgr.listNetworkDevice(this); List nwdeviceResponses = new ArrayList(); ListResponse listResponse = new ListResponse(); diff --git a/server/src/com/cloud/configuration/PremiumComponentLibrary.java b/server/src/com/cloud/configuration/PremiumComponentLibrary.java index a0a758952fe..3bef79117d3 100755 --- a/server/src/com/cloud/configuration/PremiumComponentLibrary.java +++ b/server/src/com/cloud/configuration/PremiumComponentLibrary.java @@ -35,7 +35,6 @@ import com.cloud.netapp.dao.LunDaoImpl; import com.cloud.netapp.dao.PoolDaoImpl; import com.cloud.netapp.dao.VolumeDaoImpl; import com.cloud.network.ExternalNetworkDeviceManagerImpl; -import com.cloud.network.NetworkDeviceManagerImpl; import com.cloud.network.NetworkUsageManagerImpl; import com.cloud.secstorage.CommandExecLogDaoImpl; import com.cloud.secstorage.PremiumSecondaryStorageManagerImpl; @@ -70,7 +69,6 @@ public class PremiumComponentLibrary extends DefaultComponentLibrary { addManager("BareMetalVmManager", BareMetalVmManagerImpl.class); addManager("ExternalDhcpManager", ExternalDhcpManagerImpl.class); addManager("PxeServerManager", PxeServerManagerImpl.class); - addManager("NetworkDeviceManager", NetworkDeviceManagerImpl.class); addManager("NetworkUsageManager", NetworkUsageManagerImpl.class); addManager("NetappManager", NetappManagerImpl.class); } diff --git a/server/src/com/cloud/network/ExternalNetworkDeviceManager.java b/server/src/com/cloud/network/ExternalNetworkDeviceManager.java index 262f3c6c6f4..fba46e5f621 100644 --- a/server/src/com/cloud/network/ExternalNetworkDeviceManager.java +++ b/server/src/com/cloud/network/ExternalNetworkDeviceManager.java @@ -19,76 +19,108 @@ package com.cloud.network; +import java.util.ArrayList; import java.util.List; -import java.util.Map; - import com.cloud.api.commands.AddExternalFirewallCmd; import com.cloud.api.commands.AddExternalLoadBalancerCmd; +import com.cloud.api.commands.AddNetworkDeviceCmd; import com.cloud.api.commands.DeleteExternalFirewallCmd; import com.cloud.api.commands.DeleteExternalLoadBalancerCmd; +import com.cloud.api.commands.DeleteNetworkDeviceCmd; import com.cloud.api.commands.ListExternalFirewallsCmd; import com.cloud.api.commands.ListExternalLoadBalancersCmd; +import com.cloud.api.commands.ListNetworkDeviceCmd; import com.cloud.exception.ResourceUnavailableException; import com.cloud.host.Host; -import com.cloud.host.HostVO; -import com.cloud.network.NetworkDeviceManager.NetworkDeviceType; import com.cloud.network.rules.FirewallRule; import com.cloud.offering.NetworkOffering; import com.cloud.server.api.response.ExternalFirewallResponse; import com.cloud.server.api.response.ExternalLoadBalancerResponse; +import com.cloud.server.api.response.NetworkDeviceResponse; import com.cloud.utils.component.Manager; public interface ExternalNetworkDeviceManager extends Manager { - - // External Firewall methods + + public static class NetworkDevice { + private String _name; + private String _provider; + private static List supportedNetworkDevices = new ArrayList(); - public Host addExternalFirewall(AddExternalFirewallCmd cmd); + public static final NetworkDevice ExternalDhcp = new NetworkDevice("ExternalDhcp", null); + public static final NetworkDevice PxeServer = new NetworkDevice("PxeServer", null); + public static final NetworkDevice NetscalerLoadBalancer = new NetworkDevice("NetscalerLoadBalancer", Network.Provider.Netscaler.getName()); + public static final NetworkDevice F5BigIpLoadBalancer = new NetworkDevice("F5BigIpLoadBalancer", Network.Provider.F5BigIp.getName()); + public static final NetworkDevice JuniperSRXFirewall = new NetworkDevice("JuniperSRXFirewall", Network.Provider.JuniperSRX.getName()); + + public NetworkDevice(String deviceName, String ntwkServiceprovider) { + _name = deviceName; + _provider = ntwkServiceprovider; + supportedNetworkDevices.add(this); + } + + public String getName() { + return _name; + } - public Host addExternalFirewall(Long zoneId, Long physicalNetworkId, String deviceType, Map deviceParamList); + public String getNetworkServiceProvder() { + return _provider; + } - public boolean deleteExternalFirewall(DeleteExternalFirewallCmd cmd); - - public boolean deleteExternalFirewall(Long hostId); - - public List listExternalFirewalls(ListExternalFirewallsCmd cmd); - - public List listExternalFirewalls(Long zoneId, Long networkId, String deviceType); + public static NetworkDevice getNetworkDevice(String devicerName) { + for (NetworkDevice device : supportedNetworkDevices) { + if (device.getName().equalsIgnoreCase(devicerName)) { + return device; + } + } + return null; + } + } - public ExternalFirewallResponse createExternalFirewallResponse(Host externalFirewall); - - public boolean manageGuestNetworkWithExternalFirewall(boolean add, Network network, NetworkOffering offering) throws ResourceUnavailableException; - - public boolean applyFirewallRules(Network network, List rules) throws ResourceUnavailableException; + public Host addNetworkDevice(AddNetworkDeviceCmd cmd); + + public NetworkDeviceResponse getApiResponse(Host device); + + public List listNetworkDevice(ListNetworkDeviceCmd cmd); + + public boolean deleteNetworkDevice(DeleteNetworkDeviceCmd cmd); + + // External Firewall methods - public boolean applyIps(Network network, List ipAddresses) throws ResourceUnavailableException; + public Host addExternalFirewall(AddExternalFirewallCmd cmd); - public boolean manageRemoteAccessVpn(boolean create, Network network, RemoteAccessVpn vpn) throws ResourceUnavailableException; - - public boolean manageRemoteAccessVpnUsers(Network network, RemoteAccessVpn vpn, List users) throws ResourceUnavailableException; + public boolean deleteExternalFirewall(DeleteExternalFirewallCmd cmd); + + public List listExternalFirewalls(ListExternalFirewallsCmd cmd); - // External Load balancer methods - - public Host addExternalLoadBalancer(AddExternalLoadBalancerCmd cmd); + public ExternalFirewallResponse createExternalFirewallResponse(Host externalFirewall); + + public boolean manageGuestNetworkWithExternalFirewall(boolean add, Network network, NetworkOffering offering) throws ResourceUnavailableException; + + public boolean applyFirewallRules(Network network, List rules) throws ResourceUnavailableException; - public Host addExternalLoadBalancer(Long zoneId, Long physicalNetworkId, String deviceType, Map deviceParamList); + public boolean applyIps(Network network, List ipAddresses) throws ResourceUnavailableException; - public boolean deleteExternalLoadBalancer(DeleteExternalLoadBalancerCmd cmd); + public boolean manageRemoteAccessVpn(boolean create, Network network, RemoteAccessVpn vpn) throws ResourceUnavailableException; + + public boolean manageRemoteAccessVpnUsers(Network network, RemoteAccessVpn vpn, List users) throws ResourceUnavailableException; - public boolean deleteExternalLoadBalancer(Long hostId); - - public List listExternalLoadBalancers(ListExternalLoadBalancersCmd cmd); - - public List listExternalLoadBalancers(Long zoneId, Long networkId, String deviceType); - - public ExternalLoadBalancerResponse createExternalLoadBalancerResponse(Host externalLoadBalancer); - - public boolean manageGuestNetworkWithExternalLoadBalancer(boolean add, Network guestConfig) throws ResourceUnavailableException; - - public boolean applyLoadBalancerRules(Network network, List rules) throws ResourceUnavailableException; - - // General methods - - public int getVlanOffset(long physicalNetworkId, int vlanTag); - - public int getGloballyConfiguredCidrSize(); + // External Load balancer methods + + public Host addExternalLoadBalancer(AddExternalLoadBalancerCmd cmd); + + public boolean deleteExternalLoadBalancer(DeleteExternalLoadBalancerCmd cmd); + + public List listExternalLoadBalancers(ListExternalLoadBalancersCmd cmd); + + public ExternalLoadBalancerResponse createExternalLoadBalancerResponse(Host externalLoadBalancer); + + public boolean manageGuestNetworkWithExternalLoadBalancer(boolean add, Network guestConfig) throws ResourceUnavailableException; + + public boolean applyLoadBalancerRules(Network network, List rules) throws ResourceUnavailableException; + + // General methods + + public int getVlanOffset(long physicalNetworkId, int vlanTag); + + public int getGloballyConfiguredCidrSize(); } diff --git a/server/src/com/cloud/network/ExternalNetworkDeviceManagerImpl.java b/server/src/com/cloud/network/ExternalNetworkDeviceManagerImpl.java index 2e96eb6ec2a..6496526ec10 100644 --- a/server/src/com/cloud/network/ExternalNetworkDeviceManagerImpl.java +++ b/server/src/com/cloud/network/ExternalNetworkDeviceManagerImpl.java @@ -21,6 +21,7 @@ package com.cloud.network; import java.net.URI; import java.util.ArrayList; +import java.util.Collection; import java.util.HashMap; import java.util.List; import java.util.Map; @@ -51,10 +52,17 @@ import com.cloud.agent.api.to.StaticNatRuleTO; import com.cloud.api.ApiConstants; import com.cloud.api.commands.AddExternalFirewallCmd; import com.cloud.api.commands.AddExternalLoadBalancerCmd; +import com.cloud.api.commands.AddNetworkDeviceCmd; import com.cloud.api.commands.DeleteExternalFirewallCmd; import com.cloud.api.commands.DeleteExternalLoadBalancerCmd; +import com.cloud.api.commands.DeleteNetworkDeviceCmd; import com.cloud.api.commands.ListExternalFirewallsCmd; import com.cloud.api.commands.ListExternalLoadBalancersCmd; +import com.cloud.api.commands.ListNetworkDeviceCmd; +import com.cloud.baremetal.ExternalDhcpManager; +import com.cloud.baremetal.PxeServerManager; +import com.cloud.baremetal.PxeServerProfile; +import com.cloud.baremetal.PxeServerManager.PxeServerType; import com.cloud.configuration.Config; import com.cloud.configuration.dao.ConfigurationDao; import com.cloud.dc.DataCenter; @@ -70,21 +78,24 @@ import com.cloud.exception.ResourceUnavailableException; import com.cloud.host.DetailVO; import com.cloud.host.Host; import com.cloud.host.HostVO; +import com.cloud.host.Host.Type; import com.cloud.host.dao.HostDao; import com.cloud.host.dao.HostDetailsDao; -import com.cloud.network.NetworkDeviceManager.NetworkDeviceType; import com.cloud.network.Networks.TrafficType; import com.cloud.network.dao.IPAddressDao; import com.cloud.network.dao.InlineLoadBalancerNicMapDao; import com.cloud.network.dao.LoadBalancerDao; import com.cloud.network.dao.NetworkDao; import com.cloud.network.dao.PhysicalNetworkDao; +import com.cloud.network.dao.PhysicalNetworkExternalDeviceDao; +import com.cloud.network.dao.PhysicalNetworkServiceProviderDao; +import com.cloud.network.dao.PhysicalNetworkServiceProviderVO; import com.cloud.network.dao.VpnUserDao; import com.cloud.network.lb.LoadBalancingRule; import com.cloud.network.lb.LoadBalancingRule.LbDestination; import com.cloud.network.resource.F5BigIpResource; import com.cloud.network.resource.JuniperSrxResource; -import com.cloud.network.resource.NetscalerMPXResource; +import com.cloud.network.resource.NetscalerResource; import com.cloud.network.rules.FirewallRule; import com.cloud.network.rules.FirewallRule.Purpose; import com.cloud.network.rules.FirewallRuleVO; @@ -99,6 +110,9 @@ import com.cloud.offerings.dao.NetworkOfferingDao; import com.cloud.resource.ServerResource; import com.cloud.server.api.response.ExternalFirewallResponse; import com.cloud.server.api.response.ExternalLoadBalancerResponse; +import com.cloud.server.api.response.NetworkDeviceResponse; +import com.cloud.server.api.response.NwDeviceDhcpResponse; +import com.cloud.server.api.response.PxePingResponse; import com.cloud.user.Account; import com.cloud.user.AccountManager; import com.cloud.user.AccountVO; @@ -125,118 +139,316 @@ import com.cloud.vm.dao.NicDao; @Local(value = {ExternalNetworkDeviceManager.class}) public class ExternalNetworkDeviceManagerImpl implements ExternalNetworkDeviceManager { - public enum ExternalNetworkResourceName { - JuniperSrx, - F5BigIp, - NetscalerMPX; - } - - @Inject AgentManager _agentMgr; - @Inject NetworkManager _networkMgr; - @Inject HostDao _hostDao; - @Inject DataCenterDao _dcDao; - @Inject AccountDao _accountDao; - @Inject DomainRouterDao _routerDao; - @Inject IPAddressDao _ipAddressDao; - @Inject VlanDao _vlanDao; - @Inject UserStatisticsDao _userStatsDao; - @Inject NetworkDao _networkDao; - @Inject PortForwardingRulesDao _portForwardingRulesDao; - @Inject LoadBalancerDao _loadBalancerDao; - @Inject ConfigurationDao _configDao; - @Inject HostDetailsDao _detailsDao; - @Inject NetworkOfferingDao _networkOfferingDao; + public enum ExternalNetworkResourceName { + JuniperSrx, + F5BigIp, + NetscalerMPX; + } + + @Inject ExternalDhcpManager _dhcpMgr; + @Inject PxeServerManager _pxeMgr; + @Inject AgentManager _agentMgr; + @Inject NetworkManager _networkMgr; + @Inject HostDao _hostDao; + @Inject DataCenterDao _dcDao; + @Inject AccountDao _accountDao; + @Inject DomainRouterDao _routerDao; + @Inject IPAddressDao _ipAddressDao; + @Inject VlanDao _vlanDao; + @Inject UserStatisticsDao _userStatsDao; + @Inject NetworkDao _networkDao; + @Inject PortForwardingRulesDao _portForwardingRulesDao; + @Inject LoadBalancerDao _loadBalancerDao; + @Inject ConfigurationDao _configDao; + @Inject HostDetailsDao _detailsDao; + @Inject NetworkOfferingDao _networkOfferingDao; @Inject NicDao _nicDao; @Inject VpnUserDao _vpnUsersDao; @Inject InlineLoadBalancerNicMapDao _inlineLoadBalancerNicMapDao; @Inject AccountManager _accountMgr; @Inject PhysicalNetworkDao _physicalNetworkDao; + @Inject PhysicalNetworkServiceProviderDao _physicalNetworkServiceProviderDao; + @Inject PhysicalNetworkExternalDeviceDao _physicalNetworkExternalDeviceDao; - ScheduledExecutorService _executor; - int _externalNetworkStatsInterval; - - private static final org.apache.log4j.Logger s_logger = Logger.getLogger(ExternalNetworkDeviceManagerImpl.class); - protected String _name; - - @Override - public boolean configure(String name, Map params) throws ConfigurationException { - _name = name; - _externalNetworkStatsInterval = NumbersUtil.parseInt(_configDao.getValue(Config.RouterStatsInterval.key()), 300); - if (_externalNetworkStatsInterval > 0){ - _executor = Executors.newScheduledThreadPool(1, new NamedThreadFactory("ExternalNetworkMonitor")); - } - return true; - } - - @Override - public boolean start() { - if (_externalNetworkStatsInterval > 0){ - _executor.scheduleAtFixedRate(new ExternalNetworkUsageTask(), _externalNetworkStatsInterval, _externalNetworkStatsInterval, TimeUnit.SECONDS); - } - return true; - } - - @Override - public boolean stop() { - return true; - } - - @Override - public String getName() { - return _name; - } - - public String getExternalNetworkResourceGuid(long zoneId, ExternalNetworkResourceName name, String ip) { - return zoneId + "-" + name + "-" + ip; - } - - protected HostVO getExternalNetworkAppliance(long zoneId, long networkOfferingId, Host.Type type) { - DataCenterVO zone = _dcDao.findById(zoneId); - if (!_networkMgr.networkIsConfiguredForExternalNetworking(zoneId, networkOfferingId)) { - s_logger.debug("Zone " + zone.getName() + " is not configured for external networking."); - return null; - } else { - List externalNetworkAppliancesInZone = _hostDao.listBy(type, zoneId); - if (externalNetworkAppliancesInZone.size() != 1) { - return null; - } else { - return externalNetworkAppliancesInZone.get(0); - } - } - } - + ScheduledExecutorService _executor; + int _externalNetworkStatsInterval; + + private static final org.apache.log4j.Logger s_logger = Logger.getLogger(ExternalNetworkDeviceManagerImpl.class); + protected String _name; + @Override + public boolean configure(String name, Map params) throws ConfigurationException { + _name = name; + _externalNetworkStatsInterval = NumbersUtil.parseInt(_configDao.getValue(Config.RouterStatsInterval.key()), 300); + if (_externalNetworkStatsInterval > 0){ + _executor = Executors.newScheduledThreadPool(1, new NamedThreadFactory("ExternalNetworkMonitor")); + } + return true; + } + + @Override + public boolean start() { + if (_externalNetworkStatsInterval > 0){ + _executor.scheduleAtFixedRate(new ExternalNetworkUsageTask(), _externalNetworkStatsInterval, _externalNetworkStatsInterval, TimeUnit.SECONDS); + } + return true; + } + + @Override + public boolean stop() { + return true; + } + + @Override + public String getName() { + return _name; + } + + @Override + public Host addNetworkDevice(AddNetworkDeviceCmd cmd) { + Map paramList = cmd.getParamList(); + if (paramList == null) { + throw new CloudRuntimeException("Parameter list is null"); + } + + Collection paramsCollection = paramList.values(); + HashMap params = (HashMap) (paramsCollection.toArray())[0]; + if (cmd.getType().equalsIgnoreCase(NetworkDevice.ExternalDhcp.getName())) { + Long zoneId = Long.parseLong((String) params.get(ApiConstants.ZONE_ID)); + Long podId = Long.parseLong((String)params.get(ApiConstants.POD_ID)); + String type = (String) params.get(ApiConstants.DHCP_SERVER_TYPE); + String url = (String) params.get(ApiConstants.URL); + String username = (String) params.get(ApiConstants.USERNAME); + String password = (String) params.get(ApiConstants.PASSWORD); + + return _dhcpMgr.addDhcpServer(zoneId, podId, type, url, username, password); + } else if (cmd.getType().equalsIgnoreCase(NetworkDevice.PxeServer.getName())) { + Long zoneId = Long.parseLong((String) params.get(ApiConstants.ZONE_ID)); + Long podId = Long.parseLong((String)params.get(ApiConstants.POD_ID)); + String type = (String) params.get(ApiConstants.PXE_SERVER_TYPE); + String url = (String) params.get(ApiConstants.URL); + String username = (String) params.get(ApiConstants.USERNAME); + String password = (String) params.get(ApiConstants.PASSWORD); + String pingStorageServerIp = (String) params.get(ApiConstants.PING_STORAGE_SERVER_IP); + String pingDir = (String) params.get(ApiConstants.PING_DIR); + String tftpDir = (String) params.get(ApiConstants.TFTP_DIR); + String pingCifsUsername = (String) params.get(ApiConstants.PING_CIFS_USERNAME); + String pingCifsPassword = (String) params.get(ApiConstants.PING_CIFS_PASSWORD); + PxeServerProfile profile = new PxeServerProfile(zoneId, podId, url, username, password, type, pingStorageServerIp, pingDir, tftpDir, + pingCifsUsername, pingCifsPassword); + return _pxeMgr.addPxeServer(profile); + } else if (cmd.getType().equalsIgnoreCase(NetworkDevice.JuniperSRXFirewall.getName())) { + Long zoneId = Long.parseLong((String) params.get(ApiConstants.ZONE_ID)); + Long networkId = (params.get(ApiConstants.NETWORK_ID)==null)?Long.parseLong((String)params.get(ApiConstants.NETWORK_ID)):null; + return addExternalFirewall(zoneId, networkId, NetworkDevice.JuniperSRXFirewall.getName(), cmd.getParamList()); + } else if (cmd.getType().equalsIgnoreCase(NetworkDevice.NetscalerLoadBalancer.getName())) { + Long zoneId = Long.parseLong((String) params.get(ApiConstants.ZONE_ID)); + Long networkId = (params.get(ApiConstants.NETWORK_ID)==null)?Long.parseLong((String)params.get(ApiConstants.NETWORK_ID)):null; + return addExternalLoadBalancer(zoneId, networkId, NetworkDevice.NetscalerLoadBalancer.getName(), cmd.getParamList()); + } else if (cmd.getType().equalsIgnoreCase(NetworkDevice.F5BigIpLoadBalancer.getName())) { + Long zoneId = Long.parseLong((String) params.get(ApiConstants.ZONE_ID)); + Long networkId = (params.get(ApiConstants.NETWORK_ID)==null)?Long.parseLong((String)params.get(ApiConstants.NETWORK_ID)):null; + return addExternalLoadBalancer(zoneId, networkId, NetworkDevice.F5BigIpLoadBalancer.getName(), cmd.getParamList()); + } else { + throw new CloudRuntimeException("Unsupported network device type:" + cmd.getType()); + } + } + + @Override + public NetworkDeviceResponse getApiResponse(Host device) { + NetworkDeviceResponse response; + HostVO host = (HostVO)device; + _hostDao.loadDetails(host); + if (host.getType() == Host.Type.ExternalDhcp) { + NwDeviceDhcpResponse r = new NwDeviceDhcpResponse(); + r.setZoneId(host.getDataCenterId()); + r.setPodId(host.getPodId()); + r.setUrl(host.getPrivateIpAddress()); + r.setType(host.getDetail("type")); + response = r; + } else if (host.getType() == Host.Type.PxeServer) { + String pxeType = host.getDetail("type"); + if (pxeType.equalsIgnoreCase(PxeServerType.PING.getName())) { + PxePingResponse r = new PxePingResponse(); + r.setZoneId(host.getDataCenterId()); + r.setPodId(host.getPodId()); + r.setUrl(host.getPrivateIpAddress()); + r.setType(pxeType); + r.setStorageServerIp(host.getDetail("storageServer")); + r.setPingDir(host.getDetail("pingDir")); + r.setTftpDir(host.getDetail("tftpDir")); + response = r; + } else { + throw new CloudRuntimeException("Unsupported PXE server type:" + pxeType); + } + } else { + throw new CloudRuntimeException("Unsupported network device type:" + host.getType()); + } + + response.setId(device.getId()); + return response; + } + + private List listNetworkDevice(Long zoneId, Long physicalNetworkId, Long podId, Host.Type type) { + List res = new ArrayList(); + if (podId != null) { + List devs = _hostDao.listBy(type, null, podId, zoneId); + if (devs.size() == 1) { + res.add(devs.get(0)); + } else { + s_logger.debug("List " + type + ": " + devs.size() + " found"); + } + } else { + List devs = _hostDao.listBy(type, zoneId); + res.addAll(devs); + } + + return res; + } + + @Override + public List listNetworkDevice(ListNetworkDeviceCmd cmd) { + Map paramList = cmd.getParamList(); + if (paramList == null) { + throw new CloudRuntimeException("Parameter list is null"); + } + + List res; + Collection paramsCollection = paramList.values(); + HashMap params = (HashMap) (paramsCollection.toArray())[0]; + if (NetworkDevice.ExternalDhcp.getName().equalsIgnoreCase(cmd.getType())) { + Long zoneId = Long.parseLong((String) params.get(ApiConstants.ZONE_ID)); + Long podId = Long.parseLong((String)params.get(ApiConstants.POD_ID)); + res = listNetworkDevice(zoneId, null, podId, Host.Type.ExternalDhcp); + } else if (NetworkDevice.PxeServer.getName().equalsIgnoreCase(cmd.getType())) { + Long zoneId = Long.parseLong((String) params.get(ApiConstants.ZONE_ID)); + Long podId = Long.parseLong((String)params.get(ApiConstants.POD_ID)); + res = listNetworkDevice(zoneId, null, podId, Host.Type.PxeServer); + } else if (NetworkDevice.F5BigIpLoadBalancer.getName().equalsIgnoreCase(cmd.getType())) { + Long zoneId = Long.parseLong((String) params.get(ApiConstants.ZONE_ID)); + Long networkId = (params.get(ApiConstants.NETWORK_ID)==null)?Long.parseLong((String)params.get(ApiConstants.NETWORK_ID)):null; + return listExternalLoadBalancers(zoneId, networkId, NetworkDevice.F5BigIpLoadBalancer.getName()); + } else if (NetworkDevice.NetscalerLoadBalancer.getName().equalsIgnoreCase(cmd.getType())) { + Long zoneId = Long.parseLong((String) params.get(ApiConstants.ZONE_ID)); + Long networkId = (params.get(ApiConstants.NETWORK_ID)==null)?Long.parseLong((String)params.get(ApiConstants.NETWORK_ID)):null; + return listExternalLoadBalancers(zoneId, networkId, NetworkDevice.NetscalerLoadBalancer.getName()); + } else if (NetworkDevice.JuniperSRXFirewall.getName().equalsIgnoreCase(cmd.getType())) { + Long zoneId = Long.parseLong((String) params.get(ApiConstants.ZONE_ID)); + Long networkId = (params.get(ApiConstants.NETWORK_ID)==null)?Long.parseLong((String)params.get(ApiConstants.NETWORK_ID)):null; + return listExternalFirewalls(zoneId, networkId, NetworkDevice.JuniperSRXFirewall.getName()); + } else if (cmd.getType() == null){ + Long zoneId = Long.parseLong((String) params.get(ApiConstants.ZONE_ID)); + Long podId = Long.parseLong((String)params.get(ApiConstants.POD_ID)); + Long networkId = (params.get(ApiConstants.NETWORK_ID)==null)?Long.parseLong((String)params.get(ApiConstants.NETWORK_ID)):null; + List res1 = listNetworkDevice(zoneId, networkId, podId, Host.Type.PxeServer); + List res2 = listNetworkDevice(zoneId, networkId, podId, Host.Type.ExternalDhcp); + List res3 = listNetworkDevice(zoneId, networkId, podId, Host.Type.ExternalLoadBalancer); + List res4 = listNetworkDevice(zoneId, networkId, podId, Host.Type.ExternalFirewall); + List deviceAll = new ArrayList(); + deviceAll.addAll(res1); + deviceAll.addAll(res2); + deviceAll.addAll(res3); + deviceAll.addAll(res4); + res = deviceAll; + } else { + throw new CloudRuntimeException("Unknown network device type:" + cmd.getType()); + } + + return res; + } + + @Override + public boolean deleteNetworkDevice(DeleteNetworkDeviceCmd cmd) { + HostVO device = _hostDao.findById(cmd.getId()); + if (device.getType() == Type.ExternalLoadBalancer) { + return deleteExternalLoadBalancer(cmd.getId()); + } else if (device.getType() == Type.ExternalLoadBalancer) { + return deleteExternalFirewall(cmd.getId()); + } + return true; + } + + public String getExternalNetworkResourceGuid(long zoneId, ExternalNetworkResourceName name, String ip) { + return zoneId + "-" + name + "-" + ip; + } + + protected HostVO getExternalNetworkAppliance(long zoneId, long networkOfferingId, Host.Type type) { +/* DataCenterVO zone = _dcDao.findById(zoneId); + if (!_networkMgr.networkIsConfiguredForExternalNetworking(zoneId, networkOfferingId)) { + s_logger.debug("Zone " + zone.getName() + " is not configured for external networking."); + return null; + } else { + List externalNetworkAppliancesInZone = _hostDao.listBy(type, zoneId); + if (externalNetworkAppliancesInZone.size() != 1) { + return null; + } else { + return externalNetworkAppliancesInZone.get(0); + } + }*/ + return null; + } + + @Override + @Deprecated // should use more generic addNetworkDevice command to add external load balancer public Host addExternalLoadBalancer(AddExternalLoadBalancerCmd cmd) { Long zoneId = cmd.getZoneId(); - Long networkId = cmd.getNetworkId(); - String deviceType = cmd.getDeviceType(); + // AddExternalLoadBalancerCmd support only F5 Big IP (api exists for backward compatibility) + String deviceType = NetworkDevice.F5BigIpLoadBalancer.getName(); Map deviceParams = new HashMap(); deviceParams.put(ApiConstants.USERNAME, cmd.getUsername()); deviceParams.put(ApiConstants.PASSWORD, cmd.getPassword()); - deviceParams.put(ApiConstants.URL, cmd.getUrl()); - return addExternalLoadBalancer(zoneId, networkId, deviceType, deviceParams); + deviceParams.put(ApiConstants.URL, cmd.getUrl()); + return addExternalLoadBalancer(zoneId, null, deviceType, deviceParams); } - @Override - public Host addExternalLoadBalancer(Long zoneId, Long networkId, String deviceType, Map deviceParamList) { + public Host addExternalLoadBalancer(Long zoneId, Long physicalNetworkId, String deviceName, Map deviceParamList) { ServerResource resource =null; String guid; - String url = (String) deviceParamList.get(ApiConstants.URL); - String username = (String) deviceParamList.get(ApiConstants.USERNAME); - String password = (String) deviceParamList.get(ApiConstants.PASSWORD); - - DataCenterVO zone = _dcDao.findById(zoneId); - String zoneName; - if (zone == null) { - throw new InvalidParameterValueException("Could not find zone with ID: " + zoneId); - } else { - zoneName = zone.getName(); + PhysicalNetworkVO pNetwork=null; + DataCenterVO zone =null; + NetworkDevice ntwkDevice = NetworkDevice.getNetworkDevice(deviceName); + String url=null; + String username=null; + String password=null; + + if (deviceParamList != null) { + url = (String) deviceParamList.get(ApiConstants.URL); + username = (String) deviceParamList.get(ApiConstants.USERNAME); + password = (String) deviceParamList.get(ApiConstants.PASSWORD); } - List externalLoadBalancersInZone = _hostDao.listByTypeDataCenter(Host.Type.ExternalLoadBalancer, zoneId); - if (externalLoadBalancersInZone.size() != 0) { - throw new InvalidParameterValueException("Already found an external load balancer in zone: " + zoneName); + if (((zoneId == null) && (physicalNetworkId == null)) || (ntwkDevice == null) || (url == null) || (username == null) || (password == null) ) { + throw new InvalidParameterValueException("Atleast one of the required parameters (url, username, password," + + " zone id/physical network id) is not specified or a valid parameter."); + } + + if (physicalNetworkId != null) { + pNetwork = _physicalNetworkDao.findById(physicalNetworkId); + if (pNetwork == null) { + throw new InvalidParameterValueException("Could not find phyical network with ID: " + physicalNetworkId); + } + } + + if (zoneId != null) { + zone = _dcDao.findById(zoneId); + if (zone == null) { + throw new InvalidParameterValueException("Could not find zone with ID: " + zoneId); + } + if (pNetwork == null) { + List physicalNetworks = _physicalNetworkDao.listByZone(zoneId); + if ((physicalNetworks == null) || (physicalNetworks.size() > 1)) { + throw new InvalidParameterValueException("There are multiple physical networks configured in zone with ID: " + + zoneId + ". Physical network ID must be passed to select a physical network in this zonea."); + } + pNetwork = physicalNetworks.get(0); + } + } + + PhysicalNetworkServiceProviderVO ntwkSvcProider = _physicalNetworkServiceProviderDao.findByServiceProvider(pNetwork.getId(), ntwkDevice.getNetworkServiceProvder()); + if (ntwkSvcProider.getState() != PhysicalNetworkServiceProvider.State.Enabled) { //TODO: check for other states: Shutdown? + throw new CloudRuntimeException("Network Service Provider: " + ntwkSvcProider.getProviderName() + + " is not in enabled state in the physical network: " + physicalNetworkId + "to add this device" ); } URI uri; @@ -268,20 +480,16 @@ public class ExternalNetworkDeviceManagerImpl implements ExternalNetworkDeviceMa numRetries = "1"; } - if (deviceType ==null) { - deviceType = NetworkDeviceType.NetscalerLoadBalancer.getName(); //TODO: default it to Netscaler LB for now, till UI support Netscaler & F5 + if (deviceName.equalsIgnoreCase(NetworkDevice.F5BigIpLoadBalancer.getName())) { + resource = new F5BigIpResource(); + guid = getExternalNetworkResourceGuid(zoneId, ExternalNetworkResourceName.F5BigIp, ipAddress); + } else if (deviceName.equalsIgnoreCase(NetworkDevice.NetscalerLoadBalancer.getName())) { + resource = new NetscalerResource(); + guid = getExternalNetworkResourceGuid(zoneId, ExternalNetworkResourceName.NetscalerMPX, ipAddress); + } else { + throw new CloudRuntimeException("An unsupported networt device type is added as external load balancer."); } - if (deviceType.equalsIgnoreCase(NetworkDeviceType.F5BigIpLoadBalancer.getName())) { - resource = new F5BigIpResource(); - guid = getExternalNetworkResourceGuid(zoneId, ExternalNetworkResourceName.F5BigIp, ipAddress); - } else if (deviceType.equalsIgnoreCase(NetworkDeviceType.NetscalerLoadBalancer.getName())) { - resource = new NetscalerMPXResource(); - guid = getExternalNetworkResourceGuid(zoneId, ExternalNetworkResourceName.NetscalerMPX, ipAddress); - } else { - throw new CloudRuntimeException("An unsupported networt device type is added as external load balancer."); - } - Map hostDetails = new HashMap(); hostDetails.put("zoneId", String.valueOf(zoneId)); @@ -303,12 +511,11 @@ public class ExternalNetworkDeviceManagerImpl implements ExternalNetworkDeviceMa Host host = _agentMgr.addHost(zoneId, resource, Host.Type.ExternalLoadBalancer, hostDetails); if (host != null) { - if (deviceType.equalsIgnoreCase(NetworkDeviceType.F5BigIpLoadBalancer.getName())) { - zone.setLoadBalancerProvider(Network.Provider.F5BigIp.getName()); - } else if (deviceType.equalsIgnoreCase(NetworkDeviceType.NetscalerLoadBalancer.getName())) { - zone.setLoadBalancerProvider(Network.Provider.NetscalerMPX.getName()); - } - _dcDao.update(zone.getId(), zone); + Transaction txn = Transaction.currentTxn(); + txn.start(); + PhysicalNetworkExternalDeviceVO device = new PhysicalNetworkExternalDeviceVO(ntwkSvcProider.getId(), host.getId()); + _physicalNetworkExternalDeviceDao.persist(device); + txn.commit(); return host; } else { return null; @@ -320,8 +527,7 @@ public class ExternalNetworkDeviceManagerImpl implements ExternalNetworkDeviceMa return deleteExternalLoadBalancer(cmd.getId()); } - @Override - public boolean deleteExternalLoadBalancer(Long hostId) { + public boolean deleteExternalLoadBalancer(Long hostId) { User caller = _accountMgr.getActiveUser(UserContext.current().getCallerUserId()); HostVO externalLoadBalancer = _hostDao.findById(hostId); if (externalLoadBalancer == null) { @@ -330,14 +536,8 @@ public class ExternalNetworkDeviceManagerImpl implements ExternalNetworkDeviceMa try { if (_agentMgr.maintain(hostId) && _agentMgr.deleteHost(hostId, false, false, caller)) { + // FIXME: device maintenance , rules reprogramming DataCenterVO zone = _dcDao.findById(externalLoadBalancer.getDataCenterId()); - - if (zone.getNetworkType().equals(NetworkType.Advanced)) { - zone.setLoadBalancerProvider(Network.Provider.VirtualRouter.getName()); - } else if (zone.getNetworkType().equals(NetworkType.Basic)) { - zone.setLoadBalancerProvider(null); - } - return _dcDao.update(zone.getId(), zone); } else { return false; @@ -349,21 +549,48 @@ public class ExternalNetworkDeviceManagerImpl implements ExternalNetworkDeviceMa } @Override + @Deprecated // should use more generic listNetworkDevice command public List listExternalLoadBalancers(ListExternalLoadBalancersCmd cmd) { - List lbHosts = new ArrayList(); - if (NetworkDeviceType.NetscalerLoadBalancer.getName().equalsIgnoreCase(cmd.getDeviceType())) { - lbHosts.addAll(listExternalLoadBalancers(cmd.getZoneId(), cmd.getNetworkId(), NetworkDeviceType.NetscalerLoadBalancer.getName())); - } else if (NetworkDeviceType.F5BigIpLoadBalancer.getName().equalsIgnoreCase(cmd.getDeviceType())) { - lbHosts.addAll(listExternalLoadBalancers(cmd.getZoneId(), cmd.getNetworkId(), NetworkDeviceType.F5BigIpLoadBalancer.getName())); - } - return lbHosts; + List lbHosts = new ArrayList(); + lbHosts.addAll(listExternalLoadBalancers(cmd.getZoneId(), null, NetworkDevice.F5BigIpLoadBalancer.getName())); + return lbHosts; } - @Override - public List listExternalLoadBalancers(Long zoneId, Long networkId, String type) { - List lbHosts = new ArrayList(); - lbHosts.addAll(_hostDao.listByTypeDataCenter(Host.Type.ExternalLoadBalancer, zoneId)); - return lbHosts; + public List listExternalLoadBalancers(Long zoneId, Long physicalNetworkId, String deviceName) { + List lbHosts = new ArrayList(); + List lbHostsInZone = new ArrayList(); + NetworkDevice ntwkDevice = NetworkDevice.getNetworkDevice(deviceName); + PhysicalNetworkVO pNetwork=null; + + if (((zoneId == null) && (physicalNetworkId == null)) || (ntwkDevice == null)) { + throw new InvalidParameterValueException("Atleast one of ther required parameter zone Id, physical networkId, device name is missing or invalid."); + } + + if (physicalNetworkId != null) { + pNetwork = _physicalNetworkDao.findById(physicalNetworkId); + if (pNetwork == null) { + throw new InvalidParameterValueException("Could not find phyical network with ID: " + physicalNetworkId); + } + } + + if (zoneId != null) { + if (_dcDao.findById(zoneId) == null) { + throw new InvalidParameterValueException("Could not find zone with ID: " + zoneId); + } + lbHostsInZone.addAll(_hostDao.listByTypeDataCenter(Host.Type.ExternalLoadBalancer, zoneId)); + } + if (physicalNetworkId == null) { + return lbHostsInZone; + } + PhysicalNetworkServiceProviderVO ntwkSvcProider = _physicalNetworkServiceProviderDao.findByServiceProvider(pNetwork.getId(), ntwkDevice.getNetworkServiceProvder()); + if (ntwkSvcProider == null) { + return null; + } + List providerInstances = _physicalNetworkExternalDeviceDao.listByNetworkServiceProviderId(ntwkSvcProider.getId()); + for (PhysicalNetworkExternalDeviceVO provderInstance : providerInstances) { + lbHosts.add(_hostDao.findById(provderInstance.getHostId())); + } + return lbHosts; } @Override @@ -418,7 +645,7 @@ public class ExternalNetworkDeviceManagerImpl implements ExternalNetworkDeviceMa List reservedIpAddressesForGuestNetwork = _nicDao.listIpAddressInNetwork(guestConfig.getId()); if (add && (!reservedIpAddressesForGuestNetwork.contains(selfIp))) { // Insert a new NIC for this guest network to reserve the self IP - savePlaceholderNic(guestConfig, selfIp); + savePlaceholderNic(guestConfig, selfIp); } Account account = _accountDao.findByIdIncludingRemoved(guestConfig.getAccountId()); @@ -443,12 +670,12 @@ public class ExternalNetworkDeviceManagerImpl implements ExternalNetworkDeviceMa boolean externalLoadBalancerIsInline = externalLoadBalancerIsInline(externalLoadBalancer); HostVO externalFirewall = null; if (externalLoadBalancerIsInline) { - externalFirewall = getExternalNetworkAppliance(zoneId, network.getNetworkOfferingId(), Host.Type.ExternalFirewall); - if (externalFirewall == null) { - String msg = "External load balancer in zone " + zone.getName() + " is inline, but no external firewall in this zone."; - s_logger.error(msg); - throw new ResourceUnavailableException(msg, DataCenter.class, network.getDataCenterId()); - } + externalFirewall = getExternalNetworkAppliance(zoneId, network.getNetworkOfferingId(), Host.Type.ExternalFirewall); + if (externalFirewall == null) { + String msg = "External load balancer in zone " + zone.getName() + " is inline, but no external firewall in this zone."; + s_logger.error(msg); + throw new ResourceUnavailableException(msg, DataCenter.class, network.getDataCenterId()); + } } if (network.getState() == Network.State.Allocated) { @@ -477,66 +704,66 @@ public class ExternalNetworkDeviceManagerImpl implements ExternalNetworkDeviceMa List sourceCidrs = rule.getSourceCidrList(); if (externalLoadBalancerIsInline) { - InlineLoadBalancerNicMapVO mapping = _inlineLoadBalancerNicMapDao.findByPublicIpAddress(srcIp); - NicVO loadBalancingIpNic = null; - if (!revoked) { - if (mapping == null) { - // Acquire a new guest IP address and save it as the load balancing IP address - String loadBalancingIpAddress = _networkMgr.acquireGuestIpAddress(network, null); - - if (loadBalancingIpAddress == null) { - String msg = "Ran out of guest IP addresses."; - s_logger.error(msg); - throw new ResourceUnavailableException(msg, DataCenter.class, network.getDataCenterId()); - } - - // If a NIC doesn't exist for the load balancing IP address, create one - loadBalancingIpNic = _nicDao.findByIp4Address(loadBalancingIpAddress); - if (loadBalancingIpNic == null) { - loadBalancingIpNic = savePlaceholderNic(network, loadBalancingIpAddress); - } + InlineLoadBalancerNicMapVO mapping = _inlineLoadBalancerNicMapDao.findByPublicIpAddress(srcIp); + NicVO loadBalancingIpNic = null; + if (!revoked) { + if (mapping == null) { + // Acquire a new guest IP address and save it as the load balancing IP address + String loadBalancingIpAddress = _networkMgr.acquireGuestIpAddress(network, null); + + if (loadBalancingIpAddress == null) { + String msg = "Ran out of guest IP addresses."; + s_logger.error(msg); + throw new ResourceUnavailableException(msg, DataCenter.class, network.getDataCenterId()); + } + + // If a NIC doesn't exist for the load balancing IP address, create one + loadBalancingIpNic = _nicDao.findByIp4Address(loadBalancingIpAddress); + if (loadBalancingIpNic == null) { + loadBalancingIpNic = savePlaceholderNic(network, loadBalancingIpAddress); + } - // Save a mapping between the source IP address and the load balancing IP address NIC - mapping = new InlineLoadBalancerNicMapVO(rule.getId(), srcIp, loadBalancingIpNic.getId()); - _inlineLoadBalancerNicMapDao.persist(mapping); - - // On the external firewall, create a static NAT rule between the source IP address and the load balancing IP address - applyStaticNatRuleForInlineLBRule(zone, network, externalFirewall, revoked, srcIp, loadBalancingIpNic.getIp4Address()); - } else { - loadBalancingIpNic = _nicDao.findById(mapping.getNicId()); - } - } else { - if (mapping != null) { - // Find the NIC that the mapping refers to - loadBalancingIpNic = _nicDao.findById(mapping.getNicId()); - - // On the external firewall, delete the static NAT rule between the source IP address and the load balancing IP address - applyStaticNatRuleForInlineLBRule(zone, network, externalFirewall, revoked, srcIp, loadBalancingIpNic.getIp4Address()); - - // Delete the mapping between the source IP address and the load balancing IP address - _inlineLoadBalancerNicMapDao.expunge(mapping.getId()); - - // Delete the NIC - _nicDao.expunge(loadBalancingIpNic.getId()); - } else { - s_logger.debug("Revoking a rule for an inline load balancer that has not been programmed yet."); - continue; - } - } - - // Change the source IP address for the load balancing rule to be the load balancing IP address - srcIp = loadBalancingIpNic.getIp4Address(); + // Save a mapping between the source IP address and the load balancing IP address NIC + mapping = new InlineLoadBalancerNicMapVO(rule.getId(), srcIp, loadBalancingIpNic.getId()); + _inlineLoadBalancerNicMapDao.persist(mapping); + + // On the external firewall, create a static NAT rule between the source IP address and the load balancing IP address + applyStaticNatRuleForInlineLBRule(zone, network, externalFirewall, revoked, srcIp, loadBalancingIpNic.getIp4Address()); + } else { + loadBalancingIpNic = _nicDao.findById(mapping.getNicId()); + } + } else { + if (mapping != null) { + // Find the NIC that the mapping refers to + loadBalancingIpNic = _nicDao.findById(mapping.getNicId()); + + // On the external firewall, delete the static NAT rule between the source IP address and the load balancing IP address + applyStaticNatRuleForInlineLBRule(zone, network, externalFirewall, revoked, srcIp, loadBalancingIpNic.getIp4Address()); + + // Delete the mapping between the source IP address and the load balancing IP address + _inlineLoadBalancerNicMapDao.expunge(mapping.getId()); + + // Delete the NIC + _nicDao.expunge(loadBalancingIpNic.getId()); + } else { + s_logger.debug("Revoking a rule for an inline load balancer that has not been programmed yet."); + continue; + } + } + + // Change the source IP address for the load balancing rule to be the load balancing IP address + srcIp = loadBalancingIpNic.getIp4Address(); } if (destinations != null && !destinations.isEmpty()) { - LoadBalancerTO loadBalancer = new LoadBalancerTO(srcIp, srcPort, protocol, algorithm, revoked, false, destinations); - loadBalancersToApply.add(loadBalancer); + LoadBalancerTO loadBalancer = new LoadBalancerTO(srcIp, srcPort, protocol, algorithm, revoked, false, destinations); + loadBalancersToApply.add(loadBalancer); } } if (loadBalancersToApply.size() > 0) { - int numLoadBalancersForCommand = loadBalancersToApply.size(); - LoadBalancerTO[] loadBalancersForCommand = loadBalancersToApply.toArray(new LoadBalancerTO[numLoadBalancersForCommand]); + int numLoadBalancersForCommand = loadBalancersToApply.size(); + LoadBalancerTO[] loadBalancersForCommand = loadBalancersToApply.toArray(new LoadBalancerTO[numLoadBalancersForCommand]); LoadBalancerConfigCommand cmd = new LoadBalancerConfigCommand(loadBalancersForCommand); long guestVlanTag = Integer.parseInt(network.getBroadcastUri().getHost()); cmd.setAccessDetail(NetworkElementCommand.GUEST_VLAN_TAG, String.valueOf(guestVlanTag)); @@ -553,35 +780,64 @@ public class ExternalNetworkDeviceManagerImpl implements ExternalNetworkDeviceMa } @Override + @Deprecated // should use more generic addNetworkDevice command to add firewall public Host addExternalFirewall(AddExternalFirewallCmd cmd) { Long zoneId = cmd.getZoneId(); - Long networkId = cmd.getNetworkId(); - String deviceType = cmd.getDeviceType(); + // AddExternalFirewallCmd support only Juniper SRX (api exists for backward compatibility) + String deviceType = NetworkDevice.JuniperSRXFirewall.getName(); Map deviceParams = new HashMap(); deviceParams.put(ApiConstants.USERNAME, cmd.getUsername()); deviceParams.put(ApiConstants.URL, cmd.getUrl()); - deviceParams.put(ApiConstants.PASSWORD, cmd.getPassword()); - return addExternalFirewall(zoneId, networkId, deviceType, deviceParams); + deviceParams.put(ApiConstants.PASSWORD, cmd.getPassword()); + return addExternalFirewall(zoneId, null, deviceType, deviceParams); } - @Override - public Host addExternalFirewall(Long zoneId, Long networkId, String deviceType, Map deviceParamList) { + public Host addExternalFirewall(Long zoneId, Long physicalNetworkId, String deviceName, Map deviceParamList) { - DataCenterVO zone = _dcDao.findById(zoneId); - String url = (String) deviceParamList.get(ApiConstants.URL); - String username = (String) deviceParamList.get(ApiConstants.USERNAME); - String password = (String) deviceParamList.get(ApiConstants.PASSWORD); - - String zoneName; - if (zone == null) { - throw new InvalidParameterValueException("Could not find zone with ID: " + zoneId); - } else { - zoneName = zone.getName(); + PhysicalNetworkVO pNetwork=null; + DataCenterVO zone =null; + NetworkDevice ntwkDevice = NetworkDevice.getNetworkDevice(deviceName); + String url=null; + String username=null; + String password=null; + + if (deviceParamList != null) { + url = (String) deviceParamList.get(ApiConstants.URL); + username = (String) deviceParamList.get(ApiConstants.USERNAME); + password = (String) deviceParamList.get(ApiConstants.PASSWORD); } - List externalFirewallsInZone = _hostDao.listByTypeDataCenter(Host.Type.ExternalFirewall, zoneId); - if (externalFirewallsInZone.size() != 0) { - throw new InvalidParameterValueException("Already added an external firewall in zone: " + zoneName); + if (((zoneId == null) && (physicalNetworkId == null)) || (ntwkDevice == null) || (url == null) || (username == null) || (password == null) ) { + throw new InvalidParameterValueException("Atleast one of the required parameters (url, username, password," + + " zone id/physical network id) is not specified or a valid parameter."); + } + + if (physicalNetworkId != null) { + pNetwork = _physicalNetworkDao.findById(physicalNetworkId); + if (pNetwork == null) { + throw new InvalidParameterValueException("Could not find phyical network with ID: " + physicalNetworkId); + } + } + + if (zoneId != null) { + zone = _dcDao.findById(zoneId); + if (zone == null) { + throw new InvalidParameterValueException("Could not find zone with ID: " + zoneId); + } + if (pNetwork == null) { + List physicalNetworks = _physicalNetworkDao.listByZone(zoneId); + if ((physicalNetworks == null) || (physicalNetworks.size() > 1)) { + throw new InvalidParameterValueException("There are multiple physical networks configured in zone with ID: " + + zoneId + ". Physical network ID must be passed to select a physical network in this zone."); + } + pNetwork = physicalNetworks.get(0); + } + } + + PhysicalNetworkServiceProviderVO ntwkSvcProider = _physicalNetworkServiceProviderDao.findByServiceProvider(pNetwork.getId(), ntwkDevice.getNetworkServiceProvder()); + if (ntwkSvcProider.getState() != PhysicalNetworkServiceProvider.State.Enabled) { //TODO: check for other states: Shutdown? + throw new CloudRuntimeException("Network Service Provider: " + ntwkSvcProider.getProviderName() + + " is not in enabled state in the physical network: " + physicalNetworkId + "to add this device" ); } URI uri; @@ -606,7 +862,7 @@ public class ExternalNetworkDeviceManagerImpl implements ExternalNetworkDeviceMa String guid; if (publicInterface == null) { - throw new InvalidParameterValueException("Please specify a public interface."); + throw new InvalidParameterValueException("Please specify a public interface."); } if (usageInterface != null) { @@ -639,15 +895,15 @@ public class ExternalNetworkDeviceManagerImpl implements ExternalNetworkDeviceMa timeout = "300"; } - if (deviceType ==null) { - deviceType = NetworkDeviceType.JuniperSRXFirewall.getName(); //default it to Juniper for now + if (deviceName ==null) { + deviceName = NetworkDevice.JuniperSRXFirewall.getName(); //default it to Juniper for now + } + if (deviceName.equalsIgnoreCase(NetworkDevice.JuniperSRXFirewall.getName())) { + resource = new JuniperSrxResource(); + guid = getExternalNetworkResourceGuid(zoneId, ExternalNetworkResourceName.JuniperSrx, ipAddress); + } else { + throw new CloudRuntimeException("An unsupported networt device type is added as external firewall."); } - if (deviceType.equalsIgnoreCase(NetworkDeviceType.JuniperSRXFirewall.getName())) { - resource = new JuniperSrxResource(); - guid = getExternalNetworkResourceGuid(zoneId, ExternalNetworkResourceName.JuniperSrx, ipAddress); - } else { - throw new CloudRuntimeException("An unsupported networt device type is added as external firewall."); - } Map hostDetails = new HashMap(); hostDetails.put("zoneId", String.valueOf(zoneId)); @@ -675,29 +931,12 @@ public class ExternalNetworkDeviceManagerImpl implements ExternalNetworkDeviceMa Host externalFirewall = _agentMgr.addHost(zoneId, resource, Host.Type.ExternalFirewall, hostDetails); if (externalFirewall != null) { - /* With NAAS, we no longer store default global providers with Zone. - * - zone.setFirewallProvider(Network.Provider.JuniperSRX.getName()); - zone.setUserDataProvider(Network.Provider.DhcpServer.getName()); - zone.setVpnProvider(null); - - if (zone.getGatewayProvider() == null || !zone.getGatewayProvider().equals(Network.Provider.ExternalGateWay)) { - zone.setGatewayProvider(Network.Provider.JuniperSRX.getName()); - } - - if (zone.getDnsProvider() == null || !zone.getDnsProvider().equals(Network.Provider.ExternalDhcpServer)) { - zone.setDnsProvider(Network.Provider.DhcpServer.getName()); - } - - if (zone.getDhcpProvider() == null || !zone.getDhcpProvider().equals(Network.Provider.ExternalDhcpServer)) { - zone.setDhcpProvider(Network.Provider.DhcpServer.getName()); - } - - if (zone.getLoadBalancerProvider() == null || !zone.getLoadBalancerProvider().equals(Network.Provider.F5BigIp.getName())) { - zone.setLoadBalancerProvider(Network.Provider.None.getName()); - } - - _dcDao.update(zone.getId(), zone);*/ + Transaction txn = Transaction.currentTxn(); + txn.start(); + _dcDao.update(zone.getId(), zone); + PhysicalNetworkExternalDeviceVO device = new PhysicalNetworkExternalDeviceVO(ntwkSvcProider.getId(), externalFirewall.getId()); + _physicalNetworkExternalDeviceDao.persist(device); + txn.commit(); return externalFirewall; } else { return null; @@ -706,10 +945,9 @@ public class ExternalNetworkDeviceManagerImpl implements ExternalNetworkDeviceMa @Override public boolean deleteExternalFirewall(DeleteExternalFirewallCmd cmd) { - return deleteExternalFirewall(cmd.getId()); + return deleteExternalFirewall(cmd.getId()); } - @Override public boolean deleteExternalFirewall(Long hostId) { User caller = _accountMgr.getActiveUser(UserContext.current().getCallerUserId()); HostVO externalFirewall = _hostDao.findById(hostId); @@ -718,35 +956,8 @@ public class ExternalNetworkDeviceManagerImpl implements ExternalNetworkDeviceMa } try { + // FIXME: device maintenance , rules reprogramming if (_agentMgr.maintain(hostId) && _agentMgr.deleteHost(hostId, false, false, caller)) { - /* With NAAS, we do not have the concept of global providers stored with Zone - * - * DataCenterVO zone = _dcDao.findById(externalFirewall.getDataCenterId()); - zone.setFirewallProvider(Network.Provider.VirtualRouter.getName()); - zone.setUserDataProvider(Network.Provider.VirtualRouter.getName()); - zone.setVpnProvider(Network.Provider.VirtualRouter.getName()); - - if (zone.getGatewayProvider() != null && !zone.getGatewayProvider().equals(Network.Provider.ExternalGateWay)) { - zone.setGatewayProvider(Network.Provider.VirtualRouter.getName()); - } - - if (zone.getDnsProvider() != null && !zone.getDnsProvider().equals(Network.Provider.ExternalDhcpServer)) { - zone.setDnsProvider(Network.Provider.VirtualRouter.getName()); - } - - if (zone.getDhcpProvider() != null && !zone.getDhcpProvider().equals(Network.Provider.ExternalDhcpServer)) { - zone.setDhcpProvider(Network.Provider.VirtualRouter.getName()); - } - - if (zone.getLoadBalancerProvider() != null && zone.getLoadBalancerProvider().equals(Network.Provider.None)) { - if (zone.getNetworkType().equals(NetworkType.Advanced)) { - zone.setLoadBalancerProvider(Network.Provider.VirtualRouter.getName()); - } else if (zone.getNetworkType().equals(NetworkType.Basic)) { - zone.setLoadBalancerProvider(null); - } - } - - return _dcDao.update(zone.getId(), zone);*/ return true; } else { return false; @@ -758,20 +969,48 @@ public class ExternalNetworkDeviceManagerImpl implements ExternalNetworkDeviceMa } @Override + @Deprecated // should use more generic listNetworkDevice command public List listExternalFirewalls(ListExternalFirewallsCmd cmd) { - List firewallHosts = new ArrayList(); - if (NetworkDeviceType.JuniperSRXFirewall.getName().equalsIgnoreCase(cmd.getDeviceType())) { - firewallHosts.addAll(listExternalFirewalls(cmd.getZoneId(), cmd.getNetworkId(), NetworkDeviceType.JuniperSRXFirewall.getName())); - } + List firewallHosts = new ArrayList(); + firewallHosts.addAll(listExternalFirewalls(cmd.getZoneId(), null, NetworkDevice.JuniperSRXFirewall.getName())); return firewallHosts; - } - @Override - public List listExternalFirewalls(Long zoneId, Long networkId, String type) { - List firewallHosts = new ArrayList(); - firewallHosts.addAll(_hostDao.listByTypeDataCenter(Host.Type.ExternalFirewall, zoneId)); - return firewallHosts; + public List listExternalFirewalls(Long zoneId, Long physicalNetworkId, String deviceName) { + List firewallHosts = new ArrayList(); + List firewallhostsInZone = new ArrayList(); + NetworkDevice ntwkDevice = NetworkDevice.getNetworkDevice(deviceName); + PhysicalNetworkVO pNetwork=null; + + if (((zoneId == null) && (physicalNetworkId == null)) || (ntwkDevice == null)) { + throw new InvalidParameterValueException("Atleast one of ther required parameter zone Id, physical networkId, device name is missing or invalid."); + } + + if (physicalNetworkId != null) { + pNetwork = _physicalNetworkDao.findById(physicalNetworkId); + if (pNetwork == null) { + throw new InvalidParameterValueException("Could not find phyical network with ID: " + physicalNetworkId); + } + } + + if (zoneId != null) { + if (_dcDao.findById(zoneId) == null) { + throw new InvalidParameterValueException("Could not find zone with ID: " + zoneId); + } + firewallhostsInZone.addAll(_hostDao.listByTypeDataCenter(Host.Type.ExternalFirewall, zoneId)); + } + if (physicalNetworkId == null) { + return firewallhostsInZone; + } + PhysicalNetworkServiceProviderVO ntwkSvcProider = _physicalNetworkServiceProviderDao.findByServiceProvider(pNetwork.getId(), ntwkDevice.getNetworkServiceProvder()); + if (ntwkSvcProider == null) { + return null; + } + List providerInstances = _physicalNetworkExternalDeviceDao.listByNetworkServiceProviderId(ntwkSvcProider.getId()); + for (PhysicalNetworkExternalDeviceVO provderInstance : providerInstances) { + firewallHosts.add(_hostDao.findById(provderInstance.getHostId())); + } + return firewallHosts; } @Override @@ -855,19 +1094,19 @@ public class ExternalNetworkDeviceManagerImpl implements ExternalNetworkDeviceMa List reservedIpAddressesForGuestNetwork = _nicDao.listIpAddressInNetwork(network.getId()); if (add && (!reservedIpAddressesForGuestNetwork.contains(network.getGateway()))) { // Insert a new NIC for this guest network to reserve the gateway address - savePlaceholderNic(network, network.getGateway()); + savePlaceholderNic(network, network.getGateway()); } // Delete any mappings used for inline external load balancers in this network List nicsInNetwork = _nicDao.listByNetworkId(network.getId()); for (NicVO nic : nicsInNetwork) { - InlineLoadBalancerNicMapVO mapping = _inlineLoadBalancerNicMapDao.findByNicId(nic.getId()); - - if (mapping != null) { - _nicDao.expunge(mapping.getNicId()); - _inlineLoadBalancerNicMapDao.expunge(mapping.getId()); - - } + InlineLoadBalancerNicMapVO mapping = _inlineLoadBalancerNicMapDao.findByNicId(nic.getId()); + + if (mapping != null) { + _nicDao.expunge(mapping.getNicId()); + _inlineLoadBalancerNicMapDao.expunge(mapping.getId()); + + } } @@ -952,70 +1191,70 @@ public class ExternalNetworkDeviceManagerImpl implements ExternalNetworkDeviceMa public boolean manageRemoteAccessVpn(boolean create, Network network, RemoteAccessVpn vpn) throws ResourceUnavailableException { - HostVO externalFirewall = getExternalNetworkAppliance(network.getDataCenterId(), network.getNetworkOfferingId(), Host.Type.ExternalFirewall); + HostVO externalFirewall = getExternalNetworkAppliance(network.getDataCenterId(), network.getNetworkOfferingId(), Host.Type.ExternalFirewall); if (externalFirewall == null) { return false; } - - // Create/delete VPN - IpAddress ip = _networkMgr.getIp(vpn.getServerAddressId()); - - // Mask the IP range with the network's VLAN tag - String[] ipRange = vpn.getIpRange().split("-"); - DataCenterVO zone = _dcDao.findById(network.getDataCenterId()); - int vlanTag = Integer.parseInt(network.getBroadcastUri().getHost()); - int offset = getVlanOffset(network.getPhysicalNetworkId(), vlanTag); - int cidrSize = getGloballyConfiguredCidrSize(); - - for (int i = 0; i < 2; i++) { - ipRange[i] = NetUtils.long2Ip((NetUtils.ip2Long(ipRange[i]) & 0xff000000) | (offset << (32 - cidrSize))); - } - - String maskedIpRange = ipRange[0] + "-" + ipRange[1]; - + + // Create/delete VPN + IpAddress ip = _networkMgr.getIp(vpn.getServerAddressId()); + + // Mask the IP range with the network's VLAN tag + String[] ipRange = vpn.getIpRange().split("-"); + DataCenterVO zone = _dcDao.findById(network.getDataCenterId()); + int vlanTag = Integer.parseInt(network.getBroadcastUri().getHost()); + int offset = getVlanOffset(network.getPhysicalNetworkId(), vlanTag); + int cidrSize = getGloballyConfiguredCidrSize(); + + for (int i = 0; i < 2; i++) { + ipRange[i] = NetUtils.long2Ip((NetUtils.ip2Long(ipRange[i]) & 0xff000000) | (offset << (32 - cidrSize))); + } + + String maskedIpRange = ipRange[0] + "-" + ipRange[1]; + RemoteAccessVpnCfgCommand createVpnCmd = new RemoteAccessVpnCfgCommand(create, ip.getAddress().addr(), vpn.getLocalIp(), maskedIpRange, vpn.getIpsecPresharedKey()); createVpnCmd.setAccessDetail(NetworkElementCommand.ACCOUNT_ID, String.valueOf(network.getAccountId())); createVpnCmd.setAccessDetail(NetworkElementCommand.GUEST_NETWORK_CIDR, network.getCidr()); Answer answer = _agentMgr.easySend(externalFirewall.getId(), createVpnCmd); if (answer == null || !answer.getResult()) { - String details = (answer != null) ? answer.getDetails() : "details unavailable"; + String details = (answer != null) ? answer.getDetails() : "details unavailable"; String msg = "External firewall was unable to create a remote access VPN in zone " + zone.getName() + " due to: " + details + "."; s_logger.error(msg); throw new ResourceUnavailableException(msg, DataCenter.class, zone.getId()); } - + // Add/delete users List vpnUsers = _vpnUsersDao.listByAccount(vpn.getAccountId()); - return manageRemoteAccessVpnUsers(network, vpn, vpnUsers); + return manageRemoteAccessVpnUsers(network, vpn, vpnUsers); } public boolean manageRemoteAccessVpnUsers(Network network, RemoteAccessVpn vpn, List vpnUsers) throws ResourceUnavailableException { - HostVO externalFirewall = getExternalNetworkAppliance(network.getDataCenterId(), network.getNetworkOfferingId(), Host.Type.ExternalFirewall); + HostVO externalFirewall = getExternalNetworkAppliance(network.getDataCenterId(), network.getNetworkOfferingId(), Host.Type.ExternalFirewall); if (externalFirewall == null) { return false; } List addUsers = new ArrayList(); - List removeUsers = new ArrayList(); - for (VpnUser user : vpnUsers) { - if (user.getState() == VpnUser.State.Add || - user.getState() == VpnUser.State.Active) { - addUsers.add(user); - } else if (user.getState() == VpnUser.State.Revoke) { - removeUsers.add(user); - } - } - - VpnUsersCfgCommand addUsersCmd = new VpnUsersCfgCommand(addUsers, removeUsers); - addUsersCmd.setAccessDetail(NetworkElementCommand.ACCOUNT_ID, String.valueOf(network.getAccountId())); - addUsersCmd.setAccessDetail(NetworkElementCommand.GUEST_NETWORK_CIDR, network.getCidr()); - - Answer answer = _agentMgr.easySend(externalFirewall.getId(), addUsersCmd); + List removeUsers = new ArrayList(); + for (VpnUser user : vpnUsers) { + if (user.getState() == VpnUser.State.Add || + user.getState() == VpnUser.State.Active) { + addUsers.add(user); + } else if (user.getState() == VpnUser.State.Revoke) { + removeUsers.add(user); + } + } + + VpnUsersCfgCommand addUsersCmd = new VpnUsersCfgCommand(addUsers, removeUsers); + addUsersCmd.setAccessDetail(NetworkElementCommand.ACCOUNT_ID, String.valueOf(network.getAccountId())); + addUsersCmd.setAccessDetail(NetworkElementCommand.GUEST_NETWORK_CIDR, network.getCidr()); + + Answer answer = _agentMgr.easySend(externalFirewall.getId(), addUsersCmd); if (answer == null || !answer.getResult()) { - String details = (answer != null) ? answer.getDetails() : "details unavailable"; - DataCenterVO zone = _dcDao.findById(network.getDataCenterId()); + String details = (answer != null) ? answer.getDetails() : "details unavailable"; + DataCenterVO zone = _dcDao.findById(network.getDataCenterId()); String msg = "External firewall was unable to add remote access users in zone " + zone.getName() + " due to: " + details + "."; s_logger.error(msg); throw new ResourceUnavailableException(msg, DataCenter.class, zone.getId()); @@ -1039,8 +1278,8 @@ public class ExternalNetworkDeviceManagerImpl implements ExternalNetworkDeviceMa } private boolean externalLoadBalancerIsInline(HostVO externalLoadBalancer) { - DetailVO detail = _detailsDao.findDetail(externalLoadBalancer.getId(), "inline"); - return (detail != null && detail.getValue().equals("true")); + DetailVO detail = _detailsDao.findDetail(externalLoadBalancer.getId(), "inline"); + return (detail != null && detail.getValue().equals("true")); } public int getVlanOffset(long physicalNetworkId, int vlanTag) { @@ -1058,11 +1297,11 @@ public class ExternalNetworkDeviceManagerImpl implements ExternalNetworkDeviceMa } private NicVO savePlaceholderNic(Network network, String ipAddress) { - NicVO nic = new NicVO(null, null, network.getId(), null); - nic.setIp4Address(ipAddress); - nic.setReservationStrategy(ReservationStrategy.PlaceHolder); - nic.setState(State.Reserved); - return _nicDao.persist(nic); + NicVO nic = new NicVO(null, null, network.getId(), null); + nic.setIp4Address(ipAddress); + nic.setReservationStrategy(ReservationStrategy.PlaceHolder); + nic.setState(State.Reserved); + return _nicDao.persist(nic); } public int getGloballyConfiguredCidrSize() { @@ -1073,89 +1312,89 @@ public class ExternalNetworkDeviceManagerImpl implements ExternalNetworkDeviceMa throw new CloudRuntimeException("Failed to read the globally configured VLAN bits size."); } } - - protected class ExternalNetworkUsageTask implements Runnable { - - public ExternalNetworkUsageTask() { - } - - private boolean updateBytes(UserStatisticsVO userStats, long newCurrentBytesSent, long newCurrentBytesReceived) { - long oldNetBytesSent = userStats.getNetBytesSent(); - long oldNetBytesReceived = userStats.getNetBytesReceived(); - long oldCurrentBytesSent = userStats.getCurrentBytesSent(); - long oldCurrentBytesReceived = userStats.getCurrentBytesReceived(); - String warning = "Received an external network stats byte count that was less than the stored value. Zone ID: " + userStats.getDataCenterId() + ", account ID: " + userStats.getAccountId() + "."; - - userStats.setCurrentBytesSent(newCurrentBytesSent); - if (oldCurrentBytesSent > newCurrentBytesSent) { - s_logger.warn(warning + "Stored bytes sent: " + oldCurrentBytesSent + ", new bytes sent: " + newCurrentBytesSent + "."); - userStats.setNetBytesSent(oldNetBytesSent + oldCurrentBytesSent); - } - - userStats.setCurrentBytesReceived(newCurrentBytesReceived); - if (oldCurrentBytesReceived > newCurrentBytesReceived) { - s_logger.warn(warning + "Stored bytes received: " + oldCurrentBytesReceived + ", new bytes received: " + newCurrentBytesReceived + "."); - userStats.setNetBytesReceived(oldNetBytesReceived + oldCurrentBytesReceived); - } - - return _userStatsDao.update(userStats.getId(), userStats); - } - - /* - * Creates a new stats entry for the specified parameters, if one doesn't already exist. - */ - private boolean createStatsEntry(long accountId, long zoneId, long networkId, String publicIp, long hostId) { - HostVO host = _hostDao.findById(hostId); - UserStatisticsVO userStats = _userStatsDao.findBy(accountId, zoneId, networkId, publicIp, hostId, host.getType().toString()); - if (userStats == null) { - return (_userStatsDao.persist(new UserStatisticsVO(accountId, zoneId, publicIp, hostId, host.getType().toString(), networkId)) != null); - } else { - return true; - } - } - - /* - * Updates an existing stats entry with new data from the specified usage answer. - */ - private boolean updateStatsEntry(long accountId, long zoneId, long networkId, String publicIp, long hostId, ExternalNetworkResourceUsageAnswer answer) { - AccountVO account = _accountDao.findById(accountId); - DataCenterVO zone = _dcDao.findById(zoneId); - NetworkVO network = _networkDao.findById(networkId); - HostVO host = _hostDao.findById(hostId); - String statsEntryIdentifier = "account " + account.getAccountName() + ", zone " + zone.getName() + ", network ID " + networkId + ", host ID " + host.getName(); - - long newCurrentBytesSent = 0; - long newCurrentBytesReceived = 0; - - if (publicIp != null) { - long[] bytesSentAndReceived = null; - statsEntryIdentifier += ", public IP: " + publicIp; - - if (host.getType().equals(Host.Type.ExternalLoadBalancer) && externalLoadBalancerIsInline(host)) { - // Look up stats for the guest IP address that's mapped to the public IP address - InlineLoadBalancerNicMapVO mapping = _inlineLoadBalancerNicMapDao.findByPublicIpAddress(publicIp); - - if (mapping != null) { - NicVO nic = _nicDao.findById(mapping.getNicId()); - String loadBalancingIpAddress = nic.getIp4Address(); - bytesSentAndReceived = answer.ipBytes.get(loadBalancingIpAddress); - - if (bytesSentAndReceived != null) { - bytesSentAndReceived[0] = 0; - } - } - } else { - bytesSentAndReceived = answer.ipBytes.get(publicIp); - } - - if (bytesSentAndReceived == null) { - s_logger.debug("Didn't get an external network usage answer for public IP " + publicIp); - } else { - newCurrentBytesSent += bytesSentAndReceived[0]; - newCurrentBytesReceived += bytesSentAndReceived[1]; - } - } else { - URI broadcastURI = network.getBroadcastUri(); + + protected class ExternalNetworkUsageTask implements Runnable { + + public ExternalNetworkUsageTask() { + } + + private boolean updateBytes(UserStatisticsVO userStats, long newCurrentBytesSent, long newCurrentBytesReceived) { + long oldNetBytesSent = userStats.getNetBytesSent(); + long oldNetBytesReceived = userStats.getNetBytesReceived(); + long oldCurrentBytesSent = userStats.getCurrentBytesSent(); + long oldCurrentBytesReceived = userStats.getCurrentBytesReceived(); + String warning = "Received an external network stats byte count that was less than the stored value. Zone ID: " + userStats.getDataCenterId() + ", account ID: " + userStats.getAccountId() + "."; + + userStats.setCurrentBytesSent(newCurrentBytesSent); + if (oldCurrentBytesSent > newCurrentBytesSent) { + s_logger.warn(warning + "Stored bytes sent: " + oldCurrentBytesSent + ", new bytes sent: " + newCurrentBytesSent + "."); + userStats.setNetBytesSent(oldNetBytesSent + oldCurrentBytesSent); + } + + userStats.setCurrentBytesReceived(newCurrentBytesReceived); + if (oldCurrentBytesReceived > newCurrentBytesReceived) { + s_logger.warn(warning + "Stored bytes received: " + oldCurrentBytesReceived + ", new bytes received: " + newCurrentBytesReceived + "."); + userStats.setNetBytesReceived(oldNetBytesReceived + oldCurrentBytesReceived); + } + + return _userStatsDao.update(userStats.getId(), userStats); + } + + /* + * Creates a new stats entry for the specified parameters, if one doesn't already exist. + */ + private boolean createStatsEntry(long accountId, long zoneId, long networkId, String publicIp, long hostId) { + HostVO host = _hostDao.findById(hostId); + UserStatisticsVO userStats = _userStatsDao.findBy(accountId, zoneId, networkId, publicIp, hostId, host.getType().toString()); + if (userStats == null) { + return (_userStatsDao.persist(new UserStatisticsVO(accountId, zoneId, publicIp, hostId, host.getType().toString(), networkId)) != null); + } else { + return true; + } + } + + /* + * Updates an existing stats entry with new data from the specified usage answer. + */ + private boolean updateStatsEntry(long accountId, long zoneId, long networkId, String publicIp, long hostId, ExternalNetworkResourceUsageAnswer answer) { + AccountVO account = _accountDao.findById(accountId); + DataCenterVO zone = _dcDao.findById(zoneId); + NetworkVO network = _networkDao.findById(networkId); + HostVO host = _hostDao.findById(hostId); + String statsEntryIdentifier = "account " + account.getAccountName() + ", zone " + zone.getName() + ", network ID " + networkId + ", host ID " + host.getName(); + + long newCurrentBytesSent = 0; + long newCurrentBytesReceived = 0; + + if (publicIp != null) { + long[] bytesSentAndReceived = null; + statsEntryIdentifier += ", public IP: " + publicIp; + + if (host.getType().equals(Host.Type.ExternalLoadBalancer) && externalLoadBalancerIsInline(host)) { + // Look up stats for the guest IP address that's mapped to the public IP address + InlineLoadBalancerNicMapVO mapping = _inlineLoadBalancerNicMapDao.findByPublicIpAddress(publicIp); + + if (mapping != null) { + NicVO nic = _nicDao.findById(mapping.getNicId()); + String loadBalancingIpAddress = nic.getIp4Address(); + bytesSentAndReceived = answer.ipBytes.get(loadBalancingIpAddress); + + if (bytesSentAndReceived != null) { + bytesSentAndReceived[0] = 0; + } + } + } else { + bytesSentAndReceived = answer.ipBytes.get(publicIp); + } + + if (bytesSentAndReceived == null) { + s_logger.debug("Didn't get an external network usage answer for public IP " + publicIp); + } else { + newCurrentBytesSent += bytesSentAndReceived[0]; + newCurrentBytesReceived += bytesSentAndReceived[1]; + } + } else { + URI broadcastURI = network.getBroadcastUri(); if (broadcastURI == null) { s_logger.debug("Not updating stats for guest network with ID " + network.getId() + " because the network is not implemented."); return true; @@ -1170,85 +1409,85 @@ public class ExternalNetworkDeviceManagerImpl implements ExternalNetworkDeviceMa newCurrentBytesReceived += bytesSentAndReceived[1]; } } - } - - UserStatisticsVO userStats; - try { - userStats = _userStatsDao.lock(accountId, zoneId, networkId, publicIp, hostId, host.getType().toString()); - } catch (Exception e) { - s_logger.warn("Unable to find user stats entry for " + statsEntryIdentifier); - return false; - } - - if (updateBytes(userStats, newCurrentBytesSent, newCurrentBytesReceived)) { - s_logger.debug("Successfully updated stats for " + statsEntryIdentifier); - return true; - } else { - s_logger.debug("Failed to update stats for " + statsEntryIdentifier); - return false; - } - } - - private boolean createOrUpdateStatsEntry(boolean create, long accountId, long zoneId, long networkId, String publicIp, long hostId, ExternalNetworkResourceUsageAnswer answer) { - if (create) { - return createStatsEntry(accountId, zoneId, networkId, publicIp, hostId); - } else { - return updateStatsEntry(accountId, zoneId, networkId, publicIp, hostId, answer); - } - } - - /* - * Creates/updates all necessary stats entries for an account and zone. - * Stats entries are created for source NAT IP addresses, static NAT rules, port forwarding rules, and load balancing rules - */ - private boolean manageStatsEntries(boolean create, long accountId, long zoneId, - HostVO externalFirewall, ExternalNetworkResourceUsageAnswer firewallAnswer, - HostVO externalLoadBalancer, ExternalNetworkResourceUsageAnswer lbAnswer) { - String accountErrorMsg = "Failed to update external network stats entry. Details: account ID = " + accountId; - Transaction txn = Transaction.open(Transaction.CLOUD_DB); - try { - txn.start(); - - List networksForAccount = _networkDao.listBy(accountId, zoneId, Network.Type.Isolated); - - for (NetworkVO network : networksForAccount) { - String networkErrorMsg = accountErrorMsg + ", network ID = " + network.getId(); - NetworkOfferingVO offering = _networkOfferingDao.findById(network.getNetworkOfferingId()); - - if (!offering.isSharedSourceNatService()) { - // Manage the entry for this network's source NAT IP address - List sourceNatIps = _ipAddressDao.listByAssociatedNetwork(network.getId(), true); - if (sourceNatIps.size() == 1) { - String publicIp = sourceNatIps.get(0).getAddress().addr(); - if (!createOrUpdateStatsEntry(create, accountId, zoneId, network.getId(), publicIp, externalFirewall.getId(), firewallAnswer)) { - throw new ExecutionException(networkErrorMsg + ", source NAT IP = " + publicIp); - } - } - - // Manage one entry for each static NAT rule in this network - List staticNatIps = _ipAddressDao.listStaticNatPublicIps(network.getId()); - for (IPAddressVO staticNatIp : staticNatIps) { - String publicIp = staticNatIp.getAddress().addr(); - if (!createOrUpdateStatsEntry(create, accountId, zoneId, network.getId(), publicIp, externalFirewall.getId(), firewallAnswer)) { - throw new ExecutionException(networkErrorMsg + ", static NAT rule public IP = " + publicIp); - } - } - - // Manage one entry for each port forwarding rule in this network - List portForwardingRules = _portForwardingRulesDao.listByNetwork(network.getId()); - for (PortForwardingRuleVO portForwardingRule : portForwardingRules) { - String publicIp = _networkMgr.getIp(portForwardingRule.getSourceIpAddressId()).getAddress().addr(); - if (!createOrUpdateStatsEntry(create, accountId, zoneId, network.getId(), publicIp, externalFirewall.getId(), firewallAnswer)) { - throw new ExecutionException(networkErrorMsg + ", port forwarding rule public IP = " + publicIp); - } - } - } else { - // Manage the account-wide entry for the external firewall - if (!createOrUpdateStatsEntry(create, accountId, zoneId, network.getId(), null, externalFirewall.getId(), firewallAnswer)) { - throw new ExecutionException(networkErrorMsg); - } - } - + } + + UserStatisticsVO userStats; + try { + userStats = _userStatsDao.lock(accountId, zoneId, networkId, publicIp, hostId, host.getType().toString()); + } catch (Exception e) { + s_logger.warn("Unable to find user stats entry for " + statsEntryIdentifier); + return false; + } + + if (updateBytes(userStats, newCurrentBytesSent, newCurrentBytesReceived)) { + s_logger.debug("Successfully updated stats for " + statsEntryIdentifier); + return true; + } else { + s_logger.debug("Failed to update stats for " + statsEntryIdentifier); + return false; + } + } + + private boolean createOrUpdateStatsEntry(boolean create, long accountId, long zoneId, long networkId, String publicIp, long hostId, ExternalNetworkResourceUsageAnswer answer) { + if (create) { + return createStatsEntry(accountId, zoneId, networkId, publicIp, hostId); + } else { + return updateStatsEntry(accountId, zoneId, networkId, publicIp, hostId, answer); + } + } + + /* + * Creates/updates all necessary stats entries for an account and zone. + * Stats entries are created for source NAT IP addresses, static NAT rules, port forwarding rules, and load balancing rules + */ + private boolean manageStatsEntries(boolean create, long accountId, long zoneId, + HostVO externalFirewall, ExternalNetworkResourceUsageAnswer firewallAnswer, + HostVO externalLoadBalancer, ExternalNetworkResourceUsageAnswer lbAnswer) { + String accountErrorMsg = "Failed to update external network stats entry. Details: account ID = " + accountId; + Transaction txn = Transaction.open(Transaction.CLOUD_DB); + try { + txn.start(); + + List networksForAccount = _networkDao.listBy(accountId, zoneId, Network.Type.Isolated); + + for (NetworkVO network : networksForAccount) { + String networkErrorMsg = accountErrorMsg + ", network ID = " + network.getId(); + NetworkOfferingVO offering = _networkOfferingDao.findById(network.getNetworkOfferingId()); + + if (!offering.isSharedSourceNatService()) { + // Manage the entry for this network's source NAT IP address + List sourceNatIps = _ipAddressDao.listByAssociatedNetwork(network.getId(), true); + if (sourceNatIps.size() == 1) { + String publicIp = sourceNatIps.get(0).getAddress().addr(); + if (!createOrUpdateStatsEntry(create, accountId, zoneId, network.getId(), publicIp, externalFirewall.getId(), firewallAnswer)) { + throw new ExecutionException(networkErrorMsg + ", source NAT IP = " + publicIp); + } + } + + // Manage one entry for each static NAT rule in this network + List staticNatIps = _ipAddressDao.listStaticNatPublicIps(network.getId()); + for (IPAddressVO staticNatIp : staticNatIps) { + String publicIp = staticNatIp.getAddress().addr(); + if (!createOrUpdateStatsEntry(create, accountId, zoneId, network.getId(), publicIp, externalFirewall.getId(), firewallAnswer)) { + throw new ExecutionException(networkErrorMsg + ", static NAT rule public IP = " + publicIp); + } + } + + // Manage one entry for each port forwarding rule in this network + List portForwardingRules = _portForwardingRulesDao.listByNetwork(network.getId()); + for (PortForwardingRuleVO portForwardingRule : portForwardingRules) { + String publicIp = _networkMgr.getIp(portForwardingRule.getSourceIpAddressId()).getAddress().addr(); + if (!createOrUpdateStatsEntry(create, accountId, zoneId, network.getId(), publicIp, externalFirewall.getId(), firewallAnswer)) { + throw new ExecutionException(networkErrorMsg + ", port forwarding rule public IP = " + publicIp); + } + } + } else { + // Manage the account-wide entry for the external firewall + if (!createOrUpdateStatsEntry(create, accountId, zoneId, network.getId(), null, externalFirewall.getId(), firewallAnswer)) { + throw new ExecutionException(networkErrorMsg); + } + } + // If an external load balancer is added, manage one entry for each load balancing rule in this network if (externalLoadBalancer != null && lbAnswer != null) { List loadBalancers = _loadBalancerDao.listByNetworkId(network.getId()); @@ -1259,103 +1498,103 @@ public class ExternalNetworkDeviceManagerImpl implements ExternalNetworkDeviceMa } } } - - } - - return txn.commit(); - } catch (Exception e) { - s_logger.warn("Exception: ", e); - txn.rollback(); - return false; - } finally { - txn.close(); - } - } - - private void runExternalNetworkUsageTask() { - s_logger.debug("External network stats collector is running..."); - for (DataCenterVO zone : _dcDao.listAll()) { - // Make sure the zone is configured for external networking - - //FIXME: add another way to check if zone has external networking. - - if (!_networkMgr.zoneIsConfiguredForExternalNetworking(zone.getId())) { - s_logger.debug("Zone " + zone.getName() + " is not configured for external networking, so skipping usage check."); - continue; - } - - // Only collect stats if there is an external firewall in this zone - - //FIXME: add another way to check if zone has external networking. - - HostVO externalFirewall = getExternalNetworkAppliance(zone.getId(), 0, Host.Type.ExternalFirewall); - HostVO externalLoadBalancer = getExternalNetworkAppliance(zone.getId(), 0, Host.Type.ExternalLoadBalancer); - - if (externalFirewall == null) { - s_logger.debug("Skipping usage check for zone " + zone.getName()); - continue; - } - - s_logger.debug("Collecting external network stats for zone " + zone.getName()); - - ExternalNetworkResourceUsageCommand cmd = new ExternalNetworkResourceUsageCommand(); - - // Get network stats from the external firewall - ExternalNetworkResourceUsageAnswer firewallAnswer = (ExternalNetworkResourceUsageAnswer) _agentMgr.easySend(externalFirewall.getId(), cmd); - if (firewallAnswer == null || !firewallAnswer.getResult()) { - String details = (firewallAnswer != null) ? firewallAnswer.getDetails() : "details unavailable"; - String msg = "Unable to get external firewall stats for " + zone.getName() + " due to: " + details + "."; - s_logger.error(msg); - continue; - } - - ExternalNetworkResourceUsageAnswer lbAnswer = null; - if (externalLoadBalancer != null) { - // Get network stats from the external load balancer - lbAnswer = (ExternalNetworkResourceUsageAnswer) _agentMgr.easySend(externalLoadBalancer.getId(), cmd); - if (lbAnswer == null || !lbAnswer.getResult()) { - String details = (lbAnswer != null) ? lbAnswer.getDetails() : "details unavailable"; - String msg = "Unable to get external load balancer stats for " + zone.getName() + " due to: " + details + "."; - s_logger.error(msg); - } - } - - List domainRoutersInZone = _routerDao.listByDataCenter(zone.getId()); - for (DomainRouterVO domainRouter : domainRoutersInZone) { - long accountId = domainRouter.getAccountId(); - long zoneId = domainRouter.getDataCenterIdToDeployIn(); - - AccountVO account = _accountDao.findById(accountId); - if (account == null) { - s_logger.debug("Skipping stats update for account with ID " + accountId); - continue; - } - - if (!manageStatsEntries(true, accountId, zoneId, externalFirewall, firewallAnswer, externalLoadBalancer, lbAnswer)) { - continue; - } - - manageStatsEntries(false, accountId, zoneId, externalFirewall, firewallAnswer, externalLoadBalancer, lbAnswer); - } - } - } - - @Override - public void run() { - GlobalLock scanLock = GlobalLock.getInternLock("ExternalNetworkManagerImpl"); + + } + + return txn.commit(); + } catch (Exception e) { + s_logger.warn("Exception: ", e); + txn.rollback(); + return false; + } finally { + txn.close(); + } + } + + private void runExternalNetworkUsageTask() { + s_logger.debug("External network stats collector is running..."); + for (DataCenterVO zone : _dcDao.listAll()) { + // Make sure the zone is configured for external networking + + //FIXME: add another way to check if zone has external networking. + + if (!_networkMgr.zoneIsConfiguredForExternalNetworking(zone.getId())) { + s_logger.debug("Zone " + zone.getName() + " is not configured for external networking, so skipping usage check."); + continue; + } + + // Only collect stats if there is an external firewall in this zone + + //FIXME: add another way to check if zone has external networking. + + HostVO externalFirewall = getExternalNetworkAppliance(zone.getId(), 0, Host.Type.ExternalFirewall); + HostVO externalLoadBalancer = getExternalNetworkAppliance(zone.getId(), 0, Host.Type.ExternalLoadBalancer); + + if (externalFirewall == null) { + s_logger.debug("Skipping usage check for zone " + zone.getName()); + continue; + } + + s_logger.debug("Collecting external network stats for zone " + zone.getName()); + + ExternalNetworkResourceUsageCommand cmd = new ExternalNetworkResourceUsageCommand(); + + // Get network stats from the external firewall + ExternalNetworkResourceUsageAnswer firewallAnswer = (ExternalNetworkResourceUsageAnswer) _agentMgr.easySend(externalFirewall.getId(), cmd); + if (firewallAnswer == null || !firewallAnswer.getResult()) { + String details = (firewallAnswer != null) ? firewallAnswer.getDetails() : "details unavailable"; + String msg = "Unable to get external firewall stats for " + zone.getName() + " due to: " + details + "."; + s_logger.error(msg); + continue; + } + + ExternalNetworkResourceUsageAnswer lbAnswer = null; + if (externalLoadBalancer != null) { + // Get network stats from the external load balancer + lbAnswer = (ExternalNetworkResourceUsageAnswer) _agentMgr.easySend(externalLoadBalancer.getId(), cmd); + if (lbAnswer == null || !lbAnswer.getResult()) { + String details = (lbAnswer != null) ? lbAnswer.getDetails() : "details unavailable"; + String msg = "Unable to get external load balancer stats for " + zone.getName() + " due to: " + details + "."; + s_logger.error(msg); + } + } + + List domainRoutersInZone = _routerDao.listByDataCenter(zone.getId()); + for (DomainRouterVO domainRouter : domainRoutersInZone) { + long accountId = domainRouter.getAccountId(); + long zoneId = domainRouter.getDataCenterIdToDeployIn(); + + AccountVO account = _accountDao.findById(accountId); + if (account == null) { + s_logger.debug("Skipping stats update for account with ID " + accountId); + continue; + } + + if (!manageStatsEntries(true, accountId, zoneId, externalFirewall, firewallAnswer, externalLoadBalancer, lbAnswer)) { + continue; + } + + manageStatsEntries(false, accountId, zoneId, externalFirewall, firewallAnswer, externalLoadBalancer, lbAnswer); + } + } + } + + @Override + public void run() { + GlobalLock scanLock = GlobalLock.getInternLock("ExternalNetworkManagerImpl"); try { if (scanLock.lock(20)) { try { - runExternalNetworkUsageTask(); + runExternalNetworkUsageTask(); } finally { scanLock.unlock(); } } } catch (Exception e) { - s_logger.warn("Problems while getting external network usage", e); + s_logger.warn("Problems while getting external network usage", e); } finally { scanLock.releaseRef(); } - } - } + } + } } diff --git a/server/src/com/cloud/network/NetworkDeviceManager.java b/server/src/com/cloud/network/NetworkDeviceManager.java deleted file mode 100644 index 0920d4d5881..00000000000 --- a/server/src/com/cloud/network/NetworkDeviceManager.java +++ /dev/null @@ -1,38 +0,0 @@ -package com.cloud.network; - -import java.util.List; - -import com.cloud.api.commands.AddNetworkDeviceCmd; -import com.cloud.api.commands.DeleteNetworkDeviceCmd; -import com.cloud.api.commands.ListNetworkDeviceCmd; -import com.cloud.host.Host; -import com.cloud.server.api.response.NetworkDeviceResponse; -import com.cloud.utils.component.Manager; - -public interface NetworkDeviceManager extends Manager { - public static class NetworkDeviceType { - private String _name; - - public static final NetworkDeviceType ExternalDhcp = new NetworkDeviceType("ExternalDhcp"); - public static final NetworkDeviceType PxeServer = new NetworkDeviceType("PxeServer"); - public static final NetworkDeviceType NetscalerLoadBalancer = new NetworkDeviceType("NetscalerLoadBalancer"); - public static final NetworkDeviceType F5BigIpLoadBalancer = new NetworkDeviceType("F5BigIpLoadBalancer"); - public static final NetworkDeviceType JuniperSRXFirewall = new NetworkDeviceType("JuniperSRXFirewall"); - - public NetworkDeviceType(String name) { - _name = name; - } - - public String getName() { - return _name; - } - } - - public Host addNetworkDevice(AddNetworkDeviceCmd cmd); - - public NetworkDeviceResponse getApiResponse(Host device); - - public List listNetworkDevice(ListNetworkDeviceCmd cmd); - - public boolean deleteNetworkDevice(DeleteNetworkDeviceCmd cmd); -} diff --git a/server/src/com/cloud/network/NetworkDeviceManagerImpl.java b/server/src/com/cloud/network/NetworkDeviceManagerImpl.java deleted file mode 100644 index 6a9ae8acf64..00000000000 --- a/server/src/com/cloud/network/NetworkDeviceManagerImpl.java +++ /dev/null @@ -1,224 +0,0 @@ -package com.cloud.network; - -import java.util.ArrayList; -import java.util.Collection; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import javax.ejb.Local; -import javax.naming.ConfigurationException; - -import org.apache.log4j.Logger; - -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseCmd; -import com.cloud.api.ServerApiException; -import com.cloud.api.commands.AddNetworkDeviceCmd; -import com.cloud.api.commands.DeleteNetworkDeviceCmd; -import com.cloud.api.commands.ListNetworkDeviceCmd; -import com.cloud.baremetal.ExternalDhcpManager; -import com.cloud.baremetal.PxeServerManager; -import com.cloud.baremetal.PxeServerManager.PxeServerType; -import com.cloud.baremetal.PxeServerProfile; -import com.cloud.exception.InvalidParameterValueException; -import com.cloud.host.Host; -import com.cloud.host.HostVO; -import com.cloud.host.Host.Type; -import com.cloud.host.dao.HostDao; -import com.cloud.server.api.response.NetworkDeviceResponse; -import com.cloud.server.api.response.NwDeviceDhcpResponse; -import com.cloud.server.api.response.PxePingResponse; -import com.cloud.utils.component.Inject; -import com.cloud.utils.exception.CloudRuntimeException; - -@Local(value={NetworkDeviceManager.class}) -public class NetworkDeviceManagerImpl implements NetworkDeviceManager { - public static final Logger s_logger = Logger.getLogger(NetworkDeviceManagerImpl.class); - String _name; - @Inject ExternalDhcpManager _dhcpMgr; - @Inject PxeServerManager _pxeMgr; - @Inject HostDao _hostDao; - @Inject ExternalNetworkDeviceManager _externalNetworkDeviceMgr; - @Override - public boolean configure(String name, Map params) throws ConfigurationException { - _name = name; - return true; - } - - @Override - public boolean start() { - return true; - } - - @Override - public boolean stop() { - return true; - } - - @Override - public String getName() { - return _name; - } - - @Override - public Host addNetworkDevice(AddNetworkDeviceCmd cmd) { - Map paramList = cmd.getParamList(); - if (paramList == null) { - throw new CloudRuntimeException("Parameter list is null"); - } - - Collection paramsCollection = paramList.values(); - HashMap params = (HashMap) (paramsCollection.toArray())[0]; - if (cmd.getType().equalsIgnoreCase(NetworkDeviceType.ExternalDhcp.getName())) { - Long zoneId = Long.parseLong((String) params.get(ApiConstants.ZONE_ID)); - Long podId = Long.parseLong((String)params.get(ApiConstants.POD_ID)); - String type = (String) params.get(ApiConstants.DHCP_SERVER_TYPE); - String url = (String) params.get(ApiConstants.URL); - String username = (String) params.get(ApiConstants.USERNAME); - String password = (String) params.get(ApiConstants.PASSWORD); - - return _dhcpMgr.addDhcpServer(zoneId, podId, type, url, username, password); - } else if (cmd.getType().equalsIgnoreCase(NetworkDeviceType.PxeServer.getName())) { - Long zoneId = Long.parseLong((String) params.get(ApiConstants.ZONE_ID)); - Long podId = Long.parseLong((String)params.get(ApiConstants.POD_ID)); - String type = (String) params.get(ApiConstants.PXE_SERVER_TYPE); - String url = (String) params.get(ApiConstants.URL); - String username = (String) params.get(ApiConstants.USERNAME); - String password = (String) params.get(ApiConstants.PASSWORD); - String pingStorageServerIp = (String) params.get(ApiConstants.PING_STORAGE_SERVER_IP); - String pingDir = (String) params.get(ApiConstants.PING_DIR); - String tftpDir = (String) params.get(ApiConstants.TFTP_DIR); - String pingCifsUsername = (String) params.get(ApiConstants.PING_CIFS_USERNAME); - String pingCifsPassword = (String) params.get(ApiConstants.PING_CIFS_PASSWORD); - PxeServerProfile profile = new PxeServerProfile(zoneId, podId, url, username, password, type, pingStorageServerIp, pingDir, tftpDir, - pingCifsUsername, pingCifsPassword); - return _pxeMgr.addPxeServer(profile); - } else if (cmd.getType().equalsIgnoreCase(NetworkDeviceType.JuniperSRXFirewall.getName())) { - Long zoneId = Long.parseLong((String) params.get(ApiConstants.ZONE_ID)); - Long networkId = (params.get(ApiConstants.NETWORK_ID)==null)?Long.parseLong((String)params.get(ApiConstants.NETWORK_ID)):null; - return _externalNetworkDeviceMgr.addExternalFirewall(zoneId, networkId, NetworkDeviceType.JuniperSRXFirewall.getName(), cmd.getParamList()); - } else if (cmd.getType().equalsIgnoreCase(NetworkDeviceType.NetscalerLoadBalancer.getName())) { - Long zoneId = Long.parseLong((String) params.get(ApiConstants.ZONE_ID)); - return _externalNetworkDeviceMgr.addExternalLoadBalancer(zoneId, null, NetworkDeviceType.NetscalerLoadBalancer.getName(), cmd.getParamList()); - } else if (cmd.getType().equalsIgnoreCase(NetworkDeviceType.F5BigIpLoadBalancer.getName())) { - Long zoneId = Long.parseLong((String) params.get(ApiConstants.ZONE_ID)); - return _externalNetworkDeviceMgr.addExternalLoadBalancer(zoneId, null, NetworkDeviceType.F5BigIpLoadBalancer.getName(), cmd.getParamList()); - } else { - throw new CloudRuntimeException("Unsupported network device type:" + cmd.getType()); - } - } - - @Override - public NetworkDeviceResponse getApiResponse(Host device) { - NetworkDeviceResponse response; - HostVO host = (HostVO)device; - _hostDao.loadDetails(host); - if (host.getType() == Host.Type.ExternalDhcp) { - NwDeviceDhcpResponse r = new NwDeviceDhcpResponse(); - r.setZoneId(host.getDataCenterId()); - r.setPodId(host.getPodId()); - r.setUrl(host.getPrivateIpAddress()); - r.setType(host.getDetail("type")); - response = r; - } else if (host.getType() == Host.Type.PxeServer) { - String pxeType = host.getDetail("type"); - if (pxeType.equalsIgnoreCase(PxeServerType.PING.getName())) { - PxePingResponse r = new PxePingResponse(); - r.setZoneId(host.getDataCenterId()); - r.setPodId(host.getPodId()); - r.setUrl(host.getPrivateIpAddress()); - r.setType(pxeType); - r.setStorageServerIp(host.getDetail("storageServer")); - r.setPingDir(host.getDetail("pingDir")); - r.setTftpDir(host.getDetail("tftpDir")); - response = r; - } else { - throw new CloudRuntimeException("Unsupported PXE server type:" + pxeType); - } - } else { - throw new CloudRuntimeException("Unsupported network device type:" + host.getType()); - } - - response.setId(device.getId()); - return response; - } - - private List listNetworkDevice(Long zoneId, Long podId, Host.Type type) { - List res = new ArrayList(); - if (podId != null) { - List devs = _hostDao.listBy(type, null, podId, zoneId); - if (devs.size() == 1) { - res.add(devs.get(0)); - } else { - s_logger.debug("List " + type + ": " + devs.size() + " found"); - } - } else { - List devs = _hostDao.listBy(type, zoneId); - res.addAll(devs); - } - - return res; - } - - @Override - public List listNetworkDevice(ListNetworkDeviceCmd cmd) { - Map paramList = cmd.getParamList(); - if (paramList == null) { - throw new CloudRuntimeException("Parameter list is null"); - } - - List res; - Collection paramsCollection = paramList.values(); - HashMap params = (HashMap) (paramsCollection.toArray())[0]; - if (NetworkDeviceType.ExternalDhcp.getName().equalsIgnoreCase(cmd.getType())) { - Long zoneId = Long.parseLong((String) params.get(ApiConstants.ZONE_ID)); - Long podId = Long.parseLong((String)params.get(ApiConstants.POD_ID)); - res = listNetworkDevice(zoneId, podId, Host.Type.ExternalDhcp); - } else if (NetworkDeviceType.PxeServer.getName().equalsIgnoreCase(cmd.getType())) { - Long zoneId = Long.parseLong((String) params.get(ApiConstants.ZONE_ID)); - Long podId = Long.parseLong((String)params.get(ApiConstants.POD_ID)); - res = listNetworkDevice(zoneId, podId, Host.Type.PxeServer); - } else if (NetworkDeviceType.F5BigIpLoadBalancer.getName().equalsIgnoreCase(cmd.getType())) { - Long zoneId = Long.parseLong((String) params.get(ApiConstants.ZONE_ID)); - Long networkId = Long.parseLong((String) params.get(ApiConstants.NETWORK_ID)); - return _externalNetworkDeviceMgr.listExternalLoadBalancers(zoneId, networkId, NetworkDeviceType.F5BigIpLoadBalancer.getName()); - } else if (NetworkDeviceType.NetscalerLoadBalancer.getName().equalsIgnoreCase(cmd.getType())) { - Long zoneId = Long.parseLong((String) params.get(ApiConstants.ZONE_ID)); - Long networkId = Long.parseLong((String) params.get(ApiConstants.NETWORK_ID)); - return _externalNetworkDeviceMgr.listExternalLoadBalancers(zoneId, networkId, NetworkDeviceType.NetscalerLoadBalancer.getName()); - } else if (NetworkDeviceType.JuniperSRXFirewall.getName().equalsIgnoreCase(cmd.getType())) { - Long zoneId = Long.parseLong((String) params.get(ApiConstants.ZONE_ID)); - Long networkId = Long.parseLong((String) params.get(ApiConstants.NETWORK_ID)); - return _externalNetworkDeviceMgr.listExternalFirewalls(zoneId, networkId, NetworkDeviceType.JuniperSRXFirewall.getName()); - } else if (cmd.getType() == null){ - Long zoneId = Long.parseLong((String) params.get(ApiConstants.ZONE_ID)); - Long podId = Long.parseLong((String)params.get(ApiConstants.POD_ID)); - List res1 = listNetworkDevice(zoneId, podId, Host.Type.PxeServer); - List res2 = listNetworkDevice(zoneId, podId, Host.Type.ExternalDhcp); - List res3 = listNetworkDevice(zoneId, podId, Host.Type.ExternalLoadBalancer); - List res4 = listNetworkDevice(zoneId, podId, Host.Type.ExternalFirewall); - List deviceAll = new ArrayList(); - deviceAll.addAll(res1); - deviceAll.addAll(res2); - deviceAll.addAll(res3); - deviceAll.addAll(res4); - res = deviceAll; - } else { - throw new CloudRuntimeException("Unknown network device type:" + cmd.getType()); - } - - return res; - } - - @Override - public boolean deleteNetworkDevice(DeleteNetworkDeviceCmd cmd) { - HostVO device = _hostDao.findById(cmd.getId()); - if (device.getType() == Type.ExternalLoadBalancer) { - return _externalNetworkDeviceMgr.deleteExternalLoadBalancer(cmd.getId()); - } else if (device.getType() == Type.ExternalLoadBalancer) { - return _externalNetworkDeviceMgr.deleteExternalFirewall(cmd.getId()); - } - return true; - } -} \ No newline at end of file diff --git a/server/src/com/cloud/network/NetworkManagerImpl.java b/server/src/com/cloud/network/NetworkManagerImpl.java index 08ceb40dc4d..3d3735e1027 100755 --- a/server/src/com/cloud/network/NetworkManagerImpl.java +++ b/server/src/com/cloud/network/NetworkManagerImpl.java @@ -2902,7 +2902,7 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag if (zone.getGatewayProvider() != null && zone.getGatewayProvider().equals(Network.Provider.JuniperSRX.getName()) && zone.getFirewallProvider() != null && zone.getFirewallProvider().equals(Network.Provider.JuniperSRX.getName())) { return true; - } else if (zone.getGatewayProvider() != null && zone.getLoadBalancerProvider() != null && zone.getLoadBalancerProvider().equals(Network.Provider.NetscalerMPX.getName())) { + } else if (zone.getGatewayProvider() != null && zone.getLoadBalancerProvider() != null && zone.getLoadBalancerProvider().equals(Network.Provider.Netscaler.getName())) { return true; } else { return false; @@ -2919,12 +2919,13 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag boolean usesJuniperForGatewayService = _ntwkOfferingSrvcDao.isProviderSupported(networkOfferingId, Service.Gateway, Network.Provider.JuniperSRX); boolean usesJuniperForFirewallService = _ntwkOfferingSrvcDao.isProviderSupported(networkOfferingId, Service.Firewall, Network.Provider.JuniperSRX); - boolean usesNetscalarForLBService = _ntwkOfferingSrvcDao.isProviderSupported(networkOfferingId, Service.Lb, Network.Provider.NetscalerMPX); + boolean usesNetscalarForLBService = _ntwkOfferingSrvcDao.isProviderSupported(networkOfferingId, Service.Lb, Network.Provider.Netscaler); + boolean usesF5ForLBService = _ntwkOfferingSrvcDao.isProviderSupported(networkOfferingId, Service.Lb, Network.Provider.F5BigIp); if (zone.getNetworkType() == NetworkType.Advanced) { if (usesJuniperForGatewayService && usesJuniperForFirewallService) { return true; - } else if (_ntwkOfferingSrvcDao.isServiceSupported(networkOfferingId, Service.Gateway) && usesNetscalarForLBService) { + } else if (_ntwkOfferingSrvcDao.isServiceSupported(networkOfferingId, Service.Gateway) && (usesF5ForLBService || usesNetscalarForLBService)) { return true; } else { return false; diff --git a/server/src/com/cloud/network/PhysicalNetworkExternalDeviceVO.java b/server/src/com/cloud/network/PhysicalNetworkExternalDeviceVO.java new file mode 100644 index 00000000000..1c1ba51f077 --- /dev/null +++ b/server/src/com/cloud/network/PhysicalNetworkExternalDeviceVO.java @@ -0,0 +1,64 @@ +/** + * Copyright (C) 2011 Citrix Systems, Inc. All rights reserved. + * + * This software is licensed under the GNU General Public License v3 or later. + * + * It is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or any later version. + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + */ + +package com.cloud.network; + +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; +import javax.persistence.Table; + +/** + * PhysicalNetworkExternalDeviceVO contains information about a external network devices (Network service provider instances) + * added in to a physical network. + */ + +@Entity +@Table(name="physical_network_external_devices") +public class PhysicalNetworkExternalDeviceVO { + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + @Column(name = "id") + private long id; + + @Column(name = "physical_network_service_provider_id") + private long networkServiceProviderId; + + @Column(name = "host_id") + private long hostId; + + public PhysicalNetworkExternalDeviceVO(long networkServiceProviderId, long hostId) { + this.networkServiceProviderId = networkServiceProviderId; + this.hostId = hostId; + } + + public long getId() { + return id; + } + + public long getNetworkServiceProviderId() { + return networkServiceProviderId; + } + + public long getHostId() { + return hostId; + } +} diff --git a/server/src/com/cloud/network/dao/PhysicalNetworkExternalDeviceDao.java b/server/src/com/cloud/network/dao/PhysicalNetworkExternalDeviceDao.java new file mode 100644 index 00000000000..687edf422f0 --- /dev/null +++ b/server/src/com/cloud/network/dao/PhysicalNetworkExternalDeviceDao.java @@ -0,0 +1,29 @@ +/** + * Copyright (C) 2011 Citrix Systems, Inc. All rights reserved. + * + * This software is licensed under the GNU General Public License v3 or later. + * + * It is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or any later version. + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + */ + +package com.cloud.network.dao; + +import java.util.List; +import com.cloud.network.PhysicalNetworkExternalDeviceVO; +import com.cloud.utils.db.GenericDao; + +public interface PhysicalNetworkExternalDeviceDao extends GenericDao { + + List listByNetworkServiceProviderId(long networkServiceProviderId); + +} diff --git a/server/src/com/cloud/network/dao/PhysicalNetworkExternalDeviceDaoImpl.java b/server/src/com/cloud/network/dao/PhysicalNetworkExternalDeviceDaoImpl.java new file mode 100644 index 00000000000..46168b7ec58 --- /dev/null +++ b/server/src/com/cloud/network/dao/PhysicalNetworkExternalDeviceDaoImpl.java @@ -0,0 +1,49 @@ +/** + * Copyright (C) 2011 Citrix Systems, Inc. All rights reserved. + * + * This software is licensed under the GNU General Public License v3 or later. + * + * It is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or any later version. + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + */ + +package com.cloud.network.dao; + +import java.util.List; +import javax.ejb.Local; +import com.cloud.network.PhysicalNetworkExternalDeviceVO; +import com.cloud.utils.db.DB; +import com.cloud.utils.db.GenericDaoBase; +import com.cloud.utils.db.SearchBuilder; +import com.cloud.utils.db.SearchCriteria; +import com.cloud.utils.db.SearchCriteria.Op; + +@Local(value=PhysicalNetworkExternalDeviceDao.class) @DB(txn=false) +public class PhysicalNetworkExternalDeviceDaoImpl extends GenericDaoBase implements PhysicalNetworkExternalDeviceDao { + final SearchBuilder physicalNetworkServiceProviderSearch; + + protected PhysicalNetworkExternalDeviceDaoImpl() { + super(); + physicalNetworkServiceProviderSearch = createSearchBuilder(); + physicalNetworkServiceProviderSearch.and("networkServiceProviderId", physicalNetworkServiceProviderSearch.entity().getNetworkServiceProviderId(), Op.EQ); + physicalNetworkServiceProviderSearch.done(); + + } + + @Override + public List listByNetworkServiceProviderId(long networkServiceProviderId) { + SearchCriteria sc = physicalNetworkServiceProviderSearch.create(); + sc.setParameters("networkServiceProviderId", networkServiceProviderId); + return search(sc, null); + } + +} diff --git a/server/src/com/cloud/network/dao/PhysicalNetworkServiceProviderDao.java b/server/src/com/cloud/network/dao/PhysicalNetworkServiceProviderDao.java index 128add7718d..8aab7bf5a52 100644 --- a/server/src/com/cloud/network/dao/PhysicalNetworkServiceProviderDao.java +++ b/server/src/com/cloud/network/dao/PhysicalNetworkServiceProviderDao.java @@ -23,6 +23,6 @@ import com.cloud.utils.db.GenericDao; public interface PhysicalNetworkServiceProviderDao extends GenericDao { List listBy(long physicalNetworkId); - + PhysicalNetworkServiceProviderVO findByServiceProvider(long physicalNetworkId, String providerType); void deleteProviders(long physicalNetworkId); } diff --git a/server/src/com/cloud/network/dao/PhysicalNetworkServiceProviderDaoImpl.java b/server/src/com/cloud/network/dao/PhysicalNetworkServiceProviderDaoImpl.java index 0a373510a48..f60ee6db232 100644 --- a/server/src/com/cloud/network/dao/PhysicalNetworkServiceProviderDaoImpl.java +++ b/server/src/com/cloud/network/dao/PhysicalNetworkServiceProviderDaoImpl.java @@ -30,6 +30,7 @@ import com.cloud.utils.db.SearchCriteria.Op; @Local(value=PhysicalNetworkServiceProviderDao.class) @DB(txn=false) public class PhysicalNetworkServiceProviderDaoImpl extends GenericDaoBase implements PhysicalNetworkServiceProviderDao { final SearchBuilder physicalNetworkSearch; + final SearchBuilder physicalNetworkServiceProviderSearch; protected PhysicalNetworkServiceProviderDaoImpl() { super(); @@ -37,6 +38,10 @@ public class PhysicalNetworkServiceProviderDaoImpl extends GenericDaoBase sc = physicalNetworkServiceProviderSearch.create(); + sc.setParameters("physicalNetworkId", physicalNetworkId); + sc.setParameters("serviceProvderType", providerType); + return findOneBy(sc); + } + @Override public void deleteProviders(long physicalNetworkId) { SearchCriteria sc = physicalNetworkSearch.create(); diff --git a/server/src/com/cloud/network/element/NetscalerExternalLoadBalancerElement.java b/server/src/com/cloud/network/element/NetscalerExternalLoadBalancerElement.java index 2bb3fb9b58e..07cb5c082de 100644 --- a/server/src/com/cloud/network/element/NetscalerExternalLoadBalancerElement.java +++ b/server/src/com/cloud/network/element/NetscalerExternalLoadBalancerElement.java @@ -68,7 +68,7 @@ public class NetscalerExternalLoadBalancerElement extends AdapterBase implements } return (_networkManager.networkIsConfiguredForExternalNetworking(zone.getId(), config.getNetworkOfferingId()) && - _ntwkOfferingSrvcDao.isProviderSupported(config.getNetworkOfferingId(), Service.Lb, Network.Provider.NetscalerMPX)); + _ntwkOfferingSrvcDao.isProviderSupported(config.getNetworkOfferingId(), Service.Lb, Network.Provider.Netscaler)); } @Override @@ -140,6 +140,6 @@ public class NetscalerExternalLoadBalancerElement extends AdapterBase implements @Override public Provider getProvider() { - return Provider.NetscalerMPX; + return Provider.Netscaler; } } diff --git a/setup/db/create-schema.sql b/setup/db/create-schema.sql index 5332553ec0d..8fd53cba5f9 100755 --- a/setup/db/create-schema.sql +++ b/setup/db/create-schema.sql @@ -1825,4 +1825,13 @@ CREATE TABLE `cloud`.`physical_network_service_providers` ( CONSTRAINT `fk_pnetwork_service_providers__physical_network_id` FOREIGN KEY (`physical_network_id`) REFERENCES `physical_network`(`id`) ON DELETE CASCADE ) ENGINE=InnoDB DEFAULT CHARSET=utf8; +CREATE TABLE `cloud`.`physical_network_external_devices` ( + `id` bigint unsigned NOT NULL AUTO_INCREMENT COMMENT 'id', + `physical_network_service_provider_id` bigint unsigned NOT NULL COMMENT 'id of physical network to service provider mapping', + `host_id` bigint unsigned NOT NULL COMMENT 'host id', + PRIMARY KEY (`id`), + CONSTRAINT `fk_physical_network_external_devices_network_service_provider_id` FOREIGN KEY (`physical_network_service_provider_id`) REFERENCES `physical_network_service_providers`(`id`) ON DELETE CASCADE, + CONSTRAINT `fk_physical_network_external_devices_host_id` FOREIGN KEY (`host_id`) REFERENCES `host`(`id`) ON DELETE CASCADE +) ENGINE=InnoDB DEFAULT CHARSET=utf8; + SET foreign_key_checks = 1; From 95bac58076e8e4b15476085081567d1d968ff42f Mon Sep 17 00:00:00 2001 From: alena Date: Wed, 26 Oct 2011 17:59:37 -0700 Subject: [PATCH 035/159] Cleanup firewall/pf/lb/vpn rules as a part of networkShutdown --- .../cloud/network/lb/LoadBalancingRule.java | 4 + .../com/cloud/network/NetworkManagerImpl.java | 341 +++++++++++++----- .../RedundantVirtualRouterElement.java | 4 +- .../network/element/VirtualRouterElement.java | 5 +- .../VirtualNetworkApplianceManagerImpl.java | 10 +- .../cloud/network/rules/RulesManagerImpl.java | 58 +-- 6 files changed, 278 insertions(+), 144 deletions(-) diff --git a/api/src/com/cloud/network/lb/LoadBalancingRule.java b/api/src/com/cloud/network/lb/LoadBalancingRule.java index 4cb60c2e44e..27b5c14cf63 100644 --- a/api/src/com/cloud/network/lb/LoadBalancingRule.java +++ b/api/src/com/cloud/network/lb/LoadBalancingRule.java @@ -152,6 +152,10 @@ public class LoadBalancingRule implements FirewallRule, LoadBalancer{ public boolean isRevoked() { return revoked; } + + public void setRevoked(boolean revoked) { + this.revoked = revoked; + } } @Override diff --git a/server/src/com/cloud/network/NetworkManagerImpl.java b/server/src/com/cloud/network/NetworkManagerImpl.java index 3d3735e1027..131d2764d3f 100755 --- a/server/src/com/cloud/network/NetworkManagerImpl.java +++ b/server/src/com/cloud/network/NetworkManagerImpl.java @@ -97,6 +97,7 @@ import com.cloud.network.PhysicalNetwork.BroadcastDomainRange; import com.cloud.network.addr.PublicIp; import com.cloud.network.dao.FirewallRulesDao; import com.cloud.network.dao.IPAddressDao; +import com.cloud.network.dao.LoadBalancerDao; import com.cloud.network.dao.NetworkDao; import com.cloud.network.dao.NetworkDomainDao; import com.cloud.network.dao.PhysicalNetworkDao; @@ -110,13 +111,19 @@ import com.cloud.network.element.RemoteAccessVPNServiceProvider; import com.cloud.network.element.SourceNATServiceProvider; import com.cloud.network.element.StaticNATServiceProvider; import com.cloud.network.guru.NetworkGuru; +import com.cloud.network.lb.LoadBalancingRule; +import com.cloud.network.lb.LoadBalancingRule.LbDestination; import com.cloud.network.lb.LoadBalancingRulesManager; import com.cloud.network.rules.FirewallManager; import com.cloud.network.rules.FirewallRule; import com.cloud.network.rules.FirewallRule.Purpose; import com.cloud.network.rules.FirewallRuleVO; +import com.cloud.network.rules.PortForwardingRuleVO; import com.cloud.network.rules.RulesManager; import com.cloud.network.rules.StaticNat; +import com.cloud.network.rules.StaticNatRule; +import com.cloud.network.rules.StaticNatRuleImpl; +import com.cloud.network.rules.dao.PortForwardingRulesDao; import com.cloud.network.vpn.RemoteAccessVpnService; import com.cloud.offering.NetworkOffering; import com.cloud.offering.NetworkOffering.Availability; @@ -244,6 +251,8 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag @Inject NetworkOfferingServiceMapDao _ntwkOfferingSrvcDao; @Inject PhysicalNetworkDao _physicalNetworkDao; @Inject PhysicalNetworkServiceProviderDao _pNSPDao; + @Inject PortForwardingRulesDao _portForwardingRulesDao; + @Inject LoadBalancerDao _lbDao; private final HashMap _systemNetworks = new HashMap(5); @@ -511,6 +520,32 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag } } + boolean success = applyIpAssociations(network, continueOnError, publicIps); + + if (success) { + for (IPAddressVO addr : userIps) { + + if (addr.getState() == IpAddress.State.Allocating) { + + addr.setAssociatedWithNetworkId(network.getId()); + markPublicIpAsAllocated(addr); + + } else if (addr.getState() == IpAddress.State.Releasing) { + // Cleanup all the resources for ip address if there are any, and only then un-assign ip in the system + if (cleanupIpResources(addr.getId(), Account.ACCOUNT_ID_SYSTEM, _accountMgr.getSystemAccount())) { + _ipAddressDao.unassignIpAddress(addr.getId()); + } else { + success = false; + s_logger.warn("Failed to release resources for ip address id=" + addr.getId()); + } + } + } + } + + return success; + } + + protected boolean applyIpAssociations(Network network, boolean continueOnError, List publicIps) throws ResourceUnavailableException { boolean success = true; int found = 0; for (NetworkElement element : _networkElements) { @@ -531,29 +566,10 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag } } } - - if (success) { - for (IPAddressVO addr : userIps) { - - if (addr.getState() == IpAddress.State.Allocating) { - - addr.setAssociatedWithNetworkId(network.getId()); - markPublicIpAsAllocated(addr); - - } else if (addr.getState() == IpAddress.State.Releasing) { - // Cleanup all the resources for ip address if there are any, and only then unassign ip in the system - if (cleanupIpResources(addr.getId(), Account.ACCOUNT_ID_SYSTEM, _accountMgr.getSystemAccount())) { - _ipAddressDao.unassignIpAddress(addr.getId()); - } else { - success = false; - s_logger.warn("Failed to release resources for ip address id=" + addr.getId()); - } - } - } - } - return success; } + + @Override public List getIsolatedNetworksOwnedByAccountInZone(long zoneId, Account owner) { @@ -1287,7 +1303,7 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag // reapply all the firewall/staticNat/lb rules s_logger.debug("Reprogramming network " + network + " as a part of network implement"); - if (!reprogramNetwork(networkId, UserContext.current().getCaller(), network)) { + if (!reprogramNetworkRules(networkId, UserContext.current().getCaller(), network)) { s_logger.warn("Failed to re-program the network as a part of network " + network + " implement"); throw new ResourceUnavailableException("Unable to apply network rules as a part of network " + network + " implement", DataCenter.class, network.getDataCenterId()); } @@ -2151,7 +2167,17 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag _networksDao.update(network.getId(), network); txn.commit(); - //1) FIXME - Cleanup all the rules for the network + //1) Cleanup all the rules for the network. If it fails, just log the failure and proceed with shutting down the elements + boolean cleanupResult = true; + try { + cleanupResult = shutdownNetworkResources(networkId, context.getAccount(), context.getCaller().getId()); + } catch (Exception ex) { + s_logger.warn("shutdownNetworkRules failed during the network " + network + " shutdown due to ", ex); + } finally { + if (!cleanupResult) { + s_logger.warn("Failed to cleanup network id=" + networkId + " resources as a part of shutdownNetwork"); + } + } //2) Shutdown all the network elements boolean success = true; @@ -2285,66 +2311,6 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag return success; } - private boolean cleanupNetworkResources(long networkId, Account caller, long callerUserId) { - boolean success = true; - Network network = getNetwork(networkId); - - // remove all PF/Static Nat rules for the network - try { - if (_rulesMgr.revokeAllPFStaticNatRulesForNetwork(networkId, callerUserId, caller)) { - s_logger.debug("Successfully cleaned up portForwarding/staticNat rules for network id=" + networkId); - } else { - success = false; - s_logger.warn("Failed to release portForwarding/StaticNat rules as a part of network id=" + networkId + " cleanup"); - } - } catch (ResourceUnavailableException ex) { - success = false; - // shouldn't even come here as network is being cleaned up after all network elements are shutdown - s_logger.warn("Failed to release portForwarding/StaticNat rules as a part of network id=" + networkId + " cleanup due to resourceUnavailable ", ex); - } - - // remove all LB rules for the network - if (_lbMgr.removeAllLoadBalanacersForNetwork(networkId, caller, callerUserId)) { - s_logger.debug("Successfully cleaned up load balancing rules for network id=" + networkId); - } else { - // shouldn't even come here as network is being cleaned up after all network elements are shutdown - success = false; - s_logger.warn("Failed to cleanup LB rules as a part of network id=" + networkId + " cleanup"); - } - - //revoke all firewall rules for the network - try { - if (_firewallMgr.revokeAllFirewallRulesForNetwork(networkId, callerUserId, caller)) { - s_logger.debug("Successfully cleaned up firewallRules rules for network id=" + networkId); - } else { - success = false; - s_logger.warn("Failed to cleanup Firewall rules as a part of network id=" + networkId + " cleanup"); - } - } catch (ResourceUnavailableException ex) { - success = false; - // shouldn't even come here as network is being cleaned up after all network elements are shutdown - s_logger.warn("Failed to cleanup Firewall rules as a part of network id=" + networkId + " cleanup due to resourceUnavailable ", ex); - } - - // release all ip addresses - List ipsToRelease = _ipAddressDao.listByAssociatedNetwork(networkId, null); - for (IPAddressVO ipToRelease : ipsToRelease) { - IPAddressVO ip = markIpAsUnavailable(ipToRelease.getId()); - assert (ip != null) : "Unable to mark the ip address id=" + ipToRelease.getId() + " as unavailable."; - } - - try { - if (!applyIpAssociations(network, true)) { - s_logger.warn("Unable to apply ip address associations for " + network); - success = false; - } - } catch (ResourceUnavailableException e) { - throw new CloudRuntimeException("We should never get to here because we used true when applyIpAssociations", e); - } - - return success; - } - private boolean deleteVlansInNetwork(long networkId, long userId) { List vlans = _vlanDao.listVlansByNetworkId(networkId); boolean result = true; @@ -2456,8 +2422,8 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag // This method restarts all network elements belonging to the network and re-applies all the rules Long networkId = cmd.getNetworkId(); - User caller = _accountMgr.getActiveUser(UserContext.current().getCallerUserId()); - Account callerAccount = _accountMgr.getActiveAccountById(caller.getAccountId()); + User callerUser = _accountMgr.getActiveUser(UserContext.current().getCallerUserId()); + Account callerAccount = _accountMgr.getActiveAccountById(callerUser.getAccountId()); // Check if network exists NetworkVO network = _networksDao.findById(networkId); @@ -2472,7 +2438,7 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag _accountMgr.checkAccess(callerAccount, null, network); - boolean success = restartNetwork(networkId, callerAccount, null, cleanup); + boolean success = restartNetwork(networkId, callerAccount, callerUser, null, cleanup); if (success) { s_logger.debug("Network id=" + networkId + " is restarted successfully."); @@ -2503,14 +2469,14 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag } } - private boolean restartNetwork(long networkId, Account caller, Long newNetworkOfferingId, boolean cleanup) throws ConcurrentOperationException, ResourceUnavailableException, InsufficientCapacityException { + private boolean restartNetwork(long networkId, Account callerAccount, User callerUser, Long newNetworkOfferingId, boolean cleanup) throws ConcurrentOperationException, ResourceUnavailableException, InsufficientCapacityException { NetworkVO network = _networksDao.findById(networkId); s_logger.debug("Restarting network " + networkId + "..."); //shutdown the network - ReservationContext context = new ReservationContextImpl(null, null, null, caller); + ReservationContext context = new ReservationContextImpl(null, null, callerUser, callerAccount); s_logger.debug("Shutting down the network id=" + networkId + " as a part of network restart"); shutdownNetwork(networkId, context, cleanup); @@ -2544,7 +2510,7 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag //This method re-programs the rules/ips for existing network - protected boolean reprogramNetwork(long networkId, Account caller, NetworkVO network) throws ResourceUnavailableException { + protected boolean reprogramNetworkRules(long networkId, Account caller, NetworkVO network) throws ResourceUnavailableException { boolean success = true; // associate all ip addresses if (!applyIpAssociations(network, false)) { @@ -3199,7 +3165,7 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag s_logger.info("Restarting network " + network + " as a part of update network call"); try { - success = restartNetwork(networkId, caller, networkOfferingId, true); + success = restartNetwork(networkId, caller, null, networkOfferingId, true); } catch (Exception e) { success = false; } @@ -3960,8 +3926,6 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag return pNtwks.get(0); } - - @Override public List listNetworkOfferingsForUpgrade(long networkId) { @@ -3971,5 +3935,198 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag return offerings; } + + + private boolean cleanupNetworkResources(long networkId, Account caller, long callerUserId) { + boolean success = true; + Network network = getNetwork(networkId); + + // remove all PF/Static Nat rules for the network + try { + if (_rulesMgr.revokeAllPFStaticNatRulesForNetwork(networkId, callerUserId, caller)) { + s_logger.debug("Successfully cleaned up portForwarding/staticNat rules for network id=" + networkId); + } else { + success = false; + s_logger.warn("Failed to release portForwarding/StaticNat rules as a part of network id=" + networkId + " cleanup"); + } + } catch (ResourceUnavailableException ex) { + success = false; + // shouldn't even come here as network is being cleaned up after all network elements are shutdown + s_logger.warn("Failed to release portForwarding/StaticNat rules as a part of network id=" + networkId + " cleanup due to resourceUnavailable ", ex); + } + + // remove all LB rules for the network + if (_lbMgr.removeAllLoadBalanacersForNetwork(networkId, caller, callerUserId)) { + s_logger.debug("Successfully cleaned up load balancing rules for network id=" + networkId); + } else { + // shouldn't even come here as network is being cleaned up after all network elements are shutdown + success = false; + s_logger.warn("Failed to cleanup LB rules as a part of network id=" + networkId + " cleanup"); + } + + //revoke all firewall rules for the network + try { + if (_firewallMgr.revokeAllFirewallRulesForNetwork(networkId, callerUserId, caller)) { + s_logger.debug("Successfully cleaned up firewallRules rules for network id=" + networkId); + } else { + success = false; + s_logger.warn("Failed to cleanup Firewall rules as a part of network id=" + networkId + " cleanup"); + } + } catch (ResourceUnavailableException ex) { + success = false; + // shouldn't even come here as network is being cleaned up after all network elements are shutdown + s_logger.warn("Failed to cleanup Firewall rules as a part of network id=" + networkId + " cleanup due to resourceUnavailable ", ex); + } + + // release all ip addresses + List ipsToRelease = _ipAddressDao.listByAssociatedNetwork(networkId, null); + for (IPAddressVO ipToRelease : ipsToRelease) { + IPAddressVO ip = markIpAsUnavailable(ipToRelease.getId()); + assert (ip != null) : "Unable to mark the ip address id=" + ipToRelease.getId() + " as unavailable."; + } + + try { + if (!applyIpAssociations(network, true)) { + s_logger.warn("Unable to apply ip address associations for " + network); + success = false; + } + } catch (ResourceUnavailableException e) { + throw new CloudRuntimeException("We should never get to here because we used true when applyIpAssociations", e); + } + + return success; + } + + + private boolean shutdownNetworkResources(long networkId, Account caller, long callerUserId) { + //This method cleans up network rules on the backend w/o touching them in the DB + boolean success = true; + + // Mark all PF rules as revoked and apply them on the backend (not in the DB) + List pfRules = _portForwardingRulesDao.listByNetwork(networkId); + if (s_logger.isDebugEnabled()) { + s_logger.debug("Releasing " + pfRules.size() + " port forwarding rules for network id=" + networkId + " as a part of shutdownNetworkRules"); + } + + for (PortForwardingRuleVO pfRule : pfRules) { + s_logger.trace("Marking pf rule " + pfRule + " with Revoke state"); + pfRule.setState(FirewallRule.State.Revoke); + } + + try { + if (!_firewallMgr.applyRules(pfRules, true, false)) { + s_logger.warn("Failed to cleanup pf rules as a part of shutdownNetworkRules"); + success = false; + } + } catch (ResourceUnavailableException ex) { + s_logger.warn("Failed to cleanup pf rules as a part of shutdownNetworkRules due to ", ex); + success = false; + } + + // Mark all static rules as revoked and apply them on the backend (not in the DB) + List firewallStaticNatRules = _firewallDao.listByNetworkAndPurpose(networkId, Purpose.StaticNat); + List staticNatRules = new ArrayList(); + if (s_logger.isDebugEnabled()) { + s_logger.debug("Releasing " + firewallStaticNatRules.size() + " static nat rules for network id=" + networkId + " as a part of shutdownNetworkRules"); + } + + for (FirewallRuleVO firewallStaticNatRule : firewallStaticNatRules) { + s_logger.trace("Marking static nat rule " + firewallStaticNatRule + " with Revoke state"); + IpAddress ip = _ipAddressDao.findById(firewallStaticNatRule.getSourceIpAddressId()); + FirewallRuleVO ruleVO = _firewallDao.findById(firewallStaticNatRule.getId()); + + if (ip == null || !ip.isOneToOneNat() || ip.getAssociatedWithVmId() == null) { + throw new InvalidParameterValueException("Source ip address of the rule id=" + firewallStaticNatRule.getId() + " is not static nat enabled"); + } + + String dstIp = getIpInNetwork(ip.getAssociatedWithVmId(), firewallStaticNatRule.getNetworkId()); + ruleVO.setState(FirewallRule.State.Revoke); + staticNatRules.add(new StaticNatRuleImpl(ruleVO, dstIp)); + } + + try { + if (!_firewallMgr.applyRules(staticNatRules, true, false)) { + s_logger.warn("Failed to cleanup static nat rules as a part of shutdownNetworkRules"); + success = false; + } + } catch (ResourceUnavailableException ex) { + s_logger.warn("Failed to cleanup static nat rules as a part of shutdownNetworkRules due to ", ex); + success = false; + } + + // remove all LB rules for the network + List lbs = _lbDao.listByNetworkId(networkId); + List lbRules = new ArrayList(); + for (LoadBalancerVO lb : lbs) { + s_logger.trace("Marking lb rule " + lb + " with Revoke state"); + lb.setState(FirewallRule.State.Revoke); + List dstList = _lbMgr.getExistingDestinations(lb.getId()); + //mark all destination with revoke state + for (LbDestination dst : dstList) { + s_logger.trace("Marking lb destination " + dst + " with Revoke state"); + dst.setRevoked(true); + } + + LoadBalancingRule loadBalancing = new LoadBalancingRule(lb, dstList); + lbRules.add(loadBalancing); + } + + try { + if (!_firewallMgr.applyRules(lbRules, true, false)) { + s_logger.warn("Failed to cleanup lb rules as a part of shutdownNetworkRules"); + success = false; + } + } catch (ResourceUnavailableException ex) { + s_logger.warn("Failed to cleanup lb rules as a part of shutdownNetworkRules due to ", ex); + success = false; + } + + //revoke all firewall rules for the network w/o applying them on the DB + List firewallRules = _firewallDao.listByNetworkAndPurpose(networkId, Purpose.Firewall); + if (s_logger.isDebugEnabled()) { + s_logger.debug("Releasing " + firewallRules.size() + " firewall rules for network id=" + networkId + " as a part of shutdownNetworkRules"); + } + + for (FirewallRuleVO firewallRule : firewallRules) { + s_logger.trace("Marking firewall rule " + firewallRule + " with Revoke state"); + firewallRule.setState(FirewallRule.State.Revoke); + } + + try { + if (!_firewallMgr.applyRules(firewallRules, true, false)) { + s_logger.warn("Failed to cleanup firewall rules as a part of shutdownNetworkRules"); + success = false; + } + } catch (ResourceUnavailableException ex) { + s_logger.warn("Failed to cleanup firewall rules as a part of shutdownNetworkRules due to ", ex); + success = false; + } + + // Get all ip addresses, mark as releasing and release them on the backend (except for source nat) - DONE + Network network = getNetwork(networkId); + List userIps = _ipAddressDao.listByAssociatedNetwork(networkId, null); + List publicIpsToRelease = new ArrayList(); + if (userIps != null && !userIps.isEmpty()) { + for (IPAddressVO userIp : userIps) { + if (!userIp.isSourceNat()) { + userIp.setState(State.Releasing); + } + PublicIp publicIp = new PublicIp(userIp, _vlanDao.findById(userIp.getVlanId()), NetUtils.createSequenceBasedMacAddress(userIp.getMacAddress())); + publicIpsToRelease.add(publicIp); + } + } + + try { + if (!applyIpAssociations(network, true, publicIpsToRelease)) { + s_logger.warn("Unable to apply ip address associations for " + network + " as a part of shutdownNetworkRules"); + success = false; + } + } catch (ResourceUnavailableException e) { + throw new CloudRuntimeException("We should never get to here because we used true when applyIpAssociations", e); + } + + return success; + } + } diff --git a/server/src/com/cloud/network/element/RedundantVirtualRouterElement.java b/server/src/com/cloud/network/element/RedundantVirtualRouterElement.java index 85eabbe6898..65b63058c48 100644 --- a/server/src/com/cloud/network/element/RedundantVirtualRouterElement.java +++ b/server/src/com/cloud/network/element/RedundantVirtualRouterElement.java @@ -43,9 +43,9 @@ public class RedundantVirtualRouterElement extends VirtualRouterElement implemen } private boolean canHandle(Type networkType, long offeringId) { - boolean result = (networkType == Network.Type.Isolated && _networkMgr.isProviderSupported(offeringId, Service.Gateway, Provider.VirtualRouter)); + boolean result = (networkType == Network.Type.Isolated && _networkMgr.isProviderSupported(offeringId, Service.Gateway, getProvider())); if (!result) { - s_logger.trace("Virtual router element only takes care of networktype " + Network.Type.Isolated + " for provider " + Provider.VirtualRouter.getName()); + s_logger.trace("Virtual router element only takes care of networktype " + Network.Type.Isolated + " for provider " + getProvider().getName()); } return result; } diff --git a/server/src/com/cloud/network/element/VirtualRouterElement.java b/server/src/com/cloud/network/element/VirtualRouterElement.java index 1b350a3268d..f1cfbaa6566 100644 --- a/server/src/com/cloud/network/element/VirtualRouterElement.java +++ b/server/src/com/cloud/network/element/VirtualRouterElement.java @@ -91,9 +91,9 @@ public class VirtualRouterElement extends DhcpElement implements VirtualRouterEl @Inject VirtualRouterElementsDao _vrElementsDao; private boolean canHandle(Type networkType, long offeringId) { - boolean result = (networkType == Network.Type.Isolated && _networkMgr.isProviderSupported(offeringId, Service.Gateway, Provider.VirtualRouter)); + boolean result = (networkType == Network.Type.Isolated && _networkMgr.isProviderSupported(offeringId, Service.Gateway, getProvider())); if (!result) { - s_logger.trace("Virtual router element only takes care of type " + Network.Type.Isolated + " for provider " + Provider.VirtualRouter.getName()); + s_logger.trace("Virtual router element only takes care of type " + Network.Type.Isolated + " for provider " + getProvider().getName()); } return result; } @@ -251,7 +251,6 @@ public class VirtualRouterElement extends DhcpElement implements VirtualRouterEl @Override public boolean applyIps(Network network, List ipAddress) throws ResourceUnavailableException { - DataCenter dc = _configMgr.getZone(network.getDataCenterId()); if (canHandle(network.getType(), network.getNetworkOfferingId())) { List routers = _routerDao.listByNetworkAndRole(network.getId(), Role.DHCP_FIREWALL_LB_PASSWD_USERDATA); diff --git a/server/src/com/cloud/network/router/VirtualNetworkApplianceManagerImpl.java b/server/src/com/cloud/network/router/VirtualNetworkApplianceManagerImpl.java index 991cd31466d..59bce7e92b0 100755 --- a/server/src/com/cloud/network/router/VirtualNetworkApplianceManagerImpl.java +++ b/server/src/com/cloud/network/router/VirtualNetworkApplianceManagerImpl.java @@ -2524,15 +2524,7 @@ public class VirtualNetworkApplianceManagerImpl implements VirtualNetworkApplian if (rules != null && !rules.isEmpty()) { try { if (rules.get(0).getPurpose() == Purpose.LoadBalancing) { - // for load balancer we have to resend all lb rules for the network - List lbs = _loadBalancerDao.listByNetworkId(network.getId()); - List lbRules = new ArrayList(); - for (LoadBalancerVO lb : lbs) { - List dstList = _lbMgr.getExistingDestinations(lb.getId()); - LoadBalancingRule loadBalancing = new LoadBalancingRule(lb, dstList); - lbRules.add(loadBalancing); - } - result = result && applyLBRules(router, lbRules); + result = result && applyLBRules(router, (List)rules); } else if (rules.get(0).getPurpose() == Purpose.PortForwarding) { result = result && applyPortForwardingRules(router, (List) rules); } else if (rules.get(0).getPurpose() == Purpose.StaticNat) { diff --git a/server/src/com/cloud/network/rules/RulesManagerImpl.java b/server/src/com/cloud/network/rules/RulesManagerImpl.java index 02ade29b14b..ce9592bfd4f 100755 --- a/server/src/com/cloud/network/rules/RulesManagerImpl.java +++ b/server/src/com/cloud/network/rules/RulesManagerImpl.java @@ -78,7 +78,7 @@ public class RulesManagerImpl implements RulesManager, RulesService, Manager { String _name; @Inject - PortForwardingRulesDao _forwardingDao; + PortForwardingRulesDao _portForwardingDao; @Inject FirewallRulesCidrsDao _firewallCidrsDao; @Inject @@ -204,7 +204,7 @@ public class RulesManagerImpl implements RulesManager, RulesService, Manager { PortForwardingRuleVO newRule = new PortForwardingRuleVO(rule.getXid(), rule.getSourceIpAddressId(), rule.getSourcePortStart(), rule.getSourcePortEnd(), dstIp, rule.getDestinationPortStart(), rule.getDestinationPortEnd(), rule.getProtocol().toLowerCase(), networkId, accountId, domainId, vmId); - newRule = _forwardingDao.persist(newRule); + newRule = _portForwardingDao.persist(newRule); //create firewallRule for 0.0.0.0/0 cidr if (openFirewall) { @@ -229,7 +229,7 @@ public class RulesManagerImpl implements RulesManager, RulesService, Manager { txn.start(); //no need to apply the rule as it wasn't programmed on the backend yet _firewallMgr.revokeRelatedFirewallRule(newRule.getId(), false); - _forwardingDao.remove(newRule.getId()); + _portForwardingDao.remove(newRule.getId()); txn.commit(); } @@ -300,7 +300,7 @@ public class RulesManagerImpl implements RulesManager, RulesService, Manager { txn.start(); //no need to apply the rule as it wasn't programmed on the backend yet _firewallMgr.revokeRelatedFirewallRule(newRule.getId(), false); - _forwardingDao.remove(newRule.getId()); + _portForwardingDao.remove(newRule.getId()); txn.commit(); } @@ -398,7 +398,7 @@ public class RulesManagerImpl implements RulesManager, RulesService, Manager { UserContext ctx = UserContext.current(); Account caller = ctx.getCaller(); - PortForwardingRuleVO rule = _forwardingDao.findById(ruleId); + PortForwardingRuleVO rule = _portForwardingDao.findById(ruleId); if (rule == null) { throw new InvalidParameterValueException("Unable to find " + ruleId); } @@ -409,7 +409,7 @@ public class RulesManagerImpl implements RulesManager, RulesService, Manager { } private boolean revokePortForwardingRuleInternal(long ruleId, Account caller, long userId, boolean apply) { - PortForwardingRuleVO rule = _forwardingDao.findById(ruleId); + PortForwardingRuleVO rule = _portForwardingDao.findById(ruleId); _firewallMgr.revokeRule(rule, caller, userId, true); @@ -464,7 +464,7 @@ public class RulesManagerImpl implements RulesManager, RulesService, Manager { return false; } - List rules = _forwardingDao.listByVm(vmId); + List rules = _portForwardingDao.listByVm(vmId); Set ipsToReprogram = new HashSet(); if (rules == null || rules.isEmpty()) { @@ -527,7 +527,7 @@ public class RulesManagerImpl implements RulesManager, RulesService, Manager { @Override public List listPortForwardingRulesForApplication(long ipId) { - return _forwardingDao.listForApplication(ipId); + return _portForwardingDao.listForApplication(ipId); } @Override @@ -555,7 +555,7 @@ public class RulesManagerImpl implements RulesManager, RulesService, Manager { } Filter filter = new Filter(PortForwardingRuleVO.class, "id", false, cmd.getStartIndex(), cmd.getPageSizeVal()); - SearchBuilder sb = _forwardingDao.createSearchBuilder(); + SearchBuilder sb = _portForwardingDao.createSearchBuilder(); sb.and("id", sb.entity().getId(), Op.EQ); sb.and("ip", sb.entity().getSourceIpAddressId(), Op.EQ); sb.and("accountId", sb.entity().getAccountId(), Op.IN); @@ -593,7 +593,7 @@ public class RulesManagerImpl implements RulesManager, RulesService, Manager { sc.setJoinParameters("domainSearch", "path", path + "%"); } - return _forwardingDao.search(sc, filter); + return _portForwardingDao.search(sc, filter); } @Override @@ -603,7 +603,7 @@ public class RulesManagerImpl implements RulesManager, RulesService, Manager { @Override public boolean applyPortForwardingRules(long ipId, boolean continueOnError, Account caller) { - List rules = _forwardingDao.listForApplication(ipId); + List rules = _portForwardingDao.listForApplication(ipId); if (rules.size() == 0) { s_logger.debug("There are no firwall rules to apply for ip id=" + ipId); @@ -638,25 +638,7 @@ public class RulesManagerImpl implements RulesManager, RulesService, Manager { } for (FirewallRule rule : rules) { - IpAddress sourceIp = _ipAddressDao.findById(rule.getSourceIpAddressId()); - - UserVmVO vm = _vmDao.findById(sourceIp.getAssociatedWithVmId()); - - Long networkId = sourceIp.getAssociatedWithNetworkId(); - if (networkId == null) { - throw new CloudRuntimeException("Ip address is not associated with any network"); - } - - Network network = _networkMgr.getNetwork(networkId); - - if (network == null) { - throw new CloudRuntimeException("Unable to find ip address to map to in vm id=" + vm.getId()); - } - - Nic guestNic = _networkMgr.getNicInNetworkIncludingRemoved(vm.getId(), networkId); - FirewallRuleVO ruleVO = _firewallDao.findById(rule.getId()); - - staticNatRules.add(new StaticNatRuleImpl(ruleVO, guestNic.getIp4Address())); + staticNatRules.add(buildStaticNatRule(rule)); } if (caller != null) { @@ -852,7 +834,7 @@ public class RulesManagerImpl implements RulesManager, RulesService, Manager { public boolean revokeAllPFAndStaticNatRulesForIp(long ipId, long userId, Account caller) throws ResourceUnavailableException { List rules = new ArrayList(); - List pfRules = _forwardingDao.listByIpAndNotRevoked(ipId); + List pfRules = _portForwardingDao.listByIpAndNotRevoked(ipId); if (s_logger.isDebugEnabled()) { s_logger.debug("Releasing " + pfRules.size() + " port forwarding rules for ip id=" + ipId); } @@ -883,7 +865,7 @@ public class RulesManagerImpl implements RulesManager, RulesService, Manager { applyStaticNatRules(ipId, true, caller); // Now we check again in case more rules have been inserted. - rules.addAll(_forwardingDao.listByIpAndNotRevoked(ipId)); + rules.addAll(_portForwardingDao.listByIpAndNotRevoked(ipId)); rules.addAll(_firewallDao.listByIpAndPurposeAndNotRevoked(ipId, Purpose.StaticNat)); if (s_logger.isDebugEnabled()) { @@ -897,7 +879,7 @@ public class RulesManagerImpl implements RulesManager, RulesService, Manager { public boolean revokeAllPFStaticNatRulesForNetwork(long networkId, long userId, Account caller) throws ResourceUnavailableException { List rules = new ArrayList(); - List pfRules = _forwardingDao.listByNetwork(networkId); + List pfRules = _portForwardingDao.listByNetwork(networkId); if (s_logger.isDebugEnabled()) { s_logger.debug("Releasing " + pfRules.size() + " port forwarding rules for network id=" + networkId); } @@ -925,7 +907,7 @@ public class RulesManagerImpl implements RulesManager, RulesService, Manager { success = success && applyStaticNatRulesForNetwork(networkId, true, caller); // Now we check again in case more rules have been inserted. - rules.addAll(_forwardingDao.listByNetworkAndNotRevoked(networkId)); + rules.addAll(_portForwardingDao.listByNetworkAndNotRevoked(networkId)); rules.addAll(_firewallDao.listByNetworkAndPurposeAndNotRevoked(networkId, Purpose.StaticNat)); if (s_logger.isDebugEnabled()) { @@ -996,7 +978,7 @@ public class RulesManagerImpl implements RulesManager, RulesService, Manager { txn.start(); for (FirewallRuleVO newRule : rules) { - _forwardingDao.remove(newRule.getId()); + _portForwardingDao.remove(newRule.getId()); } txn.commit(); } @@ -1014,7 +996,7 @@ public class RulesManagerImpl implements RulesManager, RulesService, Manager { } continue; } - allRules.addAll(_forwardingDao.listForApplication(addr.getId())); + allRules.addAll(_portForwardingDao.listForApplication(addr.getId())); } if (s_logger.isDebugEnabled()) { @@ -1026,7 +1008,7 @@ public class RulesManagerImpl implements RulesManager, RulesService, Manager { @Override public List listByNetworkId(long networkId) { - return _forwardingDao.listByNetwork(networkId); + return _portForwardingDao.listByNetwork(networkId); } @Override @@ -1060,7 +1042,7 @@ public class RulesManagerImpl implements RulesManager, RulesService, Manager { @Override public PortForwardingRule getPortForwardigRule(long ruleId) { - return _forwardingDao.findById(ruleId); + return _portForwardingDao.findById(ruleId); } @Override From cb329095b19e94cef014de9deb9964117e524844 Mon Sep 17 00:00:00 2001 From: alena Date: Thu, 27 Oct 2011 10:47:41 -0700 Subject: [PATCH 036/159] When restartNetwork, just shutdown/implement elements and rules, no need to shutdown/implement the network itself. --- .../DefaultComponentLibrary.java | 2 + .../com/cloud/network/NetworkManagerImpl.java | 133 ++++++++++-------- .../PhysicalNetworkExternalDeviceVO.java | 3 + 3 files changed, 77 insertions(+), 61 deletions(-) diff --git a/server/src/com/cloud/configuration/DefaultComponentLibrary.java b/server/src/com/cloud/configuration/DefaultComponentLibrary.java index 251c163bdbe..a29ed284b4b 100755 --- a/server/src/com/cloud/configuration/DefaultComponentLibrary.java +++ b/server/src/com/cloud/configuration/DefaultComponentLibrary.java @@ -81,6 +81,7 @@ import com.cloud.network.dao.NetworkDaoImpl; import com.cloud.network.dao.NetworkDomainDaoImpl; import com.cloud.network.dao.NetworkRuleConfigDaoImpl; import com.cloud.network.dao.PhysicalNetworkDaoImpl; +import com.cloud.network.dao.PhysicalNetworkExternalDeviceDaoImpl; import com.cloud.network.dao.PhysicalNetworkServiceProviderDaoImpl; import com.cloud.network.dao.RemoteAccessVpnDaoImpl; import com.cloud.network.dao.VirtualRouterElementsDaoImpl; @@ -297,6 +298,7 @@ public class DefaultComponentLibrary extends ComponentLibraryBase implements Com addDao("PhysicalNetworkDao", PhysicalNetworkDaoImpl.class); addDao("PhysicalNetworkServiceProviderDao", PhysicalNetworkServiceProviderDaoImpl.class); addDao("VirtualRouterElementsDao", VirtualRouterElementsDaoImpl.class); + addDao("PhysicalNetworkExternalDeviceDao", PhysicalNetworkExternalDeviceDaoImpl.class); } @Override diff --git a/server/src/com/cloud/network/NetworkManagerImpl.java b/server/src/com/cloud/network/NetworkManagerImpl.java index 131d2764d3f..bad8ae2010c 100755 --- a/server/src/com/cloud/network/NetworkManagerImpl.java +++ b/server/src/com/cloud/network/NetworkManagerImpl.java @@ -1282,31 +1282,8 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag network.setMode(result.getMode()); _networksDao.update(networkId, network); - // If this is a 1) guest virtual network 2) network has sourceNat service 3) network offering does not support a Shared source NAT rule, - // associate a source NAT IP (if one isn't already associated with the network) - if (network.getType() == Network.Type.Isolated && isServiceSupportedByNetworkOffering(network.getNetworkOfferingId(), Service.SourceNat) && !offering.isSharedSourceNatService()) { - List ips = _ipAddressDao.listByAssociatedNetwork(networkId, true); - - if (ips.isEmpty()) { - s_logger.debug("Creating a source nat ip for " + network); - Account owner = _accountMgr.getAccount(network.getAccountId()); - assignSourceNatIpAddress(owner, network, context.getCaller().getId()); - } - } - - for (NetworkElement element : _networkElements) { - if (s_logger.isDebugEnabled()) { - s_logger.debug("Asking " + element.getName() + " to implemenet " + network); - } - element.implement(network, offering, dest, context); - } - - // reapply all the firewall/staticNat/lb rules - s_logger.debug("Reprogramming network " + network + " as a part of network implement"); - if (!reprogramNetworkRules(networkId, UserContext.current().getCaller(), network)) { - s_logger.warn("Failed to re-program the network as a part of network " + network + " implement"); - throw new ResourceUnavailableException("Unable to apply network rules as a part of network " + network + " implement", DataCenter.class, network.getDataCenterId()); - } + //implement network elements and re-apply all the network rules + implementNetworkElementsAndResources(dest, context, network, offering); network.setState(Network.State.Implemented); _networksDao.update(network.getId(), network); @@ -1324,6 +1301,35 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag } } + private void implementNetworkElementsAndResources(DeployDestination dest, ReservationContext context, NetworkVO network, NetworkOfferingVO offering) + throws ConcurrentOperationException, InsufficientAddressCapacityException, ResourceUnavailableException, InsufficientCapacityException { + // If this is a 1) guest virtual network 2) network has sourceNat service 3) network offering does not support a Shared source NAT rule, + // associate a source NAT IP (if one isn't already associated with the network) + if (network.getType() == Network.Type.Isolated && isServiceSupportedByNetworkOffering(network.getNetworkOfferingId(), Service.SourceNat) && !offering.isSharedSourceNatService()) { + List ips = _ipAddressDao.listByAssociatedNetwork(network.getId(), true); + + if (ips.isEmpty()) { + s_logger.debug("Creating a source nat ip for " + network); + Account owner = _accountMgr.getAccount(network.getAccountId()); + assignSourceNatIpAddress(owner, network, context.getCaller().getId()); + } + } + + for (NetworkElement element : _networkElements) { + if (s_logger.isDebugEnabled()) { + s_logger.debug("Asking " + element.getName() + " to implemenet " + network); + } + element.implement(network, offering, dest, context); + } + + // reapply all the firewall/staticNat/lb rules + s_logger.debug("Reprogramming network " + network + " as a part of network implement"); + if (!reprogramNetworkRules(network.getId(), UserContext.current().getCaller(), network)) { + s_logger.warn("Failed to re-program the network as a part of network " + network + " implement"); + throw new ResourceUnavailableException("Unable to apply network rules as a part of network " + network + " implement", DataCenter.class, network.getDataCenterId()); + } + } + @DB protected void updateNic(NicVO nic, long networkId, int count) { Transaction txn = Transaction.currentTxn(); @@ -2167,15 +2173,41 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag _networksDao.update(network.getId(), network); txn.commit(); + boolean success = shutdownNetworkElementsAndResources(context, cleanupElements, network); + + txn.start(); + if (success) { + if (s_logger.isDebugEnabled()) { + s_logger.debug("Network id=" + networkId + " is shutdown successfully, cleaning up corresponding resources now."); + } + NetworkGuru guru = _networkGurus.get(network.getGuruName()); + NetworkProfile profile = convertNetworkToNetworkProfile(network.getId()); + guru.shutdown(profile, _networkOfferingDao.findById(network.getNetworkOfferingId())); + + applyProfileToNetwork(network, profile); + + network.setState(Network.State.Allocated); + _networksDao.update(network.getId(), network); + _networksDao.clearCheckForGc(networkId); + + } else { + network.setState(Network.State.Implemented); + _networksDao.update(network.getId(), network); + } + txn.commit(); + } + + private boolean shutdownNetworkElementsAndResources(ReservationContext context, boolean cleanupElements, NetworkVO network) { //1) Cleanup all the rules for the network. If it fails, just log the failure and proceed with shutting down the elements boolean cleanupResult = true; try { - cleanupResult = shutdownNetworkResources(networkId, context.getAccount(), context.getCaller().getId()); + cleanupResult = shutdownNetworkResources(network.getId(), context.getAccount(), context.getCaller().getId()); } catch (Exception ex) { s_logger.warn("shutdownNetworkRules failed during the network " + network + " shutdown due to ", ex); } finally { + //just warn the administrator that the network elements failed to shutdown if (!cleanupResult) { - s_logger.warn("Failed to cleanup network id=" + networkId + " resources as a part of shutdownNetwork"); + s_logger.warn("Failed to cleanup network id=" + network.getId() + " resources as a part of shutdownNetwork"); } } @@ -2199,27 +2231,7 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag success = false; } } - - txn.start(); - if (success) { - if (s_logger.isDebugEnabled()) { - s_logger.debug("Network id=" + networkId + " is shutdown successfully, cleaning up corresponding resources now."); - } - NetworkGuru guru = _networkGurus.get(network.getGuruName()); - NetworkProfile profile = convertNetworkToNetworkProfile(network.getId()); - guru.shutdown(profile, _networkOfferingDao.findById(network.getNetworkOfferingId())); - - applyProfileToNetwork(network, profile); - - network.setState(Network.State.Allocated); - _networksDao.update(network.getId(), network); - _networksDao.clearCheckForGc(networkId); - - } else { - network.setState(Network.State.Implemented); - _networksDao.update(network.getId(), network); - } - txn.commit(); + return success; } @Override @@ -2479,33 +2491,32 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag ReservationContext context = new ReservationContextImpl(null, null, callerUser, callerAccount); s_logger.debug("Shutting down the network id=" + networkId + " as a part of network restart"); - shutdownNetwork(networkId, context, cleanup); - - //check that the network was shutdown properly - network = _networksDao.findById(networkId); - if (network.getState() != Network.State.Allocated && network.getState() != Network.State.Setup) { - s_logger.debug("Failed to shutdown the network as a part of network restart: " + network.getState()); + if (!shutdownNetworkElementsAndResources(context, cleanup, network)) { + s_logger.debug("Failed to shutdown the network elements and resources as a part of network restart: " + network.getState()); return false; } + //Only after network was shutdown properly, change the network offering if (newNetworkOfferingId != null) { s_logger.debug("Updating network " + network + " with the new network offering id=" + newNetworkOfferingId + " as a part of network restart"); network.setNetworkOfferingId(newNetworkOfferingId); _networksDao.update(networkId, network); } - //implement the network again + //implement the network elements and rules again DeployDestination dest = new DeployDestination(_dcDao.findById(network.getDataCenterId()), null, null, null); - s_logger.debug("Implementing the network " + network + " as a part of network restart"); - Pair implemented = implementNetwork(networkId, dest, context); + s_logger.debug("Implementing the network " + network + " elements and resources as a part of network restart"); + NetworkOfferingVO offering = _networkOfferingDao.findById(network.getNetworkOfferingId()); - if (implemented.first() == null) { - s_logger.warn("Failed to implement the network " + network + " as a part of network restart"); + try { + implementNetworkElementsAndResources(dest, context, network, offering); + } catch (Exception ex) { + s_logger.warn("Failed to implement network " + network + " elements and resources as a part of network restart due to ", ex); return false; - } else { - return true; } + + return true; } diff --git a/server/src/com/cloud/network/PhysicalNetworkExternalDeviceVO.java b/server/src/com/cloud/network/PhysicalNetworkExternalDeviceVO.java index 1c1ba51f077..8d9ca116dad 100644 --- a/server/src/com/cloud/network/PhysicalNetworkExternalDeviceVO.java +++ b/server/src/com/cloud/network/PhysicalNetworkExternalDeviceVO.java @@ -49,6 +49,9 @@ public class PhysicalNetworkExternalDeviceVO { this.networkServiceProviderId = networkServiceProviderId; this.hostId = hostId; } + + protected PhysicalNetworkExternalDeviceVO(){ + } public long getId() { return id; From b369e45c78f59174ff973df7ffb182ee642be35b Mon Sep 17 00:00:00 2001 From: Sheng Yang Date: Thu, 27 Oct 2011 11:39:20 -0700 Subject: [PATCH 037/159] NaaS: Remove some configure items for virtual router DHCP range, domain name, etc. are the property of network, not virtual router specific. The focus of virtual router configuration would on separate enable/disable each service it provided. --- .../api/commands/ConfigureDhcpElementCmd.java | 42 --------- ...igureRedundantVirtualRouterElementCmd.java | 50 ---------- .../ConfigureVirtualRouterElementCmd.java | 49 ---------- .../network/element/DhcpElementService.java | 1 + .../cloud/network/element/DhcpElement.java | 28 +++--- .../RedundantVirtualRouterElement.java | 22 +---- .../network/element/VirtualRouterElement.java | 28 +----- .../element/VirtualRouterElementsVO.java | 92 +------------------ setup/db/create-schema.sql | 11 +-- 9 files changed, 20 insertions(+), 303 deletions(-) diff --git a/api/src/com/cloud/api/commands/ConfigureDhcpElementCmd.java b/api/src/com/cloud/api/commands/ConfigureDhcpElementCmd.java index e0bb937553d..fcb21147611 100644 --- a/api/src/com/cloud/api/commands/ConfigureDhcpElementCmd.java +++ b/api/src/com/cloud/api/commands/ConfigureDhcpElementCmd.java @@ -61,24 +61,6 @@ public class ConfigureDhcpElementCmd extends BaseAsyncCmd { @Parameter(name=ApiConstants.USERDATA_SERVICE, type=CommandType.BOOLEAN, required=true, description="true is user data service would be enabled") private Boolean userdataService; - @Parameter(name=ApiConstants.DHCP_RANGE, type=CommandType.STRING, description="the dhcp range for the DHCP service ") - private String dhcpRange; - - @Parameter(name=ApiConstants.DNS1, type=CommandType.STRING, description="the first DNS") - private String dns1; - - @Parameter(name=ApiConstants.DNS2, type=CommandType.STRING, description="the second DNS") - private String dns2; - - @Parameter(name=ApiConstants.INTERNAL_DNS1, type=CommandType.STRING, description="the first internal DNS") - private String internalDns1; - - @Parameter(name=ApiConstants.INTERNAL_DNS2, type=CommandType.STRING, description="the second internal DNS") - private String internalDns2; - - @Parameter(name=ApiConstants.DOMAIN, type=CommandType.STRING, description="the gateway ip") - private String domainName; - ///////////////////////////////////////////////////// /////////////////// Accessors /////////////////////// ///////////////////////////////////////////////////// @@ -99,30 +81,6 @@ public class ConfigureDhcpElementCmd extends BaseAsyncCmd { return userdataService; } - public String getDomainName() { - return domainName; - } - - public String getDhcpRange() { - return dhcpRange; - } - - public String getDns1() { - return dns1; - } - - public String getDns2() { - return dns2; - } - - public String getInternalDns1() { - return internalDns1; - } - - public String getInternalDns2() { - return internalDns2; - } - ///////////////////////////////////////////////////// /////////////// API Implementation/////////////////// ///////////////////////////////////////////////////// diff --git a/api/src/com/cloud/api/commands/ConfigureRedundantVirtualRouterElementCmd.java b/api/src/com/cloud/api/commands/ConfigureRedundantVirtualRouterElementCmd.java index 405cb7c113b..07746ac4c75 100644 --- a/api/src/com/cloud/api/commands/ConfigureRedundantVirtualRouterElementCmd.java +++ b/api/src/com/cloud/api/commands/ConfigureRedundantVirtualRouterElementCmd.java @@ -76,27 +76,6 @@ public class ConfigureRedundantVirtualRouterElementCmd extends BaseAsyncCmd { @Parameter(name=ApiConstants.VPN_SERVICE, type=CommandType.BOOLEAN, required=true, description="true is vpn service would be enabled") private Boolean vpnService; - @Parameter(name=ApiConstants.DHCP_RANGE, type=CommandType.STRING, description="the dhcp range for the DHCP service ") - private String dhcpRange; - - @Parameter(name=ApiConstants.DNS1, type=CommandType.STRING, description="the first DNS") - private String dns1; - - @Parameter(name=ApiConstants.DNS2, type=CommandType.STRING, description="the second DNS") - private String dns2; - - @Parameter(name=ApiConstants.INTERNAL_DNS1, type=CommandType.STRING, description="the first internal DNS") - private String internalDns1; - - @Parameter(name=ApiConstants.INTERNAL_DNS2, type=CommandType.STRING, description="the second internal DNS") - private String internalDns2; - - @Parameter(name=ApiConstants.GATEWAY, type=CommandType.STRING, description="the gateway ip") - private String gateway; - - @Parameter(name=ApiConstants.DOMAIN, type=CommandType.STRING, description="the gateway ip") - private String domainName; - /////////////////// Accessors /////////////////////// ///////////////////////////////////////////////////// @@ -136,35 +115,6 @@ public class ConfigureRedundantVirtualRouterElementCmd extends BaseAsyncCmd { return vpnService; } - public String getDomainName() { - return domainName; - } - - public String getDhcpRange() { - return dhcpRange; - } - - public String getDns1() { - return dns1; - } - - public String getDns2() { - return dns2; - } - - public String getInternalDns1() { - return internalDns1; - } - - public String getInternalDns2() { - return internalDns2; - } - - public String getGateway() { - return gateway; - } - - ///////////////////////////////////////////////////// /////////////// API Implementation/////////////////// ///////////////////////////////////////////////////// diff --git a/api/src/com/cloud/api/commands/ConfigureVirtualRouterElementCmd.java b/api/src/com/cloud/api/commands/ConfigureVirtualRouterElementCmd.java index af8e3297417..fc93a681ea9 100644 --- a/api/src/com/cloud/api/commands/ConfigureVirtualRouterElementCmd.java +++ b/api/src/com/cloud/api/commands/ConfigureVirtualRouterElementCmd.java @@ -76,27 +76,6 @@ public class ConfigureVirtualRouterElementCmd extends BaseAsyncCmd { @Parameter(name=ApiConstants.VPN_SERVICE, type=CommandType.BOOLEAN, required=true, description="true is vpn service would be enabled") private Boolean vpnService; - @Parameter(name=ApiConstants.DHCP_RANGE, type=CommandType.STRING, description="the dhcp range for the DHCP service ") - private String dhcpRange; - - @Parameter(name=ApiConstants.DNS1, type=CommandType.STRING, description="the first DNS") - private String dns1; - - @Parameter(name=ApiConstants.DNS2, type=CommandType.STRING, description="the second DNS") - private String dns2; - - @Parameter(name=ApiConstants.INTERNAL_DNS1, type=CommandType.STRING, description="the first internal DNS") - private String internalDns1; - - @Parameter(name=ApiConstants.INTERNAL_DNS2, type=CommandType.STRING, description="the second internal DNS") - private String internalDns2; - - @Parameter(name=ApiConstants.GATEWAY, type=CommandType.STRING, description="the gateway ip") - private String gateway; - - @Parameter(name=ApiConstants.DOMAIN, type=CommandType.STRING, description="the gateway ip") - private String domainName; - ///////////////////////////////////////////////////// /////////////////// Accessors /////////////////////// ///////////////////////////////////////////////////// @@ -137,34 +116,6 @@ public class ConfigureVirtualRouterElementCmd extends BaseAsyncCmd { return vpnService; } - public String getDomainName() { - return domainName; - } - - public String getDhcpRange() { - return dhcpRange; - } - - public String getDns1() { - return dns1; - } - - public String getDns2() { - return dns2; - } - - public String getInternalDns1() { - return internalDns1; - } - - public String getInternalDns2() { - return internalDns2; - } - - public String getGateway() { - return gateway; - } - ///////////////////////////////////////////////////// /////////////// API Implementation/////////////////// ///////////////////////////////////////////////////// diff --git a/api/src/com/cloud/network/element/DhcpElementService.java b/api/src/com/cloud/network/element/DhcpElementService.java index 4871130feef..f7a8ab18d19 100644 --- a/api/src/com/cloud/network/element/DhcpElementService.java +++ b/api/src/com/cloud/network/element/DhcpElementService.java @@ -7,4 +7,5 @@ public interface DhcpElementService extends PluggableService{ boolean configure(ConfigureDhcpElementCmd cmd); boolean addElement(Long nspId, String uuid); Long getIdByUUID(String uuid); + boolean isReady(String uuid); } diff --git a/server/src/com/cloud/network/element/DhcpElement.java b/server/src/com/cloud/network/element/DhcpElement.java index 8ea35b98080..4ab7aaa10ae 100644 --- a/server/src/com/cloud/network/element/DhcpElement.java +++ b/server/src/com/cloud/network/element/DhcpElement.java @@ -220,23 +220,8 @@ public class DhcpElement extends AdapterBase implements DhcpElementService, Pass s_logger.trace("Can't find element with UUID " + cmd.getUUID()); return false; } - if (cmd.getDhcpService() && cmd.getDhcpRange() == null) { - s_logger.trace("DHCP service is provided, but no specific DHCP range!"); - return false; - } - if (cmd.getDnsService() && (cmd.getDns1() == null || cmd.getDomainName() == null)) { - s_logger.trace("DNS service is provided, but no domain name or dns server!"); - return false; - } element.setIsDhcpProvided(cmd.getDhcpService()); - element.setDhcpRange(cmd.getDhcpRange()); - element.setIsDnsProvided(cmd.getDnsService()); - element.setDefaultDomainName(cmd.getDomainName()); - element.setDns1(cmd.getDns1()); - element.setDns2(cmd.getDns2()); - element.setInternalDns1(cmd.getInternalDns1()); - element.setInternalDns2(cmd.getInternalDns2()); element.setIsGatewayProvided(false); element.setIsFirewallProvided(false); @@ -244,6 +229,8 @@ public class DhcpElement extends AdapterBase implements DhcpElementService, Pass element.setIsSourceNatProvided(false); element.setIsVpnProvided(false); + element.setIsReady(true); + _vrElementsDao.persist(element); return true; @@ -255,7 +242,7 @@ public class DhcpElement extends AdapterBase implements DhcpElementService, Pass if (serviceOfferingId == 0) { return false; } - VirtualRouterElementsVO element = new VirtualRouterElementsVO(nspId, uuid, serviceOfferingId, false, VirtualRouterElementsType.DhcpElement, + VirtualRouterElementsVO element = new VirtualRouterElementsVO(nspId, uuid, VirtualRouterElementsType.DhcpElement, false, false, false, false, false, false, false); _vrElementsDao.persist(element); return true; @@ -269,4 +256,13 @@ public class DhcpElement extends AdapterBase implements DhcpElementService, Pass } return element.getId(); } + + @Override + public boolean isReady(String uuid) { + VirtualRouterElementsVO element = _vrElementsDao.findByUUID(uuid); + if (element == null) { + return false; + } + return element.getIsReady(); + } } diff --git a/server/src/com/cloud/network/element/RedundantVirtualRouterElement.java b/server/src/com/cloud/network/element/RedundantVirtualRouterElement.java index 65b63058c48..2d469fdc859 100644 --- a/server/src/com/cloud/network/element/RedundantVirtualRouterElement.java +++ b/server/src/com/cloud/network/element/RedundantVirtualRouterElement.java @@ -97,31 +97,21 @@ public class RedundantVirtualRouterElement extends VirtualRouterElement implemen s_logger.trace("Can't find element with UUID " + cmd.getUUID()); return false; } - if (cmd.getDhcpService() && cmd.getDhcpRange() == null) { + if (cmd.getDhcpService() == null) { s_logger.trace("DHCP service is provided, but no specific DHCP range!"); return false; } - if (cmd.getDnsService() && (cmd.getDns1() == null || cmd.getDomainName() == null)) { + if (cmd.getDnsService() == null) { s_logger.trace("DNS service is provided, but no domain name or dns server!"); return false; } - if (cmd.getGatewayService() && cmd.getGateway() == null) { + if (cmd.getGatewayService() == null) { s_logger.trace("Gateway service is provided, but no gateway IP specific!"); return false; } element.setIsDhcpProvided(cmd.getDhcpService()); - element.setDhcpRange(cmd.getDhcpRange()); - element.setIsDnsProvided(cmd.getDnsService()); - element.setDefaultDomainName(cmd.getDomainName()); - element.setDns1(cmd.getDns1()); - element.setDns2(cmd.getDns2()); - element.setInternalDns1(cmd.getInternalDns1()); - element.setInternalDns2(cmd.getInternalDns2()); - element.setIsGatewayProvided(cmd.getGatewayService()); - element.setGatewayIp(cmd.getGateway()); - element.setIsFirewallProvided(cmd.getFirewallService()); element.setIsLoadBalanceProvided(cmd.getLbService()); element.setIsSourceNatProvided(cmd.getSourceNatService()); @@ -135,11 +125,7 @@ public class RedundantVirtualRouterElement extends VirtualRouterElement implemen @Override public boolean addElement(Long nspId, String uuid) { - long serviceOfferingId = _routerMgr.getDefaultVirtualRouterServiceOfferingId(); - if (serviceOfferingId == 0) { - return false; - } - VirtualRouterElementsVO element = new VirtualRouterElementsVO(nspId, uuid, serviceOfferingId, false, VirtualRouterElementsType.RedundantVirtualRouterElement, + VirtualRouterElementsVO element = new VirtualRouterElementsVO(nspId, uuid, VirtualRouterElementsType.RedundantVirtualRouterElement, false, false, false, false, false, false, false); _vrElementsDao.persist(element); return true; diff --git a/server/src/com/cloud/network/element/VirtualRouterElement.java b/server/src/com/cloud/network/element/VirtualRouterElement.java index f1cfbaa6566..5bbcffd8745 100644 --- a/server/src/com/cloud/network/element/VirtualRouterElement.java +++ b/server/src/com/cloud/network/element/VirtualRouterElement.java @@ -382,31 +382,9 @@ public class VirtualRouterElement extends DhcpElement implements VirtualRouterEl s_logger.trace("Can't find element with UUID " + cmd.getUUID()); return false; } - if (cmd.getDhcpService() && cmd.getDhcpRange() == null) { - s_logger.trace("DHCP service is provided, but no specific DHCP range!"); - return false; - } - if (cmd.getDnsService() && (cmd.getDns1() == null || cmd.getDomainName() == null)) { - s_logger.trace("DNS service is provided, but no domain name or dns server!"); - return false; - } - if (cmd.getGatewayService() && cmd.getGateway() == null) { - s_logger.trace("Gateway service is provided, but no gateway IP specific!"); - return false; - } element.setIsDhcpProvided(cmd.getDhcpService()); - element.setDhcpRange(cmd.getDhcpRange()); - element.setIsDnsProvided(cmd.getDnsService()); - element.setDefaultDomainName(cmd.getDomainName()); - element.setDns1(cmd.getDns1()); - element.setDns2(cmd.getDns2()); - element.setInternalDns1(cmd.getInternalDns1()); - element.setInternalDns2(cmd.getInternalDns2()); - element.setIsGatewayProvided(cmd.getGatewayService()); - element.setGatewayIp(cmd.getGateway()); - element.setIsFirewallProvided(cmd.getFirewallService()); element.setIsLoadBalanceProvided(cmd.getLbService()); element.setIsSourceNatProvided(cmd.getSourceNatService()); @@ -420,11 +398,7 @@ public class VirtualRouterElement extends DhcpElement implements VirtualRouterEl @Override public boolean addElement(Long nspId, String uuid) { - long serviceOfferingId = _routerMgr.getDefaultVirtualRouterServiceOfferingId(); - if (serviceOfferingId == 0) { - return false; - } - VirtualRouterElementsVO element = new VirtualRouterElementsVO(nspId, uuid, serviceOfferingId, false, VirtualRouterElementsType.VirtualRouterElement, + VirtualRouterElementsVO element = new VirtualRouterElementsVO(nspId, uuid, VirtualRouterElementsType.VirtualRouterElement, false, false, false, false, false, false, false); _vrElementsDao.persist(element); return true; diff --git a/server/src/com/cloud/network/element/VirtualRouterElementsVO.java b/server/src/com/cloud/network/element/VirtualRouterElementsVO.java index 1211c385f67..628f142e435 100644 --- a/server/src/com/cloud/network/element/VirtualRouterElementsVO.java +++ b/server/src/com/cloud/network/element/VirtualRouterElementsVO.java @@ -51,9 +51,6 @@ public class VirtualRouterElementsVO implements VirtualRouterElements { @Column(name="uuid") private String uuid; - @Column(name="service_offering_id") - private long serviceOfferingId; - @Column(name="dhcp_provided") private boolean isDhcpProvided; @@ -75,39 +72,16 @@ public class VirtualRouterElementsVO implements VirtualRouterElements { @Column(name="vpn_provided") private boolean isVpnProvided; - @Column(name="dhcp_range") - private String dhcpRange; - - @Column(name="default_domain_name") - private String defaultDomainName; - - @Column(name="dns1") - private String dns1; - - @Column(name="dns2") - private String dns2; - - @Column(name="internal_dns1") - private String internalDns1; - - @Column(name="internal_dns2") - private String internalDns2; - - @Column(name="gateway_ip") - private String gatewayIp; - @Column(name=GenericDao.REMOVED_COLUMN) Date removed; public VirtualRouterElementsVO() { } - public VirtualRouterElementsVO(long nspId, String uuid, long serviceOfferingId, boolean isReady, VirtualRouterElementsType type, boolean isDhcpProvided, boolean isDnsProvided, + public VirtualRouterElementsVO(long nspId, String uuid, VirtualRouterElementsType type, boolean isDhcpProvided, boolean isDnsProvided, boolean isGatewayProvided, boolean isFirewallProvided, boolean isSourceNatProvided, boolean isLoadBalanceProvided, boolean isVpnProvided) { this.nspId = nspId; this.uuid = uuid; - this.serviceOfferingId = serviceOfferingId; - this.isReady = isReady; this.type = type; this.isDhcpProvided = isDhcpProvided; this.isDnsProvided = isDnsProvided; @@ -130,54 +104,6 @@ public class VirtualRouterElementsVO implements VirtualRouterElements { return id; } - public String getDhcpRange() { - return dhcpRange; - } - - public void setDhcpRange(String dhcpRange) { - this.dhcpRange = dhcpRange; - } - - public String getDefaultDomainName() { - return defaultDomainName; - } - - public void setDefaultDomainName(String defaultDomainName) { - this.defaultDomainName = defaultDomainName; - } - - public String getDns1() { - return dns1; - } - - public void setDns1(String dns1) { - this.dns1 = dns1; - } - - public String getDns2() { - return dns2; - } - - public void setDns2(String dns2) { - this.dns2 = dns2; - } - - public String getInternalDns1() { - return internalDns1; - } - - public void setInternalDns1(String internalDns1) { - this.internalDns1 = internalDns1; - } - - public String getInternalDns2() { - return internalDns2; - } - - public void setInternalDns2(String internalDns2) { - this.internalDns2 = internalDns2; - } - public boolean getIsDhcpProvided() { return isDhcpProvided; } @@ -239,14 +165,6 @@ public class VirtualRouterElementsVO implements VirtualRouterElements { return this.type; } - public String getGatewayIp() { - return gatewayIp; - } - - public void setGatewayIp(String gatewayIp) { - this.gatewayIp = gatewayIp; - } - public Date getRemoved() { return removed; } @@ -263,14 +181,6 @@ public class VirtualRouterElementsVO implements VirtualRouterElements { return isReady; } - public void setServiceOfferingId(long serviceOfferingId) { - this.serviceOfferingId = serviceOfferingId; - } - - public long getServiceOfferingId() { - return serviceOfferingId; - } - public void setId(long id) { this.id = id; } diff --git a/setup/db/create-schema.sql b/setup/db/create-schema.sql index 8fd53cba5f9..a73eb83ecf7 100755 --- a/setup/db/create-schema.sql +++ b/setup/db/create-schema.sql @@ -1738,17 +1738,8 @@ CREATE TABLE `cloud`.`virtual_router_elements` ( `source_nat_provided` int(1) NOT NULL, `load_balance_provided` int(1) NOT NULL, `vpn_provided` int(1) NOT NULL, - `service_offering_id` bigint unsigned NOT NULL, - `dhcp_range` varchar(255), - `default_domain_name` varchar(255), - `dns1` varchar(255), - `dns2` varchar(255), - `internal_dns1` varchar(255), - `internal_dns2` varchar(255), - `gateway_ip` varchar(255), `removed` datetime COMMENT 'date removed if not null', - PRIMARY KEY (`id`), - CONSTRAINT `fk_virtual_router_elements__service_offering_id` FOREIGN KEY `fk_virtual_router_elements__service_offering_id` (`service_offering_id`) REFERENCES `service_offering`(`id`) + PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8; From e1e96c0bb3f20cd1d5c4d260ff49929a5f2dae8e Mon Sep 17 00:00:00 2001 From: Sheng Yang Date: Thu, 27 Oct 2011 11:39:21 -0700 Subject: [PATCH 038/159] NaaS: Add ServiceProviders Added PortForwardingServiceProvider, StaticNatServiceProvider, rename PasswordServiceProvider to UserDataServiceProvider(may rename to a better name later). Add related function for service providers. --- .../element/FirewallServiceProvider.java | 2 +- .../element/LoadBalancingServiceProvider.java | 4 +- .../PortForwardingServiceProvider.java | 18 +++++ ...der.java => SourceNatServiceProvider.java} | 2 +- ...der.java => StaticNatServiceProvider.java} | 2 +- ...ider.java => UserDataServiceProvider.java} | 2 +- .../src/com/cloud/network/NetworkManager.java | 4 +- .../com/cloud/network/NetworkManagerImpl.java | 66 +++++++++++-------- .../cloud/network/element/DhcpElement.java | 2 +- .../element/ElasticLoadBalancerElement.java | 3 +- .../F5ExternalLoadBalancerElement.java | 3 +- .../JuniperSRXExternalFirewallElement.java | 14 +++- .../NetscalerExternalLoadBalancerElement.java | 3 +- .../network/element/VirtualRouterElement.java | 44 ++++++++++++- .../src/com/cloud/vm/UserVmManagerImpl.java | 6 +- 15 files changed, 130 insertions(+), 45 deletions(-) create mode 100644 api/src/com/cloud/network/element/PortForwardingServiceProvider.java rename api/src/com/cloud/network/element/{SourceNATServiceProvider.java => SourceNatServiceProvider.java} (88%) rename api/src/com/cloud/network/element/{StaticNATServiceProvider.java => StaticNatServiceProvider.java} (88%) rename api/src/com/cloud/network/element/{PasswordServiceProvider.java => UserDataServiceProvider.java} (85%) diff --git a/api/src/com/cloud/network/element/FirewallServiceProvider.java b/api/src/com/cloud/network/element/FirewallServiceProvider.java index 51818c5bdbb..6f65a0a6928 100644 --- a/api/src/com/cloud/network/element/FirewallServiceProvider.java +++ b/api/src/com/cloud/network/element/FirewallServiceProvider.java @@ -14,5 +14,5 @@ public interface FirewallServiceProvider extends NetworkElement { * @return * @throws ResourceUnavailableException */ - boolean applyRules(Network network, List rules) throws ResourceUnavailableException; + boolean applyFWRules(Network network, List rules) throws ResourceUnavailableException; } diff --git a/api/src/com/cloud/network/element/LoadBalancingServiceProvider.java b/api/src/com/cloud/network/element/LoadBalancingServiceProvider.java index 5bc81d39895..32b9b4776e9 100644 --- a/api/src/com/cloud/network/element/LoadBalancingServiceProvider.java +++ b/api/src/com/cloud/network/element/LoadBalancingServiceProvider.java @@ -4,7 +4,7 @@ import java.util.List; import com.cloud.exception.ResourceUnavailableException; import com.cloud.network.Network; -import com.cloud.network.rules.FirewallRule; +import com.cloud.network.lb.LoadBalancingRule; public interface LoadBalancingServiceProvider extends NetworkElement { /** @@ -14,5 +14,5 @@ public interface LoadBalancingServiceProvider extends NetworkElement { * @return * @throws ResourceUnavailableException */ - boolean applyRules(Network network, List rules) throws ResourceUnavailableException; + boolean applyLBRules(Network network, List rules) throws ResourceUnavailableException; } diff --git a/api/src/com/cloud/network/element/PortForwardingServiceProvider.java b/api/src/com/cloud/network/element/PortForwardingServiceProvider.java new file mode 100644 index 00000000000..bdd6bc01da4 --- /dev/null +++ b/api/src/com/cloud/network/element/PortForwardingServiceProvider.java @@ -0,0 +1,18 @@ +package com.cloud.network.element; + +import java.util.List; + +import com.cloud.exception.ResourceUnavailableException; +import com.cloud.network.Network; +import com.cloud.network.rules.PortForwardingRule; + +public interface PortForwardingServiceProvider extends NetworkElement { + /** + * Apply rules + * @param network + * @param rules + * @return + * @throws ResourceUnavailableException + */ + boolean applyPFRules(Network network, List rules) throws ResourceUnavailableException; +} diff --git a/api/src/com/cloud/network/element/SourceNATServiceProvider.java b/api/src/com/cloud/network/element/SourceNatServiceProvider.java similarity index 88% rename from api/src/com/cloud/network/element/SourceNATServiceProvider.java rename to api/src/com/cloud/network/element/SourceNatServiceProvider.java index 1f395953d0b..707937fb234 100644 --- a/api/src/com/cloud/network/element/SourceNATServiceProvider.java +++ b/api/src/com/cloud/network/element/SourceNatServiceProvider.java @@ -6,7 +6,7 @@ import com.cloud.exception.ResourceUnavailableException; import com.cloud.network.Network; import com.cloud.network.PublicIpAddress; -public interface SourceNATServiceProvider extends NetworkElement { +public interface SourceNatServiceProvider extends NetworkElement { /** * Apply ip addresses to this network * @param network diff --git a/api/src/com/cloud/network/element/StaticNATServiceProvider.java b/api/src/com/cloud/network/element/StaticNatServiceProvider.java similarity index 88% rename from api/src/com/cloud/network/element/StaticNATServiceProvider.java rename to api/src/com/cloud/network/element/StaticNatServiceProvider.java index a134be39d91..c73ce2b77c5 100644 --- a/api/src/com/cloud/network/element/StaticNATServiceProvider.java +++ b/api/src/com/cloud/network/element/StaticNatServiceProvider.java @@ -6,7 +6,7 @@ import com.cloud.exception.ResourceUnavailableException; import com.cloud.network.Network; import com.cloud.network.rules.StaticNat; -public interface StaticNATServiceProvider extends NetworkElement { +public interface StaticNatServiceProvider extends NetworkElement { /** * Creates static nat rule (public IP to private IP mapping) on the network element * @param config diff --git a/api/src/com/cloud/network/element/PasswordServiceProvider.java b/api/src/com/cloud/network/element/UserDataServiceProvider.java similarity index 85% rename from api/src/com/cloud/network/element/PasswordServiceProvider.java rename to api/src/com/cloud/network/element/UserDataServiceProvider.java index f933aa9202f..179cd8fa2f8 100644 --- a/api/src/com/cloud/network/element/PasswordServiceProvider.java +++ b/api/src/com/cloud/network/element/UserDataServiceProvider.java @@ -6,6 +6,6 @@ import com.cloud.vm.NicProfile; import com.cloud.vm.VirtualMachine; import com.cloud.vm.VirtualMachineProfile; -public interface PasswordServiceProvider extends NetworkElement { +public interface UserDataServiceProvider extends NetworkElement { boolean savePassword(Network network, NicProfile nic, VirtualMachineProfile vm) throws ResourceUnavailableException; } diff --git a/server/src/com/cloud/network/NetworkManager.java b/server/src/com/cloud/network/NetworkManager.java index 99dd28c75de..fc0e50b83d3 100644 --- a/server/src/com/cloud/network/NetworkManager.java +++ b/server/src/com/cloud/network/NetworkManager.java @@ -33,7 +33,7 @@ import com.cloud.network.Network.Provider; import com.cloud.network.Network.Service; import com.cloud.network.Networks.TrafficType; import com.cloud.network.addr.PublicIp; -import com.cloud.network.element.PasswordServiceProvider; +import com.cloud.network.element.UserDataServiceProvider; import com.cloud.network.element.RemoteAccessVPNServiceProvider; import com.cloud.network.guru.NetworkGuru; import com.cloud.network.rules.FirewallRule; @@ -182,7 +182,7 @@ public interface NetworkManager extends NetworkService { Nic getDefaultNic(long vmId); - List getPasswordResetElements(); + List getPasswordResetElements(); @Deprecated boolean zoneIsConfiguredForExternalNetworking(long zoneId); diff --git a/server/src/com/cloud/network/NetworkManagerImpl.java b/server/src/com/cloud/network/NetworkManagerImpl.java index bad8ae2010c..a5fa4245b30 100755 --- a/server/src/com/cloud/network/NetworkManagerImpl.java +++ b/server/src/com/cloud/network/NetworkManagerImpl.java @@ -106,10 +106,11 @@ import com.cloud.network.dao.PhysicalNetworkServiceProviderVO; import com.cloud.network.element.FirewallServiceProvider; import com.cloud.network.element.LoadBalancingServiceProvider; import com.cloud.network.element.NetworkElement; -import com.cloud.network.element.PasswordServiceProvider; +import com.cloud.network.element.PortForwardingServiceProvider; +import com.cloud.network.element.StaticNatServiceProvider; +import com.cloud.network.element.UserDataServiceProvider; import com.cloud.network.element.RemoteAccessVPNServiceProvider; -import com.cloud.network.element.SourceNATServiceProvider; -import com.cloud.network.element.StaticNATServiceProvider; +import com.cloud.network.element.SourceNatServiceProvider; import com.cloud.network.guru.NetworkGuru; import com.cloud.network.lb.LoadBalancingRule; import com.cloud.network.lb.LoadBalancingRule.LbDestination; @@ -119,6 +120,7 @@ import com.cloud.network.rules.FirewallRule; import com.cloud.network.rules.FirewallRule.Purpose; import com.cloud.network.rules.FirewallRuleVO; import com.cloud.network.rules.PortForwardingRuleVO; +import com.cloud.network.rules.PortForwardingRule; import com.cloud.network.rules.RulesManager; import com.cloud.network.rules.StaticNat; import com.cloud.network.rules.StaticNatRule; @@ -550,10 +552,10 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag int found = 0; for (NetworkElement element : _networkElements) { try { - if (!(element instanceof SourceNATServiceProvider)) { + if (!(element instanceof SourceNatServiceProvider)) { continue; } - SourceNATServiceProvider e = (SourceNATServiceProvider)element; + SourceNatServiceProvider e = (SourceNatServiceProvider)element; found ++; s_logger.trace("Asking " + element + " to apply ip associations"); e.applyIps(network, publicIps); @@ -2336,6 +2338,7 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag } @Override + /* The rules here is only the same kind of rule, e.g. all load balancing rules or all port forwarding rules */ public boolean applyRules(List rules, boolean continueOnError) throws ResourceUnavailableException { if (rules == null || rules.size() == 0) { s_logger.debug("There are no rules to forward to the network elements"); @@ -2344,22 +2347,36 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag boolean success = true; Network network = _networksDao.findById(rules.get(0).getNetworkId()); - int found = 0; + Purpose purpose = rules.get(0).getPurpose(); for (NetworkElement ne : _networkElements) { try { - if (!(ne instanceof FirewallServiceProvider) && !(ne instanceof LoadBalancingServiceProvider)) { - continue; - } - found ++; boolean handled; - if (ne instanceof FirewallServiceProvider) { - FirewallServiceProvider e = (FirewallServiceProvider)ne; - handled = e.applyRules(network, rules); - } else { - LoadBalancingServiceProvider e = (LoadBalancingServiceProvider) ne; - handled = e.applyRules(network, rules); + switch (purpose) { + case LoadBalancing: + if (!(ne instanceof LoadBalancingServiceProvider)) { + continue; + } + handled = ((LoadBalancingServiceProvider)ne).applyLBRules(network, (List)rules); + break; + case PortForwarding: + if (!(ne instanceof PortForwardingServiceProvider)) { + continue; + } + handled = ((PortForwardingServiceProvider)ne).applyPFRules(network, (List)rules); + break; + case StaticNat: + /* It's firewall rule for static nat, not static nat rule */ + /* Fall through */ + case Firewall: + if (!(ne instanceof FirewallServiceProvider)) { + continue; + } + handled = ((FirewallServiceProvider)ne).applyFWRules(network, rules); + break; + default: + s_logger.debug("Unable to handle network rules for purpose: " + purpose.toString()); + handled = false; } - s_logger.debug("Network Rules for network " + network.getId() + " were " + (handled ? "" : " not") + " handled by " + ne.getName()); } catch (ResourceUnavailableException e) { if (!continueOnError) { @@ -2857,11 +2874,11 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag } @Override - public List getPasswordResetElements() { - List elements = new ArrayList(); + public List getPasswordResetElements() { + List elements = new ArrayList(); for (NetworkElement element : _networkElements) { - if (element instanceof PasswordServiceProvider) { - PasswordServiceProvider e = (PasswordServiceProvider)element; + if (element instanceof UserDataServiceProvider) { + UserDataServiceProvider e = (UserDataServiceProvider)element; elements.add(e); } } @@ -3329,15 +3346,12 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag boolean success = true; Network network = _networksDao.findById(staticNats.get(0).getNetworkId()); - int found = 0; for (NetworkElement ne : _networkElements) { try { - if (!(ne instanceof StaticNATServiceProvider)) { + if (!(ne instanceof StaticNatServiceProvider)) { continue; } - StaticNATServiceProvider e = (StaticNATServiceProvider)ne; - found ++; - boolean handled = e.applyStaticNats(network, staticNats); + boolean handled = ((StaticNatServiceProvider)ne).applyStaticNats(network, staticNats); s_logger.debug("Static Nat for network " + network.getId() + " were " + (handled ? "" : " not") + " handled by " + ne.getName()); } catch (ResourceUnavailableException e) { if (!continueOnError) { diff --git a/server/src/com/cloud/network/element/DhcpElement.java b/server/src/com/cloud/network/element/DhcpElement.java index 4ab7aaa10ae..cdb64ffd4ef 100644 --- a/server/src/com/cloud/network/element/DhcpElement.java +++ b/server/src/com/cloud/network/element/DhcpElement.java @@ -68,7 +68,7 @@ import com.cloud.vm.dao.UserVmDao; @Local(value=NetworkElement.class) -public class DhcpElement extends AdapterBase implements DhcpElementService, PasswordServiceProvider { +public class DhcpElement extends AdapterBase implements DhcpElementService, UserDataServiceProvider { private static final Logger s_logger = Logger.getLogger(DhcpElement.class); private static final Map> capabilities = setCapabilities(); diff --git a/server/src/com/cloud/network/element/ElasticLoadBalancerElement.java b/server/src/com/cloud/network/element/ElasticLoadBalancerElement.java index 212e346b33d..e5bf52c0bc0 100644 --- a/server/src/com/cloud/network/element/ElasticLoadBalancerElement.java +++ b/server/src/com/cloud/network/element/ElasticLoadBalancerElement.java @@ -40,6 +40,7 @@ import com.cloud.network.NetworkManager; import com.cloud.network.Networks.TrafficType; import com.cloud.network.dao.NetworkDao; import com.cloud.network.lb.ElasticLoadBalancerManager; +import com.cloud.network.lb.LoadBalancingRule; import com.cloud.network.rules.FirewallRule; import com.cloud.offering.NetworkOffering; import com.cloud.offerings.dao.NetworkOfferingDao; @@ -128,7 +129,7 @@ public class ElasticLoadBalancerElement extends AdapterBase implements LoadBalan } @Override - public boolean applyRules(Network network, List rules) throws ResourceUnavailableException { + public boolean applyLBRules(Network network, List rules) throws ResourceUnavailableException { if (!canHandle(network)) { return false; } diff --git a/server/src/com/cloud/network/element/F5ExternalLoadBalancerElement.java b/server/src/com/cloud/network/element/F5ExternalLoadBalancerElement.java index db8339306f9..7b52c7e8898 100644 --- a/server/src/com/cloud/network/element/F5ExternalLoadBalancerElement.java +++ b/server/src/com/cloud/network/element/F5ExternalLoadBalancerElement.java @@ -41,6 +41,7 @@ import com.cloud.network.Network.Provider; import com.cloud.network.Network.Service; import com.cloud.network.NetworkManager; import com.cloud.network.Networks.TrafficType; +import com.cloud.network.lb.LoadBalancingRule; import com.cloud.network.rules.FirewallRule; import com.cloud.offering.NetworkOffering; import com.cloud.offerings.dao.NetworkOfferingServiceMapDao; @@ -107,7 +108,7 @@ public class F5ExternalLoadBalancerElement extends AdapterBase implements LoadBa } @Override - public boolean applyRules(Network config, List rules) throws ResourceUnavailableException { + public boolean applyLBRules(Network config, List rules) throws ResourceUnavailableException { if (!canHandle(config)) { return false; } diff --git a/server/src/com/cloud/network/element/JuniperSRXExternalFirewallElement.java b/server/src/com/cloud/network/element/JuniperSRXExternalFirewallElement.java index 88530899fe7..7f2a24ccb45 100644 --- a/server/src/com/cloud/network/element/JuniperSRXExternalFirewallElement.java +++ b/server/src/com/cloud/network/element/JuniperSRXExternalFirewallElement.java @@ -47,6 +47,8 @@ import com.cloud.network.RemoteAccessVpn; import com.cloud.network.VpnUser; import com.cloud.network.dao.NetworkDao; import com.cloud.network.rules.FirewallRule; +import com.cloud.network.rules.PortForwardingRule; +import com.cloud.network.rules.StaticNat; import com.cloud.offering.NetworkOffering; import com.cloud.offerings.NetworkOfferingVO; import com.cloud.offerings.dao.NetworkOfferingDao; @@ -58,7 +60,7 @@ import com.cloud.vm.VirtualMachine; import com.cloud.vm.VirtualMachineProfile; @Local(value=NetworkElement.class) -public class JuniperSRXExternalFirewallElement extends AdapterBase implements SourceNATServiceProvider, FirewallServiceProvider, RemoteAccessVPNServiceProvider { +public class JuniperSRXExternalFirewallElement extends AdapterBase implements SourceNatServiceProvider, FirewallServiceProvider, PortForwardingServiceProvider, RemoteAccessVPNServiceProvider { private static final Logger s_logger = Logger.getLogger(JuniperSRXExternalFirewallElement.class); @@ -142,7 +144,7 @@ public class JuniperSRXExternalFirewallElement extends AdapterBase implements So @Override - public boolean applyRules(Network config, List rules) throws ResourceUnavailableException { + public boolean applyFWRules(Network config, List rules) throws ResourceUnavailableException { if (!canHandle(config)) { return false; } @@ -231,6 +233,14 @@ public class JuniperSRXExternalFirewallElement extends AdapterBase implements So return capabilities; } + @Override + public boolean applyPFRules(Network network, List rules) throws ResourceUnavailableException { + if (!canHandle(network)) { + return false; + } + + return _externalNetworkManager.applyFirewallRules(network, rules); + } } diff --git a/server/src/com/cloud/network/element/NetscalerExternalLoadBalancerElement.java b/server/src/com/cloud/network/element/NetscalerExternalLoadBalancerElement.java index 07cb5c082de..51d4aa201b7 100644 --- a/server/src/com/cloud/network/element/NetscalerExternalLoadBalancerElement.java +++ b/server/src/com/cloud/network/element/NetscalerExternalLoadBalancerElement.java @@ -40,6 +40,7 @@ import com.cloud.network.Network.Provider; import com.cloud.network.Network.Service; import com.cloud.network.NetworkManager; import com.cloud.network.Networks.TrafficType; +import com.cloud.network.lb.LoadBalancingRule; import com.cloud.network.rules.FirewallRule; import com.cloud.offering.NetworkOffering; import com.cloud.offerings.dao.NetworkOfferingServiceMapDao; @@ -106,7 +107,7 @@ public class NetscalerExternalLoadBalancerElement extends AdapterBase implements } @Override - public boolean applyRules(Network config, List rules) throws ResourceUnavailableException { + public boolean applyLBRules(Network config, List rules) throws ResourceUnavailableException { if (!canHandle(config)) { return false; } diff --git a/server/src/com/cloud/network/element/VirtualRouterElement.java b/server/src/com/cloud/network/element/VirtualRouterElement.java index 5bbcffd8745..a0c067e6107 100644 --- a/server/src/com/cloud/network/element/VirtualRouterElement.java +++ b/server/src/com/cloud/network/element/VirtualRouterElement.java @@ -47,11 +47,13 @@ import com.cloud.network.dao.LoadBalancerDao; import com.cloud.network.dao.NetworkDao; import com.cloud.network.dao.VirtualRouterElementsDao; import com.cloud.network.element.VirtualRouterElements.VirtualRouterElementsType; +import com.cloud.network.lb.LoadBalancingRule; import com.cloud.network.lb.LoadBalancingRulesManager; import com.cloud.network.router.VirtualNetworkApplianceManager; import com.cloud.network.router.VirtualRouter; import com.cloud.network.router.VirtualRouter.Role; import com.cloud.network.rules.FirewallRule; +import com.cloud.network.rules.PortForwardingRule; import com.cloud.network.rules.RulesManager; import com.cloud.network.rules.StaticNat; import com.cloud.offering.NetworkOffering; @@ -70,7 +72,7 @@ import com.cloud.vm.dao.UserVmDao; @Local(value=NetworkElement.class) -public class VirtualRouterElement extends DhcpElement implements VirtualRouterElementService, SourceNATServiceProvider, FirewallServiceProvider, LoadBalancingServiceProvider, StaticNATServiceProvider, RemoteAccessVPNServiceProvider { +public class VirtualRouterElement extends DhcpElement implements VirtualRouterElementService, SourceNatServiceProvider, StaticNatServiceProvider, FirewallServiceProvider, LoadBalancingServiceProvider, PortForwardingServiceProvider, RemoteAccessVPNServiceProvider { private static final Logger s_logger = Logger.getLogger(VirtualRouterElement.class); private static final Map> capabilities = setCapabilities(); @@ -173,7 +175,7 @@ public class VirtualRouterElement extends DhcpElement implements VirtualRouterEl // } @Override - public boolean applyRules(Network config, List rules) throws ResourceUnavailableException { + public boolean applyFWRules(Network config, List rules) throws ResourceUnavailableException { DataCenter dc = _configMgr.getZone(config.getDataCenterId()); if (canHandle(config.getType(), config.getNetworkOfferingId())) { @@ -193,6 +195,25 @@ public class VirtualRouterElement extends DhcpElement implements VirtualRouterEl } } + @Override + public boolean applyLBRules(Network network, List rules) throws ResourceUnavailableException { + if (canHandle(network.getType(), network.getNetworkOfferingId())) { + List routers = _routerDao.listByNetworkAndRole(network.getId(), Role.DHCP_FIREWALL_LB_PASSWD_USERDATA); + 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.applyFirewallRules(network, rules, routers)){ + throw new CloudRuntimeException("Failed to apply firewall rules in network " + network.getId()); + } else { + return true; + } + } else { + return true; + } + } + @Override public String[] applyVpnUsers(RemoteAccessVpn vpn, List users) throws ResourceUnavailableException{ @@ -403,4 +424,23 @@ public class VirtualRouterElement extends DhcpElement implements VirtualRouterEl _vrElementsDao.persist(element); return true; } + + @Override + public boolean applyPFRules(Network network, List rules) throws ResourceUnavailableException { + if (canHandle(network.getType(), network.getNetworkOfferingId())) { + List routers = _routerDao.listByNetworkAndRole(network.getId(), Role.DHCP_FIREWALL_LB_PASSWD_USERDATA); + 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.applyFirewallRules(network, rules, routers)){ + throw new CloudRuntimeException("Failed to apply firewall rules in network " + network.getId()); + } else { + return true; + } + } else { + return true; + } + } } diff --git a/server/src/com/cloud/vm/UserVmManagerImpl.java b/server/src/com/cloud/vm/UserVmManagerImpl.java index 13da1a6ae10..e75b760df97 100755 --- a/server/src/com/cloud/vm/UserVmManagerImpl.java +++ b/server/src/com/cloud/vm/UserVmManagerImpl.java @@ -128,7 +128,7 @@ import com.cloud.network.dao.IPAddressDao; import com.cloud.network.dao.LoadBalancerDao; import com.cloud.network.dao.LoadBalancerVMMapDao; import com.cloud.network.dao.NetworkDao; -import com.cloud.network.element.PasswordServiceProvider; +import com.cloud.network.element.UserDataServiceProvider; import com.cloud.network.lb.LoadBalancingRulesManager; import com.cloud.network.router.VirtualNetworkApplianceManager; import com.cloud.network.rules.FirewallManager; @@ -428,10 +428,10 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, Manager VirtualMachineProfile vmProfile = new VirtualMachineProfileImpl(vmInstance); vmProfile.setParameter(VirtualMachineProfile.Param.VmPassword, password); - List elements = _networkMgr.getPasswordResetElements(); + List elements = _networkMgr.getPasswordResetElements(); boolean result = true; - for (PasswordServiceProvider element : elements) { + for (UserDataServiceProvider element : elements) { if (!element.savePassword(defaultNetwork, defaultNicProfile, vmProfile)) { result = false; } From bf4e21f315a74871f352ff194adc768bb088c5c2 Mon Sep 17 00:00:00 2001 From: Sheng Yang Date: Thu, 27 Oct 2011 14:22:41 -0700 Subject: [PATCH 039/159] NaaS: Destroy virtual router when cleanup=true at shutdown As we did in the restart() function. --- .../cloud/network/element/VirtualRouterElement.java | 10 +++++++++- 1 file changed, 9 insertions(+), 1 deletion(-) diff --git a/server/src/com/cloud/network/element/VirtualRouterElement.java b/server/src/com/cloud/network/element/VirtualRouterElement.java index a0c067e6107..8bdbea51275 100644 --- a/server/src/com/cloud/network/element/VirtualRouterElement.java +++ b/server/src/com/cloud/network/element/VirtualRouterElement.java @@ -357,8 +357,16 @@ public class VirtualRouterElement extends DhcpElement implements VirtualRouterEl } boolean result = true; for (DomainRouterVO router : routers) { - //FIXME - Sheng, for your redundant router you have to destroy the domR here if clenaup=true - just the way you did in restart() method result = result && _routerMgr.stop(router, false, context.getCaller(), context.getAccount()) != null; + if (cleanup) { + if (!result) { + s_logger.warn("Failed to stop virtual router element " + router + ", but would try to process clean up anyway."); + } + result = (_routerMgr.destroyRouter(router.getId()) != null); + if (!result) { + s_logger.warn("Failed to clean up virtual router element " + router); + } + } } return result; } From 02ada73d89110b45dc95471a85765542b1af2e93 Mon Sep 17 00:00:00 2001 From: Sheng Yang Date: Thu, 27 Oct 2011 16:36:33 -0700 Subject: [PATCH 040/159] NaaS: Make applyIp() as a function of FirewallServiceProvider --- .../network/element/FirewallServiceProvider.java | 10 ++++++++++ .../network/element/SourceNatServiceProvider.java | 14 -------------- .../src/com/cloud/network/NetworkManagerImpl.java | 6 ++---- 3 files changed, 12 insertions(+), 18 deletions(-) diff --git a/api/src/com/cloud/network/element/FirewallServiceProvider.java b/api/src/com/cloud/network/element/FirewallServiceProvider.java index 6f65a0a6928..6600831db77 100644 --- a/api/src/com/cloud/network/element/FirewallServiceProvider.java +++ b/api/src/com/cloud/network/element/FirewallServiceProvider.java @@ -4,6 +4,7 @@ import java.util.List; import com.cloud.exception.ResourceUnavailableException; import com.cloud.network.Network; +import com.cloud.network.PublicIpAddress; import com.cloud.network.rules.FirewallRule; public interface FirewallServiceProvider extends NetworkElement { @@ -15,4 +16,13 @@ public interface FirewallServiceProvider extends NetworkElement { * @throws ResourceUnavailableException */ boolean applyFWRules(Network network, List rules) throws ResourceUnavailableException; + + /** + * Apply ip addresses to this network + * @param network + * @param ipAddress + * @return + * @throws ResourceUnavailableException + */ + boolean applyIps(Network network, List ipAddress) throws ResourceUnavailableException; } diff --git a/api/src/com/cloud/network/element/SourceNatServiceProvider.java b/api/src/com/cloud/network/element/SourceNatServiceProvider.java index 707937fb234..d21e0b660a1 100644 --- a/api/src/com/cloud/network/element/SourceNatServiceProvider.java +++ b/api/src/com/cloud/network/element/SourceNatServiceProvider.java @@ -1,18 +1,4 @@ package com.cloud.network.element; -import java.util.List; - -import com.cloud.exception.ResourceUnavailableException; -import com.cloud.network.Network; -import com.cloud.network.PublicIpAddress; - public interface SourceNatServiceProvider extends NetworkElement { - /** - * Apply ip addresses to this network - * @param network - * @param ipAddress - * @return - * @throws ResourceUnavailableException - */ - boolean applyIps(Network network, List ipAddress) throws ResourceUnavailableException; } diff --git a/server/src/com/cloud/network/NetworkManagerImpl.java b/server/src/com/cloud/network/NetworkManagerImpl.java index a5fa4245b30..e41673b1a75 100755 --- a/server/src/com/cloud/network/NetworkManagerImpl.java +++ b/server/src/com/cloud/network/NetworkManagerImpl.java @@ -549,14 +549,12 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag protected boolean applyIpAssociations(Network network, boolean continueOnError, List publicIps) throws ResourceUnavailableException { boolean success = true; - int found = 0; for (NetworkElement element : _networkElements) { try { - if (!(element instanceof SourceNatServiceProvider)) { + if (!(element instanceof FirewallServiceProvider)) { continue; } - SourceNatServiceProvider e = (SourceNatServiceProvider)element; - found ++; + FirewallServiceProvider e = (FirewallServiceProvider)element; s_logger.trace("Asking " + element + " to apply ip associations"); e.applyIps(network, publicIps); } catch (ResourceUnavailableException e) { From 71b53a343244069ef7162ce4b483f39af17b2eb0 Mon Sep 17 00:00:00 2001 From: alena Date: Thu, 27 Oct 2011 11:20:08 -0700 Subject: [PATCH 041/159] Made isSharedSourceNatService a capability of SoureNatService --- .../com/cloud/offering/NetworkOffering.java | 2 -- .../ExternalNetworkDeviceManagerImpl.java | 30 +++++++++++++++---- .../com/cloud/network/NetworkManagerImpl.java | 24 +++++++++++++-- .../JuniperSRXExternalFirewallElement.java | 11 ++++--- .../network/element/VirtualRouterElement.java | 6 +++- .../cloud/offerings/NetworkOfferingVO.java | 8 ----- 6 files changed, 57 insertions(+), 24 deletions(-) diff --git a/api/src/com/cloud/offering/NetworkOffering.java b/api/src/com/cloud/offering/NetworkOffering.java index 8a5fe3a9195..bd4e02ef1b4 100644 --- a/api/src/com/cloud/offering/NetworkOffering.java +++ b/api/src/com/cloud/offering/NetworkOffering.java @@ -85,8 +85,6 @@ public interface NetworkOffering { boolean isSystemOnly(); Availability getAvailability(); - - boolean isSharedSourceNatService(); String getUniqueName(); diff --git a/server/src/com/cloud/network/ExternalNetworkDeviceManagerImpl.java b/server/src/com/cloud/network/ExternalNetworkDeviceManagerImpl.java index 6496526ec10..0ff220cc9c3 100644 --- a/server/src/com/cloud/network/ExternalNetworkDeviceManagerImpl.java +++ b/server/src/com/cloud/network/ExternalNetworkDeviceManagerImpl.java @@ -61,12 +61,11 @@ import com.cloud.api.commands.ListExternalLoadBalancersCmd; import com.cloud.api.commands.ListNetworkDeviceCmd; import com.cloud.baremetal.ExternalDhcpManager; import com.cloud.baremetal.PxeServerManager; -import com.cloud.baremetal.PxeServerProfile; import com.cloud.baremetal.PxeServerManager.PxeServerType; +import com.cloud.baremetal.PxeServerProfile; import com.cloud.configuration.Config; import com.cloud.configuration.dao.ConfigurationDao; import com.cloud.dc.DataCenter; -import com.cloud.dc.DataCenter.NetworkType; import com.cloud.dc.DataCenterVO; import com.cloud.dc.Vlan; import com.cloud.dc.VlanVO; @@ -77,10 +76,12 @@ import com.cloud.exception.InvalidParameterValueException; import com.cloud.exception.ResourceUnavailableException; import com.cloud.host.DetailVO; import com.cloud.host.Host; -import com.cloud.host.HostVO; import com.cloud.host.Host.Type; +import com.cloud.host.HostVO; import com.cloud.host.dao.HostDao; import com.cloud.host.dao.HostDetailsDao; +import com.cloud.network.Network.Capability; +import com.cloud.network.Network.Service; import com.cloud.network.Networks.TrafficType; import com.cloud.network.dao.IPAddressDao; import com.cloud.network.dao.InlineLoadBalancerNicMapDao; @@ -1047,7 +1048,16 @@ public class ExternalNetworkDeviceManagerImpl implements ExternalNetworkDeviceMa } Account account = _accountDao.findByIdIncludingRemoved(network.getAccountId()); - boolean sharedSourceNat = offering.isSharedSourceNatService(); + + boolean sharedSourceNat = false; + Map sourceNatCapabilities = _networkMgr.getServiceCapabilities(network.getNetworkOfferingId(), Service.SourceNat); + if (sourceNatCapabilities != null) { + String supportedSourceNatTypes = sourceNatCapabilities.get(Capability.SupportedSourceNatTypes).toLowerCase(); + if (supportedSourceNatTypes.contains("zone")) { + sharedSourceNat = true; + } + } + IPAddressVO sourceNatIp = null; if (!sharedSourceNat) { // Get the source NAT IP address for this network @@ -1452,9 +1462,17 @@ public class ExternalNetworkDeviceManagerImpl implements ExternalNetworkDeviceMa for (NetworkVO network : networksForAccount) { String networkErrorMsg = accountErrorMsg + ", network ID = " + network.getId(); - NetworkOfferingVO offering = _networkOfferingDao.findById(network.getNetworkOfferingId()); - if (!offering.isSharedSourceNatService()) { + boolean sharedSourceNat = false; + Map sourceNatCapabilities = _networkMgr.getServiceCapabilities(network.getNetworkOfferingId(), Service.SourceNat); + if (sourceNatCapabilities != null) { + String supportedSourceNatTypes = sourceNatCapabilities.get(Capability.SupportedSourceNatTypes).toLowerCase(); + if (supportedSourceNatTypes.contains("zone")) { + sharedSourceNat = true; + } + } + + if (!sharedSourceNat) { // Manage the entry for this network's source NAT IP address List sourceNatIps = _ipAddressDao.listByAssociatedNetwork(network.getId(), true); if (sourceNatIps.size() == 1) { diff --git a/server/src/com/cloud/network/NetworkManagerImpl.java b/server/src/com/cloud/network/NetworkManagerImpl.java index e41673b1a75..27d045aaede 100755 --- a/server/src/com/cloud/network/NetworkManagerImpl.java +++ b/server/src/com/cloud/network/NetworkManagerImpl.java @@ -661,8 +661,16 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag txn.start(); - NetworkOfferingVO offering = _networkOfferingDao.findById(network.getNetworkOfferingId()); - if (!offering.isSharedSourceNatService()) { + boolean sharedSourceNat = false; + Map sourceNatCapabilities = getServiceCapabilities(network.getNetworkOfferingId(), Service.SourceNat); + if (sourceNatCapabilities != null) { + String supportedSourceNatTypes = sourceNatCapabilities.get(Capability.SupportedSourceNatTypes).toLowerCase(); + if (supportedSourceNatTypes.contains("zone")) { + sharedSourceNat = true; + } + } + + if (!sharedSourceNat) { // First IP address should be source nat when it's being associated with Guest Virtual network List addrs = listPublicIpAddressesInVirtualNetwork(ownerId, zoneId, true, networkId); @@ -1305,7 +1313,17 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag throws ConcurrentOperationException, InsufficientAddressCapacityException, ResourceUnavailableException, InsufficientCapacityException { // If this is a 1) guest virtual network 2) network has sourceNat service 3) network offering does not support a Shared source NAT rule, // associate a source NAT IP (if one isn't already associated with the network) - if (network.getType() == Network.Type.Isolated && isServiceSupportedByNetworkOffering(network.getNetworkOfferingId(), Service.SourceNat) && !offering.isSharedSourceNatService()) { + + boolean sharedSourceNat = false; + Map sourceNatCapabilities = getServiceCapabilities(network.getNetworkOfferingId(), Service.SourceNat); + if (sourceNatCapabilities != null) { + String supportedSourceNatTypes = sourceNatCapabilities.get(Capability.SupportedSourceNatTypes).toLowerCase(); + if (supportedSourceNatTypes.contains("zone")) { + sharedSourceNat = true; + } + } + + if (network.getType() == Network.Type.Isolated && isServiceSupportedByNetworkOffering(network.getNetworkOfferingId(), Service.SourceNat) && !sharedSourceNat) { List ips = _ipAddressDao.listByAssociatedNetwork(network.getId(), true); if (ips.isEmpty()) { diff --git a/server/src/com/cloud/network/element/JuniperSRXExternalFirewallElement.java b/server/src/com/cloud/network/element/JuniperSRXExternalFirewallElement.java index 7f2a24ccb45..d704f5f5da4 100644 --- a/server/src/com/cloud/network/element/JuniperSRXExternalFirewallElement.java +++ b/server/src/com/cloud/network/element/JuniperSRXExternalFirewallElement.java @@ -212,10 +212,6 @@ public class JuniperSRXExternalFirewallElement extends AdapterBase implements So firewallCapabilities.put(Capability.MultipleIps, "true"); - // Specifies that this element supports either one source NAT rule per account, or no source NAT rules at all; - // in the latter case a shared interface NAT rule will be used - firewallCapabilities.put(Capability.SupportedSourceNatTypes, "per account, per zone"); - // Specifies that this element can measure network usage on a per public IP basis firewallCapabilities.put(Capability.TrafficStatistics, "per public ip"); @@ -229,6 +225,13 @@ public class JuniperSRXExternalFirewallElement extends AdapterBase implements So capabilities.put(Service.Firewall, firewallCapabilities); capabilities.put(Service.Gateway, null); + + + Map sourceNatCapabilities = new HashMap(); + // Specifies that this element supports either one source NAT rule per account, or no source NAT rules at all; + // in the latter case a shared interface NAT rule will be used + sourceNatCapabilities.put(Capability.SupportedSourceNatTypes, "per account, per zone"); + capabilities.put(Service.SourceNat, sourceNatCapabilities); return capabilities; } diff --git a/server/src/com/cloud/network/element/VirtualRouterElement.java b/server/src/com/cloud/network/element/VirtualRouterElement.java index 8bdbea51275..c368c5032c5 100644 --- a/server/src/com/cloud/network/element/VirtualRouterElement.java +++ b/server/src/com/cloud/network/element/VirtualRouterElement.java @@ -313,7 +313,6 @@ public class VirtualRouterElement extends DhcpElement implements VirtualRouterEl firewallCapabilities.put(Capability.StaticNat, "true"); firewallCapabilities.put(Capability.SupportedProtocols, "tcp,udp,icmp"); firewallCapabilities.put(Capability.MultipleIps, "true"); - firewallCapabilities.put(Capability.SupportedSourceNatTypes, "per account"); capabilities.put(Service.Firewall, firewallCapabilities); @@ -330,6 +329,11 @@ public class VirtualRouterElement extends DhcpElement implements VirtualRouterEl capabilities.put(Service.Dhcp, null); capabilities.put(Service.Gateway, null); + + Map sourceNatCapabilities = new HashMap(); + sourceNatCapabilities.put(Capability.SupportedSourceNatTypes, "per account"); + capabilities.put(Service.SourceNat, sourceNatCapabilities); + return capabilities; } diff --git a/server/src/com/cloud/offerings/NetworkOfferingVO.java b/server/src/com/cloud/offerings/NetworkOfferingVO.java index c9458b7f4f9..44f4d7d0ba1 100644 --- a/server/src/com/cloud/offerings/NetworkOfferingVO.java +++ b/server/src/com/cloud/offerings/NetworkOfferingVO.java @@ -91,9 +91,6 @@ public class NetworkOfferingVO implements NetworkOffering { @Column(name=GenericDao.CREATED_COLUMN) Date created; - @Column(name="shared_source_nat_service") - boolean sharedSourceNatService; - @Column(name="is_security_group_enabled") boolean securityGroupEnabled; @@ -188,11 +185,6 @@ public class NetworkOfferingVO implements NetworkOffering { this.availability = availability; } - @Override - public boolean isSharedSourceNatService() { - return sharedSourceNatService; - } - @Override public String getUniqueName() { return uniqueName; From fe0b685e95820194d46dbd348808ce098a9cc3c0 Mon Sep 17 00:00:00 2001 From: alena Date: Thu, 27 Oct 2011 14:53:44 -0700 Subject: [PATCH 042/159] Security group is a service now --- .../cloud/resource/AgentRoutingResource.java | 3 - api/src/com/cloud/api/ApiConstants.java | 2 +- .../commands/CreateNetworkOfferingCmd.java | 7 -- .../com/cloud/api/commands/CreateZoneCmd.java | 13 ++- .../com/cloud/api/commands/DeployVMCmd.java | 5 +- .../api/commands/ListNetworkOfferingsCmd.java | 7 -- .../commands/UpdateNetworkOfferingCmd.java | 7 -- .../HypervisorCapabilitiesResponse.java | 2 - .../api/response/NetworkOfferingResponse.java | 7 -- .../cloud/api/response/NetworkResponse.java | 7 -- api/src/com/cloud/dc/DataCenter.java | 1 + api/src/com/cloud/network/Network.java | 9 +- api/src/com/cloud/network/NetworkProfile.java | 7 -- .../com/cloud/offering/NetworkOffering.java | 6 +- api/src/com/cloud/vm/NicProfile.java | 4 +- client/tomcatconf/components-premium.xml.in | 3 +- .../src/com/cloud/api/ApiResponseHelper.java | 2 - .../configuration/ConfigurationManager.java | 6 +- .../ConfigurationManagerImpl.java | 46 ++++------- server/src/com/cloud/dc/DataCenterVO.java | 9 +- .../cloud/hypervisor/HypervisorGuruBase.java | 1 - .../src/com/cloud/network/NetworkManager.java | 4 +- .../com/cloud/network/NetworkManagerImpl.java | 65 +++++++++++---- server/src/com/cloud/network/NetworkVO.java | 15 +--- .../com/cloud/network/dao/NetworkDaoImpl.java | 16 +++- .../cloud/network/element/DhcpElement.java | 7 +- .../network/element/SecurityGroupElement.java | 82 +++++++++++++++++++ .../cloud/network/guru/DirectNetworkGuru.java | 7 +- .../VirtualNetworkApplianceManagerImpl.java | 2 +- .../security/SecurityGroupManagerImpl.java | 5 +- .../cloud/offerings/NetworkOfferingVO.java | 20 +---- .../offerings/dao/NetworkOfferingDaoImpl.java | 6 +- .../cloud/server/ConfigurationServerImpl.java | 18 ++-- .../src/com/cloud/vm/UserVmManagerImpl.java | 9 +- .../cloud/vm/VirtualMachineManagerImpl.java | 8 +- setup/db/create-schema.sql | 3 +- 36 files changed, 229 insertions(+), 192 deletions(-) create mode 100644 server/src/com/cloud/network/element/SecurityGroupElement.java diff --git a/agent-simulator/src/com/cloud/resource/AgentRoutingResource.java b/agent-simulator/src/com/cloud/resource/AgentRoutingResource.java index 009e4165881..2a35b55ca96 100644 --- a/agent-simulator/src/com/cloud/resource/AgentRoutingResource.java +++ b/agent-simulator/src/com/cloud/resource/AgentRoutingResource.java @@ -4,7 +4,6 @@ package com.cloud.resource; -import java.io.File; import java.util.ArrayList; import java.util.HashMap; import java.util.List; @@ -18,9 +17,7 @@ import com.cloud.agent.api.Answer; import com.cloud.agent.api.CheckVirtualMachineAnswer; import com.cloud.agent.api.CheckVirtualMachineCommand; import com.cloud.agent.api.Command; - import com.cloud.agent.api.PingCommand; -import com.cloud.agent.api.PingRoutingCommand; import com.cloud.agent.api.PingRoutingWithNwGroupsCommand; import com.cloud.agent.api.PrepareForMigrationCommand; import com.cloud.agent.api.ReadyAnswer; diff --git a/api/src/com/cloud/api/ApiConstants.java b/api/src/com/cloud/api/ApiConstants.java index 603f178df68..36cae9779ef 100755 --- a/api/src/com/cloud/api/ApiConstants.java +++ b/api/src/com/cloud/api/ApiConstants.java @@ -153,7 +153,6 @@ public class ApiConstants { public static final String SECURITY_GROUP_NAMES = "securitygroupnames"; public static final String SECURITY_GROUP_NAME = "securitygroupname"; public static final String SECURITY_GROUP_ID = "securitygroupid"; - public static final String SECURITY_GROUP_EANBLED = "securitygroupenabled"; public static final String SENT = "sent"; public static final String SENT_BYTES = "sentbytes"; public static final String SERVICE_OFFERING_ID = "serviceofferingid"; @@ -283,4 +282,5 @@ public class ApiConstants { public static final String SERVICE_NAME = "servicename"; public static final String DHCP_RANGE = "dhcprange"; public static final String UUID = "uuid"; + public static final String SECURITY_GROUP_EANBLED = "securitygroupenabled"; } diff --git a/api/src/com/cloud/api/commands/CreateNetworkOfferingCmd.java b/api/src/com/cloud/api/commands/CreateNetworkOfferingCmd.java index 2799cc6a05b..f93929b7f53 100644 --- a/api/src/com/cloud/api/commands/CreateNetworkOfferingCmd.java +++ b/api/src/com/cloud/api/commands/CreateNetworkOfferingCmd.java @@ -97,9 +97,6 @@ public class CreateNetworkOfferingCmd extends BaseCmd { @Parameter(name = ApiConstants.SERVICE_PROVIDER_LIST, type = CommandType.MAP, description = "provider to service mapping. If not specified, the provider for the service will be mapped to the default provider on the physical network") private Map serviceProviderList; - @Parameter(name=ApiConstants.SECURITY_GROUP_EANBLED, type=CommandType.BOOLEAN, description="true is security group is enabled for the network offering") - private Boolean securityGroupEnabled; - @Parameter(name=ApiConstants.TYPE, type=CommandType.STRING, required=true, description="type of the network offering: Shared or Isolated") private String type; @@ -207,10 +204,6 @@ public class CreateNetworkOfferingCmd extends BaseCmd { return serviceProviderMap; } - public Boolean getSecurityGroupEnabled() { - return securityGroupEnabled == null ? false : securityGroupEnabled; - } - ///////////////////////////////////////////////////// /////////////// API Implementation/////////////////// ///////////////////////////////////////////////////// diff --git a/api/src/com/cloud/api/commands/CreateZoneCmd.java b/api/src/com/cloud/api/commands/CreateZoneCmd.java index 67577b8ef00..c6123e3df09 100755 --- a/api/src/com/cloud/api/commands/CreateZoneCmd.java +++ b/api/src/com/cloud/api/commands/CreateZoneCmd.java @@ -68,6 +68,9 @@ public class CreateZoneCmd extends BaseCmd { @Parameter(name=ApiConstants.ALLOCATION_STATE, type=CommandType.STRING, description="Allocation state of this Zone for allocation of new resources") private String allocationState; + + @Parameter(name=ApiConstants.SECURITY_GROUP_EANBLED, type=CommandType.BOOLEAN, description="true if network is security group enabled, false otherwise") + private Boolean securitygroupenabled; ///////////////////////////////////////////////////// /////////////////// Accessors /////////////////////// @@ -111,12 +114,18 @@ public class CreateZoneCmd extends BaseCmd { public String getAllocationState() { return allocationState; - } + } + + public Boolean getSecuritygroupenabled() { + if (securitygroupenabled == null) { + return false; + } + return securitygroupenabled; + } ///////////////////////////////////////////////////// /////////////// API Implementation/////////////////// - @Override public String getCommandName() { return s_name; diff --git a/api/src/com/cloud/api/commands/DeployVMCmd.java b/api/src/com/cloud/api/commands/DeployVMCmd.java index 9803f4fcaa5..8e3188c5298 100644 --- a/api/src/com/cloud/api/commands/DeployVMCmd.java +++ b/api/src/com/cloud/api/commands/DeployVMCmd.java @@ -371,13 +371,10 @@ public class DeployVMCmd extends BaseAsyncCreateCmd { displayName, diskOfferingId, size, group, getHypervisor(), userData, sshKeyPairName, getIpToNetworkMap(), ipAddress, keyboard); } } else { - if (zone.isSecurityGroupEnabled()) { + if (getSecurityGroupIdList() != null && !getSecurityGroupIdList().isEmpty()) { vm = _userVmService.createAdvancedSecurityGroupVirtualMachine(zone, serviceOffering, template, getNetworkIds(), getSecurityGroupIdList(), owner, name, displayName, diskOfferingId, size, group, getHypervisor(), userData, sshKeyPairName, getIpToNetworkMap(), ipAddress, keyboard); } else { - if (getSecurityGroupIdList() != null && !getSecurityGroupIdList().isEmpty()) { - throw new InvalidParameterValueException("Can't create vm with security groups; security group feature is not enabled per zone"); - } vm = _userVmService.createAdvancedVirtualMachine(zone, serviceOffering, template, getNetworkIds(), owner, name, displayName, diskOfferingId, size, group, getHypervisor(), userData, sshKeyPairName, getIpToNetworkMap(), ipAddress, keyboard); } diff --git a/api/src/com/cloud/api/commands/ListNetworkOfferingsCmd.java b/api/src/com/cloud/api/commands/ListNetworkOfferingsCmd.java index 1fcd3a4de35..f5cee89e212 100644 --- a/api/src/com/cloud/api/commands/ListNetworkOfferingsCmd.java +++ b/api/src/com/cloud/api/commands/ListNetworkOfferingsCmd.java @@ -68,9 +68,6 @@ public class ListNetworkOfferingsCmd extends BaseListCmd { @Parameter(name=ApiConstants.ZONE_ID, type=CommandType.LONG, description="list netowrk offerings available for network creation in specific zone") private Long zoneId; - @Parameter(name=ApiConstants.SECURITY_GROUP_EANBLED, type=CommandType.BOOLEAN, description="list network offerings that have security group feature enabled") - private Boolean securityGroupEnabled; - @Parameter(name=ApiConstants.STATE, type=CommandType.STRING, description="list network offerings by state") private String state; @@ -120,10 +117,6 @@ public class ListNetworkOfferingsCmd extends BaseListCmd { return zoneId; } - public Boolean getSecurityGroupEnabled() { - return securityGroupEnabled; - } - public String getState() { return state; } diff --git a/api/src/com/cloud/api/commands/UpdateNetworkOfferingCmd.java b/api/src/com/cloud/api/commands/UpdateNetworkOfferingCmd.java index 435bcbabe89..25d4ec87303 100644 --- a/api/src/com/cloud/api/commands/UpdateNetworkOfferingCmd.java +++ b/api/src/com/cloud/api/commands/UpdateNetworkOfferingCmd.java @@ -88,9 +88,6 @@ public class UpdateNetworkOfferingCmd extends BaseCmd { @Parameter(name=ApiConstants.STATE, type=CommandType.STRING, description="list network offerings by state") private String state; - - @Parameter(name=ApiConstants.SECURITY_GROUP_EANBLED, type=CommandType.BOOLEAN, description="true is security group is enabled for the network offering") - private Boolean securityGroupEnabled; ///////////////////////////////////////////////////// /////////////////// Accessors /////////////////////// @@ -172,10 +169,6 @@ public class UpdateNetworkOfferingCmd extends BaseCmd { return state; } - public Boolean getSecurityGroupEnabled() { - return securityGroupEnabled; - } - ///////////////////////////////////////////////////// /////////////// API Implementation/////////////////// ///////////////////////////////////////////////////// diff --git a/api/src/com/cloud/api/response/HypervisorCapabilitiesResponse.java b/api/src/com/cloud/api/response/HypervisorCapabilitiesResponse.java index fe968369159..931a7b55b87 100644 --- a/api/src/com/cloud/api/response/HypervisorCapabilitiesResponse.java +++ b/api/src/com/cloud/api/response/HypervisorCapabilitiesResponse.java @@ -38,8 +38,6 @@ public class HypervisorCapabilitiesResponse extends BaseResponse { @SerializedName(ApiConstants.SECURITY_GROUP_EANBLED) @Param(description="true if security group is supported") private boolean isSecurityGroupEnabled; - - @Override public Long getObjectId() { return getId(); diff --git a/api/src/com/cloud/api/response/NetworkOfferingResponse.java b/api/src/com/cloud/api/response/NetworkOfferingResponse.java index 5e6f8505c94..146b2116576 100644 --- a/api/src/com/cloud/api/response/NetworkOfferingResponse.java +++ b/api/src/com/cloud/api/response/NetworkOfferingResponse.java @@ -62,9 +62,6 @@ public class NetworkOfferingResponse extends BaseResponse{ @SerializedName(ApiConstants.NETWORKRATE) @Param(description="data transfer rate in megabits per second allowed.") private Integer networkRate; - @SerializedName(ApiConstants.SECURITY_GROUP_EANBLED) @Param(description="true if security group is enabled, false otherwise") - private Boolean isSecurityGroupEnabled; - @SerializedName(ApiConstants.STATE) @Param(description="state of the network offering. Can be Disabled/Enabled/Inactive") private String state; @@ -122,10 +119,6 @@ public class NetworkOfferingResponse extends BaseResponse{ this.networkRate = networkRate; } - public void setIsSecurityGroupEnabled(Boolean isSecurityGroupEnabled) { - this.isSecurityGroupEnabled = isSecurityGroupEnabled; - } - public void setServices(List services) { this.services = services; } diff --git a/api/src/com/cloud/api/response/NetworkResponse.java b/api/src/com/cloud/api/response/NetworkResponse.java index f780b998ec2..3a599bd7d60 100644 --- a/api/src/com/cloud/api/response/NetworkResponse.java +++ b/api/src/com/cloud/api/response/NetworkResponse.java @@ -120,9 +120,6 @@ public class NetworkResponse extends BaseResponse implements ControlledEntityRes @SerializedName(ApiConstants.NETWORK_DOMAIN) @Param(description="the network domain") private String networkDomain; - @SerializedName(ApiConstants.SECURITY_GROUP_EANBLED) @Param(description="true if security group is enabled, false otherwise") - private Boolean isSecurityGroupEnabled; - @SerializedName(ApiConstants.TAGS) @Param(description="comma separated tag") private String tags; @@ -246,10 +243,6 @@ public class NetworkResponse extends BaseResponse implements ControlledEntityRes this.networkDomain = networkDomain; } - public void setIsSecurityGroupEnabled(Boolean sgEnabled) { - this.isSecurityGroupEnabled = sgEnabled; - } - public void setTags(List tags) { if (tags == null || tags.size() == 0) { return; diff --git a/api/src/com/cloud/dc/DataCenter.java b/api/src/com/cloud/dc/DataCenter.java index 8ed3bfa8b09..a326efb3491 100644 --- a/api/src/com/cloud/dc/DataCenter.java +++ b/api/src/com/cloud/dc/DataCenter.java @@ -1,4 +1,5 @@ /** + * Copyright (C) 2010 Cloud.com, Inc. All rights reserved. * * This software is licensed under the GNU General Public License v3 or later. diff --git a/api/src/com/cloud/network/Network.java b/api/src/com/cloud/network/Network.java index e9b5c1250ea..40609777134 100644 --- a/api/src/com/cloud/network/Network.java +++ b/api/src/com/cloud/network/Network.java @@ -55,6 +55,7 @@ public interface Network extends ControlledEntity { public static final Service Lb = new Service("Lb", Capability.SupportedLBAlgorithms, Capability.SupportedProtocols, Capability.TrafficStatistics, Capability.LoadBalancingSupportedIps); public static final Service UserData = new Service("UserData"); public static final Service SourceNat = new Service("SourceNat"); + public static final Service SecurityGroup = new Service("SecurityGroup"); private String name; private Capability[] caps; @@ -118,9 +119,11 @@ public interface Network extends ControlledEntity { public static final Provider ExternalGateWay = new Provider("ExternalGateWay", true); public static final Provider ElasticLoadBalancerVm = new Provider("ElasticLoadBalancerVm", false); public static final Provider RedundantVirtualRouter = new Provider("RedundantVirtualRouter", false); - public static final Provider defaultProvider = VirtualRouter; - + public static final Provider SecurityGroupProvider = new Provider("SecurityGroupProvider", false); public static final Provider None = new Provider("None", false); + + //the default provider + public static final Provider defaultProvider = VirtualRouter; private String name; private boolean isExternal; @@ -266,8 +269,6 @@ public interface Network extends ControlledEntity { String getNetworkDomain(); - boolean isSecurityGroupEnabled(); - List getTags(); Type getType(); diff --git a/api/src/com/cloud/network/NetworkProfile.java b/api/src/com/cloud/network/NetworkProfile.java index be243997683..eb4c119b7ae 100644 --- a/api/src/com/cloud/network/NetworkProfile.java +++ b/api/src/com/cloud/network/NetworkProfile.java @@ -47,7 +47,6 @@ public class NetworkProfile implements Network { private String reservationId; private boolean isDefault; private String networkDomain; - private boolean isSecurityGroupEnabled; private List tags; private Network.Type type; private boolean isShared; @@ -72,7 +71,6 @@ public class NetworkProfile implements Network { this.isDefault = network.isDefault(); this.networkDomain = network.getNetworkDomain(); this.domainId = network.getDomainId(); - this.isSecurityGroupEnabled = network.isSecurityGroupEnabled(); this.type = network.getType(); this.isShared = network.getIsShared(); this.physicalNetworkId = network.getPhysicalNetworkId(); @@ -192,11 +190,6 @@ public class NetworkProfile implements Network { public long getDomainId() { return domainId; } - - @Override - public boolean isSecurityGroupEnabled() { - return isSecurityGroupEnabled; - } @Override public Network.Type getType(){ diff --git a/api/src/com/cloud/offering/NetworkOffering.java b/api/src/com/cloud/offering/NetworkOffering.java index bd4e02ef1b4..481ae8d125e 100644 --- a/api/src/com/cloud/offering/NetworkOffering.java +++ b/api/src/com/cloud/offering/NetworkOffering.java @@ -88,13 +88,9 @@ public interface NetworkOffering { String getUniqueName(); - boolean isSecurityGroupEnabled(); - void setState(State state); State getState(); - - void setSecurityGroupEnabled(boolean securityGroupEnabled); - + Type getType(); } diff --git a/api/src/com/cloud/vm/NicProfile.java b/api/src/com/cloud/vm/NicProfile.java index d59e9e5c831..e2f737bfa3b 100644 --- a/api/src/com/cloud/vm/NicProfile.java +++ b/api/src/com/cloud/vm/NicProfile.java @@ -213,7 +213,7 @@ public class NicProfile { return strategy; } - public NicProfile(Nic nic, Network network, URI broadcastUri, URI isolationUri, Integer networkRate) { + public NicProfile(Nic nic, Network network, URI broadcastUri, URI isolationUri, Integer networkRate, boolean isSecurityGroupEnabled) { this.id = nic.getId(); this.networkId = network.getId(); this.gateway = nic.getGateway(); @@ -231,7 +231,7 @@ public class NicProfile { this.broadcastUri = broadcastUri; this.isolationUri = isolationUri; this.netmask = nic.getNetmask(); - this.isSecurityGroupEnabled = network.isSecurityGroupEnabled(); + this.isSecurityGroupEnabled = isSecurityGroupEnabled; this.vmId = nic.getInstanceId(); this.tags = network.getTags(); diff --git a/client/tomcatconf/components-premium.xml.in b/client/tomcatconf/components-premium.xml.in index 7306853c636..1aa7352521f 100755 --- a/client/tomcatconf/components-premium.xml.in +++ b/client/tomcatconf/components-premium.xml.in @@ -30,8 +30,7 @@ - - + diff --git a/server/src/com/cloud/api/ApiResponseHelper.java b/server/src/com/cloud/api/ApiResponseHelper.java index d80d375eeb7..09249ee9549 100755 --- a/server/src/com/cloud/api/ApiResponseHelper.java +++ b/server/src/com/cloud/api/ApiResponseHelper.java @@ -2109,7 +2109,6 @@ public class ApiResponseHelper implements ResponseGenerator { response.setSpecifyVlan(offering.getSpecifyVlan()); response.setAvailability(offering.getAvailability().toString()); response.setNetworkRate(ApiDBUtils.getNetworkRate(offering.getId())); - response.setIsSecurityGroupEnabled(offering.isSecurityGroupEnabled()); if (offering.getType() != null) { response.setType(offering.getType().toString()); } @@ -2190,7 +2189,6 @@ public class ApiResponseHelper implements ResponseGenerator { response.setDns1(profile.getDns1()); response.setDns2(profile.getDns2()); - response.setIsSecurityGroupEnabled(network.isSecurityGroupEnabled()); response.setTags(network.getTags()); // populate capability diff --git a/server/src/com/cloud/configuration/ConfigurationManager.java b/server/src/com/cloud/configuration/ConfigurationManager.java index c951493f1d6..ce2e81bf0e2 100644 --- a/server/src/com/cloud/configuration/ConfigurationManager.java +++ b/server/src/com/cloud/configuration/ConfigurationManager.java @@ -117,11 +117,12 @@ public interface ConfigurationManager extends ConfigurationService, Manager { * @param zoneType * @param allocationState * @param networkDomain TODO + * @param isSecurityGroupEnabled TODO * @return * @throws * @throws */ - DataCenterVO createZone(long userId, String zoneName, String dns1, String dns2, String internalDns1, String internalDns2, String guestCidr, String domain, Long domainId, NetworkType zoneType, String allocationState, String networkDomain); + DataCenterVO createZone(long userId, String zoneName, String dns1, String dns2, String internalDns1, String internalDns2, String guestCidr, String domain, Long domainId, NetworkType zoneType, String allocationState, String networkDomain, boolean isSecurityGroupEnabled); /** * Deletes a VLAN from the database, along with all of its IP addresses. Will not delete VLANs that have allocated IP addresses. @@ -177,7 +178,6 @@ public interface ConfigurationManager extends ConfigurationService, Manager { * @param networkRate TODO * @param serviceProviderMap TODO * @param isDefault TODO - * @param isSecurityGroupEnabled TODO * @param type TODO * @param systemOnly TODO * @param id @@ -185,7 +185,7 @@ public interface ConfigurationManager extends ConfigurationService, Manager { * @return network offering object */ - NetworkOfferingVO createNetworkOffering(long userId, String name, String displayText, TrafficType trafficType, String tags, Integer maxConnections, boolean specifyVlan, Availability availability, Integer networkRate, Map> serviceProviderMap, boolean isDefault, boolean isSecurityGroupEnabled, Network.Type type, boolean systemOnly); + NetworkOfferingVO createNetworkOffering(long userId, String name, String displayText, TrafficType trafficType, String tags, Integer maxConnections, boolean specifyVlan, Availability availability, Integer networkRate, Map> serviceProviderMap, boolean isDefault, Network.Type type, boolean systemOnly); Vlan createVlanAndPublicIpRange(Long userId, Long zoneId, Long podId, String startIP, String endIP, String vlanGateway, String vlanNetmask, boolean forVirtualNetwork, String vlanId, Account account, Long networkId) throws InsufficientCapacityException, ConcurrentOperationException, InvalidParameterValueException; diff --git a/server/src/com/cloud/configuration/ConfigurationManagerImpl.java b/server/src/com/cloud/configuration/ConfigurationManagerImpl.java index 1a44e8feebe..b1aa9b1ed00 100755 --- a/server/src/com/cloud/configuration/ConfigurationManagerImpl.java +++ b/server/src/com/cloud/configuration/ConfigurationManagerImpl.java @@ -1311,7 +1311,7 @@ public class ConfigurationManagerImpl implements ConfigurationManager, Configura @Override @DB public DataCenterVO createZone(long userId, String zoneName, String dns1, String dns2, String internalDns1, String internalDns2, String guestCidr, String domain, Long domainId, - NetworkType zoneType, String allocationStateStr, String networkDomain) { + NetworkType zoneType, String allocationStateStr, String networkDomain, boolean isSecurityGroupEnabled) { // checking the following params outside checkzoneparams method as we do not use these params for updatezone // hence the method below is generic to check for common params @@ -1336,7 +1336,7 @@ public class ConfigurationManagerImpl implements ConfigurationManager, Configura try { txn.start(); // Create the new zone in the database - DataCenterVO zone = new DataCenterVO(zoneName, null, dns1, dns2, internalDns1, internalDns2, guestCidr, domain, domainId, zoneType, zoneToken, networkDomain); + DataCenterVO zone = new DataCenterVO(zoneName, null, dns1, dns2, internalDns1, internalDns2, guestCidr, domain, domainId, zoneType, zoneToken, networkDomain, isSecurityGroupEnabled); if (allocationStateStr != null && !allocationStateStr.isEmpty()) { Grouping.AllocationState allocationState = Grouping.AllocationState.valueOf(allocationStateStr); zone.setAllocationState(allocationState); @@ -1386,7 +1386,6 @@ public class ConfigurationManagerImpl implements ConfigurationManager, Configura if (zone.getNetworkType() == NetworkType.Basic) { isNetworkDefault = true; broadcastDomainType = BroadcastDomainType.Native; - userNetwork.setSecurityGroupEnabled(offering.isSecurityGroupEnabled()); } else { continue; } @@ -1415,6 +1414,7 @@ public class ConfigurationManagerImpl implements ConfigurationManager, Configura Boolean isBasic = false; String allocationState = cmd.getAllocationState(); String networkDomain = cmd.getDomain(); + boolean isSecurityGroupEnabled = cmd.getSecuritygroupenabled(); if (allocationState == null) { allocationState = Grouping.AllocationState.Enabled.toString(); @@ -1428,12 +1428,12 @@ public class ConfigurationManagerImpl implements ConfigurationManager, Configura NetworkType zoneType = isBasic ? NetworkType.Basic : NetworkType.Advanced; - /*Guest cidr is required for Advanced zone creation; error out when the parameter specified for Basic zone - if (zoneType == NetworkType.Advanced && guestCidr == null && !securityGroupEnabled) { + //Guest cidr is required for Advanced zone creation; error out when the parameter specified for Basic zone + if (zoneType == NetworkType.Advanced && guestCidr == null && !isSecurityGroupEnabled) { throw new InvalidParameterValueException("guestCidrAddress parameter is required for Advanced zone creation"); } else if (zoneType == NetworkType.Basic && guestCidr != null) { throw new InvalidParameterValueException("guestCidrAddress parameter is not supported for Basic zone"); - }*/ + } DomainVO domainVO = null; @@ -1445,16 +1445,11 @@ public class ConfigurationManagerImpl implements ConfigurationManager, Configura domainVO = _domainDao.findById(domainId); } - /* Verify zone type - if (zoneType == NetworkType.Basic && vnetRange != null) { - vnetRange = null; + if (zoneType == NetworkType.Basic) { + isSecurityGroupEnabled = true; } - if (zoneType == NetworkType.Basic) { - securityGroupEnabled = true; - }*/ - - return createZone(userId, zoneName, dns1, dns2, internalDns1, internalDns2, guestCidr, domainVO != null ? domainVO.getName() : null, domainId, zoneType, allocationState, networkDomain); + return createZone(userId, zoneName, dns1, dns2, internalDns1, internalDns2, guestCidr, domainVO != null ? domainVO.getName() : null, domainId, zoneType, allocationState, networkDomain, isSecurityGroupEnabled); } @Override @@ -1904,7 +1899,7 @@ public class ConfigurationManagerImpl implements ConfigurationManager, Configura throw new InvalidParameterValueException("Vlan doesn't match vlan of the network"); } - if (forVirtualNetwork || zone.getNetworkType() == DataCenter.NetworkType.Basic || network.isSecurityGroupEnabled()) { + if (forVirtualNetwork || zone.getNetworkType() == DataCenter.NetworkType.Basic || zone.isSecurityGroupEnabled()) { if (vlanGateway == null || vlanNetmask == null || zoneId == null) { throw new InvalidParameterValueException("Gateway, netmask and zoneId have to be passed in for virtual and direct untagged networks"); } @@ -2714,7 +2709,7 @@ public class ConfigurationManagerImpl implements ConfigurationManager, Configura String trafficTypeString = cmd.getTraffictype(); Boolean specifyVlan = cmd.getSpecifyVlan(); String availabilityStr = cmd.getAvailability(); - Boolean isSecurityGroupEnabled = cmd.getSecurityGroupEnabled(); + Integer networkRate = cmd.getNetworkRate(); @@ -2820,19 +2815,19 @@ public class ConfigurationManagerImpl implements ConfigurationManager, Configura } } - return createNetworkOffering(userId, name, displayText, trafficType, tags, maxConnections, specifyVlan, availability, networkRate, serviceProviderMap, false, isSecurityGroupEnabled, type, false); + return createNetworkOffering(userId, name, displayText, trafficType, tags, maxConnections, specifyVlan, availability, networkRate, serviceProviderMap, false, type, false); } @Override @DB public NetworkOfferingVO createNetworkOffering(long userId, String name, String displayText, TrafficType trafficType, String tags, Integer maxConnections, boolean specifyVlan, - Availability availability, Integer networkRate, Map> serviceProviderMap, boolean isDefault, boolean isSecurityGroupEnabled, Network.Type type, boolean systemOnly) { + Availability availability, Integer networkRate, Map> serviceProviderMap, boolean isDefault, Network.Type type, boolean systemOnly) { String multicastRateStr = _configDao.getValue("multicast.throttling.rate"); int multicastRate = ((multicastRateStr == null) ? 10 : Integer.parseInt(multicastRateStr)); tags = cleanupTags(tags); - NetworkOfferingVO offering = new NetworkOfferingVO(name, displayText, trafficType, systemOnly, specifyVlan, networkRate, multicastRate, maxConnections, isDefault, availability, tags, isSecurityGroupEnabled, type); + NetworkOfferingVO offering = new NetworkOfferingVO(name, displayText, trafficType, systemOnly, specifyVlan, networkRate, multicastRate, maxConnections, isDefault, availability, tags, type); Transaction txn = Transaction.currentTxn(); txn.start(); @@ -2870,7 +2865,6 @@ public class ConfigurationManagerImpl implements ConfigurationManager, Configura Object specifyVlan = cmd.getSpecifyVlan(); Object isShared = cmd.getIsShared(); Object availability = cmd.getAvailability(); - Object sgEnabled = cmd.getSecurityGroupEnabled(); Object state = cmd.getState(); Long zoneId = cmd.getZoneId(); DataCenter zone = null; @@ -2926,10 +2920,6 @@ public class ConfigurationManagerImpl implements ConfigurationManager, Configura if (state != null) { sc.addAnd("state", SearchCriteria.Op.EQ, state); } - - if (sgEnabled != null) { - sc.addAnd("securityGroupEnabled", SearchCriteria.Op.EQ, sgEnabled); - } if (zone != null) { if (zone.getNetworkType() == NetworkType.Basic) { @@ -3005,7 +2995,6 @@ public class ConfigurationManagerImpl implements ConfigurationManager, Configura String name = cmd.getNetworkOfferingName(); String availabilityStr = cmd.getAvailability(); Availability availability = null; - Boolean sgEnabled = cmd.getSecurityGroupEnabled(); String state = cmd.getState(); UserContext.current().setEventDetails(" Id: "+id); @@ -3061,13 +3050,6 @@ public class ConfigurationManagerImpl implements ConfigurationManager, Configura Long networks = _networkDao.getNetworkCountByOfferingId(id); boolean networksExist = (networks != null && networks.longValue() > 0); - if (sgEnabled != null) { - if (networksExist) { - throw new InvalidParameterValueException("Unable to reset securityGroupEnabled property as there are existing networks using this network offering"); - } - offering.setSecurityGroupEnabled(sgEnabled); - } - //configure service provider map Map> serviceProviderMap = new HashMap>(); Set defaultProviders = new HashSet(); diff --git a/server/src/com/cloud/dc/DataCenterVO.java b/server/src/com/cloud/dc/DataCenterVO.java index 8732e0c737e..6b44bbac953 100644 --- a/server/src/com/cloud/dc/DataCenterVO.java +++ b/server/src/com/cloud/dc/DataCenterVO.java @@ -121,6 +121,9 @@ public class DataCenterVO implements DataCenter { @Enumerated(value=EnumType.STRING) AllocationState allocationState; + @Column(name="is_security_group_enabled") + boolean securityGroupEnabled; + @Override public String getDnsProvider() { return dnsProvider; @@ -167,12 +170,12 @@ public class DataCenterVO implements DataCenter { } public DataCenterVO(long id, String name, String description, String dns1, String dns2, String dns3, String dns4, String guestCidr, String domain, Long domainId, NetworkType zoneType, String zoneToken, String domainSuffix) { - this(name, description, dns1, dns2, dns3, dns4, guestCidr, domain, domainId, zoneType, zoneToken, domainSuffix); + this(name, description, dns1, dns2, dns3, dns4, guestCidr, domain, domainId, zoneType, zoneToken, domainSuffix, false); this.id = id; this.allocationState = Grouping.AllocationState.Enabled; } - public DataCenterVO(String name, String description, String dns1, String dns2, String dns3, String dns4, String guestCidr, String domain, Long domainId, NetworkType zoneType, String zoneToken, String domainSuffix) { + public DataCenterVO(String name, String description, String dns1, String dns2, String dns3, String dns4, String guestCidr, String domain, Long domainId, NetworkType zoneType, String zoneToken, String domainSuffix, boolean securityGroupEnabled) { this.name = name; this.description = description; this.dns1 = dns1; @@ -184,6 +187,8 @@ public class DataCenterVO implements DataCenter { this.domainId = domainId; this.networkType = zoneType; this.allocationState = Grouping.AllocationState.Enabled; + this.securityGroupEnabled = securityGroupEnabled; + if (zoneType == NetworkType.Advanced) { loadBalancerProvider = Provider.VirtualRouter.getName(); diff --git a/server/src/com/cloud/hypervisor/HypervisorGuruBase.java b/server/src/com/cloud/hypervisor/HypervisorGuruBase.java index 798b25e067e..b4aa34ae4c2 100644 --- a/server/src/com/cloud/hypervisor/HypervisorGuruBase.java +++ b/server/src/com/cloud/hypervisor/HypervisorGuruBase.java @@ -49,7 +49,6 @@ public abstract class HypervisorGuruBase extends AdapterBase implements Hypervis to.setBroadcastUri(profile.getBroadCastUri()); to.setIsolationuri(profile.getIsolationUri()); to.setNetworkRateMbps(profile.getNetworkRate()); - to.setSecurityGroupEnabled(profile.isSecurityGroupEnabled()); to.setTags(profile.getTags()); return to; } diff --git a/server/src/com/cloud/network/NetworkManager.java b/server/src/com/cloud/network/NetworkManager.java index fc0e50b83d3..0fd4ad1ea6c 100644 --- a/server/src/com/cloud/network/NetworkManager.java +++ b/server/src/com/cloud/network/NetworkManager.java @@ -223,6 +223,8 @@ public interface NetworkManager extends NetworkService { List listNetworkOfferingsForUpgrade(long networkId); - PhysicalNetwork translateZoneIdToPhysicalNetwork(long zoneId); + PhysicalNetwork translateZoneIdToPhysicalNetwork(long zoneId); + + boolean isSecurityGroupSupportedInNetwork(Network network); } diff --git a/server/src/com/cloud/network/NetworkManagerImpl.java b/server/src/com/cloud/network/NetworkManagerImpl.java index 27d045aaede..f63c95d4913 100755 --- a/server/src/com/cloud/network/NetworkManagerImpl.java +++ b/server/src/com/cloud/network/NetworkManagerImpl.java @@ -826,6 +826,15 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag defaultDirectNetworkOfferingProviders.put(Service.Dns, defaultProviders); defaultDirectNetworkOfferingProviders.put(Service.UserData, defaultProviders); + + Map> defaultDirectBasicZoneNetworkOfferingProviders = new HashMap>(); + defaultDirectBasicZoneNetworkOfferingProviders.put(Service.Dhcp, defaultProviders); + defaultDirectBasicZoneNetworkOfferingProviders.put(Service.Dns, defaultProviders); + defaultDirectBasicZoneNetworkOfferingProviders.put(Service.UserData, defaultProviders); + Set sgProviders = new HashSet(); + sgProviders.add(Provider.SecurityGroupProvider); + defaultDirectBasicZoneNetworkOfferingProviders.put(Service.SecurityGroup, sgProviders); + Map> defaultVirtualNetworkOfferingProviders = new HashMap>(); defaultProviders.clear(); defaultProviders.add(Network.Provider.VirtualRouter); @@ -845,19 +854,19 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag //check that offering already exists NetworkOfferingVO offering = null; if (_networkOfferingDao.findByUniqueName(NetworkOffering.SystemGuestNetwork) == null) { - offering = _configMgr.createNetworkOffering(Account.ACCOUNT_ID_SYSTEM, NetworkOffering.SystemGuestNetwork, "System Offering for System-Guest-Network", TrafficType.Guest, null, null, false, Availability.Optional, null, defaultDirectNetworkOfferingProviders, true, true, Network.Type.Shared, true); + offering = _configMgr.createNetworkOffering(Account.ACCOUNT_ID_SYSTEM, NetworkOffering.SystemGuestNetwork, "System Offering for System-Guest-Network", TrafficType.Guest, null, null, false, Availability.Optional, null, defaultDirectNetworkOfferingProviders, true, Network.Type.Shared, true); offering.setState(NetworkOffering.State.Enabled); _networkOfferingDao.update(offering.getId(), offering); } if (_networkOfferingDao.findByUniqueName(NetworkOffering.DefaultVirtualizedNetworkOffering) == null) { - offering = _configMgr.createNetworkOffering(Account.ACCOUNT_ID_SYSTEM,NetworkOffering.DefaultVirtualizedNetworkOffering, "Virtual Vlan", TrafficType.Guest, null, null, false, Availability.Required, null, defaultVirtualNetworkOfferingProviders, true, false, Network.Type.Isolated, false); + offering = _configMgr.createNetworkOffering(Account.ACCOUNT_ID_SYSTEM,NetworkOffering.DefaultVirtualizedNetworkOffering, "Virtual Vlan", TrafficType.Guest, null, null, false, Availability.Required, null, defaultVirtualNetworkOfferingProviders, true, Network.Type.Isolated, false); offering.setState(NetworkOffering.State.Enabled); _networkOfferingDao.update(offering.getId(), offering); } if (_networkOfferingDao.findByUniqueName(NetworkOffering.DefaultDirectNetworkOffering) == null) { - offering = _configMgr.createNetworkOffering(Account.ACCOUNT_ID_SYSTEM, NetworkOffering.DefaultDirectNetworkOffering, "Direct", TrafficType.Guest, null, null, true, Availability.Optional, null, defaultDirectNetworkOfferingProviders, true, false, Network.Type.Shared, false); + offering = _configMgr.createNetworkOffering(Account.ACCOUNT_ID_SYSTEM, NetworkOffering.DefaultDirectNetworkOffering, "Direct", TrafficType.Guest, null, null, true, Availability.Optional, null, defaultDirectNetworkOfferingProviders, true, Network.Type.Shared, false); offering.setState(NetworkOffering.State.Enabled); _networkOfferingDao.update(offering.getId(), offering); } @@ -1050,7 +1059,7 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag } NetworkVO vo = new NetworkVO(id, network, offering.getId(), guru.getName(), owner.getDomainId(), owner.getId(), related, name, displayText, isDefault, - predefined.isSecurityGroupEnabled(), (domainId != null), predefined.getNetworkDomain(), offering.getType(), isShared, plan.getDataCenterId(), plan.getPhysicalNetworkId()); + (domainId != null), predefined.getNetworkDomain(), offering.getType(), isShared, plan.getDataCenterId(), plan.getPhysicalNetworkId()); vo.setTags(tags); networks.add(_networksDao.persist(vo, vo.getType() == Network.Type.Isolated)); @@ -1149,7 +1158,7 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag nics.add(vo); Integer networkRate = getNetworkRate(config.getId(), vm.getId()); - vm.addNic(new NicProfile(vo, network.first(), vo.getBroadcastUri(), vo.getIsolationUri(), networkRate)); + vm.addNic(new NicProfile(vo, network.first(), vo.getBroadcastUri(), vo.getIsolationUri(), networkRate, isSecurityGroupSupportedInNetwork(network.first()))); } if (nics.size() != networks.size()) { @@ -1397,7 +1406,7 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag URI isolationUri = nic.getIsolationUri(); - profile = new NicProfile(nic, network, broadcastUri, isolationUri, networkRate); + profile = new NicProfile(nic, network, broadcastUri, isolationUri, networkRate, isSecurityGroupSupportedInNetwork(network)); guru.reserve(profile, network, vmProfile, dest, context); nic.setIp4Address(profile.getIp4Address()); nic.setAddressFormat(profile.getFormat()); @@ -1416,7 +1425,7 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag updateNic(nic, network.getId(), 1); } else { - profile = new NicProfile(nic, network, nic.getBroadcastUri(), nic.getIsolationUri(), networkRate); + profile = new NicProfile(nic, network, nic.getBroadcastUri(), nic.getIsolationUri(), networkRate, isSecurityGroupSupportedInNetwork(network)); guru.updateNicProfile(profile, network); nic.setState(Nic.State.Reserved); updateNic(nic, network.getId(), 1); @@ -1428,7 +1437,8 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag } element.prepare(network, profile, vmProfile, dest, context); } - profile.setSecurityGroupEnabled(network.isSecurityGroupEnabled()); + + profile.setSecurityGroupEnabled(isServiceSupportedByNetworkOffering(network.getNetworkOfferingId(), Service.SecurityGroup)); guru.updateNicProfile(profile, network); vmProfile.addNic(profile); } @@ -1442,7 +1452,7 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag Integer networkRate = getNetworkRate(network.getId(), vm.getId()); NetworkGuru guru = _networkGurus.get(network.getGuruName()); - NicProfile profile = new NicProfile(nic, network, nic.getBroadcastUri(), nic.getIsolationUri(), networkRate); + NicProfile profile = new NicProfile(nic, network, nic.getBroadcastUri(), nic.getIsolationUri(), networkRate, isSecurityGroupSupportedInNetwork(network)); guru.updateNicProfile(profile, network); vm.addNic(profile); } @@ -1459,7 +1469,7 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag NetworkGuru guru = _networkGurus.get(network.getGuruName()); nic.setState(Nic.State.Releasing); _nicDao.update(nic.getId(), nic); - NicProfile profile = new NicProfile(nic, network, nic.getBroadcastUri(), nic.getIsolationUri(), null); + NicProfile profile = new NicProfile(nic, network, nic.getBroadcastUri(), nic.getIsolationUri(), null, isSecurityGroupSupportedInNetwork(network)); if (guru.release(profile, vmProfile, nic.getReservationId())) { applyProfileToNicForRelease(nic, profile); nic.setState(Nic.State.Allocated); @@ -1493,7 +1503,7 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag Integer networkRate = getNetworkRate(network.getId(), vm.getId()); NetworkGuru guru = _networkGurus.get(network.getGuruName()); - NicProfile profile = new NicProfile(nic, network, nic.getBroadcastUri(), nic.getIsolationUri(), networkRate); + NicProfile profile = new NicProfile(nic, network, nic.getBroadcastUri(), nic.getIsolationUri(), networkRate, isSecurityGroupSupportedInNetwork(network)); guru.updateNicProfile(profile, network); profiles.add(profile); } @@ -1595,7 +1605,7 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag nic.setState(Nic.State.Deallocating); _nicDao.update(nic.getId(), nic); NetworkVO network = _networksDao.findById(nic.getNetworkId()); - NicProfile profile = new NicProfile(nic, network, null, null, null); + NicProfile profile = new NicProfile(nic, network, null, null, null, isSecurityGroupSupportedInNetwork(network)); NetworkGuru guru = _networkGurus.get(network.getGuruName()); guru.deallocate(network, profile, vm); _nicDao.remove(nic.getId()); @@ -1876,7 +1886,6 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag DataCenterDeployment plan = new DataCenterDeployment(zoneId, null, null, null, null, physicalNetwork.getId()); NetworkVO userNetwork = new NetworkVO(); userNetwork.setNetworkDomain(networkDomain); - userNetwork.setSecurityGroupEnabled(isSecurityGroupEnabled); if (cidr != null && gateway != null) { userNetwork.setCidr(cidr); @@ -3420,8 +3429,8 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag NetworkOffering oldNetworkOffering = _networkOfferingDao.findByIdIncludingRemoved(oldNetworkOfferingId); NetworkOffering newNetworkOffering = _networkOfferingDao.findById(newNetworkOfferingId); - //security group property should be the same - if (oldNetworkOffering.isSecurityGroupEnabled() != newNetworkOffering.isSecurityGroupEnabled()) { + //security group service should be the same + if (isServiceSupportedByNetworkOffering(oldNetworkOfferingId, Service.SecurityGroup) != isServiceSupportedByNetworkOffering(newNetworkOfferingId, Service.SecurityGroup)) { s_logger.debug("Offerings " + newNetworkOfferingId + " and " + oldNetworkOfferingId + " have different securityGroupProperty, can't upgrade"); return false; } @@ -3506,6 +3515,12 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag int vnetStart = 0; int vnetEnd = 0; if (vnetRange != null) { + + //Verify zone type + if (zone.getNetworkType() == NetworkType.Basic && vnetRange != null) { + vnetRange = null; + } + String[] tokens = vnetRange.split("-"); try { vnetStart = Integer.parseInt(tokens[0]); @@ -3969,12 +3984,22 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag @Override public List listNetworkOfferingsForUpgrade(long networkId) { - + List offeringsToReturn = new ArrayList(); NetworkOffering originalOffering = _configMgr.getNetworkOffering(getNetwork(networkId).getNetworkOfferingId()); + boolean securityGroupSupportedByOriginalOff = isServiceSupportedByNetworkOffering(originalOffering.getId(), Service.SecurityGroup); + + //security group supported property should be the same + List offerings = _networkOfferingDao.getOfferingIdsToUpgradeFrom(originalOffering); - return offerings; + for (Long offeringId : offerings) { + if (isServiceSupportedByNetworkOffering(offeringId, Service.SecurityGroup) == securityGroupSupportedByOriginalOff) { + offeringsToReturn.add(offeringId); + } + } + + return offeringsToReturn; } @@ -4169,5 +4194,11 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag return success; } + @Override + public boolean isSecurityGroupSupportedInNetwork(Network network) { + boolean supported = isServiceSupportedByNetworkOffering(network.getNetworkOfferingId(), Service.SecurityGroup); + + return supported; + } } diff --git a/server/src/com/cloud/network/NetworkVO.java b/server/src/com/cloud/network/NetworkVO.java index 9928ec673b9..69169e226a9 100644 --- a/server/src/com/cloud/network/NetworkVO.java +++ b/server/src/com/cloud/network/NetworkVO.java @@ -143,9 +143,6 @@ public class NetworkVO implements Network { @Column(name="is_default") boolean isDefault; - @Column(name="is_security_group_enabled") - boolean securityGroupEnabled; - @ElementCollection(targetClass = String.class, fetch=FetchType.EAGER) @Column(name="tag") @CollectionTable(name="network_tags", joinColumns=@JoinColumn(name="network_id")) @@ -183,7 +180,7 @@ public class NetworkVO implements Network { this.id = -1; } - public NetworkVO(long id, Network that, long offeringId, String guruName, long domainId, long accountId, long related, String name, String displayText, boolean isDefault, boolean isSecurityGroupEnabled, boolean isDomainSpecific, String networkDomain, Type type, boolean isShared, long dcId, Long physicalNetworkId) { + public NetworkVO(long id, Network that, long offeringId, String guruName, long domainId, long accountId, long related, String name, String displayText, boolean isDefault, boolean isDomainSpecific, String networkDomain, Type type, boolean isShared, long dcId, Long physicalNetworkId) { this(id, that.getTrafficType(), that.getMode(), that.getBroadcastDomainType(), offeringId, domainId, accountId, related, name, displayText, isDefault,isDomainSpecific, networkDomain, type, isShared, dcId, physicalNetworkId); this.gateway = that.getGateway(); this.cidr = that.getCidr(); @@ -191,7 +188,6 @@ public class NetworkVO implements Network { this.broadcastDomainType = that.getBroadcastDomainType(); this.guruName = guruName; this.state = that.getState(); - this.securityGroupEnabled = isSecurityGroupEnabled; if (state == null) { state = State.Allocated; } @@ -430,15 +426,6 @@ public class NetworkVO implements Network { return isDefault; } - @Override - public boolean isSecurityGroupEnabled() { - return securityGroupEnabled; - } - - public void setSecurityGroupEnabled(boolean enabled) { - this.securityGroupEnabled = enabled; - } - public void setShared(boolean isShared) { this.isShared = isShared; } diff --git a/server/src/com/cloud/network/dao/NetworkDaoImpl.java b/server/src/com/cloud/network/dao/NetworkDaoImpl.java index c77d93b32c3..191498b190b 100644 --- a/server/src/com/cloud/network/dao/NetworkDaoImpl.java +++ b/server/src/com/cloud/network/dao/NetworkDaoImpl.java @@ -24,6 +24,7 @@ import javax.ejb.Local; import javax.persistence.TableGenerator; import com.cloud.network.Network; +import com.cloud.network.Network.Service; import com.cloud.network.NetworkAccountDaoImpl; import com.cloud.network.NetworkAccountVO; import com.cloud.network.NetworkDomainVO; @@ -31,6 +32,8 @@ import com.cloud.network.NetworkVO; import com.cloud.network.Networks.BroadcastDomainType; import com.cloud.network.Networks.Mode; import com.cloud.network.Networks.TrafficType; +import com.cloud.offerings.NetworkOfferingServiceMapVO; +import com.cloud.offerings.dao.NetworkOfferingServiceMapDaoImpl; import com.cloud.utils.component.ComponentLocator; import com.cloud.utils.db.DB; import com.cloud.utils.db.GenericDaoBase; @@ -60,6 +63,7 @@ public class NetworkDaoImpl extends GenericDaoBase implements N NetworkAccountDaoImpl _accountsDao = ComponentLocator.inject(NetworkAccountDaoImpl.class); NetworkDomainDaoImpl _domainsDao = ComponentLocator.inject(NetworkDomainDaoImpl.class); NetworkOpDaoImpl _opDao = ComponentLocator.inject(NetworkOpDaoImpl.class); + NetworkOfferingServiceMapDaoImpl _ntwkOffSvcMap = ComponentLocator.inject(NetworkOfferingServiceMapDaoImpl.class); final TableGenerator _tgMacAddress; Random _rand = new Random(System.currentTimeMillis()); @@ -112,7 +116,9 @@ public class NetworkDaoImpl extends GenericDaoBase implements N ZoneSecurityGroupSearch = createSearchBuilder(); ZoneSecurityGroupSearch.and("dataCenterId", ZoneSecurityGroupSearch.entity().getDataCenterId(), Op.EQ); - ZoneSecurityGroupSearch.and("securityGroup", ZoneSecurityGroupSearch.entity().isSecurityGroupEnabled(), Op.EQ); + SearchBuilder join1 = _ntwkOffSvcMap.createSearchBuilder(); + join1.and("service", join1.entity().getService(), Op.EQ); + ZoneSecurityGroupSearch.join("services", join1, ZoneSecurityGroupSearch.entity().getNetworkOfferingId(), join1.entity().getNetworkOfferingId(), JoinBuilder.JoinType.INNER); ZoneSecurityGroupSearch.done(); CountByOfferingId = createSearchBuilder(Long.class); @@ -127,7 +133,9 @@ public class NetworkDaoImpl extends GenericDaoBase implements N PhysicalNetworkSearch.done(); securityGroupSearch = createSearchBuilder(); - securityGroupSearch.and("isSgEnabled", securityGroupSearch.entity().isSecurityGroupEnabled(), SearchCriteria.Op.EQ); + SearchBuilder join3 = _ntwkOffSvcMap.createSearchBuilder(); + join3.and("service", join3.entity().getService(), Op.EQ); + securityGroupSearch.join("services", join3, securityGroupSearch.entity().getNetworkOfferingId(), join3.entity().getNetworkOfferingId(), JoinBuilder.JoinType.INNER); securityGroupSearch.done(); _tgMacAddress = _tgs.get("macAddress"); @@ -267,7 +275,7 @@ public class NetworkDaoImpl extends GenericDaoBase implements N if (zoneId != null) { sc.setParameters("dataCenterId", zoneId); } - sc.setParameters("securityGroup", true); + sc.setJoinParameters("services", "service", Service.SecurityGroup.toString()); return search(sc, null); } @@ -344,7 +352,7 @@ public class NetworkDaoImpl extends GenericDaoBase implements N @Override public List listSecurityGroupEnabledNetworks() { SearchCriteria sc = securityGroupSearch.create(); - sc.setParameters("isSgEnabled", true); + sc.setJoinParameters("services", "service", Service.SecurityGroup.toString()); return listBy(sc); } diff --git a/server/src/com/cloud/network/element/DhcpElement.java b/server/src/com/cloud/network/element/DhcpElement.java index cdb64ffd4ef..1d0149837d4 100644 --- a/server/src/com/cloud/network/element/DhcpElement.java +++ b/server/src/com/cloud/network/element/DhcpElement.java @@ -29,7 +29,6 @@ import com.cloud.api.commands.ConfigureDhcpElementCmd; import com.cloud.configuration.ConfigurationManager; import com.cloud.dc.DataCenter; import com.cloud.dc.DataCenter.NetworkType; -import com.cloud.dc.Pod; import com.cloud.dc.dao.HostPodDao; import com.cloud.deploy.DeployDestination; import com.cloud.exception.ConcurrentOperationException; @@ -45,13 +44,11 @@ import com.cloud.network.NetworkManager; import com.cloud.network.Networks.TrafficType; import com.cloud.network.dao.NetworkDao; import com.cloud.network.dao.VirtualRouterElementsDao; +import com.cloud.network.element.VirtualRouterElements.VirtualRouterElementsType; import com.cloud.network.router.VirtualNetworkApplianceManager; import com.cloud.network.router.VirtualRouter; import com.cloud.network.router.VirtualRouter.Role; -import com.cloud.network.element.DhcpElementService; -import com.cloud.network.element.VirtualRouterElements.VirtualRouterElementsType; import com.cloud.offering.NetworkOffering; -import com.cloud.org.Cluster; import com.cloud.user.AccountManager; import com.cloud.uservm.UserVm; import com.cloud.utils.component.AdapterBase; @@ -126,7 +123,7 @@ public class DhcpElement extends AdapterBase implements DhcpElementService, User //for Basic zone, add all Running routers - we have to send Dhcp/vmData/password info to them when network.dns.basiczone.updates is set to "all" Long podId = dest.getPod().getId(); DataCenter dc = dest.getDataCenter(); - boolean isPodBased = (dc.getNetworkType() == NetworkType.Basic || network.isSecurityGroupEnabled()) && network.getTrafficType() == TrafficType.Guest; + boolean isPodBased = (dc.getNetworkType() == NetworkType.Basic || _networkMgr.isSecurityGroupSupportedInNetwork(network)) && network.getTrafficType() == TrafficType.Guest; if (isPodBased && _routerMgr.getDnsBasicZoneUpdate().equalsIgnoreCase("all")) { List allRunningRoutersOutsideThePod = _routerDao.findByNetworkOutsideThePod(network.getId(), podId, State.Running, Role.DHCP_USERDATA); routers.addAll(allRunningRoutersOutsideThePod); diff --git a/server/src/com/cloud/network/element/SecurityGroupElement.java b/server/src/com/cloud/network/element/SecurityGroupElement.java new file mode 100644 index 00000000000..26226ecae56 --- /dev/null +++ b/server/src/com/cloud/network/element/SecurityGroupElement.java @@ -0,0 +1,82 @@ +/** + * * Copyright (C) 2011 Citrix Systems, Inc. All rights reserved +* + * + * This software is licensed under the GNU General Public License v3 or later. + * + * It is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or any later version. + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + */ + +package com.cloud.network.element; + +import java.util.Map; + +import javax.ejb.Local; + +import com.cloud.deploy.DeployDestination; +import com.cloud.exception.ConcurrentOperationException; +import com.cloud.exception.InsufficientCapacityException; +import com.cloud.exception.ResourceUnavailableException; +import com.cloud.network.Network; +import com.cloud.network.Network.Capability; +import com.cloud.network.Network.Provider; +import com.cloud.network.Network.Service; +import com.cloud.offering.NetworkOffering; +import com.cloud.utils.component.AdapterBase; +import com.cloud.utils.db.DB; +import com.cloud.vm.NicProfile; +import com.cloud.vm.ReservationContext; +import com.cloud.vm.VirtualMachine; +import com.cloud.vm.VirtualMachineProfile; + +@Local(value=NetworkElement.class) +public class SecurityGroupElement extends AdapterBase implements NetworkElement { + + @Override + public Map> getCapabilities() { + return null; + } + + @Override + public Provider getProvider() { + return null; + } + + @Override + public boolean implement(Network network, NetworkOffering offering, DeployDestination dest, ReservationContext context) + throws ConcurrentOperationException, ResourceUnavailableException, InsufficientCapacityException { + return true; + } + + @Override @DB + public boolean prepare(Network network, NicProfile nic, VirtualMachineProfile vm, DeployDestination dest, + ReservationContext context) throws ConcurrentOperationException, ResourceUnavailableException, InsufficientCapacityException { + return true; + } + + @Override + public boolean release(Network network, NicProfile nic, VirtualMachineProfile vm, ReservationContext context) + throws ConcurrentOperationException, ResourceUnavailableException { + return true; + } + + @Override + public boolean shutdown(Network network, ReservationContext context, boolean cleanup) throws ConcurrentOperationException, ResourceUnavailableException { + return true; + } + + @Override + public boolean destroy(Network network) throws ConcurrentOperationException, ResourceUnavailableException { + return true; + } +} diff --git a/server/src/com/cloud/network/guru/DirectNetworkGuru.java b/server/src/com/cloud/network/guru/DirectNetworkGuru.java index d0d226847c2..21ab47c6d2b 100644 --- a/server/src/com/cloud/network/guru/DirectNetworkGuru.java +++ b/server/src/com/cloud/network/guru/DirectNetworkGuru.java @@ -78,7 +78,7 @@ public class DirectNetworkGuru extends AdapterBase implements NetworkGuru { // this guru handles only non-system network with type=Shared and serviceNat service disabled //TODO - after broadCastDomainType + physical network are introduced, don't rely on network type of the dc if (dc.getNetworkType() == NetworkType.Advanced && offering.getType() == Network.Type.Shared && !_networkMgr.isServiceSupportedByNetworkOffering(offering.getId(), Service.SourceNat)&& offering.getTrafficType() == TrafficType.Guest) { - if (offering.isSecurityGroupEnabled()) { + if (_networkMgr.isServiceSupportedByNetworkOffering(offering.getId(), Service.SecurityGroup)) { return true; } else if (!offering.isSystemOnly()) { return true; @@ -110,8 +110,6 @@ public class DirectNetworkGuru extends AdapterBase implements NetworkGuru { throw new InvalidParameterValueException("cidr and gateway must be specified together."); } - config.setSecurityGroupEnabled(userSpecified.isSecurityGroupEnabled()); - if (userSpecified.getCidr() != null) { config.setCidr(userSpecified.getCidr()); config.setGateway(userSpecified.getGateway()); @@ -128,7 +126,8 @@ public class DirectNetworkGuru extends AdapterBase implements NetworkGuru { } - if (config.isSecurityGroupEnabled()) { + boolean isSecurityGroupEnabled = _networkMgr.isServiceSupportedByNetworkOffering(offering.getId(), Service.SecurityGroup); + if (isSecurityGroupEnabled) { config.setName("SecurityGroupEnabledNetwork"); config.setDisplayText("SecurityGroupEnabledNetwork"); } diff --git a/server/src/com/cloud/network/router/VirtualNetworkApplianceManagerImpl.java b/server/src/com/cloud/network/router/VirtualNetworkApplianceManagerImpl.java index 59bce7e92b0..628e17e4814 100755 --- a/server/src/com/cloud/network/router/VirtualNetworkApplianceManagerImpl.java +++ b/server/src/com/cloud/network/router/VirtualNetworkApplianceManagerImpl.java @@ -1253,7 +1253,7 @@ public class VirtualNetworkApplianceManagerImpl implements VirtualNetworkApplian DataCenterDeployment plan = null; DataCenter dc = dest.getDataCenter(); long dcId = dc.getId(); - boolean isPodBased = (dc.getNetworkType() == NetworkType.Basic || guestNetwork.isSecurityGroupEnabled()) && guestNetwork.getTrafficType() == TrafficType.Guest; + boolean isPodBased = (dc.getNetworkType() == NetworkType.Basic || _networkMgr.isServiceSupportedByNetworkOffering(guestNetwork.getNetworkOfferingId(), Service.SecurityGroup)) && guestNetwork.getTrafficType() == TrafficType.Guest; DomainRouterVO router = null; List routers = null; diff --git a/server/src/com/cloud/network/security/SecurityGroupManagerImpl.java b/server/src/com/cloud/network/security/SecurityGroupManagerImpl.java index 63516f0af63..b4783ec615f 100755 --- a/server/src/com/cloud/network/security/SecurityGroupManagerImpl.java +++ b/server/src/com/cloud/network/security/SecurityGroupManagerImpl.java @@ -63,6 +63,8 @@ import com.cloud.exception.OperationTimedoutException; import com.cloud.exception.PermissionDeniedException; import com.cloud.exception.ResourceInUseException; import com.cloud.hypervisor.Hypervisor.HypervisorType; +import com.cloud.network.Network; +import com.cloud.network.Network.Service; import com.cloud.network.NetworkManager; import com.cloud.network.security.SecurityGroupWork.Step; import com.cloud.network.security.dao.IngressRuleDao; @@ -1278,7 +1280,8 @@ public class SecurityGroupManagerImpl implements SecurityGroupManager, SecurityG VirtualMachine vm = _vmDao.findByIdIncludingRemoved(vmId); List nics = _networkMgr.getNicProfiles(vm); for (NicProfile nic : nics) { - if (nic.isSecurityGroupEnabled() && vm.getHypervisorType() != HypervisorType.VMware) { + Network network = _networkMgr.getNetwork(nic.getNetworkId()); + if (_networkMgr.isSecurityGroupSupportedInNetwork(network) && vm.getHypervisorType() != HypervisorType.VMware) { return true; } } diff --git a/server/src/com/cloud/offerings/NetworkOfferingVO.java b/server/src/com/cloud/offerings/NetworkOfferingVO.java index 44f4d7d0ba1..a576db469dc 100644 --- a/server/src/com/cloud/offerings/NetworkOfferingVO.java +++ b/server/src/com/cloud/offerings/NetworkOfferingVO.java @@ -90,10 +90,7 @@ public class NetworkOfferingVO implements NetworkOffering { @Column(name=GenericDao.CREATED_COLUMN) Date created; - - @Column(name="is_security_group_enabled") - boolean securityGroupEnabled; - + @Column(name="type") @Enumerated(value=EnumType.STRING) Network.Type type; @@ -189,11 +186,6 @@ public class NetworkOfferingVO implements NetworkOffering { public String getUniqueName() { return uniqueName; } - - @Override - public boolean isSecurityGroupEnabled() { - return securityGroupEnabled; - } @Override public void setState(State state) { @@ -204,18 +196,13 @@ public class NetworkOfferingVO implements NetworkOffering { public State getState() { return state; } - - @Override - public void setSecurityGroupEnabled(boolean securityGroupEnabled) { - this.securityGroupEnabled = securityGroupEnabled; - } @Override public Network.Type getType() { return type; } - public NetworkOfferingVO(String name, String displayText, TrafficType trafficType, boolean systemOnly, boolean specifyVlan, Integer rateMbps, Integer multicastRateMbps, Integer concurrentConnections, boolean isDefault, Availability availability, String tags, boolean isSecurityGroupEnabled, Network.Type type) { + public NetworkOfferingVO(String name, String displayText, TrafficType trafficType, boolean systemOnly, boolean specifyVlan, Integer rateMbps, Integer multicastRateMbps, Integer concurrentConnections, boolean isDefault, Availability availability, String tags, Network.Type type) { this.name = name; this.displayText = displayText; this.rateMbps = rateMbps; @@ -228,7 +215,6 @@ public class NetworkOfferingVO implements NetworkOffering { this.availability = availability; this.uniqueName = name; this.tags = tags; - this.securityGroupEnabled = isSecurityGroupEnabled; this.type = type; } @@ -241,7 +227,7 @@ public class NetworkOfferingVO implements NetworkOffering { * @param trafficType */ public NetworkOfferingVO(String name, TrafficType trafficType) { - this(name, "System Offering for " + name, trafficType, true, false, 0, 0, null, true, Availability.Required, null, false, null); + this(name, "System Offering for " + name, trafficType, true, false, 0, 0, null, true, Availability.Required, null, null); this.state = State.Enabled; this.type = Type.Shared; } diff --git a/server/src/com/cloud/offerings/dao/NetworkOfferingDaoImpl.java b/server/src/com/cloud/offerings/dao/NetworkOfferingDaoImpl.java index c1eb059cd70..577b16f0520 100644 --- a/server/src/com/cloud/offerings/dao/NetworkOfferingDaoImpl.java +++ b/server/src/com/cloud/offerings/dao/NetworkOfferingDaoImpl.java @@ -77,7 +77,6 @@ public class NetworkOfferingDaoImpl extends GenericDaoBase defaultDirectGuestNetworkOfferingProviders = new HashMap(); + defaultDirectGuestNetworkOfferingProviders.put(Service.Dhcp, Provider.DhcpServer); + defaultDirectGuestNetworkOfferingProviders.put(Service.Dns, Provider.DhcpServer); + defaultDirectGuestNetworkOfferingProviders.put(Service.UserData, Provider.DhcpServer); + defaultDirectGuestNetworkOfferingProviders.put(Service.SecurityGroup, Provider.SecurityGroupProvider); + Map defaultVirtualNetworkOfferingProviders = new HashMap(); defaultVirtualNetworkOfferingProviders.put(Service.Dhcp, Provider.VirtualRouter); defaultVirtualNetworkOfferingProviders.put(Service.Dns, Provider.VirtualRouter); @@ -853,14 +861,14 @@ public class ConfigurationServerImpl implements ConfigurationServer { "System-Guest-Network", TrafficType.Guest, true, false, null, null, null, true, - Availability.Optional, null, true, Network.Type.Shared); + Availability.Optional, null, Network.Type.Shared); guestNetworkOffering.setState(NetworkOffering.State.Enabled); guestNetworkOffering = _networkOfferingDao.persistDefaultNetworkOffering(guestNetworkOffering); - for (Service service : defaultDirectNetworkOfferingProviders.keySet()) { - NetworkOfferingServiceMapVO offService = new NetworkOfferingServiceMapVO(guestNetworkOffering.getId(), service, defaultDirectNetworkOfferingProviders.get(service)); + for (Service service : defaultDirectGuestNetworkOfferingProviders.keySet()) { + NetworkOfferingServiceMapVO offService = new NetworkOfferingServiceMapVO(guestNetworkOffering.getId(), service, defaultDirectGuestNetworkOfferingProviders.get(service)); _offeringServiceMapDao.persist(offService); s_logger.trace("Added service for the network offering: " + offService); } @@ -870,7 +878,7 @@ public class ConfigurationServerImpl implements ConfigurationServer { "Virtual Vlan", TrafficType.Guest, false, false, null, null, null, true, - Availability.Required, null, false, Network.Type.Isolated); + Availability.Required, null, Network.Type.Isolated); defaultGuestNetworkOffering.setState(NetworkOffering.State.Enabled); defaultGuestNetworkOffering = _networkOfferingDao.persistDefaultNetworkOffering(defaultGuestNetworkOffering); @@ -887,7 +895,7 @@ public class ConfigurationServerImpl implements ConfigurationServer { "Direct", TrafficType.Guest, false, true, null, null, null, true, - Availability.Optional, null, false, Network.Type.Shared); + Availability.Optional, null, Network.Type.Shared); defaultGuestDirectNetworkOffering.setState(NetworkOffering.State.Enabled); defaultGuestDirectNetworkOffering = _networkOfferingDao.persistDefaultNetworkOffering(defaultGuestDirectNetworkOffering); diff --git a/server/src/com/cloud/vm/UserVmManagerImpl.java b/server/src/com/cloud/vm/UserVmManagerImpl.java index e75b760df97..1d14cd01eff 100755 --- a/server/src/com/cloud/vm/UserVmManagerImpl.java +++ b/server/src/com/cloud/vm/UserVmManagerImpl.java @@ -424,7 +424,7 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, Manager } Network defaultNetwork = _networkDao.findById(defaultNic.getNetworkId()); - NicProfile defaultNicProfile = new NicProfile(defaultNic, defaultNetwork, null, null, null); + NicProfile defaultNicProfile = new NicProfile(defaultNic, defaultNetwork, null, null, null, _networkMgr.isSecurityGroupSupportedInNetwork(defaultNetwork)); VirtualMachineProfile vmProfile = new VirtualMachineProfileImpl(vmInstance); vmProfile.setParameter(VirtualMachineProfile.Param.VmPassword, password); @@ -2079,7 +2079,7 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, Manager throw new InvalidParameterValueException("Unable to find network by id " + networkIdList.get(0).longValue()); } - if (!network.isSecurityGroupEnabled()) { + if (!_networkMgr.isSecurityGroupSupportedInNetwork(network)) { throw new InvalidParameterValueException("Network is not security group enabled: " + network.getId()); } @@ -2096,11 +2096,12 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, Manager throw new InvalidParameterValueException("Unable to find network by id " + networkIdList.get(0).longValue()); } - if (network.isSecurityGroupEnabled() && networkIdList.size() > 1) { + boolean isSecurityGroupEnabled = _networkMgr.isServiceSupportedByNetworkOffering(network.getNetworkOfferingId(), Service.SecurityGroup); + if (isSecurityGroupEnabled && networkIdList.size() > 1) { throw new InvalidParameterValueException("Can't create a vm with multiple networks one of which is Security Group enabled"); } - if (network.getTrafficType() != TrafficType.Guest || network.getType() != Network.Type.Shared || (network.getType() == Network.Type.Shared && !network.isSecurityGroupEnabled())) { + if (network.getTrafficType() != TrafficType.Guest || network.getType() != Network.Type.Shared || (network.getType() == Network.Type.Shared && !isSecurityGroupEnabled)) { throw new InvalidParameterValueException("Can specify only Direct Guest Account specific networks when deploy vm in Security Group enabled zone"); } diff --git a/server/src/com/cloud/vm/VirtualMachineManagerImpl.java b/server/src/com/cloud/vm/VirtualMachineManagerImpl.java index b42747555c0..42a7051e422 100755 --- a/server/src/com/cloud/vm/VirtualMachineManagerImpl.java +++ b/server/src/com/cloud/vm/VirtualMachineManagerImpl.java @@ -42,10 +42,11 @@ import com.cloud.agent.api.AgentControlCommand; import com.cloud.agent.api.Answer; import com.cloud.agent.api.CheckVirtualMachineAnswer; import com.cloud.agent.api.CheckVirtualMachineCommand; +import com.cloud.agent.api.ClusterSyncAnswer; +import com.cloud.agent.api.ClusterSyncCommand; import com.cloud.agent.api.Command; import com.cloud.agent.api.MigrateAnswer; import com.cloud.agent.api.MigrateCommand; -import com.cloud.agent.api.PingRoutingCommand; import com.cloud.agent.api.PrepareForMigrationAnswer; import com.cloud.agent.api.PrepareForMigrationCommand; import com.cloud.agent.api.RebootAnswer; @@ -54,12 +55,9 @@ import com.cloud.agent.api.StartAnswer; import com.cloud.agent.api.StartCommand; import com.cloud.agent.api.StartupCommand; import com.cloud.agent.api.StartupRoutingCommand; -import com.cloud.agent.api.StartupRoutingCommand.VmState; import com.cloud.agent.api.StopAnswer; import com.cloud.agent.api.StopCommand; import com.cloud.agent.api.to.VirtualMachineTO; -import com.cloud.agent.api.ClusterSyncAnswer; -import com.cloud.agent.api.ClusterSyncCommand; import com.cloud.agent.manager.Commands; import com.cloud.agent.manager.allocator.HostAllocator; import com.cloud.alert.AlertManager; @@ -1838,7 +1836,7 @@ public class VirtualMachineManagerImpl implements VirtualMachineManager, Listene List nics = _nicsDao.listByVmId(profile.getId()); for (NicVO nic : nics) { Network network = _networkMgr.getNetwork(nic.getNetworkId()); - NicProfile nicProfile = new NicProfile(nic, network, nic.getBroadcastUri(), nic.getIsolationUri(), null); + NicProfile nicProfile = new NicProfile(nic, network, nic.getBroadcastUri(), nic.getIsolationUri(), null, _networkMgr.isSecurityGroupSupportedInNetwork(network)); profile.addNic(nicProfile); } diff --git a/setup/db/create-schema.sql b/setup/db/create-schema.sql index a73eb83ecf7..743f69f0a31 100755 --- a/setup/db/create-schema.sql +++ b/setup/db/create-schema.sql @@ -188,7 +188,6 @@ CREATE TABLE `cloud`.`networks` ( `is_default` int(1) unsigned NOT NULL DEFAULT 0 COMMENT '1 if network is default', `created` datetime NOT NULL COMMENT 'date created', `removed` datetime COMMENT 'date removed if not null', - `is_security_group_enabled` tinyint NOT NULL DEFAULT 0 COMMENT '1: enabled, 0: not', `type` char(32) COMMENT 'type of the network, can be Shared or Isolated', PRIMARY KEY (`id`), CONSTRAINT `fk_networks__network_offering_id` FOREIGN KEY (`network_offering_id`) REFERENCES `network_offerings`(`id`), @@ -264,7 +263,6 @@ CREATE TABLE `cloud`.`network_offerings` ( `default` int(1) unsigned NOT NULL DEFAULT 0 COMMENT '1 if network offering is default', `availability` varchar(255) NOT NULL COMMENT 'availability of the network', `shared_source_nat_service` int(1) unsigned NOT NULL DEFAULT 0 COMMENT 'true if the network offering provides the shared source nat service', - `is_security_group_enabled` tinyint NOT NULL DEFAULT 0 COMMENT '1: enabled, 0: not', `state` char(32) COMMENT 'state of the network offering; has Disabled value by default', `type` char(32) COMMENT 'type of the network offering, can be Shared or Isolated', PRIMARY KEY (`id`), @@ -500,6 +498,7 @@ CREATE TABLE `cloud`.`data_center` ( `userdata_provider` char(64) DEFAULT 'VirtualRouter', `allocation_state` varchar(32) NOT NULL DEFAULT 'Enabled' COMMENT 'Is this data center enabled for allocation for new resources', `zone_token` varchar(255), + `is_security_group_enabled` tinyint NOT NULL DEFAULT 0 COMMENT '1: enabled, 0: not', `removed` datetime COMMENT 'date removed if not null', PRIMARY KEY (`id`), CONSTRAINT `fk_data_center__domain_id` FOREIGN KEY (`domain_id`) REFERENCES `domain`(`id`), From d315e57b0e898171c57c139701fbc12411d9c87d Mon Sep 17 00:00:00 2001 From: alena Date: Thu, 27 Oct 2011 16:33:24 -0700 Subject: [PATCH 043/159] Renamed "type" to "guestType" --- api/src/com/cloud/api/ApiConstants.java | 1 + .../commands/CreateNetworkOfferingCmd.java | 8 +-- .../api/commands/ListNetworkOfferingsCmd.java | 8 +-- .../cloud/api/commands/ListNetworksCmd.java | 8 +-- .../api/response/NetworkOfferingResponse.java | 8 +-- .../cloud/api/response/NetworkResponse.java | 8 +-- api/src/com/cloud/network/Network.java | 4 +- api/src/com/cloud/network/NetworkProfile.java | 8 +-- .../com/cloud/offering/NetworkOffering.java | 4 +- .../manager/allocator/HostAllocator.java | 4 +- .../src/com/cloud/api/ApiResponseHelper.java | 4 +- .../baremetal/BareMetalVmManagerImpl.java | 2 +- .../configuration/ConfigurationManager.java | 2 +- .../ConfigurationManagerImpl.java | 20 +++--- .../ExternalNetworkDeviceManagerImpl.java | 2 +- .../src/com/cloud/network/NetworkManager.java | 2 +- .../com/cloud/network/NetworkManagerImpl.java | 72 +++++++++---------- .../network/NetworkUsageManagerImpl.java | 4 +- server/src/com/cloud/network/NetworkVO.java | 18 ++--- .../src/com/cloud/network/dao/NetworkDao.java | 2 +- .../com/cloud/network/dao/NetworkDaoImpl.java | 10 +-- .../cloud/network/element/DhcpElement.java | 12 ++-- .../element/ElasticLoadBalancerElement.java | 4 +- .../network/element/ExternalDhcpElement.java | 10 +-- .../F5ExternalLoadBalancerElement.java | 4 +- .../JuniperSRXExternalFirewallElement.java | 4 +- .../NetscalerExternalLoadBalancerElement.java | 4 +- .../RedundantVirtualRouterElement.java | 12 ++-- .../network/element/VirtualRouterElement.java | 28 ++++---- .../cloud/network/guru/DirectNetworkGuru.java | 2 +- .../cloud/network/guru/GuestNetworkGuru.java | 2 +- .../lb/ElasticLoadBalancerManagerImpl.java | 8 +-- .../VirtualNetworkApplianceManagerImpl.java | 10 +-- .../security/SecurityGroupManagerImpl.java | 2 +- .../cloud/offerings/NetworkOfferingVO.java | 15 ++-- .../offerings/dao/NetworkOfferingDao.java | 2 +- .../offerings/dao/NetworkOfferingDaoImpl.java | 10 +-- .../cloud/server/ConfigurationServerImpl.java | 8 +-- .../src/com/cloud/vm/UserVmManagerImpl.java | 14 ++-- .../src/com/cloud/vm/dao/DomainRouterDao.java | 2 +- .../com/cloud/vm/dao/DomainRouterDaoImpl.java | 10 +-- .../src/com/cloud/vm/dao/UserVmDaoImpl.java | 4 +- setup/db/create-schema.sql | 4 +- 43 files changed, 185 insertions(+), 185 deletions(-) diff --git a/api/src/com/cloud/api/ApiConstants.java b/api/src/com/cloud/api/ApiConstants.java index 36cae9779ef..dd4436e4d65 100755 --- a/api/src/com/cloud/api/ApiConstants.java +++ b/api/src/com/cloud/api/ApiConstants.java @@ -283,4 +283,5 @@ public class ApiConstants { public static final String DHCP_RANGE = "dhcprange"; public static final String UUID = "uuid"; public static final String SECURITY_GROUP_EANBLED = "securitygroupenabled"; + public static final String GUEST_IP_TYPE = "guestiptype"; } diff --git a/api/src/com/cloud/api/commands/CreateNetworkOfferingCmd.java b/api/src/com/cloud/api/commands/CreateNetworkOfferingCmd.java index f93929b7f53..98931176128 100644 --- a/api/src/com/cloud/api/commands/CreateNetworkOfferingCmd.java +++ b/api/src/com/cloud/api/commands/CreateNetworkOfferingCmd.java @@ -97,8 +97,8 @@ public class CreateNetworkOfferingCmd extends BaseCmd { @Parameter(name = ApiConstants.SERVICE_PROVIDER_LIST, type = CommandType.MAP, description = "provider to service mapping. If not specified, the provider for the service will be mapped to the default provider on the physical network") private Map serviceProviderList; - @Parameter(name=ApiConstants.TYPE, type=CommandType.STRING, required=true, description="type of the network offering: Shared or Isolated") - private String type; + @Parameter(name=ApiConstants.GUEST_IP_TYPE, type=CommandType.STRING, required=true, description="guest type of the network offering: Shared or Isolated") + private String guestIptype; ///////////////////////////////////////////////////// /////////////////// Accessors /////////////////////// @@ -176,8 +176,8 @@ public class CreateNetworkOfferingCmd extends BaseCmd { return vpnService == null ? false : vpnService; } - public String getType() { - return type; + public String getGuestIpType() { + return guestIptype; } public Map> getServiceProviders() { diff --git a/api/src/com/cloud/api/commands/ListNetworkOfferingsCmd.java b/api/src/com/cloud/api/commands/ListNetworkOfferingsCmd.java index f5cee89e212..a29f2cea0cb 100644 --- a/api/src/com/cloud/api/commands/ListNetworkOfferingsCmd.java +++ b/api/src/com/cloud/api/commands/ListNetworkOfferingsCmd.java @@ -74,8 +74,8 @@ public class ListNetworkOfferingsCmd extends BaseListCmd { @Parameter(name=ApiConstants.NETWORK_ID, type=CommandType.LONG, description="the ID of the network. Pass this in if you want to see the available network offering that a network can be changed to.") private Long networkId; - @Parameter(name=ApiConstants.TYPE, type=CommandType.STRING, description="list network offerings by type: Shared or Isolated") - private String type; + @Parameter(name=ApiConstants.GUEST_IP_TYPE, type=CommandType.STRING, description="list network offerings by guest type: Shared or Isolated") + private String guestIpType; ///////////////////////////////////////////////////// /////////////////// Accessors /////////////////////// @@ -125,8 +125,8 @@ public class ListNetworkOfferingsCmd extends BaseListCmd { return networkId; } - public String getType() { - return type; + public String getGuestIpType() { + return guestIpType; } ///////////////////////////////////////////////////// diff --git a/api/src/com/cloud/api/commands/ListNetworksCmd.java b/api/src/com/cloud/api/commands/ListNetworksCmd.java index 7ea6e9fbbd0..3cc770667d1 100644 --- a/api/src/com/cloud/api/commands/ListNetworksCmd.java +++ b/api/src/com/cloud/api/commands/ListNetworksCmd.java @@ -52,8 +52,8 @@ public class ListNetworksCmd extends BaseListCmd { @Parameter(name=ApiConstants.ZONE_ID, type=CommandType.LONG, description="the Zone ID of the network") private Long zoneId; - @Parameter(name=ApiConstants.TYPE, type=CommandType.STRING, description="the type of the network") - private String type; + @Parameter(name=ApiConstants.GUEST_IP_TYPE, type=CommandType.STRING, description="the guest type of the network") + private String guestIpType; @Parameter(name=ApiConstants.IS_SYSTEM, type=CommandType.BOOLEAN, description="true if network is system, false otherwise") private Boolean isSystem; @@ -93,8 +93,8 @@ public class ListNetworksCmd extends BaseListCmd { return zoneId; } - public String getType() { - return type; + public String getGuestIpType() { + return guestIpType; } public Boolean getIsSystem() { diff --git a/api/src/com/cloud/api/response/NetworkOfferingResponse.java b/api/src/com/cloud/api/response/NetworkOfferingResponse.java index 146b2116576..c418eae70f6 100644 --- a/api/src/com/cloud/api/response/NetworkOfferingResponse.java +++ b/api/src/com/cloud/api/response/NetworkOfferingResponse.java @@ -65,8 +65,8 @@ public class NetworkOfferingResponse extends BaseResponse{ @SerializedName(ApiConstants.STATE) @Param(description="state of the network offering. Can be Disabled/Enabled/Inactive") private String state; - @SerializedName(ApiConstants.TYPE) @Param(description="type of the network offering, can be Shared or Isolated") - private String type; + @SerializedName(ApiConstants.GUEST_IP_TYPE) @Param(description="guest type of the network offering, can be Shared or Isolated") + private String guestIpType; @SerializedName("service") @Param(description="the list of supported services", responseObject = ServiceResponse.class) private List services; @@ -127,7 +127,7 @@ public class NetworkOfferingResponse extends BaseResponse{ this.state = state; } - public void setType(String type) { - this.type = type; + public void setGuestIpType(String type) { + this.guestIpType = type; } } diff --git a/api/src/com/cloud/api/response/NetworkResponse.java b/api/src/com/cloud/api/response/NetworkResponse.java index 3a599bd7d60..fe9ff746e8a 100644 --- a/api/src/com/cloud/api/response/NetworkResponse.java +++ b/api/src/com/cloud/api/response/NetworkResponse.java @@ -90,8 +90,8 @@ public class NetworkResponse extends BaseResponse implements ControlledEntityRes @SerializedName(ApiConstants.DNS2) @Param(description="the second DNS for the network") private String dns2; - @SerializedName(ApiConstants.TYPE) @Param(description="the type of the network") - private String type; + @SerializedName(ApiConstants.GUEST_IP_TYPE) @Param(description="the guest type of the network") + private String guestIpType; @SerializedName(ApiConstants.VLAN) @Param(description="the vlan of the network") private String vlan; @@ -179,8 +179,8 @@ public class NetworkResponse extends BaseResponse implements ControlledEntityRes this.dns2 = dns2; } - public void setType(String type) { - this.type = type; + public void setGuestIpType(String type) { + this.guestIpType = type; } public void setAccountName(String accountName) { diff --git a/api/src/com/cloud/network/Network.java b/api/src/com/cloud/network/Network.java index 40609777134..5c99a487953 100644 --- a/api/src/com/cloud/network/Network.java +++ b/api/src/com/cloud/network/Network.java @@ -39,7 +39,7 @@ import com.cloud.utils.fsm.StateMachine; */ public interface Network extends ControlledEntity { - public enum Type { + public enum GuestType { Shared, Isolated } @@ -271,7 +271,7 @@ public interface Network extends ControlledEntity { List getTags(); - Type getType(); + GuestType getGuestType(); boolean getIsShared(); diff --git a/api/src/com/cloud/network/NetworkProfile.java b/api/src/com/cloud/network/NetworkProfile.java index eb4c119b7ae..6de9a4c8d91 100644 --- a/api/src/com/cloud/network/NetworkProfile.java +++ b/api/src/com/cloud/network/NetworkProfile.java @@ -48,7 +48,7 @@ public class NetworkProfile implements Network { private boolean isDefault; private String networkDomain; private List tags; - private Network.Type type; + private Network.GuestType guestType; private boolean isShared; private Long physicalNetworkId; @@ -71,7 +71,7 @@ public class NetworkProfile implements Network { this.isDefault = network.isDefault(); this.networkDomain = network.getNetworkDomain(); this.domainId = network.getDomainId(); - this.type = network.getType(); + this.guestType = network.getGuestType(); this.isShared = network.getIsShared(); this.physicalNetworkId = network.getPhysicalNetworkId(); } @@ -192,8 +192,8 @@ public class NetworkProfile implements Network { } @Override - public Network.Type getType(){ - return type; + public Network.GuestType getGuestType(){ + return guestType; } @Override diff --git a/api/src/com/cloud/offering/NetworkOffering.java b/api/src/com/cloud/offering/NetworkOffering.java index 481ae8d125e..09902b227cd 100644 --- a/api/src/com/cloud/offering/NetworkOffering.java +++ b/api/src/com/cloud/offering/NetworkOffering.java @@ -17,7 +17,7 @@ */ package com.cloud.offering; -import com.cloud.network.Network.Type; +import com.cloud.network.Network.GuestType; import com.cloud.network.Networks.TrafficType; /** @@ -92,5 +92,5 @@ public interface NetworkOffering { State getState(); - Type getType(); + GuestType getGuestType(); } diff --git a/server/src/com/cloud/agent/manager/allocator/HostAllocator.java b/server/src/com/cloud/agent/manager/allocator/HostAllocator.java index 1ee8a7dc765..134960fe129 100755 --- a/server/src/com/cloud/agent/manager/allocator/HostAllocator.java +++ b/server/src/com/cloud/agent/manager/allocator/HostAllocator.java @@ -45,7 +45,7 @@ public interface HostAllocator extends Adapter { * * @param VirtualMachineProfile vmProfile * @param DeploymentPlan plan - * @param Type type + * @param GuestType type * @param ExcludeList avoid * @param int returnUpTo (use -1 to return all possible hosts) * @return List List of hosts that are suitable for VM allocation @@ -59,7 +59,7 @@ public interface HostAllocator extends Adapter { * * @param VirtualMachineProfile vmProfile * @param DeploymentPlan plan - * @param Type type + * @param GuestType type * @param ExcludeList avoid * @param int returnUpTo (use -1 to return all possible hosts) * @param boolean considerReservedCapacity (default should be true, set to false if host capacity calculation should not look at reserved capacity) diff --git a/server/src/com/cloud/api/ApiResponseHelper.java b/server/src/com/cloud/api/ApiResponseHelper.java index 09249ee9549..e693a253aff 100755 --- a/server/src/com/cloud/api/ApiResponseHelper.java +++ b/server/src/com/cloud/api/ApiResponseHelper.java @@ -2109,8 +2109,8 @@ public class ApiResponseHelper implements ResponseGenerator { response.setSpecifyVlan(offering.getSpecifyVlan()); response.setAvailability(offering.getAvailability().toString()); response.setNetworkRate(ApiDBUtils.getNetworkRate(offering.getId())); - if (offering.getType() != null) { - response.setType(offering.getType().toString()); + if (offering.getGuestType() != null) { + response.setGuestIpType(offering.getGuestType().toString()); } response.setState(offering.getState().name()); diff --git a/server/src/com/cloud/baremetal/BareMetalVmManagerImpl.java b/server/src/com/cloud/baremetal/BareMetalVmManagerImpl.java index bcbbdf166b2..acfc02bed96 100755 --- a/server/src/com/cloud/baremetal/BareMetalVmManagerImpl.java +++ b/server/src/com/cloud/baremetal/BareMetalVmManagerImpl.java @@ -321,7 +321,7 @@ public class BareMetalVmManagerImpl extends UserVmManagerImpl implements BareMet if (network == null) { throw new InvalidParameterValueException("Unable to find network by id " + networkId); } else { - if (network.getType() != Network.Type.Shared) { + if (network.getGuestType() != Network.GuestType.Shared) { //Check account permissions List networkMap = _networkDao.listBy(accountId, networkId); if (networkMap == null || networkMap.isEmpty()) { diff --git a/server/src/com/cloud/configuration/ConfigurationManager.java b/server/src/com/cloud/configuration/ConfigurationManager.java index ce2e81bf0e2..58c8b25d996 100644 --- a/server/src/com/cloud/configuration/ConfigurationManager.java +++ b/server/src/com/cloud/configuration/ConfigurationManager.java @@ -185,7 +185,7 @@ public interface ConfigurationManager extends ConfigurationService, Manager { * @return network offering object */ - NetworkOfferingVO createNetworkOffering(long userId, String name, String displayText, TrafficType trafficType, String tags, Integer maxConnections, boolean specifyVlan, Availability availability, Integer networkRate, Map> serviceProviderMap, boolean isDefault, Network.Type type, boolean systemOnly); + NetworkOfferingVO createNetworkOffering(long userId, String name, String displayText, TrafficType trafficType, String tags, Integer maxConnections, boolean specifyVlan, Availability availability, Integer networkRate, Map> serviceProviderMap, boolean isDefault, Network.GuestType type, boolean systemOnly); Vlan createVlanAndPublicIpRange(Long userId, Long zoneId, Long podId, String startIP, String endIP, String vlanGateway, String vlanNetmask, boolean forVirtualNetwork, String vlanId, Account account, Long networkId) throws InsufficientCapacityException, ConcurrentOperationException, InvalidParameterValueException; diff --git a/server/src/com/cloud/configuration/ConfigurationManagerImpl.java b/server/src/com/cloud/configuration/ConfigurationManagerImpl.java index b1aa9b1ed00..23b379c927d 100755 --- a/server/src/com/cloud/configuration/ConfigurationManagerImpl.java +++ b/server/src/com/cloud/configuration/ConfigurationManagerImpl.java @@ -1862,7 +1862,7 @@ public class ConfigurationManagerImpl implements ConfigurationManager, Configura if (network == null) { // find default public network in the zone networkId = _networkMgr.getSystemNetworkByZoneAndTrafficType(zoneId, TrafficType.Public).getId(); - } else if (network.getType() != null || network.getTrafficType() != TrafficType.Public) { + } else if (network.getGuestType() != null || network.getTrafficType() != TrafficType.Public) { throw new InvalidParameterValueException("Can't find Public network by id=" + networkId); } } else { @@ -1876,8 +1876,8 @@ public class ConfigurationManagerImpl implements ConfigurationManager, Configura } networkId = network.getId(); } - } else if (network.getType() == null || network.getType()== Network.Type.Isolated) { - throw new InvalidParameterValueException("Can't create direct vlan for network id=" + networkId + " with type: " + network.getType()); + } else if (network.getGuestType() == null || network.getGuestType()== Network.GuestType.Isolated) { + throw new InvalidParameterValueException("Can't create direct vlan for network id=" + networkId + " with type: " + network.getGuestType()); } } @@ -2715,7 +2715,7 @@ public class ConfigurationManagerImpl implements ConfigurationManager, Configura TrafficType trafficType = null; Availability availability = null; - Network.Type type = null; + Network.GuestType type = null; // Verify traffic type for (TrafficType tType : TrafficType.values()) { @@ -2730,8 +2730,8 @@ public class ConfigurationManagerImpl implements ConfigurationManager, Configura //Verify offering type - for (Network.Type offType : Network.Type.values()) { - if (offType.name().equalsIgnoreCase(cmd.getType())){ + for (Network.GuestType offType : Network.GuestType.values()) { + if (offType.name().equalsIgnoreCase(cmd.getGuestIpType())){ type = offType; break; } @@ -2820,7 +2820,7 @@ public class ConfigurationManagerImpl implements ConfigurationManager, Configura @Override @DB public NetworkOfferingVO createNetworkOffering(long userId, String name, String displayText, TrafficType trafficType, String tags, Integer maxConnections, boolean specifyVlan, - Availability availability, Integer networkRate, Map> serviceProviderMap, boolean isDefault, Network.Type type, boolean systemOnly) { + Availability availability, Integer networkRate, Map> serviceProviderMap, boolean isDefault, Network.GuestType type, boolean systemOnly) { String multicastRateStr = _configDao.getValue("multicast.throttling.rate"); int multicastRate = ((multicastRateStr == null) ? 10 : Integer.parseInt(multicastRateStr)); @@ -2869,7 +2869,7 @@ public class ConfigurationManagerImpl implements ConfigurationManager, Configura Long zoneId = cmd.getZoneId(); DataCenter zone = null; Long networkId = cmd.getNetworkId(); - String type = cmd.getType(); + String guestIpType = cmd.getGuestIpType(); if (zoneId != null) { zone = getZone(zoneId); @@ -2889,8 +2889,8 @@ public class ConfigurationManagerImpl implements ConfigurationManager, Configura sc.addAnd("name", SearchCriteria.Op.LIKE, "%" + name + "%"); } - if (type != null) { - sc.addAnd("type", SearchCriteria.Op.EQ, type); + if (guestIpType != null) { + sc.addAnd("guestType", SearchCriteria.Op.EQ, guestIpType); } if (displayText != null) { diff --git a/server/src/com/cloud/network/ExternalNetworkDeviceManagerImpl.java b/server/src/com/cloud/network/ExternalNetworkDeviceManagerImpl.java index 0ff220cc9c3..b93d6abfbc2 100644 --- a/server/src/com/cloud/network/ExternalNetworkDeviceManagerImpl.java +++ b/server/src/com/cloud/network/ExternalNetworkDeviceManagerImpl.java @@ -1458,7 +1458,7 @@ public class ExternalNetworkDeviceManagerImpl implements ExternalNetworkDeviceMa try { txn.start(); - List networksForAccount = _networkDao.listBy(accountId, zoneId, Network.Type.Isolated); + List networksForAccount = _networkDao.listBy(accountId, zoneId, Network.GuestType.Isolated); for (NetworkVO network : networksForAccount) { String networkErrorMsg = accountErrorMsg + ", network ID = " + network.getId(); diff --git a/server/src/com/cloud/network/NetworkManager.java b/server/src/com/cloud/network/NetworkManager.java index 0fd4ad1ea6c..a49091550ac 100644 --- a/server/src/com/cloud/network/NetworkManager.java +++ b/server/src/com/cloud/network/NetworkManager.java @@ -201,7 +201,7 @@ public interface NetworkManager extends NetworkService { String getIpOfNetworkElementInVirtualNetwork(long accountId, long dataCenterId); - List listNetworksForAccount(long accountId, long zoneId, Network.Type type, Boolean isDefault); + List listNetworksForAccount(long accountId, long zoneId, Network.GuestType type, Boolean isDefault); IPAddressVO markIpAsUnavailable(long addrId); diff --git a/server/src/com/cloud/network/NetworkManagerImpl.java b/server/src/com/cloud/network/NetworkManagerImpl.java index f63c95d4913..ab210fd5da6 100755 --- a/server/src/com/cloud/network/NetworkManagerImpl.java +++ b/server/src/com/cloud/network/NetworkManagerImpl.java @@ -574,7 +574,7 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag @Override public List getIsolatedNetworksOwnedByAccountInZone(long zoneId, Account owner) { - return _networksDao.listBy(owner.getId(), zoneId, Network.Type.Isolated); + return _networksDao.listBy(owner.getId(), zoneId, Network.GuestType.Isolated); } @Override @@ -674,7 +674,7 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag // First IP address should be source nat when it's being associated with Guest Virtual network List addrs = listPublicIpAddressesInVirtualNetwork(ownerId, zoneId, true, networkId); - if (addrs.isEmpty() && network.getType() == Network.Type.Isolated) { + if (addrs.isEmpty() && network.getGuestType() == Network.GuestType.Isolated) { isSourceNat = true; } } @@ -854,19 +854,19 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag //check that offering already exists NetworkOfferingVO offering = null; if (_networkOfferingDao.findByUniqueName(NetworkOffering.SystemGuestNetwork) == null) { - offering = _configMgr.createNetworkOffering(Account.ACCOUNT_ID_SYSTEM, NetworkOffering.SystemGuestNetwork, "System Offering for System-Guest-Network", TrafficType.Guest, null, null, false, Availability.Optional, null, defaultDirectNetworkOfferingProviders, true, Network.Type.Shared, true); + offering = _configMgr.createNetworkOffering(Account.ACCOUNT_ID_SYSTEM, NetworkOffering.SystemGuestNetwork, "System Offering for System-Guest-Network", TrafficType.Guest, null, null, false, Availability.Optional, null, defaultDirectNetworkOfferingProviders, true, Network.GuestType.Shared, true); offering.setState(NetworkOffering.State.Enabled); _networkOfferingDao.update(offering.getId(), offering); } if (_networkOfferingDao.findByUniqueName(NetworkOffering.DefaultVirtualizedNetworkOffering) == null) { - offering = _configMgr.createNetworkOffering(Account.ACCOUNT_ID_SYSTEM,NetworkOffering.DefaultVirtualizedNetworkOffering, "Virtual Vlan", TrafficType.Guest, null, null, false, Availability.Required, null, defaultVirtualNetworkOfferingProviders, true, Network.Type.Isolated, false); + offering = _configMgr.createNetworkOffering(Account.ACCOUNT_ID_SYSTEM,NetworkOffering.DefaultVirtualizedNetworkOffering, "Virtual Vlan", TrafficType.Guest, null, null, false, Availability.Required, null, defaultVirtualNetworkOfferingProviders, true, Network.GuestType.Isolated, false); offering.setState(NetworkOffering.State.Enabled); _networkOfferingDao.update(offering.getId(), offering); } if (_networkOfferingDao.findByUniqueName(NetworkOffering.DefaultDirectNetworkOffering) == null) { - offering = _configMgr.createNetworkOffering(Account.ACCOUNT_ID_SYSTEM, NetworkOffering.DefaultDirectNetworkOffering, "Direct", TrafficType.Guest, null, null, true, Availability.Optional, null, defaultDirectNetworkOfferingProviders, true, Network.Type.Shared, false); + offering = _configMgr.createNetworkOffering(Account.ACCOUNT_ID_SYSTEM, NetworkOffering.DefaultDirectNetworkOffering, "Direct", TrafficType.Guest, null, null, true, Availability.Optional, null, defaultDirectNetworkOfferingProviders, true, Network.GuestType.Shared, false); offering.setState(NetworkOffering.State.Enabled); _networkOfferingDao.update(offering.getId(), offering); } @@ -1059,9 +1059,9 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag } NetworkVO vo = new NetworkVO(id, network, offering.getId(), guru.getName(), owner.getDomainId(), owner.getId(), related, name, displayText, isDefault, - (domainId != null), predefined.getNetworkDomain(), offering.getType(), isShared, plan.getDataCenterId(), plan.getPhysicalNetworkId()); + (domainId != null), predefined.getNetworkDomain(), offering.getGuestType(), isShared, plan.getDataCenterId(), plan.getPhysicalNetworkId()); vo.setTags(tags); - networks.add(_networksDao.persist(vo, vo.getType() == Network.Type.Isolated)); + networks.add(_networksDao.persist(vo, vo.getGuestType() == Network.GuestType.Isolated)); if (domainId != null) { _networksDao.addDomainToNetwork(id, domainId); @@ -1332,7 +1332,7 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag } } - if (network.getType() == Network.Type.Isolated && isServiceSupportedByNetworkOffering(network.getNetworkOfferingId(), Service.SourceNat) && !sharedSourceNat) { + if (network.getGuestType() == Network.GuestType.Isolated && isServiceSupportedByNetworkOffering(network.getNetworkOfferingId(), Service.SourceNat) && !sharedSourceNat) { List ips = _ipAddressDao.listByAssociatedNetwork(network.getId(), true); if (ips.isEmpty()) { @@ -1659,8 +1659,8 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag // Check if the network is domain specific if (cmd.getDomainId() != null && cmd.getAccountName() == null) { - if (networkOffering.getTrafficType() != TrafficType.Guest || networkOffering.getType() != Network.Type.Shared) { - throw new InvalidParameterValueException("Domain level networks are supported just for traffic type " + TrafficType.Guest + " and type " + Network.Type.Shared); + if (networkOffering.getTrafficType() != TrafficType.Guest || networkOffering.getGuestType() != Network.GuestType.Shared) { + throw new InvalidParameterValueException("Domain level networks are supported just for traffic type " + TrafficType.Guest + " and type " + Network.GuestType.Shared); } else if (isShared == null || !isShared) { throw new InvalidParameterValueException("Network dedicated to domain should be shared"); } else { @@ -1736,9 +1736,9 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag } // Regular user can create Guest Isolated network only - if (caller.getType() == Account.ACCOUNT_TYPE_NORMAL && (networkOffering.getTrafficType() != TrafficType.Guest || networkOffering.getType() != Network.Type.Isolated)) { + if (caller.getType() == Account.ACCOUNT_TYPE_NORMAL && (networkOffering.getTrafficType() != TrafficType.Guest || networkOffering.getGuestType() != Network.GuestType.Isolated)) { throw new InvalidParameterValueException("Regular user can create a network only from the network offering having traffic type " + TrafficType.Guest + " and network type " - + Network.Type.Isolated); + + Network.GuestType.Isolated); } // Don't allow to specify cidr if the caller is a regular user @@ -1768,11 +1768,11 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag // Don't pass owner to create vlan when network offering is of type Shared - done to prevent accountVlanMap entry // creation when vlan is mapped to network - if (network.getType() == Network.Type.Shared) { + if (network.getGuestType() == Network.GuestType.Shared) { owner = null; } - if (caller.getType() == Account.ACCOUNT_TYPE_ADMIN && network.getType() == Network.Type.Shared && defineNetworkConfig) { + if (caller.getType() == Account.ACCOUNT_TYPE_ADMIN && network.getGuestType() == Network.GuestType.Shared && defineNetworkConfig) { // Create vlan ip range _configMgr.createVlanAndPublicIpRange(userId, pNtwk.getDataCenterId(), null, startIP, endIP, gateway, netmask, false, vlanId, owner, network.getId()); } @@ -1792,14 +1792,14 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag long zoneId = zone.getId(); // allow isDefault to be set only for Shared network - if (networkOffering.getType() == Network.Type.Isolated) { + if (networkOffering.getGuestType() == Network.GuestType.Isolated) { if (isDefault != null && !isDefault) { - throw new InvalidParameterValueException("Can specify isDefault parameter only for network of type " + Network.Type.Shared); + throw new InvalidParameterValueException("Can specify isDefault parameter only for network of type " + Network.GuestType.Shared); } else { isDefault = true; } if (isShared != null && isShared) { - throw new InvalidParameterValueException("Can specify isShared parameter for " + Network.Type.Shared + " networks only"); + throw new InvalidParameterValueException("Can specify isShared parameter for " + Network.GuestType.Shared + " networks only"); } } else { if (isDefault == null) { @@ -1826,8 +1826,8 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag } // Don't allow to create guest isolated network with Vlan specified - if (networkOffering.getType() == Network.Type.Isolated && vlanId != null) { - throw new InvalidParameterValueException("Can't specify vlan when create " + Network.Type.Isolated + " network"); + if (networkOffering.getGuestType() == Network.GuestType.Isolated && vlanId != null) { + throw new InvalidParameterValueException("Can't specify vlan when create " + Network.GuestType.Isolated + " network"); } // If networkDomain is not specified, take it from the global configuration @@ -1869,12 +1869,12 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag // Cidr for Direct network can't be NULL - 2.2.x limitation, remove after we introduce support for multiple ip ranges // with different Cidrs for the same Shared network - if (cidr == null && networkOffering.getTrafficType() == TrafficType.Guest && networkOffering.getType() == Network.Type.Shared) { + if (cidr == null && networkOffering.getTrafficType() == TrafficType.Guest && networkOffering.getGuestType() == Network.GuestType.Shared) { throw new InvalidParameterValueException("StartIp/endIp/gateway/netmask are required for Direct network creation"); } // Check if cidr is RFC1918 compliant if the network is Guest Isolated - if (cidr != null && networkOffering.getType() == Network.Type.Isolated && networkOffering.getTrafficType() == TrafficType.Guest) { + if (cidr != null && networkOffering.getGuestType() == Network.GuestType.Isolated && networkOffering.getTrafficType() == TrafficType.Guest) { if (!NetUtils.validateGuestCidr(cidr)) { throw new InvalidParameterValueException("Virtual Guest Cidr " + cidr + " is not RFC1918 compliant"); } @@ -1907,7 +1907,7 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag if (networks == null || networks.isEmpty()) { throw new CloudRuntimeException("Fail to create a network"); } else { - if (networks.size() > 0 && networks.get(0).getType()== Network.Type.Isolated && networks.get(0).getTrafficType() == TrafficType.Guest) { + if (networks.size() > 0 && networks.get(0).getGuestType()== Network.GuestType.Isolated && networks.get(0).getTrafficType() == TrafficType.Guest) { Network defaultGuestNetwork = networks.get(0); for (Network nw : networks) { if (nw.getCidr() != null && nw.getCidr().equals(zone.getGuestNetworkCidr())) { @@ -1933,7 +1933,7 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag Account caller = UserContext.current().getCaller(); Long domainId = cmd.getDomainId(); String accountName = cmd.getAccountName(); - String type = cmd.getType(); + String guestIpType = cmd.getGuestIpType(); String trafficType = cmd.getTrafficType(); Boolean isSystem = cmd.getIsSystem(); Boolean isShared = cmd.getIsShared(); @@ -2032,27 +2032,27 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag List networksToReturn = new ArrayList(); if (sharedNetworkDomainId != null) { - networksToReturn.addAll(listDomainLevelNetworks(buildNetworkSearchCriteria(sb, keyword, id, isSystem, zoneId, type, isDefault, trafficType, isShared, physicalNetworkId), searchFilter, sharedNetworkDomainId)); + networksToReturn.addAll(listDomainLevelNetworks(buildNetworkSearchCriteria(sb, keyword, id, isSystem, zoneId, guestIpType, isDefault, trafficType, isShared, physicalNetworkId), searchFilter, sharedNetworkDomainId)); } else { SearchBuilder domainSearch = _domainDao.createSearchBuilder(); domainSearch.and("path", domainSearch.entity().getPath(), SearchCriteria.Op.LIKE); sb.join("domainSearch", domainSearch, sb.entity().getDomainId(), domainSearch.entity().getId(), JoinBuilder.JoinType.INNER); - networksToReturn.addAll(listDomainSpecificNetworks(buildNetworkSearchCriteria(sb, keyword, id, isSystem, zoneId, type, isDefault, trafficType, isShared, physicalNetworkId), searchFilter, path)); + networksToReturn.addAll(listDomainSpecificNetworks(buildNetworkSearchCriteria(sb, keyword, id, isSystem, zoneId, guestIpType, isDefault, trafficType, isShared, physicalNetworkId), searchFilter, path)); } //if user requested only domain specific networks, don't return account/zone wide networks if (!permittedAccounts.isEmpty() || (domainId == null && accountName == null && projectId == null)) { - networksToReturn.addAll(listAccountSpecificAndZoneLevelNetworks(buildNetworkSearchCriteria(sb, keyword, id, isSystem, zoneId, type, isDefault, trafficType, isShared, physicalNetworkId), searchFilter, path, permittedAccounts)); + networksToReturn.addAll(listAccountSpecificAndZoneLevelNetworks(buildNetworkSearchCriteria(sb, keyword, id, isSystem, zoneId, guestIpType, isDefault, trafficType, isShared, physicalNetworkId), searchFilter, path, permittedAccounts)); } return networksToReturn; } else { - return _networksDao.search(buildNetworkSearchCriteria(sb, keyword, id, isSystem, zoneId, type, isDefault, trafficType, isShared, physicalNetworkId), searchFilter); + return _networksDao.search(buildNetworkSearchCriteria(sb, keyword, id, isSystem, zoneId, guestIpType, isDefault, trafficType, isShared, physicalNetworkId), searchFilter); } } - private SearchCriteria buildNetworkSearchCriteria(SearchBuilder sb, String keyword, Long id, Boolean isSystem, Long zoneId, String type, Boolean isDefault, String trafficType, Boolean isShared, Long physicalNetworkId) { + private SearchCriteria buildNetworkSearchCriteria(SearchBuilder sb, String keyword, Long id, Boolean isSystem, Long zoneId, String guestIpType, Boolean isDefault, String trafficType, Boolean isShared, Long physicalNetworkId) { SearchCriteria sc = sb.create(); if (isSystem != null) { @@ -2073,8 +2073,8 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag sc.addAnd("dataCenterId", SearchCriteria.Op.EQ, zoneId); } - if (type != null) { - sc.addAnd("guestType", SearchCriteria.Op.EQ, type); + if (guestIpType != null) { + sc.addAnd("guestType", SearchCriteria.Op.EQ, guestIpType); } if (isDefault != null) { @@ -3011,7 +3011,7 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag @Override public String getIpOfNetworkElementInVirtualNetwork(long accountId, long dataCenterId) { - List virtualNetworks = _networksDao.listBy(accountId, dataCenterId, Network.Type.Isolated); + List virtualNetworks = _networksDao.listBy(accountId, dataCenterId, Network.GuestType.Isolated); if (virtualNetworks.isEmpty()) { s_logger.trace("Unable to find default Virtual network account id=" + accountId); @@ -3031,15 +3031,15 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag } @Override - public List listNetworksForAccount(long accountId, long zoneId, Network.Type type, Boolean isDefault) { + public List listNetworksForAccount(long accountId, long zoneId, Network.GuestType type, Boolean isDefault) { List accountNetworks = new ArrayList(); List zoneNetworks = _networksDao.listByZone(zoneId); for (NetworkVO network : zoneNetworks) { NetworkOfferingVO no = _networkOfferingDao.findById(network.getNetworkOfferingId()); if (!no.isSystemOnly()) { - if (network.getType() == Network.Type.Shared || !_networksDao.listBy(accountId, network.getId()).isEmpty()) { - if ((type == null || type == network.getType()) && (isDefault == null || isDefault.booleanValue() == network.isDefault)) { + if (network.getGuestType() == Network.GuestType.Shared || !_networksDao.listBy(accountId, network.getId()).isEmpty()) { + if ((type == null || type == network.getGuestType()) && (isDefault == null || isDefault.booleanValue() == network.isDefault)) { accountNetworks.add(network); } } @@ -3093,7 +3093,7 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag public boolean isNetworkAvailableInDomain(long networkId, long domainId) { Long networkDomainId = null; Network network = getNetwork(networkId); - if (network.getType() != Network.Type.Shared) { + if (network.getGuestType() != Network.GuestType.Shared) { s_logger.trace("Network id=" + networkId + " is not shared"); return false; } @@ -3436,7 +3436,7 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag } //Type of the network should be the same - if (oldNetworkOffering.getType() != newNetworkOffering.getType()){ + if (oldNetworkOffering.getGuestType() != newNetworkOffering.getGuestType()){ s_logger.debug("Network offerings " + newNetworkOfferingId + " and " + oldNetworkOfferingId + " are of different types, can't upgrade"); return false; } diff --git a/server/src/com/cloud/network/NetworkUsageManagerImpl.java b/server/src/com/cloud/network/NetworkUsageManagerImpl.java index 664e9f7a8c1..7687fac5013 100644 --- a/server/src/com/cloud/network/NetworkUsageManagerImpl.java +++ b/server/src/com/cloud/network/NetworkUsageManagerImpl.java @@ -214,7 +214,7 @@ public class NetworkUsageManagerImpl implements NetworkUsageManager { AllocatedIpSearch.and("allocated", AllocatedIpSearch.entity().getAllocatedTime(), Op.NNULL); AllocatedIpSearch.and("dc", AllocatedIpSearch.entity().getDataCenterId(), Op.EQ); SearchBuilder networkJoin = _networksDao.createSearchBuilder(); - networkJoin.and("type", networkJoin.entity().getType(), Op.EQ); + networkJoin.and("guestType", networkJoin.entity().getGuestType(), Op.EQ); AllocatedIpSearch.join("network", networkJoin, AllocatedIpSearch.entity().getSourceNetworkId(), networkJoin.entity().getId(), JoinBuilder.JoinType.INNER); AllocatedIpSearch.done(); @@ -242,7 +242,7 @@ public class NetworkUsageManagerImpl implements NetworkUsageManager { public List listAllocatedDirectIps(long zoneId) { SearchCriteria sc = AllocatedIpSearch.create(); sc.setParameters("dc", zoneId); - sc.setJoinParameters("network", "type", Network.Type.Shared); + sc.setJoinParameters("network", "guestType", Network.GuestType.Shared); return _ipAddressDao.search(sc, null); } diff --git a/server/src/com/cloud/network/NetworkVO.java b/server/src/com/cloud/network/NetworkVO.java index 69169e226a9..14f9a1ed208 100644 --- a/server/src/com/cloud/network/NetworkVO.java +++ b/server/src/com/cloud/network/NetworkVO.java @@ -148,9 +148,9 @@ public class NetworkVO implements Network { @CollectionTable(name="network_tags", joinColumns=@JoinColumn(name="network_id")) List tags; - @Column(name="type") + @Column(name="guest_type") @Enumerated(value=EnumType.STRING) - Network.Type type; + Network.GuestType guestType; public NetworkVO() { } @@ -180,8 +180,8 @@ public class NetworkVO implements Network { this.id = -1; } - public NetworkVO(long id, Network that, long offeringId, String guruName, long domainId, long accountId, long related, String name, String displayText, boolean isDefault, boolean isDomainSpecific, String networkDomain, Type type, boolean isShared, long dcId, Long physicalNetworkId) { - this(id, that.getTrafficType(), that.getMode(), that.getBroadcastDomainType(), offeringId, domainId, accountId, related, name, displayText, isDefault,isDomainSpecific, networkDomain, type, isShared, dcId, physicalNetworkId); + public NetworkVO(long id, Network that, long offeringId, String guruName, long domainId, long accountId, long related, String name, String displayText, boolean isDefault, boolean isDomainSpecific, String networkDomain, GuestType guestType, boolean isShared, long dcId, Long physicalNetworkId) { + this(id, that.getTrafficType(), that.getMode(), that.getBroadcastDomainType(), offeringId, domainId, accountId, related, name, displayText, isDefault,isDomainSpecific, networkDomain, guestType, isShared, dcId, physicalNetworkId); this.gateway = that.getGateway(); this.cidr = that.getCidr(); this.broadcastUri = that.getBroadcastUri(); @@ -206,12 +206,12 @@ public class NetworkVO implements Network { * @param isDefault * @param isDomainSpecific * @param networkDomain - * @param type TODO + * @param guestType TODO * @param isShared TODO * @param isShared * @param dataCenterId */ - public NetworkVO(long id, TrafficType trafficType, Mode mode, BroadcastDomainType broadcastDomainType, long networkOfferingId, long domainId, long accountId, long related, String name, String displayText, boolean isDefault, boolean isDomainSpecific, String networkDomain, Type type, boolean isShared, long dcId, Long physicalNetworkId) { + public NetworkVO(long id, TrafficType trafficType, Mode mode, BroadcastDomainType broadcastDomainType, long networkOfferingId, long domainId, long accountId, long related, String name, String displayText, boolean isDefault, boolean isDomainSpecific, String networkDomain, GuestType guestType, boolean isShared, long dcId, Long physicalNetworkId) { this(trafficType, mode, broadcastDomainType, networkOfferingId, State.Allocated, dcId, physicalNetworkId); this.domainId = domainId; this.accountId = accountId; @@ -222,7 +222,7 @@ public class NetworkVO implements Network { this.isDefault = isDefault; this.isDomainSpecific = isDomainSpecific; this.networkDomain = networkDomain; - this.type = type; + this.guestType = guestType; this.isShared = isShared; } @@ -451,8 +451,8 @@ public class NetworkVO implements Network { } @Override - public Network.Type getType() { - return type; + public Network.GuestType getGuestType() { + return guestType; } @Override diff --git a/server/src/com/cloud/network/dao/NetworkDao.java b/server/src/com/cloud/network/dao/NetworkDao.java index d2cdb39799b..b099dbef39e 100644 --- a/server/src/com/cloud/network/dao/NetworkDao.java +++ b/server/src/com/cloud/network/dao/NetworkDao.java @@ -30,7 +30,7 @@ public interface NetworkDao extends GenericDao { List listByOwner(long ownerId); List listBy(long accountId, long offeringId, long dataCenterId); List listBy(long accountId, long offeringId, long dataCenterId, String cidr); - List listBy(long accountId, long dataCenterId, Network.Type type); + List listBy(long accountId, long dataCenterId, Network.GuestType type); NetworkVO persist(NetworkVO network, boolean gc); void addAccountToNetwork(long networkId, long accountId); SearchBuilder createSearchBuilderForAccount(); diff --git a/server/src/com/cloud/network/dao/NetworkDaoImpl.java b/server/src/com/cloud/network/dao/NetworkDaoImpl.java index 191498b190b..700b9cdd711 100644 --- a/server/src/com/cloud/network/dao/NetworkDaoImpl.java +++ b/server/src/com/cloud/network/dao/NetworkDaoImpl.java @@ -80,7 +80,7 @@ public class NetworkDaoImpl extends GenericDaoBase implements N AllFieldsSearch.and("datacenter", AllFieldsSearch.entity().getDataCenterId(), Op.EQ); AllFieldsSearch.and("account", AllFieldsSearch.entity().getAccountId(), Op.EQ); AllFieldsSearch.and("related", AllFieldsSearch.entity().getRelated(), Op.EQ); - AllFieldsSearch.and("type", AllFieldsSearch.entity().getType(), Op.EQ); + AllFieldsSearch.and("guestType", AllFieldsSearch.entity().getGuestType(), Op.EQ); AllFieldsSearch.and("physicalNetwork", AllFieldsSearch.entity().getPhysicalNetworkId(), Op.EQ); AllFieldsSearch.done(); @@ -143,12 +143,12 @@ public class NetworkDaoImpl extends GenericDaoBase implements N } @Override - public List listBy(long accountId, long dataCenterId, Network.Type type) { + public List listBy(long accountId, long dataCenterId, Network.GuestType type) { SearchCriteria sc = AllFieldsSearch.create(); sc.setParameters("datacenter", dataCenterId); sc.setParameters("account", accountId); if (type != null) { - sc.setParameters("type", type); + sc.setParameters("guestType", type); } return listBy(sc, null); } @@ -320,9 +320,9 @@ public class NetworkDaoImpl extends GenericDaoBase implements N public List listNetworksBy(boolean isShared) { SearchCriteria sc = AllFieldsSearch.create(); if (isShared) { - sc.setParameters("type", Network.Type.Shared); + sc.setParameters("guestType", Network.GuestType.Shared); } else { - sc.setParameters("type", Network.Type.Isolated); + sc.setParameters("guestType", Network.GuestType.Isolated); } return listBy(sc); diff --git a/server/src/com/cloud/network/element/DhcpElement.java b/server/src/com/cloud/network/element/DhcpElement.java index 1d0149837d4..2986afc3469 100644 --- a/server/src/com/cloud/network/element/DhcpElement.java +++ b/server/src/com/cloud/network/element/DhcpElement.java @@ -39,7 +39,7 @@ import com.cloud.network.Network; import com.cloud.network.Network.Capability; import com.cloud.network.Network.Provider; import com.cloud.network.Network.Service; -import com.cloud.network.Network.Type; +import com.cloud.network.Network.GuestType; import com.cloud.network.NetworkManager; import com.cloud.network.Networks.TrafficType; import com.cloud.network.dao.NetworkDao; @@ -82,20 +82,20 @@ public class DhcpElement extends AdapterBase implements DhcpElementService, User @Inject HostDao _hostDao; @Inject VirtualRouterElementsDao _vrElementsDao; - private boolean canHandle(DeployDestination dest, TrafficType trafficType, Type networkType, long offeringId) { - if (_networkMgr.isProviderSupported(offeringId, Service.Gateway, Provider.JuniperSRX) && networkType == Network.Type.Isolated) { + private boolean canHandle(DeployDestination dest, TrafficType trafficType, GuestType networkType, long offeringId) { + if (_networkMgr.isProviderSupported(offeringId, Service.Gateway, Provider.JuniperSRX) && networkType == Network.GuestType.Isolated) { return true; } else if (dest.getPod() != null && dest.getPod().getExternalDhcp()){ //This pod is using external DHCP server return false; } else { - return (networkType == Network.Type.Shared); + return (networkType == Network.GuestType.Shared); } } @Override public boolean implement(Network network, NetworkOffering offering, DeployDestination dest, ReservationContext context) throws ResourceUnavailableException, ConcurrentOperationException, InsufficientCapacityException { - if (!canHandle(dest, offering.getTrafficType(), network.getType(), network.getNetworkOfferingId())) { + if (!canHandle(dest, offering.getTrafficType(), network.getGuestType(), network.getNetworkOfferingId())) { return false; } @@ -107,7 +107,7 @@ public class DhcpElement extends AdapterBase implements DhcpElementService, User @Override public boolean prepare(Network network, NicProfile nic, VirtualMachineProfile vm, DeployDestination dest, ReservationContext context) throws ConcurrentOperationException, InsufficientCapacityException, ResourceUnavailableException { - if (canHandle(dest, network.getTrafficType(), network.getType(), network.getNetworkOfferingId())) { + if (canHandle(dest, network.getTrafficType(), network.getGuestType(), network.getNetworkOfferingId())) { if (vm.getType() != VirtualMachine.Type.User) { return false; diff --git a/server/src/com/cloud/network/element/ElasticLoadBalancerElement.java b/server/src/com/cloud/network/element/ElasticLoadBalancerElement.java index e5bf52c0bc0..ceffce76477 100644 --- a/server/src/com/cloud/network/element/ElasticLoadBalancerElement.java +++ b/server/src/com/cloud/network/element/ElasticLoadBalancerElement.java @@ -66,8 +66,8 @@ public class ElasticLoadBalancerElement extends AdapterBase implements LoadBalan TrafficType _frontEndTrafficType = TrafficType.Guest; private boolean canHandle(Network network) { - if (network.getType() != Network.Type.Shared|| network.getTrafficType() != TrafficType.Guest) { - s_logger.debug("Not handling network with type " + network.getType() + " and traffic type " + network.getTrafficType()); + if (network.getGuestType() != Network.GuestType.Shared|| network.getTrafficType() != TrafficType.Guest) { + s_logger.debug("Not handling network with type " + network.getGuestType() + " and traffic type " + network.getTrafficType()); return false; } diff --git a/server/src/com/cloud/network/element/ExternalDhcpElement.java b/server/src/com/cloud/network/element/ExternalDhcpElement.java index 7032ab38689..58047f93f8e 100644 --- a/server/src/com/cloud/network/element/ExternalDhcpElement.java +++ b/server/src/com/cloud/network/element/ExternalDhcpElement.java @@ -40,7 +40,7 @@ import com.cloud.network.Network; import com.cloud.network.Network.Capability; import com.cloud.network.Network.Provider; import com.cloud.network.Network.Service; -import com.cloud.network.Network.Type; +import com.cloud.network.Network.GuestType; import com.cloud.network.Networks.TrafficType; import com.cloud.offering.NetworkOffering; import com.cloud.utils.component.AdapterBase; @@ -56,12 +56,12 @@ public class ExternalDhcpElement extends AdapterBase implements NetworkElement { @Inject ExternalDhcpManager _dhcpMgr; private static final Map> capabilities = setCapabilities(); - private boolean canHandle(DeployDestination dest, TrafficType trafficType, Type networkType) { + private boolean canHandle(DeployDestination dest, TrafficType trafficType, GuestType networkType) { DataCenter dc = dest.getDataCenter(); Pod pod = dest.getPod(); if ((pod != null && pod.getExternalDhcp()) && dc.getNetworkType() == NetworkType.Basic && trafficType == TrafficType.Guest - && networkType == Network.Type.Shared) { + && networkType == Network.GuestType.Shared) { s_logger.debug("External DHCP can handle"); return true; } @@ -88,7 +88,7 @@ public class ExternalDhcpElement extends AdapterBase implements NetworkElement { @Override public boolean implement(Network network, NetworkOffering offering, DeployDestination dest, ReservationContext context) throws ConcurrentOperationException, ResourceUnavailableException, InsufficientCapacityException { - if (!canHandle(dest, offering.getTrafficType(), network.getType())) { + if (!canHandle(dest, offering.getTrafficType(), network.getGuestType())) { return false; } return true; @@ -98,7 +98,7 @@ public class ExternalDhcpElement extends AdapterBase implements NetworkElement { public boolean prepare(Network network, NicProfile nic, VirtualMachineProfile vm, DeployDestination dest, ReservationContext context) throws ConcurrentOperationException, ResourceUnavailableException, InsufficientCapacityException { Host host = dest.getHost(); - if (host.getHypervisorType() == HypervisorType.BareMetal || !canHandle(dest, network.getTrafficType(), network.getType())) { + if (host.getHypervisorType() == HypervisorType.BareMetal || !canHandle(dest, network.getTrafficType(), network.getGuestType())) { //BareMetalElement or DhcpElement handle this return false; } diff --git a/server/src/com/cloud/network/element/F5ExternalLoadBalancerElement.java b/server/src/com/cloud/network/element/F5ExternalLoadBalancerElement.java index 7b52c7e8898..e33720fe6a6 100644 --- a/server/src/com/cloud/network/element/F5ExternalLoadBalancerElement.java +++ b/server/src/com/cloud/network/element/F5ExternalLoadBalancerElement.java @@ -64,8 +64,8 @@ public class F5ExternalLoadBalancerElement extends AdapterBase implements LoadBa private boolean canHandle(Network config) { DataCenter zone = _configMgr.getZone(config.getDataCenterId()); - if (config.getType() != Network.Type.Isolated || config.getTrafficType() != TrafficType.Guest) { - s_logger.trace("Not handling network with Type " + config.getType() + " and traffic type " + config.getTrafficType()); + if (config.getGuestType() != Network.GuestType.Isolated || config.getTrafficType() != TrafficType.Guest) { + s_logger.trace("Not handling network with Type " + config.getGuestType() + " and traffic type " + config.getTrafficType()); return false; } diff --git a/server/src/com/cloud/network/element/JuniperSRXExternalFirewallElement.java b/server/src/com/cloud/network/element/JuniperSRXExternalFirewallElement.java index d704f5f5da4..7df767f13fa 100644 --- a/server/src/com/cloud/network/element/JuniperSRXExternalFirewallElement.java +++ b/server/src/com/cloud/network/element/JuniperSRXExternalFirewallElement.java @@ -75,8 +75,8 @@ public class JuniperSRXExternalFirewallElement extends AdapterBase implements So private boolean canHandle(Network config) { DataCenter zone = _configMgr.getZone(config.getDataCenterId()); - if ((zone.getNetworkType() == NetworkType.Advanced && config.getType() != Network.Type.Isolated) || (zone.getNetworkType() == NetworkType.Basic && config.getType() != Network.Type.Shared)) { - s_logger.trace("Not handling network type = " + config.getType()); + if ((zone.getNetworkType() == NetworkType.Advanced && config.getGuestType() != Network.GuestType.Isolated) || (zone.getNetworkType() == NetworkType.Basic && config.getGuestType() != Network.GuestType.Shared)) { + s_logger.trace("Not handling network type = " + config.getGuestType()); return false; } diff --git a/server/src/com/cloud/network/element/NetscalerExternalLoadBalancerElement.java b/server/src/com/cloud/network/element/NetscalerExternalLoadBalancerElement.java index 51d4aa201b7..fb30663a992 100644 --- a/server/src/com/cloud/network/element/NetscalerExternalLoadBalancerElement.java +++ b/server/src/com/cloud/network/element/NetscalerExternalLoadBalancerElement.java @@ -63,8 +63,8 @@ public class NetscalerExternalLoadBalancerElement extends AdapterBase implements private boolean canHandle(Network config) { DataCenter zone = _configMgr.getZone(config.getDataCenterId()); - if (config.getType() != Network.Type.Isolated || config.getTrafficType() != TrafficType.Guest) { - s_logger.trace("Not handling network with Type " + config.getType() + " and traffic type " + config.getTrafficType()); + if (config.getGuestType() != Network.GuestType.Isolated || config.getTrafficType() != TrafficType.Guest) { + s_logger.trace("Not handling network with Type " + config.getGuestType() + " and traffic type " + config.getTrafficType()); return false; } diff --git a/server/src/com/cloud/network/element/RedundantVirtualRouterElement.java b/server/src/com/cloud/network/element/RedundantVirtualRouterElement.java index 2d469fdc859..4352ce52af9 100644 --- a/server/src/com/cloud/network/element/RedundantVirtualRouterElement.java +++ b/server/src/com/cloud/network/element/RedundantVirtualRouterElement.java @@ -16,7 +16,7 @@ import com.cloud.exception.ResourceUnavailableException; import com.cloud.network.Network; import com.cloud.network.Network.Provider; import com.cloud.network.Network.Service; -import com.cloud.network.Network.Type; +import com.cloud.network.Network.GuestType; import com.cloud.network.NetworkManager; import com.cloud.network.dao.VirtualRouterElementsDao; import com.cloud.network.element.VirtualRouterElements.VirtualRouterElementsType; @@ -42,10 +42,10 @@ public class RedundantVirtualRouterElement extends VirtualRouterElement implemen return Provider.RedundantVirtualRouter; } - private boolean canHandle(Type networkType, long offeringId) { - boolean result = (networkType == Network.Type.Isolated && _networkMgr.isProviderSupported(offeringId, Service.Gateway, getProvider())); + private boolean canHandle(GuestType networkType, long offeringId) { + boolean result = (networkType == Network.GuestType.Isolated && _networkMgr.isProviderSupported(offeringId, Service.Gateway, getProvider())); if (!result) { - s_logger.trace("Virtual router element only takes care of networktype " + Network.Type.Isolated + " for provider " + getProvider().getName()); + s_logger.trace("Virtual router element only takes care of networktype " + Network.GuestType.Isolated + " for provider " + getProvider().getName()); } return result; } @@ -53,7 +53,7 @@ public class RedundantVirtualRouterElement extends VirtualRouterElement implemen @Override public boolean implement(Network guestConfig, NetworkOffering offering, DeployDestination dest, ReservationContext context) throws ResourceUnavailableException, ConcurrentOperationException, InsufficientCapacityException { - if (!canHandle(guestConfig.getType(), offering.getId())) { + if (!canHandle(guestConfig.getGuestType(), offering.getId())) { return false; } @@ -67,7 +67,7 @@ public class RedundantVirtualRouterElement extends VirtualRouterElement implemen @Override public boolean prepare(Network network, NicProfile nic, VirtualMachineProfile vm, DeployDestination dest, ReservationContext context) throws ConcurrentOperationException, InsufficientCapacityException, ResourceUnavailableException { - if (canHandle(network.getType(), network.getNetworkOfferingId())) { + if (canHandle(network.getGuestType(), network.getNetworkOfferingId())) { if (vm.getType() != VirtualMachine.Type.User) { return false; } diff --git a/server/src/com/cloud/network/element/VirtualRouterElement.java b/server/src/com/cloud/network/element/VirtualRouterElement.java index c368c5032c5..2118debe0e0 100644 --- a/server/src/com/cloud/network/element/VirtualRouterElement.java +++ b/server/src/com/cloud/network/element/VirtualRouterElement.java @@ -38,7 +38,7 @@ import com.cloud.network.Network; import com.cloud.network.Network.Capability; import com.cloud.network.Network.Provider; import com.cloud.network.Network.Service; -import com.cloud.network.Network.Type; +import com.cloud.network.Network.GuestType; import com.cloud.network.NetworkManager; import com.cloud.network.PublicIpAddress; import com.cloud.network.RemoteAccessVpn; @@ -92,17 +92,17 @@ public class VirtualRouterElement extends DhcpElement implements VirtualRouterEl @Inject ConfigurationDao _configDao; @Inject VirtualRouterElementsDao _vrElementsDao; - private boolean canHandle(Type networkType, long offeringId) { - boolean result = (networkType == Network.Type.Isolated && _networkMgr.isProviderSupported(offeringId, Service.Gateway, getProvider())); + private boolean canHandle(GuestType networkType, long offeringId) { + boolean result = (networkType == Network.GuestType.Isolated && _networkMgr.isProviderSupported(offeringId, Service.Gateway, getProvider())); if (!result) { - s_logger.trace("Virtual router element only takes care of type " + Network.Type.Isolated + " for provider " + getProvider().getName()); + s_logger.trace("Virtual router element only takes care of type " + Network.GuestType.Isolated + " for provider " + getProvider().getName()); } return result; } @Override public boolean implement(Network guestConfig, NetworkOffering offering, DeployDestination dest, ReservationContext context) throws ResourceUnavailableException, ConcurrentOperationException, InsufficientCapacityException { - if (!canHandle(guestConfig.getType(), offering.getId())) { + if (!canHandle(guestConfig.getGuestType(), offering.getId())) { return false; } @@ -116,7 +116,7 @@ public class VirtualRouterElement extends DhcpElement implements VirtualRouterEl @Override public boolean prepare(Network network, NicProfile nic, VirtualMachineProfile vm, DeployDestination dest, ReservationContext context) throws ConcurrentOperationException, InsufficientCapacityException, ResourceUnavailableException { - if (canHandle(network.getType(), network.getNetworkOfferingId())) { + if (canHandle(network.getGuestType(), network.getNetworkOfferingId())) { if (vm.getType() != VirtualMachine.Type.User) { return false; } @@ -178,7 +178,7 @@ public class VirtualRouterElement extends DhcpElement implements VirtualRouterEl public boolean applyFWRules(Network config, List rules) throws ResourceUnavailableException { DataCenter dc = _configMgr.getZone(config.getDataCenterId()); - if (canHandle(config.getType(), config.getNetworkOfferingId())) { + if (canHandle(config.getGuestType(), config.getNetworkOfferingId())) { List routers = _routerDao.listByNetworkAndRole(config.getId(), Role.DHCP_FIREWALL_LB_PASSWD_USERDATA); 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 " + config.getId()); @@ -197,7 +197,7 @@ public class VirtualRouterElement extends DhcpElement implements VirtualRouterEl @Override public boolean applyLBRules(Network network, List rules) throws ResourceUnavailableException { - if (canHandle(network.getType(), network.getNetworkOfferingId())) { + if (canHandle(network.getGuestType(), network.getNetworkOfferingId())) { List routers = _routerDao.listByNetworkAndRole(network.getId(), Role.DHCP_FIREWALL_LB_PASSWD_USERDATA); 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()); @@ -226,7 +226,7 @@ public class VirtualRouterElement extends DhcpElement implements VirtualRouterEl return null; } - if (canHandle(network.getType(), network.getNetworkOfferingId())) { + if (canHandle(network.getGuestType(), network.getNetworkOfferingId())) { return _routerMgr.applyVpnUsers(network, users, routers); } else { s_logger.debug("Element " + this.getName() + " doesn't handle applyVpnUsers command"); @@ -244,7 +244,7 @@ public class VirtualRouterElement extends DhcpElement implements VirtualRouterEl return true; } - if (canHandle(network.getType(), network.getNetworkOfferingId())) { + if (canHandle(network.getGuestType(), network.getNetworkOfferingId())) { return _routerMgr.startRemoteAccessVpn(network, vpn, routers); } else { s_logger.debug("Element " + this.getName() + " doesn't handle createVpn command"); @@ -262,7 +262,7 @@ public class VirtualRouterElement extends DhcpElement implements VirtualRouterEl return true; } - if (canHandle(network.getType(), network.getNetworkOfferingId())) { + if (canHandle(network.getGuestType(), network.getNetworkOfferingId())) { return _routerMgr.deleteRemoteAccessVpn(network, vpn, routers); } else { s_logger.debug("Element " + this.getName() + " doesn't handle removeVpn command"); @@ -272,7 +272,7 @@ public class VirtualRouterElement extends DhcpElement implements VirtualRouterEl @Override public boolean applyIps(Network network, List ipAddress) throws ResourceUnavailableException { - if (canHandle(network.getType(), network.getNetworkOfferingId())) { + if (canHandle(network.getGuestType(), network.getNetworkOfferingId())) { List routers = _routerDao.listByNetworkAndRole(network.getId(), Role.DHCP_FIREWALL_LB_PASSWD_USERDATA); if (routers == null || routers.isEmpty()) { @@ -340,7 +340,7 @@ public class VirtualRouterElement extends DhcpElement implements VirtualRouterEl @Override public boolean applyStaticNats(Network config, List rules) throws ResourceUnavailableException { DataCenter dc = _configMgr.getZone(config.getDataCenterId()); - if (canHandle(config.getType(), config.getNetworkOfferingId())) { + if (canHandle(config.getGuestType(), config.getNetworkOfferingId())) { List routers = _routerDao.listByNetworkAndRole(config.getId(), Role.DHCP_FIREWALL_LB_PASSWD_USERDATA); if (routers == null || routers.isEmpty()) { s_logger.debug("Virtual router elemnt doesn't need to apply static nat on the backend; virtual router doesn't exist in the network " + config.getId()); @@ -439,7 +439,7 @@ public class VirtualRouterElement extends DhcpElement implements VirtualRouterEl @Override public boolean applyPFRules(Network network, List rules) throws ResourceUnavailableException { - if (canHandle(network.getType(), network.getNetworkOfferingId())) { + if (canHandle(network.getGuestType(), network.getNetworkOfferingId())) { List routers = _routerDao.listByNetworkAndRole(network.getId(), Role.DHCP_FIREWALL_LB_PASSWD_USERDATA); 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()); diff --git a/server/src/com/cloud/network/guru/DirectNetworkGuru.java b/server/src/com/cloud/network/guru/DirectNetworkGuru.java index 21ab47c6d2b..5c8d07d0e38 100644 --- a/server/src/com/cloud/network/guru/DirectNetworkGuru.java +++ b/server/src/com/cloud/network/guru/DirectNetworkGuru.java @@ -77,7 +77,7 @@ public class DirectNetworkGuru extends AdapterBase implements NetworkGuru { protected boolean canHandle(NetworkOffering offering, DataCenter dc) { // this guru handles only non-system network with type=Shared and serviceNat service disabled //TODO - after broadCastDomainType + physical network are introduced, don't rely on network type of the dc - if (dc.getNetworkType() == NetworkType.Advanced && offering.getType() == Network.Type.Shared && !_networkMgr.isServiceSupportedByNetworkOffering(offering.getId(), Service.SourceNat)&& offering.getTrafficType() == TrafficType.Guest) { + if (dc.getNetworkType() == NetworkType.Advanced && offering.getGuestType() == Network.GuestType.Shared && !_networkMgr.isServiceSupportedByNetworkOffering(offering.getId(), Service.SourceNat)&& offering.getTrafficType() == TrafficType.Guest) { if (_networkMgr.isServiceSupportedByNetworkOffering(offering.getId(), Service.SecurityGroup)) { return true; } else if (!offering.isSystemOnly()) { diff --git a/server/src/com/cloud/network/guru/GuestNetworkGuru.java b/server/src/com/cloud/network/guru/GuestNetworkGuru.java index 471647eca05..a6e968c7a94 100644 --- a/server/src/com/cloud/network/guru/GuestNetworkGuru.java +++ b/server/src/com/cloud/network/guru/GuestNetworkGuru.java @@ -80,7 +80,7 @@ public class GuestNetworkGuru extends AdapterBase implements NetworkGuru { protected boolean canHandle(NetworkOffering offering, DataCenter dc) { // This guru handles only non-system Guest Isolated network that supports Source nat service - if (dc.getNetworkType() == NetworkType.Advanced && offering.getTrafficType() == TrafficType.Guest && offering.getType() == Network.Type.Isolated && _networkMgr.isServiceSupportedByNetworkOffering(offering.getId(), Service.SourceNat) && !offering.isSystemOnly()) { + if (dc.getNetworkType() == NetworkType.Advanced && offering.getTrafficType() == TrafficType.Guest && offering.getGuestType() == Network.GuestType.Isolated && _networkMgr.isServiceSupportedByNetworkOffering(offering.getId(), Service.SourceNat) && !offering.isSystemOnly()) { return true; } else { s_logger.trace("We only take care of Guest Virtual networks in zone of type " + NetworkType.Advanced); diff --git a/server/src/com/cloud/network/lb/ElasticLoadBalancerManagerImpl.java b/server/src/com/cloud/network/lb/ElasticLoadBalancerManagerImpl.java index 3e303b4c3ca..66dcd09e70b 100644 --- a/server/src/com/cloud/network/lb/ElasticLoadBalancerManagerImpl.java +++ b/server/src/com/cloud/network/lb/ElasticLoadBalancerManagerImpl.java @@ -459,7 +459,7 @@ public class ElasticLoadBalancerManagerImpl implements try { NetworkOffering offering = _networkOfferingDao.findByIdIncludingRemoved(guestNetwork.getNetworkOfferingId()); - if (offering.isSystemOnly() || guestNetwork.getType() == Network.Type.Shared) { + if (offering.isSystemOnly() || guestNetwork.getGuestType() == Network.GuestType.Shared) { owner = _accountService.getSystemAccount(); } @@ -572,7 +572,7 @@ public class ElasticLoadBalancerManagerImpl implements @DB public PublicIp allocIp(CreateLoadBalancerRuleCmd lb, Account account) throws InsufficientAddressCapacityException { //TODO: this only works in the guest network. Handle the public network case also. - List offerings = _networkOfferingDao.listByTrafficTypeAndType(true, _frontendTrafficType, Network.Type.Shared); + List offerings = _networkOfferingDao.listByTrafficTypeAndType(true, _frontendTrafficType, Network.GuestType.Shared); if (offerings == null || offerings.size() == 0) { s_logger.warn("ELB: Could not find system offering for direct networks of type " + _frontendTrafficType); return null; @@ -611,8 +611,8 @@ public class ElasticLoadBalancerManagerImpl implements NetworkVO network=_networkDao.findById(networkId); - if (network.getType() != Network.Type.Shared) { - s_logger.info("ELB: not handling traffic for network of type " + network.getType()); + if (network.getGuestType() != Network.GuestType.Shared) { + s_logger.info("ELB: not handling traffic for network of type " + network.getGuestType()); return null; } return network; diff --git a/server/src/com/cloud/network/router/VirtualNetworkApplianceManagerImpl.java b/server/src/com/cloud/network/router/VirtualNetworkApplianceManagerImpl.java index 628e17e4814..38517ad81a0 100755 --- a/server/src/com/cloud/network/router/VirtualNetworkApplianceManagerImpl.java +++ b/server/src/com/cloud/network/router/VirtualNetworkApplianceManagerImpl.java @@ -726,7 +726,7 @@ public class VirtualNetworkApplianceManagerImpl implements VirtualNetworkApplian @Override public void run() { - final List routers = _routerDao.listByStateAndNetworkType(State.Running, Network.Type.Isolated, mgmtSrvrId); + final List routers = _routerDao.listByStateAndNetworkType(State.Running, Network.GuestType.Isolated, mgmtSrvrId); s_logger.debug("Found " + routers.size() + " running routers. "); for (DomainRouterVO router : routers) { @@ -1351,7 +1351,7 @@ public class VirtualNetworkApplianceManagerImpl implements VirtualNetworkApplian public List deployDhcp(Network guestNetwork, DeployDestination dest, Account owner, Map params) throws InsufficientCapacityException, StorageUnavailableException, ConcurrentOperationException, ResourceUnavailableException { NetworkOffering offering = _networkOfferingDao.findByIdIncludingRemoved(guestNetwork.getNetworkOfferingId()); - if (offering.isSystemOnly() || guestNetwork.getType() == Network.Type.Shared) { + if (offering.isSystemOnly() || guestNetwork.getGuestType() == Network.GuestType.Shared) { owner = _accountMgr.getAccount(Account.ACCOUNT_ID_SYSTEM); } @@ -1508,11 +1508,11 @@ public class VirtualNetworkApplianceManagerImpl implements VirtualNetworkApplian buf.append(" dnssearchorder=").append(domain_suffix); } - if (!network.isDefault() && network.getType() == Network.Type.Shared) { + if (!network.isDefault() && network.getGuestType() == Network.GuestType.Shared) { buf.append(" defaultroute=false"); String virtualNetworkElementNicIP = _networkMgr.getIpOfNetworkElementInVirtualNetwork(network.getAccountId(), network.getDataCenterId()); - if (network.getType() != Network.Type.Shared && virtualNetworkElementNicIP != null) { + if (network.getGuestType() != Network.GuestType.Shared && virtualNetworkElementNicIP != null) { defaultDns1 = virtualNetworkElementNicIP; } else { s_logger.debug("No Virtual network found for account id=" + network.getAccountId() + " so setting dns to the dns of the network id=" + network.getId()); @@ -1955,7 +1955,7 @@ public class VirtualNetworkApplianceManagerImpl implements VirtualNetworkApplian if (cmds.size() > 0) { boolean podLevelException = false; //for user vm in Basic zone we should try to re-deploy vm in a diff pod if it fails to deploy in original pod; so throwing exception with Pod scope - if (isZoneBasic && podId != null && profile.getVirtualMachine().getType() == VirtualMachine.Type.User && network.getTrafficType() == TrafficType.Guest && network.getType() == Network.Type.Shared) { + if (isZoneBasic && podId != null && profile.getVirtualMachine().getType() == VirtualMachine.Type.User && network.getTrafficType() == TrafficType.Guest && network.getGuestType() == Network.GuestType.Shared) { podLevelException = true; } try { diff --git a/server/src/com/cloud/network/security/SecurityGroupManagerImpl.java b/server/src/com/cloud/network/security/SecurityGroupManagerImpl.java index b4783ec615f..f57043a89f9 100755 --- a/server/src/com/cloud/network/security/SecurityGroupManagerImpl.java +++ b/server/src/com/cloud/network/security/SecurityGroupManagerImpl.java @@ -912,7 +912,7 @@ public class SecurityGroupManagerImpl implements SecurityGroupManager, SecurityG @DB public boolean addInstanceToGroups(final Long userVmId, final List groups) { if (!isVmSecurityGroupEnabled(userVmId)) { - s_logger.warn("User vm " + userVmId + " is not security group enabled, can't add it to security group"); + s_logger.trace("User vm " + userVmId + " is not security group enabled, not adding it to security group"); return false; } if (groups != null && !groups.isEmpty()) { diff --git a/server/src/com/cloud/offerings/NetworkOfferingVO.java b/server/src/com/cloud/offerings/NetworkOfferingVO.java index a576db469dc..dbecbb757c9 100644 --- a/server/src/com/cloud/offerings/NetworkOfferingVO.java +++ b/server/src/com/cloud/offerings/NetworkOfferingVO.java @@ -29,7 +29,7 @@ import javax.persistence.Id; import javax.persistence.Table; import com.cloud.network.Network; -import com.cloud.network.Network.Type; +import com.cloud.network.Network.GuestType; import com.cloud.network.Networks.TrafficType; import com.cloud.offering.NetworkOffering; import com.cloud.utils.db.GenericDao; @@ -91,9 +91,9 @@ public class NetworkOfferingVO implements NetworkOffering { @Column(name=GenericDao.CREATED_COLUMN) Date created; - @Column(name="type") + @Column(name="guest_type") @Enumerated(value=EnumType.STRING) - Network.Type type; + Network.GuestType guestType; @Override public String getDisplayText() { @@ -198,11 +198,11 @@ public class NetworkOfferingVO implements NetworkOffering { } @Override - public Network.Type getType() { - return type; + public Network.GuestType getGuestType() { + return guestType; } - public NetworkOfferingVO(String name, String displayText, TrafficType trafficType, boolean systemOnly, boolean specifyVlan, Integer rateMbps, Integer multicastRateMbps, Integer concurrentConnections, boolean isDefault, Availability availability, String tags, Network.Type type) { + public NetworkOfferingVO(String name, String displayText, TrafficType trafficType, boolean systemOnly, boolean specifyVlan, Integer rateMbps, Integer multicastRateMbps, Integer concurrentConnections, boolean isDefault, Availability availability, String tags, Network.GuestType guestType) { this.name = name; this.displayText = displayText; this.rateMbps = rateMbps; @@ -215,7 +215,7 @@ public class NetworkOfferingVO implements NetworkOffering { this.availability = availability; this.uniqueName = name; this.tags = tags; - this.type = type; + this.guestType = guestType; } public NetworkOfferingVO() { @@ -229,7 +229,6 @@ public class NetworkOfferingVO implements NetworkOffering { public NetworkOfferingVO(String name, TrafficType trafficType) { this(name, "System Offering for " + name, trafficType, true, false, 0, 0, null, true, Availability.Required, null, null); this.state = State.Enabled; - this.type = Type.Shared; } @Override diff --git a/server/src/com/cloud/offerings/dao/NetworkOfferingDao.java b/server/src/com/cloud/offerings/dao/NetworkOfferingDao.java index 48bac473689..9affaf61339 100644 --- a/server/src/com/cloud/offerings/dao/NetworkOfferingDao.java +++ b/server/src/com/cloud/offerings/dao/NetworkOfferingDao.java @@ -59,7 +59,7 @@ public interface NetworkOfferingDao extends GenericDao List listByAvailability(Availability availability, boolean isSystem); - List listByTrafficTypeAndType(boolean isSystem, TrafficType trafficType, Network.Type type); + List listByTrafficTypeAndType(boolean isSystem, TrafficType trafficType, Network.GuestType type); List getOfferingIdsToUpgradeFrom(NetworkOffering originalOffering); diff --git a/server/src/com/cloud/offerings/dao/NetworkOfferingDaoImpl.java b/server/src/com/cloud/offerings/dao/NetworkOfferingDaoImpl.java index 577b16f0520..6aba0643781 100644 --- a/server/src/com/cloud/offerings/dao/NetworkOfferingDaoImpl.java +++ b/server/src/com/cloud/offerings/dao/NetworkOfferingDaoImpl.java @@ -66,7 +66,7 @@ public class NetworkOfferingDaoImpl extends GenericDaoBase listByTrafficTypeAndType(boolean isSystem, TrafficType trafficType, Network.Type type) { + public List listByTrafficTypeAndType(boolean isSystem, TrafficType trafficType, Network.GuestType type) { SearchCriteria sc = TrafficTypeGuestTypeSearch.create(); sc.setParameters("trafficType", trafficType); - sc.setParameters("type", type); + sc.setParameters("guestType", type); sc.setParameters("isSystem", isSystem); return listBy(sc, null); } @@ -155,7 +155,7 @@ public class NetworkOfferingDaoImpl extends GenericDaoBase networkMap = _networkDao.listBy(owner.getId(), network.getId()); if (networkMap == null || networkMap.isEmpty()) { @@ -2175,11 +2175,11 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, Manager // 2) If Availability=Optional, search for default networks for the account. If it's more than 1, throw an error. // If it's 0, and there are no default direct networks, create default Guest Virtual network - List defaultVirtualOffering = _networkOfferingDao.listByTrafficTypeAndType(false, TrafficType.Guest, Network.Type.Isolated); + List defaultVirtualOffering = _networkOfferingDao.listByTrafficTypeAndType(false, TrafficType.Guest, Network.GuestType.Isolated); PhysicalNetwork physicalNetwork = _networkMgr.translateZoneIdToPhysicalNetwork(zone.getId()); if (defaultVirtualOffering.get(0).getAvailability() == Availability.Required) { // get Virtual netowrks - List virtualNetworks = _networkMgr.listNetworksForAccount(owner.getId(), zone.getId(), Network.Type.Isolated, true); + List virtualNetworks = _networkMgr.listNetworksForAccount(owner.getId(), zone.getId(), Network.GuestType.Isolated, true); if (virtualNetworks.isEmpty()) { @@ -2238,7 +2238,7 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, Manager } // Perform account permission check - if (network.getType() != Network.Type.Shared) { + if (network.getGuestType() != Network.GuestType.Shared) { List networkMap = _networkDao.listBy(owner.getId(), network.getId()); if (networkMap == null || networkMap.isEmpty()) { throw new PermissionDeniedException("Unable to create a vm using network with id " + network.getId() + ", permission denied"); @@ -3334,7 +3334,7 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, Manager for (NetworkVO network : zoneNetworks) { // get the default networks for the account NetworkOfferingVO no = _networkOfferingDao.findById(network.getNetworkOfferingId()); if (!no.isSystemOnly()) { - if (network.getType() == Network.Type.Shared || !_networkDao.listBy(oldAccount.getId(), network.getId()).isEmpty()) { + if (network.getGuestType() == Network.GuestType.Shared || !_networkDao.listBy(oldAccount.getId(), network.getId()).isEmpty()) { if (network.isDefault()) { oldNetworks.add(network); } @@ -3344,7 +3344,7 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, Manager for (NetworkVO oldNet: oldNetworks){ long networkOffering = oldNet.getNetworkOfferingId(); PhysicalNetwork physicalNetwork = _networkMgr.translateZoneIdToPhysicalNetwork(zone.getId()); - List virtualNetworks = _networkMgr.listNetworksForAccount(newAccount.getId(), zone.getId(), Network.Type.Isolated, true); + List virtualNetworks = _networkMgr.listNetworksForAccount(newAccount.getId(), zone.getId(), Network.GuestType.Isolated, true); if (virtualNetworks.isEmpty()) { Network newNetwork = _networkMgr.createNetwork(networkOffering, newAccount.getAccountName() + "-network", newAccount.getAccountName() + "-network", null, null, null, null, null, newAccount, false, null, null, false, physicalNetwork); diff --git a/server/src/com/cloud/vm/dao/DomainRouterDao.java b/server/src/com/cloud/vm/dao/DomainRouterDao.java index f51a8347a61..502edd46791 100755 --- a/server/src/com/cloud/vm/dao/DomainRouterDao.java +++ b/server/src/com/cloud/vm/dao/DomainRouterDao.java @@ -97,7 +97,7 @@ public interface DomainRouterDao extends GenericDao { * List domain routers by state and network type which reside on Host managed by the specified management server * @return */ - List listByStateAndNetworkType(State state, Network.Type type, long mgmtSrvrId); + List listByStateAndNetworkType(State state, Network.GuestType type, long mgmtSrvrId); List findByNetworkOutsideThePod(long networkId, long podId, State state, Role role); diff --git a/server/src/com/cloud/vm/dao/DomainRouterDaoImpl.java b/server/src/com/cloud/vm/dao/DomainRouterDaoImpl.java index bb627744522..9de8f80b0e3 100755 --- a/server/src/com/cloud/vm/dao/DomainRouterDaoImpl.java +++ b/server/src/com/cloud/vm/dao/DomainRouterDaoImpl.java @@ -75,14 +75,14 @@ public class DomainRouterDaoImpl extends GenericDaoBase im HostUpSearch.and("host", HostUpSearch.entity().getHostId(), Op.EQ); HostUpSearch.and("states", HostUpSearch.entity().getState(), Op.NIN); SearchBuilder joinNetwork = _networksDao.createSearchBuilder(); - joinNetwork.and("type", joinNetwork.entity().getType(), Op.EQ); + joinNetwork.and("type", joinNetwork.entity().getGuestType(), Op.EQ); HostUpSearch.join("network", joinNetwork, joinNetwork.entity().getId(), HostUpSearch.entity().getNetworkId(), JoinType.INNER); HostUpSearch.done(); StateNetworkTypeSearch = createSearchBuilder(); StateNetworkTypeSearch.and("state", StateNetworkTypeSearch.entity().getState(), Op.EQ); SearchBuilder joinStateNetwork = _networksDao.createSearchBuilder(); - joinStateNetwork.and("type", joinStateNetwork.entity().getType(), Op.EQ); + joinStateNetwork.and("type", joinStateNetwork.entity().getGuestType(), Op.EQ); StateNetworkTypeSearch.join("network", joinStateNetwork, joinStateNetwork.entity().getId(), StateNetworkTypeSearch.entity().getNetworkId(), JoinType.INNER); SearchBuilder joinHost = _hostsDao.createSearchBuilder(); joinHost.and("mgmtServerId", joinHost.entity().getManagementServerId(), Op.EQ); @@ -158,7 +158,7 @@ public class DomainRouterDaoImpl extends GenericDaoBase im if (hostId != null) { sc.setParameters("host", hostId); } - sc.setJoinParameters("network", "type", Network.Type.Isolated); + sc.setJoinParameters("network", "type", Network.GuestType.Isolated); return listBy(sc); } @@ -169,7 +169,7 @@ public class DomainRouterDaoImpl extends GenericDaoBase im sc.setParameters("host", hostId); } sc.setParameters("states", State.Destroyed, State.Stopped, State.Expunging); - sc.setJoinParameters("network", "type", Network.Type.Isolated); + sc.setJoinParameters("network", "type", Network.GuestType.Isolated); return listBy(sc); } @@ -204,7 +204,7 @@ public class DomainRouterDaoImpl extends GenericDaoBase im } @Override - public List listByStateAndNetworkType(State state, Network.Type type, long mgmtSrvrId) { + public List listByStateAndNetworkType(State state, Network.GuestType type, long mgmtSrvrId) { SearchCriteria sc = StateNetworkTypeSearch.create(); sc.setParameters("state", state); sc.setJoinParameters("network", "type", type); diff --git a/server/src/com/cloud/vm/dao/UserVmDaoImpl.java b/server/src/com/cloud/vm/dao/UserVmDaoImpl.java index a0a2be6f4c3..668a8ed374a 100755 --- a/server/src/com/cloud/vm/dao/UserVmDaoImpl.java +++ b/server/src/com/cloud/vm/dao/UserVmDaoImpl.java @@ -82,7 +82,7 @@ public class UserVmDaoImpl extends GenericDaoBase implements Use "vm_template.enable_password, service_offering.id, disk_offering.name, storage_pool.id, storage_pool.pool_type, " + "service_offering.cpu, service_offering.speed, service_offering.ram_size, volumes.id, volumes.device_id, volumes.volume_type, security_group.id, security_group.name, " + "security_group.description, nics.id, nics.ip4_address, nics.gateway, nics.network_id, nics.netmask, nics.mac_address, nics.broadcast_uri, nics.isolation_uri, " + - "networks.traffic_type, networks.type, networks.is_default from vm_instance " + + "networks.traffic_type, networks.guest_type, networks.is_default from vm_instance " + "left join account on vm_instance.account_id=account.id " + "left join domain on vm_instance.domain_id=domain.id " + "left join instance_group_vm_map on vm_instance.id=instance_group_vm_map.instance_id " + @@ -510,7 +510,7 @@ public class UserVmDaoImpl extends GenericDaoBase implements Use nicResponse.setTrafficType(rs.getString("networks.traffic_type")); - nicResponse.setType(rs.getString("networks.type")); + nicResponse.setType(rs.getString("networks.guest_type")); nicResponse.setIsDefault(rs.getBoolean("networks.is_default")); nicResponse.setObjectName("nic"); userVmData.addNic(nicResponse); diff --git a/setup/db/create-schema.sql b/setup/db/create-schema.sql index 743f69f0a31..9b4f6d5d0d6 100755 --- a/setup/db/create-schema.sql +++ b/setup/db/create-schema.sql @@ -186,9 +186,9 @@ CREATE TABLE `cloud`.`networks` ( `network_domain` varchar(255) COMMENT 'domain', `reservation_id` char(40) COMMENT 'reservation id', `is_default` int(1) unsigned NOT NULL DEFAULT 0 COMMENT '1 if network is default', + `guest_type` char(32) COMMENT 'type of guest network; can be shared or isolated', `created` datetime NOT NULL COMMENT 'date created', `removed` datetime COMMENT 'date removed if not null', - `type` char(32) COMMENT 'type of the network, can be Shared or Isolated', PRIMARY KEY (`id`), CONSTRAINT `fk_networks__network_offering_id` FOREIGN KEY (`network_offering_id`) REFERENCES `network_offerings`(`id`), CONSTRAINT `fk_networks__data_center_id` FOREIGN KEY (`data_center_id`) REFERENCES `data_center`(`id`) ON DELETE CASCADE, @@ -264,7 +264,7 @@ CREATE TABLE `cloud`.`network_offerings` ( `availability` varchar(255) NOT NULL COMMENT 'availability of the network', `shared_source_nat_service` int(1) unsigned NOT NULL DEFAULT 0 COMMENT 'true if the network offering provides the shared source nat service', `state` char(32) COMMENT 'state of the network offering; has Disabled value by default', - `type` char(32) COMMENT 'type of the network offering, can be Shared or Isolated', + `guest_type` char(32) COMMENT 'type of guest network; can be shared or isolated', PRIMARY KEY (`id`), INDEX `i_network_offerings__system_only`(`system_only`), INDEX `i_network_offerings__removed`(`removed`) From 6d5601a84d8ce42b14983eaaf5291950f491edf9 Mon Sep 17 00:00:00 2001 From: prachi Date: Thu, 27 Oct 2011 17:27:54 -0700 Subject: [PATCH 044/159] Added commands and framework for PhysicalNetwork trafficTypes --- api/src/com/cloud/api/ApiConstants.java | 4 + api/src/com/cloud/api/ResponseGenerator.java | 4 + .../cloud/api/commands/AddTrafficTypeCmd.java | 132 ++++++++++++++++++ .../api/commands/CreateVlanIpRangeCmd.java | 14 -- .../api/commands/DeleteTrafficTypeCmd.java | 91 ++++++++++++ .../ListNetworkServiceProvidersCmd.java | 2 +- .../api/commands/ListTrafficTypesCmd.java | 90 ++++++++++++ .../api/commands/UpdateTrafficTypeCmd.java | 113 +++++++++++++++ .../api/response/TrafficTypeResponse.java | 92 ++++++++++++ api/src/com/cloud/event/EventTypes.java | 5 + api/src/com/cloud/network/NetworkService.java | 12 ++ api/src/com/cloud/network/Networks.java | 12 +- .../network/PhysicalNetworkTrafficType.java | 45 ++++++ client/tomcatconf/commands.properties.in | 6 + .../src/com/cloud/api/ApiResponseHelper.java | 16 +++ .../DefaultComponentLibrary.java | 7 +- .../com/cloud/network/NetworkManagerImpl.java | 113 ++++++++++++++- .../src/com/cloud/network/dao/NetworkDao.java | 3 + .../com/cloud/network/dao/NetworkDaoImpl.java | 9 ++ .../cloud/network/dao/PhysicalNetworkDao.java | 2 + .../network/dao/PhysicalNetworkDaoImpl.java | 26 +++- .../dao/PhysicalNetworkTrafficTypeDao.java | 28 ++++ .../PhysicalNetworkTrafficTypeDaoImpl.java | 49 +++++++ .../dao/PhysicalNetworkTrafficTypeVO.java | 109 +++++++++++++++ setup/db/create-schema.sql | 12 +- 25 files changed, 964 insertions(+), 32 deletions(-) create mode 100644 api/src/com/cloud/api/commands/AddTrafficTypeCmd.java create mode 100644 api/src/com/cloud/api/commands/DeleteTrafficTypeCmd.java create mode 100644 api/src/com/cloud/api/commands/ListTrafficTypesCmd.java create mode 100644 api/src/com/cloud/api/commands/UpdateTrafficTypeCmd.java create mode 100644 api/src/com/cloud/api/response/TrafficTypeResponse.java create mode 100644 api/src/com/cloud/network/PhysicalNetworkTrafficType.java create mode 100644 server/src/com/cloud/network/dao/PhysicalNetworkTrafficTypeDao.java create mode 100644 server/src/com/cloud/network/dao/PhysicalNetworkTrafficTypeDaoImpl.java create mode 100644 server/src/com/cloud/network/dao/PhysicalNetworkTrafficTypeVO.java diff --git a/api/src/com/cloud/api/ApiConstants.java b/api/src/com/cloud/api/ApiConstants.java index dd4436e4d65..01c3d811de9 100755 --- a/api/src/com/cloud/api/ApiConstants.java +++ b/api/src/com/cloud/api/ApiConstants.java @@ -284,4 +284,8 @@ public class ApiConstants { public static final String UUID = "uuid"; public static final String SECURITY_GROUP_EANBLED = "securitygroupenabled"; public static final String GUEST_IP_TYPE = "guestiptype"; + public static final String XEN_NETWORK_LABEL = "xennetworklabel"; + public static final String KVM_NETWORK_LABEL = "kvmnetworklabel"; + public static final String VMWARE_NETWORK_LABEL = "vmwarenetworklabel"; + } diff --git a/api/src/com/cloud/api/ResponseGenerator.java b/api/src/com/cloud/api/ResponseGenerator.java index 45dad8fad8b..a321b3982e7 100755 --- a/api/src/com/cloud/api/ResponseGenerator.java +++ b/api/src/com/cloud/api/ResponseGenerator.java @@ -62,6 +62,7 @@ import com.cloud.api.response.SystemVmInstanceResponse; import com.cloud.api.response.SystemVmResponse; import com.cloud.api.response.TemplatePermissionsResponse; import com.cloud.api.response.TemplateResponse; +import com.cloud.api.response.TrafficTypeResponse; import com.cloud.api.response.UserResponse; import com.cloud.api.response.UserVmResponse; import com.cloud.api.response.VlanIpRangeResponse; @@ -86,6 +87,7 @@ import com.cloud.network.Network.Provider; import com.cloud.network.Network.Service; import com.cloud.network.PhysicalNetwork; import com.cloud.network.PhysicalNetworkServiceProvider; +import com.cloud.network.PhysicalNetworkTrafficType; import com.cloud.network.RemoteAccessVpn; import com.cloud.network.VpnUser; import com.cloud.network.router.VirtualRouter; @@ -248,4 +250,6 @@ public interface ResponseGenerator { ProviderResponse createNetworkServiceProviderResponse(PhysicalNetworkServiceProvider result); + TrafficTypeResponse createTrafficTypeResponse(PhysicalNetworkTrafficType result); + } diff --git a/api/src/com/cloud/api/commands/AddTrafficTypeCmd.java b/api/src/com/cloud/api/commands/AddTrafficTypeCmd.java new file mode 100644 index 00000000000..cc10bcc9ccf --- /dev/null +++ b/api/src/com/cloud/api/commands/AddTrafficTypeCmd.java @@ -0,0 +1,132 @@ +/** + * Copyright (C) 2011 Citrix Systems, Inc. All rights reserved. + * + * This software is licensed under the GNU General Public License v3 or later. + * + * It is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or any later version. + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + */ + +package com.cloud.api.commands; + +import org.apache.log4j.Logger; + +import com.cloud.api.ApiConstants; +import com.cloud.api.BaseAsyncCreateCmd; +import com.cloud.api.BaseCmd; +import com.cloud.api.Implementation; +import com.cloud.api.Parameter; +import com.cloud.api.ServerApiException; +import com.cloud.api.response.TrafficTypeResponse; +import com.cloud.event.EventTypes; +import com.cloud.exception.ResourceAllocationException; +import com.cloud.network.PhysicalNetworkTrafficType; +import com.cloud.user.Account; +import com.cloud.user.UserContext; + +@Implementation(description="Adds traffic type to a physical network", responseObject=TrafficTypeResponse.class) +public class AddTrafficTypeCmd extends BaseAsyncCreateCmd { + public static final Logger s_logger = Logger.getLogger(AddTrafficTypeCmd.class.getName()); + + private static final String s_name = "addtraffictyperesponse"; + + ///////////////////////////////////////////////////// + //////////////// API parameters ///////////////////// + ///////////////////////////////////////////////////// + + @Parameter(name=ApiConstants.PHYSICAL_NETWORK_ID, type=CommandType.LONG, required=true, description="the Physical Network ID") + private Long physicalNetworkId; + + @Parameter(name=ApiConstants.TRAFFIC_TYPE, type=CommandType.STRING, required=true, description="the trafficType to be added to the physical network") + private String trafficType; + + @Parameter(name=ApiConstants.XEN_NETWORK_LABEL, type=CommandType.STRING, description="The network name label of the physical device dedicated to this traffic on a XenServer host") + private String xenLabel; + + @Parameter(name=ApiConstants.KVM_NETWORK_LABEL, type=CommandType.STRING, description="The network name label of the physical device dedicated to this traffic on a KVM host") + private String kvmLabel; + + @Parameter(name=ApiConstants.VMWARE_NETWORK_LABEL, type=CommandType.STRING, description="The network name label of the physical device dedicated to this traffic on a VMware host") + private String vmwareLabel; + + ///////////////////////////////////////////////////// + /////////////////// Accessors /////////////////////// + ///////////////////////////////////////////////////// + + public Long getPhysicalNetworkId() { + return physicalNetworkId; + } + + public String getTrafficType() { + return trafficType; + } + + public String getXenLabel() { + return xenLabel; + } + + public String getKvmLabel() { + return kvmLabel; + } + + public String getVmwareLabel() { + return vmwareLabel; + } + + ///////////////////////////////////////////////////// + /////////////// API Implementation/////////////////// + ///////////////////////////////////////////////////// + + @Override + public String getCommandName() { + return s_name; + } + + @Override + public long getEntityOwnerId() { + return Account.ACCOUNT_ID_SYSTEM; + } + + @Override + public void execute(){ + UserContext.current().setEventDetails("TrafficType Id: "+getEntityId()); + PhysicalNetworkTrafficType result = _networkService.getPhysicalNetworkTrafficType(getEntityId()); + if (result != null) { + TrafficTypeResponse response = _responseGenerator.createTrafficTypeResponse(result); + response.setResponseName(getCommandName()); + this.setResponseObject(response); + }else { + throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to add traffic type to physical network"); + } + } + + @Override + public void create() throws ResourceAllocationException { + PhysicalNetworkTrafficType result = _networkService.addTrafficTypeToPhysicalNetwork(getPhysicalNetworkId(), getTrafficType(), getXenLabel(), getKvmLabel(), getVmwareLabel()); + if (result != null) { + setEntityId(result.getId()); + } else { + throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to add traffic type to physical network"); + } + } + + @Override + public String getEventType() { + return EventTypes.EVENT_TRAFFIC_TYPE_CREATE; + } + + @Override + public String getEventDescription() { + return "Adding physical network traffic type: " + getEntityId(); + } + +} diff --git a/api/src/com/cloud/api/commands/CreateVlanIpRangeCmd.java b/api/src/com/cloud/api/commands/CreateVlanIpRangeCmd.java index be52e05a8a8..c02abc3880d 100644 --- a/api/src/com/cloud/api/commands/CreateVlanIpRangeCmd.java +++ b/api/src/com/cloud/api/commands/CreateVlanIpRangeCmd.java @@ -29,7 +29,6 @@ import com.cloud.api.response.VlanIpRangeResponse; import com.cloud.dc.Vlan; import com.cloud.exception.ConcurrentOperationException; import com.cloud.exception.InsufficientCapacityException; -import com.cloud.exception.InvalidParameterValueException; import com.cloud.exception.ResourceUnavailableException; import com.cloud.user.Account; @@ -79,19 +78,6 @@ public class CreateVlanIpRangeCmd extends BaseCmd { @Parameter(name=ApiConstants.NETWORK_ID, type=CommandType.LONG, description="the network id") private Long networkID; - @Parameter(name=ApiConstants.PHYSICAL_NETWORK_ID, type=CommandType.LONG, description="the Physical Network ID") - private Long physicalNetworkId; - - public Long getPhysicalNetworkId() { - if (physicalNetworkId != null) { - return physicalNetworkId; - } else if (zoneId != null) { - return _networkService.translateZoneIdToPhysicalNetworkId(zoneId); - } else { - throw new InvalidParameterValueException("Either zoneId or physicalNetworkId have to be specified"); - } - } - ///////////////////////////////////////////////////// /////////////////// Accessors /////////////////////// diff --git a/api/src/com/cloud/api/commands/DeleteTrafficTypeCmd.java b/api/src/com/cloud/api/commands/DeleteTrafficTypeCmd.java new file mode 100644 index 00000000000..98bd0a4c026 --- /dev/null +++ b/api/src/com/cloud/api/commands/DeleteTrafficTypeCmd.java @@ -0,0 +1,91 @@ +/** + * Copyright (C) 2011 Citrix Systems, Inc. All rights reserved. + * + * This software is licensed under the GNU General Public License v3 or later. + * + * It is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or any later version. + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + */ + +package com.cloud.api.commands; + +import org.apache.log4j.Logger; + +import com.cloud.api.ApiConstants; +import com.cloud.api.BaseAsyncCmd; +import com.cloud.api.BaseCmd; +import com.cloud.api.Implementation; +import com.cloud.api.Parameter; +import com.cloud.api.ServerApiException; +import com.cloud.api.response.SuccessResponse; +import com.cloud.event.EventTypes; +import com.cloud.user.Account; + +@Implementation(description="Deletes traffic type of a physical network", responseObject=SuccessResponse.class) +public class DeleteTrafficTypeCmd extends BaseAsyncCmd { + public static final Logger s_logger = Logger.getLogger(DeleteTrafficTypeCmd.class.getName()); + + private static final String s_name = "deletetraffictyperesponse"; + + ///////////////////////////////////////////////////// + //////////////// API parameters ///////////////////// + ///////////////////////////////////////////////////// + + @Parameter(name=ApiConstants.ID, type=CommandType.LONG, required=true, description="traffic type id") + private Long id; + + + ///////////////////////////////////////////////////// + /////////////////// Accessors /////////////////////// + ///////////////////////////////////////////////////// + + public Long getId() { + return id; + } + + ///////////////////////////////////////////////////// + /////////////// API Implementation/////////////////// + ///////////////////////////////////////////////////// + + @Override + public String getCommandName() { + return s_name; + } + + @Override + public long getEntityOwnerId() { + return Account.ACCOUNT_ID_SYSTEM; + } + + @Override + public void execute(){ + boolean result = _networkService.deletePhysicalNetworkTrafficType(getId()); + if (result) { + SuccessResponse response = new SuccessResponse(getCommandName()); + this.setResponseObject(response); + }else { + throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to delete traffic type"); + } + } + + @Override + public String getEventDescription() { + return "Deleting Traffic Type: " + getId(); + } + + @Override + public String getEventType() { + return EventTypes.EVENT_TRAFFIC_TYPE_DELETE; + } + + +} diff --git a/api/src/com/cloud/api/commands/ListNetworkServiceProvidersCmd.java b/api/src/com/cloud/api/commands/ListNetworkServiceProvidersCmd.java index f152566a0ee..7ab62300bdb 100644 --- a/api/src/com/cloud/api/commands/ListNetworkServiceProvidersCmd.java +++ b/api/src/com/cloud/api/commands/ListNetworkServiceProvidersCmd.java @@ -42,7 +42,7 @@ public class ListNetworkServiceProvidersCmd extends BaseListCmd { //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// - @Parameter(name=ApiConstants.PHYSICAL_NETWORK_ID, type=CommandType.LONG, required=true, description="the Physical Network ID to add the provider to") + @Parameter(name=ApiConstants.PHYSICAL_NETWORK_ID, type=CommandType.LONG, required=true, description="the Physical Network ID") private Long physicalNetworkId; ///////////////////////////////////////////////////// diff --git a/api/src/com/cloud/api/commands/ListTrafficTypesCmd.java b/api/src/com/cloud/api/commands/ListTrafficTypesCmd.java new file mode 100644 index 00000000000..787fd9ee1b8 --- /dev/null +++ b/api/src/com/cloud/api/commands/ListTrafficTypesCmd.java @@ -0,0 +1,90 @@ +/** + * Copyright (C) 2011 Citrix Systems, Inc. All rights reserved. + * + * This software is licensed under the GNU General Public License v3 or later. + * + * It is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or any later version. + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + */ + +package com.cloud.api.commands; + +import java.util.ArrayList; +import java.util.List; + +import org.apache.log4j.Logger; + +import com.cloud.api.ApiConstants; +import com.cloud.api.BaseListCmd; +import com.cloud.api.Implementation; +import com.cloud.api.Parameter; +import com.cloud.api.response.ListResponse; +import com.cloud.api.response.ProviderResponse; +import com.cloud.api.response.TrafficTypeResponse; +import com.cloud.network.PhysicalNetworkTrafficType; +import com.cloud.user.Account; + + +@Implementation(description="Lists traffic types of a given physical network.", responseObject=ProviderResponse.class) +public class ListTrafficTypesCmd extends BaseListCmd { + public static final Logger s_logger = Logger.getLogger(ListTrafficTypesCmd.class.getName()); + private static final String _name = "listtraffictypesresponse"; + + ///////////////////////////////////////////////////// + //////////////// API parameters ///////////////////// + ///////////////////////////////////////////////////// + + @Parameter(name=ApiConstants.PHYSICAL_NETWORK_ID, type=CommandType.LONG, required=true, description="the Physical Network ID") + private Long physicalNetworkId; + + ///////////////////////////////////////////////////// + /////////////////// Accessors /////////////////////// + ///////////////////////////////////////////////////// + + public void setPhysicalNetworkId(Long physicalNetworkId) { + this.physicalNetworkId = physicalNetworkId; + } + + public Long getPhysicalNetworkId() { + return physicalNetworkId; + } + + ///////////////////////////////////////////////////// + /////////////// API Implementation/////////////////// + ///////////////////////////////////////////////////// + @Override + public String getCommandName() { + return _name; + } + + @Override + public long getEntityOwnerId() { + return Account.ACCOUNT_ID_SYSTEM; + } + + @Override + public void execute(){ + List trafficTypes = _networkService.listTrafficTypes(getPhysicalNetworkId()); + ListResponse response = new ListResponse(); + List trafficTypesResponses = new ArrayList(); + for (PhysicalNetworkTrafficType trafficType : trafficTypes) { + TrafficTypeResponse trafficTypeResponse = _responseGenerator.createTrafficTypeResponse(trafficType); + trafficTypesResponses.add(trafficTypeResponse); + } + + response.setResponses(trafficTypesResponses); + response.setResponseName(getCommandName()); + this.setResponseObject(response); + } + + +} diff --git a/api/src/com/cloud/api/commands/UpdateTrafficTypeCmd.java b/api/src/com/cloud/api/commands/UpdateTrafficTypeCmd.java new file mode 100644 index 00000000000..b07e3640344 --- /dev/null +++ b/api/src/com/cloud/api/commands/UpdateTrafficTypeCmd.java @@ -0,0 +1,113 @@ +/** + * Copyright (C) 2011 Citrix Systems, Inc. All rights reserved. + * + * This software is licensed under the GNU General Public License v3 or later. + * + * It is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or any later version. + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + */ + +package com.cloud.api.commands; + +import org.apache.log4j.Logger; + +import com.cloud.api.ApiConstants; +import com.cloud.api.BaseAsyncCmd; +import com.cloud.api.BaseCmd; +import com.cloud.api.Implementation; +import com.cloud.api.Parameter; +import com.cloud.api.ServerApiException; +import com.cloud.api.response.TrafficTypeResponse; +import com.cloud.event.EventTypes; +import com.cloud.network.PhysicalNetworkTrafficType; +import com.cloud.user.Account; + +@Implementation(description="Updates traffic type of a physical network", responseObject=TrafficTypeResponse.class) +public class UpdateTrafficTypeCmd extends BaseAsyncCmd { + public static final Logger s_logger = Logger.getLogger(UpdateTrafficTypeCmd.class.getName()); + + private static final String s_name = "updatetraffictyperesponse"; + + ///////////////////////////////////////////////////// + //////////////// API parameters ///////////////////// + ///////////////////////////////////////////////////// + + @Parameter(name=ApiConstants.ID, type=CommandType.LONG, required=true, description="traffic type id") + private Long id; + + @Parameter(name=ApiConstants.XEN_NETWORK_LABEL, type=CommandType.STRING, description="The network name label of the physical device dedicated to this traffic on a XenServer host") + private String xenLabel; + + @Parameter(name=ApiConstants.KVM_NETWORK_LABEL, type=CommandType.STRING, description="The network name label of the physical device dedicated to this traffic on a KVM host") + private String kvmLabel; + + @Parameter(name=ApiConstants.VMWARE_NETWORK_LABEL, type=CommandType.STRING, description="The network name label of the physical device dedicated to this traffic on a VMware host") + private String vmwareLabel; + + + ///////////////////////////////////////////////////// + /////////////////// Accessors /////////////////////// + ///////////////////////////////////////////////////// + + public Long getId() { + return id; + } + public String getXenLabel() { + return xenLabel; + } + + public String getKvmLabel() { + return kvmLabel; + } + + public String getVmwareLabel() { + return vmwareLabel; + } + + ///////////////////////////////////////////////////// + /////////////// API Implementation/////////////////// + ///////////////////////////////////////////////////// + + @Override + public String getCommandName() { + return s_name; + } + + @Override + public long getEntityOwnerId() { + return Account.ACCOUNT_ID_SYSTEM; + } + + @Override + public void execute(){ + PhysicalNetworkTrafficType result = _networkService.updatePhysicalNetworkTrafficType(getId(), getXenLabel(), getKvmLabel(), getVmwareLabel()); + if (result != null) { + TrafficTypeResponse response = _responseGenerator.createTrafficTypeResponse(result); + response.setResponseName(getCommandName()); + this.setResponseObject(response); + }else { + throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to update traffic type"); + } + } + + @Override + public String getEventDescription() { + return "Updating Traffic Type: " + getId(); + } + + @Override + public String getEventType() { + return EventTypes.EVENT_TRAFFIC_TYPE_UPDATE; + } + + +} diff --git a/api/src/com/cloud/api/response/TrafficTypeResponse.java b/api/src/com/cloud/api/response/TrafficTypeResponse.java new file mode 100644 index 00000000000..67b8097eddf --- /dev/null +++ b/api/src/com/cloud/api/response/TrafficTypeResponse.java @@ -0,0 +1,92 @@ +/** + * Copyright (C) 2011 Citrix Systems, Inc. All rights reserved + * + * This software is licensed under the GNU General Public License v3 or later. + * + * It is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or any later version. + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + */ +package com.cloud.api.response; + +import com.cloud.api.ApiConstants; +import com.cloud.serializer.Param; +import com.google.gson.annotations.SerializedName; + +@SuppressWarnings("unused") +public class TrafficTypeResponse extends BaseResponse { + + @SerializedName(ApiConstants.ID) @Param(description="id of the network provider") + private Long id; + + @SerializedName(ApiConstants.TRAFFIC_TYPE) @Param(description="the trafficType to be added to the physical network") + private String trafficType; + + @SerializedName(ApiConstants.PHYSICAL_NETWORK_ID) @Param(description="the physical network this belongs to") + private Long physicalNetworkId; + + @SerializedName(ApiConstants.XEN_NETWORK_LABEL) @Param(description="The network name label of the physical device dedicated to this traffic on a XenServer host") + private String xenNetworkLabel; + + @SerializedName(ApiConstants.KVM_NETWORK_LABEL) @Param(description="The network name label of the physical device dedicated to this traffic on a KVM host") + private String kvmNetworkLabel; + + @SerializedName(ApiConstants.VMWARE_NETWORK_LABEL) @Param(description="The network name label of the physical device dedicated to this traffic on a VMware host") + private String vmwareNetworkLabel; + + public void setPhysicalNetworkId(long physicalNetworkId) { + this.physicalNetworkId = physicalNetworkId; + } + + public long getphysicalNetworkId() { + return physicalNetworkId; + } + + public void setId(Long id) { + this.id = id; + } + + public Long getId() { + return this.id; + } + + public String getTrafficType() { + return trafficType; + } + + public void setTrafficType(String trafficType) { + this.trafficType = trafficType; + } + + public String getXenLabel() { + return xenNetworkLabel; + } + + public String getKvmLabel() { + return kvmNetworkLabel; + } + + public void setXenLabel(String xenLabel) { + this.xenNetworkLabel = xenLabel; + } + + public void setKvmLabel(String kvmLabel) { + this.kvmNetworkLabel = kvmLabel; + } + + public void setVmwareLabel(String vmwareNetworkLabel) { + this.vmwareNetworkLabel = vmwareNetworkLabel; + } + + public String getVmwareLabel() { + return vmwareNetworkLabel; + } +} diff --git a/api/src/com/cloud/event/EventTypes.java b/api/src/com/cloud/event/EventTypes.java index 5840842a594..6ca15607dcc 100755 --- a/api/src/com/cloud/event/EventTypes.java +++ b/api/src/com/cloud/event/EventTypes.java @@ -225,4 +225,9 @@ public class EventTypes { public static final String EVENT_SERVICE_PROVIDER_DELETE = "SERVICE.PROVIDER.DELETE"; public static final String EVENT_SERVICE_PROVIDER_UPDATE = "SERVICE.PROVIDER.UPDATE"; + //Physical Network TrafficType Events + public static final String EVENT_TRAFFIC_TYPE_CREATE = "TRAFFIC.TYPE.CREATE"; + public static final String EVENT_TRAFFIC_TYPE_DELETE = "TRAFFIC.TYPE.DELETE"; + public static final String EVENT_TRAFFIC_TYPE_UPDATE = "TRAFFIC.TYPE.UPDATE"; + } diff --git a/api/src/com/cloud/network/NetworkService.java b/api/src/com/cloud/network/NetworkService.java index e42c9c5b32f..4651bde9029 100644 --- a/api/src/com/cloud/network/NetworkService.java +++ b/api/src/com/cloud/network/NetworkService.java @@ -114,4 +114,16 @@ public interface NetworkService { PhysicalNetworkServiceProvider getCreatedPhysicalNetworkServiceProvider(Long providerId); long translateZoneIdToPhysicalNetworkId(long zoneId); + + PhysicalNetworkTrafficType addTrafficTypeToPhysicalNetwork(Long physicalNetworkId, String trafficType, String xenLabel, String kvmLabel, String vmwareLabel); + + PhysicalNetworkTrafficType getPhysicalNetworkTrafficType(Long id); + + PhysicalNetworkTrafficType updatePhysicalNetworkTrafficType(Long id, String xenLabel, String kvmLabel, String vmwareLabel); + + boolean deletePhysicalNetworkTrafficType(Long id); + + List listTrafficTypes(Long physicalNetworkId); + + } diff --git a/api/src/com/cloud/network/Networks.java b/api/src/com/cloud/network/Networks.java index 7a07385b0d6..3bffc6f9b7a 100644 --- a/api/src/com/cloud/network/Networks.java +++ b/api/src/com/cloud/network/Networks.java @@ -103,7 +103,17 @@ public class Networks { Storage, Management, Control, - Vpn + Vpn; + + public static boolean isSystemNetwork(TrafficType trafficType) { + if(Storage.equals(trafficType) + || Management.equals(trafficType) + || Control.equals(trafficType)){ + return true; + } + return false; + } + }; public enum IsolationType { diff --git a/api/src/com/cloud/network/PhysicalNetworkTrafficType.java b/api/src/com/cloud/network/PhysicalNetworkTrafficType.java new file mode 100644 index 00000000000..8a58e4c4055 --- /dev/null +++ b/api/src/com/cloud/network/PhysicalNetworkTrafficType.java @@ -0,0 +1,45 @@ +/** + * Copyright (C) 2011 Citrix Systems, Inc. All rights reserved. + * + * This software is licensed under the GNU General Public License v3 or later. + * + * It is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or any later version. + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + */ + +/** + * + */ +package com.cloud.network; + +import com.cloud.network.Networks.TrafficType; + + + +/** + * This defines the specifics of a physical network traffic type + * + */ +public interface PhysicalNetworkTrafficType { + + long getId(); + + long getPhysicalNetworkId(); + + TrafficType getTrafficType(); + + String getXenNetworkLabel(); + + String getKvmNetworkLabel(); + + String getVmwareNetworkLabel(); +} diff --git a/client/tomcatconf/commands.properties.in b/client/tomcatconf/commands.properties.in index 45a74b945f5..a11c815c0d7 100755 --- a/client/tomcatconf/commands.properties.in +++ b/client/tomcatconf/commands.properties.in @@ -301,3 +301,9 @@ addNetworkServiceProvider=com.cloud.api.commands.AddNetworkServiceProviderCmd;1 deleteNetworkServiceProvider=com.cloud.api.commands.DeleteNetworkServiceProviderCmd;1 listNetworkServiceProviders=com.cloud.api.commands.ListNetworkServiceProvidersCmd;1 updateNetworkServiceProvider=com.cloud.api.commands.UpdateNetworkServiceProviderCmd;1 + +#### Physical Network Traffic Type commands +addTrafficType=com.cloud.api.commands.AddTrafficTypeCmd;1 +deleteTrafficType=com.cloud.api.commands.DeleteTrafficTypeCmd;1 +listTrafficTypes=com.cloud.api.commands.ListTrafficTypesCmd;1 +updateTrafficType=com.cloud.api.commands.UpdateTrafficTypeCmd;1 diff --git a/server/src/com/cloud/api/ApiResponseHelper.java b/server/src/com/cloud/api/ApiResponseHelper.java index e693a253aff..a83288f4647 100755 --- a/server/src/com/cloud/api/ApiResponseHelper.java +++ b/server/src/com/cloud/api/ApiResponseHelper.java @@ -82,6 +82,7 @@ import com.cloud.api.response.SystemVmInstanceResponse; import com.cloud.api.response.SystemVmResponse; import com.cloud.api.response.TemplatePermissionsResponse; import com.cloud.api.response.TemplateResponse; +import com.cloud.api.response.TrafficTypeResponse; import com.cloud.api.response.UserResponse; import com.cloud.api.response.UserVmResponse; import com.cloud.api.response.VlanIpRangeResponse; @@ -123,6 +124,7 @@ import com.cloud.network.NetworkProfile; import com.cloud.network.Networks.TrafficType; import com.cloud.network.PhysicalNetwork; import com.cloud.network.PhysicalNetworkServiceProvider; +import com.cloud.network.PhysicalNetworkTrafficType; import com.cloud.network.RemoteAccessVpn; import com.cloud.network.VpnUser; import com.cloud.network.router.VirtualRouter; @@ -2590,4 +2592,18 @@ public class ApiResponseHelper implements ResponseGenerator { response.setObjectName("networkserviceprovider"); return response; } + + @Override + public TrafficTypeResponse createTrafficTypeResponse(PhysicalNetworkTrafficType result) { + TrafficTypeResponse response = new TrafficTypeResponse(); + response.setId(result.getId()); + response.setPhysicalNetworkId(result.getPhysicalNetworkId()); + response.setTrafficType(result.getTrafficType().toString()); + response.setXenLabel(result.getXenNetworkLabel()); + response.setKvmLabel(result.getKvmNetworkLabel()); + response.setVmwareLabel(result.getVmwareNetworkLabel()); + + response.setObjectName("traffictype"); + return response; + } } diff --git a/server/src/com/cloud/configuration/DefaultComponentLibrary.java b/server/src/com/cloud/configuration/DefaultComponentLibrary.java index a29ed284b4b..95c3512cb7f 100755 --- a/server/src/com/cloud/configuration/DefaultComponentLibrary.java +++ b/server/src/com/cloud/configuration/DefaultComponentLibrary.java @@ -70,7 +70,6 @@ import com.cloud.keystore.KeystoreManagerImpl; import com.cloud.maint.UpgradeManagerImpl; import com.cloud.maint.dao.AgentUpgradeDaoImpl; import com.cloud.network.NetworkManagerImpl; -import com.cloud.network.VirtualNetworkApplianceService; import com.cloud.network.dao.FirewallRulesCidrsDaoImpl; import com.cloud.network.dao.FirewallRulesDaoImpl; import com.cloud.network.dao.IPAddressDaoImpl; @@ -83,14 +82,15 @@ import com.cloud.network.dao.NetworkRuleConfigDaoImpl; import com.cloud.network.dao.PhysicalNetworkDaoImpl; import com.cloud.network.dao.PhysicalNetworkExternalDeviceDaoImpl; import com.cloud.network.dao.PhysicalNetworkServiceProviderDaoImpl; +import com.cloud.network.dao.PhysicalNetworkTrafficTypeDaoImpl; import com.cloud.network.dao.RemoteAccessVpnDaoImpl; import com.cloud.network.dao.VirtualRouterElementsDaoImpl; import com.cloud.network.dao.VpnUserDaoImpl; import com.cloud.network.element.DhcpElement; -import com.cloud.network.element.RedundantVirtualRouterElement; -import com.cloud.network.element.VirtualRouterElement; import com.cloud.network.element.DhcpElementService; +import com.cloud.network.element.RedundantVirtualRouterElement; import com.cloud.network.element.RedundantVirtualRouterElementService; +import com.cloud.network.element.VirtualRouterElement; import com.cloud.network.element.VirtualRouterElementService; import com.cloud.network.firewall.FirewallManagerImpl; import com.cloud.network.lb.ElasticLoadBalancerManagerImpl; @@ -299,6 +299,7 @@ public class DefaultComponentLibrary extends ComponentLibraryBase implements Com addDao("PhysicalNetworkServiceProviderDao", PhysicalNetworkServiceProviderDaoImpl.class); addDao("VirtualRouterElementsDao", VirtualRouterElementsDaoImpl.class); addDao("PhysicalNetworkExternalDeviceDao", PhysicalNetworkExternalDeviceDaoImpl.class); + addDao("PhysicalNetworkTrafficTypeDao", PhysicalNetworkTrafficTypeDaoImpl.class); } @Override diff --git a/server/src/com/cloud/network/NetworkManagerImpl.java b/server/src/com/cloud/network/NetworkManagerImpl.java index ab210fd5da6..4d6d3c56363 100755 --- a/server/src/com/cloud/network/NetworkManagerImpl.java +++ b/server/src/com/cloud/network/NetworkManagerImpl.java @@ -103,14 +103,15 @@ import com.cloud.network.dao.NetworkDomainDao; import com.cloud.network.dao.PhysicalNetworkDao; import com.cloud.network.dao.PhysicalNetworkServiceProviderDao; import com.cloud.network.dao.PhysicalNetworkServiceProviderVO; +import com.cloud.network.dao.PhysicalNetworkTrafficTypeDao; +import com.cloud.network.dao.PhysicalNetworkTrafficTypeVO; import com.cloud.network.element.FirewallServiceProvider; import com.cloud.network.element.LoadBalancingServiceProvider; import com.cloud.network.element.NetworkElement; import com.cloud.network.element.PortForwardingServiceProvider; +import com.cloud.network.element.RemoteAccessVPNServiceProvider; import com.cloud.network.element.StaticNatServiceProvider; import com.cloud.network.element.UserDataServiceProvider; -import com.cloud.network.element.RemoteAccessVPNServiceProvider; -import com.cloud.network.element.SourceNatServiceProvider; import com.cloud.network.guru.NetworkGuru; import com.cloud.network.lb.LoadBalancingRule; import com.cloud.network.lb.LoadBalancingRule.LbDestination; @@ -119,8 +120,8 @@ import com.cloud.network.rules.FirewallManager; import com.cloud.network.rules.FirewallRule; import com.cloud.network.rules.FirewallRule.Purpose; import com.cloud.network.rules.FirewallRuleVO; -import com.cloud.network.rules.PortForwardingRuleVO; import com.cloud.network.rules.PortForwardingRule; +import com.cloud.network.rules.PortForwardingRuleVO; import com.cloud.network.rules.RulesManager; import com.cloud.network.rules.StaticNat; import com.cloud.network.rules.StaticNatRule; @@ -255,6 +256,7 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag @Inject PhysicalNetworkServiceProviderDao _pNSPDao; @Inject PortForwardingRulesDao _portForwardingRulesDao; @Inject LoadBalancerDao _lbDao; + @Inject PhysicalNetworkTrafficTypeDao _pNTrafficTypeDao; private final HashMap _systemNetworks = new HashMap(5); @@ -4201,4 +4203,109 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag return supported; } + @Override + @DB + @ActionEvent(eventType = EventTypes.EVENT_TRAFFIC_TYPE_CREATE, eventDescription = "Creating Physical Network TrafficType", create = true) + public PhysicalNetworkTrafficType addTrafficTypeToPhysicalNetwork(Long physicalNetworkId, String trafficTypeStr, String xenLabel, String kvmLabel, String vmwareLabel) { + + // verify input parameters + PhysicalNetworkVO network = _physicalNetworkDao.findById(physicalNetworkId); + if (network == null) { + throw new InvalidParameterValueException("Physical Network id=" + physicalNetworkId + "doesn't exist in the system"); + } + + + Networks.TrafficType trafficType = null; + if (trafficTypeStr != null && !trafficTypeStr.isEmpty()) { + try { + trafficType = Networks.TrafficType.valueOf(trafficTypeStr); + } catch (IllegalArgumentException ex) { + throw new InvalidParameterValueException("Unable to resolve trafficType '" + trafficTypeStr + "' to a supported value"); + } + } + + //For Storage, Control, Management, Public check if the zone has any other physical network with this traffictype already present + //If yes, we cant add these traffics to one more physical network in the zone. + + if(TrafficType.isSystemNetwork(trafficType) || TrafficType.Public.equals(trafficType)){ + if(!_physicalNetworkDao.listByZoneAndTrafficType(network.getDataCenterId(), trafficType).isEmpty()){ + throw new CloudRuntimeException("Fail to add the traffic type to physical network because Zone already has a physical network with this traffic type: "+trafficType); + } + } + + Transaction txn = Transaction.currentTxn(); + try { + txn.start(); + // Create the new traffic type in the database + PhysicalNetworkTrafficTypeVO pNetworktrafficType = new PhysicalNetworkTrafficTypeVO(physicalNetworkId, trafficType, xenLabel, kvmLabel, vmwareLabel); + pNetworktrafficType = _pNTrafficTypeDao.persist(pNetworktrafficType); + + txn.commit(); + return pNetworktrafficType; + } catch (Exception ex) { + txn.rollback(); + s_logger.warn("Exception: ", ex); + throw new CloudRuntimeException("Fail to add a traffic type to physical network"); + } finally { + txn.close(); + } + + } + + @ActionEvent(eventType = EventTypes.EVENT_TRAFFIC_TYPE_CREATE, eventDescription = "Creating Physical Network TrafficType", async = true) + public PhysicalNetworkTrafficType getPhysicalNetworkTrafficType(Long id){ + return _pNTrafficTypeDao.findById(id); + } + + @Override + @ActionEvent(eventType = EventTypes.EVENT_TRAFFIC_TYPE_UPDATE, eventDescription = "Updating physical network TrafficType", async = true) + public PhysicalNetworkTrafficType updatePhysicalNetworkTrafficType(Long id, String xenLabel, String kvmLabel, String vmwareLabel) { + + PhysicalNetworkTrafficTypeVO trafficType = _pNTrafficTypeDao.findById(id); + + if(trafficType == null){ + throw new InvalidParameterValueException("Traffic Type with id=" + id + "doesn't exist in the system"); + } + + if(xenLabel != null){ + trafficType.setXenNetworkLabel(xenLabel); + } + if(kvmLabel != null){ + trafficType.setKvmNetworkLabel(kvmLabel); + } + if(vmwareLabel != null){ + trafficType.setVmwareNetworkLabel(vmwareLabel); + } + _pNTrafficTypeDao.update(id, trafficType); + + return trafficType; + } + + @Override + @ActionEvent(eventType = EventTypes.EVENT_TRAFFIC_TYPE_DELETE, eventDescription = "Deleting physical network TrafficType", async = true) + public boolean deletePhysicalNetworkTrafficType(Long id) { + PhysicalNetworkTrafficTypeVO trafficType = _pNTrafficTypeDao.findById(id); + + if(trafficType == null){ + throw new InvalidParameterValueException("Traffic Type with id=" + id + "doesn't exist in the system"); + } + + //check if there are any networks associated to this physical network with this traffic type + if(TrafficType.Guest.equals(trafficType.getTrafficType())){ + if(!_networksDao.listByPhysicalNetworkTrafficType(trafficType.getPhysicalNetworkId(), trafficType.getTrafficType()).isEmpty()){ + throw new CloudRuntimeException("The Traffic Type is not deletable because there are existing networks with this traffic type:"+trafficType.getTrafficType()); + } + } + return _pNTrafficTypeDao.remove(id); + } + + @Override + public List listTrafficTypes(Long physicalNetworkId) { + PhysicalNetworkVO network = _physicalNetworkDao.findById(physicalNetworkId); + if (network == null) { + throw new InvalidParameterValueException("Physical Network id=" + physicalNetworkId + "doesn't exist in the system"); + } + + return _pNTrafficTypeDao.listBy(physicalNetworkId); + } } diff --git a/server/src/com/cloud/network/dao/NetworkDao.java b/server/src/com/cloud/network/dao/NetworkDao.java index b099dbef39e..ab40b96074f 100644 --- a/server/src/com/cloud/network/dao/NetworkDao.java +++ b/server/src/com/cloud/network/dao/NetworkDao.java @@ -22,6 +22,7 @@ import java.util.List; import com.cloud.network.Network; import com.cloud.network.NetworkAccountVO; import com.cloud.network.NetworkVO; +import com.cloud.network.Networks.TrafficType; import com.cloud.utils.db.GenericDao; import com.cloud.utils.db.SearchBuilder; @@ -72,4 +73,6 @@ public interface NetworkDao extends GenericDao { List listByPhysicalNetworkIncludingRemoved(long physicalNetworkId); List listSecurityGroupEnabledNetworks(); + + List listByPhysicalNetworkTrafficType(long physicalNetworkId, TrafficType trafficType); } diff --git a/server/src/com/cloud/network/dao/NetworkDaoImpl.java b/server/src/com/cloud/network/dao/NetworkDaoImpl.java index 700b9cdd711..4d4f3ebe935 100644 --- a/server/src/com/cloud/network/dao/NetworkDaoImpl.java +++ b/server/src/com/cloud/network/dao/NetworkDaoImpl.java @@ -363,4 +363,13 @@ public class NetworkDaoImpl extends GenericDaoBase implements N return listIncludingRemovedBy(sc); } + @Override + public List listByPhysicalNetworkTrafficType(long physicalNetworkId, TrafficType trafficType){ + SearchCriteria sc = AllFieldsSearch.create(); + sc.setParameters("trafficType", trafficType); + sc.setParameters("physicalNetworkId", physicalNetworkId); + return listBy(sc); + } + + } diff --git a/server/src/com/cloud/network/dao/PhysicalNetworkDao.java b/server/src/com/cloud/network/dao/PhysicalNetworkDao.java index c2c1a04ecfc..e7523eec763 100644 --- a/server/src/com/cloud/network/dao/PhysicalNetworkDao.java +++ b/server/src/com/cloud/network/dao/PhysicalNetworkDao.java @@ -19,10 +19,12 @@ package com.cloud.network.dao; import java.util.List; +import com.cloud.network.Networks.TrafficType; import com.cloud.network.PhysicalNetworkVO; import com.cloud.utils.db.GenericDao; public interface PhysicalNetworkDao extends GenericDao { List listByZone(long zoneId); List listByZoneIncludingRemoved(long zoneId); + List listByZoneAndTrafficType(long dataCenterId, TrafficType trafficType); } diff --git a/server/src/com/cloud/network/dao/PhysicalNetworkDaoImpl.java b/server/src/com/cloud/network/dao/PhysicalNetworkDaoImpl.java index d49c3830876..51f0e146f2e 100644 --- a/server/src/com/cloud/network/dao/PhysicalNetworkDaoImpl.java +++ b/server/src/com/cloud/network/dao/PhysicalNetworkDaoImpl.java @@ -21,9 +21,12 @@ import java.util.List; import javax.ejb.Local; +import com.cloud.network.Networks.TrafficType; import com.cloud.network.PhysicalNetworkVO; +import com.cloud.utils.component.ComponentLocator; import com.cloud.utils.db.DB; import com.cloud.utils.db.GenericDaoBase; +import com.cloud.utils.db.JoinBuilder; import com.cloud.utils.db.SearchBuilder; import com.cloud.utils.db.SearchCriteria; import com.cloud.utils.db.SearchCriteria.Op; @@ -31,7 +34,9 @@ import com.cloud.utils.db.SearchCriteria.Op; @Local(value=PhysicalNetworkDao.class) @DB(txn=false) public class PhysicalNetworkDaoImpl extends GenericDaoBase implements PhysicalNetworkDao { final SearchBuilder ZoneSearch; - + + protected final PhysicalNetworkTrafficTypeDaoImpl _trafficTypeDao = ComponentLocator.inject(PhysicalNetworkTrafficTypeDaoImpl.class); + protected PhysicalNetworkDaoImpl() { super(); ZoneSearch = createSearchBuilder(); @@ -53,6 +58,25 @@ public class PhysicalNetworkDaoImpl extends GenericDaoBase listByZoneAndTrafficType(long dataCenterId, TrafficType trafficType) { + + SearchBuilder trafficTypeSearch = _trafficTypeDao.createSearchBuilder(); + PhysicalNetworkTrafficTypeVO trafficTypeEntity = trafficTypeSearch.entity(); + trafficTypeSearch.and("trafficType", trafficTypeSearch.entity().getTrafficType(), SearchCriteria.Op.EQ); + + SearchBuilder dcSearch = createSearchBuilder(); + dcSearch.and("dataCenterId", dcSearch.entity().getDataCenterId(), Op.EQ); + dcSearch.join("trafficTypeSearch", trafficTypeSearch, dcSearch.entity().getId(), trafficTypeEntity.getPhysicalNetworkId(), JoinBuilder.JoinType.INNER); + + SearchCriteria sc = dcSearch.create(); + sc.setJoinParameters("trafficTypeSearch", "trafficType", trafficType); + sc.setParameters("dataCenterId", dataCenterId); + + return listBy(sc); + + } } diff --git a/server/src/com/cloud/network/dao/PhysicalNetworkTrafficTypeDao.java b/server/src/com/cloud/network/dao/PhysicalNetworkTrafficTypeDao.java new file mode 100644 index 00000000000..6b901b2ec34 --- /dev/null +++ b/server/src/com/cloud/network/dao/PhysicalNetworkTrafficTypeDao.java @@ -0,0 +1,28 @@ +/** + * Copyright (C) 2011 Citrix Systems, Inc. All rights reserved. + * + * This software is licensed under the GNU General Public License v3 or later. + * + * It is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or any later version. + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + */ +package com.cloud.network.dao; + +import java.util.List; + +import com.cloud.utils.db.GenericDao; + +public interface PhysicalNetworkTrafficTypeDao extends GenericDao { + List listBy(long physicalNetworkId); + + +} diff --git a/server/src/com/cloud/network/dao/PhysicalNetworkTrafficTypeDaoImpl.java b/server/src/com/cloud/network/dao/PhysicalNetworkTrafficTypeDaoImpl.java new file mode 100644 index 00000000000..d483b9f19a2 --- /dev/null +++ b/server/src/com/cloud/network/dao/PhysicalNetworkTrafficTypeDaoImpl.java @@ -0,0 +1,49 @@ +/** + * Copyright (C) 2011 Citrix Systems, Inc. All rights reserved. + * + * This software is licensed under the GNU General Public License v3 or later. + * + * It is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or any later version. + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + */ +package com.cloud.network.dao; + +import java.util.List; + +import javax.ejb.Local; + +import com.cloud.utils.db.DB; +import com.cloud.utils.db.GenericDaoBase; +import com.cloud.utils.db.SearchBuilder; +import com.cloud.utils.db.SearchCriteria; +import com.cloud.utils.db.SearchCriteria.Op; + +@Local(value=PhysicalNetworkTrafficTypeDao.class) @DB(txn=false) +public class PhysicalNetworkTrafficTypeDaoImpl extends GenericDaoBase implements PhysicalNetworkTrafficTypeDao { + final SearchBuilder physicalNetworkSearch; + + protected PhysicalNetworkTrafficTypeDaoImpl() { + super(); + physicalNetworkSearch = createSearchBuilder(); + physicalNetworkSearch.and("physicalNetworkId", physicalNetworkSearch.entity().getPhysicalNetworkId(), Op.EQ); + physicalNetworkSearch.done(); + + } + + @Override + public List listBy(long physicalNetworkId) { + SearchCriteria sc = physicalNetworkSearch.create(); + sc.setParameters("physicalNetworkId", physicalNetworkId); + return search(sc, null); + } + +} diff --git a/server/src/com/cloud/network/dao/PhysicalNetworkTrafficTypeVO.java b/server/src/com/cloud/network/dao/PhysicalNetworkTrafficTypeVO.java new file mode 100644 index 00000000000..6473e4cc712 --- /dev/null +++ b/server/src/com/cloud/network/dao/PhysicalNetworkTrafficTypeVO.java @@ -0,0 +1,109 @@ +/** + * Copyright (C) 2011 Citrix Systems, Inc. All rights reserved. + * + * This software is licensed under the GNU General Public License v3 or later. + * + * It is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or any later version. + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + */ +package com.cloud.network.dao; + +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.EnumType; +import javax.persistence.Enumerated; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; +import javax.persistence.Table; + +import com.cloud.network.Networks.TrafficType; +import com.cloud.network.PhysicalNetworkTrafficType; + +@Entity +@Table(name = "physical_network_traffic_types") +public class PhysicalNetworkTrafficTypeVO implements PhysicalNetworkTrafficType { + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + @Column(name = "id") + private long id; + + @Column(name = "physical_network_id") + private long physicalNetworkId; + + @Column(name="traffic_type") + @Enumerated(value=EnumType.STRING) + TrafficType trafficType; + + @Column(name = "xen_network_label") + private String xenNetworkLabel; + + @Column(name = "kvm_network_label") + private String kvmNetworkLabel; + + @Column(name = "vmware_network_label") + private String vmwareNetworkLabel; + + public PhysicalNetworkTrafficTypeVO() { + } + + public PhysicalNetworkTrafficTypeVO(long physicalNetworkId, TrafficType trafficType, String xenLabel, String kvmLabel, String vmwareLabel) { + this.physicalNetworkId = physicalNetworkId; + this.trafficType = trafficType; + this.xenNetworkLabel = xenLabel; + this.kvmNetworkLabel = kvmLabel; + this.vmwareNetworkLabel = vmwareLabel; + } + + @Override + public long getId() { + return id; + } + + @Override + public long getPhysicalNetworkId() { + return physicalNetworkId; + } + + @Override + public TrafficType getTrafficType() { + return trafficType; + } + + public void setXenNetworkLabel(String xenNetworkLabel) { + this.xenNetworkLabel = xenNetworkLabel; + } + + @Override + public String getXenNetworkLabel() { + return xenNetworkLabel; + } + + public void setKvmNetworkLabel(String kvmNetworkLabel) { + this.kvmNetworkLabel = kvmNetworkLabel; + } + + @Override + public String getKvmNetworkLabel() { + return kvmNetworkLabel; + } + + public void setVmwareNetworkLabel(String vmwareNetworkLabel) { + this.vmwareNetworkLabel = vmwareNetworkLabel; + } + + @Override + public String getVmwareNetworkLabel() { + return vmwareNetworkLabel; + } + +} diff --git a/setup/db/create-schema.sql b/setup/db/create-schema.sql index 9b4f6d5d0d6..287c74fe0e2 100755 --- a/setup/db/create-schema.sql +++ b/setup/db/create-schema.sql @@ -1791,20 +1791,14 @@ CREATE TABLE `cloud`.`physical_network_traffic_types` ( `id` bigint unsigned NOT NULL AUTO_INCREMENT COMMENT 'id', `physical_network_id` bigint unsigned NOT NULL COMMENT 'id of the physical network', `traffic_type` varchar(32) NOT NULL COMMENT 'type of traffic going through this network', + `xen_network_label` varchar(255) COMMENT 'The network name label of the physical device dedicated to this traffic on a XenServer host', + `kvm_network_label` varchar(255) COMMENT 'The network name label of the physical device dedicated to this traffic on a KVM host', + `vmware_network_label` varchar(255) COMMENT 'The network name label of the physical device dedicated to this traffic on a VMware host', PRIMARY KEY (`id`), CONSTRAINT `fk_physical_network_traffic_types__physical_network_id` FOREIGN KEY (`physical_network_id`) REFERENCES `physical_network`(`id`) ON DELETE CASCADE, UNIQUE KEY(`physical_network_id`, `traffic_type`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8; -CREATE TABLE `cloud`.`traffic_type_details` ( - `id` bigint unsigned NOT NULL auto_increment, - `traffic_type_id` bigint unsigned NOT NULL COMMENT 'traffic_type id', - `name` varchar(255) NOT NULL, - `value` varchar(255) NOT NULL, - PRIMARY KEY (`id`), - CONSTRAINT `fk_traffic_type_details__traffic_type_id` FOREIGN KEY (`traffic_type_id`) REFERENCES `physical_network_traffic_types`(`id`) ON DELETE CASCADE -) ENGINE=InnoDB DEFAULT CHARSET=utf8; - CREATE TABLE `cloud`.`physical_network_service_providers` ( `id` bigint unsigned NOT NULL AUTO_INCREMENT COMMENT 'id', `physical_network_id` bigint unsigned NOT NULL COMMENT 'id of the physical network', From 1583211352ab5b97d6360ade39a2ae43785112ca Mon Sep 17 00:00:00 2001 From: prachi Date: Thu, 27 Oct 2011 17:42:42 -0700 Subject: [PATCH 045/159] Fixing build after removing physicalNetworkId from createvlanIpRangeCmd --- server/src/com/cloud/configuration/ConfigurationManagerImpl.java | 1 - 1 file changed, 1 deletion(-) diff --git a/server/src/com/cloud/configuration/ConfigurationManagerImpl.java b/server/src/com/cloud/configuration/ConfigurationManagerImpl.java index 23b379c927d..57150fc14e9 100755 --- a/server/src/com/cloud/configuration/ConfigurationManagerImpl.java +++ b/server/src/com/cloud/configuration/ConfigurationManagerImpl.java @@ -1803,7 +1803,6 @@ public class ConfigurationManagerImpl implements ConfigurationManager, Configura Boolean forVirtualNetwork = cmd.isForVirtualNetwork(); Long networkId = cmd.getNetworkID(); String networkVlanId = null; - Long physicalNetworkId = cmd.getPhysicalNetworkId(); //projectId and accountName can't be specified together String accountName = cmd.getAccountName(); From 6445bf4c49729c971011830768ac488aab4bafb4 Mon Sep 17 00:00:00 2001 From: alena Date: Fri, 28 Oct 2011 09:52:40 -0700 Subject: [PATCH 046/159] Added services/capabilities to the SecurityGroupElement --- .../network/element/SecurityGroupElement.java | 14 ++++++++++++-- 1 file changed, 12 insertions(+), 2 deletions(-) diff --git a/server/src/com/cloud/network/element/SecurityGroupElement.java b/server/src/com/cloud/network/element/SecurityGroupElement.java index 26226ecae56..93c66da2914 100644 --- a/server/src/com/cloud/network/element/SecurityGroupElement.java +++ b/server/src/com/cloud/network/element/SecurityGroupElement.java @@ -19,6 +19,7 @@ package com.cloud.network.element; +import java.util.HashMap; import java.util.Map; import javax.ejb.Local; @@ -41,15 +42,24 @@ import com.cloud.vm.VirtualMachineProfile; @Local(value=NetworkElement.class) public class SecurityGroupElement extends AdapterBase implements NetworkElement { + private static final Map> capabilities = setCapabilities(); @Override public Map> getCapabilities() { - return null; + return capabilities; } @Override public Provider getProvider() { - return null; + return Provider.SecurityGroupProvider; + } + + private static Map> setCapabilities() { + Map> capabilities = new HashMap>(); + + capabilities.put(Service.SecurityGroup, null); + + return capabilities; } @Override From 7b982efeaa9e590335b2a4a57d7011b49c3aba6a Mon Sep 17 00:00:00 2001 From: alena Date: Fri, 28 Oct 2011 10:24:37 -0700 Subject: [PATCH 047/159] Fixed Advance zone creation with security group enabled --- .../configuration/ConfigurationManager.java | 2 +- .../ConfigurationManagerImpl.java | 461 ++++++++++-------- server/src/com/cloud/dc/DataCenterVO.java | 3 +- .../com/cloud/network/dao/NetworkDaoImpl.java | 4 +- 4 files changed, 265 insertions(+), 205 deletions(-) diff --git a/server/src/com/cloud/configuration/ConfigurationManager.java b/server/src/com/cloud/configuration/ConfigurationManager.java index 58c8b25d996..78ba6abd370 100644 --- a/server/src/com/cloud/configuration/ConfigurationManager.java +++ b/server/src/com/cloud/configuration/ConfigurationManager.java @@ -189,7 +189,7 @@ public interface ConfigurationManager extends ConfigurationService, Manager { Vlan createVlanAndPublicIpRange(Long userId, Long zoneId, Long podId, String startIP, String endIP, String vlanGateway, String vlanNetmask, boolean forVirtualNetwork, String vlanId, Account account, Long networkId) throws InsufficientCapacityException, ConcurrentOperationException, InvalidParameterValueException; - void createDefaultNetworks(long zoneId) throws ConcurrentOperationException; + void createDefaultNetworks(long zoneId, boolean isSecurityGroupEnabled) throws ConcurrentOperationException; HostPodVO getPod(long id); diff --git a/server/src/com/cloud/configuration/ConfigurationManagerImpl.java b/server/src/com/cloud/configuration/ConfigurationManagerImpl.java index 57150fc14e9..393d1f1e721 100755 --- a/server/src/com/cloud/configuration/ConfigurationManagerImpl.java +++ b/server/src/com/cloud/configuration/ConfigurationManagerImpl.java @@ -96,6 +96,7 @@ import com.cloud.exception.ResourceUnavailableException; import com.cloud.host.dao.HostDetailsDao; import com.cloud.hypervisor.Hypervisor.HypervisorType; import com.cloud.network.Network; +import com.cloud.network.Network.GuestType; import com.cloud.network.Network.Provider; import com.cloud.network.Network.Service; import com.cloud.network.NetworkManager; @@ -260,11 +261,13 @@ public class ConfigurationManagerImpl implements ConfigurationManager, Configura @Override public boolean start() { - // TODO : this may not be a good place to do integrity check here, we put it here as we need _alertMgr to be properly + // TODO : this may not be a good place to do integrity check here, we + // put it here as we need _alertMgr to be properly // configured // before we can use it - // As it is so common for people to forget about configuring management.network.cidr, + // As it is so common for people to forget about configuring + // management.network.cidr, String mgtCidr = _configDao.getValue(Config.ManagementNetwork.key()); if (mgtCidr == null || mgtCidr.trim().isEmpty()) { String[] localCidrs = NetUtils.getLocalCidrs(); @@ -305,7 +308,7 @@ public class ConfigurationManagerImpl implements ConfigurationManager, Configura s_logger.error("Failed to update configuration option, name: " + name + ", value:" + value); throw new CloudRuntimeException("Failed to update configuration value. Please contact Cloud Support."); } - if ( Config.XenGuestNetwork.key().equals(name) ) { + if (Config.XenGuestNetwork.key().equals(name)) { String sql = "update host_details set value=? where name=?"; Transaction txn = Transaction.currentTxn(); PreparedStatement pstmt = null; @@ -318,7 +321,7 @@ public class ConfigurationManagerImpl implements ConfigurationManager, Configura } catch (SQLException e) { } catch (Throwable e) { } - } else if ( Config.XenPrivateNetwork.key().equals(name) ) { + } else if (Config.XenPrivateNetwork.key().equals(name)) { String sql = "update host_details set value=? where name=?"; Transaction txn = Transaction.currentTxn(); PreparedStatement pstmt = null; @@ -331,7 +334,7 @@ public class ConfigurationManagerImpl implements ConfigurationManager, Configura } catch (SQLException e) { } catch (Throwable e) { } - } else if ( Config.XenPublicNetwork.key().equals(name) ) { + } else if (Config.XenPublicNetwork.key().equals(name)) { String sql = "update host_details set value=? where name=?"; Transaction txn = Transaction.currentTxn(); PreparedStatement pstmt = null; @@ -344,7 +347,7 @@ public class ConfigurationManagerImpl implements ConfigurationManager, Configura } catch (SQLException e) { } catch (Throwable e) { } - } else if ( Config.XenStorageNetwork1.key().equals(name) ) { + } else if (Config.XenStorageNetwork1.key().equals(name)) { String sql = "update host_details set value=? where name=?"; Transaction txn = Transaction.currentTxn(); PreparedStatement pstmt = null; @@ -357,7 +360,7 @@ public class ConfigurationManagerImpl implements ConfigurationManager, Configura } catch (SQLException e) { } catch (Throwable e) { } - } else if ( Config.XenStorageNetwork2.key().equals(name) ) { + } else if (Config.XenStorageNetwork2.key().equals(name)) { String sql = "update host_details set value=? where name=?"; Transaction txn = Transaction.currentTxn(); PreparedStatement pstmt = null; @@ -402,12 +405,13 @@ public class ConfigurationManagerImpl implements ConfigurationManager, Configura } - @Override @ActionEvent(eventType = EventTypes.EVENT_CONFIGURATION_VALUE_EDIT, eventDescription = "updating configuration") + @Override + @ActionEvent(eventType = EventTypes.EVENT_CONFIGURATION_VALUE_EDIT, eventDescription = "updating configuration") public Configuration updateConfiguration(UpdateCfgCmd cmd) { Long userId = UserContext.current().getCallerUserId(); String name = cmd.getCfgName(); String value = cmd.getValue(); - UserContext.current().setEventDetails(" Name: "+name +" New Value: "+((value == null) ? "" : value)); + UserContext.current().setEventDetails(" Name: " + name + " New Value: " + ((value == null) ? "" : value)); // check if config value exists if (_configDao.findByName(name) == null) { throw new InvalidParameterValueException("Config parameter with name " + name + " doesn't exist"); @@ -490,7 +494,7 @@ public class ConfigurationManagerImpl implements ConfigurationManager, Configura return "Please enter valid hypervisor type"; } } - }else { + } else { String[] options = range.split(","); for (String option : options) { if (option.trim().equalsIgnoreCase(value)) { @@ -593,7 +597,8 @@ public class ConfigurationManagerImpl implements ConfigurationManager, Configura } } - private void checkPodAttributes(long podId, String podName, long zoneId, String gateway, String cidr, String startIp, String endIp, String allocationStateStr, boolean checkForDuplicates, boolean skipGatewayOverlapCheck) { + private void checkPodAttributes(long podId, String podName, long zoneId, String gateway, String cidr, String startIp, String endIp, String allocationStateStr, boolean checkForDuplicates, + boolean skipGatewayOverlapCheck) { if (checkForDuplicates) { // Check if the pod already exists if (validPod(podName, zoneId)) { @@ -603,7 +608,8 @@ public class ConfigurationManagerImpl implements ConfigurationManager, Configura String cidrAddress; long cidrSize; - // Get the individual cidrAddress and cidrSize values, if the CIDR is valid. If it's not valid, return an error. + // Get the individual cidrAddress and cidrSize values, if the CIDR is + // valid. If it's not valid, return an error. if (NetUtils.isValidCIDR(cidr)) { cidrAddress = getCidrAddress(cidr); cidrSize = getCidrSize(cidr); @@ -627,7 +633,7 @@ public class ConfigurationManagerImpl implements ConfigurationManager, Configura } // Don't allow gateway to overlap with start/endIp - if(!skipGatewayOverlapCheck){ + if (!skipGatewayOverlapCheck) { if (NetUtils.ipRangesOverlap(startIp, endIp, gateway, gateway)) { throw new InvalidParameterValueException("The gateway shouldn't overlap start/end ip addresses"); } @@ -673,7 +679,7 @@ public class ConfigurationManagerImpl implements ConfigurationManager, Configura @DB public boolean deletePod(DeletePodCmd cmd) { Long podId = cmd.getId(); - + Transaction txn = Transaction.currentTxn(); // Make sure the pod exists @@ -686,18 +692,18 @@ public class ConfigurationManagerImpl implements ConfigurationManager, Configura HostPodVO pod = _podDao.findById(podId); txn.start(); - + // Delete private ip addresses for the pod if there are any List privateIps = _privateIpAddressDao.listByPodIdDcId(Long.valueOf(podId), pod.getDataCenterId()); if (!privateIps.isEmpty()) { if (!(_privateIpAddressDao.deleteIpAddressByPod(podId))) { throw new CloudRuntimeException("Failed to cleanup private ip addresses for pod " + podId); } - + // Delete corresponding capacity record _capacityDao.removeBy(Capacity.CAPACITY_TYPE_PRIVATE_IP, null, podId, null); } - + // Delete link local ip addresses for the pod List localIps = _LinkLocalIpAllocDao.listByPodIdDcId(podId, pod.getDataCenterId()); if (!localIps.isEmpty()) { @@ -718,7 +724,7 @@ public class ConfigurationManagerImpl implements ConfigurationManager, Configura if (!(_podDao.remove(podId))) { throw new CloudRuntimeException("Failed to delete pod " + podId); } - + txn.commit(); return true; @@ -745,7 +751,8 @@ public class ConfigurationManagerImpl implements ConfigurationManager, Configura String[] rightRangeToAdd = null; boolean allowToDownsize = false; - // If the gateway, CIDR, private IP range is being changed, check if the pod has allocated private IP addresses + // If the gateway, CIDR, private IP range is being changed, check if the + // pod has allocated private IP addresses if (podHasAllocatedPrivateIPs(id)) { if (netmask != null) { @@ -909,7 +916,8 @@ public class ConfigurationManagerImpl implements ConfigurationManager, Configura String cidrAddress = getCidrAddress(cidr); int cidrSize = getCidrSize(cidr); - // endIp is an optional parameter; if not specified - default it to the end ip of the pod's cidr + // endIp is an optional parameter; if not specified - default it to the + // end ip of the pod's cidr if (startIp != null) { if (endIp == null) { endIp = NetUtils.getIpRangeEndIpFromCidr(cidrAddress, cidrSize); @@ -954,7 +962,6 @@ public class ConfigurationManagerImpl implements ConfigurationManager, Configura return pod; } - @DB protected void checkIfZoneIsDeletable(long zoneId) { List> tablesToCheck = new ArrayList>(); @@ -1000,7 +1007,7 @@ public class ConfigurationManagerImpl implements ConfigurationManager, Configura physicalNetworks.add(1, "data_center_id"); physicalNetworks.add(2, "there are physical networks in this zone"); tablesToCheck.add(physicalNetworks); - + for (List table : tablesToCheck) { String tableName = table.get(0); String column = table.get(1); @@ -1143,9 +1150,9 @@ public class ConfigurationManagerImpl implements ConfigurationManager, Configura } success = _zoneDao.remove(zoneId); - + if (success) { - //delete all capacity records for the zone + // delete all capacity records for the zone _capacityDao.removeBy(null, zoneId, null, null); } @@ -1155,7 +1162,8 @@ public class ConfigurationManagerImpl implements ConfigurationManager, Configura } - @Override @DB + @Override + @DB public DataCenter editZone(UpdateZoneCmd cmd) { // Parameter validation as from execute() method in V1 Long zoneId = cmd.getId(); @@ -1168,7 +1176,7 @@ public class ConfigurationManagerImpl implements ConfigurationManager, Configura List dnsSearchOrder = cmd.getDnsSearchOrder(); Boolean isPublic = cmd.isPublic(); String allocationStateStr = cmd.getAllocationState(); - String dhcpProvider = cmd.getDhcpProvider(); + String dhcpProvider = cmd.getDhcpProvider(); Map detailsMap = cmd.getDetails(); String networkDomain = cmd.getDomain(); @@ -1177,27 +1185,30 @@ public class ConfigurationManagerImpl implements ConfigurationManager, Configura Collection zoneDetailsCollection = detailsMap.values(); Iterator iter = zoneDetailsCollection.iterator(); while (iter.hasNext()) { - HashMap detail = (HashMap)iter.next(); - String key = (String)detail.get("key"); - String value = (String)detail.get("value"); + HashMap detail = (HashMap) iter.next(); + String key = (String) detail.get("key"); + String value = (String) detail.get("value"); if ((key == null) || (value == null)) { - throw new InvalidParameterValueException("Invalid Zone Detail specified, fields 'key' and 'value' cannot be null, please specify details in the form: details[0].key=XXX&details[0].value=YYY"); - } - //validate the zone detail keys are known keys - /*if(!ZoneConfig.doesKeyExist(key)){ - throw new InvalidParameterValueException("Invalid Zone Detail parameter: "+ key); - }*/ + throw new InvalidParameterValueException( + "Invalid Zone Detail specified, fields 'key' and 'value' cannot be null, please specify details in the form: details[0].key=XXX&details[0].value=YYY"); + } + // validate the zone detail keys are known keys + /* + * if(!ZoneConfig.doesKeyExist(key)){ throw new + * InvalidParameterValueException + * ("Invalid Zone Detail parameter: "+ key); } + */ newDetails.put(key, value); } - } - + } + // add the domain prefix list to details if not null - if (dnsSearchOrder != null){ - for(String dom : dnsSearchOrder){ + if (dnsSearchOrder != null) { + for (String dom : dnsSearchOrder) { if (!NetUtils.verifyDomainName(dom)) { throw new InvalidParameterValueException( "Invalid network domain suffixes. Total length shouldn't exceed 190 chars. Each domain label must be between 1 and 63 characters long, can contain ASCII letters 'a' through 'z', the digits '0' through '9', " - + "and the hyphen ('-'); can't start or end with \"-\""); + + "and the hyphen ('-'); can't start or end with \"-\""); } } newDetails.put(ZoneConfig.DnsSearchOrder.getName(), StringUtils.join(dnsSearchOrder, ",")); @@ -1242,13 +1253,13 @@ public class ConfigurationManagerImpl implements ConfigurationManager, Configura if (guestCidr == null) { guestCidr = zone.getGuestNetworkCidr(); } - - //validate network domain + + // validate network domain if (networkDomain != null) { if (!NetUtils.verifyDomainName(networkDomain)) { throw new InvalidParameterValueException( "Invalid network domain. Total length shouldn't exceed 190 chars. Each domain label must be between 1 and 63 characters long, can contain ASCII letters 'a' through 'z', the digits '0' through '9', " - + "and the hyphen ('-'); can't start or end with \"-\""); + + "and the hyphen ('-'); can't start or end with \"-\""); } } else { networkDomain = zone.getDomain(); @@ -1282,24 +1293,24 @@ public class ConfigurationManagerImpl implements ConfigurationManager, Configura Transaction txn = Transaction.currentTxn(); txn.start(); - + Map updatedDetails = new HashMap(); _zoneDao.loadDetails(zone); - if(zone.getDetails() != null){ + if (zone.getDetails() != null) { updatedDetails.putAll(zone.getDetails()); } updatedDetails.putAll(newDetails); - zone.setDetails(updatedDetails); + zone.setDetails(updatedDetails); if (allocationStateStr != null && !allocationStateStr.isEmpty()) { Grouping.AllocationState allocationState = Grouping.AllocationState.valueOf(allocationStateStr); zone.setAllocationState(allocationState); } - if(dhcpProvider != null){ + if (dhcpProvider != null) { zone.setDhcpProvider(dhcpProvider); } - + if (!_zoneDao.update(zoneId, zone)) { throw new CloudRuntimeException("Failed to edit zone. Please contact Cloud Support."); } @@ -1313,18 +1324,19 @@ public class ConfigurationManagerImpl implements ConfigurationManager, Configura public DataCenterVO createZone(long userId, String zoneName, String dns1, String dns2, String internalDns1, String internalDns2, String guestCidr, String domain, Long domainId, NetworkType zoneType, String allocationStateStr, String networkDomain, boolean isSecurityGroupEnabled) { - // checking the following params outside checkzoneparams method as we do not use these params for updatezone + // checking the following params outside checkzoneparams method as we do + // not use these params for updatezone // hence the method below is generic to check for common params if ((guestCidr != null) && !NetUtils.validateGuestCidr(guestCidr)) { throw new InvalidParameterValueException("Please enter a valid guest cidr"); } - - //Validate network domain + + // Validate network domain if (networkDomain != null) { if (!NetUtils.verifyDomainName(networkDomain)) { throw new InvalidParameterValueException( "Invalid network domain. Total length shouldn't exceed 190 chars. Each domain label must be between 1 and 63 characters long, can contain ASCII letters 'a' through 'z', the digits '0' through '9', " - + "and the hyphen ('-'); can't start or end with \"-\""); + + "and the hyphen ('-'); can't start or end with \"-\""); } } @@ -1344,7 +1356,7 @@ public class ConfigurationManagerImpl implements ConfigurationManager, Configura zone = _zoneDao.persist(zone); // Create deafult networks - createDefaultNetworks(zone.getId()); + createDefaultNetworks(zone.getId(), isSecurityGroupEnabled); txn.commit(); return zone; } catch (Exception ex) { @@ -1357,10 +1369,11 @@ public class ConfigurationManagerImpl implements ConfigurationManager, Configura } @Override - public void createDefaultNetworks(long zoneId) throws ConcurrentOperationException { + public void createDefaultNetworks(long zoneId, boolean isSecurityGroupEnabled) throws ConcurrentOperationException { DataCenterVO zone = _zoneDao.findById(zoneId); String networkDomain = null; - // Create public, management, control and storage networks as a part of the zone creation + // Create public, management, control and storage networks as a part of + // the zone creation if (zone != null) { List ntwkOff = _networkOfferingDao.listSystemNetworkOfferings(); @@ -1386,6 +1399,8 @@ public class ConfigurationManagerImpl implements ConfigurationManager, Configura if (zone.getNetworkType() == NetworkType.Basic) { isNetworkDefault = true; broadcastDomainType = BroadcastDomainType.Native; + } else if (offering.getGuestType() == GuestType.Shared && isSecurityGroupEnabled) { + isNetworkDefault = true; } else { continue; } @@ -1415,7 +1430,7 @@ public class ConfigurationManagerImpl implements ConfigurationManager, Configura String allocationState = cmd.getAllocationState(); String networkDomain = cmd.getDomain(); boolean isSecurityGroupEnabled = cmd.getSecuritygroupenabled(); - + if (allocationState == null) { allocationState = Grouping.AllocationState.Enabled.toString(); } @@ -1428,7 +1443,8 @@ public class ConfigurationManagerImpl implements ConfigurationManager, Configura NetworkType zoneType = isBasic ? NetworkType.Basic : NetworkType.Advanced; - //Guest cidr is required for Advanced zone creation; error out when the parameter specified for Basic zone + // Guest cidr is required for Advanced zone creation; error out when the + // parameter specified for Basic zone if (zoneType == NetworkType.Advanced && guestCidr == null && !isSecurityGroupEnabled) { throw new InvalidParameterValueException("guestCidrAddress parameter is required for Advanced zone creation"); } else if (zoneType == NetworkType.Basic && guestCidr != null) { @@ -1449,13 +1465,14 @@ public class ConfigurationManagerImpl implements ConfigurationManager, Configura isSecurityGroupEnabled = true; } - return createZone(userId, zoneName, dns1, dns2, internalDns1, internalDns2, guestCidr, domainVO != null ? domainVO.getName() : null, domainId, zoneType, allocationState, networkDomain, isSecurityGroupEnabled); + return createZone(userId, zoneName, dns1, dns2, internalDns1, internalDns2, guestCidr, domainVO != null ? domainVO.getName() : null, domainId, zoneType, allocationState, networkDomain, + isSecurityGroupEnabled); } @Override public ServiceOffering createServiceOffering(CreateServiceOfferingCmd cmd) { Long userId = UserContext.current().getCallerUserId(); - + String name = cmd.getServiceOfferingName(); if ((name == null) || (name.length() == 0)) { throw new InvalidParameterValueException("Failed to create service offering: specify the name that has non-zero length"); @@ -1505,39 +1522,42 @@ public class ConfigurationManagerImpl implements ConfigurationManager, Configura if (limitCpuUse == null) { limitCpuUse = false; } - + String vmTypeString = cmd.getSystemVmType(); VirtualMachine.Type vmType = null; boolean allowNetworkRate = false; if (cmd.getIsSystem()) { - if (vmTypeString == null || VirtualMachine.Type.DomainRouter.toString().toLowerCase().equals(vmTypeString)){ + if (vmTypeString == null || VirtualMachine.Type.DomainRouter.toString().toLowerCase().equals(vmTypeString)) { vmType = VirtualMachine.Type.DomainRouter; allowNetworkRate = true; - } else if (VirtualMachine.Type.ConsoleProxy.toString().toLowerCase().equals(vmTypeString)){ + } else if (VirtualMachine.Type.ConsoleProxy.toString().toLowerCase().equals(vmTypeString)) { vmType = VirtualMachine.Type.ConsoleProxy; - } else if (VirtualMachine.Type.SecondaryStorageVm.toString().toLowerCase().equals(vmTypeString)){ + } else if (VirtualMachine.Type.SecondaryStorageVm.toString().toLowerCase().equals(vmTypeString)) { vmType = VirtualMachine.Type.SecondaryStorageVm; } else { - throw new InvalidParameterValueException("Invalid systemVmType. Supported types are: " + VirtualMachine.Type.DomainRouter + ", " + VirtualMachine.Type.ConsoleProxy + ", " + VirtualMachine.Type.SecondaryStorageVm); + throw new InvalidParameterValueException("Invalid systemVmType. Supported types are: " + VirtualMachine.Type.DomainRouter + ", " + VirtualMachine.Type.ConsoleProxy + ", " + + VirtualMachine.Type.SecondaryStorageVm); } } else { - allowNetworkRate = true;; + allowNetworkRate = true; + ; } - + if (cmd.getNetworkRate() != null && !allowNetworkRate) { throw new InvalidParameterValueException("Network rate can be specified only for non-System offering and system offerings having \"domainrouter\" systemvmtype"); } - return createServiceOffering(userId, cmd.getIsSystem(), vmType, cmd.getServiceOfferingName(), cpuNumber.intValue(), memory.intValue(), cpuSpeed.intValue(), cmd.getDisplayText(), localStorageRequired, offerHA, - limitCpuUse, cmd.getTags(), cmd.getDomainId(), cmd.getHostTag(), cmd.getNetworkRate()); + return createServiceOffering(userId, cmd.getIsSystem(), vmType, cmd.getServiceOfferingName(), cpuNumber.intValue(), memory.intValue(), cpuSpeed.intValue(), cmd.getDisplayText(), + localStorageRequired, offerHA, limitCpuUse, cmd.getTags(), cmd.getDomainId(), cmd.getHostTag(), cmd.getNetworkRate()); } @Override @ActionEvent(eventType = EventTypes.EVENT_SERVICE_OFFERING_CREATE, eventDescription = "creating service offering") - public ServiceOfferingVO createServiceOffering(long userId, boolean isSystem, VirtualMachine.Type vm_type, String name, int cpu, int ramSize, int speed, String displayText, boolean localStorageRequired, - boolean offerHA, boolean limitResourceUse, String tags, Long domainId, String hostTag, Integer networkRate) { + public ServiceOfferingVO createServiceOffering(long userId, boolean isSystem, VirtualMachine.Type vm_type, String name, int cpu, int ramSize, int speed, String displayText, + boolean localStorageRequired, boolean offerHA, boolean limitResourceUse, String tags, Long domainId, String hostTag, Integer networkRate) { tags = cleanupTags(tags); - ServiceOfferingVO offering = new ServiceOfferingVO(name, cpu, ramSize, speed, networkRate, null, offerHA, limitResourceUse, displayText, localStorageRequired, false, tags, isSystem, vm_type, domainId, hostTag); + ServiceOfferingVO offering = new ServiceOfferingVO(name, cpu, ramSize, speed, networkRate, null, offerHA, limitResourceUse, displayText, localStorageRequired, false, tags, isSystem, vm_type, + domainId, hostTag); if ((offering = _serviceOfferingDao.persist(offering)) != null) { UserContext.current().setEventDetails("Service offering id=" + offering.getId()); @@ -1581,7 +1601,8 @@ public class ConfigurationManagerImpl implements ConfigurationManager, Configura offering.setDisplayText(displayText); } - // Note: tag editing commented out for now; keeping the code intact, might need to re-enable in next releases + // Note: tag editing commented out for now; keeping the code intact, + // might need to re-enable in next releases // if (tags != null) // { // if (tags.trim().isEmpty() && offeringHandle.getTags() == null) @@ -1648,10 +1669,14 @@ public class ConfigurationManagerImpl implements ConfigurationManager, Configura String name = cmd.getOfferingName(); String description = cmd.getDisplayText(); Long numGibibytes = cmd.getDiskSize(); - boolean isCustomized = cmd.isCustomized() != null ? cmd.isCustomized() : false; // false by default + boolean isCustomized = cmd.isCustomized() != null ? cmd.isCustomized() : false; // false + // by + // default String tags = cmd.getTags(); - // Long domainId = cmd.getDomainId() != null ? cmd.getDomainId() : Long.valueOf(DomainVO.ROOT_DOMAIN); // disk offering - // always gets created under the root domain.Bug # 6055 if not passed in cmd + // Long domainId = cmd.getDomainId() != null ? cmd.getDomainId() : + // Long.valueOf(DomainVO.ROOT_DOMAIN); // disk offering + // always gets created under the root domain.Bug # 6055 if not passed in + // cmd Long domainId = cmd.getDomainId(); if (!isCustomized && numGibibytes == null) { @@ -1690,7 +1715,8 @@ public class ConfigurationManagerImpl implements ConfigurationManager, Configura diskOffering.setDisplayText(displayText); } - // Note: tag editing commented out for now;keeping the code intact, might need to re-enable in next releases + // Note: tag editing commented out for now;keeping the code intact, + // might need to re-enable in next releases // if (tags != null) // { // if (tags.trim().isEmpty() && diskOfferingHandle.getTags() == null) @@ -1698,7 +1724,8 @@ public class ConfigurationManagerImpl implements ConfigurationManager, Configura // //no new tags; no existing tags // diskOffering.setTagsArray(csvTagsToList(null)); // } - // else if (!tags.trim().isEmpty() && diskOfferingHandle.getTags() != null) + // else if (!tags.trim().isEmpty() && diskOfferingHandle.getTags() != + // null) // { // //new tags + existing tags // List oldTags = csvTagsToList(diskOfferingHandle.getTags()); @@ -1755,9 +1782,9 @@ public class ConfigurationManagerImpl implements ConfigurationManager, Configura ServiceOffering offering = getServiceOffering(offeringId); if (offering == null) { throw new InvalidParameterValueException("unable to find service offering " + offeringId); - } + } - if(offering.getDefaultUse()){ + if (offering.getDefaultUse()) { throw new InvalidParameterValueException("Default service offerings cannot be deleted"); } @@ -1803,13 +1830,13 @@ public class ConfigurationManagerImpl implements ConfigurationManager, Configura Boolean forVirtualNetwork = cmd.isForVirtualNetwork(); Long networkId = cmd.getNetworkID(); String networkVlanId = null; - - //projectId and accountName can't be specified together + + // projectId and accountName can't be specified together String accountName = cmd.getAccountName(); Long projectId = cmd.getProjectId(); Long domainId = cmd.getDomainId(); Account account = null; - + if (projectId != null) { if (accountName != null) { throw new InvalidParameterValueException("Account and projectId are mutually exclusive"); @@ -1818,7 +1845,7 @@ public class ConfigurationManagerImpl implements ConfigurationManager, Configura if (project == null) { throw new InvalidParameterValueException("Unable to find project by id " + projectId); } - + account = _accountMgr.getAccount(project.getProjectAccountId()); } @@ -1856,7 +1883,8 @@ public class ConfigurationManagerImpl implements ConfigurationManager, Configura throw new InvalidParameterValueException("Can't add virtual network into a zone with security group enabled"); } - // If networkId is not specified, and vlan is Virtual or Direct Untagged, try to locate default networks + // If networkId is not specified, and vlan is Virtual or Direct + // Untagged, try to locate default networks if (forVirtualNetwork) { if (network == null) { // find default public network in the zone @@ -1875,7 +1903,7 @@ public class ConfigurationManagerImpl implements ConfigurationManager, Configura } networkId = network.getId(); } - } else if (network.getGuestType() == null || network.getGuestType()== Network.GuestType.Isolated) { + } else if (network.getGuestType() == null || network.getGuestType() == Network.GuestType.Isolated) { throw new InvalidParameterValueException("Can't create direct vlan for network id=" + networkId + " with type: " + network.getGuestType()); } } @@ -1885,7 +1913,8 @@ public class ConfigurationManagerImpl implements ConfigurationManager, Configura endIP = startIP; } - // if vlan is specified, throw an error if it's not equal to network's vlanId + // if vlan is specified, throw an error if it's not equal to network's + // vlanId if (network != null) { URI uri = network.getBroadcastUri(); if (uri != null) { @@ -1931,7 +1960,8 @@ public class ConfigurationManagerImpl implements ConfigurationManager, Configura } } - // if it's an account specific range, associate ip address list to the account + // if it's an account specific range, associate ip address list to the + // account boolean associateIpRangeToAccount = false; if (forVirtualNetwork) { @@ -1942,7 +1972,9 @@ public class ConfigurationManagerImpl implements ConfigurationManager, Configura if (s_logger.isDebugEnabled()) { s_logger.debug(" IPResourceLimit " + ipResourceLimit + " accountIpRange " + accountIpRange); } - if (ipResourceLimit != -1 && accountIpRange > ipResourceLimit) { // -1 means infinite + if (ipResourceLimit != -1 && accountIpRange > ipResourceLimit) { // -1 + // means + // infinite throw new InvalidParameterValueException(" Public IP Resource Limit is set to " + ipResourceLimit + " which is less than the IP range of " + accountIpRange + " provided"); } associateIpRangeToAccount = true; @@ -2010,11 +2042,15 @@ public class ConfigurationManagerImpl implements ConfigurationManager, Configura throw new InvalidParameterValueException("Only Direct Untagged and Virtual networks are supported in the zone " + zone.getId() + " of type " + zone.getNetworkType()); } - //TODO - /* don't allow to create a virtual vlan when zone's vnet is NULL in Advanced zone - if ((zone.getNetworkType() == NetworkType.Advanced && zone.getVnet() == null) && forVirtualNetwork) { - throw new InvalidParameterValueException("Can't add virtual network to the zone id=" + zone.getId() + " as zone doesn't have guest vlan configured"); - }*/ + // TODO + /* + * don't allow to create a virtual vlan when zone's vnet is NULL in + * Advanced zone if ((zone.getNetworkType() == NetworkType.Advanced && + * zone.getVnet() == null) && forVirtualNetwork) { throw new + * InvalidParameterValueException + * ("Can't add virtual network to the zone id=" + zone.getId() + + * " as zone doesn't have guest vlan configured"); } + */ VlanType vlanType = forVirtualNetwork ? VlanType.VirtualNetwork : VlanType.DirectAttached; @@ -2066,7 +2102,8 @@ public class ConfigurationManagerImpl implements ConfigurationManager, Configura String newVlanSubnet = NetUtils.getSubNet(vlanGateway, vlanNetmask); - // Check if the new VLAN's subnet conflicts with the guest network in the specified zone (guestCidr is null for basic + // Check if the new VLAN's subnet conflicts with the guest network in + // the specified zone (guestCidr is null for basic // zone) String guestNetworkCidr = zone.getGuestNetworkCidr(); if (guestNetworkCidr != null) { @@ -2094,13 +2131,17 @@ public class ConfigurationManagerImpl implements ConfigurationManager, Configura checkPublicIpRangeErrors(zoneId, vlanId, vlanGateway, vlanNetmask, startIP, endIP); // Throw an exception if any of the following is true: - // 1. Another VLAN in the same zone has a different tag but the same subnet as the new VLAN. Make an exception for the + // 1. Another VLAN in the same zone has a different tag but the same + // subnet as the new VLAN. Make an exception for the // case when both vlans are Direct. - // 2. Another VLAN in the same zone that has the same tag and subnet as the new VLAN has IPs that overlap with the IPs + // 2. Another VLAN in the same zone that has the same tag and subnet as + // the new VLAN has IPs that overlap with the IPs // being added - // 3. Another VLAN in the same zone that has the same tag and subnet as the new VLAN has a different gateway than the + // 3. Another VLAN in the same zone that has the same tag and subnet as + // the new VLAN has a different gateway than the // new VLAN - // 4. If VLAN is untagged and Virtual, and there is existing UNTAGGED vlan with different subnet + // 4. If VLAN is untagged and Virtual, and there is existing UNTAGGED + // vlan with different subnet List vlans = _vlanDao.listByZone(zone.getId()); for (VlanVO vlan : vlans) { String otherVlanGateway = vlan.getVlanGateway(); @@ -2141,7 +2182,8 @@ public class ConfigurationManagerImpl implements ConfigurationManager, Configura throw new InvalidParameterValueException("The VLAN tag " + vlanId + " is already being used for the guest network in zone " + zone.getName()); } - // For untagged vlan check if vlan per pod already exists. If yes, verify that new vlan range has the same netmask and + // For untagged vlan check if vlan per pod already exists. If yes, + // verify that new vlan range has the same netmask and // gateway if (zone.getNetworkType() == NetworkType.Basic && vlanId.equalsIgnoreCase(Vlan.UNTAGGED) && podId != null) { List podVlans = _vlanDao.listVlansForPodByType(podId, VlanType.DirectAttached); @@ -2168,12 +2210,18 @@ public class ConfigurationManagerImpl implements ConfigurationManager, Configura vlan = _vlanDao.persist(vlan); if (!savePublicIPRange(startIP, endIP, zoneId, vlan.getId(), networkId)) { - throw new CloudRuntimeException("Failed to save IP range. Please contact Cloud Support."); // It can be Direct IP or + throw new CloudRuntimeException("Failed to save IP range. Please contact Cloud Support."); // It + // can + // be + // Direct + // IP + // or // Public IP. } if (account != null) { - // This VLAN is account-specific, so create an AccountVlanMapVO entry + // This VLAN is account-specific, so create an AccountVlanMapVO + // entry AccountVlanMapVO accountVlanMapVO = new AccountVlanMapVO(account.getId(), vlan.getId()); _accountVlanMapDao.persist(accountVlanMapVO); } else if (podId != null) { @@ -2401,7 +2449,8 @@ public class ConfigurationManagerImpl implements ConfigurationManager, Configura throw new InvalidParameterValueException("Please specify a valid IP range."); } - // Check that the IPs that are being added are compatible with the VLAN's gateway and netmask + // Check that the IPs that are being added are compatible with the + // VLAN's gateway and netmask if (vlanNetmask == null) { throw new InvalidParameterValueException("Please ensure that your IP range's netmask is specified"); } @@ -2438,7 +2487,8 @@ public class ConfigurationManagerImpl implements ConfigurationManager, Configura throw new InvalidParameterValueException("Please specify a valid IP range."); } - // Check that the IPs that are being added are compatible with the pod's CIDR + // Check that the IPs that are being added are compatible with the pod's + // CIDR String cidrAddress = getCidrAddress(podId); long cidrSize = getCidrSize(podId); @@ -2478,7 +2528,8 @@ public class ConfigurationManagerImpl implements ConfigurationManager, Configura private void checkPodCidrSubnets(long dcId, HashMap> currentPodCidrSubnets) { // For each pod, return an error if any of the following is true: // 1. The pod's CIDR subnet conflicts with the guest network subnet - // 2. The pod's CIDR subnet conflicts with the CIDR subnet of any other pod + // 2. The pod's CIDR subnet conflicts with the CIDR subnet of any other + // pod DataCenterVO dcVo = _zoneDao.findById(dcId); String guestNetworkCidr = dcVo.getGuestNetworkCidr(); @@ -2699,7 +2750,8 @@ public class ConfigurationManagerImpl implements ConfigurationManager, Configura throw new PermissionDeniedException("There's no way to confirm " + caller + " has access to zone:" + zone.getId()); } - @Override @ActionEvent(eventType = EventTypes.EVENT_NETWORK_OFFERING_CREATE, eventDescription = "creating network offering") + @Override + @ActionEvent(eventType = EventTypes.EVENT_NETWORK_OFFERING_CREATE, eventDescription = "creating network offering") public NetworkOffering createNetworkOffering(CreateNetworkOfferingCmd cmd) { Long userId = UserContext.current().getCallerUserId(); String name = cmd.getNetworkOfferingName(); @@ -2709,7 +2761,6 @@ public class ConfigurationManagerImpl implements ConfigurationManager, Configura Boolean specifyVlan = cmd.getSpecifyVlan(); String availabilityStr = cmd.getAvailability(); - Integer networkRate = cmd.getNetworkRate(); TrafficType trafficType = null; @@ -2727,15 +2778,14 @@ public class ConfigurationManagerImpl implements ConfigurationManager, Configura throw new InvalidParameterValueException("Invalid value for traffictype. Supported traffic types: Public, Management, Control, Guest, Vlan or Storage"); } - - //Verify offering type + // Verify offering type for (Network.GuestType offType : Network.GuestType.values()) { - if (offType.name().equalsIgnoreCase(cmd.getGuestIpType())){ + if (offType.name().equalsIgnoreCase(cmd.getGuestIpType())) { type = offType; break; } } - + if (type == null) { throw new InvalidParameterValueException("Invalid \"type\" parameter is given; can have Shared and Isolated values"); } @@ -2752,46 +2802,46 @@ public class ConfigurationManagerImpl implements ConfigurationManager, Configura } Integer maxConnections = cmd.getMaxconnections(); - - //configure service provider map + + // configure service provider map Map> serviceProviderMap = new HashMap>(); Set defaultProviders = new HashSet(); defaultProviders.add(Network.Provider.defaultProvider); - //populate all services first + // populate all services first if (cmd.getDhcpService()) { - serviceProviderMap.put(Network.Service.Dhcp, defaultProviders); + serviceProviderMap.put(Network.Service.Dhcp, defaultProviders); } - + if (cmd.getDnsService()) { - serviceProviderMap.put(Network.Service.Dns, defaultProviders); + serviceProviderMap.put(Network.Service.Dns, defaultProviders); } - + if (cmd.getFirewallService()) { - serviceProviderMap.put(Network.Service.Firewall, defaultProviders); + serviceProviderMap.put(Network.Service.Firewall, defaultProviders); } - + if (cmd.getGatewayService()) { - serviceProviderMap.put(Network.Service.Gateway, defaultProviders); + serviceProviderMap.put(Network.Service.Gateway, defaultProviders); } - + if (cmd.getLbService()) { - serviceProviderMap.put(Network.Service.Lb, defaultProviders); + serviceProviderMap.put(Network.Service.Lb, defaultProviders); } - + if (cmd.getSourceNatService()) { - serviceProviderMap.put(Network.Service.SourceNat, defaultProviders); + serviceProviderMap.put(Network.Service.SourceNat, defaultProviders); } - + if (cmd.getUserdataService()) { - serviceProviderMap.put(Network.Service.UserData, defaultProviders); + serviceProviderMap.put(Network.Service.UserData, defaultProviders); } - + if (cmd.getVpnService()) { - serviceProviderMap.put(Network.Service.Vpn, defaultProviders); - } - - //populate providers - Map> svcPrv = (Map>)cmd.getServiceProviders(); + serviceProviderMap.put(Network.Service.Vpn, defaultProviders); + } + + // populate providers + Map> svcPrv = (Map>) cmd.getServiceProviders(); if (svcPrv != null) { for (String serviceStr : svcPrv.keySet()) { Network.Service service = Network.Service.getService(serviceStr); @@ -2799,7 +2849,7 @@ public class ConfigurationManagerImpl implements ConfigurationManager, Configura serviceProviderMap.clear(); Set providers = new HashSet(); for (String prvNameStr : svcPrv.get(serviceStr)) { - //check if provider is supported + // check if provider is supported Network.Provider provider; provider = Network.Provider.getProvider(prvNameStr); if (provider == null) { @@ -2813,27 +2863,27 @@ public class ConfigurationManagerImpl implements ConfigurationManager, Configura } } } - + return createNetworkOffering(userId, name, displayText, trafficType, tags, maxConnections, specifyVlan, availability, networkRate, serviceProviderMap, false, type, false); } - @Override @DB - public NetworkOfferingVO createNetworkOffering(long userId, String name, String displayText, TrafficType trafficType, String tags, Integer maxConnections, boolean specifyVlan, + @Override + @DB + public NetworkOfferingVO createNetworkOffering(long userId, String name, String displayText, TrafficType trafficType, String tags, Integer maxConnections, boolean specifyVlan, Availability availability, Integer networkRate, Map> serviceProviderMap, boolean isDefault, Network.GuestType type, boolean systemOnly) { String multicastRateStr = _configDao.getValue("multicast.throttling.rate"); int multicastRate = ((multicastRateStr == null) ? 10 : Integer.parseInt(multicastRateStr)); tags = cleanupTags(tags); - NetworkOfferingVO offering = new NetworkOfferingVO(name, displayText, trafficType, systemOnly, specifyVlan, networkRate, multicastRate, maxConnections, isDefault, availability, tags, type); Transaction txn = Transaction.currentTxn(); txn.start(); - //create network offering object + // create network offering object s_logger.debug("Adding network offering " + offering); offering = _networkOfferingDao.persist(offering); - //populate services and providers + // populate services and providers if (serviceProviderMap != null) { for (Network.Service service : serviceProviderMap.keySet()) { for (Network.Provider provider : serviceProviderMap.get(service)) { @@ -2845,8 +2895,8 @@ public class ConfigurationManagerImpl implements ConfigurationManager, Configura } txn.commit(); - - UserContext.current().setEventDetails(" Id: "+offering.getId()+" Name: "+name); + + UserContext.current().setEventDetails(" Id: " + offering.getId() + " Name: " + name); return offering; } @@ -2887,11 +2937,11 @@ public class ConfigurationManagerImpl implements ConfigurationManager, Configura if (name != null) { sc.addAnd("name", SearchCriteria.Op.LIKE, "%" + name + "%"); } - + if (guestIpType != null) { sc.addAnd("guestType", SearchCriteria.Op.EQ, guestIpType); } - + if (displayText != null) { sc.addAnd("displayText", SearchCriteria.Op.LIKE, "%" + displayText + "%"); } @@ -2915,24 +2965,25 @@ public class ConfigurationManagerImpl implements ConfigurationManager, Configura if (availability != null) { sc.addAnd("availability", SearchCriteria.Op.EQ, availability); } - + if (state != null) { sc.addAnd("state", SearchCriteria.Op.EQ, state); } if (zone != null) { if (zone.getNetworkType() == NetworkType.Basic) { - // return empty list as we don't allow to create networks in basic zone, and shouldn't display networkOfferings + // return empty list as we don't allow to create networks in + // basic zone, and shouldn't display networkOfferings return new ArrayList(); } } - + // Don't return system network offerings to the user sc.addAnd("systemOnly", SearchCriteria.Op.EQ, false); - - //list offerings available for upgrade only + + // list offerings available for upgrade only if (networkId != null) { - //check if network exists and the caller can operate with it + // check if network exists and the caller can operate with it Network network = _networkMgr.getNetwork(networkId); if (network == null) { throw new InvalidParameterValueException("Unable to find the network by id=" + networkId); @@ -2942,18 +2993,18 @@ public class ConfigurationManagerImpl implements ConfigurationManager, Configura if (offering.isSystemOnly()) { throw new InvalidParameterValueException("Can't update system networks"); } - + _accountMgr.checkAccess(caller, null, network); - + List offeringIds = _networkMgr.listNetworkOfferingsForUpgrade(networkId); - + if (!offeringIds.isEmpty()) { - sc.addAnd("id", SearchCriteria.Op.IN, offeringIds.toArray()); + sc.addAnd("id", SearchCriteria.Op.IN, offeringIds.toArray()); } else { return new ArrayList(); } } - + if (id != null) { sc.addAnd("id", SearchCriteria.Op.EQ, id); } @@ -2961,11 +3012,12 @@ public class ConfigurationManagerImpl implements ConfigurationManager, Configura return _networkOfferingDao.search(sc, searchFilter); } - @Override @ActionEvent(eventType = EventTypes.EVENT_NETWORK_OFFERING_DELETE, eventDescription = "deleting network offering") + @Override + @ActionEvent(eventType = EventTypes.EVENT_NETWORK_OFFERING_DELETE, eventDescription = "deleting network offering") public boolean deleteNetworkOffering(DeleteNetworkOfferingCmd cmd) { Long offeringId = cmd.getId(); - UserContext.current().setEventDetails(" Id: "+offeringId); - + UserContext.current().setEventDetails(" Id: " + offeringId); + // Verify network offering id NetworkOfferingVO offering = _networkOfferingDao.findById(offeringId); if (offering == null) { @@ -2986,7 +3038,8 @@ public class ConfigurationManagerImpl implements ConfigurationManager, Configura } } - @Override @ActionEvent(eventType = EventTypes.EVENT_NETWORK_OFFERING_EDIT, eventDescription = "updating network offering") + @Override + @ActionEvent(eventType = EventTypes.EVENT_NETWORK_OFFERING_EDIT, eventDescription = "updating network offering") @DB public NetworkOffering updateNetworkOffering(UpdateNetworkOfferingCmd cmd) { String displayText = cmd.getDisplayText(); @@ -2995,8 +3048,8 @@ public class ConfigurationManagerImpl implements ConfigurationManager, Configura String availabilityStr = cmd.getAvailability(); Availability availability = null; String state = cmd.getState(); - UserContext.current().setEventDetails(" Id: "+id); - + UserContext.current().setEventDetails(" Id: " + id); + // Verify input parameters NetworkOfferingVO offeringToUpdate = _networkOfferingDao.findById(id); if (offeringToUpdate == null) { @@ -3017,7 +3070,7 @@ public class ConfigurationManagerImpl implements ConfigurationManager, Configura if (displayText != null) { offering.setDisplayText(displayText); } - + if (state != null) { boolean validState = false; for (NetworkOffering.State st : NetworkOffering.State.values()) { @@ -3044,50 +3097,51 @@ public class ConfigurationManagerImpl implements ConfigurationManager, Configura offering.setAvailability(availability); } } - - //All parameters below can be updated only when there are no networks using this offering + + // All parameters below can be updated only when there are no networks + // using this offering Long networks = _networkDao.getNetworkCountByOfferingId(id); boolean networksExist = (networks != null && networks.longValue() > 0); - - //configure service provider map + + // configure service provider map Map> serviceProviderMap = new HashMap>(); Set defaultProviders = new HashSet(); defaultProviders.add(Network.Provider.defaultProvider); - //populate all services first + // populate all services first if (cmd.getDhcpService()) { - serviceProviderMap.put(Network.Service.Dhcp, defaultProviders); + serviceProviderMap.put(Network.Service.Dhcp, defaultProviders); } - + if (cmd.getDnsService()) { - serviceProviderMap.put(Network.Service.Dns, defaultProviders); + serviceProviderMap.put(Network.Service.Dns, defaultProviders); } - + if (cmd.getFirewallService()) { - serviceProviderMap.put(Network.Service.Firewall, defaultProviders); + serviceProviderMap.put(Network.Service.Firewall, defaultProviders); } - + if (cmd.getGatewayService()) { - serviceProviderMap.put(Network.Service.Gateway, defaultProviders); + serviceProviderMap.put(Network.Service.Gateway, defaultProviders); } - + if (cmd.getLbService()) { - serviceProviderMap.put(Network.Service.Lb, defaultProviders); + serviceProviderMap.put(Network.Service.Lb, defaultProviders); } - + if (cmd.getSourceNatService()) { - serviceProviderMap.put(Network.Service.SourceNat, defaultProviders); + serviceProviderMap.put(Network.Service.SourceNat, defaultProviders); } - + if (cmd.getUserdataService()) { - serviceProviderMap.put(Network.Service.UserData, defaultProviders); + serviceProviderMap.put(Network.Service.UserData, defaultProviders); } - + if (cmd.getVpnService()) { - serviceProviderMap.put(Network.Service.Vpn, defaultProviders); - } - - //populate providers - Map> svcPrv = (Map>)cmd.getServiceProviders(); + serviceProviderMap.put(Network.Service.Vpn, defaultProviders); + } + + // populate providers + Map> svcPrv = (Map>) cmd.getServiceProviders(); if (svcPrv != null) { for (String serviceStr : svcPrv.keySet()) { Network.Service service = Network.Service.getService(serviceStr); @@ -3095,7 +3149,7 @@ public class ConfigurationManagerImpl implements ConfigurationManager, Configura serviceProviderMap.clear(); Set providers = new HashSet(); for (String prvNameStr : svcPrv.get(serviceStr)) { - //check if provider is supported + // check if provider is supported Network.Provider provider; provider = Network.Provider.getProvider(prvNameStr); if (provider == null) { @@ -3109,21 +3163,20 @@ public class ConfigurationManagerImpl implements ConfigurationManager, Configura } } } - + if (svcPrv != null && !svcPrv.isEmpty()) { if (networksExist) { throw new InvalidParameterValueException("Unable to reset service providers as there are existing networks using this network offering"); } } - - + boolean success = true; Transaction txn = Transaction.currentTxn(); txn.start(); - //update network offering + // update network offering success = success && _networkOfferingDao.update(id, offering); _ntwkOffServiceMapDao.deleteByOfferingId(id); - //update services/providers - delete old ones, insert new ones + // update services/providers - delete old ones, insert new ones if (serviceProviderMap != null) { for (Network.Service service : serviceProviderMap.keySet()) { for (Network.Provider provider : serviceProviderMap.get(service)) { @@ -3133,9 +3186,9 @@ public class ConfigurationManagerImpl implements ConfigurationManager, Configura } } } - + txn.commit(); - + if (success) { return _networkOfferingDao.findById(id); } else { @@ -3143,7 +3196,8 @@ public class ConfigurationManagerImpl implements ConfigurationManager, Configura } } - // Note: This method will be used for entity name validations in the coming releases (place holder for now) + // Note: This method will be used for entity name validations in the coming + // releases (place holder for now) private void validateEntityName(String str) { String forbidden = "~!@#$%^&*()+="; char[] searchChars = forbidden.toCharArray(); @@ -3186,8 +3240,10 @@ public class ConfigurationManagerImpl implements ConfigurationManager, Configura networkRate = Integer.parseInt(_configDao.getValue(Config.NetworkThrottlingRate.key())); } - // networkRate is unsigned int in netowrkOfferings table, and can't be set to -1 - // so 0 means unlimited; we convert it to -1, so we are consistent with all our other resources where -1 means unlimited + // networkRate is unsigned int in netowrkOfferings table, and can't be + // set to -1 + // so 0 means unlimited; we convert it to -1, so we are consistent with + // all our other resources where -1 means unlimited if (networkRate == 0) { networkRate = -1; } @@ -3200,7 +3256,8 @@ public class ConfigurationManagerImpl implements ConfigurationManager, Configura Vlan vlan = _vlanDao.findById(vlanId); Long accountId = null; - // if vlan is Virtual Account specific, get vlan information from the accountVlanMap; otherwise get account information + // if vlan is Virtual Account specific, get vlan information from the + // accountVlanMap; otherwise get account information // from the network if (vlan.getVlanType() == VlanType.VirtualNetwork) { List maps = _accountVlanMapDao.listAccountVlanMapsByVlan(vlanId); @@ -3267,7 +3324,7 @@ public class ConfigurationManagerImpl implements ConfigurationManager, Configura } private boolean allowIpRangeOverlap(VlanVO vlan, boolean forVirtualNetwork, long networkId) { - //FIXME - delete restriction for virtual network in the future + // FIXME - delete restriction for virtual network in the future if (vlan.getVlanType() == VlanType.DirectAttached && !forVirtualNetwork) { return true; } else { @@ -3303,7 +3360,7 @@ public class ConfigurationManagerImpl implements ConfigurationManager, Configura if (offering.getRateMbps() != null) { networkRate = offering.getRateMbps(); } else { - //for domain router service offering, get network rate from + // for domain router service offering, get network rate from if (offering.getSystemVmType() != null && offering.getSystemVmType().equalsIgnoreCase(VirtualMachine.Type.DomainRouter.toString())) { networkRate = Integer.parseInt(_configDao.getValue(Config.NetworkThrottlingRate.key())); } else { @@ -3311,8 +3368,10 @@ public class ConfigurationManagerImpl implements ConfigurationManager, Configura } } - // networkRate is unsigned int in serviceOffering table, and can't be set to -1 - // so 0 means unlimited; we convert it to -1, so we are consistent with all our other resources where -1 means unlimited + // networkRate is unsigned int in serviceOffering table, and can't be + // set to -1 + // so 0 means unlimited; we convert it to -1, so we are consistent with + // all our other resources where -1 means unlimited if (networkRate == 0) { networkRate = -1; } diff --git a/server/src/com/cloud/dc/DataCenterVO.java b/server/src/com/cloud/dc/DataCenterVO.java index 6b44bbac953..19b69193043 100644 --- a/server/src/com/cloud/dc/DataCenterVO.java +++ b/server/src/com/cloud/dc/DataCenterVO.java @@ -333,10 +333,11 @@ public class DataCenterVO implements DataCenter { @Override public boolean isSecurityGroupEnabled() { - return false; + return securityGroupEnabled; } public void setSecurityGroupEnabled(boolean enabled) { + this.securityGroupEnabled = enabled; } @Override diff --git a/server/src/com/cloud/network/dao/NetworkDaoImpl.java b/server/src/com/cloud/network/dao/NetworkDaoImpl.java index 4d4f3ebe935..c4114d9dcb0 100644 --- a/server/src/com/cloud/network/dao/NetworkDaoImpl.java +++ b/server/src/com/cloud/network/dao/NetworkDaoImpl.java @@ -275,7 +275,7 @@ public class NetworkDaoImpl extends GenericDaoBase implements N if (zoneId != null) { sc.setParameters("dataCenterId", zoneId); } - sc.setJoinParameters("services", "service", Service.SecurityGroup.toString()); + sc.setJoinParameters("services", "service", Service.SecurityGroup.getName()); return search(sc, null); } @@ -352,7 +352,7 @@ public class NetworkDaoImpl extends GenericDaoBase implements N @Override public List listSecurityGroupEnabledNetworks() { SearchCriteria sc = securityGroupSearch.create(); - sc.setJoinParameters("services", "service", Service.SecurityGroup.toString()); + sc.setJoinParameters("services", "service", Service.SecurityGroup.getName()); return listBy(sc); } From 818df189c545e3e475831f759a363948bde78ba5 Mon Sep 17 00:00:00 2001 From: prachi Date: Mon, 31 Oct 2011 09:48:37 -0700 Subject: [PATCH 048/159] changes to Create Vlan & Public IPs --- .../api/commands/CreateVlanIpRangeCmd.java | 7 ++ .../api/response/VlanIpRangeResponse.java | 11 +++ api/src/com/cloud/dc/Vlan.java | 2 + api/src/com/cloud/network/NetworkService.java | 3 +- .../src/com/cloud/api/ApiResponseHelper.java | 4 +- .../configuration/ConfigurationManager.java | 2 +- .../ConfigurationManagerImpl.java | 88 +++++++++++++------ server/src/com/cloud/dc/VlanVO.java | 15 +++- .../src/com/cloud/dc/dao/DataCenterDao.java | 2 +- .../com/cloud/dc/dao/DataCenterDaoImpl.java | 4 +- server/src/com/cloud/dc/dao/VlanDao.java | 2 + server/src/com/cloud/dc/dao/VlanDaoImpl.java | 13 ++- server/src/com/cloud/network/IPAddressVO.java | 11 +++ .../com/cloud/network/NetworkManagerImpl.java | 44 ++++++++-- .../src/com/cloud/network/addr/PublicIp.java | 5 ++ .../com/cloud/network/dao/IPAddressDao.java | 2 + .../cloud/network/dao/IPAddressDaoImpl.java | 9 +- .../dao/PhysicalNetworkTrafficTypeDao.java | 4 +- .../PhysicalNetworkTrafficTypeDaoImpl.java | 13 +++ .../cloud/server/ConfigurationServerImpl.java | 4 +- server/src/com/cloud/test/DatabaseConfig.java | 12 ++- server/src/com/cloud/test/IPRangeConfig.java | 23 ++--- server/src/com/cloud/test/PodZoneConfig.java | 20 ++++- setup/db/create-schema.sql | 6 +- setup/db/server-setup.xml | 1 + 25 files changed, 241 insertions(+), 66 deletions(-) diff --git a/api/src/com/cloud/api/commands/CreateVlanIpRangeCmd.java b/api/src/com/cloud/api/commands/CreateVlanIpRangeCmd.java index c02abc3880d..a67d39fe294 100644 --- a/api/src/com/cloud/api/commands/CreateVlanIpRangeCmd.java +++ b/api/src/com/cloud/api/commands/CreateVlanIpRangeCmd.java @@ -78,6 +78,8 @@ public class CreateVlanIpRangeCmd extends BaseCmd { @Parameter(name=ApiConstants.NETWORK_ID, type=CommandType.LONG, description="the network id") private Long networkID; + @Parameter(name=ApiConstants.PHYSICAL_NETWORK_ID, type=CommandType.LONG, description="the physical network id") + private Long physicalNetworkId; ///////////////////////////////////////////////////// /////////////////// Accessors /////////////////////// @@ -134,6 +136,11 @@ public class CreateVlanIpRangeCmd extends BaseCmd { return networkID; } + public Long getPhysicalNetworkId() { + return physicalNetworkId; + } + + @Override public String getCommandName() { return s_name; diff --git a/api/src/com/cloud/api/response/VlanIpRangeResponse.java b/api/src/com/cloud/api/response/VlanIpRangeResponse.java index 7effb13307e..e79790bba64 100644 --- a/api/src/com/cloud/api/response/VlanIpRangeResponse.java +++ b/api/src/com/cloud/api/response/VlanIpRangeResponse.java @@ -73,6 +73,9 @@ public class VlanIpRangeResponse extends BaseResponse implements ControlledEntit @SerializedName(ApiConstants.PROJECT) @Param(description="the project name of the vlan range") private String projectName; + + @SerializedName(ApiConstants.PHYSICAL_NETWORK_ID) @Param(description="the physical network this belongs to") + private Long physicalNetworkId; public void setId(Long id) { this.id = id; @@ -143,4 +146,12 @@ public class VlanIpRangeResponse extends BaseResponse implements ControlledEntit public void setProjectName(String projectName) { this.projectName = projectName; } + + public void setPhysicalNetworkId(long physicalNetworkId) { + this.physicalNetworkId = physicalNetworkId; + } + + public long getphysicalNetworkId() { + return physicalNetworkId; + } } diff --git a/api/src/com/cloud/dc/Vlan.java b/api/src/com/cloud/dc/Vlan.java index ad1769776a2..4fe58ddfd74 100644 --- a/api/src/com/cloud/dc/Vlan.java +++ b/api/src/com/cloud/dc/Vlan.java @@ -41,5 +41,7 @@ public interface Vlan { public VlanType getVlanType(); public Long getNetworkId(); + + public Long getPhysicalNetworkId(); } \ No newline at end of file diff --git a/api/src/com/cloud/network/NetworkService.java b/api/src/com/cloud/network/NetworkService.java index 4651bde9029..1892ced500e 100644 --- a/api/src/com/cloud/network/NetworkService.java +++ b/api/src/com/cloud/network/NetworkService.java @@ -125,5 +125,6 @@ public interface NetworkService { List listTrafficTypes(Long physicalNetworkId); - + PhysicalNetwork getDefaultPhysicalNetworkByZoneAndTrafficType(long zoneId, TrafficType trafficType); + } diff --git a/server/src/com/cloud/api/ApiResponseHelper.java b/server/src/com/cloud/api/ApiResponseHelper.java index a83288f4647..cbf149f2fee 100755 --- a/server/src/com/cloud/api/ApiResponseHelper.java +++ b/server/src/com/cloud/api/ApiResponseHelper.java @@ -636,7 +636,9 @@ public class ApiResponseHelper implements ResponseGenerator { populateAccount(vlanResponse, owner.getId()); populateDomain(vlanResponse, owner.getDomainId()); } - + + vlanResponse.setPhysicalNetworkId(vlan.getPhysicalNetworkId()); + vlanResponse.setObjectName("vlan"); return vlanResponse; } diff --git a/server/src/com/cloud/configuration/ConfigurationManager.java b/server/src/com/cloud/configuration/ConfigurationManager.java index 78ba6abd370..6519f766fe7 100644 --- a/server/src/com/cloud/configuration/ConfigurationManager.java +++ b/server/src/com/cloud/configuration/ConfigurationManager.java @@ -187,7 +187,7 @@ public interface ConfigurationManager extends ConfigurationService, Manager { NetworkOfferingVO createNetworkOffering(long userId, String name, String displayText, TrafficType trafficType, String tags, Integer maxConnections, boolean specifyVlan, Availability availability, Integer networkRate, Map> serviceProviderMap, boolean isDefault, Network.GuestType type, boolean systemOnly); - Vlan createVlanAndPublicIpRange(Long userId, Long zoneId, Long podId, String startIP, String endIP, String vlanGateway, String vlanNetmask, boolean forVirtualNetwork, String vlanId, Account account, Long networkId) throws InsufficientCapacityException, ConcurrentOperationException, InvalidParameterValueException; + Vlan createVlanAndPublicIpRange(Long userId, Long zoneId, Long podId, String startIP, String endIP, String vlanGateway, String vlanNetmask, boolean forVirtualNetwork, String vlanId, Account account, Long networkId, Long physicalNetworkId) throws InsufficientCapacityException, ConcurrentOperationException, InvalidParameterValueException; void createDefaultNetworks(long zoneId, boolean isSecurityGroupEnabled) throws ConcurrentOperationException; diff --git a/server/src/com/cloud/configuration/ConfigurationManagerImpl.java b/server/src/com/cloud/configuration/ConfigurationManagerImpl.java index 393d1f1e721..bd0768b57f8 100755 --- a/server/src/com/cloud/configuration/ConfigurationManagerImpl.java +++ b/server/src/com/cloud/configuration/ConfigurationManagerImpl.java @@ -103,8 +103,10 @@ import com.cloud.network.NetworkManager; import com.cloud.network.NetworkVO; import com.cloud.network.Networks.BroadcastDomainType; import com.cloud.network.Networks.TrafficType; +import com.cloud.network.PhysicalNetworkVO; import com.cloud.network.dao.IPAddressDao; import com.cloud.network.dao.NetworkDao; +import com.cloud.network.dao.PhysicalNetworkDao; import com.cloud.offering.DiskOffering; import com.cloud.offering.NetworkOffering; import com.cloud.offering.NetworkOffering.Availability; @@ -210,7 +212,8 @@ public class ConfigurationManagerImpl implements ConfigurationManager, Configura ProjectManager _projectMgr; @Inject NetworkOfferingServiceMapDao _ntwkOffServiceMapDao; - + @Inject PhysicalNetworkDao _physicalNetworkDao; + // FIXME - why don't we have interface for DataCenterLinkLocalIpAddressDao? protected static final DataCenterLinkLocalIpAddressDaoImpl _LinkLocalIpAllocDao = ComponentLocator.inject(DataCenterLinkLocalIpAddressDaoImpl.class); @@ -1830,8 +1833,8 @@ public class ConfigurationManagerImpl implements ConfigurationManager, Configura Boolean forVirtualNetwork = cmd.isForVirtualNetwork(); Long networkId = cmd.getNetworkID(); String networkVlanId = null; - - // projectId and accountName can't be specified together + Long physicalNetworkId = cmd.getPhysicalNetworkId(); + //projectId and accountName can't be specified together String accountName = cmd.getAccountName(); Long projectId = cmd.getProjectId(); Long domainId = cmd.getDomainId(); @@ -1855,7 +1858,7 @@ public class ConfigurationManagerImpl implements ConfigurationManager, Configura throw new InvalidParameterValueException("Please specify a valid account."); } } - + // Verify that network exists Network network = null; if (networkId != null) { @@ -1864,15 +1867,50 @@ public class ConfigurationManagerImpl implements ConfigurationManager, Configura throw new InvalidParameterValueException("Unable to find network by id " + networkId); } else { zoneId = network.getDataCenterId(); + physicalNetworkId = network.getPhysicalNetworkId(); } } + //verify that physical network exists + PhysicalNetworkVO pNtwk = null; + if(physicalNetworkId != null){ + pNtwk = _physicalNetworkDao.findById(physicalNetworkId); + if (pNtwk == null) { + throw new InvalidParameterValueException("Unable to find Physical Network with id=" + physicalNetworkId); + } + } + if(zoneId == null && pNtwk != null){ + zoneId = pNtwk.getDataCenterId(); + } // Verify that zone exists DataCenterVO zone = _zoneDao.findById(zoneId); if (zone == null) { throw new InvalidParameterValueException("Unable to find zone by id " + zoneId); } - + + if(physicalNetworkId == null){ + //deduce physicalNetworkFrom Zone or Network. + if(network != null && network.getPhysicalNetworkId() != null){ + physicalNetworkId = network.getPhysicalNetworkId(); + }else{ + if (forVirtualNetwork) { + //default physical network with public traffic in the zone + physicalNetworkId = _networkMgr.getDefaultPhysicalNetworkByZoneAndTrafficType(zoneId, TrafficType.Public).getId(); + }else{ + if (zone.getNetworkType() == DataCenter.NetworkType.Basic) { + //default physical network with guest traffic in the zone + physicalNetworkId = _networkMgr.getDefaultPhysicalNetworkByZoneAndTrafficType(zoneId, TrafficType.Guest).getId(); + }else if(zone.getNetworkType() == DataCenter.NetworkType.Advanced) { + if(zone.isSecurityGroupEnabled()){ + physicalNetworkId = _networkMgr.getDefaultPhysicalNetworkByZoneAndTrafficType(zoneId, TrafficType.Guest).getId(); + }else{ + throw new InvalidParameterValueException("Physical Network Id is null, please provide the Network id for Direct vlan creation "); + } + } + } + } + } + // Check if zone is disabled Account caller = UserContext.current().getCaller(); if (Grouping.AllocationState.Disabled == zone.getAllocationState() && !_accountMgr.isRootAdmin(caller.getType())) { @@ -1984,7 +2022,7 @@ public class ConfigurationManagerImpl implements ConfigurationManager, Configura Transaction txn = Transaction.currentTxn(); txn.start(); - Vlan vlan = createVlanAndPublicIpRange(userId, zoneId, podId, startIP, endIP, vlanGateway, vlanNetmask, forVirtualNetwork, vlanId, account, networkId); + Vlan vlan = createVlanAndPublicIpRange(userId, zoneId, podId, startIP, endIP, vlanGateway, vlanNetmask, forVirtualNetwork, vlanId, account, networkId, physicalNetworkId); if (associateIpRangeToAccount) { _networkMgr.associateIpAddressListToAccount(userId, account.getId(), zoneId, vlan.getId(), network); @@ -2016,7 +2054,7 @@ public class ConfigurationManagerImpl implements ConfigurationManager, Configura @Override @DB public Vlan createVlanAndPublicIpRange(Long userId, Long zoneId, Long podId, String startIP, String endIP, String vlanGateway, String vlanNetmask, boolean forVirtualNetwork, String vlanId, - Account account, Long networkId) { + Account account, Long networkId, Long physicalNetworkId) { // Check that the pod ID is valid if (podId != null && ((_podDao.findById(podId)) == null)) { throw new InvalidParameterValueException("Please specify a valid pod."); @@ -2034,6 +2072,12 @@ public class ConfigurationManagerImpl implements ConfigurationManager, Configura if (zoneId == null || ((zone = _zoneDao.findById(zoneId)) == null)) { throw new InvalidParameterValueException("Please specify a valid zone."); } + + PhysicalNetworkVO pNtwk; + if (physicalNetworkId == null || ((pNtwk = _physicalNetworkDao.findById(physicalNetworkId)) == null)) { + throw new InvalidParameterValueException("Please specify a valid physical network."); + } + // Allow adding untagged direct vlan only for Basic zone if (zone.getNetworkType() == NetworkType.Advanced && vlanId.equals(Vlan.UNTAGGED) && (!forVirtualNetwork || zone.isSecurityGroupEnabled())) { @@ -2042,15 +2086,10 @@ public class ConfigurationManagerImpl implements ConfigurationManager, Configura throw new InvalidParameterValueException("Only Direct Untagged and Virtual networks are supported in the zone " + zone.getId() + " of type " + zone.getNetworkType()); } - // TODO - /* - * don't allow to create a virtual vlan when zone's vnet is NULL in - * Advanced zone if ((zone.getNetworkType() == NetworkType.Advanced && - * zone.getVnet() == null) && forVirtualNetwork) { throw new - * InvalidParameterValueException - * ("Can't add virtual network to the zone id=" + zone.getId() + - * " as zone doesn't have guest vlan configured"); } - */ + // don't allow to create a virtual vlan when physical networks's vnet is NULL in Advanced zone + if ((zone.getNetworkType() == NetworkType.Advanced && pNtwk.getVnet() == null) && forVirtualNetwork) { + throw new InvalidParameterValueException("Can't add virtual network to the physical Network id="+pNtwk.getId() +" in zone id=" + zone.getId() + " as there is no guest vlan configured"); + } VlanType vlanType = forVirtualNetwork ? VlanType.VirtualNetwork : VlanType.DirectAttached; @@ -2178,7 +2217,7 @@ public class ConfigurationManagerImpl implements ConfigurationManager, Configura } // Check if a guest VLAN is using the same tag - if (_zoneDao.findVnet(zoneId, vlanId).size() > 0) { + if (_zoneDao.findVnet(zoneId, physicalNetworkId, vlanId).size() > 0) { throw new InvalidParameterValueException("The VLAN tag " + vlanId + " is already being used for the guest network in zone " + zone.getName()); } @@ -2206,16 +2245,11 @@ public class ConfigurationManagerImpl implements ConfigurationManager, Configura Transaction txn = Transaction.currentTxn(); txn.start(); - VlanVO vlan = new VlanVO(vlanType, vlanId, vlanGateway, vlanNetmask, zone.getId(), ipRange, networkId); + VlanVO vlan = new VlanVO(vlanType, vlanId, vlanGateway, vlanNetmask, zone.getId(), ipRange, networkId, physicalNetworkId); vlan = _vlanDao.persist(vlan); - if (!savePublicIPRange(startIP, endIP, zoneId, vlan.getId(), networkId)) { - throw new CloudRuntimeException("Failed to save IP range. Please contact Cloud Support."); // It - // can - // be - // Direct - // IP - // or + if (!savePublicIPRange(startIP, endIP, zoneId, vlan.getId(), networkId, physicalNetworkId)) { + throw new CloudRuntimeException("Failed to save IP range. Please contact Cloud Support."); // It can be Direct IP or // Public IP. } @@ -2376,13 +2410,13 @@ public class ConfigurationManagerImpl implements ConfigurationManager, Configura } @DB - protected boolean savePublicIPRange(String startIP, String endIP, long zoneId, long vlanDbId, long sourceNetworkid) { + protected boolean savePublicIPRange(String startIP, String endIP, long zoneId, long vlanDbId, long sourceNetworkid, long physicalNetworkId) { long startIPLong = NetUtils.ip2Long(startIP); long endIPLong = NetUtils.ip2Long(endIP); Transaction txn = Transaction.currentTxn(); txn.start(); IPRangeConfig config = new IPRangeConfig(); - List problemIps = config.savePublicIPRange(txn, startIPLong, endIPLong, zoneId, vlanDbId, sourceNetworkid); + List problemIps = config.savePublicIPRange(txn, startIPLong, endIPLong, zoneId, vlanDbId, sourceNetworkid, physicalNetworkId); txn.commit(); return problemIps != null && problemIps.size() == 0; } diff --git a/server/src/com/cloud/dc/VlanVO.java b/server/src/com/cloud/dc/VlanVO.java index 9981e0275f4..b8d26fb32d5 100644 --- a/server/src/com/cloud/dc/VlanVO.java +++ b/server/src/com/cloud/dc/VlanVO.java @@ -54,11 +54,14 @@ public class VlanVO implements Vlan { @Column(name="network_id") Long networkId; + @Column(name="physical_network_id") + Long physicalNetworkId; + @Column(name="vlan_type") @Enumerated(EnumType.STRING) VlanType vlanType; - public VlanVO(VlanType vlanType, String vlanTag, String vlanGateway, String vlanNetmask, long dataCenterId, String ipRange, Long networkId) { + public VlanVO(VlanType vlanType, String vlanTag, String vlanGateway, String vlanNetmask, long dataCenterId, String ipRange, Long networkId, Long physicalNetworkId) { this.vlanType = vlanType; this.vlanTag = vlanTag; this.vlanGateway = vlanGateway; @@ -66,6 +69,7 @@ public class VlanVO implements Vlan { this.dataCenterId = dataCenterId; this.ipRange = ipRange; this.networkId = networkId; + this.physicalNetworkId = physicalNetworkId; } public VlanVO() { @@ -107,4 +111,13 @@ public class VlanVO implements Vlan { public void setNetworkId(Long networkId) { this.networkId = networkId; } + + public Long getPhysicalNetworkId() { + return physicalNetworkId; + } + + public void setPhysicalNetworkId(Long physicalNetworkId) { + this.physicalNetworkId = physicalNetworkId; + } + } diff --git a/server/src/com/cloud/dc/dao/DataCenterDao.java b/server/src/com/cloud/dc/dao/DataCenterDao.java index 5ba0d5b4a07..5f7d2aa1cb4 100644 --- a/server/src/com/cloud/dc/dao/DataCenterDao.java +++ b/server/src/com/cloud/dc/dao/DataCenterDao.java @@ -50,7 +50,7 @@ public interface DataCenterDao extends GenericDao { void addPrivateIpAddress(long dcId,long podId, String start, String end); void addLinkLocalIpAddress(long dcId,long podId, String start, String end); - List findVnet(long dcId, String vnet); + List findVnet(long dcId, long physicalNetworkId, String vnet); String allocatePodVlan(long podId, long accountId); diff --git a/server/src/com/cloud/dc/dao/DataCenterDaoImpl.java b/server/src/com/cloud/dc/dao/DataCenterDaoImpl.java index 7f063f516b9..2e723fcef59 100644 --- a/server/src/com/cloud/dc/dao/DataCenterDaoImpl.java +++ b/server/src/com/cloud/dc/dao/DataCenterDaoImpl.java @@ -115,8 +115,8 @@ public class DataCenterDaoImpl extends GenericDaoBase implem } @Override - public List findVnet(long dcId, String vnet) { - return _vnetAllocDao.findVnet(dcId, vnet); + public List findVnet(long dcId, long physicalNetworkId, String vnet) { + return _vnetAllocDao.findVnet(dcId, physicalNetworkId, vnet); } @Override diff --git a/server/src/com/cloud/dc/dao/VlanDao.java b/server/src/com/cloud/dc/dao/VlanDao.java index 4cda0eedb9a..9860e60feda 100644 --- a/server/src/com/cloud/dc/dao/VlanDao.java +++ b/server/src/com/cloud/dc/dao/VlanDao.java @@ -50,4 +50,6 @@ public interface VlanDao extends GenericDao { List searchForZoneWideVlans(long dcId, String vlanType,String vlanId); List listVlansByNetworkId(long networkId); + + List listVlansByPhysicalNetworkId(long physicalNetworkId); } diff --git a/server/src/com/cloud/dc/dao/VlanDaoImpl.java b/server/src/com/cloud/dc/dao/VlanDaoImpl.java index b6fca31c79d..eecffaf4088 100644 --- a/server/src/com/cloud/dc/dao/VlanDaoImpl.java +++ b/server/src/com/cloud/dc/dao/VlanDaoImpl.java @@ -56,6 +56,7 @@ public class VlanDaoImpl extends GenericDaoBase implements VlanDao protected SearchBuilder ZoneTypePodSearch; protected SearchBuilder ZoneVlanSearch; protected SearchBuilder NetworkVlanSearch; + protected SearchBuilder PhysicalNetworkVlanSearch; protected PodVlanMapDaoImpl _podVlanMapDao = new PodVlanMapDaoImpl(); protected AccountVlanMapDao _accountVlanMapDao = new AccountVlanMapDaoImpl(); @@ -94,6 +95,10 @@ public class VlanDaoImpl extends GenericDaoBase implements VlanDao NetworkVlanSearch = createSearchBuilder(); NetworkVlanSearch.and("networkOfferingId", NetworkVlanSearch.entity().getNetworkId(), SearchCriteria.Op.EQ); NetworkVlanSearch.done(); + + PhysicalNetworkVlanSearch = createSearchBuilder(); + PhysicalNetworkVlanSearch.and("physicalNetworkId", PhysicalNetworkVlanSearch.entity().getPhysicalNetworkId(), SearchCriteria.Op.EQ); + PhysicalNetworkVlanSearch.done(); } @Override @@ -306,5 +311,11 @@ public class VlanDaoImpl extends GenericDaoBase implements VlanDao sc.setParameters("networkOfferingId", networkOfferingId); return listBy(sc); } - + + @Override + public List listVlansByPhysicalNetworkId(long physicalNetworkId) { + SearchCriteria sc = PhysicalNetworkVlanSearch.create(); + sc.setParameters("physicalNetworkId", physicalNetworkId); + return listBy(sc); + } } diff --git a/server/src/com/cloud/network/IPAddressVO.java b/server/src/com/cloud/network/IPAddressVO.java index aa50c1dd938..29c4e18318b 100644 --- a/server/src/com/cloud/network/IPAddressVO.java +++ b/server/src/com/cloud/network/IPAddressVO.java @@ -86,6 +86,9 @@ public class IPAddressVO implements IpAddress { @Column(name="network_id") private Long associatedWithNetworkId; + + @Column(name="physical_network_id") + private Long physicalNetworkId; protected IPAddressVO() { } @@ -229,5 +232,13 @@ public class IPAddressVO implements IpAddress { public void setSourceNetworkId(Long sourceNetworkId) { this.sourceNetworkId = sourceNetworkId; } + + public Long getPhysicalNetworkId() { + return physicalNetworkId; + } + + public void setPhysicalNetworkId(Long physicalNetworkId) { + this.physicalNetworkId = physicalNetworkId; + } } diff --git a/server/src/com/cloud/network/NetworkManagerImpl.java b/server/src/com/cloud/network/NetworkManagerImpl.java index 4d6d3c56363..f1ba716315e 100755 --- a/server/src/com/cloud/network/NetworkManagerImpl.java +++ b/server/src/com/cloud/network/NetworkManagerImpl.java @@ -1776,7 +1776,7 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag if (caller.getType() == Account.ACCOUNT_TYPE_ADMIN && network.getGuestType() == Network.GuestType.Shared && defineNetworkConfig) { // Create vlan ip range - _configMgr.createVlanAndPublicIpRange(userId, pNtwk.getDataCenterId(), null, startIP, endIP, gateway, netmask, false, vlanId, owner, network.getId()); + _configMgr.createVlanAndPublicIpRange(userId, pNtwk.getDataCenterId(), null, startIP, endIP, gateway, netmask, false, vlanId, owner, network.getId(), physicalNetworkId); } txn.commit(); @@ -3519,8 +3519,9 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag if (vnetRange != null) { //Verify zone type - if (zone.getNetworkType() == NetworkType.Basic && vnetRange != null) { - vnetRange = null; + if (zone.getNetworkType() == NetworkType.Basic + || (zone.getNetworkType() == NetworkType.Advanced && zone.isSecurityGroupEnabled())) { + throw new InvalidParameterValueException("Can't add vnet range to the physical network in the zone that supports " + zone.getNetworkType() + " network, Security Group enabled: "+ zone.isSecurityGroupEnabled()); } String[] tokens = vnetRange.split("-"); @@ -3599,8 +3600,21 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag // verify input parameters PhysicalNetworkVO network = _physicalNetworkDao.findById(id); if (network == null) { - throw new InvalidParameterValueException("Network id=" + id + "doesn't exist in the system"); + throw new InvalidParameterValueException("Physical Network id=" + id + "doesn't exist in the system"); } + + // if zone is of Basic type, don't allow to add vnet range + DataCenter zone = _dcDao.findById(network.getDataCenterId()); + if (zone == null) { + throw new InvalidParameterValueException("Zone with id=" + network.getDataCenterId() + " doesn't exist in the system"); + } + if(newVnetRangeString != null){ + if (zone.getNetworkType() == NetworkType.Basic + || (zone.getNetworkType() == NetworkType.Advanced && zone.isSecurityGroupEnabled())) { + throw new InvalidParameterValueException("Can't add vnet range to the physical network in the zone that supports " + zone.getNetworkType() + " network, Security Group enabled: "+ zone.isSecurityGroupEnabled()); + } + } + if (tags != null && tags.size() > 1) { throw new InvalidParameterException("Unable to support more than one tag on network yet"); @@ -3626,7 +3640,7 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag if(networkSpeed != null){ network.setSpeed(networkSpeed); } - + // Vnet range can be extended only boolean replaceVnet = false; ArrayList> vnetsToAdd = new ArrayList>(2); @@ -4224,6 +4238,9 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag } } + if(_pNTrafficTypeDao.isTrafficTypeSupported(physicalNetworkId, trafficType)){ + throw new CloudRuntimeException("This physical network already supports the traffic type: "+trafficType); + } //For Storage, Control, Management, Public check if the zone has any other physical network with this traffictype already present //If yes, we cant add these traffics to one more physical network in the zone. @@ -4307,5 +4324,22 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag } return _pNTrafficTypeDao.listBy(physicalNetworkId); + } + + @Override + public PhysicalNetwork getDefaultPhysicalNetworkByZoneAndTrafficType(long zoneId, TrafficType trafficType) { + PhysicalNetworkVO network = null; + + List networkList = _physicalNetworkDao.listByZoneAndTrafficType(zoneId, trafficType); + + if (networkList.isEmpty()) { + throw new InvalidParameterValueException("Unable to find the default physical network with traffic=" + trafficType +" in zone id=" + zoneId); + } + + if (networkList.size() > 1) { + throw new InvalidParameterValueException("More than one physical networks exist in zone id=" + zoneId + " with traffic type="+trafficType); + } + + return networkList.get(0); } } diff --git a/server/src/com/cloud/network/addr/PublicIp.java b/server/src/com/cloud/network/addr/PublicIp.java index 6cf9d32862e..0765fcbe6d9 100644 --- a/server/src/com/cloud/network/addr/PublicIp.java +++ b/server/src/com/cloud/network/addr/PublicIp.java @@ -171,4 +171,9 @@ public class PublicIp implements PublicIpAddress { public String toString() { return _addr.getAddress().toString(); } + + @Override + public Long getPhysicalNetworkId() { + return _vlan.getPhysicalNetworkId(); + } } diff --git a/server/src/com/cloud/network/dao/IPAddressDao.java b/server/src/com/cloud/network/dao/IPAddressDao.java index e1af6e04ce5..d66e971ba1e 100644 --- a/server/src/com/cloud/network/dao/IPAddressDao.java +++ b/server/src/com/cloud/network/dao/IPAddressDao.java @@ -53,5 +53,7 @@ public interface IPAddressDao extends GenericDao { IPAddressVO findByAssociatedVmId(long vmId); IPAddressVO findByIpAndSourceNetworkId(long networkId, String ipAddress); + + List listByPhysicalNetworkId(long physicalNetworkId); } diff --git a/server/src/com/cloud/network/dao/IPAddressDaoImpl.java b/server/src/com/cloud/network/dao/IPAddressDaoImpl.java index e09ef0bd19b..809939daddb 100644 --- a/server/src/com/cloud/network/dao/IPAddressDaoImpl.java +++ b/server/src/com/cloud/network/dao/IPAddressDaoImpl.java @@ -40,7 +40,6 @@ import com.cloud.utils.db.SearchCriteria.Op; import com.cloud.utils.db.Transaction; import com.cloud.utils.exception.CloudRuntimeException; import com.cloud.utils.net.Ip; -import com.cloud.vm.VirtualMachine; @Local(value = { IPAddressDao.class }) @DB @@ -70,6 +69,7 @@ public class IPAddressDaoImpl extends GenericDaoBase implemen AllFieldsSearch.and("associatedWithVmId", AllFieldsSearch.entity().getAssociatedWithVmId(), Op.EQ); AllFieldsSearch.and("oneToOneNat", AllFieldsSearch.entity().isOneToOneNat(), Op.EQ); AllFieldsSearch.and("sourcenetwork", AllFieldsSearch.entity().getSourceNetworkId(), Op.EQ); + AllFieldsSearch.and("physicalNetworkId", AllFieldsSearch.entity().getPhysicalNetworkId(), Op.EQ); AllFieldsSearch.done(); VlanDbIdSearchUnallocated = createSearchBuilder(); @@ -292,5 +292,12 @@ public class IPAddressDaoImpl extends GenericDaoBase implemen SearchCriteria sc = AllocatedIpCountForAccount.create(); sc.setParameters("account", accountId); return customSearch(sc, null).get(0); + } + + @Override + public List listByPhysicalNetworkId(long physicalNetworkId) { + SearchCriteria sc = AllFieldsSearch.create(); + sc.setParameters("physicalNetworkId", physicalNetworkId); + return listBy(sc); } } diff --git a/server/src/com/cloud/network/dao/PhysicalNetworkTrafficTypeDao.java b/server/src/com/cloud/network/dao/PhysicalNetworkTrafficTypeDao.java index 6b901b2ec34..f8b2c06c19f 100644 --- a/server/src/com/cloud/network/dao/PhysicalNetworkTrafficTypeDao.java +++ b/server/src/com/cloud/network/dao/PhysicalNetworkTrafficTypeDao.java @@ -19,10 +19,10 @@ package com.cloud.network.dao; import java.util.List; +import com.cloud.network.Networks.TrafficType; import com.cloud.utils.db.GenericDao; public interface PhysicalNetworkTrafficTypeDao extends GenericDao { List listBy(long physicalNetworkId); - - + boolean isTrafficTypeSupported(long physicalNetworkId, TrafficType trafficType); } diff --git a/server/src/com/cloud/network/dao/PhysicalNetworkTrafficTypeDaoImpl.java b/server/src/com/cloud/network/dao/PhysicalNetworkTrafficTypeDaoImpl.java index d483b9f19a2..0dcba8f8952 100644 --- a/server/src/com/cloud/network/dao/PhysicalNetworkTrafficTypeDaoImpl.java +++ b/server/src/com/cloud/network/dao/PhysicalNetworkTrafficTypeDaoImpl.java @@ -21,6 +21,7 @@ import java.util.List; import javax.ejb.Local; +import com.cloud.network.Networks.TrafficType; import com.cloud.utils.db.DB; import com.cloud.utils.db.GenericDaoBase; import com.cloud.utils.db.SearchBuilder; @@ -35,6 +36,7 @@ public class PhysicalNetworkTrafficTypeDaoImpl extends GenericDaoBase sc = physicalNetworkSearch.create(); + sc.setParameters("physicalNetworkId", physicalNetworkId); + sc.setParameters("trafficType", trafficType); + if (findOneBy(sc) != null) { + return true; + } else { + return false; + } + } } diff --git a/server/src/com/cloud/server/ConfigurationServerImpl.java b/server/src/com/cloud/server/ConfigurationServerImpl.java index d55289ec95c..ca2423be277 100644 --- a/server/src/com/cloud/server/ConfigurationServerImpl.java +++ b/server/src/com/cloud/server/ConfigurationServerImpl.java @@ -35,11 +35,9 @@ import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.HashMap; -import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Properties; -import java.util.Set; import java.util.UUID; import java.util.regex.Pattern; @@ -250,7 +248,7 @@ public class ConfigurationServerImpl implements ConfigurationServer { IPRangeConfig config = new IPRangeConfig(); long startIPLong = NetUtils.ip2Long(startIp); long endIPLong = NetUtils.ip2Long(endIp); - config.savePublicIPRange(txn, startIPLong, endIPLong, vlan.getDataCenterId(), vlan.getId(), vlan.getNetworkId()); + config.savePublicIPRange(txn, startIPLong, endIPLong, vlan.getDataCenterId(), vlan.getId(), vlan.getNetworkId(), vlan.getPhysicalNetworkId()); txn.commit(); } } diff --git a/server/src/com/cloud/test/DatabaseConfig.java b/server/src/com/cloud/test/DatabaseConfig.java index a0ec7c97698..6dae94a7a9c 100755 --- a/server/src/com/cloud/test/DatabaseConfig.java +++ b/server/src/com/cloud/test/DatabaseConfig.java @@ -155,7 +155,7 @@ public class DatabaseConfig { fieldNames.add("tags"); fieldNames.add("networktype"); fieldNames.add("clusterId"); - + fieldNames.add("physicalNetworkId"); s_configurationDescriptions.put("host.stats.interval", "the interval in milliseconds when host stats are retrieved from agents"); s_configurationDescriptions.put("storage.stats.interval", "the interval in milliseconds when storage stats (per host) are retrieved from agents"); @@ -665,6 +665,7 @@ public class DatabaseConfig { private void saveVlan() { String zoneId = _currentObjectParams.get("zoneId"); + String physicalNetworkIdStr = _currentObjectParams.get("physicalNetworkId"); String vlanId = _currentObjectParams.get("vlanId"); String gateway = _currentObjectParams.get("gateway"); String netmask = _currentObjectParams.get("netmask"); @@ -672,6 +673,7 @@ public class DatabaseConfig { String vlanType = _currentObjectParams.get("vlanType"); String vlanPodName = _currentObjectParams.get("podName"); + String ipError = "Please enter a valid IP address for the field: "; if (!IPRangeConfig.validOrBlankIP(gateway)) { printError(ipError + "gateway"); @@ -716,11 +718,13 @@ public class DatabaseConfig { long zoneDbId = Long.parseLong(zoneId); String zoneName = PodZoneConfig.getZoneName(zoneDbId); + long physicalNetworkId = Long.parseLong(physicalNetworkIdStr); + //Set networkId to be 0, the value will be updated after management server starts up - pzc.modifyVlan(zoneName, true, vlanId, gateway, netmask, vlanPodName, vlanType, publicIpRange, 0); + pzc.modifyVlan(zoneName, true, vlanId, gateway, netmask, vlanPodName, vlanType, publicIpRange, 0, physicalNetworkId); long vlanDbId = pzc.getVlanDbId(zoneName, vlanId); - iprc.saveIPRange("public", -1, zoneDbId, vlanDbId, startIP, endIP, null); + iprc.saveIPRange("public", -1, zoneDbId, vlanDbId, startIP, endIP, null, physicalNetworkId); } @@ -786,7 +790,7 @@ public class DatabaseConfig { if (privateIpRange != null) { // Save the IP address range - iprc.saveIPRange("private", id, dataCenterId, -1, startIP, endIP, null); + iprc.saveIPRange("private", id, dataCenterId, -1, startIP, endIP, null, -1); } } diff --git a/server/src/com/cloud/test/IPRangeConfig.java b/server/src/com/cloud/test/IPRangeConfig.java index dd10d9ac525..075d8ae919e 100644 --- a/server/src/com/cloud/test/IPRangeConfig.java +++ b/server/src/com/cloud/test/IPRangeConfig.java @@ -72,7 +72,7 @@ public class IPRangeConfig { } long zoneId = PodZoneConfig.getZoneId(zone); - result = changeRange(op, "public", -1, zoneId, startIP, endIP, null); + result = changeRange(op, "public", -1, zoneId, startIP, endIP, null, -1); result.replaceAll("
", "/n"); System.out.println(result); } else if (type.equals("private")) { @@ -94,7 +94,7 @@ public class IPRangeConfig { long podId = PodZoneConfig.getPodId(pod, zone); long zoneId = PodZoneConfig.getZoneId(zone); - result = changeRange(op, "private", podId, zoneId, startIP, endIP, null); + result = changeRange(op, "private", podId, zoneId, startIP, endIP, null, -1); result.replaceAll("
", "/n"); System.out.println(result); } else { @@ -102,14 +102,14 @@ public class IPRangeConfig { } } - public List changePublicIPRangeGUI(String op, String zone, String startIP, String endIP) { + public List changePublicIPRangeGUI(String op, String zone, String startIP, String endIP, long physicalNetworkId) { String result = checkErrors("public", op, null, zone, startIP, endIP); if (!result.equals("success")) { return DatabaseConfig.genReturnList("false", result); } long zoneId = PodZoneConfig.getZoneId(zone); - result = changeRange(op, "public", -1, zoneId, startIP, endIP, null); + result = changeRange(op, "public", -1, zoneId, startIP, endIP, null, physicalNetworkId); return DatabaseConfig.genReturnList("true", result); } @@ -122,7 +122,7 @@ public class IPRangeConfig { long podId = PodZoneConfig.getPodId(pod, zone); long zoneId = PodZoneConfig.getZoneId(zone); - result = changeRange(op, "private", podId, zoneId, startIP, endIP, null); + result = changeRange(op, "private", podId, zoneId, startIP, endIP, null, -1); return DatabaseConfig.genReturnList("true", result); } @@ -226,12 +226,12 @@ public class IPRangeConfig { } } - private String changeRange(String op, String type, long podId, long zoneId, String startIP, String endIP, Long networkId) { + private String changeRange(String op, String type, long podId, long zoneId, String startIP, String endIP, Long networkId, long physicalNetworkId) { // Go through all the IPs and add or delete them List problemIPs = null; if (op.equals("add")) { - problemIPs = saveIPRange(type, podId, zoneId, 1, startIP, endIP, networkId); + problemIPs = saveIPRange(type, podId, zoneId, 1, startIP, endIP, networkId, physicalNetworkId); } else if (op.equals("delete")) { problemIPs = deleteIPRange(type, podId, zoneId, 1, startIP, endIP); } @@ -424,7 +424,7 @@ public class IPRangeConfig { } @DB - public List saveIPRange(String type, long podId, long zoneId, long vlanDbId, String startIP, String endIP, Long sourceNetworkId) { + public List saveIPRange(String type, long podId, long zoneId, long vlanDbId, String startIP, String endIP, Long sourceNetworkId, long physicalNetworkId) { long startIPLong = NetUtils.ip2Long(startIP); long endIPLong = startIPLong; if (endIP != null) { @@ -435,7 +435,7 @@ public class IPRangeConfig { List problemIPs = null; if (type.equals("public")) { - problemIPs = savePublicIPRange(txn, startIPLong, endIPLong, zoneId, vlanDbId, sourceNetworkId); + problemIPs = savePublicIPRange(txn, startIPLong, endIPLong, zoneId, vlanDbId, sourceNetworkId, physicalNetworkId); } else if (type.equals("private")) { problemIPs = savePrivateIPRange(txn, startIPLong, endIPLong, podId, zoneId); } @@ -449,8 +449,8 @@ public class IPRangeConfig { return problemIPs; } - public Vector savePublicIPRange(Transaction txn, long startIP, long endIP, long zoneId, long vlanDbId, Long sourceNetworkId) { - String insertSql = "INSERT INTO `cloud`.`user_ip_address` (public_ip_address, data_center_id, vlan_db_id, mac_address, source_network_id) VALUES (?, ?, ?, (select mac_address from `cloud`.`data_center` where id=?), ?)"; + public Vector savePublicIPRange(Transaction txn, long startIP, long endIP, long zoneId, long vlanDbId, Long sourceNetworkId, long physicalNetworkId) { + String insertSql = "INSERT INTO `cloud`.`user_ip_address` (public_ip_address, data_center_id, vlan_db_id, mac_address, source_network_id, physical_network_id) VALUES (?, ?, ?, (select mac_address from `cloud`.`data_center` where id=?), ?, ?)"; String updateSql = "UPDATE `cloud`.`data_center` set mac_address = mac_address+1 where id=?"; Vector problemIPs = new Vector(); PreparedStatement stmt = null; @@ -470,6 +470,7 @@ public class IPRangeConfig { stmt.setLong(3, vlanDbId); stmt.setLong(4, zoneId); stmt.setLong(5, sourceNetworkId); + stmt.setLong(6, physicalNetworkId); stmt.executeUpdate(); stmt.close(); stmt = conn.prepareStatement(updateSql); diff --git a/server/src/com/cloud/test/PodZoneConfig.java b/server/src/com/cloud/test/PodZoneConfig.java index 3262cdd8deb..a55027d0583 100644 --- a/server/src/com/cloud/test/PodZoneConfig.java +++ b/server/src/com/cloud/test/PodZoneConfig.java @@ -183,12 +183,18 @@ public class PodZoneConfig { "Unable to start DB connection to read vlan DB id. Please contact Cloud Support."); } - public List modifyVlan(String zone, boolean add, String vlanId, String vlanGateway, String vlanNetmask, String pod, String vlanType, String ipRange, long networkId) { + public List modifyVlan(String zone, boolean add, String vlanId, String vlanGateway, String vlanNetmask, String pod, String vlanType, String ipRange, long networkId, long physicalNetworkId) { // Check if the zone is valid long zoneId = getZoneId(zone); if (zoneId == -1) return genReturnList("false", "Please specify a valid zone."); + //check if physical network is valid + long physicalNetworkDbId = checkPhysicalNetwork(physicalNetworkId); + if (physicalNetworkId == -1) + return genReturnList("false", "Please specify a valid physical network."); + + Long podId = pod!=null?getPodId(pod, zone):null; if (podId != null && podId == -1) return genReturnList("false", "Please specify a valid pod."); @@ -219,7 +225,7 @@ public class PodZoneConfig { */ // Everything was fine, so persist the VLAN - saveVlan(zoneId, podId, vlanId, vlanGateway, vlanNetmask, vlanType, ipRange, networkId); + saveVlan(zoneId, podId, vlanId, vlanGateway, vlanNetmask, vlanType, ipRange, networkId, physicalNetworkDbId); if (podId != null) { long vlanDbId = getVlanDbId(zone, vlanId); String sql = "INSERT INTO `cloud`.`pod_vlan_map` (pod_id, vlan_db_id) " + "VALUES ('" + podId + "','" + vlanDbId + "')"; @@ -370,8 +376,8 @@ public class PodZoneConfig { DatabaseConfig.saveSQL(sql, "Failed to delete zone due to exception. Please contact Cloud Support."); } - public void saveVlan(long zoneId, Long podId, String vlanId, String vlanGateway, String vlanNetmask, String vlanType, String ipRange, long networkId) { - String sql = "INSERT INTO `cloud`.`vlan` (vlan_id, vlan_gateway, vlan_netmask, data_center_id, vlan_type, description, network_id) " + "VALUES ('" + vlanId + "','" + vlanGateway + "','" + vlanNetmask + "','" + zoneId + "','" + vlanType + "','" + ipRange + "','" + networkId + "')"; + public void saveVlan(long zoneId, Long podId, String vlanId, String vlanGateway, String vlanNetmask, String vlanType, String ipRange, long networkId, long physicalNetworkId) { + String sql = "INSERT INTO `cloud`.`vlan` (vlan_id, vlan_gateway, vlan_netmask, data_center_id, vlan_type, description, network_id, physical_network_id) " + "VALUES ('" + vlanId + "','" + vlanGateway + "','" + vlanNetmask + "','" + zoneId + "','" + vlanType + "','" + ipRange + "','" + networkId + "','" + physicalNetworkId + "')"; DatabaseConfig.saveSQL(sql, "Failed to save vlan due to exception. Please contact Cloud Support."); } @@ -394,6 +400,12 @@ public class PodZoneConfig { return DatabaseConfig.getDatabaseValueLong(selectSql, "id", errorMsg); } + public static long checkPhysicalNetwork(long physicalNetworkId) { + String selectSql = "SELECT * FROM `cloud`.`physical_network` WHERE id = \"" + physicalNetworkId + "\""; + String errorMsg = "Could not read physicalNetwork ID from database. Please contact Cloud Support."; + return DatabaseConfig.getDatabaseValueLong(selectSql, "id", errorMsg); + } + @DB public Vector getAllZoneIDs() { Vector allZoneIDs = new Vector(); diff --git a/setup/db/create-schema.sql b/setup/db/create-schema.sql index 287c74fe0e2..247ed3b4e67 100755 --- a/setup/db/create-schema.sql +++ b/setup/db/create-schema.sql @@ -446,9 +446,11 @@ CREATE TABLE `cloud`.`vlan` ( `vlan_type` varchar(255), `data_center_id` bigint unsigned NOT NULL, `network_id` bigint unsigned NOT NULL COMMENT 'id of corresponding network offering', + `physical_network_id` bigint unsigned NOT NULL COMMENT 'physical network id that this configuration is based on', PRIMARY KEY (`id`), #CONSTRAINT `fk_vlan__network_id` FOREIGN KEY (`network_id`) REFERENCES `networks`(`id`), - CONSTRAINT `fk_vlan__data_center_id` FOREIGN KEY (`data_center_id`) REFERENCES `data_center`(`id`) + CONSTRAINT `fk_vlan__data_center_id` FOREIGN KEY (`data_center_id`) REFERENCES `data_center`(`id`), + CONSTRAINT `fk_vlan__physical_network_id` FOREIGN KEY (`physical_network_id`) REFERENCES `physical_network`(`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8; CREATE TABLE `cloud`.`pod_vlan_map` ( @@ -799,6 +801,7 @@ CREATE TABLE `cloud`.`user_ip_address` ( `mac_address` bigint unsigned NOT NULL COMMENT 'mac address of this ip', `source_network_id` bigint unsigned NOT NULL COMMENT 'network id ip belongs to', `network_id` bigint unsigned COMMENT 'network this public ip address is associated with', + `physical_network_id` bigint unsigned NOT NULL COMMENT 'physical network id that this configuration is based on', PRIMARY KEY (`id`), UNIQUE (`public_ip_address`, `source_network_id`), CONSTRAINT `fk_user_ip_address__source_network_id` FOREIGN KEY (`source_network_id`) REFERENCES `networks`(`id`), @@ -807,6 +810,7 @@ CREATE TABLE `cloud`.`user_ip_address` ( CONSTRAINT `fk_user_ip_address__vm_id` FOREIGN KEY (`vm_id`) REFERENCES `vm_instance`(`id`), CONSTRAINT `fk_user_ip_address__vlan_db_id` FOREIGN KEY (`vlan_db_id`) REFERENCES `vlan`(`id`) ON DELETE CASCADE, CONSTRAINT `fk_user_ip_address__data_center_id` FOREIGN KEY (`data_center_id`) REFERENCES `data_center`(`id`) ON DELETE CASCADE, + CONSTRAINT `fk_user_ip_address__physical_network_id` FOREIGN KEY (`physical_network_id`) REFERENCES `physical_network`(`id`) ON DELETE CASCADE, INDEX `i_user_ip_address__allocated`(`allocated`), INDEX `i_user_ip_address__source_nat`(`source_nat`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8; diff --git a/setup/db/server-setup.xml b/setup/db/server-setup.xml index b917c519666..7c5fe160b3e 100755 --- a/setup/db/server-setup.xml +++ b/setup/db/server-setup.xml @@ -75,6 +75,7 @@ -
-
- VLAN Range -
-
- - - - -
-
-
diff --git a/ui/index.jsp b/ui/index.jsp index 2b4e6b30b57..71609e20a52 100644 --- a/ui/index.jsp +++ b/ui/index.jsp @@ -477,18 +477,6 @@
- -
-
- VLAN Range -
-
- - - - -
-
-
From 7eb51d65d09432f5f82b4e6d2889f82cb28c1f52 Mon Sep 17 00:00:00 2001 From: Brian Federle Date: Fri, 11 Nov 2011 10:28:58 -0800 Subject: [PATCH 152/159] Add base install wizard scripts --- ui/index-test.html | 2 ++ ui/index.jsp | 2 ++ ui/scripts-test/installWizard.js | 12 ++++++++ ui/scripts/ui-custom/installWizard.js | 43 +++++++++++++++++++++++++++ 4 files changed, 59 insertions(+) create mode 100644 ui/scripts-test/installWizard.js create mode 100644 ui/scripts/ui-custom/installWizard.js diff --git a/ui/index-test.html b/ui/index-test.html index 15778a16d02..1d949ddb096 100644 --- a/ui/index-test.html +++ b/ui/index-test.html @@ -1391,6 +1391,8 @@ + + diff --git a/ui/index.jsp b/ui/index.jsp index 71609e20a52..3faefea0c6f 100644 --- a/ui/index.jsp +++ b/ui/index.jsp @@ -1399,6 +1399,8 @@ + + diff --git a/ui/scripts-test/installWizard.js b/ui/scripts-test/installWizard.js new file mode 100644 index 00000000000..6612c2ca2fd --- /dev/null +++ b/ui/scripts-test/installWizard.js @@ -0,0 +1,12 @@ +(function($, cloudStack, testData) { + cloudStack.installWizard = { + // Check if install wizard should be invoked + check: function(args) { + setTimeout(function() { + args.response.success({ + doInstall: false + }); + }, 100); + } + }; +}(jQuery, cloudStack, testData)); \ No newline at end of file diff --git a/ui/scripts/ui-custom/installWizard.js b/ui/scripts/ui-custom/installWizard.js new file mode 100644 index 00000000000..51acf183a07 --- /dev/null +++ b/ui/scripts/ui-custom/installWizard.js @@ -0,0 +1,43 @@ +(function($, cloudStack, testData) { + cloudStack.uiCustom.installWizard = function(args) { + var context = args.context; + var $installWizard = $('
').addClass('install-wizard'); + var $container = args.$container; + + var elems = { + nextButton: function() { + return $('
').addClass('button next').html('Next'); + } + }; + + // Layout/behavior for each step in wizard + var steps = { + // Welcome screen + welcome: function(args) { + return $.merge( + $('

').html('Welcome screen'), + $('

').html('Welcome text goes here.'), + $('

').addClass('button next').html('Next'), + elems.nextButton().click(args.nextStep) + ); + }, + + addZone: function(args) { + var $zoneWizard = $('#template').find('.multi-wizard.zone-wizard').clone(); + + return $.merge( + $zoneWizard.find('.steps .setup-zone'), + elems.nextButton().click(function() { + args.nextStep({ + data: { + zone: cloudStack.serializeForm + } + }); + }) + ); + } + }; + + $installWizard.append(steps.addZone).appendTo($container); + }; +}(jQuery, cloudStack, testData)); \ No newline at end of file From 8e12c9aa2170e8da4f22c38faef4fdc9cb90a71f Mon Sep 17 00:00:00 2001 From: Brian Federle Date: Fri, 11 Nov 2011 10:29:27 -0800 Subject: [PATCH 153/159] Update dialog appearance; add UI support for zone network providers --- ui/css/cloudstack3.css | 208 ++++++++++++++++++++++--- ui/scripts-test/cloudStack.js | 32 +++- ui/scripts-test/system.js | 35 ++--- ui/scripts/ui-custom/zoneChart.js | 51 +++--- ui/scripts/ui/dialog.js | 26 +++- ui/scripts/ui/multiEdit.js | 4 +- ui/scripts/ui/widgets/notifications.js | 3 + 7 files changed, 288 insertions(+), 71 deletions(-) diff --git a/ui/css/cloudstack3.css b/ui/css/cloudstack3.css index 3c46428f1ce..b96dbd97388 100644 --- a/ui/css/cloudstack3.css +++ b/ui/css/cloudstack3.css @@ -2047,12 +2047,14 @@ Dialogs*/ } .ui-dialog .ui-widget-content { - padding: 10px; + padding: 8px; text-align: center; + display: inline-block; } .ui-dialog-buttonset { width: 285px; + margin: 0; } .ui-dialog .ui-button { @@ -2069,10 +2071,6 @@ Dialogs*/ -webkit-border-radius: 5px; -khtml-border-radius: 5px; border-radius: 5px 5px 5px 5px; - /*+placement:shift 0px -35px;*/ - position: relative; - left: 0px; - top: -35px; } .ui-dialog .ui-button:hover { @@ -2126,8 +2124,8 @@ Dialogs*/ .ui-dialog span.message { display: block; text-align: center; - margin: 0 0 30px; color: #445361; + font-size: 15px; /*+text-shadow:0px 1px 1px #FFFFFF;*/ -moz-text-shadow: 0px 1px 1px #FFFFFF; -webkit-text-shadow: 0px 1px 1px #FFFFFF; @@ -2184,10 +2182,8 @@ Dialogs*/ .ui-dialog div.form-container { height: 106px; width: 100%; - overflow: hidden; - display: block; - padding-bottom: 37px; text-align: left; + display: inline-block; } .ui-dialog div.form-container span.message { @@ -2198,7 +2194,7 @@ Dialogs*/ .ui-dialog div.form-container div.form-item { display: inline-block; - height: 38px; + margin: 0 0 12px; } .ui-dialog div.form-container div.name { @@ -2217,9 +2213,9 @@ Dialogs*/ .ui-dialog div.form-container div.name label { display: block; - width: 100%; + width: 119px; text-align: right; - font-size: 14px; + font-size: 13px; margin-top: 2px; } @@ -2228,6 +2224,7 @@ Dialogs*/ overflow: hidden; float: right; margin: 0 0 0 15px; + display: inline-block; } .ui-dialog div.form-container div.value input { @@ -2239,6 +2236,12 @@ Dialogs*/ -webkit-border-radius: 4px; -khtml-border-radius: 4px; border-radius: 4px 4px 4px 4px; + border: 1px solid #AFAFAF; + /*+box-shadow:inset 0px 1px 0px #727272;*/ + -moz-box-shadow: inset 0px 1px 0px #727272; + -webkit-box-shadow: inset 0px 1px 0px #727272; + -o-box-shadow: inset 0px 1px 0px #727272; + box-shadow: inset 0px 1px 0px #727272; float: left; } @@ -2259,6 +2262,46 @@ Dialogs*/ display: none; } +.ui-dialog div.form-container div.multi-array { + display: inline-block; + background: #FFFFFF; + padding: 4px; + /*+border-radius:10px;*/ + -moz-border-radius: 10px; + -webkit-border-radius: 10px; + -khtml-border-radius: 10px; + border-radius: 10px 10px 10px 10px; + border: 1px solid #808080; + /*+box-shadow:inset 0px 1px 1px #929292;*/ + -moz-box-shadow: inset 0px 1px 1px #929292; + -webkit-box-shadow: inset 0px 1px 1px #929292; + -o-box-shadow: inset 0px 1px 1px #929292; + box-shadow: inset 0px 1px 1px #929292; +} + +.ui-dialog div.form-container div.multi-array .item { + width: 111px; + float: left; + margin: 0 0 13px; +} + +.ui-dialog div.form-container div.multi-array .item .name { + font-size: 11px; + width: 61px; + float: left; +} + +.ui-dialog div.form-container div.multi-array .item .value { + width: 13px; + float: left; +} + +.ui-dialog div.form-container div.multi-array .item .value input { + float: left; + margin: 0; + padding: 0; +} + .ui-dialog.create-form .ui-button.ok { margin-left: 0; float: right; @@ -3013,8 +3056,12 @@ Dialogs*/ background-position: 0px -767px; } -.zone-chart ul li.disabled .view-all.normal { - display: none; +.zone-chart ul li .view-all.configure { + /*+placement:anchor-bottom-right -1px 11px;*/ + position: absolute; + right: -1px; + bottom: 11px; + text-indent: -2px; } .zone-chart ul li .view-details { @@ -3069,10 +3116,10 @@ Dialogs*/ } .zone-chart .resources.naas ul.system-main li.main .view-all { - /*+placement:shift 43px 30px;*/ + /*+placement:shift 65px 29px;*/ position: relative; - left: 43px; - top: 30px; + left: 65px; + top: 29px; position: absolute; text-align: left; text-indent: -2px; @@ -3182,6 +3229,114 @@ Dialogs*/ margin-left: 92px; } +/*** Add initial resource form*/ +.panel .add-first-network-resource { + padding: 37px; + font-size: 14px; +} + +.panel .add-first-network-resource .title { + font-size: 26px; + color: #3984D1; + /*+text-shadow:0px 1px 2px #BCBCBC;*/ + -moz-text-shadow: 0px 1px 2px #BCBCBC; + -webkit-text-shadow: 0px 1px 2px #BCBCBC; + -o-text-shadow: 0px 1px 2px #BCBCBC; + text-shadow: 0px 1px 2px #BCBCBC; + margin: 0 0 17px; +} + +.panel .add-first-network-resource .message { + display: block; + color: #545151; + margin: 0 0 30px; +} + +.panel .add-first-network-resource .form-item { + width: 409px; + height: 39px; + padding: 5px; + position: relative; +} + +.panel .add-first-network-resource .form-item label { + float: left; +} + +.panel .add-first-network-resource .form-item label.error { + display: none; + font-size: 10px; + position: absolute; + top: 30px; + left: 137px; +} + +.panel .add-first-network-resource .form-item input { + float: right; + /*+border-radius:6px;*/ + -moz-border-radius: 6px; + -webkit-border-radius: 6px; + -khtml-border-radius: 6px; + border-radius: 6px 6px 6px 6px; + font-size: 16px; + border: 1px solid #B7B7B7; +} + +.panel .add-first-network-resource .form-item input[type=text] { + width: 276px; +} + +.panel .add-first-network-resource .button { + padding: 11px 23px 11px 21px; + cursor: pointer; + background: url(../images/bg-gradients.png) repeat-x 0px -221px; + margin: 29px 0 0; + /*+border-radius:10px;*/ + -moz-border-radius: 10px; + -webkit-border-radius: 10px; + -khtml-border-radius: 10px; + border-radius: 10px 10px 10px 10px; + border: 1px solid #858585; + color: #FFFFFF; + clear: both; + /*[empty]font-size:;*/ +} + +.panel .add-first-network-resource .multi-array { + background: #FFFFFF; + border: 1px solid #DCDCDC; + display: inline-block; + float: left; + padding: 12px; + clear: both; + width: 383px; + margin: 3px 0 0; + /*+border-radius:7px;*/ + -moz-border-radius: 7px; + -webkit-border-radius: 7px; + -khtml-border-radius: 7px; + border-radius: 7px 7px 7px 7px; +} + +.panel .add-first-network-resource .multi-array .item { + max-width: 155px; + float: left; + margin: 6px 0 0 24px; +} + +.panel .add-first-network-resource .multi-array .item .name { + float: left; +} + +.panel .add-first-network-resource .multi-array .item .value { + float: right; + margin: 0 0 0 13px; +} + +.panel .add-first-network-resource .multi-array .item .value input { + margin: 0; +} + /*Form validation*/ input.error { background: #FEE5E5; @@ -3456,7 +3611,7 @@ label.error { border: 1px solid #E2DDDD; clear: both; height: 72% !important; - width: 94%; + width: 95%; margin: auto; overflow: auto; height: 591px; @@ -3468,6 +3623,10 @@ label.error { background: #FFFFFF; } +.multi-wizard .content.tab-view div.ui-tabs-panel.ui-tabs-hide { + display: none; +} + .multi-wizard.instance-wizard .select-iso .content .select .hypervisor { float: left; display: block; @@ -4274,7 +4433,7 @@ div.detail-group td.view-all div.view-all div.end { div.panel.ui-dialog div.list-view div.fixed-header { top: 33px; - left: 22px; + left: 20px; width: 759px; height: 49px; background-color: #EAECEF; @@ -4658,6 +4817,9 @@ div.panel.ui-dialog div.list-view div.fixed-header { top: 2px; } +.recurring-snapshots .schedule .forms > div { +} + .recurring-snapshots .schedule .forms form { font-size: 12px; color: #4F6171; @@ -4907,6 +5069,10 @@ div.panel.ui-dialog div.list-view div.fixed-header { top: 0px; } +.recurring-snapshots .ui-tabs div.ui-tabs-panel.ui-tabs-hide { + display: none; +} + /*Network detail chat*/ .network-chart { width: 100%; @@ -5713,6 +5879,10 @@ div.panel.ui-dialog div.list-view div.fixed-header { height: 185px; } +.new-project .review .ui-tabs .ui-widget-content.ui-tabs-hide { + display: none; +} + .new-project .review .ui-tabs li { } diff --git a/ui/scripts-test/cloudStack.js b/ui/scripts-test/cloudStack.js index 7567393800c..83317536e8b 100644 --- a/ui/scripts-test/cloudStack.js +++ b/ui/scripts-test/cloudStack.js @@ -28,11 +28,11 @@ $(function() { var $container = $('#cloudStack3-container'); - + // Login cloudStack.uiCustom.login({ $container: $container, - + // Use this for checking the session, to bypass login screen bypassLoginCheck: function(args) { var disabledLogin = document.location.href.split('?')[1] == 'login=disabled'; @@ -66,13 +66,31 @@ return args.response.error(); }, - // Show cloudStack main UI widget complete: function(args) { - $container.cloudStack($.extend(cloudStack, { - context: { - users: [args.user] + var context = { + users: [args.user] + }; + var cloudStackArgs = $.extend(cloudStack, { + context: context + }); + + // Check to invoke install wizard + cloudStack.installWizard.check({ + context: context, + response: { + success: function(args) { + if (args.doInstall) { + cloudStack.uiCustom.installWizard({ + $container: $container, + context: context + }); + } else { + // Show cloudStack main UI + $container.cloudStack(cloudStackArgs); + } + } } - })); + }); } }); }); diff --git a/ui/scripts-test/system.js b/ui/scripts-test/system.js index 55109430396..887eb43c32d 100644 --- a/ui/scripts-test/system.js +++ b/ui/scripts-test/system.js @@ -46,22 +46,21 @@ } ], dataProvider: function(args) { - args.response.success({ _custom: { - physicalNetwork: { - ip: '192.168.1.1' - } - }, data: testData.data.networks[0] }); + args.response.success({ + data: testData.data.networks[0] + }); } }, ipAddresses: { title: 'IP Addresses', custom: function(args) { return $('
').multiEdit({ + context: args.context, noSelect: true, fields: { 'gateway': { edit: true, label: 'Gateway' }, 'netmask': { edit: true, label: 'Netmask' }, - 'vlanid': { edit: true, label: 'VLAN' }, + 'vlanid': { edit: true, label: 'VLAN', isOptional: true }, 'startip': { edit: true, label: 'Start IP' }, 'endip': { edit: true, label: 'End IP' }, 'add-rule': { label: 'Add', addButton: true } @@ -97,7 +96,13 @@ dataProvider: function(args) { setTimeout(function() { args.response.success({ - data: [] + data: [ + { + gateway: '10.223.110.223', + netmask: '255.255.255.0', + vlanid: '1480' + } + ] }); }, 100); } @@ -286,7 +291,7 @@ return { virtualRouter: 'enabled', netscaler: 'disabled', - f5: 'shutdown', + f5: 'enabled', srx: 'enabled', securityGroups: 'enabled' }; @@ -332,7 +337,7 @@ state: 'Enabled' } ] - }); + }); }, 500); } }, @@ -392,19 +397,9 @@ name: 'Router0001S', ipaddress: '192.168.1.1', state: 'Enabled' - }, - { - name: 'Router0001B', - ipaddress: '192.168.1.155', - state: 'Enabled' - }, - { - name: 'Router0002', - ipaddress: '192.168.1.13', - state: 'Enabled' } ] - }); + }); }, 500); } }, diff --git a/ui/scripts/ui-custom/zoneChart.js b/ui/scripts/ui-custom/zoneChart.js index b2d51530708..1c445d77134 100644 --- a/ui/scripts/ui-custom/zoneChart.js +++ b/ui/scripts/ui-custom/zoneChart.js @@ -262,11 +262,12 @@ var itemID = $li.attr('rel'); var status = $li.attr('network-status'); var networkProviderArgs = naas.networkProviders.types[itemID]; - var createForm = networkProviderArgs.actions.add.createForm; - var action = networkProviderArgs.actions.add; + var action = networkProviderArgs.actions ? networkProviderArgs.actions.add : null; + var createForm = action ? networkProviderArgs.actions.add.createForm : null; + var itemName = networkProviderArgs.label; $browser.cloudBrowser('addPanel', { - title: itemID + ' details', + title: itemName + ' details', maximizeIfSelected: true, complete: function($newPanel) { if (status == 'disabled') { @@ -278,13 +279,17 @@ action.action($.extend(args, { response: { success: function(args) { + $newPanel.find('form').prepend($('
').addClass('loading-overlay')); $('div.notifications').notifications('add', { desc: action.messages.notification({}), interval: 1000, - poll: action.notification.poll - }); - $newPanel.html('').listView({ - listView: naas.networkProviders.types[itemID] + poll: action.notification.poll, + complete: function(args) { + refreshChart(); + $newPanel.html('').listView({ + listView: naas.networkProviders.types[itemID] + }); + } }); } } @@ -293,22 +298,25 @@ noDialog: true }); - var $formContainer = formData.$formContainer; + var $formContainer = formData.$formContainer.addClass('add-first-network-resource'); var $form = $formContainer.find('form'); var completeAction = formData.completeAction; $newPanel.append( - $.merge( - $formContainer, - $('
') - .addClass('button submit') - .append($('').html('Add')) - .click(function() { - if ($form.valid()) { - completeAction($formContainer); - } - }) - ) + $formContainer + .prepend( + $('
').addClass('title').html('Add new ' + itemName + ' device') + ) + .append( + $('
') + .addClass('button submit') + .append($('').html('Add')) + .click(function() { + if ($form.valid()) { + completeAction($formContainer); + } + }) + ) ); } else { $newPanel.listView({ @@ -327,10 +335,13 @@ } }); - $refresh.click(function() { + var refreshChart = function() { $charts.children().remove(); loadNetworkData(); + }; + $refresh.click(function() { + refreshChart(); return false; }); }; diff --git a/ui/scripts/ui/dialog.js b/ui/scripts/ui/dialog.js index 393ec0c5456..c2b1f99e521 100644 --- a/ui/scripts/ui/dialog.js +++ b/ui/scripts/ui/dialog.js @@ -142,9 +142,29 @@ selectFn(selectArgs); } } else if (this.isBoolean) { - $input = $('').attr({ name: key, type: 'checkbox' }).appendTo($value); - if (this.isChecked) { - $input.attr('checked', 'checked'); + if (this.multiArray) { + $input = $('
') + .addClass('multi-array').addClass(key).appendTo($value); + + $.each(this.multiArray, function(itemKey, itemValue) { + $input.append( + $('
').addClass('item') + .append( + $.merge( + $('
').addClass('name').html(itemValue.label), + $('
').addClass('value').append( + $('').attr({ name: itemKey, type: 'checkbox' }).appendTo($value) + ) + ) + ) + ); + }); + + } else { + $input = $('').attr({ name: key, type: 'checkbox' }).appendTo($value); + if (this.isChecked) { + $input.attr('checked', 'checked'); + } } } else { $input = $('').attr({ diff --git a/ui/scripts/ui/multiEdit.js b/ui/scripts/ui/multiEdit.js index ff3e2d1ab9d..5af4e9cd8e7 100644 --- a/ui/scripts/ui/multiEdit.js +++ b/ui/scripts/ui/multiEdit.js @@ -381,7 +381,7 @@ name: this, type: 'text' }) - .addClass(!field.isOptional ? 'required': null) + .addClass(!field.isOptional ? 'required' : null) .attr('disabled', field.isDisabled ? 'disabled' : false) .appendTo( $('
').addClass('range-item').appendTo($range) @@ -393,7 +393,7 @@ name: fieldName, type: field.isPassword ? 'password' : 'text' }) - .addClass(!field.isOptional ? 'required': null) + .addClass(!field.isOptional ? 'required' : null) .attr('disabled', field.isDisabled ? 'disabled' : false) .appendTo($td); } diff --git a/ui/scripts/ui/widgets/notifications.js b/ui/scripts/ui/widgets/notifications.js index fa35581c6fc..e8d709b07ca 100644 --- a/ui/scripts/ui/widgets/notifications.js +++ b/ui/scripts/ui/widgets/notifications.js @@ -58,6 +58,7 @@ .append( $('
').addClass('remove') ); + var additionalComplete = args.complete; // Get information for specified section path $item.data('notification-section', args.section); @@ -77,6 +78,8 @@ notifications.cornerAlert({ message: $item.html() }); notifications.activeTasks.pop(pollTimer); $item.removeClass('pending'); + + if (additionalComplete) additionalComplete(); }, incomplete: function(args) {}, error: function(args) { From 08160fa8823c725ff791c8b5be625b53edb99e04 Mon Sep 17 00:00:00 2001 From: Alena Prokharchyk Date: Fri, 11 Nov 2011 11:02:33 -0800 Subject: [PATCH 154/159] Fixed responsename for VirtualRouter element --- server/src/com/cloud/api/ApiResponseHelper.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/server/src/com/cloud/api/ApiResponseHelper.java b/server/src/com/cloud/api/ApiResponseHelper.java index b186a88f9cf..b94942a7cc4 100755 --- a/server/src/com/cloud/api/ApiResponseHelper.java +++ b/server/src/com/cloud/api/ApiResponseHelper.java @@ -2868,7 +2868,7 @@ public class ApiResponseHelper implements ResponseGenerator { response.setNspId(result.getNspId()); response.setEnabled(result.isEnabled()); - response.setObjectName("VirtualRouterElement"); + response.setObjectName("virtualrouterelement"); return response; } } From c93730ddafedd85d658eaab294d972e65f135a9a Mon Sep 17 00:00:00 2001 From: Jessica Wang Date: Fri, 11 Nov 2011 11:09:31 -0800 Subject: [PATCH 155/159] cloudStack 3.0 new UI - network offering page - remove "Unavailable" from the drop down choice for Availability. --- ui/scripts/configuration.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/ui/scripts/configuration.js b/ui/scripts/configuration.js index 1bb285bb3e0..48d91ef6020 100644 --- a/ui/scripts/configuration.js +++ b/ui/scripts/configuration.js @@ -894,7 +894,7 @@ var items = []; items.push({id: 'Required', description: 'Required'}); items.push({id: 'Optional', description: 'Optional'}); - items.push({id: 'Unavailable', description: 'Unavailable'}); + //items.push({id: 'Unavailable', description: 'Unavailable'}); args.response.success({data: items}); } }, From 1848079bcdeeb84f066ba3aa8f94b1614839bcc6 Mon Sep 17 00:00:00 2001 From: Brian Federle Date: Fri, 11 Nov 2011 11:31:06 -0800 Subject: [PATCH 156/159] Add embedded table to detail view, for guest network configuration --- ui/css/cloudstack3.css | 35 ++- ui/scripts-test/system.js | 156 ++++-------- ui/scripts-test/test-data.js | 370 ++++++++++++++++++++++++++++ ui/scripts/ui/widgets/detailView.js | 6 + 4 files changed, 458 insertions(+), 109 deletions(-) diff --git a/ui/css/cloudstack3.css b/ui/css/cloudstack3.css index b96dbd97388..c3303cc1f2c 100644 --- a/ui/css/cloudstack3.css +++ b/ui/css/cloudstack3.css @@ -563,11 +563,27 @@ div.panel div.list-view { border-bottom: 1px solid #E7E7E7; } +.detail-view div.list-view { + width: 730px; + border: 1px solid #DAD4D4; + margin: 41px auto auto !important; + height: 536px !important; + background: #F7F7F7; +} + div.panel div.list-view div.data-table table { width: 755px; margin-top: 44px; } +.detail-view div.list-view div.data-table table { + width: 703px !important; +} + +.detail-view div.list-view div.data-table table td { + border-left: 1px solid #CACACA; +} + div.panel div.list-view div.fixed-header { position: absolute; top: 28px; @@ -580,6 +596,17 @@ div.panel div.list-view div.fixed-header { z-index: 1; } +.detail-view div.list-view div.fixed-header { + width: 703px !important; + top: 49px !important; + left: 32px !important; + background: #FFFFFF; +} + +.detail-view div.list-view div.fixed-header table { + width: 100% !important; +} + .project-view div.panel div.list-view div.fixed-header { background: #6D747D; } @@ -645,10 +672,10 @@ div.list-view td.state.off { overflow: hidden; display: inline-block; z-index: 2; - /*+placement:shift 0px 1px;*/ + /*+placement:shift 0px 2px;*/ position: relative; left: 0px; - top: 1px; + top: 2px; } .project-view .ui-tabs ul { @@ -1450,6 +1477,10 @@ div.detail-group.actions td { position: absolute; } +.detail-view .ui-tabs-panel div.toolbar { + width: 768px; +} + .project-view div.toolbar { background: #808080 url(../images/bg-nav-item-active-project-view.png) 0px -210px; } diff --git a/ui/scripts-test/system.js b/ui/scripts-test/system.js index 887eb43c32d..4769eb5dbb8 100644 --- a/ui/scripts-test/system.js +++ b/ui/scripts-test/system.js @@ -114,6 +114,7 @@ }, 'management': { detailView: { + viewAll: { path: '_zone.pods', label: 'Pods' }, tabs: { details: { title: 'Details', @@ -143,119 +144,60 @@ args.response.success({ data: testData.data.networks[0] }); } }, - cidr: { - title: 'CIDR', - custom: function(args) { - return $('
').multiEdit({ - noSelect: true, - fields: { - 'cidr': { edit: true, label: 'CIDR' }, - 'add-rule': { - label: 'Add', - addButton: true - } - }, + network: { + title: 'Network', + listView: { + section: 'networks', + id: 'networks', + fields: { + name: { label: 'Name' }, + startip: { label: 'Start IP' }, + endip: { label: 'End IP' }, + vlan: { label: 'VLAN' } + }, + actions: { add: { - label: 'Add', - action: function(args) { - setTimeout(function() { - args.response.success({ - notification: { - label: 'Added VLAN range', - poll: testData.notifications.testPoll - } - }); - }, 500); - } - }, - actions: { - destroy: { - label: 'Remove Rule', - action: function(args) { - setTimeout(function() { - args.response.success({ - notification: { - label: 'Removed VLAN range', - poll: testData.notifications.testPoll - } - }); - }, 500); + label: 'Add network', + createForm: { + title: 'Add network', + desc: 'Please fill in the following to add a guest network', + fields: { + vlan: { + label: 'VLAN ID', + validation: { required: true } + }, + gateway: { + label: 'Gateway', + validation: { required: true } + }, + netmask: { + label: 'Netmask', + validation: { required: true } + }, + startip: { + label: 'Start IP', + validation: { required: true } + }, + endip: { + label: 'Start IP', + validation: { required: true } + } } - } - }, - dataProvider: function(args) { - setTimeout(function() { - args.response.success({ - data: [ - { - cidr: '0.0.0.0/0', - startvlanrange: '1480', endvlanrange: '1559' - } - ] - }); - }, 100); - } - }); - } - }, - vlanRanges: { - title: 'VLAN Ranges', - custom: function(args) { - return $('
').multiEdit({ - noSelect: true, - fields: { - 'startvlanrange': { - edit: true, label: 'Start VLAN' }, - 'endvlanrange': { - edit: true, label: 'End VLAN' - }, - 'add-rule': { - label: 'Add', - addButton: true - } - }, - add: { - label: 'Add', + action: function(args) { - setTimeout(function() { - args.response.success({ - notification: { - label: 'Added VLAN range', - poll: testData.notifications.testPoll - } - }); - }, 500); - } - }, - actions: { - destroy: { - label: 'Remove Rule', - action: function(args) { - setTimeout(function() { - args.response.success({ - notification: { - label: 'Removed VLAN range', - poll: testData.notifications.testPoll - } - }); - }, 500); + args.response.success(); + }, + + messages: { + notification: function(args) { + return 'Added guest network'; } - } - }, - dataProvider: function(args) { - setTimeout(function() { - args.response.success({ - data: [ - { - cidr: '0.0.0.0/0', - startvlanrange: '1480', endvlanrange: '1559' - } - ] - }); - }, 100); + }, + notification: { poll: testData.notifications.testPoll } } - }); + }, + dataProvider: testData.dataProvider.listView('networks') } } } diff --git a/ui/scripts-test/test-data.js b/ui/scripts-test/test-data.js index 57cbbde6ab3..040a9dc720d 100644 --- a/ui/scripts-test/test-data.js +++ b/ui/scripts-test/test-data.js @@ -4997,6 +4997,376 @@ ], networks: [ + { + "id": 269, + "name": "vlan100", + "displaytext": "sumi-network-vlan-100", + "broadcastdomaintype": "Vlan", + "traffictype": "Guest", + "gateway": "182.172.161.1", + "netmask": "255.255.255.0", + "startip": "182.172.161.10", + "endip": "182.172.161.100", + "zoneid": 1, + "networkofferingid": 7, + "networkofferingname": "DefaultDirectNetworkOffering", + "networkofferingdisplaytext": "Direct", + "networkofferingavailability": "Optional", + "isshared": true, + "issystem": false, + "state": "Setup", + "related": 269, + "broadcasturi": "vlan://100", + "dns1": "8.8.8.8", + "type": "Direct", + "vlan": "100", + "isdefault": false, + "service": [ + { + "name": "Dns" + }, + { + "name": "UserData" + }, + { + "name": "Dhcp" + } + ], + "securitygroupenabled": false + }, + { + "id": 263, + "name": "CustomerNet", + "displaytext": "Dedicated Customer Network", + "broadcastdomaintype": "Vlan", + "traffictype": "Guest", + "gateway": "192.168.129.1", + "netmask": "255.255.255.0", + "startip": "192.168.129.10", + "endip": "192.168.129.50", + "zoneid": 1, + "networkofferingid": 7, + "networkofferingname": "DefaultDirectNetworkOffering", + "networkofferingdisplaytext": "Direct", + "networkofferingavailability": "Optional", + "isshared": true, + "issystem": false, + "state": "Setup", + "related": 263, + "broadcasturi": "vlan://129", + "dns1": "8.8.8.8", + "type": "Direct", + "vlan": "129", + "isdefault": true, + "service": [ + { + "name": "Dns" + }, + { + "name": "UserData" + }, + { + "name": "Dhcp" + } + ], + "securitygroupenabled": false + }, + { + "id": 269, + "name": "vlan100", + "displaytext": "sumi-network-vlan-100", + "broadcastdomaintype": "Vlan", + "traffictype": "Guest", + "gateway": "182.172.161.1", + "netmask": "255.255.255.0", + "startip": "182.172.161.10", + "endip": "182.172.161.100", + "zoneid": 1, + "networkofferingid": 7, + "networkofferingname": "DefaultDirectNetworkOffering", + "networkofferingdisplaytext": "Direct", + "networkofferingavailability": "Optional", + "isshared": true, + "issystem": false, + "state": "Setup", + "related": 269, + "broadcasturi": "vlan://100", + "dns1": "8.8.8.8", + "type": "Direct", + "vlan": "100", + "isdefault": false, + "service": [ + { + "name": "Dns" + }, + { + "name": "UserData" + }, + { + "name": "Dhcp" + } + ], + "securitygroupenabled": false + }, + { + "id": 263, + "name": "CustomerNet", + "displaytext": "Dedicated Customer Network", + "broadcastdomaintype": "Vlan", + "traffictype": "Guest", + "gateway": "192.168.129.1", + "netmask": "255.255.255.0", + "startip": "192.168.129.10", + "endip": "192.168.129.50", + "zoneid": 1, + "networkofferingid": 7, + "networkofferingname": "DefaultDirectNetworkOffering", + "networkofferingdisplaytext": "Direct", + "networkofferingavailability": "Optional", + "isshared": true, + "issystem": false, + "state": "Setup", + "related": 263, + "broadcasturi": "vlan://129", + "dns1": "8.8.8.8", + "type": "Direct", + "vlan": "129", + "isdefault": true, + "service": [ + { + "name": "Dns" + }, + { + "name": "UserData" + }, + { + "name": "Dhcp" + } + ], + "securitygroupenabled": false + }, + { + "id": 269, + "name": "vlan100", + "displaytext": "sumi-network-vlan-100", + "broadcastdomaintype": "Vlan", + "traffictype": "Guest", + "gateway": "182.172.161.1", + "netmask": "255.255.255.0", + "startip": "182.172.161.10", + "endip": "182.172.161.100", + "zoneid": 1, + "networkofferingid": 7, + "networkofferingname": "DefaultDirectNetworkOffering", + "networkofferingdisplaytext": "Direct", + "networkofferingavailability": "Optional", + "isshared": true, + "issystem": false, + "state": "Setup", + "related": 269, + "broadcasturi": "vlan://100", + "dns1": "8.8.8.8", + "type": "Direct", + "vlan": "100", + "isdefault": false, + "service": [ + { + "name": "Dns" + }, + { + "name": "UserData" + }, + { + "name": "Dhcp" + } + ], + "securitygroupenabled": false + }, + { + "id": 263, + "name": "CustomerNet", + "displaytext": "Dedicated Customer Network", + "broadcastdomaintype": "Vlan", + "traffictype": "Guest", + "gateway": "192.168.129.1", + "netmask": "255.255.255.0", + "startip": "192.168.129.10", + "endip": "192.168.129.50", + "zoneid": 1, + "networkofferingid": 7, + "networkofferingname": "DefaultDirectNetworkOffering", + "networkofferingdisplaytext": "Direct", + "networkofferingavailability": "Optional", + "isshared": true, + "issystem": false, + "state": "Setup", + "related": 263, + "broadcasturi": "vlan://129", + "dns1": "8.8.8.8", + "type": "Direct", + "vlan": "129", + "isdefault": true, + "service": [ + { + "name": "Dns" + }, + { + "name": "UserData" + }, + { + "name": "Dhcp" + } + ], + "securitygroupenabled": false + }, + { + "id": 269, + "name": "vlan100", + "displaytext": "sumi-network-vlan-100", + "broadcastdomaintype": "Vlan", + "traffictype": "Guest", + "gateway": "182.172.161.1", + "netmask": "255.255.255.0", + "startip": "182.172.161.10", + "endip": "182.172.161.100", + "zoneid": 1, + "networkofferingid": 7, + "networkofferingname": "DefaultDirectNetworkOffering", + "networkofferingdisplaytext": "Direct", + "networkofferingavailability": "Optional", + "isshared": true, + "issystem": false, + "state": "Setup", + "related": 269, + "broadcasturi": "vlan://100", + "dns1": "8.8.8.8", + "type": "Direct", + "vlan": "100", + "isdefault": false, + "service": [ + { + "name": "Dns" + }, + { + "name": "UserData" + }, + { + "name": "Dhcp" + } + ], + "securitygroupenabled": false + }, + { + "id": 263, + "name": "CustomerNet", + "displaytext": "Dedicated Customer Network", + "broadcastdomaintype": "Vlan", + "traffictype": "Guest", + "gateway": "192.168.129.1", + "netmask": "255.255.255.0", + "startip": "192.168.129.10", + "endip": "192.168.129.50", + "zoneid": 1, + "networkofferingid": 7, + "networkofferingname": "DefaultDirectNetworkOffering", + "networkofferingdisplaytext": "Direct", + "networkofferingavailability": "Optional", + "isshared": true, + "issystem": false, + "state": "Setup", + "related": 263, + "broadcasturi": "vlan://129", + "dns1": "8.8.8.8", + "type": "Direct", + "vlan": "129", + "isdefault": true, + "service": [ + { + "name": "Dns" + }, + { + "name": "UserData" + }, + { + "name": "Dhcp" + } + ], + "securitygroupenabled": false + }, + { + "id": 269, + "name": "vlan100", + "displaytext": "sumi-network-vlan-100", + "broadcastdomaintype": "Vlan", + "traffictype": "Guest", + "gateway": "182.172.161.1", + "netmask": "255.255.255.0", + "startip": "182.172.161.10", + "endip": "182.172.161.100", + "zoneid": 1, + "networkofferingid": 7, + "networkofferingname": "DefaultDirectNetworkOffering", + "networkofferingdisplaytext": "Direct", + "networkofferingavailability": "Optional", + "isshared": true, + "issystem": false, + "state": "Setup", + "related": 269, + "broadcasturi": "vlan://100", + "dns1": "8.8.8.8", + "type": "Direct", + "vlan": "100", + "isdefault": false, + "service": [ + { + "name": "Dns" + }, + { + "name": "UserData" + }, + { + "name": "Dhcp" + } + ], + "securitygroupenabled": false + }, + { + "id": 263, + "name": "CustomerNet", + "displaytext": "Dedicated Customer Network", + "broadcastdomaintype": "Vlan", + "traffictype": "Guest", + "gateway": "192.168.129.1", + "netmask": "255.255.255.0", + "startip": "192.168.129.10", + "endip": "192.168.129.50", + "zoneid": 1, + "networkofferingid": 7, + "networkofferingname": "DefaultDirectNetworkOffering", + "networkofferingdisplaytext": "Direct", + "networkofferingavailability": "Optional", + "isshared": true, + "issystem": false, + "state": "Setup", + "related": 263, + "broadcasturi": "vlan://129", + "dns1": "8.8.8.8", + "type": "Direct", + "vlan": "129", + "isdefault": true, + "service": [ + { + "name": "Dns" + }, + { + "name": "UserData" + }, + { + "name": "Dhcp" + } + ], + "securitygroupenabled": false + }, { "id": 269, "name": "vlan100", diff --git a/ui/scripts/ui/widgets/detailView.js b/ui/scripts/ui/widgets/detailView.js index 164758407d7..c7737858ee8 100644 --- a/ui/scripts/ui/widgets/detailView.js +++ b/ui/scripts/ui/widgets/detailView.js @@ -604,6 +604,12 @@ }).appendTo($tabContent); } + if (tabs.listView) { + return $('
').listView({ + listView: tabs.listView + }).appendTo($tabContent); + } + $.extend( $detailView.data('view-args'), { activeTab: targetTabID } From 9d523abb97c112d37381ccfb6f9750997bf1532b Mon Sep 17 00:00:00 2001 From: Jessica Wang Date: Fri, 11 Nov 2011 11:31:15 -0800 Subject: [PATCH 157/159] cloudStack 3.0 new UI - network offering page - add "enable", "disable" action. --- ui/scripts/configuration.js | 89 ++++++++++++++++++++++++++++++++++--- 1 file changed, 84 insertions(+), 5 deletions(-) diff --git a/ui/scripts/configuration.js b/ui/scripts/configuration.js index 48d91ef6020..7dbf1e287ae 100644 --- a/ui/scripts/configuration.js +++ b/ui/scripts/configuration.js @@ -845,7 +845,7 @@ success: function(json) { var items = json.listnetworkofferingsresponse.networkoffering; args.response.success({ - actionFilter: networkOfferingsActionfilter, + actionFilter: networkOfferingActionfilter, data:items }); } @@ -869,7 +869,81 @@ } }); } - } + }, + //??? +enable: { + label: 'Enable network offering', + messages: { + confirm: function(args) { + return 'Are you sure you want to enable this network offering?'; + }, + success: function(args) { + return 'This network offering is being enabled.'; + }, + notification: function(args) { + return 'Enabling network offering'; + }, + complete: function(args) { + return 'Network offering has been enabled.'; + } + }, + action: function(args) { + $.ajax({ + url: createURL("updateNetworkOffering&id=" + args.context.networkOfferings[0].id + "&state=Enabled"), + dataType: "json", + async: true, + success: function(json) { + var item = json.updatenetworkofferingresponse.networkoffering; + args.response.success({ + actionFilter: networkOfferingActionfilter, + data:item + }); + } + }); + }, + notification: { + poll: function(args) { + args.complete(); + } + } + }, + + disable: { + label: 'Disable network offering', + messages: { + confirm: function(args) { + return 'Are you sure you want to disable this network offering?'; + }, + success: function(args) { + return 'This network offering is being disabled.'; + }, + notification: function(args) { + return 'Disabling network offering'; + }, + complete: function(args) { + return 'Network offering has been disabled.'; + } + }, + action: function(args) { + $.ajax({ + url: createURL("updateNetworkOffering&id=" + args.context.networkOfferings[0].id + "&state=Disabled"), + dataType: "json", + async: true, + success: function(json) { + var item = json.updatenetworkofferingresponse.networkoffering; + args.response.success({ + actionFilter: networkOfferingActionfilter, + data:item + }); + } + }); + }, + notification: { + poll: function(args) { + args.complete(); + } + } + } }, tabs: { details: { @@ -887,6 +961,7 @@ label: 'Description', isEditable: true }, + state: { label: 'State' }, availability: { label: 'Availability', isEditable: true, @@ -928,7 +1003,7 @@ dataProvider: function(args) { args.response.success( { - actionFilter: networkOfferingsActionfilter, + actionFilter: networkOfferingActionfilter, data:args.context.networkOfferings[0] } ); @@ -965,10 +1040,14 @@ return allowedActions; } - var networkOfferingsActionfilter = function(args) { + var networkOfferingActionfilter = function(args) { var jsonObj = args.context.item; var allowedActions = []; - allowedActions.push("edit"); + allowedActions.push("edit"); + if(jsonObj.state == "Enabled") + allowedActions.push("disable"); + else if(jsonObj.state == "Disabled") + allowedActions.push("enable"); return allowedActions; } From daec18b4aec3cb617e39b625f51cb21c81882554 Mon Sep 17 00:00:00 2001 From: Alena Prokharchyk Date: Fri, 11 Nov 2011 11:54:14 -0800 Subject: [PATCH 158/159] All default network offerings come as Enabled by default --- .../configuration/ConfigurationManagerImpl.java | 1 - .../com/cloud/network/NetworkManagerImpl.java | 4 ++++ .../cloud/server/ConfigurationServerImpl.java | 17 ++++++++++++----- 3 files changed, 16 insertions(+), 6 deletions(-) diff --git a/server/src/com/cloud/configuration/ConfigurationManagerImpl.java b/server/src/com/cloud/configuration/ConfigurationManagerImpl.java index 12d57909e75..5da6e4ea8d4 100755 --- a/server/src/com/cloud/configuration/ConfigurationManagerImpl.java +++ b/server/src/com/cloud/configuration/ConfigurationManagerImpl.java @@ -35,7 +35,6 @@ import javax.naming.ConfigurationException; import org.apache.log4j.Logger; -import com.cloud.acl.ControlledEntity.ACLType; import com.cloud.acl.SecurityChecker; import com.cloud.alert.AlertManager; import com.cloud.api.commands.CreateCfgCmd; diff --git a/server/src/com/cloud/network/NetworkManagerImpl.java b/server/src/com/cloud/network/NetworkManagerImpl.java index 6efaaf17622..5c1e1e2046c 100755 --- a/server/src/com/cloud/network/NetworkManagerImpl.java +++ b/server/src/com/cloud/network/NetworkManagerImpl.java @@ -905,21 +905,25 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag NetworkOfferingVO offering = null; if (_networkOfferingDao.findByUniqueName(NetworkOffering.DefaultSharedNetworkOfferingWithSGService) == null) { offering = _configMgr.createNetworkOffering(Account.ACCOUNT_ID_SYSTEM, NetworkOffering.DefaultSharedNetworkOfferingWithSGService, "Offering for Shared Security group enabled networks", TrafficType.Guest, null, null, false, Availability.Optional, null, defaultSharedNetworkOfferingProviders, true, Network.GuestType.Shared, false, null, null); + offering.setState(NetworkOffering.State.Enabled); _networkOfferingDao.update(offering.getId(), offering); } if (_networkOfferingDao.findByUniqueName(NetworkOffering.DefaultSharedNetworkOffering) == null) { offering = _configMgr.createNetworkOffering(Account.ACCOUNT_ID_SYSTEM, NetworkOffering.DefaultSharedNetworkOffering, "Offering for Shared networks", TrafficType.Guest, null, null, true, Availability.Optional, null, defaultSharedNetworkOfferingProviders, true, Network.GuestType.Shared, false, null, null); + offering.setState(NetworkOffering.State.Enabled); _networkOfferingDao.update(offering.getId(), offering); } if (_networkOfferingDao.findByUniqueName(NetworkOffering.DefaultIsolatedNetworkOfferingWithSourceNatService) == null) { offering = _configMgr.createNetworkOffering(Account.ACCOUNT_ID_SYSTEM,NetworkOffering.DefaultIsolatedNetworkOfferingWithSourceNatService, "Offering for Isolated networks with Source Nat service enabled", TrafficType.Guest, null, null, false, Availability.Required, null, defaultIsolatedSourceNatEnabledNetworkOfferingProviders, true, Network.GuestType.Isolated, false, null, null); + offering.setState(NetworkOffering.State.Enabled); _networkOfferingDao.update(offering.getId(), offering); } if (_networkOfferingDao.findByUniqueName(NetworkOffering.DefaultIsolatedNetworkOffering) == null) { offering = _configMgr.createNetworkOffering(Account.ACCOUNT_ID_SYSTEM, NetworkOffering.DefaultIsolatedNetworkOffering, "Offering for Isolated networks with no Source Nat service", TrafficType.Guest, null, null, true, Availability.Optional, null, defaultIsolatedNetworkOfferingProviders, true, Network.GuestType.Isolated, false, null, null); + offering.setState(NetworkOffering.State.Enabled); _networkOfferingDao.update(offering.getId(), offering); } diff --git a/server/src/com/cloud/server/ConfigurationServerImpl.java b/server/src/com/cloud/server/ConfigurationServerImpl.java index a7d6fd0fb28..fb520b5399c 100644 --- a/server/src/com/cloud/server/ConfigurationServerImpl.java +++ b/server/src/com/cloud/server/ConfigurationServerImpl.java @@ -47,7 +47,6 @@ import javax.crypto.SecretKey; import org.apache.commons.codec.binary.Base64; import org.apache.log4j.Logger; -import com.cloud.acl.ControlledEntity.ACLType; import com.cloud.configuration.Config; import com.cloud.configuration.ConfigurationVO; import com.cloud.configuration.Resource; @@ -68,7 +67,6 @@ import com.cloud.domain.dao.DomainDao; import com.cloud.exception.InternalErrorException; import com.cloud.exception.InvalidParameterValueException; import com.cloud.network.Network; -import com.cloud.network.Network.GuestType; import com.cloud.network.Network.Provider; import com.cloud.network.Network.Service; import com.cloud.network.Network.State; @@ -820,7 +818,8 @@ public class ConfigurationServerImpl implements ConfigurationServer { return tags; } - private void createDefaultNetworkOfferings() { + @DB + protected void createDefaultNetworkOfferings() { NetworkOfferingVO publicNetworkOffering = new NetworkOfferingVO(NetworkOfferingVO.SystemPublicNetwork, TrafficType.Public); publicNetworkOffering = _networkOfferingDao.persistDefaultNetworkOffering(publicNetworkOffering); @@ -859,6 +858,8 @@ public class ConfigurationServerImpl implements ConfigurationServer { //The only one diff between 1 and 2 network offerings is that the first one has SG enabled. In Basic zone only first network offering has to be enabled, in Advance zone - the second one + Transaction txn = Transaction.currentTxn(); + txn.start(); //Offering #1 NetworkOfferingVO deafultSharedSGNetworkOffering = new NetworkOfferingVO( @@ -868,6 +869,7 @@ public class ConfigurationServerImpl implements ConfigurationServer { false, false, null, null, null, true, Availability.Optional, null, Network.GuestType.Shared); + deafultSharedSGNetworkOffering.setState(NetworkOffering.State.Enabled); deafultSharedSGNetworkOffering = _networkOfferingDao.persistDefaultNetworkOffering(deafultSharedSGNetworkOffering); for (Service service : defaultSharedSGNetworkOfferingProviders.keySet()) { @@ -884,6 +886,7 @@ public class ConfigurationServerImpl implements ConfigurationServer { false, true, null, null, null, true, Availability.Optional, null, Network.GuestType.Shared); + defaultSharedNetworkOffering.setState(NetworkOffering.State.Enabled); defaultSharedNetworkOffering = _networkOfferingDao.persistDefaultNetworkOffering(defaultSharedNetworkOffering); for (Service service : defaultSharedNetworkOfferingProviders.keySet()) { @@ -900,6 +903,7 @@ public class ConfigurationServerImpl implements ConfigurationServer { false, false, null, null, null, true, Availability.Required, null, Network.GuestType.Isolated); + defaultIsolatedSourceNatEnabledNetworkOffering.setState(NetworkOffering.State.Enabled); defaultIsolatedSourceNatEnabledNetworkOffering = _networkOfferingDao.persistDefaultNetworkOffering(defaultIsolatedSourceNatEnabledNetworkOffering); @@ -917,13 +921,16 @@ public class ConfigurationServerImpl implements ConfigurationServer { false, true, null, null, null, true, Availability.Optional, null, Network.GuestType.Isolated); - defaultSharedNetworkOffering = _networkOfferingDao.persistDefaultNetworkOffering(defaultIsolatedEnabledNetworkOffering); + defaultIsolatedEnabledNetworkOffering.setState(NetworkOffering.State.Enabled); + defaultIsolatedEnabledNetworkOffering = _networkOfferingDao.persistDefaultNetworkOffering(defaultIsolatedEnabledNetworkOffering); for (Service service : defaultIsolatedNetworkOfferingProviders.keySet()) { - NetworkOfferingServiceMapVO offService = new NetworkOfferingServiceMapVO(defaultSharedNetworkOffering.getId(), service, defaultIsolatedNetworkOfferingProviders.get(service)); + NetworkOfferingServiceMapVO offService = new NetworkOfferingServiceMapVO(defaultIsolatedEnabledNetworkOffering.getId(), service, defaultIsolatedNetworkOfferingProviders.get(service)); _ntwkOfferingServiceMapDao.persist(offService); s_logger.trace("Added service for the network offering: " + offService); } + + txn.commit(); } From 22f1755d776b4d0415e82f744cf982de8e7c4fa1 Mon Sep 17 00:00:00 2001 From: Brian Federle Date: Fri, 11 Nov 2011 11:56:35 -0800 Subject: [PATCH 159/159] Disable 'add pod' and 'add ip range' steps in zone wizard --- ui/css/cloudstack3.css | 11 ++++++----- ui/index-test.html | 14 ++++++-------- ui/index.jsp | 14 ++++++-------- ui/scripts/ui-custom/zoneWizard.js | 2 +- 4 files changed, 19 insertions(+), 22 deletions(-) diff --git a/ui/css/cloudstack3.css b/ui/css/cloudstack3.css index c3303cc1f2c..260db04d720 100644 --- a/ui/css/cloudstack3.css +++ b/ui/css/cloudstack3.css @@ -3451,10 +3451,11 @@ label.error { } .multi-wizard .progress ul li span.multiline { - /*+placement:shift -22px 12px;*/ + /*+placement:shift -154px 16px;*/ position: relative; - left: -22px; - top: 12px; + left: -154px; + top: 16px; + width: 87px; } .multi-wizard .progress ul li span.arrow { @@ -4207,12 +4208,12 @@ label.error { } .multi-wizard.zone-wizard .progress ul li { - width: 128px; + width: 288px; padding: 0 32px 0 0; } .multi-wizard.zone-wizard .progress ul li span.arrow { - margin: 0 0 0 32px; + margin: 0 0 0 193px; } .multi-wizard.zone-wizard .select-network .content .section { diff --git a/ui/index-test.html b/ui/index-test.html index 1d949ddb096..ef1eb43229f 100644 --- a/ui/index-test.html +++ b/ui/index-test.html @@ -374,10 +374,8 @@
    -
  • 1Select Network
  • -
  • 2Setup Zone
  • -
  • 3Setup Pod
  • -
  • 4Setup IP Range
  • +
  • 1Select Zone Type
  • +
  • 2Setup Zone
@@ -387,8 +385,8 @@
-

Setup network model

-

Please select a network model for your zone.

+

Setup zone type

+

Please select a configuration for your zone.

Choose this network model if you do not want to enable any VLAN support. All virtual instances created under this network model will be assigned an IP directly from the network and security groups are used to provide security and segregation.
@@ -516,7 +514,7 @@
-
+
Please enter the following information to add a new pod
@@ -568,7 +566,7 @@
-
+
Please add an IP range for your zone
diff --git a/ui/index.jsp b/ui/index.jsp index 3faefea0c6f..7fa80272d4c 100644 --- a/ui/index.jsp +++ b/ui/index.jsp @@ -374,10 +374,8 @@
    -
  • 1Select Network
  • -
  • 2Setup Zone
  • -
  • 3Setup Pod
  • -
  • 4Setup IP Range
  • +
  • 1Select Zone Type
  • +
  • 2Setup Zone
@@ -387,8 +385,8 @@
-

Setup network model

-

Please select a network model for your zone.

+

Setup zone type

+

Please select a configuration for your zone.

Choose this network model if you do not want to enable any VLAN support. All virtual instances created under this network model will be assigned an IP directly from the network and security groups are used to provide security and segregation.
@@ -516,7 +514,7 @@
-
+
Please enter the following information to add a new pod
@@ -568,7 +566,7 @@
-
+
Please add an IP range for your zone
diff --git a/ui/scripts/ui-custom/zoneWizard.js b/ui/scripts/ui-custom/zoneWizard.js index 9c733fa938c..a6638dec4d4 100644 --- a/ui/scripts/ui-custom/zoneWizard.js +++ b/ui/scripts/ui-custom/zoneWizard.js @@ -6,7 +6,7 @@ return function(listViewArgs) { var $wizard = $('#template').find('div.zone-wizard').clone(); var $progress = $wizard.find('div.progress ul li'); - var $steps = $wizard.find('div.steps').children().hide(); + var $steps = $wizard.find('div.steps').children().hide().filter(':not(.disabled)'); var $diagramParts = $wizard.find('div.diagram').children().hide(); // Close wizard