예제 #1
0
class Provider(BaseProvider):

    name = "virtualbox"
    parameters = []

    style = None

    def __init__(self, config):
        self.globl = None

    @classmethod
    def get_defaults(cls):
        try:
            from vboxapi import VirtualBoxManager
        except ImportError:
            return {}

        return {
            "vbox": {
                "name": "vbox",
                "type": "virtualbox",
            }
        }

    def provide(self, machine):
        if not self.globl:
            self.connect()

        lookfor = machine["name"]

        machines = self.globl.getArray(self.vb, 'machines')
        for m in machines:
            if m.name == lookfor or m.id == lookfor:
                return VirtualMachine(machine, self, m)

        # FIXME: Would be nice to support this in future...
        #for m in machines:
        #    if m.name == machine["base"] or m.id == machine["base"]:
        #        base = VirtualMachine(self, {"name": machine["base"]})
        #        break
        #else:
        #    raise SidekickError("Unable to find base '%s'" % machine['base'])

        vmdir = os.path.join(
            os.environ.get('XDG_DATA_HOME',
                           os.path.expanduser('~/.local/share')), "sidekick",
            "vbox")
        vmpath = os.path.join(vmdir, machine["name"],
                              "%s.box" % machine["name"])
        vdipath = os.path.join(vmdir, machine["name"],
                               "%s.vdi" % machine["name"])

        if not os.path.exists(vdipath):
            base_path = ImageRegistry().get_image(machine['base'])

            if os.path.isdir(base_path):
                vdis = glob.glob(os.path.join(base_path, "*.vdi"))

                if not vdis:
                    raise SidekickError("%s is not a valid base image" %
                                        machine['base'])

                base_path = vdis[0]

            base = self.vb.openMedium(base_path,
                                      self.const.DeviceType_HardDisk,
                                      self.const.AccessMode_ReadOnly)
            target = self.vb.createHardDisk("vdi", vdipath)
            progress = base.cloneTo(target, self.const.MediumVariant_Standard,
                                    None)
            Progress(self.globl, progress).do()
        else:
            target = self.vb.openMedium(vdipath,
                                        self.const.DeviceType_HardDisk,
                                        self.const.AccessMode_ReadOnly)

        if not os.path.exists(vmpath):
            desired_ostype = machine.get("os-type", "Ubuntu_64")

            matching_ostype = [
                x for x in self.globl.getArray(self.vb, "guestOSTypes")
                if x.id.lower() == desired_ostype.lower()
            ]
            if len(matching_ostype) == 0:
                raise SidekickError("Unable to find OS Type '%s'" %
                                    desired_ostype)

            m = self.vb.createMachine(vmpath, machine['name'],
                                      matching_ostype[0].id, "", False)
            m.addStorageController("IDE Controller", self.const.StorageBus_IDE)
            m.saveSettings()
            self.vb.registerMachine(m)

            with Session(self.globl, m) as s:
                s.machine.attachDevice("IDE Controller", 0, 0,
                                       self.const.DeviceType_HardDisk, target)
                s.machine.saveSettings()
        else:
            print "opening"
            m = self.vb.openMachine(vmpath)
            self.vb.registerMachine(m)

        return VirtualMachine(machine, self, m)

    def connect(self):
        cwd = os.getcwd()
        vbp = os.environ.get("VBOX_PROGRAM_PATH")
        if not vbp:
            if os.path.isfile(os.path.join(cwd, "VirtualBox")):
                vbp = cwd
            if os.path.isfile(os.path.join(cwd, "VirtualBox.exe")):
                vbp = cwd
            if vbp:
                os.environ["VBOX_PROGRAM_PATH"] = vbp
                sys.path.append(os.path.join(vbp, "sdk", "installer"))

        from vboxapi import VirtualBoxManager

        self.globl = VirtualBoxManager(self.style, None)
        self.mgr = self.globl.mgr
        self.vb = self.globl.vbox
        self.const = self.globl.constants
        self.remote = self.globl.remote
        self.type = self.globl.type

    def disconnect(self):
        self.mgr = None
        self.vb = None
        self.ifaces = None
        self.remote = None
        self.type = None

        if self.globl:
            self.globl.deinit()
            self.globl = None
