Ejemplo n.º 1
0
    def construct_ip_dict(cls, ip_addr, name="kilo"):
        try:
            d = ConfigDict("cloudmesh.yaml")
            cloud_details = d["cloudmesh"]["clouds"][name]

            # Handle Openstack Specific Output
            if cloud_details["cm_type"] == "openstack":
                ipaddr = {}
                for network in ip_addr:
                    index = 0
                    for ip in ip_addr[network]:
                        ipaddr[index] = {}
                        ipaddr[index]["network"] = network
                        ipaddr[index]["version"] = ip["version"]
                        ipaddr[index]["addr"] = ip["addr"]
                        index += 1
                return ipaddr

            # Handle EC2 Specific Output
            if cloud_details["cm_type"] == "ec2":
                print("ec2 ip dict yet to be implemented")
                TODO.implement()

            # Handle Azure Specific Output
            if cloud_details["cm_type"] == "azure":
                print("azure ip dict yet to be implemented")
                TODO.implement()

        except Exception as e:
            Error.error("error in vm construct dict", traceback=True)
Ejemplo n.º 2
0
    def __init__(self, cloudname, user=None, flat=True):
        super(CloudProvider, self).__init__(cloudname, user=user)

        try:
            d = ConfigDict("cloudmesh.yaml")
            if not cloudname in d["cloudmesh"]["clouds"]:
                raise ValueError("the cloud {} is not defined in the yaml file. failed."
                                 .format(cloudname))

            cloud_details = d["cloudmesh"]["clouds"][cloudname]

            if cloud_details["cm_type"] == "openstack":
                provider = CloudProviderOpenstackAPI(
                    cloudname,
                    cloud_details,
                    flat=flat)
                self.provider = provider
                self.provider_class = CloudProviderOpenstackAPI

            if cloud_details["cm_type"] == "ec2":
                provider = CloudProviderLibcloudEC2(
                    cloudname,
                    cloud_details,
                    flat=flat)
                self.provider = provider
                self.provider_class = CloudProviderLibcloudEC2

            if cloud_details["cm_type"] == "azure":
                raise ValueError("azure cloud provider yet implemented. failed.")
                TODO.implement()

        except Exception as e:
            Error.traceback(e)
Ejemplo n.º 3
0
    def add_from_file(cls, filename):
        """

        :param filename:
        :return:
        """
        TODO.implement()
Ejemplo n.º 4
0
 def get_table(self, kind):
     if type(kind) == str:
         if kind.lower() in ["flavor"]:
             return FLAVOR
         elif kind.lower() in ["default"]:
             return DEFAULT
         elif kind.lower() in ["var"]:
             return VAR
         elif kind.lower() in ["image"]:
             return IMAGE
         elif kind.lower() in ["vm"]:
             return VM
         elif kind.lower() in ["key"]:
             return KEY
         elif kind.lower() in ["group"]:
             return GROUP
         elif kind.lower() in ["reservation"]:
             return RESERVATION
         elif kind.lower() in ["counter"]:
             return COUNTER
         elif kind.lower() in ["vmusermap"]:
             return VMUSERMAP
         elif kind.lower() in ["batchjob"]:
             return BATCHJOB
         elif kind.lower() in ["secgroup"]:
             return SECGROUP
         elif kind.lower() in ["secgrouprule"]:
             return SECGROUPRULE
         else:
             TODO.implement("wrong table type: `{}`".format(kind))
     else:
         return kind
Ejemplo n.º 5
0
    def __init__(self, cloudname, user=None, flat=True):
        super(CloudProvider, self).__init__(cloudname, user=user)

        try:
            d = ConfigDict("cloudmesh.yaml")
            cloud_details = d["cloudmesh"]["clouds"][cloudname]

            if cloud_details["cm_type"] == "openstack":
                provider = CloudProviderOpenstackAPI(
                    cloudname,
                    cloud_details,
                    flat=flat)
                self.provider = provider
                self.provider_class = CloudProviderOpenstackAPI

            if cloud_details["cm_type"] == "ec2":
                print("ec2 cloud provider yet to be implemented")
                TODO.implement()

            if cloud_details["cm_type"] == "azure":
                print("azure cloud provider yet to be implemented")
                TODO.implement()

        except Exception, e:
            import traceback
            print(traceback.format_exc())
            print(e)
Ejemplo n.º 6
0
    def __init__(self, cloudname, user=None, flat=True):
        super(CloudProvider, self).__init__(cloudname, user=user)


        try:
            d = ConfigDict("cloudmesh.yaml")
            if not cloudname in d["cloudmesh"]["clouds"]:
                raise ValueError("the cloud {} is not defined in the yaml file"
                                 .format(cloudname))

            cloud_details = d["cloudmesh"]["clouds"][cloudname]

            if cloud_details["cm_type"] == "openstack":
                provider = CloudProviderOpenstackAPI(
                    cloudname,
                    cloud_details,
                    flat=flat)
                self.provider = provider
                self.provider_class = CloudProviderOpenstackAPI

            if cloud_details["cm_type"] == "ec2":
                print("ec2 cloud provider yet to be implemented")
                TODO.implement()

            if cloud_details["cm_type"] == "azure":
                print("azure cloud provider yet to be implemented")
                TODO.implement()

        except Exception, e:
            Error.traceback(e)
