bin/kvm-admin
author Jens Kasten <jens@kasten-edv.de>
Sun, 08 Apr 2012 00:24:35 +0200
changeset 113 d180b27d13a9
parent 112 0ca5084026ff
child 115 75c299d0bf5a
permissions -rwxr-xr-x
add 'status all --full' options, update README
#!/usr/bin/python2.7
#
# Comamandline tool to manage a qemu-kvm domain.
#
# Usage: kvm-admin guest_name action [arguments]
#
# Depencies:
#           python-argparse
#
# 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., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
#

"""
(c) 2007-2012 Jens Kasten <jens@kasten-edv.de> 
"""

import os
import sys
# for backward compality use the shipped argparse 
# if python version does not support it
try:
    import argparse
except ImportError:
    import kvmtools.argparse as argparse
import gettext

from kvmtools.kvm.action import Action

# TODO: have to create translation stuff
LOCALEAPP = sys.argv[0]
TRANSLATE = gettext.translation(LOCALEAPP, "/usr/share/locale", fallback=True)
_ = TRANSLATE.ugettext


class KvmAdmin(Action):
    """ Class for commandline usage for a qemu-kvm domain.
    Its offers methods for to start and stop the domain.
    A special method is the commandline monitor.
    In default configuration its create a socketfile for each domain and
    is it can use like the standard monitor.
    """

    def __init__(self):
        # load the methods which are available for doamin
        Action.__init__(self)
        self.value = None

    def run(self):
        """Do an action for a domain.
        Call a method based on commandline option.
        """
        kvm_method = "".join(["kvm_", self.action, "_action"])
        self.monitor_open()
        if "monitor" in self.action or "migrate" in self.action:
            # build string from third option till end
            cmd_monitor = " ".join(str(i) for i in self.monitor)
            getattr(self, kvm_method)(cmd_monitor)
        else:
            getattr(self, kvm_method)()
        self.monitor_close()

    def show_error(self):
        """Display errors if the registered."""
        errors = self.kvm_errors
        if len(errors) > 0:
            for error in errors:
                print error
            return True

    def _set(self, value):
        self.value = value

    def _get(self):
        return self.value


def main():
    """Handle the commandline arguments."""
    kvm_admin = KvmAdmin()
    actions = kvm_admin.available_actions()
    domains = kvm_admin.available_domains()

    # manage the commandline arguments
    parser = argparse.ArgumentParser()
    parser.add_argument("--debug", default=False, action="store_true",
        help="Print full python traceback.")
    
    # add action as subparser
    subparser = parser.add_subparsers(title="All commands for kvm-admin",
        description="valid kvm-admin commands",
        help="additional help")
    for i in actions:
        my_help = getattr(kvm_admin, "kvm_%s_action" % i).__doc__
        action = subparser.add_parser(i)
        action.add_argument(i, action="store", metavar=("domain"), 
            help=my_help)
        if i == "status":
            action.add_argument("--full", default=False, action="store_true", 
                #metavar=("full status information"),
                help=_("Display full status information for each running qemu-kvm domain."))
        if i == "monitor":               
            action.add_argument("args_monitor", nargs="*", default=[],
                #metavar=("monitor argument"),
                help=_("One ore more arguments to pass to the qemu-kvm monitor."))
    
    args = parser.parse_args()
    
    kvm_admin.debug = args.debug

    # assign the action and domain name dynamically
    for action in actions:
        if action in args: 
            kvm_admin.action = action
            kvm_admin.kvm_domain_name = str(getattr(args, action))
            break

    # assign the optional monitor arguments 
    if "args_monitor" in args and len(args.args_monitor) > 0:
        kvm_admin.monitor = args.args_monitor        
    else:
        # set default monitor to help
        kvm_admin.monitor =["help"] 

    # assign all as domain name its used for status
    if kvm_admin.kvm_domain_name == "all" and kvm_admin.action == "status":
        # append "all" as pseudo domain name
        domains.append("all")
        kvm_admin.kvm_status_full = args.full

    # check if the domain name has a config file and is not create
    if not kvm_admin.kvm_domain_name in domains and not "create" == kvm_admin.action:  
        parser.error(_("Available domains\n%s") % domains)


    # check if some error occurs
    if not kvm_admin.action == "modify" and kvm_admin.show_error():
        sys.exit(1)
    
    # run it
    if args.debug:
        kvm_admin.run()
    else:
        try:
            kvm_admin.run()
        except Exception, error_msg:
            print error_msg
            sys.exit(1)
            
        
if __name__ == "__main__":
    try:
        main()
    except KeyboardInterrupt:
        print _("\rUser break.")
        sys.exit(1)