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

Source Code for Module PyFoam.Infrastructure.NetworkHelpers

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