Move VM in yavijava/vijava
This is an example how to move a Virtual Machine in yavijava:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 |
package be.visualstation.vmware.test; import com.vmware.vim25.PlatformConfigFault; import com.vmware.vim25.VirtualMachineRelocateSpec; import com.vmware.vim25.mo.*; import java.net.MalformedURLException; import java.net.URL; import java.rmi.RemoteException; import java.util.Arrays; import java.util.logging.Level; import java.util.logging.Logger; public class MoveVM { private ServiceInstance serviceInstance; private static Logger logger = Logger.getLogger("Example"); public LoginConfiguration loginConfiguration; public static void main(String[] args) throws VMWareException { MoveVM mvm = new MoveVM(); mvm.loginConfiguration = new LoginConfiguration("Username","Password","https://vCenter/sdk"); mvm.moveVmToHostSystem("vmName","destinationHost (memeber of the cluster/or host)"); } private ServiceInstance getServerInstance() throws MalformedURLException, RemoteException { if (serviceInstance == null) { logger.info("Server instance is NULL ... creating a new connection"); URL url = new URL(loginConfiguration.getVmwareUrl()); serviceInstance = new ServiceInstance(url, loginConfiguration.getUserName(), loginConfiguration.getPassword(), true); } return serviceInstance; } public Boolean moveVmToHostSystem(final String vmName, final String hostName) throws VMWareException { ServiceInstance si = null; boolean retVal; try { si = this.getServerInstance(); Folder rootFolder = si.getRootFolder(); VirtualMachine vm = (VirtualMachine) new InventoryNavigator(rootFolder).searchManagedEntity("VirtualMachine", vmName); HostSystem hostSystem = null; ManagedEntity[] hostSystems = new InventoryNavigator(si.getRootFolder()).searchManagedEntities("HostSystem"); for (ManagedEntity hostSystem1 : hostSystems) { HostSystem host = (HostSystem) hostSystem1; if (host.getName().equalsIgnoreCase(hostName)) { logger.log(Level.FINE, "Found HostSystem: " + hostName); hostSystem = host; } else { logger.log(Level.FINE, "HostSystem: " + hostName + " not found! Using default HostSystem."); } } VirtualMachineRelocateSpec relSpec = new VirtualMachineRelocateSpec(); relSpec.setHost(hostSystem.getMOR()); Datastore ds = hostSystem.getDatastores()[0];//.getInfo().freeSpace; Datastore[] datastores = hostSystem.getDatastores(); Datastore dataStore = Arrays.stream(datastores).filter(myds -> myds.getName().equals("")).findFirst().orElse(null); if(dataStore != null){ } else { // Datastore not found } ComputeResource cr = (ComputeResource) hostSystem.getParent(); ResourcePool resourcePool = cr.getResourcePool(); relSpec.setDatastore(ds.getMOR()); System.out.printf(resourcePool.getName()); ResourcePool[] resourcePools = resourcePool.getResourcePools(); Arrays.stream(resourcePools).forEach(rp -> System.out.println(rp.getName())); resourcePool = Arrays.stream(resourcePools).filter(rp -> rp.getName().equals("NamedResourcePool")).findFirst().orElse(resourcePool); relSpec.setPool(resourcePool.getMOR()); Task task = vm.relocateVM_Task(relSpec); String result = task.waitForTask(); retVal = result.equals(Task.SUCCESS); return retVal; } catch (PlatformConfigFault f) { throw new VMWareException(f); } catch (RemoteException exc) { throw new VMWareException(exc); } catch (Exception exc) { throw new VMWareException(exc); } } public String getHostSystemForVM(final String vmName) throws VMWareException { ServiceInstance si = null; try { si = this.getServerInstance(); boolean found = false; HostSystem hostSystem = null; ManagedEntity[] hostsystems = new InventoryNavigator(si.getRootFolder()).searchManagedEntities("HostSystem"); for (ManagedEntity hostsystem : hostsystems) { HostSystem host = (HostSystem) hostsystem; VirtualMachine[] vms = host.getVms(); for (VirtualMachine vm : vms) { if (vm.getName().equals(vmName)) { hostSystem = host; found = true; break; } } if (found) break; } return hostSystem.getName(); } catch (PlatformConfigFault f) { throw new VMWareException(f); } catch (RemoteException exc) { throw new VMWareException(exc); } catch (Exception exc) { throw new VMWareException(exc); } } } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 |
package be.visualstation.vmware.test; public class LoginConfiguration { private String username; private String password; private String vmwareUrl; public LoginConfiguration(final String username, final String password, final String vmwareUrl) { this.username = username; this.password = password; this.vmwareUrl = vmwareUrl; } public String getUserName() { return username; } public String getPassword() { return password; } public String getOriginalPassword() { return password; } public String getVmwareUrl() { return vmwareUrl; } } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 |
package be.visualstation.vmware.test; public class VMWareException extends Exception { /** * */ private static final long serialVersionUID = 8779050125374959365L; /** * * @param exc */ public VMWareException(Exception exc) { super(exc); } public VMWareException(String cause) { super(cause); } /** * * @param cause * @param exc */ public VMWareException(String cause, VMWareException exc) { super(cause, exc); } public VMWareException(String cause, Exception exc) { super(cause, exc); } } |
Upload file via VMware VM Agent – Java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 |
package be.visualstation.vmagent.cli; import org.apache.http.HttpResponse; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpPut; import org.apache.http.config.Registry; import org.apache.http.config.RegistryBuilder; import org.apache.http.conn.socket.ConnectionSocketFactory; import org.apache.http.conn.socket.PlainConnectionSocketFactory; import org.apache.http.conn.ssl.SSLConnectionSocketFactory; import org.apache.http.entity.ContentType; import org.apache.http.entity.InputStreamEntity; import org.apache.http.impl.client.HttpClientBuilder; import org.apache.http.impl.conn.PoolingHttpClientConnectionManager; import org.apache.http.ssl.SSLContextBuilder; import org.apache.http.ssl.TrustStrategy; import org.slf4j.Logger; import javax.net.ssl.HostnameVerifier; import javax.net.ssl.SSLContext; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.net.URI; import java.security.KeyManagementException; import java.security.KeyStoreException; import java.security.NoSuchAlgorithmException; import java.security.cert.CertificateException; import java.security.cert.X509Certificate; import java.time.Instant; public class FileUpload implements Runnable { final static Logger logger = org.slf4j.LoggerFactory.getLogger(FileUpload.class); File source = null; String destination = null; URI uri = null; public FileUpload(File source, URI uri){ this.source = source; this.destination = destination; this.uri = uri; } public static HttpClient createHttpClient_AcceptsUntrustedCerts() throws KeyStoreException, NoSuchAlgorithmException, KeyManagementException { HttpClientBuilder b = HttpClientBuilder.create(); SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() { public boolean isTrusted(X509Certificate[] arg0, String arg1) throws CertificateException { return true; } }).build(); b.setSslcontext( sslContext); HostnameVerifier hostnameVerifier = SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER; SSLConnectionSocketFactory sslSocketFactory = new SSLConnectionSocketFactory(sslContext, hostnameVerifier); Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create() .register("http", PlainConnectionSocketFactory.getSocketFactory()) .register("https", sslSocketFactory) .build(); PoolingHttpClientConnectionManager connMgr = new PoolingHttpClientConnectionManager( socketFactoryRegistry); b.setConnectionManager( connMgr); HttpClient client = b.build(); return client; } @Override public void run() { HttpClient httpClient = null; try { Instant i1 = Instant.now(); logger.info("File transfer started @ " + i1.toString() + " for " + this.source.getName() + " (Size: " + Long.toString(this.source.length()) + " bytes)."); httpClient = createHttpClient_AcceptsUntrustedCerts(); HttpPut httpPut = new HttpPut(this.uri); InputStreamEntity reqEntity = new InputStreamEntity(new FileInputStream(this.source), this.source.length(), ContentType.DEFAULT_BINARY); // VMware ESX Server does not support chunked data. reqEntity.setChunked(false); httpPut.setEntity(reqEntity); HttpResponse httpResponse = httpClient.execute(httpPut); logger.info(httpResponse.getEntity().toString()); Instant i2 = Instant.now(); long ns = java.time.Duration.between(i1,i2).toNanos(); logger.info(String.format("File Transfer Duration: %s ns.",Long.toString(ns))); double seconds = ns / 1000000000; double rate = this.source.length() / seconds; logger.info("Average Transfer Rate: " + Double.toString(rate) + "B/s."); } catch (KeyStoreException e) { logger.error(e.toString()); } catch (NoSuchAlgorithmException e) { logger.error(e.toString()); } catch (KeyManagementException e) { logger.error(e.toString()); } catch (ClientProtocolException e) { logger.error(e.toString()); } catch (IOException e) { logger.error(e.toString()); } } } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 |
package be.visualstation.vmagent.cli; import be.visualstation.vmagent.config.ConfigUtil; import com.vmware.vim25.GuestFileAttributes; import com.vmware.vim25.NamePasswordAuthentication; import com.vmware.vim25.mo.*; import org.slf4j.Logger; import javax.net.ssl.HttpsURLConnection; import javax.net.ssl.SSLContext; import javax.net.ssl.TrustManager; import javax.net.ssl.X509TrustManager; import java.net.MalformedURLException; import java.net.URI; import java.net.URISyntaxException; import java.nio.file.Path; import java.nio.file.Paths; import java.rmi.RemoteException; import java.security.cert.X509Certificate; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; public class FileUploadMT { final static Logger logger = org.slf4j.LoggerFactory.getLogger(FileUploadMT.class); public static void main(String[] args) { TrustManager[] trustAllCerts = new TrustManager[]{ new X509TrustManager() { public X509Certificate[] getAcceptedIssuers() { return null; } public void checkClientTrusted( X509Certificate[] certs, String authType) { } public void checkServerTrusted( X509Certificate[] certs, String authType) { } } }; try { SSLContext sc = SSLContext.getInstance("SSL"); sc.init(null, trustAllCerts, new java.security.SecureRandom()); HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory()); } catch (Exception e) { } try { ServiceInstance si = ConfigUtil.createServiceInstance(); if(si != null){ String vmName = "vm-1"; Folder rootFolder = si.getRootFolder(); GuestOperationsManager gom = si.getGuestOperationsManager(); VirtualMachine vm = (VirtualMachine) new InventoryNavigator(rootFolder).searchManagedEntity("VirtualMachine", vmName); Path path = Paths.get("C:\\Test.file"); FileUpload fu1, fu2; ExecutorService executor = Executors.newFixedThreadPool(5); if(vm != null){ GuestFileManager gfm = gom.getFileManager(vm); NamePasswordAuthentication creds = new NamePasswordAuthentication(); creds.setUsername("root"); creds.setPassword("password"); String s = gfm.initiateFileTransferToGuest(creds, "/root/" + path.getFileName().toString(), new GuestFileAttributes(),path.toFile().length(), true); fu1 = new FileUpload(path.toFile(), new URI(s)); executor.submit(fu1); } String vmName2 = "vm2"; VirtualMachine vm2 = (VirtualMachine) new InventoryNavigator(rootFolder).searchManagedEntity("VirtualMachine", vmName2); if(vm2 != null){ GuestFileManager gfm = gom.getFileManager(vm2); NamePasswordAuthentication creds = new NamePasswordAuthentication(); creds.setUsername("Administrator"); creds.setPassword("password"); String s = gfm.initiateFileTransferToGuest(creds, "C:\\" + path.getFileName().toString(), new GuestFileAttributes(),path.toFile().length(), true); fu2 = new FileUpload(path.toFile(), new URI(s)); executor.submit(fu2); } } } catch (RemoteException e) { e.printStackTrace(); } catch (MalformedURLException e) { e.printStackTrace(); } catch (URISyntaxException e) { e.printStackTrace(); } } } |