Search in sources :

Example 1 with WmiAgentConfig

use of org.opennms.netmgt.config.wmi.WmiAgentConfig in project opennms by OpenNMS.

the class WmiCollector method getRuntimeAttributes.

@Override
public Map<String, Object> getRuntimeAttributes(CollectionAgent agent, Map<String, Object> parameters) {
    final Map<String, Object> runtimeAttributes = new HashMap<>();
    final String collectionName = ParameterMap.getKeyedString(parameters, "collection", ParameterMap.getKeyedString(parameters, "wmi-collection", null));
    final WmiCollection collection = WmiDataCollectionConfigFactory.getInstance().getWmiCollection(collectionName);
    runtimeAttributes.put(WMI_COLLECTION_KEY, collection);
    final WmiAgentConfig agentConfig = WmiPeerFactory.getInstance().getAgentConfig(agent.getAddress());
    runtimeAttributes.put(WMI_AGENT_CONFIG_KEY, agentConfig);
    return runtimeAttributes;
}
Also used : HashMap(java.util.HashMap) WmiAgentConfig(org.opennms.netmgt.config.wmi.WmiAgentConfig) OnmsWbemObject(org.opennms.protocols.wmi.wbem.OnmsWbemObject) WmiCollection(org.opennms.netmgt.config.wmi.WmiCollection)

Example 2 with WmiAgentConfig

use of org.opennms.netmgt.config.wmi.WmiAgentConfig in project opennms by OpenNMS.

the class WmiCollector method collect.

/**
 * {@inheritDoc}
 */
@Override
public CollectionSet collect(final CollectionAgent agent, final Map<String, Object> parameters) {
    // Find attributes to collect - check groups in configuration. For each,
    // check scheduled nodes to see if that group should be collected
    final WmiCollection collection = (WmiCollection) parameters.get(WMI_COLLECTION_KEY);
    final WmiAgentConfig agentConfig = (WmiAgentConfig) parameters.get(WMI_AGENT_CONFIG_KEY);
    final WmiAgentState agentState = new WmiAgentState(agent.getAddress(), agentConfig, parameters);
    // Create a new collection set.
    CollectionSetBuilder builder = new CollectionSetBuilder(agent).withStatus(CollectionStatus.FAILED);
    if (collection.getWpms().size() < 1) {
        LOG.info("No groups to collect.");
        return builder.withStatus(CollectionStatus.SUCCEEDED).build();
    }
    final NodeLevelResource nodeResource = new NodeLevelResource(agent.getNodeId());
    // Iterate through the WMI collection groups.
    for (final Wpm wpm : collection.getWpms()) {
        // A wpm consists of a list of attributes, identified by name
        if (agentState.shouldCheckAvailability(wpm.getName(), wpm.getRecheckInterval())) {
            if (!isGroupAvailable(agentState, wpm)) {
                continue;
            }
        }
        if (agentState.groupIsAvailable(wpm.getName())) {
            WmiClient client = null;
            // Collect the data
            try {
                // Tell the agent to connect
                agentState.connect(wpm.getWmiNamespace());
                // And retrieve the client object for working.
                client = (WmiClient) agentState.getWmiClient();
                // Retrieve the WbemObjectSet from the class defined on the group.
                final OnmsWbemObjectSet wOS = client.performInstanceOf(wpm.getWmiClass());
                // If we received a WbemObjectSet result, lets go through it and collect it.
                if (wOS != null) {
                    // Go through each object (class instance) in the object set.
                    for (int i = 0; i < wOS.count(); i++) {
                        // Create a new collection resource.
                        Resource resource = null;
                        // Fetch our WBEM Object
                        final OnmsWbemObject obj = wOS.get(i);
                        // If this is multi-instance, fetch the instance name and store it.
                        if (wOS.count() > 1) {
                            // Fetch the value of the key value. e.g. Name.
                            final OnmsWbemProperty prop = obj.getWmiProperties().getByName(wpm.getKeyvalue());
                            final Object propVal = prop.getWmiValue();
                            String instance = null;
                            if (propVal instanceof String) {
                                instance = (String) propVal;
                            } else {
                                instance = propVal.toString();
                            }
                            resource = getWmiResource(agent, wpm.getResourceType(), nodeResource, instance);
                        } else {
                            resource = nodeResource;
                        }
                        for (final Attrib attrib : wpm.getAttribs()) {
                            final OnmsWbemProperty prop = obj.getWmiProperties().getByName(attrib.getWmiObject());
                            final AttributeType type = attrib.getType();
                            final String stringValue = prop.getWmiValue().toString();
                            if (type.isNumeric()) {
                                Double numericValue = Double.NaN;
                                try {
                                    numericValue = Double.parseDouble(stringValue);
                                } catch (NumberFormatException e) {
                                    LOG.warn("Value '{}' for attribute named '{}' cannot be converted to a number. Skipping.", prop.getWmiValue(), attrib.getName());
                                    continue;
                                }
                                builder.withNumericAttribute(resource, wpm.getName(), attrib.getAlias(), numericValue, type);
                            } else {
                                builder.withStringAttribute(resource, wpm.getName(), attrib.getAlias(), stringValue);
                            }
                        }
                    }
                }
                builder.withStatus(CollectionStatus.SUCCEEDED);
            } catch (final WmiException e) {
                LOG.info("unable to collect params for wpm '{}'", wpm.getName(), e);
            } finally {
                if (client != null) {
                    try {
                        client.disconnect();
                    } catch (final WmiException e) {
                        LOG.warn("An error occurred disconnecting while collecting from WMI.", e);
                    }
                }
            }
        }
    }
    return builder.build();
}
Also used : CollectionSetBuilder(org.opennms.netmgt.collection.support.builder.CollectionSetBuilder) WmiAgentConfig(org.opennms.netmgt.config.wmi.WmiAgentConfig) GenericTypeResource(org.opennms.netmgt.collection.support.builder.GenericTypeResource) Resource(org.opennms.netmgt.collection.support.builder.Resource) NodeLevelResource(org.opennms.netmgt.collection.support.builder.NodeLevelResource) OnmsWbemProperty(org.opennms.protocols.wmi.wbem.OnmsWbemProperty) NodeLevelResource(org.opennms.netmgt.collection.support.builder.NodeLevelResource) WmiCollection(org.opennms.netmgt.config.wmi.WmiCollection) Attrib(org.opennms.netmgt.config.wmi.Attrib) Wpm(org.opennms.netmgt.config.wmi.Wpm) WmiClient(org.opennms.protocols.wmi.WmiClient) AttributeType(org.opennms.netmgt.collection.api.AttributeType) OnmsWbemObject(org.opennms.protocols.wmi.wbem.OnmsWbemObject) WmiAgentState(org.opennms.netmgt.collectd.wmi.WmiAgentState) OnmsWbemObjectSet(org.opennms.protocols.wmi.wbem.OnmsWbemObjectSet) WmiException(org.opennms.protocols.wmi.WmiException) OnmsWbemObject(org.opennms.protocols.wmi.wbem.OnmsWbemObject)

