Example #1
0
 def stopMachineInstance(self, args):
     res = 0
     for name in args.names:
         print(name)
         COMMANDLINELOGGER.info("Stopping machine {0}".format(name))
         try:
             instances = MACHINE_INSTANCE_REGISTRY.getInstances()
             # # Search for the requested instnce
             if name in instances.keys():
                 instances[name].stop()
             else:
                 COMMANDLINELOGGER.error(
                     "MachineInstance instance '{0}' does not exist.".
                     format(name))
             COMMANDLINELOGGER.info(
                 "MachineInstance instance '{0}' successfully stopped.".
                 format(name))
         except Exception as e:
             COMMANDLINELOGGER.error(
                 "Unable to stop machine instance '{0}': {1}.".format(
                     name, str(e)))
             if (not args.verbose):
                 COMMANDLINELOGGER.info(
                     "Run with --verbose flag for more details")
             COMMANDLINELOGGER.debug(traceback.format_exc())
             res = errno.EINVAL
         except (KeyboardInterrupt, SystemExit):
             COMMANDLINELOGGER.debug(traceback.format_exc())
             res = errno.EINVAL
     return res
Example #2
0
    def getMachineInstanceInfos(self, args):
        res = 0
        toDisplay = []
        if (args.names):
            toDisplay.append(args.names)

        instances = MACHINE_INSTANCE_REGISTRY.getInstances()

        if (len(toDisplay) == 0):
            toDisplay = instances.keys()

        for name in toDisplay:
            try:

                # # Search for the requested instnce
                if name in instances.keys():
                    COMMANDLINELOGGER.info(instances[name].getInfos())
                else:
                    COMMANDLINELOGGER.error(
                        "MachineInstance instance '{0}' does not exist.".
                        format(name))
                    res = errno.EINVAL
            except Exception as e:
                COMMANDLINELOGGER.error(
                    "Unable to get informations for machine instance '{0}': '{1}'."
                    .format(name, str(e)))
                if (not args.verbose):
                    COMMANDLINELOGGER.info(
                        "Run with --verbose flag for more details")
                COMMANDLINELOGGER.debug(traceback.format_exc())
                res = errno.EINVAL
            except (KeyboardInterrupt, SystemExit):
                COMMANDLINELOGGER.debug(traceback.format_exc())
                res = errno.EINVAL
        return res
Example #3
0
    def getMachineInstanceInfos(self, args):
        res = 0
        toDisplay = []
        if args.names:
            toDisplay.append(args.names)

        instances = MACHINE_INSTANCE_REGISTRY.getInstances()

        if len(toDisplay) == 0:
            toDisplay = instances.keys()

        for name in toDisplay:
            try:

                # # Search for the requested instnce
                if name in instances.keys():
                    COMMANDLINELOGGER.info(instances[name].getInfos())
                else:
                    COMMANDLINELOGGER.error("MachineInstance instance '{0}' does not exist.".format(name))
                    res = errno.EINVAL
            except Exception as e:
                COMMANDLINELOGGER.error(
                    "Unable to get informations for machine instance '{0}': '{1}'.".format(name, str(e))
                )
                if not args.verbose:
                    COMMANDLINELOGGER.info("Run with --verbose flag for more details")
                COMMANDLINELOGGER.debug(traceback.format_exc())
                res = errno.EINVAL
            except (KeyboardInterrupt, SystemExit):
                COMMANDLINELOGGER.debug(traceback.format_exc())
                res = errno.EINVAL
        return res
