Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -73,6 +73,13 @@ public interface VolumeDao extends GenericDao<VolumeVO, Long>, StateDao<Volume.S

void detachVolume(long volumeId);

/**
* Clears the attachment of the volume only if it is still attached to the given VM.
*
* @return true if the attachment was cleared; false if the volume is no longer attached to vmId
*/
boolean detachVolume(long volumeId, long vmId);

boolean isAnyVolumeActivelyUsingTemplateOnPool(long templateId, long poolId);

List<VolumeVO> findCreatedByInstance(long id);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -391,6 +391,23 @@ public void detachVolume(long volumeId) {
update(volumeId, volume);
}

@Override
public boolean detachVolume(long volumeId, long vmId) {
VolumeVO existing = findById(volumeId);
VolumeVO volume = createForUpdate(volumeId);
volume.setInstanceId(null);
volume.setDeviceId(null);
volume.setUpdated(new Date());
volume.setAttached(null);
if (existing != null && existing.getVolumeType() == Type.ROOT) {
volume.setVolumeType(Type.DATADISK);
}
SearchCriteria<VolumeVO> sc = AllFieldsSearch.create();
sc.setParameters("id", volumeId);
sc.setParameters("instanceId", vmId);
return update(volume, sc) > 0;
}

@Override
@DB
public HypervisorType getHypervisorType(long volumeId) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.ArgumentCaptor;
import org.mockito.Mock;
import org.mockito.MockedStatic;
import org.mockito.Mockito;
Expand All @@ -43,6 +44,8 @@

import com.cloud.storage.Volume;
import com.cloud.storage.VolumeVO;
import com.cloud.utils.Pair;
import com.cloud.utils.db.Attribute;
import com.cloud.utils.db.Filter;
import com.cloud.utils.db.SearchBuilder;
import com.cloud.utils.db.SearchCriteria;
Expand Down Expand Up @@ -231,4 +234,69 @@ public void testSearchRemovedByVms() {
Mockito.any(SearchCriteria.class), Mockito.any(Filter.class), Mockito.eq(null),
Mockito.eq(false));
}

private static final long DETACHED_VOLUME_ID = 1L;
private static final long DETACHED_FROM_VM_ID = 2L;

private void mockVolumeForConditionalDetach(Volume.Type existingType, int updatedRows) {
VolumeVO existing = Mockito.mock(VolumeVO.class);
Mockito.doReturn(existingType).when(existing).getVolumeType();
Mockito.doReturn(existing).when(volumeDao).findById(DETACHED_VOLUME_ID);
Mockito.doReturn(updatedRows).when(volumeDao).update(Mockito.any(VolumeVO.class), Mockito.<SearchCriteria<VolumeVO>>any());
}

@SuppressWarnings("unchecked")
private SearchCriteria<VolumeVO> captureConditionalDetachCriteria() {
ArgumentCaptor<SearchCriteria<VolumeVO>> criteria = ArgumentCaptor.forClass(SearchCriteria.class);
Mockito.verify(volumeDao).update(Mockito.any(VolumeVO.class), criteria.capture());
return criteria.getValue();
}

private List<Object> boundValuesOf(SearchCriteria<VolumeVO> criteria) {
List<Object> values = new ArrayList<>();
for (Pair<Attribute, Object> bound : criteria.getValues()) {
values.add(bound.second());
}
return values;
}

@Test
public void detachVolumeTestRestrictsTheUpdateToTheVmTheVolumeIsStillAttachedTo() {
mockVolumeForConditionalDetach(Volume.Type.DATADISK, 1);

volumeDao.detachVolume(DETACHED_VOLUME_ID, DETACHED_FROM_VM_ID);

SearchCriteria<VolumeVO> criteria = captureConditionalDetachCriteria();
Assert.assertTrue("the update must be restricted by instance_id, otherwise a stale detach clears a newer attachment; where clause was: "
+ criteria.getWhereClause(), criteria.getWhereClause().contains("instance_id"));
List<Object> bound = boundValuesOf(criteria);
Assert.assertEquals("expected the volume id and the vm id to be bound, got " + bound, 2, bound.size());
Assert.assertTrue("the vm id must be bound, got " + bound, bound.contains(DETACHED_FROM_VM_ID));
Assert.assertTrue("the volume id must be bound, got " + bound, bound.contains(DETACHED_VOLUME_ID));
}

