fireball 7.84 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
#!/usr/bin/python
# -*- coding: utf-8 -*-

# (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/>.

21 22 23
DOCUMENTATION = '''
---
module: fireball
Jan-Piet Mens committed
24
short_description: Enable fireball mode on remote node
25
description:
26
     - This modules launches an ephemeral I(fireball) ZeroMQ message bus daemon on the remote node which
Jan-Piet Mens committed
27
       Ansible can use to communicate with nodes at high speed.
28 29 30
     - The daemon listens on a configurable port for a configurable amount of time.
     - Starting a new fireball as a given user terminates any existing user fireballs.
     - Fireball mode is AES encrypted
31 32 33 34 35 36 37 38 39 40
version_added: "0.9"
options:
  port:
    description:
      - TCP port for ZeroMQ
    required: false
    default: 5099
    aliases: []
  minutes:
    description:
Jan-Piet Mens committed
41
      - The I(fireball) listener daemon is started on nodes and will stay around for
42
        this number of minutes before turning itself off.
43 44 45
    required: false
    default: 30
notes:
46
    - See the advanced playbooks chapter for more about using fireball mode.
47 48 49 50
requirements: [ "zmq", "keyczar" ]
author: Michael DeHaan
'''

Michael DeHaan committed
51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67
EXAMPLES = '''
# This example playbook has two plays: the first launches 'fireball' mode on all hosts via SSH, and 
# the second actually starts using it for subsequent management over the fireball connection

- hosts: devservers
  gather_facts: false
  connection: ssh
  sudo: yes
  tasks:
      - action: fireball

- hosts: devservers
  connection: fireball
  tasks:
      - command: /usr/bin/anything
'''

68 69 70 71 72 73 74
import os
import sys
import shutil
import time
import base64
import syslog
import signal
75 76
import time
import signal
77
import traceback
78 79 80 81 82

syslog.openlog('ansible-%s' % os.path.basename(__file__))
PIDFILE = os.path.expanduser("~/.fireball.pid")

def log(msg):
Michael DeHaan committed
83
    syslog.syslog(syslog.LOG_NOTICE, msg)
84 85 86 87 88 89 90 91 92 93 94 95 96 97

if os.path.exists(PIDFILE):
    try:
        data = int(open(PIDFILE).read())
        try:
            os.kill(data, signal.SIGKILL)
        except OSError:
            pass
    except ValueError:
        pass
    os.unlink(PIDFILE)

HAS_ZMQ = False
try:
Michael DeHaan committed
98 99
    import zmq
    HAS_ZMQ = True
100
except ImportError:
Michael DeHaan committed
101
    pass
102 103 104

HAS_KEYCZAR = False
try:
Michael DeHaan committed
105 106
    from keyczar.keys import AesKey
    HAS_KEYCZAR = True
107
except ImportError:
Michael DeHaan committed
108
    pass
109 110 111 112 113 114 115 116 117 118 119

# NOTE: this shares a fair amount of code in common with async_wrapper, if async_wrapper were a new module we could move
# this into utils.module_common and probably should anyway

def daemonize_self(module, password, port, minutes):
    # daemonizing code: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/66012
    try:
        pid = os.fork()
        if pid > 0:
            log("exiting pid %s" % pid)
            # exit first parent
Michael DeHaan committed
120
            module.exit_json(msg="daemonized fireball on port %s for %s minutes" % (port, minutes))
121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149
    except OSError, e:
        log("fork #1 failed: %d (%s)" % (e.errno, e.strerror))
        sys.exit(1)

    # decouple from parent environment
    os.chdir("/")
    os.setsid()
    os.umask(022)

    # do second fork
    try:
        pid = os.fork()
        if pid > 0:
            log("daemon pid %s, writing %s" % (pid, PIDFILE))
            pid_file = open(PIDFILE, "w")
            pid_file.write("%s" % pid)
            pid_file.close()
            log("pidfile written")
            sys.exit(0)
    except OSError, e:
        log("fork #2 failed: %d (%s)" % (e.errno, e.strerror))
        sys.exit(1)

    dev_null = file('/dev/null','rw')
    os.dup2(dev_null.fileno(), sys.stdin.fileno())
    os.dup2(dev_null.fileno(), sys.stdout.fileno())
    os.dup2(dev_null.fileno(), sys.stderr.fileno())
    log("daemonizing successful (%s,%s)" % (password, port))

