Search in sources :

Example 36 with TimeoutTracker

use of org.opennms.core.utils.TimeoutTracker in project opennms by OpenNMS.

the class AsteriskSIPPeerMonitor method poll.

/**
	  * {@inheritDoc}
	  *
	  * <P>
	  * Run the service monitor and return the poll status
	  * </P>
	  */
public PollStatus poll(MonitoredService svc, Map<String, Object> parameters) {
    //read configuration parameters
    String sipPeer = ParameterMap.getKeyedString(parameters, "sip-peer", DEFAULT_SIPPEER);
    if (sipPeer.equals(DEFAULT_SIPPEER)) {
        LOG.error("AsteriskMonitor: No sip-peer parameter in poller configuration");
        throw new RuntimeException("AsteriskMonitor: required parameter 'sip-peer' is not present in supplied properties.");
    }
    TimeoutTracker timeoutTracker = new TimeoutTracker(parameters, DEFAULT_RETRY, DEFAULT_TIMEOUT);
    AmiPeerFactory amiPeerFactory = AmiPeerFactory.getInstance();
    AmiAgentConfig amiConfig = amiPeerFactory.getAgentConfig(svc.getAddress());
    //setting up AMI connection	
    LOG.debug("{}: Creating new AMI-Connection: {}:{}, {}/{}", svc.getSvcName(), svc.getIpAddr(), amiConfig.getPort(), amiConfig.getUsername(), amiConfig.getPassword());
    ManagerConnectionFactory factory = new ManagerConnectionFactory(svc.getIpAddr(), amiConfig.getPort().orElse(null), amiConfig.getUsername().orElse(null), amiConfig.getPassword().orElse(null));
    ManagerConnection managerConnection;
    if (amiConfig.getUseTls().orElse(false)) {
        managerConnection = factory.createSecureManagerConnection();
    } else {
        managerConnection = factory.createManagerConnection();
    }
    managerConnection.setSocketTimeout(new Long(timeoutTracker.getTimeoutInMillis()).intValue());
    //start with polling
    while (timeoutTracker.shouldRetry()) {
        timeoutTracker.nextAttempt();
        LOG.debug("{}: Attempt {}", svc.getSvcName(), timeoutTracker.getAttempt());
        try {
            LOG.debug("{}: AMI login", svc.getSvcName());
            managerConnection.login();
            LOG.debug("{}: AMI sendAction SipShowPeer", svc.getSvcName());
            ManagerResponse response = managerConnection.sendAction(new SipShowPeerAction(sipPeer));
            if (response.getAttribute("Status") == null) {
                LOG.debug("{}: service status down", svc.getSvcName());
                return PollStatus.decode("Down", "State of SIP Peer is unknown, because it was not found on the Asterisk server");
            }
            LOG.debug("{}: Response: {}", svc.getSvcName(), response.getAttribute("Status"));
            LOG.debug("{}: AMI logoff", svc.getSvcName());
            managerConnection.logoff();
            if (response.getAttribute("Status").startsWith("OK")) {
                LOG.debug("{}: service status up", svc.getSvcName());
                return PollStatus.decode("Up", "OK");
            } else {
                LOG.debug("{}: service status down", svc.getSvcName());
                return PollStatus.decode("Down", "State of SIP Peer is " + response.getAttribute("Status") + " and not OK");
            }
        } catch (AuthenticationFailedException e) {
            LOG.debug("{}: AMI AuthenticationError.", svc.getSvcName(), e);
            return PollStatus.decode("Down", "Could not get the state of SIP Peer: AMI AuthenticationError");
        } catch (TimeoutException e) {
            LOG.debug("{}: TimeOut reached.", svc.getSvcName(), e);
        } catch (SocketTimeoutException e) {
            LOG.debug("{}: TimeOut reached.", svc.getSvcName(), e);
        } catch (Exception e) {
            LOG.error("{}: An Unknown Exception Occurred.", svc.getSvcName(), e);
            return PollStatus.decode("Down", "Could not get the state of SIP Peer: " + e.toString());
        }
    }
    //If none of the retries worked
    return PollStatus.decode("Down", "Could not get the state of SIP Peer: Timeout exceeded");
}
Also used : ManagerConnection(org.asteriskjava.manager.ManagerConnection) ManagerResponse(org.asteriskjava.manager.response.ManagerResponse) AuthenticationFailedException(org.asteriskjava.manager.AuthenticationFailedException) ManagerConnectionFactory(org.asteriskjava.manager.ManagerConnectionFactory) AmiAgentConfig(org.opennms.netmgt.config.ami.AmiAgentConfig) SipShowPeerAction(org.asteriskjava.manager.action.SipShowPeerAction) UndeclaredThrowableException(java.lang.reflect.UndeclaredThrowableException) TimeoutException(org.asteriskjava.manager.TimeoutException) SocketTimeoutException(java.net.SocketTimeoutException) AuthenticationFailedException(org.asteriskjava.manager.AuthenticationFailedException) SocketTimeoutException(java.net.SocketTimeoutException) TimeoutTracker(org.opennms.core.utils.TimeoutTracker) AmiPeerFactory(org.opennms.netmgt.config.AmiPeerFactory) TimeoutException(org.asteriskjava.manager.TimeoutException) SocketTimeoutException(java.net.SocketTimeoutException)

