ia64/xen-unstable

changeset 13037:c91f6506b270

Added xm shell command, taken from xapi.py, to make testing the Xen-API calls
a little easier.

Signed-off-by: Ewan Mellor <ewan@xensource.com>
author Ewan Mellor <ewan@xensource.com>
date Thu Dec 14 14:54:24 2006 +0000 (2006-12-14)
parents de7d7b223db2
children d0f682ada0b2
files tools/python/xen/xm/XenAPI.py tools/python/xen/xm/main.py
line diff
     1.1 --- a/tools/python/xen/xm/XenAPI.py	Thu Dec 14 14:50:35 2006 +0000
     1.2 +++ b/tools/python/xen/xm/XenAPI.py	Thu Dec 14 14:54:24 2006 +0000
     1.3 @@ -82,7 +82,7 @@ class Session(xen.util.xmlrpclib2.Server
     1.4          self._session = None
     1.5  
     1.6  
     1.7 -    def _xen_request(self, methodname, params):
     1.8 +    def xenapi_request(self, methodname, params):
     1.9          full_params = (self._session,) + params
    1.10          return _parse_result(getattr(self, methodname)(*full_params))
    1.11  
    1.12 @@ -94,7 +94,7 @@ class Session(xen.util.xmlrpclib2.Server
    1.13  
    1.14      def __getattr__(self, name):
    1.15          if name == 'xenapi':
    1.16 -            return _Dispatcher(self._xen_request, None)
    1.17 +            return _Dispatcher(self.xenapi_request, None)
    1.18          elif name.startswith('login'):
    1.19              return lambda u, p: self._login(name, u, p)
    1.20          else:
     2.1 --- a/tools/python/xen/xm/main.py	Thu Dec 14 14:50:35 2006 +0000
     2.2 +++ b/tools/python/xen/xm/main.py	Thu Dec 14 14:54:24 2006 +0000
     2.3 @@ -22,7 +22,10 @@
     2.4  """Grand unified management application for Xen.
     2.5  """
     2.6  import atexit
     2.7 +import cmd
     2.8  import os
     2.9 +import pprint
    2.10 +import shlex
    2.11  import sys
    2.12  import re
    2.13  import getopt
    2.14 @@ -77,6 +80,8 @@ USAGE_FOOTER = '<Domain> can either be t
    2.15  
    2.16  SUBCOMMAND_HELP = {
    2.17      # common commands
    2.18 +
    2.19 +    'shell'       : ('', 'Launch an interactive shell.'),
    2.20      
    2.21      'console'     : ('[-q|--quiet] <Domain>',
    2.22                       'Attach to <Domain>\'s console.'),
    2.23 @@ -245,6 +250,7 @@ common_commands = [
    2.24      "restore",
    2.25      "resume",
    2.26      "save",
    2.27 +    "shell",
    2.28      "shutdown",
    2.29      "start",
    2.30      "suspend",
    2.31 @@ -328,7 +334,7 @@ acm_commands = [
    2.32      ]
    2.33  
    2.34  all_commands = (domain_commands + host_commands + scheduler_commands +
    2.35 -                device_commands + vnet_commands + acm_commands)
    2.36 +                device_commands + vnet_commands + acm_commands + ['shell'])
    2.37  
    2.38  
    2.39  ##
    2.40 @@ -362,6 +368,7 @@ def parseAuthentication():
    2.41              server.getAttribute('password'))
    2.42  
    2.43  serverType, serverURI = parseServer()
    2.44 +server = None
    2.45  
    2.46  
    2.47  ####################################################################
    2.48 @@ -455,12 +462,16 @@ def longHelp():
    2.49      print
    2.50      print USAGE_FOOTER        
    2.51  
    2.52 -def usage(cmd = None):
    2.53 -    """ Print help usage information and exits """
    2.54 +def _usage(cmd):
    2.55 +    """ Print help usage information """
    2.56      if cmd:
    2.57          cmdHelp(cmd)
    2.58      else:
    2.59          shortHelp()
    2.60 +
    2.61 +def usage(cmd = None):
    2.62 +    """ Print help usage information and exits """
    2.63 +    _usage(cmd)
    2.64      sys.exit(1)
    2.65  
    2.66  
    2.67 @@ -523,6 +534,49 @@ def get_single_vm(dom):
    2.68          dominfo = server.xend.domain(dom, False)
    2.69          return dominfo['uuid']
    2.70  
    2.71 +##
    2.72 +#
    2.73 +# Xen-API Shell
    2.74 +#
    2.75 +##
    2.76 +
    2.77 +class Shell(cmd.Cmd):
    2.78 +    def __init__(self):
    2.79 +        cmd.Cmd.__init__(self)
    2.80 +        self.prompt = "xm> "
    2.81 +
    2.82 +    def default(self, line):
    2.83 +        words = shlex.split(line)
    2.84 +        if len(words) > 0 and words[0] == 'xm':
    2.85 +            words = words[1:]
    2.86 +        if len(words) > 0:
    2.87 +            cmd = xm_lookup_cmd(words[0])
    2.88 +            if cmd:
    2.89 +                _run_cmd(cmd, words[0], words[1:])
    2.90 +            elif serverType == SERVER_XEN_API:
    2.91 +                ok, res = _run_cmd(lambda x: server.xenapi_request(words[0],
    2.92 +                                                                   tuple(x)),
    2.93 +                                   words[0], words[1:])
    2.94 +                if ok and res != '':
    2.95 +                    pprint.pprint(res)
    2.96 +            else:
    2.97 +                print '*** Unknown command: %s' % words[0]
    2.98 +        return False
    2.99 +
   2.100 +    def emptyline(self):
   2.101 +        pass
   2.102 +
   2.103 +    def do_EOF(self, line):
   2.104 +        print
   2.105 +        sys.exit(0)
   2.106 +
   2.107 +    def do_help(self, line):
   2.108 +        _usage(line)
   2.109 +
   2.110 +
   2.111 +def xm_shell(args):
   2.112 +    Shell().cmdloop('The Xen Master. Type "help" for a list of functions.')
   2.113 +
   2.114  
   2.115  #########################################################################
   2.116  #
   2.117 @@ -1560,6 +1614,7 @@ def xm_vnet_delete(args):
   2.118      server.xend_vnet_delete(vnet)
   2.119  
   2.120  commands = {
   2.121 +    "shell": xm_shell,
   2.122      # console commands
   2.123      "console": xm_console,
   2.124      # xenstat commands
   2.125 @@ -1663,17 +1718,13 @@ def xm_lookup_cmd(cmd):
   2.126              # only execute if there is only 1 match
   2.127              if len(same_prefix_cmds) == 1:
   2.128                  return same_prefix_cmds[0]
   2.129 -            
   2.130 -        err('Sub Command %s not found!' % cmd)
   2.131 -        usage()
   2.132 +        return None
   2.133  
   2.134  def deprecated(old,new):
   2.135      print >>sys.stderr, (
   2.136          "Command %s is deprecated.  Please use xm %s instead." % (old, new))
   2.137  
   2.138  def main(argv=sys.argv):
   2.139 -    global server
   2.140 -
   2.141      if len(argv) < 2:
   2.142          usage()
   2.143  
   2.144 @@ -1682,16 +1733,26 @@ def main(argv=sys.argv):
   2.145          if help in argv[1:]:
   2.146              if help == argv[1]:
   2.147                  longHelp()
   2.148 +                sys.exit(0)
   2.149              else:
   2.150                  usage(argv[1])
   2.151 -            sys.exit(0)
   2.152 -
   2.153 -    cmd = xm_lookup_cmd(argv[1])
   2.154  
   2.155 -    # strip off prog name and subcmd
   2.156 -    args = argv[2:]
   2.157 +    cmd_name = argv[1]
   2.158 +    cmd = xm_lookup_cmd(cmd_name)
   2.159      if cmd:
   2.160 -        try:
   2.161 +        # strip off prog name and subcmd
   2.162 +        args = argv[2:]
   2.163 +        _, rc = _run_cmd(cmd, cmd_name, args)
   2.164 +        if rc:
   2.165 +            usage(cmd_name)
   2.166 +    else:
   2.167 +        usage()
   2.168 +
   2.169 +def _run_cmd(cmd, cmd_name, args):
   2.170 +    global server
   2.171 +
   2.172 +    try:
   2.173 +        if server is None:
   2.174              if serverType == SERVER_XEN_API:
   2.175                  server = XenAPI.Session(serverURI)
   2.176                  username, password = parseAuthentication()
   2.177 @@ -1705,66 +1766,55 @@ def main(argv=sys.argv):
   2.178              else:
   2.179                  server = ServerProxy(serverURI)
   2.180  
   2.181 -            rc = cmd(args)
   2.182 -            if rc:
   2.183 -                usage()
   2.184 -        except socket.error, ex:
   2.185 -            if os.geteuid() != 0:
   2.186 -                err("Most commands need root access. Please try again as root.")
   2.187 -            else:
   2.188 -                err("Unable to connect to xend: %s. Is xend running?" % ex[1])
   2.189 -            sys.exit(1)
   2.190 -        except KeyboardInterrupt:
   2.191 -            print "Interrupted."
   2.192 -            sys.exit(1)
   2.193 -        except IOError, ex:
   2.194 -            if os.geteuid() != 0:
   2.195 -                err("Most commands need root access.  Please try again as root.")
   2.196 -            else:
   2.197 -                err("Unable to connect to xend: %s." % ex[1])
   2.198 -            sys.exit(1)
   2.199 -        except SystemExit:
   2.200 -            sys.exit(1)
   2.201 -        except XenAPI.Failure, exn:
   2.202 -            err(str(exn))
   2.203 -            sys.exit(1)
   2.204 -        except xmlrpclib.Fault, ex:
   2.205 -            if ex.faultCode == XendClient.ERROR_INVALID_DOMAIN:
   2.206 -                err("Domain '%s' does not exist." % ex.faultString)
   2.207 -            else:
   2.208 -                err(ex.faultString)
   2.209 -            usage(argv[1])
   2.210 -            sys.exit(1)
   2.211 -        except xmlrpclib.ProtocolError, ex:
   2.212 -            if ex.errcode == -1:
   2.213 -                print  >>sys.stderr, (
   2.214 -                    "Xend has probably crashed!  Invalid or missing HTTP "
   2.215 -                    "status code.")
   2.216 -            else:
   2.217 -                print  >>sys.stderr, (
   2.218 -                    "Xend has probably crashed!  ProtocolError(%d, %s)." %
   2.219 -                    (ex.errcode, ex.errmsg))
   2.220 -            sys.exit(1)
   2.221 -        except (ValueError, OverflowError):
   2.222 -            err("Invalid argument.")
   2.223 -            usage(argv[1])
   2.224 -            sys.exit(1)
   2.225 -        except OptionError, e:
   2.226 -            err(str(e))
   2.227 -            usage(argv[1])
   2.228 -            print e.usage()
   2.229 -            sys.exit(1)
   2.230 -        except security.ACMError, e:
   2.231 -            err(str(e))
   2.232 -            sys.exit(1)
   2.233 -        except:
   2.234 -            print "Unexpected error:", sys.exc_info()[0]
   2.235 -            print
   2.236 -            print "Please report to xen-devel@lists.xensource.com"
   2.237 -            raise
   2.238 -                
   2.239 -    else:
   2.240 -        usage()
   2.241 +        return True, cmd(args)
   2.242 +    except socket.error, ex:
   2.243 +        if os.geteuid() != 0:
   2.244 +            err("Most commands need root access. Please try again as root.")
   2.245 +        else:
   2.246 +            err("Unable to connect to xend: %s. Is xend running?" % ex[1])
   2.247 +    except KeyboardInterrupt:
   2.248 +        print "Interrupted."
   2.249 +        return True, ''
   2.250 +    except IOError, ex:
   2.251 +        if os.geteuid() != 0:
   2.252 +            err("Most commands need root access.  Please try again as root.")
   2.253 +        else:
   2.254 +            err("Unable to connect to xend: %s." % ex[1])
   2.255 +    except SystemExit:
   2.256 +        return True, ''
   2.257 +    except XenAPI.Failure, exn:
   2.258 +        err(str(exn))
   2.259 +    except xmlrpclib.Fault, ex:
   2.260 +        if ex.faultCode == XendClient.ERROR_INVALID_DOMAIN:
   2.261 +            err("Domain '%s' does not exist." % ex.faultString)
   2.262 +        else:
   2.263 +            err(ex.faultString)
   2.264 +        _usage(cmd_name)
   2.265 +    except xmlrpclib.ProtocolError, ex:
   2.266 +        if ex.errcode == -1:
   2.267 +            print  >>sys.stderr, (
   2.268 +                "Xend has probably crashed!  Invalid or missing HTTP "
   2.269 +                "status code.")
   2.270 +        else:
   2.271 +            print  >>sys.stderr, (
   2.272 +                "Xend has probably crashed!  ProtocolError(%d, %s)." %
   2.273 +                (ex.errcode, ex.errmsg))
   2.274 +    except (ValueError, OverflowError):
   2.275 +        err("Invalid argument.")
   2.276 +        _usage(cmd_name)
   2.277 +    except OptionError, e:
   2.278 +        err(str(e))
   2.279 +        _usage(cmd_name)
   2.280 +        print e.usage()
   2.281 +    except security.ACMError, e:
   2.282 +        err(str(e))
   2.283 +    except:
   2.284 +        print "Unexpected error:", sys.exc_info()[0]
   2.285 +        print
   2.286 +        print "Please report to xen-devel@lists.xensource.com"
   2.287 +        raise
   2.288 +
   2.289 +    return False, 1
   2.290  
   2.291  if __name__ == "__main__":
   2.292      main()