Ejemplo n.º 7
0
 def mode(self, source):
     """
     Sets the source for the information to be returned. "db" and "cloud"
     :param source: the database can be queried in mode "db",
     the database can be bypassed in mode "cloud"
     """
     TODO.implement()
Ejemplo n.º 8
0
    def delete_from_file(self, filename):
        """

        :param filename:
        :return:
        """
        TODO.implement()
Ejemplo n.º 9
0
    def add_from_file(self, filename):
        """

        :param filename:
        :return:
        """
        TODO.implement()
Ejemplo n.º 10
0
 def get_table(self, kind):
     if type(kind) == str:
         if kind.lower() in ["flavor"]:
             return FLAVOR
         elif kind.lower() in ["default"]:
             return DEFAULT
         elif kind.lower() in ["var"]:
             return VAR
         elif kind.lower() in ["image"]:
             return IMAGE
         elif kind.lower() in ["vm"]:
             return VM
         elif kind.lower() in ["key"]:
             return KEY
         elif kind.lower() in ["group"]:
             return GROUP
         elif kind.lower() in ["reservation"]:
             return RESERVATION
         elif kind.lower() in ["counter"]:
             return COUNTER
         elif kind.lower() in ["vmusermap"]:
             return VMUSERMAP
         elif kind.lower() in ["batchjob"]:
             return BATCHJOB
         elif kind.lower() in ["secgroup"]:
             return SECGROUP
         elif kind.lower() in ["secgrouprule"]:
             return SECGROUPRULE
         else:
             TODO.implement("wrong table type: `{}`".format(kind))
     else:
         return kind
Ejemplo n.º 11
0
    def construct_ip_dict(cls, ip_addr, name="kilo"):
        try:
            d = ConfigDict("cloudmesh.yaml")
            cloud_details = d["cloudmesh"]["clouds"][name]

            # Handle Openstack Specific Output
            if cloud_details["cm_type"] == "openstack":
                ipaddr = {}
                for network in ip_addr:
                    index = 0
                    for ip in ip_addr[network]:
                        ipaddr[index] = {}
                        ipaddr[index]["network"] = network
                        ipaddr[index]["version"] = ip["version"]
                        ipaddr[index]["addr"] = ip["addr"]
                        index += 1
                return ipaddr

            # Handle EC2 Specific Output
            if cloud_details["cm_type"] == "ec2":
                print("ec2 ip dict yet to be implemented")
                TODO.implement()

            # Handle Azure Specific Output
            if cloud_details["cm_type"] == "azure":
                print("azure ip dict yet to be implemented")
                TODO.implement()

        except Exception, e:
            Error.traceback(e)
 def mode(self, source):
     """
     Sets the source for the information to be returned. "db" and "cloud"
     :param source: the database can be queried in mode "db",
     the database can be bypassed in mode "cloud"
     """
     TODO.implement()
Ejemplo n.º 13
0
    def delete_from_file(cls, filename):
        """

        :param filename:
        :return:
        """
        TODO.implement()
Ejemplo n.º 14
0
 def check(cls, filename):
     """
     checks the filename if it is syntactically correct and does not include tabs
     :param filename:
     :type filename: string
     :return:
     """
     TODO.implement()
Ejemplo n.º 15
0
 def check(cls, filename):
     """
     checks the filename if it is syntactically correct and does not include tabs
     :param filename:
     :type filename: string
     :return:
     """
     TODO.implement()
Ejemplo n.º 16
0
    def info(cls, user=None, project=None):
        """
        prints if the user has access to the reservation an on which host.

        :param user:
        :param project:
        :return:
        """
        TODO.implement()
Ejemplo n.º 17
0
    def info(self, user=None, project=None):
        """
        prints if the user has access to the reservation an on which host.

        :param user:
        :param project:
        :return:
        """
        TODO.implement()
Ejemplo n.º 18
0
 def _print_dict(d, header=None, format='table'):
     if format == "json":
         return json.dumps(d, indent=4)
     elif format == "yaml":
         return pyaml.dump(d)
     elif format == "table":
         return Printer.write(d,
                              order=[
                                  "id", "name", "start_time",
                                  "end_time", "user", "project",
                                  "hosts", "description", "cloud"
                              ],
                              output="table",
                              sort_keys=True)
     elif format == "csv":
         TODO.implement()
     else:
         return d
