use of com.cloud.storage.SnapshotVO in project cosmic by MissionCriticalCloud.
the class StorageSystemSnapshotStrategy method deleteSnapshot.
@Override
public boolean deleteSnapshot(final Long snapshotId) {
final SnapshotVO snapshotVO = _snapshotDao.findById(snapshotId);
if (Snapshot.State.Destroyed.equals(snapshotVO.getState())) {
return true;
}
if (Snapshot.State.Error.equals(snapshotVO.getState())) {
_snapshotDao.remove(snapshotId);
return true;
}
if (!Snapshot.State.BackedUp.equals(snapshotVO.getState())) {
throw new InvalidParameterValueException("Unable to delete snapshotshot " + snapshotId + " because it is in the following state: " + snapshotVO.getState());
}
final SnapshotObject snapshotObj = (SnapshotObject) _snapshotDataFactory.getSnapshot(snapshotId, DataStoreRole.Primary);
if (snapshotObj == null) {
s_logger.debug("Can't find snapshot; deleting it in DB");
_snapshotDao.remove(snapshotId);
return true;
}
if (ObjectInDataStoreStateMachine.State.Copying.equals(snapshotObj.getStatus())) {
throw new InvalidParameterValueException("Unable to delete snapshotshot " + snapshotId + " because it is in the copying state.");
}
try {
snapshotObj.processEvent(Snapshot.Event.DestroyRequested);
} catch (final NoTransitionException e) {
s_logger.debug("Failed to set the state to destroying: ", e);
return false;
}
try {
snapshotSvr.deleteSnapshot(snapshotObj);
snapshotObj.processEvent(Snapshot.Event.OperationSucceeded);
} catch (final Exception e) {
s_logger.debug("Failed to delete snapshot: ", e);
try {
snapshotObj.processEvent(Snapshot.Event.OperationFailed);
} catch (final NoTransitionException e1) {
s_logger.debug("Failed to change snapshot state: " + e.toString());
}
return false;
}
return true;
}
use of com.cloud.storage.SnapshotVO in project cosmic by MissionCriticalCloud.
the class XenserverSnapshotStrategy method revertSnapshot.
@Override
public boolean revertSnapshot(final SnapshotInfo snapshot) {
if (canHandle(snapshot, SnapshotOperation.REVERT) == StrategyPriority.CANT_HANDLE) {
throw new UnsupportedOperationException("Reverting not supported. Create a template or volume based on the snapshot instead.");
}
final SnapshotVO snapshotVO = snapshotDao.acquireInLockTable(snapshot.getId());
if (snapshotVO == null) {
throw new CloudRuntimeException("Failed to get lock on snapshot:" + snapshot.getId());
}
try {
final VolumeInfo volumeInfo = snapshot.getBaseVolume();
final StoragePool store = (StoragePool) volumeInfo.getDataStore();
if (store != null && store.getStatus() != StoragePoolStatus.Up) {
snapshot.processEvent(Event.OperationFailed);
throw new CloudRuntimeException("store is not in up state");
}
volumeInfo.stateTransit(Volume.Event.RevertSnapshotRequested);
boolean result = false;
try {
result = snapshotSvr.revertSnapshot(snapshot);
if (!result) {
s_logger.debug("Failed to revert snapshot: " + snapshot.getId());
throw new CloudRuntimeException("Failed to revert snapshot: " + snapshot.getId());
}
} finally {
if (result) {
volumeInfo.stateTransit(Volume.Event.OperationSucceeded);
} else {
volumeInfo.stateTransit(Volume.Event.OperationFailed);
}
}
return result;
} finally {
if (snapshotVO != null) {
snapshotDao.releaseFromLockTable(snapshot.getId());
}
}
}
use of com.cloud.storage.SnapshotVO in project cosmic by MissionCriticalCloud.
the class XenserverSnapshotStrategy method takeSnapshot.
@Override
@DB
public SnapshotInfo takeSnapshot(SnapshotInfo snapshot) {
final Object payload = snapshot.getPayload();
if (payload != null) {
final CreateSnapshotPayload createSnapshotPayload = (CreateSnapshotPayload) payload;
if (createSnapshotPayload.getQuiescevm()) {
throw new InvalidParameterValueException("can't handle quiescevm equal true for volume snapshot");
}
}
final SnapshotVO snapshotVO = snapshotDao.acquireInLockTable(snapshot.getId());
if (snapshotVO == null) {
throw new CloudRuntimeException("Failed to get lock on snapshot:" + snapshot.getId());
}
try {
final VolumeInfo volumeInfo = snapshot.getBaseVolume();
volumeInfo.stateTransit(Volume.Event.SnapshotRequested);
SnapshotResult result = null;
try {
result = snapshotSvr.takeSnapshot(snapshot);
if (result.isFailed()) {
s_logger.debug("Failed to take snapshot: " + result.getResult());
throw new CloudRuntimeException(result.getResult());
}
} finally {
if (result != null && result.isSuccess()) {
volumeInfo.stateTransit(Volume.Event.OperationSucceeded);
} else {
volumeInfo.stateTransit(Volume.Event.OperationFailed);
}
}
snapshot = result.getSnashot();
final DataStore primaryStore = snapshot.getDataStore();
final boolean backupFlag = Boolean.parseBoolean(configDao.getValue(Config.BackupSnapshotAfterTakingSnapshot.toString()));
final SnapshotInfo backupedSnapshot;
if (backupFlag) {
backupedSnapshot = backupSnapshot(snapshot);
} else {
// Fake it to get the transitions to fire in the proper order
s_logger.debug("skipping backup of snapshot due to configuration " + Config.BackupSnapshotAfterTakingSnapshot.toString());
final SnapshotObject snapObj = (SnapshotObject) snapshot;
try {
snapObj.processEvent(Snapshot.Event.OperationNotPerformed);
} catch (final NoTransitionException e) {
s_logger.debug("Failed to change state: " + snapshot.getId() + ": " + e.toString());
throw new CloudRuntimeException(e.toString());
}
backupedSnapshot = snapshot;
}
try {
final SnapshotInfo parent = snapshot.getParent();
if (backupedSnapshot != null && parent != null) {
Long parentSnapshotId = parent.getId();
while (parentSnapshotId != null && parentSnapshotId != 0L) {
final SnapshotDataStoreVO snapshotDataStoreVO = snapshotStoreDao.findByStoreSnapshot(primaryStore.getRole(), primaryStore.getId(), parentSnapshotId);
if (snapshotDataStoreVO != null) {
parentSnapshotId = snapshotDataStoreVO.getParentSnapshotId();
snapshotStoreDao.remove(snapshotDataStoreVO.getId());
} else {
parentSnapshotId = null;
}
}
final SnapshotDataStoreVO snapshotDataStoreVO = snapshotStoreDao.findByStoreSnapshot(primaryStore.getRole(), primaryStore.getId(), snapshot.getId());
if (snapshotDataStoreVO != null) {
snapshotDataStoreVO.setParentSnapshotId(0L);
snapshotStoreDao.update(snapshotDataStoreVO.getId(), snapshotDataStoreVO);
}
}
} catch (final Exception e) {
s_logger.debug("Failed to clean up snapshots on primary storage", e);
}
return backupedSnapshot;
} finally {
if (snapshotVO != null) {
snapshotDao.releaseFromLockTable(snapshot.getId());
}
}
}
use of com.cloud.storage.SnapshotVO in project cosmic by MissionCriticalCloud.
the class UserVmManagerImpl method moveVMToUser.
@DB
@Override
@ActionEvent(eventType = EventTypes.EVENT_VM_MOVE, eventDescription = "move VM to another user", async = false)
public UserVm moveVMToUser(final AssignVMCmd cmd) throws ResourceAllocationException, ConcurrentOperationException, ResourceUnavailableException, InsufficientCapacityException {
// VERIFICATIONS and VALIDATIONS
// VV 1: verify the two users
final Account caller = CallContext.current().getCallingAccount();
if (!_accountMgr.isRootAdmin(caller.getId()) && !_accountMgr.isDomainAdmin(caller.getId())) {
// VMs
throw new InvalidParameterValueException("Only domain admins are allowed to assign VMs and not " + caller.getType());
}
// get and check the valid VM
final UserVmVO vm = _vmDao.findById(cmd.getVmId());
if (vm == null) {
throw new InvalidParameterValueException("There is no vm by that id " + cmd.getVmId());
} else if (vm.getState() == State.Running) {
// running
if (s_logger.isDebugEnabled()) {
s_logger.debug("VM is Running, unable to move the vm " + vm);
}
final InvalidParameterValueException ex = new InvalidParameterValueException("VM is Running, unable to move the vm with specified vmId");
ex.addProxyObject(vm.getUuid(), "vmId");
throw ex;
}
final Account oldAccount = _accountService.getActiveAccountById(vm.getAccountId());
if (oldAccount == null) {
throw new InvalidParameterValueException("Invalid account for VM " + vm.getAccountId() + " in domain.");
}
// don't allow to move the vm from the project
if (oldAccount.getType() == Account.ACCOUNT_TYPE_PROJECT) {
final InvalidParameterValueException ex = new InvalidParameterValueException("Specified Vm id belongs to the project and can't be moved");
ex.addProxyObject(vm.getUuid(), "vmId");
throw ex;
}
final Account newAccount = _accountService.getActiveAccountByName(cmd.getAccountName(), cmd.getDomainId());
if (newAccount == null || newAccount.getType() == Account.ACCOUNT_TYPE_PROJECT) {
throw new InvalidParameterValueException("Invalid accountid=" + cmd.getAccountName() + " in domain " + cmd.getDomainId());
}
if (newAccount.getState() == Account.State.disabled) {
throw new InvalidParameterValueException("The new account owner " + cmd.getAccountName() + " is disabled.");
}
// check caller has access to both the old and new account
_accountMgr.checkAccess(caller, null, true, oldAccount);
_accountMgr.checkAccess(caller, null, true, newAccount);
// make sure the accounts are not same
if (oldAccount.getAccountId() == newAccount.getAccountId()) {
throw new InvalidParameterValueException("The new account is the same as the old account. Account id =" + oldAccount.getAccountId());
}
// don't allow to move the vm if there are existing PF/LB/Static Nat
// rules, or vm is assigned to static Nat ip
final List<PortForwardingRuleVO> pfrules = _portForwardingDao.listByVm(cmd.getVmId());
if (pfrules != null && pfrules.size() > 0) {
throw new InvalidParameterValueException("Remove the Port forwarding rules for this VM before assigning to another user.");
}
final List<FirewallRuleVO> snrules = _rulesDao.listStaticNatByVmId(vm.getId());
if (snrules != null && snrules.size() > 0) {
throw new InvalidParameterValueException("Remove the StaticNat rules for this VM before assigning to another user.");
}
final List<LoadBalancerVMMapVO> maps = _loadBalancerVMMapDao.listByInstanceId(vm.getId());
if (maps != null && maps.size() > 0) {
throw new InvalidParameterValueException("Remove the load balancing rules for this VM before assigning to another user.");
}
// check for one on one nat
final List<IPAddressVO> ips = _ipAddressDao.findAllByAssociatedVmId(cmd.getVmId());
for (final IPAddressVO ip : ips) {
if (ip.isOneToOneNat()) {
throw new InvalidParameterValueException("Remove the one to one nat rule for this VM for ip " + ip.toString());
}
}
final Zone zone = zoneRepository.findOne(vm.getDataCenterId());
// Get serviceOffering and Volumes for Virtual Machine
final ServiceOfferingVO offering = _serviceOfferingDao.findByIdIncludingRemoved(vm.getId(), vm.getServiceOfferingId());
final List<VolumeVO> volumes = _volsDao.findByInstance(cmd.getVmId());
// Remove vm from instance group
removeInstanceFromInstanceGroup(cmd.getVmId());
// VV 2: check if account/domain is with in resource limits to create a new vm
resourceLimitCheck(newAccount, vm.isDisplayVm(), new Long(offering.getCpu()), new Long(offering.getRamSize()));
// VV 3: check if volumes and primary storage space are with in resource limits
_resourceLimitMgr.checkResourceLimit(newAccount, ResourceType.volume, _volsDao.findByInstance(cmd.getVmId()).size());
Long totalVolumesSize = (long) 0;
for (final VolumeVO volume : volumes) {
totalVolumesSize += volume.getSize();
}
_resourceLimitMgr.checkResourceLimit(newAccount, ResourceType.primary_storage, totalVolumesSize);
// VV 4: Check if new owner can use the vm template
final VirtualMachineTemplate template = _templateDao.findById(vm.getTemplateId());
if (!template.isPublicTemplate()) {
final Account templateOwner = _accountMgr.getAccount(template.getAccountId());
_accountMgr.checkAccess(newAccount, null, true, templateOwner);
}
// VV 5: check the new account can create vm in the domain
final DomainVO domain = _domainDao.findById(cmd.getDomainId());
_accountMgr.checkAccess(newAccount, domain);
Transaction.execute(new TransactionCallbackNoReturn() {
@Override
public void doInTransactionWithoutResult(final TransactionStatus status) {
// update resource counts for old account
resourceCountDecrement(oldAccount.getAccountId(), vm.isDisplayVm(), new Long(offering.getCpu()), new Long(offering.getRamSize()));
// OWNERSHIP STEP 1: update the vm owner
vm.setAccountId(newAccount.getAccountId());
vm.setDomainId(cmd.getDomainId());
_vmDao.persist(vm);
// OS 2: update volume
for (final VolumeVO volume : volumes) {
_resourceLimitMgr.decrementResourceCount(oldAccount.getAccountId(), ResourceType.volume);
_resourceLimitMgr.decrementResourceCount(oldAccount.getAccountId(), ResourceType.primary_storage, new Long(volume.getSize()));
volume.setAccountId(newAccount.getAccountId());
volume.setDomainId(newAccount.getDomainId());
_volsDao.persist(volume);
_resourceLimitMgr.incrementResourceCount(newAccount.getAccountId(), ResourceType.volume);
_resourceLimitMgr.incrementResourceCount(newAccount.getAccountId(), ResourceType.primary_storage, new Long(volume.getSize()));
// snapshots: mark these removed in db
final List<SnapshotVO> snapshots = _snapshotDao.listByVolumeIdIncludingRemoved(volume.getId());
for (final SnapshotVO snapshot : snapshots) {
_snapshotDao.remove(snapshot.getId());
}
}
// update resource count of new account
resourceCountIncrement(newAccount.getAccountId(), vm.isDisplayVm(), new Long(offering.getCpu()), new Long(offering.getRamSize()));
}
});
final VirtualMachine vmoi = _itMgr.findById(vm.getId());
final VirtualMachineProfileImpl vmOldProfile = new VirtualMachineProfileImpl(vmoi);
// OS 3: update the network
final List<Long> networkIdList = cmd.getNetworkIds();
if (zone.getNetworkType() == NetworkType.Basic) {
if (networkIdList != null && !networkIdList.isEmpty()) {
throw new InvalidParameterValueException("Can't move vm with network Ids; this is a basic zone VM");
}
// cleanup the network for the oldOwner
_networkMgr.cleanupNics(vmOldProfile);
_networkMgr.expungeNics(vmOldProfile);
// security groups will be recreated for the new account, when the
// VM is started
final List<NetworkVO> networkList = new ArrayList<>();
// Get default guest network in Basic zone
final Network defaultNetwork = _networkModel.getExclusiveGuestNetwork(zone.getId());
if (defaultNetwork == null) {
throw new InvalidParameterValueException("Unable to find a default network to start a vm");
} else {
networkList.add(_networkDao.findById(defaultNetwork.getId()));
}
final LinkedHashMap<Network, List<? extends NicProfile>> networks = new LinkedHashMap<>();
final NicProfile profile = new NicProfile();
profile.setDefaultNic(true);
networks.put(networkList.get(0), new ArrayList<>(Arrays.asList(profile)));
final VirtualMachine vmi = _itMgr.findById(vm.getId());
final VirtualMachineProfileImpl vmProfile = new VirtualMachineProfileImpl(vmi);
_networkMgr.allocate(vmProfile, networks);
} else {
// cleanup the network for the oldOwner
_networkMgr.cleanupNics(vmOldProfile);
_networkMgr.expungeNics(vmOldProfile);
final Set<NetworkVO> applicableNetworks = new HashSet<>();
if (networkIdList != null && !networkIdList.isEmpty()) {
// add any additional networks
for (final Long networkId : networkIdList) {
final NetworkVO network = _networkDao.findById(networkId);
if (network == null) {
final InvalidParameterValueException ex = new InvalidParameterValueException("Unable to find specified network id");
ex.addProxyObject(networkId.toString(), "networkId");
throw ex;
}
_networkModel.checkNetworkPermissions(newAccount, network);
// don't allow to use system networks
final NetworkOffering networkOffering = _entityMgr.findById(NetworkOffering.class, network.getNetworkOfferingId());
if (networkOffering.isSystemOnly()) {
final InvalidParameterValueException ex = new InvalidParameterValueException("Specified Network id is system only and can't be used for vm deployment");
ex.addProxyObject(network.getUuid(), "networkId");
throw ex;
}
applicableNetworks.add(network);
}
} else {
final NetworkVO defaultNetwork;
final List<NetworkOfferingVO> requiredOfferings = _networkOfferingDao.listByAvailability(Availability.Required, false);
if (requiredOfferings.size() < 1) {
throw new InvalidParameterValueException("Unable to find network offering with availability=" + Availability.Required + " to automatically create the network as a part of vm creation");
}
if (requiredOfferings.get(0).getState() == NetworkOffering.State.Enabled) {
// get Virtual networks
final List<? extends Network> virtualNetworks = _networkModel.listNetworksForAccount(newAccount.getId(), zone.getId(), Network.GuestType.Isolated);
if (virtualNetworks.isEmpty()) {
final long physicalNetworkId = _networkModel.findPhysicalNetworkId(zone.getId(), requiredOfferings.get(0).getTags(), requiredOfferings.get(0).getTrafficType());
// Validate physical network
final PhysicalNetwork physicalNetwork = _physicalNetworkDao.findById(physicalNetworkId);
if (physicalNetwork == null) {
throw new InvalidParameterValueException("Unable to find physical network with id: " + physicalNetworkId + " and tag: " + requiredOfferings.get(0).getTags());
}
s_logger.debug("Creating network for account " + newAccount + " from the network offering id=" + requiredOfferings.get(0).getId() + " as a part of deployVM process");
Network newNetwork = _networkMgr.createGuestNetwork(requiredOfferings.get(0).getId(), newAccount.getAccountName() + "-network", newAccount.getAccountName() + "-network", null, null, null, null, newAccount, null, physicalNetwork, zone.getId(), ACLType.Account, null, null, null, null, true, null, null, null, null);
// if the network offering has persistent set to true, implement the network
if (requiredOfferings.get(0).getIsPersistent()) {
final DeployDestination dest = new DeployDestination(zone, null, null, null);
final UserVO callerUser = _userDao.findById(CallContext.current().getCallingUserId());
final Journal journal = new Journal.LogJournal("Implementing " + newNetwork, s_logger);
final ReservationContext context = new ReservationContextImpl(UUID.randomUUID().toString(), journal, callerUser, caller);
s_logger.debug("Implementing the network for account" + newNetwork + " as a part of" + " network provision for persistent networks");
try {
final Pair<? extends NetworkGuru, ? extends Network> implementedNetwork = _networkMgr.implementNetwork(newNetwork.getId(), dest, context);
if (implementedNetwork == null || implementedNetwork.first() == null) {
s_logger.warn("Failed to implement the network " + newNetwork);
}
newNetwork = implementedNetwork.second();
} catch (final Exception ex) {
s_logger.warn("Failed to implement network " + newNetwork + " elements and" + " resources as a part of network provision for persistent network due to ", ex);
final CloudRuntimeException e = new CloudRuntimeException("Failed to implement network" + " (with specified id) elements and resources as a part of network provision");
e.addProxyObject(newNetwork.getUuid(), "networkId");
throw e;
}
}
defaultNetwork = _networkDao.findById(newNetwork.getId());
} else if (virtualNetworks.size() > 1) {
throw new InvalidParameterValueException("More than 1 default Isolated networks are found " + "for account " + newAccount + "; please specify networkIds");
} else {
defaultNetwork = _networkDao.findById(virtualNetworks.get(0).getId());
}
} else {
throw new InvalidParameterValueException("Required network offering id=" + requiredOfferings.get(0).getId() + " is not in " + NetworkOffering.State.Enabled);
}
applicableNetworks.add(defaultNetwork);
}
// add the new nics
final LinkedHashMap<Network, List<? extends NicProfile>> networks = new LinkedHashMap<>();
int toggle = 0;
for (final NetworkVO appNet : applicableNetworks) {
final NicProfile defaultNic = new NicProfile();
if (toggle == 0) {
defaultNic.setDefaultNic(true);
toggle++;
}
networks.put(appNet, new ArrayList<>(Arrays.asList(defaultNic)));
}
final VirtualMachine vmi = _itMgr.findById(vm.getId());
final VirtualMachineProfileImpl vmProfile = new VirtualMachineProfileImpl(vmi);
_networkMgr.allocate(vmProfile, networks);
s_logger.debug("AssignVM: Advance virtual, adding networks no " + networks.size() + " to " + vm.getInstanceName());
}
// END IF ADVANCED
s_logger.info("AssignVM: vm " + vm.getInstanceName() + " now belongs to account " + cmd.getAccountName());
return vm;
}
use of com.cloud.storage.SnapshotVO in project cosmic by MissionCriticalCloud.
the class TemplateManagerImplTest method testCreatePrivateTemplateRecordForRegionStore.
@Test
public void testCreatePrivateTemplateRecordForRegionStore() throws ResourceAllocationException {
final CreateTemplateCmd mockCreateCmd = mock(CreateTemplateCmd.class);
when(mockCreateCmd.getTemplateName()).thenReturn("test");
when(mockCreateCmd.getTemplateTag()).thenReturn(null);
when(mockCreateCmd.getBits()).thenReturn(64);
when(mockCreateCmd.getRequiresHvm()).thenReturn(true);
when(mockCreateCmd.isPasswordEnabled()).thenReturn(false);
when(mockCreateCmd.isPublic()).thenReturn(false);
when(mockCreateCmd.isFeatured()).thenReturn(false);
when(mockCreateCmd.isDynamicallyScalable()).thenReturn(false);
when(mockCreateCmd.getVolumeId()).thenReturn(null);
when(mockCreateCmd.getSnapshotId()).thenReturn(1L);
when(mockCreateCmd.getOsTypeId()).thenReturn(1L);
when(mockCreateCmd.getEventDescription()).thenReturn("test");
when(mockCreateCmd.getDetails()).thenReturn(null);
final Account mockTemplateOwner = mock(Account.class);
final SnapshotVO mockSnapshot = mock(SnapshotVO.class);
when(snapshotDao.findById(anyLong())).thenReturn(mockSnapshot);
when(mockSnapshot.getVolumeId()).thenReturn(1L);
when(mockSnapshot.getState()).thenReturn(Snapshot.State.BackedUp);
when(mockSnapshot.getHypervisorType()).thenReturn(Hypervisor.HypervisorType.XenServer);
doNothing().when(resourceLimitMgr).checkResourceLimit(any(Account.class), eq(Resource.ResourceType.template));
doNothing().when(resourceLimitMgr).checkResourceLimit(any(Account.class), eq(Resource.ResourceType.secondary_storage), anyLong());
final GuestOSVO mockGuestOS = mock(GuestOSVO.class);
when(guestOSDao.findById(anyLong())).thenReturn(mockGuestOS);
when(tmpltDao.getNextInSequence(eq(Long.class), eq("id"))).thenReturn(1L);
final List<ImageStoreVO> mockRegionStores = new ArrayList<>();
final ImageStoreVO mockRegionStore = mock(ImageStoreVO.class);
mockRegionStores.add(mockRegionStore);
when(imgStoreDao.findRegionImageStores()).thenReturn(mockRegionStores);
when(tmpltDao.persist(any(VMTemplateVO.class))).thenAnswer(new Answer<VMTemplateVO>() {
@Override
public VMTemplateVO answer(final InvocationOnMock invocationOnMock) throws Throwable {
final Object[] args = invocationOnMock.getArguments();
return (VMTemplateVO) args[0];
}
});
final VMTemplateVO template = templateManager.createPrivateTemplateRecord(mockCreateCmd, mockTemplateOwner);
assertTrue("Template in a region store should have cross zones set", template.isCrossZones());
}
Aggregations