-
Notifications
You must be signed in to change notification settings - Fork 10
/
test_process
100 lines (86 loc) · 2.78 KB
/
test_process
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
#!/usr/bin/python
# -*- coding: utf-8 -*-
# (c) 2014, Will Thames <[email protected]>
#
# This file is part of Ansible
#
# Ansible is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Ansible is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Ansible. If not, see <http://www.gnu.org/licenses/>.
DOCUMENTATION = '''
---
module: test_process
version_added: 1.5
short_description: Check the status of a process
description:
- Check if a process is running or not
options:
name:
description:
- name of the process to check
required: True
default: null
args:
description:
- list of one or more arguments to look for
required: False
default: []
state:
description:
- state of the process
choices: [ 'present', 'absent' ]
default: present
author: Will Thames
'''
EXAMPLES = '''
# Check if python app is running
test_process: name=python state=present args=['app.py']
'''
def check_process_for_arg(process, arg):
return arg in ' '.join(process.split()[1:])
def check_process(process, name, args):
if not re.match(r'([^ ]*/)?%s\b' % name, process):
return False
if not args:
return True
for arg in args:
if not check_process_for_arg(process, arg):
return False
return True
def main():
module = AnsibleModule(
argument_spec = dict(
name=dict(required=True, default=None),
args=dict(type='list', required=False, default=[]),
state=dict(choices=['present', 'absent'], default='present'),
),
supports_check_mode=True
)
name = module.params.get('name')
args = module.params.get('args')
state = module.params.get('state')
# Would like this to be more cross platform
rc, stdout, stderr = module.run_command(['ps', 'axww', '-o', 'command'])
processes = stdout.split('\n')[1:]
process_running = filter(lambda x: check_process(x, name, args), processes)
if state == 'present':
if process_running:
module.exit_json()
else:
module.fail_json(msg="Process with name %s not found with arguments %s" % (name,args))
if state == 'absent':
if process_running:
module.fail_json(msg="Process with name %s was unexpectedly found" % name)
else:
module.exit_json()
from ansible.module_utils.basic import *
main()