Ejemplo n.º 19
0
    def construct_ip_dict(cls, ip_addr, name=None):
        # TODO kilo cloud as defualt should be avoided
        if name is None:
            Console.error("cloud name not set")
            return None
        try:
            d = ConfigDict("cloudmesh.yaml")
            cloud_details = d["cloudmesh"]["clouds"][name]

            # Handle Openstack Specific Output
            if cloud_details["cm_type"] == "openstack":
                ipaddr = {}
                for network in ip_addr:
                    index = 0
                    for ip in ip_addr[network]:
                        ipaddr[index] = {}
                        ipaddr[index]["network"] = network
                        ipaddr[index]["version"] = ip["version"]
                        ipaddr[index]["addr"] = ip["addr"]
                        index += 1
                return ipaddr

            # Handle EC2 Specific Output
            if cloud_details["cm_type"] == "ec2":
                Console.TODO("ec2 ip dict yet to be implemented")
                TODO.implement()

            # Handle Azure Specific Output
            if cloud_details["cm_type"] == "azure":
                index = 0
                ipaddr = {}
                for ip in ip_addr:
                    ipaddr[index] = {}
                    ipaddr[index]["network"] = ip
                    ipaddr[index]["version"] = 'ipv4'
                    ipaddr[index]["addr"] = ip
                    index += 1
                return ipaddr

        except Exception as e:
            Error.error("error in vm construct dict", traceback=True)
Ejemplo n.º 20
0
    def construct_ip_dict(cls, ip_addr, name=None):
        # TODO kilo cloud as defualt should be avoided
        if name is None:
            Console.error("cloud name not set")
            return None
        try:
            d = ConfigDict("cloudmesh.yaml")
            cloud_details = d["cloudmesh"]["clouds"][name]

            # Handle Openstack Specific Output
            if cloud_details["cm_type"] == "openstack":
                ipaddr = {}
                for network in ip_addr:
                    index = 0
                    for ip in ip_addr[network]:
                        ipaddr[index] = {}
                        ipaddr[index]["network"] = network
                        ipaddr[index]["version"] = ip["version"]
                        ipaddr[index]["addr"] = ip["addr"]
                        index += 1
                return ipaddr

            # Handle EC2 Specific Output
            if cloud_details["cm_type"] == "ec2":
                Console.TODO("ec2 ip dict yet to be implemented")
                TODO.implement()

            # Handle Azure Specific Output
            if cloud_details["cm_type"] == "azure":
                index = 0
                ipaddr = {}
                for ip in ip_addr:
                    ipaddr[index] = {}
                    ipaddr[index]["network"] = ip
                    ipaddr[index]["version"] = 'ipv4'
                    ipaddr[index]["addr"] = ip
                    index += 1
                return ipaddr

        except Exception as e:
            Error.error("error in vm construct dict", traceback=True)
Ejemplo n.º 21
0
 def _print_dict(d, header=None, format='table'):
     if format == "json":
         return json.dumps(d, indent=4)
     elif format == "yaml":
         return pyaml.dump(d)
     elif format == "table":
         return dict_printer(d,
                             order=["id",
                                    "name",
                                    "start_time",
                                    "end_time",
                                    "user",
                                    "project",
                                    "hosts",
                                    "description",
                                    "cloud"],
                             output="table",
                             sort_keys=True)
     elif format == "csv":
         TODO.implement()
     else:
         return d
Ejemplo n.º 22
0
 def refresh(cls, names=None):
     TODO.implement()
Ejemplo n.º 23
0
    def do_reservation(self, args, arguments):
        """
        ::

            Usage:
                reservation info --user=USER --project=PROJECT
                reservation list [--name=NAME]
                                 [--user=USER]
                                 [--project=PROJECT]
                                 [--hosts=HOSTS]
                                 [--start=TIME_START]
                                 [--end=TIME_END]
                                 [--format=FORMAT]
                reservation delete [all]
                                   [--user=USER]
                                   [--project=PROJECT]
                                   [--name=NAME]
                                   [--start=TIME_START]
                                   [--end=TIME_END]
                                   [--hosts=HOSTS]
                reservation delete --file=FILE
                reservation update --name=NAME
                                  [--start=TIME_START]
                                  [--end=TIME_END]
                                  [--user=USER]
                                  [--project=PROJECT]
                                  [--hosts=HOSTS]
                                  [--description=DESCRIPTION]
                reservation add --name=NAME
                                [--start=TIME_START]
                                [--end=TIME_END]
                                [--user=USER]
                                [--project=PROJECT]
                                [--hosts=HOSTS]
                                [--description=DESCRIPTION]
                reservation add --file=FILE

            Arguments:

                NAME            Name of the reservation
                USER            Registration will be done for this user
                PROJECT         Project to be used
                HOSTS           Hosts to reserve
                TIME_START      Start time of reservation
                TIME_END        End time of reservation
                FORMAT          Format of output
                DESCRIPTION     Description for reservation
                FILE            File that contains reservation data to be added/ deleted

            Options:

                --name=NAME           Names of the reservation
                --user=USER           user name
                --project=PROJECT     project id
                --start=TIME_START    Start time of the reservation, in
                                      MM/DD/YYYY at hh:mm aa format. (default value: 01/01/1901 at 12:00 am])
                --end=TIME_END        End time of the reservation, in
                                      MM/DD/YYYY at hh:mm aa format. (default value: 12/31/2100 at 11:59 pm])
                --host=HOSTS          host name
                --description=DESCRIPTION  description summary of the reservation
                --file=FILE           Adding multiple reservations from one file
                --format=FORMAT       Format is either table, json, yaml or csv
                                      [default: table]

            Description:

                reservation info
                    lists the resources that support reservation for
                    a given user or project.
        """

        # print (arguments)
        def _print_dict(d, header=None, format='table'):
            if format == "json":
                return json.dumps(d, indent=4)
            elif format == "yaml":
                return pyaml.dump(d)
            elif format == "table":
                return dict_printer(d,
                                    order=["id",
                                           "name",
                                           "start_time",
                                           "end_time",
                                           "user",
                                           "project",
                                           "hosts",
                                           "description",
                                           "cloud"],
                                    output="table",
                                    sort_keys=True)
            elif format == "csv":
                TODO.implement()
            else:
                return d
                # return dict_printer(d,order=['cm_id, name, fingerprint'])

        def _get_db_date_format(date):
            """
            Utility Function that accepts instance of Date object and returns a string with Datetime for DB.
            :param date: Date object
            :return: Date as string with format expected in DB.
            """
            db_date = "{:}-{:}-{:} {:}:{:}".format(str(date.month).zfill(2),
                                                   str(date.day).zfill(2),
                                                   str(date.year).zfill(4),
                                                   str(date.hour).zfill(2),
                                                   str(date.minute).zfill(2))
            return db_date

        if arguments["info"]:

            TODO.implement()

        elif arguments["list"]:

            try:
                _name = arguments['--name']
                _user = arguments['--user']
                _project = arguments['--project']
                _format = arguments['--format']
                _hosts = arguments['--hosts']
                _start = arguments['--start']
                _end = arguments['--end']
                _format = arguments['--format']

                reserve = Reservation()
                dict = reserve.list(_name, _start, _end, _user, _project,
                                    _hosts)
                print(_print_dict(dict, format=_format))
                msg = "info. OK."
                Console.ok(msg)

            except Exception, e:
                import traceback
                print(traceback.format_exc())
                print(e)
                Console.error("Problem listing reservations")
Ejemplo n.º 24
0
 def suspend(self, names=None):
     TODO.implement()
Ejemplo n.º 25
0
 def resume(cls, names=None):
     TODO.implement()
Ejemplo n.º 26
0
 def resume(self, names=None):
     TODO.implement()
Ejemplo n.º 27
0
 def suspend(cls, names=None):
     TODO.implement()
Ejemplo n.º 28
0
 def clear(cls, names=None):
     TODO.implement()
Ejemplo n.º 29
0
 def suspend(self, names=None):
     TODO.implement()
Ejemplo n.º 30
0
    def do_reservation(self, args, arguments):
        """
        ::

            Usage:
                reservation info --user=USER --project=PROJECT
                reservation list [--name=NAME]
                                 [--user=USER]
                                 [--project=PROJECT]
                                 [--hosts=HOSTS]
                                 [--start=TIME_START]
                                 [--end=TIME_END]
                                 [--format=FORMAT]
                reservation delete [all]
                                   [--user=USER]
                                   [--project=PROJECT]
                                   [--name=NAME]
                                   [--start=TIME_START]
                                   [--end=TIME_END]
                                   [--hosts=HOSTS]
                reservation delete --file=FILE
                reservation update --name=NAME
                                  [--start=TIME_START]
                                  [--end=TIME_END]
                                  [--user=USER]
                                  [--project=PROJECT]
                                  [--hosts=HOSTS]
                                  [--description=DESCRIPTION]
                reservation add --name=NAME
                                [--start=TIME_START]
                                [--end=TIME_END]
                                [--user=USER]
                                [--project=PROJECT]
                                [--hosts=HOSTS]
                                [--description=DESCRIPTION]
                reservation add --file=FILE

            Arguments:

                NAME            Name of the reservation
                USER            Registration will be done for this user
                PROJECT         Project to be used
                HOSTS           Hosts to reserve
                TIME_START      Start time of reservation
                TIME_END        End time of reservation
                FORMAT          Format of output
                DESCRIPTION     Description for reservation
                FILE            File that contains reservation data to be added/ deleted

            Options:

                --name=NAME           Names of the reservation
                --user=USER           user name
                --project=PROJECT     project id
                --start=TIME_START    Start time of the reservation, in
                                      MM/DD/YYYY at hh:mm aa format. (default value: 01/01/1901 at 12:00 am])
                --end=TIME_END        End time of the reservation, in
                                      MM/DD/YYYY at hh:mm aa format. (default value: 12/31/2100 at 11:59 pm])
                --host=HOSTS          host name
                --description=DESCRIPTION  description summary of the reservation
                --file=FILE           Adding multiple reservations from one file
                --format=FORMAT       Format is either table, json, yaml or csv
                                      [default: table]

            Description:

                reservation info
                    lists the resources that support reservation for
                    a given user or project.
        """

        # print (arguments)
        def _print_dict(d, header=None, format='table'):
            if format == "json":
                return json.dumps(d, indent=4)
            elif format == "yaml":
                return pyaml.dump(d)
            elif format == "table":
                return dict_printer(d,
                                    order=["id",
                                           "name",
                                           "start_time",
                                           "end_time",
                                           "user",
                                           "project",
                                           "hosts",
                                           "description",
                                           "cloud"],
                                    output="table",
                                    sort_keys=True)
            elif format == "csv":
                TODO.implement()
            else:
                return d
                # return dict_printer(d,order=['cm_id, name, fingerprint'])

        def _get_db_date_format(date):
            """
            Utility Function that accepts instance of Date object and returns a string with Datetime for DB.
            :param date: Date object
            :return: Date as string with format expected in DB.
            """
            db_date = "{:}-{:}-{:} {:}:{:}".format(str(date.month).zfill(2),
                                                   str(date.day).zfill(2),
                                                   str(date.year).zfill(4),
                                                   str(date.hour).zfill(2),
                                                   str(date.minute).zfill(2))
            return db_date

        if arguments["info"]:

            TODO.implement()

        elif arguments["list"]:

            try:
                _name = arguments['--name']
                _user = arguments['--user']
                _project = arguments['--project']
                _format = arguments['--format']
                _hosts = arguments['--hosts']
                _start = arguments['--start']
                _end = arguments['--end']
                _format = arguments['--format']

                reserve = Reservation()
                dictionary = reserve.list(_name, _start, _end, _user, _project,
                                          _hosts)
                print(_print_dict(dictionary, format=_format))
                msg = "info. OK."
                Console.ok(msg)

            except Exception as e:
                import traceback
                print(traceback.format_exc())
                print(e)
                Console.error("Problem listing reservations")

        elif arguments["delete"]:
            if arguments["all"]:

                try:
                    reserve = Reservation()
                    reserve.delete()
                    msg = "info. OK."
                    Console.ok(msg)

                except Exception as e:
                    import traceback
                    print(traceback.format_exc())
                    print(e)
                    Console.error("Problem deleting all reservations")

            else:
                try:
                    _name = arguments['--name']
                    _user = arguments['--user']
                    _project = arguments['--project']
                    _format = arguments['--format']
                    _hosts = arguments['--hosts']
                    _start = arguments['--start']
                    _end = arguments['--end']
                    _format = arguments['--format']

                    reserve = Reservation()
                    reserve.delete(_name, _start, _end, _user, _project,
                                   _hosts)
                    msg = "info. OK."
                    Console.ok(msg)

                except Exception as e:
                    import traceback
                    print(traceback.format_exc())
                    print(e)
                    Console.error("Problem deleting reservations")

        elif arguments["add"]:

            if arguments["--file"] is None:
                name = None
                try:
                    name = arguments["--name"]
                    hosts = arguments["--hosts"]
                    user = arguments["--user"]
                    project = arguments["--project"]
                    description = arguments["--description"]

                    start_time = arguments["--start"] or "01/01/1901 at 07:30 pm"
                    end_time = arguments["--end"] or "12/31/2100 at 11:59 pm"

                    stime = Date(start_time)
                    etime = Date(end_time)

                    reserve = Reservation()
                    reserve.add(name, _get_db_date_format(stime),
                                _get_db_date_format(etime), hosts=hosts,
                                user=user,
                                project=project, description=description)

                    print("Reservation {:} added successfully".format(name))
                    msg = "info. OK."
                    Console.ok(msg)

                except Exception as e:
                    import traceback
                    print(traceback.format_exc())
                    print(e)
                    Console.error(
                        "Problem adding reservation {:}".format(name))

            else:
                try:
                    TODO.implement()
                    """
                    with open(os.path.join(sys.path[0], arguments["--file"])) as file:
                        reader = csv.reader(file)
                        for row in reader:
                            reservations = Reservation(cm_id=row[0],
                                                    label=row[1],
                                                    user=row[2],
                                                    project=row[3],
                                                    start_time=row[4],
                                                    end_time=row[5],
                                                    host=row[6],
                                                    summary=row[7])
                            db.add()
                    """
                except Exception as e:
                    print("Error in adding from file. ", e)

        elif arguments["update"]:
            name = None
            try:
                name = arguments["--name"]
                hosts = arguments["--hosts"]
                user = arguments["--user"]
                project = arguments["--project"]
                description = arguments["--description"]

                start_time = arguments["--start"] or "01/01/1901 at 07:30 pm"
                end_time = arguments["--end"] or "12/31/2100 at 11:59 pm"

                stime = Date(start_time)
                etime = Date(end_time)

                reserve = Reservation()
                reserve.update(name,
                               _get_db_date_format(stime),
                               _get_db_date_format(etime),
                               hosts=hosts,
                               user=user,
                               project=project,
                               description=description)

                print("Reservation {:} updated successfully".format(name))
                msg = "info. OK."
                Console.ok(msg)

            except Exception as e:
                import traceback
                print(traceback.format_exc())
                print(e)
                Console.error("Problem updating reservation {:}".format(name))

        return ""
