@Override public void destroyNode(String vmName) { try (VSphereServiceInstance instance = serviceInstance.get();) { VirtualMachine virtualMachine = getVM(vmName, instance.getInstance().getRootFolder()); Task powerOffTask = virtualMachine.powerOffVM_Task(); if (powerOffTask.waitForTask().equals(Task.SUCCESS)) logger.debug(String.format("VM %s powered off", vmName)); else logger.debug(String.format("VM %s could not be powered off", vmName)); Task destroyTask = virtualMachine.destroy_Task(); if (destroyTask.waitForTask().equals(Task.SUCCESS)) logger.debug(String.format("VM %s destroyed", vmName)); else logger.debug(String.format("VM %s could not be destroyed", vmName)); } catch (Exception e) { logger.error("Can't destroy vm " + vmName, e); Throwables.propagateIfPossible(e); } }
@Override public void resumeNode(String vmName) { VirtualMachine virtualMachine = getNode(vmName); if (virtualMachine.getRuntime().getPowerState().equals(VirtualMachinePowerState.poweredOff)) { try { Task task = virtualMachine.powerOnVM_Task(null); if (task.waitForTask().equals(Task.SUCCESS)) logger.debug(virtualMachine.getName() + " resumed"); } catch (Exception e) { logger.error("Can't resume vm " + vmName, e); propagate(e); } } else logger.debug(vmName + " can't be resumed"); }
private VirtualMachineSnapshot getCurrentSnapshotOrCreate(String snapshotName, String snapshotDescription, VirtualMachine master) throws InvalidName, VmConfigFault, SnapshotFault, TaskInProgress, FileFault, InvalidState, RuntimeFault, RemoteException { if (master.getSnapshot() == null) { Task task = master.createSnapshot_Task(snapshotName, snapshotDescription, false, false); try { if (task.waitForTask().equals(Task.SUCCESS)) { logger.debug(String.format("snapshot taken for '%s'", master.getName())); } } catch (Exception e) { logger.debug(String.format("Can't take snapshot for '%s'", master.getName()), e); throw propagate(e); } } else logger.debug(String.format("snapshot already available for '%s'", master.getName())); return master.getCurrentSnapShot(); }
private synchronized void reconfigureVmTask(@NotNull final VmwareCloudInstance instance, @NotNull final CloudInstanceUserData cloudInstanceUserData) { myAsyncTaskExecutor.executeAsync(new VmwareTaskWrapper(new Callable<Task>() { public Task call() throws Exception { return myApiConnector.reconfigureInstance(instance, instance.getName(), cloudInstanceUserData); } },"Reconfigure " + instance.getName()) , new ImageStatusTaskWrapper(instance) { @Override public void onSuccess() { instance.setStatus(InstanceStatus.RUNNING); instance.setStartDate(new Date()); instance.updateErrors(); LOG.info("Instance started successfully"); } }); }
public void terminateInstance(@NotNull final VmwareCloudInstance instance) { LOG.info("Stopping instance " + instance.getName()); instance.setStatus(InstanceStatus.SCHEDULED_TO_STOP); myAsyncTaskExecutor.executeAsync(new VmwareTaskWrapper(new Callable<Task>() { public Task call() throws Exception { return myApiConnector.stopInstance(instance); } }, "Stop " + instance.getName()), new ImageStatusTaskWrapper(instance){ @Override public void onComplete() { instance.setStatus(InstanceStatus.STOPPED); if (myImageDetails.getBehaviour().isDeleteAfterStop()) { // we only destroy proper instances. deleteInstance(instance); } } }); }
private void deleteInstance(@NotNull final VmwareCloudInstance instance){ if (instance.getErrorInfo() == null) { LOG.info("Will delete instance " + instance.getName()); myAsyncTaskExecutor.executeAsync(new VmwareTaskWrapper(new Callable<Task>() { public Task call() throws Exception { return myApiConnector.deleteInstance(instance); } }, "Delete " + instance.getName()), new ImageStatusTaskWrapper(instance) { @Override public void onSuccess() { removeInstance(instance.getName()); } }); } else { LOG.warn(String.format("Won't delete instance %s with error: %s (%s)", instance.getName(), instance.getErrorInfo().getMessage(), instance.getErrorInfo().getDetailedMessage())); } }
public void removeVirtualMachineSnapshot(VirtualMachine vm, String nameVm) throws Exception { logger.info("Launching old snapshot removing process for {}", nameVm); if(vm.getSnapshot() != null) { logger.info("Deleting snapshot ..."); VirtualMachineSnapshotTree[] _stree = vm.getSnapshot().getRootSnapshotList(); if(_stree != null) { for(VirtualMachineSnapshotTree _st : _stree) { if(_st.getName().equals(nameVm)) { logger.info("Old snahpot {} found"); VirtualMachineSnapshot _vmsSnap = new VirtualMachineSnapshot(vm.getServerConnection(), _st.getSnapshot()); Task _taskSnap = _vmsSnap.removeSnapshot_Task(true); logger.info("Removing process launched..."); if(_taskSnap.waitForTask() != Task.SUCCESS) { logger.error("Error on snapshot removing process. {}",_taskSnap.getTaskInfo().getError().getLocalizedMessage()); throw new Exception(_taskSnap.getTaskInfo().getError().getLocalizedMessage()); } logger.info("Snapshot removed successfully"); } } } } }
@Override public void suspendNode(String vmName) { VirtualMachine virtualMachine = getNode(vmName); try { Task task = virtualMachine.suspendVM_Task(); if (task.waitForTask().equals(Task.SUCCESS)) logger.debug(vmName + " suspended"); else logger.debug(vmName + " can't be suspended"); } catch (Exception e) { logger.error("Can't suspend vm " + vmName, e); propagate(e); } }
private VirtualMachine cloneMaster(VirtualMachine master, String tag, String name, VirtualMachineCloneSpec cloneSpec, String folderName) { VirtualMachine cloned = null; try { FolderNameToFolderManagedEntity toFolderManagedEntity = new FolderNameToFolderManagedEntity(serviceInstance, master); Folder folder = toFolderManagedEntity.apply(folderName); Task task = master.cloneVM_Task(folder, name, cloneSpec); String result = task.waitForTask(); if (result.equals(Task.SUCCESS)) { logger.trace("<< after clone search for VM with name: " + name); Retryer<VirtualMachine> retryer = RetryerBuilder.<VirtualMachine>newBuilder() .retryIfResult(Predicates.<VirtualMachine>isNull()) .withStopStrategy(StopStrategies.stopAfterAttempt(5)) .retryIfException().withWaitStrategy(WaitStrategies.fixedWait(1, TimeUnit.SECONDS)) .build(); cloned = retryer.call(new GetVirtualMachineCallable(name, folder, serviceInstance.get().getInstance().getRootFolder())); } else { String errorMessage = task.getTaskInfo().getError().getLocalizedMessage(); logger.error(errorMessage); } } catch (Exception e) { if (e instanceof NoPermission){ NoPermission noPermission = (NoPermission)e; logger.error("NoPermission: " + noPermission.getPrivilegeId()); } logger.error("Can't clone vm: " + e.toString(), e); propagate(e); } if (cloned == null) logger.error("<< Failed to get cloned VM. " + name); return checkNotNull(cloned, "cloned"); }
public VmwareTaskWrapper(@NotNull final Callable<Task> vmwareTask, String taskName){ myVmwareTask = vmwareTask; myTaskName = taskName; myTaskCancelled = new AtomicBoolean(false); myFutureLazy = new Lazy<Future<CloudTaskResult>>() { @Nullable @Override protected Future<CloudTaskResult> createValue() { return execute(); } }; }
private synchronized void startVM(@NotNull final VmwareCloudInstance instance, @NotNull final CloudInstanceUserData cloudInstanceUserData) { instance.setStartDate(new Date()); instance.setStatus(InstanceStatus.STARTING); myAsyncTaskExecutor.executeAsync(new VmwareTaskWrapper(new Callable<Task>() { public Task call() throws Exception { return myApiConnector.startInstance(instance, instance.getName(), cloudInstanceUserData); } }, "Start instance " + instance.getName()) , new ImageStatusTaskWrapper(instance) { @Override public void onSuccess() { reconfigureVmTask(instance, cloudInstanceUserData); } }); }
public void check_can_start_new_instance_limits() throws RemoteException, InterruptedException { final CloudInstanceUserData data = new CloudInstanceUserData("aaa", "bbbb", "localhost", 10000l, "profileDescr", Collections.<String, String>emptyMap()); assertTrue(myImage.canStartNewInstance()); myImage.startNewInstance(data); assertTrue(myImage.canStartNewInstance()); myImage.startNewInstance(data); assertTrue(myImage.canStartNewInstance()); myImage.startNewInstance(data); assertTrue(myImage.canStartNewInstance()); myImage.startNewInstance(data); assertTrue(myImage.canStartNewInstance()); final VmwareCloudInstance instance2Stop = myImage.startNewInstance(data); assertFalse(myImage.canStartNewInstance()); new WaitFor(5*1000){ @Override protected boolean condition() { return instance2Stop.getStatus() == InstanceStatus.RUNNING; } }; final FakeVirtualMachine vm2Stop = FakeModel.instance().getVirtualMachine(instance2Stop.getName()); final String result = vm2Stop.powerOffVM_Task().waitForTask(); assertEquals(Task.SUCCESS, result); instance2Stop.setStatus(InstanceStatus.STOPPED); assertTrue(myImage.canStartNewInstance()); System.setProperty(VmwareConstants.CONSIDER_STOPPED_VMS_LIMIT, "true"); assertFalse(myImage.canStartNewInstance()); System.getProperties().remove(VmwareConstants.CONSIDER_STOPPED_VMS_LIMIT); assertTrue(myImage.canStartNewInstance()); }
public void should_report_isdone_for_error_tasks() throws ExecutionException, InterruptedException { VmwareTaskWrapper taskWrapper = new VmwareTaskWrapper(new Callable<Task>() { @Override public Task call() throws Exception { return new Task(null, null){ @Override public TaskInfo getTaskInfo() throws InvalidProperty, RuntimeFault, RemoteException { throw new RuntimeException("getTaskInfo exception"); } @Override public String waitForTask() throws RuntimeFault, RemoteException, InterruptedException { throw new RuntimeException("getTaskInfo exception"); } @Override public void cancelTask() throws RuntimeFault, RemoteException { throw new RuntimeException("getTaskInfo exception"); } }; } }, "myTask"); final Future<CloudTaskResult> async = taskWrapper.executeOrGetResultAsync(); int cnt = 0; while (!async.isDone()){ cnt++; assertTrue(cnt < 5); } final CloudTaskResult result = async.get(); assertTrue(result.isHasErrors()); }
private void handleTask(Task task) throws DestructionException, InterruptedException, RemoteException { task.waitForTask(); TaskInfo taskInfo = task.getTaskInfo(); if (TaskInfoState.error == taskInfo.getState()) { throw new DestructionException(taskInfo.getError().getLocalizedMessage()); } }
public void createHardDisk(int diskSizeMB, VirtualDiskType type, VirtualDiskMode mode) throws Exception { VirtualMachineConfigSpec vmConfigSpec = new VirtualMachineConfigSpec(); VirtualDeviceConfigSpec diskSpec = new VirtualDeviceConfigSpec(); VirtualDiskFlatVer2BackingInfo diskfileBacking = new VirtualDiskFlatVer2BackingInfo(); diskfileBacking.setFileName(""); diskfileBacking.setDiskMode(mode.toString()); diskfileBacking.setThinProvisioned(type==VirtualDiskType.thin); VirtualSCSIController scsiController = getFirstAvailableController(VirtualSCSIController.class); int unitNumber = getFirstFreeUnitNumberForController(scsiController); VirtualDisk disk = new VirtualDisk(); disk.setControllerKey(scsiController.key); disk.setUnitNumber(unitNumber); disk.setBacking(diskfileBacking); disk.setCapacityInKB(1024 * diskSizeMB); disk.setKey(-1); diskSpec.setOperation(VirtualDeviceConfigSpecOperation.add); diskSpec.setFileOperation(VirtualDeviceConfigSpecFileOperation.create); diskSpec.setDevice(disk); VirtualDeviceConfigSpec vdiskSpec = diskSpec; VirtualDeviceConfigSpec [] vdiskSpecArray = {vdiskSpec}; vmConfigSpec.setDeviceChange(vdiskSpecArray); Task task = vm.reconfigVM_Task(vmConfigSpec); task.waitForTask(200, 100); }
public void addHardDisk(String diskFilePath, VirtualDiskMode diskMode) throws Exception { VirtualMachineConfigSpec vmConfigSpec = new VirtualMachineConfigSpec(); VirtualDeviceConfigSpec diskSpec = new VirtualDeviceConfigSpec(); VirtualDeviceConfigSpec[] vdiskSpecArray = {diskSpec}; vmConfigSpec.setDeviceChange(vdiskSpecArray); VirtualDiskFlatVer2BackingInfo diskfileBacking = new VirtualDiskFlatVer2BackingInfo(); diskfileBacking.setFileName(diskFilePath); diskfileBacking.setDiskMode(diskMode.toString()); VirtualSCSIController scsiController = getFirstAvailableController(VirtualSCSIController.class); int unitNumber = getFirstFreeUnitNumberForController(scsiController); VirtualDisk disk = new VirtualDisk(); disk.setControllerKey(scsiController.key); disk.setUnitNumber(unitNumber); disk.setBacking(diskfileBacking); //Unlike required by API ref, the capacityKB is optional. So skip setCapacityInKB() method. disk.setKey(-100); diskSpec.setOperation(VirtualDeviceConfigSpecOperation.add); diskSpec.setDevice(disk); Task task = vm.reconfigVM_Task(vmConfigSpec); task.waitForTask(200, 100); }
/** Create a new virtual network adapter on the VM * Your MAC address should start with 00:50:56 */ public void createNetworkAdapter(VirtualNetworkAdapterType type, String networkName, String macAddress, boolean wakeOnLan, boolean startConnected) throws InvalidProperty, RuntimeFault, RemoteException, InterruptedException { VirtualMachinePowerState powerState = vm.getRuntime().getPowerState(); String vmVerStr = vm.getConfig().getVersion(); int vmVer = Integer.parseInt(vmVerStr.substring(vmVerStr.length()-2)); if((powerState == VirtualMachinePowerState.suspended) || (powerState == VirtualMachinePowerState.suspended && vmVer < 7)) { throw new InvalidPowerState(); } HostSystem host = new HostSystem(vm.getServerConnection(), vm.getRuntime().getHost()); ComputeResource cr = (ComputeResource) host.getParent(); EnvironmentBrowser envBrowser = cr.getEnvironmentBrowser(); ConfigTarget configTarget = envBrowser.queryConfigTarget(host); VirtualMachineConfigOption vmCfgOpt = envBrowser.queryConfigOption(null, host); type = validateNicType(vmCfgOpt.getGuestOSDescriptor(), vm.getConfig().getGuestId(), type); VirtualDeviceConfigSpec nicSpec = createNicSpec(type, networkName, macAddress, wakeOnLan, startConnected, configTarget); VirtualMachineConfigSpec vmConfigSpec = new VirtualMachineConfigSpec(); vmConfigSpec.setDeviceChange(new VirtualDeviceConfigSpec []{nicSpec}); Task task = vm.reconfigVM_Task(vmConfigSpec); task.waitForTask(200, 100); }
/** * Remove the device. Make sure the VM is powered off before calling this method. * If destroyDeviceBacking is true, it deletes backings for example files in datastore. BE CAREFUL! */ public Task removeDevice(VirtualDevice device, boolean destroyDeviceBacking) throws InvalidName, VmConfigFault, DuplicateName, TaskInProgress, FileFault, InvalidState, ConcurrentAccess, InvalidDatastore, InsufficientResourcesFault, RuntimeFault, RemoteException { ArrayList<VirtualDevice> deviceList = new ArrayList<VirtualDevice>(); deviceList.add(device); return removeDevices(deviceList, destroyDeviceBacking); }
public static void main(String[] args) throws Exception { if(args.length != 3) { System.out.println("Usage: java PrintTaskManager " + "<url> <username> <password>"); return; } ServiceInstance si = new ServiceInstance( new URL(args[0]), args[1], args[2], true); TaskManager taskMgr = si.getTaskManager(); int maxCollector = taskMgr.getMaxCollector(); System.out.println("Maximum number of collectors to " + "retrive historical tasks: " + maxCollector); System.out.println("\nTask description:"); TaskDescription td = taskMgr.getDescriptioin(); printTaskDescription(td); System.out.println("\nRecent tasks:"); Task[] recentTasks = taskMgr.getRecentTasks(); for(int i=0; recentTasks!=null && i<recentTasks.length; i++) { TaskInfo ti = recentTasks[i].getTaskInfo(); System.out.println("\nName:" + ti.getName()); System.out.println("Key:" + ti.getKey()); System.out.println("State:" + ti.getState()); } si.getServerConnection().logout(); }
private static boolean migrateVM(ServiceInstance si, Folder rootFolder, HostSystem newHost, String targetVMName, String newHostName) throws Exception { log("Selected host [vm] for vMotion: " + newHostName + " [" + targetVMName + "]"); VirtualMachine vm = (VirtualMachine)new InventoryNavigator(rootFolder) .searchManagedEntity("VirtualMachine", targetVMName); if (vm == null) { log(WARNING, "Could not resolve VM " + targetVMName + ", vMotion of this VM cannot be performed."); return false; } ComputeResource cr = (ComputeResource)newHost.getParent(); String[] checks = new String[] { "cpu", "software" }; HostVMotionCompatibility[] vmcs = si.queryVMotionCompatibility(vm, new HostSystem[] { newHost }, checks); String[] comps = vmcs[0].getCompatibility(); if (checks.length != comps.length) { log(WARNING, "CPU/software NOT compatible, vMotion failed."); return false; } long start = System.currentTimeMillis(); Task task = vm.migrateVM_Task(cr.getResourcePool(), newHost, VirtualMachineMovePriority.highPriority, VirtualMachinePowerState.poweredOn); if (task.waitForMe() == Task.SUCCESS) { long end = System.currentTimeMillis(); log("vMotion of " + targetVMName + " to " + newHostName + " completed in " + (end - start) + "ms. Task result: " + task.getTaskInfo().getResult()); return true; } else { TaskInfo info = task.getTaskInfo(); log(WARNING, "vMotion of " + targetVMName + " to " + newHostName + " failed. Error details: " + info.getError().getFault()); return false; } }
Task copyVirtualDiskTask(String sourceName, Datacenter sourceDatacenter, String destName, Datacenter destDatacenter, VirtualDiskSpec destSpec, Boolean force) throws FileFault, RuntimeFault, RemoteException;
@Override public Task copyDatastoreFileTask(String sourceName, Datacenter sourceDatacenter, String destinationName, Datacenter destinationDatacenter, boolean force) throws FileFault, InvalidDatastore, RuntimeFault, RemoteException { return null; //To change body of implemented methods use File | Settings | File Templates. }
@Override public Task deleteDatastoreFileTask(String name, Datacenter datacenter) throws FileFault, InvalidDatastore, RuntimeFault, RemoteException { return null; //To change body of implemented methods use File | Settings | File Templates. }
@Override public Task moveDatastoreFileTask(String sourceName, Datacenter sourceDatacenter, String destinationName, Datacenter destinationDatacenter, boolean force) throws FileFault, InvalidDatastore, RuntimeFault, RemoteException { return null; //To change body of implemented methods use File | Settings | File Templates. }
@Nullable Task startInstance(VmwareCloudInstance instance, String agentName, CloudInstanceUserData userData) throws VmwareCheckedCloudException, InterruptedException;
Task reconfigureInstance(@NotNull final VmwareCloudInstance instance, @NotNull final String agentName, @NotNull final CloudInstanceUserData userData) throws VmwareCheckedCloudException;
/** * @param floppyImagePath - i.e. "[storage1] myVM/myFloppy.flp" Note: there is a space after ]. */ public Task addFloppyDriveFromISO(String floppyImagePath, boolean startConnected) throws InvalidName, VmConfigFault, DuplicateName, TaskInProgress, FileFault, InvalidState, ConcurrentAccess, InvalidDatastore, InsufficientResourcesFault, RuntimeFault, RemoteException { return addFloppyDrive(floppyImagePath, null, null, startConnected); }
/** * @param hostDevice - i.e. "/dev/fd0" */ public Task addFloppyDriveFromHost(String hostDevice, boolean startConnected) throws InvalidName, VmConfigFault, DuplicateName, TaskInProgress, FileFault, InvalidState, ConcurrentAccess, InvalidDatastore, InsufficientResourcesFault, RuntimeFault, RemoteException { return addFloppyDrive(null, null, hostDevice, startConnected); }
public Task createFloppyDrive(String floppyImagePath, boolean startConnected) throws InvalidName, VmConfigFault, DuplicateName, TaskInProgress, FileFault, InvalidState, ConcurrentAccess, InvalidDatastore, InsufficientResourcesFault, RuntimeFault, RemoteException { return addFloppyDrive(null, floppyImagePath, null, startConnected); }
public static void main(String[] args) throws Exception { if(args.length!=6) { System.out.println("Usage: java VmNicOp <url> " + "<username> <password> <vmname> <op> <name>"); System.out.println("op - add|remove"); System.out.println("name - NIC name when remove; " + "Network name when add"); System.exit(0); } String vmname = args[3]; String op = args[4]; String name = args[5]; ServiceInstance si = new ServiceInstance( new URL(args[0]), args[1], args[2], true); Folder rootFolder = si.getRootFolder(); VirtualMachine vm = (VirtualMachine) new InventoryNavigator( rootFolder).searchManagedEntity("VirtualMachine", vmname); if(vm==null) { System.out.println("No VM " + vmname + " found"); si.getServerConnection().logout(); return; } VirtualMachineConfigSpec vmConfigSpec = new VirtualMachineConfigSpec(); VirtualDeviceConfigSpec nicSpec = getNICDeviceConfigSpec(vm, op, name); String result = null; if(nicSpec!=null) { vmConfigSpec.setDeviceChange( new VirtualDeviceConfigSpec []{nicSpec}); Task task = vm.reconfigVM_Task(vmConfigSpec); result = task.waitForMe(); } if(result==Task.SUCCESS) { System.out.println("Done with NIC for VM:" + vmname); } else { System.out.println("Failed with NIC for VM:" + vmname); } si.getServerConnection().logout(); }
public static void main(String[] args) throws Exception { CommandLineParser clp = new CommandLineParser(constructOptions(), args); String urlStr = clp.get_option("url"); String username = clp.get_option("username"); String password = clp.get_option("password"); String cloneName = clp.get_option("CloneName"); String vmPath = clp.get_option("vmPath"); String datacenterName= clp.get_option("DatacenterName"); try { ServiceInstance si = new ServiceInstance(new URL(urlStr), username, password, true); VirtualMachine vm = (VirtualMachine) si.getSearchIndex().findByInventoryPath(vmPath); Datacenter dc = (Datacenter) si.getSearchIndex().findByInventoryPath(datacenterName); if(vm==null || dc ==null) { System.out.println("VirtualMachine or Datacenter path is NOT correct. Pls double check. "); return; } Folder vmFolder = dc.getVmFolder(); VirtualMachineCloneSpec cloneSpec = new VirtualMachineCloneSpec(); cloneSpec.setLocation(new VirtualMachineRelocateSpec()); cloneSpec.setPowerOn(false); cloneSpec.setTemplate(false); Task task = vm.cloneVM_Task(vmFolder, cloneName, cloneSpec); System.out.println("Launching the VM clone task. It might take a while. Please wait for the result ..."); String status = task.waitForMe(); if(status==Task.SUCCESS) { System.out.println("Virtual Machine got cloned successfully."); } else { System.out.println("Failure -: Virtual Machine cannot be cloned"); } } catch(RemoteException re) { re.printStackTrace(); } catch(MalformedURLException mue) { mue.printStackTrace(); } }
public static void main(String[] args) throws Exception { if(args.length!=5) { System.out.println("Usage: java CloneVM <url> " + "<username> <password> <vmname> <clonename>"); System.exit(0); } String vmname = args[3]; String cloneName = args[4]; ServiceInstance si = new ServiceInstance( new URL(args[0]), args[1], args[2], true); Folder rootFolder = si.getRootFolder(); VirtualMachine vm = (VirtualMachine) new InventoryNavigator( rootFolder).searchManagedEntity( "VirtualMachine", vmname); if(vm==null) { System.out.println("No VM " + vmname + " found"); si.getServerConnection().logout(); return; } VirtualMachineCloneSpec cloneSpec = new VirtualMachineCloneSpec(); cloneSpec.setLocation(new VirtualMachineRelocateSpec()); cloneSpec.setPowerOn(false); cloneSpec.setTemplate(false); Task task = vm.cloneVM_Task((Folder) vm.getParent(), cloneName, cloneSpec); System.out.println("Launching the VM clone task. " + "Please wait ..."); String status = task.waitForMe(); if(status==Task.SUCCESS) { System.out.println("VM got cloned successfully."); } else { System.out.println("Failure -: VM cannot be cloned"); } }
public static void main(String[] args) throws Exception { if(args.length!=5) { System.out.println("Usage: java MigrateVM <url> " + "<username> <password> <vmname> <newhost>"); System.exit(0); } String vmname = args[3]; String newHostName = args[4]; ServiceInstance si = new ServiceInstance( new URL(args[0]), args[1], args[2], true); Folder rootFolder = si.getRootFolder(); VirtualMachine vm = (VirtualMachine) new InventoryNavigator( rootFolder).searchManagedEntity( "VirtualMachine", vmname); HostSystem newHost = (HostSystem) new InventoryNavigator( rootFolder).searchManagedEntity( "HostSystem", newHostName); ComputeResource cr = (ComputeResource) newHost.getParent(); String[] checks = new String[] {"cpu", "software"}; HostVMotionCompatibility[] vmcs = si.queryVMotionCompatibility(vm, new HostSystem[] {newHost},checks ); String[] comps = vmcs[0].getCompatibility(); if(checks.length != comps.length) { System.out.println("CPU/software NOT compatible. Exit."); si.getServerConnection().logout(); return; } Task task = vm.migrateVM_Task(cr.getResourcePool(), newHost, VirtualMachineMovePriority.highPriority, VirtualMachinePowerState.poweredOn); if(task.waitForMe()==Task.SUCCESS) { System.out.println("VMotioned!"); } else { System.out.println("VMotion failed!"); TaskInfo info = task.getTaskInfo(); System.out.println(info.getError().getFault()); } si.getServerConnection().logout(); }
public static void main(String[] args) throws Exception { if(args.length!=6) { System.out.println("Usage: java VmAllocateResource <url> " + "<username> <password> <vmname> <device> <value>"); System.out.println("device - cpu|memory"); System.out.println("value: high|low|normal|numeric value"); System.exit(0); } String vmname = args[3]; String deviceType = args[4]; String value = args[5]; ServiceInstance si = new ServiceInstance( new URL(args[0]), args[1], args[2], true); Folder rootFolder = si.getRootFolder(); VirtualMachine vm = (VirtualMachine) new InventoryNavigator( rootFolder).searchManagedEntity("VirtualMachine", vmname); if(vm==null) { System.out.println("No VM " + vmname + " found"); si.getServerConnection().logout(); return; } VirtualMachineConfigSpec vmConfigSpec = new VirtualMachineConfigSpec(); if("memory".equalsIgnoreCase(deviceType)) { System.out.println("Reconfig memory for VM: " + vmname); vmConfigSpec.setMemoryAllocation(getShares(value)); } else if("cpu".equalsIgnoreCase(deviceType)) { System.out.println("Reconfig CPU for VM: " + vmname); vmConfigSpec.setCpuAllocation(getShares(value)); } else { System.out.println("Incorrect option for " + vmname); } Task task = vm.reconfigVM_Task(vmConfigSpec); task.waitForMe(); }
public static void main(String[] args) throws Exception { if(args.length!=5) { System.out.println("Usage: java RemoveVmDisk <url> " + "<username> <password> <vmname> <diskname>"); System.exit(0); } String vmname = args[3]; String diskName = args[4]; ServiceInstance si = new ServiceInstance( new URL(args[0]), args[1], args[2], true); Folder rootFolder = si.getRootFolder(); VirtualMachine vm = (VirtualMachine) new InventoryNavigator( rootFolder).searchManagedEntity("VirtualMachine", vmname); if(vm==null) { System.out.println("No VM " + vmname + " found"); si.getServerConnection().logout(); return; } VirtualMachineConfigSpec vmConfigSpec = new VirtualMachineConfigSpec(); VirtualDeviceConfigSpec vdiskSpec = createRemoveDiskConfigSpec(vm.getConfig(), diskName); vmConfigSpec.setDeviceChange( new VirtualDeviceConfigSpec[]{vdiskSpec} ); Task task = vm.reconfigVM_Task(vmConfigSpec); if(task.waitForMe()==Task.SUCCESS) { System.out.println("Disk removed."); } else { System.out.println("Error while removing disk"); } si.getServerConnection().logout(); }
public static void main(String[] args) throws Exception { if(args.length!=3) { System.out.println("Usage: java CreateVM <url> " + "<username> <password>"); System.exit(0); } String dcName = "ha-datacenter"; String vmName = "vimasterVM"; long memorySizeMB = 500; int cupCount = 1; String guestOsId = "sles10Guest"; long diskSizeKB = 1000000; // mode: persistent|independent_persistent, // independent_nonpersistent String diskMode = "persistent"; String datastoreName = "storage1 (2)"; String netName = "VM Network"; String nicName = "Network Adapter 1"; ServiceInstance si = new ServiceInstance( new URL(args[0]), args[1], args[2], true); Folder rootFolder = si.getRootFolder(); Datacenter dc = (Datacenter) new InventoryNavigator( rootFolder).searchManagedEntity("Datacenter", dcName); ResourcePool rp = (ResourcePool) new InventoryNavigator( dc).searchManagedEntities("ResourcePool")[0]; Folder vmFolder = dc.getVmFolder(); // create vm config spec VirtualMachineConfigSpec vmSpec = new VirtualMachineConfigSpec(); vmSpec.setName(vmName); vmSpec.setAnnotation("VirtualMachine Annotation"); vmSpec.setMemoryMB(memorySizeMB); vmSpec.setNumCPUs(cupCount); vmSpec.setGuestId(guestOsId); // create virtual devices int cKey = 1000; VirtualDeviceConfigSpec scsiSpec = createScsiSpec(cKey); VirtualDeviceConfigSpec diskSpec = createDiskSpec( datastoreName, cKey, diskSizeKB, diskMode); VirtualDeviceConfigSpec nicSpec = createNicSpec( netName, nicName); vmSpec.setDeviceChange(new VirtualDeviceConfigSpec[] {scsiSpec, diskSpec, nicSpec}); // create vm file info for the vmx file VirtualMachineFileInfo vmfi = new VirtualMachineFileInfo(); vmfi.setVmPathName("["+ datastoreName +"]"); vmSpec.setFiles(vmfi); // call the createVM_Task method on the vm folder Task task = vmFolder.createVM_Task(vmSpec, rp, null); String result = task.waitForMe(); if(result == Task.SUCCESS) { System.out.println("VM Created Sucessfully"); } else { System.out.println("VM could not be created. "); } }
public static void main(String[] args) throws Exception { if(args.length != 3) { System.out.println("Usage: java CopyFile " + "<url> <username> <password>"); return; } ServiceInstance si = new ServiceInstance( new URL(args[0]), args[1], args[2], true); Datacenter dc = (Datacenter)new InventoryNavigator( si.getRootFolder()).searchManagedEntity( "Datacenter", "ha-datacenter"); FileManager fileMgr = si.getFileManager(); if(fileMgr==null) { System.out.println("FileManager not available."); si.getServerConnection().logout(); return; } String basePath = "[storage1 (2)] Nostalgia011"; String dirPath = basePath + "/" + "testDir"; // create parent directories if needed - true fileMgr.makeDirectory(dirPath, dc, true); String srcPath = basePath + "/Nostalgia011.vmdk"; String dstPath = dirPath + "/copy of Nostalgia011.vmdk"; Task cTask = fileMgr.copyDatastoreFile_Task(srcPath, dc, dstPath, dc, true); if(cTask.waitForMe()==Task.SUCCESS) { System.out.println("File copied successfully!"); } else { System.out.println("File copy failed!"); return; } Thread.sleep(30*1000); fileMgr.deleteDatastoreFile_Task(dstPath, dc); fileMgr.deleteDatastoreFile_Task(dirPath, dc); si.getServerConnection().logout(); }
@Override public String createMachine( TargetHandlerParameters parameters ) throws TargetException { this.logger.fine( "Creating a new VM @ VMware." ); // For IaaS, we only expect root instance names to be passed if( InstanceHelpers.countInstances( parameters.getScopedInstancePath()) > 1 ) throw new TargetException( "Only root instances can be passed in arguments." ); String rootInstanceName = InstanceHelpers.findRootInstancePath( parameters.getScopedInstancePath()); // Deal with the creation try { System.setProperty("org.xml.sax.driver","org.apache.xerces.parsers.SAXParser"); Map<String,String> targetProperties = parameters.getTargetProperties(); final String machineImageId = targetProperties.get( TEMPLATE ); final ServiceInstance vmwareServiceInstance = getServiceInstance( targetProperties ); final ComputeResource vmwareComputeResource = (ComputeResource)( new InventoryNavigator( vmwareServiceInstance.getRootFolder()) .searchManagedEntity("ComputeResource", targetProperties.get( CLUSTER ))); // Generate the user data first, so that nothing has been done on the IaaS if it fails String userData = UserDataHelpers.writeUserDataAsString( parameters.getMessagingProperties(), parameters.getDomain(), parameters.getApplicationName(), rootInstanceName ); VirtualMachine vm = getVirtualMachine( vmwareServiceInstance, machineImageId ); String vmwareDataCenter = targetProperties.get( DATA_CENTER ); Folder vmFolder = ((Datacenter)(new InventoryNavigator( vmwareServiceInstance.getRootFolder()) .searchManagedEntity("Datacenter", vmwareDataCenter))) .getVmFolder(); this.logger.fine("machineImageId=" + machineImageId); if (vm == null || vmFolder == null) throw new TargetException("VirtualMachine (= " + vm + " ) or Datacenter path (= " + vmFolder + " ) is NOT correct. Please, double check."); VirtualMachineCloneSpec cloneSpec = new VirtualMachineCloneSpec(); cloneSpec.setLocation(new VirtualMachineRelocateSpec()); cloneSpec.setPowerOn(false); cloneSpec.setTemplate(true); VirtualMachineConfigSpec vmSpec = new VirtualMachineConfigSpec(); vmSpec.setAnnotation( userData ); cloneSpec.setConfig(vmSpec); Task task = vm.cloneVM_Task( vmFolder, rootInstanceName, cloneSpec ); this.logger.fine("Cloning the template: "+ machineImageId +" ..."); String status = task.waitForTask(); if (!status.equals(Task.SUCCESS)) throw new TargetException("Failure: Virtual Machine cannot be cloned." ); VirtualMachine vm2 = getVirtualMachine( vmwareServiceInstance, rootInstanceName ); this.logger.fine("Transforming the clone template to Virtual machine ..."); vm2.markAsVirtualMachine( vmwareComputeResource.getResourcePool(), null); DynamicProperty dprop = new DynamicProperty(); dprop.setName("guestinfo.userdata"); dprop.setVal(userData); vm2.getGuest().setDynamicProperty(new DynamicProperty[]{dprop}); task = vm2.powerOnVM_Task(null); this.logger.fine("Starting the virtual machine: "+ rootInstanceName +" ..."); status = task.waitForTask(); if( ! status.equals( Task.SUCCESS )) throw new TargetException("Failure: Virtual Machine cannot be started." ); return vm2.getName(); } catch( Exception e ) { throw new TargetException( e ); } }
/** * SDK4.1 signature for back compatibility */ Task applyHostConfigTask(HostSystem host, HostConfigSpec configSpec) throws HostConfigFailed, InvalidState, RuntimeFault, RemoteException;