2
0

qemu-ga-client 8.2 KB

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