Ejemplo n.º 1
0
    def __init__(self, cloud=None):
        if cloud is None:
            default = Default()
            cloud = default["global"]["cloud"]
            default.close()
        cfg = Config.cloud(cloud)

        self._cloud = _authenticate(cfg)
Ejemplo n.º 2
0
    def __init__(self, cloud=None):

        if cloud is None:
            default = Default()
            cloud = default["global"]["cloud"]
            default.close()

        self.credentials = None
        self.info = Config().cloud(cloud)

        # print(yaml.dump(self.info, indent=4, Dumper=yaml.RoundTripDumper))

        self.driver = None
        self.authenticate()
Ejemplo n.º 3
0
    def replace_vars(self, line):

        # self.update_time()

        variable = Variables()
        newline = line

        if len(variable) is not None:
            for name in variable.data:
                value = str(variable[name])
                newline = newline.replace("$" + name, value)
                newline = newline.replace("var." + name, value)
            for v in os.environ:
                name = v.replace('os.', '')
                if name in newline:
                    value = os.environ[name]
                    newline = newline.replace("os." + v, value)

            default = Default()
            if default is not None:
                for v in default.data:
                    name = "default." + v.replace(",", ".")
                    value = default.data[v]
                    if name in newline:
                        newline = newline.replace(name, value)

                # replace if global is missing

                global_default = default["global"]
                if global_default is not None:
                    for v in global_default:
                        name = "default." + v
                        value = global_default[v]
                        if name in newline:
                            newline = newline.replace(name, value)

            default.close()
            variable.close()

        newline = path_expand(newline)
        return line, newline
