Search in sources :

Example 11 with CloudRuntimeException

use of com.cloud.legacymodel.exceptions.CloudRuntimeException in project cosmic by MissionCriticalCloud.

the class NfsSecondaryStorageResource method getRootDir.

@Override
public synchronized String getRootDir(final String secUrl) {
    if (!this._inSystemVM) {
        return this._parent;
    }
    try {
        final URI uri = new URI(secUrl);
        final String dir = mountUri(uri);
        return this._parent + "/" + dir;
    } catch (final Exception e) {
        final String msg = "GetRootDir for " + secUrl + " failed due to " + e.toString();
        s_logger.error(msg, e);
        throw new CloudRuntimeException(msg);
    }
}
Also used : CloudRuntimeException(com.cloud.legacymodel.exceptions.CloudRuntimeException) URI(java.net.URI) InvalidParameterValueException(com.cloud.legacymodel.exceptions.InvalidParameterValueException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) InternalErrorException(com.cloud.legacymodel.exceptions.InternalErrorException) IOException(java.io.IOException) UnknownHostException(java.net.UnknownHostException) UnsupportedEncodingException(java.io.UnsupportedEncodingException) ConfigurationException(javax.naming.ConfigurationException) CloudRuntimeException(com.cloud.legacymodel.exceptions.CloudRuntimeException)

Example 12 with CloudRuntimeException

use of com.cloud.legacymodel.exceptions.CloudRuntimeException in project cosmic by MissionCriticalCloud.

the class NfsSecondaryStorageResource method attemptMount.

protected void attemptMount(final String localRootPath, final String remoteDevice, final URI uri) {
    final String result;
    s_logger.debug("Make cmdline call to mount " + remoteDevice + " at " + localRootPath + " based on uri " + uri);
    final Script command = new Script(!this._inSystemVM, "mount", this._timeout, s_logger);
    final String scheme = uri.getScheme().toLowerCase();
    command.add("-t", scheme);
    if (scheme.equals("nfs")) {
        if ("Mac OS X".equalsIgnoreCase(System.getProperty("os.name"))) {
            // See http://wiki.qnap.com/wiki/Mounting_an_NFS_share_from_OS_X
            command.add("-o", "resvport");
        }
        if (this._inSystemVM) {
            command.add("-o", "soft,timeo=133,retrans=2147483647,tcp,acdirmax=0,acdirmin=0");
        }
    } else if (scheme.equals("cifs")) {
        final String extraOpts = parseCifsMountOptions(uri);
        // nfs acdirmax / acdirmin correspoonds to CIFS actimeo (see
        // http://linux.die.net/man/8/mount.cifs)
        // no equivalent to nfs timeo, retrans or tcp in CIFS
        // todo: allow security mode to be set.
        command.add("-o", extraOpts + "soft,actimeo=0");
    } else {
        final String errMsg = "Unsupported storage device scheme " + scheme + " in uri " + uri.toString();
        s_logger.error(errMsg);
        throw new CloudRuntimeException(errMsg);
    }
    command.add(remoteDevice);
    command.add(localRootPath);
    result = command.execute();
    if (result != null) {
        // Fedora Core 12 errors out with any -o option executed from java
        final String errMsg = "Unable to mount " + remoteDevice + " at " + localRootPath + " due to " + result;
        s_logger.error(errMsg);
        final File file = new File(localRootPath);
        if (file.exists()) {
            file.delete();
        }
        throw new CloudRuntimeException(errMsg);
    }
    s_logger.debug("Successfully mounted " + remoteDevice + " at " + localRootPath);
}
Also used : Script(com.cloud.utils.script.Script) CloudRuntimeException(com.cloud.legacymodel.exceptions.CloudRuntimeException) File(java.io.File)

Example 13 with CloudRuntimeException

use of com.cloud.legacymodel.exceptions.CloudRuntimeException in project cosmic by MissionCriticalCloud.

the class Agent method setupStartupCommand.

