use of java.net.PortUnreachableException in project opennms by OpenNMS.
the class JMXDetector method isServiceDetected.
public final boolean isServiceDetected(final InetAddress address, Map<String, String> runtimeAttributes) {
final String ipAddr = InetAddressUtils.str(address);
final int port = getPort();
final int retries = getRetries();
final int timeout = getTimeout();
LOG.info("isServiceDetected: {}: Checking address: {} for capability on port {}", getServiceName(), ipAddr, port);
for (int attempts = 0; attempts < retries; attempts++) {
try (final JmxServerConnectionWrapper client = this.connect(address, port, timeout, runtimeAttributes)) {
LOG.info("isServiceDetected: {}: Attempting to connect to address: {}, port: {}, attempt: #{}", getServiceName(), ipAddr, port, attempts);
if (client.getMBeanServerConnection().getMBeanCount() <= 0) {
return false;
}
if (m_object != null) {
client.getMBeanServerConnection().getObjectInstance(new ObjectName(m_object));
}
return true;
} catch (ConnectException e) {
// Connection refused!! Continue to retry.
LOG.info("isServiceDetected: {}: Unable to connect to address: {} port {}, attempt #{}", getServiceName(), ipAddr, port, attempts, e);
} catch (NoRouteToHostException e) {
// No Route to host!!!
LOG.info("isServiceDetected: {}: No route to address {} was available", getServiceName(), ipAddr, e);
} catch (final PortUnreachableException e) {
// Port unreachable
LOG.info("isServiceDetected: {}: Port unreachable while connecting to address {} port {} within timeout: {} attempt: {}", getServiceName(), ipAddr, port, timeout, attempts, e);
} catch (InterruptedIOException e) {
// Expected exception
LOG.info("isServiceDetected: {}: Did not connect to address {} port {} within timeout: {} attempt: {}", getServiceName(), ipAddr, port, timeout, attempts, e);
} catch (MalformedObjectNameException e) {
LOG.info("isServiceDetected: {}: Object instance {} is not valid on address {} port {} within timeout: {} attempt: {}", getServiceName(), m_object, ipAddr, port, timeout, attempts, e);
} catch (InstanceNotFoundException e) {
LOG.info("isServiceDetected: {}: Object instance {} does not exists on address {} port {} within timeout: {} attempt: {}", getServiceName(), m_object, ipAddr, port, timeout, attempts, e);
} catch (IOException e) {
// NMS-8096: Because the JMX connections wrap lower-level exceptions in an IOException,
// we need to unwrap the exceptions to provide INFO log messages about failures
boolean loggedIt = false;
// Unwrap exception
Throwable cause = e.getCause();
while (cause != null && loggedIt == false) {
if (cause instanceof ConnectException) {
// Connection refused!! Continue to retry.
LOG.info("isServiceDetected: {}: Unable to connect to address: {} port {}, attempt #{}", getServiceName(), ipAddr, port, attempts, e);
loggedIt = true;
} else if (cause instanceof NoRouteToHostException) {
// No Route to host!!!
LOG.info("isServiceDetected: {}: No route to address {} was available", getServiceName(), ipAddr, e);
loggedIt = true;
} else if (cause instanceof PortUnreachableException) {
// Port unreachable
LOG.info("isServiceDetected: {}: Port unreachable while connecting to address {} port {} within timeout: {} attempt: {}", getServiceName(), ipAddr, port, timeout, attempts, e);
loggedIt = true;
} else if (cause instanceof InterruptedIOException) {
// Expected exception
LOG.info("isServiceDetected: {}: Did not connect to address {} port {} within timeout: {} attempt: {}", getServiceName(), ipAddr, port, timeout, attempts, e);
loggedIt = true;
} else if (cause instanceof NameNotFoundException) {
LOG.info("isServiceDetected: {}: Name {} not found on address {} port {} within timeout: {} attempt: {}", getServiceName(), m_object, ipAddr, port, timeout, attempts, e);
loggedIt = true;
} else if (cause instanceof MalformedObjectNameException) {
LOG.info("isServiceDetected: {}: Object instance {} is not valid on address {} port {} within timeout: {} attempt: {}", getServiceName(), m_object, ipAddr, port, timeout, attempts, e);
loggedIt = true;
} else if (cause instanceof InstanceNotFoundException) {
LOG.info("isServiceDetected: {}: Object instance {} does not exists on address {} port {} within timeout: {} attempt: {}", getServiceName(), m_object, ipAddr, port, timeout, attempts, e);
loggedIt = true;
}
cause = cause.getCause();
}
if (!loggedIt) {
// If none of the causes are an expected type, log an error
LOG.error("isServiceDetected: {}: An unexpected I/O exception occured contacting address {} port {}", getServiceName(), ipAddr, port, e);
}
} catch (Throwable t) {
LOG.error("isServiceDetected: {}: Unexpected error trying to detect {} on address {} port {}", getServiceName(), getServiceName(), ipAddr, port, t);
}
}
return false;
}
use of java.net.PortUnreachableException in project webpieces by deanhiller.
the class Helper method read.
private static void read(SelectionKey key, SelectorManager2 mgr, BufferPool pool) throws IOException {
log.trace(() -> key.attachment() + "reading data");
WrapperAndListener struct = (WrapperAndListener) key.attachment();
DataListener in = struct.getDataHandler();
BasChannelImpl channel = (BasChannelImpl) struct.getChannel();
//pressure in RAM so just wait until they re-registerForReads and they will get the data then
if (!channel.isRegisteredForReads()) {
//do not process reads if we were unregistered
return;
}
ByteBuffer chunk = pool.nextBuffer(512);
try {
if (logBufferNextRead)
log.info(channel + "buffer=" + chunk);
int bytes = channel.readImpl(chunk);
if (logBufferNextRead) {
logBufferNextRead = false;
log.info(channel + "buffer2=" + chunk);
}
processBytes(key, chunk, bytes, mgr);
} catch (PortUnreachableException e) {
//this is a normal occurence when some writes out udp to a port that is not
//listening for udp!!! log as finer and fire to client to deal with it.
log.trace(() -> "Client sent data to a host or port that is not listening " + "to udp, or udp can't get through to that machine", e);
in.failure(channel, null, e);
} catch (NotYetConnectedException e) {
//this happens in udp when I disconnect after someone had already been streaming me
//data. It is supposed to stop listening but selector keeps firing.
log.error("Can't read until UDPChannel is connected", e);
in.failure(channel, null, e);
} catch (IOException e) {
//kept getting the following exception so I added this as protection
//NOTE: this exceptionn should never occur. read should be returning -1
//but for some reason is returning hte exception instead.
// WARNING: [server] Processing of key failed, closing channel
// java.io.IOException: An established connection was aborted by the software in your host machine
// at sun.nio.ch.SocketDispatcher.read0(Native Method)
// at sun.nio.ch.SocketDispatcher.read(SocketDispatcher.java:25)
// at sun.nio.ch.IOUtil.readIntoNativeBuffer(IOUtil.java:233)
// at sun.nio.ch.IOUtil.read(IOUtil.java:206)
// at sun.nio.ch.SocketChannelImpl.read(SocketChannelImpl.java:207)
// at biz.xsoftware.impl.nio.cm.basic.TCPChannelImpl.readImpl(TCPChannelImpl.java:168)
// at biz.xsoftware.impl.nio.cm.basic.Helper.read(Helper.java:128)
// at biz.xsoftware.impl.nio.cm.basic.Helper.processKey(Helper.java:77)
// at biz.xsoftware.impl.nio.cm.basic.Helper.processKeys(Helper.java:43)
// at biz.xsoftware.impl.nio.cm.basic.SelectorManager2.runLoop(SelectorManager2.java:262)
// at biz.xsoftware.impl.nio.cm.basic.SelectorManager2$PollingThread.run
// (SelectorManager2.java:224)
//another one that landes here is the Connection reset by peer"....
// Jan 18, 2012 1:00:42 PM biz.xsoftware.impl.nio.cm.basic.Helper read
// INFO: [stserver] Exception
// java.io.IOException: Connection reset by peer
// at sun.nio.ch.FileDispatcher.read0(Native Method)
// at sun.nio.ch.SocketDispatcher.read(SocketDispatcher.java:39)
// at sun.nio.ch.IOUtil.readIntoNativeBuffer(IOUtil.java:251)
// at sun.nio.ch.IOUtil.read(IOUtil.java:224)
// at sun.nio.ch.SocketChannelImpl.read(SocketChannelImpl.java:254)
// at biz.xsoftware.impl.nio.cm.basic.chanimpl.SocketChannelImpl.read(SocketChannelImpl.java:65)
// at biz.xsoftware.impl.nio.cm.basic.BasTCPChannel.readImpl(BasTCPChannel.java:108)
// at biz.xsoftware.impl.nio.cm.basic.Helper.read(Helper.java:162)
// at biz.xsoftware.impl.nio.cm.basic.Helper.processKey(Helper.java:104)
// at biz.xsoftware.impl.nio.cm.basic.Helper.processKeys(Helper.java:51)
// at biz.xsoftware.impl.nio.cm.basic.SelectorManager2.selectorFired(SelectorManager2.java:253)
// at biz.xsoftware.impl.nio.cm.basic.nioimpl.SelectorImpl.runLoop(SelectorImpl.java:126)
// at biz.xsoftware.impl.nio.cm.basic.nioimpl.SelectorImpl$PollingThread.run(SelectorImpl.java:107)
//One other exception starts with "An existing connection was forcibly closed"
//in the case of SSL over TCP only, sometimes instead of reading off a -1, this will
//throw an IOException: "An existing connection was forcibly closed by the remote host"
//we also close UDPChannels as well on IOException. Not sure if this is good or not.
process(key, mgr, in, channel, chunk, e);
} catch (NioException e) {
Throwable cause = e.getCause();
if (cause instanceof IOException) {
IOException ioExc = (IOException) cause;
process(key, mgr, in, channel, chunk, ioExc);
} else
throw e;
}
}
use of java.net.PortUnreachableException in project opennms by OpenNMS.
the class TrivialTimeMonitor method pollTimeUdp.
/**
* <p>pollTimeUdp</p>
*
* @param svc a {@link org.opennms.netmgt.poller.MonitoredService} object.
* @param parameters a {@link java.util.Map} object.
* @param serviceStatus a {@link org.opennms.netmgt.poller.PollStatus} object.
* @param tracker a {@link org.opennms.core.utils.TimeoutTracker} object.
* @param ipv4Addr a {@link java.net.InetAddress} object.
* @param port a int.
* @param allowedSkew a int.
* @param persistSkew a boolean.
* @return a {@link org.opennms.netmgt.poller.PollStatus} object.
*/
public PollStatus pollTimeUdp(MonitoredService svc, Map<String, Object> parameters, PollStatus serviceStatus, TimeoutTracker tracker, InetAddress ipv4Addr, int port, int allowedSkew, boolean persistSkew) {
int localTime = 0;
int remoteTime = 0;
boolean gotTime = false;
for (tracker.reset(); tracker.shouldRetry() && !gotTime; tracker.nextAttempt()) {
DatagramSocket socket = null;
final String hostAddress = InetAddressUtils.str(ipv4Addr);
try {
tracker.startAttempt();
socket = new DatagramSocket();
socket.setSoTimeout(tracker.getSoTimeout());
LOG.debug("Requesting time from host: {} on UDP port: {}", ipv4Addr, port);
//
// Send an empty datagram per RFC868
//
socket.send(new DatagramPacket(new byte[] {}, 0, ipv4Addr, port));
//
// Try to receive a response from the remote socket
//
byte[] timeBytes = new byte[4];
ByteBuffer timeByteBuffer = ByteBuffer.wrap(timeBytes);
DatagramPacket timePacket = new DatagramPacket(timeBytes, timeBytes.length, ipv4Addr, port);
socket.receive(timePacket);
int bytesRead = timePacket.getLength();
if (bytesRead != 4)
continue;
LOG.debug("pollTimeUdp: bytes read = {}", bytesRead);
try {
remoteTime = timeByteBuffer.getInt();
} catch (BufferUnderflowException bue) {
LOG.error("Encountered buffer underflow while reading time from remote socket.");
remoteTime = 0;
serviceStatus = PollStatus.unavailable("Failed to read a valid time from remote host.");
// to next iteration of for() loop
continue;
}
localTime = (int) (System.currentTimeMillis() / 1000) - EPOCH_ADJ_FACTOR;
gotTime = true;
serviceStatus = qualifyTime(remoteTime, localTime, allowedSkew, serviceStatus, tracker.elapsedTimeInMillis(), persistSkew);
} catch (PortUnreachableException e) {
String reason = "Port unreachable exception for address " + hostAddress;
LOG.debug(reason, e);
serviceStatus = PollStatus.unavailable(reason);
} catch (NoRouteToHostException e) {
String reason = "No route to host exception for address " + hostAddress;
LOG.debug(reason, e);
serviceStatus = PollStatus.unavailable(reason);
} catch (InterruptedIOException e) {
String reason = "did not connect to host with " + tracker;
LOG.debug(reason);
serviceStatus = PollStatus.unavailable(reason);
} catch (IOException e) {
String reason = "IOException while polling address: " + ipv4Addr;
LOG.debug(reason, e);
serviceStatus = PollStatus.unavailable(reason);
} finally {
if (socket != null)
socket.close();
}
}
return serviceStatus;
}
use of java.net.PortUnreachableException in project AppCenter-SDK-Android by Microsoft.
the class HttpUtilsAndroidTest method isRecoverableErrorTest.
@Test
public void isRecoverableErrorTest() {
assertTrue(isRecoverableError(new EOFException()));
assertTrue(isRecoverableError(new InterruptedIOException()));
assertTrue(isRecoverableError(new SocketTimeoutException()));
assertTrue(isRecoverableError(new SocketException()));
assertTrue(isRecoverableError(new PortUnreachableException()));
assertTrue(isRecoverableError(new UnknownHostException()));
assertTrue(isRecoverableError(new RejectedExecutionException()));
assertFalse(isRecoverableError(new MalformedURLException()));
assertFalse(isRecoverableError(new IOException()));
assertTrue(isRecoverableError(new IOException(new EOFException())));
assertFalse(isRecoverableError(new IOException(new Exception())));
for (int i = 0; i <= 4; i++) assertTrue(isRecoverableError(new HttpException(500 + i)));
for (int i = 0; i <= 6; i++) assertFalse(isRecoverableError(new HttpException(400 + i)));
assertTrue(isRecoverableError(new HttpException(408)));
assertFalse(isRecoverableError(new HttpException(413)));
assertFalse(isRecoverableError(new HttpException(429)));
assertTrue(isRecoverableError(new SSLException("Write error: ssl=0x59c28f90: I/O error during system call, Connection timed out")));
assertFalse(isRecoverableError(new SSLException(null, new CertPathValidatorException("Trust anchor for certification path not found."))));
assertFalse(isRecoverableError(new SSLException("java.lang.RuntimeException: Unexpected error: java.security.InvalidAlgorithmParameterException: the trustAnchors parameter must be non-empty")));
assertTrue(isRecoverableError(new SSLException("Read error: ssl=0x9dd07200: I/O error during system call, Connection reset by peer")));
assertTrue(isRecoverableError(new SSLException("SSL handshake aborted: ssl=0x1cc160: I/O error during system call, Connection reset by peer")));
assertTrue(isRecoverableError(new SSLHandshakeException("java.security.cert.CertPathValidatorException: Trust anchor for certification path not found.")));
assertTrue(isRecoverableError(new SSLHandshakeException("javax.net.ssl.SSLProtocolException: SSL handshake aborted: ssl=0x870c918: Failure in SSL library, usually a protocol error\nerror:14077410:SSL routines:SSL23_GET_SERVER_HELLO:sslv3 alert handshake failure (external/openssl/ssl/s23_clnt.c:658 0xb7c393a1:0x00000000)")));
}
use of java.net.PortUnreachableException in project webpieces by deanhiller.
the class KeyProcessor method read.
private void read(SelectionKey key, ChannelInfo info) throws IOException {
if (log.isTraceEnabled())
log.trace(info.getChannel() + "reading data");
DataListener in = info.getDataHandler();
BasChannelImpl channel = (BasChannelImpl) info.getChannel();
MDCUtil.setMDC(channel.isServerSide(), channel.getChannelId());
ByteBuffer chunk = pool.nextBuffer(1024);
try {
if (logBufferNextRead)
log.info(channel + " buffer=" + chunk);
int bytes = channel.readImpl(chunk);
if (logBufferNextRead) {
logBufferNextRead = false;
log.info(channel + " buffer2=" + chunk);
}
processBytes(key, info, chunk, bytes);
} catch (PortUnreachableException e) {
connectionErrors.increment();
// listening for udp!!! log as finer and fire to client to deal with it.
if (log.isTraceEnabled())
log.trace("Client sent data to a host or port that is not listening " + "to udp, or udp can't get through to that machine", e);
in.failure(channel, null, e);
} catch (NotYetConnectedException e) {
connectionErrors.increment();
// this happens in udp when I disconnect after someone had already been streaming me
// data. It is supposed to stop listening but selector keeps firing.
log.error("Can't read until UDPChannel is connected", e);
in.failure(channel, null, e);
} catch (IOException e) {
// kept getting the following exception so I added this as protection
// NOTE: this exceptionn should never occur. read should be returning -1
// but for some reason is returning hte exception instead.
// WARNING: [server] Processing of key failed, closing channel
// java.io.IOException: An established connection was aborted by the software in your host machine
// at sun.nio.ch.SocketDispatcher.read0(Native Method)
// at sun.nio.ch.SocketDispatcher.read(SocketDispatcher.java:25)
// at sun.nio.ch.IOUtil.readIntoNativeBuffer(IOUtil.java:233)
// at sun.nio.ch.IOUtil.read(IOUtil.java:206)
// at sun.nio.ch.SocketChannelImpl.read(SocketChannelImpl.java:207)
// at biz.xsoftware.impl.nio.cm.basic.TCPChannelImpl.readImpl(TCPChannelImpl.java:168)
// at biz.xsoftware.impl.nio.cm.basic.Helper.read(Helper.java:128)
// at biz.xsoftware.impl.nio.cm.basic.Helper.processKey(Helper.java:77)
// at biz.xsoftware.impl.nio.cm.basic.Helper.processKeys(Helper.java:43)
// at biz.xsoftware.impl.nio.cm.basic.SelectorManager2.runLoop(SelectorManager2.java:262)
// at biz.xsoftware.impl.nio.cm.basic.SelectorManager2$PollingThread.run
// (SelectorManager2.java:224)
// another one that landes here is the Connection reset by peer"....
// Jan 18, 2012 1:00:42 PM biz.xsoftware.impl.nio.cm.basic.Helper read
// INFO: [stserver] Exception
// java.io.IOException: Connection reset by peer
// at sun.nio.ch.FileDispatcher.read0(Native Method)
// at sun.nio.ch.SocketDispatcher.read(SocketDispatcher.java:39)
// at sun.nio.ch.IOUtil.readIntoNativeBuffer(IOUtil.java:251)
// at sun.nio.ch.IOUtil.read(IOUtil.java:224)
// at sun.nio.ch.SocketChannelImpl.read(SocketChannelImpl.java:254)
// at biz.xsoftware.impl.nio.cm.basic.chanimpl.SocketChannelImpl.read(SocketChannelImpl.java:65)
// at biz.xsoftware.impl.nio.cm.basic.BasTCPChannel.readImpl(BasTCPChannel.java:108)
// at biz.xsoftware.impl.nio.cm.basic.Helper.read(Helper.java:162)
// at biz.xsoftware.impl.nio.cm.basic.Helper.processKey(Helper.java:104)
// at biz.xsoftware.impl.nio.cm.basic.Helper.processKeys(Helper.java:51)
// at biz.xsoftware.impl.nio.cm.basic.SelectorManager2.selectorFired(SelectorManager2.java:253)
// at biz.xsoftware.impl.nio.cm.basic.nioimpl.SelectorImpl.runLoop(SelectorImpl.java:126)
// at biz.xsoftware.impl.nio.cm.basic.nioimpl.SelectorImpl$PollingThread.run(SelectorImpl.java:107)
// One other exception starts with "An existing connection was forcibly closed"
// in the case of SSL over TCP only, sometimes instead of reading off a -1, this will
// throw an IOException: "An existing connection was forcibly closed by the remote host"
// we also close UDPChannels as well on IOException. Not sure if this is good or not.
specialConnectionErrors.increment();
process(key, in, info, chunk, e);
} catch (NioException e) {
connectionErrors.increment();
Throwable cause = e.getCause();
if (cause instanceof IOException) {
specialConnectionErrors.increment();
IOException ioExc = (IOException) cause;
process(key, in, info, chunk, ioExc);
} else
throw e;
} finally {
MDCUtil.setMDC(channel.isServerSide(), channel.getChannelId());
}
}
Aggregations