use of java.net.NoRouteToHostException in project opennms by OpenNMS.
the class DnsMonitor method pollDNS.
private PollStatus pollDNS(final TimeoutTracker timeoutTracker, final int port, final InetAddress address, final String lookup, final List<Integer> fatalCodes, int minAnswers, int maxAnswers) {
final String addr = InetAddressUtils.str(address);
for (timeoutTracker.reset(); timeoutTracker.shouldRetry(); timeoutTracker.nextAttempt()) {
try {
final Name name = Name.fromString(lookup, Name.root);
final SimpleResolver resolver = new SimpleResolver();
resolver.setAddress(new InetSocketAddress(addr, port));
resolver.setLocalAddress((InetSocketAddress) null);
double timeout = timeoutTracker.getSoTimeout() / 1000;
resolver.setTimeout((timeout < 1 ? 1 : (int) timeout));
final Record question = Record.newRecord(name, Type.A, DClass.IN);
final Message query = Message.newQuery(question);
PollStatus status;
timeoutTracker.startAttempt();
final Message response = resolver.send(query);
double responseTime = timeoutTracker.elapsedTimeInMillis();
final Integer rcode = response.getHeader().getRcode();
LOG.debug("received response code: {}", rcode);
if (fatalCodes.contains(rcode)) {
status = PollStatus.unavailable("Received an invalid DNS response for address: " + addr);
LOG.debug(status.getReason());
return status;
} else if (minAnswers != DEFAULT_MIN_ANSWERS || maxAnswers != DEFAULT_MAX_ANSWERS) {
int numAnswers = response.getSectionArray(Section.ANSWER).length;
boolean tooFewAnswers = numAnswers < minAnswers;
boolean tooManyAnswers = numAnswers > maxAnswers;
if (tooFewAnswers) {
status = PollStatus.unavailable("Response contained only " + numAnswers + " answer(s), but at least " + minAnswers + " answers(s) are needed.");
LOG.warn(status.getReason());
return status;
}
if (tooManyAnswers) {
status = PollStatus.unavailable("Response contained " + numAnswers + " answer(s), but " + maxAnswers + " or fewer answers(s) are needed.");
LOG.warn(status.getReason());
return status;
}
status = PollStatus.up(responseTime);
LOG.debug("valid DNS response received with {} answer(s), responseTime = {}ms", numAnswers, responseTime);
return status;
} else {
status = PollStatus.up(responseTime);
LOG.debug("valid DNS response received, responseTime = {}ms", responseTime);
return status;
}
} catch (final InterruptedIOException e) {
// No response received, retry without marking the poll failed. If we get this condition over and over until
// the retries are exhausted, it will leave serviceStatus null and we'll get the log message at the bottom
} catch (final NoRouteToHostException e) {
String reason1 = "No route to host exception for address: " + addr;
LOG.debug(reason1, e);
return PollStatus.unavailable(reason1);
} catch (final ConnectException e) {
String reason1 = "Connection exception for address: " + addr;
LOG.debug(reason1, e);
return PollStatus.unavailable(reason1);
} catch (final IOException e) {
String reason1 = "IOException while polling address: " + addr + " " + e.getMessage();
LOG.debug(reason1, e);
return PollStatus.unavailable(reason1);
}
}
String reason = "Never received valid DNS response for address: " + addr;
LOG.debug(reason);
return PollStatus.unavailable(reason);
}
use of java.net.NoRouteToHostException in project voldemort by voldemort.
the class BannagePeriodFailureDetectorTest method testCatastrophicErrors.
@Test
public void testCatastrophicErrors() throws Exception {
Node node = Iterables.get(cluster.getNodes(), 8);
failureDetector.recordException(node, 0, new UnreachableStoreException("intentionalerror", new ConnectException("intentionalerror")));
assertEquals(false, failureDetector.isAvailable(node));
time.sleep(BANNAGE_MILLIS + 1);
assertTrue(failureDetector.isAvailable(node));
failureDetector.recordException(node, 0, new UnreachableStoreException("intentionalerror", new UnknownHostException("intentionalerror")));
assertEquals(false, failureDetector.isAvailable(node));
time.sleep(BANNAGE_MILLIS + 1);
assertTrue(failureDetector.isAvailable(node));
failureDetector.recordException(node, 0, new UnreachableStoreException("intentionalerror", new NoRouteToHostException("intentionalerror")));
assertEquals(false, failureDetector.isAvailable(node));
time.sleep(BANNAGE_MILLIS + 1);
assertTrue(failureDetector.isAvailable(node));
}
use of java.net.NoRouteToHostException in project android_frameworks_base by crdroidandroid.
the class MediaHTTPConnection method seekTo.
private void seekTo(long offset) throws IOException {
teardownConnection();
try {
int response;
int redirectCount = 0;
URL url = mURL;
// do not use any proxy for localhost (127.0.0.1)
boolean noProxy = isLocalHost(url);
while (true) {
if (noProxy) {
mConnection = (HttpURLConnection) url.openConnection(Proxy.NO_PROXY);
} else {
mConnection = (HttpURLConnection) url.openConnection();
}
mConnection.setConnectTimeout(CONNECT_TIMEOUT_MS);
// handle redirects ourselves if we do not allow cross-domain redirect
mConnection.setInstanceFollowRedirects(mAllowCrossDomainRedirect);
if (mHeaders != null) {
for (Map.Entry<String, String> entry : mHeaders.entrySet()) {
mConnection.setRequestProperty(entry.getKey(), entry.getValue());
}
}
if (offset > 0) {
mConnection.setRequestProperty("Range", "bytes=" + offset + "-");
}
response = mConnection.getResponseCode();
if (response != HttpURLConnection.HTTP_MULT_CHOICE && response != HttpURLConnection.HTTP_MOVED_PERM && response != HttpURLConnection.HTTP_MOVED_TEMP && response != HttpURLConnection.HTTP_SEE_OTHER && response != HTTP_TEMP_REDIRECT) {
// not a redirect, or redirect handled by HttpURLConnection
break;
}
if (++redirectCount > MAX_REDIRECTS) {
throw new NoRouteToHostException("Too many redirects: " + redirectCount);
}
String method = mConnection.getRequestMethod();
if (response == HTTP_TEMP_REDIRECT && !method.equals("GET") && !method.equals("HEAD")) {
// automatically redirect the request"
throw new NoRouteToHostException("Invalid redirect");
}
String location = mConnection.getHeaderField("Location");
if (location == null) {
throw new NoRouteToHostException("Invalid redirect");
}
url = new URL(mURL, /* TRICKY: don't use url! */
location);
if (!url.getProtocol().equals("https") && !url.getProtocol().equals("http")) {
throw new NoRouteToHostException("Unsupported protocol redirect");
}
boolean sameProtocol = mURL.getProtocol().equals(url.getProtocol());
if (!mAllowCrossProtocolRedirect && !sameProtocol) {
throw new NoRouteToHostException("Cross-protocol redirects are disallowed");
}
boolean sameHost = mURL.getHost().equals(url.getHost());
if (!mAllowCrossDomainRedirect && !sameHost) {
throw new NoRouteToHostException("Cross-domain redirects are disallowed");
}
if (response != HTTP_TEMP_REDIRECT) {
// update effective URL, unless it is a Temporary Redirect
mURL = url;
}
}
if (mAllowCrossDomainRedirect) {
// remember the current, potentially redirected URL if redirects
// were handled by HttpURLConnection
mURL = mConnection.getURL();
}
if (response == HttpURLConnection.HTTP_PARTIAL) {
// Partial content, we cannot just use getContentLength
// because what we want is not just the length of the range
// returned but the size of the full content if available.
String contentRange = mConnection.getHeaderField("Content-Range");
mTotalSize = -1;
if (contentRange != null) {
// format is "bytes xxx-yyy/zzz
// where "zzz" is the total number of bytes of the
// content or '*' if unknown.
int lastSlashPos = contentRange.lastIndexOf('/');
if (lastSlashPos >= 0) {
String total = contentRange.substring(lastSlashPos + 1);
try {
mTotalSize = Long.parseLong(total);
} catch (NumberFormatException e) {
}
}
}
} else if (response != HttpURLConnection.HTTP_OK) {
throw new IOException();
} else {
mTotalSize = mConnection.getContentLength();
}
if (offset > 0 && response != HttpURLConnection.HTTP_PARTIAL) {
// data from the start of the content.
throw new ProtocolException();
}
mInputStream = new BufferedInputStream(mConnection.getInputStream());
mCurrentOffset = offset;
} catch (IOException e) {
mTotalSize = -1;
mInputStream = null;
mConnection = null;
mCurrentOffset = -1;
throw e;
}
}
use of java.net.NoRouteToHostException in project http-kit by http-kit.
the class MaliciousClients method run.
public void run() {
while (remaining-- > 0) {
Socket s = new Socket();
try {
s.setReuseAddress(true);
s.setSoTimeout(100);
s.connect(addr);
ReqGenerators gen = generators[r.nextInt(generators.length)];
OutputStream os = s.getOutputStream();
os.write(gen.generate(methods[r.nextInt(methods.length)], urls[r.nextInt(urls.length)]));
InputStream is = s.getInputStream();
byte[] buffer = new byte[8096];
int read = is.read(buffer);
// System.out.println(new String(buffer, 0, read));
is.close();
os.close();
if (read > 0)
success += 1;
} catch (NoRouteToHostException e) {
// Cannot assign requested address
try {
Thread.sleep(800);
} catch (InterruptedException e1) {
}
// e.printStackTrace();
} catch (Exception e) {
} finally {
try {
s.close();
} catch (IOException e) {
}
}
if (remaining % (total / 10) == 0) {
logger.info("total: {}, remaining: {} success: {}", total, remaining, success);
}
try {
Thread.sleep(10);
} catch (InterruptedException e) {
}
}
logger.info("finished. total: {}, success: {}", total, success);
}
use of java.net.NoRouteToHostException in project hadoop by apache.
the class RPC method waitForProtocolProxy.
/**
* Get a protocol proxy that contains a proxy connection to a remote server
* and a set of methods that are supported by the server
*
* @param protocol protocol class
* @param clientVersion client version
* @param addr remote address
* @param conf configuration to use
* @param rpcTimeout timeout for each RPC
* @param timeout time in milliseconds before giving up
* @return the proxy
* @throws IOException if the far end through a RemoteException
*/
public static <T> ProtocolProxy<T> waitForProtocolProxy(Class<T> protocol, long clientVersion, InetSocketAddress addr, Configuration conf, int rpcTimeout, RetryPolicy connectionRetryPolicy, long timeout) throws IOException {
long startTime = Time.now();
IOException ioe;
while (true) {
try {
return getProtocolProxy(protocol, clientVersion, addr, UserGroupInformation.getCurrentUser(), conf, NetUtils.getDefaultSocketFactory(conf), rpcTimeout, connectionRetryPolicy);
} catch (ConnectException se) {
// namenode has not been started
LOG.info("Server at " + addr + " not available yet, Zzzzz...");
ioe = se;
} catch (SocketTimeoutException te) {
// namenode is busy
LOG.info("Problem connecting to server: " + addr);
ioe = te;
} catch (NoRouteToHostException nrthe) {
// perhaps a VIP is failing over
LOG.info("No route to host for server: " + addr);
ioe = nrthe;
}
// check if timed out
if (Time.now() - timeout >= startTime) {
throw ioe;
}
if (Thread.currentThread().isInterrupted()) {
// interrupted during some IO; this may not have been caught
throw new InterruptedIOException("Interrupted waiting for the proxy");
}
// wait for retry
try {
Thread.sleep(1000);
} catch (InterruptedException ie) {
Thread.currentThread().interrupt();
throw (IOException) new InterruptedIOException("Interrupted waiting for the proxy").initCause(ioe);
}
}
}
Aggregations