protected void setupStartupCommand(final StartupCommand startup) {
    final InetAddress addr;
    try {
        addr = InetAddress.getLocalHost();
    } catch (final UnknownHostException e) {
        logger.warn("Unknown host", e);
        throw new CloudRuntimeException("Cannot get local IP address", e);
    }
    final Script command = new Script("hostname", 500, logger);
    final OutputInterpreter.OneLineParser parser = new OutputInterpreter.OneLineParser();
    final String result = command.execute(parser);
    final String hostname = result == null ? parser.getLine() : addr.toString();
    startup.setId(getId());
    if (startup.getName() == null) {
        startup.setName(hostname);
    }
    startup.setDataCenter(this.agentConfiguration.getZone());
    startup.setPod(this.agentConfiguration.getPod());
    startup.setGuid(getResourceGuid());
    startup.setResourceName(getResourceName());
}
Also used : Script(com.cloud.utils.script.Script) UnknownHostException(java.net.UnknownHostException) CloudRuntimeException(com.cloud.legacymodel.exceptions.CloudRuntimeException) OutputInterpreter(com.cloud.utils.script.OutputInterpreter) InetAddress(java.net.InetAddress)

Example 14 with CloudRuntimeException

use of com.cloud.legacymodel.exceptions.CloudRuntimeException 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);
    }
}
Also used : AlertManager(com.cloud.alert.AlertManager) OperationTimedoutException(com.cloud.legacymodel.exceptions.OperationTimedoutException) StoragePool(com.cloud.legacymodel.storage.StoragePool) HostPodVO(com.cloud.dc.HostPodVO) VirtualMachineTO(com.cloud.legacymodel.to.VirtualMachineTO) HypervisorGuru(com.cloud.hypervisor.HypervisorGuru) InvalidParameterValueException(com.cloud.legacymodel.exceptions.InvalidParameterValueException) AgentUnavailableException(com.cloud.legacymodel.exceptions.AgentUnavailableException) CloudRuntimeException(com.cloud.legacymodel.exceptions.CloudRuntimeException) Network(com.cloud.legacymodel.network.Network) Commands(com.cloud.agent.manager.Commands) TimeZone(java.util.TimeZone) Zone(com.cloud.db.model.Zone) Cluster(com.cloud.legacymodel.dc.Cluster) Nic(com.cloud.legacymodel.network.Nic) HostVO(com.cloud.host.HostVO) AttachOrDettachConfigDriveCommand(com.cloud.legacymodel.communication.command.AttachOrDettachConfigDriveCommand) Volume(com.cloud.legacymodel.storage.Volume) DeployDestination(com.cloud.deploy.DeployDestination) NoTransitionException(com.cloud.legacymodel.exceptions.NoTransitionException)

Example 15 with CloudRuntimeException

use of com.cloud.legacymodel.exceptions.CloudRuntimeException in project cosmic by MissionCriticalCloud.

the class VirtualMachineManagerImpl method allocate.

