2
0

analyze-migration.py 23 KB

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