create_new_vm.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335
  1. #!/usr/bin/python3
  2. #
  3. # The Qubes OS Project, http://www.qubes-os.org
  4. #
  5. # Copyright (C) 2012 Agnieszka Kostrzewa <agnieszka.kostrzewa@gmail.com>
  6. # Copyright (C) 2012 Marek Marczykowski <marmarek@mimuw.edu.pl>
  7. # Copyright (C) 2017 Wojtek Porczyk <woju@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 Lesser General Public License along
  20. # with this program; if not, see <http://www.gnu.org/licenses/>.
  21. #
  22. #
  23. import os
  24. import sys
  25. import subprocess
  26. from PyQt5 import QtCore, QtWidgets, QtGui # pylint: disable=import-error
  27. import qubesadmin
  28. import qubesadmin.tools
  29. import qubesadmin.exc
  30. from . import utils
  31. from .ui_newappvmdlg import Ui_NewVMDlg # pylint: disable=import-error
  32. # pylint: disable=too-few-public-methods
  33. class CreateVMThread(QtCore.QThread):
  34. def __init__(self, app, vmclass, name, label, template, properties,
  35. pool):
  36. QtCore.QThread.__init__(self)
  37. self.app = app
  38. self.vmclass = vmclass
  39. self.name = name
  40. self.label = label
  41. self.template = template
  42. self.properties = properties
  43. self.pool = pool
  44. self.msg = None
  45. def run(self):
  46. try:
  47. if self.vmclass == 'TemplateVM' and self.template is not None:
  48. args = {}
  49. if self.pool:
  50. args['pool'] = self.pool
  51. vm = self.app.clone_vm(self.template, self.name,
  52. self.vmclass, **args)
  53. vm.label = self.label
  54. elif self.vmclass == 'StandaloneVM' and self.template is not None:
  55. args = {
  56. 'ignore_volumes': ['private']
  57. }
  58. if self.pool:
  59. args['pool'] = self.pool
  60. vm = self.app.clone_vm(self.template, self.name,
  61. self.vmclass, **args)
  62. vm.label = self.label
  63. else:
  64. args = {
  65. "name": self.name,
  66. "label": self.label,
  67. "template": self.template
  68. }
  69. if self.pool:
  70. args['pool'] = self.pool
  71. vm = self.app.add_new_vm(self.vmclass, **args)
  72. for k, v in self.properties.items():
  73. setattr(vm, k, v)
  74. except qubesadmin.exc.QubesException as qex:
  75. self.msg = str(qex)
  76. except Exception as ex: # pylint: disable=broad-except
  77. self.msg = repr(ex)
  78. class NewVmDlg(QtWidgets.QDialog, Ui_NewVMDlg):
  79. def __init__(self, qtapp, app, parent=None):
  80. super().__init__(parent)
  81. self.setupUi(self)
  82. self.qtapp = qtapp
  83. self.app = app
  84. self.thread = None
  85. self.progress = None
  86. utils.initialize_widget_with_labels(
  87. widget=self.label,
  88. qubes_app=self.app)
  89. utils.initialize_widget_with_vms(
  90. widget=self.template_vm,
  91. qubes_app=self.app,
  92. filter_function=(lambda vm: not utils.is_internal(vm) and
  93. vm.klass == 'TemplateVM'),
  94. allow_none=True)
  95. default_template = self.app.default_template
  96. for i in range(self.template_vm.count()):
  97. if self.template_vm.itemData(i) == default_template:
  98. self.template_vm.setCurrentIndex(i)
  99. self.template_vm.setItemText(
  100. i, str(default_template) + " (default)")
  101. self.template_type = "template"
  102. utils.initialize_widget_with_default(
  103. widget=self.netvm,
  104. choices=[(vm.name, vm) for vm in self.app.domains
  105. if not utils.is_internal(vm) and
  106. getattr(vm, 'provides_network', False)],
  107. add_none=True,
  108. add_qubes_default=True,
  109. default_value=getattr(self.app, 'default_netvm', None))
  110. try:
  111. utils.initialize_widget_with_default(
  112. widget=self.storage_pool,
  113. choices=[(str(pool), pool) for pool in self.app.pools.values()],
  114. add_qubes_default=True,
  115. mark_existing_as_default=True,
  116. default_value=self.app.default_pool)
  117. except qubesadmin.exc.QubesDaemonAccessError:
  118. self.storage_pool.clear()
  119. self.storage_pool.addItem("(default)", qubesadmin.DEFAULT)
  120. self.name.setValidator(QtGui.QRegExpValidator(
  121. QtCore.QRegExp("[a-zA-Z0-9_-]*", QtCore.Qt.CaseInsensitive), None))
  122. self.name.selectAll()
  123. self.name.setFocus()
  124. if self.template_vm.count() < 1:
  125. QtWidgets.QMessageBox.warning(
  126. self,
  127. self.tr('No template available!'),
  128. self.tr('Cannot create a qube when no template exists.'))
  129. type_list = [
  130. (self.tr("AppVM (persistent home, volatile root)"), 'AppVM'),
  131. (self.tr("TemplateVM (template home, persistent root)"),
  132. 'TemplateVM'),
  133. (self.tr("StandaloneVM (fully persistent)"), 'StandaloneVM'),
  134. (self.tr("DisposableVM (fully volatile)"), 'DispVM')]
  135. utils.initialize_widget(widget=self.vm_type,
  136. choices=type_list,
  137. selected_value='AppVM',
  138. add_current_label=False)
  139. self.vm_type.currentIndexChanged.connect(self.type_change)
  140. self.template_vm.currentIndexChanged.connect(self.template_change)
  141. self.launch_settings.stateChanged.connect(self.settings_change)
  142. self.install_system.stateChanged.connect(self.install_change)
  143. def reject(self):
  144. self.done(0)
  145. def accept(self):
  146. vmclass = self.vm_type.currentData()
  147. name = str(self.name.text())
  148. if name in self.app.domains:
  149. QtWidgets.QMessageBox.warning(
  150. self,
  151. self.tr('Incorrect qube name!'),
  152. self.tr('A qube with the name <b>{}</b> already exists in the '
  153. 'system!').format(name))
  154. return
  155. label = self.label.currentData()
  156. template = self.template_vm.currentData()
  157. if vmclass in ['AppVM', 'DispVM'] and template is None:
  158. QtWidgets.QMessageBox.warning(
  159. self,
  160. self.tr('Unspecified template'),
  161. self.tr('{}s must be based on a template!'.format(vmclass)))
  162. return
  163. properties = {'provides_network': self.provides_network.isChecked()}
  164. if self.netvm.currentIndex() != 0:
  165. properties['netvm'] = self.netvm.currentData()
  166. # Standalone - not based on a template
  167. if vmclass == 'StandaloneVM' and template is None:
  168. properties['virt_mode'] = 'hvm'
  169. properties['kernel'] = None
  170. if self.storage_pool.currentData() is not qubesadmin.DEFAULT:
  171. pool = self.storage_pool.currentData()
  172. else:
  173. pool = None
  174. if self.init_ram.value() > 0:
  175. properties['memory'] = self.init_ram.value()
  176. self.thread = CreateVMThread(
  177. self.app, vmclass, name, label, template, properties, pool)
  178. self.thread.finished.connect(self.create_finished)
  179. self.thread.start()
  180. self.progress = QtWidgets.QProgressDialog(
  181. self.tr("Creating new qube <b>{0}</b>...").format(name), "", 0, 0)
  182. self.progress.setCancelButton(None)
  183. self.progress.setModal(True)
  184. self.progress.show()
  185. def create_finished(self):
  186. self.progress.hide()
  187. if self.thread.msg:
  188. QtWidgets.QMessageBox.warning(
  189. self,
  190. self.tr("Error creating the qube!"),
  191. self.tr("ERROR: {0}").format(self.thread.msg))
  192. self.done(0)
  193. if not self.thread.msg:
  194. if self.launch_settings.isChecked():
  195. subprocess.check_call(['qubes-vm-settings',
  196. str(self.name.text())])
  197. if self.install_system.isChecked():
  198. subprocess.check_call(
  199. ['qubes-vm-boot-from-device', str(self.name.text())])
  200. def type_change(self):
  201. template = self.template_vm.currentData()
  202. klass = self.vm_type.currentData()
  203. if klass in ['TemplateVM', 'StandaloneVM'] and template is None:
  204. self.install_system.setEnabled(True)
  205. self.install_system.setChecked(True)
  206. else:
  207. self.install_system.setEnabled(False)
  208. self.install_system.setChecked(False)
  209. if klass == 'DispVM':
  210. self.template_vm.clear()
  211. for vm in self.app.domains:
  212. if utils.is_internal(vm):
  213. continue
  214. if vm.klass != 'AppVM':
  215. continue
  216. if getattr(vm, 'template_for_dispvms', True):
  217. self.template_vm.addItem(vm.name, userData=vm)
  218. self.template_vm.insertItem(self.template_vm.count(),
  219. utils.translate("(none)"), None)
  220. self.template_vm.setCurrentIndex(0)
  221. self.template_type = "dispvm"
  222. elif self.template_type == "dispvm":
  223. self.template_vm.clear()
  224. for vm in self.app.domains:
  225. if utils.is_internal(vm):
  226. continue
  227. if vm.klass == 'TemplateVM':
  228. self.template_vm.addItem(vm.name, userData=vm)
  229. self.template_vm.insertItem(self.template_vm.count(),
  230. utils.translate("(none)"), None)
  231. self.template_vm.setCurrentIndex(0)
  232. self.template_type = "template"
  233. def template_change(self):
  234. template = self.template_vm.currentData()
  235. klass = self.vm_type.currentData()
  236. if klass in ['TemplateVM', 'StandaloneVM'] and template is None:
  237. self.install_system.setEnabled(True)
  238. self.install_system.setChecked(True)
  239. else:
  240. self.install_system.setEnabled(False)
  241. self.install_system.setChecked(False)
  242. def install_change(self):
  243. if self.install_system.isChecked():
  244. self.launch_settings.setChecked(False)
  245. def settings_change(self):
  246. if self.launch_settings.isChecked() and self.install_system.isEnabled():
  247. self.install_system.setChecked(False)
  248. parser = qubesadmin.tools.QubesArgumentParser()
  249. def main(args=None):
  250. args = parser.parse_args(args)
  251. qtapp = QtWidgets.QApplication(sys.argv)
  252. translator = QtCore.QTranslator(qtapp)
  253. locale = QtCore.QLocale.system().name()
  254. i18n_dir = os.path.join(
  255. os.path.dirname(os.path.realpath(__file__)),
  256. 'i18n')
  257. translator.load("qubesmanager_{!s}.qm".format(locale), i18n_dir)
  258. qtapp.installTranslator(translator)
  259. QtCore.QCoreApplication.installTranslator(translator)
  260. qtapp.setOrganizationName('Invisible Things Lab')
  261. qtapp.setOrganizationDomain('https://www.qubes-os.org/')
  262. qtapp.setApplicationName(QtCore.QCoreApplication.translate(
  263. "appname", 'Create qube'))
  264. dialog = NewVmDlg(qtapp, args.app)
  265. dialog.exec_()