@Test
public void detachVolumeTestClearsAttachmentWhenStillAttachedToVm() {
mockVolumeForConditionalDetach(Volume.Type.DATADISK, 1);

Assert.assertTrue(volumeDao.detachVolume(DETACHED_VOLUME_ID, DETACHED_FROM_VM_ID));
}

@Test
public void detachVolumeTestKeepsAttachmentWhenAttachedToAnotherVm() {
mockVolumeForConditionalDetach(Volume.Type.DATADISK, 0);

Assert.assertFalse(volumeDao.detachVolume(DETACHED_VOLUME_ID, DETACHED_FROM_VM_ID));
}

@Test
public void detachVolumeTestConvertsADetachedRootVolumeToADataDisk() {
mockVolumeForConditionalDetach(Volume.Type.ROOT, 1);

volumeDao.detachVolume(DETACHED_VOLUME_ID, DETACHED_FROM_VM_ID);

ArgumentCaptor<VolumeVO> updated = ArgumentCaptor.forClass(VolumeVO.class);
Mockito.verify(volumeDao).update(updated.capture(), Mockito.<SearchCriteria<VolumeVO>>any());
Assert.assertEquals(Volume.Type.DATADISK, updated.getValue().getVolumeType());
}
}
29 changes: 27 additions & 2 deletions server/src/main/java/com/cloud/storage/VolumeApiServiceImpl.java
Original file line number Diff line number Diff line change
Expand Up @@ -3568,10 +3568,28 @@ public Volume detachVolumeViaDestroyVM(long vmId, long volumeId) {
return orchestrateDetachVolumeFromVM(vmId, volumeId);
}

/**
* A queued detach can run after the volume was already detached and attached elsewhere.
* In that case the detach must be skipped, so the newer attachment is left alone.
*
* @return true if the volume is no longer attached to the given VM
*/
protected boolean shouldDetachBeSkipped(Volume volume, VMInstanceVO vm) {
if (volume.getInstanceId() == null || volume.getInstanceId() != vm.getId()) {
logger.warn("Volume {} is no longer attached to VM {}, skipping detach", volume, vm);
return true;
}
return false;
}

private Volume orchestrateDetachVolumeFromVM(long vmId, long volumeId) {
Volume volume = _volsDao.findById(volumeId);
VMInstanceVO vm = _vmInstanceDao.findById(vmId);

if (shouldDetachBeSkipped(volume, vm)) {
return volume;
}

String errorMsg = "Failed to detach volume " + volume.getName() + " from VM " + vm.getHostName();
boolean sendCommand = vm.getState() == State.Running;

Expand Down Expand Up @@ -3621,8 +3639,15 @@ private Volume orchestrateDetachVolumeFromVM(long vmId, long volumeId) {
}

if (!sendCommand || (answer != null && answer.getResult())) {
// Mark the volume as detached
_volsDao.detachVolume(volume.getId());
// Mark the volume as detached, only if it is still attached to this VM. The host has already been told to
// unplug the disk by this point, so the remainder of this block is deliberately skipped when the volume
// moved: revoking access or publishing a detach event would assert something that is no longer true.
if (!_volsDao.detachVolume(volume.getId(), vmId)) {
Volume current = _volsDao.findById(volumeId);
logger.warn("Volume {} is no longer attached to VM {} (its attachment now points at VM id {}); leaving it unchanged",
volume, vm, current == null ? null : current.getInstanceId());
return current;
}

if (answer != null) {
String datastoreName = answer.getContextParam("datastoreName");
Expand Down
Loading
Loading