Example #4
0
    def destroyMachineInstance(self, args):
        res = 0

        for name in args.names:
            try:
                # Getting instances
                instances = MACHINE_INSTANCE_REGISTRY.getInstances()
                # Check if there is actually an instance named after the request of the user
                if name in instances.keys():
                    # Ask the user if it's ok to delete the machine
                    v = args.force
                    if v == False:
                        v = BinaryQuestion(
                            "Are you sure you want to destroy the machine named {0}. Directory {1}) will be destroyed"
                            .format(instances[name].getName(),
                                    instances[name].getPath()),
                            "Enter a Y or a N", COMMANDLINELOGGER, "Y").ask()
                    if v == True:
                        COMMANDLINELOGGER.info(
                            "Destroying machine instance '{0}'...".format(
                                name))
                        instances[name].destroy()
                        COMMANDLINELOGGER.info(
                            "MachineInstance instance successfully destroyed")
                    else:
                        COMMANDLINELOGGER.info("MachineInstance not destroyed")
                else:
                    COMMANDLINELOGGER.error(
                        "MachineInstance instance '{0}' does not exist.".
                        format(name))
                    res = errno.EINVAL
            except Exception as e:
                COMMANDLINELOGGER.error(
                    "Unable to destroy machine '{0}': {1}".format(
                        name, str(e)))
                if (not args.verbose):
                    COMMANDLINELOGGER.info(
                        "Run with --verbose flag for more details")
                COMMANDLINELOGGER.debug(traceback.format_exc())
                res = errno.EINVAL
            except (KeyboardInterrupt, SystemExit):
                COMMANDLINELOGGER.debug(traceback.format_exc())
                res = errno.EINVAL
        return res
Example #5
0
    def listMachineInstances(self, args):
        COMMANDLINELOGGER.info("Machine instances:")
        COMMANDLINELOGGER.info("-------------------")
        res = 0
        try:
            instances = MACHINE_INSTANCE_REGISTRY.getInstances()
            COMMANDLINELOGGER.debug("Instances loaded.")

            # Create an array to display the available templates
            data = {'name': [], 'path': [], 'started': []}
            for i in instances.values():
                data['name'].append(i.getName())
                data['path'].append(i.getPath())

            # Display the array of templates
            # Check if there is an item in the resulting array using the length of the column name
            if len(data['name']) != 0:
                name_col_width = max(
                    len(word) for word in data['name']) + len("Name") + 2
                path_col_width = max(
                    len(word) for word in data['path']) + len("Path") + 2

                COMMANDLINELOGGER.info("Name".ljust(name_col_width) +
                                       "Path".ljust(path_col_width))
                for row in range(0, len(data['name'])):
                    COMMANDLINELOGGER.info(
                        data['name'][row].ljust(name_col_width) +
                        data['path'][row].ljust(name_col_width))
            else:
                COMMANDLINELOGGER.info("No instances available")
        except Exception as e:
            COMMANDLINELOGGER.error("Unable to list instances: {0}".format(
                str(e)))
            if (not args.verbose):
                COMMANDLINELOGGER.info(
                    "Run with --verbose flag for more details")
            COMMANDLINELOGGER.debug(traceback.format_exc())
            res = errno.EINVAL
        except (KeyboardInterrupt, SystemExit):
            COMMANDLINELOGGER.debug(traceback.format_exc())
            res = errno.EINVAL
        COMMANDLINELOGGER.info("")
        return res
Example #6
0
    def sshIntoMachineInstance(self, args):
        res = 0
        COMMANDLINELOGGER.info("SSH into machine {0}".format(args.name))
        try:
            # # Search for the requested instance in the registry
            instances = MACHINE_INSTANCE_REGISTRY.getInstances()
            if args.name in instances.keys():
                if not instances[args.name].isStarted():
                    COMMANDLINELOGGER.error(
                        "MachineInstance instance '{0}' is not started, starting it before connecting to it."
                        .format(args.name))
                    instances[args.name].start()

                instances[args.name].ssh(args.command)
            else:
                COMMANDLINELOGGER.error(
                    "MachineInstance instance '{0}' does not exist.".format(
                        args.name))
        except Exception as e:
            COMMANDLINELOGGER.error(
                "Unable to SSH into machine instance '{0}': ".format(str(e)))
            if (not args.verbose):
                COMMANDLINELOGGER.info(
                    "Run with --verbose flag for more details")
            COMMANDLINELOGGER.debug(traceback.format_exc())
            res = errno.EINVAL
        except (KeyboardInterrupt, SystemExit):
            COMMANDLINELOGGER.debug(traceback.format_exc())
        return res
