Kaynağa Gözat

qubes/tools: qvm-start rewritten from original

Wojtek Porczyk 8 yıl önce
ebeveyn
işleme
b0be1ad584
5 değiştirilmiş dosya ile 210 ekleme ve 139 silme
  1. 55 17
      doc/manpages/qvm-start.rst
  2. 1 0
      qubes/Makefile
  3. 149 0
      qubes/tools/qvm_start.py
  4. 4 122
      qvm-tools/qvm-start
  5. 1 0
      rpm_spec/core-dom0.spec

+ 55 - 17
doc/manpages/qvm-start.rst

@@ -1,42 +1,80 @@
 .. program:: qvm-start
 
-============================================
-:program:`qvm-start` -- Start a specified VM
-============================================
+:program:`qvm-start` -- start a domain
+======================================
+
+.. warning::
+
+   This page was autogenerated from command-line parser. It shouldn't be 1:1
+   conversion, because it would add little value. Please revise it and add
+   more descriptive help, which normally won't fit in standard ``--help``
+   option.
+
+   After rewrite, please remove this admonition.
 
 Synopsis
-========
-:command:`qvm-start` [*options*] <*vm-name*>
+--------
+
+:command:`qvm-start` skel-manpage.py [-h] [--verbose] [--quiet] [--drive *DRIVE* | --hddisk *IMAGE* | --cdrom *IMAGE* | --install-windows-tools] [--conf-file *FILE*] [--debug] [--preparing-dvm] [--no-start-guid] *VMNAME*
 
 Options
-=======
+-------
 
 .. option:: --help, -h
 
-    Show this help message and exit
+   Show help message and exit.
+
+.. option:: --xml=XMLFILE
+
+   Use another qubes.xml file.
+
+.. option:: --verbose, -v
+
+   Increase verbosity.
 
 .. option:: --quiet, -q
 
-    Be quiet
+   Decrease verbosity.
+
+.. option:: --drive=DRIVE
 
-.. option:: --no-guid
+   Temporarily attach specified drive as CD/DVD or hard disk, which can be
+   specified with prefix "hd:" or "cdrom:". If not specified, default is cdrom.
 
-    Do not start the GUId (ignored)
+.. option:: --hddisk=IMAGE
 
-.. option:: --console
+   Temporarily attach specified drive as hard disk.
 
-    Attach debugging console to the newly started VM
+.. option:: --cdrom=IMAGE
 
-.. option:: --dvm
+   Temporarily attach specified drive as optical drive.
 
-    Do actions necessary when preparing DVM image
+.. option:: --install-windows-tools
 
-.. option:: --custom-config=CUSTOM_CONFIG
+   Temporarily ttach Windows tools CDROM to the domain.
 
-    Use custom Xen config instead of Qubes-generated one
+.. option:: --conf-file=FILE
+
+   Use custom libvirt config instead of Qubes-generated one.
+
+.. option:: --debug
+
+   Enable debug mode for this domain (until its shutdown).
+
+.. option:: --preparing-dvm
+
+   Do actions necessary when preparing DVM image.
+
+.. option:: --no-start-guid
+
+   Do not start GUI daemon.
 
 Authors
-=======
+-------
+
 | Joanna Rutkowska <joanna at invisiblethingslab dot com>
 | Rafal Wojtczuk <rafal at invisiblethingslab dot com>
 | Marek Marczykowski <marmarek at invisiblethingslab dot com>
+| Wojtek Porczyk <woju at invisiblethingslab dot com>
+
+.. vim: ts=3 sw=3 et tw=80

+ 1 - 0
qubes/Makefile

@@ -57,6 +57,7 @@ endif
 		tools/qvm_create.py* \
 		tools/qvm_ls.py* \
 		tools/qvm_prefs.py* \
+		tools/qvm_start.py* \
 		$(DESTDIR)$(PYTHON_QUBESPATH)/tools
 
 	cp ext/__init__.py* $(DESTDIR)$(PYTHON_QUBESPATH)/ext

+ 149 - 0
qubes/tools/qvm_start.py

