设为首页 收藏本站
查看: 1199|回复: 0

[经验分享] Java如何获取VMware中Vcenter/ServerInstance下的各种硬件信息

[复制链接]

尚未签到

发表于 2016-1-7 00:27:58 | 显示全部楼层 |阅读模式
  用Java来获取VMware ESX Server的信息可以通过一个第三方jar包进行方便的操作:
   Vijava – Vmware infrastructure(vSphere) java API
 
  关于ESX Server的介绍,可以参照我的另一篇博客:http://josh-persistence.iyunv.com/admin/blogs/1887722
  
  下面看看一些相关介绍,然后再看对应的程序:
  1.   VCenter/ServiceInstance Strucutre
  
DSC0000.gif
 
  1). ServiceInstance -- Root of the inventory; created by vSphere.   (VCenter)
 

2). Datacenter -- A container that represents a virtual data center. It contains hosts, network entities, virtual machines and virtual applications, and datastores.
 
3). ComputeResource -- A compute resource (either a cluster or a stand-alone host) (Cluster)
 
4). HostSystem -- A single host (ESX Server or VMware Server).
 
  
  5). AboutInfo -- This data object type describes system information including the name, type, version, and build number. (HostSystem/ESX Server/VMware Sever’s AboutInfo)
  
<!--[if !supportLists]-->1.     2.  Below are EsxServer/HostSystem properties is returned from Vijava.
 
 
  
DSC0001.png
 
  3. 进一步了解ESXServer的Strutcture
  
DSC0002.png
 
DSC0003.png
 
  EsxServer contains several vm(Virtual Machine of EsxServer), EsxServer and vm’ relationships set on Network(network of EsxServer), Network contains Virtual NIC, Virtual Switch. Virtual Switch is responsible for assigning Physical NIC to VM, just like the VM has its own NIC(Virtual NIC). There have to consider VM and NIC’s relationship, because the NIC may be assigned to one of the VM unexpectedly  which means the VM can be related to different Virtual NIC.
  
DSC0004.png
 
  
DSC0005.png
 
  
  从上面的架构图可看出,如果我们需要获取VCenter,ESXServer等的信息,就包括获取Disk/Volumn/Storage, 虚拟交换机,内存,虚拟网卡,物理网卡,内存等信息,最主要的是由于物理网卡通过虚拟交换机分配给每个虚拟主机作为虚拟网卡,这种关系是随机的,或者说有一定的分配规则的,我们在每次获取VCenter的信息时,都需要重新的去获取物理网卡的分配。
  
