diff --git a/server/src/main/java/com/cloud/network/NetworkServiceImpl.java b/server/src/main/java/com/cloud/network/NetworkServiceImpl.java index e9c4554a0b5..10212273e5b 100644 --- a/server/src/main/java/com/cloud/network/NetworkServiceImpl.java +++ b/server/src/main/java/com/cloud/network/NetworkServiceImpl.java @@ -198,7 +198,7 @@ import com.cloud.vm.dao.VMInstanceDao; /** * NetworkServiceImpl implements NetworkService. */ -public class NetworkServiceImpl extends ManagerBase implements NetworkService { +public class NetworkServiceImpl extends ManagerBase implements NetworkService { private static final Logger s_logger = Logger.getLogger(NetworkServiceImpl.class); private static final long MIN_VLAN_ID = 0L; @@ -429,8 +429,7 @@ public class NetworkServiceImpl extends ManagerBase implements NetworkService { throw new InvalidParameterException("There are multiple services used ip " + ip.getAddress() + "."); } if (service != null && !((Service)services.toArray()[0] == service || service.equals(Service.Firewall))) { - throw new InvalidParameterException("The IP " + ip.getAddress() + " is already used as " + ((Service)services.toArray()[0]).getName() + " rather than " - + service.getName()); + throw new InvalidParameterException("The IP " + ip.getAddress() + " is already used as " + ((Service)services.toArray()[0]).getName() + " rather than " + service.getName()); } return true; } @@ -519,8 +518,8 @@ public class NetworkServiceImpl extends ManagerBase implements NetworkService { @Override @ActionEvent(eventType = EventTypes.EVENT_NET_IP_ASSIGN, eventDescription = "allocating Ip", create = true) - public IpAddress allocateIP(Account ipOwner, long zoneId, Long networkId, Boolean displayIp) throws ResourceAllocationException, InsufficientAddressCapacityException, - ConcurrentOperationException { + public IpAddress allocateIP(Account ipOwner, long zoneId, Long networkId, Boolean displayIp) + throws ResourceAllocationException, InsufficientAddressCapacityException, ConcurrentOperationException { Account caller = CallContext.current().getCallingAccount(); long callerUserId = CallContext.current().getCallingUserId(); @@ -559,8 +558,8 @@ public class NetworkServiceImpl extends ManagerBase implements NetworkService { @Override @ActionEvent(eventType = EventTypes.EVENT_PORTABLE_IP_ASSIGN, eventDescription = "allocating portable public Ip", create = true) - public IpAddress allocatePortableIP(Account ipOwner, int regionId, Long zoneId, Long networkId, Long vpcId) throws ResourceAllocationException, - InsufficientAddressCapacityException, ConcurrentOperationException { + public IpAddress allocatePortableIP(Account ipOwner, int regionId, Long zoneId, Long networkId, Long vpcId) + throws ResourceAllocationException, InsufficientAddressCapacityException, ConcurrentOperationException { Account caller = CallContext.current().getCallingAccount(); long callerUserId = CallContext.current().getCallingUserId(); DataCenter zone = _entityMgr.findById(DataCenter.class, zoneId); @@ -613,7 +612,7 @@ public class NetworkServiceImpl extends ManagerBase implements NetworkService { try { return releaseIpAddressInternal(ipAddressId); } catch (Exception e) { - return false; + return false; } } @@ -674,18 +673,18 @@ public class NetworkServiceImpl extends ManagerBase implements NetworkService { String ipv6Address = requestedIpPair.getIp6Address(); //check whether the nic belongs to user vm. - final NicVO nicVO = _nicDao.findById(nicId); + NicVO nicVO = _nicDao.findById(nicId); if (nicVO == null) { - throw new InvalidParameterValueException("There is no nic for the " + nicId); + throw new InvalidParameterValueException("There is no NIC with the ID: " + nicId); } if (nicVO.getVmType() != VirtualMachine.Type.User) { - throw new InvalidParameterValueException("The nic is not belongs to user vm"); + throw new InvalidParameterValueException(String.format("The NIC [%s] does not belong to a user VM", nicVO.getUuid())); } VirtualMachine vm = _userVmDao.findById(nicVO.getInstanceId()); if (vm == null) { - throw new InvalidParameterValueException("There is no vm with the nic"); + throw new InvalidParameterValueException(String.format("There is no VM with the NIC [%s]", nicVO.getUuid())); } final long networkId = nicVO.getNetworkId(); @@ -711,15 +710,11 @@ public class NetworkServiceImpl extends ManagerBase implements NetworkService { String ip6addr = null; //Isolated network can exist in Basic zone only, so no need to verify the zone type if (network.getGuestType() == Network.GuestType.Isolated) { - try { - if (ipv4Address != null) { - ipaddr = _ipAddrMgr.allocateGuestIP(network, ipv4Address); - } - if (ipv6Address != null) { - ip6addr = ipv6AddrMgr.allocateGuestIpv6(network, ipv6Address); - } - } catch (InsufficientAddressCapacityException e) { - throw new InvalidParameterValueException("Allocating guest ip for nic failed"); + if ((ipv4Address != null || NetUtils.isIpv4(network.getGateway()) && org.apache.commons.lang3.StringUtils.isBlank(ipv6Address))) { + ipaddr = _ipAddrMgr.allocateGuestIP(network, ipv4Address); + } + if (ipv6Address != null) { + ip6addr = ipv6AddrMgr.allocateGuestIpv6(network, ipv6Address); } } else if (network.getGuestType() == Network.GuestType.Shared) { //for basic zone, need to provide the podId to ensure proper ip alloation @@ -784,8 +779,7 @@ public class NetworkServiceImpl extends ManagerBase implements NetworkService { @Override @DB - @ActionEvent(eventType = EventTypes.EVENT_NIC_SECONDARY_IP_UNASSIGN, eventDescription = "Removing secondary ip " + - "from nic", async = true) + @ActionEvent(eventType = EventTypes.EVENT_NIC_SECONDARY_IP_UNASSIGN, eventDescription = "Removing secondary IP from NIC", async = true) public boolean releaseSecondaryIpFromNic(long ipAddressId) { Account caller = CallContext.current().getCallingAccount(); boolean success = false; @@ -831,7 +825,7 @@ public class NetworkServiceImpl extends ManagerBase implements NetworkService { if (dc.getNetworkType() == NetworkType.Advanced && network.getGuestType() == Network.GuestType.Isolated) { //check PF or static NAT is configured on this ip address String secondaryIp = secIpVO.getIp4Address(); - List fwRulesList = _firewallDao.listByNetworkAndPurpose(network.getId(), Purpose.PortForwarding); + List fwRulesList = _firewallDao.listByNetworkAndPurpose(network.getId(), Purpose.PortForwarding); if (fwRulesList.size() != 0) { for (FirewallRuleVO rule : fwRulesList) { @@ -859,8 +853,8 @@ public class NetworkServiceImpl extends ManagerBase implements NetworkService { Transaction.execute(new TransactionCallbackNoReturn() { @Override public void doInTransactionWithoutResult(TransactionStatus status) { - _ipAddrMgr.markIpAsUnavailable(ip.getId()); - _ipAddressDao.unassignIpAddress(ip.getId()); + _ipAddrMgr.markIpAsUnavailable(ip.getId()); + _ipAddressDao.unassignIpAddress(ip.getId()); } }); } @@ -879,14 +873,14 @@ public class NetworkServiceImpl extends ManagerBase implements NetworkService { Transaction.execute(new TransactionCallbackNoReturn() { @Override public void doInTransactionWithoutResult(TransactionStatus status) { - if (lastIp) { - nic.setSecondaryIp(false); - s_logger.debug("Setting nics secondary ip to false ..."); - _nicDao.update(nicId, nic); - } + if (lastIp) { + nic.setSecondaryIp(false); + s_logger.debug("Setting nics secondary ip to false ..."); + _nicDao.update(nicId, nic); + } - s_logger.debug("Revoving nic secondary ip entry ..."); - _nicSecondaryIpDao.remove(ipVO.getId()); + s_logger.debug("Revoving nic secondary ip entry ..."); + _nicSecondaryIpDao.remove(ipVO.getId()); } }); @@ -1141,8 +1135,7 @@ public class NetworkServiceImpl extends ManagerBase implements NetworkService { if (domainId != null) { if (ntwkOff.getTrafficType() != TrafficType.Guest || ntwkOff.getGuestType() != Network.GuestType.Shared) { - throw new InvalidParameterValueException("Domain level networks are supported just for traffic type " + TrafficType.Guest + " and guest type " - + Network.GuestType.Shared); + throw new InvalidParameterValueException("Domain level networks are supported just for traffic type " + TrafficType.Guest + " and guest type " + Network.GuestType.Shared); } DomainVO domain = _domainDao.findById(domainId); @@ -1208,7 +1201,7 @@ public class NetworkServiceImpl extends ManagerBase implements NetworkService { } if (gateway != null && netmask != null) { - if(NetUtils.isNetworkorBroadcastIP(gateway,netmask)) { + if (NetUtils.isNetworkorBroadcastIP(gateway, netmask)) { if (s_logger.isDebugEnabled()) { s_logger.debug("The gateway IP provided is " + gateway + " and netmask is " + netmask + ". The IP is either broadcast or network IP."); } @@ -1247,11 +1240,11 @@ public class NetworkServiceImpl extends ManagerBase implements NetworkService { } // Regular user can create Guest Isolated Source Nat enabled network only - if (_accountMgr.isNormalUser(caller.getId()) - && (ntwkOff.getTrafficType() != TrafficType.Guest || ntwkOff.getGuestType() != Network.GuestType.Isolated - && areServicesSupportedByNetworkOffering(ntwkOff.getId(), Service.SourceNat))) { - throw new InvalidParameterValueException("Regular user can create a network only from the network" + " offering having traffic type " + TrafficType.Guest - + " and network type " + Network.GuestType.Isolated + " with a service " + Service.SourceNat.getName() + " enabled"); + if (_accountMgr.isNormalUser(caller.getId()) && (ntwkOff.getTrafficType() != TrafficType.Guest + || ntwkOff.getGuestType() != Network.GuestType.Isolated && areServicesSupportedByNetworkOffering(ntwkOff.getId(), Service.SourceNat))) { + throw new InvalidParameterValueException( + String.format("Regular users can only create a network from network offerings having traffic type [%s] and network type [%s] with a service [%s] enabled.", TrafficType.Guest, + Network.GuestType.Isolated, Service.SourceNat.getName())); } // Don't allow to specify vlan if the caller is not ROOT admin @@ -1289,17 +1282,16 @@ public class NetworkServiceImpl extends ManagerBase implements NetworkService { // if the guest network is for the VPC, if any External Provider are supported in VPC // cidr will not be null as it is generated from the super cidr of vpc. // if cidr is not null and network is not part of vpc then throw the exception - if (vpcId == null) + if (vpcId == null) { throw new InvalidParameterValueException("Cannot specify CIDR when using network offering with external devices!"); + } } } // Vlan is created in 1 cases - works in Advance zone only: // 1) GuestType is Shared - boolean createVlan = (startIP != null && endIP != null && zone.getNetworkType() == NetworkType.Advanced - && ((ntwkOff.getGuestType() == Network.GuestType.Shared) - || (ntwkOff.getGuestType() == GuestType.Isolated && - !areServicesSupportedByNetworkOffering(ntwkOff.getId(), Service.SourceNat)))); + boolean createVlan = (startIP != null && endIP != null && zone.getNetworkType() == NetworkType.Advanced && ((ntwkOff.getGuestType() == Network.GuestType.Shared) + || (ntwkOff.getGuestType() == GuestType.Isolated && !areServicesSupportedByNetworkOffering(ntwkOff.getId(), Service.SourceNat)))); if (!createVlan) { // Only support advance shared network in IPv6, which means createVlan is a must @@ -1313,9 +1305,9 @@ public class NetworkServiceImpl extends ManagerBase implements NetworkService { throwInvalidIdException("Network offering with specified id doesn't support adding multiple ip ranges", ntwkOff.getUuid(), "networkOfferingId"); } - Network network = commitNetwork(networkOfferingId, gateway, startIP, endIP, netmask, networkDomain, vlanId, bypassVlanOverlapCheck, name, displayText, caller, physicalNetworkId, zoneId, domainId, - isDomainSpecific, subdomainAccess, vpcId, startIPv6, endIPv6, ip6Gateway, ip6Cidr, displayNetwork, aclId, isolatedPvlan, ntwkOff, pNtwk, aclType, owner, cidr, - createVlan, externalId); + Network network = commitNetwork(networkOfferingId, gateway, startIP, endIP, netmask, networkDomain, vlanId, bypassVlanOverlapCheck, name, displayText, caller, physicalNetworkId, zoneId, + domainId, isDomainSpecific, subdomainAccess, vpcId, startIPv6, endIPv6, ip6Gateway, ip6Cidr, displayNetwork, aclId, isolatedPvlan, ntwkOff, pNtwk, aclType, owner, cidr, createVlan, + externalId); // if the network offering has persistent set to true, implement the network if (ntwkOff.isPersistent()) { @@ -1344,11 +1336,11 @@ public class NetworkServiceImpl extends ManagerBase implements NetworkService { return network; } - private Network commitNetwork(final Long networkOfferingId, final String gateway, final String startIP, final String endIP, final String netmask, final String networkDomain, - final String vlanId, final Boolean bypassVlanOverlapCheck, final String name, final String displayText, final Account caller, final Long physicalNetworkId, final Long zoneId, final Long domainId, - final boolean isDomainSpecific, final Boolean subdomainAccessFinal, final Long vpcId, final String startIPv6, final String endIPv6, final String ip6Gateway, - final String ip6Cidr, final Boolean displayNetwork, final Long aclId, final String isolatedPvlan, final NetworkOfferingVO ntwkOff, final PhysicalNetwork pNtwk, - final ACLType aclType, final Account ownerFinal, final String cidr, final boolean createVlan, final String externalId) throws InsufficientCapacityException, ResourceAllocationException { + private Network commitNetwork(final Long networkOfferingId, final String gateway, final String startIP, final String endIP, final String netmask, final String networkDomain, final String vlanId, + final Boolean bypassVlanOverlapCheck, final String name, final String displayText, final Account caller, final Long physicalNetworkId, final Long zoneId, final Long domainId, + final boolean isDomainSpecific, final Boolean subdomainAccessFinal, final Long vpcId, final String startIPv6, final String endIPv6, final String ip6Gateway, final String ip6Cidr, + final Boolean displayNetwork, final Long aclId, final String isolatedPvlan, final NetworkOfferingVO ntwkOff, final PhysicalNetwork pNtwk, final ACLType aclType, final Account ownerFinal, + final String cidr, final boolean createVlan, final String externalId) throws InsufficientCapacityException, ResourceAllocationException { try { Network network = Transaction.execute(new TransactionCallbackWithException() { @Override @@ -1392,8 +1384,8 @@ public class NetworkServiceImpl extends ManagerBase implements NetworkService { } } } - network = _vpcMgr.createVpcGuestNetwork(networkOfferingId, name, displayText, gateway, cidr, vlanId, networkDomain, owner, sharedDomainId, pNtwk, zoneId, - aclType, subdomainAccess, vpcId, aclId, caller, displayNetwork, externalId); + network = _vpcMgr.createVpcGuestNetwork(networkOfferingId, name, displayText, gateway, cidr, vlanId, networkDomain, owner, sharedDomainId, pNtwk, zoneId, aclType, + subdomainAccess, vpcId, aclId, caller, displayNetwork, externalId); } else { if (_configMgr.isOfferingForVpc(ntwkOff)) { throw new InvalidParameterValueException("Network offering can be used for VPC networks only"); @@ -1402,8 +1394,8 @@ public class NetworkServiceImpl extends ManagerBase implements NetworkService { throw new InvalidParameterValueException("Internal Lb can be enabled on vpc networks only"); } - network = _networkMgr.createGuestNetwork(networkOfferingId, name, displayText, gateway, cidr, vlanId, bypassVlanOverlapCheck, networkDomain, owner, sharedDomainId, pNtwk, zoneId, - aclType, subdomainAccess, vpcId, ip6Gateway, ip6Cidr, displayNetwork, isolatedPvlan, externalId); + network = _networkMgr.createGuestNetwork(networkOfferingId, name, displayText, gateway, cidr, vlanId, bypassVlanOverlapCheck, networkDomain, owner, sharedDomainId, pNtwk, + zoneId, aclType, subdomainAccess, vpcId, ip6Gateway, ip6Cidr, displayNetwork, isolatedPvlan, externalId); } if (_accountMgr.isRootAdmin(caller.getId()) && createVlan && network != null) { @@ -1526,7 +1518,7 @@ public class NetworkServiceImpl extends ManagerBase implements NetworkService { if (domainId != null) { path = _domainDao.findById(domainId).getPath(); } else { - path = _domainDao.findById(caller.getDomainId()).getPath(); + path = _domainDao.findById(caller.getDomainId()).getPath(); } if (listAll && domainId == null) { @@ -1575,46 +1567,40 @@ public class NetworkServiceImpl extends ManagerBase implements NetworkService { sb.join("domainSearch", domainSearch, sb.entity().getDomainId(), domainSearch.entity().getId(), JoinBuilder.JoinType.INNER); } - SearchBuilder accountSearch = _accountDao.createSearchBuilder(); + SearchBuilder accountSearch = _accountDao.createSearchBuilder(); accountSearch.and("typeNEQ", accountSearch.entity().getType(), SearchCriteria.Op.NEQ); accountSearch.and("typeEQ", accountSearch.entity().getType(), SearchCriteria.Op.EQ); - sb.join("accountSearch", accountSearch, sb.entity().getAccountId(), accountSearch.entity().getId(), JoinBuilder.JoinType.INNER); + sb.join("accountSearch", accountSearch, sb.entity().getAccountId(), accountSearch.entity().getId(), JoinBuilder.JoinType.INNER); List networksToReturn = new ArrayList(); if (isSystem == null || !isSystem) { if (!permittedAccounts.isEmpty()) { //get account level networks - networksToReturn.addAll(listAccountSpecificNetworks( - buildNetworkSearchCriteria(sb, keyword, id, isSystem, zoneId, guestIpType, trafficType, physicalNetworkId, aclType, skipProjectNetworks, restartRequired, - specifyIpRanges, vpcId, tags, display), searchFilter, permittedAccounts)); + networksToReturn.addAll(listAccountSpecificNetworks(buildNetworkSearchCriteria(sb, keyword, id, isSystem, zoneId, guestIpType, trafficType, physicalNetworkId, aclType, + skipProjectNetworks, restartRequired, specifyIpRanges, vpcId, tags, display), searchFilter, permittedAccounts)); //get domain level networks if (domainId != null) { - networksToReturn.addAll(listDomainLevelNetworks( - buildNetworkSearchCriteria(sb, keyword, id, isSystem, zoneId, guestIpType, trafficType, physicalNetworkId, aclType, true, restartRequired, - specifyIpRanges, vpcId, tags, display), searchFilter, domainId, false)); + networksToReturn.addAll(listDomainLevelNetworks(buildNetworkSearchCriteria(sb, keyword, id, isSystem, zoneId, guestIpType, trafficType, physicalNetworkId, aclType, true, + restartRequired, specifyIpRanges, vpcId, tags, display), searchFilter, domainId, false)); } } else { //add account specific networks - networksToReturn.addAll(listAccountSpecificNetworksByDomainPath( - buildNetworkSearchCriteria(sb, keyword, id, isSystem, zoneId, guestIpType, trafficType, physicalNetworkId, aclType, skipProjectNetworks, restartRequired, - specifyIpRanges, vpcId, tags, display), searchFilter, path, isRecursive)); + networksToReturn.addAll(listAccountSpecificNetworksByDomainPath(buildNetworkSearchCriteria(sb, keyword, id, isSystem, zoneId, guestIpType, trafficType, physicalNetworkId, aclType, + skipProjectNetworks, restartRequired, specifyIpRanges, vpcId, tags, display), searchFilter, path, isRecursive)); //add domain specific networks of domain + parent domains - networksToReturn.addAll(listDomainSpecificNetworksByDomainPath( - buildNetworkSearchCriteria(sb, keyword, id, isSystem, zoneId, guestIpType, trafficType, physicalNetworkId, aclType, skipProjectNetworks, restartRequired, - specifyIpRanges, vpcId, tags, display), searchFilter, path, isRecursive)); + networksToReturn.addAll(listDomainSpecificNetworksByDomainPath(buildNetworkSearchCriteria(sb, keyword, id, isSystem, zoneId, guestIpType, trafficType, physicalNetworkId, aclType, + skipProjectNetworks, restartRequired, specifyIpRanges, vpcId, tags, display), searchFilter, path, isRecursive)); //add networks of subdomains if (domainId == null) { - networksToReturn.addAll(listDomainLevelNetworks( - buildNetworkSearchCriteria(sb, keyword, id, isSystem, zoneId, guestIpType, trafficType, physicalNetworkId, aclType, true, restartRequired, - specifyIpRanges, vpcId, tags, display), searchFilter, caller.getDomainId(), true)); + networksToReturn.addAll(listDomainLevelNetworks(buildNetworkSearchCriteria(sb, keyword, id, isSystem, zoneId, guestIpType, trafficType, physicalNetworkId, aclType, true, + restartRequired, specifyIpRanges, vpcId, tags, display), searchFilter, caller.getDomainId(), true)); } } } else { - networksToReturn = _networksDao.search( - buildNetworkSearchCriteria(sb, keyword, id, isSystem, zoneId, guestIpType, trafficType, physicalNetworkId, null, skipProjectNetworks, restartRequired, - specifyIpRanges, vpcId, tags, display), searchFilter); + networksToReturn = _networksDao.search(buildNetworkSearchCriteria(sb, keyword, id, isSystem, zoneId, guestIpType, trafficType, physicalNetworkId, null, skipProjectNetworks, + restartRequired, specifyIpRanges, vpcId, tags, display), searchFilter); } if (supportedServicesStr != null && !supportedServicesStr.isEmpty() && !networksToReturn.isEmpty()) { @@ -1661,9 +1647,8 @@ public class NetworkServiceImpl extends ManagerBase implements NetworkService { return new Pair, Integer>(networksToReturn, networksToReturn.size()); } - private SearchCriteria buildNetworkSearchCriteria(SearchBuilder sb, String keyword, Long id, Boolean isSystem, Long zoneId, String guestIpType, - String trafficType, Long physicalNetworkId, String aclType, boolean skipProjectNetworks, Boolean restartRequired, Boolean specifyIpRanges, Long vpcId, - Map tags, Boolean display) { + private SearchCriteria buildNetworkSearchCriteria(SearchBuilder sb, String keyword, Long id, Boolean isSystem, Long zoneId, String guestIpType, String trafficType, + Long physicalNetworkId, String aclType, boolean skipProjectNetworks, Boolean restartRequired, Boolean specifyIpRanges, Long vpcId, Map tags, Boolean display) { SearchCriteria sc = sb.create(); @@ -1726,7 +1711,7 @@ public class NetworkServiceImpl extends ManagerBase implements NetworkService { if (tags != null && !tags.isEmpty()) { int count = 0; sc.setJoinParameters("tagSearch", "resourceType", ResourceObjectType.Network.toString()); - for ( Map.Entry entry: tags.entrySet()) { + for (Map.Entry entry : tags.entrySet()) { sc.setJoinParameters("tagSearch", "key" + String.valueOf(count), entry.getKey()); sc.setJoinParameters("tagSearch", "value" + String.valueOf(count), entry.getValue()); count++; @@ -1817,7 +1802,7 @@ public class NetworkServiceImpl extends ManagerBase implements NetworkService { domainSC.addAnd("aclType", SearchCriteria.Op.EQ, ACLType.Domain.toString()); sc.addAnd("id", SearchCriteria.Op.SC, domainSC); - return _networksDao.search(sc, searchFilter); + return _networksDao.search(sc, searchFilter); } else { return new ArrayList(); } @@ -1879,8 +1864,7 @@ public class NetworkServiceImpl extends ManagerBase implements NetworkService { // Don't allow to restart network if it's not in Implemented/Setup state if (!(network.getState() == Network.State.Implemented || network.getState() == Network.State.Setup)) { - throw new InvalidParameterValueException("Network is not in the right state to be restarted. Correct states are: " + Network.State.Implemented + ", " - + Network.State.Setup); + throw new InvalidParameterValueException("Network is not in the right state to be restarted. Correct states are: " + Network.State.Implemented + ", " + Network.State.Setup); } if (network.getBroadcastDomainType() == BroadcastDomainType.Lswitch) { @@ -1948,8 +1932,7 @@ public class NetworkServiceImpl extends ManagerBase implements NetworkService { if (elementCapabilities == null || !elementCapabilities.containsKey(service)) { // TBD: We should be sending providerId and not the offering object itself. - throw new UnsupportedServiceException("Service " + service.getName() + " is not supported by the element=" + element.getName() + " implementing Provider=" - + provider); + throw new UnsupportedServiceException("Service " + service.getName() + " is not supported by the element=" + element.getName() + " implementing Provider=" + provider); } serviceCapabilities = elementCapabilities.get(service); } @@ -1974,10 +1957,9 @@ public class NetworkServiceImpl extends ManagerBase implements NetworkService { protected boolean isSharedNetworkOfferingWithServices(long networkOfferingId) { NetworkOfferingVO networkOffering = _networkOfferingDao.findById(networkOfferingId); - if ((networkOffering.getGuestType() == Network.GuestType.Shared) - && (areServicesSupportedByNetworkOffering(networkOfferingId, Service.SourceNat) || areServicesSupportedByNetworkOffering(networkOfferingId, Service.StaticNat) - || areServicesSupportedByNetworkOffering(networkOfferingId, Service.Firewall) - || areServicesSupportedByNetworkOffering(networkOfferingId, Service.PortForwarding) || areServicesSupportedByNetworkOffering(networkOfferingId, Service.Lb))) { + if ((networkOffering.getGuestType() == Network.GuestType.Shared) && (areServicesSupportedByNetworkOffering(networkOfferingId, Service.SourceNat) + || areServicesSupportedByNetworkOffering(networkOfferingId, Service.StaticNat) || areServicesSupportedByNetworkOffering(networkOfferingId, Service.Firewall) + || areServicesSupportedByNetworkOffering(networkOfferingId, Service.PortForwarding) || areServicesSupportedByNetworkOffering(networkOfferingId, Service.Lb))) { return true; } return false; @@ -1992,16 +1974,15 @@ public class NetworkServiceImpl extends ManagerBase implements NetworkService { } private boolean checkForNonStoppedVmInNetwork(long networkId) { - List vms = _userVmDao.listByNetworkIdAndStates(networkId, VirtualMachine.State.Starting, VirtualMachine.State.Running, VirtualMachine.State.Migrating, - VirtualMachine.State.Stopping); + List vms = _userVmDao.listByNetworkIdAndStates(networkId, VirtualMachine.State.Starting, VirtualMachine.State.Running, VirtualMachine.State.Migrating, VirtualMachine.State.Stopping); return vms.isEmpty(); } @Override @DB @ActionEvent(eventType = EventTypes.EVENT_NETWORK_UPDATE, eventDescription = "updating network", async = true) - public Network updateGuestNetwork(final long networkId, String name, String displayText, Account callerAccount, User callerUser, String domainSuffix, - final Long networkOfferingId, Boolean changeCidr, String guestVmCidr, Boolean displayNetwork, String customId, boolean updateInSequence, boolean forced) { + public Network updateGuestNetwork(final long networkId, String name, String displayText, Account callerAccount, User callerUser, String domainSuffix, final Long networkOfferingId, + Boolean changeCidr, String guestVmCidr, Boolean displayNetwork, String customId, boolean updateInSequence, boolean forced) { boolean restartNetwork = false; // verify input parameters @@ -2075,8 +2056,8 @@ public class NetworkServiceImpl extends ManagerBase implements NetworkService { // network offering should be in Enabled state if (networkOffering.getState() != NetworkOffering.State.Enabled) { - throwInvalidIdException("Network offering with specified id is not in " + NetworkOffering.State.Enabled - + " state, can't upgrade to it", networkOffering.getUuid(), "networkOfferingId"); + throwInvalidIdException("Network offering with specified id is not in " + NetworkOffering.State.Enabled + " state, can't upgrade to it", networkOffering.getUuid(), + "networkOfferingId"); } //can't update from vpc to non-vpc network offering boolean forVpcNew = _configMgr.isOfferingForVpc(networkOffering); @@ -2100,8 +2081,7 @@ public class NetworkServiceImpl extends ManagerBase implements NetworkService { } // check if the network is upgradable if (!canUpgrade(network, oldNetworkOfferingId, networkOfferingId)) { - throw new InvalidParameterValueException("Can't upgrade from network offering " + oldNtwkOff.getUuid() + " to " + networkOffering.getUuid() - + "; check logs for more information"); + throw new InvalidParameterValueException("Can't upgrade from network offering " + oldNtwkOff.getUuid() + " to " + networkOffering.getUuid() + "; check logs for more information"); } restartNetwork = true; networkOfferingChanged = true; @@ -2111,300 +2091,296 @@ public class NetworkServiceImpl extends ManagerBase implements NetworkService { } } - final Map newSvcProviders = networkOfferingChanged ? _networkMgr.finalizeServicesAndProvidersForNetwork( - _entityMgr.findById(NetworkOffering.class, networkOfferingId), network.getPhysicalNetworkId()) : new HashMap(); + final Map newSvcProviders = networkOfferingChanged + ? _networkMgr.finalizeServicesAndProvidersForNetwork(_entityMgr.findById(NetworkOffering.class, networkOfferingId), network.getPhysicalNetworkId()) + : new HashMap(); - // don't allow to modify network domain if the service is not supported - if (domainSuffix != null) { - // validate network domain - if (!NetUtils.verifyDomainName(domainSuffix)) { - 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 \"-\""); - } + // don't allow to modify network domain if the service is not supported + if (domainSuffix != null) { + // validate network domain + if (!NetUtils.verifyDomainName(domainSuffix)) { + 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 \"-\""); + } - long offeringId = oldNetworkOfferingId; - if (networkOfferingId != null) { - offeringId = networkOfferingId; - } + long offeringId = oldNetworkOfferingId; + if (networkOfferingId != null) { + offeringId = networkOfferingId; + } - Map dnsCapabilities = getNetworkOfferingServiceCapabilities(_entityMgr.findById(NetworkOffering.class, offeringId), Service.Dns); - String isUpdateDnsSupported = dnsCapabilities.get(Capability.AllowDnsSuffixModification); - if (isUpdateDnsSupported == null || !Boolean.valueOf(isUpdateDnsSupported)) { - // TBD: use uuid instead of networkOfferingId. May need to hardcode tablename in call to addProxyObject(). - throw new InvalidParameterValueException("Domain name change is not supported by the network offering id=" + networkOfferingId); - } + Map dnsCapabilities = getNetworkOfferingServiceCapabilities(_entityMgr.findById(NetworkOffering.class, offeringId), Service.Dns); + String isUpdateDnsSupported = dnsCapabilities.get(Capability.AllowDnsSuffixModification); + if (isUpdateDnsSupported == null || !Boolean.valueOf(isUpdateDnsSupported)) { + // TBD: use uuid instead of networkOfferingId. May need to hardcode tablename in call to addProxyObject(). + throw new InvalidParameterValueException("Domain name change is not supported by the network offering id=" + networkOfferingId); + } - network.setNetworkDomain(domainSuffix); - // have to restart the network - restartNetwork = true; - } - - //IP reservation checks - // allow reservation only to Isolated Guest networks - DataCenter dc = _dcDao.findById(network.getDataCenterId()); - String networkCidr = network.getNetworkCidr(); - - if (guestVmCidr != null) { - if (dc.getNetworkType() == NetworkType.Basic) { - throw new InvalidParameterValueException("Guest VM CIDR can't be specified for zone with " + NetworkType.Basic + " networking"); - } - if (network.getGuestType() != GuestType.Isolated) { - throw new InvalidParameterValueException("Can only allow IP Reservation in networks with guest type " + GuestType.Isolated); - } - if (networkOfferingChanged) { - throw new InvalidParameterValueException("Cannot specify this nework offering change and guestVmCidr at same time. Specify only one."); - } - if (!(network.getState() == Network.State.Implemented)) { - throw new InvalidParameterValueException("The network must be in " + Network.State.Implemented + " state. IP Reservation cannot be applied in " - + network.getState() + " state"); - } - if (!NetUtils.isValidIp4Cidr(guestVmCidr)) { - throw new InvalidParameterValueException("Invalid format of Guest VM CIDR."); - } - if (!NetUtils.validateGuestCidr(guestVmCidr)) { - throw new InvalidParameterValueException("Invalid format of Guest VM CIDR. Make sure it is RFC1918 compliant. "); - } - - // If networkCidr is null it implies that there was no prior IP reservation, so the network cidr is network.getCidr() - // But in case networkCidr is a non null value (IP reservation already exists), it implies network cidr is networkCidr - if (networkCidr != null) { - if (!NetUtils.isNetworkAWithinNetworkB(guestVmCidr, networkCidr)) { - throw new InvalidParameterValueException("Invalid value of Guest VM CIDR. For IP Reservation, Guest VM CIDR should be a subset of network CIDR : " - + networkCidr); + network.setNetworkDomain(domainSuffix); + // have to restart the network + restartNetwork = true; } - } else { - if (!NetUtils.isNetworkAWithinNetworkB(guestVmCidr, network.getCidr())) { - throw new InvalidParameterValueException("Invalid value of Guest VM CIDR. For IP Reservation, Guest VM CIDR should be a subset of network CIDR : " - + network.getCidr()); - } - } - // This check makes sure there are no active IPs existing outside the guestVmCidr in the network - String[] guestVmCidrPair = guestVmCidr.split("\\/"); - Long size = Long.valueOf(guestVmCidrPair[1]); - List nicsPresent = _nicDao.listByNetworkId(networkId); + //IP reservation checks + // allow reservation only to Isolated Guest networks + DataCenter dc = _dcDao.findById(network.getDataCenterId()); + String networkCidr = network.getNetworkCidr(); - String cidrIpRange[] = NetUtils.getIpRangeFromCidr(guestVmCidrPair[0], size); - s_logger.info("The start IP of the specified guest vm cidr is: " + cidrIpRange[0] + " and end IP is: " + cidrIpRange[1]); - long startIp = NetUtils.ip2Long(cidrIpRange[0]); - long endIp = NetUtils.ip2Long(cidrIpRange[1]); - long range = endIp - startIp + 1; - s_logger.info("The specified guest vm cidr has " + range + " IPs"); + if (guestVmCidr != null) { + if (dc.getNetworkType() == NetworkType.Basic) { + throw new InvalidParameterValueException("Guest VM CIDR can't be specified for zone with " + NetworkType.Basic + " networking"); + } + if (network.getGuestType() != GuestType.Isolated) { + throw new InvalidParameterValueException("Can only allow IP Reservation in networks with guest type " + GuestType.Isolated); + } + if (networkOfferingChanged) { + throw new InvalidParameterValueException("Cannot specify this nework offering change and guestVmCidr at same time. Specify only one."); + } + if (!(network.getState() == Network.State.Implemented)) { + throw new InvalidParameterValueException("The network must be in " + Network.State.Implemented + " state. IP Reservation cannot be applied in " + network.getState() + " state"); + } + if (!NetUtils.isValidIp4Cidr(guestVmCidr)) { + throw new InvalidParameterValueException("Invalid format of Guest VM CIDR."); + } + if (!NetUtils.validateGuestCidr(guestVmCidr)) { + throw new InvalidParameterValueException("Invalid format of Guest VM CIDR. Make sure it is RFC1918 compliant. "); + } - for (NicVO nic : nicsPresent) { - long nicIp = NetUtils.ip2Long(nic.getIPv4Address()); - //check if nic IP is outside the guest vm cidr - if ((nicIp < startIp || nicIp > endIp) && nic.getState() != Nic.State.Deallocating) { + // If networkCidr is null it implies that there was no prior IP reservation, so the network cidr is network.getCidr() + // But in case networkCidr is a non null value (IP reservation already exists), it implies network cidr is networkCidr + if (networkCidr != null) { + if (!NetUtils.isNetworkAWithinNetworkB(guestVmCidr, networkCidr)) { + throw new InvalidParameterValueException("Invalid value of Guest VM CIDR. For IP Reservation, Guest VM CIDR should be a subset of network CIDR : " + networkCidr); + } + } else { + if (!NetUtils.isNetworkAWithinNetworkB(guestVmCidr, network.getCidr())) { + throw new InvalidParameterValueException("Invalid value of Guest VM CIDR. For IP Reservation, Guest VM CIDR should be a subset of network CIDR : " + network.getCidr()); + } + } + + // This check makes sure there are no active IPs existing outside the guestVmCidr in the network + String[] guestVmCidrPair = guestVmCidr.split("\\/"); + Long size = Long.valueOf(guestVmCidrPair[1]); + List nicsPresent = _nicDao.listByNetworkId(networkId); + + String cidrIpRange[] = NetUtils.getIpRangeFromCidr(guestVmCidrPair[0], size); + s_logger.info("The start IP of the specified guest vm cidr is: " + cidrIpRange[0] + " and end IP is: " + cidrIpRange[1]); + long startIp = NetUtils.ip2Long(cidrIpRange[0]); + long endIp = NetUtils.ip2Long(cidrIpRange[1]); + long range = endIp - startIp + 1; + s_logger.info("The specified guest vm cidr has " + range + " IPs"); + + for (NicVO nic : nicsPresent) { + long nicIp = NetUtils.ip2Long(nic.getIPv4Address()); + //check if nic IP is outside the guest vm cidr + if ((nicIp < startIp || nicIp > endIp) && nic.getState() != Nic.State.Deallocating) { throw new InvalidParameterValueException("Active IPs like " + nic.getIPv4Address() + " exist outside the Guest VM CIDR. Cannot apply reservation "); + } } - } - // In some scenarios even though guesVmCidr and network CIDR do not appear similar but - // the IP ranges exactly matches, in these special cases make sure no Reservation gets applied - if (network.getNetworkCidr() == null) { - if (NetUtils.isSameIpRange(guestVmCidr, network.getCidr()) && !guestVmCidr.equals(network.getCidr())) { - throw new InvalidParameterValueException("The Start IP and End IP of guestvmcidr: " + guestVmCidr + " and CIDR: " + network.getCidr() + " are same, " - + "even though both the cidrs appear to be different. As a precaution no IP Reservation will be applied."); + // In some scenarios even though guesVmCidr and network CIDR do not appear similar but + // the IP ranges exactly matches, in these special cases make sure no Reservation gets applied + if (network.getNetworkCidr() == null) { + if (NetUtils.isSameIpRange(guestVmCidr, network.getCidr()) && !guestVmCidr.equals(network.getCidr())) { + throw new InvalidParameterValueException("The Start IP and End IP of guestvmcidr: " + guestVmCidr + " and CIDR: " + network.getCidr() + " are same, " + + "even though both the cidrs appear to be different. As a precaution no IP Reservation will be applied."); + } + } else { + if (NetUtils.isSameIpRange(guestVmCidr, network.getNetworkCidr()) && !guestVmCidr.equals(network.getNetworkCidr())) { + throw new InvalidParameterValueException("The Start IP and End IP of guestvmcidr: " + guestVmCidr + " and Network CIDR: " + network.getNetworkCidr() + " are same, " + + "even though both the cidrs appear to be different. As a precaution IP Reservation will not be affected. If you want to reset IP Reservation, " + + "specify guestVmCidr to be: " + network.getNetworkCidr()); + } } - } else { - if (NetUtils.isSameIpRange(guestVmCidr, network.getNetworkCidr()) && !guestVmCidr.equals(network.getNetworkCidr())) { - throw new InvalidParameterValueException("The Start IP and End IP of guestvmcidr: " + guestVmCidr + " and Network CIDR: " + network.getNetworkCidr() - + " are same, " - + "even though both the cidrs appear to be different. As a precaution IP Reservation will not be affected. If you want to reset IP Reservation, " - + "specify guestVmCidr to be: " + network.getNetworkCidr()); + + // When reservation is applied for the first time, network_cidr will be null + // Populate it with the actual network cidr + if (network.getNetworkCidr() == null) { + network.setNetworkCidr(network.getCidr()); } + + // Condition for IP Reservation reset : guestVmCidr and network CIDR are same + if (network.getNetworkCidr().equals(guestVmCidr)) { + s_logger.warn("Guest VM CIDR and Network CIDR both are same, reservation will reset."); + network.setNetworkCidr(null); + } + // Finally update "cidr" with the guestVmCidr + // which becomes the effective address space for CloudStack guest VMs + network.setCidr(guestVmCidr); + _networksDao.update(networkId, network); + s_logger.info("IP Reservation has been applied. The new CIDR for Guests Vms is " + guestVmCidr); } - // When reservation is applied for the first time, network_cidr will be null - // Populate it with the actual network cidr - if (network.getNetworkCidr() == null) { - network.setNetworkCidr(network.getCidr()); + ReservationContext context = new ReservationContextImpl(null, null, callerUser, callerAccount); + // 1) Shutdown all the elements and cleanup all the rules. Don't allow to shutdown network in intermediate + // states - Shutdown and Implementing + int resourceCount = 1; + if (updateInSequence && restartNetwork && _networkOfferingDao.findById(network.getNetworkOfferingId()).isRedundantRouter() + && (networkOfferingId == null || _networkOfferingDao.findById(networkOfferingId).isRedundantRouter()) && network.getVpcId() == null) { + _networkMgr.canUpdateInSequence(network, forced); + NetworkDetailVO networkDetail = new NetworkDetailVO(network.getId(), Network.updatingInSequence, "true", true); + _networkDetailsDao.persist(networkDetail); + _networkMgr.configureUpdateInSequence(network); + resourceCount = _networkMgr.getResourceCount(network); + } + List servicesNotInNewOffering = null; + if (networkOfferingId != null) { + servicesNotInNewOffering = _networkMgr.getServicesNotSupportedInNewOffering(network, networkOfferingId); + } + if (!forced && servicesNotInNewOffering != null && !servicesNotInNewOffering.isEmpty()) { + NetworkOfferingVO newOffering = _networkOfferingDao.findById(networkOfferingId); + throw new CloudRuntimeException("The new offering:" + newOffering.getUniqueName() + " will remove the following services " + servicesNotInNewOffering + + "along with all the related configuration currently in use. will not proceed with the network update." + "set forced parameter to true for forcing an update."); + } + try { + if (servicesNotInNewOffering != null && !servicesNotInNewOffering.isEmpty()) { + _networkMgr.cleanupConfigForServicesInNetwork(servicesNotInNewOffering, network); + } + } catch (Throwable e) { + s_logger.debug("failed to cleanup config related to unused services error:" + e.getMessage()); } - // Condition for IP Reservation reset : guestVmCidr and network CIDR are same - if (network.getNetworkCidr().equals(guestVmCidr)) { - s_logger.warn("Guest VM CIDR and Network CIDR both are same, reservation will reset."); - network.setNetworkCidr(null); - } - // Finally update "cidr" with the guestVmCidr - // which becomes the effective address space for CloudStack guest VMs - network.setCidr(guestVmCidr); - _networksDao.update(networkId, network); - s_logger.info("IP Reservation has been applied. The new CIDR for Guests Vms is " + guestVmCidr); - } + boolean validStateToShutdown = (network.getState() == Network.State.Implemented || network.getState() == Network.State.Setup || network.getState() == Network.State.Allocated); + try { - ReservationContext context = new ReservationContextImpl(null, null, callerUser, callerAccount); - // 1) Shutdown all the elements and cleanup all the rules. Don't allow to shutdown network in intermediate - // states - Shutdown and Implementing - int resourceCount=1; - if (updateInSequence && restartNetwork && _networkOfferingDao.findById(network.getNetworkOfferingId()).isRedundantRouter() - && (networkOfferingId==null || _networkOfferingDao.findById(networkOfferingId).isRedundantRouter()) && network.getVpcId()==null) { - _networkMgr.canUpdateInSequence(network, forced); - NetworkDetailVO networkDetail =new NetworkDetailVO(network.getId(),Network.updatingInSequence,"true",true); - _networkDetailsDao.persist(networkDetail); - _networkMgr.configureUpdateInSequence(network); - resourceCount=_networkMgr.getResourceCount(network); - } - List servicesNotInNewOffering = null; - if (networkOfferingId != null) { - servicesNotInNewOffering = _networkMgr.getServicesNotSupportedInNewOffering(network, networkOfferingId); - } - if (!forced && servicesNotInNewOffering != null && !servicesNotInNewOffering.isEmpty()) { - NetworkOfferingVO newOffering = _networkOfferingDao.findById(networkOfferingId); - throw new CloudRuntimeException("The new offering:"+newOffering.getUniqueName() - +" will remove the following services "+servicesNotInNewOffering +"along with all the related configuration currently in use. will not proceed with the network update." + - "set forced parameter to true for forcing an update."); - } - try { - if (servicesNotInNewOffering!=null && !servicesNotInNewOffering.isEmpty()) { - _networkMgr.cleanupConfigForServicesInNetwork(servicesNotInNewOffering,network); - } - } catch (Throwable e) { - s_logger.debug("failed to cleanup config related to unused services error:"+e.getMessage()); - } + do { + if (restartNetwork) { + if (validStateToShutdown) { + if (!changeCidr) { + s_logger.debug("Shutting down elements and resources for network id=" + networkId + " as a part of network update"); - boolean validStateToShutdown = (network.getState() == Network.State.Implemented || network.getState() == Network.State.Setup || network.getState() == Network.State.Allocated); - try { + if (!_networkMgr.shutdownNetworkElementsAndResources(context, true, network)) { + s_logger.warn("Failed to shutdown the network elements and resources as a part of network restart: " + network); + CloudRuntimeException ex = new CloudRuntimeException("Failed to shutdown the network elements and resources as a part of update to network of specified id"); + ex.addProxyObject(network.getUuid(), "networkId"); + throw ex; + } + } else { + // We need to shutdown the network, since we want to re-implement the network. + s_logger.debug("Shutting down network id=" + networkId + " as a part of network update"); - do { - if (restartNetwork) { - if (validStateToShutdown) { - if (!changeCidr) { - s_logger.debug("Shutting down elements and resources for network id=" + networkId + " as a part of network update"); + //check if network has reservation + if (NetUtils.isNetworkAWithinNetworkB(network.getCidr(), network.getNetworkCidr())) { + s_logger.warn( + "Existing IP reservation will become ineffective for the network with id = " + networkId + " You need to reapply reservation after network reimplementation."); + //set cidr to the newtork cidr + network.setCidr(network.getNetworkCidr()); + //set networkCidr to null to bring network back to no IP reservation state + network.setNetworkCidr(null); + } - if (!_networkMgr.shutdownNetworkElementsAndResources(context, true, network)) { - s_logger.warn("Failed to shutdown the network elements and resources as a part of network restart: " + network); - CloudRuntimeException ex = new CloudRuntimeException("Failed to shutdown the network elements and resources as a part of update to network of specified id"); + if (!_networkMgr.shutdownNetwork(network.getId(), context, true)) { + s_logger.warn("Failed to shutdown the network as a part of update to network with specified id"); + CloudRuntimeException ex = new CloudRuntimeException("Failed to shutdown the network as a part of update of specified network id"); + ex.addProxyObject(network.getUuid(), "networkId"); + throw ex; + } + } + } else { + CloudRuntimeException ex = new CloudRuntimeException( + "Failed to shutdown the network elements and resources as a part of update to network with specified id; network is in wrong state: " + network.getState()); ex.addProxyObject(network.getUuid(), "networkId"); throw ex; } + } + + // 2) Only after all the elements and rules are shutdown properly, update the network VO + // get updated network + Network.State networkState = _networksDao.findById(networkId).getState(); + boolean validStateToImplement = (networkState == Network.State.Implemented || networkState == Network.State.Setup || networkState == Network.State.Allocated); + if (restartNetwork && !validStateToImplement) { + CloudRuntimeException ex = new CloudRuntimeException( + "Failed to implement the network elements and resources as a part of update to network with specified id; network is in wrong state: " + networkState); + ex.addProxyObject(network.getUuid(), "networkId"); + throw ex; + } + + if (networkOfferingId != null) { + if (networkOfferingChanged) { + Transaction.execute(new TransactionCallbackNoReturn() { + @Override + public void doInTransactionWithoutResult(TransactionStatus status) { + network.setNetworkOfferingId(networkOfferingId); + _networksDao.update(networkId, network, newSvcProviders); + // get all nics using this network + // log remove usage events for old offering + // log assign usage events for new offering + List nics = _nicDao.listByNetworkId(networkId); + for (NicVO nic : nics) { + long vmId = nic.getInstanceId(); + VMInstanceVO vm = _vmDao.findById(vmId); + if (vm == null) { + s_logger.error("Vm for nic " + nic.getId() + " not found with Vm Id:" + vmId); + continue; + } + long isDefault = (nic.isDefaultNic()) ? 1 : 0; + String nicIdString = Long.toString(nic.getId()); + UsageEventUtils.publishUsageEvent(EventTypes.EVENT_NETWORK_OFFERING_REMOVE, vm.getAccountId(), vm.getDataCenterId(), vm.getId(), nicIdString, oldNetworkOfferingId, + null, isDefault, VirtualMachine.class.getName(), vm.getUuid(), vm.isDisplay()); + UsageEventUtils.publishUsageEvent(EventTypes.EVENT_NETWORK_OFFERING_ASSIGN, vm.getAccountId(), vm.getDataCenterId(), vm.getId(), nicIdString, networkOfferingId, + null, isDefault, VirtualMachine.class.getName(), vm.getUuid(), vm.isDisplay()); + } + } + }); + } else { + network.setNetworkOfferingId(networkOfferingId); + _networksDao.update(networkId, network, + _networkMgr.finalizeServicesAndProvidersForNetwork(_entityMgr.findById(NetworkOffering.class, networkOfferingId), network.getPhysicalNetworkId())); + } } else { - // We need to shutdown the network, since we want to re-implement the network. - s_logger.debug("Shutting down network id=" + networkId + " as a part of network update"); - - //check if network has reservation - if (NetUtils.isNetworkAWithinNetworkB(network.getCidr(), network.getNetworkCidr())) { - s_logger.warn("Existing IP reservation will become ineffective for the network with id = " + networkId - + " You need to reapply reservation after network reimplementation."); - //set cidr to the newtork cidr - network.setCidr(network.getNetworkCidr()); - //set networkCidr to null to bring network back to no IP reservation state - network.setNetworkCidr(null); - } - - if (!_networkMgr.shutdownNetwork(network.getId(), context, true)) { - s_logger.warn("Failed to shutdown the network as a part of update to network with specified id"); - CloudRuntimeException ex = new CloudRuntimeException("Failed to shutdown the network as a part of update of specified network id"); - ex.addProxyObject(network.getUuid(), "networkId"); - throw ex; - } + _networksDao.update(networkId, network); } - } else { - CloudRuntimeException ex = new CloudRuntimeException( - "Failed to shutdown the network elements and resources as a part of update to network with specified id; network is in wrong state: " + network.getState()); - ex.addProxyObject(network.getUuid(), "networkId"); - throw ex; - } - } - // 2) Only after all the elements and rules are shutdown properly, update the network VO - // get updated network - Network.State networkState = _networksDao.findById(networkId).getState(); - boolean validStateToImplement = (networkState == Network.State.Implemented || networkState == Network.State.Setup || networkState == Network.State.Allocated); - if (restartNetwork && !validStateToImplement) { - CloudRuntimeException ex = new CloudRuntimeException( - "Failed to implement the network elements and resources as a part of update to network with specified id; network is in wrong state: " + networkState); - ex.addProxyObject(network.getUuid(), "networkId"); - throw ex; - } - - if (networkOfferingId != null) { - if (networkOfferingChanged) { - Transaction.execute(new TransactionCallbackNoReturn() { - @Override - public void doInTransactionWithoutResult(TransactionStatus status) { - network.setNetworkOfferingId(networkOfferingId); - _networksDao.update(networkId, network, newSvcProviders); - // get all nics using this network - // log remove usage events for old offering - // log assign usage events for new offering - List nics = _nicDao.listByNetworkId(networkId); - for (NicVO nic : nics) { - long vmId = nic.getInstanceId(); - VMInstanceVO vm = _vmDao.findById(vmId); - if (vm == null) { - s_logger.error("Vm for nic " + nic.getId() + " not found with Vm Id:" + vmId); - continue; + // 3) Implement the elements and rules again + if (restartNetwork) { + if (network.getState() != Network.State.Allocated) { + DeployDestination dest = new DeployDestination(_dcDao.findById(network.getDataCenterId()), null, null, null); + s_logger.debug("Implementing the network " + network + " elements and resources as a part of network update"); + try { + if (!changeCidr) { + _networkMgr.implementNetworkElementsAndResources(dest, context, network, _networkOfferingDao.findById(network.getNetworkOfferingId())); + } else { + _networkMgr.implementNetwork(network.getId(), dest, context); } - long isDefault = (nic.isDefaultNic()) ? 1 : 0; - String nicIdString = Long.toString(nic.getId()); - UsageEventUtils.publishUsageEvent(EventTypes.EVENT_NETWORK_OFFERING_REMOVE, vm.getAccountId(), vm.getDataCenterId(), vm.getId(), nicIdString, - oldNetworkOfferingId, null, isDefault, VirtualMachine.class.getName(), vm.getUuid(), vm.isDisplay()); - UsageEventUtils.publishUsageEvent(EventTypes.EVENT_NETWORK_OFFERING_ASSIGN, vm.getAccountId(), vm.getDataCenterId(), vm.getId(), nicIdString, - networkOfferingId, null, isDefault, VirtualMachine.class.getName(), vm.getUuid(), vm.isDisplay()); + } catch (Exception ex) { + s_logger.warn("Failed to implement network " + network + " elements and resources as a part of network update due to ", ex); + CloudRuntimeException e = new CloudRuntimeException("Failed to implement network (with specified id) elements and resources as a part of network update"); + e.addProxyObject(network.getUuid(), "networkId"); + throw e; } } - }); - } else { - network.setNetworkOfferingId(networkOfferingId); - _networksDao.update(networkId, network, - _networkMgr.finalizeServicesAndProvidersForNetwork(_entityMgr.findById(NetworkOffering.class, networkOfferingId), network.getPhysicalNetworkId())); - } - } else { - _networksDao.update(networkId, network); - } + } - // 3) Implement the elements and rules again - if (restartNetwork) { - if (network.getState() != Network.State.Allocated) { - DeployDestination dest = new DeployDestination(_dcDao.findById(network.getDataCenterId()), null, null, null); - s_logger.debug("Implementing the network " + network + " elements and resources as a part of network update"); - try { - if (!changeCidr) { - _networkMgr.implementNetworkElementsAndResources(dest, context, network, _networkOfferingDao.findById(network.getNetworkOfferingId())); - } else { - _networkMgr.implementNetwork(network.getId(), dest, context); + // 4) if network has been upgraded from a non persistent ntwk offering to a persistent ntwk offering, + // implement the network if its not already + if (networkOfferingChanged && !oldNtwkOff.isPersistent() && networkOffering.isPersistent()) { + if (network.getState() == Network.State.Allocated) { + try { + DeployDestination dest = new DeployDestination(_dcDao.findById(network.getDataCenterId()), null, null, null); + _networkMgr.implementNetwork(network.getId(), dest, context); + } catch (Exception ex) { + s_logger.warn("Failed to implement network " + network + " elements and resources as a part o" + "f network update due to ", ex); + CloudRuntimeException e = new CloudRuntimeException("Failed to implement network (with specified" + " id) elements and resources as a part of network update"); + e.addProxyObject(network.getUuid(), "networkId"); + throw e; + } } - } catch (Exception ex) { - s_logger.warn("Failed to implement network " + network + " elements and resources as a part of network update due to ", ex); - CloudRuntimeException e = new CloudRuntimeException("Failed to implement network (with specified id) elements and resources as a part of network update"); - e.addProxyObject(network.getUuid(), "networkId"); - throw e; + } + resourceCount--; + } while (updateInSequence && resourceCount > 0); + } catch (Exception exception) { + if (updateInSequence) { + _networkMgr.finalizeUpdateInSequence(network, false); + } + throw new CloudRuntimeException("failed to update network " + network.getUuid() + " due to " + exception.getMessage()); + } finally { + if (updateInSequence) { + if (_networkDetailsDao.findDetail(networkId, Network.updatingInSequence) != null) { + _networkDetailsDao.removeDetail(networkId, Network.updatingInSequence); } } } - - // 4) if network has been upgraded from a non persistent ntwk offering to a persistent ntwk offering, - // implement the network if its not already - if (networkOfferingChanged && !oldNtwkOff.isPersistent() && networkOffering.isPersistent()) { - if (network.getState() == Network.State.Allocated) { - try { - DeployDestination dest = new DeployDestination(_dcDao.findById(network.getDataCenterId()), null, null, null); - _networkMgr.implementNetwork(network.getId(), dest, context); - } catch (Exception ex) { - s_logger.warn("Failed to implement network " + network + " elements and resources as a part o" + "f network update due to ", ex); - CloudRuntimeException e = new CloudRuntimeException("Failed to implement network (with specified" + " id) elements and resources as a part of network update"); - e.addProxyObject(network.getUuid(), "networkId"); - throw e; - } - } - } - resourceCount--; - } while (updateInSequence && resourceCount>0); - } catch (Exception exception) { - if (updateInSequence) { - _networkMgr.finalizeUpdateInSequence(network, false); - } - throw new CloudRuntimeException("failed to update network "+network.getUuid()+" due to "+exception.getMessage()); - } finally { - if (updateInSequence) { - if( _networkDetailsDao.findDetail(networkId,Network.updatingInSequence)!=null){ - _networkDetailsDao.removeDetail(networkId,Network.updatingInSequence); - } - } - } - return getNetwork(network.getId()); + return getNetwork(network.getId()); } @Override @@ -2463,7 +2439,8 @@ public class NetworkServiceImpl extends ManagerBase implements NetworkService { } } - private Network migrateNetworkToPhysicalNetwork(Network network, NetworkOffering oldNtwkOff, NetworkOffering newNtwkOff, Long oldVpcId, Long newVpcId, long newPhysicalNetworkId, Account callerAccount, User callerUser) { + private Network migrateNetworkToPhysicalNetwork(Network network, NetworkOffering oldNtwkOff, NetworkOffering newNtwkOff, Long oldVpcId, Long newVpcId, long newPhysicalNetworkId, + Account callerAccount, User callerUser) { boolean resume = network.getRelated() != network.getId(); NetworkCopy networkCopy; @@ -2479,9 +2456,7 @@ public class NetworkServiceImpl extends ManagerBase implements NetworkService { throw new InvalidParameterValueException("Failed to resume migrating network as network offering does not match previously specified network offering (" + newNtwkOff.getUuid() + ")"); } } else { - networkCopy = Transaction.execute( - (TransactionCallback) - (status) -> migrateNetworkInDb(network, oldNtwkOff, newNtwkOff, oldVpcId, newVpcId, newPhysicalNetworkId)); + networkCopy = Transaction.execute((TransactionCallback)(status) -> migrateNetworkInDb(network, oldNtwkOff, newNtwkOff, oldVpcId, newVpcId, newPhysicalNetworkId)); } Long networkIdInOldPhysicalNet = networkCopy.getNetworkIdInOldPhysicalNet(); @@ -2491,16 +2466,13 @@ public class NetworkServiceImpl extends ManagerBase implements NetworkService { DataCenter zone = _dcDao.findById(network.getDataCenterId()); NetworkVO networkInOldPhysNet = _networksDao.findById(networkIdInOldPhysicalNet); - boolean shouldImplement = (newNtwkOff.isPersistent() - || networkInOldPhysNet.getState() == Network.State.Implemented) - && networkInNewPhysicalNet.getState() != Network.State.Implemented; + boolean shouldImplement = (newNtwkOff.isPersistent() || networkInOldPhysNet.getState() == Network.State.Implemented) && networkInNewPhysicalNet.getState() != Network.State.Implemented; if (shouldImplement) { DeployDestination dest = new DeployDestination(zone, null, null, null); s_logger.debug("Implementing the network " + network + " elements and resources as a part of network update"); try { - networkInNewPhysicalNet = _networkMgr.implementNetwork(networkInNewPhysicalNet.getId(), dest, context) - .second(); + networkInNewPhysicalNet = _networkMgr.implementNetwork(networkInNewPhysicalNet.getId(), dest, context).second(); } catch (Exception ex) { s_logger.warn("Failed to implement network " + network + " elements and resources as a part of network update due to ", ex); CloudRuntimeException e = new CloudRuntimeException("Failed to implement network (with specified id) elements and resources as a part of network update"); @@ -2520,7 +2492,7 @@ public class NetworkServiceImpl extends ManagerBase implements NetworkService { //The copy will be the network in the old physical network //And we will use it to store tmp data while we upgrade or original network to the new physical network Long networkIdInOldPhysicalNet = _networkMigrationManager.makeCopyOfNetwork(network, oldNtwkOff, oldVpcId); - Network networkInNewPhysicalNet = _networkMigrationManager.upgradeNetworkToNewNetworkOffering(network.getId(), newPhysicalNetworkId,newNtwkOff.getId(), newVpcId); + Network networkInNewPhysicalNet = _networkMigrationManager.upgradeNetworkToNewNetworkOffering(network.getId(), newPhysicalNetworkId, newNtwkOff.getId(), newVpcId); return new NetworkCopy(networkIdInOldPhysicalNet, networkInNewPhysicalNet); } @@ -2611,8 +2583,7 @@ public class NetworkServiceImpl extends ManagerBase implements NetworkService { } if (networkOfferingUuid == null) { - throwInvalidIdException("Failed to migrate VPC as the specified tierNetworkOfferings is not complete", - String.valueOf(network.getUuid()), "networkUuid"); + throwInvalidIdException("Failed to migrate VPC as the specified tierNetworkOfferings is not complete", String.valueOf(network.getUuid()), "networkUuid"); } NetworkOfferingVO newNtwkOff = _networkOfferingDao.findByUuid(networkOfferingUuid); @@ -2622,7 +2593,8 @@ public class NetworkServiceImpl extends ManagerBase implements NetworkService { } if (!_configMgr.isOfferingForVpc(newNtwkOff)) { - throw new InvalidParameterValueException("Network offering " + newNtwkOff.getName() + " ("+ newNtwkOff.getUuid() +") can't be used for VPC networks for network " + network.getName() + "(" + network.getUuid() + ")"); + throw new InvalidParameterValueException( + "Network offering " + newNtwkOff.getName() + " (" + newNtwkOff.getUuid() + ") can't be used for VPC networks for network " + network.getName() + "(" + network.getUuid() + ")"); } verifyNetworkCanBeMigrated(account, network); @@ -2646,8 +2618,7 @@ public class NetworkServiceImpl extends ManagerBase implements NetworkService { String tierNetworkOfferingUuid = networkToOffering.get(tier.getUuid()); if (!StringUtils.isNotBlank(tierNetworkOfferingUuid)) { - throwInvalidIdException("Failed to resume migrating VPC as the specified tierNetworkOfferings is not complete", - String.valueOf(tier.getUuid()), "networkUuid"); + throwInvalidIdException("Failed to resume migrating VPC as the specified tierNetworkOfferings is not complete", String.valueOf(tier.getUuid()), "networkUuid"); } NetworkOfferingVO newNetworkOffering = _networkOfferingDao.findByUuid(tierNetworkOfferingUuid); @@ -2657,12 +2628,13 @@ public class NetworkServiceImpl extends ManagerBase implements NetworkService { if (newNetworkOffering.getId() != tier.getNetworkOfferingId()) { NetworkOfferingVO tierNetworkOffering = _networkOfferingDao.findById(tier.getNetworkOfferingId()); - throw new InvalidParameterValueException("Failed to resume migrating VPC as at least one network offering in tierNetworkOfferings does not match previously specified network offering (network uuid=" + tier.getUuid() + " was previously specified with offering uuid=" + tierNetworkOffering.getUuid() + ")"); + throw new InvalidParameterValueException( + "Failed to resume migrating VPC as at least one network offering in tierNetworkOfferings does not match previously specified network offering (network uuid=" + tier.getUuid() + + " was previously specified with offering uuid=" + tierNetworkOffering.getUuid() + ")"); } } } - private void throwInvalidIdException(String message, String uuid, String description) { InvalidParameterValueException ex = new InvalidParameterValueException(message); ex.addProxyObject(uuid, description); @@ -2680,10 +2652,8 @@ public class NetworkServiceImpl extends ManagerBase implements NetworkService { } if (newNtwkOff.getId() != oldNtwkOff.getId() || network.getId() != network.getRelated()) { - Collection newProviders = _networkMgr.finalizeServicesAndProvidersForNetwork(newNtwkOff, newPhysicalNetworkId) - .values(); - Collection oldProviders = _networkMgr.finalizeServicesAndProvidersForNetwork(oldNtwkOff, network.getPhysicalNetworkId()) - .values(); + Collection newProviders = _networkMgr.finalizeServicesAndProvidersForNetwork(newNtwkOff, newPhysicalNetworkId).values(); + Collection oldProviders = _networkMgr.finalizeServicesAndProvidersForNetwork(oldNtwkOff, network.getPhysicalNetworkId()).values(); if (providersConfiguredForExternalNetworking(newProviders) != providersConfiguredForExternalNetworking(oldProviders)) { throw new InvalidParameterValueException("Updating network failed since guest CIDR needs to be changed!"); @@ -2691,13 +2661,11 @@ public class NetworkServiceImpl extends ManagerBase implements NetworkService { // check if the network is moveable if (!canMoveToPhysicalNetwork(network, oldNtwkOff.getId(), newNtwkOff.getId())) { - throw new InvalidParameterValueException( - "Can't upgrade from network offering " + oldNtwkOff.getUuid() + " to " + newNtwkOff.getUuid() + "; check logs for more information"); + throw new InvalidParameterValueException("Can't upgrade from network offering " + oldNtwkOff.getUuid() + " to " + newNtwkOff.getUuid() + "; check logs for more information"); } List vmInstances = _vmDao.listNonRemovedVmsByTypeAndNetwork(network.getId(), null); - boolean vmStateIsNotTransitioning = vmInstances.stream() - .anyMatch(vm -> vm.getState() != VirtualMachine.State.Stopped && vm.getState() != VirtualMachine.State.Running); + boolean vmStateIsNotTransitioning = vmInstances.stream().anyMatch(vm -> vm.getState() != VirtualMachine.State.Stopped && vm.getState() != VirtualMachine.State.Running); if (vmStateIsNotTransitioning) { throw new CloudRuntimeException("Failed to migrate network as at least one VM is not in running or stopped state."); } @@ -2726,9 +2694,7 @@ public class NetworkServiceImpl extends ManagerBase implements NetworkService { _accountMgr.checkAccess(callerAccount, null, true, network); - boolean validateNetworkReadyToMigrate = (network.getState() == Network.State.Implemented - || network.getState() == Network.State.Setup - || network.getState() == Network.State.Allocated); + boolean validateNetworkReadyToMigrate = (network.getState() == Network.State.Implemented || network.getState() == Network.State.Setup || network.getState() == Network.State.Allocated); if (!validateNetworkReadyToMigrate) { s_logger.error("Failed to migrate network as it is in invalid state."); CloudRuntimeException ex = new CloudRuntimeException("Failed to migrate network as it is in invalid state."); @@ -2818,14 +2784,14 @@ public class NetworkServiceImpl extends ManagerBase implements NetworkService { return false; } - return canMoveToPhysicalNetwork(network, oldNetworkOfferingId, newNetworkOfferingId); + return canMoveToPhysicalNetwork(network, oldNetworkOfferingId, newNetworkOfferingId); } @Override @DB @ActionEvent(eventType = EventTypes.EVENT_PHYSICAL_NETWORK_CREATE, eventDescription = "Creating Physical Network", create = true) - public PhysicalNetwork createPhysicalNetwork(final Long zoneId, final String vnetRange, final String networkSpeed, final List isolationMethods, - String broadcastDomainRangeStr, final Long domainId, final List tags, final String name) { + public PhysicalNetwork createPhysicalNetwork(final Long zoneId, final String vnetRange, final String networkSpeed, final List isolationMethods, String broadcastDomainRangeStr, + final Long domainId, final List tags, final String name) { // Check if zone exists if (zoneId == null) { @@ -2861,8 +2827,8 @@ public class NetworkServiceImpl extends ManagerBase implements NetworkService { if (vnetRange != null) { // Verify zone type if (zoneType == NetworkType.Basic || (zoneType == NetworkType.Advanced && zone.isSecurityGroupEnabled())) { - throw new InvalidParameterValueException("Can't add vnet range to the physical network in the zone that supports " + zoneType - + " network, Security Group enabled: " + zone.isSecurityGroupEnabled()); + throw new InvalidParameterValueException( + "Can't add vnet range to the physical network in the zone that supports " + zoneType + " network, Security Group enabled: " + zone.isSecurityGroupEnabled()); } } @@ -2895,41 +2861,42 @@ public class NetworkServiceImpl extends ManagerBase implements NetworkService { return Transaction.execute(new TransactionCallback() { @Override public PhysicalNetworkVO doInTransaction(TransactionStatus status) { - // Create the new physical network in the database - long id = _physicalNetworkDao.getNextInSequence(Long.class, "id"); + // Create the new physical network in the database + long id = _physicalNetworkDao.getNextInSequence(Long.class, "id"); PhysicalNetworkVO pNetwork = new PhysicalNetworkVO(id, zoneId, vnetRange, networkSpeed, domainId, broadcastDomainRangeFinal, name); - pNetwork.setTags(tags); - pNetwork.setIsolationMethods(isolationMethods); + pNetwork.setTags(tags); + pNetwork.setIsolationMethods(isolationMethods); - pNetwork = _physicalNetworkDao.persist(pNetwork); + pNetwork = _physicalNetworkDao.persist(pNetwork); - // Add vnet entries for the new zone if zone type is Advanced - if (vnetRange != null) { - addOrRemoveVnets(vnetRange.split(","), pNetwork); - } + // Add vnet entries for the new zone if zone type is Advanced + if (vnetRange != null) { + addOrRemoveVnets(vnetRange.split(","), pNetwork); + } - // add VirtualRouter as the default network service provider - addDefaultVirtualRouterToPhysicalNetwork(pNetwork.getId()); + // add VirtualRouter as the default network service provider + addDefaultVirtualRouterToPhysicalNetwork(pNetwork.getId()); - if (pNetwork.getIsolationMethods().contains("GRE")) + if (pNetwork.getIsolationMethods().contains("GRE")) { addDefaultOvsToPhysicalNetwork(pNetwork.getId()); + } - // add security group provider to the physical network - addDefaultSecurityGroupProviderToPhysicalNetwork(pNetwork.getId()); + // add security group provider to the physical network + addDefaultSecurityGroupProviderToPhysicalNetwork(pNetwork.getId()); - // add VPCVirtualRouter as the defualt network service provider - addDefaultVpcVirtualRouterToPhysicalNetwork(pNetwork.getId()); + // add VPCVirtualRouter as the defualt network service provider + addDefaultVpcVirtualRouterToPhysicalNetwork(pNetwork.getId()); - // add baremetal as the defualt network service provider - addDefaultBaremetalProvidersToPhysicalNetwork(pNetwork.getId()); + // add baremetal as the defualt network service provider + addDefaultBaremetalProvidersToPhysicalNetwork(pNetwork.getId()); - //Add Internal Load Balancer element as a default network service provider - addDefaultInternalLbProviderToPhysicalNetwork(pNetwork.getId()); + //Add Internal Load Balancer element as a default network service provider + addDefaultInternalLbProviderToPhysicalNetwork(pNetwork.getId()); - // Add the config drive provider - addConfigDriveToPhysicalNetwork(pNetwork.getId()); + // Add the config drive provider + addConfigDriveToPhysicalNetwork(pNetwork.getId()); - return pNetwork; + return pNetwork; } }); } catch (Exception ex) { @@ -2955,7 +2922,7 @@ public class NetworkServiceImpl extends ManagerBase implements NetworkService { sc.addAnd("name", SearchCriteria.Op.LIKE, "%" + name + "%"); } - Pair, Integer> result = _physicalNetworkDao.searchAndCount(sc, searchFilter); + Pair, Integer> result = _physicalNetworkDao.searchAndCount(sc, searchFilter); return new Pair, Integer>(result.first(), result.second()); } @@ -2977,8 +2944,8 @@ public class NetworkServiceImpl extends ManagerBase implements NetworkService { } if (newVnetRange != 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()); + 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()); } } @@ -3018,7 +2985,7 @@ public class NetworkServiceImpl extends ManagerBase implements NetworkService { @DB public void addOrRemoveVnets(String[] listOfRanges, final PhysicalNetworkVO network) { - List addVnets = null; + List addVnets = null; List removeVnets = null; HashSet tempVnets = new HashSet(); HashSet vnetsInDb = new HashSet(); @@ -3066,18 +3033,18 @@ public class NetworkServiceImpl extends ManagerBase implements NetworkService { @Override public void doInTransactionWithoutResult(TransactionStatus status) { if (addVnetsFinal != null) { - s_logger.debug("Adding vnet range " + addVnetsFinal.toString() + " for the physicalNetwork id= " + network.getId() + " and zone id=" - + network.getDataCenterId() + " as a part of updatePhysicalNetwork call"); - //add vnet takes a list of strings to be added. each string is a vnet. + s_logger.debug("Adding vnet range " + addVnetsFinal.toString() + " for the physicalNetwork id= " + network.getId() + " and zone id=" + network.getDataCenterId() + + " as a part of updatePhysicalNetwork call"); + //add vnet takes a list of strings to be added. each string is a vnet. _dcDao.addVnet(network.getDataCenterId(), network.getId(), addVnetsFinal); - } + } if (removeVnetsFinal != null) { - s_logger.debug("removing vnet range " + removeVnetsFinal.toString() + " for the physicalNetwork id= " + network.getId() + " and zone id=" - + network.getDataCenterId() + " as a part of updatePhysicalNetwork call"); - //deleteVnets takes a list of strings to be removed. each string is a vnet. + s_logger.debug("removing vnet range " + removeVnetsFinal.toString() + " for the physicalNetwork id= " + network.getId() + " and zone id=" + network.getDataCenterId() + + " as a part of updatePhysicalNetwork call"); + //deleteVnets takes a list of strings to be removed. each string is a vnet. _datacneterVnet.deleteVnets(TransactionLegacy.currentTxn(), network.getDataCenterId(), network.getId(), removeVnetsFinal); - } - _physicalNetworkDao.update(network.getId(), network); + } + _physicalNetworkDao.update(network.getId(), network); } }); @@ -3127,8 +3094,7 @@ public class NetworkServiceImpl extends ManagerBase implements NetworkService { return vlanTokens; } if (VnetRange.length < 2) { - throw new InvalidParameterValueException("Please provide valid vnet range. vnet range should be a coma seperated list of vlan ranges. example 500-500,600-601" - + rangeMessage); + throw new InvalidParameterValueException("Please provide valid vnet range. vnet range should be a coma seperated list of vlan ranges. example 500-500,600-601" + rangeMessage); } if (VnetRange[0] == null || VnetRange[1] == null) { @@ -3140,8 +3106,7 @@ public class NetworkServiceImpl extends ManagerBase implements NetworkService { EndVnet = Integer.parseInt(VnetRange[1]); } catch (NumberFormatException e) { s_logger.warn("Unable to parse vnet range:", e); - throw new InvalidParameterValueException("Please provide valid vnet range. The vnet range should be a coma seperated list example 2001-2012,3000-3005." - + rangeMessage); + throw new InvalidParameterValueException("Please provide valid vnet range. The vnet range should be a coma seperated list example 2001-2012,3000-3005." + rangeMessage); } if (StartVnet < minVnet || EndVnet > maxVnet) { throw new InvalidParameterValueException("Vnet range has to be" + rangeMessage); @@ -3156,7 +3121,7 @@ public class NetworkServiceImpl extends ManagerBase implements NetworkService { } - public String generateVnetString(List vnetList) { + public String generateVnetString(List vnetList) { Collections.sort(vnetList, new Comparator() { @Override public int compare(String s1, String s2) { @@ -3232,7 +3197,7 @@ public class NetworkServiceImpl extends ManagerBase implements NetworkService { } } } - return removeVnets; + return removeVnets; } @Override @@ -3251,40 +3216,40 @@ public class NetworkServiceImpl extends ManagerBase implements NetworkService { return Transaction.execute(new TransactionCallback() { @Override public Boolean doInTransaction(TransactionStatus status) { - // delete vlans for this zone - List vlans = _vlanDao.listVlansByPhysicalNetworkId(physicalNetworkId); - for (VlanVO vlan : vlans) { - _vlanDao.remove(vlan.getId()); - } + // delete vlans for this zone + List vlans = _vlanDao.listVlansByPhysicalNetworkId(physicalNetworkId); + for (VlanVO vlan : vlans) { + _vlanDao.remove(vlan.getId()); + } - // Delete networks - List networks = _networksDao.listByPhysicalNetwork(physicalNetworkId); - if (networks != null && !networks.isEmpty()) { - for (NetworkVO network : networks) { - _networksDao.remove(network.getId()); - } - } + // Delete networks + List networks = _networksDao.listByPhysicalNetwork(physicalNetworkId); + if (networks != null && !networks.isEmpty()) { + for (NetworkVO network : networks) { + _networksDao.remove(network.getId()); + } + } - // delete vnets - _dcDao.deleteVnet(physicalNetworkId); + // delete vnets + _dcDao.deleteVnet(physicalNetworkId); - // delete service providers - List providers = _pNSPDao.listBy(physicalNetworkId); + // delete service providers + List providers = _pNSPDao.listBy(physicalNetworkId); for (PhysicalNetworkServiceProviderVO provider : providers) { - try { - deleteNetworkServiceProvider(provider.getId()); + try { + deleteNetworkServiceProvider(provider.getId()); } catch (ResourceUnavailableException e) { s_logger.warn("Unable to complete destroy of the physical network provider: " + provider.getProviderName() + ", id: " + provider.getId(), e); - return false; - } catch (ConcurrentOperationException e) { + return false; + } catch (ConcurrentOperationException e) { s_logger.warn("Unable to complete destroy of the physical network provider: " + provider.getProviderName() + ", id: " + provider.getId(), e); - return false; - } - } + return false; + } + } - // delete traffic types - _pNTrafficTypeDao.deleteTrafficTypes(physicalNetworkId); + // delete traffic types + _pNTrafficTypeDao.deleteTrafficTypes(physicalNetworkId); return _physicalNetworkDao.remove(physicalNetworkId); } @@ -3428,9 +3393,9 @@ public class NetworkServiceImpl extends ManagerBase implements NetworkService { int existingStartVlan = existingRanges.get(i).first(); int existingEndVlan = existingRanges.get(i).second(); if (startVlan <= endVlan && startVlan >= existingStartVlan && endVlan <= existingEndVlan) { - exists = true; - break; - } + exists = true; + break; + } } if (!exists) { throw new InvalidParameterValueException("Unable to find guest vlan by range " + vlan); @@ -3442,7 +3407,7 @@ public class NetworkServiceImpl extends ManagerBase implements NetworkService { List allocatedVlans = _datacneterVnet.listAllocatedVnetsInRange(physicalNetwork.getDataCenterId(), physicalNetwork.getId(), startVlan, endVlan); if (allocatedVlans != null && !allocatedVlans.isEmpty()) { for (DataCenterVnetVO allocatedVlan : allocatedVlans) { - if (allocatedVlan.getAccountId() != vlanOwner.getAccountId()) { + if (allocatedVlan.getAccountId() != vlanOwner.getAccountId()) { throw new InvalidParameterValueException("Guest vlan from this range " + allocatedVlan.getVnet() + " is allocated to a different account." + " Can only dedicate a range which has no allocated vlans or has vlans allocated to the same account "); } @@ -3507,7 +3472,7 @@ public class NetworkServiceImpl extends ManagerBase implements NetworkService { _accountGuestVlanMapDao.update(guestVlanMapId, accountGuestVlanMapVO); } else { accountGuestVlanMapVO = new AccountGuestVlanMapVO(vlanOwner.getAccountId(), physicalNetworkId); - accountGuestVlanMapVO.setGuestVlanRange(startVlan + "-" + endVlan); + accountGuestVlanMapVO.setGuestVlanRange(startVlan + "-" + endVlan); _accountGuestVlanMapDao.persist(accountGuestVlanMapVO); } // For every guest vlan set the corresponding account guest vlan map id @@ -3669,8 +3634,7 @@ public class NetworkServiceImpl extends ManagerBase implements NetworkService { if (destinationPhysicalNetworkId != null) { PhysicalNetworkVO destNetwork = _physicalNetworkDao.findById(destinationPhysicalNetworkId); if (destNetwork == null) { - throwInvalidIdException("Destination Physical Network with specified id doesn't exist in the system", destinationPhysicalNetworkId.toString(), - "destinationPhysicalNetworkId"); + throwInvalidIdException("Destination Physical Network with specified id doesn't exist in the system", destinationPhysicalNetworkId.toString(), "destinationPhysicalNetworkId"); } } @@ -3696,8 +3660,7 @@ public class NetworkServiceImpl extends ManagerBase implements NetworkService { if (enabledServices != null) { if (!element.canEnableIndividualServices()) { if (enabledServices.size() != element.getCapabilities().keySet().size()) { - throw new InvalidParameterValueException("Cannot enable subset of Services, Please specify the complete list of Services for this Service Provider '" - + providerName + "'"); + throw new InvalidParameterValueException("Cannot enable subset of Services, Please specify the complete list of Services for this Service Provider '" + providerName + "'"); } } @@ -3746,8 +3709,7 @@ public class NetworkServiceImpl extends ManagerBase implements NetworkService { } @Override - public Pair, Integer> listNetworkServiceProviders(Long physicalNetworkId, String name, String state, Long startIndex, - Long pageSize) { + public Pair, Integer> listNetworkServiceProviders(Long physicalNetworkId, String name, String state, Long startIndex, Long pageSize) { Filter searchFilter = new Filter(PhysicalNetworkServiceProviderVO.class, "id", false, startIndex, pageSize); SearchBuilder sb = _pNSPDao.createSearchBuilder(); @@ -3765,7 +3727,7 @@ public class NetworkServiceImpl extends ManagerBase implements NetworkService { sc.addAnd("state", Op.EQ, state); } - Pair, Integer> result = _pNSPDao.searchAndCount(sc, searchFilter); + Pair, Integer> result = _pNSPDao.searchAndCount(sc, searchFilter); return new Pair, Integer>(result.first(), result.second()); } @@ -3796,8 +3758,7 @@ public class NetworkServiceImpl extends ManagerBase implements NetworkService { if (state != null) { if (s_logger.isDebugEnabled()) { - s_logger.debug("trying to update the state of the service provider id=" + id + " on physical network: " + provider.getPhysicalNetworkId() + " to state: " - + stateStr); + s_logger.debug("trying to update the state of the service provider id=" + id + " on physical network: " + provider.getPhysicalNetworkId() + " to state: " + stateStr); } switch (state) { case Enabled: @@ -3814,7 +3775,7 @@ public class NetworkServiceImpl extends ManagerBase implements NetworkService { update = true; break; case Shutdown: - throw new InvalidParameterValueException("Updating the provider state to 'Shutdown' is not supported"); + throw new InvalidParameterValueException("Updating the provider state to 'Shutdown' is not supported"); } } @@ -3856,8 +3817,7 @@ public class NetworkServiceImpl extends ManagerBase implements NetworkService { // check if there are networks using this provider List networks = _networksDao.listByPhysicalNetworkAndProvider(provider.getPhysicalNetworkId(), provider.getProviderName()); if (networks != null && !networks.isEmpty()) { - throw new CloudRuntimeException( - "Provider is not deletable because there are active networks using this provider, please upgrade these networks to new network offerings"); + throw new CloudRuntimeException("Provider is not deletable because there are active networks using this provider, please upgrade these networks to new network offerings"); } User callerUser = _accountMgr.getActiveUser(CallContext.current().getCallingUserId()); @@ -3966,18 +3926,15 @@ public class NetworkServiceImpl extends ManagerBase implements NetworkService { if (TrafficType.isSystemNetwork(trafficType) || TrafficType.Public.equals(trafficType) || TrafficType.Storage.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); + throw new CloudRuntimeException("Fail to add the traffic type to physical network because Zone already has a physical network with this traffic type: " + trafficType); } } if (TrafficType.Storage.equals(trafficType)) { List ssvms = _stnwMgr.getSSVMWithNoStorageNetwork(network.getDataCenterId()); if (!ssvms.isEmpty()) { - StringBuilder sb = new StringBuilder( - "Cannot add " - + trafficType - + " traffic type as there are below secondary storage vm still running. Please stop them all and add Storage traffic type again, then destory them all to allow CloudStack recreate them with storage network(If you have added storage network ip range)"); + StringBuilder sb = new StringBuilder("Cannot add " + trafficType + + " traffic type as there are below secondary storage vm still running. Please stop them all and add Storage traffic type again, then destory them all to allow CloudStack recreate them with storage network(If you have added storage network ip range)"); sb.append("SSVMs:"); for (SecondaryStorageVmVO ssvm : ssvms) { sb.append(ssvm.getInstanceName()).append(":").append(ssvm.getState()); @@ -3991,25 +3948,25 @@ public class NetworkServiceImpl extends ManagerBase implements NetworkService { if (xenLabel == null) { xenLabel = getDefaultXenNetworkLabel(trafficType); } - PhysicalNetworkTrafficTypeVO pNetworktrafficType = new PhysicalNetworkTrafficTypeVO(physicalNetworkId, trafficType, xenLabel, kvmLabel, vmwareLabel, simulatorLabel, - vlan, hypervLabel, ovm3Label); + PhysicalNetworkTrafficTypeVO pNetworktrafficType = new PhysicalNetworkTrafficTypeVO(physicalNetworkId, trafficType, xenLabel, kvmLabel, vmwareLabel, simulatorLabel, vlan, hypervLabel, + ovm3Label); pNetworktrafficType = _pNTrafficTypeDao.persist(pNetworktrafficType); // For public traffic, get isolation method of physical network and update the public network accordingly // each broadcast type will individually need to be qualified for support of public traffic - if (TrafficType.Public.equals(trafficType)){ - List isolationMethods = network.getIsolationMethods(); - if ((isolationMethods.size() == 1 && isolationMethods.get(0).toLowerCase().equals("vxlan")) - || (isolationMethod != null && isolationMethods.contains(isolationMethod) && isolationMethod.toLowerCase().equals("vxlan"))) { - // find row in networks table that is defined as 'Public', created when zone was deployed - NetworkVO publicNetwork = _networksDao.listByZoneAndTrafficType(network.getDataCenterId(),TrafficType.Public).get(0); - if (publicNetwork != null) { - s_logger.debug("setting public network " + publicNetwork + " to broadcast type vxlan"); - publicNetwork.setBroadcastDomainType(BroadcastDomainType.Vxlan); - _networksDao.persist(publicNetwork); + if (TrafficType.Public.equals(trafficType)) { + List isolationMethods = network.getIsolationMethods(); + if ((isolationMethods.size() == 1 && isolationMethods.get(0).toLowerCase().equals("vxlan")) + || (isolationMethod != null && isolationMethods.contains(isolationMethod) && isolationMethod.toLowerCase().equals("vxlan"))) { + // find row in networks table that is defined as 'Public', created when zone was deployed + NetworkVO publicNetwork = _networksDao.listByZoneAndTrafficType(network.getDataCenterId(), TrafficType.Public).get(0); + if (publicNetwork != null) { + s_logger.debug("setting public network " + publicNetwork + " to broadcast type vxlan"); + publicNetwork.setBroadcastDomainType(BroadcastDomainType.Vxlan); + _networksDao.persist(publicNetwork); + } } } - } return pNetworktrafficType; } catch (Exception ex) { @@ -4113,8 +4070,7 @@ public class NetworkServiceImpl extends ManagerBase implements NetworkService { } else if (TrafficType.Storage.equals(trafficType.getTrafficType())) { PhysicalNetworkVO pn = _physicalNetworkDao.findById(trafficType.getPhysicalNetworkId()); if (_stnwMgr.isAnyStorageIpInUseInZone(pn.getDataCenterId())) { - throw new CloudRuntimeException("The Traffic Type is not deletable because there are still some storage network ip addresses in use:" - + trafficType.getTrafficType()); + throw new CloudRuntimeException("The Traffic Type is not deletable because there are still some storage network ip addresses in use:" + trafficType.getTrafficType()); } } return _pNTrafficTypeDao.remove(id); @@ -4140,8 +4096,7 @@ public class NetworkServiceImpl extends ManagerBase implements NetworkService { } if (networks.size() > 1) { - throw new InvalidParameterValueException("Found more than 1 network with trafficType " + TrafficType.Guest + " and guestType " + GuestType.Shared + " in zone " - + zoneId); + throw new InvalidParameterValueException("Found more than 1 network with trafficType " + TrafficType.Guest + " and guestType " + GuestType.Shared + " in zone " + zoneId); } @@ -4183,7 +4138,7 @@ public class NetworkServiceImpl extends ManagerBase implements NetworkService { PhysicalNetworkServiceProvider nsp = addProviderToPhysicalNetwork(physicalNetworkId, Network.Provider.VPCVirtualRouter.getName(), null, null); - NetworkElement networkElement = _networkModel.getElementImplementingProvider(Network.Provider.VPCVirtualRouter.getName()); + NetworkElement networkElement = _networkModel.getElementImplementingProvider(Network.Provider.VPCVirtualRouter.getName()); if (networkElement == null) { throw new CloudRuntimeException("Unable to find the Network Element implementing the VPCVirtualRouter Provider"); } @@ -4198,7 +4153,7 @@ public class NetworkServiceImpl extends ManagerBase implements NetworkService { PhysicalNetworkServiceProvider nsp = addProviderToPhysicalNetwork(physicalNetworkId, Network.Provider.InternalLbVm.getName(), null, null); - NetworkElement networkElement = _networkModel.getElementImplementingProvider(Network.Provider.InternalLbVm.getName()); + NetworkElement networkElement = _networkModel.getElementImplementingProvider(Network.Provider.InternalLbVm.getName()); if (networkElement == null) { throw new CloudRuntimeException("Unable to find the Network Element implementing the " + Network.Provider.InternalLbVm.getName() + " Provider"); } @@ -4261,6 +4216,7 @@ public class NetworkServiceImpl extends ManagerBase implements NetworkService { return null; } + protected boolean isNetworkSystem(Network network) { NetworkOffering no = _networkOfferingDao.findByIdIncludingRemoved(network.getNetworkOfferingId()); if (no.isSystemOnly()) { @@ -4299,8 +4255,8 @@ public class NetworkServiceImpl extends ManagerBase implements NetworkService { @Override @ActionEvent(eventType = EventTypes.EVENT_NET_IP_ASSIGN, eventDescription = "associating Ip", async = true) - public IpAddress associateIPToNetwork(long ipId, long networkId) throws InsufficientAddressCapacityException, ResourceAllocationException, ResourceUnavailableException, - ConcurrentOperationException { + public IpAddress associateIPToNetwork(long ipId, long networkId) + throws InsufficientAddressCapacityException, ResourceAllocationException, ResourceUnavailableException, ConcurrentOperationException { Network network = _networksDao.findById(networkId); if (network == null) { @@ -4322,8 +4278,8 @@ public class NetworkServiceImpl extends ManagerBase implements NetworkService { @Override @DB - public Network createPrivateNetwork(final String networkName, final String displayText, long physicalNetworkId, String broadcastUriString, final String startIp, String endIp, - final String gateway, String netmask, final long networkOwnerId, final Long vpcId, final Boolean sourceNat, final Long networkOfferingId) + public Network createPrivateNetwork(final String networkName, final String displayText, long physicalNetworkId, String broadcastUriString, final String startIp, String endIp, final String gateway, + String netmask, final long networkOwnerId, final Long vpcId, final Boolean sourceNat, final Long networkOfferingId) throws ResourceAllocationException, ConcurrentOperationException, InsufficientCapacityException { final Account owner = _accountMgr.getAccount(networkOwnerId); @@ -4385,7 +4341,7 @@ public class NetworkServiceImpl extends ManagerBase implements NetworkService { if (privateNetwork == null) { //create Guest network privateNetwork = _networkMgr.createGuestNetwork(ntwkOffFinal.getId(), networkName, displayText, gateway, cidr, uriString, false, null, owner, null, pNtwk, - pNtwk.getDataCenterId(), ACLType.Account, null, vpcId, null, null, true, null, null); + pNtwk.getDataCenterId(), ACLType.Account, null, vpcId, null, null, true, null, null); if (privateNetwork != null) { s_logger.debug("Successfully created guest network " + privateNetwork); } else { @@ -4395,16 +4351,16 @@ public class NetworkServiceImpl extends ManagerBase implements NetworkService { s_logger.debug("Private network already exists: " + privateNetwork); //Do not allow multiple private gateways with same Vlan within a VPC if (vpcId != null && vpcId.equals(privateNetwork.getVpcId())) { - throw new InvalidParameterValueException("Private network for the vlan: " + uriString + " and cidr " + cidr + " already exists " + "for Vpc " + vpcId - + " in zone " + _entityMgr.findById(DataCenter.class, pNtwk.getDataCenterId()).getName()); + throw new InvalidParameterValueException("Private network for the vlan: " + uriString + " and cidr " + cidr + " already exists " + "for Vpc " + vpcId + " in zone " + + _entityMgr.findById(DataCenter.class, pNtwk.getDataCenterId()).getName()); } } if (vpcId != null) { //add entry to private_ip_address table PrivateIpVO privateIp = _privateIpDao.findByIpAndSourceNetworkIdAndVpcId(privateNetwork.getId(), startIp, vpcId); if (privateIp != null) { - throw new InvalidParameterValueException("Private ip address " + startIp + " already used for private gateway" + " in zone " - + _entityMgr.findById(DataCenter.class, pNtwk.getDataCenterId()).getName()); + throw new InvalidParameterValueException( + "Private ip address " + startIp + " already used for private gateway" + " in zone " + _entityMgr.findById(DataCenter.class, pNtwk.getDataCenterId()).getName()); } Long mac = dc.getMacAddress(); Long nextMac = mac + 1; @@ -4439,7 +4395,7 @@ public class NetworkServiceImpl extends ManagerBase implements NetworkService { @Override public Network getNetwork(String networkUuid) { - return _networksDao.findByUuid(networkUuid); + return _networksDao.findByUuid(networkUuid); } @Override @@ -4449,24 +4405,23 @@ public class NetworkServiceImpl extends ManagerBase implements NetworkService { long vmId = cmd.getVmId(); String keyword = cmd.getKeyword(); Long networkId = cmd.getNetworkId(); - UserVmVO userVm = _userVmDao.findById(vmId); + UserVmVO userVm = _userVmDao.findById(vmId); if (userVm == null || (!userVm.isDisplayVm() && caller.getType() == Account.ACCOUNT_TYPE_NORMAL)) { throwInvalidIdException("Virtual machine id does not exist", Long.valueOf(vmId).toString(), "vmId"); - } + } _accountMgr.checkAccess(caller, null, true, userVm); return _networkMgr.listVmNics(vmId, nicId, networkId, keyword); } @Override - public List listVmNicSecondaryIps(ListNicsCmd cmd) - { + public List listVmNicSecondaryIps(ListNicsCmd cmd) { Account caller = CallContext.current().getCallingAccount(); Long nicId = cmd.getNicId(); long vmId = cmd.getVmId(); String keyword = cmd.getKeyword(); - UserVmVO userVm = _userVmDao.findById(vmId); + UserVmVO userVm = _userVmDao.findById(vmId); if (userVm == null || (!userVm.isDisplayVm() && caller.getType() == Account.ACCOUNT_TYPE_NORMAL)) { throwInvalidIdException("Virtual machine id does not exist", Long.valueOf(vmId).toString(), "vmId"); @@ -4520,12 +4475,15 @@ public class NetworkServiceImpl extends ManagerBase implements NetworkService { long callerUserId = CallContext.current().getCallingUserId(); DataCenter zone = _entityMgr.findByUuid(DataCenter.class, zoneId); - if (zone == null) + if (zone == null) { throw new InvalidParameterValueException("Invalid zone Id "); - if (_accountMgr.checkAccessAndSpecifyAuthority(caller, zone.getId()) != zone.getId()) + } + if (_accountMgr.checkAccessAndSpecifyAuthority(caller, zone.getId()) != zone.getId()) { throw new InvalidParameterValueException("Caller does not have permission for this Zone" + "(" + zoneId + ")"); - if (s_logger.isDebugEnabled()) + } + if (s_logger.isDebugEnabled()) { s_logger.debug("Associate IP address called by the user " + callerUserId + " account " + ipOwner.getId()); + } return _ipAddrMgr.allocatePodIp(zoneId, podId); }