Example #1
0
    def find(self, args):
        """ Find a virtual machine given its name. """
        # Parse user input to get the name of the virtual machine
        parser = OptionParser(usage="vm find <options>")
        parser.add_option("-n", "--name", dest="name", help="The name of the virtual machine to find")
        parser.add_option(
            "-v", "--verbose", dest="verbose", action="store_true", help="Show virtual machine extended information"
        )
        (options, args) = parser.parse_args(args)
        name = options.name
        if not name:
            parser.print_help()
            return

        # Once user input has been read, find the virtual machine
        context = ContextLoader().load()
        try:
            cloud = context.getCloudService()
            vm = cloud.findVirtualMachine(VirtualMachinePredicates.name(name))
            if vm:
                pprint_vms([vm], options.verbose)
            else:
                print "No virtual machine found with name: %s" % name
        except (AbiquoException, AuthorizationException), ex:
            print "Error: %s" % ex.getMessage()
Example #2
0
    def deploy(self, args):
        """ Deploy an existing virtual machine given its name. """
        # Parse user input to get the name of the virtual machine
        parser = OptionParser(usage="vm deploy <options>")
        parser.add_option("-n", "--name", help="The name of the virtual machine to deploy",
                action="store", dest="name")
        (options, args) = parser.parse_args(args)
        name = options.name
        if not name:
            parser.print_help()
            return

        # Once user input has been read, find the VM
        context = ContextLoader().load_context()
        try:
            cloud = context.getCloudService()
            monitor = context.getMonitoringService().getVirtualMachineMonitor()
            vm = cloud.findVirtualMachine(VirtualMachinePredicates.name(name))
            if vm:
                print "Deploying virtual machine %s... This may take some time." % name
                vm.deploy()
                monitor.awaitCompletionDeploy(vm)
            else:
                print "No virtual machine found with name: %s" % name
        except (AbiquoException, AuthorizationException), ex:
            print "Error: %s" % ex.getMessage()
Example #3
0
    def deleteMachine(self, args):
        """ Remove a physical machine from abiquo. """
        parser = OptionParser(usage="machine delete <options>")
        parser.add_option("-n","--name",help="the name of the physical machine",action="store",dest="name")
        parser.add_option("-i","--host",help="the ip of the physical machine",action="store",dest="host")
        (options, args) = parser.parse_args(args)
        name = options.name
        host = options.host

        if not name and not host:
            parser.print_help()
            return

        context = ContextLoader().load()
        try:
            admin =  context.getAdministrationService()
            if name:
                machine = admin.findMachine(MachinePredicates.name(name))
            else:
                machine = admin.findMachine(MachinePredicates.ip(host))
            if not machine:
                print "Machine not found"
                return
            name=machine.getName()
            machine.delete()
            log.debug("Machine %s deleted succesfully" % name)

        except (AbiquoException, AuthorizationException), ex:
            print "Error %s" % ex.getMessage()
Example #4
0
    def find(self, args):
        """ Find a template given its name. """
        # Parse user input to get the name of the template
        parser = OptionParser(usage="template find <options>")
        parser.add_option("-n", "--name", help="The name of the template to find",
                action="store", dest="name")
        (options, args) = parser.parse_args(args)
        name = options.name
        if not name:
            parser.print_help()
            return

        # Once user input has been read, find the template 
        context = ContextLoader().load_context()
        try:
            admin = context.getAdministrationService()
            user = admin.getCurrentUserInfo()
            enterprise = user.getEnterprise()
            template = enterprise.findTemplate(VirtualMachineTemplatePredicates.name(name))
            if template:
                pprint_templates([template])
            else:
                print "No template found with name: %s" % name
        except (AbiquoException, AuthorizationException), ex:
            print "Error: %s" % ex.getMessage()
Example #5
0
    def delete(self, args):
        """ Delete a virtual machine given its name. """
        # Parse user input to get the name of the virtual machine
        parser = OptionParser(usage="vm delete <options>")
        parser.add_option("-n", "--name", dest="name", help="The name of the virtual machine to delete")
        parser.add_option(
            "-u",
            "--undeploy",
            dest="undeploy",
            action="store_true",
            help="undeploy the virtual machine before deleting it",
        )
        (options, args) = parser.parse_args(args)
        name = options.name
        if not name:
            parser.print_help()
            return

        context = ContextLoader().load()
        try:
            cloud = context.getCloudService()
            vm = cloud.findVirtualMachine(VirtualMachinePredicates.name(name))
            if vm:
                state = vm.getState()
                if not options.undeploy and state.existsInHypervisor():
                    print ("Virtual machine is deployed. " "Undeploy it before deleting.")
                elif options.undeploy and state.existsInHypervisor():
                    vm = helper.undeploy_vm(context, vm)
                    vm.delete()
                else:
                    vm.delete()
            else:
                print "No virtual machine found with name: %s" % name
        except (AbiquoException, AuthorizationException), ex:
            print "Error: %s" % ex.getMessage()
