Search in sources :

Example 56 with VMTemplateVO

use of com.cloud.storage.VMTemplateVO in project cloudstack by apache.

the class UserVmManagerImpl method resetVMSSHKey.

@Override
@ActionEvent(eventType = EventTypes.EVENT_VM_RESETSSHKEY, eventDescription = "resetting Vm SSHKey", async = true)
public UserVm resetVMSSHKey(ResetVMSSHKeyCmd cmd) throws ResourceUnavailableException, InsufficientCapacityException {
    Account caller = CallContext.current().getCallingAccount();
    Account owner = _accountMgr.finalizeOwner(caller, cmd.getAccountName(), cmd.getDomainId(), cmd.getProjectId());
    Long vmId = cmd.getId();
    UserVmVO userVm = _vmDao.findById(cmd.getId());
    if (userVm == null) {
        throw new InvalidParameterValueException("unable to find a virtual machine by id" + cmd.getId());
    }
    _vmDao.loadDetails(userVm);
    VMTemplateVO template = _templateDao.findByIdIncludingRemoved(userVm.getTemplateId());
    if (userVm.getState() == State.Error || userVm.getState() == State.Expunging) {
        s_logger.error("vm is not in the right state: " + vmId);
        throw new InvalidParameterValueException("Vm with specified id is not in the right state");
    }
    if (userVm.getState() != State.Stopped) {
        s_logger.error("vm is not in the right state: " + vmId);
        throw new InvalidParameterValueException("Vm " + userVm + " should be stopped to do SSH Key reset");
    }
    SSHKeyPairVO s = _sshKeyPairDao.findByName(owner.getAccountId(), owner.getDomainId(), cmd.getName());
    if (s == null) {
        throw new InvalidParameterValueException("A key pair with name '" + cmd.getName() + "' does not exist for account " + owner.getAccountName() + " in specified domain id");
    }
    _accountMgr.checkAccess(caller, null, true, userVm);
    String password = null;
    String sshPublicKey = s.getPublicKey();
    if (template != null && template.getEnablePassword()) {
        password = _mgr.generateRandomPassword();
    }
    boolean result = resetVMSSHKeyInternal(vmId, sshPublicKey, password);
    if (result) {
        userVm.setDetail("SSH.PublicKey", sshPublicKey);
        if (template != null && template.getEnablePassword()) {
            userVm.setPassword(password);
            //update the encrypted password in vm_details table too
            encryptAndStorePassword(userVm, password);
        }
        _vmDao.saveDetails(userVm);
    } else {
        throw new CloudRuntimeException("Failed to reset SSH Key for the virtual machine ");
    }
    return userVm;
}
Also used : Account(com.cloud.user.Account) InvalidParameterValueException(com.cloud.exception.InvalidParameterValueException) CloudRuntimeException(com.cloud.utils.exception.CloudRuntimeException) VMTemplateVO(com.cloud.storage.VMTemplateVO) SSHKeyPairVO(com.cloud.user.SSHKeyPairVO) ActionEvent(com.cloud.event.ActionEvent)

Example 57 with VMTemplateVO

use of com.cloud.storage.VMTemplateVO in project cloudstack by apache.

the class LoadBalanceRuleHandler method deployELBVm.