Example #7
0
    def sshIntoMachineInstance(self, args):
        res = 0
        COMMANDLINELOGGER.info("SSH into machine {0}".format(args.name))
        try:
            # # Search for the requested instance in the registry
            instances = MACHINE_INSTANCE_REGISTRY.getInstances()
            if args.name in instances.keys():
                if not instances[args.name].isStarted():
                    COMMANDLINELOGGER.error(
                        "MachineInstance instance '{0}' is not started, starting it before connecting to it.".format(
                            args.name
                        )
                    )
                    instances[args.name].start()

                instances[args.name].ssh(args.command)
            else:
                COMMANDLINELOGGER.error("MachineInstance instance '{0}' does not exist.".format(args.name))
        except Exception as e:
            COMMANDLINELOGGER.error("Unable to SSH into machine instance '{0}': ".format(str(e)))
            if not args.verbose:
                COMMANDLINELOGGER.info("Run with --verbose flag for more details")
            COMMANDLINELOGGER.debug(traceback.format_exc())
            res = errno.EINVAL
        except (KeyboardInterrupt, SystemExit):
            COMMANDLINELOGGER.debug(traceback.format_exc())
        return res
Example #8
0
    def destroyMachineInstance(self, args):
        res = 0

        for name in args.names:
            try:
                # Getting instances
                instances = MACHINE_INSTANCE_REGISTRY.getInstances()
                # Check if there is actually an instance named after the request of the user
                if name in instances.keys():
                    # Ask the user if it's ok to delete the machine
                    v = args.force
                    if v == False:
                        v = BinaryQuestion(
                            "Are you sure you want to destroy the machine named {0}. Directory {1}) will be destroyed".format(
                                instances[name].getName(), instances[name].getPath()
                            ),
                            "Enter a Y or a N",
                            COMMANDLINELOGGER,
                            "Y",
                        ).ask()
                    if v == True:
                        COMMANDLINELOGGER.info("Destroying machine instance '{0}'...".format(name))
                        instances[name].destroy()
                        COMMANDLINELOGGER.info("MachineInstance instance successfully destroyed")
                    else:
                        COMMANDLINELOGGER.info("MachineInstance not destroyed")
                else:
                    COMMANDLINELOGGER.error("MachineInstance instance '{0}' does not exist.".format(name))
                    res = errno.EINVAL
            except Exception as e:
                COMMANDLINELOGGER.error("Unable to destroy machine '{0}': {1}".format(name, str(e)))
                if not args.verbose:
                    COMMANDLINELOGGER.info("Run with --verbose flag for more details")
                COMMANDLINELOGGER.debug(traceback.format_exc())
                res = errno.EINVAL
            except (KeyboardInterrupt, SystemExit):
                COMMANDLINELOGGER.debug(traceback.format_exc())
                res = errno.EINVAL
        return res
Example #9
0
    def createMachineInstance(self, args):
        res = 0
        COMMANDLINELOGGER.info(
            "Creating a new machine instance named '{0}' using template '{1}'".format(args.name, args.template)
        )
        # Creating the template and instances registries

        try:
            templates = []
            instances = []
            # Get templates
            templates = MACHINE_TEMPLATE_REGISTRY.getTemplates()
            COMMANDLINELOGGER.debug("Templates loaded.")

            # Get instances
            instances = MACHINE_INSTANCE_REGISTRY.getInstances()
            COMMANDLINELOGGER.debug("Instances loaded.")
            w = MachineInstanceCreationWizard()
            # Check if the instance is already in the registry
            if args.force:
                if args.name in instances.keys():
                    COMMANDLINELOGGER.error(
                        "Machine instance named '{0}' already exists but creation was forced so firstly machination will delete it.".format(
                            args.name
                        )
                    )
                    instances[args.name].destroy()

            if args.force == False and args.name in instances.keys():
                COMMANDLINELOGGER.error(
                    "Unable to create machine: MachineInstance named '{0}' already exists. Change the name of your new machine or delete the existing one.".format(
                        args.name
                    )
                )
                res = errno.EALREADY
            else:
                (template, arch, osversion, provider, provisioner, guestInterfaces, sharedFolders) = w.execute(
                    args, templates
                )
                # Try to create the new machine
                instance = MachineInstance(
                    args.name, template, arch, osversion, provider, provisioner, guestInterfaces, sharedFolders
                )
                instance.create()
                COMMANDLINELOGGER.info("MachineInstance successfully created:")
                instances = MACHINE_INSTANCE_REGISTRY.getInstances()
                COMMANDLINELOGGER.info(instances[args.name].getInfos())

        except (KeyboardInterrupt, SystemExit):
            COMMANDLINELOGGER.debug(traceback.format_exc())
            res = errno.EINVAL
        except Exception as e:
            COMMANDLINELOGGER.error("Unable to create machine instance '{0}': {1}.".format(args.name, str(e)))
            if not args.verbose:
                COMMANDLINELOGGER.info("Run with --verbose flag for more details")
            COMMANDLINELOGGER.debug(traceback.format_exc())
            res = errno.EINVAL

        return res