Ejemplo n.º 4
0
    def do_openstack(self, args, arguments):
        """
        ::

          Usage:
                openstack info
                openstack yaml 
                openstack yaml list [CLOUD] 
                openstack image list [CLOUD] [--format=FORMAT]
                openstack flavor list [CLOUD] [--format=FORMAT]
                openstack vm list [CLOUD] [--user=USER] [--format=FORMAT] [--ip=public|private]

          This command does some useful things.

          Arguments:
              FILE   a file name
            
          Options:
              -f      specify the file

        """
        # print(arguments)

        default = Default()
        cloud = arguments.CLOUD or default["global"]["cloud"]
        default.close()
        arguments.format = arguments["--format"] or 'table'

        arguments.user = arguments["--user"]

        fd = None

        if arguments.info:

            if arguments.CLOUD is None:
                arguments.CLOUD = cloud

            provider = OpenStack(arguments.CLOUD)
            provider.information()

        elif arguments.yaml and arguments.list:

            filename = path_expand("~/.cloudmesh/cloudmesh.yaml")
            content = readfile(filename)
            d = yaml.load(content, Loader=yaml.RoundTripLoader)
            if arguments.CLOUD is None:
                default_cloud = default["global"]["cloud"]

                # print (yaml.dump(d, indent=4, Dumper=yaml.RoundTripDumper))
                info = OrderedDict()
                clouds = d["cloudmesh"]["clouds"]
                for cloud in clouds:
                    info[cloud] = {
                        "default": "",
                        "name": cloud,
                        "type": clouds[cloud]["cm_type"],
                        "label": clouds[cloud]["cm_label"],
                        "flavor": clouds[cloud]["default"]["flavor"],
                        "image": clouds[cloud]["default"]["image"]
                    }
                    if default_cloud == cloud:
                        info[cloud]["default"] = "*"

                print(Printer.dict(info,
                                   order=["default", "name", "type", "label", "flavor", "image"]))

            else:
                cloud = arguments.CLOUD
                clouds = d["cloudmesh"]["clouds"]
                print(yaml.dump(clouds[cloud], indent=4, Dumper=yaml.RoundTripDumper))

        elif arguments.yaml:

            filename = path_expand("~/.cloudmesh/cloudmesh.yaml")
            content = readfile(filename)
            d = yaml.load(content, Loader=yaml.RoundTripLoader)
            print(yaml.dump(d, indent=4, Dumper=yaml.RoundTripDumper))

        elif arguments.image and arguments.list:

            if arguments.CLOUD is None:
                arguments.CLOUD = cloud

            # print (arguments.CLOUD)

            provider = OpenStack(arguments.CLOUD)
            images = provider.images()

            try:
                fd = flatme(images)
            except Exception as e:
                Error.traceback(error=e, debug=True, trace=True)

            order = ["name", "extra__metadata__user_id", "extra__metadata__image_state", "extra__updated"]
            header = ["name", "user", "state", "updated"]

            if arguments.format == "table":
                print(arguments.CLOUD)
                print(Printer.dict(fd,
                                   sort_keys="name",
                                   order=order,
                                   header=header,
                                   output=arguments.format))
            # elif arguments.format == "dict":
            #    print(yaml.dump(images, indent=4, Dumper=yaml.RoundTripDumper))
            else:
                print(Printer.dict(images, output=arguments.format))

        elif arguments.flavor and arguments.list:

            if arguments.CLOUD is None:
                arguments.CLOUD = cloud

            # print (arguments.CLOUD)

            provider = OpenStack(arguments.CLOUD)
            d = provider.flavors()
            print(arguments.CLOUD)
            print(Printer.dict(d,
                               sort_keys="id",
                               output=arguments.format,
                               order=['id', 'name', 'ram', 'vcpus', 'disk']))

        elif arguments.vm and arguments.list:

            if arguments.CLOUD is None:
                arguments.CLOUD = cloud

            # print (arguments.CLOUD)

            provider = OpenStack(arguments.CLOUD)
            elements = provider.vms()

            if arguments.user is not None:
                found = {}
                for element in elements:
                    if elements[element]['extra']['userId'] == arguments.user:
                        found[element] = elements[element]
                elements = found

            try:
                fd = flatme(elements)
            except Exception as e:
                Error.traceback(error=e, debug=True, trace=True)

            order = ["name", 'extra__vm_state', 'extra__metadata__image', 'extra__metadata__flavor', "extra__key_name",
                     'extra__metadata__group', "extra__userId", "extra__created", 'private_ips', 'public_ips']
            header = ["name", "state", "image", "flavor", "key", "group", "user", "created", "private", "public"]

            if arguments.format == "table" or arguments.format == "inventory":

                for element in fd:
                    fd[element]['private_ips'] = ','.join(fd[element]['private_ips'])
                    fd[element]['public_ips'] = ','.join(fd[element]['public_ips'])
                    # fd[element]["extra__created"] = humanize.timedelta(fd[element]["extra__created"])
                    t = humanize.naturaltime(timestring.Date(fd[element]["extra__created"]).date)
                    fd[element]["extra__created"] = t

                if arguments["--ip"]:

                    kind = arguments["--ip"]

                    ips = {}
                    for element in fd:
                        ips[element] = {
                            'name': fd[element]['name'],
                            kind: fd[element][kind + '_ips']
                        }
                    if arguments.format == 'inventory':
                        # print ("[hosts]")
                        for host in ips:
                            print(ips[host][kind])
                    else:
                        print(Printer.dict(ips,
                                           # sort_keys=True,
                                           order=["name", kind],
                                           output=arguments.format))

                else:
                    print(arguments.CLOUD)
                    print(Printer.dict(fd,
                                       # sort_keys=True,
                                       order=order,
                                       header=header,
                                       output=arguments.format))
                    # elif arguments.format == "dict":
                    #    print(yaml.dump(images, indent=4, Dumper=yaml.RoundTripDumper))
            elif arguments.format == 'flatten':
                pprint(fd)
            else:
                print(Printer.dict(elements, output=arguments.format))

            return ""