private DomainRouterVO deployELBVm(Network guestNetwork, final DeployDestination dest, Account owner, final Map<Param, Object> params) throws ConcurrentOperationException, InsufficientCapacityException {
    final long dcId = dest.getDataCenter().getId();
    // lock guest network
    final Long guestNetworkId = guestNetwork.getId();
    guestNetwork = _networkDao.acquireInLockTable(guestNetworkId);
    if (guestNetwork == null) {
        throw new ConcurrentOperationException("Unable to acquire network lock: " + guestNetworkId);
    }
    try {
        if (_networkModel.isNetworkSystem(guestNetwork) || guestNetwork.getGuestType() == Network.GuestType.Shared) {
            owner = _accountService.getSystemAccount();
        }
        if (s_logger.isDebugEnabled()) {
            s_logger.debug("Starting a ELB vm for network configurations: " + guestNetwork + " in " + dest);
        }
        assert guestNetwork.getState() == Network.State.Implemented || guestNetwork.getState() == Network.State.Setup || guestNetwork.getState() == Network.State.Implementing : "Network is not yet fully implemented: " + guestNetwork;
        DataCenterDeployment plan = null;
        DomainRouterVO elbVm = null;
        plan = new DataCenterDeployment(dcId, dest.getPod().getId(), null, null, null, null);
        if (elbVm == null) {
            final long id = _routerDao.getNextInSequence(Long.class, "id");
            if (s_logger.isDebugEnabled()) {
                s_logger.debug("Creating the ELB vm " + id);
            }
            final List<? extends NetworkOffering> offerings = _networkModel.getSystemAccountNetworkOfferings(NetworkOffering.SystemControlNetwork);
            final NetworkOffering controlOffering = offerings.get(0);
            final Network controlConfig = _networkMgr.setupNetwork(_systemAcct, controlOffering, plan, null, null, false).get(0);
            final LinkedHashMap<Network, List<? extends NicProfile>> networks = new LinkedHashMap<Network, List<? extends NicProfile>>(2);
            final NicProfile guestNic = new NicProfile();
            guestNic.setDefaultNic(true);
            networks.put(controlConfig, new ArrayList<NicProfile>());
            networks.put(guestNetwork, new ArrayList<NicProfile>(Arrays.asList(guestNic)));
            final VMTemplateVO template = _templateDao.findSystemVMTemplate(dcId);
            final String typeString = "ElasticLoadBalancerVm";
            final Long physicalNetworkId = _networkModel.getPhysicalNetworkId(guestNetwork);
            final PhysicalNetworkServiceProvider provider = _physicalProviderDao.findByServiceProvider(physicalNetworkId, typeString);
            if (provider == null) {
                throw new CloudRuntimeException("Cannot find service provider " + typeString + " in physical network " + physicalNetworkId);
            }
            final VirtualRouterProvider vrProvider = _vrProviderDao.findByNspIdAndType(provider.getId(), Type.ElasticLoadBalancerVm);
            if (vrProvider == null) {
                throw new CloudRuntimeException("Cannot find virtual router provider " + typeString + " as service provider " + provider.getId());
            }
            long userId = CallContext.current().getCallingUserId();
            if (CallContext.current().getCallingAccount().getId() != owner.getId()) {
                List<UserVO> userVOs = _userDao.listByAccount(owner.getAccountId());
                if (!userVOs.isEmpty()) {
                    userId = userVOs.get(0).getId();
                }
            }
            ServiceOfferingVO elasticLbVmOffering = _serviceOfferingDao.findDefaultSystemOffering(ServiceOffering.elbVmDefaultOffUniqueName, ConfigurationManagerImpl.SystemVMUseLocalStorage.valueIn(dest.getDataCenter().getId()));
            elbVm = new DomainRouterVO(id, elasticLbVmOffering.getId(), vrProvider.getId(), VirtualMachineName.getSystemVmName(id, _instance, ELB_VM_NAME_PREFIX), template.getId(), template.getHypervisorType(), template.getGuestOSId(), owner.getDomainId(), owner.getId(), userId, false, RedundantState.UNKNOWN, elasticLbVmOffering.getOfferHA(), false, null);
            elbVm.setRole(Role.LB);
            elbVm = _routerDao.persist(elbVm);
            _itMgr.allocate(elbVm.getInstanceName(), template, elasticLbVmOffering, networks, plan, null);
            elbVm = _routerDao.findById(elbVm.getId());
        //TODO: create usage stats
        }
        final State state = elbVm.getState();
        if (state != State.Running) {
            elbVm = start(elbVm, params);
        }
        return elbVm;
    } finally {
        _networkDao.releaseFromLockTable(guestNetworkId);
    }
}
Also used : DataCenterDeployment(com.cloud.deploy.DataCenterDeployment) NetworkOffering(com.cloud.offering.NetworkOffering) VMTemplateVO(com.cloud.storage.VMTemplateVO) PhysicalNetworkServiceProvider(com.cloud.network.PhysicalNetworkServiceProvider) NicProfile(com.cloud.vm.NicProfile) ConcurrentOperationException(com.cloud.exception.ConcurrentOperationException) ServiceOfferingVO(com.cloud.service.ServiceOfferingVO) LinkedHashMap(java.util.LinkedHashMap) UserVO(com.cloud.user.UserVO) CloudRuntimeException(com.cloud.utils.exception.CloudRuntimeException) VirtualRouterProvider(com.cloud.network.VirtualRouterProvider) State(com.cloud.vm.VirtualMachine.State) RedundantState(com.cloud.network.router.VirtualRouter.RedundantState) Network(com.cloud.network.Network) List(java.util.List) ArrayList(java.util.ArrayList) DomainRouterVO(com.cloud.vm.DomainRouterVO)

Example 58 with VMTemplateVO

use of com.cloud.storage.VMTemplateVO in project cloudstack by apache.

the class DummySecondaryStorageResource method getDefaultSystemVmTemplateInfo.