@@ -0,0 +1,149 @@
+#!/usr/bin/python2 -O
+# vim: fileencoding=utf-8
+
+#
+# The Qubes OS Project, https://www.qubes-os.org/
+#
+# Copyright (C) 2010-2015  Joanna Rutkowska <joanna@invisiblethingslab.com>
+# Copyright (C) 2015       Wojtek Porczyk <woju@invisiblethingslab.com>
+#
+# This program is free software; you can redistribute it and/or modify
+# it under the terms of the GNU General Public License as published by
+# the Free Software Foundation; either version 2 of the License, or
+# (at your option) any later version.
+#
+# This program is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+# GNU General Public License for more details.
+#
+# You should have received a copy of the GNU General Public License along
+# with this program; if not, write to the Free Software Foundation, Inc.,
+# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
+#
+
+'''qvm-start - Start a domain'''
+
+# TODO notification in tray
+
+import argparse
+import qubes
+
+class DriveAction(argparse.Action):
+    '''Action for argument parser that stores drive image path.'''
+    # pylint: disable=redefined-builtin
+    def __init__(self,
+            option_strings,
+            dest='drive',
+            prefix='cdrom:',
+            metavar='IMAGE',
+            required=False,
+            help='Attach drive'):
+        super(DriveAction, self).__init__(option_strings, dest,
+            metavar=metavar, help=help)
+        self.prefix = prefix
+
+    def __call__(self, parser, namespace, values, option_string=None):
+        setattr(namespace, self.dest, prefix + value)
+
+
+parser = qubes.tools.get_parser_base(description='start a domain')
+
+
+parser_drive = parser.add_mutually_exclusive_group()
+
+parser_drive.add_argument('--drive', metavar='DRIVE',
+    help='temporarily attach specified drive as CD/DVD or hard disk (can be'
+        ' specified with prefix "hd:" or "cdrom:", default is cdrom)')
+
+parser_drive.add_argument('--hddisk',
+    action=DriveAction, prefix='hd:',
+    help='temporarily attach specified drive as hard disk')
+
+parser_drive.add_argument('--cdrom', metavar='IMAGE',
+    action=DriveAction, prefix='cdrom:',
+    help='temporarily attach specified drive as CD/DVD')
+
+parser_drive.add_argument('--install-windows-tools',
+    action='store_const', dest='drive', default=False,
+    const='cdrom:dom0:/usr/lib/qubes/qubes-windows-tools.iso',
+    help='temporarily ttach Windows tools CDROM to the domain')
+
+
+parser.add_argument('--conf-file', metavar='FILE',
+    help='use custom libvirt config instead of Qubes-generated one')
+
+parser.add_argument('--debug',
+    action='store_true', default=False,
+    help='enable debug mode for this domain (until its shutdown)')
+
+parser.add_argument('--preparing-dvm',
+    action='store_true', default=False,
+    help='do actions necessary when preparing DVM image')
+
+parser.add_argument('--no-start-guid',
+    action='store_false', dest='start_guid', default=True,
+    help='do actions necessary when preparing DVM image')
+
+#parser.add_option ("--no-guid", action="store_true", dest="noguid", default=False,
+#            help="Do not start the GUId (ignored)")
+#parser.add_option ("--tray", action="store_true", dest="tray", default=False,
+#                   help="Use tray notifications instead of stdout" )
+
+parser.add_argument('name', metavar='VMNAME',
+    help='domain to start')
+
+parser.set_defaults(drive=None)
+
+def main(args=None):
+    '''Main routine of :program:`qvm-start`.
+
+    :param list args: Optional arguments to override those delivered from \
+        command line.
+    '''
+
+    args = parser.parse_args(args)
+    qubes.tools.set_verbosity(parser, args)
+    app = qubes.Qubes(args.xml)
+
+#   if options.tray:
+#       tray_notify_init()
+
+    try:
+        vm = app.domains[args.name]
+    except KeyError:
+        parser.error('no such domain: {!r}'.format(args.name))
+
+    if args.drive is not None:
+        if 'drive' not in (prop.__name__ for prop in vm.property_list()):
+            parser.error(
+                'domain {!r} does not support attaching drives'.format(vm.name))
+
+    if args.conf_file is not None:
+        vm.conf_file = args.conf_file
+
+    if args.debug:
+        vm.debug = args.debug
+
+    try:
+        vm.verify_files()
+    except (IOError, OSError) as e:
+        parser.error(
+            'error verifying files for domain {!r}: {!r}'.format(vm.name, e))
+
+    try:
+        xid = vm.start(
+            preparing_dvm=args.preparing_dvm,
+            start_guid=args.start_guid)
+            # notify_function=
+    except MemoryError:
+        # TODO tray
+        parser.error('not enough memory to start domain {!r}'.format(vm.name))
+    except qubes.QubesException as e:
+        parser.error('Qubes error: {!r}'.format(e))
+
+    return True
+
+
+if __name__ == '__main__':
+    sys.exit(not main())

+ 4 - 122
qvm-tools/qvm-start

@@ -1,125 +1,7 @@
-#!/usr/bin/python2
-# -*- coding: utf-8 -*-
-#
-# The Qubes OS Project, http://www.qubes-os.org
-#
-# Copyright (C) 2010  Joanna Rutkowska <joanna@invisiblethingslab.com>
-#
-# This program is free software; you can redistribute it and/or
-# modify it under the terms of the GNU General Public License
-# as published by the Free Software Foundation; either version 2
-# of the License, or (at your option) any later version.
-#
-# This program is distributed in the hope that it will be useful,
-# but WITHOUT ANY WARRANTY; without even the implied warranty of
-# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
-# GNU General Public License for more details.
-#
-# You should have received a copy of the GNU General Public License
-# along with this program; if not, write to the Free Software
-# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
-#
-#
+#!/usr/bin/python2 -O
+# vim: fileencoding=utf-8
 
-from qubes.qubes import QubesVmCollection
-from qubes.qubes import QubesException
-from optparse import OptionParser
-from qubes.notify import tray_notify,tray_notify_error,tray_notify_init
-import subprocess
-import os
 import sys
