ComputerPinger.java 1.9 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28
package hudson.model;

import hudson.Extension;
import hudson.ExtensionList;
import hudson.ExtensionPoint;

import java.io.IOException;
import java.net.InetAddress;
import java.util.logging.Logger;

/**
 * A way to see if a computer is reachable.
 *
 * @since 1.378
 */
public abstract class ComputerPinger implements ExtensionPoint {
    /**
     * Is the specified address reachable?
     *
     * @param ia      The address to check.
     * @param timeout Timeout in seconds.
     */
    public abstract boolean isReachable(InetAddress ia, int timeout) throws IOException;

    /**
     * Get all registered instances.
     */
    public static ExtensionList<ComputerPinger> all() {
29
        return ExtensionList.lookup(ComputerPinger.class);
30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65
    }

    /**
     * Is this computer reachable via the given address?
     *
     * @param ia      The address to check.
     * @param timeout Timeout in seconds.
     */
    public static boolean checkIsReachable(InetAddress ia, int timeout) throws IOException {
        for (ComputerPinger pinger : ComputerPinger.all()) {
            try {
                if (pinger.isReachable(ia, timeout)) {
                    return true;
                }
            } catch (IOException e) {
                LOGGER.fine("Error checking reachability with " + pinger + ": " + e.getMessage());
            }
        }

        return false;
    }
    
    /**
     * Default pinger - use Java built-in functionality.  This doesn't always work,
     * a host may be reachable even if this returns false.
     */
    @Extension
    public static class BuiltInComputerPinger extends ComputerPinger {
        @Override
        public boolean isReachable(InetAddress ia, int timeout) throws IOException {
            return ia.isReachable(timeout * 1000);
        }
    }

    private static final Logger LOGGER = Logger.getLogger(ComputerPinger.class.getName());
}