public Map<String, TemplateProp> getDefaultSystemVmTemplateInfo() {
    List<VMTemplateVO> tmplts = _tmpltDao.listAllSystemVMTemplates();
    Map<String, TemplateProp> tmpltInfo = new HashMap<String, TemplateProp>();
    if (tmplts != null) {
        for (VMTemplateVO tmplt : tmplts) {
            TemplateProp routingInfo = new TemplateProp(tmplt.getUniqueName(), TemplateConstants.DEFAULT_SYSTEM_VM_TEMPLATE_PATH + tmplt.getId() + File.separator, false, false);
            tmpltInfo.put(tmplt.getUniqueName(), routingInfo);
        }
    }
    return tmpltInfo;
}
Also used : TemplateProp(com.cloud.storage.template.TemplateProp) HashMap(java.util.HashMap) VMTemplateVO(com.cloud.storage.VMTemplateVO)

Example 59 with VMTemplateVO

use of com.cloud.storage.VMTemplateVO in project cloudstack by apache.

the class SnapshotManagerImpl method createPolicy.

@Override
@DB
@ActionEvent(eventType = EventTypes.EVENT_SNAPSHOT_POLICY_CREATE, eventDescription = "creating snapshot policy")
public SnapshotPolicyVO createPolicy(CreateSnapshotPolicyCmd cmd, Account policyOwner) {
    Long volumeId = cmd.getVolumeId();
    boolean display = cmd.isDisplay();
    VolumeVO volume = _volsDao.findById(cmd.getVolumeId());
    if (volume == null) {
        throw new InvalidParameterValueException("Failed to create snapshot policy, unable to find a volume with id " + volumeId);
    }
    _accountMgr.checkAccess(CallContext.current().getCallingAccount(), null, true, volume);
    // If display is false we don't actually schedule snapshots.
    if (volume.getState() != Volume.State.Ready && display) {
        throw new InvalidParameterValueException("VolumeId: " + volumeId + " is not in " + Volume.State.Ready + " state but " + volume.getState() + ". Cannot take snapshot.");
    }
    if (volume.getTemplateId() != null) {
        VMTemplateVO template = _templateDao.findById(volume.getTemplateId());
        if (template != null && template.getTemplateType() == Storage.TemplateType.SYSTEM) {
            throw new InvalidParameterValueException("VolumeId: " + volumeId + " is for System VM , Creating snapshot against System VM volumes is not supported");
        }
    }
    AccountVO owner = _accountDao.findById(volume.getAccountId());
    Long instanceId = volume.getInstanceId();
    if (instanceId != null) {
        // It is not detached, but attached to a VM
        if (_vmDao.findById(instanceId) == null) {
            // It is not a UserVM but a SystemVM or DomR
            throw new InvalidParameterValueException("Failed to create snapshot policy, snapshots of volumes attached to System or router VM are not allowed");
        }
    }
    IntervalType intvType = DateUtil.IntervalType.getIntervalType(cmd.getIntervalType());
    if (intvType == null) {
        throw new InvalidParameterValueException("Unsupported interval type " + cmd.getIntervalType());
    }
    Type type = getSnapshotType(intvType);
    TimeZone timeZone = TimeZone.getTimeZone(cmd.getTimezone());
    String timezoneId = timeZone.getID();
    if (!timezoneId.equals(cmd.getTimezone())) {
        s_logger.warn("Using timezone: " + timezoneId + " for running this snapshot policy as an equivalent of " + cmd.getTimezone());
    }
    try {
        DateUtil.getNextRunTime(intvType, cmd.getSchedule(), timezoneId, null);
    } catch (Exception e) {
        throw new InvalidParameterValueException("Invalid schedule: " + cmd.getSchedule() + " for interval type: " + cmd.getIntervalType());
    }
    if (cmd.getMaxSnaps() <= 0) {
        throw new InvalidParameterValueException("maxSnaps should be greater than 0");
    }
    int intervalMaxSnaps = type.getMax();
    if (cmd.getMaxSnaps() > intervalMaxSnaps) {
        throw new InvalidParameterValueException("maxSnaps exceeds limit: " + intervalMaxSnaps + " for interval type: " + cmd.getIntervalType());
    }
    // Verify that max doesn't exceed domain and account snapshot limits in case display is on
    if (display) {
        long accountLimit = _resourceLimitMgr.findCorrectResourceLimitForAccount(owner, ResourceType.snapshot);
        long domainLimit = _resourceLimitMgr.findCorrectResourceLimitForDomain(_domainMgr.getDomain(owner.getDomainId()), ResourceType.snapshot);
        int max = cmd.getMaxSnaps().intValue();
        if (!_accountMgr.isRootAdmin(owner.getId()) && ((accountLimit != -1 && max > accountLimit) || (domainLimit != -1 && max > domainLimit))) {
            String message = "domain/account";
            if (owner.getType() == Account.ACCOUNT_TYPE_PROJECT) {
                message = "domain/project";
            }
            throw new InvalidParameterValueException("Max number of snapshots shouldn't exceed the " + message + " level snapshot limit");
        }
    }
    SnapshotPolicyVO policy = _snapshotPolicyDao.findOneByVolumeInterval(volumeId, intvType);
    if (policy == null) {
        policy = new SnapshotPolicyVO(volumeId, cmd.getSchedule(), timezoneId, intvType, cmd.getMaxSnaps(), display);
        policy = _snapshotPolicyDao.persist(policy);
        _snapSchedMgr.scheduleNextSnapshotJob(policy);
    } else {
        try {
            boolean previousDisplay = policy.isDisplay();
            policy = _snapshotPolicyDao.acquireInLockTable(policy.getId());
            policy.setSchedule(cmd.getSchedule());
            policy.setTimezone(timezoneId);
            policy.setInterval((short) intvType.ordinal());
            policy.setMaxSnaps(cmd.getMaxSnaps());
            policy.setActive(true);
            policy.setDisplay(display);
            _snapshotPolicyDao.update(policy.getId(), policy);
            _snapSchedMgr.scheduleOrCancelNextSnapshotJobOnDisplayChange(policy, previousDisplay);
        } finally {
            if (policy != null) {
                _snapshotPolicyDao.releaseFromLockTable(policy.getId());
            }
        }
    }
    // TODO - Make createSnapshotPolicy - BaseAsyncCreate and remove this.
    CallContext.current().putContextParameter(SnapshotPolicy.class, policy.getUuid());
    return policy;
}
Also used : IntervalType(com.cloud.utils.DateUtil.IntervalType) VMTemplateVO(com.cloud.storage.VMTemplateVO) AccountVO(com.cloud.user.AccountVO) StorageUnavailableException(com.cloud.exception.StorageUnavailableException) CloudRuntimeException(com.cloud.utils.exception.CloudRuntimeException) InvalidParameterValueException(com.cloud.exception.InvalidParameterValueException) ResourceAllocationException(com.cloud.exception.ResourceAllocationException) ConfigurationException(javax.naming.ConfigurationException) PermissionDeniedException(com.cloud.exception.PermissionDeniedException) EndPoint(org.apache.cloudstack.engine.subsystem.api.storage.EndPoint) ScopeType(com.cloud.storage.ScopeType) Type(com.cloud.storage.Snapshot.Type) HypervisorType(com.cloud.hypervisor.Hypervisor.HypervisorType) ResourceType(com.cloud.configuration.Resource.ResourceType) IntervalType(com.cloud.utils.DateUtil.IntervalType) ResourceObjectType(com.cloud.server.ResourceTag.ResourceObjectType) TimeZone(java.util.TimeZone) VolumeVO(com.cloud.storage.VolumeVO) InvalidParameterValueException(com.cloud.exception.InvalidParameterValueException) SnapshotPolicyVO(com.cloud.storage.SnapshotPolicyVO) ActionEvent(com.cloud.event.ActionEvent) DB(com.cloud.utils.db.DB)