Example #10
0
    def listMachineInstances(self, args):
        COMMANDLINELOGGER.info("Machine instances:")
        COMMANDLINELOGGER.info("-------------------")
        res = 0
        try:
            instances = MACHINE_INSTANCE_REGISTRY.getInstances()
            COMMANDLINELOGGER.debug("Instances loaded.")

            # Create an array to display the available templates
            data = {"name": [], "path": [], "started": []}
            for i in instances.values():
                data["name"].append(i.getName())
                data["path"].append(i.getPath())

            # Display the array of templates
            # Check if there is an item in the resulting array using the length of the column name
            if len(data["name"]) != 0:
                name_col_width = max(len(word) for word in data["name"]) + len("Name") + 2
                path_col_width = max(len(word) for word in data["path"]) + len("Path") + 2

                COMMANDLINELOGGER.info("Name".ljust(name_col_width) + "Path".ljust(path_col_width))
                for row in range(0, len(data["name"])):
                    COMMANDLINELOGGER.info(
                        data["name"][row].ljust(name_col_width) + data["path"][row].ljust(name_col_width)
                    )
            else:
                COMMANDLINELOGGER.info("No instances available")
        except Exception as e:
            COMMANDLINELOGGER.error("Unable to list instances: {0}".format(str(e)))
            if not args.verbose:
                COMMANDLINELOGGER.info("Run with --verbose flag for more details")
            COMMANDLINELOGGER.debug(traceback.format_exc())
            res = errno.EINVAL
        except (KeyboardInterrupt, SystemExit):
            COMMANDLINELOGGER.debug(traceback.format_exc())
            res = errno.EINVAL
        COMMANDLINELOGGER.info("")
        return res
Example #11
0
 def stopMachineInstance(self, args):
     res = 0
     for name in args.names:
         print(name)
         COMMANDLINELOGGER.info("Stopping machine {0}".format(name))
         try:
             instances = MACHINE_INSTANCE_REGISTRY.getInstances()
             # # Search for the requested instnce
             if name in instances.keys():
                 instances[name].stop()
             else:
                 COMMANDLINELOGGER.error("MachineInstance instance '{0}' does not exist.".format(name))
             COMMANDLINELOGGER.info("MachineInstance instance '{0}' successfully stopped.".format(name))
         except Exception as e:
             COMMANDLINELOGGER.error("Unable to stop machine instance '{0}': {1}.".format(name, str(e)))
             if not args.verbose:
                 COMMANDLINELOGGER.info("Run with --verbose flag for more details")
             COMMANDLINELOGGER.debug(traceback.format_exc())
             res = errno.EINVAL
         except (KeyboardInterrupt, SystemExit):
             COMMANDLINELOGGER.debug(traceback.format_exc())
             res = errno.EINVAL
     return res
Example #12
0
    def createMachineInstance(self, args):
        res = 0
        COMMANDLINELOGGER.info(
            "Creating a new machine instance named '{0}' using template '{1}'".
            format(args.name, args.template))
        # Creating the template and instances registries

        try:
            templates = []
            instances = []
            # Get templates
            templates = MACHINE_TEMPLATE_REGISTRY.getTemplates()
            COMMANDLINELOGGER.debug("Templates loaded.")

            # Get instances
            instances = MACHINE_INSTANCE_REGISTRY.getInstances()
            COMMANDLINELOGGER.debug("Instances loaded.")
            w = MachineInstanceCreationWizard()
            # Check if the instance is already in the registry
            if args.force:
                if args.name in instances.keys():
                    COMMANDLINELOGGER.error(
                        "Machine instance named '{0}' already exists but creation was forced so firstly machination will delete it."
                        .format(args.name))
                    instances[args.name].destroy()

            if args.force == False and args.name in instances.keys():
                COMMANDLINELOGGER.error(
                    "Unable to create machine: MachineInstance named '{0}' already exists. Change the name of your new machine or delete the existing one."
                    .format(args.name))
                res = errno.EALREADY
            else:
                (template, arch, osversion, provider, provisioner,
                 guestInterfaces, sharedFolders) = w.execute(args, templates)
                # Try to create the new machine
                instance = MachineInstance(args.name, template, arch,
                                           osversion, provider, provisioner,
                                           guestInterfaces, sharedFolders)
                instance.create()
                COMMANDLINELOGGER.info("MachineInstance successfully created:")
                instances = MACHINE_INSTANCE_REGISTRY.getInstances()
                COMMANDLINELOGGER.info(instances[args.name].getInfos())

        except (KeyboardInterrupt, SystemExit):
            COMMANDLINELOGGER.debug(traceback.format_exc())
            res = errno.EINVAL
        except Exception as e:
            COMMANDLINELOGGER.error(
                "Unable to create machine instance '{0}': {1}.".format(
                    args.name, str(e)))
            if (not args.verbose):
                COMMANDLINELOGGER.info(
                    "Run with --verbose flag for more details")
            COMMANDLINELOGGER.debug(traceback.format_exc())
            res = errno.EINVAL

        return res