예제 #2
0
def main(argv):

    #
    # Parse command line arguments.
    #
    parse = OptionParser()
    parse.add_option("-v",
                     "--verbose",
                     dest="verbose",
                     action="store_true",
                     default=False,
                     help="switch on verbose")
    parse.add_option("-a",
                     "--autopath",
                     dest="autopath",
                     action="store_true",
                     default=False,
                     help="switch on autopath")
    parse.add_option("-w",
                     "--webservice",
                     dest="style",
                     action="store_const",
                     const="WEBSERVICE",
                     help="connect to webservice")
    parse.add_option("-b",
                     "--batch",
                     dest="batch_file",
                     help="script file to execute")
    parse.add_option("-c",
                     dest="command_line",
                     help="command sequence to execute")
    parse.add_option("-o", dest="opt_line", help="option line")
    global g_fVerbose, g_sScriptFile, g_fBatchMode, g_fHasColors, g_fHasReadline, g_sCmd
    (options, args) = parse.parse_args()
    g_fVerbose = options.verbose
    style = options.style
    if options.batch_file is not None:
        g_fBatchMode = True
        g_fHasColors = False
        g_fHasReadline = False
        g_sScriptFile = options.batch_file
    if options.command_line is not None:
        g_fHasColors = False
        g_fHasReadline = False
        g_sCmd = options.command_line

    params = None
    if options.opt_line is not None:
        params = {}
        strparams = options.opt_line
        strparamlist = strparams.split(',')
        for strparam in strparamlist:
            (key, value) = strparam.split('=')
            params[key] = value

    if options.autopath:
        asLocations = [
            os.getcwd(),
        ]
        try:
            sScriptDir = os.path.dirname(os.path.abspath(__file__))
        except:
            pass  # In case __file__ isn't there.
        else:
            if platform.system() in [
                    'SunOS',
            ]:
                asLocations.append(os.path.join(sScriptDir, 'amd64'))
            asLocations.append(sScriptDir)

        sPath = os.environ.get("VBOX_PROGRAM_PATH")
        if sPath is None:
            for sCurLoc in asLocations:
                if   os.path.isfile(os.path.join(sCurLoc, "VirtualBox")) \
                  or os.path.isfile(os.path.join(sCurLoc, "VirtualBox.exe")):
                    print("Autodetected VBOX_PROGRAM_PATH as", sCurLoc)
                    os.environ["VBOX_PROGRAM_PATH"] = sCurLoc
                    sPath = sCurLoc
                    break
        if sPath:
            sys.path.append(os.path.join(sPath, "sdk", "installer"))

        sPath = os.environ.get("VBOX_SDK_PATH")
        if sPath is None:
            for sCurLoc in asLocations:
                if os.path.isfile(
                        os.path.join(sCurLoc, "sdk", "bindings",
                                     "VirtualBox.xidl")):
                    sCurLoc = os.path.join(sCurLoc, "sdk")
                    print("Autodetected VBOX_SDK_PATH as", sCurLoc)
                    os.environ["VBOX_SDK_PATH"] = sCurLoc
                    sPath = sCurLoc
                    break
        if sPath:
            sCurLoc = sPath
            sTmp = os.path.join(sCurLoc, 'bindings', 'xpcom', 'python')
            if os.path.isdir(sTmp):
                sys.path.append(sTmp)
            del sTmp
        del sPath, asLocations

    #
    # Set up the shell interpreter context and start working.
    #
    from vboxapi import VirtualBoxManager
    oVBoxMgr = VirtualBoxManager(style, params)
    ctx = {
        'global': oVBoxMgr,
        'vb': oVBoxMgr.getVirtualBox(),
        'const': oVBoxMgr.constants,
        'remote': oVBoxMgr.remote,
        'type': oVBoxMgr.type,
        'run': lambda cmd, args: runCommandCb(ctx, cmd, args),
        'machById': lambda uuid: machById(ctx, uuid),
        'argsToMach': lambda args: argsToMach(ctx, args),
        'progressBar': lambda p: progressBar(ctx, p),
        '_machlist': None,
        'prompt': g_sPrompt,
        'scriptLine': 0,
        'interrupt': False,
    }
    interpret(ctx)

    #
    # Release the interfaces references in ctx before cleaning up.
    #
    for sKey in list(ctx.keys()):
        del ctx[sKey]
    ctx = None
    gc.collect()

    oVBoxMgr.deinit()
    del oVBoxMgr
