package io.cattle.platform.process.volume;

import io.cattle.platform.core.dao.GenericMapDao;
import io.cattle.platform.core.model.Mount;
import io.cattle.platform.core.model.Volume;
import io.cattle.platform.core.model.VolumeStoragePoolMap;
import io.cattle.platform.engine.handler.HandlerResult;
import io.cattle.platform.engine.process.ProcessInstance;
import io.cattle.platform.engine.process.ProcessState;
import io.cattle.platform.object.process.StandardProcess;
import io.cattle.platform.process.base.AbstractDefaultProcessHandler;
import io.cattle.platform.process.common.util.ProcessUtils;

import javax.inject.Inject;
import javax.inject.Named;

@Named
public class VolumePurge extends AbstractDefaultProcessHandler {

    GenericMapDao mapDao;

    @Override
    public HandlerResult handle(ProcessState state, ProcessInstance process) {
        Volume volume = (Volume) state.getResource();

        deallocate(volume, state.getData());

        for (VolumeStoragePoolMap map : mapDao.findToRemove(VolumeStoragePoolMap.class, Volume.class, volume.getId())) {
            objectProcessManager.scheduleStandardProcess(StandardProcess.DEACTIVATE, map,
                    ProcessUtils.chainInData(state.getData(), "volumestoragepoolmap.deactivate", "volumestoragepoolmap.remove"));
        }

        for (Mount mount: mapDao.findToRemove(Mount.class, Volume.class, volume.getId())) {
            objectProcessManager.scheduleStandardProcess(StandardProcess.DEACTIVATE, mount,
                    ProcessUtils.chainInData(state.getData(), "mount.deactivate", "mount.remove"));
        }

        return new HandlerResult();
    }

    public GenericMapDao getMapDao() {
        return mapDao;
    }

    @Inject
    public void setMapDao(GenericMapDao mapDao) {
        this.mapDao = mapDao;
    }

}

@@ -404,16 +404,86 @@
 sState;%0A
+import io.cattle.platform.engine.process.impl.ProcessCancelException;%0A
 import i
@@ -944,17 +944,16 @@
 (Volume)
- 
 state.ge
@@ -1125,32 +1125,54 @@
 ume.getId())) %7B%0A
+            try %7B%0A    
             obje
@@ -1245,16 +1245,20 @@
 E, map,%0A
+    
         
@@ -1371,32 +1371,192 @@
 lmap.remove%22));%0A
+            %7D catch (ProcessCancelException e) %7B%0A                objectProcessManager.scheduleStandardProcess(StandardProcess.REMOVE, map, null);%0A            %7D%0A
         %7D%0A%0A     
@@ -1574,16 +1574,17 @@
 nt mount
+ 
 : mapDao
@@ -1635,32 +1635,54 @@
 ume.getId())) %7B%0A
+            try %7B%0A    
             obje
@@ -1769,32 +1769,36 @@
                 
+   
+ 
 ProcessUtils.cha
@@ -1853,32 +1853,194 @@
 ount.remove%22));%0A
+            %7D catch (ProcessCancelException e) %7B%0A                objectProcessManager.scheduleStandardProcess(StandardProcess.REMOVE, mount, null);%0A            %7D%0A
         %7D%0A%0A     

Make mount and vol sp map cleanup more robust