Example #13
0
    def listMachineTemplates(self, args):
        res = 0
        # Create the template registry that will list all available template on the machine
        COMMANDLINELOGGER.info("Machine templates:")
        COMMANDLINELOGGER.info("-------------------")

        try:
            templates = MACHINE_TEMPLATE_REGISTRY.getTemplates()
            COMMANDLINELOGGER.debug("Templates loaded.")
            # Create an array containing a set of informations about the template.
            # This array will be used to display the information to the user
            data = {
                'name': [],
                'version': [],
                'path': [],
                'provisioners': [],
                'providers': [],
                'archs': [],
                'comments': []
            }
            for f in templates.values():
                data['name'].append(f.getName())
                data['version'].append(str(f.getVersion()))
                data['path'].append(os.path.abspath(f.getPath()))
                data['provisioners'].append(",".join(
                    map(str, f.getProvisioners())))
                data['providers'].append(",".join(map(str, f.getProviders())))
                data['archs'].append(",".join(map(str, f.getArchs())))
                data['comments'].append(f.getComments())

            # Each column width will be computed as the max length of its items
            name_col_width = 0
            version_col_width = 0
            path_col_width = 0
            provisioner_col_width = 0
            providers_col_width = 0
            archs_col_width = 0
            comments_col_width = 0

            # Getting the max for each column
            if len(data['name']) != 0:
                name_col_width = max(
                    len(word) for word in data['name']) + len("Name") + 2
            if len(data['version']) != 0:
                version_col_width = max(
                    len(word) for word in data['version']) + len("Version") + 2
            if len(data['path']) != 0:
                path_col_width = max(
                    len(word) for word in data['path']) + len("Path") + 2
            if len(data['provisioners']) != 0:
                provisioner_col_width = max(
                    len(word)
                    for word in data['provisioners']) + len("Provisioners") + 2
            if len(data['providers']) != 0:
                providers_col_width = max(
                    len(word)
                    for word in data['providers']) + len("Providers") + 2
            if len(data['archs']) != 0:
                archs_col_width = max(
                    len(word)
                    for word in data['archs']) + len("Architectures") + 2
            if len(data['comments']) != 0:
                comments_col_width = max(
                    len(word)
                    for word in data['comments']) + len("Comments") + 2

            # Display the array
            # Checking number of items in the column name to know if there is something to display or not
            if len(data['name']) != 0:
                # Display the array titles
                COMMANDLINELOGGER.info(
                    "Name".ljust(name_col_width) +
                    "Version".ljust(version_col_width) +
                    "Path".ljust(path_col_width) +
                    "Provisioners".ljust(provisioner_col_width) +
                    "Providers".ljust(providers_col_width) +
                    "Architectures".ljust(archs_col_width) +
                    "Comments".ljust(comments_col_width))

                for row in range(0, len(data['name'])):
                    COMMANDLINELOGGER.info(
                        data['name'][row].ljust(name_col_width) +
                        data['version'][row].ljust(version_col_width) +
                        data['path'][row].ljust(path_col_width) +
                        data['provisioners'][row].ljust(provisioner_col_width)
                        + data['providers'][row].ljust(providers_col_width) +
                        data['archs'][row].ljust(archs_col_width) +
                        data['comments'][row].ljust(comments_col_width))
            else:
                COMMANDLINELOGGER.info("No templates available")
        except Exception as e:
            COMMANDLINELOGGER.error("Unable to list templates: {0}".format(
                str(e)))
            if (not args.verbose):
                COMMANDLINELOGGER.info(
                    "Run with --verbose flag for more details")
            COMMANDLINELOGGER.debug(traceback.format_exc())
            res = errno.EINVAL
        except (KeyboardInterrupt, SystemExit):
            COMMANDLINELOGGER.debug(traceback.format_exc())
            res = errno.EINVAL

        COMMANDLINELOGGER.info("")

        return res
