Debian Codegraph @

lib/ansible/modules/service_facts.py

raw
1 # Copyright: (c) 2017, Ansible Project
2 # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
3 # originally copied from AWX's scan_services module to bring this functionality
4 # into Core
5
6 from __future__ import annotations
7
8
9 DOCUMENTATION = r"""
10 ---
11 module: service_facts
12 short_description: Return service state information as fact data
13 description:
14 - Return service state information as fact data for various service management utilities.
15 version_added: "2.5"
16 requirements: ["Any of the following supported init systems: systemd, sysv, upstart, openrc, AIX SRC"]
17 extends_documentation_fragment:
18 - action_common_attributes
19 - action_common_attributes.facts
20 attributes:
21 check_mode:
22 support: full
23 diff_mode:
24 support: none
25 facts:
26 support: full
27 platform:
28 platforms: posix
29 notes:
30 - When accessing the RV(ansible_facts.services) facts collected by this module,
31 it is recommended to not use "dot notation" because services can have a C(-)
32 character in their name which would result in invalid "dot notation", such as
33 C(ansible_facts.services.zuul-gateway). It is instead recommended to
34 using the string value of the service name as the key in order to obtain
35 the fact data value like C(ansible_facts.services['zuul-gateway'])
36 - AIX SRC was added in version 2.11.
37 author:
38 - Adam Miller (@maxamillion)
39 """
40
41 EXAMPLES = r"""
42 - name: Populate service facts
43 ansible.builtin.service_facts:
44
45 - name: Print service facts
46 ansible.builtin.debug:
47 var: ansible_facts.services
48
49 - name: show names of existing systemd services, sometimes systemd knows about services that were never installed
50 debug: msg={{ existing_systemd_services | map(attribute='name') }}
51 vars:
52 known_systemd_services: "{{ ansible_facts['services'].values() | selectattr('source', 'equalto', 'systemd') }}"
53 existing_systemd_services: "{{ known_systemd_services | rejectattr('status', 'equalto', 'not-found') }}"
54
55 - name: restart systemd service if it exists
56 service:
57 state: restarted
58 name: ntpd.service
59 when: ansible_facts['services']['ntpd.service']['status'] | default('not-found') != 'not-found'
60
61 """
62
63 RETURN = r"""
64 ansible_facts:
65 description: Facts to add to ansible_facts about the services on the system
66 returned: always
67 type: complex
68 contains:
69 services:
70 description: States of the services with service name as key.
71 returned: always
72 type: list
73 elements: dict
74 contains:
75 source:
76 description:
77 - Init system of the service.
78 - One of V(rcctl), V(systemd), V(sysv), V(upstart), V(src).
79 returned: always
80 type: str
81 sample: sysv
82 state:
83 description:
84 - State of the service.
85 - 'This commonly includes (but is not limited to) the following: V(failed), V(running), V(stopped) or V(unknown).'
86 - Depending on the used init system additional states might be returned.
87 returned: always
88 type: str
89 sample: running
90 status:
91 description:
92 - State of the service.
93 - Either V(enabled), V(disabled), V(static), V(indirect) or V(unknown).
94 returned: systemd systems or RedHat/SUSE flavored sysvinit/upstart or OpenBSD
95 type: str
96 sample: enabled
97 name:
98 description: Name of the service.
99 returned: always
100 type: str
101 sample: arp-ethers.service
102 """
103
104
105 import os
106 import platform
107 import re
108 import sys
109
110 from ansible.module_utils.basic import AnsibleModule
111 from ansible.module_utils.common.locale import get_best_parsable_locale
112 from ansible.module_utils.service import is_systemd_managed
113
114
115 class BaseService(object):
116
117 def __init__(self, module):
118 self.module = module
119
120
121 class ServiceScanService(BaseService):
122
123 def _list_sysvinit(self, services):
124 rc, stdout, stderr = self.module.run_command("%s --status-all" % self.service_path)
125 if rc == 4 and not os.path.exists('/etc/init.d'):
126 # This function is not intended to run on Red Hat but it could happen
127 # if `chkconfig` is not installed. `service` on RHEL9 returns rc 4
128 # when /etc/init.d is missing, add the extra guard of checking /etc/init.d
129 # instead of solely relying on rc == 4
130 return
131 if rc != 0:
132 self.module.warn("Unable to query 'service' tool (%s): %s" % (rc, stderr))
133 p = re.compile(r'^\s*\[ (?P<state>\+|\-) \]\s+(?P<name>.+)$', flags=re.M)
134 for match in p.finditer(stdout):
135 service_name = match.group('name')
136 if match.group('state') == "+":
137 service_state = "running"
138 else:
139 service_state = "stopped"
140 services[service_name] = {"name": service_name, "state": service_state, "source": "sysv"}
141
142 def _list_upstart(self, services):
143 p = re.compile(r'^\s?(?P<name>.*)\s(?P<goal>\w+)\/(?P<state>\w+)(\,\sprocess\s(?P<pid>[0-9]+))?\s*$')
144 rc, stdout, stderr = self.module.run_command("%s list" % self.initctl_path)
145 if rc != 0:
146 self.module.warn('Unable to query upstart for service data: %s' % stderr)
147 else:
148 real_stdout = stdout.replace("\r", "")
149 for line in real_stdout.split("\n"):
150 m = p.match(line)
151 if not m:
152 continue
153 service_name = m.group('name')
154 service_goal = m.group('goal')
155 service_state = m.group('state')
156 if m.group('pid'):
157 pid = m.group('pid')
158 else:
159 pid = None # NOQA
160 payload = {"name": service_name, "state": service_state, "goal": service_goal, "source": "upstart"}
161 services[service_name] = payload
162
163 def _list_rh(self, services):
164
165 p = re.compile(
166 r'(?P<service>.*?)\s+[0-9]:(?P<rl0>on|off)\s+[0-9]:(?P<rl1>on|off)\s+[0-9]:(?P<rl2>on|off)\s+'
167 r'[0-9]:(?P<rl3>on|off)\s+[0-9]:(?P<rl4>on|off)\s+[0-9]:(?P<rl5>on|off)\s+[0-9]:(?P<rl6>on|off)')
168 rc, stdout, stderr = self.module.run_command('%s' % self.chkconfig_path, use_unsafe_shell=True)
169 # Check for special cases where stdout does not fit pattern
170 match_any = False
171 for line in stdout.split('\n'):
172 if p.match(line):
173 match_any = True
174 if not match_any:
175 p_simple = re.compile(r'(?P<service>.*?)\s+(?P<rl0>on|off)')
176 match_any = False
177 for line in stdout.split('\n'):
178 if p_simple.match(line):
179 match_any = True
180 if match_any:
181 # Try extra flags " -l --allservices" needed for SLES11
182 rc, stdout, stderr = self.module.run_command('%s -l --allservices' % self.chkconfig_path, use_unsafe_shell=True)
183 elif '--list' in stderr:
184 # Extra flag needed for RHEL5
185 rc, stdout, stderr = self.module.run_command('%s --list' % self.chkconfig_path, use_unsafe_shell=True)
186
187 for line in stdout.split('\n'):
188 m = p.match(line)
189 if m:
190 service_name = m.group('service')
191 service_state = 'stopped'
192 service_status = "disabled"
193 if m.group('rl3') == 'on':
194 service_status = "enabled"
195 rc, stdout, stderr = self.module.run_command('%s %s status' % (self.service_path, service_name), use_unsafe_shell=True)
196 service_state = rc
197 if rc in (0,):
198 service_state = 'running'
199 # elif rc in (1,3):
200 else:
201 output = stderr.lower()
202 for x in ('root', 'permission', 'not in sudoers'):
203 if x in output:
204 self.module.warn('Insufficient permissions to query sysV service "%s" and their states' % service_name)
205 break
206 else:
207 service_state = 'stopped'
208
209 service_data = {"name": service_name, "state": service_state, "status": service_status, "source": "sysv"}
210 services[service_name] = service_data
211
212 def _list_openrc(self, services):
213 all_services_runlevels = {}
214 dummy, stdout, dummy = self.module.run_command("%s -a -s -m 2>&1 | grep '^ ' | tr -d '[]'" % self.rc_status_path, use_unsafe_shell=True)
215 dummy, stdout_u, dummy = self.module.run_command("%s show -v 2>&1 | grep '|'" % self.rc_update_path, use_unsafe_shell=True)
216 for line in stdout_u.split('\n'):
217 line_data = line.split('|')
218 if len(line_data) < 2:
219 continue
220 service_name = line_data[0].strip()
221 runlevels = line_data[1].strip()
222 if not runlevels:
223 all_services_runlevels[service_name] = None
224 else:
225 all_services_runlevels[service_name] = runlevels.split()
226 for line in stdout.split('\n'):
227 line_data = line.split()
228 if len(line_data) < 2:
229 continue
230 service_name = line_data[0]
231 # Skip lines which are not service names
232 if service_name == "*":
233 continue
234 service_state = line_data[1]
235 try:
236 service_runlevels = all_services_runlevels[service_name]
237 except KeyError:
238 self.module.warn(f"Service {service_name} not found in the service list")
239 continue
240 service_data = {"name": service_name, "runlevels": service_runlevels, "state": service_state, "source": "openrc"}
241 services[service_name] = service_data
242
243 def gather_services(self):
244 services = {}
245
246 # find cli tools if available
247 self.service_path = self.module.get_bin_path("service")
248 self.chkconfig_path = self.module.get_bin_path("chkconfig")
249 self.initctl_path = self.module.get_bin_path("initctl")
250 self.rc_status_path = self.module.get_bin_path("rc-status")
251 self.rc_update_path = self.module.get_bin_path("rc-update")
252
253 if self.service_path and self.chkconfig_path is None and self.rc_status_path is None:
254 self._list_sysvinit(services)
255
256 # TODO: review conditionals ... they should not be this 'exclusive'
257 if self.initctl_path and self.chkconfig_path is None:
258 self._list_upstart(services)
259 elif self.chkconfig_path:
260 self._list_rh(services)
261 elif self.rc_status_path is not None and self.rc_update_path is not None:
262 self._list_openrc(services)
263
264 return services
265
266
267 class SystemctlScanService(BaseService):
268
269 BAD_STATES = frozenset(['not-found', 'masked', 'failed'])
270
271 def systemd_enabled(self):
272 return is_systemd_managed(self.module)
273
274 def _list_from_units(self, systemctl_path, services):
275
276 # list units as systemd sees them
277 rc, stdout, stderr = self.module.run_command("%s list-units --no-pager --type service --all --plain" % systemctl_path, use_unsafe_shell=True)
278 if rc != 0:
279 self.module.warn("Could not list units from systemd: %s" % stderr)
280 else:
281 for line in [svc_line for svc_line in stdout.split('\n') if '.service' in svc_line]:
282
283 state_val = "stopped"
284 status_val = "unknown"
285 fields = line.split()
286
287 # systemd sometimes gives misleading status
288 # check all fields for bad states
289 for bad in self.BAD_STATES:
290 # except description
291 if bad in fields[:-1]:
292 status_val = bad
293 break
294 else:
295 # active/inactive
296 status_val = fields[2]
297
298 service_name = fields[0]
299 if fields[3] == "running":
300 state_val = "running"
301
302 services[service_name] = {"name": service_name, "state": state_val, "status": status_val, "source": "systemd"}
303
304 def _list_from_unit_files(self, systemctl_path, services):
305
306 # now try unit files for complete picture and final 'status'
307 rc, stdout, stderr = self.module.run_command("%s list-unit-files --no-pager --type service --all" % systemctl_path, use_unsafe_shell=True)
308 if rc != 0:
309 self.module.warn("Could not get unit files data from systemd: %s" % stderr)
310 else:
311 for line in [svc_line for svc_line in stdout.split('\n') if '.service' in svc_line]:
312 # there is one more column (VENDOR PRESET) from `systemctl list-unit-files` for systemd >= 245
313 try:
314 service_name, status_val = line.split()[:2]
315 except IndexError:
316 self.module.fail_json(msg="Malformed output discovered from systemd list-unit-files: {0}".format(line))
317 if service_name not in services:
318 rc, stdout, stderr = self.module.run_command("%s show %s --property=ActiveState" % (systemctl_path, service_name), use_unsafe_shell=True)
319 state = 'unknown'
320 if not rc and stdout != '':
321 state = stdout.replace('ActiveState=', '').rstrip()
322 services[service_name] = {"name": service_name, "state": state, "status": status_val, "source": "systemd"}
323 elif services[service_name]["status"] not in self.BAD_STATES:
324 services[service_name]["status"] = status_val
325
326 def gather_services(self):
327
328 services = {}
329 if self.systemd_enabled():
330 systemctl_path = self.module.get_bin_path("systemctl", opt_dirs=["/usr/bin", "/usr/local/bin"])
331 if systemctl_path:
332 self._list_from_units(systemctl_path, services)
333 self._list_from_unit_files(systemctl_path, services)
334
335 return services
336
337
338 class AIXScanService(BaseService):
339
340 def gather_services(self):
341
342 services = {}
343 if platform.system() == 'AIX':
344 lssrc_path = self.module.get_bin_path("lssrc")
345 if lssrc_path:
346 rc, stdout, stderr = self.module.run_command("%s -a" % lssrc_path)
347 if rc != 0:
348 self.module.warn("lssrc could not retrieve service data (%s): %s" % (rc, stderr))
349 else:
350 for line in stdout.split('\n'):
351 line_data = line.split()
352 if len(line_data) < 2:
353 continue # Skipping because we expected more data
354 if line_data[0] == "Subsystem":
355 continue # Skip header
356 service_name = line_data[0]
357 if line_data[-1] == "active":
358 service_state = "running"
359 elif line_data[-1] == "inoperative":
360 service_state = "stopped"
361 else:
362 service_state = "unknown"
363 services[service_name] = {"name": service_name, "state": service_state, "source": "src"}
364 return services
365
366
367 class OpenBSDScanService(BaseService):
368
369 def query_rcctl(self, cmd):
370 svcs = []
371 rc, stdout, stderr = self.module.run_command("%s ls %s" % (self.rcctl_path, cmd))
372 if 'needs root privileges' in stderr.lower():
373 self.module.warn('rcctl requires root privileges')
374 else:
375 for svc in stdout.split('\n'):
376 if svc == '':
377 continue
378 else:
379 svcs.append(svc)
380 return svcs
381
382 def get_info(self, name):
383 info = {}
384 rc, stdout, stderr = self.module.run_command("%s get %s" % (self.rcctl_path, name))
385 if 'needs root privileges' in stderr.lower():
386 self.module.warn('rcctl requires root privileges')
387 else:
388 undy = '%s_' % name
389 for variable in stdout.split('\n'):
390 if variable == '' or '=' not in variable:
391 continue
392 else:
393 k, v = variable.replace(undy, '', 1).split('=', 1)
394 info[k] = v
395 return info
396
397 def gather_services(self):
398
399 services = {}
400 self.rcctl_path = self.module.get_bin_path("rcctl")
401 if self.rcctl_path:
402
403 # populate services will all possible
404 for svc in self.query_rcctl('all'):
405 services[svc] = {'name': svc, 'source': 'rcctl', 'rogue': False}
406 services[svc].update(self.get_info(svc))
407
408 for svc in self.query_rcctl('on'):
409 services[svc].update({'status': 'enabled'})
410
411 for svc in self.query_rcctl('started'):
412 services[svc].update({'state': 'running'})
413
414 # Override the state for services which are marked as 'failed'
415 for svc in self.query_rcctl('failed'):
416 services[svc].update({'state': 'failed'})
417
418 for svc in services.keys():
419 # Based on the list of services that are enabled/failed, determine which are disabled
420 if services[svc].get('status') is None:
421 services[svc].update({'status': 'disabled'})
422
423 # and do the same for those are aren't running
424 if services[svc].get('state') is None:
425 services[svc].update({'state': 'stopped'})
426
427 for svc in self.query_rcctl('rogue'):
428 services[svc]['rogue'] = True
429
430 return services
431
432
433 class FreeBSDScanService(BaseService):
434
435 _pid_regex = r'.+ is running as pid (\d+)\.'
436
437 def get_info(self, service):
438
439 service_info = {'status': 'unknown'}
440 rc, stdout, stderr = self.module.run_command("%s %s describe" % (self.service, service))
441 if rc == 0:
442 service_info['description'] = stdout
443 rc, stdout, stderr = self.module.run_command("%s %s status" % (self.service, service))
444 if rc == 0:
445 service_info['status'] = 'running'
446 p = re.compile(r'^\s?%s is running as pid (\d+).' % service)
447 matches = p.match(stdout[0])
448 if matches:
449 # does not always get pid output
450 service_info['pid'] = matches[0]
451 else:
452 service_info['pid'] = 'N/A'
453 elif rc == 1:
454 if stdout and 'is not running' in stdout.splitlines()[0]:
455 service_info['status'] = 'stopped'
456 elif stderr and 'unknown directive' in stderr.splitlines()[0]:
457 service_info['status'] = 'unknown'
458 self.module.warn('Status query not supported for %s' % service)
459 else:
460 service_info['status'] = 'unknown'
461 out = stderr if stderr else stdout
462 self.module.warn('Could not retrieve status for %s: %s' % (service, out))
463 else:
464 out = stderr if stderr else stdout
465 self.module.warn("Failed to get info for %s, no system message (rc=%s): %s" % (service, rc, out))
466
467 return service_info
468
469 def get_enabled(self):
470
471 services = []
472 rc, stdout, stderr = self.module.run_command("%s -e" % (self.service))
473 if rc == 0:
474 for line in stdout.splitlines():
475 if line.startswith('/'):
476 services.append(os.path.basename(line))
477 elif stderr:
478 self.module.warn("Failed to get services: %s" % stderr)
479 elif stdout:
480 self.module.warn("Failed to get services: %s" % stdout)
481 else:
482 self.module.warn("Failed to get services, no system message: rc=%s" % rc)
483
484 return services
485
486 def gather_services(self):
487
488 services = {}
489 if sys.platform.startswith('freebsd'):
490 self.service = self.module.get_bin_path("service")
491 if self.service:
492 for svc in self.get_enabled():
493 services[svc] = self.get_info(svc)
494 return services
495
496
497 def main():
498 module = AnsibleModule(argument_spec=dict(), supports_check_mode=True)
499 locale = get_best_parsable_locale(module)
500 module.run_command_environ_update = dict(LANG=locale, LC_ALL=locale)
501
502 if sys.platform.startswith('freebsd'):
503 # frebsd is not compatible but will match other classes
504 service_modules = (FreeBSDScanService,)
505 else:
506 service_modules = (ServiceScanService, SystemctlScanService, AIXScanService, OpenBSDScanService)
507
508 all_services = {}
509 for svc_module in service_modules:
510 svcmod = svc_module(module)
511 svc = svcmod.gather_services()
512 if svc:
513 all_services.update(svc)
514 if len(all_services) == 0:
515 results = dict(
516 skipped=True, # deprecated: description='remove this skipped return', core_version='2.25'
517 msg="Failed to find any services. This can be due to privileges or some other configuration issue.",
518 )
519 else:
520 results = dict(ansible_facts=dict(services=all_services))
521 module.exit_json(**results)
522
523
524 if __name__ == '__main__':
525 main()