下面就是一个实例,该实例展现了怎样从VMware上通过vSphere提供的API(vijava.jar)来获取VCener/ServerInstance下的所有信息,包括上面2.  Below are EsxServer/HostSystem properties is returned from Vijava.中列的所有信息。更多的API,可以参照:http://pubs.vmware.com/vsphere-50/index.jsp
  
  
  import java.net.URL;
  import java.util.ArrayList;
  import java.util.HashMap;
  import java.util.List;
  import java.util.Map;
  
  import org.apache.log4j.Logger;
  
  import com.ebay.odb.sync.ESXServerSync;
  import com.vmware.vim25.AboutInfo;
  import com.vmware.vim25.ClusterComputeResourceSummary;
  import com.vmware.vim25.ClusterConfigInfo;
  import com.vmware.vim25.DatastoreInfo;
  import com.vmware.vim25.HostHardwareInfo;
  import com.vmware.vim25.HostHostBusAdapter;
  import com.vmware.vim25.HostInternetScsiHba;
  import com.vmware.vim25.HostInternetScsiHbaSendTarget;
  import com.vmware.vim25.HostInternetScsiTargetTransport;
  import com.vmware.vim25.HostMultipathInfoLogicalUnit;
  import com.vmware.vim25.HostMultipathInfoPath;
  import com.vmware.vim25.HostNetworkInfo;
  import com.vmware.vim25.HostPortGroup;
  import com.vmware.vim25.HostScsiDiskPartition;
  import com.vmware.vim25.HostStorageDeviceInfo;
  import com.vmware.vim25.HostTargetTransport;
  import com.vmware.vim25.HostVirtualNic;
  import com.vmware.vim25.HostVirtualSwitch;
  import com.vmware.vim25.HostVmfsVolume;
  import com.vmware.vim25.HostNasVolume;
  import com.vmware.vim25.PhysicalNic;
  import com.vmware.vim25.VirtualDevice;
  import com.vmware.vim25.VirtualEthernetCard;
  import com.vmware.vim25.VirtualHardware;
  import com.vmware.vim25.VirtualMachineConfigInfo;
  import com.vmware.vim25.VirtualMachineSummary;
  import com.vmware.vim25.VmfsDatastoreInfo;
  import com.vmware.vim25.NasDatastoreInfo;
  import com.vmware.vim25.mo.ClusterComputeResource;
  import com.vmware.vim25.mo.Datacenter;
  import com.vmware.vim25.mo.Folder;
  import com.vmware.vim25.mo.HostSystem;
  import com.vmware.vim25.mo.InventoryNavigator;
  import com.vmware.vim25.mo.ManagedEntity;
  import com.vmware.vim25.mo.ServiceInstance;
  import com.vmware.vim25.mo.VirtualMachine;
  
  public class VCenterInventory
  {
  private static final Logger log = Logger.getLogger(ESXServerSync.class);
  private String host;
  
  private String username;
  
  private String password;
  
  public VCenterInventory(String host, String username, String password) {
  super();
  this.host = host;
  this.username = username;
  this.password = password;
  }
  
  public VCenter getVCenterInfo() throws Exception {
  URL url = new URL("https", host, "/sdk");
  ServiceInstance si = new ServiceInstance(url, username, password, true);
  Folder rootFolder = si.getRootFolder();
  VCenter vc = new VCenter();
  AboutInfo ai = si.getAboutInfo();
  vc.setHostname(host);
  vc.setDescr(ai.getFullName());
  vc.setVersion(ai.getVersion());
  InventoryNavigator inav = new InventoryNavigator(rootFolder);
  ManagedEntity[] esxs = inav.searchManagedEntities("HostSystem");
  List<ESXServer> servers = new ArrayList<ESXServer>();
  for (ManagedEntity esx : esxs) {
  HostSystem hs = (HostSystem) esx;
  HostHardwareInfo hwi = hs.getHardware();
  long hz = hwi.cpuInfo.hz;
  long e9 = 1000000000;
  double hzd = new java.math.BigDecimal(((double) hz) / e9).setScale(2, java.math.BigDecimal.ROUND_HALF_UP)
  .doubleValue();
  ESXServer server = new ESXServer();
  server.setName(hs.getName());
  server.setCpufrequency(String.valueOf(hzd) + "GHz");
  servers.add(server);
  }
  vc.setEsxservers(servers);
  
  ManagedEntity[] clusters = inav.searchManagedEntities("Datacenter");
  List<Cluster> cs = new ArrayList<Cluster>();
  for (ManagedEntity me : clusters) {
  Datacenter dc = (Datacenter) me;
  String path = dc.getName();
  cs.addAll(getClusters(dc, path, dc.getHostFolder()));
  }
  vc.setClusters(cs);
  si.getSessionManager().logout();
  return vc;
  }
  
  
  
  private static List<Cluster> getClusters(Datacenter dc, String path, Folder f) throws Exception {
  List<Cluster> cs = new ArrayList<Cluster>();
  ManagedEntity[] ces = f.getChildEntity();
  for (ManagedEntity ce : ces) {
  if (ce instanceof ClusterComputeResource) {
  cs.add(getClusterInfo(dc, path, (ClusterComputeResource) ce));
  }
  else if (ce instanceof Folder) {
  cs.addAll(getClusters(dc, path + ":" + ce.getName(), (Folder) ce));
  }
  }
  return cs;
  }
  
  public List<VMachine> getAllVM(String esxserver) throws Exception {
  ManagedEntity[] esxs = null;
  URL url = new URL("https", host, "/sdk");
  ServiceInstance si = new ServiceInstance(url, username, password, true);
  Folder rootFolder = si.getRootFolder();
  esxs = new InventoryNavigator(rootFolder).searchManagedEntities("HostSystem");
  for (ManagedEntity esx : esxs) {
  HostSystem hs = (HostSystem) esx;
  if (hs.getName().equals(esxserver)) {
  List<VMachine> vms = getAllVM(hs);
  si.getSessionManager().logout();
  return vms;
  }
  }
  si.getSessionManager().logout();
  throw new RuntimeException("Cannot find esxserver:" + esxserver);
  }
  
  public List<Datastore> getAllDatastores(String esxserver) throws Exception {
  ManagedEntity[] esxs = null;
  URL url = new URL("https", host, "/sdk");
  ServiceInstance si = new ServiceInstance(url, username, password, true);
  Folder rootFolder = si.getRootFolder();
  esxs = new InventoryNavigator(rootFolder).searchManagedEntities("HostSystem");
  for (ManagedEntity esx : esxs) {
  HostSystem hs = (HostSystem) esx;
  if (hs.getName().equals(esxserver)) {
  List<Datastore> ds= getAllDatastores(hs);
  si.getSessionManager().logout();
  return ds;
  }
  }
  si.getSessionManager().logout();
  throw new RuntimeException("Cannot find esxserver:" + esxserver);
  }
  
  public NetworkInfo getNetworkInfo(String esxserver) throws Exception {
  ManagedEntity[] esxs = null;
  URL url = new URL("https", host, "/sdk");
  ServiceInstance si = new ServiceInstance(url, username, password, true);
  Folder rootFolder = si.getRootFolder();
  esxs = new InventoryNavigator(rootFolder).searchManagedEntities("HostSystem");
  for (ManagedEntity esx : esxs) {
  HostSystem hs = (HostSystem) esx;
  if (hs.getName().equals(esxserver)) {
  NetworkInfo ni= getNetworkInfo(hs);
  si.getSessionManager().logout();
  return ni;
  }
  }
  si.getSessionManager().logout();
  throw new RuntimeException("Cannot find esxserver:" + esxserver);
  }
  
  private NetworkInfo getNetworkInfo(HostSystem esxserver) throws Exception {
  NetworkInfo ninfo = new NetworkInfo();
  HostNetworkInfo nwi = esxserver.getConfig().getNetwork();
  HostPortGroup[] portgroups = nwi.getPortgroup();
  Map<String, String> pgMap = new HashMap<String, String>();
  for (HostPortGroup portgroup : portgroups) {
  pgMap.put(portgroup.getKey(), portgroup.getSpec().getName());
  }
  PhysicalNic[] pnics = nwi.getPnic();
  Map<String, String> pnicMap = new HashMap<String, String>();
  for (PhysicalNic pnic : pnics) {
  pnicMap.put(pnic.getKey(), pnic.getMac());
  }
  List<VirtualSwitch> vss = new ArrayList<VirtualSwitch>();
  HostVirtualSwitch[] vswtichs = nwi.getVswitch();
  for (HostVirtualSwitch vswitch : vswtichs) {
  VirtualSwitch vs = new VirtualSwitch();
  vs.setName(vswitch.getName());
  String[] macKeys = vswitch.getPnic();
  if (macKeys != null) {
  for (String key : macKeys) {
  vs.addPhysicalMAC(pnicMap.get(key));
  }
  }
  String[] pgs = vswitch.getPortgroup();
  if (pgs != null) {
  for (String pg : pgs) {
  vs.addPortgroup(pgMap.get(pg));
  }
  }
  // TODO
  vss.add(vs);
  }
  ninfo.setVss(vss);
  
  List<VirtualNic> vnics = new ArrayList<VirtualNic>();
  HostVirtualNic[] virtualnics = nwi.getVnic();
  for (HostVirtualNic virtualnic : virtualnics) {
  VirtualNic vnic = new VirtualNic();
  vnic.setName(virtualnic.getDevice());
  vnic.setPortgroup(virtualnic.getPortgroup());
  vnic.setMac(virtualnic.getSpec().getMac());
  vnics.add(vnic);
  }
  ninfo.setVnics(vnics);
  return ninfo;
  }
  
  private List<Datastore> getAllDatastores(HostSystem esxserver) throws Exception {
  List<Datastore> datastores = new ArrayList<Datastore>();
  
  Map<String, Disk> storages = new HashMap<String, Disk>();
  HostStorageDeviceInfo sd = esxserver.getConfig().getStorageDevice();
  HostHostBusAdapter[] hostBusAdapters = sd.getHostBusAdapter();
  Map<String, String[]> hostBuses = new HashMap<String, String[]>();
  for (HostHostBusAdapter adapter : hostBusAdapters) {
  if (adapter instanceof HostInternetScsiHba) {
  HostInternetScsiHbaSendTarget[] targets = ((HostInternetScsiHba) adapter).getConfiguredSendTarget();
  if (null != targets && targets.length > 0) {
  String[] floatings = new String[targets.length];
  for (int i = 0; i < targets.length; i++) {
  floatings = targets.getAddress();
  }
  hostBuses.put(adapter.getKey(), floatings);
  }
  }
  }
  HostMultipathInfoLogicalUnit[] luns = sd.getMultipathInfo().getLun();
  for (HostMultipathInfoLogicalUnit lun : luns) {
  HostMultipathInfoPath[] paths = lun.getPath();
  for (HostMultipathInfoPath path : paths) {
  String pathName = path.getName();
  String diskName = pathName.substring(pathName.lastIndexOf('-') + 1);
  Disk s = new Disk();
  s.setPath(pathName);
  s.setDiskName(diskName);
  String[] floatings = hostBuses.get(path.getAdapter());
  s.setAddresses(floatings);
  HostTargetTransport transport = path.getTransport();
  if (transport instanceof HostInternetScsiTargetTransport) {
  s.setIScsiName(((HostInternetScsiTargetTransport) transport).iScsiName);
  }
  storages.put(diskName, s);
  }
  }
  
  com.vmware.vim25.mo.Datastore[] dss = esxserver.getDatastores();
  for (com.vmware.vim25.mo.Datastore ds : dss) {
  String name = ds.getName();
  DatastoreInfo info = ds.getInfo();
  HostVmfsVolume vmfs = null;
  HostNasVolume nasfs = null;
  if (info instanceof VmfsDatastoreInfo) {
  vmfs = ((VmfsDatastoreInfo) info).getVmfs();
  //log.warn("get vmfs:"+vmfs.getName());
  }else if(info instanceof NasDatastoreInfo){
  nasfs = ((NasDatastoreInfo)info).getNas();
  //log.warn("get nasfs:"+nasfs.getName());
  }
  else {
  continue;
  }
  
  Datastore datastore = new Datastore();
  datastore.setName(name);
  datastore.setStatus(ds.getOverallStatus().name());
  datastore.setCapacity(ds.getSummary().getCapacity());
  datastore.setFreeSpace(info.getFreeSpace());
  datastore.setMaxFileSize(info.getMaxFileSize());
  datastore.setUrl(info.getUrl());
  datastore.setType(ds.getSummary().getType());
  if(vmfs != null){
  datastore.setVersion(vmfs.getVersion());
  datastore.setVmfsUUID(vmfs.getUuid());
  HostScsiDiskPartition[] extents = vmfs.getExtent();
  
  for (HostScsiDiskPartition disk : extents) {
  String diskName = disk.getDiskName();
  datastore.addDisk(storages.get(diskName));
  }
  }
  VirtualMachine[] vms = ds.getVms();
  for (VirtualMachine vm : vms) {
  datastore.addVm(vm.getName());
  }
  datastores.add(datastore);
  
  }
  return datastores;
  }
  
  
  
  private List<VMachine> getAllVM(HostSystem esxserver) throws Exception {
  VirtualMachine[] vms = esxserver.getVms();
  
  List<VMachine> machines = new ArrayList<VMachine>();
  for (VirtualMachine vm : vms) {
  VirtualMachineConfigInfo config = vm.getConfig();
  VirtualMachineSummary summary = vm.getSummary();
  VMachine vmachine = new VMachine();
  vmachine.setName(vm.getName());
  vmachine.setUuid(config.getUuid());
  VirtualEthernetCard vec = getMac(config.getHardware());
  vmachine.setMac(vec.getMacAddress().toUpperCase());
  vmachine.setPortgroup(vec.getDeviceInfo().getSummary());
  vmachine.setVmPath(config.getFiles().getVmPathName());
  vmachine.setVmID(vm.getMOR().get_value());
  vmachine.setModel(config.getGuestFullName());
  vmachine.setPower(summary.getRuntime().getPowerState().name());
  vmachine.setHealth(vm.getOverallStatus().name());
  vmachine.setVersion(config.getVersion());
  vmachine.setVmIP(summary.getGuest().getIpAddress());
  vmachine.setCpucount(String.valueOf(vm.getSummary().getConfig().numCpu));
  machines.add(vmachine);
  }
  return machines;
  }
  
  private static VirtualEthernetCard getMac(VirtualHardware hardware) {
  VirtualDevice[] devices = hardware.getDevice();
  for (VirtualDevice device : devices) {
  if (device instanceof VirtualEthernetCard) {
  return ((VirtualEthernetCard) device);
  }
  }
  return null;
  }
  
  private static Cluster getClusterInfo(Datacenter dc, String path, ClusterComputeResource ccr) {
  Cluster cluster = new Cluster();
  cluster.setName(ccr.getName());
  cluster.setDatacenter(dc.getName());
  cluster.setPath(path);
  ClusterComputeResourceSummary summary = (ClusterComputeResourceSummary) ccr.getSummary();
  cluster.setCpu(summary.getTotalCpu());
  cluster.setCpucount(summary.getNumCpuCores());
  cluster.setMemory(summary.getTotalMemory());
  cluster.setEvcMode(summary.getCurrentEVCModeKey());
  ClusterConfigInfo config = ccr.getConfiguration();
  cluster.setHaEnabled(config.getDasConfig().getEnabled());
  cluster.setDrsEnabled(config.getDrsConfig().getEnabled());
  HostSystem[] hs = ccr.getHosts();
  for (HostSystem hostSystem : hs) {
  cluster.addServer(hostSystem.getName());
  }
  return cluster;
  }
  }

