"Can not find root volume for VM " + vm.getUuid());
ex.addProxyObject(vm.getUuid(), "vmId");
throw ex;
}
VolumeVO root = rootVols.get(0);
Long templateId = root.getTemplateId();
boolean isISO = false;
if(templateId == null) {
// Assuming that for a vm deployed using ISO, template ID is set to NULL
isISO = true;
templateId = vm.getIsoId();
}
VMTemplateVO template = null;
//newTemplateId can be either template or ISO id. In the following snippet based on the vm deployment (from template or ISO) it is handled accordingly
if(newTemplateId != null) {
template = _templateDao.findById(newTemplateId);
_accountMgr.checkAccess(caller, null, true, template);
if (isISO) {
if (!template.getFormat().equals(ImageFormat.ISO)) {
throw new InvalidParameterValueException("Invalid ISO id provided to restore the VM ");
}
} else {
if (template.getFormat().equals(ImageFormat.ISO)) {
throw new InvalidParameterValueException("Invalid template id provided to restore the VM ");
}
}
} else {
if (isISO && templateId == null) {
throw new CloudRuntimeException("Cannot restore the VM since there is no ISO attached to VM");
}
template = _templateDao.findById(templateId);
if (template == null) {
InvalidParameterValueException ex = new InvalidParameterValueException(
"Cannot find template/ISO for specified volumeid and vmId");
ex.addProxyObject(vm.getUuid(), "vmId");
ex.addProxyObject(root.getUuid(), "volumeId");
throw ex;
}
}
if (needRestart) {
try {
_itMgr.stop(vm, user, caller);
} catch (ResourceUnavailableException e) {
s_logger.debug("Stop vm " + vm.getUuid() + " failed", e);
CloudRuntimeException ex = new CloudRuntimeException(
"Stop vm failed for specified vmId");
ex.addProxyObject(vm.getUuid(), "vmId");
throw ex;
}
}
/* If new template/ISO is provided allocate a new volume from new template/ISO otherwise allocate new volume from original template/ISO */
VolumeVO newVol = null;
if (newTemplateId != null) {
if (isISO) {
newVol = volumeMgr.allocateDuplicateVolume(root, null);
vm.setIsoId(newTemplateId);
vm.setGuestOSId(template.getGuestOSId());
vm.setTemplateId(newTemplateId);
_vmDao.update(vmId, vm);
} else {
newVol = volumeMgr.allocateDuplicateVolume(root, newTemplateId);
vm.setGuestOSId(template.getGuestOSId());
vm.setTemplateId(newTemplateId);
_vmDao.update(vmId, vm);
}
} else {
newVol = volumeMgr.allocateDuplicateVolume(root, null);
}
_volsDao.attachVolume(newVol.getId(), vmId, newVol.getDeviceId());
/* Detach and destory the old root volume */
_volsDao.detachVolume(root.getId());
volumeMgr.destroyVolume(root);