diff --git a/labs/virtualbox/src/main/java/org/jclouds/virtualbox/compute/VirtualBoxComputeServiceAdapter.java b/labs/virtualbox/src/main/java/org/jclouds/virtualbox/compute/VirtualBoxComputeServiceAdapter.java index dcf9f3f4d0..771ce60b61 100644 --- a/labs/virtualbox/src/main/java/org/jclouds/virtualbox/compute/VirtualBoxComputeServiceAdapter.java +++ b/labs/virtualbox/src/main/java/org/jclouds/virtualbox/compute/VirtualBoxComputeServiceAdapter.java @@ -41,12 +41,13 @@ import org.jclouds.logging.Logger; import org.jclouds.virtualbox.domain.Master; import org.jclouds.virtualbox.domain.NodeSpec; import org.jclouds.virtualbox.domain.YamlImage; -import org.virtualbox_4_1.CleanupMode; +import org.jclouds.virtualbox.functions.admin.UnregisterMachineIfExistsAndForceDeleteItsMedia; import org.virtualbox_4_1.IMachine; import org.virtualbox_4_1.IProgress; import org.virtualbox_4_1.ISession; import org.virtualbox_4_1.MachineState; import org.virtualbox_4_1.SessionState; +import org.virtualbox_4_1.VBoxException; import org.virtualbox_4_1.VirtualBoxManager; import com.google.common.base.Function; @@ -138,14 +139,21 @@ public class VirtualBoxComputeServiceAdapter implements ComputeServiceAdapter { + + @Resource + @Named(ComputeServiceConstants.COMPUTE_LOGGER) + protected Logger logger = Logger.NULL; + + @Override + public Void apply(IMachine machine) { + List mediaToBeDeleted = Collections.emptyList(); + try { + mediaToBeDeleted = machine.unregister(CleanupMode.Full); + } catch (VBoxException e) { + ErrorCode errorCode = ErrorCode.valueOf(e); + switch (errorCode) { + case VBOX_E_OBJECT_NOT_FOUND: + logger.debug("Machine %s does not exists, cannot unregister", machine.getName()); + break; + default: + throw e; + } + } + + List filteredMediaToBeDeleted = Lists.newArrayList(transform(mediaToBeDeleted, + new DeleteChildrenOfMedium())); + if (!filteredMediaToBeDeleted.isEmpty()) { + try { + IProgress deletion = machine.delete(filteredMediaToBeDeleted); + deletion.waitForCompletion(-1); + } catch (Exception e) { + logger.error(e, "Problem in deleting the media attached to %s", machine.getName()); + Throwables.propagate(e); + } + } + + return null; + } + + private class DeleteChildrenOfMedium implements Function { + @Override + public IMedium apply(IMedium medium) { + checkNotNull(medium.getChildren()); + if (medium.getDeviceType().equals(DeviceType.HardDisk)) { + for (IMedium child : medium.getChildren()) { + IProgress deletion = child.deleteStorage(); + deletion.waitForCompletion(-1); + } + } + return medium; + } + + }; + +}