Example #6
0
    def checkMachines(self, args):
        """ Check state from physical machine. """
        parser = OptionParser(usage="machine check <options>")
        parser.add_option("-n","--name",help="the name of the physical machine",action="store",dest="name")
        parser.add_option("-i","--host",help="the ip of the physical machine",action="store",dest="host")
        parser.add_option("-a","--all",help="check all machines",action="store_true",dest="a")
        (options, args) = parser.parse_args(args)
        all_true = options.a
        name = options.name
        host = options.host

        if not name and not host and not all_true:
            parser.print_help()
            return

        context = ContextLoader().load()
        try:
            admin =  context.getAdministrationService()
            if all_true:
                machines = admin.listMachines()
                log.debug("%s machines found." % str(len(machines)))
                [self._checkMachine for machine in machines]
                pprint_machines(machines)
            else:
                if name:
                    machine = admin.findMachine(MachinePredicates.name(name))
                else:
                    machine = admin.findMachine(MachinePredicates.ip(host))
                self._checkMachine(machine)
                pprint_machines([machine]);
        except (AbiquoException, AuthorizationException), ex:
            print "Error %s" % ex.getMessage()
Example #7
0
    def createMachine(self, args):
        """ Create a physical machine in abiquo. This method uses configurable constats for default values."""
        parser = OptionParser(usage="machine create --host <host> <options>")

        # create options
        parser.add_option("-i","--host",
                help="ip or hostname from machine to create in abiquo [required]",action="store",dest="host")
        parser.add_option("-u","--user",help="user to loggin in the machine",action="store",dest="user")
        parser.add_option("-p","--psswd",help="password to loggin in the machine",action="store",dest="psswd")
        # parser.add_option("-c","--port",help="port from machine",action="store",dest="port")
        parser.add_option("-t","--type",help="hypervisor type of the machine",action="store",dest="hypervisor")
        parser.add_option("-r","--rsip",help="ip from remote services",action="store",dest="remoteservicesip")
        parser.add_option("-d","--datastore",
                help="datastore to enable on physical machine",action="store",dest="datastore")
        parser.add_option("-s","--vswitch",
                help="virtual switch to select on physical machine",action="store",dest="vswitch")
        (options, args) = parser.parse_args(args)
        
        # parse options
        host = options.host
        if not host:
            parser.print_help()
            return


        user = self._getConfig(options,host,"user")
        psswd = self._getConfig(options,host,"psswd")
        rsip = self._getConfig(options,host,"remoteservicesip")
        dsname = self._getConfig(options,host,"datastore")
        vswitch =  self._getConfig(options,host,"vswitch")
        hypervisor = options.hypervisor

        context = ContextLoader().load()
        try:
            admin = context.getAdministrationService()

            # search or create datacenter
            log.debug("Searching for the datacenter 'kahuna'.")
            dc = admin.findDatacenter(DatacenterPredicates.name('kahuna'))
            if not dc:
                log.debug("No datacenter 'kahuna' found.")
                dc = Datacenter.builder(context) \
                        .name('kahuna') \
                        .location('terrassa') \
                        .remoteServices(rsip,AbiquoEdition.ENTERPRISE) \
                        .build()
                try:
                    dc.save()
                except (AbiquoException), ex:
                    if ex.hasError("RS-3"):
                        print "ip %s to create remote services has been used yet, try with another one" % rsip
                        dc.delete()
                        return
                    else:
                        raise ex
                rack = Rack.builder(context,dc).name('rack').build()
                rack.save()
                log.debug("New datacenter 'kahuna' created.")
            else:
Example #8
0
    def _load_context(self):
        """ Set the context of the execution.

        It should be called only from the plugin manager once
        it has the context loaded.
        """
        log.debug("Loading context for plugin execution")
        self._context = ContextLoader(self._config_overrides()).load()