Ejemplo n.º 31
0
 def suspend(cls, names=None):
     TODO.implement()
Ejemplo n.º 32
0
    def do_ssh(self, args, arguments):
        """
        ::

            Usage:
                ssh table
                ssh list [--format=FORMAT]
                ssh cat
                ssh register NAME PARAMETERS
                ssh ARGUMENTS


            conducts a ssh login on a machine while using a set of
            registered machines specified in ~/.ssh/config

            Arguments:

              NAME        Name or ip of the machine to log in
              list        Lists the machines that are registered and
                          the commands to login to them
              PARAMETERS  Register te resource and add the given
                          parameters to the ssh config file.  if the
                          resoource exists, it will be overwritten. The
                          information will be written in /.ssh/config

            Options:

               -v       verbose mode
               --format=FORMAT   the format in which this list is given
                                 formats incluse table, json, yaml, dict
                                 [default: table]

               --user=USER       overwrites the username that is
                                 specified in ~/.ssh/config

               --key=KEY         The keyname as defined in the key list
                                 or a location that contains a pblic key

            Description:

                ssh list
                    lists the hostsnames  that are present in the
                    ~/.ssh/config file

                ssh cat
                    prints the ~/.ssh/config file

                ssh table
                    prints contents of the ~/.ssh/config file in table format

                ssh register NAME PARAMETERS
                    registers a host i ~/.ssh/config file
                    Parameters are attribute=value pairs
                    Note: Note yet implemented

                ssh ARGUMENTS
                    executes the ssh command with the given arguments
                    Example:
                        ssh myhost

                            conducts an ssh login to myhost if it is defined in
                            ~/.ssh/config file
        """
        # pprint(arguments)

        def read(filename=None):
            if filename is None:
                filename = "~/.ssh/config"
            with open(path_expand("~/.ssh/config"), "r") as f:
                content = f.readlines()
            return "".join(content)

        def print_ssh_table(output):
            content = read(filename="~/.ssh/config").split("\n")

            entries = [
            ]

            def empty():
                return {
                    "host": None,
                    "hostname": None,
                    "user": None,
                    "proxycommand": None,
                    "serveraliveinterval": None,
                    "localforward": None,
                    "forwardx11": None
                }

            entry = empty()
            for line in content:
                line = line.strip()
                if line.startswith("#"):
                    pass
                elif line.strip() == "":
                    pass
                elif "Host " in line:
                    hostname = line.strip().split("Host")[1]
                    entry["host"] = hostname.strip()
                    if entry is not None:
                        entries.append(entry)
                    entry = empty()
                else:
                    attribute, value = line.strip().split(" ", 1)
                    entry[attribute.lower()] = value.strip()

            # pprint(entries)
            order = ["host",
                     "hostname",
                     "user",
                     "proxycommand",
                     "serveraliveinterval",
                     "localforward",
                     "forwardx11"]

            print(Printer.list(entries, order=order))

        if arguments["list"]:

            output_format = arguments["--format"]

            if output_format is None:
                banner('List SSH config hosts')
                hosts = ssh_config()
                for host in hosts.list():
                    print(host)
            else:

                print_ssh_table(output_format)

            return ""

        elif arguments["table"]:

            print_ssh_table()
            return ""

        elif arguments["cat"]:

            print(read(filename="~/.ssh/config"))

        elif arguments["register"]:

            name = arguments["NAME"]
            parameters = arguments["PARAMETERS"]
            Console.ok('register {} {}'.format(name, parameters))
            TODO.implement("Not implemented")

        else:  # ssh ARGUMENTS...

            args = arguments["ARGUMENTS"]
            os.system("ssh {}".format(args))
            return ""

        return ""
