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 all commits
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
16 changes: 16 additions & 0 deletions granulate_utils/linux/ns.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@
import os
import re
from collections import deque
from functools import lru_cache
from pathlib import Path
from threading import Thread
from typing import Callable, Collection, List, Optional, TypeVar, Union
Expand Down Expand Up @@ -273,6 +274,21 @@ def _switch_and_run():
return ret


@lru_cache(maxsize=None)
def is_root() -> bool:
pcarella1 marked this conversation as resolved.
Show resolved Hide resolved
return os.geteuid() == 0


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


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
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