Search in sources :

Example 21 with ManagedEntity

use of com.vmware.vim25.mo.ManagedEntity in project opennms by OpenNMS.

the class VmwareImporter method iterateVirtualMachines.

/**
 * Iterates through the virtual machines and adds them to the requisition object.
 *
 * @param vmwareViJavaAccess the access/connection to use
 */
private void iterateVirtualMachines(VmwareViJavaAccess vmwareViJavaAccess, int apiVersion) {
    ManagedEntity[] managedEntities = null;
    logger.debug("Starting to iterate Virtual Machines on VMware host {} ...", request.getHostname());
    try {
        managedEntities = vmwareViJavaAccess.searchManagedEntities("VirtualMachine");
    } catch (RemoteException e) {
        logger.error("Error iterating Virtual Machines on VMware host {}", request.getHostname());
        logger.error("Exception thrown while iterating for Virtual Machines: ", e);
    }
    if (managedEntities != null) {
        final ExecutorService executor = Executors.newFixedThreadPool(Math.min(managedEntities.length, 10));
        final List<CompletableFuture<Optional<RequisitionNode>>> completableFutures = Arrays.stream(managedEntities).map(managedEntity -> (VirtualMachine) managedEntity).filter(virtualMachine -> checkVMPowerState(virtualMachine)).filter(virtualMachine -> checkForAttribute(virtualMachine)).map(virtualMachine -> CompletableFuture.supplyAsync(() -> {
            logger.debug("Adding Virtual Machine '{}' (ID: {})", virtualMachine.getName(), virtualMachine.getMOR().getVal());
            TreeSet<String> ipAddresses = vmwareViJavaAccess.getVirtualMachineIpAddresses(virtualMachine);
            logger.debug("Found {} IP addresses for Virtual Machine '{}' (ID: {}): {}", ipAddresses.size(), virtualMachine.getName(), virtualMachine.getMOR().getVal(), ipAddresses);
            RequisitionNode node = createRequisitionNode(ipAddresses, virtualMachine, apiVersion, vmwareViJavaAccess);
            if (virtualMachine.getGuest().getGuestFullName() != null) {
                node.putAsset(new RequisitionAsset("operatingSystem", virtualMachine.getGuest().getGuestFullName()));
            }
            try {
                node.putAsset(new RequisitionAsset("cpu", virtualMachine.getConfig().getHardware().getNumCPU() + " vCPU"));
            } catch (Exception e) {
                logger.debug("Can't find CPU information for {} (ID: {})", virtualMachine.getName(), virtualMachine.getMOR().getVal());
            }
            try {
                node.putAsset(new RequisitionAsset("ram", virtualMachine.getConfig().getHardware().getMemoryMB() + " MB"));
            } catch (Exception e) {
                logger.debug("Can't find Memory information for {} (ID: {})", virtualMachine.getName(), virtualMachine.getMOR().getVal());
            }
            return request.isPersistVMs() ? Optional.of(node) : Optional.<RequisitionNode>empty();
        }, executor)).collect(Collectors.toList());
        completableFutures.stream().map(CompletableFuture::join).filter(Optional::isPresent).forEach(m -> {
            synchronized (m_requisition) {
                m_requisition.insertNode(m.get());
            }
        });
        executor.shutdown();
    }
}
Also used : ManagedEntity(com.vmware.vim25.mo.ManagedEntity) Arrays(java.util.Arrays) StringUtils(org.apache.commons.lang.StringUtils) HostSystem(com.vmware.vim25.mo.HostSystem) LoggerFactory(org.slf4j.LoggerFactory) InetAddress(java.net.InetAddress) CIMException(org.sblim.wbem.cim.CIMException) Requisition(org.opennms.netmgt.provision.persist.requisition.Requisition) Map(java.util.Map) HostSystemPowerState(com.vmware.vim25.HostSystemPowerState) DistributedVirtualPortgroup(com.vmware.vim25.mo.DistributedVirtualPortgroup) CIMObject(org.sblim.wbem.cim.CIMObject) HostRuntimeInfo(com.vmware.vim25.HostRuntimeInfo) VmwareViJavaAccess(org.opennms.protocols.vmware.VmwareViJavaAccess) VirtualMachinePowerState(com.vmware.vim25.VirtualMachinePowerState) Set(java.util.Set) Collectors(java.util.stream.Collectors) StandardCharsets(java.nio.charset.StandardCharsets) Executors(java.util.concurrent.Executors) RemoteException(java.rmi.RemoteException) Objects(java.util.Objects) List(java.util.List) RequisitionCategory(org.opennms.netmgt.provision.persist.requisition.RequisitionCategory) CustomFieldStringValue(com.vmware.vim25.CustomFieldStringValue) VirtualMachine(com.vmware.vim25.mo.VirtualMachine) RequisitionNode(org.opennms.netmgt.provision.persist.requisition.RequisitionNode) Optional(java.util.Optional) Network(com.vmware.vim25.mo.Network) UnsupportedEncodingException(java.io.UnsupportedEncodingException) RequisitionAsset(org.opennms.netmgt.provision.persist.requisition.RequisitionAsset) Datastore(com.vmware.vim25.mo.Datastore) RequisitionMonitoredService(org.opennms.netmgt.provision.persist.requisition.RequisitionMonitoredService) HashMap(java.util.HashMap) CompletableFuture(java.util.concurrent.CompletableFuture) RequisitionInterface(org.opennms.netmgt.provision.persist.requisition.RequisitionInterface) TreeSet(java.util.TreeSet) ArrayList(java.util.ArrayList) ManagedEntity(com.vmware.vim25.mo.ManagedEntity) VirtualMachineRuntimeInfo(com.vmware.vim25.VirtualMachineRuntimeInfo) PrimaryType(org.opennms.netmgt.model.PrimaryType) ConnectException(java.net.ConnectException) ExecutorService(java.util.concurrent.ExecutorService) Logger(org.slf4j.Logger) MalformedURLException(java.net.MalformedURLException) IOException(java.io.IOException) UnknownHostException(java.net.UnknownHostException) CustomFieldDef(com.vmware.vim25.CustomFieldDef) URLEncoder(java.net.URLEncoder) TreeMap(java.util.TreeMap) CustomFieldValue(com.vmware.vim25.CustomFieldValue) InetAddressUtils(org.apache.http.conn.util.InetAddressUtils) RequisitionNode(org.opennms.netmgt.provision.persist.requisition.RequisitionNode) CompletableFuture(java.util.concurrent.CompletableFuture) ExecutorService(java.util.concurrent.ExecutorService) RemoteException(java.rmi.RemoteException) RequisitionAsset(org.opennms.netmgt.provision.persist.requisition.RequisitionAsset) CIMException(org.sblim.wbem.cim.CIMException) RemoteException(java.rmi.RemoteException) UnsupportedEncodingException(java.io.UnsupportedEncodingException) ConnectException(java.net.ConnectException) MalformedURLException(java.net.MalformedURLException) IOException(java.io.IOException) UnknownHostException(java.net.UnknownHostException)