Ejemplo n.º 33
0
    def do_ssh(self, args, arguments):
        """
        ::

            Usage:
                ssh table
                ssh list [--format=FORMAT]
                ssh cat
                ssh register NAME PARAMETERS
                ssh ARGUMENTS


            conducts a ssh login on a machine while using a set of
            registered machines specified in ~/.ssh/config

            Arguments:

              NAME        Name or ip of the machine to log in
              list        Lists the machines that are registered and
                          the commands to login to them
              PARAMETERS  Register te resource and add the given
                          parameters to the ssh config file.  if the
                          resoource exists, it will be overwritten. The
                          information will be written in /.ssh/config

            Options:

               -v       verbose mode
               --format=FORMAT   the format in which this list is given
                                 formats incluse table, json, yaml, dict
                                 [default: table]

               --user=USER       overwrites the username that is
                                 specified in ~/.ssh/config

               --key=KEY         The keyname as defined in the key list
                                 or a location that contains a pblic key

            Description:

                ssh list
                    lists the hostsnames  that are present in the
                    ~/.ssh/config file

                ssh cat
                    prints the ~/.ssh/config file

                ssh table
                    prints contents of the ~/.ssh/config file in table format

                ssh register NAME PARAMETERS
                    registers a host i ~/.ssh/config file
                    Parameters are attribute=value pairs
                    Note: Note yet implemented

                ssh ARGUMENTS
                    executes the ssh command with the given arguments
                    Example:
                        ssh myhost

                            conducts an ssh login to myhost if it is defined in
                            ~/.ssh/config file
        """

        # pprint(arguments)

        def read(filename=None):
            if filename is None:
                filename = "~/.ssh/config"
            with open(path_expand("~/.ssh/config"), "r") as f:
                content = f.readlines()
            return "".join(content)

        if arguments["list"]:

            output_format = arguments["--format"]
            banner('List SSH config hosts')
            hosts = ssh_config()
            for host in hosts.list():
                print(host)

        elif arguments["table"]:

            content = read(filename="~/.ssh/config").split("\n")

            entries = []

            def empty():
                return {
                    "host": None,
                    "hostname": None,
                    "user": None,
                    "proxycommand": None,
                    "serveraliveinterval": None,
                    "localforward": None,
                    "forwardx11": None
                }

            entry = empty()
            for line in content:
                line = line.strip()
                if line.startswith("#"):
                    pass
                elif line.strip() == "":
                    pass
                elif "Host " in line:
                    hostname = line.strip().split("Host")[1]
                    entry["host"] = hostname.strip()
                    if entry is not None:
                        entries.append(entry)
                    entry = empty()
                else:
                    attribute, value = line.strip().split(" ", 1)
                    entry[attribute.lower()] = value.strip()

            pprint(entries)
            order = [
                "host", "hostname", "user", "proxycommand",
                "serveraliveinterval", "localforward", "forwardx11"
            ]

            print(list_printer(entries, order=order))

        elif arguments["cat"]:

            print(read(filename="~/.ssh/config"))

        elif arguments["register"]:

            name = arguments["NAME"]
            parameters = arguments["PARAMETERS"]
            Console.ok('register {} {}'.format(name, parameters))
            TODO.implement("Not implemented")

        else:  # ssh ARGUMENTS...

            args = arguments["ARGUMENTS"]
            os.system("ssh {}".format(args))
            return ""

        return ""