Example #9
0
 def list(self, args):
     """ List physical machines from abiquo """
     context = ContextLoader().load()
     try:
         admin = context.getAdministrationService()
         machines = admin.listMachines()
         pprint_machines(machines)
     except (AbiquoException, AuthorizationException), ex:
         print "Error %s" % ex.getMessage()
Example #10
0
 def list(self, args):
     """ List all virtual machines. """
     context = ContextLoader().load_context()
     try:
         cloud = context.getCloudService()
         vms = cloud.listVirtualMachines()
         pprint_vms(vms)
     except (AbiquoException, AuthorizationException), ex:
         print "Error: %s" % ex.getMessage()
Example #11
0
def opencontext(plugin):
    """ Loads the context each plugin needs to be initialized
    in order to be executed """
    log.debug("Loading context for plugin execution")
    context = ContextLoader(plugin._config_overrides()).load()
    plugin._load_context(context)
    yield
    log.debug("Context closed after plugin execution")
    context.close()
Example #12
0
 def list(self, args):
     """ List all available virtual datacenters. """
     context = ContextLoader().load()
     try:
         cloud = context.getCloudService()
         vdcs = cloud.listVirtualDatacenters()
         pprint_vdcs(vdcs)
     except (AbiquoException, AuthorizationException), ex:
         print "Error: %s" % ex.getMessage()
 def list(self, args):
     """ List physical machines from abiquo """
     context = ContextLoader().load()
     try:
         admin = context.getAdministrationService()
         machines = admin.listMachines()
         pprint_machines(machines)
     except (AbiquoException, AuthorizationException), ex:
         print "Error %s" % ex.getMessage()
Example #14
0
 def list(self, args):
     """ List all available templates. """
     context = ContextLoader().load_context()
     try:
         admin = context.getAdministrationService()
         user = admin.getCurrentUserInfo()
         enterprise = user.getEnterprise()
         templates = enterprise.listTemplates()
         pprint_templates(templates)
     except (AbiquoException, AuthorizationException), ex:
         print "Error: %s" % ex.getMessage()
Example #15
0
 def list(self, args):
     """ List all available volumes. """
     context = ContextLoader().load()
     try:
         cloud = context.getCloudService()
         vdcs = cloud.listVirtualDatacenters()
         volumes = []
         [volumes.extend(vdc.listVolumes()) for vdc in vdcs]
         pprint_volumes(volumes)
     except (AbiquoException, AuthorizationException), ex:
         print "Error: %s" % ex.getMessage()
Example #16
0
    def create(self, args):
        """ Creates a virtual machine based on a given template. """
        # Parse user input to get the name of the virtual machine
        parser = OptionParser(usage="vm create <options>")
        parser.add_option("-t", "--template-id", dest="template", type="int", help="The id of the template to use")
        parser.add_option("-c", "--cpu", dest="cpu", type="int", help="The number of cores")
        parser.add_option("-r", "--ram", dest="ram", type="int", help="The RAM in MB")
        parser.add_option(
            "-d", "--deploy", dest="deploy", action="store_true", help="Deploy the virtual machine after creating it"
        )
        (options, args) = parser.parse_args(args)
        if not options.template:
            parser.print_help()
            return

        context = ContextLoader().load()
        try:
            template = helper.find_template_by_id(context, options.template)
            if not template:
                print "No template was found with id %s" % options.template
                return
            log.debug("Using template: %s" % template.getName())

            vdc = helper.get_virtual_datacenter_for_template(context, template)
            if not vdc:
                print ("Could not create a compatible virtual datacenter " "for %s") % template.getName()
                return
            log.debug("Using virtual datacenter: %s" % vdc.getName())

            name = "Kahuna-" + context.getIdentity()
            vapp = vdc.findVirtualAppliance(VirtualAppliancePredicates.name(name))
            if not vapp:
                log.debug(("Virtual appliance %s not found. " "Creating it...") % name)
                vapp = VirtualAppliance.builder(context, vdc).name(name).build()
                vapp.save()

            builder = VirtualMachine.builder(context, vapp, template)
            if options.cpu:
                builder.cpu(options.cpu)
            if options.ram:
                builder.ram(options.ram)
            vm = builder.build()
            vm.save()

            if options.deploy:
                vm = helper.deploy_vm(context, vm)

            pprint_vms([vm])
        except (AbiquoException, AuthorizationException), ex:
            print "Error: %s" % ex.getMessage()