Example 22 with ManagedEntity

use of com.vmware.vim25.mo.ManagedEntity in project opennms by OpenNMS.

the class VmwareCimQuery method cimQuery.

private static void cimQuery(String hostname, String username, String password) {
    System.out.print("Trying to connect to " + hostname + "... ");
    VmwareViJavaAccess vmwareViJavaAccess = new VmwareViJavaAccess(hostname, username, password);
    try {
        vmwareViJavaAccess.connect();
    } catch (MalformedURLException e) {
        System.out.println("Exception:");
        e.printStackTrace();
        return;
    } catch (RemoteException e) {
        System.out.println("Exception:");
        e.printStackTrace();
        return;
    }
    System.out.println("Success!");
    ManagedEntity[] hostSystems;
    System.out.print(" Querying " + hostname + " for host systems... ");
    try {
        hostSystems = vmwareViJavaAccess.searchManagedEntities("HostSystem");
    } catch (RemoteException remoteException) {
        remoteException.printStackTrace();
        vmwareViJavaAccess.disconnect();
        return;
    }
    if (hostSystems != null) {
        System.out.println(hostSystems.length + " host system(s) found!");
        for (ManagedEntity managedEntity : hostSystems) {
            HostSystem hostSystem = (HostSystem) managedEntity;
            if (hostSystem.getSummary() != null) {
                if (hostSystem.getRuntime() != null) {
                    String powerState = hostSystem.getRuntime().getPowerState().toString();
                    if (!"poweredOn".equals(powerState)) {
                        System.out.println("  Ignoring host system " + hostSystem.getName() + " (powerState=" + powerState + ")... ");
                        continue;
                    } else {
                        System.out.print("  Determining primary Ip address of host system " + hostSystem.getName() + " (powerState=" + powerState + ")... ");
                    }
                } else {
                    System.out.println("  Ignoring host system " + hostSystem.getName() + " (powerState=unknown)... ");
                    continue;
                }
            } else {
                System.out.println("  Ignoring host system " + hostSystem.getName() + " (powerState=unknown)... ");
                continue;
            }
            String ipAddress;
            ipAddress = vmwareViJavaAccess.getPrimaryHostSystemIpAddress(hostSystem);
            if (ipAddress != null) {
                System.out.print(ipAddress + "\n  Querying host system " + hostSystem.getName() + " for numeric sensors... ");
                List<CIMObject> cimObjects;
                try {
                    cimObjects = vmwareViJavaAccess.queryCimObjects(hostSystem, "CIM_NumericSensor");
                } catch (Exception e) {
                    System.out.println("Exception:");
                    e.printStackTrace();
                    continue;
                }
                if (cimObjects != null) {
                    // FIXME queryCimObjects returns an empty list or a filled list, but never null
                    System.out.println(cimObjects.size() + " sensor(s) found!");
                    for (CIMObject cimObject : cimObjects) {
                        String healthState = vmwareViJavaAccess.getPropertyOfCimObject(cimObject, "HealthState");
                        String cimObjectName = vmwareViJavaAccess.getPropertyOfCimObject(cimObject, "Name");
                        System.out.print("   " + cimObjectName);
                        if (healthState != null) {
                            System.out.println(" " + m_healthStates.get(Integer.valueOf(healthState)));
                        } else {
                            System.out.println();
                        }
                    }
                } else {
                    System.out.println("NULL - aborting...");
                    continue;
                }
            } else {
                System.out.println("NULL - aborting...");
                continue;
            }
        }
    } else {
        System.out.println("NULL - aborting...");
    }
    System.out.println("Cleaning up...");
    vmwareViJavaAccess.disconnect();
}
Also used : ManagedEntity(com.vmware.vim25.mo.ManagedEntity) MalformedURLException(java.net.MalformedURLException) CIMObject(org.sblim.wbem.cim.CIMObject) HostSystem(com.vmware.vim25.mo.HostSystem) RemoteException(java.rmi.RemoteException) MalformedURLException(java.net.MalformedURLException) RemoteException(java.rmi.RemoteException) ParseException(org.apache.commons.cli.ParseException)

