__init__.py 6.46 KB
Newer Older
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
##############################################################################
#
# Copyright (c) 2013 Vifib SARL and Contributors. All Rights Reserved.
#
# WARNING: This program as such is intended to be used by professional
# programmers who take the whole responsibility of assessing all potential
# consequences resulting from its eventual inadequacies and bugs
# End users who are looking for a ready-to-use solution with commercial
# guarantees and support are strongly adviced to contract a Free Software
# Service Company
#
# This program 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.
#
# This program 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 this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
#
##############################################################################

import argparse
import json
import os
31
import pprint
32 33 34 35 36 37 38 39 40
import socket
import time

def parseArgument():
  """
  Very basic argument parser. Might blow up for anything else than
  "./executable mysocket.sock stop/resume".
  """
  parser = argparse.ArgumentParser()
41 42
  parser.add_argument('--suspend', action='store_const', dest='action', const='suspend')
  parser.add_argument('--resume', action='store_const', dest='action', const='resume')
43 44 45
  parser.add_argument('--create-snapshot', action='store_const', dest='action', const='createSnapshot')
  parser.add_argument('--create-internal-snapshot', action='store_const', dest='action', const='createInternalSnapshot')
  parser.add_argument('--delete-internal-snapshot', action='store_const', dest='action', const='deleteInternalSnapshot')
46
  parser.add_argument('--drive-backup', action='store_const', dest='action', const='driveBackup') 
47 48
  parser.add_argument('--query-commands', action='store_const', dest='action', const='queryCommands')

49 50
  parser.add_argument('--socket', dest='unix_socket_location', required=True)
  parser.add_argument('remainding_argument_list', nargs=argparse.REMAINDER)
51
  args = parser.parse_args()
52
  return args.unix_socket_location, args.action, args.remainding_argument_list
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


class QemuQMPWrapper(object):
  """
  Small wrapper around Qemu's QMP to control a qemu VM.
  See http://git.qemu.org/?p=qemu.git;a=blob;f=qmp-commands.hx for
  QMP API definition.
  """
  def __init__(self, unix_socket_location):
    self.socket = self.connectToQemu(unix_socket_location)
    self.capabilities()

  @staticmethod
  def connectToQemu(unix_socket_location):
    """
    Create a socket, connect to qemu, be sure it answers, return socket.
    """
    if not os.path.exists(unix_socket_location):
      raise Exception('unix socket %s does not exist.' % unix_socket_location)

    print 'Connecting to qemu...'
    so = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
    connected = False
    while not connected:
      try:
        so.connect(unix_socket_location)
      except socket.error:
        time.sleep(1)
        print 'Could not connect, retrying...'
      else:
        connected = True
    so.recv(1024)

    return so


  def _send(self, message):
    self.socket.send(json.dumps(message))
91
    data = self.socket.recv(65535)
92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131
    try:
      return json.loads(data)
    except ValueError:
      print 'Wrong data: %s' % data

  def _getVMStatus(self):
    response = self._send({'execute': 'query-status'})
    if response:
      return self._send({'execute': 'query-status'})['return']['status']
    else:
      raise IOError('Empty answer')

  def _waitForVMStatus(self, wanted_status):
    while True:
      try:
        actual_status = self._getVMStatus()
        if actual_status == wanted_status:
          return
        else:
          print 'VM in %s status, wanting it to be %s, retrying...' % (
              actual_status, wanted_status)
          time.sleep(1)
      except IOError:
          print 'VM not ready, retrying...'


  def capabilities(self):
    print 'Asking for capabilities...'
    self._send({'execute': 'qmp_capabilities'})

  def suspend(self):
    print 'Suspending VM...'
    self._send({'execute': 'stop'})
    self._waitForVMStatus('paused')

  def resume(self):
    print 'Resuming VM...'
    self._send({'execute': 'cont'})
    self._waitForVMStatus('running')

132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155
  def _queryBlockJobs(self, device):
    return self._send({'execute': 'query-block-jobs'})

  def _getRunningJobList(self, device):
    result = self._queryBlockJobs(device)
    if result.get('return'):
      return result['return']
    else:
      return

  def driveBackup(self, backup_target, source_device='virtio0', sync_type='full'):
    print 'Asking Qemu to perform backup to %s' % backup_target
    # XXX: check for error
    self._send({
        'execute': 'drive-backup',
        'arguments': {
            'device': source_device,
            'sync': sync_type,
            'target': backup_target,
         }
    })
    while self._getRunningJobList(backup_target):
      print 'Job is not finished yet.'
      time.sleep(20)
156

157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188
  def createSnapshot(self, snapshot_file, device='virtio0'):
    print self._send({
        'execute': 'blockdev-snapshot-sync',
        'arguments': {
            'device': device,
            'snapshot-file': snapshot_file,
         }
    })

  def createInternalSnapshot(self, name=None, device='virtio0'):
    if name is None:
      name = int(time.time())
    self._send({
        'execute': 'blockdev-snapshot-internal-sync',
        'arguments': {
            'device': device,
            'name': name,
         }
    })

  def deleteInternalSnapshot(self, name, device='virtio0'):
    self._send({
        'execute': 'blockdev-snapshot-delete-internal-sync',
        'arguments': {
            'device': device,
            'name': name,
         }
    })

  def queryCommands(self):
    pprint.pprint(self._send({'execute': 'query-commands'})['return'])

189
def main():
190
  unix_socket_location, action, remainding_argument_list = parseArgument()
191 192
  qemu_wrapper = QemuQMPWrapper(unix_socket_location)

193 194 195 196
  if remainding_argument_list:
    getattr(qemu_wrapper, action)(*remainding_argument_list)
  else:
    getattr(qemu_wrapper, action)()
197 198 199

if __name__ == '__main__':
  main()
200