Example 60 with VMTemplateVO

use of com.cloud.storage.VMTemplateVO in project cloudstack by apache.

the class HypervisorTemplateAdapterTest method testEmitDeleteEventUuid.

@Test
public void testEmitDeleteEventUuid() throws InterruptedException, ExecutionException, EventBusException {
    //All the mocks required for this test to work.
    ImageStoreEntity store = mock(ImageStoreEntity.class);
    when(store.getId()).thenReturn(1l);
    when(store.getDataCenterId()).thenReturn(1l);
    when(store.getName()).thenReturn("Test Store");
    TemplateDataStoreVO dataStoreVO = mock(TemplateDataStoreVO.class);
    when(dataStoreVO.getDownloadState()).thenReturn(Status.DOWNLOADED);
    TemplateInfo info = mock(TemplateInfo.class);
    when(info.getDataStore()).thenReturn(store);
    VMTemplateVO template = mock(VMTemplateVO.class);
    when(template.getId()).thenReturn(1l);
    when(template.getName()).thenReturn("Test Template");
    when(template.getFormat()).thenReturn(ImageFormat.QCOW2);
    when(template.getAccountId()).thenReturn(1l);
    //TODO possibly return this from method for comparison, if things work how i want
    when(template.getUuid()).thenReturn("Test UUID");
    TemplateProfile profile = mock(TemplateProfile.class);
    when(profile.getTemplate()).thenReturn(template);
    when(profile.getZoneId()).thenReturn(1l);
    TemplateApiResult result = mock(TemplateApiResult.class);
    when(result.isSuccess()).thenReturn(true);
    when(result.isFailed()).thenReturn(false);
    @SuppressWarnings("unchecked") AsyncCallFuture<TemplateApiResult> future = mock(AsyncCallFuture.class);
    when(future.get()).thenReturn(result);
    AccountVO acct = mock(AccountVO.class);
    when(acct.getId()).thenReturn(1l);
    when(acct.getDomainId()).thenReturn(1l);
    when(_templateMgr.getImageStoreByTemplate(anyLong(), anyLong())).thenReturn(Collections.singletonList((DataStore) store));
    when(_templateStoreDao.listByTemplateStore(anyLong(), anyLong())).thenReturn(Collections.singletonList(dataStoreVO));
    when(_dataFactory.getTemplate(anyLong(), any(DataStore.class))).thenReturn(info);
    when(_dataFactory.listTemplateOnCache(anyLong())).thenReturn(Collections.singletonList(info));
    when(_templateService.deleteTemplateAsync(any(TemplateInfo.class))).thenReturn(future);
    when(_accountDao.findById(anyLong())).thenReturn(acct);
    when(_accountDao.findByIdIncludingRemoved(anyLong())).thenReturn(acct);
    //Test actually begins here.
    setupUsageUtils();
    _adapter.delete(profile);
    Assert.assertNotNull(usageEvents);
    Assert.assertNotNull(events);
    Assert.assertEquals(1, events.size());
    Event event = events.get(0);
    Assert.assertNotNull(event);
    Assert.assertNotNull(event.getResourceType());
    Assert.assertEquals(VirtualMachineTemplate.class.getName(), event.getResourceType());
    Assert.assertNotNull(event.getResourceUUID());
    Assert.assertEquals("Test UUID", event.getResourceUUID());
    Assert.assertEquals(EventTypes.EVENT_TEMPLATE_DELETE, event.getEventType());
    cleanupUsageUtils();
}
Also used : TemplateInfo(org.apache.cloudstack.engine.subsystem.api.storage.TemplateInfo) DataStore(org.apache.cloudstack.engine.subsystem.api.storage.DataStore) VMTemplateVO(com.cloud.storage.VMTemplateVO) Event(org.apache.cloudstack.framework.events.Event) ImageStoreEntity(org.apache.cloudstack.storage.image.datastore.ImageStoreEntity) TemplateDataStoreVO(org.apache.cloudstack.storage.datastore.db.TemplateDataStoreVO) AccountVO(com.cloud.user.AccountVO) TemplateApiResult(org.apache.cloudstack.engine.subsystem.api.storage.TemplateService.TemplateApiResult) TemplateProfile(com.cloud.storage.TemplateProfile) PrepareForTest(org.powermock.core.classloader.annotations.PrepareForTest) Test(org.junit.Test)

