VirtualBox

Changeset 20897 in vbox for trunk/src


Ignore:
Timestamp:
Jun 24, 2009 3:54:41 PM (16 years ago)
Author:
vboxsync
Message:

Python: cleanup, refactoring, don't fail on timed wait requests on Darwin, just return, shell improvments

Location:
trunk/src
Files:
4 edited

Legend:

Unmodified
Added
Removed
  • trunk/src/VBox/Frontends/VBoxShell/vboxshell.py

    r20818 r20897  
    3030import traceback
    3131
    32 class PerfCollector:
    33     """ This class provides a wrapper over IPerformanceCollector in order to
    34     get more 'pythonic' interface.
    35 
    36     To begin collection of metrics use setup() method.
    37 
    38     To get collected data use query() method.
    39 
    40     It is possible to disable metric collection without changing collection
    41     parameters with disable() method. The enable() method resumes metric
    42     collection.
    43     """
    44 
    45     def __init__(self, vb):
    46         """ Initializes the instance.
    47 
    48         Pass an instance of IVirtualBox as parameter.
    49         """
    50         self.collector = vb.performanceCollector
    51 
    52     def setup(self, names, objects, period, nsamples):
    53         """ Discards all previously collected values for the specified
    54         metrics, sets the period of collection and the number of retained
    55         samples, enables collection.
    56         """
    57         self.collector.setupMetrics(names, objects, period, nsamples)
    58 
    59     def enable(self, names, objects):
    60         """ Resumes metric collection for the specified metrics.
    61         """
    62         self.collector.enableMetrics(names, objects)
    63 
    64     def disable(self, names, objects):
    65         """ Suspends metric collection for the specified metrics.
    66         """
    67         self.collector.disableMetrics(names, objects)
    68 
    69     def query(self, names, objects):
    70         """ Retrieves collected metric values as well as some auxiliary
    71         information. Returns an array of dictionaries, one dictionary per
    72         metric. Each dictionary contains the following entries:
    73         'name': metric name
    74         'object': managed object this metric associated with
    75         'unit': unit of measurement
    76         'scale': divide 'values' by this number to get float numbers
    77         'values': collected data
    78         'values_as_string': pre-processed values ready for 'print' statement
    79         """
    80         (values, names_out, objects_out, units, scales, sequence_numbers,
    81             indices, lengths) = self.collector.queryMetricsData(names, objects)
    82         out = []
    83         for i in xrange(0, len(names_out)):
    84             scale = int(scales[i])
    85             if scale != 1:
    86                 fmt = '%.2f%s'
    87             else:
    88                 fmt = '%d %s'
    89             out.append({
    90                 'name':str(names_out[i]),
    91                 'object':str(objects_out[i]),
    92                 'unit':str(units[i]),
    93                 'scale':scale,
    94                 'values':[int(values[j]) for j in xrange(int(indices[i]), int(indices[i])+int(lengths[i]))],
    95                 'values_as_string':'['+', '.join([fmt % (int(values[j])/scale, units[i]) for j in xrange(int(indices[i]), int(indices[i])+int(lengths[i]))])+']'
    96             })
    97         return out
    98 
    9932# Simple implementation of IConsoleCallback, one can use it as skeleton
    10033# for custom implementations
     
    170103    def onExtraDataCanChange(self, id, key, value):
    171104        print "onExtraDataCanChange: %s %s=>%s" %(id, key, value)
    172         return True
     105        return True, ""
    173106
    174107    def onExtraDataChange(self, id, key, value):
     
    193126        print "onSnapshotChange: %s %s" %(mach, id)
    194127
    195     def onGuestPropertyChange(self, id, val1, val2, val3):
    196         print "onGuestPropertyChange: %s" %(id)
    197    
     128    def onGuestPropertyChange(self, id, name, newValue, flags):
     129        print "onGuestPropertyChange: %s: %s=%s" %(id, name, newValue)
    198130
    199131g_hasreadline = 1
     
    458390
    459391def infoCmd(ctx,args):
     392    import time
    460393    if (len(args) < 2):
    461394        print "usage: info [vmname|uuid]"
     
    468401    print "  ID: ",mach.id
    469402    print "  OS Type: ",os.description
     403    print "  CPUs:  %d" %(mach.CPUCount)
    470404    print "  RAM:  %dM" %(mach.memorySize)
    471405    print "  VRAM:  %dM" %(mach.VRAMSize)
     406    print "  Monitors:  %d" %(mach.monitorCount)
    472407    print "  Clipboard mode:  %d" %(mach.clipboardMode)
    473408    print "  Machine status: " ,mach.sessionState
    474409    bios = mach.BIOSSettings
    475     print "  BIOS ACPI: ",bios.ACPIEnabled
    476     print "  PAE: ",mach.PAEEnabled
     410    print "  ACPI: %s" %(asState(bios.ACPIEnabled))
     411    print "  APIC: %s" %(asState(bios.IOAPICEnabled))
     412    print "  PAE: %s" %(asState(mach.PAEEnabled))
    477413    print "  Hardware virtualization: ",asState(mach.HWVirtExEnabled)
     414    print "  VPID support: ",asState(mach.HWVirtExVPIDEnabled)
     415    print "  Hardware 3d acceleration: ",asState(mach.accelerate3DEnabled)
    478416    print "  Nested paging: ",asState(mach.HWVirtExNestedPagingEnabled)
    479     print "  Last changed: ",mach.lastStateChange
     417    print "  Last changed: ",time.asctime(time.localtime(mach.lastStateChange/1000))
    480418
    481419    return 0
     
    625563        dur = float(args[1])
    626564    monitorVbox(ctx, dur)
     565    return 0
     566
     567def getAdapterType(ctx, type):
     568    if (type == ctx['global'].constants.NetworkAdapterType_Am79C970A or
     569        type == ctx['global'].constants.NetworkAdapterType_Am79C973):
     570        return "pcnet"
     571    elif (type == ctx['global'].constants.NetworkAdapterType_I82540EM or
     572          type == ctx['global'].constants.NetworkAdapterType_I82545EM or
     573          type == ctx['global'].constants.NetworkAdapterType_I82543GC):
     574        return "e1000"
     575    elif (type == ctx['global'].constants.NetworkAdapterType_Null):
     576        return None
     577    else:
     578        raise Exception("Unknown adapter type: "+type)   
     579   
     580
     581def portForwardCmd(ctx, args):
     582    if (len(args) != 5):
     583        print "usage: portForward <vm> <adapter> <hostPort> <guestPort>"
     584        return 0
     585    mach = argsToMach(ctx,args)
     586    if mach == None:
     587        return 0
     588    adapterNum = int(args[2])
     589    hostPort = int(args[3])
     590    guestPort = int(args[4])
     591    proto = "TCP"
     592    session = ctx['global'].openMachineSession(mach.id)
     593    mach = session.machine
     594
     595    adapter = mach.getNetworkAdapter(adapterNum)
     596    adapterType = getAdapterType(ctx, adapter.adapterType)
     597
     598    profile_name = proto+"_"+str(hostPort)+"_"+str(guestPort)
     599    config = "VBoxInternal/Devices/" + adapterType + "/"
     600    config = config + str(adapter.slot)  +"/LUN#0/Config/" + profile_name
     601 
     602    mach.setExtraData(config + "/Protocol", proto)
     603    mach.setExtraData(config + "/HostPort", str(hostPort))
     604    mach.setExtraData(config + "/GuestPort", str(guestPort))
     605
     606    mach.saveSettings()
     607    session.close()
     608   
    627609    return 0
    628610
     
    664646            'monitorGuest':['Monitor what happens with the guest for some time: monitorGuest Win32 10', monitorGuestCmd],
    665647            'monitorVbox':['Monitor what happens with Virtual Box for some time: monitorVbox 10', monitorVboxCmd],
     648            'portForward':['Setup permanent port forwarding for a VM, takes adapter number host port and guest port: portForward Win32 0 8080 80', portForwardCmd],
    666649            }
    667650
     
    683666    vbox = ctx['vb']
    684667    print "Running VirtualBox version %s" %(vbox.version)
    685     ctx['perf'] = PerfCollector(vbox)
     668    ctx['perf'] = ctx['global'].getPerfCollector(ctx['vb'])
    686669
    687670    autoCompletion(commands, ctx)
  • trunk/src/VBox/Main/glue/vboxapi.py

    r20818 r20897  
    3333from VirtualBox_constants import VirtualBoxReflectionInfo
    3434
     35class PerfCollector:
     36    """ This class provides a wrapper over IPerformanceCollector in order to
     37    get more 'pythonic' interface.
     38
     39    To begin collection of metrics use setup() method.
     40
     41    To get collected data use query() method.
     42
     43    It is possible to disable metric collection without changing collection
     44    parameters with disable() method. The enable() method resumes metric
     45    collection.
     46    """
     47
     48    def __init__(self, vb):
     49        """ Initializes the instance.
     50
     51        Pass an instance of IVirtualBox as parameter.
     52        """
     53        self.collector = vb.performanceCollector
     54
     55    def setup(self, names, objects, period, nsamples):
     56        """ Discards all previously collected values for the specified
     57        metrics, sets the period of collection and the number of retained
     58        samples, enables collection.
     59        """
     60        self.collector.setupMetrics(names, objects, period, nsamples)
     61
     62    def enable(self, names, objects):
     63        """ Resumes metric collection for the specified metrics.
     64        """
     65        self.collector.enableMetrics(names, objects)
     66
     67    def disable(self, names, objects):
     68        """ Suspends metric collection for the specified metrics.
     69        """
     70        self.collector.disableMetrics(names, objects)
     71
     72    def query(self, names, objects):
     73        """ Retrieves collected metric values as well as some auxiliary
     74        information. Returns an array of dictionaries, one dictionary per
     75        metric. Each dictionary contains the following entries:
     76        'name': metric name
     77        'object': managed object this metric associated with
     78        'unit': unit of measurement
     79        'scale': divide 'values' by this number to get float numbers
     80        'values': collected data
     81        'values_as_string': pre-processed values ready for 'print' statement
     82        """
     83        (values, names_out, objects_out, units, scales, sequence_numbers,
     84            indices, lengths) = self.collector.queryMetricsData(names, objects)
     85        out = []
     86        for i in xrange(0, len(names_out)):
     87            scale = int(scales[i])
     88            if scale != 1:
     89                fmt = '%.2f%s'
     90            else:
     91                fmt = '%d %s'
     92            out.append({
     93                'name':str(names_out[i]),
     94                'object':str(objects_out[i]),
     95                'unit':str(units[i]),
     96                'scale':scale,
     97                'values':[int(values[j]) for j in xrange(int(indices[i]), int(indices[i])+int(lengths[i]))],
     98                'values_as_string':'['+', '.join([fmt % (int(values[j])/scale, units[i]) for j in xrange(int(indices[i]), int(indices[i])+int(lengths[i]))])+']'
     99            })
     100        return out
     101
    35102class PlatformMSCOM:
    36103    # Class to fake access to constants in style of foo.bar.boo
     
    191258        if rc >= WAIT_OBJECT_0 and rc < WAIT_OBJECT_0+len(self.handles):
    192259            # is it possible?
    193             print "how come?"
    194260            pass
    195261        elif rc==WAIT_OBJECT_0 + len(self.handles):
     
    210276        pythoncom.CoUninitialize()
    211277        pass
     278
     279    def getPerfCollector(self, vbox):
     280        # MS COM cannot invoke performance collector methods yet
     281        return None
     282
    212283
    213284class PlatformXPCOM:
     
    265336        import xpcom
    266337        xpcom._xpcom.DeinitCOM()
     338
     339    def getPerfCollector(self, vbox):
     340        return PerfCollector(vbox)
    267341
    268342class PlatformWEBSERVICE:
     
    286360
    287361    def getVirtualBox(self):
    288         return self.wsmgr.logon(self.user, self.password)
     362        self.vbox = self.wsmgr.logon(self.user, self.password)
    289363
    290364    def getConstants(self):
     
    310384
    311385    def waitForEvents(self, timeout):
    312         # Webservices cannot do that
     386        # Webservices cannot do that yet
    313387        pass
    314388
    315389    def deinit(self):
    316         # should we do something about it?
    317         pass
     390        try:
     391            if self.vbox is not None:
     392                self.wsmg.logoff(self.vbox)
     393                self.vbox = None
     394        except:
     395            pass
     396
     397    def getPerfCollector(self, vbox):
     398        return PerfCollector(vbox)   
    318399
    319400class SessionManager:
     
    338419            self.type = self.platform.getType()
    339420            self.remote = self.platform.getRemote()
     421            self.style = style           
    340422        except Exception,e:
    341423            print "init exception: ",e
     
    350432
    351433    def __del__(self):
    352         deinit(self)
     434        self.deinit()
    353435
    354436    def deinit(self):
    355437        if hasattr(self, "vbox"):
    356438            del self.vbox
     439            self.vbox = None
    357440        if hasattr(self, "platform"):
    358441            self.platform.deinit()
     442             self.platform = None
    359443
    360444    def initPerThread(self):
     
    377461    def waitForEvents(self, timeout):
    378462        return self.platform.waitForEvents(timeout)
     463
     464    def getPerfCollector(self, vbox):
     465        return self.platform.getPerfCollector(vbox)       
  • trunk/src/VBox/Main/idl/VirtualBox.xidl

    r20896 r20897  
    43264326
    43274327    <attribute name="CPUCount" type="unsigned long">
    4328       <desc>Number of virtual CPUs in the VM. In the current version of the product, this is always 1.</desc>
     4328      <desc>Number of virtual CPUs in the VM.</desc>
    43294329    </attribute>
    43304330
  • trunk/src/libs/xpcom18a4/python/src/module/_xpcom.cpp

    r20630 r20897  
    534534  /* Cannot perform timed wait otherwise */
    535535  if (fd < 0)
    536     return NULL;
    537  
     536#ifdef RT_OS_DARWIN
     537      /**
     538       * @todo: maybe need some way to implement timed wait on Darwin,
     539       *        just return immediately instead
     540       */
     541      goto ok;
     542#else
     543      return NULL;
     544#endif
    538545 
    539546  {
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