2
0

bench_block_job.py 5.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158
  1. #!/usr/bin/env python3
  2. #
  3. # Benchmark block jobs
  4. #
  5. # Copyright (c) 2019 Virtuozzo International GmbH.
  6. #
  7. # This program is free software; you can redistribute it and/or modify
  8. # it under the terms of the GNU General Public License as published by
  9. # the Free Software Foundation; either version 2 of the License, or
  10. # (at your option) any later version.
  11. #
  12. # This program is distributed in the hope that it will be useful,
  13. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  14. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  15. # GNU General Public License for more details.
  16. #
  17. # You should have received a copy of the GNU General Public License
  18. # along with this program. If not, see <http://www.gnu.org/licenses/>.
  19. #
  20. import sys
  21. import os
  22. import subprocess
  23. import socket
  24. import json
  25. sys.path.append(os.path.join(os.path.dirname(__file__), '..', '..', 'python'))
  26. from qemu.machine import QEMUMachine
  27. from qemu.qmp import ConnectError
  28. def bench_block_job(cmd, cmd_args, qemu_args):
  29. """Benchmark block-job
  30. cmd -- qmp command to run block-job (like blockdev-backup)
  31. cmd_args -- dict of qmp command arguments
  32. qemu_args -- list of Qemu command line arguments, including path to Qemu
  33. binary
  34. Returns {'seconds': int} on success and {'error': str} on failure, dict may
  35. contain addional 'vm-log' field. Return value is compatible with
  36. simplebench lib.
  37. """
  38. vm = QEMUMachine(qemu_args[0], args=qemu_args[1:])
  39. try:
  40. vm.launch()
  41. except OSError as e:
  42. return {'error': 'popen failed: ' + str(e)}
  43. except (ConnectError, socket.timeout):
  44. return {'error': 'qemu failed: ' + str(vm.get_log())}
  45. try:
  46. res = vm.qmp(cmd, **cmd_args)
  47. if res != {'return': {}}:
  48. vm.shutdown()
  49. return {'error': '"{}" command failed: {}'.format(cmd, str(res))}
  50. e = vm.event_wait('JOB_STATUS_CHANGE')
  51. assert e['data']['status'] == 'created'
  52. start_ms = e['timestamp']['seconds'] * 1000000 + \
  53. e['timestamp']['microseconds']
  54. e = vm.events_wait((('BLOCK_JOB_READY', None),
  55. ('BLOCK_JOB_COMPLETED', None),
  56. ('BLOCK_JOB_FAILED', None)), timeout=True)
  57. if e['event'] not in ('BLOCK_JOB_READY', 'BLOCK_JOB_COMPLETED'):
  58. vm.shutdown()
  59. return {'error': 'block-job failed: ' + str(e),
  60. 'vm-log': vm.get_log()}
  61. if 'error' in e['data']:
  62. vm.shutdown()
  63. return {'error': 'block-job failed: ' + e['data']['error'],
  64. 'vm-log': vm.get_log()}
  65. end_ms = e['timestamp']['seconds'] * 1000000 + \
  66. e['timestamp']['microseconds']
  67. finally:
  68. vm.shutdown()
  69. return {'seconds': (end_ms - start_ms) / 1000000.0}
  70. def get_image_size(path):
  71. out = subprocess.run(['qemu-img', 'info', '--out=json', path],
  72. stdout=subprocess.PIPE, check=True).stdout
  73. return json.loads(out)['virtual-size']
  74. def get_blockdev_size(obj):
  75. img = obj['filename'] if 'filename' in obj else obj['file']['filename']
  76. return get_image_size(img)
  77. # Bench backup or mirror
  78. def bench_block_copy(qemu_binary, cmd, cmd_options, source, target):
  79. """Helper to run bench_block_job() for mirror or backup"""
  80. assert cmd in ('blockdev-backup', 'blockdev-mirror')
  81. if target['driver'] == 'qcow2':
  82. try:
  83. os.remove(target['file']['filename'])
  84. except OSError:
  85. pass
  86. subprocess.run(['qemu-img', 'create', '-f', 'qcow2',
  87. target['file']['filename'],
  88. str(get_blockdev_size(source))],
  89. stdout=subprocess.DEVNULL,
  90. stderr=subprocess.DEVNULL, check=True)
  91. source['node-name'] = 'source'
  92. target['node-name'] = 'target'
  93. cmd_options['job-id'] = 'job0'
  94. cmd_options['device'] = 'source'
  95. cmd_options['target'] = 'target'
  96. cmd_options['sync'] = 'full'
  97. return bench_block_job(cmd, cmd_options,
  98. [qemu_binary,
  99. '-blockdev', json.dumps(source),
  100. '-blockdev', json.dumps(target)])
  101. def drv_file(filename, o_direct=True):
  102. node = {'driver': 'file', 'filename': filename}
  103. if o_direct:
  104. node['cache'] = {'direct': True}
  105. node['aio'] = 'native'
  106. return node
  107. def drv_nbd(host, port):
  108. return {'driver': 'nbd',
  109. 'server': {'type': 'inet', 'host': host, 'port': port}}
  110. def drv_qcow2(file):
  111. return {'driver': 'qcow2', 'file': file}
  112. if __name__ == '__main__':
  113. import sys
  114. if len(sys.argv) < 4:
  115. print('USAGE: {} <qmp block-job command name> '
  116. '<json string of arguments for the command> '
  117. '<qemu binary path and arguments>'.format(sys.argv[0]))
  118. exit(1)
  119. res = bench_block_job(sys.argv[1], json.loads(sys.argv[2]), sys.argv[3:])
  120. if 'seconds' in res:
  121. print('{:.2f}'.format(res['seconds']))
  122. else:
  123. print(res)