VMware {code} Community
fanliang
Contributor
Contributor
Jump to solution

VI SDK2.0(Java) api call exception throw and catch miss puzzle ?

Hi ,I have used the VI SDK2.0(Java) to control my virtualmachines through virtual center .I can use the API to control the vm such as power on ,poweroff,clone and so on.However,the exception seems a little strange.

-


Here is an example.I use the VmPowerOps.java code in the vimsamples in sdk folder.

if (getPowerOpName().equals("on")) { expectedPowerState = VirtualMachinePowerState.poweredOn; taskmor = clientInfo.getConnection().getService().powerOnVM_Task(vmmor, hostmor); } else if (getPowerOpName().equals("off")) { expectedPowerState = VirtualMachinePowerState.poweredOff; taskmor = clientInfo.getConnection().getService().powerOffVM_Task(vmmor);

} ......

-


powerOnVM_Task should throws exception if the vm is powered on.InvalidPowerState Thrown if the power state is poweredOn.Although I can see the status report in VI client task list as :the attempted operation cannot be performed in the current state(Powered on).

However, VmPowerOps.java just executes and I can not seem any exception.So how can I catch the exception in my code .Should I do as the code example in the VmPowerOps.java:

like this:

-


// If we get a valid task reference, monitor the task for success or failure // and report task completion or failure. if (taskmor != null) { log.logLine("Got Valid Task Reference"); Object[] result = clientInfo.getServiceUtil().waitForValues( taskmor, new String[] { "info.state", "info.error" }, //TODO:vmmor, new String[] { "runtime.powerState" }, new String[] { "state" }, // info has a property - state for state of the task //TODO:new String[] { "powerState" }, // info has a property - state for state of the task new Object[][] { new Object[] { TaskInfoState.success, TaskInfoState.error } } //TODO:new Object[][] { new Object[] { expectedPowerState } } ); // Wait till the task completes. if (result[0].equals(TaskInfoState.success)) { log.logLine(clientInfo.getAppName() + " : Successful " + getPowerOpName() + " for VM : " + getVmName()); } else { log.logLine(clientInfo.getAppName() + " : Failed " + getPowerOpName() + " for VM : " + getVmName()); if (result.length == 2 && result[1] != null) { if (result[1] instanceof MethodFault) { clientInfo.getUtil().logFault((MethodFault)result[1]); } } }

-


Does this means I should monitor the task for success or failure and report task completion or failure in my code.

Although the powerOnVM_Task have this declaration

ManagedObjectReference

com.vmware.vim.VimPortType.powerOnVM_Task(ManagedObjectReference arg0,

ManagedObjectReference arg1) throws RemoteException, VmConfigFault,

TaskInProgress, FileFault, InvalidState, InsufficientResourcesFault,

RuntimeFault

I can not get any exception.I have try other api, all have the same problem.

I feel realy puzzled.Did I configure something wrong?

So can some can me ?Thanks a lot .....

0 Kudos
1 Solution

Accepted Solutions
tos2k
Expert
Expert
Jump to solution

Hi!

One more comment. VimSdk does not throw exceptions in general, when an op fails.

As you wrote, you can poll the task for its success value. In the VMpowerOps.java:

private boolean getTaskInfo(ManagedObjectReference taskmor)throws Exception{

shows you an implementation on how to fetch task states. These you can use to verify success of a task in most situations.

Tos2k

View solution in original post

0 Kudos
11 Replies
tos2k
Expert
Expert
Jump to solution

Hi!

I would at least recommend to use the predefined constants from VimApi namespace, in this case replace

if (getPowerOpName().equals("on"))

with

if(myPowerstate == VirtualMachinePowerState.poweredOn)

I am a little unsure what you code does in detail, but I think you are trying to power on a powered-on VM, where VimSdk indeed throws an exception, as expected. That due that the powerstate does not match your custom string "on"...

Tos2k

fanliang
Contributor
Contributor
Jump to solution

Thanks!

The code is in SDK2.0\samples_2_0\Axis\java\com\vmware\vimsample\vmpowerops.java.

In the document and PowerOnVM_Task decalration in the vim.jar ,it will throw exception.And I can see the error status report in the VI client .However,it just does not throw exception when excuted.

Now I can only check the task reference return value to know the really fault.

It's really confusing.

0 Kudos
tos2k
Expert
Expert
Jump to solution

I checked the java file, and you are right: poor design/code, and, sometimes, confusing, when lacking predefined constants. Anyway:

1) They do not check the powerstate, so I expect your check for current powerstate to fail

2) I can just recommend com.vmware.vim25.VirtualMachinePowerState predefined constants to check any values

Tos2k

fanliang
Contributor
Contributor
Jump to solution

I try to use the sdk2.5(java).It does not throw exception too.

Here is the simple test code :

