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

[core] Use psutil.process_iter to replace psutil.pids #51123

Merged
merged 3 commits into from
Mar 7, 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
10 changes: 5 additions & 5 deletions python/ray/_private/memory_monitor.py
Original file line number Diff line number Diff line change
Expand Up @@ -37,12 +37,12 @@ def get_top_n_memory_usage(n: int = 10):
Returns:
(str) The formatted string of top n process memory usage.
"""
pids = psutil.pids()
proc_stats = []
for pid in pids:
for proc in psutil.process_iter(["memory_info", "cmdline"]):
try:
proc = psutil.Process(pid)
proc_stats.append((get_rss(proc.memory_info()), pid, proc.cmdline()))
proc_stats.append(
(get_rss(proc.info["memory_info"]), proc.pid, proc.info["cmdline"])
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

proc.pid is set when Process is constructed. No need to specify it in process_iter.

)
except psutil.NoSuchProcess:
# We should skip the process that has exited. Refer this
# issue for more detail:
Expand Down Expand Up @@ -125,7 +125,7 @@ def __init__(self, error_threshold=0.95, check_interval=1):
except IOError:
self.cgroup_memory_limit_gb = sys.maxsize / (1024**3)
if not psutil:
logger.warn(
logger.warning(
"WARNING: Not monitoring node memory since `psutil` "
"is not installed. Install this with "
"`pip install psutil` to enable "
Expand Down
24 changes: 19 additions & 5 deletions python/ray/_private/services.py
Original file line number Diff line number Diff line change
Expand Up @@ -340,23 +340,21 @@ def _find_address_from_flag(flag: str):

# The --redis-address here is what is now called the --address, but it
# appears in the default_worker.py and agent.py calls as --redis-address.
pids = psutil.pids()
addresses = set()
for pid in pids:
for proc in psutil.process_iter(["cmdline"]):
try:
proc = psutil.Process(pid)
# HACK: Workaround for UNIX idiosyncrasy
# Normally, cmdline() is supposed to return the argument list.
# But it in some cases (such as when setproctitle is called),
# an arbitrary string resembling a command-line is stored in
# the first argument.
# Explanation: https://unix.stackexchange.com/a/432681
# More info: https://github.com/giampaolo/psutil/issues/1179
cmdline = proc.cmdline()
cmdline = proc.info["cmdline"]
# NOTE(kfstorm): To support Windows, we can't use
# `os.path.basename(cmdline[0]) == "raylet"` here.

if len(cmdline) > 0 and "raylet" in os.path.basename(cmdline[0]):
if _is_raylet_process(cmdline):
for arglist in cmdline:
# Given we're merely seeking --redis-address, we just split
# every argument on spaces for now.
Expand Down Expand Up @@ -2289,3 +2287,19 @@ def start_ray_client_server(
fate_share=fate_share,
)
return process_info


def _is_raylet_process(cmdline: Optional[List[str]]) -> bool:
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

What about taking a proc object directly?

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I may prefer to use cmdline to avoid passing the whole Process object into this function. This makes it easier for us to write mock data for unit tests if needed. Another reason is to avoid using proc.info["cmdline"] in this function so that we can clearly determine that cmdline is used in the loop above; and we can easily know why do we use psutil.process_iter(["cmdline"]).

"""Check if the command line belongs to a raylet process.

Args:
cmdline: List of command line arguments or None

Returns:
bool: True if this is a raylet process, False otherwise
"""
if cmdline is None or len(cmdline) == 0:
return False

executable = os.path.basename(cmdline[0])
return "raylet" in executable
8 changes: 4 additions & 4 deletions python/ray/_private/test_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -2130,11 +2130,11 @@ def get_gcs_memory_used():
import psutil

m = {
process.name(): process.memory_info().rss
for process in psutil.process_iter()
proc.info["name"]: proc.info["memory_info"].rss
for proc in psutil.process_iter(["status", "name", "memory_info"])
if (
process.status() not in (psutil.STATUS_ZOMBIE, psutil.STATUS_DEAD)
and process.name() in ("gcs_server", "redis-server")
proc.info["status"] not in (psutil.STATUS_ZOMBIE, psutil.STATUS_DEAD)
and proc.info["name"] in ("gcs_server", "redis-server")
)
}
assert "gcs_server" in m
Expand Down