Package PyFoam :: Package Infrastructure :: Module NetworkHelpers
[hide private]
[frames] | no frames]

Source Code for Module PyFoam.Infrastructure.NetworkHelpers

 1  """Helpers for the networking functionality""" 
 2   
 3  import socket 
 4  import errno 
 5  import time 
 6   
 7  from PyFoam import configuration as config 
 8   
 9  import xmlrpclib,xml 
10   
11 -def freeServerPort(start,length=1):
12 """ 13 Finds a port that is free for serving 14 @param start: the port to start with 15 @param length: the number of ports to scan 16 @return: number of the first free port, -1 if none is found 17 """ 18 port=-1 19 20 for p in range(start,start+length): 21 sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 22 try: 23 sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) 24 sock.bind(('',p)) 25 except socket.error,e: 26 if e[0]!=errno.EADDRINUSE: 27 # sock.shutdown(2) 28 sock.close() 29 raise 30 else: 31 # sock.shutdown(2) 32 sock.close() 33 time.sleep(config().getfloat("Network","portWait")) # to avoid that the port is not available. Introduces possible race-conditons 34 port=p 35 break 36 37 38 return port
39
40 -def checkFoamServers(host,start,length=1):
41 """ 42 Finds the port on a remote host on which Foam-Servers are running 43 @param host: the IP of the host that should be checked 44 @param start: the port to start with 45 @param length: the number of ports to scan 46 @return: a list with the found ports, None if the machine is unreachable 47 """ 48 49 ports=[] 50 51 ## try: 52 ## name,alias,rest =socket.gethostbyaddr(host) 53 ## except socket.herror,reason: 54 ## # no name for the host 55 ## return None 56 57 for p in range(start,start+length): 58 sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 59 socket.setdefaulttimeout(config().getfloat("Network","socketTimeout")) 60 ok=False 61 try: 62 sock.connect((host,p)) 63 sock.close() 64 except socket.error, reason: 65 code=reason[0] 66 if code==errno.EHOSTUNREACH or code==errno.ENETUNREACH or code=="timed out" or code<0: 67 # Host unreachable: no more scanning 68 return None 69 elif code==errno.ECONNREFUSED: 70 # port does not exist 71 continue 72 else: 73 print errno.errorcode[code] 74 raise reason 75 76 try: 77 server=xmlrpclib.ServerProxy("http://%s:%d" % (host,p)) 78 ok=server.isFoamServer() 79 except xmlrpclib.ProtocolError, reason: 80 pass 81 except xml.parsers.expat.ExpatError, reason: 82 pass 83 84 if ok: 85 ports.append(p) 86 87 return ports
88