use of org.opennms.protocols.wmi.WmiException in project opennms by OpenNMS.
the class WmiManagerTest method testPerformOpInvalidObject.
/**
* Test the performOp method with an valid WMI class and invalid WMI object.
*
* Test method for
* {@link org.opennms.protocols.wmi.WmiManager#performOp(org.opennms.protocols.wmi.WmiParams)}.
*
* @throws WmiException if there is a problem with the mock object.
*/
public final void testPerformOpInvalidObject() throws WmiException {
//
// Create parameter holder.
WmiParams params = new WmiParams(WmiParams.WMI_OPERATION_INSTANCEOF, "2/12/2004 00:00:00", "EQ", "Win32_BIOS", "RelDate");
// Set up WMI mock client.
// 1) Expect a call to connect() with a bad hostname.
// 2) Throw a new WmiException indictating a bad hostname.
OnmsWbemObjectSet wos = new OnmsWbemObjectSetBiosStub(new OnmsWbemObjectBiosStub(new OnmsWbemPropSetBiosStub(new OnmsWbemPropBiosStub())));
m_WmiMock.connect("127.0.0.1", "Administrator", "password", WmiParams.WMI_DEFAULT_NAMESPACE);
expect(m_WmiMock.performInstanceOf("Win32_BIOS")).andReturn(wos);
replay(m_WmiMock);
try {
// Create a manager.
WmiManager wmiManager = new WmiManager("127.0.0.1", "Administrator", "password");
// Initialize
wmiManager.init(m_WmiMock);
// Perform an operation.
wmiManager.performOp(params);
} catch (WmiException e) {
assertTrue("Exception missing message: Unknown name: " + e, e.getMessage().contains("Unknown name"));
}
verify(m_WmiMock);
reset(m_WmiMock);
}
use of org.opennms.protocols.wmi.WmiException 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);
}
use of org.opennms.protocols.wmi.WmiException in project opennms by OpenNMS.
the class WmiDetector method isServer.
private WmiResult isServer(InetAddress host, String user, String pass, String domain, String namespace, String matchType, int retries, int timeout, WmiParams params) {
boolean isAServer = false;
WmiResult result = null;
for (int attempts = 0; attempts <= retries && !isAServer; attempts++) {
WmiManager mgr = null;
try {
mgr = new WmiManager(InetAddressUtils.str(host), user, pass, domain, matchType);
mgr.setNamespace(namespace);
// Connect to the WMI server.
mgr.init();
// Perform the operation specified in the parameters.
result = mgr.performOp(params);
if (params.getWmiOperation().equals(WmiParams.WMI_OPERATION_WQL)) {
LOG.debug("WmiPlugin: {} : {}", params.getWql(), WmiResult.convertStateToString(result.getResultCode()));
} else {
LOG.debug("WmiPlugin: \\\\{}\\{} : {}", params.getWmiClass(), params.getWmiObject(), WmiResult.convertStateToString(result.getResultCode()));
}
isAServer = true;
} catch (WmiException e) {
final StringBuilder message = new StringBuilder();
message.append("WmiPlugin: Check failed... : ");
message.append(e.getMessage());
message.append(" : ");
message.append((e.getCause() == null ? "" : e.getCause().getMessage()));
LOG.info(message.toString());
isAServer = false;
} finally {
if (mgr != null) {
try {
mgr.close();
} catch (WmiException e) {
LOG.warn("an error occurred closing the WMI Manager", e);
}
}
}
}
return result;
}
use of org.opennms.protocols.wmi.WmiException in project opennms by OpenNMS.
the class OnmsWbemObjectSetImpl method get.
/**
* {@inheritDoc}
*/
@Override
public OnmsWbemObject get(final Integer idx) throws WmiException {
try {
final IJIComObject enumComObject = wbemObjectSet.get("_NewEnum").getObjectAsComObject();
final IJIEnumVariant enumVariant = (IJIEnumVariant) JIObjectFactory.narrowObject(enumComObject.queryInterface(IJIEnumVariant.IID));
OnmsWbemObject wbemObj = null;
IJIDispatch wbemObject_dispatch = null;
for (int i = 0; i < (idx + 1); i++) {
final Object[] values = enumVariant.next(1);
final JIArray array = (JIArray) values[0];
final Object[] arrayObj = (Object[]) array.getArrayInstance();
for (int j = 0; j < arrayObj.length; j++) {
wbemObject_dispatch = (IJIDispatch) JIObjectFactory.narrowObject(((JIVariant) arrayObj[j]).getObjectAsComObject());
}
}
wbemObj = new OnmsWbemObjectImpl(wbemObject_dispatch);
return wbemObj;
} catch (final JIException e) {
throw new WmiException("Failed to enumerate WbemObject variant: " + e.getMessage(), e);
}
}
use of org.opennms.protocols.wmi.WmiException in project opennms by OpenNMS.
the class OnmsWbemPropertySetImpl method getByName.
/**
* {@inheritDoc}
*/
@Override
public OnmsWbemProperty getByName(final String name) throws WmiException {
try {
final IJIComObject enumComObject = wbemPropertySetDispatch.get("_NewEnum").getObjectAsComObject();
final IJIEnumVariant enumVariant = (IJIEnumVariant) JIObjectFactory.narrowObject(enumComObject.queryInterface(IJIEnumVariant.IID));
IJIDispatch wbemProperty_dispatch = null;
for (int i = 0; i < count(); i++) {
final Object[] values = enumVariant.next(1);
final JIArray array = (JIArray) values[0];
final Object[] arrayObj = (Object[]) array.getArrayInstance();
for (int j = 0; j < arrayObj.length; j++) {
wbemProperty_dispatch = (IJIDispatch) JIObjectFactory.narrowObject(((JIVariant) arrayObj[j]).getObjectAsComObject());
// Check the name
final JIVariant variant = wbemProperty_dispatch.get("Name");
if (variant.getObjectAsString2().equalsIgnoreCase(name)) {
return new OnmsWbemPropertyImpl(wbemProperty_dispatch);
}
}
}
throw new WmiException("Property Name '" + name + "' not found.");
} catch (final JIException e) {
throw new WmiException("Failed to enumerate WbemProperty variant: " + e.getMessage(), e);
}
}
Aggregations