Example #14
0
    def execute(self, args, templates):
        # Check if the requested template exists
        COMMANDLINELOGGER.debug(
            "Instance '{0}' does not exist, proceeding to its creation.".
            format(args.name))
        args.template = args.template.replace("\\", '')

        template = None
        guestInterfaces = []
        sharedFolders = []
        hostInterface = None
        networkInterfaces = getAllNetInterfaces()
        arch = None
        osversion = None
        provisioner = None
        provider = None

        if args.template in templates.keys():
            template = templates[args.template]
            guestInterfaces = []
            sharedFolders = []
            hostInterface = None
            networkInterfaces = getAllNetInterfaces()

            if len(networkInterfaces) == 0:
                COMMANDLINELOGGER.debug(
                    "No ethernet interfaces has been found on the host.")
                raise InvalidHardwareSupport(
                    "Your host does not have any network interface. Machines cannot be executed"
                )
            else:
                COMMANDLINELOGGER.debug(
                    "{0} interfaces has been found on the host: {1}.".format(
                        len(networkInterfaces), ', '.join(networkInterfaces)))

            arch = self.requestArchitecture(args, template)
            osversion = self.requestOsVersion(args, template)
            provisioner = self.requestProvisionner(args, template)
            provider = self.requestProvider(args, template)

            # Ask for configuration of network interface of the template
            itfCounter = 0
            if args.guestinterface != None:
                for i in range(0, template.getGuestInterfaces()):
                    (hostInterface, ipAddr, macAddr,
                     hostname) = self.unpackInterface(
                         args.guestinterface[itfCounter])
                    guestInterfaces.append(
                        NetworkInterface(ipAddr, macAddr, hostInterface,
                                         hostname))
                for i in range(itfCounter, len(args.guestinterface)):
                    (hostInterface, ipAddr, macAddr,
                     hostname) = self.unpackInterface(
                         args.guestinterface[itfCounter])
                    guestInterfaces.append(
                        NetworkInterface(ipAddr, macAddr, hostInterface,
                                         hostname))
                    itfCounter += 1
            else:
                for i in range(0, template.getGuestInterfaces()):
                    (hostInterface, ipAddr, macAddr,
                     hostname) = self.requestInterface(networkInterfaces)
                    guestInterfaces.append(
                        NetworkInterface(ipAddr, macAddr, hostInterface,
                                         hostname))

            # Ask for additional network interfaces
            if args.no_interactive == False:
                for i in range(itfCounter, template.getGuestInterfaces()):
                    (hostInterface, ipAddr, macAddr,
                     hostname) = self.requestInterface(networkInterfaces)
                    guestInterfaces.append(
                        NetworkInterface(ipAddr, macAddr, hostInterface,
                                         hostname))
            else:
                if (len(args.guestinterface) < template.getGuestInterfaces()):
                    COMMANDLINELOGGER.error(
                        "Not enough guestinterfaces given to fill requirement of template"
                    )
                    raise InvalidCmdLineArgument("guestinterface",
                                                 args.guestinterface)

            if args.no_interactive == False:
                # Ask for adding a new shared folder
                while BinaryQuestion("Do you want to add a shared folder ?",
                                     "Enter a Y or a N", COMMANDLINELOGGER,
                                     "N").ask():
                    hostPathQues = PathQuestion(
                        "Enter a path to an existing folder on the host",
                        "Entered path is invalid, Please enter a valid path",
                        COMMANDLINELOGGER, ".+", None, True).ask()
                    guestPathQues = PathQuestion(
                        "Enter the mount path on the guest directory: ",
                        "Entered path is invalid, Please enter a valid path",
                        COMMANDLINELOGGER, "^/.+", None, False).ask()
                    sharedFolders.append(
                        SharedFolder(hostPathQues, guestPathQues))

                if args.sharedfolder != None:
                    for s in args.sharedfolder:
                        sharedFolders.append(SharedFolder(s[0], s[1]))

        else:
            COMMANDLINELOGGER.error(
                "Unable to create machine: MachineInstance template '{0}:{1}' does not exists"
                .format(args.template, args.templateversion))

        return (template, arch, osversion, provider, provisioner,
                guestInterfaces, sharedFolders)
