private static String findVMNotOnHost(HostSystem host) throws RemoteException { VirtualMachine[] hostVMs = host.getVms(); boolean foundMatch = false; String targetVM = null; for (String vmName : vmNames) { for (VirtualMachine vm : hostVMs) { if (vmName.equals(vm.getName())) { foundMatch = true; break; } } if (!foundMatch) { targetVM = vmName; break; } foundMatch = false; } return targetVM; }
/** * Returns the display name of a VM */ private void getVmName(String vmName, PrintWriter out) throws IOException { try { VirtualMachine vm = (VirtualMachine) getManagedEntity(vmName, "VirtualMachine"); String name = ""; if (vm == null) { LOG.warn("No VM named '" + vmName + "' found"); } else { name = vm.getName(); } out.print(name); out.flush(); } catch (Exception ex) { LOG.error("An error occurred : " + ex.toString()); } }
protected void scan(VirtualMachine vm) { logger.debug("scanning vm: {}", vm.getName()); ObjectNode n = toComputeNodeData(vm); updateComputeInstance(n); }
/** * Deploy virtual machines, according to universe parameters */ public void deploy() { log.info("Vm deployment"); Map<String, VirtualMachine> deployment = new HashMap<>(); List<CompletableFuture<VirtualMachine>> asyncDeployment = universeParams.getVmIpAddresses() .keySet() .stream() .map(this::deployVmAsync) .collect(Collectors.toList()); asyncDeployment .stream() .map(CompletableFuture::join) .forEach(vm -> { universeParams.updateIpAddress(vm.getName(), vm.getGuest().getIpAddress()); deployment.put(vm.getName(), vm); }); log.info("The deployed VMs are: {}", universeParams.getVmIpAddresses()); vms.putAll(deployment); }
/** * Returns a JSON-formatted array with the virtual machines list for use * with Zabbix low-level discovery */ private void getVMs(PrintWriter out) throws IOException { try { ManagedEntity[] vms = getManagedEntities("VirtualMachine"); JsonArray jArray = new JsonArray(); for (int j = 0; j < vms.length; j++) { VirtualMachine vm = (VirtualMachine) vms[j]; VirtualMachineConfigInfo vmcfg = vm.getConfig(); if (vm != null && vmcfg != null) { JsonObject jObject = new JsonObject(); String vmName = vm.getName(); String vmUuid = vmcfg.getUuid(); jObject.addProperty("{#VIRTUALMACHINE}", vmName); jObject.addProperty("{#UUID}", vmUuid); jArray.add(jObject); } } JsonObject jOutput = new JsonObject(); jOutput.add("data", jArray); out.print(jOutput); out.flush(); } catch (Exception ex) { LOG.error("An error occurred : " + ex.toString()); } }
private static boolean validateVMNotOnHost(ServiceInstance si, Folder rootFolder, HostSystem newHost, String vmName, String hostName) throws Exception { VirtualMachine[] vms = newHost.getVms(); for (VirtualMachine vmac : vms) { if (vmac.getName().equals(vmName)) { Log.getLogWriter().info( vmName + " is already running on target host " + hostName + ". Selecting another pair..."); return false; } } return true; }
/** * 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."); } }
public static void main(String[] args) throws Exception { long start = System.currentTimeMillis(); ServiceInstance si = new ServiceInstance(new URL("https://8.8.8.8/sdk"), "root", "password", true); long end = System.currentTimeMillis(); System.out.println("time taken:" + (end-start)); Folder rootFolder = si.getRootFolder(); String name = rootFolder.getName(); System.out.println("root:" + name); ManagedEntity[] mes = new InventoryNavigator(rootFolder).searchManagedEntities("VirtualMachine"); if(mes==null || mes.length ==0) { return; } VirtualMachine vm = (VirtualMachine) mes[0]; VirtualMachineConfigInfo vminfo = vm.getConfig(); VirtualMachineCapability vmc = vm.getCapability(); vm.getResourcePool(); System.out.println("Hello " + vm.getName()); System.out.println("GuestOS: " + vminfo.getGuestFullName()); System.out.println("Multiple snapshot supported: " + vmc.isMultipleSnapshotsSupported()); si.getServerConnection().logout(); }
/** * Checks whether the virtual machine should be imported into the requisition. * * @param virtualMachine the system to check * @return true for import, false otherwise */ private boolean checkVMPowerState(VirtualMachine virtualMachine) { logger.debug("Checking power state for VM {} (ID: {})", virtualMachine.getName(), virtualMachine.getMOR().getVal()); String powerState = virtualMachine.getRuntime().getPowerState().toString(); if ("poweredOn".equals(powerState) && request.isImportVMPoweredOn()) { return true; } if ("poweredOff".equals(powerState) && request.isImportVMPoweredOff()) { return true; } if ("suspended".equals(powerState) && request.isImportVMSuspended()) { return true; } return false; }
protected void updateHostVmRelationship(HostSystem h, VirtualMachine vm) { logger.debug("updating relationship between host={} and vm={}", h.getName(), vm.getName()); String cypher = "match (h:ComputeHost {id:{hostId} }), (c:ComputeInstance {id: {computeId}}) MERGE (h)-[r:HOSTS]->(c) ON CREATE SET r.updateTs=timestamp(),r.createTs=timestamp() ON MATCH SET r.updateTs=timestamp() return r"; getProjector().getNeoRxClient().execCypher(cypher, "hostId", getUniqueId(h), "computeId", getUniqueId(vm)); }
System.out.println(" "+vms[k].getName());
/** * Checks whether the virtual machine should be imported into the requisition. * * @param virtualMachine the system to check * @return true for import, false otherwise */ private boolean checkVMPowerState(VirtualMachine virtualMachine) { logger.debug("Checking power state for VM {} (ID: {})", virtualMachine.getName(), virtualMachine.getMOR().getVal()); String powerState = virtualMachine.getRuntime().getPowerState().toString(); if ("poweredOn".equals(powerState) && request.isImportVMPoweredOn()) { return true; } if ("poweredOff".equals(powerState) && request.isImportVMPoweredOff()) { return true; } if ("suspended".equals(powerState) && request.isImportVMSuspended()) { return true; } return false; }
public static void main(String[] args) throws Exception { long start = System.currentTimeMillis(); ServiceInstance si = SampleUtil.createServiceInstance(); long end = System.currentTimeMillis(); Folder rootFolder = si.getRootFolder(); System.out.println("time taken:" + (end - start)); String name = rootFolder.getName(); System.out.println("vc root folder:" + name); ManagedEntity[] mes = new InventoryNavigator(rootFolder).searchManagedEntities("VirtualMachine"); if (mes == null || mes.length == 0) { return; } VirtualMachine vm = (VirtualMachine) mes[0]; VirtualMachineConfigInfo vminfo = vm.getConfig(); VirtualMachineCapability vmc = vm.getCapability(); System.out.println("Name: " + vm.getName()); System.out.println("IP: " + vm.getGuest().getIpAddress()); System.out.println("FQDN: " + vm.getGuest().getHostName()); System.out.println("MOID: " + vm.getMOR().val); System.out.println("InstanceUUID: " + vm.getSummary().getConfig().getInstanceUuid()); System.out.println("GuestOS: " + vminfo.getGuestFullName()); System.out.println("Multiple snapshot supported: " + vmc.isMultipleSnapshotsSupported()); si.getServerConnection().logout(); }
public static void main(String[] args) throws Exception { ServiceInstance si = new ServiceInstance(new URL("https://10.20.143.209/sdk"), "Administrator", "password", true); ClusterComputeResource drsCluster = (ClusterComputeResource) new InventoryNavigator( si.getRootFolder()).searchManagedEntity("ClusterComputeResource", "myDrs"); if(drsCluster==null) { System.out.println("There is no cluster called myDrs. Exiting..."); } ClusterDrsMigration[] histories = drsCluster.getMigrationHistory(); if(histories==null) { System.out.println("There is no migration history set. Please check whether it's running in automatic mode!\nExiting..."); } System.out.println("There were totally " + histories.length + " migration(s)."); for(int i=0; i < histories.length; i++) { ServerConnection sc = si.getServerConnection(); VirtualMachine vm = (VirtualMachine) MorUtil.createExactManagedEntity(sc, histories[i].getVm()); HostSystem srcHost = (HostSystem) MorUtil.createExactManagedEntity(sc, histories[i].getSource()); HostSystem dstHost = (HostSystem) MorUtil.createExactManagedEntity(sc, histories[i].getDestination()); System.out.println("VM: " + vm.getName() + " migrated from " + srcHost.getName() + " to " + dstHost.getName()); } si.getServerConnection().logout(); } }
public static void main(String[] args) throws Exception { ServiceInstance si = new ServiceInstance(new URL("https://10.20.143.209/sdk"), "Administrator", "password", true); ClusterComputeResource drsCluster = (ClusterComputeResource) new InventoryNavigator( si.getRootFolder()).searchManagedEntity("ClusterComputeResource", "myDrs"); if(drsCluster==null) { System.out.println("There is no cluster called myDrs. Exiting..."); } ClusterDrsMigration[] histories = drsCluster.getMigrationHistory(); if(histories==null) { System.out.println("There is no migration history set. Please check whether it's running in automatic mode!\nExiting..."); } System.out.println("There were totally " + histories.length + " migration(s)."); for(int i=0; i < histories.length; i++) { ServerConnection sc = si.getServerConnection(); VirtualMachine vm = (VirtualMachine) MorUtil.createExactManagedEntity(sc, histories[i].getVm()); HostSystem srcHost = (HostSystem) MorUtil.createExactManagedEntity(sc, histories[i].getSource()); HostSystem dstHost = (HostSystem) MorUtil.createExactManagedEntity(sc, histories[i].getDestination()); System.out.println("VM: " + vm.getName() + " migrated from " + srcHost.getName() + " to " + dstHost.getName()); } si.getServerConnection().logout(); } }
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."); } }
public VmServerDO(VirtualMachine vm) { VirtualMachineConfigInfo config = vm.getConfig();//虚拟机配置信息 this.invokeVmName(vm.getName()); this.content = config.getAnnotation(); this.memory = config.getHardware().getMemoryMB(); this.cpu = config.getHardware().getNumCPU(); VirtualMachinePowerState state = vm.getRuntime().powerState; this.powerState = vm.getRuntime().powerState.name(); }
static VirtualDeviceConfigSpec createAddCdConfigSpec(VirtualMachine vm, String dsName, String isoName) throws Exception { VirtualDeviceConfigSpec cdSpec = new VirtualDeviceConfigSpec(); cdSpec.setOperation(VirtualDeviceConfigSpecOperation.add); VirtualCdrom cdrom = new VirtualCdrom(); VirtualCdromIsoBackingInfo cdDeviceBacking = new VirtualCdromIsoBackingInfo(); DatastoreSummary ds = findDatastoreSummary(vm, dsName); cdDeviceBacking.setDatastore(ds.getDatastore()); cdDeviceBacking.setFileName("[" + dsName +"] "+ vm.getName() + "/" + isoName + ".iso"); VirtualDevice vd = getIDEController(vm); cdrom.setBacking(cdDeviceBacking); cdrom.setControllerKey(vd.getKey()); cdrom.setUnitNumber(vd.getUnitNumber()); cdrom.setKey(-1); cdSpec.setDevice(cdrom); return cdSpec; }
static VirtualDeviceConfigSpec createAddCdConfigSpec(VirtualMachine vm, String dsName, String isoName) throws Exception { VirtualDeviceConfigSpec cdSpec = new VirtualDeviceConfigSpec(); cdSpec.setOperation(VirtualDeviceConfigSpecOperation.add); VirtualCdrom cdrom = new VirtualCdrom(); VirtualCdromIsoBackingInfo cdDeviceBacking = new VirtualCdromIsoBackingInfo(); DatastoreSummary ds = findDatastoreSummary(vm, dsName); cdDeviceBacking.setDatastore(ds.getDatastore()); cdDeviceBacking.setFileName("[" + dsName +"] "+ vm.getName() + "/" + isoName + ".iso"); VirtualDevice vd = getIDEController(vm); cdrom.setBacking(cdDeviceBacking); cdrom.setControllerKey(vd.getKey()); cdrom.setUnitNumber(vd.getUnitNumber()); cdrom.setKey(-1); cdSpec.setDevice(cdrom); return cdSpec; }