service 6.89 KB
Newer Older
1 2
#!/usr/bin/python

3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
# (c) 2012, Michael DeHaan <michael.dehaan@gmail.com>
#
# 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/>.

20 21 22 23 24 25 26
try:
    import json
except ImportError:
    import simplejson as json
import sys
import shlex
import subprocess
27
import os.path
28
import syslog
29

30 31 32
# TODO: switch to fail_json and other helper functions
# like other modules are using

33
# ===========================================
34

35 36 37 38 39 40 41 42 43 44
SERVICE = None
CHKCONFIG = None

def fail_json(d):
    print json.dumps(d)
    sys.exit(1)

def _find_binaries():
    # list of possible paths for service/chkconfig binaries
    # with the most probable first
45 46
    global CHKCONFIG
    global SERVICE
47 48 49 50 51 52 53
    paths = ['/sbin', '/usr/sbin', '/bin', '/usr/bin']
    binaries = [ 'service', 'chkconfig', 'update-rc.d' ]
    location = dict()

    for binary in binaries:
        location[binary] = None

54 55
    for binary in binaries:
        for path in paths:
56 57 58 59 60 61 62 63 64 65 66 67 68 69
            if os.path.exists(path + '/' + binary):
                location[binary] = path + '/' + binary
                break

    if location.get('chkconfig', None):
        CHKCONFIG = location['chkconfig']
    elif location.get('update-rc.d', None):
        CHKCONFIG = location['update-rc.d']
    else:
        fail_json(dict(failed=True, msg='unable to find chkconfig or update-rc.d binary'))
    if location.get('service', None):
        SERVICE = location['service']
    else:
        fail_json(dict(failed=True, msg='unable to find service binary'))
70

71

72
def _run(cmd):
73
    # returns (rc, stdout, stderr) from shell command
74 75 76 77
    process = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True)
    stdout, stderr = process.communicate()
    return (process.returncode, stdout, stderr) 

78 79

def _do_enable(name, enable):
80 81 82 83 84 85 86 87 88 89 90 91 92
    # we change argument depending on real binary used
    # update-rc.d wants enable/disable while
    # chkconfig wants on/off
    valid_argument = dict({'on' : 'on', 'off' : 'off'})

    if CHKCONFIG.endswith("update-rc.d"):
        valid_argument['on'] = "enable"
        valid_argument['off'] = "disable"

    if enable.lower() in ['on', 'true', 'yes', 'enable']:
        rc, stdout, stderr = _run("%s %s %s" % (CHKCONFIG, name, valid_argument['on']))
    elif enable.lower() in ['off', 'false', 'no', 'disable']:
        rc, stdout, stderr = _run("%s %s %s" % (CHKCONFIG, name, valid_argument['off']))
93 94 95
    
    return rc, stdout, stderr
    
96 97
argfile = sys.argv[1]
args = open(argfile, 'r').read()
98
items = shlex.split(args)
99 100
syslog.openlog('ansible-%s' % os.path.basename(__file__))
syslog.syslog(syslog.LOG_NOTICE, 'Invoked with %s' % args)
101 102

if not len(items):
103
    fail_json(dict(failed=True, msg='this module requires arguments (-a)'))
104

105
params = {}
106 107
for arg in items:
    if "=" not in arg:
108 109
        fail_json(dict(failed=True, msg='expected key=value format arguments'))

110 111
    (name, value) = arg.split("=")
    params[name] = value
112

113 114 115
name = params.get('name', None)

if name is None:
116
    fail_json(dict(failed=True, msg='missing name'))
117 118 119

state = params.get('state', None)
list_items = params.get('list', None)
120
enable = params.get('enabled', params.get('enable', None))
121

122
# running and started are the same
123 124 125 126 127 128 129 130 131 132 133
if state and state.lower() not in [ 'running', 'started', 'stopped', 'restarted' ]:
    fail_json(dict(failed=True, msg='invalid value for state'))
if list_items and list_items.lower() not in [ 'status' ]:
    fail_json(dict(failed=True, msg='invalid value for list'))
if enable and enable.lower() not in [ 'on', 'off', 'true', 'false', 'yes', 'no', 'enable', 'disable' ]:
    fail_json(dict(failed=True, msg='invalid value for enable'))
    

# ===========================================
# find binaries locations on minion
_find_binaries()
134

135 136 137 138

# ===========================================
# get service status

139 140
rc, status_stdout, status_stderr = _run("%s %s status" % (SERVICE, name))
status = status_stdout + status_stderr
141 142 143


running = False
144
if status_stdout.find("stopped") != -1 or rc == 3:
145
    running = False
146
elif status_stdout.find("running") != -1 or rc == 0:
147
    running = True
148
elif name == 'iptables' and status_stdout.find("ACCEPT") != -1:
149 150 151 152
    # iptables status command output is lame
    # TODO: lookup if we can use a return code for this instead?
    running = True

153
if state or enable:
154
    rc = 0
155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170
    out = ''
    err = ''
    changed = False
        
    if enable:
        rc_enable, out_enable, err_enable = _do_enable(name, enable)
        rc += rc_enable
        out += out_enable
        err += err_enable

    if state:
        # a state change command has been requested

        # ===========================================
        # determine if we are going to change anything

171
        if not running and state in ("started", "running"):
172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188
            changed = True
        elif running and state == "stopped":
            changed = True
        elif state == "restarted":
            changed = True

        # ===========================================
        # run change commands if we need to

        if changed:
            if state in ('started', 'running'):
                rc_state, stdout, stderr = _run("%s %s start" % (SERVICE, name))
            elif state == 'stopped':
                rc_state, stdout, stderr = _run("%s %s stop" % (SERVICE, name))
            elif state == 'restarted':
                rc1, stdout1, stderr1 = _run("%s %s stop" % (SERVICE, name))
                rc2, stdout2, stderr2 = _run("%s %s start" % (SERVICE, name))
189
                rc_state = rc + rc1 + rc2
190 191
                stdout = stdout1 + stdout2
                stderr = stderr1 + stderr2
192

193 194
            out += stdout
            err += stderr
195
            rc = rc + rc_state
196

197 198 199 200 201 202
    if rc != 0:

        print json.dumps({
            "failed" : 1,
            "rc"     : rc,
        })
203
        print >> sys.stderr, out + err
204
        sys.exit(1)
205

206

207 208
    # ===============================================
    # success
209

210
    result = {"changed": changed}
211 212

    rc, stdout, stderr = _run("%s %s status" % (SERVICE, name))
213 214 215 216
    if list_items and list_items in [ 'status' ]:
        result['status'] = stdout
    print json.dumps(result)

217
    
218 219 220 221 222 223 224 225 226 227 228 229
elif list_items is not None:

    # solo list=status mode, don't change anything, just return
    # suitable for /usr/bin/ansible usage or API, playbooks
    # not so much

    print json.dumps({
        "status" : status
    })

else:
 
230
    print json.dumps(dict(failed=True, msg="expected state or list parameters"))
231 232 233


sys.exit(0)
234