Esempio n. 1
0
    def do(self):
        if self.environments.contains(self.args[0]):
            raise SidekickError("That environment is already registered")

        # FIXME: Generalise this and pull it back down into Command
        args = self.args[2:]
        kwargs = {}
        while args:
            if not '=' in args[0]:
                raise SidekickError("Invalid argument '%s'" % args[0])
            key, value = args.pop(0).split('=', 1)
            kwargs[key] = value

        self.environments.register(self.args[0], self.args[1], kwargs)
Esempio n. 2
0
    def provide(self, machine):
        if not self.handle:
            self.connect()

        vmwaredir = os.path.join(
            os.environ.get('XDG_DATA_HOME',
                           os.path.expanduser('~/.local/share')), "sidekick",
            "vmware")
        vmpath = os.path.join(vmwaredir, machine["name"],
                              "%s.vmx" % machine["name"])

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

            if os.path.isdir(base_path):
                vmxes = glob.glob(os.path.join(base_path, "*.vmx"))

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

                base_path = vmxes[0]

            print "VM doesnt exit - cloning..."
            base = self.open(base_path, {"name": base_path})
            base.clone(vmpath)

        return self.open(vmpath, machine)
Esempio n. 3
0
    def __new__(meta, class_name, bases, attrs):
        cls = type.__new__(meta, class_name, bases, attrs)

        if "name" in attrs:
            if attrs["name"] in meta.providers:
                raise SidekickError("Provider '%s' already defined" %
                                    attrs['name'])

            meta.providers[attrs["name"]] = cls

        return cls
Esempio n. 4
0
 def connect(self):
     self.conntype = low.VIX_SERVICEPROVIDER_VMWARE_WORKSTATION
     try:
         Provider.connect(self)
     except errors.WRAPPER_WORKSTATION_NOT_INSTALLED:
         self.conntype = low.VIX_SERVICEPROVIDER_VMWARE_PLAYER
         try:
             Provider.connect(self)
         except errors.WRAPPER_PLAYER_NOT_INSTALLED:
             raise SidekickError(
                 "Cannot find Vmware Workstation or Player Environment")
Esempio n. 5
0
    def get_current_cluster(self):
        if self.options.cluster:
            return self.get_cluster(self.options.cluster)

        path = ["/"] + list(os.getcwd().split(os.path.sep)) + ["Sidekick"]
        while len(path) > 1 and not os.path.exists(os.path.join(*path)):
            path = path[:-2] + ["Sidekick"]

        if not os.path.exists(os.path.join(*path)):
            raise SidekickError(
                "You did not specify a cluster and there is no Sidekick in cwd to look one up"
            )

        for cluster in self.get_clusters():
            if cluster.config['sidekick-file'] == os.path.join(*path):
                return cluster

        raise SidekickError(
            "You failed to specify a cluster and one could not be found based on cwd."
        )
Esempio n. 6
0
    def register(self, name, type, config):
        if self.contains(name):
            raise SidekickError("'%s' is already defined")

        env = {
            "name": name,
            "type": type,
            }
        env.update(config)

        self.index[name] = env
        self.save()
Esempio n. 7
0
    def __new__(meta, class_name, bases, new_attrs):
        cls = type.__new__(meta, class_name, bases, new_attrs)

        command = new_attrs.get("name", None)
        id = (cls.parent, command)

        if command:
            if id in meta.commands:
                raise SidekickError("Command '%s' was already defined")
            meta.commands[id] = cls

        return cls
Esempio n. 8
0
    def provision(self, backend=None, **kwargs):
        #if not self.is_running():
        #    raise errors.VmNotRunning()

        print "Provisioning vm..."

        p = None
        if backend:
            try:
                p = ProvisionerType.provisioners[backend]
            except KeyError:
                raise SidekickError("There is no such provisioner: '%s'" %
                                    backend)
        else:
            for p in ProvisionerType.provisioners.values():
                if p.can_provision(self):
                    break
            else:
                raise SidekickError("Cannot find a suitable provisioner")

        # Actually do this thing
        p(self).provision(**kwargs)
Esempio n. 9
0
    def power_on(self):
        if self.approaching("running"):
            raise SidekickError("VM Already Running")

        job = Job(
            low.vix.VixVM_PowerOn(self.vm, self.default_powerop_start,
                                  low.VIX_INVALID_HANDLE, None, None))
        job.wait(low.VIX_PROPERTY_NONE)

        mac = self.get_mac()
        for log_mac, ip in util.tail_vmware_dhcp():
            if mac == log_mac:
                self.ip = ip
                return ip
Esempio n. 10
0
    def register(self, name, env, details):
        if self.contains(name):
            raise SidekickError("'%s' is already defined" % name)

        cached_path = os.path.join(self.registry, "%s.yay" % name)
        cached = yay.dump(yay.load_uri(details))
        open(cached_path, "w").write(cached)

        self.index[name] = {
            "name": name,
            "env": env,
            "sidekick-file": details,
            "cached-sidekick-file": cached_path,
            }

        self.save()
Esempio n. 11
0
    def __enter__(self):
        self.session = self.mgr.getSessionObject(self.vb)
        if hasattr(self.machine, "lockMachine"):
            self.machine.lockMachine(self.session, self.const.LockType_Shared)
            desired_session_state = self.const.SessionState_Locked
        else:
            self.vb.openExistingSession(self.session, self.machine.id)
            desired_session_state = self.const.SessionState_Open

        if self.session.state != desired_session_state:
            #self.session.close()
            self.session = None
            raise SidekickError("Session to '%s' in wrong state: %s" %
                                (self.macine.name, self.session.state))

        return self.session
Esempio n. 12
0
    def power_on(self):
        self.logger.debug("Asked to power on")
        powerstate = self.get_powerstate()

        if powerstate == "terminated":
            raise SidekickError("A VM with the name '%s' already exists in a terminated state, cannot perform any operations on it" % self.config['name'])

        if powerstate != "undefined":
            self.logger.debug("Already powered on")
            return

        self.node = self.driver.create_node(
            name=self.config['name'],
            size=self.get_size(),
            image=self.get_image())

        self._wait_for_boot()
        self._assign_ip()
Esempio n. 13
0
    def rollback(self):
        num_snapshots = c_int()
        err = low.vix.VixVM_GetNumRootSnapshots(self.vm, byref(num_snapshots))
        if err != low.VIX_OK:
            raise errors.ErrorType.get(err)

        if num_snapshots.value == 0:
            raise SidekickError("There are no snapshots")

        snapshot = low.VixHandle()

        err = low.vix.VixVM_GetRootSnapshot(self.vm, num_snapshots.value - 1,
                                            byref(snapshot))
        if err != low.VIX_OK:
            raise errors.ErrorType.get(err)

        job = Job(
            low.vix.VixVM_RevertToSnapshot(self.vm, snapshot,
                                           self.default_powerop_start,
                                           low.VIX_INVALID_HANDLE, None, None))
        job.wait(low.VIX_PROPERTY_NONE)

        low.vix.Vix_ReleaseHandle(snapshot)
Esempio n. 14
0
    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)
Esempio n. 15
0
    def do(self):
        if not self.args[0] in self.environments.all():
            raise SidekickError("No such environment '%s'" % self.args[0])

        self.environments.delete(self.args[0])