Debian Codegraph @

neutron_fwaas/privileged/utils.py

raw symbols SCIP
1 # Copyright (c) 2017 Thales Services SAS
2 # All Rights Reserved.
3 #
4 # Licensed under the Apache License, Version 2.0 (the "License"); you may
5 # not use this file except in compliance with the License. You may obtain
6 # a copy of the License at
7 #
8 # http://www.apache.org/licenses/LICENSE-2.0
9 #
10 # Unless required by applicable law or agreed to in writing, software
11 # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
12 # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13 # License for the specific language governing permissions and limitations
14 # under the License.
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 # NOTE(cby): this code is not executed only if we fail to
53 # move in target namespace
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)