| 1 |
|
| 2 |
|
| 3 |
|
| 4 |
|
| 5 |
|
| 6 |
|
| 7 |
|
| 8 |
|
| 9 |
|
| 10 |
|
| 11 |
|
| 12 |
|
| 13 |
|
| 14 |
|
| 15 |
|
| 16 |
import contextlib |
| 17 |
import os |
| 18 |
|
| 19 |
from oslo_log import log as logging |
| 20 |
from pyroute2 import netns as pynetns |
| 21 |
|
| 22 |
from neutron_fwaas._i18n import _ |
| 23 |
|
| 24 |
|
| 25 |
PROCESS_NETNS = '/proc/self/ns/net' |
| 26 |
|
| 27 |
LOG = logging.getLogger(__name__) |
| 28 |
|
| 29 |
|
| 30 |
class BackInNamespaceExit(SystemExit): |
| 31 |
"""Raised if we fail to moved back process in its original namespace.""" |
| 32 |
|
| 33 |
|
| 34 |
@contextlib.contextmanager |
| 35 |
def in_namespace(namespace): |
| 36 |
"""Move current process in a specific namespace. |
| 37 |
|
| 38 |
This contextmanager moves current process in a specific namespace and |
| 39 |
ensures to move it back in original namespace or kills it if we fail to |
| 40 |
move back in original namespace. |
| 41 |
""" |
| 42 |
if not namespace: |
| 43 |
yield |
| 44 |
return |
| 45 |
|
| 46 |
org_netns_fd = os.open(PROCESS_NETNS, os.O_RDONLY) |
| 47 |
pynetns.setns(namespace) |
| 48 |
try: |
| 49 |
yield |
| 50 |
finally: |
| 51 |
try: |
| 52 |
|
| 53 |
|
| 54 |
pynetns.setns(org_netns_fd) |
| 55 |
except Exception as e: |
| 56 |
msg = _('Failed to move back in original netns: %s') % e |
| 57 |
LOG.critical(msg) |
| 58 |
raise BackInNamespaceExit(msg) |