Example #15
0
    def listMachineTemplates(self, args):
        res = 0
        # Create the template registry that will list all available template on the machine
        COMMANDLINELOGGER.info("Machine templates:")
        COMMANDLINELOGGER.info("-------------------")

        try:
            templates = MACHINE_TEMPLATE_REGISTRY.getTemplates()
            COMMANDLINELOGGER.debug("Templates loaded.")
            # Create an array containing a set of informations about the template.
            # This array will be used to display the information to the user
            data = {
                "name": [],
                "version": [],
                "path": [],
                "provisioners": [],
                "providers": [],
                "archs": [],
                "comments": [],
            }
            for f in templates.values():
                data["name"].append(f.getName())
                data["version"].append(str(f.getVersion()))
                data["path"].append(os.path.abspath(f.getPath()))
                data["provisioners"].append(",".join(map(str, f.getProvisioners())))
                data["providers"].append(",".join(map(str, f.getProviders())))
                data["archs"].append(",".join(map(str, f.getArchs())))
                data["comments"].append(f.getComments())

            # Each column width will be computed as the max length of its items
            name_col_width = 0
            version_col_width = 0
            path_col_width = 0
            provisioner_col_width = 0
            providers_col_width = 0
            archs_col_width = 0
            comments_col_width = 0

            # Getting the max for each column
            if len(data["name"]) != 0:
                name_col_width = max(len(word) for word in data["name"]) + len("Name") + 2
            if len(data["version"]) != 0:
                version_col_width = max(len(word) for word in data["version"]) + len("Version") + 2
            if len(data["path"]) != 0:
                path_col_width = max(len(word) for word in data["path"]) + len("Path") + 2
            if len(data["provisioners"]) != 0:
                provisioner_col_width = max(len(word) for word in data["provisioners"]) + len("Provisioners") + 2
            if len(data["providers"]) != 0:
                providers_col_width = max(len(word) for word in data["providers"]) + len("Providers") + 2
            if len(data["archs"]) != 0:
                archs_col_width = max(len(word) for word in data["archs"]) + len("Architectures") + 2
            if len(data["comments"]) != 0:
                comments_col_width = max(len(word) for word in data["comments"]) + len("Comments") + 2

            # Display the array
            # Checking number of items in the column name to know if there is something to display or not
            if len(data["name"]) != 0:
                # Display the array titles
                COMMANDLINELOGGER.info(
                    "Name".ljust(name_col_width)
                    + "Version".ljust(version_col_width)
                    + "Path".ljust(path_col_width)
                    + "Provisioners".ljust(provisioner_col_width)
                    + "Providers".ljust(providers_col_width)
                    + "Architectures".ljust(archs_col_width)
                    + "Comments".ljust(comments_col_width)
                )

                for row in range(0, len(data["name"])):
                    COMMANDLINELOGGER.info(
                        data["name"][row].ljust(name_col_width)
                        + data["version"][row].ljust(version_col_width)
                        + data["path"][row].ljust(path_col_width)
                        + data["provisioners"][row].ljust(provisioner_col_width)
                        + data["providers"][row].ljust(providers_col_width)
                        + data["archs"][row].ljust(archs_col_width)
                        + data["comments"][row].ljust(comments_col_width)
                    )
            else:
                COMMANDLINELOGGER.info("No templates available")
        except Exception as e:
            COMMANDLINELOGGER.error("Unable to list templates: {0}".format(str(e)))
            if not args.verbose:
                COMMANDLINELOGGER.info("Run with --verbose flag for more details")
            COMMANDLINELOGGER.debug(traceback.format_exc())
            res = errno.EINVAL
        except (KeyboardInterrupt, SystemExit):
            COMMANDLINELOGGER.debug(traceback.format_exc())
            res = errno.EINVAL

        COMMANDLINELOGGER.info("")

        return res
