use of com.cloud.legacymodel.exceptions.CloudRuntimeException in project cosmic by MissionCriticalCloud.
the class DedicatedResourceManagerImpl method dedicateZone.
@Override
@DB
@ActionEvent(eventType = EventTypes.EVENT_DEDICATE_RESOURCE, eventDescription = "dedicating a Zone")
public List<DedicatedResourceVO> dedicateZone(final Long zoneId, final Long domainId, final String accountName) {
Long accountId = null;
List<HostVO> hosts = null;
if (accountName != null) {
final Account caller = CallContext.current().getCallingAccount();
final Account owner = _accountMgr.finalizeOwner(caller, accountName, domainId, null);
accountId = owner.getId();
}
final List<Long> childDomainIds = getDomainChildIds(domainId);
childDomainIds.add(domainId);
checkAccountAndDomain(accountId, domainId);
final Zone zone = zoneRepository.findById(zoneId).orElse(null);
if (zone == null) {
throw new InvalidParameterValueException("Unable to find zone by id " + zoneId);
} else {
final DedicatedResourceVO dedicatedZone = _dedicatedDao.findByZoneId(zoneId);
// check if zone is dedicated
if (dedicatedZone != null) {
s_logger.error("Zone " + zone.getName() + " is already dedicated");
throw new CloudRuntimeException("Zone " + zone.getName() + " is already dedicated");
}
// check if any resource under this zone is dedicated to different account or sub-domain
final List<HostPodVO> pods = _podDao.listByDataCenterId(zone.getId());
final List<DedicatedResourceVO> podsToRelease = new ArrayList<>();
final List<DedicatedResourceVO> clustersToRelease = new ArrayList<>();
final List<DedicatedResourceVO> hostsToRelease = new ArrayList<>();
for (final HostPodVO pod : pods) {
final DedicatedResourceVO dPod = _dedicatedDao.findByPodId(pod.getId());
if (dPod != null) {
if (!(childDomainIds.contains(dPod.getDomainId()))) {
throw new CloudRuntimeException("Pod " + pod.getName() + " under this Zone " + zone.getName() + " is dedicated to different account/domain");
}
if (accountId != null) {
if (dPod.getAccountId().equals(accountId)) {
podsToRelease.add(dPod);
} else {
s_logger.error("Pod " + pod.getName() + " under this Zone " + zone.getName() + " is dedicated to different account/domain");
throw new CloudRuntimeException("Pod " + pod.getName() + " under this Zone " + zone.getName() + " is dedicated to different account/domain");
}
} else {
if (dPod.getAccountId() == null && dPod.getDomainId().equals(domainId)) {
podsToRelease.add(dPod);
}
}
}
}
for (final DedicatedResourceVO dr : podsToRelease) {
releaseDedicatedResource(null, dr.getPodId(), null, null);
}
final List<ClusterVO> clusters = _clusterDao.listClustersByDcId(zone.getId());
for (final ClusterVO cluster : clusters) {
final DedicatedResourceVO dCluster = _dedicatedDao.findByClusterId(cluster.getId());
if (dCluster != null) {
if (!(childDomainIds.contains(dCluster.getDomainId()))) {
throw new CloudRuntimeException("Cluster " + cluster.getName() + " under this Zone " + zone.getName() + " is dedicated to different account/domain");
}
if (accountId != null) {
if (dCluster.getAccountId().equals(accountId)) {
clustersToRelease.add(dCluster);
} else {
s_logger.error("Cluster " + cluster.getName() + " under this Zone " + zone.getName() + " is dedicated to different account/domain");
throw new CloudRuntimeException("Cluster " + cluster.getName() + " under this Zone " + zone.getName() + " is dedicated to different account/domain");
}
} else {
if (dCluster.getAccountId() == null && dCluster.getDomainId().equals(domainId)) {
clustersToRelease.add(dCluster);
}
}
}
}
for (final DedicatedResourceVO dr : clustersToRelease) {
releaseDedicatedResource(null, null, dr.getClusterId(), null);
}
hosts = _hostDao.listByDataCenterId(zone.getId());
for (final HostVO host : hosts) {
final DedicatedResourceVO dHost = _dedicatedDao.findByHostId(host.getId());
if (dHost != null) {
if (!(childDomainIds.contains(dHost.getDomainId()))) {
throw new CloudRuntimeException("Host " + host.getName() + " under this Zone " + zone.getName() + " is dedicated to different account/domain");
}
if (accountId != null) {
if (dHost.getAccountId().equals(accountId)) {
hostsToRelease.add(dHost);
} else {
s_logger.error("Host " + host.getName() + " under this Zone " + zone.getName() + " is dedicated to different account/domain");
throw new CloudRuntimeException("Host " + host.getName() + " under this Zone " + zone.getName() + " is dedicated to different account/domain");
}
} else {
if (dHost.getAccountId() == null && dHost.getDomainId().equals(domainId)) {
hostsToRelease.add(dHost);
}
}
}
}
for (final DedicatedResourceVO dr : hostsToRelease) {
releaseDedicatedResource(null, null, null, dr.getHostId());
}
}
checkHostsSuitabilityForExplicitDedication(accountId, childDomainIds, hosts);
final Long accountIdFinal = accountId;
return Transaction.execute(new TransactionCallback<List<DedicatedResourceVO>>() {
@Override
public List<DedicatedResourceVO> doInTransaction(final TransactionStatus status) {
// find or create the affinity group by name under this account/domain
final AffinityGroup group = findOrCreateDedicatedAffinityGroup(domainId, accountIdFinal);
if (group == null) {
s_logger.error("Unable to dedicate zone due to, failed to create dedication affinity group");
throw new CloudRuntimeException("Failed to dedicate zone. Please contact Cloud Support.");
}
DedicatedResourceVO dedicatedResource = new DedicatedResourceVO(zoneId, null, null, null, null, null, group.getId());
try {
dedicatedResource.setDomainId(domainId);
if (accountIdFinal != null) {
dedicatedResource.setAccountId(accountIdFinal);
}
dedicatedResource = _dedicatedDao.persist(dedicatedResource);
// save the domainId in the zone
zone.setDomainId(domainId);
zoneRepository.save(zone);
} catch (final Exception e) {
s_logger.error("Unable to dedicate zone due to " + e.getMessage(), e);
throw new CloudRuntimeException("Failed to dedicate zone. Please contact Cloud Support.");
}
final List<DedicatedResourceVO> result = new ArrayList<>();
result.add(dedicatedResource);
return result;
}
});
}
use of com.cloud.legacymodel.exceptions.CloudRuntimeException in project cosmic by MissionCriticalCloud.
the class DedicatedResourceManagerImpl method checkHostSuitabilityForExplicitDedication.
private boolean checkHostSuitabilityForExplicitDedication(final Long accountId, final List<Long> domainIds, final long hostId) {
final boolean suitable = true;
final List<UserVmVO> allVmsOnHost = getVmsOnHost(hostId);
if (accountId != null) {
for (final UserVmVO vm : allVmsOnHost) {
if (vm.getAccountId() != accountId) {
s_logger.info("Host " + vm.getHostId() + " found to be unsuitable for explicit dedication as it is " + "running instances of another account");
throw new CloudRuntimeException("Host " + hostId + " found to be unsuitable for explicit dedication as it is " + "running instances of another account");
}
}
} else {
for (final UserVmVO vm : allVmsOnHost) {
if (!domainIds.contains(vm.getDomainId())) {
s_logger.info("Host " + vm.getHostId() + " found to be unsuitable for explicit dedication as it is " + "running instances of another domain");
throw new CloudRuntimeException("Host " + hostId + " found to be unsuitable for explicit dedication as it is " + "running instances of another domain");
}
}
}
return suitable;
}
use of com.cloud.legacymodel.exceptions.CloudRuntimeException in project cosmic by MissionCriticalCloud.
the class DeploymentPlanningManagerImpl method findSuitablePoolsForVolumes.
protected Pair<Map<Volume, List<StoragePool>>, List<Volume>> findSuitablePoolsForVolumes(final VirtualMachineProfile vmProfile, final DeploymentPlan plan, final ExcludeList avoid, final int returnUpTo) {
final List<VolumeVO> volumesTobeCreated = _volsDao.findUsableVolumesForInstance(vmProfile.getId());
final Map<Volume, List<StoragePool>> suitableVolumeStoragePools = new HashMap<>();
final List<Volume> readyAndReusedVolumes = new ArrayList<>();
// There should be atleast the ROOT volume of the VM in usable state
if (volumesTobeCreated.isEmpty()) {
throw new CloudRuntimeException("Unable to create deployment, no usable volumes found for the VM");
}
// don't allow to start vm that doesn't have a root volume
if (_volsDao.findByInstanceAndType(vmProfile.getId(), VolumeType.ROOT).isEmpty()) {
throw new CloudRuntimeException("Unable to prepare volumes for vm as ROOT volume is missing");
}
// for each volume find list of suitable storage pools by calling the
// allocators
Set<Long> originalAvoidPoolSet = avoid.getPoolsToAvoid();
if (originalAvoidPoolSet == null) {
originalAvoidPoolSet = new HashSet<>();
}
final Set<Long> poolsToAvoidOutput = new HashSet<>(originalAvoidPoolSet);
for (final VolumeVO toBeCreated : volumesTobeCreated) {
s_logger.debug("Checking suitable pools for volume (Id, Type): (" + toBeCreated.getId() + "," + toBeCreated.getVolumeType().name() + ")");
// be reused.
if (plan.getPoolId() != null || (toBeCreated.getVolumeType() == VolumeType.DATADISK && toBeCreated.getPoolId() != null && toBeCreated.getState() == Volume.State.Ready)) {
s_logger.debug("Volume has pool already allocated, checking if pool can be reused, poolId: " + toBeCreated.getPoolId());
final List<StoragePool> suitablePools = new ArrayList<>();
StoragePool pool = null;
if (toBeCreated.getPoolId() != null) {
pool = (StoragePool) dataStoreMgr.getPrimaryDataStore(toBeCreated.getPoolId());
} else {
pool = (StoragePool) dataStoreMgr.getPrimaryDataStore(plan.getPoolId());
}
if (!pool.isInMaintenance()) {
if (!avoid.shouldAvoid(pool)) {
final long exstPoolDcId = pool.getDataCenterId();
final long exstPoolPodId = pool.getPodId() != null ? pool.getPodId() : -1;
final long exstPoolClusterId = pool.getClusterId() != null ? pool.getClusterId() : -1;
boolean canReusePool = false;
if (plan.getDataCenterId() == exstPoolDcId && plan.getPodId() == exstPoolPodId && plan.getClusterId() == exstPoolClusterId) {
canReusePool = true;
} else if (plan.getDataCenterId() == exstPoolDcId) {
final DataStore dataStore = dataStoreMgr.getPrimaryDataStore(pool.getId());
if (dataStore != null && dataStore.getScope() != null && dataStore.getScope().getScopeType() == ScopeType.ZONE) {
canReusePool = true;
}
} else {
s_logger.debug("Pool of the volume does not fit the specified plan, need to reallocate a pool for this volume");
canReusePool = false;
}
if (canReusePool) {
s_logger.debug("Planner need not allocate a pool for this volume since its READY");
suitablePools.add(pool);
suitableVolumeStoragePools.put(toBeCreated, suitablePools);
if (!(toBeCreated.getState() == Volume.State.Allocated || toBeCreated.getState() == Volume.State.Creating)) {
readyAndReusedVolumes.add(toBeCreated);
}
continue;
}
} else {
s_logger.debug("Pool of the volume is in avoid set, need to reallocate a pool for this volume");
}
} else {
s_logger.debug("Pool of the volume is in maintenance, need to reallocate a pool for this volume");
}
}
if (s_logger.isDebugEnabled()) {
s_logger.debug("We need to allocate new storagepool for this volume");
}
if (!isRootAdmin(vmProfile)) {
if (!isEnabledForAllocation(plan.getDataCenterId(), plan.getPodId(), plan.getClusterId())) {
if (s_logger.isDebugEnabled()) {
s_logger.debug("Cannot allocate new storagepool for this volume in this cluster, allocation state is disabled");
s_logger.debug("Cannot deploy to this specified plan, allocation state is disabled, returning.");
}
// Cannot find suitable storage pools under this cluster for
// this volume since allocation_state is disabled.
// - remove any suitable pools found for other volumes.
// All volumes should get suitable pools under this cluster;
// else we cant use this cluster.
suitableVolumeStoragePools.clear();
break;
}
}
s_logger.debug("Calling StoragePoolAllocators to find suitable pools");
final DiskOfferingVO diskOffering = _diskOfferingDao.findById(toBeCreated.getDiskOfferingId());
if (vmProfile.getTemplate().getFormat() == ImageFormat.ISO && vmProfile.getServiceOffering().getTagsArray().length != 0) {
diskOffering.setTagsArray(Arrays.asList(vmProfile.getServiceOffering().getTagsArray()));
}
final DiskProfile diskProfile = new DiskProfile(toBeCreated, diskOffering, vmProfile.getHypervisorType());
boolean useLocalStorage = false;
if (vmProfile.getType() != VirtualMachineType.User) {
final Zone zone = zoneRepository.findById(plan.getDataCenterId()).orElse(null);
assert (zone != null) : "Invalid zone in deployment plan";
final Boolean useLocalStorageForSystemVM = ConfigurationManagerImpl.SystemVMUseLocalStorage.valueIn(zone.getId());
if (useLocalStorageForSystemVM != null) {
useLocalStorage = useLocalStorageForSystemVM.booleanValue();
s_logger.debug("System VMs will use " + (useLocalStorage ? "local" : "shared") + " storage for zone id=" + plan.getDataCenterId());
}
} else {
useLocalStorage = diskOffering.getUseLocalStorage();
// offering when it is a ROOT disk
if (!useLocalStorage && vmProfile.getServiceOffering().getUseLocalStorage()) {
if (toBeCreated.getVolumeType() == VolumeType.ROOT) {
useLocalStorage = true;
}
}
}
diskProfile.setUseLocalStorage(useLocalStorage);
boolean foundPotentialPools = false;
for (final StoragePoolAllocator allocator : _storagePoolAllocators) {
final List<StoragePool> suitablePools = allocator.allocateToPool(diskProfile, vmProfile, plan, avoid, returnUpTo);
if (suitablePools != null && !suitablePools.isEmpty()) {
suitableVolumeStoragePools.put(toBeCreated, suitablePools);
foundPotentialPools = true;
break;
}
}
if (avoid.getPoolsToAvoid() != null) {
poolsToAvoidOutput.addAll(avoid.getPoolsToAvoid());
avoid.getPoolsToAvoid().retainAll(originalAvoidPoolSet);
}
if (!foundPotentialPools) {
s_logger.debug("No suitable pools found for volume: " + toBeCreated + " under cluster: " + plan.getClusterId());
// No suitable storage pools found under this cluster for this
// volume. - remove any suitable pools found for other volumes.
// All volumes should get suitable pools under this cluster;
// else we cant use this cluster.
suitableVolumeStoragePools.clear();
break;
}
}
final HashSet<Long> toRemove = new HashSet<>();
for (final List<StoragePool> lsp : suitableVolumeStoragePools.values()) {
for (final StoragePool sp : lsp) {
toRemove.add(sp.getId());
}
}
poolsToAvoidOutput.removeAll(toRemove);
if (avoid.getPoolsToAvoid() != null) {
avoid.getPoolsToAvoid().addAll(poolsToAvoidOutput);
}
if (suitableVolumeStoragePools.isEmpty()) {
s_logger.debug("No suitable pools found");
}
return new Pair<>(suitableVolumeStoragePools, readyAndReusedVolumes);
}
use of com.cloud.legacymodel.exceptions.CloudRuntimeException in project cosmic by MissionCriticalCloud.
the class ConsoleProxyManagerImpl method createProxyInstance.
protected Map<String, Object> createProxyInstance(final long dataCenterId, final VMTemplateVO template) throws ConcurrentOperationException {
final long id = this._consoleProxyDao.getNextInSequence(Long.class, "id");
final String name = VirtualMachineName.getConsoleProxyName(id, this._instance);
final Zone zone = this.zoneRepository.findById(dataCenterId).orElse(null);
final Account systemAcct = this._accountMgr.getSystemAccount();
final DataCenterDeployment plan = new DataCenterDeployment(dataCenterId);
final NetworkVO defaultNetwork = getDefaultNetworkForCreation(zone);
final List<? extends NetworkOffering> offerings = this._networkModel.getSystemAccountNetworkOfferings(NetworkOffering.SystemControlNetwork, NetworkOffering.SystemManagementNetwork);
final LinkedHashMap<Network, List<? extends NicProfile>> networks = new LinkedHashMap<>(offerings.size() + 1);
final NicProfile defaultNic = new NicProfile();
defaultNic.setDefaultNic(true);
networks.put(this._networkMgr.setupNetwork(systemAcct, this._networkOfferingDao.findById(defaultNetwork.getNetworkOfferingId()), plan, null, null, false).get(0), new ArrayList<>(Arrays.asList(defaultNic)));
for (final NetworkOffering offering : offerings) {
networks.put(this._networkMgr.setupNetwork(systemAcct, offering, plan, null, null, false).get(0), new ArrayList<>());
}
ServiceOfferingVO serviceOffering = this._serviceOffering;
if (serviceOffering == null) {
serviceOffering = this._offeringDao.findDefaultSystemOffering(ServiceOffering.consoleProxyDefaultOffUniqueName, ConfigurationManagerImpl.SystemVMUseLocalStorage.valueIn(dataCenterId));
}
ConsoleProxyVO proxy = new ConsoleProxyVO(id, serviceOffering.getId(), name, template.getId(), template.getHypervisorType(), template.getGuestOSId(), dataCenterId, systemAcct.getDomainId(), systemAcct.getId(), this._accountMgr.getSystemUser().getId(), 0, serviceOffering.getOfferHA(), template.getOptimiseFor(), template.getManufacturerString(), template.getCpuFlags(), template.getMacLearning(), false, template.getMaintenancePolicy());
proxy.setDynamicallyScalable(template.isDynamicallyScalable());
proxy = this._consoleProxyDao.persist(proxy);
try {
this._itMgr.allocate(name, template, serviceOffering, networks, plan, null);
} catch (final InsufficientCapacityException e) {
logger.warn("InsufficientCapacity", e);
throw new CloudRuntimeException("Insufficient capacity exception", e);
}
final Map<String, Object> context = new HashMap<>();
context.put("dc", zone);
final HostPodVO pod = this._podDao.findById(proxy.getPodIdToDeployIn());
context.put("pod", pod);
context.put("proxyVmId", proxy.getId());
return context;
}
use of com.cloud.legacymodel.exceptions.CloudRuntimeException in project cosmic by MissionCriticalCloud.
the class ConsoleProxyManagerImpl method startNew.
public ConsoleProxyVO startNew(final long dataCenterId) throws ConcurrentOperationException {
logger.debug("Assign console proxy from a newly started instance for request from data center : " + dataCenterId);
if (!allowToLaunchNew(dataCenterId)) {
logger.warn("The number of launched console proxy on zone " + dataCenterId + " has reached to limit");
return null;
}
final HypervisorType availableHypervisor = this._resourceMgr.getAvailableHypervisor(dataCenterId);
final String templateName = retrieveTemplateName(dataCenterId);
final VMTemplateVO template = this._templateDao.findRoutingTemplate(availableHypervisor, templateName, dataCenterId);
if (template == null) {
throw new CloudRuntimeException("Not able to find the System templates or not downloaded in zone " + dataCenterId);
}
final Map<String, Object> context = createProxyInstance(dataCenterId, template);
final long proxyVmId = (Long) context.get("proxyVmId");
if (proxyVmId == 0) {
logger.trace("Creating proxy instance failed, data center id : " + dataCenterId);
return null;
}
final ConsoleProxyVO proxy = this._consoleProxyDao.findById(proxyVmId);
if (proxy != null) {
SubscriptionMgr.getInstance().notifySubscribers(ConsoleProxyManager.ALERT_SUBJECT, this, new ConsoleProxyAlertEventArgs(ConsoleProxyAlertEventArgs.PROXY_CREATED, dataCenterId, proxy.getId(), proxy, null));
return proxy;
} else {
logger.debug("Unable to allocate console proxy storage, remove the console proxy record from DB, proxy id: " + proxyVmId);
}
return null;
}
Aggregations