~ubuntu-branches/ubuntu/vivid/virtualbox-ose/vivid

« back to all changes in this revision

Viewing changes to src/VBox/Frontends/VBoxShell/vboxshell.py

  • Committer: Bazaar Package Importer
  • Author(s): Felix Geyer
  • Date: 2009-09-14 18:25:07 UTC
  • mfrom: (0.4.1 squeeze)
  • Revision ID: james.westby@ubuntu.com-20090914182507-c98g07mq16hjmn6d
Tags: 3.0.6-dfsg-1ubuntu1
* Merge from debian unstable (LP: #429697), remaining changes:
  - Enable DKMS support on virtualbox host and guest modules (LP: #267097)
    - Drop virtualbox-ose{-guest,}-modules-* package templates
    - Recommend *-source instead of *-modules packages
    - Replace error messages related to missing/mismatched
      kernel module accordingly
  - Autoload kernel module
    - LOAD_VBOXDRV_MODULE=1 in virtualbox-ose.default
  - Disable update action
    - patches/u01-disable-update-action.dpatch
  - Virtualbox should go in Accessories, not in System tools (LP: #288590)
    - virtualbox-ose-qt.files/virtualbox-ose.desktop
  - Add apport hook
    - virtualbox-ose.files/source_virtualbox-ose.py
    - virtualbox-ose.install
  - Add launchpad integration
    - control
    - lpi-bug.xpm
    - patches/u02-lp-integration.dpatch
  - virtualbox, virtualbox-* (names of the upstream proprietary packages)
    conflict with virtualbox-ose (LP: #379878)
* Make debug package depend on normal or guest utils package
* Drop patches/22-pulseaudio-stubs.dpatch (applied upstream)
* Rename Ubuntu specific patches to uXX-*.dpatch
* Fix lintian warnings in maintainer scripts

Show diffs side-by-side

added added

removed removed

Lines of Context:
92
92
        print  "%s: onShowWindow: %d" %(self.mach.name, winId)
93
93
 
94
94
class VBoxMonitor:
95
 
    def __init__(self, vbox):
96
 
        self.vbox = vbox
 
95
    def __init__(self, params):
 
96
        self.vbox = params[0]
 
97
        self.isMscom = params[1]
97
98
        pass
98
99
 
99
100
    def onMachineStateChange(self, id, state):
104
105
 
105
106
    def onExtraDataCanChange(self, id, key, value):
106
107
        print "onExtraDataCanChange: %s %s=>%s" %(id, key, value)
107
 
        return True, ""
 
108
        # Witty COM bridge thinks if someone wishes to return tuple, hresult
 
109
        # is one of values we want to return
 
110
        if self.isMscom:
 
111
            return "", 0, True
 
112
        else:
 
113
            return True, ""
108
114
 
109
115
    def onExtraDataChange(self, id, key, value):
110
116
        print "onExtraDataChange: %s %s=>%s" %(id, key, value)
111
117
 
112
 
    def onMediaRegistred(self, id, type, registred):
113
 
        print "onMediaRegistred: %s" %(id)
 
118
    def onMediaRegistered(self, id, type, registered):
 
119
        print "onMediaRegistered: %s" %(id)
114
120
 
115
 
    def onMachineRegistred(self, id, registred):
116
 
        print "onMachineRegistred: %s" %(id)
 
121
    def onMachineRegistered(self, id, registred):
 
122
        print "onMachineRegistered: %s" %(id)
117
123
 
118
124
    def onSessionStateChange(self, id, state):
119
125
        print "onSessionStateChange: %s %d" %(id, state)
205
211
def split_no_quotes(s):
206
212
    return shlex.split(s)
207
213
 
 
214
def progressBar(ctx,p,wait=1000):
 
215
    try:
 
216
        while not p.completed:
 
217
            print "%d %%\r" %(p.percent),
 
218
            sys.stdout.flush()
 
219
            p.waitForCompletion(wait)
 
220
    except KeyboardInterrupt:
 
221
        print "Interrupted."
 
222
 
208
223
def createVm(ctx,name,kind,base):
209
224
    mgr = ctx['mgr']
210
225
    vb = ctx['vb']
222
237
    print "removing machine ",mach.name,"with UUID",id
223
238
    session = ctx['global'].openMachineSession(id)
224
239
    try:
225
 
       mach = session.Machine
 
240
       mach = session.machine
226
241
       for d in ctx['global'].getArray(mach, 'hardDiskAttachments'):
227
242
          mach.detachHardDisk(d.controller, d.port, d.device)
228
243
    except:
229
244
       traceback.print_exc()
 
245
    mach.saveSettings()
230
246
    ctx['global'].closeMachineSession(session)
231
247
    mach = vb.unregisterMachine(id)
232
248
    if mach:
241
257
    session = mgr.getSessionObject(vb)
242
258
    uuid = mach.id
243
259
    progress = vb.openRemoteSession(session, uuid, type, "")
244
 
    progress.waitForCompletion(-1)
 
260
    progressBar(ctx, progress, 100)
245
261
    completed = progress.completed
246
262
    rc = int(progress.resultCode)
247
263
    print "Completed:", completed, "rc:",hex(rc&0xffffffff)
302
318
    console.unregisterCallback(cb)
303
319
 
304
320
 
305
 
def monitorVbox(ctx, dur):
 
321
def monitorVBox(ctx, dur):
306
322
    vbox = ctx['vb']
307
 
    cb = ctx['global'].createCallback('IVirtualBoxCallback', VBoxMonitor, vbox)
 
323
    isMscom = (ctx['global'].type == 'MSCOM')
 
324
    cb = ctx['global'].createCallback('IVirtualBoxCallback', VBoxMonitor, [vbox, isMscom])
308
325
    vbox.registerCallback(cb)
309
326
    if dur == -1:
310
327
        # not infinity, but close enough
315
332
            ctx['global'].waitForEvents(500)
316
333
    # We need to catch all exceptions here, otherwise callback will never be unregistered
317
334
    except:
318
 
        if g_verbose:
319
 
                traceback.print_exc()
 
335
        pass
320
336
    vbox.unregisterCallback(cb)
321
337
 
322
338
def cmdExistingVm(ctx,mach,cmd,args):
347
363
         'stats':           lambda: guestStats(ctx, mach),
348
364
         'guest':           lambda: guestExec(ctx, mach, console, args),
349
365
         'monitorGuest':    lambda: monitorGuest(ctx, mach, console, args),
350
 
         'save':            lambda: console.saveState().waitForCompletion(-1)
 
366
         'save':            lambda: progressBar(ctx,console.saveState())
351
367
         }
352
368
    try:
353
369
        ops[cmd]()
382
398
        print "Machine '%s' is unknown, use list command to find available machines" %(id)
383
399
    return m
384
400
 
 
401
def helpSingleCmd(cmd,h,sp):
 
402
    if sp != 0:
 
403
        spec = " [ext from "+sp+"]"
 
404
    else:
 
405
        spec = ""
 
406
    print "    %s: %s%s" %(cmd,h,spec)
 
407
 
385
408
def helpCmd(ctx, args):
386
409
    if len(args) == 1:
387
410
        print "Help page:"
388
411
        names = commands.keys()
389
412
        names.sort()
390
413
        for i in names:
391
 
            print "   ",i,":", commands[i][0]
 
414
            helpSingleCmd(i, commands[i][0], commands[i][2])
392
415
    else:
393
 
        c = commands.get(args[1], None)
 
416
        cmd = args[1]
 
417
        c = commands.get(cmd)
394
418
        if c == None:
395
 
            print "Command '%s' not known" %(args[1])
 
419
            print "Command '%s' not known" %(cmd)
396
420
        else:
397
 
            print "   ",args[1],":", c[0]
 
421
            helpSingleCmd(cmd, c[0], c[2])
398
422
    return 0
399
423
 
400
424
def listCmd(ctx, args):
484
508
        print "  DVD:"
485
509
        print "    Image at: %s" %(vdvd.location)
486
510
        print "    Size: %s" %(vdvd.size)
 
511
        print "    Id: %s" %(vdvd.id)
487
512
        print
488
513
 
489
514
    floppy = mach.floppyDrive
689
714
    cmdExistingVm(ctx, mach, 'monitorGuest', dur)
690
715
    return 0
691
716
 
692
 
def monitorVboxCmd(ctx, args):
 
717
def monitorVBoxCmd(ctx, args):
693
718
    if (len(args) > 2):
694
 
        print "usage: monitorVbox (duration)"
 
719
        print "usage: monitorVBox (duration)"
695
720
        return 0
696
721
    dur = 5
697
722
    if len(args) > 1:
698
723
        dur = float(args[1])
699
 
    monitorVbox(ctx, dur)
 
724
    monitorVBox(ctx, dur)
700
725
    return 0
701
726
 
702
727
def getAdapterType(ctx, type):
781
806
 
782
807
def reloadExtCmd(ctx, args):
783
808
   # maybe will want more args smartness
784
 
   checkUserExtensions(ctx, commands, ctx['vb'].homeFolder)
 
809
   checkUserExtensions(ctx, commands, getHomeFolder(ctx))
785
810
   autoCompletion(commands, ctx)
786
811
   return 0
787
812
 
881
906
    ctx['vb'] = None
882
907
    return 0
883
908
 
 
909
def exportVMCmd(ctx, args):
 
910
    import sys
 
911
 
 
912
    if len(args) < 3:
 
913
        print "usage: exportVm <machine> <path> <format> <license>"
 
914
        return 0
 
915
    mach = ctx['machById'](args[1])
 
916
    if mach is None:
 
917
        return 0
 
918
    path = args[2]
 
919
    if (len(args) > 3):
 
920
        format = args[3]
 
921
    else:
 
922
        format = "ovf-1.0"
 
923
    if (len(args) > 4):
 
924
        license = args[4]
 
925
    else:
 
926
        license = "GPL"
 
927
 
 
928
    app = ctx['vb'].createAppliance()
 
929
    desc = mach.export(app)
 
930
    desc.addDescription(ctx['global'].constants.VirtualSystemDescriptionType_License, license, "")
 
931
    p = app.write(format, path)
 
932
    progressBar(ctx, p)
 
933
    print "Exported to %s in format %s" %(path, format)
 
934
    return 0
 
935
 
884
936
aliases = {'s':'start',
885
937
           'i':'info',
886
938
           'l':'list',
887
939
           'h':'help',
888
940
           'a':'alias',
889
941
           'q':'quit', 'exit':'quit',
890
 
           'v':'verbose',
891
 
           '!':'shell'}
 
942
           'v':'verbose'}
892
943
 
893
944
commands = {'help':['Prints help information', helpCmd, 0],
894
945
            'start':['Start virtual machine by name or uuid', startCmd, 0],
910
961
            'host':['Show host information', hostCmd, 0],
911
962
            'guest':['Execute command for guest: guest Win32 \'console.mouse.putMouseEvent(20, 20, 0, 0)\'', guestCmd, 0],
912
963
            'monitorGuest':['Monitor what happens with the guest for some time: monitorGuest Win32 10', monitorGuestCmd, 0],
913
 
            'monitorVbox':['Monitor what happens with Virtual Box for some time: monitorVbox 10', monitorVboxCmd, 0],
 
964
            'monitorVBox':['Monitor what happens with Virtual Box for some time: monitorVBox 10', monitorVBoxCmd, 0],
914
965
            'portForward':['Setup permanent port forwarding for a VM, takes adapter number host port and guest port: portForward Win32 0 8080 80', portForwardCmd, 0],
915
966
            'showLog':['Show log file of the VM, : showLog Win32', showLogCmd, 0],
916
967
            'reloadExt':['Reload custom extensions: reloadExt', reloadExtCmd, 0],
917
968
            'runScript':['Run VBox script: runScript script.vbox', runScriptCmd, 0],
918
969
            'sleep':['Sleep for specified number of seconds: sleep 3.14159', sleepCmd, 0],
919
 
            'shell':['Execute external shell command: shell "ls /etc/rc*"', shellCmd, 0]
 
970
            'shell':['Execute external shell command: shell "ls /etc/rc*"', shellCmd, 0],
 
971
            'exportVm':['Export VM in OVF format: export Win /tmp/win.ovf', exportVMCmd, 0]
920
972
            }
921
973
 
922
974
def runCommandArgs(ctx, args):
948
1000
#    'test': ['Test help', runTestCmd]
949
1001
# }
950
1002
# and issue reloadExt shell command.
951
 
# This file also will be read automatically on startup.
 
1003
# This file also will be read automatically on startup or 'reloadExt'.
952
1004
#
953
 
def checkUserExtensions(ctx, cmds, folder):
954
 
    name =  os.path.join(str(folder), "shellext.py")
955
 
    if not os.path.isfile(name):
 
1005
# Also one can put shell extensions into ~/.VirtualBox/shexts and
 
1006
# they will also be picked up, so this way one can exchange
 
1007
# shell extensions easily.
 
1008
def addExtsFromFile(ctx, cmds, file):
 
1009
    if not os.path.isfile(file):
956
1010
        return
957
1011
    d = {}
958
1012
    try:
959
 
        execfile(name, d, d)
 
1013
        execfile(file, d, d)
960
1014
        for (k,v) in d['commands'].items():
961
1015
            if g_verbose:
962
1016
                print "customize: adding \"%s\" - %s" %(k, v[0])
963
 
            cmds[k] = [v[0], v[1], 1]
 
1017
            cmds[k] = [v[0], v[1], file]
964
1018
    except:
965
 
        print "Error loading user extensions:"
 
1019
        print "Error loading user extensions from %s" %(file)
966
1020
        traceback.print_exc()
967
1021
 
 
1022
 
 
1023
def checkUserExtensions(ctx, cmds, folder):
 
1024
    folder = str(folder)
 
1025
    name = os.path.join(folder, "shellext.py")
 
1026
    addExtsFromFile(ctx, cmds, name)
 
1027
    # also check 'exts' directory for all files
 
1028
    shextdir = os.path.join(folder, "shexts")
 
1029
    if not os.path.isdir(shextdir):
 
1030
        return
 
1031
    exts = os.listdir(shextdir)
 
1032
    for e in exts:
 
1033
        addExtsFromFile(ctx, cmds, os.path.join(shextdir,e))
 
1034
 
 
1035
def getHomeFolder(ctx):
 
1036
    if ctx['remote'] or ctx['vb'] is None:
 
1037
        return os.path.join(os.path.expanduser("~"), ".VirtualBox")
 
1038
    else:
 
1039
        return ctx['vb'].homeFolder
 
1040
 
968
1041
def interpret(ctx):
969
1042
    if ctx['remote']:
970
1043
        commands['connect'] = ["Connect to remote VBox instance", connectCmd, 0]
974
1047
 
975
1048
    if vbox is not None:
976
1049
        print "Running VirtualBox version %s" %(vbox.version)
977
 
        ctx['perf'] = ctx['global'].getPerfCollector(ctx['vb'])
978
 
        home = vbox.homeFolder
 
1050
        ctx['perf'] = ctx['global'].getPerfCollector(vbox)
979
1051
    else:
980
1052
        ctx['perf'] = None
981
 
        home = os.path.join(os.path.expanduser("~"), ".VirtualBox")
982
1053
 
 
1054
    home = getHomeFolder(ctx)
983
1055
    checkUserExtensions(ctx, commands, home)
984
1056
 
985
1057
    autoCompletion(commands, ctx)
1048
1120
           'type':g_virtualBoxManager.type,
1049
1121
           'run': lambda cmd,args: runCommandCb(ctx, cmd, args),
1050
1122
           'machById': lambda id: machById(ctx,id),
 
1123
           'progressBar': lambda p: progressBar(ctx,p),
 
1124
           'progressBar': lambda p: progressBar(ctx,p),
1051
1125
           '_machlist':None
1052
1126
           }
1053
1127
    interpret(ctx)