2
0

analyze-migration.py 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760
  1. #!/usr/bin/env python3
  2. #
  3. # Migration Stream Analyzer
  4. #
  5. # Copyright (c) 2015 Alexander Graf <agraf@suse.de>
  6. #
  7. # This library is free software; you can redistribute it and/or
  8. # modify it under the terms of the GNU Lesser General Public
  9. # License as published by the Free Software Foundation; either
  10. # version 2.1 of the License, or (at your option) any later version.
  11. #
  12. # This library 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 GNU
  15. # Lesser General Public License for more details.
  16. #
  17. # You should have received a copy of the GNU Lesser General Public
  18. # License along with this library; if not, see <http://www.gnu.org/licenses/>.
  19. import json
  20. import os
  21. import argparse
  22. import collections
  23. import struct
  24. import sys
  25. def mkdir_p(path):
  26. try:
  27. os.makedirs(path)
  28. except OSError:
  29. pass
  30. class MigrationFile(object):
  31. def __init__(self, filename):
  32. self.filename = filename
  33. self.file = open(self.filename, "rb")
  34. def read64(self):
  35. return int.from_bytes(self.file.read(8), byteorder='big', signed=False)
  36. def read32(self):
  37. return int.from_bytes(self.file.read(4), byteorder='big', signed=False)
  38. def read16(self):
  39. return int.from_bytes(self.file.read(2), byteorder='big', signed=False)
  40. def read8(self):
  41. return int.from_bytes(self.file.read(1), byteorder='big', signed=True)
  42. def readstr(self, len = None):
  43. return self.readvar(len).decode('utf-8')
  44. def readvar(self, size = None):
  45. if size is None:
  46. size = self.read8()
  47. if size == 0:
  48. return ""
  49. value = self.file.read(size)
  50. if len(value) != size:
  51. raise Exception("Unexpected end of %s at 0x%x" % (self.filename, self.file.tell()))
  52. return value
  53. def tell(self):
  54. return self.file.tell()
  55. def seek(self, a, b):
  56. return self.file.seek(a, b)
  57. # The VMSD description is at the end of the file, after EOF. Look for
  58. # the last NULL byte, then for the beginning brace of JSON.
  59. def read_migration_debug_json(self):
  60. QEMU_VM_VMDESCRIPTION = 0x06
  61. # Remember the offset in the file when we started
  62. entrypos = self.file.tell()
  63. # Read the last 10MB
  64. self.file.seek(0, os.SEEK_END)
  65. endpos = self.file.tell()
  66. self.file.seek(max(-endpos, -10 * 1024 * 1024), os.SEEK_END)
  67. datapos = self.file.tell()
  68. data = self.file.read()
  69. # The full file read closed the file as well, reopen it
  70. self.file = open(self.filename, "rb")
  71. # Find the last NULL byte, then the first brace after that. This should
  72. # be the beginning of our JSON data.
  73. nulpos = data.rfind(b'\0')
  74. jsonpos = data.find(b'{', nulpos)
  75. # Check backwards from there and see whether we guessed right
  76. self.file.seek(datapos + jsonpos - 5, 0)
  77. if self.read8() != QEMU_VM_VMDESCRIPTION:
  78. raise Exception("No Debug Migration device found")
  79. jsonlen = self.read32()
  80. # Seek back to where we were at the beginning
  81. self.file.seek(entrypos, 0)
  82. # explicit decode() needed for Python 3.5 compatibility
  83. return data[jsonpos:jsonpos + jsonlen].decode("utf-8")
  84. def close(self):
  85. self.file.close()
  86. class RamSection(object):
  87. RAM_SAVE_FLAG_COMPRESS = 0x02
  88. RAM_SAVE_FLAG_MEM_SIZE = 0x04
  89. RAM_SAVE_FLAG_PAGE = 0x08
  90. RAM_SAVE_FLAG_EOS = 0x10
  91. RAM_SAVE_FLAG_CONTINUE = 0x20
  92. RAM_SAVE_FLAG_XBZRLE = 0x40
  93. RAM_SAVE_FLAG_HOOK = 0x80
  94. RAM_SAVE_FLAG_COMPRESS_PAGE = 0x100
  95. RAM_SAVE_FLAG_MULTIFD_FLUSH = 0x200
  96. def __init__(self, file, version_id, ramargs, section_key):
  97. if version_id != 4:
  98. raise Exception("Unknown RAM version %d" % version_id)
  99. self.file = file
  100. self.section_key = section_key
  101. self.TARGET_PAGE_SIZE = ramargs['page_size']
  102. self.dump_memory = ramargs['dump_memory']
  103. self.write_memory = ramargs['write_memory']
  104. self.ignore_shared = ramargs['ignore_shared']
  105. self.sizeinfo = collections.OrderedDict()
  106. self.data = collections.OrderedDict()
  107. self.data['section sizes'] = self.sizeinfo
  108. self.name = ''
  109. if self.write_memory:
  110. self.files = { }
  111. if self.dump_memory:
  112. self.memory = collections.OrderedDict()
  113. self.data['memory'] = self.memory
  114. def __repr__(self):
  115. return self.data.__repr__()
  116. def __str__(self):
  117. return self.data.__str__()
  118. def getDict(self):
  119. return self.data
  120. def read(self):
  121. # Read all RAM sections
  122. while True:
  123. addr = self.file.read64()
  124. flags = addr & (self.TARGET_PAGE_SIZE - 1)
  125. addr &= ~(self.TARGET_PAGE_SIZE - 1)
  126. if flags & self.RAM_SAVE_FLAG_MEM_SIZE:
  127. total_length = addr
  128. while total_length > 0:
  129. namelen = self.file.read8()
  130. self.name = self.file.readstr(len = namelen)
  131. len = self.file.read64()
  132. total_length -= len
  133. self.sizeinfo[self.name] = '0x%016x' % len
  134. if self.write_memory:
  135. print(self.name)
  136. mkdir_p('./' + os.path.dirname(self.name))
  137. f = open('./' + self.name, "wb")
  138. f.truncate(0)
  139. f.truncate(len)
  140. self.files[self.name] = f
  141. if self.ignore_shared:
  142. mr_addr = self.file.read64()
  143. flags &= ~self.RAM_SAVE_FLAG_MEM_SIZE
  144. if flags & self.RAM_SAVE_FLAG_COMPRESS:
  145. if flags & self.RAM_SAVE_FLAG_CONTINUE:
  146. flags &= ~self.RAM_SAVE_FLAG_CONTINUE
  147. else:
  148. self.name = self.file.readstr()
  149. fill_char = self.file.read8()
  150. # The page in question is filled with fill_char now
  151. if self.write_memory and fill_char != 0:
  152. self.files[self.name].seek(addr, os.SEEK_SET)
  153. self.files[self.name].write(chr(fill_char) * self.TARGET_PAGE_SIZE)
  154. if self.dump_memory:
  155. self.memory['%s (0x%016x)' % (self.name, addr)] = 'Filled with 0x%02x' % fill_char
  156. flags &= ~self.RAM_SAVE_FLAG_COMPRESS
  157. elif flags & self.RAM_SAVE_FLAG_PAGE:
  158. if flags & self.RAM_SAVE_FLAG_CONTINUE:
  159. flags &= ~self.RAM_SAVE_FLAG_CONTINUE
  160. else:
  161. self.name = self.file.readstr()
  162. if self.write_memory or self.dump_memory:
  163. data = self.file.readvar(size = self.TARGET_PAGE_SIZE)
  164. else: # Just skip RAM data
  165. self.file.file.seek(self.TARGET_PAGE_SIZE, 1)
  166. if self.write_memory:
  167. self.files[self.name].seek(addr, os.SEEK_SET)
  168. self.files[self.name].write(data)
  169. if self.dump_memory:
  170. hexdata = " ".join("{0:02x}".format(ord(c)) for c in data)
  171. self.memory['%s (0x%016x)' % (self.name, addr)] = hexdata
  172. flags &= ~self.RAM_SAVE_FLAG_PAGE
  173. elif flags & self.RAM_SAVE_FLAG_XBZRLE:
  174. raise Exception("XBZRLE RAM compression is not supported yet")
  175. elif flags & self.RAM_SAVE_FLAG_HOOK:
  176. raise Exception("RAM hooks don't make sense with files")
  177. if flags & self.RAM_SAVE_FLAG_MULTIFD_FLUSH:
  178. continue
  179. # End of RAM section
  180. if flags & self.RAM_SAVE_FLAG_EOS:
  181. break
  182. if flags != 0:
  183. raise Exception("Unknown RAM flags: %x" % flags)
  184. def __del__(self):
  185. if self.write_memory:
  186. for key in self.files:
  187. self.files[key].close()
  188. class HTABSection(object):
  189. HASH_PTE_SIZE_64 = 16
  190. def __init__(self, file, version_id, device, section_key):
  191. if version_id != 1:
  192. raise Exception("Unknown HTAB version %d" % version_id)
  193. self.file = file
  194. self.section_key = section_key
  195. def read(self):
  196. header = self.file.read32()
  197. if (header == -1):
  198. # "no HPT" encoding
  199. return
  200. if (header > 0):
  201. # First section, just the hash shift
  202. return
  203. # Read until end marker
  204. while True:
  205. index = self.file.read32()
  206. n_valid = self.file.read16()
  207. n_invalid = self.file.read16()
  208. if index == 0 and n_valid == 0 and n_invalid == 0:
  209. break
  210. self.file.readvar(n_valid * self.HASH_PTE_SIZE_64)
  211. def getDict(self):
  212. return ""
  213. class S390StorageAttributes(object):
  214. STATTR_FLAG_EOS = 0x01
  215. STATTR_FLAG_MORE = 0x02
  216. STATTR_FLAG_ERROR = 0x04
  217. STATTR_FLAG_DONE = 0x08
  218. def __init__(self, file, version_id, device, section_key):
  219. if version_id != 0:
  220. raise Exception("Unknown storage_attributes version %d" % version_id)
  221. self.file = file
  222. self.section_key = section_key
  223. def read(self):
  224. pos = 0
  225. while True:
  226. addr_flags = self.file.read64()
  227. flags = addr_flags & 0xfff
  228. if flags & self.STATTR_FLAG_DONE:
  229. pos = self.file.tell()
  230. continue
  231. elif flags & self.STATTR_FLAG_EOS:
  232. return
  233. else:
  234. # No EOS came after DONE, that's OK, but rewind the
  235. # stream because this is not our data.
  236. if pos:
  237. self.file.seek(pos, os.SEEK_SET)
  238. return
  239. raise Exception("Unknown flags %x", flags)
  240. if (flags & self.STATTR_FLAG_ERROR):
  241. raise Exception("Error in migration stream")
  242. count = self.file.read64()
  243. self.file.readvar(count)
  244. def getDict(self):
  245. return ""
  246. class ConfigurationSection(object):
  247. def __init__(self, file, desc):
  248. self.file = file
  249. self.desc = desc
  250. self.caps = []
  251. def parse_capabilities(self, vmsd_caps):
  252. if not vmsd_caps:
  253. return
  254. ncaps = vmsd_caps.data['caps_count'].data
  255. self.caps = vmsd_caps.data['capabilities']
  256. if type(self.caps) != list:
  257. self.caps = [self.caps]
  258. if len(self.caps) != ncaps:
  259. raise Exception("Number of capabilities doesn't match "
  260. "caps_count field")
  261. def has_capability(self, cap):
  262. return any([str(c) == cap for c in self.caps])
  263. def read(self):
  264. if self.desc:
  265. version_id = self.desc['version']
  266. section = VMSDSection(self.file, version_id, self.desc,
  267. 'configuration')
  268. section.read()
  269. self.parse_capabilities(
  270. section.data.get("configuration/capabilities"))
  271. else:
  272. # backward compatibility for older streams that don't have
  273. # the configuration section in the json
  274. name_len = self.file.read32()
  275. name = self.file.readstr(len = name_len)
  276. class VMSDFieldGeneric(object):
  277. def __init__(self, desc, file):
  278. self.file = file
  279. self.desc = desc
  280. self.data = ""
  281. def __repr__(self):
  282. return str(self.__str__())
  283. def __str__(self):
  284. return " ".join("{0:02x}".format(c) for c in self.data)
  285. def getDict(self):
  286. return self.__str__()
  287. def read(self):
  288. size = int(self.desc['size'])
  289. self.data = self.file.readvar(size)
  290. return self.data
  291. class VMSDFieldCap(object):
  292. def __init__(self, desc, file):
  293. self.file = file
  294. self.desc = desc
  295. self.data = ""
  296. def __repr__(self):
  297. return self.data
  298. def __str__(self):
  299. return self.data
  300. def read(self):
  301. len = self.file.read8()
  302. self.data = self.file.readstr(len)
  303. class VMSDFieldInt(VMSDFieldGeneric):
  304. def __init__(self, desc, file):
  305. super(VMSDFieldInt, self).__init__(desc, file)
  306. self.size = int(desc['size'])
  307. self.format = '0x%%0%dx' % (self.size * 2)
  308. self.sdtype = '>i%d' % self.size
  309. self.udtype = '>u%d' % self.size
  310. def __repr__(self):
  311. if self.data < 0:
  312. return ('%s (%d)' % ((self.format % self.udata), self.data))
  313. else:
  314. return self.format % self.data
  315. def __str__(self):
  316. return self.__repr__()
  317. def getDict(self):
  318. return self.__str__()
  319. def read(self):
  320. super(VMSDFieldInt, self).read()
  321. self.sdata = int.from_bytes(self.data, byteorder='big', signed=True)
  322. self.udata = int.from_bytes(self.data, byteorder='big', signed=False)
  323. self.data = self.sdata
  324. return self.data
  325. class VMSDFieldUInt(VMSDFieldInt):
  326. def __init__(self, desc, file):
  327. super(VMSDFieldUInt, self).__init__(desc, file)
  328. def read(self):
  329. super(VMSDFieldUInt, self).read()
  330. self.data = self.udata
  331. return self.data
  332. class VMSDFieldIntLE(VMSDFieldInt):
  333. def __init__(self, desc, file):
  334. super(VMSDFieldIntLE, self).__init__(desc, file)
  335. self.dtype = '<i%d' % self.size
  336. class VMSDFieldNull(VMSDFieldGeneric):
  337. NULL_PTR_MARKER = b'0'
  338. def __init__(self, desc, file):
  339. super(VMSDFieldNull, self).__init__(desc, file)
  340. def __repr__(self):
  341. # A NULL pointer is encoded in the stream as a '0' to
  342. # disambiguate from a mere 0x0 value and avoid consumers
  343. # trying to follow the NULL pointer. Displaying '0', 0x30 or
  344. # 0x0 when analyzing the JSON debug stream could become
  345. # confusing, so use an explicit term instead.
  346. return "nullptr"
  347. def __str__(self):
  348. return self.__repr__()
  349. def read(self):
  350. super(VMSDFieldNull, self).read()
  351. assert(self.data == self.NULL_PTR_MARKER)
  352. return self.data
  353. class VMSDFieldBool(VMSDFieldGeneric):
  354. def __init__(self, desc, file):
  355. super(VMSDFieldBool, self).__init__(desc, file)
  356. def __repr__(self):
  357. return self.data.__repr__()
  358. def __str__(self):
  359. return self.data.__str__()
  360. def getDict(self):
  361. return self.data
  362. def read(self):
  363. super(VMSDFieldBool, self).read()
  364. if self.data[0] == 0:
  365. self.data = False
  366. else:
  367. self.data = True
  368. return self.data
  369. class VMSDFieldStruct(VMSDFieldGeneric):
  370. QEMU_VM_SUBSECTION = 0x05
  371. def __init__(self, desc, file):
  372. super(VMSDFieldStruct, self).__init__(desc, file)
  373. self.data = collections.OrderedDict()
  374. if 'fields' not in self.desc['struct']:
  375. raise Exception("No fields in struct. VMSD:\n%s" % self.desc)
  376. # When we see compressed array elements, unfold them here
  377. new_fields = []
  378. for field in self.desc['struct']['fields']:
  379. if not 'array_len' in field:
  380. new_fields.append(field)
  381. continue
  382. array_len = field.pop('array_len')
  383. field['index'] = 0
  384. new_fields.append(field)
  385. for i in range(1, array_len):
  386. c = field.copy()
  387. c['index'] = i
  388. new_fields.append(c)
  389. self.desc['struct']['fields'] = new_fields
  390. def __repr__(self):
  391. return self.data.__repr__()
  392. def __str__(self):
  393. return self.data.__str__()
  394. def read(self):
  395. for field in self.desc['struct']['fields']:
  396. try:
  397. reader = vmsd_field_readers[field['type']]
  398. except:
  399. reader = VMSDFieldGeneric
  400. field['data'] = reader(field, self.file)
  401. field['data'].read()
  402. fname = field['name']
  403. fdata = field['data']
  404. # The field could be:
  405. # i) a single data entry, e.g. uint64
  406. # ii) an array, indicated by it containing the 'index' key
  407. #
  408. # However, the overall data after parsing the whole
  409. # stream, could be a mix of arrays and single data fields,
  410. # all sharing the same field name due to how QEMU breaks
  411. # up arrays with NULL pointers into multiple compressed
  412. # array segments.
  413. if fname not in self.data:
  414. self.data[fname] = fdata
  415. elif type(self.data[fname]) == list:
  416. self.data[fname].append(fdata)
  417. else:
  418. tmp = self.data[fname]
  419. self.data[fname] = [tmp, fdata]
  420. if 'subsections' in self.desc['struct']:
  421. for subsection in self.desc['struct']['subsections']:
  422. if self.file.read8() != self.QEMU_VM_SUBSECTION:
  423. raise Exception("Subsection %s not found at offset %x" % ( subsection['vmsd_name'], self.file.tell()))
  424. name = self.file.readstr()
  425. version_id = self.file.read32()
  426. if not subsection:
  427. raise Exception("Empty description for subsection: %s" % name)
  428. self.data[name] = VMSDSection(self.file, version_id, subsection, (name, 0))
  429. self.data[name].read()
  430. def getDictItem(self, value):
  431. # Strings would fall into the array category, treat
  432. # them specially
  433. if value.__class__ is ''.__class__:
  434. return value
  435. try:
  436. return self.getDictOrderedDict(value)
  437. except:
  438. try:
  439. return self.getDictArray(value)
  440. except:
  441. try:
  442. return value.getDict()
  443. except:
  444. return value
  445. def getDictArray(self, array):
  446. r = []
  447. for value in array:
  448. r.append(self.getDictItem(value))
  449. return r
  450. def getDictOrderedDict(self, dict):
  451. r = collections.OrderedDict()
  452. for (key, value) in dict.items():
  453. r[key] = self.getDictItem(value)
  454. return r
  455. def getDict(self):
  456. return self.getDictOrderedDict(self.data)
  457. vmsd_field_readers = {
  458. "bool" : VMSDFieldBool,
  459. "int8" : VMSDFieldInt,
  460. "int16" : VMSDFieldInt,
  461. "int32" : VMSDFieldInt,
  462. "int32 equal" : VMSDFieldInt,
  463. "int32 le" : VMSDFieldIntLE,
  464. "int64" : VMSDFieldInt,
  465. "uint8" : VMSDFieldUInt,
  466. "uint16" : VMSDFieldUInt,
  467. "uint32" : VMSDFieldUInt,
  468. "uint32 equal" : VMSDFieldUInt,
  469. "uint64" : VMSDFieldUInt,
  470. "int64 equal" : VMSDFieldInt,
  471. "uint8 equal" : VMSDFieldInt,
  472. "uint16 equal" : VMSDFieldInt,
  473. "float64" : VMSDFieldGeneric,
  474. "timer" : VMSDFieldGeneric,
  475. "buffer" : VMSDFieldGeneric,
  476. "unused_buffer" : VMSDFieldGeneric,
  477. "bitmap" : VMSDFieldGeneric,
  478. "struct" : VMSDFieldStruct,
  479. "capability": VMSDFieldCap,
  480. "nullptr": VMSDFieldNull,
  481. "unknown" : VMSDFieldGeneric,
  482. }
  483. class VMSDSection(VMSDFieldStruct):
  484. def __init__(self, file, version_id, device, section_key):
  485. self.file = file
  486. self.data = ""
  487. self.vmsd_name = ""
  488. self.section_key = section_key
  489. desc = device
  490. if 'vmsd_name' in device:
  491. self.vmsd_name = device['vmsd_name']
  492. # A section really is nothing but a FieldStruct :)
  493. super(VMSDSection, self).__init__({ 'struct' : desc }, file)
  494. ###############################################################################
  495. class MigrationDump(object):
  496. QEMU_VM_FILE_MAGIC = 0x5145564d
  497. QEMU_VM_FILE_VERSION = 0x00000003
  498. QEMU_VM_EOF = 0x00
  499. QEMU_VM_SECTION_START = 0x01
  500. QEMU_VM_SECTION_PART = 0x02
  501. QEMU_VM_SECTION_END = 0x03
  502. QEMU_VM_SECTION_FULL = 0x04
  503. QEMU_VM_SUBSECTION = 0x05
  504. QEMU_VM_VMDESCRIPTION = 0x06
  505. QEMU_VM_CONFIGURATION = 0x07
  506. QEMU_VM_SECTION_FOOTER= 0x7e
  507. def __init__(self, filename):
  508. self.section_classes = {
  509. ( 'ram', 0 ) : [ RamSection, None ],
  510. ( 's390-storage_attributes', 0 ) : [ S390StorageAttributes, None],
  511. ( 'spapr/htab', 0) : ( HTABSection, None )
  512. }
  513. self.filename = filename
  514. self.vmsd_desc = None
  515. self.vmsd_json = ""
  516. def read(self, desc_only = False, dump_memory = False,
  517. write_memory = False):
  518. # Read in the whole file
  519. file = MigrationFile(self.filename)
  520. self.vmsd_json = file.read_migration_debug_json()
  521. # File magic
  522. data = file.read32()
  523. if data != self.QEMU_VM_FILE_MAGIC:
  524. raise Exception("Invalid file magic %x" % data)
  525. # Version (has to be v3)
  526. data = file.read32()
  527. if data != self.QEMU_VM_FILE_VERSION:
  528. raise Exception("Invalid version number %d" % data)
  529. self.load_vmsd_json(file)
  530. # Read sections
  531. self.sections = collections.OrderedDict()
  532. if desc_only:
  533. return
  534. ramargs = {}
  535. ramargs['page_size'] = self.vmsd_desc['page_size']
  536. ramargs['dump_memory'] = dump_memory
  537. ramargs['write_memory'] = write_memory
  538. ramargs['ignore_shared'] = False
  539. self.section_classes[('ram',0)][1] = ramargs
  540. while True:
  541. section_type = file.read8()
  542. if section_type == self.QEMU_VM_EOF:
  543. break
  544. elif section_type == self.QEMU_VM_CONFIGURATION:
  545. config_desc = self.vmsd_desc.get('configuration')
  546. section = ConfigurationSection(file, config_desc)
  547. section.read()
  548. ramargs['ignore_shared'] = section.has_capability('x-ignore-shared')
  549. elif section_type == self.QEMU_VM_SECTION_START or section_type == self.QEMU_VM_SECTION_FULL:
  550. section_id = file.read32()
  551. name = file.readstr()
  552. instance_id = file.read32()
  553. version_id = file.read32()
  554. section_key = (name, instance_id)
  555. classdesc = self.section_classes[section_key]
  556. section = classdesc[0](file, version_id, classdesc[1], section_key)
  557. self.sections[section_id] = section
  558. section.read()
  559. elif section_type == self.QEMU_VM_SECTION_PART or section_type == self.QEMU_VM_SECTION_END:
  560. section_id = file.read32()
  561. self.sections[section_id].read()
  562. elif section_type == self.QEMU_VM_SECTION_FOOTER:
  563. read_section_id = file.read32()
  564. if read_section_id != section_id:
  565. raise Exception("Mismatched section footer: %x vs %x" % (read_section_id, section_id))
  566. else:
  567. raise Exception("Unknown section type: %d" % section_type)
  568. file.close()
  569. def load_vmsd_json(self, file):
  570. self.vmsd_desc = json.loads(self.vmsd_json,
  571. object_pairs_hook=collections.OrderedDict)
  572. for device in self.vmsd_desc['devices']:
  573. if 'fields' not in device:
  574. raise Exception("vmstate for device %s has no fields" % device['name'])
  575. key = (device['name'], device['instance_id'])
  576. value = ( VMSDSection, device )
  577. self.section_classes[key] = value
  578. def getDict(self):
  579. r = collections.OrderedDict()
  580. for (key, value) in self.sections.items():
  581. key = "%s (%d)" % ( value.section_key[0], key )
  582. r[key] = value.getDict()
  583. return r
  584. ###############################################################################
  585. class JSONEncoder(json.JSONEncoder):
  586. def default(self, o):
  587. if isinstance(o, VMSDFieldGeneric):
  588. return str(o)
  589. return json.JSONEncoder.default(self, o)
  590. parser = argparse.ArgumentParser()
  591. parser.add_argument("-f", "--file", help='migration dump to read from', required=True)
  592. parser.add_argument("-m", "--memory", help='dump RAM contents as well', action='store_true')
  593. parser.add_argument("-d", "--dump", help='what to dump ("state" or "desc")', default='state')
  594. parser.add_argument("-x", "--extract", help='extract contents into individual files', action='store_true')
  595. args = parser.parse_args()
  596. jsonenc = JSONEncoder(indent=4, separators=(',', ': '))
  597. if not any([args.extract, args.dump == "state", args.dump == "desc"]):
  598. raise Exception("Please specify either -x, -d state or -d desc")
  599. try:
  600. dump = MigrationDump(args.file)
  601. if args.extract:
  602. dump.read(desc_only = True)
  603. print("desc.json")
  604. f = open("desc.json", "w")
  605. f.truncate()
  606. f.write(jsonenc.encode(dump.vmsd_desc))
  607. f.close()
  608. dump.read(write_memory = True)
  609. dict = dump.getDict()
  610. print("state.json")
  611. f = open("state.json", "w")
  612. f.truncate()
  613. f.write(jsonenc.encode(dict))
  614. f.close()
  615. elif args.dump == "state":
  616. dump.read(dump_memory = args.memory)
  617. dict = dump.getDict()
  618. print(jsonenc.encode(dict))
  619. elif args.dump == "desc":
  620. dump.read(desc_only = True)
  621. print(jsonenc.encode(dump.vmsd_desc))
  622. except Exception:
  623. raise Exception("Full JSON dump:\n%s", dump.vmsd_json)