VirtualBox

Changeset 11892 in vbox


Ignore:
Timestamp:
Aug 31, 2008 11:49:10 PM (16 years ago)
Author:
vboxsync
Message:

docs updates, shell refactoring, uniformization of WS and XPCOM API

Location:
trunk/src/libs/xpcom18a4
Files:
3 edited

Legend:

Unmodified
Added
Removed
  • trunk/src/libs/xpcom18a4/Makefile.kmk

    r11859 r11892  
    13841384# Python Client Module - a sample script.
    13851385VBoxPython-inst-sample_INST = $(INST_SDK)bindings/xpcom/python/sample/
    1386 VBoxPython-inst-sample_SOURCES = \
    1387         python/sample/vboxshell.py
     1386VBoxPython-inst-sample_SOURCES =        \
     1387        python/sample/vboxshell.py      \
     1388        python/sample/shellcommon.py
    13881389
    13891390
  • trunk/src/libs/xpcom18a4/python/sample/vboxshell.py

    r11852 r11892  
    3434
    3535#
    36 import traceback
    37 import sys
    38 import pdb
    39 
    40 g_hasreadline = 1
    41 try:
    42     import readline
    43     import rlcompleter
    44 except:
    45     g_hasreadline = 0
    4636
    4737# this one has to be the first XPCOM related import
     
    4939import xpcom
    5040import xpcom.components
     41import sys
     42
     43from shellcommon import interpret
    5144
    5245class LocalManager:
     
    5447        return xpcom.components.classes["@virtualbox.org/Session;1"].createInstance()
    5548
    56 if g_hasreadline:
    57   class CompleterNG(rlcompleter.Completer):
    58     def __init__(self, dic, ctx):
    59         self.ctx = ctx
    60         return rlcompleter.Completer.__init__(self,dic)
     49vbox = None
     50mgr = LocalManager()
     51try:
     52    vbox = xpcom.components.classes["@virtualbox.org/VirtualBox;1"].createInstance()
     53except xpcom.Exception, e:
     54    print "XPCOM exception: ",e
     55    traceback.print_exc()
     56    sys.exit(1)
    6157
    62     def complete(self, text, state):
    63         """
    64         taken from:
    65         http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/496812
    66         """
    67         if text == "":
    68             return ['\t',None][state]
    69         else:
    70             return rlcompleter.Completer.complete(self,text,state)
     58ctx = {'mgr':mgr, 'vb':vbox, 'ifaces':xpcom.components.interfaces, 'remote':False}
    7159
    72     def global_matches(self, text):
    73         """
    74         Compute matches when text is a simple name.
    75         Return a list of all names currently defined
    76         in self.namespace that match.
    77         """
    78        
    79         matches = []
    80         n = len(text)
    81        
    82         for list in [ self.namespace ]:
    83             for word in list:
    84                 if word[:n] == text:
    85                     matches.append(word)
     60interpret(ctx)
    8661
    87         for m in getMachines(self.ctx):
    88             word = m.name
    89             if word[:n] == text:
    90                 matches.append(word)
    91             word = str(m.id)[1:-1]
    92             if word[:n] == text:
    93                     matches.append(word)
    94 
    95         return matches
    96 
    97 
    98 def autoCompletion(commands, ctx):
    99   if  not g_hasreadline:
    100       return
    101  
    102   comps = {}
    103   for (k,v) in commands.items():
    104       comps[k] = None
    105   completer = CompleterNG(comps, ctx)
    106   readline.set_completer(completer.complete)
    107   readline.parse_and_bind("tab: complete")
    108 
    109 g_verbose = True
    110 
    111 def split_no_quotes(s):
    112    return s.split()
    113    
    114 def startVm(mgr,vb,mach,type):
    115     session = mgr.getSessionObject(vb)
    116     uuid = mach.id
    117     progress = vb.openRemoteSession(session, uuid, type, "")
    118     progress.waitForCompletion(-1)
    119     completed = progress.completed
    120     rc = progress.resultCode
    121     print "Completed:", completed, "rc:",rc
    122     session.close()
    123 
    124 def getMachines(ctx):
    125     return ctx['vb'].getMachines2()
    126 
    127 def asState(var):
    128     if var:
    129         return 'on'
    130     else:
    131         return 'off'
    132 
    133 def guestStats(ctx,guest):
    134     stats = {
    135         'Guest statistics for sample': xpcom.components.interfaces.GuestStatisticType.SampleNumber,
    136         'CPU Load Idle': xpcom.components.interfaces.GuestStatisticType.CPULoad_Idle,
    137         'CPU Load User': xpcom.components.interfaces.GuestStatisticType.CPULoad_User,
    138         'CPU Load Kernel': xpcom.components.interfaces.GuestStatisticType.CPULoad_Kernel,
    139         'Threads': xpcom.components.interfaces.GuestStatisticType.Threads,
    140         'Processes': xpcom.components.interfaces.GuestStatisticType.Processes,
    141         'Handles': xpcom.components.interfaces.GuestStatisticType.Handles,
    142         }
    143     for (k,v) in stats.items():
    144         try:
    145             val = guest.getStatistic(0, v)
    146             print "'%s' = '%s'" %(k,str(v))
    147         except:
    148             print "Cannot get value for '%s'"  %(k)
    149             pass
    150 
    151 def cmdExistingVm(ctx,mach,cmd):
    152     mgr=ctx['mgr']
    153     vb=ctx['vb']
    154     session = mgr.getSessionObject(vb)
    155     uuid = mach.id
    156     try:
    157         progress = vb.openExistingSession(session, uuid)
    158     except Exception,e:
    159         print "Session to '%s' not open: %s" %(mach.name,e)
    160         if g_verbose:
    161             traceback.print_exc()
    162         return
    163     if session.state != xpcom.components.interfaces.SessionState.Open:
    164         print "Session to '%s' in wrong state: %s" %(mach.name, session.state)
    165         return
    166     console=session.console
    167     ops={'pause' :     lambda: console.pause(),
    168          'resume':     lambda: console.resume(),
    169          'powerdown':  lambda: console.powerDown(),
    170          'stats':      lambda: guestStats(ctx, console.guest)}
    171     ops[cmd]()
    172     session.close()
    173 
    174 # can cache known machines, if needed
    175 def machById(ctx,id):
    176     mach = None
    177     for m in getMachines(ctx):
    178         if str(m.id) == '{'+id+'}' or m.name == id:
    179             mach = m
    180             break
    181     return mach
    182 
    183 def argsToMach(ctx,args):
    184     if len(args) < 2:
    185         print "usage: %s [vmname|uuid]" %(args[0])
    186         return None
    187     id = args[1]
    188     m = machById(ctx, id)
    189     if m == None:
    190         print "Machine '%s' is unknown, use list command to find available machines" %(id)
    191     return m
    192 
    193 def helpCmd(ctx, args):
    194     if len(args) == 1:
    195         print "Help page:"
    196         for i in commands:
    197             print "   ",i,":", commands[i][0]
    198     else:
    199         c = commands.get(args[1], None)
    200         if c == None:
    201             print "Command '%s' not known" %(args[1])
    202         else:
    203             print "   ",args[1],":", c[0]
    204     return 0
    205 
    206 def listCmd(ctx, args):
    207     for m in getMachines(ctx):
    208         print "Machine '%s' [%s], state=%s" %(m.name,m.id,m.sessionState)
    209     return 0
    210 
    211 def infoCmd(ctx,args):
    212     if (len(args) < 2):
    213         print "usage: info [vmname|uuid]"
    214         return 0
    215     mach = argsToMach(ctx,args)
    216     if mach == None:
    217         return 0
    218     os = ctx['vb'].getGuestOSType(mach.OSTypeId)
    219     print "  Name: ",mach.name
    220     print "  ID: ",mach.id
    221     print "  OS Type: ",os.description
    222     print "  RAM:  %dM" %(mach.memorySize)
    223     print "  VRAM:  %dM" %(mach.VRAMSize)
    224     print "  Monitors:  %d" %(mach.MonitorCount)
    225     print "  Clipboard mode:  %d" %(mach.clipboardMode)
    226     print "  Machine status: " ,mach.sessionState
    227     bios = mach.BIOSSettings
    228     print "  BIOS ACPI: ",bios.ACPIEnabled
    229     print "  PAE: ",mach.PAEEnabled
    230     print "  Hardware virtualization: ",asState(mach.HWVirtExEnabled)
    231     print "  Nested paging: ",asState(mach.HWVirtExNestedPagingEnabled)
    232     print "  Last changed: ",mach.lastStateChange
    233 
    234     return 0
    235 
    236 def startCmd(ctx, args):
    237     mach = argsToMach(ctx,args)
    238     if mach == None:
    239         return 0
    240     if len(args) > 2:
    241         type = args[2]
    242     else:
    243         type = "gui"
    244     startVm(ctx['mgr'], ctx['vb'], mach, type)
    245     return 0
    246 
    247 def pauseCmd(ctx, args):
    248     mach = argsToMach(ctx,args)
    249     if mach == None:
    250         return 0
    251     cmdExistingVm(ctx, mach, 'pause')
    252     return 0
    253 
    254 def powerdownCmd(ctx, args):
    255     mach = argsToMach(ctx,args)
    256     if mach == None:
    257         return 0
    258     cmdExistingVm(ctx, mach, 'powerdown')
    259     return 0
    260 
    261 def resumeCmd(ctx, args):
    262     mach = argsToMach(ctx,args)
    263     if mach == None:
    264         return 0
    265     cmdExistingVm(ctx, mach, 'resume')
    266     return 0
    267 
    268 def statsCmd(ctx, args):
    269     mach = argsToMach(ctx,args)
    270     if mach == None:
    271         return 0
    272     cmdExistingVm(ctx, mach, 'stats')
    273     return 0
    274 
    275 def quitCmd(ctx, args):
    276     return 1
    277 
    278 def aliasesCmd(ctx, args):
    279     for (k,v) in aliases.items():
    280         print "'%s' is an alias for '%s'" %(k,v)
    281     return 0
    282 
    283 def verboseCmd(ctx, args):
    284     global g_verbose
    285     g_verbose = not g_verbose
    286     return 0
    287 
    288 def hostCmd(ctx, args):
    289    host = ctx['vb'].host
    290    cnt = host.processorCount
    291    print "Processor count:",cnt
    292    for i in range(0,cnt):
    293       print "Processor #%d speed: %dMHz" %(i,host.getProcessorSpeed(i))
    294                
    295    collector = ctx['vb'].performanceCollector
    296  
    297    (vals, names, objs, idxs, lens) = collector.queryMetricsData(["*"], [host])
    298    for i in range(0,len(vals)):
    299       print "for name:",names[i]," val:",vals[i]
    300 
    301    return 0
    302 
    303 aliases = {'s':'start', 
    304            'i':'info',
    305            'l':'list',
    306            'h':'help',
    307            'a':'aliases',
    308            'q':'quit', 'exit':'quit',
    309            'v':'verbose'}
    310 
    311 commands = {'help':['Prints help information', helpCmd],
    312             'start':['Start virtual machine by name or uuid', startCmd],
    313             'pause':['Pause virtual machine', pauseCmd],
    314             'resume':['Resume virtual machine', resumeCmd],
    315             'stats':['Stats for virtual machine', statsCmd],
    316             'powerdown':['Power down virtual machine', powerdownCmd],
    317             'list':['Shows known virtual machines', listCmd],
    318             'info':['Shows info on machine', infoCmd],
    319             'aliases':['Shows aliases', aliasesCmd],
    320             'verbose':['Toggle verbosity', verboseCmd],
    321             'quit':['Exits', quitCmd],
    322             'host':['Show host information', hostCmd]}
    323 
    324 def runCommand(ctx, cmd):
    325     if len(cmd) == 0: return 0
    326     args = split_no_quotes(cmd)
    327     c = args[0]
    328     if aliases.get(c, None) != None:
    329         c = aliases[c]
    330     ci = commands.get(c,None)
    331     if ci == None:
    332         print "Unknown command: '%s', type 'help' for list of known commands" %(c)
    333         return 0
    334     return ci[1](ctx, args)
    335 
    336 def interpret():
    337     vbox = None
    338     try:
    339         vbox = xpcom.components.classes["@virtualbox.org/VirtualBox;1"].createInstance()
    340     except xpcom.Exception, e:
    341         print "XPCOM exception: ",e
    342         traceback.print_exc()
    343         return
    344     print "Running VirtualBox version %s" %(vbox.version)
    345     mgr = LocalManager()
    346     ctx = {'mgr':mgr, 'vb':vbox }
    347 
    348     autoCompletion(commands, ctx)
    349 
    350     while True:
    351         try:
    352             cmd = raw_input("vbox> ")
    353             done = runCommand(ctx, cmd)
    354             if done != 0: break
    355         except KeyboardInterrupt:           
    356             print '====== You can type quit or q to leave'
    357             break
    358         except EOFError:
    359             break;
    360         except Exception,e:
    361             print e
    362             if g_verbose:
    363                 traceback.print_exc()
    364 
    365 
    366 interpret()
     62del vbox
  • trunk/src/libs/xpcom18a4/python/src/module/_xpcom.cpp

    r11891 r11892  
    587587#include <iprt/runtime.h>
    588588#include <iprt/stream.h>
     589
    589590extern "C" NS_EXPORT
    590591void
Note: See TracChangeset for help on using the changeset viewer.

© 2024 Oracle Support Privacy / Do Not Sell My Info Terms of Use Trademark Policy Automated Access Etiquette