| 10 | |
| 11 | |
| 12 | def enter_namespace(namespace, namespace_pid): |
| 13 | if namespace: |
| 14 | namespace_dir = f'{NETNS_RUN_DIR}/{namespace}' |
| 15 | else: |
| 16 | namespace_dir = f'/proc/{namespace_pid}/ns/net' |
| 17 | |
| 18 | if not os.path.exists(namespace_dir): |
| 19 | raise Fatal('The namespace %r does not exists.' % namespace_dir) |
| 20 | |
| 21 | debug2('loading libc') |
| 22 | libc = ctypes.CDLL(ctypes.util.find_library("c"), use_errno=True) |
| 23 | |
| 24 | default_errcheck = libc.setns.errcheck |
| 25 | |
| 26 | def errcheck(ret, *args): |
| 27 | if ret == -1: |
| 28 | e = ctypes.get_errno() |
| 29 | raise Fatal(e, os.strerror(e)) |
| 30 | if default_errcheck: |
| 31 | return default_errcheck(ret, *args) |
| 32 | |
| 33 | libc.setns.errcheck = errcheck # type: ignore |
| 34 | |
| 35 | debug1('Entering namespace %r' % namespace_dir) |
| 36 | |
| 37 | with open(namespace_dir) as fd: |
| 38 | libc.setns(fd.fileno(), CLONE_NEWNET) |
| 39 | |
| 40 | debug1('Namespace %r successfully set' % namespace_dir) |