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(); }
@Override public boolean apply(ResourcePool input) { try { for (HostSystem hostSystem : input.getOwner().getHosts()) { if (hostSystem.getName().equals(hostname)) return true; } } catch (RemoteException e) { return false; } return false; }
@Inject public MasterToVirtualMachineCloneSpec(ResourcePool resourcePool, Datastore datastore, String cloningStrategy, String linuxName, boolean postConfiguration) { this.resourcePool = resourcePool; this.datastore = datastore; this.cloningStrategy = cloningStrategy; this.linuxName = linuxName; this.postConfiguration = postConfiguration; }
private VirtualMachineRelocateSpec configureRelocateSpec(ResourcePool resourcePool, Datastore datastore, VirtualMachine master) throws Exception, InvalidProperty, RuntimeFault, RemoteException { VirtualMachineRelocateSpec rSpec = new VirtualMachineRelocateSpec(); if (cloningStrategy.equals("linked")) { ArrayList<Integer> diskKeys = getIndependentVirtualDiskKeys(master); if (diskKeys.size() > 0) { Datastore[] dss = master.getDatastores(); VirtualMachineRelocateSpecDiskLocator[] diskLocator = new VirtualMachineRelocateSpecDiskLocator[diskKeys.size()]; int count = 0; for (Integer key : diskKeys) { diskLocator[count] = new VirtualMachineRelocateSpecDiskLocator(); diskLocator[count].setDatastore(dss[0].getMOR()); diskLocator[count] .setDiskMoveType(VirtualMachineRelocateDiskMoveOptions.moveAllDiskBackingsAndDisallowSharing .toString()); diskLocator[count].setDiskId(key); count = count + 1; } rSpec.setDiskMoveType(VirtualMachineRelocateDiskMoveOptions.createNewChildDiskBacking.toString()); rSpec.setDisk(diskLocator); } else { rSpec.setDiskMoveType(VirtualMachineRelocateDiskMoveOptions.createNewChildDiskBacking.toString()); } } else if (cloningStrategy.equals("full")) { rSpec.setDatastore(datastore.getMOR()); rSpec.setPool(resourcePool.getMOR()); //rSpec.setHost(); } else throw new Exception(String.format("Cloning strategy %s not supported", cloningStrategy)); return rSpec; }
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()); }
protected VirtualMachineCloneSpec createCloneSpec(String computeResourceName, String resourcePoolName, String datastoreName) { VirtualMachineRelocateSpec relocateSpec = new VirtualMachineRelocateSpec(); // ComputeResource ComputeResource computeResource = vmwareClient.search(ComputeResource.class, computeResourceName); if (computeResource == null) { // ComputeResourceが見つからない場合 throw new AutoException("EPROCESS-000503", computeResourceName); } // ResourcePool if (StringUtils.isEmpty(resourcePoolName)) { resourcePoolName = "Resources"; } ResourcePool resourcePool = vmwareClient.search(computeResource, ResourcePool.class, resourcePoolName); if (resourcePool == null) { // ResourcePoolが見つからない場合 throw new AutoException("EPROCESS-000504", resourcePoolName); } relocateSpec.setPool(resourcePool.getMOR()); // Datastore if (StringUtils.isNotEmpty(datastoreName)) { // データストアが指定されている場合 Datastore datastore = vmwareClient.search(Datastore.class, datastoreName); if (datastore == null) { // データストアが見つからない場合 throw new AutoException("EPROCESS-000505", datastoreName); } relocateSpec.setDatastore(datastore.getMOR()); } VirtualMachineCloneSpec cloneSpec = new VirtualMachineCloneSpec(); cloneSpec.setLocation(relocateSpec); cloneSpec.setPowerOn(false); cloneSpec.setTemplate(false); return cloneSpec; }
@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; }
public static Predicate<ResourcePool> isResourcePoolOf(String hostname) { return new IsResourcePoolOf(hostname); }
@Used("Tests") public ResourcePoolBean(final ResourcePool rp){ this(rp.getMOR(), rp.getName(), null, rp.getParent().getMOR(), "dc"); }
public Map<String, ResourcePool> getResourcePools() { return myResourcePools; }
public ResourcePool getResourcePool(String name){ return myResourcePools.get(name); }
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. "); } }