Aggregations

VMTemplateVO (com.cloud.storage.VMTemplateVO)110 CloudRuntimeException (com.cloud.utils.exception.CloudRuntimeException)28 InvalidParameterValueException (com.cloud.exception.InvalidParameterValueException)27 Account (com.cloud.user.Account)27 DataStore (org.apache.cloudstack.engine.subsystem.api.storage.DataStore)24 TemplateDataStoreVO (org.apache.cloudstack.storage.datastore.db.TemplateDataStoreVO)22 TemplateInfo (org.apache.cloudstack.engine.subsystem.api.storage.TemplateInfo)17 Date (java.util.Date)16 ArrayList (java.util.ArrayList)15 PermissionDeniedException (com.cloud.exception.PermissionDeniedException)13 HypervisorType (com.cloud.hypervisor.Hypervisor.HypervisorType)13 DataCenterVO (com.cloud.dc.DataCenterVO)12 ActionEvent (com.cloud.event.ActionEvent)11 TemplateProfile (com.cloud.storage.TemplateProfile)11 VMTemplateStoragePoolVO (com.cloud.storage.VMTemplateStoragePoolVO)11 VolumeVO (com.cloud.storage.VolumeVO)11 Test (org.junit.Test)11 PrimaryDataStore (org.apache.cloudstack.engine.subsystem.api.storage.PrimaryDataStore)10 VMTemplateZoneVO (com.cloud.storage.VMTemplateZoneVO)9 DB (com.cloud.utils.db.DB)9