11package com .cloud .vmware ;
22
3+ import java .io .BufferedInputStream ;
4+ import java .io .BufferedOutputStream ;
5+ import java .io .BufferedReader ;
36import java .io .File ;
7+ import java .io .FileInputStream ;
8+ import java .io .IOException ;
9+ import java .io .InputStreamReader ;
10+ import java .net .URL ;
411import java .rmi .RemoteException ;
512import java .util .ArrayList ;
613import java .util .HashMap ;
714import java .util .List ;
815import java .util .Map ;
916
17+ import javax .net .ssl .HostnameVerifier ;
18+ import javax .net .ssl .HttpsURLConnection ;
19+ import javax .net .ssl .SSLSession ;
20+
1021import org .apache .log4j .xml .DOMConfigurator ;
1122
1223import com .cloud .utils .PropertiesUtil ;
1526import com .vmware .vim25 .HostVirtualNicSpec ;
1627import com .vmware .vim25 .HostConfigManager ;
1728import com .vmware .vim25 .HostPortGroupSpec ;
29+ import com .vmware .vim25 .HttpNfcLeaseDeviceUrl ;
30+ import com .vmware .vim25 .HttpNfcLeaseInfo ;
31+ import com .vmware .vim25 .HttpNfcLeaseState ;
32+ import com .vmware .vim25 .OvfCreateImportSpecParams ;
33+ import com .vmware .vim25 .OvfCreateImportSpecResult ;
34+ import com .vmware .vim25 .OvfFileItem ;
35+ import com .vmware .vim25 .OvfNetworkMapping ;
1836import com .vmware .vim25 .VirtualMachineConfigSpec ;
1937import com .vmware .vim25 .VirtualDeviceConfigSpecOperation ;
2038import com .vmware .vim25 .VirtualEthernetCard ;
4058public class TestVMWare {
4159 private static ExtendedAppUtil cb ;
4260
61+ static {
62+ try {
63+ javax .net .ssl .TrustManager [] trustAllCerts = new javax .net .ssl .TrustManager [1 ];
64+ javax .net .ssl .TrustManager tm = new TrustAllManager ();
65+ trustAllCerts [0 ] = tm ;
66+ javax .net .ssl .SSLContext sc = javax .net .ssl .SSLContext .getInstance ("SSL" );
67+ sc .init (null , trustAllCerts , null );
68+ javax .net .ssl .HttpsURLConnection .setDefaultSSLSocketFactory (sc .getSocketFactory ());
69+ } catch (Exception e ) {
70+ }
71+ }
72+
4373 private static void setupLog4j () {
4474 File file = PropertiesUtil .findConfigFile ("log4j-cloud.xml" );
4575
@@ -860,6 +890,174 @@ private void testFTEnable() throws Exception {
860890 System .out .println ("Enable FT resutl : " + result );
861891 }
862892
893+ private void importOVF () throws Exception {
894+ ManagedObjectReference morHost = new ManagedObjectReference ();
895+ morHost .setType ("HostSystem" );
896+ morHost .set_value ("host-223" );
897+
898+ ManagedObjectReference morRp = new ManagedObjectReference ();
899+ morRp .setType ("ResourcePool" );
900+ morRp .set_value ("resgroup-222" );
901+
902+ ManagedObjectReference morDs = new ManagedObjectReference ();
903+ morDs .setType ("Datastore" );
904+ morDs .set_value ("datastore-30" );
905+
906+ ManagedObjectReference morVmFolder = new ManagedObjectReference ();
907+ morVmFolder .setType ("Folder" );
908+ morVmFolder .set_value ("group-v3" );
909+
910+ ManagedObjectReference morNetwork = new ManagedObjectReference ();
911+ morNetwork .setType ("Network" );
912+ morNetwork .set_value ("network-32" );
913+
914+ ManagedObjectReference morOvf = cb .getServiceConnection3 ().getServiceContent ().getOvfManager ();
915+
916+ OvfCreateImportSpecParams importSpecParams = new OvfCreateImportSpecParams ();
917+ importSpecParams .setHostSystem (morHost );
918+ importSpecParams .setLocale ("US" );
919+ importSpecParams .setEntityName ("winxpsp3-ovf-deployed" );
920+ importSpecParams .setDeploymentOption ("" );
921+ importSpecParams .setDiskProvisioning ("thin" );
922+
923+ /*
924+ OvfNetworkMapping networkMapping = new OvfNetworkMapping();
925+ networkMapping.setName("VM Network");
926+ networkMapping.setNetwork(morNetwork); // network);
927+ importSpecParams.setNetworkMapping(new OvfNetworkMapping[] { networkMapping });
928+ */
929+ importSpecParams .setPropertyMapping (null );
930+
931+ String ovfDescriptor = readOvfContent ("C:\\ research\\ vmware\\ winxpsp3-ovf\\ winxpsp3-ovf.ovf" );
932+ OvfCreateImportSpecResult ovfImportResult = cb .getServiceConnection3 ().getService ().createImportSpec (
933+ morOvf , ovfDescriptor , morRp , morDs , importSpecParams );
934+
935+ if (ovfImportResult != null ) {
936+ long totalBytes = addTotalBytes (ovfImportResult );
937+
938+ ManagedObjectReference morLease = cb .getServiceConnection3 ().getService ().importVApp (morRp ,
939+ ovfImportResult .getImportSpec (), morVmFolder , morHost );
940+
941+ HttpNfcLeaseState state ;
942+ for (;;) {
943+ state = (HttpNfcLeaseState )cb .getServiceUtil3 ().getDynamicProperty (morLease , "state" );
944+ if (state == HttpNfcLeaseState .ready || state == HttpNfcLeaseState .error )
945+ break ;
946+ }
947+
948+ if (state == HttpNfcLeaseState .ready ) {
949+ HttpNfcLeaseInfo httpNfcLeaseInfo = (HttpNfcLeaseInfo )cb .getServiceUtil3 ().getDynamicProperty (morLease , "info" );
950+ HttpNfcLeaseDeviceUrl [] deviceUrls = httpNfcLeaseInfo .getDeviceUrl ();
951+ long bytesAlreadyWritten = 0 ;
952+ for (HttpNfcLeaseDeviceUrl deviceUrl : deviceUrls ) {
953+
954+ String deviceKey = deviceUrl .getImportKey ();
955+ for (OvfFileItem ovfFileItem : ovfImportResult .getFileItem ()) {
956+ if (deviceKey .equals (ovfFileItem .getDeviceId ())) {
957+ System .out .println ("Import key==OvfFileItem device id: " + deviceKey );
958+ System .out .println ("device URL: " + deviceUrl .getUrl ());
959+
960+ String absoluteFile = "C:\\ research\\ vmware\\ winxpsp3-ovf\\ " + ovfFileItem .getPath ();
961+ String urlToPost = deviceUrl .getUrl ().replace ("*" , "esxhost-1.lab.vmops.com" );
962+
963+ uploadVmdkFile (ovfFileItem .isCreate (), absoluteFile , urlToPost , bytesAlreadyWritten , totalBytes );
964+ bytesAlreadyWritten += ovfFileItem .getSize ();
965+ System .out .println ("Completed uploading the VMDK file:" + absoluteFile );
966+ }
967+ }
968+ }
969+ cb .getServiceConnection3 ().getService ().httpNfcLeaseProgress (morLease , 100 );
970+ cb .getServiceConnection3 ().getService ().httpNfcLeaseComplete (morLease );
971+ }
972+ }
973+ }
974+
975+ private static void uploadVmdkFile (boolean put , String diskFilePath , String urlStr , long bytesAlreadyWritten , long totalBytes ) throws IOException {
976+ HttpsURLConnection .setDefaultHostnameVerifier (new HostnameVerifier () {
977+ public boolean verify (String urlHostName , SSLSession session ) {
978+ return true ;
979+ }
980+ });
981+
982+ HttpsURLConnection conn = (HttpsURLConnection ) new URL (urlStr ).openConnection ();
983+
984+ conn .setDoOutput (true );
985+ conn .setUseCaches (false );
986+
987+ int CHUCK_LEN = 64 *1024 ;
988+ conn .setChunkedStreamingMode (CHUCK_LEN );
989+ conn .setRequestMethod (put ? "PUT" : "POST" ); // Use a post method to write the file.
990+ conn .setRequestProperty ("Connection" , "Keep-Alive" );
991+ conn .setRequestProperty ("Content-Type" , "application/x-vnd.vmware-streamVmdk" );
992+ conn .setRequestProperty ("Content-Length" , Long .toString (new File (diskFilePath ).length ()));
993+ BufferedOutputStream bos = new BufferedOutputStream (conn .getOutputStream ());
994+ BufferedInputStream diskis = new BufferedInputStream (new FileInputStream (diskFilePath ));
995+ int bytesAvailable = diskis .available ();
996+ int bufferSize = Math .min (bytesAvailable , CHUCK_LEN );
997+ byte [] buffer = new byte [bufferSize ];
998+ long totalBytesWritten = 0 ;
999+ while (true ) {
1000+ int bytesRead = diskis .read (buffer , 0 , bufferSize );
1001+ if (bytesRead == -1 )
1002+ {
1003+ System .out .println ("Total bytes written: " + totalBytesWritten );
1004+ break ;
1005+ }
1006+ totalBytesWritten += bytesRead ;
1007+ bos .write (buffer , 0 , bufferSize );
1008+ bos .flush ();
1009+ System .out .println ("Total bytes written: " + totalBytesWritten );
1010+
1011+ /*
1012+ int progressPercent = (int) (((bytesAlreadyWritten + totalBytesWritten) * 100) / totalBytes);
1013+ leaseUpdater.setPercent(progressPercent);
1014+ */
1015+ }
1016+ diskis .close ();
1017+ bos .flush ();
1018+ bos .close ();
1019+ conn .disconnect ();
1020+ }
1021+
1022+ public static long addTotalBytes (OvfCreateImportSpecResult ovfImportResult ) {
1023+ OvfFileItem [] fileItemArr = ovfImportResult .getFileItem ();
1024+ long totalBytes = 0 ;
1025+ if (fileItemArr != null ) {
1026+ for (OvfFileItem fi : fileItemArr ) {
1027+ printOvfFileItem (fi );
1028+ totalBytes += fi .getSize ();
1029+ }
1030+ }
1031+ return totalBytes ;
1032+ }
1033+
1034+ private static void printOvfFileItem (OvfFileItem fi ) {
1035+ System .out .println ("================ OvfFileItem ================" );
1036+ System .out .println ("chunkSize: " + fi .getChunkSize ());
1037+ System .out .println ("create: " + fi .isCreate ());
1038+ System .out .println ("deviceId: " + fi .getDeviceId ());
1039+ System .out .println ("path: " + fi .getPath ());
1040+ System .out .println ("size: " + fi .getSize ());
1041+ System .out .println ("==============================================" );
1042+ }
1043+
1044+ public static String readOvfContent (String ovfFilePath ) throws IOException {
1045+ StringBuffer strContent = new StringBuffer ();
1046+ BufferedReader in = new BufferedReader (new InputStreamReader (new FileInputStream (ovfFilePath )));
1047+ String lineStr ;
1048+ while ((lineStr = in .readLine ()) != null ) {
1049+ strContent .append (lineStr );
1050+ }
1051+
1052+ in .close ();
1053+ return strContent .toString ();
1054+ }
1055+
1056+ public static String escapeSpecialChars (String str ) {
1057+ str = str .replaceAll ("<" , "<" );
1058+ return str .replaceAll (">" , ">" ); // do not escape "&" -> "&", "\"" -> """
1059+ }
1060+
8631061 public static void main (String [] args ) throws Exception {
8641062 setupLog4j ();
8651063 TestVMWare client = new TestVMWare ();
@@ -878,7 +1076,7 @@ public static void main(String[] args) throws Exception {
8781076
8791077 // client.listInventoryFolders();
8801078 // client.listDataCenters();
881- client .powerOnVm ();
1079+ // client.powerOnVm();
8821080 // client.createSnapshot();
8831081 // client.registerTemplate();
8841082 // client.createVmFromTemplate();
@@ -890,10 +1088,37 @@ public static void main(String[] args) throws Exception {
8901088 // client.getHostVMs();
8911089 // client.testFT();
8921090 // client.testFTEnable();
1091+
1092+ client .importOVF ();
8931093
8941094 cb .disConnect ();
8951095 } catch (Exception e ) {
8961096 e .printStackTrace ();
8971097 }
8981098 }
1099+
1100+ public static class TrustAllManager implements javax .net .ssl .TrustManager , javax .net .ssl .X509TrustManager {
1101+
1102+ public java .security .cert .X509Certificate [] getAcceptedIssuers () {
1103+ return null ;
1104+ }
1105+
1106+ public boolean isServerTrusted (java .security .cert .X509Certificate [] certs ) {
1107+ return true ;
1108+ }
1109+
1110+ public boolean isClientTrusted (java .security .cert .X509Certificate [] certs ) {
1111+ return true ;
1112+ }
1113+
1114+ public void checkServerTrusted (java .security .cert .X509Certificate [] certs , String authType )
1115+ throws java .security .cert .CertificateException {
1116+ return ;
1117+ }
1118+ public void checkClientTrusted (java .security .cert .X509Certificate [] certs , String authType )
1119+ throws java .security .cert .CertificateException {
1120+ return ;
1121+ }
1122+ }
8991123}
1124+
0 commit comments