global_settings.py 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427
  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. #
  8. # This program is free software; you can redistribute it and/or
  9. # modify it under the terms of the GNU General Public License
  10. # as published by the Free Software Foundation; either version 2
  11. # of the License, or (at your option) any later version.
  12. #
  13. # This program is distributed in the hope that it will be useful,
  14. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  15. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  16. # GNU General Public License for more details.
  17. #
  18. # You should have received a copy of the GNU Lesser General Public License along
  19. # with this program; if not, see <http://www.gnu.org/licenses/>.
  20. #
  21. #
  22. import os
  23. import subprocess
  24. from PyQt5 import QtWidgets, QtCore, QtGui # pylint: disable=import-error
  25. from qubesadmin.utils import parse_size
  26. from . import ui_globalsettingsdlg # pylint: disable=no-name-in-module
  27. from . import utils
  28. from configparser import ConfigParser
  29. qmemman_config_path = '/etc/qubes/qmemman.conf'
  30. def _run_qrexec_repo(service, arg=''):
  31. # Set default locale to C in order to prevent error msg
  32. # in subprocess call related to falling back to C locale
  33. env = os.environ.copy()
  34. env['LC_ALL'] = 'C'
  35. # Fake up a "qrexec call" to dom0 because dom0 can't qrexec to itself yet
  36. cmd = '/etc/qubes-rpc/' + service
  37. p = subprocess.run(
  38. ['sudo', cmd, arg],
  39. stdout=subprocess.PIPE,
  40. stderr=subprocess.PIPE,
  41. check=False,
  42. env=env
  43. )
  44. if p.stderr:
  45. raise RuntimeError(
  46. QtCore.QCoreApplication.translate(
  47. "GlobalSettings", 'qrexec call stderr was not empty'),
  48. {'stderr': p.stderr.decode('utf-8')})
  49. if p.returncode != 0:
  50. raise RuntimeError(
  51. QtCore.QCoreApplication.translate(
  52. "GlobalSettings",
  53. 'qrexec call exited with non-zero return code'),
  54. {'returncode': p.returncode})
  55. return p.stdout.decode('utf-8')
  56. # pylint: disable=too-many-instance-attributes
  57. class GlobalSettingsWindow(ui_globalsettingsdlg.Ui_GlobalSettings,
  58. QtWidgets.QDialog):
  59. def __init__(self, app, qvm_collection, parent=None):
  60. super(GlobalSettingsWindow, self).__init__(parent)
  61. self.app = app
  62. self.qvm_collection = qvm_collection
  63. self.setupUi(self)
  64. self.buttonBox.accepted.connect(self.save_and_apply)
  65. self.buttonBox.rejected.connect(self.reject)
  66. self.__init_system_defaults__()
  67. self.__init_kernel_defaults__()
  68. self.__init_mem_defaults__()
  69. self.__init_updates__()
  70. def setup_application(self):
  71. self.app.setApplicationName(self.tr("Qubes Global Settings"))
  72. self.app.setWindowIcon(QtGui.QIcon.fromTheme("qubes-manager"))
  73. def __init_system_defaults__(self):
  74. # set up updatevm choice
  75. self.update_vm_vmlist, self.update_vm_idx = utils.prepare_vm_choice(
  76. self.update_vm_combo, self.qvm_collection, 'updatevm',
  77. None, allow_none=True,
  78. filter_function=(lambda vm: vm.klass != 'TemplateVM')
  79. )
  80. # set up clockvm choice
  81. self.clock_vm_vmlist, self.clock_vm_idx = utils.prepare_vm_choice(
  82. self.clock_vm_combo, self.qvm_collection, 'clockvm',
  83. None, allow_none=True,
  84. filter_function=(lambda vm: vm.klass != 'TemplateVM')
  85. )
  86. # set up default netvm
  87. self.default_netvm_vmlist, self.default_netvm_idx = \
  88. utils.prepare_vm_choice(
  89. self.default_netvm_combo,
  90. self.qvm_collection, 'default_netvm',
  91. None,
  92. filter_function=(lambda vm: vm.provides_network),
  93. allow_none=True)
  94. # default template
  95. self.default_template_vmlist, self.default_template_idx = \
  96. utils.prepare_vm_choice(
  97. self.default_template_combo,
  98. self.qvm_collection, 'default_template',
  99. None,
  100. filter_function=(lambda vm: vm.klass == 'TemplateVM'),
  101. allow_none=True
  102. )
  103. # default dispvm
  104. self.default_dispvm_vmlist, self.default_dispvm_idx = \
  105. utils.prepare_vm_choice(
  106. self.default_dispvm_combo,
  107. self.qvm_collection, 'default_dispvm',
  108. None,
  109. (lambda vm: getattr(vm, 'template_for_dispvms', False)),
  110. allow_none=True
  111. )
  112. def __apply_system_defaults__(self):
  113. # updatevm
  114. if self.qvm_collection.updatevm != \
  115. self.update_vm_vmlist[self.update_vm_combo.currentIndex()]:
  116. self.qvm_collection.updatevm = \
  117. self.update_vm_vmlist[self.update_vm_combo.currentIndex()]
  118. # clockvm
  119. if self.qvm_collection.clockvm != \
  120. self.clock_vm_vmlist[self.clock_vm_combo.currentIndex()]:
  121. self.qvm_collection.clockvm = \
  122. self.clock_vm_vmlist[self.clock_vm_combo.currentIndex()]
  123. # default netvm
  124. if self.qvm_collection.default_netvm != \
  125. self.default_netvm_vmlist[
  126. self.default_netvm_combo.currentIndex()]:
  127. self.qvm_collection.default_netvm = \
  128. self.default_netvm_vmlist[
  129. self.default_netvm_combo.currentIndex()]
  130. # default template
  131. if self.qvm_collection.default_template != \
  132. self.default_template_vmlist[
  133. self.default_template_combo.currentIndex()]:
  134. self.qvm_collection.default_template = \
  135. self.default_template_vmlist[
  136. self.default_template_combo.currentIndex()]
  137. # default_dispvm
  138. if self.qvm_collection.default_dispvm != \
  139. self.default_dispvm_vmlist[
  140. self.default_dispvm_combo.currentIndex()]:
  141. self.qvm_collection.default_dispvm = \
  142. self.default_dispvm_vmlist[
  143. self.default_dispvm_combo.currentIndex()]
  144. def __init_kernel_defaults__(self):
  145. self.kernels_list, self.kernels_idx = utils.prepare_kernel_choice(
  146. self.default_kernel_combo, self.qvm_collection, 'default_kernel',
  147. None,
  148. allow_none=True
  149. )
  150. def __apply_kernel_defaults__(self):
  151. if self.qvm_collection.default_kernel != \
  152. self.kernels_list[self.default_kernel_combo.currentIndex()]:
  153. self.qvm_collection.default_kernel = \
  154. self.kernels_list[self.default_kernel_combo.currentIndex()]
  155. def __init_mem_defaults__(self):
  156. # qmemman settings
  157. self.qmemman_config = ConfigParser()
  158. self.vm_min_mem_val = '200MiB' # str(qmemman_algo.MIN_PREFMEM)
  159. self.dom0_mem_boost_val = '350MiB' # str(qmemman_algo.DOM0_MEM_BOOST)
  160. self.qmemman_config.read(qmemman_config_path)
  161. if self.qmemman_config.has_section('global'):
  162. self.vm_min_mem_val = \
  163. self.qmemman_config.get('global', 'vm-min-mem')
  164. self.dom0_mem_boost_val = \
  165. self.qmemman_config.get('global', 'dom0-mem-boost')
  166. self.vm_min_mem_val = parse_size(self.vm_min_mem_val)
  167. self.dom0_mem_boost_val = parse_size(self.dom0_mem_boost_val)
  168. self.min_vm_mem.setValue(self.vm_min_mem_val / 1024 / 1024)
  169. self.dom0_mem_boost.setValue(self.dom0_mem_boost_val / 1024 / 1024)
  170. def __apply_mem_defaults__(self):
  171. # qmemman settings
  172. current_min_vm_mem = self.min_vm_mem.value()
  173. current_dom0_mem_boost = self.dom0_mem_boost.value()
  174. if current_min_vm_mem * 1024 * 1024 != self.vm_min_mem_val or \
  175. current_dom0_mem_boost * 1024 * 1024 != self.dom0_mem_boost_val:
  176. current_min_vm_mem = str(current_min_vm_mem) + 'MiB'
  177. current_dom0_mem_boost = str(current_dom0_mem_boost) + 'MiB'
  178. if not self.qmemman_config.has_section('global'):
  179. # add the whole section
  180. self.qmemman_config.add_section('global')
  181. self.qmemman_config.set(
  182. 'global', 'vm-min-mem', current_min_vm_mem)
  183. self.qmemman_config.set(
  184. 'global', 'dom0-mem-boost', current_dom0_mem_boost)
  185. self.qmemman_config.set(
  186. 'global', 'cache-margin-factor', str(1.3))
  187. # removed qmemman_algo.CACHE_FACTOR
  188. qmemman_config_file = open(qmemman_config_path, 'a')
  189. self.qmemman_config.write(qmemman_config_file)
  190. qmemman_config_file.close()
  191. else:
  192. # If there already is a 'global' section, we don't use
  193. # SafeConfigParser.write() - it would get rid of
  194. # all the comments...
  195. lines_to_add = {}
  196. lines_to_add['vm-min-mem'] = \
  197. "vm-min-mem = " + current_min_vm_mem + "\n"
  198. lines_to_add['dom0-mem-boost'] = \
  199. "dom0-mem-boost = " + current_dom0_mem_boost + "\n"
  200. config_lines = []
  201. qmemman_config_file = open(qmemman_config_path, 'r')
  202. for line in qmemman_config_file:
  203. if line.strip().startswith('vm-min-mem'):
  204. config_lines.append(lines_to_add['vm-min-mem'])
  205. del lines_to_add['vm-min-mem']
  206. elif line.strip().startswith('dom0-mem-boost'):
  207. config_lines.append(lines_to_add['dom0-mem-boost'])
  208. del lines_to_add['dom0-mem-boost']
  209. else:
  210. config_lines.append(line)
  211. qmemman_config_file.close()
  212. for line in lines_to_add:
  213. config_lines.append(line)
  214. qmemman_config_file = open(qmemman_config_path, 'w')
  215. qmemman_config_file.writelines(config_lines)
  216. qmemman_config_file.close()
  217. def __init_updates__(self):
  218. try:
  219. self.updates_dom0_val = bool(self.qvm_collection.domains[
  220. 'dom0'].features[
  221. 'service.qubes-update-check'])
  222. except KeyError:
  223. self.updates_dom0_val = True
  224. self.updates_dom0.setChecked(self.updates_dom0_val)
  225. self.updates_vm.setChecked(self.qvm_collection.check_updates_vm)
  226. self.enable_updates_all.clicked.connect(self.__enable_updates_all)
  227. self.disable_updates_all.clicked.connect(self.__disable_updates_all)
  228. self.repos = repos = dict()
  229. for i in _run_qrexec_repo('qubes.repos.List').split('\n'):
  230. lst = i.split('\0')
  231. # Keyed by repo name
  232. dct = repos[lst[0]] = dict()
  233. dct['prettyname'] = lst[1]
  234. dct['enabled'] = lst[2] == 'enabled'
  235. if repos['qubes-dom0-unstable']['enabled']:
  236. self.dom0_updates_repo.setCurrentIndex(3)
  237. elif repos['qubes-dom0-current-testing']['enabled']:
  238. self.dom0_updates_repo.setCurrentIndex(2)
  239. elif repos['qubes-dom0-security-testing']['enabled']:
  240. self.dom0_updates_repo.setCurrentIndex(1)
  241. elif repos['qubes-dom0-current']['enabled']:
  242. self.dom0_updates_repo.setCurrentIndex(0)
  243. else:
  244. raise Exception(
  245. self.tr('Cannot detect enabled dom0 update repositories'))
  246. if repos['qubes-templates-itl-testing']['enabled']:
  247. self.itl_tmpl_updates_repo.setCurrentIndex(1)
  248. elif repos['qubes-templates-itl']['enabled']:
  249. self.itl_tmpl_updates_repo.setCurrentIndex(0)
  250. else:
  251. raise Exception(self.tr('Cannot detect enabled ITL template update '
  252. 'repositories'))
  253. if repos['qubes-templates-community-testing']['enabled']:
  254. self.comm_tmpl_updates_repo.setCurrentIndex(2)
  255. elif repos['qubes-templates-community']['enabled']:
  256. self.comm_tmpl_updates_repo.setCurrentIndex(1)
  257. else:
  258. self.comm_tmpl_updates_repo.setCurrentIndex(0)
  259. def __enable_updates_all(self):
  260. reply = QtWidgets.QMessageBox.question(
  261. self, self.tr("Change state of all qubes"),
  262. self.tr("Are you sure you want to set all qubes to check "
  263. "for updates?"),
  264. QtWidgets.QMessageBox.Yes | QtWidgets.QMessageBox.Cancel)
  265. if reply == QtWidgets.QMessageBox.Cancel:
  266. return
  267. self.__set_updates_all(True)
  268. def __disable_updates_all(self):
  269. reply = QtWidgets.QMessageBox.question(
  270. self, self.tr("Change state of all qubes"),
  271. self.tr("Are you sure you want to set all qubes to not check "
  272. "for updates?"),
  273. QtWidgets.QMessageBox.Yes | QtWidgets.QMessageBox.Cancel)
  274. if reply == QtWidgets.QMessageBox.Cancel:
  275. return
  276. self.__set_updates_all(False)
  277. def __set_updates_all(self, state):
  278. for vm in self.qvm_collection.domains:
  279. if vm.klass != "AdminVM":
  280. vm.features['service.qubes-update-check'] = state
  281. def __apply_updates__(self):
  282. if self.updates_dom0.isChecked() != self.updates_dom0_val:
  283. self.qvm_collection.domains['dom0'].features[
  284. 'service.qubes-update-check'] = \
  285. self.updates_dom0.isChecked()
  286. if self.qvm_collection.check_updates_vm != self.updates_vm.isChecked():
  287. self.qvm_collection.check_updates_vm = self.updates_vm.isChecked()
  288. def _manage_repos(self, repolist, action):
  289. for name in repolist:
  290. if self.repos[name]['enabled'] and action == 'Enable' or \
  291. not self.repos[name]['enabled'] and action == 'Disable':
  292. continue
  293. try:
  294. result = _run_qrexec_repo('qubes.repos.' + action, name)
  295. if result != 'ok\n':
  296. raise RuntimeError(
  297. self.tr('qrexec call stdout did not contain "ok"'
  298. ' as expected'),
  299. {'stdout': result})
  300. except RuntimeError as ex:
  301. msg = '{desc}; {args}'.format(desc=ex.args[0], args=', '.join(
  302. # This is kind of hard to mentally parse but really all
  303. # it does is pretty-print args[1], which is a dictionary
  304. ['{key}: {val}'.format(key=i[0], val=i[1]) for i in
  305. ex.args[1].items()]
  306. ))
  307. QtWidgets.QMessageBox.warning(
  308. None,
  309. self.tr("ERROR!"),
  310. self.tr("Error managing {repo} repository settings:"
  311. " {msg}".format(repo=name, msg=msg)))
  312. def _handle_dom0_updates_combobox(self, idx):
  313. idx += 1
  314. repolist = ['qubes-dom0-current', 'qubes-dom0-security-testing',
  315. 'qubes-dom0-current-testing', 'qubes-dom0-unstable']
  316. enable = repolist[:idx]
  317. disable = repolist[idx:]
  318. self._manage_repos(enable, 'Enable')
  319. self._manage_repos(disable, 'Disable')
  320. # pylint: disable=invalid-name
  321. def _handle_itl_tmpl_updates_combobox(self, idx):
  322. idx += 1
  323. repolist = ['qubes-templates-itl', 'qubes-templates-itl-testing']
  324. enable = repolist[:idx]
  325. disable = repolist[idx:]
  326. self._manage_repos(enable, 'Enable')
  327. self._manage_repos(disable, 'Disable')
  328. # pylint: disable=invalid-name
  329. def _handle_comm_tmpl_updates_combobox(self, idx):
  330. # We don't increment idx by 1 because this is the only combobox that
  331. # has an explicit "disable this repository entirely" option
  332. repolist = ['qubes-templates-community',
  333. 'qubes-templates-community-testing']
  334. enable = repolist[:idx]
  335. disable = repolist[idx:]
  336. self._manage_repos(enable, 'Enable')
  337. self._manage_repos(disable, 'Disable')
  338. def __apply_repos__(self):
  339. self._handle_dom0_updates_combobox(
  340. self.dom0_updates_repo.currentIndex())
  341. self._handle_itl_tmpl_updates_combobox(
  342. self.itl_tmpl_updates_repo.currentIndex())
  343. self._handle_comm_tmpl_updates_combobox(
  344. self.comm_tmpl_updates_repo.currentIndex())
  345. def reject(self):
  346. self.done(0)
  347. def save_and_apply(self):
  348. self.__apply_system_defaults__()
  349. self.__apply_kernel_defaults__()
  350. self.__apply_mem_defaults__()
  351. self.__apply_updates__()
  352. self.__apply_repos__()
  353. def main():
  354. utils.run_synchronous(GlobalSettingsWindow)
  355. if __name__ == "__main__":
  356. main()