+import qubes.tools.qvm_start
 
-notify_object = None
-
-def tray_notify_generic(level, str):
-    if level == "info":
-        tray_notify(str, label=vm.label)
-    elif level == "error":
-        tray_notify_error(str)
-
-def main():
-    usage = "usage: %prog [options] <vm-name>"
-    parser = OptionParser (usage)
-    parser.add_option ("-q", "--quiet", action="store_false", dest="verbose", default=True)
-    parser.add_option ("--tray", action="store_true", dest="tray", default=False,
-                       help="Use tray notifications instead of stdout" )
-    parser.add_option ("--no-guid", action="store_true", dest="noguid", default=False,
-		      help="Do not start the GUId (ignored)")
-    parser.add_option ("--drive", dest="drive", default=None,
-                      help="Temporarily attach specified drive as CD/DVD or hard disk (can be specified with prefix 'hd:' or 'cdrom:', default is cdrom)")
-    parser.add_option ("--hddisk", dest="drive_hd", default=None,
-                      help="Temporarily attach specified drive as hard disk")
-    parser.add_option ("--cdrom", dest="drive_cdrom", default=None,
-                      help="Temporarily attach specified drive as CD/DVD")
-    parser.add_option ("--install-windows-tools", action="store_true", dest="install_windows_tools", default=False,
-                      help="Attach Windows tools CDROM to the VM")
-    parser.add_option ("--dvm", action="store_true", dest="preparing_dvm", default=False,
-                      help="Do actions necessary when preparing DVM image")
-    parser.add_option ("--custom-config", action="store", dest="custom_config", default=None,
-                      help="Use custom Xen config instead of Qubes-generated one")
-    parser.add_option ("--debug", action="store_true", dest="debug", default=False,
-                      help="Enable debug mode for this VM (until its shutdown)")
-
-    (options, args) = parser.parse_args ()
-    if (len (args) != 1):
-        parser.error ("You must specify VM name!")
-    vmname = args[0]
-
-    if options.tray:
-        tray_notify_init()
-
-    qvm_collection = QubesVmCollection()
-    qvm_collection.lock_db_for_reading()
-    qvm_collection.load()
-    qvm_collection.unlock_db()
-
-    vm = qvm_collection.get_vm_by_name(vmname)
-    if vm is None:
-        print >> sys.stderr, "A VM with the name '{0}' does not exist in the system.".format(vmname)
-        exit(1)
-
-    if bool(options.drive_hd) + bool(options.drive_cdrom) + bool(options.drive) + bool(options.install_windows_tools) > 1:
-        print >> sys.stderr, "Only one of --drive, --cdrom, --hddisk, --install-windows-tools can be specified"
-        exit(1)
-
-    if options.install_windows_tools:
-        options.drive = 'cdrom:dom0:/usr/lib/qubes/qubes-windows-tools.iso'
-
-    if options.drive_hd:
-        options.drive = 'hd:' + options.drive_hd
-
-    if options.drive_cdrom:
-        options.drive = 'cdrom:' + options.drive_cdrom
-
-    if options.drive:
-        if hasattr(vm, 'drive'):
-            vm.drive = options.drive
-        else:
-            print >> sys.stderr, "This VM does not support attaching drives"
-            exit (1)
-
-    if options.custom_config:
-        vm.conf_file = options.custom_config
-
-    if options.debug:
-        vm.debug = True
-
-    try:
-        vm.verify_files()
-        xid = vm.start(verbose=options.verbose, preparing_dvm=options.preparing_dvm, start_guid=not options.noguid, notify_function=tray_notify_generic if options.tray else None)
-    except (IOError, OSError, QubesException, MemoryError) as err:
-        if options.tray:
-            tray_notify_error(str(err))
-        else:
-            print >> sys.stderr, "ERROR: {0}".format(err)
-        exit (1)
-
-    if options.debug:
-        print >> sys.stderr, "--> Debug mode enabled. Useful logs: "
-        print >> sys.stderr, "    /var/log/xen/console/guest-%s.log" % vmname
-        if vm.type.endswith("HVM"):
-            print >> sys.stderr, "    /var/log/xen/console/guest-%s-dm.log" % vmname
-        print >> sys.stderr, "    /var/log/qubes/guid.%s.log" % vmname
-        print >> sys.stderr, "    /var/log/qubes/qrexec.%s.log" % vmname
-
-main()
+sys.exit(not qubes.tools.qvm_start.main())

+ 1 - 0
rpm_spec/core-dom0.spec

@@ -220,6 +220,7 @@ fi
 %{python_sitearch}/qubes/tools/qvm_create.py*
 %{python_sitearch}/qubes/tools/qvm_ls.py*
 %{python_sitearch}/qubes/tools/qvm_prefs.py*
+%{python_sitearch}/qubes/tools/qvm_start.py*
 
 %dir %{python_sitearch}/qubes/ext
 %{python_sitearch}/qubes/ext/__init__.py*