Debian Codegraph @

ansible_collections/community/general/plugins/modules/pids.py

raw
1 #!/usr/bin/python
2 # Copyright (c) 2019, Saranya Sridharan
3 # GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt)
4 # SPDX-License-Identifier: GPL-3.0-or-later
5
6 from __future__ import annotations
7
8 DOCUMENTATION = r"""
9 module: pids
10 description: "Retrieves a list of PIDs of given process name in Ansible controller/controlled machines. Returns an empty list
11 if no process in that name exists."
12 short_description: Retrieves process IDs list if the process is running otherwise return empty list
13 author:
14 - Saranya Sridharan (@saranyasridharan)
15 requirements:
16 - psutil(python module)
17 extends_documentation_fragment:
18 - community.general._attributes
19 attributes:
20 check_mode:
21 support: full
22 diff_mode:
23 support: none
24 options:
25 name:
26 description: The name of the process(es) you want to get PID(s) for.
27 type: str
28 pattern:
29 description: The pattern (regular expression) to match the process(es) you want to get PID(s) for.
30 type: str
31 version_added: 3.0.0
32 ignore_case:
33 description: Ignore case in pattern if using the O(pattern) option.
34 type: bool
35 default: false
36 version_added: 3.0.0
37 """
38
39 EXAMPLES = r"""
40 # Pass the process name
41 - name: Getting process IDs of the process
42 community.general.pids:
43 name: python
44 register: pids_of_python
45
46 - name: Printing the process IDs obtained
47 ansible.builtin.debug:
48 msg: "PIDS of python:{{pids_of_python.pids|join(',')}}"
49
50 - name: Getting process IDs of processes matching pattern
51 community.general.pids:
52 pattern: python(2(\.7)?|3(\.6)?)?\s+myapp\.py
53 register: myapp_pids
54 """
55
56 RETURN = r"""
57 pids:
58 description: Process IDs of the given process.
59 returned: list of none, one, or more process IDs
60 type: list
61 sample: [100, 200]
62 """
63
64 import abc
65 import re
66 from os.path import basename
67
68 from ansible.module_utils.basic import AnsibleModule
69 from ansible.module_utils.common.text.converters import to_native
70
71 from ansible_collections.community.general.plugins.module_utils import _deps as deps
72 from ansible_collections.community.general.plugins.module_utils._version import LooseVersion
73
74 with deps.declare("psutil"):
75 import psutil
76
77
78 class PSAdapterError(Exception):
79 pass
80
81
82 class PSAdapter(metaclass=abc.ABCMeta):
83 NAME_ATTRS = ("name", "cmdline")
84 PATTERN_ATTRS = ("name", "exe", "cmdline")
85
86 def __init__(self, psutil):
87 self._psutil = psutil
88
89 @staticmethod
90 def from_package(psutil):
91 version = LooseVersion(psutil.__version__)
92 if version < LooseVersion("2.0.0"):
93 return PSAdapter100(psutil)
94 elif version < LooseVersion("5.3.0"):
95 return PSAdapter200(psutil)
96 else:
97 return PSAdapter530(psutil)
98
99 def get_pids_by_name(self, name):
100 return [p.pid for p in self._process_iter(*self.NAME_ATTRS) if self._has_name(p, name)]
101
102 def _process_iter(self, *attrs):
103 return self._psutil.process_iter()
104
105 def _has_name(self, proc, name):
106 attributes = self._get_proc_attributes(proc, *self.NAME_ATTRS)
107 return (
108 compare_lower(attributes["name"], name)
109 or attributes["cmdline"]
110 and compare_lower(attributes["cmdline"][0], name)
111 )
112
113 def _get_proc_attributes(self, proc, *attributes):
114 return {attribute: self._get_attribute_from_proc(proc, attribute) for attribute in attributes}
115
116 @staticmethod
117 @abc.abstractmethod
118 def _get_attribute_from_proc(proc, attribute):
119 pass
120
121 def get_pids_by_pattern(self, pattern, ignore_case):
122 flags = 0
123 if ignore_case:
124 flags |= re.I
125
126 try:
127 regex = re.compile(pattern, flags)
128 except re.error as e:
129 raise PSAdapterError(f"'{pattern}' is not a valid regular expression: {e}") from e
130
131 return [p.pid for p in self._process_iter(*self.PATTERN_ATTRS) if self._matches_regex(p, regex)]
132
133 def _matches_regex(self, proc, regex):
134 # See https://psutil.readthedocs.io/en/latest/#find-process-by-name for more information
135 attributes = self._get_proc_attributes(proc, *self.PATTERN_ATTRS)
136 matches_name = regex.search(to_native(attributes["name"]))
137 matches_exe = attributes["exe"] and regex.search(basename(to_native(attributes["exe"])))
138 matches_cmd = attributes["cmdline"] and regex.search(to_native(" ".join(attributes["cmdline"])))
139
140 return any([matches_name, matches_exe, matches_cmd])
141
142
143 class PSAdapter100(PSAdapter):
144 def __init__(self, psutil):
145 super().__init__(psutil)
146
147 @staticmethod
148 def _get_attribute_from_proc(proc, attribute):
149 return getattr(proc, attribute)
150
151
152 class PSAdapter200(PSAdapter):
153 def __init__(self, psutil):
154 super().__init__(psutil)
155
156 @staticmethod
157 def _get_attribute_from_proc(proc, attribute):
158 method = getattr(proc, attribute)
159 return method()
160
161
162 class PSAdapter530(PSAdapter):
163 def __init__(self, psutil):
164 super().__init__(psutil)
165
166 def _process_iter(self, *attrs):
167 return self._psutil.process_iter(attrs=attrs)
168
169 @staticmethod
170 def _get_attribute_from_proc(proc, attribute):
171 return proc.info[attribute]
172
173
174 def compare_lower(a, b):
175 if a is None or b is None:
176 # this could just be "return False" but would lead to surprising behavior if both a and b are None
177 return a == b
178
179 return a.lower() == b.lower()
180
181
182 class Pids:
183 def __init__(self, module):
184 deps.validate(module)
185
186 self._ps = PSAdapter.from_package(psutil)
187
188 self._module = module
189 self._name = module.params["name"]
190 self._pattern = module.params["pattern"]
191 self._ignore_case = module.params["ignore_case"]
192
193 self._pids = []
194
195 def execute(self):
196 if self._name is not None:
197 self._pids = self._ps.get_pids_by_name(self._name)
198 else:
199 try:
200 self._pids = self._ps.get_pids_by_pattern(self._pattern, self._ignore_case)
201 except PSAdapterError as e:
202 self._module.fail_json(msg=f"{e}")
203
204 return self._module.exit_json(**self.result)
205
206 @property
207 def result(self):
208 return {
209 "pids": self._pids,
210 }
211
212
213 def main():
214 module = AnsibleModule(
215 argument_spec=dict(
216 name=dict(type="str"),
217 pattern=dict(type="str"),
218 ignore_case=dict(type="bool", default=False),
219 ),
220 required_one_of=[("name", "pattern")],
221 mutually_exclusive=[("name", "pattern")],
222 supports_check_mode=True,
223 )
224
225 Pids(module).execute()
226
227
228 if __name__ == "__main__":
229 main()