运维网声明 1、欢迎大家加入本站运维交流群:群②:261659950 群⑤:202807635 群⑦870801961 群⑧679858003
2、本站所有主题由该帖子作者发表,该帖子作者与运维网享有帖子相关版权
3、所有作品的著作权均归原作者享有,请您和我们一样尊重他人的著作权等合法权益。如果您对作品感到满意,请购买正版
4、禁止制作、复制、发布和传播具有反动、淫秽、色情、暴力、凶杀等内容的信息,一经发现立即删除。若您因此触犯法律,一切后果自负,我们对此不承担任何责任
5、所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其内容的准确性、可靠性、正当性、安全性、合法性等负责,亦不承担任何法律责任
6、所有作品仅供您个人学习、研究或欣赏,不得用于商业或者其他用途,否则,一切后果均由您自己承担,我们对此不承担任何法律责任
7、如涉及侵犯版权等问题,请您及时通知我们,我们将立即采取措施予以解决
8、联系人Email:admin@iyunv.com 网址:www.yunweiku.com

所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其承担任何法律责任,如涉及侵犯版权等问题,请您及时通知我们,我们将立即处理,联系人Email:kefu@iyunv.com,QQ:1061981298 本贴地址:https://www.yunweiku.com/thread-161109-1-1.html 上篇帖子: 如何预防由VMware驱动和后门程序导致的系统故障 下篇帖子: VMware Server 2.0+RHEL5+Oracle RAC注意事项
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

扫码加入运维网微信交流群X

扫码加入运维网微信交流群

扫描二维码加入运维网微信交流群,最新一手资源尽在官方微信交流群!快快加入我们吧...

扫描微信二维码查看详情

客服E-mail:kefu@iyunv.com 客服QQ:1061981298


QQ群⑦:运维网交流群⑦ QQ群⑧:运维网交流群⑧ k8s群:运维网kubernetes交流群


提醒:禁止发布任何违反国家法律、法规的言论与图片等内容;本站内容均来自个人观点与网络等信息,非本站认同之观点.


本站大部分资源是网友从网上搜集分享而来,其版权均归原作者及其网站所有,我们尊重他人的合法权益,如有内容侵犯您的合法权益,请及时与我们联系进行核实删除!



合作伙伴: 青云cloud

快速回复 返回顶部 返回列表