@Override
@DB
public void allocate(final String vmInstanceName, final VirtualMachineTemplate template, final ServiceOffering serviceOffering, final DiskOfferingInfo rootDiskOfferingInfo, final List<DiskOfferingInfo> dataDiskOfferings, final LinkedHashMap<? extends Network, List<? extends NicProfile>> auxiliaryNetworks, final DeploymentPlan plan, final HypervisorType hyperType, final DiskControllerType diskControllerType) throws InsufficientCapacityException {
    final VMInstanceVO vm = _vmDao.findVMByInstanceName(vmInstanceName);
    final Account owner = _entityMgr.findById(Account.class, vm.getAccountId());
    s_logger.debug("Allocating entries for VM: " + vm);
    vm.setDataCenterId(plan.getDataCenterId());
    if (plan.getPodId() != null) {
        vm.setPodIdToDeployIn(plan.getPodId());
    }
    // Set date and version we start this VM
    vm.setLastStartDateTime(getCurrentLocalDateTimeStamp());
    vm.setLastStartVersion(VirtualMachineManagerImpl.class.getPackage().getImplementationVersion());
    // Reset VM compliance state
    if (vm.getComplianceStatus() == ComplianceStatus.VMNeedsRestart) {
        vm.setComplianceStatus(ComplianceStatus.Compliant);
    }
    assert plan.getClusterId() == null && plan.getPoolId() == null : "We currently don't support cluster and pool preset yet";
    final VMInstanceVO vmFinal = _vmDao.persist(vm);
    final VirtualMachineProfileImpl vmProfile = new VirtualMachineProfileImpl(vmFinal, template, serviceOffering, null, null);
    Transaction.execute(new TransactionCallbackWithExceptionNoReturn<InsufficientCapacityException>() {

        @Override
        public void doInTransactionWithoutResult(final TransactionStatus status) throws InsufficientCapacityException {
            s_logger.debug(" nics Allocatingfor " + vmFinal);
            try {
                _networkMgr.allocate(vmProfile, auxiliaryNetworks);
            } catch (final ConcurrentOperationException e) {
                throw new CloudRuntimeException("Concurrent operation while trying to allocate resources for the VM", e);
            }
            s_logger.debug("Allocating disks for " + vmFinal);
            DiskControllerType diskController = diskControllerType;
            if (diskController == null) {
                final GuestOS guestOs = _guestOSDao.findById(vm.getGuestOSId());
                diskController = DiskControllerType.getGuestDiskModel(guestOs.getDisplayName());
            }
            if (template.getFormat() == ImageFormat.ISO) {
                volumeMgr.allocateRawVolume(VolumeType.ROOT, "ROOT-" + vmFinal.getId(), rootDiskOfferingInfo.getDiskOffering(), rootDiskOfferingInfo.getSize(), rootDiskOfferingInfo.getMinIops(), rootDiskOfferingInfo.getMaxIops(), vmFinal, template, owner, diskController);
            } else {
                volumeMgr.allocateTemplatedVolume(VolumeType.ROOT, "ROOT-" + vmFinal.getId(), rootDiskOfferingInfo.getDiskOffering(), rootDiskOfferingInfo.getSize(), rootDiskOfferingInfo.getMinIops(), rootDiskOfferingInfo.getMaxIops(), template, vmFinal, owner, diskController);
            }
            if (dataDiskOfferings != null) {
                for (final DiskOfferingInfo dataDiskOfferingInfo : dataDiskOfferings) {
                    volumeMgr.allocateRawVolume(VolumeType.DATADISK, "DATA-" + vmFinal.getId(), dataDiskOfferingInfo.getDiskOffering(), dataDiskOfferingInfo.getSize(), dataDiskOfferingInfo.getMinIops(), dataDiskOfferingInfo.getMaxIops(), vmFinal, template, owner, diskController);
                }
            }
        }
    });
    s_logger.debug("Allocation completed for VM: " + vmFinal);
}
Also used : Account(com.cloud.legacymodel.user.Account) DiskControllerType(com.cloud.model.enumeration.DiskControllerType) CloudRuntimeException(com.cloud.legacymodel.exceptions.CloudRuntimeException) TransactionStatus(com.cloud.utils.db.TransactionStatus) GuestOS(com.cloud.storage.GuestOS) InsufficientCapacityException(com.cloud.legacymodel.exceptions.InsufficientCapacityException) ConcurrentOperationException(com.cloud.legacymodel.exceptions.ConcurrentOperationException) DiskOfferingInfo(com.cloud.offering.DiskOfferingInfo) DB(com.cloud.utils.db.DB)

Aggregations

CloudRuntimeException (com.cloud.legacymodel.exceptions.CloudRuntimeException)587 InvalidParameterValueException (com.cloud.legacymodel.exceptions.InvalidParameterValueException)159 ArrayList (java.util.ArrayList)110 DB (com.cloud.utils.db.DB)90 Account (com.cloud.legacymodel.user.Account)84 SQLException (java.sql.SQLException)84 ActionEvent (com.cloud.event.ActionEvent)73 ConfigurationException (javax.naming.ConfigurationException)73 PreparedStatement (java.sql.PreparedStatement)68 HashMap (java.util.HashMap)68 ResourceUnavailableException (com.cloud.legacymodel.exceptions.ResourceUnavailableException)62 TransactionLegacy (com.cloud.utils.db.TransactionLegacy)52 HostVO (com.cloud.host.HostVO)50 ConcurrentOperationException (com.cloud.legacymodel.exceptions.ConcurrentOperationException)50 NoTransitionException (com.cloud.legacymodel.exceptions.NoTransitionException)50 XenAPIException (com.xensource.xenapi.Types.XenAPIException)47 Answer (com.cloud.legacymodel.communication.answer.Answer)45 XmlRpcException (org.apache.xmlrpc.XmlRpcException)45 TransactionStatus (com.cloud.utils.db.TransactionStatus)44 IOException (java.io.IOException)44