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 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
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
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
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
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
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
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
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
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
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
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 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