8484import com .vmware .vim25 .VirtualEthernetCardDistributedVirtualPortBackingInfo ;
8585import com .vmware .vim25 .VirtualEthernetCardNetworkBackingInfo ;
8686import com .vmware .vim25 .VirtualMachineConfigSpec ;
87+ import com .vmware .vim25 .VirtualMachineFileInfo ;
88+ import com .vmware .vim25 .VirtualMachineFileLayoutEx ;
89+ import com .vmware .vim25 .VirtualMachineFileLayoutExFileInfo ;
8790import com .vmware .vim25 .VirtualMachineGuestOsIdentifier ;
8891import com .vmware .vim25 .VirtualMachinePowerState ;
8992import com .vmware .vim25 .VirtualMachineRelocateSpec ;
@@ -1326,17 +1329,22 @@ protected StartAnswer execute(StartCommand cmd) {
13261329 VirtualMachineTO vmSpec = cmd .getVirtualMachine ();
13271330 boolean vmAlreadyExistsInVcenter = false ;
13281331
1332+ String existingVmName = null ;
1333+ VirtualMachineFileInfo existingVmFileInfo = null ;
1334+ VirtualMachineFileLayoutEx existingVmFileLayout = null ;
1335+
13291336 Pair <String , String > names = composeVmNames (vmSpec );
13301337 String vmInternalCSName = names .first ();
13311338 String vmNameOnVcenter = names .second ();
13321339
13331340 // Thus, vmInternalCSName always holds i-x-y, the cloudstack generated internal VM name.
13341341 VmwareContext context = getServiceContext ();
1342+ DatacenterMO dcMo = null ;
13351343 try {
13361344 VmwareManager mgr = context .getStockObject (VmwareManager .CONTEXT_STOCK_NAME );
13371345
13381346 VmwareHypervisorHost hyperHost = getHyperHost (context );
1339- DatacenterMO dcMo = new DatacenterMO (hyperHost .getContext (), hyperHost .getHyperHostDatacenter ());
1347+ dcMo = new DatacenterMO (hyperHost .getContext (), hyperHost .getHyperHostDatacenter ());
13401348
13411349 // Validate VM name is unique in Datacenter
13421350 VirtualMachineMO vmInVcenter = dcMo .checkIfVmAlreadyExistsInVcenter (vmNameOnVcenter , vmInternalCSName );
@@ -1404,6 +1412,15 @@ protected StartAnswer execute(StartCommand cmd) {
14041412 vmMo .tearDownDevices (new Class <?>[] {VirtualEthernetCard .class });
14051413 vmMo .ensureScsiDeviceController ();
14061414 } else {
1415+ // If a VM with the same name is found in a different cluster in the DC, unregister the old VM and configure a new VM (cold-migration).
1416+ VirtualMachineMO existingVmInDc = dcMo .findVm (vmInternalCSName );
1417+ if (existingVmInDc != null ) {
1418+ s_logger .debug ("Found VM: " + vmInternalCSName + " on a host in a different cluster. Unregistering the exisitng VM." );
1419+ existingVmName = existingVmInDc .getName ();
1420+ existingVmFileInfo = existingVmInDc .getFileInfo ();
1421+ existingVmFileLayout = existingVmInDc .getFileLayout ();
1422+ existingVmInDc .unregisterVm ();
1423+ }
14071424 Pair <ManagedObjectReference , DatastoreMO > rootDiskDataStoreDetails = null ;
14081425 for (DiskTO vol : disks ) {
14091426 if (vol .getType () == Volume .Type .ROOT ) {
@@ -1429,7 +1446,9 @@ protected StartAnswer execute(StartCommand cmd) {
14291446
14301447 assert (vmSpec .getMinSpeed () != null ) && (rootDiskDataStoreDetails != null );
14311448
1432- if (rootDiskDataStoreDetails .second ().folderExists (String .format ("[%s]" , rootDiskDataStoreDetails .second ().getName ()), vmNameOnVcenter )) {
1449+ boolean vmFolderExists = rootDiskDataStoreDetails .second ().folderExists (String .format ("[%s]" , rootDiskDataStoreDetails .second ().getName ()), vmNameOnVcenter );
1450+ String vmxFileFullPath = dsRootVolumeIsOn .searchFileInSubFolders (vmNameOnVcenter + ".vmx" , false );
1451+ if (vmFolderExists && vmxFileFullPath != null ) { // VM can be registered only if .vmx is present.
14331452 registerVm (vmNameOnVcenter , dsRootVolumeIsOn );
14341453 vmMo = hyperHost .findVmOnHyperHost (vmInternalCSName );
14351454 tearDownVm (vmMo );
@@ -1740,6 +1759,11 @@ protected StartAnswer execute(StartCommand cmd) {
17401759
17411760 startAnswer .setIqnToPath (iqnToPath );
17421761
1762+ // Since VM was successfully powered-on, if there was an existing VM in a different cluster that was unregistered, delete all the files associated with it.
1763+ if (existingVmName != null && existingVmFileLayout != null ) {
1764+ deleteUnregisteredVmFiles (existingVmFileLayout , dcMo );
1765+ }
1766+
17431767 return startAnswer ;
17441768 } catch (Throwable e ) {
17451769 if (e instanceof RemoteException ) {
@@ -1753,6 +1777,20 @@ protected StartAnswer execute(StartCommand cmd) {
17531777 if (vmAlreadyExistsInVcenter ) {
17541778 startAnswer .setContextParam ("stopRetry" , "true" );
17551779 }
1780+
1781+ // Since VM start failed, if there was an existing VM in a different cluster that was unregistered, register it back.
1782+ if (existingVmName != null && existingVmFileInfo != null ) {
1783+ s_logger .debug ("Since VM start failed, registering back an existing VM: " + existingVmName + " that was unregistered" );
1784+ try {
1785+ DatastoreFile fileInDatastore = new DatastoreFile (existingVmFileInfo .getVmPathName ());
1786+ DatastoreMO existingVmDsMo = new DatastoreMO (dcMo .getContext (), dcMo .findDatastore (fileInDatastore .getDatastoreName ()));
1787+ registerVm (existingVmName , existingVmDsMo );
1788+ } catch (Exception ex ){
1789+ String message = "Failed to register an existing VM: " + existingVmName + " due to " + VmwareHelper .getExceptionMessage (ex );
1790+ s_logger .warn (message , ex );
1791+ }
1792+ }
1793+
17561794 return startAnswer ;
17571795 } finally {
17581796 }
@@ -2204,6 +2242,41 @@ private void postDiskConfigBeforeStart(VirtualMachineMO vmMo, VirtualMachineTO v
22042242 }
22052243 }
22062244
2245+ private void deleteUnregisteredVmFiles (VirtualMachineFileLayoutEx vmFileLayout , DatacenterMO dcMo ) throws Exception {
2246+ s_logger .debug ("Deleting files associated with an existing VM that was unregistered" );
2247+ DatastoreFile vmFolder = null ;
2248+ try {
2249+ List <VirtualMachineFileLayoutExFileInfo > fileInfo = vmFileLayout .getFile ();
2250+ for (VirtualMachineFileLayoutExFileInfo file : fileInfo ) {
2251+ DatastoreFile fileInDatastore = new DatastoreFile (file .getName ());
2252+ // In case of linked clones, VM file layout includes the base disk so don't delete all disk files.
2253+ if (file .getType ().startsWith ("disk" ) || file .getType ().startsWith ("digest" ))
2254+ continue ;
2255+ else if (file .getType ().equals ("config" ))
2256+ vmFolder = new DatastoreFile (fileInDatastore .getDatastoreName (), fileInDatastore .getDir ());
2257+ DatastoreMO dsMo = new DatastoreMO (dcMo .getContext (), dcMo .findDatastore (fileInDatastore .getDatastoreName ()));
2258+ s_logger .debug ("Deleting file: " + file .getName ());
2259+ dsMo .deleteFile (file .getName (), dcMo .getMor (), true );
2260+ }
2261+ // Delete files that are present in the VM folder - this will take care of the VM disks as well.
2262+ DatastoreMO vmFolderDsMo = new DatastoreMO (dcMo .getContext (), dcMo .findDatastore (vmFolder .getDatastoreName ()));
2263+ String [] files = vmFolderDsMo .listDirContent (vmFolder .getPath ());
2264+ if (files .length != 0 ) {
2265+ for (String file : files ) {
2266+ String vmDiskFileFullPath = String .format ("%s/%s" , vmFolder .getPath (), file );
2267+ s_logger .debug ("Deleting file: " + vmDiskFileFullPath );
2268+ vmFolderDsMo .deleteFile (vmDiskFileFullPath , dcMo .getMor (), true );
2269+ }
2270+ }
2271+ // Delete VM folder
2272+ s_logger .debug ("Deleting folder: " + vmFolder .getPath ());
2273+ vmFolderDsMo .deleteFolder (vmFolder .getPath (), dcMo .getMor ());
2274+ } catch (Exception e ) {
2275+ String message = "Failed to delete files associated with an existing VM that was unregistered due to " + VmwareHelper .getExceptionMessage (e );
2276+ s_logger .warn (message , e );
2277+ }
2278+ }
2279+
22072280 private static VolumeObjectTO getVolumeInSpec (VirtualMachineTO vmSpec , VolumeObjectTO srcVol ) {
22082281 for (DiskTO disk : vmSpec .getDisks ()) {
22092282 VolumeObjectTO vol = (VolumeObjectTO )disk .getData ();
0 commit comments