1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23 package org.redhat.vmtruckloader.util;
24
25 import java.util.ArrayList;
26 import java.util.Collections;
27 import java.util.List;
28
29 import org.slf4j.Logger;
30 import org.slf4j.LoggerFactory;
31
32 import com.vmware.vim25.VirtualDevice;
33 import com.vmware.vim25.VirtualEthernetCard;
34 import com.vmware.vim25.VirtualMachineConfigInfo;
35 import com.vmware.vim25.mo.VirtualMachine;
36
37
38
39
40
41
42 public class VirtualMachineUtils {
43
44 private static final Logger LOGGER = LoggerFactory.getLogger(VirtualMachineUtils.class);
45
46 public static String getMacAddress(VirtualMachine vm) {
47 if ( vm == null )
48 throw new IllegalArgumentException("Provided instance of " + VirtualMachine.class.getName() + " was 'null'.");
49
50 final List<String> macAddresses = getMacAddresses(vm);
51 if (macAddresses.isEmpty() )
52 throw new IllegalStateException("Machine " + vm.getName() + " has no @MAC address !");
53 return macAddresses.get(0);
54 }
55
56 public static List<String> getMacAddresses(VirtualMachine vm) {
57
58 final VirtualMachineConfigInfo vmConfigInfo = vm.getConfig();
59 if ( vmConfigInfo == null ) throw new IllegalStateException("No ConfigInfo for VM:" + vm.getName());
60 if ( vmConfigInfo.getHardware() == null ) throw new IllegalStateException("No Hardware for VM:" + vm.getName());
61 if ( vmConfigInfo.getHardware().getDevice() == null ) throw new IllegalStateException("No Device for VM:" + vm.getName());
62
63 final VirtualDevice[] vdev= vmConfigInfo.getHardware().getDevice();
64 if ( vdev.length == 0 )
65 return Collections.emptyList();
66 else {
67 final List<String> macAddresses = new ArrayList<String>(vdev.length);
68 for(int idDevice=0; idDevice < vdev.length; idDevice++) {
69 if((vdev[idDevice] instanceof VirtualEthernetCard)) {
70 final String macAddress = ((VirtualEthernetCard) vdev[idDevice]).macAddress;
71 macAddresses.add(macAddress);
72 if ( LOGGER.isDebugEnabled() )
73 LOGGER.debug("@MAC:" + macAddress);
74 }
75 }
76 return macAddresses;
77 }
78 }
79 }