Author: tmckay
Date: 2011-08-04 16:40:02 +0000 (Thu, 04 Aug 2011)
New Revision: 4906
Modified:
trunk/sage/python/sage/util.py
Log:
Add utility routines to sage for hanlding listf of network locations.
Modified: trunk/sage/python/sage/util.py
===================================================================
--- trunk/sage/python/sage/util.py 2011-08-03 18:45:27 UTC (rev 4905)
+++ trunk/sage/python/sage/util.py 2011-08-04 16:40:02 UTC (rev 4906)
@@ -200,3 +200,79 @@
to create appropriate objects for addition to the pool.
'''
raise Exception("Not implemented")
+
+def host_port(hostname):
+ '''
+ Returns a tuple containing 'host' and 'port' strings from hostname.
+
+ Strings are split at the first colon to produce host and port strings.
+ A string containing only digits will result in a tuple with the host
+ value set to None and the port value set to the entire string. A string
+ containing non-digits but no colon will result in a tuple with the port
+ value set to None and the host value set to the entire string.
+ '''
+ assert type(hostname) in (str, unicode)
+ import string
+
+ host = None
+ port = None
+
+ info = string.split(hostname, ":", maxsplit=1)
+ if len(info) == 1:
+ # All digits, assume it was just a port number
+ if info[0].isdigit():
+ port = info[0]
+ else:
+ host = info[0]
+ else:
+ host = info[0]
+ port = info[1]
+ return host, port
+
+def host_port_list(netlocs, default_port=None):
+ '''
+ Parses a list of network locations and returns
+ a dictionary keyed by host containing sets of ports for each host.
+
+ Uses sage.util.host_port() to parse each item in the list.
+
+ netlocs -- comma-separated list of network locations. A network location
+ may have one of the following forms: 'host', 'host:port', or
'port'.
+ If the 'port' form is used, the 'host' value is assumed to be the
last
+ host encountered in the list or "localhost" if no host has been
+ encountered. If the 'host' form is used, an entry for the host is made
+ in the dictionary with an port list.
+
+ default_port -- port value for hosts in the dictionary which contain an
+ empty port set after 'netlocs' is fully parsed. Ignored if equal to None.
+ '''
+ assert type(netlocs) in (str, unicode)
+ import string
+
+ # A dictionary of sets of ports keyed
+ # by hostname
+ hosts = dict()
+ tokens = string.split(netlocs, ",")
+ lasthost = "localhost"
+ for name in tokens:
+ host, port = host_port(string.strip(name))
+ if host is None:
+ host = lasthost
+ else:
+ lasthost = host
+ if host not in hosts:
+ if port is None:
+ hosts[host] = set()
+ else:
+ hosts[host] = set([port])
+ elif port is not None:
+ hosts[host].add(port)
+
+ # Fill in default ports for hosts with no
+ # ports assigned
+ if default_port is not None:
+ for host, ports in hosts.iteritems():
+ if len(ports) == 0:
+ ports.add(default_port)
+ return hosts
+
Show replies by date