use of com.cloud.utils.db.TransactionCallbackNoReturn in project cloudstack by apache.
the class UserVmManagerImpl method collectVmDiskStatistics.
@Override
public void collectVmDiskStatistics(final UserVmVO userVm) {
// support KVM only util 2013.06.25
if (!userVm.getHypervisorType().equals(HypervisorType.KVM))
return;
s_logger.debug("Collect vm disk statistics from host before stopping Vm");
long hostId = userVm.getHostId();
List<String> vmNames = new ArrayList<String>();
vmNames.add(userVm.getInstanceName());
final HostVO host = _hostDao.findById(hostId);
GetVmDiskStatsAnswer diskStatsAnswer = null;
try {
diskStatsAnswer = (GetVmDiskStatsAnswer) _agentMgr.easySend(hostId, new GetVmDiskStatsCommand(vmNames, host.getGuid(), host.getName()));
} catch (Exception e) {
s_logger.warn("Error while collecting disk stats for vm: " + userVm.getInstanceName() + " from host: " + host.getName(), e);
return;
}
if (diskStatsAnswer != null) {
if (!diskStatsAnswer.getResult()) {
s_logger.warn("Error while collecting disk stats vm: " + userVm.getInstanceName() + " from host: " + host.getName() + "; details: " + diskStatsAnswer.getDetails());
return;
}
try {
final GetVmDiskStatsAnswer diskStatsAnswerFinal = diskStatsAnswer;
Transaction.execute(new TransactionCallbackNoReturn() {
@Override
public void doInTransactionWithoutResult(TransactionStatus status) {
HashMap<String, List<VmDiskStatsEntry>> vmDiskStatsByName = diskStatsAnswerFinal.getVmDiskStatsMap();
if (vmDiskStatsByName == null)
return;
List<VmDiskStatsEntry> vmDiskStats = vmDiskStatsByName.get(userVm.getInstanceName());
if (vmDiskStats == null)
return;
for (VmDiskStatsEntry vmDiskStat : vmDiskStats) {
SearchCriteria<VolumeVO> sc_volume = _volsDao.createSearchCriteria();
sc_volume.addAnd("path", SearchCriteria.Op.EQ, vmDiskStat.getPath());
List<VolumeVO> volumes = _volsDao.search(sc_volume, null);
if ((volumes == null) || (volumes.size() == 0))
break;
VolumeVO volume = volumes.get(0);
VmDiskStatisticsVO previousVmDiskStats = _vmDiskStatsDao.findBy(userVm.getAccountId(), userVm.getDataCenterId(), userVm.getId(), volume.getId());
VmDiskStatisticsVO vmDiskStat_lock = _vmDiskStatsDao.lock(userVm.getAccountId(), userVm.getDataCenterId(), userVm.getId(), volume.getId());
if ((vmDiskStat.getIORead() == 0) && (vmDiskStat.getIOWrite() == 0) && (vmDiskStat.getBytesRead() == 0) && (vmDiskStat.getBytesWrite() == 0)) {
s_logger.debug("Read/Write of IO and Bytes are both 0. Not updating vm_disk_statistics");
continue;
}
if (vmDiskStat_lock == null) {
s_logger.warn("unable to find vm disk stats from host for account: " + userVm.getAccountId() + " with vmId: " + userVm.getId() + " and volumeId:" + volume.getId());
continue;
}
if (previousVmDiskStats != null && ((previousVmDiskStats.getCurrentIORead() != vmDiskStat_lock.getCurrentIORead()) || ((previousVmDiskStats.getCurrentIOWrite() != vmDiskStat_lock.getCurrentIOWrite()) || (previousVmDiskStats.getCurrentBytesRead() != vmDiskStat_lock.getCurrentBytesRead()) || (previousVmDiskStats.getCurrentBytesWrite() != vmDiskStat_lock.getCurrentBytesWrite())))) {
s_logger.debug("vm disk stats changed from the time GetVmDiskStatsCommand was sent. " + "Ignoring current answer. Host: " + host.getName() + " . VM: " + vmDiskStat.getVmName() + " IO Read: " + vmDiskStat.getIORead() + " IO Write: " + vmDiskStat.getIOWrite() + " Bytes Read: " + vmDiskStat.getBytesRead() + " Bytes Write: " + vmDiskStat.getBytesWrite());
continue;
}
if (vmDiskStat_lock.getCurrentIORead() > vmDiskStat.getIORead()) {
if (s_logger.isDebugEnabled()) {
s_logger.debug("Read # of IO that's less than the last one. " + "Assuming something went wrong and persisting it. Host: " + host.getName() + " . VM: " + vmDiskStat.getVmName() + " Reported: " + vmDiskStat.getIORead() + " Stored: " + vmDiskStat_lock.getCurrentIORead());
}
vmDiskStat_lock.setNetIORead(vmDiskStat_lock.getNetIORead() + vmDiskStat_lock.getCurrentIORead());
}
vmDiskStat_lock.setCurrentIORead(vmDiskStat.getIORead());
if (vmDiskStat_lock.getCurrentIOWrite() > vmDiskStat.getIOWrite()) {
if (s_logger.isDebugEnabled()) {
s_logger.debug("Write # of IO that's less than the last one. " + "Assuming something went wrong and persisting it. Host: " + host.getName() + " . VM: " + vmDiskStat.getVmName() + " Reported: " + vmDiskStat.getIOWrite() + " Stored: " + vmDiskStat_lock.getCurrentIOWrite());
}
vmDiskStat_lock.setNetIOWrite(vmDiskStat_lock.getNetIOWrite() + vmDiskStat_lock.getCurrentIOWrite());
}
vmDiskStat_lock.setCurrentIOWrite(vmDiskStat.getIOWrite());
if (vmDiskStat_lock.getCurrentBytesRead() > vmDiskStat.getBytesRead()) {
if (s_logger.isDebugEnabled()) {
s_logger.debug("Read # of Bytes that's less than the last one. " + "Assuming something went wrong and persisting it. Host: " + host.getName() + " . VM: " + vmDiskStat.getVmName() + " Reported: " + vmDiskStat.getBytesRead() + " Stored: " + vmDiskStat_lock.getCurrentBytesRead());
}
vmDiskStat_lock.setNetBytesRead(vmDiskStat_lock.getNetBytesRead() + vmDiskStat_lock.getCurrentBytesRead());
}
vmDiskStat_lock.setCurrentBytesRead(vmDiskStat.getBytesRead());
if (vmDiskStat_lock.getCurrentBytesWrite() > vmDiskStat.getBytesWrite()) {
if (s_logger.isDebugEnabled()) {
s_logger.debug("Write # of Bytes that's less than the last one. " + "Assuming something went wrong and persisting it. Host: " + host.getName() + " . VM: " + vmDiskStat.getVmName() + " Reported: " + vmDiskStat.getBytesWrite() + " Stored: " + vmDiskStat_lock.getCurrentBytesWrite());
}
vmDiskStat_lock.setNetBytesWrite(vmDiskStat_lock.getNetBytesWrite() + vmDiskStat_lock.getCurrentBytesWrite());
}
vmDiskStat_lock.setCurrentBytesWrite(vmDiskStat.getBytesWrite());
if (!_dailyOrHourly) {
//update agg bytes
vmDiskStat_lock.setAggIORead(vmDiskStat_lock.getNetIORead() + vmDiskStat_lock.getCurrentIORead());
vmDiskStat_lock.setAggIOWrite(vmDiskStat_lock.getNetIOWrite() + vmDiskStat_lock.getCurrentIOWrite());
vmDiskStat_lock.setAggBytesRead(vmDiskStat_lock.getNetBytesRead() + vmDiskStat_lock.getCurrentBytesRead());
vmDiskStat_lock.setAggBytesWrite(vmDiskStat_lock.getNetBytesWrite() + vmDiskStat_lock.getCurrentBytesWrite());
}
_vmDiskStatsDao.update(vmDiskStat_lock.getId(), vmDiskStat_lock);
}
}
});
} catch (Exception e) {
s_logger.warn("Unable to update vm disk statistics for vm: " + userVm.getId() + " from host: " + hostId, e);
}
}
}
use of com.cloud.utils.db.TransactionCallbackNoReturn in project cloudstack by apache.
the class NetworkServiceImpl method updateGuestNetwork.
@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) {
boolean restartNetwork = false;
// verify input parameters
final NetworkVO network = _networksDao.findById(networkId);
if (network == null) {
// see NetworkVO.java
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) {
Vpc vpc = _entityMgr.findById(Vpc.class, network.getVpcId());
_vpcMgr.validateNtwkOffForNtwkInVpc(networkId, networkOfferingId, null, null, vpc, null, _accountMgr.getAccount(network.getAccountId()), network.getNetworkACLId());
}
// 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
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);
}
// display flag is not null and has changed
if (displayNetwork != null && displayNetwork != network.getDisplayNetwork()) {
// Update resource count if it needs to be updated
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();
NetworkOffering oldNtwkOff = _networkOfferingDao.findByIdIncludingRemoved(oldNetworkOfferingId);
NetworkOfferingVO networkOffering = _networkOfferingDao.findById(networkOfferingId);
if (networkOfferingId != null) {
if (networkOffering == null || networkOffering.isSystemOnly()) {
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) {
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
boolean forVpcNew = _configMgr.isOfferingForVpc(networkOffering);
boolean vorVpcOriginal = _configMgr.isOfferingForVpc(_entityMgr.findById(NetworkOffering.class, oldNetworkOfferingId));
if (forVpcNew != vorVpcOriginal) {
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) {
Collection<String> newProviders = _networkMgr.finalizeServicesAndProvidersForNetwork(networkOffering, network.getPhysicalNetworkId()).values();
Collection<String> oldProviders = _networkMgr.finalizeServicesAndProvidersForNetwork(oldNtwkOff, network.getPhysicalNetworkId()).values();
if (providersConfiguredForExternalNetworking(newProviders) != providersConfiguredForExternalNetworking(oldProviders) && !changeCidr) {
throw new InvalidParameterValueException("Updating network failed since guest CIDR needs to be changed!");
}
if (changeCidr) {
if (!checkForNonStoppedVmInNetwork(network.getId())) {
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 isReduntant to the new network offering's RedundantRouter.
network.setIsReduntant(_networkOfferingDao.findById(networkOfferingId).getRedundantRouter());
}
}
final Map<String, String> newSvcProviders = networkOfferingChanged ? _networkMgr.finalizeServicesAndProvidersForNetwork(_entityMgr.findById(NetworkOffering.class, networkOfferingId), network.getPhysicalNetworkId()) : new HashMap<String, String>();
// 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;
}
Map<Network.Capability, String> 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 == 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.isValidCIDR(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
String[] guestVmCidrPair = guestVmCidr.split("\\/");
Long size = Long.valueOf(guestVmCidrPair[1]);
List<NicVO> 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) {
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);
}
// 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);
}
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()).getRedundantRouter() && (networkOfferingId == null || _networkOfferingDao.findById(networkOfferingId).getRedundantRouter()) && 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<String> 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());
}
boolean validStateToShutdown = (network.getState() == Network.State.Implemented || network.getState() == Network.State.Setup || network.getState() == Network.State.Allocated);
try {
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");
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");
//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;
}
}
} 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<NicVO> 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 {
_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);
}
} 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;
}
}
}
// implement the network if its not already
if (networkOfferingChanged && !oldNtwkOff.getIsPersistent() && networkOffering.getIsPersistent()) {
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());
}
use of com.cloud.utils.db.TransactionCallbackNoReturn in project cosmic by MissionCriticalCloud.
the class AccountManagerImpl method createApiKeyAndSecretKey.
@Override
@DB
@ActionEvent(eventType = EventTypes.EVENT_REGISTER_FOR_SECRET_API_KEY, eventDescription = "register for the developer API keys")
public String[] createApiKeyAndSecretKey(final long userId) {
final User user = getUserIncludingRemoved(userId);
if (user == null) {
throw new InvalidParameterValueException("Unable to find user by id");
}
final String[] keys = new String[2];
Transaction.execute(new TransactionCallbackNoReturn() {
@Override
public void doInTransactionWithoutResult(final TransactionStatus status) {
keys[0] = AccountManagerImpl.this.createUserApiKey(userId);
keys[1] = AccountManagerImpl.this.createUserSecretKey(userId);
}
});
return keys;
}
use of com.cloud.utils.db.TransactionCallbackNoReturn in project cosmic by MissionCriticalCloud.
the class DomainManagerImpl method updateDomain.
@Override
@ActionEvent(eventType = EventTypes.EVENT_DOMAIN_UPDATE, eventDescription = "updating Domain")
@DB
public DomainVO updateDomain(final UpdateDomainCmd cmd) {
final Long domainId = cmd.getId();
final String domainName = cmd.getDomainName();
final String networkDomain = cmd.getNetworkDomain();
final String email = cmd.getEmail();
// check if domain exists in the system
final DomainVO domain = _domainDao.findById(domainId);
if (domain == null) {
final InvalidParameterValueException ex = new InvalidParameterValueException("Unable to find domain with specified domain id");
ex.addProxyObject(domainId.toString(), "domainId");
throw ex;
} else if (domain.getParent() == null && domainName != null) {
// check if domain is ROOT domain - and deny to edit it with the new name
throw new InvalidParameterValueException("ROOT domain can not be edited with a new name");
}
// check permissions
final Account caller = CallContext.current().getCallingAccount();
_accountMgr.checkAccess(caller, domain);
// domain name is unique in the cloud
if (domainName != null) {
final SearchCriteria<DomainVO> sc = _domainDao.createSearchCriteria();
sc.addAnd("name", SearchCriteria.Op.EQ, domainName);
final List<DomainVO> domains = _domainDao.search(sc, null);
final boolean sameDomain = (domains.size() == 1 && domains.get(0).getId() == domainId);
if (!domains.isEmpty() && !sameDomain) {
final InvalidParameterValueException ex = new InvalidParameterValueException("Failed to update specified domain id with name '" + domainName + "' since it already exists in the system");
ex.addProxyObject(domain.getUuid(), "domainId");
throw ex;
}
}
// validate network domain
if (networkDomain != null && !networkDomain.isEmpty()) {
if (!NetUtils.verifyDomainName(networkDomain)) {
throw new InvalidParameterValueException("Invalid network domain. Total length shouldn't exceed 190 chars. Each domain label must be between 1 and 63 characters long, can contain ASCII letters " + "'a' through 'z', the digits '0' through '9', " + "and the hyphen ('-'); can't start or end with \"-\"");
}
}
final EmailValidator validator = EmailValidator.getInstance();
if (!StringUtils.isEmpty(email) && !validator.isValid(email)) {
throw new InvalidParameterValueException("Email address is not formatted correctly");
}
Transaction.execute(new TransactionCallbackNoReturn() {
@Override
public void doInTransactionWithoutResult(final TransactionStatus status) {
if (domainName != null) {
final String updatedDomainPath = getUpdatedDomainPath(domain.getPath(), domainName);
updateDomainChildren(domain, updatedDomainPath);
domain.setName(domainName);
domain.setPath(updatedDomainPath);
}
if (networkDomain != null) {
if (networkDomain.isEmpty()) {
domain.setNetworkDomain(null);
} else {
domain.setNetworkDomain(networkDomain);
}
}
if (email != null) {
if (email.isEmpty()) {
domain.setEmail(null);
} else {
domain.setEmail(email);
}
}
_domainDao.update(domainId, domain);
CallContext.current().putContextParameter(Domain.class, domain.getUuid());
}
});
return _domainDao.findById(domainId);
}
use of com.cloud.utils.db.TransactionCallbackNoReturn in project cosmic by MissionCriticalCloud.
the class UserVmManagerImpl method updateNicIpForVirtualMachine.
@Override
public UserVm updateNicIpForVirtualMachine(final UpdateVmNicIpCmd cmd) {
final Long nicId = cmd.getNicId();
String ipaddr = cmd.getIpaddress();
final Account caller = CallContext.current().getCallingAccount();
// check whether the nic belongs to user vm.
final NicVO nicVO = _nicDao.findById(nicId);
if (nicVO == null) {
throw new InvalidParameterValueException("There is no nic for the " + nicId);
}
if (nicVO.getVmType() != VirtualMachine.Type.User) {
throw new InvalidParameterValueException("The nic is not belongs to user vm");
}
final UserVm vm = _vmDao.findById(nicVO.getInstanceId());
if (vm == null) {
throw new InvalidParameterValueException("There is no vm with the nic");
}
final Network network = _networkDao.findById(nicVO.getNetworkId());
if (network == null) {
throw new InvalidParameterValueException("There is no network with the nic");
}
// Don't allow to update vm nic ip if network is not in Implemented/Setup/Allocated state
if (!(network.getState() == Network.State.Allocated || network.getState() == Network.State.Implemented || network.getState() == Network.State.Setup)) {
throw new InvalidParameterValueException("Network is not in the right state to update vm nic ip. Correct states are: " + Network.State.Allocated + ", " + Network.State.Implemented + ", " + Network.State.Setup);
}
final NetworkOfferingVO offering = _networkOfferingDao.findByIdIncludingRemoved(network.getNetworkOfferingId());
if (offering == null) {
throw new InvalidParameterValueException("There is no network offering with the network");
}
if (!_networkModel.listNetworkOfferingServices(offering.getId()).isEmpty() && vm.getState() != State.Stopped) {
final InvalidParameterValueException ex = new InvalidParameterValueException("VM is not Stopped, unable to update the vm nic having the specified id");
ex.addProxyObject(vm.getUuid(), "vmId");
throw ex;
}
// verify permissions
_accountMgr.checkAccess(caller, null, true, vm);
final Account ipOwner = _accountDao.findByIdIncludingRemoved(vm.getAccountId());
// verify ip address
s_logger.debug("Calling the ip allocation ...");
final Zone zone = zoneRepository.findOne(network.getDataCenterId());
if (zone == null) {
throw new InvalidParameterValueException("There is no dc with the nic");
}
if (zone.getNetworkType() == NetworkType.Advanced && network.getGuestType() == Network.GuestType.Isolated) {
try {
ipaddr = _ipAddrMgr.allocateGuestIP(network, ipaddr);
} catch (final InsufficientAddressCapacityException e) {
throw new InvalidParameterValueException("Allocating ip to guest nic " + nicVO.getUuid() + " failed, for insufficient address capacity");
}
if (ipaddr == null) {
throw new InvalidParameterValueException("Allocating ip to guest nic " + nicVO.getUuid() + " failed, please choose another ip");
}
if (_networkModel.areServicesSupportedInNetwork(network.getId(), Service.StaticNat)) {
final IPAddressVO oldIP = _ipAddressDao.findByAssociatedVmId(vm.getId());
if (oldIP != null) {
oldIP.setVmIp(ipaddr);
_ipAddressDao.persist(oldIP);
}
}
// implementing the network elements and resources as a part of vm nic ip update if network has services and it is in Implemented state
if (!_networkModel.listNetworkOfferingServices(offering.getId()).isEmpty() && network.getState() == Network.State.Implemented) {
final User callerUser = _accountMgr.getActiveUser(CallContext.current().getCallingUserId());
final ReservationContext context = new ReservationContextImpl(null, null, callerUser, caller);
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 vm nic ip update");
try {
// implement the network elements and rules again
_networkMgr.implementNetworkElementsAndResources(dest, context, network, offering);
} catch (final Exception ex) {
s_logger.warn("Failed to implement network " + network + " elements and resources as a part of vm nic ip update due to ", ex);
final CloudRuntimeException e = new CloudRuntimeException("Failed to implement network (with specified id) elements and resources as a part of vm nic ip " + "update");
e.addProxyObject(network.getUuid(), "networkId");
// restore to old ip address
if (_networkModel.areServicesSupportedInNetwork(network.getId(), Service.StaticNat)) {
final IPAddressVO oldIP = _ipAddressDao.findByAssociatedVmId(vm.getId());
if (oldIP != null) {
oldIP.setVmIp(nicVO.getIPv4Address());
_ipAddressDao.persist(oldIP);
}
}
throw e;
}
}
} else if (zone.getNetworkType() == NetworkType.Basic || network.getGuestType() == Network.GuestType.Shared) {
// handle the basic networks here
// for basic zone, need to provide the podId to ensure proper ip alloation
Long podId = null;
if (zone.getNetworkType() == NetworkType.Basic) {
podId = vm.getPodIdToDeployIn();
if (podId == null) {
throw new InvalidParameterValueException("vm pod id is null in Basic zone; can't decide the range for ip allocation");
}
}
try {
ipaddr = _ipAddrMgr.allocatePublicIpForGuestNic(network, podId, ipOwner, ipaddr);
if (ipaddr == null) {
throw new InvalidParameterValueException("Allocating ip to guest nic " + nicVO.getUuid() + " failed, please choose another ip");
}
final IPAddressVO ip = _ipAddressDao.findByIpAndSourceNetworkId(nicVO.getNetworkId(), nicVO.getIPv4Address());
if (ip != null) {
Transaction.execute(new TransactionCallbackNoReturn() {
@Override
public void doInTransactionWithoutResult(final TransactionStatus status) {
_ipAddrMgr.markIpAsUnavailable(ip.getId());
_ipAddressDao.unassignIpAddress(ip.getId());
}
});
}
} catch (final InsufficientAddressCapacityException e) {
s_logger.error("Allocating ip to guest nic " + nicVO.getUuid() + " failed, for insufficient address capacity");
return null;
}
} else {
s_logger.error("UpdateVmNicIpCmd is not supported in this network...");
return null;
}
// update nic ipaddress
nicVO.setIPv4Address(ipaddr);
_nicDao.persist(nicVO);
return vm;
}
Aggregations