Ejemplo n.º 5
0
    def do_kubernetes(self, args, arguments):
        """
		::
	
          	Usage:
                	kubernetes name NAME
			kubernetes size SIZE
			kubernetes image IMAGE
			kubernetes flavor FLAVOR
			kubernetes cloud CLOUD
			kubernetes cluster info
			kubernetes cluster deploy
			kubernetes cluster benchmark

		Arguments:
		NAME	name of the cluster
		SIZE	size of the clusteri
		IMAGE	image of the cluster
		FLAVOR	flavor of the vm
		CLOUD	cloud on which the cluster will be created

          	This command does some useful things.
		"""
        default = Default()
        if arguments.name and arguments.NAME:
            print("Set name to {}.".format(arguments.NAME))
            default["kubernetes", "name"] = arguments.NAME

        elif arguments.size and arguments.SIZE:
            print(" Set size to {}.".format(arguments.SIZE))
            default["kubernetes", "size"] = arguments.SIZE

        elif arguments.image and arguments.IMAGE:
            print(" set image to {}.".format(arguments.IMAGE))
            default["kubernetes", "image"] = arguments.IMAGE

        elif arguments.flavor and arguments.FLAVOR:
            print(" set flavor to {}.".format(arguments.FLAVOR))
            default["kubernetes", "flavor"] = arguments.FLAVOR

        elif arguments.cloud and arguments.CLOUD:
            print(" set cloud to {}.".format(arguments.CLOUD))
            default["kubernetes", "cloud"] = arguments.CLOUD

        elif arguments.cluster and arguments.info:
            print("Cluster details:")
            print("\tCloud\t: {}".format(default["kubernetes", "cloud"]))
            print("\tName\t: {}".format(default["kubernetes", "name"]))
            print("\tSize\t: {}".format(default["kubernetes", "size"]))
            print("\tImage\t: {}".format(default["kubernetes", "image"]))
            print("\tFlavor\t: {}".format(default["kubernetes", "flavor"]))
            print("\nIf any of the above details are None/False,")
            print(
                "please set them using the appropriate command, before deploying the cluster."
            )

        elif arguments.cluster and arguments.deploy:
            if default["kubernetes", "name"] is not None and default[
                    "kubernetes", "size"] is not None and default[
                        "kubernetes", "image"] is not None and default[
                            "kubernetes", "flavor"] is not None and default[
                                "kubernetes", "cloud"] is not None:

                stopwatch = StopWatch()
                stopwatch.start('cluster creation for kubernetes')

                print("Creating cluster {}...".format(default["kubernetes",
                                                              "name"]))
                # Define a cluster
                command = "cm cluster define --secgroup mesos-secgroup --name {} --count {} --image {} --flavor {} -C {}".format(
                    default["kubernetes", "name"],
                    default["kubernetes", "size"], default["kubernetes",
                                                           "image"],
                    default["kubernetes", "flavor"], default["kubernetes",
                                                             "cloud"])
                os.system(command)

                # Use defined cluster
                command = "cm default cloud={}".format(default["kubernetes",
                                                               "cloud"])
                os.system(command)

                # Use defined cluster
                command = "cm cluster use {}".format(default["kubernetes",
                                                             "name"])
                os.system(command)

                # Create defined cluster
                command = "cm cluster allocate"
                os.system(command)

                # Make hosts file
                self.make_hosts()

                stopwatch.stop('cluster creation for kubernetes')
                print(
                    'Time Taken for creating clusters required for kubernetes:'
                    + str(stopwatch.get('cluster creation for kubernetes')) +
                    ' seconds')

                stopwatch = StopWatch()
                stopwatch.start('prereq for kubernetes')

                # Run ansible script for setting up the various installables
                print("Running the setup needed for Kubernetes")
                command = 'ansible-playbook ~/cloudmesh.kubernetes/ansiblescript/installations.yml -i ~/cloudmesh.kubernetes/ansiblescript/inventory.txt -e "cloud={}"'.format(
                    default["kubernetes", "cloud"])
                os.system(command)

                stopwatch.stop('prereq for kubernetes')
                print(
                    'Time Taken for installing various pre requites for kubernetes:'
                    + str(stopwatch.get('prereq for kubernetes')) + ' seconds')

                stopwatch = StopWatch()
                stopwatch.start('Kubernetes installables')

                # Run ansible script for setting up kubernetes cluster
                print("Running the Kubernetes setup")
                command = 'ansible-playbook ~/cloudmesh.kubernetes/ansiblescript/kubernetes.yml -i ~/cloudmesh.kubernetes/ansiblescript/inventory.txt -e "cloud={}"'.format(
                    default["kubernetes", "cloud"])
                os.system(command)

                stopwatch.stop('Kubernetes installables')
                print(
                    'Time Taken for installing kubernetes related packages:' +
                    str(stopwatch.get('Kubernetes installables')) + ' seconds')

                stopwatch = StopWatch()
                stopwatch.start('Kubernetes cluster creation')

                # Run ansible script for installing kubernetes on master node
                print("Installing Kubernetes on master node")
                command = 'ansible-playbook ~/cloudmesh.kubernetes/ansiblescript/master.yml -i ~/cloudmesh.kubernetes/ansiblescript/inventory.txt -e "cloud={}"'.format(
                    default["kubernetes", "cloud"])
                os.system(command)

                # Run ansible script for joining slaves to master node to make a kubernetes cluster
                print("Joining the slaves")
                command = 'ansible-playbook ~/cloudmesh.kubernetes/ansiblescript/slaves.yml -i ~/cloudmesh.kubernetes/ansiblescript/inventory.txt -e "cloud={}"'.format(
                    default["kubernetes", "cloud"])
                os.system(command)

                stopwatch.stop('Kubernetes cluster creation')
                print('Time Taken for deploying Kubernetes cluster:' +
                      str(stopwatch.get('Kubernetes cluster creation')) +
                      ' seconds')

                print("Ansible tasks have been successfully completed.")
                print(
                    "Cluster {} created and Kubernetes is running on cluster.".
                    format(default["kubernetes", "name"]))
                default["kubernetes", "deploy"] = True
            else:
                print("Please set all the required variables.")

        elif arguments.cluster and arguments.benchmark:
            if default["kubernetes", "name"] is not None and default[
                    "kubernetes", "size"] is not None and default[
                        "kubernetes", "image"] is not None and default[
                            "kubernetes", "flavor"] is not None and default[
                                "kubernetes",
                                "cloud"] is not None and default["kubernetes",
                                                                 "deploy"]:

                stopwatch = StopWatch()
                stopwatch.start('Kubernetes benchmark')

                # Running the spam detection application
                print(
                    "Running the spam detection application on kubernetes cluster"
                )
                command = 'ansible-playbook ~/cloudmesh.kubernetes/ansiblescript/runningapplicationonkubernetes.yml -i ~/cloudmesh.kubernetes/ansiblescript/inventory.txt -e "cloud={}"'.format(
                    default["kubernetes", "cloud"])
                os.system(command)

                stopwatch.stop('Kubernetes benchmark')
                print(
                    'Time Taken for running the Spam Detection application:' +
                    str(stopwatch.get('Kubernetes benchmark')) + ' seconds')

                print(
                    "Cluster {} created and Kubernetes is running on cluster.".
                    format(default["kubernetes", "name"]))
                default["kubernetes", "deploy"] = False
            else:
                print(
                    "Please set all the required variables and deploy a kubernetes cluster before running benchmarks on it."
                )
        default.close()
        return ""