150
def command(module, data):
151 152 153 154
    if 'cmd' not in data:
        return dict(failed=True, msg='internal error: cmd is required')
    if 'tmp_path' not in data:
        return dict(failed=True, msg='internal error: tmp_path is required')
155 156
    if 'executable' not in data:
        return dict(failed=True, msg='internal error: executable is required')
157 158

    log("executing: %s" % data['cmd'])
159
    rc, stdout, stderr = module.run_command(data['cmd'], executable=data['executable'], close_fds=True)
160 161 162 163 164 165
    if stdout is None:
        stdout = ''
    if stderr is None:
        stderr = ''
    log("got stdout: %s" % stdout)

166
    return dict(rc=rc, stdout=stdout, stderr=stderr)
Jan-Piet Mens committed
167

168 169
def fetch(data):
    if 'in_path' not in data:
170 171 172 173 174
        return dict(failed=True, msg='internal error: in_path is required')

    # FIXME: should probably support chunked file transfer for binary files
    # at some point.  For now, just base64 encodes the file
    # so don't use it to move ISOs, use rsync.
175 176

    fh = open(data['in_path'])
177
    data = base64.b64encode(fh.read())
178 179 180 181 182 183 184 185
    return dict(data=data)

def put(data):

    if 'data' not in data:
        return dict(failed=True, msg='internal error: data is required')
    if 'out_path' not in data:
        return dict(failed=True, msg='internal error: out_path is required')
Jan-Piet Mens committed
186

187 188 189
    # FIXME: should probably support chunked file transfer for binary files
    # at some point.  For now, just base64 encodes the file
    # so don't use it to move ISOs, use rsync.
190 191

    fh = open(data['out_path'], 'w')
192
    fh.write(base64.b64decode(data['data']))
193 194 195 196 197 198
    fh.close()

    return dict()

def serve(module, password, port, minutes):

199

200 201 202 203 204 205 206 207 208 209 210
    log("serving")
    context = zmq.Context()
    socket = context.socket(zmq.REP)
    addr = "tcp://*:%s" % port
    log("zmq serving on %s" % addr)
    socket.bind(addr)

    # password isn't so much a password but a serialized AesKey object that we xferred over SSH
    # password as a variable in ansible is never logged though, so it serves well

    key = AesKey.Read(password)
Jan-Piet Mens committed
211

212 213 214
    while True:

        data = socket.recv()
215 216 217 218 219 220

        try:
            data = key.Decrypt(data)
        except:
            continue

221 222 223 224 225 226
        data = json.loads(data)

        mode = data['mode']
        response = {}

        if mode == 'command':
227
            response = command(module, data)
228 229 230 231 232 233 234 235 236 237 238 239 240
        elif mode == 'put':
            response = put(data)
        elif mode == 'fetch':
            response = fetch(data)

        data2 = json.dumps(response)
        data2 = key.Encrypt(data2)
        socket.send(data2)

def daemonize(module, password, port, minutes):

    try:
        daemonize_self(module, password, port, minutes)
241 242 243 244 245 246 247 248

        def catcher(signum, _):
            module.exit_json(msg='timer expired')

        signal.signal(signal.SIGALRM, catcher)
        signal.setitimer(signal.ITIMER_REAL, 60 * minutes)


249 250
        serve(module, password, port, minutes)
    except Exception, e:
251 252
        tb = traceback.format_exc()
        log("exception caught, exiting fireball mode: %s\n%s" % (e, tb))
253 254 255 256 257 258 259 260 261
        sys.exit(0)

def main():

    module = AnsibleModule(
        argument_spec = dict(
            port=dict(required=False, default=5099),
            password=dict(required=True),
            minutes=dict(required=False, default=30),
262 263
        ),
        supports_check_mode=True
264 265 266 267
    )

    password  = base64.b64decode(module.params['password'])
    port      = module.params['port']
268
    minutes   = int(module.params['minutes'])
269 270 271 272

    if not HAS_ZMQ:
        module.fail_json(msg="zmq is not installed")
    if not HAS_KEYCZAR:
Jan-Piet Mens committed
273
        module.fail_json(msg="keyczar is not installed")
274 275

    daemonize(module, password, port, minutes)
Jan-Piet Mens committed
276

277

278
# import module snippets
279
from ansible.module_utils.basic import *
280
main()