Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Added run_in_ns_wrapper to only run in namespace when root is detected. #265

Merged
merged 3 commits into from
Jan 29, 2025
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
36 changes: 34 additions & 2 deletions granulate_utils/linux/ns.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,10 +18,11 @@
import enum
import os
import re
import sys
from collections import deque
from pathlib import Path
from threading import Thread
from typing import Callable, Collection, List, Optional, TypeVar, Union
from typing import Callable, Collection, List, Optional, TypeVar, Union, cast

from psutil import NoSuchProcess, Process, process_iter

Expand Down Expand Up @@ -180,7 +181,7 @@ def _find_inner_pid() -> Optional[int]:
return None

# We're searching `/proc`, so we only need to set our mount namespace
inner_pid = run_in_ns(["mnt"], _find_inner_pid, process.pid)
inner_pid = run_in_ns_wrapper(["mnt"], _find_inner_pid, process.pid)
sobolron marked this conversation as resolved.
Show resolved Hide resolved
if inner_pid is not None:
if not process.is_running(): # Make sure the pid wasn't reused for another process
raise NoSuchProcess(process.pid)
Expand Down Expand Up @@ -273,6 +274,37 @@ def _switch_and_run():
return ret


def is_this_root() -> bool:
sobolron marked this conversation as resolved.
Show resolved Hide resolved
if sys.platform == "win32":
return cast(int, ctypes.windll.shell32.IsUserAnAdmin()) == 1 # type: ignore
else:
return os.geteuid() == 0
pcarella1 marked this conversation as resolved.
Show resolved Hide resolved


def run_in_ns_wrapper(
nstypes: List[str],
callback: Callable[[], T],
target_pid: int = 1,
) -> T:
if is_this_root():
return run_in_ns(nstypes, callback, target_pid)

ret: Union[T, _Sentinel] = _SENTINEL
exc: Optional[BaseException] = None

try:
ret = callback()
except BaseException as e:
exc = e

if isinstance(ret, _Sentinel):
assert exc is not None
raise exc
else:
assert exc is None
return ret
sobolron marked this conversation as resolved.
Show resolved Hide resolved


def get_mnt_ns_ancestor(process: Process) -> Process:
"""
Gets the topmost ancestor of "process" that runs in the same mount namespace of "process".
Expand Down
2 changes: 1 addition & 1 deletion granulate_utils/linux/proc_events.py
Original file line number Diff line number Diff line change
Expand Up @@ -269,7 +269,7 @@ def wrapper(*args, **kwargs):
if _proc_events_listener is None:
try:
# needs to run in init net NS - see netlink_kernel_create() call on init_net in cn_init().
_proc_events_listener = ns.run_in_ns(["net"], _start_listener)
_proc_events_listener = ns.run_in_ns_wrapper(["net"], _start_listener)
sobolron marked this conversation as resolved.
Show resolved Hide resolved
except Exception:
# TODO: We leak the pipe FDs here...
_proc_events_listener = None
Expand Down
4 changes: 2 additions & 2 deletions granulate_utils/metadata/cloud.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@

from granulate_utils.exceptions import BadResponseCode
from granulate_utils.futures import call_in_parallel
from granulate_utils.linux.ns import run_in_ns
from granulate_utils.linux.ns import run_in_ns_wrapper
from granulate_utils.metadata import Metadata

METADATA_REQUEST_TIMEOUT = 5
Expand Down Expand Up @@ -229,7 +229,7 @@ def _fetch() -> Optional[Metadata]:
return None

try:
metadata = run_in_ns(["net"], _fetch)
metadata = run_in_ns_wrapper(["net"], _fetch)
if metadata is not None:
return metadata
except TimeoutError as exception:
Expand Down