예제 #3
0
class Provider(BaseProvider):

    name = "virtualbox"
    parameters = [
    ]

    style = None

    def __init__(self, config):
        self.globl = None

    @classmethod
    def get_defaults(cls):
        try:
            from vboxapi import VirtualBoxManager
        except ImportError:
            return {}

        return {
            "vbox": {
                "name": "vbox",
                "type": "virtualbox",
                }
            }

    def provide(self, machine):
        if not self.globl:
            self.connect()

        lookfor = machine["name"]

        machines = self.globl.getArray(self.vb, 'machines')
        for m in machines:
            if m.name == lookfor or m.id == lookfor:
                return VirtualMachine(machine, self, m)

        # FIXME: Would be nice to support this in future...
        #for m in machines:
        #    if m.name == machine["base"] or m.id == machine["base"]:
        #        base = VirtualMachine(self, {"name": machine["base"]})
        #        break
        #else:
        #    raise SidekickError("Unable to find base '%s'" % machine['base'])

        vmdir = os.path.join(os.environ.get('XDG_DATA_HOME', os.path.expanduser('~/.local/share')), "sidekick", "vbox")
        vmpath = os.path.join(vmdir, machine["name"], "%s.box" % machine["name"])
        vdipath = os.path.join(vmdir,  machine["name"], "%s.vdi" % machine["name"])

        if not os.path.exists(vdipath):
            base_path = ImageRegistry().get_image(machine['base'])

            if os.path.isdir(base_path):
                vdis = glob.glob(os.path.join(base_path, "*.vdi"))

                if not vdis:
                    raise SidekickError("%s is not a valid base image" % machine['base'])

                base_path = vdis[0]

            base = self.vb.openMedium(base_path, self.const.DeviceType_HardDisk, self.const.AccessMode_ReadOnly)
            target = self.vb.createHardDisk("vdi", vdipath)
            progress = base.cloneTo(target, self.const.MediumVariant_Standard, None)
            Progress(self.globl, progress).do()
        else:
            target = self.vb.openMedium(vdipath, self.const.DeviceType_HardDisk, self.const.AccessMode_ReadOnly)

        if not os.path.exists(vmpath):
            desired_ostype = machine.get("os-type", "Ubuntu_64")

            matching_ostype = [x for x in self.globl.getArray(self.vb, "guestOSTypes") if x.id.lower() == desired_ostype.lower()]
            if len(matching_ostype) == 0:
                raise SidekickError("Unable to find OS Type '%s'" % desired_ostype)

            m = self.vb.createMachine(vmpath, machine['name'], matching_ostype[0].id, "", False)
            m.addStorageController("IDE Controller", self.const.StorageBus_IDE)
            m.saveSettings()
            self.vb.registerMachine(m)

            with Session(self.globl, m) as s:
                s.machine.attachDevice("IDE Controller", 0, 0,  self.const.DeviceType_HardDisk, target)
                s.machine.saveSettings()
        else:
            print "opening"
            m = self.vb.openMachine(vmpath)
            self.vb.registerMachine(m)

        return VirtualMachine(machine, self, m)

    def connect(self):
        cwd = os.getcwd()
        vbp = os.environ.get("VBOX_PROGRAM_PATH")
        if not vbp:
            if os.path.isfile(os.path.join(cwd, "VirtualBox")):
                vbp = cwd
            if os.path.isfile(os.path.join(cwd, "VirtualBox.exe")):
                vbp = cwd
            if vbp:
                os.environ["VBOX_PROGRAM_PATH"] = vbp
                sys.path.append(os.path.join(vbp, "sdk", "installer"))

        from vboxapi import VirtualBoxManager

        self.globl = VirtualBoxManager(self.style, None)
        self.mgr = self.globl.mgr
        self.vb = self.globl.vbox
        self.const = self.globl.constants
        self.remote = self.globl.remote
        self.type = self.globl.type

    def disconnect(self):
        self.mgr = None
        self.vb = None
        self.ifaces = None
        self.remote = None
        self.type = None

        if self.globl:
            self.globl.deinit()
            self.globl = None