use of com.cloud.vm.ReservationContext in project cosmic by MissionCriticalCloud.
the class NetworkServiceImpl method updateGuestNetwork.
@Override
@DB
@ActionEvent(eventType = EventTypes.EVENT_NETWORK_UPDATE, eventDescription = "updating network", async = true)
public Network updateGuestNetwork(final long networkId, final String name, final String displayText, final Account callerAccount, final User callerUser, final String domainSuffix, final Long networkOfferingId, final Boolean changeCidr, final String guestVmCidr, final Boolean displayNetwork, final String customId, final String dns1, final String dns2, final String ipExclusionList) {
boolean restartNetwork = false;
// verify input parameters
final NetworkVO network = _networksDao.findById(networkId);
if (network == null) {
// see NetworkVO.java
final InvalidParameterValueException ex = new InvalidParameterValueException("Specified network id doesn't exist in the system");
ex.addProxyObject(String.valueOf(networkId), "networkId");
throw ex;
}
// perform below validation if the network is vpc network
if (network.getVpcId() != null && networkOfferingId != null) {
final Vpc vpc = _entityMgr.findById(Vpc.class, network.getVpcId());
_vpcMgr.validateNtwkOffForNtwkInVpc(networkId, networkOfferingId, null, null, vpc, null, _accountMgr.getAccount(network.getAccountId()), null);
}
// don't allow to update network in Destroy state
if (network.getState() == Network.State.Destroy) {
throw new InvalidParameterValueException("Don't allow to update network in state " + Network.State.Destroy);
}
// Don't allow to update system network
final NetworkOffering offering = _networkOfferingDao.findByIdIncludingRemoved(network.getNetworkOfferingId());
if (offering.isSystemOnly()) {
throw new InvalidParameterValueException("Can't update system networks");
}
// allow to upgrade only Guest networks
if (network.getTrafficType() != Networks.TrafficType.Guest) {
throw new InvalidParameterValueException("Can't allow networks which traffic type is not " + TrafficType.Guest);
}
_accountMgr.checkAccess(callerAccount, null, true, network);
if (name != null) {
network.setName(name);
}
if (displayText != null) {
network.setDisplayText(displayText);
}
if (customId != null) {
network.setUuid(customId);
}
if (dns1 != null) {
network.setDns1(dns1);
restartNetwork = true;
}
if (dns2 != null) {
network.setDns2(dns2);
restartNetwork = true;
}
if (ipExclusionList != null) {
String networkCidr = null;
if (guestVmCidr == null) {
networkCidr = network.getNetworkCidr();
}
final List<NicVO> nicsPresent = _nicDao.listByNetworkId(networkId);
checkIpExclusionList(ipExclusionList, networkCidr, nicsPresent);
network.setIpExclusionList(ipExclusionList);
}
// display flag is not null and has changed
if (displayNetwork != null && displayNetwork != network.getDisplayNetwork()) {
// Update resource count if it needs to be updated
final NetworkOffering networkOffering = _networkOfferingDao.findById(network.getNetworkOfferingId());
if (_networkMgr.resourceCountNeedsUpdate(networkOffering, network.getAclType())) {
_resourceLimitMgr.changeResourceCount(network.getAccountId(), Resource.ResourceType.network, displayNetwork);
}
network.setDisplayNetwork(displayNetwork);
}
// network offering and domain suffix can be updated for Isolated networks only in 3.0
if ((networkOfferingId != null || domainSuffix != null) && network.getGuestType() != GuestType.Isolated) {
throw new InvalidParameterValueException("NetworkOffering and domain suffix upgrade can be perfomed for Isolated networks only");
}
boolean networkOfferingChanged = false;
final long oldNetworkOfferingId = network.getNetworkOfferingId();
final NetworkOffering oldNtwkOff = _networkOfferingDao.findByIdIncludingRemoved(oldNetworkOfferingId);
final NetworkOfferingVO networkOffering = _networkOfferingDao.findById(networkOfferingId);
if (networkOfferingId != null) {
if (networkOffering == null || networkOffering.isSystemOnly()) {
final InvalidParameterValueException ex = new InvalidParameterValueException("Unable to find network offering with specified id");
ex.addProxyObject(networkOfferingId.toString(), "networkOfferingId");
throw ex;
}
// network offering should be in Enabled state
if (networkOffering.getState() != NetworkOffering.State.Enabled) {
final InvalidParameterValueException ex = new InvalidParameterValueException("Network offering with specified id is not in " + NetworkOffering.State.Enabled + " state, can't upgrade to it");
ex.addProxyObject(networkOffering.getUuid(), "networkOfferingId");
throw ex;
}
// can't update from vpc to non-vpc network offering
final boolean forVpcNew = _configMgr.isOfferingForVpc(networkOffering);
final boolean vorVpcOriginal = _configMgr.isOfferingForVpc(_entityMgr.findById(NetworkOffering.class, oldNetworkOfferingId));
if (forVpcNew != vorVpcOriginal) {
final String errMsg = forVpcNew ? "a vpc offering " : "not a vpc offering";
throw new InvalidParameterValueException("Can't update as the new offering is " + errMsg);
}
if (networkOfferingId != oldNetworkOfferingId) {
final Collection<String> newProviders = _networkMgr.finalizeServicesAndProvidersForNetwork(networkOffering, network.getPhysicalNetworkId()).values();
final Collection<String> oldProviders = _networkMgr.finalizeServicesAndProvidersForNetwork(oldNtwkOff, network.getPhysicalNetworkId()).values();
if (changeCidr) {
if (!checkForNonStoppedVmInNetwork(network.getId())) {
final InvalidParameterValueException ex = new InvalidParameterValueException("All user vm of network of specified id should be stopped before changing " + "CIDR!");
ex.addProxyObject(network.getUuid(), "networkId");
throw ex;
}
}
// 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");
}
restartNetwork = true;
networkOfferingChanged = true;
// Setting the new network's isRedundant to the new network offering's RedundantRouter.
network.setIsRedundant(_networkOfferingDao.findById(networkOfferingId).getRedundantRouter());
}
}
final Map<String, String> 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 \"-\"");
}
long offeringId = oldNetworkOfferingId;
if (networkOfferingId != null) {
offeringId = networkOfferingId;
}
final Map<Network.Capability, String> dnsCapabilities = getNetworkOfferingServiceCapabilities(_entityMgr.findById(NetworkOffering.class, offeringId), Service.Dns);
final 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
final DataCenter dc = _dcDao.findById(network.getDataCenterId());
final 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 == true) {
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. ");
}
// 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
final String[] guestVmCidrPair = guestVmCidr.split("\\/");
final Long size = Long.valueOf(guestVmCidrPair[1]);
final List<NicVO> nicsPresent = _nicDao.listByNetworkId(networkId);
final 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]);
final long startIp = NetUtils.ip2Long(cidrIpRange[0]);
final long endIp = NetUtils.ip2Long(cidrIpRange[1]);
final long range = endIp - startIp + 1;
s_logger.info("The specified guest vm cidr has " + range + " IPs");
for (final NicVO nic : nicsPresent) {
final long nicIp = NetUtils.ip2Long(nic.getIPv4Address());
// check if nic IP is outside the guest vm cidr
if (nicIp < startIp || nicIp > endIp) {
if (!(nic.getState() == Nic.State.Deallocating)) {
throw new InvalidParameterValueException("Active IPs like " + nic.getIPv4Address() + " exist outside the Guest VM CIDR. Cannot apply reservation ");
}
}
}
// 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());
}
}
// 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);
}
checkIpExclusionList(ipExclusionList, guestVmCidr, 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);
}
final 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
final boolean validStateToShutdown = network.getState() == Network.State.Implemented || network.getState() == Network.State.Setup || network.getState() == Network.State.Allocated;
if (restartNetwork) {
if (validStateToShutdown) {
if (!changeCidr) {
s_logger.debug("Shutting down elements and resources for network id=" + networkId + " as a part of network update");
if (!_networkMgr.shutdownNetworkElementsAndResources(context, true, network)) {
s_logger.warn("Failed to shutdown the network elements and resources as a part of network restart: " + network);
final 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");
// 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");
final 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 {
final 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
final Network.State networkState = _networksDao.findById(networkId).getState();
final boolean validStateToImplement = networkState == Network.State.Implemented || networkState == Network.State.Setup || networkState == Network.State.Allocated;
if (restartNetwork && !validStateToImplement) {
final 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(final 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
final List<NicVO> nics = _nicDao.listByNetworkId(networkId);
for (final NicVO nic : nics) {
final long vmId = nic.getInstanceId();
final VMInstanceVO vm = _vmDao.findById(vmId);
if (vm == null) {
s_logger.error("Vm for nic " + nic.getId() + " not found with Vm Id:" + vmId);
continue;
}
final long isDefault = nic.isDefaultNic() ? 1 : 0;
final String nicIdString = Long.toString(nic.getId());
}
}
});
} 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) {
final DeployDestination dest = new DeployDestination(zoneRepository.findOne(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);
}
} catch (final Exception ex) {
s_logger.warn("Failed to implement network " + network + " elements and resources as a part of network update due to ", ex);
final 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;
}
}
}
// implement the network if its not already
if (networkOfferingChanged && !oldNtwkOff.getIsPersistent() && networkOffering.getIsPersistent()) {
if (network.getState() == Network.State.Allocated) {
try {
final DeployDestination dest = new DeployDestination(zoneRepository.findOne(network.getDataCenterId()), null, null, null);
_networkMgr.implementNetwork(network.getId(), dest, context);
} catch (final Exception ex) {
s_logger.warn("Failed to implement network " + network + " elements and resources as a part o" + "f network update due to ", ex);
final 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;
}
}
}
return getNetwork(network.getId());
}
use of com.cloud.vm.ReservationContext in project cosmic by MissionCriticalCloud.
the class NetworkServiceImpl method createGuestNetwork.
@Override
@DB
@ActionEvent(eventType = EventTypes.EVENT_NETWORK_CREATE, eventDescription = "creating network")
public Network createGuestNetwork(final CreateNetworkCmd cmd) throws InsufficientCapacityException, ConcurrentOperationException, ResourceAllocationException {
final Long networkOfferingId = cmd.getNetworkOfferingId();
String gateway = cmd.getGateway();
final String startIP = cmd.getStartIp();
String endIP = cmd.getEndIp();
final String netmask = cmd.getNetmask();
final String networkDomain = cmd.getNetworkDomain();
final String vlanId = cmd.getVlan();
final String name = cmd.getNetworkName();
final String displayText = cmd.getDisplayText();
final Account caller = CallContext.current().getCallingAccount();
final Long physicalNetworkId = cmd.getPhysicalNetworkId();
Long zoneId = cmd.getZoneId();
final String aclTypeStr = cmd.getAclType();
final Long domainId = cmd.getDomainId();
boolean isDomainSpecific = false;
final Boolean subdomainAccess = cmd.getSubdomainAccess();
final Long vpcId = cmd.getVpcId();
final String startIPv6 = cmd.getStartIpv6();
String endIPv6 = cmd.getEndIpv6();
String ip6Gateway = cmd.getIp6Gateway();
final String ip6Cidr = cmd.getIp6Cidr();
Boolean displayNetwork = cmd.getDisplayNetwork();
final Long aclId = cmd.getAclId();
final String isolatedPvlan = cmd.getIsolatedPvlan();
final String dns1 = cmd.getDns1();
final String dns2 = cmd.getDns2();
final String ipExclusionList = cmd.getIpExclusionList();
// Validate network offering
final NetworkOfferingVO ntwkOff = _networkOfferingDao.findById(networkOfferingId);
if (ntwkOff == null || ntwkOff.isSystemOnly()) {
final InvalidParameterValueException ex = new InvalidParameterValueException("Unable to find network offering by specified id");
if (ntwkOff != null) {
ex.addProxyObject(ntwkOff.getUuid(), "networkOfferingId");
}
throw ex;
}
if (!GuestType.Private.equals(ntwkOff.getGuestType()) && vpcId == null) {
throw new InvalidParameterValueException("VPC ID is required");
}
if (GuestType.Private.equals(ntwkOff.getGuestType()) && (startIP != null || endIP != null || vpcId != null || gateway != null || netmask != null)) {
throw new InvalidParameterValueException("StartIp/endIp/vpcId/gateway/netmask can't be specified for guest type " + GuestType.Private);
}
// validate physical network and zone
// Check if physical network exists
PhysicalNetwork pNtwk = null;
if (physicalNetworkId != null) {
pNtwk = _physicalNetworkDao.findById(physicalNetworkId);
if (pNtwk == null) {
throw new InvalidParameterValueException("Unable to find a physical network having the specified physical network id");
}
}
if (zoneId == null) {
zoneId = pNtwk.getDataCenterId();
}
if (displayNetwork == null) {
displayNetwork = true;
}
final Zone zone = zoneRepository.findOne(zoneId);
if (zone == null) {
throw new InvalidParameterValueException("Specified zone id was not found");
}
if (AllocationState.Disabled == zone.getAllocationState() && !_accountMgr.isRootAdmin(caller.getId())) {
// See DataCenterVO.java
final PermissionDeniedException ex = new PermissionDeniedException("Cannot perform this operation since specified Zone is currently disabled");
ex.addProxyObject(zone.getUuid(), "zoneId");
throw ex;
}
// Only domain and account ACL types are supported in Acton.
ACLType aclType = null;
if (aclTypeStr != null) {
if (aclTypeStr.equalsIgnoreCase(ACLType.Account.toString())) {
aclType = ACLType.Account;
} else if (aclTypeStr.equalsIgnoreCase(ACLType.Domain.toString())) {
aclType = ACLType.Domain;
} else {
throw new InvalidParameterValueException("Incorrect aclType specified. Check the API documentation for supported types");
}
// In 3.0 all Shared networks should have aclType == Domain, all Isolated networks aclType==Account
if (ntwkOff.getGuestType() != GuestType.Shared) {
if (aclType != ACLType.Account) {
throw new InvalidParameterValueException("AclType should be " + ACLType.Account + " for network of type " + ntwkOff.getGuestType());
}
} else if (ntwkOff.getGuestType() == GuestType.Shared) {
if (!(aclType == ACLType.Domain || aclType == ACLType.Account)) {
throw new InvalidParameterValueException("AclType should be " + ACLType.Domain + " or " + ACLType.Account + " for network of type " + Network.GuestType.Shared);
}
}
} else {
aclType = (ntwkOff.getGuestType() == GuestType.Shared) ? ACLType.Domain : ACLType.Account;
}
// Only Admin can create Shared networks
if (ntwkOff.getGuestType() == GuestType.Shared && !_accountMgr.isAdmin(caller.getId())) {
throw new InvalidParameterValueException("Only Admins can create network with guest type " + GuestType.Shared);
}
// Check if the network is domain specific
if (aclType == ACLType.Domain) {
// only Admin can create domain with aclType=Domain
if (!_accountMgr.isAdmin(caller.getId())) {
throw new PermissionDeniedException("Only admin can create networks with aclType=Domain");
}
// only shared networks can be Domain specific
if (ntwkOff.getGuestType() != GuestType.Shared) {
throw new InvalidParameterValueException("Only " + GuestType.Shared + " networks can have aclType=" + ACLType.Domain);
}
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);
}
final DomainVO domain = _domainDao.findById(domainId);
if (domain == null) {
throw new InvalidParameterValueException("Unable to find domain by specified id");
}
_accountMgr.checkAccess(caller, domain);
}
isDomainSpecific = true;
} else if (subdomainAccess != null) {
throw new InvalidParameterValueException("Parameter subDomainAccess can be specified only with aclType=Domain");
}
Account owner = null;
if (cmd.getAccountName() != null && domainId != null || cmd.getProjectId() != null) {
owner = _accountMgr.finalizeOwner(caller, cmd.getAccountName(), domainId, cmd.getProjectId());
} else {
owner = caller;
}
boolean ipv4 = true, ipv6 = false;
if (startIP != null) {
ipv4 = true;
}
if (startIPv6 != null) {
ipv6 = true;
}
if (gateway != null) {
try {
// getByName on a literal representation will only check validity of the address
// http://docs.oracle.com/javase/6/docs/api/java/net/InetAddress.html#getByName(java.lang.String)
final InetAddress gatewayAddress = InetAddress.getByName(gateway);
if (gatewayAddress instanceof Inet6Address) {
ipv6 = true;
} else {
ipv4 = true;
}
} catch (final UnknownHostException e) {
s_logger.error("Unable to convert gateway IP to a InetAddress", e);
throw new InvalidParameterValueException("Gateway parameter is invalid");
}
}
String cidr = cmd.getCidr();
if (ipv4) {
// validate the CIDR
if (cidr != null && !NetUtils.isValidIp4Cidr(cidr)) {
throw new InvalidParameterValueException("Invalid format for the CIDR parameter");
}
// validate gateway with cidr
if (cidr != null && gateway != null && !NetUtils.isIpWithtInCidrRange(gateway, cidr)) {
throw new InvalidParameterValueException("The gateway ip " + gateway + " should be part of the CIDR of the network " + cidr);
}
// if end ip is not specified, default it to startIp
if (startIP != null) {
if (!NetUtils.isValidIp4(startIP)) {
throw new InvalidParameterValueException("Invalid format for the startIp parameter");
}
if (endIP == null) {
endIP = startIP;
} else if (!NetUtils.isValidIp4(endIP)) {
throw new InvalidParameterValueException("Invalid format for the endIp parameter");
}
}
if (startIP != null && endIP != null) {
if (!(gateway != null && netmask != null)) {
throw new InvalidParameterValueException("gateway and netmask should be defined when startIP/endIP are passed in");
}
}
if (gateway != null && netmask != null) {
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.");
}
throw new InvalidParameterValueException("Invalid gateway IP provided. Either the IP is broadcast or network IP.");
}
if (!NetUtils.isValidIp4(gateway)) {
throw new InvalidParameterValueException("Invalid gateway");
}
if (!NetUtils.isValidIp4Netmask(netmask)) {
throw new InvalidParameterValueException("Invalid netmask");
}
cidr = NetUtils.ipAndNetMaskToCidr(gateway, netmask);
}
checkIpExclusionList(ipExclusionList, cidr, null);
}
if (ipv6) {
// validate the ipv6 CIDR
if (ip6Cidr != null && !NetUtils.isValidIp4Cidr(ip6Cidr)) {
throw new InvalidParameterValueException("Invalid format for the CIDR parameter");
}
if (endIPv6 == null) {
endIPv6 = startIPv6;
}
_networkModel.checkIp6Parameters(startIPv6, endIPv6, ip6Gateway, ip6Cidr);
if (zone.getNetworkType() != NetworkType.Advanced || ntwkOff.getGuestType() != Network.GuestType.Shared) {
throw new InvalidParameterValueException("Can only support create IPv6 network with advance shared network!");
}
}
if (isolatedPvlan != null && (zone.getNetworkType() != NetworkType.Advanced || ntwkOff.getGuestType() != Network.GuestType.Shared)) {
throw new InvalidParameterValueException("Can only support create Private VLAN network with advance shared network!");
}
if (isolatedPvlan != null && ipv6) {
throw new InvalidParameterValueException("Can only support create Private VLAN network with IPv4!");
}
// 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");
}
// Don't allow to specify vlan if the caller is a normal user
if (_accountMgr.isNormalUser(caller.getId()) && (ntwkOff.getSpecifyVlan() || vlanId != null)) {
throw new InvalidParameterValueException("Only ROOT admin and domain admins are allowed to specify vlanId");
}
if (ipv4) {
// For non-root admins check cidr limit - if it's allowed by global config value
if (!_accountMgr.isRootAdmin(caller.getId()) && cidr != null) {
final String[] cidrPair = cidr.split("\\/");
final int cidrSize = Integer.parseInt(cidrPair[1]);
if (cidrSize < _cidrLimit) {
throw new InvalidParameterValueException("Cidr size can't be less than " + _cidrLimit);
}
}
}
// 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 || !areServicesSupportedByNetworkOffering(ntwkOff.getId(), Service.SourceNat));
if (!createVlan) {
// Only support advance shared network in IPv6, which means createVlan is a must
if (ipv6) {
createVlan = true;
}
}
// Can add vlan range only to the network which allows it
if (createVlan && !ntwkOff.getSpecifyIpRanges()) {
final InvalidParameterValueException ex = new InvalidParameterValueException("Network offering with specified id doesn't support adding multiple ip ranges");
ex.addProxyObject(ntwkOff.getUuid(), "networkOfferingId");
throw ex;
}
if (ntwkOff.getGuestType() != GuestType.Private && gateway == null && cidr != null) {
gateway = NetUtils.getCidrHostAddress(cidr);
}
if (ntwkOff.getGuestType() != GuestType.Private && ip6Gateway == null && ip6Cidr != null) {
ip6Gateway = NetUtils.getCidrHostAddress6(ip6Cidr);
}
Network network = commitNetwork(networkOfferingId, gateway, startIP, endIP, netmask, networkDomain, vlanId, name, displayText, caller, physicalNetworkId, zoneId, domainId, isDomainSpecific, subdomainAccess, vpcId, startIPv6, endIPv6, ip6Gateway, ip6Cidr, displayNetwork, aclId, isolatedPvlan, ntwkOff, pNtwk, aclType, owner, cidr, createVlan, dns1, dns2, ipExclusionList);
// if the network offering has persistent set to true, implement the network
if (ntwkOff.getIsPersistent()) {
try {
if (network.getState() == Network.State.Setup) {
s_logger.debug("Network id=" + network.getId() + " is already provisioned");
return network;
}
final DeployDestination dest = new DeployDestination(zone, null, null, null);
final UserVO callerUser = _userDao.findById(CallContext.current().getCallingUserId());
final Journal journal = new Journal.LogJournal("Implementing " + network, s_logger);
final ReservationContext context = new ReservationContextImpl(UUID.randomUUID().toString(), journal, callerUser, caller);
s_logger.debug("Implementing network " + network + " as a part of network provision for persistent network");
final Pair<? extends NetworkGuru, ? extends Network> implementedNetwork = _networkMgr.implementNetwork(network.getId(), dest, context);
if (implementedNetwork == null || implementedNetwork.first() == null) {
s_logger.warn("Failed to provision the network " + network);
}
network = implementedNetwork.second();
} catch (final ResourceUnavailableException ex) {
s_logger.warn("Failed to implement persistent guest network " + network + "due to: " + ex.getMessage());
final CloudRuntimeException e = new CloudRuntimeException("Failed to implement persistent guest network", ex);
e.addProxyObject(network.getUuid(), "networkId");
throw e;
}
}
return network;
}
use of com.cloud.vm.ReservationContext in project cosmic by MissionCriticalCloud.
the class NiciraNvpElementTest method implementTest.
@Test
public void implementTest() throws ConcurrentOperationException, ResourceUnavailableException, InsufficientCapacityException {
final Network network = mock(Network.class);
when(network.getBroadcastDomainType()).thenReturn(BroadcastDomainType.Lswitch);
when(network.getId()).thenReturn(NETWORK_ID);
final NetworkOffering offering = mock(NetworkOffering.class);
when(offering.getId()).thenReturn(NETWORK_ID);
when(offering.getTrafficType()).thenReturn(TrafficType.Guest);
when(offering.getGuestType()).thenReturn(GuestType.Isolated);
mock(DeployDestination.class);
final Domain dom = mock(Domain.class);
when(dom.getName()).thenReturn("domain");
final Account acc = mock(Account.class);
when(acc.getAccountName()).thenReturn("accountname");
final ReservationContext context = mock(ReservationContext.class);
when(context.getDomain()).thenReturn(dom);
when(context.getAccount()).thenReturn(acc);
}
use of com.cloud.vm.ReservationContext in project cosmic by MissionCriticalCloud.
the class NiciraNvpGuestNetworkGuruTest method testImplementURIException.
@Test
public void testImplementURIException() throws InsufficientVirtualNetworkCapacityException {
final PhysicalNetworkVO physnet = mock(PhysicalNetworkVO.class);
when(physnetdao.findById((Long) any())).thenReturn(physnet);
when(physnet.getIsolationMethods()).thenReturn(Arrays.asList(new String[] { "STT" }));
when(physnet.getId()).thenReturn(NETWORK_ID);
final NiciraNvpDeviceVO device = mock(NiciraNvpDeviceVO.class);
when(nvpdao.listByPhysicalNetwork(NETWORK_ID)).thenReturn(Arrays.asList(new NiciraNvpDeviceVO[] { device }));
when(device.getId()).thenReturn(1L);
final NetworkOffering offering = mock(NetworkOffering.class);
when(offering.getId()).thenReturn(NETWORK_ID);
when(offering.getTrafficType()).thenReturn(TrafficType.Guest);
when(offering.getGuestType()).thenReturn(GuestType.Isolated);
when(nosd.areServicesSupportedByNetworkOffering(NETWORK_ID, Service.Connectivity)).thenReturn(false);
mock(DeploymentPlan.class);
final NetworkVO network = mock(NetworkVO.class);
when(network.getName()).thenReturn("testnetwork");
when(network.getState()).thenReturn(Network.State.Implementing);
when(network.getPhysicalNetworkId()).thenReturn(NETWORK_ID);
final DeployDestination dest = mock(DeployDestination.class);
final Zone zone = mock(Zone.class);
when(dest.getZone()).thenReturn(zone);
final HostVO niciraHost = mock(HostVO.class);
when(hostdao.findById(anyLong())).thenReturn(niciraHost);
when(niciraHost.getDetail("transportzoneuuid")).thenReturn("aaaa");
when(niciraHost.getDetail("transportzoneisotype")).thenReturn("stt");
when(niciraHost.getId()).thenReturn(NETWORK_ID);
when(netmodel.findPhysicalNetworkId(anyLong(), (String) any(), (TrafficType) any())).thenReturn(NETWORK_ID);
final Domain dom = mock(Domain.class);
when(dom.getName()).thenReturn("domain");
final Account acc = mock(Account.class);
when(acc.getAccountName()).thenReturn("accountname");
final ReservationContext res = mock(ReservationContext.class);
when(res.getDomain()).thenReturn(dom);
when(res.getAccount()).thenReturn(acc);
final CreateLogicalSwitchAnswer answer = mock(CreateLogicalSwitchAnswer.class);
when(answer.getResult()).thenReturn(true);
// when(answer.getLogicalSwitchUuid()).thenReturn("aaaaa");
when(agentmgr.easySend(eq(NETWORK_ID), (Command) any())).thenReturn(answer);
final Network implementednetwork = guru.implement(network, offering, dest, res);
assertTrue(implementednetwork == null);
verify(agentmgr, times(1)).easySend(eq(NETWORK_ID), (Command) any());
}
use of com.cloud.vm.ReservationContext in project cosmic by MissionCriticalCloud.
the class NiciraNvpGuestNetworkGuruTest method testShutdown.
@Test
public void testShutdown() throws InsufficientVirtualNetworkCapacityException, URISyntaxException {
final PhysicalNetworkVO physnet = mock(PhysicalNetworkVO.class);
when(physnetdao.findById((Long) any())).thenReturn(physnet);
when(physnet.getIsolationMethods()).thenReturn(Arrays.asList(new String[] { "STT", "VXLAN" }));
when(physnet.getId()).thenReturn(NETWORK_ID);
final NiciraNvpDeviceVO device = mock(NiciraNvpDeviceVO.class);
when(nvpdao.listByPhysicalNetwork(NETWORK_ID)).thenReturn(Arrays.asList(new NiciraNvpDeviceVO[] { device }));
when(device.getId()).thenReturn(1L);
final NetworkOffering offering = mock(NetworkOffering.class);
when(offering.getId()).thenReturn(NETWORK_ID);
when(offering.getTrafficType()).thenReturn(TrafficType.Guest);
when(offering.getGuestType()).thenReturn(GuestType.Isolated);
when(nosd.areServicesSupportedByNetworkOffering(NETWORK_ID, Service.Connectivity)).thenReturn(false);
mock(DeploymentPlan.class);
final NetworkVO network = mock(NetworkVO.class);
when(network.getName()).thenReturn("testnetwork");
when(network.getState()).thenReturn(Network.State.Implementing);
when(network.getBroadcastDomainType()).thenReturn(BroadcastDomainType.Lswitch);
when(network.getBroadcastUri()).thenReturn(new URI("lswitch:aaaaa"));
when(network.getPhysicalNetworkId()).thenReturn(NETWORK_ID);
when(netdao.findById(NETWORK_ID)).thenReturn(network);
final DeployDestination dest = mock(DeployDestination.class);
final Zone zone = mock(Zone.class);
when(dest.getZone()).thenReturn(zone);
final HostVO niciraHost = mock(HostVO.class);
when(hostdao.findById(anyLong())).thenReturn(niciraHost);
when(niciraHost.getDetail("transportzoneuuid")).thenReturn("aaaa");
when(niciraHost.getDetail("transportzoneisotype")).thenReturn("stt");
when(niciraHost.getId()).thenReturn(NETWORK_ID);
when(netmodel.findPhysicalNetworkId(anyLong(), (String) any(), (TrafficType) any())).thenReturn(NETWORK_ID);
final Domain dom = mock(Domain.class);
when(dom.getName()).thenReturn("domain");
final Account acc = mock(Account.class);
when(acc.getAccountName()).thenReturn("accountname");
final ReservationContext res = mock(ReservationContext.class);
when(res.getDomain()).thenReturn(dom);
when(res.getAccount()).thenReturn(acc);
final DeleteLogicalSwitchAnswer answer = mock(DeleteLogicalSwitchAnswer.class);
when(answer.getResult()).thenReturn(true);
when(agentmgr.easySend(eq(NETWORK_ID), (Command) any())).thenReturn(answer);
final NetworkProfile implementednetwork = mock(NetworkProfile.class);
when(implementednetwork.getId()).thenReturn(NETWORK_ID);
when(implementednetwork.getBroadcastUri()).thenReturn(new URI("lswitch:aaaa"));
when(offering.getSpecifyVlan()).thenReturn(false);
guru.shutdown(implementednetwork, offering);
verify(agentmgr, times(1)).easySend(eq(NETWORK_ID), (Command) any());
verify(implementednetwork, times(1)).setBroadcastUri(null);
}
Aggregations