{"id":1077,"date":"2017-02-26T09:53:32","date_gmt":"2017-02-26T15:53:32","guid":{"rendered":"http:\/\/blog.ls-al.com\/?p=1077"},"modified":"2017-02-26T09:58:26","modified_gmt":"2017-02-26T15:58:26","slug":"oracle-vm-sdk-create-vm","status":"publish","type":"post","link":"https:\/\/blog.ls-al.com\/oracle-vm-sdk-create-vm\/","title":{"rendered":"Oracle VM SDK Create VM"},"content":{"rendered":"

I am playing with the java SOAP API to test creating a VM and since it took me a while to get it working I am jotting down my recipe for future refining. This is rough and needs a rewrite. Currently it is just a gutted version of the Sample that comes with the OVMM ISO.<\/p>\n

Note I ran this on the OVMM server at first and using localhost for connecting. That worked but to run this code from a different server I copied java from the OVMM server. Newer java just gave me too much SSL issues. <\/p>\n

Also I would prefer using REST\/JSON but that is not working yet. REST\/JSON gave me a NullPointerException which may provide me a clue as to why I could not get POST to work from my Python tests in a prior article. Which is actually the reason I am testing the Java code.<\/p>\n

You are WARNED this code is rough. For example it will create duplicate VM's with the same name. Also checkign the SERverPool is not safe it needs more logic. It will just grab the last one if you have more than one.<\/p>\n

You will need jersey for this code to work. Also as I mentioned this needs a lot of cleanup. I had some dependency issues so I copied a lot of classes from the SDK into my tree $APPROOT\/lib\/com\/oracle\/ovm\/mgr\/ws\/<\/p>\n

\r\nrrosso@BL:~\/src\/ovm_java_api$ ls lib\/\r\ncom  jersey-bundle-1.19.1.jar  OvmWsClient.jar\r\n<\/pre>\n

Little BASH script to show compile and run. <\/p>\n

 \r\nrrosso@BL:~\/src\/ovm_java_api$ cat buildrun.sh \r\n# Script to build and run OVM 3.3.3 specifc SDK API\r\n# Run with two parms example: .\/buildrun.sh vmname=vm1 server=ovs333\r\n# JAVA ENV\r\n#export JAVA_HOME=\/home\/rrosso\/jdk1.8.0_121\r\nexport JAVA_HOME=\/home\/rrosso\/java\r\nexport PATH=$JAVA_HOME\/bin:\/usr\/lib64\/qt-3.3\/bin:\/usr\/local\/bin:\/bin:\/usr\/bin:\/usr\/local\/sbin:\/usr\/sbin:\/sbin:\/home\/rrosso\/bin\r\n#java -version\r\n\r\nAPPROOT=\/home\/rrosso\/src\/ovm_java_api\r\nBUILDROOT=com\/oracle\/ovm\/mgr\/ws\/sample\/\r\nOVMLIB=$APPROOT\/lib\r\n\r\n# APP ROOT\r\ncd $APPROOT\r\n\r\n# BUILD\r\ncd $BUILDROOT\r\nrm WsDevClient*.class\r\njavac -cp $OVMLIB\/OvmWsClient.jar:. WsDevClient.java\r\n\r\n# RUN\r\ncd $APPROOT\r\n#java -Djavax.net.debug=ssl -cp .:$OVMLIB com.oracle.ovm.mgr.ws.sample.WsDevClient\r\n#echo "Trying to create $1 on $2"\r\njava -cp .:$OVMLIB com.oracle.ovm.mgr.ws.sample.WsDevClient $1 $2\r\n<\/pre>\n

Example run working:<\/p>\n

\r\nrrosso@BL:~\/src\/ovm_java_api$ .\/buildrun.sh vmname=vm4.3 server=ovs333\r\nStarting Ovm Api Test Using SOAP Implementation\r\n\r\nStarting VM create of: vm4.3\r\ncreate vm job id: Create Vm: vm4.3 on Server Pool: pool1(1487049718384) Uri: https:\/\/localhost:7002\/ovm\/core\/wsapi\/rest\/Job\/1487049718384\r\n<\/pre>\n

Client Source:<\/p>\n

\r\nrrosso@BL:~\/src\/ovm_java_api$ cat com\/oracle\/ovm\/mgr\/ws\/sample\/WsDevClient.java\r\npackage com.oracle.ovm.mgr.ws.sample;\r\nimport java.security.SecureRandom;\r\nimport java.security.cert.CertificateException;\r\nimport java.security.cert.X509Certificate;\r\nimport java.util.List;\r\nimport java.util.Locale;\r\nimport java.util.MissingResourceException;\r\nimport java.util.ResourceBundle;\r\nimport javax.net.ssl.HostnameVerifier;\r\nimport javax.net.ssl.HttpsURLConnection;\r\nimport javax.net.ssl.KeyManager;\r\nimport javax.net.ssl.SSLContext;\r\nimport javax.net.ssl.SSLSession;\r\nimport javax.net.ssl.TrustManager;\r\nimport javax.net.ssl.X509TrustManager;\r\nimport com.oracle.ovm.mgr.ws.client.OvmWsClient;\r\nimport com.oracle.ovm.mgr.ws.client.OvmWsClientFactory;\r\nimport com.oracle.ovm.mgr.ws.model.BaseObject;\r\nimport com.oracle.ovm.mgr.ws.model.Id;\r\nimport com.oracle.ovm.mgr.ws.model.Job;\r\nimport com.oracle.ovm.mgr.ws.model.Job.JobRunState;\r\nimport com.oracle.ovm.mgr.ws.model.JobError;\r\nimport com.oracle.ovm.mgr.ws.model.Repository;\r\nimport com.oracle.ovm.mgr.ws.model.Server;\r\nimport com.oracle.ovm.mgr.ws.model.ServerPool;\r\n\/\/import com.oracle.ovm.mgr.ws.model.StorageElement;\r\nimport com.oracle.ovm.mgr.ws.model.Vm;\r\nimport com.oracle.ovm.mgr.ws.model.Vm.VmDomainType;\r\nimport com.oracle.ovm.mgr.ws.model.VmDiskMapping;\r\nimport com.oracle.ovm.mgr.ws.model.WsException;\r\n\r\n\/**\r\n * A simple web services create vm client.\r\n * .\r\n * BEFORE RUNNING THIS you should first override the WsDevClient_<username>.properties file with your own values. See that\r\n * file for details.\r\n *\/\r\npublic class WsDevClient\r\n{\r\n    private OvmWsClient                api;\r\n    private Id<Vm>                     testVmId;\r\n    private Id<ServerPool>             testPoolId;\r\n    private Id<Server>                 testServerId;\r\n    private Id<Repository>             testRepoId;\r\n    private Id<Vm>                     importedAssemblyVmId;\r\n    private Job                        repoPresentJob;\r\n\r\n    public static void main(final String args[])\r\n    {\r\n        int index;\r\n\tString vmname="";\r\n\tString server="";\r\n        for (index = 0; index < args.length; ++index)\r\n        {\r\n            \/\/System.out.println("args[" + index + "]: " + args[index]);\r\n       \t    String[] splitted=args[index].split("=");\r\n\t    if ( splitted[0].equals("vmname") ) {\r\n\t      vmname=splitted[1];\r\n              \/\/System.out.println(vmname);\r\n\t\r\n\t    }\r\n\t    if ( splitted[0].equals("server") ) {\r\n\t      server=splitted[1];\r\n              \/\/System.out.println(server);\r\n\t    }\r\n        }\r\n       \/\/String[] vmname=args[0].split("=");;\r\n       \/\/String[] server=args[1].split("=");;\r\n        final WsDevClient wsClient = new WsDevClient();\r\n       wsClient.run(vmname,server);\r\n    }\r\n\r\n    public void run(final String testVmName,final String testServerName)\r\n    {\r\n        try\r\n        {\r\n            \/\/ Configure the SSLContext with an insecure TrustManager\r\n            \/\/ This is done to avoid the need to use valid certificates in the development environment.\r\n            \/\/ This should not be done in a real \/ secure environment.\r\n            final SSLContext ctx = SSLContext.getInstance("TLS");\r\n            ctx.init(new KeyManager[0], new TrustManager[]\r\n            {\r\n                new InsecureTrustManager()\r\n            }, new SecureRandom());\r\n            SSLContext.setDefault(ctx);\r\n\r\n            \/\/ Configure the HostnameVerifier to trust host names that do\r\n            \/\/ not match the name on the server certificate.\r\n            \/\/ This should not be done in real \/ secure environments.\r\n            final HostnameVerifier hv = new HostnameVerifier()\r\n            {\r\n                public boolean verify(final String arg0, final SSLSession arg1)\r\n                {\r\n                    return true;\r\n                }\r\n            };\r\n            HttpsURLConnection.setDefaultHostnameVerifier(hv);\r\n\r\n            final ResourceBundle rootProps = ResourceBundle.getBundle("com.oracle.ovm.mgr.ws.sample.WsDevClient");\r\n            ResourceBundle userProps = null;\r\n            try\r\n            {\r\n                userProps = ResourceBundle.getBundle("com.oracle.ovm.mgr.ws.sample.WsDevClient_" + System.getProperty("user.name"));\r\n            }\r\n            catch (final MissingResourceException ex)\r\n            {\r\n                System.out.println(ex);\r\n                System.out.println("Warning: No user-overridden properties found.  Using default values.  This is unlikely to work and is not recommended!");\r\n            }\r\n            \/\/ Load the properties. An exception will be thrown if any of these properties are not found.\r\n            final String wsimpl = getProperty("wsimpl", rootProps, userProps);\r\n            final String dialect = getProperty("dialect", rootProps, userProps);\r\n            final String hostname = getProperty("hostname", rootProps, userProps);\r\n            final String port = getProperty("port", rootProps, userProps);\r\n            final String username = getProperty("username", rootProps, userProps);\r\n            final String password = getProperty("password", rootProps, userProps);\r\n            final String testRepo = getProperty("testRepo", rootProps, userProps);\r\n            \/\/final String testVmName = getProperty("testVmName", rootProps, userProps);\r\n            final String debugStr = getProperty("debugHttpTraffic", rootProps, userProps);\r\n            \/\/final String testServerName = getProperty("testServerName", rootProps, userProps);\r\n            final String testServerPoolName = getProperty("testServerPoolName", rootProps, userProps);\r\n            final String assemblyUrl = getProperty("assemblyUrl", rootProps, userProps);\r\n            final boolean debug = debugStr.equalsIgnoreCase("true");\r\n\r\n            api = OvmWsClientFactory.getOvmWsClient(wsimpl);\r\n            api.setDebug(debug);\r\n            api.setDialect(dialect);\r\n            api.initialize(hostname, port, true);\r\n            \/\/ Authenticate with the OvmApi Service\r\n            api.login(username, password, Locale.getDefault());\r\n            System.out.println("Starting Ovm Api Test Using " + wsimpl + " Implementation\\n");\r\n\t    final List<Repository> repos = api.repositoryGetAll();\r\n            for (final Repository repo : repos)\r\n            {\r\n                \/\/printRepository(repo);\r\n\r\n                if (repo.getId().getValue().equals(testRepo))\r\n                {\r\n                    testRepoId = repo.getId();\r\n                }\r\n            }\r\n\t    \/\/ Get a list of all Server Pools\r\n            final List<Id<ServerPool>> serverPoolIds = api.serverPoolGetIds();\r\n            for (final Id<ServerPool> serverPoolId : serverPoolIds)\r\n            {\r\n                \/\/printId("ServerPool", serverPoolId);\r\n\t\t\/\/ need better checking than just picking one\r\n\t\ttestPoolId = serverPoolId;\r\n            }\r\n            \/\/ Run checks to make sure we can proceed.\r\n            if (testRepoId == null)\r\n            {\r\n                throw new Exception("Repository for VM creation (with id " + testRepo + ") not found.  Exiting.");\r\n            }\r\n            System.out.println("Starting VM create of: " + testVmName);\r\n            Vm testVm = new Vm();\r\n            testVm.setVmDomainType(VmDomainType.XEN_HVM);\r\n            testVm.setName(testVmName);\r\n            testVm.setRepositoryId(testRepoId);\r\n\t    \/\/final ServerPool serverPool = api.serverPoolGetById(testPoolId);\r\n            final Job vmCreateJob = api.vmCreate(testVm, testPoolId);\r\n            System.out.println("create vm job id: " + vmCreateJob.getId());\r\n            testVmId = waitForJobComplete(api, vmCreateJob, Vm.class);\r\n            \/\/ fetch vm create result object to fully populate the object (including the id and default values)\r\n            \/\/ in preparation for the modify test\r\n            testVm = api.vmGetById(testVmId);\r\n        }\r\n        catch (final Exception e)\r\n        {\r\n            e.printStackTrace();\r\n            System.out.println("\\nException occurred during processing.  Calling cleanup routine.");\r\n        }\r\n        finally\r\n        {\r\n                try\r\n                {\r\n                    api.logout();\r\n                }\r\n                catch (final WsException e)\r\n                {\r\n                    e.printStackTrace();\r\n                }\r\n        }\r\n    }\r\n    \/**\r\n     * @param string\r\n     * @param rootProps\r\n     * @param userProps\r\n     * @return\r\n     *\/\r\n    private String getProperty(final String key, final ResourceBundle... bundles)\r\n    {\r\n        String value = null;\r\n        MissingResourceException missingResourceEx = null;\r\n        for (final ResourceBundle bundle : bundles)\r\n        {\r\n            if (bundle != null)\r\n            {\r\n                try\r\n                {\r\n                    value = bundle.getString(key);\r\n                }\r\n                catch (final MissingResourceException ex)\r\n                {\r\n                    missingResourceEx = ex;\r\n                }\r\n            }\r\n        }\r\n        if (value == null)\r\n        {\r\n            throw missingResourceEx;\r\n        }\r\n        return value;\r\n    }\r\n    \/**\r\n     * @param group\r\n     *\/\r\n    private void printJob(final Job job)\r\n    {\r\n        System.out.println("Job Id: " + job.getId());\r\n        System.out.println("\\tUser: " + job.getUser());\r\n        System.out.println("\\tStart Time: " + job.getStartTime());\r\n        System.out.println("\\tEnd Time: " + job.getEndTime());\r\n        System.out.println("\\tRun State: " + job.getJobRunState());\r\n        System.out.println("\\tGroup: " + job.isJobGroup());\r\n        System.out.println("\\tResult Id: " + job.getResultId());\r\n        try\r\n        {\r\n            final String transcript = api.jobGetDebugTranscript(job.getId());\r\n            System.out.println(transcript);\r\n        }\r\n        catch (final Exception e)\r\n        {\r\n            e.printStackTrace();\r\n        }\r\n        final List<Id<Job>> jobChildren = job.getChildJobIds();\r\n        if (jobChildren != null)\r\n        {\r\n            for (final Id<Job> childJob : jobChildren)\r\n            {\r\n                System.out.println("\\tChildJob: " + childJob);\r\n            }\r\n        }\r\n        final JobError error = job.getError();\r\n        if (error != null)\r\n        {\r\n            System.out.println("\\tError Type: " + error.getType());\r\n            System.out.println("\\tError Message: " + error.getMessage());\r\n        }\r\n\r\n        System.out.println();\r\n    }\r\n    public void waitForJobComplete(final OvmWsClient api, final Job job) throws WsException\r\n    {\r\n        waitForJobComplete(api, job, null);\r\n    }\r\n    @SuppressWarnings("unchecked")\r\n    public <T> Id<T> waitForJobComplete(final OvmWsClient api, Job job, final Class<T> type) throws WsException\r\n    {\r\n        while (job.isSummaryDone() == false)\r\n        {\r\n            try\r\n            {\r\n                Thread.sleep(1000);\r\n            }\r\n            catch (final Exception e)\r\n            {\r\n            }\r\n\r\n            job = api.jobGetById(job.getId());\r\n\r\n            if (job.getJobRunState().equals(JobRunState.FAILURE))\r\n            {\r\n                final JobError error = job.getError();\r\n                if (error != null)\r\n                {\r\n                    System.out.println("    error type: " + error.getType());\r\n                    System.out.println("    error message: " + error.getMessage());\r\n                }\r\n                System.out.println("    transcript: " + api.jobGetDebugTranscript(job.getId()));\r\n            }\r\n        }\r\n        @SuppressWarnings("rawtypes")\r\n        final Id resultId = job.getResultId();\r\n        if (type == null)\r\n        {\r\n            return resultId;\r\n        }\r\n        else\r\n        {\r\n            final Id<T> typedResultId = resultId;\r\n            return typedResultId;\r\n        }\r\n    }\r\n    private static class InsecureTrustManager implements X509TrustManager\r\n    {\r\n        @Override\r\n        public void checkClientTrusted(final X509Certificate[] arg0, final String arg1) throws CertificateException\r\n        {\r\n        }\r\n        @Override\r\n        public void checkServerTrusted(final X509Certificate[] arg0, final String arg1) throws CertificateException\r\n        {\r\n        }\r\n        @Override\r\n        public X509Certificate[] getAcceptedIssuers()\r\n        {\r\n            return null;\r\n        }\r\n    }\r\n}\r\n<\/pre>\n

Properties file. I will work more of this into command line parms later.<\/p>\n

\r\nrrosso@BL:~\/src\/ovm_java_api$ cat com\/\/oracle\/ovm\/mgr\/ws\/sample\/WsDevClient_rrosso.properties \r\nwsimpl=SOAP\r\ndialect=XML\r\nhostname=192.168.1.231\r\nport=7002\r\nusername=admin\r\npassword=myAdminPassW\r\ntestRepo=0004fb00000300002e4e288cfa06e535\r\ntestServerPoolName=repo1\r\ndebugHttpTraffic=false\r\nassemblyUrl=http:\/\/install-vi.us.oracle.com\/tests\/assemblies\/virtual-appliance-simple\/package.ovf\r\n<\/pre>\n","protected":false},"excerpt":{"rendered":"

I am playing with the java SOAP API to test creating a VM and since it took me a while<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[29],"tags":[],"class_list":["post-1077","post","type-post","status-publish","format-standard","hentry","category-ovm"],"_links":{"self":[{"href":"https:\/\/blog.ls-al.com\/wp-json\/wp\/v2\/posts\/1077","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/blog.ls-al.com\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/blog.ls-al.com\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/blog.ls-al.com\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/blog.ls-al.com\/wp-json\/wp\/v2\/comments?post=1077"}],"version-history":[{"count":0,"href":"https:\/\/blog.ls-al.com\/wp-json\/wp\/v2\/posts\/1077\/revisions"}],"wp:attachment":[{"href":"https:\/\/blog.ls-al.com\/wp-json\/wp\/v2\/media?parent=1077"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/blog.ls-al.com\/wp-json\/wp\/v2\/categories?post=1077"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/blog.ls-al.com\/wp-json\/wp\/v2\/tags?post=1077"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}