private static boolean migrateVM(String targetVMName, String newHostName, boolean tryAnotherVM, boolean tryAnotherHost) throws Exception { ServiceInstance si = new ServiceInstance(new URL(url), username, password, true); try { Folder rootFolder = si.getRootFolder(); HostSystem newHost = (HostSystem)new InventoryNavigator(rootFolder) .searchManagedEntity("HostSystem", newHostName); return migrateVM(si, rootFolder, newHost, targetVMName, newHostName, tryAnotherVM, tryAnotherHost); } finally { si.getServerConnection().logout(); } }
private static synchronized boolean doMigrateVM(String targetVMName, String newHostName) throws Exception { ServiceInstance si = new ServiceInstance(new URL(url), username, password, true); try { Folder rootFolder = si.getRootFolder(); InventoryNavigator in = new InventoryNavigator(rootFolder); HostSystem newHost = (HostSystem)in.searchManagedEntity("HostSystem", newHostName); if (newHost == null) { throw new TestException("Could not find host " + newHostName + " as a target host for vMotion."); } return migrateVM(si, rootFolder, newHost, targetVMName, newHostName); } finally { si.getServerConnection().logout(); } }
public static void HydraTask_migrateNetDownVM() throws Exception { SharedMap sMap = VMotionBB.getBB().getSharedMap(); Boolean bool = (Boolean)sMap.get("connectionDropped"); if (bool == null || !bool) { return; } initializeParams(); if (!validateParams()) { return; } ServiceInstance si = new ServiceInstance(new URL(url), username, password, true); try { Folder rootFolder = si.getRootFolder(); HostSystem newHost = (HostSystem)new InventoryNavigator(rootFolder) .searchManagedEntity("HostSystem", hostNames[0]); migrateVM(si, rootFolder, newHost, vmNames[0], hostNames[0], false, false); } finally { si.getServerConnection().logout(); } }
private Optional<ResourcePool> tryFindResourcePool(Folder folder, String hostname) { Iterable<ResourcePool> resourcePools = ImmutableSet.<ResourcePool>of(); try { ManagedEntity[] resourcePoolEntities = new InventoryNavigator(folder).searchManagedEntities("ResourcePool"); resourcePools = Iterables.transform(Arrays.asList(resourcePoolEntities), new Function<ManagedEntity, ResourcePool>() { public ResourcePool apply(ManagedEntity input) { return (ResourcePool) input; } }); Optional<ResourcePool> optionalResourcePool = Iterables.tryFind(resourcePools, VSpherePredicate.isResourcePoolOf(hostname)); return optionalResourcePool; } catch (Exception e) { logger.error("Problem in finding a valid resource pool", e); } return Optional.absent(); }
private void populateMetrics(Folder rootFolder, List<Map<String, Object>> hostConfigs, Map<Pattern, String> replacers, Integer hostThreads, Integer vmThreads) { List<ManagedEntity> hostEntities = getHostMachines(rootFolder, hostConfigs); if (logger.isDebugEnabled()) { logger.debug("Found " + hostEntities.size() + " hosts"); StringBuilder sb = new StringBuilder(); for (ManagedEntity managedEntity : hostEntities) { if (sb.length() > 0) { sb.append(","); } sb.append(managedEntity.getName()); } logger.debug("Host machines [ " + sb.toString() + " ]"); } HostMetricCollector hostMetricCollector = new HostMetricCollector(configuration.getMetricWriter(), configuration.getMetricPrefix(), hostEntities, hostConfigs, replacers, hostThreads, vmThreads); hostMetricCollector.execute(); }
private List<ManagedEntity> getHostMachines(Folder rootFolder, List<Map<String, Object>> hostConfigs) { List<ManagedEntity> hostEntities = new ArrayList<ManagedEntity>(); for (Map<String, Object> hostConfig : hostConfigs) { String hostName = (String) hostConfig.get("host"); try { if ("*".equals(hostName)) { hostEntities = Arrays.asList(new InventoryNavigator(rootFolder).searchManagedEntities("HostSystem")); } else { ManagedEntity hostSystem = new InventoryNavigator(rootFolder).searchManagedEntity("HostSystem", hostName); if (hostSystem != null) { hostEntities.add(hostSystem); } else { logger.error("Could not find Host with name " + hostName); } } } catch (InvalidProperty invalidProperty) { logger.error("Unable to get the host details", invalidProperty); } catch (RuntimeFault runtimeFault) { logger.error("Unable to get the host details", runtimeFault); } catch (RemoteException e) { logger.error("Unable to get the host details", e); } } return hostEntities; }
private static void dummyVMotion(ServiceInstance si, Folder rootFolder, HostSystem newHost, String targetVMName, String newHostName) { log("Selected host [vm] for vMotion: " + newHostName + " [" + targetVMName + "]"); try {Thread.sleep(120000);} catch(InterruptedException ir) {} log("vMotion of " + targetVMName + " to " + newHostName + " completed"); }
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; }
private Iterable<VirtualMachine> listNodes(VSphereServiceInstance instance) { Iterable<VirtualMachine> vms = ImmutableSet.of(); try { Folder nodesFolder = instance.getInstance().getRootFolder(); ManagedEntity[] managedEntities = new InventoryNavigator(nodesFolder).searchManagedEntities("VirtualMachine"); vms = Iterables.transform(Arrays.asList(managedEntities), new Function<ManagedEntity, VirtualMachine>() { public VirtualMachine apply(ManagedEntity input) { return (VirtualMachine) input; } }); } catch (Throwable e) { logger.error("Can't find vm", e); } return vms; }
@Override public Iterable<VirtualMachine> listNodesByIds(Iterable<String> ids) { Iterable<VirtualMachine> vms = ImmutableSet.of(); try (VSphereServiceInstance instance = serviceInstance.get();) { Folder nodesFolder = instance.getInstance().getRootFolder(); List<List<String>> list = new ArrayList<List<String>>(); Iterator<String> idsIterator = ids.iterator(); while (idsIterator.hasNext()) { list.add(Lists.newArrayList("VirtualMachine", idsIterator.next())); } String[][] typeInfo = ListsUtils.ListToArray(list); ManagedEntity[] managedEntities = new InventoryNavigator(nodesFolder).searchManagedEntities( typeInfo, true); vms = Iterables.transform(Arrays.asList(managedEntities), new Function<ManagedEntity, VirtualMachine>() { public VirtualMachine apply(ManagedEntity input) { return (VirtualMachine) input; } }); } catch (Throwable e) { logger.error("Can't find vms ", e); } return vms; // Iterable<VirtualMachine> nodes = listNodes(); // Iterable<VirtualMachine> selectedNodes = Iterables.filter(nodes, VSpherePredicate.isNodeIdInList(ids)); // return selectedNodes; }
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"); }
private VirtualMachine getVMwareTemplate(String imageName, Folder rootFolder) { VirtualMachine image = null; try { VirtualMachine node = getVM(imageName, rootFolder); if (VSpherePredicate.isTemplatePredicate.apply(node)) image = node; } catch (Exception e) { logger.error("cannot find an image called " + imageName, e); propagate(e); } return checkNotNull(image, "image with name " + imageName + " not found."); }
@Override public Folder apply(final String folderName) { try { if (Strings.isNullOrEmpty(folderName)) return (Folder) master.getParent(); VSphereServiceInstance instance = serviceInstance.get(); ManagedEntity entity = new InventoryNavigator(instance.getInstance().getRootFolder()).searchManagedEntity("Folder", folderName); return (Folder) entity; } catch (Exception e) { logger.error("Problem in finding a valid Folder with name " + folderName, e); } return (Folder) master.getParent(); }
@Test public void vSphereLocationSupplierTest() throws IOException { ServerConnection serverConnection = PowerMock.createMock(ServerConnection.class); WSClient wsClient = PowerMock.createMock(WSClient.class); ManagedObjectReference managedObjectReference = PowerMock.createMock(ManagedObjectReference.class); ServiceInstance serviceInstance = PowerMock.createMock(ServiceInstance.class); CreateAndConnectVSphereClient supplier = PowerMock.createMock(CreateAndConnectVSphereClient.class); VSphereServiceInstance vSphereServiceInstance = PowerMock.createMock(VSphereServiceInstance.class); Folder rootFolder = PowerMock.createMock(Folder.class); expect(supplier.get()).andReturn(vSphereServiceInstance); expect(vSphereServiceInstance.getInstance()).andReturn(serviceInstance); expect(serviceInstance.getRootFolder()).andReturn(rootFolder); expect(rootFolder.getServerConnection()).andReturn(serverConnection).anyTimes(); expect(rootFolder.getMOR()).andReturn(managedObjectReference); expect(serverConnection.getServiceInstance()).andReturn(serviceInstance).anyTimes(); expect(serverConnection.getVimService()).andReturn(new VimPortType(wsClient)).anyTimes(); AboutInfo aboutInfo = new AboutInfo(); aboutInfo.setApiVersion("5.1"); expect(serviceInstance.getPropertyCollector()).andReturn(new PropertyCollector(serverConnection, managedObjectReference)); expect(serviceInstance.getAboutInfo()).andReturn(aboutInfo); vSphereServiceInstance.close(); replay(supplier, vSphereServiceInstance, serviceInstance, rootFolder, serverConnection); VSphereLocationSupplier vSphereLocationSupplier = new VSphereLocationSupplier(supplier); Set<? extends Location> location = vSphereLocationSupplier.get(); Assert.assertEquals(1, location.size()); for (Location l : location) { Assert.assertEquals("default", l.getId()); } verify(supplier, vSphereServiceInstance, serviceInstance, rootFolder, serverConnection); }
private <T extends ManagedEntity> T createEntity(Class<T> type, @Nullable ManagedEntity parent, String val, String name){ final ManagedObjectReference mor = new ManagedObjectReference(); mor.setType(type.getSimpleName()); mor.setVal(val); if (type==Folder.class){ return (T)new Folder(null, mor){ @Override public ManagedEntity getParent() { return parent; } @Override public String getName() { return name; } }; } if (type==ResourcePool.class){ return (T)new ResourcePool(null, mor){ @Override public ManagedEntity getParent() { return parent; } @Override public String getName() { return name; } }; } throw new IllegalArgumentException("can't create instance of type " + type.getSimpleName()); }
public <T extends ManagedEntity> void setParent(final String parentName, Class<T> parentType) { if (parentType.isAssignableFrom(FakeDatacenter.class)){ setParent(FakeModel.instance().getDatacenter(parentName)); } else if (parentType.isAssignableFrom(Folder.class)){ setParent(FakeModel.instance().getFolder(parentName)); } if (myParent == null) { Assert.fail(String.format("Unable to set parent %s of type %s", parentName, parentType.getSimpleName())); } }
protected String selectDatastore(VmwareProcessClient vmwareProcessClient, VmwareInstance vmwareInstance) { // データストアフォルダ内のデータストアのうち、アクセス可能で空き容量が最も大きいものを用いる Datastore datastore = null; long freeSpace = 0L; // ComputeResourceごとのフォルダがあれば、その中のデータストアを用いる String datastoreFolderName = vmwareInstance.getComputeResource() + "-storage"; Folder datastoreFolder = vmwareProcessClient.getVmwareClient().search(Folder.class, datastoreFolderName); if (datastoreFolder == null) { // ComputeResourceごとのフォルダがなければ、"storage"フォルダの中のデータストアを用いる datastoreFolder = vmwareProcessClient.getVmwareClient().search(Folder.class, "storage"); } if (datastoreFolder != null) { ManagedEntity[] entities = vmwareProcessClient.getVmwareClient().searchByType(datastoreFolder, Datastore.class); for (ManagedEntity entity : entities) { Datastore datastore2 = Datastore.class.cast(entity); DatastoreSummary summary2 = datastore2.getSummary(); if (summary2.isAccessible() && freeSpace < summary2.getFreeSpace()) { datastore = datastore2; freeSpace = summary2.getFreeSpace(); } } } if (datastore == null) { // 利用可能なデータストアがない場合 throw new AutoException("EPROCESS-000528", vmwareInstance.getComputeResource()); } return datastore.getName(); }
private void findHostsInFolder(Folder hostsFolder, List<HostSystem> hostsList) throws IOException, Exception { for (ManagedEntity e : hostsFolder.getChildEntity()) { if (e instanceof HostSystem) { hostsList.add((HostSystem)e); } // This is a cluster resource. Delve deeper to // find more hosts. if (e instanceof ComputeResource) { ComputeResource cr = (ComputeResource) e; if (e instanceof ClusterComputeResource) { ClusterComputeResource cluster = (ClusterComputeResource) e; if ((contrailClusterName != null) && (cluster.getName().equals(contrailClusterName) != true)) { continue; } } for(HostSystem host : cr.getHosts()) { hostsList.add((HostSystem)host); } } if (e instanceof Folder) { findHostsInFolder((Folder)e, hostsList); } } }
SortedMap<String, VirtualMachineInfo> readVirtualMachines() throws IOException, Exception { s_logger.info("Start reading virtual machines from vcenter ..."); SortedMap<String, VirtualMachineInfo> map = new ConcurrentSkipListMap<String, VirtualMachineInfo>(); /* the method below can be called in a loop to read multiple * datacenters and read VMs per hosts * for (dc: datacenters) * for (host: dc) readVirtualMachines(map, host, dc, dcName); */ Folder hostsFolder = contrailDC.getHostFolder(); if (hostsFolder == null) { s_logger.error("Unable to read VMs, hostFolder is null"); return map; } List<HostSystem> hostsList = new ArrayList<HostSystem>(); findHostsInFolder(hostsFolder, hostsList); for (HostSystem host : hostsList) { readVirtualMachines(map, host, contrailDC, contrailDataCenterName); } s_logger.info("Done reading from vcenter, found " + map.size() + " Virtual Machines"); return map; }
public static void main(String[] args) throws Exception { ServiceInstance si = new ServiceInstance(new URL("http://10.20.143.205/sdk"), "root", "password", true); Folder rootFolder = si.getRootFolder(); ManagedEntity[] vms = new InventoryNavigator(rootFolder).searchManagedEntities("VirtualMachine"); ManagedEntity[] hosts = new InventoryNavigator(rootFolder).searchManagedEntities("HostSystem"); CacheInstance vicf = new CacheInstance(si); vicf.watch(vms, new String[] {"name", "runtime.powerState", "summary"}); vicf.watch(hosts, new String[] {"name", "summary"}); vicf.start(); //check if the caching is ready to use; otherwise wait while(!vicf.isReady()) { Thread.sleep(1000); } Thread[] vrs = new VimReader[2]; for(int i=0; i<vrs.length; i++) { vrs[i] = new VimReader("Thread " + i, vicf, vms, hosts); vrs[i].start(); } for(int i=0; i<vrs.length; i++) { vrs[i].join(); } si.getServerConnection().logout(); }
public static void main(String[] args) throws Exception { if(args.length!=3) { System.out.println("Usage: java CimTicket <url> " + "<username> <password>"); return; } String urlStr = args[0]; String username = args[1]; String password = args[2]; ServiceInstance si = new ServiceInstance(new URL(urlStr), username, password, true); Folder rootFolder = si.getRootFolder(); HostSystem host = (HostSystem) new InventoryNavigator( rootFolder).searchManagedEntities("HostSystem")[0]; System.out.println(host.getName()); HostServiceTicket ticket = host.acquireCimServicesTicket(); System.out.println("\nHost Name:" + ticket.getHost()); System.out.println("sessionId=" + ticket.getSessionId()); System.out.println("sslThumpprint=" + ticket.getSslThumbprint()); System.out.println("serviceVersion=" + ticket.getServiceVersion()); System.out.println("service=" + ticket.getService()); System.out.println("port=" + ticket.getPort()); retrieveCimInfo(urlStr, ticket.getSessionId()); si.getServerConnection().logout(); }
public void run() { int vmToUse = -1; int attempts = 0; try { synchronized (vmList) { while (attempts < vmList.size()) { lastVMIndex = (lastVMIndex == (vmList.size() - 1)) ? 0 : ++lastVMIndex; vmToUse = lastVMIndex; if (!vmsInVMotion[vmToUse]) { vmsInVMotion[vmToUse] = Boolean.TRUE; lastHostIndex[vmToUse] = (lastHostIndex[vmToUse] == (vmList .get(vmToUse).size() - 1)) ? 1 : ++lastHostIndex[vmToUse]; break; } ++attempts; } } if (attempts == vmList.size()) { vmToUse = -1; // avoid logic in finally block return; // No vm available for vMotion. } String targetVMName = vmList.get(vmToUse).get(0); String newHostName = vmList.get(vmToUse).get(lastHostIndex[vmToUse]); Folder rootFolder = si.getRootFolder(); InventoryNavigator in = new InventoryNavigator(rootFolder); HostSystem newHost = (HostSystem)in.searchManagedEntity("HostSystem", newHostName); if (newHost == null) { log(WARNING, "Could not resolve host " + newHostName + ", vMotion to this host cannot be performed."); return; } //dummyVMotion(si, rootFolder, newHost, targetVMName, newHostName); migrateVM(si, rootFolder, newHost, targetVMName, newHostName); } catch (Exception e) { log(WARNING, "Found ", e); } finally { if (vmToUse != -1) { synchronized (vmList) { vmsInVMotion[vmToUse] = Boolean.FALSE; } } } }
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; } }
@Override public NodeAndInitialCredentials<VirtualMachine> createNodeWithGroupEncodedIntoName(String tag, String name, Template template) { VSphereTemplateOptions vOptions = VSphereTemplateOptions.class.cast(template.getOptions()); String datacenterName = vOptions.datacenterName(); try (VSphereServiceInstance instance = this.serviceInstance.get(); VSphereHost sphereHost = hostFunction.apply(datacenterName); /*VSphereHost sphereHost = vSphereHost.get();*/) { Folder rootFolder = instance.getInstance().getRootFolder(); ComputerNameValidator.INSTANCE.validate(name); VirtualMachine master = getVMwareTemplate(template.getImage().getId(), rootFolder); ResourcePool resourcePool = checkNotNull(tryFindResourcePool(rootFolder, sphereHost.getHost().getName()).orNull(), "resourcePool"); logger.trace("<< trying to use ResourcePool: " + resourcePool.getName()); // VSphereTemplateOptions vOptions = VSphereTemplateOptions.class.cast(template.getOptions()); VirtualMachineCloneSpec cloneSpec = new MasterToVirtualMachineCloneSpec(resourcePool, sphereHost.getDatastore(), VSphereApiMetadata.defaultProperties().getProperty(CLONING), name, vOptions.postConfiguration()).apply(master); Set<String> networks = vOptions.getNetworks(); VirtualMachineConfigSpec virtualMachineConfigSpec = new VirtualMachineConfigSpec(); virtualMachineConfigSpec.setMemoryMB((long) template.getHardware().getRam()); if (template.getHardware().getProcessors().size() > 0) virtualMachineConfigSpec.setNumCPUs((int) template.getHardware().getProcessors().get(0).getCores()); else virtualMachineConfigSpec.setNumCPUs(1); Set<NetworkConfig> networkConfigs = Sets.newHashSet(); for (String network : networks) { NetworkConfig config = networkConfigurationForNetworkAndOptions.apply(network, vOptions); networkConfigs.add(config); } List<VirtualDeviceConfigSpec> updates = configureVmHardware(name, template, master, vOptions, networkConfigs); virtualMachineConfigSpec.setDeviceChange(updates.toArray(new VirtualDeviceConfigSpec[updates.size()])); cloneSpec.setConfig(virtualMachineConfigSpec); vOptions.getPublicKey(); VirtualMachine cloned = null; try { cloned = cloneMaster(master, tag, name, cloneSpec, vOptions.vmFolder()); Set<String> tagsFromOption = vOptions.getTags(); if (tagsFromOption.size() > 0) { String tags = Joiner.on(",").join(vOptions.getTags()); cloned.getServerConnection().getServiceInstance().getCustomFieldsManager().setField(cloned, customFields.get().get(VSphereConstants.JCLOUDS_TAGS).getKey(), tags); cloned.getServerConnection().getServiceInstance().getCustomFieldsManager().setField(cloned, customFields.get().get(VSphereConstants.JCLOUDS_GROUP).getKey(), tag); if (vOptions.postConfiguration()) postConfiguration(cloned, name, tag, networkConfigs); else { VSpherePredicate.WAIT_FOR_VMTOOLS(1000 * 60 * 60 * 2, TimeUnit.MILLISECONDS).apply(cloned); } } } catch (Exception e) { logger.error("Can't clone vm " + master.getName() + ", Error message: " + e.toString(), e); propagate(e); } checkAndRecoverNicConfiguration(serviceInstance.get(), cloned); NodeAndInitialCredentials<VirtualMachine> nodeAndInitialCredentials = new NodeAndInitialCredentials<VirtualMachine>(cloned, cloned.getName(), LoginCredentials.builder().user("root") .password(vmInitPassword) .build()); return nodeAndInitialCredentials; } catch (Throwable t) { logger.error("Got ERROR while create new VM : " + t.toString()); Throwables.propagateIfPossible(t); } return null; }
GetVirtualMachineCallable(String vmName, Folder folder, Folder rootFolder) { this.vmName = vmName; this.folder = folder; this.rootFolder = rootFolder; }
@Used("Tests") public FolderBean(final Folder folder){ this(folder.getMOR(), folder.getName(), null, folder.getChildType(), folder.getParent().getMOR(), "dc"); }
public static void main(String [] args) throws Exception { if(args.length != 4) { System.out.println("Usage: java CreateScheduledTasks " + "<url> <username> <password> <vmname>"); return; } ServiceInstance si = new ServiceInstance( new URL(args[0]), args[1], args[2], true); Folder rootFolder = si.getRootFolder(); InventoryNavigator inv = new InventoryNavigator(rootFolder); String vmname = args[3]; VirtualMachine vm = (VirtualMachine)inv.searchManagedEntity( "VirtualMachine", vmname); if(vm==null) { System.out.println("Cannot find the VM " + vmname + "\nExisting..."); si.getServerConnection().logout(); return; } ScheduledTaskManager stm = si.getScheduledTaskManager(); if(stm!=null) { //to save space, we just check one name here if(taskNameExists(stm, "ViMaster_OneTime")) { si.getServerConnection().logout(); return; } // Note: the time should be fetched from server, // just to make sure it's synchronized. ScheduledTaskSpec oneSpec = createOneTimeSchedulerSpec( "ViMaster_OneTime", si.currentTime()); ScheduledTaskSpec weekSpec = createWeeklySchedulerSpec( "ViMaster_Weekly"); ScheduledTask st = stm.createScheduledTask(vm, oneSpec); ScheduledTask st1 = stm.createScheduledTask(vm, weekSpec); // sleep two minutes before deleting // the one time scheduled task. // An one time scheduled task has not to be deleted after // it's run. It can be run any time again by calling the // runScheduledTask() method. Thread.sleep(2*60*1000); st.removeScheduledTask(); } else { System.out.println("SchduledTaskManager is not " + "available on this target."); } si.getServerConnection().logout(); }
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(); }