Example #17
0
    def start(self, args):
        """ Deploys and undeploys the first virtual appliance N times. """
        # Parse user input to get the number of deployments and undeployments
        parser = OptionParser(usage="deployer start <options>")
        parser.add_option("-n", "--num", dest="num",
                help="The number of deployments to execute")
        (options, args) = parser.parse_args(args)
        if not options.num:
            parser.print_help()
            return

        # Once user input has been read, find the VM
        max = int(options.num)
        context = ContextLoader().load()
        try:
            cloud = context.getCloudService()
            monitor = context.getMonitoringService() \
                    .getVirtualApplianceMonitor()

            vdc = cloud.listVirtualDatacenters()[0]
            vapp = vdc.listVirtualAppliances()[0]
            num_vms = len(vapp.listVirtualMachines())

            print "Starting %s deployment iterations for %s (%s vms)" % (max,
                    vapp.getName(), num_vms)

            for i in range(0, max):
                print "Iteration #%s" % (i + 1)
                print "  Deploying %s (%s vms)" % (vapp.getName(), num_vms)
                vapp.deploy()
                monitor.awaitCompletionDeploy(vapp)

                # Bypass current issues with state by waiting a bit
                # before undeploying
                time.sleep(5)

                print "  Undeploying %s (%s vms)" % (vapp.getName(), num_vms)
                vapp.undeploy()
                monitor.awaitCompletionUndeploy(vapp)

                # Currently there is a minor issue when undeploying that puts
                # the vm in state UNKNOWN. Wait a bit so it gets in
                # NOT_ALLOCATED state before deploying again
                time.sleep(5)
        except (AbiquoException, AuthorizationException), ex:
            print "Error: %s" % ex.getMessage()
Example #18
0
class AbsPlugin:
    """ Abstract plugin """
    def __init__(self):
        """ Initialized basic plugin stuff. """
        self._context = None

    def _commands(self):
        """ Get the list of commands for the current plugin.
        By default all public methods in the plugin implementation
        will be used as plugin commands. This method can be overriden
        in subclasses to customize the available command list """
        attrs = filter(lambda attr: not attr.startswith('_'), dir(self))
        commands = {}
        for attr in attrs:
            method = getattr(self, attr)
            commands[attr] = method
        return commands

    def _config_overrides(self):
        """ Custom properties to override default configuration """
        return {}

    def _load_context(self):
        """ Set the context of the execution.

        It should be called only from the plugin manager once
        it has the context loaded.
        """
        log.debug("Loading context for plugin execution")
        self._context = ContextLoader(self._config_overrides()).load()

    def _close_context(self):
        """ Closes the context after plugin execution.

        It should be called only from the plugin manager.
        """
        if self._context:
            log.debug("Context closed after plugin execution")
            self._context.close()
            self._context = None
Example #19
0
File: vm.py Project: rubiojr/kahuna
    def create(self, args):
        """ Creates a virtual machine based on a given template. """
        # Parse user input to get the name of the virtual machine
        parser = OptionParser(usage="vm create <options>")
        parser.add_option("-t", "--template-id", help="The id of the template to use",
                type="int", action="store", dest="template")
        (options, args) = parser.parse_args(args)
        if not options.template:
            parser.print_help()
            return

        context = ContextLoader().load_context()
        try:
            template = helper.find_template_by_id(context, options.template)
            if not template:
                print "No template was found with id %s" % options.template
                return
            log.debug("Using template: %s" % template.getName())

            vdc = helper.find_compatible_virtual_datacenter(context, template)
            if not vdc:
                print "No virtual datacenter found for: %s" % template.getDiskFormatType()
                return
            log.debug("Using virtual datacenter: %s" % vdc.getName())

            name = "Kahuna-" + context.getIdentity()
            vapp = vdc.findVirtualAppliance(VirtualAppliancePredicates.name(name))
            if not vapp:
                log.debug("Virtual appliance %s not found. Creating it..." % name)
                vapp = VirtualAppliance.builder(context, vdc).name(name).build()
                vapp.save()

            vm = VirtualMachine.builder(context, vapp, template).build()
            vm.save()

            pprint_vms([vm])
        except (AbiquoException, AuthorizationException), ex:
            print "Error: %s" % ex.getMessage()
