Commit 36c3ad8b authored by zhifan huang's avatar zhifan huang

fix testhmac

parent 5e81ade3
from binascii import b2a_hex
import psutil
import logging
BABEL_HMAC = 'babel_hmac0', 'babel_hmac1', 'babel_hmac2'
def getConfig(db, name):
r = db.execute("SELECT value FROM config WHERE name=?", (name,)).fetchone()
if r:
return b2a_hex(*r)
def checkHMAC(db, machines):
hmac = [getConfig(db, k) for k in BABEL_HMAC]
rc = True
for x in psutil.Process().children(True):
if x.name() == 'babeld':
sign = accept = None
args = x.cmdline()
for x in args:
if x.endswith('/babeld.log'):
if x[:-11].split('/')[-1] not in machines:
break
elif x.startswith('key '):
x = x.split()
if 'sign' in x:
sign = x[-1]
elif 'accept' in x:
accept = x[-1]
else:
i = 0 if hmac[0] else 1
if hmac[i] != sign or hmac[i+1] != accept:
logging.debug('HMAC config wrong for in %s' % args)
rc = False
if rc:
logging.debug('All nodes use Babel with the correct HMAC configuration')
else:
logging.debug('Expected config: %s' % dict(zip(BABEL_HMAC, hmac)))
return rc
clean_ruleset_interval=600
allow 1024-65535 10.0.0.0/8 1024-65535
deny 0-65535 0.0.0.0/0 0-65535
...@@ -131,8 +131,12 @@ class Netns(object): ...@@ -131,8 +131,12 @@ class Netns(object):
return dev1, dev2 return dev1, dev2
def __del__(self): def __del__(self):
self.app.terminate()
self.app.wait()
try: try:
self.proc.terminate() self.proc.terminate()
self.proc.wait()
except: except:
pass pass
......
...@@ -38,6 +38,15 @@ def ip_to_serial(ip6): ...@@ -38,6 +38,15 @@ def ip_to_serial(ip6):
return int(ip6, 16) return int(ip6, 16)
def wait_ps(p, timeout=1, sec=0.1):
"""implement timeout of wait"""
now = time.time()
while time.time() -timeout < now:
if p.poll() is not None:
return
time.sleep(sec)
raise Exception("{}, not terminate".format(p.pid))
class Re6stRegistry(object): class Re6stRegistry(object):
"""class run a re6st-registry service on a namespace""" """class run a re6st-registry service on a namespace"""
registry_seq = 0 registry_seq = 0
...@@ -119,17 +128,22 @@ class Re6stRegistry(object): ...@@ -119,17 +128,22 @@ class Re6stRegistry(object):
def clean(self): def clean(self):
"""remove the file created last time""" """remove the file created last time"""
for f in [self.db, self.log]: for f in [self.log]:
if f.exists(): if f.exists():
f.unlink() f.unlink()
def __del__(self): def __del__(self):
try: try:
logging.debug("teminate process {}".format(self.proc.pid))
self.proc.terminate() self.proc.terminate()
shutil.rmtree(self.run_path) self.proc.wait(1)
except: except:
pass pass
# cleaned by node with the registry
# shutil.rmtree(self.run_path)
class Re6stNode(object): class Re6stNode(object):
"""class run a re6stnet service on a namespace""" """class run a re6stnet service on a namespace"""
node_seq = 0 node_seq = 0
...@@ -146,7 +160,11 @@ class Re6stNode(object): ...@@ -146,7 +160,11 @@ class Re6stNode(object):
self.path = WORK_DIR / self.name self.path = WORK_DIR / self.name
self.email = self.name + "@example.com" self.email = self.name + "@example.com"
self.run_path = tempfile.mkdtemp() if self.name == self.registry.name:
self.run_path = self.registry.run_path
else:
self.run_path = tempfile.mkdtemp()
self.log = self.path / "re6stnet.log" self.log = self.path / "re6stnet.log"
self.crt = self.path / "cert.crt" self.crt = self.path / "cert.crt"
self.key = self.path / 'cert.key' self.key = self.path / 'cert.key'
...@@ -233,14 +251,23 @@ class Re6stNode(object): ...@@ -233,14 +251,23 @@ class Re6stNode(object):
def clean(self): def clean(self):
"""remove the file created last time""" """remove the file created last time"""
for name in ["re6stnet.log", "babeld.state", "cache.db"]: for name in ["re6stnet.log", "babeld.state", "cache.db", "babeld.log"]:
f = self.path / name f = self.path / name
if f.exists(): if f.exists():
f.unlink() f.unlink()
def __del__(self): def __del__(self):
"""teminate process and rm temp dir"""
try: try:
logging.debug("{} teminate process {}".format(self.name, self.proc.pid))
self.proc.terminate() self.proc.terminate()
shutil.rmtree(self.run_path) # timeout only in python3. deadlock maybe
except: wait_ps(self.proc)
pass except Exception as e:
logging.warn("{}: {}".format(self.name, e))
# try:
# shutil.rmtree(self.run_path)
# except Exception as e:
# logging.error("{}: {}".format(self.name, e))
...@@ -3,6 +3,7 @@ import unittest ...@@ -3,6 +3,7 @@ import unittest
import time import time
import subprocess import subprocess
import sys import sys
import psutil
import os import os
import logging import logging
import sqlite3 import sqlite3
...@@ -21,7 +22,7 @@ def deploy_re6st(nm): ...@@ -21,7 +22,7 @@ def deploy_re6st(nm):
re6st_wrap.Re6stRegistry.registry_seq = 0 re6st_wrap.Re6stRegistry.registry_seq = 0
re6st_wrap.Re6stNode.node_seq = 0 re6st_wrap.Re6stNode.node_seq = 0
for registry in net: for registry in net:
reg = re6st_wrap.Re6stRegistry(registry, "2001:db8:42::", recreate=True) reg = re6st_wrap.Re6stRegistry(registry, "2001:db8:42::", recreate=False)
reg_node = re6st_wrap.Re6stNode(registry, reg, name=reg.name) reg_node = re6st_wrap.Re6stNode(registry, reg, name=reg.name)
registrys.append(reg) registrys.append(reg)
reg_node.run("--gateway", "--disable-proto", "none", "--ip", registry.ip) reg_node.run("--gateway", "--disable-proto", "none", "--ip", registry.ip)
...@@ -87,36 +88,43 @@ class TestNet(unittest.TestCase): ...@@ -87,36 +88,43 @@ class TestNet(unittest.TestCase):
@classmethod @classmethod
def setUpClass(cls): def setUpClass(cls):
"""create work dir""" """create work dir"""
# logging.basicConfig(level=logging.INFO) logging.basicConfig(level=logging.INFO)
re6st_wrap.initial() re6st_wrap.initial()
@classmethod @classmethod
def tearDown(cls): def tearDown(cls):
# logging.basicConfig(level=logging.WARNING) # logging.basicConfig(level=logging.WARNING)
pass # clean all the running process
for p in psutil.Process().children():
# def test_ping_demo(self): logging.warning("unterminate subprocess, name: {}, pid: {}, status: {}, cmd: {}".format(p.name(), p.pid, p.status(), p.cmdline()))
# """create a network demo, test the connectivity by ping # try:
# wait at most 60 seconds, and test each node ping to other by ipv6 addr # p.kill()
# """ # except:
# nm = my_net.net_demo() # pass
# nodes, registrys = deploy_re6st(nm)
# # wait 60, if the re6stnet stable quit wait def test_ping_demo(self):
# wait_stable(nodes, 50) """create a network demo, test the connectivity by ping
# time.sleep(10) wait at most 60 seconds, and test each node ping to other by ipv6 addr
"""
# self.assertFalse(wait_stable(nodes, 40), " ping test failed") nm = my_net.net_demo()
nodes, registrys = deploy_re6st(nm)
# wait 60, if the re6stnet stable quit wait
wait_stable(nodes, 50)
time.sleep(10)
self.assertFalse(wait_stable(nodes, 30), " ping test failed")
# def test_ping_router(self): def test_ping_router(self):
# """create a network in a net segment, test the connectivity by ping """create a network in a net segment, test the connectivity by ping
# """ """
# nm = my_net.net_route() nm = my_net.net_route()
# nodes, registrys = deploy_re6st(nm) nodes, registrys = deploy_re6st(nm)
# wait_stable(nodes) wait_stable(nodes, 50)
# for i in range(3): time.sleep(10)
# time.sleep(20)
# self.assertFalse(ping_test(nodes), "N.{} ping test failed".format(i)) self.assertFalse(wait_stable(nodes, 40), " ping test failed")
def test_hmac(self): def test_hmac(self):
"""create a network demo, and run hmac test, this test check hmac 3 times """create a network demo, and run hmac test, this test check hmac 3 times
...@@ -130,12 +138,12 @@ class TestNet(unittest.TestCase): ...@@ -130,12 +138,12 @@ class TestNet(unittest.TestCase):
registry = registrys[0] registry = registrys[0]
machine1 = nodes[1] machine1 = nodes[1]
reg1_db = sqlite3.connect(str(registry.db), isolation_level=None, check_same_thread=False) reg1_db = sqlite3.connect(str(registry.db), isolation_level=None, check_same_thread=False)
print reg1_db.text_factory
reg1_db.text_factory = str # reg1_db.text_factory = str
m_net1 = [node.name for node in nodes] m_net1 = [node.name for node in nodes]
# wait net stable # wait net stable
time.sleep(45) time.sleep(100)
logging.info('Check that the initial HMAC config is deployed on network 1') logging.info('Check that the initial HMAC config is deployed on network 1')
self.assertTrue(hmac.checkHMAC(reg1_db, m_net1), "first hmac check failed") self.assertTrue(hmac.checkHMAC(reg1_db, m_net1), "first hmac check failed")
...@@ -148,25 +156,26 @@ class TestNet(unittest.TestCase): ...@@ -148,25 +156,26 @@ class TestNet(unittest.TestCase):
# Checking HMAC on machines connected to registry 1... # Checking HMAC on machines connected to registry 1...
self.assertTrue(hmac.checkHMAC(reg1_db, m_net1), "second hmac check failed: HMAC update don't work") self.assertTrue(hmac.checkHMAC(reg1_db, m_net1), "second hmac check failed: HMAC update don't work")
# check if one machine restarted # # check if one machine restarted
logging.info('Test that machines can update upon reboot ' logging.info('Test that machines can update upon reboot '
'when they were off during a HMAC update.') 'when they were off during a HMAC update.')
logging.info('Re6st on {} is stopped'.format(machine1.name)) logging.info('Re6st on {} is stopped'.format(machine1.name))
machine1.proc.kill() machine1.proc.terminate()
machine1.proc.wait()
time.sleep(5) time.sleep(5)
registry.node.run(updateHMAC) registry.node.run(updateHMAC)
logging.info('Updated HMAC on registry (config = hmac1 & hmac2), waiting...') logging.info('Updated HMAC on registry (config = hmac1 & hmac2), waiting...')
time.sleep(60) time.sleep(60)
machine1.run() machine1.run()
logging.info( 'Started re6st on {}, waiting for it to get new conf'.format(machine1.name)) logging.info( 'Started re6st on {}, waiting for it'.format(machine1.name))
time.sleep(80) time.sleep(100)
# logging.info( 'Checking HMAC on machines connected to registry 1...') # logging.info( 'Checking HMAC on machines connected to registry 1...')
self.assertTrue(hmac.checkHMAC(reg1_db, m_net1), "third hmac check failed: machine restart failed") self.assertTrue(hmac.checkHMAC(reg1_db, m_net1), "third hmac check failed: machine restart failed")
logging.info( 'Testing of HMAC done!') logging.info( 'Testing of HMAC done!')
reg1_db.close() reg1_db.close()
if __name__ == "__main__": if __name__ == "__main__":
logging.basicConfig(level=logging.DEBUG, filename='test.log', filemode='w') logging.basicConfig(level=logging.DEBUG, filename='test.log', filemode='w')
unittest.main(verbosity=3) unittest.main(verbosity=3)
......
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