Example 3 with WmiAgentConfig

use of org.opennms.netmgt.config.wmi.WmiAgentConfig in project opennms by OpenNMS.

the class WmiPeerFactory method getAgentConfig.

/**
 * <p>getAgentConfig</p>
 *
 * @param agentInetAddress a {@link java.net.InetAddress} object.
 * @return a {@link org.opennms.protocols.wmi.WmiAgentConfig} object.
 */
public synchronized WmiAgentConfig getAgentConfig(InetAddress agentInetAddress) {
    if (getConfig() == null) {
        return new WmiAgentConfig(agentInetAddress);
    }
    WmiAgentConfig agentConfig = new WmiAgentConfig(agentInetAddress);
    // Now set the defaults from the m_config
    setWmiAgentConfig(agentConfig, new Definition());
    // Attempt to locate the node
    // 
    Iterator<Definition> edef = getConfig().getDefinitions().iterator();
    DEFLOOP: while (edef.hasNext()) {
        Definition def = edef.next();
        // check the specifics first
        for (String saddr : def.getSpecifics()) {
            InetAddress addr = InetAddressUtils.addr(saddr);
            if (addr.equals(agentConfig.getAddress())) {
                setWmiAgentConfig(agentConfig, def);
                break DEFLOOP;
            }
        }
        // check the ranges
        for (Range rng : def.getRanges()) {
            if (InetAddressUtils.isInetAddressInRange(InetAddressUtils.str(agentConfig.getAddress()), rng.getBegin(), rng.getEnd())) {
                setWmiAgentConfig(agentConfig, def);
                break DEFLOOP;
            }
        }
        // 
        for (String ipMatch : def.getIpMatches()) {
            if (IPLike.matches(InetAddressUtils.str(agentInetAddress), ipMatch)) {
                setWmiAgentConfig(agentConfig, def);
                break DEFLOOP;
            }
        }
    }
    if (agentConfig == null) {
        Definition def = new Definition();
        setWmiAgentConfig(agentConfig, def);
    }
    return agentConfig;
}
Also used : WmiAgentConfig(org.opennms.netmgt.config.wmi.WmiAgentConfig) Definition(org.opennms.netmgt.config.wmi.agent.Definition) Range(org.opennms.netmgt.config.wmi.agent.Range) InetAddress(java.net.InetAddress)

Example 4 with WmiAgentConfig

