Skip to content

Instantly share code, notes, and snippets.

@svinota
Last active August 29, 2015 14:12
Show Gist options
  • Save svinota/1c530c37e341448b0d41 to your computer and use it in GitHub Desktop.
Save svinota/1c530c37e341448b0d41 to your computer and use it in GitHub Desktop.
def add_iface_to_netns(if_name, ns_name):
#
# IPDB instantiation, as well as NetNS instantiation,
# are expensive operations. NetNS spawns an additional
# process, and IPDB populates itself with all the data
# from the operating system networking.
#
# Maybe, it would be not a bad idea to keep IPDB as a
# long-running global object, or like that.
#
ipdb = IPDB()
try:
# here you open NetNS
netns = NetNS(ns_name)
iface = getattr(ipdb.interfaces, if_name)
# here the exception can be raised
with iface as veth:
veth.net_ns_fd = netns.netns
##
# in the case of an exception, this code is not called
#
netns.close()
#
# not closed netns will cause all the script to hang on exit
##
except Exception as e:
print(e)
finally:
print("Release...")
ipdb.release()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment