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 ""
    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
Beispiel #3
0
    def do_robot(self, args, arguments):
        """
        ::

          Usage:
                robot welcome
                robot osx install
                robot osx driver
                robot image fetch
                robot probe [--format=FORMAT]
                robot flash erase [--dryrun]
                robot flash python [--dryrun]
                robot test
                robot run PROGRAM
                robot credentials set SSID USERNAME PASSWORD
                robot put (credentials | cred)
                robot list (credentials | cred)
                robot login
                robot set PORT NOT IMPLEMENTED
                robot ls [PATH]
                robot put [-o] SOURCE [DESTINATION]
                robot get PATH
                robot rm PATH
                robot rmdir PATH
                robot dance FILE IPS
                robot inventory list [--cat] [--path=PATH] [ID]
                robot inventory export FILENAME
                robot reset
                
          Arguments:
              FILE   a file name

          Options:
              -f      specify the file
        """

        # pprint(arguments)

        # "wget http://micropython.org/resources/firmware/esp8266-20170108-v1.8.7.bin"

        arguments.dryrun = arguments["--dryrun"]

        def _run(command):
            print(command)
            if arguments.dryrun:
                print(command)
            else:
                os.system(command)

        def _continue(msg):
            if not arguments.dryrun:
                c = yn_choice(msg, default='y')

        if arguments.welcome:
            print(self.Banner.show())

        elif arguments.login:

            p = Probe()
            Console.error(
                "If you do not see a >>> please press the reset button.")
            print(p)

            data = {'tty': p.tty, 'baudrate': "115200"}

            # if 'tty.SLAB_USBtoUART' in p.tty:
            #    data["baudrate"] = "9600"
            # else:
            #    data["baudrate"] = "115200"

            os.system(
                "picocom --imap lfcrlf -b {baudrate} {tty}".format(**data))

        elif arguments.flash and arguments.erase:

            p = Probe()
            print(p.tty)
            print("Please press the right buttons")

            _continue("continue?")
            command = "esptool.py --port {} erase_flash".format(p.tty)
            _run(command)

        elif arguments.flash and arguments.python:

            p = Probe()
            print(p.tty)
            print("Please press the right buttons")

            _continue("continue?")

            d = {
                "baud": str(9600 * 6),
                "dir": ".",
                "image": "esp8266-20170108-v1.8.7.bin",
                "port": p.tty
            }

            if 'tty.SLAB_USBtoUART' in p.tty:
                d["baud"] = str(460800)

            command = "esptool.py --port {port} --baud {baud} write_flash --flash_size=detect -fm dio 0x00000 {image}".format(
                **d)
            _run(command)
            # "esptool.py --port /dev/tty.wchusbserial1410 --baud 9600 write_flash --flash_size=detect -fm dio 0x00000 esp8266-20170108-v1.8.7.bin"

        elif arguments.osx and arguments.install:

            o = sys.platform

            print(o)

            if sys.platform == 'darwin':
                if Shell.command_exists("brew"):
                    pass
                else:
                    os.system(
                        '/usr/bin/ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"'
                    )

                os.system("pip install pyserial")
                #
                # INSTALLING COMMANDS WITH BREW
                #
                for package in ["lua", "picocom", "wget"]:
                    try:
                        print("installing command", package)
                        r = Shell.which(package)
                        if r is None:
                            r = Brew.install(package)
                        else:
                            print("    [OK]", package, "already installed")
                    except Exception as e:
                        print("Error", e, type(e))
                #
                # INSTALLING LIBRARIES WITH BREW
                #
                # libusb-compat
                for package in ["libusb", "mosquitto"]:
                    try:
                        print("installing", package)
                        r = Brew.install(package)
                        if r is None:
                            r = Brew.install(package)
                        else:
                            Console.error(
                                package +
                                " package already installed. skipping.")
                    except Exception as e:
                        print("Error", e, type(e))
                #
                # INSTALLING CASK LIBRARIES AND COMMANDS WITH BREW
                #
                # libusb-compat
                for package in ["adafruit-arduino",
                                "pycharm-ce"]:  # "aquamacs"
                    try:
                        print("installing", package)

                        os.system("brew cask install {}".format(package))

                    except Exception as e:
                        print("Error", e, type(e))

            if sys.platform == 'linux':
                Console.error(
                    "Linux not yet supported. Install lua and picocom.")
            return ""

        elif arguments.osx and arguments.driver:

            os.system(
                "brew tap mengbo/ch340g-ch34g-ch34x-mac-os-x-driver https://github.com/mengbo/ch340g-ch34g-ch34x-mac-os-x-driver"
            )
            os.system("brew cask install wch-ch34x-usb-serial-driver")

        elif arguments.probe:

            output_format = arguments["--format"] or "table"
            try:
                p = Probe()
                d = p.probe()

                print(Printer.attribute(d, output=output_format))

            except Exception as e:

                Error.traceback(error=e, debug=True, trace=True)

            return ""

        elif arguments.image and arguments.fetch:

            try:

                if os.path.isfile("esp8266-20170108-v1.8.7.bin"):
                    print("... image already downloaded")
                else:
                    os.system(
                        "wget http://micropython.org/resources/firmware/esp8266-20170108-v1.8.7.bin"
                    )

                    # g = Git()
                    # r = g.fetch()

            except Exception as e:

                Error.traceback(error=e, debug=True, trace=True)

            return ""

        elif arguments.run:

            p = Probe()
            d = {"port": p.tty, "program": arguments.PROGRAM}
            os.system("ampy --port {port} run {program}".format(**d))

        elif arguments.test:

            p = Probe()
            d = {"port": p.tty}
            test = textwrap.dedent("""
            n=3
            print('Count to', n)
            for i in range(1, n+1):
                print(i)
            """)
            with open("test.py", "w") as f:
                f.write(test)
            os.system("ampy --port {port} run test.py".format(**d))

        elif arguments.reset:

            p = Probe()
            d = {"port": p.tty}
            test = textwrap.dedent("""
            import machine
            machine.reset()
            """)
            with open("tmp-reset.py", "w") as f:
                f.write(test)
            os.system("ampy --port {port} run tmp-reset.py".format(**d))
            os.remove("tmp-reset.py")

        elif arguments.credentials and arguments.set:
            try:
                net = Network(ssid=arguments.SSID,
                              username=arguments.USERNAME,
                              password=arguments.PASSWORD)

            except Exception as e:
                Error.traceback(e)

        elif (arguments.credentials or arguments.cred) and arguments.put:
            try:
                filename = path_expand("~/.cloudmesh/robot/credentials.txt")
                p = Probe()
                #   print (p.tty)
                ampy = Ampy(p.tty)
                ampy.put(filename, "credentials.txt", False)
            except Exception as e:
                Error.traceback(e)
                sys.exit(1)

        elif arguments.put:
            try:
                t = StopWatch()
                t.start("put")

                size = os.path.getsize(arguments.SOURCE)

                optimize = arguments["-o"]
                p = Probe()
                ampy = Ampy(p.tty)
                ampy.put(arguments.SOURCE,
                         dest=arguments.DESTINATION,
                         optimize=optimize)
                t.stop("put")
                t.print("Time:", "put")
                print("Rate:", "{0:.2f}".format(size / t.get("put") / 1024),
                      "KB/s")
            except Exception as e:
                Error.traceback(e)

        elif arguments.credentials and arguments.list:
            try:
                p = Probe()
                ampy = Ampy(p.tty)
                filename = path_expand(
                    "~/.cloudmesh/robot/credentials.txt.robot")
                ampy.get("credentials.txt", filename)
                r = Shell.cat(filename)
                print(r)
                os.remove(filename)
            except Exception as e:
                Error.traceback(e)

        elif arguments.ls:
            try:
                p = Probe()
                ampy = Ampy(p.tty)
                r = ampy.ls()
                print(r)
            except Exception as e:
                Error.traceback(e)

        elif arguments.rm:
            try:
                p = Probe()
                ampy = Ampy(p.tty)
                ampy.rm(arguments.PATH)
            except Exception as e:
                Error.traceback(e)

        elif arguments.rmdir:
            try:
                p = Probe()
                ampy = Ampy(p.tty)
                ampy.rmdir(arguments.PATH)
            except Exception as e:
                Error.traceback(e)

        elif arguments.mkdir:
            try:
                p = Probe()
                ampy = Ampy(p.tty)
                ampy.mkdir(arguments.PATH)
            except Exception as e:
                Error.traceback(e)

        elif arguments.dance:

            pprint(arguments)

            from cloudmesh.robot.turtles import Car, Cars
            import turtle

            iplist = Parameter.expand(arguments.IPS)

            print(iplist)

            ips = []
            i = 1
            for ip in iplist:
                spec = [i, ip]
                ips.append(spec)
                i = i + 1
            print("IPS", ips)

            try:

                colors = [
                    'blue', 'red', 'green', 'oragne', 'gray', 'brown', 'cyan',
                    'pink', 'purple', 'tomato'
                ]

                cars = Cars(ips)

                print(cars)
                cars.read_dance(arguments.FILE)

                wn = turtle.Screen()  # creates a graphics window

                # def a():
                for i in range(0, len(ips)):
                    car = Car(i + 1, "robi" + str(i + 1), ips[i], colors[i])
                    cars.add(car)

                cars.run()

                wn.exitonclick()

            except Exception as e:
                Error.traceback(e)

        elif arguments.inventory and arguments.export:

            filename = arguments.FILENAME
            inventory = NetworkInventory(
                path_expand('~/.cloudmesh/robot/inventory.txt'))
            inventory.export(filename)

        elif arguments.inventory:

            def load_inventory(path):
                with open(path) as stream:
                    try:
                        d = yaml.safe_load(stream)
                    except Exception as e:
                        print("problem loading file", e)

                for id in d:
                    d[id]['id'] = str(id)
                return d

            path = path_expand(arguments["--path"]
                               or "~/.cloudmesh/robot/inventory.txt")

            print(path)

            if not os.path.isfile(path):
                print("ERROR: file does not exist")
                sys.exit(1)

            if arguments.ID:
                d = load_inventory(path)
                if arguments["--cat"]:
                    result = d[int(arguments.ID)]

                else:
                    result = Printer.attribute(d[int(arguments.ID)])
                print(result)

            elif arguments["--cat"]:
                with open(path) as stream:
                    try:
                        content = stream.read()
                        print(content)
                    except Exception as e:
                        print("problem loading file", e)

            else:

                d = load_inventory(path)
                table = Printer.dict(
                    d, order=['id', 'name', 'ip', 'mac', 'chipid'])

                print(table)
        '''
# fa19-516-153 E.Cloudmesh.Common.5

from cloudmesh.common.StopWatch import StopWatch
import time

watch = StopWatch()
watch.start("test")
time.sleep(1.0238427348)

watch.stop("test")

print(watch.get("test"))
    def do_swarm(self, args, arguments):
        """
        ::

          Usage:
            swarm host list
            swarm host delete ADDR
            swarm host install HFILE
            swarm host NAME ADDR
            swarm benchmark N
            swarm create [ARG...]
            swarm join ADDR TYPE [ARG...]
            swarm leave [ARG...]
            swarm network create NAME [ARG...]
            swarm network list [ARG...]
            swarm network refresh
            swarm network delete NAME
            swarm service create NAME IMAGE  [ARG...]
            swarm service list [ARG...]
            swarm service delete NAME
            swarm service refresh
            swarm node list
            swarm node refresh
            swarm image refresh
            swarm image list [ARG...]
            swarm container refresh
            swarm container list [ARG...]


          Arguments:
            NAME     The name of the docker swarm
            IMAGE    Docker server images
            HFILE    Ansible Inventory.txt to be used
            N        Number of Benchmark iterations
            ADDR     Address of host ip:port(if port no given default port is assumed)
            TYPE     Whether the node is Manager or Worker
            URL      URL of docker API
            [ARG..]  Denotes a extensible arguments that can be passed as a name value pair.Swarm Services
                     and networks have a lot of customization options.These options are documented here
                     http://docker-py.readthedocs.io/en/stable/index.html
                     All the options are available by simply passing the values as a name value pair
                     eg
                     swarm service create NAME IMAGE hostname=?? networks=??
          Options:
             -v       verbose mode
   
          Description:
             Manages a virtual docker swarm on a cloud

        """

        kwargs = {}
        if arguments.ARG:
            for j in arguments.ARG:
                kwargs[j.split('=', 1)[0].strip()] = j.split('=', 1)[1].strip()
                val = j.split('=', 1)[1].strip()
                print(val)
                if '[' in j.split('=', 1)[1].strip():
                    val = val.replace('[', '').replace(']', '').split(',')
                    kwargs[j.split('=', 1)[0].strip()] = val

        stopwatch = StopWatch()
        stopwatch.start('E2E')
        Base = ConfigDict('cloudmesh_cmd5.yaml', verbose=False)
        if arguments.benchmark:
            path = Base['cloudmesh']['config']['base']
            os.chdir(path + 'benchmark')
            command = 'python run_benchmark.py swarm_all.csv ' + arguments.N
            print(command)
            os.system(command)
            stopwatch.stop('E2E')
            print('Time Taken:' + str(stopwatch.get('E2E')))
            return

        if arguments.host and arguments.install:
            if arguments.HFILE:
                hosts = arguments.HFILE
            else:
                hosts = 'hosts'
            path = Base['cloudmesh']['config']['base']
            os.chdir(path + 'scripts')
            command = 'python run_script.py docker-server-setup.cms ' + hosts
            print(command)
            os.system(command)
            stopwatch.stop('E2E')
            print('Time Taken:' + str(stopwatch.get('E2E')))
            return
        os.environ["DOCKER_HOST"] = Base['cloudmesh']['container']['docker'][
            'work']['host']
        if arguments.host and arguments.list:
            swarm = Swarm(os.environ["DOCKER_HOST"])
            swarm.host_list()
            stopwatch.stop('E2E')
            print('Time Taken:' + str(stopwatch.get('E2E')))
            return

        if arguments.host and arguments.delete:
            swarm = Swarm(os.environ["DOCKER_HOST"])
            swarm.host_delete("{ADDR}".format(**arguments))
            stopwatch.stop('E2E')
            print('Time Taken:' + str(stopwatch.get('E2E')))
            return

        if arguments.host:
            swarm = Swarm("{ADDR}".format(**arguments))
            swarm.host_create("{ADDR}".format(**arguments),
                              "{NAME}".format(**arguments))
            stopwatch.stop('E2E')
            Base['cloudmesh']['container']['docker']['work'][
                'host'] = "{ADDR}".format(**arguments)
            Base.save()
            print('Time Taken:' + str(stopwatch.get('E2E')))
            return

        swarm = Swarm(os.environ["DOCKER_HOST"])

        if arguments.network and arguments.create and arguments.NAME:
            swarm.network_create("{NAME}".format(**arguments), kwargs)
            stopwatch.stop('E2E')
            print('Time Taken:' + str(stopwatch.get('E2E')))
            return

        if arguments.create and not (arguments.service):
            swarm.create(kwargs)
            stopwatch.stop('E2E')
            print('Time Taken:' + str(stopwatch.get('E2E')))
            return

        if arguments.leave:
            swarm.leave(kwargs)
            stopwatch.stop('E2E')
            print('Time Taken:' + str(stopwatch.get('E2E')))
            return

        if arguments.join and arguments.ADDR and arguments.TYPE:
            swarm.join("{ADDR}".format(**arguments),
                       "{TYPE}".format(**arguments), kwargs)
            stopwatch.stop('E2E')
            print('Time Taken:' + str(stopwatch.get('E2E')))
            return

        if arguments.service and arguments.create:
            swarm.service_create("{NAME}".format(**arguments),
                                 "{IMAGE}".format(**arguments), kwargs)
            stopwatch.stop('E2E')
            print('Time Taken:' + str(stopwatch.get('E2E')))
            return

        if arguments.service and arguments.list:
            swarm.service_list(kwargs)
            stopwatch.stop('E2E')
            print('Time Taken:' + str(stopwatch.get('E2E')))
            return

        if arguments.service and arguments.refresh:
            swarm.service_refresh(kwargs)
            stopwatch.stop('E2E')
            print('Time Taken:' + str(stopwatch.get('E2E')))
            return

        if arguments.service and arguments.delete:
            swarm.service_delete("{NAME}".format(**arguments))
            stopwatch.stop('E2E')
            print('Time Taken:' + str(stopwatch.get('E2E')))
            return

        if arguments.node and arguments.list:
            swarm.node_list(kwargs)
            stopwatch.stop('E2E')
            print('Time Taken:' + str(stopwatch.get('E2E')))
            return

        if arguments.node and arguments.refresh:
            swarm.node_refresh()
            stopwatch.stop('E2E')
            print('Time Taken:' + str(stopwatch.get('E2E')))
            return

        if arguments.network and arguments.list:
            swarm.network_list(kwargs)
            stopwatch.stop('E2E')
            print('Time Taken:' + str(stopwatch.get('E2E')))
            return

        if arguments.network and arguments.refresh:
            swarm.network_refresh(kwargs)
            stopwatch.stop('E2E')
            print('Time Taken:' + str(stopwatch.get('E2E')))
            return

        if arguments.image and arguments.list:
            swarm.images_list(kwargs)
            stopwatch.stop('E2E')
            print('Time Taken:' + str(stopwatch.get('E2E')))
            return

        if arguments.image and arguments.refresh:
            swarm.images_refresh(kwargs)
            stopwatch.stop('E2E')
            print('Time Taken:' + str(stopwatch.get('E2E')))
            return

        if arguments.container and arguments.list:
            swarm.container_list(kwargs)
            stopwatch.stop('E2E')
            print('Time Taken:' + str(stopwatch.get('E2E')))
            return

        if arguments.container and arguments.refresh:
            swarm.container_refresh(kwargs)
            stopwatch.stop('E2E')
            print('Time Taken:' + str(stopwatch.get('E2E')))
            return

        if arguments.network and arguments.delete:
            swarm.network_delete("{NAME}".format(**arguments))
            stopwatch.stop('E2E')
            print('Time Taken:' + str(stopwatch.get('E2E')))
            return