public static void main(String[] args) throws Exception { ServiceInstance si = new ServiceInstance(new URL(VCENTERURL), USERNAME, PASSWORD, true); Folder rootFolder = si.getRootFolder(); ManagedEntity[] hosts = new InventoryNavigator(rootFolder).searchManagedEntities("HostSystem"); if (hosts == null || hosts.length == 0) { return; } for (int i = 0; i < hosts.length; i++) { // get all vm in Vhost System.out.println("vHost loop ******************"); System.out.println("HostName: " + hosts[i].getName()); ManagedEntity[] mes = new InventoryNavigator(rootFolder).searchManagedEntities("VirtualMachine"); for (int j = 0; j < mes.length; j++) { VirtualMachine vm = (VirtualMachine) mes[j]; VirtualMachineConfigInfo vminfo = vm.getConfig(); vm.getResourcePool(); System.out.println("vHost: " + vm.getParent().getName()); System.out.println("Guest: " + vm.getName()); System.out.println("GuestOS: " + vminfo.getGuestFullName()); System.out.println("GuestState: " + vm.getGuest().guestState); System.out.println("Guest Ip address: " + vm.getGuest().getIpAddress()); pingByIP(vm.getGuest().getIpAddress()); // ping VM } HostSystem newHost = (HostSystem) hosts[i]; String vHost_IP = newHost.getConfig().getNetwork().getVnic()[0].getSpec().getIp().getIpAddress(); System.out.println("vHost IP address: " + vHost_IP); // test for ping vHost pingByIP(vHost_IP); // ping vHost } } // end of main
/** * Queries a host system for Cim data. * * @param hostSystem the host system to query * @param cimClass the class of Cim objects to retrieve * @param primaryIpAddress the Ip address to use * @return the list of Cim objects * @throws RemoteException * @throws CIMException */ public List<CIMObject> queryCimObjects( HostSystem hostSystem, String cimClass, String primaryIpAddress) throws ConnectException, RemoteException, CIMException { List<CIMObject> cimObjects = new ArrayList<CIMObject>(); if (!m_hostServiceTickets.containsKey(hostSystem)) { m_hostServiceTickets.put(hostSystem, hostSystem.acquireCimServicesTicket()); } HostServiceTicket hostServiceTicket = m_hostServiceTickets.get(hostSystem); if (!m_hostSystemCimUrls.containsKey(hostSystem)) { String ipAddress = primaryIpAddress; if (ipAddress == null) { ipAddress = getPrimaryHostSystemIpAddress(hostSystem); } if (ipAddress == null) { logger.warn( "Cannot determine ip address for host system '{}'", hostSystem.getMOR().getVal()); return cimObjects; } m_hostSystemCimUrls.put(hostSystem, "https://" + ipAddress + ":5989"); } String cimAgentAddress = m_hostSystemCimUrls.get(hostSystem); String namespace = "root/cimv2"; UserPrincipal userPr = new UserPrincipal(hostServiceTicket.getSessionId()); PasswordCredential pwCred = new PasswordCredential(hostServiceTicket.getSessionId().toCharArray()); CIMNameSpace ns = new CIMNameSpace(cimAgentAddress, namespace); CIMClient cimClient = new CIMClient(ns, userPr, pwCred); // very important to query esx5 hosts cimClient.useMPost(false); CIMObjectPath rpCOP = new CIMObjectPath(cimClass); Enumeration<?> rpEnm = cimClient.enumerateInstances(rpCOP); while (rpEnm.hasMoreElements()) { CIMObject rp = (CIMObject) rpEnm.nextElement(); cimObjects.add(rp); } return cimObjects; }
// TODO We should use the IP of the "Management Network" (i.e. the port that has enabled // "Management Traffic" on the available vSwitches). // Resolving the name of the HostSystem as the FQDN is the most closest thing for that. public String getPrimaryHostSystemIpAddress(HostSystem hostSystem) throws RemoteException { TreeSet<String> addresses = getHostSystemIpAddresses(hostSystem); String ipAddress = null; try { ipAddress = InetAddress.getByName(hostSystem.getName()).getHostAddress(); } catch (Exception e) { logger.debug("Can't resolve the IP address from {}.", hostSystem.getName()); } if (ipAddress == null) { return addresses.first(); } return addresses.contains(ipAddress) ? ipAddress : addresses.first(); }
/** * Searches for all ip addresses of a host system * * @param hostSystem the host system to query * @return the ip addresses of the host system, the first one is the primary * @throws RemoteException */ public TreeSet<String> getHostSystemIpAddresses(HostSystem hostSystem) throws RemoteException { TreeSet<String> ipAddresses = new TreeSet<String>(); HostNetworkSystem hostNetworkSystem = hostSystem.getHostNetworkSystem(); if (hostNetworkSystem != null) { HostNetworkInfo hostNetworkInfo = hostNetworkSystem.getNetworkInfo(); if (hostNetworkInfo != null) { HostVirtualNic[] hostVirtualNics = hostNetworkInfo.getConsoleVnic(); if (hostVirtualNics != null) { for (HostVirtualNic hostVirtualNic : hostVirtualNics) { ipAddresses.add(hostVirtualNic.getSpec().getIp().getIpAddress()); } } hostVirtualNics = hostNetworkInfo.getVnic(); if (hostVirtualNics != null) { for (HostVirtualNic hostVirtualNic : hostVirtualNics) { ipAddresses.add(hostVirtualNic.getSpec().getIp().getIpAddress()); } } } } return ipAddresses; }
/** * This method queries the Vmware vCenter server for sensor data. * * @param svc the monitored service * @param parameters the parameter map * @return the poll status for this system */ @Override public PollStatus poll(MonitoredService svc, Map<String, Object> parameters) { OnmsNode onmsNode = m_nodeDao.get(svc.getNodeId()); // retrieve the assets and String vmwareManagementServer = onmsNode.getAssetRecord().getVmwareManagementServer(); String vmwareManagedEntityType = onmsNode.getAssetRecord().getVmwareManagedEntityType(); String vmwareManagedObjectId = onmsNode.getForeignId(); TimeoutTracker tracker = new TimeoutTracker(parameters, DEFAULT_RETRY, DEFAULT_TIMEOUT); PollStatus serviceStatus = PollStatus.unknown(); for (tracker.reset(); tracker.shouldRetry() && !serviceStatus.isAvailable(); tracker.nextAttempt()) { VmwareViJavaAccess vmwareViJavaAccess = null; try { vmwareViJavaAccess = new VmwareViJavaAccess(vmwareManagementServer); } catch (MarshalException e) { logger.warn( "Error initialising VMware connection to '{}': '{}'", vmwareManagementServer, e.getMessage()); return PollStatus.unavailable( "Error initialising VMware connection to '" + vmwareManagementServer + "'"); } catch (ValidationException e) { logger.warn( "Error initialising VMware connection to '{}': '{}'", vmwareManagementServer, e.getMessage()); return PollStatus.unavailable( "Error initialising VMware connection to '" + vmwareManagementServer + "'"); } catch (IOException e) { logger.warn( "Error initialising VMware connection to '{}': '{}'", vmwareManagementServer, e.getMessage()); return PollStatus.unavailable( "Error initialising VMware connection to '" + vmwareManagementServer + "'"); } try { vmwareViJavaAccess.connect(); } catch (MalformedURLException e) { logger.warn( "Error connecting VMware management server '{}': '{}'", vmwareManagementServer, e.getMessage()); return PollStatus.unavailable( "Error connecting VMware management server '" + vmwareManagementServer + "'"); } catch (RemoteException e) { logger.warn( "Error connecting VMware management server '{}': '{}'", vmwareManagementServer, e.getMessage()); return PollStatus.unavailable( "Error connecting VMware management server '" + vmwareManagementServer + "'"); } if (!vmwareViJavaAccess.setTimeout(tracker.getConnectionTimeout())) { logger.warn( "Error setting connection timeout for VMware management server '{}'", vmwareManagementServer); } String powerState = "unknown"; if ("HostSystem".equals(vmwareManagedEntityType)) { HostSystem hostSystem = vmwareViJavaAccess.getHostSystemByManagedObjectId(vmwareManagedObjectId); if (hostSystem == null) { return PollStatus.unknown("hostSystem=null"); } else { HostRuntimeInfo hostRuntimeInfo = hostSystem.getRuntime(); if (hostRuntimeInfo == null) { return PollStatus.unknown("hostRuntimeInfo=null"); } else { HostSystemPowerState hostSystemPowerState = hostRuntimeInfo.getPowerState(); if (hostSystemPowerState == null) { return PollStatus.unknown("hostSystemPowerState=null"); } else { powerState = hostSystemPowerState.toString(); } } } } else { if ("VirtualMachine".equals(vmwareManagedEntityType)) { VirtualMachine virtualMachine = vmwareViJavaAccess.getVirtualMachineByManagedObjectId(vmwareManagedObjectId); if (virtualMachine == null) { return PollStatus.unknown("virtualMachine=null"); } else { VirtualMachineRuntimeInfo virtualMachineRuntimeInfo = virtualMachine.getRuntime(); if (virtualMachineRuntimeInfo == null) { return PollStatus.unknown("virtualMachineRuntimeInfo=null"); } else { VirtualMachinePowerState virtualMachinePowerState = virtualMachineRuntimeInfo.getPowerState(); if (virtualMachinePowerState == null) { return PollStatus.unknown("virtualMachinePowerState=null"); } else { powerState = virtualMachinePowerState.toString(); } } } } else { logger.warn( "Error getting '{}' for '{}'", vmwareManagedEntityType, vmwareManagedObjectId); vmwareViJavaAccess.disconnect(); return serviceStatus; } } if ("poweredOn".equals(powerState)) { serviceStatus = PollStatus.available(); } else { serviceStatus = PollStatus.unavailable("The system's state is '" + powerState + "'"); } vmwareViJavaAccess.disconnect(); } return serviceStatus; }
public static boolean pingVhost(HostSystem vhost) throws Exception { String ip = vhost.getConfig().getNetwork().getVnic()[0].getSpec().getIp().getIpAddress(); return pingByIP(ip); }
@Override public void run() { try { while (true) { URL url = new URL(SJSULabConfig.getvCenterURL()); try { ServiceInstance si = new ServiceInstance( url, SJSULabConfig.getvCenterUsername(), SJSULabConfig.getPassword(), true); HostSystem host = (HostSystem) new InventoryNavigator(si.getRootFolder()) .searchManagedEntity("HostSystem", ip); // System.out.println("host value" + host); PerformanceManager perfMgr = si.getPerformanceManager(); PerfProviderSummary summary = perfMgr.queryPerfProviderSummary(host); // vm int perfInterval = summary.getRefreshRate(); PerfMetricId[] queryAvailablePerfMetric = perfMgr.queryAvailablePerfMetric(host, null, null, perfInterval); PerfCounterInfo[] pci = perfMgr.getPerfCounter(); ArrayList<PerfMetricId> list = new ArrayList<PerfMetricId>(); for (int i2 = 0; i2 < queryAvailablePerfMetric.length; i2++) { PerfMetricId perfMetricId = queryAvailablePerfMetric[i2]; if (SELECTED_COUNTER_ID == perfMetricId.getCounterId()) { list.add(perfMetricId); } } PerfMetricId[] pmis = list.toArray(new PerfMetricId[list.size()]); PerfQuerySpec qSpec = new PerfQuerySpec(); qSpec.setEntity(host.getMOR()); qSpec.setMetricId(pmis); qSpec.intervalId = perfInterval; PerfEntityMetricBase[] pembs = perfMgr.queryPerf(new PerfQuerySpec[] {qSpec}); for (int i = 0; pembs != null && i < pembs.length; i++) { PerfEntityMetricBase val = pembs[i]; PerfEntityMetric pem = (PerfEntityMetric) val; PerfMetricSeries[] vals = pem.getValue(); PerfSampleInfo[] infos = pem.getSampleInfo(); Date date1 = new Date(); SimpleDateFormat sdf = new SimpleDateFormat("MM-dd-yyyy h:mm:ss"); String formattedDate = sdf.format(date1); infoList.put(aName[counter], formattedDate); for (int j = 0; vals != null && j < vals.length; ++j) { PerfMetricIntSeries val1 = (PerfMetricIntSeries) vals[j]; long[] longs = val1.getValue(); System.out.println("Host CPU :" + longs[5]); infoList.put(aName[0], String.valueOf(longs[5])); /* for (int k : a) { infoList.put(aName[counter+1], String.valueOf(longs[k])); counter++; } counter = 0; */ } } si.getServerConnection().logout(); } catch (InvalidProperty e) { e.printStackTrace(); } catch (RuntimeFault e) { e.printStackTrace(); } catch (RemoteException e) { e.printStackTrace(); } catch (MalformedURLException e) { e.printStackTrace(); } // infoList.put("vmIP", ip); counter = 0; try { StringBuilder sb = new StringBuilder(); sb.append("vmname:" + ip + ","); int countTest = 0; for (String str : aName) { sb.append(aName[countTest] + ":" + infoList.get(str).toString() + ","); countTest++; } String out = sb.toString(); out = out.substring(0, out.length() - 1); writer.write(out + "\n"); System.out.println(out); } catch (Exception e) { e.printStackTrace(); } Thread.sleep(5000); } } catch (Exception e) { e.printStackTrace(); } }