import com.vmware.apputils.vim25.ServiceConnection; import com.vmware.vim25.*; public class test { public static void main(String[] args) { try { ServiceConnection sc = new ServiceConnection("ServiceInstance"); String urlStr="http://vc-server/sdk"; String username="username"; String password="password" sc.connect(urlStr, username,password,true); VimPortType service = sc.getService(); ManagedObjectReference Index = sc.getServiceContent().getSearchIndex(); ManagedObjectReference vm = service.findByInventoryPath(Index, "/vm/test"); ManagedObjectReference taskmor = service.powerOnVM_Task(vm, null); }catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } }

Althoght I have to use try{ }catch{}.No exception throws when excuted. It seems that the PowerOnVM_Task just does not throw exception actually.I have tried some other task such asCloneVM_Task.No exception too.

In the vmware sdk samples ,tt monitor the task ManagedObjectReference.And get the result reason through TaskInfo.error which is type of LocalizedMethodFault .

It's really strange.

0 Kudos
tos2k
Expert
Expert
Jump to solution

Hi!

One more comment. VimSdk does not throw exceptions in general, when an op fails.

As you wrote, you can poll the task for its success value. In the VMpowerOps.java:

private boolean getTaskInfo(ManagedObjectReference taskmor)throws Exception{

shows you an implementation on how to fetch task states. These you can use to verify success of a task in most situations.

Tos2k

0 Kudos
fanliang
Contributor
Contributor
Jump to solution

Thanks a lot!

That's the real problem. The sdk does not throw exception when ops failed although the method signature says it will throws such exception.

As you say,I try to use the task reference to check the task staus.If the task state is "error", then error property of TaskInfo contains the fault code. And I then analyse the error property.Error is of type LocalizedMethodFault,which is a wrapper class used to pass MethodFault data objects over the wire along with a localized display message for the fault.

Although this is a little inconvenient ,it sloves my problems.

0 Kudos
tos2k
Expert
Expert
Jump to solution

Hi!

although the method signature says it will throws such exception.

I dunno where you got this from, but the online doc is correct according to this:

http://pubs.vmware.com/vi3/sdk/ReferenceGuide/vim.VirtualMachine.html#powerOn

Tos2k

0 Kudos
fanliang
Contributor
Contributor
Jump to solution

The ops does not throw exception when excuted,I still need do something like this to surpress the exception.

-


try { taskmor = service.powerOnVM_Task(vmRef, null); } catch (VmConfigFault e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (TaskInProgress e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (FileFault e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (InvalidState e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (InsufficientResourcesFault e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (RuntimeFault e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (RemoteException e) { // TODO Auto-generated catch block e.printStackTrace(); }

-


Or I should let the exception goes up?Although the exception does show up when excuted.

Thanks! :smileysilly:

0 Kudos
tos2k
Expert
Expert
Jump to solution

It depends on your programming likes and dislikes, as on what you want to achieve.

Basically I would try to fetch the task success in a try/catch block

try{

if(WaitForResult(service.powerOnVM_Task(vmRef, null)) == SUCC)

...

}catch(Exception e){

log(ex)

}

Considering that an exception is something that should not happen in general, you should also handle it so.

Tos2k

0 Kudos
fanliang
Contributor
Contributor
Jump to solution

I want to handle some speciall exception such as InvalidPowerState exception

try{ if(WaitForResult(service.powerOnVM_Task(vmRef, null)) == SUCC) ... } catch(InvalidPowerState e){ System.out.println("Virtual Machine is already powered on"); } catch(Exception e){ System.out.println("Error"); e.printStackTrace(); }

However,when excuted InvalidPowerState exception does not throw.

Then I can not handle it.Instead I should do something like this:

  • For certain common errors, identify the type and
  • print useful information about them.
if (result[0].equals(TaskInfoState.success)) { return Boolean.TRUE; } else { if (result.length == 2 && result[1] != null) { Object realFault; /* Check the fault type */ if (result[1] instanceof LocalizedMethodFault) { realFault = ((LocalizedMethodFault) result[1]) .getFault(); logger.error("Received Method Fault executing task: " + ((LocalizedMethodFault) result[1]) .getLocalizedMessage()); /* */ //for those powering operations, extract localized message for rendering if (realFault instanceof InvalidPowerState) { throw new RuntimeException(((LocalizedMethodFault) result[1]).getLocalizedMessage()); } if (realFault instanceof InvalidArgument) { logger.error("Invalid argument: " + ((InvalidArgument) realFault) .getInvalidProperty()); } } else { logger.error("Recieved unknown error in task"); } } return Boolean.FALSE;

0 Kudos
tos2k
Expert
Expert
Jump to solution

Yes, as I wrote in the message before: The default error handling should be based on task-success-state. This should give you what you need in general. All other, unwanted, behaviour should/will just occur exceptional, this is what exceptions are for.

I cannot understand why your IDE recommends/interpretes VMware faults as Exceptions. Maybe VMware was creating wrong signatures for the Java based SDK, maybe your IDE has misunderstood something.

I was using netbeans to implement some smaller Java based VimSdk functionality, but I never met that netbeans recommended exceptions for me automatically...

Tos2k

0 Kudos