diff --git a/normalizeuri.py b/normalizeuri.py new file mode 100644 index 0000000..98faf75 --- /dev/null +++ b/normalizeuri.py @@ -0,0 +1,35 @@ +import re +import socket + +# sorry for hardwiring this ... there is no CNAME reverse lookup! +# taking the original address as unique name would need a call to +# gethostbyaddr, which might take some time - also not what we want +reverse_alias = { + 'pc15139': 'linse-c', + 'pc16392': 'linse-a', +} + + +def normalizeuri(uri): + host, sep, port = uri.partition(':') + if host[0].isdigit(): + try: + socket.setdefaulttimeout(1) + host = socket.gethostbyaddr(host)[0].split('.', 1)[0] + except socket.gaierror: + pass # keep numbered IP + finally: + socket.setdefaulttimeout(None) + else: + host = host.split('.',1 )[0] + if host == 'localhost': + host = socket.gethostname() + else: + # this resolves CNAME entries (network aliases): + host = reverse_alias.get(host, host) + # strip appended IP when a host is registered twice (at PSI): + match = re.match(r'([^-]+)-129129\d{6}$', host) + host = match.group(1) if match else host + return f'{host}{sep}{port}' + + diff --git a/secop.py b/secop.py index 663c108..a7d6b84 100644 --- a/secop.py +++ b/secop.py @@ -7,6 +7,7 @@ import logging from collections import namedtuple from select import select from streams import Stream, Base, StreamDead +from normalizeuri import normalizeuri IDN = re.compile('.*ISSE.*,SEC[oO]P,') DESCRIBING = re.compile(r'describing \S* (.*)$') @@ -139,7 +140,7 @@ class UdpStream(Base): # msg['device'] = uri.split('://', 1)[-1].split(':')[0] kwargs = msg elif kind == 'node': - uri = f"{addr}:{msg['port']}" + uri = normalizeuri(f"{addr}:{msg['port']}") kwargs = {'name': msg['equipment_id']} else: continue diff --git a/streams.py b/streams.py index f431ef0..14cf791 100644 --- a/streams.py +++ b/streams.py @@ -3,6 +3,7 @@ import time import re import logging from select import select +from normalizeuri import normalizeuri class StreamDead(Exception): @@ -34,20 +35,6 @@ class Base: logging.info('FINISH BASE') -def short_hostname(host): - """psi/lin/se special - - - treat case where -129129xxxx is appended - """ - host = socket.gethostbyaddr(host)[0] - if host == 'localhost': - host = socket.gethostname() - match = re.match(r'([^.-]+)(?:-129129\d{6}|(-[~.]*|)).psi.ch', host) - if match: - host = match.group(1) + (match.group(2) or '') - return host - - class Stream(Base): _last_time = None dead = False @@ -82,10 +69,8 @@ class Stream(Base): self.socket = socket.create_connection(parse_uri(self.uri)) self.select_read[self.socket.fileno()] = self self.settimeout(self.timeout) - host, _, port = self.uri.partition(':') - # try to convert uri to host name - self.uri = self.tags['stream'] = f'{short_hostname(host)}:{port}' - logging.info('connected %s:%s = %s', host, port, self.uri) + self.uri = self.tags['stream'] = f'{normalizeuri(self.uri)}' + logging.info('connected %s', self.uri) self._buffer = [] self._deadline = INF self._next_connect = 0