Example #20
0
    def deploy(self, args):
        """ Deploy an existing virtual machine given its name. """
        # Parse user input to get the name of the virtual machine
        parser = OptionParser(usage="vm deploy <options>")
        parser.add_option("-n", "--name", dest="name", help="The name of the virtual machine to deploy")
        (options, args) = parser.parse_args(args)
        name = options.name
        if not name:
            parser.print_help()
            return

        # Once user input has been read, find the VM
        context = ContextLoader().load()
        try:
            cloud = context.getCloudService()
            vm = cloud.findVirtualMachine(VirtualMachinePredicates.name(name))
            if vm:
                vm = helper.deploy_vm(context, vm)
                pprint_vms([vm])
            else:
                print "No virtual machine found with name: %s" % name
        except (AbiquoException, AuthorizationException), ex:
            print "Error: %s" % ex.getMessage()
Example #21
0
    def find(self, args):
        """ Find a virtual datacenter given its name. """
        # Parse user input to get the name of the virtual datacenter
        parser = OptionParser(usage="vdc find <options>")
        parser.add_option("-n", "--name",
                help="The name of the virtual datacenter to find", dest="name")
        (options, args) = parser.parse_args(args)
        name = options.name
        if not name:
            parser.print_help()
            return

        # Once user input has been read, find the virtual datacenter
        context = ContextLoader().load()
        try:
            cloud = context.getCloudService()
            vdc = cloud.findVirtualDatacenter(
                    VirtualDatacenterPredicates.name(name))
            if vdc:
                pprint_vdcs([vdc])
            else:
                print "No virtual datacenter found with name: %s" % name
        except (AbiquoException, AuthorizationException), ex:
            print "Error: %s" % ex.getMessage()
Example #22
0
    def find(self, args):
        """ Find a virtual machine given its name. """
        # Parse user input to get the name of the virtual machine
        parser = OptionParser(usage="vm find <options>")
        parser.add_option("-n", "--name", help="The name of the virtual machine to find",
                action="store", dest="name")
        parser.add_option("-v", "--verbose", help="Show virtual machine extended information",
                action="store_true", dest="verbose")
        (options, args) = parser.parse_args(args)
        name = options.name
        if not name:
            parser.print_help()
            return

        # Once user input has been read, find the virtual machine
        context = ContextLoader().load_context()
        try:
            cloud = context.getCloudService()
            vm = cloud.findVirtualMachine(VirtualMachinePredicates.name(name))
            if vm:
                pprint_vms([vm])
                if options.verbose:
                    print "Found virtual machine in: "
                    print "  %s" % vm.getVirtualAppliance()
                    print "  %s" % vm.getVirtualDatacenter()
                    print "  %s" % vm.getEnterprise()
                    if vm.getState().existsInHypervisor():
                        admin = context.getAdministrationService()
                        machine = admin.findMachine(MachinePredicates.ip(vm.getVncAddress()))
                        print "  %s" % machine
                    else:
                        print "  Machine [None (VM not deployed)]"
            else:
                print "No virtual machine found with name: %s" % name
        except (AbiquoException, AuthorizationException), ex:
            print "Error: %s" % ex.getMessage()
Example #23
0
    def attach(self, args):
        """ Attach a volume to the given virtual machine. """
        parser = OptionParser(usage="volume attach <options>")
        parser.add_option("-n", "--name", dest="name",
                help="The name of the volume to attach")
        parser.add_option("-v", "--vm", dest="name",
                help=("The name of the virtual machine "
                "where the volume will be attached"))
        (options, args) = parser.parse_args(args)
        if not options.name or not options.vm:
            parser.print_help()
            return

        context = ContextLoader().load()
        try:
            volume = helper.find_volume(context, options.name)
            if not volume:
                print "No volume found with name: %s" % options.name
                return
            cloud = context.getCloudService()
            vm = cloud.findVirtualMachine(
                    VirtualMachinePredicates.name(options.vm))
            if not vm:
                print "No virtual machine found with name: %s" % options.vm
                return

            log.debug("Attaching volume %s to %s..." % (options.name,
                options.vm))
            if vm.getState().existsInHypervisor():
                print "Attaching volume to a running virtual machine.",
                print "This may take some time..."

            vm.attachVolumes(volume)
            pprint_volumes([helper.refresh_volume(context, volume)])
        except (AbiquoException, AuthorizationException), ex:
            print "Error: %s" % ex.getMessage()