Example 37 with TimeoutTracker

use of org.opennms.core.utils.TimeoutTracker in project opennms by OpenNMS.

the class JCifsMonitor method poll.

/**
     * This method queries the CIFS share.
     *
     * @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) {
    final String domain = parameters.containsKey("domain") ? (String) parameters.get("domain") : "";
    final String username = parameters.containsKey("username") ? (String) parameters.get("username") : "";
    final String password = parameters.containsKey("password") ? (String) parameters.get("password") : "";
    String mode = parameters.containsKey("mode") ? ((String) parameters.get("mode")).toUpperCase() : "PATH_EXIST";
    String path = parameters.containsKey("path") ? (String) parameters.get("path") : "";
    String smbHost = parameters.containsKey("smbHost") ? (String) parameters.get("smbHost") : "";
    final String folderIgnoreFiles = parameters.containsKey("folderIgnoreFiles") ? (String) parameters.get("folderIgnoreFiles") : "";
    // changing to Ip address of MonitoredService if no smbHost is given
    if ("".equals(smbHost)) {
        smbHost = svc.getIpAddr();
    }
    // Filename filter to give user the possibility to ignore specific files in folder for the folder check.
    SmbFilenameFilter smbFilenameFilter = new SmbFilenameFilter() {

        @Override
        public boolean accept(SmbFile smbFile, String s) throws SmbException {
            return !s.matches(folderIgnoreFiles);
        }
    };
    // Initialize mode with default as PATH_EXIST
    Mode enumMode = Mode.PATH_EXIST;
    try {
        enumMode = Mode.valueOf(mode);
    } catch (IllegalArgumentException exception) {
        logger.error("Mode '{}‘ does not exists. Valid candidates are {}", mode, modeCandidates);
        return PollStatus.unknown("Mode " + mode + " does not exists. Valid candidates are " + modeCandidates);
    }
    // Checking path parameter
    if (!path.startsWith("/")) {
        path = "/" + path;
        logger.debug("Added leading / to path.");
    }
    // Build authentication string for NtlmPasswordAuthentication: syntax: domain;username:password
    String authString = "";
    // Setting up authenticationString...
    if (domain != null && !"".equals(domain)) {
        authString += domain + ";";
    }
    authString += username + ":" + password;
    // ... and path
    String fullUrl = "smb://" + smbHost + path;
    logger.debug("Domain: [{}], Username: [{}], Password: [{}], Mode: [{}], Path: [{}], Authentication: [{}], Full Url: [{}]", new Object[] { domain, username, password, mode, path, authString, fullUrl });
    // Initializing TimeoutTracker with default values
    TimeoutTracker tracker = new TimeoutTracker(parameters, DEFAULT_RETRY, DEFAULT_TIMEOUT);
    // Setting default PollStatus
    PollStatus serviceStatus = PollStatus.unknown();
    for (tracker.reset(); tracker.shouldRetry() && !serviceStatus.isAvailable(); tracker.nextAttempt()) {
        NtlmPasswordAuthentication ntlmPasswordAuthentication = new NtlmPasswordAuthentication(authString);
        try {
            // Creating SmbFile object
            SmbFile smbFile = new SmbFile(fullUrl, ntlmPasswordAuthentication);
            // Setting the defined timeout
            smbFile.setConnectTimeout(tracker.getConnectionTimeout());
            // Does the file exists?
            boolean smbFileExists = smbFile.exists();
            switch(enumMode) {
                case PATH_EXIST:
                    if (smbFileExists) {
                        serviceStatus = PollStatus.up();
                    } else {
                        serviceStatus = PollStatus.down("File " + fullUrl + " should exists but doesn't!");
                    }
                    break;
                case PATH_NOT_EXIST:
                    if (!smbFileExists) {
                        serviceStatus = PollStatus.up();
                    } else {
                        serviceStatus = PollStatus.down("File " + fullUrl + " should not exists but does!");
                    }
                    break;
                case FOLDER_EMPTY:
                    if (smbFileExists) {
                        if (smbFile.list(smbFilenameFilter).length == 0) {
                            serviceStatus = PollStatus.up();
                        } else {
                            serviceStatus = PollStatus.down("Directory " + fullUrl + " should be empty but isn't!");
                        }
                    } else {
                        serviceStatus = PollStatus.down("Directory " + fullUrl + " should exists but doesn't!");
                    }
                    break;
                case FOLDER_NOT_EMPTY:
                    if (smbFileExists) {
                        if (smbFile.list(smbFilenameFilter).length > 0) {
                            serviceStatus = PollStatus.up();
                        } else {
                            serviceStatus = PollStatus.down("Directory " + fullUrl + " should not be empty but is!");
                        }
                    } else {
                        serviceStatus = PollStatus.down("Directory " + fullUrl + " should exists but doesn't!");
                    }
                    break;
                default:
                    logger.warn("There is no implementation for the specified mode '{}'", mode);
                    break;
            }
        } catch (MalformedURLException exception) {
            logger.error("Malformed URL on '{}' with error: '{}'", smbHost, exception.getMessage());
            serviceStatus = PollStatus.down(exception.getMessage());
        } catch (SmbException exception) {
            logger.error("SMB error on '{}' with error: '{}'", smbHost, exception.getMessage());
            serviceStatus = PollStatus.down(exception.getMessage());
        }
    }
    return serviceStatus;
}
Also used : SmbException(jcifs.smb.SmbException) MalformedURLException(java.net.MalformedURLException) PollStatus(org.opennms.netmgt.poller.PollStatus) TimeoutTracker(org.opennms.core.utils.TimeoutTracker) NtlmPasswordAuthentication(jcifs.smb.NtlmPasswordAuthentication) SmbFilenameFilter(jcifs.smb.SmbFilenameFilter) SmbFile(jcifs.smb.SmbFile)

Example 38 with TimeoutTracker

use of org.opennms.core.utils.TimeoutTracker in project opennms by OpenNMS.

the class SshClient method connect.

/** {@inheritDoc} */
@Override
public void connect(final InetAddress address, final int port, final int timeout) throws Exception {
    Map<String, ?> emptyMap = Collections.emptyMap();
    TimeoutTracker tracker = new TimeoutTracker(emptyMap, SshClient.DEFAULT_RETRY, timeout);
    String banner = m_banner;
    String match = m_match;
    String clientBanner = m_clientBanner;
    PollStatus ps = PollStatus.unavailable();
    Ssh ssh = new Ssh(address, port, tracker.getConnectionTimeout());
    ssh.setClientBanner(clientBanner);
    Pattern regex = null;
    if (match == null && (banner == null || banner.equals("*"))) {
        regex = null;
    } else if (match != null) {
        regex = Pattern.compile(match);
    } else if (banner != null) {
        regex = Pattern.compile(banner);
    }
    for (tracker.reset(); tracker.shouldRetry() && !ps.isAvailable(); tracker.nextAttempt()) {
        try {
            ps = ssh.poll(tracker);
        } catch (InsufficientParametersException e) {
            LOG.error("Caught InsufficientParametersException: {}", e.getMessage(), e);
            break;
        }
    }
    if (regex != null && ps.isAvailable()) {
        String response = ssh.getServerBanner();
        if (response == null) {
            ps = PollStatus.unavailable("server closed connection before banner was recieved.");
        }
        if (!regex.matcher(response).find()) {
            // Got a response but it didn't match... no need to attempt
            // retries
            LOG.debug("isServer: NON-matching response='{}'", response);
            ps = PollStatus.unavailable("server responded, but banner did not match '" + banner + "'");
        } else {
            LOG.debug("isServer: matching response='{}'", response);
        }
    }
    PollStatus result = ps;
    m_isAvailable = result.isAvailable();
}
Also used : Pattern(java.util.regex.Pattern) PollStatus(org.opennms.netmgt.poller.PollStatus) TimeoutTracker(org.opennms.core.utils.TimeoutTracker) Ssh(org.opennms.netmgt.provision.support.ssh.Ssh) InsufficientParametersException(org.opennms.netmgt.provision.support.ssh.InsufficientParametersException)