Example 23 with ManagedEntity

use of com.vmware.vim25.mo.ManagedEntity in project opennms by OpenNMS.

the class VmwareConfigBuilder method generateData.

private void generateData(String rrdRepository) throws Exception {
    serviceInstance = new ServiceInstance(new URL("https://" + hostname + "/sdk"), username, password);
    performanceManager = serviceInstance.getPerformanceManager();
    PerfCounterInfo[] perfCounterInfos = performanceManager.getPerfCounter();
    for (PerfCounterInfo perfCounterInfo : perfCounterInfos) {
        perfCounterInfoMap.put(perfCounterInfo.getKey(), perfCounterInfo);
    }
    System.out.println("Generating configuration files for '" + serviceInstance.getAboutInfo().getFullName() + "' using rrdRepository '" + rrdRepository + "'...");
    final StringBuilder buffer = new StringBuilder();
    buffer.append("Configuration file generated for:\n\n");
    buffer.append("Full name.......: " + serviceInstance.getAboutInfo().getFullName() + "\n");
    buffer.append("API type........: " + serviceInstance.getAboutInfo().getApiType() + "\n");
    buffer.append("API version.....: " + serviceInstance.getAboutInfo().getApiVersion() + "\n");
    buffer.append("Product name....: " + serviceInstance.getAboutInfo().getLicenseProductName() + "\n");
    buffer.append("Product version.: " + serviceInstance.getAboutInfo().getLicenseProductVersion() + "\n");
    buffer.append("OS type.........: " + serviceInstance.getAboutInfo().getOsType() + "\n");
    versionInformation = buffer.toString();
    String[] arr = serviceInstance.getAboutInfo().getApiVersion().split("\\.");
    if (arr.length > 1) {
        apiVersion = arr[0];
        if (Integer.valueOf(apiVersion) < 4) {
            apiVersion = "3";
        }
    }
    ManagedEntity[] hostSystems, virtualMachines;
    virtualMachines = new InventoryNavigator(serviceInstance.getRootFolder()).searchManagedEntities("VirtualMachine");
    if (virtualMachines != null) {
        if (virtualMachines.length > 0) {
            for (ManagedEntity managedEntity : virtualMachines) {
                if ("poweredOn".equals(((VirtualMachine) managedEntity).getRuntime().getPowerState().toString())) {
                    lookupMetrics("default-VirtualMachine" + apiVersion, managedEntity.getMOR().getVal());
                    break;
                }
            }
        } else {
            System.err.println("No virtual machines found");
        }
    }
    hostSystems = new InventoryNavigator(serviceInstance.getRootFolder()).searchManagedEntities("HostSystem");
    if (hostSystems != null) {
        if (hostSystems.length > 0) {
            for (ManagedEntity managedEntity : hostSystems) {
                if ("poweredOn".equals(((HostSystem) managedEntity).getRuntime().getPowerState().toString())) {
                    lookupMetrics("default-HostSystem" + apiVersion, managedEntity.getMOR().getVal());
                    break;
                }
            }
        } else {
            System.err.println("No host systems found!");
        }
    }
    saveVMwareDatacollectionConfig(rrdRepository);
    saveVMwareDatacollectionInclude();
    saveVMwareGraphProperties();
}
Also used : ManagedEntity(com.vmware.vim25.mo.ManagedEntity) PerfCounterInfo(com.vmware.vim25.PerfCounterInfo) ServiceInstance(com.vmware.vim25.mo.ServiceInstance) URL(java.net.URL) InventoryNavigator(com.vmware.vim25.mo.InventoryNavigator)