Ejemplo n.º 34
0
                                project=project, description=description)

                    print("Reservation {:} added successfully".format(name))
                    msg = "info. OK."
                    Console.ok(msg)

                except Exception, e:
                    import traceback
                    print(traceback.format_exc())
                    print(e)
                    Console.error(
                        "Problem adding reservation {:}".format(name))

            else:
                try:
                    TODO.implement()
                    """
                    with open(os.path.join(sys.path[0], arguments["--file"])) as file:
                        reader = csv.reader(file)
                        for row in reader:
                            reservations = Reservation(cm_id=row[0],
                                                    label=row[1],
                                                    user=row[2],
                                                    project=row[3],
                                                    start_time=row[4],
                                                    end_time=row[5],
                                                    host=row[6],
                                                    summary=row[7])
                            db.add()
                    """
                except Exception as e:
Ejemplo n.º 35
0
 def resume(cls, names=None):
     TODO.implement()
Ejemplo n.º 36
0
 def refresh(cls, names=None):
     TODO.implement()
Ejemplo n.º 37
0
 def clear(cls, names=None):
     TODO.implement()
Ejemplo n.º 38
0
 def resume(self, names=None):
     TODO.implement()
Ejemplo n.º 39
0
    def do_reservation(self, args, arguments):
        """
        ::

            Usage:
                reservation info --user=USER --project=PROJECT
                reservation list [--name=NAME]
                                 [--user=USER]
                                 [--project=PROJECT]
                                 [--hosts=HOSTS]
                                 [--start=TIME_START]
                                 [--end=TIME_END]
                                 [--format=FORMAT]
                reservation delete [all]
                                   [--user=USER]
                                   [--project=PROJECT]
                                   [--name=NAME]
                                   [--start=TIME_START]
                                   [--end=TIME_END]
                                   [--hosts=HOSTS]
                reservation delete --file=FILE
                reservation update --name=NAME
                                  [--start=TIME_START]
                                  [--end=TIME_END]
                                  [--user=USER]
                                  [--project=PROJECT]
                                  [--hosts=HOSTS]
                                  [--description=DESCRIPTION]
                reservation add --name=NAME
                                [--start=TIME_START]
                                [--end=TIME_END]
                                [--user=USER]
                                [--project=PROJECT]
                                [--hosts=HOSTS]
                                [--description=DESCRIPTION]
                reservation add --file=FILE

            Arguments:

                NAME            Name of the reservation
                USER            Registration will be done for this user
                PROJECT         Project to be used
                HOSTS           Hosts to reserve
                TIME_START      Start time of reservation
                TIME_END        End time of reservation
                FORMAT          Format of output
                DESCRIPTION     Description for reservation
                FILE            File that contains reservation data to be added/ deleted

            Options:

                --name=NAME           Names of the reservation
                --user=USER           user name
                --project=PROJECT     project id
                --start=TIME_START    Start time of the reservation, in
                                      MM/DD/YYYY at hh:mm aa format. (default value: 01/01/1901 at 12:00 am])
                --end=TIME_END        End time of the reservation, in
                                      MM/DD/YYYY at hh:mm aa format. (default value: 12/31/2100 at 11:59 pm])
                --host=HOSTS          host name
                --description=DESCRIPTION  description summary of the reservation
                --file=FILE           Adding multiple reservations from one file
                --format=FORMAT       Format is either table, json, yaml or csv
                                      [default: table]

            Description:

                reservation info
                    lists the resources that support reservation for
                    a given user or project.
        """

        # print (arguments)
        def _print_dict(d, header=None, format='table'):
            if format == "json":
                return json.dumps(d, indent=4)
            elif format == "yaml":
                return pyaml.dump(d)
            elif format == "table":
                return Printer.write(d,
                                     order=[
                                         "id", "name", "start_time",
                                         "end_time", "user", "project",
                                         "hosts", "description", "cloud"
                                     ],
                                     output="table",
                                     sort_keys=True)
            elif format == "csv":
                TODO.implement()
            else:
                return d
                # return Printer.write(d,order=['cm_id, name, fingerprint'])

        def _get_db_date_format(date):
            """
            Utility Function that accepts instance of Date object and returns a string with Datetime for DB.
            :param date: Date object
            :return: Date as string with format expected in DB.
            """
            db_date = "{:}-{:}-{:} {:}:{:}".format(
                str(date.month).zfill(2),
                str(date.day).zfill(2),
                str(date.year).zfill(4),
                str(date.hour).zfill(2),
                str(date.minute).zfill(2))
            return db_date

        if arguments["info"]:

            TODO.implement()

        elif arguments["list"]:

            try:
                _name = arguments['--name']
                _user = arguments['--user']
                _project = arguments['--project']
                _format = arguments['--format']
                _hosts = arguments['--hosts']
                _start = arguments['--start']
                _end = arguments['--end']
                _format = arguments['--format']

                reserve = Reservation()
                dictionary = reserve.list(_name, _start, _end, _user, _project,
                                          _hosts)
                print(_print_dict(dictionary, format=_format))
                msg = "info. OK."
                Console.ok(msg)

            except Exception as e:
                Error.traceback(e)
                Console.error("Problem listing reservations")

        elif arguments["delete"]:
            if arguments["all"]:

                try:
                    reserve = Reservation()
                    reserve.delete()
                    msg = "info. OK."
                    Console.ok(msg)

                except Exception as e:
                    Error.traceback(e)
                    Console.error("Problem deleting all reservations")

            else:
                try:
                    _name = arguments['--name']
                    _user = arguments['--user']
                    _project = arguments['--project']
                    _format = arguments['--format']
                    _hosts = arguments['--hosts']
                    _start = arguments['--start']
                    _end = arguments['--end']
                    _format = arguments['--format']

                    reserve = Reservation()
                    reserve.delete(_name, _start, _end, _user, _project,
                                   _hosts)
                    msg = "info. OK."
                    Console.ok(msg)

                except Exception as e:
                    Error.traceback(e)
                    Console.error("Problem deleting reservations")

        elif arguments["add"]:

            if arguments["--file"] is None:
                name = None
                try:
                    name = arguments["--name"]
                    hosts = arguments["--hosts"]
                    user = arguments["--user"]
                    project = arguments["--project"]
                    description = arguments["--description"]

                    start_time = arguments[
                        "--start"] or "01/01/1901 at 07:30 pm"
                    end_time = arguments["--end"] or "12/31/2100 at 11:59 pm"

                    stime = Date(start_time)
                    etime = Date(end_time)

                    reserve = Reservation()
                    reserve.add(name,
                                _get_db_date_format(stime),
                                _get_db_date_format(etime),
                                hosts=hosts,
                                user=user,
                                project=project,
                                description=description)

                    print("Reservation {:} added successfully".format(name))
                    msg = "info. OK."
                    Console.ok(msg)

                except Exception as e:
                    Error.traceback(e)
                    Console.error(
                        "Problem adding reservation {:}".format(name))

            else:
                try:
                    TODO.implement()
                    """
                    with open(os.path.join(sys.path[0], arguments["--file"])) as file:
                        reader = csv.reader(file)
                        for row in reader:
                            reservations = Reservation(cm_id=row[0],
                                                    label=row[1],
                                                    user=row[2],
                                                    project=row[3],
                                                    start_time=row[4],
                                                    end_time=row[5],
                                                    host=row[6],
                                                    summary=row[7])
                            db.add()
                    """
                except Exception as e:
                    print("Error in adding from file. ", e)

        elif arguments["update"]:
            name = None
            try:
                name = arguments["--name"]
                hosts = arguments["--hosts"]
                user = arguments["--user"]
                project = arguments["--project"]
                description = arguments["--description"]

                start_time = arguments["--start"] or "01/01/1901 at 07:30 pm"
                end_time = arguments["--end"] or "12/31/2100 at 11:59 pm"

                stime = Date(start_time)
                etime = Date(end_time)

                reserve = Reservation()
                reserve.update(name,
                               _get_db_date_format(stime),
                               _get_db_date_format(etime),
                               hosts=hosts,
                               user=user,
                               project=project,
                               description=description)

                print("Reservation {:} updated successfully".format(name))
                msg = "info. OK."
                Console.ok(msg)

            except Exception as e:
                Error.traceback(e)
                Console.error("Problem updating reservation {:}".format(name))

        return ""
Ejemplo n.º 40
0
 def clear(self, names=None):
     TODO.implement()