Example 39 with TimeoutTracker

use of org.opennms.core.utils.TimeoutTracker in project opennms by OpenNMS.

the class AbstractPoll method poll.

/**
     * <p>poll</p>
     *
     * @return a {@link org.opennms.netmgt.poller.PollStatus} object.
     * @throws org.opennms.netmgt.provision.support.ssh.InsufficientParametersException if any.
     */
@Override
public PollStatus poll() throws InsufficientParametersException {
    Map<String, ?> emptyMap = Collections.emptyMap();
    TimeoutTracker tracker = new TimeoutTracker(emptyMap, 1, getTimeout());
    return poll(tracker);
}
Also used : TimeoutTracker(org.opennms.core.utils.TimeoutTracker)

Example 40 with TimeoutTracker

use of org.opennms.core.utils.TimeoutTracker 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 StringBuffer reasonBuffer = new StringBuffer();
            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

TimeoutTracker (org.opennms.core.utils.TimeoutTracker)42 PollStatus (org.opennms.netmgt.poller.PollStatus)29 InetAddress (java.net.InetAddress)24 IOException (java.io.IOException)16 InterruptedIOException (java.io.InterruptedIOException)13 ConnectException (java.net.ConnectException)13 NoRouteToHostException (java.net.NoRouteToHostException)13 InetSocketAddress (java.net.InetSocketAddress)11 Socket (java.net.Socket)11 InputStreamReader (java.io.InputStreamReader)7 BufferedReader (java.io.BufferedReader)6 HashMap (java.util.HashMap)4 MalformedURLException (java.net.MalformedURLException)3 Pattern (java.util.regex.Pattern)3 HostRuntimeInfo (com.vmware.vim25.HostRuntimeInfo)2 HostSystemPowerState (com.vmware.vim25.HostSystemPowerState)2 HostSystem (com.vmware.vim25.mo.HostSystem)2 SocketTimeoutException (java.net.SocketTimeoutException)2 RemoteException (java.rmi.RemoteException)2 Properties (java.util.Properties)2