Ejemplo n.º 6
0
    def do_aws(self, args, arguments):
        """
        ::

          Usage:
            aws refresh ON
            aws api URL
            aws default image ON
            aws image [refresh] [--format=FORMAT]
            aws image list [--format=FORMAT]
            aws flavor [refresh] [--format=FORMAT]
            aws flavor list [--format=FORMAT]
            aws vm boot NODE_NAME [--image_id=IMAGE_ID] [--flavor_id=FLAVOR_ID] [--keypair_name=KEYPAIR_NAME]
            aws vm reboot NODE_NAME
            aws vm delete NODE_NAME
            aws vm list [--format=FORMAT]
            aws vm refresh [--format=FORMAT]
            aws keypair create NAME
            aws keypair delete NAME
            aws keypair list
            aws keypair refresh
            aws keypair get NAME
            aws location list
            aws location refresh
            aws volume create VOLUME_NAME
            aws volume list
            aws volume refresh
            aws volume delete VOLUME_NAME
            aws volume attach VOLUME_NAME
            aws drop collections

          Arguments:
            ON              set configuration to on/off 
            NAME            The name of the aws
            URL             URL of aws API
            FORMAT          The format in which to print the data
            UUID            Unique User ID, which gets generate after creating the node/vm
            IMAGE_ID        Image ID for which we are creating the vm
            KEYPAIR_NAME    Created Key pair name
            FLAVOR_ID       Flavor ID for which vm request to be establish
            VOLUME_ID       Unique ID after creating a volume
          Options:
            -v       verbose mode

          Description:
            Manages a virtual aws on a cloud

            to complete the command see the man page of cm boot help
        """
        v = Default()
        if v['aws', 'refresh'] != None:
            refresh = v['aws', 'refresh']
        else:
            refresh = "off"
        v.close()

        if arguments.refresh and arguments.ON:
            v = Default()
            v['aws', 'refresh'] = arguments.ON
            v.close()
        """ v = Default()
        if v['aws', 'keypair'] != None:
            print("assign the name")
            NAME = v['aws', 'keypair']
        v.close()"""
        """if arguments.create and arguments.NAME :
           print(" create new obj :: ",arguments.NAME )
           v = Default()
           v['aws', 'keypair'] = arguments.NAME
           v.close()"""

        # Initialize timer and aws client
        stopwatch = StopWatch()
        stopwatch.start('E2E')
        aws = Aws()

        if arguments.image:
            if arguments.refresh or refresh == "on":
                aws.image_refresh()
            else:
                aws.image_list()

            stopwatch.stop('E2E')
            Console.ok('Execution Time:' + str(stopwatch.get('E2E')))
            return

        if arguments.flavor:
            if arguments.refresh or refresh == "on":
                aws.flavor_refresh()
            else:
                aws.flavor_list()

            stopwatch.stop('E2E')
            Console.ok('Execution Time:' + str(stopwatch.get('E2E')))
            return

        if arguments.vm and arguments.list:
            aws.node_list()
            stopwatch.stop('E2E')
            Console.ok('Execution Time:' + str(stopwatch.get('E2E')))
            return

        if arguments.vm and arguments.refresh:
            aws.node_refresh(True)
            stopwatch.stop('E2E')
            Console.ok('Execution Time:' + str(stopwatch.get('E2E')))
            return

        if arguments.vm and arguments.reboot and arguments.NODE_NAME:
            NODE_NAME = arguments.NODE_NAME
            aws.node_reboot(NODE_NAME)
            stopwatch.stop('E2E')
            Console.ok('Execution Time:' + str(stopwatch.get('E2E')))

        if arguments.vm and arguments.boot and arguments.NODE_NAME:
            #SEL_IMAGE_ID = 'ami-0183d861' #ami-d85e75b0
            arguments.IMAGE_ID = arguments["--image_id"]
            arguments.FLAVOR_ID = arguments["--flavor_id"]
            arguments.KEYPAIR_NAME = arguments["--keypair_name"]
            config = {}
            if arguments.IMAGE_ID:
                config["image_id"] = arguments.IMAGE_ID

            if arguments.FLAVOR_ID:
                config["flavor_id"] = arguments.FLAVOR_ID

            if arguments.KEYPAIR_NAME:
                config["keypair_name"] = arguments.KEYPAIR_NAME

            # if arguments.SEC_GRP_NAMES:
            #     config["security_group_names"] = arguments.SEC_GRP_NAMES

            aws.node_create_by_imageId(arguments.NODE_NAME, config)
            stopwatch.stop('E2E')
            Console.ok('Execution Time:' + str(stopwatch.get('E2E')))
            return

        if arguments.vm and arguments.delete and arguments.NODE_NAME:
            node_name = arguments.NAME  #'61671593de3681e7de6bd6c6e33f5a4857110864'
            aws.node_delete(node_name)
            stopwatch.stop('E2E')
            Console.ok('Execution Time:' + str(stopwatch.get('E2E')))
            return

        if arguments.keypair and arguments.create and arguments.NAME:
            KEY_PAIR = arguments.NAME  #"AWS3"
            aws.keypair_create(KEY_PAIR)
            stopwatch.stop('E2E')
            Console.ok('Execution Time:' + str(stopwatch.get('E2E')))
            return

        if arguments.keypair and arguments.delete and arguments.NAME:
            KEY_PAIR = arguments.NAME  # "AWS1"
            aws.keypair_delete(KEY_PAIR)
            stopwatch.stop('E2E')
            Console.ok('Execution Time:' + str(stopwatch.get('E2E')))
            return

        if arguments.keypair and arguments.list:
            aws.keypair_list()
            stopwatch.stop('E2E')
            Console.ok('Execution Time:' + str(stopwatch.get('E2E')))
            return

        if arguments.keypair and arguments.refresh:
            aws.keypair_refresh()
            stopwatch.stop('E2E')
            Console.ok('Execution Time:' + str(stopwatch.get('E2E')))
            return

        if arguments.keypair and arguments.get and arguments.NAME:
            KEY_PAIR = arguments.NAME  #"AWS2"
            aws.keypair_get(KEY_PAIR)
            stopwatch.stop('E2E')
            Console.ok('Execution Time:' + str(stopwatch.get('E2E')))
            return

        if arguments.drop and arguments.collections:
            aws.drop_collections()
            stopwatch.stop('E2E')
            Console.ok('Execution Time:' + str(stopwatch.get('E2E')))
            return

        if arguments.location and arguments.list:
            aws.location_list(True)
            stopwatch.stop('E2E')
            Console.ok('Execution Time:' + str(stopwatch.get('E2E')))
            return

        if arguments.location and arguments.refresh:
            aws.location_refresh(True)
            stopwatch.stop('E2E')
            Console.ok('Execution Time:' + str(stopwatch.get('E2E')))
            return

        if arguments.volume and arguments.create and arguments.VOLUME_NAME:
            VOLUME_SIZE = 1  # Size of volume in gigabytes (required)
            VOLUME_NAME = arguments.VOLUME_NAME  # Name of the volume to be created
            aws.volume_create(VOLUME_SIZE, VOLUME_NAME)
            stopwatch.stop('E2E')
            Console.ok('Execution Time:' + str(stopwatch.get('E2E')))
            return

        if arguments.volume and arguments.list:
            aws.volume_list(True)
            stopwatch.stop('E2E')
            Console.ok('Execution Time:' + str(stopwatch.get('E2E')))
            return

        if arguments.volume and arguments.refresh:
            aws.volume_refresh(True)
            stopwatch.stop('E2E')
            Console.ok('Execution Time:' + str(stopwatch.get('E2E')))
            return

        if arguments.volume and arguments.delete and arguments.VOLUME_NAME:
            aws.volume_delete(arguments.VOLUME_NAME)
            stopwatch.stop('E2E')
            Console.ok('Execution Time:' + str(stopwatch.get('E2E')))
            return

        if arguments.volume and arguments.attach and arguments.VOLUME_ID:
            NODE_ID = ''  # we are taking defaulr 0th created node from node list
            aws.volume_attach(NODE_ID, arguments.VOLUME_ID)
            stopwatch.stop('E2E')
            Console.ok('Execution Time:' + str(stopwatch.get('E2E')))
            return
Ejemplo n.º 7
0
    def do_default(self, args, arguments):
        """
        ::

          Usage:
              default list [--context=CONTEXT] [--format=FORMAT]
              default delete --context=CONTEXT
              default delete KEY [--context=CONTEXT]
              default KEY [--context=CONTEXT]
              default KEY=VALUE [--CONTEXT=CONTEXT]

          Arguments:
            KEY    the name of the default
            VALUE  the value to set the key to

          Options:
             --context=CONTEXT    the name of the context
             --format=FORMAT  the output format. Values include
                              table, json, csv, yaml.

        Description:
            Cloudmesh has the ability to manage easily multiple
            clouds. One of the key concepts to manage multiple clouds
            is to use defaults for the cloud, the images, flavors,
            and other values. The default command is used to manage
            such default values. These defaults are used in other commands
            if they are not overwritten by a command parameter.

            The current default values can by listed with

                default list --all

            Via the default command you can list, set, get and delete
            default values. You can list the defaults with

               default list

            A default can be set with

                default KEY=VALUE

            To look up a default value you can say

                default KEY

            A default can be deleted with

                default delete KEY

            To be specific to a cloud you can specify the name of the
            cloud with the --cloud=CLOUD option. The list command can
            print the information in various formats iv specified.

        Examples:
            default list --all
                lists all default values

            default list --cloud=kilo
                lists the defaults for the cloud with the name kilo

            default image=xyz
                sets the default image for the default cloud to xyz

            default image=abc --cloud=kilo
                sets the default image for the cloud kilo to xyz

            default image
                list the default image of the default cloud

            default image --cloud=kilo
                list the default image of the cloud kilo

            default delete image
                deletes the value for the default image in the
                default cloud

            default delete image --cloud=kilo
                deletes the value for the default image in the
                cloud kilo

        """
        print(arguments)
        # print (">", args, "<")

        context = arguments["--context"] or "global"

        defaults = Default()

        if arguments["delete"]:

            key = arguments.KEY
            if key is None:
                del defaults[context]
            else:
                del defaults[context, key]
            # if not result :
            #    Console.error("default {} not present".format(key))
            # else:
            #    Console.ok("Deleted key {} for cloud {}. ok.".format(key,
            #                                                      cloud))
            return ""

        if arguments.KEY is not None:
            if "=" not in arguments.KEY:
                print(arguments.KEY,
                      "=",
                      defaults[context, arguments.KEY],
                      sep='')
            else:
                key, value = arguments["KEY"].split("=", 1)
                defaults[context, key] = value
            return ""

        if arguments["list"]:

            output_format = arguments["--format"] or defaults[
                "global", "output"] or 'table'

            if defaults is None:
                Console.error("No default values found")
            else:

                data = []
                d = defaults.__dict__()
                for context in d:
                    for key in d[context]:
                        data.append({
                            "context": context,
                            "key": key,
                            "value": d[context][key]
                        })
                print(Printer.list(data, output=output_format))
            return ""
