| 1 |
# -*- coding: utf-8 -*- |
| 2 |
# (c) 2017, Brian Coca <[email protected]> |
| 3 |
# (c) 2017, Adam Miller <[email protected]> |
| 4 |
# (c) 2017 Ansible Project |
| 5 |
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) |
| 6 |
|
| 7 |
from __future__ import annotations |
| 8 |
|
| 9 |
|
| 10 |
DOCUMENTATION = """ |
| 11 |
module: sysvinit |
| 12 |
author: |
| 13 |
- "Ansible Core Team" |
| 14 |
version_added: "2.6" |
| 15 |
short_description: Manage SysV services. |
| 16 |
description: |
| 17 |
- Controls services on target hosts that use the SysV init system. |
| 18 |
options: |
| 19 |
name: |
| 20 |
required: true |
| 21 |
description: |
| 22 |
- Name of the service. |
| 23 |
type: str |
| 24 |
aliases: ['service'] |
| 25 |
state: |
| 26 |
choices: [ 'started', 'stopped', 'restarted', 'reloaded' ] |
| 27 |
description: |
| 28 |
- V(started)/V(stopped) are idempotent actions that will not run commands unless necessary. |
| 29 |
Not all init scripts support V(restarted) nor V(reloaded) natively, so these will both trigger a stop and start as needed. |
| 30 |
type: str |
| 31 |
enabled: |
| 32 |
type: bool |
| 33 |
description: |
| 34 |
- Whether the service should start on boot. At least one of O(state) and O(enabled) are required. |
| 35 |
sleep: |
| 36 |
default: 1 |
| 37 |
description: |
| 38 |
- If the service is being V(restarted) or V(reloaded) then sleep this many seconds between the stop and start command. |
| 39 |
This helps to workaround badly behaving services. |
| 40 |
type: int |
| 41 |
pattern: |
| 42 |
description: |
| 43 |
- A substring to look for as would be found in the output of the I(ps) command as a stand-in for a status result. |
| 44 |
- If the string is found, the service will be assumed to be running. |
| 45 |
- "This option is mainly for use with init scripts that don't support the C(status) option." |
| 46 |
type: str |
| 47 |
runlevels: |
| 48 |
description: |
| 49 |
- The runlevels this script should be enabled/disabled from. |
| 50 |
- Use this to override the defaults set by the package or init script itself. |
| 51 |
type: list |
| 52 |
elements: str |
| 53 |
arguments: |
| 54 |
description: |
| 55 |
- Additional arguments provided on the command line that some init scripts accept. |
| 56 |
type: str |
| 57 |
aliases: [ 'args' ] |
| 58 |
daemonize: |
| 59 |
type: bool |
| 60 |
description: |
| 61 |
- Have the module daemonize as the service itself might not do so properly. |
| 62 |
- This is useful with badly written init scripts or daemons, which |
| 63 |
commonly manifests as the task hanging as it is still holding the |
| 64 |
tty or the service dying when the task is over as the connection |
| 65 |
closes the session. |
| 66 |
default: no |
| 67 |
extends_documentation_fragment: action_common_attributes |
| 68 |
attributes: |
| 69 |
check_mode: |
| 70 |
support: full |
| 71 |
diff_mode: |
| 72 |
support: none |
| 73 |
platform: |
| 74 |
platforms: posix |
| 75 |
notes: |
| 76 |
- One option other than name is required. |
| 77 |
- The service names might vary by specific OS/distribution. |
| 78 |
requirements: |
| 79 |
- That the service managed has a corresponding init script. |
| 80 |
""" |
| 81 |
|
| 82 |
EXAMPLES = """ |
| 83 |
- name: Make sure apache2 is started |
| 84 |
ansible.builtin.sysvinit: |
| 85 |
name: apache2 |
| 86 |
state: started |
| 87 |
enabled: yes |
| 88 |
|
| 89 |
- name: Sleep for 5 seconds between stop and start command of badly behaving service |
| 90 |
ansible.builtin.sysvinit: |
| 91 |
name: apache2 |
| 92 |
state: restarted |
| 93 |
sleep: 5 |
| 94 |
|
| 95 |
- name: Make sure apache2 is started on runlevels 3 and 5 |
| 96 |
ansible.builtin.sysvinit: |
| 97 |
name: apache2 |
| 98 |
state: started |
| 99 |
enabled: yes |
| 100 |
runlevels: |
| 101 |
- 3 |
| 102 |
- 5 |
| 103 |
""" |
| 104 |
|
| 105 |
RETURN = r""" |
| 106 |
results: |
| 107 |
description: results from actions taken |
| 108 |
returned: always |
| 109 |
type: complex |
| 110 |
contains: |
| 111 |
name: |
| 112 |
description: Name of the service |
| 113 |
type: str |
| 114 |
returned: always |
| 115 |
sample: "apache2" |
| 116 |
status: |
| 117 |
description: Status of the service |
| 118 |
type: dict |
| 119 |
returned: changed |
| 120 |
sample: { |
| 121 |
"enabled": { |
| 122 |
"changed": true, |
| 123 |
"rc": 0, |
| 124 |
"stderr": "", |
| 125 |
"stdout": "" |
| 126 |
}, |
| 127 |
"stopped": { |
| 128 |
"changed": true, |
| 129 |
"rc": 0, |
| 130 |
"stderr": "", |
| 131 |
"stdout": "Stopping web server: apache2.\n" |
| 132 |
} |
| 133 |
} |
| 134 |
""" |
| 135 |
|
| 136 |
import re |
| 137 |
from time import sleep |
| 138 |
from ansible.module_utils.basic import AnsibleModule |
| 139 |
from ansible.module_utils.service import sysv_is_enabled, get_sysv_script, sysv_exists, fail_if_missing, get_ps, daemonize |
| 140 |
|
| 141 |
|
| 142 |
def main(): |
| 143 |
|
| 144 |
module = AnsibleModule( |
| 145 |
argument_spec=dict( |
| 146 |
name=dict(required=True, type='str', aliases=['service']), |
| 147 |
state=dict(choices=['started', 'stopped', 'restarted', 'reloaded'], type='str'), |
| 148 |
enabled=dict(type='bool'), |
| 149 |
sleep=dict(type='int', default=1), |
| 150 |
pattern=dict(type='str'), |
| 151 |
arguments=dict(type='str', aliases=['args']), |
| 152 |
runlevels=dict(type='list', elements='str'), |
| 153 |
daemonize=dict(type='bool', default=False), |
| 154 |
), |
| 155 |
supports_check_mode=True, |
| 156 |
required_one_of=[['state', 'enabled']], |
| 157 |
) |
| 158 |
|
| 159 |
name = module.params['name'] |
| 160 |
action = module.params['state'] |
| 161 |
enabled = module.params['enabled'] |
| 162 |
runlevels = module.params['runlevels'] |
| 163 |
pattern = module.params['pattern'] |
| 164 |
sleep_for = module.params['sleep'] |
| 165 |
rc = 0 |
| 166 |
out = err = '' |
| 167 |
result = { |
| 168 |
'name': name, |
| 169 |
'changed': False, |
| 170 |
'status': {} |
| 171 |
} |
| 172 |
|
| 173 |
# ensure service exists, get script name |
| 174 |
fail_if_missing(module, sysv_exists(name), name) |
| 175 |
script = get_sysv_script(name) |
| 176 |
|
| 177 |
# locate binaries for service management |
| 178 |
paths = ['/sbin', '/usr/sbin', '/bin', '/usr/bin'] |
| 179 |
binaries = ['chkconfig', 'update-rc.d', 'insserv', 'service'] |
| 180 |
|
| 181 |
# Keeps track of the service status for various runlevels because we can |
| 182 |
# operate on multiple runlevels at once |
| 183 |
runlevel_status = {} |
| 184 |
|
| 185 |
location = {} |
| 186 |
for binary in binaries: |
| 187 |
location[binary] = module.get_bin_path(binary, opt_dirs=paths) |
| 188 |
|
| 189 |
# figure out enable status |
| 190 |
if runlevels: |
| 191 |
for rl in runlevels: |
| 192 |
runlevel_status.setdefault(rl, {}) |
| 193 |
runlevel_status[rl]["enabled"] = sysv_is_enabled(name, runlevel=rl) |
| 194 |
else: |
| 195 |
runlevel_status["enabled"] = sysv_is_enabled(name) |
| 196 |
|
| 197 |
# figure out started status, everyone does it different! |
| 198 |
is_started = False |
| 199 |
worked = False |
| 200 |
|
| 201 |
# user knows other methods fail and supplied pattern |
| 202 |
if pattern: |
| 203 |
worked = is_started = get_ps(module, pattern) |
| 204 |
else: |
| 205 |
if location.get('service'): |
| 206 |
# standard tool that has been 'destandardized' by reimplementation in other OS/distros |
| 207 |
cmd = '%s %s status' % (location['service'], name) |
| 208 |
elif script: |
| 209 |
# maybe script implements status (not LSB) |
| 210 |
cmd = '%s status' % script |
| 211 |
else: |
| 212 |
module.fail_json(msg="Unable to determine service status") |
| 213 |
|
| 214 |
(rc, out, err) = module.run_command(cmd) |
| 215 |
if not rc == -1: |
| 216 |
# special case |
| 217 |
if name == 'iptables' and "ACCEPT" in out: |
| 218 |
worked = True |
| 219 |
is_started = True |
| 220 |
|
| 221 |
# check output messages, messy but sadly more reliable than rc |
| 222 |
if not worked and out.count('\n') <= 1: |
| 223 |
|
| 224 |
cleanout = out.lower().replace(name.lower(), '') |
| 225 |
|
| 226 |
for stopped in ['stop', 'is dead ', 'dead but ', 'could not access pid file', 'inactive']: |
| 227 |
if stopped in cleanout: |
| 228 |
worked = True |
| 229 |
break |
| 230 |
|
| 231 |
if not worked: |
| 232 |
for started_status in ['run', 'start', 'active']: |
| 233 |
if started_status in cleanout and "not " not in cleanout: |
| 234 |
is_started = True |
| 235 |
worked = True |
| 236 |
break |
| 237 |
|
| 238 |
# hope rc is not lying to us, use often used 'bad' returns |
| 239 |
if not worked and rc in [1, 2, 3, 4, 69]: |
| 240 |
worked = True |
| 241 |
|
| 242 |
if not worked: |
| 243 |
# hail mary |
| 244 |
if rc == 0: |
| 245 |
is_started = True |
| 246 |
worked = True |
| 247 |
# ps for luck, can only assure positive match |
| 248 |
elif get_ps(module, name): |
| 249 |
is_started = True |
| 250 |
worked = True |
| 251 |
module.warn("Used ps output to match service name and determine it is up, this is very unreliable") |
| 252 |
|
| 253 |
if not worked: |
| 254 |
module.warn("Unable to determine if service is up, assuming it is down") |
| 255 |
|
| 256 |
########################################################################### |
| 257 |
# BEGIN: Enable/Disable |
| 258 |
result['status'].setdefault('enabled', {}) |
| 259 |
result['status']['enabled']['changed'] = False |
| 260 |
result['status']['enabled']['rc'] = None |
| 261 |
result['status']['enabled']['stdout'] = None |
| 262 |
result['status']['enabled']['stderr'] = None |
| 263 |
if runlevels: |
| 264 |
result['status']['enabled']['runlevels'] = runlevels |
| 265 |
for rl in runlevels: |
| 266 |
if enabled != runlevel_status[rl]["enabled"]: |
| 267 |
result['changed'] = True |
| 268 |
result['status']['enabled']['changed'] = True |
| 269 |
|
| 270 |
if not module.check_mode and result['changed']: |
| 271 |
# Perform enable/disable here |
| 272 |
if enabled: |
| 273 |
if location.get('update-rc.d'): |
| 274 |
(rc, out, err) = module.run_command("%s %s enable %s" % (location['update-rc.d'], name, ' '.join(runlevels))) |
| 275 |
elif location.get('chkconfig'): |
| 276 |
(rc, out, err) = module.run_command("%s --level %s %s on" % (location['chkconfig'], ''.join(runlevels), name)) |
| 277 |
else: |
| 278 |
if location.get('update-rc.d'): |
| 279 |
(rc, out, err) = module.run_command("%s %s disable %s" % (location['update-rc.d'], name, ' '.join(runlevels))) |
| 280 |
elif location.get('chkconfig'): |
| 281 |
(rc, out, err) = module.run_command("%s --level %s %s off" % (location['chkconfig'], ''.join(runlevels), name)) |
| 282 |
else: |
| 283 |
if enabled is not None and enabled != runlevel_status["enabled"]: |
| 284 |
result['changed'] = True |
| 285 |
result['status']['enabled']['changed'] = True |
| 286 |
|
| 287 |
if not module.check_mode and result['changed']: |
| 288 |
# Perform enable/disable here |
| 289 |
if enabled: |
| 290 |
if location.get('update-rc.d'): |
| 291 |
(rc, out, err) = module.run_command("%s %s defaults" % (location['update-rc.d'], name)) |
| 292 |
elif location.get('chkconfig'): |
| 293 |
(rc, out, err) = module.run_command("%s %s on" % (location['chkconfig'], name)) |
| 294 |
else: |
| 295 |
if location.get('update-rc.d'): |
| 296 |
(rc, out, err) = module.run_command("%s %s disable" % (location['update-rc.d'], name)) |
| 297 |
elif location.get('chkconfig'): |
| 298 |
(rc, out, err) = module.run_command("%s %s off" % (location['chkconfig'], name)) |
| 299 |
|
| 300 |
# Assigned above, might be useful is something goes sideways |
| 301 |
if not module.check_mode and result['status']['enabled']['changed']: |
| 302 |
result['status']['enabled']['rc'] = rc |
| 303 |
result['status']['enabled']['stdout'] = out |
| 304 |
result['status']['enabled']['stderr'] = err |
| 305 |
rc, out, err = None, None, None |
| 306 |
|
| 307 |
if "illegal runlevel specified" in result['status']['enabled']['stderr']: |
| 308 |
module.fail_json(msg="Illegal runlevel specified for enable operation on service %s" % name, **result) |
| 309 |
# END: Enable/Disable |
| 310 |
########################################################################### |
| 311 |
|
| 312 |
########################################################################### |
| 313 |
# BEGIN: state |
| 314 |
result['status'].setdefault(module.params['state'], {}) |
| 315 |
result['status'][module.params['state']]['changed'] = False |
| 316 |
result['status'][module.params['state']]['rc'] = None |
| 317 |
result['status'][module.params['state']]['stdout'] = None |
| 318 |
result['status'][module.params['state']]['stderr'] = None |
| 319 |
if action: |
| 320 |
action = re.sub(r'p?ed$', '', action.lower()) |
| 321 |
|
| 322 |
def runme(doit): |
| 323 |
|
| 324 |
args = module.params['arguments'] |
| 325 |
cmd = "%s %s %s" % (script, doit, "" if args is None else args) |
| 326 |
|
| 327 |
# how to run |
| 328 |
if module.params['daemonize']: |
| 329 |
(rc, out, err) = daemonize(module, cmd) |
| 330 |
else: |
| 331 |
(rc, out, err) = module.run_command(cmd) |
| 332 |
# FIXME: ERRORS |
| 333 |
|
| 334 |
if rc != 0: |
| 335 |
module.fail_json(msg="Failed to %s service: %s" % (action, name), rc=rc, stdout=out, stderr=err) |
| 336 |
|
| 337 |
return (rc, out, err) |
| 338 |
|
| 339 |
if action == 'restart': |
| 340 |
result['changed'] = True |
| 341 |
result['status'][module.params['state']]['changed'] = True |
| 342 |
if not module.check_mode: |
| 343 |
|
| 344 |
# cannot rely on existing 'restart' in init script |
| 345 |
for dothis in ['stop', 'start']: |
| 346 |
(rc, out, err) = runme(dothis) |
| 347 |
if sleep_for: |
| 348 |
sleep(sleep_for) |
| 349 |
|
| 350 |
elif is_started != (action == 'start'): |
| 351 |
result['changed'] = True |
| 352 |
result['status'][module.params['state']]['changed'] = True |
| 353 |
if not module.check_mode: |
| 354 |
rc, out, err = runme(action) |
| 355 |
|
| 356 |
elif is_started == (action == 'stop'): |
| 357 |
result['changed'] = True |
| 358 |
result['status'][module.params['state']]['changed'] = True |
| 359 |
if not module.check_mode: |
| 360 |
rc, out, err = runme(action) |
| 361 |
|
| 362 |
if not module.check_mode and result['status'][module.params['state']]['changed']: |
| 363 |
result['status'][module.params['state']]['rc'] = rc |
| 364 |
result['status'][module.params['state']]['stdout'] = out |
| 365 |
result['status'][module.params['state']]['stderr'] = err |
| 366 |
rc, out, err = None, None, None |
| 367 |
# END: state |
| 368 |
########################################################################### |
| 369 |
|
| 370 |
module.exit_json(**result) |
| 371 |
|
| 372 |
|
| 373 |
if __name__ == '__main__': |
| 374 |
main() |