use of com.cloud.legacymodel.network.Nic in project cosmic by MissionCriticalCloud.
the class VirtualMachineManagerImpl method orchestrateMigrateWithStorage.
private void orchestrateMigrateWithStorage(final String vmUuid, final long srcHostId, final long destHostId, final Map<Long, Long> volumeToPool) throws ResourceUnavailableException, ConcurrentOperationException {
final VMInstanceVO vm = _vmDao.findByUuid(vmUuid);
final HostVO srcHost = _hostDao.findById(srcHostId);
final HostVO destHost = _hostDao.findById(destHostId);
final VirtualMachineGuru vmGuru = getVmGuru(vm);
final Zone zone = _zoneRepository.findById(destHost.getDataCenterId()).orElse(null);
final HostPodVO pod = _podDao.findById(destHost.getPodId());
final Cluster cluster = _clusterDao.findById(destHost.getClusterId());
final DeployDestination destination = new DeployDestination(zone, pod, cluster, destHost);
// Create a map of which volume should go in which storage pool.
final VirtualMachineProfile profile = new VirtualMachineProfileImpl(vm);
final Map<Volume, StoragePool> volumeToPoolMap = getPoolListForVolumesForMigration(profile, destHost, volumeToPool);
// a vm and not migrating a vm with storage.
if (volumeToPoolMap == null || volumeToPoolMap.isEmpty()) {
throw new InvalidParameterValueException("Migration of the vm " + vm + "from host " + srcHost + " to destination host " + destHost + " doesn't involve migrating the volumes.");
}
AlertManager.AlertType alertType = AlertManager.AlertType.ALERT_TYPE_USERVM_MIGRATE;
if (VirtualMachineType.DomainRouter.equals(vm.getType())) {
alertType = AlertManager.AlertType.ALERT_TYPE_DOMAIN_ROUTER_MIGRATE;
} else if (VirtualMachineType.ConsoleProxy.equals(vm.getType())) {
alertType = AlertManager.AlertType.ALERT_TYPE_CONSOLE_PROXY_MIGRATE;
}
_networkMgr.prepareNicForMigration(profile, destination);
volumeMgr.prepareForMigration(profile, destination);
final HypervisorGuru hvGuru = _hvGuruMgr.getGuru(vm.getHypervisorType());
final VirtualMachineTO to = hvGuru.implement(profile);
ItWorkVO work = new ItWorkVO(UUID.randomUUID().toString(), _nodeId, State.Migrating, vm.getType(), vm.getId());
work.setStep(Step.Prepare);
work.setResourceType(ItWorkVO.ResourceType.Host);
work.setResourceId(destHostId);
work = _workDao.persist(work);
// Put the vm in migrating state.
vm.setLastHostId(srcHostId);
moveVmToMigratingState(vm, destHostId, work);
boolean migrated = false;
try {
// config drive: Detach the config drive at source host
// After migration successful attach the config drive in destination host
// On migration failure VM will be stopped, So configIso will be deleted
final Nic defaultNic = _networkModel.getDefaultNic(vm.getId());
List<String[]> vmData = null;
if (defaultNic != null) {
final UserVmVO userVm = _userVmDao.findById(vm.getId());
final Map<String, String> details = _vmDetailsDao.listDetailsKeyPairs(vm.getId());
vm.setDetails(details);
final Network network = _networkModel.getNetwork(defaultNic.getNetworkId());
if (_networkModel.isSharedNetworkWithoutServices(network.getId())) {
final String serviceOffering = _serviceOfferingDao.findByIdIncludingRemoved(vm.getId(), vm.getServiceOfferingId()).getDisplayText();
final String zoneName = _dcDao.findById(vm.getDataCenterId()).getName();
final boolean isWindows = _guestOSCategoryDao.findById(_guestOSDao.findById(vm.getGuestOSId()).getCategoryId()).getName().equalsIgnoreCase("Windows");
vmData = _networkModel.generateVmData(userVm.getUserData(), serviceOffering, zoneName, vm.getInstanceName(), vm.getId(), (String) profile.getParameter(VirtualMachineProfile.Param.VmSshPubKey), (String) profile.getParameter(VirtualMachineProfile.Param.VmPassword), isWindows, network);
final String vmName = vm.getInstanceName();
final String configDriveIsoRootFolder = "/tmp";
final String isoFile = configDriveIsoRootFolder + "/" + vmName + "/configDrive/" + vmName + ".iso";
profile.setVmData(vmData);
profile.setConfigDriveLabel(VmConfigDriveLabel.value());
profile.setConfigDriveIsoRootFolder(configDriveIsoRootFolder);
profile.setConfigDriveIsoFile(isoFile);
// At source host detach the config drive iso.
final AttachOrDettachConfigDriveCommand dettachCommand = new AttachOrDettachConfigDriveCommand(vm.getInstanceName(), vmData, VmConfigDriveLabel.value(), false);
try {
_agentMgr.send(srcHost.getId(), dettachCommand);
s_logger.debug("Deleted config drive ISO for vm " + vm.getInstanceName() + " In host " + srcHost);
} catch (final OperationTimedoutException e) {
s_logger.debug("TIme out occured while exeuting command AttachOrDettachConfigDrive " + e.getMessage());
}
}
}
// Migrate the vm and its volume.
volumeMgr.migrateVolumes(vm, to, srcHost, destHost, volumeToPoolMap);
// Put the vm back to running state.
moveVmOutofMigratingStateOnSuccess(vm, destHost.getId(), work);
try {
if (!checkVmOnHost(vm, destHostId)) {
s_logger.error("Vm not found on destination host. Unable to complete migration for " + vm);
try {
_agentMgr.send(srcHostId, new Commands(cleanup(vm.getInstanceName())), null);
} catch (final AgentUnavailableException e) {
s_logger.error("AgentUnavailableException while cleanup on source host: " + srcHostId);
}
cleanup(vmGuru, new VirtualMachineProfileImpl(vm), work, Event.AgentReportStopped, true);
throw new CloudRuntimeException("VM not found on desintation host. Unable to complete migration for " + vm);
}
} catch (final OperationTimedoutException e) {
s_logger.warn("Error while checking the vm " + vm + " is on host " + destHost, e);
}
migrated = true;
} finally {
if (!migrated) {
s_logger.info("Migration was unsuccessful. Cleaning up: " + vm);
_alertMgr.sendAlert(alertType, srcHost.getDataCenterId(), srcHost.getPodId(), "Unable to migrate vm " + vm.getInstanceName() + " from host " + srcHost.getName() + " in zone " + zone.getName() + " and pod " + zone.getName(), "Migrate Command failed. Please check logs.");
try {
_agentMgr.send(destHostId, new Commands(cleanup(vm.getInstanceName())), null);
stateTransitTo(vm, Event.OperationFailed, srcHostId);
} catch (final AgentUnavailableException e) {
s_logger.warn("Looks like the destination Host is unavailable for cleanup.", e);
} catch (final NoTransitionException e) {
s_logger.error("Error while transitioning vm from migrating to running state.", e);
}
}
work.setStep(Step.Done);
_workDao.update(work.getId(), work);
}
}
use of com.cloud.legacymodel.network.Nic in project cosmic by MissionCriticalCloud.
the class NetworkOrchestrator method prepareAllNicsForMigration.
/*
Prepare All Nics for migration including the nics dynamically created and not stored in DB
This is a temporary workaround work KVM migration
Once clean fix is added by stored dynamically nics is DB, this workaround won't be needed
*/
@Override
public void prepareAllNicsForMigration(final VirtualMachineProfile vm, final DeployDestination dest) {
final List<NicVO> nics = _nicDao.listByVmId(vm.getId());
final ReservationContext context = new ReservationContextImpl(UUID.randomUUID().toString(), null, null);
Long guestNetworkId = null;
for (final NicVO nic : nics) {
final NetworkVO network = _networksDao.findById(nic.getNetworkId());
if (network.getTrafficType().equals(TrafficType.Guest) && network.getGuestType().equals(GuestType.Isolated)) {
guestNetworkId = network.getId();
}
final Integer networkRate = _networkModel.getNetworkRate(network.getId(), vm.getId());
final NetworkGuru guru = AdapterBase.getAdapterByName(networkGurus, network.getGuruName());
final NicProfile profile = new NicProfile(nic, network, nic.getBroadcastUri(), nic.getIsolationUri(), networkRate, _networkModel.getNetworkTag(vm.getHypervisorType(), network));
if (guru instanceof NetworkMigrationResponder) {
if (!((NetworkMigrationResponder) guru).prepareMigration(profile, network, vm, dest, context)) {
// XXX: Transaction error
s_logger.error("NetworkGuru " + guru + " prepareForMigration failed.");
}
}
final List<Provider> providersToImplement = getNetworkProviders(network.getId());
for (final NetworkElement element : networkElements) {
if (providersToImplement.contains(element.getProvider())) {
if (!_networkModel.isProviderEnabledInPhysicalNetwork(_networkModel.getPhysicalNetworkId(network), element.getProvider().getName())) {
throw new CloudRuntimeException("Service provider " + element.getProvider().getName() + " either doesn't exist or is not enabled in physical network id: " + "" + network.getPhysicalNetworkId());
}
if (element instanceof NetworkMigrationResponder) {
if (!((NetworkMigrationResponder) element).prepareMigration(profile, network, vm, dest, context)) {
// XXX: Transaction error
s_logger.error("NetworkElement " + element + " prepareForMigration failed.");
}
}
}
}
guru.updateNicProfile(profile, network);
vm.addNic(profile);
}
final List<String> addedURIs = new ArrayList<>();
if (guestNetworkId != null) {
final List<IPAddressVO> publicIps = _ipAddressDao.listByAssociatedNetwork(guestNetworkId, null);
for (final IPAddressVO userIp : publicIps) {
final PublicIp publicIp = PublicIp.createFromAddrAndVlan(userIp, _vlanDao.findById(userIp.getVlanId()));
final URI broadcastUri = BroadcastDomainType.Vlan.toUri(publicIp.getVlanTag());
final long ntwkId = publicIp.getNetworkId();
final Nic nic = _nicDao.findByNetworkIdInstanceIdAndBroadcastUri(ntwkId, vm.getId(), broadcastUri.toString());
if (nic == null && !addedURIs.contains(broadcastUri.toString())) {
// Nic details are not available in DB
// Create nic profile for migration
s_logger.debug("Creating nic profile for migration. BroadcastUri: " + broadcastUri.toString() + " NetworkId: " + ntwkId + " Vm: " + vm.getId());
final NetworkVO network = _networksDao.findById(ntwkId);
_networkModel.getNetworkRate(network.getId(), vm.getId());
final NetworkGuru guru = AdapterBase.getAdapterByName(networkGurus, network.getGuruName());
final NicProfile profile = new NicProfile();
profile.setIPv4Address(userIp.getAddress().toString());
profile.setIPv4Netmask(publicIp.getNetmask());
profile.setIPv4Gateway(publicIp.getGateway());
profile.setMacAddress(publicIp.getMacAddress());
profile.setBroadcastType(network.getBroadcastDomainType());
profile.setTrafficType(network.getTrafficType());
profile.setBroadcastUri(broadcastUri);
profile.setIsolationUri(Networks.IsolationType.Vlan.toUri(publicIp.getVlanTag()));
profile.setName(_networkModel.getNetworkTag(vm.getHypervisorType(), network));
profile.setNetworId(network.getId());
guru.updateNicProfile(profile, network);
vm.addNic(profile);
addedURIs.add(broadcastUri.toString());
}
}
}
}
use of com.cloud.legacymodel.network.Nic in project cosmic by MissionCriticalCloud.
the class VirtualMachineManagerImpl method orchestrateRemoveVmFromNetwork.
@DB
private boolean orchestrateRemoveVmFromNetwork(final VirtualMachine vm, final Network network, final URI broadcastUri) throws ConcurrentOperationException, ResourceUnavailableException {
final CallContext cctx = CallContext.current();
final VMInstanceVO vmVO = _vmDao.findById(vm.getId());
final ReservationContext context = new ReservationContextImpl(null, null, cctx.getCallingUser(), cctx.getCallingAccount());
final VirtualMachineProfileImpl vmProfile = new VirtualMachineProfileImpl(vmVO, null, null, null, null);
final Zone zone = _zoneRepository.findById(network.getDataCenterId()).orElse(null);
final Host host = _hostDao.findById(vm.getHostId());
final DeployDestination dest = new DeployDestination(zone, null, null, host);
final HypervisorGuru hvGuru = _hvGuruMgr.getGuru(vmProfile.getVirtualMachine().getHypervisorType());
final VirtualMachineTO vmTO = hvGuru.implement(vmProfile);
Nic nic = null;
if (broadcastUri != null) {
nic = _nicsDao.findByNetworkIdInstanceIdAndBroadcastUri(network.getId(), vm.getId(), broadcastUri.toString());
} else {
nic = _networkModel.getNicInNetwork(vm.getId(), network.getId());
}
if (nic == null) {
s_logger.warn("Could not get a nic with " + network);
return false;
}
// don't delete default NIC on a user VM
if (nic.isDefaultNic() && vm.getType() == VirtualMachineType.User) {
s_logger.warn("Failed to remove nic from " + vm + " in " + network + ", nic is default.");
throw new CloudRuntimeException("Failed to remove nic from " + vm + " in " + network + ", nic is default.");
}
// Lock on nic is needed here
final Nic lock = _nicsDao.acquireInLockTable(nic.getId());
if (lock == null) {
// check if nic is still there. Return if it was released already
if (_nicsDao.findById(nic.getId()) == null) {
s_logger.debug("Not need to remove the vm " + vm + " from network " + network + " as the vm doesn't have nic in this network");
return true;
}
throw new ConcurrentOperationException("Unable to lock nic " + nic.getId());
}
s_logger.debug("Lock is acquired for nic id " + lock.getId() + " as a part of remove vm " + vm + " from network " + network);
try {
final NicProfile nicProfile = new NicProfile(nic, network, nic.getBroadcastUri(), nic.getIsolationUri(), _networkModel.getNetworkRate(network.getId(), vm.getId()), _networkModel.getNetworkTag(vmProfile.getVirtualMachine().getHypervisorType(), network));
// 1) Unplug the nic
if (vm.getState() == State.Running) {
final NicTO nicTO = toNicTO(nicProfile, vmProfile.getVirtualMachine().getHypervisorType());
s_logger.debug("Un-plugging nic for vm " + vm + " from network " + network);
final boolean result = unplugNic(network, nicTO, vmTO, context, dest);
if (result) {
s_logger.debug("Nic is unplugged successfully for vm " + vm + " in network " + network);
} else {
s_logger.warn("Failed to unplug nic for the vm " + vm + " from network " + network);
return false;
}
} else if (vm.getState() != State.Stopped) {
s_logger.warn("Unable to remove vm " + vm + " from network " + network);
throw new ResourceUnavailableException("Unable to remove vm " + vm + " from network, is not in the right state", DataCenter.class, vm.getDataCenterId());
}
// 2) Release the nic
_networkMgr.releaseNic(vmProfile, nic);
s_logger.debug("Successfully released nic " + nic + "for vm " + vm);
// 3) Remove the nic
_networkMgr.removeNic(vmProfile, nic);
return true;
} finally {
if (lock != null) {
_nicsDao.releaseFromLockTable(lock.getId());
s_logger.debug("Lock is released for nic id " + lock.getId() + " as a part of remove vm " + vm + " from network " + network);
}
}
}
use of com.cloud.legacymodel.network.Nic in project cosmic by MissionCriticalCloud.
the class NetworkModelImpl method getNetworkRate.
@Override
public Integer getNetworkRate(final long networkId, final Long vmId) {
VMInstanceVO vm = null;
if (vmId != null) {
vm = _vmDao.findById(vmId);
}
final Network network = getNetwork(networkId);
final NetworkOffering ntwkOff = _entityMgr.findById(NetworkOffering.class, network.getNetworkOfferingId());
// For default userVm Default network and domR guest/public network, get rate information from the service
// offering; for other situations get information
// from the network offering
boolean isUserVmsDefaultNetwork = false;
boolean isDomRGuestOrPublicNetwork = false;
boolean isSystemVmNetwork = false;
if (vm != null) {
final Nic nic = _nicDao.findByNtwkIdAndInstanceId(networkId, vmId);
if (vm.getType() == VirtualMachineType.User && nic != null && nic.isDefaultNic()) {
isUserVmsDefaultNetwork = true;
} else if (vm.getType() == VirtualMachineType.DomainRouter && ntwkOff != null && (ntwkOff.getTrafficType() == TrafficType.Public || ntwkOff.getTrafficType() == TrafficType.Guest)) {
isDomRGuestOrPublicNetwork = true;
} else if (vm.getType() == VirtualMachineType.ConsoleProxy || vm.getType() == VirtualMachineType.SecondaryStorageVm) {
isSystemVmNetwork = true;
}
}
if (isUserVmsDefaultNetwork || isDomRGuestOrPublicNetwork) {
return _configMgr.getServiceOfferingNetworkRate(vm.getServiceOfferingId(), network.getDataCenterId());
} else if (isSystemVmNetwork) {
return -1;
} else {
return _configMgr.getNetworkOfferingNetworkRate(ntwkOff.getId(), network.getDataCenterId());
}
}
use of com.cloud.legacymodel.network.Nic in project cosmic by MissionCriticalCloud.
the class RulesManagerImpl method updatePortForwardingRule.
@Override
@ActionEvent(eventType = EventTypes.EVENT_NET_RULE_MODIFY, eventDescription = "updating forwarding rule", async = true)
public PortForwardingRule updatePortForwardingRule(final long id, final Integer privatePort, final Long virtualMachineId, final Ip vmGuestIp, final String customId, final Boolean forDisplay) {
final Account caller = CallContext.current().getCallingAccount();
PortForwardingRuleVO rule = _portForwardingDao.findById(id);
if (rule == null) {
throw new InvalidParameterValueException("Unable to find " + id);
}
_accountMgr.checkAccess(caller, null, true, rule);
if (customId != null) {
rule.setUuid(customId);
}
if (forDisplay != null) {
rule.setDisplay(forDisplay);
}
if (!rule.getSourcePortStart().equals(rule.getSourcePortEnd()) && privatePort != null) {
throw new InvalidParameterValueException("Unable to update the private port of port forwarding rule as the rule has port range : " + rule.getSourcePortStart() + " " + "to " + rule.getSourcePortEnd());
}
if (virtualMachineId == null && vmGuestIp != null) {
throw new InvalidParameterValueException("vmguestip should be set along with virtualmachineid");
}
Ip dstIp = rule.getDestinationIpAddress();
if (virtualMachineId != null) {
// Verify that vm has nic in the network
final Nic guestNic = _networkModel.getNicInNetwork(virtualMachineId, rule.getNetworkId());
if (guestNic == null || guestNic.getIPv4Address() == null) {
throw new InvalidParameterValueException("Vm doesn't belong to network associated with ipAddress");
} else {
dstIp = new Ip(NetUtils.ip2Long(guestNic.getIPv4Address()));
}
if (vmGuestIp != null) {
// vm ip is passed so it can be primary or secondary ip addreess.
if (!dstIp.equals(vmGuestIp)) {
// the vm ip is secondary ip to the nic.
// is vmIp is secondary ip or not
final NicSecondaryIp secondaryIp = _nicSecondaryDao.findByIp4AddressAndNicId(vmGuestIp.toString(), guestNic.getId());
if (secondaryIp == null) {
throw new InvalidParameterValueException("IP Address is not in the VM nic's network ");
}
dstIp = vmGuestIp;
}
}
}
// revoke old rules at first
final List<PortForwardingRuleVO> rules = new ArrayList<>();
rule.setState(State.Revoke);
_portForwardingDao.update(id, rule);
rules.add(rule);
try {
if (!_firewallMgr.applyRules(rules, true, false)) {
throw new CloudRuntimeException("Failed to revoke the existing port forwarding rule:" + id);
}
} catch (final ResourceUnavailableException ex) {
throw new CloudRuntimeException("Failed to revoke the existing port forwarding rule:" + id + " due to ", ex);
}
rule = _portForwardingDao.findById(id);
rule.setState(State.Add);
if (privatePort != null) {
rule.setDestinationPortStart(privatePort.intValue());
rule.setDestinationPortEnd(privatePort.intValue());
}
if (virtualMachineId != null) {
rule.setVirtualMachineId(virtualMachineId);
rule.setDestinationIpAddress(dstIp);
}
_portForwardingDao.update(id, rule);
// apply new rules
if (!applyPortForwardingRules(rule.getSourceIpAddressId(), false, caller)) {
throw new CloudRuntimeException("Failed to apply the new port forwarding rule:" + id);
}
return _portForwardingDao.findById(id);
}
Aggregations