Example 24 with ManagedEntity

use of com.vmware.vim25.mo.ManagedEntity in project opennms by OpenNMS.

the class VmwareViJavaAccess method queryPerformanceValues.

/**
 * This method queries performance values for a given managed entity.
 *
 * @param managedEntity the managed entity to query
 * @return the perfomance values
 * @throws RemoteException
 */
public VmwarePerformanceValues queryPerformanceValues(ManagedEntity managedEntity) throws RemoteException {
    VmwarePerformanceValues vmwarePerformanceValues = new VmwarePerformanceValues();
    int refreshRate = getPerformanceManager().queryPerfProviderSummary(managedEntity).getRefreshRate();
    PerfQuerySpec perfQuerySpec = new PerfQuerySpec();
    perfQuerySpec.setEntity(managedEntity.getMOR());
    perfQuerySpec.setMaxSample(Integer.valueOf(1));
    perfQuerySpec.setIntervalId(refreshRate);
    PerfEntityMetricBase[] perfEntityMetricBases = getPerformanceManager().queryPerf(new PerfQuerySpec[] { perfQuerySpec });
    if (perfEntityMetricBases != null) {
        for (int i = 0; i < perfEntityMetricBases.length; i++) {
            PerfMetricSeries[] perfMetricSeries = ((PerfEntityMetric) perfEntityMetricBases[i]).getValue();
            for (int j = 0; perfMetricSeries != null && j < perfMetricSeries.length; j++) {
                if (perfMetricSeries[j] instanceof PerfMetricIntSeries) {
                    long[] longs = ((PerfMetricIntSeries) perfMetricSeries[j]).getValue();
                    if (longs.length == 1) {
                        PerfCounterInfo perfCounterInfo = getPerfCounterInfoMap().get(perfMetricSeries[j].getId().getCounterId());
                        String instance = perfMetricSeries[j].getId().getInstance();
                        String name = getHumanReadableName(perfCounterInfo);
                        if (instance != null && !"".equals(instance)) {
                            vmwarePerformanceValues.addValue(name, instance, longs[0]);
                        } else {
                            vmwarePerformanceValues.addValue(name, longs[0]);
                        }
                    }
                }
            }
        }
    }
    return vmwarePerformanceValues;
}
Also used : PerfMetricIntSeries(com.vmware.vim25.PerfMetricIntSeries) PerfCounterInfo(com.vmware.vim25.PerfCounterInfo) PerfMetricSeries(com.vmware.vim25.PerfMetricSeries) VmwarePerformanceValues(org.opennms.netmgt.collectd.vmware.vijava.VmwarePerformanceValues) PerfQuerySpec(com.vmware.vim25.PerfQuerySpec) PerfEntityMetricBase(com.vmware.vim25.PerfEntityMetricBase) PerfEntityMetric(com.vmware.vim25.PerfEntityMetric)

