qemu-ga-client 8.2 KB

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