Example #16
0
    def execute(self, args, templates):
        # Check if the requested template exists
        COMMANDLINELOGGER.debug("Instance '{0}' does not exist, proceeding to its creation.".format(args.name))
        args.template = args.template.replace("\\", "")

        template = None
        guestInterfaces = []
        sharedFolders = []
        hostInterface = None
        networkInterfaces = getAllNetInterfaces()
        arch = None
        osversion = None
        provisioner = None
        provider = None

        if args.template in templates.keys():
            template = templates[args.template]
            guestInterfaces = []
            sharedFolders = []
            hostInterface = None
            networkInterfaces = getAllNetInterfaces()

            if len(networkInterfaces) == 0:
                COMMANDLINELOGGER.debug("No ethernet interfaces has been found on the host.")
                raise InvalidHardwareSupport(
                    "Your host does not have any network interface. Machines cannot be executed"
                )
            else:
                COMMANDLINELOGGER.debug(
                    "{0} interfaces has been found on the host: {1}.".format(
                        len(networkInterfaces), ", ".join(networkInterfaces)
                    )
                )

            arch = self.requestArchitecture(args, template)
            osversion = self.requestOsVersion(args, template)
            provisioner = self.requestProvisionner(args, template)
            provider = self.requestProvider(args, template)

            # Ask for configuration of network interface of the template
            itfCounter = 0
            if args.guestinterface != None:
                for i in range(0, template.getGuestInterfaces()):
                    (hostInterface, ipAddr, macAddr, hostname) = self.unpackInterface(args.guestinterface[itfCounter])
                    guestInterfaces.append(NetworkInterface(ipAddr, macAddr, hostInterface, hostname))
                for i in range(itfCounter, len(args.guestinterface)):
                    (hostInterface, ipAddr, macAddr, hostname) = self.unpackInterface(args.guestinterface[itfCounter])
                    guestInterfaces.append(NetworkInterface(ipAddr, macAddr, hostInterface, hostname))
                    itfCounter += 1
            else:
                for i in range(0, template.getGuestInterfaces()):
                    (hostInterface, ipAddr, macAddr, hostname) = self.requestInterface(networkInterfaces)
                    guestInterfaces.append(NetworkInterface(ipAddr, macAddr, hostInterface, hostname))

            # Ask for additional network interfaces
            if args.no_interactive == False:
                for i in range(itfCounter, template.getGuestInterfaces()):
                    (hostInterface, ipAddr, macAddr, hostname) = self.requestInterface(networkInterfaces)
                    guestInterfaces.append(NetworkInterface(ipAddr, macAddr, hostInterface, hostname))
            else:
                if len(args.guestinterface) < template.getGuestInterfaces():
                    COMMANDLINELOGGER.error("Not enough guestinterfaces given to fill requirement of template")
                    raise InvalidCmdLineArgument("guestinterface", args.guestinterface)

            if args.no_interactive == False:
                # Ask for adding a new shared folder
                while BinaryQuestion(
                    "Do you want to add a shared folder ?", "Enter a Y or a N", COMMANDLINELOGGER, "N"
                ).ask():
                    hostPathQues = PathQuestion(
                        "Enter a path to an existing folder on the host",
                        "Entered path is invalid, Please enter a valid path",
                        COMMANDLINELOGGER,
                        ".+",
                        None,
                        True,
                    ).ask()
                    guestPathQues = PathQuestion(
                        "Enter the mount path on the guest directory: ",
                        "Entered path is invalid, Please enter a valid path",
                        COMMANDLINELOGGER,
                        "^/.+",
                        None,
                        False,
                    ).ask()
                    sharedFolders.append(SharedFolder(hostPathQues, guestPathQues))

                if args.sharedfolder != None:
                    for s in args.sharedfolder:
                        sharedFolders.append(SharedFolder(s[0], s[1]))

        else:
            COMMANDLINELOGGER.error(
                "Unable to create machine: MachineInstance template '{0}:{1}' does not exists".format(
                    args.template, args.templateversion
                )
            )

        return (template, arch, osversion, provider, provisioner, guestInterfaces, sharedFolders)