qemu-ga-client 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301
  1. #!/usr/bin/python
  2. # QEMU Guest Agent Client
  3. #
  4. # Copyright (C) 2012 Ryota Ozaki <ozaki.ryota@gmail.com>
  5. #
  6. # This work is licensed under the terms of the GNU GPL, version 2. See
  7. # the COPYING file in the top-level directory.
  8. #
  9. # Usage:
  10. #
  11. # Start QEMU with:
  12. #
  13. # # qemu [...] -chardev socket,path=/tmp/qga.sock,server,nowait,id=qga0 \
  14. # -device virtio-serial -device virtserialport,chardev=qga0,name=org.qemu.guest_agent.0
  15. #
  16. # Run the script:
  17. #
  18. # $ qemu-ga-client --address=/tmp/qga.sock <command> [args...]
  19. #
  20. # or
  21. #
  22. # $ export QGA_CLIENT_ADDRESS=/tmp/qga.sock
  23. # $ qemu-ga-client <command> [args...]
  24. #
  25. # For example:
  26. #
  27. # $ qemu-ga-client cat /etc/resolv.conf
  28. # # Generated by NetworkManager
  29. # nameserver 10.0.2.3
  30. # $ qemu-ga-client fsfreeze status
  31. # thawed
  32. # $ qemu-ga-client fsfreeze freeze
  33. # 2 filesystems frozen
  34. #
  35. # See also: https://wiki.qemu.org/Features/QAPI/GuestAgent
  36. #
  37. import base64
  38. import random
  39. import qmp
  40. class QemuGuestAgent(qmp.QEMUMonitorProtocol):
  41. def __getattr__(self, name):
  42. def wrapper(**kwds):
  43. return self.command('guest-' + name.replace('_', '-'), **kwds)
  44. return wrapper
  45. class QemuGuestAgentClient:
  46. error = QemuGuestAgent.error
  47. def __init__(self, address):
  48. self.qga = QemuGuestAgent(address)
  49. self.qga.connect(negotiate=False)
  50. def sync(self, timeout=3):
  51. # Avoid being blocked forever
  52. if not self.ping(timeout):
  53. raise EnvironmentError('Agent seems not alive')
  54. uid = random.randint(0, (1 << 32) - 1)
  55. while True:
  56. ret = self.qga.sync(id=uid)
  57. if isinstance(ret, int) and int(ret) == uid:
  58. break
  59. def __file_read_all(self, handle):
  60. eof = False
  61. data = ''
  62. while not eof:
  63. ret = self.qga.file_read(handle=handle, count=1024)
  64. _data = base64.b64decode(ret['buf-b64'])
  65. data += _data
  66. eof = ret['eof']
  67. return data
  68. def read(self, path):
  69. handle = self.qga.file_open(path=path)
  70. try:
  71. data = self.__file_read_all(handle)
  72. finally:
  73. self.qga.file_close(handle=handle)
  74. return data
  75. def info(self):
  76. info = self.qga.info()
  77. msgs = []
  78. msgs.append('version: ' + info['version'])
  79. msgs.append('supported_commands:')
  80. enabled = [c['name'] for c in info['supported_commands'] if c['enabled']]
  81. msgs.append('\tenabled: ' + ', '.join(enabled))
  82. disabled = [c['name'] for c in info['supported_commands'] if not c['enabled']]
  83. msgs.append('\tdisabled: ' + ', '.join(disabled))
  84. return '\n'.join(msgs)
  85. def __gen_ipv4_netmask(self, prefixlen):
  86. mask = int('1' * prefixlen + '0' * (32 - prefixlen), 2)
  87. return '.'.join([str(mask >> 24),
  88. str((mask >> 16) & 0xff),
  89. str((mask >> 8) & 0xff),
  90. str(mask & 0xff)])
  91. def ifconfig(self):
  92. nifs = self.qga.network_get_interfaces()
  93. msgs = []
  94. for nif in nifs:
  95. msgs.append(nif['name'] + ':')
  96. if 'ip-addresses' in nif:
  97. for ipaddr in nif['ip-addresses']:
  98. if ipaddr['ip-address-type'] == 'ipv4':
  99. addr = ipaddr['ip-address']
  100. mask = self.__gen_ipv4_netmask(int(ipaddr['prefix']))
  101. msgs.append("\tinet %s netmask %s" % (addr, mask))
  102. elif ipaddr['ip-address-type'] == 'ipv6':
  103. addr = ipaddr['ip-address']
  104. prefix = ipaddr['prefix']
  105. msgs.append("\tinet6 %s prefixlen %s" % (addr, prefix))
  106. if nif['hardware-address'] != '00:00:00:00:00:00':
  107. msgs.append("\tether " + nif['hardware-address'])
  108. return '\n'.join(msgs)
  109. def ping(self, timeout):
  110. self.qga.settimeout(timeout)
  111. try:
  112. self.qga.ping()
  113. except self.qga.timeout:
  114. return False
  115. return True
  116. def fsfreeze(self, cmd):
  117. if cmd not in ['status', 'freeze', 'thaw']:
  118. raise StandardError('Invalid command: ' + cmd)
  119. return getattr(self.qga, 'fsfreeze' + '_' + cmd)()
  120. def fstrim(self, minimum=0):
  121. return getattr(self.qga, 'fstrim')(minimum=minimum)
  122. def suspend(self, mode):
  123. if mode not in ['disk', 'ram', 'hybrid']:
  124. raise StandardError('Invalid mode: ' + mode)
  125. try:
  126. getattr(self.qga, 'suspend' + '_' + mode)()
  127. # On error exception will raise
  128. except self.qga.timeout:
  129. # On success command will timed out
  130. return
  131. def shutdown(self, mode='powerdown'):
  132. if mode not in ['powerdown', 'halt', 'reboot']:
  133. raise StandardError('Invalid mode: ' + mode)
  134. try:
  135. self.qga.shutdown(mode=mode)
  136. except self.qga.timeout:
  137. return
  138. def _cmd_cat(client, args):
  139. if len(args) != 1:
  140. print('Invalid argument')
  141. print('Usage: cat <file>')
  142. sys.exit(1)
  143. print(client.read(args[0]))
  144. def _cmd_fsfreeze(client, args):
  145. usage = 'Usage: fsfreeze status|freeze|thaw'
  146. if len(args) != 1:
  147. print('Invalid argument')
  148. print(usage)
  149. sys.exit(1)
  150. if args[0] not in ['status', 'freeze', 'thaw']:
  151. print('Invalid command: ' + args[0])
  152. print(usage)
  153. sys.exit(1)
  154. cmd = args[0]
  155. ret = client.fsfreeze(cmd)
  156. if cmd == 'status':
  157. print(ret)
  158. elif cmd == 'freeze':
  159. print("%d filesystems frozen" % ret)
  160. else:
  161. print("%d filesystems thawed" % ret)
  162. def _cmd_fstrim(client, args):
  163. if len(args) == 0:
  164. minimum = 0
  165. else:
  166. minimum = int(args[0])
  167. print(client.fstrim(minimum))
  168. def _cmd_ifconfig(client, args):
  169. print(client.ifconfig())
  170. def _cmd_info(client, args):
  171. print(client.info())
  172. def _cmd_ping(client, args):
  173. if len(args) == 0:
  174. timeout = 3
  175. else:
  176. timeout = float(args[0])
  177. alive = client.ping(timeout)
  178. if not alive:
  179. print("Not responded in %s sec" % args[0])
  180. sys.exit(1)
  181. def _cmd_suspend(client, args):
  182. usage = 'Usage: suspend disk|ram|hybrid'
  183. if len(args) != 1:
  184. print('Less argument')
  185. print(usage)
  186. sys.exit(1)
  187. if args[0] not in ['disk', 'ram', 'hybrid']:
  188. print('Invalid command: ' + args[0])
  189. print(usage)
  190. sys.exit(1)
  191. client.suspend(args[0])
  192. def _cmd_shutdown(client, args):
  193. client.shutdown()
  194. _cmd_powerdown = _cmd_shutdown
  195. def _cmd_halt(client, args):
  196. client.shutdown('halt')
  197. def _cmd_reboot(client, args):
  198. client.shutdown('reboot')
  199. commands = [m.replace('_cmd_', '') for m in dir() if '_cmd_' in m]
  200. def main(address, cmd, args):
  201. if not os.path.exists(address):
  202. print('%s not found' % address)
  203. sys.exit(1)
  204. if cmd not in commands:
  205. print('Invalid command: ' + cmd)
  206. print('Available commands: ' + ', '.join(commands))
  207. sys.exit(1)
  208. try:
  209. client = QemuGuestAgentClient(address)
  210. except QemuGuestAgent.error as e:
  211. import errno
  212. print(e)
  213. if e.errno == errno.ECONNREFUSED:
  214. print('Hint: qemu is not running?')
  215. sys.exit(1)
  216. if cmd == 'fsfreeze' and args[0] == 'freeze':
  217. client.sync(60)
  218. elif cmd != 'ping':
  219. client.sync()
  220. globals()['_cmd_' + cmd](client, args)
  221. if __name__ == '__main__':
  222. import sys
  223. import os
  224. import optparse
  225. address = os.environ['QGA_CLIENT_ADDRESS'] if 'QGA_CLIENT_ADDRESS' in os.environ else None
  226. usage = "%prog [--address=<unix_path>|<ipv4_address>] <command> [args...]\n"
  227. usage += '<command>: ' + ', '.join(commands)
  228. parser = optparse.OptionParser(usage=usage)
  229. parser.add_option('--address', action='store', type='string',
  230. default=address, help='Specify a ip:port pair or a unix socket path')
  231. options, args = parser.parse_args()
  232. address = options.address
  233. if address is None:
  234. parser.error('address is not specified')
  235. sys.exit(1)
  236. if len(args) == 0:
  237. parser.error('Less argument')
  238. sys.exit(1)
  239. main(address, args[0], args[1:])