qvm-prefs 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601
  1. #!/usr/bin/python2
  2. # -*- encoding: utf8 -*-
  3. #
  4. # The Qubes OS Project, http://www.qubes-os.org
  5. #
  6. # Copyright (C) 2010 Joanna Rutkowska <joanna@invisiblethingslab.com>
  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 General Public License
  19. # along with this program; if not, write to the Free Software
  20. # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
  21. #
  22. #
  23. from qubes.qubes import QubesVmCollection
  24. from qubes.qubes import QubesVmLabels
  25. from qubes.qubes import QubesHost
  26. from qubes.qubes import system_path
  27. from optparse import OptionParser
  28. import subprocess
  29. import os
  30. import sys
  31. import re
  32. def do_list(vm):
  33. label_width = 19
  34. fmt="{{0:<{0}}}: {{1}}".format(label_width)
  35. print fmt.format ("name", vm.name)
  36. print fmt.format ("label", vm.label.name)
  37. print fmt.format ("type", vm.type)
  38. if vm.template is not None:
  39. print fmt.format ("template", vm.template.name)
  40. if vm.netvm is not None:
  41. print fmt.format ("netvm", vm.netvm.name)
  42. if vm.qid != 0:
  43. print fmt.format("dispvm_netvm", "%s%s" % (
  44. vm.dispvm_netvm.name if vm.dispvm_netvm
  45. else "none",
  46. " (default)" if vm.uses_default_dispvm_netvm else ""))
  47. print fmt.format ("updateable", vm.updateable)
  48. print fmt.format ("autostart", vm.autostart)
  49. print fmt.format ("installed_by_rpm", vm.installed_by_rpm)
  50. print fmt.format ("include_in_backups", vm.include_in_backups)
  51. print fmt.format ("last_backup", vm.backup_timestamp)
  52. print fmt.format ("dir", vm.dir_path)
  53. print fmt.format ("config", vm.conf_file)
  54. print fmt.format ("pcidevs", vm.pcidevs)
  55. print fmt.format ("pci_strictreset", vm.pci_strictreset)
  56. if vm.template is None:
  57. print fmt.format ("root_img", vm.root_img)
  58. if hasattr(vm, "rootcow_img") and vm.rootcow_img is not None:
  59. print fmt.format ("root_cow_img", vm.rootcow_img)
  60. if vm.template is not None:
  61. print fmt.format ("root_img", vm.template.root_img)
  62. if hasattr(vm, 'volatile_img') and vm.volatile_img is not None:
  63. print fmt.format ("root_volatile_img", vm.volatile_img)
  64. if hasattr(vm, 'private_img') and vm.private_img is not None:
  65. print fmt.format ("private_img", vm.private_img)
  66. print fmt.format ("vcpus", str(vm.vcpus))
  67. print fmt.format ("memory", vm.memory)
  68. if hasattr(vm, 'maxmem'):
  69. print fmt.format ("maxmem", vm.maxmem)
  70. print fmt.format ("MAC", "%s%s" % (vm.mac, " (auto)" if vm._mac is None else ""))
  71. if hasattr(vm, 'kernel'):
  72. if vm.uses_default_kernel:
  73. print fmt.format ("kernel", "%s (default)" % vm.kernel)
  74. else:
  75. print fmt.format ("kernel", vm.kernel)
  76. if hasattr(vm, 'kernelopts'):
  77. if vm.uses_default_kernelopts:
  78. print fmt.format ("kernelopts", "%s (default)" % vm.kernelopts)
  79. else:
  80. print fmt.format ("kernelopts", vm.kernelopts)
  81. if hasattr(vm, 'debug'):
  82. print fmt.format("debug", "on" if vm.debug else "off")
  83. if hasattr(vm, 'default_user'):
  84. print fmt.format("default_user", str(vm.default_user))
  85. if hasattr(vm, 'qrexec_installed'):
  86. print fmt.format("qrexec_installed", str(vm.qrexec_installed))
  87. if hasattr(vm, 'qrexec_timeout'):
  88. print fmt.format("qrexec_timeout", str(vm.qrexec_timeout))
  89. if hasattr(vm, 'guiagent_installed'):
  90. print fmt.format("guiagent_installed", str(vm.guiagent_installed))
  91. if hasattr(vm, 'seamless_gui_mode'):
  92. print fmt.format("seamless_gui_mode", str(vm.seamless_gui_mode))
  93. if hasattr(vm, 'drive'):
  94. print fmt.format("drive", str(vm.drive))
  95. if hasattr(vm, 'timezone'):
  96. print fmt.format("timezone", str(vm.timezone))
  97. print fmt.format ("internal", vm.internal)
  98. def do_get(vms, vm, prop):
  99. if prop == 'config':
  100. prop = 'conf_file'
  101. elif prop == 'dir':
  102. prop = 'dir_path'
  103. elif prop == 'last_backup':
  104. prop = 'backup_timestamp'
  105. if not hasattr(vm, prop):
  106. print >>sys.stderr, "VM '{}' has no attribute '{}'".format(vm.name,
  107. prop)
  108. return
  109. if getattr(vm, prop, None) is None:
  110. # not set or set to None
  111. return
  112. if prop in ['template', 'netvm', 'dispvm_netvm']:
  113. print getattr(vm, prop).name
  114. else:
  115. print str(getattr(vm, prop))
  116. def set_label(vms, vm, args):
  117. if len (args) != 1:
  118. print >> sys.stderr, "Missing label name argument!"
  119. return False
  120. label = args[0]
  121. if label not in QubesVmLabels:
  122. print >> sys.stderr, "Wrong label name, supported values are the following:"
  123. for l in QubesVmLabels.values():
  124. print >> sys.stderr, "* {0}".format(l.name)
  125. return False
  126. vm.label = QubesVmLabels[label]
  127. return True
  128. def set_memory(vms, vm, args):
  129. if len (args) != 1:
  130. print >> sys.stderr, "Missing memory argument!"
  131. return False
  132. new_memory = int(args[0])
  133. if new_memory <= 0:
  134. print >>sys.stderr, "Memory size must be positive"
  135. return False
  136. qubes_host = QubesHost()
  137. if new_memory > qubes_host.memory_total/1024:
  138. print >> sys.stderr, "This host has only {0} MB of RAM".format(qubes_host.memory_total/1024)
  139. return False
  140. vm.memory = new_memory
  141. return True
  142. def set_maxmem(vms, vm, args):
  143. if len (args) != 1:
  144. print >> sys.stderr, "Missing maxmem argument!"
  145. exit (1)
  146. new_maxmem = int(args[0])
  147. if new_maxmem <= 0:
  148. print >>sys.stderr, "Memory size must be positive"
  149. return False
  150. qubes_host = QubesHost()
  151. if new_maxmem > qubes_host.memory_total/1024:
  152. print >> sys.stderr, "This host has only {0} MB of RAM".format(qubes_host.memory_total/1024)
  153. return False
  154. if new_maxmem < vm.memory:
  155. print >> sys.stderr, "WARNING: new maxmem smaller than memory property - VM will be able to use only 'maxmem' memory amount"
  156. vm.maxmem = new_maxmem
  157. return True
  158. def set_mac(vms, vm, args):
  159. if len (args) != 1:
  160. print >> sys.stderr, "Missing MAC argument!"
  161. return False
  162. if not re.match("[0-9a-fA-F]{2}(:[0-9a-fA-F]{2}){5}|auto", args[0]):
  163. print >> sys.stderr, "Invalid MAC argument!"
  164. print >> sys.stderr, "Possible values:"
  165. print >> sys.stderr, "1) auto"
  166. print >> sys.stderr, "2) MAC in format: XX:XX:XX:XX:XX:XX"
  167. return False
  168. mac = args[0]
  169. if mac == "auto":
  170. mac = None
  171. vm.mac = mac
  172. return True
  173. def set_pcidevs(vms, vm, args):
  174. if len (args) != 1:
  175. print >> sys.stderr, "Missing pcidevs argument!"
  176. return False
  177. if vm.is_running():
  178. print >>sys.stderr, "Cannot modify PCI devices of running VM, " \
  179. "use qvm-pci instead"
  180. return False
  181. vm.pcidevs = list(eval(args[0]))
  182. return True
  183. def set_pci_strictreset(vms, vm, args):
  184. if len (args) != 1:
  185. print >> sys.stderr, "Missing value (True/False)!"
  186. return False
  187. vm.pci_strictreset = bool(eval(args[0].capitalize()))
  188. return True
  189. def set_netvm(vms, vm, args):
  190. if len (args) != 1:
  191. print >> sys.stderr, "Missing netvm name argument!"
  192. print >> sys.stderr, "Possible values:"
  193. print >> sys.stderr, "1) default"
  194. print >> sys.stderr, "2) none"
  195. print >> sys.stderr, "3) <vmaname>"
  196. return
  197. netvm = args[0]
  198. if netvm == "none":
  199. netvm = None
  200. vm.uses_default_netvm = False
  201. elif netvm == "default":
  202. netvm = vms.get_default_netvm()
  203. vm.uses_default_netvm = True
  204. else:
  205. netvm = vms.get_vm_by_name (netvm)
  206. if netvm is None:
  207. print >> sys.stderr, "A VM with the name '{0}' does not exist in the system.".format(netvm)
  208. return False
  209. if not netvm.is_netvm():
  210. print >> sys.stderr, "VM '{0}' is not a NetVM".format(netvm)
  211. return False
  212. vm.uses_default_netvm = False
  213. vm.netvm = netvm
  214. return True
  215. def set_dispvm_netvm(vms, vm, args):
  216. if len (args) != 1:
  217. print >> sys.stderr, "Missing netvm name argument!"
  218. print >> sys.stderr, "Possible values:"
  219. print >> sys.stderr, "1) default (the same as VM own netvm)"
  220. print >> sys.stderr, "2) none"
  221. print >> sys.stderr, "3) <vmaname>"
  222. return
  223. netvm = args[0]
  224. if netvm == "none":
  225. vm.netvm = None
  226. vm.uses_default_dispvm_netvm = False
  227. elif netvm == "default":
  228. vm.uses_default_dispvm_netvm = True
  229. else:
  230. netvm = vms.get_vm_by_name (netvm)
  231. if netvm is None:
  232. print >> sys.stderr, "A VM with the name '{0}' does not exist in the system.".format(netvm)
  233. return False
  234. if not netvm.is_netvm():
  235. print >> sys.stderr, "VM '{0}' is not a NetVM".format(netvm)
  236. return False
  237. vm.dispvm_netvm = netvm
  238. vm.uses_default_dispvm_netvm = False
  239. return True
  240. def set_kernel(vms, vm, args):
  241. if len (args) != 1:
  242. print >> sys.stderr, "Missing kernel version argument!"
  243. print >> sys.stderr, "Possible values:"
  244. print >> sys.stderr, "1) default"
  245. print >> sys.stderr, "2) none (kernels subdir in VM)"
  246. print >> sys.stderr, "3) <kernel version>, one of:"
  247. for k in os.listdir(system_path["qubes_kernels_base_dir"]):
  248. print >> sys.stderr, " -", k
  249. return False
  250. kernel = args[0]
  251. if kernel == "default":
  252. kernel = vms.get_default_kernel()
  253. vm.uses_default_kernel = True
  254. elif kernel == "none":
  255. kernel = None
  256. vm.uses_default_kernel = False
  257. else:
  258. if not os.path.exists(os.path.join(system_path["qubes_kernels_base_dir"], kernel)):
  259. print >> sys.stderr, "Kernel version {0} not installed.".format(kernel)
  260. return False
  261. vm.uses_default_kernel = False
  262. vm.kernel = kernel
  263. return True
  264. def set_template(vms, vm, args):
  265. if len (args) != 1:
  266. print >> sys.stderr, "Missing template name argument!"
  267. return False
  268. template_name = args[0];
  269. template = vms.get_vm_by_name(template_name)
  270. if template is None or template.qid not in vms:
  271. print >> sys.stderr, "A VM with the name '{0}' does not exist in the system.".format(template_name)
  272. return False
  273. if not template.is_template():
  274. print >> sys.stderr, "VM '{0}' is not a TemplateVM".format(template_name)
  275. return False
  276. print >> sys.stderr, "Setting template for VM '{0}' to '{1}'...".format (vm.name, template_name)
  277. vm.template = template
  278. return True
  279. def set_vcpus(vms, vm, args):
  280. if len (args) != 1:
  281. print >> sys.stderr, "Missing vcpus count argument!"
  282. return False
  283. vcpus = int(args[0])
  284. if vcpus <= 0:
  285. print >> sys.stderr, "A vcpus count must be positive."
  286. return False
  287. qubes_host = QubesHost()
  288. if vcpus > qubes_host.no_cpus:
  289. print >> sys.stderr, "This host has only {0} cpus".format(
  290. qubes_host.no_cpus)
  291. return False
  292. print >> sys.stderr, "Setting vcpus count for VM '{0}' to '{1}'...".format (vm.name, vcpus)
  293. vm.vcpus = vcpus
  294. return True
  295. def set_kernelopts(vms, vm, args):
  296. if len (args) != 1:
  297. print >> sys.stderr, "Missing kernel opts argument!"
  298. print >> sys.stderr, "Possible values:"
  299. print >> sys.stderr, "1) default"
  300. print >> sys.stderr, "2) <opts>"
  301. return False
  302. if args[0] == 'default':
  303. vm.uses_default_kernelopts = True
  304. else:
  305. vm.uses_default_kernelopts = False
  306. vm.kernelopts = args[0]
  307. return True
  308. def set_name(vms, vm, args):
  309. if len (args) != 1:
  310. print >> sys.stderr, "Missing new name!"
  311. return False
  312. if args[0] == vm.name:
  313. return False
  314. vm.set_name(args[0])
  315. return True
  316. def set_drive(vms, vm, args):
  317. if len (args) != 1:
  318. print >> sys.stderr, "Missing new drive content (file/device)!"
  319. return False
  320. if args[0] == '' or args[0].lower() == 'none':
  321. vm.drive = None
  322. else:
  323. vm.drive = args[0]
  324. return True
  325. def set_debug(vms, vm, args):
  326. if len (args) != 1:
  327. print >> sys.stderr, "Missing value (True/False or on/off)!"
  328. return False
  329. if args[0].lower() == "on":
  330. vm.debug = True
  331. elif args[0].lower() == "off":
  332. vm.debug = False
  333. else:
  334. vm.debug = bool(eval(args[0].capitalize()))
  335. return True
  336. def set_default_user(vms, vm, args):
  337. if len (args) != 1:
  338. print >> sys.stderr, "Missing user name!"
  339. return False
  340. vm.default_user = args[0]
  341. return True
  342. def set_include_in_backups(vms, vm, args):
  343. if len (args) != 1:
  344. print >> sys.stderr, "Missing value (True/False)!"
  345. return False
  346. vm.include_in_backups = bool(eval(args[0].capitalize()))
  347. return True
  348. def set_qrexec_installed(vms, vm, args):
  349. if len (args) != 1:
  350. print >> sys.stderr, "Missing value (True/False)!"
  351. return False
  352. vm.qrexec_installed = bool(eval(args[0].capitalize()))
  353. return True
  354. def set_internal(vms, vm, args):
  355. if len (args) != 1:
  356. print >> sys.stderr, "Missing value (True/False)!"
  357. return False
  358. vm.internal = bool(eval(args[0].capitalize()))
  359. return True
  360. def set_guiagent_installed(vms, vm, args):
  361. if len (args) != 1:
  362. print >> sys.stderr, "Missing value (True/False)!"
  363. return False
  364. vm.guiagent_installed = bool(eval(args[0].capitalize()))
  365. return True
  366. def set_seamless_gui_mode(vms, vm, args):
  367. if len(args) != 1:
  368. print >> sys.stderr, "Missing value (true/false)!"
  369. return False
  370. if not args[0].lower() in ['true', 'false']:
  371. print >> sys.stderr, "Invalid value, expected 'true' or 'false'"
  372. return False
  373. if args[0].lower() == 'true':
  374. vm.seamless_gui_mode = True
  375. else:
  376. vm.seamless_gui_mode = False
  377. return True
  378. def set_autostart(vms, vm, args):
  379. if len (args) != 1:
  380. print >> sys.stderr, "Missing value (True/False)!"
  381. return False
  382. vm.autostart = bool(eval(args[0].capitalize()))
  383. return True
  384. def set_qrexec_timeout(vms, vm, args):
  385. if len (args) != 1:
  386. print >> sys.stderr, "Missing timeout value (seconds)!"
  387. return False
  388. vm.qrexec_timeout = int(args[0])
  389. return True
  390. def set_timezone(vms, vm, args):
  391. if len (args) != 1:
  392. print >> sys.stderr, "Missing value ('localtime' or timeoffset in seconds)!"
  393. return False
  394. if not args[0].isdigit() and args[0].lower() == 'localtime':
  395. print >> sys.stderr, "Invalid timezone value!"
  396. return False
  397. vm.timezone = args[0]
  398. return True
  399. properties = {
  400. "include_in_backups": set_include_in_backups,
  401. "pcidevs": set_pcidevs,
  402. "pci_strictreset": set_pci_strictreset,
  403. "label" : set_label,
  404. "netvm" : set_netvm,
  405. "dispvm_netvm" : set_dispvm_netvm,
  406. "maxmem" : set_maxmem,
  407. "memory" : set_memory,
  408. "kernel" : set_kernel,
  409. "template" : set_template,
  410. "vcpus" : set_vcpus,
  411. "kernelopts": set_kernelopts,
  412. "name": set_name,
  413. "drive": set_drive,
  414. "mac": set_mac,
  415. "debug": set_debug,
  416. "default_user": set_default_user,
  417. "qrexec_installed": set_qrexec_installed,
  418. "guiagent_installed": set_guiagent_installed,
  419. "seamless_gui_mode": set_seamless_gui_mode,
  420. "qrexec_timeout": set_qrexec_timeout,
  421. "timezone": set_timezone,
  422. "internal": set_internal,
  423. "autostart": set_autostart,
  424. }
  425. def do_set(vms, vm, property, args):
  426. if property not in properties.keys():
  427. print >> sys.stderr, "ERROR: Wrong property name: '{0}'".format(property)
  428. return False
  429. if not hasattr(vm, property):
  430. print >> sys.stderr, "ERROR: Property '{0}' not available for this VM".format(property)
  431. return False
  432. try:
  433. return properties[property](vms, vm, args)
  434. except Exception as err:
  435. print >> sys.stderr, "ERROR: %s" % str(err)
  436. return False
  437. def main():
  438. usage = "usage: %prog -l [options] <vm-name>\n"\
  439. "usage: %prog -g [options] <vm-name> <property>\n"\
  440. "usage: %prog -s [options] <vm-name> <property> [...]\n"\
  441. "List/set various per-VM properties."
  442. parser = OptionParser (usage)
  443. parser.add_option("-l", "--list", action="store_true", dest="do_list",
  444. default=False)
  445. parser.add_option("-s", "--set", action="store_true", dest="do_set",
  446. default=False)
  447. parser.add_option ("-g", "--gry", action="store_true", dest="do_get",
  448. default=False)
  449. parser.add_option("--force-root", action="store_true", dest="force_root",
  450. default=False,
  451. help="Force to run, even with root privileges")
  452. (options, args) = parser.parse_args ()
  453. if (len (args) < 1):
  454. parser.error ("You must provide at least the vmname!")
  455. vmname = args[0]
  456. if hasattr(os, "geteuid") and os.geteuid() == 0:
  457. if not options.force_root:
  458. print >> sys.stderr, "*** Running this tool as root is strongly discouraged, this will lead you in permissions problems."
  459. print >> sys.stderr, "Retry as unprivileged user."
  460. print >> sys.stderr, "... or use --force-root to continue anyway."
  461. exit(1)
  462. if options.do_list + options.do_set + options.do_get > 1:
  463. print >> sys.stderr, "You can provide at most one of -l, -g and -s at " \
  464. "the same time!"
  465. exit(1)
  466. if options.do_set:
  467. qvm_collection = QubesVmCollection()
  468. qvm_collection.lock_db_for_writing()
  469. qvm_collection.load()
  470. else:
  471. qvm_collection = QubesVmCollection()
  472. qvm_collection.lock_db_for_reading()
  473. qvm_collection.load()
  474. qvm_collection.unlock_db()
  475. vm = qvm_collection.get_vm_by_name(vmname)
  476. if vm is None or vm.qid not in qvm_collection:
  477. print >> sys.stderr, "A VM with the name '{0}' does not exist in the system.".format(vmname)
  478. exit(1)
  479. if options.do_set:
  480. if len (args) < 2:
  481. print >> sys.stderr, "You must specify the property you wish to set..."
  482. print >> sys.stderr, "Available properties:"
  483. for p in properties.keys():
  484. if hasattr(vm, p):
  485. print >> sys.stderr, "--> '{0}'".format(p)
  486. exit (1)
  487. property = args[1]
  488. if do_set(qvm_collection, vm, property, args[2:]):
  489. qvm_collection.save()
  490. qvm_collection.unlock_db()
  491. else:
  492. qvm_collection.unlock_db()
  493. exit(1)
  494. elif options.do_get or len(args) == 2:
  495. do_get(qvm_collection, vm, args[1])
  496. else:
  497. # do_list
  498. do_list(vm)
  499. main()