Commit a40a6d78 authored by Alejandro Homs Puron's avatar Alejandro Homs Puron Committed by operator for beamline

eiger_flash: refactor DirectEthernetConnection IPv4 code

parent 33b03a5a
......@@ -8,6 +8,7 @@ import re
import time
import errno
import socket
import functools
from getopt import getopt
from telnetlib import Telnet
......@@ -24,21 +25,25 @@ def get_eiger_executables_dir():
def get_domain_name():
return socket.getfqdn().strip(socket.gethostname())
get_inet_ip = functools.partial(socket.inet_pton, socket.AF_INET)
def get_route_table():
route = Popen(['/sbin/route', '-n'], stdout=PIPE)
ip_re_str = '([0-9]{1,3}\\.){3}[0-9]{1,3}'
route_re_str = ('(?P<dest>{0}){1}(?P<gw>{0}){1}(?P<mask>{0}){1}'
'(?P<flags_metric_ref_use>({2}{1}){{4}})'
'(?P<iface>{2})').format(ip_re_str, '[ \t]+', '[^ \t]+')
ip_re_str = '\\.'.join(['[0-9]{1,3}'] * 4)
route_ip_group = ['dest', 'gw', 'mask']
route_str_group = ['flags', 'metric', 'ref', 'use', 'iface']
route_re_list = [('(?P<%s>{0})' % k) for k in route_ip_group]
route_re_list += [('(?P<%s>{1})' % k) for k in route_str_group]
route_re_format = '{2}'.join(route_re_list)
route_re_str = route_re_format.format(ip_re_str, '[^ \t]+', '[ \t]+')
route_re = re.compile(route_re_str)
route_table = {}
route_table = []
for l in route.stdout.readlines():
m = route_re.match(l.strip())
if not m:
continue
d = [(k, socket.inet_pton(socket.AF_INET, m.group(k)))
for k in ['dest', 'gw', 'mask']]
route_table[m.group('iface')] = dict(d)
if m:
d = dict([(k, m.group(k)) for k in route_str_group])
d.update([(k, get_inet_ip(m.group(k))) for k in route_ip_group])
route_table.append(d)
return route_table
def get_masked_ip(addr, mask):
......@@ -63,15 +68,14 @@ class DirectEthernetConnection(Connection):
def __init__(self, name):
super(DirectEthernetConnection, self).__init__(name)
ip = socket.inet_pton(socket.AF_INET, self.addr)
null = '\x00' * 4
for iface, d in get_route_table().items():
if d['dest'] != null and get_masked_ip(ip, d['mask']) == d['dest']:
self.iface = iface
break
else:
raise RuntimeError('%s is not directly connected' % name)
ip = get_inet_ip(self.addr)
default_gw = lambda d: d['dest'] == get_inet_ip('0.0.0.0')
good_subnet = lambda d: get_masked_ip(ip, d['mask']) == d['dest']
ifaces = [d['iface'] for d in get_route_table()
if not default_gw(d) and good_subnet(d)]
if not ifaces:
raise RuntimeError('Cannot find direct link to %s' % name)
self.iface = ifaces[0]
def restart(self):
print '[%s] Disabling %s ...' % (self.name, self.iface)
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment