/** * Copyright 2009 NetApp, contribution by Eric Forgette * * This is a "drop-in" replacement for waitForMe() that uses a timed polling * in place of waitForValues. * * This method will eat 3 exceptions while trying to get TaskInfo and TaskState. * On the fourth try, the captured exception is thrown. * * @return String based on TaskInfoState * @throws RuntimeFault * @throws RemoteException * @throws InterruptedException * @throws RuntimeException if the third exception is not RuntimeFault or RemoteException * * @author Eric Forgette (forgette@netapp.com) */ public String waitForTask() throws RuntimeFault, RemoteException, InterruptedException { return waitForTask(500,1000); }
/** * Takes a snapshot of this VM. THe name of the snapshot is the current date and time. * The format of the name is yyyy-mm-dd hh:mm:ss * @throws VimFault * @throws RemoteException * @throws InterruptedException */ public void takeSnapshotOfVm() throws VimFault, RemoteException, InterruptedException { DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); Date date = new Date(); String name = dateFormat.format(date); String description = "created by Terraform's take-snapshot command"; Task task = vm.createSnapshot_Task(name, description, false, false); if (task.waitForTask() == Task.SUCCESS) { log.info("Created snapshot with name : " + name + " on virtual machine " + instanceName); } }
/** * Attempts to delete the VM from disk. * @throws RemoteException * @throws InterruptedException */ public void removeVm() throws RemoteException, InterruptedException { try { Task task = vm.destroy_Task(); String status = task.waitForTask(); if (!status.equals("success")) { String message = task.getTaskInfo().getError() .getLocalizedMessage(); throw new RemoteException("Failed: " + message); } } catch (NotFound e) { log.warn("VM not found before attempting to delete it", e); } }
public void addNewNetworkCard(VirtualMachine vm, String netName, String nicName, String nicType) throws NetworkConfigurationException { try { VirtualMachineConfigSpec vmSpec = new VirtualMachineConfigSpec(); VirtualDeviceConfigSpec nicSpec = createNicSpec(netName, nicName, nicType); vmSpec.setDeviceChange(new VirtualDeviceConfigSpec[] {nicSpec}); Task task = vm.reconfigVM_Task(vmSpec); @SuppressWarnings("unused") String result = task.waitForTask(); } catch(Exception e) { throw new NetworkConfigurationException("Exception while adding network card to VM: " + e.getClass().getCanonicalName(), e); } }
/** * Attempts to suspend the VM stored in this CloneTask object according to its OS's suspend command. * @throws InvalidProperty * @throws RuntimeFault * @throws RemoteException * @throws InterruptedException */ public void suspendVm() throws InvalidProperty, RuntimeFault, RemoteException, InterruptedException { VirtualMachineRuntimeInfo vmri = vm.getRuntime(); if (vmri.getPowerState() == VirtualMachinePowerState.poweredOn) { com.vmware.vim25.mo.Task task = vm.suspendVM_Task(); task.waitForTask(); log.info("vm:" + vm.getName() + " was suspended."); } }
/** * Powers off the VM stored in this CloneTask object. This is a "hard" powering off. * @throws InvalidProperty * @throws RuntimeFault * @throws RemoteException * @throws InterruptedException */ public void powerOffVm() throws InvalidProperty, RuntimeFault, RemoteException, InterruptedException { VirtualMachineRuntimeInfo vmri = vm.getRuntime(); if (vmri.getPowerState() == VirtualMachinePowerState.poweredOn) { sentPowerDown = true; com.vmware.vim25.mo.Task task = vm.powerOffVM_Task(); task.waitForTask(); log.info("vm:" + vm.getName() + " powered off."); } }
@Override public void terminateVM( String instanceId ) throws IaasException { try { VirtualMachine vm = getVirtualMachine(instanceId); if (vm == null) { throw new IaasException("error vm: "+instanceId+" not found"); } Task task = vm.powerOffVM_Task(); try { if(!(task.waitForTask()).equals(Task.SUCCESS)) { throw new IaasException("error when trying to stop vm: "+instanceId); } } catch (InterruptedException ignore) { /*ignore*/ } task = vm.destroy_Task(); try { if(!(task.waitForTask()).equals(Task.SUCCESS)) { throw new IaasException("error when trying to remove vm: "+instanceId); } } catch (InterruptedException ignore) { /*ignore*/ } } catch(RemoteException e) { throw new IaasException(e); } }
public void removeNetworkAdapter(ServiceInstance si, String vmName, String nicLable) throws Exception { VirtualMachine vm = (VirtualMachine) new InventoryNavigator(si.getRootFolder()).searchManagedEntity("VirtualMachine", vmName); if (vm == null) { System.out.println("Not found vm:" + vmName); return; } VirtualMachineDeviceManager vmdm = new VirtualMachineDeviceManager(vm); List<VirtualEthernetCard> vics = vmdm.getVirtualDevicesOfType(VirtualEthernetCard.class); for (VirtualEthernetCard vic : vics) { if (vic.getDeviceInfo().getLabel().equals(nicLable)) { Task task = vmdm.removeDevice(vic, false); String result = task.waitForTask(); if (Task.SUCCESS.equals(result)) { System.out.println("Remove NIC:" + nicLable + " for vm:" + vmName + " successfully!"); } else { throw new Exception("Remove NIC failed: result=" + result); } break; } } }
/** * Generate the log bundles for the specific hosts. After the task done, print all the URLs of the generated bundles. * @param si ServiceInstance object. * @param includeDefault Specifies if the bundle should include the default server. * @param hosts Lists hosts that are included. */ public void generateLogBundles(ServiceInstance si, boolean includeDefault, HostSystem[] hosts) throws Exception { DiagnosticManager diagMgr = si.getDiagnosticManager(); Task task = diagMgr.generateLogBundles_Task(includeDefault, hosts); String result = task.waitForTask(); if (Task.SUCCESS.equals(result)) { ArrayOfDiagnosticManagerBundleInfo bundleArray = (ArrayOfDiagnosticManagerBundleInfo) task.getTaskInfo().getResult(); DiagnosticManagerBundleInfo[] bundles = bundleArray.getDiagnosticManagerBundleInfo(); if (bundles != null) { System.out.println("============ Log URL ============"); for (DiagnosticManagerBundleInfo bundle : bundles) { System.out.println(bundle.getUrl()); } } else { System.out.println("No bundle generated."); } } else { throw new Exception("Generate log bundles failed: error: " + task.getTaskInfo().getError().getLocalizedMessage()); } }
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 configStaticIp(ServiceInstance si, String vmName, String ip, String netmask, String gateway, String dns1, String dns2) throws Exception { VirtualMachine vm = (VirtualMachine) new InventoryNavigator(si.getRootFolder()).searchManagedEntity("VirtualMachine", vmName); if (vm == null) { System.out.println("Not found vm:" + vmName); return; } VirtualMachineConfigSpec vmConfigSpec = new VirtualMachineConfigSpec(); OptionValue[] extraConfig = new OptionValue[1]; extraConfig[0] = new OptionValue(); //Use machine.id to store the ip related information. This information will be written to the .vmx file of the virtual machine. //And it can be retrieved with vmware tools inside the virtual machine, so the virtual machine can set up the ip, netmask, geteway, dns, etc. according to the information. //There are two sample scripts to retrive the information and set up the ip in the virtual machine, one for Linux(CentOS 6) and Windows(win 7): //Linux: src/main/resources/setup-ip.sh //Windows: src/main/resources/setup-ip.bat //More introduction about the machine.id can be found from: //http://tech.lazyllama.com/2010/06/22/passing-info-from-powercli-into-your-vm-using-guestinfo-variables/ //https://communities.vmware.com/thread/443727?start=0&tstart=0 extraConfig[0].setKey("machine.id"); //The format of ip_config is: ip:ip_value,netmask:netmask_value,gateway:gateway_value,dns1:dns1_value,dns2:dns2_value extraConfig[0].setValue("ip:" + ip + ",netmask:" + netmask + ",gateway:" + gateway + ",dns1:" + dns1 + ",dns2:" + dns2); vmConfigSpec.setExtraConfig(extraConfig); Task task = vm.reconfigVM_Task(vmConfigSpec); String result = task.waitForTask(); if (Task.SUCCESS.equals(result)) { System.out.println("Configure static IP for vm:" + vmName + " successfully!"); } else { throw new Exception("Configure static IP failed: result=" + result); } }
Task task = vm.powerOnVM_Task((HostSystem) inventoryNavigator.searchManagedEntity( "HostSystem", universeParams.getVSphereHost())); task.waitForTask(); cloneTask.waitForTask(); } catch (RemoteException | InterruptedException e) { throw new UniverseException(String.format("Deploy VM %s failed due to ", vmName), e);
public void powerOnVm() throws InvalidProperty, RuntimeFault, RemoteException, InterruptedException { Path hostPath = this.environment.getHostPath(); VirtualHost host = this.environment.fetchVirtualHost(); ComputeResource res = host.getComputeResource(hostPath); HostSystem hostSystem = res.getHosts()[0]; VirtualMachineRuntimeInfo vmri = vm.getRuntime(); if (vmri.getPowerState() == VirtualMachinePowerState.poweredOff || vmri.getPowerState() == VirtualMachinePowerState.suspended) { com.vmware.vim25.mo.Task task = vm.powerOnVM_Task(hostSystem); task.waitForTask(); log.info("vm:" + vm.getName() + " powered on."); } }
String result = task.waitForTask(); if (!Task.SUCCESS.equals(result)) { throw new Exception("Impossible to change vlan");
Task task = vm.reconfigVM_Task(vmConfigSpec); task.waitForTask(200, 100);
public void attachNic(VirtualMachine vm, VirtualEthernetCard nic, Network network) throws RemoteException, InterruptedException { VirtualEthernetCardNetworkBackingInfo backing = (VirtualEthernetCardNetworkBackingInfo) nic.getBacking(); backing.setDeviceName(network.getName()); backing.setNetwork(network.getMOR()); nic.setBacking(backing); nic.getDeviceInfo().setSummary(network.getName()); VirtualDeviceConfigSpec nicSpec = new VirtualDeviceConfigSpec(); nicSpec.setOperation(VirtualDeviceConfigSpecOperation.edit); nicSpec.setDevice(nic); VirtualDeviceConfigSpec[] configSpecs = new VirtualDeviceConfigSpec[1]; configSpecs[0] = nicSpec; VirtualMachineConfigSpec machineConfigSpec = new VirtualMachineConfigSpec(); machineConfigSpec.setDeviceChange(configSpecs); Task task = vm.reconfigVM_Task(machineConfigSpec); String status = task.waitForTask(); if (!status.equals("success")) { String message = task.getTaskInfo().getError().getLocalizedMessage(); throw new RemoteException("Failed: " + message); } }
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); }
String status = task.waitForTask();
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); }