Example 25 with ManagedEntity

use of com.vmware.vim25.mo.ManagedEntity in project opennms by OpenNMS.

the class VmwareViJavaAccess method getManagedEntityByManagedObjectId.

/**
 * Returns a managed entitiy for a given managed object Id.
 *
 * @param managedObjectId the managed object Id
 * @return the managed entity
 */
public ManagedEntity getManagedEntityByManagedObjectId(String managedObjectId) {
    ManagedObjectReference managedObjectReference = new ManagedObjectReference();
    managedObjectReference.setType("ManagedEntity");
    managedObjectReference.setVal(managedObjectId);
    ManagedEntity managedEntity = MorUtil.createExactManagedEntity(m_serviceInstance.getServerConnection(), managedObjectReference);
    return managedEntity;
}
Also used : ManagedEntity(com.vmware.vim25.mo.ManagedEntity) ManagedObjectReference(com.vmware.vim25.ManagedObjectReference)

Aggregations

ManagedEntity (com.vmware.vim25.mo.ManagedEntity)24 RemoteException (java.rmi.RemoteException)14 InventoryNavigator (com.vmware.vim25.mo.InventoryNavigator)12 MalformedURLException (java.net.MalformedURLException)10 HostSystem (com.vmware.vim25.mo.HostSystem)7 VirtualMachine (com.vmware.vim25.mo.VirtualMachine)6 ManagedObjectReference (com.vmware.vim25.ManagedObjectReference)5 ObjectSpec (com.vmware.vim25.ObjectSpec)5 PerfCounterInfo (com.vmware.vim25.PerfCounterInfo)5 PropertyFilterSpec (com.vmware.vim25.PropertyFilterSpec)5 PropertySpec (com.vmware.vim25.PropertySpec)5 TraversalSpec (com.vmware.vim25.TraversalSpec)5 Datastore (com.vmware.vim25.mo.Datastore)5 ArrayList (java.util.ArrayList)5 VcenterObjectConnectionException (com.emc.storageos.vcentercontroller.exceptions.VcenterObjectConnectionException)4 VcenterObjectNotFoundException (com.emc.storageos.vcentercontroller.exceptions.VcenterObjectNotFoundException)4 VcenterServerConnectionException (com.emc.storageos.vcentercontroller.exceptions.VcenterServerConnectionException)4 VcenterSystemException (com.emc.storageos.vcentercontroller.exceptions.VcenterSystemException)4 ObjectContent (com.vmware.vim25.ObjectContent)4 SelectionSpec (com.vmware.vim25.SelectionSpec)4