Skip to content

Commit e11bf7d

Browse files
Support older version of psutil (RHEL7 and RHEL6) (#2808) (#3189)
* Support older version of psutil (RHEL7 and RHEL6) The psutil python module is a true mess, they changed the API twice. The function arguments, as well as the objects that are returned. The documentation does not make it clear which version supports what so the safest implementation is this waterfall approach. A better approach would be to inspect the returned information, rather than trust a version, but that would not be any more efficient. In the end it is better to have something that at least works out-of-the-box on all platforms than something that requires custom updates to system packages before it works as expected. Especially for something as basic as `pids`. * A little bit more concise * Apply suggestions from code review * Add changelog fragment. Co-authored-by: Felix Fontein <felix@fontein.de> (cherry picked from commit b5d6457) Co-authored-by: Dag Wieers <dag@wieers.com>
1 parent 889989a commit e11bf7d

2 files changed

Lines changed: 16 additions & 5 deletions

File tree

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
bugfixes:
2+
- "pids - avoid crashes for older ``psutil`` versions, like on RHEL6 and RHEL7 (https://github.com/ansible-collections/community.general/pull/2808)."

plugins/modules/system/pids.py

Lines changed: 14 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -79,11 +79,20 @@ def compare_lower(a, b):
7979
def get_pid(name):
8080
pids = []
8181

82-
for proc in psutil.process_iter(attrs=['name', 'cmdline']):
83-
if compare_lower(proc.info['name'], name) or \
84-
proc.info['cmdline'] and compare_lower(proc.info['cmdline'][0], name):
85-
pids.append(proc.pid)
86-
82+
try:
83+
for proc in psutil.process_iter(attrs=['name', 'cmdline']):
84+
if compare_lower(proc.info['name'], name) or \
85+
proc.info['cmdline'] and compare_lower(proc.info['cmdline'][0], name):
86+
pids.append(proc.pid)
87+
except TypeError: # EL6, EL7: process_iter() takes no arguments (1 given)
88+
for proc in psutil.process_iter():
89+
try: # EL7
90+
proc_name, proc_cmdline = proc.name(), proc.cmdline()
91+
except TypeError: # EL6: 'str' object is not callable
92+
proc_name, proc_cmdline = proc.name, proc.cmdline
93+
if compare_lower(proc_name, name) or \
94+
proc_cmdline and compare_lower(proc_cmdline[0], name):
95+
pids.append(proc.pid)
8796
return pids
8897

8998

0 commit comments

Comments
 (0)