core2migration.py 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266
  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. # pylint: disable=undefined-variable
  35. default=(lambda self: super(AppVM, self).dir_path),
  36. saver=qubes.property.dontsave,
  37. doc="VM storage directory",
  38. )
  39. def is_running(self):
  40. return False
  41. class StandaloneVM(qubes.vm.standalonevm.StandaloneVM):
  42. """core2 compatibility StandaloneVM class, with variable dir_path"""
  43. dir_path = qubes.property('dir_path',
  44. # pylint: disable=undefined-variable
  45. default=(lambda self: super(StandaloneVM, self).dir_path),
  46. saver=qubes.property.dontsave,
  47. doc="VM storage directory")
  48. def is_running(self):
  49. return False
  50. class Core2Qubes(qubes.Qubes):
  51. def __init__(self, store=None, load=True, **kwargs):
  52. if store is None:
  53. raise ValueError("store path required")
  54. super(Core2Qubes, self).__init__(store, load, **kwargs)
  55. def load_default_template(self, element):
  56. default_template = element.get("default_template")
  57. self.default_template = int(default_template) \
  58. if default_template.lower() != "none" else None
  59. def load_globals(self, element):
  60. default_netvm = element.get("default_netvm")
  61. if default_netvm is not None:
  62. self.default_netvm = int(default_netvm) \
  63. if default_netvm != "None" else None
  64. default_fw_netvm = element.get("default_fw_netvm")
  65. if default_fw_netvm is not None:
  66. self.default_fw_netvm = int(default_fw_netvm) \
  67. if default_fw_netvm != "None" else None
  68. updatevm = element.get("updatevm")
  69. if updatevm is not None:
  70. self.updatevm = int(updatevm) \
  71. if updatevm != "None" else None
  72. clockvm = element.get("clockvm")
  73. if clockvm is not None:
  74. self.clockvm = int(clockvm) \
  75. if clockvm != "None" else None
  76. def set_netvm_dependency(self, element):
  77. kwargs = {}
  78. attr_list = ("qid", "uses_default_netvm", "netvm_qid")
  79. for attribute in attr_list:
  80. kwargs[attribute] = element.get(attribute)
  81. vm = self.domains[int(kwargs["qid"])]
  82. if element.get("uses_default_netvm") is None:
  83. uses_default_netvm = True
  84. else:
  85. uses_default_netvm = (
  86. True if element.get("uses_default_netvm") == "True" else False)
  87. if not uses_default_netvm:
  88. netvm_qid = element.get("netvm_qid")
  89. if netvm_qid is None or netvm_qid == "none":
  90. vm.netvm = None
  91. else:
  92. vm.netvm = int(netvm_qid)
  93. def set_dispvm_netvm_dependency(self, element):
  94. kwargs = {}
  95. attr_list = ("qid", "uses_default_netvm", "netvm_qid")
  96. for attribute in attr_list:
  97. kwargs[attribute] = element.get(attribute)
  98. vm = self.domains[int(kwargs["qid"])]
  99. if element.get("uses_default_dispvm_netvm") is None:
  100. uses_default_dispvm_netvm = True
  101. else:
  102. uses_default_dispvm_netvm = (
  103. True if element.get("uses_default_dispvm_netvm") == "True"
  104. else False)
  105. if not uses_default_dispvm_netvm:
  106. dispvm_netvm_qid = element.get("dispvm_netvm_qid")
  107. if dispvm_netvm_qid is None or dispvm_netvm_qid == "none":
  108. dispvm_netvm = None
  109. else:
  110. dispvm_netvm = self.domains[int(dispvm_netvm_qid)]
  111. else:
  112. dispvm_netvm = vm.netvm
  113. if dispvm_netvm:
  114. dispvm_tpl_name = 'disp-{}'.format(dispvm_netvm.name)
  115. else:
  116. dispvm_tpl_name = 'disp-no-netvm'
  117. if dispvm_tpl_name not in self.domains:
  118. vm = self.add_new_vm(qubes.vm.appvm.AppVM,
  119. name=dispvm_tpl_name)
  120. # TODO: add support for #2075
  121. # TODO: set qrexec policy based on dispvm_netvm value
  122. def import_core2_vm(self, element):
  123. vm_class_name = element.tag
  124. try:
  125. kwargs = {}
  126. if vm_class_name in ["QubesTemplateVm", "QubesTemplateHVm"]:
  127. vm_class = qubes.vm.templatevm.TemplateVM
  128. elif element.get('template_qid').lower() == "none":
  129. kwargs['dir_path'] = element.get('dir_path')
  130. vm_class = StandaloneVM
  131. else:
  132. kwargs['dir_path'] = element.get('dir_path')
  133. kwargs['template'] = self.domains[int(element.get(
  134. 'template_qid'))]
  135. vm_class = AppVM
  136. # simple attributes
  137. for attr in ['installed_by_rpm', 'include_in_backups',
  138. 'qrexec_timeout', 'internal', 'label', 'name',
  139. 'vcpus', 'memory', 'maxmem', 'default_user',
  140. 'debug', 'pci_strictreset', 'mac', 'autostart']:
  141. value = element.get(attr)
  142. if value:
  143. kwargs[attr] = value
  144. # attributes with default value
  145. for attr in ["kernel", "kernelopts"]:
  146. value = element.get(attr)
  147. if value and value.lower() == "none":
  148. value = None
  149. value_is_default = element.get(
  150. "uses_default_{}".format(attr))
  151. if value_is_default and value_is_default.lower() != \
  152. "true":
  153. kwargs[attr] = value
  154. kwargs['hvm'] = "HVm" in vm_class_name
  155. vm = self.add_new_vm(vm_class,
  156. qid=int(element.get('qid')), **kwargs)
  157. services = element.get('services')
  158. if services:
  159. services = ast.literal_eval(services)
  160. else:
  161. services = {}
  162. for service, value in services.items():
  163. feature = service
  164. for repl_feature, repl_service in \
  165. qubes.ext.r3compatibility.\
  166. R3Compatibility.features_to_services.\
  167. items():
  168. if repl_service == service:
  169. feature = repl_feature
  170. vm.features[feature] = value
  171. for attr in ['backup_content', 'backup_path',
  172. 'backup_size']:
  173. value = element.get(attr)
  174. vm.features[attr.replace('_', '-')] = value
  175. pcidevs = element.get('pcidevs')
  176. if pcidevs:
  177. pcidevs = ast.literal_eval(pcidevs)
  178. for pcidev in pcidevs:
  179. try:
  180. vm.devices["pci"].attach(
  181. self.domains[0].devices['pci'][pcidev])
  182. except qubes.exc.QubesException as e:
  183. self.log.error("VM {}: {}".format(vm.name, str(e)))
  184. except (ValueError, LookupError) as err:
  185. self.log.error("import error ({1}): {2}".format(
  186. vm_class_name, err))
  187. if 'vm' in locals():
  188. del self.domains[vm]
  189. def load(self):
  190. qubes_store_file = open(self._store, 'r')
  191. try:
  192. qubes_store_file.seek(0)
  193. tree = lxml.etree.parse(qubes_store_file)
  194. except (EnvironmentError, # pylint: disable=broad-except
  195. xml.parsers.expat.ExpatError) as err:
  196. self.log.error(err)
  197. return False
  198. self.load_initial_values()
  199. self.default_kernel = tree.getroot().get("default_kernel")
  200. vm_classes = ["TemplateVm", "TemplateHVm",
  201. "AppVm", "HVm", "NetVm", "ProxyVm"]
  202. # First load templates
  203. for vm_class_name in ["TemplateVm", "TemplateHVm"]:
  204. vms_of_class = tree.findall("Qubes" + vm_class_name)
  205. for element in vms_of_class:
  206. self.import_core2_vm(element)
  207. # Then set default template ...
  208. self.load_default_template(tree.getroot())
  209. # ... and load other VMs
  210. for vm_class_name in ["AppVm", "HVm", "NetVm", "ProxyVm"]:
  211. vms_of_class = tree.findall("Qubes" + vm_class_name)
  212. # first non-template based, then template based
  213. sorted_vms_of_class = sorted(vms_of_class,
  214. key=lambda x: str(x.get('template_qid')).lower() != "none")
  215. for element in sorted_vms_of_class:
  216. self.import_core2_vm(element)
  217. # After importing all VMs, set netvm references, in the same order
  218. for vm_class_name in vm_classes:
  219. for element in tree.findall("Qubes" + vm_class_name):
  220. try:
  221. self.set_netvm_dependency(element)
  222. except (ValueError, LookupError) as err:
  223. self.log.error("VM {}: failed to set netvm dependency: {}".
  224. format(element.get('name'), err))
  225. # and load other defaults (default netvm, updatevm etc)
  226. self.load_globals(tree.getroot())
  227. def save(self):
  228. raise NotImplementedError("Saving old qubes.xml not supported")