create_new_vm.py 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284
  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 == 'StandaloneVM' and self.template is not None:
  48. args = {
  49. 'ignore_volumes': ['private']
  50. }
  51. if self.pool:
  52. args['pool'] = self.pool
  53. vm = self.app.clone_vm(self.template, self.name,
  54. self.vmclass, **args)
  55. vm.label = self.label
  56. for k, v in self.properties.items():
  57. setattr(vm, k, v)
  58. else:
  59. args = {
  60. "name": self.name,
  61. "label": self.label,
  62. "template": self.template
  63. }
  64. if self.pool:
  65. args['pool'] = self.pool
  66. vm = self.app.add_new_vm(self.vmclass, **args)
  67. for k, v in self.properties.items():
  68. setattr(vm, k, v)
  69. except qubesadmin.exc.QubesException as qex:
  70. self.msg = str(qex)
  71. except Exception as ex: # pylint: disable=broad-except
  72. self.msg = repr(ex)
  73. class NewVmDlg(QtWidgets.QDialog, Ui_NewVMDlg):
  74. def __init__(self, qtapp, app, parent=None):
  75. super().__init__(parent)
  76. self.setupUi(self)
  77. self.qtapp = qtapp
  78. self.app = app
  79. self.thread = None
  80. self.progress = None
  81. utils.initialize_widget_with_labels(
  82. widget=self.label,
  83. qubes_app=self.app)
  84. utils.initialize_widget_with_vms(
  85. widget=self.template_vm,
  86. qubes_app=self.app,
  87. filter_function=(lambda vm: not utils.is_internal(vm) and
  88. vm.klass == 'TemplateVM'))
  89. default_template = self.app.default_template
  90. for i in range(self.template_vm.count()):
  91. if self.template_vm.itemData(i) == default_template:
  92. self.template_vm.setCurrentIndex(i)
  93. self.template_vm.setItemText(
  94. i, str(default_template) + " (default)")
  95. utils.initialize_widget_with_default(
  96. widget=self.netvm,
  97. choices=[(vm.name, vm) for vm in self.app.domains
  98. if not utils.is_internal(vm) and
  99. getattr(vm, 'provides_network', False)],
  100. add_none=True,
  101. add_qubes_default=True,
  102. default_value=getattr(self.app, 'default_netvm', None))
  103. try:
  104. utils.initialize_widget_with_default(
  105. widget=self.storage_pool,
  106. choices=[(str(pool), pool) for pool in self.app.pools.values()],
  107. add_qubes_default=True,
  108. mark_existing_as_default=True,
  109. default_value=self.app.default_pool)
  110. except qubesadmin.exc.QubesDaemonAccessError:
  111. self.storage_pool.clear()
  112. self.storage_pool.addItem("(default)", qubesadmin.DEFAULT)
  113. self.name.setValidator(QtGui.QRegExpValidator(
  114. QtCore.QRegExp("[a-zA-Z0-9_-]*", QtCore.Qt.CaseInsensitive), None))
  115. self.name.selectAll()
  116. self.name.setFocus()
  117. if self.template_vm.count() < 1:
  118. QtWidgets.QMessageBox.warning(
  119. self,
  120. self.tr('No template available!'),
  121. self.tr('Cannot create a qube when no template exists.'))
  122. type_list = [
  123. (self.tr("Qube based on a template (AppVM)"), 'AppVM'),
  124. (self.tr("Standalone qube copied from a template"),
  125. 'StandaloneVM-copy'),
  126. (self.tr("Empty standalone qube (install your own OS)"),
  127. 'StandaloneVM-empty')]
  128. utils.initialize_widget(widget=self.vm_type,
  129. choices=type_list,
  130. selected_value='AppVM',
  131. add_current_label=False)
  132. self.vm_type.currentIndexChanged.connect(self.type_change)
  133. self.launch_settings.stateChanged.connect(self.settings_change)
  134. self.install_system.stateChanged.connect(self.install_change)
  135. def reject(self):
  136. self.done(0)
  137. def accept(self):
  138. selected_type = self.vm_type.currentData()
  139. vmclass = selected_type.split('-')[0]
  140. name = str(self.name.text())
  141. if name in self.app.domains:
  142. QtWidgets.QMessageBox.warning(
  143. self,
  144. self.tr('Incorrect qube name!'),
  145. self.tr('A qube with the name <b>{}</b> already exists in the '
  146. 'system!').format(name))
  147. return
  148. label = self.label.currentData()
  149. template = self.template_vm.currentData()
  150. properties = {'provides_network': self.provides_network.isChecked()}
  151. if self.netvm.currentIndex() != 0:
  152. properties['netvm'] = self.netvm.currentData()
  153. # Standalone - not based on a template
  154. if selected_type == 'StandaloneVM-empty':
  155. properties['virt_mode'] = 'hvm'
  156. properties['kernel'] = None
  157. if self.storage_pool.currentData() is not qubesadmin.DEFAULT:
  158. pool = self.storage_pool.currentData()
  159. else:
  160. pool = None
  161. if self.init_ram.value() > 0:
  162. properties['memory'] = self.init_ram.value()
  163. self.thread = CreateVMThread(
  164. self.app, vmclass, name, label, template, properties, pool)
  165. self.thread.finished.connect(self.create_finished)
  166. self.thread.start()
  167. self.progress = QtWidgets.QProgressDialog(
  168. self.tr("Creating new qube <b>{0}</b>...").format(name), "", 0, 0)
  169. self.progress.setCancelButton(None)
  170. self.progress.setModal(True)
  171. self.progress.show()
  172. def create_finished(self):
  173. self.progress.hide()
  174. if self.thread.msg:
  175. QtWidgets.QMessageBox.warning(
  176. self,
  177. self.tr("Error creating the qube!"),
  178. self.tr("ERROR: {0}").format(self.thread.msg))
  179. self.done(0)
  180. if not self.thread.msg:
  181. if self.launch_settings.isChecked():
  182. subprocess.check_call(['qubes-vm-settings',
  183. str(self.name.text())])
  184. if self.install_system.isChecked():
  185. subprocess.check_call(
  186. ['qubes-vm-boot-from-device', str(self.name.text())])
  187. def type_change(self):
  188. if self.vm_type.currentData() == 'AppVM':
  189. self.template_vm.setEnabled(True)
  190. if self.template_vm.currentIndex() == -1:
  191. self.template_vm.setCurrentIndex(0)
  192. self.install_system.setEnabled(False)
  193. self.install_system.setChecked(False)
  194. if self.vm_type.currentData() == 'StandaloneVM-copy':
  195. self.template_vm.setEnabled(True)
  196. if self.template_vm.currentIndex() == -1:
  197. self.template_vm.setCurrentIndex(0)
  198. self.install_system.setEnabled(False)
  199. self.install_system.setChecked(False)
  200. if self.vm_type.currentData() == 'StandaloneVM-empty':
  201. self.template_vm.setEnabled(False)
  202. self.template_vm.setCurrentIndex(-1)
  203. self.install_system.setEnabled(True)
  204. self.install_system.setChecked(True)
  205. def install_change(self):
  206. if self.install_system.isChecked():
  207. self.launch_settings.setChecked(False)
  208. def settings_change(self):
  209. if self.launch_settings.isChecked() and self.install_system.isEnabled():
  210. self.install_system.setChecked(False)
  211. parser = qubesadmin.tools.QubesArgumentParser()
  212. def main(args=None):
  213. args = parser.parse_args(args)
  214. qtapp = QtWidgets.QApplication(sys.argv)
  215. translator = QtCore.QTranslator(qtapp)
  216. locale = QtCore.QLocale.system().name()
  217. i18n_dir = os.path.join(
  218. os.path.dirname(os.path.realpath(__file__)),
  219. 'i18n')
  220. translator.load("qubesmanager_{!s}.qm".format(locale), i18n_dir)
  221. qtapp.installTranslator(translator)
  222. QtCore.QCoreApplication.installTranslator(translator)
  223. qtapp.setOrganizationName('Invisible Things Lab')
  224. qtapp.setOrganizationDomain('https://www.qubes-os.org/')
  225. qtapp.setApplicationName(QtCore.QCoreApplication.translate(
  226. "appname", 'Create qube'))
  227. dialog = NewVmDlg(qtapp, args.app)
  228. dialog.exec_()