def resolveHost(self, host):
address = self.dnsCache.getCachedAddress(host)
if address != None:
log.debug("Host cached: {} {}".format(host, address))
return defer.succeed(address)
else:
log.debug("Host not cached.")
self.customResolver.port = self.urlMonitor.getResolverPort()
try:
log.debug("Resolving with DNSChef")
address = str(self.customResolver.query(host)[0].address)
return defer.succeed(address)
except Exception:
log.debug("Exception occured, falling back to Twisted")
return reactor.resolve(host)
python类resolve()的实例源码
def resolveHost(self, host):
address = self.dnsCache.getCachedAddress(host)
if address != None:
log.debug("Host cached: {} {}".format(host, address))
return defer.succeed(address)
else:
log.debug("Host not cached.")
self.customResolver.port = self.urlMonitor.getResolverPort()
try:
log.debug("Resolving with DNSChef")
address = str(self.customResolver.query(host)[0].address)
return defer.succeed(address)
except Exception:
log.debug("Exception occured, falling back to Twisted")
return reactor.resolve(host)
def resolveHost(self, host):
address = self.dnsCache.getCachedAddress(host)
if address != None:
log.debug("Host cached: {} {}".format(host, address))
return defer.succeed(address)
else:
log.debug("Host not cached.")
self.customResolver.port = self.urlMonitor.getResolverPort()
try:
log.debug("Resolving with DNSChef")
address = str(self.customResolver.query(host)[0].address)
return defer.succeed(address)
except Exception:
log.debug("Exception occured, falling back to Twisted")
return reactor.resolve(host)
def sendto(self, data, destination):
if self.check_num_packets(destination, False):
if DataChecker.is_allowed(data):
def on_error(failure):
self.logger.error("Can't resolve ip address for hostname %s. Failure: %s",
destination[0], failure)
def on_ip_address(ip_address):
self.logger.debug("Resolved hostname %s to ip_address %s", destination[0], ip_address)
try:
self.transport.write(data, (ip_address, destination[1]))
self.overlay.increase_bytes_sent(self, len(data))
except (AttributeError, MessageLengthError, socket.error) as exception:
self.logger.error(
"Failed to write data to transport: %s. Destination: %r error was: %r",
exception, destination, exception)
resolve_ip_address_deferred = reactor.resolve(destination[0])
resolve_ip_address_deferred.addCallbacks(on_ip_address, on_error)
self.register_task("resolving_%r" % destination[0], resolve_ip_address_deferred)
else:
self.logger.error("dropping forbidden packets from exit socket with circuit_id %d",
self.circuit_id)
def resolveHost(self, host):
address = self.dnsCache.getCachedAddress(host)
if address != None:
log.debug("Host cached: {} {}".format(host, address))
return defer.succeed(address)
else:
log.debug("Host not cached.")
self.customResolver.port = self.urlMonitor.getResolverPort()
try:
log.debug("Resolving with DNSChef")
address = str(self.customResolver.query(host)[0].address)
return defer.succeed(address)
except Exception:
log.debug("Exception occured, falling back to Twisted")
return reactor.resolve(host)
def get(self):
host = self.config.get('destination', self.hostname)
try:
ip = yield reactor.resolve(host)
except:
ip = None
if ip:
try:
loss, latency = yield icmp.ping(ip, 5)
except:
loss, latency = 100, None
event = [self.createEvent('ok', '%s%% loss to %s' % (loss, host),
loss, prefix="loss")]
if latency:
event.append(self.createEvent('ok', 'Latency to %s' % host,
latency, prefix="latency"))
else:
event = [self.createEvent('critical', 'Unable to resolve %s' % host,
100, prefix="loss")]
defer.returnValue(event)
def resolveHost(self, host):
address = self.dnsCache.getCachedAddress(host)
if address != None:
log.debug("Host cached: {} {}".format(host, address))
return defer.succeed(address)
else:
log.debug("Host not cached.")
self.customResolver.port = self.urlMonitor.getResolverPort()
try:
log.debug("Resolving with DNSChef")
address = str(self.customResolver.query(host)[0].address)
return defer.succeed(address)
except Exception:
log.debug("Exception occured, falling back to Twisted")
return reactor.resolve(host)
def resolveHost(self, host):
address = self.dnsCache.getCachedAddress(host)
if address != None:
log.debug("Host cached: {} {}".format(host, address))
return defer.succeed(address)
else:
log.debug("Host not cached.")
self.customResolver.port = self.urlMonitor.getResolverPort()
try:
log.debug("Resolving with DNSChef")
address = str(self.customResolver.query(host)[0].address)
return defer.succeed(address)
except Exception:
log.debug("Exception occured, falling back to Twisted")
return reactor.resolve(host)
def resolveHost(self, host):
address = self.dnsCache.getCachedAddress(host)
if address != None:
logging.debug("Host cached.")
return defer.succeed(address)
else:
logging.debug("Host not cached.")
return reactor.resolve(host)
def resolveHost(self, host):
address = self.dnsCache.getCachedAddress(host)
if address != None:
logging.debug("Host cached.")
return defer.succeed(address)
else:
logging.debug("Host not cached.")
return reactor.resolve(host)
def resolveHost(self, host):
address = self.dnsCache.getCachedAddress(host)
if address != None:
logging.debug("Host cached.")
return defer.succeed(address)
else:
logging.debug("Host not cached.")
return reactor.resolve(host)
def resolveAddress(self):
host, port = self.addr
if isIPAddress(host):
return self.addr
else:
from twisted.internet import reactor
return reactor.resolve(host).addCallback(self._filterRealAddress)
def testChildResolve(self):
# I've seen problems with reactor.run under gtk2reactor. Spawn a
# child which just does reactor.resolve after the reactor has
# started, fail if it does not complete in a timely fashion.
helperPath = os.path.abspath(self.mktemp())
helperFile = open(helperPath, 'w')
# Eeueuuggg
reactorName = reactor.__module__
helperFile.write(resolve_helper % {'reactor': reactorName})
helperFile.close()
env = os.environ.copy()
env['PYTHONPATH'] = os.pathsep.join(sys.path)
helperDeferred = Deferred()
helperProto = ChildResolveProtocol(helperDeferred)
reactor.spawnProcess(helperProto, sys.executable, ("python", "-u", helperPath), env)
def cbFinished((reason, output, error)):
# If the output is "done 127.0.0.1\n" we don't really care what
# else happened.
output = ''.join(output)
if output != 'done 127.0.0.1\n':
self.fail((
"The child process failed to produce the desired results:\n"
" Reason for termination was: %r\n"
" Output stream was: %r\n"
" Error stream was: %r\n") % (reason.getErrorMessage(), output, ''.join(error)))
def get_local_ip():
"""
Returns a deferred which will be called with a
2-uple (lan_flag, ip_address) :
- lan_flag:
- True if it's a local network (RFC1918)
- False if it's a WAN address
- ip_address is the actual ip address
@return: A deferred called with the above defined tuple
@rtype: L{twisted.internet.defer.Deferred}
"""
# first we try a connected udp socket, then via multicast
logging.debug("Resolving dns to get udp ip")
try:
ipaddr = yield reactor.resolve('A.ROOT-SERVERS.NET')
except:
pass
else:
udpprot = DatagramProtocol()
port = reactor.listenUDP(0, udpprot)
udpprot.transport.connect(ipaddr, 7)
localip = udpprot.transport.getHost().host
port.stopListening()
if is_bogus_ip(localip):
raise RuntimeError, "Invalid IP address returned"
else:
defer.returnValue((is_rfc1918_ip(localip), localip))
logging.debug("Multicast ping to retrieve local IP")
ipaddr = yield _discover_multicast()
defer.returnValue((is_rfc1918_ip(ipaddr), ipaddr))
def resolveHost(self, host):
address = self.dnsCache.getCachedAddress(host)
if address != None:
log.debug("[ClientRequest] Host cached: {} {}".format(host, address))
return defer.succeed(address)
else:
return reactor.resolve(host)
def __init__(self, channel, queued, reactor=reactor):
Request.__init__(self, channel, queued)
self.reactor = reactor
self.urlMonitor = URLMonitor.getInstance()
self.hsts = URLMonitor.getInstance().hsts
self.cookieCleaner = CookieCleaner.getInstance()
self.dnsCache = DnsCache.getInstance()
#self.uniqueId = random.randint(0, 10000)
#Use are own DNS server instead of reactor.resolve()
self.customResolver = dns.resolver.Resolver()
self.customResolver.nameservers = ['127.0.0.1']
def resolveHost(self, host):
address = self.dnsCache.getCachedAddress(host)
if address != None:
logging.debug("Host cached.")
return defer.succeed(address)
else:
logging.debug("Host not cached.")
return reactor.resolve(host)
def resolveHost(self, host):
address = self.dnsCache.getCachedAddress(host)
if address != None:
logging.debug("Host cached.")
return defer.succeed(address)
else:
logging.debug("Host not cached.")
return reactor.resolve(host)
def resolveHost(self, host):
address = self.dnsCache.getCachedAddress(host)
if address != None:
logging.debug("Host cached.")
return defer.succeed(address)
else:
logging.debug("Host not cached.")
return reactor.resolve(host)
def get_local_ip():
"""
Returns a deferred which will be called with a
2-uple (lan_flag, ip_address) :
- lan_flag:
- True if it's a local network (RFC1918)
- False if it's a WAN address
- ip_address is the actual ip address
@return: A deferred called with the above defined tuple
@rtype: L{twisted.internet.defer.Deferred}
"""
# first we try a connected udp socket, then via multicast
logging.debug("Resolving dns to get udp ip")
try:
ipaddr = yield reactor.resolve('A.ROOT-SERVERS.NET')
except:
pass
else:
udpprot = DatagramProtocol()
port = reactor.listenUDP(0, udpprot)
udpprot.transport.connect(ipaddr, 7)
localip = udpprot.transport.getHost().host
port.stopListening()
if is_bogus_ip(localip):
raise RuntimeError, "Invalid IP address returned"
else:
defer.returnValue((is_rfc1918_ip(localip), localip))
logging.debug("Multicast ping to retrieve local IP")
ipaddr = yield _discover_multicast()
defer.returnValue((is_rfc1918_ip(ipaddr), ipaddr))
def resolveHost(self, host):
address = self.dnsCache.getCachedAddress(host)
if address != None:
log.debug("[ClientRequest] Host cached: {} {}".format(host, address))
return defer.succeed(address)
else:
return reactor.resolve(host)
def __init__(self, channel, queued, reactor=reactor):
Request.__init__(self, channel, queued)
self.reactor = reactor
self.urlMonitor = URLMonitor.getInstance()
self.hsts = URLMonitor.getInstance().hsts
self.cookieCleaner = CookieCleaner.getInstance()
self.dnsCache = DnsCache.getInstance()
#self.uniqueId = random.randint(0, 10000)
#Use are own DNS server instead of reactor.resolve()
self.customResolver = dns.resolver.Resolver()
self.customResolver.nameservers = ['127.0.0.1']
def get_local_ip():
"""
Returns a deferred which will be called with a
2-uple (lan_flag, ip_address) :
- lan_flag:
- True if it's a local network (RFC1918)
- False if it's a WAN address
- ip_address is the actual ip address
@return: A deferred called with the above defined tuple
@rtype: L{twisted.internet.defer.Deferred}
"""
# first we try a connected udp socket, then via multicast
logging.debug("Resolving dns to get udp ip")
try:
ipaddr = yield reactor.resolve('A.ROOT-SERVERS.NET')
except:
pass
else:
udpprot = DatagramProtocol()
port = reactor.listenUDP(0, udpprot)
udpprot.transport.connect(ipaddr, 7)
localip = udpprot.transport.getHost().host
port.stopListening()
if is_bogus_ip(localip):
raise RuntimeError, "Invalid IP address returned"
else:
defer.returnValue((is_rfc1918_ip(localip), localip))
logging.debug("Multicast ping to retrieve local IP")
ipaddr = yield _discover_multicast()
defer.returnValue((is_rfc1918_ip(ipaddr), ipaddr))
def resolveHost(self, host):
address = self.dnsCache.getCachedAddress(host)
if address != None:
logging.debug("Host cached.")
return defer.succeed(address)
else:
logging.debug("Host not cached.")
return reactor.resolve(host)
def resolveHost(self, host):
address = self.dnsCache.getCachedAddress(host)
if address != None:
logging.debug("Host cached.")
return defer.succeed(address)
else:
logging.debug("Host not cached.")
return reactor.resolve(host)
def resolveHost(self, host):
address = self.dnsCache.getCachedAddress(host)
if address != None:
logging.debug("Host cached.")
return defer.succeed(address)
else:
logging.debug("Host not cached.")
return reactor.resolve(host)
def resolveAddress(self):
host, port = self.addr
if isIPAddress(host):
return self.addr
else:
from twisted.internet import reactor
return reactor.resolve(host).addCallback(self._filterRealAddress)
def testChildResolve(self):
# I've seen problems with reactor.run under gtk2reactor. Spawn a
# child which just does reactor.resolve after the reactor has
# started, fail if it does not complete in a timely fashion.
helperPath = os.path.abspath(self.mktemp())
helperFile = open(helperPath, 'w')
# Eeueuuggg
reactorName = reactor.__module__
helperFile.write(resolve_helper % {'reactor': reactorName})
helperFile.close()
env = os.environ.copy()
env['PYTHONPATH'] = os.pathsep.join(sys.path)
helperDeferred = Deferred()
helperProto = ChildResolveProtocol(helperDeferred)
reactor.spawnProcess(helperProto, sys.executable, ("python", "-u", helperPath), env)
def cbFinished((reason, output, error)):
# If the output is "done 127.0.0.1\n" we don't really care what
# else happened.
output = ''.join(output)
if output != 'done 127.0.0.1\n':
self.fail((
"The child process failed to produce the desired results:\n"
" Reason for termination was: %r\n"
" Output stream was: %r\n"
" Error stream was: %r\n") % (reason.getErrorMessage(), output, ''.join(error)))
def resolveHost(self, host):
address = self.dnsCache.getCachedAddress(host)
if address != None:
logging.debug("Host cached.")
return defer.succeed(address)
else:
logging.debug("Host not cached.")
return reactor.resolve(host)
def resolveHost(self, host):
address = self.dnsCache.getCachedAddress(host)
if address != None:
logging.debug("Host cached.")
return defer.succeed(address)
else:
logging.debug("Host not cached.")
return reactor.resolve(host)