Commit 64d10c7f authored by Tom Niget's avatar Tom Niget Committed by Tom Niget

wip: add more resource cleanups to remove ResourceWarnings

Python3 added automatic detection of leaked resources, which causes lots of warnings in Re6st, mostly because of unclosed subprocess streams.
parent 6f404adc
...@@ -83,7 +83,8 @@ if args.duration: ...@@ -83,7 +83,8 @@ if args.duration:
signal.signal(signal.SIGALRM, handler) signal.signal(signal.SIGALRM, handler)
signal.alarm(args.duration) signal.alarm(args.duration)
exec(compile(open("fixnemu.py", "rb").read(), "fixnemu.py", 'exec')) with open('fixnemu.py', 'rb') as f:
exec(compile(f.read(), 'fixnemu.py', 'exec'))
class Re6stNode(nemu.Node): class Re6stNode(nemu.Node):
......
...@@ -30,4 +30,5 @@ def __file__(): ...@@ -30,4 +30,5 @@ def __file__():
return os.path.join(sys.path[0], sys.argv[1]) return os.path.join(sys.path[0], sys.argv[1])
__file__ = __file__() __file__ = __file__()
exec(compile(open(__file__, "rb").read(), __file__, 'exec')) with open(__file__) as f:
exec(compile(f.read(), __file__, 'exec'))
\ No newline at end of file
...@@ -77,9 +77,10 @@ def main(): ...@@ -77,9 +77,10 @@ def main():
print("WARNING: it is strongly recommended to use --fingerprint option.") print("WARNING: it is strongly recommended to use --fingerprint option.")
network = x509.networkFromCa(ca) network = x509.networkFromCa(ca)
if config.is_needed: if config.is_needed:
route, err = subprocess.Popen(('ip', '-6', '-o', 'route', 'get', with subprocess.Popen(('ip', '-6', '-o', 'route', 'get',
utils.ipFromBin(network)), utils.ipFromBin(network)),
stdout=subprocess.PIPE).communicate() stdout=subprocess.PIPE) as proc:
route, err = proc.communicate()
sys.exit(err or route and sys.exit(err or route and
utils.binFromIp(route.split()[8]).startswith(network)) utils.binFromIp(route.split()[8]).startswith(network))
...@@ -90,7 +91,7 @@ def main(): ...@@ -90,7 +91,7 @@ def main():
reserved = 'CN', 'serial' reserved = 'CN', 'serial'
req = crypto.X509Req() req = crypto.X509Req()
try: try:
with open(cert_path) as f: with open(cert_path, "rb") as f:
cert = loadCert(f.read()) cert = loadCert(f.read())
components = dict(cert.get_subject().get_components()) components = dict(cert.get_subject().get_components())
components = {k.decode(): v for k, v in components.items()} components = {k.decode(): v for k, v in components.items()}
......
...@@ -266,8 +266,8 @@ def main(): ...@@ -266,8 +266,8 @@ def main():
def call(cmd): def call(cmd):
logging.debug('%r', cmd) logging.debug('%r', cmd)
p = subprocess.Popen(cmd, stdout=subprocess.PIPE, with subprocess.Popen(cmd, stdout=subprocess.PIPE,
stderr=subprocess.PIPE) stderr=subprocess.PIPE) as p:
stdout, stderr = p.communicate() stdout, stderr = p.communicate()
if p.returncode: if p.returncode:
raise EnvironmentError("%r failed with error %u\n%s" raise EnvironmentError("%r failed with error %u\n%s"
......
...@@ -155,6 +155,11 @@ class RegistryServer: ...@@ -155,6 +155,11 @@ class RegistryServer:
else: else:
self.newHMAC(0) self.newHMAC(0)
def close(self):
self.sock.close()
self.db.close()
self.ctl.close()
def getConfig(self, name, *default): def getConfig(self, name, *default):
r, = next(self.db.execute( r, = next(self.db.execute(
"SELECT value FROM config WHERE name=?", (name,)), default) "SELECT value FROM config WHERE name=?", (name,)), default)
......
...@@ -42,6 +42,8 @@ class TestRegistryClientInteract(unittest.TestCase): ...@@ -42,6 +42,8 @@ class TestRegistryClientInteract(unittest.TestCase):
def tearDown(self): def tearDown(self):
self.server.proc.terminate() self.server.proc.terminate()
with self.server.proc:
pass
def test_1_main(self): def test_1_main(self):
""" a client interact a server, no re6stnet node test basic function""" """ a client interact a server, no re6stnet node test basic function"""
......
...@@ -62,7 +62,7 @@ class NetManager: ...@@ -62,7 +62,7 @@ class NetManager:
""" """
for reg, nodes in self.registries.items(): for reg, nodes in self.registries.items():
for node in nodes: for node in nodes:
app0 = node.Popen(["ping", "-c", "1", reg.ip], stdout=PIPE) with node.Popen(["ping", "-c", "1", reg.ip], stdout=PIPE) as app0:
ret = app0.wait() ret = app0.wait()
if ret: if ret:
raise ConnectableError( raise ConnectableError(
......
...@@ -136,6 +136,8 @@ class Re6stRegistry: ...@@ -136,6 +136,8 @@ class Re6stRegistry:
try: try:
logging.debug("teminate process %s", self.proc.pid) logging.debug("teminate process %s", self.proc.pid)
self.proc.destroy() self.proc.destroy()
with self.proc:
pass
except: except:
pass pass
...@@ -262,6 +264,8 @@ class Re6stNode: ...@@ -262,6 +264,8 @@ class Re6stNode:
"""stop running re6stnet process""" """stop running re6stnet process"""
logging.debug("%s teminate process %s", self.name, self.proc.pid) logging.debug("%s teminate process %s", self.name, self.proc.pid)
self.proc.destroy() self.proc.destroy()
with self.proc:
pass
def __del__(self): def __del__(self):
"""teminate process and rm temp dir""" """teminate process and rm temp dir"""
......
...@@ -31,6 +31,14 @@ def deploy_re6st(nm, recreate=False): ...@@ -31,6 +31,14 @@ def deploy_re6st(nm, recreate=False):
nodes.append(node) nodes.append(node)
return nodes, registries return nodes, registries
def clean_re6st(nodes, registries):
for node in nodes:
node.node.destroy()
node.stop()
for reg in registries:
reg.__del__()
def wait_stable(nodes, timeout=240): def wait_stable(nodes, timeout=240):
"""try use ping6 from each node to the other until ping success to all the """try use ping6 from each node to the other until ping success to all the
other nodes other nodes
...@@ -94,20 +102,22 @@ class TestNet(unittest.TestCase): ...@@ -94,20 +102,22 @@ class TestNet(unittest.TestCase):
"""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 = network_build.net_route() nm = network_build.net_route()
nodes, _ = deploy_re6st(nm) nodes, registries = deploy_re6st(nm)
wait_stable(nodes, 40) wait_stable(nodes, 40)
time.sleep(10) time.sleep(10)
self.assertTrue(wait_stable(nodes, 30), " ping test failed") self.assertTrue(wait_stable(nodes, 30), " ping test failed")
clean_re6st(nodes, registries)
@unittest.skip("usually failed due to UPnP problem") @unittest.skip("usually failed due to UPnP problem")
def test_reboot_one_machine(self): def test_reboot_one_machine(self):
"""create a network demo, wait the net stable, reboot on machine, """create a network demo, wait the net stable, reboot on machine,
then test if network recover, this test seems always failed then test if network recover, this test seems always failed
""" """
nm = network_build.net_demo() nm = network_build.net_demo()
nodes, _ = deploy_re6st(nm) nodes, registries = deploy_re6st(nm)
wait_stable(nodes, 100) wait_stable(nodes, 100)
...@@ -121,12 +131,14 @@ class TestNet(unittest.TestCase): ...@@ -121,12 +131,14 @@ class TestNet(unittest.TestCase):
self.assertTrue(wait_stable(nodes, 400), "network can't recover") self.assertTrue(wait_stable(nodes, 400), "network can't recover")
clean_re6st(nodes, registries)
def test_reboot_one_machine_router(self): def test_reboot_one_machine_router(self):
"""create a network router, wait the net stable, reboot on machine, """create a network router, wait the net stable, reboot on machine,
then test if network recover, then test if network recover,
""" """
nm = network_build.net_route() nm = network_build.net_route()
nodes, _ = deploy_re6st(nm) nodes, registries = deploy_re6st(nm)
wait_stable(nodes, 40) wait_stable(nodes, 40)
...@@ -140,6 +152,8 @@ class TestNet(unittest.TestCase): ...@@ -140,6 +152,8 @@ class TestNet(unittest.TestCase):
self.assertTrue(wait_stable(nodes, 100), "network can't recover") self.assertTrue(wait_stable(nodes, 100), "network can't recover")
clean_re6st(nodes, registries)
if __name__ == "__main__": if __name__ == "__main__":
......
...@@ -70,6 +70,7 @@ class TestRegistryServer(unittest.TestCase): ...@@ -70,6 +70,7 @@ class TestRegistryServer(unittest.TestCase):
@classmethod @classmethod
def tearDownClass(cls): def tearDownClass(cls):
cls.server.close()
# remove database # remove database
for file in [cls.config.db, cls.config.ca, cls.config.key]: for file in [cls.config.db, cls.config.ca, cls.config.key]:
try: try:
......
...@@ -103,7 +103,7 @@ def decrypt(pkey, incontent): ...@@ -103,7 +103,7 @@ def decrypt(pkey, incontent):
with open("node.key", 'w') as f: with open("node.key", 'w') as f:
f.write(pkey.decode()) f.write(pkey.decode())
args = "openssl rsautl -decrypt -inkey node.key".split() args = "openssl rsautl -decrypt -inkey node.key".split()
p = subprocess.Popen( with subprocess.Popen(
args, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE) args, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE) as p:
outcontent, err = p.communicate(incontent) outcontent, err = p.communicate(incontent)
return outcontent return outcontent
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