package com.test.performance.data; import java.security.KeyManagementException; import java.security.NoSuchAlgorithmException; import java.security.cert.CertificateException; import java.security.cert.X509Certificate; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import javax.net.ssl.HostnameVerifier; import javax.net.ssl.HttpsURLConnection; import javax.net.ssl.SSLSession; import javax.net.ssl.TrustManager; import javax.net.ssl.X509TrustManager; import javax.xml.ws.BindingProvider; import com.vmware.vim25.ArrayOfPerfCounterInfo; import com.vmware.vim25.DynamicProperty; import com.vmware.vim25.InvalidLocaleFaultMsg; import com.vmware.vim25.InvalidLoginFaultMsg; import com.vmware.vim25.ManagedObjectReference; import com.vmware.vim25.ObjectContent; import com.vmware.vim25.ObjectSpec; import com.vmware.vim25.PerfCounterInfo; import com.vmware.vim25.PerfEntityMetric; import com.vmware.vim25.PerfEntityMetricBase; import com.vmware.vim25.PerfMetricId; import com.vmware.vim25.PerfMetricIntSeries; import com.vmware.vim25.PerfMetricSeries; import com.vmware.vim25.PerfQuerySpec; import com.vmware.vim25.PerfSampleInfo; import com.vmware.vim25.PerfStatsType; import com.vmware.vim25.PerfSummaryType; import com.vmware.vim25.PropertyFilterSpec; import com.vmware.vim25.PropertySpec; import com.vmware.vim25.RetrieveOptions; import com.vmware.vim25.RetrieveResult; import com.vmware.vim25.RuntimeFaultFaultMsg; import com.vmware.vim25.ServiceContent; import com.vmware.vim25.UserSession; import com.vmware.vim25.VimPortType; import com.vmware.vim25.VimService; public class TestPerformanceData { public static UserSession session = null; public static ServiceContent serviceContent = null; public ManagedObjectReference rootFolder; public ManagedObjectReference perfManager; public ManagedObjectReference propCollector; public void setServiceContent(ServiceContent serviceContent) { this.serviceContent = serviceContent; } public static VimPortType vimport = null; public static VimService vimservice = null; public static ManagedObjectReference serviceInstance = new ManagedObjectReference(); private void trustAllHttpsCertificates() throws NoSuchAlgorithmException, KeyManagementException { TrustManager[] trustAllCerts = new TrustManager[1]; TrustManager tm = new TrustAllTrustManager(); trustAllCerts[0] = tm; javax.net.ssl.SSLContext sc = javax.net.ssl.SSLContext.getInstance("SSL"); javax.net.ssl.SSLSessionContext sslsc = sc.getServerSessionContext(); sslsc.setSessionTimeout(0); sc.init(null, trustAllCerts, new java.security.SecureRandom()); HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier() { public boolean verify(String arg0, SSLSession arg1) { return true; } }); HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory()); } public void loginCheck(String vCenterIp, String vcenterUsername, String vcenterPassword) throws InvalidLoginFaultMsg { vimservice = new VimService(); serviceInstance.setType("ServiceInstance"); serviceInstance.setValue("ServiceInstance"); vimport = vimservice.getVimPort(); final String methodName = "loginCheck"; try { trustAllHttpsCertificates(); Map ctxt = ((BindingProvider) vimport).getRequestContext(); String urlString = "https://" + vCenterIp + "/sdk/vimService"; ctxt.put(BindingProvider.ENDPOINT_ADDRESS_PROPERTY, urlString); ctxt.put(BindingProvider.SESSION_MAINTAIN_PROPERTY, true); setServiceContent(vimport.retrieveServiceContent(serviceInstance)); session = vimport.login(serviceContent.getSessionManager(), vcenterUsername, vcenterPassword, null); } catch (RuntimeFaultFaultMsg e) { System.out.println(methodName + " RuntimeFaultFaultMsg Exception " + e.getMessage() + e); } catch (InvalidLocaleFaultMsg | KeyManagementException | NoSuchAlgorithmException e) { System.out.println("Username or Password is not correct."); System.out.println(e); } catch (InvalidLoginFaultMsg e) { System.out.println(e); throw e; } } public void setVariables() { rootFolder = serviceContent.getRootFolder(); perfManager = serviceContent.getPerfManager(); propCollector = serviceContent.getPropertyCollector(); } private class TrustAllTrustManager implements TrustManager, X509TrustManager { @Override public void checkClientTrusted(X509Certificate[] xcs, String string) throws CertificateException { } @Override public void checkServerTrusted(X509Certificate[] xcs, String string) throws CertificateException { } @Override public X509Certificate[] getAcceptedIssuers() { return null; } } Map>> pci = new HashMap>>(); String interval = "300"; int duration = 20; /** * Uses the new RetrievePropertiesEx method to emulate the now deprecated * RetrieveProperties method. * * @param listpfs * @return list of object content * @throws Exception */ List retrievePropertiesAllObjects(List listpfs) throws Exception { RetrieveOptions propObjectRetrieveOpts = new RetrieveOptions(); List listobjcontent = new ArrayList(); RetrieveResult rslts = vimport.retrievePropertiesEx(propCollector, listpfs, propObjectRetrieveOpts); if (rslts != null && rslts.getObjects() != null && !rslts.getObjects().isEmpty()) { listobjcontent.addAll(rslts.getObjects()); } String token = null; if (rslts != null && rslts.getToken() != null) { token = rslts.getToken(); } while (token != null && !token.isEmpty()) { rslts = vimport.continueRetrievePropertiesEx(propCollector, token); token = null; if (rslts != null) { token = rslts.getToken(); if (rslts.getObjects() != null && !rslts.getObjects().isEmpty()) { listobjcontent.addAll(rslts.getObjects()); } } } return listobjcontent; } /** * This method initializes all the performance counters available on the * system it is connected to. The performance counters are stored in the * hashmap counters with group.counter.rolluptype being the key and id being * the value. */ List getPerfCounters() throws Exception { List pciArr = null; // Create Property Spec PropertySpec propertySpec = new PropertySpec(); propertySpec.setAll(Boolean.FALSE); propertySpec.getPathSet().add("perfCounter"); propertySpec.setType("PerformanceManager"); List propertySpecs = new ArrayList(); propertySpecs.add(propertySpec); // Now create Object Spec ObjectSpec objectSpec = new ObjectSpec(); objectSpec.setObj(perfManager); List objectSpecs = new ArrayList(); objectSpecs.add(objectSpec); // Create PropertyFilterSpec using the PropertySpec and ObjectPec // created above. PropertyFilterSpec propertyFilterSpec = new PropertyFilterSpec(); propertyFilterSpec.getPropSet().add(propertySpec); propertyFilterSpec.getObjectSet().add(objectSpec); List propertyFilterSpecs = new ArrayList(); propertyFilterSpecs.add(propertyFilterSpec); List listpfs = new ArrayList(1); listpfs.add(propertyFilterSpec); List listocont = retrievePropertiesAllObjects(listpfs); if (listocont != null) { for (ObjectContent oc : listocont) { List dps = oc.getPropSet(); if (dps != null) { for (DynamicProperty dp : dps) { List pcinfolist = ((ArrayOfPerfCounterInfo) dp.getVal()).getPerfCounterInfo(); pciArr = pcinfolist; } } } } return pciArr; } void counterInfo(ManagedObjectReference pmRef) throws Exception { List cInfos = getPerfCounters(); for (int i = 0; i < cInfos.size(); ++i) { PerfCounterInfo cInfo = cInfos.get(i); String group = cInfo.getGroupInfo().getKey(); Map> nameMap = null; if (!pci.containsKey(group)) { nameMap = new HashMap>(); pci.put(group, nameMap); } else { nameMap = pci.get(group); } String name = cInfo.getNameInfo().getKey(); ArrayList counters = null; if (!nameMap.containsKey(name)) { counters = new ArrayList(); nameMap.put(name, counters); } else { counters = nameMap.get(name); } counters.add(cInfo); } } ArrayList getCounterInfos(String groupName, String counterName) { Map> nameMap = pci.get(groupName); if (nameMap != null) { ArrayList ret = nameMap.get(counterName); if (ret != null) { return ret; } } return null; } PerfCounterInfo getCounterInfo(String groupName, String counterName, PerfSummaryType rollupType, PerfStatsType statsType) { ArrayList counters = getCounterInfos(groupName, counterName); if (counters != null) { for (Iterator i = counters.iterator(); i.hasNext(); ) { PerfCounterInfo pci = (PerfCounterInfo) i.next(); if ((statsType == null || statsType.equals(pci.getStatsType())) && (rollupType == null || rollupType .equals(pci.getRollupType()))) { return pci; } } } return null; } void displayValues(List values, PerfCounterInfo pci, PerfMetricId pmid, Integer inter) { for (int i = 0; i < values.size(); ++i) { List listperfmetser = ((PerfEntityMetric) values.get(i)).getValue(); List listperfsinfo = ((PerfEntityMetric) values.get(i)).getSampleInfo(); if (listperfsinfo == null || listperfsinfo.size() == 0) { System.out.println("No Samples available. Continuing."); continue; } System.out.println( "Sample time range: " + listperfsinfo.get(0).getTimestamp().toGregorianCalendar().getTime().toString() + " - " + (listperfsinfo.get(listperfsinfo.size() - 1)).getTimestamp().toGregorianCalendar() .getTime().toString() + ", read every " + inter + " seconds"); for (int vi = 0; vi < listperfmetser.size(); ++vi) { if (pci != null) { if (pci.getKey() != listperfmetser.get(vi).getId().getCounterId()) { continue; } System.out.println(pci.getNameInfo().getSummary() + " - Instance: " + pmid.getInstance()); } if (listperfmetser.get(vi) instanceof PerfMetricIntSeries) { PerfMetricIntSeries val = (PerfMetricIntSeries) listperfmetser.get(vi); List listlongs = val.getValue(); for (int j = 0; j < listlongs.size(); j++) { System.out.println("timestamp: " + listperfsinfo.get(j).getTimestamp().toGregorianCalendar().getTime() + "\tvalue: " + listlongs.get(j)); } } } } } void displayHistory() throws Exception { counterInfo(perfManager); // String countername = "numberReadAveraged"; --> Working fine - Counter ID : 178 // String countername = "numberWriteAveraged"; --> Working fine - Counter ID : 179 // String countername = "read"; --> Working fine - Counter ID : 180 // String countername = "write"; --> Working fine - Counter ID : 181 // String countername = "totalReadLatency"; --> Not Working - Counter ID : 182 String countername = "totalWriteLatency"; // --> Not Working - Counter ID : 183 String groupname = "datastore"; PerfCounterInfo pci = getCounterInfo(groupname, countername, PerfSummaryType.AVERAGE, null); if (pci == null) { System.out.println("Incorrect Group Name and Countername specified"); } ManagedObjectReference datastoreMor = new ManagedObjectReference(); datastoreMor.setType("Datastore"); datastoreMor.setValue("datastore-316"); //here interval is set to 300 as we are fetching data of past day. List listprfmetid = vimport.queryAvailablePerfMetric(perfManager, datastoreMor, null, null, 300); // here we are unable to retrieve counter 182, 183 for any datastore. PerfMetricId ourCounter = null; for (int index = 0; index < listprfmetid.size(); ++index) { if (listprfmetid.get(index).getCounterId() == pci.getKey()) { ourCounter = listprfmetid.get(index); break; } } if (ourCounter == null) { System.out .println("No data on Host to collect. " + "Has it been running for at least " + duration + " minutes"); } else { PerfQuerySpec qSpec = new PerfQuerySpec(); List qSpecs = new ArrayList(); qSpec = new PerfQuerySpec(); qSpec.setEntity(datastoreMor); qSpec.getMetricId().addAll(Arrays.asList(new PerfMetricId[] { ourCounter })); qSpec.setIntervalId(Integer.valueOf(300)); qSpecs.add(qSpec); List alpqs = new ArrayList(1); alpqs.add(qSpec); List listpemb = vimport.queryPerf(perfManager, alpqs); if (listpemb != null) { displayValues(listpemb, pci, ourCounter, Integer.valueOf(300)); } else { System.out.println("No Samples Found"); } } } public static void main(String args[]) throws Exception { TestPerformanceData testMetric = new TestPerformanceData(); testMetric.loginCheck("10.1.51.28", "administrator@vcp.local", "Test@123"); testMetric.setVariables(); testMetric.displayHistory(); } }