Ejemplo n.º 8
0
def main():
    """cms.

    Usage:
      cms --help
      cms [--echo] [--debug] [--nosplash] [-i] [COMMAND ...]

    Arguments:
      COMMAND                  A command to be executed

    Options:
      --file=SCRIPT  -f  SCRIPT  Executes the script
      -i                 After start keep the shell interactive,
                         otherwise quit [default: False]
      --nosplash    do not show the banner [default: False]
    """
    def manual():
        print(main.__doc__)

    args = sys.argv[1:]

    arguments = {
        '--echo': '--echo' in args,
        '--help': '--help' in args,
        '--debug': '--debug' in args,
        '--nosplash': '--nosplash' in args,
        '-i': '-i' in args
    }

    echo = arguments["--echo"]
    if arguments['--help']:
        manual()
        sys.exit()

    for a in args:
        if a in arguments:
            args.remove(a)

    arguments['COMMAND'] = [' '.join(args)]

    commands = arguments["COMMAND"]
    # commands = list(arguments["COMMAND"])

    if len(commands) > 0:
        if ".cm" in commands[0]:
            arguments["SCRIPT"] = commands[0]
            commands = commands[1:]
        else:
            arguments["SCRIPT"] = None

        arguments["COMMAND"] = ' '.join(commands)
        if arguments["COMMAND"] == '':
            arguments["COMMAND"] = None

    # noinspection PySimplifyBooleanCheck
    if arguments['COMMAND'] == []:
        arguments['COMMAND'] = None

    splash = not arguments['--nosplash']
    debug = arguments['--debug']
    interactive = arguments['-i']
    script = arguments["SCRIPT"]
    command = arguments["COMMAND"]

    # context = CloudmeshContext(
    #    interactive=interactive,
    #    debug=debug,
    #    echo=echo,
    #    splash=splash)

    cmd = CMShell()

    #    if script is not None:
    #        cmd.do_exec(script)

    try:
        if echo:
            print(cmd.prompt, command)
        if command is not None:
            cmd.precmd(command)
            stop = cmd.onecmd(command)
            cmd.postcmd(stop, command)
    except Exception as e:
        print("ERROR: executing command '{0}'".format(command))
        print(70 * "=")
        print(e)
        d = Default()
        trace = d["global", "trace"] == "True"
        trace = True
        Error.traceback(error=e, debug=True, trace=trace)
        d.close()
        print(70 * "=")

    if interactive or (command is None and script is None):
        cmd.cmdloop()