use of org.opennms.netmgt.config.wmi.WmiAgentConfig in project opennms by OpenNMS.

the class WmiMonitor method poll.

/**
 * {@inheritDoc}
 *
 * Poll the specified address for service availability. During the poll an
 * attempt is made to connect the WMI agent on the specified host. If the
 * connection request is successful, the parameters are parsed and turned
 * into <code>WmiParams</code> and a check is performed against the
 * remote WMI service. If the <code>WmiManager</code> responds
 * with a <code>WmiResult</code> containing a result code of
 * <code>WmiResult.RES_STATE_OK</code> then we have determined that
 * we are talking to a valid service and we set the service status to
 * SERVICE_AVAILABLE and return.
 */
@Override
public PollStatus poll(final MonitoredService svc, final Map<String, Object> parameters) {
    // Holds the response reason.
    String reason = null;
    // Used to exit the retry loop early, if possible.
    int serviceStatus = PollStatus.SERVICE_UNAVAILABLE;
    // This will hold the data the server sends back.
    WmiResult response = null;
    // Used to track how long the request took.
    Double responseTime = null;
    final InetAddress ipAddr = svc.getAddress();
    final WmiAgentConfig agentConfig = WmiPeerFactory.getInstance().getAgentConfig(ipAddr);
    String matchType = DEFAULT_WMI_MATCH_TYPE;
    String compVal = DEFAULT_WMI_COMP_VAL;
    String compOp = DEFAULT_WMI_COMP_OP;
    String wmiClass = DEFAULT_WMI_CLASS;
    String wmiObject = DEFAULT_WMI_OBJECT;
    String wmiWqlStr = DEFAULT_WMI_WQL;
    String wmiNamespace = DEFAULT_WMI_NAMESPACE;
    if (parameters != null) {
        if (parameters.get("timeout") != null) {
            int timeout = ParameterMap.getKeyedInteger(parameters, "timeout", agentConfig.getTimeout());
            agentConfig.setTimeout(timeout);
        }
        if (parameters.get("retry") != null) {
            int retries = ParameterMap.getKeyedInteger(parameters, "retry", agentConfig.getRetries());
            agentConfig.setRetries(retries);
        }
        if (parameters.get("username") != null) {
            String user = ParameterMap.getKeyedString(parameters, "username", agentConfig.getUsername());
            agentConfig.setUsername(user);
        }
        if (parameters.get("password") != null) {
            String pass = ParameterMap.getKeyedString(parameters, "password", agentConfig.getPassword());
            agentConfig.setUsername(pass);
        }
        if (parameters.get("domain") != null) {
            String domain = ParameterMap.getKeyedString(parameters, "domain", agentConfig.getDomain());
            agentConfig.setUsername(domain);
        }
        if (parameters.get("namespace") != null) {
            wmiNamespace = ParameterMap.getKeyedString(parameters, "wmiNamespace", ParameterMap.getKeyedString(parameters, "namespace", DEFAULT_WMI_NAMESPACE));
        }
        matchType = ParameterMap.getKeyedString(parameters, "matchType", DEFAULT_WMI_MATCH_TYPE);
        compVal = ParameterMap.getKeyedString(parameters, "compareValue", DEFAULT_WMI_COMP_VAL);
        compOp = ParameterMap.getKeyedString(parameters, "compareOp", DEFAULT_WMI_COMP_OP);
        wmiWqlStr = ParameterMap.getKeyedString(parameters, "wql", DEFAULT_WMI_WQL);
        wmiClass = ParameterMap.getKeyedString(parameters, "wmiClass", DEFAULT_WMI_CLASS);
        wmiObject = ParameterMap.getKeyedString(parameters, "wmiObject", DEFAULT_WMI_OBJECT);
    }
    final TimeoutTracker tracker = new TimeoutTracker(parameters, agentConfig.getRetries(), agentConfig.getTimeout());
    final String hostAddress = InetAddressUtils.str(ipAddr);
    LOG.debug("poll: address = {}, user = {}, {}", hostAddress, agentConfig.getUsername(), tracker);
    WmiManager mgr = null;
    for (tracker.reset(); tracker.shouldRetry() && serviceStatus != PollStatus.SERVICE_AVAILABLE; tracker.nextAttempt()) {
        try {
            tracker.startAttempt();
            LOG.debug("poll: creating WmiManager object.");
            // Create a client, set up details and connect.
            mgr = new WmiManager(hostAddress, agentConfig.getUsername(), agentConfig.getPassword(), agentConfig.getDomain(), matchType);
            mgr.setTimeout(tracker.getSoTimeout());
            mgr.setNamespace(wmiNamespace);
            mgr.init();
            LOG.debug("Completed initializing WmiManager object.");
            // We are connected, so upgrade status to unresponsive
            serviceStatus = PollStatus.SERVICE_UNRESPONSIVE;
            // Set up the parameters the client will use to validate the response.
            // Note: We will check and see if we were provided with a WQL string.
            WmiParams clientParams = null;
            if (DEFAULT_WMI_WQL.equals(wmiWqlStr)) {
                clientParams = new WmiParams(WmiParams.WMI_OPERATION_INSTANCEOF, compVal, compOp, wmiClass, wmiObject);
                LOG.debug("Attempting to perform operation: \\\\{}\\{}", wmiClass, wmiObject);
            } else {
                // Create parameters to run a WQL query.
                clientParams = new WmiParams(WmiParams.WMI_OPERATION_WQL, compVal, compOp, wmiWqlStr, wmiObject);
                LOG.debug("Attempting to perform operation: {}", wmiWqlStr);
            }
            // Send the request to the server and receive the response..
            response = mgr.performOp(clientParams);
            LOG.debug("Received result: {}", response);
            // Now save the time it took to process the check command.
            responseTime = tracker.elapsedTimeInMillis();
            if (response == null) {
                continue;
            }
            final List<Object> wmiObjects = response.getResponse();
            final StringBuilder reasonBuffer = new StringBuilder();
            reasonBuffer.append("Constraint '").append(matchType).append(" ").append(clientParams.getCompareOperation()).append(" ").append(clientParams.getCompareValue()).append("' failed for value of ");
            // If there's no WQL string then use the class\object name as the result message
            if (DEFAULT_WMI_WQL.equals(wmiWqlStr)) {
                reasonBuffer.append(wmiClass).append("\\").append(wmiObject);
            } else {
                // Otherwise, print the WQL statement in the result message
                reasonBuffer.append("\"").append(wmiWqlStr).append("\"");
            }
            if (response.getResultCode() == WmiResult.RES_STATE_OK) {
                serviceStatus = PollStatus.SERVICE_AVAILABLE;
                reasonBuffer.append(": ").append(wmiObjects.get(0));
            } else if (response.getResultCode() == WmiResult.RES_STATE_CRIT) {
                serviceStatus = PollStatus.SERVICE_UNAVAILABLE;
                // set this to null so we don't try to save data when the node is down
                responseTime = null;
            }
            reason = reasonBuffer.toString();
        } catch (final WmiException e) {
            LOG.debug("WMI Poller received exception from client.", e);
            reason = "WmiException: " + e.getMessage();
        } finally {
            if (mgr != null) {
                try {
                    mgr.close();
                } catch (WmiException e) {
                    LOG.warn("An error occurred closing the WMI Manager.", e);
                }
            }
        }
    }
    // end for(;;)
    return PollStatus.get(serviceStatus, reason, responseTime);
}
Also used : WmiAgentConfig(org.opennms.netmgt.config.wmi.WmiAgentConfig) WmiManager(org.opennms.protocols.wmi.WmiManager) WmiResult(org.opennms.protocols.wmi.WmiResult) TimeoutTracker(org.opennms.core.utils.TimeoutTracker) WmiParams(org.opennms.protocols.wmi.WmiParams) WmiException(org.opennms.protocols.wmi.WmiException) InetAddress(java.net.InetAddress)

Aggregations

WmiAgentConfig (org.opennms.netmgt.config.wmi.WmiAgentConfig)4 InetAddress (java.net.InetAddress)2 WmiCollection (org.opennms.netmgt.config.wmi.WmiCollection)2 WmiException (org.opennms.protocols.wmi.WmiException)2 OnmsWbemObject (org.opennms.protocols.wmi.wbem.OnmsWbemObject)2 HashMap (java.util.HashMap)1 TimeoutTracker (org.opennms.core.utils.TimeoutTracker)1 WmiAgentState (org.opennms.netmgt.collectd.wmi.WmiAgentState)1 AttributeType (org.opennms.netmgt.collection.api.AttributeType)1 CollectionSetBuilder (org.opennms.netmgt.collection.support.builder.CollectionSetBuilder)1 GenericTypeResource (org.opennms.netmgt.collection.support.builder.GenericTypeResource)1 NodeLevelResource (org.opennms.netmgt.collection.support.builder.NodeLevelResource)1 Resource (org.opennms.netmgt.collection.support.builder.Resource)1 Attrib (org.opennms.netmgt.config.wmi.Attrib)1 Wpm (org.opennms.netmgt.config.wmi.Wpm)1 Definition (org.opennms.netmgt.config.wmi.agent.Definition)1 Range (org.opennms.netmgt.config.wmi.agent.Range)1 WmiClient (org.opennms.protocols.wmi.WmiClient)1 WmiManager (org.opennms.protocols.wmi.WmiManager)1 WmiParams (org.opennms.protocols.wmi.WmiParams)1