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
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
def from_yaml(cls, loader, node): representation = loader.construct_mapping(node, deep=True) # Retrieve the elements to create an instance arch = None if "arch" in representation.keys(): arch = Architecture.fromString(representation["arch"]) provider = None if "provider" in representation.keys(): provider = Provider.fromString(representation["provider"])() provisioner = None if "provisioner" in representation.keys(): provisioner = Provisioner.fromString(representation["provisioner"])() name = os.path.basename(os.path.dirname(loader.stream.name)) template = None if "template" in representation.keys(): template = MACHINE_TEMPLATE_REGISTRY.getTemplates()[representation["template"]] osVersion = None if "os_version" in representation.keys(): osVersion = representation["os_version"] guestInterfaces = [] if "guest_interfaces" in representation.keys(): guestInterfaces = representation["guest_interfaces"] sharedFolders = [] if "shared_folders" in representation.keys(): sharedFolders = representation["shared_folders"] return MachineInstance(name, template, arch, osVersion, provider, provisioner, guestInterfaces, sharedFolders)
def parseArgs(self, args): templates = MACHINE_TEMPLATE_REGISTRY.getTemplates() COMMANDLINELOGGER.debug("Templates loaded.") # Get instances instances = MACHINE_INSTANCE_REGISTRY.getInstances() COMMANDLINELOGGER.debug("Instances loaded.") # Create main parser parser = argparse.ArgumentParser( prog="Machination", description='Machination utility, all your appliances belong to us.' ) rootSubparsers = parser.add_subparsers(dest="function") versionParser = rootSubparsers.add_parser('version', help='Display version') # Parser for list command listParser = rootSubparsers.add_parser( 'list', help='List templates and instances') listParser.add_argument('type', help='Type to list', nargs='?', type=str, choices=("templates", "instances")) listParser.add_argument('--verbose', "-v", help='Verbose mode', action='store_true') # Parser for create command createParser = rootSubparsers.add_parser( 'create', help='Create the given machine in the path') createParser.add_argument('template', help='Name of the template to create', type=str, choices=templates.keys()) createParser.add_argument('name', help='Name of the machine to create', type=str) createParser.add_argument('--arch', '-a', help='Architecture to use', type=str) createParser.add_argument('--provider', '-p', help='Provider to use', type=str) createParser.add_argument('--provisioner', '-n', help='Provisioner to use', type=str) createParser.add_argument('--osversion', '-o', help='OS Version to use', type=str) createParser.add_argument( '--guestinterface', '-i', help='Network interface to add', metavar="<host_interface>,<ip_addr>[,mac_addr,hostname]", action='append', type=str) createParser.add_argument( '--sharedfolder', '-s', nargs=2, help='Shared folder between the new machine and the host', metavar=("<host folder>", "<guest folder>"), action='append', type=str) createParser.add_argument( '--no-interactive', help= 'Do not request for interactive configuration of optional elements (interfaces,sharedfolders)', action='store_true') createParser.add_argument('--verbose', "-v", help='Verbose mode', action='store_true') createParser.add_argument( '--force', "-f", help='Force creation by deleting an instance with same name', action='store_true') # Parser for destroy command destroyParser = rootSubparsers.add_parser( 'destroy', help='Destroy the given machine in the path') destroyParser.add_argument('names', help='Name of the machine to destroy', nargs="+", type=str, choices=instances.keys()) destroyParser.add_argument('--force', '-f', help='Do not ask for confirmation', action='store_true') destroyParser.add_argument('--verbose', "-v", help='Verbose mode', action='store_true') # Parser for start command startParser = rootSubparsers.add_parser( 'start', help='Start the given machine instance') startParser.add_argument('names', help='Name of the machine to start', nargs="+", type=str, choices=instances.keys()) startParser.add_argument('--verbose', "-v", help='Verbose mode', action='store_true') # Parser for stop command stopParser = rootSubparsers.add_parser( 'stop', help='Stop the given machine instance') stopParser.add_argument('names', help='Name of the machine to stop', nargs="+", type=str, choices=instances.keys()) stopParser.add_argument('--verbose', "-v", help='Verbose mode', action='store_true') # Parser for restart command restartParser = rootSubparsers.add_parser( 'restart', help='Restart the given machine instance') restartParser.add_argument('names', help='Name of the machine to restart', nargs="+", type=str, choices=instances.keys()) restartParser.add_argument('--verbose', "-v", help='Verbose mode', action='store_true') # Parser for infos command infosParser = rootSubparsers.add_parser( 'infos', help='Get informations about a machine instance') infosParser.add_argument( 'names', help= 'Name of the machine instance from which infos shall be retrieved', nargs="?", type=str, choices=instances.keys()) infosParser.add_argument('--verbose', "-v", help='Verbose mode', action='store_true') # Parser for ssh command sshParser = rootSubparsers.add_parser('ssh', help='SSH to the given machine') sshParser.add_argument('name', help='Name of the machine to ssh in', choices=instances.keys(), type=str) sshParser.add_argument('--command', "-c", help='Command to execute in SSH', type=str) sshParser.add_argument('--verbose', "-v", help='Verbose mode', action='store_true') # Parse the command argcomplete.autocomplete(parser) args = parser.parse_args() functions = { "list": self.listElements, "create": self.createMachineInstance, "destroy": self.destroyMachineInstance, "start": self.startMachineInstance, "stop": self.stopMachineInstance, "restart": self.restartMachineInstance, "infos": self.getMachineInstanceInfos, "ssh": self.sshIntoMachineInstance, "version": self.displayVersion } if ("verbose" in args and args.verbose): setGlobalLogLevel(logging.DEBUG) else: setGlobalLogLevel(logging.INFO) res = 0 if (args.function in functions.keys()): res = functions[args.function](args) return res
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
def parseArgs(self, args): templates = MACHINE_TEMPLATE_REGISTRY.getTemplates() COMMANDLINELOGGER.debug("Templates loaded.") # Get instances instances = MACHINE_INSTANCE_REGISTRY.getInstances() COMMANDLINELOGGER.debug("Instances loaded.") # Create main parser parser = argparse.ArgumentParser( prog="Machination", description="Machination utility, all your appliances belong to us." ) rootSubparsers = parser.add_subparsers(dest="function") versionParser = rootSubparsers.add_parser("version", help="Display version") # Parser for list command listParser = rootSubparsers.add_parser("list", help="List templates and instances") listParser.add_argument("type", help="Type to list", nargs="?", type=str, choices=("templates", "instances")) listParser.add_argument("--verbose", "-v", help="Verbose mode", action="store_true") # Parser for create command createParser = rootSubparsers.add_parser("create", help="Create the given machine in the path") createParser.add_argument("template", help="Name of the template to create", type=str, choices=templates.keys()) createParser.add_argument("name", help="Name of the machine to create", type=str) createParser.add_argument("--arch", "-a", help="Architecture to use", type=str) createParser.add_argument("--provider", "-p", help="Provider to use", type=str) createParser.add_argument("--provisioner", "-n", help="Provisioner to use", type=str) createParser.add_argument("--osversion", "-o", help="OS Version to use", type=str) createParser.add_argument( "--guestinterface", "-i", help="Network interface to add", metavar="<host_interface>,<ip_addr>[,mac_addr,hostname]", action="append", type=str, ) createParser.add_argument( "--sharedfolder", "-s", nargs=2, help="Shared folder between the new machine and the host", metavar=("<host folder>", "<guest folder>"), action="append", type=str, ) createParser.add_argument( "--no-interactive", help="Do not request for interactive configuration of optional elements (interfaces,sharedfolders)", action="store_true", ) createParser.add_argument("--verbose", "-v", help="Verbose mode", action="store_true") createParser.add_argument( "--force", "-f", help="Force creation by deleting an instance with same name", action="store_true" ) # Parser for destroy command destroyParser = rootSubparsers.add_parser("destroy", help="Destroy the given machine in the path") destroyParser.add_argument( "names", help="Name of the machine to destroy", nargs="+", type=str, choices=instances.keys() ) destroyParser.add_argument("--force", "-f", help="Do not ask for confirmation", action="store_true") destroyParser.add_argument("--verbose", "-v", help="Verbose mode", action="store_true") # Parser for start command startParser = rootSubparsers.add_parser("start", help="Start the given machine instance") startParser.add_argument( "names", help="Name of the machine to start", nargs="+", type=str, choices=instances.keys() ) startParser.add_argument("--verbose", "-v", help="Verbose mode", action="store_true") # Parser for stop command stopParser = rootSubparsers.add_parser("stop", help="Stop the given machine instance") stopParser.add_argument( "names", help="Name of the machine to stop", nargs="+", type=str, choices=instances.keys() ) stopParser.add_argument("--verbose", "-v", help="Verbose mode", action="store_true") # Parser for restart command restartParser = rootSubparsers.add_parser("restart", help="Restart the given machine instance") restartParser.add_argument( "names", help="Name of the machine to restart", nargs="+", type=str, choices=instances.keys() ) restartParser.add_argument("--verbose", "-v", help="Verbose mode", action="store_true") # Parser for infos command infosParser = rootSubparsers.add_parser("infos", help="Get informations about a machine instance") infosParser.add_argument( "names", help="Name of the machine instance from which infos shall be retrieved", nargs="?", type=str, choices=instances.keys(), ) infosParser.add_argument("--verbose", "-v", help="Verbose mode", action="store_true") # Parser for ssh command sshParser = rootSubparsers.add_parser("ssh", help="SSH to the given machine") sshParser.add_argument("name", help="Name of the machine to ssh in", choices=instances.keys(), type=str) sshParser.add_argument("--command", "-c", help="Command to execute in SSH", type=str) sshParser.add_argument("--verbose", "-v", help="Verbose mode", action="store_true") # Parse the command argcomplete.autocomplete(parser) args = parser.parse_args() functions = { "list": self.listElements, "create": self.createMachineInstance, "destroy": self.destroyMachineInstance, "start": self.startMachineInstance, "stop": self.stopMachineInstance, "restart": self.restartMachineInstance, "infos": self.getMachineInstanceInfos, "ssh": self.sshIntoMachineInstance, "version": self.displayVersion, } if "verbose" in args and args.verbose: setGlobalLogLevel(logging.DEBUG) else: setGlobalLogLevel(logging.INFO) res = 0 if args.function in functions.keys(): res = functions[args.function](args) return res
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