core2migration.py 8.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229
  1. #!/usr/bin/python
  2. # -*- coding: utf-8 -*-
  3. #
  4. # The Qubes OS Project, http://www.qubes-os.org
  5. #
  6. # Copyright (C) 2016 Marek Marczykowski-Górecki
  7. # <marmarek@invisiblethingslab.com>
  8. #
  9. # This program is free software; you can redistribute it and/or
  10. # modify it under the terms of the GNU General Public License
  11. # as published by the Free Software Foundation; either version 2
  12. # of the License, or (at your option) any later version.
  13. #
  14. # This program is distributed in the hope that it will be useful,
  15. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  16. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  17. # GNU General Public License for more details.
  18. #
  19. # You should have received a copy of the GNU General Public License
  20. # along with this program. If not, see <http://www.gnu.org/licenses/>
  21. #
  22. import ast
  23. import xml.parsers.expat
  24. import lxml.etree
  25. import qubes
  26. import qubes.vm.appvm
  27. import qubes.vm.standalonevm
  28. import qubes.vm.templatevm
  29. import qubes.vm.adminvm
  30. import qubes.ext.r3compatibility
  31. class AppVM(qubes.vm.appvm.AppVM):
  32. """core2 compatibility AppVM class, with variable dir_path"""
  33. dir_path = qubes.property('dir_path',
  34. default=(lambda self: self.storage.vmdir),
  35. saver=qubes.property.dontsave,
  36. doc="VM storage directory",
  37. )
  38. def is_running(self):
  39. return False
  40. class StandaloneVM(qubes.vm.standalonevm.StandaloneVM):
  41. """core2 compatibility StandaloneVM class, with variable dir_path"""
  42. dir_path = qubes.property('dir_path',
  43. default=(lambda self: self.storage.vmdir),
  44. saver=qubes.property.dontsave,
  45. doc="VM storage directory")
  46. def is_running(self):
  47. return False
  48. class Core2Qubes(qubes.Qubes):
  49. def __init__(self, store=None, load=True, **kwargs):
  50. if store is None:
  51. raise ValueError("store path required")
  52. super(Core2Qubes, self).__init__(store, load, **kwargs)
  53. def load_default_template(self, element):
  54. default_template = element.get("default_template")
  55. self.default_template = int(default_template) \
  56. if default_template.lower() != "none" else None
  57. def load_globals(self, element):
  58. default_netvm = element.get("default_netvm")
  59. if default_netvm is not None:
  60. self.default_netvm = int(default_netvm) \
  61. if default_netvm != "None" else None
  62. default_fw_netvm = element.get("default_fw_netvm")
  63. if default_fw_netvm is not None:
  64. self.default_fw_netvm = int(default_fw_netvm) \
  65. if default_fw_netvm != "None" else None
  66. updatevm = element.get("updatevm")
  67. if updatevm is not None:
  68. self.updatevm = int(updatevm) \
  69. if updatevm != "None" else None
  70. clockvm = element.get("clockvm")
  71. if clockvm is not None:
  72. self.clockvm = int(clockvm) \
  73. if clockvm != "None" else None
  74. def set_netvm_dependency(self, element):
  75. kwargs = {}
  76. attr_list = ("qid", "uses_default_netvm", "netvm_qid")
  77. for attribute in attr_list:
  78. kwargs[attribute] = element.get(attribute)
  79. vm = self.domains[int(kwargs["qid"])]
  80. if element.get("uses_default_netvm") is None:
  81. uses_default_netvm = True
  82. else:
  83. uses_default_netvm = (
  84. True if element.get("uses_default_netvm") == "True" else False)
  85. if not uses_default_netvm:
  86. netvm_qid = element.get("netvm_qid")
  87. if netvm_qid is None or netvm_qid == "none":
  88. vm.netvm = None
  89. else:
  90. vm.netvm = int(netvm_qid)
  91. # TODO: dispvm_netvm
  92. def import_core2_vm(self, element):
  93. vm_class_name = element.tag
  94. try:
  95. kwargs = {}
  96. if vm_class_name in ["TemplateVm", "TemplateHVm"]:
  97. vm_class = qubes.vm.templatevm.TemplateVM
  98. elif element.get('template_qid').lower() == "none":
  99. kwargs['dir_path'] = element.get('dir_path')
  100. vm_class = StandaloneVM
  101. else:
  102. kwargs['dir_path'] = element.get('dir_path')
  103. kwargs['template'] = int(element.get('template_qid'))
  104. vm_class = AppVM
  105. # simple attributes
  106. for attr in ['installed_by_rpm', 'include_in_backups',
  107. 'qrexec_timeout', 'internal', 'label', 'name',
  108. 'vcpus', 'memory', 'maxmem', 'default_user',
  109. 'debug', 'pci_strictreset', 'mac', 'autostart']:
  110. value = element.get(attr)
  111. if value:
  112. kwargs[attr] = value
  113. # attributes with default value
  114. for attr in ["kernel", "kernelopts"]:
  115. value = element.get(attr)
  116. if value and value.lower() == "none":
  117. value = None
  118. value_is_default = element.get(
  119. "uses_default_{}".format(attr))
  120. if value_is_default and value_is_default.lower() != \
  121. "true":
  122. kwargs[attr] = value
  123. kwargs['hvm'] = "HVm" in vm_class_name
  124. vm = self.add_new_vm(vm_class,
  125. qid=int(element.get('qid')), **kwargs)
  126. services = element.get('services')
  127. if services:
  128. services = ast.literal_eval(services)
  129. else:
  130. services = {}
  131. for service, value in services.iteritems():
  132. feature = service
  133. for repl_feature, repl_service in \
  134. qubes.ext.r3compatibility.\
  135. R3Compatibility.features_to_services.\
  136. iteritems():
  137. if repl_service == service:
  138. feature = repl_feature
  139. vm.features[feature] = value
  140. for attr in ['backup_content', 'backup_path',
  141. 'backup_size']:
  142. value = element.get(attr)
  143. vm.features[attr.replace('_', '-')] = value
  144. pcidevs = element.get('pcidevs')
  145. if pcidevs:
  146. pcidevs = ast.literal_eval(pcidevs)
  147. for pcidev in pcidevs:
  148. try:
  149. vm.devices["pci"].attach(pcidev)
  150. except qubes.exc.QubesException as e:
  151. self.log.error("VM {}: {}".format(vm.name, str(e)))
  152. except (ValueError, LookupError) as err:
  153. self.log.error("import error ({1}): {2}".format(
  154. vm_class_name, err))
  155. if 'vm' in locals():
  156. del self.domains[vm]
  157. def load(self):
  158. qubes_store_file = open(self._store, 'r')
  159. try:
  160. qubes_store_file.seek(0)
  161. tree = lxml.etree.parse(qubes_store_file)
  162. except (EnvironmentError, # pylint: disable=broad-except
  163. xml.parsers.expat.ExpatError) as err:
  164. self.log.error(err)
  165. return False
  166. self.load_initial_values()
  167. self.default_kernel = tree.getroot().get("default_kernel")
  168. vm_classes = ["TemplateVm", "TemplateHVm",
  169. "AppVm", "HVm", "NetVm", "ProxyVm"]
  170. # First load templates
  171. for vm_class_name in ["TemplateVm", "TemplateHVm"]:
  172. vms_of_class = tree.findall("Qubes" + vm_class_name)
  173. for element in vms_of_class:
  174. self.import_core2_vm(element)
  175. # Then set default template ...
  176. self.load_default_template(tree.getroot())
  177. # ... and load other VMs
  178. for vm_class_name in ["AppVm", "HVm", "NetVm", "ProxyVm"]:
  179. vms_of_class = tree.findall("Qubes" + vm_class_name)
  180. # first non-template based, then template based
  181. sorted_vms_of_class = sorted(vms_of_class,
  182. key=lambda x: str(x.get('template_qid')).lower() != "none")
  183. for element in sorted_vms_of_class:
  184. self.import_core2_vm(element)
  185. # After importing all VMs, set netvm references, in the same order
  186. for vm_class_name in vm_classes:
  187. for element in tree.findall("Qubes" + vm_class_name):
  188. try:
  189. self.set_netvm_dependency(element)
  190. except (ValueError, LookupError) as err:
  191. self.log.error("VM {}: failed to set netvm dependency: {}".
  192. format(element.get('name'), err))
  193. # and load other defaults (default netvm, updatevm etc)
  194. self.load_globals(tree.getroot())
  195. def save(self):
  196. raise NotImplementedError("Saving old qubes.xml not supported")